有时我被迫以编程方式向 DOM 添加 CSS 样式(如果您需要一个理由:想象一下编写一个小型 ui 小部件,它具有自己的样式,但应该仅包含一个 *.js 文件,以便于处理)。在这种情况下,我更喜欢使用对象表示法在脚本代码中定义样式,而不是混合规则、属性和标记的一个大字符串。
var thumbHoverStyle = {
"background-color": "rgba(211, 211, 211, 0.5)",
"cursor": "pointer"
};
versus
var thumbHoverStyle = "<style> .thumb:hover { background-color: rgba(211, 211, 211, 0.5); cursor: pointer; } </style>";
这样的 css 对象可以很容易地与JQuery .css() 函数 http://api.jquery.com/css/,但是当我想要设计一个样式时,麻烦就开始了CSS伪类 https://developer.mozilla.org/en/docs/Web/CSS/Pseudo-classes(在我的例子中:悬停)。在这种情况下我无法使用 JQuery.css()
函数,然后我又将相应的样式标签插入到我的 DOM 中。
var thumbHoverStyleTag = toStyleTag( { ".thumb:hover": thumbHoverStyle } );
_root.append(thumbHoverStyleTag);
我用谷歌搜索和 stackoverflowed 但找不到将我的 css 对象转换为样式标签的实用程序函数。
最后我编写了自己的函数(我可能会提供它作为这个问题的答案),但我仍然想知道是否有一个库函数可以实现这一点。
完成此任务最优雅的方法是什么?
Edit
我在 TypeScript 中的实现:
function appendPxIfNumber(value: any): string
{
return (typeof value === "number") ? "" + value + "px" : value;
}
function toStyleTag(rulesObj: any)
{
var combinedRules: string = "";
for (var selector in rulesObj)
{
var cssObject = rulesObj[selector];
var combinedProperties = "";
for (var prop in cssObject) {
var value = cssObject[prop];
combinedProperties += `${prop}: ${appendPxIfNumber(value)};` + "\n";
}
combinedRules += ` ${selector} {${combinedProperties}}` + "\n";
}
return $(`<style>${combinedRules}</style>`);
}
使用示例:
var styleTag = toStyleTag( { ".thumb": thumbStyle, ".thumb:hover": thumbHoverStyle } );