CSS style to inline style via JavaScript

℡╲_俬逩灬. 提交于 2019-12-13 00:08:53

问题


I want to add all CSS styles of a specific element to it's inline style attribute. for example:

I have:

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

and:

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

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>

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


回答1:


You can do something like this:

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);

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.




回答2:


It appears this library will do what you're looking for: https://github.com/lukehorvat/computed-style-to-inline-style

Convert a HTML element's computed CSS to inline CSS.

Uses Window.getComputedStyle internally.




回答3:


Using jQuery it can be done easily. Here is the sample code:
If you are new in jQuery and you don't know how to add and work then follow this link

$(document).ready(function(){ $("#d").css('background-color', '#444444').css('width', '50px').css('height', '20px').css('display', 'inline-block'); });

For javascript code I am not confident but for jQuery I am sure that it will work.

Correct me if I am wrong.




回答4:


This one?

    function transferComputedStyle(node) {
        var cs = getComputedStyle(node, null);
        var i;
        for (i = 0; i < cs.length; i++) {
            var s = cs[i] + "";
              node.style[s] = cs[s];
        }
    }
    function transferAll() {
        var all = document.getElementsByTagName("*");
        var i;
        for (i = 0; i < all.length; i++) {
            transferComputedStyle(all[i]);
        }
    }

Simply call transferAll onload, or whereever.



来源:https://stackoverflow.com/questions/25097566/css-style-to-inline-style-via-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!