代码之家  ›  专栏  ›  技术社区  ›  Keith Bentrup

jquery css插件,返回元素的计算样式伪克隆该元素?

  •  67
  • Keith Bentrup  · 技术社区  · 15 年前

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

    例如,使用 width ,我可以执行以下操作,使两个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个参数,则返回计算样式对象。

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

    9 回复  |  直到 10 年前
        1
  •  59
  •   Mottie    13 年前

    迟了两年,但我有你想要的解决方案。这是我写的一个插件(用插件格式包装另一个人的函数),它可以完全满足你的需要,但是 全部的 所有浏览器中可能的样式,甚至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
    

    希望有帮助。

        2
  •  22
  •   abernier    11 年前

    它不是jquery,但在firefox、opera和safari中,您可以使用 window.getComputedStyle(element) 要获取元素的计算样式,并且在ie<=8中,可以使用 element.currentStyle . 返回的对象在每一种情况下都是不同的,我不确定如何处理使用JavaScript创建的元素和样式,但也许它们会有用。

    在Safari中,您可以执行以下操作,这有点简单:

    document.getElementById('b').style.cssText = window.getComputedStyle(document.getElementById('a')).cssText;
    
        3
  •  5
  •   Quickredfox    15 年前

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

    在考虑了如何“克隆”或“复制”元素的风格从一个到另一个之后,我开始意识到,循环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中充斥着太多不正确的想法。

        4
  •  4
  •   Keith Bentrup    15 年前

    既然我已经花了一些时间来研究这个问题并更好地理解jquery的内部css方法是如何工作的,那么我所发布的内容对于我提到的用例来说似乎已经足够好用了。

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

    我希望其他人觉得它有用。如果你发现一只虫子,请告诉我。

        5
  •  3
  •   HexInteractive    14 年前

    我喜欢你的回答。我需要复制一些CSS,但不是立即,所以我修改了它,使“音调”成为可选的。

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

    谢谢你的出发点。

        6
  •  3
  •   Community CDub    7 年前

    多用途的 .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 和; HexInteractive's 答案。

        7
  •  2
  •   Shea LAW    13 年前

    我稍微修改了一下,这样你就可以选择你想要返回的值。

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

        8
  •  2
  •   marcopolo    11 年前

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

    如果要克隆应用了所有样式的元素和所有子元素,则可以使用以下代码:

    /*
     * 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()

        9
  •  0
  •   rterrani    14 年前
    $.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'])