繁体   English   中英

CSS 样式通过 JavaScript 内联样式

[英]CSS style to inline style via JavaScript

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

我有:

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

和:

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

现在我想要一个将我的 div 变成这样的 JavaScript 函数:

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

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

你可以这样做:

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是要应用样式的元素。

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

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

看来这个库会做你正在寻找的: https : //github.com/lukehorvat/computed-style-to-inline-style

将 HTML 元素的计算 CSS 转换为内联 CSS。

在内部使用 Window.getComputedStyle。

这个?

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

只需调用 transferAll onload 或任何地方。

使用 jQuery 可以轻松完成。 这是示例代码:
如果您是 jQuery 新手并且不知道如何添加和工作,请点击此链接

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

对于 javascript 代码,我没有信心,但对于 jQuery,我确信它会起作用。

如果我错了,请纠正我。

我认为,与接受答案的问题(感谢你!)就是一个prop ERTIES它试图在转移el从计算样式EMENT风格是cssText

如果我们从传输cssText和其他实际上是方法的属性中排除,它会起作用!

因此,在接受的答案和这个答案的基础上,我得到了:

var el = document.querySelector("#answer-25097808 > div > div.answercell.post-layout--right > div.s-prose.js-post-body > pre"); // change yourId to id of your element, or you can write “body” and it will convert all document
var els = el.getElementsByTagName("*");

for(var i = -1, l = els.length; ++i < l;){
    el = els[i]
    s = getComputedStyle(el)
    for (let styleKey in el.style) {
        for (let computedStyleKey in s) {
            let computedStyleKeyCamelCase = computedStyleKey.replace(/\-([a-z])/g, v => v[1].toUpperCase());
            if ((typeof el.style[styleKey] != "function") && (styleKey != 'cssText')){
                if(styleKey == computedStyleKeyCamelCase) {
                    el.style[styleKey] = s[computedStyleKey];
                }
            }
        }
    }
}

PS:上面的代码应该在开发者工具控制台中运行(在Chrome中试过)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM