2014-01-30 91 views
3

鉴于这种LESS混入:LESS - 分配混入变量和重用

#gradient { 
    .vertical (@startColor: #555, @endColor: #333) { 
     background-color: @endColor; 
     background-repeat: repeat-x; 
     background-image: -khtml-gradient(linear, left top, left bottom, from(@startColor), to(@endColor)); /* Konqueror */ 
     background-image: -moz-linear-gradient(@startColor, @endColor); /* FF 3.6+ */ 
     background-image: -ms-linear-gradient(@startColor, @endColor); /* IE10 */ 
     background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, @startColor), color-stop(100%, @endColor)); /* Safari 4+, Chrome 2+ */ 
     background-image: -webkit-linear-gradient(@startColor, @endColor); /* Safari 5.1+, Chrome 10+ */ 
     background-image: -o-linear-gradient(@startColor, @endColor); /* Opera 11.10 */ 
     filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",@startColor,@endColor)); /* IE6 & IE7 */ 
     -ms-filter: %("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",@startColor,@endColor); /* IE8+ */ 
     background-image: linear-gradient(@startColor, @endColor); /* the standard */ 
    } 
} 

它通常会被称为如下样式的页眉/页脚:

header { 
    #gradient > .vertical(@black, @white); 
    width: 100%; 
} 

footer { 
    #gradient > .vertical(@black, @white); 
    padding: 20px; 
} 

这工作没有任何问题。但是,我试图将#gradient > .vertical(@black, @white);分配给变量gradient1并重新使用它。所以像这样理想:

@gradient1:  #gradient > .vertical(@black, @white); 
@headerBackground: @gradient1; 
@footerBackground: @gradient1;  
header { @headerBackground; width: 100%; } 
footer { @footerBackground; padding: 20px; } 

这不起作用 - 但如何解决这个问题?

+0

欢迎使用Stack Overflow,并感谢您发布第一篇文章的格式良好的问题。 – ScottS

+0

这两个答案都很棒!谢谢你们俩。 –

回答

1

你不能在不到一个mixin结果赋值给一个变量。您可以使用模式匹配来获得基本相同的结果几乎相同数量的代码:

.myGradient(gradient1) { 
    #gradient > .vertical(@black, @white); 
} 
@headerBackground: gradient1; 
@footerBackground: gradient1;  
header { .myGradient(@headerBackground); width: 100%; } 
footer { .myGradient(@footerBackground); padding: 20px; } 

从本质上讲,.myGradient(gradient1)成为您的“变量”的名字产生相同的代码,无论你把它。然后你就可以通过您设置将匹配模式中的变量控制你的渐变,所以你可以设置其他渐变就像这样:

.myGradient(gradient2) { 
    #gradient > .vertical(@red, @blue); 
} 
.myGradient(gradient3) { 
    #gradient > .vertical(@yellow, @orange); 
} 

然后设置各种背景变量的gradient1gradient2gradient3值,全部使用与该模式匹配的.myGradient mixin。

3

您不能混入分配给一个变量,但您可以创建一个新的mixin作为别名:

.gradient1() { 
    #gradient > .vertical(@black, @white); 
} 
.headerBackground() { 
    .gradient1(); 
} 
.footerBackground() { 
    .gradient1(); 
}  
header { 
    .headerBackground(); 
} 
footer { 
    .footerBackground(); 
}