简体   繁体   English

在LESS mixin中使用选择器名称作为变量

[英]Use selector name as variable in LESS mixin

I'm trying to create a mixin within LESS that will use it's selector name as a variable inside of the mixing. 我正在尝试在LESS中创建一个mixin,它将使用它的选择器名称作为混合内部的变量。 The mixin should look something like this, but I cannot find the exact syntax for it or if it's even possible: mixin应该看起来像这样,但我找不到它的确切语法,或者它是否可能:

.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! 谢谢!

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: 但是,您可以构建选择器以与mixin中的文件名链接,如下所示:

LESS

.buildSelectorConnection(@selectorName, @pre: ~'') {
  @{pre}@{selectorName} {
     background-image: url('images/@{selectorName}.png');
  }
}

.buildSelectorConnection(header, ~'#');
.buildSelectorConnection(do-a-class, ~'.');

CSS Output CSS输出

#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 . 然而,如果你想让这样的东西能够处理像div#menu ul li这样的实际文件名生成的东西,那么你需要更多的逻辑,你自己的决策和一些javascript编码。 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 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. 这基本上允许你构建任何选择器字符串,但文件名本身只是传入的初始选择器,它必须是对文件名有效的东西。

Yes, LESS just introduced an extend feature in 1.4.0. 是的,LESS刚刚在1.4.0中引入了一个扩展功能。

Check out the answer to this question here: Does LESS have an "extend" feature? 在这里查看这个问题的答案: LESS是否具有“扩展”功能?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM