JavaScript CSS 조작

박지명·2026년 3월 5일

클라이언트

목록 보기
23/24

CSS 조작 방법

방법코드권장
style 문자열 직접 대입div.style = 'color:blue'
style 프로퍼티 개별 지정div.style['color'] = 'gold'
classNamediv.className = 'one two three'❌ 하드코딩
classListdiv.classList.add('one')
// style 프로퍼티 — CSS 속성명 그대로 or 캐멀 표기법
div.style['color'] = 'gold';
div.style['font-size'] = '3rem';   // '-' 포함 속성명
div.style.fontSize = '3rem';       // 캐멀 표기법

// classList
div.classList.add('one');          // 클래스 추가
div.classList.remove('two');       // 클래스 제거
div.classList.toggle('three');     // 있으면 제거, 없으면 추가

CSS 값 읽기

// 인라인 CSS만 읽힘
div.style.width;   // 인라인에 없으면 빈 문자열

// 모든 CSS 읽기 (인라인 + 임베디드 + 외부)
const computed = window.getComputedStyle(div);
computed.getPropertyValue('width');   // '200px'

너비 증가 예시

div.style.width = parseInt(div.style.width) + 50 + 'px';
// parseInt → 숫자만 추출 ('200px' → 200)

글자 크기 조절

let fontSize = 16;

btn1.onclick = () => {
    fontSize += 3;
    if (fontSize > 40) fontSize = 40;   // 최대값 제한
    p1.style['font-size'] = fontSize + 'px';
};

btn2.onclick = () => {
    fontSize -= 3;
    if (fontSize < 9) fontSize = 9;     // 최소값 제한
    p1.style['font-size'] = fontSize + 'px';
};

상자 이동

// 클릭 위치로 상자 순서대로 이동 + z-index 관리
window.onmousedown = event => {
    list[index].style['left'] = event.clientX - 75 + 'px';   // 중심 정렬
    list[index].style['top'] = event.clientY - 75 + 'px';
    list[index].style['z-index'] = zindex;

    index++;
    zindex++;
    if (index >= list.length) index = 0;   // 순환
};

동적 상자 생성/삭제

window.onmousedown = event => {
    if (event.buttons == 1) {
        // 좌클릭 → 상자 생성
        const box = document.createElement('div');
        box.className = 'box';
        box.style['left'] = event.clientX - 75 + 'px';
        box.style['top'] = event.clientY - 75 + 'px';

        // 랜덤 배경색
        let r = parseInt(Math.random() * 256);
        let g = parseInt(Math.random() * 256);
        let b = parseInt(Math.random() * 256);
        box.style['background-color'] = `rgb(${r}, ${g}, ${b})`;

        document.body.appendChild(box);

    } else if (event.buttons == 2) {
        // 우클릭 → 상자 삭제
        if (event.target.classList.contains('box')) {
            event.target.remove();
        }
    }
};

window.oncontextmenu = event => event.preventDefault();   // 우클릭 메뉴 방지

Drag & Drop

absolute vs relative 차이

positionleft/top 기준originX/Y 필요
absolute뷰포트 좌측 상단
relative원래 위치 기준✅ getBoundingClientRect()
let isDown = false;
let offsetX, offsetY;

// absolute 방식
window.onmousedown = event => {
    if (event.target.id == 'box1') {
        isDown = true;
        offsetX = event.offsetX;   // 상자 내부 클릭 위치
        offsetY = event.offsetY;
    }
};

window.onmousemove = event => {
    if (isDown) {
        box1.style['left'] = event.clientX - offsetX + 'px';
        box1.style['top'] = event.clientY - offsetY + 'px';
    }
};

window.onmouseup = () => { isDown = false; };

// relative 방식 — 원래 위치 차감 필요
let originX = box1.getBoundingClientRect().x;
let originY = box1.getBoundingClientRect().y;
// left = clientX - offsetX - originX

슬라이드 메뉴

let oldItem = null;

items.forEach(item => {
    item.onclick = event => {
        // 이전 아이템 닫기
        if (oldItem != null) oldItem.style['transform'] = 'translateY(0px)';

        // 같은 아이템 재클릭 → 닫기 / 다른 아이템 → 열기
        if (event.target != oldItem) {
            event.target.style['transform'] = 'translateY(90px)';
            oldItem = event.target;
        } else {
            oldItem = null;
        }
    };
});

CSS transition: all .5s → JS로 style 변경 시 자동으로 애니메이션 적용

배경 이미지 조작 / 스프라이트

스프라이트 기법

  • 여러 이미지를 1개 파일에 모아두고 background-position으로 잘라서 사용
// 버튼 클릭 → 배경 위치 이동 (하트 이미지 전환)
x -= 300;
if (x < -600) x = 0;
heart.style['background-position'] = x + 'px 0px';

// 타이머 + 스프라이트 → 애니메이션
runid = setInterval(run, 100);

function run() {
    x2 -= 512;
    if (x2 < -(512 * 3)) {
        x2 = 0;
        y2 -= 256;
        if (y2 < -256) y2 = 0;
    }
    puma.style['background-position'] = `${x2}px ${y2}px`;
}

스프라이트 방식은 복잡한 애니메이션에 부적합 → 복잡한 경우 <canvas> 사용 권장

0개의 댓글