我正在寻找一种方法,使用jQuery返回第一个匹配元素的计算样式对象.然后我可以将此对象传递给另一个jQuery的css方法调用.
例如,对于宽度,我可以执行以下操作以使2个div具有相同的宽度:
$('#div2').width($('#div1').width());
Run Code Online (Sandbox Code Playgroud)
如果我可以使文本输入看起来像现有的跨度,那将是很好的:
$('#input1').css($('#span1').css());
Run Code Online (Sandbox Code Playgroud)
其中.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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:我现在已经使用上面的代码一段时间了.它运行良好,行为与原始css方法完全相同,只有一个例外:如果传递0个args,则返回计算出的样式对象.
正如您所看到的,如果适用的话,它会立即调用原始的css方法.否则,它将获取所有列出属性的计算样式(从Firebug的计算样式列表中收集).虽然它获得了很长的值列表,但速度非常快.希望它对其他人有用.
我正在编写一个脚本,需要检查<style>标签内是否定义了某些CSS属性.
<style type="text/css">
#bar {width: 200px;}
</style>
Run Code Online (Sandbox Code Playgroud)
<div id="foo" style="width: 200px;">foo</div>
<div id="bar">bar</div>
Run Code Online (Sandbox Code Playgroud)
// 200px
console.log(document.getElementById("foo").style.width);
// an empty string
console.log(document.getElementById("bar").style.width);
if(property_width_defined_in_style_tag) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
这可能吗?
我不是想要getComputedStyle(ele).width顺便说一下.