jQuery的CSS插件,返回元素的计算风格伪克隆该元素?

我正在寻找一种使用jQuery的方式来返回第一个匹配元素的计算风格的对象。 然后我可以将这个对象传递给另一个jQuery的css方法调用。

例如, 宽度 ,我可以做到以下两个div有相同的宽度:

$('#div2').width($('#div1').width()); 

如果我可以使文本input看起来像一个现有的跨度将是很好的:

 $('#input1').css($('#span1').css()); 

没有参数的.css()返回一个可以传递给.css(obj)的对象 。

(我找不到一个jQuery插件,但它似乎应该存在,如果它不存在,我将把我的下面变成一个插件,并与我使用的所有属性后。

基本上,我想伪造某些元素, 但使用不同的标签 。 例如,我有一个li元素,我想隐藏并在其上看起来相同的input元素。 当用户键入时, 它看起来像在编辑内联元素

我也打开其他方法来编辑这个伪克隆问题。 有什么build议么?

这是我目前所拥有的。 唯一的问题就是获得所有可能的风格。 这可能是一个可笑的长列表。


 jQuery.fn.css2 = jQuery.fn.css; jQuery.fn.css = function() { if (arguments.length) return jQuery.fn.css2.apply(this, arguments); var attr = ['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']; var len = attr.length, obj = {}; for (var i = 0; i < len; i++) obj[attr[i]] = jQuery.fn.css2.call(this, attr[i]); return obj; } 

编辑:我现在一直在使用上面的代码。 它运行良好,行为与原始的css方法完全一样,但有一个例外:如果传​​递了0个参数,则返回计算的样式对象。

正如你所看到的,如果情况适用,它会立即调用原始的css方法。 否则,它将获得所有列出属性的计算样式(从Firebug的计算样式列表中收集)。 虽然这是一个长长的价值清单,但速度相当快。 希望对别人有用。

两年后,但我有你正在寻找的解决scheme。 这是我写的一个插件(通过将另一个人的function封装在插件格式中),它正是你想要的,但是在所有的浏览器,甚至IE中都可以获得所有可能的样式。

jquery.getStyleObject.js:

 /* * 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(/\-([az])/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(); } })(jQuery); 

基本用法很简单:

 var style = $("#original").getStyleObject(); // copy all computed CSS properties $("#original").clone() // clone the object .parent() // select it's parent .appendTo() // append the cloned object to the parent, after the original // (though this could really be anywhere and ought to be somewhere // else to show that the styles aren't just inherited again .css(style); // apply cloned styles 

希望有所帮助。

这不是jQuery,但在Firefox,Opera和Safari中,您可以使用window.getComputedStyle(element)来获取window.getComputedStyle(element)的计算样式,而在IE <= 8中,您可以使用element.currentStyle 。 返回的对象在每种情况下都是不同的,我不确定使用Javascript创build的元素和样式有多好,但也许它们会有用。

在Safari中,你可以做到以下几点:

 document.getElementById('b').style.cssText = window.getComputedStyle(document.getElementById('a')).cssText; 

我不知道如果你对迄今为止的答案感到满意,但是我不是,也可能不喜欢你,但它可以帮助别人。

在思考如何将元素的样式“克隆”或“复制”到另一个样式之后,我开始意识到这并不是一个通过n遍历并适用于n2的方法的最佳select,然而我们却不能适应这个。

当你发现自己面临这些问题时,你很less需要将所有样式从一个元素复制到另一个元素……通常有一个特定的原因希望“一些”样式适用。

这是我回到了:

 $.fn.copyCSS = function( style, toNode ){ var self = $(this); if( !$.isArray( style ) ) style=style.split(' '); $.each( style, function( i, name ){ toNode.css( name, self.css(name) ) } ); return self; } 

你可以传递一个以空格分隔的css属性列表作为第一个参数,并将你想克隆的节点作为第二个参数,如下所示:

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

无论什么似乎“错位”之后,我会尽量修改样式表,以免混乱我的Js太多的失误的想法。

现在我已经有了一些时间来研究这个问题,并且更好地理解jQuery的内部css方法是如何工作的,但是我发布的东西似乎对我提到的用例来说已经足够了。

有人build议你可以用CSS来解决这个问题,但是我认为这是一个更通用的解决scheme,无论如何都不需要添加删除类或者更新你的css。

我希望别人觉得有用。 如果您发现错误,请告诉我。

我喜欢你的答案Quickredfox。 我需要复制一些CSS,但不是立即所以我修改它使“toNode”可选。

 $.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 ); } 

如果你这样称呼它:

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

然后它会返回一个包含你的CSS声明的对象,供你稍后使用:

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

感谢您的出发点。

多用途.css()

用法

 $('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 

 (function($) { // Monkey-patching original .css() method var nativeCss = $.fn.css; var camelCase = $.camelCase || function(str) { return str.replace(/\-([az])/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); 

主要思想来自达科他和HexInteractive的答案。

OP提供的很好的function。 我稍微修改它,以便您可以select要返回的值。

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

$().css(['width','height']);select你想要的值$().css(['width','height']);

我只是想给Dakota提交的代码添加一个扩展。

如果你想克隆应用了它的所有样式和所有子元素的元素,那么你可以使用下面的代码:

 /* * 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(/\-([az])/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() { styles = {}; $this = $(this); $clone = $this.clone(); $clone.css( $this.getStyleObject() ); children = $this.children().toArray(); var i = 0; while( children.length ) { $child = $( children.pop() ); styles[i++] = $child.getStyleObject(); $child.children().each(function(i, el) { children.push(el); }) } cloneChildren = $clone.children().toArray() var i = 0; while( cloneChildren.length ) { $child = $( cloneChildren.pop() ); $child.css( styles[i++] ); $child.children().each(function(i, el) { cloneChildren.push(el); }) } return $clone } })(jQuery); 

然后你可以这样做: $clone = $("#target").cloneWithCSS()

 $.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; }; 

使用示例

 $("#element").cssCopy($("#element2"),['width','height','border'])