Javascript로 CSS 제어하기 > 개발

본문 바로가기

사이트 내 전체검색

개발

JavaScript Javascript로 CSS 제어하기

페이지 정보

냐잉 23-08-28 16:42 조회 1,406회 댓글 0건

본문

CSSOM 이란?
CSS Object Model은 Javascript로 CSS를 제어할 수 있는 API 모음이다. DOM과 흡사하지만, HTML이 아닌 CSS를 위한 것이다.

1.element.style을 통한 인라인 스타일
Javascript를 사용해서 CSS를 조작하는 가장 기본적인 방법은 style을 이용하는 것이다.
예제
document.body.style.background = 'tomato';
document.body.style.padding = '100px'


2, 계산된(computed) 스타일 가져오기
window.getComputedStyle() 메소드를 이용해서 계산된 CSS 속성의 값을 가져올 수 있다.
.을 이용해서 가져오는 방식
window.getComputedStyle(el).backgroundColor;


[대괄호]를 이용하는 방식(lint 에서 권장하지 않음)
window.getComputedStyle(el)['background-color'];
getPropertyValue() 메소드를 이용하는 방식

window.getComputedStyle(el).getPropertyValue('background-color');


setProperty(), getPropertyValue(), item(), removeProperty()
- setProperty() : 설정, 2개의 인자 (속성,값)
- getProperty() : 가져오기, 1개의 인자
- item() : 가져오려는 속성의 인덱스를 인자로 사용
- removeProperty() : 삭제

// 설정(set)
document.body.style.setProperty('color', 'lime');
document.body.style.setProperty('font-size', '16px');

// 읽기(get)
document.body.style.getPropertyValue('color');

// item() 이용
document.body.style.item(0)
document.body.style.item(1)

// 제거(remove), 제거 후에는 빈 문자열을 반환한다.
document.body.style.removeProperty('color')
document.body.style.item(1)

제이쿼리에서의 변경
  //CSS 속성값 확인
  $("변경하려는 대상").css("속성");
  
  //CSS 속성값 변경
  $("변경하려는 대상").css("속성","속성값"); 

실제 소스 적용 예시
    var instaHtml = '';
    var ex_cnt = 5; //인스타 노출 갯수
    $.ajax({
        url: 'https://graph.instagram.com/me/media?fields=id,caption,media_type,media_url,thumbnail_url,permalink&limit='+ex_cnt+'&access_token=[토큰값]',
        method: 'GET',
        dataType: 'jsonp',
        success: function (response) {
            for (var i = 0; i < ex_cnt; i++) {
                if(response.data[i].media_type == "VIDEO"){
                    instaHtml += '<a href="'+response.data[i].permalink+'" target="_blank">';
                    instaHtml += '<img src='+response.data[i].thumbnail_url+' width="203" height="203" style="object-fit:cover;">';
                    instaHtml += '</a>';
                }else{
                    instaHtml += '<a href="'+response.data[i].permalink+'" target="_blank">';
                    instaHtml += '<img src='+response.data[i].media_url+' loading="lazy" width="203" height="203">';
                    instaHtml += '</a>';
                }
            }
            $("#instaFeed").empty();
            $("#instaFeed").append(instaHtml);
        },
        error: function (xhr, status, error) {
            console.log(xhr.responseText);
        }
    });

<div class="insta_feed">
     <span id="instaFeed"><span>
</div>


.remove() :태그를 포함한 요소 전체를 제거할 때 사용
.append() :선택한 요소의 내용의 끝에 콘텐트를 추가
Yh Corp. © Designed by yh.