0

我目前正在使用 LESS。由于我使用 CSS sprites,我想知道 LESS 是否支持这种语法:

icon{x}{
  background-position:-10px -10*{x}px;
}

因为我必须创建这种 CSS 样式:

icon1{
  background-position:-10px -10px;
}
icon2{
  background-position:-10px -20px;
}
icon3{
  background-position:-10px -30px;
}
.................
4

1 回答 1

1

Is it possible ?

Unfortunately, I think it's not. LESS is a compiled language and doesn't support (yet ?) iteration control structures like while() or for().
To begin an answer, I would write the following HTML code :

<div id="1" class="icon"></div>
<div id="2" class="icon"></div>
<div id="3" class="icon"></div>

With the following LESS code :

.dynamic-background(@i)
{
    background-position: -10px (-10px * @i);
}

@var: `document.getElementsByClassName('icon')[2].id`;

.icon
{
    .dynamic-background(@var);
}

Which would result as the following CSS code :

.icon
{
    background-position: -10px -30px;
}

But as you can see, this code is dynamic for only one element by page, due to the [x] on the result of getElementsByClassName. Maybe there is an additional trick that I'm missing there, though.

Alternative solution

Maybe could you just use Javascript :

<script type="text/javascript">
    var elems = document.getElementsByClassName('icon');
    for (var i=0; elems[i]; i++)
        elems[i].style.backgroundPosition = '-10px -'+elems[i].id*10+'px';
</script>

Which results in the following:

<div id="1" class="icon" style="background-position: -10px -10px;"></div>
<div id="2" class="icon" style="background-position: -10px -20px;"></div>
<div id="3" class="icon" style="background-position: -10px -30px;"></div>
于 2012-12-04T12:07:28.143 回答