使用vanilla Javascript以类似数组的方式添加或注入多行CSS [英] Adding or injecting more than one row of CSS with vanilla Javascript in an array-like way

查看:70
本文介绍了使用vanilla Javascript以类似数组的方式添加或注入多行CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码在网页中将所有文字设为红色:

I use the following code to make all text red in a webpage:

var myCss = document.createElement("style");
myCss.type = "text/css";
myCss.innerHTML = " * {color: red !important} ";
document.body.appendChild(myCss);

此代码有效但我需要一种方法来插入几行CSS代码,而不只是一行。

This code works but I need a way to insert a few rows of CSS code, instead just one.

我尝试了这个,但没有奏效:

I tried this instead, but didn't work:

var cssArray = ["
   * {color: blue !important}
   * {background: white !important}
   #myId {display: block}
   .myClass {display: inline-block}
"];

var myCss = document.createElement("style");
myCss.type = "text/css";
myCss.innerHTML = cssArray;
document.body.appendChild(myCss);

我经历了很多SE QA会议,所有我发现在我使用时添加一个CSS行的交易以上。如果没有办法在一个命令中注入几个CSS行,你知道有没有脏的解决方法吗?

I went through many SE QA sessions and all I found deals with adding a single CSS row as I used above. If there is no way to inject several CSS rows in one command, is there any "dirty" workaround you know?

推荐答案

你如果你愿意,可以在一个字符串中做多行css。您不需要数组来执行此操作。

You can do multiple lines of css within a string if you want. You don't need an array to do this.

出于可读性目的,您可以使用 ES6模板文字

For readability purposes, you can set your multiline style string using an ES6 template literal:

// ES6 template literal `backtick` syntax
var myCss = `
  * {background: blue;}
  h2 {background: #333; color: red;}`,

  head = document.head || document.getElementsByTagName("head")[0],
  style = document.createElement("style");

style.type = "text/css";
style.styleSheet ? style.styleSheet.cssText = myCss : style.appendChild(document.createTextNode(myCss));

head.appendChild(style);

<h2>Styled with js</h2>

另见 CodePen演示

See also this CodePen Demo.

注意:如果你想支持 IE或模糊浏览器,您可能不想使用es6模板文字。

Note: If you want to support IE or obscure browsers, you might not want to use es6 template literals.

如果是这种情况,你可以简单地创建一个css字符串:

If that's the case, you can simply make a string of css:

var myCss = "* {background: blue;} h2 {background: #333; color: red;}";

或者您可以在多行连接字符串。

or you can concatenate the string on multiple lines.

var myCss = 
  "* {background: blue;} " +
  "h2 {background: #333; color: red;}";






您也可以使用原始代码并设置你的反引号语法中的css字符串。


You could use your original code as well and set your css string in the backtick syntax.

问题是你的代码会将样式插入到正文中。这可以产生一个 flash无格式内容 - 请参阅这个答案了解更多信息。

The problem is that your code will insert the styles into the body. This can produce a flash of unstyled content - see this answer for more information.

因此我建议将样式插入到头部中,上面的代码就是这样。

Therefore I recommend inserting the styles into the head, which the code above does.

这篇关于使用vanilla Javascript以类似数组的方式添加或注入多行CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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