【发布时间】: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