programing

jQuery는 요소와 관련된 모든 CSS 스타일을 가져올 수 있습니까?

randomtip 2022. 11. 22. 21:39
반응형

jQuery는 요소와 관련된 모든 CSS 스타일을 가져올 수 있습니까?

jQuery에서 모든 CSS를 기존 요소에서 가져와 모두 나열하지 않고 다른 요소에 적용할 수 있는 방법이 있습니까?

스타일 속성으로 하면 효과가 있을 거예요.attr()모든 스타일은 외부 스타일시트에 있습니다.

몇 년 늦었지만 인라인 스타일링과 외부 스타일링을 모두 검색하는 솔루션이 있습니다.

function css(a) {
    var sheets = document.styleSheets, o = {};
    for (var i in sheets) {
        var rules = sheets[i].rules || sheets[i].cssRules;
        for (var r in rules) {
            if (a.is(rules[r].selectorText)) {
                o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
            }
        }
    }
    return o;
}

function css2json(css) {
    var s = {};
    if (!css) return s;
    if (css instanceof CSSStyleDeclaration) {
        for (var i in css) {
            if ((css[i]).toLowerCase) {
                s[(css[i]).toLowerCase()] = (css[css[i]]);
            }
        }
    } else if (typeof css == "string") {
        css = css.split("; ");
        for (var i in css) {
            var l = css[i].split(": ");
            s[l[0].toLowerCase()] = (l[1]);
        }
    }
    return s;
}

jQuery 개체를 다음 위치에 전달합니다.css()오브젝트를 반환하여 jQuery에 다시 연결할 수 있습니다.$().css(), 예:

var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);

:)

2년 늦었지만 당신이 찾고 있는 해결책이 있어요오리지널 작성자의 신용을 취득할 생각은 없지만, 여기 플러그인이 있습니다.이 플러그인은 당신이 필요로 하는 것에 매우 적합하지만, 모든 브라우저, 심지어 IE에서도 가능한 모든 스타일을 갖추고 있습니다.

경고:이 코드는 많은 출력을 생성하므로 신중하게 사용해야 합니다.모든 표준 CSS 속성뿐만 아니라 해당 브라우저의 모든 벤더 CSS 속성도 복사합니다.

jquery.getStyleObject.js:

/*
 * getStyleObject Plugin for jQuery JavaScript Library
 * From: http://upshots.org/?p=112
 */

(function($){
    $.fn.getStyleObject = function(){
        var dom = this.get(0);
        var style;
        var returns = {};
        if(window.getComputedStyle){
            var camelize = function(a,b){
                return b.toUpperCase();
            };
            style = window.getComputedStyle(dom, null);
            for(var i = 0, l = style.length; i < l; i++){
                var prop = style[i];
                var camel = prop.replace(/\-([a-z])/g, camelize);
                var val = style.getPropertyValue(prop);
                returns[camel] = val;
            };
            return returns;
        };
        if(style = dom.currentStyle){
            for(var prop in style){
                returns[prop] = style[prop];
            };
            return returns;
        };
        return this.css();
    }
})(jQuery);

기본적인 사용법은 매우 간단하지만, 그에 대한 함수도 작성했습니다.

$.fn.copyCSS = function(source){
  var styles = $(source).getStyleObject();
  this.css(styles);
}

도움이 됐으면 좋겠다.

DOM 요소를 사용하지 않는가?이런 멤버를 포함하는 객체입니다.width그리고.backgroundColor.

나는 많은 다른 해결책을 시도했다.클래스 레벨에서 적용된 스타일과 요소에 직접 관련된 스타일을 선택할 수 있었던 것은 이 방법뿐이었습니다.따라서 css 파일레벨로 설정된 글꼴과 스타일 속성으로 설정된 글꼴이 올바른 글꼴을 반환합니다.

간단해! (죄송합니다만, 원래 있던 곳을 찾을 수 없습니다.)

//-- html object
var element = htmlObject; //e.g document.getElementById
//-- or jquery object
var element = htmlObject[0]; //e.g $(selector)

var stylearray = document.defaultView.getComputedStyle(element, null);
var font = stylearray["font-family"]

또는 어레이를 순환하여 모든 스타일을 나열할 수 있습니다.

for (var key in stylearray) {
console.log(key + ': ' + stylearray[key];
}

@marknadal의 솔루션은 하이픈화된 속성을 취득하지 않았습니다(예:max-width). 단, 첫 번째 변경은for루프 인하다css2json()성공했는데 반복 횟수가 적을 것 같습니다.

for (var i = 0; i < css.length; i += 1) {
    s[css[i]] = css.getPropertyValue(css[i]);
}

루프를 경유length보다는in,를 경유하여 취득하다getPropertyValue()보다는toLowerCase().

언급URL : https://stackoverflow.com/questions/754607/can-jquery-get-all-css-styles-associated-with-an-element

반응형