Javascript 返回元素的计算样式以伪克隆该元素的jQuery CSS插件?

Javascript 返回元素的计算样式以伪克隆该元素的jQuery CSS插件?,javascript,jquery,css,web-applications,Javascript,Jquery,Css,Web Applications,我正在寻找一种使用jQuery返回第一个匹配元素的计算样式对象的方法。然后我可以将这个对象传递给jQuery的css方法的另一个调用 例如,使用,我可以执行以下操作以使两个div具有相同的宽度: $('#div2').width($('#div1').width()); 如果我能使文本输入看起来像现有的span,那就太好了: $('#input1').css($('#span1').css()); 其中,不带参数的.css()返回可以传递给的对象 (我找不到用于此的jQuery插件,但它似乎

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

例如,使用,我可以执行以下操作以使两个div具有相同的宽度:

$('#div2').width($('#div1').width());
如果我能使文本输入看起来像现有的span,那就太好了

$('#input1').css($('#span1').css());
其中,不带参数的.css()返回可以传递给的对象

(我找不到用于此的jQuery插件,但它似乎应该存在。如果它不存在,我将在下面将我的插件转换为插件,并将其与我使用的所有属性一起发布。)

基本上,我想伪克隆某些元素,但使用不同的标记。例如,我有一个li元素,我想隐藏它,并在它上面放置一个看起来相同的输入元素。当用户键入时,看起来他们正在内联编辑元素

对于这个伪克隆问题,我也愿意采用其他方法进行编辑。有什么建议吗

这是我目前拥有的。唯一的问题是得到所有可能的样式。这可能是一个荒谬的长名单


jQuery.fn.css2=jQuery.fn.css;
jQuery.fn.css=函数(){
if(arguments.length)返回jQuery.fn.css2.apply(this,arguments);
var attr=['font-family'、'font-size'、'font-weight'、'font-style'、'color',
“文本转换”、“文本装饰”、“字母间距”、“单词间距”,
“行高”、“文本对齐”、“垂直对齐”、“方向”、“背景色”,
“背景图像”、“背景重复”、“背景位置”,
“背景附件”、“不透明度”、“宽度”、“高度”、“顶部”、“右侧”、“底部”,
‘左’、‘上边距’、‘右边距’、‘下边距’、‘左边距’,
“padding-top”、“padding-right”、“padding-bottom”、“padding-left”,
“边框顶部宽度”、“边框右侧宽度”、“边框底部宽度”,
“边框左侧宽度”、“边框顶部颜色”、“边框右侧颜色”,
“边框底色”、“边框左颜色”、“边框顶样式”,
“右边框样式”、“下边框样式”、“左边框样式”、“位置”,
‘显示’、‘可见性’、‘z索引’、‘溢出x’、‘溢出y’、‘空白’,
“剪辑”、“浮动”、“清除”、“光标”、“列表样式图像”、“列表样式位置”,
“列表样式类型”、“标记偏移量”];
var len=attr.length,obj={};
对于(变量i=0;i
编辑:我现在已经使用上面的代码有一段时间了。它工作良好,行为与原始css方法完全相同,但有一个例外:如果传递0个参数,它将返回计算样式对象


如您所见,如果适用,它会立即调用原始css方法。否则,它将获取所有列出属性的计算样式(从Firebug的计算样式列表中收集)。虽然它得到了一长串的值,但速度相当快。希望它对其他人有用。

它不是jQuery,但在Firefox、Opera和Safari中,您可以使用
window.getComputedStyle(element)
获取元素的计算样式,在IE中现在我已经花了一些时间来研究这个问题,更好地理解jQuery的内部css方法是如何工作的,对于我提到的用例,我所发布的内容似乎足够好

有人建议你可以用CSS解决这个问题,但我认为这是一个更通用的解决方案,在任何情况下都可以工作,而无需添加删除类或更新CSS


我希望其他人觉得它有用。如果你发现了一个bug,请告诉我。

我不知道你对目前为止得到的答案是否满意,但我不满意,我的可能也不会让你满意,但它可能会帮助其他人

在思考了如何从一个元素到另一个元素“克隆”或“复制”元素的样式之后,我逐渐意识到循环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中有太多错误的想法。

我喜欢你的答案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)'
}
谢谢你的出发点

$.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'])

迟了两年,但我有你想要的解决办法。这是我写的一个插件(通过将另一个人的函数包装成插件格式),它可以完全满足您的需求,但在所有浏览器中都可以获得all可能的样式,即使是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);

希望对您有所帮助。

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);
(函数($){
var jQuery_css=$.fn.css,
gAttr=['font-family'、'font-size'、'font-weight'、'font-style'、'color'、'text-transform'、'text-decoration'、'letter-space'、'word-space'、'line-height'、'text-align'、'vertical-align'、'direction'、'background-color'、'background-repeat'、'background-position'、'background-attachment'、'不透明'、'width'、'height'、'height'、'top'、'right'、'left'、'ma'rgin-top'、'margin-right'、'margin-bottom'、'margin-left'、'padding-top'、'padding-right'、'padding-bottom'、'border-top-width'、'border-right-width'、'border-bottom-width'、'border-left-width'、'border-top-color
/*
 * 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
(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);
$('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);
/*
 * 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);