首先,很抱歉我没有在这里放任何代码,因为我不知道如何做。
我需要的是获得所有的CSS选择器(在CSS文件中),它们专门包含一个颜色。。。比如说#3C3C3C。
示例:读取CSS文件
.first-selector div
{
color: #3C3C3C;
}
.second-selector span
{
background-color: #3C3C3C;
}
.thrid-selector
{
border: 1px solid #3C3C3C;
}
.fourth-selector .nothing
{
color: #00000;
}
预期结果-将其提取到数组中(仅包含具有特定颜色的样式)
array[0]['selector'] == ".first-selector div"
array[0]['style'] == "color"
array[1]['selector'] == ".second-selector span"
array[1]['style'] == "background-color"
array[2]['selector'] == ".thrid-selector"
array[2]['style'] == "border"
搜索具有特定颜色的选择器并将其放入数组的逻辑应该是什么?
注意这将在服务器端进行处理。
感谢
使用Files概念,只需在js中编写逻辑即可读取文件的内容,然后使用一些正则表达式逻辑或任何其他逻辑,如通过传递delimtre值来拆分内容。实际上,这不是正确的方法,只是
Javascript将允许您访问应用于文档的所有样式。检查每一个,看看它是否包含颜色。
CSS
<style>
.first-selector div
{
color: #3C3C3C;
}
.second-selector span
{
background-color: #3C3C3C;
}
.third-selector
{
border: 1px solid #3C3C3C;
}
.fourth-selector .nothing
{
color: red;
}
</style>
JS:
<script>
function getColorRules(color)
{
//convert hex to rgb, since hex color styles are internally stored as rgb
if (/[#]{0,1}[0-9A-F]{6}/.test(color))
{
color = color.replace('#', '');
var r = parseInt(color.substr(0, 2), 16);
var g = parseInt(color.substr(2, 2), 16);
var b = parseInt(color.substr(4, 2), 16);
color = "rgb(" + r + ", " + g + ", " + b + ")";
}
var returnArray = [];
//grab all stylesheets
var sheets = document.styleSheets;
for (var i in sheets) {
//to work in FF or chrome
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules)
{
//console.log(rules[r]);
if (rules[r].cssText !== undefined) { //ignore empty or non css properties
if (rules[r].cssText.indexOf(color) > -1) //if the color is found in the style rule
{ //add it to an array
var style = {
selector: rules[r].selectorText,
style: rules[r].style.cssText.split(":")[0]
};
returnArray.push(style);
}
}
}
}
return returnArray;
}
console.log(getColorRules("#3C3C3C"));
//[{ selector=".first-selector div", style="color"}, { selector=".second-selector span", style="background-color"}, { selector=".third-selector", style="border"}]
console.log(getColorRules("red"));
// [{ selector=".fourth-selector .nothing", style="color"}]
</script>