0

我正在开发一个包含多个部分的项目。根据部分的不同,该部分中的元素具有不同的颜色。通过我的 LESS 文件,我定义了所有这些可能性,如下所示:

a{
    .section_what &{
        color: darken(@what,10%);
    }
    .section_where &{
        color: darken(@where,10%);          
    }
    .section_who &{
        color: darken(@who,10%);
    }
    .section_post &{
        color: darken(@post,10%);           
    }
    .section_events &{
        color: darken(@events,10%);         
    }
    .section_deals &{
        color: darken(@deals,10%);          
    }
}   

看起来这不是最精简的做事方式。使用这种方法,我必须多次重复这个部分列表。因此,每个被其部分更改的元素都需要定义这个部分列表。有时它的颜色,背景颜色,边框颜色等......

有没有更好的办法?

4

1 回答 1

1

In LESS you can get it with more generic code like this:

@what:   #111;
@where:  #222;
@who:    #333;
@post:   #444;
@events: #555;
@deals:  #666;

@items: what,
        where,
        who,
        post,
        events,
        deals;

@items-count: 6;

.sections() {
    .-(@items-count);
    .-(@i) when (@i > 0) {
        .-((@i - 1));

        @name: extract(@items, @i);
        .section_@{name} & {
            color: darken(@@name, 10%);
        }
    }
}

a {
    .sections();
}

b {
    .sections();
}

Or, if you don't need those variables for anything else, even better:

@items: what   #111,
        where  #222,
        who    #333,
        post   #444,
        events #555,
        deals  #666;

.sections() {
    .-(length(@items));
    .-(@i) when (@i > 0) {
        .-((@i - 1));

        @item: extract(@items, @i);
        @name: extract(@item, 1);
        .section_@{name} & {
            color: darken(extract(@item, 2), 10%);
        }
    }
}

a {
    .sections();
}

b {
    .sections();
}

It looks quite verbose but I suppose a level of customization worths this. Note that length function is available only in LESS 1.5.x, for earlier versions you can use a predefined count variable as in the first example.


And yet another approach (if you prefer "copy-paste" style):

@what:   #111;
@where:  #222;
@who:    #333;
@post:   #444;
@events: #555;
@deals:  #666;

.item(@name) {
    .section_@{name} & {
        color: darken(@@name, 10%);
    }
}

a {
    .item(what);
    .item(where);
    .item(who);
    .item(post);
    .item(events);
    .item(deals);
}

P.S.

So every element that is altered by its section requires this list of sections defined. Sometimes its color, background-color, border-color etc...

It is also possible to add more "customization points" for properties as well - but it depends on how exactly those sections and CSS properties tie to each other... (So I did not put that into examples above to not make things even more complicated to understand). Basically the key is "list/loops", "mixins/abstraction" etc.

于 2013-11-02T20:03:43.997 回答