能否单独获取class中的样式,例如backgroundImage?

使用getComputedStyle只能获取联合的最终样式,想单独获取class设置的样式,甚至是某个class设置的样式,有没有方法?

阅读 2.1k
3 个回答

浏览器没有开放这个 API,网页里无法完成。CDP 可以,不过用起来很麻烦。

真的要搞,可以简单解析一下 css,然后取得一个近似结果。

只想到一个比较麻烦的方法, 对document.styleSheets的所有元素进行遍历解析来查某个class设置的样式

image.png

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .test-class {
            margin-top: 16px;
            color: bisque;
        }
    </style>
</head>

<body>
    <section>
        <div style="height: 100px;background-color: palegreen;margin-left: 20px;margin-right: 20px;"></div>
        <div class="test-class"></div>
    </section>
</body>

</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题