jQuery CSS plugin that returns computed style of element to pseudo clone that element?

后端 未结 9 1075
长情又很酷
长情又很酷 2020-11-22 15:27

I\'m looking for a way using jQuery to return an object of computed styles for the 1st matched element. I could then pass this object to another call of jQuery\'s css method

9条回答
  •  感情败类
    2020-11-22 15:58

    Multipurpose .css()

    Usage

    $('body').css();        // -> { ... } - returns all styles
    $('body').css('*');     // -> { ... } - the same (more verbose)
    $('body').css('color width height')  // -> { color: .., width: .., height: .. } - returns requested styles
    $('div').css('width height', '100%')  // set width and color to 100%, returns self
    $('body').css('color')  // -> '#000' - native behaviour
    

    Code

    (function($) {
    
        // Monkey-patching original .css() method
        var nativeCss = $.fn.css;
    
        var camelCase = $.camelCase || function(str) {
            return str.replace(/\-([a-z])/g, function($0, $1) { return $1.toUpperCase(); });
        };
    
        $.fn.css = function(name, value) {
            if (name == null || name === '*') {
                var elem = this.get(0), css, returns = {};
                if (window.getComputedStyle) {
                    css = window.getComputedStyle(elem, null);
                    for (var i = 0, l = css.length; i < l; i++) {
                        returns[camelCase(css[i])] = css.getPropertyValue(css[i]);
                    }
                    return returns;
                } else if (elem.currentStyle) {
                    css = elem.currentStyle;
                    for (var prop in css) {
                        returns[prop] = css[prop];
                    }
                }
                return returns;
            } else if (~name.indexOf(' ')) {
                var names = name.split(/ +/);
                var css = {};
                for (var i = 0, l = names.length; i < l; i++) {
                    css[names[i]] = nativeCss.call(this, names[i], value);
                }
                return arguments.length > 1 ? this : css;
            } else {
                return nativeCss.apply(this, arguments);
            }
        }
    
    })(jQuery);
    

    Main idea is taken from Dakota's & HexInteractive's answers.

提交回复
热议问题