找到你要的答案

Q:Styling CSS of Programatically created classes

Q:造型程序创建CSS类

Another component in my site creates span's with the class HighlightCOLOR where COLOR is any html color.

I then need to style the css the make the span that color. I can do this obviously by creating css classes for each color and then style the background color the named color. For example:

.HighlightMagenta
    {
        background-color:magenta;
    }

Is there a more elegant solution that simply writing css for each possible color?

Note: I can't change the structure described above. Its relevant for too many other things and the inelegant solution works well enough not not warrant a rebuild. I am happy to use javascript solutions, but would prefer a pure CSS solution. I don't do Jquery.

To clarify based on questions below:

The issue is that my html is being populated with unstyled spans of unknown (but predictable) class names. The class names are in the format HighlightColor where Color is an html color. I then need to style these classes with css that corresponds to the color named in the class title.

在我的网站的另一个组件创建跨与类,颜色是任何HTML颜色突出显示的颜色。

然后我需要的风格使跨度的CSS颜色。我可以做这个明显的CSS类的每个颜色和风格的背景颜色命名的颜色。例如:

.HighlightMagenta
    {
        background-color:magenta;
    }

有一个更优雅的解决方案,简单地编写CSS的每个可能的颜色?

注:我不能改变上面描述的结构。其相关的其它很多的事情和不完善的解决方案的好作品不需要重建。我很高兴使用JavaScript的解决方案,但更喜欢纯CSS的解决方案。我不做jQuery。

根据以下问题澄清:

问题是,我正在填充样式,跨越未知(但可预见)类名称。这类名字的格式突出显示的颜色,颜色是一种颜色。然后我需要这类风格的CSS对应的颜色在类的标题命名。

answer1: 回答1:

you can get all elements with those highlight classes and get the color name, and simply set the styling to it using JavaScript.

in my example i assume that those spans only have 1 class and its the color class, but you can easily get them even if they have other classes too.

if those spans are created dynamically, then run the function each time after new spans are created:

processColors();

function processColors() {
  coloredClasses = document.querySelectorAll('span[class^="Highlight"]');
  for (i = 0; i < coloredClasses.length; i++) {
    CurrName = coloredClasses[i].className.split("Highlight")[1];
    coloredClasses[i].style["background"] = CurrName;
  }
}
<span class="HighlightRED">Colored Span</span>
<span class="HighlightMAGENTA">Colored Span</span>
<span class="HighlightBLACK">Colored Span</span>
<span class="HighlightNAVY">Colored Span</span>
<span class="HighlightYELLOW">Colored Span</span>
<span class="HighlightGREEN">Colored Span</span>

你可以与那些强调类所有的元素和获得颜色的名字,和简单的设置样式使用JavaScript。

在我的例子中,我假设这些跨度只有1个类和它的颜色类,但你可以很容易地得到他们,即使他们有其他类太。

如果这些跨度是动态创建的,那么每次创建新的跨度后运行函数:

processColors();

function processColors() {
  coloredClasses = document.querySelectorAll('span[class^="Highlight"]');
  for (i = 0; i < coloredClasses.length; i++) {
    CurrName = coloredClasses[i].className.split("Highlight")[1];
    coloredClasses[i].style["background"] = CurrName;
  }
}
<span class="HighlightRED">Colored Span</span>
<span class="HighlightMAGENTA">Colored Span</span>
<span class="HighlightBLACK">Colored Span</span>
<span class="HighlightNAVY">Colored Span</span>
<span class="HighlightYELLOW">Colored Span</span>
<span class="HighlightGREEN">Colored Span</span>
answer2: 回答2:

While this may not be the solution you are looking for. If you want a pure css solution you'll need to declare all those classes in css.

Manually this will take a lot of time, but I suggest you look into css preprocessors like LESS or SASS (I prefer the latter).

They accept functions and will then "compile" into a css sheet which you can use for your website.

You could write a function to generate all those classes with the rules you want them to have.

LESS

SASS

虽然这可能不是你正在寻找的解决方案。如果你想要一个纯CSS的解决方案需要在CSS中声明的类。

手动这会花费很多时间,但我建议你考虑CSS预处理器不喜欢或Sass(我更喜欢后者)。

他们接受的功能,然后编译成CSS表,你可以使用你的网站。

你可以写一个函数来生成所有这些类的规则,你希望他们有。

萨斯

answer3: 回答3:

You can add style tag by javascript dynamically.

Use [class*="Highlight"] to get all elements which class contains word Highlight.

Then for each div, find its color name either use string operation or regex, then add it to either an Object or a Set to maintain its unique, then for each color, create a style tag to added those rules.

var head = head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
var targetDivs = document.querySelectorAll('div[class*="Highlight"]');
var colors = {};

var len = targetDivs.length;
var i, color, matches;
var colorString = /Highlight([a-zA-z]+)/;
var matches;
for (i = 0; i < len; ++i) {
  matches = targetDivs[i].className.match(colorString);
  if (matches) {
    colors[matches[0]] = matches[1].toLowerCase();
  }
};

var classNames = Object.keys(colors);
classNames.forEach(function(className) {
  var color = colors[className];
  var stl = 'div.' + className + '{ background-color: ' + color + '}\n';
  style.appendChild(document.createTextNode(stl));
});

head.appendChild(style);
div {
  width: 50px;
  height: 50px;
}
<div class="test HighlightMagenta"></div>
<div class="HighlightRed test"></div>
<div class="HighlightBlue"></div>

你可以添加样式标签通过JavaScript动态。

使用[类* =“高亮”]获取包含类高亮的所有元素。

然后为每个div,找到它的颜色名称字符串的操作或使用正则表达式,然后添加到一个对象或一组保持其独特的,然后为每个颜色,创建一个样式标签添加规则。

var head = head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
var targetDivs = document.querySelectorAll('div[class*="Highlight"]');
var colors = {};

var len = targetDivs.length;
var i, color, matches;
var colorString = /Highlight([a-zA-z]+)/;
var matches;
for (i = 0; i < len; ++i) {
  matches = targetDivs[i].className.match(colorString);
  if (matches) {
    colors[matches[0]] = matches[1].toLowerCase();
  }
};

var classNames = Object.keys(colors);
classNames.forEach(function(className) {
  var color = colors[className];
  var stl = 'div.' + className + '{ background-color: ' + color + '}\n';
  style.appendChild(document.createTextNode(stl));
});

head.appendChild(style);
div {
  width: 50px;
  height: 50px;
}
<div class="test HighlightMagenta"></div>
<div class="HighlightRed test"></div>
<div class="HighlightBlue"></div>
answer4: 回答4:

You can programmatically add a styleSheet and then use styleSheet.insertRule(rule, index) to insert the styles from a list of predefined color names (fiddle):

addColorRules(); // run when head element is available

function addColorRules() {
    var style = document.createElement('style'), // create new stylesheet element
        styleSheet;

    document.head.appendChild(style); // append to head

    styleSheet = style.sheet; // get the sheet from the element

    getColors().forEach(function (color) { // iterate color names
        var rule = '.Highlight' + color + '{background-color: ' + color + '; }'; // create the rule
        styleSheet.insertRule(rule, styleSheet.cssRules.length); // insert rule to style sheet
    });
}


function getColors() { // a list of predefined color names
    return ["Aliceblue", "Antiquewhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "Blanchedalmond", "Blue", "Blueviolet", "Brown"]; // include all color names
}

你可以添加一个样式表,然后使用样式表。insertrule(规则、指数)从列表中预定义的颜色名称插入方式(小提琴):

addColorRules(); // run when head element is available

function addColorRules() {
    var style = document.createElement('style'), // create new stylesheet element
        styleSheet;

    document.head.appendChild(style); // append to head

    styleSheet = style.sheet; // get the sheet from the element

    getColors().forEach(function (color) { // iterate color names
        var rule = '.Highlight' + color + '{background-color: ' + color + '; }'; // create the rule
        styleSheet.insertRule(rule, styleSheet.cssRules.length); // insert rule to style sheet
    });
}


function getColors() { // a list of predefined color names
    return ["Aliceblue", "Antiquewhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "Blanchedalmond", "Blue", "Blueviolet", "Brown"]; // include all color names
}
answer5: 回答5:

JavaScript could solve the problem:

$(document).ready(function() {
    $('.Highlight').each(function(elem){
        $(this).css('background-color',$(this).data('color'))
    })
})

http://jsfiddle.net/qtbrsbuh/

JavaScript可以解决问题:

$(document).ready(function() {
    $('.Highlight').each(function(elem){
        $(this).css('background-color',$(this).data('color'))
    })
})

http://jsfiddle.net/qtbrsbuh/

javascript  html  css