Generate variables with loops (“Shorter/friendly-named alias for a complex statement” problem)

自闭症网瘾萝莉.ら 提交于 2019-11-27 19:31:57

问题


I know that in LESS is possible to generate many CSS classes using loops. I personally used this technique to answer another user's question.

Now I'm facing the following code:

@transparent-black-10: fade(@nero, 0.1);
@transparent-black-20: fade(@nero, 0.2);
@transparent-black-30: fade(@nero, 0.3);
@transparent-black-40: fade(@nero, 0.4);
@transparent-black-50: fade(@nero, 0.5);
@transparent-black-60: fade(@nero, 0.6);
@transparent-black-70: fade(@nero, 0.7);
@transparent-black-80: fade(@nero, 0.8);
@transparent-black-90: fade(@nero, 0.9);

@transparent-white-10: fade(@bianco, 0.1);
@transparent-white-20: fade(@bianco, 0.2);
@transparent-white-30: fade(@bianco, 0.3);
@transparent-white-40: fade(@bianco, 0.4);
@transparent-white-50: fade(@bianco, 0.5);
@transparent-white-60: fade(@bianco, 0.6);
@transparent-white-70: fade(@bianco, 0.7);
@transparent-white-80: fade(@bianco, 0.8);
@transparent-white-90: fade(@bianco, 0.9);

I'm wondering if is possible to generate also LESS variables like above, using Loops, or this is denied by language. If possible, do you have some suggestion to generate above code more efficiently?


回答1:


(Now when Less v3.x and higher provides native support for custom functions).

Just as in most of other programming language, instead of a list of auto-generated/predefined variables, this programming problem is solved via function functionality. I.e. you define a function like:

.transparent-black(@value) {
    return: fade(@nero, @value ./ 10);
}

And then instead of @transparent-black-* variable you simply use .transparent-black(*)[] function call, e.g.:

div {
    color: .transparent-black(50)[];
}

This is obviously a simplified example (in a real project I certainly would make black/white/etc to be the function parameters too).



来源:https://stackoverflow.com/questions/29079094/generate-variables-with-loops-shorter-friendly-named-alias-for-a-complex-state

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!