Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

(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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...