我正在寻找一种方法,使用jQuery返回第一个匹配元素的计算样式对象。然后我可以将这个对象传递给另一个jQuery的css方法调用。
例如,使用width,我可以执行以下操作以使2个div具有相同的宽度:
$('#div2').width($('#div1').width());
如果我能使文字输入看起来像现有的范围那就太好了:
$('#input1').css($('#span1').css());
其中没有参数的.css()返回一个可以传递给.css(obj)的对象。
(我找不到这个jQuery插件,但它似乎应该存在。如果它不存在,我会把我的下面变成一个插件并发布它与我使用的所有属性。 )
基本上,我想伪克隆某些元素但使用不同的标记。例如,我有一个我要隐藏的li元素,并在其上放置一个看起来相同的输入元素。当用户输入时,看起来他们正在编辑内联元素。
我也对这种伪克隆问题的其他方法持开放态度。有什么建议吗?
这是我现在拥有的。唯一的问题是获得所有可能的样式。这可能是一个荒谬的长名单。
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个args,则返回计算出的样式对象。
正如您所看到的,如果适用的话,它会立即调用原始的css方法。否则,它将获取所有列出属性的计算样式(从Firebug的计算样式列表中收集)。虽然它获得了很长的值列表,但速度非常快。希望它对其他人有用。
答案 0 :(得分:59)
迟了两年,但我有你想要的解决方案。这是我写的插件(通过以插件格式包装其他人的功能),它完全符合您的要求,但在所有浏览器中都获得所有可能的样式,甚至是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(/\-([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();
}
})(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
希望有所帮助。
答案 1 :(得分:22)
这不是jQuery,但是在Firefox,Opera和Safari中,您可以使用window.getComputedStyle(element)
来获取元素的计算样式,而在IE&lt; = 8中,您可以使用element.currentStyle
。返回的对象在每种情况下都是不同的,我不确定使用Javascript创建的元素和样式有多好,但也许它们会很有用。
在Safari中,您可以执行以下操作:
document.getElementById('b').style.cssText = window.getComputedStyle(document.getElementById('a')).cssText;
答案 2 :(得分:5)
我不知道你是否对你到目前为止得到的答案感到满意,但我不是,我的也许也不讨好你,但它可能会帮助别人。
在思考如何“克隆”或“复制”元素的样式之后,我逐渐意识到,通过n循环并应用于n2的方法不是最优的,但我们是坚持这一点。
当您发现自己面临这些问题时,您很少需要将所有样式从一个元素复制到另一个元素......您通常有一个特定的理由希望应用“某些”样式。
这是我回复的内容:
$.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中没有太多错误的想法。
答案 3 :(得分:4)
既然我已经有时间研究这个问题并且更好地理解jQuery的内部css方法是如何工作的,那么我发布的内容似乎对我提到的用例运行得很好。
有人建议您可以使用CSS解决这个问题,但我认为这是一个更通用的解决方案,无论如何都可以使用,无需添加删除类或更新您的CSS。
我希望其他人觉得它很有用。如果您发现了错误,请告诉我。
答案 4 :(得分:3)
我喜欢你的回答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)'
}
感谢您的起点。
答案 5 :(得分:3)
.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(/\-([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);
主要思想来自Dakota's&amp; HexInteractive's回答。
答案 6 :(得分:2)
OP提供的强大功能。我稍微修改了它,以便您可以选择要返回的值。
(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']);
答案 7 :(得分:2)
我只是想为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(/\-([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() {
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()
答案 8 :(得分:0)
$.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'])