我想知道是否可以像通过 JavaScript 添加 HTML 代码那样将 CSS 代码添加为字符串,例如:
var div = document.createElement("div");
div.innerHTML =
'<div id="hs1"></div>\n' +
'<div id="hs2"></div>\n' +
'<div id="hs3"></div>\n'
document.body.appendChild(div);
我可以以类似的方式添加一个巨大的 CSS 代码吗?
基本上我有 HTML + CSS + JS 代码,我想将其放入 .js
文件而不是 .html
。
我是网络开发的新手,所以我不知道。这可能吗?
最佳答案
您可以通过 vanilla JavaScript 注入(inject) CSS:
- 创建样式元素
- 使用 CSS 将其内容设置为您的字符串
- 将样式元素添加到 DOM 的头部
示例 1(也适用于较旧的浏览器):
// get the head and create a style element
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
// create your CSS as a string
var css = '.my-element { color: white; background: cornflowerblue; }';
// IE8 and below.
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
// add it to the head
head.appendChild(style);
<div class="my-element">Text</div>
示例 2(适用于较新的浏览器):
// create a style element
var style = document.createElement('style');
// add the CSS as a string
style.innerHTML = '.my-element { color: white; background: cornflowerblue; }';
// add it to the head
document.getElementsByTagName('head')[0].appendChild(style);
<div class="my-element">Text</div>
示例 3 (ES6):
// create a style element
const style = document.createElement('style');
// add the CSS as a string using template literals
style.appendChild(document.createTextNode(`
.my-element {
color: white;
background: cornflowerblue;
}`
));
// add it to the head
const head = document.getElementsByTagName('head')[0];
head.appendChild(style);
<div class="my-element">Text</div>
关于javascript - 通过 JavaScript 将 CSS 像 HTML 一样注入(inject) DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51050533/