是否可以在Less?
中增加变量@i: 0;
.one { border: @i++; }
.two { border: @i++; }
.tree { border: @i++; }
或者在某种程度上使用mixins,比如
.increase() {
@i: @i+1;
@increase: @i;
}
为了更好地解释问题:
@icon_width: 32px;
.social{
background: url('snippet_with_n_images');
.facebook: background-position-x: -@icon_width*0;
.twitter: background-position-x: -@icon_width*1;
.googlep: background-position-x: -@icon_width*2;
...
.pinterest: background-position-x: -@icon_width*(n-1);
.linkedin: background-position-x: -@icon_width*n;
/*be replaced by */
.next(): {
background-position-x: -@icon_width*@i++;
}
.facebook: .next();
.twitter: .next();
.googlep: .next();
...
.pinterest: .next();
.linkedin: .next();
}
答案 0 :(得分:3)
简单地说,如果不在Less中使用循环(mixin),则无法增加相同的变量。这是因为Less延迟加载变量,因此多个增量会导致递归定义错误。以下代码段:
@i: 0;
.one { @i: @i + 1; border: @i; }
.two { @i: @i + 1; border: @i; }
.three { @i: @i + 1; border: @i; }
编译时会给出:
NameError:第4行第7行的@i的递归变量定义:
使用类似的mixin(.increase()
)仍会导致与上面提供的相同的错误。
增量的最佳方法是使用mixin循环。对于问题中提供的修改样本,循环应如下所示:
@icon_width: 32px;
@social-networks: facebook, twitter, googlep, pinterest, linkedin; /* an array with list of networks */
.social{
background: url('snippet_with_n_images');
.loop-social(1); /* call loop with initial value as 1 */
}
.loop-social(@index) when (@index < length(@social-networks)){ /* iterate till index is less than array length */
@social-network: extract(@social-networks, @index); /* extract value corresponding to index from array */
.@{social-network}{ /* use extracted social network value as selector */
background-position-x: -@icon_width*@index; /* assign calculated value, the index would incremented for each iteration */
}
.loop-social(@index + 1); /* call next iteration with incremented value */
}
编译时的上述Less代码将生成以下CSS:
.social {
background: url('snippet_with_n_images');
}
.social .facebook {
background-position-x: -32px;
}
.social .twitter {
background-position-x: -64px;
}
.social .googlep {
background-position-x: -96px;
}
.social .pinterest {
background-position-x: -128px;
}