将 CSS 对象转换为样式标签

2024-03-04

有时我被迫以编程方式向 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 } );

这是一个使用原始样式对象的工作示例: 我将转换JSONinto CSS。并定义一个应该设置样式的目标请记住,没有应该设置样式的选择器...所以我添加了一个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');

这是一个工作Plunk https://plnkr.co/edit/n2BnDCqTdvhLdwXIjGTw?p=preview看看它是如何工作的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 CSS 对象转换为样式标签 的相关文章