类似于Regex的CSS属性选择器通配符捕获

时间:2015-10-26 19:45:55

标签: javascript css

假设我有以下HTML:

<div class="tocolor-red">    tocolor </div>
<div class="tocolor-blue">   tocolor </div>
<div class="tocolor-green">  tocolor </div>
<div class="tocolor-yellow"> tocolor </div>

而不是像下面的代码片段那样为每种颜色重复CSS代码...

.tocolor-red{
  background: red;
}
.tocolor-red::before {
  content: "red";
}

...有没有办法编写一个CSS规则来捕获css类的颜色?为了尽职尽责,我已经查找了属性选择器,我注意到有很多方法可以在css中使用通配符。但是,我没有找到任何可以捕获通配符文本的内容,也不会作为规则的一部分。

如果正则表达式适用于CSS,规则将如下所示:

.tocolor-([\w+]) {
   background: $1;
}
.tocolor-([\w+]:before {
   content: $1;
}

2 个答案:

答案 0 :(得分:2)

CSS无法支持正则表达式捕获,而您可以选择具有以字符串tocolor-开头的类的所有元素,CSS无法捕获字符串的值以将其应用于规则

顺便提一下,有点迟了,使用JavaScript执行此操作的一种方法是:

// retrieve all elements containing the string 'tocolor-':
var elements = document.querySelectorAll('[class*="tocolor-"]'),

// declaring two variables for use in later loops:
    classes, colorString;

// iterating over the (Array-like) collection of elements,
// using Function.prototype.call() to be able to apply the
// Array.prototype.forEach() method on the collection:
Array.prototype.forEach.call(elements, function (elem) {
    // 'elem' is the individual node of the collection
    // over which we're iterating.

    // creating an Array of the classes from the element:
    classes = Array.prototype.slice.call(elem.classList, 0);

    // creating a new Array, using Array.prototype.map():
    colorString = classes.map(function (c) {
        // 'c' is the specific class of the Array of classes
        // over which we're iterating.

        // if the current class ('c') begins with the string
        // 'tocolor-' then we return that class
        if (c.indexOf('tocolor-') === 0) {

            // after first replacing the 'tocolor-' string
            // with an empty string:
            return c.replace('tocolor-','');
        }
    });

    // setting the color of the element ('elem') to
    // the string found:
    elem.style.color = colorString;
});

&#13;
&#13;
var elements = document.querySelectorAll('[class*="tocolor-"]'),
  classes, colorString;
Array.prototype.forEach.call(elements, function(elem) {
  classes = Array.prototype.slice.call(elem.classList, 0);
  colorString = classes.map(function(c) {
    if (c.indexOf('tocolor-') === 0) {
      return c.replace('tocolor-', '');
    }
  });
  elem.style.color = colorString;
});
&#13;
<div class="tocolor-red">tocolor</div>
<div class="tocolor-blue">tocolor</div>
<div class="tocolor-green">tocolor</div>
<div class="tocolor-yellow">tocolor</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这是你的通配符:

div[class^='.tocolor-'] {
    background: red;
}

但是如果你想使用变量,你应该看看SASS:

http://sass-lang.com/