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

后端 未结 9 1159
长情又很酷
长情又很酷 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: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.

提交回复
热议问题