问题
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;
}
results in:
#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.
Thank you!
回答1:
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
.buildSelectorConnection(@selectorName, @pre: ~'') {
@{pre}@{selectorName} {
background-image: url('images/@{selectorName}.png');
}
}
.buildSelectorConnection(header, ~'#');
.buildSelectorConnection(do-a-class, ~'.');
CSS Output
#header {
background-image: url('images/header.png');
}
.do-a-class {
background-image: url('images/do-a-class.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
.
Nevertheless...
Something like this could be done:
LESS
.buildSelectorConnection(@selectorName, @pre: ~'', @post: ~'') {
@{pre}@{selectorName}@{post} {
background-image: url('images/@{selectorName}.png');
}
}
.buildSelectorConnection(menu, ~'div#', ~' ul li');
CSS Output
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.
回答2:
Yes, LESS just introduced an extend feature in 1.4.0.
Check out the answer to this question here: Does LESS have an "extend" feature?
来源:https://stackoverflow.com/questions/17235676/use-selector-name-as-variable-in-less-mixin