티스토리 뷰

728x90
SMALL

CSS 개요

HTML 문서를 시각적으로 표현하는 데에는 글꼴과 색상, 여백 등 매우 많은 요소들이 관여한다. CSS 표준에서는 이런 요소들을 style 속성으로써 나열한다. CSS 표준에서는 이런 요소들을 style 속성으로써 나열한다. CSS는 글꼴과 색상, 여백, 테두리, 배경 이미지, 문자 정렬, 요소 크기, 요소 위치 등에 대한 프로퍼티를 정의한다. HTML 요소의 시각적 모양을 정의하기 위해서는 CSS 프로퍼티의 값을 지정하면 된다. CSS 프로퍼티에 값을 지정하기 위해서는 다음과 같이 프로퍼티의 이름 뒤에 콜론을 붙인 후 값을 적는다. font-weight:bold;

1. 웹브라우저의 기본 스타일시트

2. 문서의 스타일시트

3. 개별 HTML 요소의 스타일 속성

주요 CSS 프로퍼티

ms3864.tistory.com/category/css 참조

 

'css' 카테고리의 글 목록

 

ms3864.tistory.com

인라인 스타일 스크립팅

CSS를 조작하는 가장 간단한 방법은 개별 문서 요소의 style 속성을 ㄹ변경하는 것이다. 대부분의 HTML 속성처럼 style도 Element 객체의 속성이며, 자바스크립트로 조작할 수 있다. 그러나 style 속성 값은 문자열이 아니라 CSSStyleDeclaration 객체라는 점에서 다른 일반 속성과는 다르다. (-기호 없어지는거 생각)(""생각)(단위 생각)

e.style.fontSize="24pt";
e.style.fontWeight="bold";
e.style.color="blue";

e.style.margin=topMargin+"px"+rightMargin+"px"+
               bottomMargin+"px"+leftMargin+"px";

CSS 애니메이션

// Convert element e to relative positioning and "shake" it left and right.
// The first argument can be an element object or the id of an element.
// If a function is passed as the second argument, it will be invoked 
// with e as an argument when the animation is complete.
// The 3rd argument specifies how far to shake e. The default is 5 pixels.
// The 4th argument specifies how long to shake for. The default is 500 ms.
function shake(e, oncomplete, distance, time) {
    // Handle arguments
    if (typeof e === "string") e = document.getElementById(e);
    if (!time) time = 500;
    if (!distance) distance = 5;

    var originalStyle = e.style.cssText;      // Save the original style of e
    e.style.position = "relative";            // Make e relatively positioned
    var start = (new Date()).getTime();       // Note the animation start time
    animate();                                // Start the animation

    // This function checks the elapsed time and updates the position of e.
    // If the animation is complete, it restores e to its original state.
    // Otherwise, it updates e's position and schedules itself to run again.
    function animate() {
        var now = (new Date()).getTime();     // Get current time
        var elapsed = now-start;              // How long since we started
        var fraction = elapsed/time;          // What fraction of total time?

        if (fraction < 1) {     // If the animation is not yet complete
            // Compute the x position of e as a function of animation
            // completion fraction. We use a sinusoidal function, and multiply
            // the completion fraction by 4pi, so that it shakes back and
            // forth twice.
            var x = distance * Math.sin(fraction*4*Math.PI);
            e.style.left = x + "px";

            // Try to run again in 25ms or at the end of the total time.
            // We're aiming for a smooth 40 frames/second animation.
            setTimeout(animate, Math.min(25, time-elapsed));
        }
        else {                  // Otherwise, the animation is complete
            e.style.cssText = originalStyle  // Restore the original style
            if (oncomplete) oncomplete(e);   // Invoke completion callback
        }
    }
}

// Fade e from fully opaque to fully transparent over time milliseconds.
// Assume that e is fully opaque when this function is invoked.
// oncomplete is an optional function that will be invoked with e as its
// argument when the animation is done. If time is omitted, use 500ms.
// This function does not work in IE, but could be modified to animate
// IE's nonstandard filter property in addition to opacity.
function fadeOut(e, oncomplete, time) {
    if (typeof e === "string") e = document.getElementById(e);
    if (!time) time = 500;

    // We use Math.sqrt as a simple "easing function" to make the animation
    // subtly nonlinear: it fades quickly at first and then slows down some.
    var ease = Math.sqrt;

    var start = (new Date()).getTime();    // Note the animation start time
    animate();                             // And start animating

    function animate() {
        var elapsed = (new Date()).getTime()-start; // elapsed time
        var fraction = elapsed/time;                // As a fraction of total
        if (fraction < 1) {     // If the animation is not yet complete
            var opacity = 1 - ease(fraction);  // Compute element opacity
            e.style.opacity = String(opacity); // Set it on e  
            setTimeout(animate,                // Schedule another frame
                       Math.min(25, time-elapsed));
        }
        else {                  // Otherwise, we're done
            e.style.opacity = "0";          // Make e fully transparent
            if (oncomplete) oncomplete(e);  // Invoke completion callback
        }
    }
}

계산된 스타일 가져오기

인라인 스타일은 요소에 실제로 적용된 스타일을 가져오는 데는 그다지 유용하지 않다. 이런 경우에는, 계산된 스타일을 사용하면 된다. 요소의 계산된 스타일은 문서에 연결된 모든 스타일시트로부터 적용 가능한 스타일 규칙들과, 인라인 스타일들이 평가되어 브라우저에 적용된 프로퍼티 값의 집합이다. 즉, 요소를 보여주기 위해 실제로 사용된 프로퍼티의 집합인 것이다. window.getcomputedstyle() 메서드 사용. 첫번째 전달인자는 계산된 스타일을 가져오려는 요소, 두번째 전달인자에는 보통 null이나 빈 문자열을 사용하지만, 필요에 다라 ":before", ":after", ":first-line" 같은 CSS 가상 요소를 문자열로 지정할 수도 있다.

var title=document.getElementById("section1title");
var titlestyles=window.getComputedstyle(title,null);

계산된 스타일을 가져온 다음 인라인 스타일로 설정하기

// Scale the text size of element e by the specified factor
function scale(e, factor) {
    // Use the computed style to query the current size of the text
    var size = parseInt(window.getComputedStyle(e,"").fontSize);
    // And use the inline style to enlarge that size
    e.style.fontSize = factor*size + "px";
}

// Alter the background color of element e by the specified amount.
// Factors > 1 lighten the color and factors < 1 darken it.  
function scaleColor(e, factor) {
    var color = window.getComputedStyle(e, "").backgroundColor;  // Query
    var components = color.match(/[\d\.]+/g);   // Parse r,g,b, and a components
    for(var i = 0; i < 3; i++) {                // Loop through r, g and b
        var x = Number(components[i]) * factor;         // Scale each one
        x = Math.round(Math.min(Math.max(x, 0), 255));  // Round and set bounds
        components[i] = String(x);                      
    }
    if (components.length == 3)  // A rgb() color
        e.style.backgroundColor = "rgb(" + components.join() + ")";
    else                         // A rgba() color
        e.style.backgroundColor = "rgba(" + components.join() + ")";
}

CSS 클래스 스크립팅

CSS 스타일을 개별적으로 스크립팅하는 방식의 대안으로는 HTML class 속성의 값을 조작하는 방법이 있다. 요소의 클래스를 바꾸면 요소의 스타일시트 선택자도 바뀌므로 여러 CSS 프로퍼티의 값을 한꺼번에 수정할 수 있다.

function grabAttention(e){e.className="attention";}
function releaseAttention(e){e.className="";}

class 속성의 값에는 띄어쓰기로 구분된 클래스명의 목록을 담을 수 있다.

classList.add(), classList.remove()로 클래스 추가, 제거

toggle() 메서드는 요소에 해당 클래스명이 존재하지 않는다면 추가하고, 이미 존재한다면 제거

contains() 메서드는 class 속성에 특정 클래스명이 존재하는지 여부를 평가

스타일시트 스크립팅

CSS 스타일시트 자체를 스크립팅할 수도 있다. 일반적으로 사용되는 방식은 아니지만, 유용한 경우도 있다.

스타일시트를 조작하기 위해서는 두 가지 객체를 알아두어야 한다. 첫번째는 스타일시트를 포함하거나 참조하는 <style>과 <link>를 나타내는 Element 객체다. 이 요소들은 document.getelementById()를 사용해 해당 요소를 가져올 수 있다. 두번째는 스타일시트 자체를 나타내는 CSSStyleSheet 객체다. <style>이나 <link> 요소에 title 속성을 설정하면, 해당 CSSStyleSheet 객체의 title 프로퍼티를 통해 스타일시트를 참조하거나 정의할 수 있다.

스타일시트를 활성, 비활성화하기

disabled=true로 설정

스타일시트 규칙의 조회와 추가, 삭제

스타일 시트를 직접 조작하는 것은 일반적으로 자주 사용하는 방법은 아니다. 보통은 스타일시트에 새로운 규칙을 동적으로 추가하거나 수정하는 대신, 정적인 스타일시트 파일을 따로 두고 요소의 className 프로퍼티로 조작하는 편이다. 배열 document.styleSheets[]의 원소는 CSSStylesheet 객체다. 이 객체에는 스타일시트의 규칙을 포함하는 배열인 cssRules[]가 존재한다. insertRule()과 deleteRule() 메서드가 있다.

document.styleSheets[0].insertRule("H1 {text-weight: bold; }",0);

새 스타일시트 만들기

완전히 새로운 스타일시트를 만들어서 문서에 추가할 수도 있다. 대다수 브라우저에서는 <style> 요소를 만들고, 문서의 head에 삽입한 다음, innerHTML 프로퍼티를 통해 스타일시트의 내용을 설정하면 되고 이 방식은 DOM 표준 기술이다.

728x90
LIST

' > 자바스크립트 완벽 가이드' 카테고리의 다른 글

18장 HTTP 스크립팅  (0) 2020.11.27
17장 이벤트 다루기  (0) 2020.11.23
15장 문서 스크립팅  (0) 2020.11.21
14장 window 객체  (0) 2020.11.20
13장 웹브라우저의 자바스크립트  (0) 2020.11.19
댓글
공지사항