我想创建一个循环,以便遍历元素中定义的所有 CSS 属性。我的目标是创建一个合并两个元素样式的函数。
<span id="a1" style="font-family:verdana;">Hello</span>
<span id="a2" style="font-size:15;">World</span>
JS 函数看起来像这样:
function mergeStyle (obj,target){
$.each(test.style.CSSStyleDeclaration,function(){ // This will not work?
// Add to target
})
return;
};
最佳答案
我建议改用类,因为您的需求听起来不是一个好的设计。如果你仍然想要它,这应该有效:
$.fn.mergeCSS = function(other) {
var $this = $(this),
$other = $(other),
style = $other.get(0).style;
$.each(style, function(i, name) {
$this.css(name, style[name]);
});
return this;
};
元素的 .style
属性包含它的样式; CSSStyleDeclaration
是 .style
的构造函数,它不是特定于元素的。
用法:
$("<p style='color:green'>").mergeCSS("<p style='background-color:red'>");
// <p style='color: green; background-color: red; '>
它改变并返回第一个元素。
关于javascript - 遍历 HTMLElement 中的每个 CSS 值,合并 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9739664/