gpt4 book ai didi

javascript - 类正则表达式的 CSS 属性选择器通配符捕获

转载 作者:行者123 更新时间:2023-11-29 21:39:57 25 4
gpt4 key购买 nike

假设我有以下 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 中使用通配符。但是,我还没有找到任何可以让我捕获通配 rune 本并将其作为规则一部分的东西。

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

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

最佳答案

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;
});

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;
});
<div class="tocolor-red">tocolor</div>
<div class="tocolor-blue">tocolor</div>
<div class="tocolor-green">tocolor</div>
<div class="tocolor-yellow">tocolor</div>

关于javascript - 类正则表达式的 CSS 属性选择器通配符捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33354315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com