IT TIP

Javascript / jQuery를 사용하여 외부 스타일 시트에서 CSS 값 가져 오기

itqueen 2020. 12. 8. 20:34
반응형

Javascript / jQuery를 사용하여 외부 스타일 시트에서 CSS 값 가져 오기


스타일이 참조하는 요소가 아직 생성되지 않은 경우 페이지의 외부 CSS에서 값을 가져올 수 있습니까? (요소는 동적으로 생성됩니다).

내가 본 jQuery 메소드는 $('element').css('property');이지만 이것은 element페이지에있는 것에 의존 합니다. 요소의 계산 된 스타일이 아닌 CSS 내에서 속성이 무엇으로 설정되어 있는지 알아내는 방법이 있습니까?

스타일 속성에 액세스 할 수 있도록 요소의 숨겨진 사본을 페이지에 추가하는 것과 같은 추악한 작업을 수행해야합니까?


jQuery 사용 :

// Scoping function just to avoid creating a global
(function() {
    var $p = $("<p></p>").hide().appendTo("body");
    console.log($p.css("color"));
    $p.remove();
})();
p {color: blue}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

DOM 직접 사용 :

// Scoping function just to avoid creating a global
(function() {
    var p = document.createElement('p');
    document.body.appendChild(p);
    console.log(getComputedStyle(p).color);
    document.body.removeChild(p);
})();
p {color: blue}

참고 : 두 경우 모두 외부 스타일 시트를로드하는 경우 요소에 미치는 영향을 확인하기 위해로드 될 때까지 기다리는 것이 좋습니다. jQuery ready와 DOM의 DOMContentLoaded이벤트 모두 그렇게하지 않습니다 . 로드 되는 것을 지켜 보면서 확인해야합니다 .


일반적으로 브라우저가 모든 규칙을 적용한 다음 브라우저에 결과를 요청해야하지만 드물게 스타일 시트에서 값을 가져와야 하는 드문 경우에는 다음을 사용할 수 있습니다. ( JSFiddle )

function getStyleSheetPropertyValue(selectorText, propertyName) {
    // search backwards because the last match is more likely the right one
    for (var s= document.styleSheets.length - 1; s >= 0; s--) {
        var cssRules = document.styleSheets[s].cssRules ||
                document.styleSheets[s].rules || []; // IE support
        for (var c=0; c < cssRules.length; c++) {
            if (cssRules[c].selectorText === selectorText) 
                return cssRules[c].style[propertyName];
        }
    }
    return null;
}

alert(getStyleSheetPropertyValue("p", "color"));

찾고있는 규칙과 일치하는 전체 선택기 텍스트를 제공해야하고 (파싱되지 않음) 중복 항목이나 모든 종류의 우선 순위 규칙을 처리하지 않기 때문에 이것은 매우 취약합니다. 이것을 사용하는 것이 좋은 생각이라고 생각하기는 어렵지만 여기에서는 단지 예일뿐입니다.


Karim79에 대한 응답으로 나는 그 대답의 함수 버전을 버릴 것이라고 생각했습니다. 나는 그것을 여러 번해야 했으므로 이것이 내가 쓴 것입니다.

function getClassStyles(parentElem, selector, style){
    elemstr = '<div '+ selector +'></div>';
    var $elem = $(elemstr).hide().appendTo(parentElem);
        val = $elem.css(style);
    $elem.remove();
    return val;
}
val = getClassStyles('.container:first', 'class="title"', 'margin-top');
console.warn(val);

이 예제에서는 class = "container"가있는 및 요소가 있고 해당 요소에서 제목 클래스의 margin-top 스타일을 찾고 있다고 가정합니다. 물론 필요에 맞게 변경하십시오.

스타일 시트에서 :

 .container .title{ margin-top:num; }

어떻게 생각하는지 알려주세요. 수정 하시겠습니까? 그렇다면 어떻게 수정 하시겠습니까? 감사!


주어진 css 클래스에서 검색 할 css 속성을 가진 객체를 받아들이고 실제 css 속성 값을 채우는 도우미 함수를 작성했습니다. 예가 포함되어 있습니다.

function getStyleSheetValues(colScheme) {
    var tags='';
    var obj= colScheme;

    // enumerate css classes from object
    for (var prop in obj) { 
        if (obj.hasOwnProperty(prop) && typeof obj[prop]=="object") { 
            tags+= '<span class="'+prop+'"></span>';
        } 
    } 

    // generate an object that uses the given classes
    tags= $('<div>'+tags+'</div>').hide().appendTo("body");

    // read the class properties from the generated object
    var idx= 0;
    for (var prop in obj) { 
        if (obj.hasOwnProperty(prop) && typeof obj[prop]=="object") { 
            var nobj= obj[prop];
            for (var nprop in nobj) { 
                if (nobj.hasOwnProperty(nprop) && typeof(nobj[nprop])=="string") { 
                    nobj[nprop]= tags.find("span:eq("+idx+")").css(nobj[nprop]);
                }
            }
            idx++;
        } 
    } 
    tags.remove();
}

// build an object with css class names where each class name contains one 
// or more properties with an arbitrary name and the css attribute name as its value.
// This value will be replaced by the actual css value for the respective class.
var colorScheme= { chart_wall: {wallColor:'background-color',wallGrid:'color'}, chart_line1: { color:'color'} };

$(document).ready(function() {
    getStyleSheetValues(colorScheme);

    // debug: write the property values to the console;     
    if (window.console) {
        var obj= colorScheme;
        for (var prop in obj) { 
            if (obj.hasOwnProperty(prop) && typeof obj[prop]=="object") { 
                var nobj= obj[prop];
                for (var nprop in nobj) { 
                    if (nobj.hasOwnProperty(nprop)) { 
                        console.log(prop+'.'+nprop +':'+ nobj[nprop]);
                    }
                }
            } 
        } 
        // example of how to read an individual css attribute value
        console.log('css value for chart_wall.wallGrid: '+colorScheme.chart_wall.wallGrid);
    }
});

이 js 함수를 작성했으며 중첩 클래스에서도 작동하는 것 같습니다.

용법:

var style = get_css_property('.container-class .sub-container-class .child-class', 'margin');
console.log('style');


function get_css_property(class_name, property_name){
    class_names = class_name.split(/\s+/);
    var container = false;
    var child_element = false;

    for (var i = class_names.length - 1; i >= 0; i--) {
        if(class_names[i].startsWith('.'))
            class_names[i] = class_names[i].substring(1);
        var new_element = $.parseHTML('<div class="' + class_names[i] + '"></div>');
        if(!child_element)
            child_element = new_element;
        if(container)
            $(new_element).append(container);
        container = new_element;
    }
    $(container).hide().appendTo('body');
    var style = $(child_element).css(property_name);
    $(container).remove();
    return style;
}

참고 URL : https://stackoverflow.com/questions/2707790/get-a-css-value-from-external-style-sheet-with-javascript-jquery

반응형