반응형

문서 객체의 스타일 조작

문서 객체의 style 속성을 사용하면 해당 문서 객체의 스타일을 변경할 수 있습니다.

 

body 태그 구성

<body>
    <h1 id="header">Header</h1>
</body>

 

문서 객체의 스타일 지정 예

window.onload = function() {
    var header = document.getElementById('header');

    header.style.border = '1px solid #DDD';
    header.style.color = 'orange';
    header.style.fontFamily = 'helvetica';
}

위 코드처럼 style을 지정해서 여러 스타일을 넣을 수 있습니다.

 

스타일 속성 이름

자바스크립트에서는 특수 기호 '-'를 식별자에 사용할 수 없으므로 입력하면 오류가 발생합니다.

 

스타일 식별자 변환

스타일 시트의 스타일 속성 자바스크립트의 스타일 식별자
background-image backgroundImage
background-color backgroundColor
box-sizing boxSizing
list-style listStyle

문자열로 접근하면 두가지 방법 모두 사용할 수 있습니다.

 

문자열로 문서 객체의 스타일 지정 예

document.body.style['backgroundColor'] = 'red';
document.body.style['background-color'] = 'red';

 

문서 객체 제거

문서 객체를 제거할 때는 문서 객체가 갖는 제거 메서드를 사용합니다.

 

문서 객체의 제거 메서드

메서드 설명
removeChild(child) 문서 객체의 자식 노드를 제거합니다.

 

body 태그 구성

<body>
    <h1 id="will-remove>Header</h1>
</body>

 

문서 객체의 제거

window.onload = function() {
    var willRemove = document.getElementById('will-remove');

    document.body.removeChild(willRemove);
}

위 코드는 body 문서 객체 바로 아래에 제거하고자 하는 문서 객체가 있으므로 사용 가능한 코드입니다.

일반적으로 문서 객체를 제거할 때는 아래와 같이 사용합니다.

 

window.onload = function() {
    var willRemove = document.getElementById('will-remove');

    willRemove.parentNode.removeChild(willRemove);
}

아래 그림처럼 h1 태그에서 부모 노드로 이동하고 부모 노드에서 자식 노드를 삭제한 것입니다.

 

parentNode와 childNode의 관계

parentNode와 childNode

 

 

문서 객체를 사용한 시계

 

body 태그 구성

<body>
    <h1 id="clock"></h1>
</body>

 

문서 객체 설정

window.onload = function() {
    var clock = document.getElementById('clock');
};

아래 코드처럼 setInterval() 함수로 1초마다 clock 문서 객체의 innerHTML 속성을 현재 시각으로 변경합니다.

 

현재 시각 표시

window.onload = function() {
    var clock = document.getElementById('clock');

    setInterval(() => {
        clock.innerHTML = new Date().toString();
    }, 1000);
};

setInterval() 함수를 사용했기 때문에 1초마다 시간이 바뀌게 됩니다.

 

문서 객체를 사용한 움직임 구현

 

body 태그 구성

<h1 id="sun">@</h1>
<h1 id="earth">0</h1>
<h1 id="moon">*</h1>

 

문서 객체

window.onload = function() {

    var sun = document.getElementById('sun');
    var earth = document.getElementById('earth');
    var moon = document.getElementById('moon');

    // 문서 객체의 스일 속성 변경
    sun.style.position = 'absolute';
    earth.style.position = 'absolute';
    moon.style.position = 'absolute';
    sun.style.left = 250 + 'px';
    sun.style.top = 200 + 'px';

    // 변수 선언
    var earthAngle = 0;
    var moonAngle = 0;

    // 애니메이션 시작 [ 30FPS(Frames Per Second) ]
    setInterval(function() {
        var earthLeft = 250 + 150 * Math.cos(earthAngle);
        var earthTop = 200 + 150 * Math.sin(earthAngle);
        var moonLeft = earthLeft + 50 * Math.cos(moonAngle);
        var moonTop = earthTop + 50 * Math.sin(moonAngle);

        // 위치 이동
        earth.style.left = earthLeft + 'px';
        earth.style.top = earthTop + 'px';
        moon.style.left = moonLeft + 'px';
        moon.style.top = moonTop + 'px';

        // 각도 변경
        earthAngle += 0.1;
        moonAngle += 0.3;
    }, 1000 / 30)
};

 

 

문서 객체와 객체지향을 사용한 움직임 구현

 

보조함수

// 랜덤한 정수를 생성
function nextRandomInteger(limit) {
    return Math.round(Math.random() * limit);
}

// 랜덤한 알파벳을 리턴하는 함수
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

function randomAlphabet() {
    return alphabet.charAt(nextRandomInteger(25));
}

// 양수와 음수로 랜덤한 속도를 생성하는 함수
function randomSpeed(maxSpeed) {
    return Math.random() * maxSpeed - Math.random() * maxSpeed;
}

 

생성자 함수

// MovingText의 생성자 함수
var canvasWidth = 700;
var canvasHeight = 400;

function movingText() {
    // 위치와 속도 속성
    this.x = nextRandomInteger(canvasWidth);
    this.y = nextRandomInteger(canvasHeight);
    this.vx = randomSpeed(5);
    this.vy = randomSpeed(5);

    // 문서 객체를 생성
    this.body = document.createElement('h1');
    this.body.innerHTML = randomAlphabet();
    this.body.style.position = 'absolute';

    // 문서 객체를 document.body에 추가
    document.body.appendChild(this.body);
}

movingText.prototype.move = function() {
    // 범위 검사
    if(this.x < 0 || this.x > canvasWidth) this.vx *= -1;
    if(this.y < 0 || this.y > canvasHeight) this.vy *= -1;

    // 이동
    this.x += this.vx;
    this.y += this.vy;

    // 화면에 이동 표시
    this.body.style.left = this.x + 'px';
    this.body.style.top = this.y + 'px';
};

 

window.onload 부분

// 변수 선언
var movingTexts = [];

// 배열에 movingText 객체를 100개 생성
for(var i = 0; i < 100; i++) {
    movingTexts.push(new movingText());
}

setInterval(() => {
    for(var i in movingTexts) {
        movingTexts[i].move();
    }
}, 1000 / 30);

 

클로저 활용하기

 

랜덤한 알파벳을 리턴하는 함수

// 랜덤한 알파벳을 리턴하는 함수
function randomAlphabet() {
    var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    
    return alphabet.charAt(nextRandomInteger(25));
}

여러 프로그램에 으용할 수 있는 내용이므로 복사해서 사용하기 좋지만 해당 코드에서 변수 alphabet을 재정의하면 안되기 때문에 위처럼 내부 변수로 만들어주는 것이 안전합니다.

 

하지만 이 함수를 100번 사용하면 변수 alphabet이 메모리에서 100번 생성되고 100번 제거되는 일이 발생합니다. 따라서 아래처럼 외부에는 공개되지 않는 변수를 생성하는 것이 좋습니다.

 

클로저 활용 예

var randomAlphabet = (function() {
    var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    
    return function() {
        return alphabet.charAt(nextRandomInteger(25));
    }
})();

 

반응형

+ Recent posts