使用数学函数获取整数值 [英] Using math functions to get integer values

查看:98
本文介绍了使用数学函数获取整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些LessCSS基本上是这样的:

I have some LessCSS that essentially looks like this:

.foo {
    @height: 20px;
    @iconHeight: 13px;

    background-position: 0 (@height - @iconHeight) / 2;
}

然而,这显然是背景位置:0 3.5px ,我更喜欢它是一个整数(值 Math.ceil ),但是这不是工作:

However, this obviously turns out as background-position: 0 3.5px, and I'd prefer for it to be an integer (the value of Math.ceil), however this doesn't work:

background-position: 0 Math.ceil((@height - @iconHeight) / 2)

也没有使用javascript评估运算符:

Nor does using the javascript evaluation operator:

background-position: 0 `Math.ceil((@height - @iconHeight) / 2)`

...因为它被解析为 Math.ceil(20px - 13px)而且px存在语法错误。

...since this is parsed as Math.ceil(20px - 13px) and the "px" there is a syntax error.

我甚至尝试过使用 parseInt

0 `Math.ceil((parseInt('@{height}', 10) - parseInt('@{iconHeight}', 10)) / 2)`px

但结果如下:

background-position: 0 4 px

...这是不对的。最后,即使在JS评估中添加px也不起作用

...which isn't right. And finally, even adding the "px" in the JS evaluation doesn't work

background-position: 0 `Math.ceil(....) + "px"`;
// becomes
background-position: 0 "4px";

肯定有更好的方法!

推荐答案

使用临时变量和 0px hack有一个简单的解决方法。

There is a simple workaround to the problem using temporary variable and 0px hack.

.foo {
    @height: 20px;
    @iconHeight: 13px;

    @result: `Math.ceil((parseInt('@{height}') - parseInt('@{iconHeight}')) / 2)`;
    background-position: 0 (0px + @result);
}

这篇关于使用数学函数获取整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆