在JavaScript中添加动态样式

时间:2018-10-30 06:54:25

标签: javascript arrays foreach

我想从头复制现有样式并将其添加到window.open弹出窗口。以下是我的代码

const styleElements = document.getElementsByTagName('style');

let printContents ='<html><head>';

forEach(styleElements, style => {
    printContents += style;
    console.log(printContents);
});

但是我得到了:

[object HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement][object
HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement]
[object HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement][object
HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement]
[object HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement][object
HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement]
[object HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement][object
HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement]
[object HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement][object
HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement]
[object HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement][object
HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement][object HTMLStyleElement]
[object HTMLStyleElement]

4 个答案:

答案 0 :(得分:1)

Element.outerHTML

  

Element DOM接口的externalHTML属性获取描述元素(包括其后代)的序列化HTML片段。也可以设置为将元素替换为从给定字符串解析的节点。

您正在尝试将字符串与对象连接在一起。 尝试使用Element.outerHTML,方法如下:

const styleElements = document.getElementsByTagName('style');

let printContents ='<html><head>';

[...styleElements].forEach(style => {
  printContents += style.outerHTML;
  console.log(printContents);
});
<style>.test{margin: 10px;}</style>

答案 1 :(得分:0)

答案更新:

要将样式复制到通过var newWindow = window.open(); var newHead = newWindow.document.getElementsByTagName('head')[0]; var styles = document.getElementsByTagName('style'); Array.prototype.forEach.call(styles, function(style) { newHead.appendChild(style); }); 打开的新窗口中,可以尝试将仅存在的样式对象复制到新窗口的文档中:

>>> something = 'something'
>>> def bad():
...:    global something
...:    something += ' bad'
...:
>>> bad()
>>> something
>>> 'something bad'

您可以查看一个有效的示例:https://codepen.io/anon/pen/MPdjrm

答案 2 :(得分:0)

如下所示更新您的代码。

 forEach(styleElements, style => {
        printContents += style.textContent;
        console.log(printContents);
    });

答案 3 :(得分:0)

尝试一下

const styleElements = document.getElementsByTagName('style');

let printContents ='<html><head>';

Array.prototype.forEach.call(styleElements, style => {
  printContents += style.innerText;
});
console.log(printContents);
<style>
.test{background-color:red;}
</style>
<style>
.test2{background-color:green;}
</style>