作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在 LESS mixin 中,我有一个 alpha 值,我想将其转换为纯数字 (0.xx),即使它是以百分比 (xx%) 形式给出的。我找到了将数字转换为百分比的 percentage() 函数,但是 percentage(xx%) 返回“xx00%”并且除以 100 使 0.xx 变成 0.00xx,这也不好。我可以在 LESS invlove 中找到的所有“if-then”语句都创建了一个新范围,因此虽然我可以检测到“%”,但我无法将该信息传回变量以使用它。
当且仅当它是百分比时,我如何将百分比转换为数字?
最佳答案
虽然您可以在 Less 中使用 JS 来达到预期的效果,但更好的方法是使用内置的 ispercentage()
和 isnumber()
类型函数检查变量值是数字还是百分比,或者两者都不是,然后相应地输出值。
.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;
}
关于css - 如何将包含百分比的变量转换为 LESS 中的数字,但保留纯数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28685467/
我是一名优秀的程序员,十分优秀!