1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
|
---
title: Examples
slug: Web/API/Document_Object_Model/Examples
---
<p>이 장에서는 DOM을 사용한 웹, XML 개발의 긴 예제를 제공합니다. 예제는 문서의 object를 조작하기 위해 가능한 JavaScript의 일반적인 API, 트릭, 패턴을 사용합니다. </p>
<h2 id="Example_1_height_and_width" name="Example_1:_height_and_width">예제 1: 높이와 너비</h2>
<p>아래의 예제는 다양한 면적의 이미지를 통해 <code>height</code> 와 <code>width</code> 속성을 사용하는 방법을 보여줍니다:</p>
<pre class="brush:html"><!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>
</pre>
<h2 id="Example_2_Image_Attributes" name="Example_2:_Image_Attributes">예제 2: 이미지 속성</h2>
<pre class="brush:html"><!DOCTYPE html>
<html lang="en">
<head>
<title>Modifying an image border</title>
<script>
function setBorderWidth(width) {
document.getElementById("img1").style.borderWidth = width + "px";
}
</script>
</head>
<body>
<p>
<img id="img1"
src="image1.gif"
style="border: 5px solid green;"
width="100" height="100" alt="border test">
</p>
<form name="FormName">
<input type="button" value="Make border 20px-wide" onclick="setBorderWidth(20);" />
<input type="button" value="Make border 5px-wide" onclick="setBorderWidth(5);" />
</form>
</body>
</html>
</pre>
<h2 id="Example_3_Manipulating_Styles" name="Example_3:_Manipulating_Styles">예제 3: 스타일 조작</h2>
<p>아래의 간단한 예제에서 HTML 단락 element( <code><p></code>)의 일부 기본 스타일 속성들은 DOM에서 검색하고 설정할 수 있는 element의 스타일 객체와, 그 객체의 CSS 스타일 속성을 사용해 접근합니다. 이 경우 개별 스타일을 직접 조작합니다. 다음 예제(예제 4)에서는 stylesheet와 해당 규칙을 사용해 전체 문서의 스타일을 변경할 수 있습니다. </p>
<pre class="brush:html"><!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>
</pre>
<h2 id="Example_4_Using_Stylesheets" name="Example_4:_Using_Stylesheets">예제 4: Stylesheet 사용</h2>
<p>document 객체의 styleSheets 속성은 그 문서에서 로드된 stylesheet 목록을 반환합니다. 이 예제에서 설명된대로 stylesheet, 스타일, CSSRule 객체를 사용해 이러한 stylesheet와 규칙에 개별적으로 접근할 수 있습니다. 이 예제는 모든 스타일 규칙 Selector를 콘솔에 출력합니다. </p>
<pre class="brush:js">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" );
}
}</pre>
<p>아래와 같은 세가지 규칙이 정의된 하나의 stylesheet가 있는 문서의 경우: </p>
<pre class="brush:css">body { background-color: darkblue; }
p { font-face: Arial; font-size: 10pt; margin-left: .125in; }
#lumpy { display: none; }
</pre>
<p>위 스크립트의 결과물은 아래와 같습니다:</p>
<pre>BODY
P
#LUMPY
</pre>
<h2 id="Example_5_Event_Propagation" name="Example_5:_Event_Propagation">예제 5: Event 전파</h2>
<p>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.</p>
<p>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.</p>
<pre class="brush:html"><!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>
</pre>
<h2 id="Example_6_getComputedStyle" name="Example_6:_getComputedStyle">Example 6: getComputedStyle</h2>
<p>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 <code>style</code> attribute or with JavaScript (e.g., <code>elt.style.backgroundColor="rgb(173, 216, 230)"</code>). These latter types of styles can be retrieved with the more direct {{domxref("element.style", "elt.style")}} property, whose properties are listed in the <a href="/en-US/docs/Web/CSS/Reference">DOM CSS Properties List</a>.</p>
<p><code>getComputedStyle()</code> returns a <code>ComputedCSSStyleDeclaration</code> object, whose individual style properties can be referenced with this object's <code>getPropertyValue()</code> method, as the following example document shows.</p>
<pre class="brush:html"><!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>
</pre>
<h2 id="Example_7_Displaying_Event_Object_Properties" name="Example_7:_Displaying_Event_Object_Properties">Example 7: Displaying Event Object Properties</h2>
<p>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.</p>
<p>The properties of event objects differs greatly between browsers, the <a href="https://dom.spec.whatwg.org">WHATWG DOM Standard</a> lists the standard properties, however many browsers have extended these greatly.</p>
<p>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.</p>
<pre class="brush:html"><!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>
</pre>
<h2 id="Example_8_Using_the_DOM_Table_Interface" name="Example_8:_Using_the_DOM_Table_Interface">Example 8: Using the DOM Table Interface</h2>
<p>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")}}.</p>
<p>To add a row and some cells to an existing table:</p>
<pre class="brush:html"><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>
</pre>
<h3 id="Notes" name="Notes">Notes</h3>
<ul>
<li>A table's {{domxref("element.innerHTML","innerHTML")}} property should never be used to modify a table, although you can use it to write an entire table or the content of a cell.</li>
<li>If DOM Core methods {{domxref("document.createElement")}} and {{domxref("Node.appendChild")}} are used to create rows and cells, IE requires that they are appended to a tbody element, whereas other browsers will allow appending to a table element (the rows will be added to the last tbody element).</li>
<li>There are a number of other convenience methods belonging to the <a href="/en-US/docs/Web/API/HTMLTableElement#Methods">table interface</a> that can be used for creating and modifying tables.</li>
</ul>
<h2 id="Subnav">Subnav</h2>
<ul>
<li><a href="/en-US/docs/Web/API/Document_Object_Model">DOM Reference</a></li>
<li><a href="/en-US/docs/Web/API/Document_Object_Model/Introduction">Introduction to the DOM</a></li>
<li><a href="/en-US/docs/Web/API/Document_Object_Model/Events">Events and the DOM</a></li>
<li><a href="/en-US/docs/Web/API/Document_Object_Model/Examples">Examples</a></li>
</ul>
|