gpt4 book ai didi

css - 如何将包含百分比的变量转换为 LESS 中的数字,但保留纯数字?

转载 作者:行者123 更新时间:2023-11-28 11:08:18 27 4
gpt4 key购买 nike

在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com