使用Javascript从CSS文件中提取颜色 [英] Pulling colors out of a CSS file using Javascript
问题描述
因此,如果css文件包含 { background-color:#ffffff; color:#000000;}
,我希望能够创建一个由 #ffffff,#000000
组成的列表。
这是最好的方法是什么?
我正在开发的项目是在GitHub如果你想要一些参考: https://github.com/yeremenko/farbe
事先感谢您
function getFileContents(){
var reader = new FileReader();
reader.onload = function(contents){
var fileContents = content.target.result; //存储文件内容
var singleColor = / * magic * /;
};
reader.readAsText(selectedFile); //获取文件内容到字符串
};
getFileContents();
我不知道这是否完全回答了您的问题,但如果你有CSS文件,你可以阅读它的内容,那么你可以简单地解析出颜色。请注意,CSS中有更多类型的颜色规格。
示例:
- $ b $作为十六进制规范的b
-
#FFFFFF
或#FFF
正则表达式:#[0-9aA-fF] {3}
#[0-9aA-fF] {6}
-
(255,255,255)
或(255,255,255,1)
作为RGB或RGBA规范
regex: \([0-9] {1,3}(*,*)[0-9] [0-9] {1,3}(*,* [0-1] {1}(\。[0-9] *)?)\)
-
白色
作为颜色名称规范
这可能有点困难 - 通过在CSS中形成一个可用的颜色名称列表,并分别寻找它们,找到这些可能是最简单的。
考虑到这一点,你可以执行
var cssContent = cssFile.readContent // get the file into a String
firstPattern =/`#[0-9aA-fF] {3} / g;
var matches = firstPattern.exec(cssContent);
while(matches!= null){
//附加到你的输出
}
//等等其他模式
希望它至少帮助一下!
I'm uploading a css file from which I hope to log every color that is referenced.
So if the css file has {background-color:#ffffff; color:#000000;}
, I hope to be able to create a list consisting of: #ffffff, #000000
.
What would be the best way of doing this?
The project I am working on is on GitHub if you would like some reference: https://github.com/yeremenko/farbe
Thank you in advance for any help you might provide!
function getFileContents () {
var reader = new FileReader();
reader.onload = function(contents) {
var fileContents = contents.target.result; //Stores file contents
var singleColor = /*magic*/;
};
reader.readAsText(selectedFile); //Gets file contents into string
};
getFileContents();
I'm not sure if this answers your question completely, but if you have the CSS file and you can read it's content, then you can simply parse out the colors. Just keep in mind that there are more types of color specifications inside CSS.
Examples:
#FFFFFF
or#FFF
as hexadecimal specification;
regexes: #[0-9aA-fF]{3}
and #[0-9aA-fF]{6}
(255,255,255)
or(255,255,255,1)
as RGB or RGBA specification
regex: \([0-9]{1,3}( *, *)[0-9]{1,3}( *, *)[0-9]{1,3}( *, *[0-1]{1}(\.[0-9]*)?)\)
white
as a color name specification
This might be a bit difficult - finding these would be probably easiest by forming a list of the available color names in CSS and looking for them separately.
With this in mind you can for example execute
var cssContent = cssFile.readContent(); // get the file into a String
firstPattern = "/`#[0-9aA-fF]{3}/g";
var matches = firstPattern.exec(cssContent);
while(matches!=null){
// append to your output
}
//and so on for other patterns
Hope it helps at least a bit!
这篇关于使用Javascript从CSS文件中提取颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!