Gecko DOM Reference:Examples
MDC
이 장은 DOM을 쓰는 좀 더 긴 웹 개발과 XML 개발 예제를 제공합니다. 어느 곳에서라도, 예제는 문서 개체를 다루기 위해 JavaScript 공통 API, 트릭(trick), 패턴(pattern)을 씁니다.
목차 |
[편집] 예제 1: 프로퍼티 height와 width
다음 예는 바뀌는 차원 이미지(image)와 함께 height와 width 프로퍼티(property) 사용을 보입니다.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>width/height example</title>
<script type="text/javascript">
function init()
{
var arrImages = new Array(3);
arrImages[0] = document.getElementById("image1");
arrImages[1] = document.getElementById("image2");
arrImages[2] = document.getElementById("image3");
var objOutput = document.getElementById("output");
var strHtml = "<ul>";
for (var i = 0; i < arrImages.length; i++)
strHtml += "<li>image" + (i+1) +
": height=" + arrImages[i].height +
", width=" + arrImages[i].width +
", style.height=" + arrImages[i].style.height +
", style.width=" + arrImages[i].style.width +
"<\/li>";
strHtml += "<\/ul>";
objOutput.innerHTML = strHtml;
}
</script>
</head>
<body onload="init();">
<p>Image 1: no height, width, or style
<img id="image1" src="http://www.mozilla.org/images/mozilla-banner.gif">
</p>
<p>Image 2: height="50", width="500", but no style
<img id="image2" src="http://www.mozilla.org/images/mozilla-banner.gif"
height="50" width="500">
</p>
<p>Image 3: no height, width, but style="height: 50px; width: 500px;"
<img id="image3" src="http://www.mozilla.org/images/mozilla-banner.gif"
style="height: 50px; width: 500px;">
</p>
<div id="output"> </div>
</body>
</html>
height와 width는 또한 OBJECT와 APPLET 요소(element)의 프로퍼티입니다.
[편집] 예제 2: 이미지 속성
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Modifying an image border</title>
<script type="text/javascript">
function setBorderWidth(width) {
document.getElementById("img1").style.borderWidth = width + "px";
}
</script>
</head>
<body>
<p>
<img id="img1" src="image1.gif" style="border: 5px solid green;" width="100"
height="100" alt="border test">
</p>
<form name="FormName">
<p><input type="button" value="Make border 20px-wide"
onclick="setBorderWidth(20);"> <input type="button" value="Make border 5px-wide"
onclick="setBorderWidth(5);"></p>
</form>
</body>
</html>
[편집] 예제 3: 스타일 다루기
이 간단한 예제에서는, HTML paragraph 요소의 일부 기본 스타일 프로퍼티를 요소에 스타일 개체를 써서 이용하고 그 개체의 CSS 스타일 프로퍼티는 DOM에서 검색하고 설정할 수 있습니다. 이 경우에, 여러분은 개별 스타일을 바로 조작합니다. 다음 예제(예제 4를 보세요)에서, 여러분은 전체 문서의 스타일을 바꾸기 위해 스타일시트와 그 규칙을 쓸 수 있습니다.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Changing color and font-size example</title>
<script type="text/javascript">
function changeText() {
var p = document.getElementById("pid");
p.style.color = "blue"
p.style.fontSize = "18pt"
}
</script>
</head>
<body>
<p id="pid"
onclick="window.location.href = 'http://www.cnn.com/';">linker</p>
<form>
<p><input value="rec" type="button" onclick="changeText();"></p>
</form>
</body>
</html>
[편집] 예제 4: Stylesheet 사용하기
document 개체의 styleSheets 프로퍼티는 그 문서에 로드되는 스타일시트 목록을 반환합니다. 여러분은 스타일시트, style과 CSSRule 개체를 써서 이 스타일시트와 그 규칙에 하나하나 접근할 수 있습니다, 이 예제에서 실제로 보이듯이, 개체는 모든 스타일 규칙 선택자(selector)를 콘솔에 출력합니다.
ss = document.styleSheets;
for(i=0; i<ss.length; i++)
{
for(j=0; j<ss[0].cssRules.length; j++)
{
dump( ss[i].cssRules[j].style.selectorText + "\n" );
}
}
다음 세 규칙이 정의된 스타일시트 하나가 있는 문서의 경우,
BODY { background-color: darkblue; }
P { font-face: Arial; font-size: 10pt; margin-left: .125in; }
#lumpy { display: none; }
이 스크립트는 다음을 출력합니다.
BODY P #LUMPY
[편집] 예제 5: Event 전달
이 예제는 어떻게 event가 발생하고 간단한 방식으로 DOM에서 처리되는 지를 실제로 보입니다. 이 HTML 문서의 BODY가 로드될 때, event listener는 TABLE 꼭대기 줄(top row)에 등록됩니다. event listener는 표의 밑바닥(bottom) cell값을 바꾸는 stopEvent 함수를 실행하여 이벤트를 처리합니다.
그러나, stopEvent는 또한 더 이상 DOM 속으로 일어나지 않게 event를 보호하는 event 개체 메소드(event.stopPropagation)를 호출합니다. 표 자체는 표가 클릭됐을 때 메시지를 표시해야 하는 onclick event handler가 있음을 유의하세요. 하지만 stopEvent 메소드는 표의 데이터를 갱신(update)하고, event 단계가 실제로 끝나고 나서 경보 상자(alert box)가 이를 확인하기 위해 표시된 뒤에야 전달(propagation)을 멈춥니다.
<html>
<head>
<title>Event Propagation</title>
<style type="text/css">
#t-daddy { border: 1px solid red }
#c1 { background-color: pink; }
</style>
<script type="text/javascript">
function stopEvent(ev) {
c2 = document.getElementById("c2");
c2.innerHTML = "hello";
// 이 줄이 받은 마우스 클릭으로부터 t-daddy를 보호해야 합니다.
ev.stopPropagation();
alert("event propagation halted.");
}
function load() {
elem = document.getElementById("tbl1");
elem.addEventListener("click", stopEvent, false);
}
</script>
</head>
<body onload="load();">
<table id="t-daddy" onclick="alert('hi');">
<tr id="tbl1">
<td id="c1">one</td>
</tr>
<tr>
<td id="c2">two</td>
</tr>
</table>
</body>
</html>
[편집] 예제 6: getComputedStyle
이 예제는 어떻게 window.getComputedStyle 메소드가 style 속성을 쓰거나 JavaScript로( 예컨대, elt.style.backgroundColor="rgb(173, 216, 230)") 설정하지 않은 요소의 스타일을 얻는 데 쓰일 수 있는 지를 실제로 보입니다. 이 후자 형태의 스타일은 곧바로 elt.style 프로퍼티(이 프로퍼티 소유의 프로퍼티는 DOM CSS 프로퍼티 목록에 나열되어 있음)로 검색될 수 있습니다.
getComputedStyle()는 다음 예제 문서가 보이듯이 ComputedCSSStyleDeclaration 개체를 반환하고 개체의 개별 스타일 프로퍼티는 이 개체의 getPropertyValue() 메소드로 참조할 수 있습니다.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>getComputedStyle example</title>
<script type="text/javascript">
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 type="text/css">
#d1 { margin-left: 10px; background-color: rgb(173, 216, 230);
height: 20px; max-width: 20px; }
</style>
</head>
<body>
<div id="d1"> </div>
<form action="">
<p><button type="button" onclick="cStyles();">getComputedStyle</button>
height<input id="t1" type="text" value="1">
max-width<input id="t2" type="text" value="2">
bg-color<input id="t3" type="text" value="3"></p>
</form>
</body>
</html>
[편집] 예제 7: Event 개체 상수 표시하기
이 예제는 모든 event 개체 상수(constant)와 표시되는 개체 상수값으로 된 표를 만들기 위해 DOM을 쓰는 법을 보입니다. 예제는 여러분이 특정 개체의 프로퍼티를 얻게 하는 Event.prototype 프로퍼티, 그 prototype에서 프로퍼티를 반복하기 위한 좋은 패턴(pattern), 그리고 표에 표시되는 자체 상수값을 포함하는 DOM의 여러 유용한 면을 돋보이게 합니다. 이 상수의 middle range는 event동안 눌려진 실제 키를 나타내(고 charCode 프로퍼티로 fetch할 수 있)는 문자 코드임을 유의하세요. event 개체 상수를 보기 위해 웹 페이지로 다음 코드를 로드하세요.
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<!--
* ***** LICENSE BLOCK 시작 *****
* 판: NPL 1.1/GPL 2.0/LGPL 2.1
*
* 이 파일의 contents는 Netscape Public License 1.1판(이하 "License")을
* 따릅니다; you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor(s):
* Alexander J. Vincent <jscript@pacbell.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** LICENSE BLOCK 끝 ***** * -->
<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title></title>
<script language="JavaScript" type="text/javascript">
<!--
function respond() {
// 표 만듦
var table = document.createElement("table")
table.setAttribute("border", "1")
var tbody = document.createElement("tbody")
var y = 0
var tr = document.createElement("tr")
var td = document.createElement("th")
// 루프에서 같은 변수명 다시 씀
// 표 heading 정보 시작
td.appendChild(document.createTextNode("Index"))
tr.appendChild(td)
td = document.createElement("th")
td.appendChild(document.createTextNode("Property Name"))
tr.appendChild(td)
td = document.createElement("th")
td.appendChild(document.createTextNode("Property Value"))
tr.appendChild(td)
tbody.appendChild(tr)
// 표 heading 정보 끝
for (property in Event.prototype) {
if (property == property.toUpperCase()) {
// event 개체의 각 프로퍼티에 새 줄(row) 추가
tr = document.createElement("tr")
td = document.createElement("td")
td.appendChild(document.createTextNode(y))
// which property number it happens to be
tr.appendChild(td)
y++
td = document.createElement("td")
var td_text = document.createTextNode(property)
// the property name
td.appendChild(td_text)
tr.appendChild(td)
td = document.createElement("td")
var td_text = document.createTextNode(Event.prototype[property])
// the property value
td.appendChild(td_text)
tr.appendChild(td)
tbody.appendChild(tr)
}
}
table.appendChild(tbody)
document.body.appendChild(table)
}
//-->
</script>
</head>
<body onload="respond()">
<!-- 버튼을 누른 뒤 결과:
The this object is myInput.
Index Property Name Property Value
0 type click
1 target [object HTMLInputElement]
...
-->
</body>
</html>