通过JavaScript将CSS样式转换为嵌入式样式 [英] CSS style to inline style via JavaScript

查看:73
本文介绍了通过JavaScript将CSS样式转换为嵌入式样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将特定元素的所有CSS样式添加到其内联样式属性。例如:

I want to add all CSS styles of a specific element to its inline style attribute. For example:

我有:

 <div id="d"></div>

和:

#d { background: #444444; width: 50px; height: 20px; display: inline-block; }

现在,我想要一个JavaScript函数将div转换为:

Now I want a JavaScript function that turns my div into this:

<div id="d" style="background: #444444; width: 50px; height: 20px; display: inline-block;"></div>

请帮助我。而且,顺便说一句,我不希望任何CSS样式重写任何现有的内联样式。

Please help me. And, by the way, I don't want any CSS styles to re-write any existing inline style.

推荐答案

做这样的事情:

function applyStyle(el) {
    s = getComputedStyle(el);

    for (let key in s) {
        let prop = key.replace(/\-([a-z])/g, v => v[1].toUpperCase());
        el.style[prop] = s[key];
    }
}

let x = document.getElementById('my-id');
applyStyle(x);

其中 x 是您想要的元素套用样式。

Where x is the element you want to apply the style to.

基本上,此函数获取元素的计算样式,然后将每个属性(如填充,背景,颜色等)复制到元素的内联样式。

Basically this function gets the computed style of the element and then copies each property (like padding, background, color, etc.) to the inline style of the element.

我不知道您为什么需要这样做,但是,在我看来,这是一种很肮脏的方法,我个人不建议使用它。

I don't know why you need to do this, but, in my opinion, but it's really dirty approach, I would not personally advise to use it.

这篇关于通过JavaScript将CSS样式转换为嵌入式样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆