我想知道是否可以将CSS代码作为字符串添加,就像通过JavaScript添加HTML代码的方式,例如:
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
文件中。
我是Web开发的新手,所以不知道。这有可能吗?
答案 0 :(得分:6)
您可以通过原始JavaScript注入CSS:
// 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>
// 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>
// 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>
答案 1 :(得分:2)
是的,您是否尝试过创建<style>
标签,使用规则填充它并注入它?
const style = document.createElement("style");
style.innerHTML = "#foo{background-color: green;}";
document.head.appendChild(style);
<div id="foo">Foo bar</div>
答案 2 :(得分:1)
您尝试过吗?
document.getElementById('myButton').onclick = function() {
var sc = document.createElement('style');
sc.innerHTML = "#myDiv { padding: 10px; border: 1px dashed blue; }";
document.getElementById('myDiv').appendChild( sc );
}
<div id="myDiv">
Test 123
</div>
<button id="myButton">Click Me!</button>
如果您有 GIANT css文件。最好加载文件本身。您可以像上面一样创建一个style
标签,并设置href
属性以加载它。
答案 3 :(得分:1)
您可以使用CSSStyleSheet界面来处理样式表。下面的示例向您展示如何操作现有样式表。通过此方法,您可以指定插入规则的位置,而不必始终在结尾处附加>
document.querySelector("#button-1").addEventListener("click", function() {
var sheet = document.querySelector("style").sheet;
var color = "rgb(" + Math.floor(Math.random() * 256) + ", " + Math.floor(Math.random() * 256) + ", " + Math.floor(Math.random() * 256) + ")";
sheet.insertRule("p { background-color: " + color + "; }", sheet.cssRules.length);
});
/* this stylesheet intentionally left blank */
<button id="button-1">Modify Stylesheet</button>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vestibulum urna risus, non finibus sem fermentum eget. In at libero a justo molestie semper. Praesent sit amet massa justo. Donec aliquet lobortis justo tincidunt ultrices.</p>