【问题标题】:jQuery CSS plugin that returns computed style of element to pseudo clone that element?jQuery CSS插件返回元素的计算样式以伪克隆该元素?
【发布时间】:2010-11-03 12:27:10
【问题描述】:

我正在寻找一种使用 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 个参数,它会返回计算的样式对象。

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

【问题讨论】:

  • 不知道您的问题是否可以通过 CSS 类更好地解决?
  • 我也希望看到一个解决方案,但我建议不要遍历每个计算样式。当我使用非 jquery 但获取计算样式的标准方法时,仅获取一个属性大约需要 1-1.5 毫秒。遍历一个获取每个属性的数组可能会增加相当长的延迟时间。
  • @Ian,在我用了 2 年以上的旧笔记本电脑上分析上述内容,它在 7 毫秒内克隆了大约 50 个属性。
  • 您不需要用css2 污染jQuery.fn 命名空间。如果您使用闭包,您可以就地转换原始函数。在这里查看我的编辑:stackoverflow.com/a/1471256/399649

标签: javascript jquery css web-applications


【解决方案1】:

晚了两年,但我有您正在寻找的解决方案。这是我编写的一个插件(通过以插件格式包装另一个人的函数),它完全符合您的要求,但在所有浏览器中获得所有可能的样式,甚至是 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

希望对您有所帮助。

【讨论】:

  • 只需将var camel = prop.replace(/\-([a-z])/, camelize); 更改为var camel = prop.replace(/\-([a-z])/g, camelize); 就可以了。谢谢!
  • @Dakota:+1。但我在末尾添加了括号 - getStyleObject();;因为 style 将包含一个函数,而不是一个具有所有样式的对象;)
  • 有什么机会/方法可以让它与更新的 CSS3 属性一起使用,比如转换、翻译等?这不做那些
  • 有没有办法获取所有内部元素,具有各自的样式?内部元素没有得到它们的样式。
  • @HalfBloodPrince 正在寻找同样的东西,请参阅此页面上的 Nonconformist 的答案。
【解决方案2】:

它不是 jQuery,但在 Firefox、Opera 和 Safari 中,您可以使用 window.getComputedStyle(element) 来获取元素的计算样式,而在 IEelement.currentStyle。返回的对象在每种情况下都是不同的,我不确定使用 Javascript 创建的元素和样式的效果如何,但也许它们会很有用。

在 Safari 中,您可以执行以下操作:

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

【讨论】:

  • 谢谢。在进一步研究了这个问题之后,这些方法被 jquery 在 css 方法中使用,所以它会重写已经存在的内容。
  • 值得一提的是window.getComputedStyle现在得到了很好的支持:caniuse.com/getcomputedstyle
【解决方案3】:

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

在思考如何将元素的样式从一个“克隆”或“复制”到另一个之后,我开始意识到循环遍历 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】:

    我喜欢你的回答 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】:

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

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

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

      【讨论】:

        【解决方案6】:

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

        【讨论】:

        • 这太棒了!我可能会建议改进 HexInteractive's answer:添加一个 else if(name.split(' ').length &gt; 1) 并为 $('body').css('color padding width') // -&gt; { ... } 构建一个以空格分隔的 css 值的对象
        • 谢谢。添加了空格分隔的语法。请测试一下。
        • 很棒的功能!但是可能您还需要在开头添加未定义的条件: if (name == undefined || name == null || name === '*') 才能正常工作。
        • "name == null" 也处理未定义。 Сheck: undefined == null => 返回 true。
        • 谢谢,添加 $('div').css('*:not(display)') 会非常方便
        【解决方案7】:

        我只是想为 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() {
                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);
        

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

        【讨论】:

          【解决方案8】:

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

          【讨论】:

            【解决方案9】:
            $.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'])
            

            【讨论】:

              猜你喜欢
              • 2021-12-31
              • 1970-01-01
              • 2011-04-23
              • 1970-01-01
              • 2011-12-20
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多