如何通过JavaScript在自定义CSS文件中创建类? [英] How to create class in a custom CSS file by JavaScript?
问题描述
我想在运行时使用JavaScript创建一个CSS类并写入一个自定义CSS文件。
现在我编写了代码(见下文)并创建了我的类但我不知道如何在CSS文件中创建它。
$ b
$ b 创建CSS但是我想在一个自定义的css文件中创建它。
您可以请求现有的 .css
使用 XMLHttpRequest()
或 fetch()
在 html
文件中,将新样式规则附加到 XMLHttpRequest中的
或 .css
文件中。 responseText response.text()
,或使用 FileReader
。
创建一个
Blob
或文件
对象,或者编码文本表示的新 css
文本添加到现有文件中,使用 rel $创建< link>
元素c $ c>属性设置为 stylesheet
, href
属性为 objectURL
,数据URI
或创建文件的编码文本,将链接
元素附加到 document.head
。 < head>
< script>
var cssupdate =`.context-menu-icon-case1:before {
content:url(progressbar.png);
}`;
var cssfile =style.css;
fetch(cssfile)
.then(response => response.text())
.then(currentcss => {
var css = currentcss +\\\
+`$ {cssupdate}`;
var link = document.createElement(link);
link.rel =stylesheet;
link.type =text / css ;
link.href =data:text / css,+ encodeURIComponent(css);
document.querySelector(head)。appendChild(link);
});
< / script>
< / head>
plnkr http://plnkr.co/edit/Gh0qR4CcQPROXCldX9OC?p=preview
I want to create a CSS class at runtime using JavaScript and write in a custom CSS file.
Now I wrote the code (see below) and created my class but I don't know how to create it in my CSS file.
var sheet = document.createElement('style')
sheet.innerHTML = ".context-menu-icon-case1:before{content: url(progressbar.png);}";
document.body.appendChild(sheet);
It creates the CSS class in my current page but I want to create it in a custom css file.
You can request the existing .css
file using XMLHttpRequest()
or fetch()
instead of loading the file at html
, append the new style rule to the .css
file at XMLHttpRequest.responseText
or response.text()
, or using FileReader
.
Create a Blob
or File
object, or encoded text representation of new css
text appended to existing file, create a <link>
element with rel
attribute set to stylesheet
, href
attribute to an objectURL
, data URI
or encoded text of the created file, append the link
element to document.head
.
<head>
<script>
var cssupdate = `.context-menu-icon-case1:before {
content: url(progressbar.png);
}`;
var cssfile = "style.css";
fetch(cssfile)
.then(response => response.text())
.then(currentcss => {
var css = currentcss + "\n" + `${cssupdate}`;
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = "data:text/css," + encodeURIComponent(css);
document.querySelector("head").appendChild(link);
});
</script>
</head>
plnkr http://plnkr.co/edit/Gh0qR4CcQPROXCldX9OC?p=preview
这篇关于如何通过JavaScript在自定义CSS文件中创建类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!