class样式转换为行内样式

求一个方案(非node环境)将页面引入的css文件中的class样式提取出来转换为标签的行内样式style,例如:

将如下的格式

<html>
<head>
  <style>
    p { color: red; }
  </style> 
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <p>Test</p>
</body>
</html>

style.css

p {
  text-decoration: underline;
}

转换成为:

<html>
<head>
</head>
<body>
  <p style="color: red; text-decoration: underline;">Test</p>
</body>
</html>
阅读 6.8k
5 个回答

你好,可以这样试试

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div {
            background-color: #fff;
        }

        .div {
            background-color: #000;
            color: blue;
        }
    </style>
</head>
<body>
<div class='div'>
    你好,可以这样试试
</div>

<script !src="">
    var div = document.querySelector('.div')
    var style = window.getComputedStyle(div, null)
    console.log(style);


    for (var k in style) {

        if (isNaN(k) && k != 'cssText') {

            if (style[k] == '0px' || style[k] == 'none' || style[k] == 'normal' || style[k] == 'auto' || !style[k]) {
                delete  div.style[k]
            } else {
                // console.log('--------------');
                // console.log(style[k] == '0px' || style[k] == 'none' || style[k] == 'normal' || style[k] == 'auto' || !style[k]);
                // console.log(style[k], 'value');
                // console.log(k, 'k');
                // console.log('--------------');
                div.style[k] = style[k];
            }
        }


    }

</script>
</body>
</html>

你这个脑洞很清奇。
为什么会需要这么做?

兄弟 你直接写不就好了吗? 这么整累不累啊? 你想写行内直接行内 想外链直接外链多好

正上班了,愣是没憋住笑了出声

在js里面写。选中相应的的元素标签。在设置相应的属性,就可以了
图片描述

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