你如何从SASS的任何号码剥离单位? [英] How do you strip the unit from any number in SASS?

查看:138
本文介绍了你如何从SASS的任何号码剥离单位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ number我知道你可以从SASS中的数字中删除单位:16px; 
$ without-unit:16px / 1px;
@warn $ without-unit; // 16

但是有可能在不知道单位是什么的情况下从单位中剥离单位?

pre $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b}

@warn strip-unit(16px); // 16


解决方案

-



更新:您绝不应该实际需要使用此功能。萨斯数学对于单位非常聪明,我从来没有见过一个用例,在这个用例中剥离单位比单纯使用正确的数学来得到你需要的更好。请参阅 Sass问题主题,详细讨论了这一点。



这是一个聪明的功能,但如果您曾经想过使用它,那么您的数学可能存在问题。不要回避这个功能。修正你的数学问题。



-



你需要除以1。如果你使用 unit(),你会得到一个字符串而不是一个数字,但是如果你乘以零并且加1,你就有你需要的东西:

  @function strip-units($ number){
@return $ number /($ number * 0 + 1);
}

有效。 strip-units(13.48cm)将返回 13.48


I know you can strip units from numbers in SASS when you know the unit before-hand like this:

$number: 16px;
$without-unit: 16px / 1px;
@warn $without-unit; // 16

But is it possible to strip the unit from a number without knowing what the unit is first?

@function strip-unit($number) {
  // magic code here...
}

@warn strip-unit(16px); // 16

解决方案

--

UPDATE: You should never actually need to use this function. Sass math is very smart about units, and I have never seen a use-case in which stripping units was a better option than simply using correct math to get what you need. See the Sass issue thread where this has been discussed at length.

It's a clever function, but if you ever feel like using it, there's probably a problem with your math. Don't fall back on this function. Fix your math instead.

--

You need to divide by 1 of the same unit. If you use unit(), you get a string instead of a number, but if you multiply by zero and add 1, you have what you need:

@function strip-units($number) {
  @return $number / ($number * 0 + 1);
}

That works. strip-units(13.48cm) will return 13.48.

这篇关于你如何从SASS的任何号码剥离单位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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