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

后端 未结 9 1073
长情又很酷
长情又很酷 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:33
    $.fn.cssCopy=function(element,styles){
    var self=$(this);
    if(element instanceof $){
        if(styles instanceof Array){
            $.each(styles,function(val){
                self.css(val,element.css(val));
            });
        }else if(typeof styles===”string”){
            self.css(styles,element.css(styles));
        }
    }
    return this;
    };
    

    Use example

    $("#element").cssCopy($("#element2"),['width','height','border'])
    
    0 讨论(0)
  • 2020-11-22 15:37

    I like your answer Quickredfox. I needed to copy some CSS but not immediately so I modified it to make the "toNode" optional.

    $.fn.copyCSS = function( style, toNode ){
      var self = $(this),
       styleObj = {},
       has_toNode = typeof toNode != 'undefined' ? true: false;
     if( !$.isArray( style ) ) {
      style=style.split(' ');
     }
      $.each( style, function( i, name ){ 
      if(has_toNode) {
       toNode.css( name, self.css(name) );
      } else {
       styleObj[name] = self.css(name);
      }  
     });
      return ( has_toNode ? self : styleObj );
    }
    

    If you call it like this:

    $('div#copyFrom').copyCSS('width height color');
    

    Then it will return an object with your CSS declarations for you to use later:

    {
     'width': '140px',
     'height': '860px',
     'color': 'rgb(238, 238, 238)'
    }
    

    Thanks for the starting point.

    0 讨论(0)
  • 2020-11-22 15:41

    It's not jQuery but, in Firefox, Opera and Safari you can use window.getComputedStyle(element) to get the computed styles for an element and in IE<=8 you can use element.currentStyle. The returned objects are different in each case, and I'm not sure how well either work with elements and styles created using Javascript, but perhaps they'll be useful.

    In Safari you can do the following which is kind of neat:

    document.getElementById('b').style.cssText = window.getComputedStyle(document.getElementById('a')).cssText;
    
    0 讨论(0)
  • 2020-11-22 15:43

    Great function provided by the OP. I slightly modified it so that you can choose which values you want returned.

    (function ($) {
        var jQuery_css = $.fn.css,
            gAttr = ['font-family','font-size','font-weight','font-style','color','text-transform','text-decoration','letter-spacing','word-spacing','line-height','text-align','vertical-align','direction','background-color','background-image','background-repeat','background-position','background-attachment','opacity','width','height','top','right','bottom','left','margin-top','margin-right','margin-bottom','margin-left','padding-top','padding-right','padding-bottom','padding-left','border-top-width','border-right-width','border-bottom-width','border-left-width','border-top-color','border-right-color','border-bottom-color','border-left-color','border-top-style','border-right-style','border-bottom-style','border-left-style','position','display','visibility','z-index','overflow-x','overflow-y','white-space','clip','float','clear','cursor','list-style-image','list-style-position','list-style-type','marker-offset'];
        $.fn.css = function() {
            if (arguments.length && !$.isArray(arguments[0])) return jQuery_css.apply(this, arguments);
            var attr = arguments[0] || gAttr,
                len = attr.length,
                obj = {};
            for (var i = 0; i < len; i++) obj[attr[i]] = jQuery_css.call(this, attr[i]);
            return obj;
        }
    })(jQuery);
    

    Choose which values you want by specifying your own array: $().css(['width','height']);

    0 讨论(0)
  • 2020-11-22 15:47

    Now that I've had some time to look into the problem and understand better how jQuery's internal css method works, what I've posted seems to work well enough for the use case that I mentioned.

    It's been proposed that you can solve this problem with CSS, but I think this is a more generalized solution that will work in any case without having to add an remove classes or update your css.

    I hope others find it useful. If you find a bug, please let me know.

    0 讨论(0)
  • 2020-11-22 15:49

    I just wanted to add an extension to the code submitted by Dakota.

    If you want to clone an element with all of the styles applied to it and all the children elements then you can use the following code:

    /*
     * getStyleObject Plugin for jQuery JavaScript Library
     * From: http://upshots.org/?p=112
     *
     * Copyright: Unknown, see source link
     * Plugin version by Dakota Schneider (http://hackthetruth.org)
     */
    
    (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;i<style.length;i++){
                    var prop = style[i];
                    var camel = prop.replace(/\-([a-z])/g, camelize);
                    var val = style.getPropertyValue(prop);
                    returns[camel] = val;
                }
                return returns;
            }
            if(dom.currentStyle){
                style = dom.currentStyle;
                for(var prop in style){
                    returns[prop] = style[prop];
                }
                return returns;
            }
            return this.css();
        }
    
    
        $.fn.cloneWithCSS = function() {
            var styles = {};
    
            var $this = $(this);
            var $clone = $this.clone();
    
            $clone.css( $this.getStyleObject() );
    
            var children = $this.children().toArray();
            var i = 0;
            while( children.length ) {
                var $child = $( children.pop() );
                styles[i++] = $child.getStyleObject();
                $child.children().each(function(i, el) {
                    children.push(el);
                })
            }
    
            var cloneChildren = $clone.children().toArray()
            var i = 0;
            while( cloneChildren.length ) {
                var $child = $( cloneChildren.pop() );
                $child.css( styles[i++] );
                $child.children().each(function(i, el) {
                    cloneChildren.push(el);
                })
            }
    
            return $clone
        }
    
    })(jQuery);
    

    Then you can just do: $clone = $("#target").cloneWithCSS()

    0 讨论(0)
提交回复
热议问题