【问题标题】:calc() with variables not possible - SyntaxError: Operation on an invalid type无法使用变量的 calc() - SyntaxError: 对无效类型的操作
【发布时间】:2017-03-08 03:36:52
【问题描述】:

我有以下 LESS 变量:

@dashboard-height: 90.5%;
@dashlet-header-height: 35px;
@dashboard-margin: 0px;
@dashlet-border: 1px;

我想计算以下类:

.generate-dashlet-classes(6);
.generate-dashlet-classes(@n, @i: 1) when (@i =< @n) {
  &.dashlet-@{i} .dashlet-content {
    height: round((calc(@dashboard-height - (@i * (@dashlet-header-height + @dashboard-margin + @dashlet-border)))) / @i, 6);
  }
  .generate-dashlet-classes-times(@i);
  .generate-dashlet-classes(@n, (@i + 1));
}

.generate-dashlet-classes-times(@i, @times:1) when (@times < @i) {
  &.dashlet-@{times}-x-@{i} .dashlet-content {
    @dashletContainerHeight: (@dashlet-header-height + @dashboard-margin + @dashlet-border);
    height: round(((calc(@dashboard-height - (@i * @dashletContainerHeight))) / @i * @times) + (@dashletContainerHeight * (@times - 1)), 6);
  }
  .generate-dashlet-classes-times(@i, (@times + 1));
}

现在编译器抛出以下错误:

>> SyntaxError: Operation on an invalid type in app/styles/less/main.less on line 338, column 5:
>> 337 
>> 338     .generate-dashlet-classes(6);
>> 339     .generate-dashlet-classes(@n, @i: 1) when (@i =< @n) {

如果@dashboard-height 有一个 px 值并且不使用 calc() 就不会出错。但是当混合百分比和 px 值时,我们必须使用 calc(),不是吗?

【问题讨论】:

    标签: css less


    【解决方案1】:

    LESS 将尝试计算所有未转义的内容,直到您使用strict math 进行编译。换句话说:(90.5% - (3 * (35px + 0px + 1px))) / 3 的结果是什么? Less 无法知道,我猜这就是 对无效类型的操作 试图告诉我们的。

    开启严格数学模式 (lessc -sm=on myfile.less myfile.css) 将立即解决您的问题。但它有一个不想要的副作用,即您的其他 less 文件中的所有其他计算也不会得到处理(只有在不必要的括号内的数学才会被处理)。所以这可能不是一个选择,因为您可能必须重构现有的代码库。

    转义一般看起来像这样width: ~"calc(100% - 20px)";。这有点棘手,因为我们不想同时转义 calc 函数中的变量。一种插入变量的方法:
    height: ~"calc(@{dashboard-height} - (@{i} * (@{dashlet-header-height} + @{dashboard-margin} + @{dashlet-border})))" / @i;
    这将导致例如 height: calc(90.5% - (2 * (35px + 0px + 1px))) / 2。乍一看这比编译错误要好,但它是无效的 CSS。

    幸运的是,我们只能转义一些运算符(本例中的减号)
    height: calc(@dashboard-height ~"-" (@i * (@dashlet-header-height + @dashboard-margin + @dashlet-border))); 这将导致例如height: calc(90.5% - 36px);


    当您完成转义后,您将收到下一个错误,告诉您使用 LESS round function 不起作用。该函数需要一个浮点数作为参数,因此您不能将它与 CSS calc() 函数混淆。只有在编译时知道该值时,舍入才有意义。出于同样的原因,我在上述计算中删除了/ @i,因为您不能将 calc() 除以数字。

    【讨论】:

    • 简而言之,重新运行您的 less 编译:less -sm=on input.less output.css
    • 在新版本中参数被重命名为less --math=strict input.less output.css
    猜你喜欢
    • 1970-01-01
    • 2012-12-27
    • 2018-12-14
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多