如何使用函数中的 SCSS 变量进行计算 [英] How to calculate with SCSS variables from function

查看:83
本文介绍了如何使用函数中的 SCSS 变量进行计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将 px 转换为 rem 的函数.例如:

I have a function which converts px to rem. For example:

height: rem-calc(14px); // makes height: 1rem;

现在我想用它来计算变量.例如:

Now I would like to calculate with it from variables. For example:

$switch-track-width: rem-calc(50px);
$switch-thumb-size: $switch-track-width / 2; // making it 25px or 1.7857rem in this case

那不起作用,所以我尝试了其他方法:

That doesn't work so I tried something else:

$switch-thumb-size: ($switch-track-width / 2) + 0rem;
$switch-thumb-size: (#{$switch-track-width} / 2) + 0rem;

两个 $switch-thumb-size 示例也不起作用.现在这是分裂,但我也无法让 times (*)plus (+)minus (-) 工作.

Both $switch-thumb-size examples aren't working either. Now this is dividing but I'm also unable to get times (*), plus (+) and minus (-) working.

我在用 2 个变量进行计算时也遇到了问题.例如:

I'm also having a problem when calculating with 2 variables. For example:

$switch-track-height: rem-calc(14px);
$switch-track-width: rem-calc(50px);
$switch-thumb-right: $switch-track-height - $switch-track-width;

我更喜欢将函数保留在变量中而不是在属性中,例如:height: rem-calc($switch-track-height);.

I prever to keep the function inside the variable instead of in the property like: height: rem-calc($switch-track-height);.

如果有人能告诉我如何在两个示例中使用 SCSS 变量进行计算,那将非常有帮助.

If someone could tell me how to calculate with SCSS variables on both examples that would be very helpful.

提前致谢

推荐答案

我设法找到了一些有用的东西.例如:

I managed to find something that is some what working. For example:

$switch-thumb-size: rem-calc(10px);
$switch-track-height: rem-calc(20px);
$something: calc( ( #{$switch-thumb-size} - #{$switch-track-height} ) / 2 );

结果:

calc( ( 0.71428rem - 1.4285rem ) / 2 )

但是它有问题.首先,如果你知道你计算的应该总是负数,因此你在变量前添加一个 - 符号,它将不起作用.示例:

But there are problems with it. First if you know that what you calculated should always be minus and you therefor add a - sign infront of the variable it will not work. Example:

height: - $something; // Doesn't work

我对这种方法的第二个问题是它创建了很多冗余字符.

The second problem I have with this method is that it creates a lot of redundant characters.

因为它实际上将: height: calc( ( 0.71428rem - 1.4285rem )/2 ) 而不是: height: -0.35684rem

Because it actually puts: height: calc( ( 0.71428rem - 1.4285rem ) / 2 ) in your css instead of: height: -0.35684rem

这篇关于如何使用函数中的 SCSS 变量进行计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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