我正在寻找一种方法,使用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的计算样式列表中收集).虽然它获得了很长的值列表,但速度非常快.希望它对其他人有用.
所以我使用以下方法创建一个带圆角的容器:
div.rounded {
background: #CFFEB6 url('tr.gif') no-repeat top right;
}
div.rounded div {
background: url('br.gif') no-repeat bottom right;
}
div.rounded div div {
background: url('bl.gif') no-repeat bottom left;
}
div.rounded div div div {
padding: 10px;
}
Run Code Online (Sandbox Code Playgroud)
现在我想在容器中使用div:
.button {
border: 1px solid #999;
background:#eeeeee url('');
text-align:center;
}
.button:hover {
background-color:#c4e2f2;
}
<div class='round'><div><div><div>
<div class='button'><a href='#'>Test</a></div>
</div></div></div></div>
Run Code Online (Sandbox Code Playgroud)
但是,我在嵌套的div中放了一个div,按钮在角落里有bl图像.
如何删除继承的背景图像?