将CSS-Object转换为样式标记

Mar*_*tin 6 html javascript css jquery typescript

有时我被迫以编程方式将DOM样式添加到DOM中(如果您需要一个理由:想象一下编写一个带有自己样式的小UI小部件,但应该只包含一个*.js文件以便于处理).在这种情况下,我更喜欢使用对象表示法在我的脚本代码中定义样式,而不是使用混合规则,属性和标记的一个大字符串.

var thumbHoverStyle = {
    "background-color": "rgba(211, 211, 211, 0.5)",
    "cursor": "pointer"
};
Run Code Online (Sandbox Code Playgroud)

var thumbHoverStyle = "<style> .thumb:hover { background-color: rgba(211, 211, 211, 0.5); cursor: pointer; } </style>";
Run Code Online (Sandbox Code Playgroud)

这样的css-object可以很容易地与JQuery的.css()函数一起使用,但是一旦我想要设置一个css伪类(在我的例子中:hover),麻烦就开始了.在这种情况下,我无法使用JQuery .css()函数,我回过头来向我的DOM中插入相应的样式标记.

var thumbHoverStyleTag = toStyleTag( { ".thumb:hover": thumbHoverStyle } );
_root.append(thumbHoverStyleTag);
Run Code Online (Sandbox Code Playgroud)

我用google搜索和stackoverflowed但找不到将我的css-object转换为样式标记的实用程序函数.最后我编写了自己的函数(我可能会将它作为这个问题的答案),但我仍然想知道是否有一个库函数.实现这一目标的最优雅方法是什么?

编辑

我在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>`);
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

var styleTag = toStyleTag( { ".thumb": thumbStyle, ".thumb:hover": thumbHoverStyle } );
Run Code Online (Sandbox Code Playgroud)

Ber*_*ard 6

这是一个适用于原始样式对象的工作示例:我将转换JSONCSS. 并定义一个应该设置样式的目标 请记住,没有应该设置样式的选择器......所以我添加了一个targetSelector.

var targetSelector='.thumb:hover',
    styleObj = {
      "background-color": "rgba(211, 211, 211, 0.5)",
      "cursor": "pointer"
    },

    // Convert the JSON into CSS
    styleTagContent = JSON.stringify(styleObj,null,'\t')
                          .replace(/"/g,'')
                          .replace(/,\n/g,';')
                          .replace(/\}/g, ';}')  



  $('<style>'+targetSelector+styleTagContent+'</style>').appendTo('head');
Run Code Online (Sandbox Code Playgroud)

这是一个有效的Plunk来看看它是如何工作的。