在LESS mixin中使用选择器名称作为变量 [英] Use selector name as variable in LESS mixin
问题描述
我试图在LESS中创建一个mixin,它将使用它的选择器名称作为混合中的一个变量。 mixin应该看起来像这样,但我找不到确切的语法,或者如果它甚至可能:
I'm trying to create a mixin within LESS that will use it's selector name as a variable inside of the mixing. The mixin should look something like this, but I cannot find the exact syntax for it or if it's even possible:
.bg{
background-image: url('images/@{SELECTORNAME}.png');
}
#header{
.bg;
}
会导致:
#header{
background-image: url('images/header.png');
}
我认为这是不可能的,选择器是这样的:
I'm thinking this isn't possible, plus what would happen if the selecter was something like:
div#menu ul li
这不会真正工作,但也许任何人都知道一个替代,这是可能在任何其他预处理器。
That wouldn't really work but perhaps anyone knows of an alternative, wether this is possible in any other preprocessor.
谢谢!
推荐答案
您无法读取选择器名称。
但是,您可以结合使用mixin中的文件名来建立选择器,例如:
You cannot "read" the selector name.
However, you can build the selector in conjunction to linking with the file name in a mixin, something like so:
LESS
LESS
.buildSelectorConnection(@selectorName, @pre: ~'') {
@{pre}@{selectorName} {
background-image: url('images/@{selectorName}.png');
}
}
.buildSelectorConnection(header, ~'#');
.buildSelectorConnection(do-a-class, ~'.');
CSS输出
#header {
background-image: url('images/header.png');
}
.do-a-class {
background-image: url('images/do-a-class.png');
}
但是,这将需要更多的逻辑, ,和一些JavaScript编码在LESS如果你想让这样的事情能够处理像 div#menu ul li
其中实际的文件名生成的是像 div-menu-ul-li.png
。
However, it would take quite a bit more logic, decision making on your part, and some javascript coding in LESS if you wanted to make such a thing be able to handle something like div#menu ul li
where the actual filename generated was something like div-menu-ul-li.png
.
可以这样做:
LESS
.buildSelectorConnection(@selectorName, @pre: ~'', @post: ~'') {
@{pre}@{selectorName}@{post} {
background-image: url('images/@{selectorName}.png');
}
}
.buildSelectorConnection(menu, ~'div#', ~' ul li');
CSS输出
div#menu ul li {
background-image: url('images/menu.png');
}
这基本上允许你构建任何选择器字符串,但文件名本身只会是传入的初始选择器,它需要对文件名有效的。
This basically lets you build any selector string, but the file name itself will only be that initial selector passed in, which needs to be something valid for a file name.
这篇关于在LESS mixin中使用选择器名称作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!