Can jQuery get all CSS styles associated with an element?

前端 未结 5 1159
谎友^
谎友^ 2020-11-21 06:31

Is there a way in jQuery to get all CSS from an existing element and apply it to another without listing them all?

I know it would work if they were a style attribut

5条回答
  •  广开言路
    2020-11-21 06:49

    Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.

    Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.

    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);
    

    Basic usage is pretty simple, but he's written a function for that as well:

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

    Hope that helps.

提交回复
热议问题