你可以这样做:
SASS
@mixin repeater($item, $count) {
$string: "";
@for $i from 1 through $count {
$string: $string + $item;
}
content: $string;
}
.longDots {
@include repeater('.', 25);
}
.shortDots {
@include repeater('.', 10);
}
.longDashes {
@include repeater('-', 25);
}
.shortDashes {
@include repeater('-', 10);
}
mixin 也可以这样写:
@mixin repeater($item, $count) {
$string: "";
@for $i from 1 through $count {
$string: str-insert($string, $item, $i - 1);
}
content: $string;
}
或:
@mixin repeater($item, $count) {
$string: "";
@while $count > 0 {
$string: $string + $item;
$count: $count - 1;
}
content: $string;
}
或:
@mixin repeater($item, $count) {
$string: "";
@while $count > 0 {
$string: str-insert($string, $item, $count);
$count: $count - 1;
}
content: $string;
}
任何更吸引你的东西。
您可以随时在线测试您的 SASS 小部分,例如: http://sass.js.org/ 或 http://www.sassmeister.com/,如果您没有相应的本地工具。
对于 LESS,您需要更复杂的 mixins:
.contentresult(@string, @count) when (@count = 1) {
content: @string
}
.repeater(@item, @count, @string: "") when (@count > 0) {
.repeater(@item, (@count - 1), "@{string}@{item}");
.contentresult("@{string}@{item}", @count);
}
.longDots {
.repeater('.', 25);
}
.shortDots {
.repeater('.', 10);
}
.longDashes {
.repeater('-', 25);
}
.shortDashes {
.repeater('-', 10);
}
第一个 mixin 是一个 if 语句,第二个是实际的循环。使用这两个单独的 mixin 很重要,因为只有 repeater mixin 会为每次迭代生成大量 content 属性,不幸的是,最短的在底部。
用http://less2css.org/ 测试。 (使用 LESS 1.3.3 及更高版本编译成功。)
自从 OP 更新了他的问题:
SASS
@function repeater($item, $count) {
$string: "";
@for $i from 1 through $count {
$string: $string + $item;
}
@return "#{$string}";
}
.longDots {
content: repeater('.', 25);
}
对于"#{$string}",我只是向您展示了另一种访问变量内容的方法。您也可以只使用$string。我之前向您展示的每个 mixin 在您按照我在这里所做的方式将其转换为函数后都可以正常工作。
少
.contentresult(@string, @count) when (@count = 1) {
@return: @string
}
.repeater(@item, @count, @string: "") when (@count > 0) {
.repeater(@item, (@count - 1), "@{string}@{item}");
.contentresult("@{string}@{item}", @count);
}
.longDots {
.repeater('.', 25);
content: @return;
}