如何将元素css转换为JSON

How to convert an element css to JSON?

本文关键字:转换 JSON css 元素      更新时间:2023-09-26

我允许用户在打印前更改页面中每个元素的任何属性(位置、颜色等)。

我正在寻找一种方式,用户可以存储新的样式表和恢复它以后任何时候?

我试图解析element.style,但它不返回一个数组!$(element).css()也不能毫无争议地工作!

如果你可以使用插件来完成你的任务,试试这个插件:https://github.com/reworkcss/css-parse

: http://bililite.com/blog/blogfiles/cssparser/cssparsertest.php

的例子:CSS:

body {background: #eee;color: #888;}
输出:

{
    "type": "stylesheet",
        "stylesheet": {
        "rules": [{
            "type": "rule",
                "selectors": [
                "body"],
                "declarations": [{
                "type": "declaration",
                    "property": "background",
                    "value": "#eee"
            }, {
                "type": "declaration",
                    "property": "color",
                    "value": "#888"
            }]
        }]
    }
}

多亏了Johan我找到了正确的答案!我只需要解析

window.getComputedStyle(element);

tnx每个人:)

与其为每个元素分配自定义样式,不如为整个页面使用唯一的样式类和单个样式表(将其添加到头部,记住元素或给它一个唯一的id),其中包含您的自定义样式。

然后可以通过stylesheet枚举样式表。cssRules和构建自定义json