这是HTML :(示例)
<div id="id1" style="width:100px;background: rgb(196, 14, 14);">1</div>
<div id="id2" style="margin-top:10px">2</div>
to
<div id="id1" style="width:100px;background: rgb(196, 14, 14);">1</div>
<div id="id2" style="width:100px;background: rgb(196, 14, 14);margin-top:10px">2</div>
这是js:
var x = $('#id1').clone().attr('style');
$('#id2').attr('style', x);
I do not want this code margin-top:10px
to be deleted.
此代码可以帮助您动态更新样式属性。
因此,从元素中获取现有样式,向其添加x,然后使用结果更新element样式属性。另外,没有理由使用clone()。只需获取样式属性即可。
However, a better way to do this would be using classes and CSS. You can then just use
addClass()
to add the new class to the element.