2014-02-15 44 views
3

如何動態調用mixin?不需要動態調用mixin

用例可能會產生一個風格指南:

// The mixin which should be called 
.typography-xs(){ 
    font-family: Arial; 
    font-size: 16px; 
    line-height: 22px; 
} 

// The mixin which tries to call typography-xs 
.typography-demo(@typographyName, @mixinName) { 
    @{typographyName} { 
    &:before{content: '@{typographyName}';} 
    // Calling the mixin dynamically 
    @mixinName(); 
    } 
} 

// Example call of .typograhpy-demo 
.typography-demo(xs, typography-xs); 

就是這樣一個動態調用可能在所有用更少的CSS?

回答

7

你目前不能動態調用你想要的。你可以,但是,將其設置略有不同使用pattern matching,就像這樣:

// The mixin which should be called 
.typography(xs){ 
    font-family: Arial; 
    font-size: 16px; 
    line-height: 22px; 
} 

// The mixin which tries to call typography-xs 
.typography-demo(@typographyName) { 
    @{typographyName} { 
    &:before{content: '@{typographyName}';} 
    // Calling the mixin dynamically 
    .typography(@typographyName); 
    } 
} 

// Example call of .typograhpy-demo 
.typography-demo(xs); 

使用模式匹配,那麼你就可以創建其他模式,如:

.typography(xl){ 
    font-family: Arial; 
    font-size: 32px; 
    line-height: 44px; 
} 

.typography(times){ 
    font-family: 'Times New Roman'; 
    font-size: 16px; 
    line-height: 22px; 
} 

現在你可以調用模式xltimes並讓它生成代碼。基本上,把連字符後面的任何東西(比如-xs)用來區分各種排版組,然後刪除連字符並使用該名稱作爲模式來匹配mixin。

另外,我想補充的手段之前@{typographyName}像這樣把一個選擇的:

.typography-demo(@typographyName, @selector: ~".") { 
    @{selector}@{typographyName} { 
    &:before{content: '@{typographyName}';} 
    // Calling the mixin dynamically 
    .typography(@typographyName); 
    } 
} 

這樣,它默認生成的一類,但可以做成一個id或任何選擇字符串,最多@{typographyName}

+0

哦,酷,看起來夠好ty! :) – jantimon