0

我们在 styles.less 中有以下声明:

.table tbody > tr > td {
    &.colnum, &.colnumdec {
            > input[type=text], > input[type=number] {
                text-align: center;
            }
        }
    }

.inputquantity {
    .colnumdec;
    width: 50px;
}

.inputprize {
    .colnumdec;
    width: 70px;
}

问题是 LESS 抱怨 inputprize { .colnumdec; 使用未声明的 mixin。

我们试图通过添加这些类的显式声明来解决它:

.colnum, .colnumdec {
}

但是没有属性会使 LESS 编译器忽略它们,如果我们改为放置一个不相关的属性,它就可以正常工作:

.colnum, .colnumdec {
    border:inherit;
}

解决这个问题的正确方法是什么?

4

1 回答 1

5

问题是 LESS 抱怨.inputprize { .colnumdec;未声明的 mixin。

这是预期的,因为.colnumdec它不在全局范围内(并且.inputprize无法访问定义的.table tbody > tr > td范围.colnumdec)。

在其中“调用”的正确语法.colnumdec类似于.inputprize但是.table tbody > tr > td.colnumdec;LESS 不允许使用非类或非 id 选择器(即非.和非#类似body)作为混合或命名空间。

解决方案#1:

处理这类事情的常用方法是将共享代码移动到专用的 mixin 中,例如:

.colnum() {
    > input[type=text], > input[type=number] {
        text-align: center;
    }
}

.table tbody > tr > td {
    &.colnum, &.colnumdec {
        .colnum();
    }
}

.inputquantity {
    .colnum(); // parens are optional here
    width: 50px;
}

.inputprize {
    .colnum();
    width: 70px;
}

解决方案#2:

#1 产生相当臃肿的 CSS 输出,因此最近变得更流行的优化方法是使用“扩展”功能,例如:

.table tbody > tr > td {
    &.colnum, &.colnumdec {
        > input[type=text], > input[type=number] {
            text-align: center;
        }
    }
}

.colnum() {
    &:extend(.table tbody > tr > td.colnumdec all);
}

.inputquantity {
    .colnum(); // parens are optional here
    width: 50px;
}

.inputprize {
    .colnum();
    width: 70px;
}

这种extend基于解决方案的另一个重要好处是它不是侵入性的,即您不需要修改.table tbody > tr > td内容。

于 2013-12-10T13:08:46.630 回答