如何在LESS中将包含百分比的变量转换为数字,但不考虑纯数字? [英] How do I convert a variable containing a percentage to a number in LESS, but leave plain numbers alone?
问题描述
在LESS mixin中,我有一个Alpha值,即使以百分比(xx%)给出,我也希望将其转换为纯数字(0.xx).我发现percent()函数可以将数字转换为百分比,但是percent(xx%)返回"xx00%"并除以100会使0.xx变成0.00xx,这也不是一件好事.我可以在LESS invlove中找到的所有"if-then"语句都创建了一个新的作用域,因此尽管我可以检测到%",但无法将该信息传递回变量以使用它.
In a LESS mixin, I have an alpha value that I'd like to convert to a plain number (0.xx) even if it is given as a percentage (xx%). I've found the percentage() function to convert a number to a percentage, but percentage(xx%) returns "xx00%" and dividing by 100 makes 0.xx into 0.00xx, which is no good either. All the "if-then" statements that I could find in LESS invlove making a new scope, so while I could detect the "%", I couldn't pass that information back into a variable to use it.
当且仅当是百分比时,如何将百分比转换为数字?
How do I go about converting a percentage to a number if and only if it is a percentage?
推荐答案
虽然您可以在Less内使用JS以获得所需的效果,但是更好的方法是使用内置的 isnumber()
类型函数检查变量值是数字还是百分比,或者都不是,然后输出相应的值./p>
While you can use JS within Less to achieve the desired effect, a better approach would be to use the built-in ispercentage()
and isnumber()
type functions to check whether a variable value is a number or a percentage or neither and then output the value accordingly.
.percentlike(@var) {
& when (ispercentage(@var)){ /* is input value a percentage */
alpha: unit(@var / 100); /* unit() strips the % symbol */
/* you could also use the replace function like below
@percentage: @var / 100;
alpha: replace(~"@{percentage}", "%", "");
*/
}
& when not (ispercentage(@var)) and (isnumber(@var)){ /* not percentage but is a number */
alpha: @var;
}
& when not (ispercentage(@var)) and not (isnumber(@var)){ /* neither */
alpha: ~"NaN";
}
}
div#div1 {
.percentlike(20%);
}
div#div2{
.percentlike(0.2);
}
div#div3{
.percentlike(a);
}
已编译的CSS:
div#div1 {
alpha: 0.2;
}
div#div2 {
alpha: 0.2;
}
div#div3 {
alpha: NaN;
}
这篇关于如何在LESS中将包含百分比的变量转换为数字,但不考虑纯数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!